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
@@ -3,29 +3,36 @@ import * as path from "node:path";
3
3
  import { deadCodeIssueCount } from "./dead-code-client.js";
4
4
  import { logDeadCodeScan } from "./dead-code-logger.js";
5
5
  import { getDiagnosticTracker } from "./diagnostic-tracker.js";
6
+ import { resetDegradationLedger } from "./degradation-ledger.js";
7
+ import { resetDispatchAvailabilityState } from "./dispatch/runners/utils/runner-helpers.js";
6
8
  import { clearAllSessions as clearFileTimeSessions } from "./file-time.js";
7
- import { getKnipIgnorePatterns } from "./file-utils.js";
8
- import { clearTsconfigPathsCache } from "./review-graph/tsconfig-paths.js";
9
- import { resetSafeSpawnWindowsCommandCache } from "./safe-spawn.js";
10
- import { resetWorkspaceTopology } from "./workspace-topology.js";
9
+ import { createDeadline, yieldIfOverBudget } from "./cooperative-budget.js";
10
+ import { getGlobalPiLensDir, getKnipIgnorePatterns, getProjectDataDir, } from "./file-utils.js";
11
11
  import { GitleaksClient } from "./gitleaks-client.js";
12
- import { TrivyClient } from "./trivy-client.js";
13
12
  import { GovulncheckClient, } from "./govulncheck-client.js";
14
13
  import { canRunStartupHeavyScans } from "./language-policy.js";
15
14
  import { detectProjectLanguageProfile, getDefaultStartupTools, } from "./language-profile.js";
16
15
  import { logLatency } from "./latency-logger.js";
17
16
  import { runLogCleanup } from "./log-cleanup.js";
18
- import { setSessionLanguages } from "./widget-state.js";
19
17
  import { initLSPConfig, loadLSPConfig } from "./lsp/config.js";
20
- import { getLSPService } from "./lsp/index.js";
21
- import { readLatestProjectSequence } from "./project-changes.js";
22
- import { getProjectSnapshotPath, hydrateRuntimeFromProjectSnapshot, isProjectSnapshotFresh, loadProjectSnapshot, saveRuntimeProjectSnapshot, } from "./project-snapshot.js";
23
- import { scanProjectRules } from "./rules-scanner.js";
18
+ import { loadLspService } from "./lsp-lazy.js";
24
19
  import { isAtOrAboveHomeDir } from "./path-utils.js";
20
+ import { isPrintMode } from "./print-mode.js";
21
+ import { readLatestProjectSequence, readLatestProjectSequenceAsync, } from "./project-changes.js";
22
+ import { getProjectSnapshotPath, hydrateRuntimeFromProjectSnapshot, isProjectSnapshotFresh, isProjectSnapshotMetaStale, loadProjectSnapshot, PROJECT_SNAPSHOT_VERSION, readProjectSnapshotMeta, saveRuntimeProjectSnapshot, } from "./project-snapshot.js";
23
+ import { clearTsconfigPathsCache } from "./review-graph/tsconfig-paths.js";
24
+ import { scanProjectRules } from "./rules-scanner.js";
25
+ import { resetSafeSpawnWindowsCommandCache } from "./safe-spawn.js";
25
26
  import { getSlowFsVerdict, isSlowFs, slowFsDegradationNotice, } from "./slow-fs.js";
26
- import { getSubagentIdentity, isSubagentSession, subagentLightModeNotice, } from "./subagent-mode.js";
27
+ import { countRecentSmells, formatSmellsSessionStartLine, resetSmellsSessionState, } from "./smells-rollup.js";
27
28
  import { findNearestProjectRoot, getStartupScanMaxEntries, isStartupScanVerdictFresh, resolveStartupScanContext, } from "./startup-scan.js";
29
+ import { getSubagentIdentity, isSubagentSession, subagentLightModeNotice, } from "./subagent-mode.js";
30
+ import { sweepAtomicWriteStages } from "./instance-reaper.js";
31
+ import { TrivyClient } from "./trivy-client.js";
28
32
  import { isWarmAttached } from "./warm-attach.js";
33
+ import { setSessionLanguages } from "./widget-state.js";
34
+ import { logWordIndex } from "./word-index-logger.js";
35
+ import { resetWorkspaceTopology } from "./workspace-topology.js";
29
36
  function resolveSnapshotRoot(cwd) {
30
37
  const resolvedCwd = path.resolve(cwd);
31
38
  const nearest = findNearestProjectRoot(resolvedCwd);
@@ -36,6 +43,53 @@ function resolveSnapshotRoot(cwd) {
36
43
  }
37
44
  return nearest;
38
45
  }
46
+ /**
47
+ * #947: meta-first staleness gate. Both interactive paths used to sync-parse
48
+ * the whole `project-snapshot.json` body (110-130ms at 40MB, ~0.5s at the
49
+ * observed 112MB) BEFORE checking freshness — wasted work in the 71% of
50
+ * sessions where the snapshot turns out stale. Read the tiny meta sidecar
51
+ * (`project-snapshot.meta.json`, written on every save) first; when it says
52
+ * stale (seq or version mismatch — the exact fields `isProjectSnapshotFresh`
53
+ * checks), skip the body parse entirely. Callers already tolerate a missing
54
+ * snapshot (fail-open contract). A missing meta file (legacy install, or a
55
+ * snapshot written before the sidecar existed) falls through to parsing the
56
+ * body exactly as before.
57
+ */
58
+ /**
59
+ * #1019: build the bounded-replay base from the snapshot's tiny meta sidecar.
60
+ * The sequence index is mirrored into the meta (not just the body) precisely so
61
+ * this read is cheap — reading it does NOT parse the 40-112MB body, preserving
62
+ * the #947 skip-stale optimization. Returns `undefined` (→ full replay) for a
63
+ * legacy meta with no embedded index, a version-mismatched meta (a foreign
64
+ * snapshot generation), or a missing meta. A seq-stale meta is NOT rejected
65
+ * here — folding the newer entries onto it is the whole point; the base's
66
+ * trustworthiness against a truncated/ahead log is guarded inside
67
+ * `readLatestProjectSequence` itself.
68
+ */
69
+ function snapshotSequenceBase(root) {
70
+ const meta = readProjectSnapshotMeta(root);
71
+ if (!meta || meta.version !== PROJECT_SNAPSHOT_VERSION)
72
+ return undefined;
73
+ const index = meta.sequenceIndex;
74
+ if (!index)
75
+ return undefined;
76
+ return {
77
+ projectSeq: index.projectSeq,
78
+ fileSeqByPath: index.fileSeqByPath,
79
+ sinceSeq: meta.seq,
80
+ };
81
+ }
82
+ function loadSnapshotBodyUnlessStale(args) {
83
+ const meta = readProjectSnapshotMeta(args.root);
84
+ if (meta && isProjectSnapshotMetaStale(meta, args.currentProjectSeq)) {
85
+ args.dbg(`project_snapshot: meta gate stale (metaSeq=${meta.seq} metaVersion=${meta.version} current=${args.currentProjectSeq}) — skipping body parse`);
86
+ return { snapshot: null, skippedStale: true };
87
+ }
88
+ return {
89
+ snapshot: loadProjectSnapshot(args.root),
90
+ skippedStale: false,
91
+ };
92
+ }
39
93
  function describeSnapshotMiss(snapshot, currentProjectSeq) {
40
94
  if (!snapshot)
41
95
  return "missing";
@@ -58,20 +112,135 @@ function resolveStartupMode() {
58
112
  if (envMode === "full" || envMode === "minimal" || envMode === "quick") {
59
113
  return envMode;
60
114
  }
61
- const argv = process.argv;
62
- if (argv.includes("--print") || argv.includes("-p")) {
115
+ if (isPrintMode()) {
63
116
  return "quick";
64
117
  }
65
118
  return "full";
66
119
  }
67
120
  // --- Session-start helpers ---
121
+ // #1162: bound the session_start sequence read to this budget. The default
122
+ // mirrors the issue's ~250ms figure; overridable for tests (mirrors the
123
+ // `PI_LENS_WARMUP_DELAY_MS` precedent above) so a regression can use a tiny
124
+ // budget instead of racing a real 250ms wall-clock wait.
125
+ function sequenceReadBudgetMs() {
126
+ const raw = Number(process.env.PI_LENS_SEQUENCE_READ_BUDGET_MS ?? 250);
127
+ return Number.isFinite(raw) && raw > 0 ? raw : 250;
128
+ }
129
+ // #1162 review follow-up (P3): the sentinel used ONLY for the snapshot
130
+ // freshness check (`isProjectSnapshotFresh`/`isProjectSnapshotMetaStale`,
131
+ // both `=== currentProjectSeq` equality) when a sequence read timed out.
132
+ // Every real `projectSeq`/`snapshot.seq` is >= 0 (both derive from
133
+ // `Math.max(0, ...)`/a monotonic fold starting at 0), so this value can
134
+ // never collide with a legitimate seq — including a project's real
135
+ // first-ever snapshot persisted at `seq === 0`, which the cold-seed's OWN
136
+ // `projectSeq: 0` would otherwise alias. Deliberately kept separate from
137
+ // `runtime.projectSeq` (which a timed-out read still seeds to plain `0`):
138
+ // the reseed-advancement guard on the deferred continuation below needs
139
+ // `runtime.projectSeq` to read exactly 0 immediately after a cold seed so
140
+ // `> 0` reliably means "a bump happened in the stall window", which this
141
+ // sentinel is never fed into.
142
+ const UNKNOWN_PROJECT_SEQ = -1;
143
+ /**
144
+ * Bound the sequence read that gates snapshot freshness (#1162). Normally
145
+ * ~2ms, but the underlying read is a blocking `fs.readFileSync` that can
146
+ * balloon under host I/O pressure (2125ms observed) with NO escape hatch —
147
+ * and a `setTimeout`/`Promise.race` timeout can never preempt a *synchronous*
148
+ * read (the thread only returns to the event loop once the OS call
149
+ * returns). The fix is to read asynchronously (`readLatestProjectSequenceAsync`,
150
+ * which uses `fs.promises.readFile` and genuinely yields) so a timeout CAN
151
+ * win the race.
152
+ *
153
+ * On the healthy path (the overwhelming common case) the async read settles
154
+ * first and this adds ~zero overhead beyond one microtask hop. On a stalled
155
+ * read, the timeout wins: the caller proceeds immediately with a cold
156
+ * sequence (`{ projectSeq: 0, fileSeqByPath: empty }` — byte-identical to
157
+ * what a full replay of a missing/empty log already produces, so this is
158
+ * exactly the existing cold-start case, not a new code path) while the real
159
+ * read keeps running in the background. When it resolves, it re-seeds the
160
+ * runtime so the warm-start optimization is recovered for the NEXT
161
+ * session_start/turn instead of lost for the rest of the process — unless
162
+ * the session has since moved on (`runtime.isCurrentSession`) or this is a
163
+ * one-shot `pi --print` process (`isPrintMode()`), which has no future
164
+ * session in-process to benefit and where letting background work outlive
165
+ * settle is exactly the referenced-handle retention class #1154/#1153 just
166
+ * closed. The timeout timer itself is `.unref()`'d and always cleared on
167
+ * both race outcomes, so it never holds the process open either.
168
+ *
169
+ * Never silent (shape 10): the caller's `session_start_sequence_read`
170
+ * latency line always carries `timedOut`, and a successful deferred reseed
171
+ * logs its own `session_start_sequence_read_deferred_reseed` phase.
172
+ */
173
+ async function readSequenceWithBudget(args) {
174
+ const { snapshotRoot, base, cwd, runtime, sessionGeneration, dbg } = args;
175
+ const readPromise = readLatestProjectSequenceAsync(snapshotRoot, base);
176
+ let timeoutHandle;
177
+ const timeoutPromise = new Promise((resolve) => {
178
+ timeoutHandle = setTimeout(() => resolve({ timedOut: true }), sequenceReadBudgetMs());
179
+ timeoutHandle.unref();
180
+ });
181
+ const raced = await Promise.race([
182
+ readPromise.then((latestSeq) => ({ timedOut: false, latestSeq })),
183
+ timeoutPromise,
184
+ ]);
185
+ if (timeoutHandle)
186
+ clearTimeout(timeoutHandle);
187
+ if (!raced.timedOut) {
188
+ return { latestSeq: raced.latestSeq, timedOut: false };
189
+ }
190
+ dbg(`session_start: sequence read exceeded ${sequenceReadBudgetMs()}ms budget — falling back to cold-start sequence`);
191
+ if (!isPrintMode()) {
192
+ readPromise
193
+ .then((latestSeq) => {
194
+ if (!runtime.isCurrentSession(sessionGeneration))
195
+ return;
196
+ // #1162 review follow-up (P3): `isCurrentSession` alone catches a
197
+ // CROSS-session move-on but not a SAME-session advancement in the
198
+ // stall window. Interleaving: timeout -> cold seed sets
199
+ // projectSeq=0 -> handler returns -> agent edits file X ->
200
+ // `bumpFileSeq(X)` advances `_projectSeq`/`_fileSeq[X]` -> this
201
+ // deferred read completes. Reseeding here would blindly `.clear()`
202
+ // and repopulate `_fileSeq`/`_fileLastProjectSeq` from the STALE
203
+ // pre-edit snapshot, erasing the in-window bump for file X (a
204
+ // transient inconsistency that self-heals into a full sweep per
205
+ // `seedProjectSequence`'s empty-changed-map invariant — safe, but
206
+ // worth not doing). The cold seed always sets `projectSeq` to
207
+ // exactly 0, so `runtime.projectSeq > 0` here can ONLY be true if a
208
+ // `bumpFileSeq` ran since — i.e. an in-window edit — never a false
209
+ // positive from a legitimately-empty log (which leaves it at 0, and
210
+ // the reseed below is then still wanted: it recovers the real,
211
+ // possibly non-empty, result that arrived too late for the budget).
212
+ if (runtime.projectSeq > 0) {
213
+ dbg("session_start: deferred sequence read completed, but the session already advanced (in-window edit) — skipping reseed to avoid clobbering it");
214
+ return;
215
+ }
216
+ const reseedStartedAt = Date.now();
217
+ runtime.seedProjectSequence?.(latestSeq.projectSeq, latestSeq.fileSeqByPath);
218
+ logLatency({
219
+ type: "phase",
220
+ phase: "session_start_sequence_read_deferred_reseed",
221
+ filePath: cwd,
222
+ startedAt: new Date(reseedStartedAt).toISOString(),
223
+ durationMs: Date.now() - reseedStartedAt,
224
+ metadata: { entries: latestSeq.fileSeqByPath.size, deferred: true },
225
+ });
226
+ dbg(`session_start: deferred sequence read completed — reseeded projectSeq=${latestSeq.projectSeq} fileSeqEntries=${latestSeq.fileSeqByPath.size}`);
227
+ })
228
+ .catch((err) => {
229
+ dbg(`session_start: deferred sequence read failed: ${err}`);
230
+ });
231
+ }
232
+ return {
233
+ latestSeq: { projectSeq: 0, fileSeqByPath: new Map() },
234
+ timedOut: true,
235
+ };
236
+ }
68
237
  async function igniteWarmFiles(cwd, warmFiles, runtime, sessionGeneration, dbg) {
69
238
  try {
70
239
  dbg(`session_start lsp-warm: ${warmFiles.length} warm file(s) configured`);
71
240
  await initLSPConfig(cwd);
72
241
  if (!runtime.isCurrentSession(sessionGeneration))
73
242
  return;
74
- const lspService = getLSPService();
243
+ const lspService = (await loadLspService()).getLSPService();
75
244
  const total = warmFiles.length;
76
245
  let loaded = 0;
77
246
  let errors = 0;
@@ -122,9 +291,9 @@ async function igniteDominantLanguageWarm(cwd, runtime, sessionGeneration, dbg)
122
291
  await initLSPConfig(cwd);
123
292
  if (!runtime.isCurrentSession(sessionGeneration))
124
293
  return;
125
- const lspService = getLSPService();
294
+ const lspService = (await loadLspService()).getLSPService();
126
295
  const { collectSourceFilesAsync } = await import("./source-filter.js");
127
- const { detectFileKind } = await import("./file-kinds.js");
296
+ const { CODE_KINDS, detectFileKind } = await import("./file-kinds.js");
128
297
  // Async, event-loop-yielding walk (deferred off the interactive path).
129
298
  // inspectGeneratedHeaders:false keeps the walk to directory reads only — no
130
299
  // per-file content opens — so we never hold a file handle (cheaper, and it
@@ -150,9 +319,20 @@ async function igniteDominantLanguageWarm(cwd, runtime, sessionGeneration, dbg)
150
319
  return;
151
320
  }
152
321
  const ranked = [...counts.entries()].sort((a, b) => b[1] - a[1]);
322
+ // #894 review: data/doc kinds (json/yaml/markdown/…) have builtin LSP
323
+ // servers too, and broadened enumeration makes them countable — so a TS
324
+ // repo with more .json/.yml than .ts files would otherwise warm the
325
+ // json/yaml server while tsserver still pays the ~5s cold-spawn stall
326
+ // this warm exists to prevent (#203). Rank CODE_KINDS first; non-code
327
+ // kinds stay as a fallback so a pure-config/docs repo still warms its
328
+ // dominant server.
329
+ const warmOrder = [
330
+ ...ranked.filter(([kind]) => CODE_KINDS.has(kind)),
331
+ ...ranked.filter(([kind]) => !CODE_KINDS.has(kind)),
332
+ ];
153
333
  // Walk languages by descending count; warm the first that has both an LSP
154
334
  // server and a representative on-disk file.
155
- for (const [kind] of ranked) {
335
+ for (const [kind] of warmOrder) {
156
336
  const sample = files.find((f) => detectFileKind(f) === kind && lspService.supportsLSP(f));
157
337
  if (!sample)
158
338
  continue;
@@ -248,14 +428,14 @@ async function collectTodoBaselineItems(scanner, analysisRoot, stillCurrent) {
248
428
  const files = await getSourceFilesAsync(analysisRoot, true);
249
429
  if (!stillCurrent())
250
430
  return items;
251
- let processedSinceYield = 0;
431
+ const deadline = createDeadline(8);
252
432
  for (const file of files) {
253
433
  if (!stillCurrent())
254
434
  return items;
255
435
  scanOneTodoFile(scanner, file, items);
256
- if (++processedSinceYield % 30 === 0) {
257
- await new Promise((resolve) => setImmediate(resolve));
258
- }
436
+ // scanFile cost scales with the file contents, so a count cadence cannot
437
+ // bound the event-loop block across differently-sized corpora.
438
+ await yieldIfOverBudget(deadline);
259
439
  }
260
440
  }
261
441
  catch {
@@ -264,42 +444,133 @@ async function collectTodoBaselineItems(scanner, analysisRoot, stillCurrent) {
264
444
  }
265
445
  return items;
266
446
  }
267
- // word-index — identifier inverted index + BM25 for ranked symbol search
268
- // (#162). Shared load -> rebuild-if-stale -> persist lifecycle (#348), the same
269
- // shape the call-graph task uses: reuse a fresh persisted index when the
270
- // project `seq` hasn't moved since it was built, otherwise do a bounded
271
- // rebuild and persist. Called from the full-mode background task AND the
272
- // quick-mode cold-start warmup pass (below) so every startup mode ends up
273
- // with a queryable index once per session, off the hot path.
274
447
  async function buildOrRefreshWordIndex(args) {
275
448
  const { runtime, sessionGeneration, analysisRoot, snapshotRoot, dbg } = args;
276
449
  if (!runtime.isCurrentSession(sessionGeneration))
277
450
  return;
278
451
  const startMs = Date.now();
279
- const latestSeq = readLatestProjectSequence(snapshotRoot);
452
+ let rebuildPreflightFiles;
453
+ const latestSeq = readLatestProjectSequence(snapshotRoot, snapshotSequenceBase(snapshotRoot));
280
454
  const effectiveSeq = runtime.projectSeq ?? latestSeq.projectSeq;
281
455
  const snapshot = loadProjectSnapshot(snapshotRoot);
282
- if (isProjectSnapshotFresh(snapshot, effectiveSeq) && snapshot.wordIndex) {
283
- const { deserializeWordIndex } = await import("./word-index.js");
456
+ if (snapshot?.wordIndex) {
457
+ const { deserializeWordIndex, refreshWordIndexIncrementally } = await import("./word-index.js");
284
458
  const index = deserializeWordIndex(snapshot.wordIndex);
285
459
  if (index) {
286
- runtime.wordIndex = index;
287
- dbg(`session_start word-index: reused fresh snapshot (seq=${effectiveSeq}, ${index.docCount} files, ${Date.now() - startMs}ms)`);
288
- return;
460
+ try {
461
+ const result = await refreshWordIndexIncrementally(index, analysisRoot, () => runtime.isCurrentSession(sessionGeneration));
462
+ if (!runtime.isCurrentSession(sessionGeneration))
463
+ return;
464
+ if (result.mode === "full-required") {
465
+ rebuildPreflightFiles = result.preflightFiles;
466
+ dbg(`session_start word-index: incremental preflight selected full rebuild (${result.reason})`);
467
+ logWordIndex({
468
+ phase: "incremental_fallback",
469
+ cwd: snapshotRoot,
470
+ trigger: "session_start",
471
+ reason: result.reason,
472
+ });
473
+ }
474
+ else {
475
+ runtime.wordIndex = index;
476
+ // A stale project seq must be advanced even when mtimes prove every
477
+ // indexed document reusable. Fresh snapshots with no changes avoid
478
+ // an unnecessary rewrite of the large shared snapshot.
479
+ if (!isProjectSnapshotFresh(snapshot, effectiveSeq) ||
480
+ result.refreshed > 0 ||
481
+ result.dropped > 0 ||
482
+ snapshot.wordIndex.truncated !== index.truncated) {
483
+ saveRuntimeProjectSnapshot({ cwd: snapshotRoot, runtime, dbg });
484
+ }
485
+ dbg(`session_start word-index: incremental (seq=${effectiveSeq}, refreshed=${result.refreshed}, dropped=${result.dropped}, skipped=${result.skipped}, reused=${result.reused}, ${Date.now() - startMs}ms)`);
486
+ // M2, #958: the incremental-vs-full decision + honest coverage
487
+ // (indexedFileCount/truncated/skipped), independent of host `dbg`.
488
+ logWordIndex({
489
+ phase: "incremental_refresh",
490
+ cwd: snapshotRoot,
491
+ trigger: "session_start",
492
+ durationMs: Date.now() - startMs,
493
+ indexedFileCount: index.docCount,
494
+ tokens: index.postings.size,
495
+ truncated: index.truncated,
496
+ refreshed: result.refreshed,
497
+ dropped: result.dropped,
498
+ skipped: result.skipped,
499
+ reused: result.reused,
500
+ });
501
+ return result;
502
+ }
503
+ }
504
+ catch (err) {
505
+ // Supersession is an expected transition, not a failure: a newer
506
+ // session_start bumped the generation mid-refresh. Return undefined the
507
+ // way master's synchronous path did instead of reporting a fallback and
508
+ // re-walking for a rebuild whose result this generation may not publish.
509
+ if (!runtime.isCurrentSession(sessionGeneration)) {
510
+ dbg("session_start word-index: incremental refresh superseded");
511
+ return;
512
+ }
513
+ dbg(`session_start word-index: incremental refresh failed; falling back to full rebuild (${err})`);
514
+ logWordIndex({
515
+ phase: "incremental_fallback",
516
+ cwd: snapshotRoot,
517
+ trigger: "session_start",
518
+ reason: err instanceof Error ? err.message : String(err),
519
+ });
520
+ }
289
521
  }
290
522
  }
291
523
  // Shared file-walk-and-read helper (#348): the ONE collectWordIndexDocs
292
524
  // implementation backs this task, the quick-mode warmup call below, AND the
293
525
  // stateless cold-query background trigger in word-index.ts — a bound/skip
294
526
  // -rule change lands once, not in three copies.
295
- const { buildWordIndex, collectWordIndexDocs } = await import("./word-index.js");
296
- const docs = await collectWordIndexDocs(analysisRoot, () => runtime.isCurrentSession(sessionGeneration));
527
+ const { buildWordIndexAsync, collectWordIndexDocs } = await import("./word-index.js");
528
+ const docs = await collectWordIndexDocs(analysisRoot, () => runtime.isCurrentSession(sessionGeneration), rebuildPreflightFiles);
529
+ if (!runtime.isCurrentSession(sessionGeneration))
530
+ return;
531
+ // #1197 review finding 2: `buildWordIndexAsync` THROWS on supersession, and
532
+ // the quick-mode warmup caller (below) awaits this function OUTSIDE any
533
+ // per-step try/catch — an escaping throw there skips the rest of warmup,
534
+ // including the #947 LSP pre-warm, and resets `__piLensWarmupScheduled`.
535
+ // Supersession is an expected transition (master's synchronous path just
536
+ // returned), so absorb it here and let the caller continue.
537
+ let rebuiltIndex;
538
+ try {
539
+ rebuiltIndex = await buildWordIndexAsync(docs, () => runtime.isCurrentSession(sessionGeneration));
540
+ }
541
+ catch (err) {
542
+ if (!runtime.isCurrentSession(sessionGeneration)) {
543
+ dbg("session_start word-index: rebuild superseded");
544
+ return;
545
+ }
546
+ throw err;
547
+ }
297
548
  if (!runtime.isCurrentSession(sessionGeneration))
298
549
  return;
299
- runtime.wordIndex = buildWordIndex(docs);
550
+ runtime.wordIndex = rebuiltIndex;
300
551
  saveRuntimeProjectSnapshot({ cwd: snapshotRoot, runtime, dbg });
301
552
  dbg(`session_start word-index: rebuilt (absent/stale, seq=${effectiveSeq}) ` +
302
553
  `${runtime.wordIndex.docCount} files, ${runtime.wordIndex.postings.size} tokens (${Date.now() - startMs}ms)`);
554
+ // M2, #958: full-rebuild decision + honest coverage. `docs.skipped` (L1)
555
+ // counts files the walk saw but could not index (unreadable / over the byte
556
+ // cap) so a partial index is never reported as complete (#533).
557
+ logWordIndex({
558
+ phase: "full_rebuild",
559
+ cwd: snapshotRoot,
560
+ trigger: "session_start",
561
+ durationMs: Date.now() - startMs,
562
+ indexedFileCount: runtime.wordIndex.docCount,
563
+ tokens: runtime.wordIndex.postings.size,
564
+ truncated: runtime.wordIndex.truncated,
565
+ skipped: docs.skipped,
566
+ });
567
+ return {
568
+ mode: "full",
569
+ refreshed: runtime.wordIndex.docCount,
570
+ dropped: 0,
571
+ skipped: docs.skipped,
572
+ reused: 0,
573
+ };
303
574
  }
304
575
  // Fire off heavy scans as background tasks — don't block session start.
305
576
  // Each consumer already handles the "not ready yet" case gracefully
@@ -323,29 +594,38 @@ function scheduleStartupScans(deps, runtime, sessionGeneration, analysisRoot, sn
323
594
  const queuedAt = Date.now();
324
595
  dbg(`session_start task ${name}: scheduled`);
325
596
  runtime.markStartupScanInFlight(name, sessionGeneration);
326
- const fire = () => {
327
- const startedAt = Date.now();
328
- dbg(`session_start task ${name}: start queuedMs=${startedAt - queuedAt}`);
329
- void task()
330
- .then(() => {
331
- dbg(`session_start task ${name}: success runMs=${Date.now() - startedAt} queuedMs=${startedAt - queuedAt}`);
332
- })
333
- .catch((err) => {
334
- dbg(`session_start: ${name} background scan failed: ${err}`);
335
- dbg(`session_start task ${name}: failed runMs=${Date.now() - startedAt} queuedMs=${startedAt - queuedAt}`);
336
- })
337
- .finally(() => {
338
- runtime.clearStartupScanInFlight(name, sessionGeneration);
339
- dbg(`session_start task ${name}: end`);
340
- });
341
- };
342
- const delay = taskDeferMsByName[name] ?? 0;
343
- if (delay > 0) {
344
- setTimeout(fire, delay);
345
- }
346
- else {
347
- setImmediate(fire);
348
- }
597
+ const completion = new Promise((resolve) => {
598
+ const fire = () => {
599
+ const startedAt = Date.now();
600
+ dbg(`session_start task ${name}: start queuedMs=${startedAt - queuedAt}`);
601
+ void task()
602
+ .then(() => {
603
+ dbg(`session_start task ${name}: success runMs=${Date.now() - startedAt} queuedMs=${startedAt - queuedAt}`);
604
+ })
605
+ .catch((err) => {
606
+ dbg(`session_start: ${name} background scan failed: ${err}`);
607
+ dbg(`session_start task ${name}: failed runMs=${Date.now() - startedAt} queuedMs=${startedAt - queuedAt}`);
608
+ })
609
+ .finally(() => {
610
+ runtime.clearStartupScanInFlight(name, sessionGeneration);
611
+ dbg(`session_start task ${name}: end`);
612
+ resolve();
613
+ });
614
+ };
615
+ const delay = taskDeferMsByName[name] ?? 0;
616
+ if (delay > 0) {
617
+ // #1154: unref to match the repo-wide convention that every
618
+ // background timer is `.unref()`'d. Full-mode deferred scans only
619
+ // run in long-lived/interactive sessions today (never a one-shot),
620
+ // so this is defensive — but a referenced 5s timer would keep a
621
+ // process open were a full-mode one-shot ever introduced.
622
+ setTimeout(fire, delay).unref?.();
623
+ }
624
+ else {
625
+ setImmediate(fire);
626
+ }
627
+ });
628
+ return completion;
349
629
  };
350
630
  const canRunJsTsHeavyScans = canRunStartupHeavyScans(languageProfile, "jsts");
351
631
  const scanNames = ["todo", "dead-code"];
@@ -415,9 +695,11 @@ function scheduleStartupScans(deps, runtime, sessionGeneration, analysisRoot, sn
415
695
  const knipResult = await knipClient.analyze(analysisRoot, getKnipIgnorePatterns());
416
696
  if (!runtime.isCurrentSession(sessionGeneration))
417
697
  return;
418
- cacheManager.writeCache("knip", knipResult, analysisRoot, {
419
- scanDurationMs: Date.now() - startMs,
420
- });
698
+ if (knipResult.success) {
699
+ cacheManager.writeCache("knip", knipResult, analysisRoot, {
700
+ scanDurationMs: Date.now() - startMs,
701
+ });
702
+ }
421
703
  dbg(`session_start Knip scan done (${Date.now() - startMs}ms)`);
422
704
  }
423
705
  });
@@ -446,9 +728,11 @@ function scheduleStartupScans(deps, runtime, sessionGeneration, analysisRoot, sn
446
728
  const jscpdResult = await jscpdClient.scan(analysisRoot, undefined, undefined, isTsProject);
447
729
  if (!runtime.isCurrentSession(sessionGeneration))
448
730
  return;
449
- cacheManager.writeCache(scannerKey, jscpdResult, analysisRoot, {
450
- scanDurationMs: Date.now() - startMs,
451
- });
731
+ if (jscpdResult.success) {
732
+ cacheManager.writeCache(scannerKey, jscpdResult, analysisRoot, {
733
+ scanDurationMs: Date.now() - startMs,
734
+ });
735
+ }
452
736
  dbg(`session_start jscpd scan done (${Date.now() - startMs}ms, isTsProject=${isTsProject})`);
453
737
  }
454
738
  }
@@ -479,9 +763,11 @@ function scheduleStartupScans(deps, runtime, sessionGeneration, analysisRoot, sn
479
763
  const result = await client.analyze(analysisRoot);
480
764
  if (!runtime.isCurrentSession(sessionGeneration))
481
765
  return undefined;
482
- cacheManager.writeCache(cacheKey, result, analysisRoot, {
483
- scanDurationMs: Date.now() - startMs,
484
- });
766
+ if (result.success) {
767
+ cacheManager.writeCache(cacheKey, result, analysisRoot, {
768
+ scanDurationMs: Date.now() - startMs,
769
+ });
770
+ }
485
771
  logDeadCodeScan({
486
772
  language: client.language,
487
773
  success: result.success,
@@ -523,9 +809,11 @@ function scheduleStartupScans(deps, runtime, sessionGeneration, analysisRoot, sn
523
809
  const result = await govulncheckClient.analyze(analysisRoot);
524
810
  if (!runtime.isCurrentSession(sessionGeneration))
525
811
  return;
526
- cacheManager.writeCache("govulncheck", result, analysisRoot, {
527
- scanDurationMs: Date.now() - startMs,
528
- });
812
+ if (result.success) {
813
+ cacheManager.writeCache("govulncheck", result, analysisRoot, {
814
+ scanDurationMs: Date.now() - startMs,
815
+ });
816
+ }
529
817
  dbg(`session_start govulncheck: ${result.findings.length} reachable findings (${Date.now() - startMs}ms)`);
530
818
  });
531
819
  // gitleaks — committed-secrets detection (#130)
@@ -555,9 +843,11 @@ function scheduleStartupScans(deps, runtime, sessionGeneration, analysisRoot, sn
555
843
  const result = await gitleaksClient.scan(analysisRoot);
556
844
  if (!runtime.isCurrentSession(sessionGeneration))
557
845
  return;
558
- cacheManager.writeCache("gitleaks", result, analysisRoot, {
559
- scanDurationMs: Date.now() - startMs,
560
- });
846
+ if (result.success) {
847
+ cacheManager.writeCache("gitleaks", result, analysisRoot, {
848
+ scanDurationMs: Date.now() - startMs,
849
+ });
850
+ }
561
851
  dbg(`session_start gitleaks: ${result.findings.length} findings (${Date.now() - startMs}ms)`);
562
852
  });
563
853
  // opengrep — full-workspace security/quality findings via a single CLI scan
@@ -589,9 +879,11 @@ function scheduleStartupScans(deps, runtime, sessionGeneration, analysisRoot, sn
589
879
  const result = await opengrepClient.scan(analysisRoot);
590
880
  if (!runtime.isCurrentSession(sessionGeneration))
591
881
  return;
592
- cacheManager.writeCache("opengrep", result, analysisRoot, {
593
- scanDurationMs: Date.now() - startMs,
594
- });
882
+ if (result.success) {
883
+ cacheManager.writeCache("opengrep", result, analysisRoot, {
884
+ scanDurationMs: Date.now() - startMs,
885
+ });
886
+ }
595
887
  dbg(`session_start opengrep: ${result.findings.length} findings (${Date.now() - startMs}ms)`);
596
888
  });
597
889
  // madge — whole-project circular-dependency detection. Session-start + cached
@@ -649,56 +941,73 @@ function scheduleStartupScans(deps, runtime, sessionGeneration, analysisRoot, sn
649
941
  const result = await trivyClient.scan(analysisRoot);
650
942
  if (!runtime.isCurrentSession(sessionGeneration))
651
943
  return;
652
- cacheManager.writeCache("trivy", result, analysisRoot, {
653
- scanDurationMs: Date.now() - startMs,
654
- });
944
+ if (result.success) {
945
+ cacheManager.writeCache("trivy", result, analysisRoot, {
946
+ scanDurationMs: Date.now() - startMs,
947
+ });
948
+ }
655
949
  dbg(`session_start trivy: ${result.findings.length} CVE findings (${Date.now() - startMs}ms)`);
656
950
  });
657
951
  // call-graph — build function-level call graph from review graph data
658
- runTask("call-graph", async () => {
952
+ let callGraphIdentity;
953
+ const callGraphTask = runTask("call-graph", async () => {
659
954
  const { FactStore } = await import("./dispatch/fact-store.js");
660
- const { buildOrUpdateGraph, extractSymbolsAndRefsFromGraph, isReviewGraphMigrationNeeded, } = await import("./review-graph/builder.js");
661
- const { buildCallGraph, saveCallGraph, loadCallGraph, staleFiles, readMtimes, } = await import("./call-graph.js");
955
+ const { buildOrUpdateGraph, extractSymbolsAndRefsFromGraph, getReviewGraphCacheIdentity, } = await import("./review-graph/builder.js");
956
+ const { buildCallGraph, saveCallGraph, loadCallGraph } = await import("./call-graph.js");
662
957
  if (!runtime.isCurrentSession(sessionGeneration))
663
958
  return;
664
959
  const startMs = Date.now();
665
- // Try loading from cache first
666
- const cached = loadCallGraph(snapshotRoot);
667
- if (cached) {
668
- const cachedFiles = [...cached.fileMtimes.keys()];
669
- const stale = staleFiles(cached.fileMtimes, cachedFiles);
670
- // #260: a stale REVIEW-graph version must force a rebuild even when the
671
- // (separate) call-graph cache is fresh — otherwise an upgrade that
672
- // invalidated the persisted graph (e.g. v2→v3 test exclusion) leaves
673
- // reads cold until the next edit. The version check is cheap (file head).
674
- if (stale.length === 0 &&
675
- cachedFiles.length > 0 &&
676
- !isReviewGraphMigrationNeeded(analysisRoot)) {
677
- runtime.callGraph = cached.graph;
678
- dbg(`session_start call-graph: loaded from cache (${cached.graph.edges.length} edges, ${Date.now() - startMs}ms)`);
679
- return;
680
- }
681
- }
682
- // Build from the review graph (reuses already-parsed data, no re-parse)
960
+ // Build (or hydrate) the canonical review graph first. The call graph is a
961
+ // derived projection of that graph, so its freshness is the review graph's
962
+ // version/signature—not a second source walk and mtime policy.
683
963
  const sessionFacts = new FactStore();
684
964
  const graph = await buildOrUpdateGraph(analysisRoot, [], sessionFacts);
685
965
  if (!runtime.isCurrentSession(sessionGeneration))
686
966
  return;
687
- const { allSymbols, allRefs } = extractSymbolsAndRefsFromGraph(graph);
688
- const callGraph = buildCallGraph(allSymbols, allRefs);
967
+ const identity = getReviewGraphCacheIdentity(analysisRoot, graph);
968
+ if (!identity) {
969
+ dbg("session_start call-graph: canonical review-graph identity unavailable");
970
+ return;
971
+ }
972
+ callGraphIdentity = {
973
+ reviewGraphVersion: identity.version,
974
+ reviewGraphSignature: identity.signature,
975
+ };
976
+ const cached = loadCallGraph(snapshotRoot, {
977
+ reviewGraphVersion: identity.version,
978
+ reviewGraphSignature: identity.signature,
979
+ });
980
+ if (cached) {
981
+ runtime.callGraph = cached.graph;
982
+ dbg(`session_start call-graph: loaded from cache (${cached.graph.edges.length} edges, ${cached.graph.callers.size} callee entries, ${Date.now() - startMs}ms)`);
983
+ return;
984
+ }
985
+ // Build from the canonical review graph (reuses already-parsed data, no
986
+ // duplicate parser or source walk).
987
+ const { allSymbols, allRefs, coverage } = extractSymbolsAndRefsFromGraph(graph);
988
+ const callGraph = buildCallGraph(allSymbols, allRefs, coverage);
689
989
  runtime.callGraph = callGraph;
690
- const mtimes = readMtimes([...allSymbols.keys()]);
691
- saveCallGraph(snapshotRoot, callGraph, mtimes);
990
+ saveCallGraph(snapshotRoot, callGraph, {
991
+ reviewGraphVersion: identity.version,
992
+ reviewGraphSignature: identity.signature,
993
+ });
692
994
  dbg(`session_start call-graph: built ${callGraph.edges.length} edges, ${callGraph.callers.size} callee entries (${Date.now() - startMs}ms)`);
693
995
  });
694
996
  // codebase-model — build mental model from call graph (internal-only until validated)
997
+ // Keep this deferred, but await the call-graph task's completion rather than
998
+ // racing its independently deferred timer. Otherwise a slow graph build leaves
999
+ // `runtime.callGraph` unset at this task's start and loses the model for the
1000
+ // entire session (#1070).
695
1001
  runTask("codebase-model", async () => {
1002
+ await callGraphTask;
696
1003
  if (!runtime.isCurrentSession(sessionGeneration))
697
1004
  return;
698
1005
  if (!runtime.callGraph)
699
- return; // call-graph task may not have completed yet
700
- const { buildCodebaseModel, saveCodebaseModel } = await import("./codebase-model.js");
701
- const model = buildCodebaseModel(runtime.callGraph, analysisRoot);
1006
+ return;
1007
+ const { buildCodebaseModel, saveCodebaseModel, DEFAULT_CODEBASE_MODEL_TOKEN_BUDGET } = await import("./codebase-model.js");
1008
+ if (!callGraphIdentity)
1009
+ return;
1010
+ const model = buildCodebaseModel(runtime.callGraph, analysisRoot, DEFAULT_CODEBASE_MODEL_TOKEN_BUDGET, callGraphIdentity);
702
1011
  saveCodebaseModel(snapshotRoot, model);
703
1012
  const top3 = model.entries
704
1013
  .slice(0, 3)
@@ -788,7 +1097,34 @@ export const SESSION_START_GUIDANCE = [
788
1097
  "• Situational (activate via pi_lens_activate_tools): lsp_navigation, ast_grep_search, ast_grep_replace, ast_grep_dump.",
789
1098
  ];
790
1099
  export async function handleSessionStart(deps) {
791
- const sessionStartMs = Date.now();
1100
+ resetDegradationLedger();
1101
+ const handlerEnteredAt = Date.now();
1102
+ const sessionStartMs = deps.sessionStartFiredAt ?? handlerEnteredAt;
1103
+ const cwdForTelemetry = deps.ctxCwd ?? process.cwd();
1104
+ if (deps.bootstrapClientsStartedAt !== undefined &&
1105
+ deps.bootstrapClientsDurationMs !== undefined) {
1106
+ logLatency({
1107
+ type: "phase",
1108
+ filePath: cwdForTelemetry,
1109
+ phase: "bootstrap_clients_load",
1110
+ startedAt: new Date(deps.bootstrapClientsStartedAt).toISOString(),
1111
+ durationMs: deps.bootstrapClientsDurationMs,
1112
+ metadata: {
1113
+ parent: "session_start_prehandler",
1114
+ reason: deps.sessionReason,
1115
+ },
1116
+ });
1117
+ }
1118
+ if (deps.sessionStartFiredAt !== undefined) {
1119
+ logLatency({
1120
+ type: "phase",
1121
+ filePath: cwdForTelemetry,
1122
+ phase: "session_start_prehandler",
1123
+ startedAt: new Date(deps.sessionStartFiredAt).toISOString(),
1124
+ durationMs: (deps.handlerEnteredAt ?? handlerEnteredAt) - deps.sessionStartFiredAt,
1125
+ metadata: { reason: deps.sessionReason },
1126
+ });
1127
+ }
792
1128
  // Cold-start input-latency mitigation. The first `session_start` of
793
1129
  // the process — i.e. the one that fires immediately after the user
794
1130
  // launches `pi` — must return as fast as possible so the TUI input
@@ -826,18 +1162,36 @@ export async function handleSessionStart(deps) {
826
1162
  startupMode = deps.startupModeOverride ?? "quick";
827
1163
  }
828
1164
  processGlobals.__piLensFirstSessionDone = true;
1165
+ // #1154: quick mode is entered on BOTH `pi -p`/`--print` (a one-shot that
1166
+ // exits right after this turn) and an interactive process's first
1167
+ // session_start (forced quick to protect keystroke latency, then warms
1168
+ // caches for the NEXT /new). The warmup only benefits a *future* session in
1169
+ // the same process — a one-shot print invocation has none. Worse, in a
1170
+ // one-shot the warmup is a referenced-handle keep-alive: the +2s timer and
1171
+ // the LSP-prewarm children / language-profile source walk it launches
1172
+ // outlive settle with no session_shutdown teardown, holding the process
1173
+ // open (the #1097/#1110/#1122-hyp-A class). So skip warmup entirely in
1174
+ // print mode; interactive first-sessions (not print) still warm.
829
1175
  if (startupMode === "quick" &&
1176
+ !isPrintMode() &&
830
1177
  process.env.PI_LENS_COLD_START_QUICK !== "0" &&
831
1178
  !processGlobals.__piLensWarmupScheduled) {
832
1179
  processGlobals.__piLensWarmupScheduled = true;
833
1180
  const warmupDelayMs = Number(process.env.PI_LENS_WARMUP_DELAY_MS ?? 2000);
834
1181
  const warmupCwd = deps.ctxCwd ?? process.cwd();
835
1182
  const warmupDbg = deps.dbg;
836
- setTimeout(() => {
1183
+ // #1154: `.unref()` the warmup timer so — even for a warmup that IS
1184
+ // scheduled (an interactive first-session) — the pending timer alone can
1185
+ // never hold the loop open. Interactive processes stay alive for other
1186
+ // reasons, so the warmup still fires; a one-shot never reaches here (the
1187
+ // isPrintMode gate above), and repo convention is that every background
1188
+ // timer is unref'd (this file previously had none).
1189
+ const warmupTimer = setTimeout(() => {
837
1190
  const warmupStartedAt = Date.now();
838
1191
  void (async () => {
839
1192
  try {
840
1193
  warmupDbg("warmup: starting background warmup");
1194
+ const scanContextStartedAt = Date.now();
841
1195
  // Dynamic imports keep the warmup pipeline off the hot
842
1196
  // startup path — these modules don't load until the timer
843
1197
  // fires, well after the TUI is interactive.
@@ -865,6 +1219,14 @@ export async function handleSessionStart(deps) {
865
1219
  else {
866
1220
  scan =
867
1221
  await startupScanModule.resolveStartupScanContextAsync(warmupCwd);
1222
+ logLatency({
1223
+ type: "phase",
1224
+ phase: "session_start_scan_context_compute",
1225
+ filePath: warmupCwd,
1226
+ startedAt: new Date(scanContextStartedAt).toISOString(),
1227
+ durationMs: Date.now() - scanContextStartedAt,
1228
+ metadata: { mode: "quick-background" },
1229
+ });
868
1230
  warmupDbg(`warmup: scan-context done in ${Date.now() - warmupStartedAt}ms (canWarm=${scan.canWarmCaches})`);
869
1231
  // Best-effort: a save failure must never affect warmup itself —
870
1232
  // saveRuntimeProjectSnapshot already swallows its own errors.
@@ -875,6 +1237,13 @@ export async function handleSessionStart(deps) {
875
1237
  dbg: warmupDbg,
876
1238
  });
877
1239
  }
1240
+ logLatency({
1241
+ type: "phase",
1242
+ phase: "warmup_scan_context",
1243
+ filePath: warmupCwd,
1244
+ startedAt: new Date(scanContextStartedAt).toISOString(),
1245
+ durationMs: Date.now() - scanContextStartedAt,
1246
+ });
878
1247
  // Respect the startup-scan guard (#250): canWarmCaches is false for
879
1248
  // home-dir / no-project-root / too-many-source-files. Proceeding into
880
1249
  // the language-profile source walk in those cases lets it root at an
@@ -889,6 +1258,13 @@ export async function handleSessionStart(deps) {
889
1258
  const languageProfileStartedAt = Date.now();
890
1259
  await languageProfileModule.detectProjectLanguageProfileAsync(languageRoot);
891
1260
  warmupDbg(`warmup: language-profile done in ${Date.now() - languageProfileStartedAt}ms`);
1261
+ logLatency({
1262
+ type: "phase",
1263
+ phase: "warmup_language_profile",
1264
+ filePath: warmupCwd,
1265
+ startedAt: new Date(languageProfileStartedAt).toISOString(),
1266
+ durationMs: Date.now() - languageProfileStartedAt,
1267
+ });
892
1268
  // #348: fold the word-index build/refresh into this existing
893
1269
  // cold-start warmup pass so quick-mode (and any session whose very
894
1270
  // first session_start is forced quick) still ends up with a
@@ -896,7 +1272,7 @@ export async function handleSessionStart(deps) {
896
1272
  // runTask above; this is the quick-mode equivalent, once per
897
1273
  // process, off the hot path.
898
1274
  const wordIndexStartedAt = Date.now();
899
- await buildOrRefreshWordIndex({
1275
+ const wordIndexResult = await buildOrRefreshWordIndex({
900
1276
  runtime: deps.runtime,
901
1277
  sessionGeneration: deps.runtime.sessionGeneration,
902
1278
  analysisRoot: languageRoot,
@@ -904,6 +1280,62 @@ export async function handleSessionStart(deps) {
904
1280
  dbg: warmupDbg,
905
1281
  });
906
1282
  warmupDbg(`warmup: word-index done in ${Date.now() - wordIndexStartedAt}ms`);
1283
+ logLatency({
1284
+ type: "phase",
1285
+ phase: "warmup_word_index",
1286
+ filePath: warmupCwd,
1287
+ startedAt: new Date(wordIndexStartedAt).toISOString(),
1288
+ durationMs: Date.now() - wordIndexStartedAt,
1289
+ metadata: wordIndexResult ? { ...wordIndexResult } : undefined,
1290
+ });
1291
+ // #947: fold the dominant-language LSP pre-warm into this
1292
+ // warmup pass. The first-session-of-process heuristic forces
1293
+ // quick mode, and the pre-warm below is gated on
1294
+ // allowBootstrapTasks (full mode only) — so it NEVER ran in
1295
+ // practice and every session's first edit paid a cold LSP
1296
+ // spawn (~750ms wait + ~2.5s spawn, measured). Fire it here
1297
+ // instead: off the interactive path, once per process (the
1298
+ // __piLensWarmupScheduled guard above), generation-guarded
1299
+ // inside igniteDominantLanguageWarm, and honoring the same
1300
+ // skips as the full-mode path — subagent light mode (#449),
1301
+ // warm-attach (#822), the no-lsp flag, and the
1302
+ // canWarmCaches guard (the early return above). Concurrent
1303
+ // secondaries never reach handleSessionStart at all (the
1304
+ // #473 guard in index.ts), so they never schedule this
1305
+ // warmup in the first place.
1306
+ const lspPrewarmStartedAt = Date.now();
1307
+ if (deps.getFlag("no-lsp")) {
1308
+ warmupDbg("warmup: skipping LSP pre-warm (no-lsp)");
1309
+ }
1310
+ else if (isSubagentSession()) {
1311
+ warmupDbg("warmup: skipping LSP pre-warm (subagent session)");
1312
+ }
1313
+ else if (isWarmAttached()) {
1314
+ warmupDbg("warmup: skipping LSP pre-warm (attached to incumbent)");
1315
+ }
1316
+ else {
1317
+ // #957 review: honor explicit warmFiles (#203) like the full
1318
+ // path does — configured projects warm exactly what they
1319
+ // asked for; dominant-language warm is the fallback.
1320
+ const lspConfig = await loadLSPConfig(warmupCwd).catch(() => ({
1321
+ warmFiles: [],
1322
+ }));
1323
+ const warmFiles = lspConfig.warmFiles ?? [];
1324
+ if (warmFiles.length > 0) {
1325
+ await igniteWarmFiles(warmupCwd, warmFiles, deps.runtime, deps.runtime.sessionGeneration, warmupDbg);
1326
+ }
1327
+ else {
1328
+ await igniteDominantLanguageWarm(languageRoot, deps.runtime, deps.runtime.sessionGeneration, warmupDbg);
1329
+ }
1330
+ logLatency({
1331
+ type: "phase",
1332
+ phase: "warmup_lsp_prewarm",
1333
+ filePath: warmupCwd,
1334
+ startedAt: new Date(lspPrewarmStartedAt).toISOString(),
1335
+ durationMs: Date.now() - lspPrewarmStartedAt,
1336
+ });
1337
+ warmupDbg(`warmup: lsp-prewarm done in ${Date.now() - lspPrewarmStartedAt}ms`);
1338
+ }
907
1339
  warmupDbg(`warmup: total ${Date.now() - warmupStartedAt}ms`);
908
1340
  }
909
1341
  catch (err) {
@@ -911,8 +1343,18 @@ export async function handleSessionStart(deps) {
911
1343
  // Allow a future session to retry the warmup.
912
1344
  processGlobals.__piLensWarmupScheduled = false;
913
1345
  }
1346
+ finally {
1347
+ logLatency({
1348
+ type: "phase",
1349
+ phase: "warmup_total",
1350
+ filePath: warmupCwd,
1351
+ startedAt: new Date(warmupStartedAt).toISOString(),
1352
+ durationMs: Date.now() - warmupStartedAt,
1353
+ });
1354
+ }
914
1355
  })();
915
1356
  }, warmupDelayMs);
1357
+ warmupTimer.unref?.();
916
1358
  }
917
1359
  const allowBootstrapTasks = startupMode === "full";
918
1360
  const quickMode = startupMode === "quick";
@@ -937,16 +1379,62 @@ export async function handleSessionStart(deps) {
937
1379
  // previously session-lived with no reset hook at all).
938
1380
  resetWorkspaceTopology();
939
1381
  clearTsconfigPathsCache();
940
- // #817: PATH/PATHEXT command resolution is cached per (command, PATH, cwd);
941
- // drop it each session so a PATH change (e.g. a tool installed mid-session
942
- // in a prior session, or a differently-scoped shell) is picked up fresh.
1382
+ // #817/#1199: Windows command resolution is cached per (command, canonical
1383
+ // effective child PATH/PATHEXT/cwd/per-drive provenance); drop it each
1384
+ // session so environment changes (e.g.
1385
+ // a tool installed mid-session or a differently-scoped managed bin) are
1386
+ // picked up fresh.
943
1387
  resetSafeSpawnWindowsCommandCache();
944
- runtime.resetForSession();
945
- // Run log cleanup early in session start (non-blocking)
946
- const logCleanup = runLogCleanup(dbg);
947
- if (logCleanup.cleaned > 0 || logCleanup.rotated > 0) {
948
- notify(`🧹 ${logCleanup.report}`, "info");
949
- }
1388
+ // #1266: install-failure suppression in dispatch runner availability
1389
+ // checkers (`noteInstallFailure`) is meant to last only until "the next
1390
+ // session", per #1222 — but nothing called the reset helper, so a
1391
+ // transient install failure (npm registry blip, locked file) suppressed
1392
+ // the tool for the rest of the process lifetime. Clear it here, same
1393
+ // boundary as the other per-session caches on this line.
1394
+ resetDispatchAvailabilityState();
1395
+ // #1123 item 3: a fresh session can re-report smells that a prior session
1396
+ // already surfaced once (see `checkSmellsAndNoteOnce`'s once-per-session gate).
1397
+ resetSmellsSessionState();
1398
+ runtime.resetForSession(sessionStartMs);
1399
+ logLatency({
1400
+ type: "phase",
1401
+ phase: "session_start_runtime_reset",
1402
+ filePath: ctxCwd ?? process.cwd(),
1403
+ startedAt: new Date(handlerEnteredAt).toISOString(),
1404
+ durationMs: Date.now() - handlerEnteredAt,
1405
+ metadata: { mode: startupMode, reason: deps.sessionReason },
1406
+ });
1407
+ // #1019: log cleanup is deferred OFF the interactive critical path. It does
1408
+ // synchronous fs sweeps (~7ms) whose only consumer is an async notification —
1409
+ // nothing on the hot path reads its result — so running it inline just taxed
1410
+ // every session start. It still runs every session (correctness unchanged),
1411
+ // now on the next tick, and notifies when done. Errors are swallowed to a
1412
+ // dbg line: a best-effort log sweep must never surface as a session failure.
1413
+ const cleanupCwd = ctxCwd ?? process.cwd();
1414
+ setImmediate(() => {
1415
+ const logCleanupStartedAt = Date.now();
1416
+ try {
1417
+ const logCleanup = runLogCleanup(dbg);
1418
+ logLatency({
1419
+ type: "phase",
1420
+ phase: "session_start_log_cleanup",
1421
+ filePath: cleanupCwd,
1422
+ startedAt: new Date(logCleanupStartedAt).toISOString(),
1423
+ durationMs: Date.now() - logCleanupStartedAt,
1424
+ metadata: {
1425
+ mode: startupMode,
1426
+ reason: deps.sessionReason,
1427
+ deferred: true,
1428
+ },
1429
+ });
1430
+ if (logCleanup.cleaned > 0 || logCleanup.rotated > 0) {
1431
+ notify(`🧹 ${logCleanup.report}`, "info");
1432
+ }
1433
+ }
1434
+ catch (err) {
1435
+ dbg(`session_start: deferred log cleanup failed: ${err}`);
1436
+ }
1437
+ });
950
1438
  dbg(`session_start startup mode: ${startupMode}`);
951
1439
  if (!getFlag("no-lsp")) {
952
1440
  resetLSPService({ fast: true, reason: "session_start" });
@@ -955,21 +1443,90 @@ export async function handleSessionStart(deps) {
955
1443
  }
956
1444
  const hasWorkspaceCwd = typeof ctxCwd === "string" && ctxCwd.length > 0;
957
1445
  const cwd = ctxCwd ?? process.cwd();
1446
+ // #1228: generic atomic-write stages are shared by several project stores,
1447
+ // so the review-graph-specific sweep cannot own this namespace. Sweep the
1448
+ // project data roots and machine-global registry root once per session start;
1449
+ // this is fire-and-forget and bounded so it never delays startup.
1450
+ const projectDataDir = getProjectDataDir(cwd);
1451
+ void sweepAtomicWriteStages([
1452
+ projectDataDir,
1453
+ path.join(projectDataDir, "cache"),
1454
+ path.join(projectDataDir, "sessions"),
1455
+ getGlobalPiLensDir(),
1456
+ ]).catch(() => {
1457
+ // best-effort lifecycle cleanup — never fail session_start
1458
+ });
958
1459
  if (quickMode) {
959
1460
  runtime.projectRoot = cwd;
1461
+ const sequenceReadStartedAt = Date.now();
960
1462
  const snapshotRoot = resolveSnapshotRoot(cwd);
961
- const latestSeq = readLatestProjectSequence(snapshotRoot);
1463
+ const { latestSeq, timedOut } = await readSequenceWithBudget({
1464
+ snapshotRoot,
1465
+ base: snapshotSequenceBase(snapshotRoot),
1466
+ cwd,
1467
+ runtime,
1468
+ sessionGeneration: runtime.sessionGeneration,
1469
+ dbg,
1470
+ });
1471
+ logLatency({
1472
+ type: "phase",
1473
+ phase: "session_start_sequence_read",
1474
+ filePath: cwd,
1475
+ startedAt: new Date(sequenceReadStartedAt).toISOString(),
1476
+ durationMs: Date.now() - sequenceReadStartedAt,
1477
+ metadata: { entries: latestSeq.fileSeqByPath.size, timedOut },
1478
+ });
962
1479
  runtime.seedProjectSequence?.(latestSeq.projectSeq, latestSeq.fileSeqByPath);
963
1480
  const effectiveSeq = runtime.projectSeq ?? latestSeq.projectSeq;
964
1481
  dbg(`session_start sequence: projectSeq=${effectiveSeq} fileSeqEntries=${latestSeq.fileSeqByPath.size}`);
965
- const snapshot = loadProjectSnapshot(snapshotRoot);
1482
+ // #1162 review follow-up (P3): a timed-out read's cold sentinel is
1483
+ // `projectSeq: 0`, which is indistinguishable from a project's real
1484
+ // first-ever snapshot (persisted with `seq === 0` before any change was
1485
+ // logged). Feeding `effectiveSeq` (0) straight into the freshness check
1486
+ // would let that legit seq-0 snapshot match and hydrate as FRESH even
1487
+ // though the on-disk log has since moved past it. Use a value the
1488
+ // freshness check can never match (`snapshot.seq` is always >= 0) ONLY
1489
+ // for this gate when the read timed out — `runtime.projectSeq` itself
1490
+ // stays 0 (untouched), which is what Fix 1's advancement guard above
1491
+ // relies on to detect an in-window bump.
1492
+ const freshnessSeq = timedOut ? UNKNOWN_PROJECT_SEQ : effectiveSeq;
1493
+ const snapshotLoadStartedAt = Date.now();
1494
+ const snapshotPath = getProjectSnapshotPath(snapshotRoot);
1495
+ let snapshotBytes = 0;
1496
+ try {
1497
+ snapshotBytes = nodeFs.statSync(snapshotPath).size;
1498
+ }
1499
+ catch {
1500
+ // Missing snapshots are the normal cold-start case.
1501
+ }
1502
+ const snapshotGate = loadSnapshotBodyUnlessStale({
1503
+ root: snapshotRoot,
1504
+ currentProjectSeq: freshnessSeq,
1505
+ dbg,
1506
+ });
1507
+ const snapshot = snapshotGate.snapshot;
1508
+ const snapshotFresh = isProjectSnapshotFresh(snapshot, freshnessSeq);
1509
+ logLatency({
1510
+ type: "phase",
1511
+ phase: "session_start_snapshot_load",
1512
+ filePath: cwd,
1513
+ startedAt: new Date(snapshotLoadStartedAt).toISOString(),
1514
+ durationMs: Date.now() - snapshotLoadStartedAt,
1515
+ metadata: {
1516
+ bytes: snapshotBytes,
1517
+ fresh: snapshotFresh,
1518
+ seq: snapshot?.seq ?? null,
1519
+ ...(snapshotGate.skippedStale ? { skippedStale: true } : {}),
1520
+ ...(timedOut ? { sequenceUnknown: true } : {}),
1521
+ },
1522
+ });
966
1523
  logProjectSnapshotProbe({
967
1524
  dbg,
968
1525
  root: snapshotRoot,
969
- currentProjectSeq: effectiveSeq,
1526
+ currentProjectSeq: freshnessSeq,
970
1527
  snapshot,
971
1528
  });
972
- if (isProjectSnapshotFresh(snapshot, effectiveSeq)) {
1529
+ if (snapshotFresh) {
973
1530
  hydrateRuntimeFromProjectSnapshot(runtime, snapshot);
974
1531
  }
975
1532
  const quickTools = [];
@@ -979,7 +1536,17 @@ export async function handleSessionStart(deps) {
979
1536
  log(`Active tools: ${quickTools.join(", ")}`);
980
1537
  dbg(`session_start tools: ${quickTools.join(", ") || "deferred (quick mode)"}`);
981
1538
  dbg("session_start: quick mode active - skipping slow tool probes, language profiling, preinstall, scans, and error debt baseline");
982
- dbg(`session_start total: ${Date.now() - sessionStartMs}ms (interactive path)`);
1539
+ const totalDurationMs = Date.now() - sessionStartMs;
1540
+ dbg(`session_start total: ${totalDurationMs}ms (interactive path)`);
1541
+ logLatency({
1542
+ type: "phase",
1543
+ phase: "session_start_total",
1544
+ filePath: cwd,
1545
+ startedAt: new Date(sessionStartMs).toISOString(),
1546
+ durationMs: totalDurationMs,
1547
+ metadata: { mode: startupMode, reason: deps.sessionReason },
1548
+ });
1549
+ emitSmellsSessionStartLine(dbg, sessionStartMs);
983
1550
  return;
984
1551
  }
985
1552
  const tools = [];
@@ -992,21 +1559,76 @@ export async function handleSessionStart(deps) {
992
1559
  dbg(`session_start: cleaned stale tsbuildinfo: ${cleaned.join(", ")}`);
993
1560
  }
994
1561
  }
1562
+ // Captured here (not at first use, below) because #1162's bounded read
1563
+ // needs it to gate the deferred reseed against a stale/moved-on session —
1564
+ // it's stable for the rest of this call (no further `resetForSession`
1565
+ // between here and the later uses of the same generation).
1566
+ const sessionGeneration = runtime.sessionGeneration;
1567
+ const sequenceReadStartedAt = Date.now();
995
1568
  const snapshotRoot = resolveSnapshotRoot(cwd);
996
- const latestSeq = readLatestProjectSequence(snapshotRoot);
1569
+ const { latestSeq, timedOut } = await readSequenceWithBudget({
1570
+ snapshotRoot,
1571
+ base: snapshotSequenceBase(snapshotRoot),
1572
+ cwd,
1573
+ runtime,
1574
+ sessionGeneration,
1575
+ dbg,
1576
+ });
1577
+ logLatency({
1578
+ type: "phase",
1579
+ phase: "session_start_sequence_read",
1580
+ filePath: cwd,
1581
+ startedAt: new Date(sequenceReadStartedAt).toISOString(),
1582
+ durationMs: Date.now() - sequenceReadStartedAt,
1583
+ metadata: { entries: latestSeq.fileSeqByPath.size, timedOut },
1584
+ });
997
1585
  runtime.seedProjectSequence?.(latestSeq.projectSeq, latestSeq.fileSeqByPath);
998
1586
  const effectiveSeq = runtime.projectSeq ?? latestSeq.projectSeq;
999
1587
  dbg(`session_start sequence: projectSeq=${effectiveSeq} fileSeqEntries=${latestSeq.fileSeqByPath.size}`);
1000
- const snapshot = loadProjectSnapshot(snapshotRoot);
1588
+ // #1162 review follow-up (P3) — see the matching comment in the quick-mode
1589
+ // path above: a timed-out read's cold sentinel (`projectSeq: 0`) must
1590
+ // never satisfy the freshness check, or a project's real first-ever
1591
+ // snapshot (persisted at `seq === 0`) would hydrate as fresh despite the
1592
+ // on-disk log having moved past it. `runtime.projectSeq` itself is left
1593
+ // at 0, which Fix 1's advancement guard above depends on.
1594
+ const freshnessSeq = timedOut ? UNKNOWN_PROJECT_SEQ : effectiveSeq;
1595
+ const snapshotLoadStartedAt = Date.now();
1596
+ const snapshotPath = getProjectSnapshotPath(snapshotRoot);
1597
+ let snapshotBytes = 0;
1598
+ try {
1599
+ snapshotBytes = nodeFs.statSync(snapshotPath).size;
1600
+ }
1601
+ catch {
1602
+ // Missing snapshots are the normal cold-start case.
1603
+ }
1604
+ const snapshotGate = loadSnapshotBodyUnlessStale({
1605
+ root: snapshotRoot,
1606
+ currentProjectSeq: freshnessSeq,
1607
+ dbg,
1608
+ });
1609
+ const snapshot = snapshotGate.snapshot;
1610
+ const snapshotFresh = isProjectSnapshotFresh(snapshot, freshnessSeq);
1611
+ logLatency({
1612
+ type: "phase",
1613
+ phase: "session_start_snapshot_load",
1614
+ filePath: cwd,
1615
+ startedAt: new Date(snapshotLoadStartedAt).toISOString(),
1616
+ durationMs: Date.now() - snapshotLoadStartedAt,
1617
+ metadata: {
1618
+ bytes: snapshotBytes,
1619
+ fresh: snapshotFresh,
1620
+ seq: snapshot?.seq ?? null,
1621
+ ...(snapshotGate.skippedStale ? { skippedStale: true } : {}),
1622
+ ...(timedOut ? { sequenceUnknown: true } : {}),
1623
+ },
1624
+ });
1001
1625
  logProjectSnapshotProbe({
1002
1626
  dbg,
1003
1627
  root: snapshotRoot,
1004
- currentProjectSeq: effectiveSeq,
1628
+ currentProjectSeq: freshnessSeq,
1005
1629
  snapshot,
1006
1630
  });
1007
- const freshSnapshot = isProjectSnapshotFresh(snapshot, effectiveSeq)
1008
- ? snapshot
1009
- : null;
1631
+ const freshSnapshot = snapshotFresh ? snapshot : null;
1010
1632
  if (freshSnapshot) {
1011
1633
  hydrateRuntimeFromProjectSnapshot(runtime, freshSnapshot);
1012
1634
  }
@@ -1020,9 +1642,22 @@ export async function handleSessionStart(deps) {
1020
1642
  ? freshSnapshot.startupScan
1021
1643
  : undefined;
1022
1644
  const startupScanSource = cachedStartupScan ? "snapshot" : "computed";
1023
- const startupScan = cachedStartupScan
1024
- ? { ...cachedStartupScan, cwd: path.resolve(cwd) }
1025
- : resolveStartupScanContext(cwd);
1645
+ let startupScan;
1646
+ if (cachedStartupScan) {
1647
+ startupScan = { ...cachedStartupScan, cwd: path.resolve(cwd) };
1648
+ }
1649
+ else {
1650
+ const scanContextStartedAt = Date.now();
1651
+ startupScan = resolveStartupScanContext(cwd);
1652
+ logLatency({
1653
+ type: "phase",
1654
+ phase: "session_start_scan_context_compute",
1655
+ filePath: cwd,
1656
+ startedAt: new Date(scanContextStartedAt).toISOString(),
1657
+ durationMs: Date.now() - scanContextStartedAt,
1658
+ metadata: { mode: startupMode },
1659
+ });
1660
+ }
1026
1661
  phase("scan-context");
1027
1662
  dbg(`session_start scan-context source=${startupScanSource}`);
1028
1663
  const scanRoot = startupScan.projectRoot ?? cwd;
@@ -1158,7 +1793,8 @@ export async function handleSessionStart(deps) {
1158
1793
  dbg("session_start: no project rules found");
1159
1794
  }
1160
1795
  cacheManager.writeCache("session-start-guidance", { content: agentStartupGuidance.join("\n") }, analysisRoot);
1161
- const sessionGeneration = runtime.sessionGeneration;
1796
+ // `sessionGeneration` was captured earlier (#1162's bounded sequence read
1797
+ // needs it before this point) and is stable across this whole call.
1162
1798
  if (!allowBootstrapTasks) {
1163
1799
  dbg("session_start: skipping startup background scans (startup mode)");
1164
1800
  }
@@ -1220,5 +1856,31 @@ export async function handleSessionStart(deps) {
1220
1856
  phase("lsp-config");
1221
1857
  }
1222
1858
  setSessionLanguages(languageProfile.detectedKinds);
1223
- dbg(`session_start total: ${Date.now() - sessionStartMs}ms (interactive path; background tasks may continue)`);
1859
+ const totalDurationMs = Date.now() - sessionStartMs;
1860
+ dbg(`session_start total: ${totalDurationMs}ms (interactive path; background tasks may continue)`);
1861
+ logLatency({
1862
+ type: "phase",
1863
+ phase: "session_start_total",
1864
+ filePath: cwd,
1865
+ startedAt: new Date(sessionStartMs).toISOString(),
1866
+ durationMs: totalDurationMs,
1867
+ metadata: { mode: startupMode, reason: deps.sessionReason },
1868
+ });
1869
+ emitSmellsSessionStartLine(dbg, sessionStartMs);
1870
+ }
1871
+ /**
1872
+ * #1123 item 3: one bounded `session_start` line surfacing smells the manual
1873
+ * `npm run logs:smells` analyzer would otherwise only catch on demand — see
1874
+ * `clients/smells-rollup.ts` for the tail-scan cost bound and threshold
1875
+ * gating. Never throws: a rollup miss must not break session_start.
1876
+ */
1877
+ function emitSmellsSessionStartLine(dbg, sessionStartMs) {
1878
+ try {
1879
+ const line = formatSmellsSessionStartLine(countRecentSmells(undefined, sessionStartMs));
1880
+ if (line)
1881
+ dbg(line);
1882
+ }
1883
+ catch {
1884
+ // best-effort — smells rollup must never break session_start
1885
+ }
1224
1886
  }