@automaton-labs/aib 0.0.7 → 0.0.9

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 +21 -578
  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 +217 -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,7 +1,1209 @@
1
- "use strict";var ie=exports&&exports.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),oe=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),M=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&ie(r,t,n[i]);return oe(r,t),r}})(),se=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.tryReadDeclarationExecutionStatus=void 0,exports.runDeclarationCommand=pe,exports.readCachedDeclarationExecution=ge;const ae=M(require("node:crypto")),m=M(require("node:fs")),y=M(require("node:path")),l=se(require("typescript")),$=require("../config/defaults"),V=require("../config/import-rules"),ce=require("../client/http-client"),N=require("../shared/agent-text"),R=require("../shared/errors"),le=require("../shared/protocol"),ue=require("../shared/routes"),fe=require("./session-workspace"),H=require("./shared"),b=require("./declaration-preview-cache"),C=require("./declaration-execution-cache");Object.defineProperty(exports,"tryReadDeclarationExecutionStatus",{enumerable:!0,get:function(){return C.tryReadDeclarationExecutionStatus}});const de=require("./declaration-format");async function pe(e,t,r,n={}){const[i="help",a="preview",...s]=t;if(i==="help"||i==="--help")return Z();const o=_e(i),c=a??"preview";if(c==="help"||c==="--help")return Z(o);if(c==="apply"){const f=s[0];if(!f||f.startsWith("--"))throw new R.CliError("DECLARATION_PREVIEW_ID_REQUIRED",`declaration ${o} apply expects a preview id.`,{usage:`aib declaration ${o} apply <previewId>`});return he(e,o,f,n)}if(c!=="preview"&&c!=="execute"&&c!=="validate")throw new R.CliError("UNKNOWN_DECLARATION_ACTION",`Unknown declaration ${o} action: ${c}`,{availableCommands:["preview","apply","execute","validate","help"]});const u=X(e,r,o,c==="execute");return await Q(e,u,c,n)}function ge(e,t){const r=(0,C.readDeclarationExecutionStatus)(e,t);return r.result&&typeof r.result=="object"&&!Array.isArray(r.result)?(0,N.attachAgentText)(r.result,Y(e,r.result)):(0,N.attachAgentText)(r,Ae(r))}async function he(e,t,r,n){const i=(0,b.readDeclarationPreviewRecord)(e,r);(0,b.validateDeclarationPreviewFiles)(i);const a=X(e,{...i.normalizedPayload,execute:!0},t,!0);return Q(e,a,"apply",n,r)}async function Q(e,t,r,n,i){const a=t.execute?(0,C.buildDeclarationExecutionId)():void 0,s=a?(0,C.createDeclarationExecutionStatus)(e,a,`declaration.${t.operation}.${r}`,t.files.length):void 0;s&&(0,C.writeDeclarationExecutionStatus)(e,s);const o=t.operation==="remove"?me(e,t,a,s):await ye(e,t,a,s,n),c=ve(e,t,o,r,a,i);if(!t.execute&&c.ok!==!1&&(r==="preview"||r==="validate")){const u=(0,b.buildDeclarationPreviewId)(L(t)),d=(0,b.hashFiles)(o.scannedFiles),f=(0,b.buildDeclarationPreviewHash)(L(t),d,c);(0,b.writeDeclarationPreviewRecord)(e,{previewId:u,previewHash:f,createdAt:new Date().toISOString(),cwd:y.resolve(e),normalizedPayload:L(t),fileHashes:d,previewResult:c}),c.previewId=u,c.next=`aib declaration ${t.operation} apply ${u}`}return s&&(s.status=c.ok===!1?"failed":"completed",s.phase="completed",s.completedRows=c.ok===!1?o.rows.filter(u=>u.ok).length:t.files.length,s.failedRows=o.rows.filter(u=>u.ok===!1).length,s.notRunRows=Math.max(0,t.files.length-o.rows.length),s.filesWritten=o.filesWritten,s.rows=o.rows,s.result=c,c.ok===!1&&(s.error=h(c.code)??"DECLARATION_FAILED"),(0,C.writeDeclarationExecutionStatus)(e,s)),(0,N.attachAgentText)(c,Y(e,c))}function me(e,t,r,n){const i=[],a=[],s=Object.fromEntries(t.selectors.map(o=>[o,[]]));for(const o of t.files){n&&z(e,n,i,a);const c=xe(o,t.selectors);if(i.push(c),c.ok===!1)return{rows:i,filesWritten:a,scannedFiles:t.files,removedBySelector:s,failedRow:c};const u=Array.isArray(c.removed)?c.removed.filter(E):[];for(const d of u){const f=h(d.selector);f&&s[f]&&s[f].push(d)}if(t.execute&&u.length>0){const d=m.readFileSync(o,"utf8");m.writeFileSync(o,be(d,u.map(f=>({start:D(f,"start"),end:D(f,"end"),newText:""})))),a.push(o)}}return{rows:i,filesWritten:a,scannedFiles:t.files,removedBySelector:s}}async function ye(e,t,r,n,i){const a=await(0,H.resolveCompatibleTargetInstance)(e,le.CLI_COMMAND_IDS.addMissingImports,i),s=i.importRules??(0,V.readConfigImportRules)(e),o=t.prefer.length>0?O(e,t.prefer,[],{explicitFiles:!0}):[],c=O(e,t.exclude,[]),u={mode:"declaration",files:t.files,selectors:t.selectors,preferFiles:o,excludeFiles:c,execute:t.execute,importRules:(0,V.importRulesToJson)(s)},d=await(0,ce.postJson)(a.entry,ue.EXTENSION_ROUTES.addMissingImports,u,(0,H.extensionRequestOptions)(i)),f=Array.isArray(d.rows)?d.rows.filter(E):[],x=Array.isArray(d.filesWritten)?d.filesWritten.filter(g=>typeof g=="string"):[],v=Array.isArray(d.scannedFiles)?d.scannedFiles.filter(g=>typeof g=="string"):[...t.files,...o],p={};for(const g of f){const A=Array.isArray(g.addedImports)?g.addedImports.filter(E):[];for(const _ of A.flatMap(w=>Array.isArray(w.items)?w.items.filter(E):[w])){const w=h(_.selector);w&&(p[w]=[...p[w]??[],g.file])}}n&&z(e,n,f,x);const S=f.find(g=>g.ok===!1);return{rows:f,filesWritten:x,scannedFiles:v,addedBySelector:p,...S?{failedRow:S}:{}}}function xe(e,t){if(!m.existsSync(e))return{file:e,ok:!1,code:"DECLARATION_TARGET_NOT_FOUND",error:"Target file does not exist."};if(B(e))return{file:e,ok:!1,code:"DECLARATION_TARGET_IS_DIRECTORY",error:"Target is a directory."};const r=m.readFileSync(e,"utf8"),n=l.default.createSourceFile(e,r,l.default.ScriptTarget.Latest,!0,W(e)),i=j(n),a=[],s=[];for(const o of t){const c=ke(o),u=i.filter(f=>f.selector===c.name&&(!c.kind||T(f.kind)===c.kind));if(u.length===0){s.push(o);continue}if(u.length>1)return{file:e,ok:!1,selectors:t,failedSelector:o,availableSelectors:u.map(f=>Pe(f.kind,f.selector)),code:"DECLARATION_REMOVE_AMBIGUOUS",error:`Selector matched ${u.length} declarations in one file.`,removed:a,unchangedSelectors:s};const d=u[0];a.push({selector:c.raw,file:e,line:n.getLineAndCharacterOfPosition(d.node.getStart(n)).line+1,exported:d.exported,kind:d.kind,start:d.start,end:te(r,d.end)})}return{file:e,ok:!0,selectors:t,removed:a,unchangedSelectors:s}}function Ue(e,t,r){if(!m.existsSync(e))return{file:e,ok:!1,code:"DECLARATION_TARGET_NOT_FOUND",error:"Target file does not exist."};if(B(e))return{file:e,ok:!1,code:"DECLARATION_TARGET_IS_DIRECTORY",error:"Target is a directory."};const n=m.readFileSync(e,"utf8");if(Te(e,n))return{file:e,ok:!1,code:"DECLARATION_ADD_MISSING_COMMONJS_UNSUPPORTED",error:"declaration addMissing v1 does not write CommonJS require statements."};const i=t.selectors.length>0?t.selectors:Ce(e,n),a=l.default.createSourceFile(e,n,l.default.ScriptTarget.Latest,!0,W(e)),s=Re(a),o=new Map,c=[];for(const x of i){if(s.has(x)||!$e(n,x)){c.push(x);continue}const v=r.exports.get(x);if(!v||y.resolve(v)===y.resolve(e)){c.push(x);continue}o.set(v,[...o.get(v)??[],x])}const u=Oe(n,a),d=[];let f="";for(const[x,v]of o.entries()){const p=Fe(e,x),S=`import { ${v.sort().join(", ")} } from "${p}";
2
- `;f+=S;for(const g of v)d.push({selector:g,file:e,source:x,moduleSpecifier:p,start:u,end:u,newText:S})}return{file:e,ok:!0,selectors:i,addedImports:f?[{selector:[...o.values()].flat().join(","),file:e,start:u,end:u,newText:f,items:d}]:[],unchangedSelectors:c}}function Be(e,t){const r=t.prefer.length>0?O(e,t.prefer,[]):O(e,[t.scope??"."],t.exclude),n=new Map;for(const i of r)if(!(!m.existsSync(i)||B(i)))for(const a of we(i))n.has(a)||n.set(a,i);return{exports:n,sourceFiles:r}}function X(e,t,r,n){if(!t||typeof t!="object"||Array.isArray(t))throw new R.CliError("DECLARATION_PAYLOAD_REQUIRED",`declaration ${r} expects a JSON or DSL payload.`);const i=t,a=i.operation??r;if(a!==r)throw new R.CliError("DECLARATION_OPERATION_MISMATCH",`Payload operation is ${a}, but command expects ${r}.`);const s=q(i.selectors);if(r==="remove"&&s.length===0)throw new R.CliError("DECLARATION_REMOVE_SELECTORS_REQUIRED","declaration remove expects at least one selector.");const o=q(i.exclude),c=Array.isArray(i.files)&&i.files.length>0?O(e,i.files.filter(u=>typeof u=="string"),o,{explicitFiles:!0}):typeof i.scope=="string"&&i.scope.trim()!==""?O(e,[i.scope],o):[];if(c.length===0)throw new R.CliError("DECLARATION_TARGET_REQUIRED",`declaration ${r} expects @scope or @files with at least one source file.`);return{operation:r,...typeof i.scope=="string"?{scope:y.resolve(e,i.scope)}:{},files:c,selectors:s,exclude:o,prefer:q(i.prefer),details:i.details===!0,targetKind:Array.isArray(i.files)&&i.files.length>0?"files":"scope",execute:n||i.execute===!0}}function ve(e,t,r,n,i,a){const s=r.rows.filter(A=>A.ok===!1).length,o=Math.max(0,t.files.length-r.rows.length),c=r.filesWritten.map(A=>J(e,A)),u=Ne(t.operation,r.rows),d=`declaration.${t.operation}.${n}`,f=r.removedBySelector??{},x=r.addedBySelector??{},v=Object.values(f).reduce((A,_)=>A+_.length,0),p=Object.values(x).reduce((A,_)=>A+_.length,0),S=t.operation==="remove"?v:p,g=!t.details&&(S>0||s>0)?Se(e,t,r,i):null;return G({ok:s===0,operation:d,executionId:i,previewId:a,target:t.scope?J(e,t.scope):`${t.files.length} files`,selectorCount:t.selectors.length,fileCount:t.files.length,targetKind:t.targetKind,details:t.details===!0?!0:void 0,declarationsRemoved:t.operation==="remove"?v:void 0,importsAdded:t.operation==="addMissing"?p:void 0,plannedFilesCount:u,filesWrittenCount:r.filesWritten.length,failedCount:s>0?s:void 0,notRunCount:o>0?o:void 0,filesWritten:c.length>0?We(c,8):void 0,removed:t.operation==="remove"?re(f):void 0,added:t.operation==="addMissing"?re(x):void 0,failed:r.failedRow?Le(e,r.failedRow):void 0,view:g?.saved,detailsFile:g?.file,internal:{requestedSelectors:t.selectors,resolvedScope:t.scope,resolvedFiles:t.files,exclude:t.exclude,prefer:t.prefer,details:t.details===!0?!0:void 0,targetKind:t.targetKind,scannedFiles:r.scannedFiles,rows:r.rows,filesWritten:r.filesWritten},code:r.failedRow?.code,next:je(t,S,s,r.failedRow)})}function Se(e,t,r,n){return(0,fe.saveSessionResultViewJson)(e,`res_${ae.randomBytes(4).toString("hex")}`,{kind:"declarationMutation",operation:t.operation,executionId:n,selectors:t.selectors,scope:t.scope,files:t.files,rows:r.rows,filesWritten:r.filesWritten,scannedFiles:r.scannedFiles})}function Y(e,t){const r=[],n=h(t.operation)??"declaration",i=h(t.executionId)??h(t.previewId),a=n.includes("addMissing"),s=n.endsWith(".preview")||n.endsWith(".validate");r.push(i?`${n} ${i}`:n);const o=D(t,"selectorCount"),c=D(t,a?"importsAdded":"declarationsRemoved"),u=s?D(t,"plannedFilesCount"):D(t,"filesWrittenCount"),d=D(t,"failedCount"),f=D(t,"notRunCount"),x=a?`${c} ${F(c,"import")} ${s?"planned":"added"}`:`${c} ${F(c,"declaration")} ${s?"found":"removed"}`,v=[`${o} ${F(o,"selector")}`,x];if(f>0&&h(t.targetKind)==="files"&&v.push(`${f} ${F(f,"file")} not run`),(!s||d===0)&&v.push(`${u} ${F(u,"file")} ${s?"will be written":"written"}`),r.push(v.join(", ")),t.details===!0&&E(t.internal)){const p=Array.isArray(t.internal.rows)?t.internal.rows.filter(E):[];r.push(...(0,de.formatDeclarationMutationDetails)(e,a?"addMissing":"remove",p))}else{const p=E(t.removed)?t.removed:E(t.added)?t.added:null;if(p&&Object.keys(p).length>0){r.push(a?s?"planned imports:":"added:":s?"planned removes:":"removed:");for(const[S,g]of Object.entries(p))r.push(`${S}: ${g} ${F(Number(g),"file")}`)}else r.push(a?s?"planned imports: none":"added: none":s?"planned removes: none":"removed: none")}if(t.details!==!0&&E(t.failed)){const p=t.failed;r.push("failed:");const S=h(p.file),g=h(p.selector);S&&r.push(S),g&&h(t.code)==="DECLARATION_REMOVE_AMBIGUOUS"?r.push(`\`${g}\` is ambiguous.`):g&&r.push(g);const A=Array.isArray(p.availableSelectors)?p.availableSelectors.filter(_=>typeof _=="string"&&_.trim()!==""):[];if(A.length>0){r.push("Available selectors:");for(const _ of A)r.push(_)}else h(p.error)&&(h(t.code)&&r.push(`code: ${h(t.code)}`),r.push(h(p.error)))}return t.details!==!0&&h(t.view)&&r.push(`view: ${h(t.view)}`),h(t.next)&&r.push(`next: ${h(t.next)}`),r.join(`
3
- `)}function Ae(e){return`${e.status}, ${e.completedRows}/${e.rowCount} rows
4
- ${e.operation}`}function Z(e){const t=e?`aib declaration ${e} preview --stdin | aib declaration ${e} execute --stdin | aib declaration ${e} apply <previewId>`:"aib declaration remove execute --stdin | aib declaration addMissing execute --stdin";return{ok:!0,command:e?`declaration ${e}`:"declaration",usage:t}}function _e(e){if(e==="remove"||e==="addMissing")return e;if(e==="add-missing")return"addMissing";throw new R.CliError("UNKNOWN_DECLARATION_COMMAND",`Unknown declaration command: ${e}`,{availableCommands:["remove","addMissing","help"]})}function z(e,t,r,n){t.completedRows=r.filter(i=>i.ok).length,t.failedRows=r.filter(i=>i.ok===!1).length,t.filesWritten=n,t.rows=r,(0,C.writeDeclarationExecutionStatus)(e,t)}function L(e){return G({operation:e.operation,scope:e.scope,files:e.files,selectors:e.selectors,exclude:e.exclude,prefer:e.prefer,details:e.details===!0?!0:void 0,targetKind:e.targetKind})}function j(e){const t=[];for(const r of e.statements){if(l.default.isFunctionDeclaration(r)||l.default.isClassDeclaration(r)||l.default.isInterfaceDeclaration(r)||l.default.isTypeAliasDeclaration(r)||l.default.isEnumDeclaration(r)){const n=r.name?.text;n&&t.push(k(e,r,n,Ee(r)));continue}if(l.default.isVariableStatement(r)){if(r.declarationList.declarations.length!==1){for(const a of r.declarationList.declarations){const s=l.default.isIdentifier(a.name)?a.name.text:null;s&&t.push({...k(e,r,s,"variable"),kind:"variable-group"})}continue}const n=r.declarationList.declarations[0],i=l.default.isIdentifier(n.name)?n.name.text:null;i&&t.push(k(e,r,i,"variable"))}}return t}function k(e,t,r,n){return{selector:r,file:e.fileName,line:e.getLineAndCharacterOfPosition(t.getStart(e)).line+1,exported:De(t),kind:n,start:t.getFullStart(),end:t.end,node:t}}function Ee(e){return l.default.isFunctionDeclaration(e)?"function":l.default.isClassDeclaration(e)?"class":l.default.isInterfaceDeclaration(e)?"interface":l.default.isTypeAliasDeclaration(e)?"type":l.default.isEnumDeclaration(e)?"enum":"declaration"}function De(e){return!!(l.default.canHaveModifiers(e)&&l.default.getModifiers(e)?.some(t=>t.kind===l.default.SyntaxKind.ExportKeyword))}function we(e){const t=m.readFileSync(e,"utf8"),r=l.default.createSourceFile(e,t,l.default.ScriptTarget.Latest,!0,W(e)),n=[];for(const i of j(r))i.exported&&n.push(i.selector);for(const i of r.statements)if(l.default.isExportDeclaration(i)&&i.exportClause&&l.default.isNamedExports(i.exportClause)&&!i.moduleSpecifier)for(const a of i.exportClause.elements)n.push(a.name.text);return[...new Set(n)]}function Re(e){const t=new Set;for(const r of e.statements){for(const n of j(e).filter(i=>i.node===r))t.add(n.selector);if(l.default.isImportDeclaration(r)&&r.importClause){r.importClause.name&&t.add(r.importClause.name.text);const n=r.importClause.namedBindings;if(n&&l.default.isNamedImports(n))for(const i of n.elements)t.add(i.name.text);n&&l.default.isNamespaceImport(n)&&t.add(n.name.text)}}return t}function Ce(e,t){const r={allowJs:!0,checkJs:!0,jsx:l.default.JsxEmit.ReactJSX,module:l.default.ModuleKind.ESNext,target:l.default.ScriptTarget.ES2022,noEmit:!0},n=l.default.createCompilerHost(r);n.readFile=o=>y.resolve(o)===y.resolve(e)?t:m.existsSync(o)?m.readFileSync(o,"utf8"):void 0,n.fileExists=o=>y.resolve(o)===y.resolve(e)||m.existsSync(o);const i=l.default.createProgram([e],r,n),s=i.getSemanticDiagnostics(i.getSourceFile(e)).filter(o=>o.code===2304||o.code===2552).map(o=>l.default.flattenDiagnosticMessageText(o.messageText,`
5
- `)).map(o=>o.match(/Cannot find name '([^']+)'/)?.[1]??o.match(/Did you mean '([^']+)'/)?.[1]??"").filter(Boolean);return[...new Set(s)]}function O(e,t,r,n={}){const i=Ie(e,r),a=[];for(const o of t){const c=y.resolve(e,o);if(K(o)){a.push(...P(e).filter(u=>ee(I(o)).test(I(y.relative(e,u)))));continue}if(m.existsSync(c)&&m.statSync(c).isDirectory()&&n.explicitFiles!==!0){a.push(...P(c));continue}a.push(c)}const s=[...new Set(a.filter(o=>U(o)&&!i(o)))];return n.explicitFiles===!0?s:s.sort()}function P(e){if(!m.existsSync(e))return[];const t=m.statSync(e);if(t.isFile())return U(e)?[e]:[];if(!t.isDirectory())return[];const r=[];for(const n of m.readdirSync(e,{withFileTypes:!0})){if(["node_modules",".git","dist","out","build",".tmp"].includes(n.name))continue;const i=y.join(e,n.name);n.isDirectory()?r.push(...P(i)):n.isFile()&&U(i)&&r.push(i)}return r}function Ie(e,t){const r=new Set(t.filter(i=>!K(i)).map(i=>y.resolve(e,i))),n=t.filter(K).map(i=>ee(I(i)));return i=>r.has(y.resolve(i))||n.some(a=>a.test(I(y.relative(e,i))))}function K(e){return e.includes("*")}function ee(e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__AIB_GLOBSTAR__").replace(/\*/g,"[^/]*");return new RegExp(`^${t.replace(/__AIB_GLOBSTAR__/g,".*")}$`)}function be(e,t){let r=e;const n=[...t].sort((i,a)=>a.start-i.start);for(const i of n)r=`${r.slice(0,i.start)}${i.newText}${r.slice(i.end)}`;return r}function Oe(e,t){let r=0;for(const n of t.statements){if(!l.default.isImportDeclaration(n))break;r=te(e,n.end)}return r}function te(e,t){let r=t;for(;r<e.length&&(e[r]==="\r"||e[r]===`
6
- `)&&(r+=1,e[r-1]!==`
7
- `););return r}function Fe(e,t){let r=I(y.relative(y.dirname(e),t));return r=r.replace(/\.(tsx?|jsx?|mjs|cjs)$/i,""),r.startsWith(".")||(r=`./${r}`),r}function W(e){return/\.tsx$/i.test(e)?l.default.ScriptKind.TSX:/\.jsx$/i.test(e)?l.default.ScriptKind.JSX:/\.[cm]?js$/i.test(e)?l.default.ScriptKind.JS:l.default.ScriptKind.TS}function U(e){return/\.(tsx?|jsx?|mjs|cjs)$/i.test(e)&&!e.endsWith(".d.ts")}function B(e){return m.existsSync(e)&&m.statSync(e).isDirectory()}function Te(e,t){return/\.cjs$/i.test(e)||/\bmodule\.exports\b|\bexports\.[A-Za-z_$]/.test(t)}function $e(e,t){return new RegExp(`\\b${Me(t)}\\b`).test(e)}function Me(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function re(e){const t={};for(const[r,n]of Object.entries(e))n.length>0&&(t[r]=n.length);return t}function Ne(e,t){return t.filter(r=>{if(r.ok===!1)return!1;const n=e==="addMissing"?r.addedImports:r.removed;return Array.isArray(n)&&n.length>0}).length}function Le(e,t){return G({file:J(e,t.file),selector:h(t.failedSelector)??(Array.isArray(t.selectors)?t.selectors[0]:void 0),availableSelectors:Array.isArray(t.availableSelectors)?t.availableSelectors:void 0,code:t.code,error:t.error})}function je(e,t,r,n){if(r>0){if(n?.code==="DECLARATION_REMOVE_AMBIGUOUS"){const i=h(n.failedSelector)??"the ambiguous selector";return e.targetKind==="scope"?`Use a qualified selector for ${i} or exclude the file, then rerun declaration remove for the scope.`:`Use a qualified selector for ${i} and rerun declaration remove for the remaining files.`}return e.operation==="remove"?"Fix failed selector/file and rerun declaration remove for remaining targets.":"Fix failed selector/source and rerun declaration addMissing for remaining targets."}return t===0?e.operation==="remove"?"Nothing removed. Check selector names or target files.":"No missing imports added. Check selectors, prefer sources, or target files.":e.operation==="remove"?"run addMissing with desired selectors":"verify affected files only if checks report an issue"}function ke(e){const t=e.trim();for(const r of[$.DEFAULT_EFFECTIVE_CONFIG.selectorSeparator,":","-"]){const n=t.indexOf(r);if(n<=0)continue;const i=Ke(t.slice(0,n)),a=t.slice(n+r.length).trim();if(i&&a)return{raw:t,name:a,kind:i}}return{raw:t,name:t,kind:null}}function Pe(e,t){const r=T(e);return`${ne(r)??r}${$.DEFAULT_EFFECTIVE_CONFIG.selectorSeparator}${t}`}function Ke(e){const t=T(e);if(ne(t)!==null)return t;const r=Object.entries($.DEFAULT_EFFECTIVE_CONFIG.entityKindAliases).find(([,n])=>n===e)?.[0];return r?T(r):null}function ne(e){const t=T(e);return t==="class"||t==="interface"||t==="type"||t==="function"||t==="variable"||t==="enum"?$.DEFAULT_EFFECTIVE_CONFIG.entityKindAliases[t]:null}function T(e){return e==="variable-group"?"variable":e}function We(e,t){return e.length<=t?e:[...e.slice(0,t),`+ ${e.length-t} more`]}function q(e){return Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string"&&t.trim()!=="").map(t=>t.trim()))]:[]}function h(e){return typeof e=="string"&&e.trim()!==""?e.trim():null}function D(e,t){const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function G(e){const t={};for(const[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}function E(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function J(e,t){const r=y.relative(e,t);return r&&!r.startsWith("..")&&!y.isAbsolute(r)?I(r):I(t)}function I(e){return e.replace(/\\/g,"/")}function F(e,t){return e===1?t:`${t}s`}
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.tryReadDeclarationExecutionStatus = void 0;
40
+ exports.runDeclarationCommand = runDeclarationCommand;
41
+ exports.readCachedDeclarationExecution = readCachedDeclarationExecution;
42
+ const crypto = __importStar(require("node:crypto"));
43
+ const fs = __importStar(require("node:fs"));
44
+ const path = __importStar(require("node:path"));
45
+ const typescript_1 = __importDefault(require("typescript"));
46
+ const defaults_1 = require("../config/defaults");
47
+ const import_rules_1 = require("../config/import-rules");
48
+ const standalone_import_process_1 = require("../imports/standalone-import-process");
49
+ const agent_text_1 = require("../shared/agent-text");
50
+ const errors_1 = require("../shared/errors");
51
+ const session_workspace_1 = require("./session-workspace");
52
+ const declaration_preview_cache_1 = require("./declaration-preview-cache");
53
+ const declaration_execution_cache_1 = require("./declaration-execution-cache");
54
+ Object.defineProperty(exports, "tryReadDeclarationExecutionStatus", { enumerable: true, get: function () { return declaration_execution_cache_1.tryReadDeclarationExecutionStatus; } });
55
+ const declaration_format_1 = require("./declaration-format");
56
+ async function runDeclarationCommand(cwd, restArgs, rawPayload, options = {}) {
57
+ const [operationArg = "help", actionArg = "preview", ...actionArgs] = restArgs;
58
+ if (operationArg === "help" || operationArg === "--help") {
59
+ return declarationHelp();
60
+ }
61
+ const operation = readOperation(operationArg);
62
+ const action = actionArg ?? "preview";
63
+ if (action === "help" || action === "--help") {
64
+ return declarationHelp(operation);
65
+ }
66
+ if (action === "apply") {
67
+ const previewId = actionArgs[0];
68
+ if (!previewId || previewId.startsWith("--")) {
69
+ throw new errors_1.CliError("DECLARATION_PREVIEW_ID_REQUIRED", `declaration ${operation} apply expects a preview id.`, {
70
+ usage: `aib declaration ${operation} apply <previewId>`
71
+ });
72
+ }
73
+ return applyDeclarationPreview(cwd, operation, previewId, options);
74
+ }
75
+ if (action !== "preview" && action !== "execute" && action !== "validate") {
76
+ throw new errors_1.CliError("UNKNOWN_DECLARATION_ACTION", `Unknown declaration ${operation} action: ${action}`, {
77
+ availableCommands: ["preview", "apply", "execute", "validate", "help"]
78
+ });
79
+ }
80
+ const normalized = normalizePayload(cwd, rawPayload, operation, action === "execute");
81
+ const result = await runDeclarationPayload(cwd, normalized, action, options);
82
+ return result;
83
+ }
84
+ function readCachedDeclarationExecution(cwd, executionId) {
85
+ const status = (0, declaration_execution_cache_1.readDeclarationExecutionStatus)(cwd, executionId);
86
+ if (status.result && typeof status.result === "object" && !Array.isArray(status.result)) {
87
+ return (0, agent_text_1.attachAgentText)(status.result, formatDeclarationAgentText(cwd, status.result));
88
+ }
89
+ return (0, agent_text_1.attachAgentText)(status, formatDeclarationStatusText(status));
90
+ }
91
+ async function applyDeclarationPreview(cwd, operation, previewId, options) {
92
+ const record = (0, declaration_preview_cache_1.readDeclarationPreviewRecord)(cwd, previewId);
93
+ (0, declaration_preview_cache_1.validateDeclarationPreviewFiles)(record);
94
+ const normalized = normalizePayload(cwd, {
95
+ ...record.normalizedPayload,
96
+ execute: true
97
+ }, operation, true);
98
+ return runDeclarationPayload(cwd, normalized, "apply", options, previewId);
99
+ }
100
+ async function runDeclarationPayload(cwd, normalized, action, options, previewIdFromApply) {
101
+ const executionId = normalized.execute ? (0, declaration_execution_cache_1.buildDeclarationExecutionId)() : undefined;
102
+ const executionStatus = executionId
103
+ ? (0, declaration_execution_cache_1.createDeclarationExecutionStatus)(cwd, executionId, `declaration.${normalized.operation}.${action}`, normalized.files.length)
104
+ : undefined;
105
+ if (executionStatus) {
106
+ (0, declaration_execution_cache_1.writeDeclarationExecutionStatus)(cwd, executionStatus);
107
+ }
108
+ const result = normalized.operation === "remove"
109
+ ? runRemove(cwd, normalized, executionId, executionStatus)
110
+ : await runAddMissing(cwd, normalized, executionId, executionStatus, options);
111
+ const response = compactDeclarationResponse(cwd, normalized, result, action, executionId, previewIdFromApply);
112
+ if (!normalized.execute && response.ok !== false && (action === "preview" || action === "validate")) {
113
+ const previewId = (0, declaration_preview_cache_1.buildDeclarationPreviewId)(normalizedPayloadForCache(normalized));
114
+ const fileHashes = (0, declaration_preview_cache_1.hashFiles)(result.scannedFiles);
115
+ const previewHash = (0, declaration_preview_cache_1.buildDeclarationPreviewHash)(normalizedPayloadForCache(normalized), fileHashes, response);
116
+ (0, declaration_preview_cache_1.writeDeclarationPreviewRecord)(cwd, {
117
+ previewId,
118
+ previewHash,
119
+ createdAt: new Date().toISOString(),
120
+ cwd: path.resolve(cwd),
121
+ normalizedPayload: normalizedPayloadForCache(normalized),
122
+ fileHashes,
123
+ previewResult: response
124
+ });
125
+ response.previewId = previewId;
126
+ response.next = `aib declaration ${normalized.operation} apply ${previewId}`;
127
+ }
128
+ if (executionStatus) {
129
+ executionStatus.status = response.ok === false ? "failed" : "completed";
130
+ executionStatus.phase = "completed";
131
+ executionStatus.completedRows = response.ok === false ? result.rows.filter((row) => row.ok).length : normalized.files.length;
132
+ executionStatus.failedRows = result.rows.filter((row) => row.ok === false).length;
133
+ executionStatus.notRunRows = Math.max(0, normalized.files.length - result.rows.length);
134
+ executionStatus.filesWritten = result.filesWritten;
135
+ executionStatus.rows = result.rows;
136
+ executionStatus.result = response;
137
+ if (response.ok === false) {
138
+ executionStatus.error = readString(response.code) ?? "DECLARATION_FAILED";
139
+ }
140
+ (0, declaration_execution_cache_1.writeDeclarationExecutionStatus)(cwd, executionStatus);
141
+ }
142
+ return (0, agent_text_1.attachAgentText)(response, formatDeclarationAgentText(cwd, response));
143
+ }
144
+ function runRemove(cwd, normalized, executionId, status) {
145
+ const rows = [];
146
+ const filesWritten = [];
147
+ const removedBySelector = Object.fromEntries(normalized.selectors.map((selector) => [selector, []]));
148
+ let failedRow;
149
+ for (const file of normalized.files) {
150
+ status && persistProgress(cwd, status, rows, filesWritten);
151
+ const row = planRemoveFile(file, normalized.selectors);
152
+ rows.push(row);
153
+ const removed = Array.isArray(row.removed) ? row.removed.filter(isObject) : [];
154
+ for (const item of removed) {
155
+ const selector = readString(item.selector);
156
+ if (selector && removedBySelector[selector]) {
157
+ removedBySelector[selector].push(item);
158
+ }
159
+ }
160
+ if (normalized.execute && removed.length > 0) {
161
+ const text = fs.readFileSync(file, "utf8");
162
+ fs.writeFileSync(file, applyTextEdits(text, removed.map((item) => ({
163
+ start: numberField(item, "start"),
164
+ end: numberField(item, "end"),
165
+ newText: ""
166
+ }))));
167
+ filesWritten.push(file);
168
+ }
169
+ if (row.ok === false && !failedRow) {
170
+ failedRow = row;
171
+ }
172
+ if (row.ok === false && !(normalized.continueOnFailure && isContinuableRemoveRowFailure(row))) {
173
+ return {
174
+ rows,
175
+ filesWritten,
176
+ scannedFiles: normalized.files,
177
+ removedBySelector,
178
+ failedRow: row
179
+ };
180
+ }
181
+ }
182
+ return compactObject({
183
+ rows,
184
+ filesWritten,
185
+ scannedFiles: normalized.files,
186
+ removedBySelector,
187
+ failedRow
188
+ });
189
+ }
190
+ async function runAddMissing(cwd, normalized, _executionId, status, options) {
191
+ const importRules = options.importRules ?? (0, import_rules_1.readConfigImportRules)(cwd);
192
+ const preferFiles = normalized.prefer.length > 0 ? collectFilesFromInputs(cwd, normalized.prefer, [], { explicitFiles: true }) : [];
193
+ const excludeFiles = preferFiles.length > 0
194
+ ? []
195
+ : collectFilesFromInputs(cwd, normalized.exclude, []);
196
+ const shouldCheckPreferredSources = normalized.sourceCheckOnly || normalized.cleanupTail;
197
+ const sourceCheck = shouldCheckPreferredSources
198
+ ? checkPreferredSources(cwd, normalized.selectors, preferFiles)
199
+ : { resolution: {}, failures: [] };
200
+ const validSelectors = shouldCheckPreferredSources && preferFiles.length > 0
201
+ ? normalized.selectors.filter((selector) => sourceCheck.resolution[selector])
202
+ : normalized.selectors;
203
+ if (normalized.sourceCheckOnly) {
204
+ return {
205
+ rows: [],
206
+ filesWritten: [],
207
+ scannedFiles: [...normalized.files, ...preferFiles],
208
+ addedBySelector: {},
209
+ sourceResolution: sourceCheck.resolution,
210
+ sourceFailures: sourceCheck.failures,
211
+ skipped: normalized.skipped
212
+ };
213
+ }
214
+ if (normalized.selectors.length > 0 && validSelectors.length === 0) {
215
+ return {
216
+ rows: [],
217
+ filesWritten: [],
218
+ scannedFiles: [...normalized.files, ...preferFiles],
219
+ addedBySelector: {},
220
+ sourceResolution: sourceCheck.resolution,
221
+ sourceFailures: sourceCheck.failures,
222
+ skipped: normalized.skipped
223
+ };
224
+ }
225
+ const requestBody = {
226
+ mode: "declaration",
227
+ files: normalized.files,
228
+ selectors: validSelectors,
229
+ preferFiles,
230
+ excludeFiles,
231
+ execute: normalized.execute,
232
+ importRules: (0, import_rules_1.importRulesToJson)(importRules)
233
+ };
234
+ const rawResult = await (options.standaloneImportWorker ?? standalone_import_process_1.runStandaloneImportWorker)({
235
+ workspaceRoot: cwd,
236
+ operation: "declaration-add-missing",
237
+ payload: requestBody,
238
+ importRules
239
+ });
240
+ const rows = Array.isArray(rawResult.rows) ? rawResult.rows.filter(isObject) : [];
241
+ const filesWritten = Array.isArray(rawResult.filesWritten)
242
+ ? rawResult.filesWritten.filter((file) => typeof file === "string")
243
+ : [];
244
+ const scannedFiles = Array.isArray(rawResult.scannedFiles)
245
+ ? rawResult.scannedFiles.filter((file) => typeof file === "string")
246
+ : [...normalized.files, ...preferFiles];
247
+ const addedBySelector = {};
248
+ for (const row of rows) {
249
+ const addedImports = Array.isArray(row.addedImports) ? row.addedImports.filter(isObject) : [];
250
+ for (const item of addedImports.flatMap((group) => Array.isArray(group.items) ? group.items.filter(isObject) : [group])) {
251
+ const selector = readString(item.selector);
252
+ if (selector) {
253
+ addedBySelector[selector] = [...(addedBySelector[selector] ?? []), row.file];
254
+ }
255
+ }
256
+ }
257
+ if (status) {
258
+ persistProgress(cwd, status, rows, filesWritten);
259
+ }
260
+ const failedRow = rows.find((row) => row.ok === false);
261
+ return {
262
+ rows,
263
+ filesWritten,
264
+ scannedFiles,
265
+ addedBySelector,
266
+ sourceResolution: sourceCheck.resolution,
267
+ sourceFailures: sourceCheck.failures,
268
+ skipped: normalized.skipped,
269
+ ...(failedRow ? { failedRow } : {})
270
+ };
271
+ }
272
+ function planRemoveFile(file, selectors) {
273
+ if (!fs.existsSync(file)) {
274
+ return { file, ok: false, code: "DECLARATION_TARGET_NOT_FOUND", error: "Target file does not exist." };
275
+ }
276
+ if (isDirectory(file)) {
277
+ return { file, ok: false, code: "DECLARATION_TARGET_IS_DIRECTORY", error: "Target is a directory." };
278
+ }
279
+ const text = fs.readFileSync(file, "utf8");
280
+ const sourceFile = typescript_1.default.createSourceFile(file, text, typescript_1.default.ScriptTarget.Latest, true, scriptKindForFile(file));
281
+ const declarations = collectTopLevelDeclarations(sourceFile);
282
+ const removed = [];
283
+ const notFoundSelectors = [];
284
+ const failures = [];
285
+ for (const selector of selectors) {
286
+ const parsedSelector = parseDeclarationSelector(selector);
287
+ const matches = declarations.filter((declaration) => declaration.selector === parsedSelector.name &&
288
+ (!parsedSelector.kind || normalizedDeclarationKind(declaration.kind) === parsedSelector.kind));
289
+ if (matches.length === 0) {
290
+ notFoundSelectors.push(selector);
291
+ continue;
292
+ }
293
+ if (matches.length > 1) {
294
+ failures.push({
295
+ file,
296
+ selector,
297
+ availableSelectors: matches.map((match) => formatDeclarationSelector(match.kind, match.selector)),
298
+ code: "DECLARATION_REMOVE_AMBIGUOUS",
299
+ error: `Selector matched ${matches.length} declarations in one file.`
300
+ });
301
+ continue;
302
+ }
303
+ const match = matches[0];
304
+ removed.push({
305
+ selector: parsedSelector.raw,
306
+ file,
307
+ line: sourceFile.getLineAndCharacterOfPosition(match.node.getStart(sourceFile)).line + 1,
308
+ exported: match.exported,
309
+ kind: match.kind,
310
+ start: match.start,
311
+ end: extendToFollowingLineBreak(text, match.end)
312
+ });
313
+ }
314
+ const firstFailure = failures[0];
315
+ return compactObject({
316
+ file,
317
+ ok: failures.length === 0,
318
+ selectors,
319
+ removed,
320
+ notFoundSelectors,
321
+ failures: failures.length > 0 ? failures : undefined,
322
+ ...(firstFailure ? {
323
+ failedSelector: readString(firstFailure.selector),
324
+ availableSelectors: Array.isArray(firstFailure.availableSelectors) ? firstFailure.availableSelectors : undefined,
325
+ code: readString(firstFailure.code),
326
+ error: readString(firstFailure.error)
327
+ } : {})
328
+ });
329
+ }
330
+ function planAddMissingFile(file, normalized, exportIndex) {
331
+ if (!fs.existsSync(file)) {
332
+ return { file, ok: false, code: "DECLARATION_TARGET_NOT_FOUND", error: "Target file does not exist." };
333
+ }
334
+ if (isDirectory(file)) {
335
+ return { file, ok: false, code: "DECLARATION_TARGET_IS_DIRECTORY", error: "Target is a directory." };
336
+ }
337
+ const text = fs.readFileSync(file, "utf8");
338
+ if (isCommonJsFile(file, text)) {
339
+ return { file, ok: false, code: "DECLARATION_ADD_MISSING_COMMONJS_UNSUPPORTED", error: "declaration addMissing v1 does not write CommonJS require statements." };
340
+ }
341
+ const selectors = normalized.selectors.length > 0 ? normalized.selectors : collectMissingNamesWithTypeScript(file, text);
342
+ const sourceFile = typescript_1.default.createSourceFile(file, text, typescript_1.default.ScriptTarget.Latest, true, scriptKindForFile(file));
343
+ const existing = collectExistingBindings(sourceFile);
344
+ const grouped = new Map();
345
+ const unchangedSelectors = [];
346
+ for (const selector of selectors) {
347
+ if (existing.has(selector) || !containsIdentifier(text, selector)) {
348
+ unchangedSelectors.push(selector);
349
+ continue;
350
+ }
351
+ const exportedFrom = exportIndex.exports.get(selector);
352
+ if (!exportedFrom || path.resolve(exportedFrom) === path.resolve(file)) {
353
+ unchangedSelectors.push(selector);
354
+ continue;
355
+ }
356
+ grouped.set(exportedFrom, [...(grouped.get(exportedFrom) ?? []), selector]);
357
+ }
358
+ const insertAt = importInsertOffset(text, sourceFile);
359
+ const addedImports = [];
360
+ let importText = "";
361
+ for (const [source, names] of grouped.entries()) {
362
+ const moduleSpecifier = relativeModuleSpecifier(file, source);
363
+ const newText = `import { ${names.sort().join(", ")} } from "${moduleSpecifier}";\n`;
364
+ importText += newText;
365
+ for (const selector of names) {
366
+ addedImports.push({
367
+ selector,
368
+ file,
369
+ source,
370
+ moduleSpecifier,
371
+ start: insertAt,
372
+ end: insertAt,
373
+ newText
374
+ });
375
+ }
376
+ }
377
+ return {
378
+ file,
379
+ ok: true,
380
+ selectors,
381
+ addedImports: importText ? [{
382
+ selector: [...grouped.values()].flat().join(","),
383
+ file,
384
+ start: insertAt,
385
+ end: insertAt,
386
+ newText: importText,
387
+ items: addedImports
388
+ }] : [],
389
+ unchangedSelectors
390
+ };
391
+ }
392
+ function buildExportIndex(cwd, normalized) {
393
+ const sourceFiles = normalized.prefer.length > 0
394
+ ? collectFilesFromInputs(cwd, normalized.prefer, [])
395
+ : collectFilesFromInputs(cwd, [normalized.scope ?? "."], normalized.exclude);
396
+ const exports = new Map();
397
+ for (const file of sourceFiles) {
398
+ if (!fs.existsSync(file) || isDirectory(file)) {
399
+ continue;
400
+ }
401
+ for (const name of collectExportedNames(file)) {
402
+ if (!exports.has(name)) {
403
+ exports.set(name, file);
404
+ }
405
+ }
406
+ }
407
+ return {
408
+ exports,
409
+ sourceFiles
410
+ };
411
+ }
412
+ function normalizePayload(cwd, rawPayload, operation, execute) {
413
+ if (!rawPayload || typeof rawPayload !== "object" || Array.isArray(rawPayload)) {
414
+ throw new errors_1.CliError("DECLARATION_PAYLOAD_REQUIRED", `declaration ${operation} expects a JSON or DSL payload.`);
415
+ }
416
+ const raw = rawPayload;
417
+ const payloadOperation = raw.operation ?? operation;
418
+ if (payloadOperation !== operation) {
419
+ throw new errors_1.CliError("DECLARATION_OPERATION_MISMATCH", `Payload operation is ${payloadOperation}, but command expects ${operation}.`);
420
+ }
421
+ const selectors = readStringArray(raw.selectors);
422
+ if (operation === "remove" && selectors.length === 0) {
423
+ throw new errors_1.CliError("DECLARATION_REMOVE_SELECTORS_REQUIRED", "declaration remove expects at least one selector.");
424
+ }
425
+ const exclude = readStringArray(raw.exclude);
426
+ const files = Array.isArray(raw.files) && raw.files.length > 0
427
+ ? collectFilesFromInputs(cwd, raw.files.filter((item) => typeof item === "string"), exclude, { explicitFiles: true })
428
+ : typeof raw.scope === "string" && raw.scope.trim() !== ""
429
+ ? collectFilesFromInputs(cwd, [raw.scope], exclude)
430
+ : [];
431
+ if (files.length === 0) {
432
+ throw new errors_1.CliError("DECLARATION_TARGET_REQUIRED", `declaration ${operation} expects @scope or @files with at least one source file.`);
433
+ }
434
+ return {
435
+ operation,
436
+ ...(typeof raw.scope === "string" ? { scope: path.resolve(cwd, raw.scope) } : {}),
437
+ files,
438
+ selectors,
439
+ exclude,
440
+ prefer: readStringArray(raw.prefer),
441
+ details: raw.details === true,
442
+ targetKind: Array.isArray(raw.files) && raw.files.length > 0 ? "files" : "scope",
443
+ execute: execute || raw.execute === true,
444
+ sourceCheckOnly: raw.sourceCheckOnly === true,
445
+ cleanupTail: raw.cleanupTail === true,
446
+ continueOnFailure: raw.continueOnFailure === true,
447
+ skipped: Array.isArray(raw.skipped) ? raw.skipped.filter(isObject) : []
448
+ };
449
+ }
450
+ function isContinuableRemoveRowFailure(row) {
451
+ const failures = Array.isArray(row.failures) ? row.failures.filter(isObject) : [];
452
+ return failures.length > 0 && failures.every((failure) => readString(failure.code) === "DECLARATION_REMOVE_AMBIGUOUS");
453
+ }
454
+ function checkPreferredSources(cwd, selectors, preferFiles) {
455
+ if (preferFiles.length === 0 || selectors.length === 0) {
456
+ return { resolution: {}, failures: [] };
457
+ }
458
+ const exportsBySelector = new Map();
459
+ for (const file of preferFiles) {
460
+ if (!fs.existsSync(file) || isDirectory(file)) {
461
+ continue;
462
+ }
463
+ for (const name of collectExportedNames(file)) {
464
+ exportsBySelector.set(name, [...(exportsBySelector.get(name) ?? []), file]);
465
+ }
466
+ }
467
+ const resolution = {};
468
+ const failures = [];
469
+ for (const selector of selectors) {
470
+ const sources = exportsBySelector.get(selector) ?? [];
471
+ if (sources.length === 1) {
472
+ resolution[selector] = sources[0];
473
+ continue;
474
+ }
475
+ failures.push(compactObject({
476
+ selector,
477
+ code: sources.length > 1 ? "DECLARATION_ADD_MISSING_SOURCE_AMBIGUOUS" : "DECLARATION_ADD_MISSING_SOURCE_NOT_FOUND",
478
+ error: sources.length > 1
479
+ ? "Multiple preferred sources export selector."
480
+ : "No preferred source exports selector.",
481
+ sources: sources.map((source) => formatRelativePath(cwd, source))
482
+ }));
483
+ }
484
+ return { resolution, failures };
485
+ }
486
+ function compactDeclarationResponse(cwd, normalized, result, action, executionId, previewIdFromApply) {
487
+ const failedCount = result.rows.filter((row) => row.ok === false).length;
488
+ const notRunCount = Math.max(0, normalized.files.length - result.rows.length);
489
+ const filesWritten = result.filesWritten.map((file) => formatRelativePath(cwd, file));
490
+ const plannedFilesCount = countPlannedFiles(normalized.operation, result.rows);
491
+ const operation = `declaration.${normalized.operation}.${action}`;
492
+ const removedBySelector = result.removedBySelector ?? {};
493
+ const addedBySelector = result.addedBySelector ?? {};
494
+ const declarationCount = Object.values(removedBySelector).reduce((sum, items) => sum + items.length, 0);
495
+ const importCount = Object.values(addedBySelector).reduce((sum, items) => sum + items.length, 0);
496
+ const changedCount = normalized.operation === "remove" ? declarationCount : importCount;
497
+ const notFound = normalized.operation === "remove"
498
+ ? buildRemoveNotFound(cwd, normalized, removedBySelector, result.rows)
499
+ : {};
500
+ const notFoundCount = Object.keys(notFound).length;
501
+ const sourceFailures = result.sourceFailures ?? [];
502
+ const skipped = result.skipped ?? [];
503
+ const sourceFailureCount = sourceFailures.length;
504
+ const skippedCount = skipped.length;
505
+ const resolvedSourceCount = result.sourceResolution ? Object.keys(result.sourceResolution).length : 0;
506
+ const failures = normalized.operation === "remove"
507
+ ? collectRemoveFailures(cwd, result.rows)
508
+ : sourceFailures;
509
+ const allRemoveSelectorsMissing = normalized.operation === "remove" &&
510
+ failedCount === 0 &&
511
+ declarationCount === 0 &&
512
+ notFoundCount > 0;
513
+ const hasFailureIssues = failedCount > 0 || sourceFailureCount > 0 || (normalized.execute && skippedCount > 0);
514
+ const previewPartialAllowed = !normalized.execute &&
515
+ (action === "preview" || action === "validate") &&
516
+ hasFailureIssues &&
517
+ (changedCount > 0 || resolvedSourceCount > 0);
518
+ const detailArtifact = !normalized.details && (changedCount > 0 || failedCount > 0 || sourceFailureCount > 0 || skippedCount > 0)
519
+ ? saveDeclarationView(cwd, normalized, result, executionId)
520
+ : null;
521
+ return compactObject({
522
+ ok: allRemoveSelectorsMissing ? false : hasFailureIssues ? previewPartialAllowed : true,
523
+ operation,
524
+ executionId,
525
+ previewId: previewIdFromApply,
526
+ target: normalized.scope ? formatRelativePath(cwd, normalized.scope) : `${normalized.files.length} ${plural(normalized.files.length, "file")}`,
527
+ selectorCount: normalized.selectors.length,
528
+ fileCount: normalized.files.length,
529
+ targetKind: normalized.targetKind,
530
+ details: normalized.details === true ? true : undefined,
531
+ declarationsRemoved: normalized.operation === "remove" ? declarationCount : undefined,
532
+ importsAdded: normalized.operation === "addMissing" ? importCount : undefined,
533
+ notFoundCount: notFoundCount > 0 ? notFoundCount : undefined,
534
+ sourceFailureCount: sourceFailureCount > 0 ? sourceFailureCount : undefined,
535
+ skippedCount: skippedCount > 0 ? skippedCount : undefined,
536
+ plannedFilesCount,
537
+ filesWrittenCount: result.filesWritten.length,
538
+ failedCount: failedCount > 0 || sourceFailureCount > 0 || allRemoveSelectorsMissing ? Math.max(1, failedCount + sourceFailureCount) : undefined,
539
+ notRunCount: notRunCount > 0 ? notRunCount : undefined,
540
+ filesWritten: filesWritten.length > 0 ? compactFiles(filesWritten, 8) : undefined,
541
+ removed: normalized.operation === "remove" ? selectorCounts(removedBySelector) : undefined,
542
+ added: normalized.operation === "addMissing" ? selectorCounts(addedBySelector) : undefined,
543
+ notFound: Object.keys(notFound).length > 0 ? notFound : undefined,
544
+ sources: result.sourceResolution && Object.keys(result.sourceResolution).length > 0 ? formatSourceResolution(cwd, result.sourceResolution) : undefined,
545
+ sourceFailures: sourceFailures.length > 0 ? sourceFailures : undefined,
546
+ skipped: skipped.length > 0 ? skipped : undefined,
547
+ failures: failures.length > 0 ? failures : undefined,
548
+ failed: result.failedRow ? formatFailedRow(cwd, result.failedRow) : undefined,
549
+ view: detailArtifact?.saved,
550
+ detailsFile: detailArtifact?.file,
551
+ internal: {
552
+ requestedSelectors: normalized.selectors,
553
+ resolvedScope: normalized.scope,
554
+ resolvedFiles: normalized.files,
555
+ exclude: normalized.exclude,
556
+ prefer: normalized.prefer,
557
+ details: normalized.details === true ? true : undefined,
558
+ targetKind: normalized.targetKind,
559
+ scannedFiles: result.scannedFiles,
560
+ rows: result.rows,
561
+ notFound,
562
+ sourceResolution: result.sourceResolution,
563
+ sourceFailures,
564
+ skipped,
565
+ failures,
566
+ filesWritten: result.filesWritten
567
+ },
568
+ code: allRemoveSelectorsMissing ? "DECLARATION_REMOVE_NOT_FOUND" : result.failedRow?.code ?? sourceFailures[0]?.code,
569
+ next: buildNext(normalized, changedCount, failedCount, result.failedRow)
570
+ });
571
+ }
572
+ function saveDeclarationView(cwd, normalized, result, executionId) {
573
+ return (0, session_workspace_1.saveSessionResultViewJson)(cwd, `res_${crypto.randomBytes(4).toString("hex")}`, {
574
+ kind: "declarationMutation",
575
+ operation: normalized.operation,
576
+ executionId,
577
+ selectors: normalized.selectors,
578
+ scope: normalized.scope,
579
+ files: normalized.files,
580
+ rows: result.rows,
581
+ sourceResolution: result.sourceResolution,
582
+ sourceFailures: result.sourceFailures,
583
+ skipped: result.skipped,
584
+ filesWritten: result.filesWritten,
585
+ scannedFiles: result.scannedFiles
586
+ });
587
+ }
588
+ function formatDeclarationAgentText(cwd, response) {
589
+ const lines = [];
590
+ const operation = readString(response.operation) ?? "declaration";
591
+ const id = readString(response.executionId) ?? readString(response.previewId);
592
+ const isAddMissing = operation.includes("addMissing");
593
+ const isPreviewLike = operation.endsWith(".preview") || operation.endsWith(".validate");
594
+ lines.push(id ? `${operation} ${id}` : operation);
595
+ const selectorCount = numberField(response, "selectorCount");
596
+ const changed = numberField(response, isAddMissing ? "importsAdded" : "declarationsRemoved");
597
+ const affectedFiles = isPreviewLike ? numberField(response, "plannedFilesCount") : numberField(response, "filesWrittenCount");
598
+ const failed = numberField(response, "failedCount");
599
+ const notRun = numberField(response, "notRunCount");
600
+ const notFoundCount = numberField(response, "notFoundCount");
601
+ const skippedCount = numberField(response, "skippedCount");
602
+ const allMissingRemove = readString(response.code) === "DECLARATION_REMOVE_NOT_FOUND";
603
+ if (allMissingRemove) {
604
+ lines.push("No requested declarations were found.");
605
+ appendDeclarationNotFoundLines(lines, response);
606
+ if (readString(response.next)) {
607
+ lines.push(`next: ${readString(response.next)}`);
608
+ }
609
+ return lines.join("\n");
610
+ }
611
+ const changedPhrase = isAddMissing
612
+ ? `${changed} ${plural(changed, "import")} ${isPreviewLike ? "planned" : "added"}`
613
+ : `${changed} ${plural(changed, "declaration")} ${isPreviewLike ? "found" : "removed"}`;
614
+ const summaryParts = [`${selectorCount} ${plural(selectorCount, "selector")}`, changedPhrase];
615
+ if (notFoundCount > 0 && !isAddMissing) {
616
+ summaryParts.push(`${notFoundCount} ${plural(notFoundCount, "selector")} not found`);
617
+ }
618
+ if (skippedCount > 0) {
619
+ summaryParts.push(`${skippedCount} ${plural(skippedCount, "selector")} skipped`);
620
+ }
621
+ if (notRun > 0 && readString(response.targetKind) === "files") {
622
+ summaryParts.push(`${notRun} ${plural(notRun, "file")} not run`);
623
+ }
624
+ if (!isPreviewLike || failed === 0) {
625
+ summaryParts.push(`${affectedFiles} ${plural(affectedFiles, "file")} ${isPreviewLike ? "will be written" : "written"}`);
626
+ }
627
+ lines.push(summaryParts.join(", "));
628
+ if (response.details === true && isObject(response.internal)) {
629
+ const rows = Array.isArray(response.internal.rows) ? response.internal.rows.filter(isObject) : [];
630
+ lines.push(...(0, declaration_format_1.formatDeclarationMutationDetails)(cwd, isAddMissing ? "addMissing" : "remove", rows));
631
+ }
632
+ else {
633
+ const grouped = isObject(response.removed) ? response.removed : isObject(response.added) ? response.added : null;
634
+ if (grouped && Object.keys(grouped).length > 0) {
635
+ lines.push(isAddMissing ? (isPreviewLike ? "planned imports:" : "added:") : (isPreviewLike ? "planned removes:" : "removed:"));
636
+ for (const [selector, count] of Object.entries(grouped)) {
637
+ lines.push(`${selector}: ${count} ${plural(Number(count), "file")}`);
638
+ }
639
+ }
640
+ else {
641
+ lines.push(isAddMissing ? (isPreviewLike ? "planned imports: none" : "added: none") : (isPreviewLike ? "planned removes: none" : "removed: none"));
642
+ }
643
+ }
644
+ if (response.details !== true) {
645
+ appendDeclarationSourcesLines(lines, response);
646
+ appendDeclarationFailureLines(lines, response);
647
+ appendDeclarationSkippedLines(lines, response);
648
+ }
649
+ if (response.details !== true && !isAddMissing) {
650
+ appendDeclarationNotFoundLines(lines, response);
651
+ }
652
+ if (response.details !== true && readString(response.view)) {
653
+ lines.push(`view: ${readString(response.view)}`);
654
+ }
655
+ if (readString(response.next)) {
656
+ lines.push(`next: ${readString(response.next)}`);
657
+ }
658
+ return lines.join("\n");
659
+ }
660
+ function formatDeclarationStatusText(status) {
661
+ return `${status.status}, ${status.completedRows}/${status.rowCount} rows\n${status.operation}`;
662
+ }
663
+ function declarationHelp(operation) {
664
+ const usage = operation
665
+ ? `aib declaration ${operation} preview --stdin | aib declaration ${operation} execute --stdin | aib declaration ${operation} apply <previewId>`
666
+ : "aib declaration remove execute --stdin | aib declaration addMissing execute --stdin";
667
+ return {
668
+ ok: true,
669
+ command: operation ? `declaration ${operation}` : "declaration",
670
+ usage
671
+ };
672
+ }
673
+ function readOperation(value) {
674
+ if (value === "remove" || value === "addMissing") {
675
+ return value;
676
+ }
677
+ if (value === "add-missing") {
678
+ return "addMissing";
679
+ }
680
+ throw new errors_1.CliError("UNKNOWN_DECLARATION_COMMAND", `Unknown declaration command: ${value}`, {
681
+ availableCommands: ["remove", "addMissing", "help"]
682
+ });
683
+ }
684
+ function persistProgress(cwd, status, rows, filesWritten) {
685
+ status.completedRows = rows.filter((row) => row.ok).length;
686
+ status.failedRows = rows.filter((row) => row.ok === false).length;
687
+ status.filesWritten = filesWritten;
688
+ status.rows = rows;
689
+ (0, declaration_execution_cache_1.writeDeclarationExecutionStatus)(cwd, status);
690
+ }
691
+ function normalizedPayloadForCache(normalized) {
692
+ return compactObject({
693
+ operation: normalized.operation,
694
+ scope: normalized.scope,
695
+ files: normalized.files,
696
+ selectors: normalized.selectors,
697
+ exclude: normalized.exclude,
698
+ prefer: normalized.prefer,
699
+ details: normalized.details === true ? true : undefined,
700
+ sourceCheckOnly: normalized.sourceCheckOnly === true ? true : undefined,
701
+ cleanupTail: normalized.cleanupTail === true ? true : undefined,
702
+ continueOnFailure: normalized.continueOnFailure === true ? true : undefined,
703
+ targetKind: normalized.targetKind
704
+ });
705
+ }
706
+ function collectTopLevelDeclarations(sourceFile) {
707
+ const declarations = [];
708
+ for (const statement of sourceFile.statements) {
709
+ if (typescript_1.default.isFunctionDeclaration(statement) || typescript_1.default.isClassDeclaration(statement) || typescript_1.default.isInterfaceDeclaration(statement) || typescript_1.default.isTypeAliasDeclaration(statement) || typescript_1.default.isEnumDeclaration(statement)) {
710
+ const name = statement.name?.text;
711
+ if (name) {
712
+ declarations.push(buildDeclarationMatch(sourceFile, statement, name, kindForDeclaration(statement)));
713
+ }
714
+ continue;
715
+ }
716
+ if (typescript_1.default.isVariableStatement(statement)) {
717
+ if (statement.declarationList.declarations.length !== 1) {
718
+ for (const declaration of statement.declarationList.declarations) {
719
+ const name = typescript_1.default.isIdentifier(declaration.name) ? declaration.name.text : null;
720
+ if (name) {
721
+ declarations.push({
722
+ ...buildDeclarationMatch(sourceFile, statement, name, "variable"),
723
+ kind: "variable-group"
724
+ });
725
+ }
726
+ }
727
+ continue;
728
+ }
729
+ const declaration = statement.declarationList.declarations[0];
730
+ const name = typescript_1.default.isIdentifier(declaration.name) ? declaration.name.text : null;
731
+ if (name) {
732
+ declarations.push(buildDeclarationMatch(sourceFile, statement, name, "variable"));
733
+ }
734
+ }
735
+ }
736
+ return declarations;
737
+ }
738
+ function buildDeclarationMatch(sourceFile, node, selector, kind) {
739
+ return {
740
+ selector,
741
+ file: sourceFile.fileName,
742
+ line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
743
+ exported: hasExportModifier(node),
744
+ kind,
745
+ start: node.getFullStart(),
746
+ end: node.end,
747
+ node
748
+ };
749
+ }
750
+ function kindForDeclaration(node) {
751
+ if (typescript_1.default.isFunctionDeclaration(node))
752
+ return "function";
753
+ if (typescript_1.default.isClassDeclaration(node))
754
+ return "class";
755
+ if (typescript_1.default.isInterfaceDeclaration(node))
756
+ return "interface";
757
+ if (typescript_1.default.isTypeAliasDeclaration(node))
758
+ return "type";
759
+ if (typescript_1.default.isEnumDeclaration(node))
760
+ return "enum";
761
+ return "declaration";
762
+ }
763
+ function hasExportModifier(node) {
764
+ return Boolean(typescript_1.default.canHaveModifiers(node) && typescript_1.default.getModifiers(node)?.some((modifier) => modifier.kind === typescript_1.default.SyntaxKind.ExportKeyword));
765
+ }
766
+ function collectExportedNames(file) {
767
+ const text = fs.readFileSync(file, "utf8");
768
+ const sourceFile = typescript_1.default.createSourceFile(file, text, typescript_1.default.ScriptTarget.Latest, true, scriptKindForFile(file));
769
+ const names = [];
770
+ for (const declaration of collectTopLevelDeclarations(sourceFile)) {
771
+ if (declaration.exported) {
772
+ names.push(declaration.selector);
773
+ }
774
+ }
775
+ for (const statement of sourceFile.statements) {
776
+ if (typescript_1.default.isExportDeclaration(statement) && statement.exportClause && typescript_1.default.isNamedExports(statement.exportClause) && !statement.moduleSpecifier) {
777
+ for (const element of statement.exportClause.elements) {
778
+ names.push(element.name.text);
779
+ }
780
+ }
781
+ }
782
+ return [...new Set(names)];
783
+ }
784
+ function collectExistingBindings(sourceFile) {
785
+ const names = new Set();
786
+ for (const statement of sourceFile.statements) {
787
+ for (const declaration of collectTopLevelDeclarations(sourceFile).filter((item) => item.node === statement)) {
788
+ names.add(declaration.selector);
789
+ }
790
+ if (typescript_1.default.isImportDeclaration(statement) && statement.importClause) {
791
+ if (statement.importClause.name) {
792
+ names.add(statement.importClause.name.text);
793
+ }
794
+ const namedBindings = statement.importClause.namedBindings;
795
+ if (namedBindings && typescript_1.default.isNamedImports(namedBindings)) {
796
+ for (const element of namedBindings.elements) {
797
+ names.add(element.name.text);
798
+ }
799
+ }
800
+ if (namedBindings && typescript_1.default.isNamespaceImport(namedBindings)) {
801
+ names.add(namedBindings.name.text);
802
+ }
803
+ }
804
+ }
805
+ return names;
806
+ }
807
+ function collectMissingNamesWithTypeScript(file, text) {
808
+ const options = {
809
+ allowJs: true,
810
+ checkJs: true,
811
+ jsx: typescript_1.default.JsxEmit.ReactJSX,
812
+ module: typescript_1.default.ModuleKind.ESNext,
813
+ target: typescript_1.default.ScriptTarget.ES2022,
814
+ noEmit: true
815
+ };
816
+ const host = typescript_1.default.createCompilerHost(options);
817
+ host.readFile = (fileName) => path.resolve(fileName) === path.resolve(file) ? text : fs.existsSync(fileName) ? fs.readFileSync(fileName, "utf8") : undefined;
818
+ host.fileExists = (fileName) => path.resolve(fileName) === path.resolve(file) || fs.existsSync(fileName);
819
+ const program = typescript_1.default.createProgram([file], options, host);
820
+ const diagnostics = program.getSemanticDiagnostics(program.getSourceFile(file));
821
+ const names = diagnostics
822
+ .filter((diagnostic) => diagnostic.code === 2304 || diagnostic.code === 2552)
823
+ .map((diagnostic) => typescript_1.default.flattenDiagnosticMessageText(diagnostic.messageText, "\n"))
824
+ .map((message) => message.match(/Cannot find name '([^']+)'/)?.[1] ?? message.match(/Did you mean '([^']+)'/)?.[1] ?? "")
825
+ .filter(Boolean);
826
+ return [...new Set(names)];
827
+ }
828
+ function collectFilesFromInputs(cwd, inputs, exclude, options = {}) {
829
+ const excluded = buildExcludeMatcher(cwd, exclude);
830
+ const files = [];
831
+ for (const input of inputs) {
832
+ const resolved = path.resolve(cwd, input);
833
+ if (hasGlob(input)) {
834
+ files.push(...collectSourceFiles(cwd).filter((file) => globToRegex(toSlash(input)).test(toSlash(path.relative(cwd, file)))));
835
+ continue;
836
+ }
837
+ if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory() && options.explicitFiles !== true) {
838
+ files.push(...collectSourceFiles(resolved));
839
+ continue;
840
+ }
841
+ files.push(resolved);
842
+ }
843
+ const collected = [...new Set(files.filter((file) => isSourceFile(file) && !excluded(file)))];
844
+ return options.explicitFiles === true ? collected : collected.sort();
845
+ }
846
+ function collectSourceFiles(scope) {
847
+ if (!fs.existsSync(scope)) {
848
+ return [];
849
+ }
850
+ const stat = fs.statSync(scope);
851
+ if (stat.isFile()) {
852
+ return isSourceFile(scope) ? [scope] : [];
853
+ }
854
+ if (!stat.isDirectory()) {
855
+ return [];
856
+ }
857
+ const files = [];
858
+ for (const entry of fs.readdirSync(scope, { withFileTypes: true })) {
859
+ if (["node_modules", ".git", "dist", "out", "build", ".tmp"].includes(entry.name)) {
860
+ continue;
861
+ }
862
+ const child = path.join(scope, entry.name);
863
+ if (entry.isDirectory()) {
864
+ files.push(...collectSourceFiles(child));
865
+ }
866
+ else if (entry.isFile() && isSourceFile(child)) {
867
+ files.push(child);
868
+ }
869
+ }
870
+ return files;
871
+ }
872
+ function buildExcludeMatcher(cwd, exclude) {
873
+ const exact = new Set(exclude.filter((item) => !hasGlob(item)).map((item) => path.resolve(cwd, item)));
874
+ const globs = exclude.filter(hasGlob).map((item) => globToRegex(toSlash(item)));
875
+ return (file) => exact.has(path.resolve(file)) || globs.some((glob) => glob.test(toSlash(path.relative(cwd, file))));
876
+ }
877
+ function hasGlob(value) {
878
+ return value.includes("*");
879
+ }
880
+ function globToRegex(glob) {
881
+ const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&")
882
+ .replace(/\*\*/g, "__AIB_GLOBSTAR__")
883
+ .replace(/\*/g, "[^/]*");
884
+ return new RegExp(`^${escaped.replace(/__AIB_GLOBSTAR__/g, ".*")}$`);
885
+ }
886
+ function applyTextEdits(text, edits) {
887
+ let output = text;
888
+ const sorted = [...edits].sort((left, right) => right.start - left.start);
889
+ for (const edit of sorted) {
890
+ output = `${output.slice(0, edit.start)}${edit.newText}${output.slice(edit.end)}`;
891
+ }
892
+ return output;
893
+ }
894
+ function importInsertOffset(text, sourceFile) {
895
+ let offset = 0;
896
+ for (const statement of sourceFile.statements) {
897
+ if (!typescript_1.default.isImportDeclaration(statement)) {
898
+ break;
899
+ }
900
+ offset = extendToFollowingLineBreak(text, statement.end);
901
+ }
902
+ return offset;
903
+ }
904
+ function extendToFollowingLineBreak(text, end) {
905
+ let next = end;
906
+ while (next < text.length && (text[next] === "\r" || text[next] === "\n")) {
907
+ next += 1;
908
+ if (text[next - 1] === "\n") {
909
+ break;
910
+ }
911
+ }
912
+ return next;
913
+ }
914
+ function relativeModuleSpecifier(fromFile, toFile) {
915
+ let relative = toSlash(path.relative(path.dirname(fromFile), toFile));
916
+ relative = relative.replace(/\.(tsx?|jsx?|mjs|cjs)$/i, "");
917
+ if (!relative.startsWith(".")) {
918
+ relative = `./${relative}`;
919
+ }
920
+ return relative;
921
+ }
922
+ function scriptKindForFile(file) {
923
+ if (/\.tsx$/i.test(file))
924
+ return typescript_1.default.ScriptKind.TSX;
925
+ if (/\.jsx$/i.test(file))
926
+ return typescript_1.default.ScriptKind.JSX;
927
+ if (/\.[cm]?js$/i.test(file))
928
+ return typescript_1.default.ScriptKind.JS;
929
+ return typescript_1.default.ScriptKind.TS;
930
+ }
931
+ function isSourceFile(file) {
932
+ return /\.(tsx?|jsx?|mjs|cjs)$/i.test(file) && !file.endsWith(".d.ts");
933
+ }
934
+ function isDirectory(file) {
935
+ return fs.existsSync(file) && fs.statSync(file).isDirectory();
936
+ }
937
+ function isCommonJsFile(file, text) {
938
+ return /\.cjs$/i.test(file) || /\bmodule\.exports\b|\bexports\.[A-Za-z_$]/.test(text);
939
+ }
940
+ function containsIdentifier(text, selector) {
941
+ return new RegExp(`\\b${escapeRegex(selector)}\\b`).test(text);
942
+ }
943
+ function escapeRegex(value) {
944
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
945
+ }
946
+ function selectorCounts(input) {
947
+ const output = {};
948
+ for (const [selector, items] of Object.entries(input)) {
949
+ if (items.length > 0) {
950
+ output[selector] = items.length;
951
+ }
952
+ }
953
+ return output;
954
+ }
955
+ function countPlannedFiles(operation, rows) {
956
+ return rows.filter((row) => {
957
+ const items = operation === "addMissing" ? row.addedImports : row.removed;
958
+ return Array.isArray(items) && items.length > 0;
959
+ }).length;
960
+ }
961
+ function formatFailedRow(cwd, row) {
962
+ return compactObject({
963
+ file: formatRelativePath(cwd, row.file),
964
+ selector: readString(row.failedSelector) ?? (Array.isArray(row.selectors) ? row.selectors[0] : undefined),
965
+ availableSelectors: Array.isArray(row.availableSelectors) ? row.availableSelectors : undefined,
966
+ code: row.code,
967
+ error: row.error
968
+ });
969
+ }
970
+ function buildNext(normalized, changedCount, failedCount, failedRow) {
971
+ if (failedCount > 0) {
972
+ if (failedRow?.code === "DECLARATION_REMOVE_AMBIGUOUS") {
973
+ const selector = readString(failedRow.failedSelector) ?? "the ambiguous selector";
974
+ return normalized.targetKind === "scope"
975
+ ? `Use a qualified selector for ${selector} or exclude the file, then rerun declaration remove for the scope.`
976
+ : `Use a qualified selector for ${selector} and rerun declaration remove for the remaining files.`;
977
+ }
978
+ return normalized.operation === "remove"
979
+ ? "Fix failed selector/file and rerun declaration remove for remaining targets."
980
+ : "Fix failed selector/source and rerun declaration addMissing for remaining targets.";
981
+ }
982
+ if (changedCount === 0) {
983
+ return normalized.operation === "remove"
984
+ ? "Nothing removed. Check selector names or target files."
985
+ : "No missing imports added. Check selectors, prefer sources, or target files.";
986
+ }
987
+ return normalized.operation === "remove"
988
+ ? "run addMissing with desired selectors"
989
+ : "verify affected files only if checks report an issue";
990
+ }
991
+ function buildRemoveNotFound(cwd, normalized, removedBySelector, rows) {
992
+ const okRows = rows.filter((row) => row.ok !== false);
993
+ const scannedFiles = okRows.length > 0 ? okRows.map((row) => row.file) : normalized.files;
994
+ const output = {};
995
+ const failedSelectors = new Set(collectRemoveFailures(cwd, rows).map((failure) => readString(failure.selector)).filter((selector) => Boolean(selector)));
996
+ for (const selector of normalized.selectors) {
997
+ if ((removedBySelector[selector] ?? []).length > 0) {
998
+ continue;
999
+ }
1000
+ if (failedSelectors.has(selector)) {
1001
+ continue;
1002
+ }
1003
+ output[selector] = compactFiles(scannedFiles.map((file) => formatRelativePath(cwd, file)), 8);
1004
+ }
1005
+ return output;
1006
+ }
1007
+ function collectRemoveFailures(cwd, rows) {
1008
+ const failures = [];
1009
+ for (const row of rows) {
1010
+ const rowFailures = Array.isArray(row.failures) ? row.failures.filter(isObject) : [];
1011
+ if (rowFailures.length > 0) {
1012
+ for (const failure of rowFailures) {
1013
+ failures.push(formatFailure(cwd, failure, row.file));
1014
+ }
1015
+ continue;
1016
+ }
1017
+ if (row.ok === false) {
1018
+ failures.push(formatFailedRow(cwd, row));
1019
+ }
1020
+ }
1021
+ return failures;
1022
+ }
1023
+ function formatFailure(cwd, failure, fallbackFile) {
1024
+ return compactObject({
1025
+ file: formatRelativePath(cwd, readString(failure.file) ?? fallbackFile),
1026
+ selector: readString(failure.selector),
1027
+ availableSelectors: Array.isArray(failure.availableSelectors) ? failure.availableSelectors : undefined,
1028
+ code: readString(failure.code),
1029
+ error: readString(failure.error)
1030
+ });
1031
+ }
1032
+ function formatSourceResolution(cwd, resolution) {
1033
+ const output = {};
1034
+ for (const [selector, source] of Object.entries(resolution)) {
1035
+ output[selector] = formatRelativePath(cwd, source);
1036
+ }
1037
+ return output;
1038
+ }
1039
+ function appendDeclarationSourcesLines(lines, response) {
1040
+ if (!isObject(response.sources) || Object.keys(response.sources).length === 0) {
1041
+ return;
1042
+ }
1043
+ lines.push("sources:");
1044
+ for (const [selector, source] of Object.entries(response.sources)) {
1045
+ if (typeof source === "string") {
1046
+ lines.push(`${selector} -> ${source}`);
1047
+ }
1048
+ }
1049
+ }
1050
+ function appendDeclarationFailureLines(lines, response) {
1051
+ const failures = readFailureList(response);
1052
+ if (failures.length === 0) {
1053
+ return;
1054
+ }
1055
+ lines.push("failed:");
1056
+ for (const failure of failures) {
1057
+ const selector = readString(failure.selector) ?? "selector";
1058
+ const file = readString(failure.file);
1059
+ const code = readString(failure.code);
1060
+ if (code === "DECLARATION_REMOVE_AMBIGUOUS") {
1061
+ lines.push(file ? `${selector}: ambiguous in ${file}` : `${selector}: ambiguous`);
1062
+ appendAvailableSelectors(lines, failure);
1063
+ continue;
1064
+ }
1065
+ if (code === "DECLARATION_ADD_MISSING_SOURCE_AMBIGUOUS") {
1066
+ lines.push(`${selector}: multiple preferred sources export selector`);
1067
+ appendFailureSources(lines, failure);
1068
+ continue;
1069
+ }
1070
+ if (code === "DECLARATION_ADD_MISSING_SOURCE_NOT_FOUND") {
1071
+ lines.push(`${selector}: no preferred source exports selector`);
1072
+ continue;
1073
+ }
1074
+ const error = readString(failure.error);
1075
+ lines.push(error ? `${selector}: ${error}` : selector);
1076
+ }
1077
+ }
1078
+ function readFailureList(response) {
1079
+ const failures = Array.isArray(response.failures) ? response.failures.filter(isObject) : [];
1080
+ const sourceFailures = Array.isArray(response.sourceFailures) ? response.sourceFailures.filter(isObject) : [];
1081
+ if (failures.length > 0 || sourceFailures.length > 0) {
1082
+ return [...failures, ...sourceFailures];
1083
+ }
1084
+ return isObject(response.failed) ? [response.failed] : [];
1085
+ }
1086
+ function appendAvailableSelectors(lines, failure) {
1087
+ const available = Array.isArray(failure.availableSelectors)
1088
+ ? failure.availableSelectors.filter((item) => typeof item === "string" && item.trim() !== "")
1089
+ : [];
1090
+ if (available.length === 0) {
1091
+ return;
1092
+ }
1093
+ lines.push("Available selectors:");
1094
+ for (const item of available) {
1095
+ lines.push(item);
1096
+ }
1097
+ }
1098
+ function appendFailureSources(lines, failure) {
1099
+ const sources = Array.isArray(failure.sources)
1100
+ ? failure.sources.filter((item) => typeof item === "string" && item.trim() !== "")
1101
+ : [];
1102
+ if (sources.length === 0) {
1103
+ return;
1104
+ }
1105
+ lines.push("sources:");
1106
+ for (const source of sources) {
1107
+ lines.push(source);
1108
+ }
1109
+ }
1110
+ function appendDeclarationSkippedLines(lines, response) {
1111
+ const skipped = Array.isArray(response.skipped) ? response.skipped.filter(isObject) : [];
1112
+ if (skipped.length === 0) {
1113
+ return;
1114
+ }
1115
+ lines.push("skipped:");
1116
+ for (const item of skipped) {
1117
+ const selector = readString(item.selector) ?? "selector";
1118
+ const operation = readString(item.operation);
1119
+ const reason = readString(item.reason);
1120
+ lines.push(`${selector}${operation ? ` ${operation}` : ""}${reason ? ` skipped for ${reason}` : " skipped"}`);
1121
+ }
1122
+ }
1123
+ function appendDeclarationNotFoundLines(lines, response) {
1124
+ if (!isObject(response.notFound) || Object.keys(response.notFound).length === 0) {
1125
+ return;
1126
+ }
1127
+ lines.push("notFound:");
1128
+ for (const [selector, files] of Object.entries(response.notFound)) {
1129
+ const list = Array.isArray(files)
1130
+ ? files.filter((item) => typeof item === "string" && item.trim() !== "")
1131
+ : [];
1132
+ lines.push(`${selector}: ${list.length > 0 ? list.join(", ") : "no matching files"}`);
1133
+ }
1134
+ }
1135
+ function parseDeclarationSelector(selector) {
1136
+ const trimmed = selector.trim();
1137
+ for (const separator of [defaults_1.DEFAULT_EFFECTIVE_CONFIG.selectorSeparator, ":", "-"]) {
1138
+ const index = trimmed.indexOf(separator);
1139
+ if (index <= 0) {
1140
+ continue;
1141
+ }
1142
+ const maybeKind = declarationKindFromAlias(trimmed.slice(0, index));
1143
+ const name = trimmed.slice(index + separator.length).trim();
1144
+ if (maybeKind && name) {
1145
+ return { raw: trimmed, name, kind: maybeKind };
1146
+ }
1147
+ }
1148
+ return { raw: trimmed, name: trimmed, kind: null };
1149
+ }
1150
+ function formatDeclarationSelector(kind, name) {
1151
+ const normalizedKind = normalizedDeclarationKind(kind);
1152
+ const alias = declarationAliasForKind(normalizedKind) ?? normalizedKind;
1153
+ return `${alias}${defaults_1.DEFAULT_EFFECTIVE_CONFIG.selectorSeparator}${name}`;
1154
+ }
1155
+ function declarationKindFromAlias(value) {
1156
+ const normalized = normalizedDeclarationKind(value);
1157
+ if (declarationAliasForKind(normalized) !== null) {
1158
+ return normalized;
1159
+ }
1160
+ const kind = Object.entries(defaults_1.DEFAULT_EFFECTIVE_CONFIG.entityKindAliases).find(([, alias]) => alias === value)?.[0];
1161
+ return kind ? normalizedDeclarationKind(kind) : null;
1162
+ }
1163
+ function declarationAliasForKind(kind) {
1164
+ const normalized = normalizedDeclarationKind(kind);
1165
+ if (normalized === "class" || normalized === "interface" || normalized === "type" || normalized === "function" || normalized === "variable" || normalized === "enum") {
1166
+ return defaults_1.DEFAULT_EFFECTIVE_CONFIG.entityKindAliases[normalized];
1167
+ }
1168
+ return null;
1169
+ }
1170
+ function normalizedDeclarationKind(kind) {
1171
+ return kind === "variable-group" ? "variable" : kind;
1172
+ }
1173
+ function compactFiles(files, limit) {
1174
+ return files.length <= limit ? files : [...files.slice(0, limit), `+ ${files.length - limit} more`];
1175
+ }
1176
+ function readStringArray(value) {
1177
+ return Array.isArray(value) ? [...new Set(value.filter((item) => typeof item === "string" && item.trim() !== "").map((item) => item.trim()))] : [];
1178
+ }
1179
+ function readString(value) {
1180
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
1181
+ }
1182
+ function numberField(value, field) {
1183
+ const raw = value[field];
1184
+ return typeof raw === "number" && Number.isFinite(raw) ? raw : 0;
1185
+ }
1186
+ function compactObject(input) {
1187
+ const output = {};
1188
+ for (const [key, value] of Object.entries(input)) {
1189
+ if (value !== undefined && value !== null) {
1190
+ output[key] = value;
1191
+ }
1192
+ }
1193
+ return output;
1194
+ }
1195
+ function isObject(value) {
1196
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1197
+ }
1198
+ function formatRelativePath(cwd, file) {
1199
+ const relative = path.relative(cwd, file);
1200
+ return relative && !relative.startsWith("..") && !path.isAbsolute(relative)
1201
+ ? toSlash(relative)
1202
+ : toSlash(file);
1203
+ }
1204
+ function toSlash(value) {
1205
+ return value.replace(/\\/g, "/");
1206
+ }
1207
+ function plural(count, singular) {
1208
+ return count === 1 ? singular : `${singular}s`;
1209
+ }