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
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Automatic smells self-surfacing (#1123 item 3).
3
+ *
4
+ * `scripts/analyze-pi-lens-logs.mjs` (`npm run logs:smells`) already detects
5
+ * a wide catalogue of operational smells, but it is MANUAL — an operator has
6
+ * to think to run it. The #1123 investigation found 20 stale-ctx
7
+ * `emit_failed` rows (see `session-lifecycle.ts`'s stale-ctx guard) and 37
8
+ * opengrep respawns sitting in logs for days before an audit went looking.
9
+ * This module closes that gap with a small, ALWAYS-ON rollup that surfaces a
10
+ * subset of the analyzer's smells without anyone running the script.
11
+ *
12
+ * COST BOUND (the constraint that shapes the design): `~/.pi-lens/*.log`
13
+ * files are size-rotated at `PI_LENS_MAX_LOG_SIZE_MB` (default 10MB,
14
+ * `clients/log-cleanup.ts`). Re-scanning a whole rotated log on every
15
+ * `session_start` — the analyzer's own approach — is exactly the megabyte
16
+ * full-file read `session_start` (a hot, input-latency-sensitive path, see
17
+ * `runtime-session.ts`'s cold-start comment) cannot afford. So this module
18
+ * does a BOUNDED TAIL READ: at most `SMELLS_TAIL_BYTES_PER_FILE` bytes from
19
+ * the END of each source log, via a single `pread`-style `fs.readSync` at a
20
+ * computed offset — never a full-file read, by construction (see
21
+ * `tailReadText`). Two source files, ~64KB each: ~128KB total I/O, once per
22
+ * session_start plus one bounded re-check every `SMELLS_TURN_CHECK_INTERVAL`
23
+ * turns — negligible next to the multi-second full startup walk it rides
24
+ * alongside.
25
+ *
26
+ * The tail scan is bounded, but the tail can contain prior-session rows. The
27
+ * session-start caller supplies the session boundary, and rows are admitted
28
+ * only when their own UTC timestamp is at or after that boundary. This keeps
29
+ * the same bounded read without reporting historical failures as current, so
30
+ * this module does not additionally instrument the write call sites
31
+ * (`bus-publish.ts`, `clients/lsp/index.ts`'s respawn path) with parallel
32
+ * live counters. That keeps the change contained to one new module + three
33
+ * small call sites (session_start, `/lens-health`, `turn_end`) instead of
34
+ * touching every producer of the two source logs.
35
+ *
36
+ * Smells covered (deliberately a SUBSET — the two the issue named as having
37
+ * gone unnoticed; the full catalogue stays in the manual analyzer):
38
+ * - stale-ctx `emit_failed`: `bus-events.log` rows where
39
+ * `outcome === "emit_failed"` and `error` contains the SDK's
40
+ * `"stale after session replacement"` fragment (the known-benign class
41
+ * `session-lifecycle.ts` documents — still worth a glance if it recurs
42
+ * often, since a HIGH count could mask a real regression).
43
+ * - opengrep respawns: `latency.log` rows where
44
+ * `phase === "lsp_server_respawn"` and `metadata.serverId === "opengrep"`
45
+ * (`clients/lsp/index.ts`'s existing respawn log point — unmodified).
46
+ *
47
+ * Both counters are gated by trivial threshold constants (`SMELLS_THRESHOLDS`)
48
+ * so a single stray event never surfaces noise — only a repeating pattern
49
+ * does, matching the analyzer's own low/medium/high severity gating.
50
+ */
51
+ import * as fs from "node:fs";
52
+ import * as path from "node:path";
53
+ import { getGlobalPiLensDir } from "./file-utils.js";
54
+ /** Bounded tail-read budget PER source log file — never a full-file scan. */
55
+ export const SMELLS_TAIL_BYTES_PER_FILE = 64 * 1024;
56
+ /** Re-check cadence at `turn_end`, mirroring `memory-sampler.ts`'s pattern —
57
+ * cheap enough (bounded ~128KB I/O) not to need finer throttling, but a
58
+ * fixed interval keeps it from running on every single turn. */
59
+ export const SMELLS_TURN_CHECK_INTERVAL = 20;
60
+ /** Trivial threshold constants (#1123 item 3's explicit design ask). Counts
61
+ * strictly below these never surface anywhere. */
62
+ export const SMELLS_THRESHOLDS = {
63
+ staleCtxEmitFailed: 5,
64
+ opengrepRespawn: 5,
65
+ };
66
+ const SMELL_LABELS = {
67
+ staleCtxEmitFailed: "stale-ctx emit_failed (bus-events.log)",
68
+ opengrepRespawn: "opengrep respawn (latency.log)",
69
+ };
70
+ const SMELL_KEYS = ["staleCtxEmitFailed", "opengrepRespawn"];
71
+ /**
72
+ * Read at most `maxBytes` from the END of `filePath`. Never reads more than
73
+ * that regardless of the file's actual size — the cost bound is enforced by
74
+ * construction (a single sized `fs.readSync` at a computed offset), not by a
75
+ * convention callers have to remember. Missing file / unreadable → "".
76
+ *
77
+ * The leading (possibly partial) line is dropped whenever the read started
78
+ * mid-file, since we can't tell if it's a truncated JSON row.
79
+ */
80
+ export function tailReadText(filePath, maxBytes) {
81
+ let fd;
82
+ try {
83
+ fd = fs.openSync(filePath, "r");
84
+ }
85
+ catch {
86
+ return "";
87
+ }
88
+ try {
89
+ const size = fs.fstatSync(fd).size;
90
+ const readBytes = Math.min(size, maxBytes);
91
+ if (readBytes <= 0)
92
+ return "";
93
+ const start = size - readBytes;
94
+ const buf = Buffer.alloc(readBytes);
95
+ fs.readSync(fd, buf, 0, readBytes, start);
96
+ const text = buf.toString("utf8");
97
+ if (start <= 0)
98
+ return text;
99
+ const firstNewline = text.indexOf("\n");
100
+ return firstNewline >= 0 ? text.slice(firstNewline + 1) : "";
101
+ }
102
+ catch {
103
+ return "";
104
+ }
105
+ finally {
106
+ try {
107
+ fs.closeSync(fd);
108
+ }
109
+ catch {
110
+ /* already closed / nothing to do */
111
+ }
112
+ }
113
+ }
114
+ function countMatchingLines(text, predicate, sessionStartMs) {
115
+ let count = 0;
116
+ for (const line of text.split("\n")) {
117
+ if (!line.trim())
118
+ continue;
119
+ let entry;
120
+ try {
121
+ entry = JSON.parse(line);
122
+ }
123
+ catch {
124
+ continue; // partial/corrupt line at the tail boundary — skip, don't throw
125
+ }
126
+ if (entry &&
127
+ typeof entry === "object" &&
128
+ (sessionStartMs === undefined ||
129
+ isAtOrAfterSessionStart(entry, sessionStartMs)) &&
130
+ predicate(entry)) {
131
+ count++;
132
+ }
133
+ }
134
+ return count;
135
+ }
136
+ function isAtOrAfterSessionStart(entry, sessionStartMs) {
137
+ const timestamp = typeof entry.ts === "string" ? Date.parse(entry.ts) : NaN;
138
+ return Number.isFinite(timestamp) && timestamp >= sessionStartMs;
139
+ }
140
+ function isStaleCtxEmitFailed(entry) {
141
+ return (entry.outcome === "emit_failed" &&
142
+ typeof entry.error === "string" &&
143
+ entry.error.includes("stale after session replacement"));
144
+ }
145
+ function isOpengrepRespawn(entry) {
146
+ if (entry.phase !== "lsp_server_respawn")
147
+ return false;
148
+ const metadata = entry.metadata;
149
+ return metadata?.serverId === "opengrep";
150
+ }
151
+ /**
152
+ * Bounded tail-scan of the two source logs. Total I/O is capped at
153
+ * `2 * SMELLS_TAIL_BYTES_PER_FILE` regardless of how large the (size-rotated,
154
+ * up to ~10MB) source files are. `root` is injectable for tests.
155
+ */
156
+ export function countRecentSmells(root = getGlobalPiLensDir(), sessionStartMs) {
157
+ const busTail = tailReadText(path.join(root, "bus-events.log"), SMELLS_TAIL_BYTES_PER_FILE);
158
+ const latencyTail = tailReadText(path.join(root, "latency.log"), SMELLS_TAIL_BYTES_PER_FILE);
159
+ return {
160
+ staleCtxEmitFailed: countMatchingLines(busTail, isStaleCtxEmitFailed, sessionStartMs),
161
+ opengrepRespawn: countMatchingLines(latencyTail, isOpengrepRespawn, sessionStartMs),
162
+ };
163
+ }
164
+ /**
165
+ * One `sessionstart.log` line, gated to fire only when at least one smell is
166
+ * AT/ABOVE its threshold — `null` (nothing logged) otherwise, so an ordinary
167
+ * session never gets a noise line. Pairs with `logSessionStart` the same way
168
+ * every other `session_start ...` line does (see `runtime-session.ts`).
169
+ */
170
+ export function formatSmellsSessionStartLine(counts) {
171
+ const bits = [];
172
+ for (const key of SMELL_KEYS) {
173
+ if (counts[key] >= SMELLS_THRESHOLDS[key]) {
174
+ bits.push(`${SMELL_LABELS[key]} x${counts[key]}`);
175
+ }
176
+ }
177
+ if (bits.length === 0)
178
+ return null;
179
+ const tailKb = Math.round(SMELLS_TAIL_BYTES_PER_FILE / 1024);
180
+ return `session_start smells (last ${tailKb}KB tail): ${bits.join(", ")} — run \`npm run logs:smells\` for detail`;
181
+ }
182
+ /**
183
+ * Compact, ALWAYS-shown `/lens-health` line (unconditional, like
184
+ * `memory-sampler.ts`'s `formatMemoryHealthLine` — the health command is
185
+ * explicitly requested, so it always renders current counts even when
186
+ * everything is below threshold).
187
+ */
188
+ export function formatSmellsHealthLine(counts) {
189
+ return (`Smells (recent tail-scan): stale-ctx emit_failed=${counts.staleCtxEmitFailed}` +
190
+ ` · opengrep respawn=${counts.opengrepRespawn}`);
191
+ }
192
+ /** `true` on turn 20, 40, 60, ... — never turn 0. Pure so the cadence is
193
+ * unit-testable without driving a real turn loop (mirrors
194
+ * `memory-sampler.ts`'s `shouldEmitMemorySample`). */
195
+ export function shouldCheckSmellsThisTurn(turnIndex) {
196
+ return turnIndex > 0 && turnIndex % SMELLS_TURN_CHECK_INTERVAL === 0;
197
+ }
198
+ // Module-scope session state: which smells have already produced a turn-end
199
+ // note THIS session. Bounded to once per session per smell by construction —
200
+ // see `checkSmellsAndNoteOnce`.
201
+ const notifiedThisSession = new Set();
202
+ /**
203
+ * Given a fresh `counts` read, return zero or more turn-end note strings for
204
+ * smells crossing threshold for the FIRST time this session. A smell already
205
+ * notified this session never fires again, even if its count keeps growing —
206
+ * "once per session per smell" per #1123 item 3's design ask.
207
+ */
208
+ export function checkSmellsAndNoteOnce(counts) {
209
+ const notes = [];
210
+ for (const key of SMELL_KEYS) {
211
+ if (notifiedThisSession.has(key))
212
+ continue;
213
+ if (counts[key] >= SMELLS_THRESHOLDS[key]) {
214
+ notifiedThisSession.add(key);
215
+ notes.push(`pi-lens smell: ${SMELL_LABELS[key]} x${counts[key]} (recent tail-scan) — run \`npm run logs:smells\` for detail`);
216
+ }
217
+ }
218
+ return notes;
219
+ }
220
+ /** Reset the "already notified this session" state — call at `session_start`
221
+ * (a fresh session should be able to re-report) and from tests. */
222
+ export function resetSmellsSessionState() {
223
+ notifiedThisSession.clear();
224
+ }
@@ -19,7 +19,9 @@
19
19
  import * as fs from "node:fs";
20
20
  import * as path from "node:path";
21
21
  import { getProjectIgnoreMatcher } from "./file-utils.js";
22
- import { isDeclarationFile, isGeneratedOrArtifact, } from "./generated-artifacts.js";
22
+ import { classifyGeneratedOrArtifactDetailed, isDeclarationFile, } from "./generated-artifacts.js";
23
+ import { isCodeKindFile, KIND_EXTENSIONS } from "./file-kinds.js";
24
+ import { logLatency } from "./latency-logger.js";
23
25
  import { normalizeEphemeralMapKey } from "./path-utils.js";
24
26
  import { isSlowFs, SLOW_FS_REDUCED_MAX_FILES } from "./slow-fs.js";
25
27
  import { shouldRecurseIntoDir, walkTreeRecursiveSync, walkTreeStackAsync, } from "./source-walker.js";
@@ -48,32 +50,64 @@ function probeExists(filePath, cache) {
48
50
  * Order matters: first entry has highest precedence.
49
51
  */
50
52
  export const SOURCE_PRECEDENCE = {
51
- ".ts": [".js", ".mjs", ".cjs"],
53
+ ".ts": [".js", ".jsx", ".mjs", ".cjs"],
52
54
  ".tsx": [".jsx", ".js", ".mjs", ".cjs"],
55
+ ".mts": [".mjs", ".js", ".jsx", ".cjs"],
56
+ ".cts": [".cjs", ".js", ".jsx", ".mjs"],
53
57
  ".vue": [".js", ".mjs"],
54
58
  ".svelte": [".js", ".mjs"],
55
59
  ".coffee": [".js"],
56
60
  };
57
61
  /**
58
- * All extensions that could be source or artifacts, in precedence order.
62
+ * Return source-twin candidates in the policy order for a compiled path.
63
+ * This is the pure counterpart to {@link findSourceSibling}: callers that
64
+ * already have a complete file identity set (the review graph and lens map)
65
+ * must not probe the filesystem or reimplement the extension matrix.
66
+ */
67
+ export function sourceTwinCandidates(filePath) {
68
+ const ext = path.extname(filePath).toLowerCase();
69
+ const stem = filePath.slice(0, filePath.length - ext.length);
70
+ const sourceExts = ext === ".mjs"
71
+ ? [".mts", ".ts", ".tsx", ".cts"]
72
+ : ext === ".cjs"
73
+ ? [".cts", ".ts", ".tsx", ".mts"]
74
+ : ext === ".jsx"
75
+ // Deliberately retain the broad fallback: a .jsx next to a .ts
76
+ // is treated as a build artifact even without a .tsx sibling.
77
+ ? [".tsx", ".ts", ".mts", ".cts"]
78
+ : ext === ".js"
79
+ ? [".ts", ".tsx", ".mts", ".cts"]
80
+ : [];
81
+ return sourceExts.map((sourceExt) => `${stem}${sourceExt}`);
82
+ }
83
+ /**
84
+ * Resolve a compiled file to its canonical source identity within a known
85
+ * file set. The caller supplies normalized identities; this helper deliberately
86
+ * does not touch the filesystem, so complete source-set walks remain bounded
87
+ * and point-in-time consistent.
88
+ */
89
+ export function canonicalSourceTwin(filePath, availableFiles, excludedFiles) {
90
+ for (const candidate of sourceTwinCandidates(filePath)) {
91
+ if (availableFiles.has(candidate) && !excludedFiles?.has(candidate)) {
92
+ return candidate;
93
+ }
94
+ }
95
+ return filePath;
96
+ }
97
+ /**
98
+ * Every extension belonging to a supported file kind. KIND_EXTENSIONS is the
99
+ * single language-extension authority; deriving here makes a newly registered
100
+ * kind project-scannable without a second hand-maintained list (#894).
101
+ *
102
+ * SOURCE_PRECEDENCE contributes `.coffee`, the one legacy shadowing source that
103
+ * is intentionally not a supported FileKind. Generated files and declarations
104
+ * are narrowed by generated-artifacts.ts after this extension gate.
59
105
  */
60
106
  export const ALL_SCANNABLE_EXTENSIONS = [
61
- ".ts",
62
- ".tsx",
63
- ".js",
64
- ".jsx",
65
- ".mjs",
66
- ".cjs",
67
- ".vue",
68
- ".svelte",
69
- ".coffee",
70
- ".py",
71
- ".go",
72
- ".rs",
73
- ".rb",
74
- ".rake",
75
- ".gemspec",
76
- ".ru",
107
+ ...new Set([
108
+ ...Object.values(KIND_EXTENSIONS).flat(),
109
+ ...Object.keys(SOURCE_PRECEDENCE),
110
+ ]),
77
111
  ];
78
112
  /**
79
113
  * Structural safety net for the source-file walk (#250/#747 escape class).
@@ -118,16 +152,107 @@ export const DEFAULT_MAX_SOURCE_FILES = 20000;
118
152
  * `project-scale.ts`'s file header for the full rationale.
119
153
  */
120
154
  export const DEFAULT_MAX_SCAN_ENTRIES = 200_000;
121
- function shouldSkipGeneratedOrArtifact(filePath, options) {
155
+ /**
156
+ * Kept-files accumulator shared by the sync/async collectors, so the
157
+ * `prioritizeCodeKinds` policy (#894 review) lives in one place. In the
158
+ * default mode it is a plain array with the pre-existing `maxFiles` stop
159
+ * check; in prioritized mode code-kind files alone satisfy the cap and
160
+ * non-code files only fill whatever budget the code files leave unused.
161
+ */
162
+ function createKeptFilesAccumulator(maxFiles, prioritizeCodeKinds) {
163
+ if (!prioritizeCodeKinds) {
164
+ const files = [];
165
+ return {
166
+ push: (file) => void files.push(file),
167
+ isFull: () => files.length >= maxFiles,
168
+ list: () => files,
169
+ };
170
+ }
171
+ const codeFiles = [];
172
+ const otherFiles = [];
173
+ return {
174
+ push(file) {
175
+ if (isCodeKindFile(file))
176
+ codeFiles.push(file);
177
+ else if (otherFiles.length < maxFiles)
178
+ otherFiles.push(file);
179
+ },
180
+ isFull: () => codeFiles.length >= maxFiles,
181
+ list: () => [...codeFiles, ...otherFiles].slice(0, maxFiles),
182
+ };
183
+ }
184
+ function createSourceWalkSkipCounters() {
185
+ return {
186
+ generatedOrArtifactSkips: 0,
187
+ buildArtifactSkips: 0,
188
+ generatedDirSkips: 0,
189
+ generatedNameOverrides: 0,
190
+ generatedNameOnlySkips: 0,
191
+ };
192
+ }
193
+ /**
194
+ * Log a one-line rollup for a walk's skip counters through the existing
195
+ * latency/scan logging channel (`logLatency`, ndjson `latency.log`) — mirrors
196
+ * how `getGraphSourceFiles` logs `review_graph_source_walk_entry_budget`.
197
+ * Silent (no log line) when both counters are zero, so a healthy walk with no
198
+ * name/artifact-probe skips produces no new log noise.
199
+ *
200
+ * Logged once per walk call, at the walk layer itself
201
+ * (`collectSourceFilesWithBudget`/`collectSourceFilesWithBudgetAsync`) rather
202
+ * than at each of its several consumers (review-graph builder, project-
203
+ * diagnostics scanner, word-index, …): every one of those consumers funnels
204
+ * through these two functions (directly or via the plain `collectSourceFiles`/
205
+ * `collectSourceFilesAsync` wrappers), so logging here is a single choke point
206
+ * that covers all of them — the smaller diff versus exporting the counters and
207
+ * wiring a log call into each consumer separately.
208
+ */
209
+ function logSourceWalkSkipsIfAny(rootDir, counters) {
210
+ if (counters.generatedOrArtifactSkips === 0 &&
211
+ counters.buildArtifactSkips === 0 &&
212
+ counters.generatedDirSkips === 0 &&
213
+ counters.generatedNameOverrides === 0) {
214
+ return;
215
+ }
216
+ logLatency({
217
+ type: "phase",
218
+ phase: "source_walk_skip_summary",
219
+ filePath: rootDir,
220
+ durationMs: 0,
221
+ metadata: {
222
+ generatedOrArtifactSkips: counters.generatedOrArtifactSkips,
223
+ buildArtifactSkips: counters.buildArtifactSkips,
224
+ generatedDirSkips: counters.generatedDirSkips,
225
+ generatedNameOverrides: counters.generatedNameOverrides,
226
+ generatedNameOnlySkips: counters.generatedNameOnlySkips,
227
+ },
228
+ });
229
+ }
230
+ /**
231
+ * Full verdict+evidence form of {@link shouldSkipGeneratedOrArtifact} (#1107
232
+ * phase 2) — exposes `classifyGeneratedOrArtifactDetailed`'s `"override"`
233
+ * outcome (a WEAK name-only match the content-probe escape hatch rescued)
234
+ * AND, for a `"generated"` verdict, WHICH evidence tier decided it, so
235
+ * `classifyEntry` can count a genuine skip, a rescue, and the residual
236
+ * "unconfirmed name-only skip" bucket all distinctly. See
237
+ * `GeneratedArtifactEvidence`'s doc for why the tier split matters: a
238
+ * tool-facing notice keyed on the RAW skip count fires permanently on any
239
+ * repo with a lockfile, drowning the signal it exists to surface.
240
+ */
241
+ function classifySkipGeneratedOrArtifact(filePath, options) {
122
242
  const includeDeclarations = options?.includeDeclarationFiles === true;
123
243
  if (options?.includeGenerated === true) {
124
- return !includeDeclarations && isDeclarationFile(filePath);
244
+ return !includeDeclarations && isDeclarationFile(filePath)
245
+ ? { verdict: "generated", evidence: "strong" }
246
+ : { verdict: "clean" };
125
247
  }
126
- return isGeneratedOrArtifact(filePath, {
248
+ return classifyGeneratedOrArtifactDetailed(filePath, {
127
249
  readContentHeader: options?.inspectGeneratedHeaders !== false,
128
250
  includeDeclarations: !includeDeclarations,
129
251
  });
130
252
  }
253
+ function shouldSkipGeneratedOrArtifact(filePath, options) {
254
+ return classifySkipGeneratedOrArtifact(filePath, options).verdict === "generated";
255
+ }
131
256
  /**
132
257
  * Extract the basename (filename without extension) from a path.
133
258
  */
@@ -146,17 +271,20 @@ function getDir(filePath) {
146
271
  * Returns the shadowing source file path if found, null otherwise.
147
272
  */
148
273
  export function findSourceSibling(filePath, probeCache) {
274
+ for (const candidate of sourceTwinCandidates(filePath)) {
275
+ if (probeExists(candidate, probeCache))
276
+ return candidate;
277
+ }
278
+ // Keep the legacy non-JS source policies (Vue/Svelte/CoffeeScript) on the
279
+ // same seam without making them part of the JS/TS twin matrix above.
149
280
  const ext = path.extname(filePath).toLowerCase();
150
281
  const dir = getDir(filePath);
151
282
  const base = getBasename(filePath);
152
- // Find which precedence group this extension belongs to
153
283
  for (const [sourceExt, shadowedExts] of Object.entries(SOURCE_PRECEDENCE)) {
154
- if (shadowedExts.includes(ext)) {
155
- // This file could be shadowed by a source file with sourceExt
284
+ if (!sourceExtsForCompiledExt(sourceExt).length && shadowedExts.includes(ext)) {
156
285
  const siblingPath = path.join(dir, base + sourceExt);
157
- if (probeExists(siblingPath, probeCache)) {
286
+ if (probeExists(siblingPath, probeCache))
158
287
  return siblingPath;
159
- }
160
288
  }
161
289
  }
162
290
  return null;
@@ -167,6 +295,11 @@ export function findSourceSibling(filePath, probeCache) {
167
295
  * @param probeCache - Optional per-walk memo (see {@link ArtifactProbeCache}).
168
296
  * Omit for the original, uncached behavior.
169
297
  */
298
+ function sourceExtsForCompiledExt(sourceExt) {
299
+ return sourceExt === ".ts" || sourceExt === ".tsx" || sourceExt === ".mts" || sourceExt === ".cts"
300
+ ? [sourceExt]
301
+ : [];
302
+ }
170
303
  export function isBuildArtifact(filePath, probeCache) {
171
304
  return findSourceSibling(filePath, probeCache) !== null;
172
305
  }
@@ -237,7 +370,7 @@ function resolveCollectionConfig(rootDir, options, config) {
237
370
  * produce identical results — the only difference between the two is that the
238
371
  * async variant yields to the event loop every N entries.
239
372
  */
240
- function classifyEntry(entry, fullPath, cfg, probeCache) {
373
+ function classifyEntry(entry, fullPath, cfg, probeCache, skipCounters) {
241
374
  const { ignoreMatcher, extraExcludePatterns, extensions, options } = cfg;
242
375
  if (entry.isDirectory()) {
243
376
  const canRecurse = shouldRecurseIntoDir(entry, fullPath, {
@@ -245,7 +378,14 @@ function classifyEntry(entry, fullPath, cfg, probeCache) {
245
378
  extraExcludeDirs: extraExcludePatterns,
246
379
  skipGeneratedArtifactDirs: options?.includeGenerated !== true,
247
380
  followSymlinks: options?.followSymlinks === true,
248
- });
381
+ },
382
+ // #1107 phase 2: counts one event per PRUNED DIRECTORY, not per file
383
+ // inside it — see `generatedDirSkips`'s doc on `SourceCollectionResult`.
384
+ skipCounters
385
+ ? () => {
386
+ skipCounters.generatedDirSkips += 1;
387
+ }
388
+ : undefined);
249
389
  if (!canRecurse)
250
390
  return {};
251
391
  return { recurseInto: fullPath };
@@ -257,10 +397,35 @@ function classifyEntry(entry, fullPath, cfg, probeCache) {
257
397
  if (!extensions.has(ext))
258
398
  return {};
259
399
  // Skip if this is a build artifact or generated/codegen output.
260
- if (isBuildArtifact(fullPath, probeCache))
400
+ // #1107: counted separately (both are observability-only — neither
401
+ // changes what gets skipped) so an invisible coverage hole (a real
402
+ // `src/gen.ts` silently dropped by the name heuristic) is at least
403
+ // visible via `SourceCollectionResult` and the walk's rollup log line.
404
+ if (isBuildArtifact(fullPath, probeCache)) {
405
+ if (skipCounters)
406
+ skipCounters.buildArtifactSkips += 1;
261
407
  return {};
262
- if (shouldSkipGeneratedOrArtifact(fullPath, options))
408
+ }
409
+ // #1107 phase 2: the content-probe escape hatch can rescue a WEAK
410
+ // name-only match ("override") instead of skipping it — see
411
+ // `classifyGeneratedOrArtifactDetailed`'s doc for the evidence
412
+ // order/tradeoff. `evidence` additionally distinguishes a STRONG/
413
+ // content-CONFIRMED skip (expected, not a coverage-hole signal) from
414
+ // the residual "name-only" skip (unconfirmed — the one bucket a
415
+ // tool-facing notice should actually key off).
416
+ const classification = classifySkipGeneratedOrArtifact(fullPath, options);
417
+ if (classification.verdict === "generated") {
418
+ if (skipCounters) {
419
+ skipCounters.generatedOrArtifactSkips += 1;
420
+ if (classification.evidence === "name-only") {
421
+ skipCounters.generatedNameOnlySkips += 1;
422
+ }
423
+ }
263
424
  return {};
425
+ }
426
+ if (classification.verdict === "override" && skipCounters) {
427
+ skipCounters.generatedNameOverrides += 1;
428
+ }
264
429
  return { keepFile: fullPath };
265
430
  }
266
431
  return {};
@@ -291,29 +456,40 @@ export function collectSourceFilesWithBudget(dir, options) {
291
456
  const cfg = resolveCollectionConfig(rootDir, options, {
292
457
  clampForSlowFsSyncWalk: true,
293
458
  });
294
- const files = [];
459
+ const kept = createKeptFilesAccumulator(cfg.maxFiles, options?.prioritizeCodeKinds === true);
295
460
  // Per-walk sibling-probe memo (refs #191, item 1). Created here, discarded
296
461
  // on return — never persisted across calls.
297
462
  const probeCache = createArtifactProbeCache();
298
463
  const budget = createEntryBudget(cfg.maxScanEntries);
464
+ // #1107: per-walk skip counters, discarded on return like the probe cache.
465
+ const skipCounters = createSourceWalkSkipCounters();
299
466
  // #761: immediate-descent recursion driver (result-array order preserved),
300
467
  // with both caps kept as this walker's own per-entry policy: the hard
301
468
  // `maxFiles` results cap (#250) is checked BEFORE charging the entry budget
302
469
  // (#760), and a file that reaches `maxFiles` is the last one kept — the cap
303
470
  // then trips on the following entry, matching the pre-#761 loop exactly.
304
471
  walkTreeRecursiveSync(rootDir, (entry, fullPath) => {
305
- if (files.length >= cfg.maxFiles)
472
+ if (kept.isFull())
306
473
  return "stop"; // hard cap (#250)
307
474
  if (!chargeEntryBudget(budget))
308
475
  return "stop"; // entry budget (#760)
309
- const { recurseInto, keepFile } = classifyEntry(entry, fullPath, cfg, probeCache);
476
+ const { recurseInto, keepFile } = classifyEntry(entry, fullPath, cfg, probeCache, skipCounters);
310
477
  if (recurseInto)
311
478
  return "recurse";
312
479
  if (keepFile)
313
- files.push(keepFile);
480
+ kept.push(keepFile);
314
481
  return "skip";
315
482
  });
316
- return { files, entryBudgetExceeded: budget.exceeded };
483
+ logSourceWalkSkipsIfAny(rootDir, skipCounters);
484
+ return {
485
+ files: kept.list(),
486
+ entryBudgetExceeded: budget.exceeded,
487
+ generatedOrArtifactSkips: skipCounters.generatedOrArtifactSkips,
488
+ buildArtifactSkips: skipCounters.buildArtifactSkips,
489
+ generatedDirSkips: skipCounters.generatedDirSkips,
490
+ generatedNameOverrides: skipCounters.generatedNameOverrides,
491
+ generatedNameOnlySkips: skipCounters.generatedNameOnlySkips,
492
+ };
317
493
  }
318
494
  export function collectSourceFiles(dir, options) {
319
495
  return collectSourceFilesWithBudget(dir, options).files;
@@ -321,7 +497,7 @@ export function collectSourceFiles(dir, options) {
321
497
  /**
322
498
  * Async, chunked-yield twin of {@link collectSourceFiles}. Returns the exact
323
499
  * same file list (it shares `classifyEntry`), but yields to the event loop
324
- * every `yieldEvery` directory entries so a large tree never holds the loop in
500
+ * on a monotonic time budget so a large tree never holds the loop in
325
501
  * one synchronous burst.
326
502
  *
327
503
  * Why this exists: on a ~2k-file project the synchronous `collectSourceFiles`
@@ -342,26 +518,29 @@ export async function collectSourceFilesAsync(dir, options) {
342
518
  export async function collectSourceFilesWithBudgetAsync(dir, options) {
343
519
  const rootDir = path.resolve(dir);
344
520
  const cfg = resolveCollectionConfig(rootDir, options);
345
- const files = [];
521
+ const kept = createKeptFilesAccumulator(cfg.maxFiles, options?.prioritizeCodeKinds === true);
346
522
  // Per-walk sibling-probe memo (refs #191, item 1). A single async walk is
347
523
  // still one point-in-time snapshot despite yielding between chunks, so
348
524
  // caching across the whole call remains invalidation-free.
349
525
  const probeCache = createArtifactProbeCache();
350
526
  const budget = createEntryBudget(cfg.maxScanEntries);
527
+ // #1107: per-walk skip counters, discarded on return like the probe cache.
528
+ const skipCounters = createSourceWalkSkipCounters();
351
529
  // #761: shared depth-first stack driver (its reverse-push mirrors the sync
352
530
  // collector's left-to-right recursion). The async collector charges the
353
531
  // entry budget (#760) FIRST, then checks the `maxFiles` cap immediately
354
532
  // after keeping a file — subtly different from the sync collector's ordering
355
533
  // but preserved verbatim, so both stay byte-identical to their pre-#761 form.
356
534
  await walkTreeStackAsync(rootDir, (entry, fullPath) => {
535
+ options?.onEntryVisited?.();
357
536
  if (!chargeEntryBudget(budget))
358
537
  return "stop"; // entry budget (#760)
359
- const { recurseInto, keepFile } = classifyEntry(entry, fullPath, cfg, probeCache);
538
+ const { recurseInto, keepFile } = classifyEntry(entry, fullPath, cfg, probeCache, skipCounters);
360
539
  if (recurseInto)
361
540
  return "recurse";
362
541
  if (keepFile) {
363
- files.push(keepFile);
364
- if (files.length >= cfg.maxFiles)
542
+ kept.push(keepFile);
543
+ if (kept.isFull())
365
544
  return "stop"; // hard cap (#250)
366
545
  }
367
546
  return "skip";
@@ -370,13 +549,22 @@ export async function collectSourceFilesWithBudgetAsync(dir, options) {
370
549
  // even on a cold scan where every kept file pays the 4 KB generated-
371
550
  // header read (measured on a 2k-file fixture). Larger values regress
372
551
  // past the ~50ms event-loop budget; see PERF-AUDIT.md.
373
- yieldEvery: Math.max(1, options?.yieldEvery ?? 50),
552
+ budgetMs: Math.max(1, options?.budgetMs ?? 8),
374
553
  // #703: prime the tracked-files set once before the walk so a tracked
375
554
  // file matching a `.gitignore`/global pattern still surfaces. Fail-open
376
555
  // on no-git/spawn failure.
377
556
  beforeWalk: () => cfg.ignoreMatcher.ensureTrackedIndex(),
378
557
  });
379
- return { files, entryBudgetExceeded: budget.exceeded };
558
+ logSourceWalkSkipsIfAny(rootDir, skipCounters);
559
+ return {
560
+ files: kept.list(),
561
+ entryBudgetExceeded: budget.exceeded,
562
+ generatedOrArtifactSkips: skipCounters.generatedOrArtifactSkips,
563
+ buildArtifactSkips: skipCounters.buildArtifactSkips,
564
+ generatedDirSkips: skipCounters.generatedDirSkips,
565
+ generatedNameOverrides: skipCounters.generatedNameOverrides,
566
+ generatedNameOnlySkips: skipCounters.generatedNameOnlySkips,
567
+ };
380
568
  }
381
569
  /**
382
570
  * Get statistics about source file filtering for debugging/monitoring.