@optave/codegraph 3.3.0 → 3.3.1

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.
@@ -3,9 +3,13 @@
3
3
  *
4
4
  * Reuses pipeline helpers instead of duplicating node insertion and edge building
5
5
  * logic from the main builder. This eliminates the watcher.js divergence (ROADMAP 3.9).
6
+ *
7
+ * Reverse-dep cascade: when a file changes, files that have edges targeting it
8
+ * must have their outgoing edges rebuilt (since the changed file's node IDs change).
6
9
  */
7
10
  import fs from 'node:fs';
8
11
  import path from 'node:path';
12
+ import { bulkNodeIdsByFile } from '../../../db/index.js';
9
13
  import { warn } from '../../../infrastructure/logger.js';
10
14
  import { normalizePath } from '../../../shared/constants.js';
11
15
  import { parseFileIncremental } from '../../parser.js';
@@ -18,15 +22,252 @@ function insertFileNodes(stmts, relPath, symbols) {
18
22
  stmts.insertNode.run(relPath, 'file', relPath, 0, null);
19
23
  for (const def of symbols.definitions) {
20
24
  stmts.insertNode.run(def.name, def.kind, relPath, def.line, def.endLine || null);
25
+ if (def.children?.length) {
26
+ for (const child of def.children) {
27
+ stmts.insertNode.run(child.name, child.kind, relPath, child.line, child.endLine || null);
28
+ }
29
+ }
21
30
  }
22
31
  for (const exp of symbols.exports) {
23
32
  stmts.insertNode.run(exp.name, exp.kind, relPath, exp.line, null);
24
33
  }
25
34
  }
26
35
 
36
+ // ── Containment edges ──────────────────────────────────────────────────
37
+
38
+ function buildContainmentEdges(db, stmts, relPath, symbols) {
39
+ const nodeIdMap = new Map();
40
+ for (const row of bulkNodeIdsByFile(db, relPath)) {
41
+ nodeIdMap.set(`${row.name}|${row.kind}|${row.line}`, row.id);
42
+ }
43
+ const fileId = nodeIdMap.get(`${relPath}|file|0`);
44
+ let edgesAdded = 0;
45
+ for (const def of symbols.definitions) {
46
+ const defId = nodeIdMap.get(`${def.name}|${def.kind}|${def.line}`);
47
+ if (fileId && defId) {
48
+ stmts.insertEdge.run(fileId, defId, 'contains', 1.0, 0);
49
+ edgesAdded++;
50
+ }
51
+ if (def.children?.length && defId) {
52
+ for (const child of def.children) {
53
+ const childId = nodeIdMap.get(`${child.name}|${child.kind}|${child.line}`);
54
+ if (childId) {
55
+ stmts.insertEdge.run(defId, childId, 'contains', 1.0, 0);
56
+ edgesAdded++;
57
+ if (child.kind === 'parameter') {
58
+ stmts.insertEdge.run(childId, defId, 'parameter_of', 1.0, 0);
59
+ edgesAdded++;
60
+ }
61
+ }
62
+ }
63
+ }
64
+ }
65
+ return edgesAdded;
66
+ }
67
+
68
+ // ── Reverse-dep cascade ────────────────────────────────────────────────
69
+
70
+ // Lazily-cached prepared statements for reverse-dep operations
71
+ let _revDepDb = null;
72
+ let _findRevDepsStmt = null;
73
+ let _deleteOutEdgesStmt = null;
74
+
75
+ function getRevDepStmts(db) {
76
+ if (_revDepDb !== db) {
77
+ _revDepDb = db;
78
+ _findRevDepsStmt = db.prepare(
79
+ `SELECT DISTINCT n_src.file FROM edges e
80
+ JOIN nodes n_src ON e.source_id = n_src.id
81
+ JOIN nodes n_tgt ON e.target_id = n_tgt.id
82
+ WHERE n_tgt.file = ? AND n_src.file != ? AND n_src.kind != 'directory'`,
83
+ );
84
+ _deleteOutEdgesStmt = db.prepare(
85
+ 'DELETE FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE file = ?)',
86
+ );
87
+ }
88
+ return { findRevDepsStmt: _findRevDepsStmt, deleteOutEdgesStmt: _deleteOutEdgesStmt };
89
+ }
90
+
91
+ function findReverseDeps(db, relPath) {
92
+ const { findRevDepsStmt } = getRevDepStmts(db);
93
+ return findRevDepsStmt.all(relPath, relPath).map((r) => r.file);
94
+ }
95
+
96
+ function deleteOutgoingEdges(db, relPath) {
97
+ const { deleteOutEdgesStmt } = getRevDepStmts(db);
98
+ deleteOutEdgesStmt.run(relPath);
99
+ }
100
+
101
+ async function parseReverseDep(rootDir, depRelPath, engineOpts, cache) {
102
+ const absPath = path.join(rootDir, depRelPath);
103
+ if (!fs.existsSync(absPath)) return null;
104
+
105
+ let code;
106
+ try {
107
+ code = readFileSafe(absPath);
108
+ } catch {
109
+ return null;
110
+ }
111
+
112
+ return parseFileIncremental(cache, absPath, code, engineOpts);
113
+ }
114
+
115
+ function rebuildReverseDepEdges(db, rootDir, depRelPath, symbols, stmts, skipBarrel) {
116
+ const fileNodeRow = stmts.getNodeId.get(depRelPath, 'file', depRelPath, 0);
117
+ if (!fileNodeRow) return 0;
118
+
119
+ const aliases = { baseUrl: null, paths: {} };
120
+ let edgesAdded = buildContainmentEdges(db, stmts, depRelPath, symbols);
121
+ // Don't rebuild dir→file containment for reverse-deps (it was never deleted)
122
+ edgesAdded += buildImportEdges(
123
+ stmts,
124
+ depRelPath,
125
+ symbols,
126
+ rootDir,
127
+ fileNodeRow.id,
128
+ aliases,
129
+ skipBarrel ? null : db,
130
+ );
131
+ const importedNames = buildImportedNamesMap(symbols, rootDir, depRelPath, aliases);
132
+ edgesAdded += buildCallEdges(stmts, depRelPath, symbols, fileNodeRow, importedNames);
133
+ return edgesAdded;
134
+ }
135
+
136
+ // ── Directory containment edges ────────────────────────────────────────
137
+
138
+ function rebuildDirContainment(_db, stmts, relPath) {
139
+ const dir = normalizePath(path.dirname(relPath));
140
+ if (!dir || dir === '.') return 0;
141
+ const dirRow = stmts.getNodeId.get(dir, 'directory', dir, 0);
142
+ const fileRow = stmts.getNodeId.get(relPath, 'file', relPath, 0);
143
+ if (dirRow && fileRow) {
144
+ stmts.insertEdge.run(dirRow.id, fileRow.id, 'contains', 1.0, 0);
145
+ return 1;
146
+ }
147
+ return 0;
148
+ }
149
+
150
+ // ── Ancillary table cleanup ────────────────────────────────────────────
151
+
152
+ function purgeAncillaryData(db, relPath) {
153
+ const tryExec = (sql, ...args) => {
154
+ try {
155
+ db.prepare(sql).run(...args);
156
+ } catch (err) {
157
+ if (!err?.message?.includes('no such table')) throw err;
158
+ }
159
+ };
160
+ tryExec(
161
+ 'DELETE FROM function_complexity WHERE node_id IN (SELECT id FROM nodes WHERE file = ?)',
162
+ relPath,
163
+ );
164
+ tryExec(
165
+ 'DELETE FROM node_metrics WHERE node_id IN (SELECT id FROM nodes WHERE file = ?)',
166
+ relPath,
167
+ );
168
+ tryExec(
169
+ 'DELETE FROM cfg_edges WHERE function_node_id IN (SELECT id FROM nodes WHERE file = ?)',
170
+ relPath,
171
+ );
172
+ tryExec(
173
+ 'DELETE FROM cfg_blocks WHERE function_node_id IN (SELECT id FROM nodes WHERE file = ?)',
174
+ relPath,
175
+ );
176
+ tryExec(
177
+ 'DELETE FROM dataflow WHERE source_id IN (SELECT id FROM nodes WHERE file = ?) OR target_id IN (SELECT id FROM nodes WHERE file = ?)',
178
+ relPath,
179
+ relPath,
180
+ );
181
+ tryExec('DELETE FROM ast_nodes WHERE file = ?', relPath);
182
+ }
183
+
27
184
  // ── Import edge building ────────────────────────────────────────────────
28
185
 
29
- function buildImportEdges(stmts, relPath, symbols, rootDir, fileNodeId, aliases) {
186
+ // Lazily-cached prepared statements for barrel resolution (avoid re-preparing in hot loops)
187
+ let _barrelDb = null;
188
+ let _isBarrelStmt = null;
189
+ let _reexportTargetsStmt = null;
190
+ let _hasDefStmt = null;
191
+
192
+ function getBarrelStmts(db) {
193
+ if (_barrelDb !== db) {
194
+ _barrelDb = db;
195
+ _isBarrelStmt = db.prepare(
196
+ `SELECT COUNT(*) as c FROM edges e
197
+ JOIN nodes n ON e.source_id = n.id
198
+ WHERE e.kind = 'reexports' AND n.file = ? AND n.kind = 'file'`,
199
+ );
200
+ _reexportTargetsStmt = db.prepare(
201
+ `SELECT DISTINCT n2.file FROM edges e
202
+ JOIN nodes n1 ON e.source_id = n1.id
203
+ JOIN nodes n2 ON e.target_id = n2.id
204
+ WHERE e.kind = 'reexports' AND n1.file = ? AND n1.kind = 'file'`,
205
+ );
206
+ _hasDefStmt = db.prepare(
207
+ `SELECT 1 FROM nodes WHERE name = ? AND file = ? AND kind != 'file' AND kind != 'directory' LIMIT 1`,
208
+ );
209
+ }
210
+ return {
211
+ isBarrelStmt: _isBarrelStmt,
212
+ reexportTargetsStmt: _reexportTargetsStmt,
213
+ hasDefStmt: _hasDefStmt,
214
+ };
215
+ }
216
+
217
+ function isBarrelFile(db, relPath) {
218
+ const { isBarrelStmt } = getBarrelStmts(db);
219
+ const reexportCount = isBarrelStmt.get(relPath)?.c;
220
+ return (reexportCount || 0) > 0;
221
+ }
222
+
223
+ function resolveBarrelTarget(db, barrelPath, symbolName, visited = new Set()) {
224
+ if (visited.has(barrelPath)) return null;
225
+ visited.add(barrelPath);
226
+
227
+ const { reexportTargetsStmt, hasDefStmt } = getBarrelStmts(db);
228
+
229
+ // Find re-export targets from this barrel
230
+ const reexportTargets = reexportTargetsStmt.all(barrelPath);
231
+
232
+ for (const { file: targetFile } of reexportTargets) {
233
+ // Check if the symbol is defined in this target file
234
+ const hasDef = hasDefStmt.get(symbolName, targetFile);
235
+ if (hasDef) return targetFile;
236
+
237
+ // Recurse through barrel chains
238
+ if (isBarrelFile(db, targetFile)) {
239
+ const deeper = resolveBarrelTarget(db, targetFile, symbolName, visited);
240
+ if (deeper) return deeper;
241
+ }
242
+ }
243
+ return null;
244
+ }
245
+
246
+ /**
247
+ * Resolve barrel imports for a single import statement and create edges to actual source files.
248
+ * Shared by buildImportEdges (primary file) and Pass 2 of the reverse-dep cascade.
249
+ */
250
+ function resolveBarrelImportEdges(db, stmts, fileNodeId, resolvedPath, imp) {
251
+ let edgesAdded = 0;
252
+ if (!isBarrelFile(db, resolvedPath)) return edgesAdded;
253
+ const resolvedSources = new Set();
254
+ for (const name of imp.names) {
255
+ const cleanName = name.replace(/^\*\s+as\s+/, '');
256
+ const actualSource = resolveBarrelTarget(db, resolvedPath, cleanName);
257
+ if (actualSource && actualSource !== resolvedPath && !resolvedSources.has(actualSource)) {
258
+ resolvedSources.add(actualSource);
259
+ const actualRow = stmts.getNodeId.get(actualSource, 'file', actualSource, 0);
260
+ if (actualRow) {
261
+ const kind = imp.typeOnly ? 'imports-type' : 'imports';
262
+ stmts.insertEdge.run(fileNodeId, actualRow.id, kind, 0.9, 0);
263
+ edgesAdded++;
264
+ }
265
+ }
266
+ }
267
+ return edgesAdded;
268
+ }
269
+
270
+ function buildImportEdges(stmts, relPath, symbols, rootDir, fileNodeId, aliases, db) {
30
271
  let edgesAdded = 0;
31
272
  for (const imp of symbols.imports) {
32
273
  const resolvedPath = resolveImportPath(
@@ -40,6 +281,11 @@ function buildImportEdges(stmts, relPath, symbols, rootDir, fileNodeId, aliases)
40
281
  const edgeKind = imp.reexport ? 'reexports' : imp.typeOnly ? 'imports-type' : 'imports';
41
282
  stmts.insertEdge.run(fileNodeId, targetRow.id, edgeKind, 1.0, 0);
42
283
  edgesAdded++;
284
+
285
+ // Barrel resolution: create edges through re-export chains
286
+ if (!imp.reexport && db) {
287
+ edgesAdded += resolveBarrelImportEdges(db, stmts, fileNodeId, resolvedPath, imp);
288
+ }
43
289
  }
44
290
  }
45
291
  return edgesAdded;
@@ -116,7 +362,13 @@ function resolveCallTargets(stmts, call, relPath, importedNames, typeMap) {
116
362
  }
117
363
 
118
364
  function buildCallEdges(stmts, relPath, symbols, fileNodeRow, importedNames) {
119
- const typeMap = symbols.typeMap || new Map();
365
+ const rawTM = symbols.typeMap;
366
+ const typeMap =
367
+ rawTM instanceof Map
368
+ ? rawTM
369
+ : Array.isArray(rawTM) && rawTM.length > 0
370
+ ? new Map(rawTM.map((e) => [e.name, e.typeName ?? e.type ?? null]))
371
+ : new Map();
120
372
  let edgesAdded = 0;
121
373
  for (const call of symbols.calls) {
122
374
  if (call.receiver && BUILTIN_RECEIVERS.has(call.receiver)) continue;
@@ -146,7 +398,7 @@ function buildCallEdges(stmts, relPath, symbols, fileNodeRow, importedNames) {
146
398
  /**
147
399
  * Parse a single file and update the database incrementally.
148
400
  *
149
- * @param {import('better-sqlite3').Database} _db
401
+ * @param {import('better-sqlite3').Database} db
150
402
  * @param {string} rootDir - Absolute root directory
151
403
  * @param {string} filePath - Absolute file path
152
404
  * @param {object} stmts - Prepared DB statements
@@ -156,12 +408,17 @@ function buildCallEdges(stmts, relPath, symbols, fileNodeRow, importedNames) {
156
408
  * @param {Function} [options.diffSymbols] - Symbol diff function
157
409
  * @returns {Promise<object|null>} Update result or null on failure
158
410
  */
159
- export async function rebuildFile(_db, rootDir, filePath, stmts, engineOpts, cache, options = {}) {
411
+ export async function rebuildFile(db, rootDir, filePath, stmts, engineOpts, cache, options = {}) {
160
412
  const { diffSymbols } = options;
161
413
  const relPath = normalizePath(path.relative(rootDir, filePath));
162
414
  const oldNodes = stmts.countNodes.get(relPath)?.c || 0;
163
415
  const oldSymbols = diffSymbols ? stmts.listSymbols.all(relPath) : [];
164
416
 
417
+ // Find reverse-deps BEFORE purging (edges still reference the old nodes)
418
+ const reverseDeps = findReverseDeps(db, relPath);
419
+
420
+ // Purge ancillary tables, then edges, then nodes
421
+ purgeAncillaryData(db, relPath);
165
422
  stmts.deleteEdgesForFile.run(relPath);
166
423
  stmts.deleteNodes.run(relPath);
167
424
 
@@ -203,10 +460,44 @@ export async function rebuildFile(_db, rootDir, filePath, stmts, engineOpts, cac
203
460
 
204
461
  const aliases = { baseUrl: null, paths: {} };
205
462
 
206
- let edgesAdded = buildImportEdges(stmts, relPath, symbols, rootDir, fileNodeRow.id, aliases);
463
+ let edgesAdded = buildContainmentEdges(db, stmts, relPath, symbols);
464
+ edgesAdded += rebuildDirContainment(db, stmts, relPath);
465
+ edgesAdded += buildImportEdges(stmts, relPath, symbols, rootDir, fileNodeRow.id, aliases, db);
207
466
  const importedNames = buildImportedNamesMap(symbols, rootDir, relPath, aliases);
208
467
  edgesAdded += buildCallEdges(stmts, relPath, symbols, fileNodeRow, importedNames);
209
468
 
469
+ // Cascade: rebuild outgoing edges for reverse-dep files.
470
+ // Two-pass approach: first rebuild direct edges (creating reexports edges for barrels),
471
+ // then add barrel import edges (which need reexports edges to exist for resolution).
472
+ const depSymbols = new Map();
473
+ for (const depRelPath of reverseDeps) {
474
+ const symbols_ = await parseReverseDep(rootDir, depRelPath, engineOpts, cache);
475
+ if (symbols_) {
476
+ deleteOutgoingEdges(db, depRelPath);
477
+ depSymbols.set(depRelPath, symbols_);
478
+ }
479
+ }
480
+ // Pass 1: direct edges only (no barrel resolution) — creates reexports edges
481
+ for (const [depRelPath, symbols_] of depSymbols) {
482
+ edgesAdded += rebuildReverseDepEdges(db, rootDir, depRelPath, symbols_, stmts, true);
483
+ }
484
+ // Pass 2: add barrel import edges (reexports edges now exist)
485
+ for (const [depRelPath, symbols_] of depSymbols) {
486
+ const fileNodeRow_ = stmts.getNodeId.get(depRelPath, 'file', depRelPath, 0);
487
+ if (!fileNodeRow_) continue;
488
+ const aliases_ = { baseUrl: null, paths: {} };
489
+ for (const imp of symbols_.imports) {
490
+ if (imp.reexport) continue;
491
+ const resolvedPath = resolveImportPath(
492
+ path.join(rootDir, depRelPath),
493
+ imp.source,
494
+ rootDir,
495
+ aliases_,
496
+ );
497
+ edgesAdded += resolveBarrelImportEdges(db, stmts, fileNodeRow_.id, resolvedPath, imp);
498
+ }
499
+ }
500
+
210
501
  const symbolDiff = diffSymbols ? diffSymbols(oldSymbols, newSymbols) : null;
211
502
  const event = oldNodes === 0 ? 'added' : 'modified';
212
503
 
@@ -395,12 +395,23 @@ async function backfillTypeMap(filePath, source) {
395
395
  }
396
396
  const parsers = await createParsers();
397
397
  const extracted = wasmExtractSymbols(parsers, filePath, code);
398
- if (!extracted?.symbols?.typeMap) return { typeMap: [], backfilled: false };
399
- const tm = extracted.symbols.typeMap;
400
- return {
401
- typeMap: tm instanceof Map ? tm : new Map(tm.map((e) => [e.name, e.typeName])),
402
- backfilled: true,
403
- };
398
+ try {
399
+ if (!extracted?.symbols?.typeMap) {
400
+ return { typeMap: [], backfilled: false };
401
+ }
402
+ const tm = extracted.symbols.typeMap;
403
+ return {
404
+ typeMap: tm instanceof Map ? tm : new Map(tm.map((e) => [e.name, e.typeName])),
405
+ backfilled: true,
406
+ };
407
+ } finally {
408
+ // Free the WASM tree to prevent memory accumulation across repeated builds
409
+ if (extracted?.tree && typeof extracted.tree.delete === 'function') {
410
+ try {
411
+ extracted.tree.delete();
412
+ } catch {}
413
+ }
414
+ }
404
415
  }
405
416
 
406
417
  /**
@@ -441,7 +452,13 @@ export async function parseFileAuto(filePath, source, opts = {}) {
441
452
  const result = native.parseFile(filePath, source, !!opts.dataflow, opts.ast !== false);
442
453
  if (!result) return null;
443
454
  const patched = patchNativeResult(result);
444
- if (!patched.typeMap || patched.typeMap.length === 0) {
455
+ // Only backfill typeMap for TS/TSX — JS files have no type annotations,
456
+ // and the native engine already handles `new Expr()` patterns.
457
+ const TS_BACKFILL_EXTS = new Set(['.ts', '.tsx']);
458
+ if (
459
+ (!patched.typeMap || patched.typeMap.length === 0) &&
460
+ TS_BACKFILL_EXTS.has(path.extname(filePath))
461
+ ) {
445
462
  const { typeMap, backfilled } = await backfillTypeMap(filePath, source);
446
463
  patched.typeMap = typeMap;
447
464
  if (backfilled) patched._typeMapBackfilled = true;
@@ -486,21 +503,35 @@ export async function parseFilesAuto(filePaths, rootDir, opts = {}) {
486
503
  }
487
504
  // Backfill typeMap via WASM for native binaries that predate the type-map feature
488
505
  if (needsTypeMap.length > 0) {
489
- const parsers = await createParsers();
490
- for (const { filePath, relPath } of needsTypeMap) {
491
- try {
492
- const code = fs.readFileSync(filePath, 'utf-8');
493
- const extracted = wasmExtractSymbols(parsers, filePath, code);
494
- if (extracted?.symbols?.typeMap) {
495
- const symbols = result.get(relPath);
496
- symbols.typeMap =
497
- extracted.symbols.typeMap instanceof Map
498
- ? extracted.symbols.typeMap
499
- : new Map(extracted.symbols.typeMap.map((e) => [e.name, e.typeName]));
500
- symbols._typeMapBackfilled = true;
506
+ // Only backfill for languages where WASM extraction can produce typeMap
507
+ // (TS/TSX have type annotations; JS only has `new Expr()` which native already handles)
508
+ const TS_EXTS = new Set(['.ts', '.tsx']);
509
+ const tsFiles = needsTypeMap.filter(({ filePath }) => TS_EXTS.has(path.extname(filePath)));
510
+ if (tsFiles.length > 0) {
511
+ const parsers = await createParsers();
512
+ for (const { filePath, relPath } of tsFiles) {
513
+ let extracted;
514
+ try {
515
+ const code = fs.readFileSync(filePath, 'utf-8');
516
+ extracted = wasmExtractSymbols(parsers, filePath, code);
517
+ if (extracted?.symbols?.typeMap) {
518
+ const symbols = result.get(relPath);
519
+ symbols.typeMap =
520
+ extracted.symbols.typeMap instanceof Map
521
+ ? extracted.symbols.typeMap
522
+ : new Map(extracted.symbols.typeMap.map((e) => [e.name, e.typeName]));
523
+ symbols._typeMapBackfilled = true;
524
+ }
525
+ } catch {
526
+ /* skip — typeMap is a best-effort backfill */
527
+ } finally {
528
+ // Free the WASM tree to prevent memory accumulation across repeated builds
529
+ if (extracted?.tree && typeof extracted.tree.delete === 'function') {
530
+ try {
531
+ extracted.tree.delete();
532
+ } catch {}
533
+ }
501
534
  }
502
- } catch {
503
- /* skip — typeMap is a best-effort backfill */
504
535
  }
505
536
  }
506
537
  }
@@ -578,7 +609,13 @@ export async function parseFileIncremental(cache, filePath, source, opts = {}) {
578
609
  const result = cache.parseFile(filePath, source);
579
610
  if (!result) return null;
580
611
  const patched = patchNativeResult(result);
581
- if (!patched.typeMap || patched.typeMap.length === 0) {
612
+ // Only backfill typeMap for TS/TSX — JS files have no type annotations,
613
+ // and the native engine already handles `new Expr()` patterns.
614
+ const TS_BACKFILL_EXTS = new Set(['.ts', '.tsx']);
615
+ if (
616
+ (!patched.typeMap || patched.typeMap.length === 0) &&
617
+ TS_BACKFILL_EXTS.has(path.extname(filePath))
618
+ ) {
582
619
  const { typeMap, backfilled } = await backfillTypeMap(filePath, source);
583
620
  patched.typeMap = typeMap;
584
621
  if (backfilled) patched._typeMapBackfilled = true;
@@ -130,12 +130,19 @@ export const DEFAULTS = {
130
130
  },
131
131
  };
132
132
 
133
+ // Per-cwd config cache — avoids re-reading the config file on every query call.
134
+ // The config file rarely changes within a single process lifetime.
135
+ const _configCache = new Map();
136
+
133
137
  /**
134
138
  * Load project configuration from a .codegraphrc.json or similar file.
135
- * Returns merged config with defaults.
139
+ * Returns merged config with defaults. Results are cached per cwd.
136
140
  */
137
141
  export function loadConfig(cwd) {
138
142
  cwd = cwd || process.cwd();
143
+ const cached = _configCache.get(cwd);
144
+ if (cached) return structuredClone(cached);
145
+
139
146
  for (const name of CONFIG_FILES) {
140
147
  const filePath = path.join(cwd, name);
141
148
  if (fs.existsSync(filePath)) {
@@ -148,13 +155,26 @@ export function loadConfig(cwd) {
148
155
  merged.query.excludeTests = Boolean(config.excludeTests);
149
156
  }
150
157
  delete merged.excludeTests;
151
- return resolveSecrets(applyEnvOverrides(merged));
158
+ const result = resolveSecrets(applyEnvOverrides(merged));
159
+ _configCache.set(cwd, structuredClone(result));
160
+ return result;
152
161
  } catch (err) {
153
162
  debug(`Failed to parse config ${filePath}: ${err.message}`);
154
163
  }
155
164
  }
156
165
  }
157
- return resolveSecrets(applyEnvOverrides({ ...DEFAULTS }));
166
+ const defaults = resolveSecrets(applyEnvOverrides({ ...DEFAULTS }));
167
+ _configCache.set(cwd, structuredClone(defaults));
168
+ return defaults;
169
+ }
170
+
171
+ /**
172
+ * Clear the config cache. Intended for long-running processes that need to
173
+ * pick up on-disk config changes, and for test isolation when tests share
174
+ * the same cwd.
175
+ */
176
+ export function clearConfigCache() {
177
+ _configCache.clear();
158
178
  }
159
179
 
160
180
  const ENV_LLM_MAP = {
@@ -11,7 +11,7 @@ export async function handler(args, ctx) {
11
11
  };
12
12
 
13
13
  if (mode === 'keyword') {
14
- const { ftsSearchData } = await import('../../embeddings/index.js');
14
+ const { ftsSearchData } = await import('../../domain/search/index.js');
15
15
  const result = ftsSearchData(args.query, ctx.dbPath, searchOpts);
16
16
  if (result === null) {
17
17
  return {
@@ -28,7 +28,7 @@ export async function handler(args, ctx) {
28
28
  }
29
29
 
30
30
  if (mode === 'semantic') {
31
- const { searchData } = await import('../../embeddings/index.js');
31
+ const { searchData } = await import('../../domain/search/index.js');
32
32
  const result = await searchData(args.query, ctx.dbPath, searchOpts);
33
33
  if (result === null) {
34
34
  return {
@@ -45,7 +45,7 @@ export async function handler(args, ctx) {
45
45
  }
46
46
 
47
47
  // hybrid (default) — falls back to semantic if no FTS5
48
- const { hybridSearchData, searchData } = await import('../../embeddings/index.js');
48
+ const { hybridSearchData, searchData } = await import('../../domain/search/index.js');
49
49
  let result = await hybridSearchData(args.query, ctx.dbPath, searchOpts);
50
50
  if (result === null) {
51
51
  result = await searchData(args.query, ctx.dbPath, searchOpts);