UNPKG

open-memex

Version:

Local-first memory layer and protocol for AI coding agents. Markdown source of truth, SQLite FTS5 index, zero cloud.

329 lines (328 loc) • 13.6 kB
/** * §20 (D88), D91: the graph's persistence. The graph is a DERIVED layer — * rebuildable from the Markdown source of truth at any time — so it stores * into SQLite beside the FTS index, into tables created with * CREATE TABLE IF NOT EXISTS outside the versioned schema (same treatment * as the D77 `memory_usage` counters): `rebuildIndexSchema` never has to * think about it, and `refreshGraph` is the healer for any staleness. * * Storage per scope key: * - `graph_edges` — the structural edge list (see graph/extract.ts). * - `graph_meta` — build stamp + the rendered compiled outline. The * outline is stored text: the session-start injection reads it and is * never responsible for rendering. * - `graph_verdict_queue` — staged semantic-edge verdicts awaiting human * review (llm-half §8, D97). Written ONLY by the verdict ingress * (`graph verdict`) after the admissibility check; never by the * write-path refresh, never by the memory outbox (an edge verdict * staged there would be published as a memory by submit). Rows stay * `pending` until a review step accepts or declines them — that step * is a later slice, not this one. * * Project scope only in D91 (decision): personal memories stay out of the * graph per §20.5's sync rule; the entry point no-ops for the personal key * so the write-path hooks can call it unconditionally. */ import { db } from "./db.js"; import { PERSONAL_SCOPE } from "../scope.js"; import { ulid } from "./markdown.js"; import { extractEdges, } from "../graph/extract.js"; import { renderOutline } from "../graph/outline.js"; const GRAPH_SCHEMA = ` CREATE TABLE IF NOT EXISTS graph_edges ( scope_key TEXT NOT NULL, from_id TEXT NOT NULL, to_id TEXT NOT NULL, edge_type TEXT NOT NULL, provenance TEXT NOT NULL, confidence TEXT NOT NULL, via TEXT NOT NULL, PRIMARY KEY (scope_key, from_id, to_id, edge_type) ); CREATE TABLE IF NOT EXISTS graph_meta ( scope_key TEXT PRIMARY KEY, built_at TEXT NOT NULL, node_count INTEGER NOT NULL, edge_count INTEGER NOT NULL, outline TEXT NOT NULL DEFAULT '', outline_ids TEXT NOT NULL DEFAULT '[]' ); CREATE TABLE IF NOT EXISTS graph_verdict_queue ( id TEXT PRIMARY KEY, scope_key TEXT NOT NULL, from_id TEXT NOT NULL, to_id TEXT NOT NULL, edge_type TEXT NOT NULL, confidence TEXT NOT NULL, model_confidence TEXT, span_from TEXT NOT NULL, span_to TEXT NOT NULL, relation TEXT NOT NULL, resolution TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', created_at TEXT NOT NULL ); `; let _graphSchemaReady = false; function ensureSchema() { if (_graphSchemaReady) return; db().exec(GRAPH_SCHEMA); _graphSchemaReady = true; } /** * Rebuild the graph for one scope from the index in a single pass: * read rows → extract structural edges → replace the scope's edge set → * render + store the outline. Reads everything it needs up front so the * DELETE + INSERT sequence is short. The Markdown files are untouched. */ export function refreshGraph(scopeKey, cfg) { ensureSchema(); // The index carries the chain as `superseded_by` (old → forward pointer, // §3.3); the frontmatter's back pointer (`supersedes` on the new file) // is not an indexed column. The graph derives the new → old direction // from the indexed one instead of adding yet another column the sync // layer must keep in lockstep. const rows = db() .prepare(`SELECT id, type, tags, content, status, superseded_by, derived_from FROM memories WHERE scope_key = ?`) .all(scopeKey); // new → old: every row pointing forward via superseded_by means the // TARGET of that pointer is a newer memory that superseded it. const supersedesByTarget = new Map(); for (const r of rows) { if (r.superseded_by && r.superseded_by !== r.id) supersedesByTarget.set(r.superseded_by, r.id); } const nodes = rows.map((r) => ({ id: r.id, status: r.status, type: r.type, tags: r.tags ? r.tags.split(",").map((t) => t.trim()).filter(Boolean) : [], body: r.content, supersedes: supersedesByTarget.get(r.id) ?? null, derived_from: r.derived_from, snippet: r.content.replace(/\s+/g, " ").trim().slice(0, 140), })); const edges = extractEdges(nodes); const d = db(); d.exec("BEGIN"); try { d.prepare(`DELETE FROM graph_edges WHERE scope_key = ?`).run(scopeKey); const insert = d.prepare(`INSERT OR IGNORE INTO graph_edges (scope_key, from_id, to_id, edge_type, provenance, confidence, via) VALUES (?, ?, ?, ?, ?, ?, ?)`); for (const e of edges) { insert.run(scopeKey, e.from, e.to, e.type, e.provenance, e.confidence, e.via); } // The outline compiles the VISIBLE set (active memories — superseded // versions are history, not "what is in memory"; §20.4's query side // keeps the full graph including chains). const visible = nodes.filter((n) => n.status === "active"); const visibleIds = new Set(visible.map((n) => n.id)); const visibleEdges = edges.filter((e) => visibleIds.has(e.from) && visibleIds.has(e.to)); const linesCfg = cfg ?? { graphOutlineLines: 10 }; const rendered = renderOutline(visible, visibleEdges, { maxLines: linesCfg.graphOutlineLines ?? 10, }); d.prepare(`INSERT INTO graph_meta (scope_key, built_at, node_count, edge_count, outline, outline_ids) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(scope_key) DO UPDATE SET built_at = excluded.built_at, node_count = excluded.node_count, edge_count = excluded.edge_count, outline = excluded.outline, outline_ids = excluded.outline_ids`).run(scopeKey, new Date().toISOString(), nodes.length, edges.length, rendered.lines.join("\n"), JSON.stringify(rendered.exposureIds)); d.exec("COMMIT"); return { scopeKey, nodes: nodes.length, edges: edges.length, topics: rendered.topics.length, outlineLines: rendered.lines.length, }; } catch (e) { d.exec("ROLLBACK"); throw e; } } /** * The write-path ingest hook (§20.4): deterministic extraction is cheap at * memory-store sizes, so every mutating surface refreshes the project * graph right after its write. Never throws — the memory write is the * source of truth and must not fail on a derived-layer hiccup; problems * say so on stderr like every other diagnostic. Personal scope no-ops. */ export function refreshGraphQuiet(scopeKey, cfg) { if (!scopeKey || scopeKey === PERSONAL_SCOPE.key) return false; try { refreshGraph(scopeKey, cfg); return true; } catch (e) { console.error(`[open-memex] graph refresh failed (outlines and graph queries may be stale): ${e.message}`); return false; } } /** * Read the stored graph, building it first when never built (lazy first * ingest so a fresh install shows the outline on turn one without waiting * for an explicit `graph build`). Refresh is quiet — a failed derived-layer * build yields null and the injection proceeds without it. */ export function ensureGraph(scopeKey, cfg) { ensureSchema(); const has = db() .prepare(`SELECT built_at FROM graph_meta WHERE scope_key = ?`) .get(scopeKey); if (!has) refreshGraphQuiet(scopeKey, cfg); return getStoredGraph(scopeKey); } /** Read the stored outline for a scope, or null when never built. */ export function getStoredGraph(scopeKey) { ensureSchema(); const row = db() .prepare(`SELECT built_at, node_count, edge_count, outline, outline_ids FROM graph_meta WHERE scope_key = ?`) .get(scopeKey); if (!row) return null; let ids = []; try { ids = JSON.parse(row.outline_ids); } catch { ids = []; } return { builtAt: row.built_at, nodes: row.node_count, edges: row.edge_count, outline: row.outline, outlineIds: ids, }; } /** All edges for a scope (query layer input). */ export function loadGraphEdges(scopeKey) { ensureSchema(); const rows = db() .prepare(`SELECT from_id, to_id, edge_type, provenance, confidence, via FROM graph_edges WHERE scope_key = ?`) .all(scopeKey); return rows.map((r) => ({ from: r.from_id, to: r.to_id, type: r.edge_type, provenance: r.provenance, confidence: r.confidence, via: r.via, })); } /** All nodes for a scope, as the query/lint layers see them. */ export function loadGraphNodes(scopeKey) { const rows = db() .prepare(`SELECT id, type, tags, content, status, superseded_by FROM memories WHERE scope_key = ?`) .all(scopeKey); // Same derivation as refreshGraph: a row's `superseded_by` points forward // (old → new), so the target of that pointer is the newer memory that // superseded it. The admissibility check reads this for rule 4. const supersedesByTarget = new Map(); for (const r of rows) { if (r.superseded_by && r.superseded_by !== r.id) supersedesByTarget.set(r.superseded_by, r.id); } return rows.map((r) => ({ id: r.id, status: r.status, type: r.type, tags: r.tags ? r.tags.split(",").map((t) => t.trim()).filter(Boolean) : [], body: r.content, supersedes: supersedesByTarget.get(r.id) ?? null, })); } /** * Every id in the store across scopes (lint's cross-scope set): a propose * copy's derived_from legitimately points at the personal original, which * is not a node in the project graph — lint must skip it, not report it. */ export function loadAllMemoryIds() { ensureSchema(); const rows = db() .prepare(`SELECT id FROM memories`) .all(); return rows.map((r) => r.id); } function rowToStaged(r) { return { id: r.id, scopeKey: r.scope_key, from: r.from_id, to: r.to_id, type: r.edge_type, confidence: r.confidence, modelConfidence: r.model_confidence, spanFrom: r.span_from, spanTo: r.span_to, relation: r.relation, resolution: r.resolution, status: r.status, createdAt: r.created_at, }; } /** * Stage one admissible verdict in the review queue. Idempotent per * (from, to, type) for identical content: a second verdict on a pair * already pending returns the existing row instead of staging a * duplicate — the human reviews the pair once. A re-stage with * DIFFERENT content (spans, relation, or resolution) is a conflict, * not a silent no-op: it returns the existing row with conflict true * so the caller can report it (the CLI exits 1 naming the staged row). * Callers must run `checkAdmissibility` first; this function stages, * it does not re-check. modelConfidence is recorded, never compared. */ export function stageVerdict(scopeKey, verdict, cappedConfidence) { ensureSchema(); const existing = db() .prepare(`SELECT * FROM graph_verdict_queue WHERE scope_key = ? AND from_id = ? AND to_id = ? AND edge_type = ? AND status = 'pending'`) .get(scopeKey, verdict.from, verdict.to, verdict.type); if (existing) { const same = existing.span_from === verdict.spanFrom && existing.span_to === verdict.spanTo && existing.relation === verdict.relation && existing.resolution === (verdict.resolution ?? "unresolved"); // Identical re-stage refreshes the recorded confidence: the first // value is not immutable metadata, the latest model verdict is. if (same && verdict.modelConfidence != null && existing.model_confidence !== verdict.modelConfidence) { db() .prepare(`UPDATE graph_verdict_queue SET model_confidence = ? WHERE id = ?`) .run(verdict.modelConfidence, existing.id); existing.model_confidence = verdict.modelConfidence; } return { staged: rowToStaged(existing), alreadyStaged: true, conflict: !same }; } const id = ulid(); const createdAt = new Date().toISOString(); db() .prepare(`INSERT INTO graph_verdict_queue (id, scope_key, from_id, to_id, edge_type, confidence, model_confidence, span_from, span_to, relation, resolution, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)`) .run(id, scopeKey, verdict.from, verdict.to, verdict.type, cappedConfidence, verdict.modelConfidence ?? null, verdict.spanFrom, verdict.spanTo, verdict.relation, verdict.resolution ?? "unresolved", createdAt); const row = db() .prepare(`SELECT * FROM graph_verdict_queue WHERE id = ?`) .get(id); return { staged: rowToStaged(row), alreadyStaged: false, conflict: false }; } /** Pending staged verdicts for a scope, oldest first. */ export function listStagedVerdicts(scopeKey) { ensureSchema(); const rows = db() .prepare(`SELECT * FROM graph_verdict_queue WHERE scope_key = ? AND status = 'pending' ORDER BY created_at ASC, id ASC`) .all(scopeKey); return rows.map(rowToStaged); }