bada-terminal / src /agent-runner.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
28.6 kB
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<agentId, ProcessRef>
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
};