@lesliechan721/aw 0.1.0-beta.83 → 0.1.0-beta.84

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 (179) hide show
  1. package/dist/authoring/assets/aw-runtime-config.mjs +1 -1
  2. package/dist/authoring/assets/aw-runtime-config.mjs.map +1 -1
  3. package/dist/src/commands/console.js +1 -0
  4. package/dist/src/commands/console.js.map +1 -1
  5. package/dist/src/commands/intent-command.d.ts +1 -0
  6. package/dist/src/commands/intent-command.js +6 -2
  7. package/dist/src/commands/intent-command.js.map +1 -1
  8. package/dist/src/commands/plugin-capabilities.js +3 -3
  9. package/dist/src/commands/plugin-capabilities.js.map +1 -1
  10. package/dist/src/commands/public-lifecycle-result.d.ts +11 -5
  11. package/dist/src/commands/public-lifecycle-result.js +131 -46
  12. package/dist/src/commands/public-lifecycle-result.js.map +1 -1
  13. package/dist/src/commands/public-lifecycle.d.ts +1 -2
  14. package/dist/src/commands/public-lifecycle.js +56 -34
  15. package/dist/src/commands/public-lifecycle.js.map +1 -1
  16. package/dist/src/commands/public-plugin-query.js +28 -11
  17. package/dist/src/commands/public-plugin-query.js.map +1 -1
  18. package/dist/src/commands/rebuild-command.d.ts +13 -3
  19. package/dist/src/commands/rebuild-command.js +647 -286
  20. package/dist/src/commands/rebuild-command.js.map +1 -1
  21. package/dist/src/commands/rebuild-integration.d.ts +5 -2
  22. package/dist/src/commands/rebuild-integration.js +55 -29
  23. package/dist/src/commands/rebuild-integration.js.map +1 -1
  24. package/dist/src/commands/rebuild-operations.d.ts +1 -0
  25. package/dist/src/commands/rebuild-operations.js +23 -4
  26. package/dist/src/commands/rebuild-operations.js.map +1 -1
  27. package/dist/src/commands/rebuild-platform-integration.d.ts +13 -3
  28. package/dist/src/commands/rebuild-platform-integration.js +229 -133
  29. package/dist/src/commands/rebuild-platform-integration.js.map +1 -1
  30. package/dist/src/index.js +105 -50
  31. package/dist/src/index.js.map +1 -1
  32. package/dist/src/output/public-result.d.ts +2 -0
  33. package/dist/src/output/public-result.js +43 -6
  34. package/dist/src/output/public-result.js.map +1 -1
  35. package/dist/src/output/rebuild-progress.d.ts +3 -0
  36. package/dist/src/output/rebuild-progress.js +12 -2
  37. package/dist/src/output/rebuild-progress.js.map +1 -1
  38. package/dist/src/output/receipt-projection.js +55 -18
  39. package/dist/src/output/receipt-projection.js.map +1 -1
  40. package/dist/src/output/skill-invocation-notices.d.ts +16 -0
  41. package/dist/src/output/skill-invocation-notices.js +48 -0
  42. package/dist/src/output/skill-invocation-notices.js.map +1 -0
  43. package/dist/src/platforms/capabilities.d.ts +2 -0
  44. package/dist/src/platforms/capabilities.js +73 -34
  45. package/dist/src/platforms/capabilities.js.map +1 -1
  46. package/dist/src/platforms/contracts.d.ts +9 -9
  47. package/dist/src/platforms/discovery.d.ts +0 -7
  48. package/dist/src/platforms/discovery.js +13 -53
  49. package/dist/src/platforms/discovery.js.map +1 -1
  50. package/dist/src/platforms/inspection-native.js +1 -80
  51. package/dist/src/platforms/inspection-native.js.map +1 -1
  52. package/dist/src/platforms/inspection-query.d.ts +2 -3
  53. package/dist/src/platforms/inspection-query.js +7 -18
  54. package/dist/src/platforms/inspection-query.js.map +1 -1
  55. package/dist/src/platforms/inspection.js +2 -2
  56. package/dist/src/platforms/inspection.js.map +1 -1
  57. package/dist/src/platforms/layout.js +1 -5
  58. package/dist/src/platforms/layout.js.map +1 -1
  59. package/dist/src/platforms/lifecycle-native-services.d.ts +1 -1
  60. package/dist/src/platforms/lifecycle-native-services.js +14 -14
  61. package/dist/src/platforms/lifecycle-native-services.js.map +1 -1
  62. package/dist/src/platforms/lifecycle-native.js +4 -88
  63. package/dist/src/platforms/lifecycle-native.js.map +1 -1
  64. package/dist/src/platforms/lifecycle.js +56 -56
  65. package/dist/src/platforms/lifecycle.js.map +1 -1
  66. package/dist/src/platforms/projection-code-extension.js +7 -3
  67. package/dist/src/platforms/projection-code-extension.js.map +1 -1
  68. package/dist/src/platforms/projection.d.ts +3 -0
  69. package/dist/src/platforms/projection.js +86 -54
  70. package/dist/src/platforms/projection.js.map +1 -1
  71. package/dist/src/portable/materializer.js +2 -2
  72. package/dist/src/portable/materializer.js.map +1 -1
  73. package/dist/src/portable/recovery.d.ts +29 -3
  74. package/dist/src/portable/recovery.js +220 -78
  75. package/dist/src/portable/recovery.js.map +1 -1
  76. package/dist/src/recovery/coordinator.d.ts +18 -4
  77. package/dist/src/recovery/coordinator.js +357 -165
  78. package/dist/src/recovery/coordinator.js.map +1 -1
  79. package/dist/src/recovery/install-concurrency.d.ts +48 -0
  80. package/dist/src/recovery/install-concurrency.js +195 -0
  81. package/dist/src/recovery/install-concurrency.js.map +1 -0
  82. package/dist/src/recovery/interruption.d.ts +19 -0
  83. package/dist/src/recovery/interruption.js +43 -0
  84. package/dist/src/recovery/interruption.js.map +1 -0
  85. package/dist/src/recovery/joint-coordinator.d.ts +11 -4
  86. package/dist/src/recovery/joint-coordinator.js +671 -333
  87. package/dist/src/recovery/joint-coordinator.js.map +1 -1
  88. package/dist/src/recovery/joint-demand.d.ts +8 -0
  89. package/dist/src/recovery/joint-demand.js +52 -1
  90. package/dist/src/recovery/joint-demand.js.map +1 -1
  91. package/dist/src/recovery/joint-install-execution.d.ts +19 -0
  92. package/dist/src/recovery/joint-install-execution.js +307 -0
  93. package/dist/src/recovery/joint-install-execution.js.map +1 -0
  94. package/dist/src/recovery/joint-install-native-rebase.d.ts +4 -0
  95. package/dist/src/recovery/joint-install-native-rebase.js +67 -0
  96. package/dist/src/recovery/joint-install-native-rebase.js.map +1 -0
  97. package/dist/src/recovery/receipt.d.ts +20 -0
  98. package/dist/src/recovery/receipt.js +67 -1
  99. package/dist/src/recovery/receipt.js.map +1 -1
  100. package/dist/src/recovery/retirement.js +1 -1
  101. package/dist/src/recovery/retirement.js.map +1 -1
  102. package/dist/src/recovery/status.js +26 -27
  103. package/dist/src/recovery/status.js.map +1 -1
  104. package/dist/src/review/platform-profile.d.ts +4 -1
  105. package/dist/src/review/platform-profile.js +13 -4
  106. package/dist/src/review/platform-profile.js.map +1 -1
  107. package/dist/src/review/skill-materialization.d.ts +1 -0
  108. package/dist/src/review/skill-materialization.js +28 -16
  109. package/dist/src/review/skill-materialization.js.map +1 -1
  110. package/dist/src/review/source-binding.js +6 -4
  111. package/dist/src/review/source-binding.js.map +1 -1
  112. package/dist/src/tui/console-app-v4.d.ts +1 -1
  113. package/dist/src/tui/console-app-v4.js +137 -57
  114. package/dist/src/tui/console-app-v4.js.map +1 -1
  115. package/dist/src/tui/controller-runtime.js +45 -9
  116. package/dist/src/tui/controller-runtime.js.map +1 -1
  117. package/dist/src/tui/controller.d.ts +13 -4
  118. package/dist/src/tui/controller.js +233 -102
  119. package/dist/src/tui/controller.js.map +1 -1
  120. package/dist/src/tui/deployment-view.js +6 -1
  121. package/dist/src/tui/deployment-view.js.map +1 -1
  122. package/dist/src/tui/diagnostic-projection.d.ts +4 -2
  123. package/dist/src/tui/diagnostic-projection.js +40 -4
  124. package/dist/src/tui/diagnostic-projection.js.map +1 -1
  125. package/dist/src/tui/operation-diagnostic-screens.d.ts +1 -1
  126. package/dist/src/tui/operation-diagnostic-screens.js +3 -1
  127. package/dist/src/tui/operation-diagnostic-screens.js.map +1 -1
  128. package/dist/src/tui/operation-history.d.ts +6 -3
  129. package/dist/src/tui/operation-history.js +15 -2
  130. package/dist/src/tui/operation-history.js.map +1 -1
  131. package/dist/src/tui/scoped-flow.d.ts +3 -1
  132. package/dist/src/tui/scoped-flow.js +99 -1
  133. package/dist/src/tui/scoped-flow.js.map +1 -1
  134. package/dist/src/tui/session-console-app.d.ts +2 -0
  135. package/dist/src/tui/session-console-app.js +11 -0
  136. package/dist/src/tui/session-console-app.js.map +1 -1
  137. package/dist/src/types.d.ts +8 -1
  138. package/dist/src/types.js.map +1 -1
  139. package/dist/src/utils/aw-home-mutation-lock.js +2 -1
  140. package/dist/src/utils/aw-home-mutation-lock.js.map +1 -1
  141. package/dist/src/utils/catalog-source-references.js +2 -14
  142. package/dist/src/utils/catalog-source-references.js.map +1 -1
  143. package/dist/src/utils/component-resources.js +1 -1
  144. package/dist/src/utils/component-resources.js.map +1 -1
  145. package/dist/src/utils/managed-command-materialization.d.ts +2 -1
  146. package/dist/src/utils/managed-command-materialization.js +3 -3
  147. package/dist/src/utils/managed-command-materialization.js.map +1 -1
  148. package/dist/src/utils/managed-command-store.d.ts +6 -0
  149. package/dist/src/utils/managed-command-store.js +90 -18
  150. package/dist/src/utils/managed-command-store.js.map +1 -1
  151. package/dist/src/utils/multi-source-catalog.d.ts +2 -0
  152. package/dist/src/utils/multi-source-catalog.js +3 -2
  153. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  154. package/dist/src/utils/native-cli.d.ts +0 -19
  155. package/dist/src/utils/native-cli.js +2 -42
  156. package/dist/src/utils/native-cli.js.map +1 -1
  157. package/dist/src/utils/ownership.js +1 -1
  158. package/dist/src/utils/ownership.js.map +1 -1
  159. package/dist/src/utils/platform-empty-state.d.ts +1 -3
  160. package/dist/src/utils/platform-empty-state.js +1 -6
  161. package/dist/src/utils/platform-empty-state.js.map +1 -1
  162. package/dist/src/utils/plugin-config-write.d.ts +8 -0
  163. package/dist/src/utils/plugin-config-write.js +89 -25
  164. package/dist/src/utils/plugin-config-write.js.map +1 -1
  165. package/dist/src/utils/plugin-scripts.js +5 -0
  166. package/dist/src/utils/plugin-scripts.js.map +1 -1
  167. package/dist/src/utils/skill-invocation-warning.d.ts +15 -0
  168. package/dist/src/utils/skill-invocation-warning.js +42 -0
  169. package/dist/src/utils/skill-invocation-warning.js.map +1 -0
  170. package/package.json +3 -3
  171. package/dist/src/output/native-consent.d.ts +0 -2
  172. package/dist/src/output/native-consent.js +0 -5
  173. package/dist/src/output/native-consent.js.map +0 -1
  174. package/dist/src/platforms/gemini-activation.d.ts +0 -36
  175. package/dist/src/platforms/gemini-activation.js +0 -331
  176. package/dist/src/platforms/gemini-activation.js.map +0 -1
  177. package/dist/src/platforms/gemini-consent.d.ts +0 -8
  178. package/dist/src/platforms/gemini-consent.js +0 -81
  179. package/dist/src/platforms/gemini-consent.js.map +0 -1
@@ -17,10 +17,16 @@ import { CatalogPreparationReadScope } from '../utils/catalog-operation-context.
17
17
  import { readCatalogGenerationState } from '../utils/catalog-generation-state.js';
18
18
  import { readCatalogSourcesConfigSnapshot } from '../utils/catalog-sources.js';
19
19
  import { parsePluginId } from '../utils/multi-source-catalog.js';
20
- import { readDemand } from './demand.js';
21
- import { canReuseProviderAcrossScopes, readJointDemand, deriveJointDemand, deriveSharedReferenceView } from './joint-demand.js';
22
- import { prepareScopedRecovery, executeScopedRecovery, executeRecoveryPreApply, refreshRecoveryNativePreviews, describeRecoveryPlan, errorCode } from './coordinator.js';
20
+ import { readDemand, resolveDelivery } from './demand.js';
21
+ import { hasSharedUserPackage } from '../platforms/layout.js';
22
+ import { preparePortableRecovery } from '../portable/recovery.js';
23
+ import { canReuseProviderAcrossScopes, readJointDemand, deriveJointDemand, deriveSharedReferenceView, indexJointDependencies } from './joint-demand.js';
24
+ import { checkFootprints, prepareScopedRecovery, executeScopedRecovery, executeRecoveryPreApply, refreshRecoveryNativePreviews, describeRecoveryPlan, errorCode } from './coordinator.js';
23
25
  import { isTargetObservationReadError, readScopedRecoveryStatus, readRecoveryStatus } from './status.js';
26
+ import { recoveryRetryDispositions, recoveryStatusContext, retriesFromRequestedRoots } from './receipt.js';
27
+ import { limitInstallNativeRunner, mapInstallReads } from './install-concurrency.js';
28
+ import { executeJointInstall } from './joint-install-execution.js';
29
+ import { RecoveryInterruptedError, recoveryInterruptionCode } from './interruption.js';
24
30
  import { measureRecoveryPerformanceStage, recordRecoveryPerformanceStage } from './performance.js';
25
31
  import { resolvePluginMetaDependencyClosure } from '../utils/plugin-dependencies.js';
26
32
  const diagnostic = (code, message = code) => ({ code, message });
@@ -31,6 +37,9 @@ function intentReceipt(observation) {
31
37
  ...('digest' in observation ? { digest: observation.digest } : {}),
32
38
  };
33
39
  }
40
+ function isInstallBatch(command) {
41
+ return command === 'install' || command === 'sync';
42
+ }
34
43
  const observationEvidence = (value) => 'rawDigest' in value ? `${value.state}:${value.rawDigest}` : value.state;
35
44
  function snapshotEvidence(snapshot) {
36
45
  return JSON.stringify([observationEvidence(snapshot.user.intent),
@@ -42,42 +51,115 @@ function asObservation(value) {
42
51
  const rawBytes = Buffer.from(JSON.stringify(value));
43
52
  return { state: 'valid', value, digest: calculateIntentDigest(value), rawDigest: calculateIntentDigest(value), rawBytes };
44
53
  }
54
+ function targetKey(target) {
55
+ return [target.pluginId, target.agent, target.scope].join('\0');
56
+ }
57
+ function matchesExactContribution(placement, contribution, exact, reaches) {
58
+ return placement.target === exact.agent && contribution.scope === exact.scope
59
+ && reaches(contribution.root, exact.pluginId) && reaches(exact.pluginId, placement.pluginId);
60
+ }
61
+ function useDeclaredRetryRoots(receipt) {
62
+ const status = `aw plugin status --context ${recoveryStatusContext(receipt)} --json`;
63
+ const results = new Map(receipt.targetResults.map((target) => [targetKey(target), target]));
64
+ const pending = new Set(receipt.remainingTargets.map(targetKey));
65
+ const revise = (action) => {
66
+ if (/^aw plugin status --context (?:user|project) --json$/u.test(action))
67
+ return [status];
68
+ // Only rewrite the known command at the end of a backend action. Paths and instructions preceding it stay display text.
69
+ const match = /aw plugin sync (\S+) (?:--context (user|project) --target ([\w-]+)|--target ([\w-]+) --context (user|project))((?: --(?:rebuild|yes))*)([.。]?)$/u.exec(action);
70
+ if (!match)
71
+ return [action];
72
+ const prefix = action.slice(0, match.index);
73
+ if (prefix && !/(?:^|\s)run $|然后重试 $/iu.test(prefix))
74
+ return [action];
75
+ const context = prefix.replace(/(?:then run |run |然后重试 )$/iu, '').trimEnd();
76
+ const target = results.get([match[1], match[3] ?? match[4], match[2] ?? match[5]].join('\0'));
77
+ if (!target || !pending.has(targetKey(target)))
78
+ return context ? [context] : [];
79
+ const dispositions = recoveryRetryDispositions(receipt, [target]);
80
+ if (!dispositions.length)
81
+ return [context ? `${context} ${status}` : status];
82
+ return dispositions.map((root) => {
83
+ if (root.kind === 'exact-project') {
84
+ const exact = `请在 TUI 当前项目中选择 ${root.pluginId} 的 ${root.agent} 位置重新检查。`;
85
+ return context ? `${context} ${exact}` : exact;
86
+ }
87
+ const command = `aw plugin sync ${root.pluginId} --context ${root.scope} --target ${root.agent}${match[6]}`;
88
+ return prefix && prefix !== 'run ' ? `${prefix}${command}${match[7]}` : command;
89
+ });
90
+ };
91
+ for (const target of receipt.targetResults) {
92
+ if (target.recoveryActions)
93
+ target.recoveryActions = [...new Set(target.recoveryActions.flatMap(revise))];
94
+ }
95
+ receipt.recoveryActions = [...new Set(receipt.recoveryActions.flatMap(revise))];
96
+ }
45
97
  function mergeReceipts(plan, receipts) {
98
+ const joint = plan.joint;
46
99
  const receipt = structuredClone(plan.receipt);
47
100
  receipt.targetResults = receipts.flatMap((item) => item.targetResults);
48
- for (const root of plan.joint?.demand.roots ?? []) {
49
- if (!receipt.requestedRoots.includes(root.pluginId) || !receipt.selection.agents.includes(root.target)
50
- || !['unsupported', 'excluded'].includes(root.state))
51
- continue;
52
- receipt.targetResults.push({ pluginId: root.pluginId, agent: root.target, scope: root.scope,
53
- requirementScope: root.scope, delivery: null, execution: 'no-op', observation: 'verified', content: 'satisfied',
54
- satisfaction: root.state, requiredBy: [root.pluginId], blockers: [],
55
- ...(root.reasons?.length ? { reasons: root.reasons } : {}) });
56
- }
57
- receipt.requestedTargets = receipt.targetResults.map(({ pluginId, agent, scope, delivery }) => ({ pluginId, agent, scope, delivery }));
101
+ receipt.remainingTargets = receipts.flatMap((item) => item.remainingTargets);
102
+ const actions = receipts.flatMap((item) => item.recoveryActions);
103
+ const reviewedOrder = joint.targetOrder;
104
+ const byPosition = (a, b) => (reviewedOrder?.get(targetKey(a)) ?? Number.MAX_SAFE_INTEGER) - (reviewedOrder?.get(targetKey(b)) ?? Number.MAX_SAFE_INTEGER);
58
105
  for (const target of receipt.targetResults) {
59
- const placements = plan.joint?.demand.placements ?? [];
60
- const activationOnly = plan.joint?.children.some((child) => child.options.nativeActivationOnlyTargets?.some((item) => item.pluginId === target.pluginId && item.platform === target.agent && item.scope === target.scope));
106
+ const placements = joint.demand.placements;
107
+ const activationOnly = joint.children.some((child) => child.options.nativeActivationOnlyTargets?.some((item) => item.pluginId === target.pluginId && item.platform === target.agent && item.scope === target.scope));
61
108
  const placement = placements.find((item) => item.pluginId === target.pluginId && item.target === target.agent && item.scope === target.scope)
62
109
  ?? (target.scope === 'project' && activationOnly ? placements.find((item) => item.pluginId === target.pluginId && item.target === target.agent && item.scope === 'user'
63
110
  && item.contributions.some((contribution) => contribution.scope === target.scope)) : undefined);
64
111
  if (placement) {
65
112
  const contributions = placement.scope === target.scope ? placement.contributions
66
113
  : placement.contributions.filter((item) => item.scope === target.scope);
114
+ const selectedContributions = retriesFromRequestedRoots(receipt)
115
+ ? contributions.filter((item) => joint.selectedContributions.get(placement)?.includes(item)) : contributions;
67
116
  target.requiredBy = [...new Set(contributions.map((item) => item.root))];
68
117
  target.providerScope = placement.scope;
69
- if (placement.scope !== target.scope) {
118
+ if (plan.command !== 'uninstall' || placement.scope !== target.scope)
119
+ target.relation = selectedContributions.some((item) => item.root === target.pluginId && item.scope === target.scope) ? 'root' : 'dependency';
120
+ if (target.relation === 'dependency')
121
+ target.contributions = selectedContributions;
122
+ if (placement.scope !== target.scope)
70
123
  target.requirementScope = target.scope;
71
- target.relation = contributions.some((item) => item.root === target.pluginId) ? 'root' : 'dependency';
72
- }
73
124
  }
74
125
  }
75
- receipt.remainingTargets = receipts.flatMap((item) => item.remainingTargets);
126
+ const executed = new Set(receipt.targetResults.map(targetKey));
127
+ const skipped = [];
128
+ for (const root of joint.unplacedRoots) {
129
+ const position = { pluginId: root.pluginId, agent: root.target, scope: root.scope };
130
+ if (executed.has(targetKey(position)))
131
+ continue;
132
+ const common = { ...position, relation: 'root', requiredBy: [root.pluginId], requirementScope: root.scope,
133
+ blockers: root.blockers, ...(root.reasons?.length ? { reasons: root.reasons } : {}) };
134
+ if (root.state === 'excluded' || root.state === 'unsupported') {
135
+ const results = plan.options.exactTargets ? receipt.targetResults : skipped;
136
+ results.push({ ...common, delivery: null, execution: 'no-op', observation: 'verified',
137
+ content: 'satisfied', satisfaction: root.state });
138
+ continue;
139
+ }
140
+ const plugin = joint.snapshot[root.scope]?.roots?.find((item) => item.pluginId === root.pluginId)?.plugin;
141
+ const delivery = plugin ? resolveDelivery(plugin.manifest, root.target, root.scope) ?? null : null;
142
+ const recoveryActions = [
143
+ ...root.blockers.filter((blocker) => blocker.code === 'dependencyExcluded' && blocker.pluginId)
144
+ .map((blocker) => `aw target include ${blocker.pluginId} --target ${root.target}`),
145
+ `aw plugin sync ${root.pluginId} --context ${root.scope} --target ${root.target}`,
146
+ ];
147
+ receipt.targetResults.push({ ...common, delivery, execution: 'not-run', observation: 'unknown',
148
+ content: 'unknown', satisfaction: 'unknown', recoveryActions });
149
+ receipt.remainingTargets.push({ ...position, delivery });
150
+ actions.push(...recoveryActions);
151
+ }
152
+ if (reviewedOrder)
153
+ receipt.targetResults.sort(byPosition);
154
+ receipt.targetResults.push(...skipped);
155
+ receipt.requestedTargets = receipt.targetResults.map(({ pluginId, agent, scope, delivery }) => ({ pluginId, agent, scope, delivery }));
156
+ if (reviewedOrder)
157
+ receipt.remainingTargets.sort(byPosition);
76
158
  receipt.errors = [...receipt.blockers, ...receipts.flatMap((item) => [...item.blockers, ...item.errors])];
77
159
  receipt.outputsMayHaveChanged = receipts.some((item) => item.outputsMayHaveChanged);
78
160
  receipt.commandResults = receipts.flatMap((item) => item.commandResults ?? []);
79
161
  receipt.nativeToolChanges = receipts.flatMap((item) => item.nativeToolChanges ?? []);
80
- receipt.recoveryActions = [...new Set(receipts.flatMap((item) => item.recoveryActions))];
162
+ receipt.recoveryActions = [...new Set(actions)];
81
163
  receipt.ok = receipt.blockers.length === 0 && receipts.every((item) => item.ok);
82
164
  return receipt;
83
165
  }
@@ -100,9 +182,37 @@ function finalStatusReadFailure(status, receipt) {
100
182
  }
101
183
  return undefined;
102
184
  }
103
- async function readJointPreparation(command, options, locked = false) {
104
- const catalogReadScope = command === 'install' && (locked || !options.catalogOperationContext)
105
- ? new CatalogPreparationReadScope(options) : undefined;
185
+ function blockedBeforeDeployment(plan, blocker = diagnostic('operationReviewStale'), savedState) {
186
+ if (!isInstallBatch(plan.command)) {
187
+ plan.receipt.blockers.push(blocker);
188
+ return mergeReceipts(plan, []);
189
+ }
190
+ const receipt = structuredClone(plan.receipt);
191
+ receipt.ok = false;
192
+ receipt.blockers.push(blocker);
193
+ receipt.errors = [...receipt.blockers];
194
+ receipt.commandResults = [];
195
+ receipt.nativeToolChanges = [];
196
+ receipt.remainingTargets = [];
197
+ receipt.recoveryActions = savedState
198
+ ? [`aw plugin status --context ${recoveryStatusContext(receipt)} --json`,
199
+ `请核对当前${savedState === 'intent' ? '插件声明' : '本机 Agent 偏好'}。确认需要的范围后重新准备本次操作。`]
200
+ : ['确认依据已改变,请重新准备本次操作。'];
201
+ if (savedState)
202
+ receipt.unconfirmedSavedState = savedState;
203
+ receipt.targetResults = receipt.targetResults.map((target) => {
204
+ if (target.satisfaction === 'excluded' || target.satisfaction === 'unsupported')
205
+ return target;
206
+ const { pluginId, agent, scope, delivery, relation, requiredBy, requirementScope, providerScope } = target;
207
+ receipt.remainingTargets.push({ pluginId, agent, scope, delivery });
208
+ return { pluginId, agent, scope, delivery, relation, requiredBy, requirementScope, providerScope,
209
+ execution: 'not-run', observation: 'unknown', content: 'unknown', satisfaction: 'unknown', blockers: [blocker] };
210
+ });
211
+ return receipt;
212
+ }
213
+ async function readJointPreparation(command, options, locked = false, suppliedReads) {
214
+ const catalogReadScope = isInstallBatch(command)
215
+ ? (locked ? undefined : suppliedReads) ?? new CatalogPreparationReadScope(options) : undefined;
106
216
  if (locked && catalogReadScope && options.catalogOperationContext) {
107
217
  // A caller may have reviewed a subset of sources. Rebind just those IDs under
108
218
  // the lock so a changed or removed source makes the existing Review stale.
@@ -111,16 +221,22 @@ async function readJointPreparation(command, options, locked = false) {
111
221
  const sourceIds = configSnapshot.config.sources.map((source) => source.id).filter((id) => reviewed.has(id));
112
222
  options = { ...options, catalogOperationContext: await catalogReadScope.resolve({ configSnapshot, sourceIds }) };
113
223
  }
114
- const snapshot = await readJointDemand({ ...options, catalogReadScope });
115
- return { options, snapshot, catalogReadScope };
224
+ const manifestReads = isInstallBatch(command) ? new Map() : undefined;
225
+ const snapshot = await readJointDemand({ ...options, catalogReadScope, manifestReads });
226
+ return { options, snapshot, catalogReadScope, manifestReads };
116
227
  }
117
228
  /** Complete requirements determine placement before execution selectors are applied. */
118
229
  export async function prepareJointRecovery(command, selectors, options, runtime, preparation) {
119
- runtime = { ...runtime, preparedArtifactRenderResults: runtime.preparedArtifactRenderResults ?? new Map() };
120
- const { snapshot, catalogReadScope } = preparation ?? await readJointPreparation(command, options);
121
- const prepare = (current) => {
122
- const read = (nativeObservationBatch) => prepareJointRecoveryInSession(command, selectors, options, current, snapshot, { catalogReadScope, nativeObservationBatch });
123
- return command === 'install' ? withNativeObservationBatch({ runner: current.nativeCliRunner, signal: options.signal }, read) : read();
230
+ const originalRunner = runtime.nativeCliRunner ?? getDefaultNativeCliRunner();
231
+ runtime = { ...runtime, ...(isInstallBatch(command) ? { nativeCliRunner: limitInstallNativeRunner(originalRunner) } : {}),
232
+ preparedArtifactRenderResults: runtime.preparedArtifactRenderResults ?? new Map() };
233
+ const { snapshot, catalogReadScope, manifestReads } = preparation ?? await readJointPreparation(command, options, false, runtime.catalogReadScope);
234
+ const prepare = async (current) => {
235
+ const read = (nativeObservationBatch) => prepareJointRecoveryInSession(command, selectors, options, current, snapshot, { catalogReadScope, nativeObservationBatch }, manifestReads);
236
+ const plan = isInstallBatch(command)
237
+ ? await withNativeObservationBatch({ runner: current.nativeCliRunner, signal: options.signal }, read) : await read();
238
+ plan.joint.originalNativeRunner = originalRunner;
239
+ return plan;
124
240
  };
125
241
  if (runtime.codexObservationSession)
126
242
  return prepare(runtime);
@@ -131,6 +247,7 @@ export async function prepareJointRecovery(command, selectors, options, runtime,
131
247
  env: observationContext.env, runner: (invocation) => sessionRunner(invocation), manager: runtime.codexManager });
132
248
  try {
133
249
  const plan = await prepare({ ...runtime, codexObservationSession: session });
250
+ plan.joint.bindExecutionSignal = (signal) => { sessionRunner = bindNativeCliRunnerSignal(executionRunner, signal); };
134
251
  const dispose = plan.context.dispose;
135
252
  plan.context.dispose = async () => {
136
253
  try {
@@ -158,10 +275,10 @@ export async function prepareJointRecovery(command, selectors, options, runtime,
158
275
  }
159
276
  finally {
160
277
  // The same observation session also serves confirmed writes, which cannot use preparation cancellation.
161
- sessionRunner = executionRunner;
278
+ sessionRunner = bindNativeCliRunnerSignal(executionRunner, runtime.signal);
162
279
  }
163
280
  }
164
- async function prepareJointRecoveryInSession(command, selectors, { checkInstallCatalog, ...options }, runtime, snapshot, { catalogReadScope, nativeObservationBatch }) {
281
+ async function prepareJointRecoveryInSession(command, selectors, { checkInstallCatalog, ...options }, runtime, snapshot, { catalogReadScope, nativeObservationBatch }, manifestReads) {
165
282
  // Status observes saved requirements, before projecting proposed declarations.
166
283
  // Reuse them only within this preparation; execution reads them again under the lock.
167
284
  const savedDemand = snapshot;
@@ -171,6 +288,9 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
171
288
  let observedStatus;
172
289
  const evidence = snapshotEvidence(snapshot);
173
290
  const scope = options.scope ?? snapshot.context.context;
291
+ if (options.exactTargets && command !== 'uninstall') {
292
+ options = { ...options, exactTargets: options.exactTargets.map((entry) => ({ ...entry, scope: entry.scope ?? scope })) };
293
+ }
174
294
  const observedIntent = (scope === 'project' ? snapshot.project : snapshot.user).intent;
175
295
  if (options.existingOnly) {
176
296
  // Existing owned deployments can be refreshed without converting them into declarations.
@@ -195,7 +315,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
195
315
  value.sources[sourceId] = { logicalIdentity: identity };
196
316
  value.roots.push({ pluginId: item.pluginId });
197
317
  }
198
- snapshot = { ...snapshot, [currentScope]: await readDemand({ ...options, catalogReadScope, preferences: undefined, scope: currentScope, intent: asObservation(value) }) };
318
+ snapshot = { ...snapshot, [currentScope]: await readDemand({ ...options, catalogReadScope, manifestReads, preferences: undefined, scope: currentScope, intent: asObservation(value) }) };
199
319
  }
200
320
  if (snapshot.preferences)
201
321
  snapshot.preferences = { ...snapshot.preferences,
@@ -234,7 +354,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
234
354
  requested = proposed.roots;
235
355
  if (proposed.changed)
236
356
  declaration = { scope, value: proposed.state };
237
- const demand = await readDemand({ ...options, catalogReadScope, preferences: undefined, scope, intent: asObservation(proposed.state) });
357
+ const demand = await readDemand({ ...options, catalogReadScope, manifestReads, preferences: undefined, scope, intent: asObservation(proposed.state) });
238
358
  checkInstallCatalog?.(demand.catalogOperationContext, requested);
239
359
  snapshot = { ...snapshot, [scope]: demand };
240
360
  }
@@ -291,7 +411,6 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
291
411
  }
292
412
  }
293
413
  const demand = deriveJointDemand(snapshot);
294
- errors.push(...demand.errors);
295
414
  const rootIds = [...new Set([...(snapshot.user.roots ?? []), ...(snapshot.project?.roots ?? [])]
296
415
  .map((root) => root.pluginId))];
297
416
  if (command !== 'install' && command !== 'uninstall') {
@@ -304,6 +423,15 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
304
423
  }) : rootIds;
305
424
  }
306
425
  const targets = options.targets ? normalizeAgents(options.targets) : snapshot.preferences?.targets ?? [];
426
+ const unplacedRoots = demand.roots.filter((root) => root.state !== 'required'
427
+ && requested.includes(root.pluginId) && targets.includes(root.target)
428
+ && (!options.exactTargets || options.exactTargets.some((exact) => exact.pluginId === root.pluginId
429
+ && exact.agent === root.target && (exact.scope ?? scope) === root.scope))
430
+ && (command !== 'uninstall' || root.state === 'excluded' || root.state === 'unsupported'));
431
+ // Global diagnostics gate shared preparation. A blocked install root cannot prevent
432
+ // an independent selected root from checking its Project activation.
433
+ const rootErrors = new Set(demand.roots.flatMap((root) => root.blockers));
434
+ errors.push(...demand.errors.filter((error) => command === 'uninstall' || !rootErrors.has(error)));
307
435
  const explicitlyRemoves = (item) => item.scope === scope && requested.includes(item.pluginId) && (!options.exactTargets
308
436
  || options.exactTargets.some((exact) => exact.pluginId === item.pluginId && exact.agent === item.agent
309
437
  && (!exact.scope || exact.scope === item.scope)));
@@ -325,23 +453,37 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
325
453
  && (requested.includes(placement.pluginId) || placement.contributions.some((item) => requested.includes(item.root))))))) {
326
454
  errors.push(diagnostic('invalidExactTargets', '精确重试目标不属于当前请求,请重新检查并选择。'));
327
455
  }
328
- const selected = demand.placements.filter((placement) => targets.includes(placement.target)
329
- && (!options.exactTargets || options.exactTargets.some((exact) => exact.agent === placement.target
330
- && (command === 'uninstall' ? previousDemand.placements.some((previous) => previous.pluginId === placement.pluginId
331
- && previous.target === placement.target && previous.contributions.some((item) => item.path.includes(exact.pluginId)
332
- && (!exact.scope || item.scope === exact.scope)))
333
- : (!exact.scope || placement.contributions.some((item) => item.scope === exact.scope))
334
- && (exact.pluginId === placement.pluginId || placement.contributions.some((item) => item.path.includes(exact.pluginId))))))
335
- && (command === 'uninstall' ? canReuseProviderAcrossScopes(placement.target)
336
- && !(options.force && requested.includes(placement.pluginId))
337
- && previousDemand.placements.some((previous) => previous.pluginId === placement.pluginId && previous.target === placement.target
338
- && previous.scope !== placement.scope && previous.contributions.some((item) => item.scope === scope && requested.includes(item.root)))
339
- : placement.contributions.some((item) => requested.includes(item.root)
340
- || options.allowDependencySelectors && item.path.some((id) => requested.includes(id))) || options.existingOnly && requested.includes(placement.pluginId)));
456
+ const dependencyGraph = indexJointDependencies(demand);
457
+ const { reaches } = dependencyGraph;
458
+ const requestedIds = new Set(requested);
459
+ const selectedContributions = new Map();
460
+ const selected = demand.placements.filter((placement) => {
461
+ if (!targets.includes(placement.target))
462
+ return false;
463
+ if (command === 'uninstall')
464
+ return canReuseProviderAcrossScopes(placement.target)
465
+ && !(options.force && requestedIds.has(placement.pluginId))
466
+ && previousDemand.placements.some((previous) => previous.pluginId === placement.pluginId && previous.target === placement.target
467
+ && previous.scope !== placement.scope && previous.contributions.some((item) => item.scope === scope && requestedIds.has(item.root))
468
+ && (!options.exactTargets || options.exactTargets.some((exact) => exact.agent === placement.target
469
+ && previous.contributions.some((item) => item.path.includes(exact.pluginId) && (!exact.scope || item.scope === exact.scope)))));
470
+ const contributions = placement.contributions.filter((item) => {
471
+ const selects = (pluginId) => !options.exactTargets || options.exactTargets.some((exact) => matchesExactContribution(placement, item, exact, reaches)
472
+ && (reaches(pluginId, exact.pluginId) || reaches(exact.pluginId, pluginId)));
473
+ if (requestedIds.has(item.root) || options.existingOnly && requestedIds.has(placement.pluginId))
474
+ return selects(item.root);
475
+ return options.allowDependencySelectors && requested.some((id) => reaches(item.root, id)
476
+ && reaches(id, placement.pluginId) && selects(id));
477
+ });
478
+ if (!contributions.length)
479
+ return false;
480
+ selectedContributions.set(placement, contributions);
481
+ return true;
482
+ });
341
483
  const activationOnlyTargets = [];
342
484
  if (snapshot.project && !errors.length) {
343
- const sharedNative = selected.filter((item) => item.scope === 'user' && ['codex', 'claude', 'gemini', 'copilot'].includes(item.target)
344
- && item.contributions.some((entry) => entry.scope === 'project'));
485
+ const sharedNative = selected.filter((item) => item.scope === 'user' && hasSharedUserPackage(item.target)
486
+ && (command === 'uninstall' ? item.contributions : selectedContributions.get(item))?.some((entry) => entry.scope === 'project'));
345
487
  if (sharedNative.length) {
346
488
  const expanded = { ...snapshot.project, roots: [...new Map(sharedNative.map((item) => [item.pluginId, {
347
489
  pluginId: item.pluginId, sourceId: item.plugin.sourceId, sourceState: 'ready', blockers: [], plugin: item.plugin,
@@ -350,6 +492,11 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
350
492
  const observation = await readScopedRecoveryStatus({ ...options, catalogReadScope, ...initialNativeReads, scope: 'project', demandOverride: expanded,
351
493
  cwd: snapshot.context.projectRoot, targets: undefined });
352
494
  for (const item of sharedNative) {
495
+ const addProjectActivation = () => {
496
+ const activation = { ...item, scope: 'project' };
497
+ selected.push(activation);
498
+ selectedContributions.set(activation, selectedContributions.get(item)?.filter((entry) => entry.scope === 'project') ?? []);
499
+ };
353
500
  const actual = observation.inventory?.find((entry) => entry.pluginId === item.pluginId)?.targetResults
354
501
  .find((entry) => entry.agent === item.target);
355
502
  if (item.target === 'codex') {
@@ -364,20 +511,23 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
364
511
  if (!surface.nativeKinds.length || !explicitlyDisabled && !retiringProjectComponents)
365
512
  continue;
366
513
  activationOnlyTargets.push({ pluginId: item.pluginId, platform: 'codex', scope: 'project' });
367
- selected.push({ ...item, scope: 'project' });
514
+ addProjectActivation();
368
515
  continue;
369
516
  }
370
517
  }
371
518
  if (actual?.content !== 'satisfied') {
372
519
  if (item.target !== 'generic')
373
520
  activationOnlyTargets.push({ pluginId: item.pluginId, platform: item.target, scope: 'project' });
374
- selected.push({ ...item, scope: 'project' });
521
+ addProjectActivation();
375
522
  }
376
523
  }
377
524
  }
378
525
  }
379
526
  const context = await createScopeContext({ ...options, scope });
527
+ if (command !== 'uninstall')
528
+ errors.push(...unplacedRoots.flatMap((root) => root.blockers));
380
529
  const baseDemand = scope === 'project' ? snapshot.project : snapshot.user;
530
+ const rebuildsRequestedRoots = command === 'reinstall' && !options.allowDependencySelectors && !options.existingOnly;
381
531
  const receipt = {
382
532
  schemaVersion: 1, kind: 'aw-recovery', command, scope, ok: false,
383
533
  intent: intentReceipt(observedIntent),
@@ -385,11 +535,16 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
385
535
  selection: { agents: targets, origin: options.targets ? 'argument' : targets.length ? 'preference' : 'none', preferences: snapshot.user.preferences.state },
386
536
  blockers: errors, errors, recoveryActions: [], declarationChanged: false, preferencesChanged: false,
387
537
  configChanged: false, outputsMayHaveChanged: false,
538
+ ...(rebuildsRequestedRoots ? { rebuildsRequestedRoots: true } : {}),
539
+ ...((isInstallBatch(command) || rebuildsRequestedRoots) && snapshot.context.scopes.includes('project') ? {
540
+ reviewedUserRoots: intentReceipt(options.existingOnly ? savedDemand.user.intent : snapshot.user.intent)
541
+ .roots?.filter((id) => requested.includes(id)) ?? null,
542
+ } : {}),
388
543
  coverage: { scopes: snapshot.context.scopes, ...(snapshot.context.projectRoot ? { projectRoot: snapshot.context.projectRoot } : {}) },
389
544
  };
390
545
  const children = [];
391
546
  const { signal: _signal, ...executionOptions } = options;
392
- const joint = { snapshot, demand, removalDependencies: dependencyClosures, children, originalOptions: executionOptions,
547
+ const joint = { snapshot, demand, unplacedRoots, removalDependencies: dependencyClosures, selectedContributions, children, originalOptions: executionOptions,
393
548
  selectors: [...selectors], declaration, evidence };
394
549
  const plan = { command, options: { ...executionOptions, scope }, receipt, context, demand: baseDemand,
395
550
  originalIntent: observationEvidence(original.intent), preferencesEvidence: observationEvidence(snapshot.user.preferences),
@@ -400,7 +555,11 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
400
555
  || error.code === 'targetsNotConfigured' && !options.retireUnselectedTargets)
401
556
  || !snapshot.preferences || snapshot.user.roots === null || snapshot.project?.roots === null, joint };
402
557
  const dispose = context.dispose;
403
- context.dispose = async () => { await Promise.all(children.map((child) => child.context.dispose())); await dispose(); };
558
+ let portableUserContext;
559
+ context.dispose = async () => {
560
+ await Promise.all([...children.map((child) => child.context.dispose()), portableUserContext?.dispose()]);
561
+ await dispose();
562
+ };
404
563
  if (plan.blockExecution)
405
564
  return plan;
406
565
  try {
@@ -487,16 +646,33 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
487
646
  }
488
647
  plan.dependencyCleanupTargets = automaticRetirements.map((item) => ({ pluginId: item.pluginId, agent: item.target, scope: item.scope }));
489
648
  const nativeTargets = targets.filter((target) => target !== 'generic');
490
- const targetGroups = [...(nativeTargets.length ? [nativeTargets] : []),
491
- ...targets.filter((target) => target === 'generic').map((target) => [target])];
649
+ const batch = isInstallBatch(command);
650
+ const hasSelectedScripts = selected.some((item) => item.plugin.manifest.scripts?.preApply);
651
+ const portableGenerations = new Map();
652
+ const targetGroups = batch ? [...nativeTargets, ...targets.filter((target) => target === 'generic')].map((target) => [target])
653
+ : [...(nativeTargets.length ? [nativeTargets] : []), ...targets.filter((target) => target === 'generic').map((target) => [target])];
492
654
  for (const currentScope of snapshot.context.scopes) {
493
- for (const groupTargets of targetGroups) {
655
+ const prepareGroup = async (groupTargets) => {
656
+ const inheritedScripts = currentScope === 'user' && command === 'sync' && !options.existingOnly
657
+ ? selected.filter((item) => {
658
+ if (item.scope !== 'user' || !groupTargets.includes(item.target) || !item.plugin.manifest.scripts?.preApply)
659
+ return false;
660
+ const contributions = selectedContributions.get(item);
661
+ return !contributions.some((entry) => entry.scope === 'user')
662
+ && contributions.some((entry) => entry.scope === 'project' && entry.root !== item.pluginId)
663
+ && !(requestedIds.has(item.pluginId) && (!options.exactTargets || options.exactTargets.some((exact) => exact.pluginId === item.pluginId && exact.agent === item.target && contributions.some((entry) => entry.scope === exact.scope))));
664
+ }) : [];
665
+ const inheritedPortableProviderIds = inheritedScripts.filter((item) => item.target === 'generic').map((item) => item.pluginId);
494
666
  const placements = selected.filter((item) => item.scope === currentScope && groupTargets.includes(item.target)
495
667
  && !(command === 'install' && scope === 'project' && currentScope === 'user'
496
668
  && currentStatus.observedTargets?.some((observed) => observed.pluginId === item.pluginId
497
- && observed.agent === item.target && observed.scope === 'user' && observed.content === 'satisfied')));
669
+ && observed.agent === item.target && observed.scope === 'user' && observed.content === 'satisfied'))
670
+ && !(hasSharedUserPackage(item.target) && inheritedScripts.includes(item)
671
+ && currentStatus.observedTargets?.some((observed) => observed.pluginId === item.pluginId
672
+ && observed.agent === item.target && observed.scope === 'user' && observed.providerScope === 'user'
673
+ && observed.observation === 'verified' && observed.content === 'satisfied' && !observed.blockers.length)));
498
674
  if (!placements.length)
499
- continue;
675
+ return;
500
676
  const sourceDemand = currentScope === 'project' ? snapshot.project : snapshot.user;
501
677
  const childPlacements = [
502
678
  ...demand.placements.filter((item) => item.scope === currentScope && groupTargets.includes(item.target)),
@@ -511,7 +687,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
511
687
  roots: [...new Map(childPlacements.map((item) => [item.pluginId, { pluginId: item.pluginId, sourceId: item.plugin.sourceId,
512
688
  sourceState: 'ready', blockers: [], plugin: item.plugin }])).values()] };
513
689
  const child = await prepareScopedRecovery(command === 'reinstall' ? 'reinstall' : 'sync', [...new Set(placements.map((item) => item.pluginId))], { ...options, scope: currentScope, targets: groupTargets, all: false,
514
- sharedReferenceView,
690
+ sharedReferenceView, inheritedPortableProviderIds,
515
691
  cwd: snapshot.context.projectRoot ?? options.cwd, demandOverride: childDemand,
516
692
  exactTargets: placements.map((item) => ({ pluginId: item.pluginId, agent: item.target })),
517
693
  nativeActivationOnlyTargets: activationOnlyTargets.filter((item) => item.scope === currentScope
@@ -526,7 +702,10 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
526
702
  ? userProviders.filter((provider) => provider.target !== 'generic'
527
703
  && !placements.some((item) => item.pluginId === provider.pluginId && item.target === provider.target))
528
704
  .map((item) => ({ pluginId: item.pluginId, platform: item.target, scope: 'user' })) : [],
529
- }, runtime, { catalogReadScope, nativeObservationBatch: children.length === 0 ? nativeObservationBatch : undefined });
705
+ }, batch && groupTargets[0] !== 'generic'
706
+ ? { ...runtime, batchInstallPlatform: groupTargets[0] } : runtime, { catalogReadScope, portableGenerations, nativeObservationBatch: batch || children.length === 0 ? nativeObservationBatch : undefined });
707
+ // Track contexts as soon as acquired, including a sibling that finishes after cancellation.
708
+ children.push(child);
530
709
  // Synthetic roots are only an execution projection, never persisted Intent.
531
710
  child.originalIntent = observationEvidence(sourceDemand.intent);
532
711
  if (options.existingOnly) {
@@ -538,9 +717,56 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
538
717
  }
539
718
  }
540
719
  }
541
- children.push(child);
720
+ return child;
721
+ };
722
+ if (batch) {
723
+ const start = children.length;
724
+ const ordered = await mapInstallReads(targetGroups, prepareGroup, { signal: options.signal });
725
+ children.splice(start, children.length - start, ...ordered.filter((child) => child !== undefined));
542
726
  }
727
+ else
728
+ for (const groupTargets of targetGroups)
729
+ await prepareGroup(groupTargets);
543
730
  }
731
+ if (hasSelectedScripts && (batch || command === 'reinstall')) {
732
+ const projectPortable = children.find((child) => child.options.scope === 'project' && child.portableGroups.length);
733
+ const consumers = (projectPortable?.portableGroups ?? []).map((group) => ({ pluginId: group.options.selector,
734
+ providers: [...dependencyGraph.providers({ pluginId: group.options.selector, target: 'generic', scope: 'project' })]
735
+ .filter((item) => item.scope === 'user').map((item) => item.pluginId) }));
736
+ const required = [...new Set(consumers.flatMap((item) => item.providers))];
737
+ if (projectPortable && required.length) {
738
+ const userPortable = children.find((child) => child.options.scope === 'user' && child.options.targets?.includes('generic'));
739
+ const reviewed = new Map([...(userPortable?.portableProtectionGroups ?? []), ...(userPortable?.portableGroups ?? [])]
740
+ .map((group) => [group.options.selector, group]));
741
+ const providerContext = userPortable?.context ?? (portableUserContext = await createScopeContext({ ...options, scope: 'user' }));
742
+ // First Project install can reuse a healthy User provider without creating a User execution row.
743
+ await mapInstallReads(required.filter((id) => !reviewed.has(id)), async (selector) => {
744
+ const provider = await preparePortableRecovery({ scope: 'user', context: providerContext, selector, agents: ['generic'],
745
+ cliVersion: options.cliVersion, catalogOperationContext: snapshot.user.catalogOperationContext,
746
+ signal: options.signal }, catalogReadScope, portableGenerations);
747
+ delete provider.options.signal;
748
+ reviewed.set(selector, provider);
749
+ }, { signal: options.signal });
750
+ const checks = new Map();
751
+ for (const consumer of consumers)
752
+ if (consumer.providers.length) {
753
+ checks.set(consumer.pluginId, consumer.providers.map((id) => reviewed.get(id)));
754
+ }
755
+ projectPortable.options.portableProviderChecks = checks;
756
+ }
757
+ }
758
+ if (batch)
759
+ for (const currentScope of snapshot.context.scopes) {
760
+ const scoped = children.filter((child) => child.options.scope === currentScope);
761
+ if (scoped.length < 2)
762
+ continue;
763
+ const first = scoped[0];
764
+ await checkFootprints({ ...first, changes: [],
765
+ nativeGroups: scoped.flatMap((child) => child.nativeGroups),
766
+ portableGroups: scoped.flatMap((child) => child.portableGroups),
767
+ receipt: { ...first.receipt, targetResults: scoped.flatMap((child) => child.receipt.targetResults) },
768
+ });
769
+ }
544
770
  const portableCandidates = children.flatMap((child) => child.portableGroups.flatMap((prepared) => prepared.targets
545
771
  .filter((target) => target.disposition !== 'remove')
546
772
  .map((target) => ({ child, prepared, target }))));
@@ -566,7 +792,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
566
792
  const scopedExtensions = (backend?.live?.components ?? backend?.components ?? []).some((component) => component.kind === 'ownership' && component.key !== 'native'
567
793
  && !component.key.startsWith('activation-') && !component.key.startsWith('marketplace-')
568
794
  && ['present', 'partial'].includes(component.state));
569
- if (item.scope !== 'project' || !item.agent || !['codex', 'claude', 'gemini', 'copilot'].includes(item.agent))
795
+ if (item.scope !== 'project' || !item.agent || !['codex', 'claude', 'copilot'].includes(item.agent))
570
796
  return false;
571
797
  return demand.placements.some((placement) => {
572
798
  if (placement.pluginId !== item.pluginId || placement.target !== item.agent)
@@ -658,12 +884,44 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
658
884
  }
659
885
  children.unshift(...cleanups);
660
886
  }
887
+ if ((batch || command === 'reinstall' && options.exactTargets) && !children.some((child) => child.command === 'cleanup')) {
888
+ const order = new Map();
889
+ if (options.exactTargets) {
890
+ // The caller ordered exact pairs. Insert their actual providers once, before the consuming pair.
891
+ for (const exact of options.exactTargets) {
892
+ for (const item of selected.filter((placement) => selectedContributions.get(placement)?.some((contribution) => matchesExactContribution(placement, contribution, exact, reaches)))) {
893
+ const key = targetKey({ pluginId: item.pluginId, agent: item.target, scope: item.scope });
894
+ if (!order.has(key))
895
+ order.set(key, order.size);
896
+ }
897
+ const key = targetKey({ ...exact, scope: exact.scope ?? scope });
898
+ if (!order.has(key))
899
+ order.set(key, order.size);
900
+ }
901
+ }
902
+ else {
903
+ // Ordinary batches list each scope's Native roots across clients, then Portable roots.
904
+ const deliveries = [nativeTargets, targets.filter((agent) => agent === 'generic')];
905
+ for (const scope of snapshot.context.scopes)
906
+ for (const agents of deliveries) {
907
+ const roots = new Set(selected.filter((item) => item.scope === scope && agents.includes(item.target)).map((item) => item.pluginId));
908
+ for (const root of unplacedRoots)
909
+ if (root.scope === scope && agents.includes(root.target)
910
+ && (root.state === 'blocked' || root.state === 'unknown'))
911
+ roots.add(root.pluginId);
912
+ for (const pluginId of roots)
913
+ for (const agent of agents)
914
+ order.set(targetKey({ pluginId, agent, scope }), order.size);
915
+ }
916
+ }
917
+ joint.targetOrder = order;
918
+ }
661
919
  // The first preview already seals every target in its native group. A lone
662
- // Gemini/Copilot ensure group has no later sibling contribution to refresh here.
920
+ // Copilot ensure group has no later sibling contribution to refresh here.
663
921
  const onlyChild = children.length === 1 ? children[0] : undefined;
664
922
  const onlyGroup = onlyChild?.nativeGroups.length === 1 ? onlyChild.nativeGroups[0] : undefined;
665
923
  const singleNativePreviewComplete = !plan.blockExecution && onlyChild !== undefined && !onlyChild.blockExecution
666
- && onlyChild.command === 'sync' && (onlyGroup?.platform === 'gemini' || onlyGroup?.platform === 'copilot')
924
+ && onlyChild.command === 'sync' && onlyGroup?.platform === 'copilot'
667
925
  && onlyGroup.command === 'sync'
668
926
  && onlyGroup.preview.operationPlan !== undefined
669
927
  && (onlyGroup.preview.operationPlan.deploymentPlans?.length ?? 0) > 0
@@ -674,32 +932,44 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
674
932
  && onlyChild.portableResidues.length === 0;
675
933
  // Other scopes and groups can change shared descriptors, preApply actions
676
934
  // or retained packages. Refresh those previews before exposing Review.
677
- if (!singleNativePreviewComplete)
678
- for (const child of children)
679
- await refreshRecoveryNativePreviews(child, catalogReadScope);
935
+ if (!singleNativePreviewComplete) {
936
+ if (batch) {
937
+ const nativeChildren = children.filter((child) => child.nativeGroups.length);
938
+ const platforms = [...new Set(nativeChildren.map((child) => child.runtime.batchInstallPlatform))];
939
+ await mapInstallReads(platforms, async (platform) => {
940
+ const scoped = nativeChildren.filter((item) => item.runtime.batchInstallPlatform === platform);
941
+ // One complete ensure plan owns this platform session. Its initial preview already sealed
942
+ // every candidate; only another source or scope can contribute a later shared descriptor.
943
+ const only = scoped.length === 1 ? scoped[0] : undefined;
944
+ const preview = only?.nativeGroups.length === 1 ? only.nativeGroups[0].preview : undefined;
945
+ if (platform && only && !only.blockExecution && only.receipt.targetResults.every((target) => target.blockers.length === 0)
946
+ && preview?.operationPlan?.deploymentPlans?.length
947
+ && preview.operationPlan.deploymentPlans.every((deployment) => deployment.operation === 'ensure'))
948
+ return;
949
+ for (const child of scoped)
950
+ await refreshRecoveryNativePreviews(child, catalogReadScope, options.signal);
951
+ }, { signal: options.signal });
952
+ }
953
+ else
954
+ for (const child of children)
955
+ await refreshRecoveryNativePreviews(child, catalogReadScope, options.signal);
956
+ }
680
957
  const preparedNativeTargets = children.flatMap((child) => child.receipt.targetResults)
681
958
  .filter((target) => target.delivery?.kind === 'native');
682
- const failedProviders = preparedNativeTargets.filter((target) => target.blockers.length > 0);
683
- for (const target of preparedNativeTargets) {
684
- const placement = demand.placements.find((item) => item.pluginId === target.pluginId
685
- && item.target === target.agent && item.scope === target.scope);
686
- if (!placement)
687
- continue;
688
- for (const provider of failedProviders) {
689
- if (provider === target || provider.agent !== target.agent)
690
- continue;
691
- const dependency = demand.placements.find((item) => item.pluginId === provider.pluginId
692
- && item.target === provider.agent && item.scope === provider.scope);
693
- if (!dependency?.contributions.some((contribution) => placement.contributions.some((parent) => parent.root === contribution.root && parent.scope === contribution.scope
694
- && parent.path.length < contribution.path.length
695
- && parent.path.every((pluginId, index) => pluginId === contribution.path[index]))))
696
- continue;
697
- for (const blocker of provider.blockers)
698
- if (!target.blockers.some((entry) => entry.code === blocker.code && entry.pluginId === provider.pluginId)) {
699
- target.blockers.push({ ...blocker, pluginId: provider.pluginId });
700
- }
959
+ const failedProviders = new Map(preparedNativeTargets.filter((target) => target.blockers.length > 0)
960
+ .map((target) => [targetKey(target), target]));
961
+ if (failedProviders.size)
962
+ for (const target of preparedNativeTargets) {
963
+ for (const dependency of dependencyGraph.providers({ pluginId: target.pluginId, target: target.agent, scope: target.scope })) {
964
+ const provider = failedProviders.get(targetKey({ ...dependency, agent: dependency.target }));
965
+ if (!provider)
966
+ continue;
967
+ for (const blocker of provider.blockers)
968
+ if (!target.blockers.some((entry) => entry.code === blocker.code && entry.pluginId === provider.pluginId)) {
969
+ target.blockers.push({ ...blocker, pluginId: provider.pluginId });
970
+ }
971
+ }
701
972
  }
702
- }
703
973
  finalizePreparedPlatformRebuildSession(runtime.preparedArtifactRenderResults);
704
974
  plan.sourceRefreshes = [...new Map(children.flatMap((child) => child.sourceRefreshes).map((item) => [item.sourceId, item])).values()];
705
975
  plan.sourceRefreshFailures = [...new Map(children.flatMap((child) => child.sourceRefreshFailures).map((item) => [item.sourceId, item])).values()];
@@ -707,6 +977,8 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
707
977
  plan.warnings.push(...children.flatMap((child) => child.warnings));
708
978
  plan.plannedImpact.outputs = children.some((child) => child.plannedImpact.outputs);
709
979
  plan.receipt = mergeReceipts(plan, children.map((child) => child.receipt));
980
+ if (retriesFromRequestedRoots(plan.receipt) && plan.receipt.remainingTargets.length)
981
+ useDeclaredRetryRoots(plan.receipt);
710
982
  const observedManager = children.flatMap((child) => child.nativeGroups)
711
983
  .map((group) => group.preview.codexManagerPreview)
712
984
  .find((entry) => entry?.state === 'system');
@@ -723,20 +995,36 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
723
995
  export async function executeJointRecovery(plan, execution) {
724
996
  const joint = plan.joint;
725
997
  const performanceRuntime = { ...plan.runtime, ...execution.runtime };
998
+ if (isInstallBatch(plan.command)) {
999
+ const override = execution.runtime?.nativeCliRunner;
1000
+ if (!override || override === joint.originalNativeRunner || override === plan.runtime.nativeCliRunner) {
1001
+ performanceRuntime.nativeCliRunner = plan.runtime.nativeCliRunner;
1002
+ joint.bindExecutionSignal?.(performanceRuntime.signal);
1003
+ }
1004
+ else {
1005
+ performanceRuntime.nativeCliRunner = limitInstallNativeRunner(override);
1006
+ performanceRuntime.codexObservationSession = execution.runtime?.codexObservationSession;
1007
+ }
1008
+ }
1009
+ let lockedPlan;
1010
+ let completedReceipt;
726
1011
  let lockWaitStartedAt;
727
1012
  try {
728
1013
  if (plan.sourceRefreshes.length) {
729
1014
  plan.receipt.blockers.push(diagnostic('sourceRefreshConfirmationRequired'));
730
- return mergeReceipts(plan, joint.children.map((child) => child.receipt));
1015
+ const receipt = mergeReceipts(plan, joint.children.map((child) => child.receipt));
1016
+ if (retriesFromRequestedRoots(receipt))
1017
+ useDeclaredRetryRoots(receipt);
1018
+ return receipt;
731
1019
  }
732
1020
  lockWaitStartedAt = performance.now();
733
1021
  await recordRecoveryPerformanceStage(performanceRuntime, 'recovery.lock.wait', 'start', lockWaitStartedAt);
734
- return await withAwHomeMutationLock({ env: plan.options.env, token: execution.runtime?.awHomeMutationToken ?? plan.runtime.awHomeMutationToken,
1022
+ return await withAwHomeMutationLock({ env: plan.options.env, signal: performanceRuntime.signal, token: execution.runtime?.awHomeMutationToken ?? plan.runtime.awHomeMutationToken,
735
1023
  action: async (token) => {
736
1024
  const acquiredAt = lockWaitStartedAt;
737
1025
  lockWaitStartedAt = undefined;
738
1026
  await recordRecoveryPerformanceStage(performanceRuntime, 'recovery.lock.wait', 'success', acquiredAt);
739
- const preparation = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.demand', () => readJointPreparation(plan.command, joint.originalOptions, true));
1027
+ const preparation = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.demand', () => readJointPreparation(plan.command, { ...joint.originalOptions, signal: performanceRuntime.signal }, true));
740
1028
  const actual = preparation.snapshot;
741
1029
  const currentIntent = (plan.options.scope === 'project' ? actual.project : actual.user).intent;
742
1030
  plan.receipt.intent = intentReceipt(currentIntent);
@@ -744,30 +1032,33 @@ export async function executeJointRecovery(plan, execution) {
744
1032
  plan.receipt.blockers.push(describeStrongStateProblem({ kind: 'intent', scope: plan.options.scope,
745
1033
  state: currentIntent.state, filePath: await resolveIntentPath(plan.options) }));
746
1034
  }
747
- if (snapshotEvidence(actual) !== joint.evidence) {
748
- plan.receipt.blockers.push(diagnostic('operationReviewStale'));
749
- return mergeReceipts(plan, []);
750
- }
1035
+ if (snapshotEvidence(actual) !== joint.evidence)
1036
+ return blockedBeforeDeployment(plan);
751
1037
  if (plan.blockExecution)
752
1038
  return plan.receipt;
753
1039
  // Recheck all backend candidates before any strong-state or output write.
754
1040
  (execution.runtime?.codexObservationSession ?? plan.runtime.codexObservationSession)?.invalidate();
755
- const checked = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.recheck', () => prepareJointRecovery(plan.command, joint.selectors, preparation.options, { ...plan.runtime, ...execution.runtime, awHomeMutationToken: token }, preparation.catalogReadScope ? preparation : undefined));
1041
+ const checked = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.recheck', () => prepareJointRecovery(plan.command, joint.selectors, preparation.options, { ...performanceRuntime, awHomeMutationToken: token }, preparation.catalogReadScope ? preparation : undefined));
756
1042
  const stable = !checked.blockExecution && JSON.stringify(describeRecoveryPlan(plan)) === JSON.stringify(describeRecoveryPlan(checked));
757
- await checked.context.dispose();
758
- if (!stable) {
759
- plan.receipt.blockers.push(diagnostic('operationReviewStale'));
760
- return mergeReceipts(plan, []);
761
- }
1043
+ lockedPlan = checked;
1044
+ const parallel = isInstallBatch(plan.command) && !joint.children.some((child) => child.command === 'cleanup');
1045
+ const children = parallel ? checked.joint.children : joint.children;
1046
+ if (!stable)
1047
+ return blockedBeforeDeployment(plan);
1048
+ performanceRuntime.signal?.throwIfAborted();
762
1049
  if (joint.originalOptions.preferences) {
763
1050
  const saved = await writePreferences({ ...plan.options, scope: 'user', token }, joint.originalOptions.preferences);
764
1051
  plan.receipt.preferencesChanged = saved.changed;
765
1052
  const committed = await observePreferences({ ...plan.options, scope: 'user' });
1053
+ plan.receipt.selection.preferences = committed.state;
766
1054
  if (committed.state !== 'valid') {
767
- plan.receipt.blockers.push(diagnostic('deploymentPreferencesUnavailable'));
768
- return mergeReceipts(plan, []);
1055
+ return blockedBeforeDeployment(plan, diagnostic(committed.state === 'invalid'
1056
+ ? 'deploymentPreferencesInvalid' : 'deploymentPreferencesUnavailable'), 'preferences');
1057
+ }
1058
+ if (JSON.stringify(committed.value) !== JSON.stringify(saved.value)) {
1059
+ return blockedBeforeDeployment(plan, diagnostic('operationReviewStale'), 'preferences');
769
1060
  }
770
- for (const child of joint.children) {
1061
+ for (const child of children) {
771
1062
  child.demand.preferences = committed;
772
1063
  if (child.options.demandOverride)
773
1064
  child.options.demandOverride.preferences = committed;
@@ -780,11 +1071,13 @@ export async function executeJointRecovery(plan, execution) {
780
1071
  const committed = await observeIntent({ ...plan.options, scope: joint.declaration.scope });
781
1072
  plan.receipt.intent = intentReceipt(committed);
782
1073
  if (committed.state !== 'valid') {
783
- plan.receipt.blockers.push(committed.state === 'absent'
1074
+ return blockedBeforeDeployment(plan, committed.state === 'absent'
784
1075
  ? diagnostic('pluginIntentStateUnavailable', '保存后未找到插件声明,未执行输出变更。')
785
1076
  : describeStrongStateProblem({ kind: 'intent', scope: joint.declaration.scope,
786
- state: committed.state, filePath: await resolveIntentPath({ ...plan.options, scope: joint.declaration.scope }) }));
787
- return mergeReceipts(plan, []);
1077
+ state: committed.state, filePath: await resolveIntentPath({ ...plan.options, scope: joint.declaration.scope }) }), 'intent');
1078
+ }
1079
+ if (calculateIntentDigest(committed.value) !== calculateIntentDigest(saved.value)) {
1080
+ return blockedBeforeDeployment(plan, diagnostic('operationReviewStale'), 'intent');
788
1081
  }
789
1082
  }
790
1083
  const results = joint.children.filter((child) => child.blockExecution
@@ -793,248 +1086,261 @@ export async function executeJointRecovery(plan, execution) {
793
1086
  const failedPackages = new Set();
794
1087
  const failedNodes = new Set();
795
1088
  const packageResults = [];
796
- const runtime = { ...plan.runtime, ...execution.runtime, awHomeMutationToken: token };
1089
+ const runtime = { ...performanceRuntime, awHomeMutationToken: token };
797
1090
  runtime.preApplyExecutionCache ??= new Map();
798
1091
  runtime.managedCommandProducerCache ??= new Map();
799
- const packages = runtime.configApplyPackages;
800
- const failedCleanups = [];
801
- const executeChild = async (child, pluginIds, agent) => {
802
- const currentIntent = await observeIntent(child.options);
803
- if (!joint.originalOptions.existingOnly)
804
- child.demand.intent = currentIntent;
805
- const fresh = await measureRecoveryPerformanceStage(runtime, 'recovery.child.plan', () => prepareScopedRecovery(child.command, typeof pluginIds === 'string' ? [pluginIds] : pluginIds, {
806
- ...child.options, targets: agent !== 'generic' ? child.options.targets : [agent], all: false,
807
- exactTargets: child.options.exactTargets?.filter((target) => (typeof pluginIds === 'string' ? [pluginIds] : pluginIds).includes(target.pluginId)),
808
- }, runtime));
809
- fresh.originalIntent = observationEvidence(currentIntent);
810
- for (const target of fresh.receipt.targetResults) {
811
- const reviewed = child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent);
812
- if (reviewed?.relation === 'dependency') {
813
- target.relation = 'dependency';
814
- target.requiredBy = [...reviewed.requiredBy];
815
- }
816
- // Native/provider observations are refreshed after preceding nodes.
817
- // Keep only joint constraints and an already failed script gate.
818
- target.blockers.push(...(reviewed?.blockers ?? []).filter((error) => reviewed?.execution === 'failed'
819
- || ['configApplyRequiresExistingOutput', 'crossScopeSkillCollision', 'targetPlacementConflict',
820
- 'preApplyAuthorizationRequired', 'nativeToolAuthorizationRequired', 'providerSwitchPreApplyFailed', 'dependencyStillRequired'].includes(error.code)));
821
- if (reviewed?.execution === 'failed') {
822
- target.execution = 'failed';
823
- if (reviewed.backend)
824
- target.backend = reviewed.backend;
825
- }
826
- if (child.command !== 'cleanup' && failedCleanups.some((failed) => failed.agent === target.agent && (failed.pluginId === target.pluginId || joint.demand.roots.some((root) => root.pluginId === target.pluginId && root.target === target.agent && root.dependencies.includes(failed.pluginId))))) {
827
- target.blockers.push(diagnostic('providerSwitchCleanupFailed'));
828
- }
829
- const dependencies = joint.demand.placements.filter((placement) => placement.target === target.agent
830
- && placement.contributions.some((contribution) => contribution.path.includes(target.pluginId)));
831
- if (failedPackages.has(`${target.pluginId}\0${target.scope}`) || failedPackages.has(`${target.pluginId}\0user`)
832
- || dependencies.some((item) => failedPackages.has(`${item.pluginId}\0${item.scope}`))) {
833
- target.blockers.push(diagnostic('commandPackageProviderNotSatisfied'));
834
- }
835
- const failedDependency = dependencies.find((placement) => failedProviders.has(`${placement.pluginId}\0${placement.target}\0${placement.scope}`));
836
- if (failedDependency) {
837
- target.blockers.push(diagnostic(target.scope === 'project' && failedDependency.scope === 'user'
838
- ? 'userProviderNotSatisfied' : 'dependencyApplyFailed', `依赖提供者未完成。恢复后重试 aw plugin sync ${target.pluginId} --context ${target.scope} --target ${target.agent} --yes`));
1092
+ let interrupted;
1093
+ if (parallel) {
1094
+ const installed = await executeJointInstall({ children, demand: checked.joint.demand, runtime, token,
1095
+ yes: execution.yes ?? plan.options.yes, existingOnly: joint.originalOptions.existingOnly });
1096
+ interrupted = installed.interruption;
1097
+ results.push(...installed.receipts);
1098
+ packageResults.push(...installed.commands);
1099
+ plan.receipt.blockers.push(...installed.blockers);
1100
+ for (const result of installed.commands)
1101
+ if (result.state !== 'completed')
1102
+ failedPackages.add(getCommandPackageId(result.producer));
1103
+ }
1104
+ else {
1105
+ const packages = runtime.configApplyPackages;
1106
+ const dependencyGraph = indexJointDependencies(joint.demand);
1107
+ const portableProgress = { completed: [], failed: [] };
1108
+ const failedCleanups = [];
1109
+ const executeChild = async (child, pluginIds, agent) => {
1110
+ const currentIntent = await observeIntent(child.options);
1111
+ if (!joint.originalOptions.existingOnly)
1112
+ child.demand.intent = currentIntent;
1113
+ const fresh = await measureRecoveryPerformanceStage(runtime, 'recovery.child.plan', () => prepareScopedRecovery(child.command, typeof pluginIds === 'string' ? [pluginIds] : pluginIds, {
1114
+ ...child.options, targets: agent !== 'generic' ? child.options.targets : [agent], all: false,
1115
+ exactTargets: child.options.exactTargets?.filter((target) => (typeof pluginIds === 'string' ? [pluginIds] : pluginIds).includes(target.pluginId)),
1116
+ }, runtime));
1117
+ fresh.originalIntent = observationEvidence(currentIntent);
1118
+ for (const target of fresh.receipt.targetResults) {
1119
+ const reviewed = child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent);
1120
+ if (reviewed?.relation === 'dependency') {
1121
+ target.relation = 'dependency';
1122
+ target.requiredBy = [...reviewed.requiredBy];
1123
+ }
1124
+ // Native/provider observations are refreshed after preceding nodes.
1125
+ // Keep only joint constraints and an already failed script gate.
1126
+ target.blockers.push(...(reviewed?.blockers ?? []).filter((error) => reviewed?.execution === 'failed'
1127
+ || ['configApplyRequiresExistingOutput', 'crossScopeSkillCollision', 'targetPlacementConflict',
1128
+ 'preApplyAuthorizationRequired', 'nativeToolAuthorizationRequired', 'providerSwitchPreApplyFailed', 'dependencyStillRequired'].includes(error.code)));
1129
+ if (reviewed?.execution === 'failed') {
1130
+ target.execution = 'failed';
1131
+ if (reviewed.backend)
1132
+ target.backend = reviewed.backend;
1133
+ }
1134
+ if (child.command !== 'cleanup' && failedCleanups.some((failed) => failed.agent === target.agent && (failed.pluginId === target.pluginId || joint.demand.roots.some((root) => root.pluginId === target.pluginId && root.target === target.agent && root.dependencies.includes(failed.pluginId))))) {
1135
+ target.blockers.push(diagnostic('providerSwitchCleanupFailed'));
1136
+ }
1137
+ const dependencies = [...dependencyGraph.providers({ pluginId: target.pluginId, target: target.agent, scope: target.scope })];
1138
+ if (failedPackages.has(`${target.pluginId}\0${target.scope}`) || failedPackages.has(`${target.pluginId}\0user`)
1139
+ || dependencies.some((item) => failedPackages.has(`${item.pluginId}\0${item.scope}`))) {
1140
+ target.blockers.push(diagnostic('commandPackageProviderNotSatisfied'));
1141
+ }
1142
+ const failedDependency = dependencies.find((placement) => failedProviders.has(`${placement.pluginId}\0${placement.target}\0${placement.scope}`));
1143
+ if (failedDependency) {
1144
+ target.blockers.push({ code: target.scope === 'project' && failedDependency.scope === 'user'
1145
+ ? 'userProviderNotSatisfied' : 'dependencyApplyFailed',
1146
+ pluginId: failedDependency.pluginId,
1147
+ message: `依赖提供者 ${failedDependency.pluginId}(${failedDependency.target}/${failedDependency.scope})未完成。` });
1148
+ }
839
1149
  }
840
- }
841
- const result = await measureRecoveryPerformanceStage(runtime, 'recovery.child.execute', () => executeScopedRecovery(fresh, { ...execution, runtime }));
842
- if (joint.originalOptions.existingOnly)
843
- for (const target of result.targetResults) {
844
- if (!target.blockers.some((error) => error.code === 'dependencyInstallFailed'))
1150
+ const result = await measureRecoveryPerformanceStage(runtime, 'recovery.child.execute', () => executeScopedRecovery(fresh, { ...execution, runtime,
1151
+ ...(plan.command !== 'uninstall' && child.command !== 'cleanup' ? { portableProgress } : {}) }));
1152
+ if (joint.originalOptions.existingOnly)
1153
+ for (const target of result.targetResults) {
1154
+ if (!target.blockers.some((error) => error.code === 'dependencyInstallFailed'))
1155
+ continue;
1156
+ target.blockers = target.blockers.map((error) => error.code === 'dependencyInstallFailed'
1157
+ ? { ...error, code: 'dependencyApplyFailed', message: '依赖提供者未完成。请检查其执行结果。' }
1158
+ : error);
1159
+ if (target.execution === 'failed')
1160
+ target.execution = 'not-run';
1161
+ }
1162
+ results.push(result);
1163
+ return result;
1164
+ };
1165
+ // Provider changes can remove a working output. Complete the replacement's
1166
+ // authorization and scripts first, sharing the normal execution cache.
1167
+ const cleanupChildren = joint.children.filter((child) => child.command === 'cleanup');
1168
+ const replacementFailures = new Set();
1169
+ for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
1170
+ for (const target of child.receipt.targetResults) {
1171
+ if (replacementFailures.has(`${target.pluginId}\0${target.agent}`)) {
1172
+ target.blockers.push(diagnostic('dependencyApplyFailed'));
845
1173
  continue;
846
- target.blockers = target.blockers.map((error) => error.code === 'dependencyInstallFailed'
847
- ? diagnostic('dependencyApplyFailed', `依赖提供者未完成。恢复后重试 aw plugin sync ${target.pluginId} --context ${target.scope} --target ${target.agent} --yes`)
848
- : error);
849
- if (target.execution === 'failed')
850
- target.execution = 'not-run';
851
- }
852
- results.push(result);
853
- return result;
854
- };
855
- // Provider changes can remove a working output. Complete the replacement's
856
- // authorization and scripts first, sharing the normal execution cache.
857
- const cleanupChildren = joint.children.filter((child) => child.command === 'cleanup');
858
- const replacementFailures = new Set();
859
- for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
860
- for (const target of child.receipt.targetResults) {
861
- if (replacementFailures.has(`${target.pluginId}\0${target.agent}`)) {
862
- target.blockers.push(diagnostic('dependencyApplyFailed'));
863
- continue;
1174
+ }
1175
+ if (child.options.nativeActivationOnlyTargets?.some((item) => item.pluginId === target.pluginId
1176
+ && item.platform === target.agent && item.scope === target.scope))
1177
+ continue;
1178
+ if (!cleanupChildren.some((cleanup) => cleanup.receipt.requestedTargets.some((old) => old.pluginId === target.pluginId)))
1179
+ continue;
1180
+ const failure = target.blockers[0]?.code ?? await executeRecoveryPreApply({ ...child,
1181
+ options: { ...child.options, yes: execution.yes ?? plan.options.yes },
1182
+ }, target.pluginId, target.agent, runtime);
1183
+ if (!failure)
1184
+ continue;
1185
+ target.blockers.push(diagnostic(failure));
1186
+ if (failure !== 'preApplyAuthorizationRequired' && failure !== 'nativeToolAuthorizationRequired')
1187
+ target.execution = 'failed';
1188
+ replacementFailures.add(`${target.pluginId}\0${target.agent}`);
1189
+ failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
1190
+ failedNodes.add(`${target.pluginId}\0${target.scope}`);
864
1191
  }
865
- if (child.options.nativeActivationOnlyTargets?.some((item) => item.pluginId === target.pluginId
866
- && item.platform === target.agent && item.scope === target.scope))
867
- continue;
868
- if (!cleanupChildren.some((cleanup) => cleanup.receipt.requestedTargets.some((old) => old.pluginId === target.pluginId)))
869
- continue;
870
- const failure = target.blockers[0]?.code ?? await executeRecoveryPreApply({ ...child,
871
- options: { ...child.options, yes: execution.yes ?? plan.options.yes },
872
- }, target.pluginId, target.agent, runtime);
873
- if (!failure)
874
- continue;
875
- target.blockers.push(diagnostic(failure));
876
- if (failure !== 'preApplyAuthorizationRequired' && failure !== 'nativeToolAuthorizationRequired')
877
- target.execution = 'failed';
878
- replacementFailures.add(`${target.pluginId}\0${target.agent}`);
879
- failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
880
- failedNodes.add(`${target.pluginId}\0${target.scope}`);
881
1192
  }
882
- }
883
- // Target exits can replace one Agent with another. Preserve the reviewed
884
- // old output when its corresponding replacement cannot run.
885
- for (const child of joint.children.filter((child) => child.command === 'cleanup')) {
886
- for (const target of child.receipt.requestedTargets) {
887
- if (plan.command === 'uninstall' && failedCleanups.some((failed) => {
888
- if (failed.agent !== target.agent)
889
- return false;
890
- const required = joint.removalDependencies.get(failed.pluginId);
891
- return required?.includes(target.pluginId) || required === null
892
- && parsePluginId(failed.pluginId).sourceId === parsePluginId(target.pluginId).sourceId;
893
- })) {
894
- child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
895
- .blockers.push(diagnostic('dependencyStillRequired', '依赖者未完成删除,保留其依赖输出。'));
896
- }
897
- if ([...replacementFailures].some((failed) => failed.startsWith(`${target.pluginId}\0`)
898
- && (failed === `${target.pluginId}\0${target.agent}`
899
- || !joint.children.some((replacement) => replacement.command !== 'cleanup'
900
- && replacement.receipt.requestedTargets.some((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent))))) {
901
- child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
902
- .blockers.push(diagnostic('providerSwitchPreApplyFailed'));
1193
+ // Target exits can replace one Agent with another. Preserve the reviewed
1194
+ // old output when its corresponding replacement cannot run.
1195
+ for (const child of joint.children.filter((child) => child.command === 'cleanup')) {
1196
+ for (const target of child.receipt.requestedTargets) {
1197
+ if (plan.command === 'uninstall' && failedCleanups.some((failed) => {
1198
+ if (failed.agent !== target.agent)
1199
+ return false;
1200
+ const required = joint.removalDependencies.get(failed.pluginId);
1201
+ return required?.includes(target.pluginId) || required === null
1202
+ && parsePluginId(failed.pluginId).sourceId === parsePluginId(target.pluginId).sourceId;
1203
+ })) {
1204
+ child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
1205
+ .blockers.push(diagnostic('dependencyStillRequired', '依赖者未完成删除,保留其依赖输出。'));
1206
+ }
1207
+ if ([...replacementFailures].some((failed) => failed.startsWith(`${target.pluginId}\0`)
1208
+ && (failed === `${target.pluginId}\0${target.agent}`
1209
+ || !joint.children.some((replacement) => replacement.command !== 'cleanup'
1210
+ && replacement.receipt.requestedTargets.some((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent))))) {
1211
+ child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
1212
+ .blockers.push(diagnostic('providerSwitchPreApplyFailed'));
1213
+ }
1214
+ const result = await executeChild(child, target.pluginId, target.agent);
1215
+ if (!result.ok)
1216
+ failedCleanups.push(...result.requestedTargets);
903
1217
  }
904
- const result = await executeChild(child, target.pluginId, target.agent);
905
- if (!result.ok)
906
- failedCleanups.push(...result.requestedTargets);
907
1218
  }
908
- }
909
- const nodes = new Map();
910
- const nodeFor = (pluginId, scope) => {
911
- const key = `${pluginId}\0${scope}`;
912
- let node = nodes.get(key);
913
- if (!node) {
914
- node = { pluginId, scope, targets: [], dependencies: new Set() };
915
- nodes.set(key, node);
916
- }
917
- return node;
918
- };
919
- for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
920
- for (const target of child.receipt.requestedTargets)
921
- nodeFor(target.pluginId, target.scope).targets.push({ child, agent: target.agent });
922
- }
923
- const hasNative = (node) => node.targets.some(({ agent }) => agent !== 'generic');
924
- for (const target of packages?.targets ?? []) {
925
- const sameScope = nodes.get(`${target.pluginId}\0${target.scope}`);
926
- const native = sameScope && hasNative(sameScope) ? sameScope
927
- : [...nodes.values()].find((node) => node.pluginId === target.pluginId && hasNative(node));
928
- const node = native ?? nodeFor(target.pluginId, target.scope);
929
- (node.packages ??= []).push(target);
930
- }
931
- for (const node of nodes.values()) {
932
- for (const { agent } of node.targets) {
933
- const plugin = joint.demand.placements.find((item) => item.pluginId === node.pluginId && item.target === agent && item.scope === node.scope)?.plugin;
934
- for (const name of plugin?.manifest.dependencies ?? []) {
935
- const pluginId = `${plugin.sourceId}/${name}`;
936
- const providers = joint.demand.placements.filter((item) => item.pluginId === pluginId && item.target === agent);
937
- const provider = providers.find((item) => item.scope === node.scope) ?? providers.find((item) => item.scope === 'user');
938
- if (provider)
939
- node.dependencies.add(`${pluginId}\0${provider.scope}`);
1219
+ const nodes = new Map();
1220
+ const nodeFor = (pluginId, scope) => {
1221
+ const key = `${pluginId}\0${scope}`;
1222
+ let node = nodes.get(key);
1223
+ if (!node) {
1224
+ node = { pluginId, scope, targets: [], dependencies: new Set() };
1225
+ nodes.set(key, node);
940
1226
  }
1227
+ return node;
1228
+ };
1229
+ for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
1230
+ for (const target of child.receipt.requestedTargets)
1231
+ nodeFor(target.pluginId, target.scope).targets.push({ child, agent: target.agent });
941
1232
  }
942
- if (node.scope === 'project' && node.targets.some(({ agent }) => ['codex', 'claude', 'gemini', 'copilot'].includes(agent))
943
- && nodes.has(`${node.pluginId}\0user`))
944
- node.dependencies.add(`${node.pluginId}\0user`);
945
- for (const dependency of node.packages?.flatMap((item) => item.dependencies) ?? []) {
946
- for (const provider of nodes.values())
947
- if (provider.pluginId === dependency)
948
- node.dependencies.add(`${dependency}\0${provider.scope}`);
949
- }
950
- }
951
- const pending = [...nodes.values()].sort((left, right) => left.scope === right.scope
952
- ? left.pluginId.localeCompare(right.pluginId) : left.scope === 'user' ? -1 : 1);
953
- const executedNativeChildren = new Set();
954
- const completedPackages = new Map();
955
- const recordPackages = (pluginId, scope, produced) => {
956
- const key = `${pluginId}\0${scope}`;
957
- completedPackages.set(key, produced);
958
- packageResults.push(...produced);
959
- if (produced.some((result) => result.state !== 'completed')) {
960
- failedPackages.add(key);
961
- failedNodes.add(key);
1233
+ const hasNative = (node) => node.targets.some(({ agent }) => agent !== 'generic');
1234
+ for (const target of packages?.targets ?? []) {
1235
+ const sameScope = nodes.get(`${target.pluginId}\0${target.scope}`);
1236
+ const native = sameScope && hasNative(sameScope) ? sameScope
1237
+ : [...nodes.values()].find((node) => node.pluginId === target.pluginId && hasNative(node));
1238
+ const node = native ?? nodeFor(target.pluginId, target.scope);
1239
+ (node.packages ??= []).push(target);
962
1240
  }
963
- return produced;
964
- };
965
- const applyPackages = async (pluginId, scope) => {
966
- const key = `${pluginId}\0${scope}`;
967
- const previous = completedPackages.get(key);
968
- if (previous)
969
- return previous;
970
- return recordPackages(pluginId, scope, await packages.execute(pluginId, scope, token));
971
- };
972
- const blockPackages = (pluginId, scope, code) => completedPackages.get(`${pluginId}\0${scope}`)
973
- ?? recordPackages(pluginId, scope, packages?.blocked?.(pluginId, scope, code) ?? []);
974
- if (packages)
975
- runtime.nativeTargetExecution = {
976
- beforeApply: async (identity) => {
977
- const results = [];
978
- for (const target of packages.targets.filter((target) => target.pluginId === identity.pluginId
979
- && (target.scope === 'user' || target.scope === identity.scope)))
980
- results.push(...await applyPackages(target.pluginId, target.scope));
981
- return results;
982
- },
983
- blocked: (identity, code) => packages.targets.filter((target) => target.pluginId === identity.pluginId
984
- && (target.scope === 'user' || target.scope === identity.scope)).flatMap((target) => blockPackages(target.pluginId, target.scope, code === 'dependencyInstallFailed' ? 'dependencyApplyFailed' : code)),
985
- };
986
- while (pending.length) {
987
- const index = pending.findIndex((node) => {
988
- const groups = node.targets.filter(({ child, agent }) => agent !== 'generic' && !executedNativeChildren.has(child));
989
- const members = new Set([node, ...groups.flatMap(({ child }) => pending.filter((candidate) => candidate.targets.some((target) => target.child === child)))]);
990
- return [...members].every((member) => [...member.dependencies].every((key) => !pending.some((candidate) => !members.has(candidate) && `${candidate.pluginId}\0${candidate.scope}` === key)));
991
- });
992
- if (index < 0) {
993
- plan.receipt.blockers.push(diagnostic('dependencyContractInvalid'));
994
- break;
1241
+ for (const node of nodes.values()) {
1242
+ for (const { agent } of node.targets) {
1243
+ for (const provider of dependencyGraph.directProviders({ pluginId: node.pluginId, target: agent, scope: node.scope })) {
1244
+ node.dependencies.add(`${provider.pluginId}\0${provider.scope}`);
1245
+ }
1246
+ }
1247
+ if (node.scope === 'project' && node.targets.some(({ agent }) => ['codex', 'claude', 'copilot'].includes(agent))
1248
+ && nodes.has(`${node.pluginId}\0user`))
1249
+ node.dependencies.add(`${node.pluginId}\0user`);
1250
+ for (const dependency of node.packages?.flatMap((item) => item.dependencies) ?? []) {
1251
+ for (const provider of nodes.values())
1252
+ if (provider.pluginId === dependency)
1253
+ node.dependencies.add(`${dependency}\0${provider.scope}`);
1254
+ }
995
1255
  }
996
- const node = pending.splice(index, 1)[0];
997
- const key = `${node.pluginId}\0${node.scope}`;
998
- if (node.packages?.length && packages && !hasNative(node)) {
999
- if (failedNodes.has(key) || [...node.dependencies].some((dependency) => failedNodes.has(dependency))) {
1256
+ const pending = [...nodes.values()].sort((left, right) => left.scope === right.scope
1257
+ ? left.pluginId.localeCompare(right.pluginId) : left.scope === 'user' ? -1 : 1);
1258
+ const executedNativeChildren = new Set();
1259
+ const completedPackages = new Map();
1260
+ const recordPackages = (pluginId, scope, produced) => {
1261
+ const key = `${pluginId}\0${scope}`;
1262
+ completedPackages.set(key, produced);
1263
+ packageResults.push(...produced);
1264
+ if (produced.some((result) => result.state !== 'completed')) {
1000
1265
  failedPackages.add(key);
1001
1266
  failedNodes.add(key);
1002
- for (const target of node.packages)
1003
- blockPackages(target.pluginId, target.scope, 'dependencyApplyFailed');
1004
- plan.receipt.blockers.push(diagnostic('commandPackageProviderNotSatisfied', node.pluginId));
1005
1267
  }
1006
- else {
1007
- try {
1008
- const produced = [];
1268
+ return produced;
1269
+ };
1270
+ const applyPackages = async (pluginId, scope) => {
1271
+ const key = `${pluginId}\0${scope}`;
1272
+ const previous = completedPackages.get(key);
1273
+ if (previous)
1274
+ return previous;
1275
+ return recordPackages(pluginId, scope, await packages.execute(pluginId, scope, token));
1276
+ };
1277
+ const blockPackages = (pluginId, scope, code) => completedPackages.get(`${pluginId}\0${scope}`)
1278
+ ?? recordPackages(pluginId, scope, packages?.blocked?.(pluginId, scope, code) ?? []);
1279
+ if (packages)
1280
+ runtime.nativeTargetExecution = {
1281
+ beforeApply: async (identity) => {
1282
+ const results = [];
1283
+ for (const target of packages.targets.filter((target) => target.pluginId === identity.pluginId
1284
+ && (target.scope === 'user' || target.scope === identity.scope)))
1285
+ results.push(...await applyPackages(target.pluginId, target.scope));
1286
+ return results;
1287
+ },
1288
+ blocked: (identity, code) => packages.targets.filter((target) => target.pluginId === identity.pluginId
1289
+ && (target.scope === 'user' || target.scope === identity.scope)).flatMap((target) => blockPackages(target.pluginId, target.scope, code === 'dependencyInstallFailed' ? 'dependencyApplyFailed' : code)),
1290
+ };
1291
+ while (pending.length) {
1292
+ const index = pending.findIndex((node) => {
1293
+ const groups = node.targets.filter(({ child, agent }) => agent !== 'generic' && !executedNativeChildren.has(child));
1294
+ const members = new Set([node, ...groups.flatMap(({ child }) => pending.filter((candidate) => candidate.targets.some((target) => target.child === child)))]);
1295
+ return [...members].every((member) => [...member.dependencies].every((key) => !pending.some((candidate) => !members.has(candidate) && `${candidate.pluginId}\0${candidate.scope}` === key)));
1296
+ });
1297
+ if (index < 0) {
1298
+ plan.receipt.blockers.push(diagnostic('dependencyContractInvalid'));
1299
+ break;
1300
+ }
1301
+ const node = pending.splice(index, 1)[0];
1302
+ const key = `${node.pluginId}\0${node.scope}`;
1303
+ if (node.packages?.length && packages && !hasNative(node)) {
1304
+ if (failedNodes.has(key) || [...node.dependencies].some((dependency) => failedNodes.has(dependency))) {
1305
+ failedPackages.add(key);
1306
+ failedNodes.add(key);
1009
1307
  for (const target of node.packages)
1010
- produced.push(...await applyPackages(target.pluginId, target.scope));
1011
- if (produced.some((result) => result.state !== 'completed')) {
1308
+ blockPackages(target.pluginId, target.scope, 'dependencyApplyFailed');
1309
+ plan.receipt.blockers.push(diagnostic('commandPackageProviderNotSatisfied', node.pluginId));
1310
+ }
1311
+ else {
1312
+ try {
1313
+ const produced = [];
1314
+ for (const target of node.packages)
1315
+ produced.push(...await applyPackages(target.pluginId, target.scope));
1316
+ if (produced.some((result) => result.state !== 'completed')) {
1317
+ failedPackages.add(key);
1318
+ failedNodes.add(key);
1319
+ }
1320
+ }
1321
+ catch (error) {
1322
+ runtime.signal?.throwIfAborted();
1323
+ if (error instanceof Error && error.name === 'AbortError' || readSafeOperationError(error))
1324
+ throw error;
1012
1325
  failedPackages.add(key);
1013
1326
  failedNodes.add(key);
1327
+ plan.receipt.blockers.push(diagnostic('commandPackageApplyFailed', node.pluginId));
1014
1328
  }
1015
1329
  }
1016
- catch (error) {
1017
- runtime.signal?.throwIfAborted();
1018
- if (error instanceof Error && error.name === 'AbortError' || readSafeOperationError(error))
1019
- throw error;
1020
- failedPackages.add(key);
1021
- failedNodes.add(key);
1022
- plan.receipt.blockers.push(diagnostic('commandPackageApplyFailed', node.pluginId));
1023
- }
1024
1330
  }
1025
- }
1026
- for (const { child, agent } of node.targets) {
1027
- const native = agent !== 'generic';
1028
- if (native && executedNativeChildren.has(child))
1029
- continue;
1030
- if (native)
1031
- executedNativeChildren.add(child);
1032
- const result = await executeChild(child, native ? child.receipt.requestedTargets.map((target) => target.pluginId) : node.pluginId, agent);
1033
- for (const target of result.targetResults)
1034
- if (target.blockers.length || !['applied', 'no-op'].includes(target.execution)) {
1035
- failedNodes.add(`${target.pluginId}\0${target.scope}`);
1036
- failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
1037
- }
1331
+ for (const { child, agent } of node.targets) {
1332
+ const native = agent !== 'generic';
1333
+ if (native && executedNativeChildren.has(child))
1334
+ continue;
1335
+ if (native)
1336
+ executedNativeChildren.add(child);
1337
+ const result = await executeChild(child, native ? child.receipt.requestedTargets.map((target) => target.pluginId) : node.pluginId, agent);
1338
+ for (const target of result.targetResults)
1339
+ if (target.blockers.length || !['applied', 'no-op'].includes(target.execution)) {
1340
+ failedNodes.add(`${target.pluginId}\0${target.scope}`);
1341
+ failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
1342
+ }
1343
+ }
1038
1344
  }
1039
1345
  }
1040
1346
  const receipt = mergeReceipts(plan, results);
@@ -1045,29 +1351,44 @@ export async function executeJointRecovery(plan, execution) {
1045
1351
  receipt.ok &&= failedPackages.size === 0;
1046
1352
  receipt.outputsMayHaveChanged ||= packageResults.some((result) => result.state === 'completed');
1047
1353
  receipt.errors.push(...results.flatMap((result) => result.targetResults.flatMap((target) => target.blockers)));
1354
+ if (!receipt.ok && retriesFromRequestedRoots(receipt))
1355
+ useDeclaredRetryRoots(receipt);
1356
+ completedReceipt = receipt;
1357
+ if (interrupted)
1358
+ throw interrupted;
1359
+ runtime.signal?.throwIfAborted();
1048
1360
  const { cwd, scope, env, cliVersion } = joint.originalOptions;
1049
1361
  const context = joint.snapshot.context.context;
1050
1362
  let statusFailure;
1363
+ let statusFailureMessage = 'Could not read the final plugin status.';
1051
1364
  try {
1052
1365
  // The reviewed Catalog may still be readable after Active has moved. Bind the
1053
1366
  // final read to the current sources, once per binding across both scopes.
1054
1367
  const status = await measureRecoveryPerformanceStage(runtime, 'recovery.status', () => readRecoveryStatus({ cwd, scope, context, env, cliVersion, expectedProjectRoot: joint.snapshot.context.projectRoot,
1055
- catalogReadScope: new CatalogPreparationReadScope({ env }),
1056
- nativeCliRunner: runtime.nativeCliRunner, codexObservationSession: runtime.codexObservationSession }));
1368
+ catalogReadScope: new CatalogPreparationReadScope({ env, signal: runtime.signal }), signal: runtime.signal,
1369
+ nativeCliRunner: runtime.nativeCliRunner, ...(isInstallBatch(plan.command) ? {} : { codexObservationSession: runtime.codexObservationSession }) }));
1057
1370
  receipt.allSatisfied = status.allSatisfied;
1058
1371
  receipt.inSync = status.inSync;
1059
1372
  statusFailure = finalStatusReadFailure(status, receipt);
1060
1373
  }
1061
1374
  catch (error) {
1375
+ const interruption = recoveryInterruptionCode(error, runtime.signal);
1376
+ if (runtime.signal?.aborted || interruption === 'operationInterrupted')
1377
+ throw error;
1378
+ // All writes have settled. A failed final query leaves its own cleanup
1379
+ // uncertain without invalidating the previously verified target receipts.
1380
+ if (interruption === 'processCleanupUnconfirmed') {
1381
+ statusFailureMessage = 'Could not read the final plugin status. The status query process cleanup could not be confirmed.';
1382
+ }
1062
1383
  receipt.allSatisfied = null;
1063
1384
  receipt.inSync = null;
1064
1385
  statusFailure = diagnostic(readSafeOperationError(error)?.code ?? errorCode(error, 'statusUnavailable'));
1065
1386
  }
1066
1387
  if (statusFailure) {
1067
1388
  receipt.ok = false;
1068
- receipt.errors.push({ code: 'statusUnavailable', message: 'Could not read the final plugin status.',
1389
+ receipt.errors.push({ code: 'statusUnavailable', message: statusFailureMessage,
1069
1390
  subject: statusFailure.subject, detail: { reasonCode: statusFailure.code } });
1070
- receipt.recoveryActions.push(`aw plugin status --context ${context} --json`);
1391
+ receipt.recoveryActions.push(`aw plugin status --context ${recoveryStatusContext(receipt)} --json`);
1071
1392
  }
1072
1393
  return receipt;
1073
1394
  } });
@@ -1076,10 +1397,27 @@ export async function executeJointRecovery(plan, execution) {
1076
1397
  if (lockWaitStartedAt !== undefined) {
1077
1398
  await recordRecoveryPerformanceStage(performanceRuntime, 'recovery.lock.wait', 'failure', lockWaitStartedAt);
1078
1399
  }
1400
+ const code = recoveryInterruptionCode(error, performanceRuntime.signal);
1401
+ if (code) {
1402
+ const receipt = completedReceipt ?? structuredClone(plan.receipt);
1403
+ receipt.ok = false;
1404
+ receipt.allSatisfied = null;
1405
+ receipt.inSync = null;
1406
+ if (!receipt.errors.some((entry) => entry.code === code))
1407
+ receipt.errors.push(diagnostic(code));
1408
+ receipt.remainingTargets = receipt.targetResults.filter((target) => target.blockers.length || !['applied', 'no-op'].includes(target.execution))
1409
+ .map(({ pluginId, agent, scope, delivery }) => ({ pluginId, agent, scope, delivery }));
1410
+ throw new RecoveryInterruptedError(receipt, error);
1411
+ }
1079
1412
  throw error;
1080
1413
  }
1081
1414
  finally {
1082
- await plan.context.dispose();
1415
+ try {
1416
+ await lockedPlan?.context.dispose();
1417
+ }
1418
+ finally {
1419
+ await plan.context.dispose();
1420
+ }
1083
1421
  }
1084
1422
  }
1085
1423
  //# sourceMappingURL=joint-coordinator.js.map