const fs = require('fs'); const path = require('path'); const os = require('os'); const pty = require('node-pty'); const vm = require('vm'); const { EventEmitter } = require('events'); const db = require('../knowledge-db'); const configManager = require('./config-manager'); const ctx = require('./context'); const workspaceLease = require('./utils/workspace-lease'); const logCleaner = require('./utils/log-cleaner'); const processHelper = require('./utils/process-helper'); const providersConfig = require('./config/providers-config'); const llmProviderService = require('./services/llm-provider-service'); const { LoopController } = require('./loop-controller'); const batchEvents = new EventEmitter(); const { ConcurrencyQueue } = require('./utils/queue-manager'); const stepRunners = require('./batch-step-runners'); const { isUncertainCliFailure } = require('./utils/cli-storage-error'); const batchRunLease = require('./services/batch-run-lease'); const batchAdmission = require('./services/batch-admission'); const batchDefinition = require('./utils/batch-definition'); const browserLifecycle = require('./services/bong-browser-lifecycle'); // [Phase C - C4] 동적 동시성 레벨 조정 (Adaptive Concurrency) function getDynamicConcurrencyLimit() { try { const cores = os.cpus().length; const totalMemGb = os.totalmem() / (1024 * 1024 * 1024); let calculated = Math.min(Math.floor(cores / 2), Math.floor(totalMemGb / 4)); return Math.max(2, Math.min(calculated, 6)); } catch (e) { return 2; // fallback } } const batchQueue = new ConcurrencyQueue(getDynamicConcurrencyLimit()); const MAX_BUFFER_SIZE = 10 * 1024 * 1024; // 10MB 버퍼 크기 상한 설정 const { escapeShellArg, isSafeShellCommand } = require('./utils/shell-helper'); const { sanitizeEnv } = require('./utils/env-sanitizer'); const scheduledJobs = new Map(); const scheduleRegistrationErrors = new Map(); function disposeScheduledJob(job) { try { if (typeof job.destroy === 'function') job.destroy(); else { const stopped = job.stop(); stopped?.catch(error => writeDebugLog('[Schedule cleanup] ' + error.message)); } } catch (error) { writeDebugLog('[Schedule cleanup] ' + error.message); } } const runningTasks = new Set(); const activeTaskRuns = new Map(); const pendingTaskOperations = new Set(); let stoppingTasks = null; function getScheduleLedger() { return require('./services/batch-schedule-ledger').createScheduleLedger(path.join(path.dirname(db.getStorageStatus().path), 'batch-schedule-ledger')); } function freshScheduledTask(task) { return db.runInTransaction(() => { const latest = db.getBatchTasks(task.project_id).find(item => item.id === task.id); return latest ? JSON.parse(JSON.stringify(latest)) : null; }); } async function fireScheduledTask(task, now = Date.now()) { const { retryScheduleWrite } = require('./services/batch-schedule-ledger'); const latest = await retryScheduleWrite(() => freshScheduledTask(task)); if (!latest || latest.is_active !== 1) return { success: false, skipped: true }; batchDefinition.assertCertified(latest); const prior = db.getLatestTaskRun(latest.id); const ledger = getScheduleLedger(); const claim = await retryScheduleWrite(() => ledger.claim({ ...latest, schedule_from: prior?.started_at || latest.created_at }, now, () => { const owner = batchRunLease.inspect(latest.id); // 다른 작업의 폴더 대기는 기존 큐에서 처리한다. 같은 task의 실행권/미완료 기록만 발생 건 소비를 막는다. return owner.ownerState === 'released' && owner.records.length === 0 && !owner.browserError; })); if (!claim) return { success: false, skipped: true }; const scheduledOrigin = require('./services/batch-scheduled-origin').create(latest, await retryScheduleWrite(() => ledger.bind(latest, claim.id, 'run_' + require('crypto').randomUUID())), claim.id); let result; try { result = await runTask(latest, false, { scheduled: true, scheduledOrigin }); } catch (error) { result = { success: false, error: error.message }; } await retryScheduleWrite(() => ledger.finish(latest, claim.id, result)); if (latest.cron_expr.startsWith('at:') || latest.cron_expr.startsWith('once:')) deactivateOnceTask(latest.id, latest); return result; } async function resolveScheduleClaim(projectId, taskId, claimId, resolution) { const { retryScheduleWrite } = require('./services/batch-schedule-ledger'); const task = await retryScheduleWrite(() => freshScheduledTask({ project_id: projectId, id: taskId })); if (!task) throw new Error('예약 작업을 찾을 수 없습니다.'); const state = await retryScheduleWrite(() => getScheduleLedger().resolve(task, claimId, resolution)); if (state.onceConsumed && state.definition.expression === task.cron_expr) deactivateOnceTask(task.id, task); return state; } const { spawn, exec } = require('child_process'); function writeDebugLog(msg) { try { // 활성 CLI(claude/opencode 등)의 홈 디렉토리에 디버그 로그를 기록한다. // 경로 규약은 src/config/cli-paths.js 참조 (오픈코드 연동 하드코딩 제거). const logPath = require('./config/cli-paths').getCliHomeFilePath('desktop-cli-debug.log'); const time = new Date().toISOString(); fs.appendFileSync(logPath, `[${time}] [BatchManager] ${msg}\n`, 'utf-8'); } catch (e) { /* intentional: 디버그 로그 기록 자체의 실패는 무시 */ } } function sendIpcToWindows(channel, data) { // 메인 프로세스 내부의 이벤트 리스너를 위해 복사 전송 batchEvents.emit(channel, data); // 루프 이벤트의 창 전송은 여기서 한 번만 맡는다. 같은 창의 별칭도 중복 전송하지 않는다. // 설명 문서: docs/specs/batch-step-continuation.md v0.11.0 const windows = new Set([ctx.mainWindow, ctx.batchSchedulerWindow, ...(['loop:iteration', 'loop:complete'].includes(channel) ? [ctx.workflowMonitorWindow] : [])]); let uncertain = false; for (const win of windows) { try { if (win && !win.isDestroyed()) { win.webContents.send(channel, data); } } catch (e) { uncertain = true; writeDebugLog(`Failed to send IPC to window: ${e.message}`); } } return { status: uncertain ? 'uncertain' : 'submitted' }; } function isProcessAlive(pid) { return processHelper.isProcessAlive(pid); } function deactivateOnceTask(taskId, expectedTask) { try { writeDebugLog(`Deactivating once-run task: ${taskId}`); const projects = expectedTask ? [expectedTask.project_id] : (configManager.getRecentDirs() || []).map(dir => configManager.getProjectFolderForPath(dir) || configManager.getProjectFolderFallback(dir)); for (const projFolder of projects) { if (!projFolder) continue; const changed = db.runInTransaction(() => { const taskObj = db.getBatchTasks(projFolder).find(t => t.id === taskId); if (!taskObj || (expectedTask && (taskObj.cron_expr !== expectedTask.cron_expr || taskObj.timezone !== expectedTask.timezone))) return false; db.saveBatchTask(projFolder, { ...taskObj, is_active: 0 }); return true; }); if (changed) { unscheduleTask(taskId); sendIpcToWindows('batch-task-status-updated', { taskId: taskId, is_active: 0 }); break; } } } catch (e) { writeDebugLog(`Failed to deactivate once task ${taskId}: ${e.message}`); } } function resolveWorkspacePath(projFolder) { if (path.isAbsolute(projFolder) && fs.existsSync(projFolder)) { return projFolder; } const recentDirs = configManager.getRecentDirs() || []; for (const dir of recentDirs) { const folder = configManager.getProjectFolderForPath(dir) || configManager.getProjectFolderFallback(dir); if (folder === projFolder) { return dir; } } let resolved = ''; if (process.platform === 'win32') { const clean = projFolder.replace(/^-/, ''); const driveMatch = clean.match(/^([a-zA-Z])-(.*)/); if (driveMatch) { resolved = `${driveMatch[1]}:\\${driveMatch[2].replace(/-/g, '\\')}`; } else { resolved = clean.replace(/-/g, '\\'); } } else { let clean = projFolder; if (clean.startsWith('-')) clean = clean.substring(1); resolved = '/' + clean.replace(/-/g, '/'); } // Heuristic path reconstruction if hyphen was used in original directory name if (!fs.existsSync(resolved)) { const separator = process.platform === 'win32' ? '\\' : '/'; const parts = resolved.split(separator); for (let i = parts.length - 2; i >= 0; i--) { const testParts = [...parts.slice(0, i), parts.slice(i).join('-')]; const testPath = (process.platform === 'win32' ? '' : separator) + testParts.join(separator); if (fs.existsSync(testPath)) { return testPath; } } } return resolved; } /** * Windows 파일 잠금 및 메모리 오버헤드를 우회하기 위한 파일의 역방향 부분 읽기 함수 */ async function readLastLines(filePath, maxLines = 30, maxBytesToRead = 2048) { let fh; try { const fsPromises = fs.promises; if (!fs.existsSync(filePath)) return ''; const stat = await fsPromises.stat(filePath); if (stat.size === 0) return ''; fh = await fsPromises.open(filePath, 'r'); // 파일 크기보다 우리가 읽을 버퍼 크기가 크면 전체 크기만큼 읽음 const bytesToRead = Math.min(stat.size, maxBytesToRead); const position = stat.size - bytesToRead; const buffer = Buffer.alloc(bytesToRead); await fh.read(buffer, 0, bytesToRead, position); const text = buffer.toString('utf8'); // RAG 데이터 정제 적용 const sanitizedText = logCleaner.sanitizeRagLog(text); const lines = sanitizedText.split(/\r?\n/); // 비어있지 않은 유효한 라인만 추출하여 마지막 maxLines만큼 자르기 const lastLines = lines.filter(l => l.trim() !== '').slice(-maxLines); return lastLines.join('\n'); } catch (error) { writeDebugLog(`[RAG] 과거 로그 읽기 실패 (${filePath}): ${error.message}`); return ''; // 실패 시 빈 문자열 반환하여 배치 중단 방지 } finally { if (fh) { try { await fh.close(); // 파일 디스크립터(FD) 누수 방지 } catch (e) { /* intentional: 파일 핸들 해제 실패 무시 */ } } } } function isPromptReady(cleanBuffer) { const lines = cleanBuffer.split(/\r?\n/); for (let i = lines.length - 1; i >= 0; i--) { const line = lines[i].trim(); if (!line) continue; // 팁 문구와 함께 프롬프트가 한 라인으로 제공될 때(예: '❯ Try "..."')에 대비하여 includes로 판정 확장. // HUD 팁 문구 필터링보다 우선 적용하여 FSM 오탐 및 30초 초기화 타임아웃을 방지합니다. // 일반 > 기호는 가이드 텍스트 등에서의 오탐을 막기 위해 행 끝에 위치하는 경우로 제한합니다. if (line.includes('❯') || line.endsWith('>') || />\s*$/.test(line)) { return true; } // Skip separator lines if (/^[─\-═\s·•]+$/.test(line)) { continue; } // Skip HUD/status lines if (line.includes('bypass') || line.includes('permissions') || line.includes('OMC HUD') || line.includes('omc-setup') || line.includes('Boondoggling') || line.includes('Thinking') || line.includes('Cogitated') || line.includes('effort') || line.includes('control this session') || line.includes('shift+tab') || line.includes('bypasspermissionson')) { continue; } return false; } return false; } // Step runner 모듈 초기화 (공유 헬퍼 주입) stepRunners.init({ writeDebugLog, isProcessAlive, isPromptReady, MAX_BUFFER_SIZE }); /** * 활성화된 모든 배치 태스크 스케줄 등록 */ async function initialize() { try { writeDebugLog('Initializing batch scheduler...'); for (const [id, job] of scheduledJobs.entries()) { disposeScheduledJob(job); } scheduledJobs.clear(); if (db.isJsonFallback()) { writeDebugLog('Fallback JSON database active, reading fallback tasks.'); } // 최근 폴더는 UI 편의 목록(최대 5개)이므로 예약 복원의 기준으로 쓰지 않는다. // 영속 DB의 활성 예약을 읽되 실제 등록/실행은 기존 최신 정의·인증·claim 검사를 거친다. const tasks = db.getActiveBatchTasks(); const processedTasks = new Set(); for (const task of tasks) { if (processedTasks.has(task.id)) continue; processedTasks.add(task.id); if (task.is_active === 1) { try { await scheduleTask(task, { refresh: true }); } catch (error) { failScheduleRegistration(task, error); continue; } if (!task.cron_expr?.startsWith('watch:')) fireScheduledTask(task).catch(error => writeDebugLog('[Catch-up] ' + error.message)); } } writeDebugLog(`Scheduled ${scheduledJobs.size} active batch tasks.`); } catch (error) { writeDebugLog(`Error initializing scheduler: ${error.message}`); } } /** * 개별 작업 스케줄 등록/갱신 */ const scheduleOperations = new Map(); function serializeSchedule(taskId, action) { const previous = scheduleOperations.get(taskId) || Promise.resolve(); const pending = previous.catch(() => {}).then(action); scheduleOperations.set(taskId, pending); pending.finally(() => { if (scheduleOperations.get(taskId) === pending) scheduleOperations.delete(taskId); }).catch(() => {}); return pending; } function failScheduleRegistration(task, error) { unscheduleTask(task.id); scheduleRegistrationErrors.set(task.id, error.message); try { db.runInTransaction(() => { const latest = db.getBatchTasks(task.project_id).find(item => item.id === task.id); if (latest?.is_active === 1 && latest.cron_expr === task.cron_expr && latest.timezone === task.timezone) db.saveBatchTask(task.project_id, { ...latest, is_active: 2 }); }); } catch (saveError) { writeDebugLog('[Schedule error state] ' + saveError.message); } sendIpcToWindows('batch-schedule-error', { taskId: task.id, error: error.message }); } async function prepareScheduledTask(task) { if (typeof task.id !== 'string' || !task.id || ![0, 1, 2].includes(task.is_active)) throw new Error('Invalid batch task identity or active state'); if (task.is_active !== 1) return null; batchDefinition.assertCertified(task); const timezone = task.timezone || getScheduleLedger().inspect(task)?.definition?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone; const job = await require('./services/batch-trigger-registration').prepareTrigger({ ...task, timezone }, { cwd: resolveWorkspacePath(task.project_id), fire: async () => { if (!task.cron_expr.startsWith('watch:')) return fireScheduledTask(task); const latest = freshScheduledTask(task); if (!latest || latest.is_active !== 1 || latest.cron_expr !== task.cron_expr) return; return runTask(latest, false, { scheduled: true }); }, onError: error => writeDebugLog('[Schedule] ' + task.id + ': ' + error.message), onRegistrationError: error => { if (scheduledJobs.get(task.id) !== job) return; failScheduleRegistration(task, error); } }); return job; } function installScheduledTask(task, job) { job?.assertReady(); const previous = scheduledJobs.get(task.id); if (previous) disposeScheduledJob(previous); scheduledJobs.delete(task.id); scheduleRegistrationErrors.delete(task.id); if (job) { scheduledJobs.set(task.id, job); job.enable(); } } function scheduleTask(task, { refresh = false } = {}) { return serializeSchedule(task.id, async () => { if (refresh) { const latest = freshScheduledTask(task); if (!latest) { unscheduleTask(task.id); return { success: true, scheduled: false }; } task = latest; } const job = await prepareScheduledTask(task); try { installScheduledTask(task, job); } catch (error) { if (job) await job.stop(); throw error; } return { success: true, scheduled: !!job }; }); } function saveScheduledTask(projectId, task, { patch = false, signal } = {}) { return serializeSchedule(task.id, async () => { signal?.throwIfAborted(); const previous = freshScheduledTask({ id: task.id, project_id: projectId }); if (patch) { if (!previous) throw new Error('Task not found'); task = { ...previous, ...task }; } const normalized = { ...task, project_id: projectId, is_active: task.is_active ?? 0, timezone: require('./utils/batch-timezone').batchTimezone(task.timezone, previous?.timezone) }; // 비활성 저장도 정책을 검사하고 SQLite/JSON에 동일한 정의를 저장한다. const loop = require('./config/loop-configuration').normalize(normalized.loop_config, { requireGoals: false }); normalized.loop_config = loop ? JSON.stringify(loop) : null; Object.assign(normalized, batchDefinition.forSave(previous, normalized)); const job = await prepareScheduledTask(normalized); try { db.runInTransaction(() => { signal?.throwIfAborted(); job?.assertReady(); const current = db.getBatchTasks(projectId).find(item => item.id === task.id); Object.assign(normalized, batchDefinition.forSave(current, normalized)); if (normalized.is_active === 1) batchDefinition.assertCertified(normalized); db.saveBatchTask(projectId, normalized); }); } catch (error) { if (job) await job.stop(); throw error; } installScheduledTask(normalized, job); return { success: true, scheduled: !!job }; }); } function deleteScheduledTask(projectId, taskId) { return serializeSchedule(taskId, async () => { const release = batchRunLease.acquire(taskId); try { db.runInTransaction(() => { if (!db.getBatchTasks(projectId).some(task => task.id === taskId)) throw new Error('Task not found'); db.deleteBatchTask(projectId, taskId); }); } finally { release(); } unscheduleTask(taskId); abortTask(taskId); return { success: true }; }); } function importBatchTasks(projectId, tasks) { if (!Array.isArray(tasks)) throw new Error('올바른 JSON 배열 형식이 아닙니다.'); const imported = tasks.map(task => { if (!task || typeof task.name !== 'string' || !task.name.trim()) throw new Error('작업 이름이 비어 있습니다.'); const steps = typeof task.steps_json === 'string' ? JSON.parse(task.steps_json) : task.steps || []; if (!Array.isArray(steps)) throw new Error('작업 단계는 배열이어야 합니다.'); return { ...task, id: 'task_' + require('crypto').randomUUID(), project_id: projectId, steps_json: JSON.stringify(steps), is_active: 0, is_tested_success: 0, timezone: require('./utils/batch-timezone').batchTimezone(task.timezone), loop_config: task.loop_config && typeof task.loop_config === 'object' ? JSON.stringify(task.loop_config) : task.loop_config }; }); db.runInTransaction(() => { for (const task of imported) db.saveBatchTask(projectId, task); }); return { success: true, imported: imported.length }; } /** * 작업 강제 취소/스케줄 해제 */ function unscheduleTask(taskId) { if (scheduledJobs.has(taskId)) { disposeScheduledJob(scheduledJobs.get(taskId)); scheduledJobs.delete(taskId); writeDebugLog(`Unscheduled task: ${taskId}`); } } /** * 프로세스 트리 (하위 그룹 전체) 강제 종료 */ function killProcessTree(pid, isSync = false) { writeDebugLog(`Killing process group/tree for PID: ${pid} (sync: ${isSync})`); processHelper.killProcessTree(pid, isSync); } /** * 활성 중인 모든 자식 프로세스 트리를 강제 청소 (앱 종료 훅 등에서 연동) */ function cleanupAllActiveRuns() { if (stoppingTasks) return stoppingTasks; let finish; const pending = new Promise(resolve => { finish = resolve; }); stoppingTasks = pending; batchAdmission.cancelAll(); const interactiveClosing = []; writeDebugLog(`Performing cleanup of all active runs. Count: ${activeTaskRuns.size}`); for (const [taskId, activeRun] of activeTaskRuns.entries()) { activeRun.aborted = true; activeRun.lifecycleController?.abort(new Error('Batch task cancelled')); interactiveClosing.push(require('./utils/interactive-cli-session').closeSession(activeRun)); if (activeRun.currentProcess) { try { const pid = activeRun.currentProcess.pid; if (pid) killProcessTree(pid, true); else activeRun.currentProcess.kill(); } catch (e) { /* intentional: 프로세스 종료 실패 무시 (이미 종료 가능) */ } } if (activeRun.workflowPty) { try { activeRun.workflowPty.kill('SIGKILL'); } catch (e) { /* intentional: 프로세스 종료 실패 무시 (이미 종료 가능) */ } } if (activeRun.abortController) { try { activeRun.abortController.abort(); } catch (e) { /* intentional: best-effort 정리, 실패 시 무시 */ } } } // 활성 소유자는 finally의 정산/이력/실행권 해제까지 유지한다. 대기 접수도 함께 정리한다. // 설명 문서: docs/specs/owned-model-groups.md v1.0.0 Promise.allSettled([...pendingTaskOperations, ...interactiveClosing]).then(() => { if (stoppingTasks === pending) stoppingTasks = null; finish(); }); return pending; } /** * 실행 중인 작업 강제 종료 */ function abortTask(taskId) { const queued = batchAdmission.cancel(taskId); const activeRun = activeTaskRuns.get(taskId); return activeRun ? abortActiveRun(activeRun) : queued; } // 요청 소유 signal은 다른 접수/예약 실행을 취소하지 않고 정확한 실행 객체만 중단한다. // 설명 문서: docs/specs/bong-dependency-repair.md (v1.2.0) function abortActiveRun(activeRun) { if (activeRun) { activeRun.aborted = true; activeRun.lifecycleController?.abort(new Error('Batch task cancelled')); writeDebugLog(`Aborting task ${activeRun.taskId} (RunId: ${activeRun.runId})`); if (activeRun.workflowPty) { try { activeRun.workflowPty.kill(); } catch (e) { /* intentional: 디버그 로그 기록 자체의 실패는 무시 */ } } if (activeRun.currentProcess) { try { const pid = activeRun.currentProcess.pid; if (pid) { killProcessTree(pid); } if (typeof activeRun.currentProcess.kill === 'function') { activeRun.currentProcess.kill('SIGKILL'); } } catch (e) { writeDebugLog(`Failed to kill process: ${e.message}`); } } if (activeRun.abortController) { try { activeRun.abortController.abort(); } catch (e) { /* intentional: best-effort 정리, 실패 시 무시 */ } } return true; } return false; } // Step runner 함수들은 ./batch-step-runners.js 모듈로 분리됨 const { interpolateConfig, runCliStep, runApiStep, runLocalLlmStep, runPtyAgentStep, runTransformStep, runWorkflowStep, getN8nConfig, runAgentCallStep, runConductorStep, runN8nStep } = stepRunners; /** * 복합 작업 워크플로우 순차 실행 엔진 (동시성 제어 큐 적용) */ function runTask(task, isDryRun = false, options = {}) { try { require('./security/host-launch').assertHostPathSupported('uncontained-task'); } catch (error) { return Promise.resolve({ success: false, error: error.message, code: error.code }); } if (stoppingTasks || ctx.isQuitting) return Promise.resolve({ success: false, error: 'Batch shutdown is in progress' }); if (options.scheduledOrigin && options.scheduled !== true) return Promise.resolve({ success: false, error: '예약 실행 연결은 예약 접수에서만 사용할 수 있습니다.' }); let admission; try { if(options.rigExecution!==undefined)require('./services/bong-rig-execution-capability').inspect(options.rigExecution,task);admission = batchAdmission.admit(task); } catch (error) { return Promise.resolve({ success: false, error: error.message }); } const cancelAdmission = () => admission.controller.abort(new Error('Batch request cancelled')); options.signal?.addEventListener('abort', cancelAdmission, { once: true }); if (options.signal?.aborted) cancelAdmission(); // 언어는 접수 시 한 번만 고정한다. 큐 대기 중 설정 변경이나 후속 단계 입력으로 바뀌지 않는다. // 설명 문서: /docs/specs/bada-bong-language-settings.md (v0.3.0) let replyLanguage; try { replyLanguage = options.resume ? undefined : require('./utils/agent-reply-language').capture(require('./db/batch-checkpoint-record').stepsFor(admission.task), options); } catch(error) { admission.dequeue();options.signal?.removeEventListener('abort',cancelAdmission);return Promise.resolve({success:false,error:error.message}); } const acceptedOptions = { ...options, admission, replyLanguage }; const operation = batchQueue.enqueue(() => { admission.dequeue(); try { admission.assertCurrent(); } catch (error) { return { success: false, error: error.message }; } return runTaskInternal(admission.task, isDryRun, acceptedOptions); }, { signal: admission.controller.signal }).catch(error => ({ success: false, error: error.message })) .finally(() => { options.signal?.removeEventListener('abort', cancelAdmission); admission.dequeue(); }); pendingTaskOperations.add(operation); operation.then(() => pendingTaskOperations.delete(operation), () => pendingTaskOperations.delete(operation)); return operation; } // 원래 실행의 승인 영수증을 요구한다. restart와 달리 run/log/원장을 새로 만들지 않는다. // 설명 문서: docs/specs/batch-step-continuation.md (v0.20.0, R67 진행 중) function resumeBatchRun(runId, { fingerprint, signal, toolPolicyApprove } = {}) { try { const state = require('./services/batch-continuation').prepared(runId, fingerprint); return runTask(state.task, state.checkpoint.isDryRun, { signal, toolPolicyApprove, resume: { runId, fingerprint } }).then(result => ({ ...result, runId })); } catch (error) { return Promise.resolve({ success: false, runId, error: error.message }); } } function runTaskInternal(task, isDryRun = false, options = {}) { return new Promise((resolve) => { let telemetry; (async () => { if (runningTasks.has(task.id)) { writeDebugLog(`Task ${task.id} is already running. Skipping.`); return resolve({ success: false, error: 'Already running' }); } let restored; if (options.resume) { try { restored = require('./services/batch-continuation').prepared(options.resume.runId, options.resume.fingerprint); require('./utils/batch-definition').assertRequestReservation(restored.checkpoint.definition, db.getRuntimeUsage(options.resume.runId)); if (restored.task.id !== task.id || restored.task.project_id !== task.project_id || options.scheduled) throw new Error('배치 복구 요청의 작업이 다릅니다.'); isDryRun = restored.checkpoint.isDryRun; } catch (error) { return resolve({ success: false, runId: options.resume.runId, error: error.message }); } } const continuationContext = restored?.checkpoint.contextHash; const assertContinuationContext = () => { if (!continuationContext) return; try { options.admission.assertCurrent(); if (require('./services/batch-recovery-context').capture(activeRun.workDir) !== continuationContext) throw new Error(); } catch { throw Object.assign(new Error('승인한 배치 실행 설정이 변경됐습니다.'), { code: 'BATCH_CONTINUATION_CHANGED', retryable: false }); } }; // 손상된 영속 언어는 소유권/로그/실행 기록을 만들기 전에 거부한다. 없는 과거 값만 auto다. const replyPolicy = require('./utils/agent-reply-language');let replySnapshot; try { replySnapshot=restored?replyPolicy.restore(restored.checkpoint.replyLanguage,require('./db/batch-checkpoint-record').stepsFor(task)):options.replyLanguage; } catch(error) { return resolve({success:false,runId:options.resume?.runId,error:error.message}); } runningTasks.add(task.id); const runId = restored?.row.run_id || options.scheduledOrigin?.runId || 'run_' + require('crypto').randomUUID(); let logStream = null; let logPath = ''; let workDir = ''; let taskFailed = false; let failedReason = null; let lockAcquired = false; // 락 획득 플래그 도입 (Fail-safe 락 해제 목적) let steps = []; let stepOutputs = {}; let loopLedger = null; let stepCheckpoint; let loopOutbox; let releaseOwnedRun; const activeRun = { runId, taskId: task.id, projectId: task.project_id, testVerified: false, currentProcess: null, abortController: null, lifecycleController: new AbortController(), // 실행 소유 연결이 승인한 callback이며 task/DB에는 저장하지 않는다. toolPolicyApprove:typeof options.toolPolicyApprove==='function'?options.toolPolicyApprove:undefined, aborted: false }; replyPolicy.attach(activeRun,replySnapshot); activeTaskRuns.set(task.id, activeRun); const cancelRequested = () => abortActiveRun(activeRun); options.signal?.addEventListener('abort', cancelRequested, { once: true }); let fileLogCleaner = null; try { options.signal?.throwIfAborted(); // 설명 문서: /docs/specs/bada-bong-rig-execution.md (v0.1.0) // 준비 단계에서 실패해도 정리 완료 전까지 좌석을 재사용하지 않도록 실제 소유자만 먼저 연결한다. require('./services/bong-rig-execution-capability').observeOwner(options.rigExecution,activeRun,task); activeRun.executionLease = restored ? batchRunLease.claimReview(task.id, restored.lock, runId).release : batchRunLease.acquire(task.id, runId, { manualBrowserTrial: isDryRun === true && options.scheduled !== true }); if (restored) activeRun.preserveExecutionLease = true; options.admission.assertCurrent(); if (options.scheduled) { const latest = freshScheduledTask(task); if (!latest || latest.is_active !== 1 || latest.cron_expr !== task.cron_expr || latest.timezone !== task.timezone) throw new Error('Scheduled task was paused, deleted or changed before execution'); batchDefinition.assertCertified(latest); // 파일 감시는 cron 발생 건을 소비하지 않는다. 자동 상태/인증 검사는 유지하고 가짜 연결은 거부한다. if (latest.cron_expr.startsWith('watch:')) { if (options.scheduledOrigin) throw new Error('파일 감시 실행에는 예약 발생 건 연결을 사용할 수 없습니다.'); } else { if (!options.scheduledOrigin) throw new Error('예약 발생 건과 실행 연결이 필요합니다.'); require('./services/batch-scheduled-origin').dispatch(options.scheduledOrigin, latest); } } // 배치 실행 로그는 활성 CLI 홈 하위 batch-logs/ 에 기록한다 (규약: src/config/cli-paths.js). // 실제 사용 경로는 db.startBatchRun 으로 런별 영속화되므로 이후 조회는 DB의 logPath가 기준. const logsDir = require('./config/cli-paths').getCliHomeFilePath('batch-logs'); if (!fs.existsSync(logsDir)) { fs.mkdirSync(logsDir, { recursive: true }); } const safeTaskId = String(task.id).replace(/[^a-zA-Z0-9_-]/g, '_'); logPath = restored?.row.log_path || path.join(logsDir, `${safeTaskId}-${runId}.log`); workDir = restored?.row.work_dir || resolveWorkspacePath(task.project_id); if (!restored) try { db.runInTransaction(() => { db.startBatchRun(runId, task.id, logPath, workDir); if (isDryRun) db.updateBatchTaskTestStatus(task.id, 0); }); activeRun.recordStarted = true; } catch (error) { activeRun.preserveExecutionLease = true; throw error; } // 마일스톤 3: 배치 런 노드 지식 DB 적재 if (!restored) try { db.runInTransaction(() => db.saveNode(task.project_id, { id: `batch_run:${runId}`, type: 'batch_run', label: `Batch Run: ${runId.substring(4)}`, properties: { category: 'batch', status: 'running', taskId: task.id } })); } catch (nodeErr) { writeDebugLog(`Failed to save batch_run node on start: ${nodeErr.message}`); } workDir = restored?.row.work_dir || resolveWorkspacePath(task.project_id); if (!ctx.isSafePath(workDir)) { throw new Error(`Workspace directory is restricted / unsafe: ${workDir}`); } // 마일스톤 2: 프로젝트 디렉토리 락 획득 (대기 타임아웃 30초) writeDebugLog(`Acquiring project lock for: ${workDir} (Task: ${task.id})`); activeRun.workDir = workDir; // 원래 source→worktree 순서를 유지한다. 승인 복구에서 새 격리 폴더를 만들지 않는다. if (restored?.checkpoint.workspaceOrigin) { activeRun.sourceLease = await workspaceLease.acquire(restored.checkpoint.workspaceOrigin.source, 'batch-source:' + runId, { signal: activeRun.lifecycleController.signal }); activeRun.workspaceOrigin = restored.checkpoint.workspaceOrigin; activeRun.workspace = require('./services/batch-workspace-proof').workspace(activeRun.workspaceOrigin); } activeRun.lease = await workspaceLease.acquire(workDir, 'batch:' + runId, { signal: activeRun.lifecycleController.signal }); lockAcquired = true; // 성공 시에만 락 플래그 True activeRun.lifecycleController.signal.throwIfAborted(); options.admission.assertCurrent(); if (restored) { require('./services/batch-scheduled-origin').locked(restored.checkpoint, () => db.runInTransaction(() => { const heldFingerprint = require('./db/reviewed-store-lock').readLock(batchRunLease.file(task.id)).fingerprint; restored = require('./services/batch-continuation').prepared(runId, options.resume.fingerprint, { heldFingerprint, workspaceHeld: true }); require('./services/batch-loop-resume').claim(db, restored); db.transitionBatchRun(runId, restored.row, 'running'); }, { mode: 'immediate' })); activeRun.recordStarted = true; activeRun.preserveExecutionLease = false; } writeDebugLog(`Project lock acquired for: ${workDir} (Task: ${task.id})`); if (options.scheduled) batchDefinition.assertCertified(freshScheduledTask(task)); writeDebugLog(`Running batch workflow "${task.name}" (DryRun: ${isDryRun}) in: ${workDir}`); if (!fs.existsSync(workDir)) { throw new Error(`Workspace directory does not exist: ${workDir}`); } logStream = fs.createWriteStream(logPath, { flags: 'a' }); const originalWrite = logStream.write.bind(logStream); // Real-time log streaming to renderer via IPC (with line-by-line filtering) const sendLog = (data) => { const cleaned = logCleaner.cleanTerminalLog(data.toString()); if (cleaned.trim()) { sendIpcToWindows('batch-run-log', { taskId: task.id, runId, data: cleaned + '\n' }); } }; // 실시간 파일 쓰기용 LineBufferCleaner fileLogCleaner = new logCleaner.LineBufferCleaner((cleanedLine) => { originalWrite(Buffer.from(cleanedLine, 'utf8'), 'utf8'); }); logStream.write = (chunk, encoding, callback) => { sendLog(chunk); // LineBufferCleaner에 밀어넣어 줄 단위로 필터링하고 파일에 쓴다. fileLogCleaner.write(chunk); if (typeof callback === 'function') callback(); return true; }; logStream.write(`=== BADA Batch Run Started: ${new Date().toISOString()} ===\n`); logStream.write(`Task Name: ${task.name}\n`); logStream.write(`Workspace: ${workDir}\n`); logStream.write(`Execution Mode: ${isDryRun ? 'DRY-RUN (Test)' : 'SCHEDULED'}\n`); logStream.write(`====================================================\n\n`); // IPC 알림 (실행 시작) sendIpcToWindows('batch-run-started', { taskId: task.id, runId, name: task.name, isDryRun }); steps = []; try { if (task.steps_json) { steps = JSON.parse(task.steps_json); } else if (task.steps) { steps = task.steps; } } catch (e) { writeDebugLog(`Failed to parse steps JSON: ${e.message}`); } if (!steps || steps.length === 0) { steps = [{ id: 'step_1', name: 'Default Claude Agent Task', type: 'pty_agent', config: { prompt: task.prompt || 'hello', max_turns: task.max_turns || 30 }, on_failure: 'abort' }]; } // Loop Engineering 설정 파싱 const loopConfig = require('./config/loop-configuration').normalize(task.loop_config); if (loopConfig?.worktree_isolation && !restored) { const isolated = await require('./services/batch-workspace').isolate(workDir, runId, activeRun.lifecycleController.signal); activeRun.sourceLease = activeRun.lease; activeRun.lease = isolated.lease; activeRun.workspace = isolated.workspace; workDir = isolated.workspace.path; try { activeRun.workspaceOrigin = require('./services/batch-workspace-proof').create(task, runId, isolated.workspace); } catch (error) { activeRun.preserveExecutionLease = true; throw error; } logStream.write('[Loop Worktree] Results will be preserved at: ' + workDir + '\n'); } activeRun.workDir = workDir; activeRun.logStream = logStream; activeRun.tokensUsed = 0; activeRun.cumulativeCost = 0.0; activeRun.runBudgetUsd = loopConfig?.token_budget ?? null; activeRun.requestReserveUsd = loopConfig?.request_reserve_usd ?? null; db.runInTransaction(() => { if (restored) require('./utils/batch-definition').assertRequestReservation(restored.checkpoint.definition, db.getRuntimeUsage(runId)); require('./services/runtime-usage-ledger').bind(activeRun, { restore: !!restored }); }); // 각 단계의 시작/완료는 모델 비용 원장과 분리해 영속 저장한다. // 설명 문서: docs/specs/batch-step-continuation.md (v0.11.0, R67 진행 중) try { stepCheckpoint = require('./services/batch-step-checkpoint').create(activeRun, task, { isDryRun, scheduled: options.scheduled, scheduledOrigin: options.scheduledOrigin, workspaceOrigin: activeRun.workspaceOrigin, restore: !!restored }); } catch (error) { activeRun.preserveExecutionLease = true; throw error; } // 설명 문서: /docs/specs/bada-bong-agent-sources.md (v0.1.0) — 단계 원장 확보 뒤부터 관측한다. // 원장·체크포인트 확보 뒤 관측을 연다. 앞선 소유자 연결만으로 실행/담당 활성화를 만들지 않는다. require('./services/bong-rig-execution-capability').bind(options.rigExecution,activeRun,task); telemetry = require('./services/agent-telemetry-batch').create(activeRun, task, steps, { iteration: restored?.iteration ?? (loopConfig ? 1 : 0), restored }); // 승인된 원래 연결의 callback만 실제 실행권·원장 확보 뒤 등록한다. 예약/DB 입력은 상속하지 않는다. // 설명 문서: docs/specs/bong-browser-handoff.md (v0.5.0) if (typeof options.onOwnedRun === 'function') releaseOwnedRun = options.onOwnedRun(activeRun); // ── [Phase C - C3] Loop Doctor 엔진사이드 비차단 검증 ── if (loopConfig) { try { const loopDoctor = require('./loop-doctor'); const harnesses = db.getHarnesses ? (db.getHarnesses(task.project_id) || []) : []; const doctorPayload = { goal_expression: loopConfig.goals || [], max_iterations: loopConfig.max_iterations, consecutive_failure_threshold: loopConfig.consecutive_failure_threshold, token_budget: loopConfig.token_budget, max_wall_time: loopConfig.max_wall_time }; const doctorReport = loopDoctor.runLoopDoctor(doctorPayload, harnesses, { mode: 'engine' }); if (doctorReport && (doctorReport.warnings.length > 0 || doctorReport.blockers.length > 0)) { const allMsgs = [...doctorReport.blockers, ...doctorReport.warnings]; logStream.write(`[Loop Doctor Warning] ${allMsgs.join(' / ')}\n`); } } catch (doctorErr) { logStream.write(`[Loop Doctor Warning] 검증 수행 중 예외 발생: ${doctorErr.message}\n`); } } const restoredLoopEvent = restored?.loopState ? require('./services/batch-loop-first').source(restored.checkpoint,restored.loopState) : null; const loopCtrl = loopConfig ? new LoopController(activeRun, loopConfig, { checkpointSnapshot: restoredLoopEvent?.controller, deferPublications: true }) : null; let loopIteration = restored?.iteration || 0; let loopRunId = null; let previousIterationsHistory = []; activeRun.previousHistory = previousIterationsHistory; activeRun.metaAnalysisNote = null; if (loopCtrl) { if (restored?.loopState) { const saved = require('./services/batch-loop-resume').restore(db, activeRun, restored); loopLedger = saved.ledger; previousIterationsHistory = structuredClone(saved.event.history); activeRun.previousHistory = previousIterationsHistory; activeRun.metaAnalysisNote = saved.event.meta; } else { let goalId = loopConfig.goal_id; if (!goalId) { goalId = `goal-${task.id}`; try { db.saveLoopGoal(task.project_id, { id: goalId, task_id: task.id, name: `${task.name} Goal`, goal_expression: JSON.stringify(loopConfig.goals || []), max_iterations: loopConfig.max_iterations ?? 10, token_budget: loopConfig.token_budget ?? 5.0, max_wall_time: loopConfig.max_wall_time ?? 3600, consecutive_failure_threshold: loopConfig.consecutive_failure_threshold ?? 3, worktree_isolation: loopConfig.worktree_isolation ?? 0 }); } catch (goalErr) { logStream.write(`[Loop Warning] Failed to auto-save loop goal: ${goalErr.message}\n`); } } // 원래 controller epoch/빈 원장 기준은 첫 회차보다 먼저 함께 저장한다. // 설명 문서: docs/specs/batch-loop-first.md v1.0.0 loopLedger = stepCheckpoint.atomic(() => db.runInTransaction(() => { const initialLedger = new (require('./services/batch-loop-ledger').BatchLoopLedger)({ db, run: activeRun, goalId }); const b=loopCtrl.circuitBreaker; stepCheckpoint.origin({currentIteration:b.currentIteration,cumulativeCost:b.cumulativeCost,cumulativeTokens:b.cumulativeTokens,consecutiveFailures:b.consecutiveFailures,startTime:b.startTime,metricHistory:Object.fromEntries(b.metricHistory),hasWarnedBudget:loopCtrl.hasWarnedBudget,iterationResults:loopCtrl.iterationResults},db.getLoopRun(initialLedger.record.run_id)); return initialLedger; })); } loopRunId = loopLedger.record.run_id; } const loopCheckpoint = loopCtrl ? require('./services/batch-loop-checkpoint').create(stepCheckpoint, activeRun, loopCtrl, loopLedger) : null; if (loopCtrl) { loopOutbox = require('./services/batch-loop-outbox').create({ db, run: activeRun, checkpoint: stepCheckpoint, controller: loopCtrl, emit: sendIpcToWindows }); loopOutbox.initial(); } do { if (loopCtrl) { if (!restored || require('./services/batch-loop-first').isFirst(restored.loopState)) { if (!restored) loopIteration++; logStream.write(`\n=== [Loop Iteration ${loopIteration}] ===\n`); stepCheckpoint.atomic(() => loopLedger.beginIteration(loopIteration, () => loopCheckpoint('steps', loopIteration, { history: previousIterationsHistory, meta: activeRun.metaAnalysisNote }))); sendIpcToWindows('loop:iteration', { runId, iteration: loopIteration, loopRunId }); } } telemetry?.cycle(loopIteration, restored); stepOutputs = restored ? structuredClone(restored.outputs) : {}; // 승인된 과거 continue도 실패 회차다. 출력만 복원하고 서킷의 연속 실패를 지우지 않는다. let iterationFailed = !!restored && require('./services/batch-step-output').continuedKeys(restored.checkpoint).some(key => restored.checkpoint.entries[key]?.iteration === loopIteration); for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) { const step = steps[stepIndex]; // 검토된 완료 prefix는 시작 IPC/효과 전에 건너뛰고 실제 저장 출력을 보간한다. if (restored && stepIndex < restored.nextIndex) continue; if (activeRun.aborted) { throw new Error('Task execution was aborted by user.'); } logStream.write(`\n--- [Step ${stepIndex + 1}/${steps.length}] ${step.name} (${step.type}) ---\n`); // IPC 알림 (단계 시작) sendIpcToWindows('batch-step-started', { taskId: task.id, runId, stepId: step.id, stepIndex }); const onFailure = step.on_failure || 'abort'; const retryCount = onFailure === 'retry' ? (step.retry_count || 3) : 0; const retryDelay = onFailure === 'retry' ? ((step.retry_delay || 5) * 1000) : 0; let stepSuccess = false; let stepError = null; let stepResult = null; const stepStartTime = Date.now(); let stepKey; for (let attempt = 0; attempt <= retryCount; attempt++) { if (attempt > 0) { logStream.write(`[Retry] Attempt ${attempt}/${retryCount} after ${retryDelay / 1000}s delay...\n`); await new Promise(r => setTimeout(r, retryDelay)); } if (activeRun.aborted) { throw new Error('Task execution was aborted by user.'); } try { stepKey = undefined; assertContinuationContext(); require('./services/bong-rig-execution-capability').assertRun(activeRun); const isCli = step.type === 'cli'; const escapeFn = isCli ? (val) => escapeShellArg(val, process.platform === 'win32') : null; const interpolatedConfig = interpolateConfig(step.config, stepOutputs, escapeFn); stepKey = stepCheckpoint.begin(stepIndex, loopIteration, attempt, interpolatedConfig, stepOutputs); telemetry?.observe('running', step.id); await require('./workflow/node-context').withNode(activeRun, step.id, 'batch-step:' + runId + ':' + stepKey, async () => { if (step.type === 'cli') { stepResult = await runCliStep(interpolatedConfig, workDir, logStream, activeRun); } else if (step.type === 'api') { stepResult = await runApiStep(interpolatedConfig, logStream, activeRun); } else if (step.type === 'browser') { if (typeof options.browserStep !== 'function') throw Object.assign(Error('BROWSER_SURFACE_UNAVAILABLE'), { code: 'BROWSER_SURFACE_UNAVAILABLE', retryable: false }); stepResult = await options.browserStep(activeRun, interpolatedConfig, step.id); } else if (step.type === 'pty_agent') { stepResult = await runPtyAgentStep(interpolatedConfig, workDir, logStream, activeRun); } else if (step.type === 'local_llm') { stepResult = await runLocalLlmStep(interpolatedConfig, workDir, logStream, activeRun); } else if (step.type === 'transform') { stepResult = await runTransformStep(interpolatedConfig, stepOutputs, logStream); } else if (step.type === 'workflow') { // 저장된 내부 워크플로우를 id로 실행(완료까지 이벤트 대기). projectId는 작업 소속 프로젝트. activeRun.workflowInvocationContext = { stepId: step.id, stepIndex, iteration: loopIteration, definitionHash: require('./utils/batch-definition').fingerprint(task) }; try { stepResult = await runWorkflowStep(interpolatedConfig, task.project_id, logStream, activeRun); } finally { delete activeRun.workflowInvocationContext; } } else if (step.type === 'n8n') { stepResult = await runN8nStep(interpolatedConfig, logStream, activeRun); } else if (step.type === 'agent_call') { stepResult = await runAgentCallStep(interpolatedConfig, workDir, logStream, activeRun); } else if (step.type === 'conductor') { stepResult = await runConductorStep(interpolatedConfig, workDir, logStream, activeRun); } else { throw new Error(`Unknown step type: ${step.type}`); } }); stepSuccess = true; stepError = null; break; } catch (err) { stepError = err; if (stepKey && err.code !== 'BATCH_CHECKPOINT_STORAGE_FAILED') { try { stepCheckpoint.fail(stepKey, err); } catch (storageError) { stepError = storageError; } } logStream.write(`[Attempt Failed] Error in step ${step.id}: ${err.message}\n`); // 취소된 작업은 다음 retry_delay를 기다리거나 모델을 다시 제출하지 않는다. // 설명 문서: docs/specs/conductor-requests.md v1.0.0 if (activeRun.aborted || err.cancelled || isUncertainCliFailure(stepError)) break; } } const stepDuration = ((Date.now() - stepStartTime) / 1000).toFixed(2); if (stepSuccess) { stepOutputs[step.id] = stepResult || {}; stepOutputs[step.id]._duration = stepDuration; logStream.write(`[Step Success] ${step.name} completed in ${stepDuration}s.\n`); // Loop 토큰/비용 추적 (PTY Agent 한정) if (step.type === 'pty_agent' && stepResult && stepResult.output && !stepResult.usageRecorded) { const promptText = step.config.prompt || ''; const outputText = stepResult.output || ''; const inputTokens = Math.ceil(promptText.length / 3); const outputTokens = Math.ceil(outputText.length / 3); const stepCost = (inputTokens * 3.0 / 1000000) + (outputTokens * 15.0 / 1000000); require('./utils/run-usage').addUsage(activeRun, stepCost, 1, { totalTokens: inputTokens + outputTokens, tokenSource: 'estimated', costSource: 'estimated' }); logStream.write(`[Engine] Iteration Step Cost: $${stepCost.toFixed(6)} (Cumulative: $${activeRun.cumulativeCost.toFixed(6)})\n`); } // 성공 이벤트 이전에 결과와 해당 시점의 비용/호출 hash를 확정한다. require('./services/runtime-request-reservation').assertReady(activeRun); stepCheckpoint.complete(stepKey, stepOutputs[step.id]); telemetry?.observe('completed', step.id); sendIpcToWindows('batch-step-completed', { taskId: task.id, runId, stepId: step.id, status: 'success' }); } else { logStream.write(`[Step Failed] ${step.name} failed after ${stepDuration}s: ${stepError.message}\n`); telemetry?.observe(activeRun.aborted ? 'cancelled' : 'failed', step.id); sendIpcToWindows('batch-step-completed', { taskId: task.id, runId, stepId: step.id, status: 'failed', error: stepError.message }); iterationFailed = true; stepOutputs[step.id] = { error: stepError.message, _duration: stepDuration }; if (onFailure === 'continue' && !isUncertainCliFailure(stepError)) { // 후속 효과 전에 실제 전달할 오류·소요 시간을 확정한다. 저장 실패는 continue하지 않는다. stepCheckpoint.continue(stepKey, stepOutputs[step.id]); logStream.write(`[Policy: Continue] Ignoring error and proceeding to next step.\n`); } else { taskFailed = true; failedReason = stepError.message; break; } } } // 치명적인 단계 실패는 기존 파일 등으로 목표가 참이어도 성공으로 바꾸지 않는다. if (taskFailed) break; activeRun.lifecycleController.signal.throwIfAborted(); // Loop Goal 평가 및 Circuit Breaker 체크 if (loopCtrl) { // 회차 목표 성공/완료 이벤트가 finally의 브라우저 정리보다 먼저 게시되지 않게 한다. browserLifecycle.assertSafe(await browserLifecycle.settle(activeRun, { seal: false })); const { cost, tokens } = loopLedger.delta(); assertContinuationContext(); const savedPhase = restored?.loopState && !require('./services/batch-loop-first').isFirst(restored.loopState) ? restored.checkpoint.loopEvents[restored.loopState.eventKey] : null; let termResult; if (savedPhase && savedPhase.phase !== 'steps') { termResult = structuredClone(savedPhase.result); } else { loopCheckpoint('evaluation_intent', loopIteration, { history: previousIterationsHistory, meta: activeRun.metaAnalysisNote }); activeRun.loopObserver = require('./services/batch-loop-observations').create(activeRun); try { termResult = await require('./workflow/node-context').withNode(activeRun, 'loop-goal', 'batch-loop:' + runId + ':' + loopIteration + ':goal', () => loopCtrl.evaluateTermination(stepOutputs, { cost, tokens, success: !iterationFailed })); } finally { delete activeRun.loopObserver; } require('./services/runtime-request-reservation').assertReady(activeRun, { settled: termResult.shouldTerminate }); loopCheckpoint('evaluated', loopIteration, { history: previousIterationsHistory, meta: activeRun.metaAnalysisNote, result: termResult }); } const evaluated = savedPhase && Object.values(restored.checkpoint.loopEvents).find(e => e.iteration === loopIteration && e.phase === 'evaluated'); const beforeAnalysis = evaluated ? { cost: evaluated.controller.cumulativeCost, tokens: evaluated.controller.cumulativeTokens } : { cost: activeRun.cumulativeCost, tokens: activeRun.tokensUsed }; if (!termResult.shouldTerminate && !['analyzed', 'settled', 'committed'].includes(savedPhase?.phase)) { loopCheckpoint('analysis_intent', loopIteration, { history: previousIterationsHistory, meta: activeRun.metaAnalysisNote, result: termResult }); const analysisObserver = require('./services/batch-loop-observations').create(activeRun); // [Phase B - B1 & B3] 직전 이터레이션 결과 수집 및 자가 분석 수행 const worktreeHelper = require('./utils/worktree-helper'); const isGit = worktreeHelper.checkGitRepo(workDir); let iterationDiff = ''; try { iterationDiff = await worktreeHelper.getIterationDiff(workDir, isGit); } catch (diffErr) { logStream.write(`[Loop Warning] Failed to get iteration git diff: ${diffErr.message}\n`); } // 실패 에러 메시지 추출 let iterError = failedReason; if (!iterError) { for (const stepId in stepOutputs) { if (stepOutputs[stepId] && stepOutputs[stepId].error) { iterError = stepOutputs[stepId].error; break; } } } previousIterationsHistory.push({ iteration: loopIteration, goalMet: termResult.goalMet, errorMessage: iterError || (termResult.goalMet ? null : 'Goal 조건 미달성'), diff: iterationDiff }); await analysisObserver.observe('analysis:context', { iteration: loopIteration }, () => ({ history: previousIterationsHistory, meta: activeRun.metaAnalysisNote ?? null })); // B3: 연속 2회 이상 실패 시 LLM 메타 분석 자가진단 수행 const consecutiveFailures = loopCtrl.circuitBreaker.consecutiveFailures; if (consecutiveFailures >= 2) { logStream.write(`[Meta-Analysis] 연속 ${consecutiveFailures}회 실패 감지 -> 자가 분석을 시작합니다...\n`); try { const messages = require('./services/batch-loop-analysis-input').messages({ goals: loopConfig.goals, iteration: loopIteration, consecutiveFailures, errorMessage: iterError, diff: iterationDiff }); let groupId = null; const groups = providersConfig.getGroups(); if (groups && groups.length > 0) { groupId = groups[0].id; } await analysisObserver.observe('analysis:policy', { iteration: loopIteration }, () => ({ consecutiveFailures, groupId })); if (groupId) { assertContinuationContext(); const response = await require('./workflow/node-context').withNode(activeRun, 'loop-meta', 'batch-loop:' + runId + ':' + loopIteration + ':meta', () => require('./services/owned-model-group').call(llmProviderService, groupId, messages, { temperature: 0.3 }, { activeRun, logStream, loopObserver: analysisObserver })); if (response.cancelled) throw Object.assign(new Error(response.error || 'Meta analysis cancelled'), { code: 'LLM_CANCELLED', cancelled: true }); if (response && response.success && response.text) { activeRun.metaAnalysisNote = response.text.trim(); logStream.write(`[Meta-Analysis] 자가 분석 완료 및 가이드 연동 완료 (모델: ${response.model || 'local'})\n`); } else { logStream.write(`[Meta-Analysis Warning] LLM 분석 응답이 유효하지 않습니다.\n`); } } else { logStream.write(`[Meta-Analysis Warning] 활성화된 LLM 그룹이 없어 메타 분석을 건너뜁니다.\n`); } } catch (metaErr) { // 취소·미상 비용·예산/원장 실패는 보조 분석 경고로 삼켜 다음 반복을 허용하지 않는다. if (activeRun.aborted || metaErr.cancelled || metaErr.code === 'USAGE_OWNER_REQUIRED' || require('./services/batch-loop-observations').isStorageError(metaErr) || isUncertainCliFailure(metaErr)) throw metaErr; logStream.write(`[Meta-Analysis Warning] 자가 분석 중 오류 발생 (무시하고 계속): ${metaErr.message}\n`); } } else { await analysisObserver.observe('analysis:policy', { iteration: loopIteration }, () => ({ consecutiveFailures, groupId: null })); activeRun.metaAnalysisNote = null; } await analysisObserver.observe('analysis:result', { iteration: loopIteration }, () => ({ historyHash: require('./services/bong-browser-resolution').hash(previousIterationsHistory), meta: activeRun.metaAnalysisNote ?? null })); loopCheckpoint('analyzed', loopIteration, { history: previousIterationsHistory, meta: activeRun.metaAnalysisNote, result: termResult }); } // 목표 평가 뒤 발생한 메타 분석도 현재 회차에 정산한 다음 종료/다음 회차를 결정한다. // 설명 문서: docs/specs/owned-model-groups.md v1.0.0 if (!termResult.shouldTerminate && !['settled', 'committed'].includes(savedPhase?.phase)) { const supplementalUsage = { cost: activeRun.cumulativeCost - beforeAnalysis.cost, tokens: activeRun.tokensUsed - beforeAnalysis.tokens }; // 실제 정산 시각도 결과와 독립 보존한다. 유실된 정산을 재실행해 추측하지 않는다. loopCheckpoint('settlement_intent', loopIteration, { history: previousIterationsHistory, meta: activeRun.metaAnalysisNote, result: termResult }); const settlementObserver = require('./services/batch-loop-observations').create(activeRun); const decisionTime = await settlementObserver.observe('controller:settlement_clock', { iteration: loopIteration, usage: supplementalUsage }, () => Date.now()); termResult = loopCtrl.accountSupplementalUsage(supplementalUsage, decisionTime) || termResult; } require('./services/runtime-request-reservation').assertReady(activeRun, { settled: termResult.shouldTerminate }); const terminal = termResult.shouldTerminate ? { status: termResult.reason === 'goal_achieved' ? 'completed' : 'circuit_broken', goal_met: termResult.goalMet ? 1 : 0, break_reason: termResult.breakReason || null, receipt_summary: termResult.receiptSummary || null } : null; if (!['settled', 'committed'].includes(savedPhase?.phase)) loopCheckpoint('settled', loopIteration, { history: previousIterationsHistory, meta: activeRun.metaAnalysisNote, result: termResult }); if (savedPhase?.phase !== 'committed') stepCheckpoint.atomic(() => loopLedger.completeIteration({ status: termResult.goalMet && !iterationFailed ? 'success' : 'failed', outputs: stepOutputs, goalMet: termResult.goalMet, error: Object.values(stepOutputs).find(output => output?.error)?.error || null, terminal }, () => { loopCheckpoint('committed', loopIteration, { history: previousIterationsHistory, meta: activeRun.metaAnalysisNote, result: termResult }); loopOutbox.enqueue('committed'); })); loopOutbox.flush(); if (termResult.shouldTerminate) { // [NEW] 루프 완료 시점에 비동기로 CLAUDE.md 및 룰 갱신 (자율 RAG 피드 갱신) try { const skillsManager = require('./skills-manager'); await skillsManager.generateClaudeRules({ workDir }); } catch (rulesErr) { logStream.write(`[Loop Warning] Failed to load skills-manager for rules update: ${rulesErr.message}\n`); } if (termResult.reason === 'circuit_broken') { taskFailed = true; failedReason = `Circuit Breaker Tripped: ${termResult.breakReason}`; } break; } } restored = null; } while (loopCtrl && !taskFailed && !activeRun.aborted); } catch (outerErr) { taskFailed = true; failedReason = outerErr.message; if (logStream) { logStream.write(`\n[Fatal Workflow Error] ${outerErr.message}\n`); } } finally { try { await releaseOwnedRun?.(); } catch { taskFailed = true; failedReason = 'BROWSER_ORIGIN_CLEANUP_FAILED'; activeRun.preserveExecutionLease = true; } // 완료/루프 종료/예약 인증보다 실제 브라우저 종료와 영속 기록을 먼저 확정한다. // docs/specs/bong-browser-use.md v1.4.0 const browserReport = await browserLifecycle.settle(activeRun); if (browserLifecycle.unsafe(browserReport)) { taskFailed = true; failedReason = 'BROWSER_RECONCILIATION_REQUIRED'; } try { require('./services/runtime-request-reservation').assertReady(activeRun, { settled: true }); } catch (error) { taskFailed = true; failedReason = failedReason || error.message; } // 취소/단계 실패/평가 오류의 미완료 루프도 반환 전에 최종 상태로 기록한다. // docs/specs/batch-loop-records.md v1.0.0 if (!loopOutbox) require('./services/loop-hud').finishRun(activeRun, activeRun.aborted ? 'aborted' : taskFailed ? 'failed' : 'completed'); try { if (loopLedger) stepCheckpoint.atomic(() => loopLedger.finish({ aborted: activeRun.aborted, error: failedReason, outputs: stepOutputs }, () => loopOutbox.enqueue('stopped'))); loopOutbox?.flush(); } catch (recordError) { taskFailed = true; failedReason = (failedReason ? failedReason + '; ' : '') + 'Loop record finalization failed: ' + recordError.message; writeDebugLog(failedReason); } // [NEW] CLI 단계 등의 실행 중인 자식 프로세스가 잔존하는 경우 강제 종료 처리 (좀비 프로세스 누출 방지) if (activeRun.currentProcess) { try { const pid = activeRun.currentProcess.pid; if (pid) { killProcessTree(pid, true); } else if (typeof activeRun.currentProcess.kill === 'function') { activeRun.currentProcess.kill('SIGKILL'); } } catch (e) { writeDebugLog(`Failed to cleanup active run process in finally: ${e.message}`); } activeRun.currentProcess = null; } await require('./utils/interactive-cli-session').closeSession(activeRun); // 이전 계약의 PTY 참조가 있으면 동일하게 정리한다. if (activeRun.workflowPty) { try { const pid = activeRun.workflowPty.pid; if (pid) { killProcessTree(pid, true); // 하위 좀비 일괄 소거 } else { activeRun.workflowPty.kill('SIGKILL'); } } catch (e) { /* intentional: 프로세스 종료 실패 무시 (이미 종료 가능) */ } activeRun.workflowPty = null; // 레퍼런스 정리 activeRun.workflowPtyReadyPromise = null; } // 실행권 획득/최초 기록 이전 실패는 가짜 완료 이력·아카이브를 만들지 않는다. if (!activeRun.recordStarted) { runningTasks.delete(task.id); activeTaskRuns.delete(task.id); if (!activeRun.sandboxTerminationUnconfirmed && !browserReport.terminationUnconfirmed && !browserReport.journalUnconfirmed) { if (lockAcquired) activeRun.lease?.release(); activeRun.sourceLease?.release(); if (!activeRun.preserveExecutionLease) activeRun.executionLease?.(); else batchRunLease.retire(task.id, activeRun.executionLease); } options.signal?.removeEventListener('abort', cancelRequested); return resolve({ success: false, error: failedReason, stepOutputs, usage: activeRun.usage || null, terminationUnconfirmed:activeRun.sandboxTerminationUnconfirmed === true || browserReport.terminationUnconfirmed, browser: browserReport }); } let finalStatus = activeRun.aborted ? 'aborted' : taskFailed ? 'failed' : 'success'; if (activeRun.aborted) { taskFailed = true; failedReason ||= 'Batch task cancelled'; } try { db.completeBatchRun(runId, finalStatus, failedReason); // 마일스톤 3: 지식 DB에 최종 배치 런 상태 반영 및 태스크와 엣지 연동 try { db.runInTransaction(() => { db.saveNode(task.project_id, { id: `batch_run:${runId}`, type: 'batch_run', label: `Batch Run: ${runId.substring(4)} (${finalStatus === 'success' ? '✅' : '🚨'})`, properties: { category: 'batch', status: finalStatus, taskId: task.id, error: failedReason || '', usage: activeRun.usage || null } }); db.saveEdge(task.project_id, { id: `edge:${task.id}:${runId}`, source: `batch_task:${task.id}`, target: `batch_run:${runId}`, type: 'has_run', label: 'has run' }); }); } catch (nodeErr) { writeDebugLog(`Failed to update batch_run node on complete: ${nodeErr.message}`); } // 마일스톤 3: 서킷 브레이커 (연속 3회 실패 시 스케줄 비활성화) if (finalStatus === 'failed' && !isDryRun) { try { const runs = db.getBatchRuns(task.id) || []; const latestRuns = runs.slice(0, 3); const consecutiveFailures = latestRuns.filter(r => r.status === 'failed').length; if (consecutiveFailures >= 3) { writeDebugLog(`[Circuit Breaker] Task ${task.id} has failed ${consecutiveFailures} consecutive times. Deactivating...`); const latestTasks = db.getBatchTasks(task.project_id); const taskObj = latestTasks.find(t => t.id === task.id); if (taskObj) { taskObj.is_active = 0; db.runInTransaction(() => db.saveBatchTask(task.project_id, taskObj)); unscheduleTask(task.id); // 디스크 로그 파일에도 경고 기록 try { fs.appendFileSync(logPath, `\n🚨 [Circuit Breaker] 3회 연속 실행 실패로 인하여 예약 스케줄링이 강제 비활성화(Deactivated) 되었습니다. 코드를 점검하신 후 다시 켜주십시오.\n`, 'utf-8'); } catch (logErr) { /* intentional: 디버그 로그 기록 자체의 실패는 무시 */ } // IPC 알림으로 UI 스위치 끄기 동기화 sendIpcToWindows('batch-task-status-updated', { taskId: task.id, is_active: 0 }); } } } catch (cbErr) { writeDebugLog(`Error in batch circuit breaker: ${cbErr.message}`); } } } catch (dbErr) { writeDebugLog(`Failed to complete batch run in DB: ${dbErr.message}`); taskFailed = true; finalStatus = 'failed'; failedReason = 'Batch completion storage failed: ' + dbErr.message; activeRun.preserveExecutionLease = true; } if (logStream) { try { logStream.write(`\n\n=== BADA Batch Run Ended: ${new Date().toISOString()} ===\n`); logStream.write(`Final Status: ${finalStatus}\n`); if (failedReason) logStream.write(`Failure Reason: ${failedReason}\n`); fileLogCleaner?.flush(); logStream.end(); } catch (error) { writeDebugLog('Batch log finalization failed: ' + error.message); } } writeDebugLog(`Batch task finished. Status: ${finalStatus}. Log: ${logPath}`); // Dry-Run 테스트가 완전히 성공한 경우만 데이터베이스에 테스트 성공 체크 반영 if (isDryRun && !taskFailed) { try { db.runInTransaction(() => { options.admission.assertTestedDefinition(); db.updateBatchTaskTestStatus(task.id, 1, batchDefinition.fingerprint(task)); }); writeDebugLog(`Task ${task.id} verified successfully via Dry Run.`); activeRun.testVerified = true; } catch (dbErr) { activeRun.certificationError = dbErr.message; writeDebugLog(`Failed to update batch task test status: ${dbErr.message}`); } } try { sendIpcToWindows('batch-run-completed', { taskId: task.id, runId, status: finalStatus, error: failedReason, isDryRun, testVerified: activeRun.testVerified, certificationError: activeRun.certificationError, workspace: activeRun.workspace }); } catch (ipcErr) { writeDebugLog(`Failed to send run completed IPC: ${ipcErr.message}`); } // 마일스톤 v1.5.0: 옵시디언 런 아카이빙 호출 (비동기 처리) try { const WikiRunArchiver = require('./wiki-run-archiver'); const archiveResult = await WikiRunArchiver.archiveBatchRun(runId, task, finalStatus, failedReason, steps, stepOutputs, workDir); if (archiveResult?.success === false) writeDebugLog('[WikiRunArchiver] Archive incomplete: ' + archiveResult.error); // 마일스톤 v1.6.0: 생성된 온톨로지 파일(insight_ontology.jsonld) 자동 지식 Ingestion 연동 if (finalStatus === 'success') { const ontologyPath = path.join(workDir, 'insight_ontology.jsonld'); if (fs.existsSync(ontologyPath)) { writeDebugLog(`[WikiRunArchiver] Found new ontology file at ${ontologyPath}. Importing...`); const { absWikiPath } = WikiRunArchiver.getVaultDirs(workDir); const imported = await WikiRunArchiver.importOntologyJsonLd(ontologyPath, absWikiPath); if (!imported?.success) throw new Error('Ontology import failed: ' + (imported?.error || 'missing result')); } } // Knot v1.7.0: 지식 이식 완료 후 LLMWiki Linter (scripts/lint.py) 자동 기동 및 검증 const { absWikiPath } = WikiRunArchiver.getVaultDirs(workDir); if (fs.existsSync(absWikiPath)) { writeDebugLog(`[WikiRunArchiver] Executing LLMWiki Linter on: ${absWikiPath}`); const { execFileSync } = require('child_process'); try { const lintScript = path.join(process.cwd(), 'scripts', 'lint.py'); if (fs.existsSync(lintScript)) { const processHelper = require('./utils/process-helper'); const { pythonPath, env } = processHelper.getPythonEnvConfig(absWikiPath); const lintOutput = execFileSync(pythonPath, [lintScript, absWikiPath], { encoding: 'utf-8', env: env }); writeDebugLog(`[WikiRunArchiver] Linter Output:\n${lintOutput}`); } } catch (lintErr) { writeDebugLog(`[WikiRunArchiver] Linter Error (Lint failed):\n${lintErr.stdout || lintErr.message}`); } } } catch (archiveErr) { writeDebugLog(`[WikiRunArchiver] Failed to archive/import batch run data: ${archiveErr.message}`); } // 결과 저장과 아카이브까지 소유권을 유지한다. 저장 실패의 소유 증거는 종료 후에도 남긴다. if (!activeRun.sandboxTerminationUnconfirmed && !browserReport.terminationUnconfirmed && !browserReport.journalUnconfirmed) { if (workDir && lockAcquired) activeRun.lease?.release(); activeRun.sourceLease?.release(); } if (!activeRun.preserveExecutionLease) activeRun.executionLease?.(); else if (!activeRun.sandboxTerminationUnconfirmed && !browserReport.terminationUnconfirmed && !browserReport.journalUnconfirmed) batchRunLease.retire(task.id, activeRun.executionLease); options.signal?.removeEventListener('abort', cancelRequested); runningTasks.delete(task.id); activeTaskRuns.delete(task.id); require('./services/bong-rig-execution-capability').complete(activeRun); const rigUnconfirmed=options.rigExecution&&(activeRun.preserveExecutionLease||activeRun.sandboxTerminationUnconfirmed||browserReport.terminationUnconfirmed||browserReport.journalUnconfirmed); telemetry?.finish(rigUnconfirmed?'unknown':finalStatus === 'success' ? 'complete' : finalStatus === 'aborted' ? 'cancelled' : 'failed'); } resolve({ success: !taskFailed, runId, error: failedReason, stepOutputs, usage: activeRun.usage || null, loopPublications: loopOutbox?.summary(), testVerified: isDryRun ? activeRun.testVerified : undefined, certificationError: activeRun.certificationError, workspace: activeRun.workspace, terminationUnconfirmed:activeRun.sandboxTerminationUnconfirmed === true || activeRun.browserDrainReport?.terminationUnconfirmed === true, browser: activeRun.browserDrainReport }); })().catch((err) => { telemetry?.finish(options.rigExecution?'unknown':'failed'); writeDebugLog(`Fatal unhandled runTask error: ${err.message}`); resolve({ success: false, error: err.message }); }); }); } function isTaskRunning(taskId) { return runningTasks.has(taskId); } function readLastLinesSync(filePath, maxBytesToRead = 50 * 1024) { let fd; try { if (!fs.existsSync(filePath)) return ''; const stat = fs.statSync(filePath); if (stat.size === 0) return ''; fd = fs.openSync(filePath, 'r'); const bytesToRead = Math.min(stat.size, maxBytesToRead); const position = stat.size - bytesToRead; const buffer = Buffer.alloc(bytesToRead); fs.readSync(fd, buffer, 0, bytesToRead, position); return buffer.toString('utf8'); } catch (error) { writeDebugLog(`[Batch] readLastLinesSync failed (${filePath}): ${error.message}`); return ''; } finally { if (fd !== undefined) { try { fs.closeSync(fd); } catch (e) { /* intentional: 디버그 로그 기록 자체의 실패는 무시 */ } } } } function getActiveRuns() { const result = []; for (const [taskId, activeRun] of activeTaskRuns.entries()) { let logContent = ''; // 기록 측(runTaskInternal)과 동일한 규약으로 활성 CLI 홈 하위 batch-logs/ 를 조회한다. const logsDir = require('./config/cli-paths').getCliHomeFilePath('batch-logs'); const safeTaskId = String(taskId).replace(/[^a-zA-Z0-9_-]/g, '_'); const logPath = path.join(logsDir, `${safeTaskId}-${activeRun.runId}.log`); if (fs.existsSync(logPath)) { try { logContent = readLastLinesSync(logPath, 50 * 1024); } catch (e) { /* intentional: 파일 읽기 실패 시 무시 */ } } result.push({ taskId, runId: activeRun.runId, logContent, aborted: activeRun.aborted }); } return result; } function getScheduledJobsCount() { return scheduledJobs.size; } function getScheduledJobsList() { return Array.from(scheduledJobs.keys()); } // NATS Message Bus Bridge try { const natsManager = require('./services/bada-nats-manager'); const os = require('os'); const nodeId = os.hostname() || 'bada-node'; batchEvents.on('loop:iteration', (data) => { natsManager.publish(`bada.node.${nodeId}.batch.event.${data.taskId || 'loop'}`, data); }); } catch (e) { console.warn('[Batch Manager] Failed to bind NATS event bridge:', e.message); } module.exports = { resolveWorkspacePath, fireScheduledTask, getScheduleState: task => getScheduleLedger().inspect(task), getScheduleRecovery: task => getScheduleLedger().recovery(task), getScheduleRegistration: task => scheduleRegistrationErrors.has(task.id) ? { state: 'error', error: scheduleRegistrationErrors.get(task.id) } : { state: scheduledJobs.has(task.id) ? 'scheduled' : 'unregistered' }, resolveScheduleClaim, initialize, scheduleTask, saveScheduledTask, deleteScheduledTask, importBatchTasks, unscheduleTask, abortTask, runTask, resumeBatchRun, cleanupAllActiveRuns, isTaskRunning, getActiveRuns, getScheduledJobsCount, getScheduledJobsList, killProcessTree, batchEvents, // 명시 승인 알림 전달만 제공한다. 새 배치/루프/자식을 시작하지 않는다. // 설명 문서: docs/specs/batch-publication-review.md v1.0.0 publishReviewedLoopNotification: packet => sendIpcToWindows('loop:complete', packet) };