Download src/batch-manager.js from VanyaJ/bada-terminal: direct link, hf CLI and curl.
- Browser
- Download file 79.6 kB
-
https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/batch-manager.js
- Command line
-
hf download hf://VanyaJ/bada-terminal/src/batch-manager.js
-
curl -L -o batch-manager.js https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/batch-manager.js
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 {