pi-lens 4.2.1 → 4.4.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 (671) hide show
  1. package/CHANGELOG.md +1562 -0
  2. package/README.md +157 -24
  3. package/config/dependency-cruiser-eager-allowlist.json +6 -2
  4. package/dist/chunk-22AVIGXS.js +560 -0
  5. package/dist/chunk-27BBHSZC.js +106 -0
  6. package/dist/chunk-2BEMIWEW.js +51 -0
  7. package/dist/chunk-2EECBNC5.js +89 -0
  8. package/dist/chunk-34U7PLGE.js +23 -0
  9. package/dist/chunk-3I5QFT3N.js +181 -0
  10. package/dist/chunk-3MED75HT.js +37 -0
  11. package/dist/chunk-47D2BO4S.js +87 -0
  12. package/dist/chunk-4RERDEXR.js +348 -0
  13. package/dist/chunk-4W2PLC4J.js +27 -0
  14. package/dist/chunk-52H5B5TC.js +202 -0
  15. package/dist/chunk-54B42YRX.js +27 -0
  16. package/dist/chunk-5RXBNSW2.js +266 -0
  17. package/dist/chunk-5THXD6X5.js +201 -0
  18. package/dist/chunk-5W3R6LFT.js +24 -0
  19. package/dist/chunk-5ZEJHV35.js +341 -0
  20. package/dist/chunk-6P62QVEA.js +118 -0
  21. package/dist/chunk-6QIUX4EP.js +459 -0
  22. package/dist/chunk-6VCD4VKZ.js +78 -0
  23. package/dist/chunk-7F72PXY2.js +326 -0
  24. package/dist/chunk-7FBF7NPR.js +998 -0
  25. package/dist/chunk-7U2IDNXN.js +37 -0
  26. package/dist/chunk-ABBOA7UD.js +157 -0
  27. package/dist/chunk-AHDW3GPE.js +50 -0
  28. package/dist/chunk-AJ3QXTRQ.js +756 -0
  29. package/dist/chunk-AJVLWNFN.js +1610 -0
  30. package/dist/chunk-AJXODZY6.js +112 -0
  31. package/dist/chunk-ARFCXG7S.js +84 -0
  32. package/dist/chunk-AS44CFQ4.js +708 -0
  33. package/dist/chunk-AWE5TMPO.js +38 -0
  34. package/dist/chunk-B3I2UUT4.js +4692 -0
  35. package/dist/chunk-BRJKOBZP.js +331 -0
  36. package/dist/chunk-BW5KFIQC.js +59 -0
  37. package/dist/chunk-C2AUYXQH.js +149 -0
  38. package/dist/chunk-CGGAIP7J.js +29 -0
  39. package/dist/chunk-D6QS3U6M.js +30 -0
  40. package/dist/chunk-DFVMIKMQ.js +349 -0
  41. package/dist/chunk-DIULIWKU.js +169 -0
  42. package/dist/chunk-DQ2NZ7C4.js +2317 -0
  43. package/dist/chunk-E2WFBRHM.js +213 -0
  44. package/dist/chunk-E4MAEDPM.js +50 -0
  45. package/dist/chunk-EOKRQ3SA.js +30 -0
  46. package/dist/chunk-F3AU2TMM.js +2626 -0
  47. package/dist/chunk-F3P7VQ7H.js +170 -0
  48. package/dist/chunk-FC4RP4I2.js +12 -0
  49. package/dist/chunk-FJNKANOS.js +32 -0
  50. package/dist/chunk-GUOGVTCQ.js +146 -0
  51. package/dist/chunk-GVXA6CCE.js +18 -0
  52. package/dist/chunk-HHYAELLJ.js +2334 -0
  53. package/dist/chunk-HMFXILPV.js +83 -0
  54. package/dist/chunk-HVUZXSWK.js +421 -0
  55. package/dist/chunk-HWBZIGMJ.js +62 -0
  56. package/dist/chunk-I3R7GKDR.js +17 -0
  57. package/dist/chunk-I7SPGOWI.js +55 -0
  58. package/dist/chunk-IIXOAGHR.js +38 -0
  59. package/dist/chunk-IVP5KAB7.js +2250 -0
  60. package/dist/chunk-IXEBJSUE.js +22 -0
  61. package/dist/chunk-JOLITGCC.js +27 -0
  62. package/dist/chunk-K6VYLB2U.js +145 -0
  63. package/dist/chunk-LJDODBBZ.js +78 -0
  64. package/dist/chunk-LNAKEO63.js +78 -0
  65. package/dist/chunk-LSMJ6KBE.js +4139 -0
  66. package/dist/chunk-LW6XKDZQ.js +5565 -0
  67. package/dist/chunk-N3YQJI6O.js +899 -0
  68. package/dist/chunk-NABLC7W3.js +148 -0
  69. package/dist/chunk-NKOUFPQF.js +659 -0
  70. package/dist/chunk-NL5GLMFI.js +211 -0
  71. package/dist/chunk-NMABWBZN.js +327 -0
  72. package/dist/chunk-NTHH2J74.js +27 -0
  73. package/dist/chunk-NTUJEGDZ.js +59 -0
  74. package/dist/chunk-NXL4FFQQ.js +47 -0
  75. package/dist/chunk-NXPS2L6U.js +466 -0
  76. package/dist/chunk-O5WILGMI.js +42 -0
  77. package/dist/chunk-O6TQT6RI.js +48 -0
  78. package/dist/chunk-OAXNDZJ7.js +323 -0
  79. package/dist/chunk-ODEEOXPH.js +44 -0
  80. package/dist/chunk-OQGFCZJ4.js +4533 -0
  81. package/dist/chunk-ORTMY4Q4.js +282 -0
  82. package/dist/chunk-OS32RNR2.js +442 -0
  83. package/dist/chunk-PAK6IDME.js +189 -0
  84. package/dist/chunk-PWFHBTSF.js +406 -0
  85. package/dist/chunk-Q5U6FMDI.js +2352 -0
  86. package/dist/chunk-QOZXJ4NA.js +3364 -0
  87. package/dist/chunk-QYF5S6P6.js +45 -0
  88. package/dist/chunk-RIISMHKN.js +36 -0
  89. package/dist/chunk-RPD4ZSB7.js +25 -0
  90. package/dist/chunk-RPD5K5NC.js +79 -0
  91. package/dist/chunk-RUOG5D2C.js +262 -0
  92. package/dist/chunk-T4ERT73Y.js +599 -0
  93. package/dist/chunk-T6D4Q4AQ.js +54 -0
  94. package/dist/chunk-TGPXLY2J.js +391 -0
  95. package/dist/chunk-TLGFBM3F.js +12116 -0
  96. package/dist/chunk-TO6WL3GM.js +88 -0
  97. package/dist/chunk-TT22N74J.js +517 -0
  98. package/dist/chunk-TVN5N6GY.js +21216 -0
  99. package/dist/chunk-U3VGR4VU.js +308 -0
  100. package/dist/chunk-UK3CMEAL.js +1250 -0
  101. package/dist/chunk-UOPVJQ4N.js +103 -0
  102. package/dist/chunk-UXVNL3D7.js +23 -0
  103. package/dist/chunk-UY752QSN.js +45 -0
  104. package/dist/chunk-V5PXFSZK.js +188 -0
  105. package/dist/chunk-V7R425XG.js +398 -0
  106. package/dist/chunk-VCSRSYLF.js +81 -0
  107. package/dist/chunk-VD4JQCQC.js +162 -0
  108. package/dist/chunk-VDBPVIKD.js +62 -0
  109. package/dist/chunk-VHQLPIRJ.js +114 -0
  110. package/dist/chunk-VN2AXLEX.js +5414 -0
  111. package/dist/chunk-VNMT7C64.js +478 -0
  112. package/dist/chunk-WONERJTP.js +309 -0
  113. package/dist/chunk-XECLWQZN.js +85 -0
  114. package/dist/chunk-XIMYZ3JA.js +27 -0
  115. package/dist/chunk-XK4CIILI.js +144 -0
  116. package/dist/chunk-Y4T27COV.js +562 -0
  117. package/dist/chunk-YGVYKNSN.js +1860 -0
  118. package/dist/chunk-YLF3PPT5.js +308 -0
  119. package/dist/chunk-YSNFMJKN.js +14 -0
  120. package/dist/chunk-Z3CCVDUB.js +76 -0
  121. package/dist/chunk-Z54ZSOBZ.js +61 -0
  122. package/dist/chunk-ZAWW3AF6.js +97 -0
  123. package/dist/chunk-ZMOL6RQC.js +167 -0
  124. package/dist/index.js +19039 -8956
  125. package/dist/mcp/analyze-cli.js +186 -228
  126. package/dist/mcp/cli.js +137 -98
  127. package/dist/mcp/server.js +22592 -1564
  128. package/dist/mcp/worker.js +97 -38
  129. package/dist/probes/installer.js +135 -0
  130. package/dist/workers/project-snapshot-persist-worker.js +22 -0
  131. package/dist/workers/review-graph-persist-worker.js +15 -0
  132. package/docs/adr/0001-stale-advisory-live-arm.md +29 -0
  133. package/docs/adr/0002-workspace-hash-rendezvous.md +30 -0
  134. package/docs/adr/0003-git-guard-latch-writer.md +203 -0
  135. package/docs/adr/0004-disposition-policy-seam.md +38 -0
  136. package/docs/adr/0005-tool-availability-enforcement-seam.md +29 -0
  137. package/docs/adr/0006-derived-state-benchmark-first.md +31 -0
  138. package/docs/adr/0007-end-to-end-witness-per-seam-slice.md +38 -0
  139. package/docs/adr/0008-turn-end-lane-interface.md +165 -0
  140. package/docs/adr/0009-reported-path-attribution.md +114 -0
  141. package/docs/adr/README.md +26 -0
  142. package/docs/agent-guide.md +13 -4
  143. package/docs/agent-tools.md +60 -1
  144. package/docs/ast-grep_rules_catalog.md +6 -4
  145. package/docs/configuration.md +75 -2
  146. package/docs/engineering-principles.md +202 -0
  147. package/docs/environment-variables.md +113 -6
  148. package/docs/features.md +10 -6
  149. package/docs/globalconfig.md +7 -1
  150. package/docs/io-bridge-v2-migration.md +94 -0
  151. package/docs/language-coverage.md +17 -0
  152. package/docs/lsp-capability-matrix.md +131 -32
  153. package/docs/lsp-idle-eviction.md +124 -0
  154. package/docs/mcp.md +21 -5
  155. package/docs/merge-queue-rollout.md +77 -0
  156. package/docs/pi-lens-fixer.md +161 -39
  157. package/docs/pi-lens-investigator.md +77 -20
  158. package/docs/pi-lens-merge-policy.md +694 -0
  159. package/docs/pi-lens-monitor.md +73 -7
  160. package/docs/pi-lens-retro.md +6 -4
  161. package/docs/pi-lens-reviewer.md +190 -34
  162. package/docs/pi-lens-subagent.md +247 -37
  163. package/docs/pi-lens-warden.md +18 -7
  164. package/docs/public-api-stability.md +56 -0
  165. package/docs/release-qa-baseline.md +86 -17
  166. package/docs/rfcs/3654-unified-io-bridge-v2.md +316 -0
  167. package/docs/servercapabilities.md +66 -52
  168. package/docs/settings.md +13 -3
  169. package/docs/subagent-compat.md +1 -1
  170. package/docs/usage.md +5 -1
  171. package/grammars/tree-sitter-bash.wasm +0 -0
  172. package/grammars/tree-sitter-bash.wasm.json +3 -3
  173. package/package.json +23 -9
  174. package/rules/ast-grep-rules/rule-tests/advisory-registry-subset-test.yml +41 -0
  175. package/rules/ast-grep-rules/rule-tests/no-assert-tuple-test.yml +13 -0
  176. package/rules/ast-grep-rules/rule-tests/no-boolean-in-except-test.yml +26 -0
  177. package/rules/ast-grep-rules/rule-tests/no-http-headers-bracket-access-test.yml +10 -0
  178. package/rules/ast-grep-rules/rule-tests/unchecked-numeric-parse-python-test.yml +18 -0
  179. package/rules/ast-grep-rules/rule-tests/unchecked-throwing-call-python-test.yml +4 -3
  180. package/rules/ast-grep-rules/rules/advisory-registry-subset.yml +50 -0
  181. package/rules/ast-grep-rules/rules/go-no-fmt-println.yml +2 -2
  182. package/rules/ast-grep-rules/rules/no-assert-tuple.yml +23 -13
  183. package/rules/ast-grep-rules/rules/no-boolean-in-except.yml +7 -3
  184. package/rules/ast-grep-rules/rules/no-console-except-error-js.yml +2 -2
  185. package/rules/ast-grep-rules/rules/no-console-except-error.yml +2 -2
  186. package/rules/ast-grep-rules/rules/no-http-headers-bracket-access.yml +12 -7
  187. package/rules/ast-grep-rules/rules/unchecked-numeric-parse-python.yml +44 -0
  188. package/rules/ast-grep-rules/rules/unchecked-throwing-call-python.yml +5 -3
  189. package/rules/tree-sitter-queries/typescript/console-statement.yml +2 -2
  190. package/scripts/analyze-pi-lens-logs.mjs +1275 -62
  191. package/scripts/download-grammars.js +5 -0
  192. package/scripts/grammars.lock.json +6 -1
  193. package/scripts/install-selftest.mjs +38 -35
  194. package/scripts/lib/host-provided-deps.mjs +13 -4
  195. package/scripts/lib/web-tree-sitter-dir.mjs +141 -0
  196. package/dist/clients/actionable-warnings-logger.js +0 -35
  197. package/dist/clients/actionable-warnings.js +0 -1594
  198. package/dist/clients/advisory-provenance.js +0 -457
  199. package/dist/clients/agent-behavior-client.js +0 -147
  200. package/dist/clients/agent-nudge.js +0 -325
  201. package/dist/clients/analysed-root.js +0 -1
  202. package/dist/clients/ast-grep-client.js +0 -731
  203. package/dist/clients/ast-grep-rule-manager.js +0 -146
  204. package/dist/clients/ast-grep-tool-logger.js +0 -118
  205. package/dist/clients/ast-grep-types.js +0 -10
  206. package/dist/clients/ast-grep-yaml-synth.js +0 -154
  207. package/dist/clients/atomic-write-staging.js +0 -75
  208. package/dist/clients/atomic-write.js +0 -189
  209. package/dist/clients/availability-probe-flight.js +0 -12
  210. package/dist/clients/bash-file-access.js +0 -1056
  211. package/dist/clients/biome-client.js +0 -357
  212. package/dist/clients/blocker-freshness.js +0 -837
  213. package/dist/clients/blocker-past-eof.js +0 -129
  214. package/dist/clients/bootstrap.js +0 -569
  215. package/dist/clients/bounded-cache.js +0 -190
  216. package/dist/clients/bounded-pid-file-lock.js +0 -202
  217. package/dist/clients/bounded-telemetry.js +0 -295
  218. package/dist/clients/build-identity.js +0 -95
  219. package/dist/clients/bundled-resource-health.js +0 -113
  220. package/dist/clients/bus-events-logger.js +0 -105
  221. package/dist/clients/bus-publish.js +0 -171
  222. package/dist/clients/cache/rule-cache.js +0 -190
  223. package/dist/clients/cache-manager.js +0 -465
  224. package/dist/clients/cache-observability.js +0 -1313
  225. package/dist/clients/call-graph.js +0 -852
  226. package/dist/clients/cargo-manifest.js +0 -422
  227. package/dist/clients/cascade-budget.js +0 -196
  228. package/dist/clients/cascade-format.js +0 -315
  229. package/dist/clients/cascade-logger.js +0 -31
  230. package/dist/clients/cascade-types.js +0 -9
  231. package/dist/clients/child-unref.js +0 -115
  232. package/dist/clients/code-quality-warnings.js +0 -286
  233. package/dist/clients/codebase-model.js +0 -173
  234. package/dist/clients/collateral-test-role.js +0 -40
  235. package/dist/clients/complexity-client.js +0 -462
  236. package/dist/clients/config-core/deny.js +0 -221
  237. package/dist/clients/config-core/index.js +0 -50
  238. package/dist/clients/config-core/merge.js +0 -357
  239. package/dist/clients/config-core/normalize.js +0 -340
  240. package/dist/clients/config-core/process-spec.js +0 -248
  241. package/dist/clients/config-core/provenance.js +0 -164
  242. package/dist/clients/config-core/records.js +0 -218
  243. package/dist/clients/config-core/resolve.js +0 -125
  244. package/dist/clients/config-core/safe-object.js +0 -78
  245. package/dist/clients/config-core/schema.js +0 -165
  246. package/dist/clients/config-diagnostic-codes.js +0 -283
  247. package/dist/clients/config-locations.js +0 -160
  248. package/dist/clients/config-resolve.js +0 -792
  249. package/dist/clients/config-schema.js +0 -251
  250. package/dist/clients/config-warn.js +0 -407
  251. package/dist/clients/console-guard-install.js +0 -26
  252. package/dist/clients/cooperative-budget.js +0 -42
  253. package/dist/clients/dead-code-client.js +0 -510
  254. package/dist/clients/dead-code-logger.js +0 -30
  255. package/dist/clients/deadline-utils.js +0 -280
  256. package/dist/clients/debug-handles.js +0 -211
  257. package/dist/clients/debug-heap.js +0 -174
  258. package/dist/clients/deferred-lsp-work.js +0 -106
  259. package/dist/clients/degradation-ledger.js +0 -396
  260. package/dist/clients/demoted-finding-render.js +0 -169
  261. package/dist/clients/dependency-checker.js +0 -862
  262. package/dist/clients/deps/ast-grep-napi.js +0 -22
  263. package/dist/clients/deps/js-yaml.js +0 -9
  264. package/dist/clients/deps/minimatch.js +0 -4
  265. package/dist/clients/deps/pi-tui.js +0 -14
  266. package/dist/clients/deps/typebox.js +0 -14
  267. package/dist/clients/deps/vscode-jsonrpc.js +0 -1
  268. package/dist/clients/deps/web-tree-sitter.js +0 -24
  269. package/dist/clients/diagnostic-dispositions.js +0 -594
  270. package/dist/clients/diagnostic-line-freshness.js +0 -305
  271. package/dist/clients/diagnostic-logger.js +0 -73
  272. package/dist/clients/diagnostic-tracker.js +0 -105
  273. package/dist/clients/diagnostics-publish.js +0 -230
  274. package/dist/clients/dispatch/ast-grep-catalog.js +0 -65
  275. package/dist/clients/dispatch/auxiliary-lsp.js +0 -343
  276. package/dist/clients/dispatch/collect-later-tier.js +0 -35
  277. package/dist/clients/dispatch/diagnostic-taxonomy.js +0 -66
  278. package/dist/clients/dispatch/dispatcher.js +0 -1269
  279. package/dist/clients/dispatch/fact-provider-types.js +0 -1
  280. package/dist/clients/dispatch/fact-rule-runner.js +0 -17
  281. package/dist/clients/dispatch/fact-runner.js +0 -30
  282. package/dist/clients/dispatch/fact-scheduler.js +0 -68
  283. package/dist/clients/dispatch/fact-store.js +0 -377
  284. package/dist/clients/dispatch/facts/comment-facts.js +0 -22
  285. package/dist/clients/dispatch/facts/file-content.js +0 -19
  286. package/dist/clients/dispatch/facts/function-facts.js +0 -348
  287. package/dist/clients/dispatch/facts/import-facts.js +0 -204
  288. package/dist/clients/dispatch/facts/tree-sitter-facts.js +0 -34
  289. package/dist/clients/dispatch/facts/try-catch-facts.js +0 -119
  290. package/dist/clients/dispatch/finding-policy.js +0 -222
  291. package/dist/clients/dispatch/indent-detect.js +0 -411
  292. package/dist/clients/dispatch/inline-suppressions.js +0 -70
  293. package/dist/clients/dispatch/integration.js +0 -2377
  294. package/dist/clients/dispatch/lazy.js +0 -11
  295. package/dist/clients/dispatch/pending-runner-findings.js +0 -87
  296. package/dist/clients/dispatch/plan.js +0 -278
  297. package/dist/clients/dispatch/priorities.js +0 -20
  298. package/dist/clients/dispatch/rule-id-normalize.js +0 -50
  299. package/dist/clients/dispatch/rule-ignores.js +0 -62
  300. package/dist/clients/dispatch/rule-policy.js +0 -135
  301. package/dist/clients/dispatch/rules/async-noise.js +0 -40
  302. package/dist/clients/dispatch/rules/async-unnecessary-wrapper.js +0 -27
  303. package/dist/clients/dispatch/rules/cors-wildcard.js +0 -54
  304. package/dist/clients/dispatch/rules/error-obscuring.js +0 -32
  305. package/dist/clients/dispatch/rules/error-swallowing.js +0 -31
  306. package/dist/clients/dispatch/rules/framework-call-noise.js +0 -67
  307. package/dist/clients/dispatch/rules/high-complexity.js +0 -72
  308. package/dist/clients/dispatch/rules/high-fan-out.js +0 -74
  309. package/dist/clients/dispatch/rules/high-import-coupling.js +0 -37
  310. package/dist/clients/dispatch/rules/missing-error-propagation.js +0 -62
  311. package/dist/clients/dispatch/rules/no-commented-credentials.js +0 -52
  312. package/dist/clients/dispatch/rules/pass-through-wrappers.js +0 -42
  313. package/dist/clients/dispatch/rules/placeholder-comments.js +0 -40
  314. package/dist/clients/dispatch/rules/unsafe-boundary.js +0 -126
  315. package/dist/clients/dispatch/runner-context.js +0 -52
  316. package/dist/clients/dispatch/runners/actionlint.js +0 -113
  317. package/dist/clients/dispatch/runners/ast-grep-napi.js +0 -1196
  318. package/dist/clients/dispatch/runners/biome-check.js +0 -283
  319. package/dist/clients/dispatch/runners/cpp-check.js +0 -236
  320. package/dist/clients/dispatch/runners/credo.js +0 -80
  321. package/dist/clients/dispatch/runners/cue-vet.js +0 -398
  322. package/dist/clients/dispatch/runners/dart-analyze.js +0 -202
  323. package/dist/clients/dispatch/runners/detekt.js +0 -169
  324. package/dist/clients/dispatch/runners/dotnet-build.js +0 -159
  325. package/dist/clients/dispatch/runners/elixir-check.js +0 -210
  326. package/dist/clients/dispatch/runners/eslint.js +0 -154
  327. package/dist/clients/dispatch/runners/fact-rules.js +0 -29
  328. package/dist/clients/dispatch/runners/fish-indent.js +0 -69
  329. package/dist/clients/dispatch/runners/gleam-check.js +0 -87
  330. package/dist/clients/dispatch/runners/go-vet.js +0 -90
  331. package/dist/clients/dispatch/runners/golangci-lint.js +0 -120
  332. package/dist/clients/dispatch/runners/hadolint.js +0 -79
  333. package/dist/clients/dispatch/runners/helm-lint.js +0 -171
  334. package/dist/clients/dispatch/runners/helm-render.js +0 -940
  335. package/dist/clients/dispatch/runners/htmlhint.js +0 -108
  336. package/dist/clients/dispatch/runners/index.js +0 -108
  337. package/dist/clients/dispatch/runners/javac.js +0 -89
  338. package/dist/clients/dispatch/runners/ktlint.js +0 -136
  339. package/dist/clients/dispatch/runners/lsp.js +0 -378
  340. package/dist/clients/dispatch/runners/markdownlint.js +0 -160
  341. package/dist/clients/dispatch/runners/mypy.js +0 -101
  342. package/dist/clients/dispatch/runners/oxlint.js +0 -398
  343. package/dist/clients/dispatch/runners/php-lint.js +0 -62
  344. package/dist/clients/dispatch/runners/phpstan.js +0 -120
  345. package/dist/clients/dispatch/runners/prisma-validate.js +0 -62
  346. package/dist/clients/dispatch/runners/psscriptanalyzer.js +0 -445
  347. package/dist/clients/dispatch/runners/pyright.js +0 -169
  348. package/dist/clients/dispatch/runners/rubocop.js +0 -90
  349. package/dist/clients/dispatch/runners/ruff.js +0 -89
  350. package/dist/clients/dispatch/runners/rust-clippy.js +0 -251
  351. package/dist/clients/dispatch/runners/shellcheck.js +0 -169
  352. package/dist/clients/dispatch/runners/shfmt.js +0 -102
  353. package/dist/clients/dispatch/runners/spellcheck.js +0 -121
  354. package/dist/clients/dispatch/runners/spotbugs.js +0 -259
  355. package/dist/clients/dispatch/runners/sqlfluff.js +0 -174
  356. package/dist/clients/dispatch/runners/stylelint.js +0 -158
  357. package/dist/clients/dispatch/runners/swiftlint.js +0 -154
  358. package/dist/clients/dispatch/runners/taplo.js +0 -168
  359. package/dist/clients/dispatch/runners/terragrunt.js +0 -168
  360. package/dist/clients/dispatch/runners/tflint.js +0 -110
  361. package/dist/clients/dispatch/runners/tree-sitter.js +0 -620
  362. package/dist/clients/dispatch/runners/trivy-config.js +0 -247
  363. package/dist/clients/dispatch/runners/utils/availability-policy.js +0 -496
  364. package/dist/clients/dispatch/runners/utils/candidate-probe.js +0 -90
  365. package/dist/clients/dispatch/runners/utils/diagnostic-parsers.js +0 -85
  366. package/dist/clients/dispatch/runners/utils/lazy-installer.js +0 -274
  367. package/dist/clients/dispatch/runners/utils/runner-helpers.js +0 -1701
  368. package/dist/clients/dispatch/runners/utils/spawn-outcome.js +0 -101
  369. package/dist/clients/dispatch/runners/utils/tool-failure.js +0 -235
  370. package/dist/clients/dispatch/runners/utils/toolchain-availability.js +0 -169
  371. package/dist/clients/dispatch/runners/utils.js +0 -15
  372. package/dist/clients/dispatch/runners/vale.js +0 -116
  373. package/dist/clients/dispatch/runners/yaml-rule-parser.js +0 -242
  374. package/dist/clients/dispatch/runners/yamllint.js +0 -85
  375. package/dist/clients/dispatch/runners/zig-check.js +0 -91
  376. package/dist/clients/dispatch/suppress-writer.js +0 -69
  377. package/dist/clients/dispatch/tool-profile.js +0 -30
  378. package/dist/clients/dispatch/types.js +0 -21
  379. package/dist/clients/dispatch/utils/format-utils.js +0 -45
  380. package/dist/clients/dispatch/utils/lsp-diagnostics.js +0 -35
  381. package/dist/clients/disposition-logger.js +0 -32
  382. package/dist/clients/disposition-publish.js +0 -124
  383. package/dist/clients/durable-store.js +0 -97
  384. package/dist/clients/effective-config.js +0 -413
  385. package/dist/clients/env-utils.js +0 -83
  386. package/dist/clients/error-class.js +0 -23
  387. package/dist/clients/eval-timestamp.js +0 -17
  388. package/dist/clients/event-loop-hold.js +0 -274
  389. package/dist/clients/event-loop-monitor.js +0 -250
  390. package/dist/clients/extension-log.js +0 -504
  391. package/dist/clients/extension-mode.js +0 -73
  392. package/dist/clients/feature-hints.js +0 -103
  393. package/dist/clients/file-kinds.js +0 -412
  394. package/dist/clients/file-role.js +0 -134
  395. package/dist/clients/file-time.js +0 -160
  396. package/dist/clients/file-utils.js +0 -1032
  397. package/dist/clients/finding-delivery-gate.js +0 -463
  398. package/dist/clients/finding-identity.js +0 -88
  399. package/dist/clients/fix-worklog.js +0 -103
  400. package/dist/clients/format-events-publish.js +0 -343
  401. package/dist/clients/format-service.js +0 -222
  402. package/dist/clients/formatters-lazy.js +0 -9
  403. package/dist/clients/formatters.js +0 -1994
  404. package/dist/clients/freshness-cadence.js +0 -17
  405. package/dist/clients/freshness.js +0 -38
  406. package/dist/clients/generated-artifacts.js +0 -394
  407. package/dist/clients/generation-guard.js +0 -215
  408. package/dist/clients/git-guard.js +0 -923
  409. package/dist/clients/git-tracked-ignore.js +0 -243
  410. package/dist/clients/gitleaks-client.js +0 -509
  411. package/dist/clients/go-client.js +0 -104
  412. package/dist/clients/govulncheck-client.js +0 -605
  413. package/dist/clients/gradle-ktfmt-style.js +0 -252
  414. package/dist/clients/grammar-source.js +0 -465
  415. package/dist/clients/gzip-stage-write.js +0 -135
  416. package/dist/clients/hashline-anchor.js +0 -424
  417. package/dist/clients/hook-budgets.js +0 -76
  418. package/dist/clients/host-edit-normalize.js +0 -140
  419. package/dist/clients/host-ports.js +0 -39
  420. package/dist/clients/indent-retarget.js +0 -154
  421. package/dist/clients/install-diagnostics.js +0 -143
  422. package/dist/clients/installer/index.js +0 -5167
  423. package/dist/clients/installer/managed-tool-refresh-session.js +0 -58
  424. package/dist/clients/installer/managed-tool-refresh.js +0 -783
  425. package/dist/clients/instance-reaper-state.js +0 -7
  426. package/dist/clients/instance-reaper.js +0 -1137
  427. package/dist/clients/instance-registry-lock.js +0 -145
  428. package/dist/clients/instance-registry.js +0 -773
  429. package/dist/clients/jscpd-client.js +0 -370
  430. package/dist/clients/json-cache-read.js +0 -65
  431. package/dist/clients/knip-client.js +0 -788
  432. package/dist/clients/language-policy.js +0 -252
  433. package/dist/clients/language-profile.js +0 -361
  434. package/dist/clients/language-registry.js +0 -603
  435. package/dist/clients/latency-logger.js +0 -719
  436. package/dist/clients/lazy-import.js +0 -21
  437. package/dist/clients/ledger-bounds.js +0 -54
  438. package/dist/clients/lens-config.js +0 -346
  439. package/dist/clients/lens-engine.js +0 -358
  440. package/dist/clients/lens-events.js +0 -125
  441. package/dist/clients/lens-flag-registry.js +0 -467
  442. package/dist/clients/lens-map.js +0 -1156
  443. package/dist/clients/live-bus-emitter.js +0 -74
  444. package/dist/clients/log-cleanup.js +0 -222
  445. package/dist/clients/lsp/aggregation.js +0 -178
  446. package/dist/clients/lsp/cascade-tier.js +0 -421
  447. package/dist/clients/lsp/client.js +0 -4465
  448. package/dist/clients/lsp/config.js +0 -689
  449. package/dist/clients/lsp/diagnostic-binding.js +0 -225
  450. package/dist/clients/lsp/document-drift.js +0 -467
  451. package/dist/clients/lsp/edits.js +0 -1219
  452. package/dist/clients/lsp/index.js +0 -8305
  453. package/dist/clients/lsp/inferred-project.js +0 -216
  454. package/dist/clients/lsp/jvm-runtime.js +0 -298
  455. package/dist/clients/lsp/language.js +0 -63
  456. package/dist/clients/lsp/launch.js +0 -725
  457. package/dist/clients/lsp/lombok.js +0 -158
  458. package/dist/clients/lsp/path-utils.js +0 -5
  459. package/dist/clients/lsp/pending-aux-coverage.js +0 -251
  460. package/dist/clients/lsp/position-encoding.js +0 -61
  461. package/dist/clients/lsp/ruby-drive-dirs.js +0 -83
  462. package/dist/clients/lsp/server.js +0 -3209
  463. package/dist/clients/lsp/session-roots.js +0 -192
  464. package/dist/clients/lsp/spawn-history.js +0 -17
  465. package/dist/clients/lsp/sync-kind.js +0 -42
  466. package/dist/clients/lsp/tsserver-sync.js +0 -332
  467. package/dist/clients/lsp/wait-policy/capability-snapshot.js +0 -1
  468. package/dist/clients/lsp/wait-policy/classification.js +0 -85
  469. package/dist/clients/lsp/wait-policy/index.js +0 -10
  470. package/dist/clients/lsp/wait-policy/strategies.js +0 -303
  471. package/dist/clients/lsp/watch-queue.js +0 -61
  472. package/dist/clients/lsp/workspace-diagnostics-cache.js +0 -639
  473. package/dist/clients/lsp/workspace-diagnostics-session.js +0 -30
  474. package/dist/clients/lsp/workspace-sweep-hold.js +0 -184
  475. package/dist/clients/lsp-budget.js +0 -186
  476. package/dist/clients/lsp-document-symbols.js +0 -110
  477. package/dist/clients/lsp-lazy.js +0 -9
  478. package/dist/clients/lsp-mutation.js +0 -396
  479. package/dist/clients/lsp-status.js +0 -59
  480. package/dist/clients/map-with-concurrency.js +0 -40
  481. package/dist/clients/mcp/analyze.js +0 -420
  482. package/dist/clients/mcp/host-shim.js +0 -31
  483. package/dist/clients/mcp/ipc.js +0 -335
  484. package/dist/clients/mcp/review.js +0 -151
  485. package/dist/clients/mcp/session.js +0 -412
  486. package/dist/clients/memory-sampler.js +0 -208
  487. package/dist/clients/message-end-attribution.js +0 -30
  488. package/dist/clients/metrics-client.js +0 -107
  489. package/dist/clients/metrics-history.js +0 -327
  490. package/dist/clients/middle-man-analysis.js +0 -263
  491. package/dist/clients/model-provider.js +0 -53
  492. package/dist/clients/module-report-lsp.js +0 -189
  493. package/dist/clients/module-report.js +0 -2150
  494. package/dist/clients/mutating-tool.js +0 -651
  495. package/dist/clients/mutation-attribution.js +0 -368
  496. package/dist/clients/mutation-bridge.js +0 -240
  497. package/dist/clients/ndjson-logger.js +0 -734
  498. package/dist/clients/observed-mutation-sources.js +0 -101
  499. package/dist/clients/observed-mutation.js +0 -1253
  500. package/dist/clients/oldtext-autopatch.js +0 -128
  501. package/dist/clients/opaque-mutation-scan.js +0 -496
  502. package/dist/clients/opengrep-client.js +0 -328
  503. package/dist/clients/opengrep-config.js +0 -76
  504. package/dist/clients/package-manager.js +0 -607
  505. package/dist/clients/package-root.js +0 -38
  506. package/dist/clients/partial-edit-apply.js +0 -439
  507. package/dist/clients/path-attribution-telemetry.js +0 -43
  508. package/dist/clients/path-keyed-map.js +0 -108
  509. package/dist/clients/path-utils.js +0 -1244
  510. package/dist/clients/performance-report.js +0 -331
  511. package/dist/clients/persist-debounce.js +0 -70
  512. package/dist/clients/persistent-reverify.js +0 -271
  513. package/dist/clients/php-cs-fixer-config.js +0 -119
  514. package/dist/clients/pipeline.js +0 -1425
  515. package/dist/clients/post-autofix-notice.js +0 -37
  516. package/dist/clients/print-mode.js +0 -21
  517. package/dist/clients/probe-home-state.js +0 -228
  518. package/dist/clients/process-bridge.js +0 -66
  519. package/dist/clients/process-singletons.js +0 -210
  520. package/dist/clients/process-snapshot.js +0 -68
  521. package/dist/clients/project-changes.js +0 -181
  522. package/dist/clients/project-conventions.js +0 -171
  523. package/dist/clients/project-diagnostics/cache.js +0 -137
  524. package/dist/clients/project-diagnostics/extractors.js +0 -109
  525. package/dist/clients/project-diagnostics/fresh-fetch.js +0 -650
  526. package/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +0 -118
  527. package/dist/clients/project-diagnostics/runner-adapters/dead-code.js +0 -47
  528. package/dist/clients/project-diagnostics/runner-adapters/gitleaks.js +0 -40
  529. package/dist/clients/project-diagnostics/runner-adapters/govulncheck.js +0 -34
  530. package/dist/clients/project-diagnostics/runner-adapters/jscpd.js +0 -38
  531. package/dist/clients/project-diagnostics/runner-adapters/knip.js +0 -47
  532. package/dist/clients/project-diagnostics/runner-adapters/madge.js +0 -48
  533. package/dist/clients/project-diagnostics/runner-adapters/opengrep.js +0 -40
  534. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +0 -127
  535. package/dist/clients/project-diagnostics/runner-adapters/trivy.js +0 -81
  536. package/dist/clients/project-diagnostics/scanner.js +0 -520
  537. package/dist/clients/project-diagnostics/types.js +0 -1
  538. package/dist/clients/project-lens-config.js +0 -799
  539. package/dist/clients/project-report.js +0 -701
  540. package/dist/clients/project-scale.js +0 -237
  541. package/dist/clients/project-scan-policy.js +0 -11
  542. package/dist/clients/project-snapshot-fingerprint.js +0 -48
  543. package/dist/clients/project-snapshot-persist-worker.js +0 -20
  544. package/dist/clients/project-snapshot.js +0 -1653
  545. package/dist/clients/project-trust.js +0 -181
  546. package/dist/clients/python-environment.js +0 -217
  547. package/dist/clients/python-provenance.js +0 -639
  548. package/dist/clients/quiet-window-config.js +0 -47
  549. package/dist/clients/quiet-window.js +0 -236
  550. package/dist/clients/read-bridge.js +0 -139
  551. package/dist/clients/read-expansion.js +0 -266
  552. package/dist/clients/read-guard-logger.js +0 -251
  553. package/dist/clients/read-guard-tool-lines.js +0 -1306
  554. package/dist/clients/read-guard.js +0 -1561
  555. package/dist/clients/recent-touches.js +0 -240
  556. package/dist/clients/redact/secrets.js +0 -449
  557. package/dist/clients/resource-sampler.js +0 -628
  558. package/dist/clients/reverse-deps.js +0 -270
  559. package/dist/clients/review-graph/builder.js +0 -5118
  560. package/dist/clients/review-graph/format.js +0 -33
  561. package/dist/clients/review-graph/git-identity.js +0 -157
  562. package/dist/clients/review-graph/import-resolvers.js +0 -481
  563. package/dist/clients/review-graph/persist-worker.js +0 -10
  564. package/dist/clients/review-graph/query.js +0 -244
  565. package/dist/clients/review-graph/revision-drift.js +0 -21
  566. package/dist/clients/review-graph/service.js +0 -96
  567. package/dist/clients/review-graph/shared-extraction-ir.js +0 -82
  568. package/dist/clients/review-graph/symbol-id.js +0 -103
  569. package/dist/clients/review-graph/tsconfig-paths.js +0 -299
  570. package/dist/clients/review-graph/types.js +0 -1
  571. package/dist/clients/review-graph/workspace-modules.js +0 -449
  572. package/dist/clients/review-graph-logger.js +0 -81
  573. package/dist/clients/ruff-client.js +0 -152
  574. package/dist/clients/rules-scanner.js +0 -131
  575. package/dist/clients/run-duration.js +0 -55
  576. package/dist/clients/runtime-agent-end.js +0 -746
  577. package/dist/clients/runtime-config.js +0 -77
  578. package/dist/clients/runtime-context.js +0 -211
  579. package/dist/clients/runtime-coordinator.js +0 -1290
  580. package/dist/clients/runtime-session.js +0 -2485
  581. package/dist/clients/runtime-tool-call.js +0 -1284
  582. package/dist/clients/runtime-tool-result.js +0 -2034
  583. package/dist/clients/runtime-turn.js +0 -3600
  584. package/dist/clients/rust-client.js +0 -97
  585. package/dist/clients/safe-spawn.js +0 -2166
  586. package/dist/clients/sanitize.js +0 -286
  587. package/dist/clients/scan-utils.js +0 -25
  588. package/dist/clients/scratch-tree-policy.js +0 -165
  589. package/dist/clients/search-read-registration.js +0 -94
  590. package/dist/clients/secret-findings.js +0 -114
  591. package/dist/clients/security-scan-client.js +0 -352
  592. package/dist/clients/session-event-guard.js +0 -297
  593. package/dist/clients/session-lifecycle.js +0 -484
  594. package/dist/clients/session-start-observability.js +0 -94
  595. package/dist/clients/session-state-store.js +0 -101
  596. package/dist/clients/session-summary.js +0 -15
  597. package/dist/clients/sessionstart-logger.js +0 -27
  598. package/dist/clients/sg-runner.js +0 -876
  599. package/dist/clients/sgconfig.js +0 -347
  600. package/dist/clients/shared-checkout-guard.js +0 -338
  601. package/dist/clients/single-flight.js +0 -158
  602. package/dist/clients/situational-tool-telemetry.js +0 -108
  603. package/dist/clients/skills-resolver.js +0 -141
  604. package/dist/clients/slow-fs.js +0 -138
  605. package/dist/clients/smells-rollup.js +0 -231
  606. package/dist/clients/source-filter.js +0 -596
  607. package/dist/clients/source-walker.js +0 -211
  608. package/dist/clients/spawn-output-cap.js +0 -37
  609. package/dist/clients/spawn-timeout-cooldown.js +0 -110
  610. package/dist/clients/stale-marker.js +0 -17
  611. package/dist/clients/startup-scan.js +0 -400
  612. package/dist/clients/startup-timing.js +0 -130
  613. package/dist/clients/string-utils.js +0 -33
  614. package/dist/clients/subagent-mode.js +0 -111
  615. package/dist/clients/symbol-containment.js +0 -24
  616. package/dist/clients/symbol-types.js +0 -5
  617. package/dist/clients/test-runner-client.js +0 -2507
  618. package/dist/clients/test-runner-delivery.js +0 -287
  619. package/dist/clients/todo-scanner.js +0 -229
  620. package/dist/clients/tool-agreement.js +0 -423
  621. package/dist/clients/tool-config.js +0 -249
  622. package/dist/clients/tool-cwd.js +0 -270
  623. package/dist/clients/tool-definition.js +0 -47
  624. package/dist/clients/tool-event.js +0 -105
  625. package/dist/clients/tool-policy.js +0 -2755
  626. package/dist/clients/tool-probe.js +0 -53
  627. package/dist/clients/tool-render.js +0 -156
  628. package/dist/clients/tool-set-policy.js +0 -118
  629. package/dist/clients/tree-sitter-cache.js +0 -364
  630. package/dist/clients/tree-sitter-client.js +0 -4134
  631. package/dist/clients/tree-sitter-logger.js +0 -100
  632. package/dist/clients/tree-sitter-navigator.js +0 -269
  633. package/dist/clients/tree-sitter-query-loader.js +0 -569
  634. package/dist/clients/tree-sitter-shared.js +0 -158
  635. package/dist/clients/tree-sitter-symbol-extractor.js +0 -1265
  636. package/dist/clients/trivy-client.js +0 -467
  637. package/dist/clients/tui-fit.js +0 -50
  638. package/dist/clients/turn-context.js +0 -52
  639. package/dist/clients/turn-summary-render.js +0 -72
  640. package/dist/clients/turn-summary.js +0 -132
  641. package/dist/clients/typos-config.js +0 -29
  642. package/dist/clients/user-notify.js +0 -51
  643. package/dist/clients/vanished-instance-marker.js +0 -57
  644. package/dist/clients/warm-attach.js +0 -246
  645. package/dist/clients/widget-state.js +0 -1677
  646. package/dist/clients/word-index-logger.js +0 -49
  647. package/dist/clients/word-index-store.js +0 -459
  648. package/dist/clients/word-index.js +0 -2080
  649. package/dist/clients/workspace-topology.js +0 -389
  650. package/dist/clients/write-ordering-guard.js +0 -65
  651. package/dist/clients/zizmor-config.js +0 -327
  652. package/dist/i18n.js +0 -69
  653. package/dist/mcp/build-staleness.js +0 -124
  654. package/dist/scripts/lib/process-scan.mjs +0 -583
  655. package/dist/scripts/lib/skills-predicate.mjs +0 -129
  656. package/dist/tools/activate-tools.js +0 -87
  657. package/dist/tools/ast-grep-outline.js +0 -137
  658. package/dist/tools/ast-grep-replace.js +0 -244
  659. package/dist/tools/ast-grep-search.js +0 -762
  660. package/dist/tools/effective-config.js +0 -90
  661. package/dist/tools/lens-diagnostic-mark.js +0 -375
  662. package/dist/tools/lens-diagnostics.js +0 -2544
  663. package/dist/tools/lsp-diagnostics.js +0 -1634
  664. package/dist/tools/lsp-navigation.js +0 -1367
  665. package/dist/tools/lsp-structured-output.js +0 -294
  666. package/dist/tools/module-report.js +0 -382
  667. package/dist/tools/project-report.js +0 -86
  668. package/dist/tools/render-compact.js +0 -374
  669. package/dist/tools/scan-progress.js +0 -53
  670. package/dist/tools/shared.js +0 -29
  671. package/dist/tools/symbol-search.js +0 -155
@@ -1,1290 +0,0 @@
1
- import { randomBytes } from "node:crypto";
2
- import * as fs from "node:fs";
3
- import * as path from "node:path";
4
- import { logCascade } from "./cascade-logger.js";
5
- import { appendProjectChange, } from "./project-changes.js";
6
- import { normalizeMapKey, pathsEqual } from "./path-utils.js";
7
- import { PathKeyedMap } from "./path-keyed-map.js";
8
- import { BoundedLruCache } from "./bounded-cache.js";
9
- import { PartialApplyRecordStore } from "./partial-edit-apply.js";
10
- import { ReadGuard } from "./read-guard.js";
11
- import { RUNTIME_CONFIG } from "./runtime-config.js";
12
- import { TurnSummaryCollector } from "./turn-summary.js";
13
- import { deriveProviderFromModelId } from "./model-provider.js";
14
- import { beginTurnContext, setTurnContextSession } from "./turn-context.js";
15
- import { recordDegradationOnce } from "./degradation-ledger.js";
16
- /** Keep deferred cascade admission bounded without dropping late findings. */
17
- export const MAX_PENDING_CASCADE_RUNS = 32;
18
- /**
19
- * Bounded receipt ring capacity (defect shape 9: bound the axis that grows —
20
- * per-mutation receipts are unbounded across a long session). Oldest receipts
21
- * evict first; eviction is counted and surfaced via
22
- * {@link RuntimeCoordinator.droppedMutationReceiptCount} so a consumer that
23
- * needs a complete window knows the answer was truncated, never silently
24
- * incomplete (#936 honesty rule).
25
- */
26
- const MAX_MUTATION_RECEIPTS = 512;
27
- /**
28
- * Bound on in-flight tool_call → tool_result correlations. A tool_result
29
- * follows its tool_call almost immediately, so this only needs to cover
30
- * calls genuinely in flight; sized generously above any realistic
31
- * in-flight-batch width so a slow paired result is never evicted before use.
32
- */
33
- const TOOL_CALL_ATTRIBUTION_CAPACITY = 256;
34
- /**
35
- * A recorded attribution older than this is treated as expired (as if it
36
- * were never recorded) rather than trusted — defense in depth against a host
37
- * that reuses a call id, or a pathologically delayed/duplicated tool_result,
38
- * outliving the LRU capacity bound. Generous relative to any real tool
39
- * round-trip; only guards against genuine identity reuse, not slow tools.
40
- */
41
- const TOOL_CALL_ATTRIBUTION_TTL_MS = 5 * 60_000;
42
- export class RuntimeCoordinator {
43
- _projectRoot = normalizeMapKey(process.cwd());
44
- _sessionGeneration = 0;
45
- _sessionStartedAt = Date.now();
46
- _errorDebtBaseline = null;
47
- _pipelineCrashCounts = new Map();
48
- _cachedExports = new Map();
49
- _startupScansInFlight = new Map();
50
- _cascadeRuns = [];
51
- _turnEndCascadeSettleStarts = new Map();
52
- _nextCascadeSettleToken = 0;
53
- // Cascade computes are kicked off unawaited by the pipeline (#450); their
54
- // promises park here until turn_end drains them via settleCascadeRuns. Each is
55
- // guaranteed non-rejecting by the pipeline's .catch.
56
- _pendingCascadeRuns = [];
57
- _cascadeSessionStats = {
58
- runs: 0,
59
- diagnosticsSurfaced: 0,
60
- coldSnapshotTouches: 0,
61
- };
62
- _complexityBaselines = new Map();
63
- _fixedThisTurn = new PathKeyedMap(normalizeMapKey);
64
- _writtenThisTurn = new PathKeyedMap(normalizeMapKey);
65
- _autofixDemotedThisTurn = new PathKeyedMap(normalizeMapKey);
66
- _reportedThisTurn = new Set();
67
- _mutationReceipts = [];
68
- _droppedMutationReceipts = 0;
69
- _projectRulesScan = {
70
- rules: [],
71
- hasCustomRules: false,
72
- };
73
- _telemetrySessionId = `lens-${Date.now().toString(36)}`;
74
- _lifecycleReason;
75
- _hasStableSessionId = false;
76
- _telemetryModel = "unknown";
77
- // Raw model/provider identity, separate from the combined `provider/model`
78
- // display string above — worklog/disposition attribution (#1448) wants the
79
- // two fields apart, blank when the host never supplied them. `_telemetryProvider`
80
- // is the explicit host value when given, else derived from the model id
81
- // (deriveProviderFromModelId, blank on ambiguity — never guessed).
82
- _telemetryModelId = "";
83
- _telemetryProvider = "";
84
- // True once a host has supplied an explicit provider this session. An
85
- // explicit provider is never downgraded by a derivation from a later
86
- // model-only call; a DERIVED provider, by contrast, is re-derived on
87
- // every model-only call so a mid-session model switch (e.g. gpt-5-mini →
88
- // claude-sonnet-4-5) doesn't leave a stale provider from the old model.
89
- _telemetryProviderIsExplicit = false;
90
- _turnIndex = 0;
91
- _writeIndex = 0;
92
- _projectSeq = 0;
93
- _turnStartProjectSeq = 0;
94
- _fileSeq = new Map();
95
- // File key → the projectSeq value at that file's most recent bump (#451). Lets
96
- // the review-graph builder ask "which files changed since I last built?" and
97
- // skip its per-build O(project) walk+stat sweep when only pi-observed edits
98
- // occurred. Keyed identically to _fileSeq (normalizeMapKey + path.resolve).
99
- _fileLastProjectSeq = new Map();
100
- _gitGuardHasBlockers = false;
101
- _gitGuardSummary = "";
102
- _gitGuardCacheUnknownReason;
103
- callGraph = null;
104
- wordIndex = null;
105
- _readGuard = null;
106
- _pendingDeferredMutations = new PathKeyedMap(normalizeMapKey);
107
- /** tool_call → tool_result path-attribution correlation (#1642). */
108
- _toolCallAttributions = new BoundedLruCache(TOOL_CALL_ATTRIBUTION_CAPACITY);
109
- _lspReadWarmState = new Map();
110
- _pendingInlineBlockers = new PathKeyedMap(normalizeMapKey);
111
- _actionableWarningsThisTurn = new Map();
112
- _codeQualityWarningsThisTurn = new Map();
113
- // #484: opt-in per-RUN summary of diagnostics/autofixes/formats,
114
- // accumulated across the run's turns and consumed once at the
115
- // agent_settled quiet window. The collector itself is always constructed
116
- // (cheap, empty Map) but callers gate recording behind the
117
- // `lens-turn-summary` flag so it's a true no-op when the feature is off.
118
- _turnSummary = new TurnSummaryCollector();
119
- // #2402/#1053: session-scoped applied-edit records for exact-retry
120
- // recognition. Both producers (partial-apply commit, full native-edit
121
- // success) write here; the preflight consults it before declaring an
122
- // oldText miss, so an identical retry never re-executes a committed write.
123
- partialApplyRecords = new PartialApplyRecordStore();
124
- resetForSession(startedAt = Date.now()) {
125
- this._sessionGeneration += 1;
126
- this._sessionStartedAt = startedAt;
127
- this._complexityBaselines.clear();
128
- this._pipelineCrashCounts.clear();
129
- this._cachedExports.clear();
130
- this.wordIndex = null;
131
- this._startupScansInFlight.clear();
132
- this._cascadeRuns = [];
133
- this._pendingCascadeRuns = [];
134
- this._turnEndCascadeSettleStarts.clear();
135
- this._cascadeSessionStats = {
136
- runs: 0,
137
- diagnosticsSurfaced: 0,
138
- coldSnapshotTouches: 0,
139
- };
140
- this._fixedThisTurn.clear();
141
- this._writtenThisTurn.clear();
142
- this._autofixDemotedThisTurn.clear();
143
- this._reportedThisTurn.clear();
144
- this._mutationReceipts = [];
145
- this._droppedMutationReceipts = 0;
146
- this._telemetrySessionId = `lens-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
147
- this._hasStableSessionId = false;
148
- this._telemetryModel = "unknown";
149
- this._telemetryModelId = "";
150
- this._telemetryProvider = "";
151
- this._telemetryProviderIsExplicit = false;
152
- this._turnIndex = 0;
153
- this._writeIndex = 0;
154
- this._projectSeq = 0;
155
- this._turnStartProjectSeq = 0;
156
- this._fileSeq.clear();
157
- this._fileLastProjectSeq.clear();
158
- this._gitGuardHasBlockers = false;
159
- this._gitGuardSummary = "";
160
- this._gitGuardCacheUnknownReason = undefined;
161
- this._readGuard = null;
162
- this._pendingDeferredMutations.clear();
163
- // #1642 F5: every sibling correlation/state map is cleared here. A
164
- // per-session-numbered host reusing tool-call ids across sessions must
165
- // not let a NEW session inherit a DEAD session's recorded skip verdict.
166
- this._toolCallAttributions.clear();
167
- this._lspReadWarmState.clear();
168
- this._pendingInlineBlockers.clear();
169
- this._actionableWarningsThisTurn.clear();
170
- this._codeQualityWarningsThisTurn.clear();
171
- this._turnSummary.clear();
172
- // #2402: an applied-edit record is a fact about the session that applied
173
- // it; a new session must re-resolve identical payloads from content.
174
- this.partialApplyRecords.clear();
175
- }
176
- get sessionStartedAt() {
177
- return this._sessionStartedAt;
178
- }
179
- get cascadeSessionStats() {
180
- return this._cascadeSessionStats;
181
- }
182
- recordCascadeRun(diagnosticsSurfaced, coldSnapshotTouches) {
183
- this._cascadeSessionStats.runs += 1;
184
- this._cascadeSessionStats.diagnosticsSurfaced += diagnosticsSurfaced;
185
- this._cascadeSessionStats.coldSnapshotTouches += coldSnapshotTouches;
186
- }
187
- updateGitGuardStatus(hasBlockers, output) {
188
- // The status is an aggregate over the current per-file map. A clean B
189
- // result must not erase an unresolved A result; the pipeline records/clears
190
- // the edited file immediately before this method runs.
191
- this._gitGuardHasBlockers =
192
- hasBlockers || this.getInlineBlockersSnapshot().length > 0;
193
- if (!this._gitGuardHasBlockers) {
194
- this._gitGuardSummary = "";
195
- return;
196
- }
197
- const firstLine = output
198
- .split("\n")
199
- .map((line) => line.trim())
200
- .find((line) => line.length > 0);
201
- const summaries = this.getInlineBlockersSnapshot()
202
- .map((entry) => entry.summary.trim())
203
- .filter(Boolean);
204
- this._gitGuardSummary = (summaries[0] ??
205
- firstLine ??
206
- "Unresolved blockers detected").slice(0, 160);
207
- }
208
- get gitGuardHasBlockers() {
209
- return this._gitGuardHasBlockers;
210
- }
211
- get gitGuardSummary() {
212
- return this._gitGuardSummary;
213
- }
214
- markGitGuardCacheUnknown(reason) {
215
- this._gitGuardCacheUnknownReason = reason;
216
- }
217
- clearGitGuardCacheUnknown() {
218
- this._gitGuardCacheUnknownReason = undefined;
219
- }
220
- get gitGuardCacheUnknownReason() {
221
- return this._gitGuardCacheUnknownReason;
222
- }
223
- beginTurn() {
224
- // #1443: runs sitting here at turn_start were appended AFTER the last
225
- // turn_end drained them (consumeCascadeRuns) — the quiet-window reconcile's
226
- // late re-injection (`onResolvedFound`, clients/lsp/cascade-tier.ts) lands
227
- // in exactly that window. Wiping them dead-ended that delivery path: the
228
- // finding was computed, formatted, appended, and then deleted before any
229
- // turn_end could render it. Carry them into THIS turn instead, exactly
230
- // once: `carriedTurns` is stamped on the way through and a run that the
231
- // next turn_end still did not consume is dropped here with a log line
232
- // rather than queued forever (a stale finding must not outlive the state
233
- // it describes, and an unbounded queue would replay it every turn).
234
- this._cascadeRuns = this._cascadeRuns.flatMap((run) => {
235
- const carriedTurns = (run.carriedTurns ?? 0) + 1;
236
- if (carriedTurns > 1) {
237
- logCascade({
238
- phase: "cascade_carry_over_drop",
239
- filePath: run.filePath,
240
- neighborCount: run.neighborCount,
241
- diagnosticCount: run.diagnosticCount,
242
- metadata: { carriedTurns, turnIndex: this._turnIndex },
243
- });
244
- return [];
245
- }
246
- return [{ ...run, carriedTurns }];
247
- });
248
- // _pendingCascadeRuns is deliberately NOT cleared here: a cascade compute
249
- // still in flight past last turn_end's settle cap (fresh graph builds have
250
- // measured up to ~19s) must surface on the NEXT turn_end, not be dropped —
251
- // pre-#450 those findings were always awaited, never lost. Session reset
252
- // still clears it.
253
- // Inline blockers are session-scoped per-file state. They are cleared only
254
- // when that file is re-analyzed clean or the session resets; a new turn must
255
- // not let a clean unrelated file erase an unresolved blocker.
256
- this._actionableWarningsThisTurn.clear();
257
- this._codeQualityWarningsThisTurn.clear();
258
- // _turnSummary is deliberately NOT cleared here (#484 rework): the
259
- // summary entry is emitted once per RUN at the agent_settled quiet
260
- // window (sendMessage during a live stream would STEER the agent, and
261
- // turn_end can fire mid-stream), so the collector must accumulate
262
- // across the run's turns. It is cleared only by consume() at emit and
263
- // by resetForSession().
264
- this._turnStartProjectSeq = this._projectSeq;
265
- this._turnIndex += 1;
266
- beginTurnContext(this._telemetrySessionId);
267
- this._writeIndex = 0;
268
- this._reportedThisTurn.clear();
269
- this._writtenThisTurn.clear();
270
- this._autofixDemotedThisTurn.clear();
271
- }
272
- /**
273
- * THE one mutation seam. Every producer of an in-project file mutation —
274
- * native write/edit, recognized bash writes, format/autofix, LSP workspace
275
- * edits, and (phase 2) opaque script-write recovery — records through here,
276
- * once: it bumps the seq store (`bumpFileSeq`), appends a bounded attributed
277
- * receipt, and optionally appends the durable change-log entry. Consumers
278
- * derive from `getFilesChangedSince` / `getMutationsSince`; no producer or
279
- * consumer may hand-roll a parallel bump+log pairing (#2000 phase 1).
280
- *
281
- * Receipt recording never throws; change-log append failures route to
282
- * `onAppendError` (default: swallowed) so telemetry cannot break dispatch.
283
- */
284
- recordProjectMutation(args) {
285
- const { projectSeq, fileSeq, key } = this.bumpFileSeq(args.filePath);
286
- if (this._mutationReceipts.length >= MAX_MUTATION_RECEIPTS) {
287
- this._mutationReceipts.shift();
288
- this._droppedMutationReceipts += 1;
289
- }
290
- this._mutationReceipts.push({
291
- seq: projectSeq,
292
- // Reuse the bump's normalized key (a realpath syscall: ~200us on
293
- // Windows, ~1.8us on POSIX since #3098) — never re-derive it here.
294
- filePath: key,
295
- source: args.source,
296
- turnIndex: this._turnIndex,
297
- ts: Date.now(),
298
- });
299
- if (args.cwd !== undefined) {
300
- try {
301
- appendProjectChange(args.cwd, {
302
- seq: projectSeq,
303
- timestamp: new Date().toISOString(),
304
- sessionId: this.telemetrySessionId,
305
- turnIndex: this.turnIndex,
306
- source: args.source,
307
- filePath: path.resolve(args.filePath),
308
- fileSeq,
309
- changedRange: args.changedRange,
310
- });
311
- }
312
- catch (err) {
313
- args.onAppendError?.(err);
314
- }
315
- }
316
- return { projectSeq, fileSeq };
317
- }
318
- /**
319
- * Attributed mutations whose seq is strictly after `seq` — the receipt-level
320
- * counterpart of {@link getFilesChangedSince}. Bounded: entries evicted by
321
- * the ring cap are gone; compare `droppedMutationReceiptCount` against zero
322
- * before treating the result as a complete window.
323
- */
324
- getMutationsSince(seq) {
325
- // Shallow copies: a consumer mutating a returned receipt must not
326
- // corrupt the ring's internal state.
327
- return this._mutationReceipts
328
- .filter((r) => r.seq > seq)
329
- .map((r) => ({ ...r }));
330
- }
331
- get droppedMutationReceiptCount() {
332
- return this._droppedMutationReceipts;
333
- }
334
- /**
335
- * Atomically records write/edit ordering before debounce can coalesce it.
336
- *
337
- * Takes the classified {@link MutationKind}, not a raw tool name (#2423):
338
- * an edit-shaped tool pi-lens does not name still demotes this file to the
339
- * deferred pass, which is the safe timing.
340
- */
341
- recordMutationToolReceipt(filePath, kind) {
342
- if (kind === "write") {
343
- this._writtenThisTurn.set(filePath, true);
344
- }
345
- else if (this._writtenThisTurn.has(filePath)) {
346
- this._autofixDemotedThisTurn.set(filePath, true);
347
- // A later edit establishes a new final state that must be eligible for
348
- // the deferred pass even if the preceding write was fixed immediately.
349
- this._fixedThisTurn.delete(filePath);
350
- }
351
- return {
352
- autofixMode: kind === "edit" || this._autofixDemotedThisTurn.has(filePath)
353
- ? "deferred"
354
- : "immediate",
355
- };
356
- }
357
- get reportedThisTurn() {
358
- return this._reportedThisTurn;
359
- }
360
- nextWriteIndex() {
361
- this._writeIndex += 1;
362
- return this._writeIndex;
363
- }
364
- peekWriteIndex() {
365
- return this._writeIndex;
366
- }
367
- setTelemetryIdentity(identity) {
368
- if (identity.sessionId && identity.sessionId.trim()) {
369
- this._telemetrySessionId = identity.sessionId.trim();
370
- setTurnContextSession(this._telemetrySessionId);
371
- }
372
- const model = identity.model?.trim();
373
- const provider = identity.provider?.trim();
374
- if (model && provider) {
375
- this._telemetryModel = `${provider}/${model}`;
376
- }
377
- else if (model) {
378
- this._telemetryModel = model;
379
- }
380
- else if (provider) {
381
- this._telemetryModel = provider;
382
- }
383
- if (model)
384
- this._telemetryModelId = model;
385
- if (provider) {
386
- this._telemetryProvider = provider;
387
- this._telemetryProviderIsExplicit = true;
388
- }
389
- else if (model && !this._telemetryProviderIsExplicit) {
390
- // No explicit provider has ever been reported this session, so the
391
- // provider is (still) a derivation — re-derive it from the CURRENT
392
- // model id every time. Without this, a stale derived provider from
393
- // an earlier model would survive a mid-session model switch (e.g.
394
- // gpt-5-mini → claude-sonnet-4-5 with no explicit provider on
395
- // either call) because the old "has any provider ever been set"
396
- // guard treated the derived value as sticky. An explicit provider,
397
- // once set, is never touched here regardless of later model calls.
398
- this._telemetryProvider = deriveProviderFromModelId(model);
399
- }
400
- }
401
- get telemetrySessionId() {
402
- return this._telemetrySessionId;
403
- }
404
- /**
405
- * Pin the session identity to pi's STABLE session id and record why this
406
- * session started (#190). Called AFTER {@link resetForSession} (which assigns
407
- * a fresh random id), so the stable id — when pi provides one via
408
- * `ctx.sessionManager.getSessionId()` — wins and survives a quit→resume.
409
- */
410
- setSessionLifecycle(args) {
411
- if (args.sessionId && args.sessionId.trim()) {
412
- this._telemetrySessionId = args.sessionId.trim();
413
- this._hasStableSessionId = true;
414
- }
415
- this._lifecycleReason = args.reason;
416
- }
417
- /** Why the current session started: new | resume | fork | reload | startup. */
418
- get sessionLifecycleReason() {
419
- return this._lifecycleReason;
420
- }
421
- /** True once a stable pi session id has been pinned (vs the random fallback). */
422
- get hasStableSessionId() {
423
- return this._hasStableSessionId;
424
- }
425
- get telemetryModel() {
426
- return this._telemetryModel;
427
- }
428
- /** Raw model id (never the combined `provider/model` display string), blank
429
- * when the host hasn't reported one this session. Worklog/disposition
430
- * attribution (#1448) reads this, not {@link telemetryModel}. */
431
- get telemetryModelId() {
432
- return this._telemetryModelId;
433
- }
434
- /** Explicit host-reported provider, or a conservative derivation from the
435
- * model id (see clients/model-provider.ts), blank when neither is known. */
436
- get telemetryProviderId() {
437
- return this._telemetryProvider;
438
- }
439
- get turnIndex() {
440
- return this._turnIndex;
441
- }
442
- get projectSeq() {
443
- return this._projectSeq;
444
- }
445
- get turnStartProjectSeq() {
446
- return this._turnStartProjectSeq;
447
- }
448
- seedProjectSequence(projectSeq, fileSeqByPath) {
449
- this._projectSeq = Math.max(0, Math.floor(projectSeq));
450
- this._turnStartProjectSeq = this._projectSeq;
451
- this._fileSeq.clear();
452
- // Seeded per-file counters carry no projectSeq provenance, so start the
453
- // changed-since map empty; the graph fast path simply won't fire until an
454
- // in-process bump records a seq-stamped change (safe: falls back to sweep).
455
- this._fileLastProjectSeq.clear();
456
- for (const [filePath, seq] of fileSeqByPath ?? []) {
457
- this._fileSeq.set(normalizeMapKey(path.resolve(filePath)), Math.max(0, seq));
458
- }
459
- }
460
- bumpFileSeq(filePath) {
461
- // normalizeMapKey costs a realpath syscall per call — ~200us on Windows,
462
- // ~1.8us on POSIX since #3098; every caller that also needs the key must
463
- // reuse this one instead of paying it twice.
464
- const key = normalizeMapKey(path.resolve(filePath));
465
- this._projectSeq += 1;
466
- const fileSeq = (this._fileSeq.get(key) ?? 0) + 1;
467
- this._fileSeq.set(key, fileSeq);
468
- this._fileLastProjectSeq.set(key, this._projectSeq);
469
- return { projectSeq: this._projectSeq, fileSeq, key };
470
- }
471
- /**
472
- * Files whose most recent bump happened AFTER `seq` — i.e. every file the
473
- * review graph would need to re-ingest to catch up from a build taken at
474
- * projectSeq `seq` (#451). Returns NORMALIZED keys (normalizeMapKey +
475
- * path.resolve), the same form the builder's fileSignatures map uses, so the
476
- * caller can compare without re-normalizing.
477
- */
478
- getFilesChangedSince(seq) {
479
- const changed = [];
480
- for (const [key, lastSeq] of this._fileLastProjectSeq) {
481
- if (lastSeq > seq)
482
- changed.push(key);
483
- }
484
- return changed;
485
- }
486
- getFileSeq(filePath) {
487
- return this._fileSeq.get(normalizeMapKey(path.resolve(filePath))) ?? 0;
488
- }
489
- getFileSeqEntries() {
490
- return [...this._fileSeq.entries()];
491
- }
492
- get sessionGeneration() {
493
- return this._sessionGeneration;
494
- }
495
- isCurrentSession(generation) {
496
- return this._sessionGeneration === generation;
497
- }
498
- markStartupScanInFlight(name, generation) {
499
- this._startupScansInFlight.set(name, generation);
500
- }
501
- clearStartupScanInFlight(name, generation) {
502
- const owner = this._startupScansInFlight.get(name);
503
- if (owner === generation) {
504
- this._startupScansInFlight.delete(name);
505
- }
506
- }
507
- isStartupScanInFlight(name) {
508
- return this._startupScansInFlight.has(name);
509
- }
510
- formatPipelineCrashNotice(filePath, err) {
511
- const key = path.resolve(filePath);
512
- const count = (this._pipelineCrashCounts.get(key) ?? 0) + 1;
513
- this._pipelineCrashCounts.set(key, count);
514
- const message = err instanceof Error ? err.message : String(err);
515
- const shortMessage = message.split("\n")[0].slice(0, 220);
516
- const shouldSurface = count <= RUNTIME_CONFIG.crashNotice.alwaysShowFirstN ||
517
- count % RUNTIME_CONFIG.crashNotice.showEveryNth === 0;
518
- if (!shouldSurface)
519
- return "";
520
- return [
521
- "⚠️ pi-lens pipeline crashed while analyzing this write.",
522
- `File: ${path.basename(filePath)} | crash count this session: ${count}`,
523
- `Error: ${shortMessage}`,
524
- "Recovery: LSP service was reset. If this repeats, rerun with --no-lsp and report the file + stack.",
525
- ].join("\n");
526
- }
527
- getCrashEntries() {
528
- return Array.from(this._pipelineCrashCounts.entries());
529
- }
530
- get projectRoot() {
531
- return this._projectRoot;
532
- }
533
- set projectRoot(value) {
534
- this._projectRoot = normalizeMapKey(value);
535
- }
536
- get errorDebtBaseline() {
537
- return this._errorDebtBaseline;
538
- }
539
- set errorDebtBaseline(value) {
540
- this._errorDebtBaseline = value;
541
- }
542
- get cachedExports() {
543
- return this._cachedExports;
544
- }
545
- appendCascadeRun(run) {
546
- this._cascadeRuns.push(run);
547
- }
548
- appendCascadePromise(p) {
549
- if (this._pendingCascadeRuns.length < MAX_PENDING_CASCADE_RUNS) {
550
- this._pendingCascadeRuns.push(p);
551
- return;
552
- }
553
- // Preserve delivery for overflow rather than growing the per-edit array.
554
- // The settled run enters the same accumulator off-hook and is therefore
555
- // visible to the next turn-end drain.
556
- recordDegradationOnce({
557
- kind: "cascade-pending-cap",
558
- subject: "runtime-coordinator",
559
- reason: `deferred cascade admission capped at ${MAX_PENDING_CASCADE_RUNS}`,
560
- });
561
- void p
562
- .then((run) => this.appendCascadeRun(run))
563
- .catch(() => {
564
- // Pipeline promises are normally non-rejecting; preserve the existing
565
- // failure sink if a caller violates that contract.
566
- });
567
- }
568
- /**
569
- * The active turn_end settle clock, or undefined outside that wait.
570
- *
571
- * #1462 review F-F: every cascade compute in flight on this coordinator
572
- * reads the SAME clock. `_turnEndCascadeSettleStarts` is keyed by settle
573
- * token so `settleCascadeRuns` can distinguish its own drain from a nested
574
- * one, but this getter always answers with the latest active window —
575
- * there is one turn_end per runtime, not one per caller. A cascade begun
576
- * moments before turn_end and one begun long before it both measure elapsed
577
- * time against the same start, which is correct: they are racing the same
578
- * settle wait and share its deadline, not separate ones.
579
- */
580
- getTurnEndCascadeSettleStart() {
581
- let latest;
582
- for (const start of this._turnEndCascadeSettleStarts.values())
583
- latest = start;
584
- return latest;
585
- }
586
- /**
587
- * Drain the deferred cascade computes kicked off this turn (#450), racing them
588
- * against a bounded wait. Fulfilled runs feed the same accumulator as inline
589
- * runs (appendCascadeRun). A promise still pending at the cap is retained so a
590
- * late-resolving compute is picked up on the next turn_end rather than lost.
591
- * The stored promises never reject (pipeline guarantees an "error" skip-run).
592
- */
593
- async settleCascadeRuns(maxWaitMs, settleOptions = {}) {
594
- const pending = this._pendingCascadeRuns;
595
- if (pending.length === 0)
596
- return { settled: 0, timedOut: 0 };
597
- this._pendingCascadeRuns = [];
598
- const settleToken = settleOptions.trackTurnEndClock
599
- ? ++this._nextCascadeSettleToken
600
- : undefined;
601
- if (settleToken !== undefined) {
602
- this._turnEndCascadeSettleStarts.set(settleToken, Date.now());
603
- }
604
- try {
605
- // Track per-promise settlement so promises still in flight at the cap can be
606
- // carried over. A settled entry records its run; an unsettled one is re-parked.
607
- const tracked = pending.map((p) => {
608
- const entry = { done: false, promise: p };
609
- entry.promise = p.then((run) => {
610
- entry.done = true;
611
- entry.run = run;
612
- return run;
613
- });
614
- return entry;
615
- });
616
- const timeout = new Promise((resolve) => {
617
- setTimeout(resolve, maxWaitMs).unref?.();
618
- });
619
- await Promise.race([
620
- Promise.allSettled(tracked.map((t) => t.promise)),
621
- timeout,
622
- ]);
623
- let settled = 0;
624
- let timedOut = 0;
625
- for (const entry of tracked) {
626
- if (entry.done && entry.run) {
627
- this.appendCascadeRun(entry.run);
628
- settled += 1;
629
- }
630
- else {
631
- this._pendingCascadeRuns.push(entry.promise);
632
- timedOut += 1;
633
- }
634
- }
635
- return { settled, timedOut };
636
- }
637
- finally {
638
- if (settleToken !== undefined) {
639
- this._turnEndCascadeSettleStarts.delete(settleToken);
640
- }
641
- }
642
- }
643
- consumeCascadeRuns() {
644
- const runs = this._cascadeRuns;
645
- this._cascadeRuns = [];
646
- return runs;
647
- }
648
- /**
649
- * R1 (#1443 follow-up): non-destructive peek used by turn_end's read-only
650
- * fast path. A carried cascade run (or one still in flight) represents a
651
- * DELIVERY OPPORTUNITY, not turn activity — an agent that answers a question
652
- * without editing anything must still get yesterday's late finding. Before
653
- * this, the files-empty early return skipped `settleCascadeRuns` /
654
- * `consumeCascadeRuns` entirely on a read-only turn, so `beginTurn`'s next
655
- * carry pass saw the run as having survived a turn_start with no offsetting
656
- * drain and dropped it — burning the one-turn carry allowance on a turn that
657
- * never had a chance to deliver.
658
- */
659
- hasCascadeRuns() {
660
- // Carried, ALREADY-BUILT runs only. Pending (still-settling) computes are
661
- // deliberately excluded: a read-only turn that fell through for a pending
662
- // run would block on the full settle cap — every turn, forever, when the
663
- // compute never resolves (re-review finding F1). A pending run loses
664
- // nothing by waiting: settleCascadeRuns re-parks it and the next turn
665
- // that actually settles it delivers it.
666
- return this._cascadeRuns.length > 0;
667
- }
668
- recordInlineBlockers(filePath, summary, writeIndex, sources, lines, contentBaseline) {
669
- const recordedAtMs = Date.now();
670
- this._pendingInlineBlockers.set(path.resolve(filePath), {
671
- filePath,
672
- summary,
673
- writeIndex,
674
- sources,
675
- lines,
676
- recordedAtMs,
677
- stale: false,
678
- ...(contentBaseline
679
- ? {
680
- recordedSize: contentBaseline.size,
681
- recordedHash: contentBaseline.sha256,
682
- }
683
- : {}),
684
- });
685
- return recordedAtMs;
686
- }
687
- clearInlineBlockers(filePath) {
688
- this._pendingInlineBlockers.delete(path.resolve(filePath));
689
- }
690
- /**
691
- * #1631: demote a cached blocker to stale without dropping it (#1419
692
- * demote-not-drop). Called by the turn-boundary freshness sweep when the
693
- * file or one of its forward imports drifted on disk after the verdict.
694
- * Idempotent: re-marking an already-stale entry (for ANY reason) is a
695
- * no-op — a `"past-eof"` demotion already took this record out of the
696
- * authoritative channel, and `sweepInlineBlockerFreshness` re-checks next
697
- * turn once that heals. Returns true only when this call transitioned the
698
- * entry to stale, so a caller can log the demotion exactly once.
699
- */
700
- markInlineBlockerStale(filePath, reason = "dependency-drift") {
701
- const key = path.resolve(filePath);
702
- const existing = this._pendingInlineBlockers.get(key);
703
- if (!existing || existing.stale)
704
- return false;
705
- this._pendingInlineBlockers.set(key, {
706
- ...existing,
707
- stale: true,
708
- staleReason: reason,
709
- });
710
- return true;
711
- }
712
- /**
713
- * #1641: re-derive the past-EOF demotion for one inline-blocker record.
714
- * Unlike {@link markInlineBlockerStale} (a one-way latch for the
715
- * dependency-drift gate), this RE-ARMS: called every turn end with the
716
- * gate's freshly-computed verdict, it can both demote (rising edge) and
717
- * heal (falling edge — a transient shrink-then-restore of the file). Never
718
- * touches a record a sibling gate demoted (`staleReason !== "past-eof"`
719
- * while `stale`) — composing with #1631's dependency-drift gate means each
720
- * gate only heals its own demotions. Returns true only on an actual
721
- * transition, so the caller logs/resyncs exactly once per edge.
722
- */
723
- setInlineBlockerPastEofStale(filePath, isPastEof) {
724
- const key = path.resolve(filePath);
725
- const existing = this._pendingInlineBlockers.get(key);
726
- if (!existing)
727
- return false;
728
- if (existing.stale && existing.staleReason !== "past-eof")
729
- return false;
730
- const currentlyPastEof = !!existing.stale && existing.staleReason === "past-eof";
731
- if (currentlyPastEof === isPastEof)
732
- return false;
733
- this._pendingInlineBlockers.set(key, {
734
- ...existing,
735
- stale: isPastEof,
736
- staleReason: isPastEof ? "past-eof" : undefined,
737
- });
738
- return true;
739
- }
740
- /**
741
- * #2982: re-derive the self-drift demotion for one inline-blocker record.
742
- *
743
- * Modelled on {@link setInlineBlockerPastEofStale}, not on
744
- * {@link markInlineBlockerStale}: it RE-ARMS rather than latching, so a
745
- * file whose bytes drift and then come back (a checkout, a revert, an
746
- * editor writing the original content) un-demotes on the next sweep
747
- * instead of staying demoted for the session. That re-arm is what lets
748
- * this axis skip the #1950 delivery cap entirely — a record that can heal
749
- * needs no bounded-noise retirement, and applying the cap here would walk
750
- * an ast-grep or tree-sitter security finding out of turn-end rendering
751
- * permanently (#2982 review).
752
- *
753
- * Composes with the sibling gates the same way they compose with each
754
- * other: it never touches a record another gate demoted, and never heals a
755
- * demotion it did not make. Returns true only on an actual transition, so
756
- * the caller counts exactly one edge.
757
- */
758
- setInlineBlockerSelfDriftStale(filePath, isSelfDrift) {
759
- const key = path.resolve(filePath);
760
- const existing = this._pendingInlineBlockers.get(key);
761
- if (!existing)
762
- return false;
763
- if (existing.stale && existing.staleReason !== "self-drift")
764
- return false;
765
- const currentlySelfDrift = !!existing.stale && existing.staleReason === "self-drift";
766
- if (currentlySelfDrift === isSelfDrift)
767
- return false;
768
- // Omit the key rather than assigning `undefined` to it: under
769
- // `exactOptionalPropertyTypes` those are different, and writing the
770
- // `undefined` is a strictness spike the ratchet counts. Healing has to
771
- // drop `staleReason` off the rebuilt record, so destructure it away
772
- // instead of letting `...existing` carry the old value through.
773
- const { staleReason: _cleared, ...rest } = existing;
774
- this._pendingInlineBlockers.set(key, {
775
- ...rest,
776
- stale: isSelfDrift,
777
- ...(isSelfDrift ? { staleReason: "self-drift" } : {}),
778
- });
779
- return true;
780
- }
781
- /**
782
- * #1944: retire a past-EOF demotion after its ONE degraded delivery.
783
- *
784
- * The past-EOF gate demotes and re-arms, but nothing ever retired the
785
- * record, so a blocker whose file shrank past the cited lines re-served on
786
- * every turn end for the rest of the session — measured live at 80+
787
- * minutes on session 01a0234c. The re-serve is unbounded, not the six
788
- * turns the first evidence window suggested.
789
- *
790
- * It is unbounded because the record cannot resolve itself. The two
791
- * clearing events (`clearInlineBlockers` on a later dispatch of the same
792
- * path, `retireInlineBlockerOnConfirmedClean` on a fresh clean verdict)
793
- * both need the file to be looked at again, and the agent has no reason to
794
- * look: the coordinates it was handed do not exist. "Re-run to confirm" is
795
- * an instruction this record makes impossible to follow.
796
- *
797
- * So the delivery surface retires it after serving it once, degraded. That
798
- * is a DROP, which #1419's demote-not-drop rule normally forbids; the
799
- * exception is narrow and stated here. The finding was already delivered
800
- * this turn with its dead coordinates annotated, and what remains is a
801
- * message pinned to a line the file does not have. `deadLines` is required
802
- * and must be non-empty, so a record stale for any OTHER reason, or
803
- * past-EOF with no identified dead line, still stands.
804
- *
805
- * @returns true when an entry was retired — the caller records it, so the
806
- * suppression is never silent (#1432 Gap 1).
807
- */
808
- retireDemotedPastEofBlocker(filePath, deadLines) {
809
- if (deadLines.length === 0)
810
- return false;
811
- const key = path.resolve(filePath);
812
- const existing = this._pendingInlineBlockers.get(key);
813
- if (!existing)
814
- return false;
815
- // Only this gate's own demotion. A dependency-drift demotion (#1631)
816
- // keeps in-bounds coordinates the agent CAN re-run against, so it stays
817
- // in the store until a fresh verdict clears it.
818
- if (!existing.stale)
819
- return false;
820
- if ((existing.staleReason ?? "past-eof") !== "past-eof")
821
- return false;
822
- this._pendingInlineBlockers.delete(key);
823
- return true;
824
- }
825
- /**
826
- * #1950 fix-round F1: read the current delivery count WITHOUT committing
827
- * an increment. `runtime-turn.ts` needs the count a delivery would reach
828
- * BEFORE it knows whether that delivery will actually reach the agent —
829
- * the turn-end signature dedupe (`turn-end-findings-last`) can suppress a
830
- * turn whose rendered content is identical to the last one, and a
831
- * suppressed turn must not advance the counter (the agent never saw it).
832
- * The caller peeks, renders the tentative body, and only calls
833
- * {@link incrementInlineBlockerStaleDelivery} once it knows the turn's
834
- * content is NOT being suppressed.
835
- */
836
- peekInlineBlockerStaleDeliveryCount(filePath) {
837
- const key = path.resolve(filePath);
838
- return this._pendingInlineBlockers.get(key)?.staleDeliveryCount ?? 0;
839
- }
840
- /**
841
- * #1950: commit one more turn end that re-served this record while
842
- * `stale`. The caller (`runtime-turn.ts`) only calls this for a
843
- * `"dependency-drift"` demotion — a `"past-eof"` demotion retires after
844
- * its own single delivery (#1944, `retireDemotedPastEofBlocker`) and
845
- * never accumulates a count — and only AFTER confirming the turn's
846
- * content will not be suppressed by the signature dedupe (see
847
- * {@link peekInlineBlockerStaleDeliveryCount}), so this counts ACTUAL
848
- * deliveries the agent saw, not turn-end loop iterations. Returns the new
849
- * count, or 0 when there is no entry to count against (already retired,
850
- * or never recorded).
851
- */
852
- incrementInlineBlockerStaleDelivery(filePath) {
853
- const key = path.resolve(filePath);
854
- const existing = this._pendingInlineBlockers.get(key);
855
- if (!existing)
856
- return 0;
857
- const next = (existing.staleDeliveryCount ?? 0) + 1;
858
- this._pendingInlineBlockers.set(key, {
859
- ...existing,
860
- staleDeliveryCount: next,
861
- });
862
- return next;
863
- }
864
- /**
865
- * #1950: retire a dependency-drift demotion once it has been delivered
866
- * `DEPENDENCY_DRIFT_MAX_DELIVERIES` times with no re-run confirming or
867
- * clearing it. Unlike {@link retireDemotedPastEofBlocker}, the record is
868
- * NOT provably unrecoverable — its coordinates are still in bounds, and a
869
- * fresh dispatch of the file could still confirm or clear it. This is a
870
- * bounded-noise cap, not a "this can never resolve" verdict, and the
871
- * caller's ledger reason must say so (`demoted-finding-retired`'s "capped,
872
- * re-run can still confirm" vs. past-EOF's "retired, unrecoverable").
873
- *
874
- * Only ever touches this gate's OWN demotion (`staleReason ===
875
- * "dependency-drift"`) — a past-EOF demotion on the same file is that
876
- * gate's own record to retire, not this one's.
877
- *
878
- * @returns true when an entry was retired — the caller records it, so the
879
- * suppression is never silent (#1432 Gap 1).
880
- */
881
- retireDemotedDependencyDriftBlocker(filePath) {
882
- const key = path.resolve(filePath);
883
- const existing = this._pendingInlineBlockers.get(key);
884
- if (!existing)
885
- return false;
886
- if (!existing.stale)
887
- return false;
888
- if (existing.staleReason !== "dependency-drift")
889
- return false;
890
- this._pendingInlineBlockers.delete(key);
891
- return true;
892
- }
893
- /**
894
- * Retire a file's inline blocker because a FRESH, content-bound diagnostic
895
- * verdict proved it gone (#1561).
896
- *
897
- * The map was invalidated by exactly two events: a later dispatch of the
898
- * SAME path returning no blockers, and that path ceasing to exist (#1245).
899
- * Neither covers the common case that produced #1561 — a blocker on file F
900
- * whose cause lives in file G. Fixing G re-dispatches G, not F, so F's
901
- * verdict was never re-taken and "Unresolved from this turn" was re-injected
902
- * for the rest of the session. In the live case the agent then ran
903
- * `lsp_diagnostics` on F, pi-lens answered "confirmed clean", and the
904
- * blocker was STILL re-served on the next three turn ends: #571 wired that
905
- * tool's confirmed result into the widget footer and stopped there.
906
- *
907
- * This is the seam #1198 invariant 4 left undecided, decided: an affirmative
908
- * clean from the authoritative current view retires the stale verdict.
909
- *
910
- * Ordering (#1198 invariants 1-2). Both stores draw from the same
911
- * `nextWriteIndex()` counter, so when both sides are stamped the retire
912
- * requires the clean verdict to be strictly NEWER. A slow old clean that
913
- * settles after a fresh dispatch found real blockers must not erase them.
914
- * When either side is unstamped the two cannot be ordered at all; the fresh
915
- * confirmed verdict wins, because it is the only one of the two backed by an
916
- * actual observation of current content. Only production's single record site
917
- * is stamped, so in practice the unstamped branch is legacy callers/tests.
918
- *
919
- * COVERAGE (#1561 F1). A blocker is retired only by a verdict that can speak
920
- * for the tools that raised it. Inline blockers come from the whole dispatch,
921
- * not just the language server: `dispatcher.ts` collects every
922
- * `semantic === "blocking"` diagnostic across all runners, so eslint,
923
- * biome-check, actionlint, elixir/gleam-check and ast-grep security rules all
924
- * land in this map. A language-server check knows nothing about any of them,
925
- * so `coveredSources` must be a SUPERSET of the recorded sources or the entry
926
- * stands. This is a commit gate: a record whose provenance is unknown (no
927
- * `sources`) fails CLOSED and is never retired, because "we don't know what
928
- * raised this" must not resolve to "an LSP check can clear it".
929
- *
930
- * @returns true when an entry was retired — the caller logs it, so an
931
- * eviction is never silent (#1432 Gap 1).
932
- */
933
- retireInlineBlockerOnConfirmedClean(filePath, confirmedAtWriteIndex, coveredSources) {
934
- const key = path.resolve(filePath);
935
- const existing = this._pendingInlineBlockers.get(key);
936
- if (!existing)
937
- return false;
938
- if (existing.writeIndex !== undefined &&
939
- confirmedAtWriteIndex !== undefined &&
940
- confirmedAtWriteIndex <= existing.writeIndex) {
941
- return false;
942
- }
943
- // Fail closed on unknown provenance, and on any source the fresh verdict
944
- // did not consult. An eslint-origin blocker outliving an LSP-only clean is
945
- // the correct outcome — the next dispatch of that file is what clears it.
946
- if (!existing.sources || existing.sources.length === 0)
947
- return false;
948
- const covered = new Set(coveredSources ?? []);
949
- if (!existing.sources.every((source) => covered.has(source)))
950
- return false;
951
- this._pendingInlineBlockers.delete(key);
952
- return true;
953
- }
954
- reconcileInlineBlockers() {
955
- // Rebuild, never delete-in-place: `PathKeyedMap.delete()` re-normalizes
956
- // the key, and `normalizeMapKey` realpaths a live file but lowercases
957
- // the tail of a deleted one — so on Windows a mixed-case filename gets
958
- // a DIFFERENT delete-time key than its set-time key and the delete
959
- // misses (#1245, verified live: `MyCase.ts` survived reconcile).
960
- // Existence-checking the display path and rebuilding survivors avoids
961
- // the key-mismatch entirely; live survivors re-set to identical keys
962
- // (both realpath), so only the stale entries are dropped.
963
- const survivors = [];
964
- for (const [displayPath, value] of this._pendingInlineBlockers.entries()) {
965
- if (fs.existsSync(displayPath))
966
- survivors.push([displayPath, value]);
967
- }
968
- if (survivors.length !== this._pendingInlineBlockers.size) {
969
- this._pendingInlineBlockers.clear();
970
- for (const [displayPath, value] of survivors) {
971
- this._pendingInlineBlockers.set(displayPath, value);
972
- }
973
- }
974
- }
975
- /**
976
- * Stale-entry reconcile (#1245): a blocker recorded for a file that has
977
- * since been deleted can never be cleared — `clearInlineBlockers` fires
978
- * only on a LATER dispatch of the same path, which a deleted file never
979
- * gets. Every read of the blocker map (turn_end injection, git-guard
980
- * size/summary, `syncGitGuardRecord`) therefore drops entries whose file no
981
- * longer exists on disk: a blocker for a deleted file is stale by
982
- * definition (the agent cannot fix it), so it must not re-surface every
983
- * turn or gate a commit. The map is tiny (per-turn blockers) and reads are
984
- * bounded (once per turn_end / tool_result), so the probe cost is
985
- * negligible.
986
- */
987
- getInlineBlockersSnapshot() {
988
- this.reconcileInlineBlockers();
989
- return [...this._pendingInlineBlockers.values()];
990
- }
991
- consumeInlineBlockers() {
992
- const entries = this.getInlineBlockersSnapshot();
993
- this._pendingInlineBlockers.clear();
994
- return entries;
995
- }
996
- recordActionableWarnings(warnings) {
997
- for (const warning of warnings) {
998
- this._actionableWarningsThisTurn.set(warning.id, warning);
999
- }
1000
- }
1001
- peekActionableWarnings() {
1002
- return [...this._actionableWarningsThisTurn.values()];
1003
- }
1004
- clearActionableWarnings() {
1005
- this._actionableWarningsThisTurn.clear();
1006
- }
1007
- recordCodeQualityWarnings(warnings) {
1008
- for (const warning of warnings) {
1009
- this._codeQualityWarningsThisTurn.set(warning.id, warning);
1010
- }
1011
- }
1012
- peekCodeQualityWarnings() {
1013
- return [...this._codeQualityWarningsThisTurn.values()];
1014
- }
1015
- clearCodeQualityWarnings() {
1016
- this._codeQualityWarningsThisTurn.clear();
1017
- }
1018
- /** #484: the per-run diagnostics/autofix/format collector (accumulates
1019
- * across turns; consumed once at the agent_settled quiet window). Always
1020
- * present; callers gate recording behind the `lens-turn-summary` opt-in
1021
- * flag. */
1022
- get turnSummary() {
1023
- return this._turnSummary;
1024
- }
1025
- get complexityBaselines() {
1026
- return this._complexityBaselines;
1027
- }
1028
- get fixedThisTurn() {
1029
- // Self-referencing local so chained add() returns the same facade
1030
- // instead of re-entering this getter and allocating a new one per call
1031
- // (sonar S7725).
1032
- const facade = {
1033
- add: (filePath) => {
1034
- this._fixedThisTurn.set(filePath, true);
1035
- return facade;
1036
- },
1037
- has: (filePath) => this._fixedThisTurn.has(filePath),
1038
- delete: (filePath) => this._fixedThisTurn.delete(filePath),
1039
- clear: () => this._fixedThisTurn.clear(),
1040
- };
1041
- return facade;
1042
- }
1043
- get projectRulesScan() {
1044
- return this._projectRulesScan;
1045
- }
1046
- set projectRulesScan(value) {
1047
- this._projectRulesScan = value;
1048
- }
1049
- get readGuard() {
1050
- this._readGuard ??= new ReadGuard(this._telemetrySessionId);
1051
- return this._readGuard;
1052
- }
1053
- /**
1054
- * Record the canonical target `tool_call` resolved for `toolCallId`
1055
- * (#1642). The paired `tool_result` claims this exactly once via
1056
- * {@link takeToolCallAttribution} instead of re-deriving a path from its
1057
- * own diff metadata.
1058
- */
1059
- recordToolCallAttribution(toolCallId, attribution) {
1060
- this._toolCallAttributions.set(toolCallId, {
1061
- ...attribution,
1062
- recordedAt: Date.now(),
1063
- });
1064
- }
1065
- /**
1066
- * One-shot claim of a previously recorded tool-call attribution. Removed
1067
- * on read: a given `tool_call`/`tool_result` pair correlates exactly once,
1068
- * and leaving it behind would let a later, unrelated `tool_result` that
1069
- * happens to reuse a stale id inherit a stranger's resolved path.
1070
- *
1071
- * An expired entry (older than `TOOL_CALL_ATTRIBUTION_TTL_MS`) is treated
1072
- * as a miss and removed rather than returned — see the constant's doc.
1073
- */
1074
- takeToolCallAttribution(toolCallId) {
1075
- const attribution = this._toolCallAttributions.get(toolCallId);
1076
- if (attribution === undefined)
1077
- return undefined;
1078
- this._toolCallAttributions.delete(toolCallId);
1079
- if (Date.now() - attribution.recordedAt > TOOL_CALL_ATTRIBUTION_TTL_MS) {
1080
- return undefined;
1081
- }
1082
- return attribution;
1083
- }
1084
- /**
1085
- * Queue one mutation kind for `filePath` at `agent_end`. Returns `true`
1086
- * when this call created a pending entry or added a new kind, and `false`
1087
- * for a same-kind re-touch. Callers publish each kind's first transition
1088
- * without spamming repeated edits before `agent_end`.
1089
- */
1090
- deferMutation(filePath, cwd,
1091
- /** Host tool name; any mutating tool, not just `write`/`edit` (#2423). */
1092
- toolName, turnStateCwd, kind, ownerSessionId, originCwd) {
1093
- const key = path.resolve(filePath);
1094
- const now = Date.now();
1095
- const resolvedOriginCwd = originCwd ?? turnStateCwd;
1096
- const existing = this._pendingDeferredMutations.get(key);
1097
- if (existing) {
1098
- const addedKind = !existing.kinds.has(kind);
1099
- existing.lastTouchedAt = now;
1100
- existing.cwd = cwd;
1101
- existing.turnStateCwd = turnStateCwd;
1102
- existing.toolNames.add(toolName);
1103
- existing.kinds.add(kind);
1104
- existing.queuedTurnIndex = this._turnIndex;
1105
- existing.queuedTurnId = `${this._telemetrySessionId}:${this._turnIndex}`;
1106
- existing.ownerSessionId = ownerSessionId;
1107
- existing.originCwd = resolvedOriginCwd;
1108
- return addedKind;
1109
- }
1110
- this._pendingDeferredMutations.set(key, {
1111
- filePath: key,
1112
- cwd,
1113
- turnStateCwd,
1114
- firstTouchedAt: now,
1115
- lastTouchedAt: now,
1116
- toolNames: new Set([toolName]),
1117
- kinds: new Set([kind]),
1118
- queuedTurnIndex: this._turnIndex,
1119
- queuedTurnId: `${this._telemetrySessionId}:${this._turnIndex}`,
1120
- ownerSessionId,
1121
- originCwd: resolvedOriginCwd,
1122
- });
1123
- return true;
1124
- }
1125
- deferFormat(filePath, cwd,
1126
- /** Host tool name; any mutating tool, not just `write`/`edit` (#2423). */
1127
- toolName, turnStateCwd, ownerSessionId, originCwd) {
1128
- return this.deferMutation(filePath, cwd, toolName, turnStateCwd, "format", ownerSessionId, originCwd);
1129
- }
1130
- get pendingDeferredFormatCount() {
1131
- return this._pendingDeferredMutations.size;
1132
- }
1133
- get pendingDeferredMutationCount() {
1134
- return this._pendingDeferredMutations.size;
1135
- }
1136
- /**
1137
- * Legacy unconditional drain — still exposed for any caller that
1138
- * genuinely wants "everything, no ownership check" (and for tests). New
1139
- * flush call sites should prefer {@link claimDeferredFormatFiles}.
1140
- */
1141
- consumeDeferredFormatFiles() {
1142
- const records = [...this._pendingDeferredMutations.values()];
1143
- this._pendingDeferredMutations.clear();
1144
- return records;
1145
- }
1146
- /**
1147
- * Ownership-filtered drain (#791). Claims and removes only the records
1148
- * this flush is entitled to:
1149
- * - `ownerSessionId` unset on the record, OR `currentSessionId` unset, OR
1150
- * they match → claimed as "same session" (the common case, and the
1151
- * fail-safe default when either side lacks a stable session id).
1152
- * - otherwise (both known, and they differ) the record belongs to a
1153
- * DIFFERENT session (e.g. a concurrent in-process secondary/subagent)
1154
- * and is left queued for its owner's own flush — UNLESS it has sat
1155
- * unclaimed longer than `staleAfterMs` (the owner presumably died), in
1156
- * which case this flush claims it as an orphan-recovery fallback ONLY
1157
- * when `currentOriginCwd` (this flush's own workspace/worktree) exactly
1158
- * matches the record's `originCwd` (the cwd it was actually queued
1159
- * under, #1642 F3 — NOT `turnStateCwd`, which is always the workspace
1160
- * root by design and so would match every session unconditionally). A
1161
- * mismatch means the record belongs to a DIFFERENT checkout/worktree
1162
- * than the one now running `agent_end` — claiming it across that
1163
- * boundary is exactly how a worktree's queued edit got formatted onto
1164
- * the parent checkout in the reported incident. It is left queued
1165
- * (NOT deleted) and logged instead: a legitimate crashed-session
1166
- * orphan from, say, a monorepo subdir must still be claimable later by
1167
- * a flush whose origin actually matches, or stay visible for
1168
- * observability — deleting it here would drop it forever with no
1169
- * origin ever able to reclaim it.
1170
- *
1171
- * Returns the claimed records, the left-queued mismatched-origin records,
1172
- * and per-skipped record why it was left behind — callers use this for
1173
- * `agent_end`'s latency-log provenance and for the "stale fallback
1174
- * fired"/"orphan mismatch" log lines.
1175
- */
1176
- claimDeferredFormatFiles(currentSessionId, now, staleAfterMs, currentOriginCwd) {
1177
- const claimed = [];
1178
- const staleClaimed = [];
1179
- const deferredToOwner = [];
1180
- const droppedOrphans = [];
1181
- for (const [key, record] of this._pendingDeferredMutations) {
1182
- const sameSession = record.ownerSessionId === undefined ||
1183
- currentSessionId === undefined ||
1184
- record.ownerSessionId === currentSessionId;
1185
- if (sameSession) {
1186
- claimed.push(record);
1187
- this._pendingDeferredMutations.delete(key);
1188
- continue;
1189
- }
1190
- const age = now - record.lastTouchedAt;
1191
- if (age > staleAfterMs) {
1192
- // #1642 F3: origin identity is required before an orphan-recovery
1193
- // claim, not just staleness. `currentOriginCwd === undefined`
1194
- // means the caller can't state its own origin — fail-safe as
1195
- // "can't prove different" (same posture as the sameSession check
1196
- // above), not as a free pass to claim across a KNOWN mismatch.
1197
- const originMatches = currentOriginCwd === undefined ||
1198
- pathsEqual(record.originCwd, currentOriginCwd);
1199
- if (originMatches) {
1200
- this._pendingDeferredMutations.delete(key);
1201
- staleClaimed.push(record);
1202
- }
1203
- else {
1204
- // Left queued — see the doc above for why this must not be
1205
- // deleted. Reported once per claim attempt; a genuinely
1206
- // abandoned origin will keep surfacing here, which is the
1207
- // intended, safer trade-off over silent, permanent loss.
1208
- droppedOrphans.push(record);
1209
- }
1210
- continue;
1211
- }
1212
- deferredToOwner.push(record);
1213
- }
1214
- return { claimed, staleClaimed, deferredToOwner, droppedOrphans };
1215
- }
1216
- /** Return claimed records that were never started by an aborted drain. */
1217
- requeueDeferredFormatFiles(records) {
1218
- for (const record of records) {
1219
- const key = path.resolve(record.filePath);
1220
- const existing = this._pendingDeferredMutations.get(key);
1221
- if (existing) {
1222
- for (const kind of record.kinds)
1223
- existing.kinds.add(kind);
1224
- for (const toolName of record.toolNames)
1225
- existing.toolNames.add(toolName);
1226
- continue;
1227
- }
1228
- this._pendingDeferredMutations.set(key, {
1229
- ...record,
1230
- kinds: new Set(record.kinds),
1231
- toolNames: new Set(record.toolNames),
1232
- });
1233
- }
1234
- }
1235
- claimDeferredMutations(currentSessionId, now, staleAfterMs, currentOriginCwd) {
1236
- return this.claimDeferredFormatFiles(currentSessionId, now, staleAfterMs, currentOriginCwd);
1237
- }
1238
- requeueDeferredMutations(records) {
1239
- this.requeueDeferredFormatFiles(records);
1240
- }
1241
- shouldWarmLspOnRead(filePath, maxAgeMs = 120_000) {
1242
- const state = this._lspReadWarmState.get(path.resolve(filePath));
1243
- if (!state)
1244
- return true;
1245
- if (state.status === "warming")
1246
- return false;
1247
- return Date.now() - state.ts > maxAgeMs;
1248
- }
1249
- markLspReadWarmStarted(filePath) {
1250
- this._lspReadWarmState.set(path.resolve(filePath), {
1251
- status: "warming",
1252
- ts: Date.now(),
1253
- });
1254
- }
1255
- markLspReadWarmCompleted(filePath) {
1256
- this._lspReadWarmState.set(path.resolve(filePath), {
1257
- status: "ready",
1258
- ts: Date.now(),
1259
- });
1260
- }
1261
- clearLspReadWarmState(filePath) {
1262
- this._lspReadWarmState.delete(path.resolve(filePath));
1263
- }
1264
- }
1265
- /**
1266
- * Read the live model identity off a pi extension context (#1655 item 2).
1267
- *
1268
- * `ExtensionContext.model` is `AgentSession.model`, projected through a lazy
1269
- * getter guarded by `assertActive()`
1270
- * (`@earendil-works/pi-coding-agent/dist/core/extensions/runner.js:488-491`;
1271
- * `dist/core/agent-session.js:580-582`). The value is a `Model` with `id` and
1272
- * `provider` (`@earendil-works/pi-ai/dist/types.d.ts:661-667`), or `undefined`
1273
- * when no model is selected.
1274
- *
1275
- * Because the getter is lazy and guarded, reading it on a REPLACED runner
1276
- * throws. Telemetry identity is advisory; a stale ctx must degrade to "no
1277
- * identity", never take down the event handler that happened to carry it.
1278
- */
1279
- export function readHostModelIdentity(ctx) {
1280
- try {
1281
- const model = ctx?.model;
1282
- return {
1283
- model: typeof model?.id === "string" ? model.id : undefined,
1284
- provider: typeof model?.provider === "string" ? model.provider : undefined,
1285
- };
1286
- }
1287
- catch {
1288
- return {};
1289
- }
1290
- }