@esankhan3/anvil-knowledge-core 0.4.8 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +1 -1
  2. package/dist/__tests__/change-check-async.test.d.ts +6 -0
  3. package/dist/__tests__/change-check-async.test.d.ts.map +1 -0
  4. package/dist/__tests__/change-check-async.test.js +41 -0
  5. package/dist/__tests__/change-check-async.test.js.map +1 -0
  6. package/dist/__tests__/content-hash-reuse.test.js +9 -0
  7. package/dist/__tests__/content-hash-reuse.test.js.map +1 -1
  8. package/dist/__tests__/cross-repo-detector.test.js +163 -0
  9. package/dist/__tests__/cross-repo-detector.test.js.map +1 -1
  10. package/dist/__tests__/graph-store-queries.test.d.ts +4 -2
  11. package/dist/__tests__/graph-store-queries.test.d.ts.map +1 -1
  12. package/dist/__tests__/graph-store-queries.test.js +95 -4
  13. package/dist/__tests__/graph-store-queries.test.js.map +1 -1
  14. package/dist/__tests__/graph-store-update.test.d.ts +16 -0
  15. package/dist/__tests__/graph-store-update.test.d.ts.map +1 -0
  16. package/dist/__tests__/graph-store-update.test.js +363 -0
  17. package/dist/__tests__/graph-store-update.test.js.map +1 -0
  18. package/dist/__tests__/identifier-bm25.test.js +16 -0
  19. package/dist/__tests__/identifier-bm25.test.js.map +1 -1
  20. package/dist/__tests__/incremental-graph.test.d.ts +6 -0
  21. package/dist/__tests__/incremental-graph.test.d.ts.map +1 -0
  22. package/dist/__tests__/incremental-graph.test.js +55 -0
  23. package/dist/__tests__/incremental-graph.test.js.map +1 -0
  24. package/dist/__tests__/literal-tier-integration.test.js +21 -0
  25. package/dist/__tests__/literal-tier-integration.test.js.map +1 -1
  26. package/dist/__tests__/partial-cycle-chunks.test.d.ts +4 -5
  27. package/dist/__tests__/partial-cycle-chunks.test.d.ts.map +1 -1
  28. package/dist/__tests__/partial-cycle-chunks.test.js +9 -8
  29. package/dist/__tests__/partial-cycle-chunks.test.js.map +1 -1
  30. package/dist/__tests__/per-repo-chunks.test.d.ts +9 -0
  31. package/dist/__tests__/per-repo-chunks.test.d.ts.map +1 -0
  32. package/dist/__tests__/per-repo-chunks.test.js +84 -0
  33. package/dist/__tests__/per-repo-chunks.test.js.map +1 -0
  34. package/dist/__tests__/vector-index-maintenance.test.js +17 -0
  35. package/dist/__tests__/vector-index-maintenance.test.js.map +1 -1
  36. package/dist/chunks-io.d.ts +8 -5
  37. package/dist/chunks-io.d.ts.map +1 -1
  38. package/dist/chunks-io.js +7 -6
  39. package/dist/chunks-io.js.map +1 -1
  40. package/dist/cross-repo-detector.d.ts +3 -1
  41. package/dist/cross-repo-detector.d.ts.map +1 -1
  42. package/dist/cross-repo-detector.js +45 -44
  43. package/dist/cross-repo-detector.js.map +1 -1
  44. package/dist/git-diff.d.ts +5 -0
  45. package/dist/git-diff.d.ts.map +1 -1
  46. package/dist/git-diff.js +33 -14
  47. package/dist/git-diff.js.map +1 -1
  48. package/dist/graph-store.d.ts +50 -5
  49. package/dist/graph-store.d.ts.map +1 -1
  50. package/dist/graph-store.js +350 -91
  51. package/dist/graph-store.js.map +1 -1
  52. package/dist/indexer.d.ts +4 -3
  53. package/dist/indexer.d.ts.map +1 -1
  54. package/dist/indexer.js +327 -169
  55. package/dist/indexer.js.map +1 -1
  56. package/dist/repo-chunks.d.ts +43 -0
  57. package/dist/repo-chunks.d.ts.map +1 -0
  58. package/dist/repo-chunks.js +92 -0
  59. package/dist/repo-chunks.js.map +1 -0
  60. package/dist/repo-pipeline.d.ts +6 -2
  61. package/dist/repo-pipeline.d.ts.map +1 -1
  62. package/dist/repo-pipeline.js +25 -3
  63. package/dist/repo-pipeline.js.map +1 -1
  64. package/dist/storage/fs-blob-store.js +2 -2
  65. package/dist/storage/fs-blob-store.js.map +1 -1
  66. package/dist/storage/mongo-blob-store.d.ts +1 -1
  67. package/dist/storage/mongo-blob-store.js +1 -1
  68. package/dist/storage/ports.d.ts +8 -4
  69. package/dist/storage/ports.d.ts.map +1 -1
  70. package/dist/storage/resolve.d.ts +8 -5
  71. package/dist/storage/resolve.d.ts.map +1 -1
  72. package/dist/storage/resolve.js +10 -6
  73. package/dist/storage/resolve.js.map +1 -1
  74. package/dist/vector-index-maintenance.d.ts +2 -0
  75. package/dist/vector-index-maintenance.d.ts.map +1 -1
  76. package/dist/vector-index-maintenance.js +8 -3
  77. package/dist/vector-index-maintenance.js.map +1 -1
  78. package/dist/vector-store.d.ts +17 -10
  79. package/dist/vector-store.d.ts.map +1 -1
  80. package/dist/vector-store.js +148 -59
  81. package/dist/vector-store.js.map +1 -1
  82. package/package.json +1 -1
@@ -11,7 +11,7 @@
11
11
  * fallback for indexes built before this change / when no sqlite driver is
12
12
  * available. See docs/SYSTEM-GRAPH-SQLITE-PLAN.md.
13
13
  */
14
- import { existsSync, readFileSync, rmSync } from 'node:fs';
14
+ import { existsSync, readFileSync, renameSync, rmSync } from 'node:fs';
15
15
  import { join } from 'node:path';
16
16
  /** Cross-repo edge types that describe a shared resource (topic, table, key
17
17
  * prefix, bucket, type, constant, env var, dependency) rather than a
@@ -24,6 +24,10 @@ export const SYMMETRIC_EDGE_TYPES = new Set([
24
24
  * cross-repo edges (labelled `file::thing`). Fuzzy and regex name matching
25
25
  * skip them unless the caller asks for the type explicitly. */
26
26
  const NON_SYMBOL_TYPES = ['module', 'external'];
27
+ /** Fuzzy terms shorter than this (in characters) match exactly: the trigram
28
+ * index can't serve them, and a 1–2 character substring matches a large
29
+ * share of all symbols. */
30
+ export const FUZZY_MIN_CHARS = 3;
27
31
  export function systemGraphSqlitePath(basePath) {
28
32
  return join(basePath, 'system_graph.sqlite');
29
33
  }
@@ -52,6 +56,10 @@ function loadDriver() {
52
56
  }
53
57
  // nodes.key_tail = keyTail(key), indexed so exact `::name` resolution is a
54
58
  // btree lookup (files written before it existed have no such column).
59
+ // edges.cross_repo = 1 on the edges addCrossRepoEdges wrote (same-repo
60
+ // `workspace-dep` ones included), NULL on repo-graph edges: the updater
61
+ // replaces exactly that set. idx_nodes_repo, idx_edges_crossrepo (source_repo)
62
+ // and idx_edges_target_repo serve its per-repo deletes.
55
63
  const SCHEMA = `
56
64
  CREATE TABLE IF NOT EXISTS nodes (
57
65
  key TEXT PRIMARY KEY, key_tail TEXT, repo TEXT, file TEXT, label TEXT, type TEXT, degree INTEGER, attrs TEXT
@@ -63,13 +71,19 @@ CREATE INDEX IF NOT EXISTS idx_nodes_key_tail ON nodes(key_tail);
63
71
  CREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(repo, file);
64
72
  CREATE TABLE IF NOT EXISTS edges (
65
73
  source TEXT NOT NULL, target TEXT NOT NULL, type TEXT, confidence REAL,
66
- source_repo TEXT, target_repo TEXT, evidence TEXT
74
+ source_repo TEXT, target_repo TEXT, evidence TEXT, cross_repo INTEGER
67
75
  );
68
76
  CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source, type);
69
77
  CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target, type);
70
78
  CREATE INDEX IF NOT EXISTS idx_edges_crossrepo ON edges(source_repo, target_repo);
79
+ CREATE INDEX IF NOT EXISTS idx_edges_target_repo ON edges(target_repo);
80
+ CREATE INDEX IF NOT EXISTS idx_edges_cross ON edges(cross_repo) WHERE cross_repo IS NOT NULL;
71
81
  CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT);
72
82
  `;
83
+ /** meta `schemaVersion`: the file has everything above (`nodes_fts` only when
84
+ * the driver could build it). Absent: written before versioning — readers
85
+ * feature-detect, the updater refuses the file. */
86
+ const SCHEMA_VERSION = '1';
73
87
  const repoOf = (key) => key.split('::')[0] ?? '';
74
88
  const fileOf = (key) => key.split('::')[1] ?? '';
75
89
  const labelFromKey = (key) => key.split('::').slice(2).join('::') || key;
@@ -79,25 +93,88 @@ const keyTail = (key) => {
79
93
  return i < 0 ? key : key.slice(i + 2);
80
94
  };
81
95
  const INSERT_NODE = 'INSERT OR REPLACE INTO nodes(key,key_tail,repo,file,label,type,degree,attrs) VALUES(?,?,?,?,?,?,?,?)';
82
- /** Stream the in-memory graph into a fresh sqlite db. Returns false if no
83
- * driver is available (caller falls back to the JSON write). */
84
- export async function writeSystemGraphSqlite(basePath, graph) {
85
- const open = await loadDriver();
86
- if (!open)
87
- return false;
88
- const dbPath = systemGraphSqlitePath(basePath);
89
- // Full rebuild each index — drop any prior db (+ WAL sidecars) and recreate.
90
- for (const f of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) {
96
+ const INSERT_EDGE = 'INSERT INTO edges(source,target,type,confidence,source_repo,target_repo,evidence,cross_repo) VALUES(?,?,?,?,?,?,?,?)';
97
+ function writeMeta(db, nodeCount) {
98
+ const set = db.prepare('INSERT OR REPLACE INTO meta(k,v) VALUES(?,?)');
99
+ set.run('nodeCount', String(nodeCount));
100
+ set.run('schemaVersion', SCHEMA_VERSION);
101
+ }
102
+ /** A full rebuild writes here, next to the live file, and then
103
+ * {@link publishGraphFile} renames it over the live file. One name, so a
104
+ * rebuild that died is cleared by the next one (there is one writer). */
105
+ const tempGraphPath = (dbPath) => `${dbPath}.tmp`;
106
+ /** A new, empty graph file at `path` (any old one and its -wal / -shm removed). */
107
+ function createGraphFile(open, path) {
108
+ for (const f of [path, `${path}-wal`, `${path}-shm`]) {
91
109
  try {
92
110
  rmSync(f, { force: true });
93
111
  }
94
112
  catch { /* ok */ }
95
113
  }
96
- const db = open(dbPath);
114
+ const db = open(path);
97
115
  db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;');
98
116
  db.exec(SCHEMA);
117
+ return db;
118
+ }
119
+ /**
120
+ * Swap a finished, closed graph file in for the live one by rename, so a
121
+ * reader opening `system_graph.sqlite` gets the old complete graph or the new
122
+ * one, never a partial one. Connections to the old file keep reading it (its
123
+ * inode lives until they close); SQLite sees that file has moved, so their
124
+ * close neither checkpoints into nor deletes the -wal / -shm at the path.
125
+ * Those belong to the old file: the old WAL is truncated before the rename and
126
+ * both are unlinked right after it, so new connections start fresh ones. A
127
+ * connection opened between the rename and the unlink finds no WAL frames but
128
+ * shares the old -shm, so it must be reopened before the file is next updated
129
+ * (readers reopen per index generation).
130
+ */
131
+ function publishGraphFile(open, tmp, dbPath) {
132
+ if (existsSync(dbPath)) {
133
+ try {
134
+ const live = open(dbPath);
135
+ try {
136
+ live.exec('PRAGMA busy_timeout = 5000');
137
+ live.exec('PRAGMA wal_checkpoint(TRUNCATE)');
138
+ }
139
+ finally {
140
+ live.close();
141
+ }
142
+ }
143
+ catch { /* unreadable: replaced below all the same */ }
144
+ }
145
+ renameSync(tmp, dbPath);
146
+ for (const f of [`${dbPath}-wal`, `${dbPath}-shm`]) {
147
+ try {
148
+ rmSync(f, { force: true });
149
+ }
150
+ catch { /* ok */ }
151
+ }
152
+ }
153
+ /** Trigram FTS5 index over node labels (rowid = nodes.rowid; contentless, so
154
+ * it stores only the index) for fuzzy name matching. Skipped when the
155
+ * driver's SQLite has no FTS5 or trigram tokenizer (SQLite < 3.34): readers
156
+ * then scan. */
157
+ function indexLabels(db) {
158
+ try {
159
+ db.exec("CREATE VIRTUAL TABLE nodes_fts USING fts5(name, content='', columnsize=0, tokenize='trigram')");
160
+ }
161
+ catch {
162
+ return;
163
+ }
164
+ db.exec('INSERT INTO nodes_fts(rowid, name) SELECT rowid, label FROM nodes');
165
+ }
166
+ /** Stream the in-memory graph into a fresh sqlite db, swapped in for the live
167
+ * one once complete. Returns false if no driver is available (caller falls
168
+ * back to the JSON write). */
169
+ export async function writeSystemGraphSqlite(basePath, graph) {
170
+ const open = await loadDriver();
171
+ if (!open)
172
+ return false;
173
+ const dbPath = systemGraphSqlitePath(basePath);
174
+ const tmp = tempGraphPath(dbPath);
175
+ const db = createGraphFile(open, tmp);
99
176
  const insNode = db.prepare(INSERT_NODE);
100
- const insEdge = db.prepare('INSERT INTO edges(source,target,type,confidence,source_repo,target_repo,evidence) VALUES(?,?,?,?,?,?,?)');
177
+ const insEdge = db.prepare(INSERT_EDGE);
101
178
  const degree = new Map();
102
179
  db.exec('BEGIN');
103
180
  try {
@@ -105,7 +182,7 @@ export async function writeSystemGraphSqlite(basePath, graph) {
105
182
  const type = (attrs.type ?? attrs.relation ?? null);
106
183
  const confidence = (typeof attrs.confidence === 'number' ? attrs.confidence : null);
107
184
  const evidence = typeof attrs.evidence === 'string' ? attrs.evidence : null;
108
- insEdge.run(source, target, type, confidence, repoOf(source), repoOf(target), evidence);
185
+ insEdge.run(source, target, type, confidence, repoOf(source), repoOf(target), evidence, attrs.crossRepo === true ? 1 : null);
109
186
  if (type !== 'contains') {
110
187
  degree.set(source, (degree.get(source) ?? 0) + 1);
111
188
  degree.set(target, (degree.get(target) ?? 0) + 1);
@@ -117,7 +194,8 @@ export async function writeSystemGraphSqlite(basePath, graph) {
117
194
  const { label, type, repo, file, ...rest } = attrs;
118
195
  insNode.run(key, keyTail(key), repo ?? repoOf(key), file ?? fileOf(key), label ?? labelFromKey(key), type ?? '', degree.get(key) ?? 0, Object.keys(rest).length ? JSON.stringify(rest) : null);
119
196
  });
120
- db.prepare('INSERT OR REPLACE INTO meta(k,v) VALUES(?,?)').run('nodeCount', String(nodeCount));
197
+ writeMeta(db, nodeCount);
198
+ indexLabels(db);
121
199
  db.exec('COMMIT');
122
200
  }
123
201
  catch (err) {
@@ -126,96 +204,92 @@ export async function writeSystemGraphSqlite(basePath, graph) {
126
204
  throw err;
127
205
  }
128
206
  db.close();
207
+ publishGraphFile(open, tmp, dbPath);
129
208
  return true;
130
209
  }
210
+ /** One repo's nodes and edges, keyed `<repo>::<id>` (mirrors
211
+ * ProjectGraphBuilder.addRepoGraph): a duplicate key keeps its first node; an
212
+ * edge needs both endpoints. */
213
+ function insertRepoGraph(sink, repoName, graph) {
214
+ for (const node of graph.nodes ?? []) {
215
+ const key = `${repoName}::${node.id}`;
216
+ const attrs = node.community !== undefined ? JSON.stringify({ community: node.community }) : null;
217
+ sink.addNode(key, repoName, node.file ?? fileOf(key), node.label ?? labelFromKey(key), node.type ?? '', attrs);
218
+ }
219
+ for (const edge of graph.links ?? []) {
220
+ const src = `${repoName}::${edge.source}`;
221
+ const tgt = `${repoName}::${edge.target}`;
222
+ if (!sink.hasNode(src) || !sink.hasNode(tgt))
223
+ continue;
224
+ const conf = typeof edge.confidence === 'number' ? edge.confidence : 0.8;
225
+ sink.addEdge(src, tgt, edge.type ?? 'depends', conf, repoName, repoName, null, null);
226
+ }
227
+ }
228
+ /** Cross-repo edges, plus an `external` node for each endpoint not in the
229
+ * graph (mirrors ProjectGraphBuilder.addCrossRepoEdges). */
230
+ function insertCrossRepoEdges(sink, edges) {
231
+ for (const e of edges ?? []) {
232
+ const src = `${e.sourceRepo}::${e.sourceNode}`;
233
+ const tgt = `${e.targetRepo}::${e.targetNode}`;
234
+ sink.addNode(src, e.sourceRepo, fileOf(src), e.sourceNode, 'external', null);
235
+ sink.addNode(tgt, e.targetRepo, fileOf(tgt), e.targetNode, 'external', null);
236
+ const conf = typeof e.confidence === 'number' ? e.confidence : null;
237
+ sink.addEdge(src, tgt, e.edgeType, conf, e.sourceRepo, e.targetRepo, e.evidence ?? null, 1);
238
+ }
239
+ }
240
+ /** A full rebuild: writes a new file next to the live one and renames it over
241
+ * the live one at finalize, so readers never see a partial graph. */
131
242
  export async function createSystemGraphSqliteWriter(basePath) {
132
243
  const open = await loadDriver();
133
244
  if (!open)
134
245
  return null;
135
246
  const dbPath = systemGraphSqlitePath(basePath);
136
- for (const f of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) {
137
- try {
138
- rmSync(f, { force: true });
139
- }
140
- catch { /* ok */ }
141
- }
142
- const db = open(dbPath);
143
- db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;');
144
- db.exec(SCHEMA);
247
+ const tmp = tempGraphPath(dbPath);
248
+ const db = createGraphFile(open, tmp);
145
249
  const insNode = db.prepare(INSERT_NODE);
146
- const insEdge = db.prepare('INSERT INTO edges(source,target,type,confidence,source_repo,target_repo,evidence) VALUES(?,?,?,?,?,?,?)');
250
+ const insEdge = db.prepare(INSERT_EDGE);
147
251
  const updDegree = db.prepare('UPDATE nodes SET degree=? WHERE key=?');
148
252
  const nodeKeys = new Set();
149
253
  const degree = new Map();
150
254
  let edgeCount = 0;
151
- const bump = (type, src, tgt) => {
152
- if (type !== 'contains') {
153
- degree.set(src, (degree.get(src) ?? 0) + 1);
154
- degree.set(tgt, (degree.get(tgt) ?? 0) + 1);
155
- }
156
- };
157
- return {
158
- addRepoGraph(repoName, graph) {
159
- db.exec('BEGIN');
160
- try {
161
- for (const node of graph.nodes ?? []) {
162
- const key = `${repoName}::${node.id}`;
163
- if (nodeKeys.has(key))
164
- continue; // dedup — mirrors the hasNode guard
165
- nodeKeys.add(key);
166
- const attrs = node.community !== undefined ? JSON.stringify({ community: node.community }) : null;
167
- insNode.run(key, keyTail(key), repoName, node.file ?? fileOf(key), node.label ?? labelFromKey(key), node.type ?? '', 0, attrs);
168
- }
169
- for (const edge of graph.links ?? []) {
170
- const src = `${repoName}::${edge.source}`;
171
- const tgt = `${repoName}::${edge.target}`;
172
- if (!nodeKeys.has(src) || !nodeKeys.has(tgt))
173
- continue; // both endpoints must exist
174
- const type = edge.type ?? 'depends';
175
- const conf = typeof edge.confidence === 'number' ? edge.confidence : 0.8;
176
- insEdge.run(src, tgt, type, conf, repoName, repoName, null);
177
- edgeCount++;
178
- bump(type, src, tgt);
179
- }
180
- db.exec('COMMIT');
181
- }
182
- catch (e) {
183
- db.exec('ROLLBACK');
184
- throw e;
185
- }
255
+ const sink = {
256
+ addNode(key, repo, file, label, type, attrs) {
257
+ if (nodeKeys.has(key))
258
+ return; // dedup — mirrors the hasNode guard
259
+ nodeKeys.add(key);
260
+ insNode.run(key, keyTail(key), repo, file, label, type, 0, attrs);
186
261
  },
187
- addCrossRepoEdges(edges) {
188
- db.exec('BEGIN');
189
- try {
190
- for (const e of edges ?? []) {
191
- const src = `${e.sourceRepo}::${e.sourceNode}`;
192
- const tgt = `${e.targetRepo}::${e.targetNode}`;
193
- if (!nodeKeys.has(src)) {
194
- nodeKeys.add(src);
195
- insNode.run(src, keyTail(src), e.sourceRepo, fileOf(src), e.sourceNode, 'external', 0, null);
196
- }
197
- if (!nodeKeys.has(tgt)) {
198
- nodeKeys.add(tgt);
199
- insNode.run(tgt, keyTail(tgt), e.targetRepo, fileOf(tgt), e.targetNode, 'external', 0, null);
200
- }
201
- const conf = typeof e.confidence === 'number' ? e.confidence : null;
202
- insEdge.run(src, tgt, e.edgeType, conf, e.sourceRepo, e.targetRepo, e.evidence ?? null);
203
- edgeCount++;
204
- bump(e.edgeType, src, tgt);
205
- }
206
- db.exec('COMMIT');
207
- }
208
- catch (e) {
209
- db.exec('ROLLBACK');
210
- throw e;
262
+ hasNode: (key) => nodeKeys.has(key),
263
+ addEdge(src, tgt, type, conf, srcRepo, tgtRepo, evidence, crossRepo) {
264
+ insEdge.run(src, tgt, type, conf, srcRepo, tgtRepo, evidence, crossRepo);
265
+ edgeCount++;
266
+ if (type !== 'contains') {
267
+ degree.set(src, (degree.get(src) ?? 0) + 1);
268
+ degree.set(tgt, (degree.get(tgt) ?? 0) + 1);
211
269
  }
212
270
  },
271
+ };
272
+ const inTransaction = (fn) => {
273
+ db.exec('BEGIN');
274
+ try {
275
+ fn();
276
+ db.exec('COMMIT');
277
+ }
278
+ catch (e) {
279
+ db.exec('ROLLBACK');
280
+ throw e;
281
+ }
282
+ };
283
+ return {
284
+ addRepoGraph(repoName, graph) { inTransaction(() => insertRepoGraph(sink, repoName, graph)); },
285
+ addCrossRepoEdges(edges) { inTransaction(() => insertCrossRepoEdges(sink, edges)); },
213
286
  finalize() {
214
287
  db.exec('BEGIN');
215
288
  try {
216
289
  for (const [key, deg] of degree)
217
290
  updDegree.run(deg, key);
218
- db.prepare('INSERT OR REPLACE INTO meta(k,v) VALUES(?,?)').run('nodeCount', String(nodeKeys.size));
291
+ writeMeta(db, nodeKeys.size);
292
+ indexLabels(db);
219
293
  db.exec('COMMIT');
220
294
  }
221
295
  catch (e) {
@@ -224,10 +298,152 @@ export async function createSystemGraphSqliteWriter(basePath) {
224
298
  throw e;
225
299
  }
226
300
  db.close();
301
+ publishGraphFile(open, tmp, dbPath);
227
302
  return { nodeCount: nodeKeys.size, edgeCount };
228
303
  },
229
304
  };
230
305
  }
306
+ /** Null when there is no driver or the file can't be updated in place —
307
+ * missing, not at the current schema version, or without `nodes_fts` /
308
+ * `nodes.key_tail`: rebuild it with {@link createSystemGraphSqliteWriter}. */
309
+ export async function openSystemGraphSqliteUpdater(basePath) {
310
+ const open = await loadDriver();
311
+ if (!open)
312
+ return null;
313
+ const dbPath = systemGraphSqlitePath(basePath);
314
+ if (!existsSync(dbPath))
315
+ return null;
316
+ let db;
317
+ try {
318
+ db = open(dbPath);
319
+ }
320
+ catch {
321
+ return null;
322
+ }
323
+ try {
324
+ const version = db.prepare("SELECT v FROM meta WHERE k = 'schemaVersion'").get()?.v;
325
+ const hasKeyTail = db.prepare('PRAGMA table_info(nodes)').all().some((c) => c.name === 'key_tail');
326
+ if (version !== SCHEMA_VERSION || !hasKeyTail)
327
+ throw new Error('not updatable');
328
+ db.prepare('SELECT rowid FROM nodes_fts WHERE nodes_fts MATCH ?'); // throws: no table, or no FTS5 / trigram
329
+ db.exec('PRAGMA busy_timeout = 5000; PRAGMA synchronous = NORMAL;');
330
+ db.exec('BEGIN IMMEDIATE');
331
+ }
332
+ catch {
333
+ db.close();
334
+ return null;
335
+ }
336
+ const insNode = db.prepare('INSERT OR IGNORE INTO nodes(key,key_tail,repo,file,label,type,degree,attrs) VALUES(?,?,?,?,?,?,?,?)');
337
+ const insFts = db.prepare('INSERT INTO nodes_fts(rowid, name) VALUES(?, ?)');
338
+ const getNode = db.prepare('SELECT 1 FROM nodes WHERE key = ?');
339
+ const repoHasNodes = db.prepare('SELECT 1 FROM nodes WHERE repo = ? LIMIT 1');
340
+ const insEdge = db.prepare(INSERT_EDGE);
341
+ /** Nodes whose edge set changed — their degrees are recounted at finalize. */
342
+ const touched = new Set();
343
+ const added = new Set();
344
+ const touch = (rows) => { for (const r of rows) {
345
+ touched.add(r.source);
346
+ touched.add(r.target);
347
+ } };
348
+ const sink = {
349
+ addNode(key, repo, file, label, type, attrs) {
350
+ const r = insNode.run(key, keyTail(key), repo, file, label, type, 0, attrs);
351
+ if (Number(r.changes) > 0)
352
+ insFts.run(r.lastInsertRowid, label);
353
+ },
354
+ hasNode: (key) => getNode.get(key) !== undefined,
355
+ addEdge(src, tgt, type, conf, srcRepo, tgtRepo, evidence, crossRepo) {
356
+ insEdge.run(src, tgt, type, conf, srcRepo, tgtRepo, evidence, crossRepo);
357
+ if (type !== 'contains') {
358
+ touched.add(src);
359
+ touched.add(tgt);
360
+ }
361
+ },
362
+ };
363
+ let step = 0;
364
+ let closed = false;
365
+ const abort = () => {
366
+ if (closed)
367
+ return;
368
+ closed = true;
369
+ try {
370
+ db.exec('ROLLBACK');
371
+ }
372
+ catch { /* no transaction left to roll back */ }
373
+ db.close();
374
+ };
375
+ /** Run `fn` as the `next` step of the sequence; any error rolls everything back. */
376
+ const run = (next, fn) => {
377
+ if (closed)
378
+ throw new Error('system graph updater is closed');
379
+ try {
380
+ if (next < step)
381
+ throw new Error('system graph updater: call removeRepos → addRepoGraph → replaceCrossRepoEdges → finalize, in that order');
382
+ step = next;
383
+ return fn();
384
+ }
385
+ catch (e) {
386
+ abort();
387
+ throw e;
388
+ }
389
+ };
390
+ return {
391
+ removeRepos(names) {
392
+ run(0, () => {
393
+ for (const batch of chunked([...new Set(names)])) {
394
+ const ph = placeholders(batch.length);
395
+ // A cross-repo edge into a removed repo also ends at a node that stays.
396
+ touch(db.prepare(`SELECT source, target FROM edges WHERE cross_repo IS NOT NULL AND (source_repo IN (${ph}) OR target_repo IN (${ph}))`).all(...batch, ...batch));
397
+ // Contentless FTS5 deletes a row given the values it indexed.
398
+ db.prepare(`INSERT INTO nodes_fts(nodes_fts, rowid, name) SELECT 'delete', rowid, label FROM nodes WHERE repo IN (${ph})`).run(...batch);
399
+ db.prepare(`DELETE FROM nodes WHERE repo IN (${ph})`).run(...batch);
400
+ db.prepare(`DELETE FROM edges WHERE source_repo IN (${ph}) OR target_repo IN (${ph})`).run(...batch, ...batch);
401
+ }
402
+ });
403
+ },
404
+ addRepoGraph(repoName, graph) {
405
+ run(1, () => {
406
+ if (!added.has(repoName) && repoHasNodes.get(repoName) !== undefined) {
407
+ throw new Error(`system graph updater: "${repoName}" is still in the graph — removeRepos it first`);
408
+ }
409
+ added.add(repoName);
410
+ insertRepoGraph(sink, repoName, graph);
411
+ });
412
+ },
413
+ replaceCrossRepoEdges(edges) {
414
+ run(2, () => {
415
+ touch(db.prepare('SELECT source, target FROM edges WHERE cross_repo IS NOT NULL').all());
416
+ db.exec("INSERT INTO nodes_fts(nodes_fts, rowid, name) SELECT 'delete', rowid, label FROM nodes WHERE type = 'external'");
417
+ db.exec("DELETE FROM nodes WHERE type = 'external'");
418
+ db.exec('DELETE FROM edges WHERE cross_repo IS NOT NULL');
419
+ insertCrossRepoEdges(sink, edges);
420
+ });
421
+ },
422
+ finalize() {
423
+ return run(3, () => {
424
+ const nonContains = "(type IS NULL OR type <> 'contains')";
425
+ const recount = db.prepare(`UPDATE nodes SET degree = (SELECT count(*) FROM edges WHERE source = ? AND ${nonContains})`
426
+ + ` + (SELECT count(*) FROM edges WHERE target = ? AND ${nonContains}) WHERE key = ?`);
427
+ for (const key of touched)
428
+ recount.run(key, key, key);
429
+ const nodeCount = Number(db.prepare('SELECT count(*) c FROM nodes').get().c);
430
+ const edgeCount = Number(db.prepare('SELECT count(*) c FROM edges').get().c);
431
+ writeMeta(db, nodeCount);
432
+ db.exec('COMMIT');
433
+ closed = true;
434
+ // Into the file itself: an upload of system_graph.sqlite alone carries the update.
435
+ try {
436
+ db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
437
+ }
438
+ finally {
439
+ db.close();
440
+ }
441
+ return { nodeCount, edgeCount };
442
+ });
443
+ },
444
+ abort,
445
+ };
446
+ }
231
447
  // ---------------------------------------------------------------------------
232
448
  // SQLite-backed reader
233
449
  // ---------------------------------------------------------------------------
@@ -243,6 +459,12 @@ const placeholders = (n) => Array(n).fill('?').join(',');
243
459
  const neighborFilter = (types) => `(confidence IS NULL OR confidence >= 0.7) AND (type IS NULL OR type <> 'contains')${types?.length ? ` AND type IN (${placeholders(types.length)})` : ''}`;
244
460
  /** Escape LIKE's wildcards for `ESCAPE '\'`. */
245
461
  const likeEscape = (s) => s.replace(/[\\%_]/g, (c) => `\\${c}`);
462
+ /** `s` as one FTS5 phrase: over the trigram index, the labels containing it (case-insensitive). */
463
+ const ftsPhrase = (s) => `"${s.replace(/"/g, '""')}"`;
464
+ /** A searchNodes name the trigram index can serve: long enough, and free of
465
+ * regex syntax, so a case-insensitive substring; printable ASCII only, where
466
+ * the index's case folding and the regex's agree. */
467
+ const isLiteralName = (s) => s.length >= FUZZY_MIN_CHARS && /^[\x20-\x7e]+$/.test(s) && !/[\\^$.|?*+()[\]{}]/.test(s);
246
468
  /** Compile a caller-supplied name filter (case-insensitive). */
247
469
  function nameRegex(pattern) {
248
470
  try {
@@ -265,12 +487,25 @@ class SqliteGraphStore {
265
487
  /** Files written before it existed have no `nodes.key_tail`: exact resolution scans them. */
266
488
  hasKeyTail;
267
489
  hasRegexp;
490
+ /** Files written before it existed have no `nodes_fts`, and a driver without
491
+ * FTS5 / trigram can't read it: fuzzy matching scans those (bounded by its limit). */
492
+ hasFts;
268
493
  constructor(db) {
269
494
  this.db = db;
270
495
  const cols = db.prepare('PRAGMA table_info(edges)').all().map((c) => c.name);
271
496
  this.evidenceCol = cols.includes('evidence') ? 'evidence' : 'NULL AS evidence';
272
497
  this.hasKeyTail = db.prepare('PRAGMA table_info(nodes)').all().some((c) => c.name === 'key_tail');
273
498
  this.hasRegexp = this.registerRegexp();
499
+ this.hasFts = this.canReadFts();
500
+ }
501
+ canReadFts() {
502
+ try {
503
+ this.db.prepare('SELECT rowid FROM nodes_fts WHERE nodes_fts MATCH ?');
504
+ return true;
505
+ }
506
+ catch {
507
+ return false;
508
+ }
274
509
  }
275
510
  registerRegexp() {
276
511
  if (typeof this.db.function !== 'function')
@@ -288,13 +523,32 @@ class SqliteGraphStore {
288
523
  return false;
289
524
  }
290
525
  }
291
- resolveNodes(name, repo, fuzzy = false) {
526
+ resolveNodes(name, repo, fuzzy = false, limit = 5000) {
292
527
  const params = [];
293
528
  let where;
294
529
  let repoCol = 'repo';
295
- if (fuzzy) {
530
+ let from = 'nodes';
531
+ let order = 'rowid';
532
+ if (fuzzy && [...name].length >= FUZZY_MIN_CHARS) {
296
533
  where = `label LIKE '%' || ? || '%' ESCAPE '\\' AND type NOT IN (${placeholders(NON_SYMBOL_TYPES.length)})`;
297
534
  params.push(likeEscape(name), ...NON_SYMBOL_TYPES);
535
+ if (this.hasFts) {
536
+ // The index yields the candidates in rowid order, so LIMIT stops the
537
+ // read; the LIKE above keeps the scan's exact semantics.
538
+ from = 'nodes_fts JOIN nodes ON nodes.rowid = nodes_fts.rowid';
539
+ where = `nodes_fts MATCH ? AND ${where}`;
540
+ params.unshift(ftsPhrase(name));
541
+ if (repo) {
542
+ // Read only from the repo's first node to its last symbol. The writer
543
+ // inserts a repo's nodes together and cross-repo endpoints after every
544
+ // repo, so this range holds little but the repo.
545
+ where += ' AND nodes_fts.rowid BETWEEN (SELECT min(rowid) FROM nodes WHERE repo = ?)'
546
+ + ` AND (SELECT rowid FROM nodes WHERE repo = ? AND type NOT IN (${placeholders(NON_SYMBOL_TYPES.length)}) ORDER BY rowid DESC LIMIT 1)`;
547
+ params.push(repo, repo, ...NON_SYMBOL_TYPES);
548
+ }
549
+ order = 'nodes_fts.rowid';
550
+ repoCol = '+repo'; // `+`: filter only — keeps the planner on the index
551
+ }
298
552
  }
299
553
  else if (this.hasKeyTail) {
300
554
  // `=` / substr compare bytes: case-sensitive and wildcard-free. Every OR
@@ -313,7 +567,7 @@ class SqliteGraphStore {
313
567
  params.push(repo);
314
568
  }
315
569
  // rowid = insertion order, the order a scan returns (callers may take the first match).
316
- return this.db.prepare(`SELECT key, label FROM nodes WHERE ${where} ORDER BY rowid LIMIT 5000`).all(...params)
570
+ return this.db.prepare(`SELECT key, label FROM ${from} WHERE ${where} ORDER BY ${order} LIMIT ?`).all(...params, limit)
317
571
  .map((r) => ({ key: r.key, label: r.label || labelFromKey(r.key) }));
318
572
  }
319
573
  typedEndpoints(keys, side, limit, types) {
@@ -470,6 +724,11 @@ class SqliteGraphStore {
470
724
  cond.push("file LIKE '%' || ? || '%' ESCAPE '\\'");
471
725
  p.push(likeEscape(f.file));
472
726
  }
727
+ if (re && this.hasFts && isLiteralName(f.name)) {
728
+ // A plain substring: the index narrows the rows the regex checks.
729
+ cond.push('rowid IN (SELECT rowid FROM nodes_fts WHERE nodes_fts MATCH ?)');
730
+ p.push(ftsPhrase(f.name));
731
+ }
473
732
  if (re && this.hasRegexp) {
474
733
  cond.push('regexp(?, label)');
475
734
  p.push(f.name);
@@ -505,12 +764,12 @@ class JsonGraphStore {
505
764
  out.evidence = e.attributes.evidence;
506
765
  return out;
507
766
  }
508
- resolveNodes(name, repo, fuzzy = false) {
767
+ resolveNodes(name, repo, fuzzy = false, limit = 5000) {
509
768
  const inRepo = (k) => !repo || k.startsWith(repo + '::');
510
769
  const lc = name.toLowerCase();
511
- return this.nodes.filter((n) => inRepo(n.key) && (fuzzy
770
+ return this.nodes.filter((n) => inRepo(n.key) && (fuzzy && [...name].length >= FUZZY_MIN_CHARS
512
771
  ? !NON_SYMBOL_TYPES.includes(n.attributes?.type ?? '') && this.label(n).toLowerCase().includes(lc)
513
- : (n.key === name || this.label(n) === name || n.key.endsWith('::' + name)))).map((n) => ({ key: n.key, label: this.label(n) }));
772
+ : (n.key === name || this.label(n) === name || n.key.endsWith('::' + name)))).slice(0, limit).map((n) => ({ key: n.key, label: this.label(n) }));
514
773
  }
515
774
  typedEndpoints(keys, side, limit, types) {
516
775
  const set = new Set(keys);