/** * 설명 문서: /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} 평가 결과 (성공 시 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} { 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 인스턴스 */ 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 };