bada-terminal / src /db /sqlite-db.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
104 kB
const path = require('path'); const fs = require('fs'); const crypto = require('crypto'); function filterAndCapGraphData(nodes, edges, safeParse) { const MAX_NODES = 5000; const MAX_EDGES = 10000; let finalNodes = nodes; if (finalNodes.length > MAX_NODES) { const typePriority = { 'session': 0, 'wiki': 1, 'note': 1, 'tool': 2, 'file': 3, 'code': 4, 'library': 5 }; finalNodes.sort((a, b) => { const priA = typePriority[a.type] !== undefined ? typePriority[a.type] : 6; const priB = typePriority[b.type] !== undefined ? typePriority[b.type] : 6; return priA - priB; }); finalNodes = finalNodes.slice(0, MAX_NODES); } const nodeIds = new Set(finalNodes.map(n => n.id)); let finalEdges = edges.filter(e => nodeIds.has(e.source) && nodeIds.has(e.target)); if (finalEdges.length > MAX_EDGES) { finalEdges = finalEdges.slice(0, MAX_EDGES); } return { nodes: finalNodes.map(n => ({ ...n, properties: safeParse(n.properties) })), edges: finalEdges.map(e => ({ ...e, properties: safeParse(e.properties) })) }; } class SqliteDb { constructor(db) { this.db = db; this.attachedDbs = new Set(); this.initTables(); } getDecisionGate(id) { return require('./decision-gate-record').decode(this.db.prepare('SELECT gate_json FROM decision_gates WHERE id = ?').get(id)?.gate_json); } // docs/specs/bong-ui-artifacts.md v1.0.0. snapshot과 할당량을 같은 SQLite 트랜잭션에 고정한다. getUiArtifact(projectId,id){const r=require('./ui-artifact-record');r.query(projectId,id);return r.read(this.db.prepare('SELECT data_json FROM ui_artifacts WHERE project_id=? AND id=?').get(projectId,id)?.data_json,projectId,id);} listUiArtifacts(projectId){const r=require('./ui-artifact-record');r.query(projectId);return this.db.prepare('SELECT id,data_json FROM ui_artifacts WHERE project_id=? ORDER BY rowid DESC LIMIT 33').all(projectId).map(v=>r.read(v.data_json,projectId,v.id));} saveUiArtifact(projectId,value){return this.db.transaction(()=>{const r=require('./ui-artifact-record'),next=r.read(value,projectId,value.id),old=this.getUiArtifact(projectId,next.id);if(old){if(old.hash!==next.hash)r.fail();return old;}r.quota(this.listUiArtifacts(projectId),next);this.db.prepare('INSERT INTO ui_artifacts(project_id,id,data_json) VALUES (?,?,?)').run(projectId,next.id,JSON.stringify(next));return next;})();} deleteUiArtifact(projectId,id,hash){return this.db.transaction(()=>{const old=this.getUiArtifact(projectId,id);if(!old||old.hash!==hash)require('./ui-artifact-record').fail();this.db.prepare('DELETE FROM ui_artifacts WHERE project_id=? AND id=?').run(projectId,id);})();} listDecisionGates() { return this.db.prepare('SELECT gate_json FROM decision_gates ORDER BY rowid DESC LIMIT 100').all().map(row => require('./decision-gate-record').decode(row.gate_json)); } saveDecisionGate(gate, expectedRevision = null) { return this.db.transaction(() => { const records = require('./decision-gate-record'); const next = records.prepare(gate, this.getDecisionGate(gate.id), expectedRevision); if (expectedRevision === null) this.db.prepare('INSERT INTO decision_gates (id, revision, gate_json) VALUES (?, ?, ?)').run(next.id, next.revision, JSON.stringify(next)); else if (this.db.prepare('UPDATE decision_gates SET revision = ?, gate_json = ? WHERE id = ? AND revision = ?').run(next.revision, JSON.stringify(next), next.id, expectedRevision).changes !== 1) throw records.conflict(); return next; })(); } getRuntimeUsage(id) { return require('./runtime-usage-record').decode(this.db.prepare('SELECT data_json FROM runtime_usage WHERE run_id = ?').get(id)?.data_json); } getBatchCheckpoint(id) { return require('./batch-checkpoint-record').decode(this.db.prepare('SELECT data_json FROM batch_checkpoints WHERE run_id=?').get(id)?.data_json); } // 원래 checkpoint와 분리한 알림 journal: docs/specs/batch-publication-review.md v1.0.0 getBatchLoopPublicationActions(runId) { return require('./batch-publication-action-record').decode(this,runId,this.db.prepare('SELECT data_json FROM batch_publication_actions WHERE run_id=?').get(runId)?.data_json); } appendBatchLoopPublicationAction(runId,value,expectedHash,verify) { return this.db.transaction(()=>{const next=require('./batch-publication-action-record').append(this,runId,value,this.getBatchLoopPublicationActions(runId),expectedHash,verify);this.db.prepare('INSERT INTO batch_publication_actions(run_id,data_json) VALUES (?,?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(runId,JSON.stringify(next));return next;})(); } getBatchLoopObservations(runId,eventKey) { return require('./batch-loop-observation-record').decode(this,runId,eventKey,this.db.prepare('SELECT data_json FROM batch_loop_observations WHERE run_id=? AND event_key=?').get(runId,eventKey)?.data_json); } hasBatchLoopObservations(runId) { if(typeof runId!=='string'||!/^[-\w]{1,256}$/.test(runId))throw Error('Invalid batch run ID');return !!this.db.prepare('SELECT 1 FROM batch_loop_observations WHERE run_id=? LIMIT 1').get(runId); } appendBatchLoopObservation(runId,eventKey,value,expectedHash) { return this.db.transaction(()=>{const next=require('./batch-loop-observation-record').append(this,runId,eventKey,value,this.getBatchLoopObservations(runId,eventKey),expectedHash);this.db.prepare('INSERT INTO batch_loop_observations(run_id,event_key,data_json) VALUES (?,?,?) ON CONFLICT(run_id,event_key) DO UPDATE SET data_json=excluded.data_json').run(runId,eventKey,JSON.stringify(next));return next;})(); } saveBatchCheckpoint(record,revision=null,verify) { return this.db.transaction(()=>{const next=require('./batch-checkpoint-record').prepare(record,this.getBatchCheckpoint(record.runId),revision,verify);this.db.prepare('INSERT INTO batch_checkpoints (run_id,data_json) VALUES (?,?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(next.runId,JSON.stringify(next));return next;})(); } transitionBatchRun(id,expected,status) { return this.db.transaction(()=>{const row=this.getBatchRun(id),hash=require('../services/bong-browser-resolution').hash;if(!['paused','running','aborted'].includes(status)||hash(row)!==hash(expected)||['running','aborted'].includes(status)&&row?.status!=='paused'||status==='paused'&&!['failed','aborted'].includes(row?.status))throw Error('Batch continuation row changed');const result=this.db.prepare('UPDATE batch_runs SET status=?,error_message=?,completed_at=? WHERE run_id=?').run(status,status==='aborted'?'사용자 복구 준비 철회':null,status==='aborted'?new Date().toISOString():null,id);if(result.changes!==1)throw Error('Batch continuation row missing');return this.getBatchRun(id);})(); } getGoalProcedure(projectId,id){require('./goal-state-record').query(projectId,id);return require('./goal-procedure-record').read(this.db.prepare('SELECT data_json FROM goal_procedures WHERE project_id=? AND id=?').get(projectId,id)?.data_json,projectId,id);} listGoalProcedures(projectId,limit=20){require('./goal-state-record').query(projectId);if(!Number.isSafeInteger(limit)||limit<1||limit>21)throw Error('Invalid procedure limit');return this.db.prepare('SELECT id,data_json FROM goal_procedures WHERE project_id=? ORDER BY rowid DESC LIMIT ?').all(projectId,limit).map(r=>require('./goal-procedure-record').read(r.data_json,projectId,r.id));} saveGoalProcedure(projectId,id,value,revision,verify){return this.db.transaction(()=>{const r=require('./goal-procedure-record'),next=r.prepare(projectId,id,value,this.getGoalProcedure(projectId,id),revision,verify);if(revision===null){if(this.db.prepare('SELECT COUNT(*) AS count FROM goal_procedures WHERE project_id=?').get(projectId).count>=64)throw r.fail();this.db.prepare('INSERT INTO goal_procedures(project_id,id,data_json) VALUES (?,?,?)').run(projectId,id,JSON.stringify(next));}else this.db.prepare('UPDATE goal_procedures SET data_json=? WHERE project_id=? AND id=?').run(JSON.stringify(next),projectId,id);return next;})();} getGoalState(projectId,id) { const r=require('./goal-state-record');r.query(projectId,id);return r.decode(this.db.prepare('SELECT data_json FROM goal_states WHERE project_id=? AND id=?').get(projectId,id)?.data_json); } listGoalStates(projectId,limit=20) { const r=require('./goal-state-record');r.query(projectId);if(!Number.isSafeInteger(limit)||limit<1||limit>21)throw Error('Invalid goal limit');return this.db.prepare('SELECT data_json FROM goal_states WHERE project_id=? ORDER BY rowid DESC LIMIT ?').all(projectId,limit).map(row=>r.decode(row.data_json)); } appendGoalEvent(projectId,id,event,expectedRevision) { return this.db.transaction(()=>{const next=require('./goal-state-record').apply(this.getGoalState(projectId,id),projectId,id,event,expectedRevision); this.db.prepare('INSERT INTO goal_states (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'goal',id,next.runId,id,next.revision,next);return next; })(); } saveRuntimeUsage(record) { return this.db.transaction(()=>{const json = require('./runtime-usage-record').encode(record); this.db.prepare('INSERT INTO runtime_usage (run_id, data_json) VALUES (?, ?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(record.runId, json);require('../services/goal-event-feed').usageChanged(this,record);})(); } getGoalFulfillment(projectId,id) { require('./goal-state-record').query(projectId,id);return require('./goal-fulfillment-record').decode(this.db.prepare('SELECT data_json FROM goal_fulfillments WHERE project_id=? AND id=?').get(projectId,id)?.data_json); } saveGoalFulfillment(projectId,id,input,revision) { return this.db.transaction(()=>{const next=require('./goal-fulfillment-record').prepare(this,projectId,id,input,this.getGoalFulfillment(projectId,id),revision); this.db.prepare('INSERT INTO goal_fulfillments (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'confirmation',id,next.confirmations.at(-1).runId,id,next.revision,next);return next; })(); } getHarnessRunsForWorkflow(projectId,harnessId,runId) { this.getHarnessRunsForProject(projectId,harnessId,1);return this.db.prepare('SELECT * FROM harness_runs WHERE harness_id=? AND workflow_run_id=? ORDER BY created_at DESC,rowid DESC LIMIT 1').all(harnessId,runId); } getGoalFeed(projectId) { require('./goal-state-record').query(projectId);return require('./goal-feed-record').decode(this.db.prepare('SELECT data_json FROM goal_feeds WHERE project_id=?').get(projectId)?.data_json); } appendGoalFeed(projectId,event) { return this.db.transaction(()=>{const next=require('./goal-feed-record').append(this.getGoalFeed(projectId),projectId,event);this.db.prepare('INSERT INTO goal_feeds (project_id,data_json) VALUES (?,?) ON CONFLICT(project_id) DO UPDATE SET data_json=excluded.data_json').run(projectId,JSON.stringify(next));return next;})(); } getGoalPlanningCheckpoint(projectId,id) { require('./goal-state-record').query(projectId,id); return require('../services/goal-planning-checkpoint').decode(this.db.prepare('SELECT data_json FROM goal_planning_checkpoints WHERE project_id=? AND id=?').get(projectId,id)?.data_json); } saveGoalPlanningCheckpoint(projectId,id,value,revision) { return this.db.transaction(()=>{const next=require('../services/goal-planning-checkpoint').prepare(projectId,id,value,this.getGoalPlanningCheckpoint(projectId,id),revision); this.db.prepare('INSERT INTO goal_planning_checkpoints (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'preparation',id,null,id,next.revision,next);return next; })(); } appendPolicyEvent(event) { const next=require('./policy-event-record').prepare(event); return this.db.transaction(()=>{ this.db.prepare('INSERT INTO policy_events (id,project_id,data_json) VALUES (?,?,?)').run(next.id,next.projectId,JSON.stringify(next)); this.db.prepare('DELETE FROM policy_events WHERE project_id=? AND id NOT IN (SELECT id FROM policy_events WHERE project_id=? ORDER BY rowid DESC LIMIT 1000)').run(next.projectId,next.projectId); return next; })(); } listPolicyEvents(projectId,limit=20) { const records=require('./policy-event-record');records.query(projectId,limit); return this.db.prepare('SELECT data_json FROM policy_events WHERE project_id=? ORDER BY rowid DESC LIMIT ?').all(projectId,limit).map(row=>records.prepare(JSON.parse(row.data_json))); } initTables() { this.db.prepare('CREATE TABLE IF NOT EXISTS batch_publication_actions (run_id TEXT PRIMARY KEY,data_json TEXT NOT NULL)').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS batch_loop_observations (run_id TEXT NOT NULL,event_key TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(run_id,event_key))').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS ui_artifacts (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS goal_feeds (project_id TEXT PRIMARY KEY,data_json TEXT NOT NULL)').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS goal_procedures (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS goal_fulfillments (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS goal_planning_checkpoints (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS goal_states (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS policy_events (id TEXT PRIMARY KEY, project_id TEXT NOT NULL, data_json TEXT NOT NULL)').run(); this.db.prepare('CREATE INDEX IF NOT EXISTS policy_events_project ON policy_events(project_id)').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS runtime_usage (run_id TEXT PRIMARY KEY, data_json TEXT NOT NULL)').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS batch_checkpoints (run_id TEXT PRIMARY KEY, data_json TEXT NOT NULL)').run(); this.db.prepare('CREATE TABLE IF NOT EXISTS decision_gates (id TEXT PRIMARY KEY, revision INTEGER NOT NULL, gate_json TEXT NOT NULL)').run(); // 1. Nodes Table this.db.prepare(` CREATE TABLE IF NOT EXISTS nodes ( id TEXT NOT NULL, project_id TEXT NOT NULL, type TEXT NOT NULL, label TEXT NOT NULL, properties TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id, project_id) ) `).run(); // 2. Edges Table this.db.prepare(` CREATE TABLE IF NOT EXISTS edges ( id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, source TEXT NOT NULL, target TEXT NOT NULL, label TEXT NOT NULL, properties TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(project_id, source, target, label) ) `).run(); // Indexing this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_nodes_proj ON nodes (project_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_edges_proj ON edges (project_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_edges_nodes ON edges (source, target)`).run(); // 3. FTS5 Virtual Table for nodes search this.db.prepare(` CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5( id UNINDEXED, project_id, type, label, properties, tokenize='porter' ) `).run(); // Triggers to sync INSERT, UPDATE, DELETE to FTS5 this.db.prepare(` CREATE TRIGGER IF NOT EXISTS trg_nodes_fts_insert AFTER INSERT ON nodes BEGIN INSERT INTO nodes_fts (id, project_id, type, label, properties) VALUES (new.id, new.project_id, new.type, new.label, new.properties); END `).run(); this.db.prepare(` CREATE TRIGGER IF NOT EXISTS trg_nodes_fts_update AFTER UPDATE ON nodes BEGIN UPDATE nodes_fts SET id = new.id, project_id = new.project_id, type = new.type, label = new.label, properties = new.properties WHERE id = old.id AND project_id = old.project_id; END `).run(); this.db.prepare(` CREATE TRIGGER IF NOT EXISTS trg_nodes_fts_delete AFTER DELETE ON nodes BEGIN DELETE FROM nodes_fts WHERE id = old.id AND project_id = old.project_id; END `).run(); // Seed/migrate existing nodes data into FTS5 table this.db.prepare(` INSERT INTO nodes_fts (id, project_id, type, label, properties) SELECT id, project_id, type, label, properties FROM nodes WHERE NOT EXISTS ( SELECT 1 FROM nodes_fts WHERE nodes_fts.id = nodes.id AND nodes_fts.project_id = nodes.project_id ) `).run(); // 4. Batch Tasks Table this.db.prepare(` CREATE TABLE IF NOT EXISTS batch_tasks ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, name TEXT NOT NULL, prompt TEXT NOT NULL, cron_expr TEXT NOT NULL, max_turns INTEGER DEFAULT 30, is_active INTEGER DEFAULT 0, steps_json TEXT, is_tested_success INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // Migration/Add column check for steps_json and is_tested_success if (!this.db.pragma('table_info(batch_tasks)').some(column => column.name === 'timezone')) { this.db.prepare('ALTER TABLE batch_tasks ADD COLUMN timezone TEXT').run(); } if (!this.db.pragma('table_info(batch_tasks)').some(column => column.name === 'tested_fingerprint')) { this.db.prepare('ALTER TABLE batch_tasks ADD COLUMN tested_fingerprint TEXT').run(); } try { const pragma = this.db.pragma("table_info(batch_tasks)"); const hasStepsJson = pragma.some(c => c.name === 'steps_json'); const hasIsTestedSuccess = pragma.some(c => c.name === 'is_tested_success'); const hasLoopConfig = pragma.some(c => c.name === 'loop_config'); if (!hasStepsJson) { this.db.prepare(`ALTER TABLE batch_tasks ADD COLUMN steps_json TEXT`).run(); } if (!hasIsTestedSuccess) { this.db.prepare(`ALTER TABLE batch_tasks ADD COLUMN is_tested_success INTEGER DEFAULT 0`).run(); } if (!hasLoopConfig) { this.db.prepare(`ALTER TABLE batch_tasks ADD COLUMN loop_config TEXT`).run(); } const existing = this.db.prepare(`SELECT * FROM batch_tasks`).all(); for (const row of existing) { if (!row.steps_json) { const steps = [{ id: 'step_1', name: 'Claude Agent Task', type: 'pty_agent', config: { prompt: row.prompt || '', max_turns: row.max_turns || 30 }, on_failure: 'abort' }]; this.db.prepare(`UPDATE batch_tasks SET steps_json = ? WHERE id = ?`).run(JSON.stringify(steps), row.id); } } } catch (e) { console.error('[KnowledgeDB] Migration of batch_tasks columns failed:', e); } // 5. Batch Runs Table this.db.prepare(` CREATE TABLE IF NOT EXISTS batch_runs ( run_id TEXT PRIMARY KEY, task_id TEXT NOT NULL, status TEXT NOT NULL, started_at DATETIME DEFAULT CURRENT_TIMESTAMP, completed_at DATETIME, log_path TEXT, error_message TEXT, FOREIGN KEY(task_id) REFERENCES batch_tasks(id) ON DELETE CASCADE ) `).run(); // 6. Workflows Table if (!this.db.prepare('PRAGMA table_info(batch_runs)').all().some(column => column.name === 'work_dir')) { this.db.prepare('ALTER TABLE batch_runs ADD COLUMN work_dir TEXT').run(); } this.db.prepare(` CREATE TABLE IF NOT EXISTS workflows ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, name TEXT NOT NULL, description TEXT, graph_json TEXT NOT NULL, is_active INTEGER DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // 7. Workflow Runs Table this.db.prepare(` CREATE TABLE IF NOT EXISTS workflow_runs ( run_id TEXT PRIMARY KEY, workflow_id TEXT NOT NULL, status TEXT NOT NULL, current_node_id TEXT, run_data TEXT NOT NULL, log_path TEXT, started_at DATETIME DEFAULT CURRENT_TIMESTAMP, completed_at DATETIME, FOREIGN KEY(workflow_id) REFERENCES workflows(id) ON DELETE CASCADE ) `).run(); // 8. Workflow Tasks Table (SQLite Embedded Queue) this.db.prepare(` CREATE TABLE IF NOT EXISTS workflow_tasks ( task_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, node_id TEXT NOT NULL, agent_id TEXT NOT NULL, payload TEXT, status TEXT NOT NULL, result TEXT, error TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // 9. Harnesses Table this.db.prepare(` CREATE TABLE IF NOT EXISTS harnesses ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, name TEXT NOT NULL, description TEXT, trigger_pattern TEXT, validation_command TEXT NOT NULL, computer_use_enabled INTEGER DEFAULT 0, max_retries INTEGER DEFAULT 3, success_criteria TEXT, tool_chain TEXT, stages TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // 10. Harness Runs Table this.db.prepare(` CREATE TABLE IF NOT EXISTS harness_runs ( run_id TEXT PRIMARY KEY, harness_id TEXT NOT NULL, workflow_run_id TEXT, status TEXT NOT NULL, retry_count INTEGER DEFAULT 0, logs TEXT, tool_chain TEXT, stage_results TEXT, receipt_summary TEXT, definition_hash TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, completed_at DATETIME, FOREIGN KEY(harness_id) REFERENCES harnesses(id) ON DELETE CASCADE ) `).run(); // 11. Triage Items Table this.db.prepare(` CREATE TABLE IF NOT EXISTS triage_items ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, run_id TEXT NOT NULL, source_type TEXT NOT NULL, error_message TEXT, ai_analysis TEXT, status TEXT DEFAULT 'pending', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // 12. Workflow Provenance Table (NiFi Data Provenance 벤치마킹) this.db.prepare(` CREATE TABLE IF NOT EXISTS workflow_provenance ( id TEXT PRIMARY KEY, run_id TEXT NOT NULL, node_id TEXT NOT NULL, parent_node_ids TEXT, input_flow_file TEXT NOT NULL, output_flow_file TEXT, status TEXT NOT NULL, started_at DATETIME DEFAULT CURRENT_TIMESTAMP, ended_at DATETIME, retry_count INTEGER DEFAULT 0, FOREIGN KEY(run_id) REFERENCES workflow_runs(run_id) ON DELETE CASCADE ) `).run(); // Indices for foreign keys and queries this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_wf_runs_wf ON workflow_runs (workflow_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_wf_tasks_run ON workflow_tasks (run_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_harness_runs_harness ON harness_runs (harness_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_triage_items_proj ON triage_items (project_id)`).run(); // Migration(B1): 기존 harnesses 테이블에 stages 컬럼 안전 추가(다단계 검증 게이트). // WHY: 이전 버전 DB 파일을 가진 사용자도 앱 재시작 시 자동으로 컬럼이 생겨야 한다. // (batch_tasks / loop_runs 마이그레이션과 동일한 pragma("table_info")+ALTER 패턴) try { const harnessesPragma = this.db.pragma("table_info(harnesses)"); const hasStages = harnessesPragma.some(c => c.name === 'stages'); if (!hasStages) { this.db.prepare(`ALTER TABLE harnesses ADD COLUMN stages TEXT`).run(); } } catch (migErr) { console.error('[SqliteDb] harnesses stages 마이그레이션 오류:', migErr.message); } // 화면 검증 선택이 저장 중 사라져 HTTP 검사로 바뀌지 않도록 보존한다. // docs/specs/remote-harness-validation.md v1.0.0 if (!this.db.pragma('table_info(harnesses)').some(c => c.name === 'computer_use_enabled')) { this.db.prepare('ALTER TABLE harnesses ADD COLUMN computer_use_enabled INTEGER DEFAULT 0').run(); } // Migration(B2): 기존 harness_runs 테이블에 stage_results/receipt_summary 컬럼 안전 추가. // WHY: 이전 버전 DB 파일을 가진 사용자도 앱 재시작 시 자동으로 컬럼이 생겨야 한다. // (harnesses.stages / loop_runs.receipt_summary 마이그레이션과 동일한 pragma("table_info")+ALTER 패턴) try { const harnessRunsPragma = this.db.pragma("table_info(harness_runs)"); if (!harnessRunsPragma.some(c=>c.name==='goal_evidence')) this.db.prepare('ALTER TABLE harness_runs ADD COLUMN goal_evidence TEXT').run(); const hasStageResults = harnessRunsPragma.some(c => c.name === 'stage_results'); if (!hasStageResults) { this.db.prepare(`ALTER TABLE harness_runs ADD COLUMN stage_results TEXT`).run(); } const hasReceiptSummary = harnessRunsPragma.some(c => c.name === 'receipt_summary'); if (!hasReceiptSummary) { this.db.prepare(`ALTER TABLE harness_runs ADD COLUMN receipt_summary TEXT`).run(); } // 기존 성공은 NULL로 유지하며 현재 정의의 해시를 소급해서 채우지 않는다. // docs/specs/bong-harness-proof.md v1.0.0 if (!harnessRunsPragma.some(c=>c.name==='definition_hash')) { this.db.prepare(`ALTER TABLE harness_runs ADD COLUMN definition_hash TEXT`).run(); } } catch (migErr) { console.error('[SqliteDb] harness_runs stage_results/receipt_summary 마이그레이션 오류:', migErr.message); } this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_wf_prov_run ON workflow_provenance (run_id)`).run(); // 같은 실행의 최신 검증만 읽는다. 과거 50건 제한 때문에 현재 근거가 사라지지 않게 한다. // docs/specs/bong-goal-fulfillment.md v1.0.0 this.db.prepare('CREATE INDEX IF NOT EXISTS idx_harness_workflow ON harness_runs (harness_id,workflow_run_id,created_at)').run(); // 13. Troubleshoot Entries Table this.db.prepare(` CREATE TABLE IF NOT EXISTS troubleshoot_entries ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, error_pattern TEXT NOT NULL, error_type TEXT, root_cause TEXT, solution TEXT NOT NULL, affected_files TEXT, tags TEXT, hit_count INTEGER DEFAULT 1, last_hit_at DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // 14. Dev Preferences Table this.db.prepare(` CREATE TABLE IF NOT EXISTS dev_preferences ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, category TEXT NOT NULL, preference_key TEXT NOT NULL, preference_value TEXT NOT NULL, confidence REAL DEFAULT 0.5, source TEXT, occurrence_count INTEGER DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(project_id, category, preference_key) ) `).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_ts_entries_proj ON troubleshoot_entries (project_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_dev_pref_proj ON dev_preferences (project_id)`).run(); // 15. Favorite Prompts Table this.db.prepare(` CREATE TABLE IF NOT EXISTS favorite_prompts ( id TEXT PRIMARY KEY, title TEXT NOT NULL, prompt_text TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // 16. Loop Goals Table (루프 목표 정의) this.db.prepare(` CREATE TABLE IF NOT EXISTS loop_goals ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, task_id TEXT, -- batch_tasks FK (nullable) workflow_id TEXT, -- workflows FK (nullable) name TEXT NOT NULL, goal_expression TEXT NOT NULL, -- 평가식 JSON max_iterations INTEGER DEFAULT 10, token_budget REAL DEFAULT 5.0, -- USD max_wall_time INTEGER DEFAULT 3600, consecutive_failure_threshold INTEGER DEFAULT 3, worktree_isolation INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // 17. Loop Runs Table (루프 실행 기록) this.db.prepare(` CREATE TABLE IF NOT EXISTS loop_runs ( run_id TEXT PRIMARY KEY, goal_id TEXT NOT NULL, parent_run_id TEXT, status TEXT NOT NULL, -- running|completed|failed|circuit_broken|aborted total_iterations INTEGER DEFAULT 0, total_tokens_used INTEGER DEFAULT 0, total_cost REAL DEFAULT 0, goal_met INTEGER DEFAULT 0, break_reason TEXT, receipt_summary TEXT, started_at DATETIME DEFAULT CURRENT_TIMESTAMP, completed_at DATETIME, FOREIGN KEY(goal_id) REFERENCES loop_goals(id) ON DELETE CASCADE ) `).run(); // Migration: 기존 loop_runs 테이블에 receipt_summary 컬럼 안전 추가. // WHY: 이전 버전 DB 파일을 가진 사용자도 앱 재시작 시 자동으로 컬럼이 생겨야 한다. // (batch_tasks 마이그레이션과 동일한 pragma+ALTER 패턴) try { const loopRunsPragma = this.db.pragma("table_info(loop_runs)"); const hasReceiptSummary = loopRunsPragma.some(c => c.name === 'receipt_summary'); if (!hasReceiptSummary) { this.db.prepare(`ALTER TABLE loop_runs ADD COLUMN receipt_summary TEXT`).run(); } } catch (migErr) { console.error('[SqliteDb] loop_runs receipt_summary 마이그레이션 오류:', migErr.message); } // 18. Loop Iterations Table (루프 이터레이션 상세 기록) this.db.prepare(` CREATE TABLE IF NOT EXISTS loop_iterations ( id TEXT PRIMARY KEY, loop_run_id TEXT NOT NULL, iteration_number INTEGER NOT NULL, status TEXT NOT NULL, -- running|success|failed step_outputs TEXT, -- JSON snapshot goal_evaluation_result INTEGER, tokens_used INTEGER DEFAULT 0, cost REAL DEFAULT 0, worktree_branch TEXT, error_message TEXT, started_at DATETIME DEFAULT CURRENT_TIMESTAMP, completed_at DATETIME, FOREIGN KEY(loop_run_id) REFERENCES loop_runs(run_id) ON DELETE CASCADE ) `).run(); // 19. Loop Messages Table (서브에이전트 메시지 로그) this.db.prepare(` CREATE TABLE IF NOT EXISTS loop_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, loop_run_id TEXT NOT NULL, iteration_number INTEGER, sender_agent_id TEXT NOT NULL, receiver_agent_id TEXT NOT NULL, message_type TEXT NOT NULL, content TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(loop_run_id) REFERENCES loop_runs(run_id) ON DELETE CASCADE ) `).run(); // 19-b. Loop Templates Table (프로젝트 비종속 재사용 템플릿) // WHY: 특정 프로젝트에서 검증된 루프 설정(목표식+파라미터+에이전트 스텝)을 // project_id/task_id 등 종속 필드 없이 저장해 다른 프로젝트에서 재사용(인스턴스화)한다. // source_* 컬럼은 "어디서 왔는지" 참고용 기록일 뿐 종속 관계는 아니다. // CREATE TABLE IF NOT EXISTS 이므로 반복 초기화에도 idempotent 하다. this.db.prepare(` CREATE TABLE IF NOT EXISTS loop_templates ( id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, goal_expression TEXT NOT NULL, -- 평가식 JSON (loop_goals와 동일 스키마) max_iterations INTEGER DEFAULT 10, token_budget REAL DEFAULT 5.0, -- USD max_wall_time INTEGER DEFAULT 3600, consecutive_failure_threshold INTEGER DEFAULT 3, worktree_isolation INTEGER DEFAULT 0, steps_json TEXT, -- 에이전트 프롬프트/엔진/모델 스텝 (batch_tasks.steps_json 복제본) source_project_name TEXT, -- 참고용: 어느 프로젝트에서 복제됐는지 기록만 source_task_name TEXT, -- 참고용: 원본 batch_task 이름 created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); // 20. Worktree State Table (격리 워크트리 상태 관리) this.db.prepare(` CREATE TABLE IF NOT EXISTS worktree_state ( id TEXT PRIMARY KEY, run_id TEXT NOT NULL, node_id TEXT NOT NULL, wt_path TEXT NOT NULL, branch_name TEXT NOT NULL, status TEXT NOT NULL, -- active|merged|discarded|orphaned created_at TEXT DEFAULT (datetime('now', 'localtime')), completed_at TEXT ) `).run(); // Indices for Loop Tables this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_loop_runs_goal ON loop_runs(goal_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_loop_iters_run ON loop_iterations(loop_run_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_loop_msgs_run ON loop_messages(loop_run_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_wt_state_run ON worktree_state(run_id)`).run(); // 21. Headroom Metrics Table (보안 마스킹 및 감사 통계 지표) this.db.prepare(` CREATE TABLE IF NOT EXISTS headroom_metrics ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, provider TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, rule_id TEXT, rule_name TEXT, match_count INTEGER, original_tokens INTEGER, compressed_tokens INTEGER, cost_saved REAL ) `).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_headroom_metrics_rule ON headroom_metrics(rule_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_headroom_metrics_time ON headroom_metrics(timestamp)`).run(); // 22. Swarm Blackboard Table (SPEC-INNOV-001 v1.0.0) this.db.prepare(` CREATE TABLE IF NOT EXISTS blackboard_entries ( entry_id TEXT PRIMARY KEY, project_id TEXT NOT NULL DEFAULT 'default', topic TEXT NOT NULL, author_agent TEXT NOT NULL, payload TEXT NOT NULL, salience REAL DEFAULT 0.5, claimed_by TEXT, claimed_until INTEGER, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL ) `).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_bb_topic ON blackboard_entries(project_id, topic)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_bb_claim ON blackboard_entries(claimed_until)`).run(); } saveHeadroomMetric(metric) { try { const stmt = this.db.prepare(` INSERT INTO headroom_metrics (session_id, provider, rule_id, rule_name, match_count, original_tokens, compressed_tokens, cost_saved) VALUES (?, ?, ?, ?, ?, ?, ?, ?) `); return stmt.run( metric.sessionId || null, metric.provider || null, metric.ruleId || null, metric.ruleName || null, metric.matchCount || 0, metric.originalTokens || 0, metric.compressedTokens || 0, metric.costSaved || 0.0 ); } catch (e) { console.error('[sqlite-db] Failed to saveHeadroomMetric:', e); return null; } } getHeadroomStats(days = 7) { const limitDays = parseInt(days, 10) || 7; const query = ` SELECT date(timestamp, 'localtime') as date_label, rule_name, sum(match_count) as total_matches, sum(original_tokens) as total_orig_tokens, sum(compressed_tokens) as total_comp_tokens, sum(cost_saved) as total_cost_saved FROM headroom_metrics WHERE timestamp >= datetime('now', '-${limitDays} days', 'localtime') GROUP BY date_label, rule_name ORDER BY date_label ASC, total_matches DESC `; try { return this.db.prepare(query).all(); } catch (e) { console.error('[sqlite-db] Failed to getHeadroomStats:', e); return []; } } saveNode(projectId, node) { const propertiesStr = typeof node.properties === 'string' ? node.properties : JSON.stringify(node.properties || {}); const stmt = this.db.prepare(` INSERT INTO nodes (id, project_id, type, label, properties, created_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id, project_id) DO UPDATE SET type = excluded.type, label = excluded.label, properties = excluded.properties `); stmt.run(node.id, projectId, node.type, node.label, propertiesStr, node.created_at || new Date().toISOString()); } saveEdge(projectId, edge) { const propertiesStr = typeof edge.properties === 'string' ? edge.properties : JSON.stringify(edge.properties || {}); const stmt = this.db.prepare(` INSERT INTO edges (project_id, source, target, label, properties, created_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, source, target, label) DO UPDATE SET properties = excluded.properties `); stmt.run(projectId, edge.source, edge.target, edge.label, propertiesStr, edge.created_at || new Date().toISOString()); } replaceVaultEdges(projectId, vaultRoot, edges) { return this.db.transaction(() => { const old = this.db.prepare('SELECT source,target,label,properties FROM edges WHERE project_id = ?').all(projectId); const remove = this.db.prepare('DELETE FROM edges WHERE project_id = ? AND source = ? AND target = ? AND label = ?'); const retained = new Set(); const key = edge => JSON.stringify([edge.source, edge.target, edge.label]); for (const edge of old) { const props = JSON.parse(edge.properties || '{}'); if (props.owner === 'bada-vault-links-v1' && props.vaultRoot === vaultRoot) remove.run(projectId, edge.source, edge.target, edge.label); else retained.add(key(edge)); } for (const edge of edges) if (!retained.has(key(edge))) this.saveEdge(projectId, { ...edge, properties: { owner: 'bada-vault-links-v1', vaultRoot } }); })(); } getGraphData(projectId, days) { const cutoff = days ? new Date(Date.now() - days * 86400000).toISOString() : null; // 1. 해당 프로젝트 전체 노드/엣지 로딩 const nodes = this.db.prepare(`SELECT * FROM nodes WHERE project_id = ?`).all(projectId); const edges = this.db.prepare(`SELECT * FROM edges WHERE project_id = ?`).all(projectId); // 2. 날짜 필터링에 의한 세션 추출 let activeSessionIdsQuery = `SELECT id FROM nodes WHERE project_id = ? AND type = 'session'`; const params = [projectId]; if (cutoff) { activeSessionIdsQuery += ` AND created_at >= ?`; params.push(cutoff); } const activeSessionRows = this.db.prepare(activeSessionIdsQuery).all(...params); const activeSessionIds = new Set(activeSessionRows.map(r => r.id)); if (activeSessionIds.size > 0) { // 세션과 연결된 엣지 및 co-modified 엣지 const sessionEdges = edges.filter(e => activeSessionIds.has(e.source) || activeSessionIds.has(e.target) || (e.label === 'co-modified' && (!cutoff || !e.created_at || e.created_at >= cutoff)) ); // 도구 엣지가 없는 텍스트 전용 세션도 대화 조회 대상으로 남긴다. const activeNodeIds = new Set(activeSessionIds); const activeFileIds = []; sessionEdges.forEach(e => { activeNodeIds.add(e.source); activeNodeIds.add(e.target); if (e.source.startsWith('file-')) activeFileIds.push(e.source); if (e.target.startsWith('file-')) activeFileIds.push(e.target); }); const allEdges = [...sessionEdges]; if (activeFileIds.length > 0) { const uniqueFileIds = new Set(activeFileIds); // 파일들과 결합된 온톨로지 구조 엣지들 const ontologyEdges = edges.filter(e => uniqueFileIds.has(e.source) && ['defines_class', 'defines_function', 'imports', 'depends_on'].includes(e.label) ); ontologyEdges.forEach(e => { activeNodeIds.add(e.source); activeNodeIds.add(e.target); allEdges.push(e); }); } // 노드 목록 필터링 const filteredNodes = nodes.filter(n => activeNodeIds.has(n.id) || n.type === 'wiki' || n.type === 'note' || n.type === 'ghost' ); return filterAndCapGraphData(filteredNodes, allEdges, this._safeParse.bind(this)); } else { // 세션이 없는 경우: Wiki 노드와 그 엣지만 로딩 const wikiNodes = nodes.filter(n => n.type === 'wiki' || n.type === 'note' || n.type === 'ghost'); const wikiNodeIds = new Set(wikiNodes.map(n => n.id)); const wikiEdges = edges.filter(e => wikiNodeIds.has(e.source) && wikiNodeIds.has(e.target)); return filterAndCapGraphData(wikiNodes, wikiEdges, this._safeParse.bind(this)); } } // 코드맵 전용 그래프 데이터 — 세션 필터 없이 file/code/library 노드와 그 엣지만 반환한다. // (getGraphData 는 세션 중심이라 세션 노드가 없는 순수 코드 분석 결과를 표시하지 못함) getCodeGraphData(projectId) { const nodes = this.db.prepare( `SELECT * FROM nodes WHERE project_id = ? AND type IN ('file','code','library')` ).all(projectId); const edges = this.db.prepare(`SELECT * FROM edges WHERE project_id = ?`).all(projectId); return filterAndCapGraphData(nodes, edges, this._safeParse.bind(this)); } // FTS tokenizer/표시 제목과 무관하게 같은 프로젝트의 정확한 교훈 유형을 읽는다. // 설명 문서: docs/specs/goal-replan-lessons.md v1.0.0 getReplanLessons(projectId) { return this.db.prepare("SELECT * FROM nodes WHERE project_id = ? AND type = 'replan_lesson'") .all(projectId).map(n => ({ ...n, properties: this._safeParse(n.properties) })); } searchNodes(projectId, query) { const ftsQuery = query.replace(/["]/g, '').split(/\s+/).filter(Boolean).map(term => `${term}*`).join(' AND '); if (!ftsQuery) return []; try { const rows = this.db.prepare(` SELECT n.* FROM nodes n JOIN nodes_fts f ON n.id = f.id AND n.project_id = f.project_id WHERE f.project_id = ? AND nodes_fts MATCH ? `).all(projectId, ftsQuery); return rows.map(r => ({ ...r, properties: this._safeParse(r.properties) })); } catch (e) { console.warn('[KnowledgeDB] FTS5 search failed, falling back to LIKE:', e.message); const sqlLike = `%${query}%`; const fallbackRows = this.db.prepare(` SELECT * FROM nodes WHERE project_id = ? AND (label LIKE ? OR properties LIKE ?) `).all(projectId, sqlLike, sqlLike); return fallbackRows.map(r => ({ ...r, properties: this._safeParse(r.properties) })); } } getNodeDetail(nodeId, projectId) { const node = projectId ? this.db.prepare(`SELECT * FROM nodes WHERE id = ? AND project_id = ?`).get(nodeId, projectId) : this.db.prepare(`SELECT * FROM nodes WHERE id = ?`).get(nodeId); if (!node) return null; const scope = projectId || node.project_id; let edgeSql = `SELECT * FROM edges WHERE (source = ? OR target = ?)`; const edgeParams = [nodeId, nodeId]; if (scope) { edgeSql += ` AND project_id = ?`; edgeParams.push(scope); } const connectedEdges = this.db.prepare(edgeSql).all(...edgeParams); const resolvedEdges = connectedEdges.map(e => { const otherId = e.source === nodeId ? e.target : e.source; const otherNode = this.db.prepare(`SELECT label, type FROM nodes WHERE id = ? AND project_id = ?`).get(otherId, scope); return { source: e.source, target: e.target, label: e.label, otherLabel: otherNode ? otherNode.label : otherId, otherType: otherNode ? otherNode.type : 'unknown' }; }); return { node: { ...node, properties: this._safeParse(node.properties) }, edges: resolvedEdges }; } getSessionNodes(projectId, limit) { // 봉의 목록은 DB 단계에서 제한한다. 기존 전체 동기화/마이그레이션 호출은 그대로 유지한다. if (limit !== undefined) { if (typeof projectId !== 'string' || !projectId || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error('Invalid session list limit'); return this.db.prepare("SELECT * FROM nodes WHERE type = 'session' AND project_id = ? ORDER BY created_at DESC, id ASC LIMIT ?") .all(projectId, limit).map(n => ({ ...n, properties: this._safeParse(n.properties) })); } const rows = projectId ? this.db.prepare("SELECT * FROM nodes WHERE type = 'session' AND project_id = ?").all(projectId) : this.db.prepare("SELECT * FROM nodes WHERE type = 'session'").all(); return rows.map(n => ({ ...n, properties: this._safeParse(n.properties) })); } renameSessionNode(projectId, oldId, newId, properties) { return this.db.transaction(() => { const old = this.db.prepare('SELECT type FROM nodes WHERE project_id = ? AND id = ?').get(projectId, oldId); const existing = this.db.prepare('SELECT id FROM nodes WHERE project_id = ? AND id = ?').get(projectId, newId); if (old?.type !== 'session' || existing) throw Object.assign(new Error('Session migration destination conflicts'), { code: 'SESSION_MIGRATION_CONFLICT' }); this.db.prepare('UPDATE nodes SET id = ?, properties = ? WHERE project_id = ? AND id = ?').run(newId, JSON.stringify(properties), projectId, oldId); // UNIQUE 제약 충돌은 transaction 전체를 되돌려 노드·사용자 엣지를 함께 보존한다. this.db.prepare('UPDATE edges SET source = CASE WHEN source = ? THEN ? ELSE source END, target = CASE WHEN target = ? THEN ? ELSE target END WHERE project_id = ? AND (source = ? OR target = ?)') .run(oldId, newId, oldId, newId, projectId, oldId, oldId); })(); } getDependencyTree(projectId, startNodeId) { return this.db.prepare(` SELECT e.source, e.target, 1 as depth, n.label as target_label, n.type as target_type FROM edges e JOIN nodes n ON e.target = n.id AND e.project_id = n.project_id WHERE e.project_id = ? AND e.source = ? AND e.label IN ('depends_on', 'imports') `).all(projectId, startNodeId); } clearProjectData(projectId) { this.db.prepare(`DELETE FROM nodes WHERE project_id = ?`).run(projectId); this.db.prepare(`DELETE FROM edges WHERE project_id = ?`).run(projectId); this.db.prepare(`DELETE FROM nodes_fts WHERE project_id = ?`).run(projectId); } exportProjectData(projectId) { const nodes = this.db.prepare(`SELECT * FROM nodes WHERE project_id = ?`).all(projectId); const edges = this.db.prepare(`SELECT * FROM edges WHERE project_id = ?`).all(projectId); return { nodes, edges }; } importProjectData(projectId, data) { const plan = require('./graph-import-plan').prepareGraphImport(data); return this.db.transaction(() => { this.clearProjectData(projectId); const insertNode = this.db.prepare('INSERT INTO nodes (id, project_id, type, label, properties, created_at) VALUES (?, ?, ?, ?, ?, ?)'); const insertEdge = this.db.prepare('INSERT INTO edges (project_id, source, target, label, properties, created_at) VALUES (?, ?, ?, ?, ?, ?)'); // FTS는 nodes의 기존 trigger가 갱신한다. 별도 중복 삽입을 하지 않는다. for (const n of plan.nodes) insertNode.run(n.id, projectId, n.type, n.label, n.properties, n.created_at); for (const e of plan.edges) insertEdge.run(projectId, e.source, e.target, e.label, e.properties, e.created_at); })(); } deleteNode(projectId, nodeId) { this.db.prepare(`DELETE FROM nodes WHERE project_id = ? AND id = ?`).run(projectId, nodeId); this.db.prepare(`DELETE FROM edges WHERE project_id = ? AND (source = ? OR target = ?)`).run(projectId, nodeId, nodeId); } saveBatchTask(projectId, task) { const existing = this.db.prepare('SELECT * FROM batch_tasks WHERE id = ?').get(task.id); if (existing && existing.project_id !== projectId) throw new Error('Batch task ID belongs to another project'); const timezone = require('../utils/batch-timezone').batchTimezone(task.timezone, existing?.timezone); const stepsJson = typeof task.steps_json === 'string' ? task.steps_json : JSON.stringify(task.steps || []); const prompt = task.prompt || (task.steps && task.steps[0] && task.steps[0].config && task.steps[0].config.prompt) || ''; const maxTurns = task.max_turns ?? (task.steps && task.steps[0] && task.steps[0].config && task.steps[0].config.max_turns) ?? 30; const loopConfig = task.loop_config || null; const certification = require('../utils/batch-definition').forSave(existing, { ...task, project_id: projectId }); const stmt = this.db.prepare(` INSERT INTO batch_tasks (id, project_id, name, prompt, cron_expr, max_turns, is_active, steps_json, is_tested_success, loop_config, timezone, tested_fingerprint) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, prompt = excluded.prompt, cron_expr = excluded.cron_expr, max_turns = excluded.max_turns, is_active = excluded.is_active, steps_json = excluded.steps_json, is_tested_success = excluded.is_tested_success, loop_config = excluded.loop_config, timezone = excluded.timezone, tested_fingerprint = excluded.tested_fingerprint `); stmt.run(task.id, projectId, task.name, prompt, task.cron_expr ?? '', maxTurns, task.is_active ?? 0, stepsJson, certification.is_tested_success, loopConfig, timezone, certification.tested_fingerprint); } getBatchTasks(projectId) { return this.db.prepare(`SELECT * FROM batch_tasks WHERE project_id = ? ORDER BY created_at DESC`).all(projectId) .map(task => ({ ...task, is_tested_success: require('../utils/batch-definition').certified(task) ? 1 : 0 })); } // 최근 사용한 폴더 목록과 무관하게 저장된 활성 예약 전체를 복원한다. getActiveBatchTasks() { return this.db.prepare('SELECT * FROM batch_tasks WHERE is_active = 1 ORDER BY created_at DESC, id').all() .map(task => ({ ...task, is_tested_success: require('../utils/batch-definition').certified(task) ? 1 : 0 })); } deleteBatchTask(projectId, taskId) { this.db.prepare(`DELETE FROM batch_tasks WHERE project_id = ? AND id = ?`).run(projectId, taskId); } updateBatchTaskTestStatus(taskId, isTestedSuccess, fingerprint) { const task = this.db.prepare('SELECT * FROM batch_tasks WHERE id = ?').get(taskId); if (!task) return; const status = require('../utils/batch-definition').testStatus(task, isTestedSuccess, fingerprint); this.db.prepare('UPDATE batch_tasks SET is_tested_success = ?, tested_fingerprint = ? WHERE id = ?').run(status.is_tested_success, status.tested_fingerprint, taskId); } setBatchRunWorkspace(runId, workDir) { const result = this.db.prepare("UPDATE batch_runs SET work_dir = ? WHERE run_id = ? AND status = 'running'").run(workDir, runId); if (result.changes !== 1) throw new Error('Running batch record not found'); } startBatchRun(runId, taskId, logPath, workDir = null) { const stmt = this.db.prepare(` INSERT INTO batch_runs (run_id, task_id, status, log_path, started_at, work_dir) VALUES (?, ?, 'running', ?, ?, ?) `); stmt.run(runId, taskId, logPath, new Date().toISOString(), workDir); } completeBatchRun(runId, status, errorMessage) { const stmt = this.db.prepare(` UPDATE batch_runs SET status = ?, error_message = ?, completed_at = ? WHERE run_id = ? `); stmt.run(status, errorMessage || null, new Date().toISOString(), runId); } failStaleRuns() { // 다른 앱 프로세스의 실행까지 crashed로 바꾸지 않는다. 검토 복구 서비스가 종료를 판정한다. return { modified: 0 }; } getUnfinishedBatchRuns(taskId) { return this.db.prepare("SELECT * FROM batch_runs WHERE task_id = ? AND status IN ('running', 'crashed', 'paused') ORDER BY run_id").all(taskId); } getLatestTaskRun(taskId) { try { return this.db.prepare(` SELECT * FROM batch_runs WHERE task_id = ? ORDER BY started_at DESC LIMIT 1 `).get(taskId); } catch (e) { console.error('[KnowledgeDB] Failed to get latest task run:', e); return null; } } getBatchRuns(taskId) { return this.db.prepare(`SELECT * FROM batch_runs WHERE task_id = ? ORDER BY started_at DESC LIMIT 50`).all(taskId); } getBatchRun(runId) { return this.db.prepare('SELECT * FROM batch_runs WHERE run_id = ?').get(runId) || null; } saveWorkflow(projectId, workflow) { // 선행 SELECT와 저장 사이의 경합 없이 SQL 충돌 처리에서 소유권을 확인한다. // 설명 문서: docs/specs/mcp-session-boundary.md (v1.1.0) const stmt = this.db.prepare(` INSERT INTO workflows (id, project_id, name, description, graph_json) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, description = excluded.description, graph_json = excluded.graph_json WHERE workflows.project_id = excluded.project_id `); const result = stmt.run( workflow.id, projectId, workflow.name, workflow.description || '', typeof workflow.graph_json === 'string' ? workflow.graph_json : JSON.stringify(workflow.graph || {}) ); if (result.changes === 0) throw new Error('Workflow ID belongs to another project'); } getWorkflows(projectId, limit) { return this.db.prepare(`SELECT * FROM workflows WHERE project_id = ? ORDER BY created_at DESC LIMIT ?`).all(projectId, Number.isInteger(limit) && limit > 0 ? limit : -1); } // 설명 문서: docs/specs/bong-operations.md (v1.0.0). 사용량 재계산·실행 없이 체크포인트를 읽는다. getWorkflowRunsForProject(projectId, workflowId, limit = 3) { const owners = this.db.prepare(`SELECT project_id FROM workflows WHERE id = ?`).all(workflowId); if (owners.length !== 1 || owners[0].project_id !== projectId) throw new Error('Workflow ownership is unavailable'); return this.db.prepare(`SELECT * FROM workflow_runs WHERE workflow_id = ? ORDER BY started_at DESC LIMIT ?`).all(workflowId, Math.max(1, Math.min(50, Number.isInteger(limit) ? limit : 3))); } deleteWorkflow(projectId, workflowId) { // 원래 cascade와 feed를 함께 rollback한다. docs/specs/bong-goal-events.md v1.1.0 return this.db.transaction(()=>{ const {changes}=this.db.prepare(`DELETE FROM workflows WHERE project_id = ? AND id = ?`).run(projectId, workflowId); if(changes)require('../services/goal-event-feed').removed(this,projectId,'workflow_removed',workflowId); return changes; })(); } deleteWorkflowRun(runId) { return this.db.transaction(()=>{ const feed=require('../services/goal-event-feed'),binding=feed.removalBinding(this,runId); const {changes}=this.db.prepare(`DELETE FROM workflow_runs WHERE run_id = ?`).run(runId); if(changes&&binding)feed.removed(this,binding.projectId,'run_removed',runId,binding); return changes; })(); } clearAllWorkflowRuns(projectId) { return this.db.transaction(()=>{const {changes}=this.db.prepare(` DELETE FROM workflow_runs WHERE workflow_id IN (SELECT id FROM workflows WHERE project_id = ?) `).run(projectId); if(changes)require('../services/goal-event-feed').removed(this,projectId,'runs_cleared','workflow_runs'); return changes;})(); } startWorkflowRun(runId, workflowId, logPath, initialData) { return this.db.transaction(()=>{ const stmt = this.db.prepare(` INSERT INTO workflow_runs (run_id, workflow_id, status, run_data, log_path, started_at) VALUES (?, ?, 'running', ?, ?, ?) `); stmt.run(runId, workflowId, typeof initialData === 'string' ? initialData : JSON.stringify(initialData || {}), logPath, new Date().toISOString()); require('../services/goal-event-feed').runChanged(this,runId,initialData); })(); } checkpointWorkflowRun(runId, status, currentNodeId, runData) { return this.db.transaction(()=>{ const binding=require('../services/goal-event-feed').bindRun(this,runId); const stmt = this.db.prepare(` UPDATE workflow_runs SET status = ?, current_node_id = ?, run_data = ?, completed_at = CASE WHEN ? IN ('running', 'paused') THEN NULL ELSE completed_at END WHERE run_id = ? `); stmt.run(status, currentNodeId || null, typeof runData === 'string' ? runData : JSON.stringify(runData || {}), status, runId); require('../services/goal-event-feed').runChanged(this,runId,runData,'run',runId,binding); })(); } completeWorkflowRun(runId, status, runData) { return this.db.transaction(()=>{ const binding=require('../services/goal-event-feed').bindRun(this,runId); const stmt = this.db.prepare(` UPDATE workflow_runs SET status = ?, run_data = ?, completed_at = ? WHERE run_id = ? `); stmt.run(status, typeof runData === 'string' ? runData : JSON.stringify(runData || {}), new Date().toISOString(), runId); require('../services/goal-event-feed').runChanged(this,runId,runData,'run',runId,binding); })(); } getWorkflowRuns(workflowId) { return this.db.prepare(`SELECT * FROM workflow_runs WHERE workflow_id = ? ORDER BY started_at DESC LIMIT 50`).all(workflowId); } getWorkflow(workflowId) { return this.db.prepare(`SELECT * FROM workflows WHERE id = ?`).get(workflowId); } getWorkflowRun(runId) { return this.db.prepare(`SELECT * FROM workflow_runs WHERE run_id = ?`).get(runId); } enqueueWorkflowTask(taskId, runId, nodeId, agentId, payload) { const stmt = this.db.prepare(` INSERT INTO workflow_tasks (task_id, run_id, node_id, agent_id, payload, status) VALUES (?, ?, ?, ?, ?, 'queued') `); stmt.run(taskId, runId, nodeId, agentId, typeof payload === 'string' ? payload : JSON.stringify(payload || {})); } pollWorkflowQueue() { return this.db.transaction(() => { const task = this.db.prepare(` SELECT * FROM workflow_tasks WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1 `).get(); if (task) { this.db.prepare(` UPDATE workflow_tasks SET status = 'processing', updated_at = ? WHERE task_id = ? `).run(new Date().toISOString(), task.task_id); task.status = 'processing'; return task; } return null; }).immediate(); } getWorkflowTask(taskId) { return this.db.prepare(`SELECT * FROM workflow_tasks WHERE task_id = ?`).get(taskId); } getWorkflowTasks(runId) { return this.db.prepare(`SELECT * FROM workflow_tasks WHERE run_id = ? ORDER BY created_at DESC`).all(runId); } completeWorkflowTask(taskId, status, result, error) { const stmt = this.db.prepare(` UPDATE workflow_tasks SET status = ?, result = ?, error = ?, updated_at = ? WHERE task_id = ? `); stmt.run( status, result ? (typeof result === 'string' ? result : JSON.stringify(result)) : null, error ? (typeof error === 'string' ? error : JSON.stringify(error)) : null, new Date().toISOString(), taskId ); } saveHarness(projectId, harness) { return this.db.transaction(()=>{ const successCriteria = typeof harness.success_criteria === 'string' ? harness.success_criteria : JSON.stringify(harness.success_criteria || {}); const toolChain = typeof harness.tool_chain === 'string' ? harness.tool_chain : JSON.stringify(harness.tool_chain || []); // WHY: stages는 옵셔널. 미지정 시 null로 저장해야 getHarness가 null을 돌려주고 // 실행부(parseStages)가 "기존 단일-커맨드 경로"로 분기한다(기존 하네스 동작 100% 보존). const stages = (harness.stages === null || harness.stages === undefined || harness.stages === '') ? null : (typeof harness.stages === 'string' ? harness.stages : JSON.stringify(harness.stages)); const stmt = this.db.prepare(` INSERT INTO harnesses (id, project_id, name, description, trigger_pattern, validation_command, max_retries, success_criteria, tool_chain, stages, computer_use_enabled) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, description = excluded.description, trigger_pattern = excluded.trigger_pattern, validation_command = excluded.validation_command, max_retries = excluded.max_retries, success_criteria = excluded.success_criteria, tool_chain = excluded.tool_chain, stages = excluded.stages, computer_use_enabled = excluded.computer_use_enabled `); stmt.run( harness.id, projectId, harness.name, harness.description || '', harness.trigger_pattern || '', // 단계만 있는 하네스는 NOT NULL 단일 명령 열을 빈 값으로 보존한다. // 실제 실행 전 prepareHarness가 활성 모드의 명령을 검사한다. harness.validation_command ?? '', harness.max_retries ?? 3, successCriteria, toolChain, stages, harness.computer_use_enabled === true ? 1 : harness.computer_use_enabled === false ? 0 : (harness.computer_use_enabled ?? 0) ); require('../services/goal-event-feed').changed(this,projectId,'harness_definition',null,null,harness.id,0,this.getHarness(harness.id)); })(); } getHarnesses(projectId, limit) { return this.db.prepare(`SELECT * FROM harnesses WHERE project_id = ? ORDER BY created_at DESC LIMIT ?`).all(projectId, Number.isInteger(limit) && limit > 0 ? limit : -1); } getHarness(id) { return this.db.prepare(`SELECT * FROM harnesses WHERE id = ?`).get(id) || null; } deleteHarness(projectId, id) { return this.db.transaction(()=>{ const {changes}=this.db.prepare(`DELETE FROM harnesses WHERE project_id = ? AND id = ?`).run(projectId, id); if(changes)require('../services/goal-event-feed').removed(this,projectId,'harness_removed',id); return changes; })(); } saveHarnessRun(run) { return this.db.transaction(()=>{ const toolChain = typeof run.tool_chain === 'string' ? run.tool_chain : JSON.stringify(run.tool_chain || []); // WHY(B2): stage_results는 B1의 다단계 stages 실행 결과(JSON 배열). 단일-커맨드 하네스는 null로 저장. const stageResults = (run.stage_results === null || run.stage_results === undefined || run.stage_results === '') ? null : (typeof run.stage_results === 'string' ? run.stage_results : JSON.stringify(run.stage_results)); const receiptSummary = run.receipt_summary || null; // WHY(B2, COALESCE 미적용 근거): agent-runner.js의 runHarnessNode는 동일 run_id에 대해 // saveHarnessRun을 정확히 2회만 호출한다 — ① 시작 시 INSERT(status:'running', stage_results/receipt_summary 미상 → null), // ② 종료 시 UPDATE(status:'success'|'failed', 이 시점엔 stagesResult/리시트가 전부 계산 완료된 "최종" 값). // loop-controller.js의 harness_pass 분기(goal 검증용 하네스 실행)는 db.saveHarnessRun을 전혀 호출하지 않는다(harness_runs에 기록 안 함). // 즉 동일 run_id를 재저장하며 stage_results/receipt_summary를 누락시키는 제3의 호출 경로가 없으므로, // A1(loop_runs.receipt_summary)과 달리 COALESCE 보존 시맨틱이 불필요하다 — 두 번째(최종) 호출값을 그대로 덮어쓰면 된다. const stmt = this.db.prepare(` INSERT INTO harness_runs (run_id, harness_id, workflow_run_id, status, retry_count, logs, tool_chain, stage_results, receipt_summary, definition_hash, goal_evidence, created_at, completed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(run_id) DO UPDATE SET status = excluded.status, retry_count = excluded.retry_count, logs = excluded.logs, tool_chain = excluded.tool_chain, stage_results = excluded.stage_results, receipt_summary = excluded.receipt_summary, definition_hash = excluded.definition_hash, goal_evidence = excluded.goal_evidence, completed_at = excluded.completed_at `); stmt.run( run.run_id, run.harness_id, run.workflow_run_id || null, run.status, run.retry_count ?? 0, run.logs || '', toolChain, stageResults, receiptSummary, /^[a-f0-9]{64}$/.test(run.definition_hash) ? run.definition_hash : null, run.goal_evidence ? JSON.stringify(run.goal_evidence) : null, run.created_at || new Date().toISOString(), run.completed_at || null ); if(run.workflow_run_id)require('../services/goal-event-feed').runChanged(this,run.workflow_run_id,run,'harness',run.run_id); })(); } getHarnessRuns(harnessId) { return this.db.prepare(`SELECT * FROM harness_runs WHERE harness_id = ? ORDER BY created_at DESC LIMIT 50`).all(harnessId); } // 설명 문서: docs/specs/bong-operations.md (v1.0.0). 이력 조회 전에 소유권을 확인한다. getHarnessRunsForProject(projectId, harnessId, limit = 3) { const owners = this.db.prepare(`SELECT project_id FROM harnesses WHERE id = ?`).all(harnessId); if (owners.length !== 1 || owners[0].project_id !== projectId) throw new Error('Harness ownership is unavailable'); return this.db.prepare(`SELECT * FROM harness_runs WHERE harness_id = ? ORDER BY created_at DESC LIMIT ?`).all(harnessId, Math.max(1, Math.min(50, Number.isInteger(limit) ? limit : 3))); } saveTriageItem(projectId, item) { const itemId = item.id || 'tr_' + Date.now() + '_' + Math.random().toString(36).substring(2, 7); const stmt = this.db.prepare(` INSERT INTO triage_items (id, project_id, run_id, source_type, error_message, ai_analysis, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET error_message = excluded.error_message, ai_analysis = excluded.ai_analysis, status = excluded.status, updated_at = excluded.updated_at `); const now = new Date().toISOString(); stmt.run( itemId, projectId, item.run_id, item.source_type, item.error_message || '', item.ai_analysis || '', item.status || 'pending', item.created_at || now, now ); return { id: itemId, project_id: projectId, ...item }; } getTriageItems(projectId) { return this.db.prepare(`SELECT * FROM triage_items WHERE project_id = ? ORDER BY created_at DESC`).all(projectId); } resolveTriageItem(itemId) { const stmt = this.db.prepare(`UPDATE triage_items SET status = 'resolved', updated_at = ? WHERE id = ?`); const info = stmt.run(new Date().toISOString(), itemId); return info.changes > 0; } saveWorkflowProvenance(provenance) { const parentNodeIdsStr = typeof provenance.parent_node_ids === 'string' ? provenance.parent_node_ids : JSON.stringify(provenance.parent_node_ids || []); const inputFlowFileStr = typeof provenance.input_flow_file === 'string' ? provenance.input_flow_file : JSON.stringify(provenance.input_flow_file || {}); const outputFlowFileStr = provenance.output_flow_file ? (typeof provenance.output_flow_file === 'string' ? provenance.output_flow_file : JSON.stringify(provenance.output_flow_file)) : null; const stmt = this.db.prepare(` INSERT INTO workflow_provenance (id, run_id, node_id, parent_node_ids, input_flow_file, output_flow_file, status, started_at, ended_at, retry_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET output_flow_file = excluded.output_flow_file, status = excluded.status, ended_at = excluded.ended_at, retry_count = excluded.retry_count `); stmt.run( provenance.id, provenance.run_id, provenance.node_id, parentNodeIdsStr, inputFlowFileStr, outputFlowFileStr, provenance.status, provenance.started_at || new Date().toISOString(), provenance.ended_at || null, provenance.retry_count ?? 0 ); } getWorkflowProvenances(runId) { const rows = this.db.prepare(`SELECT * FROM workflow_provenance WHERE run_id = ? ORDER BY started_at ASC`).all(runId); return rows.map(r => ({ ...r, parent_node_ids: this._safeParse(r.parent_node_ids), input_flow_file: this._safeParse(r.input_flow_file), output_flow_file: r.output_flow_file ? this._safeParse(r.output_flow_file) : null })); } getWorkflowProvenance(runId, nodeId) { const r = this.db.prepare(`SELECT * FROM workflow_provenance WHERE run_id = ? AND node_id = ? ORDER BY started_at DESC LIMIT 1`).get(runId, nodeId); if (!r) return null; return { ...r, parent_node_ids: this._safeParse(r.parent_node_ids), input_flow_file: this._safeParse(r.input_flow_file), output_flow_file: r.output_flow_file ? this._safeParse(r.output_flow_file) : null }; } ensureProjectDbAttached(projectId) { if (!projectId) return 'main'; const projectHash = crypto.createHash('md5').update(projectId).digest('hex').substring(0, 16); const dbAlias = `code_graph_${projectHash}`; if (this.attachedDbs.has(dbAlias)) { return dbAlias; } try { const databaseList = this.db.pragma('database_list'); const isAttached = databaseList.some(d => d.name === dbAlias); const CLAUDE_DIR = path.join(require('os').homedir(), '.claude'); if (!fs.existsSync(CLAUDE_DIR)) { fs.mkdirSync(CLAUDE_DIR, { recursive: true }); } const dbPath = path.join(CLAUDE_DIR, `${dbAlias}.db`); if (!isAttached) { this.db.prepare(`ATTACH DATABASE ? AS ${dbAlias}`).run(dbPath); } this.db.prepare(` CREATE TABLE IF NOT EXISTS ${dbAlias}.code_symbols ( id TEXT NOT NULL, project_id TEXT NOT NULL, symbol_type TEXT NOT NULL, name TEXT NOT NULL, file_path TEXT NOT NULL, start_line INTEGER, end_line INTEGER, signature TEXT, doc_comment TEXT, commit_hash TEXT, last_modified_commit TEXT, properties TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id, project_id) ) `).run(); this.db.prepare(` CREATE TABLE IF NOT EXISTS ${dbAlias}.code_relations ( id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, source_symbol_id TEXT NOT NULL, target_symbol_id TEXT NOT NULL, relation_type TEXT NOT NULL, weight REAL DEFAULT 1.0, properties TEXT, UNIQUE(project_id, source_symbol_id, target_symbol_id, relation_type) ) `).run(); this.db.prepare(` CREATE TABLE IF NOT EXISTS ${dbAlias}.code_change_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, commit_hash TEXT NOT NULL, commit_message TEXT, commit_author TEXT, commit_timestamp DATETIME, changed_symbols TEXT, diff_summary TEXT, snapshot_json TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS ${dbAlias}.idx_cs_proj ON code_symbols (project_id)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS ${dbAlias}.idx_cs_file ON code_symbols (file_path)`).run(); this.db.prepare(`CREATE INDEX IF NOT EXISTS ${dbAlias}.idx_cr_proj ON code_relations (project_id)`).run(); this.attachedDbs.add(dbAlias); } catch (e) { console.error(`[SqliteDb] ATTACH DATABASE failed for ${projectId}:`, e.message); try { this.db.prepare(` CREATE TABLE IF NOT EXISTS code_symbols ( id TEXT NOT NULL, project_id TEXT NOT NULL, symbol_type TEXT NOT NULL, name TEXT NOT NULL, file_path TEXT NOT NULL, start_line INTEGER, end_line INTEGER, signature TEXT, doc_comment TEXT, commit_hash TEXT, last_modified_commit TEXT, properties TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id, project_id) ) `).run(); this.db.prepare(` CREATE TABLE IF NOT EXISTS code_relations ( id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, source_symbol_id TEXT NOT NULL, target_symbol_id TEXT NOT NULL, relation_type TEXT NOT NULL, weight REAL DEFAULT 1.0, properties TEXT, UNIQUE(project_id, source_symbol_id, target_symbol_id, relation_type) ) `).run(); this.db.prepare(` CREATE TABLE IF NOT EXISTS code_change_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, commit_hash TEXT NOT NULL, commit_message TEXT, commit_author TEXT, commit_timestamp DATETIME, changed_symbols TEXT, diff_summary TEXT, snapshot_json TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `).run(); return 'main'; } catch (innerError) { console.error(`[SqliteDb] Fallback creation failed:`, innerError.message); } } return dbAlias; } saveCodeSymbol(projectId, symbol) { const dbAlias = this.ensureProjectDbAttached(projectId); const propertiesStr = typeof symbol.properties === 'string' ? symbol.properties : JSON.stringify(symbol.properties || {}); const stmt = this.db.prepare(` INSERT INTO ${dbAlias}.code_symbols (id, project_id, symbol_type, name, file_path, start_line, end_line, signature, doc_comment, commit_hash, last_modified_commit, properties, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id, project_id) DO UPDATE SET symbol_type = excluded.symbol_type, name = excluded.name, file_path = excluded.file_path, start_line = excluded.start_line, end_line = excluded.end_line, signature = excluded.signature, doc_comment = excluded.doc_comment, last_modified_commit = excluded.last_modified_commit, properties = excluded.properties, updated_at = excluded.updated_at `); stmt.run( symbol.id, projectId, symbol.symbol_type, symbol.name, symbol.file_path, symbol.start_line || null, symbol.end_line || null, symbol.signature || null, symbol.doc_comment || null, symbol.commit_hash || null, symbol.last_modified_commit || null, propertiesStr, new Date().toISOString() ); } searchCodeSymbols(projectId, query) { const dbAlias = this.ensureProjectDbAttached(projectId); const sqlLike = `%${query}%`; const rows = this.db.prepare(` SELECT * FROM ${dbAlias}.code_symbols WHERE project_id = ? AND (name LIKE ? OR file_path LIKE ?) `).all(projectId, sqlLike, sqlLike); return rows.map(r => ({ ...r, properties: this._safeParse(r.properties) })); } getCodeRelations(projectId, symbolId) { const dbAlias = this.ensureProjectDbAttached(projectId); const rows = this.db.prepare(` SELECT * FROM ${dbAlias}.code_relations WHERE project_id = ? AND (source_symbol_id = ? OR target_symbol_id = ?) `).all(projectId, symbolId, symbolId); return rows.map(r => ({ ...r, properties: this._safeParse(r.properties) })); } // 프로젝트의 모든 코드 관계 조회 (내보내기/익스포트용) getAllCodeRelations(projectId) { const dbAlias = this.ensureProjectDbAttached(projectId); const rows = this.db.prepare(` SELECT * FROM ${dbAlias}.code_relations WHERE project_id = ? `).all(projectId); return rows.map(r => ({ ...r, properties: this._safeParse(r.properties) })); } // 프로젝트의 인덱싱된 코드 데이터(심볼/관계/변경이력) 전체 삭제 (프로젝트 삭제용) deleteCodeProjectData(projectId) { const dbAlias = this.ensureProjectDbAttached(projectId); this.db.prepare(`DELETE FROM ${dbAlias}.code_symbols WHERE project_id = ?`).run(projectId); this.db.prepare(`DELETE FROM ${dbAlias}.code_relations WHERE project_id = ?`).run(projectId); this.db.prepare(`DELETE FROM ${dbAlias}.code_change_history WHERE project_id = ?`).run(projectId); } saveCodeRelation(projectId, relation) { const dbAlias = this.ensureProjectDbAttached(projectId); const propertiesStr = typeof relation.properties === 'string' ? relation.properties : JSON.stringify(relation.properties || {}); const stmt = this.db.prepare(` INSERT INTO ${dbAlias}.code_relations (project_id, source_symbol_id, target_symbol_id, relation_type, weight, properties) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, source_symbol_id, target_symbol_id, relation_type) DO UPDATE SET weight = excluded.weight, properties = excluded.properties `); stmt.run( projectId, relation.source_symbol_id, relation.target_symbol_id, relation.relation_type, relation.weight ?? 1.0, propertiesStr ); } saveChangeHistory(projectId, entry) { const dbAlias = this.ensureProjectDbAttached(projectId); const changedSymbolsStr = typeof entry.changed_symbols === 'string' ? entry.changed_symbols : JSON.stringify(entry.changed_symbols || []); const diffSummaryStr = typeof entry.diff_summary === 'string' ? entry.diff_summary : JSON.stringify(entry.diff_summary || {}); const stmt = this.db.prepare(` INSERT INTO ${dbAlias}.code_change_history (project_id, commit_hash, commit_message, commit_author, commit_timestamp, changed_symbols, diff_summary, snapshot_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?) `); stmt.run( projectId, entry.commit_hash, entry.commit_message || null, entry.commit_author || null, entry.commit_timestamp || null, changedSymbolsStr, diffSummaryStr, entry.snapshot_json || null ); } getChangeHistory(projectId, symbol) { const dbAlias = this.ensureProjectDbAttached(projectId); let rows; if (symbol) { const match = `%${symbol}%`; rows = this.db.prepare(` SELECT * FROM ${dbAlias}.code_change_history WHERE project_id = ? AND (changed_symbols LIKE ? OR commit_message LIKE ?) ORDER BY created_at DESC `).all(projectId, match, match); } else { rows = this.db.prepare(` SELECT * FROM ${dbAlias}.code_change_history WHERE project_id = ? ORDER BY created_at DESC `).all(projectId); } return rows.map(r => ({ ...r, changed_symbols: this._safeParse(r.changed_symbols), diff_summary: this._safeParse(r.diff_summary) })); } saveTroubleshoot(projectId, entry) { const affectedFilesStr = typeof entry.affected_files === 'string' ? entry.affected_files : JSON.stringify(entry.affected_files || []); const tagsStr = typeof entry.tags === 'string' ? entry.tags : JSON.stringify(entry.tags || []); const entryId = entry.id || 'err_' + Date.now() + '_' + Math.random().toString(36).substring(2, 7); const stmt = this.db.prepare(` INSERT INTO troubleshoot_entries (id, project_id, error_pattern, error_type, root_cause, solution, affected_files, tags, hit_count, last_hit_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET project_id = excluded.project_id, error_pattern = excluded.error_pattern, error_type = excluded.error_type, root_cause = excluded.root_cause, solution = excluded.solution, affected_files = excluded.affected_files, tags = excluded.tags, hit_count = troubleshoot_entries.hit_count + 1, last_hit_at = excluded.last_hit_at `); stmt.run( entryId, projectId, entry.error_pattern, entry.error_type || null, entry.root_cause || '', entry.solution, affectedFilesStr, tagsStr, entry.hit_count ?? 1, entry.last_hit_at || new Date().toISOString() ); return { id: entryId, ...entry }; } searchTroubleshoot(projectId, errorPattern) { const sqlLike = `%${errorPattern}%`; const rows = this.db.prepare(` SELECT * FROM troubleshoot_entries WHERE project_id = ? AND (error_pattern LIKE ? OR root_cause LIKE ? OR solution LIKE ?) ORDER BY hit_count DESC `).all(projectId, sqlLike, sqlLike, sqlLike); return rows.map(r => ({ ...r, affected_files: this._safeParse(r.affected_files), tags: this._safeParse(r.tags) })); } incrementTroubleshootHit(entryId) { this.db.prepare(` UPDATE troubleshoot_entries SET hit_count = hit_count + 1, last_hit_at = ? WHERE id = ? `).run(new Date().toISOString(), entryId); } saveDevPreference(projectId, pref) { const entryId = pref.id || 'pref_' + Date.now() + '_' + Math.random().toString(36).substring(2, 7); const stmt = this.db.prepare(` INSERT INTO dev_preferences (id, project_id, category, preference_key, preference_value, confidence, source, occurrence_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, category, preference_key) DO UPDATE SET preference_value = excluded.preference_value, confidence = excluded.confidence, source = excluded.source, occurrence_count = dev_preferences.occurrence_count + 1, updated_at = CURRENT_TIMESTAMP `); stmt.run( entryId, projectId, pref.category, pref.preference_key, pref.preference_value, pref.confidence ?? 0.5, pref.source || 'auto_inferred', pref.occurrence_count ?? 1 ); } getDevPreferences(projectId, category) { let rows; if (category) { rows = this.db.prepare(`SELECT * FROM dev_preferences WHERE project_id = ? AND category = ?`).all(projectId, category); } else { rows = this.db.prepare(`SELECT * FROM dev_preferences WHERE project_id = ?`).all(projectId); } return rows; } // 개발 선호도 항목 삭제 (코드 인텔 프로젝트 등록 해제 등에서 사용) deleteDevPreference(projectId, category, preferenceKey) { this.db.prepare(` DELETE FROM dev_preferences WHERE project_id = ? AND category = ? AND preference_key = ? `).run(projectId, category, preferenceKey); } saveFavoritePrompt(prompt) { if (!prompt || typeof prompt !== 'object') { console.error('[SqliteDb] saveFavoritePrompt: 올바르지 않은 프롬프트 데이터 구조입니다.'); return { success: false, error: '유효한 프롬프트 객체가 필요합니다.' }; } if (!prompt.id || !prompt.title || !prompt.prompt_text) { console.error('[SqliteDb] saveFavoritePrompt: 필수 필드가 누락되었습니다.', prompt); return { success: false, error: 'ID, 제목, 프롬프트 내용은 필수 입력 항목입니다.' }; } try { const stmt = this.db.prepare(` INSERT INTO favorite_prompts (id, title, prompt_text, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET title = excluded.title, prompt_text = excluded.prompt_text `); stmt.run(prompt.id, prompt.title, prompt.prompt_text, new Date().toISOString()); return { success: true }; } catch (error) { console.error('[SqliteDb] saveFavoritePrompt 실행 오류:', error.message); throw new Error(`데이터베이스 저장 실패: ${error.message}`, { cause: error }); } } getFavoritePrompts() { try { const rows = this.db.prepare(`SELECT * FROM favorite_prompts ORDER BY created_at DESC`).all(); return rows; } catch (error) { console.error('[SqliteDb] getFavoritePrompts 조회 오류:', error.message); throw new Error(`데이터베이스 조회 실패: ${error.message}`, { cause: error }); } } deleteFavoritePrompt(id) { if (!id || typeof id !== 'string') { console.error('[SqliteDb] deleteFavoritePrompt: 유효하지 않은 ID입니다.', id); return { success: false, error: '유효한 ID가 필요합니다.' }; } try { const stmt = this.db.prepare(`DELETE FROM favorite_prompts WHERE id = ?`); stmt.run(id); return { success: true }; } catch (error) { console.error('[SqliteDb] deleteFavoritePrompt 삭제 오류:', error.message); throw new Error(`데이터베이스 삭제 실패: ${error.message}`, { cause: error }); } } // ─── Loop Engineering CRUD Helper Methods ─── getLoopGoals(projectId) { try { return this.db.prepare(`SELECT * FROM loop_goals WHERE project_id = ? ORDER BY created_at DESC`).all(projectId); } catch (error) { console.error('[SqliteDb] getLoopGoals 조회 오류:', error.message); throw error; } } saveLoopGoal(projectId, goal) { try { const goalExpressionStr = typeof goal.goal_expression === 'string' ? goal.goal_expression : JSON.stringify(goal.goal_expression || {}); const stmt = this.db.prepare(` INSERT INTO loop_goals ( id, project_id, task_id, workflow_id, name, goal_expression, max_iterations, token_budget, max_wall_time, consecutive_failure_threshold, worktree_isolation ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, goal_expression = excluded.goal_expression, max_iterations = excluded.max_iterations, token_budget = excluded.token_budget, max_wall_time = excluded.max_wall_time, consecutive_failure_threshold = excluded.consecutive_failure_threshold, worktree_isolation = excluded.worktree_isolation, task_id = excluded.task_id, workflow_id = excluded.workflow_id, updated_at = CURRENT_TIMESTAMP WHERE loop_goals.project_id = excluded.project_id `); // 소유권 비교와 갱신을 같은 SQL 문으로 처리해 조회/쓰기 사이 경합을 피한다. // 설명 문서: docs/specs/loop-project-ownership.md (v1.0.0) const result = stmt.run( goal.id, projectId, goal.task_id || null, goal.workflow_id || null, goal.name, goalExpressionStr, goal.max_iterations ?? 10, goal.token_budget ?? 5.0, goal.max_wall_time ?? 3600, goal.consecutive_failure_threshold ?? 3, goal.worktree_isolation ?? 0 ); if (result.changes === 0) throw new Error('Loop goal ID belongs to another project'); } catch (error) { console.error('[SqliteDb] saveLoopGoal 저장 오류:', error.message); throw error; } } deleteLoopGoal(goalId) { try { this.db.prepare(`DELETE FROM loop_goals WHERE id = ?`).run(goalId); } catch (error) { console.error('[SqliteDb] deleteLoopGoal 삭제 오류:', error.message); throw error; } } // ─── Loop Templates CRUD (프로젝트 비종속 재사용 템플릿) ─── getLoopTemplates() { try { // WHY: project_id가 없는 전역 카탈로그이므로 필터 없이 최신순 전체 반환. return this.db.prepare(`SELECT * FROM loop_templates ORDER BY created_at DESC`).all(); } catch (error) { console.error('[SqliteDb] getLoopTemplates 조회 오류:', error.message); throw error; } } saveLoopTemplate(template) { try { const goalExpressionStr = typeof template.goal_expression === 'string' ? template.goal_expression : JSON.stringify(template.goal_expression || {}); const stepsJsonStr = typeof template.steps_json === 'string' ? template.steps_json : JSON.stringify(template.steps_json || []); const stmt = this.db.prepare(` INSERT INTO loop_templates ( id, name, description, goal_expression, max_iterations, token_budget, max_wall_time, consecutive_failure_threshold, worktree_isolation, steps_json, source_project_name, source_task_name ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, description = excluded.description, goal_expression = excluded.goal_expression, max_iterations = excluded.max_iterations, token_budget = excluded.token_budget, max_wall_time = excluded.max_wall_time, consecutive_failure_threshold = excluded.consecutive_failure_threshold, worktree_isolation = excluded.worktree_isolation, steps_json = excluded.steps_json, source_project_name = excluded.source_project_name, source_task_name = excluded.source_task_name `); stmt.run( template.id, template.name, template.description || null, goalExpressionStr, template.max_iterations ?? 10, template.token_budget ?? 5.0, template.max_wall_time ?? 3600, template.consecutive_failure_threshold ?? 3, template.worktree_isolation ?? 0, stepsJsonStr, template.source_project_name || null, template.source_task_name || null ); } catch (error) { console.error('[SqliteDb] saveLoopTemplate 저장 오류:', error.message); throw error; } } deleteLoopTemplate(templateId) { try { this.db.prepare(`DELETE FROM loop_templates WHERE id = ?`).run(templateId); } catch (error) { console.error('[SqliteDb] deleteLoopTemplate 삭제 오류:', error.message); throw error; } } getLoopRun(runId) { try { return this.db.prepare(`SELECT * FROM loop_runs WHERE run_id = ?`).get(runId) || null; } catch (error) { console.error('[SqliteDb] getLoopRun 조회 오류:', error.message); throw error; } } getLoopRuns(goalId) { try { return this.db.prepare(`SELECT * FROM loop_runs WHERE goal_id = ? ORDER BY started_at DESC`).all(goalId); } catch (error) { console.error('[SqliteDb] getLoopRuns 조회 오류:', error.message); throw error; } } // 원본은 승인 grant에 보존한다. docs/specs/batch-loop-ghost.md v1.0.0 removeBatchLoopGhost(runId,grantId,verify) { if(!this.db.inTransaction)require('../services/batch-loop-ghost').fail();return this.db.transaction(()=>{const id=require('./batch-loop-ghost-record').verifyRemoval(this,runId,grantId,verify);if(this.db.prepare('DELETE FROM loop_iterations WHERE id=? AND loop_run_id=?').run(id,'looprun-'+runId).changes!==1)require('../services/batch-loop-ghost').fail();return id;})(); } getLoopIterations(loopRunId) { try { return this.db.prepare(`SELECT * FROM loop_iterations WHERE loop_run_id = ? ORDER BY iteration_number ASC`).all(loopRunId); } catch (error) { console.error('[SqliteDb] getLoopIterations 조회 오류:', error.message); throw error; } } getRecentLoopLearnings(projectId, limit = 5) { try { return this.db.prepare(` SELECT r.run_id, g.name as goal_name, r.status, r.total_iterations, r.total_cost, r.goal_met, r.break_reason, r.completed_at, (SELECT error_message FROM loop_iterations WHERE loop_run_id = r.run_id AND error_message IS NOT NULL AND error_message != '' ORDER BY iteration_number DESC LIMIT 1) as last_error FROM loop_runs r JOIN loop_goals g ON r.goal_id = g.id WHERE g.project_id = ? AND r.status IN ('completed', 'circuit_broken') ORDER BY r.completed_at DESC LIMIT ? `).all(projectId, limit); } catch (error) { console.error('[SqliteDb] getRecentLoopLearnings 조회 오류:', error.message); return []; } } saveLoopRun(run, options = {}) { try { const stmt = this.db.prepare(` INSERT INTO loop_runs ( run_id, goal_id, parent_run_id, status, total_iterations, total_tokens_used, total_cost, goal_met, break_reason, receipt_summary, started_at, completed_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(run_id) DO UPDATE SET status = excluded.status, total_iterations = excluded.total_iterations, total_tokens_used = excluded.total_tokens_used, total_cost = excluded.total_cost, goal_met = excluded.goal_met, break_reason = excluded.break_reason, receipt_summary = ${options.replaceReceipt === true ? 'excluded.receipt_summary' : 'COALESCE(excluded.receipt_summary, loop_runs.receipt_summary)'}, completed_at = excluded.completed_at `); stmt.run( run.run_id, run.goal_id, run.parent_run_id || null, run.status, run.total_iterations ?? 0, run.total_tokens_used ?? 0, run.total_cost ?? 0.0, run.goal_met ?? 0, run.break_reason || null, run.receipt_summary || null, run.started_at || new Date().toISOString(), run.completed_at || null ); } catch (error) { console.error('[SqliteDb] saveLoopRun 저장 오류:', error.message); throw error; } } saveLoopIteration(iter) { try { const stepOutputsStr = typeof iter.step_outputs === 'string' ? iter.step_outputs : JSON.stringify(iter.step_outputs || {}); const stmt = this.db.prepare(` INSERT INTO loop_iterations ( id, loop_run_id, iteration_number, status, step_outputs, goal_evaluation_result, tokens_used, cost, worktree_branch, error_message, started_at, completed_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET status = excluded.status, step_outputs = excluded.step_outputs, goal_evaluation_result = excluded.goal_evaluation_result, tokens_used = excluded.tokens_used, cost = excluded.cost, worktree_branch = excluded.worktree_branch, error_message = excluded.error_message, completed_at = excluded.completed_at `); stmt.run( iter.id, iter.loop_run_id, iter.iteration_number, iter.status, stepOutputsStr, iter.goal_evaluation_result ?? 0, iter.tokens_used ?? 0, iter.cost ?? 0.0, iter.worktree_branch || null, iter.error_message || null, iter.started_at || new Date().toISOString(), iter.completed_at || null ); } catch (error) { console.error('[SqliteDb] saveLoopIteration 저장 오류:', error.message); throw error; } } saveLoopMessage(msg) { try { const stmt = this.db.prepare(` INSERT INTO loop_messages ( loop_run_id, iteration_number, sender_agent_id, receiver_agent_id, message_type, content, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?) `); stmt.run( msg.loop_run_id, msg.iteration_number || null, msg.sender_agent_id, msg.receiver_agent_id, msg.message_type, msg.content, msg.created_at || new Date().toISOString() ); } catch (error) { console.error('[SqliteDb] saveLoopMessage 저장 오류:', error.message); throw error; } } getLoopMessages(loopRunId) { try { return this.db.prepare(`SELECT * FROM loop_messages WHERE loop_run_id = ? ORDER BY created_at ASC`).all(loopRunId); } catch (error) { console.error('[SqliteDb] getLoopMessages 조회 오류:', error.message); throw error; } } saveWorktreeState(wtState) { try { const stmt = this.db.prepare(` INSERT OR REPLACE INTO worktree_state (id, run_id, node_id, wt_path, branch_name, status, created_at, completed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) `); stmt.run( wtState.id, wtState.run_id, wtState.node_id, wtState.wt_path, wtState.branch_name, wtState.status, wtState.created_at || new Date().toISOString(), wtState.completed_at || null ); return true; } catch(e) { console.error('[SqliteDb] saveWorktreeState 저장 오류:', e.message); throw e; } } updateWorktreeStatus(id, status, completedAt) { try { const stmt = this.db.prepare(` UPDATE worktree_state SET status = ?, completed_at = ? WHERE id = ? `); stmt.run(status, completedAt || new Date().toISOString(), id); return true; } catch(e) { console.error('[SqliteDb] updateWorktreeStatus 수정 오류:', e.message); throw e; } } getWorktreesByRunId(runId) { try { const stmt = this.db.prepare(`SELECT * FROM worktree_state WHERE run_id = ?`); return stmt.all(runId); } catch(e) { console.error('[SqliteDb] getWorktreesByRunId 조회 오류:', e.message); throw e; } } // ─── Swarm Blackboard Methods (SPEC-INNOV-001) ─── saveBlackboardEntry(entry) { try { const now = Date.now(); const payloadStr = typeof entry.payload === 'string' ? entry.payload : JSON.stringify(entry.payload || {}); const stmt = this.db.prepare(` INSERT INTO blackboard_entries ( entry_id, project_id, topic, author_agent, payload, salience, claimed_by, claimed_until, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(entry_id) DO UPDATE SET payload = excluded.payload, salience = excluded.salience, claimed_by = excluded.claimed_by, claimed_until = excluded.claimed_until, updated_at = excluded.updated_at `); stmt.run( entry.entry_id, entry.project_id || 'default', entry.topic, entry.author_agent, payloadStr, entry.salience ?? 0.5, entry.claimed_by || null, entry.claimed_until || null, entry.created_at || now, now ); return entry; } catch (e) { console.error('[SqliteDb] saveBlackboardEntry 오류:', e.message); throw e; } } getBlackboardEntry(entryId) { try { const row = this.db.prepare(`SELECT * FROM blackboard_entries WHERE entry_id = ?`).get(entryId); if (!row) return null; return { ...row, payload: this._safeParse(row.payload) }; } catch (e) { console.error('[SqliteDb] getBlackboardEntry 오류:', e.message); throw e; } } listBlackboardEntries(topic, options = {}) { try { const projectId = options.projectId || 'default'; const limit = Math.min(options.limit || 50, 200); let query = `SELECT * FROM blackboard_entries WHERE project_id = ?`; const params = [projectId]; if (topic) { query += ` AND topic = ?`; params.push(topic); } query += ` ORDER BY created_at DESC LIMIT ?`; params.push(limit); const rows = this.db.prepare(query).all(...params); return rows.map(r => ({ ...r, payload: this._safeParse(r.payload) })); } catch (e) { console.error('[SqliteDb] listBlackboardEntries 오류:', e.message); throw e; } } claimBlackboardTask(entryId, agentId, ttlMs = 60000) { try { const now = Date.now(); const claimedUntil = now + ttlMs; // 원자적 선점: 미선점 상태이거나 TTL이 만료된 경우에만 UPDATE const stmt = this.db.prepare(` UPDATE blackboard_entries SET claimed_by = ?, claimed_until = ?, updated_at = ? WHERE entry_id = ? AND (claimed_by IS NULL OR claimed_until < ? OR claimed_by = ?) `); const res = stmt.run(agentId, claimedUntil, now, entryId, now, agentId); return res.changes > 0; } catch (e) { console.error('[SqliteDb] claimBlackboardTask 오류:', e.message); throw e; } } releaseBlackboardTask(entryId, agentId, resultPayload = null) { try { const now = Date.now(); // Zombie Writer 방지: 본인이 여전히 Claimer인 경우에만 해제/업데이트 let query = `UPDATE blackboard_entries SET claimed_by = NULL, claimed_until = NULL, updated_at = ?`; const params = [now]; if (resultPayload !== null) { const payloadStr = typeof resultPayload === 'string' ? resultPayload : JSON.stringify(resultPayload); query += `, payload = ?`; params.push(payloadStr); } // 시간 조건을 UPDATE에 포함해 조회와 기록 사이의 만료 경합을 제거한다. query += ` WHERE entry_id = ? AND claimed_by = ? AND claimed_until >= ?`; params.push(entryId, agentId, now); const res = this.db.prepare(query).run(...params); return res.changes > 0; } catch (e) { console.error('[SqliteDb] releaseBlackboardTask 오류:', e.message); throw e; } } deleteBlackboardEntry(entryId) { try { return this.db.prepare(`DELETE FROM blackboard_entries WHERE entry_id = ?`).run(entryId).changes > 0; } catch (e) { console.error('[SqliteDb] deleteBlackboardEntry 오류:', e.message); throw e; } } _safeParse(str) { try { return JSON.parse(str || '{}'); } catch(e) { if (str && str !== '{}') { console.warn('[KnowledgeDB] _safeParse failed to parse JSON string:', str, e.message); } return {}; } } } module.exports = SqliteDb;
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
function filterAndCapGraphData(nodes, edges, safeParse) {
const MAX_NODES = 5000;
const MAX_EDGES = 10000;
let finalNodes = nodes;
if (finalNodes.length > MAX_NODES) {
const typePriority = { 'session': 0, 'wiki': 1, 'note': 1, 'tool': 2, 'file': 3, 'code': 4, 'library': 5 };
finalNodes.sort((a, b) => {
const priA = typePriority[a.type] !== undefined ? typePriority[a.type] : 6;
const priB = typePriority[b.type] !== undefined ? typePriority[b.type] : 6;
return priA - priB;
});
finalNodes = finalNodes.slice(0, MAX_NODES);
}
const nodeIds = new Set(finalNodes.map(n => n.id));
let finalEdges = edges.filter(e => nodeIds.has(e.source) && nodeIds.has(e.target));
if (finalEdges.length > MAX_EDGES) {
finalEdges = finalEdges.slice(0, MAX_EDGES);
}
return {
nodes: finalNodes.map(n => ({ ...n, properties: safeParse(n.properties) })),
edges: finalEdges.map(e => ({ ...e, properties: safeParse(e.properties) }))
};
}
class SqliteDb {
constructor(db) {
this.db = db;
this.attachedDbs = new Set();
this.initTables();
}
getDecisionGate(id) { return require('./decision-gate-record').decode(this.db.prepare('SELECT gate_json FROM decision_gates WHERE id = ?').get(id)?.gate_json); }
// docs/specs/bong-ui-artifacts.md v1.0.0. snapshot과 할당량을 같은 SQLite 트랜잭션에 고정한다.
getUiArtifact(projectId,id){const r=require('./ui-artifact-record');r.query(projectId,id);return r.read(this.db.prepare('SELECT data_json FROM ui_artifacts WHERE project_id=? AND id=?').get(projectId,id)?.data_json,projectId,id);}
listUiArtifacts(projectId){const r=require('./ui-artifact-record');r.query(projectId);return this.db.prepare('SELECT id,data_json FROM ui_artifacts WHERE project_id=? ORDER BY rowid DESC LIMIT 33').all(projectId).map(v=>r.read(v.data_json,projectId,v.id));}
saveUiArtifact(projectId,value){return this.db.transaction(()=>{const r=require('./ui-artifact-record'),next=r.read(value,projectId,value.id),old=this.getUiArtifact(projectId,next.id);if(old){if(old.hash!==next.hash)r.fail();return old;}r.quota(this.listUiArtifacts(projectId),next);this.db.prepare('INSERT INTO ui_artifacts(project_id,id,data_json) VALUES (?,?,?)').run(projectId,next.id,JSON.stringify(next));return next;})();}
deleteUiArtifact(projectId,id,hash){return this.db.transaction(()=>{const old=this.getUiArtifact(projectId,id);if(!old||old.hash!==hash)require('./ui-artifact-record').fail();this.db.prepare('DELETE FROM ui_artifacts WHERE project_id=? AND id=?').run(projectId,id);})();}
listDecisionGates() { return this.db.prepare('SELECT gate_json FROM decision_gates ORDER BY rowid DESC LIMIT 100').all().map(row => require('./decision-gate-record').decode(row.gate_json)); }
saveDecisionGate(gate, expectedRevision = null) {
return this.db.transaction(() => {
const records = require('./decision-gate-record');
const next = records.prepare(gate, this.getDecisionGate(gate.id), expectedRevision);
if (expectedRevision === null) this.db.prepare('INSERT INTO decision_gates (id, revision, gate_json) VALUES (?, ?, ?)').run(next.id, next.revision, JSON.stringify(next));
else if (this.db.prepare('UPDATE decision_gates SET revision = ?, gate_json = ? WHERE id = ? AND revision = ?').run(next.revision, JSON.stringify(next), next.id, expectedRevision).changes !== 1) throw records.conflict();
return next;
})();
}
getRuntimeUsage(id) { return require('./runtime-usage-record').decode(this.db.prepare('SELECT data_json FROM runtime_usage WHERE run_id = ?').get(id)?.data_json); }
getBatchCheckpoint(id) { return require('./batch-checkpoint-record').decode(this.db.prepare('SELECT data_json FROM batch_checkpoints WHERE run_id=?').get(id)?.data_json); }
// 원래 checkpoint와 분리한 알림 journal: docs/specs/batch-publication-review.md v1.0.0
getBatchLoopPublicationActions(runId) { return require('./batch-publication-action-record').decode(this,runId,this.db.prepare('SELECT data_json FROM batch_publication_actions WHERE run_id=?').get(runId)?.data_json); }
appendBatchLoopPublicationAction(runId,value,expectedHash,verify) { return this.db.transaction(()=>{const next=require('./batch-publication-action-record').append(this,runId,value,this.getBatchLoopPublicationActions(runId),expectedHash,verify);this.db.prepare('INSERT INTO batch_publication_actions(run_id,data_json) VALUES (?,?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(runId,JSON.stringify(next));return next;})(); }
getBatchLoopObservations(runId,eventKey) { return require('./batch-loop-observation-record').decode(this,runId,eventKey,this.db.prepare('SELECT data_json FROM batch_loop_observations WHERE run_id=? AND event_key=?').get(runId,eventKey)?.data_json); }
hasBatchLoopObservations(runId) { if(typeof runId!=='string'||!/^[-\w]{1,256}$/.test(runId))throw Error('Invalid batch run ID');return !!this.db.prepare('SELECT 1 FROM batch_loop_observations WHERE run_id=? LIMIT 1').get(runId); }
appendBatchLoopObservation(runId,eventKey,value,expectedHash) { return this.db.transaction(()=>{const next=require('./batch-loop-observation-record').append(this,runId,eventKey,value,this.getBatchLoopObservations(runId,eventKey),expectedHash);this.db.prepare('INSERT INTO batch_loop_observations(run_id,event_key,data_json) VALUES (?,?,?) ON CONFLICT(run_id,event_key) DO UPDATE SET data_json=excluded.data_json').run(runId,eventKey,JSON.stringify(next));return next;})(); }
saveBatchCheckpoint(record,revision=null,verify) { return this.db.transaction(()=>{const next=require('./batch-checkpoint-record').prepare(record,this.getBatchCheckpoint(record.runId),revision,verify);this.db.prepare('INSERT INTO batch_checkpoints (run_id,data_json) VALUES (?,?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(next.runId,JSON.stringify(next));return next;})(); }
transitionBatchRun(id,expected,status) { return this.db.transaction(()=>{const row=this.getBatchRun(id),hash=require('../services/bong-browser-resolution').hash;if(!['paused','running','aborted'].includes(status)||hash(row)!==hash(expected)||['running','aborted'].includes(status)&&row?.status!=='paused'||status==='paused'&&!['failed','aborted'].includes(row?.status))throw Error('Batch continuation row changed');const result=this.db.prepare('UPDATE batch_runs SET status=?,error_message=?,completed_at=? WHERE run_id=?').run(status,status==='aborted'?'사용자 복구 준비 철회':null,status==='aborted'?new Date().toISOString():null,id);if(result.changes!==1)throw Error('Batch continuation row missing');return this.getBatchRun(id);})(); }
getGoalProcedure(projectId,id){require('./goal-state-record').query(projectId,id);return require('./goal-procedure-record').read(this.db.prepare('SELECT data_json FROM goal_procedures WHERE project_id=? AND id=?').get(projectId,id)?.data_json,projectId,id);}
listGoalProcedures(projectId,limit=20){require('./goal-state-record').query(projectId);if(!Number.isSafeInteger(limit)||limit<1||limit>21)throw Error('Invalid procedure limit');return this.db.prepare('SELECT id,data_json FROM goal_procedures WHERE project_id=? ORDER BY rowid DESC LIMIT ?').all(projectId,limit).map(r=>require('./goal-procedure-record').read(r.data_json,projectId,r.id));}
saveGoalProcedure(projectId,id,value,revision,verify){return this.db.transaction(()=>{const r=require('./goal-procedure-record'),next=r.prepare(projectId,id,value,this.getGoalProcedure(projectId,id),revision,verify);if(revision===null){if(this.db.prepare('SELECT COUNT(*) AS count FROM goal_procedures WHERE project_id=?').get(projectId).count>=64)throw r.fail();this.db.prepare('INSERT INTO goal_procedures(project_id,id,data_json) VALUES (?,?,?)').run(projectId,id,JSON.stringify(next));}else this.db.prepare('UPDATE goal_procedures SET data_json=? WHERE project_id=? AND id=?').run(JSON.stringify(next),projectId,id);return next;})();}
getGoalState(projectId,id) { const r=require('./goal-state-record');r.query(projectId,id);return r.decode(this.db.prepare('SELECT data_json FROM goal_states WHERE project_id=? AND id=?').get(projectId,id)?.data_json); }
listGoalStates(projectId,limit=20) { const r=require('./goal-state-record');r.query(projectId);if(!Number.isSafeInteger(limit)||limit<1||limit>21)throw Error('Invalid goal limit');return this.db.prepare('SELECT data_json FROM goal_states WHERE project_id=? ORDER BY rowid DESC LIMIT ?').all(projectId,limit).map(row=>r.decode(row.data_json)); }
appendGoalEvent(projectId,id,event,expectedRevision) {
return this.db.transaction(()=>{const next=require('./goal-state-record').apply(this.getGoalState(projectId,id),projectId,id,event,expectedRevision);
this.db.prepare('INSERT INTO goal_states (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'goal',id,next.runId,id,next.revision,next);return next;
})();
}
saveRuntimeUsage(record) {
return this.db.transaction(()=>{const json = require('./runtime-usage-record').encode(record);
this.db.prepare('INSERT INTO runtime_usage (run_id, data_json) VALUES (?, ?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(record.runId, json);require('../services/goal-event-feed').usageChanged(this,record);})();
}
getGoalFulfillment(projectId,id) { require('./goal-state-record').query(projectId,id);return require('./goal-fulfillment-record').decode(this.db.prepare('SELECT data_json FROM goal_fulfillments WHERE project_id=? AND id=?').get(projectId,id)?.data_json); }
saveGoalFulfillment(projectId,id,input,revision) {
return this.db.transaction(()=>{const next=require('./goal-fulfillment-record').prepare(this,projectId,id,input,this.getGoalFulfillment(projectId,id),revision);
this.db.prepare('INSERT INTO goal_fulfillments (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'confirmation',id,next.confirmations.at(-1).runId,id,next.revision,next);return next;
})();
}
getHarnessRunsForWorkflow(projectId,harnessId,runId) { this.getHarnessRunsForProject(projectId,harnessId,1);return this.db.prepare('SELECT * FROM harness_runs WHERE harness_id=? AND workflow_run_id=? ORDER BY created_at DESC,rowid DESC LIMIT 1').all(harnessId,runId); }
getGoalFeed(projectId) { require('./goal-state-record').query(projectId);return require('./goal-feed-record').decode(this.db.prepare('SELECT data_json FROM goal_feeds WHERE project_id=?').get(projectId)?.data_json); }
appendGoalFeed(projectId,event) { return this.db.transaction(()=>{const next=require('./goal-feed-record').append(this.getGoalFeed(projectId),projectId,event);this.db.prepare('INSERT INTO goal_feeds (project_id,data_json) VALUES (?,?) ON CONFLICT(project_id) DO UPDATE SET data_json=excluded.data_json').run(projectId,JSON.stringify(next));return next;})(); }
getGoalPlanningCheckpoint(projectId,id) {
require('./goal-state-record').query(projectId,id);
return require('../services/goal-planning-checkpoint').decode(this.db.prepare('SELECT data_json FROM goal_planning_checkpoints WHERE project_id=? AND id=?').get(projectId,id)?.data_json);
}
saveGoalPlanningCheckpoint(projectId,id,value,revision) {
return this.db.transaction(()=>{const next=require('../services/goal-planning-checkpoint').prepare(projectId,id,value,this.getGoalPlanningCheckpoint(projectId,id),revision);
this.db.prepare('INSERT INTO goal_planning_checkpoints (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'preparation',id,null,id,next.revision,next);return next;
})();
}