Download src/workflow/run-lifecycle.js from VanyaJ/bada-terminal: direct link, hf CLI and curl.
- Browser
- Download file 27.3 kB
-
https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/workflow/run-lifecycle.js
- Command line
-
hf download hf://VanyaJ/bada-terminal/src/workflow/run-lifecycle.js
-
curl -L -o run-lifecycle.js https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/workflow/run-lifecycle.js
27.3 kB
| // ์คํ ๊ด์ธก ์ค๋ช ๋ฌธ์: /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 }; | |