import { createHash, randomUUID } from 'node:crypto'; const isoNow = () => new Date().toISOString(); const json = (value) => JSON.stringify(value ?? {}); const parseJson = (value, fallback = {}) => { try { return JSON.parse(value); } catch { return fallback; } }; const slugify = (value) => String(value ?? 'entry').toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'entry'; const checksum = (value) => createHash('sha256').update(value).digest('hex'); function transaction(db, operation) { db.exec('BEGIN IMMEDIATE'); try { const result = operation(); db.exec('COMMIT'); return result; } catch (error) { db.exec('ROLLBACK'); throw error; } } function projectFromRow(row) { if (!row) return null; return { id: row.project_id, name: row.name, description: row.description, stage: row.stage, state: parseJson(row.state_json), createdAt: row.created_at, updatedAt: row.updated_at, archivedAt: row.archived_at }; } export class ProjectRepository { constructor(db) { this.db = db; } create(project) { const id = project.id ?? project.projectId ?? randomUUID(); const now = isoNow(); this.db.prepare(`INSERT INTO projects(project_id, name, description, stage, state_json, created_at, updated_at, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) .run(id, project.name ?? id, project.description ?? '', project.stage ?? 'Research', json(project.state), project.createdAt ?? now, project.updatedAt ?? now, project.archivedAt ?? null); return this.get(id); } get(id) { return projectFromRow(this.db.prepare('SELECT * FROM projects WHERE project_id = ?').get(id)); } update(id, changes) { const current = this.get(id); if (!current) return null; const next = { ...current, ...changes, id, updatedAt: isoNow() }; this.db.prepare(`UPDATE projects SET name = ?, description = ?, stage = ?, state_json = ?, updated_at = ?, archived_at = ? WHERE project_id = ?`) .run(next.name, next.description, next.stage, json(next.state), next.updatedAt, next.archivedAt ?? null, id); return this.get(id); } } export class CanonRepository { constructor(db) { this.db = db; } create(entry) { const id = entry.id ?? entry.entryId ?? randomUUID(); const now = isoNow(); const title = entry.title ?? 'Untitled canon entry'; const body = entry.body ?? entry.content ?? ''; const version = entry.version ?? 1; const metadata = entry.metadata ?? {}; transaction(this.db, () => { this.db.prepare(`INSERT INTO canon_entries(entry_id, project_id, slug, title, body, entry_type, status, version, source_snapshot_id, supersedes_entry_id, metadata_json, valid_from, valid_until, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(id, entry.projectId ?? null, entry.slug ?? slugify(title), title, body, entry.entryType ?? 'knowledge', entry.status ?? 'active', version, entry.sourceSnapshotId ?? null, entry.supersedesEntryId ?? null, json(metadata), entry.validFrom ?? now, entry.validUntil ?? null, entry.createdAt ?? now, entry.updatedAt ?? now); this.db.prepare(`INSERT INTO canon_revisions(revision_id, entry_id, version, title, body, source_snapshot_id, change_summary, metadata_json, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(randomUUID(), id, version, title, body, entry.sourceSnapshotId ?? null, entry.changeSummary ?? 'Initial canon entry', json(metadata), now, entry.createdBy ?? null); }); return this.get(id); } get(id) { const row = this.db.prepare('SELECT * FROM canon_entries WHERE entry_id = ?').get(id); if (!row) return null; return { id: row.entry_id, projectId: row.project_id, slug: row.slug, title: row.title, body: row.body, entryType: row.entry_type, status: row.status, version: row.version, sourceSnapshotId: row.source_snapshot_id, metadata: parseJson(row.metadata_json), createdAt: row.created_at, updatedAt: row.updated_at }; } } export class FrontierRepository { constructor(db) { this.db = db; } create(item) { const id = item.id ?? item.frontierId ?? randomUUID(); const now = isoNow(); this.db.prepare(`INSERT INTO frontier_items(frontier_id, project_id, domain, item_type, title, description, rationale, status, confidence, impact, first_seen_at, last_reviewed_at, review_after, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(id, item.projectId ?? null, item.domain ?? 'general', item.itemType ?? 'research', item.title ?? 'Untitled hypothesis', item.description ?? '', item.rationale ?? '', item.status ?? 'candidate', item.confidence ?? null, item.impact ?? 'medium', item.firstSeenAt ?? now, item.lastReviewedAt ?? null, item.reviewAfter ?? null, json(item.metadata), item.createdAt ?? now, item.updatedAt ?? now); return this.get(id); } get(id) { const row = this.db.prepare('SELECT * FROM frontier_items WHERE frontier_id = ?').get(id); if (!row) return null; return { id: row.frontier_id, projectId: row.project_id, domain: row.domain, itemType: row.item_type, title: row.title, description: row.description, rationale: row.rationale, status: row.status, confidence: row.confidence, impact: row.impact, metadata: parseJson(row.metadata_json), createdAt: row.created_at, updatedAt: row.updated_at }; } promote(id, options = {}) { const now = isoNow(); const promote = () => { const item = this.db.prepare('SELECT * FROM frontier_items WHERE frontier_id = ?').get(id); if (!item) throw new Error(`Frontier item "${id}" does not exist.`); if (item.status === 'rejected' || item.status === 'obsolete') throw new Error(`Frontier item "${id}" cannot be promoted from ${item.status}.`); const metadata = { ...parseJson(item.metadata_json), promotedFromFrontier: id }; this.db.prepare(`INSERT INTO canon_entries(entry_id, project_id, slug, title, body, entry_type, status, version, source_snapshot_id, supersedes_entry_id, metadata_json, valid_from, valid_until, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'knowledge', 'active', 1, ?, NULL, ?, ?, NULL, ?, ?)`) .run(id, item.project_id, slugify(item.title), item.title, item.description || item.rationale, options.snapshotId ?? null, json(metadata), now, now, now); this.db.prepare(`INSERT INTO canon_revisions(revision_id, entry_id, version, title, body, source_snapshot_id, change_summary, metadata_json, created_at, created_by) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?)`) .run(randomUUID(), id, item.title, item.description || item.rationale, options.snapshotId ?? null, options.changeSummary ?? 'Promoted from frontier', json(metadata), now, options.createdBy ?? null); this.db.prepare("UPDATE frontier_items SET status = 'adopted', last_reviewed_at = ?, updated_at = ? WHERE frontier_id = ?") .run(now, now, id); if (item.project_id) { this.db.prepare('INSERT INTO project_events(event_id, project_id, event_type, payload_json, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?)') .run(randomUUID(), item.project_id, 'frontier.promoted', json({ frontierId: id, canonEntryId: id }), now, options.createdBy ?? null); } }; if (options.withinTransaction) promote(); else transaction(this.db, promote); return this.db.prepare('SELECT * FROM canon_entries WHERE entry_id = ?').get(id) ?? null; } } export class SnapshotRepository { constructor(db) { this.db = db; } create(projectOrId, options = {}) { const projectId = typeof projectOrId === 'string' ? projectOrId : projectOrId.id ?? projectOrId.projectId; const project = this.db.prepare('SELECT * FROM projects WHERE project_id = ?').get(projectId); if (!project) throw new Error(`Project "${projectId}" does not exist.`); const state = { project, events: this.db.prepare('SELECT * FROM project_events WHERE project_id = ? ORDER BY event_id').all(projectId), canonEntries: this.db.prepare('SELECT * FROM canon_entries WHERE project_id = ? ORDER BY entry_id').all(projectId), canonRevisions: this.db.prepare(`SELECT r.* FROM canon_revisions r INNER JOIN canon_entries c ON c.entry_id = r.entry_id WHERE c.project_id = ? ORDER BY r.entry_id, r.version`).all(projectId), frontierItems: this.db.prepare('SELECT * FROM frontier_items WHERE project_id = ? ORDER BY frontier_id').all(projectId), frontierObservations: this.db.prepare(`SELECT o.* FROM frontier_observations o INNER JOIN frontier_items f ON f.frontier_id = o.frontier_id WHERE f.project_id = ? ORDER BY o.observation_id`).all(projectId), archives: this.db.prepare('SELECT * FROM archive_records WHERE project_id = ? ORDER BY archive_id').all(projectId), embeddings: this.db.prepare(`SELECT * FROM knowledge_embeddings WHERE (entity_type = 'project' AND entity_id = ?) OR entity_id IN (SELECT entry_id FROM canon_entries WHERE project_id = ?) OR entity_id IN (SELECT frontier_id FROM frontier_items WHERE project_id = ?) ORDER BY embedding_id`).all(projectId, projectId, projectId), dependencyFindings: this.db.prepare('SELECT * FROM dependency_findings WHERE project_id = ? ORDER BY finding_id').all(projectId), deltaRuns: this.db.prepare('SELECT * FROM delta_runs WHERE project_id = ? ORDER BY delta_run_id').all(projectId), deltaGaps: this.db.prepare(`SELECT g.* FROM delta_gaps g INNER JOIN delta_runs r ON r.delta_run_id = g.delta_run_id WHERE r.project_id = ? ORDER BY g.gap_id`).all(projectId), deltaDependencies: this.db.prepare(`SELECT d.* FROM delta_dependencies d INNER JOIN delta_runs r ON r.delta_run_id = d.delta_run_id WHERE r.project_id = ? ORDER BY d.delta_dependency_id`).all(projectId), governanceReviews: this.db.prepare('SELECT * FROM governance_reviews WHERE project_id = ? ORDER BY review_id').all(projectId) }; const stateJson = JSON.stringify(state); const digest = checksum(stateJson); const snapshotId = options.id ?? randomUUID(); const createdAt = isoNow(); const items = [ ['project', project.project_id, state.project], ...state.events.map((row) => ['project_event', row.event_id, row]), ...state.canonEntries.map((row) => ['canon_entry', row.entry_id, row]), ...state.canonRevisions.map((row) => ['canon_revision', row.revision_id, row]), ...state.frontierItems.map((row) => ['frontier_item', row.frontier_id, row]), ...state.frontierObservations.map((row) => ['frontier_observation', row.observation_id, row]), ...state.archives.map((row) => ['archive_record', row.archive_id, row]), ...state.embeddings.map((row) => ['knowledge_embedding', row.embedding_id, row]), ...state.dependencyFindings.map((row) => ['dependency_finding', row.finding_id, row]), ...state.deltaRuns.map((row) => ['delta_run', row.delta_run_id, row]), ...state.deltaGaps.map((row) => ['delta_gap', row.gap_id, row]), ...state.deltaDependencies.map((row) => ['delta_dependency', row.delta_dependency_id, row]), ...state.governanceReviews.map((row) => ['governance_review', row.review_id, row]) ]; const persistSnapshot = () => { this.db.prepare(`INSERT INTO snapshots(snapshot_id, project_id, snapshot_type, label, source, schema_version, state_json, checksum, created_at, created_by, metadata_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(snapshotId, projectId, options.type ?? 'manual', options.label ?? `Snapshot ${createdAt}`, options.source ?? 'local', '1', stateJson, digest, createdAt, options.createdBy ?? null, json(options.metadata)); const addItem = this.db.prepare(`INSERT INTO snapshot_items(snapshot_item_id, snapshot_id, entity_type, entity_id, ordinal, payload_json, content_hash) VALUES (?, ?, ?, ?, ?, ?, ?)`); items.forEach(([type, entityId, payload], ordinal) => { const content = JSON.stringify(payload); addItem.run(randomUUID(), snapshotId, type, entityId, ordinal, content, checksum(content)); }); }; if (options.withinTransaction) persistSnapshot(); else transaction(this.db, persistSnapshot); return { id: snapshotId, snapshotId, projectId, checksum: digest, createdAt, itemCount: items.length }; } get(id) { const row = this.db.prepare('SELECT * FROM snapshots WHERE snapshot_id = ?').get(id); if (!row) return null; return { id: row.snapshot_id, snapshotId: row.snapshot_id, projectId: row.project_id, type: row.snapshot_type, label: row.label, checksum: row.checksum, createdAt: row.created_at, state: parseJson(row.state_json) }; } restore(id) { const snapshot = this.db.prepare('SELECT * FROM snapshots WHERE snapshot_id = ?').get(id); if (!snapshot) throw new Error(`Snapshot "${id}" does not exist.`); if (checksum(snapshot.state_json) !== snapshot.checksum) throw new Error(`Snapshot "${id}" failed checksum validation.`); const state = JSON.parse(snapshot.state_json); if (!state?.project || state.project.project_id !== snapshot.project_id) throw new Error(`Snapshot "${id}" does not contain a matching project record.`); for (const key of ['events', 'canonEntries', 'canonRevisions', 'frontierItems', 'frontierObservations', 'archives', 'embeddings', 'dependencyFindings', 'deltaRuns', 'deltaGaps', 'deltaDependencies', 'governanceReviews']) { state[key] ??= []; } const now = isoNow(); transaction(this.db, () => { const p = state.project; this.db.prepare(`INSERT INTO projects(project_id, name, description, stage, state_json, created_at, updated_at, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(project_id) DO UPDATE SET name=excluded.name, description=excluded.description, stage=excluded.stage, state_json=excluded.state_json, updated_at=excluded.updated_at, archived_at=excluded.archived_at`) .run(p.project_id, p.name, p.description, p.stage, p.state_json, p.created_at, now, p.archived_at); for (const row of state.canonEntries) { const current = this.db.prepare('SELECT * FROM canon_entries WHERE entry_id = ?').get(row.entry_id); if (!current) { this.db.prepare(`INSERT INTO canon_entries(entry_id, project_id, slug, title, body, entry_type, status, version, source_snapshot_id, supersedes_entry_id, metadata_json, valid_from, valid_until, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(row.entry_id, row.project_id, row.slug, row.title, row.body, row.entry_type, row.status, row.version, row.source_snapshot_id, row.supersedes_entry_id, row.metadata_json, row.valid_from, row.valid_until, row.created_at, now); } else { const nextVersion = Math.max(current.version, row.version) + 1; const revisionId = randomUUID(); this.db.prepare(`UPDATE canon_entries SET project_id=?, slug=?, title=?, body=?, entry_type=?, status=?, version=?, source_snapshot_id=?, supersedes_entry_id=?, metadata_json=?, valid_from=?, valid_until=?, updated_at=? WHERE entry_id=?`) .run(row.project_id, row.slug, row.title, row.body, row.entry_type, row.status, nextVersion, row.source_snapshot_id, row.supersedes_entry_id, row.metadata_json, row.valid_from, row.valid_until, now, row.entry_id); this.db.prepare(`INSERT INTO canon_revisions(revision_id, entry_id, version, title, body, source_snapshot_id, change_summary, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(revisionId, row.entry_id, nextVersion, row.title, row.body, row.source_snapshot_id, `Restored from snapshot ${id}`, row.metadata_json, now); } } for (const row of state.canonRevisions) { this.db.prepare(`INSERT OR IGNORE INTO canon_revisions(revision_id, entry_id, version, title, body, source_snapshot_id, change_summary, metadata_json, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(row.revision_id, row.entry_id, row.version, row.title, row.body, row.source_snapshot_id, row.change_summary, row.metadata_json, row.created_at, row.created_by); } for (const row of state.frontierItems) { this.db.prepare(`INSERT INTO frontier_items(frontier_id, project_id, domain, item_type, title, description, rationale, status, confidence, impact, first_seen_at, last_reviewed_at, review_after, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(frontier_id) DO UPDATE SET project_id=excluded.project_id, domain=excluded.domain, item_type=excluded.item_type, title=excluded.title, description=excluded.description, rationale=excluded.rationale, status=excluded.status, confidence=excluded.confidence, impact=excluded.impact, last_reviewed_at=excluded.last_reviewed_at, review_after=excluded.review_after, metadata_json=excluded.metadata_json, updated_at=excluded.updated_at`) .run(row.frontier_id, row.project_id, row.domain, row.item_type, row.title, row.description, row.rationale, row.status, row.confidence, row.impact, row.first_seen_at, row.last_reviewed_at, row.review_after, row.metadata_json, row.created_at, now); } for (const row of state.frontierObservations) { this.db.prepare(`INSERT OR IGNORE INTO frontier_observations(observation_id, frontier_id, source_name, source_uri, observed_at, summary, evidence_json, confidence, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(row.observation_id, row.frontier_id, row.source_name, row.source_uri, row.observed_at, row.summary, row.evidence_json, row.confidence, row.created_at); } for (const row of state.archives) { this.db.prepare(`INSERT OR IGNORE INTO archive_records(archive_id, project_id, resource_type, resource_id, snapshot_id, payload_json, checksum, archive_reason, archived_at, archived_by, retention_until, restored_at, metadata_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(row.archive_id, row.project_id, row.resource_type, row.resource_id, row.snapshot_id, row.payload_json, row.checksum, row.archive_reason, row.archived_at, row.archived_by, row.retention_until, row.restored_at, row.metadata_json); } for (const row of state.embeddings) { this.db.prepare(`INSERT INTO knowledge_embeddings(embedding_id, entity_type, entity_id, model_key, dimensions, embedding_json, content_hash, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(entity_type, entity_id, model_key) DO UPDATE SET dimensions=excluded.dimensions, embedding_json=excluded.embedding_json, content_hash=excluded.content_hash, created_at=excluded.created_at`) .run(row.embedding_id, row.entity_type, row.entity_id, row.model_key, row.dimensions, row.embedding_json, row.content_hash, row.created_at); } for (const row of state.dependencyFindings) { this.db.prepare(`INSERT INTO dependency_findings(finding_id, project_id, kind, name, description, status, source, metadata_json, detected_at, resolved_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(finding_id) DO UPDATE SET kind=excluded.kind, name=excluded.name, description=excluded.description, status=excluded.status, source=excluded.source, metadata_json=excluded.metadata_json, resolved_at=excluded.resolved_at`) .run(row.finding_id, row.project_id, row.kind, row.name, row.description, row.status, row.source, row.metadata_json, row.detected_at, row.resolved_at); } for (const row of state.deltaRuns) { this.db.prepare(`INSERT OR IGNORE INTO delta_runs(delta_run_id, project_id, current_label, target_label, current_state_json, target_state_json, status, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(row.delta_run_id, row.project_id, row.current_label, row.target_label, row.current_state_json, row.target_state_json, row.status, row.created_at, row.created_by); } for (const row of state.deltaGaps) { this.db.prepare(`INSERT OR IGNORE INTO delta_gaps(gap_id, delta_run_id, dimension, current_values_json, target_values_json, missing_values_json, severity, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(row.gap_id, row.delta_run_id, row.dimension, row.current_values_json, row.target_values_json, row.missing_values_json, row.severity, row.status, row.created_at); } for (const row of state.deltaDependencies) { this.db.prepare(`INSERT OR IGNORE INTO delta_dependencies(delta_dependency_id, delta_run_id, finding_id, created_at) VALUES (?, ?, ?, ?)`) .run(row.delta_dependency_id, row.delta_run_id, row.finding_id, row.created_at); } for (const row of state.governanceReviews) { this.db.prepare(`INSERT OR IGNORE INTO governance_reviews(review_id, project_id, action, resource_type, resource_id, decision, requested_by, requested_at, reviewed_by, reviewed_at, reason, metadata_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(row.review_id, row.project_id, row.action, row.resource_type, row.resource_id, row.decision, row.requested_by, row.requested_at, row.reviewed_by, row.reviewed_at, row.reason, row.metadata_json); } for (const row of state.events) { this.db.prepare(`INSERT OR IGNORE INTO project_events(event_id, project_id, event_type, payload_json, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?)`) .run(row.event_id, row.project_id, row.event_type, row.payload_json, row.created_at, row.created_by); } this.db.prepare('INSERT INTO project_events(event_id, project_id, event_type, payload_json, created_at) VALUES (?, ?, ?, ?, ?)') .run(randomUUID(), snapshot.project_id, 'snapshot.restored', json({ snapshotId: id, checksum: snapshot.checksum }), now); }); return projectFromRow(this.db.prepare('SELECT * FROM projects WHERE project_id = ?').get(snapshot.project_id)); } }