Download src/loop-controller.js from VanyaJ/bada-terminal: direct link, hf CLI and curl.
- Browser
- Download file 41.9 kB
-
https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/loop-controller.js
- Command line
-
hf download hf://VanyaJ/bada-terminal/src/loop-controller.js
-
curl -L -o loop-controller.js https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/loop-controller.js
41.9 kB
| /** | |
| * ์ค๋ช ๋ฌธ์: /docs/specs/loop-configuration.md (v1.0.0) | |
| * | |
| * BADA Terminal ๋ฃจํ ์์ง๋์ด๋ง์ ํต์ฌ ์ ์ด๊ธฐ(LoopController) ๋ฐ ํ๋ก ์ฐจ๋จ๊ธฐ(LoopCircuitBreaker). | |
| * ์์ด์ ํธ์ ๋ฐ๋ณต ์คํ(Discover -> Plan -> Execute -> Verify) ๊ณผ์ ์์ | |
| * Goal ๋ฌ์ฑ ์ฌ๋ถ๋ฅผ ํ๊ฐํ๊ณ ๋ฆฌ์์ค ์์ฐ ์ด๊ณผ ๋ฐ ์ค์๋์ ์์ ํ๊ฒ ์ฐจ๋จํฉ๋๋ค. | |
| */ | |
| const { EventEmitter } = require('events'); | |
| const fs = require('fs'); | |
| const path = require('path'); | |
| const db = require('../knowledge-db'); | |
| const notifier = require('./loop-notifier'); | |
| const { isSafeShellCommand } = require('./utils/shell-helper'); | |
| // ํ๋ค์ค ์คํ/ํ์ ํต์ฌ ๋ก์ง์ ๋จ์ผ ์ถ์ฒ(agent-runner.js์ ๊ณต์ ) | |
| const harnessExecutor = require('./harness-executor'); | |
| // ์ข ๋ฃ ๋ฆฌ์ํธ(์ฌ๋์ด ์ฝ๋ ์ข ๋ฃ ์์ฝ) ์์ ํฌ๋งคํฐ โ DB/IPC ๋ฏธ์์กด, B2 ํ๋ค์ค ๋ฆฌ์ํธ์ ์ฌ์ฌ์ฉ | |
| const controllerPolicy = require('./services/loop-controller-policy'); | |
| /** | |
| * ๋ฃจํ ๋ด ๋์ ์์ ์๋ชจ ๋ฐ ์์ ์ฐจ๋จ ์กฐ๊ฑด์ ๋ชจ๋ํฐ๋งํ๋ ํ๋ก ์ฐจ๋จ๊ธฐ | |
| */ | |
| class LoopCircuitBreaker { | |
| constructor(config = {}) { | |
| this.maxIterations = config.max_iterations ?? 10; | |
| this.tokenBudget = config.token_budget ?? 5.0; // USD ๋จ์ ์์ฐ | |
| this.maxWallTime = config.max_wall_time ?? 3600; // ์ด ๋จ์ ์ต๋ ํ์ฉ ์๊ฐ | |
| this.consecutiveFailureThreshold = config.consecutive_failure_threshold ?? 3; | |
| this.stagnationWindow = config.stagnation_window ?? 5; // ์งํ ์ ์ฒด(no-progress) ํ์ ์ ์ฌ์ฉํ ์ฐ์ ๊ด์ธก ๊ฐ์ | |
| // ๋ชจ๋ํฐ๋ง ์ํ ๋ฐ์ดํฐ | |
| this.currentIteration = 0; | |
| this.cumulativeCost = 0.0; | |
| this.cumulativeTokens = 0; | |
| this.consecutiveFailures = 0; | |
| this.startTime = Date.now(); | |
| // ์งํ ์ ์ฒด ๊ฐ์ง์ฉ ์ต๊ทผ ๊ด์ธก ์ด๋ ฅ. key=metricKey(string), value=์ต๊ทผ ์์น ๋ฐฐ์ด(๊ฐ์ฅ ์ต๊ทผ์ด ๋ง์ง๋ง). | |
| this.metricHistory = new Map(); | |
| } | |
| /** | |
| * ์งํ์ฑ(progress) ์งํ์ ๊ด์ธก๊ฐ์ ์ด๋ ฅ์ ๊ธฐ๋กํ๋ค(์ ์ฒด ๊ฐ์ง์ฉ). | |
| * WHY: ์งํ๊ฐ stagnationWindowํ ์ฐ์์ผ๋ก ์ ํ ๋ณํ์ง ์์ผ๋ฉด(=์ง์ ์ด ์์ผ๋ฉด) ํ๋ก ์ฐจ๋จ๊ธฐ๊ฐ | |
| * ๋ฃจํ๋ฅผ STAGNATED๋ก ์ค๋จํ ์ ์๋๋ก, ์ฌ๊ธฐ์ ์ต๊ทผ ๊ด์ธก๊ฐ๋ง ์งง๊ฒ ์ ์งํ๋ค. | |
| * @param {string} metricKey - ์งํ ์๋ณ ํค | |
| * @param {number} value - ์ด๋ฒ ๊ด์ธก ์์น(์ ํ์๊ฐ ์๋๋ฉด ๋ฌด์) | |
| */ | |
| recordMetricValue(metricKey, value) { | |
| // ์ ํํ ์ซ์๊ฐ ์๋๋ฉด ์ ์ฒด ํ์ ์ ์๊ณกํ๋ฏ๋ก ๊ธฐ๋กํ์ง ์๋๋ค. | |
| if (typeof value !== 'number' || !Number.isFinite(value)) return; | |
| if (!this.metricHistory.has(metricKey)) { | |
| this.metricHistory.set(metricKey, []); | |
| } | |
| const arr = this.metricHistory.get(metricKey); | |
| arr.push(value); | |
| // ์ต๊ทผ stagnationWindow๊ฐ๋ง ์ ์ง(๋ฉ๋ชจ๋ฆฌ ๋ณดํธ + ํ์ ์ฐฝ ๊ณ ์ ). | |
| this.metricHistory.set(metricKey, arr.slice(-this.stagnationWindow)); | |
| } | |
| /** | |
| * ์ดํฐ๋ ์ด์ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋กํ๊ณ ์ํ๋ฅผ ๊ฐฑ์ ํฉ๋๋ค. | |
| * @param {Object} result - ์ดํฐ๋ ์ด์ ๊ฒฐ๊ณผ | |
| * @param {boolean} result.success - ์ดํฐ๋ ์ด์ ๋ด ์์ ์ฑ๊ณต ์ฌ๋ถ | |
| * @param {number} [result.cost] - ์๋ชจ ๋น์ฉ (USD) | |
| * @param {number} [result.tokens] - ์๋ชจ ํ ํฐ ์ | |
| */ | |
| recordIteration(result) { | |
| this.currentIteration++; | |
| if (result.cost) this.cumulativeCost += parseFloat(result.cost) || 0; | |
| if (result.tokens) this.cumulativeTokens += parseInt(result.tokens, 10) || 0; | |
| if (result.success) { | |
| this.consecutiveFailures = 0; | |
| } else { | |
| this.consecutiveFailures++; | |
| } | |
| } | |
| /** | |
| * ํ์ฌ ์ํ๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฃจํ๋ฅผ ๊ฐ์ ์ฐจ๋จํ ์ง ํ์ ํฉ๋๋ค. | |
| * @returns {Object} { break: boolean, reason: string | null } | |
| */ | |
| shouldBreak(now = Date.now()) { | |
| // ์๋ ๊ฒฐ์ ์๊ฐ์ ๋ช ์ํด ์ฝ๊ธฐ ๋์ฌ์ ์คํ์ ์๊ฐ/์ํท ์ฐ์ ์์๋ฅผ ๊ฐ๊ฒ ์ ์งํ๋ค. | |
| // ์ค๋ช ๋ฌธ์: docs/specs/batch-loop-observations.md v0.4.0 | |
| const reason = controllerPolicy.breakReason({ ...this, metricHistory: Object.fromEntries(this.metricHistory) }, { | |
| max_iterations: this.maxIterations, token_budget: this.tokenBudget, max_wall_time: this.maxWallTime, | |
| consecutive_failure_threshold: this.consecutiveFailureThreshold, stagnation_window: this.stagnationWindow | |
| }, now); | |
| return { break: reason !== null, reason }; | |
| } | |
| /** | |
| * ์ค๋ ์ท ๋๋ ์ด์ DB ๊ธฐ๋ก์ผ๋ก๋ถํฐ ํ๋ก ์ฐจ๋จ๊ธฐ ์ํ๋ฅผ ์์ ํ๊ฒ ๋ณต์ํฉ๋๋ค. | |
| * ๊ฒฝ๊ณผ ์๊ฐ ์๊ณก(Time Jump)์ ๋ฐฉ์งํ๊ธฐ ์ํด ๋์ ์คํ ์๊ฐ(elapsedMs)์ ๊ธฐ์ค์ผ๋ก ์์ ์๊ฐ์ ๋ณด์ ํฉ๋๋ค. | |
| * @param {Object} snapshot - ๋ณต์ํ ์ํ ๊ฐ์ฒด | |
| */ | |
| restore(snapshot = {}) { | |
| if (snapshot.currentIteration !== undefined) { | |
| this.currentIteration = Math.max(0, parseInt(snapshot.currentIteration, 10) || 0); | |
| } | |
| if (snapshot.cumulativeCost !== undefined) { | |
| this.cumulativeCost = Math.max(0, parseFloat(snapshot.cumulativeCost) || 0.0); | |
| } | |
| if (snapshot.cumulativeTokens !== undefined) { | |
| this.cumulativeTokens = Math.max(0, parseInt(snapshot.cumulativeTokens, 10) || 0); | |
| } | |
| if (snapshot.consecutiveFailures !== undefined) { | |
| this.consecutiveFailures = Math.max(0, parseInt(snapshot.consecutiveFailures, 10) || 0); | |
| } | |
| if (snapshot.elapsedMs !== undefined || snapshot.elapsedTimeMs !== undefined) { | |
| const elapsed = Math.max(0, Number(snapshot.elapsedMs ?? snapshot.elapsedTimeMs) || 0); | |
| this.startTime = Date.now() - elapsed; | |
| } | |
| if (snapshot.metricHistory && typeof snapshot.metricHistory === 'object') { | |
| this.metricHistory.clear(); | |
| for (const [key, values] of Object.entries(snapshot.metricHistory)) { | |
| if (Array.isArray(values)) { | |
| this.metricHistory.set(key, values.slice(-this.stagnationWindow)); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| /** | |
| * ์์ด์ ํธ ๋ฃจํ์ ์ดํฐ๋ ์ด์ ์ ๊ด๋ฆฌํ๊ณ Goal์ ์ค์๊ฐ ํ๊ฐํ๋ ๋ฉ์ธ ์ปจํธ๋กค๋ฌ | |
| */ | |
| class LoopController extends EventEmitter { | |
| /** | |
| * @param {Object} runContext - ์คํ ์ค์ธ ๋ฐฐ์น/์ํฌํ๋ก์ฐ ์คํ ์ฝํ ์คํธ (activeRun ๋ฑ) | |
| * @param {Object} loopConfig - ๋ฃจํ ์ค์ ์ ๋ณด | |
| */ | |
| constructor(runContext, loopConfig = {}, { checkpointSnapshot, deferPublications = false } = {}) { | |
| super(); | |
| loopConfig = require('./config/loop-configuration').normalize(loopConfig, { requireGoals: false }); | |
| this.runContext = runContext; | |
| this.loopConfig = loopConfig; | |
| this.deferPublications = deferPublications; | |
| this.workDir = runContext.workDir || process.cwd(); | |
| this.logStream = runContext.logStream || { write: console.log }; | |
| // ๊ฐ๋๋ ์ผ/ํ๋ก ์ฐจ๋จ๊ธฐ ์ด๊ธฐํ | |
| this.circuitBreaker = new LoopCircuitBreaker(loopConfig); | |
| // ํ๊ฐํ ๋ชฉํ(Goal) ๋ชฉ๋ก ์ถ์ถ | |
| this.goals = loopConfig.goals || []; | |
| // ์๋ฆผ ๊ฒฝ๊ณ ํ๋๊ทธ (์ต์ด 1ํ๋ง ๊ฒฝ๊ณ ํ๊ธฐ ์ํจ) | |
| this.hasWarnedBudget = false; | |
| // ์ข ๋ฃ ๋ฆฌ์ํธ ํฉ์ฑ์ ์ํ ๋ฐ๋ณต ๊ฒฐ๊ณผ ๋์ ๋ฒํผ. | |
| // WHY: ํฌ๋งคํฐ๋ ์์ ํจ์์ด๋ฏ๋ก, ๊ฐ ๋ฐ๋ณต์ ์ฑ๊ณต/์คํจ๋ฅผ ์ฌ๊ธฐ์ ๋ชจ์ ๋์๋ค๊ฐ | |
| // ์ข ๋ฃ ์์ ์ ํต์งธ๋ก ๋๊ธด๋ค. ๋ฃจํ "์ ์ด ํ๋ฆ"์๋ ์ํฅ์ ์ฃผ์ง ์๋ ๋ถ๊ฐ ์ ๋ณด๋ค. | |
| this.iterationResults = []; | |
| // ์ฅ์๋ช ๋ฃจํ ๋ฉ๋ชจ๋ฆฌ ๋ณดํธ์ฉ ์ํ(์ต๊ทผ N๊ฐ๋ง ๋ฆฌ์ํธ์ ๋ฐ์). | |
| this.MAX_RECEIPT_ITERATIONS = 500; | |
| // ์น์ธ๋ batch phase๋ฅผ ๋ณต์ํ ๋ ์ต์ด HUD๋ ์๋ ํ์ฐจ/๋น์ฉ์ ํ์ํ๋ค. | |
| // ์ค๋ช ๋ฌธ์: docs/specs/batch-step-continuation.md v0.11.0 | |
| if (checkpointSnapshot) { | |
| this.restore(checkpointSnapshot); | |
| this.circuitBreaker.startTime = checkpointSnapshot.startTime; | |
| this.iterationResults = structuredClone(checkpointSnapshot.iterationResults); | |
| } | |
| if (!this.deferPublications) require('./services/loop-hud').publish(this, 'running'); | |
| } | |
| toJSON() { | |
| return { | |
| goals: this.goals, | |
| circuitBreaker: { | |
| maxIterations: this.circuitBreaker.maxIterations, | |
| currentIteration: this.circuitBreaker.currentIteration, | |
| tokenBudget: this.circuitBreaker.tokenBudget, | |
| cumulativeCost: this.circuitBreaker.cumulativeCost, | |
| cumulativeTokens: this.circuitBreaker.cumulativeTokens, | |
| consecutiveFailures: this.circuitBreaker.consecutiveFailures, | |
| consecutiveFailureThreshold: this.circuitBreaker.consecutiveFailureThreshold, | |
| stagnationWindow: this.circuitBreaker.stagnationWindow, | |
| metricHistory: this.circuitBreaker.metricHistory ? Object.fromEntries(this.circuitBreaker.metricHistory.entries()) : {} | |
| } | |
| }; | |
| } | |
| validationOptions() { | |
| // ๋ฐฐ์น๋ ๊ฐ๋ณ ๋จ๊ณ์ abortController๊ฐ ๋ฐ๋๋ฏ๋ก ์คํ ์ ์ฒด์ controller๋ฅผ ์ฐ์ ํ๋ค. | |
| // workflow์ ๋ ๋ฆฝ ํธ์ถ์ ๊ธฐ์กด controller/์ํ๋ฅผ ํจ๊ป ํ์ธํ๋ค. | |
| const run = this.runContext; | |
| return { signal: run.lifecycleController?.signal || run.abortController?.signal, | |
| shouldCancel: () => !!(run.aborted || run.lifecycleController?.signal.aborted || run.abortController?.signal.aborted || (run.status !== undefined && run.status !== 'running')) }; | |
| } | |
| checkCancellation() { | |
| const { signal, shouldCancel } = this.validationOptions(); | |
| require('./utils/harness-command').checkCancellation(signal, shouldCancel); | |
| } | |
| /** | |
| * ๊ณจ(Goal) ์ค์ ์ ๋ฐ๋ฅธ ๋จ์ผ ๋ชฉํ ๋ฌ์ฑ ์ฌ๋ถ๋ฅผ ๋์ ์ผ๋ก ํ๊ฐํฉ๋๋ค. | |
| * @param {Object} goal - ๋ชฉํ ๋ช ์ธ { type, target, metric_key, operator, value, harnessId, test_command } | |
| * @param {Object} stepOutputs - ์คํ ๋ณ ์คํ ์์ํ ๋งต | |
| * @returns {Promise<boolean>} ํ๊ฐ ๊ฒฐ๊ณผ (์ฑ๊ณต ์ true, ์คํจ ์ false) | |
| */ | |
| async evaluateGoal(goal, stepOutputs, goalPath = '0') { | |
| if (!this.runContext.loopObserver) return this.evaluateGoalValue(goal, stepOutputs, goalPath); | |
| return this.observeGoalOperation(goalPath, 'result', { goalHash: require('./services/bong-browser-resolution').hash(goal), inputsHash: require('./services/bong-browser-resolution').hash(stepOutputs) }, () => this.evaluateGoalValue(goal, stepOutputs, goalPath)); | |
| } | |
| async observeGoalOperation(goalPath, operation, input, action) { | |
| const observer = this.runContext.loopObserver; | |
| return observer ? observer.observe('goal:' + goalPath + ':' + operation, input, action) : action(); | |
| } | |
| async evaluateGoalValue(goal, stepOutputs, goalPath = '0') { | |
| try { | |
| this.checkCancellation(); | |
| switch (goal.type) { | |
| case 'file_exists': { | |
| // 1. ํ์ผ ์กด์ฌ ์ฌ๋ถ ๊ฒ์ฌ | |
| if (!goal.target) return false; | |
| const fullPath = path.resolve(this.workDir, goal.target); | |
| const exists = await this.observeGoalOperation(goalPath, 'file_exists', { target: fullPath }, () => fs.existsSync(fullPath)); | |
| this.logStream.write(`[Goal Evaluation] File Exists Check ("${goal.target}"): ${exists ? 'PASSED' : 'FAILED'}\n`); | |
| return exists; | |
| } | |
| case 'file_regex': { | |
| const fullPath = path.resolve(this.workDir, goal.target); | |
| const content = await this.observeGoalOperation(goalPath, 'file_content', { target: fullPath }, () => require('./utils/regular-file-reader').readBounded(fullPath).toString('utf8')); | |
| const result = harnessExecutor.evaluateSuccessCriteria({ regex_match: goal.pattern }, content, { redosFailsCriteria: true, regexSafetyMode: 'loop' }); | |
| return result.pass && !result.error && !result.redosDetected; | |
| } | |
| case 'metric_threshold': { | |
| // 2. ์์น ์งํ ์กฐ๊ฑด ๊ฒ์ฌ (์: stepOutputs.step1.accuracy >= 0.9) | |
| if (!goal.metric_key || goal.value === undefined || goal.value === null || goal.value === '') return false; | |
| // dot notation์ ์ง์ํ์ฌ ๊ฐ์ฒด ๋ด๋ถ ๊ฐ์ ์ฐพ์ (e.g. "step_1.accuracy") | |
| const keys = goal.metric_key.split('.'); | |
| let currentVal = stepOutputs; | |
| for (const k of keys) { | |
| if (currentVal && typeof currentVal === 'object') { | |
| currentVal = currentVal[k]; | |
| } else { | |
| currentVal = undefined; | |
| break; | |
| } | |
| } | |
| await this.observeGoalOperation(goalPath, 'metric', { key: goal.metric_key }, () => ({ found: currentVal !== undefined, value: currentVal ?? null })); | |
| if (currentVal === undefined) { | |
| this.logStream.write(`[Goal Evaluation] Metric "${goal.metric_key}" not found in step outputs.\n`); | |
| return false; | |
| } | |
| const op = goal.operator || '=='; | |
| const targetVal = isNaN(Number(goal.value)) ? goal.value : Number(goal.value); | |
| const actualVal = isNaN(Number(currentVal)) ? currentVal : Number(currentVal); | |
| let isPassed = false; | |
| if (op === '>=') isPassed = actualVal >= targetVal; | |
| else if (op === '<=') isPassed = actualVal <= targetVal; | |
| else if (op === '>') isPassed = actualVal > targetVal; | |
| else if (op === '<') isPassed = actualVal < targetVal; | |
| // ๊ธฐ์กด ์ ์ฅ ๋ชฉํ์ ์ซ์ ๋ณํ ๋ค ๋์จํ ๋น๊ต ์๋ฏธ๋ฅผ ์ ์งํ๋ค. | |
| // eslint-disable-next-line eqeqeq | |
| else if (op === '==') isPassed = actualVal == targetVal; | |
| // eslint-disable-next-line eqeqeq | |
| else if (op === '!=') isPassed = actualVal != targetVal; | |
| this.logStream.write(`[Goal Evaluation] Metric Check (${goal.metric_key}: ${actualVal} ${op} ${targetVal}): ${isPassed ? 'PASSED' : 'FAILED'}\n`); | |
| // ์งํ ์ ์ฒด ๊ฐ์ง์ฉ ์ด๋ ฅ ๊ธฐ๋ก. | |
| // WHY: '=='/'!='๋ ์งํ(progress) ์งํ๊ฐ ์๋๋ผ ๊ณ ์ ๋ชฉํ์ ๋ํ ํต๊ณผ/์คํจ ํ์ ์ด๋ผ | |
| // ์๋์ ์ผ๋ก ์ ์ ์ผ ์ ์๋ค โ ์ ์ฒด ์คํ์ ๋ง๊ธฐ ์ํด ์งํ์ฑ ๋น๊ต(>=,<=,>,<)๋ง ๊ธฐ๋กํ๋ค. | |
| // ์ด๋ฏธ ํต๊ณผ(isPassed)ํ ๋ชฉํ๋ "์ ์ฒด"๊ฐ ์๋๋ผ "๋ฌ์ฑ ํ ์์ "์ด๋ฏ๋ก ๊ธฐ๋กํ์ง ์๊ณ | |
| // ๊ณผ๊ฑฐ ์ด๋ ฅ๋ ์ง์ด๋ค โ ๋ค๋ฅธ ๋ชฉํ๊ฐ ์์ง ์คํจ ์ค์ผ ๋ ์ด ๋ชฉํ์ ๊ณ ์ ๊ฐ ๋๋ฌธ์ | |
| // ์ ์ฒด ๋ฃจํ๊ฐ ์๋ชป STAGNATED๋ก ๋๋์ง ์๋๋ก ํ๋ค. | |
| // ํค๋ goal.metric_key๊ฐ ์๋๋ผ goalPath(๋ชฉํ ํธ๋ฆฌ ๋ด ์์น)๋ฅผ ์ฌ์ฉํ๋ค โ ์๋ก ๋ค๋ฅธ | |
| // ๋ชฉํ๊ฐ ์ฐ์ฐํ ๊ฐ์ metric_key ๋ฌธ์์ด์ ์จ๋ ์ด๋ ฅ์ด ์์ฌ ์ ์ฒด ํ์ ์ฐฝ์ด | |
| // ์ ๋ฐ ์๋๋ก ์ฐจ๋ ๊ฒ์ ๋ง๊ธฐ ์ํจ์ด๋ค. | |
| if ((op === '>=' || op === '<=' || op === '>' || op === '<') | |
| && typeof actualVal === 'number' && Number.isFinite(actualVal)) { | |
| if (isPassed) { | |
| this.circuitBreaker.metricHistory.delete(goalPath); | |
| } else { | |
| this.circuitBreaker.recordMetricValue(goalPath, actualVal); | |
| } | |
| } | |
| return isPassed; | |
| } | |
| case 'harness_pass': { | |
| // 3. ํ๋ค์ค ์คํ ๋ฐ ํฉ๊ฒฉ ์ฌ๋ถ ๊ฒ์ฌ | |
| if (!goal.harnessId) return false; | |
| this.logStream.write(`[Goal Evaluation] Loading validation harness "${goal.harnessId}"...\n`); | |
| const harness = db.getHarness ? db.getHarness(goal.harnessId) : null; | |
| await this.observeGoalOperation(goalPath, 'harness_definition', { id: goal.harnessId }, () => ({ hash: harness ? require('./services/bong-browser-resolution').hash(harness) : null })); | |
| if (!harness) { | |
| this.logStream.write(`[Goal Evaluation] Error: Harness "${goal.harnessId}" not found in database.\n`); | |
| return false; | |
| } | |
| // ๋ค๋จ๊ณ/๋จ์ผ ๋ชจ๋์ ์ค์ ์ ๋์ผํ๊ฒ ๊ฒ์ฆํ๋ค. ์์ ์ค์ ์ ์ฐํํ์ง ์๋๋ค. | |
| // docs/specs/harness-validation.md v1.2.0 | |
| const parsedStages = require('./config/harness-configuration').prepareHarness(harness); | |
| const validationCmd = harness.validation_command; | |
| // URL ๋ณธ๋ฌธ๊ณผ ๋ช ์์ ํ๋ฉด ๊ฒ์ฆ์ ๊ณตํต ์คํ๊ธฐ๋ฅผ ์ฌ์ฉํ๋ค. | |
| // docs/specs/remote-harness-validation.md v1.0.0 | |
| const remote = require('./remote-harness-executor'); | |
| if (!parsedStages && remote.remoteHarnessConfig(harness)) { | |
| const result = await this.observeGoalOperation(goalPath, 'remote_harness', { definitionHash: require('./services/bong-browser-resolution').hash(harness) }, () => remote.runRemoteHarness(harness, { timeoutMs: 30000, ...this.validationOptions() })); | |
| this.logStream.write('[Goal Evaluation] ' + (result.stdout || result.stderr) + '\n'); | |
| return result.success; | |
| } | |
| // B1: harness.stages(๋ค๋จ๊ณ ๊ฒ์ดํธ)๊ฐ ์์ผ๋ฉด ์์ฐจ ์คํ ๊ฒฝ๋ก๋ก ๋ถ๊ธฐ(VHK verify ๊ฐ๋ ). | |
| // stages๊ฐ ์์ผ๋ฉด ์๋ ๋จ์ผ validation_command ๊ฒฝ๋ก๊ฐ 100% ๊ธฐ์กด๊ณผ ๋์ผํ๊ฒ ๋์ํ๋ค. | |
| if (parsedStages) { | |
| this.logStream.write(`[Goal Evaluation] Multi-stage harness gate: ${parsedStages.length} stage(s)...\n`); | |
| let stagesSuccess = false; | |
| try { | |
| const modelWorkspace = parsedStages.some(stage => stage.type === 'model') | |
| ? require('./services/harness-model-workspace').inspect(this.runContext, harness) : null; | |
| const modelDefinition = modelWorkspace | |
| ? { modelDefinitionHash: require('./utils/harness-definition').fingerprint(harness), | |
| ...(modelWorkspace.workspaceOriginHash ? { modelWorkspaceHash: modelWorkspace.scopeHash } : {}) } : {}; | |
| // ๊ฐ stage๋ checkCommandSafety(๋ธ๋๋ฆฌ์คํธ ๋ฏธ์ ์ฉ, loop ๊ธฐ์กด ์ ์ฑ )+runHarnessCommand๋ก ์คํ. | |
| // required ์คํจ ์ ์กฐ๊ธฐ ์ข ๋ฃ, optional ์คํจ๋ ๊ณ์ ์งํ. | |
| const sr = await this.observeGoalOperation(goalPath, 'harness_stages', { definitionHash: require('./services/bong-browser-resolution').hash(harness), ...modelDefinition }, () => harnessExecutor.runHarnessStages({ | |
| stages: parsedStages, | |
| usageOwner: this.runContext, modelWorkspace, | |
| beforeModelSpawn: () => { | |
| let current; | |
| try { | |
| const currentHarness=db.getHarness(goal.harnessId); | |
| const scope=require('./services/harness-model-workspace').inspect(this.runContext,currentHarness); | |
| if(scope.scopeHash===modelWorkspace.scopeHash)current=require('./utils/harness-definition').fingerprint(currentHarness); | |
| } | |
| catch { /* ํ์ฌ ํ๋กํ/์ ์๋ฅผ ์ฝ์ง ๋ชปํ๋ฉด ๋ชจ๋ธ ์ ์ถ์ ๋ง๋๋ค. */ } | |
| if (current !== modelDefinition.modelDefinitionHash) throw Object.assign(new Error('Model harness definition changed before submission'), { code: 'HARNESS_MODEL_PROFILE', retryable: false }); | |
| }, | |
| cwd: this.workDir, | |
| timeoutMs: 30000, | |
| ...this.validationOptions(), | |
| windowsShell: 'cmd', | |
| applyBlacklist: false | |
| })); | |
| stagesSuccess = sr.success; | |
| for (const st of sr.stages) { | |
| const tag = st.status === 'passed' ? 'PASSED' : (st.status === 'skipped' ? 'SKIPPED' : 'FAILED'); | |
| this.logStream.write(`[Goal Evaluation] Stage "${st.name}" [${st.required ? 'required' : 'optional'}]: ${tag}\n`); | |
| } | |
| } catch (e) { | |
| if (parsedStages.some(stage => stage.type === 'model') && e.code === 'HARNESS_DEFINITION') throw Object.assign(e, { code: 'HARNESS_MODEL_PROFILE', retryable: false }); | |
| if (require('./services/harness-stop-error').isHarnessStop(e)) throw e; | |
| if (require('./services/batch-loop-observations').isStorageError(e)) throw e; | |
| this.logStream.write(`[Goal Evaluation] Multi-stage harness error: ${e.message}. FAILED.\n`); | |
| stagesSuccess = false; | |
| } | |
| this.logStream.write(`[Goal Evaluation] Multi-stage harness run: ${stagesSuccess ? 'PASSED' : 'FAILED'}\n`); | |
| return stagesSuccess; | |
| } | |
| // ์ ธ ์์ ์ฑ ๊ฒ์ฌ โ isSafeShellCommand ๋ง(๋ธ๋๋ฆฌ์คํธ ๋ฏธ์ ์ฉ, ๊ธฐ์กด ๋์ ๋ณด์กด). harness-executor ๋จ์ผ ์ถ์ฒ | |
| const safety = harnessExecutor.checkCommandSafety(validationCmd, { applyBlacklist: false }); | |
| if (!safety.safe) { | |
| this.logStream.write(`[Goal Evaluation] Security Violation: ${safety.reason}\n`); | |
| return false; | |
| } | |
| this.logStream.write(`[Goal Evaluation] Running Harness Command: "${validationCmd}"\n`); | |
| // ์ปค๋งจ๋ ์คํ(30์ด ํ์์์) โ harness-executor ๋จ์ผ ์ถ์ฒ | |
| // WHY(MEDIUM-2): ์๋ณธ์ child_process.exec()๋ฅผ ์ฌ์ฉํ๊ณ , exec()๋ win32์์ ComSpec(cmd.exe)๋ก | |
| // ์คํ๋๋ค(powershell ์๋). windowsShell:'cmd' ๋ก ๊ทธ ๋์์ ์ฌํํ๋ค. ์ด ์ธ์ ์ macOS๋ผ | |
| // ์ค์ Windows ์คํ ๊ฒ์ฆ์ ๋ถ๊ฐ๋ฅํ๊ณ , Node.js ์์ค(lib/child_process.js normalizeSpawnArguments) | |
| // ๊ธฐ์ค ๋ก์ง ๊ฒํ ๋ก๋ง ํ์ธํ๋ค โ "๊ฒ์ฆ ์๋ฃ"๊ฐ ์๋๋ผ "๋ก์ง ๊ฒํ ๋ก ๋์ฒด"์์ ๋ช ์ํ๋ค. | |
| let exitCode = 0; | |
| let cmdStdout = ''; | |
| try { | |
| const result = await this.observeGoalOperation(goalPath, 'command', { command: validationCmd, definitionHash: require('./services/bong-browser-resolution').hash(harness) }, () => harnessExecutor.runHarnessCommand({ | |
| command: validationCmd, | |
| cwd: this.workDir, | |
| timeoutMs: 30000, | |
| ...this.validationOptions(), | |
| windowsShell: 'cmd', | |
| // ํ๊ท ์์ : ์๋ ์ด ๊ฒฝ๋ก๋ child_process.exec()๋ฅผ ์ผ๊ณ ๊ธฐ๋ณธ maxBuffer 1MB ์ ํ์ด ์์๋ค. | |
| // ๊ณต์ฉ runHarnessCommand(spawn ๊ธฐ๋ฐ)๋ก ์ฎ๊ธฐ๋ฉฐ ๋ฌด์ ํ์ด ๋์ด๋ฒ๋ฆฐ ๊ฒ์ ๋ณต์ํ๋ค. | |
| maxBufferBytes: 1024 * 1024 | |
| })); | |
| exitCode = result.exitCode; | |
| cmdStdout = result.stdout; | |
| } catch (e) { | |
| if (require('./services/batch-loop-observations').isStorageError(e)) throw e; | |
| // WHY: ๊ธฐ์กด exec ๊ตฌํ์ ์คํ ์ค๋ฅ(ํ์์์ ๋ฑ) ์ error.code || 1 ๋ก ์คํจ ์ฒ๋ฆฌํ๋ค. | |
| exitCode = 1; | |
| } | |
| let isSuccess = exitCode === 0; | |
| // success_criteria.regex_match ์ถ๊ฐ ํ์ (stdout ๋์, ReDoS ์์ฌ ์ ์คํจ ์ฒ๋ฆฌ โ ๊ธฐ์กด ๋์ ๋ณด์กด) | |
| // WHY(MEDIUM-1): regexSafetyMode:'loop' ๋ก ์๋ณธ isSafeRegex(๊ธธ์ด>150 + ์ฐ์ quantifier ์ฐจ๋จ)๋ฅผ | |
| // ๋ณต์ํ๋ค. agent-runner์ 3ํจํด ์ธํธ๋ง ์ฐ๋ฉด "x++", "a.*+b" ์ฒ๋ผ RegExp ์์ฑ ์์ฒด๊ฐ throwํ๋ | |
| // ํจํด์ด ์ฌ์ ์ฐจ๋จ๋์ง ๋ชปํ๊ณ catch์ ์ผ์ผ์ ธ FAIL์ด์ด์ผ ํ ๊ฒ์ด PASS๋ก ๋ค์งํ๋ ํ๊ท๊ฐ ์์๋ค. | |
| if (isSuccess && harness.success_criteria) { | |
| const criteriaResult = harnessExecutor.evaluateSuccessCriteria(harness.success_criteria, cmdStdout, { redosFailsCriteria: true, regexSafetyMode: 'loop' }); | |
| if (criteriaResult.redosDetected) { | |
| this.logStream.write(`[Goal Evaluation] Security Alert: success_criteria regex rejected as unsafe: "${criteriaResult.regexMatch}"\n`); | |
| isSuccess = false; | |
| } else if (!criteriaResult.pass) { | |
| this.logStream.write(`[Goal Evaluation] Harness failed regex criteria match: "${criteriaResult.regexMatch}"\n`); | |
| isSuccess = false; | |
| } else if (criteriaResult.error) { | |
| this.logStream.write(`[Goal Evaluation] Warning: failed to parse/evaluate success_criteria: ${criteriaResult.error}\n`); | |
| } | |
| } | |
| this.logStream.write(`[Goal Evaluation] Harness run: ${isSuccess ? 'PASSED' : 'FAILED'}\n`); | |
| return isSuccess; | |
| } | |
| case 'test_pass': { | |
| // 4. ํ ์คํธ ์ปค๋งจ๋ ์ํ ๋ฐ ๊ฒ์ฌ | |
| if (!goal.test_command) return false; | |
| if (!isSafeShellCommand(goal.test_command)) { | |
| this.logStream.write(`[Goal Evaluation] Security Violation: Unsafe test command blocked: "${goal.test_command}"\n`); | |
| return false; | |
| } | |
| this.logStream.write(`[Goal Evaluation] Running test command: "${goal.test_command}"\n`); | |
| const result = await this.observeGoalOperation(goalPath, 'command', { command: goal.test_command }, () => harnessExecutor.runHarnessCommand({ command: goal.test_command, | |
| cwd: this.workDir, timeoutMs: 30000, windowsShell: 'cmd', maxBufferBytes: 1024 * 1024, | |
| ...this.validationOptions() })); | |
| const testResult = result.exitCode === (goal.expected_exit_code ?? 0); | |
| this.logStream.write(`[Goal Evaluation] Test command run: ${testResult ? 'PASSED' : 'FAILED'}\n`); | |
| return testResult; | |
| } | |
| case 'composite': { | |
| // 5. ์ฌ๋ฌ ์กฐ๊ฑด๋ค์ ์กฐํฉ (Logical AND / OR) | |
| const logicalOp = (goal.logical_operator || 'AND').toUpperCase(); | |
| const subGoals = goal.sub_goals || []; | |
| if (subGoals.length === 0) return true; | |
| const results = []; | |
| for (let subIndex = 0; subIndex < subGoals.length; subIndex++) { | |
| // ํ์ ๋ชฉํ๋ณ ๊ณ ์ ๊ฒฝ๋ก ํค โ metric_key ๋ฌธ์์ด์ด ์ฐ์ฐํ ๊ฒน์ณ๋ ์ ์ฒด ์ด๋ ฅ์ด | |
| // ์๋ก ๋ค๋ฅธ ๋ชฉํ๋ผ๋ฆฌ ์์ด์ง ์๊ฒ ํ๋ค. | |
| const res = await this.evaluateGoal(subGoals[subIndex], stepOutputs, `${goalPath}.${subIndex}`); | |
| results.push(res); | |
| } | |
| if (logicalOp === 'OR') { | |
| return results.some(r => r === true); | |
| } else { | |
| // ๊ธฐ๋ณธ๊ฐ์ AND | |
| return results.every(r => r === true); | |
| } | |
| } | |
| case 'wiki_sprint_approved': { | |
| // 6. ์ฌ๋ด LLM Wiki ์คํ๋ฆฐํธ ์น์ธ ๊ฒ์ดํธ(Skill_02: ์น์ธ_์ํ === Approved) ํ์ธ | |
| const gateRes = await require('./services/llm-wiki-agile-daemon').enforceSprintApprovalGate( | |
| this.workDir, | |
| { subsystem: 'loop', forceCheck: true } | |
| ); | |
| this.logStream.write( | |
| `[Goal Evaluation] LLM Wiki Sprint Gate (${gateRes.approvalStatus}): ${gateRes.allowed && !gateRes.haltRequired ? 'PASSED' : 'HALTED'}\n` | |
| ); | |
| return Boolean(gateRes.allowed && !gateRes.haltRequired); | |
| } | |
| default: | |
| this.logStream.write(`[Goal Evaluation] Unknown goal type: "${goal.type}". Evaluated as FAILED.\n`); | |
| return false; | |
| } | |
| } catch (err) { | |
| if (require('./services/harness-stop-error').isHarnessStop(err)) throw err; | |
| if (require('./services/batch-loop-observations').isStorageError(err)) throw err; | |
| this.logStream.write(`[Goal Evaluation] Exception occurred: ${err.message}\n`); | |
| return false; | |
| } | |
| } | |
| /** | |
| * ํ ๋ฒ์ ์ดํฐ๋ ์ด์ ์ด ์๋ฃ๋ ์์ ์ Goal ๋ฌ์ฑ ์ฌ๋ถ์ ๊ฐ๋๋ ์ผ ์ํ๋ฅผ ํจ๊ป ํ๊ฐํฉ๋๋ค. | |
| * @param {Object} stepOutputs - ์คํ ๋ณ ์คํ ์์ํ ๋งต | |
| * @param {Object} [iterationInfo] - ์ด๋ฒ ์ดํฐ๋ ์ด์ ์ ๋ฉํ ๋ฐ์ดํฐ (๋น์ฉ, ํ ํฐ ๋ฑ) | |
| * @returns {Promise<Object>} { shouldTerminate: boolean, reason: string, iteration: number, goalMet: boolean } | |
| */ | |
| async evaluateTermination(stepOutputs, iterationInfo = {}) { | |
| this.checkCancellation(); | |
| const usageBefore = { cost: this.runContext.cumulativeCost || 0, tokens: this.runContext.tokensUsed || 0 }; | |
| const iteration = this.circuitBreaker.currentIteration + 1; | |
| // ์ ๊ด์ธก ๊ณ์ฝ์ clock ๋๋ฝ์ ์ด์ ํ์์ผ๋ก ์ค์ธํ์ง ์๋๋ก ํจ๊ณผ ์ ์ ๊ณ ์ ํ๋ค. | |
| if (this.runContext.loopObserver) await this.runContext.loopObserver.observe('controller:evaluation_contract', { version: 1, iteration }, () => ({ clockRequired: true })); | |
| this.logStream.write(`\n--- [Loop Evaluation for Iteration ${iteration}] ---\n`); | |
| // 1. Goal๋ค ํ๊ฐ ์งํ | |
| let goalMet; | |
| if (this.goals.length === 0) { | |
| // ์ง์ ๋ ๋ชฉํ๊ฐ ์์ ๊ฒฝ์ฐ ๊ธฐ๋ณธ์ ์ผ๋ก ์ดํฐ๋ ์ด์ ์ด ์๋ฃ๋๋ฉด ๊ณจ ๋ฌ์ฑ์ผ๋ก ์ฒ๋ฆฌ | |
| goalMet = true; | |
| this.logStream.write(`[Goal Evaluation] No goals defined. Target met by default.\n`); | |
| } else { | |
| // ์ ์๋ ๋ชจ๋ Goal์ด ๋ฌ์ฑ๋์ด์ผ ๋ฃจํ๊ฐ ์ข ๋ฃ๋จ (AND ์กฐ๊ฑด ํํ) | |
| const goalResults = []; | |
| for (let goalIndex = 0; goalIndex < this.goals.length; goalIndex++) { | |
| const res = await this.evaluateGoal(this.goals[goalIndex], stepOutputs, String(goalIndex)); | |
| this.checkCancellation(); | |
| goalResults.push(res); | |
| } | |
| goalMet = goalResults.every(r => r === true); | |
| } | |
| // ๋ชจ๋ธ ๋ชฉํ ๊ฒ์ฆ ์ค ๋ฐ์ํ CLI/์ ์ฑ ๋น์ฉ๋ ๊ฐ์ ํ์ฐจ์ ํฌํจํ๋ค. ๋จ๊ณ ์คํ ์ ํฉ๊ณ์ ์ค๋ณตํ์ง ์๋๋ค. | |
| const goalCost = (this.runContext.cumulativeCost || 0) - usageBefore.cost; | |
| const goalTokens = (this.runContext.tokensUsed || 0) - usageBefore.tokens; | |
| if (!Number.isFinite(goalCost) || goalCost < 0 || !Number.isSafeInteger(goalTokens) || goalTokens < 0) { | |
| throw Object.assign(new Error('Goal evaluation usage changed unexpectedly'), { code: 'USAGE_LEDGER_FAILED', retryable: false }); | |
| } | |
| iterationInfo = { ...iterationInfo, cost: (iterationInfo.cost || 0) + goalCost, tokens: (iterationInfo.tokens || 0) + goalTokens }; | |
| // ์ต์ข evaluated ์ ์ฅ๊ณผ ๋ ๋ฆฝ๋ ์๊ฐ์ด๋ค. ์ ์ฅ ์คํจ ์ ํ์ฐจ/๋น์ฉ ์นด์ดํฐ๋ฅผ ์ ์งํ์ง ์๋๋ค. | |
| // ๋ฐฐ์น๋ receipt์ ๋ณ๋ runData๋ฅผ ๋์ง ์์ผ๋ฉฐ ๊ด์ธก ๋์ฌ๋ mock ์ 0๋ง ์ธ์ํ๋ค. | |
| const decisionTime = this.runContext.loopObserver ? await this.runContext.loopObserver.observe('controller:evaluation_clock', { | |
| iteration, iterationInfo: { cost: iterationInfo.cost || 0, tokens: iterationInfo.tokens || 0, success: iterationInfo.success !== false }, | |
| mockFallbacks: controllerPolicy.mockFallbacks(this.runContext.runData) | |
| }, () => Date.now()) : Date.now(); | |
| this.checkCancellation(); | |
| // ํ๋ก ์ฐจ๋จ๊ธฐ์ ์ดํฐ๋ ์ด์ ๊ฒฐ๊ณผ ๊ธฐ๋ก | |
| this.circuitBreaker.recordIteration({ | |
| success: iterationInfo.success !== false, | |
| cost: iterationInfo.cost || 0.0, | |
| tokens: iterationInfo.tokens || 0 | |
| }); | |
| // ๋ฆฌ์ํธ์ฉ ๋ฐ๋ณต ๊ฒฐ๊ณผ ๋์ (๋ถ๊ฐ ์ ๋ณด โ ์ ์ด ํ๋ฆ ๋ฌด๊ด). | |
| // WHY: ์ฅ์๋ช ๋ฃจํ์์ ๋ฌดํ์ ๋์ ๋์ง ์๋๋ก ์ต๊ทผ N๊ฐ๋ง ์ ์ง(๋ฉ๋ชจ๋ฆฌ ๋ณดํธ). | |
| // total_iterations ํ์๋ circuitBreaker์ ์นด์ดํฐ๋ฅผ ์ฐ๋ฏ๋ก ์ ํ๋์๋ ์ํฅ ์๋ค. | |
| this.iterationResults.push({ iteration, goalMet }); | |
| if (this.iterationResults.length > this.MAX_RECEIPT_ITERATIONS) { | |
| this.iterationResults.shift(); | |
| } | |
| // ์์ฐ ๊ฒฝ๊ณ (๋์ ๋น์ฉ์ด ์์ฐ์ 80% ์ด์์ธ์ง ํ์ธํ๊ณ ์ต์ด 1ํ ์๋ฆผ) | |
| const budgetLimit = this.circuitBreaker.tokenBudget; | |
| const currentCost = this.circuitBreaker.cumulativeCost; | |
| if (budgetLimit > 0 && currentCost >= budgetLimit * 0.8 && !this.hasWarnedBudget) { | |
| this.hasWarnedBudget = true; | |
| this.logStream.write(`[Loop Controller] WARNING: Cumulative cost ($${currentCost.toFixed(6)}) has exceeded 80% of budget ($${budgetLimit.toFixed(2)})\n`); | |
| try { | |
| if (!this.deferPublications) notifier.notifyLoopWarning(this.runContext.runId || 'UnknownTask', `๋์ ๋น์ฉ($${currentCost.toFixed(2)})์ด ์์ฐ($${budgetLimit.toFixed(2)})์ 80%๋ฅผ ์ด๊ณผํ์ต๋๋ค.`); | |
| } catch (err) { | |
| this.logStream.write(`[Loop Controller] Failed to send budget warning notification: ${err.message}\n`); | |
| } | |
| } | |
| // 2. Goal์ด ์ต์ข ๋ฌ์ฑ๋์๋์ง ๊ฒ์ฆํ์ฌ ์ ์ ์๋ฃ ํ๋จ | |
| if (goalMet) { | |
| if (!this.deferPublications) require('./services/loop-hud').publish(this, 'completed'); | |
| this.logStream.write(`[Loop Controller] Goal ACHIEVED successfully at iteration ${iteration}!\n`); | |
| try { | |
| if (!this.deferPublications) notifier.notifyLoopComplete(this.runContext.runId || 'UnknownTask', true, 'goal_achieved', currentCost); | |
| } catch (err) { | |
| this.logStream.write(`[Loop Controller] Failed to send complete notification: ${err.message}\n`); | |
| } | |
| return { | |
| shouldTerminate: true, | |
| reason: 'goal_achieved', | |
| iteration, | |
| goalMet: true, | |
| receiptSummary: this.buildReceipt('goal_achieved', null, true, decisionTime) | |
| }; | |
| } | |
| // 3. ํ๋ก ์ฐจ๋จ๊ธฐ ๊ฐ๋๋ ์ผ ์คํ ์๋ ํ์ | |
| const termination = this.breakerTermination(decisionTime); | |
| if (termination) return termination; | |
| // ๋ชฉํ๋ ๋ฌ์ฑ ๋ชปํ๊ณ ํ๋ก์ฐจ๋จ๋์ง๋ ์์์ -> ๋ค์ ์ดํฐ๋ ์ด์ ์งํ | |
| this.logStream.write(`[Loop Controller] Goal not met yet. Scheduling next iteration (${iteration + 1})...\n`); | |
| require('./services/loop-hud').publish(this, 'running'); | |
| return { | |
| shouldTerminate: false, | |
| reason: 'continue', | |
| iteration, | |
| goalMet: false | |
| }; | |
| } | |
| // ํ์ฐจ๋ฅผ ์ถ๊ฐํ์ง ์๊ณ ํ๊ฐ ๋ค ๋ฉํ ๋ถ์์ ์ค์ ์ฌ์ฉ๋์ ๊ฐ์ ํ์ฐจ์ ํฉ์ฐํ๋ค. | |
| // ์ค๋ช ๋ฌธ์: docs/specs/owned-model-groups.md v1.0.0 | |
| accountSupplementalUsage({ cost = 0, tokens = 0 }, now = Date.now()) { | |
| this.checkCancellation(); | |
| if (!Number.isFinite(cost) || cost < 0 || !Number.isSafeInteger(tokens) || tokens < 0) throw new Error('Invalid supplemental loop usage'); | |
| const nextCost = this.circuitBreaker.cumulativeCost + cost, nextTokens = this.circuitBreaker.cumulativeTokens + tokens; | |
| if (!Number.isFinite(nextCost) || !Number.isSafeInteger(nextTokens)) throw new Error('Supplemental loop usage overflow'); | |
| this.circuitBreaker.cumulativeCost = nextCost; this.circuitBreaker.cumulativeTokens = nextTokens; | |
| const termination = this.breakerTermination(now); | |
| if (!termination) require('./services/loop-hud').publish(this, 'running'); | |
| return termination; | |
| } | |
| breakerTermination(now = Date.now()) { | |
| const iteration = this.circuitBreaker.currentIteration, currentCost = this.circuitBreaker.cumulativeCost; | |
| const checkBreak = this.circuitBreaker.shouldBreak(now); | |
| if (checkBreak.break) { | |
| if (!this.deferPublications) require('./services/loop-hud').publish(this, 'circuit_broken', checkBreak.reason); | |
| this.logStream.write(`[Loop Controller] Circuit Breaker TRIPPED! Reason: ${checkBreak.reason}\n`); | |
| try { | |
| if (!this.deferPublications) notifier.notifyLoopComplete(this.runContext.runId || 'UnknownTask', false, checkBreak.reason, currentCost); | |
| } catch (err) { | |
| this.logStream.write(`[Loop Controller] Failed to send break notification: ${err.message}\n`); | |
| } | |
| return { | |
| shouldTerminate: true, | |
| reason: 'circuit_broken', | |
| breakReason: checkBreak.reason, | |
| iteration, | |
| goalMet: false, | |
| receiptSummary: this.buildReceipt('circuit_broken', checkBreak.reason, false, now) | |
| }; | |
| } | |
| return null; | |
| } | |
| /** | |
| * ์ข ๋ฃ ์์ ์ ์ฌ๋์ด ์ฝ๋ ๋ฆฌ์ํธ ํ ์คํธ๋ฅผ ํฉ์ฑํ๋ค. | |
| * WHY: DB ์กฐํ๋ ํธ์ถ๋ถ ์ฑ ์์ด๋ฏ๋ก, ์ปจํธ๋กค๋ฌ๊ฐ ๋ณด์ ํ ๋ฐ์ดํฐ(goals/๋์ ๋ฐ๋ณต๊ฒฐ๊ณผ/ํต๊ณ)๋ง | |
| * ์์ ํฌ๋งคํฐ์ ๋๊ธด๋ค. ์คํจํด๋ ๋ฃจํ ์ ์ด์ ์ํฅ์ ์ฃผ์ง ์๋๋ก ๋ฐฉ์ด์ ์ผ๋ก ๊ฐ์ผ๋ค. | |
| * @param {string} terminationReason - 'goal_achieved' | 'circuit_broken' | |
| * @param {string|null} breakReason - ํ๋ก ์ฐจ๋จ ์ฌ์ ์ฝ๋ | |
| * @param {boolean} goalMet - ์ต์ข ๋ชฉํ ๋ฌ์ฑ ์ฌ๋ถ | |
| * @returns {string|null} ๋ฆฌ์ํธ ํ ์คํธ(์์ฑ ์คํจ ์ null) | |
| */ | |
| buildReceipt(terminationReason, breakReason, goalMet, now = Date.now()) { | |
| try { | |
| return controllerPolicy.receipt({ runId: this.runContext?.runId, config: { ...this.loopConfig, goals: this.goals }, | |
| controller: { ...this.circuitBreaker, iterationResults: this.iterationResults }, | |
| reason: terminationReason, breakReason, goalMet, now, | |
| mockFallbacks: controllerPolicy.mockFallbacks(this.runContext?.runData) }); | |
| } catch (err) { | |
| // ๋ฆฌ์ํธ๋ ๋ถ๊ฐ ์ ๋ณด โ ์์ฑ ์คํจ๊ฐ ๋ฃจํ ์ข ๋ฃ๋ฅผ ๋ง์์ ์ ๋๋ค. | |
| this.logStream.write(`[Loop Controller] Failed to build receipt: ${err.message}\n`); | |
| return null; | |
| } | |
| } | |
| /** | |
| * ๋ฐ์ดํฐ๋ฒ ์ด์ค ๋ฐฑ์ ๋ฐ ํ์คํ ๋ฆฌ ๊ธฐ๋ก์ฉ ์ค๋ ์ท ์กฐํ | |
| */ | |
| getSnapshot() { | |
| return { | |
| currentIteration: this.circuitBreaker.currentIteration, | |
| cumulativeCost: this.circuitBreaker.cumulativeCost, | |
| cumulativeTokens: this.circuitBreaker.cumulativeTokens, | |
| consecutiveFailures: this.circuitBreaker.consecutiveFailures, | |
| elapsedTimeMs: Date.now() - this.circuitBreaker.startTime, | |
| metricHistory: this.circuitBreaker.metricHistory ? Object.fromEntries(this.circuitBreaker.metricHistory.entries()) : {} | |
| }; | |
| } | |
| /** | |
| * ์ค๋ ์ท ๋ฐ์ดํฐ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์ปจํธ๋กค๋ฌ ์ํ ๋ณต์ | |
| * @param {Object} snapshot | |
| */ | |
| restore(snapshot = {}) { | |
| this.circuitBreaker.restore(snapshot); | |
| if (snapshot.hasWarnedBudget !== undefined) { | |
| this.hasWarnedBudget = Boolean(snapshot.hasWarnedBudget); | |
| } | |
| } | |
| /** | |
| * DB์ loop_runs ๋ฐ loop_iterations ๊ธฐ๋ก์ ์กฐํํ์ฌ ์ด์ ๋ฃจํ๋ฅผ ๋ณต์ํฉ๋๋ค. | |
| * ์ธ์ ๊ฐ ์์จ ๋ฃจํ ๋ณต์(SPEC-INNOV-001)์ ํต์ฌ ํฉํ ๋ฆฌ ๋ฉ์๋. | |
| * | |
| * @param {string} runId - ๋ณต์ํ ๋ฃจํ ์คํ ์๋ณ์ | |
| * @param {Object} options - ์ถ๊ฐ ์ต์ (runContext, overrideConfig ๋ฑ) | |
| * @returns {Promise<LoopController>} ๋ณต์๋ LoopController ์ธ์คํด์ค | |
| */ | |
| static async restoreFromDb(runId, options = {}) { | |
| if (!runId) throw new Error('restoreFromDb requires a valid runId'); | |
| const run = db.getLoopRun(runId); | |
| if (!run) throw new Error(`Loop run with ID "${runId}" not found in database`); | |
| const iters = db.getLoopIterations(runId) || []; | |
| const lastIter = iters.length > 0 ? iters[iters.length - 1] : null; | |
| // ๊ณจ ์ค์ ๋ณต์ (run.goal_id ๊ธฐ๋ฐ) | |
| let loopConfig = options.loopConfig || {}; | |
| if (run.goal_id) { | |
| const goals = db.getLoopGoals(options.projectId || 'default') || []; | |
| const matchedGoal = goals.find(g => g.id === run.goal_id); | |
| if (matchedGoal) { | |
| let parsedGoals; | |
| try { | |
| parsedGoals = typeof matchedGoal.goal_expression === 'string' | |
| ? JSON.parse(matchedGoal.goal_expression) | |
| : matchedGoal.goal_expression; | |
| if (!Array.isArray(parsedGoals)) parsedGoals = [parsedGoals]; | |
| } catch (e) { | |
| parsedGoals = []; | |
| } | |
| loopConfig = { | |
| goals: parsedGoals, | |
| max_iterations: matchedGoal.max_iterations, | |
| token_budget: matchedGoal.token_budget, | |
| ...loopConfig | |
| }; | |
| } | |
| } | |
| const runContext = options.runContext || { | |
| runId, | |
| workDir: options.workDir || process.cwd(), | |
| logStream: options.logStream || { write: console.log }, | |
| runData: options.runData || {} | |
| }; | |
| const controller = new LoopController(runContext, loopConfig); | |
| // ๋ง์ง๋ง ์ดํฐ๋ ์ด์ ๊น์ง์ ๋์ ๋น์ฉ/ํ ํฐ/์คํจ ์ ๋ณต์ | |
| const totalCost = iters.reduce((sum, it) => sum + (parseFloat(it.cost) || 0), 0); | |
| const totalTokens = iters.reduce((sum, it) => sum + (parseInt(it.tokens_used, 10) || 0), 0); | |
| const lastSuccessIdx = iters.map(it => it.status === 'completed' || it.goal_evaluation_result === 1).lastIndexOf(true); | |
| const consecutiveFailures = lastSuccessIdx >= 0 ? iters.length - 1 - lastSuccessIdx : iters.length; | |
| // ์์ ์๊ฐ ๊ธฐ์ค ๊ฒฝ๊ณผ ์๊ฐ ๊ณ์ฐ (์ฒซ ์ดํฐ๋ ์ด์ ~ ๋ง์ง๋ง ์ดํฐ๋ ์ด์ ) | |
| let elapsedMs = 0; | |
| if (run.started_at) { | |
| const start = new Date(run.started_at).getTime(); | |
| const end = lastIter?.completed_at ? new Date(lastIter.completed_at).getTime() : Date.now(); | |
| elapsedMs = Math.max(0, end - start); | |
| } | |
| controller.restore({ | |
| currentIteration: iters.length, | |
| cumulativeCost: totalCost > 0 ? totalCost : (run.total_cost || 0), | |
| cumulativeTokens: totalTokens > 0 ? totalTokens : (run.total_tokens_used || 0), | |
| consecutiveFailures, | |
| elapsedMs | |
| }); | |
| // ์ง์ ์ดํฐ๋ ์ด์ ์ ์ํ/์๋ฌ๋ฅผ runContext์ ์ฃผ์ ํ์ฌ ๋ค์ ์คํ ์ ๋งฅ๋ฝ ๋ณด์กด | |
| if (lastIter) { | |
| let stepOutputs; | |
| try { | |
| stepOutputs = typeof lastIter.step_outputs === 'string' | |
| ? JSON.parse(lastIter.step_outputs) | |
| : (lastIter.step_outputs || {}); | |
| } catch (e) { | |
| stepOutputs = {}; | |
| } | |
| runContext.lastIteration = { | |
| iterationNumber: lastIter.iteration_number, | |
| stepOutputs, | |
| errorMessage: lastIter.error_message, | |
| goalEvaluationResult: lastIter.goal_evaluation_result | |
| }; | |
| } | |
| // Mories ์ธ์ง ๊ธฐ์ต์ ๋ฃจํ ์ฌ๊ฐ ์๋ฆผ ์ ์ก (Fire-and-Forget) | |
| require('./services/loop-hud').publish(controller, 'running'); | |
| LoopController._notifyMoriesResume(runId, iters.length, lastIter?.error_message); | |
| controller.logStream.write(`[Loop Controller] Resumed loop [${runId}] from DB: Iteration ${iters.length}, Cost $${controller.circuitBreaker.cumulativeCost.toFixed(4)} | |
| `); | |
| return controller; | |
| } | |
| /** | |
| * Mories ์ธ์ง ๊ธฐ์ต์ผ๋ก ๋ฃจํ ์ฌ๊ฐ ์๋ฆผ ์ ์ก (๋น๋๊ธฐ fire-and-forget) | |
| * @private | |
| */ | |
| static _notifyMoriesResume(runId, iterationCount, lastError) { | |
| return require('./services/mories-client').storeMemory({ | |
| content: `[LOOP_RESUME: ${runId}]\nResumed at iteration ${iterationCount}\nPrevious error: ${lastError || 'none'}`, | |
| source: 'bada-loop-engine', | |
| metadata: { runId, iterationCount, lastError: lastError || null } | |
| }, { agentId: 'bada-loop-engine', timeoutMs: 2000 }); | |
| } | |
| } | |
| module.exports = { | |
| LoopController, | |
| LoopCircuitBreaker | |
| }; | |