Download src/agent-runner.js from VanyaJ/bada-terminal: direct link, hf CLI and curl.
- Browser
- Download file 28.6 kB
-
https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/agent-runner.js
- Command line
-
hf download hf://VanyaJ/bada-terminal/src/agent-runner.js
-
curl -L -o agent-runner.js https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/agent-runner.js
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 | |
| }; | |