@lesliechan721/aw 0.1.0-beta.101 → 0.1.0-beta.103

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 (199) hide show
  1. package/dist/src/commands/catalog-generation.d.ts +2 -5
  2. package/dist/src/commands/catalog-generation.js +2 -4
  3. package/dist/src/commands/catalog-generation.js.map +1 -1
  4. package/dist/src/commands/lifecycle-command-package.d.ts +1 -1
  5. package/dist/src/commands/lifecycle-command-package.js +40 -2
  6. package/dist/src/commands/lifecycle-command-package.js.map +1 -1
  7. package/dist/src/commands/managed-commands.d.ts +2 -1
  8. package/dist/src/commands/managed-commands.js +4 -2
  9. package/dist/src/commands/managed-commands.js.map +1 -1
  10. package/dist/src/commands/operation-plan.d.ts +2 -8
  11. package/dist/src/commands/operation-plan.js.map +1 -1
  12. package/dist/src/commands/public-config-confirmation.d.ts +16 -10
  13. package/dist/src/commands/public-config-confirmation.js +87 -52
  14. package/dist/src/commands/public-config-confirmation.js.map +1 -1
  15. package/dist/src/commands/public-lifecycle.d.ts +1 -1
  16. package/dist/src/commands/public-lifecycle.js +36 -8
  17. package/dist/src/commands/public-lifecycle.js.map +1 -1
  18. package/dist/src/commands/public-plugin-query.js +6 -4
  19. package/dist/src/commands/public-plugin-query.js.map +1 -1
  20. package/dist/src/commands/rebuild-command.d.ts +22 -6
  21. package/dist/src/commands/rebuild-command.js +273 -557
  22. package/dist/src/commands/rebuild-command.js.map +1 -1
  23. package/dist/src/commands/rebuild-integration.d.ts +12 -39
  24. package/dist/src/commands/rebuild-integration.js +67 -303
  25. package/dist/src/commands/rebuild-integration.js.map +1 -1
  26. package/dist/src/commands/rebuild-operations.d.ts +0 -4
  27. package/dist/src/commands/rebuild-operations.js +9 -8
  28. package/dist/src/commands/rebuild-operations.js.map +1 -1
  29. package/dist/src/commands/rebuild-platform-integration.d.ts +14 -6
  30. package/dist/src/commands/rebuild-platform-integration.js +310 -101
  31. package/dist/src/commands/rebuild-platform-integration.js.map +1 -1
  32. package/dist/src/commands/status-v6.d.ts +3 -117
  33. package/dist/src/commands/status-v6.js +0 -2886
  34. package/dist/src/commands/status-v6.js.map +1 -1
  35. package/dist/src/commands/write-commands.js +0 -3
  36. package/dist/src/commands/write-commands.js.map +1 -1
  37. package/dist/src/index.js +44 -36
  38. package/dist/src/index.js.map +1 -1
  39. package/dist/src/intent/deployment-preferences.js +4 -3
  40. package/dist/src/intent/deployment-preferences.js.map +1 -1
  41. package/dist/src/intent/intent-store.js +3 -2
  42. package/dist/src/intent/intent-store.js.map +1 -1
  43. package/dist/src/output/command-receipt.d.ts +0 -6
  44. package/dist/src/output/command-receipt.js +0 -15
  45. package/dist/src/output/command-receipt.js.map +1 -1
  46. package/dist/src/output/receipt-projection.js +2 -1
  47. package/dist/src/output/receipt-projection.js.map +1 -1
  48. package/dist/src/platforms/capabilities.js +8 -2
  49. package/dist/src/platforms/capabilities.js.map +1 -1
  50. package/dist/src/platforms/contracts.d.ts +2 -0
  51. package/dist/src/platforms/discovery.d.ts +2 -0
  52. package/dist/src/platforms/discovery.js +95 -49
  53. package/dist/src/platforms/discovery.js.map +1 -1
  54. package/dist/src/platforms/inspection-native.d.ts +7 -1
  55. package/dist/src/platforms/inspection-native.js +6 -3
  56. package/dist/src/platforms/inspection-native.js.map +1 -1
  57. package/dist/src/platforms/inspection-query.d.ts +28 -14
  58. package/dist/src/platforms/inspection-query.js +102 -8
  59. package/dist/src/platforms/inspection-query.js.map +1 -1
  60. package/dist/src/platforms/lifecycle-native-services.d.ts +1 -1
  61. package/dist/src/platforms/lifecycle-native-services.js +7 -2
  62. package/dist/src/platforms/lifecycle-native-services.js.map +1 -1
  63. package/dist/src/platforms/lifecycle-native.js +20 -3
  64. package/dist/src/platforms/lifecycle-native.js.map +1 -1
  65. package/dist/src/platforms/lifecycle.js +5 -0
  66. package/dist/src/platforms/lifecycle.js.map +1 -1
  67. package/dist/src/platforms/supplement-state.js +11 -2
  68. package/dist/src/platforms/supplement-state.js.map +1 -1
  69. package/dist/src/portable/commands.d.ts +1 -0
  70. package/dist/src/portable/commands.js.map +1 -1
  71. package/dist/src/portable/materializer.d.ts +2 -0
  72. package/dist/src/portable/materializer.js +4 -4
  73. package/dist/src/portable/materializer.js.map +1 -1
  74. package/dist/src/portable/recovery.d.ts +1 -0
  75. package/dist/src/portable/recovery.js +3 -2
  76. package/dist/src/portable/recovery.js.map +1 -1
  77. package/dist/src/recovery/coordinator.d.ts +6 -1
  78. package/dist/src/recovery/coordinator.js +113 -108
  79. package/dist/src/recovery/coordinator.js.map +1 -1
  80. package/dist/src/recovery/demand.d.ts +1 -2
  81. package/dist/src/recovery/demand.js +4 -11
  82. package/dist/src/recovery/demand.js.map +1 -1
  83. package/dist/src/recovery/install-concurrency.d.ts +12 -0
  84. package/dist/src/recovery/install-concurrency.js +39 -0
  85. package/dist/src/recovery/install-concurrency.js.map +1 -1
  86. package/dist/src/recovery/joint-coordinator.d.ts +3 -4
  87. package/dist/src/recovery/joint-coordinator.js +324 -188
  88. package/dist/src/recovery/joint-coordinator.js.map +1 -1
  89. package/dist/src/recovery/joint-demand.js +4 -3
  90. package/dist/src/recovery/joint-demand.js.map +1 -1
  91. package/dist/src/recovery/joint-install-execution.js +46 -2
  92. package/dist/src/recovery/joint-install-execution.js.map +1 -1
  93. package/dist/src/recovery/joint-install-native-rebase.js +5 -2
  94. package/dist/src/recovery/joint-install-native-rebase.js.map +1 -1
  95. package/dist/src/recovery/locked-prepared-execution.d.ts +32 -0
  96. package/dist/src/recovery/locked-prepared-execution.js +67 -0
  97. package/dist/src/recovery/locked-prepared-execution.js.map +1 -0
  98. package/dist/src/recovery/status.d.ts +20 -6
  99. package/dist/src/recovery/status.js +153 -98
  100. package/dist/src/recovery/status.js.map +1 -1
  101. package/dist/src/review/skill-materialization.d.ts +1 -0
  102. package/dist/src/review/skill-materialization.js.map +1 -1
  103. package/dist/src/tui/console-app-v4.js +4 -14
  104. package/dist/src/tui/console-app-v4.js.map +1 -1
  105. package/dist/src/tui/controller-runtime.js +201 -57
  106. package/dist/src/tui/controller-runtime.js.map +1 -1
  107. package/dist/src/tui/controller.d.ts +8 -9
  108. package/dist/src/tui/controller.js +5 -6
  109. package/dist/src/tui/controller.js.map +1 -1
  110. package/dist/src/tui/operation-review-planner.js +14 -103
  111. package/dist/src/tui/operation-review-planner.js.map +1 -1
  112. package/dist/src/types.d.ts +5 -1
  113. package/dist/src/types.js.map +1 -1
  114. package/dist/src/utils/agent-version.js +1 -0
  115. package/dist/src/utils/agent-version.js.map +1 -1
  116. package/dist/src/utils/artifact-renderer.d.ts +10 -0
  117. package/dist/src/utils/artifact-renderer.js +28 -2
  118. package/dist/src/utils/artifact-renderer.js.map +1 -1
  119. package/dist/src/utils/aw-home-mutation-lock.d.ts +8 -0
  120. package/dist/src/utils/aw-home-mutation-lock.js +44 -8
  121. package/dist/src/utils/aw-home-mutation-lock.js.map +1 -1
  122. package/dist/src/utils/bundle-integrity.js +126 -33
  123. package/dist/src/utils/bundle-integrity.js.map +1 -1
  124. package/dist/src/utils/catalog-generation-resolver.d.ts +4 -0
  125. package/dist/src/utils/catalog-generation-resolver.js +4 -0
  126. package/dist/src/utils/catalog-generation-resolver.js.map +1 -1
  127. package/dist/src/utils/catalog-generation-service.d.ts +50 -11
  128. package/dist/src/utils/catalog-generation-service.js +276 -130
  129. package/dist/src/utils/catalog-generation-service.js.map +1 -1
  130. package/dist/src/utils/catalog-generation-state.js +6 -1
  131. package/dist/src/utils/catalog-generation-state.js.map +1 -1
  132. package/dist/src/utils/catalog-generation-store.d.ts +5 -0
  133. package/dist/src/utils/catalog-generation-store.js +36 -13
  134. package/dist/src/utils/catalog-generation-store.js.map +1 -1
  135. package/dist/src/utils/catalog-operation-context.d.ts +17 -3
  136. package/dist/src/utils/catalog-operation-context.js +220 -22
  137. package/dist/src/utils/catalog-operation-context.js.map +1 -1
  138. package/dist/src/utils/catalog-performance.d.ts +3 -0
  139. package/dist/src/utils/catalog-performance.js +26 -0
  140. package/dist/src/utils/catalog-performance.js.map +1 -0
  141. package/dist/src/utils/catalog-snapshot.d.ts +5 -2
  142. package/dist/src/utils/catalog-snapshot.js +3 -2
  143. package/dist/src/utils/catalog-snapshot.js.map +1 -1
  144. package/dist/src/utils/catalog-source-impact.d.ts +2 -1
  145. package/dist/src/utils/catalog-source-impact.js +2 -2
  146. package/dist/src/utils/catalog-source-impact.js.map +1 -1
  147. package/dist/src/utils/catalog-source-references.d.ts +2 -0
  148. package/dist/src/utils/catalog-source-references.js +284 -148
  149. package/dist/src/utils/catalog-source-references.js.map +1 -1
  150. package/dist/src/utils/codex-executable-discovery.js +1 -0
  151. package/dist/src/utils/codex-executable-discovery.js.map +1 -1
  152. package/dist/src/utils/codex-manager.js +1 -0
  153. package/dist/src/utils/codex-manager.js.map +1 -1
  154. package/dist/src/utils/codex-native-observation.d.ts +5 -2
  155. package/dist/src/utils/codex-native-observation.js +8 -4
  156. package/dist/src/utils/codex-native-observation.js.map +1 -1
  157. package/dist/src/utils/component-command-preparation.d.ts +1 -0
  158. package/dist/src/utils/component-command-preparation.js.map +1 -1
  159. package/dist/src/utils/git-catalog-provider.d.ts +38 -5
  160. package/dist/src/utils/git-catalog-provider.js +365 -156
  161. package/dist/src/utils/git-catalog-provider.js.map +1 -1
  162. package/dist/src/utils/managed-command-closure.d.ts +3 -1
  163. package/dist/src/utils/managed-command-closure.js +10 -5
  164. package/dist/src/utils/managed-command-closure.js.map +1 -1
  165. package/dist/src/utils/managed-command-materialization.d.ts +2 -0
  166. package/dist/src/utils/managed-command-materialization.js +4 -3
  167. package/dist/src/utils/managed-command-materialization.js.map +1 -1
  168. package/dist/src/utils/managed-command-preparation.js +1 -1
  169. package/dist/src/utils/managed-command-preparation.js.map +1 -1
  170. package/dist/src/utils/multi-source-catalog.d.ts +1 -1
  171. package/dist/src/utils/multi-source-catalog.js +3 -3
  172. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  173. package/dist/src/utils/native-cli.d.ts +6 -1
  174. package/dist/src/utils/native-cli.js +67 -32
  175. package/dist/src/utils/native-cli.js.map +1 -1
  176. package/dist/src/utils/platform-empty-state.d.ts +2 -0
  177. package/dist/src/utils/platform-empty-state.js +5 -5
  178. package/dist/src/utils/platform-empty-state.js.map +1 -1
  179. package/dist/src/utils/plugin-config-command-apply.d.ts +14 -4
  180. package/dist/src/utils/plugin-config-command-apply.js +49 -5
  181. package/dist/src/utils/plugin-config-command-apply.js.map +1 -1
  182. package/dist/src/utils/plugin-config-impact.d.ts +42 -0
  183. package/dist/src/utils/plugin-config-impact.js +170 -14
  184. package/dist/src/utils/plugin-config-impact.js.map +1 -1
  185. package/dist/src/utils/plugin-config-references.d.ts +3 -1
  186. package/dist/src/utils/plugin-config-references.js +3 -5
  187. package/dist/src/utils/plugin-config-references.js.map +1 -1
  188. package/dist/src/utils/plugin-config-write.d.ts +14 -5
  189. package/dist/src/utils/plugin-config-write.js +213 -117
  190. package/dist/src/utils/plugin-config-write.js.map +1 -1
  191. package/dist/src/utils/plugin-config.d.ts +2 -0
  192. package/dist/src/utils/plugin-config.js.map +1 -1
  193. package/dist/src/utils/plugin-scripts.d.ts +2 -0
  194. package/dist/src/utils/plugin-scripts.js +102 -3
  195. package/dist/src/utils/plugin-scripts.js.map +1 -1
  196. package/package.json +3 -5
  197. package/dist/src/utils/codex-reconciler.d.ts +0 -123
  198. package/dist/src/utils/codex-reconciler.js +0 -322
  199. package/dist/src/utils/codex-reconciler.js.map +0 -1
@@ -1,4 +1,8 @@
1
- import { finalizePreparedPlatformRebuildSession, recordPreparedGrokProjectRetirement } from '../commands/rebuild-integration.js';
1
+ import { isPermissionHost } from '../platforms/host-permission-policy.js';
2
+ import { resolveInvocationPolicy } from '@lesliechan721/aw-plugin-core/manifest';
3
+ import { selectPlatformInvocationPolicy } from '../generators/permissions.js';
4
+ import { handoffReviewedArtifactRenderResults } from '../utils/artifact-renderer.js';
5
+ import { disposePreparedPlatformRebuildSession, finalizePreparedPlatformRebuildSession, recordPreparedGrokProjectRetirement } from '../commands/rebuild-integration.js';
2
6
  import { commandPackageProviderSatisfied, preparePortableCommandWithdrawal, publishLifecycleCommandPackage } from '../commands/lifecycle-command-package.js';
3
7
  import { operationPlanNativeToolChanges } from '../commands/operation-plan.js';
4
8
  import { addRequirements } from '../commands/intent-command.js';
@@ -6,13 +10,13 @@ import { createEmptyIntent, calculateIntentDigest, removeIntentRoot } from '../i
6
10
  import { observeIntent, writeIntent, resolveIntentPath } from '../intent/intent-store.js';
7
11
  import { describeStrongStateProblem } from '../intent/diagnostics.js';
8
12
  import { observePreferences, normalizeAgents, writePreferences } from '../intent/deployment-preferences.js';
9
- import { withNativeObservationBatch } from '../platforms/inspection-query.js';
13
+ import { createNativeObservationBatch, withNativeObservationBatch } from '../platforms/inspection-query.js';
10
14
  import { createScopeContext } from '../intent/scope-context.js';
11
15
  import { reportCliPhase } from '../output/model.js';
12
- import { withAwHomeMutationLock } from '../utils/aw-home-mutation-lock.js';
16
+ import { LockedPreparedExecution } from './locked-prepared-execution.js';
17
+ import { advanceAwHomeMutationEpoch, isActiveAwHomeMutationToken, withAwHomeMutationLock } from '../utils/aw-home-mutation-lock.js';
13
18
  import { readSafeOperationError } from '../utils/safe-operation-diagnostic.js';
14
- import { createCodexNativeObservationSession } from '../utils/codex-native-observation.js';
15
- import { bindNativeCliRunnerSignal, getDefaultNativeCliRunner } from '../utils/native-cli.js';
19
+ import { getDefaultNativeCliRunner } from '../utils/native-cli.js';
16
20
  import { analyzeCodexSurface } from '../utils/codex-surface-analysis.js';
17
21
  import { CatalogPreparationReadScope, catalogOperationBinding, catalogOperationBindingsMatch, selectCatalogOperationContext } from '../utils/catalog-operation-context.js';
18
22
  import { readCatalogGenerationState } from '../utils/catalog-generation-state.js';
@@ -24,14 +28,15 @@ import { hasSharedUserPackage } from '../platforms/layout.js';
24
28
  import { preparePortableRecovery } from '../portable/recovery.js';
25
29
  import { canReuseProviderAcrossScopes, hasInheritableSkills, isInstalledSkillProvider, projectSkillCandidates, readJointDemand, deriveJointDemand, deriveSharedReferenceView, indexJointDependencies } from './joint-demand.js';
26
30
  import { checkFootprints, prepareScopedRecovery, executeScopedRecovery, executeRecoveryPreApply, refreshRecoveryNativePreviews, describeRecoveryPlan, errorCode, catalogRecheckDiagnostic, blockScopedRecoveryBeforeExecution } from './coordinator.js';
27
- import { isTargetObservationReadError, readScopedRecoveryStatus, readRecoveryStatus } from './status.js';
31
+ import { isTargetObservationReadError, readScopedRecoveryStatus, readRecoveryPlanningStatus, readRecoveryStatus } from './status.js';
28
32
  import { recoveryRetryDispositions, recoveryStatusContext, retriesFromRequestedRoots } from './receipt.js';
29
- import { limitInstallNativeRunner, mapInstallReads } from './install-concurrency.js';
33
+ import { createInstallPhaseBarrier, installConcurrencyLimits, limitInstallNativeRunner, mapInstallReads } from './install-concurrency.js';
30
34
  import { executeJointInstall } from './joint-install-execution.js';
31
35
  import { RecoveryInterruptedError, recoveryInterruptionCode } from './interruption.js';
32
36
  import { measureRecoveryPerformanceStage, recordRecoveryPerformanceStage } from './performance.js';
33
37
  import { resolvePluginMetaDependencyClosure } from '../utils/plugin-dependencies.js';
34
38
  import { isInstallConfigBlocked } from '../utils/plugin-config-diagnostics.js';
39
+ const SHARED_MARKETPLACE_PLATFORMS = new Set(['codex', 'claude', 'copilot']);
35
40
  const diagnostic = (code, message = code) => ({ code, message });
36
41
  function intentReceipt(observation) {
37
42
  return { state: observation.state,
@@ -61,6 +66,51 @@ function matchesExactContribution(placement, contribution, exact, reaches) {
61
66
  return placement.target === exact.agent && contribution.scope === exact.scope
62
67
  && reaches(contribution.root, exact.pluginId) && reaches(exact.pluginId, placement.pluginId);
63
68
  }
69
+ /** Select saved config consumers from the current locked status. The regular
70
+ * contribution filter still expands every selected consumer's execution providers. */
71
+ function selectPublishedConfigTargets(demand, status, requested, targets, dependencies) {
72
+ if (!demand.complete || !status.ok || !status.coverage.native || !status.inventory)
73
+ return;
74
+ const existing = new Set(status.existingTargets?.map(targetKey));
75
+ const observed = new Map(status.observedTargets?.map((item) => [targetKey(item), item]));
76
+ const selected = demand.placements.filter((item) => requested.includes(item.pluginId) && targets.includes(item.target));
77
+ const consumers = new Set(selected);
78
+ const dirty = [];
79
+ let clean = false;
80
+ let inputOrOutputDrift = false;
81
+ for (const item of selected) {
82
+ if (item.target === 'generic')
83
+ return;
84
+ const scopes = [...new Set(item.contributions.map((entry) => entry.scope))];
85
+ const positions = scopes.map((scope) => ({ pluginId: item.pluginId, agent: item.target, scope }));
86
+ const statuses = positions.map((position) => observed.get(targetKey(position)));
87
+ if (positions.some((position) => !existing.has(targetKey(position))) || statuses.some((target) => !target || target.delivery?.kind !== 'native' || !target.deploymentObservations?.length || target.blockers.length
88
+ || target.content !== 'satisfied' && target.content !== 'drifted'))
89
+ return;
90
+ // A provider outside the candidate set can still block a seemingly healthy consumer.
91
+ for (const provider of dependencies.providers(item)) {
92
+ if (consumers.has(provider))
93
+ continue;
94
+ for (const scope of new Set(provider.contributions.map((entry) => entry.scope))) {
95
+ const key = targetKey({ pluginId: provider.pluginId, agent: provider.target, scope });
96
+ const state = observed.get(key);
97
+ if (!existing.has(key) || state?.observation !== 'verified' || state.content !== 'satisfied' || state.blockers.length)
98
+ return;
99
+ }
100
+ }
101
+ const policy = resolveInvocationPolicy(item.plugin.manifest, item.target, item.pluginId);
102
+ const requiresPermissionReview = positions.some((position) => selectPlatformInvocationPolicy(policy, { pluginId: item.pluginId, target: item.target, scope: position.scope }, null).inactivePermissions.length > 0);
103
+ const drifted = statuses.some((target) => target?.content === 'drifted');
104
+ inputOrOutputDrift ||= drifted;
105
+ if (drifted || requiresPermissionReview || statuses.some((target) => target?.observation !== 'verified')) {
106
+ dirty.push(...positions);
107
+ }
108
+ else
109
+ clean = true;
110
+ }
111
+ // Keep the ordinary no-op receipt when there is no work to narrow.
112
+ return clean && inputOrOutputDrift ? dirty : undefined;
113
+ }
64
114
  function useDeclaredRetryRoots(receipt) {
65
115
  const configBlockedInstall = isInstallConfigBlocked(receipt);
66
116
  const status = `aw plugin status --context ${recoveryStatusContext(receipt)} --json`;
@@ -218,84 +268,66 @@ function blockedBeforeDeployment(plan, blocker = diagnostic('operationReviewStal
218
268
  });
219
269
  return receipt;
220
270
  }
221
- async function readJointPreparation(options, locked = false, suppliedReads) {
271
+ async function readJointPreparation(options, locked = false, suppliedReads, token) {
222
272
  // Reuse evidence for every read-only plan, including reinstall and uninstall.
223
273
  // This is independent of whether execution can use the parallel install scheduler.
224
- const catalogReadScope = (locked ? undefined : suppliedReads) ?? new CatalogPreparationReadScope(options);
274
+ const catalogReadScope = (!locked || suppliedReads?.belongsToLease(token) ? suppliedReads : undefined) ?? new CatalogPreparationReadScope(options);
225
275
  if (locked && options.catalogOperationContext) {
226
276
  // A caller may have reviewed a subset of sources. Rebind just those IDs under
227
277
  // the lock so a changed or removed source makes the existing Review stale.
228
278
  options = { ...options, catalogOperationContext: await catalogReadScope.rebind(options.catalogOperationContext) };
229
279
  }
230
- const manifestReads = new Map();
231
- const snapshot = await readJointDemand({ ...options, catalogReadScope, manifestReads });
232
- return { options, snapshot, catalogReadScope, manifestReads };
280
+ const snapshot = await readJointDemand({ ...options, catalogReadScope });
281
+ return { options, snapshot, catalogReadScope };
233
282
  }
234
283
  /** Complete requirements determine placement before execution selectors are applied. */
235
284
  export async function prepareJointRecovery(command, selectors, options, runtime, preparation) {
236
285
  const originalRunner = runtime.nativeCliRunner ?? getDefaultNativeCliRunner();
237
286
  runtime = { ...runtime, invocationCwd: runtime.invocationCwd ?? options.cwd, ...(isInstallBatch(command) ? { nativeCliRunner: limitInstallNativeRunner(originalRunner) } : {}),
238
287
  preparedArtifactRenderResults: runtime.preparedArtifactRenderResults ?? new Map() };
239
- const { snapshot, catalogReadScope, manifestReads } = preparation ?? await readJointPreparation(options, false, runtime.catalogReadScope);
240
- const prepare = async (current) => {
241
- const read = (nativeObservationBatch) => {
242
- if (nativeObservationBatch && command === 'install' && !preparation && !current.awHomeMutationToken) {
243
- nativeObservationBatch.initialInstallPreview = true;
244
- }
245
- return prepareJointRecoveryInSession(command, selectors, options, current, snapshot, { catalogReadScope, nativeObservationBatch }, manifestReads);
246
- };
247
- const plan = isInstallBatch(command)
248
- ? await withNativeObservationBatch({ runner: current.nativeCliRunner, signal: options.signal }, read) : await read();
249
- plan.joint.originalNativeRunner = originalRunner;
250
- return plan;
251
- };
252
- if (runtime.codexObservationSession)
253
- return prepare(runtime);
254
- const observationContext = await createScopeContext({ ...options, scope: snapshot.context.context });
255
- const executionRunner = runtime.nativeCliRunner ?? getDefaultNativeCliRunner();
256
- let sessionRunner = bindNativeCliRunnerSignal(executionRunner, options.signal);
257
- const session = await createCodexNativeObservationSession({ exactCwd: observationContext.executionCwd,
258
- env: observationContext.env, runner: (invocation) => sessionRunner(invocation), manager: runtime.codexManager });
259
- try {
260
- const plan = await prepare({ ...runtime, codexObservationSession: session });
261
- plan.joint.bindExecutionSignal = (signal) => { sessionRunner = bindNativeCliRunnerSignal(executionRunner, signal); };
262
- const dispose = plan.context.dispose;
263
- plan.context.dispose = async () => {
264
- try {
265
- await dispose();
266
- }
267
- finally {
268
- try {
269
- await session.dispose();
270
- }
271
- finally {
272
- await observationContext.dispose();
273
- }
274
- }
275
- };
276
- return plan;
277
- }
278
- catch (error) {
288
+ const locked = runtime.prepareLockedExecution === true && runtime.awHomeMutationToken !== undefined && isInstallBatch(command);
289
+ const reads = preparation ?? await readJointPreparation(options, locked, runtime.catalogReadScope, runtime.awHomeMutationToken);
290
+ const { snapshot, catalogReadScope } = reads;
291
+ options = reads.options;
292
+ const read = (nativeObservationBatch) => prepareJointRecoveryInSession(command, selectors, options, runtime, snapshot, { catalogReadScope, nativeObservationBatch });
293
+ let plan;
294
+ if (locked) {
295
+ const token = runtime.awHomeMutationToken;
296
+ const batch = createNativeObservationBatch({ phase: 'locked-execution', runner: runtime.nativeCliRunner,
297
+ codexExactCwd: snapshot.context.projectRoot ?? options.cwd,
298
+ signal: options.signal, onInvalidate: (impact) => advanceAwHomeMutationEpoch(token, impact === 'all' ? 'inputs' : 'outputs') });
299
+ const owner = new LockedPreparedExecution(token, batch);
279
300
  try {
280
- await session.dispose();
301
+ plan = await read(batch);
302
+ owner.bind(plan, JSON.stringify(describeRecoveryPlan(plan)));
281
303
  }
282
- finally {
283
- await observationContext.dispose();
304
+ catch (error) {
305
+ await batch.dispose();
306
+ throw error;
284
307
  }
285
- throw error;
286
308
  }
287
- finally {
288
- // The same observation session also serves confirmed writes, which cannot use preparation cancellation.
289
- sessionRunner = bindNativeCliRunnerSignal(executionRunner, runtime.signal);
309
+ else {
310
+ plan = await withNativeObservationBatch({ phase: preparation ? 'locked-execution' : 'unlocked-preview',
311
+ runner: runtime.nativeCliRunner, codexExactCwd: snapshot.context.projectRoot ?? options.cwd, signal: options.signal }, read);
290
312
  }
313
+ plan.joint.originalNativeRunner = originalRunner;
314
+ return plan;
291
315
  }
292
- async function prepareJointRecoveryInSession(command, selectors, { checkInstallCatalog, ...options }, runtime, snapshot, { catalogReadScope, nativeObservationBatch }, manifestReads) {
316
+ async function prepareJointRecoveryInSession(command, selectors, { checkInstallCatalog, ...options }, runtime, snapshot, { catalogReadScope, nativeObservationBatch }) {
293
317
  // Status observes saved requirements, before projecting proposed declarations.
294
318
  // Reuse them only within this preparation; execution reads them again under the lock.
295
319
  const savedDemand = snapshot;
296
320
  const initialNativeReads = { nativeCliRunner: nativeObservationBatch?.runner ?? runtime.nativeCliRunner,
297
- discoveryCache: nativeObservationBatch?.discoveryCache, nativeQuerySession: nativeObservationBatch?.nativeQuerySession,
298
- codexObservationSession: runtime.codexObservationSession };
321
+ nativeObservationBatch, nativeObservationExactCwd: snapshot.context.projectRoot ?? options.cwd };
322
+ const directSingleSelector = command === 'sync' && selectors.length === 1 && runtime.directCli
323
+ && runtime.prepareLockedExecution && runtime.awHomeMutationToken && nativeObservationBatch?.phase === 'locked-execution'
324
+ && !options.all && !options.existingOnly && !options.exactTargets && !options.retireUnselectedTargets && !options.preferences
325
+ ? selectors[0] : undefined;
326
+ const readPlanningStatus = (probes) => {
327
+ const statusOptions = { ...options, catalogReadScope, ...initialNativeReads, targets: undefined, projectSkillProbes: probes };
328
+ return directSingleSelector === undefined ? readRecoveryStatus(statusOptions, savedDemand)
329
+ : readRecoveryPlanningStatus(statusOptions, savedDemand, directSingleSelector);
330
+ };
299
331
  let observedStatus;
300
332
  const evidence = snapshotEvidence(snapshot);
301
333
  const scope = options.scope ?? snapshot.context.context;
@@ -326,7 +358,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
326
358
  value.sources[sourceId] = { logicalIdentity: identity };
327
359
  value.roots.push({ pluginId: item.pluginId });
328
360
  }
329
- snapshot = { ...snapshot, [currentScope]: await readDemand({ ...options, catalogReadScope, manifestReads, preferences: undefined, scope: currentScope, intent: asObservation(value) }) };
361
+ snapshot = { ...snapshot, [currentScope]: await readDemand({ ...options, catalogReadScope, preferences: undefined, scope: currentScope, intent: asObservation(value) }) };
330
362
  }
331
363
  if (snapshot.preferences)
332
364
  snapshot.preferences = { ...snapshot.preferences,
@@ -372,7 +404,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
372
404
  requested = proposed.roots;
373
405
  if (proposed.changed)
374
406
  declaration = { scope, value: proposed.state };
375
- const demand = await readDemand({ ...options, catalogReadScope, manifestReads, preferences: undefined, scope, intent: asObservation(proposed.state) });
407
+ const demand = await readDemand({ ...options, catalogReadScope, preferences: undefined, scope, intent: asObservation(proposed.state) });
376
408
  checkInstallCatalog?.(demand.catalogOperationContext, requested);
377
409
  snapshot = { ...snapshot, [scope]: demand };
378
410
  }
@@ -423,7 +455,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
423
455
  if (!errors.length) {
424
456
  if (original.intent.state === 'valid' && calculateIntentDigest(value) !== original.intent.digest)
425
457
  declaration = { scope, value };
426
- const demand = await readDemand({ ...options, catalogReadScope, manifestReads, preferences: undefined, scope, intent: asObservation(value) });
458
+ const demand = await readDemand({ ...options, catalogReadScope, preferences: undefined, scope, intent: asObservation(value) });
427
459
  snapshot = { ...snapshot, [scope]: demand };
428
460
  }
429
461
  }
@@ -432,8 +464,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
432
464
  const pendingUserSkills = [];
433
465
  const candidates = projectSkillCandidates(demand).filter((item) => !options.targets || options.targets.includes(item.target));
434
466
  if (candidates.length) {
435
- observedStatus ??= await readRecoveryStatus({ ...options, catalogReadScope, ...initialNativeReads, targets: undefined,
436
- projectSkillProbes: candidates }, savedDemand);
467
+ observedStatus ??= await readPlanningStatus(candidates);
437
468
  const providers = observedStatus.projectSkillProviders?.map((provider) => {
438
469
  if ((!provider.userNeedsRepair && !provider.userAbsent) || provider.projectCopy === 'blocked' || command !== 'sync' || options.existingOnly)
439
470
  return provider;
@@ -497,6 +528,9 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
497
528
  }
498
529
  const dependencyGraph = indexJointDependencies(demand);
499
530
  const { reaches } = dependencyGraph;
531
+ const exactContributions = options.exactTargets ?? (options.comparePublishedConfigOutputs && !pendingUserSkills.length
532
+ && runtime.awHomeMutationToken && isActiveAwHomeMutationToken(runtime.awHomeMutationToken) && observedStatus
533
+ ? selectPublishedConfigTargets(demand, observedStatus, requested, targets, dependencyGraph) : undefined);
500
534
  const requestedIds = new Set(requested);
501
535
  const selectedContributions = new Map();
502
536
  const selected = demand.placements.filter((placement) => {
@@ -510,7 +544,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
510
544
  && (!options.exactTargets || options.exactTargets.some((exact) => exact.agent === placement.target
511
545
  && previous.contributions.some((item) => item.path.includes(exact.pluginId) && (!exact.scope || item.scope === exact.scope)))));
512
546
  const contributions = placement.contributions.filter((item) => {
513
- const selects = (pluginId) => !options.exactTargets || options.exactTargets.some((exact) => matchesExactContribution(placement, item, exact, reaches)
547
+ const selects = (pluginId) => !exactContributions || exactContributions.some((exact) => matchesExactContribution(placement, item, exact, reaches)
514
548
  && (reaches(pluginId, exact.pluginId) || reaches(exact.pluginId, pluginId)));
515
549
  if (requestedIds.has(item.root) || options.existingOnly && requestedIds.has(placement.pluginId))
516
550
  return selects(item.root);
@@ -605,7 +639,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
605
639
  if (plan.blockExecution)
606
640
  return plan;
607
641
  try {
608
- const currentStatus = observedStatus ?? await readRecoveryStatus({ ...options, catalogReadScope, ...initialNativeReads, targets: undefined }, savedDemand);
642
+ const currentStatus = observedStatus ?? await readPlanningStatus();
609
643
  const sharedReferenceView = deriveSharedReferenceView(snapshot, demand, currentStatus);
610
644
  const ownsOutput = (item) => currentStatus.ownedTargets?.some((owned) => owned.pluginId === item.pluginId
611
645
  && owned.agent === item.agent && owned.scope === item.scope) === true;
@@ -707,11 +741,6 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
707
741
  const nativeTargets = targets.filter((target) => target !== 'generic');
708
742
  const batch = isInstallBatch(command);
709
743
  const hasSelectedScripts = selected.some((item) => item.plugin.manifest.scripts?.preApply);
710
- if (batch && nativeObservationBatch && [...demand.placements, ...selected].every(({ plugin }) => {
711
- const { command, scripts } = plugin.manifest;
712
- return command?.mode !== 'dynamic' && !scripts?.artifacts?.render && !scripts?.preApply && !scripts?.node?.build;
713
- }))
714
- nativeObservationBatch.scriptFreePlacement = true;
715
744
  const portableGenerations = new Map();
716
745
  const portableRenderResults = new Map();
717
746
  const targetGroups = batch ? [...nativeTargets, ...targets.filter((target) => target === 'generic')].map((target) => [target])
@@ -746,69 +775,136 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
746
775
  platforms.push(target);
747
776
  commandPackagePlatforms.set(pluginId, platforms);
748
777
  }
749
- runtime = { ...runtime, commandPackagePlatforms, retainCommandPackages: command === 'uninstall' };
778
+ runtime = { ...runtime, commandPackagePlatforms, retainCommandPackages: command === 'uninstall',
779
+ singleLockedSync: directSingleSelector === undefined ? undefined : true };
750
780
  plan.runtime = runtime;
751
- for (const currentScope of snapshot.context.scopes) {
752
- const prepareGroup = async (groupTargets) => {
753
- const inheritedPortableProviderIds = currentScope === 'user' && groupTargets.includes('generic')
754
- ? [...inheritedScripts].filter((item) => item.target === 'generic').map((item) => item.pluginId) : [];
755
- const placements = preparedPlacements.filter((item) => item.scope === currentScope && groupTargets.includes(item.target));
756
- if (!placements.length)
757
- return;
758
- const sourceDemand = currentScope === 'project' ? snapshot.project : snapshot.user;
759
- const childPlacements = [
760
- ...demand.placements.filter((item) => item.scope === currentScope && groupTargets.includes(item.target)),
761
- ...placements,
762
- ];
763
- const userProviders = demand.placements.filter((item) => item.scope === 'user' && groupTargets.includes(item.target)
764
- && !childPlacements.some((project) => project.scope === 'project' && project.pluginId === item.pluginId && project.target === item.target));
765
- const childDemand = { ...sourceDemand,
766
- targetRequirements: childPlacements.map((item) => ({ pluginId: item.pluginId, target: item.target })),
767
- userProviders: Object.fromEntries(groupTargets.map((target) => [target, userProviders
768
- .filter((item) => item.target === target).map((item) => item.pluginId)])),
769
- roots: [...new Map(childPlacements.map((item) => [item.pluginId, { pluginId: item.pluginId, sourceId: item.plugin.sourceId,
770
- sourceState: 'ready', blockers: [], plugin: item.plugin }])).values()] };
771
- const child = await prepareScopedRecovery(command === 'reinstall' ? 'reinstall' : 'sync', [...new Set(placements.map((item) => item.pluginId))], { ...options, scope: currentScope, targets: groupTargets, all: false,
772
- sharedReferenceView, inheritedPortableProviderIds,
773
- cwd: snapshot.context.projectRoot ?? options.cwd, demandOverride: childDemand,
774
- exactTargets: placements.map((item) => ({ pluginId: item.pluginId, agent: item.target })),
775
- nativeActivationOnlyTargets: activationOnlyTargets.filter((item) => item.scope === currentScope
776
- && placements.some((placement) => placement.pluginId === item.pluginId && placement.target === item.platform)),
777
- nativePlannedRetirements: command === 'uninstall' && currentScope === 'project'
778
- ? placements.filter((item) => item.target === 'codex'
779
- && currentStatus.ownedTargets?.some((owned) => owned.pluginId === item.pluginId && owned.agent === item.target && owned.scope === 'user')
780
- && !demand.placements.some((provider) => provider.pluginId === item.pluginId && provider.target === item.target && provider.scope === 'user'))
781
- .map((item) => ({ pluginId: item.pluginId, platform: 'codex', scope: 'user' })) : [],
782
- excludedPluginIds: currentScope === 'project' ? userProviders.map((item) => item.pluginId) : [],
783
- dependencyScopeOverrides: currentScope === 'project'
784
- ? userProviders.filter((provider) => provider.target !== 'generic'
785
- && !placements.some((item) => item.pluginId === provider.pluginId && item.target === provider.target))
786
- .map((item) => ({ pluginId: item.pluginId, platform: item.target, scope: 'user' })) : [],
787
- }, batch && groupTargets[0] !== 'generic'
788
- ? { ...runtime, batchInstallPlatform: groupTargets[0] } : runtime, { catalogReadScope, portableGenerations, portableRenderResults, nativeObservationBatch: batch || children.length === 0 ? nativeObservationBatch : undefined });
789
- // Track contexts as soon as acquired, including a sibling that finishes after cancellation.
790
- children.push(child);
791
- // Synthetic roots are only an execution projection, never persisted Intent.
792
- child.originalIntent = observationEvidence(sourceDemand.intent);
793
- if (options.existingOnly) {
794
- const observed = await readScopedRecoveryStatus({ ...options, catalogReadScope, nativeCliRunner: runtime.nativeCliRunner, codexObservationSession: runtime.codexObservationSession, scope: currentScope,
795
- cwd: snapshot.context.projectRoot ?? options.cwd, demandOverride: childDemand, targets: groupTargets });
796
- for (const item of child.receipt.targetResults) {
797
- if (!observed.existingTargets?.some((existing) => existing.pluginId === item.pluginId && existing.agent === item.agent && existing.scope === currentScope)) {
798
- item.blockers.push(diagnostic('configApplyRequiresExistingOutput', '输出缺失或不可确认,请先运行 sync。'));
799
- }
781
+ const prepareGroup = async (currentScope, groupTargets, awaitSharedNativePreparation, awaitLockedPeerRenderers) => {
782
+ const inheritedPortableProviderIds = currentScope === 'user' && groupTargets.includes('generic')
783
+ ? [...inheritedScripts].filter((item) => item.target === 'generic').map((item) => item.pluginId) : [];
784
+ const placements = preparedPlacements.filter((item) => item.scope === currentScope && groupTargets.includes(item.target));
785
+ if (!placements.length)
786
+ return;
787
+ const sourceDemand = currentScope === 'project' ? snapshot.project : snapshot.user;
788
+ const childPlacements = [
789
+ ...demand.placements.filter((item) => item.scope === currentScope && groupTargets.includes(item.target)),
790
+ ...placements,
791
+ ];
792
+ const userProviders = demand.placements.filter((item) => item.scope === 'user' && groupTargets.includes(item.target)
793
+ && !childPlacements.some((project) => project.scope === 'project' && project.pluginId === item.pluginId && project.target === item.target));
794
+ const childDemand = { ...sourceDemand,
795
+ targetRequirements: childPlacements.map((item) => ({ pluginId: item.pluginId, target: item.target })),
796
+ userProviders: Object.fromEntries(groupTargets.map((target) => [target, userProviders
797
+ .filter((item) => item.target === target).map((item) => item.pluginId)])),
798
+ roots: [...new Map(childPlacements.map((item) => [item.pluginId, { pluginId: item.pluginId, sourceId: item.plugin.sourceId,
799
+ sourceState: 'ready', blockers: [], plugin: item.plugin }])).values()] };
800
+ const child = await prepareScopedRecovery(command === 'reinstall' ? 'reinstall' : 'sync', [...new Set(placements.map((item) => item.pluginId))], { ...options, scope: currentScope, targets: groupTargets, all: false,
801
+ sharedReferenceView, inheritedPortableProviderIds,
802
+ cwd: snapshot.context.projectRoot ?? options.cwd, demandOverride: childDemand,
803
+ exactTargets: placements.map((item) => ({ pluginId: item.pluginId, agent: item.target })),
804
+ nativeActivationOnlyTargets: activationOnlyTargets.filter((item) => item.scope === currentScope
805
+ && placements.some((placement) => placement.pluginId === item.pluginId && placement.target === item.platform)),
806
+ nativePlannedRetirements: command === 'uninstall' && currentScope === 'project'
807
+ ? placements.filter((item) => item.target === 'codex'
808
+ && currentStatus.ownedTargets?.some((owned) => owned.pluginId === item.pluginId && owned.agent === item.target && owned.scope === 'user')
809
+ && !demand.placements.some((provider) => provider.pluginId === item.pluginId && provider.target === item.target && provider.scope === 'user'))
810
+ .map((item) => ({ pluginId: item.pluginId, platform: 'codex', scope: 'user' })) : [],
811
+ excludedPluginIds: currentScope === 'project' ? userProviders.map((item) => item.pluginId) : [],
812
+ dependencyScopeOverrides: currentScope === 'project'
813
+ ? userProviders.filter((provider) => provider.target !== 'generic'
814
+ && !placements.some((item) => item.pluginId === provider.pluginId && item.target === provider.target))
815
+ .map((item) => ({ pluginId: item.pluginId, platform: item.target, scope: 'user' })) : [],
816
+ }, batch && groupTargets[0] !== 'generic'
817
+ ? { ...runtime, batchInstallPlatform: groupTargets[0],
818
+ awaitSharedNativePreparation, awaitLockedPeerRenderers } : runtime, { catalogReadScope, portableGenerations, portableRenderResults, nativeObservationBatch });
819
+ // Track contexts as soon as acquired, including a sibling that finishes after cancellation.
820
+ children.push(child);
821
+ delete child.runtime.awaitSharedNativePreparation;
822
+ delete child.runtime.awaitLockedPeerRenderers;
823
+ // Synthetic roots are only an execution projection, never persisted Intent.
824
+ child.originalIntent = observationEvidence(sourceDemand.intent);
825
+ if (options.existingOnly) {
826
+ const observed = await readScopedRecoveryStatus({ ...options, catalogReadScope, ...initialNativeReads, scope: currentScope,
827
+ cwd: snapshot.context.projectRoot ?? options.cwd, demandOverride: childDemand, targets: groupTargets });
828
+ for (const item of child.receipt.targetResults) {
829
+ if (!observed.existingTargets?.some((existing) => existing.pluginId === item.pluginId && existing.agent === item.agent && existing.scope === currentScope)) {
830
+ item.blockers.push(diagnostic('configApplyRequiresExistingOutput', '输出缺失或不可确认,请先运行 sync。'));
800
831
  }
801
832
  }
802
- return child;
803
- };
804
- if (batch) {
805
- const start = children.length;
806
- const ordered = await mapInstallReads(targetGroups, prepareGroup, { signal: options.signal });
807
- children.splice(start, children.length - start, ...ordered.filter((child) => child !== undefined));
808
833
  }
809
- else
810
- for (const groupTargets of targetGroups)
811
- await prepareGroup(groupTargets);
834
+ return child;
835
+ };
836
+ const jobs = snapshot.context.scopes.flatMap((currentScope) => targetGroups.filter((groupTargets) => preparedPlacements.some((item) => item.scope === currentScope && groupTargets.includes(item.target)))
837
+ .map((groupTargets) => ({ currentScope, groupTargets })));
838
+ const nativeJobs = jobs.filter(({ groupTargets }) => !groupTargets.includes('generic'));
839
+ const sharesPlatform = new Set(nativeJobs.map(({ groupTargets }) => groupTargets[0])).size < nativeJobs.length;
840
+ const opaquePreparation = preparedPlacements.some(({ plugin }) => plugin.manifest.scripts?.artifacts?.render || plugin.manifest.command?.mode === 'dynamic');
841
+ if (batch && sharesPlatform && opaquePreparation) {
842
+ // All ordinary evidence is captured before any renderer may invalidate
843
+ // the live windows. The actual shared session still builds User before
844
+ // Project on each host; only its isolated read-only preparation overlaps.
845
+ const barrier = createInstallPhaseBarrier(nativeJobs.length, options.signal);
846
+ const tails = new Map();
847
+ const turns = new Map(nativeJobs.map((job) => {
848
+ const ticket = barrier.ticket();
849
+ const platform = job.groupTargets[0];
850
+ const previous = tails.get(platform);
851
+ let done;
852
+ tails.set(platform, new Promise((resolve) => { done = resolve; }));
853
+ return [job, { async wait() {
854
+ await ticket.wait();
855
+ await previous;
856
+ options.signal?.throwIfAborted();
857
+ }, finish() { ticket.arrive(); done(); } }];
858
+ }));
859
+ const results = new Map();
860
+ // Each participant must be able to reach the barrier; native process
861
+ // admission remains bounded by the operation runner.
862
+ await mapInstallReads(nativeJobs, async (job) => {
863
+ const turn = turns.get(job);
864
+ try {
865
+ results.set(job, await prepareGroup(job.currentScope, job.groupTargets, turn.wait));
866
+ }
867
+ finally {
868
+ turn.finish();
869
+ }
870
+ }, { signal: options.signal, limit: nativeJobs.length });
871
+ for (const job of jobs.filter(({ groupTargets }) => groupTargets.includes('generic'))) {
872
+ results.set(job, await prepareGroup(job.currentScope, job.groupTargets));
873
+ }
874
+ children.splice(0, children.length, ...jobs.flatMap((job) => {
875
+ const child = results.get(job);
876
+ return child ? [child] : [];
877
+ }));
878
+ }
879
+ else {
880
+ for (const currentScope of snapshot.context.scopes) {
881
+ const scoped = jobs.filter((job) => job.currentScope === currentScope);
882
+ if (batch) {
883
+ const start = children.length;
884
+ // Distinct hosts in one scope can finish their builds at different
885
+ // times. Seal only after all their renderers (including process-tree
886
+ // cleanup) have finished, so the last script cannot invalidate a
887
+ // sibling's just-read seal. No cross-scope or Portable plan opts in.
888
+ const peers = directSingleSelector !== undefined && opaquePreparation && !sharesPlatform
889
+ && scoped.length > 1 && scoped.length === jobs.length && nativeJobs.length === jobs.length
890
+ && scoped.length <= installConcurrencyLimits().reads
891
+ ? createInstallPhaseBarrier(scoped.length, options.signal) : undefined;
892
+ const tickets = peers ? new Map(scoped.map((job) => [job, peers.ticket()])) : undefined;
893
+ const ordered = await mapInstallReads(scoped, async (job) => {
894
+ const ticket = tickets?.get(job);
895
+ try {
896
+ return await prepareGroup(job.currentScope, job.groupTargets, undefined, ticket?.wait);
897
+ }
898
+ finally {
899
+ ticket?.arrive();
900
+ }
901
+ }, { signal: options.signal, ...(peers ? { limit: scoped.length } : {}) });
902
+ children.splice(start, children.length - start, ...ordered.filter((child) => child !== undefined));
903
+ }
904
+ else
905
+ for (const job of scoped)
906
+ await prepareGroup(job.currentScope, job.groupTargets);
907
+ }
812
908
  }
813
909
  if (hasSelectedScripts && (batch || command === 'reinstall')) {
814
910
  const projectPortable = children.find((child) => child.options.scope === 'project' && child.portableGroups.length);
@@ -825,8 +921,10 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
825
921
  await mapInstallReads(required.filter((id) => !reviewed.has(id)), async (selector) => {
826
922
  const provider = await preparePortableRecovery({ scope: 'user', context: providerContext, selector, agents: ['generic'],
827
923
  cliVersion: options.cliVersion, catalogOperationContext: snapshot.user.catalogOperationContext,
924
+ onScriptExecuted: () => { nativeObservationBatch?.invalidateAll(); catalogReadScope?.invalidateBundleReads(); },
828
925
  signal: options.signal }, catalogReadScope, portableGenerations, portableRenderResults);
829
926
  delete provider.options.signal;
927
+ delete provider.options.onScriptExecuted;
830
928
  reviewed.set(selector, provider);
831
929
  }, { signal: options.signal });
832
930
  const checks = new Map();
@@ -982,7 +1080,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
982
1080
  ordinaryNativeRemoval, sharedReferenceView,
983
1081
  scope: item.scope, cwd: snapshot.context.projectRoot ?? options.cwd, targets: [item.agent], all: false,
984
1082
  // Ordinary remove's force bypasses dependencies, never ownership checks.
985
- force: false, exactTargets: undefined, demandOverride: cleanupDemand }, runtime, { catalogReadScope });
1083
+ force: false, exactTargets: undefined, demandOverride: cleanupDemand }, runtime, { catalogReadScope, nativeObservationBatch });
986
1084
  if (automatic) {
987
1085
  for (const target of cleanup.receipt.targetResults) {
988
1086
  target.relation = 'dependency';
@@ -1026,44 +1124,39 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
1026
1124
  }
1027
1125
  joint.targetOrder = order;
1028
1126
  }
1029
- // The first preview already seals every target in its native group. A lone
1030
- // Copilot ensure group has no later sibling contribution to refresh here.
1031
- const onlyChild = children.length === 1 ? children[0] : undefined;
1032
- const onlyGroup = onlyChild?.nativeGroups.length === 1 ? onlyChild.nativeGroups[0] : undefined;
1033
- const singleNativePreviewComplete = !plan.blockExecution && onlyChild !== undefined && !onlyChild.blockExecution
1034
- && onlyChild.command === 'sync' && onlyGroup?.platform === 'copilot'
1035
- && onlyGroup.command === 'sync'
1036
- && onlyGroup.preview.operationPlan !== undefined
1037
- && (onlyGroup.preview.operationPlan.deploymentPlans?.length ?? 0) > 0
1038
- && onlyGroup.preview.operationPlan.deploymentPlans.every((deployment) => deployment.operation === 'ensure')
1039
- && onlyChild.receipt.targetResults.length > 0
1040
- && onlyChild.receipt.targetResults.every((target) => target.blockers.length === 0)
1041
- && onlyChild.portableGroups.length === 0 && onlyChild.portableProtectionGroups.length === 0
1042
- && onlyChild.portableResidues.length === 0;
1043
- // Other scopes and groups can change shared descriptors, preApply actions
1044
- // or retained packages. Refresh those previews before exposing Review.
1045
- if (!singleNativePreviewComplete) {
1046
- if (batch) {
1047
- const nativeChildren = children.filter((child) => child.nativeGroups.length);
1048
- const platforms = [...new Set(nativeChildren.map((child) => child.runtime.batchInstallPlatform))];
1049
- await mapInstallReads(platforms, async (platform) => {
1050
- const scoped = nativeChildren.filter((item) => item.runtime.batchInstallPlatform === platform);
1051
- // One complete ensure plan owns this platform session. Its initial preview already sealed
1052
- // every candidate; only another source or scope can contribute a later shared descriptor.
1053
- const only = scoped.length === 1 ? scoped[0] : undefined;
1054
- const preview = only?.nativeGroups.length === 1 ? only.nativeGroups[0].preview : undefined;
1055
- if (platform && only && !only.blockExecution && only.receipt.targetResults.every((target) => target.blockers.length === 0)
1056
- && preview?.operationPlan?.deploymentPlans?.length
1057
- && preview.operationPlan.deploymentPlans.every((deployment) => deployment.operation === 'ensure'))
1058
- return;
1059
- for (const child of scoped)
1060
- await refreshRecoveryNativePreviews(child, catalogReadScope, options.signal);
1061
- }, { signal: options.signal });
1127
+ // Each native group already sealed its targets. Rebuild only when a later group
1128
+ // can change its marketplace descriptor, script authorization or command-package review.
1129
+ const nativeGroups = children.flatMap((child) => child.nativeGroups.map((group) => ({ child, group })));
1130
+ const platforms = [...new Set(nativeGroups.map(({ group }) => group.platform))];
1131
+ const retained = (child) => child.nativeGroups.flatMap(({ preview }) => preview.operationPlan?.actions.filter((action) => action.kind === 'retainManagedCommandPackage').map((action) => action.pluginId) ?? []);
1132
+ const refresh = async (platform) => {
1133
+ const peers = nativeGroups.filter(({ group }) => group.platform === platform);
1134
+ for (const { child, group } of peers) {
1135
+ const crossScope = children.filter((sibling) => sibling.options.scope !== child.options.scope);
1136
+ const scripts = group.preview.operationPlan?.actions.filter((action) => action.kind === 'runPreApply') ?? [];
1137
+ const script = crossScope.some((sibling) => sibling.preApplyAuthorization?.some((authorization) => scripts.some((action) => action.pluginId === authorization.pluginId && action.platform === authorization.platform)));
1138
+ const deployments = group.preview.operationPlan?.deploymentPlans;
1139
+ const sharedPackage = crossScope.some((sibling) => retained(sibling).some((id) => group.pluginIds.includes(id))
1140
+ || retained(child).some((id) => sibling.receipt.requestedRoots.includes(id))
1141
+ || sibling.nativeGroups.some((peer) => peer.preview.operationPlan?.deploymentPlans?.some((other) => deployments?.some((current) => current.binding.physicalKey === other.binding.physicalKey
1142
+ && (current.evidence.retainPackage || other.evidence.retainPackage)))));
1143
+ const sealedEnsure = deployments?.length && deployments.every((deployment) => deployment.operation === 'ensure')
1144
+ && !child.blockExecution && child.receipt.targetResults.every((target) => target.blockers.length === 0);
1145
+ const sharedMarketplace = (platform === 'both' || SHARED_MARKETPLACE_PLATFORMS.has(platform))
1146
+ && (peers.length > 1 || !sealedEnsure);
1147
+ const sharedPermissions = isPermissionHost(platform) && peers.length > 1;
1148
+ if (script || sharedPackage || sharedMarketplace || sharedPermissions
1149
+ || group.preview.operationPlan && nativeObservationBatch
1150
+ && group.preview.nativePreviewEpoch !== nativeObservationBatch.writeEpoch) {
1151
+ await refreshRecoveryNativePreviews(child, catalogReadScope, options.signal, [group], nativeObservationBatch, true);
1152
+ }
1062
1153
  }
1063
- else
1064
- for (const child of children)
1065
- await refreshRecoveryNativePreviews(child, catalogReadScope, options.signal);
1066
- }
1154
+ };
1155
+ if (batch)
1156
+ await mapInstallReads(platforms, refresh, { signal: options.signal });
1157
+ else
1158
+ for (const platform of platforms)
1159
+ await refresh(platform);
1067
1160
  const preparedNativeTargets = children.flatMap((child) => child.receipt.targetResults)
1068
1161
  .filter((target) => target.delivery?.kind === 'native');
1069
1162
  const failedProviders = new Map(preparedNativeTargets.filter((target) => target.blockers.length > 0)
@@ -1119,12 +1212,6 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
1119
1212
  }
1120
1213
  if (retriesFromRequestedRoots(plan.receipt) && plan.receipt.remainingTargets.length)
1121
1214
  useDeclaredRetryRoots(plan.receipt);
1122
- const observedManager = children.flatMap((child) => child.nativeGroups)
1123
- .map((group) => group.preview.codexManagerPreview)
1124
- .find((entry) => entry?.state === 'system');
1125
- if (observedManager?.state === 'system') {
1126
- runtime.codexObservationSession?.setManager(observedManager.manager);
1127
- }
1128
1215
  return plan;
1129
1216
  }
1130
1217
  catch (error) {
@@ -1135,15 +1222,20 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
1135
1222
  export async function executeJointRecovery(plan, execution) {
1136
1223
  const joint = plan.joint;
1137
1224
  const performanceRuntime = { ...plan.runtime, ...execution.runtime };
1225
+ const reviewedToken = plan.runtime.awHomeMutationToken;
1226
+ const expired = reviewedToken !== undefined && !isActiveAwHomeMutationToken(reviewedToken);
1227
+ const tokenForExecution = execution.runtime?.awHomeMutationToken ?? (expired ? undefined : reviewedToken);
1228
+ if (expired) {
1229
+ performanceRuntime.preparedArtifactRenderResults = undefined;
1230
+ }
1231
+ const override = execution.runtime?.nativeCliRunner;
1232
+ const sameNativeRunner = !override || override === joint.originalNativeRunner || override === plan.runtime.nativeCliRunner;
1138
1233
  if (isInstallBatch(plan.command)) {
1139
- const override = execution.runtime?.nativeCliRunner;
1140
- if (!override || override === joint.originalNativeRunner || override === plan.runtime.nativeCliRunner) {
1234
+ if (sameNativeRunner) {
1141
1235
  performanceRuntime.nativeCliRunner = plan.runtime.nativeCliRunner;
1142
- joint.bindExecutionSignal?.(performanceRuntime.signal);
1143
1236
  }
1144
1237
  else {
1145
1238
  performanceRuntime.nativeCliRunner = limitInstallNativeRunner(override);
1146
- performanceRuntime.codexObservationSession = execution.runtime?.codexObservationSession;
1147
1239
  }
1148
1240
  }
1149
1241
  let lockedPlan;
@@ -1162,9 +1254,9 @@ export async function executeJointRecovery(plan, execution) {
1162
1254
  }
1163
1255
  lockWaitStartedAt = performance.now();
1164
1256
  await recordRecoveryPerformanceStage(performanceRuntime, 'recovery.lock.wait', 'start', lockWaitStartedAt);
1165
- return await withAwHomeMutationLock({ env: plan.options.env, signal: performanceRuntime.signal, token: execution.runtime?.awHomeMutationToken ?? plan.runtime.awHomeMutationToken,
1257
+ return await withAwHomeMutationLock({ env: plan.options.env, tracksWrites: true, signal: performanceRuntime.signal, token: tokenForExecution,
1166
1258
  onContention: (status) => {
1167
- if (performanceRuntime?.directCli && performanceRuntime.reporter)
1259
+ if (performanceRuntime.directCli && performanceRuntime.reporter)
1168
1260
  reportCliPhase(performanceRuntime.reporter, 'wait-lock', status);
1169
1261
  },
1170
1262
  action: async (token) => {
@@ -1194,8 +1286,30 @@ export async function executeJointRecovery(plan, execution) {
1194
1286
  if (plan.blockExecution)
1195
1287
  return plan.receipt;
1196
1288
  // Recheck all backend candidates before any strong-state or output write.
1197
- (execution.runtime?.codexObservationSession ?? plan.runtime.codexObservationSession)?.invalidate();
1198
- const checked = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.recheck', () => prepareJointRecovery(plan.command, joint.selectors, preparation.options, { ...performanceRuntime, awHomeMutationToken: token }, preparation));
1289
+ // A prospective declaration/policy can depend on a live provider that
1290
+ // needed no staged target. Re-derive placement before committing such
1291
+ // strong state; the private handle alone cannot prove that provider.
1292
+ let prepared = !joint.declaration && !joint.originalOptions.preferences
1293
+ && sameNativeRunner && performanceRuntime.signal === plan.runtime.signal
1294
+ ? LockedPreparedExecution.consume(plan, token, describeRecoveryPlan) : undefined;
1295
+ // Keep validated renderer output, while giving locked target drivers, staging
1296
+ // and marketplace generations a separate owner from the unlocked Review.
1297
+ const lockedResults = prepared ? plan.runtime.preparedArtifactRenderResults
1298
+ : handoffReviewedArtifactRenderResults(performanceRuntime.preparedArtifactRenderResults, performanceRuntime.signal);
1299
+ const checked = prepared ? plan : await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.recheck', () => prepareJointRecovery(plan.command, joint.selectors, preparation.options, { ...performanceRuntime, awHomeMutationToken: token, prepareLockedExecution: true,
1300
+ preparedArtifactRenderResults: lockedResults, platformRebuildSession: undefined, packagePreparationCache: undefined }, preparation)).catch(async (error) => { await disposePreparedPlatformRebuildSession(lockedResults); throw error; });
1301
+ if (checked !== plan) {
1302
+ const disposeContext = checked.context.dispose;
1303
+ checked.context.dispose = async () => {
1304
+ try {
1305
+ await disposeContext();
1306
+ }
1307
+ finally {
1308
+ await disposePreparedPlatformRebuildSession(lockedResults);
1309
+ }
1310
+ };
1311
+ }
1312
+ prepared ??= LockedPreparedExecution.consume(checked, token, describeRecoveryPlan);
1199
1313
  const stable = !checked.blockExecution && JSON.stringify(describeRecoveryPlan(plan)) === JSON.stringify(describeRecoveryPlan(checked));
1200
1314
  lockedPlan = checked;
1201
1315
  const parallel = isInstallBatch(plan.command) && !joint.pendingUserSkills.length && !joint.children.some((child) => child.command === 'cleanup');
@@ -1244,10 +1358,14 @@ export async function executeJointRecovery(plan, execution) {
1244
1358
  const failedNodes = new Set();
1245
1359
  const packageResults = [];
1246
1360
  const runtime = { ...performanceRuntime, awHomeMutationToken: token,
1361
+ nativeObservationBatch: prepared?.batch, preparedArtifactRenderResults: lockedResults,
1362
+ catalogReadScope: preparation.catalogReadScope,
1363
+ platformRebuildSession: checked.runtime.platformRebuildSession, packagePreparationCache: checked.runtime.packagePreparationCache,
1247
1364
  commandPackagePlatforms: checked.runtime.commandPackagePlatforms,
1248
1365
  retainCommandPackages: checked.runtime.retainCommandPackages };
1249
1366
  runtime.preApplyExecutionCache ??= new Map();
1250
1367
  runtime.managedCommandProducerCache ??= new Map();
1368
+ const executionEpoch = runtime.nativeObservationBatch?.writeEpoch;
1251
1369
  let interrupted;
1252
1370
  if (parallel) {
1253
1371
  const installed = await executeJointInstall({ children, demand: checked.joint.demand, runtime, token,
@@ -1471,6 +1589,8 @@ export async function executeJointRecovery(plan, execution) {
1471
1589
  const reviewedRemoval = child.nativeGroups.some(({ preview }) => preview.operationPlan?.actions.some((action) => action.kind === 'removeOwnedArtifact' && action.pluginId === target.pluginId && action.platform === 'grok'
1472
1590
  && action.scope === 'project' && action.path === project?.nativeIdentity?.sourceLocation));
1473
1591
  if (project && user && reviewedRemoval && removed?.length) {
1592
+ // Removing the Project copy reveals the User package to Grok's next inspect.
1593
+ runtime.nativeObservationBatch?.invalidatePlatform('grok', 'inspect');
1474
1594
  recordPreparedGrokProjectRetirement(runtime.preparedArtifactRenderResults, projectRoot, project, user, removed);
1475
1595
  }
1476
1596
  });
@@ -1647,7 +1767,7 @@ export async function executeJointRecovery(plan, execution) {
1647
1767
  && ['applied', 'no-op'].includes(target.execution)))
1648
1768
  continue;
1649
1769
  const result = await runtime.managedCommandProducerCache.get(action.packageId)
1650
- ?? await publishLifecycleCommandPackage(action, { cwd: joint.snapshot.context.projectRoot ?? plan.context.executionCwd }, { env: plan.context.env, reporter: runtime.reporter });
1770
+ ?? await publishLifecycleCommandPackage(action, { cwd: joint.snapshot.context.projectRoot ?? plan.context.executionCwd }, { env: plan.context.env, reporter: runtime.reporter, awHomeMutationToken: token });
1651
1771
  commandResults.set(result.packageId, result);
1652
1772
  receipt.outputsMayHaveChanged ||= result.action === 'removed' || result.state === 'partial';
1653
1773
  }
@@ -1669,9 +1789,25 @@ export async function executeJointRecovery(plan, execution) {
1669
1789
  try {
1670
1790
  // The reviewed Catalog may still be readable after Active has moved. Bind the
1671
1791
  // final read to the current sources, once per binding across both scopes.
1792
+ const catalogReadScope = new CatalogPreparationReadScope({ env, signal: runtime.signal });
1793
+ // A successful execution with no native mutation can reuse the same
1794
+ // live native window, even if an independent AW command package changed.
1795
+ // All strong inputs and package/status projections are still read now;
1796
+ // any host mutation or opaque script invalidates the execution evidence.
1797
+ const reusableNativeBatch = receipt.ok && executionEpoch !== undefined
1798
+ && runtime.nativeObservationBatch?.writeEpoch === executionEpoch
1799
+ ? runtime.nativeObservationBatch : undefined;
1800
+ const configStatusTargets = runtime.configApply
1801
+ ? [...new Set([...(joint.originalOptions.targets ?? []), ...receipt.targetResults.map((target) => target.agent)])]
1802
+ : undefined;
1803
+ const configStatusPlugins = runtime.configApply && receipt.targetResults.length
1804
+ ? [...new Set(receipt.targetResults.map((target) => target.pluginId))]
1805
+ : undefined;
1672
1806
  const status = await measureRecoveryPerformanceStage(runtime, 'recovery.status', () => readRecoveryStatus({ cwd, scope, context, env, cliVersion, expectedProjectRoot: joint.snapshot.context.projectRoot,
1673
- catalogReadScope: new CatalogPreparationReadScope({ env, signal: runtime.signal }), signal: runtime.signal,
1674
- nativeCliRunner: runtime.nativeCliRunner, ...(isInstallBatch(plan.command) ? {} : { codexObservationSession: runtime.codexObservationSession }) }));
1807
+ catalogReadScope, signal: runtime.signal, nativeCliRunner: runtime.nativeCliRunner,
1808
+ ...(configStatusTargets?.length ? { targets: configStatusTargets } : {}),
1809
+ ...(configStatusPlugins?.length ? { plugins: configStatusPlugins } : {}),
1810
+ ...(reusableNativeBatch ? { nativeObservationBatch: reusableNativeBatch, nativeObservationWindow: 'execution' } : {}) }));
1675
1811
  receipt.allSatisfied = status.allSatisfied;
1676
1812
  receipt.inSync = status.inSync;
1677
1813
  statusFailure = finalStatusReadFailure(status, receipt);