// 실행 관측 설명 문서: /docs/specs/bada-bong-agent-telemetry.md (v0.1.0) // 설명 문서: docs/specs/bada-code-quality.md (v1.0.0) // 실행 상태 맵은 엔진이 소유하고 이 모듈은 지정된 책임만 처리한다. const path = require('path'); const fs = require('fs'); const db = require('../../knowledge-db'); const configManager = require('../config-manager'); const workflowState = require('../utils/workflow-state'); const agentRunner = require('../agent-runner'); const troubleshootKB = require('../troubleshoot-kb'); const devPreferenceTracker = require('../dev-preference-tracker'); const browserLifecycle = require('../services/bong-browser-lifecycle'); function createLifecycle(dependencies) { const { activeRuns, activeProcesses, messageQueues, log, diffEngine } = dependencies; return { async completeWorkflow(runId) { try { const run = activeRuns.get(runId); if (!run || run.status !== 'running') return; run.status = 'completing'; try { // 학습/아카이브가 진행 중인 실행을 목표 관제가 완료로 오인하지 않게 한다. // docs/specs/workflow-preference-learning.md v1.0.0 db.checkpointWorkflowRun(runId, 'running', run.currentNodeId, run.runData); } catch (dbErr) { log.error(`[Engine] Complete workflow db write failed:`, dbErr); await this.handleWorkflowFailure(runId, dbErr); return; } // 성공 완료 시 실행 중인 자식 프로세스 정리 (자원 누수 방지) const procMap = activeProcesses.get(runId); if (procMap) { for (const proc of procMap.values()) { try { proc.kill(); } catch (e) { /* intentional: best-effort 처리, 실패 시 무시 */ } } } // 브라우저 transport/종료 기록/미상 효과 확인 전 학습·성공·실행권 해제를 시작하지 않는다. // docs/specs/bong-browser-use.md v1.4.0 browserLifecycle.assertSafe(await browserLifecycle.settle(run)); if (activeRuns.get(runId) !== run || run.status !== 'completing') return; // 마지막 요청 뒤 다음 제출이 없어도 초과/미상 비용을 성공으로 바꾸지 않는다. // 설명 문서: docs/specs/runtime-request-reservation.md (v1.0.0) require('../services/runtime-request-reservation').assertReady(run, { settled: true }); // 개발 선호도 자동 학습 훅 연동 try { const kConfig = configManager.getKnowledgeConfig(); const marker=run.runData._badaPreferenceLearning; if(marker&&(marker.version!==1||marker.runId!==runId||marker.projectId!==run.projectId||marker.state!=='completed'&&!require('../services/learning-completion-proof').ready(db,db.getWorkflowRun(runId))))throw Object.assign(new Error('자동 학습의 이전 제출·게시 상태를 검토해주세요.'),{code:'USAGE_RECONCILIATION_REQUIRED'}); if (kConfig.devPreferenceAutoLearn !== false&&!marker) { // 제출/게시 도중 종료되면 같은 실행 재개에서도 자동 재제출하지 않는다. run.runData._badaPreferenceLearning={version:1,runId,projectId:run.projectId,state:'pending',startedAt:new Date().toISOString()}; db.checkpointWorkflowRun(runId,'running',run.currentNodeId,run.runData); const sessionLogs = JSON.stringify(run.runData); await devPreferenceTracker.detectPreference(run.projectId, sessionLogs, {run}); if(activeRuns.get(runId)!==run||run.status!=='completing')return; run.runData._badaPreferenceLearning={...run.runData._badaPreferenceLearning,state:'completed',completedAt:new Date().toISOString()}; db.checkpointWorkflowRun(runId,'running',run.currentNodeId,run.runData); } } catch (prefErr) { log.error(`[Engine] Failed to auto-learn preferences for runId ${runId}:`, prefErr); await this.handleWorkflowFailure(runId,prefErr);return; } if (activeRuns.get(runId) !== run || run.status !== 'completing') return; // 학습 비용까지 반영한 일지/지식 상태를 기록한다. try { run.journal.finalizeJournal(runId, 'completed', run.runData); run.journal.generateFinalReport(runId, run.workflowName || run.workflowId || 'Workflow', 'completed'); } catch (journalErr) { log.error(`[Engine] Failed to record Wiki Journal for runId ${runId}:`, journalErr); } try { db.saveNode(run.projectId,{id:`workflow_run:${runId}`,type:'workflow_run',label:`Workflow Run: ${runId.substring(7)}`,properties:{category:'workflow',status:'completed',runId}}); } catch (error) { log.error('[Engine] Failed to record workflow knowledge status:',error); } // 코드 스냅샷 기록 훅 연동 try { const kConfig = configManager.getKnowledgeConfig(); if (kConfig.codeIntelEnabled !== false) { let commitHash = 'unknown'; try { const { execSync } = require('child_process'); const projectPath = run.workDir; commitHash = execSync('git rev-parse HEAD', { cwd: projectPath }).toString().trim(); } catch (e) { /* intentional: git 작업 실패 시 무시 (비-git 환경 가능) */ } const snapshot = await diffEngine.captureSnapshot(run.projectId, commitHash); await db.saveChangeHistory(run.projectId, { id: 'chg_' + Date.now(), commit_hash: commitHash, author: 'BADA Agent', change_description: `Workflow run completed: ${run.workflowName || run.workflowId}`, changed_symbols: JSON.stringify({ symbols_count: snapshot.symbols.length, relations_count: snapshot.relations.length }) }); } } catch (snapshotErr) { log.error(`[Engine] Failed to capture code snapshot for runId ${runId}:`, snapshotErr); } if (activeRuns.get(runId) !== run || run.status !== 'completing') return; // 마일스톤 v1.5.0: 옵시디언 워크플로우 런 아카이빙 호출 (비동기 및 방어적 복사 적용) try { const WikiRunArchiver = require("../wiki-run-archiver"); const workflowSnapshot = { id: run.workflowId, name: run.workflowName, edges: run.edges || [] }; const archiveResult = await WikiRunArchiver.archiveWorkflowRun(runId, workflowSnapshot, 'completed', null, run.nodes || [], run.runData || {}); if (archiveResult?.success === false) log.error('[WikiRunArchiver] Archive incomplete: ' + archiveResult.error); } catch (archiveErr) { log.error(`[WikiRunArchiver] Failed to archive workflow run:`, archiveErr); } if (activeRuns.get(runId) !== run || run.status !== 'completing') return; // 6단계: 온톨로지 자동 Ingestion 및 LLMWiki Lint 기동 if (run.workDir) { const ontologyPath = path.join(run.workDir, 'insight_ontology.jsonld'); if (fs.existsSync(ontologyPath)) { if (run.logStream) run.logStream.write(`[Engine] Found insight_ontology.jsonld at ${ontologyPath}. Starting Ingestion...\n`); try { const WikiRunArchiver = require("../wiki-run-archiver"); const { absWikiPath } = WikiRunArchiver.getVaultDirs(run.workDir); // 1. 온톨로지 이식 const imported = await WikiRunArchiver.importOntologyJsonLd(ontologyPath, absWikiPath); if (!imported?.success) throw new Error('Ontology import failed: ' + (imported?.error || 'missing result')); if (run.logStream) run.logStream.write(`[Engine] Ontology successfully imported to ${absWikiPath}\n`); // 2. LLMWiki Linter 기동 const { execFile } = require('child_process'); const lintScript = path.join(__dirname, '../../scripts/lint.py'); const processHelper = require("../utils/process-helper"); const { pythonPath, env } = processHelper.getPythonEnvConfig(absWikiPath); if (run.logStream) run.logStream.write(`[Engine] Executing Linter: ${pythonPath} ${lintScript} ${absWikiPath}\n`); await new Promise((resolve) => { execFile(pythonPath, [lintScript, absWikiPath], { timeout: 30000, env: env, signal: run.abortController?.signal }, (error, stdout, stderr) => { if (stdout) { if (run.logStream) run.logStream.write(`[Linter STDOUT]\n${stdout}\n`); log.debug('Linter STDOUT', { stdout }); } if (stderr) { if (run.logStream) run.logStream.write(`[Linter STDERR]\n${stderr}\n`); log.error(`[Linter STDERR] ${stderr}`); } if (error) { if (run.logStream) run.logStream.write(`[Engine] Linter execution failed: ${error.message}\n`); log.error(`[Engine] Linter failed:`, error); } else { if (run.logStream) run.logStream.write(`[Engine] Linter passed successfully!\n`); } resolve(); }); }); } catch (ingestErr) { log.error(`[Engine] Ingestion / Lint failed:`, ingestErr); if (run.logStream) run.logStream.write(`[Engine] Ingestion / Lint failed: ${ingestErr.message}\n`); } } } require('../services/runtime-request-reservation').assertReady(run, { settled: true }); if (run.logStream) { try { run.logStream.write(`=== Workflow Run "${runId}" Completed Successfully ===\n`); run.logStream.end(); } catch (streamErr) { /* intentional: best-effort 처리, 실패 시 무시 */ } } if (activeRuns.get(runId) !== run || run.status !== 'completing') return; // 최종 사용량과 종료를 함께 저장한 뒤에만 완료 이벤트/실행권 해제를 허용한다. db.completeWorkflowRun(runId, 'completed', run.runData); run.status = 'completed'; await this.cleanupRun(runId); this.emit('workflow:complete', { runId, runData: run.runData, usage: run.usage, cumulativeCost: run.cumulativeCost }); } catch (err) { log.error(`[Workflow Engine] Failed to complete workflow gracefully for runId ${runId}:`, err); await this.handleWorkflowFailure(runId, err); } }, async suspendWorkflowRun(runId, reason) { const run = activeRuns.get(runId); if (!run || run.suspending) return; run.suspending = true; run.status = 'pausing'; run.currentNodeId = run.sortedNodeIds[run.currentNodeIndex]; run.abortController?.abort(reason); this.killProcessesForRun(runId); if (run.pendingNodeOperations?.size) await Promise.allSettled([...run.pendingNodeOperations]); if (run.pendingParallelNodes?.size) await Promise.allSettled([...run.pendingParallelNodes]); await browserLifecycle.settle(run); run.status = 'paused'; try { db.checkpointWorkflowRun(runId, 'paused', run.currentNodeId, run.runData); workflowState.writeState(run); } catch (error) { run.preserveExecutionLease = true; log.error('[Engine] Pause checkpoint failed:', error); } await this.cleanupRun(runId); this.emit('workflow:pause', { runId, suspended: true, reason: reason.message, code: 'WORKFLOW_PAUSED', browser: run.browserDrainReport }); }, async handleWorkflowFailure(runId, err) { try { const run = activeRuns.get(runId); if (!run || run.suspending || run.status === 'failed' || run.status === 'completed') return; if (err?.code === 'WORKFLOW_PAUSED') return this.suspendWorkflowRun(runId, err); err = err instanceof Error ? err : new Error(String(err)); // 실패 처리 자체도 signal을 중단하므로 기존 소유 취소와 구별해 보존한다. // docs/specs/workflow-triage-admission.md v1.2.0 const alreadyCancelled = run.abortController?.signal.aborted; const costCodes = ['USAGE_LEDGER_FAILED', 'USAGE_RECONCILIATION_REQUIRED', 'BUDGET_EXCEEDED']; // 모델 정산 콜백의 신뢰된 중단 표시도 종료 이벤트와 같은 영속 검토 코드로 남긴다. // 이미 저장된 실제 비용은 유지하고 원 오류의 code/message를 바꾸지 않는다. const harnessUnknown = err.harnessStop === true && !require('../utils/cli-storage-error').isUncertainCliFailure({ code: err.code, retryable: err.retryable }); const costErrorCode = costCodes.includes(err.code) ? err.code : harnessUnknown ? 'USAGE_RECONCILIATION_REQUIRED' : null; const costFailure = costErrorCode !== null; let diagnosticErrorCode; run.status = 'failed'; run.abortController?.abort(err); if (typeof run.resumeHandler === 'function') { const resume = run.resumeHandler; run.resumeHandler = null; resume(err); } this.killProcessesForRun(runId); // 내부 HTTP 요청의 취소와 실패 사용량을 확정한 뒤 실패 checkpoint를 저장한다. // 설명 문서: /docs/specs/local-group-execution.md (v1.0.0) if (run.pendingNodeOperations?.size) await Promise.allSettled([...run.pendingNodeOperations]); if (run.pendingParallelNodes?.size) await Promise.allSettled([...run.pendingParallelNodes]); if (run.pendingLlmRequests?.size) await Promise.allSettled([...run.pendingLlmRequests]); await browserLifecycle.settle(run); // 원 폴더 실행권과 run을 유지한 채 진단 비용·자식 종료까지 확정한다. // 종료 이벤트/저장 상태를 본 목표 관제가 진단 전 잔액으로 재계획하지 않게 한다. if (!costFailure && !alreadyCancelled && !run.cancelRequested && !run.parentSignal?.aborted && !run.shutdownRequested) { try { await agentRunner.runAutoTriageDiagnostic(run.projectId, runId, err.message, run.workDir, run); } catch (triageError) { if (costCodes.includes(triageError.code)) diagnosticErrorCode = triageError.code; log.error('[Engine] Automatic diagnosis did not complete; original workflow failure preserved.'); } } try { // 목표 관찰은 이벤트 대신 저장된 비용 안전 코드를 읽어 재계획 우회를 막는다. // docs/specs/local-group-execution.md v1.2.0. 임의 오류 본문을 코드로 해석하지 않는다. // 직접 취소/소유 종료는 별도 boolean으로 보존해 이벤트 유실 후에도 재계획하지 않는다. // docs/specs/bong-goal-planning-checkpoint.md v1.1.0 db.completeWorkflowRun(runId, 'failed', { error: err.message, ...(costFailure ? { errorCode: costErrorCode } : {}), ...(diagnosticErrorCode ? { diagnosticErrorCode } : {}), ...((run.cancelRequested || alreadyCancelled || run.parentSignal?.aborted || run.shutdownRequested) ? { cancelRequested: true } : {}), partial_data: run.runData }); run.preserveExecutionLease = browserLifecycle.unsafe(run.browserDrainReport); } catch (dbErr) { run.preserveExecutionLease = true; log.error(`[Engine] Failure checkpoint db write failed:`, dbErr); } // 일지 마무리 기록 try { run.journal.finalizeJournal(runId, 'failed', { error: err.message, runData: run.runData }); run.journal.generateFinalReport(runId, run.workflowName || run.workflowId || 'Workflow', 'failed'); } catch (journalErr) { log.error(`[Engine] Failed to write failure Wiki Journal for runId ${runId}:`, journalErr); } // 지식 노드 갱신 try { db.saveNode(run.projectId, { id: `workflow_run:${runId}`, type: 'workflow_run', label: `Workflow Run: ${runId.substring(7)}`, properties: { category: 'workflow', status: 'failed', runId } }); } catch (e) { /* intentional: 파일 조회 실패 시 무시 */ } if (typeof run.abortHandler === 'function') { try { run.abortHandler(err); } catch (e) { /* intentional: best-effort 처리, 실패 시 무시 */ } } const procMap = activeProcesses.get(runId); if (procMap) { for (const proc of procMap.values()) { try { proc.kill(); } catch (e) { /* intentional: best-effort 처리, 실패 시 무시 */ } } } if (run.logStream) { try { run.logStream.write(`=== Workflow Run "${runId}" Failed. Error: ${err.message} ===\n`); run.logStream.end(); } catch (streamErr) { /* intentional: best-effort 처리, 실패 시 무시 */ } } // 진단 정산·종료를 포함한 실패 확정 뒤 폴더 실행권을 반환한다. run.failureCleanupReady = true; await this.cleanupRun(runId); // 이벤트 경계에서는 Error 객체의 중단 표시가 사라지므로 안전한 원장 코드로 고정한다. // 원 오류는 내부 실패 처리에 그대로 남기고 자식 workflow/배치에 진단 본문을 복제하지 않는다. this.emit('workflow:fail', { runId, terminalStatus:run.cancelRequested?'cancelled':'failed', error: harnessUnknown ? '모델 검증의 실행·비용 기록을 확인한 뒤 같은 실행을 검토하세요.' : err.message, code: harnessUnknown ? 'USAGE_RECONCILIATION_REQUIRED' : err.code, usage: run.usage, cumulativeCost: run.cumulativeCost, browser: run.browserDrainReport }); if (run.shutdownRequested) return; // 마일스톤 v1.5.0: 옵시디언 워크플로우 런 실패 아카이빙 호출 (비동기 및 방어적 복사 적용) try { const WikiRunArchiver = require("../wiki-run-archiver"); const workflowSnapshot = { id: run.workflowId, name: run.workflowName, edges: run.edges || [] }; await WikiRunArchiver.archiveWorkflowRun(runId, workflowSnapshot, 'failed', err.message, run.nodes || [], run.runData || {}); } catch (archiveErr) { log.error(`[WikiRunArchiver] Failed to archive workflow run on failure:`, archiveErr); } // 트러블슈팅 자동 포착 훅 연동 try { const kConfig = configManager.getKnowledgeConfig(); if (kConfig.troubleshootAutoCapture !== false) { await troubleshootKB.onError(run.projectId, err, { type: 'workflow_failure', workDir: run.workDir, files: [], tags: ['workflow', run.workflowId] }); } } catch (tsErr) { log.error(`[Engine] Failed to auto-capture troubleshoot for runId ${runId}:`, tsErr); } } catch (fatalErr) { log.error(`[Workflow Engine] Fatal error inside handleWorkflowFailure for runId ${runId}:`, fatalErr); } }, cleanupRun(runId) { const run = activeRuns.get(runId); // 진단 준비 전의 노드/HTTP drain도 cleanup 재진입이 앞질러 해제하면 안 된다. if (run?.status === 'failed' && run.failurePromise && !run.failureCleanupReady) { run.cancelRequested = true; run.diagnosticController?.abort(new Error('Workflow failure cleanup')); return run.failurePromise; } if (run?.triagePromise) { run.diagnosticController?.abort(new Error('Workflow diagnosis cleanup')); // 진단 finally가 소유 Promise를 지운 뒤 기존 실패 처리의 cleanup이 진행한다. return Promise.allSettled([run.triagePromise]).then(() => run.failurePromise || this.cleanupRun(runId)); } if (run?.pendingNodeOperations?.size) { run.abortController?.abort(new Error('Workflow node cleanup')); run.nodeCleanupPromise ||= Promise.allSettled([...run.pendingNodeOperations]).then(() => run.failurePromise || this.cleanupRun(runId)); return run.nodeCleanupPromise; } // 직접 정리 요청도 실제 병렬 자식의 반환/기록 확정 전에 맵과 폴더 실행권을 지우지 않는다. // 설명 문서: docs/specs/bong-browser-use.md (v1.11.0) if (run?.pendingParallelNodes?.size) { run.abortController?.abort(new Error('Workflow parallel cleanup')); run.parallelCleanupPromise ||= Promise.allSettled([...run.pendingParallelNodes]).then(() => run.failurePromise || this.cleanupRun(runId)); return run.parallelCleanupPromise; } // 비대기 호출부도 맵/실행권을 먼저 지우지 않는다. 브라우저 없는 기존 동기 계약은 유지한다. if (browserLifecycle.hasWork(run) && !run.browserCleanupSettled) { if (['completed', 'failed', 'paused', 'pausing'].includes(run.status)) run.abortController?.abort(new Error('Workflow cleanup')); run.browserCleanupPromise ||= browserLifecycle.settle(run).then(report => { browserLifecycle.apply(run, report); run.browserCleanupSettled = true; return this.cleanupRun(runId); }); return run.browserCleanupPromise; } if (run?.browserDrainReport) browserLifecycle.apply(run, run.browserDrainReport); // 세션의 HTTP/PTY/자격 정리가 끝나야 로그와 폴더 실행권을 넘길 수 있다. // 설명 문서: docs/specs/interactive-headroom-ownership.md (v1.0.0) if (run && !run.interactiveCleanupSettled && require('../utils/interactive-cli-session').hasSession(run)) { run.interactiveCleanupPromise ||= require('../utils/interactive-cli-session').closeSession(run).then(() => { run.interactiveCleanupSettled = true; return this.cleanupRun(runId); }); return run.interactiveCleanupPromise; } // 1단계: 로그 스트림 종료, PTY 자식 트리 종료 try { if (run) { require("../services/loop-hud").finishRun(run, run.status); run.parentSignal?.removeEventListener('abort', run.cancelFromParent); if (run.status === 'completed' || run.status === 'failed') run.abortController?.abort(new Error('Workflow finished')); if (run.logStream) { try { if (!run.logStream.destroyed) { run.logStream.end(); } } catch (streamErr) { log.error('[Engine] Failed to close logStream on cleanup:', streamErr); } } if (run.workflowPty) { try { const pid = run.workflowPty.pid; if (pid) { const processHelper = require("../utils/process-helper"); processHelper.killProcessTree(pid, true); } else { run.workflowPty.kill('SIGKILL'); } } catch (ptyErr) { log.error('[Engine] Failed to kill shared PTY process tree:', ptyErr); } } } } catch (err1) { log.error('[Engine] Error in cleanup stage 1 (lock/stream/pty):', err1); } // 실행 소유 상태 섹션만 정리한다. 다른 실행/사용자의 progress와 git exclude는 건드리지 않는다. try { if (run?.workDir) { const agentsMdPath = path.join(run.workDir, 'AGENTS.md'); if (fs.existsSync(agentsMdPath)) { const original = fs.readFileSync(agentsMdPath, 'utf8'); const cleaned = original.replace(workflowState.sectionRegex(runId), ''); if (cleaned !== original) { if (run.agentsMdCreated && cleaned === '') fs.unlinkSync(agentsMdPath); else fs.writeFileSync(agentsMdPath, cleaned, 'utf8'); } } if (run.status === 'completed') fs.rmSync(workflowState.statePath(runId), { force: true }); } } catch (error) { log.error('[Engine] Failed to clean owned workflow state:', error); } // 3단계: 비동기 Git 정리가 끝날 때까지 작업 폴더 실행권을 유지한다. let checkpointCleanup; try { if (run?.workDir && run.status === 'completed') { checkpointCleanup = agentRunner.deleteCheckpointBranch(run.workDir, runId); } } catch (err3) { log.error('[Engine] Failed to delete checkpoint branch:', err3); } // 4단계: 무조건(Guaranteed) 맵에서 삭제하여 메모리 회수 및 NATS 구독 정리 // 규칙 파일과 체크포인트 정리가 끝나기 전에 다음 프로세스에 폴더를 넘기지 않는다. const releaseWorkspace = () => { if (run?.lockAcquired && !run.browserDrainReport?.terminationUnconfirmed && !run.browserDrainReport?.journalUnconfirmed) { try { run.lease?.release(); } catch (error) { log.error('[Engine] Failed to release project lock:', error); } try { run.sourceLease?.release(); } catch (error) { log.error('[Engine] Failed to release source project lock:', error); } run.lockAcquired = false; } }; const workspaceCleanup = checkpointCleanup ? Promise.resolve(checkpointCleanup).catch(error => { log.error('[Engine] Failed to finish checkpoint cleanup:', error); }).then(releaseWorkspace) : releaseWorkspace(); try { const natsManager = require("../services/bada-nats-manager"); if (run && run.nodes) { for (const n of run.nodes) { const aId = (n.config && (n.config.agentProfileId || n.config.agentId)) || n.type; natsManager.unsubscribeAgentMessages(runId, aId); } } } catch (e) { log.warn('Failed to unsubscribe NATS agent messages on cleanup', null, e); } try { activeRuns.delete(runId); // 소유 정리 후에도 웹 효과/저장 실패로 남긴 실행권은 승인된 동일 실행 검토에만 넘긴다. if (run?.executionLease && run.preserveExecutionLease) require('../services/workflow-run-lease').retire(runId, run.executionLease); if (run?.executionLease && !run.preserveExecutionLease) { // 최종/정지 기록 저장 실패 시 종료 프로세스 증거를 남긴다. 실행 중 기록에서 실행권만 지우지 않는다. try { const record = db.getWorkflowRun(runId); if (!record || ['completed', 'failed', 'paused'].includes(record.status)) run.executionLease(); } catch (error) { log.error('[Engine] Preserving execution lease after storage failure:', error); } } activeProcesses.delete(runId); messageQueues.delete(runId); } catch (err4) { log.error('[Engine] Error clearing active maps:', err4); } return workspaceCleanup; } }; } module.exports = { createLifecycle };