fix: stabilize backend prisma and lint

This commit is contained in:
2026-04-06 20:21:40 +09:00
parent 90ab555915
commit a8ff05c96a
35 changed files with 989 additions and 360 deletions

View File

@@ -6,6 +6,9 @@
"private": true,
"license": "UNLICENSED",
"scripts": {
"prisma:generate": "prisma generate",
"prebuild": "npm run prisma:generate",
"pretest": "npm run prisma:generate",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",

View File

@@ -6,10 +6,7 @@ export class ActivityController {
constructor(private readonly activityService: ActivityService) {}
@Get('activity')
getFeed(
@Query('limit') limit?: string,
@Query('offset') offset?: string,
) {
getFeed(@Query('limit') limit?: string, @Query('offset') offset?: string) {
return this.activityService.getFeed(
limit ? parseInt(limit, 10) : 50,
offset ? parseInt(offset, 10) : 0,

View File

@@ -7,7 +7,9 @@ describe('ActivityService', () => {
const mockPrisma = {
activityLog: {
create: jest.fn().mockResolvedValue({ id: 1, action: 'test', createdAt: new Date() }),
create: jest
.fn()
.mockResolvedValue({ id: 1, action: 'test', createdAt: new Date() }),
findMany: jest.fn().mockResolvedValue([]),
count: jest.fn().mockResolvedValue(0),
},

View File

@@ -15,7 +15,11 @@ function sanitizeActivityDetail(detail?: string | null): string | undefined {
const raw = detail.trim();
// 내부 stderr/명령문 직접 노출 금지
if (/stderr:/i.test(raw) || /command not found/i.test(raw) || /bash:\s*line/i.test(raw)) {
if (
/stderr:/i.test(raw) ||
/command not found/i.test(raw) ||
/bash:\s*line/i.test(raw)
) {
return '내부 작업 중 오류가 발생했어. 자세한 시스템 로그는 관리자 로그에서 확인할 수 있어.';
}
@@ -66,7 +70,10 @@ export class ActivityService {
this.prisma.activityLog.count(),
]);
return {
items: items.map((item) => ({ ...item, detail: sanitizeActivityDetail(item.detail) })),
items: items.map((item) => ({
...item,
detail: sanitizeActivityDetail(item.detail),
})),
total,
limit,
offset,
@@ -87,7 +94,10 @@ export class ActivityService {
this.prisma.activityLog.count({ where: { projectId } }),
]);
return {
items: items.map((item) => ({ ...item, detail: sanitizeActivityDetail(item.detail) })),
items: items.map((item) => ({
...item,
detail: sanitizeActivityDetail(item.detail),
})),
total,
limit,
offset,

View File

@@ -10,9 +10,16 @@ describe('AdminService', () => {
let service: AdminService;
const mockSister = {
id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang',
lxcId: 105, status: 'online', lastSeen: new Date(),
sshKeyPath: null, createdAt: new Date(), updatedAt: new Date(),
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
status: 'online',
lastSeen: new Date(),
sshKeyPath: null,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockPrisma = {
@@ -30,7 +37,9 @@ describe('AdminService', () => {
{ provide: ActivityService, useValue: mockActivity },
{
provide: ConfigService,
useValue: { get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa') },
useValue: {
get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa'),
},
},
],
}).compile();
@@ -41,7 +50,11 @@ describe('AdminService', () => {
});
it('restartSister: SSH 성공 시 success=true', async () => {
mockSsh.executeCommand.mockResolvedValue({ stdout: 'RESTART_OK', stderr: '', code: 0 });
mockSsh.executeCommand.mockResolvedValue({
stdout: 'RESTART_OK',
stderr: '',
code: 0,
});
const result = await service.restartSister('narang');

View File

@@ -5,7 +5,13 @@ import { SshService } from '../sisters/ssh.service';
import { ActivityService } from '../activity/activity.service';
import { SisterName } from '../common/sister-name.pipe';
const ALLOWED_HARNESS_FILES = ['AGENTS.md', 'SOUL.md', 'PROTOCOL.md', 'TOOLS.md', 'HEARTBEAT.md'] as const;
const ALLOWED_HARNESS_FILES = [
'AGENTS.md',
'SOUL.md',
'PROTOCOL.md',
'TOOLS.md',
'HEARTBEAT.md',
] as const;
type HarnessFile = (typeof ALLOWED_HARNESS_FILES)[number];
@Injectable()
@@ -36,7 +42,9 @@ export class AdminService {
await this.activity.log({
sisterId: sister.id,
action: 'gateway_restart',
detail: success ? 'Gateway restart successful' : `stderr: ${result.stderr}`,
detail: success
? 'Gateway restart successful'
: `stderr: ${result.stderr}`,
});
return { success, output: result.stdout, error: result.stderr || null };
@@ -68,7 +76,9 @@ export class AdminService {
await this.activity.log({
sisterId: sister.id,
action: 'session_reset',
detail: success ? 'Session reset successful' : `stderr: ${result.stderr}`,
detail: success
? 'Session reset successful'
: `stderr: ${result.stderr}`,
});
return { success, output: result.stdout, error: result.stderr || null };
@@ -102,7 +112,7 @@ export class AdminService {
const keyPath = this.getKeyPath();
// 내용에서 위험한 셸 escape + null byte 방지
const escaped = content.replace(/\x00/g, '').replace(/'/g, "'\\''");
const escaped = content.split('\0').join('').replace(/'/g, "'\\''");
try {
const result = await this.ssh.executeCommand(
@@ -162,7 +172,9 @@ export class AdminService {
}
private async getSister(name: SisterName) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) throw new Error(`Sister ${name} not found`);
return sister;
}

View File

@@ -8,10 +8,15 @@ import {
Request,
BadRequestException,
} from '@nestjs/common';
import type { Request as ExpressRequest } from 'express';
import { AuthService, LoginDto } from './auth.service';
import { JwtGuard } from './jwt.guard';
import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
interface AuthenticatedRequest extends ExpressRequest {
user: { userId: number };
}
@Controller('api/auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@@ -31,7 +36,7 @@ export class AuthController {
@UseGuards(JwtGuard)
@Get('me')
getMe(@Request() req: any) {
getMe(@Request() req: AuthenticatedRequest) {
return this.authService.getMe(req.user.userId);
}
}

View File

@@ -6,10 +6,12 @@ import * as bcrypt from 'bcrypt';
import { IsString, IsNotEmpty } from 'class-validator';
export class LoginDto {
@IsString() @IsNotEmpty()
@IsString()
@IsNotEmpty()
username!: string;
@IsString() @IsNotEmpty()
@IsString()
@IsNotEmpty()
password!: string;
}
@@ -22,7 +24,9 @@ export class AuthService {
) {}
async login(dto: LoginDto) {
const user = await this.prisma.user.findUnique({ where: { username: dto.username } });
const user = await this.prisma.user.findUnique({
where: { username: dto.username },
});
if (!user) throw new UnauthorizedException('Invalid credentials');
const ok = await bcrypt.compare(dto.password, user.password);
@@ -33,11 +37,16 @@ export class AuthService {
async refresh(refreshToken: string) {
try {
const payload = this.jwt.verify<{ sub: number; username: string; role: string }>(
refreshToken,
{ secret: this.config.get<string>('JWT_SECRET') + '_refresh' },
);
const user = await this.prisma.user.findUnique({ where: { id: payload.sub } });
const payload = this.jwt.verify<{
sub: number;
username: string;
role: string;
}>(refreshToken, {
secret: this.config.get<string>('JWT_SECRET') + '_refresh',
});
const user = await this.prisma.user.findUnique({
where: { id: payload.sub },
});
if (!user) throw new UnauthorizedException();
return this.signTokens(user.id, user.username, user.role);
} catch {
@@ -60,7 +69,10 @@ export class AuthService {
const payload = { sub: userId, username, role };
const accessToken = this.jwt.sign(payload, { secret, expiresIn: '15m' });
const refreshToken = this.jwt.sign(payload, { secret: secret + '_refresh', expiresIn: '7d' });
const refreshToken = this.jwt.sign(payload, {
secret: secret + '_refresh',
expiresIn: '7d',
});
return { accessToken, refreshToken, username, role };
}

View File

@@ -23,6 +23,10 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
validate(payload: JwtPayload) {
if (!payload?.sub) throw new UnauthorizedException();
return { userId: payload.sub, username: payload.username, role: payload.role };
return {
userId: payload.sub,
username: payload.username,
role: payload.role,
};
}
}

View File

@@ -1,28 +1,46 @@
import { Injectable, CanActivate, ExecutionContext, ForbiddenException, SetMetadata } from '@nestjs/common';
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
SetMetadata,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request as ExpressRequest } from 'express';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
interface RoleUser {
role: string;
}
interface RequestWithUser extends ExpressRequest {
user?: RoleUser;
}
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) return true;
const request = context.switchToHttp().getRequest();
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (!user) throw new ForbiddenException('Authentication required');
const hasRole = requiredRoles.includes(user.role);
if (!hasRole) throw new ForbiddenException(`Role '${user.role}' not authorized. Required: ${requiredRoles.join(', ')}`);
if (!hasRole)
throw new ForbiddenException(
`Role '${user.role}' not authorized. Required: ${requiredRoles.join(', ')}`,
);
return true;
}

View File

@@ -14,7 +14,9 @@ export class CostsController {
@Get()
getCosts(@Query('period') period?: string) {
const validPeriods: CostPeriod[] = ['day', 'week', 'month'];
const p = validPeriods.includes(period as CostPeriod) ? (period as CostPeriod) : 'week';
const p = validPeriods.includes(period as CostPeriod)
? (period as CostPeriod)
: 'week';
return this.costsService.getCosts(p);
}

View File

@@ -14,8 +14,6 @@ const MODEL_PRICING: Record<string, { input: number; output: number }> = {
default: { input: 3.0, output: 15.0 },
};
const SISTER_NAMES: SisterName[] = ['harang', 'narang', 'darang', 'erang'];
export type CostPeriod = 'day' | 'week' | 'month';
@Injectable()
@@ -38,14 +36,23 @@ export class CostsService {
this.getTimeline(since, period),
]);
return { period, since: since.toISOString(), summary, bySister, byModel, timeline };
return {
period,
since: since.toISOString(),
summary,
bySister,
byModel,
timeline,
};
}
async recordCosts(sisterName: SisterName) {
const keyPath = this.config.get<string>('SSH_KEY_PATH');
if (!keyPath) return;
const sister = await this.prisma.sisterConfig.findUnique({ where: { name: sisterName } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name: sisterName },
});
if (!sister) return;
try {
@@ -99,7 +106,12 @@ export class CostsService {
private async getSummary(since: Date) {
const result = await this.prisma.costLog.aggregate({
where: { recordedAt: { gte: since } },
_sum: { inputTokens: true, outputTokens: true, totalTokens: true, estimatedUsd: true },
_sum: {
inputTokens: true,
outputTokens: true,
totalTokens: true,
estimatedUsd: true,
},
_count: true,
});
@@ -145,14 +157,23 @@ export class CostsService {
}
private async getTimeline(since: Date, period: CostPeriod) {
void period;
const logs = await this.prisma.costLog.findMany({
where: { recordedAt: { gte: since } },
orderBy: { recordedAt: 'asc' },
select: { sisterName: true, totalTokens: true, estimatedUsd: true, recordedAt: true },
select: {
sisterName: true,
totalTokens: true,
estimatedUsd: true,
recordedAt: true,
},
});
// 날짜별 집계
const grouped: Record<string, { date: string; totalTokens: number; estimatedUsd: number }> = {};
const grouped: Record<
string,
{ date: string; totalTokens: number; estimatedUsd: number }
> = {};
for (const log of logs) {
const dateKey = log.recordedAt.toISOString().slice(0, 10);
@@ -172,9 +193,12 @@ export class CostsService {
private getSince(period: CostPeriod): Date {
const now = new Date();
switch (period) {
case 'day': return new Date(now.getTime() - 24 * 60 * 60 * 1000);
case 'week': return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
case 'month': return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
case 'day':
return new Date(now.getTime() - 24 * 60 * 60 * 1000);
case 'week':
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
case 'month':
return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
}
}
}

View File

@@ -33,8 +33,10 @@ const SISTER_ROLES: Record<string, string> = {
function toneFromText(text: string): 'default' | 'warn' | 'ok' | 'active' {
const normalized = text.toLowerCase();
if (/(fail|error|blocker|offline|invalid|drift)/.test(normalized)) return 'warn';
if (/(passed|deploy|merged|restart_ok|write_ok|successful)/.test(normalized)) return 'ok';
if (/(fail|error|blocker|offline|invalid|drift)/.test(normalized))
return 'warn';
if (/(passed|deploy|merged|restart_ok|write_ok|successful)/.test(normalized))
return 'ok';
if (/(review|qa|handoff|sync|update)/.test(normalized)) return 'active';
return 'default';
}
@@ -45,18 +47,28 @@ function nodeStateFromEvidence(params: {
name: string;
}): 'idle' | 'active' | 'review' | 'blocked' | 'ready' {
const { sisterStatus, activity, name } = params;
const text = `${activity?.action ?? ''} ${activity?.detail ?? ''}`.toLowerCase();
const text =
`${activity?.action ?? ''} ${activity?.detail ?? ''}`.toLowerCase();
if (name !== 'user' && sisterStatus === 'offline') return 'blocked';
if (/(review|qa)/.test(text)) return 'review';
if (name === 'erang' && /(deploy|merged|ready for deploy|deployed)/.test(text)) return 'ready';
if (
name === 'erang' &&
/(deploy|merged|ready for deploy|deployed)/.test(text)
)
return 'ready';
if (sisterStatus === 'working') return 'active';
if (activity) return 'ready';
return 'idle';
}
function summarizeActivity(activity?: ActivityRecord | null, fallback = '최근 이벤트 없음') {
return activity?.detail?.trim() || activity?.action?.replace(/_/g, ' ') || fallback;
function summarizeActivity(
activity?: ActivityRecord | null,
fallback = '최근 이벤트 없음',
) {
return (
activity?.detail?.trim() || activity?.action?.replace(/_/g, ' ') || fallback
);
}
function parseQaSummary(content: string): string {
@@ -65,7 +77,9 @@ function parseQaSummary(content: string): string {
if (taskLine) return taskLine.replace(/^###\s+/, '').trim();
const bullet = lines.find((line) => /^-\s+/.test(line));
if (bullet) return bullet.replace(/^-\s+/, '').trim();
return lines.find((line) => line.length > 0 && !line.startsWith('#')) ?? 'QA note';
return (
lines.find((line) => line.length > 0 && !line.startsWith('#')) ?? 'QA note'
);
}
function inferQaAuthor(path: string, content: string): string {
@@ -101,7 +115,8 @@ export class DashboardService {
]);
const activities = rawActivities as ActivityRecord[];
const latestProjectActivity = activities.find((item) => item.project?.name) ?? null;
const latestProjectActivity =
activities.find((item) => item.project?.name) ?? null;
const latestBySister = new Map<string, ActivityRecord>();
for (const item of activities) {
if (item.sister?.name && !latestBySister.has(item.sister.name)) {
@@ -110,18 +125,29 @@ export class DashboardService {
}
const focusProject = latestProjectActivity?.project?.name
? projects.find((project) => project.name === latestProjectActivity.project?.name) ?? null
: projects.find((project) => ['IMPLEMENT', 'QA', 'READY FOR DEPLOY'].includes(project.phase)) ?? null;
? (projects.find(
(project) => project.name === latestProjectActivity.project?.name,
) ?? null)
: (projects.find((project) =>
['IMPLEMENT', 'QA', 'READY FOR DEPLOY'].includes(project.phase),
) ?? null);
const reviewLoopCount = activities.filter((item) => /(review|qa)/i.test(`${item.action} ${item.detail ?? ''}`)).length;
const escalationCount = projects.filter((project) => (project.blockerCount ?? 0) > 0).length;
const reviewLoopCount = activities.filter((item) =>
/(review|qa)/i.test(`${item.action} ${item.detail ?? ''}`),
).length;
const escalationCount = projects.filter(
(project) => (project.blockerCount ?? 0) > 0,
).length;
const nodes = [
{
id: 'user',
label: 'User',
role: 'Request / Approval',
state: nodeStateFromEvidence({ name: 'user', activity: latestProjectActivity }),
state: nodeStateFromEvidence({
name: 'user',
activity: latestProjectActivity,
}),
detail: latestProjectActivity
? `${latestProjectActivity.project?.name ?? 'project'} · ${summarizeActivity(latestProjectActivity, '최근 프로젝트 이벤트 없음')}`
: '명시적으로 기록된 handoff / request 로그가 아직 없어.',
@@ -130,9 +156,16 @@ export class DashboardService {
const activity = latestBySister.get(sister.name) ?? null;
return {
id: sister.name,
label: sister.name === 'erang' ? 'Irang' : `${sister.name.slice(0, 1).toUpperCase()}${sister.name.slice(1)}`,
label:
sister.name === 'erang'
? 'Irang'
: `${sister.name.slice(0, 1).toUpperCase()}${sister.name.slice(1)}`,
role: SISTER_ROLES[sister.name] ?? 'Unknown',
state: nodeStateFromEvidence({ name: sister.name, sisterStatus: sister.status, activity }),
state: nodeStateFromEvidence({
name: sister.name,
sisterStatus: sister.status,
activity,
}),
detail: activity
? summarizeActivity(activity)
: sister.status === 'offline'
@@ -147,22 +180,29 @@ export class DashboardService {
const harnessItems = activities
.filter((item) => item.action === 'harness_updated')
.slice(0, 4)
.map((item) => ({
id: `harness-${item.id}`,
title: item.detail ?? 'Harness updated',
body: '관리자 harness 편집 로그에서 직접 가져온 기록이야.',
tone: toneFromText(`${item.action} ${item.detail ?? ''}`),
author: item.sister?.name ? this.toDisplayName(item.sister.name) : 'System',
time: item.createdAt.toISOString(),
category: 'harness',
source: `activity:${item.action}`,
} satisfies OpsBoardItem));
.map(
(item) =>
({
id: `harness-${item.id}`,
title: item.detail ?? 'Harness updated',
body: '관리자 harness 편집 로그에서 직접 가져온 기록이야.',
tone: toneFromText(`${item.action} ${item.detail ?? ''}`),
author: item.sister?.name
? this.toDisplayName(item.sister.name)
: 'System',
time: item.createdAt.toISOString(),
category: 'harness',
source: `activity:${item.action}`,
}) satisfies OpsBoardItem,
);
const qaItems = await this.getLatestQaBoardItems(projects.map((project) => ({
name: project.name,
repoName: extractRepoName(project.repoUrl),
updatedAt: project.updatedAt,
})));
const qaItems = await this.getLatestQaBoardItems(
projects.map((project) => ({
name: project.name,
repoName: extractRepoName(project.repoUrl),
updatedAt: project.updatedAt,
})),
);
const board = [...harnessItems, ...qaItems]
.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
@@ -184,7 +224,10 @@ export class DashboardService {
? `${focusProject.name} · ${focusProject.currentSprint ?? focusProject.phase}`
: 'No active pipeline',
focus: latestProjectActivity
? summarizeActivity(latestProjectActivity, '최근 프로젝트 이벤트 없음')
? summarizeActivity(
latestProjectActivity,
'최근 프로젝트 이벤트 없음',
)
: '최근 프로젝트 activity 기준으로 확정된 handoff가 아직 없어.',
reviewLoopCount,
escalationCount,
@@ -195,45 +238,57 @@ export class DashboardService {
};
}
private async getLatestQaBoardItems(projects: { name: string; repoName: string; updatedAt: string }[]) {
const docs = await Promise.all(projects.map(async (project) => {
if (!project.repoName) return [] as OpsBoardItem[];
private async getLatestQaBoardItems(
projects: { name: string; repoName: string; updatedAt: string }[],
) {
const docs = await Promise.all(
projects.map(async (project) => {
if (!project.repoName) return [] as OpsBoardItem[];
const pathGroups = await Promise.all(
QA_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(project.repoName, path)),
);
const pathGroups = await Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(project.repoName, path),
),
);
const qaFiles = Array.from(
new Set(
pathGroups
.flat()
.filter((path) => /(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path)),
),
);
const qaFiles = Array.from(
new Set(
pathGroups
.flat()
.filter((path) =>
/(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path),
),
),
);
const latestPath = qaFiles.sort().at(-1);
if (!latestPath) return [] as OpsBoardItem[];
const latestPath = qaFiles.sort().at(-1);
if (!latestPath) return [] as OpsBoardItem[];
const content = await this.gitea.getRawFile(project.repoName, latestPath);
if (!content) return [] as OpsBoardItem[];
const content = await this.gitea.getRawFile(
project.repoName,
latestPath,
);
if (!content) return [] as OpsBoardItem[];
const summary = parseQaSummary(content);
const label = latestPath.split('/').pop()?.replace(/\.md$/i, '') ?? latestPath;
const tone = toneFromText(content);
const summary = parseQaSummary(content);
const label =
latestPath.split('/').pop()?.replace(/\.md$/i, '') ?? latestPath;
const tone = toneFromText(content);
return [
{
id: `qa-${project.repoName}-${label}`,
title: label,
body: summary,
tone,
author: inferQaAuthor(latestPath, content),
time: project.updatedAt,
category: 'qa-log',
source: `${project.repoName}:${latestPath}`,
} satisfies OpsBoardItem,
];
}));
return [
{
id: `qa-${project.repoName}-${label}`,
title: label,
body: summary,
tone,
author: inferQaAuthor(latestPath, content),
time: project.updatedAt,
category: 'qa-log',
source: `${project.repoName}:${latestPath}`,
} satisfies OpsBoardItem,
];
}),
);
return docs.flat();
}

View File

@@ -11,6 +11,16 @@ import { Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
interface SocketUserPayload {
username?: string;
role?: string;
sub?: number;
}
interface SocketWithUser extends Socket {
user?: SocketUserPayload;
}
@WebSocketGateway({
cors: {
origin: (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
@@ -37,11 +47,14 @@ export class EventsGateway
this.logger.log('WebSocket Gateway initialized');
}
handleConnection(client: Socket) {
handleConnection(client: SocketWithUser) {
// JWT 인증 필수 — 토큰 없거나 유효하지 않으면 disconnect
const token =
(client.handshake.auth?.token as string) ??
(client.handshake.headers.authorization as string)?.replace('Bearer ', '');
(client.handshake.headers.authorization as string)?.replace(
'Bearer ',
'',
);
if (!token) {
this.logger.debug(`WS rejected (no token): ${client.id}`);
@@ -56,9 +69,13 @@ export class EventsGateway
}
try {
const payload = this.jwtService.verify(token, { secret });
(client as any).user = payload;
this.logger.debug(`WS client connected: ${client.id} (${payload.username})`);
const payload = this.jwtService.verify<SocketUserPayload>(token, {
secret,
});
client.user = payload;
this.logger.debug(
`WS client connected: ${client.id} (${payload.username ?? 'unknown'})`,
);
} catch {
this.logger.debug(`WS rejected (invalid token): ${client.id}`);
client.disconnect();

View File

@@ -13,7 +13,11 @@ import { SistersModule } from '../sisters/sisters.module';
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: (() => { const s = config.get<string>('JWT_SECRET'); if (!s) throw new Error('JWT_SECRET is not configured'); return s; })(),
secret: (() => {
const s = config.get<string>('JWT_SECRET');
if (!s) throw new Error('JWT_SECRET is not configured');
return s;
})(),
}),
}),
],

View File

@@ -1,4 +1,9 @@
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import {
Injectable,
Logger,
OnModuleInit,
OnModuleDestroy,
} from '@nestjs/common';
import { SistersService } from '../sisters/sisters.service';
import { EventsGateway } from './events.gateway';
@@ -6,7 +11,10 @@ import { EventsGateway } from './events.gateway';
export class EventsScheduler implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(EventsScheduler.name);
private timer: NodeJS.Timeout | null = null;
private readonly INTERVAL_MS = parseInt(process.env.WS_POLL_INTERVAL_MS ?? '30000', 10);
private readonly INTERVAL_MS = parseInt(
process.env.WS_POLL_INTERVAL_MS ?? '30000',
10,
);
constructor(
private readonly sistersService: SistersService,
@@ -14,8 +22,12 @@ export class EventsScheduler implements OnModuleInit, OnModuleDestroy {
) {}
onModuleInit() {
this.timer = setInterval(() => this.tick(), this.INTERVAL_MS);
this.logger.log(`WebSocket scheduler started (interval: ${this.INTERVAL_MS}ms)`);
this.timer = setInterval(() => {
void this.tick();
}, this.INTERVAL_MS);
this.logger.log(
`WebSocket scheduler started (interval: ${this.INTERVAL_MS}ms)`,
);
}
onModuleDestroy() {

View File

@@ -14,13 +14,17 @@ export class SistersScheduler {
start() {
if (this.timer) return;
this.timer = setInterval(async () => {
try {
const sisters = await this.sistersService.getAllSistersStatus();
this.eventsGateway.broadcastSisterStatus(sisters);
} catch {
this.logger.warn('Failed to broadcast sisters update');
}
this.timer = setInterval(() => {
void this.broadcast();
}, 30000);
}
private async broadcast() {
try {
const sisters = await this.sistersService.getAllSistersStatus();
this.eventsGateway.broadcastSisterStatus(sisters);
} catch {
this.logger.warn('Failed to broadcast sisters update');
}
}
}

View File

@@ -8,7 +8,13 @@ import { AuthModule } from '../auth/auth.module';
import { ProjectsModule } from '../projects/projects.module';
@Module({
imports: [PrismaModule, GiteaModule, ActivityModule, AuthModule, ProjectsModule],
imports: [
PrismaModule,
GiteaModule,
ActivityModule,
AuthModule,
ProjectsModule,
],
controllers: [GiteaSyncController],
providers: [GiteaSyncService],
exports: [GiteaSyncService],

View File

@@ -1,5 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../prisma/prisma.service';
import { GiteaService } from '../gitea/gitea.service';
import { ActivityService } from '../activity/activity.service';
@@ -17,7 +16,11 @@ export class GiteaSyncService {
private readonly sprintSync: SprintSyncService,
) {}
async syncRepos(): Promise<{ synced: number; created: number; updated: number }> {
async syncRepos(): Promise<{
synced: number;
created: number;
updated: number;
}> {
const repos = await this.gitea.getOrgRepos();
if (!repos.length) {
@@ -71,11 +74,14 @@ export class GiteaSyncService {
});
}
this.logger.log(`Gitea sync: ${repos.length} repos, ${created} new, ${updated} updated`);
this.logger.log(
`Gitea sync: ${repos.length} repos, ${created} new, ${updated} updated`,
);
// Sprint 동기화도 함께 수행
await this.sprintSync.syncAllProjectSprints().catch((e) => {
this.logger.warn(`Sprint sync failed: ${e.message}`);
await this.sprintSync.syncAllProjectSprints().catch((e: unknown) => {
const message = e instanceof Error ? e.message : String(e);
this.logger.warn(`Sprint sync failed: ${message}`);
});
return { synced: repos.length, created, updated };

View File

@@ -45,7 +45,7 @@ export interface GiteaBranch {
@Injectable()
export class GiteaService {
private readonly logger = new Logger(GiteaService.name);
private readonly client: AxiosInstance;
private readonly client: AxiosInstance | null;
private readonly org: string;
constructor(private readonly config: ConfigService) {
@@ -54,8 +54,10 @@ export class GiteaService {
this.org = config.get<string>('GITEA_ORG') ?? 'hanarang';
if (!baseURL || !token) {
this.logger.warn('GITEA_BASE_URL or GITEA_TOKEN not set — Gitea features disabled');
this.client = null as any;
this.logger.warn(
'GITEA_BASE_URL or GITEA_TOKEN not set — Gitea features disabled',
);
this.client = null;
return;
}
@@ -66,27 +68,30 @@ export class GiteaService {
});
}
private isAvailable(): boolean {
return this.client !== null;
}
async getOrgRepos(): Promise<GiteaRepo[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaRepo[]>(`/orgs/${this.org}/repos`, {
params: { limit: 50 },
});
const { data } = await client.get<GiteaRepo[]>(
`/orgs/${this.org}/repos`,
{
params: { limit: 50 },
},
);
return data;
} catch (error) {
} catch {
this.logger.warn('Failed to fetch Gitea repos');
return [];
}
}
async getRepo(repoName: string): Promise<GiteaRepo | null> {
if (!this.isAvailable()) return null;
const client = this.client;
if (!client) return null;
try {
const { data } = await this.client.get<GiteaRepo>(`/repos/${this.org}/${repoName}`);
const { data } = await client.get<GiteaRepo>(
`/repos/${this.org}/${repoName}`,
);
return data;
} catch {
return null;
@@ -94,9 +99,10 @@ export class GiteaService {
}
async getOpenPRs(repoName: string): Promise<GiteaPR[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaPR[]>(
const { data } = await client.get<GiteaPR[]>(
`/repos/${this.org}/${repoName}/pulls`,
{ params: { state: 'open', limit: 20 } },
);
@@ -107,9 +113,10 @@ export class GiteaService {
}
async getCommits(repoName: string, limit = 20): Promise<GiteaCommit[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaCommit[]>(
const { data } = await client.get<GiteaCommit[]>(
`/repos/${this.org}/${repoName}/commits`,
{ params: { limit } },
);
@@ -121,9 +128,10 @@ export class GiteaService {
}
async getBranches(repoName: string): Promise<GiteaBranch[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaBranch[]>(
const { data } = await client.get<GiteaBranch[]>(
`/repos/${this.org}/${repoName}/branches`,
{ params: { limit: 50 } },
);
@@ -133,10 +141,14 @@ export class GiteaService {
}
}
async getPulls(repoName: string, state: 'open' | 'closed' | 'all' = 'open'): Promise<GiteaPR[]> {
if (!this.isAvailable()) return [];
async getPulls(
repoName: string,
state: 'open' | 'closed' | 'all' = 'open',
): Promise<GiteaPR[]> {
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaPR[]>(
const { data } = await client.get<GiteaPR[]>(
`/repos/${this.org}/${repoName}/pulls`,
{ params: { state, limit: 30, type: 'pulls' } },
);
@@ -147,22 +159,27 @@ export class GiteaService {
}
async getRepoTree(repoName: string, treePath: string): Promise<string[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<{ tree: { path: string; type: string }[] }>(
`/repos/${this.org}/${repoName}/git/trees/HEAD`,
{ params: { recursive: true } },
);
return (data.tree ?? []).filter((e) => e.path.startsWith(treePath) && e.type === 'blob').map((e) => e.path);
const { data } = await client.get<{
tree: { path: string; type: string }[];
}>(`/repos/${this.org}/${repoName}/git/trees/HEAD`, {
params: { recursive: true },
});
return (data.tree ?? [])
.filter((e) => e.path.startsWith(treePath) && e.type === 'blob')
.map((e) => e.path);
} catch {
return [];
}
}
async getRawFile(repoName: string, filePath: string): Promise<string | null> {
if (!this.isAvailable()) return null;
const client = this.client;
if (!client) return null;
try {
const { data } = await this.client.get<string>(
const { data } = await client.get<string>(
`/repos/${this.org}/${repoName}/raw/${filePath}`,
{ params: { ref: 'main' }, responseType: 'text' },
);

View File

@@ -3,18 +3,25 @@ import { Logger, ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import helmet from 'helmet';
function getAllowedOrigins() {
return (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
.split(',')
.map((origin) => origin.trim())
.filter((origin): origin is string => origin.length > 0);
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(helmet());
const allowedOrigins = (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
.split(',')
.map((o) => o.trim())
.filter(Boolean);
const allowedOrigins = getAllowedOrigins();
app.enableCors({
origin: (origin, callback) => {
origin: (
origin: string | undefined,
callback: (err: Error | null, allow?: boolean) => void,
) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
@@ -25,10 +32,17 @@ async function bootstrap() {
credentials: true,
});
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
const port = process.env.BACKEND_PORT ?? 3005;
const port = Number(process.env.BACKEND_PORT ?? 3005);
await app.listen(port);
Logger.log(`🚀 Backend running on port ${port}`, 'Bootstrap');
}
bootstrap();
void bootstrap();

View File

@@ -4,7 +4,10 @@ import { PrismaClient } from '@prisma/client';
import { PrismaMariaDb } from '@prisma/adapter-mariadb';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
constructor(config: ConfigService) {
const dbUrl = config.get<string>('DATABASE_URL');
if (!dbUrl) {

View File

@@ -1,4 +1,12 @@
import { Controller, Get, Param, Query, ParseIntPipe, UseGuards, Post } from '@nestjs/common';
import {
Controller,
Get,
Param,
Query,
ParseIntPipe,
UseGuards,
Post,
} from '@nestjs/common';
import { ProjectsService } from './projects.service';
import { SprintSyncService } from './sprint-sync.service';
import { JwtGuard } from '../auth/jwt.guard';

View File

@@ -3,7 +3,12 @@ import { PrismaService } from '../prisma/prisma.service';
import { GiteaService } from '../gitea/gitea.service';
type QaStatus = 'passed' | 'failed' | 'unknown';
type ProjectPhase = 'PLANNING' | 'IMPLEMENT' | 'QA' | 'READY FOR DEPLOY' | 'DEPLOYED';
type ProjectPhase =
| 'PLANNING'
| 'IMPLEMENT'
| 'QA'
| 'READY FOR DEPLOY'
| 'DEPLOYED';
export interface RepoDocumentMeta {
path: string;
@@ -36,7 +41,10 @@ function normalizeRepoName(repoUrl: string): string {
return repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
}
function extractDocOrder(path: string, kind: 'sprint' | 'hotfix' | 'qa'): number {
function extractDocOrder(
path: string,
kind: 'sprint' | 'hotfix' | 'qa',
): number {
const name = path.split('/').pop() ?? '';
if (kind === 'hotfix') {
const hotfix = name.match(/HOTFIX-(\d+)/i);
@@ -81,7 +89,8 @@ function parseTaskSummary(content: string): string | null {
function parseQaStatus(content: string): QaStatus {
if (/passed\s*[:=]\s*true/i.test(content)) return 'passed';
if (/passed\s*[:=]\s*false/i.test(content)) return 'failed';
if (/\bPASSED\b/i.test(content) && !/\bFAILED\b/i.test(content)) return 'passed';
if (/\bPASSED\b/i.test(content) && !/\bFAILED\b/i.test(content))
return 'passed';
if (/\bFAILED\b/i.test(content)) return 'failed';
return 'unknown';
}
@@ -89,19 +98,27 @@ function parseQaStatus(content: string): QaStatus {
function parseBlockerCount(content: string): number {
const jsonMatch = content.match(/"errors"\s*:\s*\[(.*?)\]/is);
if (jsonMatch) {
const items = jsonMatch[1].split(',').map((item) => item.trim()).filter(Boolean);
const items = jsonMatch[1]
.split(',')
.map((item) => item.trim())
.filter(Boolean);
if (items.length > 0) return items.length;
}
const errorLines = content
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => /^[-*]\s+/.test(line) && /(error|blocker|실패|문제)/i.test(line));
.filter(
(line) =>
/^[-*]\s+/.test(line) && /(error|blocker|실패|문제)/i.test(line),
);
return errorLines.length;
}
function isRepoDocumentMeta(value: RepoDocumentMeta | null): value is RepoDocumentMeta {
function isRepoDocumentMeta(
value: RepoDocumentMeta | null,
): value is RepoDocumentMeta {
return value !== null;
}
@@ -141,11 +158,12 @@ function buildProjectMeta(params: {
phase = 'IMPLEMENT';
}
const deployStatus = phase === 'DEPLOYED'
? 'DEPLOYED ON MAIN'
: phase === 'READY FOR DEPLOY'
? 'READY FOR DEPLOY'
: 'REDEPLOY REQUIRED';
const deployStatus =
phase === 'DEPLOYED'
? 'DEPLOYED ON MAIN'
: phase === 'READY FOR DEPLOY'
? 'READY FOR DEPLOY'
: 'REDEPLOY REQUIRED';
return {
phase,
@@ -177,17 +195,30 @@ export class ProjectsService {
const [repoMetaMap, repoDocsMap] = await Promise.all([
this.getRepoMetaMap(),
this.getRepoDocumentMap(dbProjects.map((project) => normalizeRepoName(project.repoUrl))),
this.getRepoDocumentMap(
dbProjects.map((project) => normalizeRepoName(project.repoUrl)),
),
]);
return dbProjects.map((project) => {
const totalSprints = project.sprints.length;
const doneSprints = project.sprints.filter((sprint) => sprint.status === 'done').length;
const inProgressSprint = project.sprints.find((sprint) => sprint.status === 'in_progress');
const ownerSister = project.sprints.flatMap((sprint) => sprint.tasks).find((task) => task.assignee)?.assignee ?? 'narang';
const progress = totalSprints > 0 ? Math.round((doneSprints / totalSprints) * 100) : 0;
const doneSprints = project.sprints.filter(
(sprint) => sprint.status === 'done',
).length;
const inProgressSprint = project.sprints.find(
(sprint) => sprint.status === 'in_progress',
);
const ownerSister =
project.sprints
.flatMap((sprint) => sprint.tasks)
.find((task) => task.assignee)?.assignee ?? 'narang';
const progress =
totalSprints > 0 ? Math.round((doneSprints / totalSprints) * 100) : 0;
const repoMeta = repoMetaMap[project.giteaId];
const docs = repoDocsMap.get(normalizeRepoName(project.repoUrl)) ?? { hotfixes: [], qas: [] };
const docs = repoDocsMap.get(normalizeRepoName(project.repoUrl)) ?? {
hotfixes: [],
qas: [],
};
const latestHotfix = docs.hotfixes.at(-1) ?? null;
const latestQa = docs.qas.at(-1) ?? null;
const meta = buildProjectMeta({
@@ -213,7 +244,11 @@ export class ProjectsService {
totalSprints,
doneSprints,
sprintCount: totalSprints,
currentSprint: inProgressSprint?.name ?? (doneSprints === totalSprints && totalSprints > 0 ? 'COMPLETED' : null),
currentSprint:
inProgressSprint?.name ??
(doneSprints === totalSprints && totalSprints > 0
? 'COMPLETED'
: null),
ownerSister,
openPRs: repoMeta?.openPRs ?? 0,
updatedAt: repoMeta?.updatedAt ?? project.updatedAt.toISOString(),
@@ -253,8 +288,12 @@ export class ProjectsService {
]);
const totalSprints = project.sprints.length;
const doneSprints = project.sprints.filter((sprint) => sprint.status === 'done').length;
const activeSprint = project.sprints.find((sprint) => sprint.status === 'in_progress');
const doneSprints = project.sprints.filter(
(sprint) => sprint.status === 'done',
).length;
const activeSprint = project.sprints.find(
(sprint) => sprint.status === 'in_progress',
);
const meta = buildProjectMeta({
totalSprints,
doneSprints,
@@ -276,7 +315,8 @@ export class ProjectsService {
label: docs.qas.at(-1)?.label ?? null,
status: docs.qas.at(-1)?.qaStatus ?? 'unknown',
blockerCount: docs.qas.at(-1)?.blockerCount ?? 0,
summary: docs.qas.at(-1)?.summary ?? docs.qas.at(-1)?.description ?? null,
summary:
docs.qas.at(-1)?.summary ?? docs.qas.at(-1)?.description ?? null,
}
: null,
deploy: {
@@ -310,17 +350,23 @@ export class ProjectsService {
const repoName = normalizeRepoName(project.repoUrl);
const docs = await this.collectRepoDocuments(repoName);
return [...docs.sprints, ...docs.hotfixes].filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order);
return [...docs.sprints, ...docs.hotfixes]
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order);
}
private async getProjectMeta(id: number) {
const project = await this.prisma.project.findUnique({ where: { id }, select: { id: true, repoUrl: true } });
const project = await this.prisma.project.findUnique({
where: { id },
select: { id: true, repoUrl: true },
});
if (!project) throw new NotFoundException(`Project ${id} not found`);
return project;
}
private async getRepoMetaMap() {
const repoMetaMap: Record<number, { openPRs: number; updatedAt: string }> = {};
const repoMetaMap: Record<number, { openPRs: number; updatedAt: string }> =
{};
try {
const repos = await this.gitea.getOrgRepos();
for (const repo of repos) {
@@ -337,35 +383,80 @@ export class ProjectsService {
private async getRepoDocumentMap(repoNames: string[]) {
const uniqueRepoNames = Array.from(new Set(repoNames.filter(Boolean)));
const entries = await Promise.all(uniqueRepoNames.map(async (repoName) => [repoName, await this.collectRepoDocuments(repoName)] as const));
const entries = await Promise.all(
uniqueRepoNames.map(
async (repoName) =>
[repoName, await this.collectRepoDocuments(repoName)] as const,
),
);
return new Map(entries);
}
private async collectRepoDocuments(repoName: string) {
const [sprintPaths, hotfixPathGroups, qaPathGroups] = await Promise.all([
this.gitea.getRepoTree(repoName, SPRINT_PATH),
Promise.all(HOTFIX_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(QA_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(
HOTFIX_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
]);
const sprintFiles = sprintPaths.filter((path) => /SPRINT-\d+\.md$/i.test(path));
const hotfixFiles = Array.from(new Set(hotfixPathGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path))));
const qaFiles = Array.from(new Set(qaPathGroups.flat().filter((path) => /(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path))));
const sprintFiles = sprintPaths.filter((path) =>
/SPRINT-\d+\.md$/i.test(path),
);
const hotfixFiles = Array.from(
new Set(
hotfixPathGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path)),
),
);
const qaFiles = Array.from(
new Set(
qaPathGroups
.flat()
.filter((path) =>
/(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path),
),
),
);
const [sprints, hotfixes, qas] = await Promise.all([
Promise.all(sprintFiles.map((path) => this.readRepoDocument(repoName, path, 'sprint'))),
Promise.all(hotfixFiles.map((path) => this.readRepoDocument(repoName, path, 'hotfix'))),
Promise.all(qaFiles.map((path) => this.readRepoDocument(repoName, path, 'qa'))),
Promise.all(
sprintFiles.map((path) =>
this.readRepoDocument(repoName, path, 'sprint'),
),
),
Promise.all(
hotfixFiles.map((path) =>
this.readRepoDocument(repoName, path, 'hotfix'),
),
),
Promise.all(
qaFiles.map((path) => this.readRepoDocument(repoName, path, 'qa')),
),
]);
return {
sprints: sprints.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
hotfixes: hotfixes.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
sprints: sprints
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order),
hotfixes: hotfixes
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order),
qas: qas.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
};
}
private async readRepoDocument(repoName: string, path: string, kind: 'sprint' | 'hotfix' | 'qa'): Promise<RepoDocumentMeta | null> {
private async readRepoDocument(
repoName: string,
path: string,
kind: 'sprint' | 'hotfix' | 'qa',
): Promise<RepoDocumentMeta | null> {
const content = await this.gitea.getRawFile(repoName, path);
if (!content) return null;

View File

@@ -6,6 +6,15 @@ import { GiteaService } from '../gitea/gitea.service';
describe('SprintSyncService', () => {
let service: SprintSyncService;
type TaskWriteArgs = {
data: {
taskId?: string;
assignee: string;
status: string;
};
where?: { id: number };
};
const mockPrisma = {
project: { findUnique: jest.fn(), findMany: jest.fn() },
sprint: { findFirst: jest.fn(), create: jest.fn(), update: jest.fn() },
@@ -29,8 +38,13 @@ describe('SprintSyncService', () => {
service = module.get<SprintSyncService>(SprintSyncService);
jest.clearAllMocks();
mockPrisma.project.findUnique.mockResolvedValue({ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' });
mockPrisma.project.findMany.mockResolvedValue([{ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' }]);
mockPrisma.project.findUnique.mockResolvedValue({
id: 1,
repoUrl: 'https://gitea.example.com/hanarang/project-alpha',
});
mockPrisma.project.findMany.mockResolvedValue([
{ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' },
]);
mockPrisma.sprint.findFirst.mockResolvedValue(null);
mockPrisma.sprint.create.mockResolvedValue({ id: 101, status: 'pending' });
mockPrisma.sprint.update.mockResolvedValue({ id: 101, status: 'pending' });
@@ -38,65 +52,107 @@ describe('SprintSyncService', () => {
mockPrisma.task.create.mockResolvedValue({});
mockPrisma.task.update.mockResolvedValue({});
mockGitea.getRepoTree.mockImplementation(async (_repoName: string, path: string) => {
if (path === '.plans/sprints/') return ['.plans/sprints/SPRINT-005.md', '.plans/sprints/HOTFIX-001.md'];
if (path === '.plans/qa/') return ['.plans/qa/SPRINT-005-review-darang.md'];
if (path === '.qa/') return [];
if (path === '.plans/hotfix/') return ['.plans/hotfix/HOTFIX-001.md'];
return [];
});
mockGitea.getRepoTree.mockImplementation(
(_repoName: string, path: string) => {
if (path === '.plans/sprints/') {
return [
'.plans/sprints/SPRINT-005.md',
'.plans/sprints/HOTFIX-001.md',
];
}
if (path === '.plans/qa/') {
return ['.plans/qa/SPRINT-005-review-darang.md'];
}
if (path === '.qa/') return [];
if (path === '.plans/hotfix/') return ['.plans/hotfix/HOTFIX-001.md'];
return [];
},
);
});
it('담당 라인을 읽어 assignee를 저장한다', async () => {
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 이랑이\n- **설명:** deploy\n\n### TASK-020: QA 자동화\n- **담당:** darang\n- **설명:** qa\n`;
}
if (path.includes('review')) return 'passed: true';
return '# HOTFIX-001: sample';
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 이랑이\n- **설명:** deploy\n\n### TASK-020: QA 자동화\n- **담당:** darang\n- **설명:** qa\n`;
}
if (path.includes('review')) return 'passed: true';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.create).toHaveBeenNthCalledWith(1, expect.objectContaining({
data: expect.objectContaining({ taskId: 'TASK-019', assignee: 'erang', status: 'done' }),
}));
expect(mockPrisma.task.create).toHaveBeenNthCalledWith(2, expect.objectContaining({
data: expect.objectContaining({ taskId: 'TASK-020', assignee: 'darang', status: 'done' }),
}));
const createCalls = mockPrisma.task.create.mock.calls as Array<
[TaskWriteArgs]
>;
expect(createCalls[0]?.[0]).toMatchObject({
data: {
taskId: 'TASK-019',
assignee: 'erang',
status: 'done',
},
});
expect(createCalls[1]?.[0]).toMatchObject({
data: {
taskId: 'TASK-020',
assignee: 'darang',
status: 'done',
},
});
});
it('기존 task도 assignee를 갱신한다', async () => {
mockPrisma.task.findFirst.mockResolvedValue({ id: 500, assignee: 'narang', status: 'pending' });
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 하랑이\n`;
}
if (path.includes('review')) return 'passed: false';
return '# HOTFIX-001: sample';
mockPrisma.task.findFirst.mockResolvedValue({
id: 500,
assignee: 'narang',
status: 'pending',
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 하랑이\n`;
}
if (path.includes('review')) return 'passed: false';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.update).toHaveBeenCalledWith(expect.objectContaining({
const updateCalls = mockPrisma.task.update.mock.calls as Array<
[TaskWriteArgs]
>;
expect(updateCalls[0]?.[0]).toMatchObject({
where: { id: 500 },
data: expect.objectContaining({ assignee: 'harang' }),
}));
data: { assignee: 'harang' },
});
});
it('담당 라인이 없으면 narang fallback', async () => {
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- 설명만 있음\n`;
}
if (path.includes('review')) return 'FAILED';
return '# HOTFIX-001: sample';
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- 설명만 있음\n`;
}
if (path.includes('review')) return 'FAILED';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ assignee: 'narang', status: 'pending' }),
}));
const createCalls = mockPrisma.task.create.mock.calls as Array<
[TaskWriteArgs]
>;
expect(createCalls[0]?.[0]).toMatchObject({
data: {
assignee: 'narang',
status: 'pending',
},
});
});
});

View File

@@ -13,46 +13,64 @@ const QA_PATH_CANDIDATES = ['.plans/qa/', '.qa/'];
const HOTFIX_PATH_CANDIDATES = ['.plans/hotfix/', '.plans/sprints/'];
const SISTER_NAME_MAP: Record<string, string> = {
harang: 'harang',
'하랑': 'harang',
'하랑이': 'harang',
: 'harang',
: 'harang',
narang: 'narang',
'나랑': 'narang',
'나랑이': 'narang',
: 'narang',
: 'narang',
darang: 'darang',
'다랑': 'darang',
'다랑이': 'darang',
: 'darang',
: 'darang',
erang: 'erang',
'이랑': 'erang',
'이랑이': 'erang',
: 'erang',
: 'erang',
};
function parseSprintName(content: string, filename: string, number: number): string {
const headingMatch = content.match(/^#\s+(?:SPRINT-\d+|Sprint\s+\d+)[:\s—\-]+(.+)/m);
function parseSprintName(
content: string,
filename: string,
number: number,
): string {
const headingMatch = content.match(
/^#\s+(?:SPRINT-\d+|Sprint\s+\d+)[:\s—-]+(.+)/m,
);
if (headingMatch) return headingMatch[1].trim();
return filename.replace('.md', '') || `SPRINT-${String(number).padStart(3, '0')}`;
return (
filename.replace('.md', '') || `SPRINT-${String(number).padStart(3, '0')}`
);
}
function parseTaskAssignee(taskLines: string[]): string {
for (const rawLine of taskLines) {
const line = rawLine.trim();
const match = line.match(/^-\s*(?:\*\*)?(?:담당|assignee)\s*:(?:\*\*)?\s*(.+)$/i);
const match = line.match(
/^-\s*(?:\*\*)?(?:담당|assignee)\s*:(?:\*\*)?\s*(.+)$/i,
);
if (!match) continue;
const assignee = match[1]
.trim()
.replace(/[()\[\],]/g, ' ')
.replace(/[()[\],]/g, ' ')
.split(/\s+/)
.find((token) => SISTER_NAME_MAP[token.toLowerCase()] ?? SISTER_NAME_MAP[token]);
.find(
(token) =>
SISTER_NAME_MAP[token.toLowerCase()] ?? SISTER_NAME_MAP[token],
);
if (assignee) {
return SISTER_NAME_MAP[assignee.toLowerCase()] ?? SISTER_NAME_MAP[assignee];
return (
SISTER_NAME_MAP[assignee.toLowerCase()] ?? SISTER_NAME_MAP[assignee]
);
}
}
return 'narang';
}
function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTask[] {
function parseTasks(
content: string,
sprintStatus: 'pending' | 'done',
): ParsedTask[] {
const lines = content.split(/\r?\n/);
const tasks: ParsedTask[] = [];
const seen = new Set<string>();
@@ -66,7 +84,9 @@ function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTa
if (match) status = sprintStatus;
if (!match) {
match = line.match(/^-\s*\[([ xX])\]\s*(TASK-\d+[A-Z]?)\s*[:\-]?\s*(.+)$/i);
match = line.match(
/^-\s*\[([ xX])\]\s*(TASK-\d+[A-Z]?)\s*[:-]?\s*(.+)$/i,
);
if (match) status = /x/i.test(match[1]) ? 'done' : 'pending';
}
@@ -89,7 +109,11 @@ function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTa
const taskBlock: string[] = [];
for (let lookahead = index + 1; lookahead < lines.length; lookahead += 1) {
const nextLine = lines[lookahead].trim();
if (/^#{2,6}\s+TASK-\d+[A-Z]?\s*:/i.test(nextLine) || /^-\s*\[?[ xX]?\]?\s*TASK-\d+[A-Z]?\s*[:\-]?/i.test(nextLine) || /^TASK-\d+[A-Z]?\s*:/i.test(nextLine)) {
if (
/^#{2,6}\s+TASK-\d+[A-Z]?\s*:/i.test(nextLine) ||
/^-\s*\[?[ xX]?\]?\s*TASK-\d+[A-Z]?\s*[:-]?/i.test(nextLine) ||
/^TASK-\d+[A-Z]?\s*:/i.test(nextLine)
) {
break;
}
if (/^##\s+/.test(nextLine) && !/^##\s+목표/.test(nextLine)) {
@@ -126,8 +150,12 @@ export class SprintSyncService {
private readonly gitea: GiteaService,
) {}
async syncProjectSprints(projectId: number): Promise<{ synced: number; created: number; updated: number }> {
const project = await this.prisma.project.findUnique({ where: { id: projectId } });
async syncProjectSprints(
projectId: number,
): Promise<{ synced: number; created: number; updated: number }> {
const project = await this.prisma.project.findUnique({
where: { id: projectId },
});
if (!project) return { synced: 0, created: 0, updated: 0 };
const repoName = project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
@@ -135,11 +163,14 @@ export class SprintSyncService {
}
async syncAllProjectSprints(): Promise<{ projects: number; synced: number }> {
const projects = await this.prisma.project.findMany({ select: { id: true, repoUrl: true } });
const projects = await this.prisma.project.findMany({
select: { id: true, repoUrl: true },
});
let totalSynced = 0;
for (const project of projects) {
const repoName = project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
const repoName =
project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
const result = await this.syncRepo(project.id, repoName);
totalSynced += result.synced;
}
@@ -147,16 +178,39 @@ export class SprintSyncService {
return { projects: projects.length, synced: totalSynced };
}
private async syncRepo(projectId: number, repoName: string): Promise<{ synced: number; created: number; updated: number }> {
private async syncRepo(
projectId: number,
repoName: string,
): Promise<{ synced: number; created: number; updated: number }> {
const [sprintFilePaths, qaGroups, hotfixGroups] = await Promise.all([
this.gitea.getRepoTree(repoName, '.plans/sprints/'),
Promise.all(QA_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(HOTFIX_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
Promise.all(
HOTFIX_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
]);
const sprintFiles = sprintFilePaths.filter((path) => /SPRINT-\d+\.md$/i.test(path));
const qaFiles = Array.from(new Set(qaGroups.flat().filter((path) => /SPRINT-\d+.*(?:review|qa).*\.md$/i.test(path))));
const hotfixFiles = Array.from(new Set(hotfixGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path))));
const sprintFiles = sprintFilePaths.filter((path) =>
/SPRINT-\d+\.md$/i.test(path),
);
const qaFiles = Array.from(
new Set(
qaGroups
.flat()
.filter((path) => /SPRINT-\d+.*(?:review|qa).*\.md$/i.test(path)),
),
);
const hotfixFiles = Array.from(
new Set(
hotfixGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path)),
),
);
if (!sprintFiles.length) {
this.logger.warn(`No sprint files found in ${repoName}/.plans/sprints/`);
@@ -186,14 +240,20 @@ export class SprintSyncService {
const number = parseInt(numberMatch[1], 10);
const name = parseSprintName(content, filename, number);
const status: 'pending' | 'done' = passedMap.get(number) ? 'done' : 'pending';
const status: 'pending' | 'done' = passedMap.get(number)
? 'done'
: 'pending';
const parsedTasks = parseTasks(content, status);
const existingSprint = await this.prisma.sprint.findFirst({ where: { projectId, number } });
const existingSprint = await this.prisma.sprint.findFirst({
where: { projectId, number },
});
let sprintId = existingSprint?.id ?? 0;
if (!existingSprint) {
const createdSprint = await this.prisma.sprint.create({ data: { projectId, number, name, status } });
const createdSprint = await this.prisma.sprint.create({
data: { projectId, number, name, status },
});
sprintId = createdSprint.id;
created += 1;
} else {
@@ -209,7 +269,9 @@ export class SprintSyncService {
}
for (const task of parsedTasks) {
const existingTask = await this.prisma.task.findFirst({ where: { sprintId, taskId: task.taskId } });
const existingTask = await this.prisma.task.findFirst({
where: { sprintId, taskId: task.taskId },
});
if (!existingTask) {
await this.prisma.task.create({
data: {
@@ -233,7 +295,9 @@ export class SprintSyncService {
}
}
this.logger.log(`${repoName}: ${sprintFiles.length} sprints, ${hotfixFiles.length} hotfix docs, ${passedMap.size} QA passed → ${created} created, ${updated} updated`);
this.logger.log(
`${repoName}: ${sprintFiles.length} sprints, ${hotfixFiles.length} hotfix docs, ${passedMap.size} QA passed → ${created} created, ${updated} updated`,
);
return { synced: sprintFiles.length, created, updated };
}
}

View File

@@ -24,7 +24,9 @@ export class SettingsService {
) {}
async getAll() {
const rows = await this.prisma.systemSettings.findMany({ orderBy: { key: 'asc' } });
const rows = await this.prisma.systemSettings.findMany({
orderBy: { key: 'asc' },
});
const merged = { ...DEFAULT_SETTINGS };
for (const row of rows) merged[row.key] = row.value;
return merged;
@@ -33,7 +35,9 @@ export class SettingsService {
async saveAll(payload: Record<string, string>) {
// DEFAULT_SETTINGS에 있는 키만 허용
const allowed = Object.keys(DEFAULT_SETTINGS);
const entries = Object.entries(payload).filter(([key]) => allowed.includes(key));
const entries = Object.entries(payload).filter(([key]) =>
allowed.includes(key),
);
await this.prisma.$transaction(
entries.map(([key, value]) =>
this.prisma.systemSettings.upsert({

View File

@@ -9,9 +9,16 @@ describe('SisterDetailService', () => {
let service: SisterDetailService;
const mockSister = {
id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang',
lxcId: 105, status: 'online', lastSeen: new Date(),
sshKeyPath: null, createdAt: new Date(), updatedAt: new Date(),
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
status: 'online',
lastSeen: new Date(),
sshKeyPath: null,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockPrisma = {
@@ -35,7 +42,9 @@ describe('SisterDetailService', () => {
{ provide: PrismaService, useValue: mockPrisma },
{
provide: ConfigService,
useValue: { get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa') },
useValue: {
get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa'),
},
},
],
}).compile();
@@ -58,7 +67,9 @@ describe('SisterDetailService', () => {
it('getSisterConfig: sister 없으면 NotFoundException', async () => {
mockPrisma.sisterConfig.findUnique.mockResolvedValue(null);
await expect(service.getSisterConfig('narang')).rejects.toThrow(NotFoundException);
await expect(service.getSisterConfig('narang')).rejects.toThrow(
NotFoundException,
);
});
it('getSisterSessions: SSH 실패 시 빈 배열', async () => {

View File

@@ -3,8 +3,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { SshService } from './ssh.service';
import { ConfigService } from '@nestjs/config';
const SISTER_NAMES = ['harang', 'narang', 'darang', 'erang'] as const;
type SisterName = (typeof SISTER_NAMES)[number];
type SisterName = 'harang' | 'narang' | 'darang' | 'erang';
const SISTER_ROLES: Record<SisterName, string> = {
harang: 'Orchestrator',
@@ -14,7 +13,8 @@ const SISTER_ROLES: Record<SisterName, string> = {
};
const SISTER_DESCRIPTIONS: Record<SisterName, string> = {
harang: '기획과 오케스트레이션. 스프린트를 설계하고 자매들에게 작업을 배분한다.',
harang:
'기획과 오케스트레이션. 스프린트를 설계하고 자매들에게 작업을 배분한다.',
narang: '코드 생성과 개발. 스프린트를 구현하고 PR을 만든다.',
darang: '품질 검증. 코드 리뷰와 보안 감사를 수행한다.',
erang: '인프라와 배포. 서버 관리, merge, 프로덕션 배포를 담당한다.',
@@ -70,15 +70,19 @@ export class SisterDetailService {
'SESSION_DIR=~/.hermes/sessions; [ -d "$SESSION_DIR" ] || SESSION_DIR=~/.openclaw/sessions; ls -lt "$SESSION_DIR"/ 2>/dev/null | head -20 || echo ""',
);
const lines = result.stdout.split('\n').filter((l) => l && !l.startsWith('total'));
return lines.map((line) => {
const parts = line.trim().split(/\s+/);
return {
name: parts[parts.length - 1] ?? '',
modified: parts.slice(5, 8).join(' '),
size: parts[4] ?? '0',
};
}).filter((s) => s.name && s.name !== '');
const lines = result.stdout
.split('\n')
.filter((l) => l && !l.startsWith('total'));
return lines
.map((line) => {
const parts = line.trim().split(/\s+/);
return {
name: parts[parts.length - 1] ?? '',
modified: parts.slice(5, 8).join(' '),
size: parts[4] ?? '0',
};
})
.filter((s) => s.name && s.name !== '');
} catch {
return [];
}
@@ -96,8 +100,13 @@ export class SisterDetailService {
'AGENT_DIR=~/.hermes/workspace/agents; [ -d "$AGENT_DIR" ] || AGENT_DIR=~/.openclaw/workspace/agents; ls "$AGENT_DIR"/ 2>/dev/null || echo ""',
);
const agents = result.stdout.split('\n').filter((l) => l.trim().endsWith('.md'));
return agents.map((a) => ({ name: a.trim().replace('.md', ''), file: a.trim() }));
const agents = result.stdout
.split('\n')
.filter((l) => l.trim().endsWith('.md'));
return agents.map((a) => ({
name: a.trim().replace('.md', ''),
file: a.trim(),
}));
} catch {
return [];
}
@@ -140,7 +149,9 @@ export class SisterDetailService {
}
private async getSisterRecord(name: SisterName) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) throw new NotFoundException(`Sister ${name} not found`);
return sister;
}

View File

@@ -21,7 +21,7 @@ export class SistersController {
@Get(':name/system')
async getSystemInfo(@Param('name', SisterNamePipe) name: SisterName) {
return this.sistersService.getSystemInfo(name as SisterName);
return this.sistersService.getSystemInfo(name);
}
@Get(':name/avatar')
@@ -29,7 +29,7 @@ export class SistersController {
@Param('name', SisterNamePipe) name: SisterName,
@Res() res: Response,
) {
const sister = await this.sistersService.findByName(name as SisterName);
const sister = await this.sistersService.findByName(name);
if (!sister) {
return res.status(404).json({ message: 'Sister not found' });
}
@@ -42,21 +42,21 @@ export class SistersController {
@Get(':name/config')
async getSisterConfig(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterConfig(name as SisterName);
return this.sisterDetail.getSisterConfig(name);
}
@Get(':name/sessions')
async getSisterSessions(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterSessions(name as SisterName);
return this.sisterDetail.getSisterSessions(name);
}
@Get(':name/subagents')
async getSisterSubagents(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterSubagents(name as SisterName);
return this.sisterDetail.getSisterSubagents(name);
}
@Get(':name/activity')
async getSisterActivity(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterActivityLog(name as SisterName);
return this.sisterDetail.getSisterActivityLog(name);
}
}

View File

@@ -7,13 +7,56 @@ import { ConfigService } from '@nestjs/config';
describe('SistersService', () => {
let service: SistersService;
let sshService: jest.Mocked<SshService>;
let prismaService: jest.Mocked<PrismaService>;
const mockSisters = [
{ id: 1, name: 'harang', ip: '10.10.10.112', user: 'harang', lxcId: 104, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang', lxcId: 105, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 3, name: 'darang', ip: '10.10.10.136', user: 'darang', lxcId: 106, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 4, name: 'erang', ip: '10.10.10.163', user: 'erang', lxcId: 107, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{
id: 1,
name: 'harang',
ip: '10.10.10.112',
user: 'harang',
lxcId: 104,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 3,
name: 'darang',
ip: '10.10.10.136',
user: 'darang',
lxcId: 106,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 4,
name: 'erang',
ip: '10.10.10.163',
user: 'erang',
lxcId: 107,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
];
beforeEach(async () => {
@@ -35,22 +78,28 @@ describe('SistersService', () => {
{ provide: PrismaService, useValue: mockPrisma },
{
provide: ConfigService,
useValue: { get: jest.fn().mockImplementation((key: string) => {
if (key === 'SSH_KEY_PATH') return '/home/narang/.ssh/id_rsa';
if (key === 'DATABASE_URL') return 'mysql://test:test@localhost:3306/test';
return undefined;
}) },
useValue: {
get: jest.fn().mockImplementation((key: string) => {
if (key === 'SSH_KEY_PATH') return '/home/narang/.ssh/id_rsa';
if (key === 'DATABASE_URL')
return 'mysql://test:test@localhost:3306/test';
return undefined;
}),
},
},
],
}).compile();
service = module.get<SistersService>(SistersService);
sshService = module.get(SshService);
prismaService = module.get(PrismaService);
});
it('SSH 성공 시 online 상태 반환', async () => {
sshService.executeCommand.mockResolvedValue({ stdout: 'active', stderr: '', code: 0 });
sshService.executeCommand.mockResolvedValue({
stdout: 'active',
stderr: '',
code: 0,
});
const result = await service.getAllSistersStatus();
@@ -58,11 +107,13 @@ describe('SistersService', () => {
expect(result[0].status).toBe('online');
expect(result[0].name).toBe('harang');
expect(result[0].role).toBe('Orchestrator');
expect((result[0] as any).ip).toBeUndefined(); // IP 노출 제거 확인
expect(result[0]).not.toHaveProperty('ip'); // IP 노출 제거 확인
});
it('SSH 실패 시 offline graceful fallback', async () => {
sshService.executeCommand.mockRejectedValue(new Error('Connection refused'));
sshService.executeCommand.mockRejectedValue(
new Error('Connection refused'),
);
const result = await service.getAllSistersStatus();
@@ -73,13 +124,13 @@ describe('SistersService', () => {
it('일부 SSH 실패 시 실패한 자매만 offline', async () => {
sshService.executeCommand
.mockResolvedValueOnce({ stdout: 'active', stderr: '', code: 0 }) // harang
.mockRejectedValueOnce(new Error('timeout')) // narang
.mockRejectedValueOnce(new Error('timeout')) // narang
.mockResolvedValueOnce({ stdout: 'inactive', stderr: '', code: 1 }) // darang
.mockRejectedValueOnce(new Error('timeout')); // erang
.mockRejectedValueOnce(new Error('timeout')); // erang
const result = await service.getAllSistersStatus();
expect(result[0].status).toBe('online'); // harang
expect(result[0].status).toBe('online'); // harang
expect(result[1].status).toBe('offline'); // narang (SSH 실패)
expect(result[2].status).toBe('offline'); // darang (inactive)
expect(result[3].status).toBe('offline'); // erang (SSH 실패)

View File

@@ -67,16 +67,54 @@ export class SistersService {
}
async getSystemInfo(name: string) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) return null;
const sshKeyPath = this.config.get<string>('SSH_KEY_PATH');
if (!sshKeyPath) return null;
const [uptimeRes, cpuRes, memRes, diskRes] = await Promise.all([
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, 'cat /proc/uptime 2>/dev/null || echo "0 0"').catch(() => ({ stdout: '0 0', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, "top -bn1 | grep Cpu || echo '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id'").catch(() => ({ stdout: '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, 'free -m | grep Mem || echo "Mem: 0 0 0 0 0 0"').catch(() => ({ stdout: 'Mem: 0 0 0 0 0 0', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, "df -h / | tail -1 || echo '/dev/root 0G 0G 0G 0% /'").catch(() => ({ stdout: '/dev/root 0G 0G 0G 0% /', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
'cat /proc/uptime 2>/dev/null || echo "0 0"',
)
.catch(() => ({ stdout: '0 0', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
"top -bn1 | grep Cpu || echo '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id'",
)
.catch(() => ({
stdout: '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id',
stderr: '',
code: 0,
})),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
'free -m | grep Mem || echo "Mem: 0 0 0 0 0 0"',
)
.catch(() => ({ stdout: 'Mem: 0 0 0 0 0 0', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
"df -h / | tail -1 || echo '/dev/root 0G 0G 0G 0% /'",
)
.catch(() => ({
stdout: '/dev/root 0G 0G 0G 0% /',
stderr: '',
code: 0,
})),
]);
return {
@@ -88,7 +126,15 @@ export class SistersService {
}
private async checkSisterStatus(
sister: { id: number; name: string; ip: string; user: string; lxcId: number; lastSeen: Date | null; status: string },
sister: {
id: number;
name: string;
ip: string;
user: string;
lxcId: number;
lastSeen: Date | null;
status: string;
},
sshKeyPath: string,
): Promise<SisterStatus> {
try {
@@ -110,11 +156,13 @@ export class SistersService {
});
if (prevStatus !== status && this.activity) {
await this.activity.log({
sisterId: sister.id,
action: 'status_changed',
detail: `[${sister.name}] status: ${prevStatus}${status}`,
}).catch(() => {});
await this.activity
.log({
sisterId: sister.id,
action: 'status_changed',
detail: `[${sister.name}] status: ${prevStatus}${status}`,
})
.catch(() => {});
}
return {

View File

@@ -1,4 +1,12 @@
import { Controller, Get, Post, Patch, Param, Body, ParseIntPipe } from '@nestjs/common';
import {
Controller,
Get,
Post,
Patch,
Param,
Body,
ParseIntPipe,
} from '@nestjs/common';
import { TasksService, CreateSprintDto, UpdateTaskDto } from './tasks.service';
@Controller('api')

View File

@@ -8,15 +8,27 @@ describe('TasksService', () => {
let service: TasksService;
const mockTask = {
id: 1, taskId: 'TASK-001', title: 'Test', assignee: 'narang',
status: 'pending', iteration: 0, sprintId: 1,
createdAt: new Date(), updatedAt: new Date(),
id: 1,
taskId: 'TASK-001',
title: 'Test',
assignee: 'narang',
status: 'pending',
iteration: 0,
sprintId: 1,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockSprint = {
id: 1, projectId: 1, number: 1, name: 'Sprint 001',
status: 'in_progress', startedAt: null, completedAt: null,
createdAt: new Date(), updatedAt: new Date(),
id: 1,
projectId: 1,
number: 1,
name: 'Sprint 001',
status: 'in_progress',
startedAt: null,
completedAt: null,
createdAt: new Date(),
updatedAt: new Date(),
tasks: [mockTask],
};
@@ -57,7 +69,9 @@ describe('TasksService', () => {
it('getTaskLedger: sprint + task + progress 반환', async () => {
mockPrisma.project.findUnique.mockResolvedValue({
id: 1,
sprints: [{ ...mockSprint, tasks: [{ ...mockTask, status: 'done' }, mockTask] }],
sprints: [
{ ...mockSprint, tasks: [{ ...mockTask, status: 'done' }, mockTask] },
],
});
const result = await service.getTaskLedger(1);
@@ -67,8 +81,15 @@ describe('TasksService', () => {
});
it('updateTask: 상태 변경 시 ActivityLog 기록', async () => {
mockPrisma.task.findUnique.mockResolvedValue({ ...mockTask, status: 'in_progress' });
mockPrisma.task.update.mockResolvedValue({ ...mockTask, status: 'done', sprintId: 1 });
mockPrisma.task.findUnique.mockResolvedValue({
...mockTask,
status: 'in_progress',
});
mockPrisma.task.update.mockResolvedValue({
...mockTask,
status: 'done',
sprintId: 1,
});
await service.updateTask(1, { status: 'done' });

View File

@@ -13,7 +13,15 @@ export class CreateSprintDto {
name!: string;
}
const VALID_STATUSES = ['pending', 'in_progress', 'review', 'done', 'failed', 'blocked', 'escalated'] as const;
const VALID_STATUSES = [
'pending',
'in_progress',
'review',
'done',
'failed',
'blocked',
'escalated',
] as const;
export class UpdateTaskDto {
@IsOptional()
@@ -58,14 +66,21 @@ export class TasksService {
startedAt: sprint.startedAt,
completedAt: sprint.completedAt,
tasks: sprint.tasks,
progress: sprint.tasks.length > 0
? Math.round(sprint.tasks.filter((t) => t.status === 'done').length / sprint.tasks.length * 100)
: 0,
progress:
sprint.tasks.length > 0
? Math.round(
(sprint.tasks.filter((t) => t.status === 'done').length /
sprint.tasks.length) *
100,
)
: 0,
}));
}
async createSprint(projectId: number, dto: CreateSprintDto) {
const project = await this.prisma.project.findUnique({ where: { id: projectId } });
const project = await this.prisma.project.findUnique({
where: { id: projectId },
});
if (!project) throw new NotFoundException(`Project ${projectId} not found`);
const sprint = await this.prisma.sprint.create({
@@ -90,9 +105,10 @@ export class TasksService {
where: { id: taskId },
data: {
...dto,
iteration: dto.status && dto.status !== prevStatus && prevStatus !== 'pending'
? { increment: 1 }
: undefined,
iteration:
dto.status && dto.status !== prevStatus && prevStatus !== 'pending'
? { increment: 1 }
: undefined,
},
});