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