@optave/codegraph 3.11.2 → 3.13.0

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 (236) hide show
  1. package/README.md +73 -37
  2. package/dist/cli/commands/audit.d.ts.map +1 -1
  3. package/dist/cli/commands/audit.js +2 -1
  4. package/dist/cli/commands/audit.js.map +1 -1
  5. package/dist/cli/commands/batch.d.ts.map +1 -1
  6. package/dist/cli/commands/batch.js +1 -0
  7. package/dist/cli/commands/batch.js.map +1 -1
  8. package/dist/cli/commands/build.d.ts.map +1 -1
  9. package/dist/cli/commands/build.js +6 -1
  10. package/dist/cli/commands/build.js.map +1 -1
  11. package/dist/cli/commands/config.d.ts +3 -0
  12. package/dist/cli/commands/config.d.ts.map +1 -0
  13. package/dist/cli/commands/config.js +272 -0
  14. package/dist/cli/commands/config.js.map +1 -0
  15. package/dist/cli/commands/triage.js +1 -1
  16. package/dist/cli/commands/triage.js.map +1 -1
  17. package/dist/cli/index.d.ts.map +1 -1
  18. package/dist/cli/index.js +10 -0
  19. package/dist/cli/index.js.map +1 -1
  20. package/dist/cli/shared/options.d.ts +2 -1
  21. package/dist/cli/shared/options.d.ts.map +1 -1
  22. package/dist/cli/shared/options.js +11 -1
  23. package/dist/cli/shared/options.js.map +1 -1
  24. package/dist/cli/types.d.ts +2 -0
  25. package/dist/cli/types.d.ts.map +1 -1
  26. package/dist/db/migrations.d.ts.map +1 -1
  27. package/dist/db/migrations.js +8 -1
  28. package/dist/db/migrations.js.map +1 -1
  29. package/dist/domain/analysis/module-map.d.ts +2 -0
  30. package/dist/domain/analysis/module-map.d.ts.map +1 -1
  31. package/dist/domain/analysis/module-map.js +24 -2
  32. package/dist/domain/analysis/module-map.js.map +1 -1
  33. package/dist/domain/graph/builder/call-resolver.d.ts +16 -10
  34. package/dist/domain/graph/builder/call-resolver.d.ts.map +1 -1
  35. package/dist/domain/graph/builder/call-resolver.js +251 -34
  36. package/dist/domain/graph/builder/call-resolver.js.map +1 -1
  37. package/dist/domain/graph/builder/cha.d.ts +69 -0
  38. package/dist/domain/graph/builder/cha.d.ts.map +1 -0
  39. package/dist/domain/graph/builder/cha.js +158 -0
  40. package/dist/domain/graph/builder/cha.js.map +1 -0
  41. package/dist/domain/graph/builder/context.d.ts +3 -0
  42. package/dist/domain/graph/builder/context.d.ts.map +1 -1
  43. package/dist/domain/graph/builder/context.js +2 -0
  44. package/dist/domain/graph/builder/context.js.map +1 -1
  45. package/dist/domain/graph/builder/helpers.d.ts +25 -1
  46. package/dist/domain/graph/builder/helpers.d.ts.map +1 -1
  47. package/dist/domain/graph/builder/helpers.js +178 -5
  48. package/dist/domain/graph/builder/helpers.js.map +1 -1
  49. package/dist/domain/graph/builder/incremental.d.ts.map +1 -1
  50. package/dist/domain/graph/builder/incremental.js +74 -2
  51. package/dist/domain/graph/builder/incremental.js.map +1 -1
  52. package/dist/domain/graph/builder/pipeline.d.ts.map +1 -1
  53. package/dist/domain/graph/builder/pipeline.js +37 -2
  54. package/dist/domain/graph/builder/pipeline.js.map +1 -1
  55. package/dist/domain/graph/builder/stages/build-edges.d.ts.map +1 -1
  56. package/dist/domain/graph/builder/stages/build-edges.js +704 -34
  57. package/dist/domain/graph/builder/stages/build-edges.js.map +1 -1
  58. package/dist/domain/graph/builder/stages/detect-changes.d.ts.map +1 -1
  59. package/dist/domain/graph/builder/stages/detect-changes.js +3 -2
  60. package/dist/domain/graph/builder/stages/detect-changes.js.map +1 -1
  61. package/dist/domain/graph/builder/stages/finalize.d.ts.map +1 -1
  62. package/dist/domain/graph/builder/stages/finalize.js +4 -0
  63. package/dist/domain/graph/builder/stages/finalize.js.map +1 -1
  64. package/dist/domain/graph/builder/stages/native-orchestrator.d.ts.map +1 -1
  65. package/dist/domain/graph/builder/stages/native-orchestrator.js +783 -37
  66. package/dist/domain/graph/builder/stages/native-orchestrator.js.map +1 -1
  67. package/dist/domain/graph/builder/stages/resolve-imports.d.ts +1 -0
  68. package/dist/domain/graph/builder/stages/resolve-imports.d.ts.map +1 -1
  69. package/dist/domain/graph/builder/stages/resolve-imports.js +10 -1
  70. package/dist/domain/graph/builder/stages/resolve-imports.js.map +1 -1
  71. package/dist/domain/graph/journal.js +1 -1
  72. package/dist/domain/graph/journal.js.map +1 -1
  73. package/dist/domain/graph/resolver/points-to.d.ts +53 -0
  74. package/dist/domain/graph/resolver/points-to.d.ts.map +1 -0
  75. package/dist/domain/graph/resolver/points-to.js +213 -0
  76. package/dist/domain/graph/resolver/points-to.js.map +1 -0
  77. package/dist/domain/graph/resolver/ts-resolver.d.ts +9 -0
  78. package/dist/domain/graph/resolver/ts-resolver.d.ts.map +1 -0
  79. package/dist/domain/graph/resolver/ts-resolver.js +476 -0
  80. package/dist/domain/graph/resolver/ts-resolver.js.map +1 -0
  81. package/dist/domain/parser.d.ts +12 -4
  82. package/dist/domain/parser.d.ts.map +1 -1
  83. package/dist/domain/parser.js +83 -20
  84. package/dist/domain/parser.js.map +1 -1
  85. package/dist/domain/wasm-worker-entry.js +35 -2
  86. package/dist/domain/wasm-worker-entry.js.map +1 -1
  87. package/dist/domain/wasm-worker-pool.d.ts.map +1 -1
  88. package/dist/domain/wasm-worker-pool.js +34 -0
  89. package/dist/domain/wasm-worker-pool.js.map +1 -1
  90. package/dist/domain/wasm-worker-protocol.d.ts +15 -1
  91. package/dist/domain/wasm-worker-protocol.d.ts.map +1 -1
  92. package/dist/extractors/c.js +3 -3
  93. package/dist/extractors/c.js.map +1 -1
  94. package/dist/extractors/clojure.js +1 -1
  95. package/dist/extractors/clojure.js.map +1 -1
  96. package/dist/extractors/cpp.d.ts.map +1 -1
  97. package/dist/extractors/cpp.js +45 -4
  98. package/dist/extractors/cpp.js.map +1 -1
  99. package/dist/extractors/csharp.d.ts.map +1 -1
  100. package/dist/extractors/csharp.js +37 -8
  101. package/dist/extractors/csharp.js.map +1 -1
  102. package/dist/extractors/cuda.d.ts.map +1 -1
  103. package/dist/extractors/cuda.js +45 -4
  104. package/dist/extractors/cuda.js.map +1 -1
  105. package/dist/extractors/elixir.js +6 -6
  106. package/dist/extractors/elixir.js.map +1 -1
  107. package/dist/extractors/fsharp.js +1 -1
  108. package/dist/extractors/fsharp.js.map +1 -1
  109. package/dist/extractors/go.js +5 -5
  110. package/dist/extractors/go.js.map +1 -1
  111. package/dist/extractors/haskell.js +1 -1
  112. package/dist/extractors/haskell.js.map +1 -1
  113. package/dist/extractors/helpers.d.ts +11 -0
  114. package/dist/extractors/helpers.d.ts.map +1 -1
  115. package/dist/extractors/helpers.js +40 -0
  116. package/dist/extractors/helpers.js.map +1 -1
  117. package/dist/extractors/java.d.ts.map +1 -1
  118. package/dist/extractors/java.js +10 -9
  119. package/dist/extractors/java.js.map +1 -1
  120. package/dist/extractors/javascript.d.ts +2 -0
  121. package/dist/extractors/javascript.d.ts.map +1 -1
  122. package/dist/extractors/javascript.js +1812 -71
  123. package/dist/extractors/javascript.js.map +1 -1
  124. package/dist/extractors/kotlin.js +5 -5
  125. package/dist/extractors/kotlin.js.map +1 -1
  126. package/dist/extractors/lua.js +1 -1
  127. package/dist/extractors/lua.js.map +1 -1
  128. package/dist/extractors/objc.js +3 -3
  129. package/dist/extractors/objc.js.map +1 -1
  130. package/dist/extractors/ocaml.js +1 -1
  131. package/dist/extractors/ocaml.js.map +1 -1
  132. package/dist/extractors/php.js +2 -2
  133. package/dist/extractors/php.js.map +1 -1
  134. package/dist/extractors/python.js +7 -7
  135. package/dist/extractors/python.js.map +1 -1
  136. package/dist/extractors/ruby.js +2 -2
  137. package/dist/extractors/ruby.js.map +1 -1
  138. package/dist/extractors/scala.js +1 -1
  139. package/dist/extractors/scala.js.map +1 -1
  140. package/dist/extractors/solidity.js +1 -1
  141. package/dist/extractors/solidity.js.map +1 -1
  142. package/dist/extractors/swift.js +4 -4
  143. package/dist/extractors/swift.js.map +1 -1
  144. package/dist/extractors/zig.js +4 -4
  145. package/dist/extractors/zig.js.map +1 -1
  146. package/dist/features/structure-query.d.ts +1 -1
  147. package/dist/features/structure-query.d.ts.map +1 -1
  148. package/dist/features/structure-query.js +6 -6
  149. package/dist/features/structure-query.js.map +1 -1
  150. package/dist/index.d.ts +1 -1
  151. package/dist/index.d.ts.map +1 -1
  152. package/dist/index.js +1 -1
  153. package/dist/index.js.map +1 -1
  154. package/dist/infrastructure/config.d.ts +85 -2
  155. package/dist/infrastructure/config.d.ts.map +1 -1
  156. package/dist/infrastructure/config.js +408 -19
  157. package/dist/infrastructure/config.js.map +1 -1
  158. package/dist/infrastructure/native.d.ts +11 -0
  159. package/dist/infrastructure/native.d.ts.map +1 -1
  160. package/dist/infrastructure/native.js +78 -5
  161. package/dist/infrastructure/native.js.map +1 -1
  162. package/dist/infrastructure/registry.d.ts +27 -0
  163. package/dist/infrastructure/registry.d.ts.map +1 -1
  164. package/dist/infrastructure/registry.js +59 -1
  165. package/dist/infrastructure/registry.js.map +1 -1
  166. package/dist/presentation/queries-cli/overview.d.ts.map +1 -1
  167. package/dist/presentation/queries-cli/overview.js +5 -0
  168. package/dist/presentation/queries-cli/overview.js.map +1 -1
  169. package/dist/presentation/structure.d.ts +1 -1
  170. package/dist/presentation/structure.d.ts.map +1 -1
  171. package/dist/presentation/structure.js +2 -2
  172. package/dist/presentation/structure.js.map +1 -1
  173. package/dist/types.d.ts +221 -0
  174. package/dist/types.d.ts.map +1 -1
  175. package/grammars/tree-sitter-gleam.wasm +0 -0
  176. package/package.json +7 -8
  177. package/src/cli/commands/audit.ts +2 -1
  178. package/src/cli/commands/batch.ts +1 -0
  179. package/src/cli/commands/build.ts +6 -1
  180. package/src/cli/commands/config.ts +353 -0
  181. package/src/cli/commands/triage.ts +1 -1
  182. package/src/cli/index.ts +10 -0
  183. package/src/cli/shared/options.ts +11 -1
  184. package/src/cli/types.ts +2 -0
  185. package/src/db/migrations.ts +8 -1
  186. package/src/domain/analysis/module-map.ts +29 -1
  187. package/src/domain/graph/builder/call-resolver.ts +263 -35
  188. package/src/domain/graph/builder/cha.ts +192 -0
  189. package/src/domain/graph/builder/context.ts +3 -0
  190. package/src/domain/graph/builder/helpers.ts +195 -5
  191. package/src/domain/graph/builder/incremental.ts +80 -1
  192. package/src/domain/graph/builder/pipeline.ts +49 -2
  193. package/src/domain/graph/builder/stages/build-edges.ts +867 -32
  194. package/src/domain/graph/builder/stages/detect-changes.ts +4 -2
  195. package/src/domain/graph/builder/stages/finalize.ts +4 -0
  196. package/src/domain/graph/builder/stages/native-orchestrator.ts +910 -43
  197. package/src/domain/graph/builder/stages/resolve-imports.ts +15 -1
  198. package/src/domain/graph/journal.ts +1 -1
  199. package/src/domain/graph/resolver/points-to.ts +254 -0
  200. package/src/domain/graph/resolver/ts-resolver.ts +536 -0
  201. package/src/domain/parser.ts +86 -17
  202. package/src/domain/wasm-worker-entry.ts +35 -2
  203. package/src/domain/wasm-worker-pool.ts +22 -0
  204. package/src/domain/wasm-worker-protocol.ts +15 -0
  205. package/src/extractors/c.ts +3 -3
  206. package/src/extractors/clojure.ts +1 -1
  207. package/src/extractors/cpp.ts +47 -4
  208. package/src/extractors/csharp.ts +33 -9
  209. package/src/extractors/cuda.ts +47 -4
  210. package/src/extractors/elixir.ts +6 -6
  211. package/src/extractors/fsharp.ts +1 -1
  212. package/src/extractors/go.ts +5 -5
  213. package/src/extractors/haskell.ts +1 -1
  214. package/src/extractors/helpers.ts +43 -0
  215. package/src/extractors/java.ts +10 -9
  216. package/src/extractors/javascript.ts +1929 -72
  217. package/src/extractors/kotlin.ts +5 -5
  218. package/src/extractors/lua.ts +1 -1
  219. package/src/extractors/objc.ts +3 -3
  220. package/src/extractors/ocaml.ts +1 -1
  221. package/src/extractors/php.ts +2 -2
  222. package/src/extractors/python.ts +7 -7
  223. package/src/extractors/ruby.ts +2 -2
  224. package/src/extractors/scala.ts +1 -1
  225. package/src/extractors/solidity.ts +1 -1
  226. package/src/extractors/swift.ts +4 -4
  227. package/src/extractors/zig.ts +4 -4
  228. package/src/features/structure-query.ts +7 -7
  229. package/src/index.ts +5 -1
  230. package/src/infrastructure/config.ts +494 -20
  231. package/src/infrastructure/native.ts +87 -5
  232. package/src/infrastructure/registry.ts +82 -1
  233. package/src/presentation/queries-cli/overview.ts +15 -1
  234. package/src/presentation/structure.ts +3 -3
  235. package/src/types.ts +235 -0
  236. package/grammars/tree-sitter-erlang.wasm +0 -0
@@ -21,7 +21,9 @@ import { normalizePath } from '../../../../shared/constants.js';
21
21
  import { toErrorMessage } from '../../../../shared/errors.js';
22
22
  import { CODEGRAPH_VERSION } from '../../../../shared/version.js';
23
23
  import { classifyNativeDrops, formatDropExtensionSummary, getInstalledWasmExtensions, NATIVE_SUPPORTED_EXTENSIONS, parseFilesWasmForBackfill, } from '../../../parser.js';
24
- import { batchInsertNodes, collectFiles as collectFilesUtil, fileHash, fileStat, readFileSafe, } from '../helpers.js';
24
+ import { computeConfidence } from '../../resolve.js';
25
+ import { resolveThisDispatch } from '../cha.js';
26
+ import { batchInsertEdges, batchInsertNodes, CHA_DISPATCH_PENALTY, CHA_TYPED_DISPATCH_CONFIDENCE, collectFiles as collectFilesUtil, fileHash, fileStat, readFileSafe, } from '../helpers.js';
25
27
  import { NativeDbProxy } from '../native-db-proxy.js';
26
28
  import { closeNativeDb } from './native-db-lifecycle.js';
27
29
  // ── Native orchestrator helpers ───────────────────────────────────────
@@ -242,8 +244,544 @@ async function runPostNativeAnalysis(ctx, allFileSymbols, changedFiles) {
242
244
  }
243
245
  return timing;
244
246
  }
247
+ /**
248
+ * Phase 8.6: CHA expansion post-pass for the native orchestrator path.
249
+ *
250
+ * The Rust build pipeline resolves typed receiver calls (e.g. `worker.doWork()`
251
+ * where `worker: IWorker`) to the interface method declaration only. This
252
+ * post-pass reads the class hierarchy (via `implements`/`extends` edges) and
253
+ * instantiated types (via `calls` edges to class nodes) from the DB and expands
254
+ * each call to an interface/abstract method to ALL RTA-filtered concrete
255
+ * implementations.
256
+ *
257
+ * Note: `this`/`super` dispatch is handled separately by `runPostNativeThisDispatch`,
258
+ * which WASM-re-parses JS/TS files to obtain raw call site receiver info.
259
+ *
260
+ * `changedFiles` controls candidate scoping on incremental builds:
261
+ * - null → full build; scan all call→method edges (existing behaviour).
262
+ * - array → incremental; two cheap gate queries decide scope:
263
+ * Gate A: any class/interface/trait/struct/record nodes in changed files?
264
+ * If yes, a new implementor may have appeared — full scan required.
265
+ * Gate B: any `calls` edges from changed-file sources targeting
266
+ * class/constructor/function-kind nodes? If yes, the RTA set may
267
+ * have grown (also covers the older-schema fallback where
268
+ * constructor calls target `constructor`/`function` nodes instead
269
+ * of `class` nodes) — full scan required.
270
+ * If neither gate fires: scope `callToMethods` to `src.file IN changedFiles`
271
+ * (safe because no hierarchy or RTA evidence changed).
272
+ *
273
+ * Returns the count of newly inserted CHA edges plus the set of files containing
274
+ * the new edges' endpoints, so the caller can scope role re-classification to the
275
+ * nodes whose fan-in/out actually changed. A zero count means no edges were added
276
+ * and role re-classification is unnecessary.
277
+ */
278
+ function runPostNativeCha(db, changedFiles) {
279
+ const affectedFiles = new Set();
280
+ const empty = { newEdgeCount: 0, affectedFiles };
281
+ // Fast guard: no hierarchy edges → no CHA work
282
+ const hasHierarchy = db
283
+ .prepare(`SELECT 1 FROM edges WHERE kind IN ('extends', 'implements') LIMIT 1`)
284
+ .get();
285
+ if (!hasHierarchy)
286
+ return empty;
287
+ // Build implementors map: parent/interface name → [child/implementing class names]
288
+ const hierarchyRows = db
289
+ .prepare(`
290
+ SELECT src.name AS child_name, tgt.name AS parent_name
291
+ FROM edges e
292
+ JOIN nodes src ON e.source_id = src.id
293
+ JOIN nodes tgt ON e.target_id = tgt.id
294
+ WHERE e.kind IN ('extends', 'implements')
295
+ `)
296
+ .all();
297
+ const implementors = new Map();
298
+ for (const row of hierarchyRows) {
299
+ let list = implementors.get(row.parent_name);
300
+ if (!list) {
301
+ list = [];
302
+ implementors.set(row.parent_name, list);
303
+ }
304
+ if (!list.includes(row.child_name))
305
+ list.push(row.child_name);
306
+ }
307
+ if (implementors.size === 0)
308
+ return empty;
309
+ // RTA: collect class names that are actually instantiated via `new X()`.
310
+ // Primary query targets `class`-kind nodes (the canonical schema).
311
+ // Fallback also matches `constructor`/`function`-kind nodes because some native
312
+ // engine versions record constructor calls against those kinds instead of `class`.
313
+ let rtaRows = db
314
+ .prepare(`
315
+ SELECT DISTINCT tgt.name
316
+ FROM edges e
317
+ JOIN nodes tgt ON e.target_id = tgt.id
318
+ WHERE e.kind = 'calls' AND tgt.kind = 'class'
319
+ `)
320
+ .all();
321
+ if (rtaRows.length === 0) {
322
+ // Fallback: try constructor/function-kind nodes for older native engine schemas
323
+ rtaRows = db
324
+ .prepare(`
325
+ SELECT DISTINCT tgt.name
326
+ FROM edges e
327
+ JOIN nodes tgt ON e.target_id = tgt.id
328
+ WHERE e.kind = 'calls' AND tgt.kind IN ('constructor', 'function')
329
+ AND INSTR(tgt.name, '.') = 0
330
+ `)
331
+ .all();
332
+ }
333
+ const instantiated = new Set(rtaRows.map((r) => r.name));
334
+ // noRtaEvidence: true when no constructor-call evidence exists in the DB (e.g. graph
335
+ // built by an older native engine that doesn't emit constructor call edges at all).
336
+ // In that case we skip RTA filtering so interface dispatch still produces edges —
337
+ // all instantiated implementors are admitted rather than silently dropping everything.
338
+ const noRtaEvidence = instantiated.size === 0;
339
+ if (noRtaEvidence) {
340
+ debug('runPostNativeCha: no constructor-call evidence found — proceeding without RTA filter');
341
+ }
342
+ // ── Incremental candidate scoping ──────────────────────────────────────────
343
+ // On incremental builds, two gate queries decide whether to restrict the
344
+ // candidate scan to changed-file call sites or run the full graph scan.
345
+ //
346
+ // Gate A: did a changed file add/change a class hierarchy node?
347
+ // A new `extends`/`implements` edge means a previously-untracked implementor
348
+ // is now in the hierarchy — unchanged call sites in OTHER files may gain new
349
+ // valid expansions, so the full scan is required.
350
+ // Note: *removed* class nodes are safe — Rust's `purge_changed_files` runs
351
+ // before this post-pass and deletes stale nodes and their hierarchy edges, so
352
+ // Gate A queries the post-purge DB. A deleted class returns no row here, which
353
+ // is correct: its stale CHA edges were already cleaned up by the Rust purge.
354
+ //
355
+ // Gate B: did a changed file add new RTA evidence (`new ConcreteX()`)?
356
+ // A new `calls` edge to a class/constructor/function-kind target means the
357
+ // instantiated set grew — previously RTA-filtered expansions in unchanged
358
+ // caller files become admissible, so the full scan is required.
359
+ // (`constructor`/`function` cover the older native engine fallback schema.)
360
+ //
361
+ // If neither gate fires, the hierarchy and RTA set are unchanged for all files
362
+ // outside changedFiles, so restricting to changed-file sources is safe.
363
+ let scopeToChangedFiles = false; // true → add WHERE src.file IN changedFiles
364
+ if (changedFiles !== null && changedFiles.length > 0) {
365
+ // Gate A: class/interface/trait/struct/record nodes in changed files?
366
+ const CHUNK_SIZE = 500;
367
+ let gateAFired = false;
368
+ for (let i = 0; i < changedFiles.length && !gateAFired; i += CHUNK_SIZE) {
369
+ const chunk = changedFiles.slice(i, i + CHUNK_SIZE);
370
+ const ph = chunk.map(() => '?').join(',');
371
+ const row = db
372
+ .prepare(`SELECT 1 FROM nodes
373
+ WHERE file IN (${ph})
374
+ AND kind IN ('class', 'interface', 'trait', 'struct', 'record')
375
+ LIMIT 1`)
376
+ .get(...chunk);
377
+ if (row)
378
+ gateAFired = true;
379
+ }
380
+ // Gate B: calls from changed-file sources to class/instantiable-kind targets
381
+ // (also covers older-schema fallback and future CHA extensions to struct/record).
382
+ // Includes class/interface/trait/struct/record (future CHA extension safety) and
383
+ // constructor/function (older native engine schema fallback).
384
+ let gateBFired = false;
385
+ if (!gateAFired) {
386
+ for (let i = 0; i < changedFiles.length && !gateBFired; i += CHUNK_SIZE) {
387
+ const chunk = changedFiles.slice(i, i + CHUNK_SIZE);
388
+ const ph = chunk.map(() => '?').join(',');
389
+ const row = db
390
+ .prepare(`SELECT 1 FROM edges e
391
+ JOIN nodes src ON e.source_id = src.id
392
+ JOIN nodes tgt ON e.target_id = tgt.id
393
+ WHERE e.kind = 'calls'
394
+ AND tgt.kind IN ('class', 'interface', 'trait', 'struct', 'record', 'constructor', 'function')
395
+ AND src.file IN (${ph})
396
+ LIMIT 1`)
397
+ .get(...chunk);
398
+ if (row)
399
+ gateBFired = true;
400
+ }
401
+ }
402
+ if (!gateAFired && !gateBFired) {
403
+ scopeToChangedFiles = true;
404
+ debug(`runPostNativeCha: neither gate fired — scoping candidate scan to ${changedFiles.length} changed file(s)`);
405
+ }
406
+ else {
407
+ debug(`runPostNativeCha: ${gateAFired ? 'Gate A (hierarchy)' : 'Gate B (RTA)'} fired — running full scan`);
408
+ }
409
+ }
410
+ // Find existing call edges targeting qualified methods (e.g., 'IWorker.doWork').
411
+ // Include caller_file and method_file so affectedFiles can be populated for
412
+ // incremental role reclassification; confidence uses CHA_TYPED_DISPATCH_CONFIDENCE matching runChaPostPass.
413
+ // When scopeToChangedFiles is true, restrict to call sites in the changed files
414
+ // (safe because no hierarchy or RTA evidence changed outside those files).
415
+ let callToMethods;
416
+ if (scopeToChangedFiles && changedFiles && changedFiles.length > 0) {
417
+ const CHUNK_SIZE = 500;
418
+ const rows = [];
419
+ for (let i = 0; i < changedFiles.length; i += CHUNK_SIZE) {
420
+ const chunk = changedFiles.slice(i, i + CHUNK_SIZE);
421
+ const ph = chunk.map(() => '?').join(',');
422
+ const chunkRows = db
423
+ .prepare(`SELECT e.source_id, src.name AS caller_name, tgt.name AS method_name, src.file AS caller_file
424
+ FROM edges e
425
+ JOIN nodes tgt ON e.target_id = tgt.id
426
+ JOIN nodes src ON e.source_id = src.id
427
+ WHERE e.kind = 'calls' AND tgt.kind = 'method'
428
+ AND INSTR(tgt.name, '.') > 0
429
+ AND (e.technique IS NULL OR e.technique != 'cha-expanded')
430
+ AND src.file IN (${ph})`)
431
+ .all(...chunk);
432
+ rows.push(...chunkRows);
433
+ }
434
+ callToMethods = rows;
435
+ }
436
+ else {
437
+ callToMethods = db
438
+ .prepare(`
439
+ SELECT e.source_id, src.name AS caller_name, tgt.name AS method_name, src.file AS caller_file
440
+ FROM edges e
441
+ JOIN nodes tgt ON e.target_id = tgt.id
442
+ JOIN nodes src ON e.source_id = src.id
443
+ WHERE e.kind = 'calls' AND tgt.kind = 'method'
444
+ AND INSTR(tgt.name, '.') > 0
445
+ AND (e.technique IS NULL OR e.technique != 'cha-expanded')
446
+ `)
447
+ .all();
448
+ }
449
+ // Seed seen-pairs only from the source_ids we'll be expanding — avoids loading every
450
+ // call edge in the DB (which would be O(all edges)) for large codebases.
451
+ const seen = new Set();
452
+ if (callToMethods.length > 0) {
453
+ const sourceIds = [...new Set(callToMethods.map((r) => r.source_id))];
454
+ const CHUNK_SIZE = 500;
455
+ for (let i = 0; i < sourceIds.length; i += CHUNK_SIZE) {
456
+ const chunk = sourceIds.slice(i, i + CHUNK_SIZE);
457
+ const placeholders = chunk.map(() => '?').join(',');
458
+ const existingPairs = db
459
+ .prepare(`SELECT source_id, target_id FROM edges WHERE kind = 'calls' AND source_id IN (${placeholders})`)
460
+ .all(...chunk);
461
+ for (const e of existingPairs)
462
+ seen.add(`${e.source_id}|${e.target_id}`);
463
+ }
464
+ }
465
+ // No LIMIT: multiple files can define the same qualified name in a monorepo.
466
+ const findMethodStmt = db.prepare(`SELECT id, file AS method_file FROM nodes WHERE name = ? AND kind = 'method'`);
467
+ const newEdges = [];
468
+ let newEdgeCount = 0;
469
+ for (const { source_id, method_name, caller_file } of callToMethods) {
470
+ const dotIdx = method_name.indexOf('.');
471
+ if (dotIdx === -1)
472
+ continue;
473
+ const typeName = method_name.slice(0, dotIdx);
474
+ const methodSuffix = method_name.slice(dotIdx + 1);
475
+ // BFS over the implementors map — handles multi-level hierarchies where
476
+ // abstract/non-instantiated classes sit between the call-site type and
477
+ // the concrete leaf implementations (issue #1311).
478
+ const bfsQueue = [typeName];
479
+ const bfsVisited = new Set([typeName]);
480
+ while (bfsQueue.length > 0) {
481
+ const current = bfsQueue.shift();
482
+ const children = implementors.get(current);
483
+ if (!children?.length)
484
+ continue;
485
+ for (const cls of children) {
486
+ if (bfsVisited.has(cls))
487
+ continue;
488
+ bfsVisited.add(cls);
489
+ if (noRtaEvidence || instantiated.has(cls)) {
490
+ const qualifiedName = `${cls}.${methodSuffix}`;
491
+ const methodNodes = findMethodStmt.all(qualifiedName);
492
+ for (const methodNode of methodNodes) {
493
+ if (methodNode.id === source_id)
494
+ continue; // skip self-loops
495
+ const key = `${source_id}|${methodNode.id}`;
496
+ if (seen.has(key))
497
+ continue;
498
+ seen.add(key);
499
+ const conf = CHA_TYPED_DISPATCH_CONFIDENCE;
500
+ newEdges.push([source_id, methodNode.id, 'calls', conf, 0, 'cha-expanded']);
501
+ newEdgeCount++;
502
+ if (caller_file)
503
+ affectedFiles.add(caller_file);
504
+ if (methodNode.method_file)
505
+ affectedFiles.add(methodNode.method_file);
506
+ }
507
+ }
508
+ // Always traverse children — non-instantiated classes may have instantiated subclasses.
509
+ bfsQueue.push(cls);
510
+ }
511
+ }
512
+ }
513
+ if (newEdges.length > 0) {
514
+ db.transaction(() => batchInsertEdges(db, newEdges))();
515
+ // Account for post-pass edges excluded from the build summary line (#1452),
516
+ // mirroring the this/super dispatch post-pass insertion log.
517
+ debug(`CHA expansion post-pass: inserted ${newEdgeCount} edge(s)`);
518
+ }
519
+ return { newEdgeCount, affectedFiles };
520
+ }
521
+ // Extensions where `this`/`super` dispatch can occur (JS/TS family)
522
+ const THIS_DISPATCH_EXTS = new Set(['.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs', '.mts', '.cts']);
523
+ /**
524
+ * Phase 8.5: this/super dispatch post-pass for the native orchestrator path.
525
+ *
526
+ * The Rust build pipeline resolves typed receiver calls but does NOT persist raw
527
+ * unresolved call site receiver info (e.g. `this`, `super`) to the DB. This
528
+ * hybrid post-pass re-parses JS/TS/TSX files via WASM to collect call sites with
529
+ * `this`/`super` receivers, then resolves them through the class hierarchy stored
530
+ * in DB `extends` edges — mirroring what `buildChaPostPass` does on the WASM path.
531
+ *
532
+ * Also handles function-as-object-property methods (`f.h = function() { this.g() }`):
533
+ * these use `this` to reference sibling properties on the same object (`f`), so
534
+ * `resolveThisDispatch` resolves them by treating the dot-prefix of the caller name
535
+ * (`f` from `f.h`) as the class and looking up `f.g` directly — no `extends` edge needed.
536
+ *
537
+ * Runs when either `extends` edges exist (class inheritance) OR dot-named `method`
538
+ * nodes exist (func-prop assignments); skips only when neither is present.
539
+ */
540
+ async function runPostNativeThisDispatch(db, rootDir, changedFiles, isFullBuild) {
541
+ const t0 = performance.now();
542
+ const targetIds = new Set();
543
+ // Files containing endpoints of newly inserted edges — lets the caller scope
544
+ // role re-classification to the nodes whose fan-in/out actually changed.
545
+ const affectedFiles = new Set();
546
+ // Fast guard: need at least one extends edge (class inheritance) OR a dot-named
547
+ // method node (func-prop assignment: `f.h = function() { this.g() }`) for
548
+ // this/super dispatch to produce any edges.
549
+ const hasExtends = db.prepare(`SELECT 1 FROM edges WHERE kind = 'extends' LIMIT 1`).get();
550
+ const hasFuncPropMethod = db
551
+ .prepare(`SELECT 1 FROM nodes WHERE kind = 'method' AND INSTR(name, '.') > 0 LIMIT 1`)
552
+ .get();
553
+ if (!hasExtends && !hasFuncPropMethod)
554
+ return { elapsedMs: 0, targetIds, affectedFiles };
555
+ // Build parents map: child class → direct parent class (from `extends` edges).
556
+ // May be empty when only func-prop methods exist (no class inheritance) —
557
+ // resolveThisDispatch handles that case via direct class-prefix lookup.
558
+ const parentRows = hasExtends
559
+ ? db
560
+ .prepare(`
561
+ SELECT src.name AS child_name, tgt.name AS parent_name
562
+ FROM edges e
563
+ JOIN nodes src ON e.source_id = src.id
564
+ JOIN nodes tgt ON e.target_id = tgt.id
565
+ WHERE e.kind = 'extends'
566
+ `)
567
+ .all()
568
+ : [];
569
+ const parents = new Map();
570
+ for (const row of parentRows) {
571
+ if (!parents.has(row.child_name))
572
+ parents.set(row.child_name, row.parent_name);
573
+ }
574
+ // Note: parents may be empty when hasFuncPropMethod but !hasExtends — that is
575
+ // intentional. resolveThisDispatch still resolves `this.g()` inside `f.h` by
576
+ // treating `f` (the dot-prefix of callerName `f.h`) as the class and looking
577
+ // up `f.g` directly via lookup.byName(), without traversing the parents chain.
578
+ const chaCtx = {
579
+ implementors: new Map(), // not needed for this/super resolution
580
+ parents,
581
+ instantiatedTypes: new Set(), // not needed for this/super resolution
582
+ };
583
+ // Determine which files to re-parse.
584
+ //
585
+ // On a full build we do NOT re-parse every JS/TS file — that would WASM-parse
586
+ // the entire project on top of the native pass, causing a massive regression
587
+ // (measured: +358% ms/file on codegraph itself). Instead we restrict to files
588
+ // that are part of the class inheritance hierarchy (both subclass files with
589
+ // `super.X()` calls and parent-class files with `this.X()` calls) OR that
590
+ // contain dot-named method nodes (func-prop assignments whose bodies may call
591
+ // `this.sibling()`). Any file not in either set has no class or object context
592
+ // where `this`/`super` dispatch would produce new edges.
593
+ let relFiles;
594
+ if (isFullBuild || !changedFiles) {
595
+ const rows = db
596
+ .prepare(`
597
+ SELECT DISTINCT file FROM (
598
+ SELECT src.file AS file
599
+ FROM edges e
600
+ JOIN nodes src ON e.source_id = src.id
601
+ WHERE e.kind = 'extends' AND src.file IS NOT NULL
602
+ UNION
603
+ SELECT tgt.file AS file
604
+ FROM edges e
605
+ JOIN nodes tgt ON e.target_id = tgt.id
606
+ WHERE e.kind = 'extends' AND tgt.file IS NOT NULL
607
+ UNION
608
+ -- Files with func-prop method definitions (e.g. f.h = function(){this.g()}).
609
+ -- Only include files where the method's owner prefix is NOT a known class name —
610
+ -- this keeps the re-parse set small (func-prop files only, not all class-method files).
611
+ -- AND name IS NOT NULL guards the NOT IN sub-select: if any class node had a NULL
612
+ -- name the entire NOT IN clause would silently return no rows (SQL NULL semantics).
613
+ SELECT n.file AS file
614
+ FROM nodes n
615
+ WHERE n.kind = 'method'
616
+ AND INSTR(n.name, '.') > 0
617
+ AND n.file IS NOT NULL
618
+ AND SUBSTR(n.name, 1, INSTR(n.name, '.') - 1) NOT IN (
619
+ SELECT name FROM nodes WHERE kind IN ('class', 'struct', 'interface', 'type')
620
+ AND name IS NOT NULL
621
+ )
622
+ )
623
+ `)
624
+ .all();
625
+ relFiles = rows
626
+ .map((r) => r.file)
627
+ .filter((f) => THIS_DISPATCH_EXTS.has(path.extname(f).toLowerCase()));
628
+ }
629
+ else {
630
+ // NOTE: Only files explicitly listed in changedFiles are re-parsed.
631
+ // If a parent-class method is replaced (new node ID) but the child file is
632
+ // unchanged, the stale super.method() edge is not refreshed here. A full
633
+ // rebuild (isFullBuild=true) is required to recover in that scenario.
634
+ relFiles = changedFiles.filter((f) => THIS_DISPATCH_EXTS.has(path.extname(f).toLowerCase()));
635
+ }
636
+ if (relFiles.length === 0)
637
+ return { elapsedMs: 0, targetIds, affectedFiles };
638
+ // DB-backed CallNodeLookup — resolveThisDispatch only calls byName()
639
+ const findByNameStmt = db.prepare(`SELECT id, file, kind FROM nodes WHERE name = ?`);
640
+ const lookup = {
641
+ byName: (name) => findByNameStmt.all(name),
642
+ byNameAndFile: (name, file) => findByNameStmt.all(name).filter((n) => n.file === file),
643
+ isBarrel: () => false,
644
+ resolveBarrel: () => null,
645
+ nodeId: () => undefined,
646
+ };
647
+ // Seed seen-pairs from existing call edges on source nodes in our file set
648
+ const seen = new Set();
649
+ const CHUNK = 500;
650
+ for (let i = 0; i < relFiles.length; i += CHUNK) {
651
+ const chunk = relFiles.slice(i, i + CHUNK);
652
+ const ph = chunk.map(() => '?').join(',');
653
+ const rows = db
654
+ .prepare(`SELECT e.source_id, e.target_id
655
+ FROM edges e
656
+ JOIN nodes n ON e.source_id = n.id
657
+ WHERE e.kind = 'calls' AND n.file IN (${ph})`)
658
+ .all(...chunk);
659
+ for (const r of rows)
660
+ seen.add(`${r.source_id}|${r.target_id}`);
661
+ }
662
+ // Find the innermost containing method/function for a call at `line` in `file`.
663
+ // COALESCE maps NULL end_line to a large sentinel so unbounded nodes sort last
664
+ // (SQLite ASC orders NULLs first, so a raw `end_line - line` would pick them first).
665
+ const findCallerByLineStmt = db.prepare(`
666
+ SELECT id, name FROM nodes
667
+ WHERE file = ? AND kind IN ('method', 'function')
668
+ AND line <= ? AND (end_line IS NULL OR end_line >= ?)
669
+ ORDER BY COALESCE(end_line - line, 999999999) ASC
670
+ LIMIT 1
671
+ `);
672
+ // Re-parse the files to obtain raw call sites with receiver info. Only
673
+ // `calls` (with receivers) are consumed here.
674
+ //
675
+ // The native engine is preferred: this pass only runs after a native
676
+ // orchestrator build, so the addon is already loaded and re-parses the
677
+ // hierarchy file set in single-digit milliseconds with the same
678
+ // receiver-annotated call sites as the WASM extractor. Booting the WASM
679
+ // runtime here instead cost ~40–110ms per full build (in-process
680
+ // web-tree-sitter + grammar init dominated) — part of the v3.12.0
681
+ // publish-gate regression. Files the native engine cannot parse (extension
682
+ // outside NATIVE_SUPPORTED_EXTENSIONS, e.g. .mts/.cts) and native parse
683
+ // failures fall back to the WASM backfill path so the sweep stays complete.
684
+ const absFiles = relFiles.map((f) => path.join(rootDir, f));
685
+ const nativeAbs = absFiles.filter((f) => NATIVE_SUPPORTED_EXTENSIONS.has(path.extname(f).toLowerCase()));
686
+ const callsByRel = new Map();
687
+ // Track native-supported files that returned null (per-file parse error) so
688
+ // they can be included in the WASM fallback set below, ensuring no file's
689
+ // this/super call sites are silently discarded.
690
+ const nativeNullFiles = new Set();
691
+ let nativeParsed = false;
692
+ if (nativeAbs.length > 0) {
693
+ const native = loadNative();
694
+ if (native) {
695
+ try {
696
+ const results = native.parseFiles(nativeAbs, rootDir, false, false);
697
+ for (let i = 0; i < results.length; i++) {
698
+ const r = results[i];
699
+ if (!r) {
700
+ // Per-file parse failure — fall back to WASM for this file.
701
+ const abs = nativeAbs[i];
702
+ if (abs)
703
+ nativeNullFiles.add(abs);
704
+ continue;
705
+ }
706
+ callsByRel.set(normalizePath(path.relative(rootDir, r.file)), r.calls ?? []);
707
+ }
708
+ nativeParsed = true;
709
+ }
710
+ catch (e) {
711
+ debug(`this-dispatch native re-parse failed, falling back to WASM: ${toErrorMessage(e)}`);
712
+ }
713
+ }
714
+ }
715
+ // WASM handles: (a) non-native extensions (e.g. .mts/.cts), (b) the entire
716
+ // file list when the native batch threw, and (c) individual files where the
717
+ // native addon returned null (per-file parse error).
718
+ const wasmAbs = nativeParsed
719
+ ? [
720
+ ...absFiles.filter((f) => !NATIVE_SUPPORTED_EXTENSIONS.has(path.extname(f).toLowerCase())),
721
+ ...nativeNullFiles,
722
+ ]
723
+ : absFiles;
724
+ const wasmResults = wasmAbs.length > 0
725
+ ? await parseFilesWasmForBackfill(wasmAbs, rootDir, { symbolsOnly: true })
726
+ : new Map();
727
+ for (const [relPath, symbols] of wasmResults) {
728
+ callsByRel.set(relPath, symbols.calls ?? []);
729
+ }
730
+ const newEdges = [];
731
+ for (const [relPath, calls] of callsByRel) {
732
+ for (const call of calls) {
733
+ // Only 'this' and 'super' are class-instance receivers in JS/TS.
734
+ // 'self' refers to WindowOrWorkerGlobalScope — not a class instance — so
735
+ // filtering it here prevents spurious dispatch edges from Worker call sites.
736
+ if (call.receiver !== 'this' && call.receiver !== 'super')
737
+ continue;
738
+ const callerRow = findCallerByLineStmt.get(relPath, call.line, call.line);
739
+ if (!callerRow)
740
+ continue;
741
+ const targets = resolveThisDispatch(call.name, callerRow.name, call.receiver, chaCtx, lookup, relPath);
742
+ for (const t of targets) {
743
+ if (t.id === callerRow.id)
744
+ continue; // skip self-loops
745
+ const key = `${callerRow.id}|${t.id}`;
746
+ if (seen.has(key))
747
+ continue;
748
+ seen.add(key);
749
+ const conf = computeConfidence(relPath, t.file, null) - CHA_DISPATCH_PENALTY;
750
+ if (conf <= 0)
751
+ continue;
752
+ // Tag super-dispatch edges distinctly so runPostNativeCha can exclude them
753
+ // from further CHA expansion (super calls are not virtual dispatch).
754
+ const technique = call.receiver === 'super' ? 'super-dispatch' : 'cha';
755
+ newEdges.push([callerRow.id, t.id, 'calls', conf, 0, technique]);
756
+ targetIds.add(t.id);
757
+ affectedFiles.add(relPath);
758
+ if (t.file)
759
+ affectedFiles.add(t.file);
760
+ }
761
+ }
762
+ }
763
+ if (newEdges.length > 0) {
764
+ db.transaction(() => batchInsertEdges(db, newEdges))();
765
+ debug(`this/super dispatch post-pass: inserted ${newEdges.length} edge(s)`);
766
+ }
767
+ // Free WASM parse trees — mirrors the cleanup in backfillNativeDroppedFiles
768
+ for (const [, symbols] of wasmResults) {
769
+ const tree = symbols._tree;
770
+ if (tree && typeof tree.delete === 'function') {
771
+ try {
772
+ tree.delete();
773
+ }
774
+ catch {
775
+ /* ignore cleanup errors */
776
+ }
777
+ }
778
+ symbols._tree = undefined;
779
+ symbols._langId = undefined;
780
+ }
781
+ return { elapsedMs: performance.now() - t0, targetIds, affectedFiles };
782
+ }
245
783
  /** Format timing result from native orchestrator phases + JS post-processing. */
246
- function formatNativeTimingResult(p, structurePatchMs, analysisTiming) {
784
+ function formatNativeTimingResult(p, structurePatchMs, analysisTiming, postPass) {
247
785
  return {
248
786
  phases: {
249
787
  setupMs: +(p.setupMs ?? 0).toFixed(1),
@@ -255,6 +793,11 @@ function formatNativeTimingResult(p, structurePatchMs, analysisTiming) {
255
793
  edgesMs: +(p.edgesMs ?? 0).toFixed(1),
256
794
  structureMs: +((p.structureMs ?? 0) + structurePatchMs).toFixed(1),
257
795
  rolesMs: +(p.rolesMs ?? 0).toFixed(1),
796
+ gapDetectMs: +postPass.gapDetectMs.toFixed(1),
797
+ chaMs: +postPass.chaMs.toFixed(1),
798
+ thisDispatchMs: +postPass.thisDispatchMs.toFixed(1),
799
+ reclassifyMs: +postPass.reclassifyMs.toFixed(1),
800
+ techniqueBackfillMs: +postPass.techniqueBackfillMs.toFixed(1),
258
801
  astMs: +(analysisTiming.astMs ?? 0).toFixed(1),
259
802
  complexityMs: +(analysisTiming.complexityMs ?? 0).toFixed(1),
260
803
  cfgMs: +(analysisTiming.cfgMs ?? 0).toFixed(1),
@@ -442,20 +985,83 @@ async function backfillNativeDroppedFiles(ctx, gap) {
442
985
  }
443
986
  if (missingAbs.length === 0)
444
987
  return;
988
+ // Parse all missing files via WASM first so we can distinguish real native
989
+ // extractor failures (WASM finds symbols but native didn't) from files the
990
+ // Rust engine legitimately skipped (gitignored artifacts, empty declaration
991
+ // files, etc. where WASM also produces 0 symbols). Both categories are
992
+ // backfilled — only the former triggers a WARN (#1566).
993
+ const wasmResults = await parseFilesWasmForBackfill(missingAbs, ctx.rootDir);
994
+ // Build two sets from wasmResults:
995
+ // wasmParsedFiles — rel-paths present in wasmResults (WASM succeeded, even 0 symbols)
996
+ // wasmFoundSymbols — subset where WASM found ≥1 symbol
997
+ // Files absent from wasmParsedFiles were skipped by WASM entirely (extension
998
+ // not in _extToLang, wasmExtractSymbols returned null, or a read error).
999
+ // Those files do NOT end up in the batchInsertNodes loop below.
1000
+ const wasmParsedFiles = new Set();
1001
+ const wasmFoundSymbols = new Set();
1002
+ for (const [relPath, symbols] of wasmResults) {
1003
+ wasmParsedFiles.add(relPath);
1004
+ if ((symbols.definitions?.length ?? 0) > 0 || (symbols.exports?.length ?? 0) > 0) {
1005
+ wasmFoundSymbols.add(relPath);
1006
+ }
1007
+ }
445
1008
  // Classify drops so users see per-extension reasons instead of just a count
446
1009
  // (#1011). `unsupported-by-native` is a legitimate parser limit (no Rust
447
1010
  // extractor); `native-extractor-failure` indicates a real native bug since
448
- // the language IS supported by the addon yet the file was dropped anyway.
1011
+ // the language IS supported by the addon yet WASM found symbols the native
1012
+ // engine should have extracted. Files where both engines produce 0 symbols
1013
+ // are legitimately empty (e.g. gitignored napi-generated declaration stubs)
1014
+ // and logged at debug level only.
449
1015
  const { byReason, totals } = classifyNativeDrops(missingRel);
450
1016
  if (totals['unsupported-by-native'] > 0) {
451
1017
  const buckets = byReason['unsupported-by-native'];
452
1018
  info(`Native orchestrator skipped ${totals['unsupported-by-native']} file(s) across ${buckets.size} extension(s) in languages without a Rust extractor; backfilling via WASM:${formatDropExtensionSummary(buckets)}`);
453
1019
  }
454
1020
  if (totals['native-extractor-failure'] > 0) {
455
- const buckets = byReason['native-extractor-failure'];
456
- warn(`Native orchestrator dropped ${totals['native-extractor-failure']} file(s) across ${buckets.size} extension(s) in natively-supported languages — likely a Rust extractor bug. Backfilling via WASM:${formatDropExtensionSummary(buckets)}`);
1021
+ // Three-way split of native-extractor-failure files:
1022
+ // realFailureBuckets — WASM found symbols real Rust extractor bug (WARN)
1023
+ // emptyFileBuckets — WASM parsed but found 0 symbols → gitignored/empty (debug)
1024
+ // These DO receive a file-node insert in the loop below.
1025
+ // wasmSkipBuckets — WASM skipped entirely (ext unknown or parse error) →
1026
+ // no file-node insert, and no WARN (debug only, distinct
1027
+ // message to avoid overstating backfill coverage).
1028
+ const allFailurePaths = byReason['native-extractor-failure'];
1029
+ const realFailureBuckets = new Map();
1030
+ const emptyFileBuckets = new Map();
1031
+ const wasmSkipBuckets = new Map();
1032
+ for (const [ext, paths] of allFailurePaths) {
1033
+ for (const relPath of paths) {
1034
+ let bucket;
1035
+ if (wasmFoundSymbols.has(relPath)) {
1036
+ bucket = realFailureBuckets;
1037
+ }
1038
+ else if (wasmParsedFiles.has(relPath)) {
1039
+ bucket = emptyFileBuckets;
1040
+ }
1041
+ else {
1042
+ bucket = wasmSkipBuckets;
1043
+ }
1044
+ let list = bucket.get(ext);
1045
+ if (!list) {
1046
+ list = [];
1047
+ bucket.set(ext, list);
1048
+ }
1049
+ list.push(relPath);
1050
+ }
1051
+ }
1052
+ if (realFailureBuckets.size > 0) {
1053
+ const realCount = [...realFailureBuckets.values()].reduce((s, a) => s + a.length, 0);
1054
+ warn(`Native orchestrator dropped ${realCount} file(s) across ${realFailureBuckets.size} extension(s) in natively-supported languages — likely a Rust extractor bug. Backfilling via WASM:${formatDropExtensionSummary(realFailureBuckets)}`);
1055
+ }
1056
+ if (emptyFileBuckets.size > 0) {
1057
+ const emptyCount = [...emptyFileBuckets.values()].reduce((s, a) => s + a.length, 0);
1058
+ debug(`Native orchestrator skipped ${emptyCount} file(s) in natively-supported languages that also produced 0 symbols via WASM (likely gitignored or empty); backfilling file nodes:${formatDropExtensionSummary(emptyFileBuckets)}`);
1059
+ }
1060
+ if (wasmSkipBuckets.size > 0) {
1061
+ const skipCount = [...wasmSkipBuckets.values()].reduce((s, a) => s + a.length, 0);
1062
+ debug(`Native orchestrator skipped ${skipCount} file(s) in natively-supported languages that WASM also could not parse (unregistered extension or parse error); no file-node inserted:${formatDropExtensionSummary(wasmSkipBuckets)}`);
1063
+ }
457
1064
  }
458
- const wasmResults = await parseFilesWasmForBackfill(missingAbs, ctx.rootDir);
459
1065
  const rows = [];
460
1066
  const exportKeys = [];
461
1067
  for (const [relPath, symbols] of wasmResults) {
@@ -572,6 +1178,41 @@ async function backfillNativeDroppedFiles(ctx, gap) {
572
1178
  symbols._langId = undefined;
573
1179
  }
574
1180
  }
1181
+ /**
1182
+ * Backfill the `technique` column on `calls` edges written by the native Rust
1183
+ * orchestrator, which does not write the column itself.
1184
+ *
1185
+ * For full builds, all `calls` edges in the DB are new so a global UPDATE is
1186
+ * correct. For incremental builds, only changed-file source nodes are updated
1187
+ * to avoid overwriting previously-set technique values on unchanged edges.
1188
+ */
1189
+ function backfillEdgeTechniquesAfterNativeOrchestrator(db, isFullBuild, changedFiles) {
1190
+ // Quiet incremental: no files changed → no new edges inserted, nothing to tag.
1191
+ // Running the global UPDATE here would mis-tag pre-migration NULL-technique edges
1192
+ // from unchanged files as 'ts-native'.
1193
+ if (!isFullBuild && changedFiles && changedFiles.length === 0) {
1194
+ return;
1195
+ }
1196
+ if (isFullBuild || !changedFiles) {
1197
+ db.prepare("UPDATE edges SET technique = 'ts-native' WHERE kind = 'calls' AND technique IS NULL").run();
1198
+ return;
1199
+ }
1200
+ // Incremental: scope to source nodes whose file is one of the changed files.
1201
+ // Chunk to stay within SQLite's SQLITE_LIMIT_VARIABLE_NUMBER (999 on older builds).
1202
+ const CHUNK_SIZE = 500;
1203
+ const tx = db.transaction(() => {
1204
+ for (let i = 0; i < changedFiles.length; i += CHUNK_SIZE) {
1205
+ const chunk = changedFiles.slice(i, i + CHUNK_SIZE);
1206
+ const placeholders = chunk.map(() => '?').join(',');
1207
+ db.prepare(`UPDATE edges SET technique = 'ts-native'
1208
+ WHERE kind = 'calls' AND technique IS NULL
1209
+ AND source_id IN (
1210
+ SELECT id FROM nodes WHERE file IN (${placeholders})
1211
+ )`).run(...chunk);
1212
+ }
1213
+ });
1214
+ tx();
1215
+ }
575
1216
  /**
576
1217
  * Try the native build orchestrator.
577
1218
  *
@@ -638,7 +1279,7 @@ export async function tryNativeOrchestrator(ctx) {
638
1279
  // Even on no-op rebuilds, dropped-language files added since the last
639
1280
  // full build are still missing from `nodes`/`file_hashes` (#1083), and
640
1281
  // WASM-only files deleted from disk leave stale rows behind (#1073).
641
- // The orchestrator's file_collector skipped them, so its earlyExit
1282
+ // The orchestrator's collect_files skipped them, so its earlyExit
642
1283
  // doesn't imply DB consistency. Run the gap repair before returning.
643
1284
  const gap = detectDroppedLanguageGap(ctx);
644
1285
  if (gap.missingAbs.length > 0 || gap.staleRel.length > 0) {
@@ -676,7 +1317,9 @@ export async function tryNativeOrchestrator(ctx) {
676
1317
  schema_version: String(ctx.schemaVersion),
677
1318
  built_at: new Date().toISOString(),
678
1319
  });
679
- info(`Native build orchestrator completed: ${result.nodeCount ?? 0} nodes, ${result.edgeCount ?? 0} edges, ${result.fileCount ?? 0} files`);
1320
+ // The build summary is logged after the JS edge-writing post-passes below
1321
+ // (dropped-language backfill, CHA, this/super dispatch) so the reported
1322
+ // counts include their edges (#1452).
680
1323
  // ── Post-native structure + analysis ──────────────────────────────
681
1324
  let analysisTiming = {
682
1325
  astMs: +(p.astMs ?? 0),
@@ -696,52 +1339,155 @@ export async function tryNativeOrchestrator(ctx) {
696
1339
  ctx.opts.complexity !== false ||
697
1340
  ctx.opts.cfg !== false ||
698
1341
  ctx.opts.dataflow !== false);
1342
+ // ── DB handoff ────────────────────────────────────────────────────────────
1343
+ // Ensure a proper better-sqlite3 connection is open before any post-pass that
1344
+ // writes edges (dropped-language backfill, CHA) and before structure/analysis.
1345
+ // When analysis fallback is needed the handoff already happened above; when
1346
+ // neither structure nor analysis is needed the proxy conversion is deferred to
1347
+ // here so CHA and technique-backfill can still write rows.
699
1348
  if (needsStructure || needsAnalysisFallback) {
700
- // When analysis fallback is needed, handoff to better-sqlite3 — the
701
- // analysis engine uses the suspend/resume WAL pattern that requires a
702
- // real better-sqlite3 connection, not the NativeDbProxy.
703
1349
  if (needsAnalysisFallback && ctx.nativeFirstProxy) {
704
1350
  closeNativeDb(ctx, 'pre-analysis-fallback');
705
1351
  ctx.db = openDb(ctx.dbPath);
706
1352
  ctx.nativeFirstProxy = false;
707
1353
  }
708
1354
  else if (!ctx.nativeFirstProxy && !handoffWalAfterNativeBuild(ctx)) {
709
- // DB reopen failed — return partial result
710
- return formatNativeTimingResult(p, 0, analysisTiming);
711
- }
712
- const fileSymbols = reconstructFileSymbolsFromDb(ctx);
713
- if (needsStructure) {
714
- structurePatchMs = await runPostNativeStructure(ctx, fileSymbols, !!result.isFullBuild, result.changedFiles);
715
- }
716
- if (needsAnalysisFallback) {
717
- analysisTiming = await runPostNativeAnalysis(ctx, fileSymbols, result.changedFiles);
1355
+ // DB reopen failed — return partial result (no post-pass phases completed)
1356
+ return formatNativeTimingResult(p, 0, analysisTiming, {
1357
+ gapDetectMs: 0,
1358
+ chaMs: 0,
1359
+ thisDispatchMs: 0,
1360
+ reclassifyMs: 0,
1361
+ techniqueBackfillMs: 0,
1362
+ });
718
1363
  }
719
1364
  }
1365
+ // ── Edge-writing post-passes (run before structure so roles see full graph) ──
720
1366
  // Engine parity: the native orchestrator silently drops files whose
721
1367
  // Rust extractor/grammar is missing or fails (e.g. HCL, Scala, Swift on
722
1368
  // stale native binaries). WASM handles those — backfill via WASM so both
723
1369
  // engines process the same file set (#967).
724
1370
  //
725
- // Detect the gap once (fs walk + 2 DB queries, ~20–30ms) and use it for
726
- // both gating and the backfill itself. On dirty incrementals/full builds
727
- // the orchestrator signals trigger backfill, so the walk happens once
728
- // (instead of redundantly inside backfill). On quiet incrementals we
729
- // still pay the walk so we can detect brand-new files in dropped-language
730
- // extensions a gap that the orchestrator's `detect_removed_files`
731
- // filter (#1070) leaves open (#1083, #1091). The pre-check is cheap
732
- // because the expensive part (WASM re-parse of the missing set) is
733
- // gated below.
734
- const removedCount = result.removedCount ?? 0;
735
- const changedCount = result.changedCount ?? 0;
1371
+ // Detect the gap once (fs walk + 2 DB queries) and use it for both gating
1372
+ // and the backfill itself. On quiet incrementals we still pay the walk so
1373
+ // we can detect brand-new files in dropped-language extensions a gap that
1374
+ // the orchestrator's `detect_removed_files` filter (#1070) leaves open
1375
+ // (#1083, #1091). The pre-check is cheap because the expensive part (WASM
1376
+ // re-parse of the missing set) is gated below.
1377
+ const gapDetectStart = performance.now();
736
1378
  const gap = detectDroppedLanguageGap(ctx);
737
- if (result.isFullBuild ||
738
- removedCount > 0 ||
739
- changedCount > 0 ||
740
- gap.missingAbs.length > 0 ||
741
- gap.staleRel.length > 0) {
1379
+ const backfillHappened = gap.missingAbs.length > 0 || gap.staleRel.length > 0;
1380
+ if (backfillHappened) {
742
1381
  await backfillNativeDroppedFiles(ctx, gap);
743
1382
  }
1383
+ const gapDetectMs = performance.now() - gapDetectStart;
1384
+ // Phase 8.5: this/super dispatch — hybrid WASM re-parse to resolve call sites
1385
+ // whose raw receiver info the Rust pipeline does not persist to DB.
1386
+ // Runs BEFORE the CHA expansion pass so that super.method() → Parent.method edges
1387
+ // (technique='cha') are in the DB when runPostNativeCha expands them to sibling
1388
+ // class overrides (e.g. PostMixin.m → B.m when PostMixin and B both extend A).
1389
+ const { elapsedMs: thisDispatchMs, targetIds: thisDispatchTargetIds, affectedFiles: thisDispatchAffectedFiles, } = await runPostNativeThisDispatch(ctx.db, ctx.rootDir, result.changedFiles, !!result.isFullBuild);
1390
+ // Phase 8.6: expand CHA call edges (interface dispatch → concrete implementations).
1391
+ // Returns the affected files so role re-classification below can be scoped to
1392
+ // the nodes whose fan-in/out actually changed.
1393
+ //
1394
+ // Runs AFTER this/super dispatch so super.method() edges are already in the DB.
1395
+ // The 'cha-expanded' technique tag on this pass's own output prevents re-expansion
1396
+ // of those edges in subsequent incremental builds, while 'cha'-tagged edges from
1397
+ // this/super dispatch remain eligible for expansion here.
1398
+ //
1399
+ // Function-as-object-property methods (`fn.method = function() {}`) are extracted
1400
+ // natively by the Rust engine (#1432) and resolved in-build by its edge builder, so
1401
+ // no WASM re-parse post-pass is needed for them. `Foo.prototype.bar = fn` likewise.
1402
+ const chaStart = performance.now();
1403
+ const { newEdgeCount: chaEdgeCount, affectedFiles: chaAffectedFiles } = runPostNativeCha(ctx.db,
1404
+ // null = full build (scan all call→method edges); array = incremental (gate queries decide scope)
1405
+ result.isFullBuild ? null : (result.changedFiles ?? null));
1406
+ const chaMs = performance.now() - chaStart;
1407
+ // Role re-classification after JS edge-writing post-passes.
1408
+ // The Rust orchestrator classifies roles before these post-passes (CHA,
1409
+ // this-dispatch) add edges, so roles for the edge endpoints are stale.
1410
+ // Scoped to the files containing those endpoints: a new edge only changes
1411
+ // fan-in/out for its own source and target nodes, so re-classifying their
1412
+ // files restores correctness without re-running the classifier over the
1413
+ // whole graph (which cost ~130ms per build on codegraph itself and was a
1414
+ // major part of the v3.12.0 native full-build benchmark regression).
1415
+ let reclassifyMs = 0;
1416
+ if (chaEdgeCount > 0 || thisDispatchTargetIds.size > 0) {
1417
+ const affectedFiles = [...new Set([...chaAffectedFiles, ...thisDispatchAffectedFiles])];
1418
+ // When edges were inserted but all their endpoint nodes have null `file`
1419
+ // columns (rare but possible), affectedFiles stays empty even though
1420
+ // fan-in/out changed. Fall back to full-graph re-classification in that
1421
+ // case — scoped classification with an empty set would be a no-op, leaving
1422
+ // roles stale for those nodes.
1423
+ const scopedFiles = affectedFiles.length > 0 ? affectedFiles : null;
1424
+ const reclassifyStart = performance.now();
1425
+ try {
1426
+ const { classifyNodeRoles } = (await import('../../../../features/structure.js'));
1427
+ classifyNodeRoles(ctx.db, scopedFiles);
1428
+ debug(scopedFiles
1429
+ ? `Post-pass role re-classification complete (${scopedFiles.length} file(s))`
1430
+ : 'Post-pass role re-classification complete (full graph — null-file endpoints)');
1431
+ }
1432
+ catch (err) {
1433
+ debug(`Post-pass role re-classification failed: ${toErrorMessage(err)}`);
1434
+ }
1435
+ reclassifyMs = performance.now() - reclassifyStart;
1436
+ }
1437
+ // Backfill the `technique` column on `calls` edges written by the Rust
1438
+ // orchestrator, which does not write the column. Runs after all edge-writing
1439
+ // phases (including the WASM dropped-language backfill, CHA post-pass, and
1440
+ // this/super dispatch) so every new edge in this build cycle gets a label.
1441
+ const techniqueBackfillStart = performance.now();
1442
+ backfillEdgeTechniquesAfterNativeOrchestrator(ctx.db, !!result.isFullBuild, result.changedFiles);
1443
+ const techniqueBackfillMs = performance.now() - techniqueBackfillStart;
1444
+ // Re-count nodes/edges now that all edge-writing post-passes have run: the
1445
+ // Rust orchestrator captured its counts before the JS post-passes added
1446
+ // edges, so both its summary and build_meta under-report (#1452).
1447
+ //
1448
+ // Fast path: skip the COUNT(*) scan when no post-pass wrote any edges.
1449
+ // COUNT(*) on large tables (50K+ edges) is non-trivial, especially via the
1450
+ // NativeDbProxy napi-rs round-trip. When all post-passes were no-ops, the
1451
+ // Rust orchestrator's counts are still accurate — no re-count needed.
1452
+ let finalNodeCount = result.nodeCount ?? 0;
1453
+ let finalEdgeCount = result.edgeCount ?? 0;
1454
+ const postPassWroteData = backfillHappened || chaEdgeCount > 0 || thisDispatchTargetIds.size > 0;
1455
+ if (postPassWroteData) {
1456
+ try {
1457
+ const counts = ctx.db
1458
+ .prepare('SELECT (SELECT COUNT(*) FROM nodes) AS n, (SELECT COUNT(*) FROM edges) AS e')
1459
+ .get();
1460
+ if (counts.n !== finalNodeCount || counts.e !== finalEdgeCount) {
1461
+ finalNodeCount = counts.n;
1462
+ finalEdgeCount = counts.e;
1463
+ setBuildMeta(ctx.db, { node_count: finalNodeCount, edge_count: finalEdgeCount });
1464
+ }
1465
+ }
1466
+ catch (err) {
1467
+ debug(`Post-pass node/edge re-count failed: ${toErrorMessage(err)}`);
1468
+ }
1469
+ }
1470
+ info(`Native build orchestrator completed: ${finalNodeCount} nodes, ${finalEdgeCount} edges, ${result.fileCount ?? 0} files`);
1471
+ // ── Structure and analysis fallback (run after edge-writing so roles see full graph) ──
1472
+ // Reconstruct fileSymbols once for both structure and analysis to avoid two
1473
+ // expensive DB scans. The DB handoff above already ensured ctx.db is a proper
1474
+ // better-sqlite3 connection when either flag is set.
1475
+ if (needsStructure || needsAnalysisFallback) {
1476
+ const fileSymbols = reconstructFileSymbolsFromDb(ctx);
1477
+ if (needsStructure) {
1478
+ structurePatchMs = await runPostNativeStructure(ctx, fileSymbols, !!result.isFullBuild, result.changedFiles);
1479
+ }
1480
+ if (needsAnalysisFallback) {
1481
+ analysisTiming = await runPostNativeAnalysis(ctx, fileSymbols, result.changedFiles);
1482
+ }
1483
+ }
744
1484
  closeDbPair({ db: ctx.db, nativeDb: ctx.nativeDb });
745
- return formatNativeTimingResult(p, structurePatchMs, analysisTiming);
1485
+ return formatNativeTimingResult(p, structurePatchMs, analysisTiming, {
1486
+ gapDetectMs,
1487
+ chaMs,
1488
+ thisDispatchMs,
1489
+ reclassifyMs,
1490
+ techniqueBackfillMs,
1491
+ });
746
1492
  }
747
1493
  //# sourceMappingURL=native-orchestrator.js.map