@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
@@ -1,9 +1,14 @@
1
1
  import crypto from 'node:crypto';
2
2
  import path from 'node:path';
3
+ import { mapInstallReads, runInstallTasks } from '../recovery/install-concurrency.js';
4
+ import { withNativeObservationBatch } from '../platforms/inspection-query.js';
5
+ import { RebuildInterruptedError, recoveryInterruptionCode } from '../recovery/interruption.js';
3
6
  import { inventoryRecoveryDiagnostic } from '../utils/inventory-recovery-diagnostic.js';
4
7
  import { withNativeToolRemovalImpact } from '../utils/native-tool-review.js';
5
8
  import fs from 'fs-extra';
6
9
  import { NATIVE_PLATFORM_TARGETS } from '@lesliechan721/aw-plugin-core/manifest';
10
+ import { nativeInstallResources } from './rebuild-platform-integration.js';
11
+ import { resolvePlatformConfigRoot } from '../platforms/discovery.js';
7
12
  import { getDeploymentLayout } from '../platforms/layout.js';
8
13
  import { createNoopDebugLogger } from '../output/debug-log.js';
9
14
  import { createNoopReporter } from '../output/reporter.js';
@@ -32,7 +37,7 @@ import { supportsPlatform } from '../utils/platform-support.js';
32
37
  import { pluginConfigTargetRenderScopes } from '../utils/plugin-config-impact.js';
33
38
  import { inspectPluginConfigResetTarget, readNamespacedPluginConfigStoreIdentity, resolveEffectivePluginConfig, resolvePluginConfigStorePath, } from '../utils/plugin-config.js';
34
39
  import { resolvePluginMetaDependencyClosure } from '../utils/plugin-dependencies.js';
35
- import { readSafeOperationError } from '../utils/safe-operation-diagnostic.js';
40
+ import { attachSafeOperationError, readSafeOperationError } from '../utils/safe-operation-diagnostic.js';
36
41
  import { canonicalizePathThroughExistingAncestorSync, codexProjectConfigAliasesUserHome, getClaudeHome, getCodexHome, resolveRepoRootSync, } from '../utils/state-paths.js';
37
42
  import { AwCapabilityUnsupportedError, IMPLEMENTED_AW_CAPABILITIES, } from './aw-capabilities.js';
38
43
  import { createDependencyPlacementPlan, } from './dependency-operation-plan.js';
@@ -40,8 +45,21 @@ import { forceOfflineCleanupEvidence, intentOnlyOfflineCleanupEvidence, offlineC
40
45
  import { assertOperationPlanFingerprint, createOperationPlan, createOperationPlanConfigDigest, operationPlanNativeToolChanges, } from './operation-plan.js';
41
46
  import { deploymentConfirmationEffects } from './deployment-confirmation.js';
42
47
  import { assertNoClaudeUnboundNativeNameCollision, CodexActivationPostcheckError, createRebuildIntegration, disposePreparedPlatformRebuildSession, executeCodexReconcileActivations, inspectNativeMarketplaceRegistrations, isNativeActivationOnlyTarget, postcheckCodexReconcileActivations, removeForceCleanupCodexRoleRegistration } from './rebuild-integration.js';
43
- import { executeRebuildOperation, prepareRebuildOperation } from './rebuild-operations.js';
48
+ import { executeRebuildOperation, hasPlannedPreApply, prepareRebuildOperation } from './rebuild-operations.js';
44
49
  import { createReconcileOperationPlan, } from './reconcile-operation-plan.js';
50
+ // A read scope belongs to one Review or its independent locked recheck.
51
+ const nativePreparationReads = new WeakMap();
52
+ function preparationReads(runtime) {
53
+ const scope = runtime?.catalogReadScope;
54
+ if (!scope || !runtime.previewOperationPlan || !runtime.batchInstallPlatform)
55
+ return;
56
+ let reads = nativePreparationReads.get(scope);
57
+ if (!reads) {
58
+ reads = { plugins: new Map(), inventories: new Map() };
59
+ nativePreparationReads.set(scope, reads);
60
+ }
61
+ return reads;
62
+ }
45
63
  async function measureCommandPerformanceStage(runtime, name, operation) {
46
64
  const startedAt = Date.now();
47
65
  let phase = 'success';
@@ -315,7 +333,6 @@ async function resolveRequestedNames(options) {
315
333
  }
316
334
  async function runSingleSourceRebuildCommand(options) {
317
335
  const runtime = {
318
- nativeConsent: options.runtime?.nativeConsent === true,
319
336
  referencePlugins: options.runtime?.referencePlugins,
320
337
  recoveryCandidates: options.runtime?.recoveryCandidates,
321
338
  sharedReferenceView: options.runtime?.executionInput?.requirements.sharedReferenceView ?? options.runtime?.sharedReferenceView,
@@ -361,19 +378,12 @@ async function runSingleSourceRebuildCommand(options) {
361
378
  ? readPluginManifest(pluginRoot, { mode: 'bundle' })
362
379
  : null;
363
380
  }))).filter((plugin) => plugin !== null);
364
- if (options.runtime?.namespacedSource) {
365
- for (const plugin of catalogPlugins) {
366
- plugin.sourceId = options.runtime.namespacedSource.sourceId;
367
- plugin.sourceIdentity = options.runtime.namespacedSource.sourceIdentity;
368
- plugin.catalogLogicalIdentity = options.runtime.namespacedSource.logicalIdentity;
369
- plugin.pluginId = formatPluginId({
370
- sourceId: options.runtime.namespacedSource.sourceId,
371
- pluginName: plugin.manifest.name,
372
- });
373
- plugin.marketplaceName = options.runtime.namespacedSource.marketplaceName;
374
- }
375
- }
376
- const catalogByName = new Map(catalogPlugins.map((plugin) => [plugin.manifest.name, plugin]));
381
+ const namespaced = options.runtime?.namespacedSource;
382
+ const catalogByName = new Map(catalogPlugins.map((plugin) => [plugin.manifest.name, namespaced ? {
383
+ ...plugin, sourceId: namespaced.sourceId, sourceIdentity: namespaced.sourceIdentity,
384
+ catalogLogicalIdentity: namespaced.logicalIdentity, marketplaceName: namespaced.marketplaceName,
385
+ pluginId: formatPluginId({ sourceId: namespaced.sourceId, pluginName: plugin.manifest.name }),
386
+ } : plugin]));
377
387
  if (options.commandOptions.platform === 'both'
378
388
  && options.command !== 'cleanup'
379
389
  && options.command !== 'uninstall') {
@@ -1096,7 +1106,7 @@ async function cleanupOfflineOwnedComponents(options) {
1096
1106
  // This offline path can revoke only independently owned files and directory-loaded packages.
1097
1107
  if (component.kind === 'owned-directory'
1098
1108
  && ((action.recoveryCandidate && needsFrozenNativeRemoval(action.recoveryCandidate))
1099
- || ['codex', 'claude', 'gemini', 'copilot', 'pi'].includes(target.platform)
1109
+ || ['codex', 'claude', 'copilot', 'pi'].includes(target.platform)
1100
1110
  || path.relative(path.join(resolveAwHome(options.env), 'platforms'), component.path).split(path.sep)[0] !== '..')) {
1101
1111
  preservedOutputs.push(component.path);
1102
1112
  continue;
@@ -1820,6 +1830,10 @@ async function runRebuildCommandInSession(options) {
1820
1830
  }
1821
1831
  const selectedExecutionTarget = (target) => executionInput.selectedTargets.some((selected) => selected.pluginId === target.pluginId && selected.platform === target.platform && selected.scope === target.scope);
1822
1832
  const runtimeEnv = executionInput.context.env;
1833
+ const admission = options.runtime?.installAdmission;
1834
+ const initialGeneration = admission?.exclusiveGeneration ?? 0;
1835
+ if (initialGeneration && requestedPlatforms.includes('codex'))
1836
+ options.runtime?.codexObservationSession?.invalidate();
1823
1837
  const retainSelectors = options.command === 'cleanup' ? options.pluginNames.map(parsePluginId) : [];
1824
1838
  const primarySourceId = retainSelectors.some((selector) => !selector.sourceId)
1825
1839
  ? await readCatalogSourcesConfigSnapshot(runtimeEnv)
@@ -1832,16 +1846,27 @@ async function runRebuildCommandInSession(options) {
1832
1846
  const retainedPackageActions = retainedPackages.map((entry) => ({ ...entry, kind: 'retainManagedCommandPackage', pluginId: `${entry.producer.sourceId}/${entry.producer.pluginName}`, scope: entry.producer.scope }));
1833
1847
  const readInventory = options.runtime?.inventoryCatalogSourceReferences
1834
1848
  ?? inventoryCatalogSourceReferences;
1849
+ const inventoryRequest = { cwd: options.commandOptions.cwd, env: runtimeEnv, scope: options.commandOptions.scope };
1850
+ const readCurrentInventory = () => {
1851
+ if (!admission || !options.runtime?.batchInstallPlatform)
1852
+ return readInventory(inventoryRequest);
1853
+ // The inventory includes other hosts' registries and owner markers. Sample them
1854
+ // outside any target or script lease, while sibling publishers are between writes.
1855
+ const roots = [resolveAwHome(runtimeEnv), resolveRepoRootSync(inventoryRequest.cwd),
1856
+ ...NATIVE_PLATFORM_TARGETS.map((platform) => resolvePlatformConfigRoot(platform, inventoryRequest))];
1857
+ return admission.run(roots.map((value) => ({ kind: 'path', value, access: 'read' })), () => readInventory(inventoryRequest), options.runtime.signal);
1858
+ };
1859
+ const readCache = preparationReads(options.runtime);
1835
1860
  let ordinaryInventory;
1836
- const readOrdinaryInventory = async () => {
1837
- ordinaryInventory ??= await measureCommandPerformanceStage(options.runtime, 'inventory', async () => {
1838
- const inventory = await readInventory({
1839
- cwd: options.commandOptions.cwd,
1840
- env: runtimeEnv,
1841
- scope: options.commandOptions.scope,
1842
- });
1843
- return inventory;
1844
- });
1861
+ const readOrdinaryInventory = () => {
1862
+ if (ordinaryInventory)
1863
+ return ordinaryInventory;
1864
+ const key = JSON.stringify([inventoryRequest.cwd, inventoryRequest.scope, Object.entries(runtimeEnv).sort(([a], [b]) => a.localeCompare(b))]);
1865
+ let reads = readCache?.inventories.get(readInventory);
1866
+ if (readCache && !reads)
1867
+ readCache.inventories.set(readInventory, reads = new Map());
1868
+ ordinaryInventory = reads?.get(key) ?? measureCommandPerformanceStage(options.runtime, 'inventory', readCurrentInventory);
1869
+ reads?.set(key, ordinaryInventory);
1845
1870
  return ordinaryInventory;
1846
1871
  };
1847
1872
  let requestedPluginNames = options.pluginNames;
@@ -2426,11 +2451,12 @@ async function runRebuildCommandInSession(options) {
2426
2451
  });
2427
2452
  }
2428
2453
  const available = await Promise.all(requiredEntryClosure.map(async (candidate) => {
2429
- const plugin = await readPluginManifest(path.join(candidate.source.rootDir, 'plugins', candidate.entry.name), { mode: 'bundle' });
2430
- plugin.sourceId = candidate.source.sourceId;
2431
- plugin.sourceIdentity = candidate.source.sourceIdentity;
2432
- plugin.catalogLogicalIdentity = candidate.source.logicalIdentity;
2433
- plugin.pluginId = candidate.pluginId;
2454
+ const root = path.join(candidate.source.rootDir, 'plugins', candidate.entry.name);
2455
+ const key = JSON.stringify([root, candidate.source.sourceIdentity, candidate.source.snapshotDigest, candidate.entry.contentDigest]);
2456
+ const read = readCache?.plugins.get(key) ?? readPluginManifest(root, { mode: 'bundle' });
2457
+ readCache?.plugins.set(key, read);
2458
+ const plugin = { ...await read, sourceId: candidate.source.sourceId, sourceIdentity: candidate.source.sourceIdentity,
2459
+ catalogLogicalIdentity: candidate.source.logicalIdentity, pluginId: candidate.pluginId };
2434
2460
  return { source: candidate.source, plugin, pluginId: candidate.pluginId };
2435
2461
  }));
2436
2462
  const selected = selectedEntries.map((entry) => available.find((candidate) => candidate.pluginId === entry.pluginId));
@@ -2551,7 +2577,7 @@ async function runRebuildCommandInSession(options) {
2551
2577
  const planExecutionKey = (target) => [
2552
2578
  target.pluginId,
2553
2579
  target.platform,
2554
- target.requestedScope ?? target.resolvedScope,
2580
+ options.runtime?.batchInstallPlatform ? target.resolvedScope : target.requestedScope ?? target.resolvedScope,
2555
2581
  ].join('\0');
2556
2582
  const dependencyTargetFor = (plan, consumer, dependencyPluginId) => {
2557
2583
  const candidates = plan.targets.filter((target) => target.pluginId === dependencyPluginId
@@ -2725,10 +2751,10 @@ async function runRebuildCommandInSession(options) {
2725
2751
  }
2726
2752
  }
2727
2753
  const executionContext = {
2728
- nativeConsent: options.runtime?.nativeConsent === true,
2729
2754
  recoveryCandidates: options.runtime?.recoveryCandidates,
2730
2755
  sharedReferenceView: options.runtime?.executionInput?.requirements.sharedReferenceView ?? options.runtime?.sharedReferenceView,
2731
2756
  platformRebuildSession: options.runtime?.platformRebuildSession,
2757
+ batchInstallPlatform: options.runtime?.batchInstallPlatform,
2732
2758
  packagePreparationCache: options.runtime?.packagePreparationCache,
2733
2759
  preparedArtifactRenderResults: options.runtime?.preparedArtifactRenderResults,
2734
2760
  interruption: options.runtime?.interruption,
@@ -2784,6 +2810,15 @@ async function runRebuildCommandInSession(options) {
2784
2810
  }
2785
2811
  return output;
2786
2812
  };
2813
+ const readSelections = async (read, existingBatch) => {
2814
+ const batchInstall = !!options.runtime?.batchInstallPlatform;
2815
+ const run = (batch) => mapInstallReads(executionSelections, (selection) => read(selection, batch), { signal: executionContext.signal, limit: batchInstall ? undefined : 1 });
2816
+ if (!batchInstall || executionSelections.length < 2)
2817
+ return run();
2818
+ if (existingBatch)
2819
+ return run(existingBatch);
2820
+ return withNativeObservationBatch({ runner: executionContext.nativeCliRunner, signal: executionContext.signal }, run);
2821
+ };
2787
2822
  const createPlan = async (inventory, _codexManager, planOptions) => {
2788
2823
  plannedOwnedTextTargets = new Map();
2789
2824
  plannedSkillMarkerTargets = new Map();
@@ -2792,19 +2827,10 @@ async function runRebuildCommandInSession(options) {
2792
2827
  const placementNodes = [];
2793
2828
  const blockingTargets = new Map();
2794
2829
  const actualStates = new Map();
2795
- for (const [order, selection] of executionSelections.entries()) {
2830
+ const observations = await readSelections(async (selection, observationBatch) => {
2796
2831
  const { entry, platform } = selection;
2797
- const relation = executionInput.selectedTargets.some((target) => target.pluginId === entry.pluginId && target.platform === platform)
2798
- ? 'requested' : 'dependency';
2799
2832
  const requestedScope = selection.requestedScope ?? options.commandOptions.scope;
2800
2833
  const requestedMethod = selection.requestedMethod ?? options.command;
2801
- const activationOnly = isNativeActivationOnlyTarget(executionContext, {
2802
- pluginId: entry.pluginId, platform, scope: requestedScope,
2803
- });
2804
- const otherScopeRetires = options.runtime?.previewOperationPlan === true
2805
- && options.runtime.nativePlannedRetirements?.some((target) => target.pluginId === entry.pluginId && target.platform === platform
2806
- && target.scope !== requestedScope) === true;
2807
- let resolvedScope = requestedScope;
2808
2834
  const inspectScope = async (scope) => {
2809
2835
  const marketplaceName = marketplaceNameFor(entry, platform, scope);
2810
2836
  entry.plugin.marketplaceName = marketplaceName;
@@ -2821,6 +2847,7 @@ async function runRebuildCommandInSession(options) {
2821
2847
  command: requestedMethod,
2822
2848
  catalog: toCatalogResolution(entry.source),
2823
2849
  readOnlyInspectionPlan: true,
2850
+ observationBatch,
2824
2851
  });
2825
2852
  const targetKey = [entry.pluginId, platform, scope].join('\0');
2826
2853
  const ownedTextTargets = plannedOwnedTextTargets.get(targetKey) ?? new Set();
@@ -2874,15 +2901,31 @@ async function runRebuildCommandInSession(options) {
2874
2901
  : hasAnyPresent ? 'present' : 'absent';
2875
2902
  return { ...result, state, platformObservations: desired.platformObservations ?? [], supplementPhysicalKeys };
2876
2903
  };
2877
- const otherScope = resolvedScope === 'user' ? 'project' : 'user';
2904
+ const otherScope = requestedScope === 'user' ? 'project' : 'user';
2878
2905
  const [requestedInspection, otherInspection] = await Promise.all([
2879
- inspectScope(resolvedScope),
2906
+ inspectScope(requestedScope),
2880
2907
  options.commandOptions.scope === 'user'
2881
2908
  ? Promise.resolve({ state: 'partial', components: [], errors: [], platformObservations: [], supplementPhysicalKeys: new Set() })
2882
- : platform === 'codex' && codexScopePathsAlias && resolvedScope === 'user'
2909
+ : platform === 'codex' && codexScopePathsAlias && requestedScope === 'user'
2883
2910
  ? Promise.resolve({ state: 'absent', components: [], errors: [], platformObservations: [], supplementPhysicalKeys: new Set() })
2884
2911
  : inspectScope(otherScope),
2885
2912
  ]);
2913
+ return { requestedInspection, otherInspection, otherScope };
2914
+ }, executionContext.nativeObservationBatch);
2915
+ for (const [order, selection] of executionSelections.entries()) {
2916
+ const { entry, platform } = selection;
2917
+ const relation = executionInput.selectedTargets.some((target) => target.pluginId === entry.pluginId && target.platform === platform)
2918
+ ? 'requested' : 'dependency';
2919
+ const requestedScope = selection.requestedScope ?? options.commandOptions.scope;
2920
+ const requestedMethod = selection.requestedMethod ?? options.command;
2921
+ const activationOnly = isNativeActivationOnlyTarget(executionContext, {
2922
+ pluginId: entry.pluginId, platform, scope: requestedScope,
2923
+ });
2924
+ const otherScopeRetires = options.runtime?.previewOperationPlan === true
2925
+ && options.runtime.nativePlannedRetirements?.some((target) => target.pluginId === entry.pluginId && target.platform === platform
2926
+ && target.scope !== requestedScope) === true;
2927
+ let resolvedScope = requestedScope;
2928
+ const { requestedInspection, otherInspection, otherScope } = observations[order];
2886
2929
  const surface = platform === 'codex'
2887
2930
  ? analyzeCodexSurface(entry.plugin.manifest)
2888
2931
  : undefined;
@@ -3191,6 +3234,37 @@ async function runRebuildCommandInSession(options) {
3191
3234
  const isHealthyWiderDependency = (target) => target.relation === 'dependency'
3192
3235
  && target.resolvedScope !== options.commandOptions.scope
3193
3236
  && target.action === 'keep';
3237
+ const lifecycleCommand = options.command === 'install'
3238
+ || options.command === 'sync' || options.command === 'reinstall';
3239
+ const preApplyAuthorizationForPlan = (plan, preparedTargets) => lifecycleCommand ? executionSelections.flatMap((selection) => {
3240
+ const { entry, platform } = selection;
3241
+ const planned = planTargetFor(plan, selection);
3242
+ if (!planned || planned.action === 'block' || isHealthyWiderDependency(planned)
3243
+ || !entry.plugin.manifest.scripts?.preApply)
3244
+ return [];
3245
+ const identity = { pluginId: entry.pluginId, platform, scope: planned.resolvedScope };
3246
+ if (isNativeActivationOnlyTarget(executionContext, identity))
3247
+ return [];
3248
+ if (preparedTargets) {
3249
+ const prepared = preparedTargets.get(executionKey(selection, plan));
3250
+ if (!prepared || !hasPlannedPreApply(prepared.target))
3251
+ return [];
3252
+ }
3253
+ return [{
3254
+ ...identity,
3255
+ pluginName: entry.plugin.manifest.name,
3256
+ sourceId: entry.source.sourceId,
3257
+ sourceIdentity: entry.source.sourceIdentity,
3258
+ relation: planned.relation === 'requested' ? 'requested'
3259
+ : planned.requiredBy.some((pluginId) => selectedIds.has(pluginId)) ? 'direct' : 'transitive',
3260
+ }];
3261
+ }) : [];
3262
+ const assertPreApplyAuthorization = (plan) => {
3263
+ if (options.commandOptions.yes === true || options.runtime?.preApplyConfirmed === true
3264
+ || !preApplyAuthorizationForPlan(plan).length)
3265
+ return;
3266
+ throw namespacedPreflightError('preApplyAuthorizationRequired: Running plugin preApply requires --yes or an accepted Review.', preflightTargets);
3267
+ };
3194
3268
  const createCodexPlans = async (_plan, _activationSupport = 'observed', _codexManager) => [];
3195
3269
  const operationNeedsNativeCli = async (platform, plan) => {
3196
3270
  for (const { entry, platform: selectedPlatform } of executionSelections) {
@@ -3270,12 +3344,12 @@ async function runRebuildCommandInSession(options) {
3270
3344
  scope: planned.resolvedScope, cwd: options.commandOptions.cwd, command: commandForTarget(selection, plan),
3271
3345
  catalog: toCatalogResolution(selection.entry.source) }];
3272
3346
  }));
3273
- for (const selection of executionSelections) {
3347
+ const builds = await readSelections(async (selection, observationBatch) => {
3274
3348
  const { entry, platform } = selection;
3275
3349
  const planned = planTargetFor(plan, selection);
3276
3350
  const key = executionKey(selection, plan);
3277
3351
  if (planned.action === 'block')
3278
- continue;
3352
+ return;
3279
3353
  const buildCommand = commandForTarget(selection, plan);
3280
3354
  const plannedNative = platform === 'codex'
3281
3355
  ? codexPlans.flatMap((codexPlan) => codexPlan.sharedNativeActions).find((action) => action.pluginId === entry.pluginId)
@@ -3299,6 +3373,7 @@ async function runRebuildCommandInSession(options) {
3299
3373
  scope: planned.resolvedScope,
3300
3374
  cwd: options.commandOptions.cwd,
3301
3375
  command: buildCommand,
3376
+ observationBatch,
3302
3377
  catalog: toCatalogResolution(entry.source),
3303
3378
  ...(platform === 'codex'
3304
3379
  && (buildCommand === 'cleanup' || buildCommand === 'uninstall')
@@ -3350,16 +3425,13 @@ async function runRebuildCommandInSession(options) {
3350
3425
  await integration.driver.preflightMutation?.(target);
3351
3426
  }
3352
3427
  }
3353
- preparedTargets.set(key, {
3354
- target,
3355
- });
3356
3428
  if (runTargetHook) {
3357
3429
  await rebuildCommandTestHooks?.afterTargetBuilt?.({
3358
3430
  command: selection.requestedMethod ?? options.command,
3359
3431
  identity: target.identity,
3360
3432
  });
3361
3433
  }
3362
- collisionSelections.push({
3434
+ const collision = {
3363
3435
  pluginId: entry.pluginId,
3364
3436
  targetKey: `${platform}/${target.identity.scope}`,
3365
3437
  artifactKeys: (target.desiredOwnedComponents ?? target.ownedComponents)
@@ -3374,14 +3446,27 @@ async function runRebuildCommandInSession(options) {
3374
3446
  : component.locator.kind === 'claude-permissions'
3375
3447
  ? `shared:claude:${path.resolve(component.locator.settingsPath)}:${component.locator.ownerKey}`
3376
3448
  : `shared:${component.label}`),
3377
- });
3449
+ };
3450
+ return { key, target, collision };
3378
3451
  }
3379
3452
  catch (error) {
3453
+ if (recoveryInterruptionCode(error) === 'processCleanupUnconfirmed')
3454
+ throw error;
3380
3455
  options.runtime?.signal?.throwIfAborted();
3381
- if (error instanceof Error && error.name === 'AbortError'
3382
- || readSafeOperationError(error))
3456
+ if (error instanceof Error && error.name === 'AbortError' || readSafeOperationError(error))
3383
3457
  throw error;
3384
- preparedTargetErrors.set(key, error);
3458
+ return { key, error };
3459
+ }
3460
+ });
3461
+ for (const build of builds) {
3462
+ if (!build)
3463
+ continue;
3464
+ if (build.target) {
3465
+ preparedTargets.set(build.key, { target: build.target });
3466
+ collisionSelections.push(build.collision);
3467
+ }
3468
+ else {
3469
+ preparedTargetErrors.set(build.key, build.error);
3385
3470
  }
3386
3471
  }
3387
3472
  const collisions = preflightDesiredArtifactCollisions(collisionSelections);
@@ -3453,28 +3538,7 @@ async function runRebuildCommandInSession(options) {
3453
3538
  assertWriteInventoryComplete(stateInventory, exactOwnedTextTargets(authorizationPlan), exactSkillMarkerTargets(authorizationPlan));
3454
3539
  const preview = mergeRebuildCommandResults([]);
3455
3540
  preview.dependencyPlan = authorizationPlan;
3456
- preview.preApplyAuthorization = executionSelections.flatMap((selection) => {
3457
- const { entry, platform } = selection;
3458
- const planned = planTargetFor(authorizationPlan, selection);
3459
- if (!planned || planned.action === 'block' || isHealthyWiderDependency(planned)
3460
- || !entry.plugin.manifest.scripts?.preApply) {
3461
- return [];
3462
- }
3463
- const relation = planned.relation === 'requested'
3464
- ? 'requested'
3465
- : planned.requiredBy.some((pluginId) => selectedIds.has(pluginId))
3466
- ? 'direct'
3467
- : 'transitive';
3468
- return [{
3469
- pluginId: entry.pluginId,
3470
- pluginName: entry.plugin.manifest.name,
3471
- sourceId: entry.source.sourceId,
3472
- sourceIdentity: entry.source.sourceIdentity,
3473
- platform,
3474
- scope: planned.resolvedScope,
3475
- relation,
3476
- }];
3477
- });
3541
+ preview.preApplyAuthorization = preApplyAuthorizationForPlan(authorizationPlan);
3478
3542
  return preview;
3479
3543
  }
3480
3544
  if (options.runtime?.previewOperationPlan) {
@@ -3486,6 +3550,7 @@ async function runRebuildCommandInSession(options) {
3486
3550
  const previewPreparation = await prepareRenderedTargets(initialPlan, initialCodexPlans, false);
3487
3551
  const preview = mergeRebuildCommandResults([]);
3488
3552
  preview.dependencyPlan = initialPlan;
3553
+ preview.preApplyAuthorization = preApplyAuthorizationForPlan(initialPlan, previewPreparation.preparedTargets);
3489
3554
  const blockedTargets = [...previewPreparation.preparedTargets.values()].flatMap(({ target }) => {
3490
3555
  const receipts = target.platformDeployment?.blockedReceipts ?? [];
3491
3556
  if (!receipts.length)
@@ -3570,19 +3635,7 @@ async function runRebuildCommandInSession(options) {
3570
3635
  }
3571
3636
  let lockedPlan = await measureCommandPerformanceStage(options.runtime, 'dependency.plan', () => createPlan(stateInventory));
3572
3637
  assertWriteInventoryComplete(stateInventory, exactOwnedTextTargets(lockedPlan), exactSkillMarkerTargets(lockedPlan));
3573
- const lifecycleCommand = options.command === 'install'
3574
- || options.command === 'sync'
3575
- || options.command === 'reinstall';
3576
- const preApplyRequired = lifecycleCommand && executionSelections.some(({ entry, platform }) => entry.plugin.manifest.scripts?.preApply !== undefined
3577
- && lockedPlan.targets.some((target) => target.pluginId === entry.pluginId
3578
- && target.platform === platform
3579
- && target.action !== 'block'
3580
- && !isHealthyWiderDependency(target)));
3581
- if (preApplyRequired
3582
- && options.commandOptions.yes !== true
3583
- && options.runtime?.preApplyConfirmed !== true) {
3584
- throw namespacedPreflightError('preApplyAuthorizationRequired: Running plugin preApply requires --yes or an accepted Review.', preflightTargets);
3585
- }
3638
+ assertPreApplyAuthorization(lockedPlan);
3586
3639
  const provisionalLockedCodexPlans = await createCodexPlans(lockedPlan);
3587
3640
  const codexManagerRequired = provisionalLockedCodexPlans.some((plan) => plan.sharedNativeActions.some((action) => action.action === 'install'
3588
3641
  || action.action === 'replace'
@@ -3631,6 +3684,42 @@ async function runRebuildCommandInSession(options) {
3631
3684
  return 'install';
3632
3685
  return commandForTarget(selection, lockedPlan);
3633
3686
  };
3687
+ const deferredPreApply = new Set();
3688
+ let serialScriptGeneration = 0;
3689
+ const currentGeneration = () => admission?.exclusiveGeneration ?? serialScriptGeneration;
3690
+ let observationGeneration = initialGeneration;
3691
+ const refreshCodexObservation = (includeSerial = false) => {
3692
+ if (!admission && !includeSerial)
3693
+ return;
3694
+ const generation = currentGeneration();
3695
+ if (observationGeneration === generation)
3696
+ return;
3697
+ executionContext.codexObservationSession?.invalidate();
3698
+ observationGeneration = generation;
3699
+ };
3700
+ const prepareOperation = async (input) => {
3701
+ refreshCodexObservation();
3702
+ const prepared = await prepareRebuildOperation({ ...input, onActionEvent: async (event) => {
3703
+ if (event.data.name === 'preApply' && event.data.phase === 'start') {
3704
+ if (!admission)
3705
+ serialScriptGeneration++;
3706
+ try {
3707
+ options.runtime?.onInstallTargetState?.(input.target.identity, 'running');
3708
+ }
3709
+ catch { /* Progress observers cannot change execution. */ }
3710
+ }
3711
+ await emitRebuildActionEvent(executionContext, event);
3712
+ } });
3713
+ if (prepared.status === 'failed') {
3714
+ const diagnostic = prepared.result.failures.map((failure) => failure.operationDiagnostic)
3715
+ .find((failure) => failure && recoveryInterruptionCode(failure));
3716
+ if (diagnostic) {
3717
+ throw attachSafeOperationError(new Error(diagnostic.safeMessage), diagnostic);
3718
+ }
3719
+ executionContext.signal?.throwIfAborted();
3720
+ }
3721
+ return prepared;
3722
+ };
3634
3723
  const prepareLockedTargets = async (preparationOptions) => {
3635
3724
  const preparations = new Map();
3636
3725
  const failures = new Map();
@@ -3644,6 +3733,12 @@ async function runRebuildCommandInSession(options) {
3644
3733
  const { entry, platform } = selection;
3645
3734
  const key = executionKey(selection, lockedPlan);
3646
3735
  const planned = planTargetFor(lockedPlan, selection);
3736
+ const blocked = options.runtime?.nativeInstallBlockers?.get(key);
3737
+ if (blocked) {
3738
+ failures.set(key, failedResult(options.command, targetIdentity(selection, planned.resolvedScope), `${blocked}: ${entry.pluginId} requires a verified provider.`));
3739
+ states.set(key, 'failed');
3740
+ continue;
3741
+ }
3647
3742
  if (preparationOptions.eligibleKeys
3648
3743
  && !preparationOptions.eligibleKeys.has(key)) {
3649
3744
  states.set(key, isHealthyWiderDependency(planned) ? 'ready' : 'skipped');
@@ -3691,19 +3786,26 @@ async function runRebuildCommandInSession(options) {
3691
3786
  states.set(key, 'ready');
3692
3787
  continue;
3693
3788
  }
3694
- const preparedOperation = await prepareRebuildOperation({
3789
+ // A consumer's script can change external state. Wait for the provider's
3790
+ // actual execution result even when both targets passed native preflight.
3791
+ const hasScript = hasPlannedPreApply(prepared.target);
3792
+ if (entry.plugin.manifest.dependencies?.length && hasScript)
3793
+ deferredPreApply.add(key);
3794
+ const skipPreApply = preparationOptions.skipPreApply || deferredPreApply.has(key);
3795
+ const prepare = () => prepareOperation({
3695
3796
  command: executionCommand,
3696
3797
  target: prepared.target,
3697
3798
  driver: integration.driver,
3698
- ...(preparationOptions.skipPreApply ? { skipPreApply: true } : {}),
3799
+ skipPreApply,
3699
3800
  ...(preparationOptions.deferCodexNativeInspection
3700
3801
  && platform === 'codex'
3701
3802
  && executionContext.codexManager === undefined
3702
3803
  && (prepared.target.writeNativeRequired ?? prepared.target.requiresNative)
3703
3804
  ? { deferNativeInspection: true }
3704
3805
  : {}),
3705
- onActionEvent: (event) => emitRebuildActionEvent(executionContext, event),
3706
3806
  });
3807
+ const preparedOperation = admission && hasScript && !skipPreApply
3808
+ ? await admission.run([{ kind: 'exclusive' }], prepare, executionContext.signal) : await prepare();
3707
3809
  if (preparedOperation.status === 'failed') {
3708
3810
  failures.set(key, preparedOperation.result);
3709
3811
  states.set(key, 'failed');
@@ -3811,6 +3913,7 @@ async function runRebuildCommandInSession(options) {
3811
3913
  assertWriteInventoryComplete(stateInventory, exactOwnedTextTargets(lockedPlan), exactSkillMarkerTargets(lockedPlan));
3812
3914
  }
3813
3915
  lockedCodexPlans = await createCodexPlans(lockedPlan, 'observed', executionContext.codexManager);
3916
+ assertPreApplyAuthorization(lockedPlan);
3814
3917
  lockedPreparation = await prepareRenderedTargets(lockedPlan, lockedCodexPlans, false);
3815
3918
  const eligibleKeys = new Set(operationPreparations.keys());
3816
3919
  const initialOperationPreparations = new Map(operationPreparations);
@@ -3986,14 +4089,13 @@ async function runRebuildCommandInSession(options) {
3986
4089
  const preparedTargets = lockedPreparation.preparedTargets;
3987
4090
  const preparedTargetErrors = lockedPreparation.preparedTargetErrors;
3988
4091
  const removalRequiredConsumers = new Map();
4092
+ // Sync checks live references for Codex/Claude providers. Without a possible
4093
+ // consumer the second inventory cannot add a dependency to this plan.
4094
+ const syncNeedsConsumerCheck = options.command === 'sync' && executionSelections.some(({ platform, entry }) => (platform === 'codex' || platform === 'claude') && availableEntries.some((candidate) => candidate.source.sourceId === entry.source.sourceId && candidate.entry.dependencies.includes(entry.plugin.manifest.name)));
3989
4095
  if ((options.command === 'cleanup' && !cleanupForce)
3990
4096
  || (options.command === 'uninstall' && !uninstallForce)
3991
- || options.command === 'sync') {
3992
- const removalStateInventory = await readInventory({
3993
- cwd: options.commandOptions.cwd,
3994
- env: runtimeEnv,
3995
- scope: options.commandOptions.scope,
3996
- });
4097
+ || syncNeedsConsumerCheck) {
4098
+ const removalStateInventory = await readCurrentInventory();
3997
4099
  if (options.command !== 'cleanup') {
3998
4100
  const checked = options.command === 'uninstall'
3999
4101
  ? omitSelectedPluginConfigErrors(removalStateInventory, preflightTargets)
@@ -4138,6 +4240,66 @@ async function runRebuildCommandInSession(options) {
4138
4240
  }
4139
4241
  const results = [];
4140
4242
  const dependencyStates = new Map();
4243
+ const directProviders = new Map(executionSelections.map((selection) => {
4244
+ const planned = planTargetFor(lockedPlan, selection);
4245
+ const dependencies = (selection.entry.plugin.manifest.dependencies ?? []).flatMap((pluginName) => {
4246
+ const pluginId = formatPluginId({ sourceId: selection.entry.source.sourceId, pluginName });
4247
+ const provider = dependencyTargetFor(lockedPlan, planned, pluginId);
4248
+ return provider ? [planExecutionKey(provider)] : [];
4249
+ });
4250
+ return [executionKey(selection, lockedPlan), dependencies];
4251
+ }));
4252
+ const providerKeys = new Set([...directProviders.values()].flat());
4253
+ const verifiedGenerations = new Map();
4254
+ const providerReady = (key) => ['completed', 'kept'].includes(dependencyStates.get(key) ?? '');
4255
+ const providersReady = (key) => directProviders.get(key).every(providerReady);
4256
+ const providerDeployment = (key) => {
4257
+ const deployment = preparedTargets.get(key)?.target.platformDeployment;
4258
+ return deployment?.plans.length && !deployment.blockedReceipts.length ? deployment : undefined;
4259
+ };
4260
+ // A provider's package check does not read its own providers. Include the
4261
+ // whole resolved closure after a script can invalidate earlier readback.
4262
+ const providerClosure = (key) => {
4263
+ const providers = new Set();
4264
+ const visit = (consumerKey) => {
4265
+ for (const providerKey of directProviders.get(consumerKey) ?? []) {
4266
+ if (providers.has(providerKey))
4267
+ continue;
4268
+ providers.add(providerKey);
4269
+ visit(providerKey);
4270
+ }
4271
+ };
4272
+ visit(key);
4273
+ return providers;
4274
+ };
4275
+ const verifyProviders = async (selection, key) => {
4276
+ const generation = currentGeneration();
4277
+ const target = preparedTargets.get(key)?.target;
4278
+ if (generation === initialGeneration || !directProviders.get(key)?.length
4279
+ || !target || !providersReady(key) || operationPreparationFailures.has(key))
4280
+ return;
4281
+ refreshCodexObservation(true);
4282
+ for (const provider of providerClosure(key)) {
4283
+ if (verifiedGenerations.get(provider) === generation)
4284
+ continue;
4285
+ try {
4286
+ const deployment = providerDeployment(provider);
4287
+ if (!providerReady(provider) || !deployment) {
4288
+ throw new Error('Dependency evidence is unavailable.');
4289
+ }
4290
+ await deployment.verify();
4291
+ }
4292
+ catch (error) {
4293
+ if (recoveryInterruptionCode(error, executionContext.signal))
4294
+ throw error;
4295
+ const failure = failedResult(selection.requestedMethod ?? options.command, target.identity, `dependencyInstallFailed: ${provider.split('\0', 1)[0]} could not be reverified before publishing ${selection.entry.pluginId}.`);
4296
+ failure.actions = operationPreparations.get(key)?.actions ?? [];
4297
+ operationPreparationFailures.set(key, failure);
4298
+ return;
4299
+ }
4300
+ verifiedGenerations.set(provider, generation);
4301
+ }
4302
+ };
4141
4303
  const nativeTargetExecution = lifecycleCommand ? options.runtime?.nativeTargetExecution : undefined;
4142
4304
  const recordTargetCommands = (commands) => {
4143
4305
  executionContext.commandResults ??= [];
@@ -4146,19 +4308,29 @@ async function runRebuildCommandInSession(options) {
4146
4308
  executionContext.commandResults.push(result);
4147
4309
  }
4148
4310
  };
4149
- for (const selection of executionSelections) {
4311
+ const prepareDependentScript = async (selection, key) => {
4312
+ if (!deferredPreApply.has(key) || operationPreparationFailures.has(key))
4313
+ return;
4314
+ const target = preparedTargets.get(key).target;
4315
+ const command = executionCommandFor(selection);
4316
+ if (command === 'cleanup' || command === 'uninstall')
4317
+ return;
4318
+ const preparation = await prepareOperation({ command, target, driver: lockedPreparation.integration.driver });
4319
+ if (preparation.status === 'failed')
4320
+ operationPreparationFailures.set(key, preparation.result);
4321
+ else
4322
+ operationPreparations.set(key, preparation.preparation);
4323
+ };
4324
+ const executeSelection = async (selection, index) => {
4325
+ const record = (result) => { results[index] = result; };
4150
4326
  const { entry, platform } = selection;
4151
4327
  const planned = planTargetFor(lockedPlan, selection);
4152
4328
  const key = executionKey(selection, lockedPlan);
4153
4329
  const requestedMethod = selection.requestedMethod ?? options.command;
4154
- const directDependencyIds = (entry.plugin.manifest.dependencies ?? []).map((pluginName) => formatPluginId({ sourceId: entry.source.sourceId, pluginName }));
4155
- const failedDependency = directDependencyIds.find((pluginId) => {
4156
- const dependency = dependencyTargetFor(lockedPlan, planned, pluginId);
4157
- const state = dependency
4158
- ? dependencyStates.get(planExecutionKey(dependency))
4159
- : undefined;
4330
+ const failedDependency = directProviders.get(key).find((provider) => {
4331
+ const state = dependencyStates.get(provider);
4160
4332
  return state === 'failed' || state === 'skipped';
4161
- });
4333
+ })?.split('\0', 1)[0];
4162
4334
  const failedConsumer = [...(removalRequiredConsumers.get(key) ?? [])]
4163
4335
  .find((consumerKey) => {
4164
4336
  const state = dependencyStates.get(consumerKey);
@@ -4197,7 +4369,7 @@ async function runRebuildCommandInSession(options) {
4197
4369
  ? `${entry.pluginId} remains required by an unselected declared root.`
4198
4370
  : `${entry.pluginId} dependency preflight is blocked.`}`;
4199
4371
  const result = failedResult(requestedMethod, identity, message);
4200
- results.push({
4372
+ record({
4201
4373
  platforms: [platform], plugins: [], warnings: [], rebuildResults: [result],
4202
4374
  targetResults: [{
4203
4375
  target: identity,
@@ -4219,10 +4391,25 @@ async function runRebuildCommandInSession(options) {
4219
4391
  }],
4220
4392
  });
4221
4393
  dependencyStates.set(key, failedDependency || failedConsumer ? 'skipped' : 'failed');
4222
- continue;
4394
+ return;
4395
+ }
4396
+ // Target execution normally verifies its deployment immediately before writing.
4397
+ // A producer or a retained target can finish without entering that executor.
4398
+ if ((admission || providerKeys.has(key)) && currentGeneration() !== initialGeneration
4399
+ && (planned.action === 'keep' || reconcileActivationOnly || nativeTargetExecution && (nativeTargetExecution.produces?.(identity) ?? true))
4400
+ && !operationPreparationFailures.has(key)) {
4401
+ try {
4402
+ refreshCodexObservation(true);
4403
+ await preparedTargets.get(key)?.target.platformDeployment?.verify();
4404
+ }
4405
+ catch (error) {
4406
+ if (recoveryInterruptionCode(error, executionContext.signal))
4407
+ throw error;
4408
+ operationPreparationFailures.set(key, failedResult(requestedMethod, identity, error instanceof Error ? error.message : String(error)));
4409
+ }
4223
4410
  }
4224
- if (isHealthyWiderDependency(planned)) {
4225
- results.push({
4411
+ if (isHealthyWiderDependency(planned) && !operationPreparationFailures.has(key)) {
4412
+ record({
4226
4413
  platforms: [platform], plugins: [identity.pluginName], warnings: [], rebuildResults: [],
4227
4414
  targetResults: [{ target: identity, action: 'keep', state: 'completed' }],
4228
4415
  overallState: 'succeeded',
@@ -4232,13 +4419,13 @@ async function runRebuildCommandInSession(options) {
4232
4419
  }],
4233
4420
  });
4234
4421
  dependencyStates.set(key, 'kept');
4235
- continue;
4422
+ return;
4236
4423
  }
4237
4424
  const operationPreparationFailure = operationPreparationFailures.get(key);
4238
4425
  if (operationPreparationFailure) {
4239
4426
  const targetResult = toTargetResult(operationPreparationFailure);
4240
4427
  recordTargetCommands(nativeTargetExecution?.blocked?.(identity, targetResult.errorCode ?? 'targetPreparationFailed') ?? []);
4241
- results.push({
4428
+ record({
4242
4429
  platforms: [platform],
4243
4430
  plugins: [],
4244
4431
  warnings: [],
@@ -4254,7 +4441,7 @@ async function runRebuildCommandInSession(options) {
4254
4441
  }],
4255
4442
  });
4256
4443
  dependencyStates.set(key, 'failed');
4257
- continue;
4444
+ return;
4258
4445
  }
4259
4446
  if (nativeTargetExecution) {
4260
4447
  let packageFailure;
@@ -4266,15 +4453,14 @@ async function runRebuildCommandInSession(options) {
4266
4453
  }
4267
4454
  }
4268
4455
  catch (error) {
4269
- executionContext.signal?.throwIfAborted();
4270
- if (error instanceof Error && error.name === 'AbortError')
4456
+ if (recoveryInterruptionCode(error, executionContext.signal))
4271
4457
  throw error;
4272
4458
  packageFailure = 'commandPackageApplyFailed';
4273
4459
  recordTargetCommands(nativeTargetExecution.blocked?.(identity, packageFailure) ?? []);
4274
4460
  }
4275
4461
  if (packageFailure) {
4276
4462
  const result = failedResult(requestedMethod, identity, `${packageFailure}: ${entry.pluginId} requires a completed command package provider.`);
4277
- results.push({
4463
+ record({
4278
4464
  platforms: [platform], plugins: [], warnings: [], rebuildResults: [result],
4279
4465
  targetResults: [{ ...toTargetResult(result), action: planned.action }],
4280
4466
  overallState: 'failed',
@@ -4284,7 +4470,7 @@ async function runRebuildCommandInSession(options) {
4284
4470
  }],
4285
4471
  });
4286
4472
  dependencyStates.set(key, 'failed');
4287
- continue;
4473
+ return;
4288
4474
  }
4289
4475
  }
4290
4476
  if (reconcileActivationOnly) {
@@ -4294,7 +4480,7 @@ async function runRebuildCommandInSession(options) {
4294
4480
  ? preparedError.message
4295
4481
  : String(preparedError);
4296
4482
  const result = failedResult(requestedMethod, identity, message);
4297
- results.push({
4483
+ record({
4298
4484
  platforms: [platform], plugins: [], warnings: [], rebuildResults: [result],
4299
4485
  targetResults: [{
4300
4486
  target: identity,
@@ -4310,7 +4496,7 @@ async function runRebuildCommandInSession(options) {
4310
4496
  }],
4311
4497
  });
4312
4498
  dependencyStates.set(key, 'failed');
4313
- continue;
4499
+ return;
4314
4500
  }
4315
4501
  const actions = operationPreparations.get(key)?.actions
4316
4502
  ?? [];
@@ -4320,7 +4506,7 @@ async function runRebuildCommandInSession(options) {
4320
4506
  actions,
4321
4507
  cleanupAttempted: false, removed: [], absent: [], residual: [], quarantined: [], failures: [],
4322
4508
  };
4323
- results.push({
4509
+ record({
4324
4510
  platforms: [platform],
4325
4511
  plugins: result.status === 'succeeded' ? [identity.pluginName] : [],
4326
4512
  warnings: result.failures.map((failure) => failure.message),
@@ -4340,7 +4526,7 @@ async function runRebuildCommandInSession(options) {
4340
4526
  }],
4341
4527
  });
4342
4528
  dependencyStates.set(key, result.status === 'succeeded' ? 'completed' : 'failed');
4343
- continue;
4529
+ return;
4344
4530
  }
4345
4531
  if (planned.action === 'keep'
4346
4532
  && !(preparedTargets.get(key)?.target.writeNativeRequired ?? false)
@@ -4352,7 +4538,7 @@ async function runRebuildCommandInSession(options) {
4352
4538
  ? preparedError.message
4353
4539
  : String(preparedError);
4354
4540
  const result = failedResult(requestedMethod, identity, message);
4355
- results.push({
4541
+ record({
4356
4542
  platforms: [platform], plugins: [], warnings: [], rebuildResults: [result],
4357
4543
  targetResults: [{
4358
4544
  target: identity,
@@ -4368,7 +4554,7 @@ async function runRebuildCommandInSession(options) {
4368
4554
  }],
4369
4555
  });
4370
4556
  dependencyStates.set(key, 'failed');
4371
- continue;
4557
+ return;
4372
4558
  }
4373
4559
  const actions = operationPreparations.get(key)?.actions
4374
4560
  ?? [];
@@ -4377,7 +4563,7 @@ async function runRebuildCommandInSession(options) {
4377
4563
  actions,
4378
4564
  cleanupAttempted: false, removed: [], absent: [], residual: [], quarantined: [], failures: [],
4379
4565
  };
4380
- results.push({
4566
+ record({
4381
4567
  platforms: [platform], plugins: [identity.pluginName], warnings: [], rebuildResults: [result],
4382
4568
  targetResults: [{ target: identity, action: 'keep', state: 'completed' }],
4383
4569
  overallState: 'succeeded',
@@ -4387,7 +4573,7 @@ async function runRebuildCommandInSession(options) {
4387
4573
  }],
4388
4574
  });
4389
4575
  dependencyStates.set(key, 'kept');
4390
- continue;
4576
+ return;
4391
4577
  }
4392
4578
  const marketplaceName = marketplaceNameFor(entry, platform, planned.resolvedScope);
4393
4579
  const namespacedSource = {
@@ -4442,11 +4628,11 @@ async function runRebuildCommandInSession(options) {
4442
4628
  preparationError: preparedTargetErrors.get(key),
4443
4629
  },
4444
4630
  });
4445
- results.push(executionResult);
4631
+ record(executionResult);
4446
4632
  dependencyStates.set(key, executionResult.overallState === 'succeeded' ? 'completed' : 'failed');
4447
- }
4633
+ };
4448
4634
  const failCompletedCodexTarget = (options_) => {
4449
- const resultIndex = results.findIndex((candidate) => candidate.targetResults.some((target) => target.target.pluginId === options_.identity.pluginId
4635
+ const resultIndex = results.findIndex((candidate) => candidate?.targetResults.some((target) => target.target.pluginId === options_.identity.pluginId
4450
4636
  && target.target.platform === 'codex'
4451
4637
  && target.target.scope === options_.identity.scope));
4452
4638
  if (resultIndex === -1)
@@ -4496,182 +4682,356 @@ async function runRebuildCommandInSession(options) {
4496
4682
  ].join('\0'), 'failed');
4497
4683
  return true;
4498
4684
  };
4499
- const activationMutationPluginIds = new Set(lockedCodexPlans.flatMap((plan) => [
4500
- ...plan.activationActions.user,
4501
- ...plan.activationActions.project,
4502
- ].flatMap((action) => action.action === 'none' ? [] : [action.pluginId])));
4503
- for (const selection of executionSelections) {
4504
- const { entry, platform } = selection;
4505
- const key = executionKey(selection, lockedPlan);
4506
- if (platform !== 'codex'
4507
- || !activationMutationPluginIds.has(entry.pluginId)
4508
- || (dependencyStates.get(key) !== 'completed'
4509
- && dependencyStates.get(key) !== 'kept'))
4510
- continue;
4511
- const prepared = preparedTargets.get(key)?.target;
4512
- if (!prepared)
4513
- continue;
4685
+ const codexSelections = executionSelections.filter(({ platform }) => platform === 'codex');
4686
+ const codexProviders = new Set(options.runtime?.batchInstallPlatform === 'codex' || deferredPreApply.size || serialScriptGeneration
4687
+ ? codexSelections.flatMap((selection) => directProviders.get(executionKey(selection, lockedPlan))) : []);
4688
+ const reportTargetState = (selection, state) => {
4689
+ const identity = targetIdentity(selection, planTargetFor(lockedPlan, selection).resolvedScope);
4514
4690
  try {
4515
- await lockedPreparation.integration.prepareNativeMarketplaceGroup(prepared);
4691
+ options.runtime?.onInstallTargetState?.(identity, state);
4516
4692
  }
4517
- catch (error) {
4518
- const message = error instanceof Error ? error.message : String(error);
4519
- failCompletedCodexTarget({ identity: prepared.identity, message, phase: 'native.write' });
4520
- }
4521
- }
4522
- const successfulCodexTargetScopes = new Set(executionSelections.flatMap((selection) => selection.platform === 'codex'
4523
- && (dependencyStates.get(executionKey(selection, lockedPlan)) === 'completed'
4524
- || dependencyStates.get(executionKey(selection, lockedPlan)) === 'kept')
4525
- ? [`${selection.entry.pluginId}\0${planTargetFor(lockedPlan, selection).resolvedScope}`]
4526
- : []));
4527
- const activationUserBefore = await readCodexConfigFile(resolveCodexPaths(options.commandOptions.cwd, 'user', runtimeEnv).configTomlPath);
4528
- const activationProjectBefore = options.commandOptions.scope === 'project'
4529
- ? await readCodexConfigFile(resolveCodexPaths(options.commandOptions.cwd, 'project', runtimeEnv).configTomlPath)
4530
- : undefined;
4531
- const preservedActivations = {
4532
- user: new Map(Object.entries(activationUserBefore.snapshot.plugins)
4533
- .map(([pluginId, activation]) => [pluginId, activation.enabled === true])),
4534
- project: new Map(Object.entries(activationProjectBefore?.snapshot.plugins ?? {})
4535
- .map(([pluginId, activation]) => [pluginId, activation.enabled === true])),
4693
+ catch { /* Progress observers cannot change a target's outcome. */ }
4536
4694
  };
4537
- const activationPlans = selectCodexActivationPlans(lockedCodexPlans, successfulCodexTargetScopes, preservedActivations, originalUserActivations);
4538
- if (activationPlans.length > 0
4539
- || lockedPreparation.integration.driver.completePostchecks) {
4540
- let activationError;
4541
- const activationMutationMarketplaces = new Set();
4542
- try {
4543
- if (activationPlans.length > 0) {
4544
- await executeCodexReconcileActivations({
4545
- plans: activationPlans,
4546
- cwd: options.commandOptions.cwd,
4547
- env: runtimeEnv,
4548
- manager: executionContext.codexManager,
4549
- runner: executionContext.nativeCliRunner,
4550
- observationSession: executionContext.codexObservationSession,
4551
- preflightCompleted: true,
4552
- mutationMarketplaces: activationMutationMarketplaces,
4553
- observationScopeByMarketplace: codexObservationScopeByMarketplace,
4554
- });
4695
+ const pendingCodex = new Set();
4696
+ const runSelection = async (selection, index) => {
4697
+ reportTargetState(selection, 'running');
4698
+ refreshCodexObservation();
4699
+ await executeSelection(selection, index);
4700
+ const key = executionKey(selection, lockedPlan);
4701
+ if (selection.platform === 'codex')
4702
+ pendingCodex.add(selection);
4703
+ const unconfirmed = results[index]?.rebuildResults.flatMap((result) => [
4704
+ ...result.failures.flatMap((failure) => failure.operationDiagnostic ? [failure.operationDiagnostic] : []),
4705
+ ...(result.deploymentReceipts ?? []).flatMap((receipt) => receipt.diagnostics),
4706
+ ]).find((diagnostic) => recoveryInterruptionCode(diagnostic) === 'processCleanupUnconfirmed');
4707
+ if (unconfirmed) {
4708
+ const message = 'safeMessage' in unconfirmed ? unconfirmed.safeMessage : unconfirmed.message;
4709
+ throw attachSafeOperationError(new Error(message), { code: unconfirmed.code, safeMessage: message });
4710
+ }
4711
+ if (selection.platform === 'codex') {
4712
+ const prepared = preparedTargets.get(key)?.target;
4713
+ if (codexProviders.has(key) && prepared && providerReady(key)) {
4714
+ try {
4715
+ await lockedPreparation.integration.postcheckCodexProvider(prepared);
4716
+ }
4717
+ catch (error) {
4718
+ if (recoveryInterruptionCode(error, executionContext.signal))
4719
+ throw error;
4720
+ failCompletedCodexTarget({ identity: prepared.identity, message: error instanceof Error ? error.message : String(error) });
4721
+ }
4555
4722
  }
4723
+ if (providerReady(key) && providerDeployment(key))
4724
+ verifiedGenerations.set(key, currentGeneration());
4725
+ if (!codexProviders.has(key))
4726
+ return;
4727
+ pendingCodex.delete(selection);
4556
4728
  }
4557
- catch (error) {
4558
- activationError = error;
4729
+ else if (providerReady(key) && providerDeployment(key)) {
4730
+ verifiedGenerations.set(key, currentGeneration());
4559
4731
  }
4560
- try {
4561
- await lockedPreparation.integration.captureCodexPostMutationSnapshots([...activationMutationMarketplaces]);
4732
+ reportTargetState(selection, 'completed');
4733
+ };
4734
+ const finishCodex = async () => {
4735
+ refreshCodexObservation();
4736
+ for (const selection of codexSelections) {
4737
+ const key = executionKey(selection, lockedPlan);
4738
+ if (!admission || admission.exclusiveGeneration === verifiedGenerations.get(key))
4739
+ continue;
4740
+ const target = preparedTargets.get(key)?.target;
4741
+ if (target && ['completed', 'kept'].includes(dependencyStates.get(key) ?? '')) {
4742
+ try {
4743
+ await target.platformDeployment?.verify();
4744
+ }
4745
+ catch (error) {
4746
+ if (recoveryInterruptionCode(error, executionContext.signal))
4747
+ throw error;
4748
+ failCompletedCodexTarget({ identity: target.identity, message: error instanceof Error ? error.message : String(error) });
4749
+ }
4750
+ }
4562
4751
  }
4563
- catch (error) {
4564
- activationError ??= error;
4752
+ const activationMutationPluginIds = new Set(lockedCodexPlans.flatMap((plan) => [
4753
+ ...plan.activationActions.user,
4754
+ ...plan.activationActions.project,
4755
+ ].flatMap((action) => action.action === 'none' ? [] : [action.pluginId])));
4756
+ for (const selection of executionSelections) {
4757
+ const { entry, platform } = selection;
4758
+ const key = executionKey(selection, lockedPlan);
4759
+ if (platform !== 'codex'
4760
+ || !activationMutationPluginIds.has(entry.pluginId)
4761
+ || (dependencyStates.get(key) !== 'completed'
4762
+ && dependencyStates.get(key) !== 'kept'))
4763
+ continue;
4764
+ const prepared = preparedTargets.get(key)?.target;
4765
+ if (!prepared)
4766
+ continue;
4767
+ try {
4768
+ await lockedPreparation.integration.prepareNativeMarketplaceGroup(prepared);
4769
+ }
4770
+ catch (error) {
4771
+ const message = error instanceof Error ? error.message : String(error);
4772
+ failCompletedCodexTarget({ identity: prepared.identity, message, phase: 'native.write' });
4773
+ }
4565
4774
  }
4566
- const failedCodexTargetScopes = new Set(executionSelections.flatMap((selection) => selection.platform === 'codex'
4567
- && (dependencyStates.get(executionKey(selection, lockedPlan)) === 'failed'
4568
- || dependencyStates.get(executionKey(selection, lockedPlan)) === 'skipped')
4775
+ const successfulCodexTargetScopes = new Set(executionSelections.flatMap((selection) => selection.platform === 'codex'
4776
+ && (dependencyStates.get(executionKey(selection, lockedPlan)) === 'completed'
4777
+ || dependencyStates.get(executionKey(selection, lockedPlan)) === 'kept')
4569
4778
  ? [`${selection.entry.pluginId}\0${planTargetFor(lockedPlan, selection).resolvedScope}`]
4570
4779
  : []));
4571
- for (const failure of await lockedPreparation.integration.driver.completePostchecks?.() ?? []) {
4572
- const message = failure.error instanceof Error
4573
- ? failure.error.message
4574
- : String(failure.error);
4575
- if (failCompletedCodexTarget({ identity: failure.target.identity, message })) {
4576
- const failedPluginId = failure.target.identity.pluginId
4577
- ?? failure.target.identity.pluginName;
4578
- failedCodexTargetScopes.add(`${failedPluginId}\0${failure.target.identity.scope}`);
4579
- }
4580
- }
4581
- if (!activationError && activationPlans.length > 0) {
4582
- const postcheckTargetScopes = new Set([...successfulCodexTargetScopes]
4583
- .filter((key) => !failedCodexTargetScopes.has(key)));
4584
- const postcheckPlans = selectCodexActivationPlans(activationPlans, postcheckTargetScopes, preservedActivations, originalUserActivations);
4780
+ const activationUserBefore = await readCodexConfigFile(resolveCodexPaths(options.commandOptions.cwd, 'user', runtimeEnv).configTomlPath);
4781
+ const activationProjectBefore = options.commandOptions.scope === 'project'
4782
+ ? await readCodexConfigFile(resolveCodexPaths(options.commandOptions.cwd, 'project', runtimeEnv).configTomlPath)
4783
+ : undefined;
4784
+ const preservedActivations = {
4785
+ user: new Map(Object.entries(activationUserBefore.snapshot.plugins)
4786
+ .map(([pluginId, activation]) => [pluginId, activation.enabled === true])),
4787
+ project: new Map(Object.entries(activationProjectBefore?.snapshot.plugins ?? {})
4788
+ .map(([pluginId, activation]) => [pluginId, activation.enabled === true])),
4789
+ };
4790
+ const activationPlans = selectCodexActivationPlans(lockedCodexPlans, successfulCodexTargetScopes, preservedActivations, originalUserActivations);
4791
+ if (activationPlans.length > 0
4792
+ || lockedPreparation.integration.driver.completePostchecks) {
4793
+ let activationError;
4794
+ const activationMutationMarketplaces = new Set();
4585
4795
  try {
4586
- await postcheckCodexReconcileActivations({
4587
- plans: postcheckPlans,
4588
- cwd: options.commandOptions.cwd,
4589
- env: runtimeEnv,
4590
- manager: executionContext.codexManager,
4591
- runner: executionContext.nativeCliRunner,
4592
- observationScopeByMarketplace: codexObservationScopeByMarketplace,
4593
- observationSession: executionContext.codexObservationSession,
4594
- });
4796
+ if (activationPlans.length > 0) {
4797
+ await executeCodexReconcileActivations({
4798
+ plans: activationPlans,
4799
+ cwd: options.commandOptions.cwd,
4800
+ env: runtimeEnv,
4801
+ manager: executionContext.codexManager,
4802
+ runner: executionContext.nativeCliRunner,
4803
+ observationSession: executionContext.codexObservationSession,
4804
+ preflightCompleted: true,
4805
+ mutationMarketplaces: activationMutationMarketplaces,
4806
+ observationScopeByMarketplace: codexObservationScopeByMarketplace,
4807
+ });
4808
+ }
4595
4809
  }
4596
4810
  catch (error) {
4597
4811
  activationError = error;
4598
4812
  }
4599
- }
4600
- if (activationError) {
4601
- const failedActivationTargetScopes = failedCodexActivationTargetScopes({
4602
- error: activationError,
4603
- plans: activationPlans,
4604
- successfulTargetScopes: successfulCodexTargetScopes,
4605
- });
4606
- const message = activationError instanceof Error
4607
- ? activationError.message
4608
- : String(activationError);
4609
- const failedSelections = executionSelections.filter((candidate) => candidate.platform === 'codex'
4610
- && failedActivationTargetScopes.has(`${candidate.entry.pluginId}\0${planTargetFor(lockedPlan, candidate).resolvedScope}`));
4611
- if (failedSelections.length === 0)
4612
- throw activationError;
4613
- for (const selection of failedSelections) {
4614
- const planned = planTargetFor(lockedPlan, selection);
4615
- const identity = {
4616
- sourceId: selection.entry.source.sourceId,
4617
- sourceIdentity: selection.entry.source.sourceIdentity,
4618
- pluginId: selection.entry.pluginId,
4619
- pluginName: selection.entry.plugin.manifest.name,
4620
- pluginVersion: selection.entry.plugin.manifest.version,
4621
- platform: 'codex',
4622
- scope: planned.resolvedScope,
4623
- cwd: options.commandOptions.cwd,
4624
- };
4625
- if (!failCompletedCodexTarget({ identity, message }))
4813
+ try {
4814
+ await lockedPreparation.integration.captureCodexPostMutationSnapshots([...activationMutationMarketplaces]);
4815
+ }
4816
+ catch (error) {
4817
+ activationError ??= error;
4818
+ }
4819
+ const failedCodexTargetScopes = new Set(executionSelections.flatMap((selection) => selection.platform === 'codex'
4820
+ && (dependencyStates.get(executionKey(selection, lockedPlan)) === 'failed'
4821
+ || dependencyStates.get(executionKey(selection, lockedPlan)) === 'skipped')
4822
+ ? [`${selection.entry.pluginId}\0${planTargetFor(lockedPlan, selection).resolvedScope}`]
4823
+ : []));
4824
+ for (const failure of await lockedPreparation.integration.driver.completePostchecks?.() ?? []) {
4825
+ if (recoveryInterruptionCode(failure.error, executionContext.signal))
4826
+ throw failure.error;
4827
+ const message = failure.error instanceof Error
4828
+ ? failure.error.message
4829
+ : String(failure.error);
4830
+ if (failCompletedCodexTarget({ identity: failure.target.identity, message })) {
4831
+ const failedPluginId = failure.target.identity.pluginId
4832
+ ?? failure.target.identity.pluginName;
4833
+ failedCodexTargetScopes.add(`${failedPluginId}\0${failure.target.identity.scope}`);
4834
+ }
4835
+ }
4836
+ if (!activationError && activationPlans.length > 0) {
4837
+ const postcheckTargetScopes = new Set([...successfulCodexTargetScopes]
4838
+ .filter((key) => !failedCodexTargetScopes.has(key)));
4839
+ const postcheckPlans = selectCodexActivationPlans(activationPlans, postcheckTargetScopes, preservedActivations, originalUserActivations);
4840
+ try {
4841
+ await postcheckCodexReconcileActivations({
4842
+ plans: postcheckPlans,
4843
+ cwd: options.commandOptions.cwd,
4844
+ env: runtimeEnv,
4845
+ manager: executionContext.codexManager,
4846
+ runner: executionContext.nativeCliRunner,
4847
+ observationScopeByMarketplace: codexObservationScopeByMarketplace,
4848
+ observationSession: executionContext.codexObservationSession,
4849
+ });
4850
+ }
4851
+ catch (error) {
4852
+ activationError = error;
4853
+ }
4854
+ }
4855
+ if (activationError) {
4856
+ if (recoveryInterruptionCode(activationError, executionContext.signal))
4857
+ throw activationError;
4858
+ const failedActivationTargetScopes = failedCodexActivationTargetScopes({
4859
+ error: activationError,
4860
+ plans: activationPlans,
4861
+ successfulTargetScopes: successfulCodexTargetScopes,
4862
+ });
4863
+ const message = activationError instanceof Error
4864
+ ? activationError.message
4865
+ : String(activationError);
4866
+ const failedSelections = executionSelections.filter((candidate) => candidate.platform === 'codex'
4867
+ && failedActivationTargetScopes.has(`${candidate.entry.pluginId}\0${planTargetFor(lockedPlan, candidate).resolvedScope}`));
4868
+ if (failedSelections.length === 0)
4626
4869
  throw activationError;
4627
- failedCodexTargetScopes.add(`${selection.entry.pluginId}\0${planned.resolvedScope}`);
4870
+ for (const selection of failedSelections) {
4871
+ const planned = planTargetFor(lockedPlan, selection);
4872
+ const identity = {
4873
+ sourceId: selection.entry.source.sourceId,
4874
+ sourceIdentity: selection.entry.source.sourceIdentity,
4875
+ pluginId: selection.entry.pluginId,
4876
+ pluginName: selection.entry.plugin.manifest.name,
4877
+ pluginVersion: selection.entry.plugin.manifest.version,
4878
+ platform: 'codex',
4879
+ scope: planned.resolvedScope,
4880
+ cwd: options.commandOptions.cwd,
4881
+ };
4882
+ if (!failCompletedCodexTarget({ identity, message }))
4883
+ throw activationError;
4884
+ failedCodexTargetScopes.add(`${selection.entry.pluginId}\0${planned.resolvedScope}`);
4885
+ }
4886
+ }
4887
+ let propagated = true;
4888
+ while (propagated) {
4889
+ propagated = false;
4890
+ for (const selection of executionSelections.filter((candidate) => candidate.platform === 'codex')) {
4891
+ const planned = planTargetFor(lockedPlan, selection);
4892
+ const targetScopeKey = `${selection.entry.pluginId}\0${planned.resolvedScope}`;
4893
+ if (failedCodexTargetScopes.has(targetScopeKey))
4894
+ continue;
4895
+ const failedDependency = (selection.entry.plugin.manifest.dependencies ?? [])
4896
+ .map((pluginName) => formatPluginId({
4897
+ sourceId: selection.entry.source.sourceId,
4898
+ pluginName,
4899
+ }))
4900
+ .find((pluginId) => {
4901
+ const dependency = dependencyTargetFor(lockedPlan, planned, pluginId);
4902
+ return dependency
4903
+ ? failedCodexTargetScopes.has(`${pluginId}\0${dependency.requestedScope ?? dependency.resolvedScope}`)
4904
+ : false;
4905
+ });
4906
+ if (!failedDependency)
4907
+ continue;
4908
+ const identity = {
4909
+ sourceId: selection.entry.source.sourceId,
4910
+ sourceIdentity: selection.entry.source.sourceIdentity,
4911
+ pluginId: selection.entry.pluginId,
4912
+ pluginName: selection.entry.plugin.manifest.name,
4913
+ pluginVersion: selection.entry.plugin.manifest.version,
4914
+ platform: 'codex',
4915
+ scope: planned.resolvedScope,
4916
+ cwd: options.commandOptions.cwd,
4917
+ };
4918
+ const message = `dependencyInstallFailed: ${selection.entry.pluginId} requires failed dependency ${failedDependency}.`;
4919
+ if (failCompletedCodexTarget({
4920
+ identity,
4921
+ message,
4922
+ recoveryActions: [
4923
+ `run aw plugin sync ${selection.entry.pluginId} --target codex --context ${planned.resolvedScope}`,
4924
+ ],
4925
+ })) {
4926
+ failedCodexTargetScopes.add(targetScopeKey);
4927
+ dependencyStates.set(executionKey(selection, lockedPlan), 'failed');
4928
+ propagated = true;
4929
+ }
4930
+ }
4628
4931
  }
4629
4932
  }
4630
- let propagated = true;
4631
- while (propagated) {
4632
- propagated = false;
4633
- for (const selection of executionSelections.filter((candidate) => candidate.platform === 'codex')) {
4634
- const planned = planTargetFor(lockedPlan, selection);
4635
- const targetScopeKey = `${selection.entry.pluginId}\0${planned.resolvedScope}`;
4636
- if (failedCodexTargetScopes.has(targetScopeKey))
4637
- continue;
4638
- const failedDependency = (selection.entry.plugin.manifest.dependencies ?? [])
4639
- .map((pluginName) => formatPluginId({
4640
- sourceId: selection.entry.source.sourceId,
4641
- pluginName,
4642
- }))
4643
- .find((pluginId) => {
4644
- const dependency = dependencyTargetFor(lockedPlan, planned, pluginId);
4645
- return dependency
4646
- ? failedCodexTargetScopes.has(`${pluginId}\0${dependency.requestedScope ?? dependency.resolvedScope}`)
4647
- : false;
4648
- });
4649
- if (!failedDependency)
4650
- continue;
4651
- const identity = {
4652
- sourceId: selection.entry.source.sourceId,
4653
- sourceIdentity: selection.entry.source.sourceIdentity,
4654
- pluginId: selection.entry.pluginId,
4655
- pluginName: selection.entry.plugin.manifest.name,
4656
- pluginVersion: selection.entry.plugin.manifest.version,
4657
- platform: 'codex',
4658
- scope: planned.resolvedScope,
4659
- cwd: options.commandOptions.cwd,
4660
- };
4661
- const message = `dependencyInstallFailed: ${selection.entry.pluginId} requires failed dependency ${failedDependency}.`;
4662
- if (failCompletedCodexTarget({
4663
- identity,
4664
- message,
4665
- recoveryActions: [
4666
- `run aw plugin sync ${selection.entry.pluginId} --target codex --context ${planned.resolvedScope}`,
4667
- ],
4668
- })) {
4669
- failedCodexTargetScopes.add(targetScopeKey);
4670
- dependencyStates.set(executionKey(selection, lockedPlan), 'failed');
4671
- propagated = true;
4933
+ };
4934
+ const privatePackages = [];
4935
+ try {
4936
+ if (admission && options.runtime?.batchInstallPlatform) {
4937
+ const selectedKeys = new Set(executionSelections.map((selection) => executionKey(selection, lockedPlan)));
4938
+ const tasks = executionSelections.flatMap((selection, index) => {
4939
+ const id = executionKey(selection, lockedPlan);
4940
+ const dependencies = directProviders.get(id).filter((key) => selectedKeys.has(key));
4941
+ const target = lockedPreparation.preparedTargets.get(id)?.target;
4942
+ const deployment = target?.platformDeployment;
4943
+ const resources = nativeInstallResources(deployment?.plans ?? []);
4944
+ const producesCommands = target && nativeTargetExecution
4945
+ && (nativeTargetExecution.produces?.(target.identity) ?? true);
4946
+ if (deployment?.writesManagedCommands || producesCommands
4947
+ || target?.operationActions?.some((action) => action.kind === 'syncManagedCommandPackage')) {
4948
+ resources.push({ kind: 'path', value: path.join(resolveAwHome(runtimeEnv), 'commands') });
4949
+ }
4950
+ const leaves = [];
4951
+ let prerequisites = dependencies;
4952
+ const providerPlans = [...providerClosure(id)].flatMap((key) => preparedTargets.get(key)?.target.platformDeployment?.plans ?? []);
4953
+ if (providerPlans.length)
4954
+ for (const resource of nativeInstallResources(providerPlans)) {
4955
+ resources.push(resource.kind === 'exclusive' ? resource : { ...resource, access: 'read' });
4956
+ }
4957
+ if (deferredPreApply.has(id) && operationPreparations.has(id)) {
4958
+ const script = `preApply:\0${id}`;
4959
+ leaves.push({ id: script, dependencies, resources: [{ kind: 'exclusive' }], run: async () => {
4960
+ if (!providersReady(id))
4961
+ return;
4962
+ await verifyProviders(selection, id);
4963
+ await prepareDependentScript(selection, id);
4964
+ } });
4965
+ prerequisites = [script];
4966
+ }
4967
+ const staging = deployment?.privatePackage;
4968
+ if (staging && executionSelections.length >= 2 && operationPreparations.has(id)) {
4969
+ privatePackages.push(staging);
4970
+ const stage = `package-staging:\0${id}`;
4971
+ leaves.push({ id: stage, dependencies: prerequisites, resources: [], run: async () => {
4972
+ if (!providersReady(id) || operationPreparationFailures.has(id))
4973
+ return;
4974
+ reportTargetState(selection, 'running');
4975
+ try {
4976
+ await staging.prepare();
4977
+ }
4978
+ catch (error) {
4979
+ if (recoveryInterruptionCode(error, executionContext.signal))
4980
+ throw error;
4981
+ operationPreparationFailures.set(id, failedResult(options.command, target.identity, error instanceof Error ? error.message : String(error)));
4982
+ }
4983
+ } });
4984
+ prerequisites = [stage];
4985
+ }
4986
+ leaves.push({ id, dependencies: prerequisites, resources, run: async () => {
4987
+ await verifyProviders(selection, id);
4988
+ await runSelection(selection, index);
4989
+ } });
4990
+ return leaves;
4991
+ });
4992
+ await runInstallTasks(tasks, { admission, signal: executionContext.signal });
4993
+ }
4994
+ else {
4995
+ for (const [index, selection] of executionSelections.entries()) {
4996
+ if (options.runtime?.batchInstallPlatform)
4997
+ executionContext.signal?.throwIfAborted();
4998
+ const key = executionKey(selection, lockedPlan);
4999
+ if (deferredPreApply.has(key) && providersReady(key)) {
5000
+ await verifyProviders(selection, key);
5001
+ await prepareDependentScript(selection, key);
4672
5002
  }
5003
+ await verifyProviders(selection, key);
5004
+ await runSelection(selection, index);
4673
5005
  }
4674
5006
  }
5007
+ if (options.runtime?.batchInstallPlatform)
5008
+ executionContext.signal?.throwIfAborted();
5009
+ if (codexSelections.length) {
5010
+ if (admission)
5011
+ await admission.run(nativeInstallResources(lockedOperationPlan.deploymentPlans ?? []), finishCodex, executionContext.signal);
5012
+ else
5013
+ await finishCodex();
5014
+ }
5015
+ if (options.runtime?.batchInstallPlatform)
5016
+ executionContext.signal?.throwIfAborted();
5017
+ for (const selection of pendingCodex)
5018
+ reportTargetState(selection, 'completed');
5019
+ }
5020
+ catch (error) {
5021
+ const code = recoveryInterruptionCode(error, executionContext.signal);
5022
+ if (!code)
5023
+ throw error;
5024
+ for (const selection of pendingCodex) {
5025
+ const state = dependencyStates.get(executionKey(selection, lockedPlan));
5026
+ if (state !== 'completed' && state !== 'kept')
5027
+ continue;
5028
+ failCompletedCodexTarget({ identity: targetIdentity(selection, planTargetFor(lockedPlan, selection).resolvedScope),
5029
+ message: `${code}: Codex postcheck did not complete.` });
5030
+ }
5031
+ throw new RebuildInterruptedError(mergeRebuildCommandResults(results.filter(Boolean)), error);
5032
+ }
5033
+ finally {
5034
+ await Promise.all(privatePackages.map((staging) => staging.dispose()));
4675
5035
  }
4676
5036
  const merged = mergeRebuildCommandResults(results);
4677
5037
  if (malformedSelectedConfigPreserved) {
@@ -4763,7 +5123,8 @@ export async function runRebuildCommand(options) {
4763
5123
  runtime: { ...options.runtime, env: executionInput.context.env },
4764
5124
  };
4765
5125
  try {
4766
- if (scopedOptions.runtime?.codexObservationSession) {
5126
+ if (scopedOptions.runtime?.codexObservationSession
5127
+ || scopedOptions.runtime?.batchInstallPlatform && scopedOptions.runtime.batchInstallPlatform !== 'codex') {
4767
5128
  return withCommands(await runRebuildCommandInSession(scopedOptions));
4768
5129
  }
4769
5130
  const env = executionInput.context.env;