v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

@@ -0,0 +1,80 @@
/**
* 에이전트 정의
* 각 에이전트의 역할, 시스템 프롬프트, 도구 권한 정의
*/
import type { AgentDefinition } from '@anthropic-ai/claude-agent-sdk';
import {
BACKEND_PROMPT,
FRONTEND_PROMPT,
LAYOUT_PROMPT,
TEMPLATE_PROMPT,
REVIEWER_PROMPT,
} from '../prompts/index.js';
/**
* 백엔드 개발자 에이전트
* Service-Repository 패턴, FormRequest, 훅 시스템 담당
*/
export const backendAgent: AgentDefinition = {
description: '백엔드 개발: Service-Repository 패턴, FormRequest, Controller, 훅 시스템, Migration',
prompt: BACKEND_PROMPT,
tools: ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'],
model: 'sonnet',
};
/**
* 프론트엔드 개발자 에이전트
* TSX 컴포넌트, 상태 관리, G7Core API 담당
*/
export const frontendAgent: AgentDefinition = {
description: '프론트엔드 개발: TSX 컴포넌트, 상태 관리, G7Core API, 다크 모드',
prompt: FRONTEND_PROMPT,
tools: ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'],
model: 'sonnet',
};
/**
* 레이아웃 개발자 에이전트
* 레이아웃 JSON, 데이터 바인딩, 반응형 담당
*/
export const layoutAgent: AgentDefinition = {
description: '레이아웃 개발: 레이아웃 JSON 스키마, 데이터 바인딩, 반응형, 상속/슬롯',
prompt: LAYOUT_PROMPT,
tools: ['Read', 'Write', 'Edit', 'Glob', 'Grep'],
model: 'sonnet',
};
/**
* 템플릿 개발자 에이전트
* 템플릿 구조, 빌드, 컴포넌트 등록 담당
*/
export const templateAgent: AgentDefinition = {
description: '템플릿 개발: 템플릿 구조, Vite 빌드, 컴포넌트 등록, 다국어 파일',
prompt: TEMPLATE_PROMPT,
tools: ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'],
model: 'sonnet',
};
/**
* 검수자 에이전트
* 규정 준수, 테스트, 문서화 검증 담당
*/
export const reviewerAgent: AgentDefinition = {
description: '코드 검수: 규정 준수 확인, 테스트 통과, 문서화 검증',
prompt: REVIEWER_PROMPT,
tools: ['Read', 'Glob', 'Grep', 'Bash'],
model: 'sonnet',
};
/**
* 모든 에이전트 정의
*/
export const agentDefinitions: Record<string, AgentDefinition> = {
backend: backendAgent,
frontend: frontendAgent,
layout: layoutAgent,
template: templateAgent,
reviewer: reviewerAgent,
};
export default agentDefinitions;
+11
View File
@@ -0,0 +1,11 @@
/**
* 에이전트 모듈 export
*/
export {
agentDefinitions,
backendAgent,
frontendAgent,
layoutAgent,
templateAgent,
reviewerAgent,
} from './definitions.js';
+252
View File
@@ -0,0 +1,252 @@
/**
* CLI 인터페이스
* 인터랙티브 모드 및 단일 명령어 모드 지원
*/
import * as readline from 'readline';
import { Coordinator } from './coordinator/Coordinator.js';
import {
featureDevelopmentWorkflow,
bugfixWorkflow,
prReviewWorkflow,
} from './workflows/index.js';
import { logger } from './utils/logger.js';
import type { CliOptions, WorkflowResult, WorkflowType } from './types/index.js';
const PROJECT_ROOT = process.env.G7_PROJECT_ROOT || '.';
/**
* CLI 실행
*/
export async function runCli(options: CliOptions): Promise<void> {
if (options.mode === 'interactive') {
await runInteractiveMode();
} else {
if (!options.prompt) {
console.error('Error: prompt is required for single mode');
process.exit(1);
}
await runSingleMode(options.prompt, options.workflow);
}
}
/**
* 인터랙티브 모드
*/
async function runInteractiveMode(): Promise<void> {
console.log(`
╔════════════════════════════════════════════════════════════╗
║ 그누보드7 Multi-Agent System v1.0.0 ║
║ ║
║ 사용 가능한 명령어: ║
║ /feature <설명> - 기능 개발 워크플로우 ║
║ /bugfix <설명> - 버그 수정 워크플로우 ║
║ /review <PR#> - PR 검수 워크플로우 ║
║ /help - 도움말 ║
║ /exit - 종료 ║
║ ║
║ 또는 자유롭게 요청을 입력하세요. ║
╚════════════════════════════════════════════════════════════╝
`);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const coordinator = new Coordinator({ cwd: PROJECT_ROOT });
const promptUser = () => {
rl.question('\n🤖 > ', async (input) => {
const trimmedInput = input.trim();
if (!trimmedInput) {
promptUser();
return;
}
// 종료 명령
if (trimmedInput === '/exit' || trimmedInput === 'exit') {
console.log('\n👋 안녕히 가세요!');
rl.close();
return;
}
// 도움말
if (trimmedInput === '/help') {
showHelp();
promptUser();
return;
}
try {
let result: WorkflowResult;
// 워크플로우 명령어
if (trimmedInput.startsWith('/feature ')) {
const description = trimmedInput.substring(9);
console.log('\n🚀 기능 개발 워크플로우를 시작합니다...\n');
result = await featureDevelopmentWorkflow(description, { cwd: PROJECT_ROOT });
} else if (trimmedInput.startsWith('/bugfix ')) {
const description = trimmedInput.substring(8);
console.log('\n🔧 버그 수정 워크플로우를 시작합니다...\n');
result = await bugfixWorkflow(description, { cwd: PROJECT_ROOT });
} else if (trimmedInput.startsWith('/review ')) {
const prId = trimmedInput.substring(8);
console.log('\n🔍 PR 검수 워크플로우를 시작합니다...\n');
result = await prReviewWorkflow(prId, { cwd: PROJECT_ROOT });
} else {
// 자유 형식 요청
console.log('\n🤔 요청을 처리하고 있습니다...\n');
result = await coordinator.orchestrate(trimmedInput);
}
// 결과 출력
printResult(result);
} catch (error: any) {
console.error(`\n❌ 오류: ${error.message}`);
}
promptUser();
});
};
promptUser();
}
/**
* 단일 명령어 모드
*/
async function runSingleMode(
prompt: string,
workflow?: WorkflowType
): Promise<void> {
console.log(`\n🤖 그누보드7 Multi-Agent System\n`);
let result: WorkflowResult;
try {
if (workflow === 'feature') {
console.log('🚀 기능 개발 워크플로우 실행\n');
result = await featureDevelopmentWorkflow(prompt, { cwd: PROJECT_ROOT });
} else if (workflow === 'bugfix') {
console.log('🔧 버그 수정 워크플로우 실행\n');
result = await bugfixWorkflow(prompt, { cwd: PROJECT_ROOT });
} else if (workflow === 'pr-review') {
console.log('🔍 PR 검수 워크플로우 실행\n');
result = await prReviewWorkflow(prompt, { cwd: PROJECT_ROOT });
} else {
console.log('🤔 요청 처리 중...\n');
const coordinator = new Coordinator({ cwd: PROJECT_ROOT });
result = await coordinator.orchestrate(prompt);
}
printResult(result);
// 종료 코드 설정
process.exit(result.success ? 0 : 1);
} catch (error: any) {
console.error(`\n❌ 오류: ${error.message}`);
process.exit(1);
}
}
/**
* 결과 출력
*/
function printResult(result: WorkflowResult): void {
console.log('\n' + '='.repeat(60));
if (result.success) {
console.log('✅ 작업 완료');
} else {
console.log('❌ 작업 실패');
}
if (result.output) {
console.log('\n📝 결과:');
console.log(result.output);
}
if (result.errors && result.errors.length > 0) {
console.log('\n⚠️ 오류:');
result.errors.forEach(e => console.log(` - ${e}`));
}
if (result.steps.length > 0) {
console.log('\n📊 실행 단계:');
result.steps.forEach(step => {
const icon = step.status === 'completed' ? '✓' : step.status === 'failed' ? '✗' : '○';
console.log(` ${icon} [${step.agent}] ${step.task}`);
});
}
console.log(`\n💰 비용: $${result.totalCost.toFixed(4)}`);
console.log('='.repeat(60));
}
/**
* 도움말 출력
*/
function showHelp(): void {
console.log(`
📖 그누보드7 Multi-Agent System 도움말
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔧 워크플로우 명령어:
/feature <설명>
새로운 기능을 개발합니다.
예: /feature 상품 할인 기능 추가
/bugfix <설명>
버그를 수정합니다. TDD 방식으로 진행됩니다.
예: /bugfix Form 저장 시 데이터가 사라지는 문제
/review <PR번호 또는 설명>
PR을 검수합니다.
예: /review #123
예: /review 현재 브랜치 변경사항
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🤖 에이전트:
• backend - 백엔드 개발 (Service, Repository, Controller)
• frontend - 프론트엔드 개발 (TSX 컴포넌트)
• layout - 레이아웃 개발 (JSON 스키마)
• template - 템플릿 개발 (빌드, 등록)
• reviewer - 코드 검수 (규정, 테스트)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📚 자유 형식 요청:
워크플로우 명령어 외에도 자유롭게 요청할 수 있습니다.
코디네이터가 적절한 에이전트에게 작업을 분배합니다.
예:
- "ProductService의 할인 로직을 설명해줘"
- "사용자 목록 페이지의 레이아웃 JSON을 검토해줘"
- "DataGrid 컴포넌트에 정렬 기능을 추가해줘"
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⌨️ 기타 명령어:
/help - 이 도움말 표시
/exit - 종료
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
`);
}
export default runCli;
@@ -0,0 +1,246 @@
/**
* 코디네이터
* 작업 분배 및 에이전트 오케스트레이션 담당
*/
import { query, type Options, type SDKMessage } from '@anthropic-ai/claude-agent-sdk';
import { COORDINATOR_PROMPT } from '../prompts/index.js';
import { agentDefinitions } from '../agents/index.js';
import { createG7McpServer } from '../mcp/g7-tools-server.js';
import { logger } from '../utils/logger.js';
import type { CoordinatorConfig, WorkflowResult, WorkflowStep } from '../types/index.js';
export class Coordinator {
private cwd: string;
private model: 'opus' | 'sonnet';
private mcpServer: ReturnType<typeof createG7McpServer>;
constructor(config: CoordinatorConfig = {}) {
this.cwd = config.cwd || process.env.G7_PROJECT_ROOT || '.';
this.model = config.model || 'sonnet';
this.mcpServer = createG7McpServer(this.cwd);
logger.info(`Coordinator initialized with cwd: ${this.cwd}`);
}
/**
* 사용자 요청을 분석하고 적절한 에이전트에게 작업 분배
*/
async orchestrate(userRequest: string): Promise<WorkflowResult> {
logger.info('Starting orchestration');
logger.debug(`User request: ${userRequest}`);
const result: WorkflowResult = {
success: false,
steps: [],
totalCost: 0,
};
const options: Options = {
cwd: this.cwd,
model: this.model,
systemPrompt: COORDINATOR_PROMPT,
tools: { type: 'preset', preset: 'claude_code' },
allowedTools: [
'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash', 'Task',
// MCP 도구
'validate-code', 'validate-frontend', 'run-tests',
'run-test-file', 'search-docs', 'read-doc', 'list-docs',
],
agents: agentDefinitions,
mcpServers: {
'g7-tools': this.mcpServer,
},
settingSources: ['project'], // AGENTS.md 로드
permissionMode: 'acceptEdits',
maxTurns: 50,
hooks: this.getHooks(result),
};
try {
const queryResult = query({
prompt: userRequest,
options,
});
for await (const message of queryResult) {
this.processMessage(message, result);
}
// 최종 결과 처리
const finalResult = result.steps.find(s => s.status === 'completed' && s.agent === 'coordinator');
if (finalResult?.result) {
result.output = finalResult.result.output;
}
result.success = result.steps.every(s => s.status === 'completed');
} catch (error: any) {
logger.error(`Orchestration failed: ${error.message}`);
result.success = false;
result.errors = [error.message];
}
return result;
}
/**
* 특정 에이전트에게 직접 작업 요청
*/
async delegateToAgent(
agentType: keyof typeof agentDefinitions,
task: string
): Promise<WorkflowResult> {
logger.info(`Delegating to ${agentType}: ${task}`);
const agent = agentDefinitions[agentType];
if (!agent) {
return {
success: false,
steps: [],
totalCost: 0,
errors: [`Unknown agent: ${agentType}`],
};
}
const result: WorkflowResult = {
success: false,
steps: [],
totalCost: 0,
};
const options: Options = {
cwd: this.cwd,
model: agent.model || 'sonnet',
systemPrompt: agent.prompt,
tools: { type: 'preset', preset: 'claude_code' },
allowedTools: [
...(agent.tools || []),
'validate-code', 'validate-frontend', 'run-tests',
'search-docs', 'read-doc',
],
mcpServers: {
'g7-tools': this.mcpServer,
},
settingSources: ['project'],
permissionMode: 'acceptEdits',
maxTurns: 30,
hooks: this.getHooks(result),
};
try {
const queryResult = query({
prompt: task,
options,
});
for await (const message of queryResult) {
this.processMessage(message, result);
}
result.success = !result.errors?.length;
} catch (error: any) {
logger.error(`Agent ${agentType} failed: ${error.message}`);
result.success = false;
result.errors = [error.message];
}
return result;
}
/**
* 훅 설정
*/
private getHooks(result: WorkflowResult): Options['hooks'] {
return {
SubagentStart: [{
hooks: [async (input) => {
// SubagentStartHookInput 타입 처리
if (input.hook_event_name === 'SubagentStart') {
const step: WorkflowStep = {
agent: input.agent_type as any,
task: 'Subagent task',
status: 'running',
};
result.steps.push(step);
logger.info(`Subagent started: ${input.agent_type}`);
}
return { continue: true };
}],
}],
SubagentStop: [{
hooks: [async () => {
const runningStep = result.steps.find(s => s.status === 'running');
if (runningStep) {
runningStep.status = 'completed';
}
logger.info('Subagent completed');
return { continue: true };
}],
}],
PreToolUse: [{
hooks: [async (input) => {
// PreToolUseHookInput 타입 처리
if (input.hook_event_name === 'PreToolUse') {
logger.debug(`Tool use: ${input.tool_name}`);
}
return { continue: true };
}],
}],
PostToolUse: [{
hooks: [async (input) => {
// PostToolUseHookInput 타입 처리
if (input.hook_event_name === 'PostToolUse') {
// 테스트 실패 시 로깅
if (input.tool_name === 'run-tests') {
const output = (input.tool_response as any)?.content?.[0]?.text || '';
if (output.includes('failed')) {
logger.warn('Some tests failed');
}
}
}
return { continue: true };
}],
}],
};
}
/**
* 메시지 처리
*/
private processMessage(message: SDKMessage, result: WorkflowResult): void {
if (message.type === 'result') {
if (message.subtype === 'success') {
result.totalCost = message.total_cost_usd || 0;
result.output = message.result;
// 코디네이터 결과 기록
result.steps.push({
agent: 'coordinator' as any,
task: 'Orchestration',
status: 'completed',
result: {
success: true,
agent: 'coordinator',
task: 'Orchestration',
output: message.result,
cost: message.total_cost_usd,
},
});
} else if (
message.subtype === 'error_during_execution' ||
message.subtype === 'error_max_turns' ||
message.subtype === 'error_max_budget_usd' ||
message.subtype === 'error_max_structured_output_retries'
) {
result.errors = message.errors || ['Unknown error'];
}
}
}
}
+85
View File
@@ -0,0 +1,85 @@
/**
* 그누보드7 Multi-Agent System
* AI Agent SDK 기반 멀티에이전트 협업 시스템
*/
import 'dotenv/config';
import { runCli } from './cli.js';
import type { CliOptions, WorkflowType } from './types/index.js';
async function main(): Promise<void> {
const args = process.argv.slice(2);
// 인수 파싱
const options = parseArgs(args);
// CLI 실행
await runCli(options);
}
/**
* 명령줄 인수 파싱
*/
function parseArgs(args: string[]): CliOptions {
// 기본값
const options: CliOptions = {
mode: 'interactive',
};
if (args.length === 0) {
return options;
}
const mode = args[0];
// 모드 확인
if (mode === 'interactive') {
options.mode = 'interactive';
return options;
}
if (mode === 'single') {
options.mode = 'single';
// 워크플로우 옵션 확인
const workflowIndex = args.indexOf('--workflow');
if (workflowIndex !== -1 && args[workflowIndex + 1]) {
options.workflow = args[workflowIndex + 1] as WorkflowType;
// 워크플로우 옵션 제거
args.splice(workflowIndex, 2);
}
// 나머지를 프롬프트로 사용
options.prompt = args.slice(1).join(' ');
return options;
}
// 단축 워크플로우 명령어
if (mode === 'feature' || mode === 'bugfix' || mode === 'pr-review') {
options.mode = 'single';
options.workflow = mode as WorkflowType;
options.prompt = args.slice(1).join(' ');
return options;
}
// 기본: 단일 모드로 전체 인수를 프롬프트로 사용
options.mode = 'single';
options.prompt = args.join(' ');
return options;
}
// 에러 핸들링
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
process.exit(1);
});
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
process.exit(1);
});
// 실행
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});
+700
View File
@@ -0,0 +1,700 @@
#!/usr/bin/env node
/**
* 인터랙티브 CLI - 단계별 승인 기능
* 각 에이전트 실행 전 사용자 확인을 받고 진행
*/
import 'dotenv/config';
import * as readline from 'readline';
import Anthropic from '@anthropic-ai/sdk';
import { agentDefinitions } from './agents/definitions.js';
import type { WorkflowResult, WorkflowStep, AgentType, AgentResult } from './types/index.js';
const PROJECT_ROOT = process.env.G7_PROJECT_ROOT || '.';
// 색상 코드
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m',
bgBlue: '\x1b[44m',
bgGreen: '\x1b[42m',
bgYellow: '\x1b[43m',
bgRed: '\x1b[41m',
};
// 에이전트별 색상
const agentColors: Record<string, string> = {
backend: colors.blue,
frontend: colors.magenta,
layout: colors.cyan,
template: colors.yellow,
reviewer: colors.green,
coordinator: colors.white,
};
/**
* 인터랙티브 세션 클래스
*/
class InteractiveSession {
private rl: readline.Interface;
private client: Anthropic;
private result: WorkflowResult;
private currentStep: number = 0;
constructor() {
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
this.client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
this.result = {
success: false,
steps: [],
totalCost: 0,
};
}
/**
* 세션 시작
*/
async start(): Promise<void> {
this.printBanner();
this.promptUser();
}
/**
* 배너 출력
*/
private printBanner(): void {
console.log(`
${colors.bgBlue}${colors.bright} ${colors.reset}
${colors.bgBlue}${colors.bright} 그누보드7 Multi-Agent Interactive System v1.0.0 ${colors.reset}
${colors.bgBlue}${colors.bright} ${colors.reset}
${colors.cyan}사용 가능한 명령어:${colors.reset}
${colors.yellow}/feature${colors.reset} <설명> - 기능 개발 (단계별 승인)
${colors.yellow}/bugfix${colors.reset} <설명> - 버그 수정 (단계별 승인)
${colors.yellow}/quick${colors.reset} <요청> - 빠른 실행 (승인 없이)
${colors.yellow}/agents${colors.reset} - 에이전트 목록
${colors.yellow}/help${colors.reset} - 도움말
${colors.yellow}/exit${colors.reset} - 종료
${colors.dim}또는 자유롭게 요청을 입력하세요. (단계별 승인 모드)${colors.reset}
`);
}
/**
* 사용자 입력 대기
*/
private promptUser(): void {
this.rl.question(`\n${colors.green}🤖 >${colors.reset} `, async (input) => {
const trimmedInput = input.trim();
if (!trimmedInput) {
this.promptUser();
return;
}
await this.handleInput(trimmedInput);
});
}
/**
* 입력 처리
*/
private async handleInput(input: string): Promise<void> {
// 종료
if (input === '/exit' || input === 'exit') {
console.log(`\n${colors.cyan}👋 안녕히 가세요!${colors.reset}`);
this.rl.close();
return;
}
// 도움말
if (input === '/help') {
this.showHelp();
this.promptUser();
return;
}
// 에이전트 목록
if (input === '/agents') {
this.showAgents();
this.promptUser();
return;
}
// 기능 개발
if (input.startsWith('/feature ')) {
const description = input.substring(9);
await this.runFeatureWorkflow(description);
this.promptUser();
return;
}
// 버그 수정
if (input.startsWith('/bugfix ')) {
const description = input.substring(8);
await this.runBugfixWorkflow(description);
this.promptUser();
return;
}
// 빠른 실행 (승인 없이)
if (input.startsWith('/quick ')) {
const prompt = input.substring(7);
await this.runQuickMode(prompt);
this.promptUser();
return;
}
// 자유 형식 (단계별 승인)
await this.runWithApproval(input);
this.promptUser();
}
/**
* 기능 개발 워크플로우 (단계별 승인)
*/
private async runFeatureWorkflow(description: string): Promise<void> {
console.log(`\n${colors.bgGreen}${colors.bright} 기능 개발 워크플로우 ${colors.reset}`);
console.log(`${colors.dim}설명: ${description}${colors.reset}\n`);
this.result = { success: false, steps: [], totalCost: 0 };
// 워크플로우 단계 정의
const workflow: Array<{ agent: AgentType; task: string }> = [
{ agent: 'backend', task: `백엔드 구현: ${description}` },
{ agent: 'layout', task: `레이아웃 JSON 작성: ${description}` },
{ agent: 'frontend', task: `프론트엔드 컴포넌트 개발 (필요시): ${description}` },
{ agent: 'template', task: `템플릿 빌드 및 컴포넌트 등록: ${description}` },
{ agent: 'reviewer', task: `코드 검수: ${description}` },
];
// 워크플로우 개요 표시
this.printWorkflowPlan(workflow);
// 각 단계 실행
for (let i = 0; i < workflow.length; i++) {
const step = workflow[i];
const approved = await this.requestApproval(i + 1, workflow.length, step.agent, step.task);
if (!approved) {
console.log(`\n${colors.yellow}⏭️ ${step.agent} 단계를 건너뜁니다.${colors.reset}`);
this.result.steps.push({
agent: step.agent,
task: step.task,
status: 'skipped',
});
continue;
}
await this.executeAgent(step.agent, step.task);
}
this.printFinalResult();
}
/**
* 버그 수정 워크플로우 (단계별 승인)
*/
private async runBugfixWorkflow(description: string): Promise<void> {
console.log(`\n${colors.bgYellow}${colors.bright} 버그 수정 워크플로우 ${colors.reset}`);
console.log(`${colors.dim}설명: ${description}${colors.reset}\n`);
this.result = { success: false, steps: [], totalCost: 0 };
// 1단계: 분석
console.log(`${colors.cyan}📋 버그 영향 영역을 분석합니다...${colors.reset}\n`);
const analysisPrompt = `
다음 버그 설명을 분석하고, 영향 받는 영역을 판단해주세요:
버그 설명: ${description}
그누보드7 프로젝트의 영역:
- backend: Service, Repository, Controller, FormRequest 등 PHP 코드
- frontend: TSX 컴포넌트, React 코드
- layout: 레이아웃 JSON 파일
- template: 템플릿 설정, 빌드
어떤 영역이 영향 받는지 알려주세요. 답변 형식:
영향 영역: [backend/frontend/layout/template] (쉼표로 구분)
분석 근거: [간단한 설명]
`;
const analysis = await this.callClaude(analysisPrompt);
console.log(`${colors.dim}${analysis}${colors.reset}\n`);
// 영역 추출 (간단한 파싱)
const affectedAreas: AgentType[] = [];
const lowerAnalysis = analysis.toLowerCase();
if (lowerAnalysis.includes('backend')) affectedAreas.push('backend');
if (lowerAnalysis.includes('frontend')) affectedAreas.push('frontend');
if (lowerAnalysis.includes('layout')) affectedAreas.push('layout');
if (lowerAnalysis.includes('template')) affectedAreas.push('template');
if (affectedAreas.length === 0) {
affectedAreas.push('backend'); // 기본값
}
// 워크플로우 구성
const workflow: Array<{ agent: AgentType; task: string }> = [];
// 트러블슈팅 가이드 참조 단계
workflow.push({
agent: 'reviewer',
task: `트러블슈팅 가이드에서 유사 사례 확인: ${description}`,
});
// 영향 받는 영역별 수정
for (const area of affectedAreas) {
workflow.push({
agent: area,
task: `버그 수정 (TDD 방식): ${description}`,
});
}
// 최종 검수
workflow.push({
agent: 'reviewer',
task: `테스트 통과 확인 및 최종 검수: ${description}`,
});
// 워크플로우 개요 표시
this.printWorkflowPlan(workflow);
// 각 단계 실행
for (let i = 0; i < workflow.length; i++) {
const step = workflow[i];
const approved = await this.requestApproval(i + 1, workflow.length, step.agent, step.task);
if (!approved) {
console.log(`\n${colors.yellow}⏭️ ${step.agent} 단계를 건너뜁니다.${colors.reset}`);
this.result.steps.push({
agent: step.agent,
task: step.task,
status: 'skipped',
});
continue;
}
await this.executeAgent(step.agent, step.task);
}
this.printFinalResult();
}
/**
* 단계별 승인 모드로 자유 형식 요청 실행
*/
private async runWithApproval(prompt: string): Promise<void> {
console.log(`\n${colors.bgBlue}${colors.bright} 요청 처리 ${colors.reset}`);
console.log(`${colors.dim}${prompt}${colors.reset}\n`);
this.result = { success: false, steps: [], totalCost: 0 };
// 요청 분석
console.log(`${colors.cyan}📋 요청을 분석하고 워크플로우를 계획합니다...${colors.reset}\n`);
const planPrompt = `
다음 요청을 분석하고 실행 계획을 세워주세요:
요청: ${prompt}
그누보드7 프로젝트의 에이전트:
- backend: 백엔드 개발 (Service, Repository, Controller, FormRequest, Migration)
- frontend: 프론트엔드 개발 (TSX 컴포넌트, 상태 관리)
- layout: 레이아웃 개발 (JSON 스키마, 데이터 바인딩)
- template: 템플릿 개발 (빌드, 컴포넌트 등록)
- reviewer: 코드 검수 (규정 준수, 테스트)
어떤 에이전트가 어떤 순서로 작업해야 하는지 계획해주세요.
답변 형식 (JSON):
{
"steps": [
{ "agent": "backend", "task": "구체적인 작업 내용" },
{ "agent": "layout", "task": "구체적인 작업 내용" }
]
}
`;
const planResponse = await this.callClaude(planPrompt);
// JSON 파싱 시도
let workflow: Array<{ agent: AgentType; task: string }> = [];
try {
const jsonMatch = planResponse.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const plan = JSON.parse(jsonMatch[0]);
workflow = plan.steps || [];
}
} catch {
// 파싱 실패 시 기본 워크플로우
console.log(`${colors.dim}${planResponse}${colors.reset}\n`);
workflow = [{ agent: 'backend', task: prompt }];
}
if (workflow.length === 0) {
workflow = [{ agent: 'backend', task: prompt }];
}
// 워크플로우 개요 표시
this.printWorkflowPlan(workflow);
// 각 단계 실행
for (let i = 0; i < workflow.length; i++) {
const step = workflow[i];
const validAgent = this.validateAgent(step.agent);
const approved = await this.requestApproval(i + 1, workflow.length, validAgent, step.task);
if (!approved) {
console.log(`\n${colors.yellow}⏭️ ${validAgent} 단계를 건너뜁니다.${colors.reset}`);
this.result.steps.push({
agent: validAgent,
task: step.task,
status: 'skipped',
});
continue;
}
await this.executeAgent(validAgent, step.task);
}
this.printFinalResult();
}
/**
* 빠른 모드 (승인 없이)
*/
private async runQuickMode(prompt: string): Promise<void> {
console.log(`\n${colors.bgBlue}${colors.bright} 빠른 실행 ${colors.reset}`);
console.log(`${colors.dim}승인 없이 자동으로 실행됩니다.${colors.reset}\n`);
this.result = { success: false, steps: [], totalCost: 0 };
// 단일 에이전트로 빠른 실행
await this.executeAgent('backend', prompt);
this.printFinalResult();
}
/**
* 워크플로우 계획 출력
*/
private printWorkflowPlan(workflow: Array<{ agent: AgentType; task: string }>): void {
console.log(`${colors.bright}📊 실행 계획:${colors.reset}\n`);
workflow.forEach((step, index) => {
const agentColor = agentColors[step.agent] || colors.white;
console.log(` ${colors.dim}${index + 1}.${colors.reset} ${agentColor}[${step.agent}]${colors.reset} ${step.task}`);
});
console.log('');
}
/**
* 승인 요청
*/
private async requestApproval(
current: number,
total: number,
agent: AgentType,
task: string
): Promise<boolean> {
const agentColor = agentColors[agent] || colors.white;
console.log(`\n${colors.bright}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}`);
console.log(`${colors.bright}단계 ${current}/${total}${colors.reset}`);
console.log(`${colors.bright}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}`);
console.log(`\n${agentColor}🤖 에이전트: ${agent}${colors.reset}`);
console.log(`${colors.dim}📋 작업: ${task}${colors.reset}\n`);
// 에이전트 설명 표시
const agentDef = agentDefinitions[agent];
if (agentDef) {
console.log(`${colors.dim}ℹ️ ${agentDef.description}${colors.reset}\n`);
}
return new Promise((resolve) => {
this.rl.question(
`${colors.yellow}실행하시겠습니까? ${colors.reset}[${colors.green}Y${colors.reset}es/${colors.red}N${colors.reset}o/${colors.cyan}S${colors.reset}kip all] `,
(answer) => {
const lowerAnswer = answer.toLowerCase().trim();
if (lowerAnswer === 'n' || lowerAnswer === 'no') {
resolve(false);
} else if (lowerAnswer === 's' || lowerAnswer === 'skip') {
// Skip all은 모든 후속 단계를 건너뜀
resolve(false);
} else {
resolve(true);
}
}
);
});
}
/**
* 에이전트 실행
*/
private async executeAgent(agent: AgentType, task: string): Promise<void> {
const agentColor = agentColors[agent] || colors.white;
const agentDef = agentDefinitions[agent];
console.log(`\n${agentColor}▶ ${agent} 에이전트 실행 중...${colors.reset}\n`);
const step: WorkflowStep = {
agent,
task,
status: 'running',
};
this.result.steps.push(step);
try {
// 에이전트 시스템 프롬프트 + 작업
const systemPrompt = agentDef?.prompt || '';
const fullPrompt = `
${systemPrompt}
## 현재 작업
${task}
## 프로젝트 경로
${PROJECT_ROOT}
## 지시사항
1. 위 작업을 수행하세요.
2. 필요한 파일을 읽고 수정하세요.
3. 작업 완료 후 결과를 요약해주세요.
`;
const response = await this.callClaude(fullPrompt);
step.status = 'completed';
step.result = {
success: true,
agent: agent,
task: task,
output: response,
};
// 결과 출력 (요약)
console.log(`${colors.dim}─────────────────────────────────────────────${colors.reset}`);
const summary = response.length > 500 ? response.substring(0, 500) + '...' : response;
console.log(`${colors.dim}${summary}${colors.reset}`);
console.log(`${colors.dim}─────────────────────────────────────────────${colors.reset}`);
console.log(`\n${colors.green}✅ ${agent} 완료${colors.reset}`);
} catch (error: any) {
step.status = 'failed';
step.result = {
success: false,
agent: agent,
task: task,
output: '',
errors: [error.message],
};
console.log(`\n${colors.red}❌ ${agent} 실패: ${error.message}${colors.reset}`);
this.result.errors = this.result.errors || [];
this.result.errors.push(`[${agent}] ${error.message}`);
}
}
/**
* AI API 호출
*/
private async callClaude(prompt: string): Promise<string> {
const response = await this.client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 4096,
messages: [
{ role: 'user', content: prompt },
],
});
// 비용 계산 (대략적)
const inputTokens = response.usage?.input_tokens || 0;
const outputTokens = response.usage?.output_tokens || 0;
const cost = (inputTokens * 0.003 + outputTokens * 0.015) / 1000;
this.result.totalCost += cost;
const textContent = response.content.find((c: { type: string }) => c.type === 'text') as { type: 'text'; text: string } | undefined;
return textContent?.text || '';
}
/**
* 에이전트 타입 검증
*/
private validateAgent(agent: string): AgentType {
const validAgents: AgentType[] = ['backend', 'frontend', 'layout', 'template', 'reviewer'];
if (validAgents.includes(agent as AgentType)) {
return agent as AgentType;
}
return 'backend'; // 기본값
}
/**
* 최종 결과 출력
*/
private printFinalResult(): void {
const completedSteps = this.result.steps.filter(s => s.status === 'completed').length;
const totalSteps = this.result.steps.length;
this.result.success = completedSteps > 0 && !this.result.errors?.length;
console.log(`\n${colors.bright}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}`);
console.log(`${colors.bright} 최종 결과 ${colors.reset}`);
console.log(`${colors.bright}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}\n`);
if (this.result.success) {
console.log(`${colors.green}✅ 작업 완료${colors.reset}\n`);
} else {
console.log(`${colors.red}❌ 작업 실패${colors.reset}\n`);
}
// 단계별 결과
console.log(`${colors.bright}📊 실행 단계 (${completedSteps}/${totalSteps}):${colors.reset}\n`);
this.result.steps.forEach((step, index) => {
const agentColor = agentColors[step.agent] || colors.white;
let statusIcon: string;
let statusColor: string;
switch (step.status) {
case 'completed':
statusIcon = '✅';
statusColor = colors.green;
break;
case 'failed':
statusIcon = '❌';
statusColor = colors.red;
break;
case 'skipped':
statusIcon = '⏭️';
statusColor = colors.yellow;
break;
default:
statusIcon = '⏳';
statusColor = colors.dim;
}
console.log(` ${statusIcon} ${agentColor}[${step.agent}]${colors.reset} ${statusColor}${step.task}${colors.reset}`);
});
// 오류
if (this.result.errors?.length) {
console.log(`\n${colors.red}⚠️ 오류:${colors.reset}`);
this.result.errors.forEach(e => {
console.log(` ${colors.red}- ${e}${colors.reset}`);
});
}
// 비용
console.log(`\n${colors.cyan}💰 총 비용: $${this.result.totalCost.toFixed(4)}${colors.reset}`);
console.log(`${colors.bright}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}`);
}
/**
* 에이전트 목록 표시
*/
private showAgents(): void {
console.log(`\n${colors.bright}🤖 사용 가능한 에이전트:${colors.reset}\n`);
Object.entries(agentDefinitions).forEach(([name, def]) => {
const agentColor = agentColors[name] || colors.white;
console.log(` ${agentColor}${name}${colors.reset}`);
console.log(` ${colors.dim}${def.description}${colors.reset}`);
console.log(` ${colors.dim}도구: ${(def.tools || []).join(', ')}${colors.reset}`);
console.log('');
});
}
/**
* 도움말 표시
*/
private showHelp(): void {
console.log(`
${colors.bright}📖 그누보드7 Multi-Agent Interactive System 도움말${colors.reset}
${colors.cyan}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}
${colors.bright}🔧 워크플로우 명령어 (단계별 승인):${colors.reset}
${colors.yellow}/feature${colors.reset} <설명>
새로운 기능을 개발합니다.
각 단계 실행 전 승인을 요청합니다.
${colors.dim}예: /feature 상품 할인 기능 추가${colors.reset}
${colors.yellow}/bugfix${colors.reset} <설명>
버그를 수정합니다. 영향 영역을 분석하고 TDD 방식으로 진행합니다.
${colors.dim}예: /bugfix Form 저장 시 데이터가 사라지는 문제${colors.reset}
${colors.cyan}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}
${colors.bright}⚡ 빠른 실행:${colors.reset}
${colors.yellow}/quick${colors.reset} <요청>
승인 없이 빠르게 실행합니다.
${colors.dim}예: /quick package.json 파일 분석해줘${colors.reset}
${colors.cyan}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}
${colors.bright}📚 자유 형식 요청:${colors.reset}
명령어 없이 자유롭게 입력하면 요청을 분석하여
워크플로우를 자동으로 구성하고 단계별 승인을 받습니다.
${colors.dim}예: "ProductService의 할인 로직을 구현해줘"${colors.reset}
${colors.cyan}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}
${colors.bright}⌨️ 승인 옵션:${colors.reset}
${colors.green}Y${colors.reset}/yes - 실행
${colors.red}N${colors.reset}/no - 건너뛰기
${colors.cyan}S${colors.reset}/skip - 이후 모든 단계 건너뛰기
${colors.cyan}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}
${colors.bright}⌨️ 기타 명령어:${colors.reset}
${colors.yellow}/agents${colors.reset} - 에이전트 목록
${colors.yellow}/help${colors.reset} - 이 도움말
${colors.yellow}/exit${colors.reset} - 종료
${colors.cyan}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}
`);
}
}
// 메인 실행
async function main() {
// API 키 확인
if (!process.env.ANTHROPIC_API_KEY) {
console.error(`${colors.red}❌ ANTHROPIC_API_KEY가 설정되지 않았습니다.${colors.reset}`);
console.error(`${colors.dim}.env 파일에 API 키를 설정해주세요.${colors.reset}`);
process.exit(1);
}
const session = new InteractiveSession();
await session.start();
}
main().catch((error) => {
console.error(`${colors.red}❌ 오류: ${error.message}${colors.reset}`);
process.exit(1);
});
@@ -0,0 +1,332 @@
/**
* G7 에이전트 MCP 서버
* AI 코딩 도구에서 멀티에이전트 시스템을 호출할 수 있는 MCP 서버
*/
import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
import { z } from 'zod';
import { Coordinator } from '../coordinator/Coordinator.js';
import { featureDevelopmentWorkflow, simpleFeatureWorkflow } from '../workflows/feature.js';
import { bugfixWorkflow, stateRelatedBugfix } from '../workflows/bugfix.js';
import { prReviewWorkflow } from '../workflows/pr-review.js';
import { createWorkflowLogger } from '../utils/logger.js';
const logger = createWorkflowLogger('mcp-agents');
/**
* G7 에이전트 MCP 서버 생성
* AI 코딩 도구 대화창에서 멀티에이전트 협업 시스템을 호출할 수 있음
*/
export function createG7AgentsMcpServer(projectRoot: string) {
return createSdkMcpServer({
name: 'g7-agents',
version: '1.0.0',
tools: [
// 자동 분배 (Coordinator)
tool(
'orchestrate',
'사용자 요청을 분석하여 적절한 에이전트(backend, frontend, layout, template, reviewer)에 자동 분배합니다. 복합 작업은 여러 에이전트가 순차적으로 협업합니다.',
{
prompt: z.string().describe('사용자 요청 내용'),
},
async ({ prompt }) => {
logger.info(`Orchestrating: ${prompt}`);
try {
const coordinator = new Coordinator({ cwd: projectRoot, model: 'sonnet' });
const result = await coordinator.orchestrate(prompt);
return {
content: [{
type: 'text',
text: formatWorkflowResult(result),
}],
isError: !result.success,
};
} catch (error: any) {
logger.error(`Orchestration failed: ${error.message}`);
return {
content: [{
type: 'text',
text: `❌ 오케스트레이션 실패: ${error.message}`,
}],
isError: true,
};
}
}
),
// 기능 개발 워크플로우
tool(
'feature-workflow',
'기능 개발 워크플로우를 실행합니다. Backend → Layout → Frontend → Template → Reviewer 순서로 에이전트가 협업합니다.',
{
description: z.string().describe('개발할 기능 설명'),
skipReview: z.boolean().optional().describe('리뷰 단계 생략 여부 (기본: false)'),
},
async ({ description, skipReview }) => {
logger.info(`Feature workflow: ${description}`);
try {
const result = await featureDevelopmentWorkflow(description, {
cwd: projectRoot,
skipReview: skipReview ?? false,
});
return {
content: [{
type: 'text',
text: formatWorkflowResult(result),
}],
isError: !result.success,
};
} catch (error: any) {
logger.error(`Feature workflow failed: ${error.message}`);
return {
content: [{
type: 'text',
text: `❌ 기능 개발 워크플로우 실패: ${error.message}`,
}],
isError: true,
};
}
}
),
// 간단한 기능 개발 (단일 영역)
tool(
'simple-feature',
'단일 영역의 간단한 기능을 개발합니다. 복합 워크플로우 없이 해당 에이전트만 호출합니다.',
{
description: z.string().describe('개발할 기능 설명'),
area: z.enum(['backend', 'frontend', 'layout', 'template'])
.describe('기능이 속한 영역'),
},
async ({ description, area }) => {
logger.info(`Simple feature (${area}): ${description}`);
try {
const result = await simpleFeatureWorkflow(description, {
cwd: projectRoot,
area,
});
return {
content: [{
type: 'text',
text: formatWorkflowResult(result),
}],
isError: !result.success,
};
} catch (error: any) {
logger.error(`Simple feature failed: ${error.message}`);
return {
content: [{
type: 'text',
text: `❌ 간단한 기능 개발 실패: ${error.message}`,
}],
isError: true,
};
}
}
),
// 버그 수정 워크플로우
tool(
'bugfix-workflow',
'버그 수정 워크플로우를 실행합니다. 트러블슈팅 가이드를 참조하고 TDD 방식으로 수정합니다.',
{
description: z.string().describe('버그 설명 (증상, 재현 방법 등)'),
affectedAreas: z.array(z.enum(['backend', 'frontend', 'layout', 'template', 'unknown']))
.optional()
.describe('영향 받는 영역 (지정하지 않으면 자동 분석)'),
},
async ({ description, affectedAreas }) => {
logger.info(`Bugfix workflow: ${description}`);
try {
const result = await bugfixWorkflow(description, {
cwd: projectRoot,
affectedAreas: affectedAreas as any,
});
return {
content: [{
type: 'text',
text: formatWorkflowResult(result),
}],
isError: !result.success,
};
} catch (error: any) {
logger.error(`Bugfix workflow failed: ${error.message}`);
return {
content: [{
type: 'text',
text: `❌ 버그 수정 워크플로우 실패: ${error.message}`,
}],
isError: true,
};
}
}
),
// 상태 관련 버그 수정 (특화)
tool(
'state-bugfix',
'상태 관리 관련 버그를 수정합니다. Stale Closure, setState 병합, 타이밍 이슈 등에 특화되어 있습니다.',
{
description: z.string().describe('상태 관련 버그 설명'),
},
async ({ description }) => {
logger.info(`State-related bugfix: ${description}`);
try {
const result = await stateRelatedBugfix(description, {
cwd: projectRoot,
});
return {
content: [{
type: 'text',
text: formatWorkflowResult(result),
}],
isError: !result.success,
};
} catch (error: any) {
logger.error(`State bugfix failed: ${error.message}`);
return {
content: [{
type: 'text',
text: `❌ 상태 버그 수정 실패: ${error.message}`,
}],
isError: true,
};
}
}
),
// PR 검수 워크플로우
tool(
'pr-review',
'PR을 검수합니다. 변경된 파일 유형에 따라 적절한 에이전트가 검수합니다.',
{
prIdentifier: z.string().describe('PR 번호 또는 브랜치명'),
},
async ({ prIdentifier }) => {
logger.info(`PR review: ${prIdentifier}`);
try {
const result = await prReviewWorkflow(prIdentifier, {
cwd: projectRoot,
});
return {
content: [{
type: 'text',
text: formatWorkflowResult(result),
}],
isError: !result.success,
};
} catch (error: any) {
logger.error(`PR review failed: ${error.message}`);
return {
content: [{
type: 'text',
text: `❌ PR 검수 실패: ${error.message}`,
}],
isError: true,
};
}
}
),
// 특정 에이전트 직접 호출
tool(
'delegate',
'특정 에이전트에 직접 작업을 위임합니다. 단일 영역 작업에 적합합니다.',
{
agent: z.enum(['backend', 'frontend', 'layout', 'template', 'reviewer'])
.describe('호출할 에이전트'),
task: z.string().describe('수행할 작업 내용'),
},
async ({ agent, task }) => {
logger.info(`Delegating to ${agent}: ${task}`);
try {
const coordinator = new Coordinator({ cwd: projectRoot, model: 'sonnet' });
const result = await coordinator.delegateToAgent(agent, task);
return {
content: [{
type: 'text',
text: formatWorkflowResult(result),
}],
isError: !result.success,
};
} catch (error: any) {
logger.error(`Delegation failed: ${error.message}`);
return {
content: [{
type: 'text',
text: `❌ 에이전트 호출 실패: ${error.message}`,
}],
isError: true,
};
}
}
),
],
});
}
/**
* 워크플로우 결과 포맷팅
*/
function formatWorkflowResult(result: any): string {
const lines: string[] = [];
// 성공/실패 헤더
if (result.success) {
lines.push('## ✅ 작업 완료\n');
} else {
lines.push('## ❌ 작업 실패\n');
}
// 실행된 단계들
if (result.steps && result.steps.length > 0) {
lines.push('### 실행 단계');
for (const step of result.steps) {
const statusIcon = step.status === 'completed' ? '✅' :
step.status === 'failed' ? '❌' :
step.status === 'running' ? '🔄' : '⏳';
lines.push(`${statusIcon} [${step.agent}] ${step.task}`);
if (step.result?.filesModified && step.result.filesModified.length > 0) {
lines.push(` 수정된 파일: ${step.result.filesModified.join(', ')}`);
}
}
lines.push('');
}
// 출력 내용
if (result.output) {
lines.push('### 결과');
lines.push(result.output);
lines.push('');
}
// 에러 메시지
if (result.errors && result.errors.length > 0) {
lines.push('### 오류');
for (const error of result.errors) {
lines.push(`- ${error}`);
}
lines.push('');
}
// 비용 정보
if (result.totalCost && result.totalCost > 0) {
lines.push(`### 비용: $${result.totalCost.toFixed(4)}`);
}
return lines.join('\n');
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,234 @@
/**
* G7 MCP 도구 서버
* AI Agent SDK와 통합되는 커스텀 MCP 서버
*/
import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
import { z } from 'zod';
import { validateBackendCode } from './tools/validate-code.js';
import { validateFrontendCode } from './tools/validate-frontend.js';
import { runTests, runTestFile } from './tools/run-tests.js';
import { searchDocs, readDoc, listDocs } from './tools/search-docs.js';
/**
* G7 프로젝트 전용 MCP 서버 생성
*/
export function createG7McpServer(projectRoot: string) {
return createSdkMcpServer({
name: 'g7-tools',
version: '1.0.0',
tools: [
// 백엔드 코드 검증
tool(
'validate-code',
'Service, FormRequest, Repository, Listener, Controller 파일의 G7 규정 준수 여부를 검증합니다',
{
filePath: z.string().describe('검증할 파일 경로 (프로젝트 루트 기준 상대 경로)'),
},
async ({ filePath }) => {
const result = validateBackendCode(projectRoot, filePath);
return {
content: [{
type: 'text',
text: formatValidationResult(result),
}],
};
}
),
// 프론트엔드/레이아웃 검증
tool(
'validate-frontend',
'레이아웃 JSON 또는 TSX 컴포넌트의 G7 규정 준수 여부를 검증합니다',
{
filePath: z.string().describe('검증할 파일 경로 (프로젝트 루트 기준 상대 경로)'),
},
async ({ filePath }) => {
const result = validateFrontendCode(projectRoot, filePath);
return {
content: [{
type: 'text',
text: formatValidationResult(result),
}],
};
}
),
// 테스트 실행
tool(
'run-tests',
'백엔드(PHPUnit) 또는 프론트엔드(Vitest) 테스트를 실행합니다',
{
type: z.enum(['backend', 'frontend', 'all']).describe('테스트 타입'),
filter: z.string().optional().describe('테스트 필터 (클래스명 또는 테스트 이름)'),
template: z.string().optional().describe('프론트엔드 테스트 시 템플릿 이름'),
},
async ({ type, filter, template }) => {
const result = runTests(projectRoot, { type, filter, template });
return {
content: [{
type: 'text',
text: result.success
? `✅ ${result.message}\n\n${result.data}`
: `❌ ${result.message}\n\n${result.data}`,
}],
isError: !result.success,
};
}
),
// 특정 테스트 파일 실행
tool(
'run-test-file',
'특정 테스트 파일을 실행합니다',
{
testFilePath: z.string().describe('테스트 파일 경로'),
},
async ({ testFilePath }) => {
const result = runTestFile(projectRoot, testFilePath);
return {
content: [{
type: 'text',
text: result.success
? `✅ ${result.message}\n\n${result.data}`
: `❌ ${result.message}\n\n${result.data}`,
}],
isError: !result.success,
};
}
),
// 규정 문서 검색
tool(
'search-docs',
'G7 규정 문서(docs/)에서 관련 정보를 검색합니다',
{
query: z.string().describe('검색 키워드'),
category: z.enum(['backend', 'frontend', 'extension', 'database', 'testing', 'all'])
.optional()
.describe('검색할 카테고리'),
maxResults: z.number().optional().describe('최대 결과 수 (기본: 5)'),
},
async ({ query, category, maxResults }) => {
const result = searchDocs(projectRoot, { query, category, maxResults });
if (!result.success || !Array.isArray(result.data) || result.data.length === 0) {
return {
content: [{
type: 'text',
text: '검색 결과가 없습니다',
}],
};
}
const formatted = result.data.map((doc: any) =>
`## ${doc.file}\n**${doc.title}**\n\`\`\`\n${doc.snippet}\n\`\`\``
).join('\n\n');
return {
content: [{
type: 'text',
text: `${result.message}\n\n${formatted}`,
}],
};
}
),
// 규정 문서 읽기
tool(
'read-doc',
'특정 G7 규정 문서의 전체 내용을 읽습니다',
{
docPath: z.string().describe('문서 경로 (예: backend/service-repository.md)'),
},
async ({ docPath }) => {
const result = readDoc(projectRoot, docPath);
return {
content: [{
type: 'text',
text: result.success
? result.data as string
: `❌ ${result.message}`,
}],
isError: !result.success,
};
}
),
// 규정 문서 목록
tool(
'list-docs',
'G7 규정 문서 목록을 조회합니다',
{
category: z.enum(['backend', 'frontend', 'extension', 'database', 'testing', 'all'])
.optional()
.describe('조회할 카테고리'),
},
async ({ category }) => {
const result = listDocs(projectRoot, category);
if (!result.success || !Array.isArray(result.data)) {
return {
content: [{
type: 'text',
text: '문서 목록을 조회할 수 없습니다',
}],
};
}
const formatted = result.data.map((doc: any) =>
`- ${doc.path}: ${doc.title}`
).join('\n');
return {
content: [{
type: 'text',
text: `${result.message}\n\n${formatted}`,
}],
};
}
),
],
});
}
/**
* 검증 결과 포맷팅
*/
function formatValidationResult(result: { valid: boolean; issues: any[] }): string {
if (result.valid && result.issues.length === 0) {
return '✅ 검증 통과: G7 규정을 준수합니다.';
}
const errors = result.issues.filter(i => i.severity === 'error');
const warnings = result.issues.filter(i => i.severity === 'warning');
let output = result.valid
? '⚠️ 검증 통과 (경고 있음)\n\n'
: '❌ 검증 실패\n\n';
if (errors.length > 0) {
output += '### 오류\n';
for (const issue of errors) {
output += `- [${issue.rule}] ${issue.file}`;
if (issue.line) output += `:${issue.line}`;
output += `\n ${issue.message}\n`;
}
output += '\n';
}
if (warnings.length > 0) {
output += '### 경고\n';
for (const issue of warnings) {
output += `- [${issue.rule}] ${issue.file}`;
if (issue.line) output += `:${issue.line}`;
output += `\n ${issue.message}\n`;
}
}
return output;
}
+310
View File
@@ -0,0 +1,310 @@
#!/usr/bin/env node
/**
* 그누보드7 에이전트 MCP 서버 진입점
* AI 코딩 도구에서 멀티에이전트 시스템을 호출할 수 있는 MCP 서버
*
* 사용법:
* .mcp.json에 등록하여 AI 코딩 도구에서 자동으로 호출
*
* 환경 변수:
* G7_PROJECT_ROOT: 프로젝트 루트 경로 (기본: .)
* ANTHROPIC_API_KEY: Anthropic API 키 (필수)
* LOG_LEVEL: 로그 레벨 (기본: info)
*/
import 'dotenv/config';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import { Coordinator } from '../coordinator/Coordinator.js';
import { featureDevelopmentWorkflow, simpleFeatureWorkflow } from '../workflows/feature.js';
import { bugfixWorkflow, stateRelatedBugfix } from '../workflows/bugfix.js';
import { prReviewWorkflow } from '../workflows/pr-review.js';
import { logger, createWorkflowLogger } from '../utils/logger.js';
const workflowLogger = createWorkflowLogger('mcp-agents');
// 프로젝트 루트 설정
const projectRoot = process.env.G7_PROJECT_ROOT || '.';
// API 키 확인
if (!process.env.ANTHROPIC_API_KEY) {
logger.warn('ANTHROPIC_API_KEY가 설정되지 않았습니다. 에이전트 호출 시 오류가 발생할 수 있습니다.');
}
// MCP 서버 생성
const server = new McpServer({
name: 'g7-agents',
version: '1.0.0',
});
/**
* 워크플로우 결과 포맷팅
*/
function formatWorkflowResult(result: any): string {
const lines: string[] = [];
if (result.success) {
lines.push('## ✅ 작업 완료\n');
} else {
lines.push('## ❌ 작업 실패\n');
}
if (result.steps && result.steps.length > 0) {
lines.push('### 실행 단계');
for (const step of result.steps) {
const statusIcon = step.status === 'completed' ? '✅' :
step.status === 'failed' ? '❌' :
step.status === 'running' ? '🔄' : '⏳';
lines.push(`${statusIcon} [${step.agent}] ${step.task}`);
if (step.result?.filesModified && step.result.filesModified.length > 0) {
lines.push(` 수정된 파일: ${step.result.filesModified.join(', ')}`);
}
}
lines.push('');
}
if (result.output) {
lines.push('### 결과');
lines.push(result.output);
lines.push('');
}
if (result.errors && result.errors.length > 0) {
lines.push('### 오류');
for (const error of result.errors) {
lines.push(`- ${error}`);
}
lines.push('');
}
if (result.totalCost && result.totalCost > 0) {
lines.push(`### 비용: $${result.totalCost.toFixed(4)}`);
}
return lines.join('\n');
}
// Tool: orchestrate - 자동 분배
server.tool(
'orchestrate',
'사용자 요청을 분석하여 적절한 에이전트(backend, frontend, layout, template, reviewer)에 자동 분배합니다.',
{
prompt: z.string().describe('사용자 요청 내용'),
},
async ({ prompt }) => {
workflowLogger.info(`Orchestrating: ${prompt}`);
try {
const coordinator = new Coordinator({ cwd: projectRoot, model: 'sonnet' });
const result = await coordinator.orchestrate(prompt);
return {
content: [{ type: 'text', text: formatWorkflowResult(result) }],
isError: !result.success,
};
} catch (error: any) {
workflowLogger.error(`Orchestration failed: ${error.message}`);
return {
content: [{ type: 'text', text: `❌ 오케스트레이션 실패: ${error.message}` }],
isError: true,
};
}
}
);
// Tool: feature-workflow - 기능 개발
server.tool(
'feature-workflow',
'기능 개발 워크플로우를 실행합니다. Backend → Layout → Frontend → Template → Reviewer 순서로 에이전트가 협업합니다.',
{
description: z.string().describe('개발할 기능 설명'),
skipReview: z.boolean().optional().describe('리뷰 단계 생략 여부 (기본: false)'),
},
async ({ description, skipReview }) => {
workflowLogger.info(`Feature workflow: ${description}`);
try {
const result = await featureDevelopmentWorkflow(description, {
cwd: projectRoot,
skipReview: skipReview ?? false,
});
return {
content: [{ type: 'text', text: formatWorkflowResult(result) }],
isError: !result.success,
};
} catch (error: any) {
workflowLogger.error(`Feature workflow failed: ${error.message}`);
return {
content: [{ type: 'text', text: `❌ 기능 개발 워크플로우 실패: ${error.message}` }],
isError: true,
};
}
}
);
// Tool: simple-feature - 단일 영역 기능 개발
server.tool(
'simple-feature',
'단일 영역의 간단한 기능을 개발합니다.',
{
description: z.string().describe('개발할 기능 설명'),
area: z.enum(['backend', 'frontend', 'layout', 'template']).describe('기능이 속한 영역'),
},
async ({ description, area }) => {
workflowLogger.info(`Simple feature (${area}): ${description}`);
try {
const result = await simpleFeatureWorkflow(description, {
cwd: projectRoot,
area,
});
return {
content: [{ type: 'text', text: formatWorkflowResult(result) }],
isError: !result.success,
};
} catch (error: any) {
workflowLogger.error(`Simple feature failed: ${error.message}`);
return {
content: [{ type: 'text', text: `❌ 간단한 기능 개발 실패: ${error.message}` }],
isError: true,
};
}
}
);
// Tool: bugfix-workflow - 버그 수정
server.tool(
'bugfix-workflow',
'버그 수정 워크플로우를 실행합니다. 트러블슈팅 가이드를 참조하고 TDD 방식으로 수정합니다.',
{
description: z.string().describe('버그 설명'),
affectedAreas: z.array(z.enum(['backend', 'frontend', 'layout', 'template', 'unknown'])).optional()
.describe('영향 받는 영역 (지정하지 않으면 자동 분석)'),
},
async ({ description, affectedAreas }) => {
workflowLogger.info(`Bugfix workflow: ${description}`);
try {
const result = await bugfixWorkflow(description, {
cwd: projectRoot,
affectedAreas: affectedAreas as any,
});
return {
content: [{ type: 'text', text: formatWorkflowResult(result) }],
isError: !result.success,
};
} catch (error: any) {
workflowLogger.error(`Bugfix workflow failed: ${error.message}`);
return {
content: [{ type: 'text', text: `❌ 버그 수정 워크플로우 실패: ${error.message}` }],
isError: true,
};
}
}
);
// Tool: state-bugfix - 상태 관련 버그 수정
server.tool(
'state-bugfix',
'상태 관리 관련 버그를 수정합니다. Stale Closure, setState 병합, 타이밍 이슈 등에 특화되어 있습니다.',
{
description: z.string().describe('상태 관련 버그 설명'),
},
async ({ description }) => {
workflowLogger.info(`State-related bugfix: ${description}`);
try {
const result = await stateRelatedBugfix(description, {
cwd: projectRoot,
});
return {
content: [{ type: 'text', text: formatWorkflowResult(result) }],
isError: !result.success,
};
} catch (error: any) {
workflowLogger.error(`State bugfix failed: ${error.message}`);
return {
content: [{ type: 'text', text: `❌ 상태 버그 수정 실패: ${error.message}` }],
isError: true,
};
}
}
);
// Tool: pr-review - PR 검수
server.tool(
'pr-review',
'PR을 검수합니다. 변경된 파일 유형에 따라 적절한 에이전트가 검수합니다.',
{
prIdentifier: z.string().describe('PR 번호 또는 브랜치명'),
},
async ({ prIdentifier }) => {
workflowLogger.info(`PR review: ${prIdentifier}`);
try {
const result = await prReviewWorkflow(prIdentifier, {
cwd: projectRoot,
});
return {
content: [{ type: 'text', text: formatWorkflowResult(result) }],
isError: !result.success,
};
} catch (error: any) {
workflowLogger.error(`PR review failed: ${error.message}`);
return {
content: [{ type: 'text', text: `❌ PR 검수 실패: ${error.message}` }],
isError: true,
};
}
}
);
// Tool: delegate - 특정 에이전트 직접 호출
server.tool(
'delegate',
'특정 에이전트에 직접 작업을 위임합니다.',
{
agent: z.enum(['backend', 'frontend', 'layout', 'template', 'reviewer']).describe('호출할 에이전트'),
task: z.string().describe('수행할 작업 내용'),
},
async ({ agent, task }) => {
workflowLogger.info(`Delegating to ${agent}: ${task}`);
try {
const coordinator = new Coordinator({ cwd: projectRoot, model: 'sonnet' });
const result = await coordinator.delegateToAgent(agent, task);
return {
content: [{ type: 'text', text: formatWorkflowResult(result) }],
isError: !result.success,
};
} catch (error: any) {
workflowLogger.error(`Delegation failed: ${error.message}`);
return {
content: [{ type: 'text', text: `❌ 에이전트 호출 실패: ${error.message}` }],
isError: true,
};
}
}
);
// 서버 시작
async function main() {
logger.info(`그누보드7 에이전트 MCP 서버 시작 (프로젝트: ${projectRoot})`);
const transport = new StdioServerTransport();
await server.connect(transport);
logger.info('MCP 서버가 stdio 모드로 실행 중입니다.');
}
main().catch((error) => {
logger.error(`MCP 서버 시작 실패: ${error.message}`);
process.exit(1);
});
@@ -0,0 +1,174 @@
/**
* 테스트 실행 도구
* PHPUnit (백엔드) 및 Vitest (프론트엔드) 테스트 실행
*/
import { execSync } from 'child_process';
import type { ToolResult } from '../../types/index.js';
export type TestType = 'backend' | 'frontend' | 'all';
export interface TestOptions {
type: TestType;
filter?: string;
template?: string;
}
export function runTests(
projectRoot: string,
options: TestOptions
): ToolResult {
const { type, filter, template } = options;
const results: string[] = [];
let success = true;
try {
// 백엔드 테스트
if (type === 'backend' || type === 'all') {
const backendResult = runBackendTests(projectRoot, filter);
results.push('=== Backend Tests ===');
results.push(backendResult.output);
if (!backendResult.success) {
success = false;
}
}
// 프론트엔드 테스트
if (type === 'frontend' || type === 'all') {
const frontendResult = runFrontendTests(projectRoot, filter, template);
results.push('=== Frontend Tests ===');
results.push(frontendResult.output);
if (!frontendResult.success) {
success = false;
}
}
return {
success,
message: success ? '모든 테스트 통과' : '일부 테스트 실패',
data: results.join('\n\n'),
};
} catch (error: any) {
return {
success: false,
message: '테스트 실행 중 오류 발생',
data: error.message,
};
}
}
function runBackendTests(
projectRoot: string,
filter?: string
): { success: boolean; output: string } {
try {
const cmd = filter
? `php artisan test --filter=${filter}`
: 'php artisan test';
const output = execSync(cmd, {
cwd: projectRoot,
encoding: 'utf-8',
timeout: 300000, // 5분 타임아웃
});
// 테스트 결과 파싱
const passMatch = output.match(/Tests:\s*(\d+)\s*passed/);
const failMatch = output.match(/(\d+)\s*failed/);
const passed = passMatch ? parseInt(passMatch[1]) : 0;
const failed = failMatch ? parseInt(failMatch[1]) : 0;
return {
success: failed === 0,
output: `Passed: ${passed}, Failed: ${failed}\n${output}`,
};
} catch (error: any) {
return {
success: false,
output: error.stdout || error.message,
};
}
}
function runFrontendTests(
projectRoot: string,
filter?: string,
template?: string
): { success: boolean; output: string } {
try {
let cwd = projectRoot;
let cmd = 'npm run test:run';
// 템플릿 지정 시 해당 디렉토리에서 실행
if (template) {
cwd = `${projectRoot}/templates/${template}`;
}
if (filter) {
cmd += ` -- ${filter}`;
}
// Windows에서는 PowerShell 래퍼 필수
const fullCmd = `powershell -Command "${cmd}"`;
const output = execSync(fullCmd, {
cwd,
encoding: 'utf-8',
timeout: 300000, // 5분 타임아웃
});
// Vitest 결과 파싱
const passMatch = output.match(/(\d+)\s*passed/);
const failMatch = output.match(/(\d+)\s*failed/);
const passed = passMatch ? parseInt(passMatch[1]) : 0;
const failed = failMatch ? parseInt(failMatch[1]) : 0;
return {
success: failed === 0,
output: `Passed: ${passed}, Failed: ${failed}\n${output}`,
};
} catch (error: any) {
return {
success: false,
output: error.stdout || error.message,
};
}
}
/**
* 특정 테스트 파일 실행
*/
export function runTestFile(
projectRoot: string,
testFilePath: string
): ToolResult {
const isPhp = testFilePath.endsWith('.php');
const isTs = testFilePath.endsWith('.ts') || testFilePath.endsWith('.tsx');
if (isPhp) {
// PHPUnit 테스트
const testClass = testFilePath
.replace(/\//g, '\\')
.replace('.php', '')
.replace('tests\\', 'Tests\\');
return runTests(projectRoot, {
type: 'backend',
filter: testClass,
});
} else if (isTs) {
// Vitest 테스트
const testName = testFilePath.split('/').pop()?.replace(/\.(test|spec)\.(ts|tsx)$/, '');
return runTests(projectRoot, {
type: 'frontend',
filter: testName,
});
}
return {
success: false,
message: '지원하지 않는 테스트 파일 형식입니다',
};
}
@@ -0,0 +1,275 @@
/**
* 규정 문서 검색 도구
* docs 디렉토리에서 규정 문서 검색
*/
import * as fs from 'fs';
import * as path from 'path';
import type { ToolResult } from '../../types/index.js';
export type DocCategory = 'backend' | 'frontend' | 'extension' | 'database' | 'testing' | 'all';
export interface SearchOptions {
query: string;
category?: DocCategory;
maxResults?: number;
}
export interface DocSearchResult {
file: string;
title: string;
snippet: string;
relevance: number;
}
export function searchDocs(
projectRoot: string,
options: SearchOptions
): ToolResult {
const { query, category = 'all', maxResults = 5 } = options;
const docsPath = path.join(projectRoot, 'docs');
const results: DocSearchResult[] = [];
const searchPaths = category === 'all'
? [docsPath]
: [path.join(docsPath, category)];
// 특수 파일 매핑
const specialFiles: Record<string, string> = {
database: path.join(docsPath, 'database-guide.md'),
testing: path.join(docsPath, 'testing-guide.md'),
};
// 카테고리별 특수 파일 추가
if (category !== 'all' && specialFiles[category]) {
searchPaths.push(specialFiles[category]);
}
for (const searchPath of searchPaths) {
if (fs.existsSync(searchPath)) {
if (fs.statSync(searchPath).isDirectory()) {
searchDirectory(searchPath, docsPath, query, results);
} else {
searchFile(searchPath, docsPath, query, results);
}
}
}
// 관련도 순으로 정렬
results.sort((a, b) => b.relevance - a.relevance);
// 결과 제한
const limitedResults = results.slice(0, maxResults);
if (limitedResults.length === 0) {
return {
success: true,
message: '검색 결과가 없습니다',
data: [],
};
}
return {
success: true,
message: `${limitedResults.length}개의 문서를 찾았습니다`,
data: limitedResults,
};
}
function searchDirectory(
dirPath: string,
docsPath: string,
query: string,
results: DocSearchResult[]
): void {
try {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
searchDirectory(fullPath, docsPath, query, results);
} else if (entry.name.endsWith('.md')) {
searchFile(fullPath, docsPath, query, results);
}
}
} catch (error) {
// 디렉토리 접근 오류 무시
}
}
function searchFile(
filePath: string,
docsPath: string,
query: string,
results: DocSearchResult[]
): void {
try {
const content = fs.readFileSync(filePath, 'utf-8');
const relativePath = path.relative(docsPath, filePath);
const lowerContent = content.toLowerCase();
const lowerQuery = query.toLowerCase();
// 쿼리가 포함되어 있는지 확인
if (!lowerContent.includes(lowerQuery)) {
return;
}
// 제목 추출 (첫 번째 # 라인)
const titleMatch = content.match(/^#\s+(.+)$/m);
const title = titleMatch ? titleMatch[1] : relativePath;
// 관련도 계산
let relevance = 0;
// 파일명에 쿼리 포함
if (relativePath.toLowerCase().includes(lowerQuery)) {
relevance += 10;
}
// 제목에 쿼리 포함
if (title.toLowerCase().includes(lowerQuery)) {
relevance += 5;
}
// 쿼리 등장 횟수
const matches = lowerContent.split(lowerQuery).length - 1;
relevance += Math.min(matches, 10);
// TL;DR 섹션에 포함
if (content.includes('TL;DR') && content.split('TL;DR')[1]?.toLowerCase().includes(lowerQuery)) {
relevance += 3;
}
// 스니펫 추출
const snippet = extractSnippet(content, query);
results.push({
file: relativePath,
title,
snippet,
relevance,
});
} catch (error) {
// 파일 읽기 오류 무시
}
}
function extractSnippet(content: string, query: string): string {
const lowerContent = content.toLowerCase();
const lowerQuery = query.toLowerCase();
const index = lowerContent.indexOf(lowerQuery);
if (index === -1) {
// TL;DR 섹션이 있으면 그것을 반환
const tldrMatch = content.match(/## TL;DR[^#]*(```[\s\S]*?```)/);
if (tldrMatch) {
return tldrMatch[1].substring(0, 300) + '...';
}
// 첫 문단 반환
const lines = content.split('\n').filter(l => l.trim() && !l.startsWith('#'));
return lines.slice(0, 3).join('\n').substring(0, 300) + '...';
}
// 쿼리 주변 컨텍스트 추출
const start = Math.max(0, index - 100);
const end = Math.min(content.length, index + query.length + 200);
let snippet = content.substring(start, end);
// 시작/끝 정리
if (start > 0) {
snippet = '...' + snippet.substring(snippet.indexOf(' ') + 1);
}
if (end < content.length) {
snippet = snippet.substring(0, snippet.lastIndexOf(' ')) + '...';
}
return snippet;
}
/**
* 특정 문서 읽기
*/
export function readDoc(
projectRoot: string,
docPath: string
): ToolResult {
const fullPath = path.join(projectRoot, 'docs', docPath);
if (!fs.existsSync(fullPath)) {
return {
success: false,
message: `문서를 찾을 수 없습니다: ${docPath}`,
};
}
try {
const content = fs.readFileSync(fullPath, 'utf-8');
return {
success: true,
message: `문서 로드 완료: ${docPath}`,
data: content,
};
} catch (error: any) {
return {
success: false,
message: `문서 읽기 오류: ${error.message}`,
};
}
}
/**
* 규정 문서 목록 조회
*/
export function listDocs(
projectRoot: string,
category?: DocCategory
): ToolResult {
const docsPath = path.join(projectRoot, 'docs');
const docs: { path: string; title: string }[] = [];
function scanDir(dir: string) {
try {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relativePath = path.relative(docsPath, fullPath);
if (entry.isDirectory()) {
if (!category || relativePath === category) {
scanDir(fullPath);
}
} else if (entry.name.endsWith('.md')) {
// 카테고리 필터링
if (category && category !== 'all') {
if (!relativePath.startsWith(category)) {
continue;
}
}
const content = fs.readFileSync(fullPath, 'utf-8');
const titleMatch = content.match(/^#\s+(.+)$/m);
const title = titleMatch ? titleMatch[1] : entry.name;
docs.push({
path: relativePath,
title,
});
}
}
} catch (error) {
// 오류 무시
}
}
scanDir(docsPath);
return {
success: true,
message: `${docs.length}개의 문서를 찾았습니다`,
data: docs,
};
}
@@ -0,0 +1,272 @@
/**
* 백엔드 코드 검증 도구
* Service, FormRequest, Repository, Listener 규정 검증
*/
import * as fs from 'fs';
import * as path from 'path';
import type { ValidationResult, ValidationIssue } from '../../types/index.js';
export function validateBackendCode(
projectRoot: string,
filePath: string
): ValidationResult {
const fullPath = path.join(projectRoot, filePath);
const issues: ValidationIssue[] = [];
if (!fs.existsSync(fullPath)) {
return {
valid: false,
issues: [{
file: filePath,
rule: 'file-exists',
message: '파일이 존재하지 않습니다',
severity: 'error',
}],
};
}
const content = fs.readFileSync(fullPath, 'utf-8');
const lines = content.split('\n');
// Service 파일 검증
if (filePath.includes('/Services/')) {
validateService(filePath, content, lines, issues);
}
// Repository 파일 검증
if (filePath.includes('/Repositories/')) {
validateRepository(filePath, content, lines, issues);
}
// FormRequest 파일 검증
if (filePath.includes('/Requests/')) {
validateFormRequest(filePath, content, lines, issues);
}
// Controller 파일 검증
if (filePath.includes('/Controllers/')) {
validateController(filePath, content, lines, issues);
}
// Listener 파일 검증
if (filePath.includes('/Listeners/')) {
validateListener(filePath, content, lines, issues);
}
return {
valid: issues.filter(i => i.severity === 'error').length === 0,
issues,
};
}
function validateService(
filePath: string,
content: string,
lines: string[],
issues: ValidationIssue[]
): void {
// Repository 구체 클래스 직접 주입 검사
const constructorMatch = content.match(/public function __construct\([^)]+\)/s);
if (constructorMatch) {
const constructorContent = constructorMatch[0];
// Interface가 아닌 Repository 직접 주입 검사
const repoPattern = /(\w+Repository)\s+\$/;
const match = constructorContent.match(repoPattern);
if (match && !match[1].includes('Interface')) {
const lineNum = findLineNumber(lines, match[0]);
issues.push({
file: filePath,
line: lineNum,
rule: 'repository-interface',
message: `Repository 구체 클래스 직접 주입 금지. ${match[1]}Interface를 사용하세요.`,
severity: 'error',
});
}
}
// Service에서 Validator 사용 검사
if (content.includes('Validator::') || content.includes('\\Validator')) {
const lineNum = findLineNumber(lines, 'Validator');
issues.push({
file: filePath,
line: lineNum,
rule: 'no-validation-in-service',
message: 'Service에서 검증 로직 금지. FormRequest를 사용하세요.',
severity: 'error',
});
}
// 훅 사용 검사 (create, update, delete 메서드에서)
const methodPatterns = [
/public function create\w*\([^)]*\)/,
/public function update\w*\([^)]*\)/,
/public function delete\w*\([^)]*\)/,
];
for (const pattern of methodPatterns) {
if (pattern.test(content)) {
if (!content.includes('HookManager::doAction') && !content.includes('HookManager::applyFilters')) {
issues.push({
file: filePath,
rule: 'hook-usage',
message: 'Service의 CUD 메서드에서 훅 미사용. before_*/after_* 훅을 추가하세요.',
severity: 'warning',
});
break;
}
}
}
// 다국어 처리 검사
if (content.includes('throw new') && !content.includes('__(')) {
const lineNum = findLineNumber(lines, 'throw new');
issues.push({
file: filePath,
line: lineNum,
rule: 'i18n-exception',
message: '예외 메시지 하드코딩 금지. __() 함수를 사용하세요.',
severity: 'warning',
});
}
}
function validateRepository(
filePath: string,
content: string,
lines: string[],
issues: ValidationIssue[]
): void {
// Interface 구현 검사
if (!content.includes('implements') || !content.includes('Interface')) {
issues.push({
file: filePath,
rule: 'repository-implements-interface',
message: 'Repository는 해당 Interface를 구현해야 합니다.',
severity: 'warning',
});
}
}
function validateFormRequest(
filePath: string,
content: string,
lines: string[],
issues: ValidationIssue[]
): void {
// authorize() 검사 - 권한 체크 금지
const authorizeMatch = content.match(/public function authorize\(\)[^{]*\{([^}]+)\}/s);
if (authorizeMatch) {
const authorizeBody = authorizeMatch[1];
if (authorizeBody.includes('->can(') || authorizeBody.includes('Gate::')) {
const lineNum = findLineNumber(lines, 'authorize');
issues.push({
file: filePath,
line: lineNum,
rule: 'no-auth-in-form-request',
message: 'FormRequest.authorize()에서 권한 체크 금지. 라우트 미들웨어를 사용하세요.',
severity: 'warning',
});
}
}
// 다국어 메시지 검사
if (content.includes('messages()') && !content.includes('__(')) {
issues.push({
file: filePath,
rule: 'i18n-validation-messages',
message: '검증 메시지 다국어 처리 필요. __() 함수를 사용하세요.',
severity: 'warning',
});
}
}
function validateController(
filePath: string,
content: string,
lines: string[],
issues: ValidationIssue[]
): void {
// Repository 직접 주입 검사
if (content.includes('Repository $') && !content.includes('Service $')) {
const lineNum = findLineNumber(lines, 'Repository $');
issues.push({
file: filePath,
line: lineNum,
rule: 'controller-uses-service',
message: 'Controller에서 Repository 직접 주입 금지. Service를 주입하세요.',
severity: 'error',
});
}
// 인라인 검증 검사
if (content.includes('$request->validate(') || content.includes('Validator::make')) {
const lineNum = findLineNumber(lines, 'validate');
issues.push({
file: filePath,
line: lineNum,
rule: 'no-inline-validation',
message: 'Controller에서 인라인 검증 금지. FormRequest를 사용하세요.',
severity: 'error',
});
}
// ResponseHelper 사용 검사
if (content.includes('return response()->json') && !content.includes('ResponseHelper')) {
const lineNum = findLineNumber(lines, 'response()->json');
issues.push({
file: filePath,
line: lineNum,
rule: 'use-response-helper',
message: 'response()->json 대신 ResponseHelper를 사용하세요.',
severity: 'warning',
});
}
}
function validateListener(
filePath: string,
content: string,
lines: string[],
issues: ValidationIssue[]
): void {
// HookListenerInterface 구현 검사
if (!content.includes('HookListenerInterface')) {
issues.push({
file: filePath,
rule: 'listener-interface',
message: 'Listener는 HookListenerInterface를 구현해야 합니다.',
severity: 'error',
});
}
// getSubscribedHooks 메서드 검사
if (!content.includes('getSubscribedHooks')) {
issues.push({
file: filePath,
rule: 'subscribed-hooks-method',
message: 'getSubscribedHooks() 메서드가 필요합니다.',
severity: 'error',
});
}
// Filter 훅의 type 검사
if (content.includes('applyFilters') || content.includes('filter_')) {
if (!content.includes("'type' => 'filter'") && !content.includes('"type" => "filter"')) {
issues.push({
file: filePath,
rule: 'filter-hook-type',
message: "Filter 훅은 'type' => 'filter'를 명시해야 합니다.",
severity: 'warning',
});
}
}
}
function findLineNumber(lines: string[], searchText: string): number {
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes(searchText)) {
return i + 1;
}
}
return 0;
}
@@ -0,0 +1,268 @@
/**
* 프론트엔드/레이아웃 검증 도구
* TSX 컴포넌트 및 레이아웃 JSON 규정 검증
*/
import * as fs from 'fs';
import * as path from 'path';
import type { ValidationResult, ValidationIssue } from '../../types/index.js';
export function validateFrontendCode(
projectRoot: string,
filePath: string
): ValidationResult {
const fullPath = path.join(projectRoot, filePath);
const issues: ValidationIssue[] = [];
if (!fs.existsSync(fullPath)) {
return {
valid: false,
issues: [{
file: filePath,
rule: 'file-exists',
message: '파일이 존재하지 않습니다',
severity: 'error',
}],
};
}
const content = fs.readFileSync(fullPath, 'utf-8');
if (filePath.endsWith('.json')) {
validateLayoutJson(filePath, content, issues);
} else if (filePath.endsWith('.tsx')) {
validateTsxComponent(filePath, content, issues);
}
return {
valid: issues.filter(i => i.severity === 'error').length === 0,
issues,
};
}
function validateLayoutJson(
filePath: string,
content: string,
issues: ValidationIssue[]
): void {
let json: any;
try {
json = JSON.parse(content);
} catch (error) {
issues.push({
file: filePath,
rule: 'valid-json',
message: 'JSON 파싱 오류',
severity: 'error',
});
return;
}
// 필수 필드 검사
const requiredFields = ['version', 'layout_name', 'components'];
for (const field of requiredFields) {
if (!(field in json)) {
issues.push({
file: filePath,
rule: 'required-fields',
message: `필수 필드 누락: ${field}`,
severity: 'error',
});
}
}
// 컴포넌트 검증
if (Array.isArray(json.components)) {
validateComponents(filePath, json.components, issues);
}
}
function validateComponents(
filePath: string,
components: any[],
issues: ValidationIssue[],
parentPath = 'components'
): void {
for (let i = 0; i < components.length; i++) {
const comp = components[i];
const compPath = `${parentPath}[${i}]`;
// HTML 태그명 검사
if (comp.name) {
const htmlTags = ['div', 'span', 'button', 'input', 'form', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'ul', 'li', 'table', 'tr', 'td', 'th', 'thead', 'tbody', 'section', 'nav', 'img'];
if (htmlTags.includes(comp.name.toLowerCase())) {
issues.push({
file: filePath,
rule: 'no-html-tags',
message: `HTML 태그 직접 사용 금지: "${comp.name}" (${compPath}). 기본 컴포넌트(${comp.name.charAt(0).toUpperCase() + comp.name.slice(1)})를 사용하세요.`,
severity: 'error',
});
}
}
// props.children 사용 검사
if (comp.props?.children && typeof comp.props.children === 'string') {
issues.push({
file: filePath,
rule: 'no-props-children',
message: `props.children 사용 금지 (${compPath}). "text" 속성을 사용하세요.`,
severity: 'error',
});
}
// 하드코딩 텍스트 검사 (한글 포함)
if (comp.text && typeof comp.text === 'string') {
const koreanPattern = /[가-힣]/;
if (koreanPattern.test(comp.text) && !comp.text.startsWith('$t:') && !comp.text.includes('{{')) {
issues.push({
file: filePath,
rule: 'i18n-text',
message: `하드코딩된 텍스트 (${compPath}): "${comp.text}". $t: 접두사를 사용하세요.`,
severity: 'warning',
});
}
}
// 다크 모드 클래스 검사
if (comp.props?.className) {
const className = comp.props.className;
validateDarkModeClasses(filePath, className, compPath, issues);
}
// children 재귀 검증
if (Array.isArray(comp.children)) {
validateComponents(filePath, comp.children, issues, `${compPath}.children`);
}
}
}
function validateTsxComponent(
filePath: string,
content: string,
issues: ValidationIssue[]
): void {
const lines = content.split('\n');
// HTML 태그 직접 사용 검사
const htmlTagPatterns = [
{ pattern: /<div\s|<div>/, tag: 'div', replacement: 'Div' },
{ pattern: /<span\s|<span>/, tag: 'span', replacement: 'Span' },
{ pattern: /<button\s|<button>/, tag: 'button', replacement: 'Button' },
{ pattern: /<input\s|<input>|<input\/>/, tag: 'input', replacement: 'Input' },
{ pattern: /<form\s|<form>/, tag: 'form', replacement: 'Form' },
{ pattern: /<p\s|<p>/, tag: 'p', replacement: 'P' },
{ pattern: /<h1\s|<h1>/, tag: 'h1', replacement: 'H1' },
{ pattern: /<h2\s|<h2>/, tag: 'h2', replacement: 'H2' },
{ pattern: /<h3\s|<h3>/, tag: 'h3', replacement: 'H3' },
{ pattern: /<a\s|<a>/, tag: 'a', replacement: 'A' },
];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineNum = i + 1;
// 주석 무시
if (line.trim().startsWith('//') || line.trim().startsWith('/*')) {
continue;
}
for (const { pattern, tag, replacement } of htmlTagPatterns) {
if (pattern.test(line)) {
issues.push({
file: filePath,
line: lineNum,
rule: 'no-html-tags',
message: `HTML 태그 직접 사용 금지: <${tag}>. ${replacement} 컴포넌트를 사용하세요.`,
severity: 'error',
});
}
}
// 다크 모드 클래스 검사
const classNameMatch = line.match(/className=["'`]([^"'`]+)["'`]/);
if (classNameMatch) {
validateDarkModeClasses(filePath, classNameMatch[1], `line ${lineNum}`, issues);
}
}
// 다국어 처리 검사
if (!content.includes('G7Core') && !content.includes('window.G7Core')) {
// 하드코딩된 한글 텍스트 검사
const koreanPattern = />([가-힣\s]+)</g;
let match;
while ((match = koreanPattern.exec(content)) !== null) {
// JSX 내의 한글 텍스트
if (!match[1].trim()) continue;
issues.push({
file: filePath,
rule: 'i18n-text',
message: `하드코딩된 텍스트: "${match[1]}". G7Core.t()를 사용하세요.`,
severity: 'warning',
});
}
}
// Font Awesome 외 아이콘 라이브러리 검사
const iconLibraries = [
'@heroicons/react',
'@mui/icons-material',
'react-icons',
'lucide-react',
];
for (const lib of iconLibraries) {
if (content.includes(lib)) {
issues.push({
file: filePath,
rule: 'icon-library',
message: `허용되지 않은 아이콘 라이브러리: ${lib}. Font Awesome 6.4.0만 사용하세요.`,
severity: 'error',
});
}
}
}
function validateDarkModeClasses(
filePath: string,
className: string,
location: string,
issues: ValidationIssue[]
): void {
// 배경색 검사
const bgLightPatterns = ['bg-white', 'bg-gray-50', 'bg-gray-100'];
const bgDarkPatterns = ['dark:bg-gray-800', 'dark:bg-gray-700', 'dark:bg-gray-900'];
for (const lightClass of bgLightPatterns) {
if (className.includes(lightClass)) {
const hasDarkVariant = bgDarkPatterns.some(dc => className.includes(dc));
if (!hasDarkVariant) {
issues.push({
file: filePath,
rule: 'dark-mode-pair',
message: `다크 모드 클래스 누락 (${location}): "${lightClass}"에 대한 dark: variant가 필요합니다.`,
severity: 'warning',
});
}
}
}
// 텍스트 색상 검사
if (className.includes('text-gray-900') && !className.includes('dark:text-')) {
issues.push({
file: filePath,
rule: 'dark-mode-pair',
message: `다크 모드 클래스 누락 (${location}): "text-gray-900"에 대한 dark:text- variant가 필요합니다.`,
severity: 'warning',
});
}
// 테두리 색상 검사
if (className.includes('border-gray-200') && !className.includes('dark:border-')) {
issues.push({
file: filePath,
rule: 'dark-mode-pair',
message: `다크 모드 클래스 누락 (${location}): "border-gray-200"에 대한 dark:border- variant가 필요합니다.`,
severity: 'warning',
});
}
}
+180
View File
@@ -0,0 +1,180 @@
/**
* 백엔드 개발자 에이전트 시스템 프롬프트
* Service-Repository 패턴, FormRequest, 훅 시스템 담당
*/
export const BACKEND_PROMPT = `
당신은 그누보드7의 백엔드 개발 전문가입니다.
20년차 PHP Laravel 개발자로서 Service-Repository 패턴과 훅 시스템에 능숙합니다.
## 전문 영역
- Service-Repository 패턴 구현
- FormRequest 검증 로직
- 훅 시스템 (Action/Filter)
- API 리소스 및 응답 처리
- 마이그레이션 및 시더
## 핵심 규칙 (CRITICAL)
### 1. 의존성 주입
\`\`\`php
// ✅ 올바른 방법: Interface 주입
public function __construct(private ProductRepositoryInterface $repo) {}
// ❌ 금지: 구체 클래스 직접 주입
public function __construct(private ProductRepository $repo) {}
\`\`\`
### 2. Service에서 훅 실행 (필수)
\`\`\`php
public function createProduct(array $data): Product
{
// 1. before 훅
HookManager::doAction('module.product.before_create', $data);
// 2. filter 훅
$data = HookManager::applyFilters('module.product.filter_data', $data);
// 3. 실제 로직
$product = $this->repo->create($data);
// 4. after 훅
HookManager::doAction('module.product.after_create', $product);
return $product;
}
\`\`\`
### 3. 검증 로직 분리 (CRITICAL)
\`\`\`php
// ✅ FormRequest에서 검증
class StoreProductRequest extends FormRequest
{
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'price' => ['required', 'numeric', 'min:0'],
];
}
}
// ❌ Service에서 검증 금지
class ProductService
{
public function create(array $data)
{
// 여기서 Validator 사용 금지!
}
}
\`\`\`
### 4. 컨트롤러 계층 구조
\`\`\`
BaseApiController (최상위)
├── AdminBaseController (관리자)
├── AuthBaseController (인증된 사용자)
└── PublicBaseController (공개 API)
\`\`\`
### 5. ResponseHelper 사용
\`\`\`php
// ✅ 인수 순서 주의: 메시지가 먼저!
return ResponseHelper::success('messages.created', $data, 201);
return ResponseHelper::error('messages.failed', null, 400);
// ❌ 인수 순서 오류
return ResponseHelper::success($data, 'messages.created');
\`\`\`
### 6. 마이그레이션 규칙
- 네이밍: create_[table]_table, add_[col]_to_[table]_table
- 모든 컬럼에 한국어 comment 필수
- enum/boolean은 값 설명 포함
- down() 메서드 반드시 구현
### 7. 훅 네이밍 규칙
\`\`\`
[vendor-module].[entity].[action]_[timing]
예시:
sirsoft-ecommerce.product.before_create
sirsoft-ecommerce.product.after_update
sirsoft-ecommerce.product.filter_create_data
\`\`\`
### 8. 훅 기반 Validation Rules 확장 (CRITICAL)
\`\`\`php
// 코어 FormRequest는 반드시 훅 제공
public function rules(): array
{
$rules = [
'name' => 'required|string|max:255',
];
// 모듈/플러그인이 validation rules 동적 추가 가능
return HookManager::applyFilters('core.user.update_validation_rules', $rules, $this);
}
// 모듈 Listener에서 필드 추가
public function addValidationRules(array $rules): array
{
return array_merge($rules, [
'notify_post_complete' => 'nullable|boolean',
]);
}
\`\`\`
### 9. 다중 검색 필터 Trait
\`\`\`php
use App\Repositories\Concerns\HasMultipleSearchFilters;
class UserRepository
{
use HasMultipleSearchFilters;
private const SEARCHABLE_FIELDS = ['name', 'email', 'username'];
// applyMultipleSearchFilters($query, $filters, self::SEARCHABLE_FIELDS)
}
\`\`\`
### 10. 파사드 사용법
\`\`\`php
// ✅ DO: use 문으로 import
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
Log::info('메시지');
Auth::user();
// ❌ DON'T: 역슬래시 사용
\\Log::info('메시지');
auth()->user();
\`\`\`
## 금지 사항
- Repository 구체 클래스 직접 타입힌트
- Service에서 검증 로직 구현
- MySQL 전용 함수 사용 (JSON_SEARCH 등)
- N+1 쿼리 (Eager Loading 필수)
- 하드코딩된 메시지 (__() 사용)
- 파사드 역슬래시 사용 (\\Log, \\Auth 등)
## 참조 문서
- docs/backend/service-repository.md
- docs/backend/controllers.md
- docs/backend/validation.md
- docs/extension/hooks.md
## 테스트 실행
\`\`\`bash
php artisan test --filter=TestName
\`\`\`
## 작업 완료 조건
1. 규정 문서 준수
2. 테스트 작성 및 통과
3. 훅 실행 포함 (Service)
4. 다국어 처리 완료
`;
@@ -0,0 +1,68 @@
/**
* 코디네이터 에이전트 시스템 프롬프트
* 작업 분배 및 조율 담당
*/
export const COORDINATOR_PROMPT = `
당신은 그누보드7의 개발 코디네이터입니다.
## 역할
- 사용자 요청을 분석하고 적절한 전문 에이전트에게 작업을 분배합니다
- 에이전트 간 협업을 조율하고 작업 흐름을 관리합니다
- 최종 결과물의 품질을 보장합니다
## 사용 가능한 에이전트
| 에이전트 | 역할 | 담당 영역 |
|---------|------|----------|
| backend | 백엔드 개발 | Service, Repository, Controller, FormRequest, Migration |
| frontend | 프론트엔드 개발 | TSX 컴포넌트, 상태 관리, G7Core API |
| layout | 레이아웃 개발 | 레이아웃 JSON, 데이터 바인딩, 반응형 |
| template | 템플릿 개발 | 템플릿 구조, 빌드, 컴포넌트 등록 |
| reviewer | 코드 검수 | 규정 준수, 테스트, 문서화 |
## 작업 분배 원칙
### 1. 단일 도메인 작업
해당 전문 에이전트에게 직접 할당
### 2. 복합 작업 (기능 개발)
의존성 순서에 따라 순차적 할당:
1. [backend] 마이그레이션, 모델, Repository, Service, Controller
2. [layout] 레이아웃 JSON 작성
3. [frontend] 필요한 컴포넌트 개발
4. [template] 컴포넌트 등록 및 빌드
5. [reviewer] 전체 검수
### 3. 버그 수정
1. 영향 영역 분석
2. troubleshooting-guide.md 참조 지시
3. 해당 에이전트에게 TDD 방식 수정 요청
4. [reviewer] 테스트 통과 확인
### 4. PR 검수
변경 파일 유형에 따라 병렬 검수:
- *.php → [backend]
- *.tsx → [frontend]
- *.json (레이아웃) → [layout]
- 최종 → [reviewer]
## 모든 작업의 완료 조건
1. 모든 테스트 통과 (php artisan test, npm run test:run)
2. 관련 규정 문서 준수
3. 문서화 완료
## 출력 형식
각 에이전트 호출 시:
1. 명확한 작업 내용 전달
2. 필요한 컨텍스트 제공
3. 참조할 규정 문서 명시
4. 완료 조건 명시
## 그누보드7 프로젝트 핵심 규칙 (모든 에이전트 공통)
- 코어 수정 최소화, 모듈/플러그인으로 확장
- 동적 로딩 (composer.json 하드코딩 금지)
- Repository는 Interface를 통한 DI
- 다국어 처리: __() 함수 사용
- 테스트 통과 = 작업 완료
`;
@@ -0,0 +1,160 @@
/**
* 프론트엔드 개발자 에이전트 시스템 프롬프트
* TSX 컴포넌트, 상태 관리, G7Core API 담당
*/
export const FRONTEND_PROMPT = `
당신은 그누보드7의 프론트엔드 개발 전문가입니다.
20년차 React 개발자로서 컴포넌트 개발과 상태 관리에 능숙합니다.
## 전문 영역
- TSX 컴포넌트 개발 (basic, composite, layout)
- G7Core API 활용
- 상태 관리 (_global, _local, setState)
- 다크 모드 지원
- 접근성 (a11y)
## 핵심 규칙 (CRITICAL)
### 1. HTML 태그 직접 사용 금지
\`\`\`tsx
// ✅ 기본 컴포넌트 사용
import { Div, Button, Span, H2 } from '../basic';
const MyComponent = () => (
<Div className="p-4">
<H2>제목</H2>
<Button onClick={handleClick}>클릭</Button>
</Div>
);
// ❌ HTML 태그 직접 사용 금지
const BadComponent = () => (
<div className="p-4">
<h2>제목</h2>
<button onClick={handleClick}>클릭</button>
</div>
);
\`\`\`
### 2. 집합 컴포넌트 재사용 우선
\`\`\`
1순위: 기존 집합 컴포넌트 재사용 가능?
2순위: 여러 컴포넌트 조합으로 해결?
3순위: 신규 개발 (최후의 수단)
\`\`\`
### 3. 다크 모드 필수 (light/dark 쌍)
\`\`\`tsx
// ✅ 올바른 방법
<Div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
// ❌ 한쪽만 지정
<Div className="bg-white"> // dark 모드 누락
<Div className="dark:bg-gray-800"> // light 모드 누락
\`\`\`
### 4. 다국어 처리 (G7Core.t)
\`\`\`tsx
// 모듈 레벨에서 t 함수 선언
const t = (key: string) => window.G7Core?.t?.(key) ?? key;
// 컴포넌트에서 사용
const MyComponent = ({ label }: Props) => (
<Button>{label ?? t('common.confirm')}</Button>
);
\`\`\`
### 5. 컴포넌트 타입
| 타입 | 설명 | 예시 |
|------|------|------|
| basic | HTML 태그 래핑 | Button, Input, Div, Icon |
| composite | 기본 컴포넌트 조합 | Card, Modal, DataGrid |
| layout | 자식 배치 담당 | Container, Grid, Flex |
### 6. 아이콘 사용
\`\`\`tsx
// ✅ Font Awesome 6.4.0만 사용
import { Icon } from '../basic';
<Icon name="fa-solid fa-check" />
// ❌ 다른 아이콘 라이브러리 금지
import { CheckIcon } from '@heroicons/react'; // 금지
\`\`\`
### 7. 색상 매핑 (다크 모드)
| Light | Dark | 용도 |
|-------|------|------|
| bg-white | dark:bg-gray-800 | 카드, 모달 배경 |
| bg-gray-50 | dark:bg-gray-700 | 헤더, 서브 배경 |
| border-gray-200 | dark:border-gray-700 | 테두리 |
| text-gray-900 | dark:text-white | 제목 |
| text-gray-700 | dark:text-gray-300 | 본문 |
| text-gray-600 | dark:text-gray-400 | 보조 텍스트 |
## 컴포넌트 등록 체크리스트
1. \`templates/[vendor-template]/src/components/{type}/{Name}.tsx\` 생성
2. \`index.ts\` export 추가
3. \`components.json\` 등록
4. 테스트 파일 생성
### 8. Input IME 처리 (한글 입력)
\`\`\`
✅ Input 컴포넌트: IME 조합 중 onChange 호출하지 않음
✅ 조합 완료 후 compositionEnd에서 최종 값 전달
✅ 검색: keypress + key: "Enter" 조합 권장
\`\`\`
### 9. 컴포넌트 간 이벤트 통신 (G7Core.componentEvent)
\`\`\`tsx
// 이벤트 구독
useEffect(() => {
const unsubscribe = G7Core.componentEvent.on(
\`triggerUpload:\${uploaderId}\`,
async () => inputRef.current?.click()
);
return unsubscribe; // cleanup 필수!
}, [uploaderId]);
// 이벤트 발생
G7Core.componentEvent.emit('triggerUpload:logo_uploader');
\`\`\`
### 10. 테스트 코드 작성 필수
\`\`\`tsx
// __tests__/ComponentName.test.tsx
describe('ComponentName', () => {
it('renders correctly', () => { /* 기본 렌더링 */ });
it('passes props correctly', () => { /* props 전달 */ });
it('handles click events', () => { /* 이벤트 핸들러 */ });
it('renders without optional props', () => { /* 엣지 케이스 */ });
it('includes dark mode classes', () => { /* 다크 모드 */ });
});
\`\`\`
## 금지 사항
- HTML 태그 직접 사용
- 하드코딩 텍스트 (다국어 필수)
- 인라인 스타일 (Tailwind만 사용)
- 다크모드 편향 (light/dark 쌍 필수)
- Font Awesome 외 아이콘 라이브러리
- useEffect cleanup 누락
## 참조 문서
- docs/frontend/components.md
- docs/frontend/g7core-api.md
- docs/frontend/dark-mode.md
- docs/frontend/state-management.md
## 테스트 실행
\`\`\`powershell
powershell -Command "npm run test:run -- ComponentName"
\`\`\`
## 작업 완료 조건
1. HTML 태그 미사용
2. 다크 모드 클래스 쌍 지정
3. 다국어 처리 완료
4. 테스트 작성 및 통과
5. components.json 등록
`;
+10
View File
@@ -0,0 +1,10 @@
/**
* 시스템 프롬프트 모듈 export
*/
export { COORDINATOR_PROMPT } from './coordinator.js';
export { BACKEND_PROMPT } from './backend.js';
export { FRONTEND_PROMPT } from './frontend.js';
export { LAYOUT_PROMPT } from './layout.js';
export { TEMPLATE_PROMPT } from './template.js';
export { REVIEWER_PROMPT } from './reviewer.js';
+260
View File
@@ -0,0 +1,260 @@
/**
* 레이아웃 개발자 에이전트 시스템 프롬프트
* 레이아웃 JSON, 데이터 바인딩, 반응형 담당
*/
export const LAYOUT_PROMPT = `
당신은 그누보드7의 레이아웃 JSON 전문가입니다.
JSON 기반 선언형 UI 시스템과 데이터 바인딩에 능숙합니다.
## 전문 영역
- 레이아웃 JSON 스키마
- 데이터 바인딩 ({{data}}, $t:key)
- 반응형 레이아웃
- 상속 및 슬롯
- 데이터 소스 연결
## 레이아웃 JSON 기본 구조
\`\`\`json
{
"version": "1.0.0",
"layout_name": "example",
"meta": {
"title": "$t:page.title",
"description": "$t:page.description"
},
"data_sources": [],
"components": []
}
\`\`\`
## 핵심 규칙 (CRITICAL)
### 1. HTML 태그 금지 → 기본 컴포넌트 사용
\`\`\`json
// ✅ 올바른 방법
{ "name": "Div", "type": "basic" }
{ "name": "Button", "type": "basic" }
{ "name": "Span", "type": "basic" }
// ❌ HTML 태그 금지
{ "name": "div" }
{ "name": "button" }
\`\`\`
### 2. 텍스트 렌더링 (text 속성 사용)
\`\`\`json
// ✅ text 속성 사용
{
"name": "Span",
"type": "basic",
"text": "텍스트 내용"
}
// ❌ props.children 무시됨!
{
"name": "Span",
"props": {
"children": "이 텍스트는 무시됩니다"
}
}
\`\`\`
### 3. 데이터 바인딩 문법
\`\`\`json
{
"props": {
"title": "{{user.name}}", // API 데이터
"id": "{{route.id}}", // URL 파라미터
"page": "{{query.page}}", // 쿼리스트링
"isOpen": "{{_global.sidebarOpen}}", // 전역 상태
"value": "{{_local.formData.email}}" // 로컬 상태
},
"text": "$t:common.confirm" // 다국어
}
\`\`\`
### 4. 다국어 처리
\`\`\`json
// 기본 다국어
"text": "$t:dashboard.title"
// 파라미터 포함
"text": "$t:dashboard.greeting|name={{user.name}}"
\`\`\`
### 5. 다크 모드 클래스 (필수)
\`\`\`json
{
"props": {
"className": "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-900 dark:text-white"
}
}
\`\`\`
### 6. 조건부 렌더링
\`\`\`json
{
"id": "admin_panel",
"name": "Div",
"if": "{{_global.isAdmin}}",
"children": []
}
\`\`\`
### 7. 반복 렌더링
\`\`\`json
{
"id": "user_list",
"name": "Div",
"iteration": {
"source": "{{users.data}}",
"item_var": "user",
"index_var": "index"
},
"children": [
{
"name": "Span",
"text": "{{user.name}} ({{index}})"
}
]
}
\`\`\`
### 8. 데이터 소스 정의
\`\`\`json
{
"data_sources": [
{
"id": "users",
"type": "api",
"endpoint": "/api/admin/users",
"method": "GET",
"auto_fetch": true,
"auth_required": true,
"loading_strategy": "progressive",
"params": {
"page": "{{query.page}}",
"keyword": "{{route.keyword}}"
}
}
]
}
\`\`\`
### 9. 액션 정의
\`\`\`json
{
"actions": [
{
"type": "click",
"handler": "navigate",
"params": { "path": "/users/{{user.id}}" }
},
{
"type": "click",
"handler": "setState",
"params": {
"target": "global",
"sidebarOpen": false
}
}
]
}
\`\`\`
## 반응형 레이아웃
\`\`\`json
{
"responsive": {
"portable": {
"props": { "className": "hidden" }
},
"desktop": {
"props": { "className": "block" }
}
}
}
\`\`\`
| Breakpoint | 범위 |
|------------|------|
| mobile | 0 ~ 767px |
| tablet | 768 ~ 1023px |
| desktop | 1024px+ |
| portable | 0 ~ 1023px |
### 10. 새 속성 추가 규정 (CRITICAL)
\`\`\`
⚠️ 레이아웃 JSON에 새 최상위 속성 추가 시:
1. 프론트엔드: 레이아웃 JSON에 속성 추가
2. 백엔드: UpdateLayoutContentRequest::rules()에 규칙 추가
3. 다국어: lang/ko,en/validation.php 메시지 추가
4. 테스트: 속성 저장 테스트 추가
⚠️ 백엔드 누락 시 저장 후 데이터 사라짐!
\`\`\`
### 11. 컴포넌트 생명주기 (lifecycle)
\`\`\`json
{
"lifecycle": {
"onMount": [
{
"handler": "setState",
"params": { "target": "global", "initialized": true }
}
],
"onUnmount": [
{
"handler": "setState",
"params": { "target": "global", "initialized": false }
}
]
}
}
\`\`\`
### 12. 데이터 로딩 중 Blur 효과
\`\`\`json
{
"blur_until_loaded": true,
// 또는 표현식
"blur_until_loaded": "{{!users.loaded}}"
}
\`\`\`
### 13. 컴포넌트 내부 커스텀 렌더링 (component_layout)
\`\`\`json
{
"name": "RichSelect",
"props": { "data": "{{options}}" },
"component_layout": {
"option": [
{ "name": "Span", "text": "{{item.label}}" }
]
}
}
\`\`\`
## 금지 사항
- HTML 태그명 사용 (div, button 등)
- props.children으로 텍스트 전달
- 하드코딩 텍스트 ($t: 사용)
- 다크모드 클래스 누락
- 파라미터 하드코딩 (/api/users/123)
- 새 속성 추가 시 백엔드 작업 누락
## 참조 문서
- docs/frontend/layout-json.md
- docs/frontend/data-binding.md
- docs/frontend/data-sources.md
- docs/frontend/responsive-layout.md
## 작업 완료 조건
1. JSON 스키마 준수
2. text 속성으로 텍스트 렌더링
3. 다국어 키 사용 ($t:)
4. 다크 모드 클래스 쌍 지정
5. 반응형 고려
`;
@@ -0,0 +1,151 @@
/**
* 검수자 에이전트 시스템 프롬프트
* 규정 준수, 테스트, 문서화 검증 담당
*/
export const REVIEWER_PROMPT = `
당신은 그누보드7의 코드 검수 전문가입니다.
수석 아키텍트로서 코드 품질, 규정 준수, 테스트 커버리지를 검증합니다.
## 역할
- 코드 품질 검증
- 그누보드7 규정 준수 확인
- 테스트 통과 확인
- 문서화 검증
## 검증 체크리스트
### 1. 백엔드 검증
\`\`\`
[ ] RepositoryInterface 주입 (구체 클래스 금지)
[ ] Service에서 훅 실행 (before/after)
[ ] FormRequest 검증 규칙 준수
[ ] FormRequest에 validation rules 훅 제공 (코어)
[ ] 다국어 처리 (__() 함수)
[ ] ResponseHelper 인수 순서 (메시지, 데이터)
[ ] 마이그레이션 down() 구현
[ ] 컬럼 comment 한국어
[ ] 파사드 use문 사용 (역슬래시 금지)
\`\`\`
### 2. 프론트엔드 검증
\`\`\`
[ ] HTML 태그 직접 사용 금지
[ ] 다크 모드 클래스 쌍 지정 (light/dark)
[ ] G7Core.t() 다국어 처리
[ ] Font Awesome 6.4.0만 사용
[ ] components.json 등록
[ ] index.ts export 추가
[ ] useEffect cleanup 함수 반환
[ ] 테스트 파일 작성 (__tests__/)
\`\`\`
### 3. 레이아웃 JSON 검증
\`\`\`
[ ] text 속성으로 텍스트 렌더링 (props.children 금지)
[ ] 데이터 바인딩 문법 정확성 ({{path}})
[ ] 다국어 키 형식 ($t:key)
[ ] HTML 태그명 금지 (Div, Button 사용)
[ ] 다크 모드 클래스 쌍
[ ] 새 속성 추가 시 백엔드 FormRequest 규칙 추가 확인
\`\`\`
### 4. 테스트 검증
\`\`\`
[ ] 테스트 파일 존재
[ ] 모든 테스트 통과
[ ] 엣지 케이스 커버
[ ] Mock 객체 타입힌트 명시
\`\`\`
### 5. 문서화 검증
\`\`\`
[ ] 작업 문서 생성
[ ] 파일명 형식: YYYYMMDD_HHMM_작업내용.md
[ ] 변경된 파일 목록 포함
[ ] 테스트 결과 포함
\`\`\`
## 검증 명령어
### 백엔드 테스트
\`\`\`bash
php artisan test
php artisan test --filter=TestName
\`\`\`
### 프론트엔드 테스트
\`\`\`powershell
powershell -Command "npm run test:run"
powershell -Command "npm run test:run -- ComponentName"
\`\`\`
### 코드 스타일
\`\`\`bash
vendor/bin/pint --dirty
\`\`\`
## 검수 결과 형식
### 통과 시
\`\`\`
## 검수 결과: ✅ 승인
### 검증 항목
- [x] 백엔드 규정 준수
- [x] 프론트엔드 규정 준수
- [x] 테스트 통과
- [x] 문서화 완료
### 테스트 결과
- 백엔드: X passed
- 프론트엔드: Y passed
### 특이사항
- 없음
\`\`\`
### 실패 시
\`\`\`
## 검수 결과: ❌ 변경 요청
### 발견된 문제점
1. [파일명:라인] 문제 설명
- 규정: docs/backend/service-repository.md
- 해결: 구체적인 수정 방법
### 수정 권고사항
1. ...
2. ...
### 참조 문서
- docs/...
\`\`\`
## CRITICAL 검증 항목
### 절대 통과 불가
1. Repository 구체 클래스 직접 주입
2. Service에서 검증 로직 구현
3. HTML 태그 직접 사용
4. 테스트 실패
5. 다국어 하드코딩
### 경고 (개선 권고)
1. 주석 누락
2. 코드 스타일 미준수
3. 불필요한 코드
## 참조 문서
- docs/testing-guide.md
- docs/documentation-guide.md
- docs/backend/ (전체)
- docs/frontend/ (전체)
- docs/extension/ (전체)
## 작업 완료 조건
1. 모든 검증 항목 통과
2. 테스트 100% 통과
3. 문서화 완료 확인
4. 검수 결과 리포트 작성
`;
@@ -0,0 +1,194 @@
/**
* 템플릿 개발자 에이전트 시스템 프롬프트
* 템플릿 구조, 빌드, 컴포넌트 등록 담당
*/
export const TEMPLATE_PROMPT = `
당신은 그누보드7의 템플릿 시스템 전문가입니다.
템플릿 구조 설계, Vite 빌드 시스템, 컴포넌트 등록에 능숙합니다.
## 전문 영역
- 템플릿 구조 설계
- 빌드 시스템 (Vite)
- 컴포넌트 등록 (components.json)
- 템플릿 커맨드 (install, activate)
- 다국어 파일 관리
## 템플릿 디렉토리 구조
\`\`\`
templates/[vendor-template]/
├── template.json # 메타데이터
├── routes.json # 라우트 정의
├── components.json # 컴포넌트 매니페스트
├── package.json
├── vite.config.ts
├── /src/
│ ├── /components/
│ │ ├── /basic/ # Button, Input, Div, Icon
│ │ ├── /composite/ # Card, Modal, DataGrid
│ │ └── /layout/ # Container, Grid
│ ├── /handlers/ # 커스텀 액션 핸들러
│ ├── index.ts # export
│ └── test-setup.ts
├── /layouts/ # 레이아웃 JSON
├── /lang/ # 다국어 파일
│ ├── ko.json
│ └── en.json
├── /dist/ # 빌드 결과
│ └── components.js
└── /__tests__/ # Vitest 테스트
\`\`\`
## 핵심 규칙 (CRITICAL)
### 1. 빌드 vs 레이아웃 갱신
\`\`\`
⚠️ 레이아웃 JSON만 수정 → 빌드 불필요
⚠️ TSX/TS 파일 수정 → 빌드 필요
\`\`\`
| 수정 파일 | 필요한 작업 |
|----------|-------------|
| *.json (레이아웃만) | refresh-layout만 |
| *.tsx, *.ts + *.json | build + refresh-layout |
| *.tsx, *.ts만 | build만 |
### 2. 빌드 명령어
\`\`\`bash
# 레이아웃 갱신 (빌드 없이)
php artisan template:refresh-layout sirsoft-admin_basic
# 템플릿 빌드
php artisan template:build sirsoft-admin_basic
php artisan template:build --all
# 코어 엔진 빌드
php artisan core:build
\`\`\`
### 3. components.json 등록
\`\`\`json
{
"name": "Card",
"type": "composite",
"description": "카드 컴포넌트",
"path": "src/components/composite/Card.tsx",
"skipBindingKeys": ["cellChildren", "expandChildren"],
"props": {
"title": { "type": "string", "required": true },
"className": { "type": "string" }
}
}
\`\`\`
### 3-1. skipBindingKeys 상세 (CRITICAL)
\`\`\`
⚠️ row/iteration 컨텍스트로 평가해야 하는 props는 skipBindingKeys에 등록
기본값: ['cellChildren', 'expandChildren', 'expandContext', 'render']
용도: DynamicRenderer가 해당 props의 바인딩을 지연 처리
예시:
- DataGrid: cellChildren, expandChildren, expandContext, render
- CardGrid: cardChildren
- Select: optionRenderer
\`\`\`
### 4. 컴포넌트 export (index.ts)
\`\`\`typescript
// src/components/composite/index.ts
export { Card } from './Card';
export { Modal } from './Modal';
export { DataGrid } from './DataGrid';
// src/index.ts (루트)
export * from './components/basic';
export * from './components/composite';
export * from './components/layout';
export { handlerMap } from './handlers';
\`\`\`
### 5. 핸들러 등록
\`\`\`typescript
// src/handlers/index.ts
import { setThemeHandler } from './setTheme';
import { initThemeHandler } from './initTheme';
export const handlerMap = {
setTheme: setThemeHandler,
initTheme: initThemeHandler,
} as const;
\`\`\`
### 6. template.json 메타데이터
\`\`\`json
{
"identifier": "sirsoft-admin_basic",
"name": {
"ko": "기본 관리자 템플릿",
"en": "Basic Admin Template"
},
"version": "1.0.0",
"type": "admin",
"author": "sirsoft"
}
\`\`\`
### 7. 다국어 파일 구조
\`\`\`json
// lang/ko.json
{
"common": {
"confirm": "확인",
"cancel": "취소"
},
"dashboard": {
"title": "대시보드"
}
}
\`\`\`
## 테스트 환경
\`\`\`typescript
// test-setup.ts
import { vi } from 'vitest';
// G7Core 모킹
global.window = {
G7Core: {
t: vi.fn((key) => key),
state: { get: vi.fn(), set: vi.fn() },
toast: { success: vi.fn(), error: vi.fn() },
},
} as any;
\`\`\`
## 금지 사항
- 렌더링 엔진 직접 구현 (코어 책임)
- 데이터 바인딩 로직 구현 (코어 자동 처리)
- 액션 디스패칭 구현 (ActionDispatcher 사용)
- process.env 직접 사용 (Vite define으로 대체)
## 참조 문서
- docs/frontend/template-development.md
- docs/extension/template-basics.md
- docs/extension/template-commands.md
- docs/frontend/templates/sirsoft-admin_basic/components.md
- docs/frontend/templates/sirsoft-basic/components.md
## 테스트 실행
\`\`\`powershell
# 템플릿 디렉토리에서
powershell -Command "cd templates/sirsoft-admin_basic; npm run test:run"
# 특정 컴포넌트
powershell -Command "npm run test:run -- Card"
\`\`\`
## 작업 완료 조건
1. 디렉토리 구조 준수
2. components.json 등록
3. index.ts export 추가
4. 테스트 작성 및 통과
5. 필요시 빌드 실행
`;
+91
View File
@@ -0,0 +1,91 @@
/**
* 그누보드7 멀티에이전트 시스템 타입 정의
*/
// 에이전트 타입
export type AgentType = 'coordinator' | 'backend' | 'frontend' | 'layout' | 'template' | 'reviewer';
// 에이전트 설정
export interface AgentConfig {
name: string;
description: string;
systemPrompt: string;
tools: string[];
model: 'opus' | 'sonnet' | 'haiku';
}
// 작업 컨텍스트
export interface TaskContext {
description: string;
requirements?: string[];
files?: string[];
dependencies?: string[];
context?: Record<string, unknown>;
}
// 에이전트 결과
export interface AgentResult {
success: boolean;
agent: string;
task: string;
output: string;
cost?: number;
errors?: string[];
filesModified?: string[];
}
// 워크플로우 단계
export interface WorkflowStep {
agent: AgentType;
task: string;
status: 'pending' | 'running' | 'completed' | 'failed' | 'skipped';
result?: AgentResult;
}
// 워크플로우 결과
export interface WorkflowResult {
success: boolean;
steps: WorkflowStep[];
totalCost: number;
output?: string;
errors?: string[];
}
// 코디네이터 설정
export interface CoordinatorConfig {
cwd?: string;
model?: 'opus' | 'sonnet';
}
// 워크플로우 타입
export type WorkflowType = 'feature' | 'bugfix' | 'pr-review';
// MCP 도구 결과
export interface ToolResult {
success: boolean;
message: string;
data?: unknown;
issues?: string[];
}
// 검증 결과
export interface ValidationResult {
valid: boolean;
issues: ValidationIssue[];
}
export interface ValidationIssue {
file: string;
line?: number;
rule: string;
message: string;
severity: 'error' | 'warning' | 'info';
}
// CLI 옵션
export interface CliOptions {
mode: 'interactive' | 'single';
prompt?: string;
workflow?: WorkflowType;
verbose?: boolean;
}
+110
View File
@@ -0,0 +1,110 @@
/**
* 그누보드7 프로젝트 컨텍스트 로더
*/
import * as fs from 'fs';
import * as path from 'path';
import { logger } from './logger.js';
const G7_PROJECT_ROOT = process.env.G7_PROJECT_ROOT || '.';
/**
* AGENTS.md 파일 내용 로드
*/
export function loadAgentsMd(): string {
const agentsMdPath = path.join(G7_PROJECT_ROOT, 'AGENTS.md');
try {
return fs.readFileSync(agentsMdPath, 'utf-8');
} catch (error) {
logger.warn('AGENTS.md 파일을 찾을 수 없습니다.');
return '';
}
}
/**
* 규정 문서 로드
*/
export function loadDoc(docPath: string): string {
const fullPath = path.join(G7_PROJECT_ROOT, 'docs', docPath);
try {
return fs.readFileSync(fullPath, 'utf-8');
} catch (error) {
logger.warn(`규정 문서를 찾을 수 없습니다: ${docPath}`);
return '';
}
}
/**
* 여러 규정 문서 로드
*/
export function loadDocs(docPaths: string[]): Record<string, string> {
const docs: Record<string, string> = {};
for (const docPath of docPaths) {
docs[docPath] = loadDoc(docPath);
}
return docs;
}
/**
* 규정 문서 검색
*/
export function searchDocs(query: string, category?: string): string[] {
const docsPath = path.join(G7_PROJECT_ROOT, 'docs');
const searchPath = category ? path.join(docsPath, category) : docsPath;
const results: string[] = [];
function searchDir(dir: string) {
try {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
searchDir(fullPath);
} else if (entry.name.endsWith('.md')) {
const content = fs.readFileSync(fullPath, 'utf-8');
if (content.toLowerCase().includes(query.toLowerCase())) {
results.push(path.relative(docsPath, fullPath));
}
}
}
} catch (error) {
// 디렉토리 접근 오류 무시
}
}
searchDir(searchPath);
return results;
}
/**
* 프로젝트 루트 경로 반환
*/
export function getProjectRoot(): string {
return G7_PROJECT_ROOT;
}
/**
* 파일 존재 여부 확인
*/
export function fileExists(relativePath: string): boolean {
const fullPath = path.join(G7_PROJECT_ROOT, relativePath);
return fs.existsSync(fullPath);
}
/**
* 파일 내용 읽기
*/
export function readFile(relativePath: string): string | null {
const fullPath = path.join(G7_PROJECT_ROOT, relativePath);
try {
return fs.readFileSync(fullPath, 'utf-8');
} catch {
return null;
}
}
+30
View File
@@ -0,0 +1,30 @@
/**
* 그누보드7 에이전트 시스템 로거
*/
import pino from 'pino';
const level = process.env.LOG_LEVEL || 'info';
export const logger = pino({
level,
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'SYS:standard',
ignore: 'pid,hostname',
},
},
});
// 에이전트별 로거 생성
export function createAgentLogger(agentName: string) {
return logger.child({ agent: agentName });
}
// 워크플로우 로거 생성
export function createWorkflowLogger(workflowName: string) {
return logger.child({ workflow: workflowName });
}
export default logger;
@@ -0,0 +1,204 @@
/**
* 버그 수정 워크플로우
* TDD 기반: 버그 재현 테스트 → 수정 → 테스트 통과
*/
import { Coordinator } from '../coordinator/Coordinator.js';
import { createWorkflowLogger } from '../utils/logger.js';
import type { WorkflowResult } from '../types/index.js';
const workflowLogger = createWorkflowLogger('bugfix');
export type AffectedArea = 'backend' | 'frontend' | 'layout' | 'template' | 'unknown';
export interface BugfixOptions {
cwd?: string;
affectedAreas?: AffectedArea[];
skipTroubleshooting?: boolean;
}
/**
* 버그 수정 워크플로우 실행
*/
export async function bugfixWorkflow(
bugDescription: string,
options: BugfixOptions = {}
): Promise<WorkflowResult> {
workflowLogger.info(`Starting bugfix: ${bugDescription}`);
const { affectedAreas = ['unknown'], skipTroubleshooting = false } = options;
const coordinator = new Coordinator({
cwd: options.cwd,
model: 'sonnet',
});
// 영향 영역에 따른 에이전트 선택
const agentInstructions = getAgentInstructions(affectedAreas);
const prompt = `
버그를 수정해주세요: ${bugDescription}
## 작업 순서 (TDD 기반)
### 1. 트러블슈팅 가이드 확인
${skipTroubleshooting ? '(건너뛰기)' : `
- search-docs 도구로 유사 사례 검색
- docs/frontend/troubleshooting-guide.md 확인
- docs/frontend/troubleshooting-state.md (상태 관련)
- docs/frontend/troubleshooting-cache.md (캐시 관련)
- docs/frontend/troubleshooting-components.md (컴포넌트 관련)
`}
### 2. 버그 분석
- 버그 재현 조건 파악
- 영향 받는 파일 식별
- 근본 원인 분석
### 3. 버그 재현 테스트 작성 (TDD - RED)
- 버그를 재현하는 테스트 케이스 작성
- 테스트 실행하여 실패 확인
### 4. 버그 수정 (TDD - GREEN)
- 최소한의 변경으로 버그 수정
- 그누보드7 규정 준수
### 5. 테스트 실행 (TDD - REFACTOR)
- 작성한 테스트 통과 확인
- 기존 테스트도 모두 통과 확인
- 필요시 코드 정리
### 6. 검수
- 규정 준수 확인
- 부작용 없는지 확인
- 문서화
${agentInstructions}
## 중요 규칙
- 버그 재현 테스트 먼저 작성 (TDD)
- 최소한의 변경으로 수정
- 모든 테스트 통과 필수
- 유사 버그 재발 방지 고려
## 참조 문서
- docs/frontend/troubleshooting-guide.md
- docs/testing-guide.md
`;
try {
const result = await coordinator.orchestrate(prompt);
if (result.success) {
workflowLogger.info('Bugfix completed successfully');
} else {
workflowLogger.error(`Bugfix failed: ${result.errors?.join(', ')}`);
}
return result;
} catch (error: any) {
workflowLogger.error(`Bugfix error: ${error.message}`);
return {
success: false,
steps: [],
totalCost: 0,
errors: [error.message],
};
}
}
/**
* 영향 영역에 따른 에이전트 지시사항 생성
*/
function getAgentInstructions(areas: AffectedArea[]): string {
const instructions: string[] = [];
if (areas.includes('backend') || areas.includes('unknown')) {
instructions.push(`
### [backend] 백엔드 수정 시
- Service-Repository 패턴 준수
- 훅 실행 확인
- FormRequest 검증
- 테스트: php artisan test --filter=TestName
`);
}
if (areas.includes('frontend') || areas.includes('unknown')) {
instructions.push(`
### [frontend] 프론트엔드 수정 시
- HTML 태그 직접 사용 금지
- 다크 모드 클래스 쌍 확인
- G7Core.t() 다국어 처리
- 테스트: powershell -Command "npm run test:run"
`);
}
if (areas.includes('layout') || areas.includes('unknown')) {
instructions.push(`
### [layout] 레이아웃 수정 시
- text 속성 사용 (props.children 금지)
- 데이터 바인딩 문법 확인
- 다국어 키 형식 확인
- 갱신: php artisan template:refresh-layout
`);
}
if (areas.includes('template')) {
instructions.push(`
### [template] 템플릿 수정 시
- components.json 확인
- index.ts export 확인
- 빌드: php artisan template:build sirsoft-admin_basic
`);
}
return instructions.join('\n');
}
/**
* 상태 관련 버그 수정 (특화)
*/
export async function stateRelatedBugfix(
bugDescription: string,
options: { cwd?: string } = {}
): Promise<WorkflowResult> {
workflowLogger.info(`Starting state-related bugfix: ${bugDescription}`);
const coordinator = new Coordinator({
cwd: options.cwd,
model: 'sonnet',
});
const prompt = `
상태 관리 관련 버그를 수정해주세요: ${bugDescription}
## 필수 확인 사항 (troubleshooting-state.md 참조)
### 1. Stale Closure 문제
- setState 호출 후 즉시 상태 참조 시 이전 값 문제
- 해결: getter 함수, useRef, 또는 콜백 패턴 사용
### 2. sequence 내 setState 병합 문제
- 여러 setState가 하나로 병합되는 문제
- 해결: 별도 sequence로 분리 또는 직접 상태 조합
### 3. dot notation 충돌
- 깊은 경로 업데이트 시 데이터 손실
- 해결: 전체 객체 업데이트 또는 _merge 옵션
### 4. 타이밍 이슈
- API 응답과 setState 타이밍 불일치
- 해결: onSuccess/onError 콜백 사용
## 작업 순서
1. docs/frontend/troubleshooting-state.md 읽기
2. 유사 사례 확인
3. 버그 재현 테스트 작성
4. 수정 구현
5. 테스트 통과 확인
`;
return coordinator.orchestrate(prompt);
}
export default bugfixWorkflow;
@@ -0,0 +1,168 @@
/**
* 기능 개발 워크플로우
* Backend → Layout → Frontend → Template → Reviewer 순서로 실행
*/
import { Coordinator } from '../coordinator/Coordinator.js';
import { logger, createWorkflowLogger } from '../utils/logger.js';
import type { WorkflowResult } from '../types/index.js';
const workflowLogger = createWorkflowLogger('feature');
/**
* 기능 개발 워크플로우 실행
*/
export async function featureDevelopmentWorkflow(
featureDescription: string,
options: {
cwd?: string;
skipReview?: boolean;
} = {}
): Promise<WorkflowResult> {
workflowLogger.info(`Starting feature development: ${featureDescription}`);
const coordinator = new Coordinator({
cwd: options.cwd,
model: 'sonnet',
});
const prompt = `
새로운 기능을 개발해주세요: ${featureDescription}
## 작업 순서 (순차 실행)
### 1. [backend] 백엔드 구현
- 필요한 마이그레이션 생성 (php artisan make:migration)
- Model 생성/수정
- RepositoryInterface 및 Repository 구현
- Service 클래스 구현 (훅 실행 포함)
- FormRequest 검증 클래스
- Controller 구현
- 라우트 등록
### 2. [layout] 레이아웃 JSON 작성
- 데이터 소스 정의 (API 엔드포인트 연결)
- 컴포넌트 구조 설계
- 데이터 바인딩 설정
- 다국어 키 사용
### 3. [frontend] 컴포넌트 개발 (필요한 경우)
- 기존 컴포넌트로 해결 가능한지 먼저 확인
- 필요시 새 컴포넌트 개발
- 다크 모드 지원
- G7Core.t() 다국어 처리
### 4. [template] 템플릿 등록 및 빌드
- components.json 등록 (새 컴포넌트인 경우)
- index.ts export 추가
- 빌드 실행: php artisan template:build sirsoft-admin_basic
### 5. [reviewer] 최종 검수
- 백엔드 규정 준수 확인
- 프론트엔드 규정 준수 확인
- 테스트 실행 및 통과 확인
- 문서화 확인
## 중요 규칙
- 각 단계 완료 후 다음 에이전트에게 필요한 컨텍스트 전달
- 모든 작업은 그누보드7 프로젝트 규정(docs/) 준수
- 테스트 통과가 완료 조건
- 문서화 필수
## 참조 문서
- 백엔드: docs/backend/
- 프론트엔드: docs/frontend/
- 확장 시스템: docs/extension/
`;
try {
const result = await coordinator.orchestrate(prompt);
if (result.success) {
workflowLogger.info('Feature development completed successfully');
} else {
workflowLogger.error(`Feature development failed: ${result.errors?.join(', ')}`);
}
return result;
} catch (error: any) {
workflowLogger.error(`Feature development error: ${error.message}`);
return {
success: false,
steps: [],
totalCost: 0,
errors: [error.message],
};
}
}
/**
* 간단한 기능 추가 (단일 도메인)
*/
export async function simpleFeatureWorkflow(
featureDescription: string,
options: {
cwd?: string;
area: 'backend' | 'frontend' | 'layout' | 'template';
}
): Promise<WorkflowResult> {
const { area } = options;
workflowLogger.info(`Starting simple feature (${area}): ${featureDescription}`);
const coordinator = new Coordinator({
cwd: options.cwd,
model: 'sonnet',
});
const areaPrompts: Record<string, string> = {
backend: `
백엔드 기능을 구현해주세요: ${featureDescription}
작업 내용:
1. 필요한 파일 생성/수정
2. 그누보드7 백엔드 규정 준수 (Service-Repository 패턴, FormRequest, 훅)
3. 테스트 작성 및 실행
4. 문서화
참조: docs/backend/
`,
frontend: `
프론트엔드 컴포넌트를 개발해주세요: ${featureDescription}
작업 내용:
1. 컴포넌트 파일 생성
2. 그누보드7 프론트엔드 규정 준수 (기본 컴포넌트 사용, 다크 모드, 다국어)
3. components.json 등록
4. 테스트 작성 및 실행
참조: docs/frontend/components.md
`,
layout: `
레이아웃 JSON을 작성해주세요: ${featureDescription}
작업 내용:
1. 레이아웃 JSON 파일 생성
2. 그누보드7 레이아웃 규정 준수 (text 속성, 다국어, 다크 모드 클래스)
3. 데이터 소스 및 바인딩 설정
4. 레이아웃 갱신: php artisan template:refresh-layout
참조: docs/frontend/layout-json.md
`,
template: `
템플릿 컴포넌트를 등록하고 빌드해주세요: ${featureDescription}
작업 내용:
1. components.json에 컴포넌트 등록
2. index.ts에 export 추가
3. 빌드 실행: php artisan template:build sirsoft-admin_basic
참조: docs/frontend/template-development.md
`,
};
const result = await coordinator.orchestrate(areaPrompts[area]);
return result;
}
export default featureDevelopmentWorkflow;
@@ -0,0 +1,6 @@
/**
* 워크플로우 모듈 export
*/
export { featureDevelopmentWorkflow, simpleFeatureWorkflow } from './feature.js';
export { bugfixWorkflow, stateRelatedBugfix } from './bugfix.js';
export { prReviewWorkflow, reviewFiles } from './pr-review.js';
@@ -0,0 +1,198 @@
/**
* PR 검수 워크플로우
* 변경된 파일 유형에 따라 적절한 에이전트가 검수
*/
import { Coordinator } from '../coordinator/Coordinator.js';
import { createWorkflowLogger } from '../utils/logger.js';
import type { WorkflowResult } from '../types/index.js';
const workflowLogger = createWorkflowLogger('pr-review');
export interface PRReviewOptions {
cwd?: string;
baseBranch?: string;
skipTests?: boolean;
}
/**
* PR 검수 워크플로우 실행
*/
export async function prReviewWorkflow(
prIdentifier: string | number,
options: PRReviewOptions = {}
): Promise<WorkflowResult> {
workflowLogger.info(`Starting PR review: ${prIdentifier}`);
const { baseBranch = 'master', skipTests = false } = options;
const coordinator = new Coordinator({
cwd: options.cwd,
model: 'sonnet',
});
const prompt = `
PR을 검수해주세요: ${prIdentifier}
## 작업 순서
### 1. 변경 사항 분석
\`\`\`bash
# 변경된 파일 목록 확인
git diff --name-only ${baseBranch}...HEAD
# 변경 내용 확인
git diff ${baseBranch}...HEAD
\`\`\`
### 2. 파일 유형별 검수 할당
변경된 파일 확장자/경로에 따라 적절한 에이전트에게 검수 요청:
| 파일 패턴 | 담당 에이전트 |
|----------|--------------|
| app/**/*.php | [backend] |
| database/migrations/*.php | [backend] |
| templates/**/src/**/*.tsx | [frontend] |
| templates/**/layouts/**/*.json | [layout] |
| resources/layouts/**/*.json | [layout] |
| templates/**/components.json | [template] |
### 3. [backend] 백엔드 검수 (해당 시)
- [ ] RepositoryInterface 주입 확인
- [ ] Service 훅 실행 확인
- [ ] FormRequest 검증 규칙
- [ ] ResponseHelper 사용
- [ ] 마이그레이션 down() 구현
- [ ] 다국어 처리 (__())
### 4. [frontend] 프론트엔드 검수 (해당 시)
- [ ] HTML 태그 직접 사용 금지
- [ ] 다크 모드 클래스 쌍 지정
- [ ] G7Core.t() 다국어 처리
- [ ] Font Awesome 아이콘만 사용
- [ ] components.json 등록
### 5. [layout] 레이아웃 검수 (해당 시)
- [ ] text 속성 사용 (props.children 금지)
- [ ] 데이터 바인딩 문법 정확성
- [ ] 다국어 키 형식 ($t:)
- [ ] 다크 모드 클래스 쌍
### 6. [reviewer] 최종 검수
${skipTests ? '(테스트 건너뛰기)' : `
- 백엔드 테스트: php artisan test
- 프론트엔드 테스트: powershell -Command "npm run test:run"
`}
- 규정 준수 종합 확인
- 문서화 확인
## 검수 결과 형식
### 승인 시
\`\`\`
## 검수 결과: ✅ 승인
### 검증 항목
- [x] 백엔드 규정 준수
- [x] 프론트엔드 규정 준수
- [x] 테스트 통과
- [x] 문서화 완료
### 테스트 결과
- 백엔드: X passed
- 프론트엔드: Y passed
### 특이사항
- 없음
\`\`\`
### 변경 요청 시
\`\`\`
## 검수 결과: ❌ 변경 요청
### 발견된 문제점
1. [파일:라인] 문제 설명
- 규정: docs/...
- 해결: 구체적인 수정 방법
### 수정 권고사항
1. ...
### 참조 문서
- docs/...
\`\`\`
`;
try {
const result = await coordinator.orchestrate(prompt);
if (result.success) {
workflowLogger.info('PR review completed');
} else {
workflowLogger.error(`PR review failed: ${result.errors?.join(', ')}`);
}
return result;
} catch (error: any) {
workflowLogger.error(`PR review error: ${error.message}`);
return {
success: false,
steps: [],
totalCost: 0,
errors: [error.message],
};
}
}
/**
* 특정 파일만 검수
*/
export async function reviewFiles(
files: string[],
options: { cwd?: string } = {}
): Promise<WorkflowResult> {
workflowLogger.info(`Reviewing files: ${files.join(', ')}`);
const coordinator = new Coordinator({
cwd: options.cwd,
model: 'sonnet',
});
const fileList = files.map(f => `- ${f}`).join('\n');
const prompt = `
다음 파일들을 검수해주세요:
${fileList}
## 검수 항목
각 파일 유형에 맞는 그누보드7 규정 준수 여부를 확인하세요:
### PHP 파일
- validate-code 도구 사용
- Service-Repository 패턴
- FormRequest 검증
- 훅 시스템
### TSX 파일
- validate-frontend 도구 사용
- HTML 태그 사용 금지
- 다크 모드 클래스
- 다국어 처리
### JSON 레이아웃 파일
- validate-frontend 도구 사용
- text 속성 사용
- 데이터 바인딩 문법
- 다국어 키 형식
## 결과 형식
각 파일별로 검수 결과를 정리해주세요.
`;
return coordinator.orchestrate(prompt);
}
export default prReviewWorkflow;