const path = require('path'); const fs = require('fs'); const MAX_BUFFER_SIZE = 10 * 1024 * 1024; // 10MB 버퍼 크기 상한 설정 const ctx = require('./context'); const db = require('../knowledge-db'); const agentProfileManager = require('./agent-profile-manager'); const WikiJournalManager = require('./wiki-journal-manager'); const worktreeHelper = require('./utils/worktree-helper'); const ptyRunner = require('./agent-pty-runner'); const MemoryFacade = require('./memory-facade'); // 하네스 실행/판정/기록 핵심 로직의 단일 출처(loop-controller.js와 공유) const harnessExecutor = require('./harness-executor'); const { syncHarnessRunToMories } = harnessExecutor; // B2: 하네스 실행 결과 → 사람이 읽는 리시트 텍스트 (A1의 loop 리시트와 동일 순수 포매터 재사용) const { formatHarnessReceipt } = require('./receipt-formatter'); // 통합 메모리 파사드: 과거 런 이력 회수(리포트 + triage 진단)를 단일 진입점으로. // runHistorySearchAgent의 얕은 "최근 3건 slice + 리포트만" 회수를 대체한다. // [docs/HANDOVER_P8_AUTONOMOUS_AGENT.md §6 v1.0] let _memoryFacade = null; function getMemoryFacade() { if (!_memoryFacade) _memoryFacade = new MemoryFacade(); return _memoryFacade; } function setupPtyExitListener(ptyProc, callback) { if (typeof ptyProc.onExit === 'function') { return ptyProc.onExit(callback); } else if (typeof ptyProc.on === 'function') { ptyProc.on('exit', (exitCode, signal) => callback({ exitCode, signal })); return { dispose: () => {} }; } return { dispose: () => {} }; } // ── 세션 격리형 프로세스 브로커 상태 ─────────────────────────── const activeProcesses = new Map(); // runId -> Map const activeDiagnostics = require('./services/workflow-triage').activeProcesses; // ── Git Worktree 격리 (Worktrees) 헬퍼 ── async function createWorktree(projectCwd, runId, nodeId) { return worktreeHelper.createWorktree(projectCwd, runId, nodeId); } async function cleanupWorktree(projectCwd, wtPath, branchName, success, logStream) { return worktreeHelper.cleanupWorktree(projectCwd, wtPath, branchName, success, logStream); } // ── Checkpoint Branching 헬퍼 ── async function createCheckpointBranch(projectCwd, runId, logStream) { return worktreeHelper.createCheckpointBranch(projectCwd, runId, logStream); } async function restoreCheckpointBranch(projectCwd, runId, logStream) { return worktreeHelper.restoreCheckpointBranch(projectCwd, runId, logStream); } async function deleteCheckpointBranch(projectCwd, runId, logStream) { return worktreeHelper.deleteCheckpointBranch(projectCwd, runId, logStream); } function estimatePtyCost(promptText, outputText) { const inputTokens = Math.ceil((promptText || '').length / 3); const outputTokens = Math.ceil((outputText || '').length / 3); const cost = (inputTokens * 3.0 / 1000000) + (outputTokens * 15.0 / 1000000); return { cost, inputTokens, outputTokens, totalTokens: inputTokens + outputTokens, costSource: 'estimated', tokenSource: 'estimated' }; } // 진단도 원 실행의 비용·취소·종료 수명 안에서 기존 CLI 실행기를 사용한다. // docs/specs/workflow-triage-admission.md v1.1.0 function runAutoTriageDiagnostic(projectId, runId, errorMessage, workDir, run) { return require('./services/workflow-triage').run({ projectId, runId, errorMessage, workDir, owner: run }); } // ── 과거 정보 탐색 에이전트 (HistorySearchAgent) ── // 실행별 저널을 이력 원문/요약/기록에 함께 적용한다. docs/specs/workflow-wiki-context.md v1.0.0 async function runHistorySearchAgent(workflowId, currentRunId, logStream, projectId, journal = WikiJournalManager) { logStream.write(`[HistorySearchAgent] 과거 워크플로우 실행 이력 탐색 중...\n`); let runs = []; try { runs = db.getWorkflowRuns(workflowId) || []; } catch (dbErr) { logStream.write(`[HistorySearchAgent] 과거 런 목록 DB 조회 실패: ${dbErr.message}\n`); } const successfulRuns = []; const failedRuns = []; for (const r of runs) { if (r.run_id === currentRunId) continue; let data; try { data = typeof r.run_data === 'string' ? JSON.parse(r.run_data) : r.run_data; } catch(e) { continue; } const record = { runId: r.run_id, status: r.status, startedAt: r.started_at, completedAt: r.completed_at, variables: data, reportContext: '' }; if (r.status === 'completed') { successfulRuns.push(record); } else if (r.status === 'failed') { failedRuns.push(record); } } logStream.write(`[HistorySearchAgent] 탐색 완료: 성공 ${successfulRuns.length}건, 실패 ${failedRuns.length}건\n`); const selectedSuccess = successfulRuns.slice(0, 3); const selectedFailed = failedRuns.slice(0, 3); const referencedRunIds = [...selectedSuccess, ...selectedFailed].map(r => r.runId); const workflowsDir = journal.getWorkflowsDir(); const loadReportContext = (runId) => { try { const reportPath = path.join(workflowsDir, `workflow_report_${runId}.md`); if (fs.existsSync(reportPath)) { const raw = fs.readFileSync(reportPath, 'utf-8'); const contentOnly = raw.replace(/^---[\s\S]*?---\r?\n/m, ''); return contentOnly.trim(); } } catch(e) { logStream.write(`[HistorySearchAgent] 과거 보고서 ${runId} 읽기 실패: ${e.message}\n`); } return ''; }; selectedSuccess.forEach(r => { r.reportContext = loadReportContext(r.runId); }); selectedFailed.forEach(r => { r.reportContext = loadReportContext(r.runId); }); // MemoryFacade로 합성한 풍부한 이력 컨텍스트(성공/실패 분리 + 리포트 스니펫 + 실패 triage 진단). // 이것이 에이전트 프롬프트 주입의 1차 경로이며, 비어 있으면 호출자가 위 record 배열로 폴백한다. let historyContext = ''; try { historyContext = getMemoryFacade().getHistoryContext(projectId, workflowId, currentRunId, { limit: 3, journal }); } catch (e) { logStream.write(`[HistorySearchAgent] 이력 컨텍스트 합성 실패(폴백 사용): ${e.message}\n`); } journal.recordHistorySearch(currentRunId, { successCount: successfulRuns.length, failedCount: failedRuns.length, referencedRunIds }); try { db.saveNode(projectId, { id: `workflow_run:${currentRunId}`, type: 'workflow_run', label: `Workflow Run: ${currentRunId.substring(7)}`, properties: { category: 'workflow', status: 'running', runId: currentRunId } }); db.saveNode(projectId, { id: `workflow_journal:${currentRunId}`, type: 'workflow_journal', label: `Journal: ${currentRunId.substring(7)}`, properties: { category: 'workflow', file: `workflow_journal_${currentRunId}.md` } }); db.saveEdge(projectId, { source: `workflow_run:${currentRunId}`, target: `workflow_journal:${currentRunId}`, label: 'has_journal', properties: {} }); for (const refId of referencedRunIds) { const pastRun = runs.find(r => r.run_id === refId); db.saveNode(projectId, { id: `workflow_run:${refId}`, type: 'workflow_run', label: `Workflow Run: ${refId.substring(7)}`, properties: { category: 'workflow', status: (pastRun ? pastRun.status : 'completed'), runId: refId } }); db.saveEdge(projectId, { source: `workflow_run:${currentRunId}`, target: `workflow_run:${refId}`, label: 'referenced_history', properties: {} }); } } catch (e) { logStream.write(`[HistorySearchAgent] 지식 그래프 등록 실패: ${e.message}\n`); } return { successfulRuns: selectedSuccess, failedRuns: selectedFailed, historyContext }; } // ── 5-3. LLM Redesign Orchestrator (PTY) ── // [P15 A1] orchestrator 프리셋 로더 — 도메인별 프롬프트/폴백을 외부 JSON으로 분리. // 과거에는 배터리 도메인 프롬프트가 하드코딩되어 타 도메인 워크플로우에서 // 엉뚱한 배터리 전략이 생성되는 결함이 있었다. // 설계: docs/DESIGN_P15_MULTIAGENT_LOOP_IMPROVEMENTS.md §3 A1 (v1.1) let _orchestratorPresets = null; function loadOrchestratorPreset(domain) { if (!_orchestratorPresets) { try { _orchestratorPresets = require('./config/orchestrator-presets.json'); } catch (e) { // intentional: 프리셋 파일 손상 시에도 동작하도록 최소 generic 내장 폴백 _orchestratorPresets = { generic: { promptTemplate: '작업 분배 전략을 수립하라.\n실패 항목: {{failedItems}}\n격차: {{gaps}}\n현재: {{currentDesign}}\n목표: {{targetSpec}}\nJSON({"strategy","taskAssignments","constraints"})으로만 응답할 것.', fallbackStrategy: null } }; } } return _orchestratorPresets[domain] || _orchestratorPresets['generic']; } // 프롬프트 템플릿의 {{변수}}를 config 값(JSON 직렬화)으로 치환한다 function interpolateOrchestratorPrompt(template, vars) { return template.replace(/\{\{(\w+)\}\}/g, (m, key) => Object.prototype.hasOwnProperty.call(vars, key) ? JSON.stringify(vars[key]) : m); } async function runOrchestratorNode(run, node, config) { run.logStream.write(`[Orchestrator] Calling LLM Meta-Agent for tradeoffs analysis...\n`); const failedItems = config.failedItems || []; const gaps = config.gaps || {}; const currentDesign = config.currentDesign || {}; const targetSpec = config.target || {}; const nodeId = node.id; // [P15 A1] 프롬프트 3단 폴백: 사용자 정의 > 도메인 프리셋 > generic 기본 const domain = config.domain || 'generic'; const preset = loadOrchestratorPreset(domain); const promptVars = { failedItems, gaps, currentDesign, targetSpec }; const basePrompt = config.orchestrationPrompt ? interpolateOrchestratorPrompt(config.orchestrationPrompt, promptVars) : interpolateOrchestratorPrompt(preset.promptTemplate, promptVars); const prompt = require('./utils/agent-reply-language').append(basePrompt, run, node); run.logStream.write(`[Orchestrator] Domain preset: ${config.orchestrationPrompt ? 'custom' : domain}\n`); const profiles = agentProfileManager.loadProfiles().profiles || {}; if (config.agentProfileId && !profiles[config.agentProfileId]) throw new Error('Orchestrator agent profile not found: ' + config.agentProfileId); const profile = profiles[config.agentProfileId || 'default'] || {}; let cliCommand = profile.cliCommand || ctx.getActiveCli(); if (!config.agentProfileId && cliCommand === 'claude') cliCommand = ctx.getActiveCli(); const output = await require('./utils/cli-text-runner').runCliText({ usageOwner: run, cliCommand, cliArguments: profile.cliArguments || [], model: config.model || profile.model, prompt, cwd: run.workDir || ctx.currentCwd, signal: run.abortController?.signal, timeoutMs: Number.isFinite(config.timeoutMs) && config.timeoutMs > 0 ? config.timeoutMs : 60000, register: process => { if (!activeProcesses.has(run.runId)) activeProcesses.set(run.runId, new Map()); activeProcesses.get(run.runId).set(nodeId, process); }, unregister: () => activeProcesses.get(run.runId)?.delete(nodeId), onUsage: (usage, text) => { // CLI가 단가를 모르면 0을 실비로 확정하지 않는다. 예산 호환용 기존 추정은 별도 출처로 남긴다. const estimate = estimatePtyCost(prompt, text); const cost = usage.costUsd ?? Math.max(usage.reportedCostUsd || 0, estimate.cost); require('./utils/run-usage').recordUsage(run, cost, { ...usage, costSource: usage.costUsd === null ? 'estimated' : usage.costSource }); } }); return require('./utils/orchestrator-output').parseOrchestratorOutput(output); } // PTY 에이전트 실행 함수들은 ./agent-pty-runner.js 모듈로 분리됨 const { runAgentNode, runReviewerNode } = ptyRunner; // ── 5-4.5 Local Harness Execution Gate ── async function runHarnessNode(run, node, config) { const harnessId = config.harnessId; const parentAgentNodeId = config.parentAgentNodeId; const { prepareHarness, configurationError } = require('./config/harness-configuration'); if (!harnessId) throw configurationError('Harness Node에 harnessId가 지정되지 않았습니다.'); if (run.status !== 'running') { throw new Error('[Harness] Workflow run was cancelled or failed.'); } run.logStream.write(`[Harness] Loading harness configuration for "${harnessId}"...\n`); const harness = db.getHarness(harnessId); if (!harness) { throw configurationError(`하네스 설정을 데이터베이스에서 찾을 수 없습니다: ${harnessId}`); } // 설정 오류는 실행 시작 이력을 만들기 전에 차단한다. 상세 계약: // docs/specs/harness-validation.md v1.2.0 const parsedStages = prepareHarness(harness); // 실행 시작 전 원래 저장 정의를 고정한다. 현재 설정으로 과거 기록을 소급 인증하지 않는다. // docs/specs/bong-harness-proof.md v1.0.0 let definitionHash=null, modelWorkspace; try{ if(parsedStages?.some(stage=>stage.type==='model'))modelWorkspace=require('./services/harness-model-workspace').inspect(run,harness); definitionHash=require('./utils/harness-definition').fingerprint(harness);}catch(error){ if(parsedStages?.some(stage=>stage.type==='model'))throw Object.assign(error,{code:'HARNESS_MODEL_PROFILE',retryable:false}); if(config.expectedDefinitionHash)throw error; /* 레거시 명령의 프로젝트 정보 누락은 기존처럼 미확인으로 보존한다. */ } if(config.expectedDefinitionHash&&definitionHash!==config.expectedDefinitionHash)throw configurationError('승인한 완료 조건 하네스 정의가 변경됐습니다. 새 계획으로 검토해주세요.'); const remoteExecutor = require('./remote-harness-executor'); const remoteConfig = !parsedStages && remoteExecutor.remoteHarnessConfig(harness); const maxRetries = harness.max_retries ?? 3; const retryKey = `harness_${harnessId}_retry_count`; const currentRetry = run.runData[retryKey] || 0; const runId = 'hr_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7); run.logStream.write(`[Harness] Starting validation run ${currentRetry + 1}/${maxRetries + 1} (Command: "${harness.validation_command}")...\n`); // 사용자 완료 조건 파일을 검증 시작/종료에 대사한다. 누락은 PASS 대신 근거 미확인이다. // docs/specs/bong-goal-fulfillment.md v1.0.0 const goalEvidence=require('./services/goal-fulfillment-evidence'),goalEvidenceBefore=goalEvidence.captureHarness(db,run,harnessId); const harnessRunObj = { run_id: runId, harness_id: harnessId, workflow_run_id: run.runId, status: 'running', retry_count: currentRetry, logs: '', tool_chain: harness.tool_chain, definition_hash: definitionHash, created_at: new Date().toISOString() }; try { db.saveHarnessRun(harnessRunObj); } catch (dbErr) { run.logStream.write(`[Harness] Warning: Failed to save harness run record: ${dbErr.message}\n`); } let stdout = ''; let stderr = ''; let exitCode; let stagesResult = null; let harnessStop; // B1: harness.stages(다단계 게이트)가 있으면 순차 실행 경로로 분기한다(VHK verify 개념). // stages가 없으면(=전체 기존 하네스 데이터) 아래 else의 단일 validation_command 경로가 // 100% 기존과 동일하게 동작한다(재시도/타임아웃/롤백/DB/success_criteria 로직 모두 그대로). if (parsedStages) { run.logStream.write(`[Harness] Multi-stage validation gate: ${parsedStages.length} stage(s)...\n`); if (!activeProcesses.has(run.runId)) { activeProcesses.set(run.runId, new Map()); } // 각 stage는 checkCommandSafety(블랙리스트)+runHarnessCommand로 실행. required 실패 시 조기 종료. try { stagesResult = await harnessExecutor.runHarnessStages({ stages: parsedStages, usageOwner: run, modelWorkspace, beforeModelSpawn: () => { let current; try { const currentHarness=db.getHarness(harnessId); const scope=require('./services/harness-model-workspace').inspect(run,currentHarness); if(scope.scopeHash===modelWorkspace.scopeHash)current=require('./utils/harness-definition').fingerprint(currentHarness); } catch { /* 읽기 실패도 이전 승인과 같다고 추정하지 않는다. */ } if (current !== definitionHash) throw Object.assign(new Error('Model harness definition changed before submission'), { code: 'HARNESS_MODEL_PROFILE', retryable: false }); }, cwd: (run.workDir || ctx.currentCwd), timeoutMs: 60000, signal: run.abortController?.signal, errorPrefix: '[Harness] ', applyBlacklist: true, onData: (chunk) => { if (run.logStream && run.logStream.writable) { run.logStream.write(chunk); } }, shouldCancel: () => run.status !== 'running', registerProcess: (proc) => { activeProcesses.get(run.runId).set(node.id, proc); }, unregisterProcess: () => { const procMap = activeProcesses.get(run.runId); if (procMap) procMap.delete(node.id); } }); } catch (error) { if (!require('./services/harness-stop-error').isHarnessStop(error) || !error.harnessResult) throw error; harnessStop = error; stagesResult = error.harnessResult; } // stage별 결과를 로그로 남기고, 다운스트림(재시도/롤백/DB) 호환을 위해 exitCode를 0/1로 요약한다. for (const st of stagesResult.stages) { const tag = st.status === 'passed' ? 'PASS' : (st.status === 'skipped' ? 'SKIP' : 'FAIL'); run.logStream.write(`[Harness] Stage "${st.name}" [${st.required ? 'required' : 'optional'}]: ${tag}${st.exitCode !== null ? ` (exit ${st.exitCode})` : ''}\n`); stdout += `\n[Stage:${st.name}] ${st.stdout || ''}`; if (st.stderr) stderr += `\n[Stage:${st.name}] ${st.stderr}`; } exitCode = stagesResult.success ? 0 : 1; if (!stagesResult.success && stagesResult.failedStage) { run.logStream.write(`[Harness] Multi-stage gate FAILED at required stage "${stagesResult.failedStage}".\n`); } } else if (remoteConfig) { // 루프와 같은 URL/화면 판정 및 요청 취소를 사용한다. // docs/specs/remote-harness-validation.md v1.0.0 try { const result = await remoteExecutor.runRemoteHarness(harness, { timeoutMs: 60000, signal: run.abortController?.signal, shouldCancel: () => run.status !== 'running' }); exitCode = result.success ? 0 : 1; stdout = result.stdout; stderr = result.stderr; } catch (error) { exitCode = -1; stderr = error.message; } } else { // ── 기존 단일 명령 경로 ── // C-4: 셸 인젝션 방어(블랙리스트 + isSafeShellCommand) — harness-executor 단일 출처 if (harness.validation_command) { const safety = harnessExecutor.checkCommandSafety(harness.validation_command, { applyBlacklist: true }); if (!safety.safe) { throw new Error(`[Harness] Security Blocked: ${safety.reason}`); } } try { if (!activeProcesses.has(run.runId)) { activeProcesses.set(run.runId, new Map()); } // H-8: 60초 타임아웃 가드 + 취소 폴링(run.status) + 로그 스트리밍 // windowsShell 미지정 → 기본 'powershell'(agent-runner 원본과 동일, 변경 없음) const result = await harnessExecutor.runHarnessCommand({ command: harness.validation_command, cwd: (run.workDir || ctx.currentCwd), timeoutMs: 60000, signal: run.abortController?.signal, errorPrefix: '[Harness] ', onData: (chunk) => { if (run.logStream && run.logStream.writable) { run.logStream.write(chunk); } }, shouldCancel: () => run.status !== 'running', registerProcess: (proc) => { activeProcesses.get(run.runId).set(node.id, proc); }, unregisterProcess: () => { const procMap = activeProcesses.get(run.runId); if (procMap) procMap.delete(node.id); } }); exitCode = result.exitCode; stdout = result.stdout; stderr = result.stderr; } catch (cmdErr) { // WHY(LOW-1): 원본은 stdout/stderr가 외부 스코프 변수라 타임아웃/취소 시에도 이미 수신된 // 부분 출력이 보존됐다. 모듈은 내부 클로저에 stdout/stderr를 갖고 있으므로 reject된 // Error 객체에 실린 부분 출력(err.stdout/err.stderr)을 복원해 동일하게 유지한다. exitCode = -1; stdout = cmdErr.stdout || stdout; stderr = (cmdErr.stderr || stderr) + '\nExecution Error: ' + cmdErr.message; } } const fullLog = stdout + '\n' + stderr; let isSuccess = (exitCode === 0); // exitCode===0 이후 success_criteria.regex_match 추가 판정 (ReDoS 방지 포함) // 위험하거나 해석할 수 없는 기준은 실패다. 단일 명령에만 적용하고, // 다단계 경로 판정은 각 required stage 통과 여부로 결정한다. if (!parsedStages && !remoteConfig && isSuccess && harness.success_criteria) { const criteriaResult = harnessExecutor.evaluateSuccessCriteria(harness.success_criteria, fullLog, { redosFailsCriteria: false }); if (!criteriaResult.pass) { isSuccess = false; run.logStream.write(`[Harness] Validation failed: ${criteriaResult.error}\n`); } else if (criteriaResult.error) { run.logStream.write(`[Harness] Success criteria parsing failed: ${criteriaResult.error}\n`); } } const goalEvidenceAfter=goalEvidence.captureHarness(db,run,harnessId); harnessRunObj.goal_evidence=goalEvidenceBefore&&require('./services/goal-plan-review').hash(goalEvidenceBefore)===require('./services/goal-plan-review').hash(goalEvidenceAfter)?goalEvidenceAfter:null; harnessRunObj.logs = fullLog; harnessRunObj.completed_at = new Date().toISOString(); // B2: stagesResult가 있으면(다단계 하네스) stage별 구조화 결과를 JSON으로 저장하고, // 단일-커맨드 하네스는 stage_results를 null로 남겨 기존 동작(구조화 기록 없음)을 그대로 보존한다. // WHY: 이 시점(isSuccess 최종 판정 이후)에서만 리시트/stage_results를 채운다 — 순수 확장이며 // status/retry_count/logs/tool_chain 등 기존 저장 필드와 그 계산 로직은 건드리지 않는다. harnessRunObj.stage_results = stagesResult ? JSON.stringify(stagesResult.stages) : null; harnessRunObj.receipt_summary = formatHarnessReceipt({ harnessName: harness.name, validationCommand: harness.validation_command, success: isSuccess, exitCode, retryCount: harnessRunObj.retry_count, stages: stagesResult ? stagesResult.stages : null, failedStage: stagesResult ? stagesResult.failedStage : null }); const executionTimeMs = Date.now() - new Date(harnessRunObj.created_at).getTime(); const summaryStr = isSuccess ? `Validation PASSED successfully. exitCode: ${exitCode}` : `Validation FAILED. exitCode: ${exitCode}. Error logs: ${fullLog.substring(0, 1000)}`; // Fire-and-forget sync to Mories if (!harnessStop) syncHarnessRunToMories(harnessId, isSuccess, executionTimeMs, summaryStr, harness.tool_chain, run.logStream); if (isSuccess) { harnessRunObj.status = 'success'; try { db.saveHarnessRun(harnessRunObj); } catch (dbErr) { run.logStream.write(`[Harness] Warning: Failed to save harness run record: ${dbErr.message}\n`); } run.logStream.write(`[Harness] Validation PASSED successfully!\n`); delete run.runData[`harness_${node.id}`]; // stagesResult가 있으면 stage별 구조화 결과를 함께 반환한다(B2에서 harness_runs 기록/리시트에 사용). return { success: true, exitCode, stdout, stderr, ...(stagesResult ? { stages: stagesResult.stages } : {}) }; } else { harnessRunObj.status = 'failed'; try { db.saveHarnessRun(harnessRunObj); } catch (dbErr) { run.logStream.write(`[Harness] Warning: Failed to save harness run record: ${dbErr.message}\n`); } run.logStream.write(`[Harness] Validation FAILED (Exit Code: ${exitCode}).\n`); // 비용·소유·취소 실패는 이력만 남기고 maker 재실행/자동 진단으로 바꾸지 않는다. // 설명 문서: docs/specs/harness-model-stage.md (v1.0.0) if (harnessStop) throw harnessStop; if (currentRetry < maxRetries) { run.runData[retryKey] = currentRetry + 1; run.runData[`harness_${node.id}`] = { parentAgentNodeId, errorLog: fullLog }; const parentIdx = run.sortedNodeIds.indexOf(parentAgentNodeId); if (parentIdx >= 0) { run.logStream.write(`[Harness] Evolution loop triggered! Re-scheduling agent node "${parentAgentNodeId}" (Retry ${currentRetry + 1}/${maxRetries})...\n`); run.currentNodeIndex = parentIdx - 1; return { success: false, evolved: true }; } else { run.logStream.write(`[Harness] Warning: Parent agent node "${parentAgentNodeId}" not found in sorted node list.\n`); } } // 공유 작업 폴더에는 실행 전 변경과 사용자의 동시 편집이 있을 수 있다. // 실패한 산출물은 진단용으로 남기고, 격리 worktree의 폐기는 소유 실행기가 담당한다. run.logStream.write('[Harness] Retries exhausted. Working files preserved for inspection.\n'); throw new Error('[Harness] 장기 작업 검증 실패: 최대 재시도 횟수 초과. 작업 파일은 보존되었습니다.'); } } function isPromptReady(cleanBuffer) { const lines = cleanBuffer.split(/\r?\n/); for (let i = lines.length - 1; i >= 0; i--) { const line = lines[i].trim(); if (!line) continue; // 팁 문구와 함께 프롬프트가 한 라인으로 제공될 때(예: '❯ Try "..."')에 대비하여 includes로 판정 확장. // HUD 팁 문구 필터링보다 우선 적용하여 FSM 오탐 및 30초 초기화 타임아웃을 방지합니다. // 일반 > 기호는 가이드 텍스트 등에서의 오탐을 막기 위해 행 끝에 위치하는 경우로 제한합니다. if (line.includes('❯') || line.endsWith('>') || />\s*$/.test(line)) { return true; } // Skip separator lines if (/^[─\-═\s·•]+$/.test(line)) { continue; } // Skip HUD/status lines if (line.includes('bypass') || line.includes('permissions') || line.includes('OMC HUD') || line.includes('omc-setup') || line.includes('Boondoggling') || line.includes('Thinking') || line.includes('Cogitated') || line.includes('effort') || line.includes('control this session') || line.includes('shift+tab') || line.includes('bypasspermissionson')) { continue; } return false; } return false; } function stripAnsi(str) { // 실제 ESC/BEL 제어 프레임만 제거하며 일반 출력 문자는 유지한다. // eslint-disable-next-line no-control-regex const ansiRegex = /[\u001b\u009b]\[[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|[\u001b\u009b]\][^\u0007]*\u0007/g; return str.replace(ansiRegex, ''); } // syncHarnessRunToMories 는 ./harness-executor 모듈로 이관되어 상단에서 import 한다. // PTY runner 모듈 초기화 (공유 헬퍼 주입) ptyRunner.init({ setupPtyExitListener, createWorktree, cleanupWorktree, createCheckpointBranch, estimatePtyCost, isPromptReady, stripAnsi, activeProcesses, MAX_BUFFER_SIZE }); module.exports = { // [P15 A1] 테스트 전용 노출(프리셋 해석·프롬프트 치환) — 프로덕션 코드는 사용 금지 _test: { loadOrchestratorPreset, interpolateOrchestratorPrompt }, activeProcesses, activeDiagnostics, createWorktree, cleanupWorktree, createCheckpointBranch, restoreCheckpointBranch, deleteCheckpointBranch, estimatePtyCost, runAutoTriageDiagnostic, runHistorySearchAgent, runOrchestratorNode, runAgentNode, runReviewerNode, runHarnessNode };