pi-lens 3.8.73 → 4.0.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 (346) hide show
  1. package/CHANGELOG.md +2614 -12
  2. package/README.md +50 -21
  3. package/dist/clients/actionable-warnings.js +73 -18
  4. package/dist/clients/agent-behavior-client.js +21 -4
  5. package/dist/clients/ast-grep-client.js +68 -16
  6. package/dist/clients/ast-grep-types.js +0 -1
  7. package/dist/clients/ast-grep-yaml-synth.js +37 -10
  8. package/dist/clients/atomic-write-staging.js +63 -0
  9. package/dist/clients/atomic-write.js +116 -16
  10. package/dist/clients/bash-file-access.js +193 -23
  11. package/dist/clients/biome-client.js +29 -25
  12. package/dist/clients/bootstrap.js +11 -2
  13. package/dist/clients/bounded-cache.js +34 -0
  14. package/dist/clients/bounded-pid-file-lock.js +192 -0
  15. package/dist/clients/bus-events-logger.js +5 -1
  16. package/dist/clients/bus-publish.js +10 -3
  17. package/dist/clients/cache/rule-cache.js +89 -6
  18. package/dist/clients/cache-manager.js +97 -9
  19. package/dist/clients/cache-observability.js +498 -0
  20. package/dist/clients/call-graph.js +460 -108
  21. package/dist/clients/cascade-logger.js +5 -1
  22. package/dist/clients/child-unref.js +85 -0
  23. package/dist/clients/codebase-model.js +52 -23
  24. package/dist/clients/collateral-test-role.js +40 -0
  25. package/dist/clients/complexity-client.js +6 -8
  26. package/dist/clients/console-guard-install.js +14 -0
  27. package/dist/clients/cooperative-budget.js +42 -0
  28. package/dist/clients/dead-code-client.js +2 -1
  29. package/dist/clients/debug-handles.js +206 -0
  30. package/dist/clients/debug-heap.js +167 -0
  31. package/dist/clients/degradation-ledger.js +153 -0
  32. package/dist/clients/dependency-checker.js +466 -63
  33. package/dist/clients/diagnostic-dispositions.js +83 -13
  34. package/dist/clients/diagnostics-publish.js +10 -3
  35. package/dist/clients/dispatch/auxiliary-lsp.js +34 -0
  36. package/dist/clients/dispatch/dispatcher.js +71 -13
  37. package/dist/clients/dispatch/fact-store.js +11 -0
  38. package/dist/clients/dispatch/facts/function-facts.js +37 -7
  39. package/dist/clients/dispatch/facts/import-facts.js +108 -119
  40. package/dist/clients/dispatch/facts/tree-sitter-facts.js +12 -12
  41. package/dist/clients/dispatch/facts/try-catch-facts.js +13 -0
  42. package/dist/clients/dispatch/indent-detect.js +35 -0
  43. package/dist/clients/dispatch/inline-suppressions.js +17 -8
  44. package/dist/clients/dispatch/integration.js +1094 -611
  45. package/dist/clients/dispatch/lazy.js +14 -0
  46. package/dist/clients/dispatch/plan.js +11 -1
  47. package/dist/clients/dispatch/rule-id-normalize.js +50 -0
  48. package/dist/clients/dispatch/rule-policy.js +135 -0
  49. package/dist/clients/dispatch/rules/async-noise.js +1 -0
  50. package/dist/clients/dispatch/rules/unsafe-boundary.js +7 -0
  51. package/dist/clients/dispatch/runners/ast-grep-napi.js +47 -6
  52. package/dist/clients/dispatch/runners/biome-check.js +5 -9
  53. package/dist/clients/dispatch/runners/detekt.js +3 -2
  54. package/dist/clients/dispatch/runners/hadolint.js +2 -1
  55. package/dist/clients/dispatch/runners/helm-lint.js +154 -0
  56. package/dist/clients/dispatch/runners/htmlhint.js +3 -2
  57. package/dist/clients/dispatch/runners/index.js +5 -1
  58. package/dist/clients/dispatch/runners/lsp.js +14 -6
  59. package/dist/clients/dispatch/runners/markdownlint.js +4 -9
  60. package/dist/clients/dispatch/runners/psscriptanalyzer.js +10 -1
  61. package/dist/clients/dispatch/runners/pyright.js +9 -5
  62. package/dist/clients/dispatch/runners/ruff.js +4 -8
  63. package/dist/clients/dispatch/runners/shellcheck.js +2 -3
  64. package/dist/clients/dispatch/runners/shfmt.js +2 -3
  65. package/dist/clients/dispatch/runners/spotbugs.js +2 -1
  66. package/dist/clients/dispatch/runners/taplo.js +2 -1
  67. package/dist/clients/dispatch/runners/terragrunt.js +163 -0
  68. package/dist/clients/dispatch/runners/tflint.js +37 -5
  69. package/dist/clients/dispatch/runners/tree-sitter.js +155 -166
  70. package/dist/clients/dispatch/runners/trivy-config.js +13 -7
  71. package/dist/clients/dispatch/runners/utils/lazy-installer.js +3 -0
  72. package/dist/clients/dispatch/runners/utils/runner-helpers.js +284 -34
  73. package/dist/clients/dispatch/runners/utils/spawn-outcome.js +22 -0
  74. package/dist/clients/dispatch/runners/yaml-rule-parser.js +5 -4
  75. package/dist/clients/disposition-publish.js +10 -3
  76. package/dist/clients/durable-store.js +97 -0
  77. package/dist/clients/event-loop-monitor.js +94 -3
  78. package/dist/clients/extension-log.js +139 -0
  79. package/dist/clients/extension-mode.js +73 -0
  80. package/dist/clients/feature-hints.js +53 -7
  81. package/dist/clients/file-kinds.js +143 -31
  82. package/dist/clients/file-role.js +18 -3
  83. package/dist/clients/file-utils.js +56 -34
  84. package/dist/clients/fix-worklog.js +14 -2
  85. package/dist/clients/format-events-publish.js +16 -3
  86. package/dist/clients/format-service.js +24 -8
  87. package/dist/clients/formatters-lazy.js +8 -0
  88. package/dist/clients/formatters.js +358 -61
  89. package/dist/clients/generated-artifacts.js +169 -15
  90. package/dist/clients/git-guard.js +681 -11
  91. package/dist/clients/git-tracked-ignore.js +4 -0
  92. package/dist/clients/go-client.js +2 -1
  93. package/dist/clients/govulncheck-client.js +8 -0
  94. package/dist/clients/grammar-source.js +12 -4
  95. package/dist/clients/gzip-stage-write.js +102 -0
  96. package/dist/clients/host-ports.js +31 -0
  97. package/dist/clients/installer/index.js +733 -213
  98. package/dist/clients/instance-reaper.js +142 -172
  99. package/dist/clients/jscpd-client.js +31 -54
  100. package/dist/clients/knip-client.js +78 -36
  101. package/dist/clients/language-policy.js +14 -2
  102. package/dist/clients/language-profile.js +72 -77
  103. package/dist/clients/latency-logger.js +28 -16
  104. package/dist/clients/lens-config.js +140 -166
  105. package/dist/clients/lens-engine.js +124 -21
  106. package/dist/clients/lens-events.js +27 -4
  107. package/dist/clients/lens-flag-registry.js +293 -0
  108. package/dist/clients/lens-map.js +96 -26
  109. package/dist/clients/live-bus-emitter.js +30 -0
  110. package/dist/clients/log-cleanup.js +8 -18
  111. package/dist/clients/lsp/cascade-tier.js +23 -3
  112. package/dist/clients/lsp/client.js +566 -57
  113. package/dist/clients/lsp/config.js +74 -10
  114. package/dist/clients/lsp/diagnostic-binding.js +86 -0
  115. package/dist/clients/lsp/edits.js +1012 -121
  116. package/dist/clients/lsp/index.js +1840 -803
  117. package/dist/clients/lsp/language.js +4 -1
  118. package/dist/clients/lsp/launch.js +40 -32
  119. package/dist/clients/lsp/path-utils.js +1 -1
  120. package/dist/clients/lsp/ruby-drive-dirs.js +83 -0
  121. package/dist/clients/lsp/server.js +279 -60
  122. package/dist/clients/lsp/workspace-diagnostics-cache.js +28 -4
  123. package/dist/clients/lsp-document-symbols.js +112 -0
  124. package/dist/clients/lsp-lazy.js +8 -0
  125. package/dist/clients/lsp-mutation.js +248 -0
  126. package/dist/clients/mcp/analyze.js +128 -36
  127. package/dist/clients/mcp/ipc.js +157 -24
  128. package/dist/clients/mcp/review.js +36 -3
  129. package/dist/clients/mcp/session.js +216 -8
  130. package/dist/clients/memory-sampler.js +115 -0
  131. package/dist/clients/metrics-client.js +2 -1
  132. package/dist/clients/metrics-history.js +2 -1
  133. package/dist/clients/module-report-lsp.js +5 -0
  134. package/dist/clients/module-report.js +267 -82
  135. package/dist/clients/ndjson-logger.js +334 -103
  136. package/dist/clients/opengrep-client.js +1 -1
  137. package/dist/clients/partial-edit-apply.js +120 -5
  138. package/dist/clients/path-keyed-map.js +76 -0
  139. package/dist/clients/path-utils.js +141 -5
  140. package/dist/clients/performance-report.js +327 -0
  141. package/dist/clients/pipeline.js +54 -13
  142. package/dist/clients/print-mode.js +21 -0
  143. package/dist/clients/project-changes.js +117 -4
  144. package/dist/clients/project-diagnostics/cache.js +3 -2
  145. package/dist/clients/project-diagnostics/extractors.js +26 -115
  146. package/dist/clients/project-diagnostics/fresh-fetch.js +149 -19
  147. package/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +117 -0
  148. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +37 -5
  149. package/dist/clients/project-diagnostics/scanner.js +268 -128
  150. package/dist/clients/project-lens-config.js +138 -34
  151. package/dist/clients/project-report.js +64 -25
  152. package/dist/clients/project-scale.js +8 -10
  153. package/dist/clients/project-snapshot-persist-worker.js +6 -0
  154. package/dist/clients/project-snapshot.js +767 -8
  155. package/dist/clients/project-trust.js +181 -0
  156. package/dist/clients/quiet-window.js +27 -5
  157. package/dist/clients/read-bridge.js +147 -0
  158. package/dist/clients/read-expansion.js +22 -12
  159. package/dist/clients/read-guard-logger.js +159 -1
  160. package/dist/clients/read-guard-tool-lines.js +150 -29
  161. package/dist/clients/read-guard.js +262 -3
  162. package/dist/clients/redact/secrets.js +449 -0
  163. package/dist/clients/resource-sampler.js +144 -39
  164. package/dist/clients/reverse-deps.js +48 -0
  165. package/dist/clients/review-graph/builder.js +2570 -326
  166. package/dist/clients/review-graph/git-identity.js +2 -1
  167. package/dist/clients/review-graph/import-resolvers.js +21 -10
  168. package/dist/clients/review-graph/persist-worker.js +10 -0
  169. package/dist/clients/review-graph/query.js +5 -0
  170. package/dist/clients/review-graph/shared-extraction-ir.js +90 -0
  171. package/dist/clients/review-graph/symbol-id.js +46 -0
  172. package/dist/clients/review-graph/tsconfig-paths.js +57 -6
  173. package/dist/clients/review-graph/workspace-modules.js +51 -3
  174. package/dist/clients/review-graph-logger.js +53 -0
  175. package/dist/clients/ruff-client.js +27 -44
  176. package/dist/clients/runtime-agent-end.js +111 -75
  177. package/dist/clients/runtime-context.js +36 -12
  178. package/dist/clients/runtime-coordinator.js +76 -8
  179. package/dist/clients/runtime-session.js +799 -137
  180. package/dist/clients/runtime-tool-call.js +117 -62
  181. package/dist/clients/runtime-tool-result.js +218 -23
  182. package/dist/clients/runtime-turn.js +284 -40
  183. package/dist/clients/rust-client.js +2 -1
  184. package/dist/clients/safe-spawn.js +873 -71
  185. package/dist/clients/security-scan-client.js +2 -1
  186. package/dist/clients/session-start-observability.js +15 -0
  187. package/dist/clients/session-state-store.js +5 -3
  188. package/dist/clients/sessionstart-logger.js +18 -0
  189. package/dist/clients/sg-runner.js +284 -159
  190. package/dist/clients/slow-fs.js +2 -1
  191. package/dist/clients/smells-rollup.js +224 -0
  192. package/dist/clients/source-filter.js +231 -43
  193. package/dist/clients/source-walker.js +66 -10
  194. package/dist/clients/startup-scan.js +15 -16
  195. package/dist/clients/startup-timing.js +9 -0
  196. package/dist/clients/test-runner-client.js +38 -8
  197. package/dist/clients/todo-scanner.js +30 -3
  198. package/dist/clients/tool-event.js +35 -0
  199. package/dist/clients/tool-policy.js +388 -39
  200. package/dist/clients/tool-render.js +155 -0
  201. package/dist/clients/tree-sitter-cache.js +153 -140
  202. package/dist/clients/tree-sitter-client.js +1722 -80
  203. package/dist/clients/tree-sitter-logger.js +64 -1
  204. package/dist/clients/tree-sitter-query-loader.js +117 -12
  205. package/dist/clients/tree-sitter-shared.js +48 -19
  206. package/dist/clients/tree-sitter-symbol-extractor.js +115 -11
  207. package/dist/clients/user-notify.js +51 -0
  208. package/dist/clients/vanished-instance-marker.js +57 -0
  209. package/dist/clients/warm-attach.js +33 -13
  210. package/dist/clients/widget-state.js +342 -49
  211. package/dist/clients/word-index-logger.js +44 -0
  212. package/dist/clients/word-index.js +612 -68
  213. package/dist/clients/workspace-topology.js +100 -7
  214. package/dist/index.js +65923 -47161
  215. package/dist/mcp/analyze-cli.js +185 -29
  216. package/dist/mcp/cli.js +110 -0
  217. package/dist/mcp/server.js +272 -50
  218. package/dist/tools/ast-grep-search.js +93 -27
  219. package/dist/tools/lens-diagnostics.js +247 -41
  220. package/dist/tools/lsp-diagnostics.js +153 -40
  221. package/dist/tools/lsp-navigation.js +51 -31
  222. package/dist/tools/module-report.js +9 -0
  223. package/dist/tools/symbol-search.js +21 -2
  224. package/docs/agent-guide.md +247 -0
  225. package/docs/agent-tools.md +21 -10
  226. package/docs/analysisall.md +192 -0
  227. package/docs/api-ports-inventory.md +165 -0
  228. package/docs/ast-grep_rules_catalog.md +5 -2
  229. package/docs/astplayground.md +3 -4
  230. package/docs/audit1.md +5 -5
  231. package/docs/durable-store-audit-1202.md +32 -0
  232. package/docs/environment-variables.md +197 -11
  233. package/docs/fable.md +27 -0
  234. package/docs/features.md +35 -5
  235. package/docs/globalconfig.md +101 -5
  236. package/docs/language-coverage.md +6 -5
  237. package/docs/lsp-capability-matrix.md +2 -2
  238. package/docs/mcp.md +54 -20
  239. package/docs/servercapabilities.md +7 -4
  240. package/docs/settings.md +192 -0
  241. package/docs/tools.md +18 -1
  242. package/docs/tree-sitter_rules_catalog.md +11 -31
  243. package/docs/usage.md +31 -0
  244. package/package.json +139 -138
  245. package/rules/ast-grep-rules/rule-tests/hardcoded-url-js-test.yml +1 -0
  246. package/rules/ast-grep-rules/rule-tests/hardcoded-url-test.yml +2 -0
  247. package/rules/ast-grep-rules/rule-tests/no-bare-except-test.yml +49 -0
  248. package/rules/ast-grep-rules/rule-tests/no-bare-host-path-in-win32-branch-test.yml +87 -0
  249. package/rules/ast-grep-rules/rule-tests/no-case-declarations-js-test.yml +10 -0
  250. package/rules/ast-grep-rules/rule-tests/no-case-declarations-test.yml +10 -0
  251. package/rules/ast-grep-rules/rule-tests/no-javascript-url-js-test.yml +10 -0
  252. package/rules/ast-grep-rules/rule-tests/no-javascript-url-test.yml +10 -0
  253. package/rules/ast-grep-rules/rule-tests/no-nested-links-test.yml +11 -1
  254. package/rules/ast-grep-rules/rule-tests/no-raw-json-store-write-test.yml +17 -0
  255. package/rules/ast-grep-rules/rule-tests/no-win32-isabsolute-for-qualification-test.yml +16 -0
  256. package/rules/ast-grep-rules/rule-tests/strict-equality-js-test.yml +3 -0
  257. package/rules/ast-grep-rules/rule-tests/strict-equality-test.yml +3 -0
  258. package/rules/ast-grep-rules/rule-tests/strict-inequality-js-test.yml +3 -0
  259. package/rules/ast-grep-rules/rule-tests/strict-inequality-test.yml +4 -0
  260. package/rules/ast-grep-rules/rules/hardcoded-url-js.yml +22 -4
  261. package/rules/ast-grep-rules/rules/hardcoded-url.yml +22 -4
  262. package/rules/ast-grep-rules/rules/no-bare-except.yml +3 -15
  263. package/rules/ast-grep-rules/rules/no-bare-host-path-in-win32-branch.yml +25 -0
  264. package/rules/ast-grep-rules/rules/no-case-declarations-js.yml +4 -3
  265. package/rules/ast-grep-rules/rules/no-case-declarations.yml +4 -3
  266. package/rules/ast-grep-rules/rules/no-console-except-error-js.yml +10 -0
  267. package/rules/ast-grep-rules/rules/no-console-except-error.yml +10 -0
  268. package/rules/ast-grep-rules/rules/no-javascript-url-js.yml +42 -6
  269. package/rules/ast-grep-rules/rules/no-javascript-url.yml +42 -6
  270. package/rules/ast-grep-rules/rules/no-nested-links.yml +7 -0
  271. package/rules/ast-grep-rules/rules/no-raw-json-store-write.yml +30 -0
  272. package/rules/ast-grep-rules/rules/no-win32-isabsolute-for-qualification.yml +23 -0
  273. package/rules/ast-grep-rules/rules/strict-equality-js.yml +14 -1
  274. package/rules/ast-grep-rules/rules/strict-equality.yml +14 -1
  275. package/rules/ast-grep-rules/rules/strict-inequality-js.yml +14 -1
  276. package/rules/ast-grep-rules/rules/strict-inequality.yml +14 -1
  277. package/rules/tree-sitter-queries/cpp/no-memset-sensitive-data.yml +9 -3
  278. package/rules/tree-sitter-queries/cpp/no-scoped-lock-without-args.yml +6 -6
  279. package/rules/tree-sitter-queries/css/calc-spacing.yml +8 -6
  280. package/rules/tree-sitter-queries/go/go-mutex-copy.yml +21 -18
  281. package/rules/tree-sitter-queries/go/go-shared-map-write-goroutine.yml +3 -3
  282. package/rules/tree-sitter-queries/java/infinite-loop-java.yml +3 -3
  283. package/rules/tree-sitter-queries/java/junit-call-super.yml +6 -4
  284. package/rules/tree-sitter-queries/java/no-double-checked-locking.yml +10 -8
  285. package/rules/tree-sitter-queries/java/no-field-shadowing.yml +1 -1
  286. package/rules/tree-sitter-queries/java/prepared-statement-valid-indices.yml +2 -3
  287. package/rules/tree-sitter-queries/java/resources-closed.yml +2 -2
  288. package/rules/tree-sitter-queries/java/springboot-default-package.yml +6 -3
  289. package/rules/tree-sitter-queries/java/switch-fall-through.yml +6 -4
  290. package/rules/tree-sitter-queries/java/switch-non-case-labels.yml +4 -3
  291. package/rules/tree-sitter-queries/java/tests-include-assertions.yml +6 -5
  292. package/rules/tree-sitter-queries/javascript/switch-case-termination-js.yml +5 -8
  293. package/rules/tree-sitter-queries/javascript/switch-non-case-labels.yml +3 -2
  294. package/rules/tree-sitter-queries/kotlin/prepared-statement-indices.yml +9 -5
  295. package/rules/tree-sitter-queries/php/this-in-static-context.yml +5 -5
  296. package/rules/tree-sitter-queries/python/exit-signature-check.yml +2 -9
  297. package/rules/tree-sitter-queries/python/in-operator-unsupported.yml +3 -4
  298. package/rules/tree-sitter-queries/python/no-super-torchscript.yml +4 -8
  299. package/rules/tree-sitter-queries/python/notimplemented-boolean-context.yml +1 -5
  300. package/rules/tree-sitter-queries/python/python-empty-except.yml +1 -1
  301. package/rules/tree-sitter-queries/python/return-in-init.yml +0 -2
  302. package/rules/tree-sitter-queries/python/yield-return-outside-function.yml +0 -3
  303. package/rules/tree-sitter-queries/ruby/ruby-command-injection.yml +1 -12
  304. package/rules/tree-sitter-queries/ruby/ruby-eval.yml +1 -1
  305. package/rules/tree-sitter-queries/ruby/ruby-insecure-deserialization.yml +4 -4
  306. package/rules/tree-sitter-queries/ruby/ruby-insecure-random.yml +4 -11
  307. package/rules/tree-sitter-queries/ruby/ruby-open-struct.yml +1 -1
  308. package/rules/tree-sitter-queries/ruby/ruby-string-eval.yml +2 -3
  309. package/rules/tree-sitter-queries/ruby/ruby-weak-hash.yml +4 -4
  310. package/rules/tree-sitter-queries/rust/rust-lock-held-across-await.yml +4 -3
  311. package/rules/tree-sitter-queries/tsx/no-nested-links.yml +4 -6
  312. package/rules/tree-sitter-queries/typescript/console-statement.yml +11 -0
  313. package/rules/tree-sitter-queries/typescript/duplicate-function-arg.yml +4 -9
  314. package/rules/tree-sitter-queries/typescript/empty-switch-case.yml +13 -9
  315. package/rules/tree-sitter-queries/typescript/infinite-loop.yml +2 -2
  316. package/rules/tree-sitter-queries/typescript/mixed-async-styles.yml +10 -1
  317. package/rules/tree-sitter-queries/typescript/switch-case-termination.yml +5 -8
  318. package/rules/tree-sitter-queries/typescript/ts-insecure-random.yml +7 -10
  319. package/rules/tree-sitter-queries/typescript/unsafe-regex.yml +4 -2
  320. package/rules/typos/_typos.toml +17 -0
  321. package/scripts/analyze-pi-lens-logs.mjs +55 -2
  322. package/skills/pi-lens-write-tree-sitter-rule/SKILL.md +5 -0
  323. package/dist/clients/ast-grep-parser.js +0 -86
  324. package/dist/clients/config-enabled-shape.js +0 -39
  325. package/dist/clients/lsp/interactive-install.js +0 -367
  326. package/dist/clients/lsp/lsp-index.js +0 -10
  327. package/dist/clients/lsp/server-strategies.js +0 -5
  328. package/dist/clients/project-metadata.js +0 -690
  329. package/dist/clients/source-groups.js +0 -96
  330. package/dist/clients/types.js +0 -11
  331. package/docs/env_variables.md +0 -10
  332. package/rules/tree-sitter-queries/abap-disabled/delete-where.yml +0 -46
  333. package/rules/tree-sitter-queries/cpp/no-confused-move-forward.yml +0 -59
  334. package/rules/tree-sitter-queries/cpp/noexcept-functions.yml +0 -58
  335. package/rules/tree-sitter-queries/java/mockito-initialized.yml +0 -66
  336. package/rules/tree-sitter-queries/java/no-wait-notify-on-thread.yml +0 -58
  337. package/rules/tree-sitter-queries/java/short-circuit-logic.yml +0 -57
  338. package/rules/tree-sitter-queries/java/spring-session-attributes-setcomplete.yml +0 -75
  339. package/rules/tree-sitter-queries/plsql-disabled/delete-update-where.yml +0 -56
  340. package/rules/tree-sitter-queries/plsql-disabled/end-loop-semicolon.yml +0 -51
  341. package/rules/tree-sitter-queries/plsql-disabled/fetch-bulk-collect-limit.yml +0 -47
  342. package/rules/tree-sitter-queries/plsql-disabled/forallsave-exceptions.yml +0 -51
  343. package/rules/tree-sitter-queries/plsql-disabled/nchar-nvarchar2-bytes.yml +0 -54
  344. package/rules/tree-sitter-queries/plsql-disabled/not-null-initialization.yml +0 -59
  345. package/rules/tree-sitter-queries/plsql-disabled/raise-application-error-codes.yml +0 -50
  346. package/rules/tree-sitter-queries/typescript-disabled/ts-path-traversal.yml +0 -71
@@ -21,17 +21,23 @@ import { logCascade } from "../cascade-logger.js";
21
21
  import { getDiagnosticTracker } from "../diagnostic-tracker.js";
22
22
  import { isTierAwareCascadeEnabled, recordOutstandingCascadeTouch, } from "../lsp/cascade-tier.js";
23
23
  import { classifyCascadeWaitTier } from "../lsp/wait-policy/index.js";
24
+ import { bindingStateLabel, } from "../lsp/diagnostic-binding.js";
24
25
  import { getServersForFileWithConfig } from "../lsp/config.js";
25
26
  import { getLSPService } from "../lsp/index.js";
26
27
  import { isExternalOrVendorFile, normalizeMapKey } from "../path-utils.js";
27
28
  import { getProjectIgnoreMatcher } from "../file-utils.js";
28
- import { clearReviewGraphWorkspaceCache, getLastGraphBuildInfo, } from "../review-graph/builder.js";
29
- import { buildReverseDependencyIndexFromGraph, getAffectedFilesFromIndex, writeReverseDependencyIndexToSnapshot, } from "../reverse-deps.js";
29
+ import { resetAstGrepUnsupportedLanguageLog } from "./runners/ast-grep-napi.js";
30
+ import { isTestRoleCollateral } from "../collateral-test-role.js";
31
+ import { clearReviewGraphWorkspaceCache, getGraphBuildInfoForGraph, getGraphImportChanges, graphBuildInfoIsTrustworthy, } from "../review-graph/builder.js";
32
+ import { buildReverseDependencyIndexFromGraph, getAffectedFilesFromIndex, patchReverseDependencyIndex, writeReverseDependencyIndexToSnapshot, } from "../reverse-deps.js";
30
33
  import { buildOrUpdateGraph, computeImpactCascade, computeTransitiveImpact, formatImpactCascade, } from "../review-graph/service.js";
31
34
  import { clearModuleGraphCache } from "../review-graph/workspace-modules.js";
35
+ import { releaseWorkspaceTopologyIdleTimers } from "../workspace-topology.js";
32
36
  import { RUNTIME_CONFIG } from "../runtime-config.js";
33
37
  import { findCompiledClassesDir, hasJavaBuildDescriptor, } from "../tool-policy.js";
34
38
  import { removeWordIndexDocument, updateWordIndexDocument, WORD_INDEX_MAX_BYTES, } from "../word-index.js";
39
+ import { reconcileCascadeNeighborLspErrors } from "../widget-state.js";
40
+ import { findAuxiliaryProfileForSource } from "./auxiliary-lsp.js";
35
41
  // Register fact providers. All register eagerly here (the dispatch entry) — the
36
42
  // tree-sitter-backed providers included, since the parsing stack loads
37
43
  // `web-tree-sitter` lazily inside client.init(), not at module import, so it
@@ -292,6 +298,7 @@ export function getDispatchGroupsForKind(kind, pi) {
292
298
  export function resetDispatchBaselines(cwd) {
293
299
  if (cwd)
294
300
  applyProjectLensConfig(cwd);
301
+ resetAstGrepUnsupportedLanguageLog();
295
302
  sessionFacts.clearAll();
296
303
  resetSessionSlopScore();
297
304
  clearCoverageNoticeState();
@@ -321,6 +328,14 @@ export function getCascadeSessionStats() {
321
328
  }
322
329
  const neighborTouchCache = new Map();
323
330
  const recentlyCleanNeighborCache = new Map();
331
+ /** O(1) entry counts of this module's turn-bounded caches (#1123 item 2
332
+ * memory attribution) — both are `Map.size` reads, never iterated. */
333
+ export function getDispatchCascadeCacheStats() {
334
+ return {
335
+ neighborTouchCacheSize: neighborTouchCache.size,
336
+ recentlyCleanNeighborCacheSize: recentlyCleanNeighborCache.size,
337
+ };
338
+ }
324
339
  const RECENTLY_CLEAN_TTL_TURNS = 5;
325
340
  // B10: tracks files that were the *primary* edited file this turn.
326
341
  // These are excluded from cascade neighbor results — their own pipeline run
@@ -342,14 +357,136 @@ function ensureCascadeTurnScope(turnSeq) {
342
357
  const CASCADE_TTL_MS = 240_000;
343
358
  const MAX_PER_FILE = RUNTIME_CONFIG.pipeline.cascadeMaxDiagnosticsPerFile;
344
359
  const MAX_FILES = RUNTIME_CONFIG.pipeline.cascadeMaxFiles;
360
+ /**
361
+ * The genuine language-server ERROR diagnostics from a cascade neighbor
362
+ * re-check, ready to reconcile into the footer widget (#1093).
363
+ *
364
+ * Drops any diagnostic whose `source` matches an auxiliary-LSP profile
365
+ * (opengrep/ast-grep/zizmor/typos — `findAuxiliaryProfileForSource`). The
366
+ * cascade's `convertLspDiagnostics` tags everything `tool: "lsp"`,
367
+ * `semantic: "blocking"` and — unlike every OTHER widget writer
368
+ * (`runners/lsp.ts`, `tools/lsp-diagnostics.ts`, `tools/lens-diagnostics.ts`) —
369
+ * never runs `retagAuxiliaryDiagnostics`. Since `getAllDiagnostics` /
370
+ * `touchFile({clientScope:"all"})` include the auxiliary servers' findings,
371
+ * writing them here would (a) DOUBLE-COUNT a neighbor's own correctly-tagged aux
372
+ * entry and (b) ESCALATE an advisory/suppressed aux finding into a blocking
373
+ * `tool:"lsp"` error, bypassing aux policy (semantic downgrade, native
374
+ * `# nosemgrep`/`zizmor:ignore` suppression, `skipTestFiles`). Aux findings are
375
+ * per-file lint/security signals the neighbor's OWN per-edit runners own; they
376
+ * are not cross-file impact, so the cascade simply excludes them and the merge
377
+ * (`reconcileCascadeNeighborLspErrors`) preserves the neighbor's existing aux
378
+ * entries untouched. This keeps `isLspErrorEntry`'s "tool === 'lsp' uniquely
379
+ * identifies a genuine language-server entry" contract true for what we write.
380
+ *
381
+ * The DISPLAY list (`diags` at each call site) is deliberately left as-is —
382
+ * that is pre-existing cascade output behavior, out of scope for #1093.
383
+ */
384
+ function cascadeReconcilableLspErrors(rawDiags, neighborPath) {
385
+ return convertLspDiagnostics(rawDiags
386
+ .filter((d) => d.severity === 1 && !findAuxiliaryProfileForSource(d.source))
387
+ .slice(0, MAX_PER_FILE), neighborPath);
388
+ }
389
+ /**
390
+ * Read the content `binding` verdict off a diagnostics result (#1095).
391
+ *
392
+ * `touchFile` carries `binding` as an EXPLICIT enumerable field on its
393
+ * `TouchFileResult` wrapper (#1179), so it survives any copy of `.diags`.
394
+ * `getAllDiagnostics` still attaches `binding` as a lazy, disk-verifying
395
+ * NON-enumerable getter on each Map entry — reading it directly off the
396
+ * producer's own entry (never a spread/clone, which drops non-enumerables)
397
+ * triggers the disk verify exactly once (memoized per entry). Accepts either
398
+ * shape; returns `undefined` when no binding was attached at all (a partially-
399
+ * mocked client, a non-collecting touch) — indistinguishable from "unknown" at
400
+ * every call site, which is the intended pre-#1095 fall-through.
401
+ */
402
+ function readBoundToCurrentDisk(rawDiags) {
403
+ return rawDiags
404
+ ?.binding?.boundToCurrentDisk;
405
+ }
406
+ /**
407
+ * #1095: is this active-touch result a CONFIRMED observation of the neighbor's
408
+ * current on-disk LSP-error state — safe to reconcile into the footer widget and
409
+ * (when clean) to seed the recently-clean neighbor cache?
410
+ *
411
+ * Composes the two independent disqualifiers into ONE clearly-named predicate so
412
+ * a future flag cannot be silently missed at just one of the several gate sites:
413
+ * - `inconclusive` (#1093/#571): the notify/diagnostics wait lapsed its deadline,
414
+ * so a resolved `[]` is NOT a confirmed clean (the #533 false-clean trap).
415
+ * - `binding.boundToCurrentDisk === false` (#1095): the diagnostics were computed
416
+ * against a DIFFERENT disk state than what is on disk now (the server's view
417
+ * diverged / a pre-fix buffer) — not an observation of current disk. `true` and
418
+ * `"unknown"` both pass; `"unknown"` preserves pre-#1095 behavior for a
419
+ * version-less server exactly.
420
+ *
421
+ * #1179: both flags are EXPLICIT enumerable fields on the `touchFile`
422
+ * `TouchFileResult` wrapper — read them off the wrapper (`rawDiags`), whose
423
+ * `.diags` a downstream `.filter()`/copy operates on without touching the flags.
424
+ */
425
+ function readInconclusive(rawDiags) {
426
+ return rawDiags?.inconclusive === true;
427
+ }
428
+ function isConfirmedTouch(rawDiags) {
429
+ return !readInconclusive(rawDiags) && readBoundToCurrentDisk(rawDiags) !== false;
430
+ }
345
431
  const reverseDepsIndexCache = new Map();
432
+ const REVERSE_DEPS_MAX_WARM_ROOTS = 8;
433
+ const REVERSE_DEPS_IDLE_EVICT_MS_DEFAULT = 20 * 60_000;
434
+ function reverseDepsIdleEvictMs() {
435
+ const value = Number.parseInt(process.env.PI_LENS_REVERSE_DEPS_IDLE_EVICT_MS ?? "", 10);
436
+ return Number.isSafeInteger(value) && value > 0 ? value : REVERSE_DEPS_IDLE_EVICT_MS_DEFAULT;
437
+ }
438
+ function deleteReverseDepsEntry(key) {
439
+ const entry = reverseDepsIndexCache.get(key);
440
+ if (entry?.idleTimer !== undefined)
441
+ clearTimeout(entry.idleTimer);
442
+ if (entry)
443
+ entry.idleTimer = undefined;
444
+ reverseDepsIndexCache.delete(key);
445
+ }
446
+ function touchReverseDepsEntry(key, entry, armIdleTimer = true) {
447
+ entry.lastUsedAt = Date.now();
448
+ if (entry.idleTimer !== undefined)
449
+ clearTimeout(entry.idleTimer);
450
+ entry.idleTimer = undefined;
451
+ if (!armIdleTimer)
452
+ return;
453
+ const stamp = entry.lastUsedAt;
454
+ entry.idleTimer = setTimeout(() => {
455
+ if (reverseDepsIndexCache.get(key) !== entry || entry.lastUsedAt !== stamp)
456
+ return;
457
+ deleteReverseDepsEntry(key);
458
+ }, reverseDepsIdleEvictMs());
459
+ entry.idleTimer.unref?.();
460
+ }
461
+ function setReverseDepsEntry(key, entry, armIdleTimer = true) {
462
+ const resident = { ...entry, lastUsedAt: Date.now() };
463
+ reverseDepsIndexCache.set(key, resident);
464
+ touchReverseDepsEntry(key, resident, armIdleTimer);
465
+ while (reverseDepsIndexCache.size > REVERSE_DEPS_MAX_WARM_ROOTS) {
466
+ const victim = [...reverseDepsIndexCache.entries()].sort(([, a], [, b]) => a.lastUsedAt - b.lastUsedAt)[0];
467
+ if (!victim)
468
+ break;
469
+ deleteReverseDepsEntry(victim[0]);
470
+ }
471
+ }
346
472
  function reverseDepsReuseEnabled() {
347
473
  const raw = process.env.PI_LENS_REVERSE_DEPS_REUSE;
348
474
  return raw !== "0" && raw !== "false";
349
475
  }
350
476
  /** Test-reset hook — mirrors clearReviewGraphWorkspaceCache's scope. */
351
477
  export function clearReverseDepsIndexCache() {
352
- reverseDepsIndexCache.clear();
478
+ for (const key of reverseDepsIndexCache.keys())
479
+ deleteReverseDepsEntry(key);
480
+ }
481
+ /** Test-only visibility for Tier-2 eviction/recovery tests. */
482
+ export function _getReverseDepsIndexCacheKeysForTests() {
483
+ return [...reverseDepsIndexCache.entries()]
484
+ .sort(([, a], [, b]) => a.lastUsedAt - b.lastUsedAt)
485
+ .map(([key]) => key);
486
+ }
487
+ /** Test-only seed that still exercises the production timer/cap seam. */
488
+ export function _seedReverseDepsIndexCacheForTests(key, index, generation) {
489
+ setReverseDepsEntry(key, { index, savedToSnapshot: false, generation });
353
490
  }
354
491
  // Bounded transitive cascade (#162): expand neighbour derivation beyond the
355
492
  // one-hop importers/callers to depth-2 dependents, so an edit's blast radius
@@ -460,679 +597,994 @@ function updateWordIndexForCascade(args) {
460
597
  onUpdated?.(wordIndex);
461
598
  }
462
599
  export async function computeCascadeForFile(filePath, cwd, options = {}) {
463
- const { hasBlockers = false, dbg, turnSeq = 0, writeSeq, seqState, fileContent, wordIndex, onWordIndexUpdated, } = options;
464
- ensureCascadeTurnScope(turnSeq);
465
- if (hasBlockers) {
466
- logCascade({
467
- phase: "cascade_skip",
468
- filePath,
469
- reason: "primary_has_blockers",
470
- });
471
- return {
472
- filePath,
473
- result: undefined,
474
- neighborCount: 0,
475
- diagnosticCount: 0,
476
- skipReason: "blockers",
477
- };
478
- }
479
- const fileKind = detectFileKind(filePath);
480
- if (!fileKind) {
481
- logCascade({ phase: "cascade_skip", filePath, reason: "non_code_file" });
482
- return {
483
- filePath,
484
- result: undefined,
485
- neighborCount: 0,
486
- diagnosticCount: 0,
487
- skipReason: "non_code",
488
- };
489
- }
490
- const normalizedFile = resolveRunnerPath(cwd, filePath);
491
- const normalizedFileKey = normalizeMapKey(normalizedFile);
492
- // B10: record this file as a primary edit so later cascade calls in the same
493
- // turn won't show it as a neighbor.
494
- primaryFilesThisTurn.add(normalizedFileKey);
495
- // #348 phase 2: warm per-edit word-index maintenance, review-graph style —
496
- // update at the SAME seam as the graph rebuild below, using content the
497
- // pipeline already read (no extra I/O). See computeCascadeForFile's
498
- // `wordIndex`/`fileContent` doc comments for the cold/no-forward-index
499
- // no-op rules.
500
- //
501
- // Deliberately keyed by `path.resolve(filePath)`, NOT `normalizedFile`
502
- // (which is `normalizeMapKey`'d — realpath-canonicalized + lowercased on
503
- // Windows). The word index's OWN keys come from `collectWordIndexDocs` →
504
- // `collectSourceFilesAsync`'s file walk, which yields plain
505
- // `path.resolve()`-joined paths (native separators, on-disk casing as
506
- // reported by the walk, no realpath call). Keying this update with the
507
- // cascade's normalized key would silently create a SECOND, orphaned entry
508
- // next to the walker's original-cased entry instead of replacing it —
509
- // exactly the kind of divergence the equivalence-property test is meant to
510
- // catch, so the key shape here must match the build path's, not the
511
- // cascade/graph's own (different) normalization scheme.
512
- updateWordIndexForCascade({
513
- wordIndex,
514
- filePath: nodePath.resolve(filePath),
515
- content: fileContent,
516
- onUpdated: onWordIndexUpdated,
517
- dbg,
518
- });
519
- let impact = {
520
- filePath: normalizedFile,
521
- changedSymbols: [],
522
- directImporters: [],
523
- directCallers: [],
524
- neighborFiles: [],
525
- riskFlags: [],
526
- };
527
- let sortedNeighbors = [];
528
- let importerSet = new Set();
529
- let callerSet = new Set();
530
- let referenceCount = 0;
531
- if (CASCADE_GRAPH_KINDS.has(fileKind)) {
532
- const graphStart = Date.now();
533
- const graph = await buildOrUpdateGraph(cwd, [normalizedFile], sessionFacts, seqState);
534
- const graphMs = Date.now() - graphStart;
535
- // #459: the reuse decision keys on graph.buildGeneration — a stamp that
536
- // travels WITH the graph instance this cascade holds. Deliberately NOT the
537
- // global last-build-info slot: post-#450 cascades overlap, and another
538
- // cascade's cache-hit build can overwrite that slot (graphChanged:false)
539
- // between this build mutating the graph and this read — which would turn a
540
- // changed graph into a spurious reuse of a stale index that steady-state
541
- // cache hits then never heal. Generation equality can't be clobbered into
542
- // a false positive: a graph-mutating build always mints a new generation.
543
- // An unstamped graph (mode "skipped") always rebuilds.
544
- const graphBuildInfo = getLastGraphBuildInfo();
545
- const workspaceKey = normalizeMapKey(cwd);
546
- const cachedReverseDeps = reverseDepsIndexCache.get(workspaceKey);
547
- const canReuse = reverseDepsReuseEnabled() &&
548
- cachedReverseDeps !== undefined &&
549
- graph.buildGeneration !== undefined &&
550
- cachedReverseDeps.generation === graph.buildGeneration;
551
- let reverseDepsIndex;
552
- let reverseDepsSaved;
553
- if (canReuse && cachedReverseDeps) {
554
- reverseDepsIndex = cachedReverseDeps.index;
555
- reverseDepsSaved = cachedReverseDeps.savedToSnapshot;
600
+ const reverseDepsTimersToRelease = new Set();
601
+ const reverseDepsEntriesAtStart = new Set(reverseDepsIndexCache.values());
602
+ try {
603
+ const { hasBlockers = false, dbg, turnSeq = 0, writeSeq, seqState, fileContent, wordIndex, onWordIndexUpdated, } = options;
604
+ ensureCascadeTurnScope(turnSeq);
605
+ if (hasBlockers) {
556
606
  logCascade({
557
- phase: "reverse_deps_cache",
607
+ phase: "cascade_skip",
558
608
  filePath,
559
- durationMs: Date.now() - graphStart,
560
- metadata: {
561
- action: "reused_unchanged",
562
- savedToSnapshot: reverseDepsSaved,
563
- importsFileCount: Object.keys(reverseDepsIndex.imports).length,
564
- importedByFileCount: Object.keys(reverseDepsIndex.importedBy).length,
565
- },
566
- });
567
- }
568
- else {
569
- reverseDepsIndex = buildReverseDependencyIndexFromGraph({
570
- cwd,
571
- graph,
572
- });
573
- reverseDepsSaved = writeReverseDependencyIndexToSnapshot({
574
- cwd,
575
- index: reverseDepsIndex,
576
- dbg,
609
+ reason: "primary_has_blockers",
577
610
  });
578
- reverseDepsIndexCache.set(workspaceKey, {
579
- index: reverseDepsIndex,
580
- savedToSnapshot: reverseDepsSaved,
581
- generation: graph.buildGeneration,
582
- });
583
- logCascade({
584
- phase: "reverse_deps_cache",
611
+ return {
585
612
  filePath,
586
- durationMs: Date.now() - graphStart,
587
- metadata: {
588
- action: "refresh_from_review_graph",
589
- savedToSnapshot: reverseDepsSaved,
590
- importsFileCount: Object.keys(reverseDepsIndex.imports).length,
591
- importedByFileCount: Object.keys(reverseDepsIndex.importedBy).length,
592
- importEdgeCount: Object.values(reverseDepsIndex.imports).reduce((total, imports) => total + imports.length, 0),
593
- },
594
- });
613
+ result: undefined,
614
+ neighborCount: 0,
615
+ diagnosticCount: 0,
616
+ skipReason: "blockers",
617
+ };
595
618
  }
596
- // Count files represented in the graph (nodes with a filePath).
597
- const graphFileCount = new Set([...graph.nodes.values()].flatMap((n) => n.filePath ? [n.filePath] : [])).size;
598
- logCascade({
599
- phase: "graph_build",
600
- filePath,
601
- graphBuiltMs: graphMs,
602
- graphReused: graphBuildInfo.reused,
603
- graphNodeCount: graph.nodes.size,
604
- graphFileCount,
605
- graphChangedSymbolCount: (graph.changedSymbolsByFile.get(normalizedFileKey) ?? []).length,
606
- metadata: {
607
- graphBuildMode: graphBuildInfo.mode,
608
- skipReason: graphBuildInfo.skipReason,
609
- sourceFileCount: graphBuildInfo.sourceFileCount,
610
- maxFileCount: graphBuildInfo.maxFileCount,
611
- // #451: when the seq fast path fell back (or was skipped), why — so
612
- // cascade.log surfaces the fast-path hit/miss rate.
613
- seqFastpathFallback: graphBuildInfo.seqFastpathFallback,
614
- },
615
- });
616
- impact = computeImpactCascade(graph, normalizedFile, cwd);
617
- const reverseDepNeighbors = getAffectedFilesFromIndex(reverseDepsIndex, normalizedFile, 1, MAX_FILES * 2);
618
- logCascade({
619
- phase: "reverse_deps_cache",
620
- filePath,
621
- metadata: {
622
- action: "merge_neighbors",
623
- depth: 1,
624
- neighborCount: reverseDepNeighbors.length,
625
- neighbors: reverseDepNeighbors.slice(0, 10),
626
- },
627
- });
628
- if (reverseDepNeighbors.length > 0) {
629
- impact.directImporters = [
630
- ...new Set([...impact.directImporters, ...reverseDepNeighbors]),
631
- ];
632
- impact.neighborFiles = [
633
- ...new Set([...impact.neighborFiles, ...reverseDepNeighbors]),
634
- ];
635
- logCascade({
636
- phase: "neighbor_snapshot",
619
+ const fileKind = detectFileKind(filePath);
620
+ if (!fileKind) {
621
+ logCascade({ phase: "cascade_skip", filePath, reason: "non_code_file" });
622
+ return {
637
623
  filePath,
638
- neighborFile: "[reverse-deps-cache]",
639
- diagnosticCount: reverseDepNeighbors.length,
640
- autoPropagate: false,
641
- metadata: { reverseDepsCache: true },
642
- });
624
+ result: undefined,
625
+ neighborCount: 0,
626
+ diagnosticCount: 0,
627
+ skipReason: "non_code",
628
+ };
643
629
  }
644
- // Symbol-level blast radius via LSP references (precision upgrade over
645
- // file-level import edges). Only when changed symbols are detected.
646
- // Keep the budget tight: 750ms per symbol, 1200ms total, max 3 symbols.
647
- if (impact.changedSymbols.length > 0) {
648
- const lspService = getLSPService();
649
- const symbolNodeIds = graph.symbolNodesByFile.get(normalizedFileKey) ?? [];
650
- const refFiles = new Set();
651
- const refsStart = Date.now();
652
- for (const symbolName of impact.changedSymbols.slice(0, 3)) {
653
- const symbolNodeId = symbolNodeIds.find((id) => {
654
- const node = graph.nodes.get(id);
655
- return node?.symbolName === symbolName;
630
+ const normalizedFile = resolveRunnerPath(cwd, filePath);
631
+ const normalizedFileKey = normalizeMapKey(normalizedFile);
632
+ // B10: record this file as a primary edit so later cascade calls in the same
633
+ // turn won't show it as a neighbor.
634
+ primaryFilesThisTurn.add(normalizedFileKey);
635
+ // #348 phase 2: warm per-edit word-index maintenance, review-graph style —
636
+ // update at the SAME seam as the graph rebuild below, using content the
637
+ // pipeline already read (no extra I/O). See computeCascadeForFile's
638
+ // `wordIndex`/`fileContent` doc comments for the cold/no-forward-index
639
+ // no-op rules.
640
+ //
641
+ // Keyed by `path.resolve(filePath)` (native separators, tool-input casing).
642
+ // Since #1025 the word index's path maps are `PathKeyedMap`s that fold every
643
+ // key through `wordIndexKey` (`normalizeEphemeralMapKey` — slash-fold +
644
+ // win32-lowercase) INTERNALLY, so this per-edit key and the build path's own
645
+ // walk-derived key (`collectWordIndexDocs` → `collectSourceFilesAsync`)
646
+ // collapse to the same entry regardless of on-disk-vs-input casing/separator.
647
+ // The old hazard — this update silently orphaning a SECOND entry next to the
648
+ // walker's original-cased one — is now structurally impossible at the map
649
+ // layer, so this seam no longer has to hand-match the build path's key shape.
650
+ updateWordIndexForCascade({
651
+ wordIndex,
652
+ filePath: nodePath.resolve(filePath),
653
+ content: fileContent,
654
+ onUpdated: onWordIndexUpdated,
655
+ dbg,
656
+ });
657
+ let impact = {
658
+ filePath: normalizedFile,
659
+ changedSymbols: [],
660
+ directImporters: [],
661
+ directCallers: [],
662
+ neighborFiles: [],
663
+ riskFlags: [],
664
+ };
665
+ let sortedNeighbors = [];
666
+ let importerSet = new Set();
667
+ let callerSet = new Set();
668
+ let referenceCount = 0;
669
+ if (CASCADE_GRAPH_KINDS.has(fileKind)) {
670
+ const graphStart = Date.now();
671
+ const graph = await buildOrUpdateGraph(cwd, [normalizedFile], sessionFacts, seqState);
672
+ const graphMs = Date.now() - graphStart;
673
+ // #459: the reuse decision keys on graph.buildGeneration — a stamp that
674
+ // travels WITH the graph instance this cascade holds. Deliberately NOT the
675
+ // global last-build-info slot: post-#450 cascades overlap, and another
676
+ // cascade's cache-hit build can overwrite that slot (graphChanged:false)
677
+ // between this build mutating the graph and this read — which would turn a
678
+ // changed graph into a spurious reuse of a stale index that steady-state
679
+ // cache hits then never heal. Generation equality can't be clobbered into
680
+ // a false positive: a graph-mutating build always mints a new generation.
681
+ // An unstamped graph (mode "skipped") always rebuilds.
682
+ const graphBuildInfo = getGraphBuildInfoForGraph(graph);
683
+ // #1179 fail-closed: `getGraphBuildInfoForGraph` falls back to the global
684
+ // last-build slot on a WeakMap identity miss, which — once some real build
685
+ // has stamped — could carry a SIBLING graph's healthy `mode: "cached"`. The
686
+ // degraded-marker gate below must not read a sibling's state, so it checks
687
+ // trustworthiness and, when the slot cannot be trusted for THIS graph, treats
688
+ // coverage as unknown (degraded) rather than clean. Always trustworthy on the
689
+ // live path — every `_doBuildGraph` return stamps the graph before the cascade
690
+ // reads it — so this is inert today and only hardens a future unstamped graph.
691
+ const graphBuildInfoTrustworthy = graphBuildInfoIsTrustworthy(graph);
692
+ const workspaceKey = normalizeMapKey(cwd);
693
+ const cachedReverseDeps = reverseDepsIndexCache.get(workspaceKey);
694
+ if (cachedReverseDeps) {
695
+ touchReverseDepsEntry(workspaceKey, cachedReverseDeps, false);
696
+ reverseDepsTimersToRelease.add(workspaceKey);
697
+ }
698
+ const importDelta = getGraphImportChanges(graph);
699
+ // A one-step delta is only usable against an index cached at exactly the
700
+ // delta's predecessor generation. Builds minted elsewhere (mcp analyze,
701
+ // lens-map, session warm) advance generations whose import changes this
702
+ // delta does not cover — reusing/patching across that gap stamps a stale
703
+ // index as current, and generation equality then hides the loss forever
704
+ // (#939 review finding 1).
705
+ const deltaContiguous = importDelta !== undefined &&
706
+ importDelta.fromGeneration !== undefined &&
707
+ cachedReverseDeps !== undefined &&
708
+ cachedReverseDeps.generation === importDelta.fromGeneration;
709
+ const importChanges = deltaContiguous ? importDelta.changes : undefined;
710
+ const importsChanged = importChanges?.some((change) => change.existedBefore !== change.existsAfter ||
711
+ change.priorTargets.length !== change.newTargets.length ||
712
+ change.priorTargets.some((target, index) => target !== change.newTargets[index]));
713
+ const canReuse = reverseDepsReuseEnabled() &&
714
+ cachedReverseDeps !== undefined &&
715
+ ((graph.buildGeneration !== undefined &&
716
+ cachedReverseDeps.generation === graph.buildGeneration) ||
717
+ (importChanges !== undefined && !importsChanged));
718
+ let reverseDepsIndex;
719
+ let reverseDepsSaved;
720
+ if (canReuse && cachedReverseDeps) {
721
+ reverseDepsIndex = cachedReverseDeps.index;
722
+ reverseDepsSaved = cachedReverseDeps.savedToSnapshot;
723
+ cachedReverseDeps.generation = graph.buildGeneration;
724
+ logCascade({
725
+ phase: "reverse_deps_cache",
726
+ filePath,
727
+ durationMs: Date.now() - graphStart,
728
+ metadata: {
729
+ action: "reused_unchanged",
730
+ savedToSnapshot: reverseDepsSaved,
731
+ importsFileCount: Object.keys(reverseDepsIndex.imports).length,
732
+ importedByFileCount: Object.keys(reverseDepsIndex.importedBy).length,
733
+ },
656
734
  });
657
- if (!symbolNodeId)
658
- continue;
659
- const node = graph.nodes.get(symbolNodeId);
660
- const line = Number(node?.metadata?.line ?? 0);
661
- const column = Number(node?.metadata?.column ?? 0);
662
- if (line <= 0)
663
- continue;
664
- try {
665
- const refs = await Promise.race([
666
- lspService.references(normalizedFile, line - 1, column - 1, false),
667
- new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 750)),
668
- ]);
669
- for (const ref of refs) {
670
- let resolved;
671
- try {
672
- resolved = ref.uri.startsWith("file://")
673
- ? fileURLToPath(ref.uri)
674
- : ref.uri;
675
- }
676
- catch {
677
- continue;
678
- }
679
- if (normalizeMapKey(resolved) !== normalizedFileKey &&
680
- nodeFs.existsSync(resolved)) {
681
- refFiles.add(normalizeMapKey(resolved));
682
- }
683
- }
684
- }
685
- catch {
686
- // Timeout or LSP error — fall back to import-graph neighbors
687
- }
688
- if (Date.now() - refsStart > 1200)
689
- break; // Hard ceiling
690
735
  }
691
- if (refFiles.size > 0) {
692
- impact.neighborFiles = [
693
- ...new Set([...impact.neighborFiles, ...refFiles]),
694
- ];
736
+ else if (cachedReverseDeps && importChanges && importsChanged) {
737
+ reverseDepsIndex = patchReverseDependencyIndex(cachedReverseDeps.index, importChanges);
738
+ reverseDepsSaved = writeReverseDependencyIndexToSnapshot({
739
+ cwd,
740
+ index: reverseDepsIndex,
741
+ dbg,
742
+ });
743
+ setReverseDepsEntry(workspaceKey, {
744
+ index: reverseDepsIndex,
745
+ savedToSnapshot: reverseDepsSaved,
746
+ generation: graph.buildGeneration,
747
+ }, false);
748
+ reverseDepsTimersToRelease.add(workspaceKey);
695
749
  logCascade({
696
- phase: "neighbor_snapshot",
750
+ phase: "reverse_deps_cache",
697
751
  filePath,
698
- neighborFile: "[lsp-references]",
699
- diagnosticCount: refFiles.size,
700
- durationMs: Date.now() - refsStart,
701
- autoPropagate: false,
702
- metadata: { lspReferences: true },
752
+ durationMs: Date.now() - graphStart,
753
+ metadata: {
754
+ action: "patched_import_changes",
755
+ changedFileCount: importChanges.length,
756
+ savedToSnapshot: reverseDepsSaved,
757
+ },
703
758
  });
704
759
  }
705
- }
706
- // Bounded transitive expansion: add depth>1 dependents (indirect
707
- // importers/callers/referencers) so the blast radius isn't limited to one
708
- // hop. The one-hop sets above remain the floor (they sort first); these
709
- // fill the remaining budget. Graph BFS is in-memory + capped.
710
- if (CASCADE_TRANSITIVE_DEPTH > 1) {
711
- const transitive = computeTransitiveImpact(graph, normalizedFile, {
712
- maxDepth: CASCADE_TRANSITIVE_DEPTH,
713
- maxHits: CASCADE_NEIGHBOUR_BUDGET,
714
- });
715
- const added = [
716
- ...new Set(transitive.hits
717
- .map((hit) => hit.file)
718
- .filter((file) => file && normalizeMapKey(file) !== normalizedFileKey)),
719
- ].filter((file) => !impact.neighborFiles.includes(file));
720
- if (added.length > 0) {
721
- impact.neighborFiles = [...impact.neighborFiles, ...added];
760
+ else {
761
+ reverseDepsIndex = buildReverseDependencyIndexFromGraph({
762
+ cwd,
763
+ graph,
764
+ });
765
+ reverseDepsSaved = writeReverseDependencyIndexToSnapshot({
766
+ cwd,
767
+ index: reverseDepsIndex,
768
+ dbg,
769
+ });
770
+ setReverseDepsEntry(workspaceKey, {
771
+ index: reverseDepsIndex,
772
+ savedToSnapshot: reverseDepsSaved,
773
+ generation: graph.buildGeneration,
774
+ }, false);
775
+ reverseDepsTimersToRelease.add(workspaceKey);
722
776
  logCascade({
723
- phase: "neighbor_snapshot",
777
+ phase: "reverse_deps_cache",
724
778
  filePath,
725
- neighborFile: "[transitive-impact]",
726
- diagnosticCount: added.length,
727
- autoPropagate: false,
779
+ durationMs: Date.now() - graphStart,
728
780
  metadata: {
729
- transitive: true,
730
- maxDepth: CASCADE_TRANSITIVE_DEPTH,
731
- maxDepthReached: transitive.maxDepthReached,
732
- truncated: transitive.truncated,
781
+ action: "refresh_from_review_graph",
782
+ savedToSnapshot: reverseDepsSaved,
783
+ importsFileCount: Object.keys(reverseDepsIndex.imports).length,
784
+ importedByFileCount: Object.keys(reverseDepsIndex.importedBy).length,
785
+ importEdgeCount: Object.values(reverseDepsIndex.imports).reduce((total, imports) => total + imports.length, 0),
733
786
  },
734
787
  });
735
788
  }
736
- }
737
- // Sort by relationship strength (B6) then cap to the neighbour budget.
738
- // directImporters are most impactful, then callers, then reference edges.
739
- importerSet = new Set(impact.directImporters);
740
- callerSet = new Set(impact.directCallers);
741
- // neighbors that are neither direct importers nor callers are reference-edge neighbors
742
- const importerOrCallerSet = new Set([
743
- ...impact.directImporters,
744
- ...impact.directCallers,
745
- ]);
746
- referenceCount = impact.neighborFiles.filter((n) => !importerOrCallerSet.has(n)).length;
747
- sortedNeighbors = [...impact.neighborFiles]
748
- .filter((n) => nodeFs.existsSync(n))
749
- .filter((n) => !isExternalOrVendorFile(n, cwd))
750
- // Honour the project's ignore config: a user-ignored neighbour (e.g.
751
- // `**/*.test.ts`) must not surface as collateral cascade noise (#297).
752
- .filter((n) => !isIgnoredCascadeNeighbor(n, cwd))
753
- // B10: exclude files already edited as primary this turn — their own pipeline
754
- // run is the authoritative diagnostic source; showing them as neighbors is noise.
755
- .filter((n) => !primaryFilesThisTurn.has(normalizeMapKey(n)))
756
- .sort((a, b) => {
757
- const rank = (p) => importerSet.has(p) ? 0 : callerSet.has(p) ? 1 : 2;
758
- return rank(a) - rank(b);
759
- })
760
- .slice(0, CASCADE_NEIGHBOUR_BUDGET);
761
- }
762
- else {
763
- logCascade({
764
- phase: "cascade_skip",
765
- filePath,
766
- reason: "unsupported_graph_kind",
767
- metadata: { fileKind },
768
- });
769
- return {
770
- filePath,
771
- result: undefined,
772
- neighborCount: 0,
773
- diagnosticCount: 0,
774
- skipReason: "non_code",
775
- };
776
- }
777
- logCascade({
778
- phase: "neighbors_computed",
779
- filePath,
780
- neighborCount: sortedNeighbors.length,
781
- totalNeighborCount: impact.neighborFiles.length,
782
- importerCount: impact.directImporters.length,
783
- callerCount: impact.directCallers.length,
784
- referenceCount: Math.max(0, referenceCount),
785
- riskFlags: impact.riskFlags,
786
- metadata: { neighbors: sortedNeighbors.slice(0, 10) },
787
- });
788
- const lspService = getLSPService();
789
- // Hoist passive snapshot once — used for auto-propagating LSPs and fallback path.
790
- const allDiags = await lspService.getAllDiagnostics();
791
- const neighbors = [];
792
- let producedLspData = false;
793
- let coldSnapshotPaths = [];
794
- if (sortedNeighbors.length > 0) {
795
- const snapshotPaths = sortedNeighbors.filter(shouldReadCascadeFromSnapshot);
796
- const activePaths = sortedNeighbors.filter((n) => !shouldReadCascadeFromSnapshot(n));
797
- // Auto-propagating LSPs (TypeScript/Deno) — read passive snapshot with normalized key.
798
- // When the snapshot is valid, use it immediately (no touch needed — server already has
799
- // fresh data from auto-propagation). When missing or stale, fall through to the active
800
- // touch pool below so we get real diagnostics instead of silently returning zero.
801
- coldSnapshotPaths = [];
802
- for (const neighborPath of snapshotPaths) {
803
- const neighborStart = Date.now();
804
- const entry = allDiags.get(normalizeMapKey(neighborPath));
805
- const snapshotAgeSec = entry
806
- ? Math.round((Date.now() - entry.ts) / 1000)
807
- : undefined;
808
- const snapshotValid = entry != null && Date.now() - entry.ts < CASCADE_TTL_MS;
809
- if (!snapshotValid) {
810
- // No usable snapshot — queue for active touch alongside non-jsts neighbors.
789
+ // Count files represented in the graph (nodes with a filePath).
790
+ const graphFileCount = new Set([...graph.nodes.values()].flatMap((n) => n.filePath ? [n.filePath] : [])).size;
791
+ logCascade({
792
+ phase: "graph_build",
793
+ filePath,
794
+ graphBuiltMs: graphMs,
795
+ graphReused: graphBuildInfo.reused,
796
+ graphNodeCount: graph.nodes.size,
797
+ graphFileCount,
798
+ graphChangedSymbolCount: (graph.changedSymbolsByFile.get(normalizedFileKey) ?? []).length,
799
+ metadata: {
800
+ graphBuildMode: graphBuildInfo.mode,
801
+ skipReason: graphBuildInfo.skipReason,
802
+ sourceFileCount: graphBuildInfo.sourceFileCount,
803
+ maxFileCount: graphBuildInfo.maxFileCount,
804
+ // #451: when the seq fast path fell back (or was skipped), why — so
805
+ // cascade.log surfaces the fast-path hit/miss rate.
806
+ seqFastpathFallback: graphBuildInfo.seqFastpathFallback,
807
+ },
808
+ });
809
+ impact = computeImpactCascade(graph, normalizedFile, cwd);
810
+ // #1023: buildOrUpdateGraph returns an EMPTY graph (seeded only with the
811
+ // changed file's own symbols) when the repo is over
812
+ // PI_LENS_REVIEW_GRAPH_MAX_FILES (`too_many_files`) or the root is unsafe
813
+ // (`unsafe_root`) — both stamp mode "skipped" on the already-read
814
+ // graphBuildInfo. A capped or entry-budget-truncated graph is also not a
815
+ // complete dependent set even though it has nodes, so it must not look like
816
+ // a clean leaf. Thread the ALREADY-KNOWN degraded state (never re-derived)
817
+ // onto the result so the turn-end seam surfaces an honest advisory instead
818
+ // of a silent all-clear (#533). Keyed strictly off the graph's explicit
819
+ // degraded marker, NOT off `neighborFiles.length === 0`.
820
+ if ((graphBuildInfo.mode === "skipped" ||
821
+ graph.persistCoverage?.partial === true ||
822
+ !graphBuildInfoTrustworthy) &&
823
+ !impact.indeterminate) {
824
+ const coverage = graph.persistCoverage;
825
+ impact.indeterminate = {
826
+ reason: "graph_degraded",
827
+ detail: !graphBuildInfoTrustworthy
828
+ ? // #1179 fail-closed: the graph's own build-info was not found under
829
+ // its identity and the global slot may be a sibling build's — don't
830
+ // trust its mode. Surface an honest "unknown" advisory rather than a
831
+ // (possibly sibling-derived) all-clear.
832
+ "review graph coverage unknown — build state unavailable for this graph"
833
+ : graphBuildInfo.mode === "skipped"
834
+ ? graphBuildInfo.skipReason === "too_many_files"
835
+ ? graphBuildInfo.sourceFileCountTruncated
836
+ ? `review graph disabled — more than ${graphBuildInfo.maxFileCount ?? "?"} files (cap ${graphBuildInfo.maxFileCount ?? "?"})`
837
+ : `review graph disabled — ${graphBuildInfo.sourceFileCount ?? "?"} files over the ${graphBuildInfo.maxFileCount ?? "?"} cap`
838
+ : graphBuildInfo.skipReason === "unsafe_root"
839
+ ? "review graph skipped — workspace root is at/above home dir"
840
+ : `review graph unavailable (${graphBuildInfo.skipReason ?? "skipped"})`
841
+ : coverage?.sourceFilesTruncated
842
+ ? "review graph partial — source walk stopped at its visited-entry budget"
843
+ : "review graph partial — persisted graph coverage is incomplete",
844
+ sourceFileCount: graphBuildInfo.sourceFileCount,
845
+ maxFileCount: graphBuildInfo.maxFileCount,
846
+ };
847
+ }
848
+ const reverseDepNeighbors = getAffectedFilesFromIndex(reverseDepsIndex, normalizedFile, 1, MAX_FILES * 2);
849
+ logCascade({
850
+ phase: "reverse_deps_cache",
851
+ filePath,
852
+ metadata: {
853
+ action: "merge_neighbors",
854
+ depth: 1,
855
+ neighborCount: reverseDepNeighbors.length,
856
+ neighbors: reverseDepNeighbors.slice(0, 10),
857
+ },
858
+ });
859
+ if (reverseDepNeighbors.length > 0) {
860
+ impact.directImporters = [
861
+ ...new Set([...impact.directImporters, ...reverseDepNeighbors]),
862
+ ];
863
+ impact.neighborFiles = [
864
+ ...new Set([...impact.neighborFiles, ...reverseDepNeighbors]),
865
+ ];
811
866
  logCascade({
812
867
  phase: "neighbor_snapshot",
813
868
  filePath,
814
- neighborFile: neighborPath,
815
- diagnosticCount: 0,
816
- durationMs: Date.now() - neighborStart,
817
- autoPropagate: true,
818
- snapshotMissing: entry == null,
819
- snapshotAgeSec,
820
- coldSnapshot: true,
869
+ neighborFile: "[reverse-deps-cache]",
870
+ diagnosticCount: reverseDepNeighbors.length,
871
+ autoPropagate: false,
872
+ metadata: { reverseDepsCache: true },
821
873
  });
822
- coldSnapshotPaths.push(neighborPath);
823
- continue;
824
874
  }
825
- // #692: `source: "cascade"` used to be passed here to label `rule`
826
- // (`cascade:<code>`) — that override is gone (identity must come from
827
- // the diagnostic's own source; see `scanOrigin`'s doc comment), and
828
- // cascade neighbor diagnostics are ephemeral display-only output
829
- // (never reconciled into persisted widget/dedup state), so the label
830
- // had no remaining purpose and is simply dropped rather than migrated.
831
- const diags = convertLspDiagnostics(entry.diags.filter((d) => d.severity === 1).slice(0, MAX_PER_FILE), neighborPath);
832
- producedLspData = true;
833
- const durationMs = Date.now() - neighborStart;
875
+ // Symbol-level blast radius via LSP references (precision upgrade over
876
+ // file-level import edges). Only when changed symbols are detected.
877
+ // Keep the budget tight: 750ms per symbol, 1200ms total, max 3 symbols.
878
+ if (impact.changedSymbols.length > 0) {
879
+ const lspService = getLSPService();
880
+ const symbolNodeIds = graph.symbolNodesByFile.get(normalizedFileKey) ?? [];
881
+ const refFiles = new Set();
882
+ const refsStart = Date.now();
883
+ for (const symbolName of impact.changedSymbols.slice(0, 3)) {
884
+ const symbolNodeId = symbolNodeIds.find((id) => {
885
+ const node = graph.nodes.get(id);
886
+ return node?.symbolName === symbolName;
887
+ });
888
+ if (!symbolNodeId)
889
+ continue;
890
+ const node = graph.nodes.get(symbolNodeId);
891
+ const line = Number(node?.metadata?.line ?? 0);
892
+ const column = Number(node?.metadata?.column ?? 0);
893
+ if (line <= 0)
894
+ continue;
895
+ // #1109: store the timer and clear it once the race settles. Without
896
+ // this, when `references()` wins (the common case), the losing
897
+ // `setTimeout` stays a REF'D pending timer for the remaining 750ms —
898
+ // harmless in a long-lived session, but a keep-alive tail in a
899
+ // one-shot `pi --print` process (same uncleared-race-timeout class
900
+ // fixed for the LSP client-wait leak in clients/lsp/index.ts, #1097).
901
+ let refsTimer;
902
+ try {
903
+ const refs = await Promise.race([
904
+ lspService.references(normalizedFile, line - 1, column - 1, false),
905
+ new Promise((_, reject) => {
906
+ refsTimer = setTimeout(() => reject(new Error("timeout")), 750);
907
+ }),
908
+ ]);
909
+ for (const ref of refs) {
910
+ let resolved;
911
+ try {
912
+ resolved = ref.uri.startsWith("file://")
913
+ ? fileURLToPath(ref.uri)
914
+ : ref.uri;
915
+ }
916
+ catch {
917
+ continue;
918
+ }
919
+ if (normalizeMapKey(resolved) !== normalizedFileKey &&
920
+ nodeFs.existsSync(resolved)) {
921
+ refFiles.add(normalizeMapKey(resolved));
922
+ }
923
+ }
924
+ }
925
+ catch {
926
+ // Timeout or LSP error — fall back to import-graph neighbors
927
+ }
928
+ finally {
929
+ if (refsTimer !== undefined)
930
+ clearTimeout(refsTimer);
931
+ }
932
+ if (Date.now() - refsStart > 1200)
933
+ break; // Hard ceiling
934
+ }
935
+ if (refFiles.size > 0) {
936
+ impact.neighborFiles = [
937
+ ...new Set([...impact.neighborFiles, ...refFiles]),
938
+ ];
939
+ logCascade({
940
+ phase: "neighbor_snapshot",
941
+ filePath,
942
+ neighborFile: "[lsp-references]",
943
+ diagnosticCount: refFiles.size,
944
+ durationMs: Date.now() - refsStart,
945
+ autoPropagate: false,
946
+ metadata: { lspReferences: true },
947
+ });
948
+ }
949
+ }
950
+ // Bounded transitive expansion: add depth>1 dependents (indirect
951
+ // importers/callers/referencers) so the blast radius isn't limited to one
952
+ // hop. The one-hop sets above remain the floor (they sort first); these
953
+ // fill the remaining budget. Graph BFS is in-memory + capped.
954
+ if (CASCADE_TRANSITIVE_DEPTH > 1) {
955
+ const transitive = computeTransitiveImpact(graph, normalizedFile, {
956
+ maxDepth: CASCADE_TRANSITIVE_DEPTH,
957
+ maxHits: CASCADE_NEIGHBOUR_BUDGET,
958
+ });
959
+ const added = [
960
+ ...new Set(transitive.hits
961
+ .map((hit) => hit.file)
962
+ .filter((file) => file && normalizeMapKey(file) !== normalizedFileKey)),
963
+ ].filter((file) => !impact.neighborFiles.includes(file));
964
+ if (added.length > 0) {
965
+ impact.neighborFiles = [...impact.neighborFiles, ...added];
966
+ logCascade({
967
+ phase: "neighbor_snapshot",
968
+ filePath,
969
+ neighborFile: "[transitive-impact]",
970
+ diagnosticCount: added.length,
971
+ autoPropagate: false,
972
+ metadata: {
973
+ transitive: true,
974
+ maxDepth: CASCADE_TRANSITIVE_DEPTH,
975
+ maxDepthReached: transitive.maxDepthReached,
976
+ truncated: transitive.truncated,
977
+ },
978
+ });
979
+ }
980
+ }
981
+ // #1080: exclude KNOWN test-role files from every collateral impact
982
+ // surface — the formatted header (formatImpactCascade reads `impact`
983
+ // directly for `Direct importers`/`Direct callers`/`Check next` counts and
984
+ // names), the active-touch/passive-snapshot neighbor set (sortedNeighbors is
985
+ // derived from `impact.neighborFiles` below), and the returned `impact`
986
+ // object. Applied HERE — after graph neighbors, reverse-deps, LSP reference
987
+ // expansion, and transitive expansion have all been merged in — so it covers
988
+ // every neighbor source (incl. module-level downstream files that entered via
989
+ // computeImpactCascade and reference URIs pointing at `*.test.*`). Filtering
990
+ // upstream of `sortedNeighbors` also means a test URI is never actively
991
+ // touched solely for cascade diagnostics. Composes the shared `detectFileRole`
992
+ // seam; a classifier failure RETAINS the candidate (honest — never a false
993
+ // clean). The project ignore filter below is separate and unchanged (#297).
994
+ impact.directImporters = impact.directImporters.filter((f) => !isTestRoleCollateral(f));
995
+ impact.directCallers = impact.directCallers.filter((f) => !isTestRoleCollateral(f));
996
+ impact.neighborFiles = impact.neighborFiles.filter((f) => !isTestRoleCollateral(f));
997
+ // Sort by relationship strength (B6) then cap to the neighbour budget.
998
+ // directImporters are most impactful, then callers, then reference edges.
999
+ importerSet = new Set(impact.directImporters);
1000
+ callerSet = new Set(impact.directCallers);
1001
+ // neighbors that are neither direct importers nor callers are reference-edge neighbors
1002
+ const importerOrCallerSet = new Set([
1003
+ ...impact.directImporters,
1004
+ ...impact.directCallers,
1005
+ ]);
1006
+ referenceCount = impact.neighborFiles.filter((n) => !importerOrCallerSet.has(n)).length;
1007
+ sortedNeighbors = [...impact.neighborFiles]
1008
+ .filter((n) => nodeFs.existsSync(n))
1009
+ .filter((n) => !isExternalOrVendorFile(n, cwd))
1010
+ // Honour the project's ignore config: a user-ignored neighbour (e.g.
1011
+ // `**/*.test.ts`) must not surface as collateral cascade noise (#297).
1012
+ .filter((n) => !isIgnoredCascadeNeighbor(n, cwd))
1013
+ // B10: exclude files already edited as primary this turn — their own pipeline
1014
+ // run is the authoritative diagnostic source; showing them as neighbors is noise.
1015
+ .filter((n) => !primaryFilesThisTurn.has(normalizeMapKey(n)))
1016
+ .sort((a, b) => {
1017
+ const rank = (p) => importerSet.has(p) ? 0 : callerSet.has(p) ? 1 : 2;
1018
+ return rank(a) - rank(b);
1019
+ })
1020
+ .slice(0, CASCADE_NEIGHBOUR_BUDGET);
1021
+ }
1022
+ else {
834
1023
  logCascade({
835
- phase: "neighbor_snapshot",
1024
+ phase: "cascade_skip",
836
1025
  filePath,
837
- neighborFile: neighborPath,
838
- diagnosticCount: diags.length,
839
- durationMs,
840
- autoPropagate: true,
841
- snapshotMissing: false,
842
- snapshotAgeSec,
843
- });
844
- neighbors.push({
845
- filePath: neighborPath,
846
- reason: neighborReason(importerSet, callerSet, neighborPath),
847
- diagnostics: diags,
848
- lspTouched: false,
849
- durationMs,
1026
+ reason: "unsupported_graph_kind",
1027
+ metadata: { fileKind },
850
1028
  });
1029
+ return {
1030
+ filePath,
1031
+ result: undefined,
1032
+ neighborCount: 0,
1033
+ diagnosticCount: 0,
1034
+ skipReason: "non_code",
1035
+ };
851
1036
  }
852
- // fan-out active touches in parallel (A3):
853
- // - non-jsts neighbors (always touched)
854
- // - autoPropagate neighbors whose snapshot was missing/stale (coldSnapshotPaths)
855
- // use a tighter 1000ms budget since the server is expected to be warm already.
856
- const touchResults = await Promise.allSettled([...activePaths, ...coldSnapshotPaths].map(async (neighborPath) => {
857
- const isColdSnapshot = coldSnapshotPaths.includes(neighborPath);
858
- const neighborStart = Date.now();
859
- const cacheKey = normalizeMapKey(neighborPath);
860
- const passiveEntry = allDiags.get(cacheKey);
861
- const hasFreshPassiveErrors = passiveEntry != null &&
862
- Date.now() - passiveEntry.ts < CASCADE_TTL_MS &&
863
- passiveEntry.diags.some((d) => d.severity === 1);
864
- const recentlyClean = recentlyCleanNeighborCache.get(cacheKey);
865
- if (recentlyClean &&
866
- turnSeq - recentlyClean.turnSeq <= RECENTLY_CLEAN_TTL_TURNS &&
867
- !hasFreshPassiveErrors) {
1037
+ logCascade({
1038
+ phase: "neighbors_computed",
1039
+ filePath,
1040
+ neighborCount: sortedNeighbors.length,
1041
+ totalNeighborCount: impact.neighborFiles.length,
1042
+ importerCount: impact.directImporters.length,
1043
+ callerCount: impact.directCallers.length,
1044
+ referenceCount: Math.max(0, referenceCount),
1045
+ riskFlags: impact.riskFlags,
1046
+ metadata: { neighbors: sortedNeighbors.slice(0, 10) },
1047
+ });
1048
+ const lspService = getLSPService();
1049
+ // Hoist passive snapshot once — used for auto-propagating LSPs and fallback path.
1050
+ // #1095 memo-freeze caveat: each getAllDiagnostics() result attaches `.binding`
1051
+ // as a LAZY getter that memoizes its disk verdict PER RESULT OBJECT. This cascade
1052
+ // re-calls getAllDiagnostics() every run and never retains the Map across turns,
1053
+ // so every run reads a FRESH verdict against current disk. If cross-turn retention
1054
+ // of this Map is ever introduced, the memoized binding would freeze stale — re-read
1055
+ // a fresh getAllDiagnostics() result at binding-read time instead of caching it.
1056
+ const allDiags = await lspService.getAllDiagnostics();
1057
+ const neighbors = [];
1058
+ let producedLspData = false;
1059
+ let coldSnapshotPaths = [];
1060
+ // #1104: did any DEGRADED-fallback display path (touch-error fallback,
1061
+ // appendFallbackNeighbors) withhold a TTL-fresh entry solely because its
1062
+ // content binding was rejected (`boundToCurrentDisk === false` — computed
1063
+ // against a diverged/pre-fix-edit disk state)? Tracked separately from
1064
+ // `producedLspData` so the HONESTY check below can tell "genuinely nothing to
1065
+ // show" apart from "something existed but was untrustworthy and was hidden" —
1066
+ // the latter must not collapse into a clean-looking result (#1104 honesty
1067
+ // rule, same doctrine as #1023's graph-degraded indeterminate marker).
1068
+ let fallbackBindingRejected = false;
1069
+ if (sortedNeighbors.length > 0) {
1070
+ const snapshotPaths = sortedNeighbors.filter(shouldReadCascadeFromSnapshot);
1071
+ const activePaths = sortedNeighbors.filter((n) => !shouldReadCascadeFromSnapshot(n));
1072
+ // Auto-propagating LSPs (TypeScript/Deno) — read passive snapshot with normalized key.
1073
+ // When the snapshot is valid, use it immediately (no touch needed — server already has
1074
+ // fresh data from auto-propagation). When missing or stale, fall through to the active
1075
+ // touch pool below so we get real diagnostics instead of silently returning zero.
1076
+ coldSnapshotPaths = [];
1077
+ for (const neighborPath of snapshotPaths) {
1078
+ const neighborStart = Date.now();
1079
+ const entry = allDiags.get(normalizeMapKey(neighborPath));
1080
+ const snapshotAgeSec = entry
1081
+ ? Math.round((Date.now() - entry.ts) / 1000)
1082
+ : undefined;
1083
+ const ttlFresh = entry != null && Date.now() - entry.ts < CASCADE_TTL_MS;
1084
+ // #1095: content binding is the INNER gate; TTL stays the outer bound.
1085
+ // false → the server's diagnostics were computed against a DIFFERENT
1086
+ // disk state (e.g. the PRE-fix content) — don't trust or
1087
+ // reconcile this snapshot; fall through to an active touch on
1088
+ // the same (cold-snapshot) budget as a TTL-stale entry. This
1089
+ // kills the window where the first cascade after a fix-edit
1090
+ // replays the neighbor's pre-fix snapshot.
1091
+ // "unknown" → version-less/unreadable: keep EXACTLY the pre-#1095 TTL-only
1092
+ // behavior (reconcile if TTL-fresh).
1093
+ // true → bound to current disk: reconcile (TTL still the outer bound).
1094
+ // Reading `.binding` triggers the lazy disk verify on the getAllDiagnostics
1095
+ // result — done ONLY when TTL-fresh so a doomed (stale) entry never pays the
1096
+ // stat+hash.
1097
+ const boundToDisk = ttlFresh
1098
+ ? readBoundToCurrentDisk(entry)
1099
+ : undefined;
1100
+ const bindingRejected = boundToDisk === false;
1101
+ const snapshotValid = ttlFresh && !bindingRejected;
1102
+ if (!snapshotValid) {
1103
+ // No usable snapshot — queue for active touch alongside non-jsts neighbors.
1104
+ logCascade({
1105
+ phase: "neighbor_snapshot",
1106
+ filePath,
1107
+ neighborFile: neighborPath,
1108
+ diagnosticCount: 0,
1109
+ durationMs: Date.now() - neighborStart,
1110
+ autoPropagate: true,
1111
+ snapshotMissing: entry == null,
1112
+ snapshotAgeSec,
1113
+ coldSnapshot: true,
1114
+ // #1095: distinguish a binding-rejected fall-through (TTL-fresh but the
1115
+ // server's view diverged from disk) from a plain TTL-stale/missing one.
1116
+ ...(bindingRejected && {
1117
+ metadata: { bindingState: bindingStateLabel(boundToDisk) },
1118
+ }),
1119
+ });
1120
+ coldSnapshotPaths.push(neighborPath);
1121
+ continue;
1122
+ }
1123
+ // #692: `source: "cascade"` used to be passed here to label `rule`
1124
+ // (`cascade:<code>`) — that override is gone (identity must come from
1125
+ // the diagnostic's own source; see `scanOrigin`'s doc comment), and
1126
+ // cascade neighbor diagnostics are ephemeral display-only output
1127
+ // (never reconciled into persisted widget/dedup state), so the label
1128
+ // had no remaining purpose and is simply dropped rather than migrated.
1129
+ const diags = convertLspDiagnostics(entry.diags.filter((d) => d.severity === 1).slice(0, MAX_PER_FILE), neighborPath);
868
1130
  producedLspData = true;
869
1131
  const durationMs = Date.now() - neighborStart;
870
1132
  logCascade({
871
1133
  phase: "neighbor_snapshot",
872
1134
  filePath,
873
1135
  neighborFile: neighborPath,
874
- diagnosticCount: 0,
1136
+ diagnosticCount: diags.length,
875
1137
  durationMs,
876
- autoPropagate: false,
1138
+ autoPropagate: true,
877
1139
  snapshotMissing: false,
878
- metadata: {
879
- recentlyClean: true,
880
- cleanTurnSeq: recentlyClean.turnSeq,
881
- },
1140
+ snapshotAgeSec,
882
1141
  });
883
- return {
1142
+ // #1093: a valid passive snapshot IS a confirmed observation of this
1143
+ // neighbor's current LSP-error state (#571 semantics) — reconcile it into
1144
+ // the footer widget, INCLUDING the confirmed-clean `[]` case, so a
1145
+ // fix-edit to the primary that resolves a cross-file error in this
1146
+ // neighbor clears the neighbor's now-stale footer entry (the #1092
1147
+ // defect). MERGE (genuine LSP errors only — auxiliary findings excluded,
1148
+ // see `cascadeReconcilableLspErrors`) so a live biome/ruff/aux finding or
1149
+ // LSP warning on the neighbor is preserved. Keyed by the primary edit's
1150
+ // `writeSeq` so a genuinely newer per-edit write still wins the
1151
+ // WriteOrderingGuard. `observedAt = entry.ts` (the snapshot's own publish
1152
+ // time, up to CASCADE_TTL_MS old) — NOT now() — so replaying an aging
1153
+ // snapshot never re-arms the mtime-staleness gate (the same #1092
1154
+ // re-arming defect this PR fixes for cache hits).
1155
+ //
1156
+ // #1186: `observedAt` here stamps only the INCOMING LSP-error entries.
1157
+ // PRESERVED entries keep their own (possibly fresher) per-entry
1158
+ // `observedAt`, and `reconcileStaleWidgetFiles` now gates per ENTRY — so
1159
+ // if the neighbor's mtime later falls between this `entry.ts` and a
1160
+ // preserved entry's real observation time, only the stale incoming entry
1161
+ // drops and the fresher preserved finding survives (previously the whole
1162
+ // record was over-cleared; that residual is now fixed).
1163
+ reconcileCascadeNeighborLspErrors(neighborPath, cascadeReconcilableLspErrors(entry.diags, neighborPath), writeSeq, entry.ts);
1164
+ neighbors.push({
884
1165
  filePath: neighborPath,
885
1166
  reason: neighborReason(importerSet, callerSet, neighborPath),
886
- diagnostics: [],
1167
+ diagnostics: diags,
887
1168
  lspTouched: false,
888
1169
  durationMs,
889
- };
1170
+ });
890
1171
  }
891
- // A5: skip re-touch if this neighbor was already diagnosed at the current
892
- // write sequence. A new write (higher writeSeq) invalidates the cache entry.
893
- const cached = writeSeq != null ? neighborTouchCache.get(cacheKey) : undefined;
894
- if (cached?.turnSeq === turnSeq && cached?.writeSeq === writeSeq) {
895
- producedLspData = true;
1172
+ // fan-out active touches in parallel (A3):
1173
+ // - non-jsts neighbors (always touched)
1174
+ // - autoPropagate neighbors whose snapshot was missing/stale (coldSnapshotPaths)
1175
+ // use a tighter 1000ms budget since the server is expected to be warm already.
1176
+ const touchResults = await Promise.allSettled([...activePaths, ...coldSnapshotPaths].map(async (neighborPath) => {
1177
+ const isColdSnapshot = coldSnapshotPaths.includes(neighborPath);
1178
+ const neighborStart = Date.now();
1179
+ const cacheKey = normalizeMapKey(neighborPath);
1180
+ const passiveEntry = allDiags.get(cacheKey);
1181
+ const hasFreshPassiveErrors = passiveEntry != null &&
1182
+ Date.now() - passiveEntry.ts < CASCADE_TTL_MS &&
1183
+ passiveEntry.diags.some((d) => d.severity === 1);
1184
+ const recentlyClean = recentlyCleanNeighborCache.get(cacheKey);
1185
+ if (recentlyClean &&
1186
+ turnSeq - recentlyClean.turnSeq <= RECENTLY_CLEAN_TTL_TURNS &&
1187
+ !hasFreshPassiveErrors) {
1188
+ producedLspData = true;
1189
+ const durationMs = Date.now() - neighborStart;
1190
+ logCascade({
1191
+ phase: "neighbor_snapshot",
1192
+ filePath,
1193
+ neighborFile: neighborPath,
1194
+ diagnosticCount: 0,
1195
+ durationMs,
1196
+ autoPropagate: false,
1197
+ snapshotMissing: false,
1198
+ metadata: {
1199
+ recentlyClean: true,
1200
+ cleanTurnSeq: recentlyClean.turnSeq,
1201
+ },
1202
+ });
1203
+ return {
1204
+ filePath: neighborPath,
1205
+ reason: neighborReason(importerSet, callerSet, neighborPath),
1206
+ diagnostics: [],
1207
+ lspTouched: false,
1208
+ durationMs,
1209
+ };
1210
+ }
1211
+ // A5: skip re-touch if this neighbor was already diagnosed at the current
1212
+ // write sequence. A new write (higher writeSeq) invalidates the cache entry.
1213
+ const cached = writeSeq != null ? neighborTouchCache.get(cacheKey) : undefined;
1214
+ if (cached?.turnSeq === turnSeq && cached?.writeSeq === writeSeq) {
1215
+ producedLspData = true;
1216
+ const durationMs = Date.now() - neighborStart;
1217
+ logCascade({
1218
+ phase: "neighbor_snapshot",
1219
+ filePath,
1220
+ neighborFile: neighborPath,
1221
+ diagnosticCount: cached.diagnostics.length,
1222
+ durationMs,
1223
+ autoPropagate: false,
1224
+ snapshotMissing: false,
1225
+ metadata: { cachedWriteSeq: writeSeq },
1226
+ });
1227
+ return {
1228
+ filePath: neighborPath,
1229
+ reason: neighborReason(importerSet, callerSet, neighborPath),
1230
+ diagnostics: cached.diagnostics,
1231
+ lspTouched: false,
1232
+ durationMs,
1233
+ };
1234
+ }
1235
+ const configuredServerCount = getServersForFileWithConfig(neighborPath).length;
1236
+ if (configuredServerCount === 0) {
1237
+ logCascade({
1238
+ phase: "neighbor_fallback",
1239
+ filePath,
1240
+ neighborFile: neighborPath,
1241
+ fallbackUsed: false,
1242
+ error: "no_lsp_server_configured",
1243
+ });
1244
+ return undefined;
1245
+ }
1246
+ // A6: async read to avoid blocking event loop on network-mounted drives
1247
+ const content = await nodeFs.promises.readFile(neighborPath, "utf8");
1248
+ // #458: tier-aware cascade-lane wait. A Tier-3 (push-only,
1249
+ // silent-on-clean — typescript is the lone core-set instance today)
1250
+ // primary can never give this in-lane wait an affirmative clean
1251
+ // signal, so the budget is pure cost. Fire the touch (didOpen/
1252
+ // didChange still happens — the server starts real work) and record
1253
+ // it as outstanding for the agent_settled quiet window to reconcile
1254
+ // instead of waiting here. Ambiguous/missing capability data always
1255
+ // classifies as "waits" (today's behavior) — see cascade-tier.ts.
1256
+ // The whole attempt is try/caught: any surprise (a service shape
1257
+ // that doesn't expose getCapabilitySnapshots/getClientForFile, a
1258
+ // thrown rejection) falls through to the existing full-wait path
1259
+ // below rather than skip the wait on a failure.
1260
+ if (isTierAwareCascadeEnabled()) {
1261
+ try {
1262
+ const snapshots = (await lspService.getCapabilitySnapshots?.(neighborPath)) ?? [];
1263
+ const tier = classifyCascadeWaitTier(lspService, neighborPath, snapshots);
1264
+ if (tier === "tier3-silent") {
1265
+ const spawnedForTouch = await lspService.getClientForFile(neighborPath);
1266
+ if (spawnedForTouch) {
1267
+ // Sampled BEFORE the touchFile notify: a publish landing
1268
+ // in the notify→record gap must read as post-touch at
1269
+ // reconcile time, never be misclassified as pre-touch
1270
+ // (the reconcile compares this against the client's
1271
+ // PER-FILE publish timestamp — see cascade-tier.ts).
1272
+ const touchedAt = Date.now();
1273
+ await lspService.touchFile(neighborPath, content, {
1274
+ diagnostics: "none",
1275
+ collectDiagnostics: false,
1276
+ silent: true,
1277
+ source: "cascade",
1278
+ clientScope: "primary",
1279
+ });
1280
+ recordOutstandingCascadeTouch({
1281
+ filePath: neighborPath,
1282
+ serverId: spawnedForTouch.client.serverId,
1283
+ touchedAt,
1284
+ });
1285
+ const durationMs = Date.now() - neighborStart;
1286
+ logCascade({
1287
+ phase: "cascade_tier3_skip",
1288
+ filePath,
1289
+ neighborFile: neighborPath,
1290
+ durationMs,
1291
+ lspServerCount: configuredServerCount,
1292
+ coldSnapshot: isColdSnapshot,
1293
+ metadata: { serverId: spawnedForTouch.client.serverId },
1294
+ });
1295
+ // Deliberately NOT cached as clean/diagnosed — the wait was
1296
+ // skipped, not resolved, so neither neighborTouchCache nor
1297
+ // recentlyCleanNeighborCache may treat this as a real answer
1298
+ // (#240 doctrine). Return undefined: the degraded-fallback
1299
+ // path below still has a chance to surface a passive/stale
1300
+ // snapshot, same as any other "no fresh data this touch" case.
1301
+ return undefined;
1302
+ }
1303
+ }
1304
+ }
1305
+ catch (tierErr) {
1306
+ dbg?.(`cascade tier-aware skip attempt failed for ${neighborPath}, falling back to full wait: ${tierErr}`);
1307
+ }
1308
+ }
1309
+ // Open with silent=true (suppresses didChangeWatchedFiles rechecks, C2)
1310
+ // and collect diagnostics from the same touched clients.
1311
+ // Cold-snapshot neighbors (autoPropagate LSP, server warm) use a tighter
1312
+ // 1000ms budget — they should respond quickly; we'd rather return zero
1313
+ // than block cascade for 2s on a slow open.
1314
+ const rawDiags = await lspService.touchFile(neighborPath, content, {
1315
+ diagnostics: "document",
1316
+ collectDiagnostics: true,
1317
+ maxClientWaitMs: isColdSnapshot ? 1000 : 2000,
1318
+ silent: true,
1319
+ source: "cascade",
1320
+ clientScope: "all",
1321
+ });
1322
+ if (!rawDiags)
1323
+ return undefined;
1324
+ // #1093/#571/#1095: a touch result is only a CONFIRMED observation of the
1325
+ // neighbor's current on-disk state when it is neither `inconclusive` (the
1326
+ // notify/diagnostics wait lapsed — e.g. the tight 1000ms cold-snapshot
1327
+ // budget on a slow server) NOR bound-false (`binding.boundToCurrentDisk
1328
+ // === false` — the diagnostics were computed against a different disk state
1329
+ // than what's on disk now). Either disqualifier means a resolved `[]` is
1330
+ // NOT a confirmed clean: treating it as one would WIPE a live footer finding
1331
+ // (the #533 false-clean trap, worse than the stale-display bug). Both flags
1332
+ // are folded into `isConfirmedTouch` so no gate below can miss one. A
1333
+ // confirmed result reconciles and may seed the recently-clean cache; an
1334
+ // unconfirmed one does neither (else the short-circuit on the next cascade
1335
+ // would make the wipe self-sustain).
1336
+ const confirmed = isConfirmedTouch(rawDiags);
1337
+ const bindingRejected = readBoundToCurrentDisk(rawDiags) === false;
1338
+ const inconclusive = readInconclusive(rawDiags);
1339
+ // #692: `source: "cascade"` no longer overrides `rule` (see the
1340
+ // doc comment on the sibling call above) — dropped rather than
1341
+ // migrated to `scanOrigin` since cascade output never touches
1342
+ // persisted widget/dedup state.
1343
+ // #1179: `.filter()` here operates on `rawDiags.diags`; the
1344
+ // `inconclusive`/`binding` flags read above stay on the `rawDiags`
1345
+ // wrapper and are unaffected by this copy (the shape-5 fix).
1346
+ const diags = convertLspDiagnostics(rawDiags.diags.filter((d) => d.severity === 1).slice(0, MAX_PER_FILE), neighborPath);
896
1347
  const durationMs = Date.now() - neighborStart;
1348
+ // Update cache for this neighbor at the current write sequence
1349
+ if (writeSeq != null) {
1350
+ neighborTouchCache.set(cacheKey, {
1351
+ turnSeq,
1352
+ writeSeq,
1353
+ diagnostics: diags,
1354
+ });
1355
+ }
1356
+ if (diags.length === 0) {
1357
+ // Only a CONFIRMED clean touch may seed the recently-clean cache
1358
+ // (#1095: a bound-false touch is unconfirmed, exactly like inconclusive).
1359
+ if (confirmed) {
1360
+ recentlyCleanNeighborCache.set(cacheKey, {
1361
+ turnSeq,
1362
+ checkedAt: Date.now(),
1363
+ });
1364
+ }
1365
+ }
1366
+ else {
1367
+ recentlyCleanNeighborCache.delete(cacheKey);
1368
+ }
1369
+ producedLspData = true;
897
1370
  logCascade({
898
- phase: "neighbor_snapshot",
1371
+ phase: "neighbor_touch",
899
1372
  filePath,
900
1373
  neighborFile: neighborPath,
901
- diagnosticCount: cached.diagnostics.length,
1374
+ diagnosticCount: diags.length,
902
1375
  durationMs,
903
- autoPropagate: false,
904
- snapshotMissing: false,
905
- metadata: { cachedWriteSeq: writeSeq },
1376
+ lspTouched: true,
1377
+ lspServerCount: configuredServerCount,
1378
+ coldSnapshot: isColdSnapshot,
1379
+ // #1104: an unconfirmed touch has two independent, otherwise
1380
+ // indistinguishable causes — `inconclusive` (the notify/diagnostics
1381
+ // wait lapsed its deadline) and bound-false (`bindingState`, #1095 —
1382
+ // diagnostics computed against a diverged disk state). Surface
1383
+ // `inconclusive` unconditionally so cascade.log alone (no
1384
+ // cross-referencing latency.log) tells them apart; `bindingState`
1385
+ // stays conditional since "bound" carries no extra signal.
1386
+ metadata: {
1387
+ inconclusive,
1388
+ ...(bindingRejected && { bindingState: bindingStateLabel(false) }),
1389
+ },
906
1390
  });
1391
+ // #1093/#1095: a completed, CONFIRMED active touch is a confirmed
1392
+ // observation of this neighbor's current LSP-error state (#571) —
1393
+ // reconcile it into the footer widget, INCLUDING the confirmed-clean `[]`
1394
+ // case, so a fix-edit to the primary that resolves a cross-file error in
1395
+ // this neighbor clears the neighbor's now-stale footer entry (the #1092
1396
+ // defect). MERGE (genuine LSP errors only — auxiliary findings excluded,
1397
+ // see `cascadeReconcilableLspErrors`) so a live biome/ruff/aux finding or
1398
+ // LSP warning survives this errors-only re-check. Keyed by the primary
1399
+ // edit's `writeSeq` so a genuinely newer per-edit write still wins the
1400
+ // WriteOrderingGuard. `observedAt` stays now (a fresh touch). The
1401
+ // inconclusive touch, the BOUND-FALSE touch (#1095 — computed against a
1402
+ // diverged disk state), the tier-3-silent skip, the recently-clean
1403
+ // short-circuit, the within-turn cache hit, and the rejected-touch
1404
+ // fallback are all deliberately NOT reconciled — none is a confirmed
1405
+ // observation.
1406
+ if (confirmed) {
1407
+ reconcileCascadeNeighborLspErrors(neighborPath, cascadeReconcilableLspErrors(rawDiags.diags, neighborPath), writeSeq);
1408
+ }
907
1409
  return {
908
1410
  filePath: neighborPath,
909
1411
  reason: neighborReason(importerSet, callerSet, neighborPath),
910
- diagnostics: cached.diagnostics,
911
- lspTouched: false,
1412
+ diagnostics: diags,
1413
+ lspTouched: true,
912
1414
  durationMs,
913
1415
  };
914
- }
915
- const configuredServerCount = getServersForFileWithConfig(neighborPath).length;
916
- if (configuredServerCount === 0) {
917
- logCascade({
918
- phase: "neighbor_fallback",
919
- filePath,
920
- neighborFile: neighborPath,
921
- fallbackUsed: false,
922
- error: "no_lsp_server_configured",
923
- });
924
- return undefined;
925
- }
926
- // A6: async read to avoid blocking event loop on network-mounted drives
927
- const content = await nodeFs.promises.readFile(neighborPath, "utf8");
928
- // #458: tier-aware cascade-lane wait. A Tier-3 (push-only,
929
- // silent-on-clean — typescript is the lone core-set instance today)
930
- // primary can never give this in-lane wait an affirmative clean
931
- // signal, so the budget is pure cost. Fire the touch (didOpen/
932
- // didChange still happens — the server starts real work) and record
933
- // it as outstanding for the agent_settled quiet window to reconcile
934
- // instead of waiting here. Ambiguous/missing capability data always
935
- // classifies as "waits" (today's behavior) — see cascade-tier.ts.
936
- // The whole attempt is try/caught: any surprise (a service shape
937
- // that doesn't expose getCapabilitySnapshots/getClientForFile, a
938
- // thrown rejection) falls through to the existing full-wait path
939
- // below rather than skip the wait on a failure.
940
- if (isTierAwareCascadeEnabled()) {
941
- try {
942
- const snapshots = (await lspService.getCapabilitySnapshots?.(neighborPath)) ?? [];
943
- const tier = classifyCascadeWaitTier(lspService, neighborPath, snapshots);
944
- if (tier === "tier3-silent") {
945
- const spawnedForTouch = await lspService.getClientForFile(neighborPath);
946
- if (spawnedForTouch) {
947
- // Sampled BEFORE the touchFile notify: a publish landing
948
- // in the notify→record gap must read as post-touch at
949
- // reconcile time, never be misclassified as pre-touch
950
- // (the reconcile compares this against the client's
951
- // PER-FILE publish timestamp — see cascade-tier.ts).
952
- const touchedAt = Date.now();
953
- await lspService.touchFile(neighborPath, content, {
954
- diagnostics: "none",
955
- collectDiagnostics: false,
956
- silent: true,
957
- source: "cascade",
958
- clientScope: "primary",
959
- });
960
- recordOutstandingCascadeTouch({
961
- filePath: neighborPath,
962
- serverId: spawnedForTouch.client.serverId,
963
- touchedAt,
964
- });
965
- const durationMs = Date.now() - neighborStart;
966
- logCascade({
967
- phase: "cascade_tier3_skip",
968
- filePath,
969
- neighborFile: neighborPath,
970
- durationMs,
971
- lspServerCount: configuredServerCount,
972
- coldSnapshot: isColdSnapshot,
973
- metadata: { serverId: spawnedForTouch.client.serverId },
974
- });
975
- // Deliberately NOT cached as clean/diagnosed — the wait was
976
- // skipped, not resolved, so neither neighborTouchCache nor
977
- // recentlyCleanNeighborCache may treat this as a real answer
978
- // (#240 doctrine). Return undefined: the degraded-fallback
979
- // path below still has a chance to surface a passive/stale
980
- // snapshot, same as any other "no fresh data this touch" case.
981
- return undefined;
982
- }
983
- }
1416
+ }));
1417
+ const allTouchPaths = [...activePaths, ...coldSnapshotPaths];
1418
+ for (let i = 0; i < touchResults.length; i++) {
1419
+ const result = touchResults[i];
1420
+ const neighborPath = allTouchPaths[i];
1421
+ if (result.status === "fulfilled") {
1422
+ if (result.value)
1423
+ neighbors.push(result.value);
984
1424
  }
985
- catch (tierErr) {
986
- dbg?.(`cascade tier-aware skip attempt failed for ${neighborPath}, falling back to full wait: ${tierErr}`);
1425
+ else {
1426
+ // A3: one failed LSP doesn't kill the rest — fall back to passive snapshot
1427
+ dbg?.(`cascade neighbor touch error for ${neighborPath}: ${result.reason}`);
1428
+ const entry = allDiags.get(normalizeMapKey(neighborPath));
1429
+ const ttlFresh = entry != null && Date.now() - entry.ts < CASCADE_TTL_MS;
1430
+ // #1104: consult binding before trusting a TTL-fresh fallback snapshot —
1431
+ // MATCH #1100/#1095 semantics (false → skip, "unknown" → keep the
1432
+ // pre-#1104 TTL-only behavior, true → use). Without this, a failed
1433
+ // active touch could still re-display a bound-false (pre-fix-edit)
1434
+ // snapshot even though the reconcile path (#1100) already refuses to
1435
+ // trust it for the widget — the widget is protected but the display
1436
+ // wasn't. Reading `.binding` triggers the lazy disk verify — done ONLY
1437
+ // when TTL-fresh, same discipline as the snapshot-tier gate above.
1438
+ const boundToDisk = ttlFresh
1439
+ ? readBoundToCurrentDisk(entry)
1440
+ : undefined;
1441
+ const bindingRejected = boundToDisk === false;
1442
+ if (bindingRejected)
1443
+ fallbackBindingRejected = true;
1444
+ logCascade({
1445
+ phase: "neighbor_fallback",
1446
+ filePath,
1447
+ neighborFile: neighborPath,
1448
+ fallbackUsed: true,
1449
+ error: String(result.reason),
1450
+ // #1104: distinguish a binding-rejected fallback (TTL-fresh but the
1451
+ // server's view diverged from disk) from a plain TTL-stale/missing
1452
+ // one — same conditional pattern as the neighbor_touch/neighbor_snapshot
1453
+ // phases above.
1454
+ ...(bindingRejected && {
1455
+ metadata: { bindingState: bindingStateLabel(boundToDisk) },
1456
+ }),
1457
+ });
1458
+ // #692: `source: "cascade"` dropped (see the doc comment above the
1459
+ // first cascade call site in this file) — no longer affects `rule`
1460
+ // and cascade output never touches persisted widget/dedup state.
1461
+ const diags = ttlFresh && !bindingRejected
1462
+ ? convertLspDiagnostics(entry.diags
1463
+ .filter((d) => d.severity === 1)
1464
+ .slice(0, MAX_PER_FILE), neighborPath)
1465
+ : [];
1466
+ neighbors.push({
1467
+ filePath: neighborPath,
1468
+ reason: "fallback",
1469
+ diagnostics: diags,
1470
+ lspTouched: false,
1471
+ });
987
1472
  }
988
1473
  }
989
- // Open with silent=true (suppresses didChangeWatchedFiles rechecks, C2)
990
- // and collect diagnostics from the same touched clients.
991
- // Cold-snapshot neighbors (autoPropagate LSP, server warm) use a tighter
992
- // 1000ms budget — they should respond quickly; we'd rather return zero
993
- // than block cascade for 2s on a slow open.
994
- const rawDiags = await lspService.touchFile(neighborPath, content, {
995
- diagnostics: "document",
996
- collectDiagnostics: true,
997
- maxClientWaitMs: isColdSnapshot ? 1000 : 2000,
998
- silent: true,
999
- source: "cascade",
1000
- clientScope: "all",
1001
- });
1002
- if (!rawDiags)
1003
- return undefined;
1004
- // #692: `source: "cascade"` no longer overrides `rule` (see the
1005
- // doc comment on the sibling call above) — dropped rather than
1006
- // migrated to `scanOrigin` since cascade output never touches
1007
- // persisted widget/dedup state.
1008
- const diags = convertLspDiagnostics(rawDiags.filter((d) => d.severity === 1).slice(0, MAX_PER_FILE), neighborPath);
1009
- const durationMs = Date.now() - neighborStart;
1010
- // Update cache for this neighbor at the current write sequence
1011
- if (writeSeq != null) {
1012
- neighborTouchCache.set(cacheKey, {
1013
- turnSeq,
1014
- writeSeq,
1015
- diagnostics: diags,
1016
- });
1017
- }
1018
- if (diags.length === 0) {
1019
- recentlyCleanNeighborCache.set(cacheKey, {
1020
- turnSeq,
1021
- checkedAt: Date.now(),
1022
- });
1023
- }
1024
- else {
1025
- recentlyCleanNeighborCache.delete(cacheKey);
1026
- }
1027
- producedLspData = true;
1028
- logCascade({
1029
- phase: "neighbor_touch",
1030
- filePath,
1031
- neighborFile: neighborPath,
1032
- diagnosticCount: diags.length,
1033
- durationMs,
1034
- lspTouched: true,
1035
- lspServerCount: configuredServerCount,
1036
- coldSnapshot: isColdSnapshot,
1037
- });
1038
- return {
1039
- filePath: neighborPath,
1040
- reason: neighborReason(importerSet, callerSet, neighborPath),
1041
- diagnostics: diags,
1042
- lspTouched: true,
1043
- durationMs,
1044
- };
1045
- }));
1046
- const allTouchPaths = [...activePaths, ...coldSnapshotPaths];
1047
- for (let i = 0; i < touchResults.length; i++) {
1048
- const result = touchResults[i];
1049
- const neighborPath = allTouchPaths[i];
1050
- if (result.status === "fulfilled") {
1051
- if (result.value)
1052
- neighbors.push(result.value);
1053
- }
1054
- else {
1055
- // A3: one failed LSP doesn't kill the rest — fall back to passive snapshot
1056
- dbg?.(`cascade neighbor touch error for ${neighborPath}: ${result.reason}`);
1474
+ }
1475
+ // CR-3/A2: degraded fallback when no neighbor produced trustworthy LSP data —
1476
+ // not merely when the graph returned zero neighbors.
1477
+ if (!producedLspData) {
1478
+ const bindingRejected = appendFallbackNeighbors(neighbors, allDiags, normalizedFileKey, cwd, filePath);
1479
+ if (bindingRejected)
1480
+ fallbackBindingRejected = true;
1481
+ if (neighbors.some((n) => n.reason === "fallback")) {
1057
1482
  logCascade({
1058
1483
  phase: "neighbor_fallback",
1059
1484
  filePath,
1060
- neighborFile: neighborPath,
1061
1485
  fallbackUsed: true,
1062
- error: String(result.reason),
1063
- });
1064
- const entry = allDiags.get(normalizeMapKey(neighborPath));
1065
- // #692: `source: "cascade"` dropped (see the doc comment above the
1066
- // first cascade call site in this file) — no longer affects `rule`
1067
- // and cascade output never touches persisted widget/dedup state.
1068
- const diags = entry && Date.now() - entry.ts < CASCADE_TTL_MS
1069
- ? convertLspDiagnostics(entry.diags
1070
- .filter((d) => d.severity === 1)
1071
- .slice(0, MAX_PER_FILE), neighborPath)
1072
- : [];
1073
- neighbors.push({
1074
- filePath: neighborPath,
1075
- reason: "fallback",
1076
- diagnostics: diags,
1077
- lspTouched: false,
1486
+ neighborCount: neighbors.length,
1078
1487
  });
1079
1488
  }
1080
1489
  }
1081
- }
1082
- // CR-3/A2: degraded fallback when no neighbor produced trustworthy LSP data —
1083
- // not merely when the graph returned zero neighbors.
1084
- if (!producedLspData) {
1085
- appendFallbackNeighbors(neighbors, allDiags, normalizedFileKey, cwd);
1086
- if (neighbors.some((n) => n.reason === "fallback")) {
1087
- logCascade({
1088
- phase: "neighbor_fallback",
1490
+ const visibleNeighbors = applyCascadeDeltaBaselines(neighbors);
1491
+ const formatted = formatCascadeResult(cwd, impact, visibleNeighbors, impact.neighborFiles.length);
1492
+ // #1104 HONESTY: filtering a bound-false display candidate must not turn a
1493
+ // degraded/indeterminate cascade into a clean-looking one (same doctrine as
1494
+ // #1023's graph-degraded marker). If every candidate the degraded-fallback
1495
+ // paths considered this run was binding-rejected and nothing else produced
1496
+ // output, thread the SAME indeterminate marker #1023 built so the turn-end
1497
+ // advisory (clients/runtime-turn.ts) surfaces an honest note instead of
1498
+ // silence — never let a withheld-stale-snapshot run look like a genuine
1499
+ // clean leaf. `!impact.indeterminate` preserves a graph-degraded marker that
1500
+ // already exists (never overwritten).
1501
+ if (!formatted && fallbackBindingRejected && !impact.indeterminate) {
1502
+ impact.indeterminate = {
1503
+ reason: "lsp_binding_rejected",
1504
+ detail: "cascade fallback diagnostics were withheld — stale snapshot content did not match current disk (binding rejected)",
1505
+ };
1506
+ }
1507
+ const filesWithErrors = visibleNeighbors.filter((n) => n.diagnostics.length > 0).length;
1508
+ logCascade({
1509
+ phase: "cascade_result",
1510
+ filePath,
1511
+ neighborCount: visibleNeighbors.length,
1512
+ diagnosticCount: visibleNeighbors.reduce((sum, n) => sum + n.diagnostics.length, 0),
1513
+ metadata: {
1514
+ filesWithErrors,
1515
+ hasOutput: formatted.length > 0,
1516
+ // Log when cascade ran but found nothing — distinguishes "clean" from "no signal"
1517
+ noNeighbors: visibleNeighbors.length === 0,
1518
+ noErrors: visibleNeighbors.length > 0 && filesWithErrors === 0,
1519
+ neighbors: visibleNeighbors.slice(0, 10).map((n) => ({
1520
+ file: n.filePath.replace(/\\/g, "/").split("/").slice(-2).join("/"),
1521
+ diagnostics: n.diagnostics.length,
1522
+ })),
1523
+ },
1524
+ });
1525
+ const diagCount = visibleNeighbors.reduce((sum, n) => sum + n.diagnostics.length, 0);
1526
+ cascadeSessionStats.runs += 1;
1527
+ cascadeSessionStats.diagnosticsSurfaced += diagCount;
1528
+ cascadeSessionStats.coldSnapshotTouches += coldSnapshotPaths.length;
1529
+ if (!formatted) {
1530
+ // #1023: an indeterminate compute (degraded/cold/missing-node graph) must
1531
+ // NOT collapse into "no_neighbors" — that is the exact silent all-clear the
1532
+ // bug is about. Distinguish it by the marker threaded onto `impact`, never
1533
+ // by `visibleNeighbors.length === 0` alone (a healthy leaf is also empty).
1534
+ if (impact.indeterminate) {
1535
+ return {
1536
+ filePath,
1537
+ result: undefined,
1538
+ neighborCount: visibleNeighbors.length,
1539
+ diagnosticCount: diagCount,
1540
+ skipReason: "indeterminate",
1541
+ indeterminate: impact.indeterminate,
1542
+ };
1543
+ }
1544
+ const skipReason = visibleNeighbors.length === 0 ? "no_neighbors" : "clean";
1545
+ return {
1089
1546
  filePath,
1090
- fallbackUsed: true,
1091
- neighborCount: neighbors.length,
1092
- });
1547
+ result: undefined,
1548
+ neighborCount: visibleNeighbors.length,
1549
+ diagnosticCount: diagCount,
1550
+ skipReason,
1551
+ };
1093
1552
  }
1094
- }
1095
- const visibleNeighbors = applyCascadeDeltaBaselines(neighbors);
1096
- const formatted = formatCascadeResult(cwd, impact, visibleNeighbors, impact.neighborFiles.length);
1097
- const filesWithErrors = visibleNeighbors.filter((n) => n.diagnostics.length > 0).length;
1098
- logCascade({
1099
- phase: "cascade_result",
1100
- filePath,
1101
- neighborCount: visibleNeighbors.length,
1102
- diagnosticCount: visibleNeighbors.reduce((sum, n) => sum + n.diagnostics.length, 0),
1103
- metadata: {
1104
- filesWithErrors,
1105
- hasOutput: formatted.length > 0,
1106
- // Log when cascade ran but found nothing — distinguishes "clean" from "no signal"
1107
- noNeighbors: visibleNeighbors.length === 0,
1108
- noErrors: visibleNeighbors.length > 0 && filesWithErrors === 0,
1109
- neighbors: visibleNeighbors.slice(0, 10).map((n) => ({
1110
- file: n.filePath.replace(/\\/g, "/").split("/").slice(-2).join("/"),
1111
- diagnostics: n.diagnostics.length,
1112
- })),
1113
- },
1114
- });
1115
- const diagCount = visibleNeighbors.reduce((sum, n) => sum + n.diagnostics.length, 0);
1116
- cascadeSessionStats.runs += 1;
1117
- cascadeSessionStats.diagnosticsSurfaced += diagCount;
1118
- cascadeSessionStats.coldSnapshotTouches += coldSnapshotPaths.length;
1119
- if (!formatted) {
1120
- const skipReason = visibleNeighbors.length === 0 ? "no_neighbors" : "clean";
1553
+ getDiagnosticTracker().trackShown(visibleNeighbors.flatMap((n) => n.diagnostics));
1121
1554
  return {
1122
1555
  filePath,
1123
- result: undefined,
1556
+ result: { filePath, impact, neighbors: visibleNeighbors, formatted },
1124
1557
  neighborCount: visibleNeighbors.length,
1125
1558
  diagnosticCount: diagCount,
1126
- skipReason,
1559
+ // #1023: even when some fallback neighbors surfaced, a degraded graph means
1560
+ // the dependent set is INCOMPLETE — carry the marker so the turn-end seam
1561
+ // still notes downstream impact was under-computed this turn.
1562
+ ...(impact.indeterminate && { indeterminate: impact.indeterminate }),
1127
1563
  };
1128
1564
  }
1129
- getDiagnosticTracker().trackShown(visibleNeighbors.flatMap((n) => n.diagnostics));
1130
- return {
1131
- filePath,
1132
- result: { filePath, impact, neighbors: visibleNeighbors, formatted },
1133
- neighborCount: visibleNeighbors.length,
1134
- diagnosticCount: diagCount,
1135
- };
1565
+ finally {
1566
+ // Keep the cache entry warm, but do not let a one-shot cascade leave an
1567
+ // idle handle behind. The next consumer re-arms it through touch.
1568
+ for (const key of reverseDepsTimersToRelease) {
1569
+ const entry = reverseDepsIndexCache.get(key);
1570
+ if (entry?.idleTimer !== undefined)
1571
+ clearTimeout(entry.idleTimer);
1572
+ if (entry)
1573
+ entry.idleTimer = undefined;
1574
+ }
1575
+ for (const [key, entry] of reverseDepsIndexCache) {
1576
+ if (entry.idleTimer !== undefined)
1577
+ clearTimeout(entry.idleTimer);
1578
+ entry.idleTimer = undefined;
1579
+ if (!reverseDepsTimersToRelease.has(key) && reverseDepsEntriesAtStart.has(entry)) {
1580
+ reverseDepsTimersToRelease.add(key);
1581
+ }
1582
+ }
1583
+ for (const timer of astGrepWarnDebounceTimers.values())
1584
+ clearTimeout(timer);
1585
+ astGrepWarnDebounceTimers.clear();
1586
+ releaseWorkspaceTopologyIdleTimers();
1587
+ }
1136
1588
  }
1137
1589
  function diagnosticDeltaKey(diagnostic) {
1138
1590
  return [
@@ -1159,10 +1611,17 @@ function applyCascadeDeltaBaselines(neighbors) {
1159
1611
  };
1160
1612
  });
1161
1613
  }
1162
- function appendFallbackNeighbors(neighbors, allDiags, normalizedFileKey, cwd) {
1614
+ /**
1615
+ * Returns `true` when at least one otherwise-eligible candidate was withheld
1616
+ * because its content binding was rejected (#1104) — the caller folds this
1617
+ * into the run-level `fallbackBindingRejected` flag for the honesty check.
1618
+ */
1619
+ function appendFallbackNeighbors(neighbors, allDiags, normalizedFileKey, cwd, filePath) {
1163
1620
  const now = Date.now();
1164
1621
  const seen = new Set(neighbors.map((n) => normalizeMapKey(n.filePath)));
1165
- for (const [diagPath, { diags, ts }] of allDiags) {
1622
+ let bindingRejected = false;
1623
+ for (const [diagPath, entry] of allDiags) {
1624
+ const { diags, ts } = entry;
1166
1625
  const diagKey = normalizeMapKey(diagPath);
1167
1626
  if (diagKey === normalizedFileKey || seen.has(diagKey))
1168
1627
  continue;
@@ -1172,10 +1631,33 @@ function appendFallbackNeighbors(neighbors, allDiags, normalizedFileKey, cwd) {
1172
1631
  continue;
1173
1632
  if (isIgnoredCascadeNeighbor(diagPath, cwd))
1174
1633
  continue;
1634
+ // #1080: a KNOWN test-role file must not surface as a collateral fallback
1635
+ // neighbor either (the passive-snapshot path the graph/reference filters
1636
+ // above never reach). Ignore filtering (#297) stays separate and above.
1637
+ if (isTestRoleCollateral(diagPath))
1638
+ continue;
1175
1639
  if (!nodeFs.existsSync(diagPath))
1176
1640
  continue;
1177
1641
  if (now - ts > CASCADE_TTL_MS)
1178
1642
  continue;
1643
+ // #1104: a TTL-fresh entry is not automatically trustworthy — consult
1644
+ // binding the same way the reconcile path (#1100) and the touch-error
1645
+ // fallback above do. `false` → skip (a stale/pre-fix-edit snapshot whose
1646
+ // server view diverged from current disk); "unknown"/`true` → unchanged
1647
+ // (the pre-#1104 fallback contract). Reading `.binding` triggers the lazy
1648
+ // disk verify — done ONLY when TTL-fresh, per the established discipline.
1649
+ const boundToDisk = readBoundToCurrentDisk(entry);
1650
+ if (boundToDisk === false) {
1651
+ bindingRejected = true;
1652
+ logCascade({
1653
+ phase: "neighbor_fallback",
1654
+ filePath,
1655
+ neighborFile: diagPath,
1656
+ fallbackUsed: false,
1657
+ metadata: { bindingState: bindingStateLabel(false) },
1658
+ });
1659
+ continue;
1660
+ }
1179
1661
  // #692: `source: "cascade"` dropped — see the doc comment above the
1180
1662
  // first cascade `convertLspDiagnostics` call site in this file.
1181
1663
  const errors = convertLspDiagnostics(diags.filter((d) => d.severity === 1).slice(0, MAX_PER_FILE), diagPath);
@@ -1191,6 +1673,7 @@ function appendFallbackNeighbors(neighbors, allDiags, normalizedFileKey, cwd) {
1191
1673
  if (neighbors.length >= MAX_FILES)
1192
1674
  break;
1193
1675
  }
1676
+ return bindingRejected;
1194
1677
  }
1195
1678
  function shouldReadCascadeFromSnapshot(filePath) {
1196
1679
  return getServersForFileWithConfig(filePath).some((server) => server.autoPropagateDiagnostics === true);
@@ -1235,11 +1718,11 @@ function formatCascadeResult(cwd, impact, neighbors, totalNeighbors) {
1235
1718
  * @param pi - Pi agent API (for flags)
1236
1719
  * @returns Output string to display to user
1237
1720
  */
1238
- export async function dispatchLint(filePath, cwd, pi, modifiedRanges) {
1721
+ export async function dispatchLint(filePath, cwd, pi, modifiedRanges, projectRoot) {
1239
1722
  // By default, only run BLOCKING rules for fast feedback on file write
1240
1723
  // Uses persistent sessionBaselines so delta mode actually filters
1241
1724
  // pre-existing issues after the first write.
1242
- const ctx = createDispatchContext(filePath, cwd, pi, sessionFacts, true, modifiedRanges);
1725
+ const ctx = createDispatchContext(filePath, cwd, pi, sessionFacts, true, modifiedRanges, projectRoot);
1243
1726
  sessionFacts.clearFileFactsFor(ctx.filePath);
1244
1727
  const kind = ctx.kind;
1245
1728
  if (!kind)
@@ -1259,7 +1742,7 @@ export async function dispatchLintWithResult(filePath, cwd, pi, modifiedRanges,
1259
1742
  // Default true preserves the per-edit fast path (errors only). Callers that
1260
1743
  // want the full picture (warnings + structural smells), e.g. the MCP review
1261
1744
  // facade, pass blockingOnly=false to run every runner.
1262
- const ctx = createDispatchContext(filePath, cwd, pi, sessionFacts, options?.blockingOnly ?? true, modifiedRanges);
1745
+ const ctx = createDispatchContext(filePath, cwd, pi, sessionFacts, options?.blockingOnly ?? true, modifiedRanges, options?.projectRoot, options?.writeIndex);
1263
1746
  sessionFacts.clearFileFactsFor(ctx.filePath);
1264
1747
  const kind = ctx.kind;
1265
1748
  if (!kind) {
@@ -1321,7 +1804,7 @@ export async function dispatchLintDetailed(filePath, cwd, pi, options) {
1321
1804
  blockerOutput: "",
1322
1805
  hasBlockers: false,
1323
1806
  };
1324
- const ctx = createDispatchContext(filePath, cwd, pi, sessionFacts, options?.blockingOnly ?? false, options?.modifiedRanges);
1807
+ const ctx = createDispatchContext(filePath, cwd, pi, sessionFacts, options?.blockingOnly ?? false, options?.modifiedRanges, options?.projectRoot);
1325
1808
  sessionFacts.clearFileFactsFor(ctx.filePath);
1326
1809
  const kind = ctx.kind;
1327
1810
  if (!kind)