@esankhan3/anvil-knowledge-core 0.4.5 → 0.4.7
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.
- package/dist/__tests__/ast-graph.test.d.ts +9 -0
- package/dist/__tests__/ast-graph.test.d.ts.map +1 -0
- package/dist/__tests__/ast-graph.test.js +93 -0
- package/dist/__tests__/ast-graph.test.js.map +1 -0
- package/dist/__tests__/chunker-boundaries.test.d.ts +10 -0
- package/dist/__tests__/chunker-boundaries.test.d.ts.map +1 -0
- package/dist/__tests__/chunker-boundaries.test.js +218 -0
- package/dist/__tests__/chunker-boundaries.test.js.map +1 -0
- package/dist/__tests__/content-hash-reuse.test.d.ts +8 -0
- package/dist/__tests__/content-hash-reuse.test.d.ts.map +1 -0
- package/dist/__tests__/content-hash-reuse.test.js +110 -0
- package/dist/__tests__/content-hash-reuse.test.js.map +1 -0
- package/dist/__tests__/cross-repo-detector.test.js +5 -0
- package/dist/__tests__/cross-repo-detector.test.js.map +1 -1
- package/dist/__tests__/env-overrides.test.js +29 -0
- package/dist/__tests__/env-overrides.test.js.map +1 -1
- package/dist/__tests__/graph-store-queries.test.d.ts +14 -0
- package/dist/__tests__/graph-store-queries.test.d.ts.map +1 -0
- package/dist/__tests__/graph-store-queries.test.js +246 -0
- package/dist/__tests__/graph-store-queries.test.js.map +1 -0
- package/dist/__tests__/identifier-bm25.test.d.ts +7 -0
- package/dist/__tests__/identifier-bm25.test.d.ts.map +1 -0
- package/dist/__tests__/identifier-bm25.test.js +107 -0
- package/dist/__tests__/identifier-bm25.test.js.map +1 -0
- package/dist/__tests__/index-cycle-cost.test.d.ts +8 -0
- package/dist/__tests__/index-cycle-cost.test.d.ts.map +1 -0
- package/dist/__tests__/index-cycle-cost.test.js +122 -0
- package/dist/__tests__/index-cycle-cost.test.js.map +1 -0
- package/dist/__tests__/index-integrity.test.d.ts +10 -0
- package/dist/__tests__/index-integrity.test.d.ts.map +1 -0
- package/dist/__tests__/index-integrity.test.js +151 -0
- package/dist/__tests__/index-integrity.test.js.map +1 -0
- package/dist/__tests__/kb-fixture.d.ts +32 -0
- package/dist/__tests__/kb-fixture.d.ts.map +1 -0
- package/dist/__tests__/kb-fixture.js +116 -0
- package/dist/__tests__/kb-fixture.js.map +1 -0
- package/dist/__tests__/nprobes-calibration.test.d.ts +10 -0
- package/dist/__tests__/nprobes-calibration.test.d.ts.map +1 -0
- package/dist/__tests__/nprobes-calibration.test.js +107 -0
- package/dist/__tests__/nprobes-calibration.test.js.map +1 -0
- package/dist/__tests__/project-graph-cross-edges.test.d.ts +7 -0
- package/dist/__tests__/project-graph-cross-edges.test.d.ts.map +1 -0
- package/dist/__tests__/project-graph-cross-edges.test.js +45 -0
- package/dist/__tests__/project-graph-cross-edges.test.js.map +1 -0
- package/dist/__tests__/query-caches.test.d.ts +7 -0
- package/dist/__tests__/query-caches.test.d.ts.map +1 -0
- package/dist/__tests__/query-caches.test.js +86 -0
- package/dist/__tests__/query-caches.test.js.map +1 -0
- package/dist/__tests__/retriever-config.test.d.ts +8 -0
- package/dist/__tests__/retriever-config.test.d.ts.map +1 -0
- package/dist/__tests__/retriever-config.test.js +77 -0
- package/dist/__tests__/retriever-config.test.js.map +1 -0
- package/dist/__tests__/retriever-graph-expansion.test.d.ts +8 -0
- package/dist/__tests__/retriever-graph-expansion.test.d.ts.map +1 -0
- package/dist/__tests__/retriever-graph-expansion.test.js +79 -0
- package/dist/__tests__/retriever-graph-expansion.test.js.map +1 -0
- package/dist/__tests__/tree-sitter-parse.test.d.ts +8 -0
- package/dist/__tests__/tree-sitter-parse.test.d.ts.map +1 -0
- package/dist/__tests__/tree-sitter-parse.test.js +124 -0
- package/dist/__tests__/tree-sitter-parse.test.js.map +1 -0
- package/dist/ast-graph-builder.d.ts +4 -2
- package/dist/ast-graph-builder.d.ts.map +1 -1
- package/dist/ast-graph-builder.js +60 -35
- package/dist/ast-graph-builder.js.map +1 -1
- package/dist/chunker.d.ts +16 -6
- package/dist/chunker.d.ts.map +1 -1
- package/dist/chunker.js +130 -42
- package/dist/chunker.js.map +1 -1
- package/dist/config.d.ts +3 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +6 -6
- package/dist/config.js.map +1 -1
- package/dist/cross-repo-detector.d.ts +5 -2
- package/dist/cross-repo-detector.d.ts.map +1 -1
- package/dist/cross-repo-detector.js +31 -3
- package/dist/cross-repo-detector.js.map +1 -1
- package/dist/embedder.d.ts +5 -5
- package/dist/embedder.d.ts.map +1 -1
- package/dist/embedder.js.map +1 -1
- package/dist/file-walker.d.ts +3 -1
- package/dist/file-walker.d.ts.map +1 -1
- package/dist/file-walker.js +9 -3
- package/dist/file-walker.js.map +1 -1
- package/dist/git-diff.d.ts.map +1 -1
- package/dist/git-diff.js +5 -11
- package/dist/git-diff.js.map +1 -1
- package/dist/graph-store.d.ts +34 -6
- package/dist/graph-store.d.ts.map +1 -1
- package/dist/graph-store.js +263 -101
- package/dist/graph-store.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/indexer.d.ts +8 -0
- package/dist/indexer.d.ts.map +1 -1
- package/dist/indexer.js +293 -122
- package/dist/indexer.js.map +1 -1
- package/dist/project-graph-builder.d.ts.map +1 -1
- package/dist/project-graph-builder.js +12 -11
- package/dist/project-graph-builder.js.map +1 -1
- package/dist/query-expander.d.ts.map +1 -1
- package/dist/query-expander.js +12 -8
- package/dist/query-expander.js.map +1 -1
- package/dist/query-router.d.ts +5 -0
- package/dist/query-router.d.ts.map +1 -1
- package/dist/query-router.js +1 -1
- package/dist/query-router.js.map +1 -1
- package/dist/repo-pipeline.d.ts +8 -0
- package/dist/repo-pipeline.d.ts.map +1 -1
- package/dist/repo-pipeline.js +9 -6
- package/dist/repo-pipeline.js.map +1 -1
- package/dist/retriever.d.ts.map +1 -1
- package/dist/retriever.js +36 -21
- package/dist/retriever.js.map +1 -1
- package/dist/storage/fs-blob-store.d.ts +3 -4
- package/dist/storage/fs-blob-store.d.ts.map +1 -1
- package/dist/storage/fs-blob-store.js +14 -7
- package/dist/storage/fs-blob-store.js.map +1 -1
- package/dist/storage/ports.d.ts +15 -0
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/tree-sitter-parser.d.ts +10 -2
- package/dist/tree-sitter-parser.d.ts.map +1 -1
- package/dist/tree-sitter-parser.js +169 -43
- package/dist/tree-sitter-parser.js.map +1 -1
- package/dist/types.d.ts +12 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/vector-index-maintenance.d.ts +4 -1
- package/dist/vector-index-maintenance.d.ts.map +1 -1
- package/dist/vector-index-maintenance.js +26 -1
- package/dist/vector-index-maintenance.js.map +1 -1
- package/dist/vector-recall.d.ts +13 -1
- package/dist/vector-recall.d.ts.map +1 -1
- package/dist/vector-recall.js +33 -0
- package/dist/vector-recall.js.map +1 -1
- package/dist/vector-store.d.ts +54 -8
- package/dist/vector-store.d.ts.map +1 -1
- package/dist/vector-store.js +222 -56
- package/dist/vector-store.js.map +1 -1
- package/package.json +3 -3
package/dist/graph-store.js
CHANGED
|
@@ -13,6 +13,17 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
15
15
|
import { join } from 'node:path';
|
|
16
|
+
/** Cross-repo edge types that describe a shared resource (topic, table, key
|
|
17
|
+
* prefix, bucket, type, constant, env var, dependency) rather than a
|
|
18
|
+
* client → provider call: the detector stores one edge per pair in an
|
|
19
|
+
* arbitrary order, so each side depends on the other. */
|
|
20
|
+
export const SYMMETRIC_EDGE_TYPES = new Set([
|
|
21
|
+
'event-schema', 'database', 'redis', 's3', 'shared-type', 'shared-constant', 'env-var', 'npm-dep',
|
|
22
|
+
]);
|
|
23
|
+
/** Node types that are not symbols: files, and the synthetic endpoints of
|
|
24
|
+
* cross-repo edges (labelled `file::thing`). Fuzzy and regex name matching
|
|
25
|
+
* skip them unless the caller asks for the type explicitly. */
|
|
26
|
+
const NON_SYMBOL_TYPES = ['module', 'external'];
|
|
16
27
|
export function systemGraphSqlitePath(basePath) {
|
|
17
28
|
return join(basePath, 'system_graph.sqlite');
|
|
18
29
|
}
|
|
@@ -39,17 +50,20 @@ function loadDriver() {
|
|
|
39
50
|
}
|
|
40
51
|
return driverPromise;
|
|
41
52
|
}
|
|
53
|
+
// nodes.key_tail = keyTail(key), indexed so exact `::name` resolution is a
|
|
54
|
+
// btree lookup (files written before it existed have no such column).
|
|
42
55
|
const SCHEMA = `
|
|
43
56
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
44
|
-
key TEXT PRIMARY KEY, repo TEXT, file TEXT, label TEXT, type TEXT, degree INTEGER, attrs TEXT
|
|
57
|
+
key TEXT PRIMARY KEY, key_tail TEXT, repo TEXT, file TEXT, label TEXT, type TEXT, degree INTEGER, attrs TEXT
|
|
45
58
|
);
|
|
46
59
|
CREATE INDEX IF NOT EXISTS idx_nodes_repo ON nodes(repo);
|
|
47
60
|
CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type);
|
|
48
61
|
CREATE INDEX IF NOT EXISTS idx_nodes_label ON nodes(label);
|
|
62
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_key_tail ON nodes(key_tail);
|
|
49
63
|
CREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(repo, file);
|
|
50
64
|
CREATE TABLE IF NOT EXISTS edges (
|
|
51
65
|
source TEXT NOT NULL, target TEXT NOT NULL, type TEXT, confidence REAL,
|
|
52
|
-
source_repo TEXT, target_repo TEXT
|
|
66
|
+
source_repo TEXT, target_repo TEXT, evidence TEXT
|
|
53
67
|
);
|
|
54
68
|
CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source, type);
|
|
55
69
|
CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target, type);
|
|
@@ -59,6 +73,12 @@ CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT);
|
|
|
59
73
|
const repoOf = (key) => key.split('::')[0] ?? '';
|
|
60
74
|
const fileOf = (key) => key.split('::')[1] ?? '';
|
|
61
75
|
const labelFromKey = (key) => key.split('::').slice(2).join('::') || key;
|
|
76
|
+
/** Text after the last `::`. A key ending in `::name` has the same tail as `::name`. */
|
|
77
|
+
const keyTail = (key) => {
|
|
78
|
+
const i = key.lastIndexOf('::');
|
|
79
|
+
return i < 0 ? key : key.slice(i + 2);
|
|
80
|
+
};
|
|
81
|
+
const INSERT_NODE = 'INSERT OR REPLACE INTO nodes(key,key_tail,repo,file,label,type,degree,attrs) VALUES(?,?,?,?,?,?,?,?)';
|
|
62
82
|
/** Stream the in-memory graph into a fresh sqlite db. Returns false if no
|
|
63
83
|
* driver is available (caller falls back to the JSON write). */
|
|
64
84
|
export async function writeSystemGraphSqlite(basePath, graph) {
|
|
@@ -76,15 +96,16 @@ export async function writeSystemGraphSqlite(basePath, graph) {
|
|
|
76
96
|
const db = open(dbPath);
|
|
77
97
|
db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;');
|
|
78
98
|
db.exec(SCHEMA);
|
|
79
|
-
const insNode = db.prepare(
|
|
80
|
-
const insEdge = db.prepare('INSERT INTO edges(source,target,type,confidence,source_repo,target_repo) VALUES(
|
|
99
|
+
const insNode = db.prepare(INSERT_NODE);
|
|
100
|
+
const insEdge = db.prepare('INSERT INTO edges(source,target,type,confidence,source_repo,target_repo,evidence) VALUES(?,?,?,?,?,?,?)');
|
|
81
101
|
const degree = new Map();
|
|
82
102
|
db.exec('BEGIN');
|
|
83
103
|
try {
|
|
84
104
|
graph.forEachEdge((source, target, attrs) => {
|
|
85
105
|
const type = (attrs.type ?? attrs.relation ?? null);
|
|
86
106
|
const confidence = (typeof attrs.confidence === 'number' ? attrs.confidence : null);
|
|
87
|
-
|
|
107
|
+
const evidence = typeof attrs.evidence === 'string' ? attrs.evidence : null;
|
|
108
|
+
insEdge.run(source, target, type, confidence, repoOf(source), repoOf(target), evidence);
|
|
88
109
|
if (type !== 'contains') {
|
|
89
110
|
degree.set(source, (degree.get(source) ?? 0) + 1);
|
|
90
111
|
degree.set(target, (degree.get(target) ?? 0) + 1);
|
|
@@ -94,7 +115,7 @@ export async function writeSystemGraphSqlite(basePath, graph) {
|
|
|
94
115
|
graph.forEachNode((key, attrs) => {
|
|
95
116
|
nodeCount++;
|
|
96
117
|
const { label, type, repo, file, ...rest } = attrs;
|
|
97
|
-
insNode.run(key, repo ?? repoOf(key), file ?? fileOf(key), label ?? labelFromKey(key), type ?? '', degree.get(key) ?? 0, Object.keys(rest).length ? JSON.stringify(rest) : null);
|
|
118
|
+
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);
|
|
98
119
|
});
|
|
99
120
|
db.prepare('INSERT OR REPLACE INTO meta(k,v) VALUES(?,?)').run('nodeCount', String(nodeCount));
|
|
100
121
|
db.exec('COMMIT');
|
|
@@ -121,8 +142,8 @@ export async function createSystemGraphSqliteWriter(basePath) {
|
|
|
121
142
|
const db = open(dbPath);
|
|
122
143
|
db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;');
|
|
123
144
|
db.exec(SCHEMA);
|
|
124
|
-
const insNode = db.prepare(
|
|
125
|
-
const insEdge = db.prepare('INSERT INTO edges(source,target,type,confidence,source_repo,target_repo) VALUES(
|
|
145
|
+
const insNode = db.prepare(INSERT_NODE);
|
|
146
|
+
const insEdge = db.prepare('INSERT INTO edges(source,target,type,confidence,source_repo,target_repo,evidence) VALUES(?,?,?,?,?,?,?)');
|
|
126
147
|
const updDegree = db.prepare('UPDATE nodes SET degree=? WHERE key=?');
|
|
127
148
|
const nodeKeys = new Set();
|
|
128
149
|
const degree = new Map();
|
|
@@ -143,7 +164,7 @@ export async function createSystemGraphSqliteWriter(basePath) {
|
|
|
143
164
|
continue; // dedup — mirrors the hasNode guard
|
|
144
165
|
nodeKeys.add(key);
|
|
145
166
|
const attrs = node.community !== undefined ? JSON.stringify({ community: node.community }) : null;
|
|
146
|
-
insNode.run(key, repoName, node.file ?? fileOf(key), node.label ?? labelFromKey(key), node.type ?? '', 0, attrs);
|
|
167
|
+
insNode.run(key, keyTail(key), repoName, node.file ?? fileOf(key), node.label ?? labelFromKey(key), node.type ?? '', 0, attrs);
|
|
147
168
|
}
|
|
148
169
|
for (const edge of graph.links ?? []) {
|
|
149
170
|
const src = `${repoName}::${edge.source}`;
|
|
@@ -152,7 +173,7 @@ export async function createSystemGraphSqliteWriter(basePath) {
|
|
|
152
173
|
continue; // both endpoints must exist
|
|
153
174
|
const type = edge.type ?? 'depends';
|
|
154
175
|
const conf = typeof edge.confidence === 'number' ? edge.confidence : 0.8;
|
|
155
|
-
insEdge.run(src, tgt, type, conf, repoName, repoName);
|
|
176
|
+
insEdge.run(src, tgt, type, conf, repoName, repoName, null);
|
|
156
177
|
edgeCount++;
|
|
157
178
|
bump(type, src, tgt);
|
|
158
179
|
}
|
|
@@ -171,14 +192,14 @@ export async function createSystemGraphSqliteWriter(basePath) {
|
|
|
171
192
|
const tgt = `${e.targetRepo}::${e.targetNode}`;
|
|
172
193
|
if (!nodeKeys.has(src)) {
|
|
173
194
|
nodeKeys.add(src);
|
|
174
|
-
insNode.run(src, e.sourceRepo, fileOf(src), e.sourceNode, 'external', 0, null);
|
|
195
|
+
insNode.run(src, keyTail(src), e.sourceRepo, fileOf(src), e.sourceNode, 'external', 0, null);
|
|
175
196
|
}
|
|
176
197
|
if (!nodeKeys.has(tgt)) {
|
|
177
198
|
nodeKeys.add(tgt);
|
|
178
|
-
insNode.run(tgt, e.targetRepo, fileOf(tgt), e.targetNode, 'external', 0, null);
|
|
199
|
+
insNode.run(tgt, keyTail(tgt), e.targetRepo, fileOf(tgt), e.targetNode, 'external', 0, null);
|
|
179
200
|
}
|
|
180
201
|
const conf = typeof e.confidence === 'number' ? e.confidence : null;
|
|
181
|
-
insEdge.run(src, tgt, e.edgeType, conf, e.sourceRepo, e.targetRepo);
|
|
202
|
+
insEdge.run(src, tgt, e.edgeType, conf, e.sourceRepo, e.targetRepo, e.evidence ?? null);
|
|
182
203
|
edgeCount++;
|
|
183
204
|
bump(e.edgeType, src, tgt);
|
|
184
205
|
}
|
|
@@ -217,99 +238,195 @@ function chunked(xs, n = CHUNK) {
|
|
|
217
238
|
out.push(xs.slice(i, i + n));
|
|
218
239
|
return out;
|
|
219
240
|
}
|
|
241
|
+
const placeholders = (n) => Array(n).fill('?').join(',');
|
|
242
|
+
/** Edges a traversal follows: not `contains`, confidence ≥ 0.7 (or unset), of `types` when given. */
|
|
243
|
+
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
|
+
/** Escape LIKE's wildcards for `ESCAPE '\'`. */
|
|
245
|
+
const likeEscape = (s) => s.replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
246
|
+
/** Compile a caller-supplied name filter (case-insensitive). */
|
|
247
|
+
function nameRegex(pattern) {
|
|
248
|
+
try {
|
|
249
|
+
return new RegExp(pattern, 'i');
|
|
250
|
+
}
|
|
251
|
+
catch (e) {
|
|
252
|
+
throw new Error(`Invalid regex for name: ${e instanceof Error ? e.message : String(e)}`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function rowToEdge(r) {
|
|
256
|
+
const e = { source: r.source, target: r.target, type: r.type ?? undefined };
|
|
257
|
+
if (r.evidence != null)
|
|
258
|
+
e.evidence = r.evidence;
|
|
259
|
+
return e;
|
|
260
|
+
}
|
|
220
261
|
class SqliteGraphStore {
|
|
221
262
|
db;
|
|
263
|
+
/** Files written before cross-repo evidence was stored have no `evidence` column. */
|
|
264
|
+
evidenceCol;
|
|
265
|
+
/** Files written before it existed have no `nodes.key_tail`: exact resolution scans them. */
|
|
266
|
+
hasKeyTail;
|
|
267
|
+
hasRegexp;
|
|
222
268
|
constructor(db) {
|
|
223
269
|
this.db = db;
|
|
270
|
+
const cols = db.prepare('PRAGMA table_info(edges)').all().map((c) => c.name);
|
|
271
|
+
this.evidenceCol = cols.includes('evidence') ? 'evidence' : 'NULL AS evidence';
|
|
272
|
+
this.hasKeyTail = db.prepare('PRAGMA table_info(nodes)').all().some((c) => c.name === 'key_tail');
|
|
273
|
+
this.hasRegexp = this.registerRegexp();
|
|
274
|
+
}
|
|
275
|
+
registerRegexp() {
|
|
276
|
+
if (typeof this.db.function !== 'function')
|
|
277
|
+
return false;
|
|
278
|
+
let last;
|
|
279
|
+
try {
|
|
280
|
+
this.db.function('regexp', { deterministic: true }, (src, value) => {
|
|
281
|
+
if (last?.src !== src)
|
|
282
|
+
last = { src, re: new RegExp(src, 'i') };
|
|
283
|
+
return typeof value === 'string' && last.re.test(value) ? 1 : 0;
|
|
284
|
+
});
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
224
290
|
}
|
|
225
291
|
resolveNodes(name, repo, fuzzy = false) {
|
|
226
|
-
const repoClause = repo ? " AND key LIKE ? || '::%'" : '';
|
|
227
292
|
const params = [];
|
|
228
293
|
let where;
|
|
294
|
+
let repoCol = 'repo';
|
|
229
295
|
if (fuzzy) {
|
|
230
|
-
where =
|
|
231
|
-
params.push(name,
|
|
296
|
+
where = `label LIKE '%' || ? || '%' ESCAPE '\\' AND type NOT IN (${placeholders(NON_SYMBOL_TYPES.length)})`;
|
|
297
|
+
params.push(likeEscape(name), ...NON_SYMBOL_TYPES);
|
|
298
|
+
}
|
|
299
|
+
else if (this.hasKeyTail) {
|
|
300
|
+
// `=` / substr compare bytes: case-sensitive and wildcard-free. Every OR
|
|
301
|
+
// arm has an index (key, label, key_tail); key_tail narrows the suffix
|
|
302
|
+
// test to the keys that can end in `::name`.
|
|
303
|
+
where = '(key = ? OR label = ? OR (key_tail = ? AND substr(key, -length(?)) = ?))';
|
|
304
|
+
params.push(name, name, keyTail(`::${name}`), `::${name}`, `::${name}`);
|
|
305
|
+
repoCol = '+repo'; // `+`: filter only — keeps the planner on the OR's indexes, not a scan of the repo
|
|
232
306
|
}
|
|
233
307
|
else {
|
|
234
|
-
where =
|
|
235
|
-
params.push(name, name);
|
|
308
|
+
where = '(key = ? OR label = ? OR substr(key, -length(?)) = ?)';
|
|
309
|
+
params.push(name, name, `::${name}`, `::${name}`);
|
|
236
310
|
}
|
|
237
|
-
if (repo)
|
|
311
|
+
if (repo) {
|
|
312
|
+
where += ` AND ${repoCol} = ?`;
|
|
238
313
|
params.push(repo);
|
|
239
|
-
|
|
314
|
+
}
|
|
315
|
+
// 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)
|
|
240
317
|
.map((r) => ({ key: r.key, label: r.label || labelFromKey(r.key) }));
|
|
241
318
|
}
|
|
242
|
-
|
|
319
|
+
typedEndpoints(keys, side, limit, types) {
|
|
243
320
|
const col = side === 'callers' ? 'source' : 'target';
|
|
244
321
|
const match = side === 'callers' ? 'target' : 'source';
|
|
245
|
-
const
|
|
322
|
+
const typeClause = types?.length ? ` AND type IN (${placeholders(types.length)})` : '';
|
|
323
|
+
const seen = new Map();
|
|
246
324
|
for (const batch of chunked(keys)) {
|
|
247
|
-
const
|
|
248
|
-
const rows = this.db.prepare(`SELECT DISTINCT ${col} AS v FROM edges WHERE ${match} IN (${ph}) AND (type IS NULL OR type <> 'contains') LIMIT ?`).all(...batch, limit);
|
|
325
|
+
const rows = this.db.prepare(`SELECT DISTINCT ${col} AS v, type FROM edges WHERE ${match} IN (${placeholders(batch.length)}) AND (type IS NULL OR type <> 'contains')${typeClause} LIMIT ?`).all(...batch, ...(types ?? []), limit);
|
|
249
326
|
for (const r of rows) {
|
|
250
|
-
|
|
327
|
+
const type = r.type ?? '';
|
|
328
|
+
seen.set(`${type}\0${r.v}`, { key: r.v, type });
|
|
251
329
|
if (seen.size >= limit)
|
|
252
|
-
return [...seen];
|
|
330
|
+
return [...seen.values()];
|
|
253
331
|
}
|
|
254
332
|
}
|
|
255
|
-
return [...seen];
|
|
333
|
+
return [...seen.values()];
|
|
256
334
|
}
|
|
257
|
-
callers(targetKeys, limit) { return this.
|
|
258
|
-
dependencies(sourceKeys, limit) { return this.
|
|
335
|
+
callers(targetKeys, limit, types) { return this.typedEndpoints(targetKeys, 'callers', limit, types); }
|
|
336
|
+
dependencies(sourceKeys, limit, types) { return this.typedEndpoints(sourceKeys, 'deps', limit, types); }
|
|
259
337
|
crossRepoEdges(repo, limit) {
|
|
260
|
-
const base =
|
|
338
|
+
const base = "FROM edges WHERE (source_repo <> target_repo OR type = 'workspace-dep')" + (repo ? ' AND (source_repo = ? OR target_repo = ?)' : '');
|
|
261
339
|
const p = repo ? [repo, repo] : [];
|
|
262
340
|
const total = this.db.prepare(`SELECT COUNT(*) c ${base}`).get(...p).c;
|
|
263
|
-
const edges = this.db.prepare(`SELECT source, target, type ${base} LIMIT ?`).all(...p, limit)
|
|
264
|
-
.map((r) => ({ source: r.source, target: r.target, type: r.type }));
|
|
341
|
+
const edges = this.db.prepare(`SELECT source, target, type, ${this.evidenceCol} ${base} LIMIT ?`).all(...p, limit).map(rowToEdge);
|
|
265
342
|
return { edges, total };
|
|
266
343
|
}
|
|
267
344
|
nodesInFiles(repo, files, entity) {
|
|
268
345
|
const out = [];
|
|
346
|
+
const ent = entity ? ' AND substr(key, -length(?)) = ?' : '';
|
|
347
|
+
// Keys under a file sort between `<prefix>::` and `<prefix>:;` (';' follows ':').
|
|
348
|
+
const stmt = this.db.prepare(`SELECT key FROM nodes WHERE repo = ? AND (key = ? OR (key >= ? AND key < ?))${ent} LIMIT 2000`);
|
|
269
349
|
for (const file of files) {
|
|
270
350
|
const prefix = `${repo}::${file}`;
|
|
271
|
-
const
|
|
272
|
-
const params = [repo, prefix, `${prefix}::%`];
|
|
351
|
+
const params = [repo, prefix, `${prefix}::`, `${prefix}:;`];
|
|
273
352
|
if (entity)
|
|
274
|
-
params.push(
|
|
275
|
-
|
|
276
|
-
for (const r of rows)
|
|
353
|
+
params.push(`::${entity}`, `::${entity}`);
|
|
354
|
+
for (const r of stmt.all(...params))
|
|
277
355
|
out.push(r.key);
|
|
278
356
|
}
|
|
279
357
|
return out;
|
|
280
358
|
}
|
|
281
|
-
dependents(nodeKeys, limit) {
|
|
359
|
+
dependents(nodeKeys, limit, maxRows) {
|
|
282
360
|
const set = new Set(nodeKeys);
|
|
361
|
+
const sym = [...SYMMETRIC_EDGE_TYPES];
|
|
283
362
|
const edges = [];
|
|
284
363
|
const repos = new Set();
|
|
285
364
|
let total = 0;
|
|
365
|
+
let read = 0;
|
|
366
|
+
const take = (r) => {
|
|
367
|
+
if (set.has(r.source))
|
|
368
|
+
return; // dependents are from OUTSIDE the set
|
|
369
|
+
total++;
|
|
370
|
+
repos.add(r.source_repo || repoOf(r.source));
|
|
371
|
+
if (edges.length < limit)
|
|
372
|
+
edges.push(rowToEdge(r));
|
|
373
|
+
};
|
|
374
|
+
const full = () => maxRows !== undefined && read >= maxRows;
|
|
375
|
+
const scan = (sql, params) => {
|
|
376
|
+
const rows = this.db.prepare(`${sql} LIMIT ?`).all(...params, maxRows === undefined ? -1 : maxRows - read); // -1 = no limit
|
|
377
|
+
read += rows.length;
|
|
378
|
+
for (const r of rows)
|
|
379
|
+
take(r);
|
|
380
|
+
};
|
|
286
381
|
for (const batch of chunked(nodeKeys)) {
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
repos.add(r.source_repo || repoOf(r.source));
|
|
294
|
-
if (edges.length < limit)
|
|
295
|
-
edges.push({ source: r.source, target: r.target, type: r.type });
|
|
382
|
+
if (full())
|
|
383
|
+
break;
|
|
384
|
+
const ph = placeholders(batch.length);
|
|
385
|
+
scan(`SELECT source, target, type, ${this.evidenceCol}, source_repo FROM edges WHERE target IN (${ph}) AND (type IS NULL OR type <> 'contains')`, batch);
|
|
386
|
+
if (!full()) {
|
|
387
|
+
scan(`SELECT target AS source, source AS target, type, ${this.evidenceCol}, target_repo AS source_repo FROM edges WHERE source IN (${ph}) AND type IN (${placeholders(sym.length)})`, [...batch, ...sym]);
|
|
296
388
|
}
|
|
297
389
|
}
|
|
298
|
-
return { edges, total, repos: [...repos] };
|
|
390
|
+
return { edges, total, repos: [...repos], truncated: full() };
|
|
299
391
|
}
|
|
300
|
-
neighborsOf(key, direction) {
|
|
392
|
+
neighborsOf(key, direction, types) {
|
|
301
393
|
const out = new Set();
|
|
302
|
-
const conf =
|
|
394
|
+
const conf = neighborFilter(types);
|
|
395
|
+
const tp = types ?? [];
|
|
303
396
|
if (direction === 'callees' || direction === 'both') {
|
|
304
|
-
for (const r of this.db.prepare(`SELECT target FROM edges WHERE source = ? AND ${conf}`).all(key))
|
|
397
|
+
for (const r of this.db.prepare(`SELECT target FROM edges WHERE source = ? AND ${conf}`).all(key, ...tp))
|
|
305
398
|
out.add(r.target);
|
|
306
399
|
}
|
|
307
400
|
if (direction === 'callers' || direction === 'both') {
|
|
308
|
-
for (const r of this.db.prepare(`SELECT source FROM edges WHERE target = ? AND ${conf}`).all(key))
|
|
401
|
+
for (const r of this.db.prepare(`SELECT source FROM edges WHERE target = ? AND ${conf}`).all(key, ...tp))
|
|
309
402
|
out.add(r.source);
|
|
310
403
|
}
|
|
311
404
|
return [...out];
|
|
312
405
|
}
|
|
406
|
+
neighborEdges(keys, direction, types, limit) {
|
|
407
|
+
const filter = neighborFilter(types);
|
|
408
|
+
const tp = types ?? [];
|
|
409
|
+
const out = [];
|
|
410
|
+
for (const batch of chunked(keys)) {
|
|
411
|
+
if (out.length >= limit)
|
|
412
|
+
break;
|
|
413
|
+
const ph = placeholders(batch.length);
|
|
414
|
+
const parts = [];
|
|
415
|
+
const params = [];
|
|
416
|
+
if (direction === 'callees' || direction === 'both') {
|
|
417
|
+
parts.push(`SELECT source AS k, target AS n FROM edges WHERE source IN (${ph}) AND ${filter}`);
|
|
418
|
+
params.push(...batch, ...tp);
|
|
419
|
+
}
|
|
420
|
+
if (direction === 'callers' || direction === 'both') {
|
|
421
|
+
parts.push(`SELECT target AS k, source AS n FROM edges WHERE target IN (${ph}) AND ${filter}`);
|
|
422
|
+
params.push(...batch, ...tp);
|
|
423
|
+
}
|
|
424
|
+
for (const r of this.db.prepare(`${parts.join(' UNION ALL ')} LIMIT ?`).all(...params, limit - out.length)) {
|
|
425
|
+
out.push([r.k, r.n]);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return out;
|
|
429
|
+
}
|
|
313
430
|
labelsOf(keys) {
|
|
314
431
|
const m = new Map();
|
|
315
432
|
for (const batch of chunked(keys)) {
|
|
@@ -334,28 +451,39 @@ class SqliteGraphStore {
|
|
|
334
451
|
return m;
|
|
335
452
|
}
|
|
336
453
|
searchNodes(f, limit) {
|
|
454
|
+
const re = f.name ? nameRegex(f.name) : undefined;
|
|
337
455
|
const cond = ['degree >= ?'];
|
|
338
456
|
const p = [f.minDegree ?? 0];
|
|
339
457
|
if (f.repo) {
|
|
340
|
-
cond.push(
|
|
458
|
+
cond.push('repo = ?');
|
|
341
459
|
p.push(f.repo);
|
|
342
460
|
}
|
|
343
461
|
if (f.type) {
|
|
344
462
|
cond.push('type = ?');
|
|
345
463
|
p.push(f.type);
|
|
346
464
|
}
|
|
465
|
+
else if (re) {
|
|
466
|
+
cond.push(`type NOT IN (${placeholders(NON_SYMBOL_TYPES.length)})`);
|
|
467
|
+
p.push(...NON_SYMBOL_TYPES);
|
|
468
|
+
}
|
|
347
469
|
if (f.file) {
|
|
348
|
-
cond.push("file LIKE '%' || ? || '%'");
|
|
349
|
-
p.push(f.file);
|
|
470
|
+
cond.push("file LIKE '%' || ? || '%' ESCAPE '\\'");
|
|
471
|
+
p.push(likeEscape(f.file));
|
|
350
472
|
}
|
|
351
|
-
if (
|
|
352
|
-
cond.push(
|
|
353
|
-
p.push(f.name
|
|
473
|
+
if (re && this.hasRegexp) {
|
|
474
|
+
cond.push('regexp(?, label)');
|
|
475
|
+
p.push(f.name);
|
|
354
476
|
}
|
|
355
477
|
const where = cond.join(' AND ');
|
|
478
|
+
const toRow = (r) => ({ key: r.key, label: r.label || labelFromKey(r.key), type: r.type || '?', file: r.file || fileOf(r.key), degree: r.degree ?? 0 });
|
|
479
|
+
const select = `SELECT key,label,type,file,degree FROM nodes WHERE ${where} ORDER BY degree DESC`;
|
|
480
|
+
if (re && !this.hasRegexp) {
|
|
481
|
+
// Driver without user functions: match the label in JS.
|
|
482
|
+
const all = this.db.prepare(select).all(...p).filter((r) => re.test(r.label ?? ''));
|
|
483
|
+
return { rows: all.slice(0, limit).map(toRow), total: all.length };
|
|
484
|
+
}
|
|
356
485
|
const total = this.db.prepare(`SELECT COUNT(*) c FROM nodes WHERE ${where}`).get(...p).c;
|
|
357
|
-
const rows = this.db.prepare(
|
|
358
|
-
.map((r) => ({ key: r.key, label: r.label || labelFromKey(r.key), type: r.type || '?', file: r.file || fileOf(r.key), degree: r.degree ?? 0 }));
|
|
486
|
+
const rows = this.db.prepare(`${select} LIMIT ?`).all(...p, limit).map(toRow);
|
|
359
487
|
return { rows, total };
|
|
360
488
|
}
|
|
361
489
|
close() { this.db.close(); }
|
|
@@ -363,8 +491,7 @@ class SqliteGraphStore {
|
|
|
363
491
|
class JsonGraphStore {
|
|
364
492
|
nodes;
|
|
365
493
|
edges;
|
|
366
|
-
|
|
367
|
-
adjCallers;
|
|
494
|
+
adjCache = new Map();
|
|
368
495
|
degreeCache;
|
|
369
496
|
constructor(nodes, edges) {
|
|
370
497
|
this.nodes = nodes;
|
|
@@ -372,28 +499,46 @@ class JsonGraphStore {
|
|
|
372
499
|
}
|
|
373
500
|
et(e) { return e.attributes?.type ?? e.attributes?.relation; }
|
|
374
501
|
label(n) { return n.attributes?.label ?? labelFromKey(n.key); }
|
|
502
|
+
edge(e) {
|
|
503
|
+
const out = { source: e.source, target: e.target, type: this.et(e) };
|
|
504
|
+
if (e.attributes?.evidence != null)
|
|
505
|
+
out.evidence = e.attributes.evidence;
|
|
506
|
+
return out;
|
|
507
|
+
}
|
|
375
508
|
resolveNodes(name, repo, fuzzy = false) {
|
|
376
509
|
const inRepo = (k) => !repo || k.startsWith(repo + '::');
|
|
510
|
+
const lc = name.toLowerCase();
|
|
377
511
|
return this.nodes.filter((n) => inRepo(n.key) && (fuzzy
|
|
378
|
-
? (
|
|
379
|
-
: (n.
|
|
380
|
-
}
|
|
381
|
-
callers(targetKeys, limit) {
|
|
382
|
-
const set = new Set(targetKeys);
|
|
383
|
-
return [...new Set(this.edges.filter((e) => set.has(e.target) && this.et(e) !== 'contains').map((e) => e.source))].slice(0, limit);
|
|
512
|
+
? !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) }));
|
|
384
514
|
}
|
|
385
|
-
|
|
386
|
-
const set = new Set(
|
|
387
|
-
|
|
515
|
+
typedEndpoints(keys, side, limit, types) {
|
|
516
|
+
const set = new Set(keys);
|
|
517
|
+
const want = types?.length ? new Set(types) : null;
|
|
518
|
+
const seen = new Map();
|
|
519
|
+
for (const e of this.edges) {
|
|
520
|
+
const type = this.et(e) ?? '';
|
|
521
|
+
if (type === 'contains' || (want && !want.has(type)))
|
|
522
|
+
continue;
|
|
523
|
+
if (!set.has(side === 'callers' ? e.target : e.source))
|
|
524
|
+
continue;
|
|
525
|
+
const key = side === 'callers' ? e.source : e.target;
|
|
526
|
+
seen.set(`${type}\0${key}`, { key, type });
|
|
527
|
+
if (seen.size >= limit)
|
|
528
|
+
break;
|
|
529
|
+
}
|
|
530
|
+
return [...seen.values()];
|
|
388
531
|
}
|
|
532
|
+
callers(targetKeys, limit, types) { return this.typedEndpoints(targetKeys, 'callers', limit, types); }
|
|
533
|
+
dependencies(sourceKeys, limit, types) { return this.typedEndpoints(sourceKeys, 'deps', limit, types); }
|
|
389
534
|
crossRepoEdges(repo, limit) {
|
|
390
535
|
const cross = this.edges.filter((e) => {
|
|
391
536
|
const s = repoOf(e.source), t = repoOf(e.target);
|
|
392
|
-
if (!s || !t || s === t)
|
|
537
|
+
if (!s || !t || (s === t && this.et(e) !== 'workspace-dep'))
|
|
393
538
|
return false;
|
|
394
539
|
return !repo || s === repo || t === repo;
|
|
395
540
|
});
|
|
396
|
-
return { edges: cross.slice(0, limit).map((e) =>
|
|
541
|
+
return { edges: cross.slice(0, limit).map((e) => this.edge(e)), total: cross.length };
|
|
397
542
|
}
|
|
398
543
|
nodesInFiles(repo, files, entity) {
|
|
399
544
|
const out = [];
|
|
@@ -406,22 +551,38 @@ class JsonGraphStore {
|
|
|
406
551
|
}
|
|
407
552
|
return out;
|
|
408
553
|
}
|
|
409
|
-
dependents(nodeKeys, limit) {
|
|
554
|
+
dependents(nodeKeys, limit, maxRows = Number.POSITIVE_INFINITY) {
|
|
410
555
|
const set = new Set(nodeKeys);
|
|
411
|
-
const all =
|
|
556
|
+
const all = [];
|
|
557
|
+
for (const e of this.edges) {
|
|
558
|
+
if (all.length >= maxRows)
|
|
559
|
+
break;
|
|
560
|
+
const type = this.et(e);
|
|
561
|
+
if (type === 'contains')
|
|
562
|
+
continue;
|
|
563
|
+
if (set.has(e.target) && !set.has(e.source))
|
|
564
|
+
all.push(this.edge(e));
|
|
565
|
+
else if (type && SYMMETRIC_EDGE_TYPES.has(type) && set.has(e.source) && !set.has(e.target)) {
|
|
566
|
+
all.push({ ...this.edge(e), source: e.target, target: e.source });
|
|
567
|
+
}
|
|
568
|
+
}
|
|
412
569
|
const repos = [...new Set(all.map((e) => repoOf(e.source)))];
|
|
413
|
-
return { edges: all.slice(0, limit)
|
|
570
|
+
return { edges: all.slice(0, limit), total: all.length, repos, truncated: all.length >= maxRows };
|
|
414
571
|
}
|
|
415
|
-
adj(direction) {
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
if (
|
|
419
|
-
return
|
|
572
|
+
adj(direction, types) {
|
|
573
|
+
const cacheKey = `${direction}|${types?.join(',') ?? '*'}`;
|
|
574
|
+
const cached = this.adjCache.get(cacheKey);
|
|
575
|
+
if (cached)
|
|
576
|
+
return cached;
|
|
577
|
+
const want = types?.length ? new Set(types) : null;
|
|
420
578
|
const m = new Map();
|
|
421
579
|
const add = (a, b) => { if (!m.has(a))
|
|
422
580
|
m.set(a, new Set()); m.get(a).add(b); };
|
|
423
581
|
for (const e of this.edges) {
|
|
424
|
-
|
|
582
|
+
const type = this.et(e);
|
|
583
|
+
if (!e.source || !e.target || type === 'contains')
|
|
584
|
+
continue;
|
|
585
|
+
if (want && !want.has(type ?? ''))
|
|
425
586
|
continue;
|
|
426
587
|
if ((e.attributes?.confidence ?? 0.8) < 0.7)
|
|
427
588
|
continue;
|
|
@@ -430,13 +591,22 @@ class JsonGraphStore {
|
|
|
430
591
|
if (direction === 'callers' || direction === 'both')
|
|
431
592
|
add(e.target, e.source);
|
|
432
593
|
}
|
|
433
|
-
|
|
434
|
-
this.adjCallees = m;
|
|
435
|
-
else if (direction === 'callers')
|
|
436
|
-
this.adjCallers = m;
|
|
594
|
+
this.adjCache.set(cacheKey, m);
|
|
437
595
|
return m;
|
|
438
596
|
}
|
|
439
|
-
neighborsOf(key, direction) { return [...(this.adj(direction).get(key) ?? [])]; }
|
|
597
|
+
neighborsOf(key, direction, types) { return [...(this.adj(direction, types).get(key) ?? [])]; }
|
|
598
|
+
neighborEdges(keys, direction, types, limit) {
|
|
599
|
+
const adj = this.adj(direction, types);
|
|
600
|
+
const out = [];
|
|
601
|
+
for (const k of keys) {
|
|
602
|
+
for (const n of adj.get(k) ?? []) {
|
|
603
|
+
if (out.length >= limit)
|
|
604
|
+
return out;
|
|
605
|
+
out.push([k, n]);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
return out;
|
|
609
|
+
}
|
|
440
610
|
labelsOf(keys) {
|
|
441
611
|
const want = new Set(keys);
|
|
442
612
|
const m = new Map();
|
|
@@ -469,27 +639,19 @@ class JsonGraphStore {
|
|
|
469
639
|
return (this.degreeCache = d);
|
|
470
640
|
}
|
|
471
641
|
searchNodes(f, limit) {
|
|
642
|
+
const re = f.name ? nameRegex(f.name) : undefined;
|
|
472
643
|
const deg = this.degree();
|
|
473
|
-
|
|
474
|
-
if (f.name) {
|
|
475
|
-
try {
|
|
476
|
-
const re = new RegExp(f.name, 'i');
|
|
477
|
-
nameTest = (s) => re.test(s);
|
|
478
|
-
}
|
|
479
|
-
catch {
|
|
480
|
-
const lc = f.name.toLowerCase();
|
|
481
|
-
nameTest = (s) => s.toLowerCase().includes(lc);
|
|
482
|
-
}
|
|
483
|
-
}
|
|
644
|
+
const fileLc = f.file?.toLowerCase();
|
|
484
645
|
const matches = this.nodes.filter((n) => {
|
|
485
646
|
if (f.repo && !n.key.startsWith(f.repo + '::'))
|
|
486
647
|
return false;
|
|
487
|
-
|
|
648
|
+
const type = n.attributes?.type ?? '';
|
|
649
|
+
if (f.type ? type !== f.type : re && NON_SYMBOL_TYPES.includes(type))
|
|
488
650
|
return false;
|
|
489
651
|
const file = n.attributes?.file ?? fileOf(n.key);
|
|
490
|
-
if (
|
|
652
|
+
if (fileLc && !file.toLowerCase().includes(fileLc))
|
|
491
653
|
return false;
|
|
492
|
-
if (
|
|
654
|
+
if (re && !re.test(this.label(n)))
|
|
493
655
|
return false;
|
|
494
656
|
return (deg.get(n.key) ?? 0) >= (f.minDegree ?? 0);
|
|
495
657
|
}).map((n) => ({ key: n.key, label: this.label(n), type: n.attributes?.type ?? '?', file: n.attributes?.file ?? fileOf(n.key), degree: deg.get(n.key) ?? 0 }))
|