@lesliechan721/aw 0.1.0-beta.82 → 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 (190) 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 +14 -3
  28. package/dist/src/commands/rebuild-platform-integration.js +240 -137
  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 +21 -5
  77. package/dist/src/recovery/coordinator.js +383 -151
  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 +681 -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/catalog-generation.d.ts +6 -0
  113. package/dist/src/tui/catalog-generation.js +22 -6
  114. package/dist/src/tui/catalog-generation.js.map +1 -1
  115. package/dist/src/tui/console-app-v4.d.ts +1 -1
  116. package/dist/src/tui/console-app-v4.js +139 -59
  117. package/dist/src/tui/console-app-v4.js.map +1 -1
  118. package/dist/src/tui/controller-runtime.js +145 -53
  119. package/dist/src/tui/controller-runtime.js.map +1 -1
  120. package/dist/src/tui/controller.d.ts +13 -4
  121. package/dist/src/tui/controller.js +241 -102
  122. package/dist/src/tui/controller.js.map +1 -1
  123. package/dist/src/tui/deployment-view.js +6 -1
  124. package/dist/src/tui/deployment-view.js.map +1 -1
  125. package/dist/src/tui/diagnostic-projection.d.ts +4 -2
  126. package/dist/src/tui/diagnostic-projection.js +40 -4
  127. package/dist/src/tui/diagnostic-projection.js.map +1 -1
  128. package/dist/src/tui/glossary.js +1 -0
  129. package/dist/src/tui/glossary.js.map +1 -1
  130. package/dist/src/tui/operation-diagnostic-screens.d.ts +1 -1
  131. package/dist/src/tui/operation-diagnostic-screens.js +3 -1
  132. package/dist/src/tui/operation-diagnostic-screens.js.map +1 -1
  133. package/dist/src/tui/operation-history.d.ts +6 -3
  134. package/dist/src/tui/operation-history.js +15 -2
  135. package/dist/src/tui/operation-history.js.map +1 -1
  136. package/dist/src/tui/scoped-flow.d.ts +3 -1
  137. package/dist/src/tui/scoped-flow.js +99 -1
  138. package/dist/src/tui/scoped-flow.js.map +1 -1
  139. package/dist/src/tui/session-console-app.d.ts +2 -0
  140. package/dist/src/tui/session-console-app.js +11 -0
  141. package/dist/src/tui/session-console-app.js.map +1 -1
  142. package/dist/src/types.d.ts +8 -1
  143. package/dist/src/types.js.map +1 -1
  144. package/dist/src/utils/aw-home-mutation-lock.js +2 -1
  145. package/dist/src/utils/aw-home-mutation-lock.js.map +1 -1
  146. package/dist/src/utils/catalog-generation-resolver.d.ts +1 -0
  147. package/dist/src/utils/catalog-generation-resolver.js +1 -0
  148. package/dist/src/utils/catalog-generation-resolver.js.map +1 -1
  149. package/dist/src/utils/catalog-operation-context.d.ts +11 -0
  150. package/dist/src/utils/catalog-operation-context.js +18 -3
  151. package/dist/src/utils/catalog-operation-context.js.map +1 -1
  152. package/dist/src/utils/catalog-source-references.js +2 -14
  153. package/dist/src/utils/catalog-source-references.js.map +1 -1
  154. package/dist/src/utils/component-resources.js +1 -1
  155. package/dist/src/utils/component-resources.js.map +1 -1
  156. package/dist/src/utils/managed-command-materialization.d.ts +2 -1
  157. package/dist/src/utils/managed-command-materialization.js +3 -3
  158. package/dist/src/utils/managed-command-materialization.js.map +1 -1
  159. package/dist/src/utils/managed-command-store.d.ts +6 -0
  160. package/dist/src/utils/managed-command-store.js +90 -18
  161. package/dist/src/utils/managed-command-store.js.map +1 -1
  162. package/dist/src/utils/multi-source-catalog.d.ts +2 -0
  163. package/dist/src/utils/multi-source-catalog.js +3 -2
  164. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  165. package/dist/src/utils/native-cli.d.ts +0 -19
  166. package/dist/src/utils/native-cli.js +2 -42
  167. package/dist/src/utils/native-cli.js.map +1 -1
  168. package/dist/src/utils/ownership.js +1 -1
  169. package/dist/src/utils/ownership.js.map +1 -1
  170. package/dist/src/utils/platform-empty-state.d.ts +1 -3
  171. package/dist/src/utils/platform-empty-state.js +1 -6
  172. package/dist/src/utils/platform-empty-state.js.map +1 -1
  173. package/dist/src/utils/plugin-config-write.d.ts +8 -0
  174. package/dist/src/utils/plugin-config-write.js +89 -25
  175. package/dist/src/utils/plugin-config-write.js.map +1 -1
  176. package/dist/src/utils/plugin-scripts.js +5 -0
  177. package/dist/src/utils/plugin-scripts.js.map +1 -1
  178. package/dist/src/utils/skill-invocation-warning.d.ts +15 -0
  179. package/dist/src/utils/skill-invocation-warning.js +42 -0
  180. package/dist/src/utils/skill-invocation-warning.js.map +1 -0
  181. package/package.json +3 -3
  182. package/dist/src/output/native-consent.d.ts +0 -2
  183. package/dist/src/output/native-consent.js +0 -5
  184. package/dist/src/output/native-consent.js.map +0 -1
  185. package/dist/src/platforms/gemini-activation.d.ts +0 -36
  186. package/dist/src/platforms/gemini-activation.js +0 -331
  187. package/dist/src/platforms/gemini-activation.js.map +0 -1
  188. package/dist/src/platforms/gemini-consent.d.ts +0 -8
  189. package/dist/src/platforms/gemini-consent.js +0 -81
  190. 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, 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, options, runtim
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, options, runtim
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,9 +354,19 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
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) });
358
+ checkInstallCatalog?.(demand.catalogOperationContext, requested);
238
359
  snapshot = { ...snapshot, [scope]: demand };
239
360
  }
361
+ else if (checkInstallCatalog && catalogReadScope
362
+ && proposed.errors.some((error) => ['sourceMissing', 'sourceActiveUnavailable', 'pluginUnavailable', 'sourceIdentityConflict'].includes(error.code))) {
363
+ // The same error on the accepted generation remains an ordinary planner diagnostic.
364
+ const configSnapshot = await readCatalogSourcesConfigSnapshot(options.env);
365
+ const requestedSources = new Set(proposed.roots.map((root) => parsePluginId(root).sourceId));
366
+ const sourceIds = configSnapshot.config.sources.map((source) => source.id)
367
+ .filter((id) => requestedSources.has(id) || requestedSources.has(undefined));
368
+ checkInstallCatalog(await catalogReadScope.resolve({ configSnapshot, sourceIds }), proposed.roots);
369
+ }
240
370
  }
241
371
  }
242
372
  else if (command === 'uninstall') {
@@ -281,7 +411,6 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
281
411
  }
282
412
  }
283
413
  const demand = deriveJointDemand(snapshot);
284
- errors.push(...demand.errors);
285
414
  const rootIds = [...new Set([...(snapshot.user.roots ?? []), ...(snapshot.project?.roots ?? [])]
286
415
  .map((root) => root.pluginId))];
287
416
  if (command !== 'install' && command !== 'uninstall') {
@@ -294,6 +423,15 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
294
423
  }) : rootIds;
295
424
  }
296
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)));
297
435
  const explicitlyRemoves = (item) => item.scope === scope && requested.includes(item.pluginId) && (!options.exactTargets
298
436
  || options.exactTargets.some((exact) => exact.pluginId === item.pluginId && exact.agent === item.agent
299
437
  && (!exact.scope || exact.scope === item.scope)));
@@ -315,23 +453,37 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
315
453
  && (requested.includes(placement.pluginId) || placement.contributions.some((item) => requested.includes(item.root))))))) {
316
454
  errors.push(diagnostic('invalidExactTargets', '精确重试目标不属于当前请求,请重新检查并选择。'));
317
455
  }
318
- const selected = demand.placements.filter((placement) => targets.includes(placement.target)
319
- && (!options.exactTargets || options.exactTargets.some((exact) => exact.agent === placement.target
320
- && (command === 'uninstall' ? previousDemand.placements.some((previous) => previous.pluginId === placement.pluginId
321
- && previous.target === placement.target && previous.contributions.some((item) => item.path.includes(exact.pluginId)
322
- && (!exact.scope || item.scope === exact.scope)))
323
- : (!exact.scope || placement.contributions.some((item) => item.scope === exact.scope))
324
- && (exact.pluginId === placement.pluginId || placement.contributions.some((item) => item.path.includes(exact.pluginId))))))
325
- && (command === 'uninstall' ? canReuseProviderAcrossScopes(placement.target)
326
- && !(options.force && requested.includes(placement.pluginId))
327
- && previousDemand.placements.some((previous) => previous.pluginId === placement.pluginId && previous.target === placement.target
328
- && previous.scope !== placement.scope && previous.contributions.some((item) => item.scope === scope && requested.includes(item.root)))
329
- : placement.contributions.some((item) => requested.includes(item.root)
330
- || 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
+ });
331
483
  const activationOnlyTargets = [];
332
484
  if (snapshot.project && !errors.length) {
333
- const sharedNative = selected.filter((item) => item.scope === 'user' && ['codex', 'claude', 'gemini', 'copilot'].includes(item.target)
334
- && 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'));
335
487
  if (sharedNative.length) {
336
488
  const expanded = { ...snapshot.project, roots: [...new Map(sharedNative.map((item) => [item.pluginId, {
337
489
  pluginId: item.pluginId, sourceId: item.plugin.sourceId, sourceState: 'ready', blockers: [], plugin: item.plugin,
@@ -340,6 +492,11 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
340
492
  const observation = await readScopedRecoveryStatus({ ...options, catalogReadScope, ...initialNativeReads, scope: 'project', demandOverride: expanded,
341
493
  cwd: snapshot.context.projectRoot, targets: undefined });
342
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
+ };
343
500
  const actual = observation.inventory?.find((entry) => entry.pluginId === item.pluginId)?.targetResults
344
501
  .find((entry) => entry.agent === item.target);
345
502
  if (item.target === 'codex') {
@@ -354,20 +511,23 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
354
511
  if (!surface.nativeKinds.length || !explicitlyDisabled && !retiringProjectComponents)
355
512
  continue;
356
513
  activationOnlyTargets.push({ pluginId: item.pluginId, platform: 'codex', scope: 'project' });
357
- selected.push({ ...item, scope: 'project' });
514
+ addProjectActivation();
358
515
  continue;
359
516
  }
360
517
  }
361
518
  if (actual?.content !== 'satisfied') {
362
519
  if (item.target !== 'generic')
363
520
  activationOnlyTargets.push({ pluginId: item.pluginId, platform: item.target, scope: 'project' });
364
- selected.push({ ...item, scope: 'project' });
521
+ addProjectActivation();
365
522
  }
366
523
  }
367
524
  }
368
525
  }
369
526
  const context = await createScopeContext({ ...options, scope });
527
+ if (command !== 'uninstall')
528
+ errors.push(...unplacedRoots.flatMap((root) => root.blockers));
370
529
  const baseDemand = scope === 'project' ? snapshot.project : snapshot.user;
530
+ const rebuildsRequestedRoots = command === 'reinstall' && !options.allowDependencySelectors && !options.existingOnly;
371
531
  const receipt = {
372
532
  schemaVersion: 1, kind: 'aw-recovery', command, scope, ok: false,
373
533
  intent: intentReceipt(observedIntent),
@@ -375,11 +535,16 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
375
535
  selection: { agents: targets, origin: options.targets ? 'argument' : targets.length ? 'preference' : 'none', preferences: snapshot.user.preferences.state },
376
536
  blockers: errors, errors, recoveryActions: [], declarationChanged: false, preferencesChanged: false,
377
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
+ } : {}),
378
543
  coverage: { scopes: snapshot.context.scopes, ...(snapshot.context.projectRoot ? { projectRoot: snapshot.context.projectRoot } : {}) },
379
544
  };
380
545
  const children = [];
381
546
  const { signal: _signal, ...executionOptions } = options;
382
- const joint = { snapshot, demand, removalDependencies: dependencyClosures, children, originalOptions: executionOptions,
547
+ const joint = { snapshot, demand, unplacedRoots, removalDependencies: dependencyClosures, selectedContributions, children, originalOptions: executionOptions,
383
548
  selectors: [...selectors], declaration, evidence };
384
549
  const plan = { command, options: { ...executionOptions, scope }, receipt, context, demand: baseDemand,
385
550
  originalIntent: observationEvidence(original.intent), preferencesEvidence: observationEvidence(snapshot.user.preferences),
@@ -390,7 +555,11 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
390
555
  || error.code === 'targetsNotConfigured' && !options.retireUnselectedTargets)
391
556
  || !snapshot.preferences || snapshot.user.roots === null || snapshot.project?.roots === null, joint };
392
557
  const dispose = context.dispose;
393
- 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
+ };
394
563
  if (plan.blockExecution)
395
564
  return plan;
396
565
  try {
@@ -477,16 +646,33 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
477
646
  }
478
647
  plan.dependencyCleanupTargets = automaticRetirements.map((item) => ({ pluginId: item.pluginId, agent: item.target, scope: item.scope }));
479
648
  const nativeTargets = targets.filter((target) => target !== 'generic');
480
- const targetGroups = [...(nativeTargets.length ? [nativeTargets] : []),
481
- ...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])];
482
654
  for (const currentScope of snapshot.context.scopes) {
483
- 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);
484
666
  const placements = selected.filter((item) => item.scope === currentScope && groupTargets.includes(item.target)
485
667
  && !(command === 'install' && scope === 'project' && currentScope === 'user'
486
668
  && currentStatus.observedTargets?.some((observed) => observed.pluginId === item.pluginId
487
- && 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)));
488
674
  if (!placements.length)
489
- continue;
675
+ return;
490
676
  const sourceDemand = currentScope === 'project' ? snapshot.project : snapshot.user;
491
677
  const childPlacements = [
492
678
  ...demand.placements.filter((item) => item.scope === currentScope && groupTargets.includes(item.target)),
@@ -501,7 +687,7 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
501
687
  roots: [...new Map(childPlacements.map((item) => [item.pluginId, { pluginId: item.pluginId, sourceId: item.plugin.sourceId,
502
688
  sourceState: 'ready', blockers: [], plugin: item.plugin }])).values()] };
503
689
  const child = await prepareScopedRecovery(command === 'reinstall' ? 'reinstall' : 'sync', [...new Set(placements.map((item) => item.pluginId))], { ...options, scope: currentScope, targets: groupTargets, all: false,
504
- sharedReferenceView,
690
+ sharedReferenceView, inheritedPortableProviderIds,
505
691
  cwd: snapshot.context.projectRoot ?? options.cwd, demandOverride: childDemand,
506
692
  exactTargets: placements.map((item) => ({ pluginId: item.pluginId, agent: item.target })),
507
693
  nativeActivationOnlyTargets: activationOnlyTargets.filter((item) => item.scope === currentScope
@@ -516,7 +702,10 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
516
702
  ? userProviders.filter((provider) => provider.target !== 'generic'
517
703
  && !placements.some((item) => item.pluginId === provider.pluginId && item.target === provider.target))
518
704
  .map((item) => ({ pluginId: item.pluginId, platform: item.target, scope: 'user' })) : [],
519
- }, 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);
520
709
  // Synthetic roots are only an execution projection, never persisted Intent.
521
710
  child.originalIntent = observationEvidence(sourceDemand.intent);
522
711
  if (options.existingOnly) {
@@ -528,9 +717,56 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
528
717
  }
529
718
  }
530
719
  }
531
- 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));
532
726
  }
727
+ else
728
+ for (const groupTargets of targetGroups)
729
+ await prepareGroup(groupTargets);
533
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
+ }
534
770
  const portableCandidates = children.flatMap((child) => child.portableGroups.flatMap((prepared) => prepared.targets
535
771
  .filter((target) => target.disposition !== 'remove')
536
772
  .map((target) => ({ child, prepared, target }))));
@@ -556,7 +792,7 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
556
792
  const scopedExtensions = (backend?.live?.components ?? backend?.components ?? []).some((component) => component.kind === 'ownership' && component.key !== 'native'
557
793
  && !component.key.startsWith('activation-') && !component.key.startsWith('marketplace-')
558
794
  && ['present', 'partial'].includes(component.state));
559
- 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))
560
796
  return false;
561
797
  return demand.placements.some((placement) => {
562
798
  if (placement.pluginId !== item.pluginId || placement.target !== item.agent)
@@ -648,12 +884,44 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
648
884
  }
649
885
  children.unshift(...cleanups);
650
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
+ }
651
919
  // The first preview already seals every target in its native group. A lone
652
- // Gemini/Copilot ensure group has no later sibling contribution to refresh here.
920
+ // Copilot ensure group has no later sibling contribution to refresh here.
653
921
  const onlyChild = children.length === 1 ? children[0] : undefined;
654
922
  const onlyGroup = onlyChild?.nativeGroups.length === 1 ? onlyChild.nativeGroups[0] : undefined;
655
923
  const singleNativePreviewComplete = !plan.blockExecution && onlyChild !== undefined && !onlyChild.blockExecution
656
- && onlyChild.command === 'sync' && (onlyGroup?.platform === 'gemini' || onlyGroup?.platform === 'copilot')
924
+ && onlyChild.command === 'sync' && onlyGroup?.platform === 'copilot'
657
925
  && onlyGroup.command === 'sync'
658
926
  && onlyGroup.preview.operationPlan !== undefined
659
927
  && (onlyGroup.preview.operationPlan.deploymentPlans?.length ?? 0) > 0
@@ -664,32 +932,44 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
664
932
  && onlyChild.portableResidues.length === 0;
665
933
  // Other scopes and groups can change shared descriptors, preApply actions
666
934
  // or retained packages. Refresh those previews before exposing Review.
667
- if (!singleNativePreviewComplete)
668
- for (const child of children)
669
- 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
+ }
670
957
  const preparedNativeTargets = children.flatMap((child) => child.receipt.targetResults)
671
958
  .filter((target) => target.delivery?.kind === 'native');
672
- const failedProviders = preparedNativeTargets.filter((target) => target.blockers.length > 0);
673
- for (const target of preparedNativeTargets) {
674
- const placement = demand.placements.find((item) => item.pluginId === target.pluginId
675
- && item.target === target.agent && item.scope === target.scope);
676
- if (!placement)
677
- continue;
678
- for (const provider of failedProviders) {
679
- if (provider === target || provider.agent !== target.agent)
680
- continue;
681
- const dependency = demand.placements.find((item) => item.pluginId === provider.pluginId
682
- && item.target === provider.agent && item.scope === provider.scope);
683
- if (!dependency?.contributions.some((contribution) => placement.contributions.some((parent) => parent.root === contribution.root && parent.scope === contribution.scope
684
- && parent.path.length < contribution.path.length
685
- && parent.path.every((pluginId, index) => pluginId === contribution.path[index]))))
686
- continue;
687
- for (const blocker of provider.blockers)
688
- if (!target.blockers.some((entry) => entry.code === blocker.code && entry.pluginId === provider.pluginId)) {
689
- target.blockers.push({ ...blocker, pluginId: provider.pluginId });
690
- }
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
+ }
691
972
  }
692
- }
693
973
  finalizePreparedPlatformRebuildSession(runtime.preparedArtifactRenderResults);
694
974
  plan.sourceRefreshes = [...new Map(children.flatMap((child) => child.sourceRefreshes).map((item) => [item.sourceId, item])).values()];
695
975
  plan.sourceRefreshFailures = [...new Map(children.flatMap((child) => child.sourceRefreshFailures).map((item) => [item.sourceId, item])).values()];
@@ -697,6 +977,8 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
697
977
  plan.warnings.push(...children.flatMap((child) => child.warnings));
698
978
  plan.plannedImpact.outputs = children.some((child) => child.plannedImpact.outputs);
699
979
  plan.receipt = mergeReceipts(plan, children.map((child) => child.receipt));
980
+ if (retriesFromRequestedRoots(plan.receipt) && plan.receipt.remainingTargets.length)
981
+ useDeclaredRetryRoots(plan.receipt);
700
982
  const observedManager = children.flatMap((child) => child.nativeGroups)
701
983
  .map((group) => group.preview.codexManagerPreview)
702
984
  .find((entry) => entry?.state === 'system');
@@ -713,20 +995,36 @@ async function prepareJointRecoveryInSession(command, selectors, options, runtim
713
995
  export async function executeJointRecovery(plan, execution) {
714
996
  const joint = plan.joint;
715
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;
716
1011
  let lockWaitStartedAt;
717
1012
  try {
718
1013
  if (plan.sourceRefreshes.length) {
719
1014
  plan.receipt.blockers.push(diagnostic('sourceRefreshConfirmationRequired'));
720
- 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;
721
1019
  }
722
1020
  lockWaitStartedAt = performance.now();
723
1021
  await recordRecoveryPerformanceStage(performanceRuntime, 'recovery.lock.wait', 'start', lockWaitStartedAt);
724
- 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,
725
1023
  action: async (token) => {
726
1024
  const acquiredAt = lockWaitStartedAt;
727
1025
  lockWaitStartedAt = undefined;
728
1026
  await recordRecoveryPerformanceStage(performanceRuntime, 'recovery.lock.wait', 'success', acquiredAt);
729
- 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));
730
1028
  const actual = preparation.snapshot;
731
1029
  const currentIntent = (plan.options.scope === 'project' ? actual.project : actual.user).intent;
732
1030
  plan.receipt.intent = intentReceipt(currentIntent);
@@ -734,30 +1032,33 @@ export async function executeJointRecovery(plan, execution) {
734
1032
  plan.receipt.blockers.push(describeStrongStateProblem({ kind: 'intent', scope: plan.options.scope,
735
1033
  state: currentIntent.state, filePath: await resolveIntentPath(plan.options) }));
736
1034
  }
737
- if (snapshotEvidence(actual) !== joint.evidence) {
738
- plan.receipt.blockers.push(diagnostic('operationReviewStale'));
739
- return mergeReceipts(plan, []);
740
- }
1035
+ if (snapshotEvidence(actual) !== joint.evidence)
1036
+ return blockedBeforeDeployment(plan);
741
1037
  if (plan.blockExecution)
742
1038
  return plan.receipt;
743
1039
  // Recheck all backend candidates before any strong-state or output write.
744
1040
  (execution.runtime?.codexObservationSession ?? plan.runtime.codexObservationSession)?.invalidate();
745
- 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));
746
1042
  const stable = !checked.blockExecution && JSON.stringify(describeRecoveryPlan(plan)) === JSON.stringify(describeRecoveryPlan(checked));
747
- await checked.context.dispose();
748
- if (!stable) {
749
- plan.receipt.blockers.push(diagnostic('operationReviewStale'));
750
- return mergeReceipts(plan, []);
751
- }
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();
752
1049
  if (joint.originalOptions.preferences) {
753
1050
  const saved = await writePreferences({ ...plan.options, scope: 'user', token }, joint.originalOptions.preferences);
754
1051
  plan.receipt.preferencesChanged = saved.changed;
755
1052
  const committed = await observePreferences({ ...plan.options, scope: 'user' });
1053
+ plan.receipt.selection.preferences = committed.state;
756
1054
  if (committed.state !== 'valid') {
757
- plan.receipt.blockers.push(diagnostic('deploymentPreferencesUnavailable'));
758
- 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');
759
1060
  }
760
- for (const child of joint.children) {
1061
+ for (const child of children) {
761
1062
  child.demand.preferences = committed;
762
1063
  if (child.options.demandOverride)
763
1064
  child.options.demandOverride.preferences = committed;
@@ -770,11 +1071,13 @@ export async function executeJointRecovery(plan, execution) {
770
1071
  const committed = await observeIntent({ ...plan.options, scope: joint.declaration.scope });
771
1072
  plan.receipt.intent = intentReceipt(committed);
772
1073
  if (committed.state !== 'valid') {
773
- plan.receipt.blockers.push(committed.state === 'absent'
1074
+ return blockedBeforeDeployment(plan, committed.state === 'absent'
774
1075
  ? diagnostic('pluginIntentStateUnavailable', '保存后未找到插件声明,未执行输出变更。')
775
1076
  : describeStrongStateProblem({ kind: 'intent', scope: joint.declaration.scope,
776
- state: committed.state, filePath: await resolveIntentPath({ ...plan.options, scope: joint.declaration.scope }) }));
777
- 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');
778
1081
  }
779
1082
  }
780
1083
  const results = joint.children.filter((child) => child.blockExecution
@@ -783,248 +1086,261 @@ export async function executeJointRecovery(plan, execution) {
783
1086
  const failedPackages = new Set();
784
1087
  const failedNodes = new Set();
785
1088
  const packageResults = [];
786
- const runtime = { ...plan.runtime, ...execution.runtime, awHomeMutationToken: token };
1089
+ const runtime = { ...performanceRuntime, awHomeMutationToken: token };
787
1090
  runtime.preApplyExecutionCache ??= new Map();
788
1091
  runtime.managedCommandProducerCache ??= new Map();
789
- const packages = runtime.configApplyPackages;
790
- const failedCleanups = [];
791
- const executeChild = async (child, pluginIds, agent) => {
792
- const currentIntent = await observeIntent(child.options);
793
- if (!joint.originalOptions.existingOnly)
794
- child.demand.intent = currentIntent;
795
- const fresh = await measureRecoveryPerformanceStage(runtime, 'recovery.child.plan', () => prepareScopedRecovery(child.command, typeof pluginIds === 'string' ? [pluginIds] : pluginIds, {
796
- ...child.options, targets: agent !== 'generic' ? child.options.targets : [agent], all: false,
797
- exactTargets: child.options.exactTargets?.filter((target) => (typeof pluginIds === 'string' ? [pluginIds] : pluginIds).includes(target.pluginId)),
798
- }, runtime));
799
- fresh.originalIntent = observationEvidence(currentIntent);
800
- for (const target of fresh.receipt.targetResults) {
801
- const reviewed = child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent);
802
- if (reviewed?.relation === 'dependency') {
803
- target.relation = 'dependency';
804
- target.requiredBy = [...reviewed.requiredBy];
805
- }
806
- // Native/provider observations are refreshed after preceding nodes.
807
- // Keep only joint constraints and an already failed script gate.
808
- target.blockers.push(...(reviewed?.blockers ?? []).filter((error) => reviewed?.execution === 'failed'
809
- || ['configApplyRequiresExistingOutput', 'crossScopeSkillCollision', 'targetPlacementConflict',
810
- 'preApplyAuthorizationRequired', 'nativeToolAuthorizationRequired', 'providerSwitchPreApplyFailed', 'dependencyStillRequired'].includes(error.code)));
811
- if (reviewed?.execution === 'failed') {
812
- target.execution = 'failed';
813
- if (reviewed.backend)
814
- target.backend = reviewed.backend;
815
- }
816
- 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))))) {
817
- target.blockers.push(diagnostic('providerSwitchCleanupFailed'));
818
- }
819
- const dependencies = joint.demand.placements.filter((placement) => placement.target === target.agent
820
- && placement.contributions.some((contribution) => contribution.path.includes(target.pluginId)));
821
- if (failedPackages.has(`${target.pluginId}\0${target.scope}`) || failedPackages.has(`${target.pluginId}\0user`)
822
- || dependencies.some((item) => failedPackages.has(`${item.pluginId}\0${item.scope}`))) {
823
- target.blockers.push(diagnostic('commandPackageProviderNotSatisfied'));
824
- }
825
- const failedDependency = dependencies.find((placement) => failedProviders.has(`${placement.pluginId}\0${placement.target}\0${placement.scope}`));
826
- if (failedDependency) {
827
- target.blockers.push(diagnostic(target.scope === 'project' && failedDependency.scope === 'user'
828
- ? '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
+ }
829
1149
  }
830
- }
831
- const result = await measureRecoveryPerformanceStage(runtime, 'recovery.child.execute', () => executeScopedRecovery(fresh, { ...execution, runtime }));
832
- if (joint.originalOptions.existingOnly)
833
- for (const target of result.targetResults) {
834
- 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'));
835
1173
  continue;
836
- target.blockers = target.blockers.map((error) => error.code === 'dependencyInstallFailed'
837
- ? diagnostic('dependencyApplyFailed', `依赖提供者未完成。恢复后重试 aw plugin sync ${target.pluginId} --context ${target.scope} --target ${target.agent} --yes`)
838
- : error);
839
- if (target.execution === 'failed')
840
- target.execution = 'not-run';
841
- }
842
- results.push(result);
843
- return result;
844
- };
845
- // Provider changes can remove a working output. Complete the replacement's
846
- // authorization and scripts first, sharing the normal execution cache.
847
- const cleanupChildren = joint.children.filter((child) => child.command === 'cleanup');
848
- const replacementFailures = new Set();
849
- for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
850
- for (const target of child.receipt.targetResults) {
851
- if (replacementFailures.has(`${target.pluginId}\0${target.agent}`)) {
852
- target.blockers.push(diagnostic('dependencyApplyFailed'));
853
- 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}`);
854
1191
  }
855
- if (child.options.nativeActivationOnlyTargets?.some((item) => item.pluginId === target.pluginId
856
- && item.platform === target.agent && item.scope === target.scope))
857
- continue;
858
- if (!cleanupChildren.some((cleanup) => cleanup.receipt.requestedTargets.some((old) => old.pluginId === target.pluginId)))
859
- continue;
860
- const failure = target.blockers[0]?.code ?? await executeRecoveryPreApply({ ...child,
861
- options: { ...child.options, yes: execution.yes ?? plan.options.yes },
862
- }, target.pluginId, target.agent, runtime);
863
- if (!failure)
864
- continue;
865
- target.blockers.push(diagnostic(failure));
866
- if (failure !== 'preApplyAuthorizationRequired' && failure !== 'nativeToolAuthorizationRequired')
867
- target.execution = 'failed';
868
- replacementFailures.add(`${target.pluginId}\0${target.agent}`);
869
- failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
870
- failedNodes.add(`${target.pluginId}\0${target.scope}`);
871
1192
  }
872
- }
873
- // Target exits can replace one Agent with another. Preserve the reviewed
874
- // old output when its corresponding replacement cannot run.
875
- for (const child of joint.children.filter((child) => child.command === 'cleanup')) {
876
- for (const target of child.receipt.requestedTargets) {
877
- if (plan.command === 'uninstall' && failedCleanups.some((failed) => {
878
- if (failed.agent !== target.agent)
879
- return false;
880
- const required = joint.removalDependencies.get(failed.pluginId);
881
- return required?.includes(target.pluginId) || required === null
882
- && parsePluginId(failed.pluginId).sourceId === parsePluginId(target.pluginId).sourceId;
883
- })) {
884
- child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
885
- .blockers.push(diagnostic('dependencyStillRequired', '依赖者未完成删除,保留其依赖输出。'));
886
- }
887
- if ([...replacementFailures].some((failed) => failed.startsWith(`${target.pluginId}\0`)
888
- && (failed === `${target.pluginId}\0${target.agent}`
889
- || !joint.children.some((replacement) => replacement.command !== 'cleanup'
890
- && replacement.receipt.requestedTargets.some((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent))))) {
891
- child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
892
- .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);
893
1217
  }
894
- const result = await executeChild(child, target.pluginId, target.agent);
895
- if (!result.ok)
896
- failedCleanups.push(...result.requestedTargets);
897
1218
  }
898
- }
899
- const nodes = new Map();
900
- const nodeFor = (pluginId, scope) => {
901
- const key = `${pluginId}\0${scope}`;
902
- let node = nodes.get(key);
903
- if (!node) {
904
- node = { pluginId, scope, targets: [], dependencies: new Set() };
905
- nodes.set(key, node);
906
- }
907
- return node;
908
- };
909
- for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
910
- for (const target of child.receipt.requestedTargets)
911
- nodeFor(target.pluginId, target.scope).targets.push({ child, agent: target.agent });
912
- }
913
- const hasNative = (node) => node.targets.some(({ agent }) => agent !== 'generic');
914
- for (const target of packages?.targets ?? []) {
915
- const sameScope = nodes.get(`${target.pluginId}\0${target.scope}`);
916
- const native = sameScope && hasNative(sameScope) ? sameScope
917
- : [...nodes.values()].find((node) => node.pluginId === target.pluginId && hasNative(node));
918
- const node = native ?? nodeFor(target.pluginId, target.scope);
919
- (node.packages ??= []).push(target);
920
- }
921
- for (const node of nodes.values()) {
922
- for (const { agent } of node.targets) {
923
- const plugin = joint.demand.placements.find((item) => item.pluginId === node.pluginId && item.target === agent && item.scope === node.scope)?.plugin;
924
- for (const name of plugin?.manifest.dependencies ?? []) {
925
- const pluginId = `${plugin.sourceId}/${name}`;
926
- const providers = joint.demand.placements.filter((item) => item.pluginId === pluginId && item.target === agent);
927
- const provider = providers.find((item) => item.scope === node.scope) ?? providers.find((item) => item.scope === 'user');
928
- if (provider)
929
- 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);
930
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 });
931
1232
  }
932
- if (node.scope === 'project' && node.targets.some(({ agent }) => ['codex', 'claude', 'gemini', 'copilot'].includes(agent))
933
- && nodes.has(`${node.pluginId}\0user`))
934
- node.dependencies.add(`${node.pluginId}\0user`);
935
- for (const dependency of node.packages?.flatMap((item) => item.dependencies) ?? []) {
936
- for (const provider of nodes.values())
937
- if (provider.pluginId === dependency)
938
- node.dependencies.add(`${dependency}\0${provider.scope}`);
939
- }
940
- }
941
- const pending = [...nodes.values()].sort((left, right) => left.scope === right.scope
942
- ? left.pluginId.localeCompare(right.pluginId) : left.scope === 'user' ? -1 : 1);
943
- const executedNativeChildren = new Set();
944
- const completedPackages = new Map();
945
- const recordPackages = (pluginId, scope, produced) => {
946
- const key = `${pluginId}\0${scope}`;
947
- completedPackages.set(key, produced);
948
- packageResults.push(...produced);
949
- if (produced.some((result) => result.state !== 'completed')) {
950
- failedPackages.add(key);
951
- 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);
952
1240
  }
953
- return produced;
954
- };
955
- const applyPackages = async (pluginId, scope) => {
956
- const key = `${pluginId}\0${scope}`;
957
- const previous = completedPackages.get(key);
958
- if (previous)
959
- return previous;
960
- return recordPackages(pluginId, scope, await packages.execute(pluginId, scope, token));
961
- };
962
- const blockPackages = (pluginId, scope, code) => completedPackages.get(`${pluginId}\0${scope}`)
963
- ?? recordPackages(pluginId, scope, packages?.blocked?.(pluginId, scope, code) ?? []);
964
- if (packages)
965
- runtime.nativeTargetExecution = {
966
- beforeApply: async (identity) => {
967
- const results = [];
968
- for (const target of packages.targets.filter((target) => target.pluginId === identity.pluginId
969
- && (target.scope === 'user' || target.scope === identity.scope)))
970
- results.push(...await applyPackages(target.pluginId, target.scope));
971
- return results;
972
- },
973
- blocked: (identity, code) => packages.targets.filter((target) => target.pluginId === identity.pluginId
974
- && (target.scope === 'user' || target.scope === identity.scope)).flatMap((target) => blockPackages(target.pluginId, target.scope, code === 'dependencyInstallFailed' ? 'dependencyApplyFailed' : code)),
975
- };
976
- while (pending.length) {
977
- const index = pending.findIndex((node) => {
978
- const groups = node.targets.filter(({ child, agent }) => agent !== 'generic' && !executedNativeChildren.has(child));
979
- const members = new Set([node, ...groups.flatMap(({ child }) => pending.filter((candidate) => candidate.targets.some((target) => target.child === child)))]);
980
- return [...members].every((member) => [...member.dependencies].every((key) => !pending.some((candidate) => !members.has(candidate) && `${candidate.pluginId}\0${candidate.scope}` === key)));
981
- });
982
- if (index < 0) {
983
- plan.receipt.blockers.push(diagnostic('dependencyContractInvalid'));
984
- 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
+ }
985
1255
  }
986
- const node = pending.splice(index, 1)[0];
987
- const key = `${node.pluginId}\0${node.scope}`;
988
- if (node.packages?.length && packages && !hasNative(node)) {
989
- 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')) {
990
1265
  failedPackages.add(key);
991
1266
  failedNodes.add(key);
992
- for (const target of node.packages)
993
- blockPackages(target.pluginId, target.scope, 'dependencyApplyFailed');
994
- plan.receipt.blockers.push(diagnostic('commandPackageProviderNotSatisfied', node.pluginId));
995
1267
  }
996
- else {
997
- try {
998
- 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);
999
1307
  for (const target of node.packages)
1000
- produced.push(...await applyPackages(target.pluginId, target.scope));
1001
- 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;
1002
1325
  failedPackages.add(key);
1003
1326
  failedNodes.add(key);
1327
+ plan.receipt.blockers.push(diagnostic('commandPackageApplyFailed', node.pluginId));
1004
1328
  }
1005
1329
  }
1006
- catch (error) {
1007
- runtime.signal?.throwIfAborted();
1008
- if (error instanceof Error && error.name === 'AbortError' || readSafeOperationError(error))
1009
- throw error;
1010
- failedPackages.add(key);
1011
- failedNodes.add(key);
1012
- plan.receipt.blockers.push(diagnostic('commandPackageApplyFailed', node.pluginId));
1013
- }
1014
1330
  }
1015
- }
1016
- for (const { child, agent } of node.targets) {
1017
- const native = agent !== 'generic';
1018
- if (native && executedNativeChildren.has(child))
1019
- continue;
1020
- if (native)
1021
- executedNativeChildren.add(child);
1022
- const result = await executeChild(child, native ? child.receipt.requestedTargets.map((target) => target.pluginId) : node.pluginId, agent);
1023
- for (const target of result.targetResults)
1024
- if (target.blockers.length || !['applied', 'no-op'].includes(target.execution)) {
1025
- failedNodes.add(`${target.pluginId}\0${target.scope}`);
1026
- failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
1027
- }
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
+ }
1028
1344
  }
1029
1345
  }
1030
1346
  const receipt = mergeReceipts(plan, results);
@@ -1035,29 +1351,44 @@ export async function executeJointRecovery(plan, execution) {
1035
1351
  receipt.ok &&= failedPackages.size === 0;
1036
1352
  receipt.outputsMayHaveChanged ||= packageResults.some((result) => result.state === 'completed');
1037
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();
1038
1360
  const { cwd, scope, env, cliVersion } = joint.originalOptions;
1039
1361
  const context = joint.snapshot.context.context;
1040
1362
  let statusFailure;
1363
+ let statusFailureMessage = 'Could not read the final plugin status.';
1041
1364
  try {
1042
1365
  // The reviewed Catalog may still be readable after Active has moved. Bind the
1043
1366
  // final read to the current sources, once per binding across both scopes.
1044
1367
  const status = await measureRecoveryPerformanceStage(runtime, 'recovery.status', () => readRecoveryStatus({ cwd, scope, context, env, cliVersion, expectedProjectRoot: joint.snapshot.context.projectRoot,
1045
- catalogReadScope: new CatalogPreparationReadScope({ env }),
1046
- 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 }) }));
1047
1370
  receipt.allSatisfied = status.allSatisfied;
1048
1371
  receipt.inSync = status.inSync;
1049
1372
  statusFailure = finalStatusReadFailure(status, receipt);
1050
1373
  }
1051
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
+ }
1052
1383
  receipt.allSatisfied = null;
1053
1384
  receipt.inSync = null;
1054
1385
  statusFailure = diagnostic(readSafeOperationError(error)?.code ?? errorCode(error, 'statusUnavailable'));
1055
1386
  }
1056
1387
  if (statusFailure) {
1057
1388
  receipt.ok = false;
1058
- receipt.errors.push({ code: 'statusUnavailable', message: 'Could not read the final plugin status.',
1389
+ receipt.errors.push({ code: 'statusUnavailable', message: statusFailureMessage,
1059
1390
  subject: statusFailure.subject, detail: { reasonCode: statusFailure.code } });
1060
- receipt.recoveryActions.push(`aw plugin status --context ${context} --json`);
1391
+ receipt.recoveryActions.push(`aw plugin status --context ${recoveryStatusContext(receipt)} --json`);
1061
1392
  }
1062
1393
  return receipt;
1063
1394
  } });
@@ -1066,10 +1397,27 @@ export async function executeJointRecovery(plan, execution) {
1066
1397
  if (lockWaitStartedAt !== undefined) {
1067
1398
  await recordRecoveryPerformanceStage(performanceRuntime, 'recovery.lock.wait', 'failure', lockWaitStartedAt);
1068
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
+ }
1069
1412
  throw error;
1070
1413
  }
1071
1414
  finally {
1072
- await plan.context.dispose();
1415
+ try {
1416
+ await lockedPlan?.context.dispose();
1417
+ }
1418
+ finally {
1419
+ await plan.context.dispose();
1420
+ }
1073
1421
  }
1074
1422
  }
1075
1423
  //# sourceMappingURL=joint-coordinator.js.map