bada-terminal / src /loop-controller.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
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
};