pi-lens 4.3.0 → 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 (650) hide show
  1. package/CHANGELOG.md +1064 -0
  2. package/README.md +115 -25
  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 +16456 -8335
  125. package/dist/mcp/analyze-cli.js +186 -232
  126. package/dist/mcp/cli.js +137 -98
  127. package/dist/mcp/server.js +22589 -1573
  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/agent-guide.md +13 -4
  133. package/docs/agent-tools.md +42 -0
  134. package/docs/ast-grep_rules_catalog.md +3 -2
  135. package/docs/configuration.md +20 -1
  136. package/docs/environment-variables.md +52 -2
  137. package/docs/features.md +8 -4
  138. package/docs/globalconfig.md +1 -0
  139. package/docs/io-bridge-v2-migration.md +94 -0
  140. package/docs/lsp-capability-matrix.md +36 -4
  141. package/docs/lsp-idle-eviction.md +124 -0
  142. package/docs/mcp.md +21 -5
  143. package/docs/merge-queue-rollout.md +77 -0
  144. package/docs/pi-lens-fixer.md +156 -88
  145. package/docs/pi-lens-investigator.md +74 -26
  146. package/docs/pi-lens-merge-policy.md +694 -0
  147. package/docs/pi-lens-monitor.md +73 -7
  148. package/docs/pi-lens-retro.md +6 -4
  149. package/docs/pi-lens-reviewer.md +188 -48
  150. package/docs/pi-lens-subagent.md +246 -45
  151. package/docs/pi-lens-warden.md +18 -7
  152. package/docs/public-api-stability.md +55 -0
  153. package/docs/release-qa-baseline.md +84 -17
  154. package/docs/rfcs/3654-unified-io-bridge-v2.md +316 -0
  155. package/docs/servercapabilities.md +53 -49
  156. package/docs/settings.md +1 -0
  157. package/docs/usage.md +5 -1
  158. package/grammars/tree-sitter-bash.wasm +0 -0
  159. package/grammars/tree-sitter-bash.wasm.json +3 -3
  160. package/package.json +19 -7
  161. package/rules/ast-grep-rules/rule-tests/advisory-registry-subset-test.yml +41 -0
  162. package/rules/ast-grep-rules/rules/advisory-registry-subset.yml +50 -0
  163. package/scripts/analyze-pi-lens-logs.mjs +1275 -62
  164. package/scripts/download-grammars.js +5 -0
  165. package/scripts/grammars.lock.json +6 -1
  166. package/scripts/install-selftest.mjs +33 -34
  167. package/scripts/lib/host-provided-deps.mjs +13 -4
  168. package/scripts/lib/web-tree-sitter-dir.mjs +18 -0
  169. package/dist/clients/actionable-warnings-logger.js +0 -35
  170. package/dist/clients/actionable-warnings.js +0 -1610
  171. package/dist/clients/advisory-provenance.js +0 -593
  172. package/dist/clients/agent-behavior-client.js +0 -147
  173. package/dist/clients/agent-nudge.js +0 -325
  174. package/dist/clients/analysed-root.js +0 -1
  175. package/dist/clients/ast-grep-client.js +0 -731
  176. package/dist/clients/ast-grep-rule-manager.js +0 -146
  177. package/dist/clients/ast-grep-tool-logger.js +0 -118
  178. package/dist/clients/ast-grep-types.js +0 -10
  179. package/dist/clients/ast-grep-yaml-synth.js +0 -154
  180. package/dist/clients/atomic-write-staging.js +0 -75
  181. package/dist/clients/atomic-write.js +0 -189
  182. package/dist/clients/availability-probe-flight.js +0 -12
  183. package/dist/clients/bash-file-access.js +0 -1056
  184. package/dist/clients/biome-client.js +0 -357
  185. package/dist/clients/blocker-freshness.js +0 -837
  186. package/dist/clients/blocker-past-eof.js +0 -129
  187. package/dist/clients/bootstrap.js +0 -569
  188. package/dist/clients/bounded-cache.js +0 -190
  189. package/dist/clients/bounded-pid-file-lock.js +0 -202
  190. package/dist/clients/bounded-telemetry.js +0 -295
  191. package/dist/clients/build-identity.js +0 -95
  192. package/dist/clients/bundled-resource-health.js +0 -113
  193. package/dist/clients/bus-events-logger.js +0 -105
  194. package/dist/clients/bus-publish.js +0 -171
  195. package/dist/clients/cache/rule-cache.js +0 -190
  196. package/dist/clients/cache-manager.js +0 -524
  197. package/dist/clients/cache-observability.js +0 -1313
  198. package/dist/clients/call-graph.js +0 -852
  199. package/dist/clients/cargo-manifest.js +0 -422
  200. package/dist/clients/cascade-budget.js +0 -196
  201. package/dist/clients/cascade-format.js +0 -315
  202. package/dist/clients/cascade-logger.js +0 -31
  203. package/dist/clients/cascade-types.js +0 -9
  204. package/dist/clients/child-unref.js +0 -124
  205. package/dist/clients/code-quality-warnings.js +0 -286
  206. package/dist/clients/codebase-model.js +0 -173
  207. package/dist/clients/collateral-test-role.js +0 -40
  208. package/dist/clients/complexity-client.js +0 -462
  209. package/dist/clients/config-core/deny.js +0 -221
  210. package/dist/clients/config-core/index.js +0 -50
  211. package/dist/clients/config-core/merge.js +0 -357
  212. package/dist/clients/config-core/normalize.js +0 -340
  213. package/dist/clients/config-core/process-spec.js +0 -248
  214. package/dist/clients/config-core/provenance.js +0 -164
  215. package/dist/clients/config-core/records.js +0 -218
  216. package/dist/clients/config-core/resolve.js +0 -125
  217. package/dist/clients/config-core/safe-object.js +0 -78
  218. package/dist/clients/config-core/schema.js +0 -165
  219. package/dist/clients/config-diagnostic-codes.js +0 -285
  220. package/dist/clients/config-locations.js +0 -388
  221. package/dist/clients/config-resolve.js +0 -798
  222. package/dist/clients/config-schema.js +0 -251
  223. package/dist/clients/config-warn.js +0 -407
  224. package/dist/clients/console-guard-install.js +0 -26
  225. package/dist/clients/cooperative-budget.js +0 -42
  226. package/dist/clients/dead-code-client.js +0 -510
  227. package/dist/clients/dead-code-logger.js +0 -30
  228. package/dist/clients/deadline-utils.js +0 -280
  229. package/dist/clients/debug-handles.js +0 -211
  230. package/dist/clients/debug-heap.js +0 -174
  231. package/dist/clients/deferred-lsp-work.js +0 -106
  232. package/dist/clients/degradation-ledger.js +0 -426
  233. package/dist/clients/demoted-finding-render.js +0 -169
  234. package/dist/clients/dependency-checker.js +0 -885
  235. package/dist/clients/deps/ast-grep-napi.js +0 -22
  236. package/dist/clients/deps/js-yaml.js +0 -9
  237. package/dist/clients/deps/minimatch.js +0 -4
  238. package/dist/clients/deps/pi-tui.js +0 -14
  239. package/dist/clients/deps/typebox.js +0 -14
  240. package/dist/clients/deps/vscode-jsonrpc.js +0 -1
  241. package/dist/clients/deps/web-tree-sitter.js +0 -24
  242. package/dist/clients/diagnostic-dispositions.js +0 -630
  243. package/dist/clients/diagnostic-line-freshness.js +0 -305
  244. package/dist/clients/diagnostic-logger.js +0 -73
  245. package/dist/clients/diagnostic-tracker.js +0 -105
  246. package/dist/clients/diagnostics-publish.js +0 -230
  247. package/dist/clients/dispatch/ast-grep-catalog.js +0 -65
  248. package/dist/clients/dispatch/auxiliary-lsp.js +0 -343
  249. package/dist/clients/dispatch/collect-later-tier.js +0 -35
  250. package/dist/clients/dispatch/diagnostic-taxonomy.js +0 -66
  251. package/dist/clients/dispatch/dispatcher.js +0 -1269
  252. package/dist/clients/dispatch/fact-provider-types.js +0 -1
  253. package/dist/clients/dispatch/fact-rule-runner.js +0 -17
  254. package/dist/clients/dispatch/fact-runner.js +0 -30
  255. package/dist/clients/dispatch/fact-scheduler.js +0 -68
  256. package/dist/clients/dispatch/fact-store.js +0 -377
  257. package/dist/clients/dispatch/facts/comment-facts.js +0 -22
  258. package/dist/clients/dispatch/facts/file-content.js +0 -19
  259. package/dist/clients/dispatch/facts/function-facts.js +0 -348
  260. package/dist/clients/dispatch/facts/import-facts.js +0 -204
  261. package/dist/clients/dispatch/facts/tree-sitter-facts.js +0 -34
  262. package/dist/clients/dispatch/facts/try-catch-facts.js +0 -119
  263. package/dist/clients/dispatch/finding-policy.js +0 -339
  264. package/dist/clients/dispatch/indent-detect.js +0 -417
  265. package/dist/clients/dispatch/inline-suppressions.js +0 -89
  266. package/dist/clients/dispatch/integration.js +0 -2377
  267. package/dist/clients/dispatch/lazy.js +0 -11
  268. package/dist/clients/dispatch/pending-runner-findings.js +0 -87
  269. package/dist/clients/dispatch/plan.js +0 -278
  270. package/dist/clients/dispatch/priorities.js +0 -20
  271. package/dist/clients/dispatch/rule-id-normalize.js +0 -50
  272. package/dist/clients/dispatch/rule-ignores.js +0 -69
  273. package/dist/clients/dispatch/rule-policy.js +0 -135
  274. package/dist/clients/dispatch/rules/async-noise.js +0 -40
  275. package/dist/clients/dispatch/rules/async-unnecessary-wrapper.js +0 -27
  276. package/dist/clients/dispatch/rules/cors-wildcard.js +0 -54
  277. package/dist/clients/dispatch/rules/error-obscuring.js +0 -32
  278. package/dist/clients/dispatch/rules/error-swallowing.js +0 -31
  279. package/dist/clients/dispatch/rules/framework-call-noise.js +0 -67
  280. package/dist/clients/dispatch/rules/high-complexity.js +0 -72
  281. package/dist/clients/dispatch/rules/high-fan-out.js +0 -74
  282. package/dist/clients/dispatch/rules/high-import-coupling.js +0 -37
  283. package/dist/clients/dispatch/rules/missing-error-propagation.js +0 -62
  284. package/dist/clients/dispatch/rules/no-commented-credentials.js +0 -52
  285. package/dist/clients/dispatch/rules/pass-through-wrappers.js +0 -42
  286. package/dist/clients/dispatch/rules/placeholder-comments.js +0 -40
  287. package/dist/clients/dispatch/rules/unsafe-boundary.js +0 -126
  288. package/dist/clients/dispatch/runner-context.js +0 -52
  289. package/dist/clients/dispatch/runners/actionlint.js +0 -111
  290. package/dist/clients/dispatch/runners/ast-grep-napi.js +0 -1196
  291. package/dist/clients/dispatch/runners/biome-check.js +0 -296
  292. package/dist/clients/dispatch/runners/cpp-check.js +0 -219
  293. package/dist/clients/dispatch/runners/credo.js +0 -82
  294. package/dist/clients/dispatch/runners/cue-vet.js +0 -416
  295. package/dist/clients/dispatch/runners/dart-analyze.js +0 -183
  296. package/dist/clients/dispatch/runners/detekt.js +0 -176
  297. package/dist/clients/dispatch/runners/dotnet-build.js +0 -164
  298. package/dist/clients/dispatch/runners/elixir-check.js +0 -195
  299. package/dist/clients/dispatch/runners/eslint.js +0 -137
  300. package/dist/clients/dispatch/runners/fact-rules.js +0 -29
  301. package/dist/clients/dispatch/runners/fish-indent.js +0 -69
  302. package/dist/clients/dispatch/runners/gleam-check.js +0 -167
  303. package/dist/clients/dispatch/runners/go-vet.js +0 -104
  304. package/dist/clients/dispatch/runners/golangci-lint.js +0 -135
  305. package/dist/clients/dispatch/runners/hadolint.js +0 -91
  306. package/dist/clients/dispatch/runners/helm-lint.js +0 -171
  307. package/dist/clients/dispatch/runners/helm-render.js +0 -940
  308. package/dist/clients/dispatch/runners/htmlhint.js +0 -117
  309. package/dist/clients/dispatch/runners/index.js +0 -108
  310. package/dist/clients/dispatch/runners/javac.js +0 -99
  311. package/dist/clients/dispatch/runners/ktlint.js +0 -110
  312. package/dist/clients/dispatch/runners/lsp.js +0 -379
  313. package/dist/clients/dispatch/runners/markdownlint.js +0 -167
  314. package/dist/clients/dispatch/runners/mypy.js +0 -102
  315. package/dist/clients/dispatch/runners/oxlint.js +0 -414
  316. package/dist/clients/dispatch/runners/php-lint.js +0 -85
  317. package/dist/clients/dispatch/runners/phpstan.js +0 -120
  318. package/dist/clients/dispatch/runners/prisma-validate.js +0 -62
  319. package/dist/clients/dispatch/runners/psscriptanalyzer.js +0 -445
  320. package/dist/clients/dispatch/runners/pyright.js +0 -169
  321. package/dist/clients/dispatch/runners/rubocop.js +0 -99
  322. package/dist/clients/dispatch/runners/ruff.js +0 -88
  323. package/dist/clients/dispatch/runners/rust-clippy.js +0 -256
  324. package/dist/clients/dispatch/runners/shellcheck.js +0 -173
  325. package/dist/clients/dispatch/runners/shfmt.js +0 -102
  326. package/dist/clients/dispatch/runners/spellcheck.js +0 -128
  327. package/dist/clients/dispatch/runners/spotbugs.js +0 -259
  328. package/dist/clients/dispatch/runners/sqlfluff.js +0 -183
  329. package/dist/clients/dispatch/runners/stylelint.js +0 -166
  330. package/dist/clients/dispatch/runners/swiftlint.js +0 -163
  331. package/dist/clients/dispatch/runners/taplo.js +0 -174
  332. package/dist/clients/dispatch/runners/terragrunt.js +0 -168
  333. package/dist/clients/dispatch/runners/tflint.js +0 -125
  334. package/dist/clients/dispatch/runners/tree-sitter.js +0 -643
  335. package/dist/clients/dispatch/runners/trivy-config.js +0 -253
  336. package/dist/clients/dispatch/runners/utils/availability-policy.js +0 -496
  337. package/dist/clients/dispatch/runners/utils/candidate-probe.js +0 -90
  338. package/dist/clients/dispatch/runners/utils/diagnostic-parsers.js +0 -95
  339. package/dist/clients/dispatch/runners/utils/lazy-installer.js +0 -274
  340. package/dist/clients/dispatch/runners/utils/runner-helpers.js +0 -1701
  341. package/dist/clients/dispatch/runners/utils/spawn-outcome.js +0 -101
  342. package/dist/clients/dispatch/runners/utils/tool-failure.js +0 -235
  343. package/dist/clients/dispatch/runners/utils/toolchain-availability.js +0 -169
  344. package/dist/clients/dispatch/runners/utils.js +0 -15
  345. package/dist/clients/dispatch/runners/vale.js +0 -128
  346. package/dist/clients/dispatch/runners/yaml-rule-parser.js +0 -242
  347. package/dist/clients/dispatch/runners/yamllint.js +0 -95
  348. package/dist/clients/dispatch/runners/zig-check.js +0 -79
  349. package/dist/clients/dispatch/suppress-writer.js +0 -79
  350. package/dist/clients/dispatch/tool-profile.js +0 -30
  351. package/dist/clients/dispatch/types.js +0 -21
  352. package/dist/clients/dispatch/utils/format-utils.js +0 -45
  353. package/dist/clients/dispatch/utils/lsp-diagnostics.js +0 -35
  354. package/dist/clients/disposition-logger.js +0 -32
  355. package/dist/clients/disposition-publish.js +0 -124
  356. package/dist/clients/durable-store.js +0 -97
  357. package/dist/clients/effective-config.js +0 -415
  358. package/dist/clients/env-utils.js +0 -83
  359. package/dist/clients/error-class.js +0 -23
  360. package/dist/clients/eval-timestamp.js +0 -17
  361. package/dist/clients/event-loop-hold.js +0 -274
  362. package/dist/clients/event-loop-monitor.js +0 -250
  363. package/dist/clients/extension-log.js +0 -504
  364. package/dist/clients/extension-mode.js +0 -73
  365. package/dist/clients/feature-hints.js +0 -103
  366. package/dist/clients/file-kinds.js +0 -412
  367. package/dist/clients/file-role.js +0 -134
  368. package/dist/clients/file-time.js +0 -160
  369. package/dist/clients/file-utils.js +0 -1032
  370. package/dist/clients/finding-delivery-gate.js +0 -494
  371. package/dist/clients/finding-identity.js +0 -88
  372. package/dist/clients/fix-worklog.js +0 -103
  373. package/dist/clients/format-events-publish.js +0 -343
  374. package/dist/clients/format-service.js +0 -222
  375. package/dist/clients/formatters-lazy.js +0 -9
  376. package/dist/clients/formatters.js +0 -2032
  377. package/dist/clients/freshness-cadence.js +0 -17
  378. package/dist/clients/freshness.js +0 -38
  379. package/dist/clients/generated-artifacts.js +0 -394
  380. package/dist/clients/generation-guard.js +0 -215
  381. package/dist/clients/git-guard.js +0 -1136
  382. package/dist/clients/git-tracked-ignore.js +0 -243
  383. package/dist/clients/gitleaks-client.js +0 -509
  384. package/dist/clients/go-client.js +0 -104
  385. package/dist/clients/govulncheck-client.js +0 -605
  386. package/dist/clients/gradle-ktfmt-style.js +0 -348
  387. package/dist/clients/grammar-source.js +0 -465
  388. package/dist/clients/gzip-stage-write.js +0 -135
  389. package/dist/clients/hashline-anchor.js +0 -424
  390. package/dist/clients/hook-budgets.js +0 -76
  391. package/dist/clients/host-edit-normalize.js +0 -140
  392. package/dist/clients/host-ports.js +0 -39
  393. package/dist/clients/indent-retarget.js +0 -154
  394. package/dist/clients/inline-blocker-dispositions.js +0 -186
  395. package/dist/clients/install-diagnostics.js +0 -156
  396. package/dist/clients/installer/index.js +0 -5416
  397. package/dist/clients/installer/managed-tool-refresh-session.js +0 -58
  398. package/dist/clients/installer/managed-tool-refresh.js +0 -783
  399. package/dist/clients/instance-reaper-state.js +0 -7
  400. package/dist/clients/instance-reaper.js +0 -1137
  401. package/dist/clients/instance-registry-lock.js +0 -145
  402. package/dist/clients/instance-registry.js +0 -773
  403. package/dist/clients/jscpd-client.js +0 -378
  404. package/dist/clients/json-cache-read.js +0 -65
  405. package/dist/clients/knip-client.js +0 -788
  406. package/dist/clients/language-policy.js +0 -252
  407. package/dist/clients/language-profile.js +0 -361
  408. package/dist/clients/language-registry.js +0 -603
  409. package/dist/clients/latency-logger.js +0 -727
  410. package/dist/clients/lazy-import.js +0 -21
  411. package/dist/clients/ledger-bounds.js +0 -54
  412. package/dist/clients/lens-config.js +0 -404
  413. package/dist/clients/lens-engine.js +0 -358
  414. package/dist/clients/lens-events.js +0 -125
  415. package/dist/clients/lens-flag-registry.js +0 -467
  416. package/dist/clients/lens-map.js +0 -1156
  417. package/dist/clients/live-bus-emitter.js +0 -74
  418. package/dist/clients/log-cleanup.js +0 -222
  419. package/dist/clients/lsp/aggregation.js +0 -178
  420. package/dist/clients/lsp/cascade-tier.js +0 -421
  421. package/dist/clients/lsp/client.js +0 -4593
  422. package/dist/clients/lsp/config.js +0 -691
  423. package/dist/clients/lsp/content-limits.js +0 -41
  424. package/dist/clients/lsp/diagnostic-binding.js +0 -225
  425. package/dist/clients/lsp/document-drift.js +0 -467
  426. package/dist/clients/lsp/edits.js +0 -1219
  427. package/dist/clients/lsp/index.js +0 -8305
  428. package/dist/clients/lsp/inferred-project.js +0 -216
  429. package/dist/clients/lsp/jvm-runtime.js +0 -298
  430. package/dist/clients/lsp/language.js +0 -63
  431. package/dist/clients/lsp/launch.js +0 -746
  432. package/dist/clients/lsp/lombok.js +0 -158
  433. package/dist/clients/lsp/path-utils.js +0 -5
  434. package/dist/clients/lsp/pending-aux-coverage.js +0 -251
  435. package/dist/clients/lsp/position-encoding.js +0 -61
  436. package/dist/clients/lsp/ruby-drive-dirs.js +0 -83
  437. package/dist/clients/lsp/server.js +0 -3290
  438. package/dist/clients/lsp/session-roots.js +0 -192
  439. package/dist/clients/lsp/spawn-history.js +0 -17
  440. package/dist/clients/lsp/sync-kind.js +0 -56
  441. package/dist/clients/lsp/tsserver-sync.js +0 -332
  442. package/dist/clients/lsp/wait-policy/capability-snapshot.js +0 -1
  443. package/dist/clients/lsp/wait-policy/classification.js +0 -85
  444. package/dist/clients/lsp/wait-policy/index.js +0 -10
  445. package/dist/clients/lsp/wait-policy/strategies.js +0 -392
  446. package/dist/clients/lsp/watch-queue.js +0 -61
  447. package/dist/clients/lsp/workspace-diagnostics-cache.js +0 -639
  448. package/dist/clients/lsp/workspace-diagnostics-session.js +0 -30
  449. package/dist/clients/lsp/workspace-sweep-hold.js +0 -184
  450. package/dist/clients/lsp-budget.js +0 -186
  451. package/dist/clients/lsp-document-symbols.js +0 -110
  452. package/dist/clients/lsp-lazy.js +0 -9
  453. package/dist/clients/lsp-mutation.js +0 -396
  454. package/dist/clients/lsp-status.js +0 -59
  455. package/dist/clients/map-with-concurrency.js +0 -40
  456. package/dist/clients/mcp/analyze.js +0 -420
  457. package/dist/clients/mcp/host-shim.js +0 -31
  458. package/dist/clients/mcp/ipc.js +0 -523
  459. package/dist/clients/mcp/review.js +0 -197
  460. package/dist/clients/mcp/session.js +0 -412
  461. package/dist/clients/memory-sampler.js +0 -208
  462. package/dist/clients/message-end-attribution.js +0 -30
  463. package/dist/clients/metrics-client.js +0 -107
  464. package/dist/clients/metrics-history.js +0 -327
  465. package/dist/clients/middle-man-analysis.js +0 -263
  466. package/dist/clients/model-provider.js +0 -53
  467. package/dist/clients/module-report-lsp.js +0 -189
  468. package/dist/clients/module-report.js +0 -2150
  469. package/dist/clients/mutating-tool.js +0 -651
  470. package/dist/clients/mutation-attribution.js +0 -368
  471. package/dist/clients/mutation-bridge.js +0 -240
  472. package/dist/clients/ndjson-logger.js +0 -734
  473. package/dist/clients/observed-mutation-sources.js +0 -101
  474. package/dist/clients/observed-mutation.js +0 -1253
  475. package/dist/clients/oldtext-autopatch.js +0 -128
  476. package/dist/clients/opaque-mutation-scan.js +0 -496
  477. package/dist/clients/opengrep-client.js +0 -333
  478. package/dist/clients/opengrep-config.js +0 -76
  479. package/dist/clients/package-manager.js +0 -607
  480. package/dist/clients/package-root.js +0 -38
  481. package/dist/clients/partial-edit-apply.js +0 -439
  482. package/dist/clients/path-attribution-telemetry.js +0 -43
  483. package/dist/clients/path-keyed-map.js +0 -108
  484. package/dist/clients/path-utils.js +0 -1244
  485. package/dist/clients/performance-report.js +0 -331
  486. package/dist/clients/persist-debounce.js +0 -70
  487. package/dist/clients/persistent-reverify.js +0 -271
  488. package/dist/clients/php-cs-fixer-config.js +0 -119
  489. package/dist/clients/pipeline.js +0 -1480
  490. package/dist/clients/post-autofix-notice.js +0 -37
  491. package/dist/clients/print-mode.js +0 -21
  492. package/dist/clients/probe-home-state.js +0 -228
  493. package/dist/clients/process-bridge.js +0 -66
  494. package/dist/clients/process-singletons.js +0 -210
  495. package/dist/clients/process-snapshot.js +0 -68
  496. package/dist/clients/project-changes.js +0 -181
  497. package/dist/clients/project-conventions.js +0 -171
  498. package/dist/clients/project-diagnostics/cache.js +0 -137
  499. package/dist/clients/project-diagnostics/extractors.js +0 -109
  500. package/dist/clients/project-diagnostics/fresh-fetch.js +0 -668
  501. package/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +0 -118
  502. package/dist/clients/project-diagnostics/runner-adapters/dead-code.js +0 -47
  503. package/dist/clients/project-diagnostics/runner-adapters/gitleaks.js +0 -40
  504. package/dist/clients/project-diagnostics/runner-adapters/govulncheck.js +0 -34
  505. package/dist/clients/project-diagnostics/runner-adapters/jscpd.js +0 -38
  506. package/dist/clients/project-diagnostics/runner-adapters/knip.js +0 -47
  507. package/dist/clients/project-diagnostics/runner-adapters/madge.js +0 -48
  508. package/dist/clients/project-diagnostics/runner-adapters/opengrep.js +0 -40
  509. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +0 -127
  510. package/dist/clients/project-diagnostics/runner-adapters/trivy.js +0 -81
  511. package/dist/clients/project-diagnostics/scanner.js +0 -520
  512. package/dist/clients/project-diagnostics/types.js +0 -1
  513. package/dist/clients/project-lens-config.js +0 -807
  514. package/dist/clients/project-report.js +0 -701
  515. package/dist/clients/project-scale.js +0 -237
  516. package/dist/clients/project-scan-policy.js +0 -11
  517. package/dist/clients/project-snapshot-fingerprint.js +0 -48
  518. package/dist/clients/project-snapshot-persist-worker.js +0 -20
  519. package/dist/clients/project-snapshot.js +0 -1653
  520. package/dist/clients/project-trust.js +0 -181
  521. package/dist/clients/python-environment.js +0 -217
  522. package/dist/clients/python-provenance.js +0 -639
  523. package/dist/clients/quiet-window-config.js +0 -47
  524. package/dist/clients/quiet-window.js +0 -236
  525. package/dist/clients/read-bridge.js +0 -139
  526. package/dist/clients/read-expansion.js +0 -266
  527. package/dist/clients/read-guard-logger.js +0 -251
  528. package/dist/clients/read-guard-tool-lines.js +0 -1306
  529. package/dist/clients/read-guard.js +0 -1561
  530. package/dist/clients/recent-touches.js +0 -240
  531. package/dist/clients/redact/secrets.js +0 -449
  532. package/dist/clients/resource-sampler.js +0 -628
  533. package/dist/clients/reverse-deps.js +0 -270
  534. package/dist/clients/review-graph/builder.js +0 -5126
  535. package/dist/clients/review-graph/format.js +0 -33
  536. package/dist/clients/review-graph/git-identity.js +0 -163
  537. package/dist/clients/review-graph/import-resolvers.js +0 -481
  538. package/dist/clients/review-graph/persist-worker.js +0 -10
  539. package/dist/clients/review-graph/query.js +0 -244
  540. package/dist/clients/review-graph/revision-drift.js +0 -21
  541. package/dist/clients/review-graph/service.js +0 -96
  542. package/dist/clients/review-graph/shared-extraction-ir.js +0 -82
  543. package/dist/clients/review-graph/symbol-id.js +0 -103
  544. package/dist/clients/review-graph/tsconfig-paths.js +0 -299
  545. package/dist/clients/review-graph/types.js +0 -1
  546. package/dist/clients/review-graph/workspace-modules.js +0 -449
  547. package/dist/clients/review-graph-logger.js +0 -81
  548. package/dist/clients/ruff-client.js +0 -179
  549. package/dist/clients/rules-scanner.js +0 -131
  550. package/dist/clients/run-duration.js +0 -55
  551. package/dist/clients/runtime-agent-end.js +0 -746
  552. package/dist/clients/runtime-config.js +0 -77
  553. package/dist/clients/runtime-context.js +0 -211
  554. package/dist/clients/runtime-coordinator.js +0 -1324
  555. package/dist/clients/runtime-session.js +0 -2485
  556. package/dist/clients/runtime-tool-call.js +0 -1295
  557. package/dist/clients/runtime-tool-result.js +0 -2049
  558. package/dist/clients/runtime-turn.js +0 -3767
  559. package/dist/clients/rust-client.js +0 -97
  560. package/dist/clients/safe-spawn.js +0 -2357
  561. package/dist/clients/sanitize.js +0 -286
  562. package/dist/clients/scan-utils.js +0 -25
  563. package/dist/clients/scratch-tree-policy.js +0 -165
  564. package/dist/clients/search-read-registration.js +0 -94
  565. package/dist/clients/secret-findings.js +0 -114
  566. package/dist/clients/security-scan-client.js +0 -352
  567. package/dist/clients/session-event-guard.js +0 -297
  568. package/dist/clients/session-lifecycle.js +0 -484
  569. package/dist/clients/session-start-observability.js +0 -94
  570. package/dist/clients/session-state-store.js +0 -101
  571. package/dist/clients/session-summary.js +0 -15
  572. package/dist/clients/sessionstart-logger.js +0 -27
  573. package/dist/clients/sg-runner.js +0 -876
  574. package/dist/clients/sgconfig.js +0 -347
  575. package/dist/clients/shared-checkout-guard.js +0 -338
  576. package/dist/clients/single-flight.js +0 -158
  577. package/dist/clients/situational-tool-telemetry.js +0 -108
  578. package/dist/clients/skills-resolver.js +0 -141
  579. package/dist/clients/slow-fs.js +0 -138
  580. package/dist/clients/smells-rollup.js +0 -231
  581. package/dist/clients/source-filter.js +0 -596
  582. package/dist/clients/source-walker.js +0 -211
  583. package/dist/clients/spawn-output-cap.js +0 -120
  584. package/dist/clients/spawn-timeout-cooldown.js +0 -110
  585. package/dist/clients/stale-marker.js +0 -17
  586. package/dist/clients/startup-scan.js +0 -400
  587. package/dist/clients/startup-timing.js +0 -130
  588. package/dist/clients/string-utils.js +0 -33
  589. package/dist/clients/subagent-mode.js +0 -111
  590. package/dist/clients/symbol-containment.js +0 -24
  591. package/dist/clients/symbol-types.js +0 -5
  592. package/dist/clients/test-runner-client.js +0 -2507
  593. package/dist/clients/test-runner-delivery.js +0 -287
  594. package/dist/clients/todo-scanner.js +0 -229
  595. package/dist/clients/tool-agreement.js +0 -423
  596. package/dist/clients/tool-config.js +0 -249
  597. package/dist/clients/tool-cwd.js +0 -270
  598. package/dist/clients/tool-definition.js +0 -47
  599. package/dist/clients/tool-event.js +0 -105
  600. package/dist/clients/tool-policy.js +0 -2755
  601. package/dist/clients/tool-probe.js +0 -53
  602. package/dist/clients/tool-render.js +0 -156
  603. package/dist/clients/tool-set-policy.js +0 -118
  604. package/dist/clients/tree-sitter-cache.js +0 -364
  605. package/dist/clients/tree-sitter-client.js +0 -4195
  606. package/dist/clients/tree-sitter-logger.js +0 -100
  607. package/dist/clients/tree-sitter-navigator.js +0 -269
  608. package/dist/clients/tree-sitter-query-loader.js +0 -569
  609. package/dist/clients/tree-sitter-shared.js +0 -158
  610. package/dist/clients/tree-sitter-symbol-extractor.js +0 -1265
  611. package/dist/clients/trivy-client.js +0 -467
  612. package/dist/clients/tui-fit.js +0 -50
  613. package/dist/clients/turn-context.js +0 -52
  614. package/dist/clients/turn-end/lane.js +0 -51
  615. package/dist/clients/turn-end/lanes/govulncheck.js +0 -112
  616. package/dist/clients/turn-end/lanes/secrets.js +0 -204
  617. package/dist/clients/turn-summary-render.js +0 -72
  618. package/dist/clients/turn-summary.js +0 -132
  619. package/dist/clients/typos-config.js +0 -29
  620. package/dist/clients/user-notify.js +0 -51
  621. package/dist/clients/vanished-instance-marker.js +0 -57
  622. package/dist/clients/warm-attach.js +0 -305
  623. package/dist/clients/widget-state.js +0 -1808
  624. package/dist/clients/word-index-logger.js +0 -49
  625. package/dist/clients/word-index-store.js +0 -459
  626. package/dist/clients/word-index.js +0 -2080
  627. package/dist/clients/workspace-topology.js +0 -443
  628. package/dist/clients/write-ordering-guard.js +0 -65
  629. package/dist/clients/zizmor-config.js +0 -340
  630. package/dist/i18n.js +0 -69
  631. package/dist/mcp/build-staleness.js +0 -124
  632. package/dist/scripts/lib/process-scan.mjs +0 -583
  633. package/dist/scripts/lib/skills-predicate.mjs +0 -129
  634. package/dist/scripts/lib/web-tree-sitter-dir.mjs +0 -123
  635. package/dist/tools/activate-tools.js +0 -87
  636. package/dist/tools/ast-grep-outline.js +0 -137
  637. package/dist/tools/ast-grep-replace.js +0 -244
  638. package/dist/tools/ast-grep-search.js +0 -762
  639. package/dist/tools/effective-config.js +0 -90
  640. package/dist/tools/lens-diagnostic-mark.js +0 -375
  641. package/dist/tools/lens-diagnostics.js +0 -2571
  642. package/dist/tools/lsp-diagnostics.js +0 -1745
  643. package/dist/tools/lsp-navigation.js +0 -1367
  644. package/dist/tools/lsp-structured-output.js +0 -294
  645. package/dist/tools/module-report.js +0 -382
  646. package/dist/tools/project-report.js +0 -86
  647. package/dist/tools/render-compact.js +0 -374
  648. package/dist/tools/scan-progress.js +0 -53
  649. package/dist/tools/shared.js +0 -29
  650. package/dist/tools/symbol-search.js +0 -155
@@ -1,1306 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import * as nodeFs from "node:fs";
3
- import { BoundedFifoMap } from "./bounded-cache.js";
4
- import { hostWouldApplyOldText, normalizeForGuardMatch, normalizeToLF, stripBom, } from "./host-edit-normalize.js";
5
- import { classifyMutatingTool } from "./mutating-tool.js";
6
- import { isExactAppliedRetry, } from "./partial-edit-apply.js";
7
- import { boundedEditIndexes, createReadGuardEditBatchSummary, logReadGuardEvent, } from "./read-guard-logger.js";
8
- // Track repeated oldtext_not_found failures per (filePath, preview) to escalate messages.
9
- export const MAX_FAILURE_TRACKER_SIZE = 200;
10
- const recentOldTextFailures = new BoundedFifoMap(MAX_FAILURE_TRACKER_SIZE);
11
- const REPEAT_FAILURE_TTL_MS = 300_000;
12
- function trackOldTextFailure(filePath, preview) {
13
- const key = `${filePath}::${preview}`;
14
- const now = Date.now();
15
- const prev = recentOldTextFailures.get(key);
16
- const count = prev && now - prev.lastTs < REPEAT_FAILURE_TTL_MS ? prev.count + 1 : 1;
17
- recentOldTextFailures.set(key, { count, lastTs: now });
18
- return count;
19
- }
20
- /** #2442 test-only: exercise the bounded failure tracker's capacity
21
- * eviction directly, without a full read-guard preflight call. */
22
- export function _trackOldTextFailureForTests(filePath, preview) {
23
- return trackOldTextFailure(filePath, preview);
24
- }
25
- /** #2442 test-only: was this (filePath, preview) pair's escalation count
26
- * reset by capacity eviction? (A fresh `_trackOldTextFailureForTests` call
27
- * answering 1 again, after previously answering >1, means yes — but this
28
- * reads the tracker's residency directly instead.) */
29
- export function _hasOldTextFailureForTests(filePath, preview) {
30
- return recentOldTextFailures.has(`${filePath}::${preview}`);
31
- }
32
- function findFirstLineOfOldText(content, oldText) {
33
- const firstLine = oldText.replace(/\r\n/g, "\n").split("\n")[0].trim();
34
- if (firstLine.length < 5)
35
- return undefined;
36
- const lines = content.split("\n");
37
- for (let i = 0; i < lines.length; i++) {
38
- if (lines[i].trim() === firstLine)
39
- return i + 1;
40
- }
41
- return undefined;
42
- }
43
- function tokenizeForSimilarity(text) {
44
- return text.toLowerCase().match(/[a-z0-9_]+/g) ?? [];
45
- }
46
- /** Jaccard similarity over identifier/number tokens (whitespace + punctuation insensitive). */
47
- function tokenSimilarity(a, b) {
48
- const ta = new Set(tokenizeForSimilarity(a));
49
- const tb = new Set(tokenizeForSimilarity(b));
50
- if (ta.size === 0 || tb.size === 0)
51
- return 0;
52
- let intersection = 0;
53
- for (const token of ta)
54
- if (tb.has(token))
55
- intersection += 1;
56
- return intersection / (ta.size + tb.size - intersection);
57
- }
58
- /**
59
- * "Did you mean?" recovery: when an oldText line can't be found, surface the
60
- * closest *current* file lines (by token similarity) so the model can rebuild
61
- * its edit from verbatim text in one turn instead of re-reading blind. Scans a
62
- * ±window around `nearLine` when known (the first-line locator), else the whole
63
- * file. Returns the top matches above `minScore`, with their real line numbers.
64
- *
65
- * Scores in normalized space but returns only `{ line, score }` — the caller
66
- * renders the text from a structurally-aligned RAW view so a suggestion can
67
- * never quote the normalized projection (#1050). NFKC folds CJK full-width
68
- * punctuation (`:`→`:`, `,`→`,`, `;`→`;`) and HOST_UNICODE_DASHES folds
69
- * `—`→`-`, so a suggestion rendered from normalized content told the agent to
70
- * copy bytes the file does not contain; the host's edit tool then fuzzy-matched
71
- * it and wrote the folded form onto the touched line. Normalization here is
72
- * comparison-only, exactly as everywhere else in this file.
73
- */
74
- function findSimilarLines(content, target, options = {}) {
75
- const { nearLine, window = 60, max = 3, minScore = 0.5 } = options;
76
- const needle = target.trim();
77
- if (needle.length < 4)
78
- return [];
79
- const lines = content.split("\n");
80
- const start = nearLine ? Math.max(0, nearLine - 1 - window) : 0;
81
- const end = nearLine
82
- ? Math.min(lines.length, nearLine - 1 + window)
83
- : lines.length;
84
- const scored = [];
85
- for (let i = start; i < end; i += 1) {
86
- const text = lines[i];
87
- if (text.trim() === "")
88
- continue;
89
- const score = tokenSimilarity(needle, text);
90
- if (score >= minScore)
91
- scored.push({ line: i + 1, score });
92
- }
93
- scored.sort((a, b) => b.score - a.score);
94
- return scored.slice(0, max);
95
- }
96
- /**
97
- * Render did-you-mean rows from the file's real characters rather than the
98
- * normalized match space the line numbers were scored in. Taking only
99
- * `{ line }` from the scan makes quoting normalized text structurally
100
- * impossible (#1050).
101
- *
102
- * `rawLineAligned` must be `normalizeToLF(stripBom(raw).text)`: the same
103
- * STRUCTURAL normalization `normalizeForGuardMatch` applies (so line indices
104
- * cross-index 1:1 even for lone-CR or BOM files) but none of its CHARACTER
105
- * folding, so full-width punctuation, smart quotes, and NBSP survive.
106
- */
107
- function formatSimilarLines(suggestions, rawLineAligned) {
108
- const rawLines = rawLineAligned.split("\n");
109
- const pad = (n) => String(n).padStart(4, " ");
110
- const rows = suggestions.map(({ line }) => ` ${pad(line)} │ ${(rawLines[line - 1] ?? "").trimEnd()}`);
111
- return `\n\nDid you mean one of these current lines?\n${rows.join("\n")}`;
112
- }
113
- export function countFileLines(filePath) {
114
- try {
115
- const content = nodeFs.readFileSync(filePath, "utf-8");
116
- if (content.length === 0)
117
- return 1;
118
- return content.split(/\r?\n/).length;
119
- }
120
- catch {
121
- return 1;
122
- }
123
- }
124
- // Match the host edit tool's fuzzy-match space (NFKC + smart quotes/dashes/
125
- // spaces + BOM + lone-CR), so the guard resolves oldText -> range exactly where
126
- // the host would apply it instead of false-blocking valid edits (#257).
127
- //
128
- // This is also where #505's "confusable-hyphen normalization" bundled item
129
- // lives: normalizeForGuardMatch folds HOST_UNICODE_DASHES (U+2010, U+2011,
130
- // U+2012, U+2013, U+2014, U+2015, U+2212 -> ASCII '-') before either side of
131
- // the comparison below, so it runs on the PRIMARY match here, before any of
132
- // the Tier A/B/C fallbacks in tryCorrectIndentationMismatchFromContent are
133
- // even reached. Comparison-only, same as every tier below it — the bytes
134
- // actually written on a successful edit are always the caller's original
135
- // oldText/newText (see resolveOldTextEdits / applyPartiallyApplicableEdits),
136
- // never this normalized form.
137
- function normalizeContent(text) {
138
- return normalizeForGuardMatch(text);
139
- }
140
- function lineNumberAt(content, index) {
141
- return content.substring(0, index).split("\n").length;
142
- }
143
- /**
144
- * Deduplicated overlapping pairs, in candidate order, for the overlap error
145
- * message. Each overlapping edit appears in exactly one pair where possible;
146
- * a chain (A-B-C all overlapping) reports A-B and A-C.
147
- */
148
- function overlapPairs(candidates) {
149
- const pairs = [];
150
- const reported = new Set();
151
- for (let i = 0; i < candidates.length; i += 1) {
152
- const a = candidates[i];
153
- if (reported.has(a))
154
- continue;
155
- for (let j = i + 1; j < candidates.length; j += 1) {
156
- const b = candidates[j];
157
- if (reported.has(b))
158
- continue;
159
- if (b.spanStart < a.spanEnd && a.spanStart < b.spanEnd) {
160
- pairs.push([a, b]);
161
- reported.add(a);
162
- reported.add(b);
163
- break;
164
- }
165
- }
166
- }
167
- return pairs;
168
- }
169
- /** ✅ note appended to preflight/composed messages for recognized retries. */
170
- export function formatAlreadyAppliedNotes(editIndexes) {
171
- if (!editIndexes || editIndexes.length === 0)
172
- return "";
173
- const list = boundedEditIndexes(editIndexes)
174
- .map((index) => `edits[${index}]`)
175
- .join(", ");
176
- const suffix = editIndexes.length === 1 ? "was" : "were";
177
- const pronoun = editIndexes.length === 1 ? "it" : "them";
178
- return `\n\n✅ ${list} ${suffix} already applied by an identical earlier edit — the file already contains the result. Do NOT resubmit ${pronoun}.`;
179
- }
180
- function findOccurrenceLines(content, needle) {
181
- const lines = [];
182
- let pos = 0;
183
- while (pos < content.length) {
184
- const idx = content.indexOf(needle, pos);
185
- if (idx === -1)
186
- break;
187
- lines.push(lineNumberAt(content, idx));
188
- pos = idx + needle.length;
189
- }
190
- return lines;
191
- }
192
- function formatOccurrenceContext(content, occurrenceLines, matchSpanLines, maxOccurrences = 5) {
193
- const fileLines = content.split("\n");
194
- const shown = occurrenceLines.slice(0, maxOccurrences);
195
- const extra = occurrenceLines.length - shown.length;
196
- const pad = (n) => String(n).padStart(4, " ");
197
- const blocks = shown.map((startLine) => {
198
- const endLine = startLine + matchSpanLines - 1;
199
- const before = startLine > 1 ? fileLines[startLine - 2] : undefined;
200
- const after = endLine < fileLines.length ? fileLines[endLine] : undefined;
201
- const lines = [` • Line ${startLine}:`];
202
- if (before !== undefined)
203
- lines.push(` ${pad(startLine - 1)} │ ${before}`);
204
- if (matchSpanLines === 1) {
205
- lines.push(` ${pad(startLine)} │ ${fileLines[startLine - 1] ?? ""} ← match`);
206
- }
207
- else {
208
- lines.push(` ${pad(startLine)} │ ${fileLines[startLine - 1] ?? ""} ← match start`);
209
- if (matchSpanLines > 2) {
210
- lines.push(` ${pad(0)} │ … (${matchSpanLines - 2} more line${matchSpanLines - 2 === 1 ? "" : "s"})`);
211
- }
212
- lines.push(` ${pad(endLine)} │ ${fileLines[endLine - 1] ?? ""} ← match end`);
213
- }
214
- if (after !== undefined)
215
- lines.push(` ${pad(endLine + 1)} │ ${after}`);
216
- return lines.join("\n");
217
- });
218
- const tail = extra > 0
219
- ? `\n • … and ${extra} more occurrence${extra === 1 ? "" : "s"}`
220
- : "";
221
- return blocks.join("\n") + tail;
222
- }
223
- function countRawOccurrences(content, needle) {
224
- if (!needle)
225
- return 0;
226
- let count = 0;
227
- let pos = 0;
228
- while (pos < content.length) {
229
- const idx = content.indexOf(needle, pos);
230
- if (idx === -1)
231
- break;
232
- count += 1;
233
- pos = idx + needle.length;
234
- }
235
- return count;
236
- }
237
- function exactOldTextForApply(rawContentLf, normalizedContent, oldText, candidate) {
238
- const oldTextLf = oldText.replace(/\r\n/g, "\n");
239
- if (countRawOccurrences(rawContentLf, oldTextLf) === 1) {
240
- const start = rawContentLf.indexOf(oldTextLf);
241
- return { text: oldTextLf, start, end: start + oldTextLf.length };
242
- }
243
- if (candidate !== oldTextLf &&
244
- countRawOccurrences(rawContentLf, candidate) === 1) {
245
- const start = rawContentLf.indexOf(candidate);
246
- return { text: candidate, start, end: start + candidate.length };
247
- }
248
- if (candidate !== oldTextLf)
249
- return undefined;
250
- const matchStart = normalizedContent.indexOf(candidate);
251
- if (matchStart < 0)
252
- return undefined;
253
- const rawLines = rawContentLf.split("\n");
254
- const normalizedLines = normalizedContent.split("\n");
255
- const rawLineStarts = [];
256
- let rawOffset = 0;
257
- for (const line of rawLines) {
258
- rawLineStarts.push(rawOffset);
259
- rawOffset += line.length + 1;
260
- }
261
- const normalizedLineStarts = [];
262
- let normalizedOffset = 0;
263
- for (const line of normalizedLines) {
264
- normalizedLineStarts.push(normalizedOffset);
265
- normalizedOffset += line.length + 1;
266
- }
267
- const mapOffset = (offset, preferEnd) => {
268
- const line = Math.min(normalizedLines.length - 1, normalizedContent.slice(0, offset).split("\n").length - 1);
269
- const rawLine = rawLines[line] ?? "";
270
- const bomOffset = line === 0 && rawLine.startsWith("\uFEFF") ? 1 : 0;
271
- const rawMatchLine = rawLine.slice(bomOffset);
272
- const target = offset - normalizedLineStarts[line];
273
- const normalizedLine = normalizedLines[line] ?? "";
274
- if (target >= normalizedLine.length) {
275
- if (preferEnd)
276
- return rawLineStarts[line] + rawLine.length;
277
- return rawLineStarts[line] + bomOffset + rawMatchLine.length;
278
- }
279
- let lower = 0;
280
- let upper = rawMatchLine.length;
281
- for (let boundary = 0; boundary <= rawMatchLine.length; boundary += 1) {
282
- const length = normalizeContent(rawMatchLine.slice(0, boundary)).length;
283
- if (length === target)
284
- return rawLineStarts[line] + bomOffset + boundary;
285
- if (length < target)
286
- lower = boundary;
287
- else if (upper === rawMatchLine.length)
288
- upper = boundary;
289
- }
290
- return rawLineStarts[line] + bomOffset + (preferEnd ? upper : lower);
291
- };
292
- const start = mapOffset(matchStart, false);
293
- const end = mapOffset(matchStart + candidate.length, true);
294
- const text = rawContentLf.slice(start, end);
295
- return normalizeContent(text) === candidate
296
- ? { text, start, end }
297
- : undefined;
298
- }
299
- function resolveOldTextEdits(edits, filePath, sessionId, correlationId, partialApplyRecords) {
300
- const startedAt = Date.now();
301
- const requestedIndexes = [];
302
- const logBatchEvent = (entry) => logReadGuardEvent({ ...entry, correlationId });
303
- let rawBytes;
304
- try {
305
- rawBytes = nodeFs.readFileSync(filePath);
306
- }
307
- catch {
308
- const editBatchSummary = createReadGuardEditBatchSummary({
309
- requestedIndexes: edits.map((edit, index) => edit.originalIndex ?? index),
310
- rejectedReasons: edits.map((edit, index) => ({
311
- index: edit.originalIndex ?? index,
312
- code: "preflight_blocked",
313
- })),
314
- });
315
- logBatchEvent({
316
- event: "touched_lines_missing",
317
- sessionId,
318
- filePath,
319
- metadata: {
320
- tool: "edit",
321
- source: "edits_without_ranges",
322
- editCount: edits.length,
323
- },
324
- });
325
- logBatchEvent({
326
- event: "edit_batch_summary",
327
- filePath,
328
- metadata: { tool: "edit", editBatchSummary },
329
- });
330
- return { touchedLines: undefined, editBatchSummary };
331
- }
332
- const rawContent = rawBytes.toString("utf8");
333
- const rawContentLf = normalizeToLF(rawContent);
334
- const content = normalizeContent(rawContent);
335
- // #1053: the identity the spans below are resolved against. The apply step
336
- // re-reads the file and rejects the whole batch when this no longer holds,
337
- // so spans are never re-interpreted against changed bytes. The hash covers
338
- // byte identity; spans carry their own bounds checks.
339
- const snapshot = {
340
- hash: createHash("sha256").update(rawBytes).digest("hex"),
341
- };
342
- const errors = [];
343
- const failureKinds = [];
344
- const failedEditIndexes = [];
345
- const failedOldTextPreviews = [];
346
- const rejectedReasons = [];
347
- const resolvedIndexes = [];
348
- const resolvedRanges = [];
349
- const candidateEdits = [];
350
- const passedEdits = [];
351
- let overlapRejectedCount = 0;
352
- const alreadyAppliedEdits = [];
353
- let maxFailCount = 0;
354
- for (let i = 0; i < edits.length; i++) {
355
- const oldText = edits[i].oldText;
356
- const editIndex = edits[i].originalIndex ?? i;
357
- if (requestedIndexes.length < 100)
358
- requestedIndexes.push(editIndex);
359
- if (!oldText)
360
- continue;
361
- // Exact-retry recognition (#2402): an identical (oldText, newText) pair
362
- // this session already applied is recognized from the applied record and
363
- // confirmed by content evidence — never resolved again, never re-applied,
364
- // never counted as a failure. This is deliberately NOT a global
365
- // newText-present heuristic: the record only exists for pairs this
366
- // process actually committed.
367
- if (partialApplyRecords) {
368
- const record = partialApplyRecords.find(filePath, oldText, edits[i].newText);
369
- if (record &&
370
- isExactAppliedRetry({
371
- contentLf: rawContentLf,
372
- oldKey: normalizeContent(oldText),
373
- newKey: normalizeContent(edits[i].newText ?? ""),
374
- contentHash: snapshot.hash,
375
- expectedContentHash: record.contentHash,
376
- expectedAfterWriteHash: record.afterWriteContentHash,
377
- })) {
378
- if (alreadyAppliedEdits.length < 100)
379
- alreadyAppliedEdits.push(editIndex);
380
- logBatchEvent({
381
- event: "edit_already_applied_retry",
382
- sessionId,
383
- filePath,
384
- metadata: {
385
- tool: "edit",
386
- source: "edits_without_ranges",
387
- editIndex,
388
- },
389
- });
390
- continue;
391
- }
392
- }
393
- let needle = normalizeContent(oldText);
394
- let occurrenceLines = findOccurrenceLines(content, needle);
395
- if (occurrenceLines.length === 0) {
396
- const corrected = tryCorrectIndentationMismatchFromContent(oldText, rawContentLf);
397
- if (corrected !== undefined) {
398
- needle = normalizeContent(corrected);
399
- occurrenceLines = findOccurrenceLines(content, needle);
400
- if (occurrenceLines.length > 0) {
401
- logBatchEvent({
402
- event: "oldtext_indent_corrected",
403
- sessionId,
404
- filePath,
405
- metadata: {
406
- tool: "edit",
407
- source: "edits_without_ranges",
408
- editIndex,
409
- },
410
- });
411
- }
412
- }
413
- }
414
- if (occurrenceLines.length === 0) {
415
- const preview = oldText.trimStart().substring(0, 60).replace(/\n/g, "↵");
416
- failureKinds.push("oldtext_not_found");
417
- if (failedEditIndexes.length < 100) {
418
- failedEditIndexes.push(editIndex);
419
- failedOldTextPreviews.push(preview);
420
- }
421
- if (rejectedReasons.length < 100) {
422
- rejectedReasons.push({ index: editIndex, code: "oldtext_not_found" });
423
- }
424
- const failCount = trackOldTextFailure(filePath, preview);
425
- if (failCount > maxFailCount)
426
- maxFailCount = failCount;
427
- let errorMsg = `edits[${editIndex}].oldText ("${preview}") was not found in the current file content.`;
428
- // Quote-style hint: if swapping " ↔ ' gives exactly one match, tell the agent why it failed.
429
- const quoteSwapCandidates = [];
430
- if (needle.includes('"'))
431
- quoteSwapCandidates.push(needle.replace(/"/g, "'"));
432
- if (needle.includes("'"))
433
- quoteSwapCandidates.push(needle.replace(/'/g, '"'));
434
- const quoteHit = quoteSwapCandidates.find((s) => s !== needle && findOccurrenceLines(content, s).length === 1);
435
- if (quoteHit !== undefined) {
436
- errorMsg += ` The file uses a different quote style — your oldText has ${needle.includes('"') ? "double" : "single"} quotes but the file has ${needle.includes('"') ? "single" : "double"} quotes. Fix the quote style in both oldText and newText before retrying.`;
437
- }
438
- else {
439
- const lineHint = findFirstLineOfOldText(content, oldText);
440
- const offsetHint = lineHint !== undefined
441
- ? `\`offset=${Math.max(1, lineHint - 2)} limit=20\``
442
- : undefined;
443
- if (lineHint !== undefined) {
444
- // First line content exists in the file — the surrounding block has drifted.
445
- // Indentation autopatch already ran before this point and did not fix it,
446
- // so this is a content-drift failure, not a whitespace issue.
447
- if (failCount >= 2) {
448
- errorMsg +=
449
- ` This is attempt #${failCount} — the first line of your oldText appears near line ${lineHint}` +
450
- ` but the surrounding content no longer matches. This is a content-drift failure,` +
451
- ` not an indentation issue (indentation autopatch already ran and did not fix it).` +
452
- ` Re-read ${offsetHint} and rebuild oldText verbatim from the current file.`;
453
- }
454
- else {
455
- errorMsg +=
456
- ` The first line of your oldText appears near line ${lineHint} but the rest doesn't match.` +
457
- ` The file has likely changed since your last read — this is a content-drift issue, not indentation.` +
458
- ` Re-read ${offsetHint} and rebuild oldText from the verbatim file content.`;
459
- }
460
- }
461
- else {
462
- // First line not found anywhere in the file, even ignoring whitespace.
463
- if (failCount >= 2) {
464
- errorMsg +=
465
- ` This is attempt #${failCount} — this text does not appear anywhere in the file,` +
466
- ` even ignoring whitespace differences. Do NOT retry from memory.` +
467
- ` Re-read the relevant section before rebuilding your edit.`;
468
- }
469
- else {
470
- errorMsg +=
471
- ` This text does not appear anywhere in the file, even ignoring indentation differences —` +
472
- ` the file has likely changed significantly. Re-read the relevant section before retrying.`;
473
- }
474
- }
475
- }
476
- // "Did you mean?" — surface the closest current lines (token
477
- // similarity) so the model can rebuild oldText verbatim in one turn
478
- // instead of re-reading blind. Skipped on the quote-style path, which
479
- // already names the precise fix. Anchored near the first-line locator
480
- // when known, else scans the whole file. Scored against `content`
481
- // (normalized) but RENDERED from a structurally-aligned raw view —
482
- // quoting the normalized projection told the agent to copy bytes the
483
- // file does not contain (#1050).
484
- if (!errorMsg.includes("quote style")) {
485
- const similarLines = findSimilarLines(content, oldText.replace(/\r\n/g, "\n").split("\n")[0], { nearLine: findFirstLineOfOldText(content, oldText) });
486
- if (similarLines.length > 0) {
487
- errorMsg += formatSimilarLines(similarLines, normalizeToLF(stripBom(rawContent).text));
488
- }
489
- }
490
- errors.push(errorMsg);
491
- // Counterfactual: would the host's edit tool have applied this oldText
492
- // anyway? hostWouldApply=true => this block is a false-block (pi-lens
493
- // friction the host wouldn't have); false => a genuine miss. This is the
494
- // measurement that tells us whether the guard earns its keep (#257).
495
- const hostMatch = hostWouldApplyOldText(rawContent, oldText);
496
- logBatchEvent({
497
- event: "oldtext_not_found",
498
- sessionId,
499
- filePath,
500
- metadata: {
501
- tool: "edit",
502
- source: "edits_without_ranges",
503
- editIndex,
504
- oldTextPreview: preview,
505
- repeatFailureCount: failCount,
506
- hostWouldApply: hostMatch.wouldApply,
507
- hostOccurrences: hostMatch.occurrences,
508
- hostUsedFuzzyMatch: hostMatch.usedFuzzyMatch,
509
- },
510
- });
511
- }
512
- else if (occurrenceLines.length === 1) {
513
- const startLine = occurrenceLines[0];
514
- const endLine = startLine + needle.split("\n").length - 1;
515
- const applySpan = exactOldTextForApply(rawContentLf, content, oldText, needle);
516
- if (applySpan !== undefined) {
517
- // #1053: carry the exact span the preflight approved, plus the
518
- // snapshot identity it was resolved against. The apply step
519
- // consumes these instead of re-searching oldText.
520
- candidateEdits.push({
521
- oldText,
522
- appliedSpanText: applySpan.text,
523
- newText: edits[i].newText,
524
- originalIndex: editIndex,
525
- snapshot,
526
- spanStart: applySpan.start,
527
- spanEnd: applySpan.end,
528
- });
529
- resolvedRanges.push([startLine, endLine]);
530
- if (resolvedIndexes.length < 100)
531
- resolvedIndexes.push(editIndex);
532
- }
533
- else {
534
- failureKinds.push("oldtext_unrepresentable");
535
- if (failedEditIndexes.length < 100)
536
- failedEditIndexes.push(editIndex);
537
- if (rejectedReasons.length < 100) {
538
- rejectedReasons.push({
539
- index: editIndex,
540
- code: "oldtext_unrepresentable",
541
- });
542
- }
543
- errors.push(`edits[${editIndex}].oldText matched normalized content but could not be mapped to one raw file span; the whole batch must be rebuilt from the current file content.`);
544
- logBatchEvent({
545
- event: "edit_preflight_blocked",
546
- sessionId,
547
- filePath,
548
- metadata: {
549
- tool: "edit",
550
- source: "edits_without_ranges",
551
- reasonKind: "oldtext_unrepresentable",
552
- editIndex,
553
- },
554
- });
555
- }
556
- if (applySpan !== undefined) {
557
- logBatchEvent({
558
- event: "oldtext_resolved",
559
- sessionId,
560
- filePath,
561
- metadata: {
562
- tool: "edit",
563
- source: "edits_without_ranges",
564
- editIndex,
565
- touchedLines: [startLine, endLine],
566
- },
567
- });
568
- }
569
- }
570
- else {
571
- const preview = oldText.trimStart().substring(0, 60).replace(/\n/g, "↵");
572
- failureKinds.push("oldtext_duplicate");
573
- if (failedEditIndexes.length < 100) {
574
- failedEditIndexes.push(editIndex);
575
- failedOldTextPreviews.push(preview);
576
- }
577
- if (rejectedReasons.length < 100) {
578
- rejectedReasons.push({ index: editIndex, code: "oldtext_duplicate" });
579
- }
580
- const matchSpanLines = needle.split("\n").length;
581
- const contextBlock = formatOccurrenceContext(content, occurrenceLines, matchSpanLines);
582
- errors.push(`edits[${editIndex}].oldText ("${preview}") appears ${occurrenceLines.length} times:\n${contextBlock}\nPick the location you want and extend your oldText with the unique line above or below it (shown as context).`);
583
- logBatchEvent({
584
- event: "oldtext_duplicate",
585
- sessionId,
586
- filePath,
587
- metadata: {
588
- tool: "edit",
589
- source: "edits_without_ranges",
590
- editIndex,
591
- occurrenceLines: occurrenceLines.slice(0, 100),
592
- occurrenceCount: occurrenceLines.length,
593
- oldTextPreview: preview,
594
- },
595
- });
596
- }
597
- }
598
- // Overlap guard (#1053): individually-unique matches can still overlap
599
- // (e.g. "abc" and "bcd" both matching inside "xabcy"). Applying both would
600
- // splice corrupt content, so overlapping candidates are rejected together
601
- // with one explicit message instead of being silently skipped.
602
- const sortedCandidates = [...candidateEdits].sort((a, b) => a.spanStart - b.spanStart);
603
- const overlaps = overlapPairs(sortedCandidates);
604
- for (let i = 0; i < sortedCandidates.length; i += 1) {
605
- const candidate = sortedCandidates[i];
606
- const overlapping = sortedCandidates.find((other) => other !== candidate &&
607
- other.spanStart < candidate.spanEnd &&
608
- candidate.spanStart < other.spanEnd);
609
- if (overlapping) {
610
- overlapRejectedCount += 1;
611
- if (rejectedReasons.length < 100) {
612
- rejectedReasons.push({
613
- index: candidate.originalIndex,
614
- code: "span_overlap",
615
- });
616
- }
617
- continue;
618
- }
619
- passedEdits.push(candidate);
620
- }
621
- for (const [a, b] of overlaps) {
622
- errors.push(`edits[${a.originalIndex}] and edits[${b.originalIndex}] resolved to overlapping spans of the file — their oldTexts match regions that share bytes. Extend one oldText with a unique neighboring line so each edit targets one unambiguous span, or apply them in separate calls.`);
623
- }
624
- // Overlap is a batch-level safety failure. Do not partially commit an
625
- // unrelated candidate from the same request while another pair is
626
- // ambiguous; the apply seam promises all-or-nothing preflight rejection.
627
- if (overlaps.length > 0)
628
- passedEdits.length = 0;
629
- const oldTextEditCount = edits.filter((edit) => !!edit.oldText).length;
630
- // Pure already-applied batch (#2402): every oldText edit is a recognized
631
- // exact retry, nothing failed, nothing remains to apply. The verdict is the
632
- // idempotent "already applied" note, never an escalating error.
633
- if (errors.length === 0 &&
634
- passedEdits.length === 0 &&
635
- alreadyAppliedEdits.length > 0 &&
636
- alreadyAppliedEdits.length === oldTextEditCount) {
637
- const header = `✅ ALREADY APPLIED — every edit in this call was already applied by an identical earlier submission. Do NOT retry this payload; re-read the file if you need to build a new edit.`;
638
- const details = alreadyAppliedEdits.map((editIndex) => `edits[${editIndex}]: already applied — do not resubmit.`);
639
- const editBatchSummary = createReadGuardEditBatchSummary({
640
- requestedIndexes,
641
- requestedTotal: edits.length,
642
- alreadyAppliedIndexes: boundedEditIndexes(alreadyAppliedEdits),
643
- alreadyAppliedTotal: alreadyAppliedEdits.length,
644
- durationMs: Date.now() - startedAt,
645
- terminalStatus: "skipped",
646
- });
647
- logBatchEvent({
648
- event: "edit_batch_summary",
649
- correlationId,
650
- filePath,
651
- metadata: { tool: "edit", editBatchSummary },
652
- });
653
- return {
654
- touchedLines: undefined,
655
- preflightError: `${header}\n\n${details.join("\n")}`,
656
- preflightHeader: header,
657
- preflightDetails: details,
658
- alreadyAppliedEdits,
659
- editBatchSummary,
660
- };
661
- }
662
- if (errors.length > 0 ||
663
- alreadyAppliedEdits.length > 0 ||
664
- resolvedRanges.length !== oldTextEditCount) {
665
- const failureDetails = errors.length > 0
666
- ? errors
667
- : alreadyAppliedEdits.map((editIndex) => `edits[${editIndex}]: already applied — do not resubmit.`);
668
- const uniqueFailureKinds = [...new Set(failureKinds)];
669
- const editBatchSummary = createReadGuardEditBatchSummary({
670
- requestedIndexes,
671
- requestedTotal: edits.length,
672
- resolvedIndexes,
673
- resolvedTotal: resolvedRanges.length,
674
- rejectedReasons,
675
- rejectedTotal: Math.max(0, oldTextEditCount -
676
- resolvedRanges.length -
677
- alreadyAppliedEdits.length +
678
- overlapRejectedCount),
679
- alreadyAppliedIndexes: boundedEditIndexes(alreadyAppliedEdits),
680
- alreadyAppliedTotal: alreadyAppliedEdits.length,
681
- durationMs: Date.now() - startedAt,
682
- terminalStatus: "blocked",
683
- });
684
- logBatchEvent({
685
- event: "edit_preflight_blocked",
686
- correlationId,
687
- sessionId,
688
- filePath,
689
- metadata: {
690
- tool: "edit",
691
- source: "edits_without_ranges",
692
- reasonKind: uniqueFailureKinds.length === 1
693
- ? uniqueFailureKinds[0]
694
- : "oldtext_resolution_failed",
695
- failureKinds: uniqueFailureKinds,
696
- editCount: edits.length,
697
- oldTextEditCount,
698
- resolvedOldTextEditCount: resolvedRanges.length,
699
- unresolvedOldTextEditCount: oldTextEditCount - resolvedRanges.length,
700
- alreadyAppliedCount: alreadyAppliedEdits.length,
701
- overlapRejectedCount,
702
- failedEditIndexes,
703
- oldTextPreviews: failedOldTextPreviews.slice(0, 5),
704
- errorCount: errors.length,
705
- },
706
- });
707
- const header = errors.length === 0
708
- ? `✅ ALREADY APPLIED — some edits in this call were already applied by an identical earlier submission. Do NOT resubmit them.`
709
- : maxFailCount >= 2
710
- ? `🛑 RE-READ REQUIRED — You have submitted this oldText before and it still does not match.\n\nDo NOT retry from memory. Re-read \`${filePath}\` to get the current content, then rebuild your edit from the verbatim file text.`
711
- : uniqueFailureKinds.length === 1 &&
712
- uniqueFailureKinds[0] === "span_overlap"
713
- ? `🔄 RETRYABLE — Overlapping edit spans`
714
- : `🔄 RETRYABLE — Edit target not found`;
715
- logBatchEvent({
716
- event: "edit_batch_summary",
717
- correlationId,
718
- filePath,
719
- metadata: { tool: "edit", editBatchSummary },
720
- });
721
- return {
722
- touchedLines: undefined,
723
- preflightError: `${header}\n\n${failureDetails.join("\n\n")}${formatAlreadyAppliedNotes(alreadyAppliedEdits)}`,
724
- preflightHeader: header,
725
- preflightDetails: failureDetails,
726
- partiallyApplicable: passedEdits.length > 0 &&
727
- !failureKinds.includes("oldtext_unrepresentable")
728
- ? passedEdits
729
- : undefined,
730
- alreadyAppliedEdits: alreadyAppliedEdits.length > 0 ? alreadyAppliedEdits : undefined,
731
- editBatchSummary,
732
- };
733
- }
734
- if (resolvedRanges.length === 0) {
735
- const editBatchSummary = createReadGuardEditBatchSummary({
736
- requestedIndexes,
737
- requestedTotal: edits.length,
738
- rejectedTotal: oldTextEditCount,
739
- terminalStatus: "blocked",
740
- });
741
- logBatchEvent({
742
- event: "touched_lines_missing",
743
- sessionId,
744
- filePath,
745
- metadata: {
746
- tool: "edit",
747
- source: "edits_without_ranges",
748
- editCount: edits.length,
749
- },
750
- });
751
- logBatchEvent({
752
- event: "edit_batch_summary",
753
- filePath,
754
- metadata: { tool: "edit", editBatchSummary },
755
- });
756
- return { touchedLines: undefined, editBatchSummary };
757
- }
758
- const starts = resolvedRanges.map(([s]) => s);
759
- const ends = resolvedRanges.map(([, e]) => e);
760
- const touchedLines = [
761
- Math.min(...starts),
762
- Math.max(...ends),
763
- ];
764
- const editRanges = resolvedRanges.length > 1 ? resolvedRanges : undefined;
765
- logBatchEvent({
766
- event: "touched_lines_detected",
767
- sessionId,
768
- filePath,
769
- metadata: {
770
- tool: "edit",
771
- source: "oldtext_resolved",
772
- touchedLines,
773
- resolvedEditCount: resolvedRanges.length,
774
- totalEditCount: edits.length,
775
- },
776
- });
777
- const editBatchSummary = createReadGuardEditBatchSummary({
778
- requestedIndexes,
779
- requestedTotal: edits.length,
780
- resolvedIndexes,
781
- resolvedTotal: resolvedRanges.length,
782
- durationMs: Date.now() - startedAt,
783
- terminalStatus: "success",
784
- });
785
- return {
786
- touchedLines,
787
- editRanges,
788
- contentMatchValidated: true,
789
- editBatchSummary,
790
- };
791
- }
792
- // Canonical applied-edit keying lives beside the partial-apply seam that both
793
- // writes and consumes it (partial-edit-apply.ts, #1053/#2402).
794
- export { stripOldTextTrailingWhitespace } from "./partial-edit-apply.js";
795
- /**
796
- * Normalises an oldText string for whitespace-only differences that editors routinely
797
- * introduce: trailing spaces/tabs on each line are stripped, and any trailing blank
798
- * lines (lines that are empty after trimming) are removed from the end. CRLF is
799
- * normalised to LF. Returns the same string if no change was needed.
800
- */
801
- /**
802
- * Tries to fix a tab/space indentation mismatch between the model's oldText and the
803
- * actual file. Returns the corrected oldText if a matching variant is found, or
804
- * undefined if the text already matches or no indentation conversion fixes it.
805
- */
806
- export function tryCorrectIndentationMismatchFromContent(oldText, content) {
807
- const normalized = oldText.replace(/\r\n/g, "\n");
808
- if (content.includes(normalized))
809
- return undefined;
810
- const conversions = [
811
- // tabs → 2 spaces
812
- (s) => s
813
- .split("\n")
814
- .map((l) => l.replace(/^\t+/, (m) => " ".repeat(m.length)))
815
- .join("\n"),
816
- // tabs → 4 spaces
817
- (s) => s
818
- .split("\n")
819
- .map((l) => l.replace(/^\t+/, (m) => " ".repeat(m.length)))
820
- .join("\n"),
821
- // 2 spaces → tabs
822
- (s) => s
823
- .split("\n")
824
- .map((l) => l.replace(/^( {2})+/, (m) => "\t".repeat(m.length / 2)))
825
- .join("\n"),
826
- // 4 spaces → tabs
827
- (s) => s
828
- .split("\n")
829
- .map((l) => l.replace(/^( {4})+/, (m) => "\t".repeat(m.length / 4)))
830
- .join("\n"),
831
- ];
832
- for (const convert of conversions) {
833
- const candidate = convert(normalized);
834
- if (candidate !== normalized && content.includes(candidate))
835
- return candidate;
836
- }
837
- const indentationInsensitiveCandidate = findIndentationInsensitiveCandidate(content, normalized);
838
- if (indentationInsensitiveCandidate !== undefined) {
839
- return indentationInsensitiveCandidate;
840
- }
841
- // Tier A (#200): the fixed-length matchers above can't bridge a mid-block
842
- // blank-line difference; fall back to a blank-line-insensitive match that
843
- // recovers the real file span (unique-match guarded).
844
- const blankLineCandidate = findBlankLineInsensitiveCandidate(content, normalized);
845
- if (blankLineCandidate !== undefined) {
846
- return blankLineCandidate;
847
- }
848
- // Tier B: interior-whitespace drift the earlier tiers can't bridge — the
849
- // indentation- and blank-line-insensitive tiers both still require each
850
- // non-blank line to match character-for-character after trimming only the
851
- // OUTER edges. When whitespace drifts INSIDE a line (a formatter collapsed
852
- // `a + b` → `a + b`, re-spaced operators/args, etc.) those tiers miss.
853
- // Matching on a fully-whitespace-collapsed signature catches it. Same
854
- // safety contract as Tier A: unique-match guarded, ≥2 anchors, recovers the
855
- // verbatim file span.
856
- const whitespaceCandidate = findWhitespaceInsensitiveCandidate(content, normalized);
857
- if (whitespaceCandidate !== undefined) {
858
- return whitespaceCandidate;
859
- }
860
- // Tier C: Unicode-punctuation drift the whitespace tiers can't bridge — the
861
- // model emitted smart quotes / em-dashes / NBSP where the file has straight
862
- // quotes / hyphens / regular spaces (or vice versa), common when text is
863
- // pasted from rendered Markdown or the model "tidies" punctuation. Folding
864
- // those to their ASCII equivalents (on top of whitespace collapse) catches it.
865
- // Same safety contract as Tier B: signature-matched, unique-match guarded, ≥2
866
- // anchors, recovers the verbatim file span (the file's real characters).
867
- const unicodeCandidate = findUnicodePunctuationInsensitiveCandidate(content, normalized);
868
- if (unicodeCandidate !== undefined) {
869
- return unicodeCandidate;
870
- }
871
- return undefined;
872
- }
873
- export function tryCorrectIndentationMismatch(oldText, filePath) {
874
- try {
875
- return tryCorrectIndentationMismatchFromContent(oldText, nodeFs.readFileSync(filePath, "utf-8").replace(/\r\n/g, "\n"));
876
- }
877
- catch {
878
- return undefined;
879
- }
880
- }
881
- function findIndentationInsensitiveCandidate(content, oldText) {
882
- const contentLines = content.split("\n");
883
- const oldLines = oldText.split("\n");
884
- const stripIndent = (line) => line.replace(/^[\t ]+/, "").trimEnd();
885
- const expected = oldLines.map(stripIndent);
886
- for (let start = 0; start <= contentLines.length - oldLines.length; start += 1) {
887
- let matches = true;
888
- for (let offset = 0; offset < oldLines.length; offset += 1) {
889
- if (stripIndent(contentLines[start + offset] ?? "") !== expected[offset]) {
890
- matches = false;
891
- break;
892
- }
893
- }
894
- if (matches) {
895
- const candidate = contentLines
896
- .slice(start, start + oldLines.length)
897
- .join("\n");
898
- if (candidate !== oldText)
899
- return candidate;
900
- }
901
- }
902
- return undefined;
903
- }
904
- /**
905
- * Tier A of the blank-line autopatch (#200): tolerate mid-block blank-line
906
- * divergence — a blank line added or removed *inside* the block — which the
907
- * fixed-length window in {@link findIndentationInsensitiveCandidate} can't (any
908
- * interior blank-line delta breaks its 1:1 alignment). Blank lines are
909
- * semantically insignificant in every supported language, so matching the
910
- * oldText's non-blank lines (indentation-insensitive) against consecutive
911
- * content while skipping interior blanks on the content side is safe.
912
- *
913
- * Safety: matches by the non-blank "signature" but **recovers and returns the
914
- * real file span** (first→last matched non-blank line, real interior blanks
915
- * included) so the applied oldText is verbatim file bytes; requires the
916
- * signature to match **exactly once** (returns undefined on 0 or ≥2). Anchored
917
- * on ≥2 non-blank lines to avoid trivial single-line collisions.
918
- */
919
- function findBlankLineInsensitiveCandidate(content, oldText) {
920
- const stripIndent = (line) => line.replace(/^[\t ]+/, "").trimEnd();
921
- const isBlank = (line) => stripIndent(line) === "";
922
- const contentLines = content.split("\n");
923
- const oldNonBlank = oldText
924
- .split("\n")
925
- .map(stripIndent)
926
- .filter((line) => line !== "");
927
- // Need ≥2 anchors to be meaningful and collision-resistant; single-line
928
- // drift has no interior to differ and is handled by other tiers.
929
- if (oldNonBlank.length < 2)
930
- return undefined;
931
- const spans = [];
932
- for (let start = 0; start < contentLines.length; start += 1) {
933
- if (stripIndent(contentLines[start]) !== oldNonBlank[0])
934
- continue;
935
- let contentIdx = start + 1;
936
- let oldIdx = 1;
937
- let end = start;
938
- let ok = true;
939
- while (oldIdx < oldNonBlank.length) {
940
- while (contentIdx < contentLines.length &&
941
- isBlank(contentLines[contentIdx]))
942
- contentIdx += 1;
943
- if (contentIdx >= contentLines.length ||
944
- stripIndent(contentLines[contentIdx]) !== oldNonBlank[oldIdx]) {
945
- ok = false;
946
- break;
947
- }
948
- end = contentIdx;
949
- oldIdx += 1;
950
- contentIdx += 1;
951
- }
952
- if (ok)
953
- spans.push([start, end]);
954
- }
955
- if (spans.length !== 1)
956
- return undefined;
957
- const [start, end] = spans[0];
958
- const candidate = contentLines.slice(start, end + 1).join("\n");
959
- return candidate === oldText ? undefined : candidate;
960
- }
961
- /**
962
- * Tier B of the whitespace autopatch: tolerate INTERIOR whitespace divergence
963
- * that {@link findBlankLineInsensitiveCandidate} (outer-trim only) and the
964
- * fixed-width converters can't bridge. The signature is each non-blank line
965
- * with **all** whitespace removed (`/\s+/g` → ""), so re-spacing inside a line
966
- * — `a + b` ↔ `a + b`, `foo( x )` ↔ `foo(x)`, tab/space mixes mid-line — no
967
- * longer breaks the match. This mirrors the content-hash normalization the
968
- * read-guard already uses for staleness (`lineContentHash`), so a span that
969
- * passes here is a span the guard considers semantically identical.
970
- *
971
- * Safety mirrors Tier A exactly: matches by the collapsed signature but
972
- * **recovers and returns the real file span** (verbatim bytes, interior blanks
973
- * included) so the applied oldText is exact; requires the signature to match
974
- * **exactly once** (0 or ≥2 → undefined); anchored on ≥2 non-blank lines to
975
- * resist single-line collisions (collapsing whitespace makes single-line
976
- * collisions more likely, so the ≥2 floor matters more here than in Tier A).
977
- */
978
- function findWhitespaceInsensitiveCandidate(content, oldText) {
979
- const collapse = (line) => line.replace(/\s+/g, "");
980
- const isBlank = (line) => collapse(line) === "";
981
- const contentLines = content.split("\n");
982
- const oldSignature = oldText
983
- .split("\n")
984
- .map(collapse)
985
- .filter((line) => line !== "");
986
- if (oldSignature.length < 2)
987
- return undefined;
988
- const spans = [];
989
- for (let start = 0; start < contentLines.length; start += 1) {
990
- if (collapse(contentLines[start]) !== oldSignature[0])
991
- continue;
992
- let contentIdx = start + 1;
993
- let sigIdx = 1;
994
- let end = start;
995
- let ok = true;
996
- while (sigIdx < oldSignature.length) {
997
- while (contentIdx < contentLines.length &&
998
- isBlank(contentLines[contentIdx]))
999
- contentIdx += 1;
1000
- if (contentIdx >= contentLines.length ||
1001
- collapse(contentLines[contentIdx]) !== oldSignature[sigIdx]) {
1002
- ok = false;
1003
- break;
1004
- }
1005
- end = contentIdx;
1006
- sigIdx += 1;
1007
- contentIdx += 1;
1008
- }
1009
- if (ok)
1010
- spans.push([start, end]);
1011
- }
1012
- if (spans.length !== 1)
1013
- return undefined;
1014
- const [start, end] = spans[0];
1015
- const candidate = contentLines.slice(start, end + 1).join("\n");
1016
- return candidate === oldText ? undefined : candidate;
1017
- }
1018
- /**
1019
- * Fold the Unicode punctuation that models and rendered text routinely swap for
1020
- * ASCII (and back) to a canonical ASCII form: smart single/double quotes →
1021
- * `'`/`"`, the dash family (hyphen, figure/en/em dash, horizontal bar, minus) →
1022
- * `-`, and non-breaking / typographic spaces → a regular space. Used only to
1023
- * build a match signature — never to rewrite file content.
1024
- */
1025
- function normalizeUnicodePunctuation(text) {
1026
- return text
1027
- .replace(/[‘’‚‛]/g, "'")
1028
- .replace(/[“”„‟]/g, '"')
1029
- .replace(/[‐-―−]/g, "-")
1030
- .replace(/[  -    ]/g, " ");
1031
- }
1032
- /**
1033
- * Tier C of the autopatch ladder: tolerate Unicode-punctuation divergence the
1034
- * whitespace tiers can't bridge (smart quotes ↔ straight, em/en-dash ↔ hyphen,
1035
- * NBSP ↔ space). The signature folds Unicode punctuation to ASCII and then
1036
- * collapses all whitespace (so it subsumes Tier B and additionally absorbs the
1037
- * punctuation swap). Safety mirrors Tier B exactly: matches by the folded
1038
- * signature but **recovers and returns the verbatim file span** (the file's real
1039
- * characters), requires the signature to match **exactly once**, and anchors on
1040
- * ≥2 non-blank lines to resist single-line collisions.
1041
- */
1042
- function findUnicodePunctuationInsensitiveCandidate(content, oldText) {
1043
- const fold = (line) => normalizeUnicodePunctuation(line).replace(/\s+/g, "");
1044
- const isBlank = (line) => fold(line) === "";
1045
- const contentLines = content.split("\n");
1046
- const oldSignature = oldText
1047
- .split("\n")
1048
- .map(fold)
1049
- .filter((line) => line !== "");
1050
- if (oldSignature.length < 2)
1051
- return undefined;
1052
- const spans = [];
1053
- for (let start = 0; start < contentLines.length; start += 1) {
1054
- if (fold(contentLines[start]) !== oldSignature[0])
1055
- continue;
1056
- let contentIdx = start + 1;
1057
- let sigIdx = 1;
1058
- let end = start;
1059
- let ok = true;
1060
- while (sigIdx < oldSignature.length) {
1061
- while (contentIdx < contentLines.length &&
1062
- isBlank(contentLines[contentIdx]))
1063
- contentIdx += 1;
1064
- if (contentIdx >= contentLines.length ||
1065
- fold(contentLines[contentIdx]) !== oldSignature[sigIdx]) {
1066
- ok = false;
1067
- break;
1068
- }
1069
- end = contentIdx;
1070
- sigIdx += 1;
1071
- contentIdx += 1;
1072
- }
1073
- if (ok)
1074
- spans.push([start, end]);
1075
- }
1076
- if (spans.length !== 1)
1077
- return undefined;
1078
- const [start, end] = spans[0];
1079
- const candidate = contentLines.slice(start, end + 1).join("\n");
1080
- return candidate === oldText ? undefined : candidate;
1081
- }
1082
- /**
1083
- * Shift a native range edit's line numbers, in place, by the relocation delta.
1084
- * Returns true when a range matching `from` was found and rewritten. Powers the
1085
- * content-verified range-stale auto-apply: the lines the agent meant to edit
1086
- * moved (proven by read-time line hashes uniquely matching the new location),
1087
- * so we re-target the positional edit to where the content now lives.
1088
- *
1089
- * Shifts by a constant line delta (`to[0] - from[0]`) applied to both the start
1090
- * and end lines, so inclusive/exclusive end conventions and any character
1091
- * offsets are preserved untouched — only the line position moves. Matches both
1092
- * the single `oldRange` shape and `edits[].range` entries.
1093
- */
1094
- export function relocateEditRange(input, from, to) {
1095
- const delta = to[0] - from[0];
1096
- if (delta === 0 || !input || typeof input !== "object")
1097
- return false;
1098
- const editInput = input;
1099
- const matchesFrom = (start, end) => start === from[0] && end === from[1];
1100
- let applied = false;
1101
- const oldRange = editInput.oldRange;
1102
- if (oldRange?.start?.line !== undefined &&
1103
- oldRange.end?.line !== undefined &&
1104
- matchesFrom(oldRange.start.line, oldRange.end.line)) {
1105
- oldRange.start.line += delta;
1106
- oldRange.end.line += delta;
1107
- applied = true;
1108
- }
1109
- if (Array.isArray(editInput.edits)) {
1110
- for (const edit of editInput.edits) {
1111
- const start = edit.range?.start?.line;
1112
- const end = edit.range?.end?.line ?? start;
1113
- if (start !== undefined && matchesFrom(start, end)) {
1114
- edit.range.start.line = start + delta;
1115
- if (edit.range?.end?.line !== undefined) {
1116
- edit.range.end.line += delta;
1117
- }
1118
- applied = true;
1119
- }
1120
- }
1121
- }
1122
- return applied;
1123
- }
1124
- export function getTouchedLinesForGuard(event, filePath, sessionId, correlationId, partialApplyRecords) {
1125
- // #2423: the seam decides whether this event mutates a file, and which shape
1126
- // adapter (if any) already resolved its ranges. A tool named `replace` or
1127
- // `insert` reaches the native-shape ladder below exactly like `edit` does.
1128
- const mutation = classifyMutatingTool(event, {
1129
- filePath,
1130
- sessionId,
1131
- correlationId,
1132
- });
1133
- if (mutation === undefined)
1134
- return { touchedLines: undefined };
1135
- if (mutation.kind === "edit") {
1136
- // An adapter that recognized the input owns the answer, including a
1137
- // blocking preflight error.
1138
- if (mutation.touchedLines !== undefined || mutation.preflightError) {
1139
- return {
1140
- touchedLines: mutation.touchedLines,
1141
- ...(mutation.editRanges ? { editRanges: mutation.editRanges } : {}),
1142
- ...(mutation.preflightError
1143
- ? { preflightError: mutation.preflightError }
1144
- : {}),
1145
- ...(mutation.editBatchSummary
1146
- ? { editBatchSummary: mutation.editBatchSummary }
1147
- : {}),
1148
- };
1149
- }
1150
- // The host standard-edit fields (path, edits[].oldText/newText) are pinned
1151
- // to the SDK's EditToolInput, so a host edit-schema change is a compile
1152
- // error instead of silently falling through to `unknown_edit_schema`. The
1153
- // remaining keys are pi-lens's own extensions for native-ranged + hashline
1154
- // edit tools; oldText/newText are probed as optional because range-only
1155
- // edits omit them (refs #3).
1156
- const editInput = event.input;
1157
- if (editInput.oldRange) {
1158
- const touchedLines = [
1159
- editInput.oldRange.start.line,
1160
- editInput.oldRange.end.line,
1161
- ];
1162
- if (filePath) {
1163
- logReadGuardEvent({
1164
- event: "touched_lines_detected",
1165
- correlationId,
1166
- sessionId,
1167
- filePath,
1168
- metadata: {
1169
- tool: "edit",
1170
- source: "oldRange",
1171
- touchedLines,
1172
- },
1173
- });
1174
- }
1175
- return { touchedLines };
1176
- }
1177
- if (editInput.edits?.length) {
1178
- const rangedEdits = editInput.edits
1179
- .map((edit) => {
1180
- const start = edit.range?.start?.line;
1181
- const end = edit.range?.end?.line ?? start;
1182
- if (typeof start !== "number" || typeof end !== "number") {
1183
- return null;
1184
- }
1185
- return [start, end];
1186
- })
1187
- .filter((range) => range !== null);
1188
- const unresolvedOldTextEdits = editInput.edits
1189
- .map((edit, index) => ({ ...edit, originalIndex: index }))
1190
- .filter((edit) => typeof edit.range?.start?.line !== "number" && !!edit.oldText);
1191
- if (rangedEdits.length === 0) {
1192
- if (filePath) {
1193
- return resolveOldTextEdits(editInput.edits, filePath, sessionId, correlationId, partialApplyRecords);
1194
- }
1195
- return { touchedLines: undefined };
1196
- }
1197
- let oldTextTouchedLines;
1198
- let oldTextEditRanges;
1199
- if (unresolvedOldTextEdits.length > 0 && filePath) {
1200
- const resolved = resolveOldTextEdits(unresolvedOldTextEdits, filePath, sessionId, correlationId, partialApplyRecords);
1201
- if (resolved.preflightError) {
1202
- // A mixed range/oldText request is one host operation. If any
1203
- // oldText edit cannot be represented as a carried raw span,
1204
- // close the whole batch instead of letting the host apply only
1205
- // the native ranges.
1206
- return {
1207
- ...resolved,
1208
- partiallyApplicable: undefined,
1209
- touchedLines: undefined,
1210
- };
1211
- }
1212
- oldTextTouchedLines = resolved.touchedLines;
1213
- oldTextEditRanges = resolved.editRanges;
1214
- }
1215
- const starts = rangedEdits.map(([start]) => start);
1216
- const ends = rangedEdits.map(([, end]) => end);
1217
- if (oldTextTouchedLines) {
1218
- starts.push(oldTextTouchedLines[0]);
1219
- ends.push(oldTextTouchedLines[1]);
1220
- }
1221
- const touchedLines = [
1222
- Math.min(...starts),
1223
- Math.max(...ends),
1224
- ];
1225
- const allEditRanges = [...rangedEdits];
1226
- if (oldTextEditRanges?.length) {
1227
- allEditRanges.push(...oldTextEditRanges);
1228
- }
1229
- else if (oldTextTouchedLines) {
1230
- allEditRanges.push(oldTextTouchedLines);
1231
- }
1232
- const editRanges = allEditRanges.length > 1 ? allEditRanges : undefined;
1233
- if (filePath) {
1234
- logReadGuardEvent({
1235
- event: "touched_lines_detected",
1236
- correlationId,
1237
- sessionId,
1238
- filePath,
1239
- metadata: {
1240
- tool: "edit",
1241
- source: unresolvedOldTextEdits.length > 0
1242
- ? "edits_mixed"
1243
- : "edits_ranges",
1244
- touchedLines,
1245
- rangedEditCount: rangedEdits.length,
1246
- resolvedOldTextEditCount: unresolvedOldTextEdits.length,
1247
- totalEditCount: editInput.edits.length,
1248
- },
1249
- });
1250
- }
1251
- return { touchedLines, editRanges };
1252
- }
1253
- if (filePath) {
1254
- const topLevelKeys = Object.keys(editInput);
1255
- logReadGuardEvent({
1256
- event: "touched_lines_missing",
1257
- correlationId,
1258
- sessionId,
1259
- filePath,
1260
- metadata: {
1261
- tool: "edit",
1262
- source: "unknown_edit_schema",
1263
- // #2423: name the tool. An unknown schema under a third-party
1264
- // tool name is the actionable case — it says which producer
1265
- // needs a shape adapter.
1266
- mutatingToolName: mutation.toolName,
1267
- mutationProvenance: mutation.provenance,
1268
- // #2423 review round 1 (F1): an adapter that RECOGNIZED the
1269
- // shape but could not turn its anchors into lines says so here.
1270
- // `adapterSource: "hashline-edit-pro"` with
1271
- // `unresolvedReason: "remove_from:anchor_not_found"` is the
1272
- // production record of a stale anchor — a report, not a block.
1273
- adapterSource: mutation.source,
1274
- unresolvedReason: mutation.unresolvedReason,
1275
- topLevelKeys,
1276
- hasNativeOldRange: !!editInput.oldRange,
1277
- hasNativeEdits: Array.isArray(editInput.edits),
1278
- hasHashlineSetLine: !!editInput.set_line,
1279
- hasHashlineReplaceLines: !!editInput.replace_lines,
1280
- hasHashlineReplaceSymbol: !!editInput.replace_symbol,
1281
- hasHashlineBatch: Array.isArray(editInput.operations) || Array.isArray(editInput.ops),
1282
- strictModeWouldBlock: true,
1283
- },
1284
- });
1285
- }
1286
- return { touchedLines: undefined };
1287
- }
1288
- // kind === "write": the whole file is the touched range.
1289
- const lineCount = filePath ? countFileLines(filePath) : 1;
1290
- const writeTouchedLines = [1, lineCount];
1291
- if (filePath) {
1292
- logReadGuardEvent({
1293
- event: "touched_lines_detected",
1294
- correlationId,
1295
- sessionId,
1296
- filePath,
1297
- metadata: {
1298
- tool: "write",
1299
- source: "full_file_write",
1300
- touchedLines: writeTouchedLines,
1301
- lineCount,
1302
- },
1303
- });
1304
- }
1305
- return { touchedLines: writeTouchedLines };
1306
- }