From 5844ab3f213a713ea51f8bd5a0874ca47af245b1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 14:50:43 +0000 Subject: [PATCH 1/2] test(core): inventory the CLI and UI graph reader profiles Assert, on nonempty Odysseus fixtures, every difference between the `brain graph` reader and the supported query API's graph reader: node and edge scope, isolate defaults, ordering, missing centers and roots, virtual root shape, absent/old/uncomputed data, staleDays bounds and caps. Written and passing against the readers before consolidation (#1354). Co-Authored-By: Claude Opus 5.5 --- packages/core/tests/graph-profiles.test.ts | 582 +++++++++++++++++++++ 1 file changed, 582 insertions(+) create mode 100644 packages/core/tests/graph-profiles.test.ts diff --git a/packages/core/tests/graph-profiles.test.ts b/packages/core/tests/graph-profiles.test.ts new file mode 100644 index 0000000000..2dea5c9861 --- /dev/null +++ b/packages/core/tests/graph-profiles.test.ts @@ -0,0 +1,582 @@ +import { afterAll, afterEach, beforeAll, describe, expect, setSystemTime, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { mkdtempSync, rmSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; + +import { openDatabase } from "../src/lib/db"; +import { + getClusterGraph, + getDiscoveryGraph, + getEgoGraph, + getGraphStats, + getMaintenanceFindings, +} from "../src/lib/graph/queries"; +import * as queries from "../src/queries/index"; +import type { QueryCode, QueryResult } from "../src/queries/index"; + +// Profile inventory (#1354). Core reads one set of graph tables for two +// surfaces: the `brain graph` CLI (lib/graph/queries.ts) and the supported +// `./queries` API, whose behaviour is the UI profile (queries/graph.ts). The +// two differ on purpose and the 2026-10-09 ruling preserves every difference. +// Each expected value below was written against, and passed on, the readers as +// they stood before they were consolidated; none is computed by either reader. + +const NOW = "2026-07-12T12:00:00Z"; +const INDEXED_AT = "2026-07-12T08:00:00Z"; +const COMPUTED_AT = "2026-07-12T09:00:00Z"; + +const temporary: string[] = []; +afterAll(() => { + for (const dir of temporary) rmSync(dir, { recursive: true, force: true }); +}); +afterEach(() => setSystemTime()); + +function dbPath(brainPath: string): string { + return join(brainPath, ".brain-index", "brain.db"); +} + +function brain(seed: (db: Database) => void): string { + const dir = mkdtempSync(join(tmpdir(), "brain-graph-profiles-")); + temporary.push(dir); + const db = openDatabase(dbPath(dir)); + try { + db.transaction(() => seed(db))(); + db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + } finally { + db.close(); + } + return dir; +} + +function edit(brainPath: string, sql: string): void { + const db = new Database(dbPath(brainPath)); + try { + db.exec(sql); + db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + } finally { + db.close(true); + } +} + +/** The CLI opens the resolved database read-only and hands it to the reader. */ +function cli(brainPath: string, read: (db: Database) => T): T { + const db = openDatabase(dbPath(brainPath), { readonly: true }); + try { + return read(db); + } finally { + db.close(); + } +} + +function ok(result: QueryResult): T { + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) throw new Error("expected a successful query"); + return result.value; +} + +function failed(result: QueryResult, code: QueryCode): void { + expect(result).toEqual({ ok: false, error: { code, retryable: false } }); +} + +const ids = (nodes: { id: number }[]): number[] => nodes.map((node) => node.id); +const sortedEdges = (edges: { source: number; target: number }[]): string[] => + edges.map((edge) => `${edge.source}>${edge.target}`).sort(); + +interface Doc { + id: number; + path: string; + title: string; + type: string; + updated: string; + asset: string | null; +} + +/** + * The voyage: Odysseus links to Ithaca (twice, once through an alias), to + * Penelope, to himself, to a chart PDF and to Thrinacia, which resolves to + * nothing. Penelope links to Telemachus, who links back to Odysseus; Troy + * links to Odysseus. Eurylochus is an isolate. The raft log is a document + * whose asset type is NULL — a node to the UI profile and not to the CLI. + * Precomputed analytics cover only the CLI's node set, as the precompute does. + */ +const VOYAGE: Doc[] = [ + { id: 1, path: "crew/odysseus.md", title: "Odysseus", type: "person", updated: "2026-07-12", asset: "markdown" }, + { id: 2, path: "places/ithaca.md", title: "Ithaca", type: "place", updated: "2026-07-10", asset: "markdown" }, + { id: 3, path: "crew/penelope.md", title: "Penelope", type: "person", updated: "2026-07-11", asset: "markdown" }, + { id: 4, path: "crew/telemachus.md", title: "Telemachus", type: "person", updated: "2026-07-01", asset: "markdown" }, + { id: 5, path: "places/troy.md", title: "Troy", type: "place", updated: "2016-07-12", asset: "markdown" }, + { id: 6, path: "crew/eurylochus.md", title: "Eurylochus", type: "person", updated: "2026-03-01", asset: "markdown" }, + { id: 7, path: "maps/aegean.pdf", title: "Aegean chart", type: "asset", updated: "2026-07-12", asset: "pdf" }, + { id: 8, path: "logs/raft-build.md", title: "Raft build", type: "log", updated: "2026-07-08", asset: null }, +]; + +const LINKS: [number, string, number | null][] = [ + [1, "places/ithaca.md", 2], + [1, "Ithaca Harbour", 2], + [1, "crew/penelope.md", 3], + [1, "crew/odysseus.md", 1], + [1, "maps/aegean.pdf", 7], + [1, "Thrinacia", null], + [3, "crew/telemachus.md", 4], + [4, "crew/odysseus.md", 1], + [5, "crew/odysseus.md", 1], + [2, "logs/raft-build.md", 8], + [8, "Scheria", null], +]; + +// document_id, in, out, pagerank, community +const METRICS: [number, number, number, number, number | null][] = [ + [1, 2, 2, 0.3, 0], + [2, 1, 0, 0.2, 0], + [3, 1, 1, 0.15, 0], + [4, 1, 1, 0.1, 0], + [5, 0, 1, 0.05, 1], + [6, 0, 0, 0.01, null], +]; + +function insertDocs(db: Database, docs: Doc[]): void { + const insert = db.query( + `INSERT INTO documents (id, path, title, type, status, created, updated, content, indexed_at, asset_type) + VALUES (?, ?, ?, ?, 'active', '2026-01-01', ?, 'Ithaca', ?, ?)` + ); + for (const doc of docs) insert.run(doc.id, doc.path, doc.title, doc.type, doc.updated, INDEXED_AT, doc.asset); +} + +function seedVoyage(db: Database): void { + insertDocs(db, VOYAGE); + const link = db.query("INSERT INTO links (source_id, target, target_id) VALUES (?, ?, ?)"); + for (const [source, target, targetId] of LINKS) link.run(source, target, targetId); + const metric = db.query( + "INSERT INTO graph_metrics (document_id, in_degree, out_degree, component, pagerank, community) VALUES (?, ?, ?, 1, ?, ?)" + ); + for (const [id, inDegree, outDegree, pagerank, community] of METRICS) metric.run(id, inDegree, outDegree, pagerank, community); + const layout = db.query("INSERT INTO graph_layouts (mode, document_id, x, y) VALUES ('clusters', ?, ?, ?)"); + for (const [id] of METRICS) layout.run(id, id * 10, -id * 10); + db.run("INSERT INTO graph_communities (community, size, label, top_terms) VALUES (0, 4, 'Ithaca', '[\"ithaca\"]'), (1, 1, 'Troy', '[]')"); + const distance = db.query("INSERT INTO graph_root_distances (document_id, distance, parent_id) VALUES (?, ?, ?)"); + distance.run(1, 1, null); + distance.run(2, 2, 1); + distance.run(3, 2, 1); + distance.run(4, 3, 3); + const meta = db.query("INSERT OR REPLACE INTO index_metadata (key, value) VALUES (?, ?)"); + meta.run("graph_computed_at", COMPUTED_AT); + meta.run("graph_root", "virtual:AGENTS.md"); + meta.run("graph_root_links", "[1]"); +} + +/** Strip the precompute: graph tables empty, no graph metadata. */ +const UNCOMPUTE = `DELETE FROM graph_metrics; DELETE FROM graph_layouts; DELETE FROM graph_communities; + DELETE FROM graph_root_distances; DELETE FROM index_metadata WHERE key LIKE 'graph_%';`; + +/** A supported pre-v8 layout: no graph tables at all. */ +const DOWNGRADE = `DROP TABLE graph_metrics; DROP TABLE graph_layouts; DROP TABLE graph_communities; + DROP TABLE graph_root_distances; DELETE FROM index_metadata WHERE key LIKE 'graph_%'; + UPDATE index_metadata SET value = '7' WHERE key = 'schema_version';`; + +let voyage: string; +beforeAll(() => { + voyage = brain(seedVoyage); +}); + +describe("node and edge scope", () => { + test("UI treats a NULL asset type as markdown and orders edges by the engine; CLI requires 'markdown' and sorts", () => { + const ui = ok(queries.readGraphClusters({ brainPath: voyage, includeIsolates: true })); + const cliGraph = cli(voyage, (db) => getClusterGraph(db)); + expect(ids(ui.nodes)).toEqual([1, 2, 3, 4, 5, 6, 8]); + expect(ids(cliGraph.nodes)).toEqual([1, 2, 3, 4, 5, 6]); + expect(sortedEdges(ui.edges)).toEqual(["1>2", "1>3", "2>8", "3>4", "4>1", "5>1"]); + expect(cliGraph.edges).toEqual([ + { source: 1, target: 2 }, + { source: 1, target: 3 }, + { source: 3, target: 4 }, + { source: 4, target: 1 }, + { source: 5, target: 1 }, + ]); + }); +}); + +describe("clusters: isolate defaults, ordering and node shape", () => { + test("UI excludes isolates by metrics degree and ranks by pagerank", () => { + const ui = ok(queries.readGraphClusters({ brainPath: voyage })); + expect(ids(ui.nodes)).toEqual([1, 2, 3, 4, 5]); + expect(ui.truncated).toBe(false); + expect(ui.nodes[0]).toEqual({ + id: 1, + path: "crew/odysseus.md", + title: "Odysseus", + type: "person", + inDegree: 2, + outDegree: 2, + community: 0, + pagerank: 0.3, + x: 10, + y: -10, + }); + expect(sortedEdges(ui.edges)).toEqual(["1>2", "1>3", "3>4", "4>1", "5>1"]); + // NULL pagerank sorts last; a node without metrics carries no analytics. + const all = ok(queries.readGraphClusters({ brainPath: voyage, includeIsolates: true })); + expect(all.nodes.at(-1)).toEqual({ + id: 8, + path: "logs/raft-build.md", + title: "Raft build", + type: "log", + inDegree: 0, + outDegree: 0, + }); + }); + + test("CLI includes isolates by default, keeps document id order and drops isolates by adjacency", () => { + const all = cli(voyage, (db) => getClusterGraph(db)); + expect(ids(all.nodes)).toEqual([1, 2, 3, 4, 5, 6]); + expect(all.truncated).toBe(false); + expect(all.nodes[5]).toEqual({ + id: 6, + path: "crew/eurylochus.md", + title: "Eurylochus", + type: "person", + inDegree: 0, + outDegree: 0, + pagerank: 0.01, + x: 60, + y: -60, + }); + const linked = cli(voyage, (db) => getClusterGraph(db, { includeIsolates: false })); + expect(ids(linked.nodes)).toEqual([1, 2, 3, 4, 5]); + const community = cli(voyage, (db) => getClusterGraph(db, { community: 1 })); + expect(ids(community.nodes)).toEqual([5]); + expect(community.edges).toEqual([]); + }); +}); + +describe("neighborhood: ordering, missing centers and path handling", () => { + test("UI loads the reached ids in row order with layout; CLI keeps BFS order without layout", () => { + const ui = ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "crew/telemachus.md" })); + expect(ui.nodes.map((n) => [n.id, n.distance])).toEqual([ + [1, 1], + [3, 1], + [4, 0], + ]); + expect(ui.nodes[0].x).toBe(10); + const cliGraph = cli(voyage, (db) => getEgoGraph(db, { center: "crew/telemachus.md" })); + expect(cliGraph.nodes.map((n) => [n.id, n.distance])).toEqual([ + [4, 0], + [1, 1], + [3, 1], + ]); + expect(cliGraph.nodes[1]).toEqual({ + id: 1, + path: "crew/odysseus.md", + title: "Odysseus", + type: "person", + inDegree: 2, + outDegree: 2, + community: 0, + pagerank: 0.3, + distance: 1, + }); + expect(cliGraph.edges).toEqual([ + { source: 1, target: 3 }, + { source: 3, target: 4 }, + { source: 4, target: 1 }, + ]); + }); + + test("depth defaults to 1 and clamps to 3 in both; the walk follows each profile's edge scope", () => { + const uiDeep = ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "crew/odysseus.md", depth: 9, direction: "out" })); + expect(uiDeep.nodes.map((n) => [n.id, n.distance])).toEqual([ + [1, 0], + [2, 1], + [3, 1], + [4, 2], + [8, 2], + ]); + const cliDeep = cli(voyage, (db) => getEgoGraph(db, { center: "crew/odysseus.md", depth: 9, direction: "out" })); + expect(cliDeep.nodes.map((n) => [n.id, n.distance])).toEqual([ + [1, 0], + [2, 1], + [3, 1], + [4, 2], + ]); + expect(ids(ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "crew/odysseus.md" })).nodes)).toEqual([1, 2, 3, 4, 5]); + expect(ids(cli(voyage, (db) => getEgoGraph(db, { center: "crew/odysseus.md" })).nodes)).toEqual([1, 2, 3, 4, 5]); + }); + + test("a missing center is not_found for the UI and an empty subgraph for the CLI", () => { + failed(queries.readGraphNeighborhood({ brainPath: voyage, center: "crew/argos.md" }), "not_found"); + failed(queries.readGraphNeighborhood({ brainPath: voyage, center: "maps/aegean.pdf" }), "not_found"); + const empty = { nodes: [], edges: [], truncated: false }; + expect(cli(voyage, (db) => getEgoGraph(db, { center: "crew/argos.md" }))).toEqual(empty); + expect(cli(voyage, (db) => getEgoGraph(db, { center: "maps/aegean.pdf" }))).toEqual(empty); + // The NULL-asset log is a UI node and no CLI node. + expect(ids(ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "logs/raft-build.md" })).nodes)).toEqual([2, 8]); + expect(cli(voyage, (db) => getEgoGraph(db, { center: "logs/raft-build.md" }))).toEqual(empty); + // The UI normalizes a leading "./"; the CLI matches the stored path exactly. + expect(ids(ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "./places/troy.md" })).nodes)).toEqual([1, 5]); + expect(cli(voyage, (db) => getEgoGraph(db, { center: "./places/troy.md" }))).toEqual(empty); + }); +}); + +describe("discovery: virtual root, explicit roots and counts", () => { + test("the default virtual root differs in shape, edge position and reach counts", () => { + const ui = ok(queries.readGraphDiscovery({ brainPath: voyage })); + expect(ui.nodes[0]).toEqual({ + id: 0, + path: "AGENTS.md", + title: "AGENTS.md", + type: "root", + inDegree: 0, + outDegree: 1, + distance: 0, + virtual: true, + }); + expect(ui.nodes.map((n) => [n.id, n.distance])).toEqual([ + [0, 0], + [1, 1], + [2, 2], + [3, 2], + [4, 3], + ]); + expect(ui.edges[0]).toEqual({ source: 0, target: 1 }); + expect(sortedEdges(ui.edges)).toEqual(["0>1", "1>2", "1>3", "3>4", "4>1"]); + expect(ui.reachableCount).toBe(4); + expect(ui.unreachableCount).toBe(3); + expect(ui.truncated).toBe(false); + + const cliGraph = cli(voyage, (db) => getDiscoveryGraph(db)); + expect(cliGraph.nodes[0]).toEqual({ + id: 0, + path: "AGENTS.md", + title: "AGENTS.md", + type: "index", + inDegree: 0, + outDegree: 0, + distance: 0, + virtual: true, + }); + expect(ids(cliGraph.nodes)).toEqual([0, 1, 2, 3, 4]); + expect(cliGraph.edges).toEqual([ + { source: 1, target: 2 }, + { source: 1, target: 3 }, + { source: 3, target: 4 }, + { source: 4, target: 1 }, + { source: 0, target: 1 }, + ]); + expect(cliGraph).not.toHaveProperty("reachableCount"); + expect(cliGraph).not.toHaveProperty("unreachableCount"); + + expect(ids(ok(queries.readGraphDiscovery({ brainPath: voyage, maxDepth: 2 })).nodes)).toEqual([0, 1, 2, 3]); + expect(ids(cli(voyage, (db) => getDiscoveryGraph(db, { maxDepth: 2 })).nodes)).toEqual([0, 1, 2, 3]); + }); + + test("root link ids: the UI keeps finite numbers, the CLI coerces to integers", () => { + const dir = brain(seedVoyage); + edit(dir, `UPDATE index_metadata SET value = '[1, "5", 2.5]' WHERE key = 'graph_root_links'; + INSERT INTO graph_root_distances (document_id, distance, parent_id) VALUES (5, 1, NULL);`); + const ui = ok(queries.readGraphDiscovery({ brainPath: dir })); + expect(ui.edges.filter((e) => e.source === 0)).toEqual([{ source: 0, target: 1 }]); + const cliGraph = cli(dir, (db) => getDiscoveryGraph(db)); + expect(cliGraph.edges.filter((e) => e.source === 0)).toEqual([ + { source: 0, target: 1 }, + { source: 0, target: 5 }, + ]); + }); + + test("an explicit root walks per request; only the UI reports reach", () => { + const ui = ok(queries.readGraphDiscovery({ brainPath: voyage, root: "crew/penelope.md" })); + expect(ui.nodes.map((n) => [n.id, n.distance])).toEqual([ + [1, 2], + [2, 3], + [3, 0], + [4, 1], + [8, 4], + ]); + expect(ui.reachableCount).toBe(5); + expect(ui.unreachableCount).toBe(2); + const cliGraph = cli(voyage, (db) => getDiscoveryGraph(db, { root: "crew/penelope.md" })); + expect(cliGraph.nodes.map((n) => [n.id, n.distance])).toEqual([ + [3, 0], + [4, 1], + [1, 2], + [2, 3], + ]); + expect(cliGraph).not.toHaveProperty("reachableCount"); + // Only the CLI walks inbound from a discovery root. + failed(queries.readGraphDiscovery({ brainPath: voyage, root: "crew/odysseus.md", direction: "in" as "out" }), "invalid_input"); + expect(ids(cli(voyage, (db) => getDiscoveryGraph(db, { root: "crew/odysseus.md", direction: "in", maxDepth: 1 })).nodes)).toEqual([1, 4, 5]); + }); + + test("a missing root is not_found for the UI and an empty subgraph for the CLI", () => { + failed(queries.readGraphDiscovery({ brainPath: voyage, root: "crew/argos.md" }), "not_found"); + expect(cli(voyage, (db) => getDiscoveryGraph(db, { root: "crew/argos.md" }))).toEqual({ nodes: [], edges: [], truncated: false }); + }); +}); + +describe("maintenance: findings, ordering and staleDays", () => { + test("defaults: 180 days, UI ordering and caps, CLI id order and root echo", () => { + setSystemTime(new Date(NOW)); + const ui = ok(queries.readGraphMaintenance({ brainPath: voyage })); + expect(ui.staleDays).toBe(180); + expect(ids(ui.orphans)).toEqual([8, 6]); + expect(ids(ui.unreachable)).toEqual([5, 6, 8]); + expect(ids(ui.stale)).toEqual([5]); + expect(ui.stale[0].updated).toBe("2016-07-12"); + expect(ui.brokenLinks).toEqual([ + { sourcePath: "crew/odysseus.md", target: "Thrinacia" }, + { sourcePath: "logs/raft-build.md", target: "Scheria" }, + ]); + expect(ui).not.toHaveProperty("root"); + + const cliFindings = cli(voyage, (db) => getMaintenanceFindings(db)); + expect(cliFindings.staleDays).toBe(180); + expect(cliFindings.root).toBe("virtual:AGENTS.md"); + expect(ids(cliFindings.orphans)).toEqual([6]); + expect(ids(cliFindings.unreachable)).toEqual([5, 6]); + expect(ids(cliFindings.stale)).toEqual([5]); + expect(cliFindings.brokenLinks).toEqual(ui.brokenLinks); + }); + + test("the UI clamps staleDays to 1..3650; the CLI uses the value as given", () => { + setSystemTime(new Date(NOW)); + const stale = (staleDays: number) => { + const ui = ok(queries.readGraphMaintenance({ brainPath: voyage, staleDays, now: NOW })); + const cliFindings = cli(voyage, (db) => getMaintenanceFindings(db, { staleDays })); + return { + ui: [ui.staleDays, ids(ui.stale)], + cli: [cliFindings.staleDays, ids(cliFindings.stale)], + }; + }; + expect(stale(0)).toEqual({ ui: [1, [5, 6, 4, 8, 2]], cli: [0, [2, 3, 4, 5, 6]] }); + expect(stale(-5)).toEqual({ ui: [1, [5, 6, 4, 8, 2]], cli: [-5, [1, 2, 3, 4, 5, 6]] }); + expect(stale(4000)).toEqual({ ui: [3650, [5]], cli: [4000, []] }); + expect(stale(3650)).toEqual({ ui: [3650, [5]], cli: [3650, [5]] }); + }); +}); + +describe("absent, uncomputed and older graph data", () => { + test("uncomputed: the UI refuses derived modes and keeps raw neighborhoods; the CLI degrades every mode", () => { + const dir = brain(seedVoyage); + edit(dir, UNCOMPUTE); + failed(queries.readGraphClusters({ brainPath: dir }), "not_computed"); + failed(queries.readGraphDiscovery({ brainPath: dir }), "not_computed"); + failed(queries.readGraphDiscovery({ brainPath: dir, root: "crew/odysseus.md" }), "not_computed"); + failed(queries.readGraphMaintenance({ brainPath: dir }), "not_computed"); + const hood = ok(queries.readGraphNeighborhood({ brainPath: dir, center: "crew/odysseus.md" })); + // Without metrics the UI reports zero degrees; the CLI counts adjacency. + expect(hood.nodes.find((n) => n.id === 1)).toEqual({ + id: 1, + path: "crew/odysseus.md", + title: "Odysseus", + type: "person", + inDegree: 0, + outDegree: 0, + distance: 0, + }); + const ego = cli(dir, (db) => getEgoGraph(db, { center: "crew/odysseus.md" })); + expect(ego.nodes[0]).toEqual({ + id: 1, + path: "crew/odysseus.md", + title: "Odysseus", + type: "person", + inDegree: 2, + outDegree: 2, + distance: 0, + }); + const clusters = cli(dir, (db) => getClusterGraph(db)); + expect(ids(clusters.nodes)).toEqual([1, 2, 3, 4, 5, 6]); + expect(clusters.nodes.every((n) => n.pagerank === undefined && n.x === undefined)).toBe(true); + expect(cli(dir, (db) => getDiscoveryGraph(db))).toEqual({ nodes: [], edges: [], truncated: false }); + expect(ids(cli(dir, (db) => getDiscoveryGraph(db, { root: "crew/odysseus.md", maxDepth: 1 })).nodes)).toEqual([1, 2, 3]); + const findings = cli(dir, (db) => getMaintenanceFindings(db)); + expect(findings.root).toBeNull(); + expect(findings.unreachable).toEqual([]); + expect(ids(findings.orphans)).toEqual([6]); + expect(cli(dir, (db) => getGraphStats(db))).toMatchObject({ computedAt: null, root: null, nodes: 0, edges: 5, reachable: 0 }); + }); + + test("older layout: the UI keeps only the neighborhood; the CLI reads links without the derived tables", () => { + const dir = brain(seedVoyage); + edit(dir, DOWNGRADE); + expect(ok(queries.readGraphMeta({ brainPath: dir }))).toMatchObject({ available: false, reason: "schema", schemaVersion: 7 }); + failed(queries.readGraphClusters({ brainPath: dir }), "incompatible_index"); + failed(queries.readGraphDiscovery({ brainPath: dir }), "incompatible_index"); + failed(queries.readGraphMaintenance({ brainPath: dir }), "incompatible_index"); + expect(ids(ok(queries.readGraphNeighborhood({ brainPath: dir, center: "crew/odysseus.md" })).nodes)).toEqual([1, 2, 3, 4, 5]); + expect(ids(cli(dir, (db) => getClusterGraph(db)).nodes)).toEqual([1, 2, 3, 4, 5, 6]); + expect(cli(dir, (db) => getDiscoveryGraph(db))).toEqual({ nodes: [], edges: [], truncated: false }); + expect(ids(cli(dir, (db) => getEgoGraph(db, { center: "crew/odysseus.md" })).nodes)).toEqual([1, 2, 3, 4, 5]); + expect(ids(cli(dir, (db) => getMaintenanceFindings(db)).orphans)).toEqual([6]); + expect(cli(dir, (db) => getGraphStats(db))).toMatchObject({ computedAt: null, nodes: 0, edges: 5, components: 0, communities: [] }); + }); + + test("an absent index is a typed UI failure", () => { + const dir = mkdtempSync(join(tmpdir(), "brain-graph-profiles-absent-")); + temporary.push(dir); + failed(queries.readGraphNeighborhood({ brainPath: dir, center: "crew/odysseus.md" }), "missing_index"); + }); +}); + +describe("caps and truncation on a fleet-sized ledger", () => { + // Odysseus's hub note links to 5,100 ledger entries, all last touched in + // 2015. Every UI cap is exceeded; the CLI has no cap in any mode. + const ENTRIES = 5100; + let fleet: string; + beforeAll(() => { + fleet = brain((db) => { + const entries: Doc[] = []; + for (let i = 0; i < ENTRIES; i++) { + entries.push({ id: 100 + i, path: `ledger/entry-${String(i).padStart(4, "0")}.md`, title: `Ledger ${i}`, type: "note", updated: "2015-07-12", asset: "markdown" }); + } + insertDocs(db, [VOYAGE[0], ...entries]); + const link = db.query("INSERT INTO links (source_id, target, target_id) VALUES (1, ?, ?)"); + for (const entry of entries) link.run(entry.path, entry.id); + const metric = db.query( + "INSERT INTO graph_metrics (document_id, in_degree, out_degree, component, pagerank, community) VALUES (?, ?, ?, 1, ?, 0)" + ); + metric.run(1, 0, ENTRIES, 1); + for (const entry of entries) metric.run(entry.id, 1, 0, entry.id / 1e6); + db.run("INSERT OR REPLACE INTO index_metadata (key, value) VALUES ('graph_computed_at', ?)", [COMPUTED_AT]); + }); + }); + + test("neighborhood: the UI stops at 1,500 nodes; the CLI returns every neighbour", () => { + const ui = ok(queries.readGraphNeighborhood({ brainPath: fleet, center: "crew/odysseus.md" })); + expect(ui.nodes.length).toBe(1500); + expect(ui.truncated).toBe(true); + const cliGraph = cli(fleet, (db) => getEgoGraph(db, { center: "crew/odysseus.md" })); + expect(cliGraph.nodes.length).toBe(ENTRIES + 1); + expect(cliGraph.edges.length).toBe(ENTRIES); + expect(cliGraph.truncated).toBe(false); + }); + + test("explicit-root discovery: the UI caps at 5,000 and reports full reach; the CLI walk has no budget", () => { + const ui = ok(queries.readGraphDiscovery({ brainPath: fleet, root: "crew/odysseus.md" })); + expect(ui.nodes.length).toBe(5000); + expect(ui.truncated).toBe(true); + expect(ui.reachableCount).toBe(ENTRIES + 1); + expect(ui.unreachableCount).toBe(0); + const cliGraph = cli(fleet, (db) => getDiscoveryGraph(db, { root: "crew/odysseus.md" })); + expect(cliGraph.nodes.length).toBe(ENTRIES + 1); + expect(cliGraph.truncated).toBe(false); + }); + + test("clusters keep the 5,000 highest-pagerank nodes for the UI and every node for the CLI", () => { + const ui = ok(queries.readGraphClusters({ brainPath: fleet })); + expect(ui.nodes.length).toBe(5000); + expect(ui.truncated).toBe(true); + expect(ui.nodes[0].id).toBe(1); + expect(ui.nodes[1].id).toBe(100 + ENTRIES - 1); + const cliGraph = cli(fleet, (db) => getClusterGraph(db)); + expect(cliGraph.nodes.length).toBe(ENTRIES + 1); + expect(cliGraph.truncated).toBe(false); + }); + + test("maintenance lists stop at 5,000 for the UI and are complete for the CLI", () => { + setSystemTime(new Date(NOW)); + const ui = ok(queries.readGraphMaintenance({ brainPath: fleet, now: NOW })); + expect(ui.stale.length).toBe(5000); + expect(ui.stale[0].id).toBe(100); + const cliFindings = cli(fleet, (db) => getMaintenanceFindings(db)); + expect(cliFindings.stale.length).toBe(ENTRIES); + }); +}); From eb828cdbce7c6bd5e7a145e2498b03296462fd03 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 15:13:50 +0000 Subject: [PATCH 2/2] refactor(core): read the graph through one reader with CLI and UI profiles Move the link structure, path lookup, breadth-first walk, depth and staleness defaults, root distances, broken links and scene caps into lib/graph/reader.ts. Two concrete internal profiles keep every difference the inventory test records: node scope, edge order, caps and truncation, isolate defaults, path handling, staleDays bounds, root seed parsing and derived-table degradation. The adapters keep their result shapes, node materialization and error policy, each selecting its profile in one place. Constants are defined once, and the stale header claiming ui-server keeps its own reader is replaced by the actual profile differences (#1354). Co-Authored-By: Claude Opus 5.5 --- .changeset/graph-reader-profiles.md | 5 + docs/decisions/index-query-api.md | 2 +- docs/plans/index-query-api.md | 2 +- packages/core/src/lib/graph/queries.ts | 318 +++++++--------------- packages/core/src/lib/graph/reader.ts | 360 +++++++++++++++++++++++++ packages/core/src/queries/graph.ts | 241 ++++------------- 6 files changed, 512 insertions(+), 416 deletions(-) create mode 100644 .changeset/graph-reader-profiles.md create mode 100644 packages/core/src/lib/graph/reader.ts diff --git a/.changeset/graph-reader-profiles.md b/.changeset/graph-reader-profiles.md new file mode 100644 index 0000000000..02bebe43bc --- /dev/null +++ b/.changeset/graph-reader-profiles.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain": patch +--- + +Core's two graph readers, behind `brain graph` and the supported `./queries` graph reads, now share one internal reader with an explicit CLI profile and UI profile (#1354). Both keep their former results, defaults, caps, ordering and errors. No `--json` shape, query result or export changes. diff --git a/docs/decisions/index-query-api.md b/docs/decisions/index-query-api.md index 74886b6add..7d08ffc6b2 100644 --- a/docs/decisions/index-query-api.md +++ b/docs/decisions/index-query-api.md @@ -29,7 +29,7 @@ alone does not excuse changing the documented results or error behavior. Two packages currently own graph SQL. UI-server opens a short-lived read-only connection (`openBrainDb`, `packages/ui-server/src/db/brain-db.ts:75-97`), interprets graph availability ([pre-migration `getGraphMeta`](https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/packages/ui-server/src/graph/reader.ts#L437-L471)) and walks raw links for -interactive neighborhoods ([pre-migration `getNeighborhood`](https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/packages/ui-server/src/graph/reader.ts#L525-L540)). Core has its own cluster query (`getClusterGraph`, `packages/core/src/lib/graph/queries.ts:181-204`). +interactive neighborhoods ([pre-migration `getNeighborhood`](https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/packages/ui-server/src/graph/reader.ts#L525-L540)). Core has its own cluster query (`getClusterGraph`, `packages/core/src/lib/graph/queries.ts:142-159`). Their defaults and responses differ. A wrapper around one existing helper is not automatically a behavior-preserving replacement for the other. diff --git a/docs/plans/index-query-api.md b/docs/plans/index-query-api.md index df402b543d..6464678315 100644 --- a/docs/plans/index-query-api.md +++ b/docs/plans/index-query-api.md @@ -269,7 +269,7 @@ resolved; direction affects an explicit root, not precomputed default distances. Preserve existing maintenance ordering, unresolved link text and stale cutoff. Core CLI graph helpers have different defaults, fields and cap behavior -(`getClusterGraph`, `packages/core/src/lib/graph/queries.ts:181-204`). They may share private mechanics, but their public CLI `--json` +(`getClusterGraph`, `packages/core/src/lib/graph/queries.ts:142-159`). They may share private mechanics, but their public CLI `--json` shapes/defaults remain unchanged. Pi and MCP link walking default to depth 1/both. Pi and the supported link-walk query clamp depth to 1..4; core MCP's own cap is 5. It is a different result from the drawn graph: unresolved text is preserved and cycle/deduplication behavior diff --git a/packages/core/src/lib/graph/queries.ts b/packages/core/src/lib/graph/queries.ts index 5e03a9c67b..73d82b2c4a 100644 --- a/packages/core/src/lib/graph/queries.ts +++ b/packages/core/src/lib/graph/queries.ts @@ -1,13 +1,14 @@ /** - * Read side of the graph, used by the `brain graph` CLI. - * - * ui-server has its own reader over the same tables (it deliberately does not - * depend on core). Both are governed by docs/integration-contract.md — change - * the table shapes and both must move. + * The `brain graph` CLI's graph modes: the CLI profile of the shared graph + * reader (`GraphReader`, `./reader.ts`). This adapter owns the `--json` + * shapes and node materialization; the reader's header lists every way this + * profile differs from the supported `./queries` API. Both read the same + * tables, which docs/integration-contract.md governs. */ import type { Database } from "bun:sqlite"; +import { CLI_GRAPH_PROFILE, GraphReader, VIRTUAL_ROOT_ID, parseGraphRootKey, type Walk } from "./reader.js"; import type { GraphDirection, GraphEdgeRecord, @@ -15,14 +16,12 @@ import type { GraphSubgraph, } from "./types.js"; -/** Depth beyond this stops being a neighbourhood and becomes the whole vault. */ -export const MAX_EGO_DEPTH = 3; -/** Discovery rings past this are noise at any realistic corpus size. */ -export const MAX_DISCOVERY_DEPTH = 8; -/** Default staleness horizon, matching the core taxonomy default. */ -export const DEFAULT_STALE_DAYS = 180; -/** The synthesized virtual-root node; no document carries id 0. */ -export const VIRTUAL_ROOT_ID = 0; +export { + DEFAULT_STALE_DAYS, + MAX_DISCOVERY_DEPTH, + MAX_NEIGHBORHOOD_DEPTH as MAX_EGO_DEPTH, + VIRTUAL_ROOT_ID, +} from "./reader.js"; interface DocumentRow { id: number; @@ -42,97 +41,49 @@ interface MetricsRow { } /** - * Nodes, both adjacency directions and degrees, straight from `links` — no - * derived table involved. Every mode that walks the graph per request (ego, - * arbitrary-root discovery, orphan detection) runs off this, so those modes - * keep working before the first precompute. + * The CLI's nodes, in document id order, over the reader's link structure. + * Degrees and walks come straight from `links` — no derived table involved — + * so the ego, explicit-root discovery and orphan modes keep working before the + * first precompute. */ -interface Adjacency { +interface CliGraph { + reader: GraphReader; docs: Map; - idByPath: Map; out: Map; in: Map; edges: GraphEdgeRecord[]; } -function loadAdjacency(db: Database): Adjacency { +/** Every CLI graph read selects the CLI profile here, and only here. */ +function cliReader(db: Database): GraphReader { + return new GraphReader(db, CLI_GRAPH_PROFILE); +} + +function openGraph(db: Database): CliGraph { + const reader = cliReader(db); const docs = new Map(); - const idByPath = new Map(); const rows = db .prepare( - `SELECT id, path, title, type, updated - FROM documents WHERE asset_type = 'markdown' ORDER BY id` + `SELECT d.id AS id, d.path AS path, d.title AS title, d.type AS type, d.updated AS updated + FROM documents d WHERE ${reader.scope} ORDER BY d.id` ) .all() as DocumentRow[]; - for (const row of rows) { - docs.set(row.id, row); - idByPath.set(row.path, row.id); - } - - const out = new Map(); - const inbound = new Map(); - const edges: GraphEdgeRecord[] = []; - const seen = new Set(); - - const linkRows = db - .prepare( - `SELECT source_id AS source, target_id AS target - FROM links WHERE target_id IS NOT NULL ORDER BY source_id, target_id` - ) - .all() as { source: number; target: number }[]; - - for (const link of linkRows) { - if (!docs.has(link.source) || !docs.has(link.target)) continue; - if (link.source === link.target) continue; - const key = `${link.source}>${link.target}`; - if (seen.has(key)) continue; - seen.add(key); - - edges.push({ source: link.source, target: link.target }); - - const outbound = out.get(link.source); - if (outbound) outbound.push(link.target); - else out.set(link.source, [link.target]); - - const incoming = inbound.get(link.target); - if (incoming) incoming.push(link.source); - else inbound.set(link.target, [link.source]); - } - - return { docs, idByPath, out, in: inbound, edges }; -} - -function neighbors(adjacency: Adjacency, id: number, direction: GraphDirection): number[] { - if (direction === "out") return adjacency.out.get(id) ?? []; - if (direction === "in") return adjacency.in.get(id) ?? []; - return [...(adjacency.out.get(id) ?? []), ...(adjacency.in.get(id) ?? [])]; -} - -/** - * A read-only connection never runs migrations, so these tables are simply - * absent on a pre-v8 database. Missing derived data degrades every mode to the - * links-only view rather than failing the command. - */ -function queryOrEmpty(db: Database, sql: string, params: unknown[] = []): T[] { - try { - return db.prepare(sql).all(...(params as never[])) as T[]; - } catch { - return []; - } + for (const row of rows) docs.set(row.id, row); + const links = reader.links(); + return { reader, docs, out: links.out, in: links.in, edges: links.edges }; } -function loadMetrics(db: Database): Map { +function loadMetrics(graph: CliGraph): Map { const metrics = new Map(); - for (const row of queryOrEmpty(db, "SELECT * FROM graph_metrics")) { + for (const row of graph.reader.derived("SELECT * FROM graph_metrics")) { metrics.set(row.document_id, row); } return metrics; } -function loadLayout(db: Database, mode = "clusters"): Map { +function loadLayout(graph: CliGraph, mode = "clusters"): Map { const layout = new Map(); - const rows = queryOrEmpty<{ id: number; x: number; y: number }>( - db, + const rows = graph.reader.derived<{ id: number; x: number; y: number }>( "SELECT document_id AS id, x, y FROM graph_layouts WHERE mode = ?", [mode] ); @@ -143,7 +94,7 @@ function loadLayout(db: Database, mode = "clusters"): Map = {} ): GraphQueryNode { @@ -152,8 +103,8 @@ function toNode( path: doc.path, title: doc.title, type: doc.type, - inDegree: metrics?.in_degree ?? (adjacency.in.get(doc.id) ?? []).length, - outDegree: metrics?.out_degree ?? (adjacency.out.get(doc.id) ?? []).length, + inDegree: metrics?.in_degree ?? (graph.in.get(doc.id) ?? []).length, + outDegree: metrics?.out_degree ?? (graph.out.get(doc.id) ?? []).length, }; if (metrics) { if (metrics.community !== null) node.community = metrics.community; @@ -162,9 +113,19 @@ function toNode( return { ...node, ...extra }; } -/** Edges with both endpoints inside `ids`. */ -function inducedEdges(adjacency: Adjacency, ids: Set): GraphEdgeRecord[] { - return adjacency.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target)); +function degree(graph: CliGraph, id: number): number { + return (graph.out.get(id) ?? []).length + (graph.in.get(id) ?? []).length; +} + +const EMPTY: () => GraphSubgraph = () => ({ nodes: [], edges: [], truncated: false }); + +/** Nodes for every reached id, in walk order, with edges among them. */ +function walkScene(graph: CliGraph, walk: Walk, cap: number): GraphSubgraph { + const metrics = loadMetrics(graph); + const nodes = [...walk.distances.entries()].map(([id, distance]) => + toNode(graph.docs.get(id)!, graph, metrics.get(id), { distance }) + ); + return graph.reader.scene(nodes, graph.edges, cap, walk.truncated); } export interface ClusterGraphOptions { @@ -179,27 +140,22 @@ export interface ClusterGraphOptions { * first v8 index run — the caller reports that, this returns no rows. */ export function getClusterGraph(db: Database, options: ClusterGraphOptions = {}): GraphSubgraph { - const adjacency = loadAdjacency(db); - const metrics = loadMetrics(db); - const layout = loadLayout(db); - const includeIsolates = options.includeIsolates ?? true; + const graph = openGraph(db); + const metrics = loadMetrics(graph); + const layout = loadLayout(graph); + const includeIsolates = graph.reader.includeIsolates(options.includeIsolates); const nodes: GraphQueryNode[] = []; - const ids = new Set(); - for (const doc of adjacency.docs.values()) { + for (const doc of graph.docs.values()) { const nodeMetrics = metrics.get(doc.id); if (options.community !== undefined && nodeMetrics?.community !== options.community) continue; - - const degree = - (adjacency.out.get(doc.id) ?? []).length + (adjacency.in.get(doc.id) ?? []).length; - if (!includeIsolates && degree === 0) continue; + if (!includeIsolates && degree(graph, doc.id) === 0) continue; const position = layout.get(doc.id); - nodes.push(toNode(doc, adjacency, nodeMetrics, position ? { x: position.x, y: position.y } : {})); - ids.add(doc.id); + nodes.push(toNode(doc, graph, nodeMetrics, position ? { x: position.x, y: position.y } : {})); } - return { nodes, edges: inducedEdges(adjacency, ids), truncated: false }; + return graph.reader.scene(nodes, graph.edges, graph.reader.profile.sceneNodes); } export interface EgoGraphOptions { @@ -214,34 +170,12 @@ export interface EgoGraphOptions { * one mode that works against a database that has never been precomputed. */ export function getEgoGraph(db: Database, options: EgoGraphOptions): GraphSubgraph { - const adjacency = loadAdjacency(db); - const metrics = loadMetrics(db); - const depth = Math.min(Math.max(options.depth ?? 1, 1), MAX_EGO_DEPTH); - const direction = options.direction ?? "both"; - - const centerId = adjacency.idByPath.get(options.center); - if (centerId === undefined) return { nodes: [], edges: [], truncated: false }; - - const distances = new Map([[centerId, 0]]); - let frontier = [centerId]; - for (let hop = 1; hop <= depth && frontier.length > 0; hop++) { - const next: number[] = []; - for (const id of frontier) { - for (const neighbor of neighbors(adjacency, id, direction)) { - if (distances.has(neighbor)) continue; - distances.set(neighbor, hop); - next.push(neighbor); - } - } - frontier = next; - } - - const ids = new Set(distances.keys()); - const nodes = [...distances.entries()].map(([id, distance]) => - toNode(adjacency.docs.get(id)!, adjacency, metrics.get(id), { distance }) - ); + const graph = openGraph(db); + const centerId = graph.reader.lookup(options.center); + if (centerId === null) return EMPTY(); - return { nodes, edges: inducedEdges(adjacency, ids), truncated: false }; + const walk = graph.reader.neighborhood(centerId, options.depth, options.direction); + return walkScene(graph, walk, graph.reader.profile.neighborhoodNodes); } export interface DiscoveryGraphOptions { @@ -261,73 +195,49 @@ export function getDiscoveryGraph( db: Database, options: DiscoveryGraphOptions = {} ): GraphSubgraph { - const adjacency = loadAdjacency(db); - const metrics = loadMetrics(db); - const direction = options.direction ?? "out"; - const maxDepth = Math.min(Math.max(options.maxDepth ?? MAX_DISCOVERY_DEPTH, 1), MAX_DISCOVERY_DEPTH); + const graph = openGraph(db); + const maxDepth = graph.reader.discoveryDepth(options.maxDepth); if (options.root) { - const rootId = adjacency.idByPath.get(options.root); - if (rootId === undefined) return { nodes: [], edges: [], truncated: false }; - - const distances = new Map([[rootId, 0]]); - let frontier = [rootId]; - for (let hop = 1; hop <= maxDepth && frontier.length > 0; hop++) { - const next: number[] = []; - for (const id of frontier) { - for (const neighbor of neighbors(adjacency, id, direction)) { - if (distances.has(neighbor)) continue; - distances.set(neighbor, hop); - next.push(neighbor); - } - } - frontier = next; - } + const rootId = graph.reader.lookup(options.root); + if (rootId === null) return EMPTY(); - const ids = new Set(distances.keys()); - const nodes = [...distances.entries()].map(([id, distance]) => - toNode(adjacency.docs.get(id)!, adjacency, metrics.get(id), { distance }) - ); - return { nodes, edges: inducedEdges(adjacency, ids), truncated: false }; + const walk = graph.reader.discovery(rootId, maxDepth, options.direction); + return walkScene(graph, walk, graph.reader.profile.sceneNodes); } - const rootKey = getGraphMetaValue(db, "graph_root"); - const rows = queryOrEmpty<{ id: number; distance: number; parentId: number | null }>( - db, - "SELECT document_id AS id, distance, parent_id AS parentId FROM graph_root_distances" - ); - + const metrics = loadMetrics(graph); + const root = parseGraphRootKey(getGraphMetaValue(db, "graph_root")); const nodes: GraphQueryNode[] = []; const ids = new Set(); - for (const row of rows) { - const doc = adjacency.docs.get(row.id); - if (!doc || row.distance > maxDepth) continue; - nodes.push(toNode(doc, adjacency, metrics.get(row.id), { distance: row.distance })); - ids.add(row.id); + for (const [id, distance] of graph.reader.rootDistances()) { + const doc = graph.docs.get(id); + if (!doc || distance > maxDepth) continue; + nodes.push(toNode(doc, graph, metrics.get(id), { distance })); + ids.add(id); } - const edges = inducedEdges(adjacency, ids); - - // A virtual root is drawn from its recorded seed list; an indexed root is - // already one of the nodes above at distance 0. - if (rootKey?.startsWith("virtual:")) { - const path = rootKey.slice("virtual:".length); + // A virtual root is drawn from its recorded seed list, after the edges + // between documents; an indexed root is already one of the nodes above at + // distance 0. + const edges = [...graph.edges]; + if (root?.virtual) { nodes.unshift({ id: VIRTUAL_ROOT_ID, - path, - title: path, + path: root.path, + title: root.path, type: "index", inDegree: 0, outDegree: 0, distance: 0, virtual: true, }); - for (const seedId of readRootLinks(db)) { + for (const seedId of graph.reader.rootLinks(getGraphMetaValue(db, "graph_root_links"))) { if (ids.has(seedId)) edges.push({ source: VIRTUAL_ROOT_ID, target: seedId }); } } - return { nodes, edges, truncated: false }; + return graph.reader.scene(nodes, edges, graph.reader.profile.sceneNodes); } export interface MaintenanceOptions { @@ -355,44 +265,31 @@ export function getMaintenanceFindings( db: Database, options: MaintenanceOptions = {} ): MaintenanceFindings { - const adjacency = loadAdjacency(db); - const metrics = loadMetrics(db); - const staleDays = options.staleDays ?? DEFAULT_STALE_DAYS; + const graph = openGraph(db); + const metrics = loadMetrics(graph); + const staleDays = graph.reader.staleDays(options.staleDays); const root = getGraphMetaValue(db, "graph_root"); const cutoff = new Date(Date.now() - staleDays * 86_400_000).toISOString().split("T")[0]; const orphans: GraphQueryNode[] = []; const stale: (GraphQueryNode & { updated: string })[] = []; - for (const doc of adjacency.docs.values()) { - const degree = - (adjacency.out.get(doc.id) ?? []).length + (adjacency.in.get(doc.id) ?? []).length; - if (degree === 0) orphans.push(toNode(doc, adjacency, metrics.get(doc.id))); + for (const doc of graph.docs.values()) { + if (degree(graph, doc.id) === 0) orphans.push(toNode(doc, graph, metrics.get(doc.id))); if (doc.updated < cutoff) { - stale.push({ ...toNode(doc, adjacency, metrics.get(doc.id)), updated: doc.updated }); + stale.push({ ...toNode(doc, graph, metrics.get(doc.id)), updated: doc.updated }); } } const unreachable: GraphQueryNode[] = []; if (root) { - const reachable = new Set( - queryOrEmpty<{ id: number }>(db, "SELECT document_id AS id FROM graph_root_distances").map( - (row) => row.id - ) - ); - for (const doc of adjacency.docs.values()) { - if (!reachable.has(doc.id)) unreachable.push(toNode(doc, adjacency, metrics.get(doc.id))); + const reachable = graph.reader.rootDistances(); + for (const doc of graph.docs.values()) { + if (!reachable.has(doc.id)) unreachable.push(toNode(doc, graph, metrics.get(doc.id))); } } - const brokenLinks = db - .prepare( - `SELECT d.path AS sourcePath, l.target AS target - FROM links l JOIN documents d ON d.id = l.source_id - WHERE l.target_id IS NULL - ORDER BY d.path, l.target` - ) - .all() as { sourcePath: string; target: string }[]; + const brokenLinks = graph.reader.brokenLinks(); return { staleDays, root, orphans, unreachable, brokenLinks, stale }; } @@ -412,13 +309,13 @@ export interface GraphStats { /** Everything `brain graph stats` reports, straight out of the derived tables. */ export function getGraphStats(db: Database): GraphStats { - const communities = queryOrEmpty<{ + const reader = cliReader(db); + const communities = reader.derived<{ community: number; size: number; label: string | null; topTerms: string | null; }>( - db, "SELECT community, size, label, top_terms AS topTerms FROM graph_communities ORDER BY size DESC, community ASC" ).map((row) => ({ community: row.community, @@ -427,7 +324,7 @@ export function getGraphStats(db: Database): GraphStats { topTerms: parseJsonArray(row.topTerms), })); - const count = (sql: string): number => queryOrEmpty<{ n: number }>(db, sql)[0]?.n ?? 0; + const count = (sql: string): number => reader.derived<{ n: number }>(sql)[0]?.n ?? 0; const algoRaw = getGraphMetaValue(db, "graph_algo"); let algo: unknown = null; @@ -445,13 +342,7 @@ export function getGraphStats(db: Database): GraphStats { nodes: count("SELECT COUNT(*) AS n FROM graph_metrics"), // Counted the way the graph counts them — deduped, self-links dropped, and // links into binary assets excluded — so this agrees with `graph compute`. - edges: count( - `SELECT COUNT(*) AS n FROM ( - SELECT DISTINCT l.source_id, l.target_id FROM links l - JOIN documents s ON s.id = l.source_id AND s.asset_type = 'markdown' - JOIN documents t ON t.id = l.target_id AND t.asset_type = 'markdown' - WHERE l.source_id <> l.target_id)` - ), + edges: count(`SELECT COUNT(*) AS n FROM (${reader.edgeSql})`), brokenLinks: count("SELECT COUNT(*) AS n FROM links WHERE target_id IS NULL"), components: count("SELECT COUNT(DISTINCT component) AS n FROM graph_metrics"), reachable: count("SELECT COUNT(*) AS n FROM graph_root_distances"), @@ -471,17 +362,6 @@ function parseJsonArray(raw: string | null): string[] { } } -function readRootLinks(db: Database): number[] { - const raw = getGraphMetaValue(db, "graph_root_links"); - if (!raw) return []; - try { - const parsed = JSON.parse(raw); - return Array.isArray(parsed) ? parsed.map(Number).filter(Number.isInteger) : []; - } catch { - return []; - } -} - function getGraphMetaValue(db: Database, key: string): string | null { const row = db.prepare("SELECT value FROM index_metadata WHERE key = ?").get(key) as | { value: string } diff --git a/packages/core/src/lib/graph/reader.ts b/packages/core/src/lib/graph/reader.ts new file mode 100644 index 0000000000..1432f78adf --- /dev/null +++ b/packages/core/src/lib/graph/reader.ts @@ -0,0 +1,360 @@ +/** + * The one reader over the derived graph tables, behind both read surfaces in + * core: the `brain graph` CLI (`./queries.ts`) and the supported `./queries` + * API (`../../queries/graph.ts`), whose graph semantics are the former UI + * server's. Each surface selects a concrete profile below; profiles are not a + * public option and not an extension point (#1354). + * + * The reader owns the mechanics both surfaces share: which documents are + * nodes, the distinct edge list and its adjacency, path lookup, the + * breadth-first walk, depth/staleness defaults and bounds, the precomputed + * root distances, broken links and the scene caps. The adapters own their + * result shapes and error policy, which differ on purpose: + * + * - Node scope. The UI counts a NULL `asset_type` as markdown; the CLI + * requires `'markdown'`, as the precompute does. + * - Edge order. The CLI sorts edges by (source, target); the UI keeps the + * engine's DISTINCT order. + * - Caps. The UI bounds a neighborhood walk and scene at 1,500 nodes and every + * other scene at 5,000 nodes / 20,000 edges, ranked by pagerank, and reports + * `truncated`; it also limits each maintenance list to 5,000. The CLI has no + * cap or walk budget anywhere, so its `truncated` is always false. + * - Isolates. UI clusters exclude isolates unless asked; CLI clusters include + * them unless asked. (The UI judges isolation by precomputed degree, the CLI + * by the live links — that, like node degrees and layout fields, is node + * materialization and stays with each adapter.) + * - Paths and missing nodes. The UI strips a leading `./` or `/` and fails a + * missing center or root with `not_found`; the CLI matches the stored path + * exactly and returns an empty subgraph. + * - Old and uncomputed data. The UI refuses derived modes before v8 or before + * a precompute; the CLI reads whatever exists, degrading a missing derived + * table to no rows. + * - `staleDays`. Both default to 180; the UI clamps to 1..3650, the CLI takes + * the value as given. The UI accepts a caller clock and compares the date + * prefix in SQL; the CLI uses the system clock and the whole string. + * - Root seed list. The UI keeps finite JSON numbers; the CLI coerces entries + * to integers. + * + * Every table read here is governed by docs/integration-contract.md. + */ + +import type { Database } from "bun:sqlite"; + +import type { GraphDirection, GraphEdgeRecord } from "./types.js"; + +/** Depth beyond this stops being a neighbourhood and becomes the whole vault. */ +export const MAX_NEIGHBORHOOD_DEPTH = 3; +/** Discovery rings past this are noise at any realistic corpus size. */ +export const MAX_DISCOVERY_DEPTH = 8; +/** Default staleness horizon, matching the core taxonomy default. */ +export const DEFAULT_STALE_DAYS = 180; +/** The synthesized virtual-root node; no document carries id 0. */ +export const VIRTUAL_ROOT_ID = 0; + +const VIRTUAL_ROOT_PREFIX = "virtual:"; + +export interface GraphProfile { + /** SQL predicate selecting graph nodes from a `documents` alias. */ + nodeScope(alias: string): string; + /** Appended to the distinct edge query. */ + edgeOrder: string; + /** Strip a leading `./` or `/` before looking a path up. */ + normalizePaths: boolean; + /** Cluster isolates when the caller does not say. */ + isolatesByDefault: boolean; + /** Walk budget and scene node cap for a neighborhood. */ + neighborhoodNodes: number; + /** Walk budget and scene node cap for every other scene. */ + sceneNodes: number; + sceneEdges: number; + /** Row limit for each maintenance list; Infinity for none. */ + findingLimit: number; + /** Inclusive staleDays bounds, or null to take the value as given. */ + staleDays: { min: number; max: number } | null; + /** How the precomputed root seed list is read. */ + rootLinks: "finite" | "integer"; + /** Whether a missing derived table reads as no rows instead of failing. */ + degradeDerived: boolean; +} + +/** The supported `./queries` graph: the former UI server's reader. */ +export const UI_GRAPH_PROFILE: GraphProfile = Object.freeze({ + nodeScope: (alias: string) => `COALESCE(${alias}.asset_type, 'markdown') = 'markdown'`, + edgeOrder: "", + normalizePaths: true, + isolatesByDefault: false, + neighborhoodNodes: 1500, + sceneNodes: 5000, + sceneEdges: 20000, + findingLimit: 5000, + staleDays: Object.freeze({ min: 1, max: 3650 }), + rootLinks: "finite", + degradeDerived: false, +}); + +/** `brain graph export` and `brain graph stats`. */ +export const CLI_GRAPH_PROFILE: GraphProfile = Object.freeze({ + nodeScope: (alias: string) => `${alias}.asset_type = 'markdown'`, + edgeOrder: " ORDER BY source, target", + normalizePaths: false, + isolatesByDefault: true, + neighborhoodNodes: Infinity, + sceneNodes: Infinity, + sceneEdges: Infinity, + findingLimit: Infinity, + staleDays: null, + rootLinks: "integer", + degradeDerived: true, +}); + +/** The distinct edge list plus adjacency in both directions, in edge order. */ +export interface LinkStructure { + edges: GraphEdgeRecord[]; + out: Map; + in: Map; +} + +export interface Walk { + /** Hops from the start, in the order nodes were reached. */ + distances: Map; + /** The walk stopped at its node budget. */ + truncated: boolean; +} + +export interface Scene { + nodes: N[]; + edges: GraphEdgeRecord[]; + truncated: boolean; +} + +export interface GraphRootKey { + path: string; + virtual: boolean; +} + +/** Ranking inputs for a capped scene. */ +interface RankedNode { + id: number; + pagerank?: number; + virtual?: boolean; +} + +/** + * One request's read of the graph on a connection the caller owns: the + * supported API's root-bound snapshot or the CLI's resolved database. The + * reader never opens, closes or writes a connection. + */ +export class GraphReader { + private structure: LinkStructure | undefined; + + constructor( + private readonly db: Database, + readonly profile: GraphProfile + ) {} + + /** The node predicate over `documents d`. */ + get scope(): string { + return this.profile.nodeScope("d"); + } + + /** + * One edge per distinct (source, target) document pair — two wiki links that + * resolve to the same note are one edge — with self-links dropped and both + * ends graph nodes. Shared by the adjacency load and the edge counts so + * every count agrees with the edges drawn. + */ + get edgeSql(): string { + return `SELECT DISTINCT l.source_id AS source, l.target_id AS target + FROM links l + JOIN documents d ON d.id = l.source_id AND ${this.profile.nodeScope("d")} + JOIN documents t ON t.id = l.target_id AND ${this.profile.nodeScope("t")} + WHERE l.target_id IS NOT NULL AND l.target_id <> l.source_id${this.profile.edgeOrder}`; + } + + /** Loaded once per reader, straight from `links`: no derived table needed. */ + links(): LinkStructure { + if (this.structure) return this.structure; + const edges = this.db.query(this.edgeSql).all(); + const out = new Map(); + const inbound = new Map(); + for (const edge of edges) { + push(out, edge.source, edge.target); + push(inbound, edge.target, edge.source); + } + this.structure = { edges, out, in: inbound }; + return this.structure; + } + + /** The node id at `path`, or null when no graph node has it. */ + lookup(path: string): number | null { + const key = this.profile.normalizePaths ? path.replace(/^\.?\//, "") : path; + const row = this.db + .query<{ id: number }, [string]>(`SELECT d.id AS id FROM documents d WHERE ${this.scope} AND d.path = ?`) + .get(key); + return row?.id ?? null; + } + + /** Breadth-first, level by level, stopping at `maxDepth` hops or `budget` nodes. */ + walk(start: number, direction: GraphDirection, maxDepth: number, budget: number): Walk { + const structure = this.links(); + const distances = new Map([[start, 0]]); + let frontier = [start]; + let depth = 0; + let truncated = false; + while (frontier.length > 0 && depth < maxDepth && !truncated) { + depth++; + const next: number[] = []; + for (const id of frontier) { + const neighbors: number[] = []; + if (direction !== "in") neighbors.push(...(structure.out.get(id) ?? [])); + if (direction !== "out") neighbors.push(...(structure.in.get(id) ?? [])); + for (const neighbor of neighbors) { + if (distances.has(neighbor)) continue; + if (distances.size >= budget) { + truncated = true; + break; + } + distances.set(neighbor, depth); + next.push(neighbor); + } + if (truncated) break; + } + frontier = next; + } + return { distances, truncated }; + } + + /** The ego walk: depth 1..3 (default 1), both directions by default. */ + neighborhood(center: number, depth?: number, direction?: GraphDirection): Walk { + return this.walk( + center, + direction ?? "both", + clamp(depth ?? 1, 1, MAX_NEIGHBORHOOD_DEPTH), + this.profile.neighborhoodNodes + ); + } + + /** Depth 1..8, default 8. */ + discoveryDepth(maxDepth?: number): number { + return clamp(maxDepth ?? MAX_DISCOVERY_DEPTH, 1, MAX_DISCOVERY_DEPTH); + } + + /** The discovery walk from an explicit root, outbound by default. */ + discovery(root: number, maxDepth: number, direction?: GraphDirection): Walk { + return this.walk(root, direction ?? "out", maxDepth, this.profile.sceneNodes); + } + + includeIsolates(requested?: boolean): boolean { + return requested ?? this.profile.isolatesByDefault; + } + + staleDays(requested?: number): number { + const days = requested ?? DEFAULT_STALE_DAYS; + const bounds = this.profile.staleDays; + return bounds ? clamp(days, bounds.min, bounds.max) : days; + } + + /** + * Precomputed distances from the default root, in table order, optionally + * limited to `maxDepth`. Direction does not apply: the precomputed walk is + * the one that was run. + */ + rootDistances(maxDepth?: number): Map { + const rows = + maxDepth === undefined + ? this.derived<{ id: number; distance: number }>( + "SELECT document_id AS id, distance FROM graph_root_distances" + ) + : this.derived<{ id: number; distance: number }>( + "SELECT document_id AS id, distance FROM graph_root_distances WHERE distance <= ?", + [maxDepth] + ); + return new Map(rows.map((row) => [row.id, row.distance])); + } + + /** The precomputed virtual root's seed ids from `graph_root_links`. */ + rootLinks(raw: string | null | undefined): number[] { + if (!raw) return []; + try { + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed)) return []; + return this.profile.rootLinks === "integer" + ? parsed.map(Number).filter(Number.isInteger) + : parsed.filter((id): id is number => Number.isFinite(id)); + } catch { + return []; + } + } + + /** Unresolved wiki links with their literal text, by source path then text. */ + brokenLinks(): { sourcePath: string; target: string }[] { + const limit = this.profile.findingLimit; + const sql = `SELECT d.path AS sourcePath, l.target AS target + FROM links l JOIN documents d ON d.id = l.source_id + WHERE l.target_id IS NULL + ORDER BY d.path ASC, l.target ASC`; + return Number.isFinite(limit) + ? this.db.query<{ sourcePath: string; target: string }, [number]>(`${sql} LIMIT ?`).all(limit) + : this.db.query<{ sourcePath: string; target: string }, []>(sql).all(); + } + + /** + * Narrows `edges` to the ones between kept nodes, applying the profile's + * caps. Over the node cap the highest-pagerank nodes survive (a virtual root + * always does — dropping the thing the view is rooted on would be + * nonsense); over the edge cap, the edges whose weaker end ranks highest. + */ + scene(nodes: N[], edges: GraphEdgeRecord[], nodeCap: number, walkTruncated = false): Scene { + let truncated = false; + let keptNodes = nodes; + if (nodes.length > nodeCap) { + truncated = true; + keptNodes = [...nodes] + .sort((a, b) => Number(b.virtual ?? false) - Number(a.virtual ?? false) || (b.pagerank ?? 0) - (a.pagerank ?? 0)) + .slice(0, nodeCap); + } + const ids = new Set(keptNodes.map((n) => n.id)); + let keptEdges = edges.filter((e) => ids.has(e.source) && ids.has(e.target)); + if (keptEdges.length > this.profile.sceneEdges) { + truncated = true; + const rank = new Map(keptNodes.map((n) => [n.id, n.pagerank ?? 0])); + keptEdges = keptEdges + .map((edge) => ({ edge, weight: Math.min(rank.get(edge.source) ?? 0, rank.get(edge.target) ?? 0) })) + .sort((a, b) => b.weight - a.weight) + .slice(0, this.profile.sceneEdges) + .map((entry) => entry.edge); + } + return { nodes: keptNodes, edges: keptEdges, truncated: truncated || walkTruncated }; + } + + /** + * A read of a derived (v8) table. A read-only connection never migrates, so + * on an older database the table is absent; a degrading profile reads that + * as no rows. + */ + derived(sql: string, params: (string | number)[] = []): T[] { + if (!this.profile.degradeDerived) return this.db.query(sql).all(...params); + try { + return this.db.prepare(sql).all(...params); + } catch { + return []; + } + } +} + +/** `graph_root` metadata: an indexed path, or `virtual:`. */ +export function parseGraphRootKey(raw: string | null | undefined): GraphRootKey | null { + if (!raw) return null; + if (raw.startsWith(VIRTUAL_ROOT_PREFIX)) return { path: raw.slice(VIRTUAL_ROOT_PREFIX.length), virtual: true }; + return { path: raw, virtual: false }; +} + +function push(map: Map, key: number, value: number): void { + const existing = map.get(key); + if (existing) existing.push(value); + else map.set(key, [value]); +} + +function clamp(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)); +} diff --git a/packages/core/src/queries/graph.ts b/packages/core/src/queries/graph.ts index 8167f7ad26..546e773904 100644 --- a/packages/core/src/queries/graph.ts +++ b/packages/core/src/queries/graph.ts @@ -1,14 +1,18 @@ -/** Private UI-profile graph mechanics; core CLI graph defaults remain independent. */ +/** + * The supported `./queries` graph modes: the UI profile of the shared graph + * reader (`GraphReader`, `../lib/graph/reader.ts`). This adapter owns the + * result shapes, node materialization and typed failures; the reader's header + * lists every way this profile differs from the `brain graph` CLI. + */ import type { Database } from "bun:sqlite"; import { basename } from "path"; -import type { Node, Edge, Community, GraphMeta, Subgraph, Maintenance, Direction } from "./types.js"; +import type { Node, Community, GraphMeta, Subgraph, Maintenance, Direction } from "./types.js"; import { QueryFailure } from "./snapshot.js"; -const MAX_NODES = 5000; -const MAX_EDGES = 20000; -const MAX_NEIGHBORHOOD_NODES = 1500; -const MAX_NEIGHBORHOOD_DEPTH = 3; -const MAX_DISCOVERY_DEPTH = 8; -const DEFAULT_STALE_DAYS = 180; +import { GraphReader, UI_GRAPH_PROFILE, VIRTUAL_ROOT_ID, parseGraphRootKey } from "../lib/graph/reader.js"; +/** Every supported graph read selects the UI profile here, and only here. */ +function reader(db: Database): GraphReader { + return new GraphReader(db, UI_GRAPH_PROFILE); +} function requireComputedGraph(meta: Map): void { if (!meta.get("graph_computed_at")) throw new QueryFailure("not_computed"); @@ -27,7 +31,7 @@ interface NodeRow { y: number | null; } /** Only markdown notes are graph nodes; other assets carry no wiki links. */ -const MARKDOWN_ONLY = "COALESCE(d.asset_type, 'markdown') = 'markdown'"; +const MARKDOWN_ONLY = UI_GRAPH_PROFILE.nodeScope("d"); /** * The analytical columns come from tables that do not exist below schema v8, * so the select degrades to literals — that is what keeps the neighborhood @@ -82,119 +86,11 @@ function loadNodesByIds(db: Database, ids: number[], withGraphTables: boolean): } return out; } -function lookupDocumentId(db: Database, path: string): number { - const normalized = path.replace(/^\.?\//, ""); - const row = db - .query<{ - id: number; - }, [ - string - ]>(`SELECT d.id AS id FROM documents d WHERE ${MARKDOWN_ONLY} AND d.path = ?`) - .get(normalized); - if (!row) +function lookupDocumentId(graph: GraphReader, path: string): number { + const id = graph.lookup(path); + if (id === null) throw new QueryFailure("not_found"); - return row.id; -} -// --- link structure -------------------------------------------------------- -interface LinkStructure { - edges: Edge[]; - out: Map; - in: Map; -} -/** - * The one definition of an edge, shared by the adjacency load and the meta - * count so /api/graph/meta agrees with `brain graph stats`: one edge per - * distinct (source, target) DOCUMENT pair — two wiki links that resolve to the - * same note are one edge — self-links dropped, and both ends markdown, since - * non-markdown assets are not graph nodes. - */ -const DISTINCT_EDGES_SQL = `SELECT DISTINCT l.source_id AS source, l.target_id AS target - FROM links l - JOIN documents d ON d.id = l.source_id AND ${MARKDOWN_ONLY} - JOIN documents t ON t.id = l.target_id AND COALESCE(t.asset_type, 'markdown') = 'markdown' - WHERE l.target_id IS NOT NULL AND l.target_id <> l.source_id`; -/** The whole link table as an edge list plus adjacency maps in both directions. */ -function loadLinkStructure(db: Database): LinkStructure { - const edges = db.query(DISTINCT_EDGES_SQL).all(); - const out = new Map(); - const inbound = new Map(); - for (const edge of edges) { - push(out, edge.source, edge.target); - push(inbound, edge.target, edge.source); - } - return { edges, out, in: inbound }; -} -function push(map: Map, key: number, value: number): void { - const existing = map.get(key); - if (existing) - existing.push(value); - else - map.set(key, [value]); -} -interface BfsResult { - distances: Map; - truncated: boolean; -} -/** Breadth-first walk, level by level, stopping at `maxDepth` or `limit` nodes. */ -function bfs(structure: LinkStructure, start: number, direction: Direction, maxDepth: number, limit: number): BfsResult { - const distances = new Map([[start, 0]]); - let frontier = [start]; - let depth = 0; - let truncated = false; - while (frontier.length > 0 && depth < maxDepth && !truncated) { - depth++; - const next: number[] = []; - for (const id of frontier) { - const neighbors: number[] = []; - if (direction !== "in") - neighbors.push(...(structure.out.get(id) ?? [])); - if (direction !== "out") - neighbors.push(...(structure.in.get(id) ?? [])); - for (const neighbor of neighbors) { - if (distances.has(neighbor)) - continue; - if (distances.size >= limit) { - truncated = true; - break; - } - distances.set(neighbor, depth); - next.push(neighbor); - } - if (truncated) - break; - } - frontier = next; - } - return { distances, truncated }; -} -// --- caps ------------------------------------------------------------------ -/** - * Trims a subgraph to the response caps, keeping the highest-pagerank nodes - * (a virtual root always survives — dropping the thing the view is rooted on - * would be nonsense). Edges are then filtered to the surviving node set, which - * is also how a whole-corpus edge list is narrowed to the requested subgraph. - */ -function applyCaps(nodes: Node[], edges: Edge[], maxNodes: number): Subgraph { - let truncated = false; - let keptNodes = nodes; - if (nodes.length > maxNodes) { - truncated = true; - keptNodes = [...nodes] - .sort((a, b) => Number(b.virtual ?? false) - Number(a.virtual ?? false) || (b.pagerank ?? 0) - (a.pagerank ?? 0)) - .slice(0, maxNodes); - } - const ids = new Set(keptNodes.map((n) => n.id)); - let keptEdges = edges.filter((e) => ids.has(e.source) && ids.has(e.target)); - if (keptEdges.length > MAX_EDGES) { - truncated = true; - const rank = new Map(keptNodes.map((n) => [n.id, n.pagerank ?? 0])); - keptEdges = keptEdges - .map((edge) => ({ edge, weight: Math.min(rank.get(edge.source) ?? 0, rank.get(edge.target) ?? 0) })) - .sort((a, b) => b.weight - a.weight) - .slice(0, MAX_EDGES) - .map((entry) => entry.edge); - } - return { nodes: keptNodes, edges: keptEdges, truncated }; + return id; } // --- meta ------------------------------------------------------------------ function countGraph(db: Database): { @@ -203,7 +99,7 @@ function countGraph(db: Database): { } { const edges = db.query<{ c: number; - }, []>(`SELECT COUNT(*) AS c FROM (${DISTINCT_EDGES_SQL})`).get(); + }, []>(`SELECT COUNT(*) AS c FROM (${reader(db).edgeSql})`).get(); return { nodeCount: countMarkdownDocs(db), edgeCount: edges?.c ?? 0 }; } /** @@ -222,29 +118,6 @@ function countMarkdownDocs(db: Database): number { c: number; }, []>(`SELECT COUNT(*) AS c FROM documents d WHERE ${MARKDOWN_ONLY}`).get()?.c ?? 0); } -function parseDefaultRoot(meta: Map): { - path: string; - virtual: boolean; -} | null { - const raw = meta.get("graph_root"); - if (!raw) - return null; - if (raw.startsWith("virtual:")) - return { path: raw.slice("virtual:".length), virtual: true }; - return { path: raw, virtual: false }; -} -function parseRootLinks(meta: Map): number[] { - const raw = meta.get("graph_root_links"); - if (!raw) - return []; - try { - const parsed = JSON.parse(raw); - return Array.isArray(parsed) ? parsed.filter((id): id is number => Number.isFinite(id)) : []; - } - catch { - return []; - } -} function readCommunities(db: Database): Community[] { const rows = db .query<{ @@ -299,7 +172,7 @@ export function graphMeta(db: Database, meta: Map, schemaVersion stale: isStale(db, computedAt), ...counts, communities: readCommunities(db), - defaultRoot: parseDefaultRoot(meta), + defaultRoot: parseGraphRootKey(meta.get("graph_root")), }; if (meta.get("graph_layout_skipped") === "1") response.layoutSkipped = true; @@ -326,19 +199,20 @@ export function graphClusters(db: Database, meta: Map, opts: { includeIsolates?: boolean; }): Subgraph { requireComputedGraph(meta); + const graph = reader(db); const filters: string[] = [MARKDOWN_ONLY]; const params: number[] = []; if (opts.community !== undefined) { filters.push("m.community = ?"); params.push(opts.community); } - if (!opts.includeIsolates) { + if (!graph.includeIsolates(opts.includeIsolates)) { filters.push("(COALESCE(m.in_degree, 0) + COALESCE(m.out_degree, 0)) > 0"); } const rows = db .query(`${nodeSelect(true)} WHERE ${filters.join(" AND ")} ORDER BY m.pagerank DESC, d.id ASC`) .all(...params); - return applyCaps(rows.map((row) => toNode(row)), loadLinkStructure(db).edges, MAX_NODES); + return graph.scene(rows.map((row) => toNode(row)), graph.links().edges, graph.profile.sceneNodes); } /** * Deliberately exempt from the schema gate: an ego graph needs nothing but the @@ -350,64 +224,52 @@ export function graphNeighborhood(db: Database, schemaVersion: number, opts: { depth?: number; direction?: Direction; }): Subgraph { - const depth = clamp(opts.depth ?? 1, 1, MAX_NEIGHBORHOOD_DEPTH); - const direction = opts.direction ?? "both"; - const centerId = lookupDocumentId(db, opts.center); + const graph = reader(db); + const centerId = lookupDocumentId(graph, opts.center); const withGraphTables = schemaVersion >= 8; - const structure = loadLinkStructure(db); - const { distances, truncated } = bfs(structure, centerId, direction, depth, MAX_NEIGHBORHOOD_NODES); + const { distances, truncated } = graph.neighborhood(centerId, opts.depth, opts.direction); const rows = loadNodesByIds(db, [...distances.keys()], withGraphTables); const nodes = rows.map((row) => toNode(row, distances.get(row.id))); - const capped = applyCaps(nodes, structure.edges, MAX_NEIGHBORHOOD_NODES); - return { ...capped, truncated: capped.truncated || truncated }; + return graph.scene(nodes, graph.links().edges, graph.profile.neighborhoodNodes, truncated); } export function graphDiscovery(db: Database, meta: Map, opts: { root?: string; direction?: "out" | "both"; maxDepth?: number; }): Subgraph { - const maxDepth = clamp(opts.maxDepth ?? MAX_DISCOVERY_DEPTH, 1, MAX_DISCOVERY_DEPTH); - const direction = opts.direction ?? "out"; + const graph = reader(db); + const maxDepth = graph.discoveryDepth(opts.maxDepth); requireComputedGraph(meta); - const structure = loadLinkStructure(db); + const structure = graph.links(); const total = countMarkdownDocs(db); if (opts.root) { - const rootId = lookupDocumentId(db, opts.root); - const { distances, truncated } = bfs(structure, rootId, direction, maxDepth, MAX_NODES); + const rootId = lookupDocumentId(graph, opts.root); + const { distances, truncated } = graph.discovery(rootId, maxDepth, opts.direction); const rows = loadNodesByIds(db, [...distances.keys()], true); - const capped = applyCaps(rows.map((row) => toNode(row, distances.get(row.id))), structure.edges, MAX_NODES); + const capped = graph.scene(rows.map((row) => toNode(row, distances.get(row.id))), structure.edges, graph.profile.sceneNodes, truncated); // Reach is a property of the graph, not of the scene, so it is measured // by a second walk with no depth window. A BFS can neither exceed the // node count in levels nor in nodes, so `total` bounds both exactly. - const reachable = bfs(structure, rootId, direction, total, total).distances.size; + const reachable = graph.walk(rootId, opts.direction ?? "out", total, total).distances.size; return { ...capped, - truncated: capped.truncated || truncated, reachableCount: reachable, unreachableCount: Math.max(0, total - reachable), }; } // Default root: the distances were computed at index time, so `direction` // does not apply here — the precomputed walk is the one that was run. - const distanceRows = db - .query<{ - document_id: number; - distance: number; - }, [ - number - ]>("SELECT document_id, distance FROM graph_root_distances WHERE distance <= ?") - .all(maxDepth); - const distances = new Map(distanceRows.map((row) => [row.document_id, row.distance])); + const distances = graph.rootDistances(maxDepth); const rows = loadNodesByIds(db, [...distances.keys()], true); const nodes = rows.map((row) => toNode(row, distances.get(row.id))); - const root = parseDefaultRoot(meta); + const root = parseGraphRootKey(meta.get("graph_root")); const edges = [...structure.edges]; if (root?.virtual) { // The entry file is excluded from indexing, so it has no documents row: // the node standing in for it is synthesized here, at id 0. - const rootLinks = parseRootLinks(meta).filter((id) => distances.has(id)); + const rootLinks = graph.rootLinks(meta.get("graph_root_links")).filter((id) => distances.has(id)); nodes.unshift({ - id: 0, + id: VIRTUAL_ROOT_ID, path: root.path, title: basename(root.path), type: "root", @@ -416,9 +278,9 @@ export function graphDiscovery(db: Database, meta: Map, opts: { distance: 0, virtual: true, }); - edges.unshift(...rootLinks.map((id) => ({ source: 0, target: id }))); + edges.unshift(...rootLinks.map((id) => ({ source: VIRTUAL_ROOT_ID, target: id }))); } - const response = applyCaps(nodes, edges, MAX_NODES); + const response: Subgraph = graph.scene(nodes, edges, graph.profile.sceneNodes); if (hasResolvedRoot(meta)) { // Every distance row is one reached DOCUMENT — a virtual root is none, so // this needs no adjustment for the synthesized node. Counted over the @@ -435,7 +297,9 @@ export function graphMaintenance(db: Database, meta: Map, opts: staleDays?: number; now?: string; }): Maintenance { - const staleDays = clamp(opts.staleDays ?? DEFAULT_STALE_DAYS, 1, 3650); + const graph = reader(db); + const staleDays = graph.staleDays(opts.staleDays); + const limit = graph.profile.findingLimit; requireComputedGraph(meta); const orphans = db .query, opts: ]>(`${nodeSelect(true)} WHERE ${MARKDOWN_ONLY} AND COALESCE(m.in_degree, 0) = 0 AND COALESCE(m.out_degree, 0) = 0 ORDER BY d.updated DESC, d.id ASC LIMIT ?`) - .all(MAX_NODES) + .all(limit) .map((row) => toNode(row)); // Keyed on whether a root was RESOLVED, not on whether any note has a // distance: a named root that reached nothing leaves the distances empty, @@ -458,19 +322,9 @@ export function graphMaintenance(db: Database, meta: Map, opts: LEFT JOIN graph_root_distances rd ON rd.document_id = d.id WHERE ${MARKDOWN_ONLY} AND rd.document_id IS NULL ORDER BY m.pagerank DESC, d.id ASC LIMIT ?`) - .all(MAX_NODES) + .all(limit) .map((row) => toNode(row)); - const brokenLinks = db - .query<{ - sourcePath: string; - target: string; - }, [ - number - ]>(`SELECT d.path AS sourcePath, l.target AS target - FROM links l JOIN documents d ON d.id = l.source_id - WHERE l.target_id IS NULL - ORDER BY d.path ASC, l.target ASC LIMIT ?`) - .all(MAX_NODES); + const brokenLinks = graph.brokenLinks(); // `documents.updated` is a date, `indexed_at` a timestamp — compare on the // date prefix so a mix of both formats still sorts correctly. const cutoff = new Date((opts.now === undefined ? Date.now() : Date.parse(opts.now)) - staleDays * 86400000).toISOString().slice(0, 10); @@ -483,10 +337,7 @@ export function graphMaintenance(db: Database, meta: Map, opts: ]>(`${nodeSelect(true, ", d.updated AS updated")} WHERE ${MARKDOWN_ONLY} AND substr(d.updated, 1, 10) < ? ORDER BY d.updated ASC, d.id ASC LIMIT ?`) - .all(cutoff, MAX_NODES) + .all(cutoff, limit) .map((row) => ({ ...toNode(row), updated: row.updated })); return { orphans, unreachable, brokenLinks, stale, staleDays }; } -function clamp(value: number, min: number, max: number): number { - return Math.min(max, Math.max(min, value)); -}