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 };