@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
@@ -1,5 +1,1053 @@
1
- "use strict";var ge=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Re=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Q=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&ge(n,t,r[o]);return Re(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runFileRename=Me,exports.readCachedFileRenameExecution=Ce;const _=Q(require("node:fs")),f=Q(require("node:path")),x=require("zod"),Fe=require("../client/http-client"),E=require("../config/env-vars"),Ee=require("../config/product-storage"),W=require("../config/import-rules"),O=require("../shared/agent-text"),S=require("../shared/errors"),U=require("../shared/protocol"),_e=require("../shared/routes"),B=require("./shared"),X=require("./inspect-cycles"),b=require("./file-rename-preview-cache"),w=require("./file-rename-execution-cache"),F=require("./file-mutation-runtime"),Y=require("./mutation-execution-cache"),Z=x.z.object({base:x.z.string().min(1),renames:x.z.array(x.z.object({source:x.z.string().min(1),target:x.z.string().min(1)})).min(1),execute:x.z.boolean().optional()});async function Me(e,t,n={},r=[]){const o=Be(),i=r[0]??"preview";if(i==="help"||i==="--help")return Ge();if(i==="apply"){const l=r[1];if(!l||l.startsWith("--"))throw new S.CliError("FILE_RENAME_PREVIEW_ID_REQUIRED","file rename apply expects a preview id.",{usage:"aib file rename apply <previewId>"});return we(e,l,n,o)}if(i!=="preview"&&i!=="execute"&&i!=="validate")throw new S.CliError("UNKNOWN_FILE_RENAME_COMMAND",`Unknown file rename command: ${i}`,{availableCommands:["preview","apply","execute","validate","help"]});const s=Z.parse(t);return i==="execute"&&K()>0?ee(e,{...s,execute:!0},n,"execute",K(),o):te(e,{...s,execute:i==="execute"},n,i,o)}async function we(e,t,n,r){const o=(0,b.readFileRenamePreviewRecord)(e,t);(0,b.validateFileMoveStates)(o);const i=Z.parse({...o.normalizedPayload,execute:!0}),s=K();if(s>0)return ee(e,i,n,"apply",s,r,t);const l=await te(e,i,n,"apply",r,t);return l.ok===!1?(0,O.attachAgentText)({...l,next:"Fix the file rename request and rerun preview."},G({...l,next:"Fix the file rename request and rerun preview."})):l}async function ee(e,t,n,r,o,i,s){const l=ie(e,t,!0),a=(0,w.buildFileRenameExecutionId)(),u=`file.rename.${r}`,d=(0,F.estimateFileMutationDurationMs)(qe(l.operations)),c=(0,w.createFileRenameExecutionStatus)(e,a,u,We(e,l.operations));(0,w.writeFileRenameExecutionStatus)(e,c);const R=Date.now(),M=Ve(),P=(0,F.startFileMutationBackgroundJob)(()=>(0,Ee.runWithProductStorageOverride)(M[E.CLI_ENV.productStorageDir],()=>(0,F.withFileMutationBackgroundEnv)(M,async()=>{try{const m=await ne(e,l,r,n,i,a,c,s),I=Ue(m);return c.status=m.ok===!1?"failed":"completed",c.phase="completed",c.completedRows=m.ok===!1?I.filter(A=>A.ok!==!1).length:c.rowCount,c.failedRows=m.ok===!1?I.filter(A=>A.ok===!1).length:0,c.notRunRows=m.ok===!1?Math.max(0,c.rowCount-I.length):0,c.filesWritten=$(m.filesWritten),c.touchedFiles=$(m.touchedFiles),c.moves=Array.isArray(m.renames)?m.renames.filter(h):[],c.rows=I,h(m.postMutation)&&(c.postMutation=m.postMutation),c.result=m,m.ok===!1&&(c.error=p(m.code)??le(I)??"FILE_RENAME_FAILED"),(0,w.writeFileRenameExecutionStatus)(e,c),m}catch(m){throw c.status="failed",c.phase="completed",c.failedRows=Math.max(1,c.failedRows),c.notRunRows=Math.max(0,c.rowCount-c.completedRows-c.failedRows),c.error=m instanceof Error?m.message:String(m),(0,w.writeFileRenameExecutionStatus)(e,c),m}}))),T=await(0,Y.waitForMutationDeadline)(P,o);return T.status==="result"?T.result:(P.catch(()=>{}),xe(e,a,u,d,Date.now()-R))}async function te(e,t,n,r,o,i,s,l){await(0,F.maybeDelayFileMutationForTest)(process.env[E.CLI_ENV.testFileRenameDelayMs]);const a=l??ie(e,t,r==="execute"||r==="apply"),u=a.execute?await ne(e,a,r==="apply"?"apply":"execute",n,o,s,void 0,i):be(a.operations),d=se(e,u,a,r,i,s);if((r==="preview"||r==="validate")&&d.ok!==!1){const c=(0,b.buildFileRenamePreviewId)(a.normalizedPayload),R=(0,b.readFileMoveStates)(a.operations),M=(0,b.buildFileRenamePreviewHash)(a.normalizedPayload,R,d);(0,b.writeFileRenamePreviewRecord)(e,{previewId:c,previewHash:M,createdAt:new Date().toISOString(),cwd:f.resolve(e),normalizedPayload:a.normalizedPayload,states:R,previewResult:d}),d.previewId=c,d.next=`aib file rename apply ${c}`}return(0,O.attachAgentText)(d,G(d))}async function ne(e,t,n,r,o,i,s,l){const a=[],u=new Set,d=new Set,c=[],R=ce(e,t.operations.map(y=>y.sourceFile));let M=[],P=null;for(const y of t.operations){s&&(s.phase="movingFile",s.status="running",q(e,s,a,u,d),await z());const C=await ve(e,y,r,o),L=Array.isArray(C.rows)&&h(C.rows[0])?C.rows[0]:v(y,"FILE_RENAME_FAILED","Extension did not return a file rename row.");a.push(L);for(const N of D(L.savedFiles))u.add(f.normalize(N));for(const N of D(L.touchedFiles))d.add(f.normalize(N));for(const N of Je(L.importSnapshotBefore))c.push(N);if(s&&(q(e,s,a,u,d),await z()),L.ok===!1)break;await(0,F.delayFileMutationForTest)(o.testRowDelayMs)}const T=a.every(y=>y.ok!==!1)&&a.length===t.operations.length;if(a.some(y=>y.ok!==!1)&&o.postProcessImports&&d.size>0){s&&(s.phase="postProcessImports",q(e,s,a,u,d),await z()),await(0,F.delayFileMutationForTest)(o.testImportPostProcessDelayMs);const y=await Ie(e,Array.from(d),c,r);M=Array.isArray(y.cleanup)?y.cleanup.filter(h):[];for(const C of D(y.savedFiles))u.add(f.normalize(C))}const m=M.every(y=>y.ok!==!1);if(T&&m){s&&(s.phase="postMutation.cycles",q(e,s,a,u,d),await z()),await nt(o.testPostMutationCyclesDelayMs);const y=ye([...Array.from(d),...Array.from(u)]),C=ce(e,y);P={cycles:Qe(R,C,new Set(pe(e,y)))}}const I=J({...!T||!m?{ok:!1}:{},operation:U.CLI_COMMAND_IDS.fileMutation,execute:!0,rowCount:t.operations.length,appliedCount:a.filter(y=>y.applied===!0).length,savedFiles:Array.from(u),touchedFiles:Array.from(d),cleanup:M,rows:a,postMutation:P}),A=se(e,I,t,n,l,i);return(0,O.attachAgentText)(A,G(A))}function q(e,t,n,r,o){const i=n.map(s=>ae(e,s));t.rows=i,t.completedRows=i.filter(s=>s.ok!==!1).length,t.failedRows=i.filter(s=>s.ok===!1).length,t.notRunRows=t.failedRows>0?Math.max(0,t.rowCount-i.length):0,t.filesWritten=Array.from(r).sort((s,l)=>s.localeCompare(l)).map(s=>g(e,s)),t.touchedFiles=Array.from(o).sort((s,l)=>s.localeCompare(l)).map(s=>g(e,s)),t.failedRows>0&&(t.status="failed",t.error=le(i)??"FILE_RENAME_FAILED"),(0,w.writeFileRenameExecutionStatus)(e,t)}async function ve(e,t,n,r){const o=await(0,B.resolveCompatibleTargetInstance)(e,U.CLI_COMMAND_IDS.fileMutation,n),i=n.importRules??(0,W.readConfigImportRules)(e),s=r.testFailRequiredImportUpdate,a={operations:[s?{...t,testFailRequiredImportUpdate:s}:t],execute:!0,importRules:(0,W.importRulesToJson)(i),postProcessImports:!1};return s&&(a.testFailRequiredImportUpdate=s),oe(o.entry,a,n)}async function Ie(e,t,n,r){const o=await(0,B.resolveCompatibleTargetInstance)(e,U.CLI_COMMAND_IDS.fileMutation,r),i=r.importRules??(0,W.readConfigImportRules)(e);return oe(o.entry,{action:"postProcessImports",files:t,importRules:(0,W.importRulesToJson)(i),importSnapshotBefore:n},r)}function Ce(e,t){const n=(0,w.readFileRenameExecutionStatus)(e,t),r={operation:"execution.status",executionId:n.executionId,status:n.status,phase:n.phase,summary:j(n),progress:`${n.completedRows}/${n.rowCount}`,filesWritten:n.filesWritten,touchedFiles:n.touchedFiles,...n.postMutation?{postMutation:n.postMutation}:{},updatedAt:n.updatedAt,...n.error?{error:n.error}:{}};return(0,O.attachAgentText)(r,Se(n))}function xe(e,t,n,r,o){const i=(0,w.readFileRenameExecutionStatus)(e,t),s=Math.max(0,r-o),l={operation:"execution.status",executionId:i.executionId,status:i.status,phase:i.phase,summary:j(i),progress:`${i.completedRows}/${i.rowCount}`,filesWritten:i.filesWritten,touchedFiles:i.touchedFiles,...i.postMutation?{postMutation:i.postMutation}:{},updatedAt:i.updatedAt,estimatedRemainingMs:s};return(0,O.attachAgentText)(l,Ae(n,i,s))}function Ae(e,t,n){return[`${e} ${t.executionId}`,j(t),re(t),n>0?`estimated remaining: ${(0,F.formatFileMutationDuration)(Math.max(n,5e3))}`:"estimated remaining: check status again soon"].join(`
2
- `)}function Se(e){const t=[j(e)];if(e.status==="running")return t.push(re(e)),t.join(`
3
- `);je(t,e);const n=e.rows.filter(o=>o.ok===!1),r=n[0];if(r){const o=p(r.code)??e.error??"FILE_RENAME_FAILED";t.push(`code: ${o}`),typeof r.error=="string"&&t.push(r.error),typeof r.rollback=="string"&&t.push(`rollback: ${r.rollback}`),typeof r.hint=="string"&&t.push(`hint: ${r.hint}`),t.push("failed:");for(const i of n)t.push(`${p(i.source)??"source"} -> ${p(i.target)??"target"}`)}else e.error&&t.push(e.error);return ze(t,e),e.filesWritten.length>0&&de(t,e.filesWritten,e.plannedMoves.map(o=>o.target)),h(e.postMutation)&&h(e.postMutation.cycles)&&he(t,e.postMutation.cycles),e.status==="failed"&&t.push("next: Fix failed rename row and rerun file.rename preview."),t.join(`
4
- `)}function re(e){return e.phase==="postProcessImports"?"updating imports":e.phase==="postMutation.cycles"?"checking cycles":"renaming files"}function j(e){const t=Math.floor(Math.max(0,e.completedRows)/Math.max(1,e.rowCount)*100);if(e.status==="completed")return`completed, ${e.completedRows}/${e.rowCount} rows, ${t}% files, ${e.filesWritten.length} files written`;if(e.status==="failed"){const n=[`failed, ${e.completedRows}/${e.rowCount} rows, ${t}% files`,`${e.failedRows} failed`];return e.notRunRows>0&&n.push(`${e.notRunRows} not run`),n.push(`${e.filesWritten.length} files written`),n.join(", ")}return`in progress, ${e.completedRows}/${e.rowCount} rows, ${t}% files`}async function oe(e,t,n){try{return await(0,Fe.postJson)(e,_e.EXTENSION_ROUTES.fileMutation,t,(0,B.extensionRequestOptions)(n))}catch(r){if(r instanceof S.CliError&&r.code==="REMOTE_ERROR"){const o=h(r.details)?r.details:{},i=h(o.payload)?o.payload:null;if(i)return i}throw r}}function ie(e,t,n){const r=Le(e,t.base),o=[],i=new Set;for(const s of t.renames){const l=Pe(e,r,s.source);V(e,l,"FILE_RENAME_SOURCE_OUTSIDE_CWD");const a=Te(e,r,l,s.target);V(e,a,"FILE_RENAME_TARGET_OUTSIDE_CWD");const u=tt(a);if(i.has(u))throw new S.CliError("FILE_RENAME_DUPLICATE_TARGET","Several file renames resolve to the same target.",{targetFile:g(e,a)});i.add(u),o.push({id:`rename-${o.length+1}`,kind:"fileRename",sourceFile:l,targetDir:f.dirname(a),targetFile:a,execute:n})}if(o.length===0)throw new S.CliError("FILE_RENAME_ROWS_REQUIRED","file rename expects at least one rename pair.");return{execute:n,baseDir:r,operations:o,normalizedPayload:{base:r,renames:ke(o),execute:n}}}function be(e){const t=[];for(const r of e){if(t.some(o=>o.ok===!1))break;t.push(De(r))}return{...t.every(r=>r.ok!==!1)&&t.length===e.length?{}:{ok:!1},operation:U.CLI_COMMAND_IDS.fileMutation,execute:!1,rowCount:e.length,appliedCount:0,savedFiles:[],rows:t}}function De(e){if(e.kind!=="fileRename")return v(e,"FILE_MUTATION_KIND_UNSUPPORTED",`Unsupported file mutation kind: ${e.kind}`);if(!_.existsSync(e.sourceFile))return v(e,"FILE_RENAME_SOURCE_NOT_FOUND","Source file does not exist.");try{if(!_.statSync(e.sourceFile).isFile())return v(e,"FILE_RENAME_SOURCE_DIRECTORY_UNSUPPORTED","file rename v1 supports files only, not directories.")}catch(t){return v(e,"FILE_RENAME_SOURCE_STAT_FAILED",t instanceof Error?t.message:String(t))}return _.existsSync(e.targetFile)?v(e,"FILE_RENAME_TARGET_EXISTS","Target file already exists.","Pick another target directory/name or remove the target collision."):$e(e.sourceFile)?v(e,"FILE_RENAME_SOURCE_ASSET_UNSUPPORTED","CSS/SCSS files cannot be renamed with file rename v1."):_.existsSync(e.targetDir)?{id:e.id,ok:!0,sourceFile:e.sourceFile,targetFile:e.targetFile,applied:!1}:v(e,"FILE_RENAME_TARGET_DIR_NOT_FOUND","Target parent directory does not exist.")}function v(e,t,n,r){return{id:e.id,ok:!1,sourceFile:e.sourceFile,targetFile:e.targetFile,applied:!1,code:t,error:n,...r?{hint:r}:{}}}function $e(e){return[".css",".scss"].includes(f.extname(e).toLowerCase())}function ke(e){return e.map(t=>({source:t.sourceFile,target:t.targetFile}))}function Pe(e,t,n){const r=n.trim();if(f.isAbsolute(r))return f.normalize(r);const o=f.normalize(f.resolve(t,r));if(_.existsSync(o))return o;const i=f.normalize(f.resolve(e,r));return _.existsSync(i)?i:o}function Te(e,t,n,r){const o=r.trim();return f.isAbsolute(o)?f.normalize(o):o.includes("/")||o.includes("\\")?f.normalize(f.resolve(t,o)):f.normalize(f.resolve(f.dirname(n),o))}function Le(e,t){const n=f.normalize(f.isAbsolute(t)?t:f.resolve(e,t));return V(e,n,"FILE_RENAME_PATH_OUTSIDE_CWD"),n}function V(e,t,n){const r=f.resolve(e),o=f.relative(r,t);if(!(o===""||!o.startsWith("..")&&!f.isAbsolute(o)))throw new S.CliError(n,"File move paths must stay inside the current workspace.",{cwd:r,filePath:t})}function se(e,t,n,r,o,i){const s=Array.isArray(t.rows)?t.rows.filter(h).map(R=>ae(e,R)):[],l=t.ok!==!1&&s.every(R=>R.ok!==!1),a=He(s,"target"),u=Ye(e,D(t.savedFiles)).map(R=>g(e,R)),d=r==="apply"?"file.rename.apply":n.execute?"file.rename.execute":"file.rename.preview";return J({...l?{}:{ok:!1},operation:d,executionId:i??null,base:g(e,n.baseDir),operationCount:n.operations.length,summary:l?n.execute?`${n.operations.length} ${k(n.operations.length,"file","files")} renamed, ${u.length} ${k(u.length,"file","files")} written`:`${n.operations.length} ${k(n.operations.length,"file","files")} ready`:Oe(s,n.operations.length,n.execute||r==="apply"),renames:Ne(e,n.operations),...n.execute||r==="apply"?{filesWritten:u,filesRenamed:a}:{},...h(t.postMutation)?{postMutation:t.postMutation}:{},rows:l?null:s,previewId:o??null})}function ae(e,t){return J({id:p(t.id),ok:t.ok!==!1,source:g(e,p(t.sourceFile)??""),target:g(e,p(t.targetFile)??""),applied:typeof t.applied=="boolean"?t.applied:null,rollback:p(t.rollback),savedFiles:Ze(D(t.savedFiles).map(n=>g(e,n)),5),code:p(t.code),error:p(t.error),hint:p(t.hint)})}function Ne(e,t){return t.map(n=>({source:g(e,n.sourceFile),target:g(e,n.targetFile)}))}function Oe(e,t,n){const r=e.filter(i=>i.ok===!1).length,o=Math.max(0,t-e.length);if(!n){const i=Math.min(t,e.length);return`${t} ${k(t,"file","files")}, validation blocked at row ${i}`}return`${t} ${k(t,"file","files")}, ${r} failed${o>0?`, ${o} not run`:""}`}function We(e,t){return t.map(n=>({source:g(e,n.sourceFile),target:g(e,n.targetFile),targetDir:g(e,n.targetDir)}))}function Ue(e){return Array.isArray(e.rows)?e.rows.filter(h):[]}function qe(e){const t=new Set(e.map(r=>r.targetDir));let n=0;for(const r of t)_.existsSync(r)||(n+=1);return{rowCount:e.length,targetDirCount:t.size,dirsToCreate:n}}function le(e){const t=e.find(n=>n.ok===!1);return t?p(t.code):null}function je(e,t){const n=new Set(t.rows.filter(o=>o.ok!==!1).map(o=>p(o.source)).filter(o=>!!o)),r=[];for(const o of t.plannedMoves)t.status!=="completed"&&!n.has(o.source)||r.push(`${o.source} -> ${o.target}`);if(r.length!==0){e.push("renames:");for(const o of r)e.push(o)}}function ze(e,t){if(t.notRunRows<=0)return;const n=new Set(t.rows.map(o=>p(o.source)).filter(o=>!!o)),r=t.plannedMoves.filter(o=>!n.has(o.source));if(r.length!==0){e.push("not run:");for(const o of r)e.push(o.source)}}function K(){return(0,Y.readMutationSyncWaitMs)(process.env[E.CLI_ENV.fileRenameSyncWaitMs],12e4)}function Be(){return{postProcessImports:(0,F.isFileMutationImportPostProcessEnabled)(),testFailRequiredImportUpdate:p(process.env[E.CLI_ENV.testFileRenameFailImports]),testRowDelayMs:(0,F.readFileMutationTestDelayMs)(process.env[E.CLI_ENV.testFileRenameRowDelayMs],6e4),testImportPostProcessDelayMs:(0,F.readFileMutationTestDelayMs)(process.env[E.CLI_ENV.testFileRenameImportsDelayMs],6e4),testPostMutationCyclesDelayMs:(0,F.readFileMutationTestDelayMs)(process.env[E.CLI_ENV.testPostMutationCyclesDelayMs],6e4)}}function Ve(){return(0,F.captureFileMutationBackgroundEnv)([E.CLI_ENV.testFileRenameDelayMs,E.CLI_ENV.testFileRenameRowDelayMs,E.CLI_ENV.testFileRenameImportsDelayMs,E.CLI_ENV.testFileRenameFailImports])}function G(e){const t=p(e.operation);if(!t?.startsWith("file.rename."))return null;const n=[],r=p(e.previewId),o=p(e.executionId);n.push(e.ok===!1?`${t} failed`:r&&t==="file.rename.preview"?`${t} ${r}`:o&&(t==="file.rename.apply"||t==="file.rename.execute")?`${t} ${o}`:t),typeof e.summary=="string"&&n.push(e.summary);const i=Array.isArray(e.renames)?e.renames.filter(h):[];if(i.length>0&&e.ok!==!1){n.push("renames:");for(const l of i){const a=p(l.source),u=p(l.target);a&&u&&n.push(`${a} -> ${u}`)}}Ke(n,e);const s=Array.isArray(e.filesWritten)?e.filesWritten:[];return s.length>0&&de(n,s,Array.isArray(e.filesRenamed)?e.filesRenamed:[]),h(e.postMutation)&&h(e.postMutation.cycles)&&he(n,e.postMutation.cycles),typeof e.next=="string"&&n.push(`next: ${e.next}`),n.join(`
5
- `)}function Ke(e,t){if(t.ok!==!1||!Array.isArray(t.rows))return;const n=t.rows.filter(h).find(r=>r.ok===!1);n&&(e.push("failed:"),e.push(`${p(n.source)??"source"} -> ${p(n.target)??"target"}`),e.push(`code: ${p(n.code)??"FILE_RENAME_FAILED"}`),typeof n.error=="string"&&e.push(n.error),typeof n.rollback=="string"&&e.push(`rollback: ${n.rollback}`),typeof n.hint=="string"&&e.push(`hint: ${n.hint}`))}function Ge(){return{ok:!0,command:"file rename",usage:"aib file rename preview --stdin | aib file rename execute --stdin | aib file rename apply <previewId>",dsl:["@base packages/agent-project-tooling/src","rename workspace-runner-cli.ts->cli.ts workspace-runner-command-hints.ts->command-hints.ts"],notes:["preview validates planned file renames without writing.","execute renames files and updates TypeScript imports.","apply uses the cached preview id and refuses stale source/target state."]}}function He(e,t){return e.map(n=>p(n[t])).filter(n=>!!n)}function D(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Je(e){return Array.isArray(e)?e.filter(h):[]}function ce(e,t){const n=pe(e,t).filter(o=>_.existsSync(me(e,o)));if(n.length===0)return{op:"cycles",componentCount:0,components:[]};const r=["cycles"];for(const o of n)r.push("--files",o);return r.push("--detail","imports","--limit","50"),(0,X.runInspectCycles)(e,r,void 0)}function Qe(e,t,n){const r=new Set(ue(e).map(fe)),o=ue(t).filter(i=>$(i.files).some(s=>n.has(s))&&!r.has(fe(i)));return{status:o.length>0?"new-or-changed":"none",detail:"imports",newOrChangedCount:o.length,preComponentCount:H(e.componentCount),postComponentCount:H(t.componentCount),components:o}}function ue(e){return(Array.isArray(e.components)?e.components:[]).filter(h).map(t=>({kind:p(t.kind)??"mixed",files:$(t.files).sort(),chain:p(t.chain)??"",...h(t.cycle)?{cycle:t.cycle}:{},imports:Xe(t)}))}function Xe(e){const t=h(e.cycle)?e.cycle:{};return $(t.imports)}function fe(e){return`${p(e.kind)??"mixed"}:${$(e.files).sort().join("|")}`}function pe(e,t){return ye(t.map(n=>g(e,me(e,n))))}function me(e,t){return f.normalize(f.isAbsolute(t)?t:f.resolve(e,t))}function $(e){return D(e)}function Ye(e,t){return t.filter(n=>{const r=f.isAbsolute(n)?n:f.resolve(e,n);return _.existsSync(r)})}function Ze(e,t){const n=Array.from(new Set(e)).sort((i,s)=>i.localeCompare(s)),r=n.slice(0,t),o=n.length-r.length;return o>0?[...r,`+ ${o} more`]:r}function rt(e,t){const n=e.slice(0,t),r=e.length-n.length;return r>0?`${n.join(", ")}, + ${r} more`:n.join(", ")}function de(e,t,n){const r=t.filter(u=>typeof u=="string");if(r.length===0)return;const o=new Set(n.filter(u=>typeof u=="string")),i=r.filter(u=>o.has(u)),s=r.filter(u=>!o.has(u)),l=s.slice(0,8),a=s.length-l.length;e.push("filesWritten:");for(const u of[...i,...l])e.push(u);a>0&&e.push(`+ ${a} reference ${k(a,"file","files")}`)}function he(e,t){e.push("cycles:");const n=H(t.newOrChangedCount);if(n===0){e.push("no new/changed cycles involving touched files");return}const r=Array.isArray(t.components)?t.components.filter(h):[];e.push(et(n,r)),r.forEach((o,i)=>{(0,X.appendCycleComponentText)(e,o,{detail:"imports",prefix:r.length===1?"":`${i+1}. `,indent:r.length===1?"":" "})})}function et(e,t){const n=t.map(i=>p(i.kind)??"mixed"),r=Array.from(new Set(n)),o=r.length===1?`${r[0]} `:"";return`${e} new/changed ${o}${e===1?"cycle":"cycles"} involving touched files`}function k(e,t,n){return e===1?t:n}function p(e){return typeof e=="string"&&e.length>0?e:null}function H(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function J(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t==null?!1:!(Array.isArray(t)&&t.length===0)))}function h(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tt(e){const t=f.normalize(e);return process.platform==="win32"?t.toLowerCase():t}function ye(e){return Array.from(new Set(e))}function z(){return new Promise(e=>setImmediate(e))}async function nt(e){e<=0||await new Promise(t=>setTimeout(t,e))}function g(e,t){return t?f.relative(e,t).replace(/\\/g,"/"):""}
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.runFileRename = runFileRename;
37
+ exports.runFileRenameExecutionWorker = runFileRenameExecutionWorker;
38
+ exports.readCachedFileRenameExecution = readCachedFileRenameExecution;
39
+ const fs = __importStar(require("node:fs"));
40
+ const path = __importStar(require("node:path"));
41
+ const node_child_process_1 = require("node:child_process");
42
+ const zod_1 = require("zod");
43
+ const env_vars_1 = require("../config/env-vars");
44
+ const agent_text_1 = require("../shared/agent-text");
45
+ const errors_1 = require("../shared/errors");
46
+ const inspect_cycles_1 = require("./inspect-cycles");
47
+ const mutation_eta_1 = require("./mutation-eta");
48
+ const file_rename_preview_cache_1 = require("./file-rename-preview-cache");
49
+ const file_rename_execution_cache_1 = require("./file-rename-execution-cache");
50
+ const file_mutation_runtime_1 = require("./file-mutation-runtime");
51
+ const mutation_execution_cache_1 = require("./mutation-execution-cache");
52
+ const mutate_child_execution_1 = require("./mutate-child-execution");
53
+ const file_mutation_worker_apply_1 = require("./file-mutation-worker-apply");
54
+ const file_impact_scan_1 = require("../mutation/file-impact-scan");
55
+ const runtime_lifecycle_1 = require("../session/runtime-lifecycle");
56
+ const FileRenamePayloadSchema = zod_1.z.object({
57
+ base: zod_1.z.string().min(1),
58
+ renames: zod_1.z.array(zod_1.z.object({
59
+ source: zod_1.z.string().min(1),
60
+ target: zod_1.z.string().min(1)
61
+ })).min(1),
62
+ execute: zod_1.z.boolean().optional()
63
+ });
64
+ async function runFileRename(cwd, rawPayload, options = {}, restArgs = []) {
65
+ const runtimeOptions = readFileRenameRuntimeOptions();
66
+ const action = restArgs[0] ?? "preview";
67
+ if (action === "help" || action === "--help") {
68
+ return FileRenameHelp();
69
+ }
70
+ if (action === "apply") {
71
+ const previewId = restArgs[1];
72
+ if (!previewId || previewId.startsWith("--")) {
73
+ throw new errors_1.CliError("FILE_RENAME_PREVIEW_ID_REQUIRED", "file rename apply expects a preview id.", {
74
+ usage: "aib file rename apply <previewId>"
75
+ });
76
+ }
77
+ return applyFileRenamePreview(cwd, previewId, options, runtimeOptions);
78
+ }
79
+ if (action !== "preview" && action !== "execute" && action !== "validate") {
80
+ throw new errors_1.CliError("UNKNOWN_FILE_RENAME_COMMAND", `Unknown file rename command: ${action}`, {
81
+ availableCommands: ["preview", "apply", "execute", "validate", "help"]
82
+ });
83
+ }
84
+ const payload = FileRenamePayloadSchema.parse(rawPayload);
85
+ if (action === "execute" && readFileRenameSyncWaitMs() > 0) {
86
+ return runFileRenamePayloadWithExecution(cwd, {
87
+ ...payload,
88
+ execute: true
89
+ }, options, "execute", readFileRenameSyncWaitMs(), runtimeOptions);
90
+ }
91
+ return runFileRenamePayload(cwd, {
92
+ ...payload,
93
+ execute: action === "execute"
94
+ }, options, action, runtimeOptions);
95
+ }
96
+ async function applyFileRenamePreview(cwd, previewId, options, runtimeOptions) {
97
+ const record = (0, file_rename_preview_cache_1.readFileRenamePreviewRecord)(cwd, previewId);
98
+ (0, file_rename_preview_cache_1.validateFileMoveStates)(record);
99
+ const payload = FileRenamePayloadSchema.parse({
100
+ ...record.normalizedPayload,
101
+ execute: true
102
+ });
103
+ const syncWaitMs = readFileRenameSyncWaitMs();
104
+ if (syncWaitMs > 0) {
105
+ return runFileRenamePayloadWithExecution(cwd, payload, options, "apply", syncWaitMs, runtimeOptions, previewId);
106
+ }
107
+ const result = await runFileRenamePayload(cwd, payload, options, "apply", runtimeOptions, previewId);
108
+ return result.ok === false
109
+ ? (0, agent_text_1.attachAgentText)({ ...result, next: "Fix the file rename request and rerun preview." }, formatFileRenameAgentText({ ...result, next: "Fix the file rename request and rerun preview." }))
110
+ : result;
111
+ }
112
+ async function runFileRenamePayloadWithExecution(cwd, payload, options, action, syncWaitMs, runtimeOptions, previewIdFromApply) {
113
+ const normalized = normalizePayload(cwd, payload, true);
114
+ const executionId = (0, file_rename_execution_cache_1.buildFileRenameExecutionId)();
115
+ const operation = `file.rename.${action}`;
116
+ const etaEstimate = (0, file_mutation_runtime_1.estimateFileMutationEta)(buildFileMutationEtaInput(cwd, normalized.operations));
117
+ const estimatedDurationMs = etaEstimate.selectedMs;
118
+ const status = (0, file_rename_execution_cache_1.createFileRenameExecutionStatus)(cwd, executionId, operation, buildPlannedMoves(cwd, normalized.operations));
119
+ (0, file_rename_execution_cache_1.writeFileRenameExecutionStatus)(cwd, status);
120
+ const startedAtMs = Date.now();
121
+ const backgroundEnv = captureFileRenameBackgroundEnv();
122
+ const workerInputPath = writeFileRenameWorkerInput(cwd, executionId, {
123
+ schemaVersion: 1,
124
+ cwd,
125
+ payload,
126
+ normalized,
127
+ options: serializeResolveTargetInstanceOptions(options),
128
+ action,
129
+ runtimeOptions,
130
+ executionId,
131
+ status,
132
+ previewIdFromApply: previewIdFromApply ?? null
133
+ });
134
+ const workerPid = startFileRenameWorkerProcess(cwd, workerInputPath, backgroundEnv);
135
+ if (workerPid === null) {
136
+ return failFileRenameWorkerStart(cwd, status, "FILE_RENAME_WORKER_START_FAILED", "File rename worker did not publish a process id.");
137
+ }
138
+ const publicationFailure = await (0, mutate_child_execution_1.awaitFileMutationWorkerPublication)({
139
+ cwd,
140
+ executionId,
141
+ kind: "file.rename",
142
+ operation,
143
+ workerPid
144
+ });
145
+ if (publicationFailure) {
146
+ return publicationFailure;
147
+ }
148
+ const result = await waitForFileRenameWorkerResult(cwd, executionId, syncWaitMs);
149
+ if (result) {
150
+ return result;
151
+ }
152
+ const finalStatus = (0, file_rename_execution_cache_1.tryReadFileRenameExecutionStatus)(cwd, executionId);
153
+ if (finalStatus && finalStatus.status !== "running") {
154
+ return isObject(finalStatus.result)
155
+ ? finalStatus.result
156
+ : readCachedFileRenameExecution(cwd, executionId);
157
+ }
158
+ return buildFileRenameStillRunningResponse(cwd, executionId, operation, workerPid, estimatedDurationMs, Date.now() - startedAtMs, etaEstimate);
159
+ }
160
+ async function runFileRenameExecutionWorker(input) {
161
+ const status = input.status;
162
+ status.workerPid = process.pid;
163
+ (0, file_rename_execution_cache_1.writeFileRenameExecutionStatus)(input.cwd, status);
164
+ try {
165
+ const result = await executeFileRenameOperations(input.cwd, input.normalized, input.action, input.options, input.runtimeOptions, input.executionId, status, input.previewIdFromApply ?? undefined);
166
+ const rows = readFileRenameRows(result);
167
+ status.status = result.ok === false ? "failed" : "completed";
168
+ status.phase = "completed";
169
+ status.completedRows = result.ok === false ? rows.filter((row) => row.ok !== false).length : status.rowCount;
170
+ status.failedRows = result.ok === false ? rows.filter((row) => row.ok === false).length : 0;
171
+ status.notRunRows = result.ok === false ? Math.max(0, status.rowCount - rows.length) : 0;
172
+ status.filesWritten = readStringArray(result.filesWritten);
173
+ status.touchedFiles = readStringArray(result.touchedFiles);
174
+ status.moves = Array.isArray(result.renames) ? result.renames.filter(isObject) : [];
175
+ status.rows = rows;
176
+ if (isObject(result.postMutation)) {
177
+ status.postMutation = result.postMutation;
178
+ }
179
+ status.result = result;
180
+ if (result.ok === false) {
181
+ status.error = readString(result.code) ?? readFirstFailedCode(rows) ?? "FILE_RENAME_FAILED";
182
+ }
183
+ (0, file_rename_execution_cache_1.writeFileRenameExecutionStatus)(input.cwd, status);
184
+ return result;
185
+ }
186
+ catch (error) {
187
+ status.status = "failed";
188
+ status.phase = "completed";
189
+ status.failedRows = Math.max(1, status.failedRows);
190
+ status.notRunRows = Math.max(0, status.rowCount - status.completedRows - status.failedRows);
191
+ status.error = error instanceof Error ? error.message : String(error);
192
+ (0, file_rename_execution_cache_1.writeFileRenameExecutionStatus)(input.cwd, status);
193
+ throw error;
194
+ }
195
+ }
196
+ function writeFileRenameWorkerInput(cwd, executionId, input) {
197
+ const filePath = path.join(fileRenameWorkerDir(cwd, executionId), "worker-input.json");
198
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
199
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
200
+ fs.writeFileSync(tmpPath, `${JSON.stringify(input, null, 2)}\n`);
201
+ fs.renameSync(tmpPath, filePath);
202
+ return filePath;
203
+ }
204
+ function fileRenameWorkerDir(cwd, executionId) {
205
+ return path.join(cwd, ".tmp", "aib-file-rename-workers", executionId.replace(/[^a-z0-9_-]+/gi, "-"));
206
+ }
207
+ function startFileRenameWorkerProcess(cwd, inputPath, envPatch) {
208
+ const env = { ...process.env };
209
+ for (const [key, value] of Object.entries(envPatch)) {
210
+ if (value === undefined) {
211
+ delete env[key];
212
+ }
213
+ else {
214
+ env[key] = value;
215
+ }
216
+ }
217
+ const child = (0, node_child_process_1.spawn)(process.execPath, [path.join(__dirname, "file-rename-worker.js"), inputPath], {
218
+ cwd,
219
+ env,
220
+ detached: true,
221
+ stdio: "ignore",
222
+ windowsHide: true
223
+ });
224
+ child.on("error", () => undefined);
225
+ (0, runtime_lifecycle_1.trackSessionOwnedProcess)(child, "file-rename-worker");
226
+ child.unref();
227
+ return child.pid ?? null;
228
+ }
229
+ async function waitForFileRenameWorkerResult(cwd, executionId, syncWaitMs) {
230
+ if (syncWaitMs <= 0) {
231
+ return null;
232
+ }
233
+ const deadline = Date.now() + syncWaitMs;
234
+ while (Date.now() < deadline) {
235
+ const status = (0, file_rename_execution_cache_1.tryReadFileRenameExecutionStatus)(cwd, executionId);
236
+ if (status && isFinalFileRenameWorkerStatus(status)) {
237
+ return isObject(status.result)
238
+ ? status.result
239
+ : readCachedFileRenameExecution(cwd, executionId);
240
+ }
241
+ await new Promise((resolve) => setTimeout(resolve, 100));
242
+ }
243
+ const finalStatus = (0, file_rename_execution_cache_1.tryReadFileRenameExecutionStatus)(cwd, executionId);
244
+ if (finalStatus && isFinalFileRenameWorkerStatus(finalStatus)) {
245
+ return isObject(finalStatus.result)
246
+ ? finalStatus.result
247
+ : readCachedFileRenameExecution(cwd, executionId);
248
+ }
249
+ return null;
250
+ }
251
+ function isFinalFileRenameWorkerStatus(status) {
252
+ return isObject(status.result) || status.phase === "completed";
253
+ }
254
+ function serializeResolveTargetInstanceOptions(options) {
255
+ return {
256
+ ...(options.metricsEnabled !== undefined ? { metricsEnabled: options.metricsEnabled } : {}),
257
+ ...(options.importRules ? { importRules: options.importRules } : {}),
258
+ ...(options.mutationComments ? { mutationComments: options.mutationComments } : {})
259
+ };
260
+ }
261
+ async function runFileRenamePayload(cwd, payload, options, action, runtimeOptions, previewIdFromApply, executionId, normalizedFromExecution) {
262
+ await (0, file_mutation_runtime_1.maybeDelayFileMutationForTest)(process.env[env_vars_1.CLI_ENV.testFileRenameDelayMs]);
263
+ const normalized = normalizedFromExecution ?? normalizePayload(cwd, payload, action === "execute" || action === "apply");
264
+ const result = normalized.execute
265
+ ? await executeFileRenameOperations(cwd, normalized, action === "apply" ? "apply" : "execute", options, runtimeOptions, executionId, undefined, previewIdFromApply)
266
+ : buildLocalFileRenamePreviewResult(normalized.operations);
267
+ const response = compactFileRenameResponse(cwd, result, normalized, action, previewIdFromApply, executionId);
268
+ if ((action === "preview" || action === "validate") && response.ok !== false) {
269
+ const previewId = (0, file_rename_preview_cache_1.buildFileRenamePreviewId)(normalized.normalizedPayload);
270
+ const states = (0, file_rename_preview_cache_1.readFileMoveStates)(normalized.operations);
271
+ const previewHash = (0, file_rename_preview_cache_1.buildFileRenamePreviewHash)(normalized.normalizedPayload, states, response);
272
+ (0, file_rename_preview_cache_1.writeFileRenamePreviewRecord)(cwd, {
273
+ previewId,
274
+ previewHash,
275
+ createdAt: new Date().toISOString(),
276
+ cwd: path.resolve(cwd),
277
+ normalizedPayload: normalized.normalizedPayload,
278
+ states,
279
+ previewResult: response
280
+ });
281
+ response.previewId = previewId;
282
+ response.next = `aib file rename apply ${previewId}`;
283
+ }
284
+ return (0, agent_text_1.attachAgentText)(response, formatFileRenameAgentText(response));
285
+ }
286
+ async function executeFileRenameOperations(cwd, normalized, action, options, runtimeOptions, executionId, status, previewIdFromApply) {
287
+ const rawRows = [];
288
+ const filesWritten = new Set();
289
+ const touchedFiles = new Set();
290
+ const importSnapshotBefore = [];
291
+ const preMutationCycles = runPostMutationCyclesSnapshot(cwd, normalized.operations.map((operation) => operation.sourceFile));
292
+ let cleanup = [];
293
+ let postMutation = null;
294
+ for (const operation of normalized.operations) {
295
+ if (status) {
296
+ status.phase = "movingFile";
297
+ status.status = "running";
298
+ persistFileRenameExecutionProgress(cwd, status, rawRows, filesWritten, touchedFiles);
299
+ await yieldToEventLoop();
300
+ }
301
+ const rowResult = await (0, file_mutation_worker_apply_1.executeWorkerOwnedFileMutationRow)(cwd, operation, options, runtimeOptions);
302
+ const row = Array.isArray(rowResult.rows) && isObject(rowResult.rows[0])
303
+ ? rowResult.rows[0]
304
+ : localFailureRow(operation, "FILE_RENAME_FAILED", "Extension did not return a file rename row.");
305
+ rawRows.push(row);
306
+ for (const savedFile of collectStringArray(row.savedFiles)) {
307
+ filesWritten.add(path.normalize(savedFile));
308
+ }
309
+ for (const touchedFile of collectStringArray(row.touchedFiles)) {
310
+ touchedFiles.add(path.normalize(touchedFile));
311
+ }
312
+ for (const snapshot of collectImportSnapshots(row.importSnapshotBefore)) {
313
+ importSnapshotBefore.push(snapshot);
314
+ }
315
+ for (const cleanupRow of collectImportSnapshots(row.cleanup)) {
316
+ cleanup.push(cleanupRow);
317
+ }
318
+ if (status) {
319
+ persistFileRenameExecutionProgress(cwd, status, rawRows, filesWritten, touchedFiles);
320
+ await yieldToEventLoop();
321
+ }
322
+ if (row.ok === false) {
323
+ break;
324
+ }
325
+ await (0, file_mutation_runtime_1.delayFileMutationForTest)(runtimeOptions.testRowDelayMs);
326
+ }
327
+ const rowsOk = rawRows.every((row) => row.ok !== false) && rawRows.length === normalized.operations.length;
328
+ const cleanupOk = cleanup.every((row) => row.ok !== false);
329
+ if (rowsOk && cleanupOk) {
330
+ if (status) {
331
+ status.phase = "postMutation.cycles";
332
+ persistFileRenameExecutionProgress(cwd, status, rawRows, filesWritten, touchedFiles);
333
+ await yieldToEventLoop();
334
+ }
335
+ await maybeDelayPostMutationCycles(runtimeOptions.testPostMutationCyclesDelayMs);
336
+ const postMutationFocusFiles = uniqueStrings([...Array.from(touchedFiles), ...Array.from(filesWritten)]);
337
+ const postMutationCycles = runPostMutationCyclesSnapshot(cwd, postMutationFocusFiles);
338
+ postMutation = {
339
+ cycles: diffPostMutationCycles(preMutationCycles, postMutationCycles, new Set(formatCycleFocusFiles(cwd, postMutationFocusFiles)))
340
+ };
341
+ }
342
+ const rawResult = compactObject({
343
+ ...(!rowsOk || !cleanupOk ? { ok: false } : {}),
344
+ operation: "fileMutation",
345
+ execute: true,
346
+ rowCount: normalized.operations.length,
347
+ appliedCount: rawRows.filter((row) => row.applied === true).length,
348
+ savedFiles: Array.from(filesWritten),
349
+ touchedFiles: Array.from(touchedFiles),
350
+ cleanup,
351
+ rows: rawRows,
352
+ postMutation
353
+ });
354
+ const response = compactFileRenameResponse(cwd, rawResult, normalized, action, previewIdFromApply, executionId);
355
+ return (0, agent_text_1.attachAgentText)(response, formatFileRenameAgentText(response));
356
+ }
357
+ function persistFileRenameExecutionProgress(cwd, status, rawRows, filesWritten, touchedFiles) {
358
+ const compactRows = rawRows.map((row) => compactRow(cwd, row));
359
+ status.rows = compactRows;
360
+ status.completedRows = compactRows.filter((row) => row.ok !== false).length;
361
+ status.failedRows = compactRows.filter((row) => row.ok === false).length;
362
+ status.notRunRows = status.failedRows > 0 ? Math.max(0, status.rowCount - compactRows.length) : 0;
363
+ status.filesWritten = Array.from(filesWritten).sort((left, right) => left.localeCompare(right)).map((file) => formatRelativePath(cwd, file));
364
+ status.touchedFiles = Array.from(touchedFiles).sort((left, right) => left.localeCompare(right)).map((file) => formatRelativePath(cwd, file));
365
+ if (status.failedRows > 0) {
366
+ status.status = "failed";
367
+ status.error = readFirstFailedCode(compactRows) ?? "FILE_RENAME_FAILED";
368
+ }
369
+ (0, file_rename_execution_cache_1.writeFileRenameExecutionStatus)(cwd, status);
370
+ }
371
+ function readCachedFileRenameExecution(cwd, executionId) {
372
+ const status = (0, file_rename_execution_cache_1.readFileRenameExecutionStatus)(cwd, executionId);
373
+ const response = {
374
+ operation: "execution.status",
375
+ executionId: status.executionId,
376
+ status: status.status,
377
+ phase: status.phase,
378
+ summary: buildFileRenameExecutionSummary(status),
379
+ progress: `${status.completedRows}/${status.rowCount}`,
380
+ filesWritten: status.filesWritten,
381
+ touchedFiles: status.touchedFiles,
382
+ ...(status.postMutation ? { postMutation: status.postMutation } : {}),
383
+ updatedAt: status.updatedAt,
384
+ ...(status.error ? { error: status.error } : {})
385
+ };
386
+ return (0, agent_text_1.attachAgentText)(response, formatFileRenameExecutionStatusText(status));
387
+ }
388
+ function buildFileRenameStillRunningResponse(cwd, executionId, operation, workerPid, estimatedDurationMs, elapsedMs, estimate = null) {
389
+ const status = (0, file_rename_execution_cache_1.readFileRenameExecutionStatus)(cwd, executionId);
390
+ const estimatedRemainingMs = Math.max(0, estimatedDurationMs - elapsedMs);
391
+ const eta = (0, mutation_eta_1.buildMutationEtaHint)(status.executionId, estimatedRemainingMs);
392
+ const response = {
393
+ operation: "execution.status",
394
+ executionId: status.executionId,
395
+ childExecutionKind: "file.rename",
396
+ childOperation: operation,
397
+ childCacheNamespace: file_rename_execution_cache_1.FILE_RENAME_EXECUTION_NAMESPACE,
398
+ childWorkerPid: workerPid,
399
+ status: status.status,
400
+ phase: status.phase,
401
+ summary: buildFileRenameExecutionSummary(status),
402
+ progress: `${status.completedRows}/${status.rowCount}`,
403
+ filesWritten: status.filesWritten,
404
+ touchedFiles: status.touchedFiles,
405
+ ...(status.postMutation ? { postMutation: status.postMutation } : {}),
406
+ updatedAt: status.updatedAt,
407
+ ...(estimate ? { eta: estimate } : {}),
408
+ estimatedRemainingMs: eta.estimatedRemainingMs,
409
+ suggestedFirstCheckMs: eta.suggestedFirstCheckMs,
410
+ next: eta.next
411
+ };
412
+ return (0, agent_text_1.attachAgentText)(response, formatFileRenameStillRunningText(operation, status, eta));
413
+ }
414
+ function failFileRenameWorkerStart(cwd, status, code, error) {
415
+ const result = {
416
+ ok: false,
417
+ operation: status.operation,
418
+ executionId: status.executionId,
419
+ code,
420
+ error,
421
+ filesWritten: [],
422
+ filesTouched: []
423
+ };
424
+ status.status = "failed";
425
+ status.phase = "completed";
426
+ status.failedRows = Math.max(1, status.failedRows);
427
+ status.notRunRows = Math.max(0, status.rowCount - status.completedRows - status.failedRows);
428
+ status.error = code;
429
+ status.result = result;
430
+ (0, file_rename_execution_cache_1.writeFileRenameExecutionStatus)(cwd, status);
431
+ return result;
432
+ }
433
+ function formatFileRenameStillRunningText(operation, status, eta) {
434
+ return [
435
+ `${operation} ${status.executionId}`,
436
+ buildFileRenameExecutionSummary(status),
437
+ formatFileRenamePhaseLine(status),
438
+ ...(0, mutation_eta_1.formatMutationEtaLines)(eta)
439
+ ].join("\n");
440
+ }
441
+ function formatFileRenameExecutionStatusText(status) {
442
+ const lines = [
443
+ buildFileRenameExecutionSummary(status)
444
+ ];
445
+ if (status.status === "running") {
446
+ lines.push(formatFileRenamePhaseLine(status));
447
+ return lines.join("\n");
448
+ }
449
+ appendExecutionRenameLines(lines, status);
450
+ const failedRows = status.rows.filter((row) => row.ok === false);
451
+ const firstFailed = failedRows[0];
452
+ if (firstFailed) {
453
+ const code = readString(firstFailed.code) ?? status.error ?? "FILE_RENAME_FAILED";
454
+ lines.push(`code: ${code}`);
455
+ if (typeof firstFailed.error === "string") {
456
+ lines.push(firstFailed.error);
457
+ }
458
+ if (typeof firstFailed.rollback === "string") {
459
+ lines.push(`rollback: ${firstFailed.rollback}`);
460
+ }
461
+ if (typeof firstFailed.hint === "string") {
462
+ lines.push(`hint: ${firstFailed.hint}`);
463
+ }
464
+ lines.push("failed:");
465
+ for (const row of failedRows) {
466
+ lines.push(`${readString(row.source) ?? "source"} -> ${readString(row.target) ?? "target"}`);
467
+ }
468
+ }
469
+ else if (status.error) {
470
+ lines.push(status.error);
471
+ }
472
+ appendExecutionNotRunLines(lines, status);
473
+ if (status.filesWritten.length > 0) {
474
+ appendFilesWrittenLines(lines, status.filesWritten, status.plannedMoves.map((move) => move.target));
475
+ }
476
+ if (isObject(status.postMutation) && isObject(status.postMutation.cycles)) {
477
+ appendPostMutationCyclesText(lines, status.postMutation.cycles);
478
+ }
479
+ if (status.status === "failed") {
480
+ lines.push("next: Fix failed rename row and rerun file.rename preview.");
481
+ }
482
+ return lines.join("\n");
483
+ }
484
+ function formatFileRenamePhaseLine(status) {
485
+ if (status.phase === "postProcessImports") {
486
+ return "updating imports";
487
+ }
488
+ if (status.phase === "postMutation.cycles") {
489
+ return "checking cycles";
490
+ }
491
+ return "renaming files";
492
+ }
493
+ function buildFileRenameExecutionSummary(status) {
494
+ const percent = Math.floor((Math.max(0, status.completedRows) / Math.max(1, status.rowCount)) * 100);
495
+ if (status.status === "completed") {
496
+ return `completed, ${status.completedRows}/${status.rowCount} rows, ${percent}% files, ${status.filesWritten.length} files written`;
497
+ }
498
+ if (status.status === "failed") {
499
+ const parts = [
500
+ `failed, ${status.completedRows}/${status.rowCount} rows, ${percent}% files`,
501
+ `${status.failedRows} failed`
502
+ ];
503
+ if (status.notRunRows > 0) {
504
+ parts.push(`${status.notRunRows} not run`);
505
+ }
506
+ parts.push(`${status.filesWritten.length} files written`);
507
+ return parts.join(", ");
508
+ }
509
+ return `in progress, ${status.completedRows}/${status.rowCount} rows, ${percent}% files`;
510
+ }
511
+ function normalizePayload(cwd, payload, execute) {
512
+ const baseDir = resolveInsideCwd(cwd, payload.base);
513
+ const operations = [];
514
+ const seenTargets = new Set();
515
+ for (const rename of payload.renames) {
516
+ const sourceFile = resolveSourceFile(cwd, baseDir, rename.source);
517
+ assertInsideCwd(cwd, sourceFile, "FILE_RENAME_SOURCE_OUTSIDE_CWD");
518
+ const targetFile = resolveRenameTargetFile(cwd, baseDir, sourceFile, rename.target);
519
+ assertInsideCwd(cwd, targetFile, "FILE_RENAME_TARGET_OUTSIDE_CWD");
520
+ const targetKey = normalizeKey(targetFile);
521
+ if (seenTargets.has(targetKey)) {
522
+ throw new errors_1.CliError("FILE_RENAME_DUPLICATE_TARGET", "Several file renames resolve to the same target.", {
523
+ targetFile: formatRelativePath(cwd, targetFile)
524
+ });
525
+ }
526
+ seenTargets.add(targetKey);
527
+ operations.push({
528
+ id: `rename-${operations.length + 1}`,
529
+ kind: "fileRename",
530
+ sourceFile,
531
+ targetDir: path.dirname(targetFile),
532
+ targetFile,
533
+ execute
534
+ });
535
+ }
536
+ if (operations.length === 0) {
537
+ throw new errors_1.CliError("FILE_RENAME_ROWS_REQUIRED", "file rename expects at least one rename pair.");
538
+ }
539
+ return {
540
+ execute,
541
+ baseDir,
542
+ operations,
543
+ normalizedPayload: {
544
+ base: baseDir,
545
+ renames: normalizedPayloadRenames(operations),
546
+ execute
547
+ }
548
+ };
549
+ }
550
+ function buildLocalFileRenamePreviewResult(operations) {
551
+ const rows = [];
552
+ for (const operation of operations) {
553
+ if (rows.some((row) => row.ok === false)) {
554
+ break;
555
+ }
556
+ rows.push(validateLocalMoveOperation(operation));
557
+ }
558
+ const ok = rows.every((row) => row.ok !== false) && rows.length === operations.length;
559
+ return {
560
+ ...(ok ? {} : { ok: false }),
561
+ operation: "fileMutation",
562
+ execute: false,
563
+ rowCount: operations.length,
564
+ appliedCount: 0,
565
+ savedFiles: [],
566
+ rows
567
+ };
568
+ }
569
+ function validateLocalMoveOperation(operation) {
570
+ if (operation.kind !== "fileRename") {
571
+ return localFailureRow(operation, "FILE_MUTATION_KIND_UNSUPPORTED", `Unsupported file mutation kind: ${operation.kind}`);
572
+ }
573
+ if (!fs.existsSync(operation.sourceFile)) {
574
+ return localFailureRow(operation, "FILE_RENAME_SOURCE_NOT_FOUND", "Source file does not exist.");
575
+ }
576
+ try {
577
+ const stat = fs.statSync(operation.sourceFile);
578
+ if (!stat.isFile()) {
579
+ return localFailureRow(operation, "FILE_RENAME_SOURCE_DIRECTORY_UNSUPPORTED", "file rename v1 supports files only, not directories.");
580
+ }
581
+ }
582
+ catch (error) {
583
+ return localFailureRow(operation, "FILE_RENAME_SOURCE_STAT_FAILED", error instanceof Error ? error.message : String(error));
584
+ }
585
+ if (fs.existsSync(operation.targetFile)) {
586
+ return localFailureRow(operation, "FILE_RENAME_TARGET_EXISTS", "Target file already exists.", "Pick another target directory/name or remove the target collision.");
587
+ }
588
+ if (isCssLikeAsset(operation.sourceFile)) {
589
+ return localFailureRow(operation, "FILE_RENAME_SOURCE_ASSET_UNSUPPORTED", "CSS/SCSS files cannot be renamed with file rename v1.");
590
+ }
591
+ if (!fs.existsSync(operation.targetDir)) {
592
+ return localFailureRow(operation, "FILE_RENAME_TARGET_DIR_NOT_FOUND", "Target parent directory does not exist.");
593
+ }
594
+ return {
595
+ id: operation.id,
596
+ ok: true,
597
+ sourceFile: operation.sourceFile,
598
+ targetFile: operation.targetFile,
599
+ applied: false
600
+ };
601
+ }
602
+ function localFailureRow(operation, code, error, hint) {
603
+ return {
604
+ id: operation.id,
605
+ ok: false,
606
+ sourceFile: operation.sourceFile,
607
+ targetFile: operation.targetFile,
608
+ applied: false,
609
+ code,
610
+ error,
611
+ ...(hint ? { hint } : {})
612
+ };
613
+ }
614
+ function isCssLikeAsset(filePath) {
615
+ return [".css", ".scss"].includes(path.extname(filePath).toLowerCase());
616
+ }
617
+ function normalizedPayloadRenames(operations) {
618
+ return operations.map((operation) => ({
619
+ source: operation.sourceFile,
620
+ target: operation.targetFile
621
+ }));
622
+ }
623
+ function resolveSourceFile(cwd, baseDir, rawPath) {
624
+ const trimmed = rawPath.trim();
625
+ if (path.isAbsolute(trimmed)) {
626
+ return path.normalize(trimmed);
627
+ }
628
+ const baseRelative = path.normalize(path.resolve(baseDir, trimmed));
629
+ if (fs.existsSync(baseRelative)) {
630
+ return baseRelative;
631
+ }
632
+ const cwdRelative = path.normalize(path.resolve(cwd, trimmed));
633
+ if (fs.existsSync(cwdRelative)) {
634
+ return cwdRelative;
635
+ }
636
+ return baseRelative;
637
+ }
638
+ function resolveRenameTargetFile(cwd, baseDir, sourceFile, rawTarget) {
639
+ const trimmed = rawTarget.trim();
640
+ if (path.isAbsolute(trimmed)) {
641
+ return path.normalize(trimmed);
642
+ }
643
+ if (trimmed.includes("/") || trimmed.includes("\\")) {
644
+ return path.normalize(path.resolve(baseDir, trimmed));
645
+ }
646
+ return path.normalize(path.resolve(path.dirname(sourceFile), trimmed));
647
+ }
648
+ function resolveInsideCwd(cwd, rawPath) {
649
+ const resolved = path.normalize(path.isAbsolute(rawPath) ? rawPath : path.resolve(cwd, rawPath));
650
+ assertInsideCwd(cwd, resolved, "FILE_RENAME_PATH_OUTSIDE_CWD");
651
+ return resolved;
652
+ }
653
+ function assertInsideCwd(cwd, filePath, code) {
654
+ const root = path.resolve(cwd);
655
+ const relative = path.relative(root, filePath);
656
+ if (relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))) {
657
+ return;
658
+ }
659
+ throw new errors_1.CliError(code, "File move paths must stay inside the current workspace.", {
660
+ cwd: root,
661
+ filePath
662
+ });
663
+ }
664
+ function compactFileRenameResponse(cwd, raw, normalized, action, previewIdFromApply, executionId) {
665
+ const rows = Array.isArray(raw.rows)
666
+ ? raw.rows.filter(isObject).map((row) => compactRow(cwd, row))
667
+ : [];
668
+ const ok = raw.ok !== false && rows.every((row) => row.ok !== false);
669
+ const renamedFiles = collectRows(rows, "target");
670
+ const filesWritten = collectExistingFiles(cwd, collectStringArray(raw.savedFiles)).map((file) => formatRelativePath(cwd, file));
671
+ const operation = action === "apply"
672
+ ? "file.rename.apply"
673
+ : normalized.execute
674
+ ? "file.rename.execute"
675
+ : "file.rename.preview";
676
+ const response = compactObject({
677
+ ...(ok ? {} : { ok: false }),
678
+ operation,
679
+ executionId: executionId ?? null,
680
+ base: formatRelativePath(cwd, normalized.baseDir),
681
+ operationCount: normalized.operations.length,
682
+ summary: ok
683
+ ? normalized.execute
684
+ ? `${normalized.operations.length} ${plural(normalized.operations.length, "file", "files")} renamed, ${filesWritten.length} ${plural(filesWritten.length, "file", "files")} written`
685
+ : `${normalized.operations.length} ${plural(normalized.operations.length, "file", "files")} ready`
686
+ : buildFailureSummary(rows, normalized.operations.length, normalized.execute || action === "apply"),
687
+ renames: formatRenamePairs(cwd, normalized.operations),
688
+ ...(normalized.execute || action === "apply" ? { filesWritten, filesRenamed: renamedFiles } : {}),
689
+ ...(isObject(raw.postMutation) ? { postMutation: raw.postMutation } : {}),
690
+ rows: ok ? null : rows,
691
+ previewId: previewIdFromApply ?? null
692
+ });
693
+ return response;
694
+ }
695
+ function compactRow(cwd, row) {
696
+ return compactObject({
697
+ id: readString(row.id),
698
+ ok: row.ok !== false,
699
+ source: formatRelativePath(cwd, readString(row.sourceFile) ?? ""),
700
+ target: formatRelativePath(cwd, readString(row.targetFile) ?? ""),
701
+ applied: typeof row.applied === "boolean" ? row.applied : null,
702
+ rollback: readString(row.rollback),
703
+ savedFiles: compactList(collectStringArray(row.savedFiles).map((file) => formatRelativePath(cwd, file)), 5),
704
+ code: readString(row.code),
705
+ error: readString(row.error),
706
+ hint: readString(row.hint)
707
+ });
708
+ }
709
+ function formatRenamePairs(cwd, operations) {
710
+ return operations.map((operation) => ({
711
+ source: formatRelativePath(cwd, operation.sourceFile),
712
+ target: formatRelativePath(cwd, operation.targetFile)
713
+ }));
714
+ }
715
+ function buildFailureSummary(rows, total, executed) {
716
+ const failed = rows.filter((row) => row.ok === false).length;
717
+ const notRun = Math.max(0, total - rows.length);
718
+ if (!executed) {
719
+ const checked = Math.min(total, rows.length);
720
+ return `${total} ${plural(total, "file", "files")}, validation blocked at row ${checked}`;
721
+ }
722
+ return `${total} ${plural(total, "file", "files")}, ${failed} failed${notRun > 0 ? `, ${notRun} not run` : ""}`;
723
+ }
724
+ function buildPlannedMoves(cwd, operations) {
725
+ return operations.map((operation) => ({
726
+ source: formatRelativePath(cwd, operation.sourceFile),
727
+ target: formatRelativePath(cwd, operation.targetFile),
728
+ targetDir: formatRelativePath(cwd, operation.targetDir)
729
+ }));
730
+ }
731
+ function readFileRenameRows(result) {
732
+ return Array.isArray(result.rows) ? result.rows.filter(isObject) : [];
733
+ }
734
+ function buildFileMutationEtaInput(cwd, operations) {
735
+ const targetDirs = new Set(operations.map((operation) => operation.targetDir));
736
+ let dirsToCreate = 0;
737
+ for (const targetDir of targetDirs) {
738
+ if (!fs.existsSync(targetDir)) {
739
+ dirsToCreate += 1;
740
+ }
741
+ }
742
+ const impact = (0, file_impact_scan_1.estimateFileMutationImpact)(cwd, operations.map((operation) => operation.sourceFile));
743
+ return {
744
+ rowCount: operations.length,
745
+ targetDirCount: targetDirs.size,
746
+ dirsToCreate,
747
+ importingFileCount: impact.importingFileCount,
748
+ importStatementCount: impact.importStatementCount,
749
+ barrelExportCount: impact.barrelExportCount,
750
+ sourceFileCount: impact.sourceFileCount,
751
+ existingSourceFileCount: impact.existingSourceFileCount,
752
+ scanTruncated: impact.truncated
753
+ };
754
+ }
755
+ function readFirstFailedCode(rows) {
756
+ const failed = rows.find((row) => row.ok === false);
757
+ return failed ? readString(failed.code) : null;
758
+ }
759
+ function appendExecutionRenameLines(lines, status) {
760
+ const completedSources = new Set(status.rows.filter((row) => row.ok !== false).map((row) => readString(row.source)).filter((value) => Boolean(value)));
761
+ const pairs = [];
762
+ for (const move of status.plannedMoves) {
763
+ if (status.status !== "completed" && !completedSources.has(move.source)) {
764
+ continue;
765
+ }
766
+ pairs.push(`${move.source} -> ${move.target}`);
767
+ }
768
+ if (pairs.length === 0) {
769
+ return;
770
+ }
771
+ lines.push("renames:");
772
+ for (const pair of pairs) {
773
+ lines.push(pair);
774
+ }
775
+ }
776
+ function appendExecutionNotRunLines(lines, status) {
777
+ if (status.notRunRows <= 0) {
778
+ return;
779
+ }
780
+ const seenSources = new Set(status.rows.map((row) => readString(row.source)).filter((value) => Boolean(value)));
781
+ const notRun = status.plannedMoves.filter((move) => !seenSources.has(move.source));
782
+ if (notRun.length === 0) {
783
+ return;
784
+ }
785
+ lines.push("not run:");
786
+ for (const move of notRun) {
787
+ lines.push(move.source);
788
+ }
789
+ }
790
+ function readFileRenameSyncWaitMs() {
791
+ return (0, mutation_execution_cache_1.readMutationSyncWaitMs)(process.env[env_vars_1.CLI_ENV.fileRenameSyncWaitMs], 120_000);
792
+ }
793
+ function readFileRenameRuntimeOptions() {
794
+ return {
795
+ postProcessImports: (0, file_mutation_runtime_1.isFileMutationImportPostProcessEnabled)(),
796
+ testFailRequiredImportUpdate: readString(process.env[env_vars_1.CLI_ENV.testFileRenameFailImports]),
797
+ testRowDelayMs: (0, file_mutation_runtime_1.readFileMutationTestDelayMs)(process.env[env_vars_1.CLI_ENV.testFileRenameRowDelayMs], 60_000),
798
+ testImportPostProcessDelayMs: (0, file_mutation_runtime_1.readFileMutationTestDelayMs)(process.env[env_vars_1.CLI_ENV.testFileRenameImportsDelayMs], 60_000),
799
+ testPostMutationCyclesDelayMs: (0, file_mutation_runtime_1.readFileMutationTestDelayMs)(process.env[env_vars_1.CLI_ENV.testPostMutationCyclesDelayMs], 60_000)
800
+ };
801
+ }
802
+ function captureFileRenameBackgroundEnv() {
803
+ return (0, file_mutation_runtime_1.captureFileMutationBackgroundEnv)([
804
+ env_vars_1.CLI_ENV.testFileRenameDelayMs,
805
+ env_vars_1.CLI_ENV.testFileRenameRowDelayMs,
806
+ env_vars_1.CLI_ENV.testFileRenameImportsDelayMs,
807
+ env_vars_1.CLI_ENV.testFileRenameFailImports
808
+ ]);
809
+ }
810
+ function formatFileRenameAgentText(response) {
811
+ const operation = readString(response.operation);
812
+ if (!operation?.startsWith("file.rename.")) {
813
+ return null;
814
+ }
815
+ const lines = [];
816
+ const previewId = readString(response.previewId);
817
+ const executionId = readString(response.executionId);
818
+ lines.push(response.ok === false
819
+ ? `${operation} failed`
820
+ : previewId && operation === "file.rename.preview"
821
+ ? `${operation} ${previewId}`
822
+ : executionId && (operation === "file.rename.apply" || operation === "file.rename.execute")
823
+ ? `${operation} ${executionId}`
824
+ : operation);
825
+ if (typeof response.summary === "string") {
826
+ lines.push(response.summary);
827
+ }
828
+ const renames = Array.isArray(response.renames) ? response.renames.filter(isObject) : [];
829
+ if (renames.length > 0 && response.ok !== false) {
830
+ lines.push("renames:");
831
+ for (const rename of renames) {
832
+ const source = readString(rename.source);
833
+ const target = readString(rename.target);
834
+ if (source && target) {
835
+ lines.push(`${source} -> ${target}`);
836
+ }
837
+ }
838
+ }
839
+ appendFailureLines(lines, response);
840
+ const filesWritten = Array.isArray(response.filesWritten) ? response.filesWritten : [];
841
+ if (filesWritten.length > 0) {
842
+ appendFilesWrittenLines(lines, filesWritten, Array.isArray(response.filesRenamed) ? response.filesRenamed : []);
843
+ }
844
+ if (isObject(response.postMutation) && isObject(response.postMutation.cycles)) {
845
+ appendPostMutationCyclesText(lines, response.postMutation.cycles);
846
+ }
847
+ if (typeof response.next === "string") {
848
+ lines.push(`next: ${response.next}`);
849
+ }
850
+ return lines.join("\n");
851
+ }
852
+ function appendFailureLines(lines, response) {
853
+ if (response.ok !== false || !Array.isArray(response.rows)) {
854
+ return;
855
+ }
856
+ const failed = response.rows.filter(isObject).find((row) => row.ok === false);
857
+ if (!failed) {
858
+ return;
859
+ }
860
+ lines.push("failed:");
861
+ lines.push(`${readString(failed.source) ?? "source"} -> ${readString(failed.target) ?? "target"}`);
862
+ lines.push(`code: ${readString(failed.code) ?? "FILE_RENAME_FAILED"}`);
863
+ if (typeof failed.error === "string") {
864
+ lines.push(failed.error);
865
+ }
866
+ if (typeof failed.rollback === "string") {
867
+ lines.push(`rollback: ${failed.rollback}`);
868
+ }
869
+ if (typeof failed.hint === "string") {
870
+ lines.push(`hint: ${failed.hint}`);
871
+ }
872
+ }
873
+ function FileRenameHelp() {
874
+ return {
875
+ ok: true,
876
+ command: "file rename",
877
+ usage: "aib file rename preview --stdin | aib file rename execute --stdin | aib file rename apply <previewId>",
878
+ dsl: [
879
+ "@base packages/agent-project-tooling/src",
880
+ "rename workspace-runner-cli.ts->cli.ts workspace-runner-command-hints.ts->command-hints.ts"
881
+ ],
882
+ notes: [
883
+ "preview validates planned file renames without writing.",
884
+ "execute renames files and updates TypeScript imports.",
885
+ "apply uses the cached preview id and refuses stale source/target state."
886
+ ]
887
+ };
888
+ }
889
+ function collectRows(rows, field) {
890
+ return rows.map((row) => readString(row[field])).filter((value) => Boolean(value));
891
+ }
892
+ function collectStringArray(value) {
893
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
894
+ }
895
+ function collectImportSnapshots(value) {
896
+ return Array.isArray(value) ? value.filter(isObject) : [];
897
+ }
898
+ function runPostMutationCyclesSnapshot(cwd, files) {
899
+ const existingFiles = formatCycleFocusFiles(cwd, files).filter((file) => fs.existsSync(resolveCliFilePath(cwd, file)));
900
+ if (existingFiles.length === 0) {
901
+ return {
902
+ op: "cycles",
903
+ componentCount: 0,
904
+ components: []
905
+ };
906
+ }
907
+ const args = ["cycles"];
908
+ for (const file of existingFiles) {
909
+ args.push("--files", file);
910
+ }
911
+ args.push("--detail", "imports", "--limit", "50");
912
+ return (0, inspect_cycles_1.runInspectCycles)(cwd, args, undefined);
913
+ }
914
+ function diffPostMutationCycles(prePayload, postPayload, touchedFiles) {
915
+ const preKeys = new Set(readCycleComponents(prePayload).map(cycleComponentKey));
916
+ const newOrChanged = readCycleComponents(postPayload).filter((component) => readStringArray(component.files).some((file) => touchedFiles.has(file)) &&
917
+ !preKeys.has(cycleComponentKey(component)));
918
+ return {
919
+ status: newOrChanged.length > 0 ? "new-or-changed" : "none",
920
+ detail: "imports",
921
+ newOrChangedCount: newOrChanged.length,
922
+ preComponentCount: readNumber(prePayload.componentCount),
923
+ postComponentCount: readNumber(postPayload.componentCount),
924
+ components: newOrChanged
925
+ };
926
+ }
927
+ function readCycleComponents(payload) {
928
+ return (Array.isArray(payload.components) ? payload.components : [])
929
+ .filter(isObject)
930
+ .map((component) => ({
931
+ kind: readString(component.kind) ?? "mixed",
932
+ files: readStringArray(component.files).sort(),
933
+ chain: readString(component.chain) ?? "",
934
+ ...(isObject(component.cycle) ? { cycle: component.cycle } : {}),
935
+ imports: readCycleImports(component)
936
+ }));
937
+ }
938
+ function readCycleImports(component) {
939
+ const cycle = isObject(component.cycle) ? component.cycle : {};
940
+ return readStringArray(cycle.imports);
941
+ }
942
+ function cycleComponentKey(component) {
943
+ return `${readString(component.kind) ?? "mixed"}:${readStringArray(component.files).sort().join("|")}`;
944
+ }
945
+ function formatCycleFocusFiles(cwd, files) {
946
+ return uniqueStrings(files.map((file) => formatRelativePath(cwd, resolveCliFilePath(cwd, file))));
947
+ }
948
+ function resolveCliFilePath(cwd, file) {
949
+ return path.normalize(path.isAbsolute(file) ? file : path.resolve(cwd, file));
950
+ }
951
+ function readStringArray(value) {
952
+ return collectStringArray(value);
953
+ }
954
+ function collectExistingFiles(cwd, files) {
955
+ return files.filter((file) => {
956
+ const resolved = path.isAbsolute(file) ? file : path.resolve(cwd, file);
957
+ return fs.existsSync(resolved);
958
+ });
959
+ }
960
+ function compactList(items, limit) {
961
+ const unique = Array.from(new Set(items)).sort((left, right) => left.localeCompare(right));
962
+ const visible = unique.slice(0, limit);
963
+ const hidden = unique.length - visible.length;
964
+ return hidden > 0 ? [...visible, `+ ${hidden} more`] : visible;
965
+ }
966
+ function formatInlineList(values, limit) {
967
+ const visible = values.slice(0, limit);
968
+ const hidden = values.length - visible.length;
969
+ return hidden > 0 ? `${visible.join(", ")}, + ${hidden} more` : visible.join(", ");
970
+ }
971
+ function appendFilesWrittenLines(lines, values, movedTargets) {
972
+ const files = values.filter((value) => typeof value === "string");
973
+ if (files.length === 0) {
974
+ return;
975
+ }
976
+ const moved = new Set(movedTargets.filter((value) => typeof value === "string"));
977
+ const movedFiles = files.filter((file) => moved.has(file));
978
+ const referenceFiles = files.filter((file) => !moved.has(file));
979
+ const visibleReferenceFiles = referenceFiles.slice(0, 8);
980
+ const hiddenReferenceFiles = referenceFiles.length - visibleReferenceFiles.length;
981
+ lines.push("filesWritten:");
982
+ for (const file of [...movedFiles, ...visibleReferenceFiles]) {
983
+ lines.push(file);
984
+ }
985
+ if (hiddenReferenceFiles > 0) {
986
+ lines.push(`+ ${hiddenReferenceFiles} reference ${plural(hiddenReferenceFiles, "file", "files")}`);
987
+ }
988
+ }
989
+ function appendPostMutationCyclesText(lines, cycles) {
990
+ lines.push("cycles:");
991
+ const count = readNumber(cycles.newOrChangedCount);
992
+ if (count === 0) {
993
+ lines.push("no new/changed cycles involving touched files");
994
+ return;
995
+ }
996
+ const components = Array.isArray(cycles.components) ? cycles.components.filter(isObject) : [];
997
+ lines.push(formatPostMutationCycleSummary(count, components));
998
+ components.forEach((component, index) => {
999
+ (0, inspect_cycles_1.appendCycleComponentText)(lines, component, {
1000
+ detail: "imports",
1001
+ prefix: components.length === 1 ? "" : `${index + 1}. `,
1002
+ indent: components.length === 1 ? "" : " "
1003
+ });
1004
+ });
1005
+ }
1006
+ function formatPostMutationCycleSummary(count, components) {
1007
+ const kinds = components.map((component) => readString(component.kind) ?? "mixed");
1008
+ const uniqueKinds = Array.from(new Set(kinds));
1009
+ const kindText = uniqueKinds.length === 1 ? `${uniqueKinds[0]} ` : "";
1010
+ return `${count} new/changed ${kindText}${count === 1 ? "cycle" : "cycles"} involving touched files`;
1011
+ }
1012
+ function plural(count, one, many) {
1013
+ return count === 1 ? one : many;
1014
+ }
1015
+ function readString(value) {
1016
+ return typeof value === "string" && value.length > 0 ? value : null;
1017
+ }
1018
+ function readNumber(value) {
1019
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
1020
+ }
1021
+ function compactObject(input) {
1022
+ return Object.fromEntries(Object.entries(input).filter(([, value]) => {
1023
+ if (value === null || value === undefined) {
1024
+ return false;
1025
+ }
1026
+ return !(Array.isArray(value) && value.length === 0);
1027
+ }));
1028
+ }
1029
+ function isObject(value) {
1030
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1031
+ }
1032
+ function normalizeKey(filePath) {
1033
+ const normalized = path.normalize(filePath);
1034
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
1035
+ }
1036
+ function uniqueStrings(values) {
1037
+ return Array.from(new Set(values));
1038
+ }
1039
+ function yieldToEventLoop() {
1040
+ return new Promise((resolve) => setImmediate(resolve));
1041
+ }
1042
+ async function maybeDelayPostMutationCycles(delayMs) {
1043
+ if (delayMs <= 0) {
1044
+ return;
1045
+ }
1046
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1047
+ }
1048
+ function formatRelativePath(cwd, filePath) {
1049
+ if (!filePath) {
1050
+ return "";
1051
+ }
1052
+ return path.relative(cwd, filePath).replace(/\\/g, "/");
1053
+ }