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
@@ -15,9 +15,25 @@
15
15
  */
16
16
  import * as fs from "node:fs";
17
17
  import * as path from "node:path";
18
- import { isAtOrAboveHomeDir } from "./path-utils.js";
18
+ import { PathKeyedMap } from "./path-keyed-map.js";
19
+ import { isAtOrAboveHomeDir, normalizeEphemeralMapKey } from "./path-utils.js";
19
20
  import { createDebounceScheduler, } from "./persist-debounce.js";
20
21
  import { getWordIndexMaxFilesDerived } from "./project-scale.js";
22
+ import { logWordIndex } from "./word-index-logger.js";
23
+ import { createDeadline, forEachCooperatively, yieldIfOverBudget, } from "./cooperative-budget.js";
24
+ /**
25
+ * The single normalizer every word-index path key folds through (#1025). The
26
+ * CHEAP form — slash-fold + win32-lowercase, NO filesystem I/O — because the
27
+ * index is a hot, single-process, in-memory structure whose keys this process
28
+ * produces itself (`collectSourceFilesAsync`'s walk, `path.resolve` at the
29
+ * per-edit seams). `normalizeMapKey`'s `realpathSync` per call would be wrong on
30
+ * the BM25 path. Applied at BOTH the build seam and the per-edit update seam so
31
+ * a file's on-disk casing (walk) and its tool-input casing (edit) can no longer
32
+ * diverge into a duplicate doc entry with stale postings (the #1025 item #2
33
+ * bug). Kept as a named alias so every seam is grep-visible and provably shares
34
+ * ONE normalizer with the {@link PathKeyedMap}s below.
35
+ */
36
+ export const wordIndexKey = normalizeEphemeralMapKey;
21
37
  // Common language keywords / boilerplate — indexing them adds noise and bloats
22
38
  // postings without improving relevance. Kept deliberately small and
23
39
  // language-agnostic.
@@ -29,7 +45,7 @@ const STOPWORDS = new Set([
29
45
  "impl", "pub", "use", "mod", "in", "of", "as", "is", "not", "with",
30
46
  ]);
31
47
  const TEST_VENDOR_RE = /(?:(^|[\\/])(?:tests?|__tests__|spec|specs|__mocks__|vendor|node_modules|examples?|fixtures?|\.git|dist|build|coverage)([\\/]|$))|(?:\.(?:test|spec)\.[a-z]+$)/i;
32
- const DOC_FILE_RE = /\.(?:md|mdx|markdown|json|jsonc|txt|rst|lock|ya?ml|toml|csv)$/i;
48
+ const DOC_FILE_RE = /\.(?:md|mdx|markdown|json|json5|jsonc|txt|rst|lock|ya?ml|toml|csv)$/i;
33
49
  const TEST_VENDOR_PENALTY = 0.3;
34
50
  const DOC_FILE_PENALTY = 0.5;
35
51
  const BM25_K1 = 1.2;
@@ -79,42 +95,112 @@ export function tokenizeLine(line) {
79
95
  }
80
96
  return tokens;
81
97
  }
98
+ const WORD_INDEX_BUILD_YIELD_BUDGET_MS = 8;
82
99
  /**
83
- * Build the inverted index from file contents. One posting per (token, file,
84
- * line) — a token repeated on the same line counts once — so term frequency is
85
- * "lines mentioning the token", a stable signal that doesn't over-weight a line
86
- * that repeats an identifier. Document length is the total indexed token count.
100
+ * A line at or above this length is treated as a yield checkpoint on its own.
101
+ * The per-50-lines cadence is a proxy for work that only holds on hand-written
102
+ * source: a minified/bundled single-line file up to {@link WORD_INDEX_MAX_BYTES}
103
+ * that the source filter did not exclude would otherwise get ZERO in-document
104
+ * yields — one unbroken tokenize+push burst far above the budget (#1197 review
105
+ * finding 4). Checking the clock after any long line makes the cooperativeness
106
+ * claim true per BYTE, not just per line count.
107
+ */
108
+ const WORD_INDEX_LONG_LINE_YIELD_CHARS = 4096;
109
+ /**
110
+ * Shared cooperative time-slicer for every bulk word-index path (#1197).
111
+ *
112
+ * Time-based, not count-based: "yield every N items" is only a bound when the
113
+ * per-item cost is bounded too, and the incremental refresh's per-document cost
114
+ * grows with the corpus (each replacement filters shared posting arrays). The
115
+ * #1197 outage was exactly that shape — 239 stale documents held pi's event loop
116
+ * for seconds between two "every 100 files" checkpoints. Callers combine this
117
+ * The shared deadline is checked at every bounded work unit so abort latency
118
+ * and occupancy are governed by the same monotonic budget.
87
119
  */
120
+ function createEmptyWordIndex(truncated) {
121
+ return {
122
+ postings: new Map(),
123
+ docLengths: new PathKeyedMap(wordIndexKey),
124
+ totalTokens: 0,
125
+ docCount: 0,
126
+ truncated,
127
+ forward: new PathKeyedMap(wordIndexKey),
128
+ fileMtimes: new PathKeyedMap(wordIndexKey),
129
+ fileSizes: new PathKeyedMap(wordIndexKey),
130
+ };
131
+ }
132
+ function indexWordLine(index, filePath, line, lineNumber, tokenLineCounts) {
133
+ const lineTokens = tokenizeLine(line);
134
+ const seenOnLine = new Set();
135
+ for (const token of lineTokens) {
136
+ if (seenOnLine.has(token))
137
+ continue;
138
+ seenOnLine.add(token);
139
+ const arr = index.postings.get(token);
140
+ if (arr)
141
+ arr.push({ file: filePath, line: lineNumber });
142
+ else
143
+ index.postings.set(token, [{ file: filePath, line: lineNumber }]);
144
+ tokenLineCounts.set(token, (tokenLineCounts.get(token) ?? 0) + 1);
145
+ }
146
+ return lineTokens.length;
147
+ }
148
+ function finishWordIndexDocument(index, doc, docLength, tokenLineCounts) {
149
+ index.docLengths.set(doc.path, docLength);
150
+ index.forward?.set(doc.path, tokenLineCounts);
151
+ index.fileMtimes.set(doc.path, doc.mtimeMs ?? 0);
152
+ index.fileSizes.set(doc.path, doc.size ?? Buffer.byteLength(doc.content, "utf-8"));
153
+ index.totalTokens += docLength;
154
+ index.docCount += 1;
155
+ }
156
+ function indexWordDocument(index, doc) {
157
+ const lines = doc.content.split(/\r?\n/);
158
+ const tokenLineCounts = new Map();
159
+ let docLength = 0;
160
+ for (let i = 0; i < lines.length; i += 1) {
161
+ docLength += indexWordLine(index, doc.path, lines[i], i + 1, tokenLineCounts);
162
+ }
163
+ finishWordIndexDocument(index, doc, docLength, tokenLineCounts);
164
+ }
88
165
  export function buildWordIndex(files) {
89
- const postings = new Map();
90
- const docLengths = new Map();
91
- const forward = new Map();
92
- let totalTokens = 0;
93
- for (const { path: filePath, content } of files) {
94
- const lines = content.split(/\r?\n/);
95
- let docLength = 0;
166
+ const index = createEmptyWordIndex(files.truncated ?? false);
167
+ for (const doc of files)
168
+ indexWordDocument(index, doc);
169
+ return index;
170
+ }
171
+ /**
172
+ * Cooperative production builder for bulk/cold paths. It produces the exact
173
+ * same index as {@link buildWordIndex}, but time-slices both between documents
174
+ * and within a large document so startup warmup cannot monopolize pi's TUI
175
+ * event loop (#1197). The index is private until this resolves, so a superseded
176
+ * build never publishes a partial replacement.
177
+ */
178
+ export async function buildWordIndexAsync(files, shouldContinue = () => true) {
179
+ const index = createEmptyWordIndex(files.truncated ?? false);
180
+ const deadline = createDeadline(WORD_INDEX_BUILD_YIELD_BUDGET_MS);
181
+ for (const doc of files) {
182
+ if (!shouldContinue())
183
+ throw new Error("word index build superseded");
184
+ const lines = doc.content.split(/\r?\n/);
96
185
  const tokenLineCounts = new Map();
186
+ let docLength = 0;
97
187
  for (let i = 0; i < lines.length; i += 1) {
98
- const lineTokens = tokenizeLine(lines[i]);
99
- docLength += lineTokens.length;
100
- const seenOnLine = new Set();
101
- for (const token of lineTokens) {
102
- if (seenOnLine.has(token))
103
- continue;
104
- seenOnLine.add(token);
105
- const arr = postings.get(token);
106
- if (arr)
107
- arr.push({ file: filePath, line: i + 1 });
108
- else
109
- postings.set(token, [{ file: filePath, line: i + 1 }]);
110
- tokenLineCounts.set(token, (tokenLineCounts.get(token) ?? 0) + 1);
188
+ const line = lines[i];
189
+ docLength += indexWordLine(index, doc.path, line, i + 1, tokenLineCounts);
190
+ if (line.length >= WORD_INDEX_LONG_LINE_YIELD_CHARS ||
191
+ deadline.expired()) {
192
+ await yieldIfOverBudget(deadline);
193
+ if (!shouldContinue())
194
+ throw new Error("word index build superseded");
111
195
  }
112
196
  }
113
- docLengths.set(filePath, docLength);
114
- forward.set(filePath, tokenLineCounts);
115
- totalTokens += docLength;
197
+ finishWordIndexDocument(index, doc, docLength, tokenLineCounts);
198
+ if (deadline.expired() && (await yieldIfOverBudget(deadline))) {
199
+ if (!shouldContinue())
200
+ throw new Error("word index build superseded");
201
+ }
116
202
  }
117
- return { postings, docLengths, totalTokens, docCount: files.length, forward };
203
+ return index;
118
204
  }
119
205
  /**
120
206
  * Remove `filePath`'s postings/docLength/forward entry from `index` in place,
@@ -130,11 +216,17 @@ export function removeWordIndexDocument(index, filePath) {
130
216
  const tokenLineCounts = index.forward.get(filePath);
131
217
  if (!tokenLineCounts)
132
218
  return false;
219
+ // `postings` is token-keyed (not a PathKeyedMap), so its `WordHit.file`
220
+ // display strings must be compared through the SAME normalizer the path maps
221
+ // use — otherwise a build-form hit (`SUB/a.ts`) survives an edit-form removal
222
+ // (`sub/a.ts`) on a case-insensitive FS and lingers as a stale posting
223
+ // (the #1025 item #2 bug this fix closes).
224
+ const removedKey = wordIndexKey(filePath);
133
225
  for (const token of tokenLineCounts.keys()) {
134
226
  const arr = index.postings.get(token);
135
227
  if (!arr)
136
228
  continue;
137
- const next = arr.filter((hit) => hit.file !== filePath);
229
+ const next = arr.filter((hit) => wordIndexKey(hit.file) !== removedKey);
138
230
  if (next.length > 0)
139
231
  index.postings.set(token, next);
140
232
  else
@@ -143,6 +235,8 @@ export function removeWordIndexDocument(index, filePath) {
143
235
  const docLength = index.docLengths.get(filePath) ?? 0;
144
236
  index.docLengths.delete(filePath);
145
237
  index.forward.delete(filePath);
238
+ index.fileMtimes.delete(filePath);
239
+ index.fileSizes.delete(filePath);
146
240
  index.totalTokens -= docLength;
147
241
  index.docCount = Math.max(0, index.docCount - 1);
148
242
  return true;
@@ -200,6 +294,123 @@ export function updateWordIndexDocument(index, doc) {
200
294
  }
201
295
  index.docLengths.set(doc.path, docLength);
202
296
  index.forward.set(doc.path, tokenLineCounts);
297
+ // Per-edit callers generally already have content but not a stat. -1 is an
298
+ // impossible real mtime, so it deliberately makes the document stale at the
299
+ // next startup refresh (`-1 !== realMtime` always) — unlike 0, which is a
300
+ // legal on-disk mtime (SOURCE_DATE_EPOCH=0, archive extraction) and would
301
+ // collide, leaving such a file never re-tokenized (#958 review F2).
302
+ index.fileMtimes.set(doc.path, -1);
303
+ // Size is likewise recorded for the #1105 mtime+size refresh gate. The -1
304
+ // mtime already forces a re-read next session, so this value only keeps the
305
+ // map dense (parallel to fileMtimes); store the real byte length so a
306
+ // deserialize→reserialize round-trip before any refresh carries a truthful
307
+ // size rather than a placeholder.
308
+ index.fileSizes.set(doc.path, Buffer.byteLength(doc.content, "utf-8"));
309
+ index.totalTokens += docLength;
310
+ index.docCount += 1;
311
+ return true;
312
+ }
313
+ async function stageWordIndexDocumentRemoval(index, filePath, shouldContinue) {
314
+ if (!index.forward)
315
+ return undefined;
316
+ const tokenLineCounts = index.forward.get(filePath);
317
+ if (!tokenLineCounts)
318
+ return undefined;
319
+ const removedKey = wordIndexKey(filePath);
320
+ const postings = new Map();
321
+ const deadline = createDeadline(WORD_INDEX_BUILD_YIELD_BUDGET_MS);
322
+ for (const token of tokenLineCounts.keys()) {
323
+ if (!shouldContinue())
324
+ throw new Error("word index refresh superseded");
325
+ const arr = index.postings.get(token);
326
+ if (!arr)
327
+ continue;
328
+ const next = [];
329
+ for (const hit of arr) {
330
+ if (wordIndexKey(hit.file) !== removedKey)
331
+ next.push(hit);
332
+ if (deadline.expired() && (await yieldIfOverBudget(deadline))) {
333
+ if (!shouldContinue())
334
+ throw new Error("word index refresh superseded");
335
+ }
336
+ }
337
+ postings.set(token, next.length > 0 ? next : undefined);
338
+ }
339
+ return { postings, docLength: index.docLengths.get(filePath) ?? 0 };
340
+ }
341
+ function commitWordIndexDocumentRemoval(index, filePath, staged) {
342
+ for (const [token, hits] of staged.postings) {
343
+ if (hits)
344
+ index.postings.set(token, hits);
345
+ else
346
+ index.postings.delete(token);
347
+ }
348
+ index.docLengths.delete(filePath);
349
+ index.forward?.delete(filePath);
350
+ index.fileMtimes.delete(filePath);
351
+ index.fileSizes.delete(filePath);
352
+ index.totalTokens -= staged.docLength;
353
+ index.docCount = Math.max(0, index.docCount - 1);
354
+ }
355
+ /** Cooperative, atomically-published removal used only by bulk refresh. */
356
+ export async function removeWordIndexDocumentAsync(index, filePath, shouldContinue = () => true) {
357
+ const staged = await stageWordIndexDocumentRemoval(index, filePath, shouldContinue);
358
+ if (!staged)
359
+ return false;
360
+ if (!shouldContinue())
361
+ throw new Error("word index refresh superseded");
362
+ commitWordIndexDocumentRemoval(index, filePath, staged);
363
+ return true;
364
+ }
365
+ /** Cooperative replacement whose old/new state is committed without an await. */
366
+ export async function updateWordIndexDocumentAsync(index, doc, shouldContinue = () => true) {
367
+ if (!index.forward)
368
+ return false;
369
+ const removal = index.forward.has(doc.path)
370
+ ? await stageWordIndexDocumentRemoval(index, doc.path, shouldContinue)
371
+ : undefined;
372
+ if (index.forward.has(doc.path) && !removal)
373
+ return false;
374
+ const perTokenHits = new Map();
375
+ let docLength = 0;
376
+ const lines = doc.content.split(/\r?\n/);
377
+ await forEachCooperatively(lines, (line, i) => {
378
+ const lineTokens = tokenizeLine(line);
379
+ docLength += lineTokens.length;
380
+ const seenOnLine = new Set();
381
+ for (const token of lineTokens) {
382
+ if (seenOnLine.has(token))
383
+ continue;
384
+ seenOnLine.add(token);
385
+ const arr = perTokenHits.get(token);
386
+ if (arr)
387
+ arr.push(i + 1);
388
+ else
389
+ perTokenHits.set(token, [i + 1]);
390
+ }
391
+ }, {
392
+ budgetMs: WORD_INDEX_BUILD_YIELD_BUDGET_MS,
393
+ shouldContinue,
394
+ abortMessage: "word index refresh superseded",
395
+ });
396
+ if (!shouldContinue())
397
+ throw new Error("word index refresh superseded");
398
+ if (removal)
399
+ commitWordIndexDocumentRemoval(index, doc.path, removal);
400
+ const tokenLineCounts = new Map();
401
+ for (const [token, lineNumbers] of perTokenHits) {
402
+ tokenLineCounts.set(token, lineNumbers.length);
403
+ const hits = lineNumbers.map((line) => ({ file: doc.path, line }));
404
+ const arr = index.postings.get(token);
405
+ if (arr)
406
+ arr.push(...hits);
407
+ else
408
+ index.postings.set(token, hits);
409
+ }
410
+ index.docLengths.set(doc.path, docLength);
411
+ index.forward.set(doc.path, tokenLineCounts);
412
+ index.fileMtimes.set(doc.path, -1);
413
+ index.fileSizes.set(doc.path, Buffer.byteLength(doc.content, "utf-8"));
203
414
  index.totalTokens += docLength;
204
415
  index.docCount += 1;
205
416
  return true;
@@ -224,7 +435,7 @@ export const WORD_INDEX_MAX_BYTES = 512 * 1024;
224
435
  * `shouldContinue` lets a session-scoped caller abort early (session
225
436
  * superseded) without this module knowing about RuntimeCoordinator.
226
437
  */
227
- export async function collectWordIndexDocs(root, shouldContinue = () => true) {
438
+ export async function collectWordIndexDocs(root, shouldContinue = () => true, preflightFiles) {
228
439
  const { collectSourceFilesAsync } = await import("./source-filter.js");
229
440
  // #747 hardening: pass the cap INTO the walk — without it,
230
441
  // `collectSourceFilesAsync` defaults to an unbounded traversal and the
@@ -234,32 +445,296 @@ export async function collectWordIndexDocs(root, shouldContinue = () => true) {
234
445
  // visited-entry budget (DEFAULT_MAX_SCAN_ENTRIES), so a mixed tree with few
235
446
  // source files among a huge pile of non-source files can't force a
236
447
  // full-tree walk either; an index over the truncated list is acceptable.
237
- const maxFiles = getWordIndexMaxFilesDerived(root);
238
- const files = await collectSourceFilesAsync(root, {
239
- maxFiles,
240
- });
448
+ const maxFiles = preflightFiles?.length ?? getWordIndexMaxFilesDerived(root);
449
+ // #894 review: prioritize code kinds within the cap — with broadened
450
+ // enumeration, thousands of data/doc files (locale JSON, fixtures, …)
451
+ // ahead of the code dirs in walk order could exhaust `maxFiles` and evict
452
+ // real source files from the index entirely (DOC_FILE_PENALTY can't
453
+ // rescue a file that never made the slice).
454
+ const files = preflightFiles
455
+ ? preflightFiles.map((file) => file.path)
456
+ : await collectSourceFilesAsync(root, {
457
+ maxFiles,
458
+ prioritizeCodeKinds: true,
459
+ });
460
+ const truncated = preflightFiles?.truncated ?? files.length === maxFiles;
461
+ const docs = Object.assign([], { truncated, skipped: 0 });
241
462
  if (!shouldContinue())
242
- return [];
243
- const docs = [];
244
- let processed = 0;
463
+ return docs;
464
+ const deadline = createDeadline(WORD_INDEX_BUILD_YIELD_BUDGET_MS);
245
465
  for (const file of files.slice(0, maxFiles)) {
466
+ if (!shouldContinue())
467
+ return docs;
246
468
  try {
469
+ // A preflight list saves the second full WALK, but its metadata may be
470
+ // stale by the time this rebuild reads the file. Re-stat each document at
471
+ // content-read time so the stored freshness stamp describes the bytes we
472
+ // actually index and the next incremental refresh cannot miss a change in
473
+ // the walk-to-read window (#1302).
247
474
  const stat = fs.statSync(file);
248
475
  if (stat.size <= WORD_INDEX_MAX_BYTES) {
249
- docs.push({ path: file, content: fs.readFileSync(file, "utf-8") });
476
+ docs.push({
477
+ path: file,
478
+ content: fs.readFileSync(file, "utf-8"),
479
+ mtimeMs: stat.mtimeMs,
480
+ size: stat.size,
481
+ });
482
+ }
483
+ else {
484
+ // Over the byte cap — enumerated but deliberately not indexed. Count
485
+ // it (L1, #958) so callers can keep coverage honest instead of the
486
+ // old silent drop.
487
+ docs.skipped += 1;
250
488
  }
251
489
  }
252
490
  catch {
253
- // unreadable / vanished file — skip
491
+ // unreadable / vanished file — skip, but count it (see above).
492
+ docs.skipped += 1;
254
493
  }
255
- if (++processed % 100 === 0) {
256
- await new Promise((resolve) => setImmediate(resolve));
494
+ if (deadline.expired() && (await yieldIfOverBudget(deadline))) {
257
495
  if (!shouldContinue())
258
496
  return docs;
259
497
  }
260
498
  }
261
499
  return docs;
262
500
  }
501
+ const WORD_INDEX_INCREMENTAL_CHURN_THRESHOLD = 0.3;
502
+ // A ratio alone misclassifies one stale file in a three-file project as dense.
503
+ // Below this absolute floor, per-document replacement is bounded and cheaper
504
+ // than a second full walk/read even when the percentage is high (#1197).
505
+ const WORD_INDEX_DENSE_REFRESH_MIN_DOCUMENTS = 32;
506
+ /**
507
+ * Cost of one file's stat+read+decode expressed in tokenizer-token units, so
508
+ * the work model below can compare a path that re-reads EVERY file (full
509
+ * rebuild) against one that re-reads only the stale files (incremental) in a
510
+ * single currency. One read ≈ 300 tokens at the ~1 µs/token measured below.
511
+ * Order-of-magnitude by design — it only has to keep a tiny-vocabulary corpus
512
+ * (where posting scans are nearly free) from being sent to a full rebuild that
513
+ * re-reads everything to save a handful of array filters.
514
+ */
515
+ const WORD_INDEX_FILE_READ_TOKEN_COST = 300;
516
+ /**
517
+ * Cost of scanning ONE posting-array element (the `wordIndexKey` compare in
518
+ * {@link removeWordIndexDocument}'s filter) relative to tokenizing one token,
519
+ * so both sides of the model below are denominated in tokens. Measured on this
520
+ * repository's own 2,062-document corpus: 213 ns per element scan against 979 ns
521
+ * per token — and the resulting predicted crossover (23 stale documents) lands
522
+ * on the directly measured one (~21, from 97.8 ms per document replacement
523
+ * against a 1,436 ms rebuild + re-read). The synthetic high-df corpus in the
524
+ * #1197 probe gives 0.09, so this is the conservative (incremental-favouring)
525
+ * end of the observed range.
526
+ */
527
+ const WORD_INDEX_POSTING_SCAN_TOKEN_COST = 0.2;
528
+ /**
529
+ * Refresh a serializer-v2 index from the current bounded source-file set.
530
+ * The walk/stat pass is cheap; only sparse stale/new documents are read and
531
+ * tokenized. Expected dense/legacy states return `full-required` BEFORE any
532
+ * mutation; unexpected corruption or supersession still throws.
533
+ */
534
+ export async function refreshWordIndexIncrementally(index, root, shouldContinue = () => true) {
535
+ if (!index.forward || !index.fileMtimes || !index.fileSizes) {
536
+ return {
537
+ mode: "full-required",
538
+ reason: "missing-incremental-metadata",
539
+ };
540
+ }
541
+ const { collectSourceFilesAsync } = await import("./source-filter.js");
542
+ const maxFiles = getWordIndexMaxFilesDerived(root);
543
+ const walked = await collectSourceFilesAsync(root, {
544
+ maxFiles,
545
+ prioritizeCodeKinds: true,
546
+ });
547
+ if (!shouldContinue())
548
+ throw new Error("word index refresh superseded");
549
+ // This set-difference must run in the SAME normalized key space the path
550
+ // maps use (#1025 review). Otherwise a file whose stored displayPath became
551
+ // the edit form (last-writer-wins after a case/separator-divergent per-edit
552
+ // update) no longer string-matches its walk form here — even though
553
+ // `fileMtimes.get(walkForm)` folds and hits — which would (1) double-count
554
+ // churn (the same file scored as both "dropped" and "added"), possibly
555
+ // crossing the threshold and forcing a needless full rebuild, and (2) drop
556
+ // then re-add an unchanged file, opening a regression window because the drop
557
+ // loop runs BEFORE the re-read: a transient read failure (skipped++) would
558
+ // strand the file with no postings. Keying `current` and `oldSet` through
559
+ // `wordIndexKey` keeps build/edit/refresh convergent; `current`'s value
560
+ // retains the raw walk path for the stat/read and for the display key.
561
+ const current = new Map();
562
+ // Check both supersession and the monotonic budget at every stat unit. Unlike
563
+ // the former modulus cadence, this remains bounded as per-file work changes.
564
+ const deadline = createDeadline(WORD_INDEX_BUILD_YIELD_BUDGET_MS);
565
+ for (const file of walked) {
566
+ if (!shouldContinue())
567
+ throw new Error("word index refresh superseded");
568
+ try {
569
+ const stat = fs.statSync(file);
570
+ if (stat.size <= WORD_INDEX_MAX_BYTES) {
571
+ current.set(wordIndexKey(file), {
572
+ path: file,
573
+ mtimeMs: stat.mtimeMs,
574
+ size: stat.size,
575
+ });
576
+ }
577
+ }
578
+ catch {
579
+ // A file vanishing between walk and stat is simply absent.
580
+ }
581
+ if (deadline.expired() && (await yieldIfOverBudget(deadline))) {
582
+ if (!shouldContinue())
583
+ throw new Error("word index refresh superseded");
584
+ }
585
+ }
586
+ const preflightFiles = Object.assign([...current.values()], {
587
+ truncated: walked.length === maxFiles,
588
+ });
589
+ const oldSet = new Set([...index.docLengths.keys()].map(wordIndexKey));
590
+ let changedSet = 0;
591
+ for (const key of oldSet)
592
+ if (!current.has(key))
593
+ changedSet++;
594
+ for (const key of current.keys())
595
+ if (!oldSet.has(key))
596
+ changedSet++;
597
+ const denominator = Math.max(oldSet.size, current.size, 1);
598
+ if (changedSet / denominator > WORD_INDEX_INCREMENTAL_CHURN_THRESHOLD) {
599
+ return { mode: "full-required", reason: "file-set-churn", preflightFiles };
600
+ }
601
+ // Replacing one document filters every shared posting array for that
602
+ // document's tokens. That is excellent for a sparse edit, but repeating it
603
+ // for most of the corpus becomes effectively quadratic. Decide the dense
604
+ // transition BEFORE dropping or editing anything so the old index remains a
605
+ // valid fallback until a separately-built full replacement is ready (#1197).
606
+ let staleDocuments = 0;
607
+ for (const { path: file, mtimeMs, size } of current.values()) {
608
+ if (index.fileMtimes.get(file) !== mtimeMs ||
609
+ (index.fileSizes.get(file) ?? -1) !== size) {
610
+ staleDocuments += 1;
611
+ }
612
+ }
613
+ // Density alone is NOT a bound (#1197 review finding 1): the per-document cost
614
+ // GROWS with the corpus, so a stale set comfortably under any fixed ratio (or
615
+ // any fixed absolute ceiling) still costs orders of magnitude more than a
616
+ // rebuild on a big enough repository. 800 documents with 239 stale — 29.875%,
617
+ // just under the ratio — measured 90.6 s with a 39.6 s synchronous block
618
+ // against 1.3 s / 10.6 ms for a full build, and at the 6,000-file cap up to
619
+ // 1,799 stale documents would have stayed on that path.
620
+ //
621
+ // So compare estimated WORK, both sides denominated in tokenizer tokens:
622
+ // incremental ≈ stale x (docTokens x postingLength x scanCost + readCost)
623
+ // full ≈ totalTokens + corpusSize x readCost
624
+ // This is self-bounding in a way no constant is: the incremental path is taken
625
+ // only while its total estimated cost stays under ONE full rebuild, so the
626
+ // worst case is "about as expensive as rebuilding", whatever the corpus size.
627
+ //
628
+ // Both statistics come from cheap metadata passes — one over `postings`
629
+ // (distinct tokens, reading only `.length`) and one over `forward` (documents,
630
+ // reading only `.size`). Neither touches a posting ELEMENT, which is the work
631
+ // this decision exists to avoid.
632
+ let postingEntries = 0;
633
+ let weightedPostingEntries = 0;
634
+ for (const hits of index.postings.values()) {
635
+ postingEntries += hits.length;
636
+ weightedPostingEntries += hits.length * hits.length;
637
+ }
638
+ // The mean posting-array length weighted by OCCURRENCES, not the plain mean:
639
+ // a document's tokens are drawn from the frequency distribution, so the arrays
640
+ // a removal actually filters skew hard toward the high-document-frequency
641
+ // tokens. The unweighted mean (dominated by the long tail of df=1 tokens)
642
+ // underestimates the real cost by an order of magnitude.
643
+ const expectedPostingLength = postingEntries > 0 ? weightedPostingEntries / postingEntries : 0;
644
+ let distinctTokenEntries = 0;
645
+ for (const tokenLineCounts of index.forward.values()) {
646
+ distinctTokenEntries += tokenLineCounts.size;
647
+ }
648
+ const expectedDocumentTokens = index.docCount > 0 ? distinctTokenEntries / index.docCount : 0;
649
+ const estimatedIncrementalWork = staleDocuments *
650
+ (expectedDocumentTokens *
651
+ expectedPostingLength *
652
+ WORD_INDEX_POSTING_SCAN_TOKEN_COST +
653
+ WORD_INDEX_FILE_READ_TOKEN_COST);
654
+ const estimatedFullRebuildWork = index.totalTokens + current.size * WORD_INDEX_FILE_READ_TOKEN_COST;
655
+ // The document-count floor guards the RATIO test only — its documented job is
656
+ // that "one stale file in a three-file project" is 33% but not dense. It must
657
+ // NOT gate the work test: a floor is another constant, and letting one
658
+ // suppress the work comparison would reintroduce exactly the unbounded-on-the
659
+ // -other-axis shape (31 documents at 98 ms each on this repository's own
660
+ // corpus, and worse as the corpus grows). The work test needs no floor — on a
661
+ // small project a full rebuild is cheap, so it never fires there.
662
+ if ((staleDocuments >= WORD_INDEX_DENSE_REFRESH_MIN_DOCUMENTS &&
663
+ staleDocuments / Math.max(current.size, 1) >
664
+ WORD_INDEX_INCREMENTAL_CHURN_THRESHOLD) ||
665
+ estimatedIncrementalWork > estimatedFullRebuildWork) {
666
+ return {
667
+ mode: "full-required",
668
+ reason: "stale-document-churn",
669
+ preflightFiles,
670
+ };
671
+ }
672
+ let dropped = 0;
673
+ for (const key of oldSet) {
674
+ if (!current.has(key)) {
675
+ // `key` is already folded; removeWordIndexDocument re-folds it
676
+ // idempotently via the PathKeyedMap, so the drop hits the right entry.
677
+ if (!(await removeWordIndexDocumentAsync(index, key, shouldContinue))) {
678
+ throw new Error(`failed to drop word-index document: ${key}`);
679
+ }
680
+ dropped++;
681
+ }
682
+ }
683
+ let refreshed = 0;
684
+ let skipped = 0;
685
+ for (const { path: file, mtimeMs, size } of current.values()) {
686
+ // #1105: mtime-first, size-second freshness — mtime alone is a stale
687
+ // signal (mtime-preserving content changes serve stale identifiers to
688
+ // symbol_search). Size is free (the stat above already read it) and
689
+ // catches every content change that alters byte length. Both come from the
690
+ // SAME stat, so a mismatch on EITHER axis re-reads. `?? -1` makes a file
691
+ // absent from the (possibly legacy, pre-#1105) size map always count as
692
+ // changed → one-time re-read that repopulates the size, the safe direction.
693
+ if (index.fileMtimes.get(file) !== mtimeMs ||
694
+ (index.fileSizes.get(file) ?? -1) !== size) {
695
+ // A file the walk/stat pass saw can still fail to read here — a
696
+ // transient exclusive lock (antivirus, an editor, a build step) or a
697
+ // file that vanished in the interim. Match collectWordIndexDocs'
698
+ // tolerance: skip this one file and leave its existing posting (and
699
+ // its old mtime, so it is retried next session) rather than aborting
700
+ // the whole incremental pass into a full rebuild (#958 review F1).
701
+ let content;
702
+ try {
703
+ content = fs.readFileSync(file, "utf-8");
704
+ }
705
+ catch {
706
+ skipped++;
707
+ continue;
708
+ }
709
+ if (!(await updateWordIndexDocumentAsync(index, { path: file, content }, shouldContinue))) {
710
+ throw new Error(`failed to refresh word-index document: ${file}`);
711
+ }
712
+ // updateWordIndexDocument stamps mtime=-1 (per-edit convention); the
713
+ // refresh path KNOWS the real on-disk stat, so overwrite both axes with
714
+ // the true values so this document is not needlessly re-read next pass.
715
+ index.fileMtimes.set(file, mtimeMs);
716
+ index.fileSizes.set(file, size);
717
+ refreshed++;
718
+ }
719
+ // Same OR as the stat loop. This is the loop the #1197 outage actually
720
+ // blocked in: replacing one document costs more the larger the corpus is,
721
+ // so a count-only checkpoint let 100 replacements run back to back for
722
+ // seconds. The gate above keeps the stale set sparse; this keeps even a
723
+ // sparse-but-expensive set off the event loop.
724
+ if (deadline.expired() && (await yieldIfOverBudget(deadline))) {
725
+ if (!shouldContinue())
726
+ throw new Error("word index refresh superseded");
727
+ }
728
+ }
729
+ index.truncated = walked.length === maxFiles;
730
+ return {
731
+ mode: "incremental",
732
+ refreshed,
733
+ dropped,
734
+ skipped,
735
+ reused: current.size - refreshed - skipped,
736
+ };
737
+ }
263
738
  /**
264
739
  * Rank files for a query by BM25 over the query's identifier tokens, then apply
265
740
  * priors: demote test/vendor and doc/data files, and boost by graph centrality
@@ -349,6 +824,8 @@ export function centralityFromReverseDeps(index, reverseDeps, normalizeKey = (fi
349
824
  }
350
825
  return centrality;
351
826
  }
827
+ /** Persisted word-index serialization format version. Bump on breaking format changes. */
828
+ export const WORD_INDEX_FORMAT_VERSION = 2;
352
829
  export function serializeWordIndex(index) {
353
830
  const files = [...index.docLengths.keys()];
354
831
  const fileIndex = new Map();
@@ -372,22 +849,41 @@ export function serializeWordIndex(index) {
372
849
  ])
373
850
  : undefined;
374
851
  return {
852
+ version: WORD_INDEX_FORMAT_VERSION,
375
853
  files,
376
854
  postings,
377
855
  docLengths: files.map((file) => index.docLengths.get(file) ?? 0),
378
856
  totalTokens: index.totalTokens,
857
+ indexedFileCount: index.docCount,
858
+ truncated: index.truncated,
859
+ fileMtimes: files.map((file) => index.fileMtimes.get(file) ?? 0),
860
+ fileSizes: files.map((file) => index.fileSizes.get(file) ?? 0),
379
861
  forward,
380
862
  };
381
863
  }
382
864
  export function deserializeWordIndex(data) {
383
865
  if (!data ||
866
+ data.version !== WORD_INDEX_FORMAT_VERSION ||
384
867
  !Array.isArray(data.files) ||
385
868
  !Array.isArray(data.postings) ||
386
- !Array.isArray(data.docLengths)) {
869
+ !Array.isArray(data.docLengths) ||
870
+ !Array.isArray(data.fileMtimes) ||
871
+ data.fileMtimes.length !== data.files.length) {
387
872
  return null;
388
873
  }
389
- const docLengths = new Map();
874
+ const docLengths = new PathKeyedMap(wordIndexKey);
875
+ const fileMtimes = new PathKeyedMap(wordIndexKey);
876
+ const fileSizes = new PathKeyedMap(wordIndexKey);
390
877
  data.files.forEach((file, i) => docLengths.set(file, data.docLengths[i] ?? 0));
878
+ data.files.forEach((file, i) => fileMtimes.set(file, data.fileMtimes[i] ?? 0));
879
+ // #1105: `fileSizes` is optional on the wire (pre-#1105 snapshots omit it).
880
+ // Only populate when the array is present AND parallel to `files`; otherwise
881
+ // leave it empty so the refresh gate re-reads every file once to repopulate,
882
+ // rather than trusting a bogus/misaligned size. Never treated as "current".
883
+ if (Array.isArray(data.fileSizes) &&
884
+ data.fileSizes.length === data.files.length) {
885
+ data.files.forEach((file, i) => fileSizes.set(file, data.fileSizes?.[i] ?? 0));
886
+ }
391
887
  const postings = new Map();
392
888
  for (const [token, flat] of data.postings) {
393
889
  if (typeof token !== "string" || !Array.isArray(flat))
@@ -405,7 +901,7 @@ export function deserializeWordIndex(data) {
405
901
  }
406
902
  let forward;
407
903
  if (Array.isArray(data.forward)) {
408
- forward = new Map();
904
+ forward = new PathKeyedMap(wordIndexKey);
409
905
  for (const entry of data.forward) {
410
906
  if (!Array.isArray(entry) || entry.length !== 2)
411
907
  continue;
@@ -430,23 +926,19 @@ export function deserializeWordIndex(data) {
430
926
  docLengths,
431
927
  totalTokens: typeof data.totalTokens === "number" ? data.totalTokens : 0,
432
928
  docCount: data.files.length,
929
+ truncated: data.truncated === true,
433
930
  forward,
931
+ fileMtimes,
932
+ fileSizes,
434
933
  };
435
934
  }
436
- // --- Cold-query background build trigger (#348) -------------------------------
437
- //
438
- // `symbol_search` (pi tool) / `pilens_symbol_search` (MCP) are stateless callers:
439
- // no RuntimeCoordinator, no session lifecycle — just a synchronous read of the
440
- // persisted snapshot via `symbolSearch()`. When the index is missing (e.g. the
441
- // session-start / warmup lifecycle in runtime-session.ts hasn't run yet, or this
442
- // is an MCP-only session that never ran pilens_session_start), the tool must
443
- // never block the query on a project walk (#348 decision 3): it triggers a
444
- // single background build, keyed by the resolved cwd so a burst of queries in
445
- // the same cold window only pays for one walk, and returns immediately.
446
- const inFlightBuilds = new Set();
935
+ const buildStatuses = new Map();
936
+ export function getWordIndexBuildStatus(cwd) {
937
+ return buildStatuses.get(path.resolve(cwd));
938
+ }
447
939
  /** Test-only: reset the in-flight-build guard between test files/cases. */
448
940
  export function _resetWordIndexBuildGuardForTests() {
449
- inFlightBuilds.clear();
941
+ buildStatuses.clear();
450
942
  }
451
943
  /**
452
944
  * Fire a one-time bounded background build for `cwd` if one isn't already
@@ -465,18 +957,29 @@ export function triggerBackgroundWordIndexBuild(cwd, dbg, options = {}) {
465
957
  // a home-rooted cwd. Apply the same `isAtOrAboveHomeDir` ceiling here so a
466
958
  // cold query from $HOME never starts a whole-home walk-and-read.
467
959
  if (isAtOrAboveHomeDir(key, options.homeDir)) {
468
- dbg?.(`word-index cold-build: skipped — root at/above home directory (${key})`);
469
- return;
960
+ const reason = `root at/above home directory (${key})`;
961
+ dbg?.(`word-index cold-build: skipped — ${reason}`);
962
+ logWordIndex({
963
+ phase: "cold_build_refused",
964
+ cwd: key,
965
+ trigger: "cold_query",
966
+ reason,
967
+ });
968
+ const status = { state: "refused", reason };
969
+ buildStatuses.set(key, status);
970
+ return status;
470
971
  }
471
- if (inFlightBuilds.has(key))
472
- return;
473
- inFlightBuilds.add(key);
972
+ const current = buildStatuses.get(key);
973
+ if (current?.state === "building")
974
+ return current;
975
+ const status = { state: "building" };
976
+ buildStatuses.set(key, status);
474
977
  void (async () => {
475
978
  const startMs = Date.now();
476
979
  try {
477
980
  const { loadProjectSnapshot, saveProjectSnapshot, PROJECT_SNAPSHOT_VERSION } = await import("./project-snapshot.js");
478
981
  const docs = await collectWordIndexDocs(key);
479
- const index = buildWordIndex(docs);
982
+ const index = await buildWordIndexAsync(docs);
480
983
  const existing = loadProjectSnapshot(key);
481
984
  const snapshot = existing ?? {
482
985
  version: PROJECT_SNAPSHOT_VERSION,
@@ -492,14 +995,34 @@ export function triggerBackgroundWordIndexBuild(cwd, dbg, options = {}) {
492
995
  snapshot.wordIndex = serializeWordIndex(index);
493
996
  saveProjectSnapshot(key, snapshot);
494
997
  dbg?.(`word-index cold-build: ${index.docCount} files, ${index.postings.size} tokens (${Date.now() - startMs}ms)`);
998
+ // M2, #958: durable decision/coverage record for the MCP-critical cold
999
+ // path (this is where symbol_search reads the index and dbg is a no-op).
1000
+ logWordIndex({
1001
+ phase: "cold_build",
1002
+ cwd: key,
1003
+ trigger: "cold_query",
1004
+ durationMs: Date.now() - startMs,
1005
+ indexedFileCount: index.docCount,
1006
+ tokens: index.postings.size,
1007
+ truncated: index.truncated,
1008
+ skipped: docs.skipped,
1009
+ });
1010
+ buildStatuses.delete(key);
495
1011
  }
496
1012
  catch (err) {
497
- dbg?.(`word-index cold-build: failed: ${err}`);
498
- }
499
- finally {
500
- inFlightBuilds.delete(key);
1013
+ const reason = err instanceof Error ? err.message : String(err);
1014
+ buildStatuses.set(key, { state: "failed", reason });
1015
+ dbg?.(`word-index cold-build: failed: ${reason}`);
1016
+ logWordIndex({
1017
+ phase: "cold_build_failed",
1018
+ cwd: key,
1019
+ trigger: "cold_query",
1020
+ durationMs: Date.now() - startMs,
1021
+ error: reason,
1022
+ });
501
1023
  }
502
1024
  })();
1025
+ return status;
503
1026
  }
504
1027
  // --- Debounced per-edit persist (#348 phase 2) --------------------------------
505
1028
  //
@@ -552,9 +1075,30 @@ async function writeWordIndexSnapshot(cwd, index, dbg) {
552
1075
  snapshot.wordIndex = serializeWordIndex(index);
553
1076
  saveProjectSnapshot(cwd, snapshot);
554
1077
  dbg?.(`word-index persist: ${index.docCount} files, ${index.postings.size} tokens`);
1078
+ // #958 review F1: durably record persist SUCCESS too, not just failures —
1079
+ // in the MCP host (`dbg` is a no-op) this is the only signal that the index
1080
+ // is actually being kept fresh across edits. Debounced (~1.5s), so not
1081
+ // spammy. Mirrors the review graph's persist_succeeded.
1082
+ logWordIndex({
1083
+ phase: "persist_succeeded",
1084
+ cwd: path.resolve(cwd),
1085
+ trigger: "per_edit",
1086
+ indexedFileCount: index.docCount,
1087
+ tokens: index.postings.size,
1088
+ });
555
1089
  }
556
1090
  catch (err) {
557
1091
  dbg?.(`word-index persist: failed: ${err}`);
1092
+ // M3, #958: a swallowed persist means every LATER symbol_search reads a
1093
+ // stale index with no trace — the exact silent-failure this durable log
1094
+ // exists to surface (dbg is a no-op in the MCP host).
1095
+ logWordIndex({
1096
+ phase: "persist_failed",
1097
+ cwd: path.resolve(cwd),
1098
+ trigger: "per_edit",
1099
+ indexedFileCount: index.docCount,
1100
+ error: err instanceof Error ? err.message : String(err),
1101
+ });
558
1102
  }
559
1103
  }
560
1104
  /**