@optave/codegraph 3.9.0 → 3.9.2

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 (196) hide show
  1. package/README.md +12 -13
  2. package/dist/ast-analysis/engine.d.ts.map +1 -1
  3. package/dist/ast-analysis/engine.js +78 -48
  4. package/dist/ast-analysis/engine.js.map +1 -1
  5. package/dist/ast-analysis/visitors/ast-store-visitor.d.ts.map +1 -1
  6. package/dist/ast-analysis/visitors/ast-store-visitor.js +15 -18
  7. package/dist/ast-analysis/visitors/ast-store-visitor.js.map +1 -1
  8. package/dist/cli/commands/batch.d.ts.map +1 -1
  9. package/dist/cli/commands/batch.js +5 -17
  10. package/dist/cli/commands/batch.js.map +1 -1
  11. package/dist/cli/commands/structure.d.ts.map +1 -1
  12. package/dist/cli/commands/structure.js +18 -1
  13. package/dist/cli/commands/structure.js.map +1 -1
  14. package/dist/db/connection.d.ts +3 -0
  15. package/dist/db/connection.d.ts.map +1 -1
  16. package/dist/db/connection.js +24 -6
  17. package/dist/db/connection.js.map +1 -1
  18. package/dist/db/index.d.ts +1 -1
  19. package/dist/db/index.d.ts.map +1 -1
  20. package/dist/db/index.js +1 -1
  21. package/dist/db/index.js.map +1 -1
  22. package/dist/db/repository/base.d.ts +35 -0
  23. package/dist/db/repository/base.d.ts.map +1 -1
  24. package/dist/db/repository/base.js +8 -0
  25. package/dist/db/repository/base.js.map +1 -1
  26. package/dist/db/repository/index.d.ts +1 -0
  27. package/dist/db/repository/index.d.ts.map +1 -1
  28. package/dist/db/repository/index.js.map +1 -1
  29. package/dist/db/repository/native-repository.d.ts +7 -1
  30. package/dist/db/repository/native-repository.d.ts.map +1 -1
  31. package/dist/db/repository/native-repository.js +46 -1
  32. package/dist/db/repository/native-repository.js.map +1 -1
  33. package/dist/domain/analysis/context.d.ts.map +1 -1
  34. package/dist/domain/analysis/context.js +5 -15
  35. package/dist/domain/analysis/context.js.map +1 -1
  36. package/dist/domain/analysis/dependencies.d.ts +6 -33
  37. package/dist/domain/analysis/dependencies.d.ts.map +1 -1
  38. package/dist/domain/analysis/dependencies.js +18 -16
  39. package/dist/domain/analysis/dependencies.js.map +1 -1
  40. package/dist/domain/analysis/fn-impact.js +2 -2
  41. package/dist/domain/analysis/fn-impact.js.map +1 -1
  42. package/dist/domain/analysis/implementations.d.ts.map +1 -1
  43. package/dist/domain/analysis/implementations.js +3 -13
  44. package/dist/domain/analysis/implementations.js.map +1 -1
  45. package/dist/domain/graph/builder/context.d.ts +4 -0
  46. package/dist/domain/graph/builder/context.d.ts.map +1 -1
  47. package/dist/domain/graph/builder/context.js +4 -0
  48. package/dist/domain/graph/builder/context.js.map +1 -1
  49. package/dist/domain/graph/builder/incremental.d.ts.map +1 -1
  50. package/dist/domain/graph/builder/incremental.js +18 -0
  51. package/dist/domain/graph/builder/incremental.js.map +1 -1
  52. package/dist/domain/graph/builder/native-db-proxy.d.ts +24 -0
  53. package/dist/domain/graph/builder/native-db-proxy.d.ts.map +1 -0
  54. package/dist/domain/graph/builder/native-db-proxy.js +87 -0
  55. package/dist/domain/graph/builder/native-db-proxy.js.map +1 -0
  56. package/dist/domain/graph/builder/pipeline.d.ts.map +1 -1
  57. package/dist/domain/graph/builder/pipeline.js +410 -349
  58. package/dist/domain/graph/builder/pipeline.js.map +1 -1
  59. package/dist/domain/graph/builder/stages/build-edges.d.ts.map +1 -1
  60. package/dist/domain/graph/builder/stages/build-edges.js +44 -4
  61. package/dist/domain/graph/builder/stages/build-edges.js.map +1 -1
  62. package/dist/domain/graph/builder/stages/build-structure.js +2 -2
  63. package/dist/domain/graph/builder/stages/build-structure.js.map +1 -1
  64. package/dist/domain/graph/builder/stages/detect-changes.d.ts.map +1 -1
  65. package/dist/domain/graph/builder/stages/detect-changes.js +6 -28
  66. package/dist/domain/graph/builder/stages/detect-changes.js.map +1 -1
  67. package/dist/domain/graph/builder/stages/finalize.js +1 -1
  68. package/dist/domain/graph/builder/stages/finalize.js.map +1 -1
  69. package/dist/domain/graph/builder/stages/insert-nodes.d.ts.map +1 -1
  70. package/dist/domain/graph/builder/stages/insert-nodes.js +16 -12
  71. package/dist/domain/graph/builder/stages/insert-nodes.js.map +1 -1
  72. package/dist/domain/graph/builder/stages/resolve-imports.d.ts.map +1 -1
  73. package/dist/domain/graph/builder/stages/resolve-imports.js +21 -26
  74. package/dist/domain/graph/builder/stages/resolve-imports.js.map +1 -1
  75. package/dist/domain/graph/watcher.d.ts.map +1 -1
  76. package/dist/domain/graph/watcher.js +99 -95
  77. package/dist/domain/graph/watcher.js.map +1 -1
  78. package/dist/domain/parser.d.ts.map +1 -1
  79. package/dist/domain/parser.js +7 -2
  80. package/dist/domain/parser.js.map +1 -1
  81. package/dist/domain/queries.d.ts +1 -1
  82. package/dist/domain/queries.d.ts.map +1 -1
  83. package/dist/domain/queries.js +1 -1
  84. package/dist/domain/queries.js.map +1 -1
  85. package/dist/extractors/go.js +53 -35
  86. package/dist/extractors/go.js.map +1 -1
  87. package/dist/extractors/javascript.js +66 -27
  88. package/dist/extractors/javascript.js.map +1 -1
  89. package/dist/features/audit.d.ts.map +1 -1
  90. package/dist/features/audit.js +3 -2
  91. package/dist/features/audit.js.map +1 -1
  92. package/dist/features/boundaries.d.ts.map +1 -1
  93. package/dist/features/boundaries.js +3 -5
  94. package/dist/features/boundaries.js.map +1 -1
  95. package/dist/features/branch-compare.d.ts.map +1 -1
  96. package/dist/features/branch-compare.js +2 -1
  97. package/dist/features/branch-compare.js.map +1 -1
  98. package/dist/features/complexity.d.ts.map +1 -1
  99. package/dist/features/complexity.js +78 -58
  100. package/dist/features/complexity.js.map +1 -1
  101. package/dist/features/dataflow.d.ts.map +1 -1
  102. package/dist/features/dataflow.js +109 -118
  103. package/dist/features/dataflow.js.map +1 -1
  104. package/dist/features/flow.d.ts.map +1 -1
  105. package/dist/features/flow.js +2 -1
  106. package/dist/features/flow.js.map +1 -1
  107. package/dist/features/manifesto.d.ts.map +1 -1
  108. package/dist/features/manifesto.js +15 -1
  109. package/dist/features/manifesto.js.map +1 -1
  110. package/dist/features/structure.d.ts.map +1 -1
  111. package/dist/features/structure.js +147 -97
  112. package/dist/features/structure.js.map +1 -1
  113. package/dist/graph/algorithms/louvain.d.ts.map +1 -1
  114. package/dist/graph/algorithms/louvain.js +4 -2
  115. package/dist/graph/algorithms/louvain.js.map +1 -1
  116. package/dist/graph/classifiers/roles.d.ts +2 -0
  117. package/dist/graph/classifiers/roles.d.ts.map +1 -1
  118. package/dist/graph/classifiers/roles.js +13 -5
  119. package/dist/graph/classifiers/roles.js.map +1 -1
  120. package/dist/infrastructure/config.d.ts +1 -0
  121. package/dist/infrastructure/config.d.ts.map +1 -1
  122. package/dist/infrastructure/config.js +1 -0
  123. package/dist/infrastructure/config.js.map +1 -1
  124. package/dist/presentation/batch.d.ts.map +1 -1
  125. package/dist/presentation/batch.js +1 -0
  126. package/dist/presentation/batch.js.map +1 -1
  127. package/dist/presentation/communities.d.ts.map +1 -1
  128. package/dist/presentation/communities.js +38 -34
  129. package/dist/presentation/communities.js.map +1 -1
  130. package/dist/presentation/manifesto.d.ts.map +1 -1
  131. package/dist/presentation/manifesto.js +31 -33
  132. package/dist/presentation/manifesto.js.map +1 -1
  133. package/dist/presentation/queries-cli/inspect.d.ts.map +1 -1
  134. package/dist/presentation/queries-cli/inspect.js +47 -46
  135. package/dist/presentation/queries-cli/inspect.js.map +1 -1
  136. package/dist/presentation/structure.d.ts +1 -1
  137. package/dist/presentation/structure.d.ts.map +1 -1
  138. package/dist/presentation/structure.js +1 -1
  139. package/dist/presentation/structure.js.map +1 -1
  140. package/dist/shared/file-utils.d.ts.map +1 -1
  141. package/dist/shared/file-utils.js +94 -72
  142. package/dist/shared/file-utils.js.map +1 -1
  143. package/dist/shared/normalize.d.ts +12 -0
  144. package/dist/shared/normalize.d.ts.map +1 -1
  145. package/dist/shared/normalize.js +4 -0
  146. package/dist/shared/normalize.js.map +1 -1
  147. package/dist/types.d.ts +82 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/package.json +7 -7
  150. package/src/ast-analysis/engine.ts +99 -55
  151. package/src/ast-analysis/visitors/ast-store-visitor.ts +19 -21
  152. package/src/cli/commands/batch.ts +5 -26
  153. package/src/cli/commands/structure.ts +21 -1
  154. package/src/db/connection.ts +26 -7
  155. package/src/db/index.ts +2 -0
  156. package/src/db/repository/base.ts +43 -0
  157. package/src/db/repository/index.ts +1 -0
  158. package/src/db/repository/native-repository.ts +67 -1
  159. package/src/domain/analysis/context.ts +5 -15
  160. package/src/domain/analysis/dependencies.ts +19 -16
  161. package/src/domain/analysis/fn-impact.ts +2 -2
  162. package/src/domain/analysis/implementations.ts +3 -13
  163. package/src/domain/graph/builder/context.ts +4 -0
  164. package/src/domain/graph/builder/incremental.ts +21 -0
  165. package/src/domain/graph/builder/native-db-proxy.ts +98 -0
  166. package/src/domain/graph/builder/pipeline.ts +514 -416
  167. package/src/domain/graph/builder/stages/build-edges.ts +45 -3
  168. package/src/domain/graph/builder/stages/build-structure.ts +2 -2
  169. package/src/domain/graph/builder/stages/detect-changes.ts +11 -33
  170. package/src/domain/graph/builder/stages/finalize.ts +1 -1
  171. package/src/domain/graph/builder/stages/insert-nodes.ts +17 -14
  172. package/src/domain/graph/builder/stages/resolve-imports.ts +22 -23
  173. package/src/domain/graph/watcher.ts +118 -98
  174. package/src/domain/parser.ts +8 -2
  175. package/src/domain/queries.ts +1 -1
  176. package/src/extractors/go.ts +57 -32
  177. package/src/extractors/javascript.ts +67 -27
  178. package/src/features/audit.ts +3 -2
  179. package/src/features/boundaries.ts +3 -5
  180. package/src/features/branch-compare.ts +2 -3
  181. package/src/features/complexity.ts +94 -58
  182. package/src/features/dataflow.ts +153 -132
  183. package/src/features/flow.ts +2 -1
  184. package/src/features/manifesto.ts +15 -1
  185. package/src/features/structure.ts +167 -95
  186. package/src/graph/algorithms/louvain.ts +5 -2
  187. package/src/graph/classifiers/roles.ts +14 -5
  188. package/src/infrastructure/config.ts +1 -0
  189. package/src/presentation/batch.ts +1 -0
  190. package/src/presentation/communities.ts +44 -39
  191. package/src/presentation/manifesto.ts +35 -38
  192. package/src/presentation/queries-cli/inspect.ts +48 -46
  193. package/src/presentation/structure.ts +2 -2
  194. package/src/shared/file-utils.ts +116 -77
  195. package/src/shared/normalize.ts +10 -0
  196. package/src/types.ts +86 -0
@@ -4,9 +4,10 @@
4
4
  * This is the heart of the builder refactor (ROADMAP 3.9): the monolithic buildGraph()
5
5
  * is decomposed into independently testable stages that communicate via PipelineContext.
6
6
  */
7
+ import fs from 'node:fs';
7
8
  import path from 'node:path';
8
9
  import { performance } from 'node:perf_hooks';
9
- import { closeDbPair, getBuildMeta, initSchema, MIGRATIONS, openDb, setBuildMeta, } from '../../../db/index.js';
10
+ import { acquireAdvisoryLock, closeDbPair, getBuildMeta, initSchema, MIGRATIONS, openDb, releaseAdvisoryLock, setBuildMeta, } from '../../../db/index.js';
10
11
  import { detectWorkspaces, loadConfig } from '../../../infrastructure/config.js';
11
12
  import { debug, info, warn } from '../../../infrastructure/logger.js';
12
13
  import { loadNative } from '../../../infrastructure/native.js';
@@ -17,6 +18,7 @@ import { getActiveEngine } from '../../parser.js';
17
18
  import { setWorkspaces } from '../resolve.js';
18
19
  import { PipelineContext } from './context.js';
19
20
  import { loadPathAliases } from './helpers.js';
21
+ import { NativeDbProxy } from './native-db-proxy.js';
20
22
  import { buildEdges } from './stages/build-edges.js';
21
23
  import { buildStructure } from './stages/build-structure.js';
22
24
  // Pipeline stages
@@ -33,28 +35,11 @@ function initializeEngine(ctx) {
33
35
  engine: ctx.opts.engine || 'auto',
34
36
  dataflow: ctx.opts.dataflow !== false,
35
37
  ast: ctx.opts.ast !== false,
36
- nativeDb: ctx.nativeDb,
37
- // WAL checkpoint callbacks for dual-connection WAL guard (#696, #715).
38
- // Feature modules (ast, cfg, complexity, dataflow) receive `db` as a
39
- // parameter and cannot tolerate close/reopen (stale reference). Instead,
40
- // checkpoint the WAL so native writes start with a clean slate.
41
- // After native writes, resumeJsDb checkpoints through rusqlite so
42
- // better-sqlite3 never reads WAL frames from a different SQLite library.
43
- suspendJsDb: ctx.nativeDb
44
- ? () => {
45
- ctx.db.pragma('wal_checkpoint(TRUNCATE)');
46
- }
47
- : undefined,
48
- resumeJsDb: ctx.nativeDb
49
- ? () => {
50
- try {
51
- ctx.nativeDb?.exec('PRAGMA wal_checkpoint(TRUNCATE)');
52
- }
53
- catch (e) {
54
- debug(`resumeJsDb: WAL checkpoint failed (nativeDb may already be closed): ${toErrorMessage(e)}`);
55
- }
56
- }
57
- : undefined,
38
+ // nativeDb and WAL callbacks are set later when NativeDatabase is opened
39
+ // (deferred to skip overhead on no-op rebuilds).
40
+ nativeDb: undefined,
41
+ suspendJsDb: undefined,
42
+ resumeJsDb: undefined,
58
43
  };
59
44
  const { name: engineName, version: engineVersion } = getActiveEngine(ctx.engineOpts);
60
45
  ctx.engineName = engineName;
@@ -67,10 +52,10 @@ function checkEngineSchemaMismatch(ctx) {
67
52
  ctx.forceFullRebuild = false;
68
53
  if (!ctx.incremental)
69
54
  return;
70
- // Route metadata reads through NativeDatabase only when using the native engine,
71
- // to avoid dual-SQLite WAL conflicts (rusqlite + better-sqlite3 on same file).
72
- const useNativeDb = ctx.engineName === 'native' && !!ctx.nativeDb;
73
- const meta = (key) => useNativeDb ? ctx.nativeDb.getBuildMeta(key) : getBuildMeta(ctx.db, key);
55
+ // NativeDatabase is deferred until after change detection, so always use
56
+ // better-sqlite3 for metadata reads here. Reads are safe WAL conflicts
57
+ // only arise from concurrent writes.
58
+ const meta = (key) => getBuildMeta(ctx.db, key);
74
59
  const prevEngine = meta('engine');
75
60
  if (prevEngine && prevEngine !== ctx.engineName) {
76
61
  info(`Engine changed (${prevEngine} → ${ctx.engineName}), promoting to full rebuild.`);
@@ -107,36 +92,46 @@ function loadAliases(ctx) {
107
92
  function setupPipeline(ctx) {
108
93
  ctx.rootDir = path.resolve(ctx.rootDir);
109
94
  ctx.dbPath = path.join(ctx.rootDir, '.codegraph', 'graph.db');
110
- ctx.db = openDb(ctx.dbPath);
111
- // Use NativeDatabase for schema init when native engine is available (Phase 6.13).
112
- // better-sqlite3 (ctx.db) is still always opened — needed for queries and stages
113
- // that haven't been migrated to rusqlite yet.
114
- // Skip native DB entirely when user explicitly requested --engine wasm.
95
+ // Detect whether native engine is available.
115
96
  const enginePref = ctx.opts.engine || 'auto';
116
97
  const native = enginePref !== 'wasm' ? loadNative() : null;
117
- if (native?.NativeDatabase) {
98
+ ctx.nativeAvailable = !!native?.NativeDatabase;
99
+ // Native-first: use only rusqlite for the entire pipeline (no better-sqlite3).
100
+ // This eliminates the dual-connection WAL corruption problem and enables all
101
+ // native fast-paths (bulkInsertNodes, classifyRolesFull, etc.).
102
+ // Fallback: if native is unavailable or FORCE_JS is set, use better-sqlite3.
103
+ if (ctx.nativeAvailable &&
104
+ native?.NativeDatabase &&
105
+ process.env.CODEGRAPH_FORCE_JS_PIPELINE !== '1') {
118
106
  try {
107
+ const dir = path.dirname(ctx.dbPath);
108
+ if (!fs.existsSync(dir))
109
+ fs.mkdirSync(dir, { recursive: true });
110
+ acquireAdvisoryLock(ctx.dbPath);
119
111
  ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath);
120
112
  ctx.nativeDb.initSchema();
121
- // Checkpoint WAL through rusqlite so better-sqlite3 sees a clean DB
122
- // with no cross-library WAL frames (#715, #717).
123
- ctx.nativeDb.exec('PRAGMA wal_checkpoint(TRUNCATE)');
113
+ const proxy = new NativeDbProxy(ctx.nativeDb);
114
+ proxy.__lockPath = `${ctx.dbPath}.lock`;
115
+ ctx.db = proxy;
116
+ ctx.nativeFirstProxy = true;
124
117
  }
125
118
  catch (err) {
126
- warn(`NativeDatabase setup failed, falling back to JS: ${toErrorMessage(err)}`);
119
+ warn(`NativeDatabase setup failed, falling back to better-sqlite3: ${toErrorMessage(err)}`);
127
120
  try {
128
121
  ctx.nativeDb?.close();
129
122
  }
130
- catch (e) {
131
- debug(`setupNativeDb: close failed during fallback: ${toErrorMessage(e)}`);
123
+ catch {
124
+ /* ignore */
132
125
  }
133
126
  ctx.nativeDb = undefined;
127
+ ctx.nativeFirstProxy = false;
128
+ releaseAdvisoryLock(`${ctx.dbPath}.lock`);
129
+ ctx.db = openDb(ctx.dbPath);
130
+ initSchema(ctx.db);
134
131
  }
135
- // Always run JS initSchema so better-sqlite3 sees the schema —
136
- // nativeDb is closed during pipeline stages and reopened for analyses.
137
- initSchema(ctx.db);
138
132
  }
139
133
  else {
134
+ ctx.db = openDb(ctx.dbPath);
140
135
  initSchema(ctx.db);
141
136
  }
142
137
  ctx.config = loadConfig(ctx.rootDir);
@@ -227,14 +222,351 @@ function refreshJsDb(ctx) {
227
222
  }
228
223
  ctx.db = openDb(ctx.dbPath);
229
224
  }
225
+ // ── Native orchestrator helpers ───────────────────────────────────────
226
+ /** Determine whether the native orchestrator should be skipped. Returns a reason string, or null if it should run. */
227
+ function shouldSkipNativeOrchestrator(ctx) {
228
+ if (process.env.CODEGRAPH_FORCE_JS_PIPELINE === '1')
229
+ return 'CODEGRAPH_FORCE_JS_PIPELINE=1';
230
+ if (ctx.forceFullRebuild)
231
+ return 'forceFullRebuild';
232
+ // v3.9.0 addon had buggy incremental purge (wrong SQL on analysis tables,
233
+ // scoped removal over-detection). Fixed in v3.9.1 by PR #865. Gate on
234
+ // < 3.9.1 so v3.9.1+ uses the fast Rust orchestrator path.
235
+ const orchestratorBuggy = !!ctx.engineVersion && semverCompare(ctx.engineVersion, '3.9.1') < 0;
236
+ if (orchestratorBuggy)
237
+ return `buggy addon ${ctx.engineVersion}`;
238
+ if (ctx.engineName !== 'native')
239
+ return `engine=${ctx.engineName}`;
240
+ return null;
241
+ }
242
+ /** Checkpoint WAL through rusqlite, close nativeDb, and reopen better-sqlite3.
243
+ * Returns false if the DB reopen fails (caller should return partial result). */
244
+ function handoffWalAfterNativeBuild(ctx) {
245
+ closeNativeDb(ctx, 'post-native-build');
246
+ try {
247
+ ctx.db.close();
248
+ }
249
+ catch (e) {
250
+ debug(`handoffWal JS db close failed: ${toErrorMessage(e)}`);
251
+ }
252
+ try {
253
+ ctx.db = openDb(ctx.dbPath);
254
+ return true;
255
+ }
256
+ catch (reopenErr) {
257
+ warn(`Failed to reopen DB after native build: ${reopenErr.message}`);
258
+ return false;
259
+ }
260
+ }
261
+ /**
262
+ * Reconstruct fileSymbols from the DB after a native orchestrator build.
263
+ * When `scopeFiles` is provided, only loads those files (for analysis-only).
264
+ * When omitted, loads all files (needed for structure rebuilds).
265
+ */
266
+ function reconstructFileSymbolsFromDb(ctx, scopeFiles) {
267
+ let query = 'SELECT file, name, kind, line, end_line as endLine FROM nodes WHERE file IS NOT NULL';
268
+ const params = [];
269
+ if (scopeFiles && scopeFiles.length > 0) {
270
+ const placeholders = scopeFiles.map(() => '?').join(',');
271
+ query += ` AND file IN (${placeholders})`;
272
+ params.push(...scopeFiles);
273
+ }
274
+ query += ' ORDER BY file, line';
275
+ const rows = ctx.db.prepare(query).all(...params);
276
+ const fileSymbols = new Map();
277
+ for (const row of rows) {
278
+ let entry = fileSymbols.get(row.file);
279
+ if (!entry) {
280
+ entry = {
281
+ definitions: [],
282
+ calls: [],
283
+ imports: [],
284
+ classes: [],
285
+ exports: [],
286
+ typeMap: new Map(),
287
+ };
288
+ fileSymbols.set(row.file, entry);
289
+ }
290
+ entry.definitions.push({
291
+ name: row.name,
292
+ kind: row.kind,
293
+ line: row.line,
294
+ endLine: row.endLine ?? undefined,
295
+ });
296
+ }
297
+ // Populate import/export counts from DB edges so buildStructure
298
+ // computes correct import_count/export_count in node_metrics.
299
+ // The extractor arrays aren't persisted to the DB, so we derive
300
+ // counts from edge data instead (#804).
301
+ const importCountRows = ctx.db
302
+ .prepare(`SELECT n.file, COUNT(*) AS cnt
303
+ FROM edges e JOIN nodes n ON e.source_id = n.id
304
+ WHERE e.kind IN ('imports', 'imports-type', 'dynamic-imports')
305
+ AND n.file IS NOT NULL
306
+ GROUP BY n.file`)
307
+ .all();
308
+ for (const row of importCountRows) {
309
+ const entry = fileSymbols.get(row.file);
310
+ if (entry)
311
+ entry.imports = new Array(row.cnt);
312
+ }
313
+ const exportCountRows = ctx.db
314
+ .prepare(`SELECT n_tgt.file, COUNT(DISTINCT n_tgt.id) AS cnt
315
+ FROM edges e
316
+ JOIN nodes n_tgt ON e.target_id = n_tgt.id
317
+ JOIN nodes n_src ON e.source_id = n_src.id
318
+ WHERE e.kind IN ('imports', 'imports-type', 'reexports')
319
+ AND n_tgt.file IS NOT NULL
320
+ AND n_src.file != n_tgt.file
321
+ GROUP BY n_tgt.file`)
322
+ .all();
323
+ for (const row of exportCountRows) {
324
+ const entry = fileSymbols.get(row.file);
325
+ if (entry)
326
+ entry.exports = new Array(row.cnt);
327
+ }
328
+ return fileSymbols;
329
+ }
330
+ /**
331
+ * Run JS buildStructure() after native orchestrator to fill directory nodes + contains edges.
332
+ * For full builds, passes changedFiles=null (full rebuild).
333
+ * For incremental builds, passes the changed file list to scope the update.
334
+ */
335
+ async function runPostNativeStructure(ctx, allFileSymbols, isFullBuild, changedFiles) {
336
+ const structureStart = performance.now();
337
+ try {
338
+ const directories = new Set();
339
+ for (const relPath of allFileSymbols.keys()) {
340
+ const parts = relPath.split('/');
341
+ for (let i = 1; i < parts.length; i++) {
342
+ directories.add(parts.slice(0, i).join('/'));
343
+ }
344
+ }
345
+ const lineCountMap = new Map();
346
+ const cachedLineCounts = ctx.db
347
+ .prepare(`SELECT n.name AS file, m.line_count
348
+ FROM node_metrics m JOIN nodes n ON m.node_id = n.id
349
+ WHERE n.kind = 'file'`)
350
+ .all();
351
+ for (const row of cachedLineCounts) {
352
+ lineCountMap.set(row.file, row.line_count);
353
+ }
354
+ // Full builds need null (rebuild everything). Incremental builds pass the
355
+ // changed file list so buildStructure only updates those files' metrics
356
+ // and contains edges — matching the JS pipeline's medium-incremental path.
357
+ const changedFilePaths = isFullBuild || !changedFiles?.length ? null : changedFiles;
358
+ const { buildStructure: buildStructureFn } = (await import('../../../features/structure.js'));
359
+ buildStructureFn(ctx.db, allFileSymbols, ctx.rootDir, lineCountMap, directories, changedFilePaths);
360
+ debug(`Structure phase completed after native orchestrator${changedFilePaths ? ` (${changedFilePaths.length} files)` : ' (full)'}`);
361
+ }
362
+ catch (err) {
363
+ warn(`Structure phase failed after native build: ${toErrorMessage(err)}`);
364
+ }
365
+ return performance.now() - structureStart;
366
+ }
367
+ /** Run AST/complexity/CFG/dataflow analysis after native orchestrator. */
368
+ async function runPostNativeAnalysis(ctx, allFileSymbols, changedFiles) {
369
+ const timing = { astMs: 0, complexityMs: 0, cfgMs: 0, dataflowMs: 0 };
370
+ // Scope analysis fileSymbols to changed files only
371
+ let analysisFileSymbols;
372
+ if (changedFiles && changedFiles.length > 0) {
373
+ analysisFileSymbols = new Map();
374
+ for (const f of changedFiles) {
375
+ const entry = allFileSymbols.get(f);
376
+ if (entry)
377
+ analysisFileSymbols.set(f, entry);
378
+ }
379
+ }
380
+ else {
381
+ analysisFileSymbols = allFileSymbols;
382
+ }
383
+ // In native-first mode, nativeDb is already open — no reopen needed.
384
+ if (!ctx.nativeFirstProxy) {
385
+ const native = loadNative();
386
+ if (native?.NativeDatabase) {
387
+ try {
388
+ ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath);
389
+ if (ctx.engineOpts)
390
+ ctx.engineOpts.nativeDb = ctx.nativeDb;
391
+ }
392
+ catch {
393
+ ctx.nativeDb = undefined;
394
+ if (ctx.engineOpts)
395
+ ctx.engineOpts.nativeDb = undefined;
396
+ }
397
+ }
398
+ }
399
+ else if (ctx.engineOpts) {
400
+ ctx.engineOpts.nativeDb = ctx.nativeDb;
401
+ }
402
+ try {
403
+ const { runAnalyses: runAnalysesFn } = await import('../../../ast-analysis/engine.js');
404
+ const result = await runAnalysesFn(ctx.db, analysisFileSymbols, ctx.rootDir, ctx.opts, ctx.engineOpts);
405
+ timing.astMs = result.astMs ?? 0;
406
+ timing.complexityMs = result.complexityMs ?? 0;
407
+ timing.cfgMs = result.cfgMs ?? 0;
408
+ timing.dataflowMs = result.dataflowMs ?? 0;
409
+ }
410
+ catch (err) {
411
+ warn(`Analysis phases failed after native build: ${toErrorMessage(err)}`);
412
+ }
413
+ // Close nativeDb after analyses (skip in native-first — single connection stays open)
414
+ if (ctx.nativeDb && !ctx.nativeFirstProxy) {
415
+ try {
416
+ ctx.nativeDb.exec('PRAGMA wal_checkpoint(TRUNCATE)');
417
+ }
418
+ catch {
419
+ /* ignore checkpoint errors */
420
+ }
421
+ try {
422
+ ctx.nativeDb.close();
423
+ }
424
+ catch {
425
+ /* ignore close errors */
426
+ }
427
+ ctx.nativeDb = undefined;
428
+ if (ctx.engineOpts)
429
+ ctx.engineOpts.nativeDb = undefined;
430
+ }
431
+ return timing;
432
+ }
433
+ /** Format timing result from native orchestrator phases + JS post-processing. */
434
+ function formatNativeTimingResult(p, structurePatchMs, analysisTiming) {
435
+ return {
436
+ phases: {
437
+ setupMs: +((p.setupMs ?? 0) + (p.collectMs ?? 0) + (p.detectMs ?? 0)).toFixed(1),
438
+ parseMs: +(p.parseMs ?? 0).toFixed(1),
439
+ insertMs: +(p.insertMs ?? 0).toFixed(1),
440
+ resolveMs: +(p.resolveMs ?? 0).toFixed(1),
441
+ edgesMs: +(p.edgesMs ?? 0).toFixed(1),
442
+ structureMs: +((p.structureMs ?? 0) + structurePatchMs).toFixed(1),
443
+ rolesMs: +(p.rolesMs ?? 0).toFixed(1),
444
+ astMs: +(analysisTiming.astMs ?? 0).toFixed(1),
445
+ complexityMs: +(analysisTiming.complexityMs ?? 0).toFixed(1),
446
+ cfgMs: +(analysisTiming.cfgMs ?? 0).toFixed(1),
447
+ dataflowMs: +(analysisTiming.dataflowMs ?? 0).toFixed(1),
448
+ finalizeMs: +(p.finalizeMs ?? 0).toFixed(1),
449
+ },
450
+ };
451
+ }
452
+ /** Try the native build orchestrator. Returns a BuildResult on success, undefined to fall through to JS pipeline. */
453
+ async function tryNativeOrchestrator(ctx) {
454
+ const skipReason = shouldSkipNativeOrchestrator(ctx);
455
+ if (skipReason) {
456
+ debug(`Skipping native orchestrator: ${skipReason}`);
457
+ return undefined;
458
+ }
459
+ // In native-first mode, nativeDb is already open from setupPipeline.
460
+ // Otherwise, open it on demand (deferred to skip overhead on no-op rebuilds).
461
+ if (!ctx.nativeDb && ctx.nativeAvailable) {
462
+ const native = loadNative();
463
+ if (native?.NativeDatabase) {
464
+ try {
465
+ ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath);
466
+ ctx.nativeDb.initSchema();
467
+ ctx.nativeDb.exec('PRAGMA wal_checkpoint(TRUNCATE)');
468
+ }
469
+ catch (err) {
470
+ warn(`NativeDatabase setup failed, falling back to JS: ${toErrorMessage(err)}`);
471
+ try {
472
+ ctx.nativeDb?.close();
473
+ }
474
+ catch (e) {
475
+ debug(`tryNativeOrchestrator: close failed during fallback: ${toErrorMessage(e)}`);
476
+ }
477
+ ctx.nativeDb = undefined;
478
+ }
479
+ }
480
+ }
481
+ if (!ctx.nativeDb?.buildGraph)
482
+ return undefined;
483
+ const resultJson = ctx.nativeDb.buildGraph(ctx.rootDir, JSON.stringify(ctx.config), JSON.stringify(ctx.aliases), JSON.stringify(ctx.opts));
484
+ const result = JSON.parse(resultJson);
485
+ if (result.earlyExit) {
486
+ info('No changes detected');
487
+ closeDbPair({ db: ctx.db, nativeDb: ctx.nativeDb });
488
+ return 'early-exit';
489
+ }
490
+ // Log incremental status to match JS pipeline output
491
+ const changed = result.changedCount ?? 0;
492
+ const removed = result.removedCount ?? 0;
493
+ if (!result.isFullBuild && (changed > 0 || removed > 0)) {
494
+ info(`Incremental: ${changed} changed, ${removed} removed`);
495
+ }
496
+ const p = result.phases;
497
+ // Sync build_meta so JS-side version/engine checks work on next build.
498
+ setBuildMeta(ctx.db, {
499
+ engine: ctx.engineName,
500
+ engine_version: ctx.engineVersion || '',
501
+ codegraph_version: CODEGRAPH_VERSION,
502
+ schema_version: String(ctx.schemaVersion),
503
+ built_at: new Date().toISOString(),
504
+ node_count: String(result.nodeCount ?? 0),
505
+ edge_count: String(result.edgeCount ?? 0),
506
+ });
507
+ info(`Native build orchestrator completed: ${result.nodeCount ?? 0} nodes, ${result.edgeCount ?? 0} edges, ${result.fileCount ?? 0} files`);
508
+ // ── Post-native structure + analysis ──────────────────────────────
509
+ let analysisTiming = { astMs: 0, complexityMs: 0, cfgMs: 0, dataflowMs: 0 };
510
+ let structurePatchMs = 0;
511
+ const needsAnalysis = ctx.opts.ast !== false ||
512
+ ctx.opts.complexity !== false ||
513
+ ctx.opts.cfg !== false ||
514
+ ctx.opts.dataflow !== false;
515
+ // Skip JS structure when the Rust pipeline's small-incremental fast path
516
+ // already handled it. For full builds and large incrementals where Rust
517
+ // skipped structure, we must run the JS fallback.
518
+ const needsStructure = !result.structureHandled;
519
+ if (needsAnalysis || needsStructure) {
520
+ // In native-first mode the proxy is already wired — no WAL handoff needed.
521
+ if (!ctx.nativeFirstProxy && !handoffWalAfterNativeBuild(ctx)) {
522
+ // DB reopen failed — return partial result
523
+ return formatNativeTimingResult(p, 0, analysisTiming);
524
+ }
525
+ // When structure was handled by Rust, we only need changed files for
526
+ // analysis — no need to load the entire graph from DB. When structure
527
+ // was NOT handled, we need all files to build the complete directory tree.
528
+ const scopeFiles = needsStructure ? undefined : result.changedFiles;
529
+ const fileSymbols = reconstructFileSymbolsFromDb(ctx, scopeFiles);
530
+ if (needsStructure) {
531
+ structurePatchMs = await runPostNativeStructure(ctx, fileSymbols, !!result.isFullBuild, result.structureScope ?? result.changedFiles);
532
+ }
533
+ if (needsAnalysis) {
534
+ analysisTiming = await runPostNativeAnalysis(ctx, fileSymbols, result.changedFiles);
535
+ }
536
+ }
537
+ closeDbPair({ db: ctx.db, nativeDb: ctx.nativeDb });
538
+ return formatNativeTimingResult(p, structurePatchMs, analysisTiming);
539
+ }
230
540
  // ── Pipeline stages execution ───────────────────────────────────────────
231
541
  async function runPipelineStages(ctx) {
232
- // Prevent dual-connection WAL corruption during pipeline stages: when both
233
- // better-sqlite3 (ctx.db) and rusqlite (ctx.nativeDb) are open to the same
234
- // WAL-mode file, native writes corrupt the DB. Close nativeDb so stages
235
- // use JS fallback paths. Reopened before runAnalyses for feature modules
236
- // that use suspendJsDb/resumeJsDb WAL checkpoint pattern (#696).
237
- const hadNativeDb = !!ctx.nativeDb;
542
+ // ── Native-first mode ────────────────────────────────────────────────
543
+ // When ctx.nativeFirstProxy is true, ctx.db is a NativeDbProxy backed by
544
+ // the single rusqlite connection (ctx.nativeDb). No dual-connection WAL
545
+ // dance is needed every stage uses the same connection transparently.
546
+ if (ctx.nativeFirstProxy) {
547
+ // Ensure engineOpts.nativeDb is set so stages can use dedicated native methods.
548
+ if (ctx.engineOpts) {
549
+ ctx.engineOpts.nativeDb = ctx.nativeDb;
550
+ }
551
+ await collectFiles(ctx);
552
+ await detectChanges(ctx);
553
+ if (ctx.earlyExit)
554
+ return;
555
+ await parseFiles(ctx);
556
+ await insertNodes(ctx);
557
+ await resolveImports(ctx);
558
+ await buildEdges(ctx);
559
+ await buildStructure(ctx);
560
+ await runAnalyses(ctx);
561
+ await finalize(ctx);
562
+ return;
563
+ }
564
+ // ── Legacy dual-connection mode (WASM / fallback) ────────────────────
565
+ // NativeDatabase is deferred — not opened during setup. collectFiles and
566
+ // detectChanges only need better-sqlite3. If no files changed, we exit
567
+ // early without ever opening the native connection, saving ~5ms.
568
+ // If nativeDb was opened by tryNativeOrchestrator (which fell through),
569
+ // suspend it now to avoid dual-connection WAL corruption during stages.
238
570
  if (ctx.db && ctx.nativeDb) {
239
571
  suspendNativeDb(ctx, 'pre-collect');
240
572
  }
@@ -243,10 +575,12 @@ async function runPipelineStages(ctx) {
243
575
  if (ctx.earlyExit)
244
576
  return;
245
577
  await parseFiles(ctx);
246
- // Temporarily reopen nativeDb for insertNodes it uses the WAL checkpoint
247
- // guard internally (same pattern as feature modules). Closed again before
248
- // resolveImports/buildEdges which don't yet have the guard (#709).
249
- if (hadNativeDb && ctx.engineName === 'native') {
578
+ // For small incremental builds (≤smallFilesThreshold files), skip the nativeDb open/close
579
+ // cycle for insertNodes the WAL checkpoint + connection churn (~5-10ms)
580
+ // exceeds the napi bulk-insert savings on a handful of files. The JS
581
+ // fallback path inside insertNodes handles this case efficiently.
582
+ const smallIncremental = !ctx.isFullBuild && ctx.allSymbols.size <= ctx.config.build.smallFilesThreshold;
583
+ if (ctx.nativeAvailable && ctx.engineName === 'native' && !smallIncremental) {
250
584
  reopenNativeDb(ctx, 'insertNodes');
251
585
  }
252
586
  await insertNodes(ctx);
@@ -260,13 +594,27 @@ async function runPipelineStages(ctx) {
260
594
  await buildStructure(ctx);
261
595
  // Reopen nativeDb for feature modules (ast, cfg, complexity, dataflow)
262
596
  // which use suspendJsDb/resumeJsDb WAL checkpoint before native writes.
263
- if (hadNativeDb) {
597
+ // Skip for small incremental builds — same rationale as insertNodes above.
598
+ if (ctx.nativeAvailable && !smallIncremental) {
264
599
  reopenNativeDb(ctx, 'analyses');
265
600
  if (ctx.nativeDb && ctx.engineOpts) {
266
601
  ctx.engineOpts.nativeDb = ctx.nativeDb;
602
+ ctx.engineOpts.suspendJsDb = () => {
603
+ ctx.db.pragma('wal_checkpoint(TRUNCATE)');
604
+ };
605
+ ctx.engineOpts.resumeJsDb = () => {
606
+ try {
607
+ ctx.nativeDb?.exec('PRAGMA wal_checkpoint(TRUNCATE)');
608
+ }
609
+ catch (e) {
610
+ debug(`resumeJsDb: WAL checkpoint failed (nativeDb may already be closed): ${toErrorMessage(e)}`);
611
+ }
612
+ };
267
613
  }
268
614
  if (!ctx.nativeDb && ctx.engineOpts) {
269
615
  ctx.engineOpts.nativeDb = undefined;
616
+ ctx.engineOpts.suspendJsDb = undefined;
617
+ ctx.engineOpts.resumeJsDb = undefined;
270
618
  }
271
619
  }
272
620
  await runAnalyses(ctx);
@@ -296,303 +644,16 @@ export async function buildGraph(rootDir, opts = {}) {
296
644
  // When available, run the entire build pipeline in Rust with zero
297
645
  // napi crossings (eliminates WAL dual-connection dance). Falls back
298
646
  // to the JS pipeline on failure or when native is unavailable.
299
- //
300
- // Native addon ≤3.8.0 has a path bug: file_symbols keys are absolute
301
- // paths but known_files are relative, causing zero import/call edges.
302
- // Native addon ≤3.8.1 has an incremental barrel bug: the Rust pipeline
303
- // doesn't re-parse barrel files that are imported by changed files,
304
- // causing missing barrel import edges and lost analysis data for
305
- // reverse-dep files during incremental builds.
306
- // Skip the orchestrator for affected versions (fixed in 3.9.0+).
307
- const orchestratorBuggy = !!ctx.engineVersion && semverCompare(ctx.engineVersion, '3.8.1') <= 0;
308
- const forceJs = process.env.CODEGRAPH_FORCE_JS_PIPELINE === '1' ||
309
- ctx.forceFullRebuild ||
310
- orchestratorBuggy ||
311
- ctx.engineName !== 'native';
312
- if (forceJs) {
313
- const reason = process.env.CODEGRAPH_FORCE_JS_PIPELINE === '1'
314
- ? 'CODEGRAPH_FORCE_JS_PIPELINE=1'
315
- : ctx.forceFullRebuild
316
- ? 'forceFullRebuild'
317
- : orchestratorBuggy
318
- ? `buggy addon ${ctx.engineVersion}`
319
- : `engine=${ctx.engineName}`;
320
- debug(`Skipping native orchestrator: ${reason}`);
647
+ try {
648
+ const nativeResult = await tryNativeOrchestrator(ctx);
649
+ if (nativeResult === 'early-exit')
650
+ return;
651
+ if (nativeResult)
652
+ return nativeResult;
321
653
  }
322
- if (!forceJs && ctx.nativeDb?.buildGraph) {
323
- try {
324
- const resultJson = ctx.nativeDb.buildGraph(ctx.rootDir, JSON.stringify(ctx.config), JSON.stringify(ctx.aliases), JSON.stringify(opts));
325
- const result = JSON.parse(resultJson);
326
- if (result.earlyExit) {
327
- info('No changes detected');
328
- closeDbPair({ db: ctx.db, nativeDb: ctx.nativeDb });
329
- return;
330
- }
331
- // Log incremental status to match JS pipeline output
332
- const changed = result.changedCount ?? 0;
333
- const removed = result.removedCount ?? 0;
334
- if (!result.isFullBuild && (changed > 0 || removed > 0)) {
335
- info(`Incremental: ${changed} changed, ${removed} removed`);
336
- }
337
- // Map Rust timing fields to the JS BuildResult format.
338
- // Rust handles collect+detect+parse+insert+resolve+edges+structure+roles.
339
- const p = result.phases;
340
- // Sync build_meta so JS-side version/engine checks work on next build.
341
- // Note: the Rust orchestrator also writes codegraph_version (using
342
- // CARGO_PKG_VERSION). We intentionally overwrite it here with the npm
343
- // package version so that the JS-side "version changed → full rebuild"
344
- // detection (line ~97) compares against the authoritative JS version.
345
- // The two versions are kept in lockstep by the release process.
346
- setBuildMeta(ctx.db, {
347
- engine: ctx.engineName,
348
- engine_version: ctx.engineVersion || '',
349
- codegraph_version: CODEGRAPH_VERSION,
350
- schema_version: String(ctx.schemaVersion),
351
- built_at: new Date().toISOString(),
352
- node_count: String(result.nodeCount ?? 0),
353
- edge_count: String(result.edgeCount ?? 0),
354
- });
355
- info(`Native build orchestrator completed: ${result.nodeCount ?? 0} nodes, ${result.edgeCount ?? 0} edges, ${result.fileCount ?? 0} files`);
356
- // ── Run structure + analysis phases after native orchestrator ──
357
- // Structure (directory nodes, contains edges, metrics) is not fully
358
- // ported to Rust — the native pipeline only handles the small
359
- // incremental fast path (≤5 changed files). For full builds and
360
- // larger incremental builds, run JS buildStructure() to fill the gap.
361
- // Analysis phases (AST, complexity, CFG, dataflow) are also not yet
362
- // ported; run via JS engine after reconstructing fileSymbols from DB.
363
- let analysisTiming = { astMs: 0, complexityMs: 0, cfgMs: 0, dataflowMs: 0 };
364
- let structurePatchMs = 0;
365
- const needsAnalysis = opts.ast !== false ||
366
- opts.complexity !== false ||
367
- opts.cfg !== false ||
368
- opts.dataflow !== false;
369
- // The native fast path only runs structure for small incremental
370
- // builds: !isFullBuild && changedCount <= 5 && existingFileCount > 20.
371
- // For all other cases (full builds, large incrementals), we must
372
- // run JS buildStructure() to create directory nodes + contains edges (#804).
373
- // Always run JS structure — the native fast-path has an additional
374
- // existingFileCount > 20 guard that isn't reflected in the result JSON,
375
- // so we can't reliably detect whether native actually ran structure.
376
- const nativeHandledStructure = false;
377
- const needsStructure = !nativeHandledStructure;
378
- if (needsAnalysis || needsStructure) {
379
- // WAL handoff: checkpoint through rusqlite, close nativeDb,
380
- // reopen better-sqlite3 with a fresh page cache (#715, #736).
381
- try {
382
- ctx.nativeDb.exec('PRAGMA wal_checkpoint(TRUNCATE)');
383
- }
384
- catch {
385
- /* ignore checkpoint errors */
386
- }
387
- try {
388
- ctx.nativeDb.close();
389
- }
390
- catch {
391
- /* ignore close errors */
392
- }
393
- ctx.nativeDb = undefined;
394
- try {
395
- ctx.db.close();
396
- }
397
- catch {
398
- /* ignore close errors */
399
- }
400
- ctx.db = null; // avoid closeDbPair operating on a stale handle
401
- try {
402
- ctx.db = openDb(ctx.dbPath);
403
- }
404
- catch (reopenErr) {
405
- warn(`Failed to reopen DB after native build: ${reopenErr.message}`);
406
- // Native build succeeded but we can't run post-processing — return partial result
407
- return {
408
- phases: {
409
- setupMs: +((p.setupMs ?? 0) + (p.collectMs ?? 0) + (p.detectMs ?? 0)).toFixed(1),
410
- parseMs: +(p.parseMs ?? 0).toFixed(1),
411
- insertMs: +(p.insertMs ?? 0).toFixed(1),
412
- resolveMs: +(p.resolveMs ?? 0).toFixed(1),
413
- edgesMs: +(p.edgesMs ?? 0).toFixed(1),
414
- structureMs: +(p.structureMs ?? 0).toFixed(1),
415
- rolesMs: +(p.rolesMs ?? 0).toFixed(1),
416
- astMs: 0,
417
- complexityMs: 0,
418
- cfgMs: 0,
419
- dataflowMs: 0,
420
- finalizeMs: +(p.finalizeMs ?? 0).toFixed(1),
421
- },
422
- };
423
- }
424
- // Reconstruct fileSymbols from DB. For structure we need ALL files
425
- // (to build complete directory tree); for analysis we scope to
426
- // changed files only. Load all files, then scope analysis later.
427
- const allFileRows = ctx.db
428
- .prepare('SELECT file, name, kind, line, end_line as endLine FROM nodes WHERE file IS NOT NULL ORDER BY file, line')
429
- .all();
430
- const allFileSymbols = new Map();
431
- for (const row of allFileRows) {
432
- let entry = allFileSymbols.get(row.file);
433
- if (!entry) {
434
- entry = {
435
- definitions: [],
436
- calls: [],
437
- imports: [],
438
- classes: [],
439
- exports: [],
440
- typeMap: new Map(),
441
- };
442
- allFileSymbols.set(row.file, entry);
443
- }
444
- entry.definitions.push({
445
- name: row.name,
446
- kind: row.kind,
447
- line: row.line,
448
- endLine: row.endLine ?? undefined,
449
- });
450
- }
451
- // Populate import/export counts from DB edges so buildStructure
452
- // computes correct import_count/export_count in node_metrics.
453
- // The extractor arrays aren't persisted to the DB, so we derive
454
- // counts from edge data instead (#804).
455
- const importCountRows = ctx.db
456
- .prepare(`SELECT n.file, COUNT(*) AS cnt
457
- FROM edges e JOIN nodes n ON e.source_id = n.id
458
- WHERE e.kind IN ('imports', 'imports-type', 'dynamic-imports')
459
- AND n.file IS NOT NULL
460
- GROUP BY n.file`)
461
- .all();
462
- for (const row of importCountRows) {
463
- const entry = allFileSymbols.get(row.file);
464
- if (entry)
465
- entry.imports = new Array(row.cnt);
466
- }
467
- // Export count: definitions in this file that are imported by other files
468
- const exportCountRows = ctx.db
469
- .prepare(`SELECT n_tgt.file, COUNT(DISTINCT n_tgt.id) AS cnt
470
- FROM edges e
471
- JOIN nodes n_tgt ON e.target_id = n_tgt.id
472
- JOIN nodes n_src ON e.source_id = n_src.id
473
- WHERE e.kind IN ('imports', 'imports-type', 'reexports')
474
- AND n_tgt.file IS NOT NULL
475
- AND n_src.file != n_tgt.file
476
- GROUP BY n_tgt.file`)
477
- .all();
478
- for (const row of exportCountRows) {
479
- const entry = allFileSymbols.get(row.file);
480
- if (entry)
481
- entry.exports = new Array(row.cnt);
482
- }
483
- // ── Structure phase: directory nodes + contains edges (#804) ──
484
- if (needsStructure) {
485
- const structureStart = performance.now();
486
- try {
487
- // Derive directories from file paths
488
- const directories = new Set();
489
- for (const relPath of allFileSymbols.keys()) {
490
- const parts = relPath.split('/');
491
- for (let i = 1; i < parts.length; i++) {
492
- directories.add(parts.slice(0, i).join('/'));
493
- }
494
- }
495
- // Build line count map from DB metrics or file content
496
- const lineCountMap = new Map();
497
- const cachedLineCounts = ctx.db
498
- .prepare(`SELECT n.name AS file, m.line_count
499
- FROM node_metrics m JOIN nodes n ON m.node_id = n.id
500
- WHERE n.kind = 'file'`)
501
- .all();
502
- for (const row of cachedLineCounts) {
503
- lineCountMap.set(row.file, row.line_count);
504
- }
505
- // Native ran no structure at all — always do a full rebuild so
506
- // every directory gets nodes + contains edges (#804).
507
- const changedFilePaths = null;
508
- const { buildStructure: buildStructureFn } = (await import('../../../features/structure.js'));
509
- buildStructureFn(ctx.db, allFileSymbols, ctx.rootDir, lineCountMap, directories, changedFilePaths);
510
- debug('Structure phase completed after native orchestrator');
511
- }
512
- catch (err) {
513
- warn(`Structure phase failed after native build: ${toErrorMessage(err)}`);
514
- }
515
- structurePatchMs = performance.now() - structureStart;
516
- }
517
- // ── Analysis phase ──
518
- if (needsAnalysis) {
519
- // Scope analysis fileSymbols to changed files only
520
- const changedFiles = result.changedFiles;
521
- let analysisFileSymbols;
522
- if (changedFiles && changedFiles.length > 0) {
523
- analysisFileSymbols = new Map();
524
- for (const f of changedFiles) {
525
- const entry = allFileSymbols.get(f);
526
- if (entry)
527
- analysisFileSymbols.set(f, entry);
528
- }
529
- }
530
- else {
531
- analysisFileSymbols = allFileSymbols;
532
- }
533
- // Reopen nativeDb for analysis features (suspend/resume WAL pattern).
534
- const native = loadNative();
535
- if (native?.NativeDatabase) {
536
- try {
537
- ctx.nativeDb = native.NativeDatabase.openReadWrite(ctx.dbPath);
538
- if (ctx.engineOpts)
539
- ctx.engineOpts.nativeDb = ctx.nativeDb;
540
- }
541
- catch {
542
- ctx.nativeDb = undefined;
543
- if (ctx.engineOpts)
544
- ctx.engineOpts.nativeDb = undefined;
545
- }
546
- }
547
- try {
548
- const { runAnalyses: runAnalysesFn } = await import('../../../ast-analysis/engine.js');
549
- analysisTiming = await runAnalysesFn(ctx.db, analysisFileSymbols, ctx.rootDir, opts, ctx.engineOpts);
550
- }
551
- catch (err) {
552
- warn(`Analysis phases failed after native build: ${toErrorMessage(err)}`);
553
- }
554
- // Close nativeDb after analyses
555
- if (ctx.nativeDb) {
556
- try {
557
- ctx.nativeDb.exec('PRAGMA wal_checkpoint(TRUNCATE)');
558
- }
559
- catch {
560
- /* ignore checkpoint errors */
561
- }
562
- try {
563
- ctx.nativeDb.close();
564
- }
565
- catch {
566
- /* ignore close errors */
567
- }
568
- ctx.nativeDb = undefined;
569
- if (ctx.engineOpts)
570
- ctx.engineOpts.nativeDb = undefined;
571
- }
572
- }
573
- }
574
- closeDbPair({ db: ctx.db, nativeDb: ctx.nativeDb });
575
- return {
576
- phases: {
577
- setupMs: +((p.setupMs ?? 0) + (p.collectMs ?? 0) + (p.detectMs ?? 0)).toFixed(1),
578
- parseMs: +(p.parseMs ?? 0).toFixed(1),
579
- insertMs: +(p.insertMs ?? 0).toFixed(1),
580
- resolveMs: +(p.resolveMs ?? 0).toFixed(1),
581
- edgesMs: +(p.edgesMs ?? 0).toFixed(1),
582
- structureMs: +((p.structureMs ?? 0) + structurePatchMs).toFixed(1),
583
- rolesMs: +(p.rolesMs ?? 0).toFixed(1),
584
- astMs: +(analysisTiming.astMs ?? 0).toFixed(1),
585
- complexityMs: +(analysisTiming.complexityMs ?? 0).toFixed(1),
586
- cfgMs: +(analysisTiming.cfgMs ?? 0).toFixed(1),
587
- dataflowMs: +(analysisTiming.dataflowMs ?? 0).toFixed(1),
588
- finalizeMs: +(p.finalizeMs ?? 0).toFixed(1),
589
- },
590
- };
591
- }
592
- catch (err) {
593
- warn(`Native build orchestrator failed, falling back to JS pipeline: ${toErrorMessage(err)}`);
594
- // Fall through to JS pipeline
595
- }
654
+ catch (err) {
655
+ warn(`Native build orchestrator failed, falling back to JS pipeline: ${toErrorMessage(err)}`);
656
+ // Fall through to JS pipeline
596
657
  }
597
658
  await runPipelineStages(ctx);
598
659
  }