bada-terminal / src /workflow /node-dispatch.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
24.1 kB
// ๋ธŒ๋ผ์šฐ์ € ์˜ˆ์‚ฐ ์ •์ง€ drain: docs/specs/bong-browser-use.md (v1.4.0)
// ์„ค๋ช… ๋ฌธ์„œ: docs/specs/bada-code-quality.md (v1.0.0)
// ์‹คํ–‰ ์ƒํƒœ ๋งต์€ ์—”์ง„์ด ์†Œ์œ ํ•˜๊ณ  ์ด ๋ชจ๋“ˆ์€ ์ง€์ •๋œ ์ฑ…์ž„๋งŒ ์ฒ˜๋ฆฌํ•œ๋‹ค.
const db = require('../../knowledge-db');
const { isUncertainCliFailure } = require('../utils/cli-storage-error');
const agentRunner = require('../agent-runner');
function createNodeDispatch(dependencies) {
const { activeRuns, log, syncAgentsMd } = dependencies;
return {
async onNodeTrigger(runId) {
const run = activeRuns.get(runId);
if (!run || run.status !== 'running') return;
if (run.isExecuting) {
if (run.logStream && run.logStream.writable) {
run.logStream.write(`[Engine] Warning: Concurrency guard blocked re-entry trigger for run ${runId}\n`);
}
return;
}
run.isExecuting = true;
let nodeId = '';
let nodeName = 'Unknown Node';
let taskId = null;
let node = null;
try {
if (run.currentNodeIndex >= run.sortedNodeIds.length) {
this.completeWorkflow(runId);
return;
}
nodeId = run.sortedNodeIds[run.currentNodeIndex];
// Skip sequential execution of child nodes that ran in parallel
if (run.parallelExecutedNodeIds && run.parallelExecutedNodeIds.has(nodeId)) {
run.logStream.write(`[Engine] Skipping Node "${nodeId}" because it was already executed in parallel.\n`);
run.parallelExecutedNodeIds.delete(nodeId);
run.currentNodeIndex++;
setImmediate(() => this.emit('node:trigger', runId));
return;
}
node = run.nodes.find(n => n.id === nodeId);
if (!node) {
this.handleWorkflowFailure(runId, new Error(`๋…ธ๋“œ '${nodeId}'๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.`));
return;
}
nodeName = node.name;
require("../services/runtime-usage-ledger").refresh(run);
require("../services/runtime-usage-ledger").checkAncestors(run);
// Budget Guard
const isAgentType = ['agent', 'pty_agent', 'orchestrator', 'reviewer'].includes(node.type);
if (isAgentType) {
run.agentRunCount = (run.agentRunCount || 0) + 1;
let graph = {};
try {
const runRecord = db.getWorkflowRun ? db.getWorkflowRun(runId) : null;
const workflow = runRecord ? db.getWorkflow(runRecord.workflow_id) : null;
graph = workflow && typeof workflow.graph_json === 'string' ? JSON.parse(workflow.graph_json) : (workflow?.graph || {});
} catch (e) {
graph = {};
}
const maxAgentRuns = node.config?.maxAgentRuns || graph.maxAgentRuns || 5;
if (run.agentRunCount > maxAgentRuns) {
run.status = 'pausing';
run.logStream.write(`[Engine] Agent run budget exceeded (${run.agentRunCount} > ${maxAgentRuns}). Pausing workflow run.\n`);
try {
db.saveTriageItem(run.projectId, {
run_id: run.runId,
source_type: 'workflow',
error_message: `Budget Exceeded: Agent run limit reached (${maxAgentRuns} runs)`,
ai_analysis: `### ๐Ÿšจ Budget Exceeded (์˜ˆ์‚ฐ ์ดˆ๊ณผ)\n- **์‚ฌ์œ **: ์—์ด์ „ํŠธ ์‹คํ–‰ ํ•œ๋„(${maxAgentRuns}ํšŒ)๋ฅผ ์ดˆ๊ณผํ•˜์—ฌ ์ž๋™ ์ผ์‹œ์ •์ง€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.\n- **ํ•ด๊ฒฐ ๋ฐฉ์•ˆ**: ์›Œํฌํ”Œ๋กœ์šฐ ๋ฃจํ”„ ์„ค๊ณ„๋ฅผ ๊ฒ€ํ† ํ•˜๊ฑฐ๋‚˜ ํ•œ๋„ ๊ฐ’์„ ์ƒํ–ฅ ์กฐ์ •ํ•˜์‹ญ์‹œ์˜ค.\n\n**์ตœ๊ทผ ์ƒํƒœ**: ๋ฃจํ”„๋ฐฑ ํšŸ์ˆ˜๊ฐ€ ์ดˆ๊ณผ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.`,
status: 'pending'
});
} catch (dbErr) {
log.error('[Engine] Failed to save budget exceeded triage item:', dbErr);
}
this.emit('node:progress', { runId, nodeId, status: 'pausing', error: 'Agent run budget exceeded' });
run.journal.appendStep(runId, `[Engine] Agent ์‹คํ–‰ ํ•œ๋„(${maxAgentRuns}ํšŒ) ์ดˆ๊ณผ๋กœ ์ž‘์—…์ด ์ผ์‹œ์ •์ง€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.`);
await this.suspendWorkflowRun(runId, Object.assign(new Error('Agent run budget exceeded'), { code: 'WORKFLOW_PAUSED' }));
return;
}
// Token Cost Budget Guard
const maxBudget = node.config?.maxBudget || graph.maxBudget || 1.0;
if ((run.cumulativeCost || 0) > maxBudget) {
run.status = 'pausing';
run.logStream.write(`[Engine] Token budget exceeded ($${(run.cumulativeCost || 0).toFixed(4)} > $${maxBudget.toFixed(2)}). Pausing workflow run.\n`);
try {
db.saveTriageItem(run.projectId, {
run_id: run.runId,
source_type: 'workflow',
error_message: `Budget Exceeded: Token budget limit reached ($${maxBudget.toFixed(2)})`,
ai_analysis: `### ๐Ÿšจ Budget Exceeded (ํ† ํฐ ์˜ˆ์‚ฐ ์ดˆ๊ณผ)\n- **์‚ฌ์œ **: ๋ˆ„์  ํ† ํฐ ๋น„์šฉ($${(run.cumulativeCost || 0).toFixed(4)})์ด ์„ค์ •๋œ ํ•œ๋„($${maxBudget.toFixed(2)})๋ฅผ ์ดˆ๊ณผํ•˜์—ฌ ์ž๋™ ์ผ์‹œ์ •์ง€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.\n- **ํ•ด๊ฒฐ ๋ฐฉ์•ˆ**: API ์‚ฌ์šฉ๋Ÿ‰์„ ๊ฒ€ํ† ํ•˜๊ฑฐ๋‚˜ ์˜ˆ์‚ฐ ํ•œ๋„(maxBudget) ๊ฐ’์„ ๋Š˜๋ฆฌ์‹ญ์‹œ์˜ค.\n\n**์ตœ๊ทผ ์ƒํƒœ**: ๋ˆ„์  ์‹คํ–‰ ๋น„์šฉ์ด ์ดˆ๊ณผ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.`,
status: 'pending'
});
} catch (dbErr) {
log.error('[Engine] Failed to save budget exceeded triage item:', dbErr);
}
this.emit('node:progress', { runId, nodeId, status: 'pausing', error: 'Token budget exceeded' });
run.journal.appendStep(runId, `[Engine] ํ† ํฐ ์˜ˆ์‚ฐ ํ•œ๋„($${maxBudget.toFixed(2)}) ์ดˆ๊ณผ๋กœ ์ž‘์—…์ด ์ผ์‹œ์ •์ง€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.`);
await this.suspendWorkflowRun(runId, Object.assign(new Error('Token budget exceeded'), { code: 'WORKFLOW_PAUSED' }));
return;
}
}
// Workflow Run Budget Guard (B1)
if (run.runBudgetUsd && run.usage && (run.usage.costUsd || 0) >= run.runBudgetUsd) {
if (run.logStream && run.logStream.writable) {
run.logStream.write(`[Engine] Workflow run budget exceeded ($${(run.usage.costUsd || 0).toFixed(4)} >= $${run.runBudgetUsd.toFixed(2)}). Terminating workflow run.\n`);
}
try {
db.saveTriageItem(run.projectId, {
run_id: run.runId,
source_type: 'workflow',
error_message: `BUDGET_EXCEEDED: run budget limit reached ($${run.runBudgetUsd.toFixed(2)})`,
ai_analysis: `### ๐Ÿšจ Budget Exceeded (๋Ÿฐ ์˜ˆ์‚ฐ ์ดˆ๊ณผ)\n- **์‚ฌ์œ **: ๋ˆ„์  ์‹คํ–‰ ๋น„์šฉ($${(run.usage.costUsd || 0).toFixed(4)})์ด ์„ค์ •๋œ ๋Ÿฐ ์˜ˆ์‚ฐ ํ•œ๋„($${run.runBudgetUsd.toFixed(2)})๋ฅผ ๋‹ฌ์„ฑ/์ดˆ๊ณผํ•˜์—ฌ ์‹คํŒจ ์ฒ˜๋ฆฌ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.\n- **ํ•ด๊ฒฐ ๋ฐฉ์•ˆ**: ์˜ˆ์‚ฐ ์„ค์ •์„ ๊ฒ€ํ† ํ•˜๊ฑฐ๋‚˜ ๋น„์šฉ์„ ์ƒํ–ฅ ์กฐ์ •ํ•˜์‹ญ์‹œ์˜ค.`,
status: 'pending'
});
} catch (dbErr) {
log.error('[Engine] Failed to save workflow run budget exceeded triage item:', dbErr);
}
this.emit('node:progress', { runId, nodeId, status: 'failed', error: 'BUDGET_EXCEEDED' });
run.journal.appendStep(runId, `[Engine] ๋Ÿฐ ์˜ˆ์‚ฐ ํ•œ๋„($${run.runBudgetUsd.toFixed(2)}) ์ดˆ๊ณผ๋กœ ์ž‘์—…์ด ์‹คํŒจ ์ค‘๋‹จ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.`);
this.handleWorkflowFailure(runId, Object.assign(new Error(`BUDGET_EXCEEDED: run budget limit reached ($${run.runBudgetUsd.toFixed(2)})`), { code: 'BUDGET_EXCEEDED' }));
return;
}
run.currentNodeId = nodeId;
syncAgentsMd(run);
try {
db.checkpointWorkflowRun(runId, 'running', nodeId, run.runData);
} catch (dbErr) {
run.logStream.write(`[Engine] Checkpoint database write failed: ${dbErr.message}\n`);
dbErr.code = 'WORKFLOW_CHECKPOINT';
throw dbErr;
}
run.logStream.write(`\n[Node ${run.currentNodeIndex + 1}/${run.sortedNodeIds.length}] Executing: ${node.name} (${node.type})\n`);
this.emit('node:progress', { runId, nodeId, status: 'running', name: node.name });
run.journal.appendStep(runId, `๋…ธ๋“œ [${node.name}] (${node.type}) ์‹คํ–‰์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.`);
const taskQuestion = node.config ? (node.config.prompt || `Run step ${node.name} (${node.type})`) : `Run step ${node.name}`;
const incomingEdges = run.edges.filter(e => e.target === nodeId);
run.nodeTasks = run.nodeTasks || {};
const parentTaskIds = incomingEdges.map(e => run.nodeTasks[e.source]).filter(Boolean);
const agentId = (node.config && (node.config.agentProfileId || node.config.agentId)) || node.type;
taskId = 'task_' + runId + '_' + nodeId + '_' + Date.now();
run.nodeTasks[nodeId] = taskId;
// NATS ๋™์  ๊ตฌ๋… ํ™œ์„ฑํ™”
try {
const natsManager = require("../services/bada-nats-manager");
natsManager.subscribeAgentMessages(runId, agentId);
} catch (natsErr) {
log.warn('Failed to register dynamic NATS subscriber', null, natsErr);
}
run.journal.createTaskNote(runId, taskId, agentId, taskQuestion, parentTaskIds);
try {
db.enqueueWorkflowTask(taskId, runId, nodeId, agentId, node.config || {});
db.completeWorkflowTask(taskId, 'running', null, null);
} catch (dbErr) {
log.error('[Engine] Failed to write task to DB:', dbErr.message);
}
const interpolatedConfig = this.interpolate(node.config || {}, run.runData);
let evolutionContext = '';
for (const [key, val] of Object.entries(run.runData)) {
if (key.startsWith('harness_') && val && val.parentAgentNodeId === nodeId && val.errorLog) {
evolutionContext += `\n\nโš ๏ธ [์ด์ „ ๊ฒ€์ฆ ์‹คํŒจ ํ”ผ๋“œ๋ฐฑ ๋ฐ ์ง„ํ™” ๋กœ๊ทธ] โš ๏ธ\n์ด์ „ ์‹คํ–‰์˜ ๊ฒ€์ฆ ๊ฒฐ๊ณผ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ์•„๋ž˜ ์—๋Ÿฌ ๋กœ๊ทธ๋ฅผ ๋ถ„์„ํ•˜์—ฌ ์›์ธ์„ ์ˆ˜์ •ํ•˜์‹ญ์‹œ์˜ค:\n- ์—๋Ÿฌ ๋กœ๊ทธ:\n${val.errorLog}\n`;
}
}
if (evolutionContext) {
interpolatedConfig.prompt = (interpolatedConfig.prompt || '') + evolutionContext;
run.logStream.write(`[Engine] Evolved failure context injected for node "${nodeId}"\n`);
}
let reviewerContext = '';
for (const [key, val] of Object.entries(run.runData)) {
if (key.startsWith('reviewer_') && key.endsWith('_feedback') && val) {
const reviewerId = key.substring('reviewer_'.length, key.length - '_feedback'.length);
const hasEdge = run.edges.some(e => e.source === nodeId && e.target === reviewerId);
if (hasEdge) {
reviewerContext += `\n\nโš ๏ธ [๋ฆฌ๋ทฐ์–ด ๋ฐ˜๋ ค ํ”ผ๋“œ๋ฐฑ] โš ๏ธ\n์ด์ „ ๊ตฌํ˜„์— ๋Œ€ํ•ด ๋ฆฌ๋ทฐ์–ด ์—์ด์ „ํŠธ(${reviewerId})๊ฐ€ ๋ฐ˜๋ คํ–ˆ์Šต๋‹ˆ๋‹ค. ์•„๋ž˜ ํ”ผ๋“œ๋ฐฑ์„ ์ฐธ๊ณ ํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•˜์‹ญ์‹œ์˜ค:\n- ํ”ผ๋“œ๋ฐฑ:\n${val}\n`;
}
}
}
if (reviewerContext) {
interpolatedConfig.prompt = (interpolatedConfig.prompt || '') + reviewerContext;
run.logStream.write(`[Engine] Reviewer feedback context injected for node "${nodeId}"\n`);
}
if (node.type === 'orchestrator' || node.type === 'agent' || node.type === 'pty_agent') {
const history = await agentRunner.runHistorySearchAgent(run.workflowId, run.runId, run.logStream, run.projectId, run.journal);
if (history.successfulRuns.length > 0 || history.failedRuns.length > 0) {
const header = `\n\n=== [๊ณผ๊ฑฐ ์ •๋ณด ํƒ์ƒ‰ ์—์ด์ „ํŠธ ์ œ๊ณต] ์ด์ „ ์‹คํ–‰ ์ด๋ ฅ ๋ฐ ์˜์‚ฌ๊ฒฐ์ • ์ธ๊ณผ๊ด€๊ณ„ ===\n`;
const footer = `\n==========================================================\n`;
let body;
if (history.historyContext && history.historyContext.trim()) {
// 1์ฐจ ๊ฒฝ๋กœ: MemoryFacade๊ฐ€ ํ•ฉ์„ฑํ•œ ์ปจํ…์ŠคํŠธ(๋ฆฌํฌํŠธ ์Šค๋‹ˆํŽซ + ์‹คํŒจ triage ์ง„๋‹จ ํฌํ•จ)
body = history.historyContext;
} else {
// ํด๋ฐฑ: record ๋ฐฐ์—ด์—์„œ ๋ณ€์ˆ˜ ์ƒํƒœ + ๋ฆฌํฌํŠธ ๋ณธ๋ฌธ์„ ์ง์ ‘ ์กฐ๋ฆฝ
body = '';
history.successfulRuns.forEach(r => {
body += `- [์„ฑ๊ณต ๋Ÿฐ: ${r.runId}] ๋ณ€์ˆ˜ ์ƒํƒœ: ${JSON.stringify(r.variables)}\n`;
if (r.reportContext) body += ` ์ด์ „ ์‹คํ–‰ ์ธ๊ณผ ๋ถ„์„:\n${r.reportContext}\n`;
});
history.failedRuns.forEach(r => {
body += `- [์‹คํŒจ ๋Ÿฐ: ${r.runId}] ๋ณ€์ˆ˜ ์ƒํƒœ: ${JSON.stringify(r.variables)}\n`;
if (r.reportContext) body += ` ์ด์ „ ์‹คํ–‰ ์ธ๊ณผ ๋ถ„์„:\n${r.reportContext}\n`;
});
}
interpolatedConfig.prompt = (interpolatedConfig.prompt || '') + header + body + footer;
}
}
const provId = 'prov_' + runId + '_' + nodeId + '_' + Date.now();
const parentNodeIds = incomingEdges.map(e => e.source);
// [NiFi Provenance] ๋…ธ๋“œ ์‹คํ–‰ ์ „ ์ž…๋ ฅ ๋ฐ์ดํ„ฐ ์Šค๋ƒ…์ƒท ๊ธฐ๋ก
try {
db.saveWorkflowProvenance({
id: provId,
run_id: runId,
node_id: nodeId,
parent_node_ids: parentNodeIds,
input_flow_file: run.runData,
status: 'running',
started_at: new Date().toISOString()
});
} catch (provErr) {
run.logStream.write(`[Provenance Engine] Failed to save initial provenance: ${provErr.message}\n`);
}
run.runData[`node_timeline_${nodeId}`] = {
startedAt: new Date().toISOString(),
endedAt: null,
agentProfile: node.config?.agentProfileId || node.config?.agent_profile_id || null
};
let output = null;
let attempt = 0;
const maxAttempts = (node.config && typeof node.config.retry_count === 'number') ? node.config.retry_count + 1 : 1;
const retryDelay = (node.config && typeof node.config.retry_delay === 'number') ? node.config.retry_delay : 5;
while (attempt < maxAttempts) {
try {
run.abortController?.signal.throwIfAborted();
attempt++;
if (attempt > 1) {
run.logStream.write(`[Engine] Retrying node "${nodeId}" (Attempt ${attempt}/${maxAttempts}) in ${retryDelay}s...\n`);
await require('timers/promises').setTimeout(retryDelay * 1000, undefined, { signal: run.abortController?.signal });
try {
db.saveWorkflowProvenance({
id: provId,
run_id: runId,
node_id: nodeId,
status: 'running',
retry_count: attempt - 1
});
} catch (e) { /* intentional: ํŒŒ์ผ ์กฐํšŒ ์‹คํŒจ ์‹œ ๋ฌด์‹œ */ }
}
output = await require('./node-operation').execute(run, node, () => this.executeNode(run, node, interpolatedConfig));
run.abortController?.signal.throwIfAborted();
break;
} catch (execErr) {
if (run.abortController?.signal.aborted || isUncertainCliFailure(execErr) || ['WORKFLOW_PAUSED', 'DECISION_GATE_DENIED', 'HARNESS_CONFIGURATION'].includes(execErr.code) || node.type === 'decision_gate') throw execErr;
run.logStream.write(`[Engine] Node "${nodeId}" execution attempt ${attempt} failed: ${execErr.message}\n`);
if (attempt >= maxAttempts) {
// [NiFi Provenance] ์ตœ์ข… ์‹œ๋„ ์‹คํŒจ ์‹œ ์ƒํƒœ ์—…๋ฐ์ดํŠธ
try {
db.saveWorkflowProvenance({
id: provId,
run_id: runId,
node_id: nodeId,
status: 'failed',
output_flow_file: { error: execErr.message },
ended_at: new Date().toISOString(),
retry_count: attempt - 1
});
} catch (provErr) { /* intentional: ํŒŒ์ผ ์กฐํšŒ ์‹คํŒจ ์‹œ ๋ฌด์‹œ */ }
throw execErr;
}
}
}
// [NiFi Provenance] ๋…ธ๋“œ ์‹คํ–‰ ์„ฑ๊ณต ์‹œ ์ถœ๋ ฅ ์Šค๋ƒ…์ƒท ๊ธฐ๋ก
try {
db.saveWorkflowProvenance({
id: provId,
run_id: runId,
node_id: nodeId,
status: 'success',
output_flow_file: output,
ended_at: new Date().toISOString()
});
} catch (provErr) { /* intentional: ํŒŒ์ผ ์กฐํšŒ ์‹คํŒจ ์‹œ ๋ฌด์‹œ */ }
if (run.runData[`node_timeline_${nodeId}`]) {
run.runData[`node_timeline_${nodeId}`].endedAt = new Date().toISOString();
}
run.runData[nodeId] = { status: 'success', output };
run.logStream.write(`[Node ${nodeId}] Completed successfully.\n`);
this.emit('node:progress', { runId, nodeId, status: 'completed', output });
if (taskId) {
try {
db.completeWorkflowTask(taskId, 'completed', output, null);
} catch (dbErr) {
log.error('[Engine] Failed to write task completion to DB:', dbErr.message);
}
}
run.journal.appendStep(runId, `๋…ธ๋“œ [${node.name}] ์‹คํ–‰ ์™„๋ฃŒ. ๊ฒฐ๊ณผ ๋ฐ์ดํ„ฐ: ${JSON.stringify(output)}`);
const taskDecision = output ? (output.strategy || output.decision || JSON.stringify(output)) : 'Success';
run.journal.updateTaskNoteDecision(taskId, taskDecision, JSON.stringify(output, null, 2));
if (node.type === 'reviewer' && output && (output.approved === false || output.approved === 'false')) {
run.runData[`reviewer_${nodeId}_feedback`] = output.feedback || '๋ฐ˜๋ ค ํ”ผ๋“œ๋ฐฑ์ด ์ง€์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.';
const incomingEdges = run.edges.filter(e => e.target === nodeId);
const predecessorId = incomingEdges.length > 0 ? incomingEdges[0].source : null;
const predecessorIndex = predecessorId ? run.sortedNodeIds.indexOf(predecessorId) : -1;
if (predecessorIndex !== -1) {
const backRouteKey = `reviewer_backroute_${nodeId}_${predecessorId}`;
run.runData[backRouteKey] = (run.runData[backRouteKey] || 0) + 1;
const maxBackRoutes = (node.config && node.config.maxReviewerRetries) || 3;
if (run.runData[backRouteKey] > maxBackRoutes) {
// [P15 A3] ๋ฐ˜๋ ค ์ƒํ•œ ์†Œ์ง„ ์‹œ ์ฒ˜๋ฆฌ โ€” ๊ณผ๊ฑฐ์—๋Š” ๋ฐ˜๋ ค๋œ ์‚ฐ์ถœ๋ฌผ์ด "๋ฌด์–ธ ํ†ต๊ณผ"
// (์Šน์ธ๋œ ๊ฒƒ์ฒ˜๋Ÿผ ๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ง„ํ–‰)๋˜์–ด ํ’ˆ์งˆ ๊ฒŒ์ดํŠธ๊ฐ€ ์šฐํšŒ๋˜๋Š” ๊ฒฐํ•จ์ด ์žˆ์—ˆ๋‹ค.
// config.onExhaust๋กœ ๋™์ž‘์„ ์„ ํƒํ•œ๋‹ค: 'fail'(์ค‘๋‹จ) | 'hitl'(์‚ฌ๋žŒ ํŒ๋‹จ ์ด๊ด€) |
// 'proceed'(๋ช…์‹œ์  ์„ ํƒ ์‹œ์—๋งŒ โ€” ํ’ˆ์งˆ ๋ฏธ๋‹ฌ ์‚ฐ์ถœ๋ฌผ ๋ฌด์–ธ ํ†ต๊ณผ ์œ„ํ—˜ ์ธ์ง€ ํ•„์ˆ˜).
// โš  v2 ์ „ํ™˜ ์™„๋ฃŒ: ๊ธฐ๋ณธ๊ฐ’์„ 'fail'๋กœ ์ „ํ™˜ํ•˜์—ฌ ํ’ˆ์งˆ ๊ฒŒ์ดํŠธ ์šฐํšŒ๋ฅผ ์›์ฒœ ์ฐจ๋‹จ.
// ๊ธฐ์กด 'proceed' ๋™์ž‘์ด ํ•„์š”ํ•˜๋ฉด ๋…ธ๋“œ config์— onExhaust:'proceed' ๋ช…์‹œ.
// ์„ค๊ณ„ ๊ทผ๊ฑฐ: docs/DESIGN_P15_MULTIAGENT_LOOP_IMPROVEMENTS.md ยง3 A3
const onExhaust = (node.config && node.config.onExhaust) || 'fail';
const exhaustMsg = `[Reviewer] ์ตœ๋Œ€ ๋ฐ˜๋ ค ํšŸ์ˆ˜(${maxBackRoutes}ํšŒ) ์ดˆ๊ณผ (onExhaust=${onExhaust}). ๋งˆ์ง€๋ง‰ ํ”ผ๋“œ๋ฐฑ: ${output.feedback || '์—†์Œ'}`;
run.logStream.write(exhaustMsg + '\n');
run.journal.appendStep(runId, exhaustMsg);
// ์—์Šค์ปฌ๋ ˆ์ด์…˜ ์‚ฌ์œ ๋ฅผ ํ‘œ์ค€ ์œ„์น˜์— ๊ธฐ๋ก โ€” HITL ๋…ธ๋“œ/๋ฆฌ์‹œํŠธ๊ฐ€ ๊ณตํ†ต ์ฐธ์กฐ(A4 ์—ฐ๊ณ„)
run.runData._escalation = {
reason: 'REVIEWER_EXHAUSTED',
nodeId,
rejections: run.runData[backRouteKey] - 1,
lastFeedback: output.feedback || null
};
if (onExhaust === 'fail') {
// ๋…ธ๋“œ ์‹คํŒจ ๊ฒฝ๋กœ(catch โ†’ on_failure ์ „๋žต)๋กœ ์ •ํ•ฉํ•˜๊ฒŒ ํ˜๋ ค๋ณด๋‚ธ๋‹ค
throw new Error(`REVIEWER_EXHAUSTED: ๋ฆฌ๋ทฐ์–ด ๋ฐ˜๋ ค ${maxBackRoutes}ํšŒ ์ดˆ๊ณผ โ€” ํ’ˆ์งˆ ๊ธฐ์ค€ ๋ฏธ๋‹ฌ๋กœ ์ค‘๋‹จ`);
}
if (onExhaust === 'hitl') {
// ๊ทธ๋ž˜ํ”„์— hitl ๋…ธ๋“œ๊ฐ€ ์žˆ์œผ๋ฉด ๊ทธ ๋…ธ๋“œ๋กœ ์ ํ”„ํ•ด ์‚ฌ๋žŒ ํŒ๋‹จ์œผ๋กœ ์ด๊ด€ํ•œ๋‹ค
const hitlIndex = run.sortedNodeIds.findIndex((nid) => {
const n = run.nodes.find((x) => x.id === nid);
return n && n.type === 'hitl';
});
if (hitlIndex !== -1) {
run.logStream.write(`[Reviewer] HITL ๋…ธ๋“œ(${run.sortedNodeIds[hitlIndex]})๋กœ ์—์Šค์ปฌ๋ ˆ์ด์…˜ํ•ฉ๋‹ˆ๋‹ค.\n`);
run.currentNodeIndex = hitlIndex;
setImmediate(() => this.emit('node:trigger', runId));
return;
}
// hitl ๋…ธ๋“œ๊ฐ€ ์—†์œผ๋ฉด fail ํด๋ฐฑ(๋ฌด์–ธ ํ†ต๊ณผ๋ณด๋‹ค ์•ˆ์ „ํ•œ ์ชฝ์œผ๋กœ)
throw new Error(`REVIEWER_EXHAUSTED: ๋ฐ˜๋ ค ${maxBackRoutes}ํšŒ ์ดˆ๊ณผ + HITL ๋…ธ๋“œ ๋ถ€์žฌ โ€” ์ค‘๋‹จ(fail ํด๋ฐฑ)`);
}
// 'proceed'(๊ธฐ์กด ๋™์ž‘): ์ง„ํ–‰ํ•˜๋˜ ๋‹ค์šด์ŠคํŠธ๋ฆผ์ด ์‹๋ณ„ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ”Œ๋ž˜๊ทธ๋ฅผ ๋‚จ๊ธด๋‹ค
run.runData._reviewerExhausted = true;
run.logStream.write(`[Reviewer] โš  ๊ฒฝ๊ณ : ๋ฐ˜๋ ค๋œ ์‚ฐ์ถœ๋ฌผ์ด ๊ทธ๋Œ€๋กœ ์ง„ํ–‰๋ฉ๋‹ˆ๋‹ค(_reviewerExhausted=true). onExhaust:'fail' ์„ค์ •์„ ๊ถŒ์žฅํ•ฉ๋‹ˆ๋‹ค.\n`);
// Fall through to next node instead of back-routing
} else {
run.logStream.write(`[Reviewer] ๋ฐ˜๋ ค๋จ (${run.runData[backRouteKey]}/${maxBackRoutes}): ${output.feedback || '์ด์œ  ๋ฏธ์ง€์ •'}. ${predecessorId} ๋…ธ๋“œ๋กœ ๋ฐฑ-๋ผ์šฐํŒ…ํ•ฉ๋‹ˆ๋‹ค.\n`);
run.journal.appendStep(runId, `[Reviewer] ๋ฐ˜๋ ค๋จ (${run.runData[backRouteKey]}/${maxBackRoutes}): ${predecessorId} ๋…ธ๋“œ๋กœ ๋ฐฑ-๋ผ์šฐํŒ…ํ•ฉ๋‹ˆ๋‹ค.`);
run.currentNodeIndex = predecessorIndex;
setImmediate(() => this.emit('node:trigger', runId));
return;
}
} else {
run.logStream.write(`[Reviewer] ๋ฐ˜๋ ค๋˜์—ˆ์œผ๋‚˜ ์ด์ „ ๋ฉ”์ปค ๋…ธ๋“œ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์Œ ๋‹จ๊ณ„๋กœ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค.\n`);
}
}
run.currentNodeIndex++;
setImmediate(() => this.emit('node:trigger', runId));
} catch (err) {
const checkRun = activeRuns.get(runId);
if (!checkRun || checkRun.status !== 'running') {
return;
}
if (run.runData[`node_timeline_${nodeId}`]) {
run.runData[`node_timeline_${nodeId}`].endedAt = new Date().toISOString();
}
const onFailureStrategy = (node && node.config && node.config.on_failure) || 'abort';
if (nodeId) {
run.logStream.write(`[Node ${nodeId}] Failed: ${err.message}. (Strategy: ${onFailureStrategy})\n`);
this.emit('node:progress', { runId, nodeId, status: 'failed', error: err.message });
run.journal.appendStep(runId, `๋…ธ๋“œ [${nodeName}] ์‹คํ–‰ ์‹คํŒจ. ์—๋Ÿฌ: ${err.message}`);
if (taskId) run.journal.updateTaskNoteDecision(taskId, `Failed: ${err.message}`, `Error: ${err.message}`);
if (taskId) {
try {
db.completeWorkflowTask(taskId, 'failed', null, err.message);
} catch (dbErr) {
log.error('[Engine] Failed to write task failure to DB:', dbErr.message);
}
}
}
if (onFailureStrategy === 'continue' && !isUncertainCliFailure(err) && node?.type !== 'decision_gate' && !['WORKFLOW_PAUSED', 'DECISION_GATE_DENIED', 'HARNESS_CONFIGURATION', 'WORKFLOW_CHECKPOINT'].includes(err.code)) {
run.logStream.write(`[Engine] Strategy 'continue' triggered. Moving to next node.\n`);
run.currentNodeIndex++;
setImmediate(() => this.emit('node:trigger', runId));
} else {
this.handleWorkflowFailure(runId, err);
}
} finally {
const activeRun = activeRuns.get(runId);
if (activeRun) {
activeRun.isExecuting = false;
}
}
}
};
}
module.exports = { createNodeDispatch };