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,2034 +0,0 @@
1
- import * as nodeCrypto from "node:crypto";
2
- import * as nodeFs from "node:fs";
3
- import * as path from "node:path";
4
- import { noteAuthoritativeContentAttachment } from "./agent-nudge.js";
5
- import { captureFileStats, diffFileContent, getOpaqueBaselineStore, recoverOpaqueChangesViaGit, } from "./opaque-mutation-scan.js";
6
- import { normalizeMapKey } from "./path-utils.js";
7
- import { detectFileKind } from "./file-kinds.js";
8
- import { extractReadPathsFromCommand, extractDeletedPathsFromCommand, extractGrepSearchReadsFromOutput, extractWrittenPathsFromCommand, tokenizeShellCommand, } from "./bash-file-access.js";
9
- import { registerSearchReads, } from "./search-read-registration.js";
10
- import { createFileTime } from "./file-time.js";
11
- import { publishFormatQueued } from "./format-events-publish.js";
12
- import { invalidateProjectIgnoreMatcherForPath, isPathIgnoredByProject, } from "./file-utils.js";
13
- import { invalidateFormatterCacheForPath } from "./formatters.js";
14
- import { getFormatService } from "./format-service.js";
15
- import { isExternalOrVendorFile, normalizeEphemeralMapKey, pathsEqual, } from "./path-utils.js";
16
- import { PathKeyedMap } from "./path-keyed-map.js";
17
- import { resolveLanguageRootForFile } from "./language-profile.js";
18
- import { logLatency } from "./latency-logger.js";
19
- import { classifyMutatingTool, PI_LENS_SYNTHETIC_MUTATION_FIELD, } from "./mutating-tool.js";
20
- import { hasPendingObservation, noteMutationHandled, settleObservedMutation, } from "./observed-mutation.js";
21
- import { replayThroughMutationBridge, storedLineHashesFor, } from "./observed-mutation-sources.js";
22
- import { getAmbientAbortSignal } from "./safe-spawn.js";
23
- import { resolveToolCallCorrelationId } from "./tool-event.js";
24
- import { boundedIndexesForCount, createReadGuardEditBatchSummary, getReadGuardCorrelationId, logReadGuardEvent, } from "./read-guard-logger.js";
25
- import { countFileLines } from "./read-guard-tool-lines.js";
26
- import { notifyExternalFileChange, resyncGitChangedFiles, } from "./lsp/index.js";
27
- import { runPipeline } from "./pipeline.js";
28
- import { renderPostAutofixNotice, } from "./post-autofix-notice.js";
29
- import { syncGitGuardRecord } from "./git-guard.js";
30
- import { scheduleWordIndexPersist } from "./word-index.js";
31
- import { RUNTIME_CONFIG } from "./runtime-config.js";
32
- import { getActiveSessionId } from "./session-lifecycle.js";
33
- import { requestBootstrapClients } from "./bootstrap.js";
34
- import { bounded } from "./deadline-utils.js";
35
- import { HOOK_WALL_BUDGET_MS } from "./hook-budgets.js";
36
- import { incrementDegradationCount, recordDegradationOnce, } from "./degradation-ledger.js";
37
- const AUTHORITATIVE_CONTENT_MAX_BYTES = RUNTIME_CONFIG.pipeline.lspMaxFileBytes;
38
- // Keep same-turn analysis below the observed-directory capture bound so one
39
- // opaque codemod cannot monopolize the hook or analyzer fleet.
40
- const OBSERVED_DISPATCH_MAX_PATHS = 32;
41
- /**
42
- * Git subcommands that import ANOTHER commit's content into the index. The
43
- * whole family, with a verdict for each (#2060):
44
- * - merge, rebase, cherry-pick, pull, revert, am: IN. Each stages the other
45
- * side's clean files beside the unmerged ones. `pull` is fetch+merge and
46
- * `am --3way` reaches the same unmerged state, both probed on git 2.55.
47
- * - stash pop / stash apply: OUT. A conflicted pop leaves `M ` entries too,
48
- * but that content is the agent's OWN stashed work. Excluding it would
49
- * destroy exactly what opaque recovery exists to capture.
50
- * - checkout -m: OUT. Its "incoming" side is the agent's local modifications
51
- * carried across the switch, so the same reasoning applies.
52
- * - apply -3 / --3way: OUT. The patch is normally one the agent wrote, and
53
- * `apply` is far more often used without conflicts, so the narrower default
54
- * is to keep capturing.
55
- * Membership only ARMS the filter; it still needs a real unmerged entry to do
56
- * anything, so a non-integration use of a listed subcommand is inert.
57
- */
58
- const GIT_INTEGRATION_SUBCOMMANDS = new Set([
59
- "merge",
60
- "rebase",
61
- "cherry-pick",
62
- "pull",
63
- "revert",
64
- "am",
65
- ]);
66
- const GIT_GLOBAL_OPTIONS_WITH_VALUE = new Set([
67
- "-C",
68
- "-c",
69
- "--config-env",
70
- "--git-dir",
71
- "--namespace",
72
- "--work-tree",
73
- ]);
74
- /**
75
- * Failed integration commands are the one opaque-recovery case where Git's
76
- * index contains changes made by the other branch rather than the agent.
77
- * Keep this narrow: ordinary scripts and successful Git operations retain the
78
- * normal recovery contract.
79
- */
80
- export function isFailedGitIntegrationCommand(command, isError) {
81
- if (isError !== true)
82
- return false;
83
- return tokenizeShellCommand(command).some(({ tokens, unsupported }) => {
84
- if (unsupported)
85
- return false;
86
- const executable = path.win32
87
- .basename(tokens[0] ?? "")
88
- .toLowerCase()
89
- .replace(/\.(?:cmd|exe)$/, "");
90
- if (executable !== "git")
91
- return false;
92
- for (let index = 1; index < tokens.length; index += 1) {
93
- const token = tokens[index] ?? "";
94
- if (GIT_GLOBAL_OPTIONS_WITH_VALUE.has(token)) {
95
- index += 1;
96
- continue;
97
- }
98
- if (token.startsWith("-"))
99
- continue;
100
- return GIT_INTEGRATION_SUBCOMMANDS.has(token);
101
- }
102
- return false;
103
- });
104
- }
105
- function ensureToolResultClients(deps) {
106
- if (deps.biomeClient && deps.ruffClient && deps.metricsClient)
107
- return true;
108
- const request = {
109
- reason: "tool-result-analysis",
110
- hook: "tool_result_edit",
111
- timeoutMs: HOOK_WALL_BUDGET_MS.tool_result_edit,
112
- ...(deps.signal === undefined ? {} : { signal: deps.signal }),
113
- };
114
- return bounded(requestBootstrapClients(request), {
115
- ms: HOOK_WALL_BUDGET_MS.tool_result_edit,
116
- signal: deps.signal,
117
- hook: "tool_result_edit",
118
- label: "tool-result-bootstrap-demand",
119
- }).then((clients) => {
120
- if (!clients)
121
- return false;
122
- deps.biomeClient = clients.biomeClient;
123
- deps.ruffClient = clients.ruffClient;
124
- deps.metricsClient = clients.metricsClient;
125
- return true;
126
- });
127
- }
128
- function parseDiffRanges(diff) {
129
- const changedLines = [];
130
- for (const line of diff.split("\n")) {
131
- const match = line.match(/^[+-]\s*(\d+)\s/);
132
- if (match) {
133
- changedLines.push(Number.parseInt(match[1], 10));
134
- }
135
- }
136
- if (changedLines.length === 0)
137
- return [];
138
- const sorted = [...new Set(changedLines)].sort((a, b) => a - b);
139
- const ranges = [];
140
- let rangeStart = sorted[0];
141
- let rangeEnd = sorted[0];
142
- for (const line of sorted.slice(1)) {
143
- if (line <= rangeEnd + 1) {
144
- rangeEnd = line;
145
- }
146
- else {
147
- ranges.push({ start: rangeStart, end: rangeEnd });
148
- rangeStart = line;
149
- rangeEnd = line;
150
- }
151
- }
152
- ranges.push({ start: rangeStart, end: rangeEnd });
153
- return ranges;
154
- }
155
- // Keyed by (normalized) filePath, then by the raw stateHash — the path portion
156
- // needs normalizing (divergent Windows spellings must collapse to one entry),
157
- // the stateHash suffix must NOT be folded into the path key (a real content
158
- // change for the same file has to stay a distinct entry). A flat
159
- // `PathKeyedMap<InFlightPipeline>` keyed by a composite `${filePath}:${hash}`
160
- // string can't express that split cleanly (the normalizer only sees the whole
161
- // composite string, so it can't fold the path half without also mangling the
162
- // hash half); nesting keeps each axis normalized/compared with its own rules.
163
- const inFlightPipelines = new PathKeyedMap(normalizeEphemeralMapKey);
164
- const lastAnalyzedStateByFile = new PathKeyedMap(normalizeEphemeralMapKey);
165
- // Called at turn_start — entries from the previous turn can never match the new
166
- // turnIndex so they're dead weight. Clearing here keeps the map bounded to the
167
- // files touched in the current turn only (typically < 20).
168
- export function clearLastAnalyzedStateCache() {
169
- lastAnalyzedStateByFile.clear();
170
- }
171
- /**
172
- * Register one in-flight pipeline and hand back the inner map it landed in.
173
- *
174
- * Paired with {@link releaseInFlightPipeline}; split out of
175
- * `dispatchPipelineAnalysis` so registration and deregistration are one seam
176
- * with one owner (#2464 review round 3, F1) rather than two open-coded blocks
177
- * ~80 lines apart whose invariants only line up if a reader checks both.
178
- *
179
- * Kept private because both dispatch call sites now use the shared claim before
180
- * registration; publishing this seam without the claim obligation would make
181
- * the identity guard's precondition easy to violate again.
182
- */
183
- function registerInFlightPipeline(filePath, stateHash, pipeline) {
184
- let filePipelines = inFlightPipelines.get(filePath);
185
- if (!filePipelines) {
186
- filePipelines = new Map();
187
- inFlightPipelines.set(filePath, filePipelines);
188
- }
189
- filePipelines.set(stateHash, pipeline);
190
- return filePipelines;
191
- }
192
- /**
193
- * Release one in-flight pipeline, pruning the per-file inner map once it is
194
- * empty so a file touched once this session doesn't leave a permanent empty
195
- * entry in the outer map.
196
- *
197
- * The IDENTITY check on the outer delete is load-bearing (#2464 review round 3,
198
- * F1). `registered` is a reference captured BEFORE the pipeline await. Deleting
199
- * by path alone assumes the outer entry still IS that map, and when it is not —
200
- * anything that replaced it while this pipeline ran — the delete evicts a LIVE,
201
- * unrelated pipeline's registration: its concurrent duplicates then stop
202
- * deduping and its `participantIds`/`participantTotal` under-count. Delete only
203
- * when the outer map still points at the very map this registration went into.
204
- */
205
- function releaseInFlightPipeline(filePath, stateHash, registered) {
206
- registered.delete(stateHash);
207
- if (registered.size === 0 && inFlightPipelines.get(filePath) === registered) {
208
- inFlightPipelines.delete(filePath);
209
- }
210
- }
211
- /**
212
- * The two pre-conditions EVERY pipeline dispatch shares (#2464 review round 3,
213
- * F1): the in-flight dedup for a concurrent call on the same post-write state,
214
- * and the already-analysed latch for a sequential duplicate in the same turn.
215
- *
216
- * Both call sites of {@link dispatchPipelineAnalysis} consult this, so the
217
- * PRE-conditions are as by-construction as the post-conditions that helper
218
- * already owns. The observed-mutation path shipped without either check in
219
- * round 2: two concurrent observed `tool_result`s for one file+hash both
220
- * registered, the second overwrote the first's entry in the per-file map, and
221
- * the first's release then evicted the whole outer entry — taking a live,
222
- * unrelated classified pipeline's registration with it.
223
- *
224
- * ## Why this is SYNCHRONOUS and hands the join promise back
225
- *
226
- * Check-then-act here has to be atomic against the microtask queue.
227
- * `dispatchPipelineAnalysis` registers synchronously before its own first
228
- * await, so a caller that claims and then dispatches with no `await` in between
229
- * cannot be interleaved. An `async` pre-check would reintroduce exactly that
230
- * interleave — both racers see an empty registry, both resume, both dispatch —
231
- * so the join's `await` is deliberately left to the caller.
232
- *
233
- * ## Why this is NOT folded into `dispatchPipelineAnalysis`
234
- *
235
- * On the classified chain the latch check sits ABOVE `addModifiedRange` and
236
- * `recordProjectChange`. Moving it down into the helper would write
237
- * `turn-state.json` ranges and an attributed change-log receipt for a state
238
- * already analysed this turn — the duplicate-recording inversion #2464 exists
239
- * to remove.
240
- */
241
- function claimPipelineDispatch(args) {
242
- const { filePath, stateHash, turnIndex, participantId, dbg } = args;
243
- // Deduplicate concurrent calls for the same final file state (pi can fire one
244
- // tool_result per edit hunk). Do not dedupe by file alone: a distinct later
245
- // same-turn edit to this file must still be analyzed.
246
- const inFlight = inFlightPipelines.get(filePath)?.get(stateHash);
247
- if (inFlight) {
248
- dbg(`tool_result: skipping duplicate concurrent state for ${filePath}`);
249
- if (inFlight.participantIds.length < 100) {
250
- inFlight.participantIds.push(participantId);
251
- }
252
- inFlight.participantTotal += 1;
253
- return { proceed: false, joined: inFlight.promise };
254
- }
255
- // Deduplicate sequential duplicate events for the same post-write state in
256
- // the same turn while allowing later same-file edits whose content changed.
257
- const lastAnalyzed = lastAnalyzedStateByFile.get(filePath);
258
- if (lastAnalyzed?.turnIndex === turnIndex &&
259
- lastAnalyzed.stateHash === stateHash) {
260
- dbg(`tool_result: skipping already-analyzed file state this turn for ${filePath}`);
261
- return { proceed: false, joined: undefined };
262
- }
263
- return { proceed: true };
264
- }
265
- const debouncedPipelines = new PathKeyedMap(normalizeEphemeralMapKey);
266
- const DEFAULT_DEBOUNCE_MS = 0;
267
- const MAX_DEBOUNCE_MS = 1000;
268
- function getDebounceMs() {
269
- const raw = Number(process.env.PI_LENS_TOOL_RESULT_DEBOUNCE_MS);
270
- if (!Number.isFinite(raw) || raw < 0)
271
- return DEFAULT_DEBOUNCE_MS;
272
- // Cap at 1s so turn_end and agent_end don't block on the timer for
273
- // pathologically long windows. flushDebouncedToolResults below also
274
- // short-circuits at boundary events.
275
- return Math.min(raw, MAX_DEBOUNCE_MS);
276
- }
277
- /**
278
- * Drain any pending debounced tool_result pipelines immediately, awaiting their
279
- * completion. Call from turn_end / agent_end before reading anything that depends
280
- * on the pipeline's bookkeeping (project change log, modified ranges, etc.).
281
- *
282
- * Passing a filePath flushes only that entry; omitting it flushes all.
283
- */
284
- export async function flushDebouncedToolResults(filePath) {
285
- const entries = filePath
286
- ? debouncedPipelines.has(filePath)
287
- ? [
288
- [
289
- filePath,
290
- debouncedPipelines.get(filePath),
291
- ],
292
- ]
293
- : []
294
- : [...debouncedPipelines.entries()];
295
- for (const [key, entry] of entries) {
296
- clearTimeout(entry.timer);
297
- debouncedPipelines.delete(key);
298
- // Re-enter the pipeline synchronously via the bypass flag so the
299
- // timer body's resolve/reject still fires through the shared promise.
300
- handleToolResult({ ...entry.latestDeps, _bypassDebounce: true }).then(entry.resolve, entry.reject);
301
- }
302
- if (entries.length > 0) {
303
- // Allow microtasks to settle so awaiting callers see the latest state.
304
- await Promise.all(entries.map(([, entry]) => entry.promise.catch(() => undefined)));
305
- }
306
- }
307
- function scheduleDebounced(filePath, debounceMs, deps) {
308
- const existing = debouncedPipelines.get(filePath);
309
- if (existing) {
310
- clearTimeout(existing.timer);
311
- const incomingId = deps._telemetryParticipantIds?.[0] ??
312
- getReadGuardCorrelationId(deps.event);
313
- const priorIds = existing.latestDeps._telemetryParticipantIds ?? [];
314
- existing.latestDeps = {
315
- ...deps,
316
- _telemetryParticipantIds: [...priorIds, incomingId].slice(0, 100),
317
- _telemetryParticipantTotal: (existing.latestDeps._telemetryParticipantTotal ?? priorIds.length) + 1,
318
- };
319
- existing.coalescedCount += 1;
320
- existing.timer = setTimeout(() => {
321
- debouncedPipelines.delete(filePath);
322
- deps.dbg(`tool_result: debounce fired after ${existing.coalescedCount} coalesced calls for ${filePath}`);
323
- handleToolResult({ ...existing.latestDeps, _bypassDebounce: true }).then(existing.resolve, existing.reject);
324
- }, debounceMs);
325
- deps.dbg(`tool_result: coalesced into pending debounce for ${filePath} (count=${existing.coalescedCount})`);
326
- return existing.promise;
327
- }
328
- let resolveFn;
329
- let rejectFn;
330
- const promise = new Promise((res, rej) => {
331
- resolveFn = res;
332
- rejectFn = rej;
333
- });
334
- const initialParticipantIds = deps._telemetryParticipantIds ?? [
335
- getReadGuardCorrelationId(deps.event),
336
- ];
337
- const entry = {
338
- timer: setTimeout(() => {
339
- debouncedPipelines.delete(filePath);
340
- handleToolResult({ ...entry.latestDeps, _bypassDebounce: true }).then(entry.resolve, entry.reject);
341
- }, debounceMs),
342
- promise,
343
- resolve: resolveFn,
344
- reject: rejectFn,
345
- latestDeps: {
346
- ...deps,
347
- _telemetryParticipantIds: initialParticipantIds.slice(0, 100),
348
- _telemetryParticipantTotal: deps._telemetryParticipantTotal ?? initialParticipantIds.length,
349
- },
350
- scheduledAt: Date.now(),
351
- coalescedCount: 1,
352
- };
353
- debouncedPipelines.set(filePath, entry);
354
- return promise;
355
- }
356
- function getFileStateHash(filePath) {
357
- try {
358
- const content = nodeFs.readFileSync(filePath);
359
- return nodeCrypto.createHash("sha256").update(content).digest("hex");
360
- }
361
- catch (err) {
362
- const code = err.code ?? "unknown";
363
- return `unreadable:${code}`;
364
- }
365
- }
366
- function getRequestedEditCount(event, kind) {
367
- if (kind === "write")
368
- return 1;
369
- const edits = event.input?.edits;
370
- return Array.isArray(edits) && edits.length > 0 ? edits.length : 1;
371
- }
372
- function getRequestedEditIndexes(event, kind) {
373
- return boundedIndexesForCount(getRequestedEditCount(event, kind));
374
- }
375
- /**
376
- * Change-log attribution for one classified mutation (#2423).
377
- *
378
- * A third-party tool gets its OWN source (`agent-tool:<name>`) rather than
379
- * being folded into `agent-edit`: a report that attributes a change to "the
380
- * model's edit tool" must not silently absorb an extension's rewrite.
381
- */
382
- function sourceForMutation(classification, details) {
383
- if (details
384
- ?.piLensPartialApply) {
385
- return "partial-apply";
386
- }
387
- if (classification.provenance === "builtin" ||
388
- classification.provenance === "bash-derived") {
389
- return classification.kind === "write" ? "agent-write" : "agent-edit";
390
- }
391
- return `agent-tool:${classification.toolName}`;
392
- }
393
- function singleRange(ranges) {
394
- return ranges?.length === 1 ? ranges[0] : undefined;
395
- }
396
- function recordProjectChange(args) {
397
- // One mutation seam (#2000 phase 1): bump + receipt + change-log live in
398
- // RuntimeCoordinator.recordProjectMutation; this wrapper only carries the
399
- // legacy dbg shape.
400
- args.runtime.recordProjectMutation?.({
401
- filePath: args.filePath,
402
- source: args.source,
403
- cwd: args.cwd,
404
- changedRange: args.changedRange,
405
- onAppendError: (err) => args.dbg(`project change log append failed for ${args.filePath}: ${err}`),
406
- });
407
- }
408
- /**
409
- * #2402 applied-edit records for a native edit tool, so an identical retry is
410
- * recognized as already-applied instead of escalating through the
411
- * oldText-not-found ladder. `input` carries the EXECUTED args (post-autopatch),
412
- * the same text the preflight resolves against.
413
- *
414
- * Extracted (#2449 review round 4, S4) because the observational-settle skip
415
- * path needs the IDENTICAL records: the mutation bridge does not write them, so
416
- * an early return that skipped this block left every retry of an observed
417
- * tool's edit looking unapplied. One body, two call sites — a second copy on the
418
- * skip path is the drift this repo keeps catching.
419
- */
420
- function recordNativeAppliedPairs(args) {
421
- const pairs = [];
422
- if (args.kind !== "edit")
423
- return pairs;
424
- const appliedInput = args.input;
425
- const record = (oldText, newText) => {
426
- if (typeof oldText === "string" && oldText.length > 0) {
427
- args.runtime.partialApplyRecords.record(args.filePath, oldText, newText, args.stateHash);
428
- pairs.push({ oldText, newText });
429
- }
430
- };
431
- if (Array.isArray(appliedInput.edits)) {
432
- for (const edit of appliedInput.edits)
433
- record(edit.oldText, edit.newText);
434
- }
435
- else {
436
- record(appliedInput.oldText, appliedInput.newText);
437
- }
438
- return pairs;
439
- }
440
- /**
441
- * Keep `cachedExports` in sync after each write/edit so the pre-write STOP check
442
- * does not fire on names that were removed from this file this session.
443
- *
444
- * Extracted for the same reason as {@link recordNativeAppliedPairs} (#2449
445
- * review round 4, S4): the mutation bridge does not touch this cache, so the
446
- * observational-settle skip path left it holding names an observed tool had
447
- * just deleted.
448
- */
449
- function refreshCachedExports(runtime, filePath) {
450
- if (runtime.cachedExports.size === 0 || !nodeFs.existsSync(filePath))
451
- return;
452
- const exportRe = new RegExp("export\\s+(?:async\\s+)?(?:function|class|const|let|type|interface)\\s+(\\w+)", "g");
453
- for (const [name, file] of runtime.cachedExports) {
454
- if (path.resolve(file) === path.resolve(filePath)) {
455
- runtime.cachedExports.delete(name);
456
- }
457
- }
458
- try {
459
- const freshContent = nodeFs.readFileSync(filePath, "utf-8");
460
- for (const match of freshContent.matchAll(exportRe)) {
461
- const name = match[1];
462
- if (!runtime.cachedExports.has(name)) {
463
- runtime.cachedExports.set(name, filePath);
464
- }
465
- }
466
- }
467
- catch {
468
- // Non-fatal — stale entry is worse than a missing one
469
- }
470
- }
471
- /**
472
- * #2464: the pipeline's own lint/diagnostics dispatch, factored out of the
473
- * block below that ALSO writes `turn-state.json` modified ranges and the
474
- * attributed change-log receipt (`cacheManager.addModifiedRange` /
475
- * `recordProjectChange`). The classified chain in `handleToolResult` still
476
- * does both, in the same order as before this split — see the call site
477
- * right after `recordProjectChange` below, which is byte-identical to what
478
- * used to be inlined there.
479
- *
480
- * The observed-mutation early return (#2430/#2449 round 4, S4) is the SECOND
481
- * caller: the mutation bridge already recorded the turn-state range and the
482
- * change-log receipt for that edit, so it calls this helper for analysis
483
- * WITHOUT asking for the recording a second time — which a shared "run the
484
- * pipeline AND record" block could not express.
485
- */
486
- async function dispatchPipelineAnalysis(args) {
487
- const { deps, runtime, filePath, dispatchCwd, turnStateCwd, autofixMode, modifiedRanges, writeIndex, initialStateHash, readGuardCorrelationId, requestedEditIndexes, requestedEditTotal, isPartialApplyResult, toolResultStart, nativeAppliedPairs, allowReadGuardWrites, } = args;
488
- const { event, getFlag, getFlagSource, dbg, biomeClient, ruffClient, metricsClient, resetLSPService, } = deps;
489
- const pipelinePromise = runPipeline({
490
- signal: deps.signal,
491
- filePath,
492
- cwd: dispatchCwd,
493
- projectRoot: turnStateCwd,
494
- toolName: event.toolName,
495
- autofixMode,
496
- modifiedRanges,
497
- telemetry: {
498
- model: runtime.telemetryModel,
499
- sessionId: runtime.telemetrySessionId,
500
- turnIndex: runtime.turnIndex,
501
- writeIndex,
502
- modelId: runtime.telemetryModelId,
503
- provider: runtime.telemetryProviderId,
504
- },
505
- getFlag,
506
- getFlagSource,
507
- dbg,
508
- // #451: hand the deferred cascade live sequence accessors so the
509
- // review-graph builder can skip its per-build O(project) sweep when
510
- // only pi-observed edits happened. projectSeq is a function because the
511
- // cascade runs after this returns (#450) — read current, not captured.
512
- seqState: {
513
- projectSeq: () => runtime.projectSeq,
514
- getFilesChangedSince: (seq) => runtime.getFilesChangedSince(seq),
515
- },
516
- // The settle clock is live because the deferred cascade may reach its
517
- // budget derivation before or after turn_end starts waiting.
518
- turnEndCascadeSettleStart: () => runtime.getTurnEndCascadeSettleStart(),
519
- // #348 phase 2: live reference so the deferred cascade can update the
520
- // warm word index in place at the same seam as the graph rebuild.
521
- // `runtime.wordIndex` is read fresh (not captured) via this closure-free
522
- // property access being re-evaluated at object-literal construction
523
- // time here — that's fine because runPipeline reads `ctx.wordIndex`
524
- // synchronously into computeCascadeForFile's options before returning
525
- // (the deferred part is the cascade's OWN execution, not this handoff).
526
- wordIndex: runtime.wordIndex,
527
- onWordIndexUpdated: (index) => {
528
- scheduleWordIndexPersist(dispatchCwd, index, dbg);
529
- },
530
- }, {
531
- biomeClient: biomeClient,
532
- ruffClient: ruffClient,
533
- metricsClient: metricsClient,
534
- getFormatService,
535
- fixedThisTurn: runtime.fixedThisTurn,
536
- });
537
- const pipelineTelemetry = {
538
- promise: pipelinePromise,
539
- participantIds: [...new Set(args.participantIds)].slice(0, 100),
540
- participantTotal: args.participantTotal,
541
- };
542
- // Synchronous, and the FIRST thing after `runPipeline` handed back its
543
- // promise: `claimPipelineDispatch` at each call site is only atomic because
544
- // nothing awaits between the claim and this registration.
545
- const registeredPipelines = registerInFlightPipeline(filePath, initialStateHash, pipelineTelemetry);
546
- let result;
547
- try {
548
- result = await pipelinePromise;
549
- }
550
- catch (pipelineErr) {
551
- if (getFlag("lens-guard")) {
552
- runtime.markGitGuardCacheUnknown("pipeline_crash");
553
- }
554
- dbg(`runPipeline crashed: ${pipelineErr}`);
555
- logReadGuardEvent({
556
- event: "edit_post_edit_pipeline_failed",
557
- correlationId: readGuardCorrelationId,
558
- filePath,
559
- metadata: {
560
- tool: event.toolName,
561
- commitStatus: "committed",
562
- reasonCode: "pipeline_failed",
563
- },
564
- });
565
- logReadGuardEvent({
566
- event: "edit_batch_summary",
567
- correlationId: readGuardCorrelationId,
568
- filePath,
569
- metadata: {
570
- tool: event.toolName,
571
- editBatchSummary: createReadGuardEditBatchSummary({
572
- requestedIndexes: requestedEditIndexes,
573
- requestedTotal: requestedEditTotal,
574
- resolvedIndexes: requestedEditIndexes,
575
- resolvedTotal: requestedEditTotal,
576
- appliedIndexes: requestedEditIndexes,
577
- appliedTotal: requestedEditTotal,
578
- participantIds: pipelineTelemetry.participantIds,
579
- participantTotal: pipelineTelemetry.participantTotal,
580
- commitStatus: "committed",
581
- postEditStatus: "failed",
582
- terminalStatus: "failed",
583
- durationMs: Date.now() - toolResultStart,
584
- }),
585
- },
586
- });
587
- dbg(`runPipeline crash stack: ${pipelineErr.stack}`);
588
- // The LSP fleet is process-wide, but a pipeline crash belongs to one
589
- // evaluation. A registered primary owns the fleet; a known secondary
590
- // must not tear it down. Keep the historical reset when no registration
591
- // exists because synthetic callers and early startup have no role evidence.
592
- const activePrimarySessionId = getActiveSessionId();
593
- const crashBelongsToPrimary = activePrimarySessionId === undefined ||
594
- activePrimarySessionId === runtime.telemetrySessionId;
595
- if (!getFlag("no-lsp") && crashBelongsToPrimary) {
596
- resetLSPService({ fast: true, reason: "pipeline_crash" });
597
- }
598
- logLatency({
599
- type: "tool_result",
600
- toolName: event.toolName,
601
- filePath,
602
- durationMs: Date.now() - toolResultStart,
603
- result: "pipeline_crash",
604
- });
605
- const notice = runtime.formatPipelineCrashNotice(filePath, pipelineErr);
606
- return {
607
- crashed: true,
608
- response: {
609
- content: notice
610
- ? [...event.content, { type: "text", text: notice }]
611
- : event.content,
612
- isError: true,
613
- },
614
- };
615
- }
616
- finally {
617
- releaseInFlightPipeline(filePath, initialStateHash, registeredPipelines);
618
- }
619
- if (!isPartialApplyResult) {
620
- const postEditStatus = result.isError ? "failed" : "succeeded";
621
- if (result.isError) {
622
- logReadGuardEvent({
623
- event: "edit_post_edit_pipeline_failed",
624
- correlationId: readGuardCorrelationId,
625
- filePath,
626
- metadata: {
627
- tool: event.toolName,
628
- commitStatus: "committed",
629
- reasonCode: "pipeline_failed",
630
- },
631
- });
632
- }
633
- logReadGuardEvent({
634
- event: "edit_batch_summary",
635
- correlationId: readGuardCorrelationId,
636
- filePath,
637
- metadata: {
638
- tool: event.toolName,
639
- editBatchSummary: createReadGuardEditBatchSummary({
640
- requestedIndexes: requestedEditIndexes,
641
- requestedTotal: requestedEditTotal,
642
- resolvedIndexes: requestedEditIndexes,
643
- resolvedTotal: requestedEditTotal,
644
- appliedIndexes: requestedEditIndexes,
645
- appliedTotal: requestedEditTotal,
646
- participantIds: pipelineTelemetry.participantIds,
647
- participantTotal: pipelineTelemetry.participantTotal,
648
- commitStatus: "committed",
649
- postEditStatus,
650
- terminalStatus: postEditStatus === "failed" ? "failed" : "success",
651
- durationMs: Date.now() - toolResultStart,
652
- }),
653
- },
654
- });
655
- }
656
- // ── Post-pipeline post-conditions (#2464 review round 2, S1) ───────────────
657
- // These live INSIDE the helper rather than at its call sites so EVERY
658
- // provenance gets them by construction. The observed path used to discard
659
- // `result` entirely, so under `--immediate-format` the pipeline rewrote the
660
- // file and none of the three below ran: the next edit was then blocked with
661
- // a spurious `file_modified` (the read-guard staleness stamp was never
662
- // re-taken), an identical retry escalated through the oldText-not-found
663
- // ladder (the #2402 after-write hash was never stamped), and a duplicate
664
- // tool_result for the same bytes analysed the file a second time (the
665
- // already-analysed latch was never set).
666
- // The latch identifies the bytes this pipeline actually analysed. A pipeline
667
- // that reports no write analysed its input state, even if another writer
668
- // changed disk while the await was parked. A pipeline-reported write selects
669
- // only the identity captured by runPipeline before analysis awaits (#2499).
670
- const pipelineOwnedWriteHash = result.fileModified
671
- ? result.postWriteStateHash
672
- : undefined;
673
- const finalStateHash = pipelineOwnedWriteHash ?? initialStateHash;
674
- if (!result.fileModified || pipelineOwnedWriteHash !== undefined) {
675
- lastAnalyzedStateByFile.set(filePath, {
676
- turnIndex: runtime.turnIndex,
677
- stateHash: finalStateHash,
678
- });
679
- }
680
- // #2402: pi-lens' own immediate format/autofix may have rewritten the file
681
- // after the native edit was recorded by the caller. Stamp the post-pipeline
682
- // state so an identical retry against the formatted bytes is still
683
- // recognized as already-applied. Only the pairs recorded this invocation are
684
- // stamped, and only when the pipeline actually changed the bytes.
685
- // `initialStateHash` IS the post-write hash at both call sites — the
686
- // classified chain passes `postWriteStateHash` verbatim, the observed path
687
- // passes the same pre-settle digest.
688
- if (pipelineOwnedWriteHash !== undefined) {
689
- for (const pair of nativeAppliedPairs) {
690
- runtime.partialApplyRecords.noteAfterWriteHash(filePath, pair.oldText, pair.newText, finalStateHash);
691
- }
692
- }
693
- // The model's write/edit and pi-lens' own immediate format/autofix are now
694
- // reflected on disk. Refresh read-guard staleness stamps so a follow-up edit
695
- // is judged by read-range coverage, not by our own previous write.
696
- if (!getFlag("no-read-guard") && allowReadGuardWrites) {
697
- const changedForReadGuard = new Set([
698
- path.resolve(filePath),
699
- ...(result.changedFiles ?? []).map((changedFile) => path.resolve(changedFile)),
700
- ]);
701
- for (const changedFile of changedForReadGuard) {
702
- if (nodeFs.existsSync(changedFile)) {
703
- deps.readGuard?.recordWritten(changedFile);
704
- }
705
- }
706
- }
707
- return { crashed: false, result };
708
- }
709
- export async function handleToolResult(deps) {
710
- const { event, getFlag, dbg, runtime, cacheManager, agentBehaviorRecord, formatBehaviorWarnings, } = deps;
711
- const rawFilePath = event.input.path;
712
- const workspaceRoot = runtime.projectRoot || process.cwd();
713
- let bashAuthorshipConfirmed = deps._readGuardAuthorship ?? event.toolName !== "bash";
714
- // #1642: a gitignored worktree edit got re-attributed onto a
715
- // same-relative-path file in the parent checkout because this handler
716
- // used to always resolve a relative path against `workspaceRoot`
717
- // (`runtime.projectRoot`), with no idea the call actually ran under a
718
- // different cwd/worktree.
719
- //
720
- // Source-level correction (pi host audit, earendil-works/pi): tool_call's
721
- // own resolved path is NOT authoritative for what executed —
722
- // `agent-session.ts:914-919`'s extension-handler contract lets a LATER
723
- // `tool_call` handler mutate `event.input` in place with no
724
- // re-validation, and edit's `prepareArguments` rewrites args before the
725
- // event fires at all. `tool_result.input`, by contrast, is populated
726
- // from the EXECUTED args (`agent-session.ts:502-516`) — it is the
727
- // authoritative path source. So the correlation record's job is narrower
728
- // than "the path": it is the RESOLUTION BASIS (the cwd/worktree the call
729
- // actually ran under). Every tool_result resolves ITS OWN authoritative
730
- // `rawFilePath` against that basis, rather than trusting a call-time path
731
- // that a later handler may have superseded.
732
- const toolCallId = resolveToolCallCorrelationId(event);
733
- const attribution = toolCallId !== undefined
734
- ? runtime.takeToolCallAttribution(toolCallId)
735
- : undefined;
736
- let resolutionBasis;
737
- if (attribution) {
738
- resolutionBasis = attribution.originCwd;
739
- }
740
- else if (toolCallId !== undefined &&
741
- rawFilePath &&
742
- !path.isAbsolute(rawFilePath)) {
743
- // A real correlation id existed (the host DOES support one) but no
744
- // attribution was recorded under it — evicted, cleared because the
745
- // call was blocked before it could execute, or simply never seen by
746
- // `handleToolCall`. A RELATIVE path here is ambiguous: we have no
747
- // idea which cwd it is relative to, and guessing `workspaceRoot` is
748
- // exactly the #1642 collapse. Fail CLOSED instead of guessing — no
749
- // turn state, no deferred work — and log it so a real incident is
750
- // countable rather than silently mis-attributed.
751
- const guessedPath = path.resolve(workspaceRoot, rawFilePath);
752
- // Existence is not execution evidence: a same-named file can exist in
753
- // the workspace while the tool ran in another cwd. Without the recorded
754
- // call target and origin cwd there is no comparison to make, so retain the
755
- // full record and fail closed.
756
- dbg(`path_attribution_missing: no recorded resolution basis for toolCallId=${toolCallId}, refusing relative path ${rawFilePath} (would have guessed ${guessedPath})`);
757
- logLatency({
758
- type: "phase",
759
- toolName: event.toolName,
760
- filePath: guessedPath,
761
- phase: "path_attribution_missing",
762
- durationMs: 0,
763
- metadata: { toolCallId, rawFilePath, guessedPath },
764
- });
765
- return;
766
- }
767
- else {
768
- // Either an ABSOLUTE path (bash-synthetic writes always pass one —
769
- // unambiguous regardless of any basis, see the bash-write dispatch
770
- // below) or a host that supplies NO correlation id at all under any
771
- // known field name. The latter cannot be correlated by identity full
772
- // stop; this is the SAME exposure every host had before this fix,
773
- // not a regression introduced by it.
774
- resolutionBasis = workspaceRoot;
775
- }
776
- const filePath = rawFilePath
777
- ? path.isAbsolute(rawFilePath)
778
- ? rawFilePath
779
- : path.resolve(resolutionBasis, rawFilePath)
780
- : rawFilePath;
781
- if (filePath) {
782
- invalidateProjectIgnoreMatcherForPath(filePath);
783
- invalidateFormatterCacheForPath(filePath);
784
- }
785
- // Purely diagnostic: tool_call's call-time verdict (computed on ITS OWN
786
- // resolved path, which may since have been superseded) disagreed with
787
- // what actually executed. This does NOT gate anything by itself — the
788
- // ignore re-check below, running on the freshly & correctly resolved
789
- // `filePath`, is the real decision — but a divergence is exactly the
790
- // shape of the reported incident, so it is named legibly.
791
- if (attribution?.skipped &&
792
- filePath &&
793
- attribution.resolvedPath &&
794
- !pathsEqual(filePath, attribution.resolvedPath)) {
795
- const message = `path_attribution_refused: call target ${attribution.resolvedPath} (originCwd=${attribution.originCwd}) vs tool_result resolved ${filePath}`;
796
- dbg(message);
797
- logLatency({
798
- type: "phase",
799
- toolName: event.toolName,
800
- filePath,
801
- phase: "path_attribution_refused",
802
- durationMs: 0,
803
- metadata: {
804
- callTarget: attribution.resolvedPath,
805
- resolvedPath: filePath,
806
- originCwd: attribution.originCwd,
807
- },
808
- });
809
- }
810
- const behaviorWarnings = agentBehaviorRecord(event.toolName, filePath);
811
- const syntheticWriteContent = [];
812
- // #1590: one shared authoritative-content budget for every path this bash
813
- // command wrote. It is handed DOWN to each synthetic call so the single
814
- // attachment decision there sees both limits; nothing re-decides out here.
815
- const syntheticAttachmentBudget = {
816
- remaining: AUTHORITATIVE_CONTENT_MAX_BYTES,
817
- };
818
- // Bash writes (redirects, tee, sed -i, cp/mv, touch, git checkout/restore) —
819
- // these change file content but never go through the edit tool, so bash
820
- // early-returns before the dispatch pipeline below. For each in-project file
821
- // the command wrote/restored we therefore: (1) mark it authored-by-agent for
822
- // the read-guard (like the Write tool), and (2) re-run the pipeline via a
823
- // synthetic `write` event so its diagnostics, fileSeq, and change-log refresh.
824
- // Without (2) a `git checkout -- f` restore keeps serving the pre-restore
825
- // (e.g. broken-state) warnings on every later lens_diagnostics call.
826
- if (event.toolName === "bash" &&
827
- typeof event.input.command === "string") {
828
- const command = event.input.command;
829
- const recognized = extractWrittenPathsFromCommand(command, workspaceRoot);
830
- // The SURVIVING recognized set: what will actually dispatch. Failure
831
- // atomicity (#2000 invariant 5) means opaque recovery must subtract
832
- // THIS set, not raw recognized - otherwise a redirect target dropped
833
- // by the isError filter would be subtracted from recovery AND
834
- // excluded here, attributed nowhere.
835
- let recognizedWritten = event.isError !== true
836
- ? recognized.filter((wp) => !isExternalOrVendorFile(wp, workspaceRoot) &&
837
- !isPathIgnoredByProject(wp, workspaceRoot, false))
838
- : [];
839
- // Fence the mtime-based session-authored fallback before any async
840
- // observation. Only later content evidence may clear this fence.
841
- if (!getFlag("no-read-guard")) {
842
- for (const recognizedPath of recognizedWritten)
843
- deps.readGuard?.recordUnchanged?.(recognizedPath);
844
- }
845
- // #2000 phase 2: when the extractor recognizes NOTHING, the command is
846
- // opaque-candidate — recover its actual changed set by diffing the pre
847
- // snapshot taken at tool_call. Partial writes that landed before a
848
- // nonzero exit ARE attributed (the files changed and the agent authored
849
- // them) — a deliberate divergence from the isError filter above, which
850
- // exists for restore semantics where attribution would lie.
851
- let opaquePaths = [];
852
- let observedChangedKeys;
853
- let recognizedAuthored = [];
854
- // Recovery runs for EVERY bash command with a pending baseline - not
855
- // only recognized-empty ones. A mixed command (`python x.py > out.ts`
856
- // plus script-internal writes) previously skipped observation entirely
857
- // with zero telemetry; git-first recovery is cheap enough (~60ms) to
858
- // close that gap, subtracting already-recognized paths so nothing
859
- // double-dispatches.
860
- if (workspaceRoot && !getFlag("no-read-guard")) {
861
- const scanRoot = workspaceRoot;
862
- const started = Date.now();
863
- const pending = getOpaqueBaselineStore().take(`${normalizeMapKey(path.resolve(scanRoot))}:${runtime.sessionGeneration}`);
864
- let unknownReason;
865
- if (!pending && recognized.length > 0) {
866
- // Partial coverage without observation: the explicit verdict
867
- // invariant 1 demands (never silently imply no change).
868
- unknownReason = "partial-recognition-no-baseline";
869
- }
870
- else if (!pending) {
871
- unknownReason = "no-pending-snapshot";
872
- }
873
- else if (pending.strategy === "git") {
874
- // Git-first: no universe cap - works on any repo size.
875
- const recovery = await recoverOpaqueChangesViaGit(scanRoot, pending.startedAt, {
876
- excludeIndexOnlyWhenUnmerged: isFailedGitIntegrationCommand(command, event.isError),
877
- });
878
- if (recovery.verdict === "recovered") {
879
- opaquePaths = recovery.paths.filter((p) => !isExternalOrVendorFile(p, scanRoot) &&
880
- !isPathIgnoredByProject(p, scanRoot, false));
881
- observedChangedKeys = new Set(opaquePaths);
882
- }
883
- else if (recovery.verdict === "unknown") {
884
- // #2060: deliberately WIDER than the old `recognized.length > 0`
885
- // guard. A fully opaque command whose probe failed is the shape
886
- // whose coverage is least knowable, and it used to record
887
- // nothing at all.
888
- unknownReason = recovery.unknownReason;
889
- }
890
- else {
891
- // A clean git verdict is complete evidence that no path
892
- // changed; it is not missing evidence. Keep recognized writes
893
- // out of authorship because git found no changed bytes.
894
- observedChangedKeys = new Set();
895
- }
896
- // #2060: both counts are bounded (one record per tool_result, no
897
- // per-path logging) and exist because filtering is invisible in
898
- // production otherwise - the dropped paths simply never appear.
899
- if ((recovery.excludedIncomingCount ?? 0) > 0) {
900
- logLatency({
901
- type: "phase",
902
- phase: "opaque_mutation_incoming_excluded",
903
- filePath: command.slice(0, 80),
904
- durationMs: Date.now() - started,
905
- result: `excluded:${recovery.excludedIncomingCount}`,
906
- });
907
- }
908
- if ((recovery.unknownStatusCount ?? 0) > 0) {
909
- logLatency({
910
- type: "phase",
911
- phase: "opaque_mutation_status_pair_unknown",
912
- filePath: command.slice(0, 80),
913
- durationMs: Date.now() - started,
914
- result: `kept:${recovery.unknownStatusCount}`,
915
- });
916
- }
917
- }
918
- else if (pending.stats) {
919
- const outcome = await captureFileStats(scanRoot, {
920
- withHashes: true,
921
- ...deps._opaqueCaptureOptions,
922
- });
923
- if (outcome.snapshot && !outcome.unknownReason) {
924
- opaquePaths = diffFileContent(pending.stats, outcome.snapshot);
925
- observedChangedKeys = new Set(opaquePaths);
926
- }
927
- else {
928
- unknownReason =
929
- outcome.unknownReason ??
930
- pending.statsUnknownReason ??
931
- "walk-failed";
932
- }
933
- }
934
- else {
935
- unknownReason = pending.statsUnknownReason ?? "walk-failed";
936
- }
937
- if (opaquePaths.length > 0 && recognizedWritten.length > 0) {
938
- const survivingKeys = new Set(recognizedWritten.map((p) => normalizeMapKey(path.resolve(p))));
939
- opaquePaths = opaquePaths.filter((p) => !survivingKeys.has(p));
940
- }
941
- if (observedChangedKeys) {
942
- recognizedAuthored = recognizedWritten.filter((file) => observedChangedKeys.has(normalizeMapKey(path.resolve(file))));
943
- if (recognizedAuthored.length === 0)
944
- recognizedWritten = [];
945
- }
946
- else if (unknownReason) {
947
- recognizedAuthored = [];
948
- // The bounded opaque_mutation_coverage_unknown record below remains
949
- // the production proof that authorship evidence was unavailable.
950
- }
951
- if (unknownReason) {
952
- logLatency({
953
- type: "phase",
954
- phase: "opaque_mutation_coverage_unknown",
955
- filePath: command.slice(0, 80),
956
- durationMs: Date.now() - started,
957
- result: unknownReason,
958
- });
959
- }
960
- if (opaquePaths.length > 0) {
961
- logLatency({
962
- type: "phase",
963
- phase: "opaque_mutation_recovered",
964
- filePath: opaquePaths.slice(0, 5).join(","),
965
- durationMs: Date.now() - started,
966
- result: `changed:${opaquePaths.length}`,
967
- });
968
- void resyncGitChangedFiles(opaquePaths).catch((err) => {
969
- dbg(`git-change LSP resync failed: ${err}`);
970
- });
971
- }
972
- }
973
- // wp iterates opaquePaths VERBATIM (already normalizeMapKey keys), so the
974
- // set must hold those exact strings - no re-resolution.
975
- const opaqueSet = new Set(opaquePaths);
976
- const written = [...recognizedWritten, ...opaquePaths];
977
- const recognizedAuthoredSet = new Set(recognizedAuthored);
978
- bashAuthorshipConfirmed =
979
- recognizedAuthored.length > 0 || opaquePaths.length > 0;
980
- for (const wp of written) {
981
- if (!getFlag("no-read-guard") &&
982
- (opaqueSet.has(wp) || recognizedAuthoredSet.has(wp)))
983
- deps.readGuard?.recordWritten(wp);
984
- else if (!getFlag("no-read-guard") && recognizedWritten.includes(wp))
985
- deps.readGuard?.recordUnchanged?.(wp);
986
- const receipt = runtime
987
- .recordMutationToolReceipt;
988
- const autofixMode = receipt
989
- ? receipt.call(runtime, wp, "write").autofixMode
990
- : "immediate";
991
- // Recovered opaque writes carry their own source so the change log
992
- // distinguishes them from parsed writes (auditable in production).
993
- const isOpaque = opaqueSet.has(wp);
994
- // Failure atomicity: an opaque-recovered file VERIFIABLY exists on
995
- // disk, so its synthetic event must not inherit isError - the main
996
- // path early-returns on failed host results before attribution,
997
- // which would silently drop exactly the partial writes invariant 5
998
- // says to attribute.
999
- const syntheticEvent = {
1000
- ...event,
1001
- toolName: "write",
1002
- input: { path: wp },
1003
- isError: false,
1004
- // #2423: pi-lens SYNTHESIZED this write from a bash command, so the
1005
- // seam reports `provenance: "bash-derived"` and a consumer can tell
1006
- // it apart from the host's own write tool.
1007
- [PI_LENS_SYNTHETIC_MUTATION_FIELD]: "bash",
1008
- };
1009
- const syntheticResult = await handleToolResult({
1010
- ...deps,
1011
- event: syntheticEvent,
1012
- _bypassDebounce: true,
1013
- _autofixMode: autofixMode,
1014
- _attachmentBudget: syntheticAttachmentBudget,
1015
- _mutationSourceOverride: isOpaque ? "opaque-script" : undefined,
1016
- _readGuardAuthorship: opaqueSet.has(wp) || recognizedAuthoredSet.has(wp),
1017
- });
1018
- if (syntheticResult) {
1019
- // #1590: forward verbatim. The synthetic call already charged the
1020
- // shared budget above and phrased its own notice from the decision
1021
- // it made, so a second verdict out here could only contradict it —
1022
- // which is exactly the defect this shape produced before.
1023
- syntheticWriteContent.push(...syntheticResult.content.slice(event.content.length));
1024
- }
1025
- }
1026
- if (event.isError !== true && !getFlag("no-read-guard")) {
1027
- const truncation = event.details?.truncation;
1028
- const parsedSpans = extractReadPathsFromCommand(command, workspaceRoot);
1029
- let spans = parsedSpans;
1030
- if (truncation?.truncated === true &&
1031
- typeof truncation.outputLines === "number") {
1032
- if (parsedSpans.length === 1) {
1033
- const span = parsedSpans[0];
1034
- if (span) {
1035
- // countFileLines intentionally preserves the split-based guard
1036
- // convention, where a trailing newline contributes an empty final
1037
- // element. The host's output line count does not include that
1038
- // element, so remove it from the span basis before taking the tail.
1039
- const hasTrailingNewline = nodeFs
1040
- .readFileSync(span.filePath, "utf8")
1041
- .endsWith("\n");
1042
- const spanLineCount = hasTrailingNewline
1043
- ? Math.max(1, span.limit - 1)
1044
- : span.limit;
1045
- const shown = Math.min(truncation.outputLines, spanLineCount);
1046
- spans =
1047
- shown > 0
1048
- ? [
1049
- {
1050
- ...span,
1051
- offset: span.offset + spanLineCount - shown,
1052
- limit: shown,
1053
- },
1054
- ]
1055
- : [];
1056
- }
1057
- }
1058
- else if (parsedSpans.length > 1) {
1059
- recordDegradationOnce({
1060
- kind: "bash-view-clipped",
1061
- subject: "multi-span",
1062
- reason: "truncated bash view contained multiple spans",
1063
- });
1064
- spans = [];
1065
- }
1066
- if (parsedSpans.length === 1 &&
1067
- spans.length === 1 &&
1068
- (spans[0]?.offset !== parsedSpans[0]?.offset ||
1069
- spans[0]?.limit !== parsedSpans[0]?.limit)) {
1070
- recordDegradationOnce({
1071
- kind: "bash-view-clipped",
1072
- subject: parsedSpans[0]?.filePath ?? "unknown",
1073
- reason: "truncated bash view narrowed a single span",
1074
- });
1075
- }
1076
- }
1077
- for (const span of spans) {
1078
- if (isExternalOrVendorFile(span.filePath, workspaceRoot))
1079
- continue;
1080
- if (isPathIgnoredByProject(span.filePath, workspaceRoot, false))
1081
- continue;
1082
- deps.readGuard?.recordRead({
1083
- filePath: span.filePath,
1084
- requestedOffset: span.offset,
1085
- requestedLimit: span.limit,
1086
- effectiveOffset: span.offset,
1087
- effectiveLimit: span.limit,
1088
- expandedByLsp: false,
1089
- turnIndex: runtime.turnIndex,
1090
- writeIndex: runtime.peekWriteIndex(),
1091
- timestamp: Date.now(),
1092
- });
1093
- }
1094
- }
1095
- // #1668: bash-deleted files never go through the edit tool, so nothing
1096
- // else tells an LSP server one of its watched files is gone — the ONLY
1097
- // existing enqueue site fires on first open and can only emit type 1/2.
1098
- // Extract the command's likely delete targets, confirm each by existence
1099
- // (never scan the workspace — only the paths the command named), and only
1100
- // act on paths pi-lens already knows about (a read or a write this
1101
- // session) so an `rm` on something pi-lens never touched is not treated
1102
- // as a signal. Each match is routed to already-active LSP clients as a
1103
- // type-3 watched-files event through the same #271 coalescing queue a
1104
- // burst of deletes still flushes as one notification per server.
1105
- if (event.isError !== true &&
1106
- !getFlag("no-lsp") &&
1107
- !getFlag("no-read-guard")) {
1108
- for (const dp of extractDeletedPathsFromCommand(command, workspaceRoot)) {
1109
- if (isExternalOrVendorFile(dp, workspaceRoot))
1110
- continue;
1111
- if (isPathIgnoredByProject(dp, workspaceRoot, false))
1112
- continue;
1113
- if (!deps.readGuard || !deps.readGuard.hasKnownPath(dp))
1114
- continue;
1115
- // #1668 review F4: this is the ONLY gate standing between a merely
1116
- // NAMED path and an actual confirmed delete — extractDeletedPathsFromCommand
1117
- // only proposes candidates from parsing the command text, so it can't
1118
- // tell `git rm --cached f` (index-only, file still on disk) from a
1119
- // real delete, can't see a short-circuited `rm f && false` that never
1120
- // ran, and can't resolve a relative path run from a `cd`-ed subdirectory
1121
- // against the wrong cwd. Every one of those is caught here, and only
1122
- // here — do not remove or reorder this check relative to the loop body.
1123
- if (nodeFs.existsSync(dp))
1124
- continue; // still there — not a real delete
1125
- deps.readGuard.forgetPath(dp);
1126
- void notifyExternalFileChange(dp, 3).catch((err) => {
1127
- dbg(`tool_result: external-delete notify failed for ${dp}: ${err}`);
1128
- });
1129
- }
1130
- }
1131
- }
1132
- // Search tools reveal specific lines (file:line) the agent then edits — register
1133
- // those shown lines (± context) as reads so the follow-up edit isn't blocked (#169).
1134
- // Our tools attach locations as `details.searchReads`; bash grep is parsed from
1135
- // `grep -n` output. Only shown lines are registered, never the whole file.
1136
- if (deps.readGuard && event.isError !== true && !getFlag("no-read-guard")) {
1137
- const searchReads = [];
1138
- const detailSearchReads = event.details?.searchReads;
1139
- if (Array.isArray(detailSearchReads))
1140
- searchReads.push(...detailSearchReads);
1141
- if (event.toolName === "bash" &&
1142
- typeof event.input.command === "string") {
1143
- const command = event.input.command;
1144
- const output = event.content
1145
- .map((part) => (typeof part.text === "string" ? part.text : ""))
1146
- .join("\n");
1147
- searchReads.push(...extractGrepSearchReadsFromOutput(command, workspaceRoot, output));
1148
- }
1149
- if (searchReads.length > 0) {
1150
- registerSearchReads(deps.readGuard, searchReads, {
1151
- projectRoot: workspaceRoot,
1152
- turnIndex: runtime.turnIndex,
1153
- writeIndex: runtime.peekWriteIndex(),
1154
- });
1155
- }
1156
- }
1157
- // Native read results are the authoritative read boundary. The tool_call
1158
- // input can request past EOF, and the host can cap bytes or lines before the
1159
- // result reaches the model. Register only the delivered range (#2802).
1160
- if (deps.readGuard &&
1161
- event.toolName === "read" &&
1162
- event.isError !== true &&
1163
- filePath &&
1164
- !getFlag("no-read-guard") &&
1165
- !isExternalOrVendorFile(filePath, workspaceRoot)) {
1166
- const deliveredFilePath = attribution?.resolvedPath && nodeFs.existsSync(attribution.resolvedPath)
1167
- ? attribution.resolvedPath
1168
- : filePath;
1169
- if (nodeFs.existsSync(deliveredFilePath)) {
1170
- const nativeReadToolCallId = resolveToolCallCorrelationId(event);
1171
- const input = event.input;
1172
- const requestedOffset = input.offset ?? 1;
1173
- const requestedLimit = input.limit;
1174
- const truncation = event.details?.truncation;
1175
- const available = Math.max(0, countFileLines(deliveredFilePath) - requestedOffset + 1);
1176
- const deliveredLimit = Math.min(available, truncation?.outputLines ?? requestedLimit ?? available);
1177
- if (deliveredLimit > 0) {
1178
- if (truncation?.truncated === true && deliveredLimit < available) {
1179
- recordDegradationOnce({
1180
- kind: "native-read-clipped",
1181
- subject: deliveredFilePath,
1182
- reason: "native read result was clipped before delivery",
1183
- });
1184
- }
1185
- logReadGuardEvent({
1186
- event: "read_pattern",
1187
- sessionId: runtime.telemetrySessionId,
1188
- filePath: deliveredFilePath,
1189
- requestedOffset,
1190
- requestedLimit: requestedLimit ?? deliveredLimit,
1191
- effectiveOffset: requestedOffset,
1192
- effectiveLimit: deliveredLimit,
1193
- metadata: {
1194
- totalLines: countFileLines(deliveredFilePath),
1195
- isPartial: deliveredLimit < available,
1196
- fileKind: detectFileKind(deliveredFilePath) ?? "unknown",
1197
- fractionRead: available > 0
1198
- ? Math.round((deliveredLimit / available) * 100) / 100
1199
- : 1,
1200
- expandedByTs: false,
1201
- },
1202
- });
1203
- const deliveredRecord = {
1204
- filePath: deliveredFilePath,
1205
- requestedOffset,
1206
- requestedLimit: requestedLimit ?? deliveredLimit,
1207
- effectiveOffset: requestedOffset,
1208
- effectiveLimit: deliveredLimit,
1209
- expandedByLsp: false,
1210
- turnIndex: runtime.turnIndex,
1211
- writeIndex: runtime.peekWriteIndex(),
1212
- timestamp: Date.now(),
1213
- };
1214
- if (nativeReadToolCallId) {
1215
- deps.readGuard.recordRead(deliveredRecord, {
1216
- supersedes: { toolCallId: nativeReadToolCallId },
1217
- });
1218
- }
1219
- else {
1220
- deps.readGuard.recordRead(deliveredRecord);
1221
- }
1222
- }
1223
- }
1224
- }
1225
- // #2423: THE inbound gate. Everything below this line is the mutation
1226
- // bookkeeping chain — read-guard staleness stamp, turn state, change-log
1227
- // receipt, deferred autofix and format. Before the seam this compared
1228
- // `event.toolName` to two literals, so a host or extension edit tool under
1229
- // any other name was dropped here with the path already resolved.
1230
- // `recognizeOnly` (#2423 review round 1, finding F5): the tool_call side
1231
- // already ran the adapters against the PRE-edit file and logged what they
1232
- // resolved. Re-running them here logged a second `touched_lines_detected`
1233
- // for every edit and an `edit_preflight_blocked` for edits that were never
1234
- // blocked, and any anchor it re-resolved would be resolved against content
1235
- // the edit has already rewritten. The seam carries the tool_call ranges
1236
- // forward by `toolCallId` instead.
1237
- const mutation = classifyMutatingTool(event, {
1238
- filePath: filePath || undefined,
1239
- sessionId: deps.sessionId,
1240
- recognizeOnly: true,
1241
- });
1242
- // #2430: settle the observational baseline BEFORE the classification gate
1243
- // returns. On the FIRST call of an unknown tool nothing below this line will
1244
- // run — that is the bug — so the disk diff is the only thing that can put
1245
- // the file in `turn-state.json`, and it replays through the mutation bridge
1246
- // to get the identical bookkeeping a `write` gets.
1247
- //
1248
- // The PROBE is synchronous and is the first thing asked, so the
1249
- // overwhelmingly common call — no baseline armed — pays one map lookup and
1250
- // nothing else (#2449 round 2, F1).
1251
- //
1252
- // The SETTLE is async (#2449 round 3, T4: no synchronous filesystem work on
1253
- // this path), so it yields. `handleToolResult` has no other `await` before
1254
- // it registers with `debouncedPipelines`/`inFlightPipelines`, and
1255
- // `tests/clients/runtime-tool-result-debounce.test.ts` asserts that a
1256
- // racing second tool_result for the same path cannot miss the first's
1257
- // entry — so everything the chain below derives from the file's POST-RESULT
1258
- // bytes is read HERE, before the yield. Otherwise the racing call rewrites
1259
- // the file while this one is awaiting and this one registers under the
1260
- // OTHER call's state hash, collapsing two distinct pipelines into one.
1261
- const observationPending = !getFlag("no-read-guard") &&
1262
- hasPendingObservation(resolveToolCallCorrelationId(event));
1263
- // #2464 review round 2 (S2): NOT gated on `mutation !== undefined` any more.
1264
- // The observed path now dispatches on call ONE of an unknown tool too, and
1265
- // that call is by definition unclassified — gating the pre-yield digest on a
1266
- // classification that does not exist yet would have left exactly the racing
1267
- // re-read this hoist exists to prevent.
1268
- const preSettleStateHash = observationPending && filePath ? getFileStateHash(filePath) : undefined;
1269
- let observedReplayed = 0;
1270
- let observedChangedPaths = [];
1271
- if (observationPending) {
1272
- const observed = await settleObservedMutation({
1273
- toolCallId: resolveToolCallCorrelationId(event),
1274
- toolName: event.toolName,
1275
- sessionGeneration: runtime.sessionGeneration,
1276
- turnIndex: runtime.turnIndex,
1277
- signal: getAmbientAbortSignal(),
1278
- record: replayThroughMutationBridge,
1279
- getStoredLineHashes: (candidate) => storedLineHashesFor(deps.readGuard, candidate),
1280
- isRecordable: (candidate) => !isExternalOrVendorFile(candidate, workspaceRoot) &&
1281
- !isPathIgnoredByProject(candidate, workspaceRoot, false),
1282
- dbg,
1283
- });
1284
- observedReplayed = observed.replayed;
1285
- observedChangedPaths = observed.changedPaths;
1286
- if (observed.replayed > 0) {
1287
- dbg(`tool_result: observed ${observed.replayed} mutation(s) from tool "${event.toolName}"`);
1288
- }
1289
- else if (observed.reason) {
1290
- dbg(`tool_result: observation for "${event.toolName}" did not settle: ${observed.reason}`);
1291
- }
1292
- }
1293
- // #2464 review round 2 (S5): ONE clock, started above BOTH exits, so
1294
- // `edit_batch_summary.durationMs` and the `tool_result` latency row measure
1295
- // the same span whichever provenance a tool takes. The observed path used to
1296
- // start its clock at the dispatch call itself, so its durations were
1297
- // pipeline-only and silently incomparable with the classified path's.
1298
- // Deliberately below the settle: neither path should be charged for the
1299
- // observational disk diff, which is arm-time work, not tool_result work.
1300
- const toolResultStart = Date.now();
1301
- // #2449 review round 3 (S2), narrowed in round 4 (S4). A tool learned from
1302
- // ONE observation is classified by NAME from here on AND is still armed —
1303
- // that second property is what makes a second observation, and therefore
1304
- // persistence, reachable at all (round 2, F2). Both halves then recorded the
1305
- // same physical edit: the settle above replayed it through the mutation
1306
- // bridge with measured ranges, and the chain below recorded it AGAIN as a
1307
- // whole-file change, so a three-edit session produced four change-log
1308
- // receipts.
1309
- //
1310
- // The settle wins, deliberately. It ran the disk diff, so it knows which
1311
- // LINES moved; the chain, reached through `recognizeOnly`, has no ranges for
1312
- // an unknown tool and over-approximates to the file. Skipping the arm
1313
- // instead would be the other way to fix this, and it is the wrong one — it
1314
- // makes PERSIST_AFTER_OBSERVATIONS unreachable again.
1315
- //
1316
- // ## What this return skips, stated in full (round 4, S4; #2464)
1317
- //
1318
- // The first cut called this "skipping turn tracking" and returned. It skipped
1319
- // considerably more than turn tracking, and THREE of those steps have no
1320
- // counterpart in `recordMutationThroughSeam`, so nothing else ran them. Those
1321
- // three run here, before the return:
1322
- //
1323
- // - the #2402 applied-edit records — without them an identical retry of
1324
- // the observed tool's edit escalates through the oldText-not-found ladder
1325
- // instead of being recognized as already applied;
1326
- // - `recordMutationToolReceipt`, the write→edit sticky turn transition,
1327
- // which is pure ordering state the bridge never touches;
1328
- // - the `cachedExports` refresh — without it the pre-write STOP check keeps
1329
- // firing on names this very edit removed.
1330
- //
1331
- // What stays skipped is skipped because the BRIDGE already did it: the
1332
- // read-guard staleness stamp, the `turn-state.json` modified ranges, the
1333
- // attributed change-log receipt, and the deferred autofix/format pair —
1334
- // `recordMutationThroughSeam` steps 1-4. #2464 pulled the pipeline's own
1335
- // lint/diagnostics dispatch (`dispatchPipelineAnalysis`, defined above) out
1336
- // of the block below that also writes those same turn-state ranges and the
1337
- // change-log receipt, so it can be called HERE too — analysis without asking
1338
- // for the recording a second time.
1339
- //
1340
- // ## Why this sits ABOVE the classification gates (#2464 review round 2, S2)
1341
- //
1342
- // It used to sit BELOW `mutation === undefined`, which meant CALL ONE of every
1343
- // unknown tool — the call the observational net exists for — was recorded by
1344
- // the bridge and then returned unanalysed: `runPipeline` was never reached, so
1345
- // the file was fixed and formatted by the `agent_settled` drain but never
1346
- // linted, and AC2 ("an observed mutation gets its pipeline analysis in the
1347
- // same turn") was met on the second call only. `observedReplayed > 0` is the
1348
- // whole condition now: the bridge recorded this edit, whoever the tool is.
1349
- if (observedReplayed > 0) {
1350
- // ## The `hostToolResultFailed` asymmetry, stated rather than hidden
1351
- //
1352
- // The classified chain returns below on `event.isError === true` with a
1353
- // `commitStatus: "failed"` receipt; this block does not consult it, so an
1354
- // unknown tool that reports failure and STILL moved bytes is recorded,
1355
- // analysed, and receipted as `committed`. That is deliberate: the
1356
- // observation is disk evidence, not a claim — the bytes changed whatever
1357
- // the tool says about itself — and the classified early return is safe
1358
- // only because a failed host edit did not write. Reading a third-party
1359
- // tool's self-reported status as authority over what is on disk is the
1360
- // exact gap the observational net exists to close.
1361
- //
1362
- // The gates below (`mutation === undefined` / `!filePath` /
1363
- // `isExternalOrVendorFile`) are deliberately NOT consulted for the SKIP:
1364
- // once the bridge has recorded the edit, re-running the classified chain
1365
- // double-records it regardless of how the tool classifies. They are
1366
- // consulted for what this block can still usefully DO.
1367
- if (filePath && !isExternalOrVendorFile(filePath, workspaceRoot)) {
1368
- // On call ONE the tool is not classified at all, so there is no
1369
- // `mutation.kind` to read. The observation itself is the authority and
1370
- // it only ever records "edit" (`settleObservedMutation` hard-codes
1371
- // `kind: "edit"`, and #2430 tier 4 only ever classifies a learned tool
1372
- // as "edit"), so the two agree wherever both exist.
1373
- const observedKind = mutation?.kind ?? "edit";
1374
- const observedStateHash = preSettleStateHash ?? getFileStateHash(filePath);
1375
- const observedAppliedPairs = recordNativeAppliedPairs({
1376
- runtime,
1377
- input: event.input,
1378
- kind: observedKind,
1379
- filePath,
1380
- stateHash: observedStateHash,
1381
- });
1382
- const receiptOutcome = runtime.recordMutationToolReceipt?.call(runtime, filePath, observedKind);
1383
- refreshCachedExports(runtime, filePath);
1384
- // Same fallback formula the classified chain uses below, minus its
1385
- // `_bypassDebounce` branch (#2464 review round 2, S3): that branch was
1386
- // unreachable here. Both callers that set `_bypassDebounce` arrive with
1387
- // no pending baseline — `scheduleDebounced`'s re-entry because THIS
1388
- // call already consumed it at the settle above, and the bash-derived
1389
- // synthetic write because `runtime-tool-call.ts` excludes `bash` from
1390
- // arming outright (`toolName !== "bash"`). `observedKind` is always
1391
- // "edit", so the un-receipted default is "deferred" either way.
1392
- const observedAutofixMode = receiptOutcome?.autofixMode ??
1393
- (observedKind === "edit" ? "deferred" : "immediate");
1394
- // Analyse the files the observation actually RECORDED, not merely the
1395
- // path the tool named. A directory is never a pipeline target.
1396
- const observedDispatchPaths = observedChangedPaths
1397
- .filter((candidate) => {
1398
- try {
1399
- return !nodeFs.statSync(candidate).isDirectory();
1400
- }
1401
- catch {
1402
- return false;
1403
- }
1404
- })
1405
- .slice(0, OBSERVED_DISPATCH_MAX_PATHS);
1406
- const observedDispatchDropped = observedChangedPaths.length - observedDispatchPaths.length;
1407
- if (observedDispatchDropped > 0) {
1408
- incrementDegradationCount({
1409
- kind: "observed-mutation-dispatch-cap",
1410
- subject: event.toolName,
1411
- reason: `observed mutation dispatch capped at ${OBSERVED_DISPATCH_MAX_PATHS}; ${observedDispatchDropped} path(s) not dispatched`,
1412
- });
1413
- }
1414
- if (observedDispatchPaths.length > 0) {
1415
- const observedClients = ensureToolResultClients(deps);
1416
- if (observedClients !== true &&
1417
- !(await bounded(Promise.resolve(observedClients), {
1418
- ms: HOOK_WALL_BUDGET_MS.tool_result_edit,
1419
- signal: deps.signal ?? undefined,
1420
- hook: "tool_result_edit",
1421
- label: "observed-tool-result-analysis",
1422
- })))
1423
- return;
1424
- const observedReadGuardCorrelationId = getReadGuardCorrelationId(event);
1425
- // #2464 review round 3 (F1): the SAME two pre-conditions the
1426
- // classified site consults, through the same shared claim. Round 2
1427
- // dispatched here with neither, so two concurrent observed
1428
- // `tool_result`s for one file+hash both registered and both ran
1429
- // `runPipeline` — two autofix/format writers racing on one file — the
1430
- // second overwrote the first's registry entry, and the first's
1431
- // release then evicted the outer entry a live, unrelated classified
1432
- // pipeline had since re-created under it.
1433
- for (const observedPath of observedDispatchPaths) {
1434
- const observedDispatchSignal = deps.signal;
1435
- const observedJoinSignal = deps.signal;
1436
- const observedStateHashForPath = getFileStateHash(observedPath);
1437
- const observedClaim = claimPipelineDispatch({
1438
- filePath: observedPath,
1439
- stateHash: observedStateHashForPath,
1440
- turnIndex: runtime.turnIndex,
1441
- participantId: observedReadGuardCorrelationId,
1442
- dbg,
1443
- });
1444
- if (!observedClaim.proceed) {
1445
- if (observedClaim.joined) {
1446
- await bounded(observedClaim.joined, {
1447
- ms: HOOK_WALL_BUDGET_MS.tool_result_edit,
1448
- signal: observedJoinSignal,
1449
- hook: "tool_result_edit",
1450
- label: "observed-tool-result-join",
1451
- });
1452
- }
1453
- continue;
1454
- }
1455
- const observedDispatchOutcome = await bounded(dispatchPipelineAnalysis({
1456
- deps,
1457
- runtime,
1458
- filePath: observedPath,
1459
- dispatchCwd: resolveLanguageRootForFile(observedPath, workspaceRoot),
1460
- turnStateCwd: path.resolve(workspaceRoot),
1461
- autofixMode: observedAutofixMode,
1462
- modifiedRanges: undefined,
1463
- writeIndex: runtime.nextWriteIndex(),
1464
- initialStateHash: observedStateHashForPath,
1465
- readGuardCorrelationId: observedReadGuardCorrelationId,
1466
- requestedEditIndexes: getRequestedEditIndexes(event, observedKind),
1467
- requestedEditTotal: getRequestedEditCount(event, observedKind),
1468
- isPartialApplyResult: (event.details ?? {})
1469
- .piLensPartialApply === true,
1470
- participantIds: [observedReadGuardCorrelationId],
1471
- participantTotal: 1,
1472
- toolResultStart,
1473
- nativeAppliedPairs: observedAppliedPairs,
1474
- // #2802 authorship rule (master): the observational
1475
- // settle already recorded this edit through the
1476
- // bridge, so the dispatch's read-guard write refresh
1477
- // carries evidence and stays enabled on every
1478
- // per-path dispatch.
1479
- allowReadGuardWrites: true,
1480
- }), {
1481
- ms: HOOK_WALL_BUDGET_MS.tool_result_edit,
1482
- signal: observedDispatchSignal,
1483
- hook: "tool_result_edit",
1484
- label: "observed-tool-result-analysis",
1485
- });
1486
- if (observedDispatchOutcome?.crashed) {
1487
- // #2464 review round 2, S6: parity with the classified chain — a
1488
- // pipeline crash surfaces its notice to the agent instead of being
1489
- // swallowed into a dbg line the model never sees. The recorded
1490
- // edit stands either way; only the analysis was lost.
1491
- dbg(`tool_result: pipeline analysis crashed for the observed mutation on ${observedPath}; the recorded edit stands, analysis did not run this turn`);
1492
- return observedDispatchOutcome.response;
1493
- }
1494
- }
1495
- dbg(`tool_result: the observational settle already recorded ${observedReplayed} mutation(s) for "${event.toolName}"; kept the applied-edit records, mutation receipt, cachedExports refresh, and ran the pipeline dispatch (#2464); skipped the bridge-covered staleness stamp / turn-state ranges / change-log receipt / deferred autofix+format`);
1496
- }
1497
- else {
1498
- dbg(`tool_result: the observational settle recorded ${observedReplayed} mutation(s) for "${event.toolName}", but no dispatchable changed paths remained`);
1499
- }
1500
- }
1501
- return syntheticWriteContent.length > 0
1502
- ? { content: [...event.content, ...syntheticWriteContent] }
1503
- : undefined;
1504
- }
1505
- if (mutation === undefined) {
1506
- dbg(`tool_result: skipped turn tracking - toolName="${event.toolName}" is not a classified mutation`);
1507
- return syntheticWriteContent.length > 0
1508
- ? { content: [...event.content, ...syntheticWriteContent] }
1509
- : undefined;
1510
- }
1511
- if (!filePath) {
1512
- dbg(`tool_result: skipped turn tracking - no filePath for toolName="${event.toolName}"`);
1513
- return;
1514
- }
1515
- if (isExternalOrVendorFile(filePath, workspaceRoot)) {
1516
- dbg(`tool_result: skipped pipeline - file outside project root or in node_modules: ${filePath}`);
1517
- return;
1518
- }
1519
- // #2430: a classified mutation is accounted for by the chain below, so the
1520
- // `agent_settled` sweep must re-baseline this file rather than report the
1521
- // same bytes as unexplained drift.
1522
- noteMutationHandled(filePath);
1523
- const readGuardCorrelationId = getReadGuardCorrelationId(event);
1524
- const resultDetails = (event.details ?? {});
1525
- const isPartialApplyResult = resultDetails.piLensPartialApply === true;
1526
- const requestedEditIndexes = getRequestedEditIndexes(event, mutation.kind);
1527
- const requestedEditTotal = getRequestedEditCount(event, mutation.kind);
1528
- const participantIds = [
1529
- ...(deps._telemetryParticipantIds ?? []),
1530
- readGuardCorrelationId,
1531
- ].slice(0, 100);
1532
- const participantTotal = (deps._telemetryParticipantTotal ?? 0) +
1533
- (deps._telemetryParticipantIds?.includes(readGuardCorrelationId) ? 0 : 1);
1534
- const hostToolResultFailed = event.isError === true || resultDetails.isError === true;
1535
- if (hostToolResultFailed) {
1536
- logReadGuardEvent({
1537
- event: "edit_batch_summary",
1538
- correlationId: readGuardCorrelationId,
1539
- filePath,
1540
- metadata: {
1541
- tool: event.toolName,
1542
- source: "host_tool_result",
1543
- editBatchSummary: createReadGuardEditBatchSummary({
1544
- requestedIndexes: requestedEditIndexes,
1545
- requestedTotal: requestedEditTotal,
1546
- rejectedReasons: requestedEditIndexes.map((index) => ({
1547
- index,
1548
- code: "write_failed",
1549
- })),
1550
- rejectedTotal: requestedEditTotal,
1551
- participantIds: [readGuardCorrelationId],
1552
- participantTotal: 1,
1553
- commitStatus: "failed",
1554
- terminalStatus: "failed",
1555
- }),
1556
- },
1557
- });
1558
- return { content: event.content, isError: true };
1559
- }
1560
- // One post-result raw-byte hash, reused for the applied-edit records below and
1561
- // for the pipeline dedup key (`initialStateHash`) further down (finding 3):
1562
- // nothing between here and that point rewrites the file, so a second read
1563
- // would only re-derive the same digest.
1564
- //
1565
- // `preSettleStateHash` is that same digest taken BEFORE the observational
1566
- // settle's yield, on the only path that has one (#2449 round 3, T4). Reusing
1567
- // it is not an optimization: re-reading here would read whatever a racing
1568
- // tool_result wrote while this call was awaiting.
1569
- const postWriteStateHash = preSettleStateHash ?? getFileStateHash(filePath);
1570
- // #2402: a fully-applied native edit is also an applied record, so an
1571
- // identical retry is recognized as already-applied instead of escalating
1572
- // through the oldText-not-found ladder. `event.input` carries the EXECUTED
1573
- // args (post-autopatch), the same text the preflight resolves against.
1574
- const nativeAppliedPairs = recordNativeAppliedPairs({
1575
- runtime,
1576
- input: event.input,
1577
- kind: mutation.kind,
1578
- filePath,
1579
- stateHash: postWriteStateHash,
1580
- });
1581
- // Must happen before debounce admission: latestDeps intentionally retains only
1582
- // the latest event, but write -> edit is a sticky turn transition.
1583
- const receipt = runtime
1584
- .recordMutationToolReceipt;
1585
- const autofixMode = deps._bypassDebounce
1586
- ? (deps._autofixMode ??
1587
- (mutation.kind === "edit" ? "deferred" : "immediate"))
1588
- : receipt
1589
- ? receipt.call(runtime, filePath, mutation.kind).autofixMode
1590
- : mutation.kind === "edit"
1591
- ? "deferred"
1592
- : "immediate";
1593
- // Coalesce sequential edits to the same file into one pipeline run against
1594
- // the final state. Only the debounce-fired call (with _bypassDebounce=true)
1595
- // proceeds to the pipeline body; in-window callers share its promise.
1596
- if (!deps._bypassDebounce) {
1597
- const debounceMs = getDebounceMs();
1598
- if (debounceMs > 0) {
1599
- return scheduleDebounced(filePath, debounceMs, {
1600
- ...deps,
1601
- _autofixMode: autofixMode,
1602
- _telemetryParticipantIds: [readGuardCorrelationId],
1603
- _telemetryParticipantTotal: 1,
1604
- });
1605
- }
1606
- }
1607
- // Refresh the read-guard's FileTime stamp so that the model's own write
1608
- // doesn't trigger a spurious "file_modified" block on the next edit.
1609
- if (bashAuthorshipConfirmed)
1610
- deps.readGuard?.recordWritten(filePath);
1611
- // Keep cachedExports in sync after each write/edit so the pre-write STOP
1612
- // check doesn't fire on names that were removed from this file this session.
1613
- refreshCachedExports(runtime, filePath);
1614
- // Reuse the hash taken right after the write landed (finding 3): the file is
1615
- // unchanged between that read and here, so this is byte-identical.
1616
- const initialStateHash = postWriteStateHash;
1617
- // #2464 review round 3 (F1): the in-flight dedup and the already-analysed
1618
- // latch moved into `claimPipelineDispatch`, shared verbatim with the observed
1619
- // call site, which shipped round 2 with NEITHER check. The position is
1620
- // unchanged — still ABOVE `addModifiedRange`/`recordProjectChange`, so a
1621
- // duplicate state still writes no turn-state range and no change-log
1622
- // receipt. Nothing may await between this claim and the dispatch below: the
1623
- // claim is only atomic because `dispatchPipelineAnalysis` registers before
1624
- // its own first await.
1625
- const classifiedClaim = claimPipelineDispatch({
1626
- filePath,
1627
- stateHash: initialStateHash,
1628
- turnIndex: runtime.turnIndex,
1629
- participantId: readGuardCorrelationId,
1630
- dbg,
1631
- });
1632
- if (!classifiedClaim.proceed) {
1633
- if (classifiedClaim.joined) {
1634
- await classifiedClaim.joined;
1635
- }
1636
- return;
1637
- }
1638
- const sessionFileTime = createFileTime("default");
1639
- // tool_result is emitted after write/edit has already been applied.
1640
- // Asserting pre-write stamps here produces false positives on rapid edits.
1641
- sessionFileTime.read(filePath);
1642
- if (!getFlag("no-read-guard") && bashAuthorshipConfirmed) {
1643
- const readGuard = runtime.readGuard;
1644
- readGuard?.recordWritten?.(filePath);
1645
- }
1646
- // `toolResultStart` is hoisted above both provenance exits (#2464 review
1647
- // round 2, S5) so the two paths' durations are comparable — see its
1648
- // declaration right after the observational settle.
1649
- dbg(`tool_result: tracking turn state for ${event.toolName} on ${filePath}`);
1650
- if (isPathIgnoredByProject(filePath, workspaceRoot, false)) {
1651
- dbg(`tool_result: skipping gitignored file ${filePath}`);
1652
- return;
1653
- }
1654
- const dispatchCwd = resolveLanguageRootForFile(filePath, workspaceRoot);
1655
- const turnStateCwd = path.resolve(workspaceRoot);
1656
- dbg(`tool_result: resolved dispatch cwd ${dispatchCwd} for ${filePath} (turnState cwd ${turnStateCwd})`);
1657
- // #1655 item 2: a `setTelemetryIdentity` call used to sit here, gated on
1658
- // `event.model`/`provider`/`sessionId`/`session.id`. pi sets none of those on
1659
- // a `tool_result` — `afterToolCall` builds the event with exactly
1660
- // `type`/`toolName`/`toolCallId`/`input`/`content`/`details`/`isError`/`usage`
1661
- // (`@earendil-works/pi-coding-agent/dist/core/agent-session.js:243-256`,
1662
- // source `src/core/agent-session.ts:502-516`), so the gate was always false
1663
- // against a real host and the branch never ran. Identity for this dispatch
1664
- // comes from the runtime, which `message_start`/`session_start` populate —
1665
- // see the `telemetry:` block handed to `runPipeline` below.
1666
- const writeIndex = runtime.nextWriteIndex();
1667
- let modifiedRanges;
1668
- // #2423: ranges a shape adapter resolved from the tool's own input. Only a
1669
- // classified non-native edit shape sets these — a plain host `edit` carries
1670
- // its ranges in `details.diff` and is handled by the branch below.
1671
- const adapterRanges = mutation.editRanges && mutation.editRanges.length > 0
1672
- ? mutation.editRanges.map(([start, end]) => ({ start, end }))
1673
- : mutation.touchedLines
1674
- ? [{ start: mutation.touchedLines[0], end: mutation.touchedLines[1] }]
1675
- : undefined;
1676
- try {
1677
- // #1334 S6: the host DECLARES this payload (`EditToolDetails`, a
1678
- // type-only export), so use it instead of re-declaring `{ diff?: string }`
1679
- // here — the ad-hoc shape hid the sibling `patch`/`firstChangedLine`
1680
- // fields. `Partial<>` keeps the defensive posture: the host types mark
1681
- // `diff` required, but this runs against whatever a live host actually
1682
- // sent, and the `details?.diff` truthiness check below is what the code
1683
- // has always relied on.
1684
- const details = event.details;
1685
- dbg(`tool_result: details.diff=${details?.diff ? "present" : "missing"}, details keys: ${Object.keys(event.details || {}).join(", ")}`);
1686
- if (mutation.kind === "edit" && details?.diff) {
1687
- const diff = details.diff;
1688
- dbg(`tool_result: diff content (first 500 chars): ${diff.substring(0, 500)}`);
1689
- const ranges = parseDiffRanges(diff);
1690
- modifiedRanges = ranges;
1691
- const importsChanged = /import\s/.test(diff) || /from\s+['"]/.test(diff);
1692
- dbg(`tool_result: parsed ${ranges.length} ranges, importsChanged=${importsChanged}`);
1693
- for (const range of ranges) {
1694
- dbg(`tool_result: adding range ${range.start}-${range.end} for ${filePath}`);
1695
- cacheManager.addModifiedRange(filePath, range, importsChanged, turnStateCwd, runtime.telemetrySessionId);
1696
- }
1697
- dbg(`tool_result: turn state after add: ${JSON.stringify(cacheManager.readTurnState(turnStateCwd))}`);
1698
- }
1699
- else if (mutation.kind === "edit" &&
1700
- adapterRanges &&
1701
- nodeFs.existsSync(filePath)) {
1702
- // #2423: a third-party edit tool ships no host `details.diff`, so the
1703
- // diff branch above never fires and the file used to leave `files: {}`
1704
- // empty in turn-state.json. The shape adapter already resolved which
1705
- // lines the call touched — use those.
1706
- const content = nodeFs.readFileSync(filePath, "utf-8");
1707
- const importsChanged = /^import\s/m.test(content);
1708
- modifiedRanges = adapterRanges;
1709
- for (const range of adapterRanges) {
1710
- cacheManager.addModifiedRange(filePath, range, importsChanged, turnStateCwd, runtime.telemetrySessionId);
1711
- }
1712
- }
1713
- else if (mutation.kind === "edit" &&
1714
- mutation.provenance === "declared" &&
1715
- nodeFs.existsSync(filePath)) {
1716
- // #2423 review round 1 (F1): a third-party edit whose anchors did not
1717
- // resolve — a stale anchor, or the read-guard preflight never ran to
1718
- // resolve them — still CHANGED the file. Recording the whole file is a
1719
- // deliberate superset: turn state exists to say "this file changed,
1720
- // format and attribute it", and an empty `files` map is the exact
1721
- // symptom the issue reports. A host `edit` keeps its old behavior,
1722
- // because its ranges come from `details.diff` above.
1723
- const content = nodeFs.readFileSync(filePath, "utf-8");
1724
- const lineCount = content.split("\n").length;
1725
- const importsChanged = /^import\s/m.test(content);
1726
- modifiedRanges = [{ start: 1, end: lineCount }];
1727
- cacheManager.addModifiedRange(filePath, { start: 1, end: lineCount }, importsChanged, turnStateCwd, runtime.telemetrySessionId);
1728
- }
1729
- else if (mutation.kind === "write" && nodeFs.existsSync(filePath)) {
1730
- const content = nodeFs.readFileSync(filePath, "utf-8");
1731
- const lineCount = content.split("\n").length;
1732
- const hasImports = /^import\s/m.test(content);
1733
- modifiedRanges = [{ start: 1, end: lineCount }];
1734
- cacheManager.addModifiedRange(filePath, { start: 1, end: lineCount }, hasImports, turnStateCwd, runtime.telemetrySessionId);
1735
- }
1736
- }
1737
- catch (err) {
1738
- dbg(`turn state tracking error: ${err}`);
1739
- dbg(`turn state tracking error stack: ${err.stack}`);
1740
- }
1741
- recordProjectChange({
1742
- runtime,
1743
- cwd: turnStateCwd,
1744
- filePath,
1745
- source: deps._mutationSourceOverride ??
1746
- sourceForMutation(mutation, event.details),
1747
- changedRange: singleRange(modifiedRanges),
1748
- dbg,
1749
- });
1750
- const turnStateMs = Date.now() - toolResultStart;
1751
- logLatency({
1752
- type: "phase",
1753
- toolName: event.toolName,
1754
- filePath,
1755
- phase: "turn_state_tracking",
1756
- durationMs: turnStateMs,
1757
- });
1758
- dbg(`tool_result fired for: ${filePath} (turn_state: ${turnStateMs}ms)`);
1759
- // #2464: the pipeline dispatch itself now lives in `dispatchPipelineAnalysis`
1760
- // (defined above `handleToolResult`), shared with the observed-mutation
1761
- // early return. This call site is otherwise unchanged — same arguments, same
1762
- // crash-then-return / success-then-continue shape as before the split.
1763
- const classifiedClients = ensureToolResultClients(deps);
1764
- if (classifiedClients !== true &&
1765
- !(await bounded(Promise.resolve(classifiedClients), {
1766
- ms: HOOK_WALL_BUDGET_MS.tool_result_edit,
1767
- signal: deps.signal,
1768
- hook: "tool_result_edit",
1769
- label: "classified-tool-result-analysis",
1770
- })))
1771
- return;
1772
- const dispatchOutcome = await bounded(dispatchPipelineAnalysis({
1773
- deps,
1774
- runtime,
1775
- filePath,
1776
- dispatchCwd,
1777
- turnStateCwd,
1778
- autofixMode,
1779
- modifiedRanges,
1780
- writeIndex,
1781
- initialStateHash,
1782
- readGuardCorrelationId,
1783
- requestedEditIndexes,
1784
- requestedEditTotal,
1785
- isPartialApplyResult,
1786
- participantIds,
1787
- participantTotal,
1788
- toolResultStart,
1789
- nativeAppliedPairs,
1790
- allowReadGuardWrites: bashAuthorshipConfirmed,
1791
- }), {
1792
- ms: HOOK_WALL_BUDGET_MS.tool_result_edit,
1793
- signal: deps.signal || undefined,
1794
- hook: "tool_result_edit",
1795
- label: "pipeline-analysis",
1796
- });
1797
- if (!dispatchOutcome)
1798
- return;
1799
- if (dispatchOutcome.crashed) {
1800
- return dispatchOutcome.response;
1801
- }
1802
- // #2464 review round 2 (S1): the three post-pipeline post-conditions that
1803
- // used to be written out here — the already-analysed latch, the #2402
1804
- // after-write hash stamp, and the read-guard staleness re-stamp over
1805
- // `result.changedFiles` — now live INSIDE `dispatchPipelineAnalysis`, so the
1806
- // observed path gets them by construction rather than by a second author
1807
- // remembering to copy them.
1808
- const result = dispatchOutcome.result;
1809
- let autofixNewlyQueued = false;
1810
- if (!result.isError &&
1811
- autofixMode === "deferred" &&
1812
- nodeFs.existsSync(filePath)) {
1813
- autofixNewlyQueued =
1814
- runtime.deferMutation?.call(runtime, filePath, dispatchCwd, event.toolName, turnStateCwd, "autofix", deps.sessionId, resolutionBasis) ?? false;
1815
- dbg(`tool_result: queued deferred autofix for ${filePath}`);
1816
- }
1817
- let formatQueued = false;
1818
- if (!result.isError &&
1819
- !getFlag("no-autoformat", filePath) &&
1820
- (autofixMode === "deferred" || !getFlag("immediate-format")) &&
1821
- nodeFs.existsSync(filePath)) {
1822
- const isNewlyQueued = runtime.deferFormat(filePath, dispatchCwd, event.toolName, turnStateCwd, deps.sessionId, resolutionBasis);
1823
- formatQueued = true;
1824
- dbg(`tool_result: queued deferred format for ${filePath}`);
1825
- logLatency({
1826
- type: "phase",
1827
- toolName: event.toolName,
1828
- filePath,
1829
- phase: "deferred_format_queued",
1830
- durationMs: 0,
1831
- metadata: { cwd: dispatchCwd },
1832
- });
1833
- // Publish a file's first queue entry and each newly added kind. A same-kind
1834
- // re-touch before agent_end carries no new information and stays silent.
1835
- if (isNewlyQueued || autofixNewlyQueued) {
1836
- publishFormatQueued({
1837
- filePath,
1838
- cwd: dispatchCwd,
1839
- // The v1 `pilens:format:queued` payload declares
1840
- // `tool: "write" | "edit"`, so a third-party tool publishes under
1841
- // its KIND rather than its name. Widening the published field is a
1842
- // public-API decision tracked in #2421; until then the kind is the
1843
- // honest projection.
1844
- tool: mutation.kind,
1845
- dbg,
1846
- kinds: autofixMode === "deferred" ? ["autofix", "format"] : ["format"],
1847
- });
1848
- }
1849
- }
1850
- if (autofixNewlyQueued && !formatQueued) {
1851
- publishFormatQueued({
1852
- filePath,
1853
- cwd: dispatchCwd,
1854
- // Same #2421 projection as the queued-with-format publish above.
1855
- tool: mutation.kind,
1856
- kinds: ["autofix"],
1857
- dbg,
1858
- });
1859
- }
1860
- for (const changedFile of result.changedFiles ?? []) {
1861
- const resolvedChanged = path.resolve(changedFile);
1862
- invalidateFormatterCacheForPath(resolvedChanged);
1863
- if (!nodeFs.existsSync(resolvedChanged))
1864
- continue;
1865
- recordProjectChange({
1866
- runtime,
1867
- cwd: turnStateCwd,
1868
- filePath: resolvedChanged,
1869
- source: "autofix",
1870
- dbg,
1871
- });
1872
- if (resolvedChanged === path.resolve(filePath))
1873
- continue;
1874
- try {
1875
- const content = nodeFs.readFileSync(resolvedChanged, "utf-8");
1876
- const lineCount = content.split("\n").length;
1877
- const hasImports = /^import\s/m.test(content);
1878
- cacheManager.addModifiedRange(resolvedChanged, { start: 1, end: lineCount }, hasImports, turnStateCwd);
1879
- dbg(`tool_result: tracking pi-lens side-effect change for ${resolvedChanged}`);
1880
- }
1881
- catch (err) {
1882
- dbg(`tool_result: side-effect tracking failed for ${resolvedChanged}: ${err}`);
1883
- }
1884
- }
1885
- if (result.cascadePromise) {
1886
- runtime.appendCascadePromise(result.cascadePromise);
1887
- }
1888
- if (result.actionableWarnings?.length) {
1889
- runtime.recordActionableWarnings(result.actionableWarnings);
1890
- }
1891
- if (result.codeQualityWarnings?.length) {
1892
- runtime.recordCodeQualityWarnings(result.codeQualityWarnings);
1893
- }
1894
- // #484: opt-in per-turn summary collection. Same signals the pipeline
1895
- // already computed above (diagnostics, autofix count/tools, formatters
1896
- // used) — no new collection plumbing, just fed into the collector when
1897
- // the feature is on.
1898
- if (getFlag("lens-turn-summary")) {
1899
- if (result.diagnostics?.length) {
1900
- for (const d of result.diagnostics) {
1901
- runtime.turnSummary.recordDiagnostic(d.filePath || filePath, {
1902
- tool: d.tool,
1903
- ruleId: d.rule ?? d.code,
1904
- severity: d.severity,
1905
- line: d.line,
1906
- description: d.message,
1907
- });
1908
- }
1909
- }
1910
- if (result.fixedCount && result.fixedCount > 0) {
1911
- for (const label of result.autofixTools ?? []) {
1912
- const [tool, countStr] = label.split(":");
1913
- const count = Number.parseInt(countStr ?? "", 10);
1914
- runtime.turnSummary.recordAutofix(filePath, {
1915
- tool: tool || label,
1916
- description: Number.isFinite(count) && count > 0
1917
- ? `${count} issue(s) fixed`
1918
- : undefined,
1919
- });
1920
- }
1921
- }
1922
- if (result.formattersUsed?.length) {
1923
- for (const tool of result.formattersUsed) {
1924
- runtime.turnSummary.recordFormat(filePath, { tool });
1925
- }
1926
- }
1927
- }
1928
- if (result.inlineBlockerSummary) {
1929
- // #1561: stamp the verdict with THIS dispatch's write token — the same
1930
- // counter `lsp_diagnostics`' reconciliation seam draws from — so a later
1931
- // confirmed-clean result can be ordered against it instead of racing it.
1932
- runtime.recordInlineBlockers(filePath, result.inlineBlockerSummary, writeIndex, result.inlineBlockerSources, result.inlineBlockerLines, result.inlineBlockerFileContent);
1933
- }
1934
- else {
1935
- runtime.clearInlineBlockers(filePath);
1936
- }
1937
- runtime.updateGitGuardStatus(result.hasBlockers, result.output);
1938
- if (getFlag("lens-guard")) {
1939
- syncGitGuardRecord(runtime, cacheManager, turnStateCwd, filePath);
1940
- if (result.isError && !result.hasBlockers) {
1941
- runtime.markGitGuardCacheUnknown("pipeline_error");
1942
- }
1943
- }
1944
- if (result.isError) {
1945
- return {
1946
- content: [...event.content, { type: "text", text: result.output }],
1947
- isError: true,
1948
- };
1949
- }
1950
- let output = result.output;
1951
- if (behaviorWarnings.length > 0 && !result.hasBlockers) {
1952
- output += `\n\n${formatBehaviorWarnings(behaviorWarnings)}`;
1953
- }
1954
- const totalMs = Date.now() - toolResultStart;
1955
- logLatency({
1956
- type: "tool_result",
1957
- toolName: event.toolName,
1958
- filePath,
1959
- durationMs: totalMs,
1960
- result: output ? "completed" : "no_output",
1961
- });
1962
- runtime.reportedThisTurn.add(filePath);
1963
- // --- The ONE authoritative-attachment decision (#1590) ---
1964
- // Everything downstream — the attached block, the telemetry row, the nudge
1965
- // suppression, and the notice sentence — reads this single verdict. It is
1966
- // the only place that sees both limits: the per-file cap and the shared
1967
- // per-command budget a multi-file bash write threads in.
1968
- const postMutation = result.postMutation;
1969
- const attachmentText = postMutation
1970
- ? `pi-lens applied autofix to ${postMutation.filePath}. The following full content is authoritative for subsequent edits:\n\n${postMutation.content}`
1971
- : "";
1972
- const contentBytes = postMutation
1973
- ? Buffer.byteLength(postMutation.content, "utf-8")
1974
- : 0;
1975
- const withinPerFileCap = contentBytes <= AUTHORITATIVE_CONTENT_MAX_BYTES;
1976
- const budget = deps._attachmentBudget;
1977
- const withinSharedBudget = !budget || Buffer.byteLength(attachmentText, "utf-8") <= budget.remaining;
1978
- const attachAuthoritativeContent = postMutation !== undefined && withinPerFileCap && withinSharedBudget;
1979
- const attachmentDecision = !postMutation
1980
- ? "none"
1981
- : attachAuthoritativeContent
1982
- ? "attached"
1983
- : withinPerFileCap
1984
- ? "aggregate-budget-degraded"
1985
- : "size-capped";
1986
- // #1590: the pipeline hands up the changed-file data and this layer renders
1987
- // the sentence, so a size-capped write can no longer carry both "attached
1988
- // content is authoritative" and "too large to attach". The fallback covers
1989
- // a post-mutation with no notice data, which must still say re-read.
1990
- const notice = result.postAutofixNotice ??
1991
- (postMutation
1992
- ? { targetPath: postMutation.filePath, changedFiles: [] }
1993
- : undefined);
1994
- if (postMutation && attachAuthoritativeContent && budget) {
1995
- budget.remaining -= Buffer.byteLength(attachmentText, "utf-8");
1996
- }
1997
- // #1590 review F1: every mutation that produced a notice logs a row,
1998
- // INCLUDING the `none` decision a format-only change makes. Gating the row
1999
- // on `postMutation` made a legitimate "nothing was attachable here" verdict
2000
- // indistinguishable from missing instrumentation, which is the same
2001
- // empty-vs-errored confusion the read paths already guard against.
2002
- if (postMutation || notice) {
2003
- logLatency({
2004
- type: "phase",
2005
- phase: "authoritative_content_attachment_decision",
2006
- filePath: postMutation?.filePath ?? filePath,
2007
- durationMs: 0,
2008
- metadata: {
2009
- path: postMutation?.filePath ?? filePath,
2010
- bytes: contentBytes,
2011
- decision: attachmentDecision,
2012
- },
2013
- });
2014
- }
2015
- if (postMutation) {
2016
- // #1464: the nudge suppresses exactly the paths this decision
2017
- // delivered. Same boolean the attachment below reads — the nudge layer
2018
- // never re-derives the cap or the budget for itself.
2019
- noteAuthoritativeContentAttachment(postMutation.filePath, attachAuthoritativeContent);
2020
- }
2021
- const returnedContent = attachAuthoritativeContent
2022
- ? [...event.content, { type: "text", text: attachmentText }]
2023
- : event.content;
2024
- if (notice) {
2025
- output = `${output ? `${output}\n\n` : ""}${renderPostAutofixNotice(notice, attachmentDecision)}`;
2026
- }
2027
- if (!output && !result.postMutation)
2028
- return;
2029
- return {
2030
- content: output
2031
- ? [...returnedContent, { type: "text", text: output }]
2032
- : returnedContent,
2033
- };
2034
- }