@lesliechan721/aw 0.1.0-beta.85 → 0.1.0-beta.87

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 (233) hide show
  1. package/dist/authoring/assets/command-runtime-config.d.mts +9 -0
  2. package/dist/authoring/assets/command-runtime-config.mjs +106 -0
  3. package/dist/authoring/assets/command-runtime-config.mjs.map +1 -0
  4. package/dist/authoring/scripts/validate-plugin.mjs +17 -22
  5. package/dist/authoring/scripts/validate-plugin.mjs.map +1 -1
  6. package/dist/scripts/aw-skill-eval-materializer.d.ts +4 -0
  7. package/dist/scripts/aw-skill-eval-materializer.js +27 -0
  8. package/dist/scripts/aw-skill-eval-materializer.js.map +1 -1
  9. package/dist/scripts/bundle-plugins.js +1 -1
  10. package/dist/scripts/bundle-plugins.js.map +1 -1
  11. package/dist/scripts/test-plugin-scripts.js +13 -2
  12. package/dist/scripts/test-plugin-scripts.js.map +1 -1
  13. package/dist/src/commands/aw-capabilities.d.ts +1 -1
  14. package/dist/src/commands/aw-capabilities.js +2 -2
  15. package/dist/src/commands/catalog-source.d.ts +2 -1
  16. package/dist/src/commands/catalog-source.js +8 -7
  17. package/dist/src/commands/catalog-source.js.map +1 -1
  18. package/dist/src/commands/deployment-confirmation.d.ts +8 -1
  19. package/dist/src/commands/deployment-confirmation.js +79 -11
  20. package/dist/src/commands/deployment-confirmation.js.map +1 -1
  21. package/dist/src/commands/lifecycle-command-package.d.ts +44 -0
  22. package/dist/src/commands/lifecycle-command-package.js +195 -0
  23. package/dist/src/commands/lifecycle-command-package.js.map +1 -0
  24. package/dist/src/commands/managed-commands.d.ts +6 -0
  25. package/dist/src/commands/managed-commands.js +203 -152
  26. package/dist/src/commands/managed-commands.js.map +1 -1
  27. package/dist/src/commands/operation-plan.d.ts +22 -21
  28. package/dist/src/commands/operation-plan.js +2 -5
  29. package/dist/src/commands/operation-plan.js.map +1 -1
  30. package/dist/src/commands/permission-batch.d.ts +5 -0
  31. package/dist/src/commands/permission-batch.js +80 -0
  32. package/dist/src/commands/permission-batch.js.map +1 -0
  33. package/dist/src/commands/plugin-capabilities.js +17 -13
  34. package/dist/src/commands/plugin-capabilities.js.map +1 -1
  35. package/dist/src/commands/public-config-confirmation.d.ts +8 -2
  36. package/dist/src/commands/public-config-confirmation.js +22 -5
  37. package/dist/src/commands/public-config-confirmation.js.map +1 -1
  38. package/dist/src/commands/public-lifecycle-result.d.ts +4 -4
  39. package/dist/src/commands/public-lifecycle-result.js +55 -14
  40. package/dist/src/commands/public-lifecycle-result.js.map +1 -1
  41. package/dist/src/commands/public-lifecycle.js +49 -8
  42. package/dist/src/commands/public-lifecycle.js.map +1 -1
  43. package/dist/src/commands/rebuild-command.d.ts +4 -0
  44. package/dist/src/commands/rebuild-command.js +160 -101
  45. package/dist/src/commands/rebuild-command.js.map +1 -1
  46. package/dist/src/commands/rebuild-integration.d.ts +17 -6
  47. package/dist/src/commands/rebuild-integration.js +76 -183
  48. package/dist/src/commands/rebuild-integration.js.map +1 -1
  49. package/dist/src/commands/rebuild-operations.d.ts +2 -1
  50. package/dist/src/commands/rebuild-operations.js +2 -0
  51. package/dist/src/commands/rebuild-operations.js.map +1 -1
  52. package/dist/src/commands/rebuild-platform-integration.d.ts +5 -3
  53. package/dist/src/commands/rebuild-platform-integration.js +166 -135
  54. package/dist/src/commands/rebuild-platform-integration.js.map +1 -1
  55. package/dist/src/commands/skill-eval.js +10 -1
  56. package/dist/src/commands/skill-eval.js.map +1 -1
  57. package/dist/src/generators/local-plugin.js +14 -15
  58. package/dist/src/generators/local-plugin.js.map +1 -1
  59. package/dist/src/generators/permissions.d.ts +14 -6
  60. package/dist/src/generators/permissions.js +59 -61
  61. package/dist/src/generators/permissions.js.map +1 -1
  62. package/dist/src/index.js +77 -40
  63. package/dist/src/index.js.map +1 -1
  64. package/dist/src/output/command-receipt.js +7 -8
  65. package/dist/src/output/command-receipt.js.map +1 -1
  66. package/dist/src/output/component-delivery.d.ts +7 -0
  67. package/dist/src/output/component-delivery.js +59 -3
  68. package/dist/src/output/component-delivery.js.map +1 -1
  69. package/dist/src/output/public-result.d.ts +15 -0
  70. package/dist/src/output/public-result.js +75 -12
  71. package/dist/src/output/public-result.js.map +1 -1
  72. package/dist/src/output/rebuild-progress.js +7 -4
  73. package/dist/src/output/rebuild-progress.js.map +1 -1
  74. package/dist/src/output/receipt-projection.js +39 -27
  75. package/dist/src/output/receipt-projection.js.map +1 -1
  76. package/dist/src/platforms/antigravity-permissions.d.ts +50 -0
  77. package/dist/src/platforms/antigravity-permissions.js +388 -0
  78. package/dist/src/platforms/antigravity-permissions.js.map +1 -0
  79. package/dist/src/platforms/contracts.d.ts +10 -1
  80. package/dist/src/platforms/discovery.d.ts +2 -0
  81. package/dist/src/platforms/discovery.js.map +1 -1
  82. package/dist/src/platforms/grok-permission-config.d.ts +22 -0
  83. package/dist/src/platforms/grok-permission-config.js +184 -0
  84. package/dist/src/platforms/grok-permission-config.js.map +1 -0
  85. package/dist/src/platforms/grok-permission-document.d.ts +4 -0
  86. package/dist/src/platforms/grok-permission-document.js +145 -0
  87. package/dist/src/platforms/grok-permission-document.js.map +1 -0
  88. package/dist/src/platforms/grok-permissions.d.ts +17 -0
  89. package/dist/src/platforms/grok-permissions.js +311 -0
  90. package/dist/src/platforms/grok-permissions.js.map +1 -0
  91. package/dist/src/platforms/host-permission-policy.d.ts +38 -0
  92. package/dist/src/platforms/host-permission-policy.js +86 -0
  93. package/dist/src/platforms/host-permission-policy.js.map +1 -0
  94. package/dist/src/platforms/inspection-grok.js +47 -5
  95. package/dist/src/platforms/inspection-grok.js.map +1 -1
  96. package/dist/src/platforms/layout.d.ts +8 -0
  97. package/dist/src/platforms/layout.js +53 -8
  98. package/dist/src/platforms/layout.js.map +1 -1
  99. package/dist/src/platforms/lifecycle.js +39 -17
  100. package/dist/src/platforms/lifecycle.js.map +1 -1
  101. package/dist/src/platforms/opencode-permission-config.d.ts +13 -0
  102. package/dist/src/platforms/opencode-permission-config.js +253 -0
  103. package/dist/src/platforms/opencode-permission-config.js.map +1 -0
  104. package/dist/src/platforms/opencode-permissions.d.ts +39 -0
  105. package/dist/src/platforms/opencode-permissions.js +212 -0
  106. package/dist/src/platforms/opencode-permissions.js.map +1 -0
  107. package/dist/src/platforms/opencode-related-permissions.d.ts +40 -0
  108. package/dist/src/platforms/opencode-related-permissions.js +177 -0
  109. package/dist/src/platforms/opencode-related-permissions.js.map +1 -0
  110. package/dist/src/platforms/permission-ownership.d.ts +89 -0
  111. package/dist/src/platforms/permission-ownership.js +543 -0
  112. package/dist/src/platforms/permission-ownership.js.map +1 -0
  113. package/dist/src/platforms/permission-sidecar.d.ts +70 -0
  114. package/dist/src/platforms/permission-sidecar.js +215 -0
  115. package/dist/src/platforms/permission-sidecar.js.map +1 -0
  116. package/dist/src/platforms/projection.js +58 -8
  117. package/dist/src/platforms/projection.js.map +1 -1
  118. package/dist/src/recovery/coordinator.d.ts +2 -0
  119. package/dist/src/recovery/coordinator.js +24 -27
  120. package/dist/src/recovery/coordinator.js.map +1 -1
  121. package/dist/src/recovery/joint-coordinator.js +103 -47
  122. package/dist/src/recovery/joint-coordinator.js.map +1 -1
  123. package/dist/src/recovery/joint-demand.js +1 -1
  124. package/dist/src/recovery/joint-demand.js.map +1 -1
  125. package/dist/src/recovery/joint-install-execution.js +2 -1
  126. package/dist/src/recovery/joint-install-execution.js.map +1 -1
  127. package/dist/src/recovery/retirement.js +11 -17
  128. package/dist/src/recovery/retirement.js.map +1 -1
  129. package/dist/src/recovery/status.js +32 -2
  130. package/dist/src/recovery/status.js.map +1 -1
  131. package/dist/src/review/eval-source-input.d.ts +1 -0
  132. package/dist/src/review/eval-source-input.js +7 -1
  133. package/dist/src/review/eval-source-input.js.map +1 -1
  134. package/dist/src/review/review-selection.js +12 -5
  135. package/dist/src/review/review-selection.js.map +1 -1
  136. package/dist/src/review/skill-materialization.d.ts +1 -1
  137. package/dist/src/review/skill-materialization.js +3 -7
  138. package/dist/src/review/skill-materialization.js.map +1 -1
  139. package/dist/src/tui/console-app-v4.js +37 -30
  140. package/dist/src/tui/console-app-v4.js.map +1 -1
  141. package/dist/src/tui/controller-runtime.js +71 -6
  142. package/dist/src/tui/controller-runtime.js.map +1 -1
  143. package/dist/src/tui/controller.d.ts +4 -1
  144. package/dist/src/tui/controller.js.map +1 -1
  145. package/dist/src/tui/deployment-view.d.ts +1 -1
  146. package/dist/src/tui/deployment-view.js +16 -3
  147. package/dist/src/tui/deployment-view.js.map +1 -1
  148. package/dist/src/tui/diagnostic-projection.js +11 -6
  149. package/dist/src/tui/diagnostic-projection.js.map +1 -1
  150. package/dist/src/tui/entity-cards.js +1 -1
  151. package/dist/src/tui/entity-cards.js.map +1 -1
  152. package/dist/src/tui/operation-review-planner.js +130 -70
  153. package/dist/src/tui/operation-review-planner.js.map +1 -1
  154. package/dist/src/types.d.ts +8 -20
  155. package/dist/src/types.js.map +1 -1
  156. package/dist/src/utils/artifact-plan.d.ts +3 -36
  157. package/dist/src/utils/artifact-plan.js +11 -77
  158. package/dist/src/utils/artifact-plan.js.map +1 -1
  159. package/dist/src/utils/artifact-renderer.d.ts +0 -59
  160. package/dist/src/utils/artifact-renderer.js +2 -49
  161. package/dist/src/utils/artifact-renderer.js.map +1 -1
  162. package/dist/src/utils/artifact-request.d.ts +3 -26
  163. package/dist/src/utils/artifact-request.js +13 -36
  164. package/dist/src/utils/artifact-request.js.map +1 -1
  165. package/dist/src/utils/artifact-sources.d.ts +0 -8
  166. package/dist/src/utils/artifact-sources.js +0 -8
  167. package/dist/src/utils/artifact-sources.js.map +1 -1
  168. package/dist/src/utils/bundle-layout.js +2 -7
  169. package/dist/src/utils/bundle-layout.js.map +1 -1
  170. package/dist/src/utils/catalog-source-references.js +10 -0
  171. package/dist/src/utils/catalog-source-references.js.map +1 -1
  172. package/dist/src/utils/component-command-preparation.d.ts +6 -11
  173. package/dist/src/utils/component-command-preparation.js +109 -228
  174. package/dist/src/utils/component-command-preparation.js.map +1 -1
  175. package/dist/src/utils/managed-command-cli-review.d.ts +43 -0
  176. package/dist/src/utils/managed-command-cli-review.js +389 -0
  177. package/dist/src/utils/managed-command-cli-review.js.map +1 -0
  178. package/dist/src/utils/managed-command-closure.d.ts +14 -3
  179. package/dist/src/utils/managed-command-closure.js +144 -23
  180. package/dist/src/utils/managed-command-closure.js.map +1 -1
  181. package/dist/src/utils/managed-command-errors.d.ts +5 -0
  182. package/dist/src/utils/managed-command-errors.js +10 -0
  183. package/dist/src/utils/managed-command-errors.js.map +1 -0
  184. package/dist/src/utils/managed-command-materialization.d.ts +77 -113
  185. package/dist/src/utils/managed-command-materialization.js +324 -323
  186. package/dist/src/utils/managed-command-materialization.js.map +1 -1
  187. package/dist/src/utils/managed-command-preparation.d.ts +28 -65
  188. package/dist/src/utils/managed-command-preparation.js +33 -140
  189. package/dist/src/utils/managed-command-preparation.js.map +1 -1
  190. package/dist/src/utils/managed-command-review.d.ts +11 -4
  191. package/dist/src/utils/managed-command-review.js +33 -21
  192. package/dist/src/utils/managed-command-review.js.map +1 -1
  193. package/dist/src/utils/managed-command-runtime.d.ts +1 -0
  194. package/dist/src/utils/managed-command-runtime.js +6 -3
  195. package/dist/src/utils/managed-command-runtime.js.map +1 -1
  196. package/dist/src/utils/managed-command-snapshots.d.ts +17 -0
  197. package/dist/src/utils/managed-command-snapshots.js +84 -0
  198. package/dist/src/utils/managed-command-snapshots.js.map +1 -0
  199. package/dist/src/utils/managed-command-store.d.ts +65 -78
  200. package/dist/src/utils/managed-command-store.js +446 -383
  201. package/dist/src/utils/managed-command-store.js.map +1 -1
  202. package/dist/src/utils/multi-source-catalog.d.ts +2 -0
  203. package/dist/src/utils/multi-source-catalog.js +3 -1
  204. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  205. package/dist/src/utils/native-tool-context.d.ts +6 -3
  206. package/dist/src/utils/native-tool-context.js +3 -1
  207. package/dist/src/utils/native-tool-context.js.map +1 -1
  208. package/dist/src/utils/native-tool-review.d.ts +2 -12
  209. package/dist/src/utils/native-tool-review.js +6 -108
  210. package/dist/src/utils/native-tool-review.js.map +1 -1
  211. package/dist/src/utils/ownership.d.ts +7 -0
  212. package/dist/src/utils/ownership.js.map +1 -1
  213. package/dist/src/utils/platform-empty-state.d.ts +2 -1
  214. package/dist/src/utils/platform-empty-state.js +13 -12
  215. package/dist/src/utils/platform-empty-state.js.map +1 -1
  216. package/dist/src/utils/plugin-config-command-apply.d.ts +33 -0
  217. package/dist/src/utils/plugin-config-command-apply.js +134 -0
  218. package/dist/src/utils/plugin-config-command-apply.js.map +1 -0
  219. package/dist/src/utils/plugin-config-impact.d.ts +19 -9
  220. package/dist/src/utils/plugin-config-impact.js +56 -37
  221. package/dist/src/utils/plugin-config-impact.js.map +1 -1
  222. package/dist/src/utils/plugin-config-write.d.ts +19 -19
  223. package/dist/src/utils/plugin-config-write.js +194 -772
  224. package/dist/src/utils/plugin-config-write.js.map +1 -1
  225. package/dist/src/utils/rendered-contract.js +12 -6
  226. package/dist/src/utils/rendered-contract.js.map +1 -1
  227. package/package.json +4 -3
  228. package/dist/src/platforms/managed-command-placement.d.ts +0 -8
  229. package/dist/src/platforms/managed-command-placement.js +0 -79
  230. package/dist/src/platforms/managed-command-placement.js.map +0 -1
  231. package/dist/src/utils/managed-command-evidence.d.ts +0 -7
  232. package/dist/src/utils/managed-command-evidence.js +0 -10
  233. package/dist/src/utils/managed-command-evidence.js.map +0 -1
@@ -1,30 +1,30 @@
1
+ import { catalogGenerationErrorCode } from './catalog-generation-error.js';
2
+ import { CatalogPluginNotFoundError } from './multi-source-catalog.js';
1
3
  import { resolveWorkContext } from '../intent/work-context.js';
2
4
  import { RecoveryInterruptedError, recoveryInterruptionCode } from '../recovery/interruption.js';
3
5
  import { readDemand, demandNativeProjection } from '../recovery/demand.js';
4
6
  import { createScopeContext } from '../intent/scope-context.js';
5
7
  import { nativeDeploymentHasVerifiedComponentWrite } from '../commands/rebuild-platform-integration.js';
6
- import { projectDeploymentNotices } from '../commands/public-lifecycle-result.js';
8
+ import { projectDeploymentNotices, projectRelatedProjectPermissionFailures } from '../commands/public-lifecycle-result.js';
9
+ import { recoveryHostPermissionEffects } from '../commands/deployment-confirmation.js';
7
10
  import { projectComponentDelivery } from '../output/component-delivery.js';
8
- import { selectPluginConfigProfile, NATIVE_PLATFORM_TARGETS, getCommandPackageId } from '@lesliechan721/aw-plugin-core/manifest';
9
- import { readScopedRecoveryStatus } from '../recovery/status.js';
11
+ import { canonicalizeIdentityValue, selectPluginConfigProfile } from '@lesliechan721/aw-plugin-core/manifest';
10
12
  import { syncWriteCommand } from '../commands/write-commands.js';
11
13
  import { skillInvocationDiagnostics } from '../output/skill-invocation-notices.js';
12
14
  import { CONFIG_MUTATION_RECEIPT_SCHEMA_VERSION, } from '../types.js';
13
- import { getDefaultNativeCliRunner, prepareNativeCliExecution } from './native-cli.js';
14
15
  import { assertPluginConfigMutationCandidate, assertSafePluginConfigSegment, coercePluginConfigUpdates, patchPluginConfigStore, PluginConfigSchemaResolutionError, readPluginConfigStore, readNamespacedPluginConfigStoreIdentity, resetPluginConfigStore, resolveConfigRead, resolveEffectivePluginConfig, resolvePluginConfigStorePath, resolvePluginConfigSchemaAccess, summarizeEffectivePluginConfig, } from './plugin-config.js';
15
- import { analyzePluginConfigMutationImpact, discoverPluginConfigManagedCommandPackages, pluginConfigTargetRenderScopes, pluginSharedNativeConfigRenderUnits } from './plugin-config-impact.js';
16
+ import { analyzePluginConfigMutationImpact, discoverPluginConfigManagedCommandPackages, pluginSharedNativeConfigRenderUnits } from './plugin-config-impact.js';
16
17
  import { collectPluginConfigReferenceEvidence, resolvePluginConfigReferencePlugins, resolvePluginConfigReferenceConsumers } from './plugin-config-references.js';
17
- import { orderPluginMetasByDependencies, resolvePluginMetaDependencyClosure } from './plugin-dependencies.js';
18
- import { assertManagedCommandPackageNativeToolsUnchanged, discoverInstalledPluginManagedCommandPackages, syncPluginManagedCommandPackage, } from './managed-command-materialization.js';
19
- import { captureManagedCommandPackageEvidence, listManagedCommandPackages, managedCommandDiagnostic } from './managed-command-store.js';
18
+ import { resolvePluginMetaDependencyClosure } from './plugin-dependencies.js';
19
+ import { publishPreparedManagedCommandPackage } from './managed-command-materialization.js';
20
+ import { ManagedCommandError, managedCommandDiagnostic } from './managed-command-store.js';
21
+ import { configPackageResult, inspectConfigCommandPackageReview, prepareConfigCommandPackages } from './plugin-config-command-apply.js';
20
22
  import { collectSensitivePluginConfigValues, redactPluginScriptOutput, } from './plugin-scripts.js';
21
- import { resolveClaudeProjectKey, resolveCodexProjectKey, resolveCliPackageRoot } from './paths.js';
22
- import { createProjectLocationKey, resolveRequiredCanonicalRepoRoot } from './state-paths.js';
23
+ import { resolveCliPackageRoot } from './paths.js';
23
24
  import { readSafeOperationError } from './safe-operation-diagnostic.js';
24
25
  import { withAwHomeMutationLock, } from './aw-home-mutation-lock.js';
25
26
  import fs from 'fs-extra';
26
27
  import path from 'node:path';
27
- import { parsePluginId } from './multi-source-catalog.js';
28
28
  export function buildConfigMutationReceipt(command, receipt) {
29
29
  return {
30
30
  ...receipt,
@@ -32,32 +32,6 @@ export function buildConfigMutationReceipt(command, receipt) {
32
32
  command,
33
33
  };
34
34
  }
35
- function publicConfigApplyTargetResult(result) {
36
- return {
37
- target: {
38
- pluginName: result.target.pluginName,
39
- ...(result.target.pluginId ? { pluginId: result.target.pluginId } : {}),
40
- platform: result.target.platform,
41
- scope: result.target.scope,
42
- },
43
- action: result.action,
44
- state: result.state,
45
- ...projectComponentDelivery(result),
46
- ...(result.partialDelivery ? { partialDelivery: true } : {}),
47
- ...(result.message ? { message: result.message } : {}),
48
- ...(result.errorCode ? { errorCode: result.errorCode } : {}),
49
- ...(result.relation ? { relation: result.relation } : {}),
50
- ...(result.requiredBy ? { requiredBy: result.requiredBy } : {}),
51
- };
52
- }
53
- function publicConfigApplyResult(apply) {
54
- if (apply.state === 'skipped')
55
- return apply;
56
- return {
57
- ...apply,
58
- targetResults: apply.targetResults.map(publicConfigApplyTargetResult),
59
- };
60
- }
61
35
  export function configWriteStateForError(error) {
62
36
  return error?.configWrite === 'failed'
63
37
  ? 'failed'
@@ -70,7 +44,18 @@ function markConfigWriteFailed(error) {
70
44
  function skippedApply(reason) {
71
45
  return { state: 'skipped', reason, targetResults: [] };
72
46
  }
73
- function unavailableApply(reason, stage, targetResults = [], commandPackages = []) {
47
+ export function configActiveAvailabilityError(error) {
48
+ if (error instanceof CatalogPluginNotFoundError)
49
+ return { code: 'pluginUnavailable',
50
+ message: 'The plugin is absent from the active catalog. Run aw source sync and check the selector.' };
51
+ if (['catalogGenerationUnavailable', 'catalogGenerationSourceMissing', 'catalogGenerationIdentityMismatch',
52
+ 'catalogGenerationStateInvalid', 'catalogGenerationMetadataInvalid'].includes(catalogGenerationErrorCode(error))) {
53
+ return { code: 'sourceActiveUnavailable',
54
+ message: 'The active catalog is unavailable. Run aw source sync, then retry configuration apply.' };
55
+ }
56
+ return undefined;
57
+ }
58
+ function unavailableApply(reason, stage) {
74
59
  const messages = {
75
60
  invalidConfig: 'The effective config is invalid for every visible target.',
76
61
  schemaUnavailable: 'The config schema is unavailable after the config commit.',
@@ -78,21 +63,7 @@ function unavailableApply(reason, stage, targetResults = [], commandPackages = [
78
63
  effectiveConfigUnavailable: 'The effective config cannot be read after the config commit.',
79
64
  targetDiscoveryFailed: 'Visible config apply targets cannot be discovered after the config commit.',
80
65
  };
81
- return {
82
- state: 'unavailable',
83
- reason,
84
- targetResults,
85
- ...(commandPackages.length > 0 ? { commandResults: commandPackages.map((target) => ({
86
- producer: target.producer, state: 'failed', commandIds: [], removedCommandIds: [],
87
- errors: [{ code: reason, message: messages[reason] }],
88
- recoveryActions: [`aw command package sync ${target.producer.sourceId}/${target.producer.pluginName} ${target.packageKey} --scope ${target.producer.scope} --yes`,
89
- `aw command package remove ${target.packageId} --yes`],
90
- })) } : {}),
91
- error: { stage, code: reason, message: messages[reason] },
92
- };
93
- }
94
- function overallStateForApply(apply) {
95
- return apply.state === 'succeeded' || apply.state === 'skipped' ? 'succeeded' : 'partial';
66
+ return { state: 'unavailable', reason, targetResults: [], error: { stage, code: reason, message: messages[reason] } };
96
67
  }
97
68
  function uniqueInOrder(values) {
98
69
  return [...new Set(values)];
@@ -109,466 +80,6 @@ function dedupeTargets(targets) {
109
80
  deduped.set(targetKey(target), target);
110
81
  return [...deduped.values()];
111
82
  }
112
- async function resolveProjectKey(platform, cwd) {
113
- return platform === 'codex' ? resolveCodexProjectKey(cwd)
114
- : platform === 'claude' ? resolveClaudeProjectKey(cwd)
115
- : createProjectLocationKey(await resolveRequiredCanonicalRepoRoot(cwd));
116
- }
117
- async function createCandidateTarget(options) {
118
- return {
119
- pluginName: options.pluginName,
120
- platform: options.platform,
121
- scope: options.scope,
122
- ...(options.scope === 'project'
123
- ? { projectKey: await resolveProjectKey(options.platform, options.cwd) }
124
- : {}),
125
- };
126
- }
127
- async function discoverVisibleTargets(options) {
128
- const targets = [];
129
- const failures = [];
130
- const selector = options.plugin.pluginId ?? options.pluginName;
131
- const consumers = await resolvePluginConfigReferenceConsumers({ plugin: options.plugin, env: options.env,
132
- plugins: options.rebuildRuntime?.referencePlugins });
133
- const selectors = consumers.map((plugin) => plugin.pluginId ?? plugin.manifest.name);
134
- const status = await readScopedRecoveryStatus({ scope: options.scope,
135
- cwd: options.cwd, env: options.env,
136
- nativeCliRunner: options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner,
137
- catalogOperationContext: options.rebuildRuntime?.catalogOperationContext,
138
- codexObservationSession: options.rebuildRuntime?.codexObservationSession,
139
- });
140
- for (const statusTarget of status.existingTargets ?? []) {
141
- if (statusTarget.agent === 'generic' || statusTarget.scope !== options.scope)
142
- continue;
143
- const identity = parsePluginId(statusTarget.pluginId);
144
- if (!selectors.includes(statusTarget.pluginId) && statusTarget.pluginId !== selector
145
- && !selectors.some((entry) => !entry.includes('/') && entry === identity.pluginName))
146
- continue;
147
- // Existing targets already require this scope's observed activation or owned directory.
148
- const plugin = consumers.find((entry) => entry.pluginId === statusTarget.pluginId);
149
- targets.push({ ...await createCandidateTarget({ pluginName: identity.pluginName,
150
- platform: statusTarget.agent, scope: statusTarget.scope, cwd: options.cwd }),
151
- pluginId: statusTarget.pluginId, sourceId: identity.sourceId,
152
- ...(plugin?.sourceIdentity ? { sourceIdentity: plugin.sourceIdentity } : {}),
153
- });
154
- }
155
- return { targets: dedupeTargets(targets), failures };
156
- }
157
- async function reinstallVisibleTargets(options) {
158
- const nativeCliRunner = options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner ?? getDefaultNativeCliRunner();
159
- const discovered = options.discovered ?? await resolveConfigApplyTargets(options);
160
- const managedCommandProducerCache = options.rebuildRuntime?.managedCommandProducerCache
161
- ?? new Map();
162
- if (discovered.targets.some((target) => target.pluginName !== options.plugin.manifest.name)
163
- || discovered.commandPackages?.some((target) => target.producer.pluginName !== options.plugin.manifest.name)) {
164
- const plugins = discovered.plugins ?? await resolvePluginConfigReferencePlugins({ sourceId: options.plugin.sourceId,
165
- sourceIdentity: options.plugin.sourceIdentity, logicalIdentity: options.plugin.catalogLogicalIdentity,
166
- env: options.env, plugins: options.rebuildRuntime?.referencePlugins });
167
- const results = [...discovered.failures];
168
- const commandResults = [];
169
- const failed = new Set(discovered.failures.map(({ target }) => `${target.pluginName}\0${target.platform}\0${target.scope}`));
170
- const failedPackages = new Set();
171
- const errors = (discovered.commandDiscoveryErrors ?? []).map((error) => ({
172
- stage: 'targetDiscovery', code: error.code, message: error.message,
173
- }));
174
- let partial = discovered.failures.length > 0 || errors.length > 0;
175
- for (const plugin of orderPluginMetasByDependencies(plugins)) {
176
- const targets = discovered.targets.filter((target) => target.pluginName === plugin.manifest.name);
177
- const packages = (discovered.commandPackages ?? []).filter((target) => target.producer.pluginName === plugin.manifest.name);
178
- if (!targets.length && !packages.length)
179
- continue;
180
- const dependencies = resolvePluginMetaDependencyClosure(plugins, [plugin.manifest.name])
181
- .filter((entry) => entry.manifest.name !== plugin.manifest.name).map((entry) => entry.manifest.name);
182
- const dependencyPackageFailed = (scope) => dependencies.some((dependency) => failedPackages.has(`${dependency}\0${scope}`) || (scope === 'project' && failedPackages.has(`${dependency}\0user`)));
183
- const blocked = targets.filter((target) => dependencies.some((dependency) => failed.has(`${dependency}\0${target.platform}\0${target.scope}`)
184
- || (target.scope === 'project' && failed.has(`${dependency}\0${target.platform}\0user`)))
185
- || dependencyPackageFailed(target.scope));
186
- if (blocked.length) {
187
- partial = true;
188
- for (const target of blocked)
189
- failed.add(`${plugin.manifest.name}\0${target.platform}\0${target.scope}`);
190
- results.push(...blocked.map((target) => ({ target, action: 'skipped',
191
- state: 'skipped', errorCode: 'dependencyApplyFailed',
192
- message: `A required provider failed. Run aw plugin sync ${plugin.pluginId ?? plugin.manifest.name} --context ${target.scope} --target ${target.platform} --yes.` })));
193
- }
194
- const blockedPackages = packages.filter((target) => {
195
- const platforms = plugin.manifest.managedCommands?.packages.find((entry) => entry.key === target.packageKey
196
- && entry.scope === target.producer.scope)?.platforms ?? NATIVE_PLATFORM_TARGETS;
197
- return dependencyPackageFailed(target.producer.scope) || dependencies.some((dependency) => platforms.some((platform) => failed.has(`${dependency}\0${platform}\0${target.producer.scope}`)
198
- || (target.producer.scope === 'project' && failed.has(`${dependency}\0${platform}\0user`))));
199
- });
200
- for (const target of blockedPackages) {
201
- partial = true;
202
- failedPackages.add(`${plugin.manifest.name}\0${target.producer.scope}`);
203
- commandResults.push({ producer: target.producer, state: 'failed', commandIds: [], removedCommandIds: [],
204
- errors: [{ code: 'dependencyApplyFailed', message: 'A required provider failed; the command package was not refreshed.' }],
205
- recoveryActions: [`aw command package sync ${plugin.pluginId ?? plugin.manifest.name} ${target.packageKey} --scope ${target.producer.scope} --yes`] });
206
- }
207
- const available = targets.filter((target) => !blocked.includes(target));
208
- const availablePackages = packages.filter((target) => !blockedPackages.includes(target));
209
- if (!available.length && !availablePackages.length)
210
- continue;
211
- const own = plugin.manifest.name === options.plugin.manifest.name;
212
- const result = await reinstallVisibleTargets({ ...options, plugin,
213
- changedConfigKeys: own ? options.changedConfigKeys : [],
214
- rebuildRuntime: { ...options.rebuildRuntime, referencePlugins: plugins, managedCommandProducerCache },
215
- discovered: { targets: available, failures: [], commandPackages: availablePackages,
216
- commandDiscoveryErrors: [] } });
217
- if (result.state !== 'succeeded' && result.state !== 'skipped') {
218
- partial = true;
219
- for (const target of available) {
220
- if (!('targetResults' in result) || !result.targetResults.some((entry) => targetKey(entry.target) === targetKey(target) && entry.state === 'completed')) {
221
- failed.add(`${plugin.manifest.name}\0${target.platform}\0${target.scope}`);
222
- }
223
- }
224
- }
225
- if ('targetResults' in result)
226
- results.push(...result.targetResults);
227
- if ('commandResults' in result) {
228
- commandResults.push(...result.commandResults ?? []);
229
- for (const entry of result.commandResults ?? []) {
230
- if (entry.state !== 'completed')
231
- failedPackages.add(`${plugin.manifest.name}\0${entry.producer.scope}`);
232
- }
233
- }
234
- if ('errors' in result)
235
- errors.push(...result.errors ?? []);
236
- }
237
- return { state: partial ? 'partial' : 'succeeded', targetResults: results,
238
- ...(commandResults.length ? { commandResults } : {}), ...(errors.length ? { errors } : {}) };
239
- }
240
- const contexts = new Map();
241
- const demands = new Map();
242
- const failedScopes = new Set();
243
- try {
244
- const targetResults = [...discovered.failures];
245
- const commandResults = new Map();
246
- let runtimeFailed = discovered.failures.length > 0
247
- || (discovered.commandDiscoveryErrors?.length ?? 0) > 0;
248
- let invalidTargets = 0;
249
- let unavailableTargets = 0;
250
- const errors = [];
251
- for (const scope of new Set(discovered.targets.map((target) => target.scope))) {
252
- try {
253
- const context = await createScopeContext({ scope, cwd: options.cwd, env: options.env });
254
- contexts.set(scope, context);
255
- const demand = await readDemand({ scope, cwd: context.executionCwd, env: context.env });
256
- demandNativeProjection(demand);
257
- demands.set(scope, demand);
258
- }
259
- catch {
260
- failedScopes.add(scope);
261
- runtimeFailed = true;
262
- for (const target of discovered.targets.filter((entry) => entry.scope === scope)) {
263
- targetResults.push({ target, action: 'reinstall', state: 'failed', errorCode: 'configApplyContextUnavailable',
264
- message: 'The target scope or its demand cannot be read safely.' });
265
- }
266
- errors.push({ stage: 'targetValidation', code: 'configApplyContextUnavailable',
267
- message: 'A visible target scope or its demand cannot be read safely.' });
268
- }
269
- }
270
- if ((discovered.commandDiscoveryErrors?.length ?? 0) > 0) {
271
- errors.push(...discovered.commandDiscoveryErrors.map((error) => ({
272
- stage: 'targetDiscovery', code: error.code, message: error.message,
273
- })));
274
- }
275
- const reinstall = options.reinstallCommandImpl ?? syncWriteCommand;
276
- if (options.plugin.sourceId && !options.plugin.pluginId) {
277
- throw new Error(`Plugin "${options.plugin.manifest.name}" is missing its namespaced plugin ID.`);
278
- }
279
- const selector = options.plugin.sourceId
280
- ? options.plugin.pluginId
281
- : options.plugin.manifest.name;
282
- const nativeFailures = [];
283
- for (const target of discovered.commandPackages ?? []) {
284
- try {
285
- await assertManagedCommandPackageNativeToolsUnchanged({ plugin: options.plugin, producer: target.producer, env: options.env });
286
- }
287
- catch (error) {
288
- nativeFailures.push({ producer: target.producer, state: 'failed', commandIds: [], removedCommandIds: [],
289
- errors: [managedCommandDiagnostic(error)],
290
- recoveryActions: [`aw command package sync ${selector} ${target.packageKey} --scope ${target.producer.scope} --yes`] });
291
- }
292
- }
293
- if (nativeFailures.length > 0) {
294
- return { state: 'partial', commandResults: nativeFailures,
295
- targetResults: [...targetResults, ...discovered.targets.map((target) => ({
296
- target, action: 'reinstall', state: 'failed', errorCode: 'nativeToolSyncRequired',
297
- message: 'Run a reviewed producer sync or package sync before configuration apply.',
298
- }))] };
299
- }
300
- const sanitizeFailure = async (message, target) => {
301
- let sensitiveValues = [];
302
- try {
303
- const effective = await resolveEffectivePluginConfig({
304
- ...(options.plugin.sourceId ? {
305
- sourceId: options.plugin.sourceId,
306
- sourceIdentity: options.plugin.sourceIdentity,
307
- logicalIdentity: options.plugin.catalogLogicalIdentity,
308
- } : {}),
309
- pluginName: options.plugin.manifest.name,
310
- manifest: options.plugin.manifest,
311
- referencePlugins: options.rebuildRuntime?.referencePlugins,
312
- targetScope: target.scope,
313
- platform: target.platform ?? undefined,
314
- cwd: options.cwd,
315
- env: options.env,
316
- });
317
- sensitiveValues = collectSensitivePluginConfigValues(options.plugin.manifest, effective.values, target.platform ?? undefined);
318
- }
319
- catch {
320
- // Generic credential redaction and known config paths still apply.
321
- }
322
- let sanitized = redactPluginScriptOutput(message, sensitiveValues);
323
- for (const privatePath of [target.projectKey, options.cwd]) {
324
- if (privatePath)
325
- sanitized = sanitized.split(privatePath).join('<project>');
326
- }
327
- for (const scope of ['user', 'project']) {
328
- const configPath = resolvePluginConfigStorePath({
329
- sourceId: options.plugin.sourceId,
330
- pluginName: options.plugin.manifest.name,
331
- scope,
332
- cwd: options.cwd,
333
- env: options.env,
334
- });
335
- const safeTarget = `${scope}/plugin-config/${[
336
- options.plugin.sourceId,
337
- options.plugin.manifest.name,
338
- 'config.json',
339
- ].filter(Boolean).join('/')}`;
340
- sanitized = sanitized.split(configPath).join(safeTarget);
341
- }
342
- return sanitized;
343
- };
344
- const sanitizeProjection = async (value, target, freeText = false) => {
345
- if (typeof value === 'string')
346
- return freeText ? sanitizeFailure(value, target) : value;
347
- if (value === null || typeof value !== 'object')
348
- return value;
349
- if (Array.isArray(value)) {
350
- return Promise.all(value.map((entry) => sanitizeProjection(entry, target, freeText)));
351
- }
352
- return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [
353
- key,
354
- await sanitizeProjection(entry, target, typeof entry === 'string'
355
- ? /^(?:message|error|stack|stdout|stderr|output|warning)$/u.test(key)
356
- : Array.isArray(entry) && /^(?:messages|warnings)$/u.test(key)),
357
- ])));
358
- };
359
- const preApplyExecutionCache = new Map();
360
- for (const target of discovered.targets) {
361
- if (failedScopes.has(target.scope))
362
- continue;
363
- try {
364
- const configs = await Promise.all(pluginConfigTargetRenderScopes(options.plugin, target).map((scope) => resolveEffectivePluginConfig({
365
- ...(options.plugin.sourceId ? {
366
- sourceId: options.plugin.sourceId,
367
- sourceIdentity: options.plugin.sourceIdentity,
368
- logicalIdentity: options.plugin.catalogLogicalIdentity,
369
- } : {}),
370
- pluginName: options.plugin.manifest.name,
371
- manifest: options.plugin.manifest,
372
- referencePlugins: options.rebuildRuntime?.referencePlugins,
373
- targetScope: scope,
374
- platform: target.platform ?? undefined,
375
- cwd: options.cwd,
376
- env: options.env,
377
- })));
378
- if (configs.some((effective) => effective.issues.length > 0)) {
379
- invalidTargets += 1;
380
- targetResults.push({
381
- target,
382
- action: 'reinstall',
383
- state: 'skipped',
384
- errorCode: 'invalidConfig',
385
- message: 'The effective config is invalid for this target.',
386
- });
387
- continue;
388
- }
389
- }
390
- catch {
391
- runtimeFailed = true;
392
- unavailableTargets += 1;
393
- targetResults.push({
394
- target,
395
- action: 'reinstall',
396
- state: 'failed',
397
- errorCode: 'effectiveConfigUnavailable',
398
- message: 'The effective config cannot be read for this target.',
399
- });
400
- errors.push({
401
- stage: 'targetValidation',
402
- code: 'effectiveConfigUnavailable',
403
- message: 'The effective config cannot be read for a visible target.',
404
- });
405
- continue;
406
- }
407
- try {
408
- const debugLogger = options.rebuildRuntime?.debugLogger;
409
- const reporter = options.rebuildRuntime?.reporter;
410
- const result = await reinstall([selector], {
411
- cwd: contexts.get(target.scope).executionCwd,
412
- platform: target.platform,
413
- scope: target.scope,
414
- ...(options.rebuildRuntime?.scriptTimeoutMs === undefined
415
- ? {}
416
- : { scriptTimeoutMs: options.rebuildRuntime.scriptTimeoutMs }),
417
- }, {
418
- ...options.rebuildRuntime,
419
- env: contexts.get(target.scope).env,
420
- nativeCliRunner,
421
- executionInput: {
422
- context: contexts.get(target.scope),
423
- requirements: demandNativeProjection(demands.get(target.scope)),
424
- selectedTargets: [{ pluginId: selector, platform: target.platform, scope: target.scope }],
425
- preserveOtherObservedTargets: true,
426
- },
427
- preApplyConfirmed: options.preApplyConfirmed === true,
428
- preApplyExecutionCache,
429
- managedCommandProducerCache,
430
- ...(debugLogger ? {
431
- debugLogger: {
432
- ...debugLogger,
433
- log: async (value) => debugLogger.log(await sanitizeProjection(value, target)),
434
- },
435
- } : {}),
436
- ...(reporter ? {
437
- reporter: {
438
- event: async (value) => reporter.event(await sanitizeProjection(value, target)),
439
- notice: async (value) => reporter.notice(await sanitizeProjection(value, target)),
440
- },
441
- } : {}),
442
- });
443
- options.rebuildRuntime?.operationDiagnosticSink?.(result.rebuildResults);
444
- for (const producer of result.commandResults ?? []) {
445
- commandResults.set(getCommandPackageId(producer.producer), producer);
446
- if (producer.state !== 'completed')
447
- runtimeFailed = true;
448
- }
449
- if (result.overallState !== 'succeeded')
450
- runtimeFailed = true;
451
- targetResults.push(...await Promise.all(result.targetResults.map(async (entry) => ({
452
- ...entry,
453
- state: entry.action === 'skipped' ? 'skipped' : entry.state,
454
- ...(entry.message ? { message: await sanitizeFailure(entry.message, entry.target) } : {}),
455
- }))));
456
- }
457
- catch (error) {
458
- runtimeFailed = true;
459
- const message = await sanitizeFailure(error instanceof Error ? error.message : String(error), target);
460
- targetResults.push({
461
- target,
462
- action: 'reinstall',
463
- state: 'failed',
464
- message,
465
- });
466
- errors.push({
467
- stage: 'apply',
468
- code: 'targetApplyFailed',
469
- message: 'A visible config apply target failed.',
470
- });
471
- }
472
- }
473
- for (const target of discovered.commandPackages ?? []) {
474
- await options.rebuildRuntime?.reporter?.event({
475
- type: 'managed-command:producer',
476
- source: { plugin: options.plugin.manifest.name, scope: target.producer.scope },
477
- data: { packageKey: target.packageKey, phase: 'start' },
478
- });
479
- let result;
480
- if (!target.declared) {
481
- result = {
482
- producer: target.producer, state: 'failed', commandIds: [], removedCommandIds: [],
483
- errors: [{ code: 'commandPackageDeclarationMissing',
484
- message: 'The installed command package is no longer declared by this plugin.' }],
485
- recoveryActions: [`aw command package remove ${target.packageId} --yes`],
486
- };
487
- }
488
- else {
489
- try {
490
- result = await syncPluginManagedCommandPackage({
491
- plugin: options.plugin, packageKey: target.packageKey, scope: target.producer.scope,
492
- cwd: options.cwd, env: options.env, managedCommandProducerCache, expectedPackage: target.expectedPackage,
493
- referencePlugins: options.rebuildRuntime?.referencePlugins,
494
- event: options.changedConfigKeys?.length ? 'refresh' : 'install',
495
- changedConfigKeys: options.changedConfigKeys ?? [],
496
- signal: options.rebuildRuntime?.signal,
497
- scriptTimeoutMs: options.rebuildRuntime?.scriptTimeoutMs,
498
- });
499
- }
500
- catch (error) {
501
- if (recoveryInterruptionCode(error, options.rebuildRuntime?.signal) || readSafeOperationError(error))
502
- throw error;
503
- result = {
504
- producer: target.producer, state: 'failed', commandIds: [], removedCommandIds: [],
505
- errors: [{ code: 'commandPackageApplyFailed', message: 'The managed command package could not be refreshed.' }],
506
- recoveryActions: [`aw command package sync ${selector} ${target.packageKey} --scope ${target.producer.scope} --yes`,
507
- `aw command package remove ${target.packageId} --yes`],
508
- };
509
- }
510
- }
511
- result = { ...result, errors: await Promise.all(result.errors.map(async (error) => ({
512
- ...error, message: await sanitizeFailure(error.message, { scope: target.producer.scope,
513
- ...(target.producer.projectRoot ? { projectKey: target.producer.projectRoot } : {}) }),
514
- }))) };
515
- commandResults.set(getCommandPackageId(result.producer), result);
516
- await options.rebuildRuntime?.reporter?.event({
517
- type: 'managed-command:producer',
518
- source: { plugin: options.plugin.manifest.name, scope: target.producer.scope },
519
- data: { packageKey: target.packageKey, phase: result.state === 'completed' ? 'success' : 'failure' },
520
- });
521
- if (result.state !== 'completed')
522
- runtimeFailed = true;
523
- }
524
- const commands = commandResults.size > 0 ? { commandResults: [...commandResults.values()] } : {};
525
- const commandTargetCount = (discovered.commandPackages?.length ?? 0);
526
- if (discovered.targets.length === 0 && discovered.failures.length === 0
527
- && commandTargetCount === 0 && !runtimeFailed) {
528
- return skippedApply('noVisibleTarget');
529
- }
530
- if (discovered.targets.length > 0 && invalidTargets === discovered.targets.length && commandTargetCount === 0) {
531
- return { ...unavailableApply('invalidConfig', 'targetValidation', targetResults), ...commands };
532
- }
533
- if (discovered.targets.length > 0 && unavailableTargets === discovered.targets.length && commandTargetCount === 0) {
534
- return { ...unavailableApply('effectiveConfigUnavailable', 'targetValidation', targetResults), ...commands };
535
- }
536
- if (runtimeFailed
537
- || invalidTargets > 0
538
- || unavailableTargets > 0
539
- || targetResults.some((entry) => entry.state === 'failed' || entry.state === 'skipped')) {
540
- return {
541
- state: 'partial',
542
- targetResults,
543
- ...commands,
544
- ...(errors.length > 0 ? { errors } : {}),
545
- };
546
- }
547
- return { state: 'succeeded', targetResults, ...commands };
548
- }
549
- finally {
550
- await Promise.all([...contexts.values()].map((context) => context.dispose()));
551
- }
552
- }
553
- async function resolveConfigApplyTargets(options) {
554
- const platformTargets = options.applyTargets !== undefined
555
- ? { targets: dedupeTargets(options.applyTargets), failures: [] }
556
- : await discoverVisibleTargets({
557
- pluginName: options.plugin.manifest.name,
558
- plugin: options.plugin,
559
- scope: options.scope,
560
- cwd: options.cwd,
561
- env: options.env,
562
- nativeCliRunner: options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner ?? getDefaultNativeCliRunner(),
563
- rebuildRuntime: options.rebuildRuntime,
564
- });
565
- const commands = await discoverPluginConfigManagedCommandPackages({
566
- plugin: options.plugin, scope: options.scope, cwd: options.cwd, env: options.env,
567
- platformTargets: platformTargets.targets,
568
- referencePlugins: options.rebuildRuntime?.referencePlugins,
569
- });
570
- return { ...platformTargets, commandPackages: commands.packages, commandDiscoveryErrors: commands.errors };
571
- }
572
83
  async function configApplyHasValidSharedNativeTarget(options) {
573
84
  const plugins = await resolvePluginConfigReferenceConsumers({ plugin: options.plugin, env: options.env, plugins: options.plugins });
574
85
  for (const plugin of plugins) {
@@ -587,7 +98,8 @@ async function configApplyHasValidSharedNativeTarget(options) {
587
98
  return false;
588
99
  }
589
100
  export async function resolveConfigPreApplyAuthorization(options) {
590
- const applyTargets = dedupeTargets(options.applyTargets);
101
+ const applyTargets = dedupeTargets(options.applyTargets).filter((target) => !options.rebuildRuntime?.configApplyPackages?.targets.some((entry) => entry.blocker
102
+ && entry.pluginId === (target.pluginId ?? options.plugin.pluginId) && entry.platforms.includes(target.platform)));
591
103
  if (applyTargets.some((target) => target.pluginName !== options.plugin.manifest.name)) {
592
104
  const plugins = await resolvePluginConfigReferencePlugins({ sourceId: options.plugin.sourceId,
593
105
  sourceIdentity: options.plugin.sourceIdentity, logicalIdentity: options.plugin.catalogLogicalIdentity,
@@ -734,121 +246,14 @@ function buildReceiptFieldEntry(options) {
734
246
  };
735
247
  }
736
248
  export async function replayConfigRuntimeWrites(options) {
737
- if (!options.awHomeMutationToken) {
738
- await prepareNativeCliExecution({ env: options.env, runner: options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner });
739
- }
740
- return withAwHomeMutationLock({
741
- env: options.env,
742
- token: options.awHomeMutationToken,
743
- action: async (awHomeMutationToken) => {
744
- const env = options.env ?? process.env;
745
- const rebuildRuntime = { ...options.rebuildRuntime, awHomeMutationToken };
746
- let discovered;
747
- try {
748
- discovered = await resolveConfigApplyTargets({
749
- plugin: options.plugin,
750
- scope: options.scope,
751
- cwd: options.cwd,
752
- env,
753
- applyTargets: options.applyTargets,
754
- nativeCliRunner: options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner,
755
- rebuildRuntime,
756
- });
757
- }
758
- catch {
759
- const apply = unavailableApply('targetDiscoveryFailed', 'targetDiscovery');
760
- return {
761
- configWrite: 'succeeded',
762
- overallState: 'partial',
763
- apply: publicConfigApplyResult(apply),
764
- otherProjectsMayRequireSync: false,
765
- };
766
- }
767
- const preApplyAuthorization = await resolveConfigPreApplyAuthorization({
768
- plugin: options.plugin,
769
- scope: options.scope,
770
- cwd: options.cwd,
771
- env,
772
- applyTargets: discovered.targets,
773
- nativeCliRunner: options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner,
774
- rebuildRuntime,
775
- reinstallCommandImpl: options.reinstallCommandImpl,
776
- });
777
- if (preApplyAuthorization.targets.length > 0 && !preApplyAuthorizationIsConfirmed({
778
- required: preApplyAuthorization.targets,
779
- confirmed: options.preApplyConfirmed,
780
- authorizedTargets: options.preApplyAuthorizedTargets,
781
- })) {
782
- const apply = {
783
- state: 'partial',
784
- targetResults: preApplyAuthorization.targets.map((target) => ({
785
- target: {
786
- pluginName: target.pluginName,
787
- pluginId: target.pluginId,
788
- platform: target.platform,
789
- scope: target.scope,
790
- },
791
- action: 'reinstall',
792
- state: 'failed',
793
- errorCode: 'preApplyAuthorizationRequired',
794
- message: 'Running plugin preApply requires explicit authorization.',
795
- })),
796
- };
797
- return {
798
- configWrite: 'succeeded',
799
- overallState: 'partial',
800
- apply: publicConfigApplyResult(apply),
801
- otherProjectsMayRequireSync: false,
802
- };
803
- }
804
- discovered = {
805
- ...discovered,
806
- targets: preApplyAuthorization.availableApplyTargets,
807
- failures: [...discovered.failures, ...preApplyAuthorization.unavailableTargetResults],
808
- };
809
- if (discovered.targets.length === 0
810
- && preApplyAuthorization.unavailableTargetResults.length > 0
811
- && (discovered.commandPackages?.length ?? 0) === 0) {
812
- const apply = unavailableApply('sourceUnavailable', 'source', preApplyAuthorization.unavailableTargetResults);
813
- return {
814
- configWrite: 'succeeded',
815
- overallState: 'partial',
816
- apply: publicConfigApplyResult(apply),
817
- otherProjectsMayRequireSync: false,
818
- };
819
- }
820
- if (options.scope === 'user'
821
- && options.sharedNativeApplyConfirmed !== true
822
- && await configApplyHasValidSharedNativeTarget({
823
- plugin: options.plugin,
824
- targets: discovered.targets,
825
- cwd: options.cwd,
826
- env,
827
- plugins: rebuildRuntime.referencePlugins,
828
- })) {
829
- throwSharedNativeApplyConfirmationRequired();
830
- }
831
- const apply = await reinstallVisibleTargets({
832
- plugin: options.plugin,
833
- scope: options.scope,
834
- cwd: options.cwd,
835
- env,
836
- applyTargets: options.applyTargets,
837
- nativeCliRunner: options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner,
838
- reinstallCommandImpl: options.reinstallCommandImpl,
839
- rebuildRuntime,
840
- discovered,
841
- preApplyConfirmed: options.preApplyConfirmed,
842
- });
843
- return {
844
- configWrite: 'succeeded',
845
- overallState: overallStateForApply(apply),
846
- apply: publicConfigApplyResult(apply),
847
- otherProjectsMayRequireSync: false,
848
- };
849
- },
850
- });
851
- }
249
+ if (options.scope === 'user' && options.sharedNativeApplyConfirmed !== true && await configApplyHasValidSharedNativeTarget({
250
+ ...options, plugins: options.rebuildRuntime?.referencePlugins, targets: options.applyTargets ?? [],
251
+ }))
252
+ throwSharedNativeApplyConfirmationRequired();
253
+ const result = await applyPluginConfig(options);
254
+ return { ...result, configWrite: 'succeeded', otherProjectsMayRequireSync: false };
255
+ }
256
+ const commandCandidateCleanup = new WeakMap();
852
257
  function configApplyRequestedTargets(plan) {
853
258
  const targets = plan.joint
854
259
  ? plan.joint.children.filter((child) => child.command !== 'cleanup' && child.command !== 'uninstall')
@@ -857,115 +262,69 @@ function configApplyRequestedTargets(plan) {
857
262
  return targets.filter((target) => !plan.receipt.targetResults.some((result) => result.pluginId === target.pluginId && result.agent === target.agent && result.scope === target.scope
858
263
  && (result.satisfaction === 'unsupported' || result.satisfaction === 'excluded')));
859
264
  }
860
- async function prepareConfigApplyPackages(options, plugins, plan, referencePlugins) {
265
+ function configApplyPackageHook(options, entries, referencePlugins) {
861
266
  const env = options.env ?? process.env;
862
- const context = options.context ?? options.scope;
863
- const discoveries = [];
864
- const scopes = context === 'project' ? ['user', 'project'] : ['user'];
865
- const nativeTargets = configApplyRequestedTargets(plan).flatMap((target) => target.agent !== 'generic'
866
- ? [{ pluginName: target.pluginId.split('/').at(-1), pluginId: target.pluginId, platform: target.agent, scope: target.scope }] : []);
867
- for (const plugin of plugins) {
868
- for (const scope of scopes) {
869
- discoveries.push(await discoverInstalledPluginManagedCommandPackages({ plugin, scope, cwd: options.cwd, env,
870
- platformTargets: nativeTargets.filter((target) => target.pluginId === (plugin.pluginId ?? plugin.manifest.name)
871
- && (scope === 'user' || target.scope === 'project')) }));
872
- }
873
- }
874
- const packages = [...new Map(discoveries.flatMap((discovery) => discovery.packages).filter((target) => {
875
- if (options.applyCommandPackages && !options.applyCommandPackages.includes(target.packageId))
876
- return false;
877
- if (options.platform)
878
- return false;
879
- if (!options.targets)
880
- return true;
881
- const plugin = plugins.find((entry) => entry.manifest.name === target.producer.pluginName);
882
- const declaration = plugin?.manifest.managedCommands?.packages.find((entry) => entry.key === target.packageKey && entry.scope === target.producer.scope);
883
- return declaration?.platforms.some((platform) => options.targets.includes(platform)) ?? false;
884
- }).map((target) => [target.packageId, target])).values()];
885
- const inventory = await listManagedCommandPackages(env);
886
- const entries = await Promise.all(packages.map(async (target) => {
887
- const plugin = plugins.find((entry) => entry.manifest.name === target.producer.pluginName);
888
- const installed = inventory.packages.find((entry) => entry.id === target.packageId);
889
- let expectedPackage;
890
- let blocker;
891
- if (!target.installed || !installed) {
892
- blocker = { code: 'configApplyRequiresExistingOutput', message: 'Configuration apply requires an existing command package. Run package sync first.' };
893
- }
894
- else if (!target.declared) {
895
- blocker = { code: 'commandPackageDeclarationMissing', message: 'The installed command package is no longer declared by this plugin.' };
896
- }
897
- else {
898
- try {
899
- await assertManagedCommandPackageNativeToolsUnchanged({ plugin, producer: target.producer, env });
900
- expectedPackage = await captureManagedCommandPackageEvidence(installed, env);
901
- }
902
- catch (error) {
903
- blocker = managedCommandDiagnostic(error);
904
- }
905
- }
906
- return { target, expectedPackage, blocker };
267
+ const targets = entries.map(({ target, plugin, evidence }) => ({
268
+ pluginId: plugin.pluginId ?? plugin.manifest.name,
269
+ scope: 'user',
270
+ packageId: target.packageId,
271
+ platforms: evidence.review?.routeChanges.length || evidence.blocker
272
+ ? [...plugin.manifest.command?.platforms ?? target.runtimeConfigPlatforms] : [],
273
+ ...(evidence.blocker && ['nativeToolSyncRequired', 'configApplyVersionMismatch'].includes(evidence.blocker.code)
274
+ ? { blocker: evidence.blocker } : {}),
275
+ dependencies: resolvePluginMetaDependencyClosure(referencePlugins, [plugin.manifest.name])
276
+ .filter((entry) => entry.manifest.name !== plugin.manifest.name).map((entry) => entry.pluginId ?? entry.manifest.name),
907
277
  }));
908
- const errors = [...new Map(discoveries.flatMap((discovery) => discovery.errors).map((error) => [JSON.stringify(error), error])).values()];
909
- const evidence = { packages: entries, errors };
910
- const targets = entries.map(({ target }) => {
911
- const plugin = plugins.find((entry) => entry.manifest.name === target.producer.pluginName);
912
- const pluginId = plugin.pluginId ?? plugin.manifest.name;
913
- const dependencies = resolvePluginMetaDependencyClosure(referencePlugins, [plugin.manifest.name])
914
- .filter((entry) => entry.manifest.name !== plugin.manifest.name).map((entry) => entry.pluginId ?? entry.manifest.name);
915
- const declaration = plugin.manifest.managedCommands?.packages.find((item) => item.key === target.packageKey && item.scope === target.producer.scope);
916
- return { pluginId, scope: target.producer.scope, packageId: target.packageId, platforms: declaration?.platforms ?? [], dependencies };
917
- });
918
- const cache = plan.runtime.managedCommandProducerCache ??= new Map();
919
- const hook = { targets, evidence,
920
- blocked: (pluginId, scope, code, packageId) => {
921
- const plugin = plugins.find((entry) => (entry.pluginId ?? entry.manifest.name) === pluginId);
922
- return entries.filter(({ target }) => target.producer.pluginName === plugin.manifest.name && target.producer.scope === scope
923
- && (!packageId || target.packageId === packageId))
924
- .map(({ target }) => ({
925
- producer: target.producer, state: 'failed', commandIds: [], removedCommandIds: [],
926
- errors: [{ code, message: 'The command package refresh did not complete.' }],
927
- recoveryActions: [`aw command package sync ${pluginId} ${target.packageKey} --scope ${scope} --yes`],
928
- }));
929
- },
930
- execute: async (pluginId, scope, token, packageId) => {
931
- const plugin = plugins.find((entry) => (entry.pluginId ?? entry.manifest.name) === pluginId);
932
- const selected = entries.filter(({ target }) => target.producer.pluginName === plugin.manifest.name && target.producer.scope === scope
933
- && (!packageId || target.packageId === packageId));
278
+ const selected = (pluginId, packageId) => entries.filter(({ target, plugin }) => (plugin.pluginId ?? plugin.manifest.name) === pluginId && (!packageId || target.packageId === packageId));
279
+ return { targets, evidence: entries.map(({ evidence }) => evidence),
280
+ blocked: (pluginId, _scope, code, packageId) => selected(pluginId, packageId).map(({ target, candidate, evidence }) => configPackageResult(target, [evidence.blocker ?? { code, message: 'The command package refresh did not complete.' }], candidate)),
281
+ execute: async (pluginId, _scope, _token, packageId) => {
934
282
  const results = [];
935
- let executionContext;
936
- try {
937
- executionContext = await createScopeContext({ scope, cwd: options.cwd, env });
938
- for (const { target, expectedPackage, blocker } of selected) {
939
- if (blocker) {
940
- const result = { producer: target.producer, state: 'failed', commandIds: [], removedCommandIds: [],
941
- errors: [blocker], recoveryActions: [target.declared
942
- ? `aw command package sync ${pluginId} ${target.packageKey} --scope ${scope} --yes`
943
- : `aw command package remove ${target.packageId} --yes`] };
944
- cache.set(target.packageId, Promise.resolve(result));
945
- results.push(result);
946
- continue;
283
+ for (const { target, plugin, candidate, evidence } of selected(pluginId, packageId)) {
284
+ if (evidence.blocker || !candidate) {
285
+ results.push(configPackageResult(target, [evidence.blocker ?? {
286
+ code: 'commandPackageApplyFailed', message: 'The command package could not be prepared.',
287
+ }]));
288
+ continue;
289
+ }
290
+ try {
291
+ options.rebuildRuntime?.signal?.throwIfAborted();
292
+ if (canonicalizeIdentityValue(evidence.review) !== canonicalizeIdentityValue(await inspectConfigCommandPackageReview(options, target, candidate))) {
293
+ throw new ManagedCommandError('operationReviewStale', 'Permissions affecting the reviewed routes changed. Prepare a new Review.');
947
294
  }
948
- const applied = await reinstallVisibleTargets({ plugin, scope, cwd: executionContext.executionCwd, env: executionContext.env,
949
- changedConfigKeys: [...target.refreshKeys],
950
- rebuildRuntime: { ...options.rebuildRuntime, awHomeMutationToken: token, referencePlugins, managedCommandProducerCache: cache },
951
- discovered: { targets: [], failures: [], commandPackages: [{ ...target, expectedPackage }], commandDiscoveryErrors: [] } });
952
- results.push(...('commandResults' in applied ? applied.commandResults ?? [] : []));
295
+ const published = await publishPreparedManagedCommandPackage({ plugin, candidate, cwd: options.cwd, env, referencePlugins });
296
+ results.push(configPackageResult(target, [], candidate, published));
297
+ }
298
+ catch (error) {
299
+ if (recoveryInterruptionCode(error, options.rebuildRuntime?.signal) || readSafeOperationError(error))
300
+ throw error;
301
+ results.push(configPackageResult(target, [managedCommandDiagnostic(error)], candidate));
953
302
  }
954
- return results;
955
- }
956
- finally {
957
- await executionContext?.dispose();
958
303
  }
959
- } };
960
- return { packages, evidence, errors, hook };
304
+ return results;
305
+ },
306
+ };
961
307
  }
962
308
  /** Prepare the same existing-output plan used by apply, without saving config or output. */
963
- export async function preparePluginConfigApply(options) {
309
+ export async function preparePluginConfigApply(options, { inspectOnly = false } = {}) {
964
310
  const { prepareRecovery, describeRecoveryPlan } = await import('../recovery/coordinator.js');
965
311
  const context = options.context ?? options.scope;
966
312
  const referencePlugins = await resolvePluginConfigReferencePlugins({ sourceId: options.plugin.sourceId,
967
313
  sourceIdentity: options.plugin.sourceIdentity, logicalIdentity: options.plugin.catalogLogicalIdentity,
968
- env: options.env, plugins: options.rebuildRuntime?.referencePlugins });
314
+ env: options.env, plugins: options.rebuildRuntime?.referencePlugins,
315
+ operationContext: options.rebuildRuntime?.catalogOperationContext }).catch((error) => {
316
+ if (recoveryInterruptionCode(error, options.rebuildRuntime?.signal))
317
+ throw error;
318
+ throw Object.assign(new Error('The selected source has no usable Active Catalog.'), { code: 'sourceActiveUnavailable' });
319
+ });
320
+ if (options.plugin.sourceId) {
321
+ const activePlugin = referencePlugins.find((entry) => entry.manifest.name === options.plugin.manifest.name);
322
+ if (activePlugin)
323
+ options = { ...options, plugin: activePlugin };
324
+ else if (options.plugin.manifest.command) {
325
+ throw Object.assign(new Error('The plugin is unavailable in Active Catalog.'), { code: 'pluginUnavailable' });
326
+ }
327
+ }
969
328
  const plugins = await resolvePluginConfigReferenceConsumers({ plugin: options.plugin, env: options.env,
970
329
  plugins: referencePlugins });
971
330
  const selectors = plugins.map((plugin) => plugin.pluginId ?? plugin.manifest.name);
@@ -993,33 +352,65 @@ export async function preparePluginConfigApply(options) {
993
352
  return true;
994
353
  });
995
354
  }
996
- const plan = await prepareRecovery('sync', selectors, {
997
- scope: context,
998
- context,
999
- cwd: options.cwd,
1000
- env: options.env,
1001
- signal: options.rebuildRuntime?.signal,
1002
- cliVersion: version,
1003
- existingOnly: true,
1004
- ...(exactTargets ? { exactTargets } : {}),
1005
- ...(options.targets ? { targets: options.targets } : options.platform ? { targets: [options.platform] } : {}),
1006
- }, {
1007
- ...options.rebuildRuntime,
1008
- referencePlugins,
1009
- nativeCliRunner: options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner,
1010
- awHomeMutationToken: options.awHomeMutationToken,
1011
- preApplyConfirmed: options.preApplyConfirmed,
355
+ const env = options.env ?? process.env;
356
+ const commands = await discoverPluginConfigManagedCommandPackages({ plugin: options.plugin, scope: context,
357
+ cwd: options.cwd, env, referencePlugins });
358
+ let selectedPackages = commands.packages.filter((target) => {
359
+ if (options.applyCommandPackages && !options.applyCommandPackages.includes(target.packageId))
360
+ return false;
361
+ const plugin = plugins.find((entry) => entry.manifest.name === target.producer.pluginName);
362
+ const platforms = plugin?.manifest.command?.platforms ?? target.runtimeConfigPlatforms;
363
+ if (options.platform)
364
+ return options.platform !== 'generic' && platforms.includes(options.platform) && target.runtimeConfigKeys.length > 0;
365
+ return (target.refreshKeys.length > 0 || target.runtimeConfigKeys.length > 0)
366
+ && (!options.targets || platforms.some((platform) => options.targets.includes(platform)));
1012
367
  });
368
+ if (options.mutation) {
369
+ const impact = await analyzePluginConfigMutationImpact({ ...options, scope: context, visibleTargets: [],
370
+ mutation: options.mutation, commandDiscovery: { ...commands, packages: selectedPackages }, referencePlugins });
371
+ selectedPackages = impact.affectedCommandPackages;
372
+ }
373
+ const entries = await prepareConfigCommandPackages(options, selectedPackages, plugins, referencePlugins, { inspectOnly });
374
+ const cleanup = () => Promise.all(entries.map(({ candidate }) => candidate?.cleanup()));
375
+ const packagePreparationCache = new Map();
376
+ for (const { target, candidate } of entries) {
377
+ if (candidate)
378
+ packagePreparationCache.set(target.packageId, Promise.resolve(candidate));
379
+ }
380
+ let plan;
1013
381
  try {
382
+ plan = await prepareRecovery('sync', selectors, {
383
+ scope: context,
384
+ context,
385
+ cwd: options.cwd,
386
+ env: options.env,
387
+ signal: options.rebuildRuntime?.signal,
388
+ cliVersion: version,
389
+ existingOnly: true,
390
+ ...(exactTargets ? { exactTargets } : {}),
391
+ ...(options.platform ? { targets: [options.platform] } : options.targets ? { targets: options.targets } : {}),
392
+ }, {
393
+ ...options.rebuildRuntime,
394
+ configApply: true,
395
+ packagePreparationCache,
396
+ configApplyPackages: configApplyPackageHook(options, entries, referencePlugins),
397
+ referencePlugins,
398
+ nativeCliRunner: options.nativeCliRunner ?? options.rebuildRuntime?.nativeCliRunner,
399
+ awHomeMutationToken: options.awHomeMutationToken,
400
+ preApplyConfirmed: options.preApplyConfirmed,
401
+ });
402
+ commandCandidateCleanup.set(plan, cleanup);
1014
403
  plan.warnings.push(...retainedLegacyTargets.map((target) => `${target.pluginId ?? target.pluginName}/${target.platform}/${target.scope}:保留已停用的历史输出;配置 apply 不创建激活。`));
1015
- const commands = await prepareConfigApplyPackages(options, plugins, plan, referencePlugins);
1016
- plan.runtime.configApplyPackages = commands.hook;
1017
404
  const profiles = configApplyRequestedTargets(plan).map((target) => ({
1018
405
  pluginName: target.pluginId.split('/').at(-1), scope: target.scope, platform: target.agent,
1019
406
  }));
1020
- // A package has platform=null and always consumes the public common profile.
1021
- profiles.push(...commands.packages.map((target) => ({ pluginName: target.producer.pluginName,
1022
- scope: target.producer.scope, platform: undefined })));
407
+ for (const { target, candidate } of entries) {
408
+ for (const platform of candidate?.runtimeConfigEvidence.keys() ?? []) {
409
+ profiles.push({ pluginName: target.producer.pluginName, scope: 'user', platform });
410
+ }
411
+ if (candidate?.routeConfigEvidence)
412
+ profiles.push({ pluginName: target.producer.pluginName, scope: 'user' });
413
+ }
1023
414
  const references = await collectPluginConfigReferenceEvidence({ plugin: options.plugin, plugins: referencePlugins,
1024
415
  profiles, cwd: options.cwd, env: options.env });
1025
416
  const authorization = await resolveConfigPreApplyAuthorization({
@@ -1035,17 +426,25 @@ export async function preparePluginConfigApply(options) {
1035
426
  ];
1036
427
  const preApplyAuthorization = [...new Map([...authorization.targets, ...portableAuthorization(plan)]
1037
428
  .map((target) => [[target.pluginId, target.platform, target.scope].join('\0'), target])).values()];
429
+ const commandPackageEvidence = entries.map(({ evidence }) => evidence);
1038
430
  return { plan, retainedLegacyTargets, commandPackages: commands.packages, commandDiscoveryErrors: commands.errors,
431
+ commandPackageEvidence, commandPackageReviews: commandPackageEvidence.flatMap(({ review }) => review ? [review] : []),
1039
432
  preApplyAuthorization,
1040
- evidence: { recovery: describeRecoveryPlan(plan), references, commands: commands.evidence,
433
+ evidence: { recovery: describeRecoveryPlan(plan), references, commandPackageEvidence,
1041
434
  preApplyAuthorization, retainedLegacyTargets } };
1042
435
  }
1043
436
  catch (error) {
1044
- await disposePluginConfigApply(plan);
437
+ if (plan)
438
+ await disposePluginConfigApply(plan);
439
+ else
440
+ await cleanup();
1045
441
  throw error;
1046
442
  }
1047
443
  }
1048
444
  export async function disposePluginConfigApply(plan) {
445
+ const cleanup = commandCandidateCleanup.get(plan);
446
+ commandCandidateCleanup.delete(plan);
447
+ await cleanup?.();
1049
448
  for (const child of plan.joint?.children ?? [])
1050
449
  await disposePluginConfigApply(child);
1051
450
  await plan.context.dispose();
@@ -1091,10 +490,17 @@ export async function applyPluginConfig(options) {
1091
490
  let prepared;
1092
491
  try {
1093
492
  const { executeRecovery } = await import('../recovery/coordinator.js');
1094
- prepared = await preparePluginConfigApply({ ...options, awHomeMutationToken: token });
493
+ const expectedCommands = options.expectedCommandPackageEvidence
494
+ ?? options.expectedEvidence?.commandPackageEvidence;
495
+ prepared = await preparePluginConfigApply({ ...options, awHomeMutationToken: token,
496
+ expectedCommandPackageEvidence: expectedCommands });
1095
497
  if (options.expectedEvidence !== undefined
1096
498
  && JSON.stringify(options.expectedEvidence) !== JSON.stringify(prepared.evidence)) {
1097
- throw Object.assign(new Error('operationPlanStale: Configuration apply inputs changed. Prepare a new Review.'), { code: 'operationPlanStale' });
499
+ throw Object.assign(new Error('Configuration apply inputs changed. Prepare a new Review.'), { code: 'operationReviewStale' });
500
+ }
501
+ const authorizedEffects = new Set(options.expectedHostPermissionEffects?.map((effect) => JSON.stringify(effect)));
502
+ if (recoveryHostPermissionEffects(prepared.plan).some((effect) => !authorizedEffects.has(JSON.stringify(effect)))) {
503
+ throw Object.assign(new Error('Host permission effects changed after Review. Prepare a new Review.'), { code: 'operationReviewStale' });
1098
504
  }
1099
505
  const authorization = prepared.preApplyAuthorization;
1100
506
  if (authorization.length && !preApplyAuthorizationIsConfirmed({ required: authorization,
@@ -1122,12 +528,11 @@ export async function applyPluginConfig(options) {
1122
528
  });
1123
529
  const retainedLegacyTargets = prepared.retainedLegacyTargets.filter((target) => !receipt.targetResults.some((result) => (target.pluginId ? result.pluginId === target.pluginId : result.pluginId.split('/').at(-1) === target.pluginName)
1124
530
  && result.agent === target.platform && result.scope === target.scope));
1125
- prepared = undefined;
1126
531
  const ok = receipt.ok && discoveryErrors.length === 0;
1127
532
  const errors = [...discoveryErrors, ...receipt.blockers, ...receipt.errors].map((error) => ({
1128
533
  stage: 'stage' in error ? error.stage : 'apply', code: error.code, message: error.message,
1129
534
  }));
1130
- const diagnostics = projectDeploymentNotices(receipt.targetResults);
535
+ const diagnostics = [...projectDeploymentNotices(receipt.targetResults), ...projectRelatedProjectPermissionFailures(receipt.targetResults)];
1131
536
  const apply = {
1132
537
  state: ok ? 'succeeded' : 'partial',
1133
538
  targetResults: [...receipt.targetResults.filter((target) => target.satisfaction !== 'unsupported' && target.satisfaction !== 'excluded').map((target) => ({
@@ -1157,14 +562,20 @@ export async function applyPluginConfig(options) {
1157
562
  otherProjectsMayRequireSync: true };
1158
563
  }
1159
564
  catch (error) {
1160
- if (options.rebuildRuntime?.signal?.aborted || error instanceof Error && error.name === 'AbortError'
565
+ if (recoveryInterruptionCode(error, options.rebuildRuntime?.signal)
1161
566
  || readSafeOperationError(error))
1162
567
  throw error;
1163
568
  const apply = unavailableApply('targetDiscoveryFailed', 'targetDiscovery');
1164
569
  const code = error?.code;
570
+ if (code === 'sourceActiveUnavailable' || code === 'pluginUnavailable') {
571
+ return { configWrite: 'notStarted', overallState: 'partial', apply: {
572
+ ...unavailableApply('sourceUnavailable', 'source'),
573
+ error: { stage: 'source', code, message: error instanceof Error ? error.message : 'The Active Catalog plugin is unavailable.' },
574
+ }, otherProjectsMayRequireSync: true };
575
+ }
1165
576
  if (typeof code === 'string')
1166
577
  apply.error = { stage: 'apply', code,
1167
- message: code === 'operationPlanStale' ? 'Configuration apply inputs changed. Prepare a new Review.'
578
+ message: code === 'operationReviewStale' ? 'Configuration apply inputs changed. Prepare a new Review.'
1168
579
  : 'The existing outputs cannot be refreshed with the current authorization.' };
1169
580
  return { configWrite: 'notStarted', overallState: 'partial', apply, otherProjectsMayRequireSync: true };
1170
581
  }
@@ -1236,29 +647,37 @@ async function prepareConfigMutationApplySelection(options) {
1236
647
  return undefined;
1237
648
  let prepared;
1238
649
  try {
1239
- prepared = await preparePluginConfigApply({ ...options, plugin: options.plugin });
650
+ prepared = await preparePluginConfigApply({ ...options, plugin: options.plugin }, { inspectOnly: true });
1240
651
  const requestedTargets = configApplyRequestedTargets(prepared.plan);
1241
- if (requestedTargets.some((target) => target.agent === 'generic'))
1242
- return undefined;
1243
- const visibleTargets = requestedTargets.map((target) => ({
1244
- pluginName: target.pluginId.split('/').at(-1), pluginId: target.pluginId,
1245
- platform: target.agent, scope: target.scope,
1246
- }));
1247
- if (!visibleTargets.length && !prepared.commandPackages.length && !prepared.commandDiscoveryErrors.length) {
1248
- if (prepared.plan.blockExecution || prepared.plan.receipt.blockers.length || prepared.plan.receipt.errors.length)
1249
- return undefined;
1250
- return { skipReason: 'noVisibleTarget' };
1251
- }
652
+ const hasGeneric = requestedTargets.some((target) => target.agent === 'generic');
653
+ const visibleTargets = requestedTargets.flatMap((target) => target.agent === 'generic' ? [] : [{
654
+ pluginName: target.pluginId.split('/').at(-1), pluginId: target.pluginId,
655
+ platform: target.agent, scope: target.scope,
656
+ }]);
1252
657
  const impact = await analyzePluginConfigMutationImpact({ plugin: options.plugin, scope: options.context ?? options.scope,
1253
658
  platform: options.platform, cwd: options.cwd, env: options.env, visibleTargets,
1254
659
  commandDiscovery: { packages: prepared.commandPackages, errors: prepared.commandDiscoveryErrors },
1255
660
  referencePlugins: options.rebuildRuntime?.referencePlugins,
1256
661
  mutation: 'request' in options ? { kind: 'patch', ...options.request } : { kind: 'reset' } });
1257
- return { applyTargets: impact.affectedTargets,
662
+ if (options.expectedCommandPackageEvidence) {
663
+ const referencePlugins = prepared.plan.runtime.referencePlugins ?? [];
664
+ const plugins = await resolvePluginConfigReferenceConsumers({ plugin: options.plugin, env: options.env, plugins: referencePlugins });
665
+ const entries = await prepareConfigCommandPackages({ ...options, plugin: options.plugin,
666
+ mutation: 'request' in options ? { kind: 'patch', ...options.request } : { kind: 'reset' } }, impact.affectedCommandPackages, plugins, referencePlugins);
667
+ await Promise.all(entries.map(({ candidate }) => candidate?.cleanup()));
668
+ }
669
+ if (!hasGeneric && !visibleTargets.length && !prepared.commandPackages.length && !prepared.commandDiscoveryErrors.length) {
670
+ if (prepared.plan.blockExecution || prepared.plan.receipt.blockers.length || prepared.plan.receipt.errors.length)
671
+ return undefined;
672
+ return { skipReason: 'noVisibleTarget' };
673
+ }
674
+ return { applyTargets: hasGeneric ? undefined : impact.affectedTargets,
1258
675
  applyCommandPackages: impact.affectedCommandPackages.map((target) => target.packageId),
1259
- ...(impact.noEffectiveChange ? { skipReason: 'noEffectiveConfigChange' } : {}) };
676
+ ...(!hasGeneric && impact.noEffectiveChange ? { skipReason: 'noEffectiveConfigChange' } : {}) };
1260
677
  }
1261
- catch {
678
+ catch (error) {
679
+ if (error?.code === 'operationReviewStale' || recoveryInterruptionCode(error, options.rebuildRuntime?.signal))
680
+ throw error;
1262
681
  // A failed output discovery must not prevent a valid configuration save.
1263
682
  return undefined;
1264
683
  }
@@ -1440,8 +859,11 @@ export async function resetPluginConfigWithHelper(options) {
1440
859
  apply: false, awHomeMutationToken, rebuildRuntime: { ...options.rebuildRuntime, awHomeMutationToken } });
1441
860
  if (options.apply !== true)
1442
861
  return saved;
1443
- if (!options.plugin)
1444
- return { ...saved, overallState: 'partial', apply: unavailableApply('sourceUnavailable', 'source') };
862
+ if (!options.plugin) {
863
+ const apply = unavailableApply('sourceUnavailable', 'source');
864
+ const cause = configActiveAvailabilityError(options.pluginError);
865
+ return { ...saved, overallState: 'partial', apply: cause ? { ...apply, error: { stage: 'source', ...cause } } : apply };
866
+ }
1445
867
  if (saved.apply.state === 'skipped' && saved.apply.reason === 'noConfigChange')
1446
868
  return saved;
1447
869
  if (selection?.skipReason)