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
@@ -6,16 +6,19 @@
6
6
  * connects to it to get LSP-complete diagnostics from the warm process instead
7
7
  * of running its own cold analysis.
8
8
  *
9
- * This module is the CLIENT + the shared path derivation only — deliberately
10
- * light (node:net + type-only result), so the bin can try the warm path WITHOUT
11
- * loading the dispatch graph. The server side lives in mcp/server.ts (which
12
- * already holds the analysis engine). If the warm path is unavailable, the
13
- * client resolves `undefined` and the caller falls back to cold local analysis.
9
+ * This module is the CLIENT + the shared path derivation + the one-shot line
10
+ * reader the server wires into its socket (deliberately light: node:net +
11
+ * type-only result, so the bin can try the warm path WITHOUT loading the
12
+ * dispatch graph). The analysis engine lives in mcp/server.ts. If the warm
13
+ * path is unavailable, the client resolves `undefined` and the caller falls
14
+ * back to cold local analysis.
14
15
  */
15
16
  import * as crypto from "node:crypto";
17
+ import * as fs from "node:fs";
16
18
  import * as net from "node:net";
17
19
  import * as os from "node:os";
18
20
  import * as path from "node:path";
21
+ import { writeFileAtomic } from "../atomic-write.js";
19
22
  export const WARM_DIAGNOSTICS_SCHEMA_VERSION = 1;
20
23
  export const WARM_CODE_ACTION_LOOKUP_LIMIT = 6;
21
24
  /**
@@ -25,19 +28,23 @@ export const WARM_CODE_ACTION_LOOKUP_LIMIT = 6;
25
28
  * the same project they meet. Mismatch → the client just falls back to cold.
26
29
  */
27
30
  export function ipcPathForCwd(cwd) {
28
- const root = path.resolve(cwd).toLowerCase();
29
- // sha256 (not for security — just a stable short id for the IPC socket/pipe
30
- // name keyed by cwd; sha256 over sha1 keeps SonarCloud's weak-hash check quiet)
31
- const hash = crypto
32
- .createHash("sha256")
33
- .update(root)
34
- .digest("hex")
35
- .slice(0, 16);
31
+ const hash = workspaceHash(cwd);
36
32
  if (process.platform === "win32") {
37
33
  return `\\\\.\\pipe\\pi-lens-mcp-${hash}`;
38
34
  }
39
35
  return path.join(os.tmpdir(), `pi-lens-mcp-${hash}.sock`);
40
36
  }
37
+ /**
38
+ * The single stable per-workspace id both endpoint derivations key on. Every
39
+ * per-workspace side-channel name (socket/pipe, turn-end status file) must come
40
+ * from HERE, so the hook process and the server process cannot drift apart.
41
+ */
42
+ function workspaceHash(cwd) {
43
+ const root = path.resolve(cwd).toLowerCase();
44
+ // sha256 (not for security — just a stable short id for the IPC socket/pipe
45
+ // name keyed by cwd; sha256 over sha1 keeps SonarCloud's weak-hash check quiet)
46
+ return crypto.createHash("sha256").update(root).digest("hex").slice(0, 16);
47
+ }
41
48
  /** PID-scoped endpoint used by pi sessions. The legacy MCP analyze endpoint
42
49
  * remains workspace-scoped for compatibility with the PostToolUse hook. */
43
50
  export function diagnosticsIpcPathForCwd(cwd, pid) {
@@ -50,15 +57,16 @@ export function contentHash(content) {
50
57
  return crypto.createHash("sha256").update(content).digest("hex");
51
58
  }
52
59
  /**
53
- * Shared one-shot request/response transport for the warm-attach IPC routes
54
- * (#822): connect to the incumbent's PID-scoped endpoint, write one JSON
55
- * line, read one JSON line back, classify. The per-route `validate` callback
56
- * returns a failure reason for an on-time but unusable reply (schema skew,
57
- * staleness) or `undefined` to accept it; transport failures map uniformly to
58
- * timeout/ipc-error. One transport, N routes — the diagnostics and
59
- * code-action clients cannot drift apart.
60
+ * Shared one-shot request/response transport for the tagged IPC routes (#822):
61
+ * connect to `endpoint`, write one JSON line, read one JSON line back,
62
+ * classify. The endpoint is PID-scoped for the warm-attach routes and
63
+ * workspace-scoped for the hook bin's turn-end route. The per-route `validate`
64
+ * callback returns a failure reason for an on-time but unusable reply (schema
65
+ * skew, staleness) or `undefined` to accept it; transport failures map
66
+ * uniformly to timeout/ipc-error. One transport, N routes — the clients cannot
67
+ * drift apart.
60
68
  */
61
- function requestOverWarmIpc(cwd, incumbentPid, timeoutMs, buildRequest, validate) {
69
+ function requestOverWarmIpc(endpoint, timeoutMs, buildRequest, validate) {
62
70
  return new Promise((resolve) => {
63
71
  let settled = false;
64
72
  const finish = (value) => {
@@ -70,7 +78,7 @@ function requestOverWarmIpc(cwd, incumbentPid, timeoutMs, buildRequest, validate
70
78
  resolve(value);
71
79
  };
72
80
  const deadlineAt = Date.now() + timeoutMs;
73
- const socket = net.createConnection(diagnosticsIpcPathForCwd(cwd, incumbentPid));
81
+ const socket = net.createConnection(endpoint);
74
82
  socket.setEncoding("utf8");
75
83
  let buffer = "";
76
84
  const timer = setTimeout(() => finish({ available: false, reason: "timeout" }), timeoutMs);
@@ -108,7 +116,7 @@ function requestOverWarmIpc(cwd, incumbentPid, timeoutMs, buildRequest, validate
108
116
  }
109
117
  export function requestWarmDiagnostics(cwd, incumbentPid, file, content, timeoutMs) {
110
118
  const expectedHash = contentHash(content);
111
- return requestOverWarmIpc(cwd, incumbentPid, timeoutMs, (deadlineAt) => ({
119
+ return requestOverWarmIpc(diagnosticsIpcPathForCwd(cwd, incumbentPid), timeoutMs, (deadlineAt) => ({
112
120
  route: "diagnostics",
113
121
  version: WARM_DIAGNOSTICS_SCHEMA_VERSION,
114
122
  file,
@@ -131,7 +139,7 @@ export function requestWarmDiagnostics(cwd, incumbentPid, file, content, timeout
131
139
  });
132
140
  }
133
141
  export function requestWarmCodeActions(cwd, incumbentPid, file, expectedContentHash, ranges, timeoutMs) {
134
- return requestOverWarmIpc(cwd, incumbentPid, timeoutMs, (deadlineAt) => ({
142
+ return requestOverWarmIpc(diagnosticsIpcPathForCwd(cwd, incumbentPid), timeoutMs, (deadlineAt) => ({
135
143
  route: "code-actions",
136
144
  version: WARM_DIAGNOSTICS_SCHEMA_VERSION,
137
145
  file,
@@ -154,6 +162,99 @@ export function requestWarmCodeActions(cwd, incumbentPid, file, expectedContentH
154
162
  return undefined;
155
163
  });
156
164
  }
165
+ // v2 adds an explicit receipt acknowledgement. A v1 server must reject rather
166
+ // than consume a pass without the new delivery contract.
167
+ export const WARM_TURN_END_SCHEMA_VERSION = 2;
168
+ /**
169
+ * Ask the warm server to run pi-lens's real turn-end pass. Execution and
170
+ * delivery are separate: the first one-shot connection returns a capability,
171
+ * then a second one-shot connection acknowledges receipt. If the client
172
+ * deadline or either connection loses, the server leaves the durable finding
173
+ * cache untouched for a later Stop. 55 s expires inside Claude Code's 60 s hook
174
+ * timeout.
175
+ */
176
+ export async function requestWarmTurnEnd(cwd, timeoutMs = 55_000) {
177
+ const startedAt = Date.now();
178
+ const first = await requestOverWarmIpc(ipcPathForCwd(cwd), timeoutMs, () => ({
179
+ route: "turn-end",
180
+ version: WARM_TURN_END_SCHEMA_VERSION,
181
+ cwd,
182
+ }), (result) => result.route === "turn-end" &&
183
+ result.version === WARM_TURN_END_SCHEMA_VERSION
184
+ ? undefined
185
+ : "schema-mismatch");
186
+ if (!first.available || !first.response.deliveryId)
187
+ return first;
188
+ const remainingMs = timeoutMs - (Date.now() - startedAt);
189
+ if (remainingMs <= 0)
190
+ return { available: false, reason: "timeout" };
191
+ const ack = await requestOverWarmIpc(ipcPathForCwd(cwd), remainingMs, () => ({
192
+ route: "turn-end-ack",
193
+ version: WARM_TURN_END_SCHEMA_VERSION,
194
+ cwd,
195
+ deliveryId: first.response.deliveryId,
196
+ }), (result) => result.route === "turn-end-ack" && result.acknowledged === true
197
+ ? undefined
198
+ : "ipc-error");
199
+ return ack.available
200
+ ? { available: true, response: first.response }
201
+ : { available: false, reason: ack.reason };
202
+ }
203
+ /** Per-workspace status file, keyed by the same hash as the IPC endpoint. */
204
+ export function turnEndStatusPathForCwd(cwd) {
205
+ return path.join(os.tmpdir(), `pi-lens-turn-end-${workspaceHash(cwd)}.json`);
206
+ }
207
+ export function readTurnEndStatus(cwd) {
208
+ try {
209
+ const raw = fs.readFileSync(turnEndStatusPathForCwd(cwd), "utf8");
210
+ const parsed = JSON.parse(raw);
211
+ if (!parsed || typeof parsed !== "object")
212
+ return undefined;
213
+ return {
214
+ ran: typeof parsed.ran === "number" ? parsed.ran : 0,
215
+ skipped: typeof parsed.skipped === "number" ? parsed.skipped : 0,
216
+ lastSkipReason: parsed.lastSkipReason,
217
+ lastRunAt: parsed.lastRunAt,
218
+ lastSkipAt: parsed.lastSkipAt,
219
+ };
220
+ }
221
+ catch {
222
+ // never written, unreadable, or corrupt — "no turn-end activity recorded"
223
+ return undefined;
224
+ }
225
+ }
226
+ /**
227
+ * Append one turn-end outcome from the hook process. Never throws.
228
+ *
229
+ * Read-modify-write against a shared per-workspace tmpdir file: two Stop
230
+ * hooks for the same workspace can race this concurrently (separate
231
+ * processes, no lock). `writeFileAtomic` only closes the *publication* half
232
+ * of that — it guarantees this write's own staging+rename can't torn-read
233
+ * (parse-fail and reset counters) or hit a Windows sharing violation against
234
+ * a concurrent writer's rename. It does NOT fix the read-modify-write race
235
+ * itself: two overlapping calls can still both read the same `previous` and
236
+ * publish from it, silently dropping one increment. That's accepted here —
237
+ * this is bounded best-effort telemetry (self-heals, errors already
238
+ * swallowed below), and a lock on this path isn't worth it.
239
+ */
240
+ export function recordTurnEndOutcome(cwd, outcome) {
241
+ try {
242
+ const now = new Date().toISOString();
243
+ const previous = readTurnEndStatus(cwd) ?? { ran: 0, skipped: 0 };
244
+ const next = outcome.ran
245
+ ? { ...previous, ran: previous.ran + 1, lastRunAt: now }
246
+ : {
247
+ ...previous,
248
+ skipped: previous.skipped + 1,
249
+ lastSkipReason: outcome.reason,
250
+ lastSkipAt: now,
251
+ };
252
+ writeFileAtomic(turnEndStatusPathForCwd(cwd), `${JSON.stringify(next)}\n`);
253
+ }
254
+ catch {
255
+ // telemetry only — a read-only tmpdir must not break the Stop hook
256
+ }
257
+ }
157
258
  /**
158
259
  * Ask the warm server to analyze a file. Resolves the server's result, or
159
260
  * `undefined` on ANY failure (no server, refused, stale socket, timeout, bad
@@ -200,3 +301,35 @@ export function requestWarmAnalyze(cwd, file, timeoutMs = 30_000) {
200
301
  socket.on("close", () => finish(undefined));
201
302
  });
202
303
  }
304
+ /**
305
+ * One-shot line reader for the warm IPC socket (#1219). The clients write
306
+ * exactly one newline-terminated request per connection and read one reply, so
307
+ * the server must dispatch at most one line and ignore anything after it — a
308
+ * `data` handler that keeps re-reading the same buffered line re-dispatches
309
+ * the request on stray bytes. Returns the handler to attach to the socket's
310
+ * `data` event.
311
+ */
312
+ export function createWarmIpcLineReader(onLine) {
313
+ let buffer = "";
314
+ let dispatched = false;
315
+ return (chunk) => {
316
+ if (dispatched)
317
+ return;
318
+ buffer += chunk;
319
+ const newline = buffer.indexOf("\n");
320
+ if (newline === -1)
321
+ return;
322
+ dispatched = true;
323
+ onLine(buffer.slice(0, newline));
324
+ };
325
+ }
326
+ export function createWarmIpcRequestQueue() {
327
+ let chain = Promise.resolve();
328
+ return {
329
+ enqueue(work) {
330
+ const next = chain.then(work);
331
+ chain = next.catch(() => undefined);
332
+ return next;
333
+ },
334
+ };
335
+ }
@@ -7,6 +7,8 @@
7
7
  * `pilens_analyze mode=fresh` measures the just-built code first-hand.
8
8
  */
9
9
  import { spawn } from "node:child_process";
10
+ import { existsSync } from "node:fs";
11
+ import { join } from "node:path";
10
12
  import { pmBinary, resolveNodePackageManager, runScriptArgs, } from "../package-manager.js";
11
13
  import { safeSpawnAsync } from "../safe-spawn.js";
12
14
  /**
@@ -31,9 +33,21 @@ export function analyzeFileFresh(workerPath, file, cwd, options = {}, timeoutMs
31
33
  const args = [workerPath, `--file=${file}`, `--cwd=${cwd}`];
32
34
  if (options.flags)
33
35
  args.push(`--flags=${JSON.stringify(options.flags)}`);
34
- const child = spawn(process.execPath, args, {
35
- stdio: ["ignore", "pipe", "pipe"],
36
- });
36
+ let child;
37
+ try {
38
+ child = spawn(process.execPath, args, {
39
+ stdio: ["ignore", "pipe", "pipe"],
40
+ });
41
+ }
42
+ catch (err) {
43
+ // SYNCHRONOUS spawn throw (Windows `spawn UNKNOWN`/EINVAL, the pidusage
44
+ // bug class, #533) — resolve the failure rather than reject/crash the
45
+ // host; every caller inspects the outcome's `error` field.
46
+ resolve({
47
+ error: `failed to fork worker: ${err instanceof Error ? err.message : String(err)}`,
48
+ });
49
+ return;
50
+ }
37
51
  let stdout = "";
38
52
  let stderr = "";
39
53
  let settled = false;
@@ -71,6 +85,17 @@ export function analyzeFileFresh(workerPath, file, cwd, options = {}, timeoutMs
71
85
  });
72
86
  });
73
87
  }
88
+ /**
89
+ * Rebuilds are safe only from a source checkout. Published packages contain
90
+ * `dist/` but not tsconfig.dist.json, and build:dist deletes dist before tsc.
91
+ * The node_modules check also refuses unusual installs that happen to carry a
92
+ * stray tsconfig.
93
+ */
94
+ export function canRebuildPiLens(repoRoot) {
95
+ const inNodeModules = /(^|[\\/])node_modules([\\/]|$)/i.test(repoRoot);
96
+ return !inNodeModules && existsSync(join(repoRoot, "tsconfig.dist.json"));
97
+ }
98
+ export const REBUILD_UNAVAILABLE_MESSAGE = "pilens_rebuild is unavailable in an installed pi-lens package. Rebuilding is only safe from a source checkout containing tsconfig.dist.json; reinstall or update pi-lens through your package manager instead.";
74
99
  /**
75
100
  * Run `<pm> run <script>` in the pi-lens repo, where `<pm>` is resolved from the
76
101
  * repo's lockfile / installed managers. Uses `safeSpawnAsync` (Windows
@@ -78,6 +103,14 @@ export function analyzeFileFresh(workerPath, file, cwd, options = {}, timeoutMs
78
103
  */
79
104
  export async function runRebuild(repoRoot, script, timeoutMs = 300_000) {
80
105
  const start = Date.now();
106
+ if (!canRebuildPiLens(repoRoot)) {
107
+ return {
108
+ ok: false,
109
+ script,
110
+ durationMs: Date.now() - start,
111
+ output: REBUILD_UNAVAILABLE_MESSAGE,
112
+ };
113
+ }
81
114
  const packageManager = await resolveNodePackageManager(repoRoot);
82
115
  const res = await safeSpawnAsync(pmBinary(packageManager), runScriptArgs(script), {
83
116
  cwd: repoRoot,
@@ -5,7 +5,7 @@
5
5
  * doesn't — session-start warms the dominant-language LSP (so warm `analyze` is
6
6
  * LSP-complete), establishes the error-debt baseline + complexity baselines, and
7
7
  * kicks off knip/jscpd/type-coverage/dep/secrets scans; turn-end runs
8
- * knip/jscpd incrementally, dep-circular, tests, cascade, and the
8
+ * knip incrementally, dep-circular, tests, cascade, and the
9
9
  * actionable/code-quality aggregation.
10
10
  *
11
11
  * The handlers don't return findings — they emit them through the same
@@ -16,15 +16,16 @@
16
16
  * persistent RuntimeCoordinator + CacheManager (so baselines/turn-state survive
17
17
  * across calls, like a real session), and the bootstrap client bundle.
18
18
  */
19
+ import * as crypto from "node:crypto";
19
20
  import * as fs from "node:fs";
20
21
  import * as path from "node:path";
21
22
  import { AstGrepClient } from "../ast-grep-client.js";
22
23
  import { loadBootstrapClients } from "../bootstrap.js";
23
- import { CacheManager } from "../cache-manager.js";
24
+ import { CacheManager, MCP_TURN_STATE_OWNER_ID, } from "../cache-manager.js";
24
25
  import { resetDispatchBaselines } from "../dispatch/integration.js";
25
26
  import { resetFormatService } from "../format-service.js";
26
27
  import { getLSPService, resetLSPService } from "../lsp/index.js";
27
- import { consumeSessionStartGuidance, consumeTestFindings, consumeTurnEndFindings, } from "../runtime-context.js";
28
+ import { consumeSessionStartGuidance, consumeTestFindings, consumeTurnEndFindings, peekTestFindings, peekTurnEndFindings, } from "../runtime-context.js";
28
29
  import { RuntimeCoordinator } from "../runtime-coordinator.js";
29
30
  import { handleSessionStart } from "../runtime-session.js";
30
31
  import { handleTurnEnd } from "../runtime-turn.js";
@@ -105,12 +106,82 @@ export async function runSessionStart(cwd) {
105
106
  aliveLspClients: getLSPService().getAliveClientCount(),
106
107
  };
107
108
  }
109
+ /**
110
+ * #1274: the delivery map used to be unbounded — every timed-out client and
111
+ * every distinct raw-cwd alias left an entry for the life of the process.
112
+ * Both bounds drop entries WITHOUT committing, which re-arms the findings in
113
+ * the cache: the safe direction, since an un-consumed finding is re-reported on
114
+ * a later Stop while a wrongly-consumed one is gone for good. The TTL is
115
+ * generous next to Claude Code's 60 s hook budget — it exists to bound the map,
116
+ * not to police clients.
117
+ */
118
+ const TURN_END_DELIVERY_TTL_MS = 10 * 60_000;
119
+ const TURN_END_DELIVERY_MAX = 8;
120
+ const TURN_END_QUEUE_WAIT_MS = 5_000;
121
+ /**
122
+ * A bounded, cancellable serial queue. A turn_end mutates shared runtime and
123
+ * cache state, so concurrent passes are unsafe; a disconnected/hung pass must
124
+ * nevertheless not accumulate an unbounded tail of Stop requests.
125
+ */
126
+ class TurnEndQueue {
127
+ running = false;
128
+ pending = [];
129
+ enqueue(work, waitMs = TURN_END_QUEUE_WAIT_MS) {
130
+ if (this.pending.length >= 1) {
131
+ return Promise.reject(new Error("turn_end queue is busy"));
132
+ }
133
+ return new Promise((resolve, reject) => {
134
+ const item = {
135
+ work,
136
+ resolve,
137
+ reject,
138
+ timer: setTimeout(() => {
139
+ const index = this.pending.indexOf(item);
140
+ if (index === -1)
141
+ return;
142
+ this.pending.splice(index, 1);
143
+ reject(new Error("turn_end queue wait timed out"));
144
+ }, waitMs),
145
+ };
146
+ item.timer.unref();
147
+ this.pending.push(item);
148
+ this.drain();
149
+ });
150
+ }
151
+ drain() {
152
+ if (this.running)
153
+ return;
154
+ const item = this.pending.shift();
155
+ if (!item)
156
+ return;
157
+ clearTimeout(item.timer);
158
+ this.running = true;
159
+ void item
160
+ .work()
161
+ .then(item.resolve, item.reject)
162
+ .finally(() => {
163
+ this.running = false;
164
+ this.drain();
165
+ });
166
+ }
167
+ reset() {
168
+ for (const item of this.pending.splice(0)) {
169
+ clearTimeout(item.timer);
170
+ item.reject(new Error("turn_end queue reset"));
171
+ }
172
+ this.running = false;
173
+ }
174
+ }
175
+ const turnEndQueue = new TurnEndQueue();
176
+ const pendingTurnEndDeliveries = new Map();
177
+ /** In-flight Stop-hook passes, keyed by cwd — see `runTurnEndForIpc` (#1274). */
178
+ const inFlightIpcTurnEnds = new Map();
108
179
  /**
109
180
  * Run pi-lens's real turn_end over the files edited this "turn". The handler
110
181
  * reads edited files from turn-state, so we register the caller-supplied files
111
182
  * first (a full-file range, importsChanged=true so dep/knip re-check broadly).
112
183
  */
113
- export async function runTurnEnd(cwd, files = []) {
184
+ async function runTurnEndNow(cwd, files = [], deferredDelivery = false) {
114
185
  const ctx = await getMcpSessionContext();
115
186
  const host = createMcpHost(undefined, cwd);
116
187
  let registered = 0;
@@ -123,9 +194,15 @@ export async function runTurnEnd(cwd, files = []) {
123
194
  catch {
124
195
  continue; // unreadable / deleted — skip
125
196
  }
126
- ctx.cacheManager.addModifiedRange(abs, { start: 1, end: lineCount }, true, cwd, ctx.runtime.telemetrySessionId);
197
+ ctx.cacheManager.addModifiedRange(abs, { start: 1, end: lineCount }, true, cwd, MCP_TURN_STATE_OWNER_ID, "mcp");
127
198
  registered++;
128
199
  }
200
+ const owner = {
201
+ kind: "mcp",
202
+ id: MCP_TURN_STATE_OWNER_ID,
203
+ pid: process.pid,
204
+ lastSeen: new Date().toISOString(),
205
+ };
129
206
  await handleTurnEnd({
130
207
  ctxCwd: cwd,
131
208
  getFlag: host.getFlag,
@@ -136,12 +213,143 @@ export async function runTurnEnd(cwd, files = []) {
136
213
  deadCodeClients: ctx.clients.deadCodeClients,
137
214
  depChecker: ctx.clients.depChecker,
138
215
  testRunnerClient: ctx.clients.testRunnerClient,
216
+ owner,
139
217
  resetLSPService,
140
218
  resetFormatService,
141
219
  });
220
+ const outcome = deferredDelivery
221
+ ? {
222
+ turnEnd: joinMessages(peekTurnEndFindings(ctx.cacheManager, cwd)),
223
+ tests: joinMessages(peekTestFindings(ctx.cacheManager, cwd)),
224
+ filesRegistered: registered,
225
+ }
226
+ : {
227
+ turnEnd: joinMessages(consumeTurnEndFindings(ctx.cacheManager, cwd)),
228
+ tests: joinMessages(consumeTestFindings(ctx.cacheManager, cwd)),
229
+ filesRegistered: registered,
230
+ };
142
231
  return {
143
- turnEnd: joinMessages(consumeTurnEndFindings(ctx.cacheManager, cwd)),
144
- tests: joinMessages(consumeTestFindings(ctx.cacheManager, cwd)),
145
- filesRegistered: registered,
232
+ outcome,
233
+ commit: () => {
234
+ if (!deferredDelivery)
235
+ return;
236
+ consumeTurnEndFindings(ctx.cacheManager, cwd);
237
+ consumeTestFindings(ctx.cacheManager, cwd);
238
+ },
146
239
  };
147
240
  }
241
+ /**
242
+ * Run a normal MCP turn_end. Its caller owns the tool response, so the
243
+ * historical consume-on-return behavior remains unchanged.
244
+ */
245
+ export function runTurnEnd(cwd, files = []) {
246
+ return turnEndQueue.enqueue(async () => (await runTurnEndNow(cwd, files)).outcome);
247
+ }
248
+ /** A result with no findings needs no durable delivery transaction. */
249
+ function hasTurnEndFindings(outcome) {
250
+ return Boolean(outcome.turnEnd || outcome.tests);
251
+ }
252
+ /** Drop expired deliveries, then the oldest ones over the cap. Never commits. */
253
+ function prunePendingTurnEndDeliveries(now = Date.now()) {
254
+ for (const [deliveryId, delivery] of pendingTurnEndDeliveries) {
255
+ if (now - delivery.createdAt >= TURN_END_DELIVERY_TTL_MS) {
256
+ pendingTurnEndDeliveries.delete(deliveryId);
257
+ }
258
+ }
259
+ // Map iteration is insertion-ordered, so the head is the oldest entry.
260
+ while (pendingTurnEndDeliveries.size > TURN_END_DELIVERY_MAX) {
261
+ const oldest = pendingTurnEndDeliveries.keys().next();
262
+ if (oldest.done)
263
+ break;
264
+ pendingTurnEndDeliveries.delete(oldest.value);
265
+ }
266
+ }
267
+ function pendingForCwd(cwd) {
268
+ for (const [deliveryId, delivery] of pendingTurnEndDeliveries) {
269
+ if (delivery.cwd === cwd)
270
+ return [deliveryId, delivery];
271
+ }
272
+ return undefined;
273
+ }
274
+ /**
275
+ * Run the Stop-hook pass as a durable delivery transaction. The result is
276
+ * acknowledged through a separate one-shot IPC request. Until that request
277
+ * arrives, the findings cache is deliberately left unconsumed; a client
278
+ * timeout, socket close, or server restart therefore leaves the result for a
279
+ * later Stop request instead of losing it between execution and reply.
280
+ */
281
+ export function runTurnEndForIpc(cwd) {
282
+ // #1274: the Stop-hook request carries no files and no sessionId, so two
283
+ // overlapping ones are byte-identical and a second pass would be pure waste
284
+ // — worse, the queue only holds ONE waiter, so a third Stop is rejected
285
+ // outright. Identical in-flight requests share the one pass and one
286
+ // deliveryId; the ack is idempotent-by-capability, so the loser of the race
287
+ // simply finds the delivery already committed.
288
+ const inFlight = inFlightIpcTurnEnds.get(cwd);
289
+ if (inFlight)
290
+ return inFlight;
291
+ const run = runTurnEndForIpcNow(cwd).finally(() => {
292
+ inFlightIpcTurnEnds.delete(cwd);
293
+ });
294
+ inFlightIpcTurnEnds.set(cwd, run);
295
+ return run;
296
+ }
297
+ function runTurnEndForIpcNow(cwd) {
298
+ return turnEndQueue.enqueue(async () => {
299
+ prunePendingTurnEndDeliveries();
300
+ const pending = pendingForCwd(cwd);
301
+ if (pending) {
302
+ return {
303
+ outcome: pending[1].transaction.outcome,
304
+ deliveryId: pending[0],
305
+ };
306
+ }
307
+ const ctx = await getMcpSessionContext();
308
+ const cachedOutcome = {
309
+ turnEnd: joinMessages(peekTurnEndFindings(ctx.cacheManager, cwd)),
310
+ tests: joinMessages(peekTestFindings(ctx.cacheManager, cwd)),
311
+ filesRegistered: 0,
312
+ };
313
+ const transaction = hasTurnEndFindings(cachedOutcome)
314
+ ? {
315
+ outcome: cachedOutcome,
316
+ commit: () => {
317
+ consumeTurnEndFindings(ctx.cacheManager, cwd);
318
+ consumeTestFindings(ctx.cacheManager, cwd);
319
+ },
320
+ }
321
+ : await runTurnEndNow(cwd, [], true);
322
+ if (!hasTurnEndFindings(transaction.outcome)) {
323
+ return { outcome: transaction.outcome };
324
+ }
325
+ const deliveryId = crypto.randomUUID();
326
+ pendingTurnEndDeliveries.set(deliveryId, {
327
+ cwd,
328
+ transaction,
329
+ createdAt: Date.now(),
330
+ });
331
+ prunePendingTurnEndDeliveries();
332
+ return { outcome: transaction.outcome, deliveryId };
333
+ });
334
+ }
335
+ /** Commit exactly one admitted delivery capability. */
336
+ export function acknowledgeTurnEnd(cwd, deliveryId) {
337
+ prunePendingTurnEndDeliveries();
338
+ const delivery = pendingTurnEndDeliveries.get(deliveryId);
339
+ if (!delivery || delivery.cwd !== cwd)
340
+ return false;
341
+ // #1274: commit BEFORE dropping the capability. Deleting first meant a
342
+ // throwing consume destroyed the only handle to the findings — precisely the
343
+ // loss this two-phase protocol exists to prevent, reintroduced on the error
344
+ // path. Leaving the entry in place on a throw keeps the delivery re-fetchable
345
+ // by a later Stop.
346
+ delivery.transaction.commit();
347
+ pendingTurnEndDeliveries.delete(deliveryId);
348
+ return true;
349
+ }
350
+ /** Test hook — drop pending requests so one failed test cannot wedge the rest. */
351
+ export function _resetTurnEndChain() {
352
+ turnEndQueue.reset();
353
+ pendingTurnEndDeliveries.clear();
354
+ inFlightIpcTurnEnds.clear();
355
+ }