@lesliechan721/aw 0.1.0-beta.9 → 0.1.0-beta.90

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 (829) 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 +221 -0
  5. package/dist/authoring/assets/aw-runtime-config.mjs.map +1 -0
  6. package/dist/authoring/assets/command-runtime-config.d.mts +9 -0
  7. package/dist/authoring/assets/command-runtime-config.mjs +134 -0
  8. package/dist/authoring/assets/command-runtime-config.mjs.map +1 -0
  9. package/dist/authoring/scripts/add-skill.mjs +15 -38
  10. package/dist/authoring/scripts/add-skill.mjs.map +1 -1
  11. package/dist/authoring/scripts/init-plugin.mjs +72 -96
  12. package/dist/authoring/scripts/init-plugin.mjs.map +1 -1
  13. package/dist/authoring/scripts/lib/plugin-root.mjs +4 -4
  14. package/dist/authoring/scripts/lib/plugin-root.mjs.map +1 -1
  15. package/dist/authoring/scripts/lib/plugin-version-check.d.mts +1 -0
  16. package/dist/authoring/scripts/lib/plugin-version-check.mjs +230 -9
  17. package/dist/authoring/scripts/lib/plugin-version-check.mjs.map +1 -1
  18. package/dist/authoring/scripts/lib/skill-scaffold.d.mts +2 -2
  19. package/dist/authoring/scripts/lib/skill-scaffold.mjs +4 -7
  20. package/dist/authoring/scripts/lib/skill-scaffold.mjs.map +1 -1
  21. package/dist/authoring/scripts/remove-plugin.mjs +1 -1
  22. package/dist/authoring/scripts/remove-plugin.mjs.map +1 -1
  23. package/dist/authoring/scripts/validate-plugin.mjs +396 -1997
  24. package/dist/authoring/scripts/validate-plugin.mjs.map +1 -1
  25. package/dist/authoring/scripts/validate-skill.mjs +1 -1
  26. package/dist/index.js +2 -6
  27. package/dist/index.js.map +1 -1
  28. package/dist/native-runtime/reader-runtime.mjs +34 -0
  29. package/dist/native-runtime/reader.d.mts +6 -0
  30. package/dist/native-runtime/reader.mjs +11 -0
  31. package/dist/scripts/aw-skill-eval-materializer.d.ts +11 -1
  32. package/dist/scripts/aw-skill-eval-materializer.js +118 -115
  33. package/dist/scripts/aw-skill-eval-materializer.js.map +1 -1
  34. package/dist/scripts/bundle-plugins.js +25 -7
  35. package/dist/scripts/bundle-plugins.js.map +1 -1
  36. package/dist/scripts/plugin-staging.d.ts +7 -7
  37. package/dist/scripts/plugin-staging.js +10 -8
  38. package/dist/scripts/plugin-staging.js.map +1 -1
  39. package/dist/scripts/plugin-test-reporter.d.mts +2 -0
  40. package/dist/scripts/plugin-test-reporter.mjs +21 -0
  41. package/dist/scripts/plugin-test-reporter.mjs.map +1 -0
  42. package/dist/scripts/test-plugin-scripts.d.ts +5 -0
  43. package/dist/scripts/test-plugin-scripts.js +284 -78
  44. package/dist/scripts/test-plugin-scripts.js.map +1 -1
  45. package/dist/scripts/test-workers.d.mts +24 -0
  46. package/dist/scripts/test-workers.mjs +59 -0
  47. package/dist/scripts/test-workers.mjs.map +1 -0
  48. package/dist/src/adapters/helpers.d.ts +7 -0
  49. package/dist/src/adapters/helpers.js.map +1 -1
  50. package/dist/src/authoring/workspace-commands.d.ts +3 -0
  51. package/dist/src/authoring/workspace-commands.js +7 -2
  52. package/dist/src/authoring/workspace-commands.js.map +1 -1
  53. package/dist/src/commands/aw-capabilities.d.ts +1 -1
  54. package/dist/src/commands/aw-capabilities.js +42 -21
  55. package/dist/src/commands/aw-capabilities.js.map +1 -1
  56. package/dist/src/commands/catalog-dev-source.d.ts +42 -3
  57. package/dist/src/commands/catalog-dev-source.js +351 -43
  58. package/dist/src/commands/catalog-dev-source.js.map +1 -1
  59. package/dist/src/commands/catalog-generation.d.ts +8 -0
  60. package/dist/src/commands/catalog-generation.js +1 -5
  61. package/dist/src/commands/catalog-generation.js.map +1 -1
  62. package/dist/src/commands/catalog-publication-inspection.d.ts +42 -3
  63. package/dist/src/commands/catalog-publication-inspection.js +379 -48
  64. package/dist/src/commands/catalog-publication-inspection.js.map +1 -1
  65. package/dist/src/commands/catalog-publication-journal.d.ts +23 -4
  66. package/dist/src/commands/catalog-publication-journal.js +165 -20
  67. package/dist/src/commands/catalog-publication-journal.js.map +1 -1
  68. package/dist/src/commands/catalog-publish.d.ts +34 -3
  69. package/dist/src/commands/catalog-publish.js +311 -165
  70. package/dist/src/commands/catalog-publish.js.map +1 -1
  71. package/dist/src/commands/catalog-source.d.ts +54 -8
  72. package/dist/src/commands/catalog-source.js +277 -15
  73. package/dist/src/commands/catalog-source.js.map +1 -1
  74. package/dist/src/commands/catalog-status.js +2 -2
  75. package/dist/src/commands/catalog-status.js.map +1 -1
  76. package/dist/src/commands/catalog-store.d.ts +104 -0
  77. package/dist/src/commands/catalog-store.js +685 -0
  78. package/dist/src/commands/catalog-store.js.map +1 -0
  79. package/dist/src/commands/catalog-workspace-resolution.d.ts +4 -0
  80. package/dist/src/commands/catalog-workspace-resolution.js +18 -3
  81. package/dist/src/commands/catalog-workspace-resolution.js.map +1 -1
  82. package/dist/src/commands/console.js +33 -20
  83. package/dist/src/commands/console.js.map +1 -1
  84. package/dist/src/commands/dependency-operation-plan.d.ts +14 -56
  85. package/dist/src/commands/dependency-operation-plan.js +90 -133
  86. package/dist/src/commands/dependency-operation-plan.js.map +1 -1
  87. package/dist/src/commands/deployment-confirmation.d.ts +11 -0
  88. package/dist/src/commands/deployment-confirmation.js +88 -0
  89. package/dist/src/commands/deployment-confirmation.js.map +1 -0
  90. package/dist/src/commands/init.js +1 -1
  91. package/dist/src/commands/init.js.map +1 -1
  92. package/dist/src/commands/intent-command.d.ts +34 -0
  93. package/dist/src/commands/intent-command.js +174 -0
  94. package/dist/src/commands/intent-command.js.map +1 -0
  95. package/dist/src/commands/lifecycle-command-package.d.ts +45 -0
  96. package/dist/src/commands/lifecycle-command-package.js +199 -0
  97. package/dist/src/commands/lifecycle-command-package.js.map +1 -0
  98. package/dist/src/commands/managed-commands.d.ts +41 -0
  99. package/dist/src/commands/managed-commands.js +404 -0
  100. package/dist/src/commands/managed-commands.js.map +1 -0
  101. package/dist/src/commands/offline-cleanup-evidence.d.ts +29 -3
  102. package/dist/src/commands/offline-cleanup-evidence.js +80 -10
  103. package/dist/src/commands/offline-cleanup-evidence.js.map +1 -1
  104. package/dist/src/commands/operation-plan.d.ts +191 -0
  105. package/dist/src/commands/operation-plan.js +96 -0
  106. package/dist/src/commands/operation-plan.js.map +1 -0
  107. package/dist/src/commands/operation-planner.d.ts +47 -0
  108. package/dist/src/commands/operation-planner.js +142 -0
  109. package/dist/src/commands/operation-planner.js.map +1 -0
  110. package/dist/src/commands/options.d.ts +11 -20
  111. package/dist/src/commands/options.js +31 -36
  112. package/dist/src/commands/options.js.map +1 -1
  113. package/dist/src/commands/permission-batch.d.ts +5 -0
  114. package/dist/src/commands/permission-batch.js +80 -0
  115. package/dist/src/commands/permission-batch.js.map +1 -0
  116. package/dist/src/commands/plugin-capabilities.js +96 -46
  117. package/dist/src/commands/plugin-capabilities.js.map +1 -1
  118. package/dist/src/commands/public-config-confirmation.d.ts +14 -0
  119. package/dist/src/commands/public-config-confirmation.js +73 -0
  120. package/dist/src/commands/public-config-confirmation.js.map +1 -0
  121. package/dist/src/commands/public-interruption.d.ts +9 -0
  122. package/dist/src/commands/public-interruption.js +23 -0
  123. package/dist/src/commands/public-interruption.js.map +1 -0
  124. package/dist/src/commands/public-lifecycle-result.d.ts +106 -0
  125. package/dist/src/commands/public-lifecycle-result.js +518 -0
  126. package/dist/src/commands/public-lifecycle-result.js.map +1 -0
  127. package/dist/src/commands/public-lifecycle.d.ts +27 -0
  128. package/dist/src/commands/public-lifecycle.js +563 -0
  129. package/dist/src/commands/public-lifecycle.js.map +1 -0
  130. package/dist/src/commands/public-plugin-query.d.ts +16 -0
  131. package/dist/src/commands/public-plugin-query.js +230 -0
  132. package/dist/src/commands/public-plugin-query.js.map +1 -0
  133. package/dist/src/commands/rebuild-command.d.ts +176 -25
  134. package/dist/src/commands/rebuild-command.js +3989 -1392
  135. package/dist/src/commands/rebuild-command.js.map +1 -1
  136. package/dist/src/commands/rebuild-integration.d.ts +133 -52
  137. package/dist/src/commands/rebuild-integration.js +1097 -2692
  138. package/dist/src/commands/rebuild-integration.js.map +1 -1
  139. package/dist/src/commands/rebuild-operations.d.ts +74 -23
  140. package/dist/src/commands/rebuild-operations.js +334 -227
  141. package/dist/src/commands/rebuild-operations.js.map +1 -1
  142. package/dist/src/commands/rebuild-platform-integration.d.ts +81 -0
  143. package/dist/src/commands/rebuild-platform-integration.js +1992 -0
  144. package/dist/src/commands/rebuild-platform-integration.js.map +1 -0
  145. package/dist/src/commands/reconcile-operation-plan.d.ts +31 -0
  146. package/dist/src/commands/reconcile-operation-plan.js +48 -0
  147. package/dist/src/commands/reconcile-operation-plan.js.map +1 -0
  148. package/dist/src/commands/review-inspection.d.ts +60 -0
  149. package/dist/src/commands/review-inspection.js +436 -0
  150. package/dist/src/commands/review-inspection.js.map +1 -0
  151. package/dist/src/commands/review-preparation.d.ts +51 -0
  152. package/dist/src/commands/review-preparation.js +400 -0
  153. package/dist/src/commands/review-preparation.js.map +1 -0
  154. package/dist/src/commands/runtime.d.ts +6 -6
  155. package/dist/src/commands/runtime.js +44 -24
  156. package/dist/src/commands/runtime.js.map +1 -1
  157. package/dist/src/commands/skill-eval.d.ts +8 -0
  158. package/dist/src/commands/skill-eval.js +126 -73
  159. package/dist/src/commands/skill-eval.js.map +1 -1
  160. package/dist/src/commands/status-v6.d.ts +185 -68
  161. package/dist/src/commands/status-v6.js +1592 -499
  162. package/dist/src/commands/status-v6.js.map +1 -1
  163. package/dist/src/commands/targets-command.d.ts +38 -0
  164. package/dist/src/commands/targets-command.js +182 -0
  165. package/dist/src/commands/targets-command.js.map +1 -0
  166. package/dist/src/commands/wizard.d.ts +8 -5
  167. package/dist/src/commands/wizard.js +7 -4
  168. package/dist/src/commands/wizard.js.map +1 -1
  169. package/dist/src/commands/write-commands.d.ts +9 -3
  170. package/dist/src/commands/write-commands.js +144 -44
  171. package/dist/src/commands/write-commands.js.map +1 -1
  172. package/dist/src/constants.d.ts +2 -3
  173. package/dist/src/constants.js +2 -3
  174. package/dist/src/constants.js.map +1 -1
  175. package/dist/src/eval/manifest-v1.d.ts +6 -2
  176. package/dist/src/eval/manifest-v1.js +58 -26
  177. package/dist/src/eval/manifest-v1.js.map +1 -1
  178. package/dist/src/generators/local-plugin.d.ts +4 -2
  179. package/dist/src/generators/local-plugin.js +207 -346
  180. package/dist/src/generators/local-plugin.js.map +1 -1
  181. package/dist/src/generators/permissions.d.ts +20 -2
  182. package/dist/src/generators/permissions.js +82 -15
  183. package/dist/src/generators/permissions.js.map +1 -1
  184. package/dist/src/index.d.ts +3 -33
  185. package/dist/src/index.js +1786 -1945
  186. package/dist/src/index.js.map +1 -1
  187. package/dist/src/intent/deployment-preferences.d.ts +63 -0
  188. package/dist/src/intent/deployment-preferences.js +170 -0
  189. package/dist/src/intent/deployment-preferences.js.map +1 -0
  190. package/dist/src/intent/diagnostics.d.ts +11 -0
  191. package/dist/src/intent/diagnostics.js +14 -0
  192. package/dist/src/intent/diagnostics.js.map +1 -0
  193. package/dist/src/intent/intent-codec.d.ts +19 -0
  194. package/dist/src/intent/intent-codec.js +117 -0
  195. package/dist/src/intent/intent-codec.js.map +1 -0
  196. package/dist/src/intent/intent-store.d.ts +43 -0
  197. package/dist/src/intent/intent-store.js +118 -0
  198. package/dist/src/intent/intent-store.js.map +1 -0
  199. package/dist/src/intent/scope-context.d.ts +35 -0
  200. package/dist/src/intent/scope-context.js +179 -0
  201. package/dist/src/intent/scope-context.js.map +1 -0
  202. package/dist/src/intent/work-context.d.ts +13 -0
  203. package/dist/src/intent/work-context.js +22 -0
  204. package/dist/src/intent/work-context.js.map +1 -0
  205. package/dist/src/output/command-receipt.d.ts +37 -86
  206. package/dist/src/output/command-receipt.js +257 -179
  207. package/dist/src/output/command-receipt.js.map +1 -1
  208. package/dist/src/output/component-delivery.d.ts +28 -0
  209. package/dist/src/output/component-delivery.js +138 -0
  210. package/dist/src/output/component-delivery.js.map +1 -0
  211. package/dist/src/output/public-result.d.ts +69 -0
  212. package/dist/src/output/public-result.js +403 -0
  213. package/dist/src/output/public-result.js.map +1 -0
  214. package/dist/src/output/rebuild-progress.d.ts +3 -0
  215. package/dist/src/output/rebuild-progress.js +34 -16
  216. package/dist/src/output/rebuild-progress.js.map +1 -1
  217. package/dist/src/output/receipt-projection.d.ts +7 -0
  218. package/dist/src/output/receipt-projection.js +664 -0
  219. package/dist/src/output/receipt-projection.js.map +1 -0
  220. package/dist/src/output/skill-invocation-notices.d.ts +18 -0
  221. package/dist/src/output/skill-invocation-notices.js +84 -0
  222. package/dist/src/output/skill-invocation-notices.js.map +1 -0
  223. package/dist/src/platforms/antigravity-permissions.d.ts +50 -0
  224. package/dist/src/platforms/antigravity-permissions.js +388 -0
  225. package/dist/src/platforms/antigravity-permissions.js.map +1 -0
  226. package/dist/src/platforms/capabilities.d.ts +17 -0
  227. package/dist/src/platforms/capabilities.js +328 -0
  228. package/dist/src/platforms/capabilities.js.map +1 -0
  229. package/dist/src/platforms/contracts.d.ts +402 -0
  230. package/dist/src/platforms/contracts.js +2 -0
  231. package/dist/src/platforms/contracts.js.map +1 -0
  232. package/dist/src/platforms/cursor-workspace-hook.d.ts +28 -0
  233. package/dist/src/platforms/cursor-workspace-hook.js +198 -0
  234. package/dist/src/platforms/cursor-workspace-hook.js.map +1 -0
  235. package/dist/src/platforms/discovery.d.ts +98 -0
  236. package/dist/src/platforms/discovery.js +777 -0
  237. package/dist/src/platforms/discovery.js.map +1 -0
  238. package/dist/src/platforms/grok-permission-config.d.ts +23 -0
  239. package/dist/src/platforms/grok-permission-config.js +184 -0
  240. package/dist/src/platforms/grok-permission-config.js.map +1 -0
  241. package/dist/src/platforms/grok-permission-document.d.ts +4 -0
  242. package/dist/src/platforms/grok-permission-document.js +145 -0
  243. package/dist/src/platforms/grok-permission-document.js.map +1 -0
  244. package/dist/src/platforms/grok-permissions.d.ts +17 -0
  245. package/dist/src/platforms/grok-permissions.js +311 -0
  246. package/dist/src/platforms/grok-permissions.js.map +1 -0
  247. package/dist/src/platforms/host-permission-policy.d.ts +38 -0
  248. package/dist/src/platforms/host-permission-policy.js +86 -0
  249. package/dist/src/platforms/host-permission-policy.js.map +1 -0
  250. package/dist/src/platforms/identity.d.ts +4 -0
  251. package/dist/src/platforms/identity.js +22 -0
  252. package/dist/src/platforms/identity.js.map +1 -0
  253. package/dist/src/platforms/inspection-grok.d.ts +4 -0
  254. package/dist/src/platforms/inspection-grok.js +366 -0
  255. package/dist/src/platforms/inspection-grok.js.map +1 -0
  256. package/dist/src/platforms/inspection-native.d.ts +6 -0
  257. package/dist/src/platforms/inspection-native.js +373 -0
  258. package/dist/src/platforms/inspection-native.js.map +1 -0
  259. package/dist/src/platforms/inspection-opencode.d.ts +4 -0
  260. package/dist/src/platforms/inspection-opencode.js +98 -0
  261. package/dist/src/platforms/inspection-opencode.js.map +1 -0
  262. package/dist/src/platforms/inspection-pi.d.ts +9 -0
  263. package/dist/src/platforms/inspection-pi.js +482 -0
  264. package/dist/src/platforms/inspection-pi.js.map +1 -0
  265. package/dist/src/platforms/inspection-query.d.ts +24 -0
  266. package/dist/src/platforms/inspection-query.js +119 -0
  267. package/dist/src/platforms/inspection-query.js.map +1 -0
  268. package/dist/src/platforms/inspection.d.ts +20 -0
  269. package/dist/src/platforms/inspection.js +259 -0
  270. package/dist/src/platforms/inspection.js.map +1 -0
  271. package/dist/src/platforms/layout.d.ts +35 -0
  272. package/dist/src/platforms/layout.js +317 -0
  273. package/dist/src/platforms/layout.js.map +1 -0
  274. package/dist/src/platforms/lifecycle-native-services.d.ts +3 -0
  275. package/dist/src/platforms/lifecycle-native-services.js +147 -0
  276. package/dist/src/platforms/lifecycle-native-services.js.map +1 -0
  277. package/dist/src/platforms/lifecycle-native.d.ts +14 -0
  278. package/dist/src/platforms/lifecycle-native.js +223 -0
  279. package/dist/src/platforms/lifecycle-native.js.map +1 -0
  280. package/dist/src/platforms/lifecycle.d.ts +27 -0
  281. package/dist/src/platforms/lifecycle.js +567 -0
  282. package/dist/src/platforms/lifecycle.js.map +1 -0
  283. package/dist/src/platforms/opencode-permission-config.d.ts +13 -0
  284. package/dist/src/platforms/opencode-permission-config.js +253 -0
  285. package/dist/src/platforms/opencode-permission-config.js.map +1 -0
  286. package/dist/src/platforms/opencode-permissions.d.ts +39 -0
  287. package/dist/src/platforms/opencode-permissions.js +212 -0
  288. package/dist/src/platforms/opencode-permissions.js.map +1 -0
  289. package/dist/src/platforms/opencode-related-permissions.d.ts +40 -0
  290. package/dist/src/platforms/opencode-related-permissions.js +177 -0
  291. package/dist/src/platforms/opencode-related-permissions.js.map +1 -0
  292. package/dist/src/platforms/permission-ownership.d.ts +89 -0
  293. package/dist/src/platforms/permission-ownership.js +543 -0
  294. package/dist/src/platforms/permission-ownership.js.map +1 -0
  295. package/dist/src/platforms/permission-sidecar.d.ts +70 -0
  296. package/dist/src/platforms/permission-sidecar.js +215 -0
  297. package/dist/src/platforms/permission-sidecar.js.map +1 -0
  298. package/dist/src/platforms/projection-code-extension.d.ts +8 -0
  299. package/dist/src/platforms/projection-code-extension.js +126 -0
  300. package/dist/src/platforms/projection-code-extension.js.map +1 -0
  301. package/dist/src/platforms/projection-command-resources.d.ts +7 -0
  302. package/dist/src/platforms/projection-command-resources.js +74 -0
  303. package/dist/src/platforms/projection-command-resources.js.map +1 -0
  304. package/dist/src/platforms/projection-files.d.ts +27 -0
  305. package/dist/src/platforms/projection-files.js +111 -0
  306. package/dist/src/platforms/projection-files.js.map +1 -0
  307. package/dist/src/platforms/projection-marketplace.d.ts +19 -0
  308. package/dist/src/platforms/projection-marketplace.js +42 -0
  309. package/dist/src/platforms/projection-marketplace.js.map +1 -0
  310. package/dist/src/platforms/projection.d.ts +13 -0
  311. package/dist/src/platforms/projection.js +576 -0
  312. package/dist/src/platforms/projection.js.map +1 -0
  313. package/dist/src/platforms/registry.d.ts +4 -0
  314. package/dist/src/platforms/registry.js +30 -0
  315. package/dist/src/platforms/registry.js.map +1 -0
  316. package/dist/src/platforms/supplement-layout.d.ts +20 -0
  317. package/dist/src/platforms/supplement-layout.js +53 -0
  318. package/dist/src/platforms/supplement-layout.js.map +1 -0
  319. package/dist/src/platforms/supplement-state.d.ts +13 -0
  320. package/dist/src/platforms/supplement-state.js +93 -0
  321. package/dist/src/platforms/supplement-state.js.map +1 -0
  322. package/dist/src/portable/commands.d.ts +58 -11
  323. package/dist/src/portable/commands.js +99 -345
  324. package/dist/src/portable/commands.js.map +1 -1
  325. package/dist/src/portable/historical-materialization.d.ts +22 -0
  326. package/dist/src/portable/historical-materialization.js +124 -0
  327. package/dist/src/portable/historical-materialization.js.map +1 -0
  328. package/dist/src/portable/materializer.d.ts +29 -1
  329. package/dist/src/portable/materializer.js +197 -258
  330. package/dist/src/portable/materializer.js.map +1 -1
  331. package/dist/src/portable/recovery-layout.d.ts +17 -0
  332. package/dist/src/portable/recovery-layout.js +42 -0
  333. package/dist/src/portable/recovery-layout.js.map +1 -0
  334. package/dist/src/portable/recovery.d.ts +176 -0
  335. package/dist/src/portable/recovery.js +556 -0
  336. package/dist/src/portable/recovery.js.map +1 -0
  337. package/dist/src/portable/writer.d.ts +67 -0
  338. package/dist/src/portable/writer.js +321 -0
  339. package/dist/src/portable/writer.js.map +1 -0
  340. package/dist/src/recovery/coordinator.d.ts +168 -0
  341. package/dist/src/recovery/coordinator.js +1558 -0
  342. package/dist/src/recovery/coordinator.js.map +1 -0
  343. package/dist/src/recovery/demand.d.ts +53 -0
  344. package/dist/src/recovery/demand.js +189 -0
  345. package/dist/src/recovery/demand.js.map +1 -0
  346. package/dist/src/recovery/install-concurrency.d.ts +48 -0
  347. package/dist/src/recovery/install-concurrency.js +196 -0
  348. package/dist/src/recovery/install-concurrency.js.map +1 -0
  349. package/dist/src/recovery/interruption.d.ts +19 -0
  350. package/dist/src/recovery/interruption.js +43 -0
  351. package/dist/src/recovery/interruption.js.map +1 -0
  352. package/dist/src/recovery/joint-coordinator.d.ts +46 -0
  353. package/dist/src/recovery/joint-coordinator.js +1641 -0
  354. package/dist/src/recovery/joint-coordinator.js.map +1 -0
  355. package/dist/src/recovery/joint-demand.d.ts +72 -0
  356. package/dist/src/recovery/joint-demand.js +332 -0
  357. package/dist/src/recovery/joint-demand.js.map +1 -0
  358. package/dist/src/recovery/joint-install-execution.d.ts +19 -0
  359. package/dist/src/recovery/joint-install-execution.js +308 -0
  360. package/dist/src/recovery/joint-install-execution.js.map +1 -0
  361. package/dist/src/recovery/joint-install-native-rebase.d.ts +4 -0
  362. package/dist/src/recovery/joint-install-native-rebase.js +67 -0
  363. package/dist/src/recovery/joint-install-native-rebase.js.map +1 -0
  364. package/dist/src/recovery/performance.d.ts +4 -0
  365. package/dist/src/recovery/performance.js +26 -0
  366. package/dist/src/recovery/performance.js.map +1 -0
  367. package/dist/src/recovery/receipt.d.ts +129 -0
  368. package/dist/src/recovery/receipt.js +91 -0
  369. package/dist/src/recovery/receipt.js.map +1 -0
  370. package/dist/src/recovery/retirement.d.ts +47 -0
  371. package/dist/src/recovery/retirement.js +463 -0
  372. package/dist/src/recovery/retirement.js.map +1 -0
  373. package/dist/src/recovery/status.d.ts +143 -0
  374. package/dist/src/recovery/status.js +1517 -0
  375. package/dist/src/recovery/status.js.map +1 -0
  376. package/dist/src/recovery/types.d.ts +85 -0
  377. package/dist/src/recovery/types.js +2 -0
  378. package/dist/src/recovery/types.js.map +1 -0
  379. package/dist/src/review/eval-source-input.d.ts +44 -0
  380. package/dist/src/review/eval-source-input.js +213 -0
  381. package/dist/src/review/eval-source-input.js.map +1 -0
  382. package/dist/src/review/platform-profile.d.ts +6 -0
  383. package/dist/src/review/platform-profile.js +24 -0
  384. package/dist/src/review/platform-profile.js.map +1 -0
  385. package/dist/src/review/review-profile.d.ts +20 -0
  386. package/dist/src/review/review-profile.js +276 -0
  387. package/dist/src/review/review-profile.js.map +1 -0
  388. package/dist/src/review/review-selection.d.ts +20 -0
  389. package/dist/src/review/review-selection.js +502 -0
  390. package/dist/src/review/review-selection.js.map +1 -0
  391. package/dist/src/review/review-types.d.ts +71 -0
  392. package/dist/src/review/review-types.js +16 -0
  393. package/dist/src/review/review-types.js.map +1 -0
  394. package/dist/src/review/skill-materialization.d.ts +65 -0
  395. package/dist/src/review/skill-materialization.js +228 -0
  396. package/dist/src/review/skill-materialization.js.map +1 -0
  397. package/dist/src/review/source-binding.d.ts +201 -0
  398. package/dist/src/review/source-binding.js +782 -0
  399. package/dist/src/review/source-binding.js.map +1 -0
  400. package/dist/src/tui/agent-management.d.ts +23 -0
  401. package/dist/src/tui/agent-management.js +319 -0
  402. package/dist/src/tui/agent-management.js.map +1 -0
  403. package/dist/src/tui/agent-settings.d.ts +47 -0
  404. package/dist/src/tui/agent-settings.js +97 -0
  405. package/dist/src/tui/agent-settings.js.map +1 -0
  406. package/dist/src/tui/catalog-freshness.d.ts +1 -0
  407. package/dist/src/tui/catalog-freshness.js +2 -0
  408. package/dist/src/tui/catalog-freshness.js.map +1 -0
  409. package/dist/src/tui/catalog-generation.d.ts +8 -16
  410. package/dist/src/tui/catalog-generation.js +97 -10
  411. package/dist/src/tui/catalog-generation.js.map +1 -1
  412. package/dist/src/tui/catalog-sources/projection.d.ts +4 -0
  413. package/dist/src/tui/catalog-sources/projection.js +17 -0
  414. package/dist/src/tui/catalog-sources/projection.js.map +1 -0
  415. package/dist/src/tui/catalog-sources/review.d.ts +3 -0
  416. package/dist/src/tui/catalog-sources/review.js +13 -0
  417. package/dist/src/tui/catalog-sources/review.js.map +1 -0
  418. package/dist/src/tui/catalog-sources/screens.d.ts +12 -0
  419. package/dist/src/tui/catalog-sources/screens.js +40 -0
  420. package/dist/src/tui/catalog-sources/screens.js.map +1 -0
  421. package/dist/src/tui/catalog-sources/session.d.ts +32 -0
  422. package/dist/src/tui/catalog-sources/session.js +300 -0
  423. package/dist/src/tui/catalog-sources/session.js.map +1 -0
  424. package/dist/src/tui/catalog-sources/types.d.ts +54 -0
  425. package/dist/src/tui/catalog-sources/types.js +2 -0
  426. package/dist/src/tui/catalog-sources/types.js.map +1 -0
  427. package/dist/src/tui/catalog-store-task.d.ts +16 -0
  428. package/dist/src/tui/catalog-store-task.js +19 -0
  429. package/dist/src/tui/catalog-store-task.js.map +1 -0
  430. package/dist/src/tui/clipboard.d.ts +13 -0
  431. package/dist/src/tui/clipboard.js +95 -0
  432. package/dist/src/tui/clipboard.js.map +1 -0
  433. package/dist/src/tui/components.d.ts +113 -3
  434. package/dist/src/tui/components.js +201 -34
  435. package/dist/src/tui/components.js.map +1 -1
  436. package/dist/src/tui/config-array-draft.d.ts +30 -0
  437. package/dist/src/tui/config-array-draft.js +51 -0
  438. package/dist/src/tui/config-array-draft.js.map +1 -0
  439. package/dist/src/tui/config-leaf-editor.d.ts +44 -0
  440. package/dist/src/tui/config-leaf-editor.js +227 -0
  441. package/dist/src/tui/config-leaf-editor.js.map +1 -0
  442. package/dist/src/tui/config-object-suggestions.d.ts +15 -0
  443. package/dist/src/tui/config-object-suggestions.js +71 -0
  444. package/dist/src/tui/config-object-suggestions.js.map +1 -0
  445. package/dist/src/tui/config-references.d.ts +38 -0
  446. package/dist/src/tui/config-references.js +82 -0
  447. package/dist/src/tui/config-references.js.map +1 -0
  448. package/dist/src/tui/config-suggestions.d.ts +27 -0
  449. package/dist/src/tui/config-suggestions.js +62 -0
  450. package/dist/src/tui/config-suggestions.js.map +1 -0
  451. package/dist/src/tui/config-value-presentation.d.ts +21 -0
  452. package/dist/src/tui/config-value-presentation.js +129 -0
  453. package/dist/src/tui/config-value-presentation.js.map +1 -0
  454. package/dist/src/tui/console-app-v4.d.ts +14 -5
  455. package/dist/src/tui/console-app-v4.js +10344 -2133
  456. package/dist/src/tui/console-app-v4.js.map +1 -1
  457. package/dist/src/tui/content-item-card.d.ts +13 -0
  458. package/dist/src/tui/content-item-card.js +51 -0
  459. package/dist/src/tui/content-item-card.js.map +1 -0
  460. package/dist/src/tui/controller-runtime.d.ts +8 -3
  461. package/dist/src/tui/controller-runtime.js +2301 -842
  462. package/dist/src/tui/controller-runtime.js.map +1 -1
  463. package/dist/src/tui/controller.d.ts +664 -79
  464. package/dist/src/tui/controller.js +3670 -830
  465. package/dist/src/tui/controller.js.map +1 -1
  466. package/dist/src/tui/dependency-graph-view.d.ts +39 -0
  467. package/dist/src/tui/dependency-graph-view.js +121 -0
  468. package/dist/src/tui/dependency-graph-view.js.map +1 -0
  469. package/dist/src/tui/dependency-graph.d.ts +81 -0
  470. package/dist/src/tui/dependency-graph.js +452 -0
  471. package/dist/src/tui/dependency-graph.js.map +1 -0
  472. package/dist/src/tui/deployment-view.d.ts +13 -0
  473. package/dist/src/tui/deployment-view.js +155 -0
  474. package/dist/src/tui/deployment-view.js.map +1 -0
  475. package/dist/src/tui/diagnostic-projection.d.ts +31 -0
  476. package/dist/src/tui/diagnostic-projection.js +681 -0
  477. package/dist/src/tui/diagnostic-projection.js.map +1 -0
  478. package/dist/src/tui/diagnostics.d.ts +6 -2
  479. package/dist/src/tui/diagnostics.js +14 -2
  480. package/dist/src/tui/diagnostics.js.map +1 -1
  481. package/dist/src/tui/entity-cards.d.ts +56 -0
  482. package/dist/src/tui/entity-cards.js +321 -0
  483. package/dist/src/tui/entity-cards.js.map +1 -0
  484. package/dist/src/tui/glossary.d.ts +25 -0
  485. package/dist/src/tui/glossary.js +78 -0
  486. package/dist/src/tui/glossary.js.map +1 -0
  487. package/dist/src/tui/guided-setup.d.ts +25 -0
  488. package/dist/src/tui/guided-setup.js +101 -0
  489. package/dist/src/tui/guided-setup.js.map +1 -0
  490. package/dist/src/tui/index.d.ts +5 -1
  491. package/dist/src/tui/index.js +4 -1
  492. package/dist/src/tui/index.js.map +1 -1
  493. package/dist/src/tui/input-display.d.ts +1 -0
  494. package/dist/src/tui/input-display.js +23 -1
  495. package/dist/src/tui/input-display.js.map +1 -1
  496. package/dist/src/tui/keys.d.ts +44 -0
  497. package/dist/src/tui/keys.js +43 -15
  498. package/dist/src/tui/keys.js.map +1 -1
  499. package/dist/src/tui/lifecycle-action-view.d.ts +6 -0
  500. package/dist/src/tui/lifecycle-action-view.js +36 -0
  501. package/dist/src/tui/lifecycle-action-view.js.map +1 -0
  502. package/dist/src/tui/model.d.ts +187 -52
  503. package/dist/src/tui/model.js +1202 -426
  504. package/dist/src/tui/model.js.map +1 -1
  505. package/dist/src/tui/operation-diagnostic-screens.d.ts +8 -0
  506. package/dist/src/tui/operation-diagnostic-screens.js +76 -0
  507. package/dist/src/tui/operation-diagnostic-screens.js.map +1 -0
  508. package/dist/src/tui/operation-history.d.ts +91 -0
  509. package/dist/src/tui/operation-history.js +167 -0
  510. package/dist/src/tui/operation-history.js.map +1 -0
  511. package/dist/src/tui/operation-review-planner.d.ts +28 -0
  512. package/dist/src/tui/operation-review-planner.js +1456 -0
  513. package/dist/src/tui/operation-review-planner.js.map +1 -0
  514. package/dist/src/tui/plugin-content.d.ts +33 -0
  515. package/dist/src/tui/plugin-content.js +245 -0
  516. package/dist/src/tui/plugin-content.js.map +1 -0
  517. package/dist/src/tui/plugin-detail.d.ts +75 -0
  518. package/dist/src/tui/plugin-detail.js +267 -0
  519. package/dist/src/tui/plugin-detail.js.map +1 -0
  520. package/dist/src/tui/plugin-write-task.d.ts +69 -0
  521. package/dist/src/tui/plugin-write-task.js +286 -0
  522. package/dist/src/tui/plugin-write-task.js.map +1 -0
  523. package/dist/src/tui/prompt.js +4 -15
  524. package/dist/src/tui/prompt.js.map +1 -1
  525. package/dist/src/tui/query-header.d.ts +30 -0
  526. package/dist/src/tui/query-header.js +40 -0
  527. package/dist/src/tui/query-header.js.map +1 -0
  528. package/dist/src/tui/reader.d.ts +38 -0
  529. package/dist/src/tui/reader.js +49 -0
  530. package/dist/src/tui/reader.js.map +1 -0
  531. package/dist/src/tui/router.d.ts +182 -39
  532. package/dist/src/tui/router.js +338 -50
  533. package/dist/src/tui/router.js.map +1 -1
  534. package/dist/src/tui/scoped-flow.d.ts +49 -0
  535. package/dist/src/tui/scoped-flow.js +212 -0
  536. package/dist/src/tui/scoped-flow.js.map +1 -0
  537. package/dist/src/tui/scoped-inventory.d.ts +131 -0
  538. package/dist/src/tui/scoped-inventory.js +280 -0
  539. package/dist/src/tui/scoped-inventory.js.map +1 -0
  540. package/dist/src/tui/screen-registry.d.ts +696 -0
  541. package/dist/src/tui/screen-registry.js +226 -0
  542. package/dist/src/tui/screen-registry.js.map +1 -0
  543. package/dist/src/tui/session-console-app.d.ts +8 -0
  544. package/dist/src/tui/session-console-app.js +24 -0
  545. package/dist/src/tui/session-console-app.js.map +1 -0
  546. package/dist/src/tui/session-host.d.ts +45 -0
  547. package/dist/src/tui/session-host.js +219 -0
  548. package/dist/src/tui/session-host.js.map +1 -0
  549. package/dist/src/tui/source-detail-card.d.ts +29 -0
  550. package/dist/src/tui/source-detail-card.js +45 -0
  551. package/dist/src/tui/source-detail-card.js.map +1 -0
  552. package/dist/src/tui/theme.d.ts +12 -0
  553. package/dist/src/tui/theme.js +12 -0
  554. package/dist/src/tui/theme.js.map +1 -1
  555. package/dist/src/tui/viewport.d.ts +1 -0
  556. package/dist/src/tui/viewport.js +23 -0
  557. package/dist/src/tui/viewport.js.map +1 -1
  558. package/dist/src/tui/wizard.js +37 -13
  559. package/dist/src/tui/wizard.js.map +1 -1
  560. package/dist/src/types.d.ts +177 -85
  561. package/dist/src/types.js +1 -0
  562. package/dist/src/types.js.map +1 -1
  563. package/dist/src/utils/agent-version.d.ts +10 -4
  564. package/dist/src/utils/agent-version.js +6 -8
  565. package/dist/src/utils/agent-version.js.map +1 -1
  566. package/dist/src/utils/artifact-plan.d.ts +17 -24
  567. package/dist/src/utils/artifact-plan.js +59 -436
  568. package/dist/src/utils/artifact-plan.js.map +1 -1
  569. package/dist/src/utils/artifact-renderer.d.ts +61 -89
  570. package/dist/src/utils/artifact-renderer.js +187 -364
  571. package/dist/src/utils/artifact-renderer.js.map +1 -1
  572. package/dist/src/utils/artifact-request.d.ts +21 -0
  573. package/dist/src/utils/artifact-request.js +57 -0
  574. package/dist/src/utils/artifact-request.js.map +1 -0
  575. package/dist/src/utils/artifact-sources.d.ts +4 -8
  576. package/dist/src/utils/artifact-sources.js +15 -6
  577. package/dist/src/utils/artifact-sources.js.map +1 -1
  578. package/dist/src/utils/aw-home-mutation-lock.js +2 -1
  579. package/dist/src/utils/aw-home-mutation-lock.js.map +1 -1
  580. package/dist/src/utils/bundle-layout.js +59 -173
  581. package/dist/src/utils/bundle-layout.js.map +1 -1
  582. package/dist/src/utils/catalog-capability-projection.d.ts +8 -0
  583. package/dist/src/utils/catalog-capability-projection.js +14 -0
  584. package/dist/src/utils/catalog-capability-projection.js.map +1 -0
  585. package/dist/src/utils/catalog-digests.d.ts +2 -9
  586. package/dist/src/utils/catalog-digests.js +7 -45
  587. package/dist/src/utils/catalog-digests.js.map +1 -1
  588. package/dist/src/utils/catalog-generation-error.d.ts +4 -1
  589. package/dist/src/utils/catalog-generation-error.js +2 -0
  590. package/dist/src/utils/catalog-generation-error.js.map +1 -1
  591. package/dist/src/utils/catalog-generation-resolver.d.ts +32 -3
  592. package/dist/src/utils/catalog-generation-resolver.js +182 -40
  593. package/dist/src/utils/catalog-generation-resolver.js.map +1 -1
  594. package/dist/src/utils/catalog-generation-service.d.ts +142 -2
  595. package/dist/src/utils/catalog-generation-service.js +1146 -171
  596. package/dist/src/utils/catalog-generation-service.js.map +1 -1
  597. package/dist/src/utils/catalog-generation-state.d.ts +5 -0
  598. package/dist/src/utils/catalog-generation-state.js +25 -1
  599. package/dist/src/utils/catalog-generation-state.js.map +1 -1
  600. package/dist/src/utils/catalog-generation-store.d.ts +29 -2
  601. package/dist/src/utils/catalog-generation-store.js +240 -36
  602. package/dist/src/utils/catalog-generation-store.js.map +1 -1
  603. package/dist/src/utils/catalog-manifest-v7.d.ts +5 -0
  604. package/dist/src/utils/{catalog-manifest-v6.js → catalog-manifest-v7.js} +23 -23
  605. package/dist/src/utils/{catalog-manifest-v6.js.map → catalog-manifest-v7.js.map} +1 -1
  606. package/dist/src/utils/catalog-operation-context.d.ts +27 -3
  607. package/dist/src/utils/catalog-operation-context.js +75 -4
  608. package/dist/src/utils/catalog-operation-context.js.map +1 -1
  609. package/dist/src/utils/catalog-public-error.js +7 -0
  610. package/dist/src/utils/catalog-public-error.js.map +1 -1
  611. package/dist/src/utils/catalog-runtime-projection.d.ts +4 -3
  612. package/dist/src/utils/catalog-runtime-projection.js.map +1 -1
  613. package/dist/src/utils/catalog-snapshot.d.ts +5 -2
  614. package/dist/src/utils/catalog-snapshot.js +4 -1
  615. package/dist/src/utils/catalog-snapshot.js.map +1 -1
  616. package/dist/src/utils/catalog-source-impact.d.ts +21 -0
  617. package/dist/src/utils/catalog-source-impact.js +344 -0
  618. package/dist/src/utils/catalog-source-impact.js.map +1 -0
  619. package/dist/src/utils/catalog-source-references.d.ts +22 -8
  620. package/dist/src/utils/catalog-source-references.js +457 -365
  621. package/dist/src/utils/catalog-source-references.js.map +1 -1
  622. package/dist/src/utils/catalog-sources.d.ts +14 -1
  623. package/dist/src/utils/catalog-sources.js +155 -11
  624. package/dist/src/utils/catalog-sources.js.map +1 -1
  625. package/dist/src/utils/codex-executable-discovery.d.ts +28 -0
  626. package/dist/src/utils/codex-executable-discovery.js +431 -0
  627. package/dist/src/utils/codex-executable-discovery.js.map +1 -0
  628. package/dist/src/utils/codex-manager.d.ts +23 -42
  629. package/dist/src/utils/codex-manager.js +79 -767
  630. package/dist/src/utils/codex-manager.js.map +1 -1
  631. package/dist/src/utils/codex-marketplace-path.d.ts +5 -0
  632. package/dist/src/utils/codex-marketplace-path.js +45 -0
  633. package/dist/src/utils/codex-marketplace-path.js.map +1 -0
  634. package/dist/src/utils/codex-native-observation.d.ts +55 -0
  635. package/dist/src/utils/codex-native-observation.js +198 -0
  636. package/dist/src/utils/codex-native-observation.js.map +1 -0
  637. package/dist/src/utils/codex-reconciler.d.ts +6 -14
  638. package/dist/src/utils/codex-reconciler.js +45 -50
  639. package/dist/src/utils/codex-reconciler.js.map +1 -1
  640. package/dist/src/utils/codex-shared-native.d.ts +28 -39
  641. package/dist/src/utils/codex-shared-native.js +92 -57
  642. package/dist/src/utils/codex-shared-native.js.map +1 -1
  643. package/dist/src/utils/codex-skill-staging.d.ts +4 -3
  644. package/dist/src/utils/codex-skill-staging.js.map +1 -1
  645. package/dist/src/utils/codex-skills-root.d.ts +4 -0
  646. package/dist/src/utils/codex-skills-root.js +25 -0
  647. package/dist/src/utils/codex-skills-root.js.map +1 -0
  648. package/dist/src/utils/codex-surface-analysis.d.ts +8 -3
  649. package/dist/src/utils/codex-surface-analysis.js +35 -62
  650. package/dist/src/utils/codex-surface-analysis.js.map +1 -1
  651. package/dist/src/utils/component-command-preparation.d.ts +31 -0
  652. package/dist/src/utils/component-command-preparation.js +127 -0
  653. package/dist/src/utils/component-command-preparation.js.map +1 -0
  654. package/dist/src/utils/component-gap.d.ts +4 -0
  655. package/dist/src/utils/component-gap.js +20 -0
  656. package/dist/src/utils/component-gap.js.map +1 -0
  657. package/dist/src/utils/component-resources.d.ts +51 -0
  658. package/dist/src/utils/component-resources.js +320 -0
  659. package/dist/src/utils/component-resources.js.map +1 -0
  660. package/dist/src/utils/config-platforms.d.ts +21 -0
  661. package/dist/src/utils/config-platforms.js +51 -0
  662. package/dist/src/utils/config-platforms.js.map +1 -0
  663. package/dist/src/utils/dynamic-skill-tree.d.ts +18 -6
  664. package/dist/src/utils/dynamic-skill-tree.js +33 -40
  665. package/dist/src/utils/dynamic-skill-tree.js.map +1 -1
  666. package/dist/src/utils/git-catalog-provider.d.ts +16 -0
  667. package/dist/src/utils/git-catalog-provider.js +112 -6
  668. package/dist/src/utils/git-catalog-provider.js.map +1 -1
  669. package/dist/src/utils/inventory-recovery-diagnostic.d.ts +4 -0
  670. package/dist/src/utils/inventory-recovery-diagnostic.js +15 -0
  671. package/dist/src/utils/inventory-recovery-diagnostic.js.map +1 -0
  672. package/dist/src/utils/local-marketplace.d.ts +17 -12
  673. package/dist/src/utils/local-marketplace.js +85 -195
  674. package/dist/src/utils/local-marketplace.js.map +1 -1
  675. package/dist/src/utils/managed-command-cli-review.d.ts +53 -0
  676. package/dist/src/utils/managed-command-cli-review.js +431 -0
  677. package/dist/src/utils/managed-command-cli-review.js.map +1 -0
  678. package/dist/src/utils/managed-command-closure.d.ts +14 -0
  679. package/dist/src/utils/managed-command-closure.js +156 -0
  680. package/dist/src/utils/managed-command-closure.js.map +1 -0
  681. package/dist/src/utils/managed-command-errors.d.ts +5 -0
  682. package/dist/src/utils/managed-command-errors.js +10 -0
  683. package/dist/src/utils/managed-command-errors.js.map +1 -0
  684. package/dist/src/utils/managed-command-materialization.d.ts +90 -0
  685. package/dist/src/utils/managed-command-materialization.js +375 -0
  686. package/dist/src/utils/managed-command-materialization.js.map +1 -0
  687. package/dist/src/utils/managed-command-preparation.d.ts +30 -0
  688. package/dist/src/utils/managed-command-preparation.js +39 -0
  689. package/dist/src/utils/managed-command-preparation.js.map +1 -0
  690. package/dist/src/utils/managed-command-review.d.ts +33 -0
  691. package/dist/src/utils/managed-command-review.js +80 -0
  692. package/dist/src/utils/managed-command-review.js.map +1 -0
  693. package/dist/src/utils/managed-command-runtime.d.ts +36 -0
  694. package/dist/src/utils/managed-command-runtime.js +126 -0
  695. package/dist/src/utils/managed-command-runtime.js.map +1 -0
  696. package/dist/src/utils/managed-command-snapshots.d.ts +24 -0
  697. package/dist/src/utils/managed-command-snapshots.js +89 -0
  698. package/dist/src/utils/managed-command-snapshots.js.map +1 -0
  699. package/dist/src/utils/managed-command-store.d.ts +141 -0
  700. package/dist/src/utils/managed-command-store.js +839 -0
  701. package/dist/src/utils/managed-command-store.js.map +1 -0
  702. package/dist/src/utils/multi-source-catalog.d.ts +4 -0
  703. package/dist/src/utils/multi-source-catalog.js +7 -3
  704. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  705. package/dist/src/utils/native-cli-interruption.d.ts +8 -0
  706. package/dist/src/utils/native-cli-interruption.js +65 -0
  707. package/dist/src/utils/native-cli-interruption.js.map +1 -0
  708. package/dist/src/utils/native-cli.d.ts +37 -6
  709. package/dist/src/utils/native-cli.js +523 -60
  710. package/dist/src/utils/native-cli.js.map +1 -1
  711. package/dist/src/utils/native-demand.d.ts +29 -0
  712. package/dist/src/utils/native-demand.js +4 -0
  713. package/dist/src/utils/native-demand.js.map +1 -0
  714. package/dist/src/utils/native-tool-context.d.ts +17 -0
  715. package/dist/src/utils/native-tool-context.js +40 -0
  716. package/dist/src/utils/native-tool-context.js.map +1 -0
  717. package/dist/src/utils/native-tool-review.d.ts +8 -0
  718. package/dist/src/utils/native-tool-review.js +14 -0
  719. package/dist/src/utils/native-tool-review.js.map +1 -0
  720. package/dist/src/utils/orphan-marketplace-cleanup.js +0 -2
  721. package/dist/src/utils/orphan-marketplace-cleanup.js.map +1 -1
  722. package/dist/src/utils/ownership.d.ts +111 -11
  723. package/dist/src/utils/ownership.js +247 -126
  724. package/dist/src/utils/ownership.js.map +1 -1
  725. package/dist/src/utils/package-content.d.ts +7 -0
  726. package/dist/src/utils/package-content.js +70 -0
  727. package/dist/src/utils/package-content.js.map +1 -0
  728. package/dist/src/utils/path-catalog-provider.js +2 -0
  729. package/dist/src/utils/path-catalog-provider.js.map +1 -1
  730. package/dist/src/utils/paths.d.ts +1 -1
  731. package/dist/src/utils/paths.js +5 -2
  732. package/dist/src/utils/paths.js.map +1 -1
  733. package/dist/src/utils/platform-empty-state.d.ts +69 -0
  734. package/dist/src/utils/platform-empty-state.js +226 -0
  735. package/dist/src/utils/platform-empty-state.js.map +1 -0
  736. package/dist/src/utils/platform-support.d.ts +1 -1
  737. package/dist/src/utils/platform-support.js +1 -1
  738. package/dist/src/utils/platform-support.js.map +1 -1
  739. package/dist/src/utils/plugin-config-command-apply.d.ts +33 -0
  740. package/dist/src/utils/plugin-config-command-apply.js +142 -0
  741. package/dist/src/utils/plugin-config-command-apply.js.map +1 -0
  742. package/dist/src/utils/plugin-config-diagnostics.d.ts +16 -0
  743. package/dist/src/utils/plugin-config-diagnostics.js +44 -0
  744. package/dist/src/utils/plugin-config-diagnostics.js.map +1 -0
  745. package/dist/src/utils/plugin-config-impact.d.ts +75 -0
  746. package/dist/src/utils/plugin-config-impact.js +355 -0
  747. package/dist/src/utils/plugin-config-impact.js.map +1 -0
  748. package/dist/src/utils/plugin-config-references.d.ts +96 -0
  749. package/dist/src/utils/plugin-config-references.js +357 -0
  750. package/dist/src/utils/plugin-config-references.js.map +1 -0
  751. package/dist/src/utils/plugin-config-suggestion-runner.d.ts +83 -0
  752. package/dist/src/utils/plugin-config-suggestion-runner.js +308 -0
  753. package/dist/src/utils/plugin-config-suggestion-runner.js.map +1 -0
  754. package/dist/src/utils/plugin-config-suggestions.d.ts +50 -0
  755. package/dist/src/utils/plugin-config-suggestions.js +302 -0
  756. package/dist/src/utils/plugin-config-suggestions.js.map +1 -0
  757. package/dist/src/utils/plugin-config-write.d.ts +123 -31
  758. package/dist/src/utils/plugin-config-write.js +828 -399
  759. package/dist/src/utils/plugin-config-write.js.map +1 -1
  760. package/dist/src/utils/plugin-config.d.ts +192 -109
  761. package/dist/src/utils/plugin-config.js +970 -1150
  762. package/dist/src/utils/plugin-config.js.map +1 -1
  763. package/dist/src/utils/plugin-dependencies.d.ts +1 -1
  764. package/dist/src/utils/plugin-dependencies.js.map +1 -1
  765. package/dist/src/utils/plugin-scripts.d.ts +80 -127
  766. package/dist/src/utils/plugin-scripts.js +655 -524
  767. package/dist/src/utils/plugin-scripts.js.map +1 -1
  768. package/dist/src/utils/process-lock.js +14 -5
  769. package/dist/src/utils/process-lock.js.map +1 -1
  770. package/dist/src/utils/process-tree.d.ts +2 -2
  771. package/dist/src/utils/process-tree.js +1 -1
  772. package/dist/src/utils/process-tree.js.map +1 -1
  773. package/dist/src/utils/project-boundary.d.ts +11 -13
  774. package/dist/src/utils/project-boundary.js +28 -34
  775. package/dist/src/utils/project-boundary.js.map +1 -1
  776. package/dist/src/utils/rendered-contract.js +24 -1
  777. package/dist/src/utils/rendered-contract.js.map +1 -1
  778. package/dist/src/utils/runtime-config.d.ts +18 -0
  779. package/dist/src/utils/runtime-config.js +64 -0
  780. package/dist/src/utils/runtime-config.js.map +1 -0
  781. package/dist/src/utils/runtime-skill-closure.d.ts +2 -2
  782. package/dist/src/utils/runtime-skill-closure.js +47 -6
  783. package/dist/src/utils/runtime-skill-closure.js.map +1 -1
  784. package/dist/src/utils/safe-fs.d.ts +21 -0
  785. package/dist/src/utils/safe-fs.js +111 -0
  786. package/dist/src/utils/safe-fs.js.map +1 -0
  787. package/dist/src/utils/safe-operation-diagnostic.d.ts +15 -0
  788. package/dist/src/utils/safe-operation-diagnostic.js +33 -0
  789. package/dist/src/utils/safe-operation-diagnostic.js.map +1 -0
  790. package/dist/src/utils/sensitive-content.d.ts +4 -0
  791. package/dist/src/utils/sensitive-content.js +36 -0
  792. package/dist/src/utils/sensitive-content.js.map +1 -0
  793. package/dist/src/utils/skill-invocation-warning.d.ts +20 -0
  794. package/dist/src/utils/skill-invocation-warning.js +68 -0
  795. package/dist/src/utils/skill-invocation-warning.js.map +1 -0
  796. package/dist/src/utils/state-paths.d.ts +8 -3
  797. package/dist/src/utils/state-paths.js +53 -16
  798. package/dist/src/utils/state-paths.js.map +1 -1
  799. package/dist/src/utils/target-eligibility.d.ts +3 -3
  800. package/dist/src/utils/target-eligibility.js +11 -6
  801. package/dist/src/utils/target-eligibility.js.map +1 -1
  802. package/dist/src/utils/windows-claude-shim.d.ts +7 -0
  803. package/dist/src/utils/windows-claude-shim.js +10 -0
  804. package/dist/src/utils/windows-claude-shim.js.map +1 -0
  805. package/dist/src/utils/windows-npm-shim.d.ts +16 -0
  806. package/dist/src/utils/windows-npm-shim.js +155 -0
  807. package/dist/src/utils/windows-npm-shim.js.map +1 -0
  808. package/dist/vitest.config.js +106 -9
  809. package/dist/vitest.config.js.map +1 -1
  810. package/package.json +30 -21
  811. package/dist/src/commands/review-publication.d.ts +0 -99
  812. package/dist/src/commands/review-publication.js +0 -904
  813. package/dist/src/commands/review-publication.js.map +0 -1
  814. package/dist/src/commands/sync-command.d.ts +0 -21
  815. package/dist/src/commands/sync-command.js +0 -206
  816. package/dist/src/commands/sync-command.js.map +0 -1
  817. package/dist/src/portable/skills-cli.d.ts +0 -43
  818. package/dist/src/portable/skills-cli.js +0 -148
  819. package/dist/src/portable/skills-cli.js.map +0 -1
  820. package/dist/src/utils/catalog-manifest-v6.d.ts +0 -5
  821. package/dist/src/utils/lifecycle-active-store.d.ts +0 -147
  822. package/dist/src/utils/lifecycle-active-store.js +0 -1064
  823. package/dist/src/utils/lifecycle-active-store.js.map +0 -1
  824. package/dist/src/utils/plugin-intent-state.d.ts +0 -39
  825. package/dist/src/utils/plugin-intent-state.js +0 -325
  826. package/dist/src/utils/plugin-intent-state.js.map +0 -1
  827. package/dist/src/utils/slash-commands.d.ts +0 -1
  828. package/dist/src/utils/slash-commands.js +0 -2
  829. package/dist/src/utils/slash-commands.js.map +0 -1
@@ -1,28 +1,91 @@
1
+ import { readAgentSettings, previewAgentSettings, saveAgentSettings } from './agent-settings.js';
2
+ import { observePreferences } from '../intent/deployment-preferences.js';
3
+ import { resolveConfigurableLayers, classifyResidualConfigLayers } from '../utils/config-platforms.js';
4
+ import { configObjectHasSensitiveChild } from './config-value-presentation.js';
5
+ import { selectPluginConfigProfile, getPluginConfigReferenceChoices, PLATFORM_TARGETS, NATIVE_PLATFORM_TARGETS, resolveSupportedPlatforms } from '@lesliechan721/aw-plugin-core';
6
+ import { configReferenceKey, configReferenceScalars } from './config-references.js';
7
+ import { preparePluginConfigSuggestions } from '../utils/plugin-config-suggestions.js';
1
8
  import crypto from 'node:crypto';
2
9
  import path from 'node:path';
3
- import { statusCommandV6, } from '../commands/status-v6.js';
10
+ import { managedCommandRecoveryPlanChanges } from './operation-review-planner.js';
11
+ import { recoveryHostPermissionEffects } from '../commands/deployment-confirmation.js';
12
+ import { isPermissionHost } from '../platforms/host-permission-policy.js';
13
+ import { resolveWorkContext } from '../intent/work-context.js';
14
+ import { flattenStatusTargets, statusTargetHasLiveConfigConsumer, } from '../commands/status-v6.js';
4
15
  import { addCatalogSourceCommand, listCatalogSources, preflightCatalogSourceMutation, removeCatalogSourceCommand, setPrimaryCatalogSourceCommand, updateCatalogSourceCommand, } from '../commands/catalog-source.js';
5
- import { cleanupWriteCommand, installWriteCommand, reinstallWriteCommand, uninstallWriteCommand, upgradeWriteCommand, } from '../commands/write-commands.js';
16
+ import { parseScriptTimeoutMs, SCRIPT_TIMEOUT_DEFAULT_MS, } from '../commands/options.js';
6
17
  import { readCliPackageInfo } from '../utils/local-marketplace.js';
7
- import { readCatalogSourcesConfigSnapshot, } from '../utils/catalog-sources.js';
18
+ import { readCatalogSourcesConfigSnapshot, recoverInvalidCatalogSourcesConfig, } from '../utils/catalog-sources.js';
8
19
  import { withResolvedCatalogPlugin, withResolvedMultiSourceCatalog, formatPluginId, parsePluginId, } from '../utils/multi-source-catalog.js';
9
- import { coercePluginConfigUpdates, readNamespacedPluginConfigStoreIdentity, readPluginConfigStore, resolveConfigRead, } from '../utils/plugin-config.js';
10
- import { applyPluginConfigWrite, resetPluginConfigWithHelper, } from '../utils/plugin-config-write.js';
11
- import { offlineCleanupEvidenceFromInventory, } from '../commands/offline-cleanup-evidence.js';
20
+ import { coercePluginConfigUpdates, inspectPluginConfigResetTarget, listNamespacedPluginConfigStoreIdentities, readPluginConfigStore, replacePluginConfigStoreLayer, resolveConfigRead, resolveEffectivePluginConfig, resolveEffectivePluginConfigFromStores, resolvePluginConfigReferenceContext, } from '../utils/plugin-config.js';
21
+ import { readRecoveryStatus } from '../recovery/status.js';
22
+ import { readJointDemand } from '../recovery/joint-demand.js';
23
+ import { RecoveryInterruptedError } from '../recovery/interruption.js';
24
+ import { catalogSourceErrorCode, sanitizeCatalogSourceError } from '../utils/catalog-public-error.js';
25
+ import { activateRecoverySourcesAndReprepare, prepareRecovery, executeRecovery, } from '../recovery/coordinator.js';
26
+ import { prepareRetire, executeRetire } from '../recovery/retirement.js';
27
+ import { prepareTargetsPlan, executeTargetsPlan, prepareIntentPlan, executeIntentPlan } from './scoped-flow.js';
28
+ import { applyPluginConfigWrite, applyPluginConfig, ConfigApplyInterruptedError, preparePluginConfigApply, disposePluginConfigApply, resolveConfigPreApplyAuthorization, resetPluginConfigWithHelper, } from '../utils/plugin-config-write.js';
29
+ import { analyzePluginConfigMutationImpact, discoverPluginConfigManagedCommandPackages, pluginConfigTargetRenderScopes, pluginSharedNativeConfigRenderUnits } from '../utils/plugin-config-impact.js';
30
+ import { describeConfigCommandPackageReviews } from '../utils/plugin-config-command-apply.js';
31
+ import { collectPluginConfigReferenceEvidence, pluginConfigHasExternalReferences, resolvePluginConfigReferenceConsumers, resolvePluginConfigReferencePlugins } from '../utils/plugin-config-references.js';
12
32
  import { inventoryCatalogSourceReferences } from '../utils/catalog-source-references.js';
13
- import { operationEvidenceFingerprint, TuiController, TuiOperationBlockedError, } from './controller.js';
14
- import { buildConfigGroups, buildConfigPage, isPureNativeCodexTarget, projectPlatformPlacement, } from './model.js';
33
+ import { operationEvidenceMatches, operationEvidenceFingerprint, configApplyHasCompletedWork, TuiConfigInvalidStoreError, TuiController, TuiOperationBlockedError, } from './controller.js';
34
+ import { buildConfigPage, } from './model.js';
15
35
  import { projectCatalogSourceLocation } from '../utils/catalog-source-presentation.js';
16
- import { targetCanBeUninstalled, targetHasArtifactCollision, } from '../utils/target-eligibility.js';
17
- import { calculateCatalogSourceIdentity } from '../utils/catalog-source-identity.js';
36
+ import { calculateCatalogSourceConfigFingerprint, calculateCatalogSourceIdentity, } from '../utils/catalog-source-identity.js';
18
37
  import { checkAwCapabilitySupport, readPluginManifest } from '../utils/manifest.js';
19
38
  import { withAwHomeMutationLock } from '../utils/aw-home-mutation-lock.js';
20
39
  import { IMPLEMENTED_AW_CAPABILITIES } from '../commands/aw-capabilities.js';
21
- import { resolveCatalogOperationContext, resolvePartialCatalogOperationContext, selectCatalogOperationContext, } from '../utils/catalog-operation-context.js';
40
+ import { calculateCatalogGenerationSetDigest, createCatalogPreparationStoreKey, resolveActiveCatalogGeneration, } from '../utils/catalog-generation-resolver.js';
41
+ import { CatalogPreparationReadScope, resolveCatalogOperationContext, resolvePartialCatalogOperationContext, selectCatalogOperationContext, } from '../utils/catalog-operation-context.js';
42
+ import { createCatalogStoreKey, readCatalogStoreEntry, } from '../utils/catalog-generation-store.js';
43
+ import { activateCatalogSourceGeneration, compareCatalogGenerationFreshness, probeCatalogSourceFreshness, probeCatalogSourceGeneration, probeCatalogSourceRepairGeneration, recoverCatalogGenerationStateAndActivate, repairCatalogSourceGeneration, replaceDamagedCatalogSourceGeneration, } from '../utils/catalog-generation-service.js';
44
+ import { calculateCatalogSourceImpactDigest, inspectCatalogSourceImpact, } from '../utils/catalog-source-impact.js';
45
+ import { readCatalogGenerationState } from '../utils/catalog-generation-state.js';
46
+ import { CatalogGenerationError } from '../utils/catalog-generation-error.js';
47
+ import { CatalogProviderCompatibilityError } from '../utils/catalog-public-error.js';
22
48
  import { loadCatalogGenerationViewModels } from './catalog-generation.js';
23
- import { installPortableSkills, preparePortableInstall, PortableCommandError, } from '../portable/commands.js';
24
- import { MANAGED_CODEX_PACKAGE_NAME, MANAGED_CODEX_VERSION, } from '../utils/codex-manager.js';
25
- import { calculatePluginIntentDigest, canonicalizePluginIntentState, readPluginIntentState, writePluginIntentState, } from '../utils/plugin-intent-state.js';
49
+ import { recoveryReason } from './glossary.js';
50
+ import { executePortableRetry, installPortableSkills, preparePortableInstall, preparePortableRetry, PortableCommandError, recheckPortableInstall, } from '../portable/commands.js';
51
+ import { projectPluginContentOverview, } from './plugin-content.js';
52
+ import { executeCatalogStoreTask, inspectCatalogStoreTask, prepareCatalogStoreTask, } from './catalog-store-task.js';
53
+ function installSourceBinding(catalog, sourceId) {
54
+ const generation = catalog?.generationSet.sources.find((source) => source.sourceId === sourceId);
55
+ const resolution = catalog?.catalog.sources.find((source) => source.sourceId === sourceId)?.resolution;
56
+ return generation && resolution && createCatalogPreparationStoreKey({ ...generation, requestedRef: resolution.requestedRef });
57
+ }
58
+ function homeGenerationsMatch(catalog, generations, configured) {
59
+ if (generations.length !== catalog.catalog.sources.length)
60
+ return false;
61
+ return generations.every((view) => {
62
+ const bound = catalog.generationSet.sources.find((source) => source.sourceId === view.sourceId);
63
+ const source = catalog.catalog.sources.find((item) => item.sourceId === view.sourceId);
64
+ if (!bound)
65
+ return source?.error !== undefined && catalogSourceErrorCode(source.error)
66
+ === (view.configMismatch ? 'catalogGenerationIdentityMismatch' : view.errorCode);
67
+ const config = configured.sources.find((item) => item.id === view.sourceId);
68
+ return view.state === 'ready' && view.active?.storeKey === bound.storeKey
69
+ && view.active.resolvedCommit === bound.resolvedCommit && view.active.requestedRef === source?.resolution?.requestedRef
70
+ && config?.sourceIdentity === bound.sourceIdentity && calculateCatalogSourceConfigFingerprint(config) === bound.sourceConfigFingerprint;
71
+ });
72
+ }
73
+ function reusableCandidateEvidenceIsComplete(candidate) {
74
+ const evidence = candidate.probe.candidate;
75
+ return [
76
+ evidence.sourceConfigFingerprint,
77
+ evidence.sourceIdentity,
78
+ evidence.logicalIdentity,
79
+ evidence.requestedRef,
80
+ evidence.resolvedCommit,
81
+ evidence.catalogVersion,
82
+ evidence.channel,
83
+ evidence.manifestDigest,
84
+ evidence.snapshotDigest,
85
+ ].every((value) => typeof value === 'string' && value.length > 0)
86
+ && typeof candidate.probe.manifest === 'object'
87
+ && candidate.probe.manifest !== null;
88
+ }
26
89
  async function loadPortablePluginIds(options) {
27
90
  return withResolvedMultiSourceCatalog({
28
91
  cliVersion: options.cliVersion,
@@ -35,12 +98,12 @@ async function loadPortablePluginIds(options) {
35
98
  ? item.resolution.manifest.entries.flatMap((entry) => {
36
99
  const support = checkAwCapabilitySupport(entry.requires.aw.capabilities ?? [], IMPLEMENTED_AW_CAPABILITIES);
37
100
  return support.supported
38
- ? [readPluginManifest(path.join(item.resolution.rootDir, 'plugins', entry.name), { mode: 'bundle' }).then((plugin) => plugin.manifest.distributions?.agentSkills
101
+ ? [readPluginManifest(path.join(item.resolution.rootDir, 'plugins', entry.name), { mode: 'bundle' }).then((plugin) => resolveSupportedPlatforms(plugin.manifest).has('generic')
39
102
  ? formatPluginId({
40
103
  sourceId: item.resolution.sourceId,
41
104
  pluginName: entry.name,
42
105
  })
43
- : null)]
106
+ : null).catch(() => { options.signal.throwIfAborted(); return null; })]
44
107
  : [];
45
108
  })
46
109
  : []))).filter((pluginId) => pluginId !== null),
@@ -53,6 +116,10 @@ export function setTuiControllerRuntimeTestHooksForTests(hooks) {
53
116
  function digest(value) {
54
117
  return `sha256:${crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex')}`;
55
118
  }
119
+ function configSchemaIdentity(plugin, manifestDigest, platform) {
120
+ return digest({ manifestDigest, profile: platform ?? 'common',
121
+ definition: selectPluginConfigProfile(plugin.manifest.config, platform) });
122
+ }
56
123
  export function statusTargetFingerprint(targets, revisions = []) {
57
124
  return digest({
58
125
  targets: targets.map((target) => ({
@@ -61,9 +128,14 @@ export function statusTargetFingerprint(targets, revisions = []) {
61
128
  platform: target.platform,
62
129
  scope: target.scope,
63
130
  state: target.state,
64
- errors: target.errors.map((error) => error.code).sort(),
131
+ errors: target.reasons.map((error) => error.code).sort(),
132
+ sharedReasons: [...(target.sharedReasons ?? [])]
133
+ .sort((left, right) => `${left.code}\0${left.message}`.localeCompare(`${right.code}\0${right.message}`, 'en')),
65
134
  components: target.components.map((component) => [component.key, component.state])
66
135
  .sort(([left], [right]) => left.localeCompare(right, 'en')),
136
+ sharedComponents: (target.sharedComponents ?? [])
137
+ .map((component) => [component.key, component.state, component.metadata])
138
+ .sort(([left], [right]) => left.localeCompare(right, 'en')),
67
139
  })).sort((left, right) => [left.pluginId, left.platform, left.scope].join('\0')
68
140
  .localeCompare([right.pluginId, right.platform, right.scope].join('\0'), 'en')),
69
141
  revisions: revisions.map((entry) => ({
@@ -75,33 +147,249 @@ export function statusTargetFingerprint(targets, revisions = []) {
75
147
  .localeCompare([right.pluginId, right.platform, right.scope].join('\0'), 'en')),
76
148
  });
77
149
  }
78
- export function configAffectedStatusTargets(targets, pluginId, configScope) {
79
- return targets.filter((target) => target.pluginId === pluginId
80
- && (configScope === 'user' || target.scope === 'project')
81
- && (target.state === 'present' || target.state === 'partial'))
82
- .sort((left, right) => `${left.platform}\0${left.scope}`
83
- .localeCompare(`${right.platform}\0${right.scope}`, 'en'));
150
+ export function configAffectedStatusTargets(targets, pluginId, configContext, consumerPluginIds = [], platform) {
151
+ const affected = new Map();
152
+ const selected = new Set([pluginId, ...consumerPluginIds]);
153
+ for (const target of flattenStatusTargets(targets)) {
154
+ if (!selected.has(target.pluginId) || !statusTargetHasLiveConfigConsumer(target))
155
+ continue;
156
+ if (configContext === 'user' && target.scope !== 'user')
157
+ continue;
158
+ if (platform && target.platform !== platform)
159
+ continue;
160
+ affected.set(`${target.pluginId}\0${target.platform}\0${target.scope}`, target);
161
+ }
162
+ return [...affected.values()]
163
+ .sort((left, right) => `${left.pluginId}\0${left.platform}\0${left.scope}`
164
+ .localeCompare(`${right.pluginId}\0${right.platform}\0${right.scope}`, 'en'));
165
+ }
166
+ function currentConfigTargets(status, pluginId, configContext, consumers = [], platform) {
167
+ const selected = new Set([pluginId, ...consumers]);
168
+ const observations = [...(status.observedTargets ?? []), ...(status.inventory ?? []).flatMap((root) => root.targetResults)];
169
+ return [...new Map((status.existingTargets ?? []).flatMap((target) => {
170
+ if (target.agent === 'generic' || !selected.has(target.pluginId)
171
+ || configContext === 'user' && target.scope !== 'user'
172
+ || platform && target.agent !== platform)
173
+ return [];
174
+ return [{ pluginId: target.pluginId, pluginName: parsePluginId(target.pluginId).pluginName,
175
+ platform: target.agent, scope: target.scope,
176
+ observation: observations.find((item) => item.pluginId === target.pluginId
177
+ && item.agent === target.agent && item.scope === target.scope) }];
178
+ }).map((target) => [`${target.pluginId}\0${target.platform}\0${target.scope}`, target])).values()]
179
+ .sort((left, right) => `${left.pluginId}\0${left.platform}\0${left.scope}`.localeCompare(`${right.pluginId}\0${right.platform}\0${right.scope}`, 'en'));
180
+ }
181
+ function currentTargetFingerprint(status, targets) {
182
+ return digest({ intent: status.intent, selection: status.selection, targets: targets.map((target) => ({
183
+ pluginId: target.pluginId, platform: target.platform, scope: target.scope,
184
+ observation: target.observation ? { observation: target.observation.observation,
185
+ content: target.observation.content, blockers: target.observation.blockers,
186
+ expectedVersion: target.observation.expectedVersion, installedVersion: target.observation.installedVersion,
187
+ deployments: target.observation.deploymentObservations,
188
+ exclusions: target.observation.deploymentExclusions,
189
+ gaps: target.observation.componentGaps } : null,
190
+ })) });
191
+ }
192
+ function scopedCurrentStatus(status, snapshot, scope) {
193
+ const demand = scope === 'project' ? snapshot.project : snapshot.user;
194
+ const inventory = demand.roots === null ? null : demand.roots.map((root) => ({
195
+ pluginId: root.pluginId, source: root.sourceId, sourceState: root.sourceState,
196
+ blockers: root.blockers.map((code) => ({ code, message: `来源需要处理:${code}。` })),
197
+ targetResults: (status.inventory ?? []).filter((entry) => entry.pluginId === root.pluginId)
198
+ .flatMap((entry) => entry.targetResults.filter((target) => target.scope === scope)),
199
+ }));
200
+ const targets = inventory?.flatMap((root) => root.targetResults) ?? [];
201
+ const counts = { blocked: targets.filter((target) => target.blockers.length > 0).length,
202
+ pending: targets.filter((target) => target.satisfaction !== 'not-applicable' && ['absent', 'drifted'].includes(target.content ?? '')).length,
203
+ unconfirmed: targets.filter((target) => target.content === 'unknown').length,
204
+ ready: targets.filter((target) => target.content === 'satisfied').length };
205
+ return { ...status, scope, intent: { state: demand.intent.state,
206
+ ...('digest' in demand.intent ? { digest: demand.intent.digest } : {}) }, inventory, counts,
207
+ extraObserved: status.extraObserved.filter((target) => target.scope === scope),
208
+ allSatisfied: counts.blocked || counts.pending ? false : counts.unconfirmed || inventory === null
209
+ || !['valid', 'absent'].includes(demand.intent.state) ? null : true };
210
+ }
211
+ /** Source metadata only. Actual installation facts are supplied by RecoveryStatus. */
212
+ async function loadCatalogView(options) {
213
+ return withResolvedMultiSourceCatalog({ cliVersion: options.cliVersion, env: options.context.env,
214
+ signal: options.signal, operationContext: options.catalogOperationContext,
215
+ consume: async (catalog) => ({
216
+ payload: { schemaVersion: 8, catalog: { primarySourceId: catalog.primarySourceId,
217
+ configDigest: catalog.configDigest, compositeDigest: catalog.compositeDigest,
218
+ ...(options.catalogOperationContext ? { generationSetDigest: options.catalogOperationContext.generationSetDigest } : {}),
219
+ sources: catalog.sources.map((item) => ({ id: item.sourceId,
220
+ identity: item.resolution?.sourceIdentity ?? '', type: item.resolution?.transport ?? 'path',
221
+ primary: item.sourceId === catalog.primarySourceId,
222
+ requestedRef: item.resolution?.requestedRef ?? 'AW channel',
223
+ ...(item.resolution ? { resolvedCommit: item.resolution.resolvedCommit,
224
+ catalogVersion: item.resolution.manifest.catalogVersion, channel: item.resolution.manifest.channel,
225
+ freshness: 'active' } : {}),
226
+ ...(item.error ? { error: sanitizeCatalogSourceError(item.error).message, errorCode: catalogSourceErrorCode(item.error) } : {}), })) }, filters: { plugins: [], platform: 'both', cwd: options.context.cwd }, targets: [], errors: [] },
227
+ pluginSummaries: (await Promise.all(catalog.sources.flatMap((item) => item.resolution
228
+ ? item.resolution.manifest.entries.map(async (entry) => {
229
+ const support = checkAwCapabilitySupport(entry.requires.aw.capabilities ?? [], IMPLEMENTED_AW_CAPABILITIES);
230
+ const metadata = { pluginName: entry.name,
231
+ pluginId: formatPluginId({ sourceId: item.sourceId, pluginName: entry.name }),
232
+ displayName: entry.interface?.displayName ?? entry.name, description: entry.description, version: entry.version };
233
+ // Future definitions may use a schema this CLI cannot parse. The source
234
+ // index is the boundary for deciding whether that definition can be read.
235
+ if (!support.supported)
236
+ return { ...metadata, missingCapabilities: support.missing };
237
+ try {
238
+ const manifest = await readPluginManifest(path.join(item.resolution.rootDir, 'plugins', entry.name), { mode: 'bundle' });
239
+ options.signal.throwIfAborted();
240
+ const platforms = [...resolveSupportedPlatforms(manifest.manifest)];
241
+ return { ...metadata, platforms, supportedTargets: Object.fromEntries(platforms.filter((platform) => platform !== 'generic')
242
+ .map((platform) => [platform, ['user', 'project']])),
243
+ configFieldCount: new Set(manifest.manifest.config ? [undefined, ...PLATFORM_TARGETS]
244
+ .flatMap((platform) => Object.keys(selectPluginConfigProfile(manifest.manifest.config, platform).fields)) : []).size,
245
+ ...(manifest.manifest.config ? { configSchema: manifest.manifest.config.fields } : {}) };
246
+ }
247
+ catch {
248
+ options.signal.throwIfAborted();
249
+ return { ...metadata, definitionUnavailable: true };
250
+ }
251
+ }) : []))),
252
+ }),
253
+ });
254
+ }
255
+ function configNeedsReferencePlugins(plugin) {
256
+ return pluginConfigHasExternalReferences(plugin.manifest)
257
+ || (plugin.manifest.config !== undefined && [undefined, ...PLATFORM_TARGETS].some((platform) => Object.values(selectPluginConfigProfile(plugin.manifest.config, platform).fields)
258
+ .some((field) => field.type === 'array' && field.items.type === 'object')));
259
+ }
260
+ async function configRetrySharedNativeRenderUnits(plugin, targets, env, referencePlugins) {
261
+ const plugins = await resolvePluginConfigReferenceConsumers({ plugin, env, plugins: referencePlugins });
262
+ return plugins.flatMap((consumer) => pluginSharedNativeConfigRenderUnits(consumer).filter((shared) => targets.some((target) => (target.pluginName ?? plugin.manifest.name) === consumer.manifest.name
263
+ && target.platform === shared.platform)));
264
+ }
265
+ function configPackageReviewChanges(plan, reviews) {
266
+ return [
267
+ ...describeConfigCommandPackageReviews(reviews).map((description) => ({
268
+ kind: 'change', group: 'configImpact', title: '命令包影响', description,
269
+ })),
270
+ ...managedCommandRecoveryPlanChanges(plan).map((change) => ({ ...change, group: 'configImpact' })),
271
+ ];
272
+ }
273
+ async function reviewConfigMutationApply(options, reviewed, fresh) {
274
+ const mayChangeHostPermissions = options.applyTargets?.some(({ platform }) => isPermissionHost(platform) || platform === 'claude');
275
+ // The writer revalidates the frozen command package candidate before saving.
276
+ if (fresh && !mayChangeHostPermissions)
277
+ return {
278
+ commandPackageEvidence: reviewed?.commandPackageEvidence,
279
+ commandReviewChanges: reviewed?.commandReviewChanges,
280
+ };
281
+ if (!options.applyCommandPackages?.length && !mayChangeHostPermissions)
282
+ return { commandPackageEvidence: [] };
283
+ const prepared = await preparePluginConfigApply(options);
284
+ try {
285
+ const hostPermissionEffects = recoveryHostPermissionEffects(prepared.plan);
286
+ return { commandPackageEvidence: prepared.commandPackageEvidence,
287
+ commandReviewChanges: configPackageReviewChanges(prepared.plan, prepared.commandPackageReviews),
288
+ ...(hostPermissionEffects.length ? { hostPermissionEffects } : {}) };
289
+ }
290
+ finally {
291
+ await disposePluginConfigApply(prepared.plan);
292
+ }
293
+ }
294
+ async function configRetryStoreDigest(options) {
295
+ const plugins = await resolvePluginConfigReferencePlugins({ sourceId: options.plugin.sourceId,
296
+ sourceIdentity: options.plugin.sourceIdentity, logicalIdentity: options.plugin.catalogLogicalIdentity,
297
+ env: options.env, plugins: options.plugins });
298
+ const byName = new Map([...plugins, options.plugin].map((plugin) => [plugin.manifest.name, plugin]));
299
+ const profiles = [{ pluginName: options.plugin.manifest.name, scope: options.scope, platform: options.platform },
300
+ ...options.targets.flatMap((target) => {
301
+ const plugin = byName.get(target.pluginName);
302
+ if (!plugin)
303
+ throw operationReviewStale('重试目标的插件定义已变化。');
304
+ return pluginConfigTargetRenderScopes(plugin, target).map((scope) => ({ pluginName: target.pluginName, scope, platform: target.platform }));
305
+ }),
306
+ ...options.commandPackages.flatMap(({ producer, runtimeConfigPlatforms }) => [undefined, ...runtimeConfigPlatforms]
307
+ .map((platform) => ({ pluginName: producer.pluginName, scope: 'user', platform }))),
308
+ ...options.preApplyAuthorization.map(({ pluginName, scope }) => ({ pluginName, scope, platform: options.platform }))];
309
+ return digest(await collectPluginConfigReferenceEvidence({ ...options, profiles, plugins }));
310
+ }
311
+ function configImpactVisibleTargets(pluginName, targets) {
312
+ return targets.map((target) => ({
313
+ pluginName: target.pluginName ?? pluginName,
314
+ platform: target.platform,
315
+ scope: target.scope,
316
+ }));
317
+ }
318
+ function configIntentRequestsApply(intent) {
319
+ if (!intent.apply)
320
+ return false;
321
+ if (intent.retryApply === true)
322
+ return true;
323
+ if (intent.changes)
324
+ return intent.changes.length > 0;
325
+ return Object.keys(intent.updates ?? {}).length > 0
326
+ || (intent.removeKeys?.length ?? 0) > 0;
327
+ }
328
+ function configSaveBatchGroupIntent(intent, group) {
329
+ return {
330
+ kind: 'configSave',
331
+ pluginId: intent.pluginId,
332
+ scope: 'user',
333
+ platform: group.platform,
334
+ context: intent.context ?? 'user',
335
+ apply: intent.apply,
336
+ ...(intent.scriptTimeoutMs === undefined ? {} : { scriptTimeoutMs: intent.scriptTimeoutMs }),
337
+ ...(group.updates ? { updates: group.updates } : {}),
338
+ ...(group.removeKeys ? { removeKeys: group.removeKeys } : {}),
339
+ ...(group.sensitiveKeys ? { sensitiveKeys: group.sensitiveKeys } : {}),
340
+ ...(group.privateKeys ? { privateKeys: group.privateKeys } : {}),
341
+ ...(group.changes ? { changes: group.changes } : {}),
342
+ };
343
+ }
344
+ function assertConfigSaveBatchIntent(intent) {
345
+ if (intent.groups.length === 0 || intent.groups.length > PLATFORM_TARGETS.length + 1
346
+ || new Set(intent.groups.map((group) => group.platform ?? 'common')).size !== intent.groups.length
347
+ || intent.groups.some((group) => Object.keys(group.updates ?? {}).length === 0
348
+ && (group.removeKeys?.length ?? 0) === 0)) {
349
+ throw new TuiOperationBlockedError('configBatchInvalid', '设置批次必须包含唯一且非空的公共或平台配置。');
350
+ }
84
351
  }
85
- function operationReviewStale(message) {
86
- return new TuiOperationBlockedError('operationReviewStale', `operationReviewStale: ${message}`);
352
+ function operationReviewStale(message, diagnostics) {
353
+ return new TuiOperationBlockedError('operationReviewStale', `operationReviewStale: ${message}`, diagnostics);
87
354
  }
88
355
  function sourceEvidenceForPlugin(source, pluginName) {
89
356
  const entry = source.manifest.entries.find((candidate) => candidate.name === pluginName);
90
357
  return {
91
358
  sourceId: source.sourceId,
92
359
  sourceIdentity: source.sourceIdentity,
360
+ logicalIdentity: source.logicalIdentity,
93
361
  requestedRef: source.requestedRef,
94
362
  resolvedCommit: source.resolvedCommit,
95
363
  manifestDigest: source.manifestDigest,
96
364
  snapshotDigest: source.snapshotDigest,
97
365
  contentDigest: entry.contentDigest,
366
+ pluginVersion: entry.version,
98
367
  catalogVersion: source.manifest.catalogVersion,
99
368
  channel: source.manifest.channel,
100
369
  };
101
370
  }
371
+ async function configLayerStoreDigest(options) {
372
+ const store = await readPluginConfigStore({
373
+ sourceId: options.source.sourceId,
374
+ sourceIdentity: options.source.sourceIdentity,
375
+ ...('logicalIdentity' in options.source
376
+ ? { logicalIdentity: options.source.logicalIdentity }
377
+ : {}),
378
+ pluginName: options.pluginName,
379
+ scope: 'user',
380
+ platform: options.platform,
381
+ cwd: options.cwd,
382
+ env: options.env,
383
+ });
384
+ return options.profileOnly
385
+ ? digest({ profile: options.platform ?? 'common', state: store.state === 'invalid' ? 'invalid' : 'ready',
386
+ values: store.values, ...(store.state === 'invalid' ? { rawDigest: store.rawDigest } : {}) })
387
+ : digest({ exists: store.exists, rawDigest: store.rawDigest });
388
+ }
102
389
  function assertSourceEvidenceMatches(expected, actual) {
103
390
  if (actual.sourceId !== expected.sourceId
104
391
  || actual.sourceIdentity !== expected.sourceIdentity
392
+ || actual.logicalIdentity !== expected.logicalIdentity
105
393
  || actual.resolvedCommit !== expected.resolvedCommit
106
394
  || actual.manifestDigest !== expected.manifestDigest
107
395
  || actual.snapshotDigest !== expected.snapshotDigest
@@ -109,162 +397,22 @@ function assertSourceEvidenceMatches(expected, actual) {
109
397
  throw operationReviewStale('确认后来源内容发生变化。');
110
398
  }
111
399
  }
112
- function throwIfWriteReviewStale(result) {
113
- const stale = result.targetResults.find((target) => target.errorCode === 'operationReviewStale');
114
- if (stale) {
115
- throw operationReviewStale('确认后实际写入计划发生变化。');
116
- }
117
- }
118
400
  const SOURCE_PROGRESS_PHASES = {
119
401
  savingConfig: '保存来源配置',
120
402
  };
121
- function pluginIntent(intent) {
122
- return 'pluginId' in intent;
123
- }
124
- function assertIntentIsLegal(intent, targets, revisions = []) {
125
- const platforms = intent.platform === 'both'
126
- ? ['codex', 'claude']
127
- : [intent.platform];
128
- for (const platform of platforms) {
129
- const platformTargets = targets.filter((target) => target.pluginId === intent.pluginId
130
- && target.platform === platform);
131
- const selected = platformTargets.find((target) => target.scope === intent.scope)
132
- ?? (platform === 'codex' ? platformTargets[0] : undefined);
133
- if (!selected || selected.errors.some((error) => error.code === 'unsupportedTarget')) {
134
- throw new TuiOperationBlockedError('unsupportedTarget', '所选插件不支持这个平台和使用位置。');
135
- }
136
- if (intent.action === 'sync' && platform !== 'codex') {
137
- throw new TuiOperationBlockedError('syncPlatformUnsupported', 'sync 只支持 Codex。');
138
- }
139
- if (intent.dependencyPlacementOnly === 'desired')
140
- continue;
141
- const otherScope = intent.scope === 'user' ? 'project' : 'user';
142
- const otherScopeInstalled = platform === 'codex'
143
- ? platformTargets.some((target) => target.desired.scopes.includes(otherScope)
144
- || target.activation?.[otherScope] === true)
145
- : targets.some((target) => target.platform === platform
146
- && target.scope !== intent.scope
147
- && (target.state === 'present' || target.state === 'partial'));
148
- const pureNativeCodex = isPureNativeCodexTarget(selected);
149
- if (intent.action === 'install' && otherScopeInstalled && !pureNativeCodex
150
- && !intent.dependencyPlacementAdjustment) {
151
- throw new TuiOperationBlockedError('scopeConflict', '这个平台已安装在另一个使用位置。请先移除原位置。');
152
- }
153
- if ((intent.action === 'install' || intent.action === 'upgrade' || intent.action === 'reinstall')
154
- && targetHasArtifactCollision(selected)) {
155
- throw new TuiOperationBlockedError('artifactCollision', '所选位置存在输出冲突。请先移除或迁移冲突内容。');
156
- }
157
- const selectedScopeInstalled = platform === 'codex'
158
- ? selected.desired.scopes.includes(intent.scope)
159
- || selected.activation?.[intent.scope] === true
160
- : selected.state !== 'absent';
161
- if (intent.action === 'install' && selectedScopeInstalled
162
- && !intent.dependencyPlacementAdjustment) {
163
- throw new TuiOperationBlockedError('targetAlreadyInstalled', '所选位置已经安装。');
164
- }
165
- if (intent.action === 'sync'
166
- && selected.actual.state !== 'needsSync'
167
- && selected.actual.state !== 'drifted'
168
- && selected.actual.state !== 'conflict') {
169
- throw new TuiOperationBlockedError('targetStateChanged', '当前安装状态不需要同步。');
170
- }
171
- const revision = revisions.find((entry) => entry.pluginId === intent.pluginId
172
- && entry.platform === platform && entry.scope === intent.scope)?.revision;
173
- if (intent.action === 'upgrade'
174
- && (selected.state !== 'present' || revision?.state !== 'upgradeAvailable')) {
175
- throw new TuiOperationBlockedError('targetStateChanged', '当前安装状态不允许执行这个操作。');
176
- }
177
- if (intent.action === 'uninstall' && !targetCanBeUninstalled(selected.state)) {
178
- throw new TuiOperationBlockedError('targetStateChanged', '当前安装状态不允许执行这个操作。');
179
- }
180
- if ((intent.action === 'reinstall' || intent.action === 'cleanup') && selected.state === 'absent') {
181
- throw new TuiOperationBlockedError('targetAbsent', '所选位置没有可处理的 AW 安装。');
182
- }
183
- }
184
- }
185
- async function assertTypedIssueOrigin(intent, targets) {
186
- if (!intent.originIssue)
187
- return;
188
- const stale = (message) => {
189
- throw new TuiOperationBlockedError('operationReviewStale', `operationReviewStale: ${message}`);
190
- };
191
- const selected = targets.find((target) => target.pluginId === intent.pluginId
192
- && target.platform === intent.platform
193
- && target.scope === intent.scope)
194
- ?? targets.find((target) => target.pluginId === intent.pluginId
195
- && target.platform === 'codex');
196
- if (intent.originIssue.category === 'dependencyMissing') {
197
- if (intent.originIssue.actionId !== 'installDependency'
198
- || intent.action !== 'install' || !selected || selected.state !== 'absent') {
199
- stale('原缺失依赖问题已变化。');
200
- }
201
- }
202
- else if (intent.originIssue.category === 'dependencyNotReady') {
203
- if (intent.originIssue.actionId !== 'reinstallDependency'
204
- || intent.action !== 'reinstall' || !selected
205
- || (selected.state !== 'partial' && selected.state !== 'error')) {
206
- stale('原依赖安装问题已变化。');
207
- }
208
- }
209
- else if (intent.originIssue.category === 'incompleteInstallation') {
210
- if (!selected || !targetCanBeUninstalled(selected.state) || selected.state !== 'partial'
211
- || !((intent.originIssue.actionId === 'reinstall' && intent.action === 'reinstall')
212
- || (intent.originIssue.actionId === 'remove' && intent.action === 'uninstall'))) {
213
- stale('原安装问题已变化。');
214
- }
215
- return;
216
- }
217
- else if (intent.originIssue.category === 'sourceUnavailable') {
218
- if (intent.originIssue.actionId !== 'cleanup' || intent.action !== 'cleanup'
219
- || !selected || !selected.errors.some((error) => error.code === 'bundleUnavailable')) {
220
- stale('原 Catalog 缺失插件问题已变化。');
221
- }
222
- return;
223
- }
224
- else if (intent.originIssue.category === 'sourceMissing') {
225
- if (intent.originIssue.actionId !== 'cleanup' || intent.action !== 'cleanup'
226
- || !selected || !selected.errors.some((error) => error.code === 'sourceMissing')) {
227
- stale('原来源缺失问题已变化。');
228
- }
229
- return;
403
+ function reviewedScriptTimeoutMs(intent) {
404
+ if (intent.kind === 'pluginWriteTask') {
405
+ return parseScriptTimeoutMs(intent.scriptTimeoutMs ?? SCRIPT_TIMEOUT_DEFAULT_MS);
230
406
  }
231
- else if (intent.originIssue.category === 'scopeConflict') {
232
- const installedScopes = new Set();
233
- for (const target of targets.filter((candidate) => candidate.pluginId === intent.pluginId && candidate.platform === intent.platform)) {
234
- if (target.state === 'present' || target.state === 'partial')
235
- installedScopes.add(target.scope);
236
- for (const scope of target.desired.scopes)
237
- installedScopes.add(scope);
238
- if (target.activation?.user === true)
239
- installedScopes.add('user');
240
- if (target.activation?.project === true)
241
- installedScopes.add('project');
242
- }
243
- const correctBranch = intent.action === 'uninstall'
244
- && ((intent.originIssue.actionId === 'keepUserScope' && intent.scope === 'project')
245
- || (intent.originIssue.actionId === 'keepProjectScope' && intent.scope === 'user'));
246
- if (!correctBranch || !installedScopes.has('user') || !installedScopes.has('project')) {
247
- stale('原位置冲突已变化。');
248
- }
249
- return;
407
+ if ((intent.kind === 'pluginWrite' || intent.kind === 'pluginWriteBatch')
408
+ && (intent.action === 'install' || intent.action === 'refreshAndSync'
409
+ || intent.action === 'reinstall' || intent.action === 'sync')) {
410
+ return parseScriptTimeoutMs(intent.scriptTimeoutMs ?? SCRIPT_TIMEOUT_DEFAULT_MS);
250
411
  }
251
- else
252
- stale('这个问题没有安全的自动写入动作。');
253
- const origin = intent.originIssue;
254
- if (!origin.consumerPluginId || !origin.consumerSourceIdentity || !origin.consumerPlatform
255
- || !origin.consumerScope || !origin.dependencyPluginId || !origin.dependencyPlatform
256
- || !origin.dependencyScope || origin.dependencyProject === undefined
257
- || origin.dependencyPluginId !== intent.pluginId
258
- || origin.dependencyPlatform !== intent.platform || origin.dependencyScope !== intent.scope) {
259
- stale('依赖问题来源缺少稳定目标证据。');
412
+ if ((intent.kind === 'configSave' || intent.kind === 'configSaveBatch') && intent.apply) {
413
+ return parseScriptTimeoutMs(intent.scriptTimeoutMs ?? SCRIPT_TIMEOUT_DEFAULT_MS);
260
414
  }
261
- const consumer = targets.find((target) => target.pluginId === origin.consumerPluginId
262
- && target.sourceIdentity === origin.consumerSourceIdentity
263
- && target.platform === origin.consumerPlatform
264
- && target.scope === origin.consumerScope);
265
- const consumerError = consumer?.errors.some((error) => error.code === origin.category && error.message.includes(origin.dependencyPluginId));
266
- if (!consumer || !consumerError)
267
- stale('原 consumer 依赖问题已消失或变化。');
415
+ return undefined;
268
416
  }
269
417
  async function loadDependencyOverviews(options) {
270
418
  const graph = await withResolvedMultiSourceCatalog({
@@ -281,6 +429,7 @@ async function loadDependencyOverviews(options) {
281
429
  sourceId: item.resolution.sourceId,
282
430
  pluginName: entry.name,
283
431
  }),
432
+ sourceIdentity: item.resolution.sourceIdentity,
284
433
  displayName: entry.interface?.displayName ?? entry.name,
285
434
  dependencies: entry.dependencies.map((pluginName) => formatPluginId({ sourceId: item.resolution.sourceId, pluginName })),
286
435
  }))
@@ -291,7 +440,7 @@ async function loadDependencyOverviews(options) {
291
440
  }),
292
441
  });
293
442
  const nodes = new Map(graph.nodes.map((node) => [node.pluginId, node]));
294
- const summaryById = new Map(options.status.pluginSummaries.map((summary) => [summary.pluginId, summary]));
443
+ const summaryById = new Map(options.pluginSummaries.map((summary) => [summary.pluginId, summary]));
295
444
  const displayName = (pluginId) => nodes.get(pluginId)?.displayName
296
445
  ?? parsePluginId(pluginId).pluginName;
297
446
  const reverse = new Map();
@@ -301,56 +450,52 @@ async function loadDependencyOverviews(options) {
301
450
  }
302
451
  }
303
452
  const targetsByPlugin = new Map();
304
- for (const target of options.status.payload.targets) {
453
+ for (const target of options.status.observedTargets ?? []) {
305
454
  targetsByPlugin.set(target.pluginId, [...(targetsByPlugin.get(target.pluginId) ?? []), target]);
306
455
  }
307
- const unsupportedPluginIds = new Set(options.status.pluginSummaries
308
- .filter((summary) => (summary.missingCapabilities?.length ?? 0) > 0)
456
+ const unsupportedPluginIds = new Set(options.pluginSummaries.filter((summary) => (summary.missingCapabilities?.length ?? 0) > 0)
309
457
  .map((summary) => summary.pluginId));
310
- const placementReferences = new Map();
311
- for (const consumer of options.status.payload.targets.filter((target) => target.state !== 'absent')) {
312
- const consumerNode = nodes.get(consumer.pluginId);
313
- if (!consumerNode)
314
- continue;
315
- for (const dependencyPluginId of consumerNode.dependencies) {
316
- const dependencyTargets = (targetsByPlugin.get(dependencyPluginId) ?? [])
317
- .filter((target) => target.platform === consumer.platform);
318
- const projectTarget = dependencyTargets.find((target) => target.scope === 'project');
319
- const userTarget = dependencyTargets.find((target) => target.scope === 'user');
320
- const dependencyScope = consumer.scope === 'user'
321
- ? 'user'
322
- : userTarget && (!projectTarget
323
- || (userTarget.state !== 'absent' && projectTarget.state === 'absent'))
324
- ? 'user'
325
- : 'project';
326
- const reference = {
327
- consumer: {
328
- pluginId: consumer.pluginId,
329
- platform: consumer.platform,
330
- scope: consumer.scope,
331
- project: consumer.scope === 'project' ? 'current' : null,
332
- },
333
- dependency: {
334
- pluginId: dependencyPluginId,
335
- platform: consumer.platform,
336
- scope: dependencyScope,
337
- project: dependencyScope === 'project' ? 'current' : null,
338
- },
339
- };
340
- const key = `${consumer.pluginId}\0${dependencyPluginId}`;
341
- placementReferences.set(key, [...(placementReferences.get(key) ?? []), reference]);
342
- }
343
- }
344
- const placementsFor = (pluginId) => {
345
- const targets = targetsByPlugin.get(pluginId) ?? [];
346
- if (targets.length > 0) {
347
- return ['codex', 'claude'].flatMap((platform) => {
348
- const selected = targets.filter((target) => target.platform === platform);
349
- return selected.length > 0 ? [projectPlatformPlacement(platform, selected)] : [];
458
+ const availableReferencesFor = (rootId, dependencyId) => {
459
+ const references = (targetsByPlugin.get(dependencyId) ?? []).flatMap((dependency) => {
460
+ if (dependency.agent === 'generic' || dependency.content !== 'satisfied' || dependency.observation !== 'verified'
461
+ || dependency.providerScope !== dependency.scope
462
+ || !options.status.existingTargets?.some((item) => item.pluginId === dependencyId
463
+ && item.agent === dependency.agent && item.scope === dependency.scope))
464
+ return [];
465
+ return (dependency.contributions ?? []).flatMap((contribution) => {
466
+ if (contribution.root !== rootId || contribution.path.at(-1) !== dependencyId || contribution.path.length < 2)
467
+ return [];
468
+ const parentId = contribution.path.at(-2);
469
+ if (!nodes.get(parentId)?.dependencies.includes(dependencyId)
470
+ || nodes.get(parentId)?.sourceIdentity !== nodes.get(dependencyId)?.sourceIdentity)
471
+ return [];
472
+ return (targetsByPlugin.get(parentId) ?? []).filter((consumer) => consumer.agent === dependency.agent
473
+ && consumer.providerScope === consumer.scope
474
+ && consumer.contributions?.some((entry) => entry.root === contribution.root && entry.scope === contribution.scope
475
+ && JSON.stringify(entry.path) === JSON.stringify(contribution.path.slice(0, -1)))
476
+ && options.status.existingTargets?.some((item) => item.pluginId === parentId && item.agent === consumer.agent && item.scope === consumer.scope))
477
+ .map((consumer) => ({ requirementScope: contribution.scope,
478
+ consumer: { pluginId: parentId, platform: dependency.agent, scope: consumer.scope,
479
+ project: consumer.scope === 'project' ? 'current' : null },
480
+ dependency: { pluginId: dependencyId, platform: dependency.agent, scope: dependency.scope,
481
+ project: dependency.scope === 'project' ? 'current' : null } }));
350
482
  });
351
- }
352
- return [];
483
+ });
484
+ return [...new Map(references.map((reference) => [JSON.stringify(reference), reference])).values()];
353
485
  };
486
+ const placementsFor = (pluginId) => (targetsByPlugin.get(pluginId) ?? []).flatMap((target) => {
487
+ if (target.agent === 'generic')
488
+ return [];
489
+ const exists = options.status.existingTargets?.some((item) => item.pluginId === pluginId
490
+ && item.agent === target.agent && item.scope === target.scope);
491
+ if (!exists)
492
+ return [{ platform: target.agent, state: 'notInstalled', supportedScopes: ['user', 'project'] }];
493
+ return [{ platform: target.agent, state: 'installed', scope: target.scope,
494
+ health: target.content === 'satisfied' && !target.blockers.length ? 'ready'
495
+ : target.blockers.length || target.content === 'conflict' ? 'error' : 'incomplete',
496
+ revision: { state: 'unknown', ...(target.expectedVersion ? { availableVersion: target.expectedVersion } : {}),
497
+ ...(target.installedVersion ? { installedVersion: target.installedVersion } : {}) }, relation: target.relation === 'dependency' ? 'dependency' : 'root' }];
498
+ });
354
499
  const aggregateFor = (pluginId, placements) => {
355
500
  const sourceId = parsePluginId(pluginId).sourceId;
356
501
  if (graph.sourceErrors.some((error) => error.sourceId === sourceId)
@@ -412,7 +557,8 @@ async function loadDependencyOverviews(options) {
412
557
  })),
413
558
  placements,
414
559
  aggregateStatus: aggregateFor(dependency.pluginId, placements),
415
- placementReferences: placementReferences.get(`${pluginId}\0${dependency.pluginId}`) ?? [],
560
+ placementReferences: [],
561
+ availablePlacementReferences: availableReferencesFor(pluginId, dependency.pluginId),
416
562
  };
417
563
  });
418
564
  const dependentIds = [...new Set(reverse.get(pluginId) ?? [])].sort();
@@ -426,10 +572,11 @@ async function loadDependencyOverviews(options) {
426
572
  requiredBy: [],
427
573
  placements,
428
574
  aggregateStatus: aggregateFor(dependentId, placements),
429
- placementReferences: placementReferences.get(`${dependentId}\0${pluginId}`) ?? [],
575
+ placementReferences: [],
576
+ availablePlacementReferences: availableReferencesFor(dependentId, pluginId),
430
577
  };
431
578
  });
432
- const targetBlockers = (targetsByPlugin.get(pluginId) ?? []).flatMap((target) => target.errors.filter((error) => error.code.startsWith('dependency') || error.code === 'sourceChanged')
579
+ const targetBlockers = (targetsByPlugin.get(pluginId) ?? []).flatMap((target) => target.blockers.filter((error) => error.code.startsWith('dependency') || error.code === 'sourceChanged')
433
580
  .map((error) => ({
434
581
  code: error.code,
435
582
  title: '依赖关系需要处理',
@@ -440,7 +587,7 @@ async function loadDependencyOverviews(options) {
440
587
  const dependencyTargets = summaryById.get(dependency.pluginId)?.supportedTargets;
441
588
  if (!consumerTargets || !dependencyTargets)
442
589
  return true;
443
- return ['codex', 'claude'].some((platform) => consumerTargets[platform].length > 0 && dependencyTargets[platform].length === 0);
590
+ return NATIVE_PLATFORM_TARGETS.some((platform) => (consumerTargets[platform]?.length ?? 0) > 0 && (dependencyTargets[platform]?.length ?? 0) === 0);
444
591
  });
445
592
  const sourceId = parsePluginId(pluginId).sourceId;
446
593
  const blockers = [
@@ -508,13 +655,15 @@ function createReviewStageReporter(options) {
508
655
  export function createTuiControllerDependencies(context, progressFeed, options = {}) {
509
656
  const readInventory = options.inventoryCatalogSourceReferences
510
657
  ?? inventoryCatalogSourceReferences;
511
- const validatedStoreEntries = new Map();
512
- const validatingStoreEntries = new Map();
513
- const loadCatalogGenerations = async () => {
658
+ let validatedStoreEntries = new Map();
659
+ let validatingStoreEntries = new Map();
660
+ const loadCatalogGenerations = async (entries, signal, preparation) => {
514
661
  const generations = await loadCatalogGenerationViewModels({
515
662
  env: context.env,
516
- validatedStoreEntries,
517
- validatingStoreEntries,
663
+ signal,
664
+ preparation,
665
+ validatedStoreEntries: entries,
666
+ validatingStoreEntries: new Map(),
518
667
  onStage: (event) => context.debugLogger.log({
519
668
  type: 'performance:stage',
520
669
  level: 'debug',
@@ -526,18 +675,15 @@ export function createTuiControllerDependencies(context, progressFeed, options =
526
675
  const retained = new Set(generations.flatMap((source) => [
527
676
  source.active?.storeKey,
528
677
  ].filter((value) => value !== undefined)));
529
- for (const storeKey of validatedStoreEntries.keys()) {
678
+ for (const storeKey of entries.keys()) {
530
679
  if (!retained.has(storeKey))
531
- validatedStoreEntries.delete(storeKey);
680
+ entries.delete(storeKey);
532
681
  }
533
682
  return generations;
534
683
  };
535
684
  const createOperationInventoryReader = () => {
536
685
  let ordinaryInventory;
537
686
  return (inventoryOptions) => {
538
- if (inventoryOptions.includeHistoricalProjects === true) {
539
- return readInventory(inventoryOptions);
540
- }
541
687
  ordinaryInventory ??= readInventory(inventoryOptions);
542
688
  return ordinaryInventory;
543
689
  };
@@ -545,43 +691,103 @@ export function createTuiControllerDependencies(context, progressFeed, options =
545
691
  const catalogOperationByEvidence = new WeakMap();
546
692
  let sessionCatalogOperationContext;
547
693
  let sessionStatusResult;
694
+ let sessionRecoveryStatus;
695
+ let latestStatusRead = 0;
696
+ let bindNewCatalog = true;
548
697
  const sessionContextForPlugin = (pluginId) => {
549
698
  const sourceId = parsePluginId(pluginId).sourceId;
550
699
  if (!sourceId || !sessionCatalogOperationContext)
551
700
  return undefined;
552
701
  return selectCatalogOperationContext(sessionCatalogOperationContext, [sourceId]);
553
702
  };
703
+ const readConfigStoresForTui = async (config) => {
704
+ const user = await readPluginConfigStore({
705
+ sourceId: config.sourceId,
706
+ sourceIdentity: config.sourceIdentity,
707
+ logicalIdentity: config.logicalIdentity,
708
+ pluginName: config.pluginName,
709
+ scope: 'user',
710
+ platform: config.platform,
711
+ cwd: context.cwd,
712
+ env: context.env,
713
+ schema: config.schema,
714
+ });
715
+ config.signal.throwIfAborted();
716
+ if (user.state === 'invalid')
717
+ throw new TuiConfigInvalidStoreError([{
718
+ scope: 'user', code: user.invalidCode,
719
+ pathSummary: `AW_HOME/plugin-config/${config.sourceId ?? '<source>'}/${config.pluginName}/config.json`,
720
+ }]);
721
+ return { user };
722
+ };
723
+ const assertConfigEditEvidence = async (intent, evidence) => {
724
+ if (!intent.editEvidence)
725
+ return;
726
+ if (!evidence.source || !evidence.config)
727
+ throw operationReviewStale('设置编辑缺少当前证据。');
728
+ const currentDigest = await configLayerStoreDigest({ source: evidence.source,
729
+ pluginName: parsePluginId(intent.pluginId).pluginName, scope: 'user', platform: intent.platform,
730
+ cwd: context.cwd, env: context.env });
731
+ for (const expected of Object.values(intent.editEvidence)) {
732
+ if (expected.sourceIdentity !== evidence.source.sourceIdentity
733
+ || expected.schemaIdentity !== evidence.config.schemaIdentity
734
+ || expected.platform !== intent.platform
735
+ || (expected.context ?? 'user') !== (intent.context ?? 'user')
736
+ || expected.storeDigests.user !== undefined && expected.storeDigests.user !== currentDigest) {
737
+ throw operationReviewStale('编辑期间设置、来源或定义已变化。请重新打开设置。');
738
+ }
739
+ }
740
+ };
554
741
  const loadStatus = async (signal) => {
555
742
  signal.throwIfAborted();
743
+ const read = ++latestStatusRead;
744
+ const pinnedContext = bindNewCatalog ? undefined : sessionCatalogOperationContext;
745
+ const sessionStoreEntries = validatedStoreEntries;
556
746
  const packageInfo = await readCliPackageInfo();
557
- const catalogOperationContext = sessionCatalogOperationContext
558
- ?? await resolvePartialCatalogOperationContext({
559
- env: context.env,
560
- signal,
561
- validatedStoreEntries,
562
- validatingStoreEntries,
563
- }).catch(() => undefined);
564
- if (catalogOperationContext)
565
- sessionCatalogOperationContext = catalogOperationContext;
566
747
  for (let attempt = 0; attempt < 3; attempt += 1) {
567
- const result = await statusCommandV6({
568
- cwd: context.cwd,
569
- env: context.env,
570
- cliVersion: packageInfo.version,
571
- verbose: context.diagnostics.verbose,
572
- ...(catalogOperationContext ? { catalogOperationContext } : {}),
573
- inventoryCatalogSourceReferences: readInventory,
748
+ const catalogReadScope = pinnedContext ? undefined : new CatalogPreparationReadScope({ env: context.env, signal });
749
+ const catalogOperationContext = pinnedContext ?? await catalogReadScope?.resolve({}).catch(async (error) => {
750
+ signal.throwIfAborted();
751
+ if (!(error instanceof CatalogGenerationError)
752
+ || error.code !== 'catalogGenerationStateInvalid')
753
+ return undefined;
754
+ const snapshot = await readCatalogSourcesConfigSnapshot(context.env);
755
+ const primarySourceId = snapshot.config.sources.find((source) => source.primary).id;
756
+ const generationSetDigest = calculateCatalogGenerationSetDigest(snapshot.digest, primarySourceId, []);
757
+ return {
758
+ generationSet: {
759
+ generationSetDigest,
760
+ configDigest: snapshot.digest,
761
+ primarySourceId,
762
+ sources: [],
763
+ },
764
+ generationSetDigest,
765
+ catalog: {
766
+ sources: snapshot.config.sources.map((source) => ({
767
+ sourceId: source.id,
768
+ error,
769
+ })),
770
+ primarySourceId,
771
+ configDigest: snapshot.digest,
772
+ compositeDigest: generationSetDigest,
773
+ },
774
+ };
574
775
  });
575
- signal.throwIfAborted();
576
- const configured = await listCatalogSources({ env: context.env });
577
- signal.throwIfAborted();
578
- if (result.payload.catalog.configDigest !== configured.configDigest)
579
- continue;
580
- sessionStatusResult = result;
776
+ const result = await loadCatalogView({ context, cliVersion: packageInfo.version, signal,
777
+ ...(catalogOperationContext ? { catalogOperationContext } : {}) });
778
+ const snapshot = await readJointDemand({ cwd: context.cwd, env: context.env, signal, catalogOperationContext, catalogReadScope,
779
+ ...(catalogOperationContext ? { resolveCatalog: async () => ({
780
+ context: catalogOperationContext,
781
+ configured: new Set(catalogOperationContext.catalog.sources.map((source) => source.sourceId)),
782
+ }) } : {}),
783
+ });
784
+ const current = await readRecoveryStatus({ cwd: context.cwd, env: context.env, signal,
785
+ cliVersion: packageInfo.version, nativeCliRunner: context.nativeCliRunner, catalogOperationContext, catalogReadScope }, snapshot);
581
786
  const dependencyOverviews = await loadDependencyOverviews({
582
787
  context,
583
788
  cliVersion: packageInfo.version,
584
- status: result,
789
+ status: current,
790
+ pluginSummaries: result.pluginSummaries,
585
791
  signal,
586
792
  ...(catalogOperationContext ? { catalogOperationContext } : {}),
587
793
  });
@@ -592,16 +798,51 @@ export function createTuiControllerDependencies(context, progressFeed, options =
592
798
  ...(catalogOperationContext ? { catalogOperationContext } : {}),
593
799
  });
594
800
  signal.throwIfAborted();
595
- const catalogGenerations = await loadCatalogGenerations();
801
+ const storeEntries = new Map(catalogReadScope ? undefined : sessionStoreEntries);
802
+ const catalogGenerations = await loadCatalogGenerations(storeEntries, signal, catalogReadScope
803
+ ? { scope: catalogReadScope, context: catalogOperationContext } : undefined);
804
+ signal.throwIfAborted();
805
+ const configStoreInventory = (await Promise.all(['user'].map(async (scope) => {
806
+ try {
807
+ return (await listNamespacedPluginConfigStoreIdentities({
808
+ cwd: context.cwd,
809
+ env: context.env,
810
+ scope,
811
+ })).map(({ pluginId, sourceId, pluginName }) => ({
812
+ pluginId, sourceId, pluginName, scope,
813
+ }));
814
+ }
815
+ catch {
816
+ await context.debugLogger.log({
817
+ type: 'tui:config-inventory-error',
818
+ level: 'debug',
819
+ target: 'debugLog',
820
+ message: 'TUI saved config inventory could not be read.',
821
+ data: { scope },
822
+ });
823
+ return [];
824
+ }
825
+ }))).flat();
826
+ const configured = await listCatalogSources({ env: context.env });
596
827
  signal.throwIfAborted();
828
+ if (result.payload.catalog.configDigest !== configured.configDigest
829
+ || catalogOperationContext && !homeGenerationsMatch(catalogOperationContext, catalogGenerations, configured)) {
830
+ if (pinnedContext)
831
+ break;
832
+ continue;
833
+ }
597
834
  const statusById = new Map(result.payload.catalog.sources.map((source) => [source.id, source]));
598
- return {
835
+ const status = {
599
836
  cliChannel: packageInfo.version.includes('-') ? 'beta' : 'latest',
837
+ ...(current.coverage.projectRoot ? { projectRoot: current.coverage.projectRoot } : {}),
838
+ scopedRecovery: { user: { ...scopedCurrentStatus(current, snapshot, 'user'), dependencyOverviews },
839
+ ...(snapshot.project ? { project: { ...scopedCurrentStatus(current, snapshot, 'project'), dependencyOverviews } } : {}) },
840
+ configuredSources: structuredClone(configured.sources),
600
841
  payload: result.payload,
601
842
  pluginSummaries: result.pluginSummaries,
602
- targetRevisions: result.targetRevisions,
603
843
  dependencyOverviews,
604
844
  portablePluginIds,
845
+ configStoreInventory,
605
846
  catalogGenerations,
606
847
  sessionGenerationKeys: Object.fromEntries((catalogOperationContext?.generationSet.sources ?? [])
607
848
  .map((source) => [source.sourceId, source.storeKey])),
@@ -611,6 +852,7 @@ export function createTuiControllerDependencies(context, progressFeed, options =
611
852
  id: source.id,
612
853
  type: source.type,
613
854
  primary: source.primary,
855
+ autoCheck: source.autoCheck,
614
856
  locationSummary: projectCatalogSourceLocation(source.type === 'git' ? source.url : source.path),
615
857
  ...(source.type === 'git' ? {
616
858
  refPolicy: source.refPolicy.type,
@@ -629,219 +871,856 @@ export function createTuiControllerDependencies(context, progressFeed, options =
629
871
  };
630
872
  }),
631
873
  };
874
+ // Details and Review consume the same accepted read as the home view.
875
+ if (read === latestStatusRead) {
876
+ bindNewCatalog = false;
877
+ sessionCatalogOperationContext = catalogOperationContext;
878
+ sessionStatusResult = result;
879
+ sessionRecoveryStatus = current;
880
+ validatedStoreEntries = storeEntries;
881
+ validatingStoreEntries = new Map();
882
+ }
883
+ return status;
632
884
  }
633
- throw new TuiOperationBlockedError('operationReviewStale', '状态读取期间来源配置持续变化。请重试。');
885
+ throw new TuiOperationBlockedError('operationReviewStale', '状态读取期间 Catalog 持续变化。请按 H 重新加载。');
634
886
  };
635
- const captureEvidence = async (intent, signal, preparation, operationInventory = createOperationInventoryReader(), freshCatalog = false) => {
636
- if (intent.kind === 'sourceMutation') {
637
- signal?.throwIfAborted();
638
- if (intent.action === 'add' && !intent.source
639
- || intent.action === 'update' && !intent.update) {
640
- throw new TuiOperationBlockedError('invalidSourceMutation', '来源操作缺少候选输入。');
641
- }
642
- const request = intent.action === 'add'
643
- ? { action: 'add', source: intent.source }
644
- : intent.action === 'update'
645
- ? { action: 'update', sourceId: intent.sourceId, update: intent.update }
646
- : { action: intent.action, sourceId: intent.sourceId };
647
- await preparation?.reporter.emit('validate');
648
- const preview = await preflightCatalogSourceMutation({
649
- request,
650
- cwd: context.cwd,
887
+ const loadPluginContent = async (pluginId, signal) => {
888
+ signal.throwIfAborted();
889
+ try {
890
+ const packageInfo = await readCliPackageInfo();
891
+ const catalogOperation = sessionContextForPlugin(pluginId);
892
+ return await withResolvedCatalogPlugin({
893
+ selector: pluginId,
894
+ cliVersion: packageInfo.version,
651
895
  env: context.env,
896
+ signal,
897
+ ...(catalogOperation ? { operationContext: catalogOperation } : {}),
898
+ consume: ({ plugin, source }) => projectPluginContentOverview({
899
+ pluginId,
900
+ catalogVersion: source.manifest.catalogVersion,
901
+ plugin,
902
+ }),
652
903
  });
904
+ }
905
+ catch {
906
+ signal.throwIfAborted();
907
+ const summary = sessionStatusResult?.pluginSummaries.find((entry) => entry.pluginId === pluginId);
908
+ let sourceId;
909
+ try {
910
+ sourceId = parsePluginId(pluginId).sourceId;
911
+ }
912
+ catch {
913
+ // The fixed unavailable result below does not repeat an unsafe selector.
914
+ }
915
+ const catalogVersion = sessionStatusResult?.payload.catalog.sources
916
+ .find((source) => source.id === sourceId)?.catalogVersion;
917
+ return {
918
+ pluginId,
919
+ pluginVersion: summary?.version ?? '待确认',
920
+ catalogVersion: catalogVersion ?? '待确认',
921
+ evidence: 'unavailable',
922
+ items: [],
923
+ notices: ['当前无法安全读取这个插件的目录内容。请检查来源状态后重试。'],
924
+ coverage: 'unavailable',
925
+ coverageIssue: {
926
+ code: 'unreadable',
927
+ message: '当前无法安全读取这个插件的目录内容。请检查来源状态后重试。',
928
+ },
929
+ };
930
+ }
931
+ };
932
+ const captureEvidence = async (intent, signal, preparation, operationInventory = createOperationInventoryReader(), freshCatalog = false, reusableCandidate, reviewedEvidence) => {
933
+ if (intent.kind === 'pluginWrite' || intent.kind === 'pluginWriteBatch'
934
+ || intent.kind === 'pluginWriteTask') {
935
+ throw new TuiOperationBlockedError('useScopedRecovery', '请使用统一范围恢复任务。');
936
+ }
937
+ reviewedScriptTimeoutMs(intent);
938
+ if ((intent.kind === 'configSave' || intent.kind === 'configSaveBatch' || intent.kind === 'configReset')
939
+ && intent.context === 'project') {
940
+ await resolveWorkContext({ cwd: context.cwd, context: 'project' });
653
941
  signal?.throwIfAborted();
654
- await preparation?.reporter.emit('evidence');
942
+ }
943
+ if (intent.kind === 'catalogStorePrune') {
655
944
  signal?.throwIfAborted();
656
- const evidence = {
657
- catalog: { configDigest: preview.configDigest, compositeDigest: preview.proposedConfigDigest },
658
- sourceWrite: {
659
- configDigest: preview.configDigest,
660
- proposedConfigDigest: preview.proposedConfigDigest,
661
- ...(preview.sourceIdentity ? { sourceIdentity: preview.sourceIdentity } : {}),
662
- inventoryDigest: digest({ references: preview.references.references, errors: preview.references.errors }),
663
- referenceCount: preview.references.references.length,
664
- inventoryComplete: preview.references.errors.length === 0,
665
- },
945
+ const config = await readCatalogSourcesConfigSnapshot(context.env);
946
+ const catalogStore = await prepareCatalogStoreTask({ env: context.env });
947
+ signal?.throwIfAborted();
948
+ return {
949
+ catalog: { configDigest: config.digest, compositeDigest: config.digest },
950
+ catalogStore,
666
951
  };
667
- if (preparation?.validateIntent
668
- && evidence.sourceWrite?.configDigest === evidence.sourceWrite?.proposedConfigDigest) {
669
- throw new TuiOperationBlockedError('sourceNoChanges', '来源没有变化。');
952
+ }
953
+ if (intent.kind === 'configSaveBatch') {
954
+ assertConfigSaveBatchIntent(intent);
955
+ const groupEvidence = [];
956
+ let batchBase;
957
+ let batchCatalogOperation;
958
+ for (const group of intent.groups) {
959
+ const current = await captureEvidence(configSaveBatchGroupIntent(intent, group), signal, preparation, operationInventory, freshCatalog, reusableCandidate, { config: reviewedEvidence?.configBatch?.groups.find((item) => item.platform === group.platform)?.config });
960
+ if (!current.config || !current.source || !current.targetFingerprint) {
961
+ throw operationReviewStale('设置批次缺少单层证据。');
962
+ }
963
+ if (batchBase && (JSON.stringify(batchBase.catalog) !== JSON.stringify(current.catalog)
964
+ || JSON.stringify(batchBase.source) !== JSON.stringify(current.source))) {
965
+ throw operationReviewStale('准备设置批次期间 Catalog 或来源发生变化。');
966
+ }
967
+ for (const expected of Object.values(group.editEvidence ?? {})) {
968
+ if (expected.sourceIdentity !== current.source.sourceIdentity
969
+ || expected.schemaIdentity !== current.config.schemaIdentity
970
+ || expected.platform !== group.platform
971
+ || (expected.context ?? 'user') !== (intent.context ?? 'user')) {
972
+ throw operationReviewStale('编辑期间插件来源或设置定义已变化,请重新打开列表。');
973
+ }
974
+ for (const scope of ['user']) {
975
+ if (expected.storeDigests[scope] === undefined)
976
+ continue;
977
+ const currentDigest = await configLayerStoreDigest({
978
+ source: current.source, pluginName: parsePluginId(intent.pluginId).pluginName,
979
+ scope, cwd: context.cwd, env: context.env,
980
+ });
981
+ if (expected.storeDigests[scope] !== currentDigest) {
982
+ throw operationReviewStale('编辑期间设置已被外部修改,请重新打开列表。');
983
+ }
984
+ }
985
+ }
986
+ batchBase ??= current;
987
+ batchCatalogOperation ??= catalogOperationByEvidence.get(current);
988
+ groupEvidence.push({
989
+ scope: 'user',
990
+ platform: group.platform,
991
+ config: {
992
+ ...current.config,
993
+ storeDigest: await configLayerStoreDigest({
994
+ source: current.source,
995
+ pluginName: parsePluginId(intent.pluginId).pluginName,
996
+ scope: 'user',
997
+ platform: group.platform,
998
+ profileOnly: true,
999
+ cwd: context.cwd,
1000
+ env: context.env,
1001
+ }),
1002
+ },
1003
+ targetFingerprint: current.targetFingerprint,
1004
+ });
670
1005
  }
1006
+ const evidence = {
1007
+ catalog: batchBase.catalog,
1008
+ source: batchBase.source,
1009
+ configBatch: { groups: groupEvidence },
1010
+ };
1011
+ if (batchCatalogOperation)
1012
+ catalogOperationByEvidence.set(evidence, batchCatalogOperation);
671
1013
  return evidence;
672
1014
  }
673
- if (!pluginIntent(intent)) {
674
- throw new TuiOperationBlockedError('operationNotImplemented', '这个写操作尚未接入新 Controller。');
675
- }
676
- signal?.throwIfAborted();
677
- const packageInfo = await readCliPackageInfo();
678
- const offlineCleanupReason = intent.kind === 'pluginWrite'
679
- && intent.action === 'cleanup'
680
- && intent.originIssue?.actionId === 'cleanup'
681
- && (intent.originIssue?.category === 'sourceMissing'
682
- || intent.originIssue?.category === 'sourceUnavailable')
683
- ? intent.originIssue.category === 'sourceMissing' ? 'sourceMissing' : 'bundleUnavailable'
684
- : undefined;
685
- let catalogOperation;
686
- let catalogOperationError;
687
- if (!offlineCleanupReason && intent.kind !== 'portableInstall') {
688
- try {
689
- const sourceIds = [parsePluginId(intent.pluginId).sourceId];
690
- catalogOperation = !freshCatalog && sessionCatalogOperationContext
691
- ? selectCatalogOperationContext(sessionCatalogOperationContext, sourceIds)
692
- : await resolveCatalogOperationContext({
693
- sourceIds,
694
- env: context.env,
695
- ...(!freshCatalog ? { validatedStoreEntries, validatingStoreEntries } : {}),
696
- ...(signal ? { signal } : {}),
697
- });
698
- }
699
- catch (error) {
700
- catalogOperationError = error;
1015
+ if (intent.kind === 'configReset') {
1016
+ const parsed = parsePluginId(intent.pluginId);
1017
+ if (!parsed.sourceId || !parsed.pluginName) {
1018
+ throw new TuiOperationBlockedError('invalidPluginId', '设置目标必须使用 canonical pluginId。');
701
1019
  }
702
- }
703
- if (intent.kind === 'portableInstall') {
704
- await preparation?.reporter.emit('portable');
705
- const portableSourceId = parsePluginId(intent.pluginId).sourceId;
706
- const portableCatalogOperation = sessionCatalogOperationContext
707
- ? selectCatalogOperationContext(sessionCatalogOperationContext, [portableSourceId])
708
- : undefined;
709
- const portable = await preparePortableInstall({
710
- selector: intent.pluginId,
711
- scope: intent.scope,
712
- ...(intent.selectedSkills.length > 0 ? { requestedSkills: intent.selectedSkills } : {}),
713
- ...(intent.requestedAgents ? { requestedAgents: intent.requestedAgents } : {}),
1020
+ await preparation?.reporter.emit('config');
1021
+ const target = await inspectPluginConfigResetTarget({
1022
+ sourceId: parsed.sourceId,
1023
+ pluginName: parsed.pluginName,
1024
+ scope: 'user',
714
1025
  cwd: context.cwd,
715
1026
  env: context.env,
716
- cliVersion: packageInfo.version,
717
- signal,
718
- ...(portableCatalogOperation
719
- ? { catalogOperationContext: portableCatalogOperation }
720
- : {}),
721
1027
  });
722
1028
  signal?.throwIfAborted();
1029
+ if (target.kind === 'special') {
1030
+ throw new TuiOperationBlockedError('configResetTargetUnsupported', '设置目标是特殊文件系统节点,不能自动重置。请手动移动后重试。');
1031
+ }
1032
+ const relevantTargets = sessionRecoveryStatus
1033
+ ? currentConfigTargets(sessionRecoveryStatus, intent.pluginId, intent.context ?? 'user', [], intent.platform)
1034
+ : [];
1035
+ let selected;
1036
+ try {
1037
+ const packageInfo = await readCliPackageInfo();
1038
+ selected = await withResolvedCatalogPlugin({
1039
+ selector: intent.pluginId,
1040
+ cliVersion: packageInfo.version,
1041
+ env: context.env,
1042
+ ...(preparation && sessionContextForPlugin(intent.pluginId)
1043
+ ? { operationContext: sessionContextForPlugin(intent.pluginId) }
1044
+ : {}),
1045
+ ...(signal ? { signal } : {}),
1046
+ consume: async ({ plugin, source: resolvedSource }) => ({
1047
+ source: sourceEvidenceForPlugin(resolvedSource, plugin.manifest.name),
1048
+ impact: await analyzePluginConfigMutationImpact({
1049
+ plugin,
1050
+ scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1051
+ cwd: context.cwd,
1052
+ env: context.env,
1053
+ visibleTargets: configImpactVisibleTargets(plugin.manifest.name, relevantTargets),
1054
+ mutation: { kind: 'reset' },
1055
+ }),
1056
+ }),
1057
+ });
1058
+ }
1059
+ catch (error) {
1060
+ if (error?.code === 'configValidationMemoryExhausted')
1061
+ throw error;
1062
+ selected = undefined;
1063
+ }
1064
+ signal?.throwIfAborted();
723
1065
  await preparation?.reporter.emit('evidence');
1066
+ return {
1067
+ catalog: sessionStatusResult ? {
1068
+ configDigest: sessionStatusResult.payload.catalog.configDigest,
1069
+ compositeDigest: sessionStatusResult.payload.catalog.compositeDigest,
1070
+ } : {
1071
+ configDigest: 'config-reset-offline',
1072
+ compositeDigest: 'config-reset-target',
1073
+ },
1074
+ ...(selected ? { source: selected.source } : {}),
1075
+ ...(sessionStatusResult ? {
1076
+ targetFingerprint: currentTargetFingerprint(sessionRecoveryStatus, relevantTargets),
1077
+ } : {}),
1078
+ config: {
1079
+ scope: 'user', platform: intent.platform, context: intent.context ?? 'user',
1080
+ storeDigest: selected?.impact.storeDigest ?? target.fingerprint,
1081
+ impactState: selected?.impact.impactState ?? 'unknown',
1082
+ ...(selected?.impact.noEffectiveChange ? { noEffectiveChange: true } : {}),
1083
+ ...(selected?.impact.affectedCommandPackages.length
1084
+ ? { commandPackages: selected.impact.affectedCommandPackages } : {}),
1085
+ affectedTargets: (selected?.impact.affectedTargets
1086
+ ?? relevantTargets).map(({ platform, scope }) => ({ platform, scope })),
1087
+ ...((selected?.impact.sharedNativeRenderUnits.length ?? 0) > 0
1088
+ ? { sharedNativeRenderUnits: selected.impact.sharedNativeRenderUnits }
1089
+ : {}),
1090
+ },
1091
+ resetTarget: {
1092
+ sourceId: parsed.sourceId,
1093
+ pluginName: parsed.pluginName,
1094
+ scope: 'user', platform: intent.platform, context: intent.context ?? 'user',
1095
+ kind: target.kind,
1096
+ fingerprint: target.fingerprint,
1097
+ },
1098
+ };
1099
+ }
1100
+ if (intent.kind === 'catalogSourcesRecovery') {
724
1101
  signal?.throwIfAborted();
725
- const evidence = {
1102
+ await preparation?.reporter.emit('validate');
1103
+ await preparation?.reporter.emit('evidence');
1104
+ return {
726
1105
  catalog: {
727
- configDigest: portable.configDigest,
728
- compositeDigest: portable.evidenceDigest,
729
- ...(portable.generationSetDigest
730
- ? { generationSetDigest: portable.generationSetDigest }
731
- : {}),
1106
+ configDigest: 'invalid-catalog-sources-config',
1107
+ compositeDigest: 'bootstrap-recovery',
732
1108
  },
733
- portable,
734
1109
  };
735
- if (catalogOperation)
736
- catalogOperationByEvidence.set(evidence, catalogOperation);
737
- return evidence;
738
1110
  }
739
- if (preparation && (intent.kind === 'configSave' || intent.kind === 'configReset')) {
740
- if (!sessionStatusResult || !catalogOperation) {
741
- throw operationReviewStale('当前 TUI session 没有可复用的设置证据。');
742
- }
743
- await preparation.reporter.emit('config');
744
- const configSnapshot = await readCatalogSourcesConfigSnapshot(context.env);
1111
+ if (intent.kind === 'catalogGeneration') {
745
1112
  signal?.throwIfAborted();
746
- if (configSnapshot.digest !== sessionStatusResult.payload.catalog.configDigest) {
1113
+ await preparation?.reporter.emit('validate');
1114
+ const packageInfo = await readCliPackageInfo();
1115
+ const config = await readCatalogSourcesConfigSnapshot(context.env);
1116
+ const configuredSource = config.config.sources.find((source) => source.id === intent.sourceId);
1117
+ let proposedSource;
1118
+ let proposedConfigDigest;
1119
+ let explicitSourceChange = false;
1120
+ let sourceIdentityChangeImpact;
1121
+ if (intent.sourceMutation) {
1122
+ const preview = await preflightCatalogSourceMutation({
1123
+ request: intent.sourceMutation.action === 'add'
1124
+ ? intent.sourceMutation
1125
+ : { action: 'update', sourceId: intent.sourceId, update: intent.sourceMutation.update },
1126
+ cwd: context.cwd,
1127
+ env: context.env,
1128
+ });
1129
+ proposedSource = preview.proposedSource;
1130
+ proposedConfigDigest = preview.proposedConfigDigest;
1131
+ if (preview.configDigest !== config.digest) {
1132
+ throw operationReviewStale('准备 Catalog 候选期间来源配置发生变化。');
1133
+ }
1134
+ const sourceFingerprintChanged = Boolean(proposedSource && (!configuredSource
1135
+ || calculateCatalogSourceConfigFingerprint(proposedSource)
1136
+ !== calculateCatalogSourceConfigFingerprint(configuredSource)));
1137
+ explicitSourceChange = preview.proposedConfigDigest !== preview.configDigest
1138
+ && (preview.identityChanged || sourceFingerprintChanged);
1139
+ if (preview.identityChanged)
1140
+ sourceIdentityChangeImpact = {
1141
+ impactSchemaVersion: 3,
1142
+ sourceId: preview.sourceId,
1143
+ primaryChange: preview.references.primaryChange,
1144
+ inventoryComplete: preview.references.inventoryComplete,
1145
+ references: preview.references.references,
1146
+ affectedReferences: preview.references.references,
1147
+ changes: {
1148
+ added: [], removed: [], changed: [], newlyIncompatible: [],
1149
+ dependencyChanged: [], platformSupportChanged: [],
1150
+ },
1151
+ errors: preview.references.errors,
1152
+ };
1153
+ if (!explicitSourceChange) {
1154
+ throw new TuiOperationBlockedError('sourceNoChanges', '来源没有变化。');
1155
+ }
1156
+ }
1157
+ let previousActive;
1158
+ let healthyActive;
1159
+ let previousActiveVersion;
1160
+ let previousStoreReady = false;
1161
+ try {
1162
+ previousActive = (await readCatalogGenerationState(context.env))
1163
+ .sources[intent.sourceId]?.active;
1164
+ }
1165
+ catch (error) {
1166
+ if (intent.action !== 'recoverState'
1167
+ || !(error instanceof CatalogGenerationError)
1168
+ || error.code !== 'catalogGenerationStateInvalid')
1169
+ throw error;
1170
+ }
1171
+ const activeStoreKey = previousActive
1172
+ ? createCatalogStoreKey(previousActive.logicalIdentity, previousActive.snapshotDigest)
1173
+ : null;
1174
+ const configuredFingerprint = configuredSource
1175
+ ? calculateCatalogSourceConfigFingerprint(configuredSource)
1176
+ : undefined;
1177
+ const canReuseCandidate = Boolean(reusableCandidate
1178
+ && !intent.sourceMutation
1179
+ && (intent.action === 'activate' || intent.action === 'update')
1180
+ && configuredFingerprint
1181
+ && reusableCandidate.sourceId === intent.sourceId
1182
+ && reusableCandidate.sourceConfigFingerprint === configuredFingerprint
1183
+ && reusableCandidate.probe.candidate.sourceConfigFingerprint === configuredFingerprint
1184
+ && reusableCandidate.activeStoreKey === activeStoreKey
1185
+ && reusableCandidate.probe.sourceId === intent.sourceId
1186
+ && reusableCandidateEvidenceIsComplete(reusableCandidate));
1187
+ const probe = intent.action === 'repair'
1188
+ ? await probeCatalogSourceRepairGeneration({
1189
+ sourceId: intent.sourceId,
1190
+ cliVersion: packageInfo.version,
1191
+ ...(previousActive ? { expectedActive: previousActive } : {}),
1192
+ expectedConfigDigest: config.digest,
1193
+ env: context.env,
1194
+ signal,
1195
+ runtime: options.catalogGenerationRuntime,
1196
+ })
1197
+ : canReuseCandidate
1198
+ ? structuredClone(reusableCandidate.probe)
1199
+ : await probeCatalogSourceGeneration({
1200
+ sourceId: intent.sourceId,
1201
+ ...(proposedSource ? { source: proposedSource } : {}),
1202
+ cliVersion: packageInfo.version,
1203
+ env: context.env,
1204
+ signal,
1205
+ runtime: options.catalogGenerationRuntime,
1206
+ });
1207
+ signal?.throwIfAborted();
1208
+ await preparation?.reporter.emit('evidence');
1209
+ if (intent.action === 'activate' || intent.action === 'update') {
1210
+ try {
1211
+ healthyActive = await resolveActiveCatalogGeneration({ sourceId: intent.sourceId, env: context.env });
1212
+ }
1213
+ catch (error) {
1214
+ if (!(error instanceof CatalogGenerationError)
1215
+ && !(error instanceof CatalogProviderCompatibilityError))
1216
+ throw error;
1217
+ }
1218
+ }
1219
+ const comparisonSource = proposedSource
1220
+ ?? configuredSource;
1221
+ if (previousActive) {
1222
+ const store = await readCatalogStoreEntry({
1223
+ logicalIdentity: previousActive.logicalIdentity,
1224
+ snapshotDigest: previousActive.snapshotDigest,
1225
+ env: context.env,
1226
+ }).catch(() => undefined);
1227
+ previousStoreReady = Boolean(store);
1228
+ previousActiveVersion = healthyActive?.catalogVersion
1229
+ ?? store?.metadata.catalogVersion;
1230
+ }
1231
+ if (intent.action === 'update' && !intent.sourceMutation && previousActive && comparisonSource) {
1232
+ explicitSourceChange = previousActive.sourceConfigFingerprint
1233
+ !== calculateCatalogSourceConfigFingerprint(comparisonSource)
1234
+ || previousActive.sourceIdentity !== await calculateCatalogSourceIdentity(comparisonSource);
1235
+ }
1236
+ const comparisonActive = healthyActive
1237
+ ? {
1238
+ logicalIdentity: healthyActive.logicalIdentity,
1239
+ catalogVersion: healthyActive.catalogVersion,
1240
+ snapshotDigest: healthyActive.snapshotDigest,
1241
+ resolvedCommit: healthyActive.resolvedCommit,
1242
+ }
1243
+ : previousActive && previousActiveVersion
1244
+ ? {
1245
+ logicalIdentity: previousActive.logicalIdentity,
1246
+ catalogVersion: previousActiveVersion,
1247
+ snapshotDigest: previousActive.snapshotDigest,
1248
+ resolvedCommit: previousActive.resolvedCommit,
1249
+ }
1250
+ : undefined;
1251
+ const candidateRelation = comparisonActive && comparisonSource
1252
+ ? compareCatalogGenerationFreshness({
1253
+ sourceType: comparisonSource.type,
1254
+ active: comparisonActive,
1255
+ candidate: probe.candidate,
1256
+ }).state
1257
+ : undefined;
1258
+ const exactStoreTarget = Boolean(previousActive)
1259
+ && createCatalogStoreKey(previousActive.logicalIdentity, previousActive.snapshotDigest)
1260
+ === createCatalogStoreKey(probe.candidate.logicalIdentity, probe.candidate.snapshotDigest);
1261
+ if (intent.action === 'repair' && !exactStoreTarget) {
1262
+ throw new CatalogGenerationError({
1263
+ code: 'catalogReplaceDamagedRequired', sourceId: intent.sourceId,
1264
+ message: `Catalog source "${intent.sourceId}" cannot reproduce the damaged Active entry. Use the current candidate replacement Review.`,
1265
+ });
1266
+ }
1267
+ const exactRepair = (intent.action === 'repair' || intent.action === 'update')
1268
+ && exactStoreTarget && !previousStoreReady;
1269
+ if (previousActive && !previousStoreReady && !exactStoreTarget
1270
+ && !intent.sourceMutation && intent.action !== 'replaceDamaged') {
1271
+ throw new CatalogGenerationError({
1272
+ code: 'catalogReplaceDamagedRequired',
1273
+ sourceId: intent.sourceId,
1274
+ message: `Catalog source "${intent.sourceId}" has a damaged Active entry whose version cannot be compared safely. The current Active remains unchanged. Edit the source explicitly, or remove and add it again.`,
1275
+ });
1276
+ }
1277
+ if (intent.action !== 'replaceDamaged' && !explicitSourceChange && candidateRelation === 'incompatible') {
1278
+ throw new CatalogGenerationError({
1279
+ code: 'catalogLogicalIdentityChanged', sourceId: intent.sourceId,
1280
+ message: `Catalog source "${intent.sourceId}" changed logical identity. Edit or remove and re-add the source.`,
1281
+ });
1282
+ }
1283
+ if (intent.action !== 'replaceDamaged' && !explicitSourceChange && candidateRelation === 'versionConflict') {
1284
+ throw new TuiOperationBlockedError('catalogVersionConflict', '候选 Catalog 与当前 Active 版本相同,但内容摘要不同。普通更新已阻止。');
1285
+ }
1286
+ if (intent.action !== 'replaceDamaged' && !explicitSourceChange && candidateRelation === 'rollbackDetected') {
1287
+ throw new TuiOperationBlockedError('catalogRollbackDetected', '候选 Catalog 版本低于当前 Active。普通更新已阻止。');
1288
+ }
1289
+ const impact = exactRepair ? undefined
1290
+ : sourceIdentityChangeImpact ?? await inspectCatalogSourceImpact({
1291
+ sourceId: intent.sourceId,
1292
+ cwd: context.cwd,
1293
+ env: context.env,
1294
+ sourcePrimary: comparisonSource?.primary === true,
1295
+ mode: 'generation',
1296
+ candidateManifest: probe.manifest,
1297
+ });
1298
+ const primaryPreview = intent.setPrimaryAfterActivation
1299
+ ? await preflightCatalogSourceMutation({
1300
+ request: { action: 'setPrimary', sourceId: intent.sourceId },
1301
+ cwd: context.cwd,
1302
+ env: context.env,
1303
+ })
1304
+ : undefined;
1305
+ if (primaryPreview && primaryPreview.configDigest !== config.digest) {
1306
+ throw operationReviewStale('准备主来源切换期间来源配置发生变化。');
1307
+ }
1308
+ const primaryImpact = primaryPreview ? {
1309
+ impactSchemaVersion: 3,
1310
+ sourceId: primaryPreview.sourceId,
1311
+ primaryChange: primaryPreview.references.primaryChange,
1312
+ inventoryComplete: primaryPreview.references.inventoryComplete,
1313
+ references: primaryPreview.references.references,
1314
+ affectedReferences: primaryPreview.references.references,
1315
+ changes: {
1316
+ added: [], removed: [], changed: [], newlyIncompatible: [],
1317
+ dependencyChanged: [], platformSupportChanged: [],
1318
+ },
1319
+ errors: primaryPreview.references.errors,
1320
+ } : undefined;
1321
+ return {
1322
+ catalog: {
1323
+ configDigest: config.digest,
1324
+ compositeDigest: probe.candidate.snapshotDigest,
1325
+ },
1326
+ catalogGeneration: {
1327
+ action: intent.action,
1328
+ ...(previousActive ? { previousActive } : {}),
1329
+ ...(previousActiveVersion ? { previousActiveVersion } : {}),
1330
+ candidate: probe.candidate,
1331
+ ...(candidateRelation ? { candidateRelation } : {}),
1332
+ ...(explicitSourceChange ? { explicitSourceChange: true } : {}),
1333
+ ...(exactRepair ? { exactRepair: true } : {}),
1334
+ activationMode: intent.action === 'replaceDamaged' ? 'replaceDamaged'
1335
+ : explicitSourceChange ? 'explicitSourceChange' : 'normal',
1336
+ ...(impact ? {
1337
+ impact,
1338
+ impactDigest: calculateCatalogSourceImpactDigest(impact),
1339
+ impactMode: sourceIdentityChangeImpact ? 'identityChange' : 'generation',
1340
+ } : {}),
1341
+ ...(primaryPreview && primaryImpact ? {
1342
+ primaryImpact,
1343
+ primaryImpactDigest: primaryPreview.impactDigest,
1344
+ primaryConfigDigest: primaryPreview.configDigest,
1345
+ } : {}),
1346
+ configDigest: config.digest,
1347
+ ...(proposedConfigDigest ? { proposedConfigDigest } : {}),
1348
+ ...(proposedSource ? { proposedSource } : {}),
1349
+ ...(intent.sourceMutation ? { sourceMutation: intent.sourceMutation } : {}),
1350
+ ...(intent.setPrimaryAfterActivation ? { setPrimaryAfterActivation: true } : {}),
1351
+ },
1352
+ };
1353
+ }
1354
+ if (intent.kind === 'sourceMutation') {
1355
+ signal?.throwIfAborted();
1356
+ if (intent.action === 'add' && !intent.source
1357
+ || intent.action === 'update' && !intent.update) {
1358
+ throw new TuiOperationBlockedError('invalidSourceMutation', '来源操作缺少候选输入。');
1359
+ }
1360
+ const request = intent.action === 'add'
1361
+ ? { action: 'add', source: intent.source }
1362
+ : intent.action === 'update'
1363
+ ? { action: 'update', sourceId: intent.sourceId, update: intent.update }
1364
+ : { action: intent.action, sourceId: intent.sourceId };
1365
+ await preparation?.reporter.emit('validate');
1366
+ const preview = await preflightCatalogSourceMutation({
1367
+ request,
1368
+ cwd: context.cwd,
1369
+ env: context.env,
1370
+ });
1371
+ signal?.throwIfAborted();
1372
+ await preparation?.reporter.emit('evidence');
1373
+ signal?.throwIfAborted();
1374
+ const evidence = {
1375
+ catalog: { configDigest: preview.configDigest, compositeDigest: preview.proposedConfigDigest },
1376
+ sourceWrite: {
1377
+ configDigest: preview.configDigest,
1378
+ proposedConfigDigest: preview.proposedConfigDigest,
1379
+ ...(preview.identityChanged ? { identityChanged: true } : {}),
1380
+ ...(preview.sourceIdentity ? { sourceIdentity: preview.sourceIdentity } : {}),
1381
+ inventoryDigest: digest({ references: preview.references.references, errors: preview.references.errors }),
1382
+ impactDigest: preview.impactDigest,
1383
+ referenceCount: preview.references.references.length,
1384
+ inventoryComplete: preview.references.inventoryComplete,
1385
+ impact: {
1386
+ impactSchemaVersion: 3,
1387
+ sourceId: preview.sourceId,
1388
+ primaryChange: preview.references.primaryChange,
1389
+ inventoryComplete: preview.references.inventoryComplete,
1390
+ references: preview.references.references,
1391
+ affectedReferences: preview.references.references,
1392
+ changes: {
1393
+ added: [], removed: [], changed: [], newlyIncompatible: [],
1394
+ dependencyChanged: [], platformSupportChanged: [],
1395
+ },
1396
+ errors: preview.references.errors,
1397
+ },
1398
+ },
1399
+ };
1400
+ if (preparation?.validateIntent
1401
+ && evidence.sourceWrite?.configDigest === evidence.sourceWrite?.proposedConfigDigest) {
1402
+ throw new TuiOperationBlockedError('sourceNoChanges', '来源没有变化。');
1403
+ }
1404
+ return evidence;
1405
+ }
1406
+ if (intent.kind !== 'configSave'
1407
+ && intent.kind !== 'portableInstall') {
1408
+ throw new TuiOperationBlockedError('operationNotImplemented', '这个写操作尚未接入新 Controller。');
1409
+ }
1410
+ signal?.throwIfAborted();
1411
+ const packageInfo = await readCliPackageInfo();
1412
+ let catalogOperation;
1413
+ let catalogOperationError;
1414
+ if (intent.kind !== 'portableInstall') {
1415
+ try {
1416
+ const sourceIds = [parsePluginId(intent.pluginId).sourceId];
1417
+ catalogOperation = !freshCatalog && sessionCatalogOperationContext
1418
+ ? selectCatalogOperationContext(sessionCatalogOperationContext, sourceIds)
1419
+ : await resolveCatalogOperationContext({
1420
+ sourceIds,
1421
+ env: context.env,
1422
+ ...(!freshCatalog ? { validatedStoreEntries, validatingStoreEntries } : {}),
1423
+ ...(signal ? { signal } : {}),
1424
+ });
1425
+ }
1426
+ catch (error) {
1427
+ catalogOperationError = error;
1428
+ }
1429
+ }
1430
+ if (intent.kind === 'portableInstall') {
1431
+ await preparation?.reporter.emit('portable');
1432
+ if (intent.retry
1433
+ && (intent.retry.receipt.plugin.id !== intent.pluginId
1434
+ || intent.retry.receipt.scope !== intent.scope)) {
1435
+ throw operationReviewStale('Portable 重试结果与当前插件或范围不匹配。');
1436
+ }
1437
+ const portableSourceId = parsePluginId(intent.pluginId).sourceId;
1438
+ const portableCatalogOperation = sessionCatalogOperationContext
1439
+ ? selectCatalogOperationContext(sessionCatalogOperationContext, [portableSourceId])
1440
+ : undefined;
1441
+ const portable = intent.retry
1442
+ ? await preparePortableRetry({
1443
+ receipt: intent.retry.receipt,
1444
+ cwd: context.cwd,
1445
+ env: context.env,
1446
+ cliVersion: packageInfo.version,
1447
+ signal,
1448
+ ...(portableCatalogOperation
1449
+ ? { catalogOperationContext: portableCatalogOperation }
1450
+ : {}),
1451
+ })
1452
+ : await preparePortableInstall({
1453
+ selector: intent.pluginId,
1454
+ scope: intent.scope,
1455
+ ...(intent.selectedSkills.length > 0 ? { requestedSkills: intent.selectedSkills } : {}),
1456
+ ...(intent.requestedAgents ? { requestedAgents: intent.requestedAgents } : {}),
1457
+ cwd: context.cwd,
1458
+ env: context.env,
1459
+ cliVersion: packageInfo.version,
1460
+ signal,
1461
+ ...(portableCatalogOperation
1462
+ ? { catalogOperationContext: portableCatalogOperation }
1463
+ : {}),
1464
+ });
1465
+ signal?.throwIfAborted();
1466
+ await preparation?.reporter.emit('evidence');
1467
+ signal?.throwIfAborted();
1468
+ const evidence = {
1469
+ catalog: {
1470
+ configDigest: portable.configDigest,
1471
+ compositeDigest: portable.evidenceDigest,
1472
+ ...(portable.generationSetDigest
1473
+ ? { generationSetDigest: portable.generationSetDigest }
1474
+ : {}),
1475
+ },
1476
+ portable,
1477
+ };
1478
+ if (catalogOperation)
1479
+ catalogOperationByEvidence.set(evidence, catalogOperation);
1480
+ return evidence;
1481
+ }
1482
+ if (intent.kind === 'configSave' && intent.retryApply) {
1483
+ await preparation?.reporter.emit('config');
1484
+ if (!catalogOperation)
1485
+ throw catalogOperationError ?? operationReviewStale('无法取得设置应用所需的 Catalog。');
1486
+ const selectedCatalogOperation = catalogOperation;
1487
+ const evidence = await withResolvedCatalogPlugin({
1488
+ selector: intent.pluginId, cliVersion: packageInfo.version, env: context.env,
1489
+ ...(selectedCatalogOperation ? { operationContext: selectedCatalogOperation } : {}),
1490
+ ...(signal ? { signal } : {}),
1491
+ consume: async ({ plugin, source }) => {
1492
+ const referencePlugins = await resolvePluginConfigReferencePlugins({
1493
+ sourceId: plugin.sourceId, sourceIdentity: plugin.sourceIdentity,
1494
+ logicalIdentity: plugin.catalogLogicalIdentity, env: context.env,
1495
+ operationContext: selectedCatalogOperation,
1496
+ });
1497
+ const prepared = await preparePluginConfigApply({
1498
+ plugin, scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1499
+ ...(intent.targets ? { targets: intent.targets } : {}),
1500
+ cwd: context.cwd, env: context.env, cliVersion: packageInfo.version,
1501
+ nativeCliRunner: context.nativeCliRunner,
1502
+ expectedCommandPackageEvidence: reviewedEvidence?.config?.commandPackageEvidence,
1503
+ rebuildRuntime: {
1504
+ ...context,
1505
+ referencePlugins,
1506
+ ...(selectedCatalogOperation ? { catalogOperationContext: selectedCatalogOperation,
1507
+ expectedGenerationSetDigest: selectedCatalogOperation.generationSetDigest } : {}),
1508
+ ...(reviewedScriptTimeoutMs(intent) === undefined ? {} : { scriptTimeoutMs: reviewedScriptTimeoutMs(intent) }),
1509
+ },
1510
+ });
1511
+ try {
1512
+ signal?.throwIfAborted();
1513
+ const targets = prepared.plan.receipt.requestedTargets
1514
+ .filter((target) => !prepared.plan.receipt.targetResults.some((result) => result.pluginId === target.pluginId && result.agent === target.agent && result.scope === target.scope
1515
+ && (result.satisfaction === 'unsupported' || result.satisfaction === 'excluded')))
1516
+ .map((target) => ({
1517
+ pluginName: parsePluginId(target.pluginId).pluginName, platform: target.agent, scope: target.scope,
1518
+ }));
1519
+ return {
1520
+ catalog: {
1521
+ configDigest: selectedCatalogOperation.catalog.configDigest,
1522
+ compositeDigest: selectedCatalogOperation.catalog.compositeDigest,
1523
+ ...(selectedCatalogOperation ? { generationSetDigest: selectedCatalogOperation.generationSetDigest } : {}),
1524
+ },
1525
+ source: sourceEvidenceForPlugin(source, plugin.manifest.name),
1526
+ config: {
1527
+ scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1528
+ schemaIdentity: configSchemaIdentity(plugin, source.manifestDigest, intent.platform),
1529
+ storeDigest: digest(prepared.evidence),
1530
+ impactState: 'known', affectedTargets: targets,
1531
+ commandPackages: prepared.commandPackages,
1532
+ applyEvidence: prepared.evidence, applyChanges: prepared.plan.changes,
1533
+ commandPackageEvidence: prepared.commandPackageEvidence,
1534
+ commandReviewChanges: configPackageReviewChanges(prepared.plan, prepared.commandPackageReviews),
1535
+ hostPermissionEffects: recoveryHostPermissionEffects(prepared.plan),
1536
+ applyWarnings: prepared.plan.warnings,
1537
+ applyBlockers: [...new Map([
1538
+ ...prepared.commandPackageEvidence.flatMap(({ blocker }) => blocker ? [blocker] : []),
1539
+ ...prepared.plan.receipt.blockers, ...prepared.plan.receipt.errors,
1540
+ ...prepared.plan.receipt.targetResults.flatMap((target) => target.blockers),
1541
+ ].map((item) => [`${item.code}\0${item.message}`, item])).values()],
1542
+ preApplyAuthorization: prepared.preApplyAuthorization,
1543
+ sharedNativeRenderUnits: await configRetrySharedNativeRenderUnits(plugin, targets.filter((target) => NATIVE_PLATFORM_TARGETS.includes(target.platform)), context.env, referencePlugins),
1544
+ },
1545
+ };
1546
+ }
1547
+ finally {
1548
+ await disposePluginConfigApply(prepared.plan);
1549
+ }
1550
+ },
1551
+ });
1552
+ if (catalogOperation)
1553
+ catalogOperationByEvidence.set(evidence, catalogOperation);
1554
+ return evidence;
1555
+ }
1556
+ const needsReferencePlugins = intent.kind === 'configSave'
1557
+ && await withResolvedCatalogPlugin({
1558
+ selector: intent.pluginId, cliVersion: packageInfo.version, env: context.env,
1559
+ ...(catalogOperation ? { operationContext: catalogOperation } : {}),
1560
+ ...(signal ? { signal } : {}),
1561
+ consume: ({ plugin }) => configNeedsReferencePlugins(plugin),
1562
+ });
1563
+ const referencePlugins = needsReferencePlugins
1564
+ ? await resolvePluginConfigReferencePlugins({
1565
+ sourceId: parsePluginId(intent.pluginId).sourceId,
1566
+ env: context.env,
1567
+ operationContext: catalogOperation,
1568
+ })
1569
+ : undefined;
1570
+ const configReferencePluginIds = intent.kind === 'configSave' && needsReferencePlugins
1571
+ ? await withResolvedCatalogPlugin({
1572
+ selector: intent.pluginId, cliVersion: packageInfo.version, env: context.env,
1573
+ ...(catalogOperation ? { operationContext: catalogOperation } : {}),
1574
+ ...(signal ? { signal } : {}),
1575
+ consume: async ({ plugin }) => (await resolvePluginConfigReferenceConsumers({
1576
+ plugin, env: context.env, plugins: referencePlugins,
1577
+ })).map((entry) => entry.pluginId ?? `${entry.sourceId}/${entry.manifest.name}`),
1578
+ })
1579
+ : [];
1580
+ if (preparation && intent.kind === 'configSave'
1581
+ && sessionRecoveryStatus?.scope === (intent.context ?? 'user')) {
1582
+ if (!sessionStatusResult || !sessionRecoveryStatus || !catalogOperation) {
1583
+ throw operationReviewStale('当前 TUI session 没有可复用的设置证据。');
1584
+ }
1585
+ await preparation.reporter.emit('config');
1586
+ const configSnapshot = await readCatalogSourcesConfigSnapshot(context.env);
1587
+ signal?.throwIfAborted();
1588
+ if (configSnapshot.digest !== sessionStatusResult.payload.catalog.configDigest) {
747
1589
  throw operationReviewStale('准备设置确认期间来源配置发生变化。');
748
1590
  }
1591
+ const relevantTargets = currentConfigTargets(sessionRecoveryStatus, intent.pluginId, intent.context ?? 'user', configReferencePluginIds, intent.platform);
1592
+ const preparedCatalogOperation = catalogOperation;
749
1593
  const selected = await withResolvedCatalogPlugin({
750
1594
  selector: intent.pluginId,
751
1595
  cliVersion: packageInfo.version,
752
1596
  configSnapshot,
753
1597
  env: context.env,
754
- operationContext: catalogOperation,
1598
+ operationContext: preparedCatalogOperation,
755
1599
  ...(signal ? { signal } : {}),
756
1600
  consume: async ({ plugin, source }) => {
757
1601
  if (!plugin.manifest.config) {
758
1602
  throw new TuiOperationBlockedError('configSchemaUnavailable', '这个插件没有设置 schema。');
759
1603
  }
1604
+ const definition = selectPluginConfigProfile(plugin.manifest.config, intent.platform);
760
1605
  if (intent.kind === 'configSave') {
761
1606
  await coercePluginConfigUpdates({
762
- schema: plugin.manifest.config.schema,
1607
+ schema: definition.fields,
763
1608
  updates: intent.updates ?? {},
764
1609
  cwd: context.cwd,
765
1610
  });
766
- for (const key of intent.removeKeys ?? []) {
767
- if (!plugin.manifest.config.schema[key]) {
768
- throw new TuiOperationBlockedError('unknownConfigKey', '设置字段已变化,请重新检查。');
769
- }
770
- }
771
1611
  }
1612
+ const impact = intent.retryApply ? undefined : await analyzePluginConfigMutationImpact({
1613
+ plugin,
1614
+ referencePlugins,
1615
+ scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1616
+ cwd: context.cwd,
1617
+ env: context.env,
1618
+ visibleTargets: configImpactVisibleTargets(plugin.manifest.name, relevantTargets),
1619
+ mutation: {
1620
+ kind: 'patch',
1621
+ updates: intent.updates,
1622
+ removeKeys: intent.removeKeys,
1623
+ },
1624
+ });
1625
+ const affectedTargets = intent.retryApply
1626
+ ? configImpactVisibleTargets(plugin.manifest.name, relevantTargets)
1627
+ : impact.affectedTargets;
1628
+ const commandPackages = impact?.affectedCommandPackages
1629
+ ?? (await discoverPluginConfigManagedCommandPackages({ plugin, scope: intent.context ?? 'user',
1630
+ cwd: context.cwd, env: context.env ?? process.env, platformTargets: affectedTargets, referencePlugins })).packages;
1631
+ const preApplyAuthorization = configIntentRequestsApply(intent)
1632
+ ? (await resolveConfigPreApplyAuthorization({
1633
+ plugin,
1634
+ scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1635
+ cwd: context.cwd,
1636
+ env: context.env,
1637
+ applyTargets: affectedTargets,
1638
+ nativeCliRunner: context.nativeCliRunner,
1639
+ rebuildRuntime: {
1640
+ referencePlugins,
1641
+ catalogOperationContext: preparedCatalogOperation,
1642
+ expectedGenerationSetDigest: preparedCatalogOperation.generationSetDigest,
1643
+ inventoryCatalogSourceReferences: operationInventory,
1644
+ },
1645
+ })).targets
1646
+ : [];
1647
+ const commandReview = configIntentRequestsApply(intent) ? await reviewConfigMutationApply({
1648
+ plugin, scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1649
+ cwd: context.cwd, env: context.env, cliVersion: packageInfo.version, nativeCliRunner: context.nativeCliRunner,
1650
+ applyTargets: affectedTargets, applyCommandPackages: commandPackages.map(({ packageId }) => packageId),
1651
+ mutation: { kind: 'patch', updates: intent.updates, removeKeys: intent.removeKeys },
1652
+ rebuildRuntime: { ...context, signal, referencePlugins, catalogOperationContext: preparedCatalogOperation,
1653
+ expectedGenerationSetDigest: preparedCatalogOperation.generationSetDigest,
1654
+ scriptTimeoutMs: reviewedScriptTimeoutMs(intent), inventoryCatalogSourceReferences: operationInventory },
1655
+ }, reviewedEvidence?.config, freshCatalog) : {};
772
1656
  return {
773
1657
  pluginName: plugin.manifest.name,
774
1658
  source: sourceEvidenceForPlugin(source, plugin.manifest.name),
1659
+ schemaIdentity: configSchemaIdentity(plugin, source.manifestDigest, intent.platform),
1660
+ impact,
1661
+ commandPackages,
1662
+ commandReview,
1663
+ preApplyAuthorization,
1664
+ retryStoreDigest: intent.retryApply ? await configRetryStoreDigest({ plugin, scope: intent.context ?? 'user', platform: intent.platform,
1665
+ targets: affectedTargets, commandPackages, preApplyAuthorization, cwd: context.cwd, env: context.env, plugins: referencePlugins }) : undefined,
1666
+ sharedNativeRenderUnits: intent.retryApply
1667
+ ? await configRetrySharedNativeRenderUnits(plugin, affectedTargets, context.env, referencePlugins)
1668
+ : impact.sharedNativeRenderUnits,
775
1669
  };
776
1670
  },
777
1671
  });
778
- const store = await readPluginConfigStore({
779
- sourceId: selected.source.sourceId,
780
- sourceIdentity: selected.source.sourceIdentity,
781
- pluginName: selected.pluginName,
782
- scope: intent.scope,
783
- projectLayer: intent.projectLayer,
784
- cwd: context.cwd,
785
- env: context.env,
786
- });
787
1672
  signal?.throwIfAborted();
788
- const relevantTargets = configAffectedStatusTargets(sessionStatusResult.payload.targets, intent.pluginId, intent.scope);
789
- const relevantRevisions = (sessionStatusResult.targetRevisions ?? []).filter((revision) => relevantTargets.some((target) => target.platform === revision.platform
790
- && target.scope === revision.scope
791
- && target.pluginId === revision.pluginId));
792
1673
  await preparation.reporter.emit('evidence');
793
1674
  const evidence = {
794
1675
  catalog: {
795
1676
  configDigest: sessionStatusResult.payload.catalog.configDigest,
796
- compositeDigest: sessionStatusResult.payload.catalog.compositeDigest,
797
- generationSetDigest: catalogOperation.generationSetDigest,
1677
+ compositeDigest: preparedCatalogOperation.catalog.compositeDigest,
1678
+ ...(catalogOperation ? { generationSetDigest: catalogOperation.generationSetDigest } : {}),
798
1679
  },
799
- source: selected.source,
800
- targetFingerprint: statusTargetFingerprint(relevantTargets, relevantRevisions),
1680
+ ...(selected.source ? { source: selected.source } : {}),
1681
+ targetFingerprint: currentTargetFingerprint(sessionRecoveryStatus, relevantTargets),
801
1682
  config: {
802
- scope: intent.scope,
803
- projectLayer: intent.projectLayer,
804
- schemaIdentity: selected.source.manifestDigest,
805
- storeDigest: digest({ exists: store.exists, values: store.values }),
806
- affectedTargets: relevantTargets.map(({ platform, scope }) => ({ platform, scope })),
1683
+ scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1684
+ schemaIdentity: selected.schemaIdentity,
1685
+ storeDigest: selected.impact?.storeDigest
1686
+ ?? selected.retryStoreDigest,
1687
+ impactState: selected.impact?.impactState ?? 'known',
1688
+ ...(selected.impact?.noEffectiveChange ? { noEffectiveChange: true } : {}),
1689
+ ...(selected.commandPackages.length ? { commandPackages: selected.commandPackages } : {}),
1690
+ ...selected.commandReview,
1691
+ affectedTargets: (selected.impact?.affectedTargets
1692
+ ?? relevantTargets).map(({ pluginName, platform, scope }) => ({ pluginName, platform, scope })),
1693
+ ...(selected.preApplyAuthorization.length > 0
1694
+ ? { preApplyAuthorization: selected.preApplyAuthorization }
1695
+ : {}),
1696
+ ...(selected.sharedNativeRenderUnits.length > 0
1697
+ ? { sharedNativeRenderUnits: selected.sharedNativeRenderUnits }
1698
+ : {}),
807
1699
  },
808
1700
  };
809
- catalogOperationByEvidence.set(evidence, catalogOperation);
1701
+ await assertConfigEditEvidence(intent, evidence);
1702
+ if (catalogOperation)
1703
+ catalogOperationByEvidence.set(evidence, catalogOperation);
810
1704
  return evidence;
811
1705
  }
812
1706
  await preparation?.reporter.emit('status');
813
- const statusCatalogOperation = offlineCleanupReason
814
- ? undefined
815
- : catalogOperation ?? (!freshCatalog ? sessionCatalogOperationContext : undefined);
816
- const status = await statusCommandV6({
817
- plugins: [...new Set([intent.pluginId,
818
- ...(intent.kind === 'pluginWrite' && intent.originIssue?.consumerPluginId
819
- ? [intent.originIssue.consumerPluginId] : [])])],
820
- ...('platform' in intent ? { platform: intent.platform } : {}),
821
- ...(intent.kind !== 'pluginWrite' && intent.scope === 'project'
822
- ? { scope: intent.scope }
823
- : {}),
824
- cwd: context.cwd,
825
- env: context.env,
826
- cliVersion: packageInfo.version,
1707
+ const statusCatalogOperation = catalogOperation
1708
+ ?? (!freshCatalog ? sessionCatalogOperationContext : undefined);
1709
+ const status = await readRecoveryStatus({
1710
+ context: intent.context ?? 'user', cwd: context.cwd, env: context.env,
1711
+ nativeCliRunner: context.nativeCliRunner, cliVersion: packageInfo.version,
1712
+ ...(signal ? { signal } : {}),
827
1713
  ...(statusCatalogOperation ? { catalogOperationContext: statusCatalogOperation } : {}),
828
- inventoryCatalogSourceReferences: operationInventory,
829
1714
  });
830
1715
  signal?.throwIfAborted();
831
1716
  const configSnapshot = await readCatalogSourcesConfigSnapshot(context.env);
832
1717
  signal?.throwIfAborted();
833
- if (configSnapshot.digest !== status.payload.catalog.configDigest) {
1718
+ if (statusCatalogOperation && configSnapshot.digest !== statusCatalogOperation.catalog.configDigest) {
834
1719
  throw operationReviewStale('准备确认信息期间来源配置发生变化。');
835
1720
  }
836
1721
  if (catalogOperationError)
837
1722
  throw catalogOperationError;
838
- if (intent.kind === 'pluginWrite') {
839
- await assertTypedIssueOrigin(intent, status.payload.targets);
840
- if (preparation?.validateIntent) {
841
- assertIntentIsLegal(intent, status.payload.targets, status.targetRevisions);
842
- }
843
- }
844
- if (!offlineCleanupReason && !catalogOperation) {
1723
+ if (!catalogOperation) {
845
1724
  catalogOperation = await resolveCatalogOperationContext({
846
1725
  sourceIds: [parsePluginId(intent.pluginId).sourceId],
847
1726
  configSnapshot,
@@ -850,232 +1729,319 @@ export function createTuiControllerDependencies(context, progressFeed, options =
850
1729
  ...(signal ? { signal } : {}),
851
1730
  });
852
1731
  }
853
- let dependencyPlan;
854
- let codexReconcilePlans;
855
1732
  await preparation?.reporter.emit('catalog');
856
- const offlineCleanupTarget = offlineCleanupReason && intent.kind === 'pluginWrite'
857
- ? status.payload.targets.find((target) => target.pluginId === intent.pluginId
858
- && target.platform === intent.platform
859
- && target.scope === intent.scope
860
- && target.errors.some((error) => error.code === offlineCleanupReason))
861
- : undefined;
862
- const catalogSource = offlineCleanupTarget
863
- ? status.payload.catalog.sources.find((source) => source.id === offlineCleanupTarget.sourceId)
864
- : undefined;
865
- let offlineCleanup;
866
- if (offlineCleanupReason && offlineCleanupTarget) {
867
- await preparation?.reporter.emit('inventory');
868
- const inventory = await operationInventory({
869
- cwd: context.cwd,
870
- env: context.env,
871
- });
872
- signal?.throwIfAborted();
873
- offlineCleanup = offlineCleanupEvidenceFromInventory({
874
- reason: offlineCleanupReason,
875
- pluginId: offlineCleanupTarget.pluginId,
876
- pluginName: offlineCleanupTarget.pluginName,
877
- sourceId: offlineCleanupTarget.sourceId,
878
- sourceIdentity: offlineCleanupTarget.sourceIdentity,
879
- platform: offlineCleanupTarget.platform,
880
- scope: offlineCleanupTarget.scope,
881
- inventory,
882
- }) ?? undefined;
883
- if (!offlineCleanup) {
884
- throw operationReviewStale('离线清理现场证据已消失或无法验证。');
885
- }
886
- }
887
- const selected = offlineCleanupTarget
888
- ? {
889
- pluginName: offlineCleanupTarget.pluginName,
890
- source: {
891
- sourceId: offlineCleanupTarget.sourceId,
892
- sourceIdentity: offlineCleanupTarget.sourceIdentity,
893
- ...(catalogSource?.requestedRef ? { requestedRef: catalogSource.requestedRef } : {}),
894
- ...(catalogSource?.resolvedCommit ? { resolvedCommit: catalogSource.resolvedCommit } : {}),
895
- },
896
- }
897
- : await withResolvedCatalogPlugin({
898
- selector: intent.pluginId,
899
- cliVersion: packageInfo.version,
900
- configSnapshot,
901
- env: context.env,
902
- ...(catalogOperation ? { operationContext: catalogOperation } : {}),
903
- ...(signal ? { signal } : {}),
904
- consume: async ({ plugin, source }) => {
905
- if (preparation?.validateIntent && intent.kind === 'configSave') {
906
- await preparation.reporter.emit('config');
907
- if (!plugin.manifest.config) {
908
- throw new TuiOperationBlockedError('configSchemaUnavailable', '这个插件没有设置 schema。');
909
- }
910
- await coercePluginConfigUpdates({
911
- schema: plugin.manifest.config.schema,
912
- updates: intent.updates ?? {},
913
- cwd: context.cwd,
914
- });
915
- for (const key of intent.removeKeys ?? []) {
916
- if (!plugin.manifest.config.schema[key]) {
917
- throw new TuiOperationBlockedError('unknownConfigKey', '设置字段已变化,请重新检查。');
918
- }
919
- }
1733
+ const configVisibleTargets = intent.kind === 'configSave'
1734
+ ? currentConfigTargets(status, intent.pluginId, intent.context ?? 'user', configReferencePluginIds, intent.platform)
1735
+ : [];
1736
+ const selected = await withResolvedCatalogPlugin({
1737
+ selector: intent.pluginId,
1738
+ cliVersion: packageInfo.version,
1739
+ configSnapshot,
1740
+ env: context.env,
1741
+ ...(catalogOperation ? { operationContext: catalogOperation } : {}),
1742
+ ...(signal ? { signal } : {}),
1743
+ consume: async ({ plugin, source }) => {
1744
+ if (preparation?.validateIntent && intent.kind === 'configSave') {
1745
+ await preparation.reporter.emit('config');
1746
+ if (!plugin.manifest.config) {
1747
+ throw new TuiOperationBlockedError('configSchemaUnavailable', '这个插件没有设置 schema。');
920
1748
  }
921
- return {
922
- pluginName: plugin.manifest.name,
923
- source: sourceEvidenceForPlugin(source, plugin.manifest.name),
924
- };
925
- },
926
- });
927
- let codexManager;
928
- const hasDeclaredDependencies = (status.pluginSummaries.find((summary) => summary.pluginId === intent.pluginId)?.dependencyTotalCount ?? 0) > 0;
929
- if (intent.kind === 'pluginWrite') {
930
- const command = {
931
- install: installWriteCommand,
932
- upgrade: upgradeWriteCommand,
933
- reinstall: reinstallWriteCommand,
934
- uninstall: uninstallWriteCommand,
935
- cleanup: cleanupWriteCommand,
936
- sync: installWriteCommand,
937
- }[intent.action];
938
- const preview = await command([intent.pluginId], {
939
- cwd: context.cwd,
940
- platform: intent.platform,
941
- scope: intent.scope,
942
- ...(intent.action === 'install' && intent.dependencyScopeOverrides
943
- ? { dependencyScopeOverrides: intent.dependencyScopeOverrides }
944
- : {}),
945
- ...(intent.action === 'cleanup' ? { force: intent.force === true } : {}),
946
- }, {
947
- ...context,
948
- inventoryCatalogSourceReferences: operationInventory,
949
- expectedCatalogConfigDigest: status.payload.catalog.configDigest,
950
- ...(catalogOperation ? {
951
- catalogOperationContext: catalogOperation,
952
- expectedGenerationSetDigest: catalogOperation.generationSetDigest,
953
- } : {}),
954
- previewDependencyPlanOnly: true,
955
- ...(intent.action === 'sync' ? { reconcileIntentOnly: true } : {}),
956
- ...(preparation ? {
957
- onPreviewStage: (stage) => stage === 'catalog' ? undefined : preparation.reporter.emit(stage),
958
- } : {}),
959
- });
960
- signal?.throwIfAborted();
961
- codexReconcilePlans = intent.dependencyPlacementOnly === 'desired'
962
- ? undefined
963
- : preview?.codexReconcilePlans;
964
- if (hasDeclaredDependencies
965
- && (intent.action === 'install'
966
- || intent.action === 'upgrade'
967
- || intent.action === 'reinstall'
968
- || intent.action === 'sync')) {
969
- dependencyPlan = preview.dependencyPlan;
970
- if (!dependencyPlan) {
971
- throw new TuiOperationBlockedError('dependencyGraphInvalid', '无法建立可信的依赖安装计划。');
972
- }
973
- const blocker = dependencyPlan.targets.find((target) => target.action === 'block');
974
- if (blocker) {
975
- throw new TuiOperationBlockedError(blocker.errorCode ?? 'dependencyNotReady', `${blocker.errorCode ?? 'dependencyNotReady'}: 依赖安装计划被阻止。`);
1749
+ const definition = selectPluginConfigProfile(plugin.manifest.config, intent.platform);
1750
+ await coercePluginConfigUpdates({
1751
+ schema: definition.fields,
1752
+ updates: intent.updates ?? {},
1753
+ cwd: context.cwd,
1754
+ });
976
1755
  }
977
- }
978
- const managerPreview = preview?.codexManagerPreview;
979
- if (managerPreview?.state === 'blocked' && intent.dependencyPlacementOnly !== 'desired') {
980
- const message = managerPreview.code === 'codexSystemCliUnsupported'
981
- ? '系统 Codex CLI 版本不受支持。请升级官方 Codex CLI 后重试。'
982
- : 'AW-managed Codex runtime 当前不可用。请重试、升级 AW,或安装官方 Codex CLI。';
983
- throw new TuiOperationBlockedError(managerPreview.code, `${managerPreview.code}: ${message}`);
984
- }
985
- if (managerPreview && managerPreview.state !== 'blocked'
986
- && intent.dependencyPlacementOnly !== 'desired') {
987
- codexManager = {
988
- state: managerPreview.state,
989
- packageName: MANAGED_CODEX_PACKAGE_NAME,
990
- version: managerPreview.state === 'requires-install'
991
- ? MANAGED_CODEX_VERSION
992
- : managerPreview.manager.version,
1756
+ const impact = intent.kind === 'configSave' && !intent.retryApply
1757
+ ? await analyzePluginConfigMutationImpact({
1758
+ plugin,
1759
+ referencePlugins,
1760
+ scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1761
+ cwd: context.cwd,
1762
+ env: context.env,
1763
+ visibleTargets: configImpactVisibleTargets(plugin.manifest.name, configVisibleTargets),
1764
+ mutation: {
1765
+ kind: 'patch',
1766
+ updates: intent.updates,
1767
+ removeKeys: intent.removeKeys,
1768
+ },
1769
+ })
1770
+ : undefined;
1771
+ const affectedTargets = intent.kind === 'configSave'
1772
+ ? intent.retryApply ? configImpactVisibleTargets(plugin.manifest.name, configVisibleTargets) : impact.affectedTargets
1773
+ : [];
1774
+ const commandPackages = impact?.affectedCommandPackages
1775
+ ?? (intent.kind === 'configSave' ? (await discoverPluginConfigManagedCommandPackages({
1776
+ plugin, scope: intent.context ?? 'user', cwd: context.cwd, env: context.env ?? process.env,
1777
+ platformTargets: configImpactVisibleTargets(plugin.manifest.name, configVisibleTargets),
1778
+ referencePlugins,
1779
+ })).packages : []);
1780
+ const preApplyAuthorization = intent.kind === 'configSave'
1781
+ && configIntentRequestsApply(intent)
1782
+ ? (await resolveConfigPreApplyAuthorization({
1783
+ plugin,
1784
+ scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1785
+ cwd: context.cwd,
1786
+ env: context.env,
1787
+ applyTargets: intent.retryApply
1788
+ ? configImpactVisibleTargets(plugin.manifest.name, configVisibleTargets)
1789
+ : impact.affectedTargets,
1790
+ nativeCliRunner: context.nativeCliRunner,
1791
+ rebuildRuntime: {
1792
+ referencePlugins,
1793
+ ...(catalogOperation ? { catalogOperationContext: catalogOperation } : {}),
1794
+ ...(catalogOperation?.generationSetDigest
1795
+ ? { expectedGenerationSetDigest: catalogOperation.generationSetDigest }
1796
+ : {}),
1797
+ inventoryCatalogSourceReferences: operationInventory,
1798
+ },
1799
+ })).targets
1800
+ : [];
1801
+ const commandReview = intent.kind === 'configSave' && configIntentRequestsApply(intent) ? await reviewConfigMutationApply({
1802
+ plugin, scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1803
+ cwd: context.cwd, env: context.env, cliVersion: packageInfo.version, nativeCliRunner: context.nativeCliRunner,
1804
+ applyTargets: affectedTargets, applyCommandPackages: commandPackages.map(({ packageId }) => packageId),
1805
+ mutation: { kind: 'patch', updates: intent.updates, removeKeys: intent.removeKeys },
1806
+ rebuildRuntime: { ...context, signal, referencePlugins, catalogOperationContext: catalogOperation,
1807
+ expectedGenerationSetDigest: catalogOperation?.generationSetDigest,
1808
+ scriptTimeoutMs: reviewedScriptTimeoutMs(intent), inventoryCatalogSourceReferences: operationInventory },
1809
+ }, reviewedEvidence?.config, freshCatalog) : {};
1810
+ return {
1811
+ pluginName: plugin.manifest.name,
1812
+ source: sourceEvidenceForPlugin(source, plugin.manifest.name),
1813
+ schemaIdentity: configSchemaIdentity(plugin, source.manifestDigest, intent.platform),
1814
+ impact,
1815
+ commandPackages,
1816
+ commandReview,
1817
+ preApplyAuthorization,
1818
+ retryStoreDigest: intent.kind === 'configSave' && intent.retryApply
1819
+ ? await configRetryStoreDigest({ plugin, scope: intent.context ?? 'user', platform: intent.platform, targets: affectedTargets,
1820
+ commandPackages, preApplyAuthorization, cwd: context.cwd, env: context.env, plugins: referencePlugins }) : undefined,
1821
+ sharedNativeRenderUnits: intent.kind === 'configSave'
1822
+ ? intent.retryApply
1823
+ ? await configRetrySharedNativeRenderUnits(plugin, configImpactVisibleTargets(plugin.manifest.name, configVisibleTargets), context.env, referencePlugins)
1824
+ : impact.sharedNativeRenderUnits
1825
+ : [],
993
1826
  };
994
- }
995
- }
1827
+ },
1828
+ });
996
1829
  await preparation?.reporter.emit('evidence');
997
1830
  signal?.throwIfAborted();
998
- let projectIntentDigest;
999
- if (intent.kind === 'pluginWrite' && intent.dependencyPlacementOnly === 'desired') {
1000
- if (intent.scope !== 'project') {
1001
- throw new TuiOperationBlockedError('dependencyPlacementScopeInvalid', '缩小依赖位置只能更新当前项目 desired intent。');
1002
- }
1003
- projectIntentDigest = calculatePluginIntentDigest(await readPluginIntentState({
1004
- scope: 'project',
1005
- cwd: context.cwd,
1006
- env: context.env,
1007
- }));
1008
- signal?.throwIfAborted();
1009
- }
1010
- const evidenceTargets = intent.kind === 'configSave' || intent.kind === 'configReset'
1011
- ? configAffectedStatusTargets(status.payload.targets, intent.pluginId, intent.scope)
1012
- : status.payload.targets;
1013
- const evidenceRevisions = intent.kind === 'configSave' || intent.kind === 'configReset'
1014
- ? (status.targetRevisions ?? []).filter((revision) => evidenceTargets.some((target) => target.platform === revision.platform
1015
- && target.scope === revision.scope
1016
- && target.pluginId === revision.pluginId))
1017
- : (status.targetRevisions ?? []);
1831
+ const evidenceTargets = configVisibleTargets;
1018
1832
  const evidence = {
1019
1833
  catalog: {
1020
- configDigest: status.payload.catalog.configDigest,
1021
- compositeDigest: status.payload.catalog.compositeDigest,
1834
+ configDigest: configSnapshot.digest,
1835
+ compositeDigest: catalogOperation.catalog.compositeDigest,
1022
1836
  ...(catalogOperation
1023
1837
  ? { generationSetDigest: catalogOperation.generationSetDigest }
1024
1838
  : {}),
1025
1839
  },
1026
- source: selected.source,
1027
- ...(offlineCleanup ? { offlineCleanup } : {}),
1028
- ...(dependencyPlan ? { dependencyPlan } : {}),
1029
- ...(projectIntentDigest ? { projectIntentDigest } : {}),
1030
- ...(codexReconcilePlans ? { codexReconcilePlans } : {}),
1031
- ...(codexManager ? { codexManager } : {}),
1032
- targetFingerprint: statusTargetFingerprint(evidenceTargets, evidenceRevisions),
1033
- };
1034
- if (intent.kind === 'configSave' || intent.kind === 'configReset') {
1035
- const store = await readPluginConfigStore({
1036
- sourceId: selected.source.sourceId,
1037
- sourceIdentity: selected.source.sourceIdentity,
1038
- pluginName: selected.pluginName,
1039
- scope: intent.scope,
1040
- projectLayer: intent.projectLayer,
1041
- cwd: context.cwd,
1042
- env: context.env,
1043
- });
1840
+ source: selected.source,
1841
+ targetFingerprint: currentTargetFingerprint(status, evidenceTargets),
1842
+ };
1843
+ if (intent.kind === 'configSave') {
1844
+ const impact = 'impact' in selected ? selected.impact : undefined;
1845
+ const storeDigest = impact?.storeDigest ?? ('retryStoreDigest' in selected ? selected.retryStoreDigest : undefined);
1846
+ if (!storeDigest)
1847
+ throw operationReviewStale('设置操作缺少实际配置输入证据。');
1044
1848
  signal?.throwIfAborted();
1045
1849
  evidence.config = {
1046
- scope: intent.scope,
1047
- projectLayer: intent.projectLayer,
1048
- schemaIdentity: selected.source.manifestDigest,
1049
- storeDigest: digest({ exists: store.exists, values: store.values }),
1050
- affectedTargets: evidenceTargets.map(({ platform, scope }) => ({ platform, scope })),
1850
+ scope: 'user', context: intent.context ?? 'user', platform: intent.platform,
1851
+ schemaIdentity: selected.schemaIdentity,
1852
+ storeDigest,
1853
+ impactState: impact?.impactState ?? 'known',
1854
+ ...(impact?.noEffectiveChange ? { noEffectiveChange: true } : {}),
1855
+ ...('commandPackages' in selected && selected.commandPackages.length
1856
+ ? { commandPackages: selected.commandPackages } : {}),
1857
+ ...('commandReview' in selected ? selected.commandReview : {}),
1858
+ affectedTargets: (impact?.affectedTargets
1859
+ ?? evidenceTargets).map(({ pluginName, platform, scope }) => ({ pluginName, platform, scope })),
1860
+ ...('sharedNativeRenderUnits' in selected
1861
+ && selected.sharedNativeRenderUnits.length > 0
1862
+ ? { sharedNativeRenderUnits: selected.sharedNativeRenderUnits }
1863
+ : {}),
1864
+ ...('preApplyAuthorization' in selected
1865
+ && selected.preApplyAuthorization.length > 0
1866
+ ? { preApplyAuthorization: selected.preApplyAuthorization }
1867
+ : {}),
1051
1868
  };
1052
1869
  }
1870
+ await assertConfigEditEvidence(intent, evidence);
1053
1871
  if (catalogOperation)
1054
1872
  catalogOperationByEvidence.set(evidence, catalogOperation);
1055
1873
  return evidence;
1056
1874
  };
1057
1875
  const dependencies = {
1876
+ readAgentSettings: () => readAgentSettings(context),
1877
+ previewAgentSettings: (preferences, pluginId) => previewAgentSettings(context, preferences, pluginId),
1878
+ saveAgentSettings: (request) => saveAgentSettings(context, request),
1058
1879
  beginCatalogSession(sessionOptions) {
1059
- sessionCatalogOperationContext = undefined;
1060
- if (sessionOptions?.reuseValidatedGenerations !== true) {
1061
- validatedStoreEntries.clear();
1062
- validatingStoreEntries.clear();
1063
- }
1880
+ latestStatusRead += 1;
1881
+ bindNewCatalog = true;
1882
+ validatedStoreEntries = sessionOptions?.reuseValidatedGenerations === true
1883
+ ? new Map(validatedStoreEntries) : new Map();
1884
+ validatingStoreEntries = new Map();
1064
1885
  },
1065
1886
  loadStatus,
1066
- async inspectSourceRemoval(_sourceId, signal) {
1887
+ async loadScopedStatus(scope, signal) {
1888
+ signal.throwIfAborted();
1889
+ const read = latestStatusRead;
1890
+ const pinnedContext = sessionCatalogOperationContext;
1891
+ const catalogView = sessionStatusResult;
1892
+ const storeEntries = { validatedStoreEntries, validatingStoreEntries };
1893
+ const packageInfo = await readCliPackageInfo();
1894
+ const currentCatalog = await resolvePartialCatalogOperationContext({
1895
+ env: context.env, signal, ...storeEntries,
1896
+ });
1897
+ signal.throwIfAborted();
1898
+ if (pinnedContext && currentCatalog.generationSetDigest !== pinnedContext.generationSetDigest) {
1899
+ throw new TuiOperationBlockedError('catalogSessionReloadRequired', 'Catalog 已变化。请按 H 重新加载,再检查清单。');
1900
+ }
1901
+ const catalogOperationContext = pinnedContext ?? currentCatalog;
1902
+ const snapshot = await readJointDemand({ scope, cwd: context.cwd, env: context.env, signal, catalogOperationContext });
1903
+ const status = await readRecoveryStatus({ scope, cwd: context.cwd, env: context.env, cliVersion: packageInfo.version,
1904
+ nativeCliRunner: context.nativeCliRunner, catalogOperationContext, signal }, snapshot);
1905
+ signal.throwIfAborted();
1906
+ const source = catalogView ?? await loadCatalogView({ context, cliVersion: packageInfo.version, signal, catalogOperationContext });
1907
+ const dependencyOverviews = await loadDependencyOverviews({ context, cliVersion: packageInfo.version, status,
1908
+ pluginSummaries: source.pluginSummaries, signal, catalogOperationContext });
1909
+ signal.throwIfAborted();
1910
+ if (read === latestStatusRead)
1911
+ sessionRecoveryStatus = status;
1912
+ return { ...scopedCurrentStatus(status, snapshot, scope), dependencyOverviews };
1913
+ },
1914
+ async prepareScopedTask(request, signal) {
1915
+ signal.throwIfAborted();
1916
+ if (request.kind === 'targets') {
1917
+ return prepareTargetsPlan({ scope: request.scope, cwd: context.cwd, env: context.env }, request.action, request.agents);
1918
+ }
1919
+ if (request.kind === 'intent') {
1920
+ return prepareIntentPlan({ scope: request.scope, cwd: context.cwd, env: context.env }, request.action, request.selector);
1921
+ }
1922
+ if (request.kind === 'retire') {
1923
+ const packageInfo = await readCliPackageInfo();
1924
+ signal.throwIfAborted();
1925
+ const plan = await prepareRetire({ scope: request.scope, cwd: context.cwd, env: context.env,
1926
+ signal,
1927
+ selector: request.selector, cliVersion: packageInfo.version,
1928
+ ...(request.targets ? { targets: request.targets } : {}),
1929
+ deleteConfig: request.deleteConfig === true,
1930
+ }, context);
1931
+ if (signal.aborted) {
1932
+ await plan.context.dispose();
1933
+ signal.throwIfAborted();
1934
+ }
1935
+ return { kind: 'retire', scope: request.scope, plan };
1936
+ }
1937
+ const packageInfo = await readCliPackageInfo();
1938
+ signal.throwIfAborted();
1939
+ const pinned = sessionCatalogOperationContext;
1940
+ const plan = await prepareRecovery(request.command ?? 'sync', request.selectors, {
1941
+ signal,
1942
+ scope: request.scope, cwd: context.cwd, env: context.env,
1943
+ cliVersion: packageInfo.version,
1944
+ all: request.selectors.length === 0,
1945
+ ...(request.allowDependencySelectors ? { allowDependencySelectors: true } : {}),
1946
+ ...(request.targets ? { targets: request.targets } : {}),
1947
+ ...(request.force ? { force: true } : {}),
1948
+ ...(request.refresh ? { refresh: true } : {}),
1949
+ ...(request.command === 'install' && !request.refresh && pinned ? {
1950
+ checkInstallCatalog(current, roots) {
1951
+ for (const sourceId of new Set(roots.map((id) => parsePluginId(id).sourceId))) {
1952
+ if (!sourceId)
1953
+ continue;
1954
+ if (installSourceBinding(pinned, sourceId) !== installSourceBinding(current, sourceId)
1955
+ || (pinned.generationSet.primarySourceId === sourceId) !== (current?.generationSet.primarySourceId === sourceId)) {
1956
+ throw new TuiOperationBlockedError('catalogSessionReloadRequired', recoveryReason('catalogSessionReloadRequired'));
1957
+ }
1958
+ }
1959
+ },
1960
+ } : {}),
1961
+ ...(request.retireUnselectedTargets ? { retireUnselectedTargets: true } : {}),
1962
+ ...(request.scriptTimeoutMs !== undefined ? { scriptTimeoutMs: request.scriptTimeoutMs } : {}),
1963
+ ...(request.dependencyScopeOverrides?.length
1964
+ ? { dependencyScopeOverrides: request.dependencyScopeOverrides } : {}),
1965
+ ...(request.exactTargets ? { exactTargets: request.exactTargets } : {}),
1966
+ ...(request.saveDependencyScopeOverrides ? { saveDependencyScopeOverrides: true } : {}),
1967
+ }, context);
1968
+ if (signal.aborted) {
1969
+ await plan.context.dispose();
1970
+ signal.throwIfAborted();
1971
+ }
1972
+ return { kind: 'recovery', scope: request.scope, plan };
1973
+ },
1974
+ async executeScopedTask(plan) {
1975
+ if (plan.kind === 'targets') {
1976
+ const result = await executeTargetsPlan({ scope: plan.scope, cwd: context.cwd, env: context.env }, plan);
1977
+ return { kind: 'targets', ...result };
1978
+ }
1979
+ if (plan.kind === 'intent') {
1980
+ const receipt = await executeIntentPlan({ scope: plan.scope, cwd: context.cwd, env: context.env }, plan);
1981
+ return { kind: 'recovery', receipt };
1982
+ }
1983
+ if (plan.kind === 'retire') {
1984
+ const receipt = await executeRetire(plan.plan, { yes: true, runtime: context });
1985
+ return { kind: 'recovery', receipt };
1986
+ }
1987
+ if ((plan.plan.sourceRefreshes?.length ?? 0) > 0) {
1988
+ const refreshed = await activateRecoverySourcesAndReprepare(plan.plan, { runtime: context });
1989
+ return { kind: 'recoveryReview', plan: { kind: 'recovery', scope: plan.scope, plan: refreshed } };
1990
+ }
1991
+ const receipt = await executeRecovery(plan.plan, {
1992
+ yes: true,
1993
+ runtime: progressFeed ? { ...context, onInstallProgress: progressFeed.setInstallProgress } : context,
1994
+ }).catch((error) => {
1995
+ if (!(error instanceof RecoveryInterruptedError))
1996
+ throw error;
1997
+ if (context.interruption && error.code === 'processCleanupUnconfirmed')
1998
+ context.interruption.cleanupFailed = true;
1999
+ return error.receipt;
2000
+ });
2001
+ return { kind: 'recovery', receipt };
2002
+ },
2003
+ loadPluginContent,
2004
+ async probeCatalogFreshness(sourceId, freshnessOptions, signal) {
2005
+ signal.throwIfAborted();
2006
+ const storeEntries = { validatedStoreEntries, validatingStoreEntries };
2007
+ const packageInfo = await readCliPackageInfo();
2008
+ return probeCatalogSourceFreshness({
2009
+ sourceId,
2010
+ cliVersion: packageInfo.version,
2011
+ env: context.env,
2012
+ signal,
2013
+ fullValidation: freshnessOptions.fullValidation,
2014
+ runtime: {
2015
+ ...options.catalogGenerationRuntime,
2016
+ ...storeEntries,
2017
+ },
2018
+ });
2019
+ },
2020
+ async inspectSourceRemoval(sourceId, signal) {
1067
2021
  signal.throwIfAborted();
2022
+ const config = await readCatalogSourcesConfigSnapshot(context.env);
2023
+ const source = config.config.sources.find((entry) => entry.id === sourceId);
2024
+ if (!source)
2025
+ throw new TuiOperationBlockedError('catalogGenerationSourceMissing', '来源不存在。');
2026
+ const impact = await inspectCatalogSourceImpact({
2027
+ sourceId,
2028
+ cwd: context.cwd,
2029
+ env: context.env,
2030
+ sourcePrimary: source.primary,
2031
+ mode: 'remove',
2032
+ });
2033
+ const counts = (category) => impact.affectedReferences.filter((reference) => reference.category === category).length;
1068
2034
  return {
1069
- blocked: false,
1070
- inventoryComplete: true,
1071
- installationCount: 0,
1072
- configCount: 0,
1073
- lifecycleCount: 0,
1074
- marketplaceCount: 0,
1075
- dependencies: [],
2035
+ blocked: impact.affectedReferences.length > 0 || !impact.inventoryComplete,
2036
+ inventoryComplete: impact.inventoryComplete,
2037
+ installationCount: counts('installation'),
2038
+ configCount: counts('config'),
2039
+ lifecycleCount: counts('lifecycle'),
2040
+ marketplaceCount: counts('marketplace'),
2041
+ dependencies: impact.affectedReferences,
1076
2042
  };
1077
2043
  },
1078
- async prepareReviewEvidence(intent, signal, onStage) {
2044
+ async prepareReviewEvidence(intent, signal, onStage, reusableCandidate) {
1079
2045
  const reporter = createReviewStageReporter({
1080
2046
  context,
1081
2047
  onStage,
@@ -1085,17 +2051,49 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1085
2051
  return await captureEvidence(intent, signal, {
1086
2052
  reporter,
1087
2053
  validateIntent: true,
1088
- });
2054
+ }, createOperationInventoryReader(), false, reusableCandidate);
1089
2055
  }
1090
2056
  finally {
1091
2057
  await reporter.finish();
1092
2058
  }
1093
2059
  },
1094
2060
  async previewDependencyPlacement(intent, signal) {
1095
- const evidence = await captureEvidence(intent, signal);
1096
- return evidence.dependencyPlan;
2061
+ const targets = intent.platform === 'both' ? ['codex', 'claude']
2062
+ : [intent.platform === 'claude' ? 'claude' : 'codex'];
2063
+ const prepared = await dependencies.prepareScopedTask({
2064
+ kind: 'recovery', command: 'install', scope: intent.scope,
2065
+ selectors: [intent.pluginId], targets: [...targets],
2066
+ dependencyScopeOverrides: intent.dependencyScopeOverrides,
2067
+ }, signal);
2068
+ if (prepared.kind !== 'recovery')
2069
+ throw new Error('dependencyPlacementUnavailable');
2070
+ try {
2071
+ const plans = prepared.plan.nativeGroups.flatMap((group) => group.preview.dependencyPlan ? [group.preview.dependencyPlan] : []);
2072
+ if (plans.length === 0) {
2073
+ throw new Error(prepared.plan.receipt.blockers[0]?.code
2074
+ ?? prepared.plan.receipt.targetResults[0]?.blockers[0]?.code ?? 'dependencyPlacementUnavailable');
2075
+ }
2076
+ return {
2077
+ requestedPluginIds: [...new Set(plans.flatMap((plan) => plan.requestedPluginIds))],
2078
+ resolvedPluginIds: [...new Set(plans.flatMap((plan) => plan.resolvedPluginIds))],
2079
+ dependencyEdges: plans.flatMap((plan) => plan.dependencyEdges),
2080
+ scopeOverrides: plans.flatMap((plan) => plan.scopeOverrides),
2081
+ targets: plans.flatMap((plan) => plan.targets),
2082
+ };
2083
+ }
2084
+ finally {
2085
+ await prepared.plan.context.dispose();
2086
+ }
1097
2087
  },
1098
2088
  async validateIntent(intent, signal) {
2089
+ if (intent.kind === 'catalogSourcesRecovery') {
2090
+ signal.throwIfAborted();
2091
+ return;
2092
+ }
2093
+ if (intent.kind === 'catalogGeneration') {
2094
+ signal.throwIfAborted();
2095
+ return;
2096
+ }
1099
2097
  if (intent.kind === 'sourceMutation') {
1100
2098
  const evidence = await captureEvidence(intent, signal);
1101
2099
  if (evidence.sourceWrite?.configDigest === evidence.sourceWrite?.proposedConfigDigest) {
@@ -1103,6 +2101,13 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1103
2101
  }
1104
2102
  return;
1105
2103
  }
2104
+ if (intent.kind === 'configSaveBatch') {
2105
+ assertConfigSaveBatchIntent(intent);
2106
+ for (const group of intent.groups) {
2107
+ await dependencies.validateIntent(configSaveBatchGroupIntent(intent, group), signal);
2108
+ }
2109
+ return;
2110
+ }
1106
2111
  if (intent.kind === 'configSave') {
1107
2112
  const packageInfo = await readCliPackageInfo();
1108
2113
  await withResolvedCatalogPlugin({
@@ -1117,16 +2122,12 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1117
2122
  if (!plugin.manifest.config) {
1118
2123
  throw new TuiOperationBlockedError('configSchemaUnavailable', '这个插件没有设置 schema。');
1119
2124
  }
2125
+ const definition = selectPluginConfigProfile(plugin.manifest.config, intent.platform);
1120
2126
  await coercePluginConfigUpdates({
1121
- schema: plugin.manifest.config.schema,
2127
+ schema: definition.fields,
1122
2128
  updates: intent.updates ?? {},
1123
2129
  cwd: context.cwd,
1124
2130
  });
1125
- for (const key of intent.removeKeys ?? []) {
1126
- if (!plugin.manifest.config.schema[key]) {
1127
- throw new TuiOperationBlockedError('unknownConfigKey', '设置字段已变化,请重新检查。');
1128
- }
1129
- }
1130
2131
  },
1131
2132
  });
1132
2133
  return;
@@ -1134,55 +2135,24 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1134
2135
  if (intent.kind !== 'pluginWrite')
1135
2136
  return;
1136
2137
  signal.throwIfAborted();
1137
- const packageInfo = await readCliPackageInfo();
1138
- const pluginIds = [...new Set([intent.pluginId,
1139
- ...(intent.originIssue?.consumerPluginId ? [intent.originIssue.consumerPluginId] : [])])];
1140
- const offlineCleanup = intent.action === 'cleanup'
1141
- && intent.originIssue?.actionId === 'cleanup'
1142
- && (intent.originIssue.category === 'sourceMissing'
1143
- || intent.originIssue.category === 'sourceUnavailable');
1144
- const sourceIds = pluginIds.map((pluginId) => parsePluginId(pluginId).sourceId);
1145
- let catalogOperation = offlineCleanup
1146
- ? undefined
1147
- : sessionCatalogOperationContext
1148
- ? selectCatalogOperationContext(sessionCatalogOperationContext, sourceIds)
1149
- : undefined;
1150
- const statusOptions = {
1151
- plugins: pluginIds,
1152
- platform: intent.platform,
2138
+ const parsed = parsePluginId(intent.pluginId);
2139
+ if (!parsed.sourceId || !parsed.pluginName) {
2140
+ throw new TuiOperationBlockedError('invalidPluginId', '操作必须使用 canonical pluginId。');
2141
+ }
2142
+ },
2143
+ captureEvidence,
2144
+ inspectCatalogStore(signal) {
2145
+ signal.throwIfAborted();
2146
+ return inspectCatalogStoreTask({ env: context.env });
2147
+ },
2148
+ recheckPortableInstall(receipt, signal) {
2149
+ return recheckPortableInstall({
2150
+ receipt,
1153
2151
  cwd: context.cwd,
1154
2152
  env: context.env,
1155
- cliVersion: packageInfo.version,
1156
- inventoryCatalogSourceReferences: readInventory,
1157
- };
1158
- let status = await statusCommandV6({
1159
- ...statusOptions,
1160
- ...(catalogOperation ? { catalogOperationContext: catalogOperation } : {}),
2153
+ signal,
1161
2154
  });
1162
- const platforms = intent.platform === 'both'
1163
- ? ['codex', 'claude']
1164
- : [intent.platform];
1165
- const missingSelectedTarget = platforms.some((platform) => !status.payload.targets.some((target) => target.pluginId === intent.pluginId
1166
- && target.platform === platform
1167
- && (platform === 'codex' || target.scope === intent.scope)));
1168
- if (!offlineCleanup && !catalogOperation && missingSelectedTarget) {
1169
- catalogOperation = await resolveCatalogOperationContext({
1170
- sourceIds,
1171
- env: context.env,
1172
- validatedStoreEntries,
1173
- validatingStoreEntries,
1174
- signal,
1175
- });
1176
- status = await statusCommandV6({
1177
- ...statusOptions,
1178
- catalogOperationContext: catalogOperation,
1179
- });
1180
- }
1181
- signal.throwIfAborted();
1182
- await assertTypedIssueOrigin(intent, status.payload.targets);
1183
- assertIntentIsLegal(intent, status.payload.targets, status.targetRevisions);
1184
2155
  },
1185
- captureEvidence,
1186
2156
  logError(_error, code, logContext) {
1187
2157
  return context.debugLogger.log({
1188
2158
  type: 'tui:controller-error',
@@ -1194,7 +2164,12 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1194
2164
  data: { code },
1195
2165
  });
1196
2166
  },
1197
- async getConfigGroups(pluginId, layer, signal) {
2167
+ async getConfigGroups(pluginId, config, signal) {
2168
+ return (await dependencies.getConfigPage(pluginId, config, signal)).groups;
2169
+ },
2170
+ async getConfigPage(pluginId, config, signal) {
2171
+ if (config.context === 'project')
2172
+ await resolveWorkContext({ cwd: context.cwd, context: 'project' });
1198
2173
  const packageInfo = await readCliPackageInfo();
1199
2174
  return withResolvedCatalogPlugin({
1200
2175
  selector: pluginId,
@@ -1204,142 +2179,443 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1204
2179
  ...(sessionContextForPlugin(pluginId)
1205
2180
  ? { operationContext: sessionContextForPlugin(pluginId) }
1206
2181
  : {}),
1207
- consume: async ({ plugin }) => {
2182
+ consume: async ({ plugin, source }) => {
1208
2183
  if (!plugin.manifest.config) {
1209
2184
  throw new TuiOperationBlockedError('configSchemaUnavailable', '这个插件没有设置 schema。');
1210
2185
  }
2186
+ const definition = selectPluginConfigProfile(plugin.manifest.config, config.platform);
2187
+ const stores = await readConfigStoresForTui({
2188
+ sourceId: plugin.sourceId,
2189
+ sourceIdentity: plugin.sourceIdentity,
2190
+ logicalIdentity: plugin.catalogLogicalIdentity,
2191
+ pluginName: plugin.manifest.name,
2192
+ schema: definition.fields,
2193
+ platform: config.platform,
2194
+ signal,
2195
+ });
2196
+ const userStore = stores.user;
2197
+ const preferences = await observePreferences({ scope: 'user', cwd: context.cwd, env: context.env });
2198
+ const configurableLayers = resolveConfigurableLayers(pluginId, plugin.manifest, preferences);
2199
+ const residualLayers = classifyResidualConfigLayers(userStore, configurableLayers).map(({ layer }) => {
2200
+ const fields = selectPluginConfigProfile(plugin.manifest.config, layer === 'common' ? undefined : layer).fields;
2201
+ const stored = layer === 'common' ? userStore.common : userStore.platforms?.[layer];
2202
+ return { profile: layer, keys: Object.keys(stored ?? {}).sort().map((key) => {
2203
+ const field = Object.hasOwn(fields, key) ? fields[key] : undefined;
2204
+ return field && !field.sensitive && !configObjectHasSensitiveChild(field) ? key : '[redacted]';
2205
+ }) };
2206
+ });
1211
2207
  const read = await resolveConfigRead({
1212
2208
  pluginName: plugin.manifest.name,
1213
2209
  plugin,
1214
- scope: layer.scope,
1215
- projectLayer: layer.projectLayer,
2210
+ scope: config.view === 'effective' ? 'effective' : 'user',
2211
+ platform: config.platform,
2212
+ context: config.context ?? 'user',
1216
2213
  cwd: context.cwd,
1217
2214
  env: context.env,
1218
2215
  });
1219
- const effectiveRead = await resolveConfigRead({
2216
+ const effectiveRead = config.view === 'effective' ? read : await resolveConfigRead({
1220
2217
  pluginName: plugin.manifest.name,
1221
2218
  plugin,
1222
2219
  scope: 'effective',
1223
- projectLayer: layer.projectLayer,
2220
+ platform: config.platform,
2221
+ context: config.context ?? 'user',
2222
+ cwd: context.cwd,
2223
+ env: context.env,
2224
+ });
2225
+ const effectiveRaw = await resolveEffectivePluginConfig({
2226
+ sourceId: plugin.sourceId,
2227
+ sourceIdentity: plugin.sourceIdentity,
2228
+ logicalIdentity: plugin.catalogLogicalIdentity,
2229
+ pluginName: plugin.manifest.name,
2230
+ manifest: plugin.manifest,
2231
+ platform: config.platform,
2232
+ context: config.context ?? 'user',
1224
2233
  cwd: context.cwd,
1225
2234
  env: context.env,
1226
2235
  });
1227
- return buildConfigGroups({ schema: plugin.manifest.config, read, effectiveRead });
2236
+ const page = buildConfigPage({
2237
+ pluginId,
2238
+ context: config.context ?? 'user',
2239
+ schema: definition,
2240
+ read,
2241
+ effectiveRead,
2242
+ ...(config.view === 'effective' ? {} : { rawValues: userStore.values }),
2243
+ rawLayerValues: {
2244
+ common: userStore.common ?? {},
2245
+ ...(userStore.platforms ?? {}),
2246
+ },
2247
+ effectiveRawValues: effectiveRaw.values,
2248
+ sharedNativeRefreshKeys: new Set(plugin.manifest.artifacts?.configKeys ?? []),
2249
+ });
2250
+ return { ...page, configurableLayers, residualLayers, editEvidence: {
2251
+ platform: config.platform,
2252
+ context: config.context ?? 'user',
2253
+ sourceIdentity: source.sourceIdentity,
2254
+ schemaIdentity: configSchemaIdentity(plugin, source.manifestDigest, config.platform),
2255
+ storeDigests: {
2256
+ user: digest({ exists: userStore.exists, rawDigest: userStore.rawDigest }),
2257
+ },
2258
+ } };
1228
2259
  },
1229
2260
  });
1230
2261
  },
1231
- async getConfigPage(pluginId, layer, signal) {
2262
+ async getConfigReferenceContext(pluginId, config, draft, signal) {
2263
+ const workContext = await resolveWorkContext({ cwd: context.cwd, context: config.context ?? 'user' });
1232
2264
  const packageInfo = await readCliPackageInfo();
1233
2265
  return withResolvedCatalogPlugin({
1234
- selector: pluginId,
1235
- cliVersion: packageInfo.version,
1236
- env: context.env,
1237
- signal,
1238
- ...(sessionContextForPlugin(pluginId)
1239
- ? { operationContext: sessionContextForPlugin(pluginId) }
1240
- : {}),
2266
+ selector: pluginId, cliVersion: packageInfo.version, env: context.env, signal,
2267
+ ...(sessionContextForPlugin(pluginId) ? { operationContext: sessionContextForPlugin(pluginId) } : {}),
1241
2268
  consume: async ({ plugin }) => {
1242
- if (!plugin.manifest.config) {
2269
+ if (!plugin.manifest.config)
1243
2270
  throw new TuiOperationBlockedError('configSchemaUnavailable', '这个插件没有设置 schema。');
1244
- }
1245
- const read = await resolveConfigRead({
1246
- pluginName: plugin.manifest.name,
1247
- plugin,
1248
- scope: layer.scope,
1249
- projectLayer: layer.projectLayer,
1250
- cwd: context.cwd,
1251
- env: context.env,
2271
+ const definition = selectPluginConfigProfile(plugin.manifest.config, config.platform);
2272
+ const scalars = Object.values(definition.fields).flatMap(configReferenceScalars);
2273
+ if (!scalars.length)
2274
+ return { platform: config.platform, selections: {} };
2275
+ const stores = await readConfigStoresForTui({
2276
+ sourceId: plugin.sourceId, sourceIdentity: plugin.sourceIdentity,
2277
+ logicalIdentity: plugin.catalogLogicalIdentity, pluginName: plugin.manifest.name,
2278
+ schema: definition.fields, platform: config.platform, signal,
1252
2279
  });
1253
- const effectiveRead = layer.scope === 'effective' ? read : await resolveConfigRead({
1254
- pluginName: plugin.manifest.name,
1255
- plugin,
1256
- scope: 'effective',
1257
- projectLayer: layer.projectLayer,
1258
- cwd: context.cwd,
1259
- env: context.env,
2280
+ const edited = stores.user;
2281
+ const values = { ...edited.values };
2282
+ for (const key of draft.removes)
2283
+ delete values[key];
2284
+ Object.assign(values, draft.updates);
2285
+ const candidateStores = { user: replacePluginConfigStoreLayer(edited, values, config.platform) };
2286
+ const references = await resolvePluginConfigReferenceContext({
2287
+ sourceId: plugin.sourceId, sourceIdentity: plugin.sourceIdentity,
2288
+ logicalIdentity: plugin.catalogLogicalIdentity, manifest: plugin.manifest,
2289
+ scope: 'user', context: config.context ?? 'user', platform: config.platform, cwd: context.cwd, env: context.env,
1260
2290
  });
1261
- const layerReads = layer.scope === 'effective' ? undefined : {
1262
- user: await resolveConfigRead({
1263
- pluginName: plugin.manifest.name,
1264
- plugin,
1265
- scope: 'user',
1266
- projectLayer: 'shared',
1267
- cwd: context.cwd,
1268
- env: context.env,
1269
- }),
1270
- project: await resolveConfigRead({
1271
- pluginName: plugin.manifest.name,
1272
- plugin,
1273
- scope: 'project',
1274
- projectLayer: 'shared',
1275
- cwd: context.cwd,
1276
- env: context.env,
1277
- }),
1278
- local: await resolveConfigRead({
1279
- pluginName: plugin.manifest.name,
1280
- plugin,
1281
- scope: 'project',
1282
- projectLayer: 'local',
1283
- cwd: context.cwd,
1284
- env: context.env,
1285
- }),
1286
- };
1287
- return buildConfigPage({
1288
- pluginId,
1289
- schema: plugin.manifest.config,
1290
- read,
1291
- effectiveRead,
1292
- ...(layerReads ? { layerReads } : {}),
2291
+ const effective = await resolveEffectivePluginConfigFromStores({
2292
+ manifest: plugin.manifest, context: config.context ?? 'user', platform: config.platform,
2293
+ projectRoot: workContext.projectRoot ?? '', stores: candidateStores,
2294
+ referenceContext: references.context,
1293
2295
  });
2296
+ // Keep invalid raw sources for Core validation; effective.values omits them.
2297
+ // Preserve active branches in other references that reserve source values.
2298
+ // Only source choices and entry digests leave this boundary.
2299
+ const candidate = {};
2300
+ for (const key of Object.keys(definition.fields)) {
2301
+ const source = effective.sources[key];
2302
+ if (source === 'default')
2303
+ candidate[key] = definition.fields[key].default;
2304
+ else if (source === 'common')
2305
+ candidate[key] = candidateStores.user.common?.[key];
2306
+ else if (source === 'platform' && config.platform)
2307
+ candidate[key] = candidateStores.user.platforms?.[config.platform]?.[key];
2308
+ }
2309
+ const result = { platform: config.platform, selections: {} };
2310
+ for (const scalar of scalars) {
2311
+ const ref = scalar.valueRef;
2312
+ const selection = getPluginConfigReferenceChoices(definition, scalar, candidate, references.context);
2313
+ const entries = ref.plugin ? references.context.plugins[ref.plugin]?.values?.[ref.field] : candidate[ref.field];
2314
+ result.selections[configReferenceKey(scalar, config.platform)] = {
2315
+ ...selection, source: (ref.plugin
2316
+ ? references.evidence.find((entry) => entry.plugin === ref.plugin)?.sources[ref.field]
2317
+ : effective.sources[ref.field]) ?? 'missing',
2318
+ entries: Array.isArray(entries) ? Object.fromEntries(entries.flatMap((entry) => entry && typeof entry === 'object' && Object.hasOwn(entry, ref.key)
2319
+ ? [[JSON.stringify(entry[ref.key]), digest(entry)]] : [])) : {},
2320
+ };
2321
+ }
2322
+ return result;
1294
2323
  },
1295
2324
  });
1296
2325
  },
1297
- async getConfigResetAvailability(pluginId, layer, signal) {
2326
+ async getConfigSuggestions(lookup, run, signal) {
2327
+ const { pluginId, options: config, ...request } = lookup;
2328
+ const packageInfo = await readCliPackageInfo();
2329
+ const operationContext = sessionContextForPlugin(pluginId);
2330
+ return withResolvedCatalogPlugin({
2331
+ selector: pluginId, cliVersion: packageInfo.version, env: context.env, signal,
2332
+ ...(operationContext ? { operationContext } : {}),
2333
+ consume: async ({ plugin }) => run(await preparePluginConfigSuggestions({
2334
+ plugin, platform: config.platform, context: config.context ?? 'user',
2335
+ cwd: context.cwd, env: context.env, signal, ...request,
2336
+ })),
2337
+ });
2338
+ },
2339
+ async getConfigResetAvailability(pluginId, config, signal) {
2340
+ if (config.context === 'project')
2341
+ await resolveWorkContext({ cwd: context.cwd, context: 'project' });
2342
+ const parsed = parsePluginId(pluginId);
2343
+ if (!parsed.sourceId || !parsed.pluginName) {
2344
+ throw new TuiOperationBlockedError('invalidPluginId', '设置目标必须使用 canonical pluginId。');
2345
+ }
2346
+ let sourceIdentity;
2347
+ let logicalIdentity;
2348
+ try {
2349
+ const packageInfo = await readCliPackageInfo();
2350
+ const source = await withResolvedCatalogPlugin({
2351
+ selector: pluginId,
2352
+ cliVersion: packageInfo.version,
2353
+ env: context.env,
2354
+ signal,
2355
+ ...(sessionContextForPlugin(pluginId)
2356
+ ? { operationContext: sessionContextForPlugin(pluginId) }
2357
+ : {}),
2358
+ consume: async ({ source }) => ({
2359
+ sourceIdentity: source.sourceIdentity,
2360
+ logicalIdentity: source.logicalIdentity,
2361
+ }),
2362
+ });
2363
+ sourceIdentity = source.sourceIdentity;
2364
+ logicalIdentity = source.logicalIdentity;
2365
+ }
2366
+ catch {
2367
+ sourceIdentity = undefined;
2368
+ logicalIdentity = undefined;
2369
+ }
1298
2370
  signal.throwIfAborted();
1299
- const { sourceId, pluginName } = parsePluginId(pluginId);
1300
- if (!sourceId)
1301
- return { exists: false, sourceIdentityPresent: false };
1302
- const identity = await readNamespacedPluginConfigStoreIdentity({
1303
- sourceId,
1304
- pluginName,
1305
- scope: layer.scope,
1306
- projectLayer: layer.projectLayer,
2371
+ const target = await inspectPluginConfigResetTarget({
2372
+ sourceId: parsed.sourceId,
2373
+ pluginName: parsed.pluginName,
2374
+ scope: 'user',
1307
2375
  cwd: context.cwd,
1308
2376
  env: context.env,
1309
2377
  });
1310
2378
  signal.throwIfAborted();
1311
- if (!identity)
1312
- return { exists: false, sourceIdentityPresent: false };
1313
- const configured = await readCatalogSourcesConfigSnapshot(context.env);
1314
- const source = configured.config.sources.find((entry) => entry.id === sourceId);
1315
- const configuredIdentity = source
1316
- ? await calculateCatalogSourceIdentity(source)
1317
- : undefined;
1318
- if (identity.sourceIdentity !== configuredIdentity) {
2379
+ if (target.kind === 'regularFile') {
2380
+ const store = await readPluginConfigStore({
2381
+ sourceId: parsed.sourceId,
2382
+ ...(sourceIdentity ? { sourceIdentity } : {}),
2383
+ ...(logicalIdentity ? { logicalIdentity } : {}),
2384
+ pluginName: parsed.pluginName,
2385
+ scope: 'user',
2386
+ platform: config.platform,
2387
+ cwd: context.cwd,
2388
+ env: context.env,
2389
+ });
2390
+ signal.throwIfAborted();
1319
2391
  return {
1320
- exists: true,
1321
- sourceIdentityPresent: false,
1322
- sourceIdentity: identity.sourceIdentity,
2392
+ exists: store.exists,
2393
+ state: store.state,
2394
+ ...(store.invalidCode ? { invalidCode: store.invalidCode } : {}),
2395
+ sourceIdentityPresent: sourceIdentity !== undefined,
2396
+ ...(sourceIdentity ? { sourceIdentity } : {}),
2397
+ targetKind: target.kind,
2398
+ resettable: target.resettable,
2399
+ storeDigest: target.fingerprint,
1323
2400
  };
1324
2401
  }
1325
2402
  return {
1326
- exists: true,
1327
- sourceIdentityPresent: true,
1328
- sourceIdentity: identity.sourceIdentity,
1329
- storeDigest: digest({
1330
- exists: identity.store.exists,
1331
- sourceIdentity: identity.sourceIdentity,
1332
- values: identity.store.values,
1333
- }),
2403
+ exists: target.exists,
2404
+ state: target.kind === 'absent' ? 'missing' : 'invalid',
2405
+ sourceIdentityPresent: sourceIdentity !== undefined,
2406
+ ...(sourceIdentity ? { sourceIdentity } : {}),
2407
+ targetKind: target.kind,
2408
+ resettable: target.resettable,
2409
+ storeDigest: target.fingerprint,
1334
2410
  };
1335
2411
  },
1336
- async executeIntent(intent, expectedEvidence) {
2412
+ async executeIntent(intent, expectedEvidence, signal) {
2413
+ if (intent.kind === 'pluginWrite' || intent.kind === 'pluginWriteBatch'
2414
+ || intent.kind === 'pluginWriteTask') {
2415
+ throw new TuiOperationBlockedError('useScopedRecovery', '请使用统一范围恢复任务。');
2416
+ }
2417
+ if (intent.kind === 'catalogStorePrune') {
2418
+ signal?.throwIfAborted();
2419
+ if (!expectedEvidence.catalogStore) {
2420
+ throw new TuiOperationBlockedError('catalogStoreReviewStale', '确认信息缺少精确清理目标。');
2421
+ }
2422
+ return executeCatalogStoreTask({
2423
+ env: context.env,
2424
+ authorizedItems: expectedEvidence.catalogStore.authorizedItems,
2425
+ });
2426
+ }
2427
+ if (intent.kind === 'catalogSourcesRecovery') {
2428
+ signal?.throwIfAborted();
2429
+ return recoverInvalidCatalogSourcesConfig({ env: context.env });
2430
+ }
2431
+ if (intent.kind === 'catalogGeneration') {
2432
+ signal?.throwIfAborted();
2433
+ const expected = expectedEvidence.catalogGeneration;
2434
+ if (!expected)
2435
+ throw new TuiOperationBlockedError('catalogGenerationReviewStale', '确认信息缺少 Catalog candidate。');
2436
+ const packageInfo = await readCliPackageInfo();
2437
+ let configSaved = false;
2438
+ if (intent.sourceMutation) {
2439
+ const common = {
2440
+ cwd: context.cwd,
2441
+ env: context.env,
2442
+ cliVersion: packageInfo.version,
2443
+ expectedConfigDigest: expected.configDigest,
2444
+ };
2445
+ if (intent.sourceMutation.action === 'add') {
2446
+ await addCatalogSourceCommand({
2447
+ ...common,
2448
+ source: intent.sourceMutation.source,
2449
+ expectedProposedConfigDigest: expected.proposedConfigDigest,
2450
+ expectedImpactDigest: expected.impactDigest,
2451
+ requireImpactConfirmation: true,
2452
+ confirmImpact: true,
2453
+ });
2454
+ }
2455
+ else {
2456
+ await updateCatalogSourceCommand({
2457
+ ...common,
2458
+ sourceId: intent.sourceId,
2459
+ update: intent.sourceMutation.update,
2460
+ expectedProposedConfigDigest: expected.proposedConfigDigest,
2461
+ expectedImpactDigest: expected.impactDigest,
2462
+ requireIdentityChangeConfirmation: true,
2463
+ confirmIdentityChange: true,
2464
+ });
2465
+ }
2466
+ configSaved = true;
2467
+ await tuiControllerRuntimeTestHooks?.afterCatalogSourceConfigCommit?.();
2468
+ }
2469
+ try {
2470
+ let generation;
2471
+ if (intent.action === 'recoverState') {
2472
+ generation = await recoverCatalogGenerationStateAndActivate({
2473
+ sourceId: intent.sourceId,
2474
+ cliVersion: packageInfo.version,
2475
+ cwd: context.cwd,
2476
+ impactConfirmed: true,
2477
+ expectedImpactDigest: expected.impactDigest,
2478
+ expectedCandidate: expected.candidate,
2479
+ env: context.env,
2480
+ signal,
2481
+ runtime: options.catalogGenerationRuntime,
2482
+ });
2483
+ }
2484
+ else if (intent.action === 'repair') {
2485
+ generation = await repairCatalogSourceGeneration({
2486
+ sourceId: intent.sourceId,
2487
+ cliVersion: packageInfo.version,
2488
+ cwd: context.cwd,
2489
+ expectedCandidate: expected.candidate,
2490
+ expectedActive: expected.previousActive ?? null,
2491
+ expectedConfigDigest: expected.proposedConfigDigest ?? expected.configDigest,
2492
+ env: context.env,
2493
+ signal,
2494
+ runtime: {
2495
+ ...options.catalogGenerationRuntime,
2496
+ afterCandidateResolved: tuiControllerRuntimeTestHooks
2497
+ ?.afterCatalogGenerationCandidateResolved,
2498
+ },
2499
+ });
2500
+ }
2501
+ else if (intent.action === 'update' && expected.exactRepair) {
2502
+ generation = await repairCatalogSourceGeneration({
2503
+ sourceId: intent.sourceId,
2504
+ cliVersion: packageInfo.version,
2505
+ cwd: context.cwd,
2506
+ expectedActive: expected.previousActive ?? null,
2507
+ expectedConfigDigest: expected.proposedConfigDigest ?? expected.configDigest,
2508
+ env: context.env,
2509
+ signal,
2510
+ runtime: options.catalogGenerationRuntime,
2511
+ });
2512
+ }
2513
+ else if (intent.action === 'replaceDamaged') {
2514
+ generation = await replaceDamagedCatalogSourceGeneration({
2515
+ sourceId: intent.sourceId,
2516
+ cliVersion: packageInfo.version,
2517
+ cwd: context.cwd,
2518
+ expectedCandidate: expected.candidate,
2519
+ expectedActive: expected.previousActive,
2520
+ expectedConfigDigest: expected.proposedConfigDigest ?? expected.configDigest,
2521
+ impactConfirmed: true,
2522
+ expectedImpactDigest: expected.impactDigest,
2523
+ env: context.env,
2524
+ signal,
2525
+ runtime: {
2526
+ ...options.catalogGenerationRuntime,
2527
+ afterCandidateResolved: tuiControllerRuntimeTestHooks
2528
+ ?.afterCatalogGenerationCandidateResolved,
2529
+ },
2530
+ });
2531
+ }
2532
+ else {
2533
+ generation = await activateCatalogSourceGeneration({
2534
+ sourceId: intent.sourceId,
2535
+ cliVersion: packageInfo.version,
2536
+ cwd: context.cwd,
2537
+ activationMode: expected.activationMode,
2538
+ impactConfirmed: true,
2539
+ expectedImpactDigest: expected.impactDigest,
2540
+ impactMode: expected.impactMode,
2541
+ expectedCandidate: expected.candidate,
2542
+ expectedActive: expected.previousActive ?? null,
2543
+ expectedConfigDigest: expected.proposedConfigDigest ?? expected.configDigest,
2544
+ env: context.env,
2545
+ signal,
2546
+ runtime: {
2547
+ ...options.catalogGenerationRuntime,
2548
+ afterCandidateResolved: tuiControllerRuntimeTestHooks
2549
+ ?.afterCatalogGenerationCandidateResolved,
2550
+ },
2551
+ });
2552
+ }
2553
+ let primaryChanged = false;
2554
+ if (intent.setPrimaryAfterActivation) {
2555
+ try {
2556
+ await setPrimaryCatalogSourceCommand({
2557
+ sourceId: intent.sourceId,
2558
+ cwd: context.cwd,
2559
+ env: context.env,
2560
+ expectedConfigDigest: expected.primaryConfigDigest,
2561
+ expectedImpactDigest: expected.primaryImpactDigest,
2562
+ requireImpactConfirmation: true,
2563
+ confirmImpact: true,
2564
+ });
2565
+ primaryChanged = true;
2566
+ }
2567
+ catch (error) {
2568
+ return {
2569
+ status: 'partial',
2570
+ partialReason: 'primary',
2571
+ configSaved,
2572
+ generation,
2573
+ activeAvailable: true,
2574
+ errorCode: typeof error === 'object' && error !== null
2575
+ && 'code' in error && typeof error.code === 'string'
2576
+ ? error.code
2577
+ : error instanceof Error ? error.name : 'catalogSourcePrimaryFailed',
2578
+ };
2579
+ }
2580
+ }
2581
+ return { status: 'succeeded', generation, configSaved, primaryChanged };
2582
+ }
2583
+ catch (error) {
2584
+ if (!configSaved)
2585
+ throw error;
2586
+ return {
2587
+ status: 'partial',
2588
+ partialReason: 'activation',
2589
+ configSaved: true,
2590
+ errorCode: error instanceof CatalogGenerationError ? error.code : 'catalogGenerationRefreshFailed',
2591
+ };
2592
+ }
2593
+ }
1337
2594
  if (intent.kind === 'portableInstall') {
1338
2595
  if (!expectedEvidence.portable) {
1339
2596
  throw operationReviewStale('确认信息缺少 Portable evidence。');
1340
2597
  }
1341
2598
  const packageInfo = await readCliPackageInfo();
1342
2599
  try {
2600
+ if (intent.retry) {
2601
+ if (!('retryPairs' in expectedEvidence.portable)) {
2602
+ throw operationReviewStale('确认信息缺少 Portable 重试目标。');
2603
+ }
2604
+ return await executePortableRetry({
2605
+ receipt: intent.retry.receipt,
2606
+ review: expectedEvidence.portable,
2607
+ expectedEvidenceDigest: expectedEvidence.portable.evidenceDigest,
2608
+ cwd: context.cwd,
2609
+ env: context.env,
2610
+ cliVersion: packageInfo.version,
2611
+ signal,
2612
+ onProgress(stage) {
2613
+ const phase = stage === 'prepare' ? '重新检查失败目标'
2614
+ : stage === 'add' ? '重试缺失的 Skills' : '验证重试结果';
2615
+ progressFeed?.setCurrent({ target: 'Skills CLI', phase }, `Portable Skills:${phase}`);
2616
+ },
2617
+ });
2618
+ }
1343
2619
  return await installPortableSkills({
1344
2620
  selector: intent.pluginId,
1345
2621
  scope: intent.scope,
@@ -1383,19 +2659,44 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1383
2659
  cwd: context.cwd,
1384
2660
  env: context.env,
1385
2661
  expectedConfigDigest: expectedEvidence.sourceWrite?.configDigest,
2662
+ expectedProposedConfigDigest: expectedEvidence.sourceWrite?.proposedConfigDigest,
2663
+ expectedImpactDigest: expectedEvidence.sourceWrite?.impactDigest,
1386
2664
  runtime,
1387
2665
  };
1388
2666
  if (intent.action === 'add' && intent.source) {
1389
- return addCatalogSourceCommand({ ...common, source: intent.source, cliVersion: packageInfo.version });
2667
+ return addCatalogSourceCommand({
2668
+ ...common,
2669
+ source: intent.source,
2670
+ cliVersion: packageInfo.version,
2671
+ requireImpactConfirmation: true,
2672
+ confirmImpact: true,
2673
+ });
1390
2674
  }
1391
2675
  if (intent.action === 'update' && intent.update) {
1392
- return updateCatalogSourceCommand({ ...common, sourceId: intent.sourceId, update: intent.update, cliVersion: packageInfo.version });
2676
+ return updateCatalogSourceCommand({
2677
+ ...common,
2678
+ sourceId: intent.sourceId,
2679
+ update: intent.update,
2680
+ cliVersion: packageInfo.version,
2681
+ requireIdentityChangeConfirmation: true,
2682
+ confirmIdentityChange: true,
2683
+ });
1393
2684
  }
1394
2685
  if (intent.action === 'setPrimary') {
1395
- return setPrimaryCatalogSourceCommand({ ...common, sourceId: intent.sourceId });
2686
+ return setPrimaryCatalogSourceCommand({
2687
+ ...common,
2688
+ sourceId: intent.sourceId,
2689
+ requireImpactConfirmation: true,
2690
+ confirmImpact: true,
2691
+ });
1396
2692
  }
1397
2693
  if (intent.action === 'remove') {
1398
- return removeCatalogSourceCommand({ ...common, sourceId: intent.sourceId });
2694
+ return removeCatalogSourceCommand({
2695
+ ...common,
2696
+ sourceId: intent.sourceId,
2697
+ requireImpactConfirmation: true,
2698
+ confirmImpact: true,
2699
+ });
1399
2700
  }
1400
2701
  throw new TuiOperationBlockedError('invalidSourceMutation', '来源操作缺少候选输入。');
1401
2702
  }
@@ -1404,8 +2705,8 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1404
2705
  action: async (awHomeMutationToken) => {
1405
2706
  await tuiControllerRuntimeTestHooks?.beforeMutationEvidenceCapture?.();
1406
2707
  const operationInventory = createOperationInventoryReader();
1407
- const currentEvidence = await captureEvidence(intent, undefined, undefined, operationInventory, true);
1408
- if (operationEvidenceFingerprint(currentEvidence) !== operationEvidenceFingerprint(expectedEvidence)) {
2708
+ const currentEvidence = await captureEvidence(intent, undefined, undefined, operationInventory, true, undefined, expectedEvidence);
2709
+ if (!operationEvidenceMatches(expectedEvidence, currentEvidence)) {
1409
2710
  throw new TuiOperationBlockedError('operationReviewStale', '确认后状态发生变化。');
1410
2711
  }
1411
2712
  const catalogOperation = catalogOperationByEvidence.get(currentEvidence);
@@ -1414,81 +2715,204 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1414
2715
  throw operationReviewStale('确认后 Active Catalog generation 发生变化。');
1415
2716
  }
1416
2717
  await tuiControllerRuntimeTestHooks?.afterMutationEvidenceCapture?.();
1417
- if (intent.kind === 'pluginWrite') {
1418
- if (intent.dependencyPlacementOnly === 'desired') {
1419
- const plan = currentEvidence.dependencyPlan;
1420
- if (!plan || !expectedEvidence.projectIntentDigest) {
1421
- throw operationReviewStale('确认信息缺少依赖位置或 project intent 证据。');
2718
+ if (intent.kind === 'configSaveBatch') {
2719
+ assertConfigSaveBatchIntent(intent);
2720
+ const reviewedBatch = expectedEvidence.configBatch;
2721
+ if (!reviewedBatch || !currentEvidence.configBatch || !currentEvidence.source) {
2722
+ throw operationReviewStale('确认信息缺少设置批次证据。');
2723
+ }
2724
+ const approvedApplyTargets = new Set(reviewedBatch.groups.flatMap((group) => group.config.affectedTargets.map((target) => `${target.pluginName ?? parsePluginId(intent.pluginId).pluginName}\0${target.platform}\0${target.scope}`)));
2725
+ const approvedCommandPackages = new Set(reviewedBatch.groups.flatMap((group) => (group.config.commandPackages ?? []).map((target) => target.packageId)));
2726
+ const approvedPreApplyTargets = reviewedBatch.groups.flatMap((group) => group.config.preApplyAuthorization ?? []);
2727
+ const results = [];
2728
+ const packageInfo = await readCliPackageInfo();
2729
+ let interrupted = false;
2730
+ for (const group of intent.groups) {
2731
+ if (interrupted) {
2732
+ results.push({
2733
+ scope: 'user', platform: group.platform, status: 'notStarted',
2734
+ configSaved: false, applyRequested: intent.apply, applyStatus: intent.apply ? 'notStarted' : 'notRequested',
2735
+ });
2736
+ continue;
1422
2737
  }
1423
- const location = { scope: 'project', cwd: context.cwd, env: context.env };
1424
- const currentIntent = await readPluginIntentState(location);
1425
- if (calculatePluginIntentDigest(currentIntent) !== expectedEvidence.projectIntentDigest) {
1426
- throw operationReviewStale('确认后 project desired intent 发生变化。');
2738
+ const groupIntent = configSaveBatchGroupIntent(intent, group);
2739
+ const reviewedGroup = reviewedBatch.groups.find((item) => item.platform === group.platform);
2740
+ if (!reviewedGroup) {
2741
+ throw operationReviewStale('确认信息缺少设置层基线。');
2742
+ }
2743
+ let configSaved = false;
2744
+ const operationRebuildResults = [];
2745
+ try {
2746
+ const freshEvidence = await captureEvidence(groupIntent, undefined, undefined, operationInventory, true);
2747
+ const freshSource = freshEvidence.source;
2748
+ const freshConfig = freshEvidence.config;
2749
+ if (!freshSource || !freshConfig) {
2750
+ throw operationReviewStale('设置目标缺少最新证据。');
2751
+ }
2752
+ assertSourceEvidenceMatches(currentEvidence.source, freshSource);
2753
+ const freshLayerStoreDigest = await configLayerStoreDigest({
2754
+ source: freshSource,
2755
+ pluginName: parsePluginId(intent.pluginId).pluginName,
2756
+ scope: 'user', platform: group.platform, profileOnly: true,
2757
+ cwd: context.cwd,
2758
+ env: context.env,
2759
+ });
2760
+ if (freshLayerStoreDigest !== reviewedGroup.config.storeDigest) {
2761
+ throw operationReviewStale('保存设置期间此设置层的原始内容发生变化。');
2762
+ }
2763
+ if (freshConfig.affectedTargets.some((target) => !approvedApplyTargets.has(`${target.pluginName ?? parsePluginId(intent.pluginId).pluginName}\0${target.platform}\0${target.scope}`))
2764
+ || freshConfig.commandPackages?.some((target) => !approvedCommandPackages.has(target.packageId))) {
2765
+ throw operationReviewStale('同批前一层变更扩大了未经确认的应用目标。');
2766
+ }
2767
+ const groupCatalogOperation = catalogOperationByEvidence.get(freshEvidence);
2768
+ if (expectedEvidence.catalog.generationSetDigest
2769
+ && groupCatalogOperation?.generationSetDigest
2770
+ !== expectedEvidence.catalog.generationSetDigest) {
2771
+ throw operationReviewStale('保存设置期间 Active Catalog generation 发生变化。');
2772
+ }
2773
+ const result = await withResolvedCatalogPlugin({
2774
+ selector: intent.pluginId,
2775
+ cliVersion: packageInfo.version,
2776
+ env: context.env,
2777
+ ...(groupCatalogOperation ? { operationContext: groupCatalogOperation } : {}),
2778
+ consume: async ({ plugin, source }) => {
2779
+ assertSourceEvidenceMatches(freshSource, sourceEvidenceForPlugin(source, plugin.manifest.name));
2780
+ const referencePlugins = configNeedsReferencePlugins(plugin) ? await resolvePluginConfigReferencePlugins({
2781
+ sourceId: plugin.sourceId,
2782
+ sourceIdentity: plugin.sourceIdentity,
2783
+ logicalIdentity: plugin.catalogLogicalIdentity,
2784
+ env: context.env,
2785
+ operationContext: groupCatalogOperation,
2786
+ }) : undefined;
2787
+ const applyTargets = intent.apply
2788
+ ? freshConfig.affectedTargets.filter((target) => NATIVE_PLATFORM_TARGETS.includes(target.platform)).map((target) => ({
2789
+ pluginName: target.pluginName ?? plugin.manifest.name,
2790
+ platform: target.platform,
2791
+ scope: target.scope,
2792
+ }))
2793
+ : [];
2794
+ return applyPluginConfigWrite({
2795
+ plugin,
2796
+ pluginName: plugin.manifest.name,
2797
+ scope: 'user', platform: group.platform, context: intent.context ?? 'user',
2798
+ apply: intent.apply,
2799
+ cwd: context.cwd,
2800
+ env: context.env,
2801
+ nativeCliRunner: context.nativeCliRunner,
2802
+ rebuildRuntime: {
2803
+ ...context,
2804
+ referencePlugins,
2805
+ awHomeMutationToken,
2806
+ operationDiagnosticSink: (entries) => {
2807
+ operationRebuildResults.push(...structuredClone(entries));
2808
+ },
2809
+ ...(reviewedScriptTimeoutMs(intent) === undefined ? {} : {
2810
+ scriptTimeoutMs: reviewedScriptTimeoutMs(intent),
2811
+ }),
2812
+ ...(groupCatalogOperation ? {
2813
+ catalogOperationContext: groupCatalogOperation,
2814
+ expectedGenerationSetDigest: expectedEvidence.catalog.generationSetDigest,
2815
+ } : {}),
2816
+ },
2817
+ awHomeMutationToken,
2818
+ ...(applyTargets.length ? { applyTargets } : {}),
2819
+ request: { updates: group.updates, removeKeys: group.removeKeys },
2820
+ sharedNativeApplyConfirmed: true,
2821
+ expectedCommandPackageEvidence: reviewedGroup.config.commandPackageEvidence,
2822
+ expectedHostPermissionEffects: reviewedGroup.config.hostPermissionEffects,
2823
+ preApplyConfirmed: true,
2824
+ preApplyAuthorizedTargets: approvedPreApplyTargets,
2825
+ });
2826
+ },
2827
+ });
2828
+ configSaved = result.configWrite === 'succeeded';
2829
+ const applyStatus = !intent.apply
2830
+ ? 'notRequested'
2831
+ : result.apply.state === 'succeeded'
2832
+ ? 'succeeded'
2833
+ : result.apply.state === 'skipped'
2834
+ ? 'notNeeded'
2835
+ : configApplyHasCompletedWork(result.apply) ? 'partial' : 'failed';
2836
+ const applyIncomplete = applyStatus === 'failed' || applyStatus === 'partial';
2837
+ results.push({
2838
+ scope: 'user', platform: group.platform,
2839
+ status: applyIncomplete ? 'failed' : 'succeeded',
2840
+ configSaved,
2841
+ applyRequested: intent.apply,
2842
+ applyStatus,
2843
+ execution: { ...result, operationRebuildResults },
2844
+ ...(applyIncomplete ? {
2845
+ errorCode: result.apply.state === 'unavailable'
2846
+ ? result.apply.error?.code ?? result.apply.reason
2847
+ : result.apply.targetResults.find((target) => target.errorCode)?.errorCode
2848
+ ?? 'runtimeApplyFailed',
2849
+ } : {}),
2850
+ });
2851
+ }
2852
+ catch (error) {
2853
+ const interruption = error instanceof ConfigApplyInterruptedError ? error : undefined;
2854
+ if (interruption) {
2855
+ interrupted = true;
2856
+ if (context.interruption && interruption.code === 'processCleanupUnconfirmed') {
2857
+ context.interruption.cleanupFailed = true;
2858
+ }
2859
+ }
2860
+ configSaved = error?.configWrite === 'succeeded';
2861
+ const errorCode = typeof error === 'object' && error !== null
2862
+ && 'code' in error && typeof error.code === 'string'
2863
+ ? error.code
2864
+ : configSaved ? 'runtimeApplyFailed' : 'configWriteFailed';
2865
+ results.push({
2866
+ scope: 'user', platform: group.platform,
2867
+ status: 'failed',
2868
+ configSaved,
2869
+ applyRequested: intent.apply,
2870
+ applyStatus: !intent.apply ? 'notRequested'
2871
+ : configApplyHasCompletedWork(interruption?.apply) ? 'partial' : 'failed',
2872
+ errorCode,
2873
+ ...(interruption || operationRebuildResults.length > 0
2874
+ ? { execution: {
2875
+ operationRebuildResults,
2876
+ ...(interruption ? { apply: interruption.apply, operationDiagnostic: interruption.operationDiagnostic } : {}),
2877
+ } }
2878
+ : {}),
2879
+ });
1427
2880
  }
1428
- const plannedKeys = new Set(plan.targets.map((target) => `${target.pluginId}\0${target.platform}`));
1429
- const nextIntent = canonicalizePluginIntentState({
1430
- ...currentIntent,
1431
- dependencyScopeOverrides: [
1432
- ...currentIntent.dependencyScopeOverrides.filter((override) => !plannedKeys.has(`${override.pluginId}\0${override.platform}`)),
1433
- ...plan.scopeOverrides,
1434
- ],
1435
- });
1436
- await writePluginIntentState(location, nextIntent);
1437
- return { dependencyPlan: plan, desiredPlacementUpdated: true };
1438
2881
  }
1439
- const options = {
1440
- cwd: context.cwd,
1441
- platform: intent.platform,
1442
- scope: intent.scope,
1443
- ...(intent.action === 'install' && intent.dependencyScopeOverrides
1444
- ? { dependencyScopeOverrides: intent.dependencyScopeOverrides }
1445
- : {}),
1446
- ...(expectedEvidence.codexManager?.state === 'requires-install'
1447
- ? { allowManagedCodexInstall: true }
1448
- : {}),
1449
- ...(intent.action === 'cleanup' ? { force: intent.force === true } : {}),
2882
+ const succeeded = results.filter((result) => result.status === 'succeeded').length;
2883
+ return {
2884
+ status: succeeded === results.length
2885
+ ? 'succeeded'
2886
+ : succeeded > 0 || results.some((result) => result.configSaved)
2887
+ ? 'partial'
2888
+ : 'failed',
2889
+ groups: results,
1450
2890
  };
1451
- const command = {
1452
- install: installWriteCommand,
1453
- upgrade: upgradeWriteCommand,
1454
- reinstall: reinstallWriteCommand,
1455
- uninstall: uninstallWriteCommand,
1456
- cleanup: cleanupWriteCommand,
1457
- sync: installWriteCommand,
1458
- }[intent.action];
1459
- const currentSource = currentEvidence.source;
1460
- const offlineCleanup = currentEvidence.offlineCleanup;
1461
- if (!offlineCleanup && (!expectedEvidence.source || !currentSource)) {
1462
- throw new TuiOperationBlockedError('operationReviewStale', '确认信息缺少来源身份。');
1463
- }
1464
- const result = await command([intent.pluginId], options, {
1465
- ...context,
1466
- awHomeMutationToken,
1467
- inventoryCatalogSourceReferences: operationInventory,
1468
- ...(currentEvidence.dependencyPlan
1469
- ? { expectedOperationDependencyPlan: currentEvidence.dependencyPlan }
1470
- : {}),
1471
- ...(currentEvidence.codexReconcilePlans
1472
- ? { expectedCodexReconcilePlans: currentEvidence.codexReconcilePlans }
1473
- : {}),
1474
- ...(intent.action === 'sync' ? { reconcileIntentOnly: true } : {}),
1475
- expectedCatalogConfigDigest: expectedEvidence.catalog.configDigest,
1476
- ...(catalogOperation ? {
1477
- catalogOperationContext: catalogOperation,
1478
- expectedGenerationSetDigest: expectedEvidence.catalog.generationSetDigest,
1479
- } : {}),
1480
- ...(expectedEvidence.codexManager?.state === 'requires-install'
1481
- ? { managedCodexAuthorizer: async () => true }
1482
- : {}),
1483
- ...(offlineCleanup
1484
- ? { expectedOfflineCleanupEvidence: offlineCleanup }
1485
- : { reviewPreflight: (actual) => assertSourceEvidenceMatches(currentSource, actual) }),
1486
- });
1487
- throwIfWriteReviewStale(result);
1488
- return result;
1489
2891
  }
1490
2892
  if (intent.kind === 'configSave' || intent.kind === 'configReset') {
2893
+ const operationRebuildResults = [];
2894
+ const operationDiagnosticSink = (results) => {
2895
+ operationRebuildResults.push(...structuredClone(results));
2896
+ };
1491
2897
  const currentSource = currentEvidence.source;
2898
+ if (intent.kind === 'configReset') {
2899
+ const parsed = parsePluginId(intent.pluginId);
2900
+ if (!parsed.sourceId || !parsed.pluginName) {
2901
+ throw operationReviewStale('确认信息缺少 qualified 设置目标。');
2902
+ }
2903
+ return resetPluginConfigWithHelper({
2904
+ sourceId: parsed.sourceId,
2905
+ pluginName: parsed.pluginName,
2906
+ scope: 'user', platform: intent.platform, context: intent.context ?? 'user',
2907
+ cwd: context.cwd,
2908
+ env: context.env,
2909
+ nativeCliRunner: context.nativeCliRunner,
2910
+ rebuildRuntime: { ...context, awHomeMutationToken },
2911
+ awHomeMutationToken,
2912
+ apply: false,
2913
+ sharedNativeApplyConfirmed: false,
2914
+ });
2915
+ }
1492
2916
  if (!currentSource) {
1493
2917
  throw operationReviewStale('确认信息缺少来源身份。');
1494
2918
  }
@@ -1500,53 +2924,88 @@ export function createTuiControllerDependencies(context, progressFeed, options =
1500
2924
  ...(catalogOperation ? { operationContext: catalogOperation } : {}),
1501
2925
  consume: async ({ plugin, source }) => {
1502
2926
  assertSourceEvidenceMatches(currentSource, sourceEvidenceForPlugin(source, plugin.manifest.name));
1503
- const applyTargets = currentEvidence.config?.affectedTargets.map((target) => ({
1504
- pluginName: plugin.manifest.name,
1505
- platform: target.platform,
1506
- scope: target.scope,
1507
- })) ?? [];
1508
- const result = intent.kind === 'configSave'
1509
- ? await applyPluginConfigWrite({
2927
+ const referencePlugins = configNeedsReferencePlugins(plugin) ? await resolvePluginConfigReferencePlugins({
2928
+ sourceId: plugin.sourceId,
2929
+ sourceIdentity: plugin.sourceIdentity,
2930
+ logicalIdentity: plugin.catalogLogicalIdentity,
2931
+ env: context.env,
2932
+ operationContext: catalogOperation,
2933
+ }) : undefined;
2934
+ const applyTargets = intent.retryApply || intent.apply
2935
+ ? currentEvidence.config?.affectedTargets.filter((target) => NATIVE_PLATFORM_TARGETS.includes(target.platform)).map((target) => ({
2936
+ pluginName: target.pluginName ?? plugin.manifest.name,
2937
+ platform: target.platform,
2938
+ scope: target.scope,
2939
+ })) ?? []
2940
+ : [];
2941
+ const result = intent.retryApply
2942
+ ? await applyPluginConfig({
1510
2943
  plugin,
1511
- pluginName: plugin.manifest.name,
1512
- scope: intent.scope,
1513
- projectLayer: intent.projectLayer,
2944
+ scope: 'user', platform: intent.platform, context: intent.context ?? 'user',
2945
+ ...(intent.targets ? { targets: intent.targets } : {}),
2946
+ cliVersion: packageInfo.version,
1514
2947
  cwd: context.cwd,
1515
2948
  env: context.env,
1516
2949
  nativeCliRunner: context.nativeCliRunner,
1517
2950
  rebuildRuntime: {
1518
2951
  ...context,
2952
+ referencePlugins,
1519
2953
  awHomeMutationToken,
2954
+ operationDiagnosticSink,
2955
+ ...(reviewedScriptTimeoutMs(intent) === undefined
2956
+ ? {}
2957
+ : { scriptTimeoutMs: reviewedScriptTimeoutMs(intent) }),
1520
2958
  ...(catalogOperation ? {
1521
2959
  catalogOperationContext: catalogOperation,
1522
2960
  expectedGenerationSetDigest: expectedEvidence.catalog.generationSetDigest,
1523
2961
  } : {}),
1524
2962
  },
1525
2963
  awHomeMutationToken,
1526
- applyTargets,
1527
- request: { updates: intent.updates, removeKeys: intent.removeKeys },
2964
+ expectedEvidence: expectedEvidence.config?.applyEvidence,
2965
+ expectedCommandPackageEvidence: expectedEvidence.config?.commandPackageEvidence,
2966
+ expectedHostPermissionEffects: expectedEvidence.config?.hostPermissionEffects,
2967
+ sharedNativeApplyConfirmed: true,
2968
+ preApplyConfirmed: true,
2969
+ preApplyAuthorizedTargets: expectedEvidence.config?.preApplyAuthorization ?? [],
1528
2970
  })
1529
- : await resetPluginConfigWithHelper({
2971
+ : await applyPluginConfigWrite({
1530
2972
  plugin,
1531
2973
  pluginName: plugin.manifest.name,
1532
- scope: intent.scope,
1533
- projectLayer: intent.projectLayer,
2974
+ scope: 'user', platform: intent.platform, context: intent.context ?? 'user',
2975
+ apply: intent.apply,
1534
2976
  cwd: context.cwd,
1535
2977
  env: context.env,
1536
2978
  nativeCliRunner: context.nativeCliRunner,
1537
2979
  rebuildRuntime: {
1538
2980
  ...context,
2981
+ referencePlugins,
1539
2982
  awHomeMutationToken,
2983
+ operationDiagnosticSink,
2984
+ ...(reviewedScriptTimeoutMs(intent) === undefined
2985
+ ? {}
2986
+ : { scriptTimeoutMs: reviewedScriptTimeoutMs(intent) }),
1540
2987
  ...(catalogOperation ? {
1541
2988
  catalogOperationContext: catalogOperation,
1542
2989
  expectedGenerationSetDigest: expectedEvidence.catalog.generationSetDigest,
1543
2990
  } : {}),
1544
2991
  },
1545
2992
  awHomeMutationToken,
1546
- applyTargets,
2993
+ ...(applyTargets.length ? { applyTargets } : {}),
2994
+ request: { updates: intent.updates, removeKeys: intent.removeKeys },
2995
+ sharedNativeApplyConfirmed: true,
2996
+ expectedCommandPackageEvidence: expectedEvidence.config?.commandPackageEvidence,
2997
+ expectedHostPermissionEffects: expectedEvidence.config?.hostPermissionEffects,
2998
+ preApplyConfirmed: true,
2999
+ preApplyAuthorizedTargets: expectedEvidence.config?.preApplyAuthorization ?? [],
1547
3000
  });
1548
- return result;
3001
+ return { ...result, operationRebuildResults };
1549
3002
  },
3003
+ }).catch((error) => {
3004
+ if (error instanceof ConfigApplyInterruptedError && context.interruption
3005
+ && error.code === 'processCleanupUnconfirmed') {
3006
+ context.interruption.cleanupFailed = true;
3007
+ }
3008
+ throw error;
1550
3009
  });
1551
3010
  }
1552
3011
  throw new TuiOperationBlockedError('operationNotImplemented', '这个写操作尚未接入新 Controller。');