pi-lens 4.3.0 → 4.4.1

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 (659) hide show
  1. package/CHANGELOG.md +1159 -0
  2. package/README.md +116 -25
  3. package/config/dependency-cruiser-eager-allowlist.json +6 -2
  4. package/dist/chunk-2BEMIWEW.js +51 -0
  5. package/dist/chunk-2EECBNC5.js +89 -0
  6. package/dist/chunk-2FQ62SPM.js +83 -0
  7. package/dist/chunk-2UMYMRI3.js +118 -0
  8. package/dist/chunk-34OCDWOS.js +48 -0
  9. package/dist/chunk-3FERWMCH.js +144 -0
  10. package/dist/chunk-3JL6IFD7.js +97 -0
  11. package/dist/chunk-3JSEWUWI.js +327 -0
  12. package/dist/chunk-3MED75HT.js +37 -0
  13. package/dist/chunk-3MRXIJ6I.js +79 -0
  14. package/dist/chunk-3P4PF2BX.js +2250 -0
  15. package/dist/chunk-3PNFWVHT.js +201 -0
  16. package/dist/chunk-3TTPKMEF.js +162 -0
  17. package/dist/chunk-5JHXUETW.js +326 -0
  18. package/dist/chunk-5W3R6LFT.js +24 -0
  19. package/dist/chunk-64LU2OVH.js +341 -0
  20. package/dist/chunk-6B5I6ICN.js +44 -0
  21. package/dist/chunk-6P54TMWL.js +274 -0
  22. package/dist/chunk-6UYA642J.js +145 -0
  23. package/dist/chunk-6XX5HCLK.js +398 -0
  24. package/dist/chunk-7AXO3ZDF.js +30 -0
  25. package/dist/chunk-7BX5DWSA.js +1907 -0
  26. package/dist/chunk-7ELY2CSM.js +902 -0
  27. package/dist/chunk-7M4T5N3V.js +38 -0
  28. package/dist/chunk-7U2IDNXN.js +37 -0
  29. package/dist/chunk-ABBOA7UD.js +157 -0
  30. package/dist/chunk-AFZYMAIV.js +756 -0
  31. package/dist/chunk-ALQRYH6O.js +112 -0
  32. package/dist/chunk-AXKPQ6ZI.js +1610 -0
  33. package/dist/chunk-BHWHXMQ2.js +62 -0
  34. package/dist/chunk-BJF25SUG.js +22 -0
  35. package/dist/chunk-BNKLYOOO.js +18 -0
  36. package/dist/chunk-BW5KFIQC.js +59 -0
  37. package/dist/chunk-CBD2B5CP.js +599 -0
  38. package/dist/chunk-CFYISHUW.js +42 -0
  39. package/dist/chunk-CMU4RMJB.js +30 -0
  40. package/dist/chunk-CULQYFLU.js +14 -0
  41. package/dist/chunk-D65GOCJB.js +289 -0
  42. package/dist/chunk-D6YF5HKX.js +59 -0
  43. package/dist/chunk-DMS52BEP.js +342 -0
  44. package/dist/chunk-ELVWJYRV.js +211 -0
  45. package/dist/chunk-EUT3B22Y.js +27 -0
  46. package/dist/chunk-F5VLZHUW.js +146 -0
  47. package/dist/chunk-FC4RP4I2.js +12 -0
  48. package/dist/chunk-FGALODG3.js +55 -0
  49. package/dist/chunk-G3RLJYA2.js +2358 -0
  50. package/dist/chunk-GAYGGICG.js +32 -0
  51. package/dist/chunk-H2W2AXD3.js +419 -0
  52. package/dist/chunk-H5EV3VMF.js +114 -0
  53. package/dist/chunk-HREZQCT3.js +106 -0
  54. package/dist/chunk-HSIRMK2D.js +517 -0
  55. package/dist/chunk-IMSQR4WO.js +184 -0
  56. package/dist/chunk-IQZXOZ7S.js +4816 -0
  57. package/dist/chunk-IR6XFA5P.js +37 -0
  58. package/dist/chunk-IUKPRZER.js +78 -0
  59. package/dist/chunk-IUR76K6A.js +262 -0
  60. package/dist/chunk-J3FZR3YY.js +98 -0
  61. package/dist/chunk-J6DFZDFA.js +562 -0
  62. package/dist/chunk-J7WJZ6W7.js +50 -0
  63. package/dist/chunk-JONGANYH.js +202 -0
  64. package/dist/chunk-KJCWXUUS.js +425 -0
  65. package/dist/chunk-KJN4IOEJ.js +17 -0
  66. package/dist/chunk-KMGPUKFD.js +25 -0
  67. package/dist/chunk-LD7WFTRX.js +4533 -0
  68. package/dist/chunk-LJDODBBZ.js +78 -0
  69. package/dist/chunk-LNOMA3MP.js +169 -0
  70. package/dist/chunk-MGIWSROG.js +2334 -0
  71. package/dist/chunk-MQA2YBAH.js +308 -0
  72. package/dist/chunk-MTDRLSI7.js +21720 -0
  73. package/dist/chunk-N2IRDBZI.js +2355 -0
  74. package/dist/chunk-N77WFUL7.js +50 -0
  75. package/dist/chunk-N7YNJE5R.js +466 -0
  76. package/dist/chunk-NABLC7W3.js +148 -0
  77. package/dist/chunk-NFXP47RV.js +999 -0
  78. package/dist/chunk-NJF2X5XF.js +45 -0
  79. package/dist/chunk-NXL4FFQQ.js +47 -0
  80. package/dist/chunk-O7HZX7CA.js +309 -0
  81. package/dist/chunk-OC7LYAU5.js +708 -0
  82. package/dist/chunk-OEX24ECI.js +348 -0
  83. package/dist/chunk-OYOB3ZFG.js +78 -0
  84. package/dist/chunk-OYTMZXRF.js +41 -0
  85. package/dist/chunk-OZJINN4O.js +84 -0
  86. package/dist/chunk-PCHDGUKT.js +23 -0
  87. package/dist/chunk-QOZXJ4NA.js +3364 -0
  88. package/dist/chunk-QYF5S6P6.js +45 -0
  89. package/dist/chunk-RJFED73B.js +79 -0
  90. package/dist/chunk-RTQNRM5X.js +27 -0
  91. package/dist/chunk-S6AMWKPC.js +189 -0
  92. package/dist/chunk-T4QZ6FEH.js +308 -0
  93. package/dist/chunk-T54VJRAD.js +5456 -0
  94. package/dist/chunk-TA5L5KWQ.js +167 -0
  95. package/dist/chunk-TQFBZVCG.js +27 -0
  96. package/dist/chunk-U52SAGRM.js +62 -0
  97. package/dist/chunk-UEAHAMEI.js +5814 -0
  98. package/dist/chunk-UGSMCQ4D.js +327 -0
  99. package/dist/chunk-UOPVJQ4N.js +103 -0
  100. package/dist/chunk-USHG4DLH.js +459 -0
  101. package/dist/chunk-UXVNL3D7.js +23 -0
  102. package/dist/chunk-V5MEBST3.js +4139 -0
  103. package/dist/chunk-VGEVL5EQ.js +29 -0
  104. package/dist/chunk-VPWKF3GN.js +87 -0
  105. package/dist/chunk-VSMJK3ZJ.js +1250 -0
  106. package/dist/chunk-VYKKMYVT.js +560 -0
  107. package/dist/chunk-VZHJS6DR.js +442 -0
  108. package/dist/chunk-WATC3IQR.js +213 -0
  109. package/dist/chunk-WPE5FPGR.js +54 -0
  110. package/dist/chunk-WSEWKCXU.js +188 -0
  111. package/dist/chunk-WW5BLB74.js +659 -0
  112. package/dist/chunk-XGUL4SLQ.js +406 -0
  113. package/dist/chunk-XHSCVSOL.js +170 -0
  114. package/dist/chunk-XIMYZ3JA.js +27 -0
  115. package/dist/chunk-YLN4K6WD.js +385 -0
  116. package/dist/chunk-Z3CCVDUB.js +76 -0
  117. package/dist/chunk-Z54ZSOBZ.js +61 -0
  118. package/dist/chunk-Z6BB4JLQ.js +478 -0
  119. package/dist/chunk-Z7QQA2KT.js +27 -0
  120. package/dist/chunk-ZETYB3XG.js +2626 -0
  121. package/dist/chunk-ZMOMPX2Z.js +87 -0
  122. package/dist/chunk-ZOEYVXSV.js +149 -0
  123. package/dist/chunk-ZZUFZUQZ.js +12120 -0
  124. package/dist/index.js +39712 -29876
  125. package/dist/mcp/analyze-cli.js +186 -232
  126. package/dist/mcp/cli.js +137 -98
  127. package/dist/mcp/server.js +22688 -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 +5 -4
  135. package/docs/configuration.md +28 -2
  136. package/docs/custom-rules.md +25 -2
  137. package/docs/environment-variables.md +86 -8
  138. package/docs/features.md +45 -5
  139. package/docs/globalconfig.md +2 -1
  140. package/docs/io-bridge-v2-migration.md +94 -0
  141. package/docs/lsp-capability-matrix.md +37 -4
  142. package/docs/lsp-idle-eviction.md +124 -0
  143. package/docs/mcp.md +21 -5
  144. package/docs/merge-queue-rollout.md +77 -0
  145. package/docs/pi-lens-fixer.md +160 -88
  146. package/docs/pi-lens-investigator.md +74 -26
  147. package/docs/pi-lens-merge-policy.md +736 -0
  148. package/docs/pi-lens-monitor.md +75 -7
  149. package/docs/pi-lens-retro.md +6 -4
  150. package/docs/pi-lens-reviewer.md +189 -48
  151. package/docs/pi-lens-subagent.md +246 -45
  152. package/docs/pi-lens-warden.md +18 -7
  153. package/docs/public-api-stability.md +55 -0
  154. package/docs/release-qa-baseline.md +84 -17
  155. package/docs/rfcs/3654-unified-io-bridge-v2.md +316 -0
  156. package/docs/schema/pi-lens-config-v1.json +530 -0
  157. package/docs/servercapabilities.md +56 -49
  158. package/docs/settings.md +1 -0
  159. package/docs/usage.md +5 -1
  160. package/docs/word-index.md +6 -0
  161. package/grammars/tree-sitter-bash.wasm +0 -0
  162. package/grammars/tree-sitter-bash.wasm.json +3 -3
  163. package/package.json +19 -7
  164. package/rules/ast-grep-rules/rule-tests/advisory-registry-subset-test.yml +41 -0
  165. package/rules/ast-grep-rules/rule-tests/no-identity-operator-on-literals-test.yml +12 -2
  166. package/rules/ast-grep-rules/rule-tests/throw-new-error-js-test.yml +2 -0
  167. package/rules/ast-grep-rules/rule-tests/throw-new-error-test.yml +2 -0
  168. package/rules/ast-grep-rules/rules/advisory-registry-subset.yml +50 -0
  169. package/rules/ast-grep-rules/rules/no-identity-operator-on-literals.yml +20 -12
  170. package/rules/ast-grep-rules/rules/throw-new-error-js.yml +2 -2
  171. package/rules/ast-grep-rules/rules/throw-new-error.yml +2 -2
  172. package/scripts/analyze-pi-lens-logs.mjs +1275 -62
  173. package/scripts/download-grammars.js +5 -0
  174. package/scripts/grammars.lock.json +6 -1
  175. package/scripts/install-selftest.mjs +33 -34
  176. package/scripts/lib/host-provided-deps.mjs +13 -4
  177. package/scripts/lib/web-tree-sitter-dir.mjs +18 -0
  178. package/dist/clients/actionable-warnings-logger.js +0 -35
  179. package/dist/clients/actionable-warnings.js +0 -1610
  180. package/dist/clients/advisory-provenance.js +0 -593
  181. package/dist/clients/agent-behavior-client.js +0 -147
  182. package/dist/clients/agent-nudge.js +0 -325
  183. package/dist/clients/analysed-root.js +0 -1
  184. package/dist/clients/ast-grep-client.js +0 -731
  185. package/dist/clients/ast-grep-rule-manager.js +0 -146
  186. package/dist/clients/ast-grep-tool-logger.js +0 -118
  187. package/dist/clients/ast-grep-types.js +0 -10
  188. package/dist/clients/ast-grep-yaml-synth.js +0 -154
  189. package/dist/clients/atomic-write-staging.js +0 -75
  190. package/dist/clients/atomic-write.js +0 -189
  191. package/dist/clients/availability-probe-flight.js +0 -12
  192. package/dist/clients/bash-file-access.js +0 -1056
  193. package/dist/clients/biome-client.js +0 -357
  194. package/dist/clients/blocker-freshness.js +0 -837
  195. package/dist/clients/blocker-past-eof.js +0 -129
  196. package/dist/clients/bootstrap.js +0 -569
  197. package/dist/clients/bounded-cache.js +0 -190
  198. package/dist/clients/bounded-pid-file-lock.js +0 -202
  199. package/dist/clients/bounded-telemetry.js +0 -295
  200. package/dist/clients/build-identity.js +0 -95
  201. package/dist/clients/bundled-resource-health.js +0 -113
  202. package/dist/clients/bus-events-logger.js +0 -105
  203. package/dist/clients/bus-publish.js +0 -171
  204. package/dist/clients/cache/rule-cache.js +0 -190
  205. package/dist/clients/cache-manager.js +0 -524
  206. package/dist/clients/cache-observability.js +0 -1313
  207. package/dist/clients/call-graph.js +0 -852
  208. package/dist/clients/cargo-manifest.js +0 -422
  209. package/dist/clients/cascade-budget.js +0 -196
  210. package/dist/clients/cascade-format.js +0 -315
  211. package/dist/clients/cascade-logger.js +0 -31
  212. package/dist/clients/cascade-types.js +0 -9
  213. package/dist/clients/child-unref.js +0 -124
  214. package/dist/clients/code-quality-warnings.js +0 -286
  215. package/dist/clients/codebase-model.js +0 -173
  216. package/dist/clients/collateral-test-role.js +0 -40
  217. package/dist/clients/complexity-client.js +0 -462
  218. package/dist/clients/config-core/deny.js +0 -221
  219. package/dist/clients/config-core/index.js +0 -50
  220. package/dist/clients/config-core/merge.js +0 -357
  221. package/dist/clients/config-core/normalize.js +0 -340
  222. package/dist/clients/config-core/process-spec.js +0 -248
  223. package/dist/clients/config-core/provenance.js +0 -164
  224. package/dist/clients/config-core/records.js +0 -218
  225. package/dist/clients/config-core/resolve.js +0 -125
  226. package/dist/clients/config-core/safe-object.js +0 -78
  227. package/dist/clients/config-core/schema.js +0 -165
  228. package/dist/clients/config-diagnostic-codes.js +0 -285
  229. package/dist/clients/config-locations.js +0 -388
  230. package/dist/clients/config-resolve.js +0 -798
  231. package/dist/clients/config-schema.js +0 -251
  232. package/dist/clients/config-warn.js +0 -407
  233. package/dist/clients/console-guard-install.js +0 -26
  234. package/dist/clients/cooperative-budget.js +0 -42
  235. package/dist/clients/dead-code-client.js +0 -510
  236. package/dist/clients/dead-code-logger.js +0 -30
  237. package/dist/clients/deadline-utils.js +0 -280
  238. package/dist/clients/debug-handles.js +0 -211
  239. package/dist/clients/debug-heap.js +0 -174
  240. package/dist/clients/deferred-lsp-work.js +0 -106
  241. package/dist/clients/degradation-ledger.js +0 -426
  242. package/dist/clients/demoted-finding-render.js +0 -169
  243. package/dist/clients/dependency-checker.js +0 -885
  244. package/dist/clients/deps/ast-grep-napi.js +0 -22
  245. package/dist/clients/deps/js-yaml.js +0 -9
  246. package/dist/clients/deps/minimatch.js +0 -4
  247. package/dist/clients/deps/pi-tui.js +0 -14
  248. package/dist/clients/deps/typebox.js +0 -14
  249. package/dist/clients/deps/vscode-jsonrpc.js +0 -1
  250. package/dist/clients/deps/web-tree-sitter.js +0 -24
  251. package/dist/clients/diagnostic-dispositions.js +0 -630
  252. package/dist/clients/diagnostic-line-freshness.js +0 -305
  253. package/dist/clients/diagnostic-logger.js +0 -73
  254. package/dist/clients/diagnostic-tracker.js +0 -105
  255. package/dist/clients/diagnostics-publish.js +0 -230
  256. package/dist/clients/dispatch/ast-grep-catalog.js +0 -65
  257. package/dist/clients/dispatch/auxiliary-lsp.js +0 -343
  258. package/dist/clients/dispatch/collect-later-tier.js +0 -35
  259. package/dist/clients/dispatch/diagnostic-taxonomy.js +0 -66
  260. package/dist/clients/dispatch/dispatcher.js +0 -1269
  261. package/dist/clients/dispatch/fact-provider-types.js +0 -1
  262. package/dist/clients/dispatch/fact-rule-runner.js +0 -17
  263. package/dist/clients/dispatch/fact-runner.js +0 -30
  264. package/dist/clients/dispatch/fact-scheduler.js +0 -68
  265. package/dist/clients/dispatch/fact-store.js +0 -377
  266. package/dist/clients/dispatch/facts/comment-facts.js +0 -22
  267. package/dist/clients/dispatch/facts/file-content.js +0 -19
  268. package/dist/clients/dispatch/facts/function-facts.js +0 -348
  269. package/dist/clients/dispatch/facts/import-facts.js +0 -204
  270. package/dist/clients/dispatch/facts/tree-sitter-facts.js +0 -34
  271. package/dist/clients/dispatch/facts/try-catch-facts.js +0 -119
  272. package/dist/clients/dispatch/finding-policy.js +0 -339
  273. package/dist/clients/dispatch/indent-detect.js +0 -417
  274. package/dist/clients/dispatch/inline-suppressions.js +0 -89
  275. package/dist/clients/dispatch/integration.js +0 -2377
  276. package/dist/clients/dispatch/lazy.js +0 -11
  277. package/dist/clients/dispatch/pending-runner-findings.js +0 -87
  278. package/dist/clients/dispatch/plan.js +0 -278
  279. package/dist/clients/dispatch/priorities.js +0 -20
  280. package/dist/clients/dispatch/rule-id-normalize.js +0 -50
  281. package/dist/clients/dispatch/rule-ignores.js +0 -69
  282. package/dist/clients/dispatch/rule-policy.js +0 -135
  283. package/dist/clients/dispatch/rules/async-noise.js +0 -40
  284. package/dist/clients/dispatch/rules/async-unnecessary-wrapper.js +0 -27
  285. package/dist/clients/dispatch/rules/cors-wildcard.js +0 -54
  286. package/dist/clients/dispatch/rules/error-obscuring.js +0 -32
  287. package/dist/clients/dispatch/rules/error-swallowing.js +0 -31
  288. package/dist/clients/dispatch/rules/framework-call-noise.js +0 -67
  289. package/dist/clients/dispatch/rules/high-complexity.js +0 -72
  290. package/dist/clients/dispatch/rules/high-fan-out.js +0 -74
  291. package/dist/clients/dispatch/rules/high-import-coupling.js +0 -37
  292. package/dist/clients/dispatch/rules/missing-error-propagation.js +0 -62
  293. package/dist/clients/dispatch/rules/no-commented-credentials.js +0 -52
  294. package/dist/clients/dispatch/rules/pass-through-wrappers.js +0 -42
  295. package/dist/clients/dispatch/rules/placeholder-comments.js +0 -40
  296. package/dist/clients/dispatch/rules/unsafe-boundary.js +0 -126
  297. package/dist/clients/dispatch/runner-context.js +0 -52
  298. package/dist/clients/dispatch/runners/actionlint.js +0 -111
  299. package/dist/clients/dispatch/runners/ast-grep-napi.js +0 -1196
  300. package/dist/clients/dispatch/runners/biome-check.js +0 -296
  301. package/dist/clients/dispatch/runners/cpp-check.js +0 -219
  302. package/dist/clients/dispatch/runners/credo.js +0 -82
  303. package/dist/clients/dispatch/runners/cue-vet.js +0 -416
  304. package/dist/clients/dispatch/runners/dart-analyze.js +0 -183
  305. package/dist/clients/dispatch/runners/detekt.js +0 -176
  306. package/dist/clients/dispatch/runners/dotnet-build.js +0 -164
  307. package/dist/clients/dispatch/runners/elixir-check.js +0 -195
  308. package/dist/clients/dispatch/runners/eslint.js +0 -137
  309. package/dist/clients/dispatch/runners/fact-rules.js +0 -29
  310. package/dist/clients/dispatch/runners/fish-indent.js +0 -69
  311. package/dist/clients/dispatch/runners/gleam-check.js +0 -167
  312. package/dist/clients/dispatch/runners/go-vet.js +0 -104
  313. package/dist/clients/dispatch/runners/golangci-lint.js +0 -135
  314. package/dist/clients/dispatch/runners/hadolint.js +0 -91
  315. package/dist/clients/dispatch/runners/helm-lint.js +0 -171
  316. package/dist/clients/dispatch/runners/helm-render.js +0 -940
  317. package/dist/clients/dispatch/runners/htmlhint.js +0 -117
  318. package/dist/clients/dispatch/runners/index.js +0 -108
  319. package/dist/clients/dispatch/runners/javac.js +0 -99
  320. package/dist/clients/dispatch/runners/ktlint.js +0 -110
  321. package/dist/clients/dispatch/runners/lsp.js +0 -379
  322. package/dist/clients/dispatch/runners/markdownlint.js +0 -167
  323. package/dist/clients/dispatch/runners/mypy.js +0 -102
  324. package/dist/clients/dispatch/runners/oxlint.js +0 -414
  325. package/dist/clients/dispatch/runners/php-lint.js +0 -85
  326. package/dist/clients/dispatch/runners/phpstan.js +0 -120
  327. package/dist/clients/dispatch/runners/prisma-validate.js +0 -62
  328. package/dist/clients/dispatch/runners/psscriptanalyzer.js +0 -445
  329. package/dist/clients/dispatch/runners/pyright.js +0 -169
  330. package/dist/clients/dispatch/runners/rubocop.js +0 -99
  331. package/dist/clients/dispatch/runners/ruff.js +0 -88
  332. package/dist/clients/dispatch/runners/rust-clippy.js +0 -256
  333. package/dist/clients/dispatch/runners/shellcheck.js +0 -173
  334. package/dist/clients/dispatch/runners/shfmt.js +0 -102
  335. package/dist/clients/dispatch/runners/spellcheck.js +0 -128
  336. package/dist/clients/dispatch/runners/spotbugs.js +0 -259
  337. package/dist/clients/dispatch/runners/sqlfluff.js +0 -183
  338. package/dist/clients/dispatch/runners/stylelint.js +0 -166
  339. package/dist/clients/dispatch/runners/swiftlint.js +0 -163
  340. package/dist/clients/dispatch/runners/taplo.js +0 -174
  341. package/dist/clients/dispatch/runners/terragrunt.js +0 -168
  342. package/dist/clients/dispatch/runners/tflint.js +0 -125
  343. package/dist/clients/dispatch/runners/tree-sitter.js +0 -643
  344. package/dist/clients/dispatch/runners/trivy-config.js +0 -253
  345. package/dist/clients/dispatch/runners/utils/availability-policy.js +0 -496
  346. package/dist/clients/dispatch/runners/utils/candidate-probe.js +0 -90
  347. package/dist/clients/dispatch/runners/utils/diagnostic-parsers.js +0 -95
  348. package/dist/clients/dispatch/runners/utils/lazy-installer.js +0 -274
  349. package/dist/clients/dispatch/runners/utils/runner-helpers.js +0 -1701
  350. package/dist/clients/dispatch/runners/utils/spawn-outcome.js +0 -101
  351. package/dist/clients/dispatch/runners/utils/tool-failure.js +0 -235
  352. package/dist/clients/dispatch/runners/utils/toolchain-availability.js +0 -169
  353. package/dist/clients/dispatch/runners/utils.js +0 -15
  354. package/dist/clients/dispatch/runners/vale.js +0 -128
  355. package/dist/clients/dispatch/runners/yaml-rule-parser.js +0 -242
  356. package/dist/clients/dispatch/runners/yamllint.js +0 -95
  357. package/dist/clients/dispatch/runners/zig-check.js +0 -79
  358. package/dist/clients/dispatch/suppress-writer.js +0 -79
  359. package/dist/clients/dispatch/tool-profile.js +0 -30
  360. package/dist/clients/dispatch/types.js +0 -21
  361. package/dist/clients/dispatch/utils/format-utils.js +0 -45
  362. package/dist/clients/dispatch/utils/lsp-diagnostics.js +0 -35
  363. package/dist/clients/disposition-logger.js +0 -32
  364. package/dist/clients/disposition-publish.js +0 -124
  365. package/dist/clients/durable-store.js +0 -97
  366. package/dist/clients/effective-config.js +0 -415
  367. package/dist/clients/env-utils.js +0 -83
  368. package/dist/clients/error-class.js +0 -23
  369. package/dist/clients/eval-timestamp.js +0 -17
  370. package/dist/clients/event-loop-hold.js +0 -274
  371. package/dist/clients/event-loop-monitor.js +0 -250
  372. package/dist/clients/extension-log.js +0 -504
  373. package/dist/clients/extension-mode.js +0 -73
  374. package/dist/clients/feature-hints.js +0 -103
  375. package/dist/clients/file-kinds.js +0 -412
  376. package/dist/clients/file-role.js +0 -134
  377. package/dist/clients/file-time.js +0 -160
  378. package/dist/clients/file-utils.js +0 -1032
  379. package/dist/clients/finding-delivery-gate.js +0 -494
  380. package/dist/clients/finding-identity.js +0 -88
  381. package/dist/clients/fix-worklog.js +0 -103
  382. package/dist/clients/format-events-publish.js +0 -343
  383. package/dist/clients/format-service.js +0 -222
  384. package/dist/clients/formatters-lazy.js +0 -9
  385. package/dist/clients/formatters.js +0 -2032
  386. package/dist/clients/freshness-cadence.js +0 -17
  387. package/dist/clients/freshness.js +0 -38
  388. package/dist/clients/generated-artifacts.js +0 -394
  389. package/dist/clients/generation-guard.js +0 -215
  390. package/dist/clients/git-guard.js +0 -1136
  391. package/dist/clients/git-tracked-ignore.js +0 -243
  392. package/dist/clients/gitleaks-client.js +0 -509
  393. package/dist/clients/go-client.js +0 -104
  394. package/dist/clients/govulncheck-client.js +0 -605
  395. package/dist/clients/gradle-ktfmt-style.js +0 -348
  396. package/dist/clients/grammar-source.js +0 -465
  397. package/dist/clients/gzip-stage-write.js +0 -135
  398. package/dist/clients/hashline-anchor.js +0 -424
  399. package/dist/clients/hook-budgets.js +0 -76
  400. package/dist/clients/host-edit-normalize.js +0 -140
  401. package/dist/clients/host-ports.js +0 -39
  402. package/dist/clients/indent-retarget.js +0 -154
  403. package/dist/clients/inline-blocker-dispositions.js +0 -186
  404. package/dist/clients/install-diagnostics.js +0 -156
  405. package/dist/clients/installer/index.js +0 -5416
  406. package/dist/clients/installer/managed-tool-refresh-session.js +0 -58
  407. package/dist/clients/installer/managed-tool-refresh.js +0 -783
  408. package/dist/clients/instance-reaper-state.js +0 -7
  409. package/dist/clients/instance-reaper.js +0 -1137
  410. package/dist/clients/instance-registry-lock.js +0 -145
  411. package/dist/clients/instance-registry.js +0 -773
  412. package/dist/clients/jscpd-client.js +0 -378
  413. package/dist/clients/json-cache-read.js +0 -65
  414. package/dist/clients/knip-client.js +0 -788
  415. package/dist/clients/language-policy.js +0 -252
  416. package/dist/clients/language-profile.js +0 -361
  417. package/dist/clients/language-registry.js +0 -603
  418. package/dist/clients/latency-logger.js +0 -727
  419. package/dist/clients/lazy-import.js +0 -21
  420. package/dist/clients/ledger-bounds.js +0 -54
  421. package/dist/clients/lens-config.js +0 -404
  422. package/dist/clients/lens-engine.js +0 -358
  423. package/dist/clients/lens-events.js +0 -125
  424. package/dist/clients/lens-flag-registry.js +0 -467
  425. package/dist/clients/lens-map.js +0 -1156
  426. package/dist/clients/live-bus-emitter.js +0 -74
  427. package/dist/clients/log-cleanup.js +0 -222
  428. package/dist/clients/lsp/aggregation.js +0 -178
  429. package/dist/clients/lsp/cascade-tier.js +0 -421
  430. package/dist/clients/lsp/client.js +0 -4593
  431. package/dist/clients/lsp/config.js +0 -691
  432. package/dist/clients/lsp/content-limits.js +0 -41
  433. package/dist/clients/lsp/diagnostic-binding.js +0 -225
  434. package/dist/clients/lsp/document-drift.js +0 -467
  435. package/dist/clients/lsp/edits.js +0 -1219
  436. package/dist/clients/lsp/index.js +0 -8305
  437. package/dist/clients/lsp/inferred-project.js +0 -216
  438. package/dist/clients/lsp/jvm-runtime.js +0 -298
  439. package/dist/clients/lsp/language.js +0 -63
  440. package/dist/clients/lsp/launch.js +0 -746
  441. package/dist/clients/lsp/lombok.js +0 -158
  442. package/dist/clients/lsp/path-utils.js +0 -5
  443. package/dist/clients/lsp/pending-aux-coverage.js +0 -251
  444. package/dist/clients/lsp/position-encoding.js +0 -61
  445. package/dist/clients/lsp/ruby-drive-dirs.js +0 -83
  446. package/dist/clients/lsp/server.js +0 -3290
  447. package/dist/clients/lsp/session-roots.js +0 -192
  448. package/dist/clients/lsp/spawn-history.js +0 -17
  449. package/dist/clients/lsp/sync-kind.js +0 -56
  450. package/dist/clients/lsp/tsserver-sync.js +0 -332
  451. package/dist/clients/lsp/wait-policy/capability-snapshot.js +0 -1
  452. package/dist/clients/lsp/wait-policy/classification.js +0 -85
  453. package/dist/clients/lsp/wait-policy/index.js +0 -10
  454. package/dist/clients/lsp/wait-policy/strategies.js +0 -392
  455. package/dist/clients/lsp/watch-queue.js +0 -61
  456. package/dist/clients/lsp/workspace-diagnostics-cache.js +0 -639
  457. package/dist/clients/lsp/workspace-diagnostics-session.js +0 -30
  458. package/dist/clients/lsp/workspace-sweep-hold.js +0 -184
  459. package/dist/clients/lsp-budget.js +0 -186
  460. package/dist/clients/lsp-document-symbols.js +0 -110
  461. package/dist/clients/lsp-lazy.js +0 -9
  462. package/dist/clients/lsp-mutation.js +0 -396
  463. package/dist/clients/lsp-status.js +0 -59
  464. package/dist/clients/map-with-concurrency.js +0 -40
  465. package/dist/clients/mcp/analyze.js +0 -420
  466. package/dist/clients/mcp/host-shim.js +0 -31
  467. package/dist/clients/mcp/ipc.js +0 -523
  468. package/dist/clients/mcp/review.js +0 -197
  469. package/dist/clients/mcp/session.js +0 -412
  470. package/dist/clients/memory-sampler.js +0 -208
  471. package/dist/clients/message-end-attribution.js +0 -30
  472. package/dist/clients/metrics-client.js +0 -107
  473. package/dist/clients/metrics-history.js +0 -327
  474. package/dist/clients/middle-man-analysis.js +0 -263
  475. package/dist/clients/model-provider.js +0 -53
  476. package/dist/clients/module-report-lsp.js +0 -189
  477. package/dist/clients/module-report.js +0 -2150
  478. package/dist/clients/mutating-tool.js +0 -651
  479. package/dist/clients/mutation-attribution.js +0 -368
  480. package/dist/clients/mutation-bridge.js +0 -240
  481. package/dist/clients/ndjson-logger.js +0 -734
  482. package/dist/clients/observed-mutation-sources.js +0 -101
  483. package/dist/clients/observed-mutation.js +0 -1253
  484. package/dist/clients/oldtext-autopatch.js +0 -128
  485. package/dist/clients/opaque-mutation-scan.js +0 -496
  486. package/dist/clients/opengrep-client.js +0 -333
  487. package/dist/clients/opengrep-config.js +0 -76
  488. package/dist/clients/package-manager.js +0 -607
  489. package/dist/clients/package-root.js +0 -38
  490. package/dist/clients/partial-edit-apply.js +0 -439
  491. package/dist/clients/path-attribution-telemetry.js +0 -43
  492. package/dist/clients/path-keyed-map.js +0 -108
  493. package/dist/clients/path-utils.js +0 -1244
  494. package/dist/clients/performance-report.js +0 -331
  495. package/dist/clients/persist-debounce.js +0 -70
  496. package/dist/clients/persistent-reverify.js +0 -271
  497. package/dist/clients/php-cs-fixer-config.js +0 -119
  498. package/dist/clients/pipeline.js +0 -1480
  499. package/dist/clients/post-autofix-notice.js +0 -37
  500. package/dist/clients/print-mode.js +0 -21
  501. package/dist/clients/probe-home-state.js +0 -228
  502. package/dist/clients/process-bridge.js +0 -66
  503. package/dist/clients/process-singletons.js +0 -210
  504. package/dist/clients/process-snapshot.js +0 -68
  505. package/dist/clients/project-changes.js +0 -181
  506. package/dist/clients/project-conventions.js +0 -171
  507. package/dist/clients/project-diagnostics/cache.js +0 -137
  508. package/dist/clients/project-diagnostics/extractors.js +0 -109
  509. package/dist/clients/project-diagnostics/fresh-fetch.js +0 -668
  510. package/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +0 -118
  511. package/dist/clients/project-diagnostics/runner-adapters/dead-code.js +0 -47
  512. package/dist/clients/project-diagnostics/runner-adapters/gitleaks.js +0 -40
  513. package/dist/clients/project-diagnostics/runner-adapters/govulncheck.js +0 -34
  514. package/dist/clients/project-diagnostics/runner-adapters/jscpd.js +0 -38
  515. package/dist/clients/project-diagnostics/runner-adapters/knip.js +0 -47
  516. package/dist/clients/project-diagnostics/runner-adapters/madge.js +0 -48
  517. package/dist/clients/project-diagnostics/runner-adapters/opengrep.js +0 -40
  518. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +0 -127
  519. package/dist/clients/project-diagnostics/runner-adapters/trivy.js +0 -81
  520. package/dist/clients/project-diagnostics/scanner.js +0 -520
  521. package/dist/clients/project-diagnostics/types.js +0 -1
  522. package/dist/clients/project-lens-config.js +0 -807
  523. package/dist/clients/project-report.js +0 -701
  524. package/dist/clients/project-scale.js +0 -237
  525. package/dist/clients/project-scan-policy.js +0 -11
  526. package/dist/clients/project-snapshot-fingerprint.js +0 -48
  527. package/dist/clients/project-snapshot-persist-worker.js +0 -20
  528. package/dist/clients/project-snapshot.js +0 -1653
  529. package/dist/clients/project-trust.js +0 -181
  530. package/dist/clients/python-environment.js +0 -217
  531. package/dist/clients/python-provenance.js +0 -639
  532. package/dist/clients/quiet-window-config.js +0 -47
  533. package/dist/clients/quiet-window.js +0 -236
  534. package/dist/clients/read-bridge.js +0 -139
  535. package/dist/clients/read-expansion.js +0 -266
  536. package/dist/clients/read-guard-logger.js +0 -251
  537. package/dist/clients/read-guard-tool-lines.js +0 -1306
  538. package/dist/clients/read-guard.js +0 -1561
  539. package/dist/clients/recent-touches.js +0 -240
  540. package/dist/clients/redact/secrets.js +0 -449
  541. package/dist/clients/resource-sampler.js +0 -628
  542. package/dist/clients/reverse-deps.js +0 -270
  543. package/dist/clients/review-graph/builder.js +0 -5126
  544. package/dist/clients/review-graph/format.js +0 -33
  545. package/dist/clients/review-graph/git-identity.js +0 -163
  546. package/dist/clients/review-graph/import-resolvers.js +0 -481
  547. package/dist/clients/review-graph/persist-worker.js +0 -10
  548. package/dist/clients/review-graph/query.js +0 -244
  549. package/dist/clients/review-graph/revision-drift.js +0 -21
  550. package/dist/clients/review-graph/service.js +0 -96
  551. package/dist/clients/review-graph/shared-extraction-ir.js +0 -82
  552. package/dist/clients/review-graph/symbol-id.js +0 -103
  553. package/dist/clients/review-graph/tsconfig-paths.js +0 -299
  554. package/dist/clients/review-graph/types.js +0 -1
  555. package/dist/clients/review-graph/workspace-modules.js +0 -449
  556. package/dist/clients/review-graph-logger.js +0 -81
  557. package/dist/clients/ruff-client.js +0 -179
  558. package/dist/clients/rules-scanner.js +0 -131
  559. package/dist/clients/run-duration.js +0 -55
  560. package/dist/clients/runtime-agent-end.js +0 -746
  561. package/dist/clients/runtime-config.js +0 -77
  562. package/dist/clients/runtime-context.js +0 -211
  563. package/dist/clients/runtime-coordinator.js +0 -1324
  564. package/dist/clients/runtime-session.js +0 -2485
  565. package/dist/clients/runtime-tool-call.js +0 -1295
  566. package/dist/clients/runtime-tool-result.js +0 -2049
  567. package/dist/clients/runtime-turn.js +0 -3767
  568. package/dist/clients/rust-client.js +0 -97
  569. package/dist/clients/safe-spawn.js +0 -2357
  570. package/dist/clients/sanitize.js +0 -286
  571. package/dist/clients/scan-utils.js +0 -25
  572. package/dist/clients/scratch-tree-policy.js +0 -165
  573. package/dist/clients/search-read-registration.js +0 -94
  574. package/dist/clients/secret-findings.js +0 -114
  575. package/dist/clients/security-scan-client.js +0 -352
  576. package/dist/clients/session-event-guard.js +0 -297
  577. package/dist/clients/session-lifecycle.js +0 -484
  578. package/dist/clients/session-start-observability.js +0 -94
  579. package/dist/clients/session-state-store.js +0 -101
  580. package/dist/clients/session-summary.js +0 -15
  581. package/dist/clients/sessionstart-logger.js +0 -27
  582. package/dist/clients/sg-runner.js +0 -876
  583. package/dist/clients/sgconfig.js +0 -347
  584. package/dist/clients/shared-checkout-guard.js +0 -338
  585. package/dist/clients/single-flight.js +0 -158
  586. package/dist/clients/situational-tool-telemetry.js +0 -108
  587. package/dist/clients/skills-resolver.js +0 -141
  588. package/dist/clients/slow-fs.js +0 -138
  589. package/dist/clients/smells-rollup.js +0 -231
  590. package/dist/clients/source-filter.js +0 -596
  591. package/dist/clients/source-walker.js +0 -211
  592. package/dist/clients/spawn-output-cap.js +0 -120
  593. package/dist/clients/spawn-timeout-cooldown.js +0 -110
  594. package/dist/clients/stale-marker.js +0 -17
  595. package/dist/clients/startup-scan.js +0 -400
  596. package/dist/clients/startup-timing.js +0 -130
  597. package/dist/clients/string-utils.js +0 -33
  598. package/dist/clients/subagent-mode.js +0 -111
  599. package/dist/clients/symbol-containment.js +0 -24
  600. package/dist/clients/symbol-types.js +0 -5
  601. package/dist/clients/test-runner-client.js +0 -2507
  602. package/dist/clients/test-runner-delivery.js +0 -287
  603. package/dist/clients/todo-scanner.js +0 -229
  604. package/dist/clients/tool-agreement.js +0 -423
  605. package/dist/clients/tool-config.js +0 -249
  606. package/dist/clients/tool-cwd.js +0 -270
  607. package/dist/clients/tool-definition.js +0 -47
  608. package/dist/clients/tool-event.js +0 -105
  609. package/dist/clients/tool-policy.js +0 -2755
  610. package/dist/clients/tool-probe.js +0 -53
  611. package/dist/clients/tool-render.js +0 -156
  612. package/dist/clients/tool-set-policy.js +0 -118
  613. package/dist/clients/tree-sitter-cache.js +0 -364
  614. package/dist/clients/tree-sitter-client.js +0 -4195
  615. package/dist/clients/tree-sitter-logger.js +0 -100
  616. package/dist/clients/tree-sitter-navigator.js +0 -269
  617. package/dist/clients/tree-sitter-query-loader.js +0 -569
  618. package/dist/clients/tree-sitter-shared.js +0 -158
  619. package/dist/clients/tree-sitter-symbol-extractor.js +0 -1265
  620. package/dist/clients/trivy-client.js +0 -467
  621. package/dist/clients/tui-fit.js +0 -50
  622. package/dist/clients/turn-context.js +0 -52
  623. package/dist/clients/turn-end/lane.js +0 -51
  624. package/dist/clients/turn-end/lanes/govulncheck.js +0 -112
  625. package/dist/clients/turn-end/lanes/secrets.js +0 -204
  626. package/dist/clients/turn-summary-render.js +0 -72
  627. package/dist/clients/turn-summary.js +0 -132
  628. package/dist/clients/typos-config.js +0 -29
  629. package/dist/clients/user-notify.js +0 -51
  630. package/dist/clients/vanished-instance-marker.js +0 -57
  631. package/dist/clients/warm-attach.js +0 -305
  632. package/dist/clients/widget-state.js +0 -1808
  633. package/dist/clients/word-index-logger.js +0 -49
  634. package/dist/clients/word-index-store.js +0 -459
  635. package/dist/clients/word-index.js +0 -2080
  636. package/dist/clients/workspace-topology.js +0 -443
  637. package/dist/clients/write-ordering-guard.js +0 -65
  638. package/dist/clients/zizmor-config.js +0 -340
  639. package/dist/i18n.js +0 -69
  640. package/dist/mcp/build-staleness.js +0 -124
  641. package/dist/scripts/lib/process-scan.mjs +0 -583
  642. package/dist/scripts/lib/skills-predicate.mjs +0 -129
  643. package/dist/scripts/lib/web-tree-sitter-dir.mjs +0 -123
  644. package/dist/tools/activate-tools.js +0 -87
  645. package/dist/tools/ast-grep-outline.js +0 -137
  646. package/dist/tools/ast-grep-replace.js +0 -244
  647. package/dist/tools/ast-grep-search.js +0 -762
  648. package/dist/tools/effective-config.js +0 -90
  649. package/dist/tools/lens-diagnostic-mark.js +0 -375
  650. package/dist/tools/lens-diagnostics.js +0 -2571
  651. package/dist/tools/lsp-diagnostics.js +0 -1745
  652. package/dist/tools/lsp-navigation.js +0 -1367
  653. package/dist/tools/lsp-structured-output.js +0 -294
  654. package/dist/tools/module-report.js +0 -382
  655. package/dist/tools/project-report.js +0 -86
  656. package/dist/tools/render-compact.js +0 -374
  657. package/dist/tools/scan-progress.js +0 -53
  658. package/dist/tools/shared.js +0 -29
  659. package/dist/tools/symbol-search.js +0 -155
@@ -0,0 +1,2626 @@
1
+ import { createRequire as __pilensCreateRequire } from "node:module"; const require = __pilensCreateRequire(import.meta.url);
2
+ import {
3
+ tryLazyInstallForFormatter
4
+ } from "./chunk-ZOEYVXSV.js";
5
+ import {
6
+ stripAnsi
7
+ } from "./chunk-FC4RP4I2.js";
8
+ import {
9
+ OXFMT_SUPPORTED_EXTENSIONS,
10
+ findPSScriptAnalyzerConfigPath,
11
+ getAutoInstallToolIdForFormatter,
12
+ getFormatterPolicyForFile,
13
+ getSmartDefaultFormatterName,
14
+ gradleBlockRanges,
15
+ hasBiomeConfig,
16
+ hasBlackConfig,
17
+ hasClangFormatConfig,
18
+ hasCljfmtConfig,
19
+ hasCmakeFormatConfig,
20
+ hasCsharpierConfig,
21
+ hasDetektConfig,
22
+ hasFantomasConfig,
23
+ hasGolangciConfig,
24
+ hasGoogleJavaFormatConfig,
25
+ hasGradleKtlintPlugin,
26
+ hasKtfmtConfig,
27
+ hasKtlintConfig,
28
+ hasMarkdownlintConfig,
29
+ hasMixFormatConfig,
30
+ hasNearestPackageJsonDependency,
31
+ hasNearestPackageJsonField,
32
+ hasOcamlformatConfig,
33
+ hasOrmoluConfig,
34
+ hasOxfmtConfig,
35
+ hasOxfmtSvelteConfig,
36
+ hasPSScriptAnalyzerConfig,
37
+ hasPhpCsFixerConfig,
38
+ hasPrettierConfig,
39
+ hasRubocopConfig,
40
+ hasRuffConfig,
41
+ hasSqlfluffConfig,
42
+ hasStandardrbConfig,
43
+ hasStyluaConfig,
44
+ hasSwiftformatConfig,
45
+ hasTaploConfig,
46
+ hasTerraformConfig,
47
+ hasVitePlusConfig,
48
+ stripGradleCommentsAndStrings
49
+ } from "./chunk-MGIWSROG.js";
50
+ import {
51
+ load
52
+ } from "./chunk-QOZXJ4NA.js";
53
+ import {
54
+ readTextFileOrUndefined,
55
+ resolveCargoPackageEdition
56
+ } from "./chunk-S6AMWKPC.js";
57
+ import {
58
+ getToolPath
59
+ } from "./chunk-LD7WFTRX.js";
60
+ import {
61
+ resolveToolCwd
62
+ } from "./chunk-IUR76K6A.js";
63
+ import {
64
+ VENDOR_BIN_DIRS,
65
+ VENV_BIN_DIRS,
66
+ findGlobalBinary,
67
+ findLocalBinUpwards
68
+ } from "./chunk-T4QZ6FEH.js";
69
+ import {
70
+ assertInstallAllowed
71
+ } from "./chunk-D6YF5HKX.js";
72
+ import {
73
+ probeToolAsync
74
+ } from "./chunk-CMU4RMJB.js";
75
+ import {
76
+ classifyProbeFailure,
77
+ createAvailabilityLatch,
78
+ logAvailabilityDecision,
79
+ startHostStallSampler
80
+ } from "./chunk-O7HZX7CA.js";
81
+ import {
82
+ createGenerationSource,
83
+ safeSpawnAsync
84
+ } from "./chunk-T54VJRAD.js";
85
+ import {
86
+ TERRAGRUNT_FILENAMES
87
+ } from "./chunk-64LU2OVH.js";
88
+ import {
89
+ compareOrdinal,
90
+ getDegradationLedgerGeneration,
91
+ incrementDegradationCount,
92
+ recordDegradationOnce
93
+ } from "./chunk-7ELY2CSM.js";
94
+ import {
95
+ logExtension
96
+ } from "./chunk-34OCDWOS.js";
97
+ import {
98
+ logLatency
99
+ } from "./chunk-3PNFWVHT.js";
100
+ import {
101
+ BoundedFifoMap,
102
+ BoundedLruCache
103
+ } from "./chunk-ABBOA7UD.js";
104
+ import {
105
+ findNearestContaining,
106
+ findNearestMarkerRoot,
107
+ normalizeMapKey,
108
+ toPosix
109
+ } from "./chunk-G3RLJYA2.js";
110
+
111
+ // dist/clients/formatters.js
112
+ import { AsyncLocalStorage } from "node:async_hooks";
113
+ import * as fs2 from "node:fs/promises";
114
+ import * as os2 from "node:os";
115
+ import * as path4 from "node:path";
116
+
117
+ // dist/clients/gradle-ktfmt-style.js
118
+ import * as os from "node:os";
119
+ import * as path from "node:path";
120
+ var KTFMT_GRADLE_ROOT_FILES = [
121
+ "build.gradle.kts",
122
+ "build.gradle",
123
+ "settings.gradle.kts",
124
+ "settings.gradle"
125
+ ];
126
+ var MAX_GRADLE_ANCESTOR_HOPS = 16;
127
+ var MAX_SPOTLESS_KTFMT_CALL_CHARS = 4096;
128
+ var KTFMT_STYLE_CLI_FLAG = {
129
+ google: "--google-style",
130
+ kotlinlang: "--kotlinlang-style"
131
+ };
132
+ function styleFromKtfmtBlockBody(body) {
133
+ let style;
134
+ let lastIndex = -1;
135
+ for (const [call, candidate] of [
136
+ [/\bgoogleStyle\s*\(\s*\)/g, "google"],
137
+ [/\bkotlinLangStyle\s*\(\s*\)/g, "kotlinlang"]
138
+ ]) {
139
+ for (const match of body.matchAll(call)) {
140
+ if (match.index > lastIndex) {
141
+ lastIndex = match.index;
142
+ style = candidate;
143
+ }
144
+ }
145
+ }
146
+ return style;
147
+ }
148
+ function findBalancedCallEnd(source, openingParen) {
149
+ let depth = 0;
150
+ const limit = Math.min(source.length, openingParen + MAX_SPOTLESS_KTFMT_CALL_CHARS);
151
+ for (let index = openingParen; index < limit; index += 1) {
152
+ if (source[index] === "(")
153
+ depth += 1;
154
+ if (source[index] !== ")")
155
+ continue;
156
+ depth -= 1;
157
+ if (depth === 0)
158
+ return index + 1;
159
+ }
160
+ return void 0;
161
+ }
162
+ function styleFromSpotlessKotlinBody(body) {
163
+ let style;
164
+ for (const call of body.matchAll(/\bktfmt\s*(?=\()/g)) {
165
+ const callOpenParen = call.index + call[0].length;
166
+ const closeParen = findBalancedCallEnd(body, callOpenParen);
167
+ if (closeParen === void 0)
168
+ continue;
169
+ const chain = /^\s*((?:\.\s*(?:googleStyle|kotlinlangStyle|dropboxStyle)\s*\(\s*\)\s*)+)/.exec(body.slice(closeParen));
170
+ if (!chain)
171
+ continue;
172
+ const chainBody = chain[1];
173
+ if (!chainBody)
174
+ continue;
175
+ for (const method of chainBody.matchAll(/\.\s*(googleStyle|kotlinlangStyle|dropboxStyle)\s*\(\s*\)/g)) {
176
+ if (method[1] === "googleStyle")
177
+ style = "google";
178
+ if (method[1] === "kotlinlangStyle")
179
+ style = "kotlinlang";
180
+ if (method[1] === "dropboxStyle")
181
+ style = "spotless-dropbox-unsupported";
182
+ }
183
+ }
184
+ return style;
185
+ }
186
+ var SCOPE_BY_ENCLOSING_BLOCK = {
187
+ subprojects: "descendants",
188
+ allprojects: "both"
189
+ };
190
+ function scopeOfGradleStyleBlock(range, ranges) {
191
+ const enclosing = ranges.filter((outer) => outer.start < range.start && outer.end >= range.end);
192
+ if (enclosing.length === 0)
193
+ return "own";
194
+ if (enclosing.length > 1)
195
+ return void 0;
196
+ return SCOPE_BY_ENCLOSING_BLOCK[enclosing[0].name];
197
+ }
198
+ function styleSelectionForGradleBlock(block, source, allBlockRanges, nonSpotlessRanges) {
199
+ if (block.name === "ktfmt") {
200
+ const scope2 = scopeOfGradleStyleBlock(block, allBlockRanges);
201
+ if (!scope2)
202
+ return void 0;
203
+ const style2 = styleFromKtfmtBlockBody(source.slice(block.start, block.end));
204
+ return style2 ? { scope: scope2, style: style2 } : void 0;
205
+ }
206
+ if (block.name !== "kotlin")
207
+ return void 0;
208
+ const enclosingSpotless = [];
209
+ for (const outer of allBlockRanges) {
210
+ if (outer.name === "spotless" && outer.start < block.start && outer.end >= block.end) {
211
+ enclosingSpotless.push(outer);
212
+ }
213
+ }
214
+ if (enclosingSpotless.length !== 1)
215
+ return void 0;
216
+ const scope = scopeOfGradleStyleBlock(block, nonSpotlessRanges);
217
+ if (!scope)
218
+ return void 0;
219
+ const style = styleFromSpotlessKotlinBody(source.slice(block.start, block.end));
220
+ return style ? { scope, style } : void 0;
221
+ }
222
+ function stylesFromGradleContent(content) {
223
+ const stripped = stripGradleCommentsAndStrings(content);
224
+ const blocks = gradleBlockRanges(stripped);
225
+ const scopeRanges = [];
226
+ for (const range of blocks) {
227
+ if (range.name !== "spotless")
228
+ scopeRanges.push(range);
229
+ }
230
+ const styles = {};
231
+ for (const range of blocks) {
232
+ const selection = styleSelectionForGradleBlock(range, stripped, blocks, scopeRanges);
233
+ if (!selection)
234
+ continue;
235
+ if (selection.scope !== "descendants")
236
+ styles.own = selection.style;
237
+ if (selection.scope !== "own")
238
+ styles.descendants = selection.style;
239
+ }
240
+ return styles;
241
+ }
242
+ async function stylesForGradleDir(gradleDir) {
243
+ for (const gradleFile of KTFMT_GRADLE_ROOT_FILES) {
244
+ const content = await readTextFileOrUndefined(path.join(gradleDir, gradleFile));
245
+ if (content === void 0)
246
+ continue;
247
+ const styles = stylesFromGradleContent(content);
248
+ if (styles.own || styles.descendants)
249
+ return styles;
250
+ }
251
+ return {};
252
+ }
253
+ async function resolveKtfmtGradleStyle(filePath, homeDir = os.homedir()) {
254
+ let searchDir = path.dirname(path.resolve(filePath));
255
+ for (let hop = 0; hop < MAX_GRADLE_ANCESTOR_HOPS; hop += 1) {
256
+ const gradleDir = findNearestMarkerRoot(searchDir, KTFMT_GRADLE_ROOT_FILES, {
257
+ homeDir
258
+ });
259
+ if (!gradleDir)
260
+ return void 0;
261
+ const styles = await stylesForGradleDir(gradleDir);
262
+ const style = hop === 0 ? styles.own : styles.descendants;
263
+ if (style === "spotless-dropbox-unsupported") {
264
+ const reason = "Spotless ktfmt dropboxStyle(): pi-lens standalone CLI cannot express the style; falling back to bare ktfmt";
265
+ const firstOccurrence = incrementDegradationCount({
266
+ kind: "formatter-skip",
267
+ subject: "ktfmt:spotless-dropbox",
268
+ reason,
269
+ metadata: { filePath, gradleDir }
270
+ });
271
+ if (firstOccurrence) {
272
+ logExtension({
273
+ subsystem: "format",
274
+ level: "debug",
275
+ message: reason,
276
+ metadata: { filePath, gradleDir }
277
+ });
278
+ }
279
+ return void 0;
280
+ }
281
+ if (style)
282
+ return KTFMT_STYLE_CLI_FLAG[style];
283
+ const parent = path.dirname(gradleDir);
284
+ if (parent === gradleDir)
285
+ return void 0;
286
+ searchDir = parent;
287
+ }
288
+ return void 0;
289
+ }
290
+
291
+ // dist/clients/php-cs-fixer-config.js
292
+ import { existsSync } from "node:fs";
293
+ import * as path2 from "node:path";
294
+ var PHP_CS_FIXER_CONFIG_NAMES = [
295
+ ".php-cs-fixer.php",
296
+ ".php-cs-fixer.dist.php"
297
+ ];
298
+ function resolvePhpCsFixerConfig(filePath) {
299
+ const absolute = path2.resolve(filePath);
300
+ const startDir = resolveToolCwd("formatter", "php-cs-fixer", absolute, {
301
+ cwd: path2.parse(absolute).root,
302
+ allowHomeMarker: true
303
+ }).cwd;
304
+ return PHP_CS_FIXER_CONFIG_NAMES.map((name) => path2.join(startDir, name)).find(existsSync);
305
+ }
306
+
307
+ // dist/clients/dispatch/indent-detect.js
308
+ var DEFAULT_INDENTATION = { style: "space", width: 2 };
309
+ function detectIndentation(content) {
310
+ const lines = structuralLines(content.split(/\r?\n/));
311
+ const tabs = lines.filter((line) => /^\t+\S/.test(line)).length;
312
+ const spaceCounts = lines.map((line) => line.match(/^ +(?=\S)/)?.[0].length ?? 0).filter((count) => count > 0);
313
+ if (tabs === 0 && spaceCounts.length === 0) {
314
+ return hasDetectableIndentation(content) ? void 0 : DEFAULT_INDENTATION;
315
+ }
316
+ if (tabs > spaceCounts.length)
317
+ return { style: "tab", width: 1 };
318
+ if (spaceCounts.length > tabs) {
319
+ const minimum = Math.min(...spaceCounts);
320
+ const gcd = spaceCounts.reduce((unit, count) => greatestCommonDivisor(unit, count), 0);
321
+ const nonBlank = lines.map((line) => line.match(/^( *)\S/)?.[1]?.length).filter((count) => count !== void 0);
322
+ const hasStructuralBoundary = nonBlank.some((count, index) => {
323
+ const previous = nonBlank[index - 1];
324
+ return count === minimum && previous !== void 0 && previous < minimum;
325
+ });
326
+ if (hasStructuralBoundary && minimum <= 8) {
327
+ return { style: "space", width: minimum };
328
+ }
329
+ if (gcd < minimum && gcd <= 8) {
330
+ return { style: "space", width: gcd };
331
+ }
332
+ return void 0;
333
+ }
334
+ return DEFAULT_INDENTATION;
335
+ }
336
+ function opensBlockComment(line) {
337
+ const blockAt = line.indexOf("/*");
338
+ if (blockAt < 0)
339
+ return false;
340
+ const lineAt = line.indexOf("//");
341
+ if (lineAt >= 0 && lineAt < blockAt)
342
+ return false;
343
+ return line.indexOf("*/", blockAt + 2) < 0;
344
+ }
345
+ function blockCommentInteriorMask(lines) {
346
+ const mask = Array.from({ length: lines.length }, () => false);
347
+ let pendingStart = -1;
348
+ for (const [i, line] of lines.entries()) {
349
+ if (pendingStart >= 0) {
350
+ mask[i] = true;
351
+ if (line.includes("*/"))
352
+ pendingStart = -1;
353
+ continue;
354
+ }
355
+ if (opensBlockComment(line))
356
+ pendingStart = i;
357
+ }
358
+ if (pendingStart >= 0) {
359
+ for (let i = pendingStart + 1; i < lines.length; i += 1)
360
+ mask[i] = false;
361
+ }
362
+ return mask;
363
+ }
364
+ function hasLiveFrame(stack) {
365
+ return stack.some((frame) => frame.kind !== "block");
366
+ }
367
+ function advanceTemplateState(line, stack) {
368
+ let j = 0;
369
+ while (j < line.length) {
370
+ const top = stack[stack.length - 1];
371
+ if (top?.kind === "template") {
372
+ if (line[j] === "\\") {
373
+ j += 2;
374
+ continue;
375
+ }
376
+ if (line.startsWith("${", j)) {
377
+ stack.push({ kind: "expr", braceDepth: 1 });
378
+ j += 2;
379
+ continue;
380
+ }
381
+ if (line[j] === "`") {
382
+ stack.pop();
383
+ j += 1;
384
+ continue;
385
+ }
386
+ j += 1;
387
+ continue;
388
+ }
389
+ if (top?.kind === "block") {
390
+ const closeAt = line.indexOf("*/", j);
391
+ if (closeAt < 0)
392
+ return;
393
+ stack.pop();
394
+ j = closeAt + 2;
395
+ continue;
396
+ }
397
+ if (line.startsWith("//", j))
398
+ return;
399
+ if (line.startsWith("/*", j)) {
400
+ stack.push({ kind: "block" });
401
+ j += 2;
402
+ continue;
403
+ }
404
+ if (line[j] === "/" && isRegexOpenerPosition(line, j)) {
405
+ const after = skipRegexLiteral(line, j);
406
+ if (after >= 0) {
407
+ j = after;
408
+ continue;
409
+ }
410
+ }
411
+ const ch = line[j];
412
+ if (ch === '"' || ch === "'") {
413
+ j = skipQuoted(line, j, ch);
414
+ continue;
415
+ }
416
+ if (ch === "`") {
417
+ stack.push({ kind: "template" });
418
+ j += 1;
419
+ continue;
420
+ }
421
+ if (top?.kind === "expr") {
422
+ if (ch === "{") {
423
+ top.braceDepth += 1;
424
+ j += 1;
425
+ continue;
426
+ }
427
+ if (ch === "}") {
428
+ top.braceDepth -= 1;
429
+ j += 1;
430
+ if (top.braceDepth === 0)
431
+ stack.pop();
432
+ continue;
433
+ }
434
+ }
435
+ j += 1;
436
+ }
437
+ }
438
+ function skipQuoted(line, start, quote) {
439
+ let j = start + 1;
440
+ while (j < line.length) {
441
+ if (line[j] === "\\") {
442
+ j += 2;
443
+ continue;
444
+ }
445
+ if (line[j] === quote)
446
+ return j + 1;
447
+ j += 1;
448
+ }
449
+ return line.length;
450
+ }
451
+ var REGEX_OPENER_PUNCTUATION = /* @__PURE__ */ new Set([
452
+ "(",
453
+ ",",
454
+ "=",
455
+ ":",
456
+ "[",
457
+ "!",
458
+ "&",
459
+ "|",
460
+ "?"
461
+ ]);
462
+ var REGEX_OPENER_KEYWORD = /(?:^|[^A-Za-z0-9_$])(?:return|typeof|case)$/;
463
+ function isRegexOpenerPosition(line, at) {
464
+ const before = line.slice(0, at).replace(/[ \t]+$/, "");
465
+ if (before === "")
466
+ return true;
467
+ if (REGEX_OPENER_KEYWORD.test(before))
468
+ return true;
469
+ return REGEX_OPENER_PUNCTUATION.has(before.at(-1) ?? "");
470
+ }
471
+ var REGEX_FLAG_CHARS = "dgimsuvy";
472
+ function skipRegexLiteral(line, start) {
473
+ let j = start + 1;
474
+ let inClass = false;
475
+ while (j < line.length) {
476
+ const c = line[j];
477
+ if (c === "\\") {
478
+ j += 2;
479
+ continue;
480
+ }
481
+ if (inClass) {
482
+ if (c === "]")
483
+ inClass = false;
484
+ j += 1;
485
+ continue;
486
+ }
487
+ if (c === "[") {
488
+ inClass = true;
489
+ j += 1;
490
+ continue;
491
+ }
492
+ if (c === "/") {
493
+ let k = j + 1;
494
+ while (k < line.length && REGEX_FLAG_CHARS.includes(line[k] ?? ""))
495
+ k += 1;
496
+ if (k < line.length && /[A-Za-z0-9_$]/.test(line[k] ?? ""))
497
+ return -1;
498
+ return j + 1;
499
+ }
500
+ j += 1;
501
+ }
502
+ return -1;
503
+ }
504
+ function templateLiteralInteriorMask(lines) {
505
+ const mask = Array.from({ length: lines.length }, () => false);
506
+ const stack = [];
507
+ let openLine = -1;
508
+ for (const [i, line] of lines.entries()) {
509
+ if (hasLiveFrame(stack)) {
510
+ mask[i] = true;
511
+ } else {
512
+ openLine = i;
513
+ }
514
+ advanceTemplateState(line, stack);
515
+ }
516
+ if (hasLiveFrame(stack)) {
517
+ for (let i = openLine + 1; i < lines.length; i += 1)
518
+ mask[i] = false;
519
+ }
520
+ return mask;
521
+ }
522
+ function structuralLines(lines) {
523
+ const blockCommentMask = blockCommentInteriorMask(lines);
524
+ const templateMask = templateLiteralInteriorMask(lines);
525
+ return lines.filter((_, index) => !blockCommentMask[index] && !templateMask[index]);
526
+ }
527
+ function greatestCommonDivisor(left, right) {
528
+ while (right !== 0)
529
+ [left, right] = [right, left % right];
530
+ return left;
531
+ }
532
+ function hasDetectableIndentation(content) {
533
+ return /^(?:\t+| {1,})\S/m.test(content);
534
+ }
535
+
536
+ // dist/clients/tool-agreement.js
537
+ import * as fs from "node:fs";
538
+ import * as path3 from "node:path";
539
+ var NODE_PACKAGES = {
540
+ biome: "@biomejs/biome",
541
+ eslint: "eslint",
542
+ markdownlint: "markdownlint-cli2",
543
+ oxfmt: "oxfmt",
544
+ oxlint: "oxlint",
545
+ prettier: "prettier",
546
+ stylelint: "stylelint"
547
+ };
548
+ var NODE_LOCKFILE_PRECEDENCE = [
549
+ "package-lock.json",
550
+ "pnpm-lock.yaml",
551
+ "yarn.lock"
552
+ ];
553
+ var NODE_LOCKFILE_MAX_BYTES = 16 * 1024 * 1024;
554
+ var TOOL_AGREEMENT_POLICIES = {
555
+ biome: { bucket: "node-lockfile", withoutEvidence: "decline" },
556
+ eslint: { bucket: "node-lockfile", withoutEvidence: "decline" },
557
+ markdownlint: {
558
+ bucket: "node-lockfile",
559
+ withoutEvidence: "decline",
560
+ check: hasMarkdownlintConfig
561
+ },
562
+ oxfmt: { bucket: "node-lockfile", withoutEvidence: "decline" },
563
+ oxlint: { bucket: "node-lockfile", withoutEvidence: "decline" },
564
+ prettier: { bucket: "node-lockfile", withoutEvidence: "decline" },
565
+ stylelint: { bucket: "node-lockfile", withoutEvidence: "decline" },
566
+ ruff: {
567
+ bucket: "project-config",
568
+ withoutEvidence: "decline",
569
+ check: hasRuffConfig
570
+ },
571
+ black: {
572
+ bucket: "project-config",
573
+ withoutEvidence: "decline",
574
+ check: hasBlackConfig
575
+ },
576
+ sqlfluff: {
577
+ bucket: "project-config",
578
+ withoutEvidence: "decline",
579
+ check: hasSqlfluffConfig
580
+ },
581
+ rubocop: {
582
+ bucket: "project-config",
583
+ withoutEvidence: "decline",
584
+ check: hasRubocopConfig
585
+ },
586
+ standardrb: {
587
+ bucket: "project-config",
588
+ withoutEvidence: "decline",
589
+ check: hasStandardrbConfig
590
+ },
591
+ ktlint: { bucket: "standalone-cli", withoutEvidence: "decline" },
592
+ // typstyle is a standalone formatter binary. Its smart-default policy is
593
+ // autonomous, so PATH or managed-install availability is sufficient
594
+ // agreement; it is not owned by a project manifest (#3037).
595
+ typstyle: { bucket: "standalone-cli", withoutEvidence: "decline" },
596
+ ktfmt: {
597
+ bucket: "project-config",
598
+ withoutEvidence: "decline",
599
+ check: hasKtfmtConfig
600
+ },
601
+ "rust-clippy": {
602
+ bucket: "project-config",
603
+ withoutEvidence: "decline",
604
+ check: (cwd) => hasMarker(cwd, ["Cargo.toml"])
605
+ },
606
+ "dart-analyze": {
607
+ bucket: "project-config",
608
+ withoutEvidence: "decline",
609
+ check: (cwd) => hasMarker(cwd, ["pubspec.yaml"])
610
+ },
611
+ "golangci-lint": {
612
+ bucket: "project-config",
613
+ withoutEvidence: "decline",
614
+ check: hasGolangciConfig
615
+ },
616
+ detekt: {
617
+ bucket: "project-config",
618
+ withoutEvidence: "decline",
619
+ check: hasDetektConfig
620
+ },
621
+ gofmt: {
622
+ bucket: "project-config",
623
+ withoutEvidence: "decline",
624
+ check: (cwd) => hasMarker(cwd, ["go.mod"])
625
+ },
626
+ rustfmt: {
627
+ bucket: "project-config",
628
+ withoutEvidence: "decline",
629
+ check: (cwd) => hasMarker(cwd, ["Cargo.toml"])
630
+ },
631
+ zig: {
632
+ bucket: "project-config",
633
+ withoutEvidence: "decline",
634
+ check: (cwd) => hasMarker(cwd, ["build.zig"])
635
+ },
636
+ dart: {
637
+ bucket: "project-config",
638
+ withoutEvidence: "decline",
639
+ check: (cwd) => hasMarker(cwd, ["pubspec.yaml"])
640
+ },
641
+ shfmt: {
642
+ bucket: "project-config",
643
+ withoutEvidence: "decline",
644
+ check: (cwd) => hasMarker(cwd, [".editorconfig"])
645
+ },
646
+ // nixfmt has no honest project marker. It remains in the population and is
647
+ // declined by the conservative absent-evidence path below.
648
+ nixfmt: { bucket: "project-config", withoutEvidence: "decline" },
649
+ mix: {
650
+ bucket: "project-config",
651
+ withoutEvidence: "decline",
652
+ check: hasMixFormatConfig
653
+ },
654
+ ocamlformat: {
655
+ bucket: "project-config",
656
+ withoutEvidence: "decline",
657
+ check: hasOcamlformatConfig
658
+ },
659
+ "clang-format": {
660
+ bucket: "project-config",
661
+ withoutEvidence: "decline",
662
+ check: hasClangFormatConfig
663
+ },
664
+ gleam: {
665
+ bucket: "project-config",
666
+ withoutEvidence: "decline",
667
+ check: (cwd) => hasMarker(cwd, ["gleam.toml"])
668
+ },
669
+ terraform: {
670
+ bucket: "project-config",
671
+ withoutEvidence: "decline",
672
+ check: hasTerraformConfig
673
+ },
674
+ "terragrunt-hcl": {
675
+ bucket: "project-config",
676
+ withoutEvidence: "decline",
677
+ check: (cwd) => hasMarker(cwd, ["terragrunt.hcl", "terragrunt.hcl.json"])
678
+ },
679
+ "php-cs-fixer": {
680
+ bucket: "project-config",
681
+ withoutEvidence: "decline",
682
+ check: hasPhpCsFixerConfig
683
+ },
684
+ csharpier: {
685
+ bucket: "project-config",
686
+ withoutEvidence: "decline",
687
+ check: hasCsharpierConfig
688
+ },
689
+ fantomas: {
690
+ bucket: "project-config",
691
+ withoutEvidence: "decline",
692
+ check: hasFantomasConfig
693
+ },
694
+ swiftformat: {
695
+ bucket: "project-config",
696
+ withoutEvidence: "decline",
697
+ check: hasSwiftformatConfig
698
+ },
699
+ stylua: {
700
+ bucket: "project-config",
701
+ withoutEvidence: "decline",
702
+ check: hasStyluaConfig
703
+ },
704
+ ormolu: {
705
+ bucket: "project-config",
706
+ withoutEvidence: "decline",
707
+ check: hasOrmoluConfig
708
+ },
709
+ taplo: {
710
+ bucket: "project-config",
711
+ withoutEvidence: "decline",
712
+ check: hasTaploConfig
713
+ },
714
+ "google-java-format": {
715
+ bucket: "project-config",
716
+ withoutEvidence: "decline",
717
+ check: hasGoogleJavaFormatConfig
718
+ },
719
+ cljfmt: {
720
+ bucket: "project-config",
721
+ withoutEvidence: "decline",
722
+ check: hasCljfmtConfig
723
+ },
724
+ "cmake-format": {
725
+ bucket: "project-config",
726
+ withoutEvidence: "decline",
727
+ check: hasCmakeFormatConfig
728
+ },
729
+ "psscriptanalyzer-format": {
730
+ bucket: "project-config",
731
+ withoutEvidence: "decline",
732
+ check: (cwd) => hasMarker(cwd, [
733
+ "PSScriptAnalyzerSettings.psd1",
734
+ "ScriptAnalyzerSettings.psd1"
735
+ ])
736
+ },
737
+ cue: {
738
+ bucket: "project-config",
739
+ withoutEvidence: "decline",
740
+ check: (cwd) => hasMarker(cwd, ["cue.mod"])
741
+ }
742
+ };
743
+ function hasMarker(cwd, markers) {
744
+ return findNearestMarkerRoot(cwd, markers, {
745
+ boundaries: [".git", ".hg", ".svn"]
746
+ }) !== null;
747
+ }
748
+ function readJson(filePath) {
749
+ if (!fs.existsSync(filePath))
750
+ return { kind: "missing" };
751
+ try {
752
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
753
+ return value && typeof value === "object" ? { kind: "value", value } : { kind: "unparseable" };
754
+ } catch (error) {
755
+ return {
756
+ kind: error instanceof SyntaxError ? "unparseable" : "unreadable"
757
+ };
758
+ }
759
+ }
760
+ function declaredRange(pkg, name) {
761
+ for (const field of [
762
+ "dependencies",
763
+ "devDependencies",
764
+ "optionalDependencies"
765
+ ]) {
766
+ const deps = pkg[field];
767
+ if (deps && typeof deps === "object") {
768
+ const range = deps[name];
769
+ if (typeof range === "string")
770
+ return range;
771
+ }
772
+ }
773
+ return void 0;
774
+ }
775
+ function parseCoreVersion(version) {
776
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
777
+ if (!match)
778
+ return void 0;
779
+ const parts = match.slice(1).map(Number);
780
+ if (parts.some((part) => !Number.isSafeInteger(part)))
781
+ return void 0;
782
+ return parts;
783
+ }
784
+ function exactOrSimpleRangeMatches(range, version) {
785
+ const clean = range.trim().replace(/^v/, "");
786
+ const actual = parseCoreVersion(version);
787
+ if (!actual)
788
+ return { matches: false, unsupported: version.includes("+") };
789
+ if (/^\d+\.\d+\.\d+$/.test(clean))
790
+ return { matches: clean === version, unsupported: false };
791
+ const caret = clean.match(/^\^(\d+)\.(\d+)\.(\d+)$/);
792
+ if (caret) {
793
+ const [major, minor, patch] = caret.slice(1).map(Number);
794
+ return {
795
+ matches: actual[0] === major && (major !== 0 || actual[1] === minor) && (major !== 0 || minor !== 0 || actual[2] === patch) && (actual[1] > minor || actual[1] === minor && actual[2] >= patch),
796
+ unsupported: false
797
+ };
798
+ }
799
+ const tilde = clean.match(/^~(\d+)\.(\d+)\.(\d+)$/);
800
+ if (tilde) {
801
+ const [major, minor, patch] = tilde.slice(1).map(Number);
802
+ return {
803
+ matches: actual[0] === major && actual[1] === minor && actual[2] >= patch,
804
+ unsupported: false
805
+ };
806
+ }
807
+ return { matches: false, unsupported: true };
808
+ }
809
+ function pnpmEvidence(doc, packageName, importerKey) {
810
+ if (doc && typeof doc === "object" && !Array.isArray(doc)) {
811
+ const docRecord = doc;
812
+ const importers = docRecord.importers;
813
+ if (importers && typeof importers === "object" && !Array.isArray(importers)) {
814
+ const importer = importers[importerKey];
815
+ if (importer && typeof importer === "object") {
816
+ for (const field of ["dependencies", "devDependencies"]) {
817
+ const deps = importer[field];
818
+ if (deps && typeof deps === "object") {
819
+ const entry = deps[packageName];
820
+ if (entry && typeof entry === "object") {
821
+ return {
822
+ kind: "resolved",
823
+ version: entry.version
824
+ };
825
+ }
826
+ }
827
+ }
828
+ }
829
+ return { kind: "resolved", version: void 0 };
830
+ }
831
+ let sawTopLevelMaps = false;
832
+ let v6version;
833
+ let v6found = false;
834
+ for (const field of ["dependencies", "devDependencies"]) {
835
+ const deps = docRecord[field];
836
+ if (deps && typeof deps === "object" && !Array.isArray(deps)) {
837
+ sawTopLevelMaps = true;
838
+ const entry = deps[packageName];
839
+ if (entry && typeof entry === "object") {
840
+ v6version = entry.version;
841
+ v6found = true;
842
+ break;
843
+ }
844
+ }
845
+ }
846
+ if (v6found || sawTopLevelMaps) {
847
+ return { kind: "resolved", version: v6found ? v6version : void 0 };
848
+ }
849
+ }
850
+ return { kind: "unsupported-shape" };
851
+ }
852
+ function decideNodeVersionAgreement(tool, packageName, range, version, supplier) {
853
+ const comparison = typeof version === "string" ? exactOrSimpleRangeMatches(range, version) : { matches: false, unsupported: false };
854
+ if (typeof version !== "string" || !comparison.matches) {
855
+ const reasonCode = typeof version === "string" && comparison.unsupported ? "evidence-unsupported" : typeof version === "string" && version.includes("+") ? "evidence-unsupported" : "evidence-unparseable";
856
+ const reason = typeof version === "string" && comparison.unsupported ? `the project declares ${packageName}@${range} in package.json, but the lockfile shape ${packageName}@${version} in ${supplier} or its range is unsupported; tool agreement cannot be established` : typeof version === "string" && parseCoreVersion(version) ? `the project declares ${packageName}@${range} in package.json, but the lockfile resolves ${packageName}@${version} in ${supplier}; agreement disagrees` : `the project declares ${packageName}@${range} in package.json, but ${supplier} does not establish its resolved version; tool agreement cannot be established`;
857
+ return {
858
+ decision: "decline",
859
+ subject: `node:${tool}`,
860
+ reason,
861
+ reasonCode
862
+ };
863
+ }
864
+ return { decision: "established", lockfile: supplier };
865
+ }
866
+ function readLockfileBounded(filePath) {
867
+ let fd;
868
+ try {
869
+ fd = fs.openSync(filePath, "r");
870
+ const buffer = Buffer.allocUnsafe(Math.min(fs.fstatSync(fd).size, NODE_LOCKFILE_MAX_BYTES) + 1);
871
+ let total = 0;
872
+ while (total < buffer.length) {
873
+ const read = fs.readSync(fd, buffer, total, buffer.length - total, null);
874
+ if (read === 0)
875
+ break;
876
+ total += read;
877
+ }
878
+ return total > NODE_LOCKFILE_MAX_BYTES ? { kind: "too-large" } : { kind: "text", text: buffer.toString("utf8", 0, total) };
879
+ } catch {
880
+ return { kind: "unreadable" };
881
+ } finally {
882
+ if (fd !== void 0) {
883
+ try {
884
+ fs.closeSync(fd);
885
+ } catch {
886
+ }
887
+ }
888
+ }
889
+ }
890
+ function lockfileReadDecline(tool, lockfile, read) {
891
+ return read.kind === "too-large" ? {
892
+ decision: "decline",
893
+ subject: `node:${tool}`,
894
+ reason: `the project ${lockfile} exceeds the ${NODE_LOCKFILE_MAX_BYTES}-byte lockfile read bound; tool agreement cannot be established`,
895
+ reasonCode: "evidence-too-large"
896
+ } : {
897
+ decision: "decline",
898
+ subject: `node:${tool}`,
899
+ reason: `the project ${lockfile} is unreadable; tool agreement cannot be established`,
900
+ reasonCode: "evidence-unreadable"
901
+ };
902
+ }
903
+ function stripPnpmPeerSuffix(version) {
904
+ const core = /^\d+\.\d+\.\d+/.exec(version)?.[0];
905
+ if (!core || core.length === version.length)
906
+ return version;
907
+ let depth = 0;
908
+ for (let i = core.length; i < version.length; i += 1) {
909
+ const char = version[i];
910
+ if (char === "(") {
911
+ depth += 1;
912
+ } else if (char === ")") {
913
+ if (depth === 0 || version[i - 1] === "(")
914
+ return version;
915
+ depth -= 1;
916
+ } else if (depth === 0) {
917
+ return version;
918
+ }
919
+ }
920
+ return depth === 0 ? core : version;
921
+ }
922
+ function pnpmAgreement(tool, packageName, range, root, lockDir) {
923
+ const filePath = path3.join(lockDir, "pnpm-lock.yaml");
924
+ const read = readLockfileBounded(filePath);
925
+ if (read.kind !== "text") {
926
+ return lockfileReadDecline(tool, "pnpm-lock.yaml", read);
927
+ }
928
+ let doc;
929
+ try {
930
+ doc = load(read.text);
931
+ } catch {
932
+ return {
933
+ decision: "decline",
934
+ subject: `node:${tool}`,
935
+ reason: "the project pnpm-lock.yaml is unparseable; tool agreement cannot be established",
936
+ reasonCode: "evidence-unparseable"
937
+ };
938
+ }
939
+ const importerKey = lockDir === path3.resolve(root) ? "." : toPosix(path3.relative(lockDir, root));
940
+ const evidence = pnpmEvidence(doc, packageName, importerKey);
941
+ if (evidence.kind === "unsupported-shape") {
942
+ return {
943
+ decision: "decline",
944
+ subject: `node:${tool}`,
945
+ reason: "the project pnpm-lock.yaml has an unsupported lockfile shape; tool agreement cannot be established",
946
+ reasonCode: "evidence-unsupported"
947
+ };
948
+ }
949
+ return decideNodeVersionAgreement(tool, packageName, range, typeof evidence.version === "string" ? stripPnpmPeerSuffix(evidence.version) : evidence.version, "pnpm-lock.yaml");
950
+ }
951
+ function yarnV1Blocks(text, packageName) {
952
+ const found = [];
953
+ for (const block of text.split(/\n[ \t]*\n/)) {
954
+ const lines = block.split("\n");
955
+ const header = (lines[0] ?? "").trim();
956
+ if (!header.endsWith(":"))
957
+ continue;
958
+ const prefix = `${packageName}@`;
959
+ const descriptors = [];
960
+ for (const rawPart of header.slice(0, -1).split(",")) {
961
+ const part = rawPart.trim().replace(/^"|"$/g, "").trim();
962
+ if (part.startsWith(prefix) && !part.slice(prefix.length).includes(":")) {
963
+ descriptors.push(part);
964
+ }
965
+ }
966
+ if (descriptors.length === 0)
967
+ continue;
968
+ let version;
969
+ for (const line of lines.slice(1)) {
970
+ const match = /^\s*version\s+"([^"]*)"/.exec(line);
971
+ if (match) {
972
+ version = match[1];
973
+ break;
974
+ }
975
+ }
976
+ found.push({ descriptors, version });
977
+ }
978
+ return found;
979
+ }
980
+ function yarnBerryEntries(doc, packageName) {
981
+ if (!doc || typeof doc !== "object" || Array.isArray(doc))
982
+ return void 0;
983
+ const docRecord = doc;
984
+ if (!docRecord.__metadata || typeof docRecord.__metadata !== "object")
985
+ return void 0;
986
+ const found = [];
987
+ const marker = "@npm:";
988
+ for (const [key, entry] of Object.entries(docRecord)) {
989
+ const unquoted = key.replace(/^"|"$/g, "");
990
+ const at = unquoted.lastIndexOf(marker);
991
+ if (at < 0)
992
+ continue;
993
+ if (unquoted.slice(0, at) !== packageName)
994
+ continue;
995
+ const version = entry && typeof entry === "object" ? entry.version : void 0;
996
+ found.push({ descriptors: [unquoted.slice(at + marker.length)], version });
997
+ }
998
+ return found;
999
+ }
1000
+ function selectNodeCandidate(candidates, range) {
1001
+ for (const candidate of candidates) {
1002
+ if (candidate.descriptors.some((descriptor) => descriptor === range)) {
1003
+ return typeof candidate.version === "string" ? candidate.version : void 0;
1004
+ }
1005
+ }
1006
+ const first = candidates.length > 0 ? candidates[0]?.version : void 0;
1007
+ return typeof first === "string" ? first : void 0;
1008
+ }
1009
+ function yarnAgreement(tool, packageName, range, filePath) {
1010
+ const read = readLockfileBounded(filePath);
1011
+ if (read.kind !== "text")
1012
+ return lockfileReadDecline(tool, "yarn.lock", read);
1013
+ const raw = read.text.replace(/\r\n?/g, "\n");
1014
+ let doc;
1015
+ let yamlOk = true;
1016
+ try {
1017
+ doc = load(raw);
1018
+ } catch {
1019
+ yamlOk = false;
1020
+ }
1021
+ if (yamlOk) {
1022
+ const berry = yarnBerryEntries(doc, packageName);
1023
+ if (berry) {
1024
+ return decideNodeVersionAgreement(tool, packageName, range, selectNodeCandidate(berry, range), "yarn.lock");
1025
+ }
1026
+ }
1027
+ const v1 = yarnV1Blocks(raw, packageName);
1028
+ if (v1.length > 0) {
1029
+ return decideNodeVersionAgreement(tool, packageName, range, selectNodeCandidate(v1, range), "yarn.lock");
1030
+ }
1031
+ if (!yamlOk) {
1032
+ return {
1033
+ decision: "decline",
1034
+ subject: `node:${tool}`,
1035
+ reason: "the project yarn.lock is unparseable; tool agreement cannot be established",
1036
+ reasonCode: "evidence-unparseable"
1037
+ };
1038
+ }
1039
+ return {
1040
+ decision: "decline",
1041
+ subject: `node:${tool}`,
1042
+ reason: "the project yarn.lock has an unsupported lockfile shape; tool agreement cannot be established",
1043
+ reasonCode: "evidence-unsupported"
1044
+ };
1045
+ }
1046
+ function nodeAgreement(tool, root) {
1047
+ const packageName = NODE_PACKAGES[tool];
1048
+ if (!packageName)
1049
+ return void 0;
1050
+ const pkg = readJson(path3.join(root, "package.json"));
1051
+ if (pkg.kind === "unreadable" || pkg.kind === "unparseable") {
1052
+ return {
1053
+ decision: "decline",
1054
+ subject: `node:${tool}`,
1055
+ reason: `the project package.json is ${pkg.kind}; tool agreement cannot be established`,
1056
+ reasonCode: `evidence-${pkg.kind}`
1057
+ };
1058
+ }
1059
+ const range = pkg.kind === "value" ? declaredRange(pkg.value, packageName) : void 0;
1060
+ if (!range)
1061
+ return void 0;
1062
+ const lockDir = findNearestMarkerRoot(root, [...NODE_LOCKFILE_PRECEDENCE], {
1063
+ boundaries: [".git", ".hg", ".svn"]
1064
+ });
1065
+ if (!lockDir) {
1066
+ return {
1067
+ decision: "decline",
1068
+ subject: `node:${tool}`,
1069
+ reason: `the project declares ${packageName}@${range} in package.json, but no lockfile (package-lock.json, pnpm-lock.yaml, yarn.lock) establishes its resolved version; tool agreement cannot be established`,
1070
+ reasonCode: "evidence-absent"
1071
+ };
1072
+ }
1073
+ const supplier = fs.existsSync(path3.join(lockDir, "package-lock.json")) ? "package-lock.json" : fs.existsSync(path3.join(lockDir, "pnpm-lock.yaml")) ? "pnpm-lock.yaml" : "yarn.lock";
1074
+ if (supplier === "package-lock.json") {
1075
+ const lock = readJson(path3.join(lockDir, "package-lock.json"));
1076
+ if (lock.kind === "unreadable" || lock.kind === "unparseable") {
1077
+ return {
1078
+ decision: "decline",
1079
+ subject: `node:${tool}`,
1080
+ reason: `the project package-lock.json is ${lock.kind}; tool agreement cannot be established`,
1081
+ reasonCode: `evidence-${lock.kind}`
1082
+ };
1083
+ }
1084
+ const packages = lock.kind === "value" ? lock.value.packages : void 0;
1085
+ const entry = packages && typeof packages === "object" ? packages[`node_modules/${packageName}`] : void 0;
1086
+ const version = entry && typeof entry === "object" ? entry.version : void 0;
1087
+ const comparison = typeof version === "string" ? exactOrSimpleRangeMatches(range, version) : { matches: false, unsupported: false };
1088
+ if (typeof version !== "string" || !comparison.matches) {
1089
+ const reasonCode = typeof version === "string" && comparison.unsupported ? "evidence-unsupported" : typeof version === "string" && version.includes("+") ? "evidence-unsupported" : "evidence-unparseable";
1090
+ const reason = typeof version === "string" && comparison.unsupported ? `the project declares ${packageName}@${range}, but the lockfile shape ${packageName}@${version} or its range is unsupported; tool agreement cannot be established` : typeof version === "string" && parseCoreVersion(version) ? `the project declares ${packageName}@${range} in package.json, but the lockfile resolves ${packageName}@${version} in package-lock.json; agreement disagrees` : `the project declares ${packageName}@${range} in package.json, but package-lock.json does not establish its resolved version; tool agreement cannot be established`;
1091
+ return {
1092
+ decision: "decline",
1093
+ subject: `node:${tool}`,
1094
+ reason,
1095
+ reasonCode
1096
+ };
1097
+ }
1098
+ return { decision: "established", lockfile: supplier };
1099
+ }
1100
+ if (supplier === "pnpm-lock.yaml") {
1101
+ return pnpmAgreement(tool, packageName, range, root, lockDir);
1102
+ }
1103
+ return yarnAgreement(tool, packageName, range, path3.join(lockDir, "yarn.lock"));
1104
+ }
1105
+ function establishToolAgreement(tool, cwd) {
1106
+ const key = `${getDegradationLedgerGeneration()}\0${path3.resolve(cwd)}\0${tool}`;
1107
+ const cached = agreementCache.get(key);
1108
+ if (cached)
1109
+ return cached;
1110
+ agreementResolutionCount += 1;
1111
+ const policy = TOOL_AGREEMENT_POLICIES[tool];
1112
+ if (!policy) {
1113
+ const agreement2 = {
1114
+ decision: "decline",
1115
+ subject: `tool:${tool}`,
1116
+ reason: "the autonomous writer is not registered with a project-evidence policy; tool agreement cannot be established",
1117
+ reasonCode: "evidence-unsupported"
1118
+ };
1119
+ agreementCache.set(key, agreement2);
1120
+ return agreement2;
1121
+ }
1122
+ let agreement = { decision: "established" };
1123
+ if (tool === "ktlint") {
1124
+ const ownership = hasGradleKtlintPlugin(cwd);
1125
+ if (ownership.kind === "owned" || hasKtlintConfig(cwd)) {
1126
+ agreement = {
1127
+ decision: "decline",
1128
+ subject: "kotlin:gradle-ktlint",
1129
+ reason: "the project resolves ktlint through Gradle, so CLI agreement cannot be established from project data",
1130
+ reasonCode: "evidence-unsupported"
1131
+ };
1132
+ } else if (ownership.kind === "indeterminate") {
1133
+ agreement = {
1134
+ decision: "decline",
1135
+ subject: "kotlin:gradle-ktlint",
1136
+ reason: "Gradle ownership evidence is unreadable or exceeded its scan budget; tool agreement cannot be established",
1137
+ reasonCode: "evidence-unreadable"
1138
+ };
1139
+ }
1140
+ }
1141
+ if (agreement.decision === "established" && policy.bucket === "node-lockfile") {
1142
+ const root = findNearestMarkerRoot(cwd, ["package.json"], {
1143
+ boundaries: [".git", ".hg", ".svn"]
1144
+ });
1145
+ const node = root ? nodeAgreement(tool, root) : void 0;
1146
+ agreement = node ?? {
1147
+ decision: "decline",
1148
+ subject: `node:${tool}`,
1149
+ reason: "the project has no package declaration and lockfile evidence for this tool",
1150
+ reasonCode: "evidence-absent"
1151
+ };
1152
+ } else if (agreement.decision === "established" && policy.bucket === "project-config" && (!policy.check || !policy.check(cwd))) {
1153
+ agreement = {
1154
+ decision: "decline",
1155
+ subject: `project:${tool}`,
1156
+ reason: "the project has no readable configuration or manifest evidence selecting this tool",
1157
+ reasonCode: "evidence-absent"
1158
+ };
1159
+ }
1160
+ if (agreement.decision === "established" && !policy.bucket) {
1161
+ agreement = {
1162
+ decision: "decline",
1163
+ subject: `tool:${tool}`,
1164
+ reason: "the tool evidence bucket is unsupported",
1165
+ reasonCode: "evidence-unsupported"
1166
+ };
1167
+ }
1168
+ agreementCache.set(key, agreement);
1169
+ return agreement;
1170
+ }
1171
+ var agreementCache = new BoundedFifoMap(512);
1172
+ var agreementResolutionCount = 0;
1173
+
1174
+ // dist/clients/formatters.js
1175
+ async function tryLazyInstallFormatterTool(tool, cwd) {
1176
+ const ok = await tryLazyInstallForFormatter(tool, cwd);
1177
+ if (ok)
1178
+ resetWhichLatches();
1179
+ return ok;
1180
+ }
1181
+ var SKIP_FORMATTING = "skip-formatting";
1182
+ var FORMATTER_UNAVAILABLE = "formatter-unavailable";
1183
+ var FORMATTER_AGREEMENT_UNAVAILABLE = "formatter-agreement-unavailable";
1184
+ async function fileExists(filePath) {
1185
+ try {
1186
+ await fs2.access(filePath);
1187
+ return true;
1188
+ } catch {
1189
+ return false;
1190
+ }
1191
+ }
1192
+ async function findUp(targets, startDir, stopDir = path4.parse(startDir).root) {
1193
+ const found = [];
1194
+ let currentDir = startDir;
1195
+ while (currentDir !== stopDir) {
1196
+ let entries;
1197
+ try {
1198
+ entries = await fs2.readdir(currentDir);
1199
+ } catch {
1200
+ entries = [];
1201
+ }
1202
+ if (entries.length > 0) {
1203
+ const foldCase = process.platform === "win32" || process.platform === "darwin";
1204
+ const entrySet = new Set(foldCase ? entries.map((e) => e.toLowerCase()) : entries);
1205
+ for (const target of targets) {
1206
+ if (target.includes("/") || target.includes("\\"))
1207
+ continue;
1208
+ if (entrySet.has(foldCase ? target.toLowerCase() : target)) {
1209
+ const candidate = path4.join(currentDir, target);
1210
+ if (await fileExists(candidate))
1211
+ found.push(candidate);
1212
+ }
1213
+ }
1214
+ }
1215
+ for (const target of targets) {
1216
+ if (!target.includes("/") && !target.includes("\\"))
1217
+ continue;
1218
+ const candidate = path4.join(currentDir, target);
1219
+ if (await fileExists(candidate))
1220
+ found.push(candidate);
1221
+ }
1222
+ const parent = path4.dirname(currentDir);
1223
+ if (parent === currentDir)
1224
+ break;
1225
+ currentDir = parent;
1226
+ }
1227
+ return found;
1228
+ }
1229
+ function _findUpForTests(targets, startDir, stopDir) {
1230
+ return findUp(targets, startDir, stopDir);
1231
+ }
1232
+ var WHICH_BUDGET_MS = 5e3;
1233
+ var whichLatchByCommand = /* @__PURE__ */ new Map();
1234
+ var whichTransientCommands = /* @__PURE__ */ new Set();
1235
+ var probedCommandsStorage = new AsyncLocalStorage();
1236
+ async function detectCandidate(formatter, cwd) {
1237
+ const probed = /* @__PURE__ */ new Set();
1238
+ let detected = false;
1239
+ let error;
1240
+ try {
1241
+ detected = await probedCommandsStorage.run(probed, () => formatter.detect(cwd));
1242
+ } catch (err) {
1243
+ error = err;
1244
+ }
1245
+ const stalledCommands = [...probed].filter((command) => whichTransientCommands.has(command));
1246
+ return {
1247
+ detected,
1248
+ ...error !== void 0 && { error },
1249
+ outcome: {
1250
+ name: formatter.name,
1251
+ verdict: detected ? "available" : stalledCommands.length > 0 ? "unreachable" : "missing",
1252
+ stalledCommands
1253
+ }
1254
+ };
1255
+ }
1256
+ function resetWhichLatches() {
1257
+ whichLatchByCommand.clear();
1258
+ whichTransientCommands.clear();
1259
+ cooldownRecordedForRetryAtMs.clear();
1260
+ }
1261
+ var cooldownRecordedForRetryAtMs = /* @__PURE__ */ new Map();
1262
+ function noteCooldownServedVerdict(command, latch) {
1263
+ if (latch.getOutcome() !== "transient")
1264
+ return;
1265
+ const retryAtMs = latch.getRetryAtMs();
1266
+ if (retryAtMs <= 0)
1267
+ return;
1268
+ if (cooldownRecordedForRetryAtMs.get(command) === retryAtMs)
1269
+ return;
1270
+ cooldownRecordedForRetryAtMs.set(command, retryAtMs);
1271
+ const cause = latch.getCause();
1272
+ if (cause === null) {
1273
+ logExtension({
1274
+ subsystem: "format",
1275
+ message: `which latch: transient outcome with no cause for ${command}; cooldown-served record dropped`,
1276
+ metadata: { tool: command, retryAtMs }
1277
+ });
1278
+ return;
1279
+ }
1280
+ logAvailabilityDecision({
1281
+ tool: command,
1282
+ verdict: "unavailable",
1283
+ outcome: "transient",
1284
+ cause,
1285
+ elapsedMs: 0,
1286
+ latched: false,
1287
+ retryAfterMs: Math.max(1, retryAtMs - Date.now()),
1288
+ budgetMs: WHICH_BUDGET_MS,
1289
+ servedFromCooldown: true,
1290
+ // No probe ran here: the latch's own remembered cause is replayed
1291
+ // as-is, so the call site is the one asserting it (#2209).
1292
+ classifiedBy: "caller"
1293
+ });
1294
+ }
1295
+ async function which(command) {
1296
+ probedCommandsStorage.getStore()?.add(command);
1297
+ let entry = whichLatchByCommand.get(command);
1298
+ if (!entry) {
1299
+ entry = { latch: createAvailabilityLatch(), resolved: null };
1300
+ whichLatchByCommand.set(command, entry);
1301
+ }
1302
+ const memo = entry.latch.read();
1303
+ if (memo !== null) {
1304
+ if (!memo)
1305
+ noteCooldownServedVerdict(command, entry.latch);
1306
+ return memo ? entry.resolved : null;
1307
+ }
1308
+ const stallSampler = startHostStallSampler();
1309
+ const startedAt = Date.now();
1310
+ const result = await safeSpawnAsync(process.platform === "win32" ? "where" : "which", [command], { timeout: WHICH_BUDGET_MS });
1311
+ const hostStallMs = stallSampler.stop();
1312
+ const elapsedMs = Date.now() - startedAt;
1313
+ const resolved = !result.error && result.status === 0 ? result.stdout?.trim().split(/\r?\n/)[0] ?? null : null;
1314
+ if (resolved) {
1315
+ entry.resolved = resolved;
1316
+ entry.latch.noteAvailable();
1317
+ whichTransientCommands.delete(command);
1318
+ cooldownRecordedForRetryAtMs.delete(command);
1319
+ logAvailabilityDecision({
1320
+ tool: command,
1321
+ verdict: "available",
1322
+ outcome: "success",
1323
+ cause: "ok",
1324
+ elapsedMs,
1325
+ latched: true,
1326
+ hostStallMs,
1327
+ budgetMs: WHICH_BUDGET_MS,
1328
+ classifiedBy: "probe"
1329
+ });
1330
+ return resolved;
1331
+ }
1332
+ entry.resolved = null;
1333
+ const proberRan = !result.error;
1334
+ const classified = classifyProbeFailure(result, {
1335
+ hostStallMs,
1336
+ ...proberRan && { unclassifiedFailureOutcome: "missing" }
1337
+ });
1338
+ let { outcome, cause } = classified;
1339
+ let outcomeForced = false;
1340
+ if (!proberRan && outcome !== "transient") {
1341
+ outcome = "transient";
1342
+ cause = "probe-rejected";
1343
+ outcomeForced = true;
1344
+ }
1345
+ const retryAfterMs = entry.latch.noteUnavailable(outcome, cause);
1346
+ if (outcome === "transient")
1347
+ whichTransientCommands.add(command);
1348
+ else
1349
+ whichTransientCommands.delete(command);
1350
+ cooldownRecordedForRetryAtMs.delete(command);
1351
+ logAvailabilityDecision({
1352
+ tool: command,
1353
+ verdict: "unavailable",
1354
+ outcome,
1355
+ cause,
1356
+ elapsedMs,
1357
+ latched: retryAfterMs === 0,
1358
+ hostStallMs,
1359
+ ...retryAfterMs > 0 && { retryAfterMs },
1360
+ budgetMs: WHICH_BUDGET_MS,
1361
+ classifiedBy: outcomeForced ? "caller" : "probe"
1362
+ });
1363
+ return null;
1364
+ }
1365
+ async function resolveGoFmtBinary() {
1366
+ const inPath = await which("gofmt");
1367
+ if (inPath)
1368
+ return inPath;
1369
+ const goCheck = await probeToolAsync("go", ["env", "GOROOT"], {
1370
+ timeout: 5e3
1371
+ });
1372
+ if (goCheck.error || goCheck.status !== 0)
1373
+ return null;
1374
+ const goroot = (goCheck.stdout ?? "").trim();
1375
+ if (!goroot)
1376
+ return null;
1377
+ const binary = path4.join(goroot, "bin", process.platform === "win32" ? "gofmt.exe" : "gofmt");
1378
+ return await fileExists(binary) ? binary : null;
1379
+ }
1380
+ async function findInVenv(binary, cwd) {
1381
+ return findLocalBinUpwards(binary, cwd, {
1382
+ windowsExt: ".exe",
1383
+ binDirs: VENV_BIN_DIRS
1384
+ }) ?? null;
1385
+ }
1386
+ async function findInVendorBin(binary, cwd) {
1387
+ return findLocalBinUpwards(binary, cwd, {
1388
+ windowsExt: ".bat",
1389
+ binDirs: VENDOR_BIN_DIRS
1390
+ }) ?? null;
1391
+ }
1392
+ async function findInNodeModules(binary, cwd) {
1393
+ return findLocalBinUpwards(binary, cwd) ?? null;
1394
+ }
1395
+ async function canUseBundleExec(cwd) {
1396
+ if (await which("bundle") === null)
1397
+ return false;
1398
+ const lockfiles = await findUp(["Gemfile.lock"], cwd);
1399
+ return lockfiles.length > 0;
1400
+ }
1401
+ async function resolveManagedSmartDefaultCommand(formatterName, filePath, args) {
1402
+ const toolId = getAutoInstallToolIdForFormatter(formatterName);
1403
+ if (!toolId)
1404
+ return FORMATTER_UNAVAILABLE;
1405
+ const { ensureTool } = await import("./probes/installer.js");
1406
+ const installed = await ensureTool(toolId);
1407
+ if (!installed) {
1408
+ recordDegradationOnce({
1409
+ kind: "formatter-unavailable",
1410
+ subject: formatterName,
1411
+ reason: "managed formatter lookup and installation returned no executable"
1412
+ });
1413
+ return FORMATTER_UNAVAILABLE;
1414
+ }
1415
+ return [installed, ...args, filePath];
1416
+ }
1417
+ async function resolveManagedFormatterCommand(toolId, filePath, args, findLocal, cwd) {
1418
+ const local = findLocal && cwd ? await findLocal(toolId, cwd) : null;
1419
+ const installed = local ?? await which(toolId) ?? await getToolPath(toolId);
1420
+ return installed ? [installed, ...args, filePath] : FORMATTER_UNAVAILABLE;
1421
+ }
1422
+ function managedFormatterResolver(toolId, args, findLocal) {
1423
+ return (filePath, cwd) => resolveManagedFormatterCommand(toolId, filePath, args, findLocal, cwd);
1424
+ }
1425
+ function managedToolDetect(toolId, configDetect, nativeDetect) {
1426
+ return async (cwd) => {
1427
+ const available = nativeDetect && await nativeDetect(cwd) || Boolean(await getToolPath(toolId));
1428
+ return available && (configDetect ? await configDetect(cwd) : true);
1429
+ };
1430
+ }
1431
+ var EXPLICIT_FORMATTER_CONFIG_CHECKS = /* @__PURE__ */ new Map([
1432
+ ["biome", (cwd) => hasBiomeConfig(cwd)],
1433
+ [
1434
+ "prettier",
1435
+ (cwd) => hasPrettierConfig(cwd) || hasNearestPackageJsonField(cwd, "prettier")
1436
+ ],
1437
+ // .svelte is conditional beyond "an oxfmt config exists": oxfmt requires the
1438
+ // `svelte` package installed AND the config's `svelte` flag enabled
1439
+ // (verified empirically — see hasOxfmtSvelteConfig). The generic checks
1440
+ // below are NOT sufficient for .svelte — an oxfmt.toml with no svelte flag,
1441
+ // or an oxfmt dependency alone, both fail at runtime for .svelte
1442
+ // specifically (other extensions are unaffected by this stricter gate).
1443
+ [
1444
+ "oxfmt",
1445
+ (cwd, ext) => ext === ".svelte" ? hasOxfmtSvelteConfig(cwd) : hasOxfmtConfig(cwd) || hasVitePlusConfig(cwd) || // The published package is `oxfmt`; `@oxc-project/oxfmt` does not
1446
+ // exist on npm. Accept both (scoped kept for forward-compat).
1447
+ hasNearestPackageJsonDependency(cwd, "oxfmt") || hasNearestPackageJsonDependency(cwd, "@oxc-project/oxfmt")
1448
+ ],
1449
+ ["ruff", (cwd) => hasRuffConfig(cwd)],
1450
+ ["black", (cwd) => hasBlackConfig(cwd)],
1451
+ ["sqlfluff", (cwd) => hasSqlfluffConfig(cwd)],
1452
+ ["rubocop", (cwd) => hasRubocopConfig(cwd)],
1453
+ ["standardrb", (cwd) => hasStandardrbConfig(cwd)],
1454
+ ["clang-format", (cwd) => hasClangFormatConfig(cwd)],
1455
+ ["php-cs-fixer", (cwd) => hasPhpCsFixerConfig(cwd)],
1456
+ ["stylua", (cwd) => hasStyluaConfig(cwd)],
1457
+ ["ocamlformat", (cwd) => hasOcamlformatConfig(cwd)],
1458
+ ["google-java-format", (cwd) => hasGoogleJavaFormatConfig(cwd)],
1459
+ ["ktfmt", (cwd) => hasKtfmtConfig(cwd)],
1460
+ ["ktlint", (cwd) => hasKtlintConfig(cwd)],
1461
+ ["cljfmt", (cwd) => hasCljfmtConfig(cwd)],
1462
+ ["cmake-format", (cwd) => hasCmakeFormatConfig(cwd)],
1463
+ ["psscriptanalyzer-format", (cwd) => hasPSScriptAnalyzerConfig(cwd)],
1464
+ // #1595 sweep — see the comment above hasCsharpierConfig et al. in
1465
+ // tool-policy.ts for why nixfmt (the 8th formatter #1572 flagged) is NOT
1466
+ // wired here: it has no config-file convention and no manifest-marker
1467
+ // equivalent to `.terraform.lock.hcl`, so there is no honest opt-in signal.
1468
+ ["csharpier", (cwd) => hasCsharpierConfig(cwd)],
1469
+ ["ormolu", (cwd) => hasOrmoluConfig(cwd)],
1470
+ ["taplo", (cwd) => hasTaploConfig(cwd)],
1471
+ ["terraform", (cwd) => hasTerraformConfig(cwd)],
1472
+ ["swiftformat", (cwd) => hasSwiftformatConfig(cwd)],
1473
+ ["fantomas", (cwd) => hasFantomasConfig(cwd)],
1474
+ ["mix", (cwd) => hasMixFormatConfig(cwd)]
1475
+ ]);
1476
+ function hasExplicitFormatterConfig(formatterName, cwd, ext) {
1477
+ return EXPLICIT_FORMATTER_CONFIG_CHECKS.get(formatterName)?.(cwd, ext) ?? false;
1478
+ }
1479
+ var FORMATTERS_WITH_EXPLICIT_CONFIG_CHECK = new Set(EXPLICIT_FORMATTER_CONFIG_CHECKS.keys());
1480
+ async function hasEditorConfig(cwd) {
1481
+ return findNearestContaining(cwd, [".editorconfig"]) !== void 0;
1482
+ }
1483
+ async function indentationArgs(filePath, tool, cwd) {
1484
+ if (await hasEditorConfig(cwd) || hasExplicitFormatterConfig(tool, cwd, path4.extname(filePath))) {
1485
+ return [];
1486
+ }
1487
+ let content;
1488
+ try {
1489
+ content = await fs2.readFile(filePath, "utf8");
1490
+ } catch {
1491
+ return [];
1492
+ }
1493
+ if (!hasDetectableIndentation(content))
1494
+ return null;
1495
+ const indentation = detectIndentation(content);
1496
+ if (!indentation) {
1497
+ recordDegradationOnce({
1498
+ kind: "formatter-skip",
1499
+ subject: tool,
1500
+ reason: "indentation evidence is ambiguous; formatter style not pinned"
1501
+ });
1502
+ return null;
1503
+ }
1504
+ if (tool === "shfmt")
1505
+ return indentation.style === "tab" ? ["-i", "0"] : ["-i", String(indentation.width)];
1506
+ if (tool === "prettier") {
1507
+ return [
1508
+ indentation.style === "tab" ? "--use-tabs" : "--no-use-tabs",
1509
+ "--tab-width",
1510
+ String(indentation.width)
1511
+ ];
1512
+ }
1513
+ if (tool === "ruff") {
1514
+ return [
1515
+ "--config",
1516
+ `indent-width=${indentation.width}`,
1517
+ "--config",
1518
+ `format.indent-style='${indentation.style}'`
1519
+ ];
1520
+ }
1521
+ return [
1522
+ "--indent-style",
1523
+ indentation.style,
1524
+ "--indent-width",
1525
+ String(indentation.width)
1526
+ ];
1527
+ }
1528
+ function resolveFormatterCwd(absolutePath, formatterName, homeDir = os2.homedir()) {
1529
+ return resolveToolCwd("formatter", formatterName ?? "unknown", absolutePath, {
1530
+ // Formatter discovery historically walks above the file directory. The
1531
+ // filesystem root is the neutral dispatch boundary; the seam's `$HOME`
1532
+ // ceiling prevents it from escaping the user's workspace.
1533
+ cwd: path4.parse(path4.resolve(absolutePath)).root,
1534
+ homeDir
1535
+ }).cwd;
1536
+ }
1537
+ var BIOME_UNMATCHED_FLAG = "--no-errors-on-unmatched";
1538
+ var biomeFormatter = {
1539
+ name: "biome",
1540
+ command: [
1541
+ "npx",
1542
+ "@biomejs/biome",
1543
+ "format",
1544
+ "--write",
1545
+ BIOME_UNMATCHED_FLAG,
1546
+ "$FILE"
1547
+ ],
1548
+ async resolveCommand(filePath, cwd) {
1549
+ const editorConfigFlag = await hasEditorConfig(cwd) ? ["--use-editorconfig=true"] : [];
1550
+ const styleArgs = await indentationArgs(filePath, "biome", cwd);
1551
+ if (styleArgs === null)
1552
+ return SKIP_FORMATTING;
1553
+ const args = [
1554
+ "format",
1555
+ "--write",
1556
+ BIOME_UNMATCHED_FLAG,
1557
+ ...editorConfigFlag,
1558
+ ...styleArgs
1559
+ ];
1560
+ const local = await findInNodeModules("biome", cwd);
1561
+ if (local)
1562
+ return [local, ...args, filePath];
1563
+ const global = await findGlobalBinary("biome");
1564
+ if (global)
1565
+ return [global, ...args, filePath];
1566
+ const toolId = getAutoInstallToolIdForFormatter("biome");
1567
+ if (!toolId)
1568
+ return null;
1569
+ const { ensureTool } = await import("./probes/installer.js");
1570
+ const installed = await ensureTool(toolId);
1571
+ if (installed)
1572
+ return [installed, ...args, filePath];
1573
+ return null;
1574
+ },
1575
+ extensions: [
1576
+ ".js",
1577
+ ".jsx",
1578
+ ".mjs",
1579
+ ".cjs",
1580
+ ".ts",
1581
+ ".tsx",
1582
+ ".mts",
1583
+ ".cts",
1584
+ ".json",
1585
+ ".jsonc",
1586
+ ".css",
1587
+ ".scss",
1588
+ ".sass",
1589
+ ".vue",
1590
+ ".svelte",
1591
+ ".html",
1592
+ ".htm"
1593
+ ],
1594
+ async detect(cwd) {
1595
+ return hasBiomeConfig(cwd) || hasNearestPackageJsonDependency(cwd, "@biomejs/biome");
1596
+ }
1597
+ };
1598
+ var prettierFormatter = {
1599
+ name: "prettier",
1600
+ command: ["npx", "prettier", "--write", "$FILE"],
1601
+ async resolveCommand(filePath, cwd) {
1602
+ const styleArgs = await indentationArgs(filePath, "prettier", cwd);
1603
+ if (styleArgs === null)
1604
+ return SKIP_FORMATTING;
1605
+ const args = ["--write", ...styleArgs];
1606
+ const local = await findInNodeModules("prettier", cwd);
1607
+ if (local)
1608
+ return [local, ...args, filePath];
1609
+ const global = await findGlobalBinary("prettier");
1610
+ if (global)
1611
+ return [global, ...args, filePath];
1612
+ return resolveManagedSmartDefaultCommand("prettier", filePath, args);
1613
+ },
1614
+ extensions: [
1615
+ ".js",
1616
+ ".jsx",
1617
+ ".mjs",
1618
+ ".cjs",
1619
+ ".ts",
1620
+ ".tsx",
1621
+ ".mts",
1622
+ ".cts",
1623
+ ".json",
1624
+ ".jsonc",
1625
+ ".css",
1626
+ ".scss",
1627
+ ".sass",
1628
+ ".less",
1629
+ ".vue",
1630
+ ".svelte",
1631
+ ".html",
1632
+ ".htm",
1633
+ ".md",
1634
+ ".mdx",
1635
+ ".yaml",
1636
+ ".yml",
1637
+ ".graphql",
1638
+ ".gql"
1639
+ ],
1640
+ async detect(cwd) {
1641
+ return hasPrettierConfig(cwd) || hasNearestPackageJsonDependency(cwd, "prettier") || hasNearestPackageJsonField(cwd, "prettier");
1642
+ }
1643
+ };
1644
+ var OXFMT_NO_ERROR_ON_UNMATCHED = "--no-error-on-unmatched-pattern";
1645
+ var oxfmtFormatter = {
1646
+ name: "oxfmt",
1647
+ command: ["oxfmt", OXFMT_NO_ERROR_ON_UNMATCHED, "$FILE"],
1648
+ // #1337 audit: oxfmt (and the `vp fmt --write` path) publish no exit-code
1649
+ // table. `--write` is the default and `--check` is the separate verification
1650
+ // mode, so there is no documented nonzero-on-reformat. Absent a documented
1651
+ // benign-nonzero mode, it stays strict — the safe direction, since the failure
1652
+ // mode of guessing wrong the other way is a silent no-op (#1336).
1653
+ async resolveCommand(filePath, cwd) {
1654
+ if (hasVitePlusConfig(cwd)) {
1655
+ const localVp = await findInNodeModules("vp", cwd);
1656
+ if (localVp)
1657
+ return [localVp, "fmt", filePath, "--write"];
1658
+ const globalVp = await which("vp");
1659
+ if (globalVp)
1660
+ return [globalVp, "fmt", filePath, "--write"];
1661
+ }
1662
+ const local = await findInNodeModules("oxfmt", cwd);
1663
+ if (local)
1664
+ return [local, OXFMT_NO_ERROR_ON_UNMATCHED, filePath];
1665
+ const found = await which("oxfmt");
1666
+ if (found)
1667
+ return [found, OXFMT_NO_ERROR_ON_UNMATCHED, filePath];
1668
+ return await resolveManagedFormatterCommand("oxfmt", filePath, [OXFMT_NO_ERROR_ON_UNMATCHED], findInNodeModules, cwd) ?? FORMATTER_UNAVAILABLE;
1669
+ },
1670
+ // Single source of truth: OXFMT_SUPPORTED_EXTENSIONS in tool-policy.ts.
1671
+ // Do not hand-maintain a second copy of this list (#1134 — previously two
1672
+ // parallel hand-maintained lists, the #883 single-source-of-truth class).
1673
+ extensions: [...OXFMT_SUPPORTED_EXTENSIONS],
1674
+ async detect(cwd) {
1675
+ return hasOxfmtConfig(cwd) || hasVitePlusConfig(cwd) || // Published package is `oxfmt` (the scoped name does not exist on npm).
1676
+ hasNearestPackageJsonDependency(cwd, "oxfmt") || hasNearestPackageJsonDependency(cwd, "@oxc-project/oxfmt");
1677
+ }
1678
+ };
1679
+ var ruffFormatter = {
1680
+ name: "ruff",
1681
+ command: ["ruff", "format", "$FILE"],
1682
+ extensions: [".py", ".pyi"],
1683
+ // Strict (the #1337 default): `ruff format` exits 0 on a successful in-place
1684
+ // rewrite and 2 on argument rejection / syntax error (verified, ruff 0.x:
1685
+ // well-formed → 0, reformatted → 0, unparseable → 2). The exit-2 no-op is
1686
+ // exactly what hid the bad --indent-style flags for a full release cycle.
1687
+ async resolveCommand(filePath, cwd) {
1688
+ const styleArgs = await indentationArgs(filePath, "ruff", cwd);
1689
+ if (styleArgs === null)
1690
+ return SKIP_FORMATTING;
1691
+ const args = ["format", ...styleArgs];
1692
+ const venv = await findInVenv("ruff", cwd);
1693
+ if (venv)
1694
+ return [venv, ...args, filePath];
1695
+ const toolId = getAutoInstallToolIdForFormatter("ruff");
1696
+ if (!toolId)
1697
+ return null;
1698
+ const { ensureTool } = await import("./probes/installer.js");
1699
+ const installed = await ensureTool(toolId);
1700
+ if (installed)
1701
+ return [installed, ...args, filePath];
1702
+ return FORMATTER_UNAVAILABLE;
1703
+ },
1704
+ async detect(cwd) {
1705
+ if (hasRuffConfig(cwd))
1706
+ return true;
1707
+ return Boolean(await getToolPath("ruff"));
1708
+ }
1709
+ };
1710
+ var blackFormatter = {
1711
+ name: "black",
1712
+ command: ["black", "$FILE"],
1713
+ extensions: [".py", ".pyi"],
1714
+ resolveCommand: managedFormatterResolver("black", [], findInVenv),
1715
+ async detect(cwd) {
1716
+ return hasBlackConfig(cwd);
1717
+ }
1718
+ };
1719
+ var sqlfluffFormatter = {
1720
+ name: "sqlfluff",
1721
+ command: ["sqlfluff", "fix", "--force", "$FILE"],
1722
+ extensions: [".sql"],
1723
+ lenientExitCode: "lint-autofix: `sqlfluff fix` writes the corrected file and then exits 1 when unfixable violations remain (its documented exit codes are 0 = all clean, 1 = violations remain, 2 = command/config failure), so a nonzero exit routinely accompanies a successful rewrite.",
1724
+ lenientStatuses: [1],
1725
+ async resolveCommand(filePath, cwd) {
1726
+ const venv = await findInVenv("sqlfluff", cwd);
1727
+ if (venv)
1728
+ return [venv, "fix", "--force", filePath];
1729
+ return null;
1730
+ },
1731
+ async detect(cwd) {
1732
+ return hasSqlfluffConfig(cwd);
1733
+ }
1734
+ };
1735
+ var gofmtFormatter = {
1736
+ name: "gofmt",
1737
+ command: ["gofmt", "-w", "$FILE"],
1738
+ extensions: [".go"],
1739
+ async resolveCommand(filePath, _cwd) {
1740
+ const gofmtBinary = await resolveGoFmtBinary();
1741
+ if (!gofmtBinary)
1742
+ return null;
1743
+ return [gofmtBinary, "-w", filePath];
1744
+ },
1745
+ async detect(_cwd) {
1746
+ return await resolveGoFmtBinary() !== null;
1747
+ }
1748
+ };
1749
+ var rustfmtFormatter = {
1750
+ name: "rustfmt",
1751
+ command: ["rustfmt", "$FILE"],
1752
+ extensions: [".rs"],
1753
+ // #2466: rustfmt defaults to an OLDER edition than the file's actual Cargo
1754
+ // package when invoked bare, so it can reject valid newer-edition syntax
1755
+ // (e.g. Rust 2024). Carry the nearest package's `edition` (honoring
1756
+ // `edition.workspace = true` inheritance) through `--edition`; `undefined`
1757
+ // (unreadable/unparseable manifest) falls back to the static command
1758
+ // above, unchanged from pre-#2466 behavior.
1759
+ async resolveCommand(filePath, _cwd) {
1760
+ const edition = await resolveCargoPackageEdition(filePath);
1761
+ if (edition === void 0)
1762
+ return null;
1763
+ return ["rustfmt", "--edition", edition, filePath];
1764
+ },
1765
+ async detect(cwd) {
1766
+ if (await which("rustfmt") !== null)
1767
+ return true;
1768
+ const rustProject = (await findUp(["Cargo.toml"], cwd)).length > 0;
1769
+ if (!rustProject)
1770
+ return false;
1771
+ if (await which("rustup") === null)
1772
+ return false;
1773
+ await tryLazyInstallFormatterTool("rustfmt", cwd);
1774
+ return await which("rustfmt") !== null;
1775
+ }
1776
+ };
1777
+ var zigFormatter = {
1778
+ name: "zig",
1779
+ command: ["zig", "fmt", "$FILE"],
1780
+ extensions: [".zig", ".zon"],
1781
+ async detect(_cwd) {
1782
+ return await which("zig") !== null;
1783
+ }
1784
+ };
1785
+ var dartFormatter = {
1786
+ name: "dart",
1787
+ command: ["dart", "format", "$FILE"],
1788
+ extensions: [".dart"],
1789
+ async detect(_cwd) {
1790
+ return await which("dart") !== null;
1791
+ }
1792
+ };
1793
+ var shfmtFormatter = {
1794
+ name: "shfmt",
1795
+ command: ["shfmt", "-w", "$FILE"],
1796
+ extensions: [".sh", ".bash"],
1797
+ async resolveCommand(filePath, cwd) {
1798
+ const styleArgs = await indentationArgs(filePath, "shfmt", cwd);
1799
+ if (styleArgs === null)
1800
+ return SKIP_FORMATTING;
1801
+ const inPath = await which("shfmt");
1802
+ if (inPath)
1803
+ return [inPath, "-w", ...styleArgs, filePath];
1804
+ return resolveManagedSmartDefaultCommand("shfmt", filePath, [
1805
+ "-w",
1806
+ ...styleArgs
1807
+ ]);
1808
+ },
1809
+ detect: managedToolDetect("shfmt", void 0, async () => await which("shfmt") !== null)
1810
+ };
1811
+ var nixfmtFormatter = {
1812
+ name: "nixfmt",
1813
+ command: ["nixfmt", "$FILE"],
1814
+ // #1337 audit: nixfmt's README documents in-place formatting but has no
1815
+ // exit-code section and no change-detection mode, so nothing documents a
1816
+ // benign nonzero. Strict by default (see oxfmt above for the rationale).
1817
+ extensions: [".nix"],
1818
+ async detect(_cwd) {
1819
+ return await which("nixfmt") !== null;
1820
+ }
1821
+ };
1822
+ var mixFormatter = {
1823
+ name: "mix",
1824
+ command: ["mix", "format", "$FILE"],
1825
+ extensions: [".ex", ".exs", ".eex", ".heex", ".leex"],
1826
+ async detect(_cwd) {
1827
+ return await which("mix") !== null;
1828
+ }
1829
+ };
1830
+ var ocamlformatFormatter = {
1831
+ name: "ocamlformat",
1832
+ command: ["ocamlformat", "-i", "$FILE"],
1833
+ extensions: [".ml", ".mli"],
1834
+ async detect(cwd) {
1835
+ const hasBinary = await which("ocamlformat") !== null;
1836
+ if (!hasBinary)
1837
+ return false;
1838
+ const configs = [".ocamlformat"];
1839
+ const found = await findUp(configs, cwd);
1840
+ return found.length > 0;
1841
+ }
1842
+ };
1843
+ var clangFormatFormatter = {
1844
+ name: "clang-format",
1845
+ command: ["clang-format", "-i", "$FILE"],
1846
+ extensions: [".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".ino"],
1847
+ async detect(cwd) {
1848
+ const hasBinary = await which("clang-format") !== null;
1849
+ if (!hasBinary)
1850
+ return false;
1851
+ const configs = [".clang-format", "_clang-format"];
1852
+ const found = await findUp(configs, cwd);
1853
+ return found.length > 0;
1854
+ }
1855
+ };
1856
+ var ktlintFormatter = {
1857
+ name: "ktlint",
1858
+ command: ["ktlint", "-F", "$FILE"],
1859
+ extensions: [".kt", ".kts"],
1860
+ lenientExitCode: "lint-autofix: `ktlint -F` autocorrects what it can and then exits 1 if any lint error remains unfixed \u2014 the documented CLI contract (ktlint exits nonzero whenever violations are reported, and -F does not suppress the ones it cannot correct).",
1861
+ lenientStatuses: [1],
1862
+ async resolveCommand(filePath, _cwd) {
1863
+ const inPath = await which("ktlint");
1864
+ if (inPath)
1865
+ return [inPath, "-F", filePath];
1866
+ return resolveManagedSmartDefaultCommand("ktlint", filePath, ["-F"]);
1867
+ },
1868
+ detect: managedToolDetect("ktlint", void 0, async () => await which("ktlint") !== null)
1869
+ };
1870
+ var ktfmtFormatter = {
1871
+ name: "ktfmt",
1872
+ // ktfmt formats in place when given a file path (no flag needed).
1873
+ command: ["ktfmt", "$FILE"],
1874
+ extensions: [".kt", ".kts"],
1875
+ // #2468: ktfmt's CLI never reads a project's Gradle `ktfmt { googleStyle()
1876
+ // | kotlinLangStyle() }` selection — style is CLI-flag-only
1877
+ // (`--google-style`/`--kotlinlang-style`, verified against ktfmt v0.63's
1878
+ // own arg parser). Carry the nearest module's declared style through;
1879
+ // `undefined` (no declaration, unreadable/unparseable manifest, or an
1880
+ // unsupported style like the removed `dropboxStyle()`) falls back to the
1881
+ // bare invocation, unchanged from pre-#2468 behavior.
1882
+ async resolveCommand(filePath, _cwd) {
1883
+ const styleFlag = await resolveKtfmtGradleStyle(filePath);
1884
+ const inPath = await which("ktfmt");
1885
+ if (inPath)
1886
+ return styleFlag ? [inPath, styleFlag, filePath] : [inPath, filePath];
1887
+ const { ensureTool } = await import("./probes/installer.js");
1888
+ const installed = await ensureTool("ktfmt");
1889
+ if (!installed)
1890
+ return FORMATTER_UNAVAILABLE;
1891
+ return styleFlag ? [installed, styleFlag, filePath] : [installed, filePath];
1892
+ },
1893
+ async detect(cwd) {
1894
+ return hasKtfmtConfig(cwd);
1895
+ }
1896
+ };
1897
+ var rubocopFormatter = {
1898
+ name: "rubocop",
1899
+ command: ["rubocop", "-a", "--no-color", "$FILE"],
1900
+ extensions: [".rb", ".rake", ".gemspec", ".ru"],
1901
+ lenientExitCode: "lint-autofix: `rubocop -a` exits 1 whenever ANY offense remains after it has already rewritten the file. Verified locally (rubocop on Ruby 3.4): a file with an unfixable Lint/UselessAssignment exits 1, and even a tidy file exits 1 on an unfixable Style/Documentation offense \u2014 nonzero is the normal outcome, not a failure.",
1902
+ lenientStatuses: [1],
1903
+ async resolveCommand(filePath, cwd) {
1904
+ if (await canUseBundleExec(cwd))
1905
+ return ["bundle", "exec", "rubocop", "-a", "--no-color", filePath];
1906
+ return null;
1907
+ },
1908
+ async detect(cwd) {
1909
+ if (!hasRubocopConfig(cwd))
1910
+ return false;
1911
+ if (await which("rubocop") !== null)
1912
+ return true;
1913
+ await tryLazyInstallFormatterTool("rubocop", cwd);
1914
+ return await which("rubocop") !== null;
1915
+ }
1916
+ };
1917
+ var standardrbFormatter = {
1918
+ name: "standardrb",
1919
+ command: ["standardrb", "--fix", "$FILE"],
1920
+ extensions: [".rb", ".rake"],
1921
+ lenientExitCode: "lint-autofix: standardrb is a RuboCop wrapper and inherits its exit contract \u2014 `--fix` exits 1 when offenses remain after the rewrite.",
1922
+ lenientStatuses: [1],
1923
+ async resolveCommand(filePath, cwd) {
1924
+ if (await canUseBundleExec(cwd))
1925
+ return ["bundle", "exec", "standardrb", "--fix", filePath];
1926
+ return null;
1927
+ },
1928
+ async detect(cwd) {
1929
+ if (!hasStandardrbConfig(cwd))
1930
+ return false;
1931
+ return await which("standardrb") !== null;
1932
+ }
1933
+ };
1934
+ var gleamFormatter = {
1935
+ name: "gleam",
1936
+ command: ["gleam", "format", "$FILE"],
1937
+ extensions: [".gleam"],
1938
+ async detect(cwd) {
1939
+ const found = await findUp(["gleam.toml"], cwd);
1940
+ if (found.length > 0)
1941
+ return await which("gleam") !== null;
1942
+ return false;
1943
+ }
1944
+ };
1945
+ var typstyleFormatter = {
1946
+ name: "typstyle",
1947
+ command: ["typstyle", "-i", "$FILE"],
1948
+ extensions: [".typ", ".typc"],
1949
+ async resolveCommand(filePath) {
1950
+ const inPath = await which("typstyle");
1951
+ if (inPath)
1952
+ return [inPath, "-i", filePath];
1953
+ return resolveManagedSmartDefaultCommand("typstyle", filePath, ["-i"]);
1954
+ },
1955
+ detect: managedToolDetect("typstyle", void 0, async () => await which("typstyle") !== null)
1956
+ };
1957
+ var terraformFormatter = {
1958
+ name: "terraform",
1959
+ command: ["terraform", "fmt", "$FILE"],
1960
+ extensions: [".tf", ".tfvars"],
1961
+ async detect(_cwd) {
1962
+ return await which("terraform") !== null;
1963
+ }
1964
+ };
1965
+ var terragruntHclFormatter = {
1966
+ name: "terragrunt-hcl",
1967
+ command: ["terragrunt", "hcl", "fmt", "--file", "$FILE"],
1968
+ extensions: [],
1969
+ filenames: TERRAGRUNT_FILENAMES,
1970
+ // Strict (the #1337 default): verified exit 0 on a successful in-place format
1971
+ // against terragrunt v1.1.2. A binary predating the `hcl` command group exits
1972
+ // nonzero and touches nothing, which unguarded reads as "already formatted".
1973
+ async detect(_cwd) {
1974
+ return await which("terragrunt") !== null;
1975
+ }
1976
+ };
1977
+ var phpCsFixerFormatter = {
1978
+ name: "php-cs-fixer",
1979
+ command: ["php-cs-fixer", "fix", "$FILE"],
1980
+ extensions: [".php"],
1981
+ // #2472: php-cs-fixer does NOT walk up parent directories looking for its
1982
+ // own config the way prettier/biome/eslint do (verified against upstream
1983
+ // `computeConfigFiles()` — see `resolvePhpCsFixerConfig`'s doc comment),
1984
+ // and `formatFile` spawns with cwd = the FILE's own directory, which is
1985
+ // not necessarily where the ancestor config `detect()` found actually
1986
+ // lives. Always resolve the binary explicitly here (vendor/bin first,
1987
+ // then global) rather than falling through to the static `command` above
1988
+ // — that static command can never carry `--config`, so a config found at
1989
+ // an ancestor would silently be dropped whenever the vendor lookup here
1990
+ // missed but a global binary still resolved. `--config` is attached
1991
+ // whenever a config resolves, even when it sits in the file's own
1992
+ // directory (AC3): unlike the pre-#2472 code, correctness no longer
1993
+ // depends on php-cs-fixer's own (nonexistent) upward search.
1994
+ async resolveCommand(filePath, cwd) {
1995
+ const configPath = resolvePhpCsFixerConfig(filePath);
1996
+ const binary = await findInVendorBin("php-cs-fixer", cwd) ?? await which("php-cs-fixer");
1997
+ const managed = await resolveManagedFormatterCommand("php-cs-fixer", filePath, [], findInVendorBin, cwd);
1998
+ if (managed === FORMATTER_UNAVAILABLE)
1999
+ return FORMATTER_UNAVAILABLE;
2000
+ const resolved = binary ?? managed[0];
2001
+ if (!resolved)
2002
+ return FORMATTER_UNAVAILABLE;
2003
+ return configPath ? [resolved, "fix", "--config", configPath, filePath] : [resolved, "fix", filePath];
2004
+ },
2005
+ detect: managedToolDetect("php-cs-fixer", async (cwd) => (await findUp([".php-cs-fixer.php", ".php-cs-fixer.dist.php"], cwd)).length > 0, async (cwd) => Boolean(await findInVendorBin("php-cs-fixer", cwd) || await which("php-cs-fixer")))
2006
+ };
2007
+ var csharpierFormatter = {
2008
+ name: "csharpier",
2009
+ // CSharpier ≥1.0 is a standalone `csharpier format <file>`; the `dotnet
2010
+ // csharpier <file>` form was removed (a bare `dotnet csharpier` now errors
2011
+ // "a dotnet-prefixed executable with this name could not be found"). Keep the
2012
+ // legacy form as a fallback for CSharpier 0.x via resolveCommand.
2013
+ command: ["csharpier", "format", "$FILE"],
2014
+ extensions: [".cs"],
2015
+ async resolveCommand(filePath, _cwd) {
2016
+ if (await which("csharpier") !== null) {
2017
+ return ["csharpier", "format", filePath];
2018
+ }
2019
+ if (await which("dotnet") !== null) {
2020
+ const legacy = await probeToolAsync("dotnet", ["csharpier", "--version"], { timeout: 5e3 });
2021
+ if (!legacy.error && legacy.status === 0) {
2022
+ return ["dotnet", "csharpier", filePath];
2023
+ }
2024
+ }
2025
+ return null;
2026
+ },
2027
+ async detect(_cwd) {
2028
+ if (await which("csharpier") !== null)
2029
+ return true;
2030
+ if (await which("dotnet") === null)
2031
+ return false;
2032
+ const result = await probeToolAsync("dotnet", ["csharpier", "--version"], {
2033
+ timeout: 5e3
2034
+ });
2035
+ return !result.error && result.status === 0;
2036
+ }
2037
+ };
2038
+ var fantomasFormatter = {
2039
+ name: "fantomas",
2040
+ command: ["fantomas", "$FILE"],
2041
+ extensions: [".fs", ".fsi", ".fsx"],
2042
+ async detect(_cwd) {
2043
+ return await which("fantomas") !== null;
2044
+ }
2045
+ };
2046
+ var swiftformatFormatter = {
2047
+ name: "swiftformat",
2048
+ command: ["swiftformat", "$FILE"],
2049
+ extensions: [".swift"],
2050
+ async detect(_cwd) {
2051
+ return await which("swiftformat") !== null;
2052
+ }
2053
+ };
2054
+ var styluaFormatter = {
2055
+ name: "stylua",
2056
+ command: ["stylua", "$FILE"],
2057
+ extensions: [".lua"],
2058
+ resolveCommand: managedFormatterResolver("stylua", [], findLocalBinUpwards),
2059
+ detect: managedToolDetect("stylua", async (cwd) => (await findUp(["stylua.toml", ".stylua.toml"], cwd)).length > 0, async (cwd) => Boolean(findLocalBinUpwards("stylua", cwd) || await which("stylua")))
2060
+ };
2061
+ var ormoluFormatter = {
2062
+ name: "ormolu",
2063
+ command: ["ormolu", "--mode", "inplace", "$FILE"],
2064
+ extensions: [".hs", ".lhs"],
2065
+ async detect(_cwd) {
2066
+ return await which("ormolu") !== null;
2067
+ }
2068
+ };
2069
+ var taploFormatter = {
2070
+ name: "taplo",
2071
+ command: ["taplo", "fmt", "$FILE"],
2072
+ extensions: [".toml"],
2073
+ async resolveCommand(filePath, _cwd) {
2074
+ const inPath = await which("taplo");
2075
+ if (inPath)
2076
+ return [inPath, "fmt", filePath];
2077
+ return resolveManagedSmartDefaultCommand("taplo", filePath, ["fmt"]);
2078
+ },
2079
+ detect: managedToolDetect("taplo", void 0, async () => await which("taplo") !== null)
2080
+ };
2081
+ var googleJavaFormatFormatter = {
2082
+ name: "google-java-format",
2083
+ command: ["google-java-format", "--replace", "$FILE"],
2084
+ extensions: [".java"],
2085
+ resolveCommand: managedFormatterResolver("google-java-format", ["--replace"]),
2086
+ detect: managedToolDetect("google-java-format", hasGoogleJavaFormatConfig, async () => await which("google-java-format") !== null)
2087
+ };
2088
+ var cljfmtFormatter = {
2089
+ name: "cljfmt",
2090
+ command: ["cljfmt", "fix", "$FILE"],
2091
+ extensions: [".clj", ".cljc", ".cljs"],
2092
+ resolveCommand: managedFormatterResolver("cljfmt", ["fix"]),
2093
+ detect: managedToolDetect("cljfmt", hasCljfmtConfig, async () => await which("cljfmt") !== null)
2094
+ };
2095
+ var cmakeFormatFormatter = {
2096
+ name: "cmake-format",
2097
+ command: ["cmake-format", "-i", "$FILE"],
2098
+ extensions: [".cmake"],
2099
+ resolveCommand: managedFormatterResolver("cmake-format", ["-i"]),
2100
+ detect: managedToolDetect("cmake-format", hasCmakeFormatConfig, async () => await which("cmake-format") !== null)
2101
+ };
2102
+ var cueFormatter = {
2103
+ name: "cue",
2104
+ // `cue fmt <file>` rewrites in place already. There is no `-w`: the only
2105
+ // flags are --check, -d/--diff and --files, so `cue fmt -w` aborts with
2106
+ // "unknown shorthand flag: 'w'" on every .cue write (verified on cue
2107
+ // v0.17.1).
2108
+ command: ["cue", "fmt", "$FILE"],
2109
+ extensions: [".cue"],
2110
+ async detect(_cwd) {
2111
+ return await which("cue") !== null;
2112
+ }
2113
+ };
2114
+ function psScriptAnalyzerCommand(filePath, settingsPath) {
2115
+ const quoted = filePath.replace(/'/g, "''");
2116
+ const settingsArg = settingsPath ? ` -Settings '${settingsPath.replace(/'/g, "''")}'` : "";
2117
+ return [
2118
+ "$ErrorActionPreference = 'Stop'",
2119
+ `$p = '${quoted}'`,
2120
+ "$content = Get-Content -Raw -LiteralPath $p",
2121
+ "if ([string]::IsNullOrWhiteSpace($content)) { exit 0 }",
2122
+ `$formatted = Invoke-Formatter -ScriptDefinition $content${settingsArg}`,
2123
+ "if ($null -eq $formatted) { throw 'Invoke-Formatter returned no output' }",
2124
+ "Set-Content -LiteralPath $p -Value $formatted"
2125
+ ].join("; ");
2126
+ }
2127
+ var psscriptanalyzerFormatFormatter = {
2128
+ name: "psscriptanalyzer-format",
2129
+ command: ["pwsh", "-NoProfile", "-Command", psScriptAnalyzerCommand("$FILE")],
2130
+ extensions: [".ps1", ".psm1", ".psd1"],
2131
+ async resolveCommand(filePath, cwd) {
2132
+ const pwsh = await which("pwsh") ?? await which("powershell");
2133
+ if (!pwsh)
2134
+ return null;
2135
+ const settingsPath = findPSScriptAnalyzerConfigPath(cwd);
2136
+ return [
2137
+ pwsh,
2138
+ "-NoProfile",
2139
+ "-Command",
2140
+ psScriptAnalyzerCommand(filePath, settingsPath)
2141
+ ];
2142
+ },
2143
+ async detect(_cwd) {
2144
+ const pwsh = await which("pwsh") ?? await which("powershell");
2145
+ if (!pwsh)
2146
+ return false;
2147
+ const result = await probeToolAsync(pwsh, [
2148
+ "-NoProfile",
2149
+ "-Command",
2150
+ "Get-Module -ListAvailable PSScriptAnalyzer | Select-Object -First 1 -ExpandProperty Name"
2151
+ ], { timeout: 5e3 });
2152
+ return (result.stdout ?? "").includes("PSScriptAnalyzer");
2153
+ }
2154
+ };
2155
+ var ALL_FORMATTERS = [
2156
+ biomeFormatter,
2157
+ prettierFormatter,
2158
+ oxfmtFormatter,
2159
+ ruffFormatter,
2160
+ blackFormatter,
2161
+ sqlfluffFormatter,
2162
+ gofmtFormatter,
2163
+ rustfmtFormatter,
2164
+ zigFormatter,
2165
+ dartFormatter,
2166
+ shfmtFormatter,
2167
+ nixfmtFormatter,
2168
+ mixFormatter,
2169
+ ocamlformatFormatter,
2170
+ clangFormatFormatter,
2171
+ ktlintFormatter,
2172
+ ktfmtFormatter,
2173
+ terraformFormatter,
2174
+ terragruntHclFormatter,
2175
+ phpCsFixerFormatter,
2176
+ csharpierFormatter,
2177
+ fantomasFormatter,
2178
+ swiftformatFormatter,
2179
+ styluaFormatter,
2180
+ ormoluFormatter,
2181
+ rubocopFormatter,
2182
+ standardrbFormatter,
2183
+ gleamFormatter,
2184
+ typstyleFormatter,
2185
+ taploFormatter,
2186
+ googleJavaFormatFormatter,
2187
+ cljfmtFormatter,
2188
+ cmakeFormatFormatter,
2189
+ cueFormatter,
2190
+ psscriptanalyzerFormatFormatter
2191
+ ];
2192
+ var FILENAME_FORMATTER_BASENAMES = new Set(ALL_FORMATTERS.flatMap((f) => f.filenames ?? []));
2193
+ var detectionCache = new BoundedLruCache(32);
2194
+ var formatterSignatureFlights = new BoundedLruCache(32);
2195
+ var formatterCacheGeneration = createGenerationSource("formatter-cache");
2196
+ var FORMATTER_CONFIG_FILES = [
2197
+ "package.json",
2198
+ "biome.json",
2199
+ "biome.jsonc",
2200
+ ".prettierrc",
2201
+ ".prettierrc.json",
2202
+ ".prettierrc.yml",
2203
+ ".prettierrc.yaml",
2204
+ ".prettierrc.js",
2205
+ ".prettierrc.cjs",
2206
+ ".prettierrc.mjs",
2207
+ "prettier.config.js",
2208
+ "prettier.config.cjs",
2209
+ "prettier.config.mjs",
2210
+ "prettier.config.ts",
2211
+ "pyproject.toml",
2212
+ "ruff.toml",
2213
+ ".ruff.toml",
2214
+ "black.toml",
2215
+ ".black",
2216
+ "tox.ini",
2217
+ "setup.cfg",
2218
+ "requirements.txt",
2219
+ "Pipfile",
2220
+ ".sqlfluff",
2221
+ ".rubocop.yml",
2222
+ ".rubocop.yaml",
2223
+ "Gemfile",
2224
+ ".clang-format",
2225
+ "_clang-format",
2226
+ ".php-cs-fixer.php",
2227
+ ".php-cs-fixer.dist.php",
2228
+ "stylua.toml",
2229
+ ".stylua.toml",
2230
+ ".ocamlformat",
2231
+ ".editorconfig",
2232
+ ".google-java-format",
2233
+ ".ktfmt",
2234
+ ".ktfmt.kts",
2235
+ "build.gradle.kts",
2236
+ "build.gradle",
2237
+ "settings.gradle.kts",
2238
+ "settings.gradle",
2239
+ ".cljfmt.edn",
2240
+ "cljfmt.edn",
2241
+ ".cljfmt",
2242
+ ".cmake-format",
2243
+ ".cmake-format.yaml",
2244
+ ".cmake-format.yml",
2245
+ ".cmake-format.json",
2246
+ ".cmake-format.py",
2247
+ "cmake-format.py",
2248
+ "cmake-format.yaml",
2249
+ "cmake-format.yml",
2250
+ "oxfmt.toml",
2251
+ ".oxfmtrc.json",
2252
+ "vite-plus.json",
2253
+ "vite.config.ts",
2254
+ "vite.config.mts",
2255
+ "vite.config.cts",
2256
+ "vite.config.js",
2257
+ "vite.config.mjs",
2258
+ "vite.config.cjs",
2259
+ "PSScriptAnalyzerSettings.psd1",
2260
+ "ScriptAnalyzerSettings.psd1",
2261
+ // #1595 sweep additions.
2262
+ ".csharpierrc",
2263
+ ".csharpierrc.json",
2264
+ ".csharpierrc.yaml",
2265
+ ".csharpierrc.yml",
2266
+ ".ormolu",
2267
+ "taplo.toml",
2268
+ ".taplo.toml",
2269
+ ".terraform.lock.hcl",
2270
+ ".swiftformat",
2271
+ ".fantomasignore",
2272
+ ".formatter.exs"
2273
+ ];
2274
+ async function formatterConfigSignature(cwd) {
2275
+ const paths = await findUp(FORMATTER_CONFIG_FILES, cwd);
2276
+ const parts = await Promise.all(paths.sort(compareOrdinal).map(async (filePath) => {
2277
+ try {
2278
+ const stat2 = await fs2.stat(filePath);
2279
+ return `${filePath}:${stat2.mtimeMs}:${stat2.size}`;
2280
+ } catch {
2281
+ return `${filePath}:missing`;
2282
+ }
2283
+ }));
2284
+ return parts.join("|");
2285
+ }
2286
+ async function getFormatterConfigSignature(cwd, normalizedCwd) {
2287
+ const existing = formatterSignatureFlights.get(normalizedCwd);
2288
+ if (existing)
2289
+ return existing.promise;
2290
+ const promise = formatterConfigSignature(cwd).finally(() => {
2291
+ const current = formatterSignatureFlights.get(normalizedCwd);
2292
+ if (current?.promise === promise)
2293
+ formatterSignatureFlights.delete(normalizedCwd);
2294
+ });
2295
+ formatterSignatureFlights.set(normalizedCwd, { promise });
2296
+ return promise;
2297
+ }
2298
+ async function getFormattersForFile(filePath, cwd) {
2299
+ const ext = path4.extname(filePath).toLowerCase();
2300
+ const base = path4.basename(filePath).toLowerCase();
2301
+ const normalizedCwd = normalizeMapKey(cwd);
2302
+ const cacheKey = FILENAME_FORMATTER_BASENAMES.has(base) ? `${normalizedCwd}:${ext}:${base}` : `${normalizedCwd}:${ext}`;
2303
+ let cached = detectionCache.get(normalizedCwd);
2304
+ if (cached?.entries.has(cacheKey)) {
2305
+ const enabledNames2 = cached.entries.get(cacheKey);
2306
+ const selectedFormatterName = enabledNames2 && enabledNames2.length > 0 ? enabledNames2[0] : null;
2307
+ logLatency({
2308
+ type: "phase",
2309
+ phase: "formatter_selected",
2310
+ filePath,
2311
+ durationMs: 0,
2312
+ metadata: {
2313
+ formatter: selectedFormatterName,
2314
+ reason: "cache",
2315
+ cached: true,
2316
+ outcome: "hit",
2317
+ cwd
2318
+ }
2319
+ });
2320
+ if (!enabledNames2 || enabledNames2.length === 0)
2321
+ return [];
2322
+ return ALL_FORMATTERS.filter((f) => enabledNames2.includes(f.name));
2323
+ }
2324
+ if (!cached) {
2325
+ const generation = formatterCacheGeneration.capture();
2326
+ const configSignature = await getFormatterConfigSignature(cwd, normalizedCwd);
2327
+ if (!generation.isCurrent()) {
2328
+ return getFormattersForFile(filePath, cwd);
2329
+ }
2330
+ cached = detectionCache.get(normalizedCwd);
2331
+ if (!cached) {
2332
+ cached = { signature: configSignature, entries: /* @__PURE__ */ new Map() };
2333
+ detectionCache.set(normalizedCwd, cached);
2334
+ }
2335
+ }
2336
+ const matching = ALL_FORMATTERS.filter((f) => f.extensions.includes(ext) || f.filenames?.includes(base));
2337
+ const formatterPolicy = getFormatterPolicyForFile(filePath);
2338
+ const smartDefaultFormatterName = getSmartDefaultFormatterName(filePath);
2339
+ const candidateFormatters = formatterPolicy?.formatterNames?.length ? matching.filter((f) => formatterPolicy.formatterNames.includes(f.name)) : matching;
2340
+ let selected;
2341
+ const candidateOutcomes = [];
2342
+ if (formatterPolicy) {
2343
+ const explicitlyConfigured = candidateFormatters.filter((formatter) => hasExplicitFormatterConfig(formatter.name, cwd, ext));
2344
+ if (explicitlyConfigured.length > 0) {
2345
+ selected = formatterPolicy.defaultFormatter ? explicitlyConfigured.find((f) => f.name === formatterPolicy.defaultFormatter) ?? explicitlyConfigured[0] : explicitlyConfigured[0];
2346
+ } else if (smartDefaultFormatterName) {
2347
+ const smartDefaultFormatter = candidateFormatters.find((f) => f.name === smartDefaultFormatterName);
2348
+ if (smartDefaultFormatter) {
2349
+ const autoInstallToolId = getAutoInstallToolIdForFormatter(smartDefaultFormatter.name);
2350
+ if (autoInstallToolId) {
2351
+ selected = smartDefaultFormatter;
2352
+ } else {
2353
+ const { detected, error, outcome } = await detectCandidate(smartDefaultFormatter, cwd);
2354
+ candidateOutcomes.push(outcome);
2355
+ if (error !== void 0)
2356
+ throw error;
2357
+ if (detected)
2358
+ selected = smartDefaultFormatter;
2359
+ }
2360
+ }
2361
+ }
2362
+ } else {
2363
+ for (const formatter of candidateFormatters) {
2364
+ const { detected, error, outcome } = await detectCandidate(formatter, cwd);
2365
+ candidateOutcomes.push(outcome);
2366
+ if (error !== void 0) {
2367
+ logExtension({
2368
+ subsystem: "format",
2369
+ message: `Detection failed for ${formatter.name}: ${error instanceof Error ? error.message : String(error)}`,
2370
+ metadata: { formatter: formatter.name, cwd }
2371
+ });
2372
+ continue;
2373
+ }
2374
+ if (detected) {
2375
+ selected = formatter;
2376
+ break;
2377
+ }
2378
+ }
2379
+ }
2380
+ const enabled = selected ? [selected] : [];
2381
+ const stalledCandidateCommands = [
2382
+ ...new Set(candidateOutcomes.flatMap((outcome) => outcome.stalledCommands))
2383
+ ];
2384
+ const poisonedByTransientProbe = enabled.length === 0 && stalledCandidateCommands.length > 0;
2385
+ const winnerIndex = selected ? candidateOutcomes.findIndex((outcome) => outcome.name === selected.name) : -1;
2386
+ const unreachablePreferred = candidateOutcomes.slice(0, winnerIndex === -1 ? 0 : winnerIndex).filter((outcome) => outcome.verdict === "unreachable").map((outcome) => outcome.name);
2387
+ const degradedSelection = unreachablePreferred.length > 0;
2388
+ let selectionReason;
2389
+ if (poisonedByTransientProbe) {
2390
+ selectionReason = "probe-timeout";
2391
+ } else if (degradedSelection) {
2392
+ selectionReason = "preferred-unreachable";
2393
+ } else if (!selected) {
2394
+ selectionReason = "none";
2395
+ } else if (!formatterPolicy) {
2396
+ selectionReason = "detect";
2397
+ } else {
2398
+ selectionReason = candidateFormatters.some((f) => hasExplicitFormatterConfig(f.name, cwd, ext)) ? "explicit-config" : "smart-default";
2399
+ }
2400
+ const provisional = poisonedByTransientProbe || degradedSelection;
2401
+ logLatency({
2402
+ type: "phase",
2403
+ phase: "formatter_selected",
2404
+ filePath,
2405
+ durationMs: 0,
2406
+ metadata: {
2407
+ formatter: selected?.name ?? null,
2408
+ reason: selectionReason,
2409
+ outcome: "miss",
2410
+ cwd,
2411
+ ...provisional && {
2412
+ cached: false,
2413
+ stalledProbes: stalledCandidateCommands
2414
+ },
2415
+ ...degradedSelection && { unreachablePreferred }
2416
+ }
2417
+ });
2418
+ if (provisional)
2419
+ return enabled;
2420
+ const enabledNames = enabled.map((f) => f.name);
2421
+ if (detectionCache.get(normalizedCwd) === cached) {
2422
+ cached.entries.set(cacheKey, enabledNames);
2423
+ }
2424
+ return enabled;
2425
+ }
2426
+ function clearFormatterCache() {
2427
+ formatterCacheGeneration.bump();
2428
+ formatterSignatureFlights.clear();
2429
+ detectionCache.clear();
2430
+ resetWhichLatches();
2431
+ }
2432
+ var formatterConfigBasenames = new Set(FORMATTER_CONFIG_FILES.map((fileName) => fileName.toLowerCase()));
2433
+ function invalidateFormatterCacheForPath(filePath) {
2434
+ const basename2 = filePath.includes("\\") ? path4.win32.basename(filePath) : path4.basename(filePath);
2435
+ if (!formatterConfigBasenames.has(basename2.toLowerCase()))
2436
+ return;
2437
+ clearFormatterCache();
2438
+ }
2439
+ function _getFormatterResetStateForTests() {
2440
+ return {
2441
+ whichLatchByCommand,
2442
+ whichTransientCommands,
2443
+ cooldownRecordedForRetryAtMs,
2444
+ detectionCache,
2445
+ formatterSignatureFlights
2446
+ };
2447
+ }
2448
+ function clearFormatterRuntimeState() {
2449
+ clearFormatterCache();
2450
+ }
2451
+ var BOX_DRAWING_GLOBAL = /[\u2500-\u257F]/g;
2452
+ var DECORATION_RULE = /^[\u2500-\u257F\s]*$/;
2453
+ var DECORATION_HEADING = /^\S+[ \t]+[\u2500-\u257F][\u2500-\u257F\s]*$/;
2454
+ function firstDiagnosticLine(text) {
2455
+ for (const raw of (text ?? "").split("\n")) {
2456
+ const line = stripAnsi(raw).trimEnd();
2457
+ if (isDecorativeLine(line))
2458
+ continue;
2459
+ return line.replace(BOX_DRAWING_GLOBAL, "").trim().slice(0, 300);
2460
+ }
2461
+ return void 0;
2462
+ }
2463
+ function isDecorativeLine(line) {
2464
+ return DECORATION_RULE.test(line) || DECORATION_HEADING.test(line);
2465
+ }
2466
+ var FORMATTER_ERROR_TAIL_LINES = 20;
2467
+ function diagnosticTail(text, maxLines = FORMATTER_ERROR_TAIL_LINES) {
2468
+ const lines = [];
2469
+ for (const raw of (text ?? "").split("\n")) {
2470
+ const line = stripAnsi(raw).trimEnd();
2471
+ if (isDecorativeLine(line))
2472
+ continue;
2473
+ lines.push(line.slice(0, 300));
2474
+ }
2475
+ if (lines.length === 0)
2476
+ return void 0;
2477
+ return lines.slice(-maxLines).join("\n");
2478
+ }
2479
+ async function resolveFormatterCommand(formatter, absolutePath, cwd) {
2480
+ const agreement = establishToolAgreement(formatter.name, cwd);
2481
+ if (agreement.decision === "decline") {
2482
+ recordDegradationOnce({
2483
+ kind: "formatter-agreement-unavailable",
2484
+ subject: agreement.subject,
2485
+ reason: agreement.reason
2486
+ });
2487
+ return FORMATTER_AGREEMENT_UNAVAILABLE;
2488
+ }
2489
+ const resolved = formatter.resolveCommand ? await formatter.resolveCommand(absolutePath, cwd) : null;
2490
+ if (resolved === SKIP_FORMATTING)
2491
+ return SKIP_FORMATTING;
2492
+ if (resolved === FORMATTER_UNAVAILABLE)
2493
+ return FORMATTER_UNAVAILABLE;
2494
+ if (resolved !== null)
2495
+ return resolved;
2496
+ const fallback = formatter.command.map((c) => c.replace("$FILE", absolutePath));
2497
+ if (fallback[0] === "npx" && !assertInstallAllowed(`formatter npx fallback: ${formatter.name}`)) {
2498
+ return SKIP_FORMATTING;
2499
+ }
2500
+ return fallback;
2501
+ }
2502
+ async function formatFile(filePath, formatter, enter) {
2503
+ try {
2504
+ const absolutePath = path4.resolve(filePath);
2505
+ const cwd = path4.dirname(absolutePath);
2506
+ const formatterCwd = resolveToolCwd("formatter", formatter.name, absolutePath, { cwd: path4.parse(absolutePath).root }).cwd;
2507
+ const cmd = await resolveFormatterCommand(formatter, absolutePath, cwd);
2508
+ if (cmd === SKIP_FORMATTING) {
2509
+ return { success: true, changed: false, outcome: "skipped" };
2510
+ }
2511
+ if (cmd === FORMATTER_UNAVAILABLE) {
2512
+ return {
2513
+ success: true,
2514
+ changed: false,
2515
+ outcome: "unavailable",
2516
+ error: `${formatter.name}: formatter executable not found`
2517
+ };
2518
+ }
2519
+ if (cmd === FORMATTER_AGREEMENT_UNAVAILABLE) {
2520
+ return {
2521
+ success: true,
2522
+ changed: false,
2523
+ outcome: "unavailable",
2524
+ error: `${formatter.name}: project tool agreement could not be established`
2525
+ };
2526
+ }
2527
+ await enter?.();
2528
+ const contentBefore = await fs2.readFile(absolutePath, "utf-8");
2529
+ const result = await safeSpawnAsync(cmd[0], cmd.slice(1), {
2530
+ timeout: 15e3,
2531
+ cwd: formatterCwd
2532
+ });
2533
+ if (result.spawnFailure?.kind === "tool-not-found") {
2534
+ return {
2535
+ success: true,
2536
+ changed: false,
2537
+ outcome: "unavailable",
2538
+ error: result.spawnFailure.message
2539
+ };
2540
+ }
2541
+ const lenientOk = formatter.lenientExitCode !== void 0 && result.status !== null && (formatter.lenientStatuses ?? []).includes(result.status);
2542
+ if (result.error || result.status !== 0 && !lenientOk) {
2543
+ return {
2544
+ success: false,
2545
+ changed: false,
2546
+ outcome: "failed",
2547
+ error: result.error?.message || diagnosticTail(result.stderr) || // biome, ktlint and `mix format` report on STDOUT; without this
2548
+ // their diagnostic is discarded and the user is told only that
2549
+ // the tool "exited with status 1".
2550
+ diagnosticTail(result.stdout) || `${formatter.name} exited with status ${result.status}`
2551
+ };
2552
+ }
2553
+ const contentAfter = await fs2.readFile(absolutePath, "utf-8");
2554
+ const changed = contentBefore !== contentAfter;
2555
+ return {
2556
+ success: true,
2557
+ changed,
2558
+ outcome: changed ? "formatted" : "unchanged"
2559
+ };
2560
+ } catch (err) {
2561
+ return {
2562
+ success: false,
2563
+ changed: false,
2564
+ outcome: "failed",
2565
+ error: err instanceof Error ? err.message : String(err)
2566
+ };
2567
+ }
2568
+ }
2569
+ function listAllFormatters() {
2570
+ return ALL_FORMATTERS.map((f) => f.name);
2571
+ }
2572
+
2573
+ export {
2574
+ tryLazyInstallFormatterTool,
2575
+ SKIP_FORMATTING,
2576
+ FORMATTER_UNAVAILABLE,
2577
+ FORMATTER_AGREEMENT_UNAVAILABLE,
2578
+ _findUpForTests,
2579
+ FORMATTERS_WITH_EXPLICIT_CONFIG_CHECK,
2580
+ resolveFormatterCwd,
2581
+ biomeFormatter,
2582
+ prettierFormatter,
2583
+ oxfmtFormatter,
2584
+ ruffFormatter,
2585
+ blackFormatter,
2586
+ sqlfluffFormatter,
2587
+ gofmtFormatter,
2588
+ rustfmtFormatter,
2589
+ zigFormatter,
2590
+ dartFormatter,
2591
+ shfmtFormatter,
2592
+ nixfmtFormatter,
2593
+ mixFormatter,
2594
+ ocamlformatFormatter,
2595
+ clangFormatFormatter,
2596
+ ktlintFormatter,
2597
+ ktfmtFormatter,
2598
+ rubocopFormatter,
2599
+ standardrbFormatter,
2600
+ gleamFormatter,
2601
+ typstyleFormatter,
2602
+ terraformFormatter,
2603
+ terragruntHclFormatter,
2604
+ phpCsFixerFormatter,
2605
+ csharpierFormatter,
2606
+ fantomasFormatter,
2607
+ swiftformatFormatter,
2608
+ styluaFormatter,
2609
+ ormoluFormatter,
2610
+ taploFormatter,
2611
+ googleJavaFormatFormatter,
2612
+ cljfmtFormatter,
2613
+ cmakeFormatFormatter,
2614
+ cueFormatter,
2615
+ psscriptanalyzerFormatFormatter,
2616
+ ALL_FORMATTERS,
2617
+ getFormattersForFile,
2618
+ clearFormatterCache,
2619
+ invalidateFormatterCacheForPath,
2620
+ _getFormatterResetStateForTests,
2621
+ clearFormatterRuntimeState,
2622
+ firstDiagnosticLine,
2623
+ diagnosticTail,
2624
+ formatFile,
2625
+ listAllFormatters
2626
+ };