@automaton-labs/aib 0.0.7 → 0.0.8

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 (477) hide show
  1. package/README.md +36 -257
  2. package/config/agent-dx-policy.default.json +31 -0
  3. package/config/control-plane-client.default.json +3 -0
  4. package/dist/agent-dx/agent-dx.js +805 -0
  5. package/dist/agent-dx/presentation.js +32 -0
  6. package/dist/alias-advisor/analyze.js +982 -0
  7. package/dist/alias-advisor/exact-text-cost.js +74 -0
  8. package/dist/alias-advisor/lexical.js +240 -0
  9. package/dist/alias-advisor/model.js +2 -0
  10. package/dist/alias-advisor/path-identity.js +49 -0
  11. package/dist/alias-advisor/ranking.js +171 -0
  12. package/dist/alias-advisor/token-estimator.js +85 -0
  13. package/dist/bin/aib.js +5 -1
  14. package/dist/bin/cli.js +811 -4
  15. package/dist/commands/add-missing-imports-preview-cache.js +99 -2
  16. package/dist/commands/add-missing-imports.js +241 -2
  17. package/dist/commands/apply-module-plan.js +1319 -3
  18. package/dist/commands/background-command.js +378 -2
  19. package/dist/commands/captured-input.js +74 -1
  20. package/dist/commands/config-command.js +314 -2
  21. package/dist/commands/config-output.js +357 -10
  22. package/dist/commands/control-plane-command.js +183 -1
  23. package/dist/commands/declaration-command.js +1209 -7
  24. package/dist/commands/declaration-execution-cache.js +79 -1
  25. package/dist/commands/declaration-format.js +221 -1
  26. package/dist/commands/declaration-preview-cache.js +114 -2
  27. package/dist/commands/diagnostics-command.js +70 -3
  28. package/dist/commands/doctor.js +137 -3
  29. package/dist/commands/execution-command.js +117 -1
  30. package/dist/commands/exports-star-collapse-command.js +178 -0
  31. package/dist/commands/exports-star-command.js +252 -0
  32. package/dist/commands/exports-star-preview-cache.js +84 -0
  33. package/dist/commands/feedback-command.js +176 -3
  34. package/dist/commands/file-move-to-dir-execution-cache.js +92 -1
  35. package/dist/commands/file-move-to-dir-preview-cache.js +125 -2
  36. package/dist/commands/file-move-to-dir-worker.js +54 -0
  37. package/dist/commands/file-move-to-dir.js +1073 -5
  38. package/dist/commands/file-mutation-runtime.js +102 -1
  39. package/dist/commands/file-mutation-worker-apply.js +180 -0
  40. package/dist/commands/file-refactor-batch-execution-cache.js +90 -1
  41. package/dist/commands/file-refactor-batch-preview-cache.js +125 -2
  42. package/dist/commands/file-refactor-batch-worker.js +54 -0
  43. package/dist/commands/file-refactor-batch.js +1154 -5
  44. package/dist/commands/file-rename-execution-cache.js +92 -1
  45. package/dist/commands/file-rename-preview-cache.js +125 -2
  46. package/dist/commands/file-rename-worker.js +54 -0
  47. package/dist/commands/file-rename.js +1053 -5
  48. package/dist/commands/file-text-edit-executor.js +205 -0
  49. package/dist/commands/find-importers.js +52 -1
  50. package/dist/commands/find-unused-imports.js +55 -1
  51. package/dist/commands/generate-docs-command.js +244 -6
  52. package/dist/commands/help-command.js +460 -7
  53. package/dist/commands/import-specifier-policy.js +391 -0
  54. package/dist/commands/imports-command.js +68 -1
  55. package/dist/commands/imports-rebase.js +1138 -0
  56. package/dist/commands/init-skill-usage.js +92 -3
  57. package/dist/commands/init-workspace.js +30 -1
  58. package/dist/commands/inspect-alias-candidates.js +413 -0
  59. package/dist/commands/inspect-cycles.js +811 -5
  60. package/dist/commands/inspect-direct-usages.js +98 -0
  61. package/dist/commands/inspect-duplicates-format.js +229 -0
  62. package/dist/commands/inspect-format-primitives.js +127 -0
  63. package/dist/commands/inspect-format.js +1590 -18
  64. package/dist/commands/inspect-graph.js +1553 -9
  65. package/dist/commands/inspect-imports.js +339 -2
  66. package/dist/commands/inspect-mixed-format.js +524 -0
  67. package/dist/commands/inspect-module-plan-format.js +216 -0
  68. package/dist/commands/inspect-module-plan-serialization.js +402 -0
  69. package/dist/commands/inspect-reference-path-format.js +157 -0
  70. package/dist/commands/inspect-request-values.js +599 -0
  71. package/dist/commands/inspect-selector-kind.js +21 -0
  72. package/dist/commands/inspect-selector.js +50 -0
  73. package/dist/commands/inspect-symbol-format.js +90 -0
  74. package/dist/commands/inspect-topology.js +435 -0
  75. package/dist/commands/inspect-tree.js +827 -5
  76. package/dist/commands/inspect-usages-detail.js +793 -0
  77. package/dist/commands/inspect-usages-evidence.js +31 -0
  78. package/dist/commands/inspect-usages-format.js +367 -0
  79. package/dist/commands/inspect.js +1450 -16
  80. package/dist/commands/internal-command.js +64 -0
  81. package/dist/commands/json-file-input.js +60 -1
  82. package/dist/commands/module-plan-cache.js +156 -2
  83. package/dist/commands/module-plan-standalone.js +208 -0
  84. package/dist/commands/module-plan-timeout.js +77 -1
  85. package/dist/commands/move-preview-cache.js +101 -2
  86. package/dist/commands/mutate-aggregate-output.js +996 -0
  87. package/dist/commands/mutate-child-execution.js +374 -0
  88. package/dist/commands/mutate-command.js +1394 -0
  89. package/dist/commands/mutate-declaration-output.js +313 -0
  90. package/dist/commands/mutate-domain-adapters.js +638 -0
  91. package/dist/commands/mutate-execution-cache.js +114 -0
  92. package/dist/commands/mutate-execution-status.js +598 -0
  93. package/dist/commands/mutate-failure-output.js +531 -0
  94. package/dist/commands/mutate-file-view.js +151 -0
  95. package/dist/commands/mutate-object-output.js +91 -0
  96. package/dist/commands/mutate-output-values.js +97 -0
  97. package/dist/commands/mutate-preview-cache.js +86 -0
  98. package/dist/commands/mutate-response-replay.js +153 -0
  99. package/dist/commands/mutate-result-projection.js +818 -0
  100. package/dist/commands/mutation-eta.js +28 -0
  101. package/dist/commands/mutation-execution-cache.js +140 -3
  102. package/dist/commands/mutation-recovery-journal.js +195 -0
  103. package/dist/commands/normalize-imports.js +1120 -4
  104. package/dist/commands/object-pack-command.js +546 -0
  105. package/dist/commands/object-pack-preview-cache.js +88 -0
  106. package/dist/commands/observability-command.js +47 -3
  107. package/dist/commands/ota-command.js +403 -2
  108. package/dist/commands/print-config.js +10 -1
  109. package/dist/commands/quick-read.js +1113 -11
  110. package/dist/commands/refactor-batch-builder.js +265 -1
  111. package/dist/commands/refactor-batch-execution-cache.js +85 -1
  112. package/dist/commands/refactor-batch-preview-cache.js +96 -2
  113. package/dist/commands/refactor-batch.js +461 -4
  114. package/dist/commands/rename-entities.js +794 -4
  115. package/dist/commands/rename-execution-cache.js +49 -1
  116. package/dist/commands/rename-input.js +22 -1
  117. package/dist/commands/rename-polling-policy.js +68 -0
  118. package/dist/commands/rename-preview-cache.js +96 -2
  119. package/dist/commands/result-view.js +993 -7
  120. package/dist/commands/reveal-command.js +445 -5
  121. package/dist/commands/selector-suggestions.js +93 -0
  122. package/dist/commands/session-workspace.js +1836 -31
  123. package/dist/commands/shared.js +2 -1
  124. package/dist/commands/skills-command.js +315 -0
  125. package/dist/commands/sync-command.js +59 -2
  126. package/dist/commands/worker-command.js +173 -1
  127. package/dist/commands/workspace-cache.js +55 -1
  128. package/dist/config/defaults.js +26 -1
  129. package/dist/config/env-vars.js +77 -1
  130. package/dist/config/glob-match.js +44 -1
  131. package/dist/config/import-rules.js +165 -1
  132. package/dist/config/local-config.js +293 -3
  133. package/dist/config/mutation-comments.js +51 -1
  134. package/dist/config/path-aliases.js +165 -1
  135. package/dist/config/path-display.js +84 -1
  136. package/dist/config/product-storage.js +37 -1
  137. package/dist/config/request-env.js +21 -0
  138. package/dist/config/request-routing-context.js +23 -0
  139. package/dist/config/resolve-command-alias.js +74 -1
  140. package/dist/config/resolve.js +24 -1
  141. package/dist/config/tsconfig-discovery.js +113 -1
  142. package/dist/config/typescript-preferences.js +131 -0
  143. package/dist/config/workspace-root.js +310 -3
  144. package/dist/config/workspace-state.js +254 -1
  145. package/dist/content/content-bundle.js +88 -1
  146. package/dist/diagnostics/module-plan-timeline.js +75 -2
  147. package/dist/diagnostics/readiness-text.js +45 -8
  148. package/dist/dsl/aib-dsl.js +838 -1
  149. package/dist/dsl/declaration-dsl.js +264 -1
  150. package/dist/dsl/file-move-to-dir-dsl.js +123 -1
  151. package/dist/dsl/file-refactor-batch-dsl.js +203 -1
  152. package/dist/dsl/file-rename-dsl.js +135 -1
  153. package/dist/dsl/mutate-dsl.js +746 -0
  154. package/dist/help/bootstrap.bash.md +176 -341
  155. package/dist/help/bootstrap.md +175 -340
  156. package/dist/help/bootstrap.pwsh.md +176 -341
  157. package/dist/help/docs/basics.md +1 -1
  158. package/dist/help/docs/config-setup.import-normalize.md +65 -65
  159. package/dist/help/docs/config-setup.import-rules.md +6 -5
  160. package/dist/help/docs/first-setup.md +6 -5
  161. package/dist/help/docs/help-protocol.md +4 -3
  162. package/dist/help/docs/import.base.md +38 -0
  163. package/dist/help/docs/import.rebase.md +85 -0
  164. package/dist/help/docs/inspect.aliasCandidates.md +39 -0
  165. package/dist/help/docs/inspect.code.md +1 -7
  166. package/dist/help/docs/inspect.file.md +10 -19
  167. package/dist/help/docs/inspect.graph.md +3 -17
  168. package/dist/help/{dsl/docs/inspect.md → docs/inspect.shared.md} +13 -12
  169. package/dist/help/docs/modulePlan.md +24 -28
  170. package/dist/help/docs/move.md +19 -22
  171. package/dist/help/{dsl/topics/file.move.md → docs/moveToDir.md} +36 -34
  172. package/dist/help/docs/mutate.mixed.md +34 -0
  173. package/dist/help/docs/mutation.shared.md +55 -0
  174. package/dist/help/docs/patterns.md +3 -12
  175. package/dist/help/docs/qr.md +12 -6
  176. package/dist/help/docs/quick-map.md +36 -24
  177. package/dist/help/docs/recipe.file-layout.md +10 -10
  178. package/dist/help/docs/recipe.import-boundary.md +92 -0
  179. package/dist/help/docs/recipe.safe-artifact-probing.md +68 -0
  180. package/dist/help/docs/recipe.unfamiliar-area.md +64 -0
  181. package/dist/help/docs/recipes.md +20 -0
  182. package/dist/help/docs/rename.md +19 -27
  183. package/dist/help/docs/renameFile.md +36 -0
  184. package/dist/help/docs/rules.md +26 -0
  185. package/dist/help/dsl/bootstrap.bash.md +176 -341
  186. package/dist/help/dsl/bootstrap.md +175 -340
  187. package/dist/help/dsl/bootstrap.pwsh.md +176 -341
  188. package/dist/help/dsl/docs/basics.md +1 -1
  189. package/dist/help/dsl/docs/config-setup.import-normalize.md +65 -65
  190. package/dist/help/dsl/docs/config-setup.import-rules.md +6 -5
  191. package/dist/help/dsl/docs/first-setup.md +6 -5
  192. package/dist/help/dsl/docs/help-protocol.md +4 -3
  193. package/dist/help/dsl/docs/import.base.md +38 -0
  194. package/dist/help/dsl/docs/import.rebase.md +85 -0
  195. package/dist/help/dsl/docs/inspect.aliasCandidates.md +39 -0
  196. package/dist/help/dsl/docs/inspect.code.md +1 -7
  197. package/dist/help/dsl/docs/inspect.file.md +10 -19
  198. package/dist/help/dsl/docs/inspect.graph.md +3 -17
  199. package/dist/help/{docs/inspect.md → dsl/docs/inspect.shared.md} +13 -12
  200. package/dist/help/dsl/docs/modulePlan.md +24 -28
  201. package/dist/help/dsl/docs/move.md +19 -22
  202. package/dist/help/{topics/file.move.md → dsl/docs/moveToDir.md} +36 -34
  203. package/dist/help/dsl/docs/mutate.mixed.md +34 -0
  204. package/dist/help/dsl/docs/mutation.shared.md +55 -0
  205. package/dist/help/dsl/docs/patterns.md +3 -12
  206. package/dist/help/dsl/docs/qr.md +12 -6
  207. package/dist/help/dsl/docs/quick-map.md +36 -24
  208. package/dist/help/dsl/docs/recipe.file-layout.md +10 -10
  209. package/dist/help/dsl/docs/recipe.import-boundary.md +92 -0
  210. package/dist/help/dsl/docs/recipe.safe-artifact-probing.md +68 -0
  211. package/dist/help/dsl/docs/recipe.unfamiliar-area.md +64 -0
  212. package/dist/help/dsl/docs/recipes.md +20 -0
  213. package/dist/help/dsl/docs/rename.md +19 -27
  214. package/dist/help/dsl/docs/renameFile.md +36 -0
  215. package/dist/help/dsl/docs/rules.md +26 -0
  216. package/dist/help/dsl/full.md +175 -340
  217. package/dist/help/dsl/help-index.md +48 -43
  218. package/dist/help/dsl/snippets/agents.md +2 -2
  219. package/dist/help/dsl/tokens/qr.inline.examples.md +1 -1
  220. package/dist/help/dsl/topics/basics.md +1 -1
  221. package/dist/help/dsl/topics/config-setup.import-normalize.md +65 -65
  222. package/dist/help/dsl/topics/config-setup.import-rules.md +6 -5
  223. package/dist/help/dsl/topics/first-setup.md +6 -5
  224. package/dist/help/dsl/topics/help-protocol.md +4 -3
  225. package/dist/help/dsl/topics/import.base.md +36 -0
  226. package/dist/help/dsl/topics/import.rebase.md +83 -0
  227. package/dist/help/dsl/topics/inspect.aliasCandidates.md +37 -0
  228. package/dist/help/dsl/topics/inspect.code.md +1 -7
  229. package/dist/help/dsl/topics/inspect.file.md +10 -19
  230. package/dist/help/dsl/topics/inspect.graph.md +3 -17
  231. package/dist/help/dsl/topics/{inspect.md → inspect.shared.md} +13 -12
  232. package/dist/help/dsl/topics/modulePlan.md +21 -26
  233. package/dist/help/dsl/topics/move.md +17 -18
  234. package/dist/help/{docs/file.move.md → dsl/topics/moveToDir.md} +33 -35
  235. package/dist/help/dsl/topics/mutate.mixed.md +32 -0
  236. package/dist/help/dsl/topics/mutation.shared.md +53 -0
  237. package/dist/help/dsl/topics/patterns.md +3 -12
  238. package/dist/help/dsl/topics/qr.md +12 -6
  239. package/dist/help/dsl/topics/quick-map.md +36 -24
  240. package/dist/help/dsl/topics/recipe.file-layout.md +10 -10
  241. package/dist/help/dsl/topics/recipe.import-boundary.md +90 -0
  242. package/dist/help/dsl/topics/recipe.safe-artifact-probing.md +66 -0
  243. package/dist/help/dsl/topics/recipe.unfamiliar-area.md +62 -0
  244. package/dist/help/dsl/topics/recipes.md +18 -0
  245. package/dist/help/dsl/topics/rename.md +15 -15
  246. package/dist/help/dsl/topics/renameFile.md +34 -0
  247. package/dist/help/dsl/topics/rules.md +24 -0
  248. package/dist/help/full.md +175 -340
  249. package/dist/help/help-index.md +48 -43
  250. package/dist/help/help-meta.json +98 -48
  251. package/dist/help/index.md +52 -20
  252. package/dist/help/snippets/agents.md +2 -2
  253. package/dist/help/tokens/qr.inline.examples.md +1 -1
  254. package/dist/help/topics/basics.md +1 -1
  255. package/dist/help/topics/config-setup.import-normalize.md +65 -65
  256. package/dist/help/topics/config-setup.import-rules.md +6 -5
  257. package/dist/help/topics/first-setup.md +6 -5
  258. package/dist/help/topics/help-protocol.md +4 -3
  259. package/dist/help/topics/import.base.md +36 -0
  260. package/dist/help/topics/import.rebase.md +83 -0
  261. package/dist/help/topics/inspect.aliasCandidates.md +37 -0
  262. package/dist/help/topics/inspect.code.md +1 -7
  263. package/dist/help/topics/inspect.file.md +10 -19
  264. package/dist/help/topics/inspect.graph.md +3 -17
  265. package/dist/help/topics/{inspect.md → inspect.shared.md} +13 -12
  266. package/dist/help/topics/modulePlan.md +21 -26
  267. package/dist/help/topics/move.md +17 -18
  268. package/dist/help/{dsl/docs/file.move.md → topics/moveToDir.md} +33 -35
  269. package/dist/help/topics/mutate.mixed.md +32 -0
  270. package/dist/help/topics/mutation.shared.md +53 -0
  271. package/dist/help/topics/patterns.md +3 -12
  272. package/dist/help/topics/qr.md +12 -6
  273. package/dist/help/topics/quick-map.md +36 -24
  274. package/dist/help/topics/recipe.file-layout.md +10 -10
  275. package/dist/help/topics/recipe.import-boundary.md +90 -0
  276. package/dist/help/topics/recipe.safe-artifact-probing.md +66 -0
  277. package/dist/help/topics/recipe.unfamiliar-area.md +62 -0
  278. package/dist/help/topics/recipes.md +18 -0
  279. package/dist/help/topics/rename.md +15 -15
  280. package/dist/help/topics/renameFile.md +34 -0
  281. package/dist/help/topics/rules.md +24 -0
  282. package/dist/host/capabilities.js +56 -1
  283. package/dist/imports/standalone-import-analysis.js +602 -0
  284. package/dist/imports/standalone-import-model.js +2 -0
  285. package/dist/imports/standalone-import-process.js +66 -0
  286. package/dist/imports/standalone-import-worker.js +27 -0
  287. package/dist/imports/standalone-ts-project.js +147 -0
  288. package/dist/inspect/inspect-duplicates-service.js +526 -0
  289. package/dist/inspect/inspect-reverse-module-closure.js +338 -0
  290. package/dist/inspect/inspect-source-ranges.js +82 -0
  291. package/dist/inspect/inspect-source-shape.js +649 -0
  292. package/dist/inspect/standalone-inspect-analysis.js +319 -0
  293. package/dist/inspect/standalone-inspect-model.js +9 -0
  294. package/dist/inspect/standalone-inspect-process.js +55 -0
  295. package/dist/inspect/standalone-inspect-usages.js +274 -0
  296. package/dist/inspect/standalone-inspect-worker.js +13 -0
  297. package/dist/metrics/central-metrics.js +101 -2
  298. package/dist/mutation/concrete-edit-plan.js +157 -0
  299. package/dist/mutation/exports-star-collapse-preview.js +361 -0
  300. package/dist/mutation/exports-star-expand-apply.js +373 -0
  301. package/dist/mutation/exports-star-expand-preview.js +807 -0
  302. package/dist/mutation/file-impact-scan.js +182 -0
  303. package/dist/mutation/file-mutation-discovery.js +674 -0
  304. package/dist/mutation/file-mutation-eta.js +99 -0
  305. package/dist/mutation/file-mutation-standalone-apply.js +584 -0
  306. package/dist/mutation/file-mutation-standalone-planner.js +500 -0
  307. package/dist/mutation/file-mutation-tsserver-session.js +473 -0
  308. package/dist/mutation/mutation-estimate.js +45 -0
  309. package/dist/mutation/mutation-plan.js +467 -0
  310. package/dist/mutation/object-mutation-foundation.js +2 -0
  311. package/dist/mutation/object-mutation-partition.js +148 -0
  312. package/dist/mutation/object-pack-semantic-apply.js +507 -0
  313. package/dist/mutation/object-pack-semantic-preview.js +984 -0
  314. package/dist/mutation/object-unpack-semantic-preview.js +993 -0
  315. package/dist/mutation/package-manifest-impact.js +176 -0
  316. package/dist/mutation/rename-owner-worker-child.js +37 -0
  317. package/dist/mutation/rename-owner-worker.js +122 -0
  318. package/dist/mutation/runtime-cycle-query.js +66 -0
  319. package/dist/mutation/semantic-execution-progress.js +63 -0
  320. package/dist/mutation/semantic-export-index.js +474 -0
  321. package/dist/mutation/semantic-impact-scan.js +434 -0
  322. package/dist/mutation/semantic-model.js +2 -0
  323. package/dist/mutation/semantic-move-best-effort-planner.js +209 -0
  324. package/dist/mutation/semantic-move-config-worker-child.js +61 -0
  325. package/dist/mutation/semantic-move-config-worker.js +449 -0
  326. package/dist/mutation/semantic-move-declarations.js +94 -0
  327. package/dist/mutation/semantic-move-metrics.js +119 -0
  328. package/dist/mutation/semantic-move-model.js +2 -0
  329. package/dist/mutation/semantic-move-owner-authority.js +122 -0
  330. package/dist/mutation/semantic-move-owner-candidates.js +300 -0
  331. package/dist/mutation/semantic-move-owner-divergence-harness.js +474 -0
  332. package/dist/mutation/semantic-move-owner-divergence-runner.js +162 -0
  333. package/dist/mutation/semantic-move-plan-hash.js +56 -0
  334. package/dist/mutation/semantic-move-policy.js +360 -0
  335. package/dist/mutation/semantic-move-process.js +218 -0
  336. package/dist/mutation/semantic-move-provider-diagnostics.js +27 -0
  337. package/dist/mutation/semantic-move-standalone-engine.js +919 -0
  338. package/dist/mutation/semantic-move-standalone-planner.js +1553 -0
  339. package/dist/mutation/semantic-move-transaction.js +639 -0
  340. package/dist/mutation/semantic-mutation-engine.js +478 -0
  341. package/dist/mutation/semantic-mutation-runtime.js +521 -0
  342. package/dist/mutation/semantic-planner-retry.js +26 -0
  343. package/dist/mutation/semantic-program-roots.js +69 -0
  344. package/dist/mutation/semantic-rename-commonjs.js +229 -0
  345. package/dist/mutation/semantic-rename-config-worker-child.js +46 -0
  346. package/dist/mutation/semantic-rename-config-worker.js +498 -0
  347. package/dist/mutation/semantic-rename-locations.js +192 -0
  348. package/dist/mutation/semantic-rename-model.js +2 -0
  349. package/dist/mutation/semantic-rename-process.js +210 -0
  350. package/dist/mutation/semantic-rename-standalone-engine.js +302 -0
  351. package/dist/mutation/semantic-rename-standalone-planner.js +567 -0
  352. package/dist/mutation/semantic-rename-transaction.js +333 -0
  353. package/dist/mutation/semantic-unused-import-cleanup.js +248 -0
  354. package/dist/mutation/semantic-worker-retry.js +40 -0
  355. package/dist/mutation/semantic-workspace.js +804 -0
  356. package/dist/mutation/targeted-import-canonicalizer.js +359 -0
  357. package/dist/observability/config.js +206 -1
  358. package/dist/observability/context.js +59 -1
  359. package/dist/observability/failure-snapshot.js +124 -2
  360. package/dist/observability/recent.js +63 -2
  361. package/dist/payloads/read-stdin-json.js +212 -1
  362. package/dist/rg-wrapper/core.js +714 -6
  363. package/dist/rg-wrapper/options.js +125 -1
  364. package/dist/rtk-wrapper/core.js +144 -2
  365. package/dist/rtk-wrapper/git-safety.js +203 -0
  366. package/dist/rtk-wrapper/output-adapter.js +106 -0
  367. package/dist/runtime/buffered-process.js +114 -0
  368. package/dist/runtime/bundled-node.js +97 -1
  369. package/dist/runtime/command-lifecycle.js +2 -0
  370. package/dist/runtime/input-source.js +238 -1
  371. package/dist/runtime/node-cli-identity.js +37 -0
  372. package/dist/runtime/run-command.js +191 -1
  373. package/dist/selectors/parse-entities.js +84 -1
  374. package/dist/semantic/semantic-context-pool.js +830 -0
  375. package/dist/semantic/semantic-context-provider.js +416 -0
  376. package/dist/semantic/semantic-resident-admission.js +38 -0
  377. package/dist/semantic/semantic-worker-child.js +40 -0
  378. package/dist/semantic/semantic-worker-manager.js +460 -0
  379. package/dist/semantic/semantic-worker-protocol.js +2 -0
  380. package/dist/semantic/semantic-worker-runtime.js +38 -0
  381. package/dist/semantic/workspace-semantic-context-pools.js +136 -0
  382. package/dist/session/client.js +359 -1
  383. package/dist/session/daemon-state.js +185 -2
  384. package/dist/session/external-tool-coordinator.js +88 -0
  385. package/dist/session/external-tool-request.js +52 -0
  386. package/dist/session/lane-owner.js +116 -0
  387. package/dist/session/paths.js +71 -1
  388. package/dist/session/runtime-lifecycle.js +225 -0
  389. package/dist/session/runtime-shutdown.js +95 -0
  390. package/dist/session/server.js +1194 -7
  391. package/dist/session/session-health.js +27 -0
  392. package/dist/shared/agent-text.js +29 -1
  393. package/dist/shared/errors.js +496 -30
  394. package/dist/shared/event-loop.js +6 -1
  395. package/dist/shared/hints.js +37 -1
  396. package/dist/shared/metrics.js +43 -1
  397. package/dist/shared/presentation.js +69 -4
  398. package/dist/shared/stdin-examples.js +77 -1
  399. package/dist/shared/stdout.js +6 -2
  400. package/dist/shared/types.js +23 -1
  401. package/dist/tool-runtime/runtime-tools.js +120 -1
  402. package/dist/topology/availability.js +663 -0
  403. package/dist/topology/cache.js +130 -0
  404. package/dist/topology/candidates.js +372 -0
  405. package/dist/topology/core.js +903 -0
  406. package/dist/topology/dependency-snapshot.js +189 -0
  407. package/dist/topology/model.js +2 -0
  408. package/dist/topology/scope.js +100 -0
  409. package/dist/topology/ts-oracle-batch.js +529 -0
  410. package/dist/topology/ts-oracle-host.js +69 -0
  411. package/dist/topology/ts-oracle-model.js +2 -0
  412. package/dist/topology/ts-oracle.js +224 -0
  413. package/dist/topology/tsconfig-loader.js +105 -0
  414. package/dist/topology/workspace-project-index.js +542 -0
  415. package/dist/tracing/config.js +192 -2
  416. package/dist/tracing/failure-summary.js +100 -0
  417. package/dist/tracing/trace.js +318 -5
  418. package/dist/tsc-wrapper/core.js +697 -0
  419. package/dist/workers/control-plane/aib-control-plane-worker.cjs +32 -32
  420. package/dist/workers/control-plane/client-config.default.json +3 -3
  421. package/dist/workers/lexical-worker-child.js +27 -0
  422. package/dist/workers/lexical-worker-manager.js +394 -0
  423. package/dist/workers/lexical-worker-protocol.js +2 -0
  424. package/dist/workers/lexical-worker-runtime.js +25 -0
  425. package/dist/workers/owned-one-shot-process.js +115 -0
  426. package/dist/workers/product-storage.js +23 -1
  427. package/dist/workers/registry.js +241 -1
  428. package/package.json +8 -13
  429. package/scripts/postinstall.cjs +29 -29
  430. package/scripts/provision-runtime.cjs +411 -459
  431. package/dist/client/http-client.js +0 -1
  432. package/dist/client/transport-options.js +0 -1
  433. package/dist/client/websocket-client.js +0 -1
  434. package/dist/commands/entity-resolution.js +0 -1
  435. package/dist/commands/file-command.js +0 -1
  436. package/dist/commands/host-command.js +0 -1
  437. package/dist/commands/inspect-symbol-query.js +0 -1
  438. package/dist/commands/list-instances.js +0 -1
  439. package/dist/commands/module-plan-command.js +0 -1
  440. package/dist/commands/move-command.js +0 -1
  441. package/dist/commands/move-to-file.js +0 -2
  442. package/dist/commands/ping.js +0 -1
  443. package/dist/commands/refactor-command.js +0 -1
  444. package/dist/commands/rename-command.js +0 -1
  445. package/dist/commands/runtime-command.js +0 -4
  446. package/dist/commands/runtime-info.js +0 -1
  447. package/dist/commands/validate-module-plan.js +0 -2
  448. package/dist/compatibility/policy.js +0 -1
  449. package/dist/config/auto-start-ide.js +0 -1
  450. package/dist/discovery/registry.js +0 -1
  451. package/dist/discovery/select-instance.js +0 -1
  452. package/dist/help/docs/file.rename.md +0 -35
  453. package/dist/help/docs/mutation.md +0 -60
  454. package/dist/help/docs/refactor.batch.md +0 -44
  455. package/dist/help/dsl/docs/file.rename.md +0 -35
  456. package/dist/help/dsl/docs/mutation.md +0 -60
  457. package/dist/help/dsl/docs/refactor.batch.md +0 -44
  458. package/dist/help/dsl/topics/file.rename.md +0 -33
  459. package/dist/help/dsl/topics/mutation.md +0 -58
  460. package/dist/help/dsl/topics/refactor.batch.md +0 -33
  461. package/dist/help/topics/file.rename.md +0 -33
  462. package/dist/help/topics/mutation.md +0 -58
  463. package/dist/help/topics/refactor.batch.md +0 -33
  464. package/dist/ide-launch/common.cjs +0 -162
  465. package/dist/managed-host/extension-vsix-resolver.js +0 -1
  466. package/dist/managed-host/manage-serve-web-host.cjs +0 -141
  467. package/dist/managed-host/serve-web-autostart.js +0 -1
  468. package/dist/managed-host/serve-web-host.cjs +0 -2115
  469. package/dist/runtime/managed-runtime-provisioning.js +0 -1
  470. package/dist/shared/diagnostic-catalog.js +0 -1
  471. package/dist/shared/diagnostics.js +0 -1
  472. package/dist/shared/operations.js +0 -1
  473. package/dist/shared/protocol.js +0 -1
  474. package/dist/shared/routes.js +0 -1
  475. package/extension/vscode-refactor-bridge-extension.vsix +0 -0
  476. package/runtimes/launcher/linux-x64/aib +0 -0
  477. package/runtimes/launcher/win-x64/aib.exe +0 -0
@@ -0,0 +1,1394 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.formatMutateResponseForReplay = exports.readCachedMutateExecution = void 0;
37
+ exports.runMutateCommand = runMutateCommand;
38
+ const fs = __importStar(require("node:fs"));
39
+ const path = __importStar(require("node:path"));
40
+ const agent_dx_1 = require("../agent-dx/agent-dx");
41
+ const agent_text_1 = require("../shared/agent-text");
42
+ const errors_1 = require("../shared/errors");
43
+ const mutate_dsl_1 = require("../dsl/mutate-dsl");
44
+ const central_metrics_1 = require("../metrics/central-metrics");
45
+ const mutate_domain_adapters_1 = require("./mutate-domain-adapters");
46
+ const mutate_execution_cache_1 = require("./mutate-execution-cache");
47
+ const mutate_preview_cache_1 = require("./mutate-preview-cache");
48
+ const mutation_execution_cache_1 = require("./mutation-execution-cache");
49
+ const mutation_estimate_1 = require("../mutation/mutation-estimate");
50
+ const mutate_output_values_1 = require("./mutate-output-values");
51
+ const mutate_child_execution_1 = require("./mutate-child-execution");
52
+ const mutate_execution_status_1 = require("./mutate-execution-status");
53
+ var mutate_execution_status_2 = require("./mutate-execution-status");
54
+ Object.defineProperty(exports, "readCachedMutateExecution", { enumerable: true, get: function () { return mutate_execution_status_2.readCachedMutateExecution; } });
55
+ const mutate_result_projection_1 = require("./mutate-result-projection");
56
+ const mutate_failure_output_1 = require("./mutate-failure-output");
57
+ const mutate_file_view_1 = require("./mutate-file-view");
58
+ const exports_star_command_1 = require("./exports-star-command");
59
+ const mutate_aggregate_output_1 = require("./mutate-aggregate-output");
60
+ const mutate_response_replay_1 = require("./mutate-response-replay");
61
+ var mutate_response_replay_2 = require("./mutate-response-replay");
62
+ Object.defineProperty(exports, "formatMutateResponseForReplay", { enumerable: true, get: function () { return mutate_response_replay_2.formatMutateResponseForReplay; } });
63
+ async function runMutateCommand(cwd, restArgs, rawPayload, options = {}, commandOptions = {}) {
64
+ const [action = "preview", ...actionArgs] = restArgs;
65
+ if (action === "help" || action === "--help") {
66
+ return mutateHelp();
67
+ }
68
+ if (action === "apply") {
69
+ const previewId = actionArgs[0];
70
+ if (!previewId || previewId.startsWith("--")) {
71
+ throw new errors_1.CliError("MUTATE_PREVIEW_ID_REQUIRED", "mutate apply expects a preview id.", {
72
+ usage: "aib mutate apply <previewId>"
73
+ });
74
+ }
75
+ return applyMutatePreview(cwd, previewId, options);
76
+ }
77
+ if (action !== "preview" && action !== "execute") {
78
+ throw new errors_1.CliError("UNKNOWN_MUTATE_COMMAND", `Unknown mutate command: ${action}`, {
79
+ availableCommands: ["preview", "apply", "execute", "help"]
80
+ });
81
+ }
82
+ const payload = normalizeMutatePayload(rawPayload);
83
+ const plan = (0, mutate_execution_status_1.buildMutatePlan)(cwd, `mutate.${action}`, payload.segments);
84
+ if (action === "preview") {
85
+ return previewMutate(cwd, payload, plan, options, commandOptions.semanticContextPool);
86
+ }
87
+ const preflightFailure = validateMutateIntentBeforeExecution(cwd, payload.segments, "mutate.execute");
88
+ if (preflightFailure) {
89
+ return withMutateMetricsAndText(cwd, preflightFailure, (0, mutate_aggregate_output_1.formatMutateFileLayoutValidationText)(cwd, preflightFailure));
90
+ }
91
+ if ((0, mutate_domain_adapters_1.isSingleModulePlanPayload)(payload)) {
92
+ return (0, mutate_domain_adapters_1.executeSingleModulePlanMutate)(cwd, payload.segments[0], options);
93
+ }
94
+ if ((0, mutate_domain_adapters_1.isSingleFilePayload)(payload)) {
95
+ return (0, mutate_domain_adapters_1.executeSingleFileMutate)(cwd, payload.segments[0], options);
96
+ }
97
+ return executeMutateWithStatus(cwd, payload.segments, plan, options);
98
+ }
99
+ async function previewMutate(cwd, payload, plan, options, semanticContextPool) {
100
+ const preflightFailure = validateMutateIntentBeforeExecution(cwd, payload.segments, "mutate.preview");
101
+ if (preflightFailure) {
102
+ const withDx = (0, agent_dx_1.applyAgentDxSignals)(cwd, preflightFailure, payload.agentDxSignals);
103
+ return withText(withDx, (0, mutate_aggregate_output_1.formatMutateFileLayoutValidationText)(cwd, withDx));
104
+ }
105
+ if (payload.segments.length > 0 && payload.segments.every((segment) => segment.kind === "exports.star")) {
106
+ return previewExportsStarMutateBatch(cwd, payload, plan, semanticContextPool);
107
+ }
108
+ const childSegments = [];
109
+ const responses = [];
110
+ let sawDeclarationRemove = false;
111
+ for (const segment of payload.segments) {
112
+ if (segment.kind === "imports.normalize" || segment.kind === "imports.rebase" || segment.kind === "declaration" || segment.kind === "exports.object" || segment.kind === "exports.star") {
113
+ const preparedSegment = prepareDeclarationPreviewSegment(segment, sawDeclarationRemove);
114
+ const response = await (0, mutate_domain_adapters_1.runMutateSegment)(cwd, preparedSegment, "preview", options);
115
+ responses.push(response);
116
+ if (isDeclarationRemoveSegment(segment)) {
117
+ sawDeclarationRemove = true;
118
+ }
119
+ if (response.ok === false && !shouldContinueAfterMutateSegmentFailure(segment, response, createDeclarationCleanupState(payload.segments))) {
120
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(payload.segments, responses, childSegments, responses.length - 1);
121
+ const failure = (0, mutate_output_values_1.compactObject)({
122
+ ok: false,
123
+ operation: "mutate.preview",
124
+ failedSegment: responses.length,
125
+ segments: summary,
126
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
127
+ filesWritten: [],
128
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
129
+ response,
130
+ next: "Fix failed group and rerun mutate preview."
131
+ });
132
+ const withDx = (0, agent_dx_1.applyAgentDxSignals)(cwd, failure, payload.agentDxSignals);
133
+ if (segment.kind === "exports.object") {
134
+ return withText(withDx, (0, mutate_failure_output_1.formatObjectPackFailureAsMutatePreviewText)(response));
135
+ }
136
+ return withText(withDx, (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, withDx));
137
+ }
138
+ const childId = shouldPersistChildPreviewId(preparedSegment) ? readChildPreviewId(segment, response) : null;
139
+ childSegments.push({
140
+ kind: String(segment.kind),
141
+ childId: childId ?? "",
142
+ response
143
+ });
144
+ }
145
+ else {
146
+ responses.push(buildCheapMutatePreviewResponse(cwd, segment));
147
+ }
148
+ }
149
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(payload.segments, responses, childSegments);
150
+ const aggregate = (0, mutate_result_projection_1.buildMutateAggregateModel)(summary);
151
+ if (isNoopImportsNormalizePreview(payload.segments, aggregate)) {
152
+ const noPolicy = hasNoPolicyImportsNormalize(aggregate);
153
+ const response = {
154
+ operation: "mutate.preview",
155
+ summary: noPolicy ? "no import normalization policy matched" : "no import normalization changes planned",
156
+ segments: summary,
157
+ aggregate,
158
+ next: noPolicy
159
+ ? "Add importNormalize config for this scope or rerun with an explicit to= target."
160
+ : "No action needed unless the scope or target style is wrong."
161
+ };
162
+ const withDx = (0, agent_dx_1.applyAgentDxSignals)(cwd, (0, mutate_file_view_1.attachMutateAggregateFilesView)(cwd, response), payload.agentDxSignals);
163
+ return withText(withDx, (0, mutate_response_replay_1.formatMutatePreviewAggregateText)(cwd, withDx));
164
+ }
165
+ if (isNoopImportsRebasePreview(payload.segments, aggregate)) {
166
+ const skipped = countImportRebaseSkipped(aggregate);
167
+ const response = {
168
+ operation: "mutate.preview",
169
+ summary: skipped > 0 ? `no import boundary changes planned; ${skipped} skipped` : "no import boundary changes planned",
170
+ segments: summary,
171
+ aggregate,
172
+ next: skipped > 0
173
+ ? "Review skipped imports; adjust scope/barrel/symbols and rerun if needed."
174
+ : "No action needed unless the scope/barrel/symbols are wrong."
175
+ };
176
+ const withDx = (0, agent_dx_1.applyAgentDxSignals)(cwd, (0, mutate_file_view_1.attachMutateAggregateFilesView)(cwd, response), payload.agentDxSignals);
177
+ return withText(withDx, (0, mutate_response_replay_1.formatMutatePreviewAggregateText)(cwd, withDx));
178
+ }
179
+ if (payload.segments.length === 1 && payload.segments[0]?.kind === "exports.object" && responses[0]?.applyAvailable === false) {
180
+ const response = {
181
+ ok: true,
182
+ operation: "mutate.preview",
183
+ summary: "object.unpack semantic preview ready; apply/execute disabled",
184
+ segments: summary,
185
+ aggregate,
186
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
187
+ filesWritten: [],
188
+ next: "Review object.unpack view evidence; apply/execute is not available yet."
189
+ };
190
+ const withDx = (0, agent_dx_1.applyAgentDxSignals)(cwd, (0, mutate_file_view_1.attachMutateAggregateFilesView)(cwd, response), payload.agentDxSignals);
191
+ return withText(withDx, (0, mutate_domain_adapters_1.formatTransparentMutateText)(cwd, "preview", undefined, payload.segments, responses, childSegments) ?? (0, mutate_response_replay_1.formatMutatePreviewAggregateText)(cwd, withDx));
192
+ }
193
+ const previewId = (0, mutate_preview_cache_1.buildMutatePreviewId)(payload);
194
+ const previewHash = (0, mutate_preview_cache_1.buildMutatePreviewHash)(payload, childSegments);
195
+ (0, mutate_preview_cache_1.writeMutatePreviewRecord)(cwd, {
196
+ previewId,
197
+ previewHash,
198
+ createdAt: new Date().toISOString(),
199
+ cwd,
200
+ normalizedPayload: payload,
201
+ plan,
202
+ segments: childSegments
203
+ });
204
+ const response = {
205
+ operation: "mutate.preview",
206
+ previewId,
207
+ summary: `${payload.segments.length} ${payload.segments.length === 1 ? "segment" : "segments"} ready`,
208
+ segments: summary,
209
+ aggregate,
210
+ next: `aib mutate apply ${previewId}`
211
+ };
212
+ const withDx = (0, agent_dx_1.applyAgentDxSignals)(cwd, (0, mutate_file_view_1.attachMutateAggregateFilesView)(cwd, response), payload.agentDxSignals);
213
+ return withText(withDx, (0, mutate_domain_adapters_1.formatTransparentMutateText)(cwd, "preview", previewId, payload.segments, responses, childSegments) ?? (0, mutate_response_replay_1.formatMutatePreviewAggregateText)(cwd, withDx));
214
+ }
215
+ async function previewExportsStarMutateBatch(cwd, payload, _plan, semanticContextPool) {
216
+ const responses = await (0, mutate_domain_adapters_1.runExportsStarMutatePreviewBatch)(cwd, payload.segments, semanticContextPool);
217
+ const previewId = responses.map((response) => (0, mutate_output_values_1.readString)(response.previewId)).find((value) => Boolean(value));
218
+ const childSegments = payload.segments.map((segment, index) => ({
219
+ kind: String(segment.kind),
220
+ childId: previewId ?? "",
221
+ response: responses[index]
222
+ }));
223
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(payload.segments, responses, childSegments);
224
+ const aggregate = (0, mutate_result_projection_1.buildMutateAggregateModel)(summary);
225
+ if (previewId) {
226
+ (0, mutate_preview_cache_1.writeMutatePreviewRecord)(cwd, {
227
+ previewId,
228
+ previewHash: (0, mutate_preview_cache_1.buildMutatePreviewHash)(payload, childSegments),
229
+ createdAt: new Date().toISOString(),
230
+ cwd,
231
+ normalizedPayload: payload,
232
+ segments: childSegments
233
+ });
234
+ }
235
+ const response = {
236
+ ok: true,
237
+ operation: "mutate.preview",
238
+ applyAvailable: Boolean(previewId),
239
+ ...(previewId ? { previewId } : {}),
240
+ summary: payload.segments.every((segment) => segment.operation === "collapse")
241
+ ? previewId ? "exports.star.collapse semantic preview ready" : "exports.star.collapse review evidence ready; no safe edits"
242
+ : previewId ? "exports.star.expand semantic preview ready"
243
+ : "exports.star.expand review evidence ready; no safe edits",
244
+ segments: summary,
245
+ aggregate,
246
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
247
+ filesWritten: [],
248
+ next: previewId ? `aib mutate apply ${previewId}` : payload.segments.every((segment) => segment.operation === "collapse")
249
+ ? "Review exports.star.collapse view evidence; apply/execute is not available yet."
250
+ : "Review retained exports.star.expand evidence; no safe edits are available to apply."
251
+ };
252
+ const withDx = (0, agent_dx_1.applyAgentDxSignals)(cwd, response, payload.agentDxSignals);
253
+ return withText(withDx, (0, mutate_domain_adapters_1.formatTransparentMutateText)(cwd, "preview", undefined, payload.segments, responses, childSegments) ?? (0, mutate_response_replay_1.formatMutatePreviewAggregateText)(cwd, withDx));
254
+ }
255
+ function isNoopImportsNormalizePreview(segments, aggregate) {
256
+ if (segments.length === 0 || !segments.every((segment) => segment.kind === "imports.normalize")) {
257
+ return false;
258
+ }
259
+ const operations = (0, mutate_output_values_1.isObject)(aggregate.operations) ? aggregate.operations : {};
260
+ const normalizations = (0, mutate_output_values_1.readObjectArray)(operations.importNormalizations);
261
+ return normalizations.length > 0 && normalizations.every((item) => ((0, mutate_output_values_1.readNumber)(item.edits) ?? 0) === 0);
262
+ }
263
+ function hasNoPolicyImportsNormalize(aggregate) {
264
+ const operations = (0, mutate_output_values_1.isObject)(aggregate.operations) ? aggregate.operations : {};
265
+ return (0, mutate_output_values_1.readObjectArray)(operations.importNormalizations).some((item) => item.noPolicy === true);
266
+ }
267
+ function isNoopImportsRebasePreview(segments, aggregate) {
268
+ if (segments.length === 0 || !segments.every((segment) => segment.kind === "imports.rebase")) {
269
+ return false;
270
+ }
271
+ const operations = (0, mutate_output_values_1.isObject)(aggregate.operations) ? aggregate.operations : {};
272
+ const importRebases = (0, mutate_output_values_1.readObjectArray)(operations.importRebases);
273
+ return importRebases.length > 0 && importRebases.every((item) => ((0, mutate_output_values_1.readNumber)(item.edits) ?? 0) === 0 && ((0, mutate_output_values_1.readNumber)(item.filesChanged) ?? 0) === 0);
274
+ }
275
+ function countImportRebaseSkipped(aggregate) {
276
+ const operations = (0, mutate_output_values_1.isObject)(aggregate.operations) ? aggregate.operations : {};
277
+ return (0, mutate_output_values_1.readObjectArray)(operations.importRebases)
278
+ .reduce((count, item) => count + ((0, mutate_output_values_1.readNumber)(item.skippedCount) ?? 0), 0);
279
+ }
280
+ async function applyMutatePreview(cwd, previewId, options) {
281
+ const record = (0, mutate_preview_cache_1.readMutatePreviewRecord)(cwd, previewId);
282
+ if (record.segments.length > 0 && record.segments.every((segment) => segment.kind === "exports.star" && segment.childId === previewId)) {
283
+ return applyMutateSegmentAsResponse(cwd, record.segments[0], options);
284
+ }
285
+ if (record.segments.length === 1 && record.segments[0]?.kind === "modulePlan") {
286
+ return (0, mutate_domain_adapters_1.applySingleModulePlanMutate)(cwd, previewId, record.segments[0], options);
287
+ }
288
+ if (record.segments.length === 1 && record.segments[0]?.kind === "file") {
289
+ return (0, mutate_domain_adapters_1.applySingleFileMutate)(cwd, previewId, record.segments[0], options);
290
+ }
291
+ const intentSegments = readMutateRecordIntentSegments(record);
292
+ const plan = (0, mutate_output_values_1.isObject)(record.plan)
293
+ ? record.plan
294
+ : (0, mutate_execution_status_1.buildMutatePlan)(cwd, "mutate.apply", intentSegments);
295
+ const preflightFailure = validateMutateIntentBeforeExecution(cwd, intentSegments, "mutate.apply", previewId);
296
+ if (preflightFailure) {
297
+ return withMutateMetricsAndText(cwd, preflightFailure, (0, mutate_aggregate_output_1.formatMutateFileLayoutValidationText)(cwd, preflightFailure));
298
+ }
299
+ const syncWaitMs = (0, mutate_execution_status_1.readMutateSyncWaitMs)();
300
+ if (syncWaitMs > 0) {
301
+ return applyMutatePreviewWithStatus(cwd, previewId, intentSegments, record.segments, plan, options, syncWaitMs);
302
+ }
303
+ const responses = [];
304
+ const successfulRemoveSelectors = createDeclarationCleanupState(intentSegments);
305
+ for (const [index, segment] of intentSegments.entries()) {
306
+ const previewSegment = record.segments[index];
307
+ const preparedSegment = prepareDeclarationExecutionSegment(segment, successfulRemoveSelectors);
308
+ const initialResponse = previewSegment && previewSegment.kind === segment.kind && previewSegment.childId
309
+ ? await applyMutateSegmentAsResponse(cwd, previewSegment, options)
310
+ : await runMutateSegmentAsResponse(cwd, preparedSegment, "execute", options);
311
+ const response = await (0, mutate_child_execution_1.awaitNestedFileMutationResponse)(cwd, initialResponse);
312
+ responses.push(response);
313
+ updateSuccessfulDeclarationRemoveSelectors(successfulRemoveSelectors, segment, response);
314
+ if (response.ok === false && !shouldContinueAfterMutateSegmentFailure(segment, response, successfulRemoveSelectors)) {
315
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(intentSegments, responses, record.segments, index);
316
+ const failure = {
317
+ ok: false,
318
+ operation: "mutate.apply",
319
+ previewId,
320
+ failedSegment: index + 1,
321
+ segments: summary,
322
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
323
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
324
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
325
+ response,
326
+ next: "Fix failed group and rerun remaining mutate intent."
327
+ };
328
+ return withMutateMetricsAndText(cwd, failure, (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, failure));
329
+ }
330
+ }
331
+ const manualExtractionIndex = findFirstNonBlockingManualExtractionFailure(intentSegments, responses);
332
+ if (manualExtractionIndex >= 0) {
333
+ return buildMutateManualExtractionAggregateResponse(cwd, "mutate.apply", intentSegments, responses, record.segments, manualExtractionIndex, previewId);
334
+ }
335
+ const partialDeclarationIndex = findFirstPartialDeclarationCleanupFailure(intentSegments, responses);
336
+ if (partialDeclarationIndex >= 0) {
337
+ return buildMutatePartialDeclarationCleanupAggregateResponse(cwd, "mutate.apply", intentSegments, responses, record.segments, previewId);
338
+ }
339
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(intentSegments, responses, record.segments);
340
+ const response = {
341
+ operation: "mutate.apply",
342
+ previewId,
343
+ summary: `${responses.length} ${responses.length === 1 ? "segment" : "segments"} applied`,
344
+ segments: summary,
345
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
346
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
347
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses)
348
+ };
349
+ return withMutateMetricsAndText(cwd, response, (0, mutate_domain_adapters_1.formatTransparentAppliedMutateText)(cwd, "apply", previewId, record.segments, responses) ?? (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, response));
350
+ }
351
+ async function applyMutatePreviewWithStatus(cwd, previewId, intentSegments, previewSegments, plan, options, syncWaitMs) {
352
+ const executionId = (0, mutate_execution_cache_1.buildMutateExecutionId)();
353
+ const status = (0, mutate_execution_cache_1.createMutateExecutionStatus)(cwd, executionId, "mutate.apply", (0, mutate_execution_status_1.buildApplyExecutionGroups)(intentSegments, previewSegments, plan), (0, mutate_execution_status_1.selectMutatePollingPolicy)(intentSegments));
354
+ status.plan = plan;
355
+ status.estimatedDurationMs = (0, mutation_estimate_1.estimateMutationPlanDurationMs)(plan);
356
+ (0, mutate_execution_cache_1.writeMutateExecutionStatus)(cwd, status);
357
+ const startedAtMs = Date.now();
358
+ const jobPromise = (0, mutate_execution_status_1.startMutateBackgroundJob)(async () => {
359
+ try {
360
+ await (0, mutate_execution_status_1.maybeDeferMutateBackgroundWorkForStatus)(syncWaitMs, intentSegments);
361
+ const result = await applyMutatePreviewRows(cwd, previewId, intentSegments, previewSegments, options, status);
362
+ status.status = result.ok === false ? "failed" : "completed";
363
+ status.phase = "completed";
364
+ status.result = result;
365
+ (0, mutate_execution_status_1.mergeMutateStatusFiles)(status, result);
366
+ if (result.ok === false) {
367
+ status.error = (0, mutate_output_values_1.readString)(result.code) ?? "MUTATE_APPLY_FAILED";
368
+ }
369
+ else {
370
+ delete status.error;
371
+ }
372
+ (0, mutate_execution_status_1.finalizeMutateStatusRows)(status);
373
+ (0, mutate_execution_cache_1.writeMutateExecutionStatus)(cwd, status);
374
+ return result;
375
+ }
376
+ catch (error) {
377
+ status.status = "failed";
378
+ status.phase = "completed";
379
+ status.error = error instanceof Error ? error.message : String(error);
380
+ (0, mutate_execution_status_1.finalizeMutateStatusRows)(status);
381
+ (0, mutate_execution_cache_1.writeMutateExecutionStatus)(cwd, status);
382
+ throw error;
383
+ }
384
+ });
385
+ const waitResult = await (0, mutation_execution_cache_1.waitForMutationDeadline)(jobPromise, syncWaitMs);
386
+ if (waitResult.status === "result") {
387
+ return waitResult.result;
388
+ }
389
+ jobPromise.catch(() => undefined);
390
+ return (0, mutate_execution_status_1.buildMutateStillRunningResponse)(cwd, executionId, "mutate.apply", (0, mutate_execution_status_1.estimateMutateDurationMs)(status), Date.now() - startedAtMs, syncWaitMs);
391
+ }
392
+ async function applyMutatePreviewRows(cwd, previewId, intentSegments, previewSegments, options, status) {
393
+ const responses = [];
394
+ const successfulRemoveSelectors = createDeclarationCleanupState(intentSegments);
395
+ for (const [index, segment] of intentSegments.entries()) {
396
+ (0, mutate_execution_status_1.markMutateGroupRunning)(cwd, status, index);
397
+ const previewSegment = previewSegments[index];
398
+ const preparedSegment = prepareDeclarationExecutionSegment(segment, successfulRemoveSelectors);
399
+ const initialResponse = previewSegment && previewSegment.kind === segment.kind && previewSegment.childId
400
+ ? await applyMutateSegmentAsResponse(cwd, previewSegment, withMutateSemanticRenameEvidence(options, cwd, status, index))
401
+ : await runMutateSegmentAsResponse(cwd, preparedSegment, "execute", withMutateSemanticRenameEvidence(options, cwd, status, index));
402
+ const response = await (0, mutate_child_execution_1.awaitNestedFileMutationResponse)(cwd, initialResponse, {
403
+ onDelegated: (childExecutionId) => (0, mutate_execution_status_1.markMutateGroupDelegated)(cwd, status, index, childExecutionId)
404
+ });
405
+ responses.push(response);
406
+ updateSuccessfulDeclarationRemoveSelectors(successfulRemoveSelectors, segment, response);
407
+ (0, mutate_execution_status_1.markMutateGroupFinished)(cwd, status, index, response);
408
+ if (response.ok === false && !shouldContinueAfterMutateSegmentFailure(segment, response, successfulRemoveSelectors)) {
409
+ (0, mutate_execution_status_1.markMutateGroupsNotRun)(cwd, status, index + 1);
410
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(intentSegments, responses, previewSegments, index);
411
+ const failure = {
412
+ ok: false,
413
+ operation: "mutate.apply",
414
+ previewId,
415
+ failedSegment: index + 1,
416
+ segments: summary,
417
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
418
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
419
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
420
+ response,
421
+ next: "Fix failed group and rerun remaining mutate intent."
422
+ };
423
+ return withMutateMetricsAndText(cwd, failure, (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, failure));
424
+ }
425
+ }
426
+ const manualExtractionIndex = findFirstNonBlockingManualExtractionFailure(intentSegments, responses);
427
+ if (manualExtractionIndex >= 0) {
428
+ return buildMutateManualExtractionAggregateResponse(cwd, "mutate.apply", intentSegments, responses, previewSegments, manualExtractionIndex, previewId);
429
+ }
430
+ const partialDeclarationIndex = findFirstPartialDeclarationCleanupFailure(intentSegments, responses);
431
+ if (partialDeclarationIndex >= 0) {
432
+ return buildMutatePartialDeclarationCleanupAggregateResponse(cwd, "mutate.apply", intentSegments, responses, previewSegments, previewId);
433
+ }
434
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(intentSegments, responses, previewSegments);
435
+ const response = {
436
+ operation: "mutate.apply",
437
+ previewId,
438
+ summary: `${responses.length} ${responses.length === 1 ? "segment" : "segments"} applied`,
439
+ segments: summary,
440
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
441
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
442
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses)
443
+ };
444
+ return withMutateMetricsAndText(cwd, response, (0, mutate_domain_adapters_1.formatTransparentAppliedMutateText)(cwd, "apply", previewId, previewSegments, responses) ?? (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, response));
445
+ }
446
+ function readMutateRecordIntentSegments(record) {
447
+ const segments = (0, mutate_output_values_1.isObject)(record.normalizedPayload) && Array.isArray(record.normalizedPayload.segments)
448
+ ? record.normalizedPayload.segments.filter(mutate_output_values_1.isObject)
449
+ : [];
450
+ if (segments.length > 0) {
451
+ return segments;
452
+ }
453
+ return record.segments.map((segment) => ({
454
+ kind: segment.kind
455
+ }));
456
+ }
457
+ async function executeMutateSegments(cwd, segments, action, options) {
458
+ const responses = [];
459
+ const successfulRemoveSelectors = createDeclarationCleanupState(segments);
460
+ for (const [index, segment] of segments.entries()) {
461
+ const preparedSegment = prepareDeclarationExecutionSegment(segment, successfulRemoveSelectors);
462
+ const initialResponse = await runMutateSegmentAsResponse(cwd, preparedSegment, action, options);
463
+ const response = await (0, mutate_child_execution_1.awaitNestedFileMutationResponse)(cwd, initialResponse);
464
+ responses.push(response);
465
+ updateSuccessfulDeclarationRemoveSelectors(successfulRemoveSelectors, segment, response);
466
+ if (response.ok === false && !shouldContinueAfterMutateSegmentFailure(segment, response, successfulRemoveSelectors)) {
467
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(segments, responses, [], index);
468
+ const failure = {
469
+ ok: false,
470
+ operation: "mutate.execute",
471
+ failedSegment: index + 1,
472
+ segments: summary,
473
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
474
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
475
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
476
+ response,
477
+ next: "Fix failed group and rerun remaining mutate intent."
478
+ };
479
+ return withMutateMetricsAndText(cwd, failure, (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, failure));
480
+ }
481
+ }
482
+ const manualExtractionIndex = findFirstNonBlockingManualExtractionFailure(segments, responses);
483
+ if (manualExtractionIndex >= 0) {
484
+ return buildMutateManualExtractionAggregateResponse(cwd, "mutate.execute", segments, responses, [], manualExtractionIndex);
485
+ }
486
+ const partialDeclarationIndex = findFirstPartialDeclarationCleanupFailure(segments, responses);
487
+ if (partialDeclarationIndex >= 0) {
488
+ return buildMutatePartialDeclarationCleanupAggregateResponse(cwd, "mutate.execute", segments, responses, []);
489
+ }
490
+ const presentedResponses = segments.length > 0 && segments.every((segment) => segment.kind === "exports.star")
491
+ ? (0, exports_star_command_1.consolidateExportsStarWriteViews)(cwd, responses)
492
+ : responses;
493
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(segments, presentedResponses);
494
+ const response = {
495
+ operation: "mutate.execute",
496
+ summary: `${responses.length} ${responses.length === 1 ? "segment" : "segments"} executed`,
497
+ segments: summary,
498
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
499
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
500
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses)
501
+ };
502
+ return withMutateMetricsAndText(cwd, response, (0, mutate_domain_adapters_1.formatTransparentMutateText)(cwd, "execute", undefined, segments, presentedResponses) ?? (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, response));
503
+ }
504
+ async function executeMutateWithStatus(cwd, segments, plan, options) {
505
+ const syncWaitMs = (0, mutate_execution_status_1.readMutateSyncWaitMs)();
506
+ if (syncWaitMs <= 0) {
507
+ return executeMutateSegments(cwd, segments, "execute", options);
508
+ }
509
+ const executionId = (0, mutate_execution_cache_1.buildMutateExecutionId)();
510
+ const status = (0, mutate_execution_cache_1.createMutateExecutionStatus)(cwd, executionId, "mutate.execute", (0, mutate_execution_status_1.buildExecuteExecutionGroups)(segments, plan), (0, mutate_execution_status_1.selectMutatePollingPolicy)(segments));
511
+ status.plan = plan;
512
+ (0, mutate_execution_cache_1.writeMutateExecutionStatus)(cwd, status);
513
+ const startedAtMs = Date.now();
514
+ const jobPromise = (0, mutate_execution_status_1.startMutateBackgroundJob)(async () => {
515
+ try {
516
+ await (0, mutate_execution_status_1.maybeDeferMutateBackgroundWorkForStatus)(syncWaitMs, segments);
517
+ const result = await executeMutateSegmentsWithStatus(cwd, segments, options, status);
518
+ status.status = result.ok === false ? "failed" : "completed";
519
+ status.phase = "completed";
520
+ status.result = result;
521
+ (0, mutate_execution_status_1.mergeMutateStatusFiles)(status, result);
522
+ if (result.ok === false) {
523
+ status.error = (0, mutate_output_values_1.readString)(result.code) ?? "MUTATE_EXECUTE_FAILED";
524
+ }
525
+ else {
526
+ delete status.error;
527
+ }
528
+ (0, mutate_execution_status_1.finalizeMutateStatusRows)(status);
529
+ (0, mutate_execution_cache_1.writeMutateExecutionStatus)(cwd, status);
530
+ return result;
531
+ }
532
+ catch (error) {
533
+ status.status = "failed";
534
+ status.phase = "completed";
535
+ status.error = error instanceof Error ? error.message : String(error);
536
+ (0, mutate_execution_status_1.finalizeMutateStatusRows)(status);
537
+ (0, mutate_execution_cache_1.writeMutateExecutionStatus)(cwd, status);
538
+ throw error;
539
+ }
540
+ });
541
+ const waitResult = await (0, mutation_execution_cache_1.waitForMutationDeadline)(jobPromise, syncWaitMs);
542
+ if (waitResult.status === "result") {
543
+ return waitResult.result;
544
+ }
545
+ jobPromise.catch(() => undefined);
546
+ return (0, mutate_execution_status_1.buildMutateStillRunningResponse)(cwd, executionId, "mutate.execute", (0, mutate_execution_status_1.estimateMutateDurationMs)(status), Date.now() - startedAtMs, syncWaitMs);
547
+ }
548
+ async function executeMutateSegmentsWithStatus(cwd, segments, options, status) {
549
+ await (0, mutate_execution_status_1.maybeDelayMutateForTest)();
550
+ const responses = [];
551
+ const successfulRemoveSelectors = createDeclarationCleanupState(segments);
552
+ for (const [index, segment] of segments.entries()) {
553
+ (0, mutate_execution_status_1.markMutateGroupRunning)(cwd, status, index);
554
+ const preparedSegment = prepareDeclarationExecutionSegment(segment, successfulRemoveSelectors);
555
+ const initialResponse = await runMutateSegmentAsResponse(cwd, preparedSegment, "execute", withMutateSemanticRenameEvidence(options, cwd, status, index));
556
+ const response = await (0, mutate_child_execution_1.awaitNestedFileMutationResponse)(cwd, initialResponse, {
557
+ onDelegated: (childExecutionId) => (0, mutate_execution_status_1.markMutateGroupDelegated)(cwd, status, index, childExecutionId)
558
+ });
559
+ responses.push(response);
560
+ updateSuccessfulDeclarationRemoveSelectors(successfulRemoveSelectors, segment, response);
561
+ (0, mutate_execution_status_1.markMutateGroupFinished)(cwd, status, index, response);
562
+ if (response.ok === false && !shouldContinueAfterMutateSegmentFailure(segment, response, successfulRemoveSelectors)) {
563
+ (0, mutate_execution_status_1.markMutateGroupsNotRun)(cwd, status, index + 1);
564
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(segments, responses, [], index);
565
+ const failure = {
566
+ ok: false,
567
+ operation: "mutate.execute",
568
+ failedSegment: index + 1,
569
+ segments: summary,
570
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
571
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
572
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
573
+ response,
574
+ next: "Fix failed group and rerun remaining mutate intent."
575
+ };
576
+ return withMutateMetricsAndText(cwd, failure, (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, failure));
577
+ }
578
+ }
579
+ const manualExtractionIndex = findFirstNonBlockingManualExtractionFailure(segments, responses);
580
+ if (manualExtractionIndex >= 0) {
581
+ return buildMutateManualExtractionAggregateResponse(cwd, "mutate.execute", segments, responses, [], manualExtractionIndex);
582
+ }
583
+ const partialDeclarationIndex = findFirstPartialDeclarationCleanupFailure(segments, responses);
584
+ if (partialDeclarationIndex >= 0) {
585
+ return buildMutatePartialDeclarationCleanupAggregateResponse(cwd, "mutate.execute", segments, responses, []);
586
+ }
587
+ const presentedResponses = segments.length > 0 && segments.every((segment) => segment.kind === "exports.star")
588
+ ? (0, exports_star_command_1.consolidateExportsStarWriteViews)(cwd, responses)
589
+ : responses;
590
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(segments, presentedResponses);
591
+ const response = {
592
+ operation: "mutate.execute",
593
+ summary: `${responses.length} ${responses.length === 1 ? "segment" : "segments"} executed`,
594
+ segments: summary,
595
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
596
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
597
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses)
598
+ };
599
+ return withMutateMetricsAndText(cwd, response, (0, mutate_domain_adapters_1.formatTransparentMutateText)(cwd, "execute", undefined, segments, presentedResponses) ?? (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, response));
600
+ }
601
+ function withMutateSemanticRenameEvidence(options, cwd, status, index) {
602
+ if (!status) {
603
+ return options;
604
+ }
605
+ return {
606
+ ...options,
607
+ semanticRenameExecutionEvidence: {
608
+ beforeApply(writeSet) {
609
+ options.semanticRenameExecutionEvidence?.beforeApply(writeSet);
610
+ (0, mutate_execution_status_1.markMutateGroupApplying)(cwd, status, index, writeSet);
611
+ },
612
+ afterProgress(progress) {
613
+ options.semanticRenameExecutionEvidence?.afterProgress?.(progress);
614
+ (0, mutate_execution_status_1.markMutateGroupSemanticProgress)(cwd, status, index, progress);
615
+ }
616
+ },
617
+ semanticMoveExecutionEvidence: {
618
+ beforeApply(writeSet) {
619
+ options.semanticMoveExecutionEvidence?.beforeApply(writeSet);
620
+ (0, mutate_execution_status_1.markMutateGroupApplying)(cwd, status, index, writeSet);
621
+ },
622
+ afterProgress(progress) {
623
+ options.semanticMoveExecutionEvidence?.afterProgress?.(progress);
624
+ (0, mutate_execution_status_1.markMutateGroupSemanticProgress)(cwd, status, index, progress);
625
+ },
626
+ afterRoute(route) {
627
+ options.semanticMoveExecutionEvidence?.afterRoute?.(route);
628
+ }
629
+ }
630
+ };
631
+ }
632
+ async function runMutateSegmentAsResponse(cwd, segment, action, options) {
633
+ try {
634
+ return await (0, mutate_domain_adapters_1.runMutateSegment)(cwd, segment, action, options);
635
+ }
636
+ catch (error) {
637
+ return errorToMutateSegmentResponse(error);
638
+ }
639
+ }
640
+ async function applyMutateSegmentAsResponse(cwd, segment, options) {
641
+ try {
642
+ return await (0, mutate_domain_adapters_1.applyMutateSegment)(cwd, segment, options);
643
+ }
644
+ catch (error) {
645
+ return errorToMutateSegmentResponse(error);
646
+ }
647
+ }
648
+ function findFirstNonBlockingManualExtractionFailure(segments, responses) {
649
+ return responses.findIndex((response, index) => response.ok === false &&
650
+ isNonBlockingManualExtractionFailure(segments[index] ?? {}, response));
651
+ }
652
+ function isNonBlockingManualExtractionFailure(segment, response) {
653
+ const kind = (0, mutate_output_values_1.readString)(segment.kind);
654
+ if (kind !== "semantic" && kind !== "modulePlan") {
655
+ return false;
656
+ }
657
+ return shouldContinueAfterMutateSegmentFailure(segment, response);
658
+ }
659
+ function findFirstPartialDeclarationCleanupFailure(segments, responses) {
660
+ let sawSuccessfulRemove = false;
661
+ let firstDeclarationRemoveNotFound = -1;
662
+ for (const [index, response] of responses.entries()) {
663
+ const segment = segments[index] ?? {};
664
+ if (isDeclarationRemoveSegment(segment) && readPositiveSelectorKeys(response.removed).length > 0) {
665
+ sawSuccessfulRemove = true;
666
+ }
667
+ if (firstDeclarationRemoveNotFound < 0 &&
668
+ isDeclarationRemoveSegment(segment) &&
669
+ (0, mutate_output_values_1.readString)(response.code) === "DECLARATION_REMOVE_NOT_FOUND") {
670
+ firstDeclarationRemoveNotFound = index;
671
+ }
672
+ if (response.ok !== false) {
673
+ continue;
674
+ }
675
+ if (isPartialDeclarationCleanupResponse(segment, response)) {
676
+ return index;
677
+ }
678
+ if (sawSuccessfulRemove && isDeclarationAddMissingSegment(segment) && hasDeclarationSourceOrSkippedIssue(response)) {
679
+ return index;
680
+ }
681
+ }
682
+ if (firstDeclarationRemoveNotFound >= 0 &&
683
+ responses.some((response) => ((0, mutate_output_values_1.readNumber)(response.declarationsRemoved) ?? 0) > 0 || ((0, mutate_output_values_1.readNumber)(response.importsAdded) ?? 0) > 0)) {
684
+ return firstDeclarationRemoveNotFound;
685
+ }
686
+ return -1;
687
+ }
688
+ function shouldContinueAfterMutateSegmentFailure(segment, response, declarationCleanupState) {
689
+ if (response.ok !== false) {
690
+ return false;
691
+ }
692
+ const kind = (0, mutate_output_values_1.readString)(segment.kind);
693
+ if (kind === "semantic") {
694
+ const failedRows = (0, mutate_execution_status_1.readResponseRows)(response).filter((row) => row.ok === false);
695
+ return failedRows.length > 0 && failedRows.every(mutate_output_values_1.isSemanticManualExtractionRow);
696
+ }
697
+ if (kind === "modulePlan") {
698
+ const failedRows = (0, mutate_execution_status_1.readResponseRows)(response).filter((row) => row.ok === false);
699
+ if (failedRows.length === 0 || (0, mutate_output_values_1.readObjectArray)(response.notRun).length > 0) {
700
+ return false;
701
+ }
702
+ return failedRows.every((row) => (0, mutate_output_values_1.readNestedManualExtractionEntities)(row).length > 0);
703
+ }
704
+ if (kind === "declaration") {
705
+ if (isDeclarationRemoveSegment(segment) &&
706
+ declarationCleanupState?.enabled === true &&
707
+ (0, mutate_output_values_1.readString)(response.code) === "DECLARATION_REMOVE_NOT_FOUND") {
708
+ return true;
709
+ }
710
+ if (isDeclarationAddMissingSegment(segment) &&
711
+ declarationCleanupState?.enabled === true &&
712
+ hasDeclarationSourceOrSkippedIssue(response)) {
713
+ return true;
714
+ }
715
+ return isPartialDeclarationCleanupResponse(segment, response);
716
+ }
717
+ return false;
718
+ }
719
+ function isPartialDeclarationCleanupResponse(segment, response) {
720
+ if (segment.kind !== "declaration" || response.ok !== false) {
721
+ return false;
722
+ }
723
+ if ((0, mutate_output_values_1.readString)(response.code) === "DECLARATION_REMOVE_NOT_FOUND") {
724
+ return false;
725
+ }
726
+ const declarationsRemoved = (0, mutate_output_values_1.readNumber)(response.declarationsRemoved) ?? 0;
727
+ const importsAdded = (0, mutate_output_values_1.readNumber)(response.importsAdded) ?? 0;
728
+ return declarationsRemoved > 0 || importsAdded > 0;
729
+ }
730
+ function hasDeclarationSourceOrSkippedIssue(response) {
731
+ return ((0, mutate_output_values_1.readNumber)(response.sourceFailureCount) ?? 0) > 0 || ((0, mutate_output_values_1.readNumber)(response.skippedCount) ?? 0) > 0;
732
+ }
733
+ function createDeclarationCleanupState(segments) {
734
+ const removeSegments = segments.filter(isDeclarationRemoveSegment);
735
+ const hasAddMissing = segments.some(isDeclarationAddMissingSegment);
736
+ return removeSegments.length > 0 && hasAddMissing
737
+ ? { enabled: true }
738
+ : null;
739
+ }
740
+ function prepareDeclarationPreviewSegment(segment, sawDeclarationRemove) {
741
+ if (!sawDeclarationRemove || !isDeclarationAddMissingSegment(segment)) {
742
+ return segment;
743
+ }
744
+ const request = (0, mutate_output_values_1.isObject)(segment.request) ? segment.request : {};
745
+ return {
746
+ ...segment,
747
+ request: {
748
+ ...request,
749
+ sourceCheckOnly: true
750
+ }
751
+ };
752
+ }
753
+ function shouldPersistChildPreviewId(segment) {
754
+ const request = (0, mutate_output_values_1.isObject)(segment.request) ? segment.request : {};
755
+ return request.sourceCheckOnly !== true;
756
+ }
757
+ function prepareDeclarationExecutionSegment(segment, state) {
758
+ if (!state?.enabled || !isDeclarationAddMissingSegment(segment)) {
759
+ return segment;
760
+ }
761
+ const request = (0, mutate_output_values_1.isObject)(segment.request) ? segment.request : {};
762
+ return {
763
+ ...segment,
764
+ request: {
765
+ ...request,
766
+ cleanupTail: true
767
+ }
768
+ };
769
+ }
770
+ function updateSuccessfulDeclarationRemoveSelectors(state, segment, response) {
771
+ }
772
+ function readPositiveSelectorKeys(value) {
773
+ if (!(0, mutate_output_values_1.isObject)(value)) {
774
+ return [];
775
+ }
776
+ return Object.entries(value)
777
+ .filter(([, count]) => typeof count === "number" && count > 0)
778
+ .map(([selector]) => selector);
779
+ }
780
+ function isDeclarationRemoveSegment(segment) {
781
+ if (segment.kind !== "declaration" || !(0, mutate_output_values_1.isObject)(segment.request)) {
782
+ return false;
783
+ }
784
+ return (0, mutate_output_values_1.readString)(segment.request.operation) === "remove";
785
+ }
786
+ function isDeclarationAddMissingSegment(segment) {
787
+ if (segment.kind !== "declaration" || !(0, mutate_output_values_1.isObject)(segment.request)) {
788
+ return false;
789
+ }
790
+ return (0, mutate_output_values_1.readString)(segment.request.operation) === "addMissing";
791
+ }
792
+ function buildMutatePartialDeclarationCleanupAggregateResponse(cwd, operation, segments, responses, previews, previewId) {
793
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(segments, responses, previews);
794
+ const hasNotFound = responses.some((response) => ((0, mutate_output_values_1.readNumber)(response.notFoundCount) ?? 0) > 0);
795
+ const response = (0, mutate_output_values_1.compactObject)({
796
+ ok: false,
797
+ operation,
798
+ ...(previewId ? { previewId } : {}),
799
+ segments: summary,
800
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
801
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
802
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
803
+ partialDeclarationCleanup: true,
804
+ next: hasNotFound
805
+ ? "Fix missing selectors and rerun only the remaining declaration cleanup intent."
806
+ : "Fix failed selectors and rerun only the remaining declaration cleanup intent."
807
+ });
808
+ return withMutateMetricsAndText(cwd, response, (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, response));
809
+ }
810
+ function buildMutateManualExtractionAggregateResponse(cwd, operation, segments, responses, previews, failedIndex, previewId) {
811
+ const summary = (0, mutate_result_projection_1.summarizeSegments)(segments, responses, previews, failedIndex);
812
+ const response = (0, mutate_output_values_1.compactObject)({
813
+ ok: false,
814
+ operation,
815
+ ...(previewId ? { previewId } : {}),
816
+ failedSegment: failedIndex + 1,
817
+ segments: summary,
818
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
819
+ filesWritten: (0, mutate_execution_status_1.collectResponsesFilesWritten)(responses),
820
+ filesTouched: (0, mutate_execution_status_1.collectResponsesFilesTouched)(responses),
821
+ next: "use manual extraction for listed symbols"
822
+ });
823
+ return withMutateMetricsAndText(cwd, response, (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, response));
824
+ }
825
+ function errorToMutateSegmentResponse(error) {
826
+ return (0, errors_1.errorPayload)(error);
827
+ }
828
+ function normalizeMutatePayload(rawPayload) {
829
+ if (!rawPayload || typeof rawPayload !== "object" || Array.isArray(rawPayload)) {
830
+ throw new errors_1.CliError("MUTATE_PAYLOAD_REQUIRED", "mutate expects a JSON/DSL payload.");
831
+ }
832
+ const payload = rawPayload;
833
+ const segments = (0, mutate_output_values_1.readObjectArray)(payload.segments);
834
+ if (segments.length === 0) {
835
+ throw new errors_1.CliError("MUTATE_SEGMENTS_REQUIRED", "mutate expects at least one segment.");
836
+ }
837
+ const hasModulePlan = segments.some((segment) => segment.kind === "modulePlan");
838
+ const hasImportsNormalize = segments.some((segment) => segment.kind === "imports.normalize");
839
+ const hasImportsRebase = segments.some((segment) => segment.kind === "imports.rebase");
840
+ const hasImportsMutation = hasImportsNormalize || hasImportsRebase;
841
+ const hasDeclaration = segments.some((segment) => segment.kind === "declaration");
842
+ const hasExportsObject = segments.some((segment) => segment.kind === "exports.object");
843
+ const hasExportsStar = segments.some((segment) => segment.kind === "exports.star");
844
+ const hasStandardMutation = segments.some((segment) => segment.kind === "semantic" || segment.kind === "file");
845
+ const hasOtherMutation = segments.some((segment) => segment.kind !== "modulePlan");
846
+ if (hasModulePlan && hasOtherMutation) {
847
+ throw new errors_1.CliError("MUTATE_MODULE_PLAN_MIX_UNSUPPORTED", "modulePlan cannot be mixed with other mutation operations yet.", {
848
+ next: "Run modulePlan as a separate mutate request, then run the remaining mutations."
849
+ });
850
+ }
851
+ if (hasImportsMutation && segments.length > 1) {
852
+ throw new errors_1.CliError("MUTATE_IMPORTS_MIX_UNSUPPORTED", "imports mutations cannot be mixed with other mutation operations yet.", {
853
+ next: "Run imports mutation as a separate mutate request."
854
+ });
855
+ }
856
+ if (hasDeclaration && (hasStandardMutation || hasModulePlan || hasImportsMutation)) {
857
+ throw new errors_1.CliError("MUTATE_DECLARATION_MIX_UNSUPPORTED", "declaration remove/addMissing cannot be mixed with semantic, file, module, or imports.normalize operations yet.", {
858
+ next: "Run declaration cleanup as a separate mutate request."
859
+ });
860
+ }
861
+ if (hasExportsObject && segments.length > 1) {
862
+ throw new errors_1.CliError("MUTATE_OBJECT_PACK_MIX_UNSUPPORTED", "object.pack/object.unpack cannot be mixed with other mutation operations yet.", {
863
+ next: "Run object.pack or object.unpack as a separate mutate request."
864
+ });
865
+ }
866
+ if (hasExportsStar && segments.some((segment) => segment.kind !== "exports.star")) {
867
+ throw new errors_1.CliError("MUTATE_EXPORTS_STAR_MIX_UNSUPPORTED", "exports.star mutations cannot be mixed with other mutation operations yet.", { next: "Run exports.star.expand or exports.star.collapse as a separate mutate request." });
868
+ }
869
+ if (hasExportsStar && new Set(segments.filter((segment) => segment.kind === "exports.star").map((segment) => segment.operation)).size > 1) {
870
+ throw new errors_1.CliError("MUTATE_EXPORTS_STAR_OPERATION_MIX_UNSUPPORTED", "exports.star.expand and exports.star.collapse cannot be mixed in one request yet.", { next: "Run expand and collapse as separate mutate requests." });
871
+ }
872
+ return {
873
+ segments,
874
+ agentDxSignals: collectMutateDslAgentDxSignals(payload[mutate_dsl_1.MUTATE_DSL_AGENT_DX_FIELD])
875
+ };
876
+ }
877
+ function collectMutateDslAgentDxSignals(value) {
878
+ const diagnostics = Array.isArray(value) ? value.filter(mutate_output_values_1.isObject) : [];
879
+ const signals = [];
880
+ for (const diagnostic of diagnostics) {
881
+ if (diagnostic.kind !== "unknownOption") {
882
+ continue;
883
+ }
884
+ const command = (0, mutate_output_values_1.readString)(diagnostic.command);
885
+ const flags = (0, mutate_output_values_1.readStringArray)(diagnostic.options);
886
+ if (!command || flags.length === 0) {
887
+ continue;
888
+ }
889
+ signals.push({
890
+ kind: "unknownFlag",
891
+ command,
892
+ flags
893
+ });
894
+ }
895
+ return signals;
896
+ }
897
+ function readChildPreviewId(segment, response) {
898
+ if (typeof response.previewId === "string") {
899
+ return response.previewId;
900
+ }
901
+ if (typeof response.planId === "string") {
902
+ return response.planId;
903
+ }
904
+ if (segment.kind === "modulePlan" && typeof response.planId === "string") {
905
+ return response.planId;
906
+ }
907
+ return null;
908
+ }
909
+ function buildCheapMutatePreviewResponse(cwd, segment) {
910
+ if (segment.kind === "semantic") {
911
+ return buildCheapSemanticPreviewResponse(segment);
912
+ }
913
+ if (segment.kind === "file") {
914
+ return buildCheapFilePreviewResponse(segment);
915
+ }
916
+ if (segment.kind === "modulePlan") {
917
+ return buildCheapModulePlanPreviewResponse(cwd, segment);
918
+ }
919
+ if (segment.kind === "imports.normalize") {
920
+ const request = (0, mutate_output_values_1.isObject)(segment.request) ? segment.request : {};
921
+ return {
922
+ operation: "imports.normalize.preview",
923
+ summary: "imports normalize request ready",
924
+ rows: [(0, mutate_output_values_1.compactObject)({
925
+ ok: true,
926
+ scope: (0, mutate_output_values_1.readString)(request.scope),
927
+ target: (0, mutate_output_values_1.readString)(request.to) ?? (0, mutate_output_values_1.readString)(request.mode)
928
+ })]
929
+ };
930
+ }
931
+ if (segment.kind === "imports.rebase") {
932
+ const request = (0, mutate_output_values_1.isObject)(segment.request) ? segment.request : {};
933
+ return {
934
+ operation: `${(0, mutate_output_values_1.readString)(request.operation) ?? "imports.rebase"}.preview`,
935
+ summary: "imports rebase request ready",
936
+ rows: [(0, mutate_output_values_1.compactObject)({
937
+ ok: true,
938
+ barrel: (0, mutate_output_values_1.readString)(request.barrel),
939
+ scope: (0, mutate_output_values_1.readString)(request.scope),
940
+ files: (0, mutate_output_values_1.readStringArray)(request.files),
941
+ symbols: (0, mutate_output_values_1.readStringArray)(request.symbols)
942
+ })]
943
+ };
944
+ }
945
+ if (segment.kind === "declaration") {
946
+ const request = (0, mutate_output_values_1.isObject)(segment.request) ? segment.request : {};
947
+ return {
948
+ operation: "declaration.preview",
949
+ summary: `${(0, mutate_output_values_1.readString)(request.operation) ?? "declaration"} request ready`,
950
+ rows: [(0, mutate_output_values_1.compactObject)({
951
+ ok: true,
952
+ operation: (0, mutate_output_values_1.readString)(request.operation),
953
+ scope: (0, mutate_output_values_1.readString)(request.scope),
954
+ selectors: (0, mutate_output_values_1.readStringArray)(request.selectors)
955
+ })]
956
+ };
957
+ }
958
+ if (segment.kind === "exports.object") {
959
+ const operation = (0, mutate_failure_output_1.readObjectOperationFromPacks)((0, mutate_output_values_1.readObjectArray)(segment.packs));
960
+ const label = `object.${operation}`;
961
+ return {
962
+ operation: `exports.object.${operation}.preview`,
963
+ summary: `${label} request ready`,
964
+ rows: (0, mutate_output_values_1.readObjectArray)(segment.packs).map((pack) => (0, mutate_output_values_1.compactObject)({
965
+ ok: true,
966
+ sourceFile: (0, mutate_output_values_1.readString)(segment.sourceFile),
967
+ operation: (0, mutate_output_values_1.readString)(pack.operation) ?? operation,
968
+ objectName: (0, mutate_output_values_1.readString)(pack.objectName),
969
+ selectors: (0, mutate_output_values_1.readStringArray)(pack.selectors)
970
+ }))
971
+ };
972
+ }
973
+ return {
974
+ ok: false,
975
+ operation: "mutate.preview",
976
+ code: "MUTATE_SEGMENT_KIND_UNSUPPORTED",
977
+ error: `Unsupported mutate segment kind: ${String(segment.kind)}`
978
+ };
979
+ }
980
+ function buildCheapSemanticPreviewResponse(segment) {
981
+ const builderRows = (0, mutate_output_values_1.readObjectArray)(segment.requests).map((request, requestIndex) => {
982
+ const op = (0, mutate_output_values_1.readString)(request.op) ?? "unknown";
983
+ if (op === "rename") {
984
+ const renames = readRenameMap(request.renames);
985
+ return (0, mutate_output_values_1.compactObject)({
986
+ op,
987
+ sourceFile: (0, mutate_output_values_1.readString)(request.sourceFile),
988
+ builtRows: renames.map(([entity, newName], index) => ({
989
+ id: `preview-rename-${requestIndex + 1}-${index + 1}`,
990
+ entity,
991
+ sourceFile: (0, mutate_output_values_1.readString)(request.sourceFile),
992
+ newName
993
+ }))
994
+ });
995
+ }
996
+ const entities = (0, mutate_output_values_1.readStringArray)(request.entities);
997
+ return (0, mutate_output_values_1.compactObject)({
998
+ op,
999
+ sourceFile: (0, mutate_output_values_1.readString)(request.sourceFile),
1000
+ targetFile: (0, mutate_output_values_1.readString)(request.targetFile),
1001
+ entities,
1002
+ builtRows: entities.map((entity, index) => ({
1003
+ id: `preview-move-${requestIndex + 1}-${index + 1}`,
1004
+ entity,
1005
+ sourceFile: (0, mutate_output_values_1.readString)(request.sourceFile),
1006
+ targetFile: (0, mutate_output_values_1.readString)(request.targetFile)
1007
+ }))
1008
+ });
1009
+ });
1010
+ const responseRows = builderRows.flatMap((row) => (0, mutate_output_values_1.readObjectArray)(row.builtRows).map((builtRow) => (0, mutate_output_values_1.compactObject)({
1011
+ id: (0, mutate_output_values_1.readString)(builtRow.id),
1012
+ ok: true,
1013
+ outcome: "planned",
1014
+ entity: (0, mutate_output_values_1.readString)(builtRow.entity),
1015
+ sourceFile: (0, mutate_output_values_1.readString)(builtRow.sourceFile),
1016
+ targetFile: (0, mutate_output_values_1.readString)(builtRow.targetFile),
1017
+ newName: (0, mutate_output_values_1.readString)(builtRow.newName)
1018
+ })));
1019
+ return {
1020
+ operation: "mutate.preview",
1021
+ summary: `${responseRows.length} ${responseRows.length === 1 ? "semantic row" : "semantic rows"} planned`,
1022
+ builder: { rows: builderRows },
1023
+ response: {
1024
+ batchStatus: "planned",
1025
+ rows: responseRows
1026
+ }
1027
+ };
1028
+ }
1029
+ function buildCheapFilePreviewResponse(segment) {
1030
+ const operations = (0, mutate_output_values_1.readObjectArray)(segment.operations);
1031
+ const moves = groupFileMoveOperations(operations);
1032
+ const renames = operations
1033
+ .filter((operation) => operation.kind === "fileRename")
1034
+ .map((operation) => (0, mutate_output_values_1.compactObject)({
1035
+ source: (0, mutate_output_values_1.readString)(operation.sourceFile),
1036
+ target: (0, mutate_output_values_1.readString)(operation.targetFile)
1037
+ }));
1038
+ const rows = operations.map((operation, index) => (0, mutate_output_values_1.compactObject)({
1039
+ id: (0, mutate_output_values_1.readString)(operation.id) ?? `preview-file-${index + 1}`,
1040
+ ok: true,
1041
+ applied: false,
1042
+ sourceFile: (0, mutate_output_values_1.readString)(operation.sourceFile),
1043
+ targetFile: (0, mutate_output_values_1.readString)(operation.targetFile)
1044
+ }));
1045
+ return (0, mutate_output_values_1.compactObject)({
1046
+ operation: "file.mutation.preview",
1047
+ summary: `${operations.length} ${operations.length === 1 ? "file row" : "file rows"} planned`,
1048
+ operationCount: operations.length,
1049
+ moves,
1050
+ renames,
1051
+ rows
1052
+ });
1053
+ }
1054
+ function buildCheapModulePlanPreviewResponse(cwd, segment) {
1055
+ const sourceFile = (0, mutate_output_values_1.readString)(segment.sourceFile);
1056
+ const modules = (0, mutate_output_values_1.readObjectArray)(segment.modules);
1057
+ const rows = modules.map((module) => {
1058
+ const target = (0, mutate_output_values_1.readString)(module.targetFile) ?? (0, mutate_output_values_1.readString)(module.target) ?? "";
1059
+ const entities = readModulePlanIntentEntities(module);
1060
+ return (0, mutate_output_values_1.compactObject)({
1061
+ target: (0, mutate_failure_output_1.formatPathForMutateOutput)(cwd, target),
1062
+ entities,
1063
+ ok: true,
1064
+ summary: target && !fs.existsSync((0, mutate_result_projection_1.resolveMaybeRelative)(cwd, target)) ? "target will be created" : "target ready"
1065
+ });
1066
+ });
1067
+ return (0, mutate_output_values_1.compactObject)({
1068
+ operation: "modulePlan.preview",
1069
+ sourceFile,
1070
+ summary: (0, mutate_domain_adapters_1.formatReadyModulePlanSummary)(rows),
1071
+ moduleCount: modules.length,
1072
+ rows,
1073
+ targets: rows.map((row) => (0, mutate_output_values_1.compactObject)({
1074
+ file: (0, mutate_output_values_1.readString)(row.target),
1075
+ entities: (0, mutate_output_values_1.readStringArray)(row.entities),
1076
+ summary: (0, mutate_output_values_1.readString)(row.summary)
1077
+ }))
1078
+ });
1079
+ }
1080
+ function validateMutateIntentBeforeExecution(cwd, segments, operation, previewId) {
1081
+ for (const [index, segment] of segments.entries()) {
1082
+ if (segment.kind !== "file") {
1083
+ continue;
1084
+ }
1085
+ const validation = validateFileLayoutSegment(cwd, segment);
1086
+ if (!validation) {
1087
+ continue;
1088
+ }
1089
+ const summary = summarizePreflightFailureSegments(cwd, segments, index);
1090
+ return (0, mutate_output_values_1.compactObject)({
1091
+ ok: false,
1092
+ operation,
1093
+ ...(previewId ? { previewId } : {}),
1094
+ code: (0, mutate_output_values_1.readString)(validation.code) ?? "MUTATE_FILE_LAYOUT_VALIDATION_FAILED",
1095
+ failedSegment: index + 1,
1096
+ segments: summary,
1097
+ aggregate: (0, mutate_result_projection_1.buildMutateAggregateModel)(summary),
1098
+ validation,
1099
+ filesWritten: [],
1100
+ filesTouched: [],
1101
+ next: `fix the mutate request and rerun ${operation.replace("mutate.", "")}`
1102
+ });
1103
+ }
1104
+ return null;
1105
+ }
1106
+ function validateFileLayoutSegment(cwd, segment) {
1107
+ const operations = (0, mutate_output_values_1.readObjectArray)(segment.operations);
1108
+ const state = createFileLayoutValidationState();
1109
+ for (const group of groupFileLayoutValidationOperations(operations)) {
1110
+ const validation = validateFileLayoutOperationGroup(cwd, group, state);
1111
+ if (validation) {
1112
+ return validation;
1113
+ }
1114
+ applyFileLayoutValidationGroup(cwd, group, state);
1115
+ }
1116
+ return null;
1117
+ }
1118
+ function createFileLayoutValidationState() {
1119
+ return {
1120
+ added: new Set(),
1121
+ removed: new Set(),
1122
+ seenTargets: new Set()
1123
+ };
1124
+ }
1125
+ function validateFileLayoutOperationGroup(cwd, operations, state) {
1126
+ const duplicateTargets = [];
1127
+ const missingSources = [];
1128
+ const unsupportedSources = [];
1129
+ for (const operation of operations) {
1130
+ const source = (0, mutate_output_values_1.readString)(operation.sourceFile);
1131
+ const target = (0, mutate_output_values_1.readString)(operation.targetFile);
1132
+ if (target) {
1133
+ const resolvedTarget = (0, mutate_result_projection_1.normalizePathKey)((0, mutate_result_projection_1.resolveMaybeRelative)(cwd, target));
1134
+ if (state.seenTargets.has(resolvedTarget)) {
1135
+ duplicateTargets.push(target);
1136
+ }
1137
+ }
1138
+ if (source && !fileLayoutPathExists(cwd, source, state)) {
1139
+ missingSources.push(source);
1140
+ }
1141
+ else if (source && isCssLikeFileLayoutSource(source)) {
1142
+ unsupportedSources.push(source);
1143
+ }
1144
+ }
1145
+ const family = operations.every((operation) => operation.kind === "fileRename")
1146
+ ? "file rename"
1147
+ : "file move";
1148
+ if (duplicateTargets.length > 0) {
1149
+ return {
1150
+ code: family === "file rename" ? "MUTATE_FILE_RENAME_DUPLICATE_TARGET" : "MUTATE_FILE_MOVE_DUPLICATE_TARGET",
1151
+ family,
1152
+ duplicateTargets: (0, mutate_output_values_1.uniqueStrings)(duplicateTargets)
1153
+ };
1154
+ }
1155
+ if (missingSources.length > 0) {
1156
+ return {
1157
+ code: family === "file rename" ? "MUTATE_FILE_RENAME_SOURCE_NOT_FOUND" : "MUTATE_FILE_MOVE_SOURCE_NOT_FOUND",
1158
+ family,
1159
+ missingSources: (0, mutate_output_values_1.uniqueStrings)(missingSources)
1160
+ };
1161
+ }
1162
+ if (unsupportedSources.length > 0) {
1163
+ return {
1164
+ code: family === "file rename" ? "FILE_RENAME_SOURCE_ASSET_UNSUPPORTED" : "FILE_MOVE_SOURCE_ASSET_UNSUPPORTED",
1165
+ family,
1166
+ unsupportedSources: (0, mutate_output_values_1.uniqueStrings)(unsupportedSources)
1167
+ };
1168
+ }
1169
+ return null;
1170
+ }
1171
+ function isCssLikeFileLayoutSource(source) {
1172
+ const extension = path.extname(source).toLowerCase();
1173
+ return extension === ".css" || extension === ".scss";
1174
+ }
1175
+ function applyFileLayoutValidationGroup(cwd, operations, state) {
1176
+ for (const operation of operations) {
1177
+ const source = (0, mutate_output_values_1.readString)(operation.sourceFile);
1178
+ const target = (0, mutate_output_values_1.readString)(operation.targetFile);
1179
+ if (target) {
1180
+ state.seenTargets.add((0, mutate_result_projection_1.normalizePathKey)((0, mutate_result_projection_1.resolveMaybeRelative)(cwd, target)));
1181
+ }
1182
+ if (source) {
1183
+ const sourceKey = (0, mutate_result_projection_1.normalizePathKey)((0, mutate_result_projection_1.resolveMaybeRelative)(cwd, source));
1184
+ state.added.delete(sourceKey);
1185
+ state.removed.add(sourceKey);
1186
+ }
1187
+ if (target) {
1188
+ const targetKey = (0, mutate_result_projection_1.normalizePathKey)((0, mutate_result_projection_1.resolveMaybeRelative)(cwd, target));
1189
+ state.removed.delete(targetKey);
1190
+ state.added.add(targetKey);
1191
+ }
1192
+ }
1193
+ }
1194
+ function fileLayoutPathExists(cwd, value, state) {
1195
+ const key = (0, mutate_result_projection_1.normalizePathKey)((0, mutate_result_projection_1.resolveMaybeRelative)(cwd, value));
1196
+ if (state.added.has(key)) {
1197
+ return true;
1198
+ }
1199
+ if (state.removed.has(key)) {
1200
+ return false;
1201
+ }
1202
+ return fs.existsSync((0, mutate_result_projection_1.resolveMaybeRelative)(cwd, value));
1203
+ }
1204
+ function groupFileLayoutValidationOperations(operations) {
1205
+ const groups = [];
1206
+ for (const operation of operations) {
1207
+ const previousGroup = groups[groups.length - 1];
1208
+ const previousOperation = previousGroup?.[previousGroup.length - 1];
1209
+ if (previousGroup && previousOperation && isSameFileLayoutValidationGroup(previousOperation, operation)) {
1210
+ previousGroup.push(operation);
1211
+ continue;
1212
+ }
1213
+ groups.push([operation]);
1214
+ }
1215
+ return groups;
1216
+ }
1217
+ function isSameFileLayoutValidationGroup(previous, next) {
1218
+ if (previous.kind !== next.kind) {
1219
+ return false;
1220
+ }
1221
+ if (previous.kind === "fileMoveToDir") {
1222
+ return (0, mutate_output_values_1.readString)(previous.targetDir) === (0, mutate_output_values_1.readString)(next.targetDir);
1223
+ }
1224
+ if (previous.kind === "fileRename") {
1225
+ return (0, mutate_output_values_1.readString)(previous.targetDir) === (0, mutate_output_values_1.readString)(next.targetDir);
1226
+ }
1227
+ return false;
1228
+ }
1229
+ function summarizePreflightFailureSegments(cwd, segments, failedIndex) {
1230
+ return segments.map((segment, index) => {
1231
+ const status = index === failedIndex ? "failed" : "notRun";
1232
+ const response = index <= failedIndex ? buildCheapMutatePreviewResponse(cwd, segment) : undefined;
1233
+ return (0, mutate_output_values_1.compactObject)({
1234
+ index: index + 1,
1235
+ kind: String(segment.kind ?? "unknown"),
1236
+ status,
1237
+ ok: false,
1238
+ summary: response ? (0, mutate_output_values_1.readSummary)(response) : "not run",
1239
+ estimatedDurationMs: (0, mutate_domain_adapters_1.estimateMutateSegmentDurationMs)(segment),
1240
+ filesWritten: [],
1241
+ filesTouched: [],
1242
+ ...(response ? { details: (0, mutate_result_projection_1.buildMutateSegmentDetails)(segment, response) } : {})
1243
+ });
1244
+ });
1245
+ }
1246
+ function groupFileMoveOperations(operations) {
1247
+ const groups = new Map();
1248
+ for (const operation of operations) {
1249
+ if (operation.kind !== "fileMoveToDir") {
1250
+ continue;
1251
+ }
1252
+ const targetDir = (0, mutate_output_values_1.readString)(operation.targetDir) ?? "";
1253
+ groups.set(targetDir, [...(groups.get(targetDir) ?? []), (0, mutate_output_values_1.readString)(operation.sourceFile) ?? ""]);
1254
+ }
1255
+ return Array.from(groups.entries()).map(([targetDir, files]) => (0, mutate_output_values_1.compactObject)({
1256
+ targetDir,
1257
+ files: files.filter(Boolean)
1258
+ }));
1259
+ }
1260
+ function readRenameMap(value) {
1261
+ if (!(0, mutate_output_values_1.isObject)(value)) {
1262
+ return [];
1263
+ }
1264
+ return Object.entries(value)
1265
+ .filter((entry) => typeof entry[1] === "string");
1266
+ }
1267
+ function readModulePlanIntentEntities(module) {
1268
+ const entities = (0, mutate_output_values_1.readStringArray)(module.entities);
1269
+ if (entities.length > 0) {
1270
+ return entities;
1271
+ }
1272
+ const symbols = Array.isArray(module.symbols) ? module.symbols : [];
1273
+ return symbols
1274
+ .map((symbol) => {
1275
+ if (typeof symbol === "string") {
1276
+ return symbol;
1277
+ }
1278
+ if ((0, mutate_output_values_1.isObject)(symbol)) {
1279
+ return (0, mutate_output_values_1.readString)(symbol.raw) ?? (0, mutate_output_values_1.readString)(symbol.symbolName);
1280
+ }
1281
+ return null;
1282
+ })
1283
+ .filter((symbol) => Boolean(symbol));
1284
+ }
1285
+ function withText(response, text = null) {
1286
+ return (0, agent_text_1.attachAgentText)(response, text ?? (0, mutate_response_replay_1.formatMutateAgentText)(response));
1287
+ }
1288
+ function withMutateMetricsAndText(cwd, response, text = null) {
1289
+ const presentationModel = (0, mutate_file_view_1.attachMutateAggregateFilesView)(cwd, (0, mutate_result_projection_1.attachDeclarationCleanupAggregateView)(cwd, response));
1290
+ const prepared = (0, mutate_result_projection_1.attachMutateResultModel)(presentationModel);
1291
+ recordMutateCentralMetrics(cwd, prepared);
1292
+ if (hasDeclarationCleanupOperations(presentationModel)) {
1293
+ return (0, agent_text_1.attachAgentText)(prepared, (0, mutate_aggregate_output_1.formatMutateAggregateText)(cwd, presentationModel) ?? text ?? (0, mutate_response_replay_1.formatMutateAgentText)(presentationModel));
1294
+ }
1295
+ return (0, agent_text_1.attachAgentText)(prepared, text ?? (0, mutate_response_replay_1.formatMutateAgentText)(presentationModel));
1296
+ }
1297
+ function hasDeclarationCleanupOperations(response) {
1298
+ const aggregate = (0, mutate_output_values_1.isObject)(response.aggregate) ? response.aggregate : {};
1299
+ const operations = (0, mutate_output_values_1.isObject)(aggregate.operations) ? aggregate.operations : {};
1300
+ return (0, mutate_output_values_1.readObjectArray)(operations.declarationCleanups).length > 0;
1301
+ }
1302
+ function recordMutateCentralMetrics(cwd, response) {
1303
+ const operation = (0, mutate_output_values_1.readString)(response.operation);
1304
+ if (operation !== "mutate.execute" && operation !== "mutate.apply") {
1305
+ return;
1306
+ }
1307
+ const aggregate = (0, mutate_output_values_1.isObject)(response.aggregate) ? response.aggregate : {};
1308
+ const operations = (0, mutate_output_values_1.isObject)(aggregate.operations) ? aggregate.operations : {};
1309
+ const filesWritten = (0, mutate_output_values_1.readStringArray)(response.filesWritten).length > 0
1310
+ ? (0, mutate_output_values_1.readStringArray)(response.filesWritten)
1311
+ : (0, mutate_output_values_1.readStringArray)(aggregate.filesWritten);
1312
+ const filesTouched = (0, mutate_output_values_1.readStringArray)(response.filesTouched).length > 0
1313
+ ? (0, mutate_output_values_1.readStringArray)(response.filesTouched)
1314
+ : (0, mutate_output_values_1.readStringArray)(aggregate.filesTouched);
1315
+ const renames = (0, mutate_output_values_1.readObjectArray)(operations.renames);
1316
+ for (const rename of renames) {
1317
+ (0, central_metrics_1.recordCentralMetric)({
1318
+ kind: "mutation.entity",
1319
+ operation,
1320
+ domainOperation: "rename",
1321
+ cwd: path.resolve(cwd),
1322
+ sourceFile: (0, mutate_output_values_1.readString)(rename.sourceFile),
1323
+ entity: (0, mutate_output_values_1.readString)(rename.entity),
1324
+ newName: (0, mutate_output_values_1.readString)(rename.newName),
1325
+ ok: response.ok !== false,
1326
+ totalEntities: renames.length,
1327
+ changedFileCount: filesTouched.length,
1328
+ savedFileCount: filesWritten.length,
1329
+ ...((0, central_metrics_1.mutationImpactMetricsEnabled)()
1330
+ ? {
1331
+ impact: {
1332
+ locationCount: null,
1333
+ fileCount: filesTouched.length,
1334
+ impactCollectionMs: null
1335
+ },
1336
+ changedFiles: filesTouched,
1337
+ savedFiles: filesWritten
1338
+ }
1339
+ : {})
1340
+ });
1341
+ }
1342
+ for (const move of (0, mutate_output_values_1.readObjectArray)(operations.declarationMoves)) {
1343
+ const entities = (0, mutate_output_values_1.readStringArray)(move.entities);
1344
+ for (const entity of entities) {
1345
+ (0, central_metrics_1.recordCentralMetric)({
1346
+ kind: "mutation.entity",
1347
+ operation,
1348
+ domainOperation: "move.toFile",
1349
+ cwd: path.resolve(cwd),
1350
+ sourceFile: (0, mutate_output_values_1.readString)(move.sourceFile),
1351
+ targetFile: (0, mutate_output_values_1.readString)(move.targetFile),
1352
+ entity,
1353
+ ok: response.ok !== false,
1354
+ totalEntities: entities.length,
1355
+ changedFileCount: filesTouched.length,
1356
+ savedFileCount: filesWritten.length,
1357
+ ...((0, central_metrics_1.mutationImpactMetricsEnabled)()
1358
+ ? {
1359
+ impact: {
1360
+ referenceCount: null,
1361
+ fileCount: filesTouched.length,
1362
+ impactCollectionMs: null
1363
+ },
1364
+ changedFiles: filesTouched,
1365
+ savedFiles: filesWritten
1366
+ }
1367
+ : {})
1368
+ });
1369
+ }
1370
+ }
1371
+ (0, central_metrics_1.recordCentralMetric)({
1372
+ kind: "mutation.summary",
1373
+ operation,
1374
+ cwd: path.resolve(cwd),
1375
+ ok: response.ok !== false,
1376
+ summary: (0, mutate_output_values_1.readString)(response.summary) ?? (0, mutate_aggregate_output_1.formatMutateAggregateSummary)(aggregate, operation, response),
1377
+ filesWrittenCount: filesWritten.length,
1378
+ filesTouchedCount: filesTouched.length
1379
+ });
1380
+ }
1381
+ function mutateHelp() {
1382
+ return {
1383
+ ok: true,
1384
+ command: "mutate",
1385
+ usage: "aib mutate preview --stdin | aib mutate execute --stdin | aib mutate apply <previewId>",
1386
+ notes: [
1387
+ "mutate is the unified mutation entrypoint.",
1388
+ "rename is semantic symbol rename.",
1389
+ "renameFile is whole-file rename.",
1390
+ "move <targetFile>: <entities> is semantic declaration move.",
1391
+ "moveToDir <targetDir>: <files> is whole-file move."
1392
+ ]
1393
+ };
1394
+ }