@lesliechan721/aw 0.1.0-beta.7 → 0.1.0-beta.72

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 (726) hide show
  1. package/dist/authoring/assets/aw-config.mjs +100 -501
  2. package/dist/authoring/assets/aw-config.mjs.map +1 -1
  3. package/dist/authoring/assets/aw-runtime-config.d.mts +13 -0
  4. package/dist/authoring/assets/aw-runtime-config.mjs +199 -0
  5. package/dist/authoring/assets/aw-runtime-config.mjs.map +1 -0
  6. package/dist/authoring/scripts/add-skill.mjs +13 -27
  7. package/dist/authoring/scripts/add-skill.mjs.map +1 -1
  8. package/dist/authoring/scripts/init-plugin.mjs +74 -103
  9. package/dist/authoring/scripts/init-plugin.mjs.map +1 -1
  10. package/dist/authoring/scripts/lib/plugin-root.mjs +4 -4
  11. package/dist/authoring/scripts/lib/plugin-root.mjs.map +1 -1
  12. package/dist/authoring/scripts/lib/plugin-version-check.d.mts +1 -0
  13. package/dist/authoring/scripts/lib/plugin-version-check.mjs +229 -8
  14. package/dist/authoring/scripts/lib/plugin-version-check.mjs.map +1 -1
  15. package/dist/authoring/scripts/lib/skill-scaffold.d.mts +79 -92
  16. package/dist/authoring/scripts/lib/skill-scaffold.mjs +103 -126
  17. package/dist/authoring/scripts/lib/skill-scaffold.mjs.map +1 -1
  18. package/dist/authoring/scripts/plugin-status.mjs +8 -11
  19. package/dist/authoring/scripts/plugin-status.mjs.map +1 -1
  20. package/dist/authoring/scripts/remove-plugin.mjs +3 -2
  21. package/dist/authoring/scripts/remove-plugin.mjs.map +1 -1
  22. package/dist/authoring/scripts/validate-plugin.mjs +527 -1673
  23. package/dist/authoring/scripts/validate-plugin.mjs.map +1 -1
  24. package/dist/authoring/scripts/validate-skill.mjs +1 -1
  25. package/dist/native-runtime/reader-runtime.mjs +34 -0
  26. package/dist/native-runtime/reader.d.mts +6 -0
  27. package/dist/native-runtime/reader.mjs +11 -0
  28. package/dist/scripts/aw-skill-eval-materializer.d.ts +28 -0
  29. package/dist/scripts/aw-skill-eval-materializer.js +339 -0
  30. package/dist/scripts/aw-skill-eval-materializer.js.map +1 -0
  31. package/dist/scripts/bundle-plugins.d.ts +1 -0
  32. package/dist/scripts/bundle-plugins.js +27 -8
  33. package/dist/scripts/bundle-plugins.js.map +1 -1
  34. package/dist/scripts/plugin-staging.d.ts +8 -10
  35. package/dist/scripts/plugin-staging.js +19 -30
  36. package/dist/scripts/plugin-staging.js.map +1 -1
  37. package/dist/scripts/plugin-test-reporter.d.mts +2 -0
  38. package/dist/scripts/plugin-test-reporter.mjs +21 -0
  39. package/dist/scripts/plugin-test-reporter.mjs.map +1 -0
  40. package/dist/scripts/test-plugin-scripts.d.ts +5 -0
  41. package/dist/scripts/test-plugin-scripts.js +246 -108
  42. package/dist/scripts/test-plugin-scripts.js.map +1 -1
  43. package/dist/scripts/test-workers.d.mts +24 -0
  44. package/dist/scripts/test-workers.mjs +59 -0
  45. package/dist/scripts/test-workers.mjs.map +1 -0
  46. package/dist/src/adapters/helpers.d.ts +7 -0
  47. package/dist/src/adapters/helpers.js +2 -2
  48. package/dist/src/adapters/helpers.js.map +1 -1
  49. package/dist/src/authoring/workspace-commands.d.ts +20 -1
  50. package/dist/src/authoring/workspace-commands.js +28 -6
  51. package/dist/src/authoring/workspace-commands.js.map +1 -1
  52. package/dist/src/commands/aw-capabilities.d.ts +78 -0
  53. package/dist/src/commands/aw-capabilities.js +270 -0
  54. package/dist/src/commands/aw-capabilities.js.map +1 -0
  55. package/dist/src/commands/catalog-dev-source.d.ts +157 -0
  56. package/dist/src/commands/catalog-dev-source.js +725 -0
  57. package/dist/src/commands/catalog-dev-source.js.map +1 -0
  58. package/dist/src/commands/catalog-generation.d.ts +21 -0
  59. package/dist/src/commands/catalog-generation.js +9 -0
  60. package/dist/src/commands/catalog-generation.js.map +1 -0
  61. package/dist/src/commands/catalog-publication-inspection.d.ts +71 -30
  62. package/dist/src/commands/catalog-publication-inspection.js +475 -63
  63. package/dist/src/commands/catalog-publication-inspection.js.map +1 -1
  64. package/dist/src/commands/catalog-publication-journal.d.ts +68 -0
  65. package/dist/src/commands/catalog-publication-journal.js +292 -0
  66. package/dist/src/commands/catalog-publication-journal.js.map +1 -0
  67. package/dist/src/commands/catalog-publication-target.d.ts +18 -0
  68. package/dist/src/commands/catalog-publication-target.js +95 -0
  69. package/dist/src/commands/catalog-publication-target.js.map +1 -0
  70. package/dist/src/commands/catalog-publish.d.ts +89 -15
  71. package/dist/src/commands/catalog-publish.js +736 -210
  72. package/dist/src/commands/catalog-publish.js.map +1 -1
  73. package/dist/src/commands/catalog-source.d.ts +64 -22
  74. package/dist/src/commands/catalog-source.js +327 -91
  75. package/dist/src/commands/catalog-source.js.map +1 -1
  76. package/dist/src/commands/catalog-status.d.ts +18 -22
  77. package/dist/src/commands/catalog-status.js +82 -116
  78. package/dist/src/commands/catalog-status.js.map +1 -1
  79. package/dist/src/commands/catalog-store.d.ts +104 -0
  80. package/dist/src/commands/catalog-store.js +685 -0
  81. package/dist/src/commands/catalog-store.js.map +1 -0
  82. package/dist/src/commands/catalog-workspace-resolution.d.ts +17 -0
  83. package/dist/src/commands/catalog-workspace-resolution.js +57 -0
  84. package/dist/src/commands/catalog-workspace-resolution.js.map +1 -0
  85. package/dist/src/commands/console.js +32 -20
  86. package/dist/src/commands/console.js.map +1 -1
  87. package/dist/src/commands/dependency-operation-plan.d.ts +52 -15
  88. package/dist/src/commands/dependency-operation-plan.js +289 -7
  89. package/dist/src/commands/dependency-operation-plan.js.map +1 -1
  90. package/dist/src/commands/init.d.ts +5 -11
  91. package/dist/src/commands/init.js +30 -51
  92. package/dist/src/commands/init.js.map +1 -1
  93. package/dist/src/commands/intent-command.d.ts +32 -0
  94. package/dist/src/commands/intent-command.js +171 -0
  95. package/dist/src/commands/intent-command.js.map +1 -0
  96. package/dist/src/commands/managed-commands.d.ts +35 -0
  97. package/dist/src/commands/managed-commands.js +359 -0
  98. package/dist/src/commands/managed-commands.js.map +1 -0
  99. package/dist/src/commands/offline-cleanup-evidence.d.ts +67 -0
  100. package/dist/src/commands/offline-cleanup-evidence.js +181 -0
  101. package/dist/src/commands/offline-cleanup-evidence.js.map +1 -0
  102. package/dist/src/commands/operation-plan.d.ts +184 -0
  103. package/dist/src/commands/operation-plan.js +72 -0
  104. package/dist/src/commands/operation-plan.js.map +1 -0
  105. package/dist/src/commands/operation-planner.d.ts +47 -0
  106. package/dist/src/commands/operation-planner.js +142 -0
  107. package/dist/src/commands/operation-planner.js.map +1 -0
  108. package/dist/src/commands/options.d.ts +10 -17
  109. package/dist/src/commands/options.js +91 -38
  110. package/dist/src/commands/options.js.map +1 -1
  111. package/dist/src/commands/plugin-capabilities.js +85 -30
  112. package/dist/src/commands/plugin-capabilities.js.map +1 -1
  113. package/dist/src/commands/public-config-confirmation.d.ts +8 -0
  114. package/dist/src/commands/public-config-confirmation.js +56 -0
  115. package/dist/src/commands/public-config-confirmation.js.map +1 -0
  116. package/dist/src/commands/public-interruption.d.ts +9 -0
  117. package/dist/src/commands/public-interruption.js +23 -0
  118. package/dist/src/commands/public-interruption.js.map +1 -0
  119. package/dist/src/commands/public-lifecycle-result.d.ts +53 -0
  120. package/dist/src/commands/public-lifecycle-result.js +102 -0
  121. package/dist/src/commands/public-lifecycle-result.js.map +1 -0
  122. package/dist/src/commands/public-lifecycle.d.ts +26 -0
  123. package/dist/src/commands/public-lifecycle.js +469 -0
  124. package/dist/src/commands/public-lifecycle.js.map +1 -0
  125. package/dist/src/commands/public-plugin-query.d.ts +15 -0
  126. package/dist/src/commands/public-plugin-query.js +154 -0
  127. package/dist/src/commands/public-plugin-query.js.map +1 -0
  128. package/dist/src/commands/rebuild-command.d.ts +177 -29
  129. package/dist/src/commands/rebuild-command.js +4113 -745
  130. package/dist/src/commands/rebuild-command.js.map +1 -1
  131. package/dist/src/commands/rebuild-integration.d.ts +163 -22
  132. package/dist/src/commands/rebuild-integration.js +3553 -1456
  133. package/dist/src/commands/rebuild-integration.js.map +1 -1
  134. package/dist/src/commands/rebuild-operations.d.ts +60 -30
  135. package/dist/src/commands/rebuild-operations.js +266 -320
  136. package/dist/src/commands/rebuild-operations.js.map +1 -1
  137. package/dist/src/commands/reconcile-operation-plan.d.ts +28 -0
  138. package/dist/src/commands/reconcile-operation-plan.js +47 -0
  139. package/dist/src/commands/reconcile-operation-plan.js.map +1 -0
  140. package/dist/src/commands/review-inspection.d.ts +60 -0
  141. package/dist/src/commands/review-inspection.js +399 -0
  142. package/dist/src/commands/review-inspection.js.map +1 -0
  143. package/dist/src/commands/review-preparation.d.ts +49 -0
  144. package/dist/src/commands/review-preparation.js +437 -0
  145. package/dist/src/commands/review-preparation.js.map +1 -0
  146. package/dist/src/commands/runtime.d.ts +5 -5
  147. package/dist/src/commands/runtime.js +42 -54
  148. package/dist/src/commands/runtime.js.map +1 -1
  149. package/dist/src/commands/skill-eval.d.ts +41 -0
  150. package/dist/src/commands/skill-eval.js +406 -0
  151. package/dist/src/commands/skill-eval.js.map +1 -0
  152. package/dist/src/commands/status-v6.d.ts +317 -0
  153. package/dist/src/commands/status-v6.js +2970 -0
  154. package/dist/src/commands/status-v6.js.map +1 -0
  155. package/dist/src/commands/targets-command.d.ts +29 -0
  156. package/dist/src/commands/targets-command.js +131 -0
  157. package/dist/src/commands/targets-command.js.map +1 -0
  158. package/dist/src/commands/wizard.d.ts +8 -5
  159. package/dist/src/commands/wizard.js +6 -4
  160. package/dist/src/commands/wizard.js.map +1 -1
  161. package/dist/src/commands/write-commands.d.ts +9 -3
  162. package/dist/src/commands/write-commands.js +129 -30
  163. package/dist/src/commands/write-commands.js.map +1 -1
  164. package/dist/src/constants.d.ts +7 -2
  165. package/dist/src/constants.js +7 -2
  166. package/dist/src/constants.js.map +1 -1
  167. package/dist/src/eval/manifest-v1.d.ts +70 -0
  168. package/dist/src/eval/manifest-v1.js +358 -0
  169. package/dist/src/eval/manifest-v1.js.map +1 -0
  170. package/dist/src/generators/local-plugin.d.ts +7 -2
  171. package/dist/src/generators/local-plugin.js +377 -210
  172. package/dist/src/generators/local-plugin.js.map +1 -1
  173. package/dist/src/generators/permissions.d.ts +5 -2
  174. package/dist/src/generators/permissions.js +28 -15
  175. package/dist/src/generators/permissions.js.map +1 -1
  176. package/dist/src/index.d.ts +1 -27
  177. package/dist/src/index.js +1877 -1592
  178. package/dist/src/index.js.map +1 -1
  179. package/dist/src/intent/deployment-preferences.d.ts +63 -0
  180. package/dist/src/intent/deployment-preferences.js +170 -0
  181. package/dist/src/intent/deployment-preferences.js.map +1 -0
  182. package/dist/src/intent/diagnostics.d.ts +11 -0
  183. package/dist/src/intent/diagnostics.js +14 -0
  184. package/dist/src/intent/diagnostics.js.map +1 -0
  185. package/dist/src/intent/intent-codec.d.ts +19 -0
  186. package/dist/src/intent/intent-codec.js +117 -0
  187. package/dist/src/intent/intent-codec.js.map +1 -0
  188. package/dist/src/intent/intent-store.d.ts +43 -0
  189. package/dist/src/intent/intent-store.js +118 -0
  190. package/dist/src/intent/intent-store.js.map +1 -0
  191. package/dist/src/intent/scope-context.d.ts +33 -0
  192. package/dist/src/intent/scope-context.js +145 -0
  193. package/dist/src/intent/scope-context.js.map +1 -0
  194. package/dist/src/intent/work-context.d.ts +13 -0
  195. package/dist/src/intent/work-context.js +22 -0
  196. package/dist/src/intent/work-context.js.map +1 -0
  197. package/dist/src/output/command-receipt.d.ts +47 -46
  198. package/dist/src/output/command-receipt.js +284 -79
  199. package/dist/src/output/command-receipt.js.map +1 -1
  200. package/dist/src/output/model.d.ts +3 -44
  201. package/dist/src/output/model.js +1 -144
  202. package/dist/src/output/model.js.map +1 -1
  203. package/dist/src/output/public-result.d.ts +43 -0
  204. package/dist/src/output/public-result.js +139 -0
  205. package/dist/src/output/public-result.js.map +1 -0
  206. package/dist/src/output/rebuild-progress.js +15 -13
  207. package/dist/src/output/rebuild-progress.js.map +1 -1
  208. package/dist/src/output/receipt-projection.d.ts +7 -0
  209. package/dist/src/output/receipt-projection.js +575 -0
  210. package/dist/src/output/receipt-projection.js.map +1 -0
  211. package/dist/src/portable/commands.d.ts +59 -10
  212. package/dist/src/portable/commands.js +98 -302
  213. package/dist/src/portable/commands.js.map +1 -1
  214. package/dist/src/portable/historical-materialization.d.ts +22 -0
  215. package/dist/src/portable/historical-materialization.js +124 -0
  216. package/dist/src/portable/historical-materialization.js.map +1 -0
  217. package/dist/src/portable/materializer.d.ts +25 -4
  218. package/dist/src/portable/materializer.js +247 -68
  219. package/dist/src/portable/materializer.js.map +1 -1
  220. package/dist/src/portable/recovery-layout.d.ts +17 -0
  221. package/dist/src/portable/recovery-layout.js +55 -0
  222. package/dist/src/portable/recovery-layout.js.map +1 -0
  223. package/dist/src/portable/recovery.d.ts +143 -0
  224. package/dist/src/portable/recovery.js +339 -0
  225. package/dist/src/portable/recovery.js.map +1 -0
  226. package/dist/src/portable/writer.d.ts +64 -0
  227. package/dist/src/portable/writer.js +316 -0
  228. package/dist/src/portable/writer.js.map +1 -0
  229. package/dist/src/recovery/coordinator.d.ts +140 -0
  230. package/dist/src/recovery/coordinator.js +1200 -0
  231. package/dist/src/recovery/coordinator.js.map +1 -0
  232. package/dist/src/recovery/demand.d.ts +44 -0
  233. package/dist/src/recovery/demand.js +178 -0
  234. package/dist/src/recovery/demand.js.map +1 -0
  235. package/dist/src/recovery/joint-coordinator.d.ts +24 -0
  236. package/dist/src/recovery/joint-coordinator.js +797 -0
  237. package/dist/src/recovery/joint-coordinator.js.map +1 -0
  238. package/dist/src/recovery/joint-demand.d.ts +68 -0
  239. package/dist/src/recovery/joint-demand.js +166 -0
  240. package/dist/src/recovery/joint-demand.js.map +1 -0
  241. package/dist/src/recovery/performance.d.ts +4 -0
  242. package/dist/src/recovery/performance.js +26 -0
  243. package/dist/src/recovery/performance.js.map +1 -0
  244. package/dist/src/recovery/receipt.d.ts +81 -0
  245. package/dist/src/recovery/receipt.js +2 -0
  246. package/dist/src/recovery/receipt.js.map +1 -0
  247. package/dist/src/recovery/retirement.d.ts +47 -0
  248. package/dist/src/recovery/retirement.js +367 -0
  249. package/dist/src/recovery/retirement.js.map +1 -0
  250. package/dist/src/recovery/status.d.ts +108 -0
  251. package/dist/src/recovery/status.js +418 -0
  252. package/dist/src/recovery/status.js.map +1 -0
  253. package/dist/src/recovery/types.d.ts +86 -0
  254. package/dist/src/recovery/types.js +2 -0
  255. package/dist/src/recovery/types.js.map +1 -0
  256. package/dist/src/review/eval-source-input.d.ts +43 -0
  257. package/dist/src/review/eval-source-input.js +207 -0
  258. package/dist/src/review/eval-source-input.js.map +1 -0
  259. package/dist/src/review/review-profile.d.ts +19 -0
  260. package/dist/src/review/review-profile.js +270 -0
  261. package/dist/src/review/review-profile.js.map +1 -0
  262. package/dist/src/review/review-selection.d.ts +29 -0
  263. package/dist/src/review/review-selection.js +469 -0
  264. package/dist/src/review/review-selection.js.map +1 -0
  265. package/dist/src/review/review-types.d.ts +68 -0
  266. package/dist/src/review/review-types.js +16 -0
  267. package/dist/src/review/review-types.js.map +1 -0
  268. package/dist/src/review/skill-materialization.d.ts +27 -0
  269. package/dist/src/review/skill-materialization.js +228 -0
  270. package/dist/src/review/skill-materialization.js.map +1 -0
  271. package/dist/src/review/source-binding.d.ts +198 -0
  272. package/dist/src/review/source-binding.js +714 -0
  273. package/dist/src/review/source-binding.js.map +1 -0
  274. package/dist/src/tui/agent-management.d.ts +23 -0
  275. package/dist/src/tui/agent-management.js +217 -0
  276. package/dist/src/tui/agent-management.js.map +1 -0
  277. package/dist/src/tui/agent-settings.d.ts +44 -0
  278. package/dist/src/tui/agent-settings.js +98 -0
  279. package/dist/src/tui/agent-settings.js.map +1 -0
  280. package/dist/src/tui/catalog-freshness.d.ts +1 -0
  281. package/dist/src/tui/catalog-freshness.js +2 -0
  282. package/dist/src/tui/catalog-freshness.js.map +1 -0
  283. package/dist/src/tui/catalog-generation.d.ts +21 -0
  284. package/dist/src/tui/catalog-generation.js +156 -0
  285. package/dist/src/tui/catalog-generation.js.map +1 -0
  286. package/dist/src/tui/catalog-sources/projection.d.ts +4 -0
  287. package/dist/src/tui/catalog-sources/projection.js +17 -0
  288. package/dist/src/tui/catalog-sources/projection.js.map +1 -0
  289. package/dist/src/tui/catalog-sources/review.d.ts +3 -0
  290. package/dist/src/tui/catalog-sources/review.js +13 -0
  291. package/dist/src/tui/catalog-sources/review.js.map +1 -0
  292. package/dist/src/tui/catalog-sources/screens.d.ts +12 -0
  293. package/dist/src/tui/catalog-sources/screens.js +40 -0
  294. package/dist/src/tui/catalog-sources/screens.js.map +1 -0
  295. package/dist/src/tui/catalog-sources/session.d.ts +32 -0
  296. package/dist/src/tui/catalog-sources/session.js +300 -0
  297. package/dist/src/tui/catalog-sources/session.js.map +1 -0
  298. package/dist/src/tui/catalog-sources/types.d.ts +54 -0
  299. package/dist/src/tui/catalog-sources/types.js +2 -0
  300. package/dist/src/tui/catalog-sources/types.js.map +1 -0
  301. package/dist/src/tui/catalog-store-task.d.ts +16 -0
  302. package/dist/src/tui/catalog-store-task.js +19 -0
  303. package/dist/src/tui/catalog-store-task.js.map +1 -0
  304. package/dist/src/tui/clipboard.d.ts +13 -0
  305. package/dist/src/tui/clipboard.js +95 -0
  306. package/dist/src/tui/clipboard.js.map +1 -0
  307. package/dist/src/tui/components.d.ts +113 -3
  308. package/dist/src/tui/components.js +192 -36
  309. package/dist/src/tui/components.js.map +1 -1
  310. package/dist/src/tui/config-array-draft.d.ts +29 -0
  311. package/dist/src/tui/config-array-draft.js +48 -0
  312. package/dist/src/tui/config-array-draft.js.map +1 -0
  313. package/dist/src/tui/config-leaf-editor.d.ts +43 -0
  314. package/dist/src/tui/config-leaf-editor.js +224 -0
  315. package/dist/src/tui/config-leaf-editor.js.map +1 -0
  316. package/dist/src/tui/config-references.d.ts +38 -0
  317. package/dist/src/tui/config-references.js +82 -0
  318. package/dist/src/tui/config-references.js.map +1 -0
  319. package/dist/src/tui/config-value-presentation.d.ts +20 -0
  320. package/dist/src/tui/config-value-presentation.js +104 -0
  321. package/dist/src/tui/config-value-presentation.js.map +1 -0
  322. package/dist/src/tui/console-app-v4.d.ts +13 -4
  323. package/dist/src/tui/console-app-v4.js +9764 -1955
  324. package/dist/src/tui/console-app-v4.js.map +1 -1
  325. package/dist/src/tui/content-item-card.d.ts +13 -0
  326. package/dist/src/tui/content-item-card.js +51 -0
  327. package/dist/src/tui/content-item-card.js.map +1 -0
  328. package/dist/src/tui/controller-runtime.d.ts +11 -2
  329. package/dist/src/tui/controller-runtime.js +2223 -471
  330. package/dist/src/tui/controller-runtime.js.map +1 -1
  331. package/dist/src/tui/controller.d.ts +697 -66
  332. package/dist/src/tui/controller.js +3695 -778
  333. package/dist/src/tui/controller.js.map +1 -1
  334. package/dist/src/tui/dependency-graph-view.d.ts +39 -0
  335. package/dist/src/tui/dependency-graph-view.js +121 -0
  336. package/dist/src/tui/dependency-graph-view.js.map +1 -0
  337. package/dist/src/tui/dependency-graph.d.ts +81 -0
  338. package/dist/src/tui/dependency-graph.js +452 -0
  339. package/dist/src/tui/dependency-graph.js.map +1 -0
  340. package/dist/src/tui/diagnostic-projection.d.ts +23 -0
  341. package/dist/src/tui/diagnostic-projection.js +595 -0
  342. package/dist/src/tui/diagnostic-projection.js.map +1 -0
  343. package/dist/src/tui/diagnostics.d.ts +3 -3
  344. package/dist/src/tui/diagnostics.js +14 -2
  345. package/dist/src/tui/diagnostics.js.map +1 -1
  346. package/dist/src/tui/entity-cards.d.ts +55 -0
  347. package/dist/src/tui/entity-cards.js +298 -0
  348. package/dist/src/tui/entity-cards.js.map +1 -0
  349. package/dist/src/tui/glossary.d.ts +25 -0
  350. package/dist/src/tui/glossary.js +62 -0
  351. package/dist/src/tui/glossary.js.map +1 -0
  352. package/dist/src/tui/index.d.ts +6 -1
  353. package/dist/src/tui/index.js +5 -1
  354. package/dist/src/tui/index.js.map +1 -1
  355. package/dist/src/tui/input-display.d.ts +9 -0
  356. package/dist/src/tui/input-display.js +58 -0
  357. package/dist/src/tui/input-display.js.map +1 -0
  358. package/dist/src/tui/keys.d.ts +44 -0
  359. package/dist/src/tui/keys.js +43 -15
  360. package/dist/src/tui/keys.js.map +1 -1
  361. package/dist/src/tui/lifecycle-action-view.d.ts +6 -0
  362. package/dist/src/tui/lifecycle-action-view.js +36 -0
  363. package/dist/src/tui/lifecycle-action-view.js.map +1 -0
  364. package/dist/src/tui/model.d.ts +246 -35
  365. package/dist/src/tui/model.js +1514 -401
  366. package/dist/src/tui/model.js.map +1 -1
  367. package/dist/src/tui/operation-diagnostic-screens.d.ts +8 -0
  368. package/dist/src/tui/operation-diagnostic-screens.js +71 -0
  369. package/dist/src/tui/operation-diagnostic-screens.js.map +1 -0
  370. package/dist/src/tui/operation-history.d.ts +81 -0
  371. package/dist/src/tui/operation-history.js +136 -0
  372. package/dist/src/tui/operation-history.js.map +1 -0
  373. package/dist/src/tui/operation-review-planner.d.ts +23 -0
  374. package/dist/src/tui/operation-review-planner.js +1341 -0
  375. package/dist/src/tui/operation-review-planner.js.map +1 -0
  376. package/dist/src/tui/plugin-content.d.ts +31 -0
  377. package/dist/src/tui/plugin-content.js +683 -0
  378. package/dist/src/tui/plugin-content.js.map +1 -0
  379. package/dist/src/tui/plugin-detail.d.ts +71 -0
  380. package/dist/src/tui/plugin-detail.js +252 -0
  381. package/dist/src/tui/plugin-detail.js.map +1 -0
  382. package/dist/src/tui/plugin-write-task.d.ts +69 -0
  383. package/dist/src/tui/plugin-write-task.js +286 -0
  384. package/dist/src/tui/plugin-write-task.js.map +1 -0
  385. package/dist/src/tui/prompt.js +4 -15
  386. package/dist/src/tui/prompt.js.map +1 -1
  387. package/dist/src/tui/query-header.d.ts +30 -0
  388. package/dist/src/tui/query-header.js +40 -0
  389. package/dist/src/tui/query-header.js.map +1 -0
  390. package/dist/src/tui/reader.d.ts +38 -0
  391. package/dist/src/tui/reader.js +49 -0
  392. package/dist/src/tui/reader.js.map +1 -0
  393. package/dist/src/tui/router.d.ts +194 -17
  394. package/dist/src/tui/router.js +338 -50
  395. package/dist/src/tui/router.js.map +1 -1
  396. package/dist/src/tui/scoped-flow.d.ts +45 -0
  397. package/dist/src/tui/scoped-flow.js +96 -0
  398. package/dist/src/tui/scoped-flow.js.map +1 -0
  399. package/dist/src/tui/scoped-inventory.d.ts +122 -0
  400. package/dist/src/tui/scoped-inventory.js +225 -0
  401. package/dist/src/tui/scoped-inventory.js.map +1 -0
  402. package/dist/src/tui/screen-registry.d.ts +701 -0
  403. package/dist/src/tui/screen-registry.js +226 -0
  404. package/dist/src/tui/screen-registry.js.map +1 -0
  405. package/dist/src/tui/session-console-app.d.ts +6 -0
  406. package/dist/src/tui/session-console-app.js +13 -0
  407. package/dist/src/tui/session-console-app.js.map +1 -0
  408. package/dist/src/tui/session-host.d.ts +45 -0
  409. package/dist/src/tui/session-host.js +219 -0
  410. package/dist/src/tui/session-host.js.map +1 -0
  411. package/dist/src/tui/source-detail-card.d.ts +29 -0
  412. package/dist/src/tui/source-detail-card.js +45 -0
  413. package/dist/src/tui/source-detail-card.js.map +1 -0
  414. package/dist/src/tui/source-ref-presets.d.ts +3 -0
  415. package/dist/src/tui/source-ref-presets.js +11 -0
  416. package/dist/src/tui/source-ref-presets.js.map +1 -0
  417. package/dist/src/tui/theme.d.ts +12 -0
  418. package/dist/src/tui/theme.js +12 -0
  419. package/dist/src/tui/theme.js.map +1 -1
  420. package/dist/src/tui/viewport.d.ts +1 -0
  421. package/dist/src/tui/viewport.js +23 -0
  422. package/dist/src/tui/viewport.js.map +1 -1
  423. package/dist/src/tui/views.js +31 -3
  424. package/dist/src/tui/views.js.map +1 -1
  425. package/dist/src/tui/wizard.js +37 -13
  426. package/dist/src/tui/wizard.js.map +1 -1
  427. package/dist/src/types.d.ts +268 -23
  428. package/dist/src/types.js +1 -0
  429. package/dist/src/types.js.map +1 -1
  430. package/dist/src/utils/agent-version.d.ts +7 -1
  431. package/dist/src/utils/agent-version.js +38 -7
  432. package/dist/src/utils/agent-version.js.map +1 -1
  433. package/dist/src/utils/artifact-plan.d.ts +8 -6
  434. package/dist/src/utils/artifact-plan.js +80 -19
  435. package/dist/src/utils/artifact-plan.js.map +1 -1
  436. package/dist/src/utils/artifact-renderer.d.ts +35 -11
  437. package/dist/src/utils/artifact-renderer.js +250 -227
  438. package/dist/src/utils/artifact-renderer.js.map +1 -1
  439. package/dist/src/utils/artifact-request.d.ts +33 -0
  440. package/dist/src/utils/artifact-request.js +100 -0
  441. package/dist/src/utils/artifact-request.js.map +1 -0
  442. package/dist/src/utils/artifact-sources.d.ts +6 -2
  443. package/dist/src/utils/artifact-sources.js +17 -0
  444. package/dist/src/utils/artifact-sources.js.map +1 -1
  445. package/dist/src/utils/aw-home-mutation-lock.d.ts +1 -0
  446. package/dist/src/utils/aw-home-mutation-lock.js +32 -4
  447. package/dist/src/utils/aw-home-mutation-lock.js.map +1 -1
  448. package/dist/src/utils/bundle-integrity.d.ts +0 -1
  449. package/dist/src/utils/bundle-integrity.js +0 -25
  450. package/dist/src/utils/bundle-integrity.js.map +1 -1
  451. package/dist/src/utils/bundle-layout.js +47 -45
  452. package/dist/src/utils/bundle-layout.js.map +1 -1
  453. package/dist/src/utils/catalog-capability-projection.d.ts +8 -0
  454. package/dist/src/utils/catalog-capability-projection.js +14 -0
  455. package/dist/src/utils/catalog-capability-projection.js.map +1 -0
  456. package/dist/src/utils/catalog-digests.d.ts +10 -0
  457. package/dist/src/utils/catalog-digests.js +59 -20
  458. package/dist/src/utils/catalog-digests.js.map +1 -1
  459. package/dist/src/utils/catalog-generation-control-snapshot.d.ts +11 -0
  460. package/dist/src/utils/catalog-generation-control-snapshot.js +45 -0
  461. package/dist/src/utils/catalog-generation-control-snapshot.js.map +1 -0
  462. package/dist/src/utils/catalog-generation-error.d.ts +16 -0
  463. package/dist/src/utils/catalog-generation-error.js +30 -0
  464. package/dist/src/utils/catalog-generation-error.js.map +1 -0
  465. package/dist/src/utils/catalog-generation-resolver.d.ts +44 -0
  466. package/dist/src/utils/catalog-generation-resolver.js +273 -0
  467. package/dist/src/utils/catalog-generation-resolver.js.map +1 -0
  468. package/dist/src/utils/catalog-generation-service.d.ts +183 -0
  469. package/dist/src/utils/catalog-generation-service.js +1281 -0
  470. package/dist/src/utils/catalog-generation-service.js.map +1 -0
  471. package/dist/src/utils/catalog-generation-state.d.ts +22 -0
  472. package/dist/src/utils/catalog-generation-state.js +192 -0
  473. package/dist/src/utils/catalog-generation-state.js.map +1 -0
  474. package/dist/src/utils/catalog-generation-store.d.ts +58 -0
  475. package/dist/src/utils/catalog-generation-store.js +452 -0
  476. package/dist/src/utils/catalog-generation-store.js.map +1 -0
  477. package/dist/src/utils/catalog-manifest-v7.d.ts +5 -0
  478. package/dist/src/utils/{catalog-manifest-v4.js → catalog-manifest-v7.js} +35 -43
  479. package/dist/src/utils/catalog-manifest-v7.js.map +1 -0
  480. package/dist/src/utils/catalog-operation-context.d.ts +20 -0
  481. package/dist/src/utils/catalog-operation-context.js +142 -0
  482. package/dist/src/utils/catalog-operation-context.js.map +1 -0
  483. package/dist/src/utils/catalog-public-error.d.ts +7 -3
  484. package/dist/src/utils/catalog-public-error.js +28 -8
  485. package/dist/src/utils/catalog-public-error.js.map +1 -1
  486. package/dist/src/utils/catalog-runtime-projection.d.ts +7 -3
  487. package/dist/src/utils/catalog-runtime-projection.js +5 -40
  488. package/dist/src/utils/catalog-runtime-projection.js.map +1 -1
  489. package/dist/src/utils/catalog-snapshot.d.ts +5 -3
  490. package/dist/src/utils/catalog-snapshot.js +11 -3
  491. package/dist/src/utils/catalog-snapshot.js.map +1 -1
  492. package/dist/src/utils/catalog-source-identity.d.ts +1 -0
  493. package/dist/src/utils/catalog-source-identity.js +21 -2
  494. package/dist/src/utils/catalog-source-identity.js.map +1 -1
  495. package/dist/src/utils/catalog-source-impact.d.ts +21 -0
  496. package/dist/src/utils/catalog-source-impact.js +344 -0
  497. package/dist/src/utils/catalog-source-impact.js.map +1 -0
  498. package/dist/src/utils/catalog-source-references.d.ts +8 -2
  499. package/dist/src/utils/catalog-source-references.js +200 -367
  500. package/dist/src/utils/catalog-source-references.js.map +1 -1
  501. package/dist/src/utils/catalog-sources.d.ts +15 -1
  502. package/dist/src/utils/catalog-sources.js +206 -27
  503. package/dist/src/utils/catalog-sources.js.map +1 -1
  504. package/dist/src/utils/claude-native-render-receipt.d.ts +14 -0
  505. package/dist/src/utils/claude-native-render-receipt.js +26 -0
  506. package/dist/src/utils/claude-native-render-receipt.js.map +1 -0
  507. package/dist/src/utils/claude-skills-root.d.ts +8 -0
  508. package/dist/src/utils/claude-skills-root.js +87 -0
  509. package/dist/src/utils/claude-skills-root.js.map +1 -0
  510. package/dist/src/utils/codex-config.d.ts +2 -0
  511. package/dist/src/utils/codex-config.js +26 -5
  512. package/dist/src/utils/codex-config.js.map +1 -1
  513. package/dist/src/utils/codex-executable-discovery.d.ts +26 -0
  514. package/dist/src/utils/codex-executable-discovery.js +397 -0
  515. package/dist/src/utils/codex-executable-discovery.js.map +1 -0
  516. package/dist/src/utils/codex-manager.d.ts +62 -0
  517. package/dist/src/utils/codex-manager.js +122 -0
  518. package/dist/src/utils/codex-manager.js.map +1 -0
  519. package/dist/src/utils/codex-marketplace-path.d.ts +5 -0
  520. package/dist/src/utils/codex-marketplace-path.js +45 -0
  521. package/dist/src/utils/codex-marketplace-path.js.map +1 -0
  522. package/dist/src/utils/codex-native-observation.d.ts +49 -0
  523. package/dist/src/utils/codex-native-observation.js +169 -0
  524. package/dist/src/utils/codex-native-observation.js.map +1 -0
  525. package/dist/src/utils/codex-native-render-receipt.d.ts +40 -0
  526. package/dist/src/utils/codex-native-render-receipt.js +205 -0
  527. package/dist/src/utils/codex-native-render-receipt.js.map +1 -0
  528. package/dist/src/utils/codex-reconciler.d.ts +123 -0
  529. package/dist/src/utils/codex-reconciler.js +322 -0
  530. package/dist/src/utils/codex-reconciler.js.map +1 -0
  531. package/dist/src/utils/codex-shared-native.d.ts +43 -0
  532. package/dist/src/utils/codex-shared-native.js +81 -0
  533. package/dist/src/utils/codex-shared-native.js.map +1 -0
  534. package/dist/src/utils/codex-skill-staging.d.ts +2 -0
  535. package/dist/src/utils/codex-skill-staging.js.map +1 -1
  536. package/dist/src/utils/codex-skills-root.d.ts +4 -0
  537. package/dist/src/utils/codex-skills-root.js +25 -0
  538. package/dist/src/utils/codex-skills-root.js.map +1 -0
  539. package/dist/src/utils/codex-surface-analysis.d.ts +46 -0
  540. package/dist/src/utils/codex-surface-analysis.js +249 -0
  541. package/dist/src/utils/codex-surface-analysis.js.map +1 -0
  542. package/dist/src/utils/dynamic-skill-tree.d.ts +5 -0
  543. package/dist/src/utils/dynamic-skill-tree.js +56 -7
  544. package/dist/src/utils/dynamic-skill-tree.js.map +1 -1
  545. package/dist/src/utils/git-catalog-provider.d.ts +16 -0
  546. package/dist/src/utils/git-catalog-provider.js +177 -145
  547. package/dist/src/utils/git-catalog-provider.js.map +1 -1
  548. package/dist/src/utils/local-marketplace.d.ts +39 -1
  549. package/dist/src/utils/local-marketplace.js +601 -84
  550. package/dist/src/utils/local-marketplace.js.map +1 -1
  551. package/dist/src/utils/managed-command-closure.d.ts +3 -0
  552. package/dist/src/utils/managed-command-closure.js +35 -0
  553. package/dist/src/utils/managed-command-closure.js.map +1 -0
  554. package/dist/src/utils/managed-command-evidence.d.ts +7 -0
  555. package/dist/src/utils/managed-command-evidence.js +86 -0
  556. package/dist/src/utils/managed-command-evidence.js.map +1 -0
  557. package/dist/src/utils/managed-command-materialization.d.ts +121 -0
  558. package/dist/src/utils/managed-command-materialization.js +369 -0
  559. package/dist/src/utils/managed-command-materialization.js.map +1 -0
  560. package/dist/src/utils/managed-command-runtime.d.ts +33 -0
  561. package/dist/src/utils/managed-command-runtime.js +121 -0
  562. package/dist/src/utils/managed-command-runtime.js.map +1 -0
  563. package/dist/src/utils/managed-command-store.d.ts +143 -0
  564. package/dist/src/utils/managed-command-store.js +654 -0
  565. package/dist/src/utils/managed-command-store.js.map +1 -0
  566. package/dist/src/utils/manifest.d.ts +1 -3
  567. package/dist/src/utils/manifest.js +1 -3
  568. package/dist/src/utils/manifest.js.map +1 -1
  569. package/dist/src/utils/multi-source-catalog.d.ts +3 -9
  570. package/dist/src/utils/multi-source-catalog.js +54 -110
  571. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  572. package/dist/src/utils/native-cli.d.ts +62 -7
  573. package/dist/src/utils/native-cli.js +449 -58
  574. package/dist/src/utils/native-cli.js.map +1 -1
  575. package/dist/src/utils/native-demand.d.ts +10 -0
  576. package/dist/src/utils/native-demand.js +4 -0
  577. package/dist/src/utils/native-demand.js.map +1 -0
  578. package/dist/src/utils/native-tool-context.d.ts +14 -0
  579. package/dist/src/utils/native-tool-context.js +38 -0
  580. package/dist/src/utils/native-tool-context.js.map +1 -0
  581. package/dist/src/utils/native-tool-review.d.ts +21 -0
  582. package/dist/src/utils/native-tool-review.js +102 -0
  583. package/dist/src/utils/native-tool-review.js.map +1 -0
  584. package/dist/src/utils/orphan-marketplace-cleanup.js +0 -4
  585. package/dist/src/utils/orphan-marketplace-cleanup.js.map +1 -1
  586. package/dist/src/utils/ownership.d.ts +88 -20
  587. package/dist/src/utils/ownership.js +187 -223
  588. package/dist/src/utils/ownership.js.map +1 -1
  589. package/dist/src/utils/path-catalog-provider.d.ts +1 -1
  590. package/dist/src/utils/path-catalog-provider.js +54 -65
  591. package/dist/src/utils/path-catalog-provider.js.map +1 -1
  592. package/dist/src/utils/paths.d.ts +0 -1
  593. package/dist/src/utils/paths.js +1 -2
  594. package/dist/src/utils/paths.js.map +1 -1
  595. package/dist/src/utils/platform-support.d.ts +1 -1
  596. package/dist/src/utils/platform-support.js +1 -1
  597. package/dist/src/utils/platform-support.js.map +1 -1
  598. package/dist/src/utils/plugin-config-impact.d.ts +58 -0
  599. package/dist/src/utils/plugin-config-impact.js +323 -0
  600. package/dist/src/utils/plugin-config-impact.js.map +1 -0
  601. package/dist/src/utils/plugin-config-references.d.ts +89 -0
  602. package/dist/src/utils/plugin-config-references.js +335 -0
  603. package/dist/src/utils/plugin-config-references.js.map +1 -0
  604. package/dist/src/utils/plugin-config-write.d.ts +109 -27
  605. package/dist/src/utils/plugin-config-write.js +1246 -368
  606. package/dist/src/utils/plugin-config-write.js.map +1 -1
  607. package/dist/src/utils/plugin-config.d.ts +189 -120
  608. package/dist/src/utils/plugin-config.js +926 -1270
  609. package/dist/src/utils/plugin-config.js.map +1 -1
  610. package/dist/src/utils/plugin-scripts.d.ts +75 -128
  611. package/dist/src/utils/plugin-scripts.js +556 -525
  612. package/dist/src/utils/plugin-scripts.js.map +1 -1
  613. package/dist/src/utils/process-lock.js +14 -5
  614. package/dist/src/utils/process-lock.js.map +1 -1
  615. package/dist/src/utils/process-tree.d.ts +2 -2
  616. package/dist/src/utils/process-tree.js +1 -1
  617. package/dist/src/utils/process-tree.js.map +1 -1
  618. package/dist/src/utils/project-boundary.d.ts +11 -13
  619. package/dist/src/utils/project-boundary.js +28 -34
  620. package/dist/src/utils/project-boundary.js.map +1 -1
  621. package/dist/src/utils/rendered-contract.js +18 -1
  622. package/dist/src/utils/rendered-contract.js.map +1 -1
  623. package/dist/src/utils/runtime-config.d.ts +20 -0
  624. package/dist/src/utils/runtime-config.js +77 -0
  625. package/dist/src/utils/runtime-config.js.map +1 -0
  626. package/dist/src/utils/runtime-skill-closure.d.ts +2 -2
  627. package/dist/src/utils/runtime-skill-closure.js +47 -6
  628. package/dist/src/utils/runtime-skill-closure.js.map +1 -1
  629. package/dist/src/utils/safe-fs.d.ts +21 -0
  630. package/dist/src/utils/safe-fs.js +111 -0
  631. package/dist/src/utils/safe-fs.js.map +1 -0
  632. package/dist/src/utils/safe-operation-diagnostic.d.ts +15 -0
  633. package/dist/src/utils/safe-operation-diagnostic.js +33 -0
  634. package/dist/src/utils/safe-operation-diagnostic.js.map +1 -0
  635. package/dist/src/utils/sensitive-content.d.ts +4 -0
  636. package/dist/src/utils/sensitive-content.js +36 -0
  637. package/dist/src/utils/sensitive-content.js.map +1 -0
  638. package/dist/src/utils/state-paths.d.ts +8 -3
  639. package/dist/src/utils/state-paths.js +51 -9
  640. package/dist/src/utils/state-paths.js.map +1 -1
  641. package/dist/src/utils/target-eligibility.d.ts +8 -2
  642. package/dist/src/utils/target-eligibility.js +17 -8
  643. package/dist/src/utils/target-eligibility.js.map +1 -1
  644. package/dist/src/utils/windows-claude-shim.d.ts +7 -0
  645. package/dist/src/utils/windows-claude-shim.js +10 -0
  646. package/dist/src/utils/windows-claude-shim.js.map +1 -0
  647. package/dist/src/utils/windows-npm-shim.d.ts +16 -0
  648. package/dist/src/utils/windows-npm-shim.js +138 -0
  649. package/dist/src/utils/windows-npm-shim.js.map +1 -0
  650. package/dist/vitest.config.js +101 -9
  651. package/dist/vitest.config.js.map +1 -1
  652. package/package.json +31 -21
  653. package/dist/authoring/scripts/check-plugin-versions.d.mts +0 -2
  654. package/dist/authoring/scripts/check-plugin-versions.mjs +0 -5
  655. package/dist/authoring/scripts/check-plugin-versions.mjs.map +0 -1
  656. package/dist/scripts/aw-skill-eval-engine.d.ts +0 -13
  657. package/dist/scripts/aw-skill-eval-engine.js +0 -31
  658. package/dist/scripts/aw-skill-eval-engine.js.map +0 -1
  659. package/dist/scripts/codex-eval-app-server.d.ts +0 -89
  660. package/dist/scripts/codex-eval-app-server.js +0 -1228
  661. package/dist/scripts/codex-eval-app-server.js.map +0 -1
  662. package/dist/scripts/codex-eval-isolation.d.ts +0 -61
  663. package/dist/scripts/codex-eval-isolation.js +0 -318
  664. package/dist/scripts/codex-eval-isolation.js.map +0 -1
  665. package/dist/scripts/codex-eval-process-management.d.ts +0 -8
  666. package/dist/scripts/codex-eval-process-management.js +0 -69
  667. package/dist/scripts/codex-eval-process-management.js.map +0 -1
  668. package/dist/scripts/codex-eval-process-tree.d.ts +0 -38
  669. package/dist/scripts/codex-eval-process-tree.js +0 -803
  670. package/dist/scripts/codex-eval-process-tree.js.map +0 -1
  671. package/dist/scripts/codex-eval-runtime-config.d.ts +0 -62
  672. package/dist/scripts/codex-eval-runtime-config.js +0 -843
  673. package/dist/scripts/codex-eval-runtime-config.js.map +0 -1
  674. package/dist/scripts/codex-trigger-eval.d.ts +0 -84
  675. package/dist/scripts/codex-trigger-eval.js +0 -968
  676. package/dist/scripts/codex-trigger-eval.js.map +0 -1
  677. package/dist/scripts/eval-plugin-skills-audited.d.ts +0 -6
  678. package/dist/scripts/eval-plugin-skills-audited.js +0 -261
  679. package/dist/scripts/eval-plugin-skills-audited.js.map +0 -1
  680. package/dist/scripts/eval-plugin-skills.d.ts +0 -45
  681. package/dist/scripts/eval-plugin-skills.js +0 -1586
  682. package/dist/scripts/eval-plugin-skills.js.map +0 -1
  683. package/dist/scripts/eval-run-layout.d.ts +0 -17
  684. package/dist/scripts/eval-run-layout.js +0 -26
  685. package/dist/scripts/eval-run-layout.js.map +0 -1
  686. package/dist/scripts/plugin-eval-contract.d.ts +0 -185
  687. package/dist/scripts/plugin-eval-contract.js +0 -695
  688. package/dist/scripts/plugin-eval-contract.js.map +0 -1
  689. package/dist/scripts/plugin-eval-materializer.d.ts +0 -13
  690. package/dist/scripts/plugin-eval-materializer.js +0 -421
  691. package/dist/scripts/plugin-eval-materializer.js.map +0 -1
  692. package/dist/scripts/skill-reporting.d.ts +0 -212
  693. package/dist/scripts/skill-reporting.js +0 -922
  694. package/dist/scripts/skill-reporting.js.map +0 -1
  695. package/dist/src/commands/review-publication.d.ts +0 -99
  696. package/dist/src/commands/review-publication.js +0 -904
  697. package/dist/src/commands/review-publication.js.map +0 -1
  698. package/dist/src/commands/status-v4.d.ts +0 -123
  699. package/dist/src/commands/status-v4.js +0 -905
  700. package/dist/src/commands/status-v4.js.map +0 -1
  701. package/dist/src/commands/status.d.ts +0 -93
  702. package/dist/src/commands/status.js +0 -442
  703. package/dist/src/commands/status.js.map +0 -1
  704. package/dist/src/portable/skills-cli.d.ts +0 -43
  705. package/dist/src/portable/skills-cli.js +0 -148
  706. package/dist/src/portable/skills-cli.js.map +0 -1
  707. package/dist/src/utils/active-marketplace-runtime-lock.d.ts +0 -12
  708. package/dist/src/utils/active-marketplace-runtime-lock.js +0 -133
  709. package/dist/src/utils/active-marketplace-runtime-lock.js.map +0 -1
  710. package/dist/src/utils/catalog-manifest-v3.d.ts +0 -2
  711. package/dist/src/utils/catalog-manifest-v3.js +0 -3
  712. package/dist/src/utils/catalog-manifest-v3.js.map +0 -1
  713. package/dist/src/utils/catalog-manifest-v4.d.ts +0 -5
  714. package/dist/src/utils/catalog-manifest-v4.js.map +0 -1
  715. package/dist/src/utils/catalog-source-cache.d.ts +0 -62
  716. package/dist/src/utils/catalog-source-cache.js +0 -296
  717. package/dist/src/utils/catalog-source-cache.js.map +0 -1
  718. package/dist/src/utils/codex-project-surface.d.ts +0 -3
  719. package/dist/src/utils/codex-project-surface.js +0 -49
  720. package/dist/src/utils/codex-project-surface.js.map +0 -1
  721. package/dist/src/utils/lifecycle-active-store.d.ts +0 -175
  722. package/dist/src/utils/lifecycle-active-store.js +0 -1276
  723. package/dist/src/utils/lifecycle-active-store.js.map +0 -1
  724. package/dist/src/utils/plugin-release.d.ts +0 -2
  725. package/dist/src/utils/plugin-release.js +0 -2
  726. package/dist/src/utils/plugin-release.js.map +0 -1
package/dist/src/index.js CHANGED
@@ -1,41 +1,54 @@
1
1
  #!/usr/bin/env node
2
+ import { describeNativeToolClosure } from './utils/native-tool-review.js';
3
+ import { preparePublicConfigConfirmation } from './commands/public-config-confirmation.js';
4
+ import { createPublicCommandInterruption } from './commands/public-interruption.js';
5
+ import { commandResult, publicExitCode, renderPublicResult, safePublicMessage } from './output/public-result.js';
6
+ import { projectReceipt } from './output/receipt-projection.js';
7
+ import { runPublicLifecycle } from './commands/public-lifecycle.js';
8
+ import { runPublicPluginList, runPublicPluginShow, runPublicPluginStatus } from './commands/public-plugin-query.js';
2
9
  import fs from 'node:fs';
3
10
  import path from 'node:path';
4
- import { spawn } from 'node:child_process';
11
+ import { defaultPluginProcessRunner } from './utils/plugin-scripts.js';
5
12
  import { fileURLToPath } from 'node:url';
6
- import { Command, CommanderError, Option } from 'commander';
7
- import { initCommand } from './commands/init.js';
8
- import { addCatalogSourceCommand, explicitRefPolicy, listCatalogSources, removeCatalogSourceCommand, setPrimaryCatalogSourceCommand, updateCatalogSourceCommand, } from './commands/catalog-source.js';
9
- import { cleanupWriteCommand as cleanupCommand, installWriteCommand as installCommand, reinstallWriteCommand as reinstallCommand, uninstallWriteCommand as uninstallCommand, upgradeWriteCommand as upgradeCommand, } from './commands/write-commands.js';
10
- import { formatInteractiveConsoleUnavailableMessage, runConsoleController, } from './commands/console.js';
11
- import { runCommandWizard, toWizardCandidates, WizardExecutionError, } from './commands/wizard.js';
13
+ import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
14
+ import { doctorEvalProviders } from '@lesliechan721/agent-skill-eval';
15
+ import { compilePluginConfigDefinition, selectPluginConfigProfile, PLATFORM_TARGETS, PORTABLE_PLATFORM_TARGETS } from '@lesliechan721/aw-plugin-core/manifest';
16
+ import { CatalogWorkspaceMissingError, resolveCatalogWorkspaceRoot } from './commands/catalog-workspace-resolution.js';
17
+ import { addCatalogSourceCommand, preflightCatalogSourceMutation, explicitRefPolicy, listCatalogSources, removeCatalogSourceCommand, updateCatalogSourceCommand, } from './commands/catalog-source.js';
18
+ import { catalogSourceStatusCommand, syncCatalogSourceCommand, } from './commands/catalog-generation.js';
19
+ import { catalogStoreErrorCode, catalogStorePrune, catalogStoreStatus, } from './commands/catalog-store.js';
20
+ import { runConsoleController, } from './commands/console.js';
21
+ import { WizardExecutionError, } from './commands/wizard.js';
12
22
  import { createCliExecutionContext, emitCommandEvent, } from './commands/runtime.js';
13
- import { loadConsoleItemsResult } from './commands/status.js';
14
- import { statusCommandV4 } from './commands/status-v4.js';
15
- import { normalizeUninstallCommandOptions, normalizeCleanupCommandOptions, resolveConfigReadResolution, resolveConfigProjectLayer, resolveConfigWriteScope, normalizeInstallCommandOptions, normalizeReinstallCommandOptions, normalizeUpgradeCommandOptions, } from './commands/options.js';
16
- import { isCommandWarningError, } from './types.js';
17
- import { formatWarnings } from './output/reporter.js';
23
+ import { parseContextValue, parsePlatformTargetValue, parseScopeValue, resolveScriptTimeoutMs, } from './commands/options.js';
24
+ import { createNoopReporter, formatWarnings } from './output/reporter.js';
18
25
  import { redactString, redactValue } from './output/redact.js';
19
- import { renderShellCommand, } from './output/equivalent-command.js';
20
- import { buildRebuildReceiptJson, buildInitReceiptJson, renderRebuildReceipt, renderInitReceipt, } from './output/command-receipt.js';
21
26
  import { resolveCliPackageRoot } from './utils/paths.js';
22
- import { coercePluginConfigUpdates, findConfigFieldEntry, listNamespacedPluginConfigStores, listPluginConfigStorePluginNames, readPluginConfigStore, renderPluginConfigValueForDisplay, resolveConfigRead, } from './utils/plugin-config.js';
23
- import { applyPluginConfigWrite, describeResetAffectedFields, resetPluginConfigWithHelper, } from './utils/plugin-config-write.js';
27
+ import { coercePluginConfigUpdates, assertPluginConfigMutationCandidate, findConfigFieldEntry, formatPluginConfigSetRecoveryCommand, listNamespacedPluginConfigStores, readPluginConfigStore, renderPluginConfigValueForDisplay, resolveConfigRead, } from './utils/plugin-config.js';
28
+ import { applyPluginConfigWrite, applyPluginConfig, buildConfigMutationReceipt, configWriteStateForError, resetPluginConfigWithHelper, } from './utils/plugin-config-write.js';
24
29
  import { assertStrictSemVer } from './utils/manifest.js';
25
- import { writeCandidateEligibility } from './utils/target-eligibility.js';
26
30
  import { assertCatalogSourceReferencesSupported, inventoryLegacyConfigReferences, } from './utils/catalog-source-references.js';
27
31
  import { parsePluginId, withResolvedCatalogPlugin, withResolvedMultiSourceCatalog, } from './utils/multi-source-catalog.js';
28
- import { sanitizeCatalogSourceError } from './utils/catalog-public-error.js';
29
- import { formatConfigCommandValue, parseConfigValue, } from './utils/config-value.js';
32
+ import { sanitizeCatalogSourceError, sanitizeCatalogSourceErrorMessage, } from './utils/catalog-public-error.js';
33
+ import { catalogGenerationErrorCode } from './utils/catalog-generation-error.js';
34
+ import { resolveCatalogOperationContext, } from './utils/catalog-operation-context.js';
30
35
  import { withAwHomeMutationLock, } from './utils/aw-home-mutation-lock.js';
31
- import { installPortableSkills, materializePortableSkillsToDirectory, PortableCommandError, renderPortableReview, } from './portable/commands.js';
32
- import { SkillsCliError } from './portable/skills-cli.js';
33
- import { computeReviewComponentDigest, listReviewRecords, parseReviewAttachment, publishReviewRecord, showReviewRecord, verifyReviewRecord, } from './commands/review-publication.js';
34
- import { resolveRepoRoot } from './utils/state-paths.js';
36
+ import { materializePortableSkillsToDirectory, PortableCommandError } from './portable/commands.js';
37
+ import { createReviewInspectionFailure, getReviewInspectionExitCode, inspectReviewTarget, } from './commands/review-inspection.js';
38
+ import { prepareReviewTarget, } from './commands/review-preparation.js';
35
39
  import { runCatalogBuildCommand, runCatalogInitCommand, runCatalogValidateCommand, runCatalogVersionCommand, runPluginBuildCommand, runPluginTestCommand, } from './authoring/workspace-commands.js';
36
- import { runCatalogPublishCommand } from './commands/catalog-publish.js';
40
+ import { CatalogPublicationApplyFailure, runCatalogPublishApplyCommand, runCatalogPublishPlanCommand, } from './commands/catalog-publish.js';
41
+ import { catalogPublicationFailure, } from './commands/catalog-publication-inspection.js';
37
42
  import { getCatalogStatus, renderCatalogStatus } from './commands/catalog-status.js';
43
+ import { activateCatalogDevSource, catalogDevSourceError, createCatalogDevFailureReceipt, deactivateCatalogDevSource, getCatalogDevSourceStatus, } from './commands/catalog-dev-source.js';
38
44
  import { getPluginCapabilitiesResult, parsePluginCapabilitySurface, renderPluginCapabilities, } from './commands/plugin-capabilities.js';
45
+ import { AwCapabilityUnsupportedError, checkCurrentAw, describeCurrentAw, inspectPluginRequirements, } from './commands/aw-capabilities.js';
46
+ import { prepareSkillEval } from './commands/skill-eval.js';
47
+ import { targetsSet, targetsList, targetsChangeExclusion } from './commands/targets-command.js';
48
+ import { normalizeAgents } from './intent/deployment-preferences.js';
49
+ import { resolveWorkContext } from './intent/work-context.js';
50
+ import { registerManagedCommandCli, runManagedCommandCli } from './commands/managed-commands.js';
51
+ const receiptSinks = new WeakMap();
39
52
  function createDefaultIo() {
40
53
  return {
41
54
  stdout: (text) => process.stdout.write(text),
@@ -45,6 +58,41 @@ function createDefaultIo() {
45
58
  function writeLine(write, line) {
46
59
  write(`${line}\n`);
47
60
  }
61
+ function strictValueOption(flags, description, choices) {
62
+ let seen = false;
63
+ const option = new Option(flags, description);
64
+ if (choices)
65
+ option.choices([...choices]);
66
+ return option.argParser((value) => {
67
+ if (seen)
68
+ throw new InvalidArgumentError(`${option.long} can be specified only once.`);
69
+ if (choices && !choices.includes(value)) {
70
+ throw new InvalidArgumentError(`${option.long} must be one of: ${choices.join(', ')}.`);
71
+ }
72
+ seen = true;
73
+ return value;
74
+ });
75
+ }
76
+ function collectUniqueOption(value, previous = []) {
77
+ return previous.includes(value) ? previous : [...previous, value];
78
+ }
79
+ function renderReviewSkills(write, skills, issues) {
80
+ for (const skill of skills) {
81
+ writeLine(write, `${skill.skill}\t${skill.profile.platform}/${skill.profile.scope}\t${skill.state}\t${skill.finalPath ?? '-'}`);
82
+ }
83
+ for (const issue of issues)
84
+ writeLine(write, `${issue.code}: ${issue.message}`);
85
+ }
86
+ function renderReviewInspection(write, receipt) {
87
+ writeLine(write, `Review inspection (${receipt.view}): ${receipt.ok ? 'ok' : 'failed'}`);
88
+ renderReviewSkills(write, receipt.skills, receipt.issues);
89
+ }
90
+ function renderReviewPreparation(write, receipt) {
91
+ writeLine(write, `Review preparation: ${receipt.ok ? 'complete' : 'failed'}`);
92
+ if (receipt.sourceBindingPath)
93
+ writeLine(write, `Source binding: ${receipt.sourceBindingPath}`);
94
+ renderReviewSkills(write, receipt.skills, receipt.issues);
95
+ }
48
96
  function writeWarnings(write, warnings, options = {}) {
49
97
  for (const warning of formatWarnings(warnings, options)) {
50
98
  writeLine(write, warning);
@@ -55,31 +103,95 @@ function resolveCliVersion() {
55
103
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
56
104
  return assertStrictSemVer(packageJson.version, 'packages/cli/package.json version');
57
105
  }
58
- function resolveCommandReceiptExitCode(result) {
59
- if (result.overallState === 'failed') {
60
- return 1;
106
+ class WriteCommandRequestError extends Error {
107
+ code = 'invalidArguments';
108
+ }
109
+ function normalizeWriteRequest(normalize) {
110
+ try {
111
+ return normalize();
112
+ }
113
+ catch (error) {
114
+ throw new WriteCommandRequestError(error instanceof Error ? error.message : String(error));
115
+ }
116
+ }
117
+ function configMutationFailure(error, env, cwd) {
118
+ const configWrite = error?.configWrite === 'succeeded' ? 'succeeded' : configWriteStateForError(error);
119
+ if (error instanceof CommanderError) {
120
+ return {
121
+ code: 'invalidArguments',
122
+ message: 'error: invalid config mutation arguments',
123
+ configWrite,
124
+ };
125
+ }
126
+ const message = catalogPublicationFailure({
127
+ error,
128
+ env,
129
+ sensitiveRoots: [cwd],
130
+ }).message;
131
+ if (message.includes('Usage:'))
132
+ return { code: 'invalidArguments', message, configWrite };
133
+ const generationCode = catalogGenerationErrorCode(error);
134
+ if (generationCode === 'catalogGenerationUnavailable'
135
+ || generationCode === 'catalogGenerationSourceMissing') {
136
+ return { code: 'catalogSourceUnavailable', message, configWrite };
137
+ }
138
+ if (generationCode !== 'catalogGenerationFailed')
139
+ return { code: generationCode, message, configWrite };
140
+ const explicitCode = error?.code;
141
+ if (typeof explicitCode === 'string' && /^[A-Za-z][A-Za-z0-9]*$/u.test(explicitCode)) {
142
+ return { code: explicitCode, message, configWrite };
143
+ }
144
+ if (message.includes('legacyStateUnsupported'))
145
+ return { code: 'legacyStateUnsupported', message, configWrite };
146
+ if (message.includes('sourceChanged'))
147
+ return { code: 'sourceChanged', message, configWrite };
148
+ if (message.includes('sourceMissing'))
149
+ return { code: 'sourceMissing', message, configWrite };
150
+ if (message.startsWith('Cannot resolve required catalog sources:')) {
151
+ return { code: 'catalogSourceUnavailable', message, configWrite };
152
+ }
153
+ const prefix = message.match(/^([A-Za-z][A-Za-z0-9]*):/u)?.[1];
154
+ return { code: prefix ?? 'configMutationFailed', message, configWrite };
155
+ }
156
+ function writeConfigMutationFailureReceipt(write, request, failure) {
157
+ let plugin;
158
+ try {
159
+ if (request.plugin) {
160
+ parsePluginId(request.plugin);
161
+ plugin = request.plugin;
162
+ }
61
163
  }
62
- return 0;
164
+ catch {
165
+ // Do not echo an invalid selector from raw argv in an early failure receipt.
166
+ }
167
+ writeJsonReceipt(write, buildConfigMutationReceipt(request.command, {
168
+ ok: false,
169
+ overallState: 'failed',
170
+ configWrite: failure.configWrite,
171
+ ...(plugin ? { plugin } : {}),
172
+ errors: [failure],
173
+ }));
63
174
  }
64
175
  async function runAuthoringScript(options) {
65
176
  const scriptPath = path.join(resolveCliPackageRoot(), 'dist', 'authoring', 'scripts', options.scriptName);
66
- return new Promise((resolve, reject) => {
67
- const child = spawn(process.execPath, [scriptPath, ...options.args], {
68
- cwd: options.cwd,
69
- env: options.env,
70
- stdio: ['ignore', 'pipe', 'pipe'],
71
- });
72
- child.stdout.on('data', (chunk) => options.io.stdout(String(chunk)));
73
- child.stderr.on('data', (chunk) => options.io.stderr(String(chunk)));
74
- child.once('error', reject);
75
- child.once('close', (code, signal) => {
76
- if (signal) {
77
- reject(new Error(`Plugin authoring command terminated by signal ${signal}.`));
78
- return;
79
- }
80
- resolve(code ?? 1);
177
+ try {
178
+ const result = await defaultPluginProcessRunner.run({ command: process.execPath, args: [scriptPath, ...options.args], cwd: options.cwd, env: options.env }, {
179
+ // Authoring has no CLI timeout option. Keep the largest Node timer while
180
+ // using the existing process-tree cleanup contract for interruption.
181
+ timeoutMs: 2_147_483_647, signal: options.interruption?.signal, maxStdoutBytes: 32 * 1024 * 1024,
81
182
  });
82
- });
183
+ options.io.stdout(result.stdout);
184
+ options.io.stderr(result.stderr);
185
+ return result.exitCode ?? 1;
186
+ }
187
+ catch (error) {
188
+ if (options.interruption?.signal.aborted && error !== options.interruption.signal.reason)
189
+ options.interruption.cleanupFailed = true;
190
+ if (options.interruption?.signal.aborted && ['init-plugin.mjs', 'add-skill.mjs', 'remove-plugin.mjs'].includes(options.scriptName)) {
191
+ throw Object.assign(new Error('The authoring command was interrupted after execution started.'), { code: 'operationInterrupted', authoringChanges: 'unknown' });
192
+ }
193
+ throw error;
194
+ }
83
195
  }
84
196
  function toCliDiagnosticsOptions(commandName, rawOptions, runtimeDiagnostics) {
85
197
  return {
@@ -93,259 +205,104 @@ function toCliDiagnosticsOptions(commandName, rawOptions, runtimeDiagnostics) {
93
205
  function isWizardAvailable(context, rawOptions) {
94
206
  return context.interactive && context.isTty && !context.isCi && rawOptions.json !== true;
95
207
  }
96
- function shellCommand(tokens) {
97
- return renderShellCommand(tokens, 'posix');
98
- }
99
- function optionTokens(flag, value) {
100
- return value === undefined ? [] : [flag, value];
101
- }
102
- function writeCommandUsage(command) {
103
- const cardinality = command === 'reinstall' || command === 'cleanup' ? '<plugin>' : '<plugin...>';
104
- const scope = command === 'cleanup' ? ' --scope <project|user>' : ' [--scope <project|user>]';
105
- const all = command === 'upgrade' ? ' 或 aw upgrade --all --platform both --scope user' : '';
106
- return [
107
- `${command} 命令缺少必要参数。`,
108
- `Usage: aw ${command} ${cardinality} --platform <codex|claude|both>${scope}`,
109
- `Example: aw ${command} example-plugin --platform codex --scope user${all}`,
110
- ].join('\n');
111
- }
112
- function configCommandUsage(command) {
113
- const argumentsByCommand = {
114
- list: '<plugin>',
115
- get: '<plugin> [key]',
116
- set: '<plugin> <key> <value>',
117
- unset: '<plugin> <key>',
118
- reset: '<plugin> --scope <project|user> --yes',
119
- };
120
- return [
121
- `config ${command} 命令缺少必要参数。`,
122
- `Usage: aw config ${command} ${argumentsByCommand[command]}`,
123
- `Example: aw config ${command} example-plugin${command === 'set' ? ' key value' : command === 'unset' ? ' key' : command === 'reset' ? ' --scope user --yes' : ''}`,
124
- ].join('\n');
125
- }
126
- function assertUpgradeAllConflict(pluginNames, all) {
127
- if (all && pluginNames.length > 0) {
128
- throw new Error('upgrade 命令不能同时使用插件名和 `--all`。');
208
+ async function readUtf8Stdin(stdin) {
209
+ const chunks = [];
210
+ for await (const chunk of stdin) {
211
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk));
129
212
  }
213
+ return Buffer.concat(chunks).toString('utf8');
130
214
  }
131
- function equivalentWriteCommand(command, selection, rawOptions) {
132
- return shellCommand(buildEquivalentWriteCommandTokens(command, selection, rawOptions));
133
- }
134
- export function buildEquivalentWriteCommandTokens(command, selection, rawOptions) {
135
- const all = command === 'upgrade' && rawOptions.all === true;
136
- return [
137
- 'aw',
138
- command,
139
- ...(all ? ['--all'] : []),
140
- '--platform',
141
- selection.platform ?? 'both',
142
- '--scope',
143
- selection.scope ?? 'user',
144
- ...(command === 'cleanup' ? [] : optionTokens('--script-timeout', rawOptions.scriptTimeout)),
145
- ...(!all && selection.plugins.length > 0 ? ['--', ...selection.plugins] : []),
146
- ];
147
- }
148
- function equivalentConfigCommand(options) {
149
- return shellCommand(buildEquivalentConfigCommandTokens(options));
150
- }
151
- function equivalentConfigCommandProjection(resolve) {
152
- return {
153
- equivalentCommand: (selection) => equivalentConfigCommand(resolve(selection)),
154
- equivalentCommandTokens: (selection) => buildEquivalentConfigCommandTokens(resolve(selection)),
155
- };
156
- }
157
- function configSetEquivalentOptions(selection, candidates, rawOptions) {
158
- const field = candidates.find((entry) => entry.pluginName === selection.plugins[0])
159
- ?.configSchema?.[selection.key ?? ''];
160
- const placeholder = configFieldPlaceholder(field);
161
- return {
162
- command: 'set',
163
- plugin: selection.plugins[0],
164
- key: selection.key,
165
- value: placeholder
166
- ? rawOptions.valueJson ? JSON.stringify(placeholder) : placeholder
167
- : formatConfigCommandValue(selection.value, rawOptions.valueJson === true),
168
- scope: selection.scope ?? 'user',
169
- projectLayer: selection.projectLayer,
170
- valueJson: rawOptions.valueJson,
171
- };
172
- }
173
- function configFieldPlaceholder(field) {
174
- if (field?.sensitive)
175
- return '<sensitive-value>';
176
- if (field?.type === 'file')
177
- return '<file-path>';
178
- if (field?.type === 'directory')
179
- return '<directory-path>';
180
- return undefined;
181
- }
182
- export function buildEquivalentConfigCommandTokens(options) {
183
- return [
184
- 'aw',
185
- 'config',
186
- options.command,
187
- ...optionTokens('--scope', options.scope),
188
- ...(options.projectLayer === 'local' ? ['--local'] : []),
189
- ...(options.valueJson ? ['--value-json'] : []),
190
- ...(options.confirmed ? ['--yes'] : []),
191
- '--',
192
- options.plugin,
193
- ...(options.key === undefined ? [] : [options.key]),
194
- ...(options.value === undefined ? [] : [options.value]),
195
- ];
196
- }
197
- function hasSelectableWriteCandidate(command, candidates, selection, options) {
198
- const platforms = options.missingPlatform
199
- ? ['codex', 'claude', 'both']
200
- : [selection.platform ?? 'both'];
201
- const scopes = options.missingScope ? ['user', 'project'] : [selection.scope ?? 'user'];
202
- return candidates.some((candidate) => platforms.some((platform) => scopes.some((scope) => writeCandidateEligibility(command, candidate, { ...selection, platform, scope }).selectable)));
203
- }
204
- function hasConfigSchemaKeys(candidate) {
205
- return candidate.configSchema !== undefined && Object.keys(candidate.configSchema).length > 0;
206
- }
207
- async function loadWizardCandidates(context, rawOptions) {
208
- const loaded = await loadConsoleItemsResult({
209
- cwd: context.cwd,
210
- scope: rawOptions.scope,
211
- platform: rawOptions.platform,
212
- includeCatalogOnly: true,
213
- }, context);
214
- return toWizardCandidates(loaded.items);
215
- }
216
- function mergeWizardCandidates(current, stored) {
217
- const merged = new Map(current.map((candidate) => [candidate.pluginName, candidate]));
218
- for (const candidate of stored) {
219
- const existing = merged.get(candidate.pluginName);
220
- if (!existing) {
221
- merged.set(candidate.pluginName, candidate);
222
- }
223
- else if (!existing.configSchema) {
224
- merged.set(candidate.pluginName, { ...candidate, ...existing });
225
- }
215
+ async function resolveStoredConfigResetIdentity(options) {
216
+ const parsed = parsePluginId(options.selector);
217
+ if (parsed.sourceId) {
218
+ return {
219
+ pluginName: parsed.pluginName,
220
+ pluginId: options.selector,
221
+ sourceId: parsed.sourceId,
222
+ };
226
223
  }
227
- return [...merged.values()];
228
- }
229
- async function loadStoredConfigWizardCandidates(context, locations, options = {}) {
230
- const legacy = await listPluginConfigStorePluginNames({ cwd: context.cwd, env: context.env });
231
- if (legacy.length > 0) {
232
- throw new Error('legacyStateUnsupported: legacy bare-name config stores are not supported.');
224
+ const matches = (await listNamespacedPluginConfigStores({
225
+ cwd: options.context.cwd,
226
+ env: options.context.env,
227
+ scope: options.scope,
228
+ })).filter((store) => store.pluginName === parsed.pluginName);
229
+ if (matches.length === 0) {
230
+ throw new Error(`configStoreMissing: ${options.selector} has no config in the selected store.`);
233
231
  }
234
- const storesByPlugin = new Map();
235
- for (const location of locations) {
236
- const stores = await listNamespacedPluginConfigStores({
237
- cwd: context.cwd,
238
- env: context.env,
239
- scope: location.scope,
240
- ...(location.scope === 'project' ? { projectLayer: location.projectLayer } : {}),
241
- });
242
- for (const store of stores) {
243
- const keys = Object.keys(store.values);
244
- if (keys.length === 0 && options.includeEmptyStores !== true)
245
- continue;
246
- const existing = storesByPlugin.get(store.pluginId) ?? {
247
- sourceId: store.sourceId,
248
- sourceIdentity: store.sourceIdentity,
249
- keys: new Set(),
250
- };
251
- if (existing.sourceIdentity !== store.sourceIdentity) {
252
- throw new Error(`sourceChanged: ${store.pluginId} config stores have different source identities.`);
253
- }
254
- for (const key of keys)
255
- existing.keys.add(key);
256
- storesByPlugin.set(store.pluginId, existing);
257
- }
232
+ if (matches.length > 1) {
233
+ throw new Error(`configTargetAmbiguous: ${options.selector} exists in multiple source namespaces: ${matches.map((store) => store.pluginId).join(', ')}. Use a full pluginId.`);
258
234
  }
259
- return [...storesByPlugin]
260
- .sort(([left], [right]) => left.localeCompare(right))
261
- .map(([pluginId, store]) => ({
262
- pluginName: pluginId,
263
- pluginId,
264
- sourceId: store.sourceId,
265
- sourceIdentity: store.sourceIdentity,
266
- targets: [],
267
- configKeys: [...store.keys].sort((left, right) => left.localeCompare(right)),
268
- }));
269
- }
270
- function configReadStoreLocations(rawOptions) {
271
- if (rawOptions.local)
272
- return [{ scope: 'project', projectLayer: 'local' }];
273
- if (rawOptions.scope === 'user')
274
- return [{ scope: 'user', projectLayer: 'shared' }];
275
- if (rawOptions.scope === 'project')
276
- return [{ scope: 'project', projectLayer: 'shared' }];
277
- return [
278
- { scope: 'user', projectLayer: 'shared' },
279
- { scope: 'project', projectLayer: 'shared' },
280
- { scope: 'project', projectLayer: 'local' },
281
- ];
282
- }
283
- function overallResultState(value) {
284
- return value.overallState;
235
+ const [match] = matches;
236
+ return {
237
+ pluginName: match.pluginName,
238
+ pluginId: match.pluginId,
239
+ sourceId: match.sourceId,
240
+ sourceIdentity: match.binding.sourceIdentity,
241
+ };
285
242
  }
286
243
  async function resolveStoredOnlyConfigIdentity(options) {
287
244
  const parsed = parsePluginId(options.selector);
288
245
  if (!parsed.sourceId)
289
246
  throw new Error(`Plugin "${options.selector}" is not a qualified stored config target.`);
290
- const stores = (await Promise.all(options.locations.map((location) => listNamespacedPluginConfigStores({
291
- cwd: options.context.cwd,
292
- env: options.context.env,
293
- scope: location.scope,
294
- ...(location.scope === 'project' ? { projectLayer: location.projectLayer } : {}),
295
- })))).flat().filter((store) => store.pluginId === options.selector);
247
+ const stores = (await listNamespacedPluginConfigStores({
248
+ cwd: options.context.cwd, env: options.context.env, scope: 'user',
249
+ })).filter((store) => store.pluginId === options.selector);
296
250
  if (stores.length === 0)
297
251
  throw new Error(`Plugin "${options.selector}" does not have a namespaced config store.`);
298
- const identities = new Set(stores.map((store) => store.sourceIdentity));
299
- if (identities.size !== 1)
300
- throw new Error(`sourceChanged: ${options.selector} config stores have different source identities.`);
301
- const sourceIdentity = [...identities][0];
302
- await withResolvedMultiSourceCatalog({
252
+ const sourceBindings = stores.flatMap((store) => store.binding.kind === 'source'
253
+ ? [store.binding.sourceIdentity] : []);
254
+ if (new Set(sourceBindings).size > 1) {
255
+ throw new Error(`identityMismatch: ${options.selector} config stores have different bindings.`);
256
+ }
257
+ const currentSource = await withResolvedMultiSourceCatalog({
303
258
  cliVersion: resolveCliVersion(),
304
- freshnessPolicy: 'cacheFirst',
305
259
  sourceIds: [parsed.sourceId],
306
260
  env: options.context.env,
307
261
  consume: async (catalog) => {
308
262
  const source = catalog.sources.find((entry) => entry.sourceId === parsed.sourceId);
309
- if (!source?.resolution)
263
+ if (!source?.resolution) {
310
264
  throw source?.error ?? new Error(`Catalog source "${parsed.sourceId}" is unavailable.`);
311
- if (source.resolution.sourceIdentity !== sourceIdentity) {
312
- throw new Error(`sourceChanged: ${options.selector} config source identity does not match the current source.`);
313
265
  }
266
+ return {
267
+ sourceIdentity: source.resolution.sourceIdentity,
268
+ logicalIdentity: source.resolution.logicalIdentity,
269
+ };
314
270
  },
315
271
  });
272
+ if (sourceBindings[0] && sourceBindings[0] !== currentSource.sourceIdentity) {
273
+ throw new Error(`identityMismatch: ${options.selector} user config does not match the current source identity.`);
274
+ }
316
275
  return {
317
276
  pluginName: parsed.pluginName,
318
277
  pluginId: options.selector,
319
278
  sourceId: parsed.sourceId,
320
- sourceIdentity,
279
+ sourceIdentity: currentSource.sourceIdentity,
280
+ logicalIdentity: currentSource.logicalIdentity,
321
281
  };
322
282
  }
323
283
  async function resolveMultiSourceConfigRead(options) {
324
284
  const inventory = await inventoryLegacyConfigReferences({
325
285
  cwd: options.context.cwd,
326
286
  env: options.context.env,
287
+ scope: options.rawOptions.context === 'project' ? 'project' : 'user',
327
288
  });
328
289
  assertCatalogSourceReferencesSupported(inventory);
329
- const projectLayer = resolveConfigProjectLayer(options.rawOptions);
330
290
  return withResolvedCatalogPlugin({
331
291
  selector: options.selector,
332
292
  cliVersion: resolveCliVersion(),
333
- freshnessPolicy: 'cacheFirst',
334
293
  env: options.context.env,
335
294
  consume: async ({ pluginId, source, plugin }) => {
336
295
  const result = await resolveConfigRead({
337
296
  pluginName: plugin.manifest.name,
338
297
  plugin,
339
- scope: options.rawOptions.local
340
- ? 'project'
341
- : resolveConfigReadResolution(options.rawOptions.scope),
342
- projectLayer,
298
+ scope: options.rawOptions.context === 'project' ? 'project' : 'user',
299
+ platform: options.rawOptions.platform,
343
300
  cwd: options.context.cwd,
344
301
  env: options.context.env,
345
302
  });
346
303
  if (options.key !== undefined) {
347
304
  const field = findConfigFieldEntry(result.fields, options.key);
348
- if (!field && plugin.manifest.config?.schema?.[options.key] === undefined) {
305
+ if (!field && compilePluginConfigDefinition(plugin.manifest.config, options.rawOptions.platform).fields[options.key] === undefined) {
349
306
  throw new Error(`Unknown config key "${options.key}".`);
350
307
  }
351
308
  if (field)
@@ -366,17 +323,15 @@ async function resolveMultiSourceConfigRead(options) {
366
323
  const stored = await resolveStoredOnlyConfigIdentity({
367
324
  selector: options.selector,
368
325
  context: options.context,
369
- locations: configReadStoreLocations(options.rawOptions),
370
326
  });
371
327
  const result = await resolveConfigRead({
372
328
  sourceId: stored.sourceId,
373
329
  sourceIdentity: stored.sourceIdentity,
330
+ logicalIdentity: stored.logicalIdentity,
374
331
  pluginName: stored.pluginName,
375
332
  plugin: null,
376
- scope: options.rawOptions.local
377
- ? 'project'
378
- : resolveConfigReadResolution(options.rawOptions.scope),
379
- projectLayer,
333
+ scope: options.rawOptions.context === 'project' ? 'project' : 'user',
334
+ platform: options.rawOptions.platform,
380
335
  cwd: options.context.cwd,
381
336
  env: options.context.env,
382
337
  });
@@ -389,100 +344,42 @@ async function resolveMultiSourceConfigRead(options) {
389
344
  return { ...stored, result };
390
345
  });
391
346
  }
392
- async function executeWriteCommand(command, pluginNames, rawOptions, context) {
393
- const raw = { cwd: context.cwd, ...rawOptions };
394
- const commandOptions = command === 'install'
395
- ? normalizeInstallCommandOptions(raw)
396
- : command === 'upgrade'
397
- ? normalizeUpgradeCommandOptions(raw)
398
- : command === 'uninstall'
399
- ? normalizeUninstallCommandOptions(raw)
400
- : command === 'cleanup'
401
- ? normalizeCleanupCommandOptions(raw)
402
- : normalizeReinstallCommandOptions(raw);
403
- await emitCommandEvent(context, {
404
- type: 'options:normalized',
405
- data: { plugins: pluginNames, options: commandOptions },
406
- });
407
- switch (command) {
408
- case 'install': return installCommand(pluginNames, commandOptions, context);
409
- case 'upgrade': return upgradeCommand(pluginNames, commandOptions, context);
410
- case 'uninstall': return uninstallCommand(pluginNames, commandOptions, context);
411
- case 'cleanup': return cleanupCommand(pluginNames, commandOptions, context);
412
- case 'reinstall': return reinstallCommand(pluginNames, commandOptions, context);
413
- }
414
- }
415
- async function runWriteCommandAction(command, pluginNames, rawOptions, context) {
416
- if ((command === 'cleanup' || command === 'reinstall') && pluginNames.length > 1) {
417
- throw new Error(`${command} 命令当前只支持单个插件目标。`);
418
- }
419
- if (command === 'upgrade')
420
- assertUpgradeAllConflict(pluginNames, rawOptions.all === true);
421
- const missingPlugin = pluginNames.length === 0 && !(command === 'upgrade' && rawOptions.all === true);
422
- const missingPlatform = rawOptions.platform === undefined;
423
- const missingScope = command === 'cleanup' && rawOptions.scope === undefined;
424
- const missing = missingPlugin || missingPlatform || missingScope;
425
- // Validate every value already supplied by the caller before opening the TUI.
426
- const validationOptions = {
427
- cwd: context.cwd,
428
- ...rawOptions,
429
- platform: rawOptions.platform ?? 'both',
430
- ...(command === 'cleanup' ? { scope: rawOptions.scope ?? 'user' } : {}),
431
- };
432
- void validationOptions;
433
- if (!missing) {
434
- return {
435
- cancelled: false,
436
- result: await executeWriteCommand(command, pluginNames, rawOptions, context),
437
- };
347
+ function renderRecoveryReceipt(write, value) {
348
+ writeLine(write, `${value.command} [${value.scope}]: ${value.ok ? 'ok' : 'failed'}`);
349
+ writeLine(write, `需求:${value.intent.roots?.join('、') || (value.intent.roots === null ? '不可读' : '无')}`);
350
+ writeLine(write, `本机工具:${value.selection.agents.join('、') || '未配置'}`);
351
+ writeLine(write, `变化:声明 ${value.declarationChanged ? '已保存' : '无'};偏好 ${value.preferencesChanged ? '已保存' : '无'};配置 ${value.configChanged ? '已保存' : '无'};输出 ${value.outputsMayHaveChanged ? '可能已变更' : '无'}`);
352
+ for (const target of value.targetResults) {
353
+ writeLine(write, `${target.pluginId} / ${target.agent} [${target.scope}]: ${target.execution}; ${target.content ?? target.observation}`);
438
354
  }
439
- if (!isWizardAvailable(context, rawOptions)) {
440
- throw new Error(writeCommandUsage(command));
355
+ for (const result of value.commandResults ?? []) {
356
+ const producer = result.producer;
357
+ writeLine(write, `托管命令 ${producer.sourceId}/${producer.pluginName}/${producer.key} [${producer.scope}]: ${result.state}`);
441
358
  }
442
- const loaded = await loadConsoleItemsResult({
443
- cwd: context.cwd,
444
- scope: rawOptions.scope,
445
- platform: rawOptions.platform,
446
- includeCatalogOnly: true,
447
- }, context);
448
- if (loaded.catalogUnavailable) {
449
- throw new Error('插件目录不可用。请运行 `aw init` 或 `aw init --force`,或使用完整参数重试。');
359
+ for (const change of value.nativeToolChanges ?? []) {
360
+ for (const phase of ['before', 'after']) {
361
+ const closure = change[phase];
362
+ if (closure)
363
+ for (const description of describeNativeToolClosure(closure)) {
364
+ writeLine(write, `原生工具 ${change.producer.sourceId}/${change.producer.pluginName} ${phase}: ${description}`);
365
+ }
366
+ }
450
367
  }
451
- const candidates = missingPlugin ? toWizardCandidates(loaded.items) : [];
452
- const initialSelection = {
453
- plugins: pluginNames,
454
- platform: rawOptions.platform,
455
- scope: (rawOptions.scope ?? 'user'),
368
+ const diagnostics = new Map([...value.blockers, ...value.errors,
369
+ ...value.targetResults.flatMap((target) => target.blockers),
370
+ ...(value.commandResults ?? []).flatMap((result) => result.errors),
371
+ ].map((item) => [`${item.code}:${item.message}`, item]));
372
+ for (const item of diagnostics.values())
373
+ writeLine(write, `${item.code}: ${item.message}`);
374
+ for (const action of value.recoveryActions)
375
+ writeLine(write, action);
376
+ }
377
+ function recoveryRuntime(context, rawOptions, directCli) {
378
+ return {
379
+ ...context,
380
+ directCli,
381
+ preApplyConfirmed: rawOptions.yes === true,
456
382
  };
457
- if (missingPlugin && !hasSelectableWriteCandidate(command, candidates, initialSelection, {
458
- missingPlatform,
459
- missingScope,
460
- })) {
461
- throw new Error('没有可执行此操作的目标。请运行 `aw status` 检查当前状态。');
462
- }
463
- const result = await runCommandWizard(context, {
464
- command,
465
- candidates,
466
- initial: initialSelection,
467
- pluginMode: missingPlugin
468
- ? command === 'cleanup' || command === 'reinstall' ? 'single' : 'multiple'
469
- : 'none',
470
- promptForPlatform: missingPlatform,
471
- promptForScope: missingScope,
472
- destructive: command === 'uninstall' || command === 'cleanup',
473
- equivalentCommand: (selection) => equivalentWriteCommand(command, selection, rawOptions),
474
- equivalentCommandTokens: (selection) => buildEquivalentWriteCommandTokens(command, selection, rawOptions),
475
- isPluginSelectable: (candidate, selection) => writeCandidateEligibility(command, candidate, selection),
476
- resultState: overallResultState,
477
- execute: (selection) => executeWriteCommand(command, selection.plugins, {
478
- ...rawOptions,
479
- platform: selection.platform,
480
- scope: selection.scope,
481
- }, context),
482
- });
483
- if (result.cancelled)
484
- return { cancelled: true };
485
- return { cancelled: false, result: result.value };
486
383
  }
487
384
  function parseBareConsoleOptions(argv) {
488
385
  if (argv.length === 0) {
@@ -541,7 +438,7 @@ async function runActionWithContext(context, action) {
541
438
  Promise.resolve().then(() => context.debugLogger.flush?.()),
542
439
  ]);
543
440
  if (context.diagnostics.debug && context.debugLogger.logFile) {
544
- writeLine(context.io.stderr, `调试日志:${context.debugLogger.logFile}`);
441
+ writeLine(context.io.stderr, `Debug log: ${context.debugLogger.logFile}`);
545
442
  }
546
443
  return result;
547
444
  }
@@ -581,42 +478,84 @@ async function runActionWithContext(context, action) {
581
478
  Promise.resolve().then(() => context.debugLogger.flush?.()),
582
479
  ]);
583
480
  if (context.diagnostics.debug && context.debugLogger.logFile) {
584
- writeLine(context.io.stderr, `调试日志:${context.debugLogger.logFile}`);
481
+ writeLine(context.io.stderr, `Debug log: ${context.debugLogger.logFile}`);
585
482
  }
586
483
  throw error;
587
484
  }
588
485
  }
589
486
  function writeJsonReceipt(write, payload) {
590
- writeLine(write, JSON.stringify(payload, null, 2));
591
- }
592
- function configLayerLabel(scope, projectLayer = 'shared') {
593
- if (scope === 'user') {
594
- return '个人';
595
- }
596
- return projectLayer === 'local' ? '当前项目(本机私有覆盖)' : '当前项目';
487
+ const sink = receiptSinks.get(write);
488
+ if (sink)
489
+ sink(payload);
490
+ else
491
+ writeLine(write, JSON.stringify(payload, null, 2));
597
492
  }
598
493
  function writeConfigApplyNotice(write, receipt) {
599
- if (receipt.targetResults.length === 0) {
600
- const message = receipt.applySkippedReason === 'noConfigChange'
601
- ? '配置内容没有变化,因此没有运行 reinstall。'
602
- : '配置已保存。当前没有可见的 AW 安装目标,因此没有应用配置。';
494
+ const sanitizeMessage = (message) => redactString(message)
495
+ .replace(/https?:\/\/\S+/giu, '[REDACTED URL]')
496
+ .replace(/file:\/\/\S+/giu, '[REDACTED PATH]')
497
+ .replace(/(?:file:\/\/)?(?:\/[\w.@+-]+){2,}/gu, '[REDACTED PATH]')
498
+ .replace(/[A-Za-z]:\\(?:[^\s\\]+\\)+[^\s\\]*/gu, '[REDACTED PATH]');
499
+ const writeTargetFailures = () => {
500
+ for (const entry of receipt.apply.targetResults.filter((target) => target.state === 'failed' || target.state === 'skipped')) {
501
+ const reason = entry.message
502
+ ? `${entry.errorCode ? `[${entry.errorCode}] ` : ''}${sanitizeMessage(entry.message)}`
503
+ : entry.errorCode
504
+ ? `失败原因:${entry.errorCode}。`
505
+ : '未提供安全失败原因。';
506
+ const command = `aw plugin sync ${receipt.plugin} --rebuild --target ${entry.target.platform} --context ${entry.target.scope}`;
507
+ const recovery = entry.errorCode === 'invalidConfig'
508
+ ? ` 请修复无效配置后运行 ${command}。`
509
+ : entry.errorCode === 'preApplyAuthorizationRequired'
510
+ || entry.errorCode === 'sharedNativeConfigApplyConfirmationRequired'
511
+ || entry.errorCode === 'sharedNativeImpactAuthorizationRequired'
512
+ ? ` 请运行 ${command} --yes 重试。`
513
+ : entry.state === 'failed'
514
+ ? ` 请在解决失败原因后运行 ${command}。`
515
+ : '';
516
+ writeLine(write, `${entry.target.platform}/${entry.target.scope}:${reason}${recovery}`);
517
+ }
518
+ };
519
+ const targetResults = receipt.apply.targetResults;
520
+ if (receipt.apply.state === 'skipped') {
521
+ const message = receipt.apply.reason === 'noConfigChange'
522
+ ? '配置内容没有变化,因此没有刷新输出。'
523
+ : receipt.apply.reason === 'noEffectiveConfigChange'
524
+ ? '配置存储已更新,但有效配置没有变化,因此没有刷新输出。'
525
+ : receipt.apply.reason === 'notRequested'
526
+ ? '配置已保存,但未请求应用配置。'
527
+ : '配置已保存。当前没有可见的 AW 安装目标,因此没有应用配置。';
603
528
  writeLine(write, message);
604
529
  }
605
- else {
606
- const completed = receipt.targetResults.filter((entry) => entry.state === 'completed').length;
607
- const failed = receipt.targetResults.filter((entry) => entry.state === 'failed');
608
- writeLine(write, `配置已保存。已重装 ${completed} 个当前可见目标;失败 ${failed.length} 个。`);
609
- for (const entry of failed) {
610
- writeLine(write, `${entry.target.platform}/${entry.target.scope}:${entry.message ?? 'reinstall 失败。'} `
611
- + `请重试 aw reinstall ${receipt.plugin} -p ${entry.target.platform} -s ${entry.target.scope}。`);
612
- }
530
+ else if (receipt.apply.state === 'unavailable') {
531
+ const fallbackMessages = {
532
+ invalidConfig: '可见目标的有效配置无效。',
533
+ schemaUnavailable: '配置 schema 不可用。',
534
+ sourceUnavailable: '插件来源不可用。',
535
+ effectiveConfigUnavailable: '无法读取有效配置。',
536
+ targetDiscoveryFailed: '无法发现可应用配置的目标。',
537
+ };
538
+ const detail = receipt.apply.error
539
+ ? `${receipt.apply.error.code}:${sanitizeMessage(receipt.apply.error.message)}`
540
+ : `${receipt.apply.reason}:${fallbackMessages[receipt.apply.reason]}`;
541
+ const recovery = receipt.apply.reason === 'invalidConfig'
542
+ ? '请修复无效配置,再运行 aw plugin sync <source/plugin>。'
543
+ : receipt.apply.reason === 'effectiveConfigUnavailable'
544
+ ? '请修复配置,再运行 aw plugin sync <source/plugin>。'
545
+ : receipt.apply.reason === 'schemaUnavailable' || receipt.apply.reason === 'sourceUnavailable'
546
+ ? '请修复插件来源或配置,再运行 aw plugin sync <source/plugin>。'
547
+ : '请修复来源或配置,再运行 aw plugin sync <source/plugin>。';
548
+ writeLine(write, `配置已保存,但当前无法应用配置。${detail} ${recovery}`);
549
+ writeTargetFailures();
613
550
  }
614
- if (receipt.otherProjectsRequireReinstall) {
615
- writeLine(write, '其它项目没有被扫描。请进入每个项目目录并运行对应的 aw reinstall 命令。');
551
+ else {
552
+ const completed = targetResults.filter((entry) => entry.state === 'completed').length;
553
+ const failed = targetResults.filter((entry) => entry.state === 'failed').length;
554
+ const skipped = targetResults.filter((entry) => entry.state === 'skipped').length;
555
+ writeLine(write, `配置已保存。已刷新 ${completed} 个当前可见目标;失败 ${failed} 个;跳过 ${skipped} 个。`);
556
+ writeTargetFailures();
616
557
  }
617
- }
618
- function writeProjectLocalConfigNotice(write) {
619
- writeLine(write, '当前显示的是当前项目的本机私有覆盖层,不作为 repo-visible artifact 渲染输入。');
558
+ writeWarnings(write, receipt.warnings);
620
559
  }
621
560
  function renderConfigFieldState(field) {
622
561
  if (field.valueState === 'invalid') {
@@ -635,14 +574,14 @@ function writeConfigReadHuman(write, resolved, pluginName) {
635
574
  writeLine(write, ` stored=${field.storedSourceLayer} ${renderPluginConfigValueForDisplay(field.storedValue)}`);
636
575
  }
637
576
  if (field.kind === 'manifest' && field.valueState === 'invalid') {
638
- const sourceScope = field.sourceLayer === 'project'
639
- ? ' -s project'
640
- : field.sourceLayer === 'local'
641
- ? ' -s project --local'
642
- : ' -s user';
643
- writeLine(write, ` aw config set ${pluginName} ${field.key} <value>${sourceScope}`);
644
- writeLine(write, ` aw config unset ${pluginName} ${field.key}${sourceScope}`);
645
- writeLine(write, ` aw config reset ${pluginName}${sourceScope}`);
577
+ const context = resolved.context ?? 'user';
578
+ const definition = resolved.fieldDefinitions?.[field.key];
579
+ if (definition) {
580
+ writeLine(write, ` ${formatPluginConfigSetRecoveryCommand(pluginName, field.key, definition, context, resolved.platform)}`);
581
+ }
582
+ const profileOptions = ` --context ${context}${resolved.platform ? ` --platform ${resolved.platform}` : ''}`;
583
+ writeLine(write, ` aw plugin config unset ${pluginName} ${field.key}${profileOptions}`);
584
+ writeLine(write, ` aw plugin config reset ${pluginName}${profileOptions} --yes`);
646
585
  }
647
586
  }
648
587
  }
@@ -659,10 +598,13 @@ export function buildProgram(options = {}) {
659
598
  cwd,
660
599
  env,
661
600
  io,
662
- interactive: options.interactive,
601
+ interactive: false,
602
+ reporter: options.reporter ?? createNoopReporter(),
663
603
  diagnostics: toCliDiagnosticsOptions(commandName, rawOptions, options.diagnostics),
664
604
  });
665
- const program = new Command();
605
+ if (io.result)
606
+ receiptSinks.set(io.stdout, io.result);
607
+ const program = new Command().enablePositionalOptions();
666
608
  program
667
609
  .name('aw')
668
610
  .description('Agent workflow marketplace installer')
@@ -673,13 +615,42 @@ export function buildProgram(options = {}) {
673
615
  writeErr: (text) => io.stderr(text),
674
616
  outputError: (text, write) => write(text),
675
617
  });
618
+ const dev = program.command('dev').description('Create, validate, build, and publish author sources');
619
+ const devPlugin = dev.command('plugin').description('Manage plugin source code');
676
620
  const plugin = program
677
621
  .command('plugin')
678
- .description('Create and validate AW plugin source');
679
- plugin
622
+ .description('Manage plugin demand, outputs, configuration, and author sources');
623
+ registerManagedCommandCli(program, (rawOptions = {}) => createActionContext('command', rawOptions), {
624
+ cliEntry: fileURLToPath(import.meta.url),
625
+ cliVersion: resolveCliVersion(),
626
+ }, (code) => { commandExitState.exitCode = code; });
627
+ const self = program
628
+ .command('self')
629
+ .description('Describe and check this AW executable');
630
+ self
631
+ .command('describe')
632
+ .description('Describe implemented AW capabilities')
633
+ .requiredOption('--json', 'emit one machine-readable JSON object')
634
+ .action(() => {
635
+ writeJsonReceipt(io.stdout, describeCurrentAw(resolveCliVersion()));
636
+ });
637
+ self
638
+ .command('check')
639
+ .description('Check nearby plugin requirements against this AW executable')
640
+ .option('--from <path>', 'start discovery from this file or directory')
641
+ .requiredOption('--json', 'emit one machine-readable JSON object')
642
+ .action(async (rawOptions) => {
643
+ const result = await checkCurrentAw({
644
+ awVersion: resolveCliVersion(),
645
+ from: path.resolve(cwd, rawOptions.from ?? '.'),
646
+ });
647
+ writeJsonReceipt(io.stdout, result);
648
+ commandExitState.exitCode = result.ok ? 0 : 1;
649
+ });
650
+ devPlugin
680
651
  .command('capabilities')
681
- .description('Show the current plugin authoring capability contract')
682
- .option('--surface <surface>', 'manifest | build-config | extensions | slash-commands | mcp-apps | config | lifecycle | artifacts')
652
+ .description('Show the current plugin manifest authoring surface')
653
+ .option('--surface <surface>', 'manifest | build-config | extensions | slash-commands | mcp-apps | config | pre-apply | artifacts')
683
654
  .option('--json', 'emit one machine-readable JSON object', false)
684
655
  .action((rawOptions) => {
685
656
  try {
@@ -701,269 +672,229 @@ export function buildProgram(options = {}) {
701
672
  commandExitState.exitCode = 1;
702
673
  }
703
674
  });
704
- const skill = program
705
- .command('skill')
706
- .description('Install, materialize, or validate Agent Skills');
707
- const review = program
708
- .command('review')
709
- .description('Publish and inspect immutable review records');
710
- const reviewRecordDir = (repoRoot, record) => path.relative(fs.realpathSync(repoRoot), record.root).split(path.sep).join('/');
711
- const reviewJsonRecord = (repoRoot, record) => ({
712
- recordDir: reviewRecordDir(repoRoot, record),
713
- manifest: record.manifest,
714
- });
715
- review
716
- .command('digest')
717
- .description('Compute one canonical workflow component digest')
718
- .argument('<path>', 'repository file or directory')
719
- .option('--json', 'emit one component digest JSON object', false)
720
- .action(async (componentPath, rawOptions) => {
721
- const repoRoot = await resolveRepoRoot(cwd);
722
- const result = await computeReviewComponentDigest({ repoRoot, path: componentPath });
723
- if (rawOptions.json) {
724
- writeJsonReceipt(io.stdout, {
725
- schemaVersion: 1,
726
- command: 'review:digest',
727
- ok: true,
728
- ...result,
675
+ devPlugin
676
+ .command('requirements')
677
+ .description('Inspect or update effective AW capabilities required by a plugin')
678
+ .argument('<plugin-directory>', 'plugin source directory')
679
+ .option('--workspace-root <root>', 'Catalog Workspace root (default: nearest ancestor from plugin directory)')
680
+ .option('--add <capability>', 'add one declared AW capability')
681
+ .option('--remove <capability>', 'remove one declared AW capability')
682
+ .requiredOption('--json', 'emit one machine-readable JSON object')
683
+ .action(async (pluginDirectory, rawOptions) => {
684
+ try {
685
+ const result = await inspectPluginRequirements({
686
+ pluginDirectory,
687
+ ...(rawOptions.workspaceRoot ? { workspaceRoot: rawOptions.workspaceRoot } : {}),
688
+ ...(rawOptions.add ? { add: rawOptions.add } : {}),
689
+ ...(rawOptions.remove ? { remove: rawOptions.remove } : {}),
690
+ cwd,
729
691
  });
730
- return;
692
+ writeJsonReceipt(io.stdout, result);
693
+ if (result.observations.some((observation) => observation.blocking)) {
694
+ commandExitState.exitCode = 1;
695
+ }
731
696
  }
732
- writeLine(io.stdout, `${result.path}: ${result.digest}`);
733
- });
734
- review
735
- .command('publish')
736
- .description('Publish one immutable review record')
737
- .requiredOption('--kind <skill|workflow|aw-plugin|aw-workflow>', 'review target kind')
738
- .requiredOption('--target <path-or-id>', 'review target path or ID')
739
- .requiredOption('--report <report.md>', 'review report Markdown file')
740
- .option('--scope <scope.json>', 'workflow scope JSON file')
741
- .option('--result <review-result.json>', 'review result JSON file')
742
- .option('--check <kind=path>', 'archive one JSON check attachment', (value, previous) => [
743
- ...previous,
744
- parseReviewAttachment(value, 'Check'),
745
- ], [])
746
- .option('--evidence <kind=path>', 'archive one JSON evidence attachment', (value, previous) => [
747
- ...previous,
748
- parseReviewAttachment(value, 'Evidence'),
749
- ], [])
750
- .option('--release-check <release-check.json>', 'release check JSON file')
751
- .option('--supersedes <review-id>', 'review ID that this record supersedes')
752
- .option('--json', 'emit one review record JSON object', false)
753
- .action(async (rawOptions) => {
754
- const repoRoot = await resolveRepoRoot(cwd);
755
- const record = await publishReviewRecord({
756
- repoRoot,
757
- kind: rawOptions.kind,
758
- target: rawOptions.target,
759
- report: rawOptions.report,
760
- ...(rawOptions.scope === undefined ? {} : { scope: rawOptions.scope }),
761
- ...(rawOptions.result === undefined ? {} : { result: rawOptions.result }),
762
- ...(rawOptions.check.length === 0 ? {} : { checks: rawOptions.check }),
763
- ...(rawOptions.evidence.length === 0 ? {} : { evidence: rawOptions.evidence }),
764
- ...(rawOptions.releaseCheck === undefined ? {} : { releaseCheck: rawOptions.releaseCheck }),
765
- ...(rawOptions.supersedes === undefined ? {} : { supersedes: rawOptions.supersedes }),
766
- });
767
- const recordDir = reviewRecordDir(repoRoot, record);
768
- if (rawOptions.json) {
697
+ catch (error) {
698
+ if (error instanceof CatalogWorkspaceMissingError)
699
+ throw error;
769
700
  writeJsonReceipt(io.stdout, {
770
701
  schemaVersion: 1,
771
- command: 'review:publish',
772
- ok: true,
773
- ...reviewJsonRecord(repoRoot, record),
774
- existing: record.existing,
702
+ command: 'plugin:requirements',
703
+ ok: false,
704
+ error: error instanceof Error ? error.message : String(error),
775
705
  });
776
- return;
706
+ commandExitState.exitCode = 1;
777
707
  }
778
- writeLine(io.stdout, `${record.existing ? 'Existing' : 'Published'} review ${record.manifest.reviewId}: ${recordDir}`);
779
708
  });
780
- review
781
- .command('verify')
782
- .description('Verify one archived review record')
783
- .argument('<report-dir>', 'review record directory')
784
- .option('--json', 'emit one review record JSON object', false)
785
- .action(async (reportDir, rawOptions) => {
786
- const repoRoot = await resolveRepoRoot(cwd);
787
- const record = await verifyReviewRecord({ repoRoot, reportDir });
788
- const relativeRecordDir = reviewRecordDir(repoRoot, record);
789
- if (rawOptions.json) {
790
- writeJsonReceipt(io.stdout, {
791
- schemaVersion: 1,
792
- command: 'review:verify',
793
- ok: true,
794
- ...reviewJsonRecord(repoRoot, record),
795
- });
796
- return;
709
+ const skill = dev
710
+ .command('skill')
711
+ .description('Install, materialize, or validate Agent Skills');
712
+ const skillEval = dev
713
+ .command('eval')
714
+ .description('Prepare or diagnose deterministic Agent Skill Eval inputs');
715
+ skillEval
716
+ .command('check')
717
+ .description('Inspect Agent Skill Eval provider readiness without model execution')
718
+ .requiredOption('--json', 'emit one provider doctor JSON object')
719
+ .action(async () => {
720
+ try {
721
+ writeJsonReceipt(io.stdout, await doctorEvalProviders({
722
+ sourceEnv: env,
723
+ }));
797
724
  }
798
- writeLine(io.stdout, `Verified review ${record.manifest.reviewId}: ${relativeRecordDir}`);
799
- });
800
- review
801
- .command('list')
802
- .description('List immutable review records')
803
- .option('--kind <kind>', 'filter by review target kind')
804
- .option('--target <id>', 'filter by review target ID')
805
- .option('--json', 'emit one review records JSON object', false)
806
- .action(async (rawOptions) => {
807
- const repoRoot = await resolveRepoRoot(cwd);
808
- const records = await listReviewRecords({
809
- repoRoot,
810
- ...(rawOptions.kind === undefined ? {} : { kind: rawOptions.kind }),
811
- ...(rawOptions.target === undefined ? {} : { targetId: rawOptions.target }),
812
- });
813
- if (rawOptions.json) {
725
+ catch (error) {
814
726
  writeJsonReceipt(io.stdout, {
815
- schemaVersion: 1,
816
- command: 'review:list',
817
- ok: true,
818
- records: records.map((record) => reviewJsonRecord(repoRoot, record)),
727
+ ok: false,
728
+ error: redactString(error instanceof Error ? error.message : String(error)),
819
729
  });
820
- return;
821
- }
822
- for (const record of records) {
823
- writeLine(io.stdout, [
824
- record.manifest.reviewId,
825
- record.manifest.target.kind,
826
- record.manifest.target.id,
827
- record.manifest.publishedAt,
828
- ].join(' '));
730
+ commandExitState.exitCode = 1;
829
731
  }
830
732
  });
831
- review
832
- .command('show')
833
- .description('Show one immutable review record')
834
- .argument('<review-id>', 'review record ID')
835
- .option('--json', 'emit one review record JSON object', false)
836
- .action(async (reviewId, rawOptions) => {
837
- const repoRoot = await resolveRepoRoot(cwd);
838
- const record = await showReviewRecord({ repoRoot, reviewId });
839
- if (rawOptions.json) {
840
- writeJsonReceipt(io.stdout, {
841
- schemaVersion: 1,
842
- command: 'review:show',
843
- ok: true,
844
- ...reviewJsonRecord(repoRoot, record),
733
+ skillEval
734
+ .command('prepare')
735
+ .description('Prepare one complete Agent Skill Eval input directory')
736
+ .argument('<plugin>', 'canonical Workspace plugin name')
737
+ .argument('<skill>', 'owner Skill name')
738
+ .option('--suite <suite>', 'Eval suite ID')
739
+ .option('--profile <profile>', 'Eval profile ID')
740
+ .option('--config-file <path>', 'non-sensitive plugin config overrides for the Eval profile')
741
+ .option('--workspace-root <root>', 'Catalog Workspace root')
742
+ .option('--split <split>', 'case split filter')
743
+ .option('--case <id>', 'case ID filter')
744
+ .option('--runs <count>', 'runs per selected case')
745
+ .option('--timeout-ms <milliseconds>', 'timeout for each provider attempt')
746
+ .option('--baseline <mode>', 'append without-skill comparison')
747
+ .option('--previous-version <runtime-skill-root>', 'append a previous-version comparison')
748
+ .option('--keep-workspace', 'retain the preparation materialization workspace', false)
749
+ .requiredOption('--output <spec-directory>', 'new EvalSpec directory')
750
+ .requiredOption('--json', 'emit one preparation receipt JSON object')
751
+ .action(async (pluginName, skillName, rawOptions) => {
752
+ try {
753
+ const workspace = await resolveCatalogWorkspaceRoot({
754
+ cwd,
755
+ ...(rawOptions.workspaceRoot === undefined ? {} : { explicitRoot: rawOptions.workspaceRoot }),
756
+ mode: 'existing',
757
+ env,
845
758
  });
846
- return;
759
+ const runs = rawOptions.runs === undefined
760
+ ? undefined
761
+ : (/^[1-9][0-9]*$/u.test(rawOptions.runs) ? Number(rawOptions.runs) : Number.NaN);
762
+ const timeoutMs = rawOptions.timeoutMs === undefined
763
+ ? undefined
764
+ : (/^[1-9][0-9]*$/u.test(rawOptions.timeoutMs) ? Number(rawOptions.timeoutMs) : Number.NaN);
765
+ const receipt = await prepareSkillEval({
766
+ workspaceRoot: workspace.workspaceRoot,
767
+ workspaceRootResolvedFrom: workspace.workspaceRootResolvedFrom,
768
+ pluginName,
769
+ skillName,
770
+ ...(rawOptions.suite === undefined ? {} : { suiteId: rawOptions.suite }),
771
+ ...(rawOptions.profile === undefined ? {} : { profileId: rawOptions.profile }),
772
+ ...(rawOptions.configFile === undefined ? {} : { configFile: path.resolve(cwd, rawOptions.configFile) }),
773
+ output: rawOptions.output,
774
+ cwd,
775
+ env,
776
+ ...(rawOptions.split === undefined ? {} : { split: rawOptions.split }),
777
+ ...(rawOptions.case === undefined ? {} : { caseId: rawOptions.case }),
778
+ ...(runs === undefined ? {} : { runs }),
779
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
780
+ ...(rawOptions.baseline === undefined ? {} : {
781
+ baseline: rawOptions.baseline,
782
+ }),
783
+ ...(rawOptions.previousVersion === undefined ? {} : {
784
+ previousVersion: rawOptions.previousVersion,
785
+ }),
786
+ ...(rawOptions.keepWorkspace === true ? { keepWorkspace: true } : {}),
787
+ });
788
+ writeJsonReceipt(io.stdout, receipt);
847
789
  }
848
- const manifest = record.manifest;
849
- writeLine(io.stdout, `Review: ${manifest.reviewId}`);
850
- writeLine(io.stdout, `Target: ${manifest.target.kind} ${manifest.target.id}`);
851
- writeLine(io.stdout, `Published: ${manifest.publishedAt}`);
852
- writeLine(io.stdout, `Report: ${manifest.report.path}`);
853
- writeLine(io.stdout, `Result: ${manifest.result?.path ?? 'none'}`);
854
- writeLine(io.stdout, `Checks: ${manifest.checks.map((entry) => entry.kind).join(', ') || 'none'}`);
855
- writeLine(io.stdout, `Evidence: ${manifest.evidence.map((entry) => entry.kind).join(', ') || 'none'}`);
856
- writeLine(io.stdout, `Release check: ${manifest.releaseCheck?.path ?? 'none'}`);
857
- writeLine(io.stdout, `Supersedes: ${manifest.supersedes ?? 'none'}`);
858
- });
859
- skill
860
- .command('install')
861
- .description('Install portable Skills through the skills CLI')
862
- .argument('<plugin>', 'plugin or source/plugin selector')
863
- .requiredOption('-s, --scope <scope>', 'project or user')
864
- .option('--skill <name...>', 'install only selected Skill names')
865
- .option('--agent <id...>', 'install to explicit Agent IDs')
866
- .option('-y, --yes', 'confirm the reviewed install', false)
867
- .option('-j, --json', 'emit one receipt v4 JSON object', false)
868
- .action(async (selector, rawOptions) => {
869
- const context = createActionContext('skill:install', {});
870
- const writeFailure = (error) => {
871
- const code = error instanceof PortableCommandError || error instanceof SkillsCliError
872
- ? error.code
873
- : 'portableInstallFailed';
790
+ catch (error) {
791
+ if (error instanceof CatalogWorkspaceMissingError)
792
+ throw error;
874
793
  writeJsonReceipt(io.stdout, {
875
- receiptSchemaVersion: 4,
876
- command: 'skill:install',
794
+ schemaVersion: 1,
795
+ command: 'skill:eval:prepare',
877
796
  ok: false,
878
- status: 'failed',
879
- plugin: { id: selector },
880
- scope: rawOptions.scope,
881
- selectedSkills: [],
882
- ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
883
- agentMode: rawOptions.agent ? 'explicit' : 'automatic',
884
- requestedAgents: rawOptions.agent ?? [],
885
- skillsCliVersion: null,
886
- collisions: [],
887
- dependencies: [],
888
- materializationDigest: null,
889
- verification: { records: [], missing: [] },
890
- warnings: [],
891
- failures: [{ code, message: `${code}: portable Skill 安装未执行。` }],
797
+ errors: [{
798
+ code: 'evalPreparationFailed',
799
+ message: redactString(error instanceof Error ? error.message : String(error)),
800
+ }],
892
801
  });
893
- };
894
- if (rawOptions.json && !rawOptions.yes) {
895
- writeFailure(new PortableCommandError('confirmationRequired', '写入型 --json 必须同时使用 --yes。'));
896
802
  commandExitState.exitCode = 1;
897
- return;
898
803
  }
804
+ });
805
+ const review = dev
806
+ .command('review')
807
+ .description('Inspect and prepare Skill review materializations');
808
+ review
809
+ .command('inspect')
810
+ .description('Inspect current AW Review source and materialization facts')
811
+ .argument('<target>', 'Catalog Workspace, Plugin, or source Skill path')
812
+ .addOption(strictValueOption('--workspace-root <root>', 'explicit Catalog Workspace root'))
813
+ .option('--skill <name>', 'select one declared Skill', collectUniqueOption, [])
814
+ .addOption(strictValueOption('--platform <platform>', 'select a canonical platform target', PLATFORM_TARGETS))
815
+ .addOption(strictValueOption('--scope <scope>', 'select user or project scope', ['user', 'project']))
816
+ .addOption(strictValueOption('--config <file>', 'review config JSON file'))
817
+ .option('--materialization <receipt>', 'validate one aw-source-binding receipt', collectUniqueOption, [])
818
+ .addOption(strictValueOption('--view <view>', 'select the review navigation view', ['review']).default('review'))
819
+ .option('--json', 'emit one Review inspection JSON object', false)
820
+ .action(async (target, rawOptions) => {
899
821
  try {
900
- const receipt = await runActionWithContext(context, () => installPortableSkills({
901
- selector,
902
- scope: rawOptions.scope,
903
- ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
904
- ...(rawOptions.agent ? { requestedAgents: rawOptions.agent } : {}),
905
- yes: rawOptions.yes,
906
- cwd: context.cwd,
907
- cliVersion: resolveCliVersion(),
908
- env: context.env,
909
- ...(context.interactive && context.prompt.confirm ? {
910
- confirm: async () => context.prompt.confirm({
911
- message: '确认按以上 Review 安装 portable Skills?',
912
- defaultValue: false,
913
- }),
914
- } : {}),
915
- ...(!rawOptions.json ? {
916
- onReview: (review) => {
917
- for (const line of renderPortableReview(review))
918
- writeLine(io.stdout, line);
919
- },
920
- } : {}),
921
- }));
822
+ const receipt = await inspectReviewTarget({
823
+ cwd,
824
+ target,
825
+ ...(rawOptions.workspaceRoot === undefined
826
+ ? {}
827
+ : { workspaceRoot: rawOptions.workspaceRoot }),
828
+ skills: rawOptions.skill,
829
+ ...(rawOptions.platform === undefined ? {} : { platform: rawOptions.platform }),
830
+ ...(rawOptions.scope === undefined ? {} : { scope: rawOptions.scope }),
831
+ ...(rawOptions.config === undefined ? {} : { configFile: rawOptions.config }),
832
+ materializations: [...new Set(rawOptions.materialization
833
+ .map((entry) => path.resolve(cwd, entry)))],
834
+ view: rawOptions.view,
835
+ env,
836
+ });
922
837
  if (rawOptions.json)
923
838
  writeJsonReceipt(io.stdout, receipt);
924
- else if (receipt.ok)
925
- writeLine(io.stdout, `portable Skill 安装完成:${receipt.selectedSkills.length} 项。`);
926
- else {
927
- const sanitize = (value) => redactString(value)
928
- .replace(/https?:\/\/\S+/giu, '[REDACTED URL]')
929
- .replace(/(?:file:\/\/)?(?:\/[\w.@+-]+){2,}/gu, '[REDACTED PATH]')
930
- .replace(/[A-Za-z]:\\(?:[^\s\\]+\\)+[^\s\\]*/gu, '[REDACTED PATH]');
931
- const lines = new Set();
932
- for (const failure of receipt.failures) {
933
- lines.add(`${failure.code}: ${sanitize(failure.message)}`);
934
- }
935
- for (const warning of receipt.warnings)
936
- lines.add(`警告:${sanitize(warning)}`);
937
- const recoveries = receipt.failures.map((failure) => failure.recovery).filter(Boolean);
938
- const recovery = recoveries.find((entry) => entry.includes('aw skill install')
939
- && entry.includes('skills remove'))
940
- ?? '重新运行 aw skill install;如需清理外部写入,请使用 skills remove。';
941
- lines.add(`恢复:${sanitize(recovery)}`);
942
- for (const line of lines)
943
- writeLine(io.stderr, line);
944
- }
945
- commandExitState.exitCode = receipt.ok ? 0 : 1;
839
+ else
840
+ renderReviewInspection(io.stdout, receipt);
841
+ commandExitState.exitCode = 0;
946
842
  }
947
843
  catch (error) {
948
- if (!rawOptions.json)
949
- throw error;
950
- writeFailure(error);
951
- commandExitState.exitCode = 1;
844
+ const receipt = createReviewInspectionFailure(error);
845
+ if (rawOptions.json)
846
+ writeJsonReceipt(io.stdout, receipt);
847
+ else
848
+ renderReviewInspection(io.stdout, receipt);
849
+ commandExitState.exitCode = getReviewInspectionExitCode(error);
952
850
  }
953
851
  });
852
+ review
853
+ .command('prepare')
854
+ .description('Prepare deterministic Skill finals for AW Review')
855
+ .argument('<target>', 'Plugin or source Skill path')
856
+ .addOption(strictValueOption('--workspace-root <root>', 'explicit Catalog Workspace root'))
857
+ .option('--skill <name>', 'select one declared Skill', collectUniqueOption, [])
858
+ .addOption(strictValueOption('--platform <platform>', 'select a canonical platform target', PLATFORM_TARGETS).makeOptionMandatory())
859
+ .addOption(strictValueOption('--scope <scope>', 'select user or project scope', ['user', 'project']).makeOptionMandatory())
860
+ .addOption(strictValueOption('--config <file>', 'review config JSON file'))
861
+ .addOption(strictValueOption('--out <new-dir>', 'new output directory').makeOptionMandatory())
862
+ .option('--json', 'emit one Review preparation JSON object', false)
863
+ .action(async (target, rawOptions) => {
864
+ const result = await prepareReviewTarget({
865
+ cwd,
866
+ target,
867
+ ...(rawOptions.workspaceRoot === undefined
868
+ ? {}
869
+ : { workspaceRoot: rawOptions.workspaceRoot }),
870
+ skills: rawOptions.skill,
871
+ platform: rawOptions.platform,
872
+ scope: rawOptions.scope,
873
+ ...(rawOptions.config === undefined ? {} : { configFile: rawOptions.config }),
874
+ out: rawOptions.out,
875
+ env,
876
+ });
877
+ if (rawOptions.json)
878
+ writeJsonReceipt(io.stdout, result.receipt);
879
+ else
880
+ renderReviewPreparation(io.stdout, result.receipt);
881
+ commandExitState.exitCode = result.exitCode;
882
+ });
954
883
  skill
955
- .command('materialize')
884
+ .command('export')
956
885
  .description('Write portable Skills to a safe output directory')
957
886
  .argument('<plugin>', 'plugin or source/plugin selector')
958
- .requiredOption('-s, --scope <scope>', 'project or user')
887
+ .addOption(strictValueOption('--platform <target>', 'Portable platform target', PORTABLE_PLATFORM_TARGETS).makeOptionMandatory())
888
+ .addOption(strictValueOption('-s, --scope <scope>', 'artifact scope', ['user', 'project']).makeOptionMandatory())
959
889
  .requiredOption('--out <dir>', 'output directory')
960
890
  .option('--skill <name...>', 'write only selected Skill names')
961
- .option('-j, --json', 'emit one receipt v4 JSON object', false)
891
+ .option('-j, --json', 'emit one receipt v5 JSON object', false)
962
892
  .action(async (selector, rawOptions) => {
963
893
  const context = createActionContext('skill:materialize', {});
964
894
  try {
965
895
  const receipt = await runActionWithContext(context, () => materializePortableSkillsToDirectory({
966
896
  selector,
897
+ platform: rawOptions.platform,
967
898
  scope: rawOptions.scope,
968
899
  out: rawOptions.out,
969
900
  ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
@@ -979,15 +910,18 @@ export function buildProgram(options = {}) {
979
910
  catch (error) {
980
911
  if (!rawOptions.json)
981
912
  throw error;
982
- const code = error instanceof PortableCommandError || error instanceof SkillsCliError
983
- ? error.code
984
- : 'portableMaterializeFailed';
913
+ const capabilityError = error instanceof AwCapabilityUnsupportedError ? error : undefined;
914
+ const code = capabilityError?.code
915
+ ?? (error instanceof PortableCommandError
916
+ ? error.code
917
+ : 'portableMaterializeFailed');
985
918
  writeJsonReceipt(io.stdout, {
986
- receiptSchemaVersion: 4,
919
+ receiptSchemaVersion: 5,
987
920
  command: 'skill:materialize',
988
921
  ok: false,
989
922
  plugin: { id: selector },
990
923
  scope: rawOptions.scope,
924
+ platform: rawOptions.platform,
991
925
  out: path.resolve(context.cwd, rawOptions.out),
992
926
  selectedSkills: [],
993
927
  ...(rawOptions.skill ? { requestedSkills: rawOptions.skill } : {}),
@@ -995,19 +929,27 @@ export function buildProgram(options = {}) {
995
929
  configDigest: null,
996
930
  materializationDigest: null,
997
931
  outputDigest: null,
998
- errors: [{ code, message: `${code}: portable Skill 导出未执行。` }],
932
+ errors: [{
933
+ code,
934
+ message: capabilityError?.message ?? `${code}: portable Skill 导出未执行。`,
935
+ ...(capabilityError ? {
936
+ plugin: capabilityError.plugin,
937
+ missingCapabilities: capabilityError.missingCapabilities,
938
+ availableCapabilities: capabilityError.availableCapabilities,
939
+ } : {}),
940
+ }],
999
941
  });
1000
942
  commandExitState.exitCode = 1;
1001
943
  }
1002
944
  });
1003
- plugin
1004
- .command('init')
945
+ devPlugin
946
+ .command('create')
1005
947
  .description('Create a new deterministic plugin scaffold')
1006
948
  .addHelpText('after', [
1007
949
  '',
1008
950
  'During development, keep the current stable target when production content changes.',
1009
- 'Next, run `aw plugin validate`, `aw plugin test`, `aw plugin build`, and `aw catalog build`.',
1010
- 'Publish only as an explicit later step; inspect `aw catalog publish --help` first.',
951
+ 'Next, run `aw dev plugin validate`, `aw dev plugin test`, `aw dev plugin build`, and `aw dev catalog build`.',
952
+ 'Publish only as an explicit later step; inspect `aw dev catalog publish plan --help` first.',
1011
953
  '',
1012
954
  ].join('\n'))
1013
955
  .argument('<plugin-name>', 'lowercase hyphen-case plugin name')
@@ -1019,63 +961,64 @@ export function buildProgram(options = {}) {
1019
961
  .option('--skill-short-description <text>', 'initial Skill UI summary (25-64 characters)')
1020
962
  .option('--skill-invocation <mode>', 'model | manual | claude-model-only (default: model)')
1021
963
  .option('--version <semver>', 'initial stable plugin version (default: 0.1.0)')
1022
- .option('--min-version <semver>', 'compatibility.aw.minVersion')
1023
- .option('--catalog-min-version <semver>', 'target catalog compatibility minimum')
1024
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
964
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)')
1025
965
  .option('--no-skills', 'create the plugin without a skills directory')
1026
966
  .option('--with-mcp', 'add a minimal .mcp.json', false)
1027
967
  .option('--with-apps', 'add a minimal .app.json', false)
1028
968
  .option('--with-config-api', 'add AW config schema and helper', false)
1029
- .option('--with-lifecycle', 'add a lifecycle script sample', false);
1030
- plugin
1031
- .command('add-skill')
969
+ .option('--with-pre-apply', 'add an idempotent Node preApply environment check', false);
970
+ skill
971
+ .command('create')
1032
972
  .description('Add one static Skill scaffold to an existing plugin')
1033
973
  .addHelpText('after', [
1034
974
  '',
1035
975
  'During development, keep the current stable target when production content changes.',
1036
- 'Next, run `aw plugin validate`, `aw plugin test`, `aw plugin build`, and `aw catalog build`.',
1037
- 'Publish only as an explicit later step; inspect `aw catalog publish --help` first.',
976
+ 'Next, run `aw dev plugin validate`, `aw dev plugin test`, `aw dev plugin build`, and `aw dev catalog build`.',
977
+ 'Publish only as an explicit later step; inspect `aw dev catalog publish plan --help` first.',
1038
978
  '',
1039
979
  ].join('\n'))
1040
- .argument('<plugin-name>', 'existing lowercase hyphen-case plugin name')
980
+ .requiredOption('--plugin <name>', 'Plugin that owns the Skill')
1041
981
  .option('--skill-name <name>', 'new static Skill name (required)')
1042
982
  .option('--skill-description <text>', 'Skill goal and discovery description (required)')
1043
983
  .option('--skill-short-description <text>', 'Skill UI summary (25-64 characters)')
1044
984
  .option('--skill-invocation <mode>', 'model | manual | claude-model-only (default: model)')
1045
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)');
1046
- plugin
1047
- .command('remove')
1048
- .description('Remove one committed and unchanged canonical plugin source tree')
1049
- .argument('<plugin-name>', 'existing lowercase hyphen-case plugin name')
1050
- .requiredOption('--workspace-root <path>', 'Catalog Workspace root')
1051
- .option('--yes', 'confirm plugin source deletion', false)
1052
- .option('--json', 'emit one schema 1 JSON object', false);
1053
- plugin
985
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)');
986
+ devPlugin
1054
987
  .command('validate')
1055
988
  .description('Validate one source plugin directory')
1056
989
  .argument('<plugin-directory>', 'source plugin directory')
1057
- .option('--catalog-min-version <semver>', 'validate compatibility against a target catalog')
1058
990
  .option('--strict-agent-skills', 'allow only Agent Skills portable core frontmatter', false)
1059
991
  .option('--claude-skill-profile <profile>', 'minimum | current (default: minimum)')
1060
992
  .option('--version-base <git-ref>', 'production bundle comparison base (default: HEAD)')
1061
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
993
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from plugin directory)')
1062
994
  .option('--json', 'emit one machine-readable JSON result', false);
1063
- plugin
995
+ devPlugin
1064
996
  .command('test')
1065
997
  .description('Run deterministic Node tests declared by one source plugin')
1066
998
  .argument('<plugin-directory>', 'source plugin directory')
1067
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
999
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from plugin directory)')
1000
+ .option('--native-mode <mode>', 'fixture | installed | source-candidate (default: fixture)')
1001
+ .option('--native-context <path>', 'explicit tool context JSON for fixture or source-candidate mode')
1068
1002
  .option('--json', 'emit one machine-readable JSON result', false)
1069
1003
  .action(async (pluginDirectory, rawOptions) => {
1070
1004
  try {
1005
+ const workspace = await resolveCatalogWorkspaceRoot({
1006
+ cwd: path.resolve(cwd, pluginDirectory),
1007
+ ...(rawOptions.workspaceRoot === undefined ? {} : { explicitRoot: path.resolve(cwd, rawOptions.workspaceRoot) }),
1008
+ mode: 'existing',
1009
+ });
1071
1010
  commandExitState.exitCode = await runPluginTestCommand({
1072
- workspaceRoot: path.resolve(cwd, rawOptions.workspaceRoot ?? '.'),
1073
- pluginDirectory,
1011
+ ...workspace,
1012
+ pluginDirectory: path.resolve(cwd, pluginDirectory),
1013
+ nativeMode: rawOptions.nativeMode,
1014
+ nativeContext: rawOptions.nativeContext ? path.resolve(cwd, rawOptions.nativeContext) : undefined,
1074
1015
  json: rawOptions.json,
1075
1016
  io,
1076
1017
  });
1077
1018
  }
1078
1019
  catch (error) {
1020
+ if (error instanceof CatalogWorkspaceMissingError)
1021
+ throw error;
1079
1022
  const message = error instanceof Error ? error.message : String(error);
1080
1023
  if (rawOptions.json)
1081
1024
  writeJsonReceipt(io.stdout, { command: 'plugin:test', ok: false, errors: [{ message }] });
@@ -1083,19 +1026,24 @@ export function buildProgram(options = {}) {
1083
1026
  commandExitState.exitCode = 1;
1084
1027
  }
1085
1028
  });
1086
- plugin
1029
+ devPlugin
1087
1030
  .command('build')
1088
1031
  .description('Build and inspect one source plugin bundle')
1089
1032
  .argument('<plugin-directory>', 'source plugin directory')
1090
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
1033
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from plugin directory)')
1091
1034
  .option('--out <path>', 'output path inside the Catalog Workspace')
1092
1035
  .option('--force', 'replace an existing generated output', false)
1093
1036
  .option('--json', 'emit one machine-readable JSON result', false)
1094
1037
  .action(async (pluginDirectory, rawOptions) => {
1095
1038
  try {
1039
+ const workspace = await resolveCatalogWorkspaceRoot({
1040
+ cwd: path.resolve(cwd, pluginDirectory),
1041
+ ...(rawOptions.workspaceRoot === undefined ? {} : { explicitRoot: path.resolve(cwd, rawOptions.workspaceRoot) }),
1042
+ mode: 'existing',
1043
+ });
1096
1044
  await runPluginBuildCommand({
1097
- workspaceRoot: path.resolve(cwd, rawOptions.workspaceRoot ?? '.'),
1098
- pluginDirectory,
1045
+ ...workspace,
1046
+ pluginDirectory: path.resolve(cwd, pluginDirectory),
1099
1047
  out: rawOptions.out,
1100
1048
  force: rawOptions.force,
1101
1049
  json: rawOptions.json,
@@ -1103,6 +1051,8 @@ export function buildProgram(options = {}) {
1103
1051
  });
1104
1052
  }
1105
1053
  catch (error) {
1054
+ if (error instanceof CatalogWorkspaceMissingError)
1055
+ throw error;
1106
1056
  const message = error instanceof Error ? error.message : String(error);
1107
1057
  if (rawOptions.json)
1108
1058
  writeJsonReceipt(io.stdout, { command: 'plugin:build', ok: false, errors: [{ message }] });
@@ -1110,22 +1060,6 @@ export function buildProgram(options = {}) {
1110
1060
  commandExitState.exitCode = 1;
1111
1061
  }
1112
1062
  });
1113
- plugin
1114
- .command('status')
1115
- .description('Show current plugin status or compare against an explicit Git base')
1116
- .argument('[plugin-name]', 'one explicit plugin name')
1117
- .option('--all', 'check every current Catalog Workspace plugin', false)
1118
- .option('--base <git-ref>', 'explicit Git comparison base')
1119
- .option('--json', 'emit one schema v3 JSON document', false)
1120
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)');
1121
- plugin
1122
- .command('check-versions')
1123
- .description('Deprecated alias for plugin status')
1124
- .argument('[plugin-name]', 'one explicit plugin name')
1125
- .option('--all', 'check every plugin changed relative to the Git base', false)
1126
- .option('--base <git-ref>', 'explicit Git comparison base')
1127
- .option('--json', 'emit one schema v3 JSON document', false)
1128
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)');
1129
1063
  skill
1130
1064
  .command('validate')
1131
1065
  .description('Validate one Agent Skill directory')
@@ -1133,13 +1067,13 @@ export function buildProgram(options = {}) {
1133
1067
  .option('--frontmatter-profile <profile>', 'portable-agent-skills | claude-2.1.88 | claude-current (default: portable-agent-skills)')
1134
1068
  .option('--codex-metadata <policy>', 'required | optional | ignore (default: optional)')
1135
1069
  .option('--json', 'emit one machine-readable JSON result', false);
1136
- const catalog = program
1070
+ const catalog = dev
1137
1071
  .command('catalog')
1138
1072
  .description('Build and manage catalogs');
1139
1073
  catalog
1140
- .command('init')
1074
+ .command('create')
1141
1075
  .description('Initialize a local AW Catalog Workspace')
1142
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
1076
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor, then Git worktree root, then current directory)')
1143
1077
  .option('--owner-name <name>', 'catalog owner name')
1144
1078
  .option('--owner-url <url>', 'catalog owner URL')
1145
1079
  .option('--display-name <name>', 'catalog display name')
@@ -1148,9 +1082,15 @@ export function buildProgram(options = {}) {
1148
1082
  .option('--json', 'emit one machine-readable JSON result', false)
1149
1083
  .action(async (rawOptions) => {
1150
1084
  try {
1085
+ const workspace = await resolveCatalogWorkspaceRoot({
1086
+ cwd,
1087
+ ...(rawOptions.workspaceRoot === undefined ? {} : { explicitRoot: rawOptions.workspaceRoot }),
1088
+ mode: 'initialize',
1089
+ env,
1090
+ });
1151
1091
  await runCatalogInitCommand({
1152
1092
  ...rawOptions,
1153
- workspaceRoot: path.resolve(cwd, rawOptions.workspaceRoot ?? '.'),
1093
+ ...workspace,
1154
1094
  io,
1155
1095
  });
1156
1096
  }
@@ -1167,12 +1107,17 @@ export function buildProgram(options = {}) {
1167
1107
  .description('Read or set the Catalog version')
1168
1108
  .argument('[version]', 'stable or x.y.z-beta.N catalog version')
1169
1109
  .option('--bump <level>', 'bump the stable SemVer base: patch, minor, or major')
1170
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
1110
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)')
1171
1111
  .option('--json', 'emit one machine-readable JSON result', false)
1172
1112
  .action(async (version, rawOptions) => {
1173
1113
  try {
1114
+ const workspace = await resolveCatalogWorkspaceRoot({
1115
+ cwd,
1116
+ ...(rawOptions.workspaceRoot === undefined ? {} : { explicitRoot: rawOptions.workspaceRoot }),
1117
+ mode: 'existing',
1118
+ });
1174
1119
  await runCatalogVersionCommand({
1175
- workspaceRoot: path.resolve(cwd, rawOptions.workspaceRoot ?? '.'),
1120
+ ...workspace,
1176
1121
  version,
1177
1122
  bump: rawOptions.bump,
1178
1123
  json: rawOptions.json,
@@ -1180,6 +1125,8 @@ export function buildProgram(options = {}) {
1180
1125
  });
1181
1126
  }
1182
1127
  catch (error) {
1128
+ if (error instanceof CatalogWorkspaceMissingError)
1129
+ throw error;
1183
1130
  const message = error instanceof Error ? error.message : String(error);
1184
1131
  if (rawOptions.json)
1185
1132
  writeJsonReceipt(io.stdout, { command: 'catalog:version', ok: false, errors: [{ message }] });
@@ -1190,14 +1137,19 @@ export function buildProgram(options = {}) {
1190
1137
  catalog
1191
1138
  .command('build')
1192
1139
  .description('Build a deterministic development Catalog snapshot')
1193
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
1140
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)')
1194
1141
  .option('--out <path>', 'output path inside the Catalog Workspace')
1195
1142
  .option('--force', 'replace an existing generated output', false)
1196
1143
  .option('--json', 'emit one machine-readable JSON result', false)
1197
1144
  .action(async (rawOptions) => {
1198
1145
  try {
1146
+ const workspace = await resolveCatalogWorkspaceRoot({
1147
+ cwd,
1148
+ ...(rawOptions.workspaceRoot === undefined ? {} : { explicitRoot: rawOptions.workspaceRoot }),
1149
+ mode: 'existing',
1150
+ });
1199
1151
  await runCatalogBuildCommand({
1200
- workspaceRoot: path.resolve(cwd, rawOptions.workspaceRoot ?? '.'),
1152
+ ...workspace,
1201
1153
  out: rawOptions.out,
1202
1154
  force: rawOptions.force,
1203
1155
  json: rawOptions.json,
@@ -1205,6 +1157,8 @@ export function buildProgram(options = {}) {
1205
1157
  });
1206
1158
  }
1207
1159
  catch (error) {
1160
+ if (error instanceof CatalogWorkspaceMissingError)
1161
+ throw error;
1208
1162
  const message = error instanceof Error ? error.message : String(error);
1209
1163
  if (rawOptions.json)
1210
1164
  writeJsonReceipt(io.stdout, { command: 'catalog:build', ok: false, errors: [{ message }] });
@@ -1214,7 +1168,7 @@ export function buildProgram(options = {}) {
1214
1168
  });
1215
1169
  catalog
1216
1170
  .command('validate')
1217
- .description('Validate a schema 4 Catalog snapshot')
1171
+ .description('Validate a schema 7 Catalog snapshot')
1218
1172
  .argument('<snapshot-directory>', 'Catalog snapshot directory')
1219
1173
  .option('--json', 'emit one machine-readable JSON result', false)
1220
1174
  .action(async (snapshotDirectory, rawOptions) => {
@@ -1235,18 +1189,13 @@ export function buildProgram(options = {}) {
1235
1189
  });
1236
1190
  catalog
1237
1191
  .command('status')
1238
- .description('Inspect a Catalog Workspace; --preflight executes plugin validation and build code')
1239
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
1240
- .option('--remote <name>', 'configured Git remote name for preflight (default: origin)')
1241
- .option('--branch <name>', 'dedicated Catalog branch for preflight (default: catalog)')
1242
- .option('--preflight', 'run publication validation and temporary plugin builds (executes plugin code)', false)
1192
+ .description('Inspect static Catalog Workspace, snapshot, and Git facts')
1193
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)')
1243
1194
  .option('--json', 'emit one machine-readable JSON status object', false)
1244
1195
  .action(async (rawOptions) => {
1245
1196
  const receipt = await getCatalogStatus({
1246
- workspaceRoot: path.resolve(cwd, rawOptions.workspaceRoot ?? '.'),
1247
- remote: rawOptions.remote,
1248
- branch: rawOptions.branch,
1249
- preflight: rawOptions.preflight,
1197
+ cwd,
1198
+ workspaceRoot: rawOptions.workspaceRoot,
1250
1199
  env,
1251
1200
  });
1252
1201
  if (rawOptions.json)
@@ -1255,60 +1204,200 @@ export function buildProgram(options = {}) {
1255
1204
  io.stdout(renderCatalogStatus(receipt));
1256
1205
  commandExitState.exitCode = receipt.ok ? 0 : 1;
1257
1206
  });
1258
- catalog
1207
+ const catalogPublish = catalog
1259
1208
  .command('publish')
1260
- .description('Publish a versioned Catalog snapshot to a configured Git remote')
1261
- .option('--workspace-root <path>', 'Catalog Workspace root (default: current directory)')
1262
- .option('--remote <name>', 'configured Git remote name (default: origin)')
1209
+ .description('Plan or apply a versioned Catalog publication');
1210
+ catalogPublish
1211
+ .command('plan')
1212
+ .description('Prepare and inspect the exact Catalog publication plan')
1213
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)')
1214
+ .option('--remote <name>', 'Git remote (default: origin, otherwise sole remote; explicit if ambiguous)')
1263
1215
  .option('--branch <name>', 'dedicated Catalog branch (default: catalog)')
1264
- .option('--expected-descriptor-digest <digest>', 'required exact descriptor returned by publication preflight')
1265
- .option('-y, --yes', 'confirm publication without a prompt', false)
1266
1216
  .option('--json', 'emit one machine-readable JSON result', false)
1267
1217
  .action(async (rawOptions) => {
1268
1218
  try {
1269
- const context = createActionContext('catalog:publish', {});
1270
- const result = await runCatalogPublishCommand({
1271
- workspaceRoot: path.resolve(cwd, rawOptions.workspaceRoot ?? '.'),
1219
+ const result = await runCatalogPublishPlanCommand({
1220
+ cwd,
1221
+ workspaceRoot: rawOptions.workspaceRoot,
1272
1222
  remote: rawOptions.remote,
1273
1223
  branch: rawOptions.branch,
1274
- expectedDescriptorDigest: rawOptions.expectedDescriptorDigest,
1275
- yes: rawOptions.yes,
1276
- json: rawOptions.json,
1277
1224
  env,
1278
- interactive: context.interactive,
1279
- ...(context.prompt.confirm ? {
1280
- confirm: async (message) => {
1281
- const response = await context.prompt.confirm({ message, defaultValue: false });
1282
- return !response.cancelled && response.value === true;
1283
- },
1284
- } : {}),
1285
1225
  io,
1286
1226
  });
1287
- if (!result)
1288
- return;
1289
1227
  if (rawOptions.json)
1290
1228
  writeJsonReceipt(io.stdout, result);
1291
1229
  else {
1292
- writeLine(io.stdout, `Published Catalog ${result.catalogVersion} to ${result.remote} (${result.pushUrl}).`);
1230
+ writeLine(io.stdout, `Workspace identity: ${result.workspaceIdentity}`);
1231
+ writeLine(io.stdout, `Source HEAD: ${result.sourceHead}`);
1232
+ writeLine(io.stdout, `Remote identity: ${result.descriptor.remote.identityDigest}`);
1233
+ writeLine(io.stdout, `Remote: ${result.remote} (${result.remoteUrl})`);
1293
1234
  writeLine(io.stdout, `Branch: refs/heads/${result.branch}`);
1235
+ writeLine(io.stdout, `Parent: ${result.parent ?? '<root>'}`);
1294
1236
  writeLine(io.stdout, `Tag: refs/tags/${result.tag}`);
1295
- writeLine(io.stdout, `Commit: ${result.commit}`);
1296
- writeLine(io.stdout, `Add it as a source: aw catalog source add <id> --git ${result.fetchUrl} --ref refs/heads/${result.branch}`);
1237
+ writeLine(io.stdout, `Snapshot digest: ${result.snapshotDigest}`);
1238
+ writeLine(io.stdout, `Expected commit: ${result.expectedCommit}`);
1239
+ writeLine(io.stdout, `Plan digest: ${result.planDigest}`);
1297
1240
  }
1298
1241
  }
1299
1242
  catch (error) {
1300
- const message = error instanceof Error ? error.message : String(error);
1243
+ if (error instanceof CatalogWorkspaceMissingError)
1244
+ throw error;
1245
+ const failure = catalogPublicationFailure({
1246
+ error,
1247
+ env,
1248
+ sensitiveRoots: [
1249
+ cwd,
1250
+ ...(rawOptions.workspaceRoot ? [path.resolve(cwd, rawOptions.workspaceRoot)] : []),
1251
+ ],
1252
+ });
1301
1253
  if (rawOptions.json)
1302
- writeJsonReceipt(io.stdout, {
1303
- command: 'catalog:publish',
1304
- ok: false,
1305
- errors: [{ message }],
1306
- });
1307
- writeLine(io.stderr, message);
1254
+ writeJsonReceipt(io.stdout, failure);
1255
+ writeLine(io.stderr, failure.message);
1256
+ commandExitState.exitCode = 1;
1257
+ }
1258
+ });
1259
+ catalogPublish
1260
+ .command('apply')
1261
+ .description('Apply an authorized Catalog publication plan')
1262
+ .option('--workspace-root <path>', 'Catalog Workspace root (default: nearest ancestor from current directory)')
1263
+ .option('--remote <name>', 'Git remote (default: origin, otherwise sole remote; explicit if ambiguous)')
1264
+ .option('--branch <name>', 'dedicated Catalog branch (default: catalog)')
1265
+ .requiredOption('--expected-plan-digest <sha256>', 'exact plan digest returned by catalog publish plan')
1266
+ .option('-y, --yes', 'confirm publication without a prompt', false)
1267
+ .option('--json', 'emit one machine-readable JSON result', false)
1268
+ .action(async (rawOptions) => {
1269
+ try {
1270
+ const context = createActionContext('catalog:publish:apply', {});
1271
+ const result = await runCatalogPublishApplyCommand({
1272
+ cwd,
1273
+ workspaceRoot: rawOptions.workspaceRoot,
1274
+ remote: rawOptions.remote,
1275
+ branch: rawOptions.branch,
1276
+ expectedPlanDigest: rawOptions.expectedPlanDigest,
1277
+ yes: rawOptions.yes,
1278
+ json: rawOptions.json,
1279
+ env,
1280
+ interactive: context.interactive,
1281
+ ...(context.prompt.confirm ? {
1282
+ confirm: async (message) => {
1283
+ const response = await context.prompt.confirm({ message, defaultValue: false });
1284
+ return !response.cancelled && response.value === true;
1285
+ },
1286
+ } : {}),
1287
+ io,
1288
+ });
1289
+ if (!result)
1290
+ return;
1291
+ if (rawOptions.json)
1292
+ writeJsonReceipt(io.stdout, result);
1293
+ else {
1294
+ writeLine(io.stdout, `Published Catalog ${result.catalogVersion} to ${result.remote} (${result.pushUrl}).`);
1295
+ writeLine(io.stdout, `Branch: refs/heads/${result.branch}`);
1296
+ writeLine(io.stdout, `Tag: refs/tags/${result.tag}`);
1297
+ writeLine(io.stdout, `Commit: ${result.commit}`);
1298
+ writeLine(io.stdout, `Add it as a source: aw source add <id> --git ${result.fetchUrl} --ref refs/heads/${result.branch}`);
1299
+ }
1300
+ }
1301
+ catch (error) {
1302
+ if (error instanceof CatalogWorkspaceMissingError)
1303
+ throw error;
1304
+ const failure = catalogPublicationFailure({
1305
+ error,
1306
+ env,
1307
+ sensitiveRoots: [
1308
+ cwd,
1309
+ ...(rawOptions.workspaceRoot ? [path.resolve(cwd, rawOptions.workspaceRoot)] : []),
1310
+ ],
1311
+ });
1312
+ if (rawOptions.json)
1313
+ writeJsonReceipt(io.stdout, { ...failure, ...(error instanceof CatalogPublicationApplyFailure ? { overallState: 'partial', ...error.outcome } : {}) });
1314
+ writeLine(io.stderr, failure.message);
1315
+ commandExitState.exitCode = 1;
1316
+ }
1317
+ });
1318
+ const catalogDev = dev
1319
+ .command('source')
1320
+ .description('Manage the current Catalog Workspace development source');
1321
+ catalogDev
1322
+ .command('activate')
1323
+ .option('--workspace-root <path>', 'explicit Catalog Workspace root')
1324
+ .option('--source-id <id>', 'explicit managed source ID')
1325
+ .option('--primary', 'make the development source primary', false)
1326
+ .option('--force-build', 'rebuild a current snapshot', false)
1327
+ .option('-y, --yes', 'confirm affected or unknown source references', false)
1328
+ .requiredOption('--json', 'emit one schema 2 JSON receipt')
1329
+ .action(async (rawOptions) => {
1330
+ try {
1331
+ const receipt = await activateCatalogDevSource({
1332
+ cwd,
1333
+ workspaceRoot: rawOptions.workspaceRoot,
1334
+ sourceId: rawOptions.sourceId,
1335
+ primary: rawOptions.primary,
1336
+ forceBuild: rawOptions.forceBuild,
1337
+ yes: rawOptions.yes,
1338
+ cliVersion: resolveCliVersion(),
1339
+ env,
1340
+ });
1341
+ writeJsonReceipt(io.stdout, receipt);
1342
+ commandExitState.exitCode = receipt.ok ? 0 : 1;
1343
+ }
1344
+ catch (error) {
1345
+ if (error instanceof CatalogWorkspaceMissingError)
1346
+ throw error;
1347
+ const failure = catalogDevSourceError(error);
1348
+ writeJsonReceipt(io.stdout, createCatalogDevFailureReceipt({
1349
+ command: 'activate', cwd, workspaceRoot: rawOptions.workspaceRoot,
1350
+ sourceId: rawOptions.sourceId, ...failure,
1351
+ }));
1352
+ commandExitState.exitCode = 1;
1353
+ }
1354
+ });
1355
+ catalogDev
1356
+ .command('status')
1357
+ .option('--workspace-root <path>', 'explicit Catalog Workspace root')
1358
+ .requiredOption('--json', 'emit one schema 4 JSON receipt')
1359
+ .action(async (rawOptions) => {
1360
+ const receipt = await getCatalogDevSourceStatus({
1361
+ cwd,
1362
+ workspaceRoot: rawOptions.workspaceRoot,
1363
+ cliVersion: resolveCliVersion(),
1364
+ env,
1365
+ });
1366
+ writeJsonReceipt(io.stdout, receipt);
1367
+ commandExitState.exitCode = receipt.ok ? 0 : 1;
1368
+ });
1369
+ catalogDev
1370
+ .command('deactivate')
1371
+ .option('--workspace-root <path>', 'explicit Catalog Workspace root')
1372
+ .option('--source-id <id>', 'recover one managed source by exact ID')
1373
+ .option('--replacement-primary <id>', 'replacement when the target source is primary')
1374
+ .option('-y, --yes', 'confirm source impact or recovery by source ID', false)
1375
+ .requiredOption('--json', 'emit one schema 4 JSON receipt')
1376
+ .action(async (rawOptions) => {
1377
+ try {
1378
+ const receipt = await deactivateCatalogDevSource({
1379
+ cwd,
1380
+ workspaceRoot: rawOptions.workspaceRoot,
1381
+ sourceId: rawOptions.sourceId,
1382
+ replacementPrimary: rawOptions.replacementPrimary,
1383
+ yes: rawOptions.yes,
1384
+ env,
1385
+ });
1386
+ writeJsonReceipt(io.stdout, receipt);
1387
+ commandExitState.exitCode = receipt.ok ? 0 : 1;
1388
+ }
1389
+ catch (error) {
1390
+ if (error instanceof CatalogWorkspaceMissingError)
1391
+ throw error;
1392
+ const failure = catalogDevSourceError(error);
1393
+ writeJsonReceipt(io.stdout, createCatalogDevFailureReceipt({
1394
+ command: 'deactivate', cwd, workspaceRoot: rawOptions.workspaceRoot,
1395
+ sourceId: rawOptions.sourceId, ...failure,
1396
+ }));
1308
1397
  commandExitState.exitCode = 1;
1309
1398
  }
1310
1399
  });
1311
- const catalogSource = catalog
1400
+ const catalogSource = program
1312
1401
  .command('source')
1313
1402
  .description('Manage catalog sources');
1314
1403
  const writeCatalogSourceFailure = async (command, sourceId, json, error, sensitiveRoots = []) => {
@@ -1316,64 +1405,138 @@ export function buildProgram(options = {}) {
1316
1405
  const message = failure instanceof Error ? failure.message : String(error);
1317
1406
  if (json) {
1318
1407
  writeJsonReceipt(io.stdout, {
1319
- receiptSchemaVersion: 4,
1408
+ receiptSchemaVersion: 6,
1320
1409
  command,
1321
1410
  ok: false,
1322
1411
  changed: false,
1323
1412
  sourceId,
1324
- references: failure.inventory?.references ?? [],
1413
+ primaryChange: failure.impact?.primaryChange ?? null,
1414
+ references: failure.impact?.references ?? failure.inventory?.references ?? [],
1415
+ impact: failure.impact ?? failure.inventory ?? null,
1325
1416
  errors: [{ code: failure.code ?? failure.name ?? 'catalogSourceMutationFailed', message }],
1326
1417
  });
1327
1418
  }
1328
1419
  writeLine(io.stderr, message);
1329
1420
  commandExitState.exitCode = 1;
1330
1421
  };
1331
- const writeConfigMutationFailure = (command, plugin, json, error) => {
1332
- const message = error instanceof Error ? error.message : String(error);
1333
- const code = message.includes('legacyStateUnsupported')
1334
- ? 'legacyStateUnsupported'
1335
- : message.includes('sourceChanged')
1336
- ? 'sourceChanged'
1337
- : message.includes('sourceMissing')
1338
- ? 'sourceMissing'
1339
- : message.startsWith('Cannot resolve required catalog sources:')
1340
- ? 'catalogSourceUnavailable'
1341
- : message.split(':', 1)[0] || 'configMutationFailed';
1342
- if (json && !message.includes('Usage:')) {
1422
+ const writeCatalogGenerationFailure = (command, sourceId, json, error) => {
1423
+ const failure = sanitizeCatalogSourceError(error, env);
1424
+ const message = redactString(failure.message);
1425
+ if (json) {
1343
1426
  writeJsonReceipt(io.stdout, {
1344
- receiptSchemaVersion: 4,
1427
+ ...(command === 'catalog:source:sync'
1428
+ ? { catalogGenerationSchemaVersion: 1 }
1429
+ : { catalogGenerationStatusSchemaVersion: 2 }),
1345
1430
  command,
1346
1431
  ok: false,
1347
- overallState: 'failed',
1348
- ...(plugin ? { plugin } : {}),
1349
- errors: [{ code, message }],
1432
+ ...(sourceId ? { sourceId } : {}),
1433
+ ...(failure.impact ? { impact: failure.impact } : {}),
1434
+ errors: [{ code: catalogGenerationErrorCode(error), message }],
1350
1435
  });
1351
1436
  }
1352
1437
  writeLine(io.stderr, message);
1353
1438
  commandExitState.exitCode = 1;
1354
1439
  };
1355
- const withResolvedConfigMutationPlugin = (context, selector, consume) => withAwHomeMutationLock({
1356
- env: context.env,
1357
- action: (awHomeMutationToken) => withResolvedCatalogPlugin({
1358
- selector,
1359
- cliVersion: resolveCliVersion(),
1360
- freshnessPolicy: 'requireRemote',
1440
+ const writeConfigMutationFailure = (command, plugin, json, error) => {
1441
+ const failure = configMutationFailure(error, env, cwd);
1442
+ const confirmation = error?.confirmation;
1443
+ if (confirmation) {
1444
+ writeJsonReceipt(io.stdout, { command, ok: false, pluginId: plugin, configWrite: 'notStarted', confirmation, errors: [failure] });
1445
+ commandExitState.exitCode = 3;
1446
+ return;
1447
+ }
1448
+ if (json) {
1449
+ writeConfigMutationFailureReceipt(io.stdout, {
1450
+ command,
1451
+ ...(plugin ? { plugin } : {}),
1452
+ }, failure);
1453
+ }
1454
+ const message = json
1455
+ ? failure.message
1456
+ : redactString(sanitizeCatalogSourceErrorMessage(error instanceof Error ? error.message : String(error), env, [cwd]));
1457
+ writeLine(io.stderr, message);
1458
+ commandExitState.exitCode = failure.code === 'invalidArguments' ? 2 : 1;
1459
+ };
1460
+ const withResolvedConfigMutationPlugin = (context, selector, consume, _apply = false) => (async () => {
1461
+ const parsed = parsePluginId(selector);
1462
+ return withAwHomeMutationLock({
1361
1463
  env: context.env,
1362
- consume: (resolution) => consume(resolution, awHomeMutationToken),
1363
- }),
1464
+ action: async (awHomeMutationToken) => {
1465
+ const catalogOperationContext = await resolveCatalogOperationContext({
1466
+ ...(parsed.sourceId ? { sourceIds: [parsed.sourceId] } : {}),
1467
+ env: context.env,
1468
+ });
1469
+ return withResolvedCatalogPlugin({
1470
+ selector,
1471
+ cliVersion: resolveCliVersion(),
1472
+ operationContext: catalogOperationContext,
1473
+ env: context.env,
1474
+ consume: (resolution) => consume(resolution, awHomeMutationToken, catalogOperationContext),
1475
+ });
1476
+ },
1477
+ });
1478
+ })();
1479
+ catalogSource
1480
+ .command('sync')
1481
+ .argument('<id>')
1482
+ .option('--replace-damaged', 'replace a damaged Active entry with the current candidate', false)
1483
+ .option('-y, --yes', 'confirm affected, unknown, or damaged Active replacement impact', false)
1484
+ .option('-j, --json', 'print the source sync result as JSON', false)
1485
+ .action(async (id, rawOptions) => {
1486
+ try {
1487
+ if (rawOptions.check && rawOptions.replaceDamaged) {
1488
+ throw new Error('catalog source sync --check cannot use --replace-damaged.');
1489
+ }
1490
+ const result = await syncCatalogSourceCommand({
1491
+ sourceId: id,
1492
+ cliVersion: resolveCliVersion(),
1493
+ cwd,
1494
+ check: rawOptions.check === true,
1495
+ impactConfirmed: rawOptions.yes === true,
1496
+ replaceDamaged: rawOptions.replaceDamaged === true,
1497
+ env,
1498
+ });
1499
+ if (rawOptions.json) {
1500
+ writeJsonReceipt(io.stdout, {
1501
+ ...result,
1502
+ command: 'catalog:source:sync',
1503
+ ok: true,
1504
+ });
1505
+ }
1506
+ else {
1507
+ writeLine(io.stdout, rawOptions.check
1508
+ ? `Catalog source ${id} is valid.`
1509
+ : `Catalog source ${id}: ${result.outcome}.`);
1510
+ }
1511
+ }
1512
+ catch (error) {
1513
+ writeCatalogGenerationFailure('catalog:source:sync', id, rawOptions.json === true, error);
1514
+ }
1364
1515
  });
1365
1516
  catalogSource
1366
- .command('list')
1367
- .option('-j, --json', 'print catalog sources as JSON', false)
1368
- .action(async (rawOptions) => {
1369
- const payload = await listCatalogSources({ env });
1370
- if (rawOptions.json) {
1371
- writeJsonReceipt(io.stdout, payload);
1372
- return;
1517
+ .command('status')
1518
+ .argument('[id]')
1519
+ .option('-j, --json', 'print offline Catalog source status schema 2 as JSON', false)
1520
+ .action(async (id, rawOptions) => {
1521
+ try {
1522
+ const result = await catalogSourceStatusCommand({ sourceId: id, env });
1523
+ if (rawOptions.json) {
1524
+ writeJsonReceipt(io.stdout, result);
1525
+ }
1526
+ else {
1527
+ for (const source of result.sources) {
1528
+ const active = source.active
1529
+ ? `Active ${source.active.snapshotDigest}`
1530
+ : 'no Active';
1531
+ const readiness = source.compatibility?.state === 'unsupported'
1532
+ ? `incompatible (required: ${source.compatibility.requiredCapabilities.join(', ')}; missing: ${source.compatibility.missingCapabilities.join(', ')})`
1533
+ : source.activeReady ? 'ready' : 'not ready';
1534
+ writeLine(io.stdout, `${source.sourceId}: ${active}, ${readiness}`);
1535
+ }
1536
+ }
1373
1537
  }
1374
- writeLine(io.stdout, `Primary source: ${payload.primarySourceId}`);
1375
- for (const source of payload.sources) {
1376
- writeLine(io.stdout, `${source.primary ? '*' : '-'} ${source.id} ${source.type} ${source.sourceIdentity}`);
1538
+ catch (error) {
1539
+ writeCatalogGenerationFailure('catalog:source:status', id, rawOptions.json === true, error);
1377
1540
  }
1378
1541
  });
1379
1542
  catalogSource
@@ -1384,18 +1547,20 @@ export function buildProgram(options = {}) {
1384
1547
  .addOption(new Option('--ref <ref>', 'use an explicit Git ref'))
1385
1548
  .addOption(new Option('--default-ref', 'select the Git ref from the CLI release channel'))
1386
1549
  .option('--subdir <path>', 'use a catalog snapshot below the Git repository root')
1550
+ .option('--no-auto-check', 'disable automatic update checks for this source')
1387
1551
  .option('--primary', 'make this source primary', false)
1552
+ .option('-y, --yes', 'confirm affected or unknown primary source references', false)
1388
1553
  .option('-j, --json', 'print mutation receipt as JSON', false)
1389
1554
  .action(async (id, rawOptions) => {
1390
1555
  try {
1391
1556
  if ((rawOptions.git === undefined) === (rawOptions.path === undefined)) {
1392
- throw new Error('catalog source add requires exactly one of `--git` or `--path`.');
1557
+ throw new WriteCommandRequestError('catalog source add requires exactly one of `--git` or `--path`.');
1393
1558
  }
1394
1559
  if (rawOptions.git !== undefined && ((rawOptions.ref === undefined) === (rawOptions.defaultRef !== true))) {
1395
- throw new Error('Git catalog source add requires exactly one of `--ref` or `--default-ref`.');
1560
+ throw new WriteCommandRequestError('Git catalog source add requires exactly one of `--ref` or `--default-ref`.');
1396
1561
  }
1397
1562
  if (rawOptions.path !== undefined && (rawOptions.ref !== undefined || rawOptions.defaultRef === true || rawOptions.subdir !== undefined)) {
1398
- throw new Error('Path catalog source add only accepts `--path` and `--primary`.');
1563
+ throw new WriteCommandRequestError('Path catalog source add only accepts `--path`, `--primary`, `--no-auto-check`, and `--yes`.');
1399
1564
  }
1400
1565
  const source = rawOptions.git !== undefined
1401
1566
  ? {
@@ -1405,21 +1570,35 @@ export function buildProgram(options = {}) {
1405
1570
  url: rawOptions.git,
1406
1571
  refPolicy: explicitRefPolicy(rawOptions.ref, rawOptions.defaultRef === true),
1407
1572
  ...(rawOptions.subdir ? { subdir: rawOptions.subdir } : {}),
1573
+ ...(rawOptions.autoCheck === false ? { autoCheck: false } : {}),
1408
1574
  }
1409
1575
  : {
1410
1576
  id,
1411
1577
  type: 'path',
1412
1578
  primary: rawOptions.primary === true,
1413
1579
  path: rawOptions.path,
1580
+ ...(rawOptions.autoCheck === false ? { autoCheck: false } : {}),
1414
1581
  };
1582
+ const preview = source.primary
1583
+ ? await preflightCatalogSourceMutation({
1584
+ request: { action: 'add', source }, cwd, env,
1585
+ })
1586
+ : undefined;
1415
1587
  const receipt = await addCatalogSourceCommand({
1416
1588
  source,
1417
1589
  cliVersion: resolveCliVersion(),
1418
1590
  cwd,
1419
1591
  env,
1592
+ ...(preview ? {
1593
+ expectedConfigDigest: preview.configDigest,
1594
+ expectedProposedConfigDigest: preview.proposedConfigDigest,
1595
+ expectedImpactDigest: preview.impactDigest,
1596
+ } : {}),
1597
+ requireImpactConfirmation: true,
1598
+ confirmImpact: rawOptions.yes === true,
1420
1599
  });
1421
1600
  if (rawOptions.json)
1422
- writeJsonReceipt(io.stdout, receipt);
1601
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview?.references ?? null, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
1423
1602
  else
1424
1603
  writeLine(io.stdout, `Catalog source ${id} added.`);
1425
1604
  for (const diagnostic of receipt.errors)
@@ -1438,28 +1617,41 @@ export function buildProgram(options = {}) {
1438
1617
  .addOption(new Option('--default-ref', 'select the Git ref from the CLI release channel'))
1439
1618
  .addOption(new Option('--subdir <path>', 'update the Git catalog subdirectory'))
1440
1619
  .addOption(new Option('--no-subdir', 'remove the Git catalog subdirectory'))
1620
+ .addOption(new Option('--auto-check', 'enable automatic update checks for this source'))
1621
+ .addOption(new Option('--no-auto-check', 'disable automatic update checks for this source'))
1622
+ .option('-y, --yes', 'confirm a source identity change', false)
1441
1623
  .option('-j, --json', 'print mutation receipt as JSON', false)
1442
1624
  .action(async (id, rawOptions) => {
1443
1625
  try {
1444
1626
  if (rawOptions.git !== undefined && rawOptions.path !== undefined) {
1445
- throw new Error('catalog source update cannot combine `--git` and `--path`.');
1627
+ throw new WriteCommandRequestError('catalog source update cannot combine `--git` and `--path`.');
1446
1628
  }
1447
1629
  if (rawOptions.ref !== undefined && rawOptions.defaultRef === true) {
1448
- throw new Error('catalog source update cannot combine `--ref` and `--default-ref`.');
1630
+ throw new WriteCommandRequestError('catalog source update cannot combine `--ref` and `--default-ref`.');
1449
1631
  }
1450
- const hasUpdate = rawOptions.git !== undefined
1632
+ const hasUpdate = rawOptions.primary === true || rawOptions.git !== undefined
1451
1633
  || rawOptions.path !== undefined
1452
1634
  || rawOptions.ref !== undefined
1453
1635
  || rawOptions.defaultRef === true
1454
- || rawOptions.subdir !== undefined;
1636
+ || rawOptions.subdir !== undefined
1637
+ || rawOptions.autoCheck !== undefined;
1455
1638
  if (!hasUpdate)
1456
- throw new Error('catalog source update requires at least one update option.');
1639
+ throw new WriteCommandRequestError('catalog source update requires at least one update option.');
1457
1640
  if (rawOptions.path !== undefined && (rawOptions.ref !== undefined || rawOptions.defaultRef === true || rawOptions.subdir !== undefined))
1458
- throw new Error('Path catalog source update only accepts `--path`.');
1459
- const update = rawOptions.path !== undefined
1460
- ? { type: 'path', path: rawOptions.path }
1461
- : {
1641
+ throw new WriteCommandRequestError('Path catalog source update only accepts `--path` and auto-check options.');
1642
+ const hasGitUpdate = rawOptions.git !== undefined
1643
+ || rawOptions.ref !== undefined
1644
+ || rawOptions.defaultRef === true
1645
+ || rawOptions.subdir !== undefined;
1646
+ const transportUpdate = rawOptions.path !== undefined
1647
+ ? {
1648
+ type: 'path',
1649
+ path: rawOptions.path,
1650
+ ...(rawOptions.autoCheck !== undefined ? { autoCheck: rawOptions.autoCheck } : {}),
1651
+ }
1652
+ : hasGitUpdate ? {
1462
1653
  type: 'git',
1654
+ ...(rawOptions.autoCheck !== undefined ? { autoCheck: rawOptions.autoCheck } : {}),
1463
1655
  ...(rawOptions.git !== undefined ? { url: rawOptions.git } : {}),
1464
1656
  ...(rawOptions.ref !== undefined || rawOptions.defaultRef === true
1465
1657
  ? { refPolicy: explicitRefPolicy(rawOptions.ref, rawOptions.defaultRef === true) }
@@ -1467,16 +1659,29 @@ export function buildProgram(options = {}) {
1467
1659
  ...(rawOptions.subdir !== undefined
1468
1660
  ? { subdir: rawOptions.subdir === false ? null : rawOptions.subdir }
1469
1661
  : {}),
1470
- };
1662
+ }
1663
+ : { autoCheck: rawOptions.autoCheck };
1664
+ const update = transportUpdate;
1665
+ const preview = await preflightCatalogSourceMutation({
1666
+ request: { action: 'update', sourceId: id, update, ...(rawOptions.primary ? { primary: true } : {}) }, cwd, env,
1667
+ });
1471
1668
  const receipt = await updateCatalogSourceCommand({
1472
1669
  sourceId: id,
1473
1670
  update,
1671
+ ...(rawOptions.primary ? { primary: true } : {}),
1672
+ requireImpactConfirmation: true,
1673
+ confirmImpact: rawOptions.yes === true,
1474
1674
  cliVersion: resolveCliVersion(),
1475
1675
  cwd,
1476
1676
  env,
1677
+ expectedConfigDigest: preview.configDigest,
1678
+ expectedProposedConfigDigest: preview.proposedConfigDigest,
1679
+ expectedImpactDigest: preview.impactDigest,
1680
+ requireIdentityChangeConfirmation: true,
1681
+ confirmIdentityChange: rawOptions.yes === true,
1477
1682
  });
1478
1683
  if (rawOptions.json)
1479
- writeJsonReceipt(io.stdout, receipt);
1684
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview.references, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
1480
1685
  else
1481
1686
  writeLine(io.stdout, `Catalog source ${id} updated.`);
1482
1687
  for (const diagnostic of receipt.errors)
@@ -1486,31 +1691,23 @@ export function buildProgram(options = {}) {
1486
1691
  await writeCatalogSourceFailure('catalog:source:update', id, rawOptions.json === true, error, rawOptions.path === undefined ? [] : [rawOptions.path, path.resolve(cwd, rawOptions.path)]);
1487
1692
  }
1488
1693
  });
1489
- catalogSource
1490
- .command('set-primary')
1491
- .argument('<id>')
1492
- .option('-j, --json', 'print mutation receipt as JSON', false)
1493
- .action(async (id, rawOptions) => {
1494
- try {
1495
- const receipt = await setPrimaryCatalogSourceCommand({ sourceId: id, cwd, env });
1496
- if (rawOptions.json)
1497
- writeJsonReceipt(io.stdout, receipt);
1498
- else
1499
- writeLine(io.stdout, `Primary catalog source set to ${id}.`);
1500
- }
1501
- catch (error) {
1502
- await writeCatalogSourceFailure('catalog:source:set-primary', id, rawOptions.json === true, error);
1503
- }
1504
- });
1505
1694
  catalogSource
1506
1695
  .command('remove')
1507
1696
  .argument('<id>')
1697
+ .option('-y, --yes', 'confirm affected or unknown source references', false)
1508
1698
  .option('-j, --json', 'print mutation receipt as JSON', false)
1509
1699
  .action(async (id, rawOptions) => {
1510
1700
  try {
1511
- const receipt = await removeCatalogSourceCommand({ sourceId: id, cwd, env });
1701
+ const preview = await preflightCatalogSourceMutation({ request: { action: 'remove', sourceId: id }, cwd, env });
1702
+ const receipt = await removeCatalogSourceCommand({
1703
+ sourceId: id,
1704
+ cwd,
1705
+ env,
1706
+ requireImpactConfirmation: true,
1707
+ confirmImpact: rawOptions.yes === true,
1708
+ });
1512
1709
  if (rawOptions.json)
1513
- writeJsonReceipt(io.stdout, receipt);
1710
+ writeJsonReceipt(io.stdout, { ...receipt, impact: preview.references, confirmation: sourceConfirmation(id, rawOptions.yes, preview) });
1514
1711
  else
1515
1712
  writeLine(io.stdout, `Catalog source ${id} removed.`);
1516
1713
  }
@@ -1518,876 +1715,964 @@ export function buildProgram(options = {}) {
1518
1715
  await writeCatalogSourceFailure('catalog:source:remove', id, rawOptions.json === true, error);
1519
1716
  }
1520
1717
  });
1521
- program
1522
- .command('init')
1523
- .option('-f, --force', 're-fetch and rebuild the current catalog cache entry', false)
1524
- .option('-j, --json', 'print receipt as JSON', false)
1525
- .option('-v, --verbose', 'show command diagnostics', false)
1526
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1527
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1718
+ const catalogStore = program
1719
+ .command('cache')
1720
+ .description('Inspect or prune the immutable Catalog store');
1721
+ catalogStore
1722
+ .command('status')
1723
+ .option('-j, --json', 'print Catalog store status as JSON', false)
1528
1724
  .action(async (rawOptions) => {
1529
- const context = createActionContext('init', rawOptions);
1530
- const result = await runActionWithContext(context, () => initCommand({
1531
- force: rawOptions.force,
1532
- cliVersion: resolveCliVersion(),
1533
- env: context.env,
1534
- }));
1535
- if (rawOptions.json) {
1536
- writeJsonReceipt(io.stdout, buildInitReceiptJson(result));
1537
- }
1538
- else {
1539
- for (const line of renderInitReceipt(result)) {
1540
- writeLine(io.stdout, line);
1725
+ try {
1726
+ const result = await catalogStoreStatus({ env });
1727
+ if (rawOptions.json) {
1728
+ writeJsonReceipt(io.stdout, result);
1729
+ }
1730
+ else if (result.entries.length === 0) {
1731
+ writeLine(io.stdout, 'Catalog store is empty.');
1732
+ }
1733
+ else {
1734
+ for (const entry of result.entries) {
1735
+ const bytes = entry.reclaimableBytes === null ? 'unknown bytes' : `${entry.reclaimableBytes} bytes`;
1736
+ writeLine(io.stdout, `${entry.storeKey}: ${entry.category}, ${entry.status}, ${entry.reason}, ${bytes}`);
1737
+ }
1738
+ writeLine(io.stdout, `Reclaimable: ${result.totals.reclaimableEntries} item(s).`);
1739
+ if (result.errors.length > 0) {
1740
+ writeLine(io.stderr, `${result.errors.length} item(s) could not be fully inspected and were retained.`);
1741
+ }
1541
1742
  }
1743
+ commandExitState.exitCode = result.ok ? 0 : 1;
1542
1744
  }
1543
- writeWarnings(io.stderr, result.warnings, { actionableOnly: true });
1544
- for (const source of result.sources) {
1545
- if (!source.ok && source.error)
1546
- writeLine(io.stderr, `${source.id}: ${source.error}`);
1745
+ catch (error) {
1746
+ const failure = sanitizeCatalogSourceError(error, env);
1747
+ const message = redactString(failure.message);
1748
+ if (rawOptions.json)
1749
+ writeJsonReceipt(io.stdout, {
1750
+ catalogStoreSchemaVersion: 2,
1751
+ command: 'catalog:store:status',
1752
+ ok: false,
1753
+ entries: [],
1754
+ errors: [{ code: catalogStoreErrorCode(error), message }],
1755
+ });
1756
+ writeLine(io.stderr, message);
1757
+ commandExitState.exitCode = 1;
1547
1758
  }
1548
- commandExitState.exitCode = result.ok ? 0 : 1;
1549
1759
  });
1550
- program
1551
- .command('install')
1552
- .argument('[plugins...]')
1553
- .option('-s, --scope <scope>', 'project or user')
1554
- .option('-p, --platform <platform>', 'codex | claude | both')
1555
- .option('--script-timeout <ms>', 'override plugin lifecycle script timeout in milliseconds')
1556
- .option('-j, --json', 'print receipt as JSON', false)
1557
- .option('-v, --verbose', 'show command diagnostics', false)
1558
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1559
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1560
- .action(async (plugins, rawOptions) => {
1561
- const context = createActionContext('install', rawOptions);
1562
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('install', plugins ?? [], rawOptions, context));
1563
- if (outcome.cancelled)
1564
- return;
1565
- const receipt = outcome.result;
1566
- if (rawOptions.json) {
1567
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('install', receipt));
1568
- }
1569
- else {
1570
- for (const line of renderRebuildReceipt('install', receipt)) {
1571
- writeLine(io.stdout, line);
1760
+ catalogStore
1761
+ .command('prune')
1762
+ .option('--dry-run', 'inspect reclaimable items without deleting them', false)
1763
+ .option('-y, --yes', 'delete items classified as safely reclaimable', false)
1764
+ .option('-j, --json', 'print the prune receipt as JSON', false)
1765
+ .action(async (rawOptions) => {
1766
+ const dryRun = rawOptions.yes !== true;
1767
+ try {
1768
+ if (rawOptions.dryRun === true && rawOptions.yes === true) {
1769
+ throw Object.assign(new Error('catalog store prune cannot combine `--dry-run` and `--yes`.'), {
1770
+ code: 'invalidArguments',
1771
+ });
1572
1772
  }
1573
- }
1574
- writeWarnings(io.stderr, receipt.warnings, { actionableOnly: true });
1575
- commandExitState.exitCode = resolveCommandReceiptExitCode(receipt);
1576
- });
1577
- program
1578
- .command('uninstall')
1579
- .argument('[plugins...]')
1580
- .option('-s, --scope <scope>', 'project or user')
1581
- .option('-p, --platform <platform>', 'codex | claude | both')
1582
- .option('--script-timeout <ms>', 'override plugin lifecycle script timeout in milliseconds')
1583
- .option('-j, --json', 'print receipt as JSON', false)
1584
- .option('-v, --verbose', 'show command diagnostics', false)
1585
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1586
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1587
- .action(async (plugins, rawOptions) => {
1588
- const context = createActionContext('uninstall', rawOptions);
1589
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('uninstall', plugins ?? [], rawOptions, context));
1590
- if (outcome.cancelled)
1591
- return;
1592
- const receipt = outcome.result;
1593
- if (rawOptions.json) {
1594
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('uninstall', receipt));
1595
- }
1596
- else {
1597
- for (const line of renderRebuildReceipt('uninstall', receipt)) {
1598
- writeLine(io.stdout, line);
1773
+ const result = await catalogStorePrune({ dryRun, env });
1774
+ if (rawOptions.json) {
1775
+ writeJsonReceipt(io.stdout, result);
1599
1776
  }
1600
- }
1601
- writeWarnings(io.stderr, receipt.warnings, { actionableOnly: true });
1602
- commandExitState.exitCode = resolveCommandReceiptExitCode(receipt);
1603
- });
1604
- program
1605
- .command('upgrade')
1606
- .argument('[plugins...]')
1607
- .option('-a, --all', 'upgrade all plugins', false)
1608
- .option('-s, --scope <scope>', 'project or user')
1609
- .option('-p, --platform <platform>', 'codex | claude | both')
1610
- .option('--script-timeout <ms>', 'override plugin lifecycle script timeout in milliseconds')
1611
- .option('-j, --json', 'print receipt as JSON', false)
1612
- .option('-v, --verbose', 'show command diagnostics', false)
1613
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1614
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1615
- .action(async (plugins, rawOptions) => {
1616
- const context = createActionContext('upgrade', rawOptions);
1617
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('upgrade', plugins ?? [], rawOptions, context));
1618
- if (outcome.cancelled)
1619
- return;
1620
- const receipt = outcome.result;
1621
- if (rawOptions.json) {
1622
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('upgrade', receipt));
1623
- }
1624
- else {
1625
- for (const line of renderRebuildReceipt('upgrade', receipt)) {
1626
- writeLine(io.stdout, line);
1777
+ else if (dryRun) {
1778
+ writeLine(io.stdout, `Dry run: ${result.entries.filter((entry) => entry.status === 'reclaimable').length} item(s) are reclaimable.`);
1779
+ writeLine(io.stdout, 'Run `aw cache prune --yes` to delete them.');
1780
+ if (result.errors.length > 0)
1781
+ writeLine(io.stderr, `${result.errors.length} item(s) could not be fully inspected and were retained.`);
1627
1782
  }
1628
- }
1629
- writeWarnings(io.stderr, receipt.warnings, { actionableOnly: true });
1630
- commandExitState.exitCode = resolveCommandReceiptExitCode(receipt);
1631
- });
1632
- program
1633
- .command('cleanup')
1634
- .argument('[plugins...]')
1635
- .option('-s, --scope <scope>', 'project or user')
1636
- .option('-p, --platform <platform>', 'codex | claude | both')
1637
- .option('-j, --json', 'print cleanup result as JSON', false)
1638
- .option('--force', 'remove exclusively owned plugin output without dependency protection', false)
1639
- .option('-v, --verbose', 'show command diagnostics', false)
1640
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1641
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1642
- .action(async (plugins, rawOptions) => {
1643
- const context = createActionContext('cleanup', rawOptions);
1644
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('cleanup', plugins ?? [], rawOptions, context));
1645
- if (outcome.cancelled)
1646
- return;
1647
- const result = outcome.result;
1648
- if (rawOptions.json) {
1649
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('cleanup', result));
1650
- }
1651
- else {
1652
- for (const line of renderRebuildReceipt('cleanup', result)) {
1653
- writeLine(io.stdout, line);
1783
+ else {
1784
+ writeLine(io.stdout, `Deleted ${result.deleted.length} Catalog store item(s) (${result.deletedBytes} bytes).`);
1785
+ if (result.errors.length > 0)
1786
+ writeLine(io.stderr, `${result.errors.length} item(s) could not be fully inspected or deleted and were retained.`);
1654
1787
  }
1788
+ commandExitState.exitCode = result.ok ? 0 : 1;
1655
1789
  }
1656
- writeWarnings(io.stderr, result.warnings, { actionableOnly: true });
1657
- commandExitState.exitCode = result.overallState === 'failed' ? 1 : 0;
1658
- });
1659
- program
1660
- .command('reinstall')
1661
- .argument('[plugins...]')
1662
- .option('-s, --scope <scope>', 'project or user')
1663
- .option('-p, --platform <platform>', 'codex | claude | both')
1664
- .option('--script-timeout <ms>', 'override plugin lifecycle script timeout in milliseconds')
1665
- .option('-j, --json', 'print receipt as JSON', false)
1666
- .option('-v, --verbose', 'show command diagnostics', false)
1667
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1668
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1669
- .action(async (plugins, rawOptions) => {
1670
- const context = createActionContext('reinstall', rawOptions);
1671
- const outcome = await runActionWithContext(context, () => runWriteCommandAction('reinstall', plugins ?? [], rawOptions, context));
1672
- if (outcome.cancelled)
1673
- return;
1674
- const receipt = outcome.result;
1675
- if (rawOptions.json) {
1676
- writeJsonReceipt(io.stdout, buildRebuildReceiptJson('reinstall', receipt));
1677
- }
1678
- else {
1679
- const lines = renderRebuildReceipt('reinstall', receipt);
1680
- for (const line of lines) {
1681
- writeLine(io.stdout, line);
1682
- }
1790
+ catch (error) {
1791
+ const failure = sanitizeCatalogSourceError(error, env);
1792
+ const message = redactString(failure.message);
1793
+ const code = catalogStoreErrorCode(error);
1794
+ if (rawOptions.json)
1795
+ writeJsonReceipt(io.stdout, {
1796
+ catalogStoreSchemaVersion: 2,
1797
+ command: 'catalog:store:prune',
1798
+ ok: false,
1799
+ overallState: 'failed',
1800
+ dryRun,
1801
+ entries: [],
1802
+ deleted: [],
1803
+ retained: [],
1804
+ errors: [{ code, message }],
1805
+ reclaimableBytes: null,
1806
+ deletedBytes: 0,
1807
+ });
1808
+ writeLine(io.stderr, message);
1809
+ commandExitState.exitCode = 1;
1683
1810
  }
1684
- writeWarnings(io.stderr, receipt.warnings, { actionableOnly: true });
1685
- commandExitState.exitCode = resolveCommandReceiptExitCode(receipt);
1686
1811
  });
1687
- const config = program
1688
- .command('config')
1689
- .description('Manage AW plugin configuration');
1690
- config
1691
- .command('list')
1692
- .argument('[plugin]')
1693
- .option('-s, --scope <scope>', 'read only project or user config')
1694
- .option('--local', 'read only the current project local override layer', false)
1695
- .option('-j, --json', 'print config as JSON', false)
1812
+ const recoveryCommand = (command) => command
1813
+ .option('-j, --json', 'print one recovery receipt as JSON', false)
1696
1814
  .option('-v, --verbose', 'show command diagnostics', false)
1697
1815
  .option('-D, --debug', 'write debug diagnostics to a log file', false)
1698
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1699
- .action(async (pluginName, rawOptions) => {
1700
- const context = createActionContext('config:list', rawOptions);
1701
- const outcome = await runActionWithContext(context, async () => {
1702
- resolveConfigProjectLayer(rawOptions);
1703
- if (!rawOptions.local)
1704
- resolveConfigReadResolution(rawOptions.scope);
1705
- const execute = async (selectedPlugin) => resolveMultiSourceConfigRead({
1706
- selector: selectedPlugin,
1707
- rawOptions,
1708
- context,
1709
- });
1710
- if (pluginName)
1711
- return { cancelled: false, pluginName, value: await execute(pluginName) };
1712
- if (!isWizardAvailable(context, rawOptions))
1713
- throw new Error(configCommandUsage('list'));
1714
- const currentCandidates = await loadWizardCandidates(context, {});
1715
- const storedCandidates = await loadStoredConfigWizardCandidates(context, configReadStoreLocations(rawOptions));
1716
- const candidates = mergeWizardCandidates(currentCandidates, storedCandidates);
1717
- if (candidates.length === 0) {
1718
- throw new Error('No plugin config candidates exist in the selected location.');
1719
- }
1720
- const result = await runCommandWizard(context, {
1721
- command: 'config:list',
1722
- candidates,
1723
- initial: { plugins: [], scope: rawOptions.scope },
1724
- pluginMode: 'single',
1725
- ...equivalentConfigCommandProjection((selection) => ({
1726
- command: 'list',
1727
- plugin: selection.plugins[0],
1728
- scope: rawOptions.scope,
1729
- projectLayer: rawOptions.local ? 'local' : 'shared',
1730
- })),
1731
- execute: (selection) => execute(selection.plugins[0]),
1732
- });
1733
- return result.cancelled
1734
- ? { cancelled: true }
1735
- : { cancelled: false, pluginName: result.selection.plugins[0], value: result.value };
1816
+ .option('--log-file <path>', 'write debug diagnostics to the specified file');
1817
+ const contextualCommand = (command) => recoveryCommand(command)
1818
+ .addOption(strictValueOption('--context <context>', 'user only, or user and current project', ['user', 'project']));
1819
+ const recoveryScope = (rawOptions) => normalizeWriteRequest(() => parseScopeValue(rawOptions.scope));
1820
+ const recoveryContext = (rawOptions) => rawOptions.context === undefined
1821
+ ? undefined : normalizeWriteRequest(() => parseContextValue(rawOptions.context));
1822
+ const runRecoveryAction = async (command, rawOptions, action) => {
1823
+ const context = createActionContext(command, rawOptions);
1824
+ const result = await runActionWithContext(context, () => action(context));
1825
+ if (rawOptions.json)
1826
+ writeJsonReceipt(io.stdout, result);
1827
+ else
1828
+ renderRecoveryReceipt(io.stdout, result);
1829
+ commandExitState.exitCode = result.ok ? 0
1830
+ : result.errors.some((error) => error.code === 'invalidArguments') ? 2 : 1;
1831
+ };
1832
+ const showWorkContext = async (context, rawOptions) => {
1833
+ if (rawOptions.scope === 'project' && rawOptions.context === 'user') {
1834
+ throw new WriteCommandRequestError('--scope project cannot be combined with --context user.');
1835
+ }
1836
+ const work = await resolveWorkContext({ cwd: context.cwd, context: recoveryContext(rawOptions),
1837
+ ...(rawOptions.scope === undefined ? {} : { scope: recoveryScope(rawOptions) }) });
1838
+ if (!rawOptions.json)
1839
+ writeLine(io.stdout, work.projectRoot
1840
+ ? `工作上下文:用户与当前项目 ${work.projectRoot}` : '工作上下文:仅用户');
1841
+ return work;
1842
+ };
1843
+ const targets = program.command('target').description('Manage the local platform policy');
1844
+ contextualCommand(targets.command('set').argument('[targets...]'))
1845
+ .option('--none', 'save an empty target set', false)
1846
+ .option('--apply', 'apply the saved target policy in this work context', false)
1847
+ .option('-y, --yes', 'confirm reviewed output changes', false)
1848
+ .action(async (agents, rawOptions) => {
1849
+ if (rawOptions.none ? agents.length > 0 : agents.length === 0) {
1850
+ throw new WriteCommandRequestError('Use target IDs or --none, but not both.');
1851
+ }
1852
+ const normalized = normalizeWriteRequest(() => normalizeAgents(agents));
1853
+ await runRecoveryAction('targets:set', rawOptions, async (context) => {
1854
+ await showWorkContext(context, rawOptions);
1855
+ return targetsSet({ cwd: context.cwd, env: context.env, targets: normalized,
1856
+ context: recoveryContext(rawOptions), apply: rawOptions.apply, yes: rawOptions.yes,
1857
+ cliVersion: resolveCliVersion(), runtime: recoveryRuntime(context, rawOptions, true) });
1736
1858
  });
1737
- if (outcome.cancelled)
1738
- return;
1739
- const resolved = outcome.value;
1740
- const selectedPluginName = resolved.pluginName;
1741
- if (rawOptions.json) {
1742
- writeJsonReceipt(io.stdout, {
1743
- ok: true,
1744
- configSchemaVersion: 4,
1745
- command: 'config:list',
1746
- plugin: selectedPluginName,
1747
- pluginName: selectedPluginName,
1748
- pluginId: resolved.pluginId,
1749
- sourceId: resolved.sourceId,
1750
- sourceIdentity: resolved.sourceIdentity,
1751
- scope: rawOptions.local ? 'project' : rawOptions.scope ?? 'effective',
1752
- projectLayer: rawOptions.local ? 'local' : 'shared',
1753
- ...(resolved.result.schema ? { schema: resolved.result.schema } : {}),
1754
- fields: resolved.result.fields,
1755
- });
1756
- }
1757
- else {
1758
- writeConfigReadHuman(io.stdout, resolved.result, resolved.pluginId);
1759
- }
1760
1859
  });
1761
- config
1762
- .command('get')
1763
- .argument('[plugin]')
1764
- .argument('[key]')
1765
- .option('-s, --scope <scope>', 'read only project or user config')
1766
- .option('--local', 'read only the current project local override layer', false)
1767
- .option('-j, --json', 'print config as JSON', false)
1768
- .option('-v, --verbose', 'show command diagnostics', false)
1769
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1770
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1771
- .action(async (pluginName, key, rawOptions) => {
1772
- const context = createActionContext('config:get', rawOptions);
1773
- const outcome = await runActionWithContext(context, async () => {
1774
- resolveConfigProjectLayer(rawOptions);
1775
- if (!rawOptions.local)
1776
- resolveConfigReadResolution(rawOptions.scope);
1777
- const execute = async (selectedPlugin) => resolveMultiSourceConfigRead({
1778
- selector: selectedPlugin,
1779
- ...(key === undefined ? {} : { key }),
1780
- rawOptions,
1781
- context,
1782
- });
1783
- if (pluginName)
1784
- return { cancelled: false, pluginName, value: await execute(pluginName) };
1785
- if (!isWizardAvailable(context, rawOptions))
1786
- throw new Error(configCommandUsage('get'));
1787
- const currentCandidates = await loadWizardCandidates(context, {});
1788
- const storedCandidates = await loadStoredConfigWizardCandidates(context, configReadStoreLocations(rawOptions));
1789
- const candidates = mergeWizardCandidates(currentCandidates, storedCandidates);
1790
- if (candidates.length === 0) {
1791
- throw new Error('No plugin config candidates exist in the selected location.');
1792
- }
1793
- const result = await runCommandWizard(context, {
1794
- command: 'config:get',
1795
- candidates,
1796
- initial: { plugins: [], key, scope: rawOptions.scope },
1797
- pluginMode: 'single',
1798
- ...equivalentConfigCommandProjection((selection) => ({
1799
- command: 'get',
1800
- plugin: selection.plugins[0],
1801
- key,
1802
- scope: rawOptions.scope,
1803
- projectLayer: rawOptions.local ? 'local' : 'shared',
1804
- })),
1805
- execute: (selection) => execute(selection.plugins[0]),
1860
+ contextualCommand(targets.command('list'))
1861
+ .action(async (rawOptions) => runRecoveryAction('targets:list', rawOptions, (context) => targetsList({ cwd: context.cwd, env: context.env, context: recoveryContext(rawOptions) })));
1862
+ for (const action of ['exclude', 'include']) {
1863
+ contextualCommand(targets.command(action).argument('<plugin>'))
1864
+ .addOption(strictValueOption('--target <target>', 'one canonical platform target', PLATFORM_TARGETS).makeOptionMandatory())
1865
+ .option('--apply', 'apply the saved exclusion policy in this work context', false)
1866
+ .option('-y, --yes', 'confirm reviewed output changes', false)
1867
+ .action(async (selector, rawOptions) => {
1868
+ await runRecoveryAction(`targets:${action}`, rawOptions, async (context) => {
1869
+ await showWorkContext(context, rawOptions);
1870
+ return targetsChangeExclusion({ cwd: context.cwd, env: context.env, context: recoveryContext(rawOptions),
1871
+ selector, target: rawOptions.target, excluded: action === 'exclude', apply: rawOptions.apply,
1872
+ yes: rawOptions.yes, cliVersion: resolveCliVersion(), runtime: recoveryRuntime(context, rawOptions, true) });
1806
1873
  });
1807
- return result.cancelled
1808
- ? { cancelled: true }
1809
- : { cancelled: false, pluginName: result.selection.plugins[0], value: result.value };
1810
1874
  });
1811
- if (outcome.cancelled)
1812
- return;
1813
- const resolved = outcome.value;
1814
- const selectedPluginName = resolved.pluginName;
1815
- if (rawOptions.json) {
1816
- writeJsonReceipt(io.stdout, {
1817
- ok: true,
1818
- configSchemaVersion: 4,
1819
- command: 'config:get',
1820
- plugin: selectedPluginName,
1821
- pluginName: selectedPluginName,
1822
- pluginId: resolved.pluginId,
1823
- sourceId: resolved.sourceId,
1824
- sourceIdentity: resolved.sourceIdentity,
1825
- key,
1826
- scope: rawOptions.local ? 'project' : rawOptions.scope ?? 'effective',
1827
- projectLayer: rawOptions.local ? 'local' : 'shared',
1828
- ...(resolved.result.schema ? { schema: resolved.result.schema } : {}),
1829
- fields: resolved.result.fields,
1830
- });
1831
- }
1832
- else {
1833
- writeConfigReadHuman(io.stdout, resolved.result, resolved.pluginId);
1834
- }
1835
- });
1836
- config
1837
- .command('set')
1838
- .argument('[plugin]')
1839
- .argument('[key]')
1840
- .argument('[value]')
1841
- .option('-s, --scope <scope>', 'project or user')
1842
- .option('--local', 'write only the current project local override layer', false)
1843
- .option('--value-json', 'parse value as a JSON literal', false)
1844
- .option('-j, --json', 'print receipt as JSON', false)
1875
+ }
1876
+ const config = plugin.command('config').description('Manage user common and platform configuration');
1877
+ const configCommand = (command) => command
1878
+ .addOption(strictValueOption('--platform <target>', 'configuration platform; omitted means common', PLATFORM_TARGETS))
1879
+ .addOption(strictValueOption('--context <context>', 'definition and reference context', ['user', 'project']))
1880
+ .option('-j, --json', 'print one JSON object', false)
1845
1881
  .option('-v, --verbose', 'show command diagnostics', false)
1846
1882
  .option('-D, --debug', 'write debug diagnostics to a log file', false)
1847
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1848
- .action(async (pluginName, key, rawValue, rawOptions) => {
1849
- const context = createActionContext('config:set', rawOptions);
1850
- let outcome;
1851
- try {
1852
- outcome = await runActionWithContext(context, async () => {
1853
- const scope = resolveConfigWriteScope(rawOptions.scope);
1854
- const projectLayer = resolveConfigProjectLayer(rawOptions);
1855
- const execute = async (selectedPlugin, selectedKey, inputValue) => withResolvedConfigMutationPlugin(context, selectedPlugin, async ({ pluginId, source, plugin }, awHomeMutationToken) => {
1856
- if (!plugin.manifest.config?.schema) {
1857
- throw new Error(`configSchemaUnavailable: Plugin "${selectedPlugin}" does not declare an AW config schema.`);
1883
+ .option('--log-file <path>', 'write debug diagnostics to the specified file');
1884
+ const configMutation = (command) => configCommand(command)
1885
+ .option('--apply', 'refresh existing affected outputs after saving', false)
1886
+ .option('--script-timeout <ms>', 'override plugin preApply timeout in milliseconds')
1887
+ .option('-y, --yes', 'confirm reviewed output changes', false);
1888
+ const configContext = async (context, rawOptions, apply = rawOptions.apply === true) => {
1889
+ const requested = rawOptions.context === undefined ? apply ? undefined : 'user'
1890
+ : normalizeWriteRequest(() => parseContextValue(rawOptions.context));
1891
+ const work = await resolveWorkContext({ cwd: context.cwd, context: requested });
1892
+ if (apply && !rawOptions.json)
1893
+ writeLine(io.stdout, work.projectRoot
1894
+ ? `工作上下文:用户与当前项目 ${work.projectRoot}` : '工作上下文:仅用户');
1895
+ return work;
1896
+ };
1897
+ const configPlatform = (rawOptions) => rawOptions.platform === undefined
1898
+ ? undefined : normalizeWriteRequest(() => parsePlatformTargetValue(rawOptions.platform));
1899
+ for (const command of ['schema', 'list', 'get']) {
1900
+ const entry = configCommand((command === 'list' ? new Command(command) : config.command(command)).argument('<plugin>'));
1901
+ if (command === 'get')
1902
+ entry.argument('[key]');
1903
+ entry.action(async (...args) => {
1904
+ const selector = args[0];
1905
+ const key = command === 'get' ? args[1] : undefined;
1906
+ const rawOptions = args[command === 'get' ? 2 : 1];
1907
+ const context = createActionContext(`config:${command}`, rawOptions);
1908
+ const work = await configContext(context, rawOptions);
1909
+ const resolved = await runActionWithContext(context, () => resolveMultiSourceConfigRead({
1910
+ selector, key, rawOptions: { ...rawOptions, context: work.context }, context,
1911
+ }));
1912
+ if (rawOptions.json) {
1913
+ const result = projectReceipt(`plugin.config.${command}`, {
1914
+ ok: true, configSchemaVersion: 5, command: `config:${command}`,
1915
+ plugin: resolved.pluginName, pluginName: resolved.pluginName, pluginId: resolved.pluginId,
1916
+ sourceId: resolved.sourceId, sourceIdentity: resolved.sourceIdentity,
1917
+ context: work, platform: configPlatform(rawOptions) ?? 'common',
1918
+ ...(resolved.result.schema ? { schema: resolved.result.schema } : {}),
1919
+ fields: command === 'schema' ? resolved.result.fieldDefinitions ?? {} : resolved.result.fields,
1920
+ ...(key === undefined ? {} : { key }),
1921
+ });
1922
+ if (command === 'get')
1923
+ for (const field of resolved.result.fields) {
1924
+ const definition = resolved.result.fieldDefinitions?.[field.key];
1925
+ if (field.kind !== 'manifest' || field.valueState !== 'invalid' || !definition?.sensitive)
1926
+ continue;
1927
+ result.nextActions.push({ kind: 'command',
1928
+ argv: ['aw', 'plugin', 'config', 'set', resolved.pluginId, field.key,
1929
+ '--context', work.context, ...(resolved.result.platform ? ['--platform', resolved.result.platform] : []), '--value-stdin'],
1930
+ reason: 'Replace the invalid sensitive configuration value through stdin.', requiresConfirmation: false });
1858
1931
  }
1859
- if (!plugin.manifest.config.schema[selectedKey]) {
1860
- throw new Error(`Unknown config key "${selectedKey}".`);
1932
+ writeJsonReceipt(io.stdout, result);
1933
+ }
1934
+ else if (command === 'schema')
1935
+ writeJsonReceipt(io.stdout, resolved.result.fieldDefinitions ?? {});
1936
+ else
1937
+ writeConfigReadHuman(io.stdout, resolved.result, resolved.pluginId);
1938
+ });
1939
+ }
1940
+ for (const command of ['set', 'edit', 'unset']) {
1941
+ const entry = configMutation((command === 'edit' ? new Command(command) : config.command(command)).argument('<plugin>'));
1942
+ if (command !== 'edit')
1943
+ entry.argument('<field>');
1944
+ if (command === 'set')
1945
+ entry
1946
+ .option('--value-json <json>', 'set an exact JSON value')
1947
+ .option('--value-stdin', 'read the exact string value until stdin EOF', false)
1948
+ .option('--preset <id>', 'use a declared preset');
1949
+ entry.action(async (...args) => {
1950
+ const selector = args[0];
1951
+ const rawOptions = args[command === 'edit' ? 1 : 2];
1952
+ let key = command === 'edit' ? undefined : args[1];
1953
+ const context = createActionContext(`config:${command}`, rawOptions);
1954
+ try {
1955
+ const work = await configContext(context, rawOptions);
1956
+ const platform = configPlatform(rawOptions);
1957
+ const scriptTimeoutMs = normalizeWriteRequest(() => resolveScriptTimeoutMs(rawOptions));
1958
+ if (command === 'edit' && (!isWizardAvailable(context, rawOptions) || !context.prompt.select || !context.prompt.input)) {
1959
+ throw new WriteCommandRequestError('config edit requires an interactive terminal. Use config set for scripts.');
1960
+ }
1961
+ const explicitValueCount = [rawOptions.valueJson !== undefined, rawOptions.valueStdin === true,
1962
+ rawOptions.preset !== undefined].filter(Boolean).length;
1963
+ if (command === 'set' && (explicitValueCount > 1 || explicitValueCount === 0
1964
+ && !(context.interactive && context.isTty && !context.isCi && !rawOptions.json))) {
1965
+ throw new WriteCommandRequestError('Use exactly one of --value-json, --value-stdin, or --preset.');
1966
+ }
1967
+ const receipt = await runActionWithContext(context, () => withResolvedConfigMutationPlugin(context, selector, async ({ pluginId, source, plugin }, awHomeMutationToken, catalogOperationContext) => {
1968
+ if (!plugin.manifest.config)
1969
+ throw Object.assign(new Error(`configSchemaUnavailable: Plugin "${plugin.manifest.name}" does not declare an AW config schema.`), { code: 'configSchemaUnavailable' });
1970
+ const fields = selectPluginConfigProfile(plugin.manifest.config, platform).fields;
1971
+ if (command === 'edit') {
1972
+ const selected = await context.prompt.select({ message: `编辑用户${platform ?? 'common'}配置`,
1973
+ choices: Object.entries(fields).map(([value, field]) => ({ value, label: field.title ?? value })) });
1974
+ if (selected.cancelled || selected.action !== 'select' || selected.value === undefined)
1975
+ return undefined;
1976
+ key = selected.value;
1977
+ }
1978
+ const field = fields[key];
1979
+ const store = await readPluginConfigStore({ sourceId: source.sourceId,
1980
+ sourceIdentity: source.sourceIdentity, logicalIdentity: source.logicalIdentity,
1981
+ pluginName: plugin.manifest.name, scope: 'user', platform, cwd: context.cwd, env: context.env,
1982
+ schema: fields });
1983
+ if (command === 'unset') {
1984
+ if (!Object.hasOwn(store.values, key))
1985
+ throw new WriteCommandRequestError(`Unknown config key "${key}" in the selected layer.`);
1986
+ }
1987
+ else if (!field)
1988
+ throw new WriteCommandRequestError(`Unknown config key "${key}".`);
1989
+ let inputValue;
1990
+ if (command !== 'unset') {
1991
+ const sensitive = field.sensitive === true;
1992
+ if (sensitive && (rawOptions.valueJson !== undefined || rawOptions.preset !== undefined)) {
1993
+ throw Object.assign(new WriteCommandRequestError('Sensitive config requires --value-stdin.'), { code: 'sensitiveConfigInputUnsupported' });
1994
+ }
1995
+ if (rawOptions.valueStdin)
1996
+ inputValue = await readUtf8Stdin(context.stdin);
1997
+ else if (sensitive) {
1998
+ if (!context.interactive || !context.isTty || context.isCi || rawOptions.json || !context.prompt.password) {
1999
+ throw new Error('sensitiveConfigStdinRequired: Use --value-stdin outside an interactive terminal.');
2000
+ }
2001
+ const response = await context.prompt.password({ message: `输入 ${field.title ?? key}`, mask: true });
2002
+ if (response.cancelled || response.action !== 'select' || response.value === undefined)
2003
+ return undefined;
2004
+ inputValue = response.value;
2005
+ }
2006
+ else if (command === 'edit' || explicitValueCount === 0) {
2007
+ if (!context.prompt.input)
2008
+ throw new WriteCommandRequestError('Use --value-json, --value-stdin, or --preset.');
2009
+ const response = await context.prompt.input({ message: `输入 ${field.title ?? key} 的 JSON 值`,
2010
+ defaultValue: JSON.stringify(store.values[key]) });
2011
+ if (response.cancelled || response.action !== 'select' || response.value === undefined)
2012
+ return undefined;
2013
+ try {
2014
+ inputValue = JSON.parse(response.value);
2015
+ }
2016
+ catch {
2017
+ throw new WriteCommandRequestError('Enter a valid JSON value.');
2018
+ }
2019
+ }
2020
+ else if (rawOptions.valueJson !== undefined) {
2021
+ try {
2022
+ inputValue = JSON.parse(rawOptions.valueJson);
2023
+ }
2024
+ catch {
2025
+ throw new WriteCommandRequestError('--value-json must contain valid JSON.');
2026
+ }
2027
+ }
2028
+ else {
2029
+ const preset = field.choices?.presets.find((candidate) => candidate.id === rawOptions.preset);
2030
+ if (!preset)
2031
+ throw new WriteCommandRequestError(`Unknown preset "${rawOptions.preset}".`);
2032
+ inputValue = structuredClone(preset.value);
2033
+ }
2034
+ }
2035
+ if (command !== 'unset') {
2036
+ try {
2037
+ inputValue = (await coercePluginConfigUpdates({ schema: fields, updates: { [key]: inputValue }, cwd: context.cwd }))[key];
2038
+ }
2039
+ catch {
2040
+ throw new WriteCommandRequestError(`Invalid value for configuration field "${key}".`);
2041
+ }
2042
+ }
2043
+ try {
2044
+ await assertPluginConfigMutationCandidate({ sourceId: source.sourceId, sourceIdentity: source.sourceIdentity,
2045
+ logicalIdentity: source.logicalIdentity, pluginName: plugin.manifest.name, manifest: plugin.manifest,
2046
+ scope: work.context, platform, cwd: context.cwd, env: context.env,
2047
+ updates: command === 'unset' ? {} : { [key]: inputValue }, removeKeys: command === 'unset' ? [key] : [] });
2048
+ }
2049
+ catch (error) {
2050
+ if (error?.code === 'configReferenceInvalid')
2051
+ throw new WriteCommandRequestError(`Invalid value or reference for configuration field "${key}".`);
2052
+ throw error;
1861
2053
  }
1862
- const writeReceipt = await applyPluginConfigWrite({
1863
- plugin,
1864
- pluginName: plugin.manifest.name,
1865
- scope,
1866
- projectLayer,
1867
- cwd: context.cwd,
1868
- env: context.env,
1869
- nativeCliRunner: context.nativeCliRunner,
1870
- rebuildRuntime: { ...context, awHomeMutationToken },
1871
- awHomeMutationToken,
1872
- request: {
1873
- updates: { [selectedKey]: inputValue },
1874
- },
2054
+ const mutation = command === 'unset' ? { kind: 'patch', removeKeys: [key] } : { kind: 'patch', updates: { [key]: inputValue } };
2055
+ const confirmation = rawOptions.apply ? await preparePublicConfigConfirmation({ plugin, scope: work.context,
2056
+ context: work.context, platform, cwd: context.cwd, env: context.env, cliVersion: resolveCliVersion(),
2057
+ nativeCliRunner: context.nativeCliRunner, awHomeMutationToken, yes: rawOptions.yes, mutation,
2058
+ rebuildRuntime: { ...context, awHomeMutationToken, catalogOperationContext,
2059
+ expectedGenerationSetDigest: catalogOperationContext.generationSetDigest } })
2060
+ : { required: false, provided: rawOptions.yes === true, effects: [] };
2061
+ const writeReceipt = await applyPluginConfigWrite({ plugin, pluginName: plugin.manifest.name,
2062
+ scope: work.context, context: work.context, platform, cliVersion: resolveCliVersion(),
2063
+ cwd: context.cwd, env: context.env, nativeCliRunner: context.nativeCliRunner,
2064
+ rebuildRuntime: { ...context, awHomeMutationToken, catalogOperationContext,
2065
+ expectedGenerationSetDigest: catalogOperationContext.generationSetDigest,
2066
+ ...(scriptTimeoutMs === undefined ? {} : { scriptTimeoutMs }) },
2067
+ awHomeMutationToken, request: command === 'unset' ? { removeKeys: [key] } : { updates: { [key]: inputValue } },
2068
+ apply: rawOptions.apply === true, sharedNativeApplyConfirmed: rawOptions.yes === true,
2069
+ preApplyConfirmed: rawOptions.yes === true });
2070
+ return buildConfigMutationReceipt(`config:${command}`, {
2071
+ ...writeReceipt, confirmation, ok: writeReceipt.overallState === 'succeeded', plugin: plugin.manifest.name,
2072
+ pluginName: plugin.manifest.name, pluginId, sourceId: source.sourceId, sourceIdentity: source.sourceIdentity,
2073
+ context: work, platform: platform ?? 'common',
2074
+ ...(command === 'unset' ? { removedKey: key, existed: true } : {}),
2075
+ affectedFields: [{ key: key, title: field?.title ?? key, kind: 'manifest', reserved: false,
2076
+ action: command === 'unset' ? 'unset' : 'set', scope: 'user',
2077
+ ...(writeReceipt.staleRemovedKeys?.includes(key) ? { stale: true } : {}) }],
1875
2078
  });
1876
- return {
1877
- ok: writeReceipt.overallState === 'succeeded',
1878
- receiptSchemaVersion: 4,
1879
- command: 'config:set',
1880
- ...writeReceipt,
1881
- plugin: plugin.manifest.name,
1882
- pluginName: plugin.manifest.name,
1883
- pluginId,
1884
- sourceId: source.sourceId,
1885
- sourceIdentity: source.sourceIdentity,
1886
- affectedFields: [{
1887
- key: selectedKey,
1888
- title: plugin?.manifest.config?.schema?.[selectedKey]?.title ?? selectedKey,
1889
- kind: 'manifest',
1890
- reserved: false,
1891
- action: 'set',
1892
- scope,
1893
- ...(scope === 'project' ? { projectLayer } : {}),
1894
- }],
1895
- };
1896
- });
1897
- if (pluginName && key && rawValue !== undefined) {
1898
- const inputValue = parseConfigValue(rawValue, rawOptions.valueJson === true);
1899
- return {
1900
- cancelled: false,
1901
- key,
1902
- value: await execute(pluginName, key, inputValue),
1903
- };
2079
+ }, rawOptions.apply === true));
2080
+ if (!receipt)
2081
+ return;
2082
+ if (rawOptions.json)
2083
+ writeJsonReceipt(io.stdout, receipt);
2084
+ else {
2085
+ writeLine(io.stdout, `已保存 ${receipt.plugin}.${key}(用户 ${platform ?? 'common'} 配置)。`);
2086
+ writeConfigApplyNotice(io.stderr, receipt);
1904
2087
  }
1905
- if (!isWizardAvailable(context, rawOptions))
1906
- throw new Error(configCommandUsage('set'));
1907
- const candidates = await loadWizardCandidates(context, {});
1908
- if (pluginName) {
1909
- const candidate = candidates.find((entry) => entry.pluginName === pluginName);
1910
- if (!candidate)
1911
- throw new Error(`Unknown plugin "${pluginName}".`);
1912
- if (!hasConfigSchemaKeys(candidate)) {
1913
- throw new Error(`configSchemaUnavailable: Plugin "${pluginName}" does not declare an AW config schema.`);
1914
- }
1915
- if (key && !candidate.configSchema?.[key])
1916
- throw new Error(`Unknown config key "${key}".`);
2088
+ commandExitState.exitCode = receipt.overallState === 'succeeded' ? 0 : 1;
2089
+ }
2090
+ catch (error) {
2091
+ writeConfigMutationFailure(`config:${command}`, selector, rawOptions.json === true, error);
2092
+ }
2093
+ });
2094
+ }
2095
+ configMutation(config.command('reset').argument('<plugin>'))
2096
+ .action(async (selector, rawOptions) => {
2097
+ const context = createActionContext('config:reset', rawOptions);
2098
+ try {
2099
+ const work = await configContext(context, rawOptions);
2100
+ const platform = configPlatform(rawOptions);
2101
+ if (!rawOptions.yes) {
2102
+ if (!isWizardAvailable(context, rawOptions) || !context.prompt.confirm)
2103
+ throw new WriteCommandRequestError('config reset requires --yes.');
2104
+ const confirmed = await context.prompt.confirm({ message: `删除 ${selector} 的用户 ${platform ?? 'common'} 覆盖?`, defaultValue: false });
2105
+ if (confirmed.cancelled || confirmed.value !== true)
2106
+ return;
2107
+ }
2108
+ const located = await resolveStoredConfigResetIdentity({ selector, context, scope: 'user' });
2109
+ const resetStore = async (plugin, pluginError) => withAwHomeMutationLock({ env: context.env, action: async (awHomeMutationToken) => {
2110
+ const confirmation = plugin && rawOptions.apply ? await preparePublicConfigConfirmation({ plugin,
2111
+ scope: work.context, context: work.context, platform, cwd: context.cwd, env: context.env,
2112
+ cliVersion: resolveCliVersion(), nativeCliRunner: context.nativeCliRunner, awHomeMutationToken,
2113
+ yes: rawOptions.yes, mutation: { kind: 'reset' }, rebuildRuntime: context }) : null;
2114
+ const receipt = await resetPluginConfigWithHelper({ ...located, plugin, pluginError, platform, scope: work.context,
2115
+ context: work.context, cliVersion: resolveCliVersion(), cwd: context.cwd, env: context.env, awHomeMutationToken,
2116
+ nativeCliRunner: context.nativeCliRunner, apply: rawOptions.apply === true,
2117
+ rebuildRuntime: { ...context, awHomeMutationToken, scriptTimeoutMs: resolveScriptTimeoutMs(rawOptions) },
2118
+ sharedNativeApplyConfirmed: true, preApplyConfirmed: rawOptions.yes === true });
2119
+ return { ...receipt, confirmation };
2120
+ } });
2121
+ let started = false;
2122
+ const resetReceipt = await runActionWithContext(context, async () => {
2123
+ try {
2124
+ return await withResolvedCatalogPlugin({ selector: located.pluginId, cliVersion: resolveCliVersion(), env: context.env,
2125
+ consume: ({ plugin }) => { started = true; return resetStore(plugin, null); } });
1917
2126
  }
1918
- const configurableCandidates = candidates.filter(hasConfigSchemaKeys);
1919
- if (configurableCandidates.length === 0) {
1920
- throw new Error('configSchemaUnavailable: No current plugin declares an AW config schema.');
2127
+ catch (error) {
2128
+ if (started)
2129
+ throw error;
2130
+ return resetStore(null, error instanceof Error ? error : new Error(String(error)));
1921
2131
  }
1922
- const result = await runCommandWizard(context, {
1923
- command: 'config:set',
1924
- candidates: configurableCandidates,
1925
- initial: {
1926
- plugins: pluginName ? [pluginName] : [],
1927
- key,
1928
- ...(rawValue !== undefined ? { value: rawValue } : {}),
1929
- scope,
1930
- projectLayer,
1931
- },
1932
- pluginMode: pluginName ? 'none' : 'single',
1933
- valueJson: rawOptions.valueJson === true,
1934
- promptForKey: key === undefined,
1935
- promptForValue: rawValue === undefined,
1936
- ...equivalentConfigCommandProjection((selection) => configSetEquivalentOptions(selection, candidates, rawOptions)),
1937
- commandIsTemplate: (selection) => candidates.find((entry) => entry.pluginName === selection.plugins[0])?.configSchema?.[selection.key ?? ''] !== undefined
1938
- && configFieldPlaceholder(candidates.find((entry) => entry.pluginName === selection.plugins[0])?.configSchema?.[selection.key ?? '']) !== undefined,
1939
- resultState: overallResultState,
1940
- execute: async (selection) => {
1941
- const selectedPlugin = selection.plugins[0];
1942
- const selectedKey = selection.key;
1943
- const schema = candidates.find((entry) => entry.pluginName === selectedPlugin).configSchema;
1944
- const updates = await coercePluginConfigUpdates({
1945
- schema,
1946
- updates: {
1947
- [selectedKey]: parseConfigValue(selection.value, rawOptions.valueJson === true),
1948
- },
1949
- cwd: context.cwd,
1950
- });
1951
- return execute(selectedPlugin, selectedKey, updates[selectedKey]);
1952
- },
1953
- });
1954
- return result.cancelled
1955
- ? { cancelled: true }
1956
- : { cancelled: false, key: result.selection.key, value: result.value };
1957
2132
  });
2133
+ const receipt = buildConfigMutationReceipt('config:reset', { ...resetReceipt,
2134
+ ok: resetReceipt.overallState === 'succeeded', ...located, plugin: located.pluginName,
2135
+ context: work, platform: platform ?? 'common' });
2136
+ if (rawOptions.json)
2137
+ writeJsonReceipt(io.stdout, receipt);
2138
+ else {
2139
+ writeLine(io.stdout, `已恢复 ${receipt.plugin} 的用户 ${platform ?? 'common'} 默认配置。`);
2140
+ writeConfigApplyNotice(io.stderr, receipt);
2141
+ }
2142
+ commandExitState.exitCode = receipt.overallState === 'succeeded' ? 0 : 1;
1958
2143
  }
1959
2144
  catch (error) {
1960
- writeConfigMutationFailure('config:set', pluginName, rawOptions.json === true, error);
1961
- return;
1962
- }
1963
- if (outcome.cancelled)
1964
- return;
1965
- const receipt = outcome.value;
1966
- const selectedKey = outcome.key;
1967
- if (rawOptions.json) {
1968
- writeJsonReceipt(io.stdout, receipt);
2145
+ writeConfigMutationFailure('config:reset', selector, rawOptions.json === true, error);
1969
2146
  }
2147
+ });
2148
+ contextualCommand(config.command('apply').argument('<plugin>'))
2149
+ .option('--target <target>', 'limit existing-output refresh to this platform target', collectUniqueOption)
2150
+ .option('-y, --yes', 'confirm reviewed output changes', false)
2151
+ .option('--script-timeout <ms>', 'override plugin preApply timeout in milliseconds')
2152
+ .action(async (selector, rawOptions) => {
2153
+ const context = createActionContext('config:apply', rawOptions);
2154
+ const work = await configContext(context, rawOptions, true);
2155
+ const targets = rawOptions.target?.map((target) => normalizeWriteRequest(() => parsePlatformTargetValue(target)));
2156
+ const receipt = await runActionWithContext(context, () => withResolvedConfigMutationPlugin(context, selector, async ({ plugin, pluginId, source }, awHomeMutationToken) => {
2157
+ const confirmation = await preparePublicConfigConfirmation({ plugin, scope: work.context, context: work.context, targets, cwd: context.cwd, env: context.env, cliVersion: resolveCliVersion(), nativeCliRunner: context.nativeCliRunner, awHomeMutationToken, yes: rawOptions.yes, rebuildRuntime: context });
2158
+ return { confirmation, ...await applyPluginConfig({ plugin, scope: work.context, context: work.context, targets,
2159
+ cliVersion: resolveCliVersion(), cwd: context.cwd, env: context.env, awHomeMutationToken,
2160
+ nativeCliRunner: context.nativeCliRunner, sharedNativeApplyConfirmed: rawOptions.yes === true,
2161
+ preApplyConfirmed: rawOptions.yes === true, rebuildRuntime: { ...context, scriptTimeoutMs: resolveScriptTimeoutMs(rawOptions) } }),
2162
+ command: 'config:apply', plugin: plugin.manifest.name, pluginId, sourceId: source.sourceId,
2163
+ context: work,
2164
+ };
2165
+ }, true));
2166
+ const result = buildConfigMutationReceipt('config:apply', { ...receipt,
2167
+ ok: receipt.overallState === 'succeeded' });
2168
+ if (rawOptions.json)
2169
+ writeJsonReceipt(io.stdout, result);
1970
2170
  else {
1971
- writeLine(io.stdout, `已写入 ${receipt.plugin}.${selectedKey}(${configLayerLabel(receipt.scope, receipt.projectLayer)}配置)。`);
1972
- if (receipt.projectLayer === 'local') {
1973
- writeProjectLocalConfigNotice(io.stdout);
1974
- }
1975
- writeConfigApplyNotice(io.stderr, receipt);
2171
+ writeLine(io.stdout, `配置应用:${result.ok ? '完成' : '部分失败'}。`);
2172
+ writeConfigApplyNotice(io.stderr, { ...result, warnings: [] });
1976
2173
  }
1977
- commandExitState.exitCode = receipt.overallState === 'failed' ? 1 : 0;
2174
+ commandExitState.exitCode = result.ok ? 0 : 1;
1978
2175
  });
1979
- config
1980
- .command('unset')
1981
- .argument('[plugin]')
1982
- .argument('[key]')
1983
- .option('-s, --scope <scope>', 'project or user')
1984
- .option('--local', 'write only the current project local override layer', false)
1985
- .option('-j, --json', 'print receipt as JSON', false)
1986
- .option('-v, --verbose', 'show command diagnostics', false)
1987
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
1988
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
1989
- .action(async (pluginName, key, rawOptions) => {
1990
- const context = createActionContext('config:unset', rawOptions);
1991
- let outcome;
1992
- try {
1993
- outcome = await runActionWithContext(context, async () => {
1994
- const scope = resolveConfigWriteScope(rawOptions.scope);
1995
- const projectLayer = resolveConfigProjectLayer(rawOptions);
1996
- const execute = async (selectedPlugin, selectedKey) => withResolvedConfigMutationPlugin(context, selectedPlugin, async ({ pluginId, source, plugin }, awHomeMutationToken) => {
1997
- if (plugin.manifest.config?.schema && !plugin.manifest.config.schema[selectedKey]) {
1998
- throw new Error(`Unknown config key "${selectedKey}".`);
2176
+ configurePublicCommands(program, options, io, commandExitState);
2177
+ Object.assign(program, { __awCommandExitState: commandExitState });
2178
+ return program;
2179
+ }
2180
+ /** Invoke the packaged author tool. Its JSON remains an internal child-process protocol. */
2181
+ async function runAuthoringCliAdapter(argv, options) {
2182
+ const io = { ...createDefaultIo(), ...options.io };
2183
+ const authoringPluginCommand = argv[0] === 'plugin';
2184
+ const explicitWorkspace = argv.some((token) => token === '--workspace-root' || token.startsWith('--workspace-root='));
2185
+ const authoringScriptByCommand = {
2186
+ init: 'init-plugin.mjs',
2187
+ 'add-skill': 'add-skill.mjs',
2188
+ remove: 'remove-plugin.mjs',
2189
+ validate: 'validate-plugin.mjs',
2190
+ status: 'plugin-status.mjs',
2191
+ };
2192
+ const authoringScript = authoringPluginCommand
2193
+ ? authoringScriptByCommand[argv[1] ?? '']
2194
+ : argv[0] === 'skill' && argv[1] === 'validate'
2195
+ ? 'validate-skill.mjs'
2196
+ : undefined;
2197
+ if (authoringScript && ((!argv.includes('--help') && !argv.includes('-h'))
2198
+ || explicitWorkspace && ['remove', 'status'].includes(argv[1] ?? ''))) {
2199
+ const authoringArgs = argv.slice(2);
2200
+ let authoringEnv = options.env ?? process.env;
2201
+ if (argv[0] === 'plugin'
2202
+ && !authoringArgs.some((token) => token === '--plugin-root' || token.startsWith('--plugin-root='))) {
2203
+ let explicitRoot;
2204
+ for (let index = 0; index < authoringArgs.length; index += 1) {
2205
+ const token = authoringArgs[index];
2206
+ if (token.startsWith('--workspace-root='))
2207
+ explicitRoot = token.slice('--workspace-root='.length);
2208
+ if (token === '--workspace-root')
2209
+ explicitRoot = authoringArgs[index + 1];
2210
+ }
2211
+ const originalCwd = options.cwd ?? process.cwd();
2212
+ let discoveryCwd = originalCwd;
2213
+ if (argv[1] === 'validate') {
2214
+ const valueOptions = new Set(['--workspace-root', '--claude-skill-profile', '--version-base']);
2215
+ for (let index = 0; index < authoringArgs.length; index += 1) {
2216
+ const token = authoringArgs[index];
2217
+ if (valueOptions.has(token)) {
2218
+ index += 1;
2219
+ continue;
2220
+ }
2221
+ if (!token.startsWith('-')) {
2222
+ discoveryCwd = path.resolve(originalCwd, token);
2223
+ authoringArgs[index] = discoveryCwd;
2224
+ break;
1999
2225
  }
2000
- const store = await readPluginConfigStore({
2001
- sourceId: source.sourceId,
2002
- sourceIdentity: source.sourceIdentity,
2003
- pluginName: plugin.manifest.name,
2004
- scope,
2005
- ...(scope === 'project' ? { projectLayer } : {}),
2006
- cwd: context.cwd,
2007
- env: context.env,
2008
- });
2009
- const existed = Object.hasOwn(store.values, selectedKey);
2010
- if (!existed)
2011
- throw new Error(`Unknown config key "${selectedKey}".`);
2012
- const writeReceipt = await applyPluginConfigWrite({
2013
- plugin,
2014
- pluginName: plugin.manifest.name,
2015
- scope,
2016
- projectLayer,
2017
- cwd: context.cwd,
2018
- env: context.env,
2019
- nativeCliRunner: context.nativeCliRunner,
2020
- rebuildRuntime: { ...context, awHomeMutationToken },
2021
- awHomeMutationToken,
2022
- request: {
2023
- removeKeys: [selectedKey],
2024
- },
2025
- });
2026
- return {
2027
- ok: writeReceipt.overallState === 'succeeded',
2028
- receiptSchemaVersion: 4,
2029
- command: 'config:unset',
2030
- ...writeReceipt,
2031
- plugin: plugin.manifest.name,
2032
- pluginName: plugin.manifest.name,
2033
- pluginId,
2034
- sourceId: source.sourceId,
2035
- sourceIdentity: source.sourceIdentity,
2036
- removedKey: selectedKey,
2037
- existed,
2038
- affectedFields: [{
2039
- key: selectedKey,
2040
- title: plugin?.manifest.config?.schema?.[selectedKey]?.title ?? selectedKey,
2041
- kind: 'manifest',
2042
- reserved: false,
2043
- action: 'unset',
2044
- scope,
2045
- ...(scope === 'project' ? { projectLayer } : {}),
2046
- }],
2047
- };
2048
- });
2049
- if (pluginName && key) {
2050
- return { cancelled: false, value: await execute(pluginName, key) };
2051
- }
2052
- if (!isWizardAvailable(context, rawOptions))
2053
- throw new Error(configCommandUsage('unset'));
2054
- const loadedCurrentCandidates = await loadWizardCandidates(context, {});
2055
- const currentCandidates = loadedCurrentCandidates.filter(hasConfigSchemaKeys);
2056
- const candidates = currentCandidates;
2057
- if (pluginName && !candidates.some((entry) => entry.pluginName === pluginName)) {
2058
- throw new Error(`Unknown plugin "${pluginName}".`);
2059
- }
2060
- if (candidates.length === 0) {
2061
- throw new Error('No plugin config candidates exist in the selected location.');
2062
2226
  }
2063
- const result = await runCommandWizard(context, {
2064
- command: 'config:unset',
2065
- candidates,
2066
- initial: { plugins: pluginName ? [pluginName] : [], key, scope, projectLayer },
2067
- pluginMode: pluginName ? 'none' : 'single',
2068
- promptForKey: key === undefined,
2069
- destructive: true,
2070
- ...equivalentConfigCommandProjection((selection) => ({
2071
- command: 'unset',
2072
- plugin: selection.plugins[0],
2073
- key: selection.key,
2074
- scope: selection.scope ?? 'user',
2075
- projectLayer: selection.projectLayer,
2076
- })),
2077
- resultState: overallResultState,
2078
- execute: (selection) => execute(selection.plugins[0], selection.key),
2079
- });
2080
- return result.cancelled
2081
- ? { cancelled: true }
2082
- : { cancelled: false, value: result.value };
2227
+ }
2228
+ const workspace = await resolveCatalogWorkspaceRoot({
2229
+ cwd: discoveryCwd,
2230
+ ...(explicitRoot === undefined ? {} : { explicitRoot: path.resolve(options.cwd ?? process.cwd(), explicitRoot) }),
2231
+ mode: 'existing',
2083
2232
  });
2084
- }
2085
- catch (error) {
2086
- writeConfigMutationFailure('config:unset', pluginName, rawOptions.json === true, error);
2087
- return;
2088
- }
2089
- if (outcome.cancelled)
2233
+ authoringEnv = {
2234
+ ...authoringEnv,
2235
+ AW_AUTHORING_WORKSPACE_ROOT: workspace.workspaceRoot,
2236
+ AW_AUTHORING_WORKSPACE_ROOT_RESOLVED_FROM: workspace.workspaceRootResolvedFrom,
2237
+ };
2238
+ if (explicitRoot === undefined)
2239
+ authoringArgs.push('--workspace-root', workspace.workspaceRoot);
2240
+ }
2241
+ return runAuthoringScript({
2242
+ scriptName: authoringScript,
2243
+ args: authoringArgs,
2244
+ cwd: options.cwd ?? process.cwd(),
2245
+ env: authoringEnv,
2246
+ io,
2247
+ interruption: options.interruption,
2248
+ });
2249
+ }
2250
+ throw new Error('No authoring script is registered for this operation.');
2251
+ }
2252
+ function sourceConfirmation(sourceId, yes, preview) {
2253
+ const required = preview !== undefined && (preview.identityChanged || !preview.references.inventoryComplete || preview.references.references.length > 0);
2254
+ return { required, provided: yes === true, effects: required ? [{ code: 'changeSource', message: 'Change the source used by the affected or unobserved plugin references.', subject: { sourceId }, impact: preview?.references.inventoryComplete ? 'shared' : 'unknown' }] : [] };
2255
+ }
2256
+ function commandId(command) {
2257
+ const names = [];
2258
+ for (let current = command; current?.parent; current = current.parent)
2259
+ names.unshift(current.name());
2260
+ return names.join('.');
2261
+ }
2262
+ function configurePublicCommands(program, options, io, exit) {
2263
+ const find = (parent, name) => {
2264
+ const result = parent.commands.find((entry) => entry.name() === name);
2265
+ if (!result)
2266
+ throw new Error(`Missing registered command: ${name}`);
2267
+ return result;
2268
+ };
2269
+ const plugin = find(program, 'plugin');
2270
+ const dev = find(program, 'dev');
2271
+ const devPlugin = find(dev, 'plugin');
2272
+ const catalog = find(dev, 'catalog');
2273
+ const source = find(program, 'source');
2274
+ const sourceUpdate = find(source, 'update');
2275
+ sourceUpdate.option('--primary', 'Make this source primary');
2276
+ const sourceStatus = find(source, 'status');
2277
+ sourceStatus.option('--remote', 'Check remote candidates without changing stored state');
2278
+ sourceStatus.action(async (id, raw) => {
2279
+ const env = options.env ?? process.env;
2280
+ const [observed, configured] = await Promise.all([catalogSourceStatusCommand({ sourceId: id, env }), listCatalogSources({ env })]);
2281
+ const result = { ...observed, primarySourceId: configured.primarySourceId, sources: observed.sources.map((source) => ({ ...source, configuration: configured.sources.find((entry) => entry.id === source.sourceId) ?? null })) };
2282
+ if (!raw.remote) {
2283
+ io.result?.(result);
2090
2284
  return;
2091
- const receipt = outcome.value;
2092
- if (rawOptions.json) {
2093
- writeJsonReceipt(io.stdout, receipt);
2094
2285
  }
2095
- else {
2096
- writeLine(io.stdout, receipt.existed
2097
- ? `已删除 ${receipt.plugin}.${receipt.removedKey}(${configLayerLabel(receipt.scope, receipt.projectLayer)}配置)。`
2098
- : `${receipt.plugin}.${receipt.removedKey}(${configLayerLabel(receipt.scope, receipt.projectLayer)}配置)原本不存在。`);
2099
- if (receipt.projectLayer === 'local') {
2100
- writeProjectLocalConfigNotice(io.stdout);
2286
+ const remote = await Promise.all(result.sources.map(async (source) => {
2287
+ try {
2288
+ const probe = await syncCatalogSourceCommand({ sourceId: source.sourceId, cliVersion: resolveCliVersion(), cwd: options.cwd, check: true, env });
2289
+ return { sourceId: source.sourceId, checked: true, candidate: probe.resolution, outcome: probe.outcome };
2101
2290
  }
2102
- writeConfigApplyNotice(io.stderr, receipt);
2103
- }
2104
- commandExitState.exitCode = receipt.overallState === 'failed' ? 1 : 0;
2291
+ catch (error) {
2292
+ const safe = sanitizeCatalogSourceError(error, env);
2293
+ return { sourceId: source.sourceId, checked: false, error: { code: catalogGenerationErrorCode(error), message: safe.message } };
2294
+ }
2295
+ }));
2296
+ const failures = remote.filter((entry) => !entry.checked);
2297
+ const projected = projectReceipt('source.status', { ...result, remote, complete: failures.length === 0 });
2298
+ projected.diagnostics.push(...failures.map((entry) => ({ code: entry.error.code, severity: 'error', message: safePublicMessage(entry.error.message), subject: { sourceId: entry.sourceId } })));
2299
+ io.result?.(projected);
2105
2300
  });
2106
- config
2107
- .command('reset')
2108
- .argument('[plugin]')
2109
- .option('-s, --scope <scope>', 'project or user')
2110
- .option('--local', 'reset only the current project local override layer', false)
2111
- .option('-y, --yes', 'confirm destructive reset', false)
2112
- .option('-j, --json', 'print receipt as JSON', false)
2113
- .option('-v, --verbose', 'show command diagnostics', false)
2114
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2115
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2116
- .action(async (pluginName, rawOptions) => {
2117
- const context = createActionContext('config:reset', rawOptions);
2118
- let outcome;
2119
- try {
2120
- outcome = await runActionWithContext(context, async () => {
2121
- const execute = async (selectedPlugin, selectedScope, projectLayer, confirmed) => {
2122
- if (!confirmed) {
2123
- throw new Error(`Reset requires confirmation. Re-run \`aw config reset ${selectedPlugin} -s ${selectedScope}${projectLayer === 'local' ? ' --local' : ''} --yes\` to delete this store.`);
2301
+ const context = (name, raw = {}) => createCliExecutionContext({ ...options, io, interactive: false, reporter: options.reporter ?? createNoopReporter(), diagnostics: toCliDiagnosticsOptions(name, raw, options.diagnostics) });
2302
+ for (const name of ['install', 'remove', 'sync']) {
2303
+ const cmd = plugin.command(name).argument(name === 'sync' ? '[plugins...]' : '<plugins...>');
2304
+ if (name !== 'sync')
2305
+ cmd.addOption(strictValueOption('--scope <scope>', 'Requirement or physical scope', ['user', 'project']).makeOptionMandatory());
2306
+ cmd.addOption(strictValueOption('--context <context>', 'User or current project context', ['user', 'project']))
2307
+ .option('--target <target>', 'Select an execution target', collectUniqueOption)
2308
+ .option('-y, --yes', 'Confirm the listed effects');
2309
+ if (name !== 'sync')
2310
+ cmd.addOption(strictValueOption('--only <mode>', 'Limit the effects', name === 'install' ? ['requirements'] : ['requirements', 'outputs']));
2311
+ if (name === 'remove')
2312
+ cmd.option('--delete-config', 'Delete all local plugin configuration').option('--force', 'Recover provably owned damaged output');
2313
+ if (name !== 'remove')
2314
+ cmd.option('--script-timeout <ms>', 'Plugin script timeout');
2315
+ if (name === 'sync')
2316
+ cmd.option('--rebuild', 'Rebuild selected owned output').option('--refresh', 'Refresh required Catalog sources');
2317
+ cmd.action(async (plugins, raw) => {
2318
+ io.result?.(await runPublicLifecycle(name, plugins, { ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context(`plugin.${name}`, raw)));
2319
+ });
2320
+ }
2321
+ plugin.command('list').description('List available plugins or direct requirements')
2322
+ .option('--requested', 'List direct requirement roots')
2323
+ .addOption(strictValueOption('--scope <scope>', 'Requirement scope', ['user', 'project']))
2324
+ .action(async (raw) => { io.result?.(await runPublicPluginList({ ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.list', raw))); });
2325
+ plugin.command('show').description('Show one plugin').argument('<plugin>')
2326
+ .action(async (selector) => { io.result?.(await runPublicPluginShow(selector, { cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.show'))); });
2327
+ plugin.command('status').description('Inspect requirements, outputs, and coverage').argument('[plugins...]')
2328
+ .addOption(strictValueOption('--context <context>', 'Observation context', ['user', 'project']))
2329
+ .action(async (plugins, raw) => { io.result?.(await runPublicPluginStatus(plugins, { ...raw, cwd: options.cwd ?? process.cwd(), env: options.env, cliVersion: resolveCliVersion() }, context('plugin.status', raw))); });
2330
+ devPlugin.command('remove').description('Delete one owned plugin source tree').argument('<plugin>')
2331
+ .option('--workspace-root <path>', 'Catalog Workspace root').option('-y, --yes', 'Confirm source deletion');
2332
+ devPlugin.command('status').description('Check source plugin version policy').argument('[plugin]')
2333
+ .option('--all', 'Check all source plugins').option('--base <ref>', 'Git comparison base').option('--workspace-root <path>', 'Catalog Workspace root');
2334
+ find(devPlugin, 'build').option('-y, --yes', 'Confirm replacement of generated output');
2335
+ find(catalog, 'build').option('-y, --yes', 'Confirm replacement of generated output');
2336
+ const scriptRoutes = {
2337
+ 'dev.plugin.create': ['plugin', 'init'], 'dev.plugin.validate': ['plugin', 'validate'],
2338
+ 'dev.plugin.remove': ['plugin', 'remove'], 'dev.plugin.status': ['plugin', 'status'],
2339
+ 'dev.skill.create': ['plugin', 'add-skill'], 'dev.skill.validate': ['skill', 'validate'],
2340
+ };
2341
+ const attach = (parent) => {
2342
+ for (const cmd of parent.commands) {
2343
+ const id = commandId(cmd);
2344
+ if (scriptRoutes[id])
2345
+ cmd.action(async (...args) => {
2346
+ const selected = args.at(-1);
2347
+ const raw = selected.opts();
2348
+ const tokens = [...scriptRoutes[id], ...(id === 'dev.skill.create' ? [String(raw.plugin)] : selected.args)];
2349
+ for (const option of selected.options) {
2350
+ const value = selected.getOptionValue(option.attributeName());
2351
+ if (['json', 'plugin', 'verbose', 'debug', 'logFile'].includes(option.attributeName()) || value === undefined || value === false && !option.negate || value === true && option.negate)
2352
+ continue;
2353
+ tokens.push(option.long);
2354
+ if (value !== true && !option.negate)
2355
+ tokens.push(String(value));
2356
+ }
2357
+ const hasProtocol = !['dev.plugin.create', 'dev.skill.create'].includes(id);
2358
+ if (hasProtocol)
2359
+ tokens.push('--json');
2360
+ if (['dev.plugin.remove', 'dev.plugin.status'].includes(id) && !raw.workspaceRoot) {
2361
+ const workspace = await resolveCatalogWorkspaceRoot({ cwd: options.cwd ?? process.cwd(), mode: 'existing', env: options.env });
2362
+ tokens.push('--workspace-root', workspace.workspaceRoot);
2124
2363
  }
2125
- return withResolvedConfigMutationPlugin(context, selectedPlugin, async ({ pluginId, source, plugin }, awHomeMutationToken) => {
2126
- const affectedFields = await describeResetAffectedFields({
2127
- pluginName: plugin.manifest.name,
2128
- plugin,
2129
- scope: selectedScope,
2130
- projectLayer,
2131
- cwd: context.cwd,
2132
- env: context.env,
2133
- });
2134
- const resetReceipt = await resetPluginConfigWithHelper({
2135
- pluginName: plugin.manifest.name,
2136
- scope: selectedScope,
2137
- projectLayer,
2138
- cwd: context.cwd,
2139
- env: context.env,
2140
- nativeCliRunner: context.nativeCliRunner,
2141
- rebuildRuntime: { ...context, awHomeMutationToken },
2142
- awHomeMutationToken,
2143
- plugin,
2144
- });
2145
- return {
2146
- ok: resetReceipt.overallState === 'succeeded',
2147
- receiptSchemaVersion: 4,
2148
- command: 'config:reset',
2149
- ...resetReceipt,
2150
- plugin: plugin.manifest.name,
2151
- pluginName: plugin.manifest.name,
2152
- pluginId,
2153
- sourceId: source.sourceId,
2154
- sourceIdentity: source.sourceIdentity,
2155
- affectedFields,
2156
- };
2157
- }).catch((error) => {
2158
- const message = error instanceof Error ? error.message : String(error);
2159
- if (message.includes('Catalog source')
2160
- || message.startsWith('Cannot resolve required catalog sources:')) {
2161
- throw new Error(`sourceMissing: ${selectedPlugin} source is unavailable; config store was not changed.`);
2364
+ let protocol = '';
2365
+ let scriptDiagnostics = '';
2366
+ exit.exitCode = await runAuthoringCliAdapter(tokens, { ...options, interactive: false, io: { stdout: (text) => { if (hasProtocol)
2367
+ protocol += text;
2368
+ else
2369
+ io.stderr(text); }, stderr: (text) => { scriptDiagnostics += text; io.stderr(text); } } });
2370
+ if (hasProtocol && protocol.trim()) {
2371
+ let value;
2372
+ try {
2373
+ value = JSON.parse(protocol);
2162
2374
  }
2163
- if (message.includes('does not exist in the required catalog source set')) {
2164
- throw new Error(`configSchemaUnavailable: Plugin "${selectedPlugin}" is unavailable; config store was not changed.`);
2375
+ catch {
2376
+ throw new Error('The authoring tool returned invalid structured output.');
2165
2377
  }
2166
- throw error;
2167
- });
2168
- };
2169
- const scope = resolveConfigWriteScope(rawOptions.scope);
2170
- const projectLayer = resolveConfigProjectLayer(rawOptions);
2171
- const needsWizard = pluginName === undefined || rawOptions.yes !== true;
2172
- if (!needsWizard) {
2173
- return {
2174
- cancelled: false,
2175
- value: await execute(pluginName, scope, projectLayer, true),
2176
- };
2177
- }
2178
- if (!isWizardAvailable(context, rawOptions)) {
2179
- if (!pluginName)
2180
- throw new Error(configCommandUsage('reset'));
2181
- return {
2182
- cancelled: false,
2183
- value: await execute(pluginName, scope, projectLayer, false),
2184
- };
2185
- }
2186
- const currentCandidates = pluginName ? [] : await loadWizardCandidates(context, {});
2187
- const candidatesByScope = new Map();
2188
- if (!pluginName && (rawOptions.scope === undefined || scope === 'user')) {
2189
- candidatesByScope.set('user', mergeWizardCandidates(currentCandidates, await loadStoredConfigWizardCandidates(context, [{ scope: 'user', projectLayer: 'shared' }], { includeEmptyStores: true })));
2190
- }
2191
- if (!pluginName && (rawOptions.scope === undefined || scope === 'project')) {
2192
- candidatesByScope.set('project', mergeWizardCandidates(currentCandidates, await loadStoredConfigWizardCandidates(context, [{ scope: 'project', projectLayer }], { includeEmptyStores: true })));
2193
- }
2194
- const candidates = mergeWizardCandidates(candidatesByScope.get('user') ?? [], candidatesByScope.get('project') ?? []);
2195
- if (!pluginName && candidates.length === 0) {
2196
- throw new Error('No plugin config candidates exist in the selected location.');
2197
- }
2198
- const result = await runCommandWizard(context, {
2199
- command: 'config:reset',
2200
- candidates,
2201
- initial: { plugins: pluginName ? [pluginName] : [], scope, projectLayer },
2202
- pluginMode: pluginName ? 'none' : 'single',
2203
- promptForScope: rawOptions.scope === undefined,
2204
- destructive: true,
2205
- isPluginVisible: (candidate, selection) => candidatesByScope
2206
- .get(selection.scope ?? 'user')
2207
- ?.some((entry) => entry.pluginName === candidate.pluginName) !== false,
2208
- ...equivalentConfigCommandProjection((selection) => ({
2209
- command: 'reset',
2210
- plugin: selection.plugins[0],
2211
- scope: selection.scope ?? 'user',
2212
- projectLayer: selection.projectLayer,
2213
- confirmed: true,
2214
- })),
2215
- resultState: overallResultState,
2216
- execute: (selection) => execute(selection.plugins[0], selection.scope ?? 'user', selection.projectLayer ?? 'shared', true),
2378
+ io.result?.(value);
2379
+ }
2380
+ else
2381
+ io.result?.({ ok: exit.exitCode === 0, pluginName: raw.plugin ?? selected.args[0], workspaceRoot: raw.workspaceRoot ?? options.cwd, ...(exit.exitCode ? { errors: [{ code: 'authoringFailed', message: scriptDiagnostics.trim() || 'The authoring tool did not complete.' }] } : {}) });
2217
2382
  });
2218
- return result.cancelled
2219
- ? { cancelled: true }
2220
- : { cancelled: false, value: result.value };
2221
- });
2383
+ if (!cmd.options.some((option) => option.long === '--json'))
2384
+ cmd.option('-j, --json', 'Output one JSON result');
2385
+ const json = cmd.options.find((option) => option.long === '--json');
2386
+ json.makeOptionMandatory(false);
2387
+ if (!json.short)
2388
+ json.short = '-j';
2389
+ if (!cmd.options.some((option) => option.long === '--verbose'))
2390
+ cmd.option('-v, --verbose', 'Show additional details');
2391
+ if (!cmd.options.some((option) => option.long === '--debug'))
2392
+ cmd.option('-D, --debug', 'Write diagnostic logs');
2393
+ if (!cmd.options.some((option) => option.long === '--log-file'))
2394
+ cmd.option('--log-file <path>', 'Diagnostic log path');
2395
+ attach(cmd);
2222
2396
  }
2223
- catch (error) {
2224
- writeConfigMutationFailure('config:reset', pluginName, rawOptions.json === true, error);
2225
- return;
2397
+ };
2398
+ program.option('-j, --json', 'Output one JSON result').option('-v, --verbose', 'Show additional details').option('-D, --debug', 'Write diagnostic logs').option('--log-file <path>', 'Diagnostic log path');
2399
+ program.command('tui').description('Open the interactive console').action(() => undefined);
2400
+ attach(program);
2401
+ program.hook('preAction', (_root, action) => { action.setOptionValue('json', true); });
2402
+ }
2403
+ function resolveRegisteredCommand(program, argv) {
2404
+ let current = program;
2405
+ let commandIndex = -1;
2406
+ for (let index = 0; index < argv.length; index++) {
2407
+ const token = argv[index];
2408
+ if (token === '--')
2409
+ break;
2410
+ if (token.startsWith('-')) {
2411
+ const option = [...current.options, ...program.options].find((candidate) => candidate.long === token.split('=')[0] || candidate.short === token);
2412
+ if (option?.required && !token.includes('='))
2413
+ index++;
2414
+ continue;
2226
2415
  }
2227
- if (outcome.cancelled)
2228
- return;
2229
- const receipt = outcome.value;
2230
- if (rawOptions.json) {
2231
- writeJsonReceipt(io.stdout, receipt);
2416
+ const child = current.commands.find((entry) => entry.name() === token);
2417
+ if (child) {
2418
+ current = child;
2419
+ commandIndex = index;
2232
2420
  }
2233
- else {
2234
- writeLine(io.stdout, receipt.deleted
2235
- ? `已重置 ${receipt.plugin} 的${configLayerLabel(receipt.scope, receipt.projectLayer)}配置。`
2236
- : `${receipt.plugin} 没有可重置的${configLayerLabel(receipt.scope, receipt.projectLayer)}配置。`);
2237
- if (receipt.projectLayer === 'local') {
2238
- writeProjectLocalConfigNotice(io.stdout);
2239
- }
2240
- writeConfigApplyNotice(io.stderr, receipt);
2241
- }
2242
- commandExitState.exitCode = receipt.overallState === 'failed' ? 1 : 0;
2421
+ else if (current.commands.length === 0 || current.registeredArguments.length > 0)
2422
+ break;
2423
+ else
2424
+ return { command: null, index: commandIndex };
2425
+ }
2426
+ return { command: current, index: commandIndex };
2427
+ }
2428
+ function helpResult(program, selected) {
2429
+ return commandResult('help', {
2430
+ command: commandId(selected) || 'aw', description: selected.description(),
2431
+ arguments: selected.registeredArguments.map((argument) => ({ name: argument.name(), required: argument.required, variadic: argument.variadic, description: argument.description })),
2432
+ options: [...selected.options, ...(selected === program ? [] : program.options)].map((option) => ({ flags: option.flags, description: option.description, required: option.mandatory, choices: option.argChoices ?? null, conflicts: [] })),
2433
+ commands: selected.commands.map((command) => ({ command: commandId(command), description: command.description() })),
2434
+ resultSchema: { schemaVersion: 1, statuses: ['success', 'partial', 'blocked', 'failed'] },
2435
+ rules: commandId(selected) === 'plugin.install' ? ['--scope is required.', '--only requirements cannot use --target or --script-timeout.'] : commandId(selected) === 'plugin.remove' ? ['--scope is required.', '--only outputs requires --target.', '--force requires --only outputs.', '--delete-config cannot use --only.'] : [],
2436
+ effects: selected.options.some((option) => option.long === '--yes') ? ['Important effects require --yes.'] : [],
2437
+ examples: [selected === program ? ['aw', 'plugin', 'list'] : ['aw', ...commandId(selected).split('.'), '--help']],
2243
2438
  });
2244
- program
2245
- .command('status')
2246
- .argument('[plugins...]')
2247
- .option('-s, --scope <scope>', 'filter by scope')
2248
- .option('-p, --platform <platform>', 'filter by platform')
2249
- .option('-v, --verbose', 'show status details and command diagnostics', false)
2250
- .option('-D, --debug', 'write debug diagnostics to a log file', false)
2251
- .option('--log-file <path>', 'write debug diagnostics to the specified file')
2252
- .option('-j, --json', 'print status as JSON', false)
2253
- .action(async (plugins, rawOptions) => {
2254
- const context = createActionContext('status', rawOptions);
2255
- const result = await runActionWithContext(context, () => statusCommandV4({
2256
- plugins: plugins ?? [],
2257
- cwd,
2258
- env: context.env,
2259
- cliVersion: resolveCliVersion(),
2260
- platform: rawOptions.platform,
2261
- scope: rawOptions.scope,
2262
- json: rawOptions.json,
2263
- verbose: rawOptions.verbose,
2264
- }));
2265
- commandExitState.exitCode = result.hasErrors ? 1 : 0;
2266
- writeLine(io.stdout, result.output);
2267
- for (const source of result.payload.catalog.sources) {
2268
- if (source.error)
2269
- writeLine(io.stderr, `${source.id}: ${source.error}`);
2270
- }
2271
- for (const error of result.payload.errors) {
2272
- if (error.code !== 'nativeStateUnreadable' && error.code !== 'stateInventoryFailed') {
2273
- writeLine(io.stderr, error.message);
2439
+ }
2440
+ function scanPresentation(program, argv) {
2441
+ const result = { json: false, help: false, version: false };
2442
+ let command = program;
2443
+ for (let index = 0; index < argv.length; index++) {
2444
+ const token = argv[index];
2445
+ if (token === '--')
2446
+ break;
2447
+ if (!token.startsWith('-')) {
2448
+ command = command.commands.find((entry) => entry.name() === token) ?? command;
2449
+ continue;
2450
+ }
2451
+ const available = [...command.options, ...program.options];
2452
+ if (token.startsWith('--')) {
2453
+ const flag = token.split('=')[0];
2454
+ const option = available.find((entry) => entry.long === flag);
2455
+ if (flag === '--json')
2456
+ result.json = true;
2457
+ if (flag === '--help')
2458
+ result.help = true;
2459
+ if (flag === '--version' && !option?.required)
2460
+ result.version = true;
2461
+ if (option?.required && !token.includes('='))
2462
+ index++;
2463
+ }
2464
+ else {
2465
+ for (let offset = 1; offset < token.length; offset++) {
2466
+ const flag = `-${token[offset]}`;
2467
+ const option = available.find((entry) => entry.short === flag);
2468
+ if (flag === '-j')
2469
+ result.json = true;
2470
+ if (flag === '-h')
2471
+ result.help = true;
2472
+ if (flag === '-V')
2473
+ result.version = true;
2474
+ if (option?.required) {
2475
+ if (offset === token.length - 1)
2476
+ index++;
2477
+ break;
2478
+ }
2274
2479
  }
2275
2480
  }
2276
- });
2277
- Object.assign(program, { __awCommandExitState: commandExitState });
2278
- return program;
2279
- }
2280
- function handleCliError(error, writeError) {
2281
- if (error instanceof CommanderError) {
2282
- return error.exitCode;
2283
- }
2284
- if (isCommandWarningError(error)) {
2285
- writeWarnings(writeError, error.warnings);
2286
- writeLine(writeError, error.message);
2287
- return error.exitCode;
2288
2481
  }
2289
- writeLine(writeError, error instanceof Error ? error.message : String(error));
2290
- return 1;
2482
+ return result;
2291
2483
  }
2292
2484
  export async function runCli(argv, options = {}) {
2293
- const io = {
2294
- ...createDefaultIo(),
2295
- ...options.io,
2485
+ const interruption = createPublicCommandInterruption();
2486
+ const io = { ...createDefaultIo(), ...options.io };
2487
+ const delimiter = argv.indexOf('--');
2488
+ const awArgs = delimiter < 0 ? argv : argv.slice(0, delimiter);
2489
+ const context = createCliExecutionContext({ ...options, io });
2490
+ let receipt;
2491
+ const stderr = [];
2492
+ const commandOptions = { ...options, interactive: false, io: {
2493
+ stdout: (text) => { stderr.push(text); }, stderr: (text) => { stderr.push(text); }, result: (value) => { receipt = value; },
2494
+ } };
2495
+ const program = buildProgram(commandOptions);
2496
+ const presentation = scanPresentation(program, awArgs);
2497
+ const json = presentation.json;
2498
+ const resolvedCommand = resolveRegisteredCommand(program, awArgs);
2499
+ const selected = resolvedCommand.command;
2500
+ const id = selected && selected !== program ? commandId(selected) : null;
2501
+ const controlledInterrupt = ['plugin.install', 'plugin.remove', 'plugin.sync',
2502
+ 'dev.plugin.create', 'dev.plugin.validate', 'dev.plugin.remove', 'dev.plugin.status',
2503
+ 'dev.skill.create', 'dev.skill.validate'].includes(id ?? '');
2504
+ if (controlledInterrupt) {
2505
+ commandOptions.interruption = interruption;
2506
+ commandOptions.signal = interruption.signal;
2507
+ }
2508
+ if (id === 'command.run' && !presentation.help)
2509
+ return runManagedCommandCli(['run', ...argv.slice(resolvedCommand.index + 1)], { ...context, interactive: false }, { cliEntry: fileURLToPath(import.meta.url), cliVersion: resolveCliVersion() });
2510
+ let confirmation = null;
2511
+ const emit = (result, invalid = false) => {
2512
+ if (result.diagnostics.some((diagnostic) => diagnostic.code === 'catalogWorkspaceMissing')) {
2513
+ const workspaceRoot = selected?.getOptionValue('workspaceRoot');
2514
+ result.nextActions = result.nextActions.filter((action) => action.kind !== 'command'
2515
+ || action.argv.slice(0, 4).join(' ') !== 'aw dev catalog create');
2516
+ result.nextActions.push({ kind: 'command',
2517
+ argv: ['aw', 'dev', 'catalog', 'create', ...(typeof workspaceRoot === 'string' ? ['--workspace-root', workspaceRoot] : [])],
2518
+ reason: 'Create a Catalog Workspace explicitly before running authoring commands.', requiresConfirmation: false });
2519
+ }
2520
+ io.stdout(json ? `${JSON.stringify(result)}\n` : renderPublicResult(result, awArgs.includes('--verbose') || awArgs.includes('-v')));
2521
+ for (const diagnostic of result.diagnostics)
2522
+ io.stderr(`${diagnostic.code}: ${diagnostic.message}\n`);
2523
+ if (options.diagnostics?.verbose || awArgs.includes('--verbose'))
2524
+ for (const line of stderr)
2525
+ io.stderr(`${safePublicMessage(line.trim())}\n`);
2526
+ return interruption.exitCode ? interruption.cleanupFailed ? 1 : interruption.exitCode : publicExitCode(result, invalid);
2296
2527
  };
2297
- const jsonAuthoringCommand = argv.includes('--json')
2298
- && ((argv[0] === 'catalog' && ['init', 'version', 'build', 'validate', 'status', 'publish'].includes(argv[1] ?? ''))
2299
- || (argv[0] === 'plugin' && ['build', 'test'].includes(argv[1] ?? '')))
2300
- ? `${argv[0]}:${argv[1]}`
2301
- : null;
2528
+ if (presentation.version)
2529
+ return emit(commandResult('version', { version: resolveCliVersion(), resultSchemaVersion: 1 }));
2530
+ if (selected && presentation.help || argv.length === 0 && !context.interactive || selected === program && json) {
2531
+ const target = selected ?? program;
2532
+ if (!json) {
2533
+ target.configureOutput({ writeOut: io.stdout });
2534
+ target.outputHelp();
2535
+ return 0;
2536
+ }
2537
+ return emit(helpResult(program, target));
2538
+ }
2539
+ let bareOptions;
2302
2540
  try {
2303
- const authoringScriptByCommand = {
2304
- init: 'init-plugin.mjs',
2305
- 'add-skill': 'add-skill.mjs',
2306
- remove: 'remove-plugin.mjs',
2307
- validate: 'validate-plugin.mjs',
2308
- status: 'plugin-status.mjs',
2309
- 'check-versions': 'check-plugin-versions.mjs',
2310
- };
2311
- const authoringScript = argv[0] === 'plugin'
2312
- ? authoringScriptByCommand[argv[1] ?? '']
2313
- : argv[0] === 'skill' && argv[1] === 'validate'
2314
- ? 'validate-skill.mjs'
2315
- : undefined;
2316
- if (authoringScript && !argv.includes('--help') && !argv.includes('-h')) {
2317
- const authoringArgs = argv.slice(2);
2318
- if (argv[0] === 'plugin'
2319
- && argv[1] === 'validate'
2320
- && !authoringArgs.some((token) => token === '--workspace-root' || token.startsWith('--workspace-root='))) {
2321
- authoringArgs.push('--workspace-root', options.cwd ?? process.cwd());
2541
+ bareOptions = parseBareConsoleOptions(argv);
2542
+ }
2543
+ catch {
2544
+ return emit(commandResult(null, {}, { status: 'failed', diagnostics: [{ code: 'invalidArguments', severity: 'error', message: 'A diagnostic option requires a value.' }] }), true);
2545
+ }
2546
+ if (bareOptions !== null || id === 'tui') {
2547
+ if (id === 'tui') {
2548
+ try {
2549
+ await program.parseAsync(['node', 'aw', ...argv]);
2322
2550
  }
2323
- return runAuthoringScript({
2324
- scriptName: authoringScript,
2325
- args: authoringArgs,
2326
- cwd: options.cwd ?? process.cwd(),
2327
- env: options.env ?? process.env,
2328
- io,
2329
- });
2330
- }
2331
- if (argv.some((token) => token === '--subdir' || token.startsWith('--subdir='))
2332
- && argv.includes('--no-subdir')) {
2333
- const message = 'option --subdir cannot be used with option --no-subdir';
2334
- if (argv.includes('--json') && argv[0] === 'catalog' && argv[1] === 'source' && argv[2] === 'update') {
2335
- writeJsonReceipt(io.stdout, {
2336
- receiptSchemaVersion: 4,
2337
- command: 'catalog:source:update',
2338
- ok: false,
2339
- changed: false,
2340
- sourceId: argv[3] ?? '',
2341
- references: [],
2342
- errors: [{ code: 'catalogSourceOptionConflict', message }],
2343
- });
2551
+ catch {
2552
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'invalidArguments', severity: 'error', message: 'Invalid TUI arguments.' }] }), true);
2344
2553
  }
2345
- writeLine(io.stderr, `error: ${message}`);
2346
- return 1;
2347
2554
  }
2348
- const bareConsoleOptions = parseBareConsoleOptions(argv);
2349
- if (bareConsoleOptions) {
2350
- const context = createCliExecutionContext({
2351
- ...options,
2352
- io,
2353
- env: options.env ?? process.env,
2354
- diagnostics: {
2355
- ...toCliDiagnosticsOptions('console', bareConsoleOptions, options.diagnostics),
2356
- metadata: {
2357
- ...options.diagnostics?.metadata,
2358
- argCount: argv.length,
2359
- },
2360
- },
2361
- });
2362
- if (!context.interactive) {
2363
- writeLine(io.stderr, formatInteractiveConsoleUnavailableMessage(context));
2364
- return 1;
2365
- }
2366
- return await runActionWithContext(context, () => runConsoleController(context));
2555
+ if (json)
2556
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'invalidOptionCombination', severity: 'error', message: 'tui cannot use --json.' }] }), true);
2557
+ if (!context.interactive)
2558
+ return emit(commandResult('tui', {}, { status: 'blocked', diagnostics: [{ code: 'interactiveTerminalRequired', severity: 'error', message: 'The TUI requires an interactive terminal.' }] }));
2559
+ const tuiContext = createCliExecutionContext({ ...options, io, diagnostics: toCliDiagnosticsOptions('console', bareOptions ?? {}, options.diagnostics) });
2560
+ try {
2561
+ return await runActionWithContext(tuiContext, () => runConsoleController(tuiContext));
2367
2562
  }
2368
- const program = buildProgram({
2369
- ...options,
2370
- io,
2371
- diagnostics: {
2372
- ...options.diagnostics,
2373
- metadata: {
2374
- ...options.diagnostics?.metadata,
2375
- argCount: argv.length,
2376
- },
2377
- },
2563
+ catch (error) {
2564
+ return emit(commandResult('tui', {}, { status: 'failed', diagnostics: [{ code: 'tuiFailed', severity: 'error', message: safePublicMessage(error instanceof Error ? error.message : String(error)) }] }));
2565
+ }
2566
+ }
2567
+ // Only these adapters carry cancellation through every long-running child.
2568
+ // Other routes retain Node's normal signal termination until their domain
2569
+ // runner provides the same cleanup contract. Managed run and TUI exited above.
2570
+ const stopListening = controlledInterrupt ? interruption.listen() : () => undefined;
2571
+ try {
2572
+ program.hook('preAction', (_root, command) => {
2573
+ interruption.signal.throwIfAborted();
2574
+ const raw = command.opts();
2575
+ const current = commandId(command);
2576
+ if (current === 'dev.eval.prepare')
2577
+ for (const field of ['runs', 'timeoutMs'])
2578
+ if (raw[field] !== undefined && (!/^[1-9][0-9]*$/u.test(raw[field]) || !Number.isSafeInteger(Number(raw[field]))))
2579
+ throw new WriteCommandRequestError(`${field} must be a positive safe integer.`);
2580
+ if (current === 'dev.plugin.capabilities' && raw.surface !== undefined)
2581
+ normalizeWriteRequest(() => parsePluginCapabilitySurface(raw.surface));
2582
+ if (current === 'dev.catalog.version') {
2583
+ const version = command.args[0];
2584
+ if (version && raw.bump)
2585
+ throw new WriteCommandRequestError('Choose an exact version or --bump, not both.');
2586
+ if (raw.bump && !['patch', 'minor', 'major'].includes(raw.bump))
2587
+ throw new WriteCommandRequestError('--bump must be patch, minor, or major.');
2588
+ if (version && !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-beta\.(0|[1-9][0-9]*))?$/u.test(version))
2589
+ throw new WriteCommandRequestError('Use a stable version or x.y.z-beta.N.');
2590
+ }
2591
+ if (current === 'source.add' && ((raw.git === undefined) === (raw.path === undefined)))
2592
+ throw new WriteCommandRequestError('Choose exactly one of --git or --path.');
2593
+ if (current === 'source.update' && awArgs.includes('--auto-check') && awArgs.includes('--no-auto-check'))
2594
+ throw new WriteCommandRequestError('--auto-check cannot use --no-auto-check.');
2595
+ if (current === 'source.update' && raw.subdir !== undefined && awArgs.includes('--no-subdir') && awArgs.some((arg) => arg === '--subdir' || arg.startsWith('--subdir=')))
2596
+ throw new WriteCommandRequestError('--subdir cannot use --no-subdir.');
2597
+ if (current === 'plugin.config.set' && [raw.valueJson !== undefined, raw.valueStdin === true, raw.preset !== undefined].filter(Boolean).length !== 1)
2598
+ throw new WriteCommandRequestError('Choose exactly one of --value-json, --value-stdin, or --preset.');
2599
+ let effect;
2600
+ if (current === 'plugin.config.reset')
2601
+ effect = { code: 'deletePluginConfig', message: 'Delete the selected local plugin configuration.', subject: { pluginId: command.args[0], scope: 'user' }, impact: 'user-wide' };
2602
+ if (current === 'dev.plugin.remove')
2603
+ effect = { code: 'deletePluginSource', message: 'Delete the selected plugin source tree.', subject: { pluginId: command.args[0] }, impact: 'selected-scope' };
2604
+ if (current === 'dev.catalog.publish.apply' && !/^sha256:[0-9a-f]{64}$/u.test(raw.expectedPlanDigest ?? ''))
2605
+ throw new WriteCommandRequestError('Use the exact --expected-plan-digest returned by dev catalog publish plan.');
2606
+ if (current === 'dev.catalog.publish.apply')
2607
+ effect = { code: 'publishRemote', message: 'Publish the prepared Catalog to the remote.', impact: 'shared' };
2608
+ if ((current === 'dev.catalog.build' || current === 'dev.plugin.build') && raw.force)
2609
+ effect = { code: 'removeOwnedOutput', message: 'Replace existing generated output.', impact: 'selected-scope' };
2610
+ if (effect) {
2611
+ confirmation = { required: true, provided: raw.yes === true, effects: [effect] };
2612
+ if (!raw.yes)
2613
+ throw Object.assign(new Error('Repeat the command with --yes to confirm the listed effects.'), { code: 'confirmationRequired' });
2614
+ }
2378
2615
  });
2379
2616
  await program.parseAsync(['node', 'aw', ...argv]);
2380
- return program.__awCommandExitState?.exitCode ?? 0;
2617
+ const exitCode = program.__awCommandExitState.exitCode;
2618
+ if (receipt === undefined) {
2619
+ if (selected?.commands.length)
2620
+ return emit(helpResult(program, selected));
2621
+ throw new Error('The command did not return a result.');
2622
+ }
2623
+ if (id === 'dev.plugin.test' && receipt && typeof receipt === 'object') {
2624
+ const logs = receipt;
2625
+ if (typeof logs.stdout === 'string')
2626
+ io.stderr(redactString(logs.stdout));
2627
+ if (typeof logs.stderr === 'string')
2628
+ io.stderr(redactString(logs.stderr));
2629
+ }
2630
+ const result = projectReceipt(id, receipt, { yes: awArgs.includes('--yes') || awArgs.includes('-y'), exitCode, confirmation });
2631
+ if (interruption.exitCode)
2632
+ result.diagnostics.push({ code: interruption.cleanupFailed ? 'processCleanupUnconfirmed' : 'operationInterrupted', severity: 'error', message: interruption.cleanupFailed ? 'Process cleanup could not be confirmed after interruption.' : 'The command was interrupted. Completed changes are retained in the result.' });
2633
+ if (result.status === 'success' && ['dev.plugin.create', 'dev.skill.create'].includes(id)) {
2634
+ const data = result.data;
2635
+ const name = typeof data.pluginName === 'string' ? data.pluginName : selected?.args[0];
2636
+ if (name)
2637
+ for (const action of ['validate', 'test', 'build'])
2638
+ result.nextActions.push({ kind: 'command', argv: ['aw', 'dev', 'plugin', action, `plugins/${name}`], reason: 'Check and build the new source.', requiresConfirmation: false });
2639
+ result.nextActions.push({ kind: 'command', argv: ['aw', 'dev', 'catalog', 'build'], reason: 'Build the Catalog after checking the source.', requiresConfirmation: false });
2640
+ }
2641
+ const invalid = result.diagnostics.some((diagnostic) => /invalidArguments|invalidOption|missingArgument|sensitiveConfigInputUnsupported/u.test(diagnostic.code));
2642
+ if (invalid && result.status !== 'partial') {
2643
+ result.status = 'failed';
2644
+ result.data = {};
2645
+ }
2646
+ return emit(result, invalid);
2381
2647
  }
2382
2648
  catch (error) {
2383
- if (jsonAuthoringCommand && error instanceof CommanderError) {
2384
- writeJsonReceipt(io.stdout, {
2385
- command: jsonAuthoringCommand,
2386
- ok: false,
2387
- errors: [{ code: 'invalidArguments', message: error.message }],
2388
- });
2389
- }
2390
- return handleCliError(error, io.stderr);
2649
+ if (error instanceof CommanderError && error.exitCode === 0)
2650
+ return emit(helpResult(program, selected ?? program));
2651
+ const argumentError = error instanceof CommanderError || error instanceof WriteCommandRequestError;
2652
+ const raw = id?.startsWith('plugin.config.') && !(error instanceof CommanderError) && !(error instanceof WriteCommandRequestError)
2653
+ ? configMutationFailure(error, options.env ?? process.env, options.cwd ?? process.cwd())
2654
+ : error;
2655
+ const code = argumentError ? error instanceof InvalidArgumentError || error instanceof CommanderError && error.code === 'commander.invalidArgument' ? 'invalidOptionValue' : 'invalidArguments' : raw.code ?? catalogGenerationErrorCode(error);
2656
+ const blocked = code === 'confirmationRequired' || /unavailable|missing|stale|conflict|unsupported|identityMismatch/iu.test(code);
2657
+ let message = raw.message ?? 'The operation failed.';
2658
+ if (error instanceof CommanderError) {
2659
+ const field = raw.message?.match(/--([a-z][a-z-]*)/u)?.[1];
2660
+ if (error.code === 'commander.unknownOption')
2661
+ message = field ? `Unknown option --${field}.` : 'Unknown option.';
2662
+ else if (error.code === 'commander.unknownCommand')
2663
+ message = 'Unknown command.';
2664
+ else if (error.code === 'commander.invalidArgument')
2665
+ message = field ? `Invalid value for --${field}.` : 'Invalid argument value.';
2666
+ else if (error.code === 'commander.excessArguments')
2667
+ message = 'Too many positional arguments.';
2668
+ }
2669
+ const preparedConfirmation = error?.confirmation ?? confirmation;
2670
+ const unknownAuthoringChanges = error?.authoringChanges === 'unknown';
2671
+ const data = { ...(preparedConfirmation ? { confirmation: preparedConfirmation } : {}), ...(unknownAuthoringChanges ? { changes: 'unknown' } : {}) };
2672
+ return emit(commandResult(id, data, { status: unknownAuthoringChanges ? 'partial' : blocked ? 'blocked' : 'failed', diagnostics: [{ code, severity: 'error', message: safePublicMessage(message, code), ...(code === 'invalidOptionValue' ? { subject: { field: raw.message?.match(/--([a-z][a-z-]*)/u)?.[1] ?? 'option' } } : {}) }], nextActions: code === 'confirmationRequired' ? [{ kind: 'manual', message: 'Review the effects and repeat the command with --yes.' }] : [] }), argumentError);
2673
+ }
2674
+ finally {
2675
+ stopListening();
2391
2676
  }
2392
2677
  }
2393
2678
  export async function main(argv = process.argv.slice(2), options = {}) {