File size: 24,122 Bytes
d739b1b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | // λΈλΌμ°μ μμ° μ μ§ 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 };
|