module.exports = { register(ipcMain, ctx) { const windowManager = require('../window-manager'); // --- Loop Engineering IPC Handlers --- ipcMain.handle('get-loop-goals', async (event, projectId) => { try { const db = require('../../knowledge-db'); return { success: true, goals: db.getLoopGoals(projectId) }; } catch (e) { return { success: false, error: e.message }; } }); ipcMain.handle('save-loop-goal', async (event, projectId, goal) => { try { const db = require('../../knowledge-db'); db.saveLoopGoal(projectId, goal); return { success: true }; } catch (e) { return { success: false, error: e.message }; } }); // 배터리 정식 자산(HTTP 노드 워크플로우 + 루프 골) 시드 핸들러. // TR-015의 loop-builder.js 강제 주입을 대체하는 클린 경로 — Electron(SQLite) 컨텍스트에서 1회 호출하면 등록된다. ipcMain.handle('seed-battery-assets', async (event, projectId) => { try { const db = require('../../knowledge-db'); const workflow = require('../config/battery-redesign-workflow.json'); const goal = require('../config/battery-redesign-goal.json'); const pid = projectId || 'global'; db.saveWorkflow(pid, workflow); db.saveLoopGoal(pid, goal); return { success: true, projectId: pid, workflowId: workflow.id, goalId: goal.id }; } catch (e) { return { success: false, error: e.message }; } }); ipcMain.handle('delete-loop-goal', async (event, goalId) => { try { const db = require('../../knowledge-db'); db.deleteLoopGoal(goalId); return { success: true }; } catch (e) { return { success: false, error: e.message }; } }); // ─── Loop Templates: 프로젝트 비종속 재사용 카탈로그 ─── // WHY: 이 프로젝트에서 검증된 루프 설정을 project_id/task_id 없이 복제 저장해 // 다른 프로젝트에서도 재사용(인스턴스화)한다. 기존 loop_goals/batch_tasks 로직은 // 전혀 건드리지 않고 순수 신규 경로만 추가한다. // 프로젝트 절대경로 하드코딩 휴리스틱 — 경고만 반환(치환/살균은 하지 않음). // WHY: 프롬프트에 현재 프로젝트의 절대경로/폴더명이 그대로 박혀 있으면 다른 프로젝트에서 // 재사용 시 경로가 어긋난다. 사용자가 인지하도록 경고 문자열만 만든다. const detectHardcodedPaths = (projectId, goalExpression, stepsJson) => { const warnings = []; try { const path = require('path'); const haystack = [ typeof goalExpression === 'string' ? goalExpression : JSON.stringify(goalExpression || {}), typeof stepsJson === 'string' ? stepsJson : JSON.stringify(stepsJson || []) ].join('\n'); const pid = String(projectId || ''); const looksAbsolute = pid.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(pid); if (looksAbsolute && pid.length > 3 && haystack.includes(pid)) { warnings.push(`에이전트 프롬프트/목표식에 현재 프로젝트 절대경로("${pid}")가 그대로 포함되어 있습니다. 다른 프로젝트에서 이 템플릿을 적용하면 경로가 맞지 않을 수 있으니 적용 후 프롬프트를 확인하세요.`); } else { const base = path.basename(pid); if (base && base.length >= 3 && haystack.includes(base)) { warnings.push(`에이전트 프롬프트/목표식에 현재 프로젝트 폴더명("${base}")이 포함되어 있습니다. 다른 프로젝트에서 재사용 시 경로 확인이 필요할 수 있습니다.`); } } } catch (e) { // 휴리스틱 자체의 오류가 저장을 막아서는 안 된다(경고 생략). console.error('[loop-ipc] detectHardcodedPaths 오류(무시):', e.message); } return warnings; }; ipcMain.handle('get-loop-templates', async () => { try { const db = require('../../knowledge-db'); return { success: true, templates: db.getLoopTemplates() }; } catch (e) { return { success: false, error: e.message }; } }); // 기존 loop_goal 하나(+대응 batch_task 스텝)를 프로젝트 비종속 템플릿으로 복제 저장. ipcMain.handle('save-loop-template', async (event, projectId, goalId, options = {}) => { try { const db = require('../../knowledge-db'); const path = require('path'); const goals = db.getLoopGoals(projectId) || []; const goal = goals.find(g => g.id === goalId); if (!goal) { return { success: false, error: `루프 목표를 찾을 수 없습니다: ${goalId}` }; } // 대응하는 batch_task의 에이전트 스텝(steps_json)을 함께 복제한다. const tasks = db.getBatchTasks(projectId) || []; const task = goal.task_id ? tasks.find(t => t.id === goal.task_id) : null; const stepsJson = task ? (task.steps_json || '[]') : '[]'; const warnings = detectHardcodedPaths(projectId, goal.goal_expression, stepsJson); // WHY: 동시에 여러 번 호출되면 Date.now()만으로는 밀리초 단위 충돌(덮어쓰기) 가능성이 있어 // 코드베이스 관례(예: sqlite-db.js의 Date.now()+random 접미사 패턴)를 따라 랜덤 접미사를 더한다. const templateId = `looptmpl-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`; const template = { id: templateId, name: (options.name || goal.name || 'Untitled Loop Template'), description: options.description || null, // 프로젝트 종속 필드(project_id/task_id/workflow_id)는 의도적으로 제외한다. goal_expression: goal.goal_expression, max_iterations: goal.max_iterations, token_budget: goal.token_budget, max_wall_time: goal.max_wall_time, consecutive_failure_threshold: goal.consecutive_failure_threshold, worktree_isolation: goal.worktree_isolation, steps_json: stepsJson, source_project_name: path.basename(String(projectId || '')) || String(projectId || '') || null, source_task_name: task ? task.name : null }; db.saveLoopTemplate(template); return { success: true, templateId, warnings }; } catch (e) { return { success: false, error: e.message }; } }); // 템플릿을 현재 프로젝트에 인스턴스화 — 새 loop_goal + batch_task 행 생성. ipcMain.handle('apply-loop-template', async (event, projectId, templateId, options = {}) => { try { const db = require('../../knowledge-db'); const templates = db.getLoopTemplates() || []; const tmpl = templates.find(t => t.id === templateId); if (!tmpl) { return { success: false, error: `템플릿을 찾을 수 없습니다: ${templateId}` }; } // WHY: 짧은 시간 내 연속 적용(더블클릭 등) 시 Date.now() 단독으로는 충돌 가능 — 랜덤 접미사로 보강. const stamp = `${Date.now()}-${Math.random().toString(36).substring(2, 7)}`; const newGoalId = `goal-${stamp}`; const newTaskId = `task-loop-${stamp}`; // goal_expression에서 goals 배열을 추출해 loop_config를 재구성한다(buildTaskPayload와 동일 시맨틱). let goalExpr = {}; try { goalExpr = typeof tmpl.goal_expression === 'string' ? JSON.parse(tmpl.goal_expression) : (tmpl.goal_expression || {}); } catch (_) { goalExpr = {}; } const goals = Array.isArray(goalExpr) ? goalExpr : (goalExpr.goals || []); // 1) 새 loop_goal (대상 프로젝트에 종속) const goal = { id: newGoalId, task_id: newTaskId, workflow_id: null, name: options.name || tmpl.name, goal_expression: tmpl.goal_expression, max_iterations: tmpl.max_iterations, token_budget: tmpl.token_budget, max_wall_time: tmpl.max_wall_time, consecutive_failure_threshold: tmpl.consecutive_failure_threshold, worktree_isolation: tmpl.worktree_isolation }; db.saveLoopGoal(projectId, goal); // 2) 새 batch_task (에이전트 스텝 복제 + loop_config 재구성, 미검증 드래프트로 시작) let steps = []; try { steps = JSON.parse(tmpl.steps_json || '[]'); } catch (_) { steps = []; } const firstStepCfg = (steps[0] && steps[0].config) || {}; const loopConfig = { goal_id: newGoalId, goals, max_iterations: tmpl.max_iterations, token_budget: tmpl.token_budget, max_wall_time: tmpl.max_wall_time, consecutive_failure_threshold: tmpl.consecutive_failure_threshold, worktree_isolation: tmpl.worktree_isolation }; const task = { id: newTaskId, name: `🔄 [Loop] ${goal.name}`, prompt: firstStepCfg.prompt || '', cron_expr: 'once:0 3 * * *', max_turns: firstStepCfg.max_turns || 30, is_active: 0, steps_json: tmpl.steps_json || '[]', loop_config: JSON.stringify(loopConfig), is_tested_success: 0 }; db.saveBatchTask(projectId, task); return { success: true, goalId: newGoalId, taskId: newTaskId }; } catch (e) { return { success: false, error: e.message }; } }); ipcMain.handle('delete-loop-template', async (event, templateId) => { try { const db = require('../../knowledge-db'); db.deleteLoopTemplate(templateId); return { success: true }; } catch (e) { return { success: false, error: e.message }; } }); ipcMain.handle('get-loop-runs', async (event, goalId) => { try { const db = require('../../knowledge-db'); return { success: true, runs: db.getLoopRuns(goalId) }; } catch (e) { return { success: false, error: e.message }; } }); ipcMain.handle('get-loop-iterations', async (event, loopRunId) => { try { const db = require('../../knowledge-db'); return { success: true, iterations: db.getLoopIterations(loopRunId) }; } catch (e) { return { success: false, error: e.message }; } }); ipcMain.handle('get-loop-messages', async (event, loopRunId) => { try { const db = require('../../knowledge-db'); return { success: true, messages: db.getLoopMessages(loopRunId) }; } catch (e) { return { success: false, error: e.message }; } }); ipcMain.handle('save-loop-message', async (event, msg) => { try { const db = require('../../knowledge-db'); db.saveLoopMessage(msg); return { success: true }; } catch (e) { return { success: false, error: e.message }; } }); // --- Loop Engineering 창 열기 IPC 리스너 --- // 루프 빌더 화면 열기 수신 ipcMain.on('open-loop-builder', () => { windowManager.openLoopBuilder(); }); // 루프 실시간 모니터링 대시보드 화면 열기 수신 (실행 ID, 태스크 ID, 목표 ID 전달) ipcMain.on('open-loop-dashboard', (event, data = {}) => { windowManager.openLoopDashboard(data.runId, data.taskId, data.goalId); }); // 루프 실시간 HUD 스냅샷 조회 (Electron 데스크탑 및 Web Server IpcBridge 공통 지원) ipcMain.handle('loop:hud-snapshot', () => require('../services/loop-hud').snapshot()); // 루프 실행 이력 화면 열기 수신 ipcMain.on('open-loop-history', () => { windowManager.openLoopHistory(); }); } };