@lesliechan721/aw 0.1.0-beta.95 → 0.1.0-beta.97

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 (114) hide show
  1. package/dist/scripts/aw-skill-eval-materializer.js +3 -2
  2. package/dist/scripts/aw-skill-eval-materializer.js.map +1 -1
  3. package/dist/scripts/bundle-plugins.js +10 -3
  4. package/dist/scripts/bundle-plugins.js.map +1 -1
  5. package/dist/scripts/plugin-staging.js +2 -1
  6. package/dist/scripts/plugin-staging.js.map +1 -1
  7. package/dist/scripts/plugin-test-context-guard.d.mts +1 -0
  8. package/dist/scripts/plugin-test-context-guard.mjs +59 -0
  9. package/dist/scripts/plugin-test-context-guard.mjs.map +1 -0
  10. package/dist/scripts/test-plugin-scripts.js +90 -44
  11. package/dist/scripts/test-plugin-scripts.js.map +1 -1
  12. package/dist/scripts/test-workers.mjs +1 -1
  13. package/dist/scripts/test-workers.mjs.map +1 -1
  14. package/dist/src/commands/aw-capabilities.d.ts +1 -1
  15. package/dist/src/commands/aw-capabilities.js +3 -0
  16. package/dist/src/commands/aw-capabilities.js.map +1 -1
  17. package/dist/src/commands/permission-batch.d.ts +1 -1
  18. package/dist/src/commands/permission-batch.js +6 -3
  19. package/dist/src/commands/permission-batch.js.map +1 -1
  20. package/dist/src/commands/plugin-capabilities.js +5 -0
  21. package/dist/src/commands/plugin-capabilities.js.map +1 -1
  22. package/dist/src/commands/public-lifecycle-result.js +3 -2
  23. package/dist/src/commands/public-lifecycle-result.js.map +1 -1
  24. package/dist/src/commands/public-lifecycle.js +12 -8
  25. package/dist/src/commands/public-lifecycle.js.map +1 -1
  26. package/dist/src/commands/public-plugin-query.js +3 -2
  27. package/dist/src/commands/public-plugin-query.js.map +1 -1
  28. package/dist/src/commands/rebuild-command.d.ts +12 -0
  29. package/dist/src/commands/rebuild-command.js +78 -8
  30. package/dist/src/commands/rebuild-command.js.map +1 -1
  31. package/dist/src/commands/rebuild-integration.d.ts +8 -5
  32. package/dist/src/commands/rebuild-integration.js +21 -7
  33. package/dist/src/commands/rebuild-integration.js.map +1 -1
  34. package/dist/src/commands/rebuild-platform-integration.d.ts +16 -2
  35. package/dist/src/commands/rebuild-platform-integration.js +314 -23
  36. package/dist/src/commands/rebuild-platform-integration.js.map +1 -1
  37. package/dist/src/commands/review-inspection.js +3 -2
  38. package/dist/src/commands/review-inspection.js.map +1 -1
  39. package/dist/src/generators/local-plugin.js +117 -37
  40. package/dist/src/generators/local-plugin.js.map +1 -1
  41. package/dist/src/platforms/contracts.d.ts +6 -0
  42. package/dist/src/platforms/discovery.js +20 -18
  43. package/dist/src/platforms/discovery.js.map +1 -1
  44. package/dist/src/platforms/inspection-grok.js +20 -6
  45. package/dist/src/platforms/inspection-grok.js.map +1 -1
  46. package/dist/src/platforms/inspection-native.js +9 -2
  47. package/dist/src/platforms/inspection-native.js.map +1 -1
  48. package/dist/src/platforms/inspection-query.d.ts +2 -0
  49. package/dist/src/platforms/inspection-query.js +20 -21
  50. package/dist/src/platforms/inspection-query.js.map +1 -1
  51. package/dist/src/platforms/read-only-retry-policy.d.ts +34 -0
  52. package/dist/src/platforms/read-only-retry-policy.js +70 -0
  53. package/dist/src/platforms/read-only-retry-policy.js.map +1 -0
  54. package/dist/src/portable/commands.d.ts +3 -1
  55. package/dist/src/portable/commands.js +11 -23
  56. package/dist/src/portable/commands.js.map +1 -1
  57. package/dist/src/portable/historical-materialization.d.ts +4 -1
  58. package/dist/src/portable/historical-materialization.js +35 -11
  59. package/dist/src/portable/historical-materialization.js.map +1 -1
  60. package/dist/src/portable/materializer.d.ts +17 -1
  61. package/dist/src/portable/materializer.js +95 -29
  62. package/dist/src/portable/materializer.js.map +1 -1
  63. package/dist/src/portable/recovery.d.ts +3 -2
  64. package/dist/src/portable/recovery.js +49 -8
  65. package/dist/src/portable/recovery.js.map +1 -1
  66. package/dist/src/recovery/coordinator.d.ts +9 -2
  67. package/dist/src/recovery/coordinator.js +105 -39
  68. package/dist/src/recovery/coordinator.js.map +1 -1
  69. package/dist/src/recovery/joint-coordinator.d.ts +3 -3
  70. package/dist/src/recovery/joint-coordinator.js +402 -320
  71. package/dist/src/recovery/joint-coordinator.js.map +1 -1
  72. package/dist/src/recovery/retirement.d.ts +2 -2
  73. package/dist/src/recovery/retirement.js +3 -3
  74. package/dist/src/recovery/retirement.js.map +1 -1
  75. package/dist/src/review/skill-materialization.d.ts +2 -1
  76. package/dist/src/review/skill-materialization.js +2 -3
  77. package/dist/src/review/skill-materialization.js.map +1 -1
  78. package/dist/src/tui/config-value-presentation.js +7 -4
  79. package/dist/src/tui/config-value-presentation.js.map +1 -1
  80. package/dist/src/tui/console-app-v4.js +1 -1
  81. package/dist/src/tui/console-app-v4.js.map +1 -1
  82. package/dist/src/utils/artifact-renderer.d.ts +9 -2
  83. package/dist/src/utils/artifact-renderer.js +67 -31
  84. package/dist/src/utils/artifact-renderer.js.map +1 -1
  85. package/dist/src/utils/bundle-layout.d.ts +2 -0
  86. package/dist/src/utils/bundle-layout.js +40 -13
  87. package/dist/src/utils/bundle-layout.js.map +1 -1
  88. package/dist/src/utils/catalog-generation-resolver.d.ts +9 -2
  89. package/dist/src/utils/catalog-generation-resolver.js +82 -10
  90. package/dist/src/utils/catalog-generation-resolver.js.map +1 -1
  91. package/dist/src/utils/catalog-operation-context.d.ts +35 -2
  92. package/dist/src/utils/catalog-operation-context.js +155 -5
  93. package/dist/src/utils/catalog-operation-context.js.map +1 -1
  94. package/dist/src/utils/catalog-source-references.js +11 -4
  95. package/dist/src/utils/catalog-source-references.js.map +1 -1
  96. package/dist/src/utils/codex-native-observation.js +8 -12
  97. package/dist/src/utils/codex-native-observation.js.map +1 -1
  98. package/dist/src/utils/codex-skills-root.js +5 -1
  99. package/dist/src/utils/codex-skills-root.js.map +1 -1
  100. package/dist/src/utils/component-resources.js +2 -3
  101. package/dist/src/utils/component-resources.js.map +1 -1
  102. package/dist/src/utils/multi-source-catalog.d.ts +2 -1
  103. package/dist/src/utils/multi-source-catalog.js +2 -1
  104. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  105. package/dist/src/utils/plugin-config-suggestions.js +13 -4
  106. package/dist/src/utils/plugin-config-suggestions.js.map +1 -1
  107. package/dist/src/utils/plugin-config.js +13 -4
  108. package/dist/src/utils/plugin-config.js.map +1 -1
  109. package/dist/src/utils/runtime-skill-closure.d.ts +1 -1
  110. package/dist/src/utils/runtime-skill-closure.js +3 -1
  111. package/dist/src/utils/runtime-skill-closure.js.map +1 -1
  112. package/dist/vitest.config.js +3 -0
  113. package/dist/vitest.config.js.map +1 -1
  114. package/package.json +4 -3
@@ -13,16 +13,16 @@ import { readSafeOperationError } from '../utils/safe-operation-diagnostic.js';
13
13
  import { createCodexNativeObservationSession } from '../utils/codex-native-observation.js';
14
14
  import { bindNativeCliRunnerSignal, getDefaultNativeCliRunner } from '../utils/native-cli.js';
15
15
  import { analyzeCodexSurface } from '../utils/codex-surface-analysis.js';
16
- import { validateCatalogSnapshotComplete } from '../utils/catalog-snapshot.js';
17
- import { CatalogPreparationReadScope } from '../utils/catalog-operation-context.js';
16
+ import { CatalogPreparationReadScope, catalogOperationBinding, catalogOperationBindingsMatch, selectCatalogOperationContext } from '../utils/catalog-operation-context.js';
18
17
  import { readCatalogGenerationState } from '../utils/catalog-generation-state.js';
18
+ import { CatalogGenerationError } from '../utils/catalog-generation-error.js';
19
19
  import { readCatalogSourcesConfigSnapshot } from '../utils/catalog-sources.js';
20
20
  import { parsePluginId } from '../utils/multi-source-catalog.js';
21
21
  import { readDemand, resolveDelivery } from './demand.js';
22
22
  import { hasSharedUserPackage } from '../platforms/layout.js';
23
23
  import { preparePortableRecovery } from '../portable/recovery.js';
24
24
  import { canReuseProviderAcrossScopes, hasInheritableSkills, isInstalledSkillProvider, projectSkillCandidates, readJointDemand, deriveJointDemand, deriveSharedReferenceView, indexJointDependencies } from './joint-demand.js';
25
- import { checkFootprints, prepareScopedRecovery, executeScopedRecovery, executeRecoveryPreApply, refreshRecoveryNativePreviews, describeRecoveryPlan, errorCode } from './coordinator.js';
25
+ import { checkFootprints, prepareScopedRecovery, executeScopedRecovery, executeRecoveryPreApply, refreshRecoveryNativePreviews, describeRecoveryPlan, errorCode, catalogRecheckDiagnostic, blockScopedRecoveryBeforeExecution } from './coordinator.js';
26
26
  import { isTargetObservationReadError, readScopedRecoveryStatus, readRecoveryStatus } from './status.js';
27
27
  import { recoveryRetryDispositions, recoveryStatusContext, retriesFromRequestedRoots } from './receipt.js';
28
28
  import { limitInstallNativeRunner, mapInstallReads } from './install-concurrency.js';
@@ -46,8 +46,8 @@ const observationEvidence = (value) => 'rawDigest' in value ? `${value.state}:${
46
46
  function snapshotEvidence(snapshot) {
47
47
  return JSON.stringify([observationEvidence(snapshot.user.intent),
48
48
  snapshot.project ? observationEvidence(snapshot.project.intent) : null,
49
- observationEvidence(snapshot.user.preferences), snapshot.user.catalogOperationContext?.generationSetDigest,
50
- snapshot.project?.catalogOperationContext?.generationSetDigest]);
49
+ observationEvidence(snapshot.user.preferences), catalogOperationBinding(snapshot.user.catalogOperationContext),
50
+ catalogOperationBinding(snapshot.project?.catalogOperationContext)]);
51
51
  }
52
52
  function asObservation(value) {
53
53
  const rawBytes = Buffer.from(JSON.stringify(value));
@@ -194,10 +194,6 @@ function finalStatusReadFailure(status, receipt) {
194
194
  return undefined;
195
195
  }
196
196
  function blockedBeforeDeployment(plan, blocker = diagnostic('operationReviewStale'), savedState) {
197
- if (!isInstallBatch(plan.command)) {
198
- plan.receipt.blockers.push(blocker);
199
- return mergeReceipts(plan, []);
200
- }
201
197
  const receipt = structuredClone(plan.receipt);
202
198
  receipt.ok = false;
203
199
  receipt.blockers.push(blocker);
@@ -221,18 +217,16 @@ function blockedBeforeDeployment(plan, blocker = diagnostic('operationReviewStal
221
217
  });
222
218
  return receipt;
223
219
  }
224
- async function readJointPreparation(command, options, locked = false, suppliedReads) {
225
- const catalogReadScope = isInstallBatch(command)
226
- ? (locked ? undefined : suppliedReads) ?? new CatalogPreparationReadScope(options) : undefined;
227
- if (locked && catalogReadScope && options.catalogOperationContext) {
220
+ async function readJointPreparation(options, locked = false, suppliedReads) {
221
+ // Reuse evidence for every read-only plan, including reinstall and uninstall.
222
+ // This is independent of whether execution can use the parallel install scheduler.
223
+ const catalogReadScope = (locked ? undefined : suppliedReads) ?? new CatalogPreparationReadScope(options);
224
+ if (locked && options.catalogOperationContext) {
228
225
  // A caller may have reviewed a subset of sources. Rebind just those IDs under
229
226
  // the lock so a changed or removed source makes the existing Review stale.
230
- const reviewed = new Set(options.catalogOperationContext.catalog.sources.map((source) => source.sourceId));
231
- const configSnapshot = await readCatalogSourcesConfigSnapshot(options.env);
232
- const sourceIds = configSnapshot.config.sources.map((source) => source.id).filter((id) => reviewed.has(id));
233
- options = { ...options, catalogOperationContext: await catalogReadScope.resolve({ configSnapshot, sourceIds }) };
227
+ options = { ...options, catalogOperationContext: await catalogReadScope.rebind(options.catalogOperationContext) };
234
228
  }
235
- const manifestReads = isInstallBatch(command) ? new Map() : undefined;
229
+ const manifestReads = new Map();
236
230
  const snapshot = await readJointDemand({ ...options, catalogReadScope, manifestReads });
237
231
  return { options, snapshot, catalogReadScope, manifestReads };
238
232
  }
@@ -241,9 +235,14 @@ export async function prepareJointRecovery(command, selectors, options, runtime,
241
235
  const originalRunner = runtime.nativeCliRunner ?? getDefaultNativeCliRunner();
242
236
  runtime = { ...runtime, invocationCwd: runtime.invocationCwd ?? options.cwd, ...(isInstallBatch(command) ? { nativeCliRunner: limitInstallNativeRunner(originalRunner) } : {}),
243
237
  preparedArtifactRenderResults: runtime.preparedArtifactRenderResults ?? new Map() };
244
- const { snapshot, catalogReadScope, manifestReads } = preparation ?? await readJointPreparation(command, options, false, runtime.catalogReadScope);
238
+ const { snapshot, catalogReadScope, manifestReads } = preparation ?? await readJointPreparation(options, false, runtime.catalogReadScope);
245
239
  const prepare = async (current) => {
246
- const read = (nativeObservationBatch) => prepareJointRecoveryInSession(command, selectors, options, current, snapshot, { catalogReadScope, nativeObservationBatch }, manifestReads);
240
+ const read = (nativeObservationBatch) => {
241
+ if (nativeObservationBatch && command === 'install' && !preparation && !current.awHomeMutationToken) {
242
+ nativeObservationBatch.initialInstallPreview = true;
243
+ }
244
+ return prepareJointRecoveryInSession(command, selectors, options, current, snapshot, { catalogReadScope, nativeObservationBatch }, manifestReads);
245
+ };
247
246
  const plan = isInstallBatch(command)
248
247
  ? await withNativeObservationBatch({ runner: current.nativeCliRunner, signal: options.signal }, read) : await read();
249
248
  plan.joint.originalNativeRunner = originalRunner;
@@ -403,7 +402,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
403
402
  const source = original.catalogOperationContext?.catalog.sources.find((entry) => entry.sourceId === sourceId)?.resolution;
404
403
  if (!source)
405
404
  throw new Error('sourceActiveUnavailable');
406
- await validateCatalogSnapshotComplete(source.rootDir);
405
+ await CatalogPreparationReadScope.validateEntries(catalogReadScope, source);
407
406
  }
408
407
  }
409
408
  catch (error) {
@@ -423,7 +422,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
423
422
  if (!errors.length) {
424
423
  if (original.intent.state === 'valid' && calculateIntentDigest(value) !== original.intent.digest)
425
424
  declaration = { scope, value };
426
- const demand = await readDemand({ ...options, preferences: undefined, scope, intent: asObservation(value) });
425
+ const demand = await readDemand({ ...options, catalogReadScope, manifestReads, preferences: undefined, scope, intent: asObservation(value) });
427
426
  snapshot = { ...snapshot, [scope]: demand };
428
427
  }
429
428
  }
@@ -713,6 +712,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
713
712
  }))
714
713
  nativeObservationBatch.scriptFreePlacement = true;
715
714
  const portableGenerations = new Map();
715
+ const portableRenderResults = new Map();
716
716
  const targetGroups = batch ? [...nativeTargets, ...targets.filter((target) => target === 'generic')].map((target) => [target])
717
717
  : [...(nativeTargets.length ? [nativeTargets] : []), ...targets.filter((target) => target === 'generic').map((target) => [target])];
718
718
  const inheritedScripts = command === 'sync' && !options.existingOnly ? new Set(selected.filter((item) => {
@@ -784,7 +784,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
784
784
  && !placements.some((item) => item.pluginId === provider.pluginId && item.target === provider.target))
785
785
  .map((item) => ({ pluginId: item.pluginId, platform: item.target, scope: 'user' })) : [],
786
786
  }, batch && groupTargets[0] !== 'generic'
787
- ? { ...runtime, batchInstallPlatform: groupTargets[0] } : runtime, { catalogReadScope, portableGenerations, nativeObservationBatch: batch || children.length === 0 ? nativeObservationBatch : undefined });
787
+ ? { ...runtime, batchInstallPlatform: groupTargets[0] } : runtime, { catalogReadScope, portableGenerations, portableRenderResults, nativeObservationBatch: batch || children.length === 0 ? nativeObservationBatch : undefined });
788
788
  // Track contexts as soon as acquired, including a sibling that finishes after cancellation.
789
789
  children.push(child);
790
790
  // Synthetic roots are only an execution projection, never persisted Intent.
@@ -824,7 +824,7 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
824
824
  await mapInstallReads(required.filter((id) => !reviewed.has(id)), async (selector) => {
825
825
  const provider = await preparePortableRecovery({ scope: 'user', context: providerContext, selector, agents: ['generic'],
826
826
  cliVersion: options.cliVersion, catalogOperationContext: snapshot.user.catalogOperationContext,
827
- signal: options.signal }, catalogReadScope, portableGenerations);
827
+ signal: options.signal }, catalogReadScope, portableGenerations, portableRenderResults);
828
828
  delete provider.options.signal;
829
829
  reviewed.set(selector, provider);
830
830
  }, { signal: options.signal });
@@ -964,13 +964,25 @@ async function prepareJointRecoveryInSession(command, selectors, { checkInstallC
964
964
  userProviders: Object.fromEntries((snapshot.preferences?.targets ?? []).map((target) => [target,
965
965
  demand.placements.filter((placement) => placement.scope === 'user' && placement.target === target)
966
966
  .map((placement) => placement.pluginId)])), } : snapshot.user;
967
+ const automatic = automaticRetirements.some((candidate) => candidate.pluginId === item.pluginId
968
+ && candidate.target === item.agent && candidate.scope === item.scope);
969
+ // The scoped child must remain cleanup: its declaration and dependency ordering
970
+ // are owned by the joint remove. Only its exact, current Active native target
971
+ // may use normal removal rather than outputs-only package preservation.
972
+ const activePlugin = original.plugins.find((plugin) => plugin.pluginId === item.pluginId);
973
+ const ordinaryNativeRemoval = command === 'uninstall' && item.agent !== 'generic'
974
+ && hasSharedUserPackage(item.agent) && targets.includes(item.agent) && ownsOutput(item)
975
+ && (explicitlyRemoves(item) || automatic) && !joint.providerRetirements.has(targetKey({ ...item, agent: item.agent }))
976
+ && activePlugin && original.catalogOperationContext
977
+ ? { target: { pluginId: item.pluginId, platform: item.agent, scope: item.scope },
978
+ catalog: selectCatalogOperationContext(original.catalogOperationContext, [activePlugin.sourceId]) }
979
+ : undefined;
967
980
  const cleanup = await prepareScopedRecovery('cleanup', [item.pluginId], { ...options,
968
- sharedReferenceView,
981
+ ordinaryNativeRemoval, sharedReferenceView,
969
982
  scope: item.scope, cwd: snapshot.context.projectRoot ?? options.cwd, targets: [item.agent], all: false,
970
983
  // Ordinary remove's force bypasses dependencies, never ownership checks.
971
- force: false, exactTargets: undefined, demandOverride: cleanupDemand }, runtime);
972
- if (automaticRetirements.some((candidate) => candidate.pluginId === item.pluginId
973
- && candidate.target === item.agent && candidate.scope === item.scope)) {
984
+ force: false, exactTargets: undefined, demandOverride: cleanupDemand }, runtime, { catalogReadScope });
985
+ if (automatic) {
974
986
  for (const target of cleanup.receipt.targetResults) {
975
987
  target.relation = 'dependency';
976
988
  target.requiredBy = previousDemand.placements.find((candidate) => candidate.pluginId === item.pluginId
@@ -1154,7 +1166,17 @@ export async function executeJointRecovery(plan, execution) {
1154
1166
  const acquiredAt = lockWaitStartedAt;
1155
1167
  lockWaitStartedAt = undefined;
1156
1168
  await recordRecoveryPerformanceStage(performanceRuntime, 'recovery.lock.wait', 'success', acquiredAt);
1157
- const preparation = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.demand', () => readJointPreparation(plan.command, { ...joint.originalOptions, signal: performanceRuntime.signal }, true));
1169
+ let preparation;
1170
+ try {
1171
+ preparation = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.demand', () => readJointPreparation({ ...joint.originalOptions, signal: performanceRuntime.signal }, true));
1172
+ }
1173
+ catch (error) {
1174
+ // A control-file failure during rebind is a known pre-write stop, not
1175
+ // an uncertain execution failure. Keep the original reviewed targets.
1176
+ if (!(error instanceof CatalogGenerationError))
1177
+ throw error;
1178
+ return blockedBeforeDeployment(plan, catalogRecheckDiagnostic(error, performanceRuntime.signal));
1179
+ }
1158
1180
  const actual = preparation.snapshot;
1159
1181
  const currentIntent = (plan.options.scope === 'project' ? actual.project : actual.user).intent;
1160
1182
  plan.receipt.intent = intentReceipt(currentIntent);
@@ -1168,7 +1190,7 @@ export async function executeJointRecovery(plan, execution) {
1168
1190
  return plan.receipt;
1169
1191
  // Recheck all backend candidates before any strong-state or output write.
1170
1192
  (execution.runtime?.codexObservationSession ?? plan.runtime.codexObservationSession)?.invalidate();
1171
- const checked = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.recheck', () => prepareJointRecovery(plan.command, joint.selectors, preparation.options, { ...performanceRuntime, awHomeMutationToken: token }, preparation.catalogReadScope ? preparation : undefined));
1193
+ const checked = await measureRecoveryPerformanceStage(performanceRuntime, 'recovery.locked.recheck', () => prepareJointRecovery(plan.command, joint.selectors, preparation.options, { ...performanceRuntime, awHomeMutationToken: token }, preparation));
1172
1194
  const stable = !checked.blockExecution && JSON.stringify(describeRecoveryPlan(plan)) === JSON.stringify(describeRecoveryPlan(checked));
1173
1195
  lockedPlan = checked;
1174
1196
  const parallel = isInstallBatch(plan.command) && !joint.pendingUserSkills.length && !joint.children.some((child) => child.command === 'cleanup');
@@ -1231,323 +1253,383 @@ export async function executeJointRecovery(plan, execution) {
1231
1253
  plan.receipt.blockers.push(...installed.blockers);
1232
1254
  }
1233
1255
  else {
1234
- const packages = runtime.configApplyPackages;
1235
- const dependencyGraph = indexJointDependencies(joint.demand);
1236
- const readCurrentProviders = (plugins, targets) => {
1237
- const { cwd, env, cliVersion } = joint.originalOptions;
1238
- return readRecoveryStatus({ cwd, env, cliVersion, context: joint.snapshot.context.context,
1239
- expectedProjectRoot: joint.snapshot.context.projectRoot, plugins: [...new Set(plugins)], targets: [...new Set(targets)],
1240
- nativeCliRunner: runtime.nativeCliRunner, signal: runtime.signal });
1241
- };
1242
- const portableProgress = { completed: [], failed: [] };
1243
- const failedCleanups = [];
1244
- const executeChild = async (child, pluginIds, agent) => {
1245
- const childRuntime = { ...runtime, batchInstallPlatform: child.runtime.batchInstallPlatform };
1246
- const currentIntent = await observeIntent(child.options);
1247
- if (!joint.originalOptions.existingOnly)
1248
- child.demand.intent = currentIntent;
1249
- const fresh = await measureRecoveryPerformanceStage(runtime, 'recovery.child.plan', () => prepareScopedRecovery(child.command, typeof pluginIds === 'string' ? [pluginIds] : pluginIds, {
1250
- ...child.options, targets: agent !== 'generic' ? child.options.targets : [agent], all: false,
1251
- exactTargets: child.options.exactTargets?.filter((target) => (typeof pluginIds === 'string' ? [pluginIds] : pluginIds).includes(target.pluginId)),
1252
- }, childRuntime));
1253
- fresh.originalIntent = observationEvidence(currentIntent);
1254
- for (const target of fresh.receipt.targetResults) {
1255
- const reviewed = child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent);
1256
- if (reviewed?.relation === 'dependency') {
1257
- target.relation = 'dependency';
1258
- target.requiredBy = [...reviewed.requiredBy];
1259
- }
1260
- // Native/provider observations are refreshed after preceding nodes.
1261
- // Keep only joint constraints and an already failed script gate.
1262
- target.blockers.push(...(reviewed?.blockers ?? []).filter((error) => reviewed?.execution === 'failed'
1263
- || ['configApplyRequiresExistingOutput', 'crossScopeSkillCollision', 'targetPlacementConflict',
1264
- 'preApplyAuthorizationRequired', 'nativeToolAuthorizationRequired', 'providerSwitchPreApplyFailed', 'providerSwitchVerificationFailed', 'dependencyStillRequired'].includes(error.code)));
1265
- if (reviewed?.execution === 'failed') {
1266
- target.execution = 'failed';
1267
- if (reviewed.backend)
1268
- target.backend = reviewed.backend;
1269
- }
1270
- if (child.command !== 'cleanup' && failedCleanups.some((failed) => failed.agent === target.agent && (failed.pluginId === target.pluginId || joint.demand.roots.some((root) => root.pluginId === target.pluginId && root.target === target.agent && root.dependencies.includes(failed.pluginId))))) {
1271
- target.blockers.push(diagnostic('providerSwitchCleanupFailed'));
1256
+ try {
1257
+ const packages = runtime.configApplyPackages;
1258
+ const dependencyGraph = indexJointDependencies(joint.demand);
1259
+ const readCurrentProviders = (plugins, targets) => {
1260
+ const { cwd, env, cliVersion } = joint.originalOptions;
1261
+ return readRecoveryStatus({ cwd, env, cliVersion, context: joint.snapshot.context.context,
1262
+ expectedProjectRoot: joint.snapshot.context.projectRoot, plugins: [...new Set(plugins)], targets: [...new Set(targets)],
1263
+ nativeCliRunner: runtime.nativeCliRunner, signal: runtime.signal,
1264
+ catalogReadScope: new CatalogPreparationReadScope({ env, signal: runtime.signal }) });
1265
+ };
1266
+ const portableProgress = { completed: [], failed: [] };
1267
+ const failedCleanups = [];
1268
+ const executeChild = async (child, pluginIds, agent) => {
1269
+ runtime.signal?.throwIfAborted();
1270
+ const childRuntime = { ...runtime, batchInstallPlatform: child.runtime.batchInstallPlatform };
1271
+ const currentIntent = await observeIntent(child.options);
1272
+ if (!joint.originalOptions.existingOnly)
1273
+ child.demand.intent = currentIntent;
1274
+ const catalogReadScope = new CatalogPreparationReadScope({ env: child.context.env, signal: runtime.signal });
1275
+ const reviewedCatalog = child.demand.catalogOperationContext;
1276
+ let currentCatalog = reviewedCatalog;
1277
+ if (child.command !== 'cleanup' && reviewedCatalog) {
1278
+ const selected = (pluginId) => typeof pluginIds === 'string' ? pluginId === pluginIds : pluginIds.includes(pluginId);
1279
+ const stopChild = (blocker) => {
1280
+ const result = blockScopedRecoveryBeforeExecution(structuredClone({ ...child.receipt,
1281
+ requestedRoots: child.receipt.requestedRoots.filter(selected),
1282
+ targetResults: child.receipt.targetResults.filter((target) => selected(target.pluginId)
1283
+ && (agent !== 'generic' || target.agent === agent)),
1284
+ }), blocker);
1285
+ results.push(result);
1286
+ return result;
1287
+ };
1288
+ // A logical generation digest does not bind requestedRef or resolvedCommit.
1289
+ // Never replace the Review with fresh objects unless the full binding matches.
1290
+ try {
1291
+ const rebound = await catalogReadScope.rebind(reviewedCatalog);
1292
+ if (!catalogOperationBindingsMatch(reviewedCatalog, rebound)) {
1293
+ const unavailable = rebound.catalog.sources.find((source) => source.error
1294
+ && reviewedCatalog.catalog.sources.some((reviewed) => reviewed.sourceId === source.sourceId && reviewed.resolution));
1295
+ return stopChild(unavailable
1296
+ ? catalogRecheckDiagnostic(unavailable.error, runtime.signal, unavailable.sourceId)
1297
+ : diagnostic('operationReviewStale'));
1298
+ }
1299
+ currentCatalog = rebound;
1300
+ }
1301
+ catch (error) {
1302
+ return stopChild(catalogRecheckDiagnostic(error, runtime.signal));
1303
+ }
1272
1304
  }
1273
- const dependencies = [...dependencyGraph.providers({ pluginId: target.pluginId, target: target.agent, scope: target.scope })];
1274
- if (failedPackages.has(`${target.pluginId}\0${target.scope}`) || failedPackages.has(`${target.pluginId}\0user`)
1275
- || dependencies.some((item) => failedPackages.has(`${item.pluginId}\0${item.scope}`))) {
1276
- target.blockers.push(diagnostic('commandPackageProviderNotSatisfied'));
1305
+ const fresh = await measureRecoveryPerformanceStage(runtime, 'recovery.child.plan', () => prepareScopedRecovery(child.command, typeof pluginIds === 'string' ? [pluginIds] : pluginIds, {
1306
+ ...child.options, signal: runtime.signal,
1307
+ ...(child.command !== 'cleanup' ? {
1308
+ catalogOperationContext: currentCatalog,
1309
+ ...(child.options.demandOverride ? { demandOverride: { ...child.options.demandOverride, catalogOperationContext: currentCatalog } } : {}),
1310
+ } : {}), targets: agent !== 'generic' ? child.options.targets : [agent], all: false,
1311
+ exactTargets: child.options.exactTargets?.filter((target) => (typeof pluginIds === 'string' ? [pluginIds] : pluginIds).includes(target.pluginId)),
1312
+ }, childRuntime, { catalogReadScope }));
1313
+ fresh.originalIntent = observationEvidence(currentIntent);
1314
+ for (const target of fresh.receipt.targetResults) {
1315
+ const reviewed = child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent);
1316
+ if (reviewed?.relation === 'dependency') {
1317
+ target.relation = 'dependency';
1318
+ target.requiredBy = [...reviewed.requiredBy];
1319
+ }
1320
+ // Native/provider observations are refreshed after preceding nodes.
1321
+ // Keep only joint constraints and an already failed script gate.
1322
+ target.blockers.push(...(reviewed?.blockers ?? []).filter((error) => reviewed?.execution === 'failed'
1323
+ || ['configApplyRequiresExistingOutput', 'crossScopeSkillCollision', 'targetPlacementConflict',
1324
+ 'preApplyAuthorizationRequired', 'nativeToolAuthorizationRequired', 'providerSwitchPreApplyFailed', 'providerSwitchVerificationFailed', 'dependencyStillRequired'].includes(error.code)));
1325
+ if (reviewed?.execution === 'failed') {
1326
+ target.execution = 'failed';
1327
+ if (reviewed.backend)
1328
+ target.backend = reviewed.backend;
1329
+ }
1330
+ if (child.command !== 'cleanup' && failedCleanups.some((failed) => failed.agent === target.agent && (failed.pluginId === target.pluginId || joint.demand.roots.some((root) => root.pluginId === target.pluginId && root.target === target.agent && root.dependencies.includes(failed.pluginId))))) {
1331
+ target.blockers.push(diagnostic('providerSwitchCleanupFailed'));
1332
+ }
1333
+ const dependencies = [...dependencyGraph.providers({ pluginId: target.pluginId, target: target.agent, scope: target.scope })];
1334
+ if (failedPackages.has(`${target.pluginId}\0${target.scope}`) || failedPackages.has(`${target.pluginId}\0user`)
1335
+ || dependencies.some((item) => failedPackages.has(`${item.pluginId}\0${item.scope}`))) {
1336
+ target.blockers.push(diagnostic('commandPackageProviderNotSatisfied'));
1337
+ }
1338
+ const failedDependency = dependencies.find((placement) => failedProviders.has(`${placement.pluginId}\0${placement.target}\0${placement.scope}`));
1339
+ if (failedDependency) {
1340
+ target.blockers.push({ code: target.scope === 'project' && failedDependency.scope === 'user'
1341
+ ? 'userProviderNotSatisfied' : 'dependencyApplyFailed',
1342
+ pluginId: failedDependency.pluginId,
1343
+ message: `依赖提供者 ${failedDependency.pluginId}(${failedDependency.target}/${failedDependency.scope})未完成。` });
1344
+ }
1277
1345
  }
1278
- const failedDependency = dependencies.find((placement) => failedProviders.has(`${placement.pluginId}\0${placement.target}\0${placement.scope}`));
1279
- if (failedDependency) {
1280
- target.blockers.push({ code: target.scope === 'project' && failedDependency.scope === 'user'
1281
- ? 'userProviderNotSatisfied' : 'dependencyApplyFailed',
1282
- pluginId: failedDependency.pluginId,
1283
- message: `依赖提供者 ${failedDependency.pluginId}(${failedDependency.target}/${failedDependency.scope})未完成。` });
1346
+ if (child.command !== 'cleanup' && child.options.scope === 'project') {
1347
+ const required = joint.pendingUserSkills.filter((item) => fresh.receipt.targetResults.some((target) => target.agent === item.target && dependencyGraph.reaches(target.pluginId, item.pluginId)));
1348
+ if (required.length) {
1349
+ const verified = await readCurrentProviders(required.map((item) => item.pluginId), required.map((item) => item.target));
1350
+ for (const provider of required) {
1351
+ if (verified.projectSkillProviders?.some((item) => item.pluginId === provider.pluginId && item.target === provider.target
1352
+ && item.sourceIdentity === provider.sourceIdentity && !item.userAbsent && !item.userNeedsRepair && item.projectCopy !== 'blocked'))
1353
+ continue;
1354
+ for (const target of fresh.receipt.targetResults.filter((item) => item.agent === provider.target
1355
+ && dependencyGraph.reaches(item.pluginId, provider.pluginId)))
1356
+ target.blockers.push(diagnostic('userProviderNotSatisfied'));
1357
+ }
1358
+ }
1284
1359
  }
1285
- }
1286
- if (child.command !== 'cleanup' && child.options.scope === 'project') {
1287
- const required = joint.pendingUserSkills.filter((item) => fresh.receipt.targetResults.some((target) => target.agent === item.target && dependencyGraph.reaches(target.pluginId, item.pluginId)));
1288
- if (required.length) {
1289
- const verified = await readCurrentProviders(required.map((item) => item.pluginId), required.map((item) => item.target));
1290
- for (const provider of required) {
1291
- if (verified.projectSkillProviders?.some((item) => item.pluginId === provider.pluginId && item.target === provider.target
1292
- && item.sourceIdentity === provider.sourceIdentity && !item.userAbsent && !item.userNeedsRepair && item.projectCopy !== 'blocked'))
1360
+ const result = await measureRecoveryPerformanceStage(runtime, 'recovery.child.execute', () => executeScopedRecovery(fresh, { ...execution, runtime: childRuntime,
1361
+ ...(plan.command !== 'uninstall' && child.command !== 'cleanup' ? { portableProgress } : {}) }));
1362
+ if (joint.originalOptions.existingOnly)
1363
+ for (const target of result.targetResults) {
1364
+ if (!target.blockers.some((error) => error.code === 'dependencyInstallFailed'))
1293
1365
  continue;
1294
- for (const target of fresh.receipt.targetResults.filter((item) => item.agent === provider.target
1295
- && dependencyGraph.reaches(item.pluginId, provider.pluginId)))
1296
- target.blockers.push(diagnostic('userProviderNotSatisfied'));
1366
+ target.blockers = target.blockers.map((error) => error.code === 'dependencyInstallFailed'
1367
+ ? { ...error, code: 'dependencyApplyFailed', message: '依赖提供者未完成。请检查其执行结果。' }
1368
+ : error);
1369
+ if (target.execution === 'failed')
1370
+ target.execution = 'not-run';
1297
1371
  }
1298
- }
1299
- }
1300
- const result = await measureRecoveryPerformanceStage(runtime, 'recovery.child.execute', () => executeScopedRecovery(fresh, { ...execution, runtime: childRuntime,
1301
- ...(plan.command !== 'uninstall' && child.command !== 'cleanup' ? { portableProgress } : {}) }));
1302
- if (joint.originalOptions.existingOnly)
1303
- for (const target of result.targetResults) {
1304
- if (!target.blockers.some((error) => error.code === 'dependencyInstallFailed'))
1372
+ results.push(result);
1373
+ return result;
1374
+ };
1375
+ // Provider changes can remove a working output. Complete the replacement's
1376
+ // authorization and scripts first, sharing the normal execution cache.
1377
+ const cleanups = joint.children.filter((child) => child.command === 'cleanup');
1378
+ const deferred = cleanups.filter((child) => child.receipt.requestedTargets.some((target) => joint.providerRetirements.has(targetKey(target))));
1379
+ const cleanupChildren = cleanups.filter((child) => !deferred.includes(child));
1380
+ const replacementFailures = new Set();
1381
+ for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
1382
+ for (const target of child.receipt.targetResults) {
1383
+ if (replacementFailures.has(`${target.pluginId}\0${target.agent}`)) {
1384
+ target.blockers.push(diagnostic('dependencyApplyFailed'));
1305
1385
  continue;
1306
- target.blockers = target.blockers.map((error) => error.code === 'dependencyInstallFailed'
1307
- ? { ...error, code: 'dependencyApplyFailed', message: '依赖提供者未完成。请检查其执行结果。' }
1308
- : error);
1309
- if (target.execution === 'failed')
1310
- target.execution = 'not-run';
1311
- }
1312
- results.push(result);
1313
- return result;
1314
- };
1315
- // Provider changes can remove a working output. Complete the replacement's
1316
- // authorization and scripts first, sharing the normal execution cache.
1317
- const cleanups = joint.children.filter((child) => child.command === 'cleanup');
1318
- const deferred = cleanups.filter((child) => child.receipt.requestedTargets.some((target) => joint.providerRetirements.has(targetKey(target))));
1319
- const cleanupChildren = cleanups.filter((child) => !deferred.includes(child));
1320
- const replacementFailures = new Set();
1321
- for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
1322
- for (const target of child.receipt.targetResults) {
1323
- if (replacementFailures.has(`${target.pluginId}\0${target.agent}`)) {
1324
- target.blockers.push(diagnostic('dependencyApplyFailed'));
1325
- continue;
1386
+ }
1387
+ if (child.options.nativeActivationOnlyTargets?.some((item) => item.pluginId === target.pluginId
1388
+ && item.platform === target.agent && item.scope === target.scope))
1389
+ continue;
1390
+ if (!cleanupChildren.some((cleanup) => cleanup.receipt.requestedTargets.some((old) => old.pluginId === target.pluginId)))
1391
+ continue;
1392
+ const failure = target.blockers[0]?.code ?? await executeRecoveryPreApply({ ...child,
1393
+ options: { ...child.options, yes: execution.yes ?? plan.options.yes },
1394
+ }, target.pluginId, target.agent, runtime);
1395
+ if (!failure)
1396
+ continue;
1397
+ target.blockers.push(diagnostic(failure));
1398
+ if (failure !== 'preApplyAuthorizationRequired' && failure !== 'nativeToolAuthorizationRequired')
1399
+ target.execution = 'failed';
1400
+ replacementFailures.add(`${target.pluginId}\0${target.agent}`);
1401
+ failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
1402
+ failedNodes.add(`${target.pluginId}\0${target.scope}`);
1326
1403
  }
1327
- if (child.options.nativeActivationOnlyTargets?.some((item) => item.pluginId === target.pluginId
1328
- && item.platform === target.agent && item.scope === target.scope))
1329
- continue;
1330
- if (!cleanupChildren.some((cleanup) => cleanup.receipt.requestedTargets.some((old) => old.pluginId === target.pluginId)))
1331
- continue;
1332
- const failure = target.blockers[0]?.code ?? await executeRecoveryPreApply({ ...child,
1333
- options: { ...child.options, yes: execution.yes ?? plan.options.yes },
1334
- }, target.pluginId, target.agent, runtime);
1335
- if (!failure)
1336
- continue;
1337
- target.blockers.push(diagnostic(failure));
1338
- if (failure !== 'preApplyAuthorizationRequired' && failure !== 'nativeToolAuthorizationRequired')
1339
- target.execution = 'failed';
1340
- replacementFailures.add(`${target.pluginId}\0${target.agent}`);
1341
- failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
1342
- failedNodes.add(`${target.pluginId}\0${target.scope}`);
1343
1404
  }
1344
- }
1345
- // Target exits can replace one Agent with another. Preserve the reviewed
1346
- // old output when its corresponding replacement cannot run.
1347
- const clean = async (child, verified = true, onSuccess) => {
1348
- for (const target of child.receipt.requestedTargets) {
1349
- if (!verified)
1350
- child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
1351
- .blockers.push(diagnostic('providerSwitchVerificationFailed', '替代位置尚未确认就绪,保留原输出。'));
1352
- if ((plan.command === 'uninstall' || deferred.includes(child)) && failedCleanups.some((failed) => {
1353
- if (failed.agent !== target.agent)
1354
- return false;
1355
- const required = joint.removalDependencies.get(failed.pluginId);
1356
- return required?.includes(target.pluginId) || required === null
1357
- && parsePluginId(failed.pluginId).sourceId === parsePluginId(target.pluginId).sourceId;
1358
- })) {
1359
- child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
1360
- .blockers.push(diagnostic('dependencyStillRequired', '依赖者未完成删除,保留其依赖输出。'));
1405
+ // Target exits can replace one Agent with another. Preserve the reviewed
1406
+ // old output when its corresponding replacement cannot run.
1407
+ const clean = async (child, verified = true, onSuccess) => {
1408
+ for (const target of child.receipt.requestedTargets) {
1409
+ if (!verified)
1410
+ child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
1411
+ .blockers.push(diagnostic('providerSwitchVerificationFailed', '替代位置尚未确认就绪,保留原输出。'));
1412
+ if ((plan.command === 'uninstall' || deferred.includes(child)) && failedCleanups.some((failed) => {
1413
+ if (failed.agent !== target.agent)
1414
+ return false;
1415
+ const required = joint.removalDependencies.get(failed.pluginId);
1416
+ return required?.includes(target.pluginId) || required === null
1417
+ && parsePluginId(failed.pluginId).sourceId === parsePluginId(target.pluginId).sourceId;
1418
+ })) {
1419
+ child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
1420
+ .blockers.push(diagnostic('dependencyStillRequired', '依赖者未完成删除,保留其依赖输出。'));
1421
+ }
1422
+ if ([...replacementFailures].some((failed) => failed.startsWith(`${target.pluginId}\0`)
1423
+ && (failed === `${target.pluginId}\0${target.agent}`
1424
+ || !joint.children.some((replacement) => replacement.command !== 'cleanup'
1425
+ && replacement.receipt.requestedTargets.some((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent))))) {
1426
+ child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
1427
+ .blockers.push(diagnostic('providerSwitchPreApplyFailed'));
1428
+ }
1429
+ const result = await executeChild(child, target.pluginId, target.agent);
1430
+ if (!result.ok)
1431
+ failedCleanups.push(...result.requestedTargets);
1432
+ else
1433
+ onSuccess?.(result);
1361
1434
  }
1362
- if ([...replacementFailures].some((failed) => failed.startsWith(`${target.pluginId}\0`)
1363
- && (failed === `${target.pluginId}\0${target.agent}`
1364
- || !joint.children.some((replacement) => replacement.command !== 'cleanup'
1365
- && replacement.receipt.requestedTargets.some((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent))))) {
1366
- child.receipt.targetResults.find((entry) => entry.pluginId === target.pluginId && entry.agent === target.agent)
1367
- .blockers.push(diagnostic('providerSwitchPreApplyFailed'));
1435
+ };
1436
+ for (const child of cleanupChildren)
1437
+ await clean(child);
1438
+ const retireVerified = async (oldScope) => {
1439
+ const retiring = deferred.filter((child) => child.options.scope === oldScope);
1440
+ if (!retiring.length)
1441
+ return;
1442
+ const old = retiring.flatMap((child) => child.receipt.requestedTargets);
1443
+ const verified = await readCurrentProviders(old.map((item) => item.pluginId), old.map((item) => item.agent));
1444
+ for (const child of retiring) {
1445
+ const target = child.receipt.requestedTargets[0];
1446
+ const replacement = { ...target, scope: oldScope === 'user' ? 'project' : 'user' };
1447
+ const reviewedSource = joint.demand.placements.find((item) => item.pluginId === replacement.pluginId
1448
+ && item.scope === replacement.scope && item.target === replacement.agent)?.plugin.sourceIdentity;
1449
+ const confirmed = reviewedSource && !failedProviders.has(targetKey(replacement)) && (oldScope === 'project'
1450
+ ? verified.projectSkillProviders?.some((item) => item.pluginId === target.pluginId && item.target === target.agent
1451
+ && item.sourceIdentity === reviewedSource && !item.userAbsent && !item.userNeedsRepair && item.projectCopy === 'owned')
1452
+ : verified.observedTargets?.some((item) => targetKey(item) === targetKey(replacement)
1453
+ && item.observation === 'verified' && item.content === 'satisfied' && !item.blockers.length)
1454
+ && verified.existingTargets?.some((item) => targetKey(item) === targetKey(replacement)
1455
+ && item.nativePackage?.sourceIdentity === reviewedSource && item.nativePackage.skillsReady));
1456
+ await clean(child, Boolean(confirmed), (receipt) => {
1457
+ const projectRoot = joint.snapshot.context.projectRoot;
1458
+ if (!confirmed || !projectRoot || oldScope !== 'project' || target.agent !== 'grok' || !runtime.preparedArtifactRenderResults)
1459
+ return;
1460
+ const project = verified.extraObserved.find((item) => item.pluginId === target.pluginId && item.agent === 'grok' && item.scope === 'project')
1461
+ ?.deploymentObservations?.find(({ after }) => after.nativeIdentity?.route === 'grok-directory')?.after;
1462
+ const user = verified.observedTargets?.find((item) => targetKey(item) === targetKey(replacement))
1463
+ ?.deploymentObservations?.find(({ after }) => after.nativeIdentity?.route === 'grok-cli')?.after;
1464
+ const backend = receipt.targetResults.find((item) => targetKey(item) === targetKey(target))?.backend;
1465
+ const removed = backend?.command === 'cleanup' && backend.ok ? backend.targetResults.find(({ target: item }) => item.pluginId === target.pluginId && item.platform === 'grok' && item.scope === 'project')?.removed : undefined;
1466
+ const reviewedRemoval = child.nativeGroups.some(({ preview }) => preview.operationPlan?.actions.some((action) => action.kind === 'removeOwnedArtifact' && action.pluginId === target.pluginId && action.platform === 'grok'
1467
+ && action.scope === 'project' && action.path === project?.nativeIdentity?.sourceLocation));
1468
+ if (project && user && reviewedRemoval && removed?.length) {
1469
+ recordPreparedGrokProjectRetirement(runtime.preparedArtifactRenderResults, projectRoot, project, user, removed);
1470
+ }
1471
+ });
1368
1472
  }
1369
- const result = await executeChild(child, target.pluginId, target.agent);
1370
- if (!result.ok)
1371
- failedCleanups.push(...result.requestedTargets);
1372
- else
1373
- onSuccess?.(result);
1374
- }
1375
- };
1376
- for (const child of cleanupChildren)
1377
- await clean(child);
1378
- const retireVerified = async (oldScope) => {
1379
- const retiring = deferred.filter((child) => child.options.scope === oldScope);
1380
- if (!retiring.length)
1381
- return;
1382
- const old = retiring.flatMap((child) => child.receipt.requestedTargets);
1383
- const verified = await readCurrentProviders(old.map((item) => item.pluginId), old.map((item) => item.agent));
1384
- for (const child of retiring) {
1385
- const target = child.receipt.requestedTargets[0];
1386
- const replacement = { ...target, scope: oldScope === 'user' ? 'project' : 'user' };
1387
- const reviewedSource = joint.demand.placements.find((item) => item.pluginId === replacement.pluginId
1388
- && item.scope === replacement.scope && item.target === replacement.agent)?.plugin.sourceIdentity;
1389
- const confirmed = reviewedSource && !failedProviders.has(targetKey(replacement)) && (oldScope === 'project'
1390
- ? verified.projectSkillProviders?.some((item) => item.pluginId === target.pluginId && item.target === target.agent
1391
- && item.sourceIdentity === reviewedSource && !item.userAbsent && !item.userNeedsRepair && item.projectCopy === 'owned')
1392
- : verified.observedTargets?.some((item) => targetKey(item) === targetKey(replacement)
1393
- && item.observation === 'verified' && item.content === 'satisfied' && !item.blockers.length)
1394
- && verified.existingTargets?.some((item) => targetKey(item) === targetKey(replacement)
1395
- && item.nativePackage?.sourceIdentity === reviewedSource && item.nativePackage.skillsReady));
1396
- await clean(child, Boolean(confirmed), (receipt) => {
1397
- const projectRoot = joint.snapshot.context.projectRoot;
1398
- if (!confirmed || !projectRoot || oldScope !== 'project' || target.agent !== 'grok' || !runtime.preparedArtifactRenderResults)
1399
- return;
1400
- const project = verified.extraObserved.find((item) => item.pluginId === target.pluginId && item.agent === 'grok' && item.scope === 'project')
1401
- ?.deploymentObservations?.find(({ after }) => after.nativeIdentity?.route === 'grok-directory')?.after;
1402
- const user = verified.observedTargets?.find((item) => targetKey(item) === targetKey(replacement))
1403
- ?.deploymentObservations?.find(({ after }) => after.nativeIdentity?.route === 'grok-cli')?.after;
1404
- const backend = receipt.targetResults.find((item) => targetKey(item) === targetKey(target))?.backend;
1405
- const removed = backend?.command === 'cleanup' && backend.ok ? backend.targetResults.find(({ target: item }) => item.pluginId === target.pluginId && item.platform === 'grok' && item.scope === 'project')?.removed : undefined;
1406
- const reviewedRemoval = child.nativeGroups.some(({ preview }) => preview.operationPlan?.actions.some((action) => action.kind === 'removeOwnedArtifact' && action.pluginId === target.pluginId && action.platform === 'grok'
1407
- && action.scope === 'project' && action.path === project?.nativeIdentity?.sourceLocation));
1408
- if (project && user && reviewedRemoval && removed?.length) {
1409
- recordPreparedGrokProjectRetirement(runtime.preparedArtifactRenderResults, projectRoot, project, user, removed);
1410
- }
1411
- });
1412
- }
1413
- };
1414
- let retiredProjectCopies = false;
1415
- const nodes = new Map();
1416
- const nodeFor = (pluginId, scope) => {
1417
- const key = `${pluginId}\0${scope}`;
1418
- let node = nodes.get(key);
1419
- if (!node) {
1420
- node = { pluginId, scope, targets: [], dependencies: new Set() };
1421
- nodes.set(key, node);
1422
- }
1423
- return node;
1424
- };
1425
- for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
1426
- for (const target of child.receipt.requestedTargets)
1427
- nodeFor(target.pluginId, target.scope).targets.push({ child, agent: target.agent });
1428
- }
1429
- const consumesPackage = (node, target) => !target.blocker && node.targets.some(({ agent }) => agent !== 'generic' && target.platforms.includes(agent));
1430
- for (const target of packages?.targets ?? []) {
1431
- const sameScope = nodes.get(`${target.pluginId}\0${target.scope}`);
1432
- const native = sameScope && consumesPackage(sameScope, target) ? sameScope
1433
- : [...nodes.values()].find((node) => node.pluginId === target.pluginId && consumesPackage(node, target));
1434
- const node = native ?? nodeFor(target.pluginId, target.scope);
1435
- (node.packages ??= []).push(target);
1436
- }
1437
- for (const node of nodes.values()) {
1438
- for (const { agent } of node.targets) {
1439
- for (const provider of dependencyGraph.directProviders({ pluginId: node.pluginId, target: agent, scope: node.scope })) {
1440
- node.dependencies.add(`${provider.pluginId}\0${provider.scope}`);
1473
+ };
1474
+ let retiredProjectCopies = false;
1475
+ const nodes = new Map();
1476
+ const nodeFor = (pluginId, scope) => {
1477
+ const key = `${pluginId}\0${scope}`;
1478
+ let node = nodes.get(key);
1479
+ if (!node) {
1480
+ node = { pluginId, scope, targets: [], dependencies: new Set() };
1481
+ nodes.set(key, node);
1441
1482
  }
1442
- }
1443
- if (node.scope === 'project' && node.targets.some(({ agent }) => ['codex', 'claude', 'copilot'].includes(agent))
1444
- && nodes.has(`${node.pluginId}\0user`))
1445
- node.dependencies.add(`${node.pluginId}\0user`);
1446
- for (const dependency of node.packages?.flatMap((item) => item.dependencies) ?? []) {
1447
- for (const provider of nodes.values())
1448
- if (provider.pluginId === dependency)
1449
- node.dependencies.add(`${dependency}\0${provider.scope}`);
1450
- }
1451
- }
1452
- const pending = [...nodes.values()].sort((left, right) => left.scope === right.scope
1453
- ? left.pluginId.localeCompare(right.pluginId) : left.scope === 'user' ? -1 : 1);
1454
- const executedNativeChildren = new Set();
1455
- const completedPackages = new Map();
1456
- const recordPackages = (pluginId, scope, produced) => {
1457
- const key = `${pluginId}\0${scope}`;
1458
- completedPackages.set(key, produced);
1459
- packageResults.push(...produced);
1460
- if (!produced.every(commandPackageProviderSatisfied)) {
1461
- failedPackages.add(key);
1462
- failedNodes.add(key);
1463
- }
1464
- return produced;
1465
- };
1466
- const applyPackages = async (pluginId, scope) => {
1467
- const key = `${pluginId}\0${scope}`;
1468
- const previous = completedPackages.get(key);
1469
- if (previous)
1470
- return previous;
1471
- return recordPackages(pluginId, scope, await packages.execute(pluginId, scope, token));
1472
- };
1473
- const blockPackages = (pluginId, scope, code) => completedPackages.get(`${pluginId}\0${scope}`)
1474
- ?? recordPackages(pluginId, scope, packages?.blocked?.(pluginId, scope, code) ?? []);
1475
- const nativePackages = (identity) => packages?.targets.filter((target) => target.pluginId === identity.pluginId
1476
- && target.platforms.includes(identity.platform)
1477
- && (target.scope === 'user' || target.scope === identity.scope)) ?? [];
1478
- if (packages)
1479
- runtime.nativeTargetExecution = {
1480
- produces: (identity) => nativePackages(identity).length > 0,
1481
- beforeApply: async (identity) => {
1482
- const results = [];
1483
- for (const target of nativePackages(identity))
1484
- results.push(...await applyPackages(target.pluginId, target.scope));
1485
- return results;
1486
- },
1487
- blocked: (identity, code) => nativePackages(identity).flatMap((target) => blockPackages(target.pluginId, target.scope, code === 'dependencyInstallFailed' ? 'dependencyApplyFailed' : code)),
1483
+ return node;
1488
1484
  };
1489
- while (pending.length) {
1490
- const index = pending.findIndex((node) => {
1491
- const groups = node.targets.filter(({ child, agent }) => agent !== 'generic' && !executedNativeChildren.has(child));
1492
- const members = new Set([node, ...groups.flatMap(({ child }) => pending.filter((candidate) => candidate.targets.some((target) => target.child === child)))]);
1493
- return [...members].every((member) => [...member.dependencies].every((key) => !pending.some((candidate) => !members.has(candidate) && `${candidate.pluginId}\0${candidate.scope}` === key)));
1494
- });
1495
- if (index < 0) {
1496
- plan.receipt.blockers.push(diagnostic('dependencyContractInvalid'));
1497
- break;
1485
+ for (const child of joint.children.filter((child) => child.command !== 'cleanup')) {
1486
+ for (const target of child.receipt.requestedTargets)
1487
+ nodeFor(target.pluginId, target.scope).targets.push({ child, agent: target.agent });
1498
1488
  }
1499
- const node = pending.splice(index, 1)[0];
1500
- if (node.scope === 'project' && !retiredProjectCopies) {
1501
- await retireVerified('project');
1502
- retiredProjectCopies = true;
1489
+ const consumesPackage = (node, target) => !target.blocker && node.targets.some(({ agent }) => agent !== 'generic' && target.platforms.includes(agent));
1490
+ for (const target of packages?.targets ?? []) {
1491
+ const sameScope = nodes.get(`${target.pluginId}\0${target.scope}`);
1492
+ const native = sameScope && consumesPackage(sameScope, target) ? sameScope
1493
+ : [...nodes.values()].find((node) => node.pluginId === target.pluginId && consumesPackage(node, target));
1494
+ const node = native ?? nodeFor(target.pluginId, target.scope);
1495
+ (node.packages ??= []).push(target);
1496
+ }
1497
+ for (const node of nodes.values()) {
1498
+ for (const { agent } of node.targets) {
1499
+ for (const provider of dependencyGraph.directProviders({ pluginId: node.pluginId, target: agent, scope: node.scope })) {
1500
+ node.dependencies.add(`${provider.pluginId}\0${provider.scope}`);
1501
+ }
1502
+ }
1503
+ if (node.scope === 'project' && node.targets.some(({ agent }) => ['codex', 'claude', 'copilot'].includes(agent))
1504
+ && nodes.has(`${node.pluginId}\0user`))
1505
+ node.dependencies.add(`${node.pluginId}\0user`);
1506
+ for (const dependency of node.packages?.flatMap((item) => item.dependencies) ?? []) {
1507
+ for (const provider of nodes.values())
1508
+ if (provider.pluginId === dependency)
1509
+ node.dependencies.add(`${dependency}\0${provider.scope}`);
1510
+ }
1503
1511
  }
1504
- const key = `${node.pluginId}\0${node.scope}`;
1505
- const standalonePackages = node.packages?.filter((target) => !consumesPackage(node, target)) ?? [];
1506
- if (standalonePackages.length && packages) {
1507
- if (failedNodes.has(key) || [...node.dependencies].some((dependency) => failedNodes.has(dependency))) {
1512
+ const pending = [...nodes.values()].sort((left, right) => left.scope === right.scope
1513
+ ? left.pluginId.localeCompare(right.pluginId) : left.scope === 'user' ? -1 : 1);
1514
+ const executedNativeChildren = new Set();
1515
+ const completedPackages = new Map();
1516
+ const recordPackages = (pluginId, scope, produced) => {
1517
+ const key = `${pluginId}\0${scope}`;
1518
+ completedPackages.set(key, produced);
1519
+ packageResults.push(...produced);
1520
+ if (!produced.every(commandPackageProviderSatisfied)) {
1508
1521
  failedPackages.add(key);
1509
1522
  failedNodes.add(key);
1510
- for (const target of standalonePackages)
1511
- blockPackages(target.pluginId, target.scope, 'dependencyApplyFailed');
1512
- plan.receipt.blockers.push(diagnostic('commandPackageProviderNotSatisfied', node.pluginId));
1513
1523
  }
1514
- else {
1515
- try {
1516
- const produced = [];
1524
+ return produced;
1525
+ };
1526
+ const applyPackages = async (pluginId, scope) => {
1527
+ const key = `${pluginId}\0${scope}`;
1528
+ const previous = completedPackages.get(key);
1529
+ if (previous)
1530
+ return previous;
1531
+ return recordPackages(pluginId, scope, await packages.execute(pluginId, scope, token));
1532
+ };
1533
+ const blockPackages = (pluginId, scope, code) => completedPackages.get(`${pluginId}\0${scope}`)
1534
+ ?? recordPackages(pluginId, scope, packages?.blocked?.(pluginId, scope, code) ?? []);
1535
+ const nativePackages = (identity) => packages?.targets.filter((target) => target.pluginId === identity.pluginId
1536
+ && target.platforms.includes(identity.platform)
1537
+ && (target.scope === 'user' || target.scope === identity.scope)) ?? [];
1538
+ if (packages)
1539
+ runtime.nativeTargetExecution = {
1540
+ produces: (identity) => nativePackages(identity).length > 0,
1541
+ beforeApply: async (identity) => {
1542
+ const results = [];
1543
+ for (const target of nativePackages(identity))
1544
+ results.push(...await applyPackages(target.pluginId, target.scope));
1545
+ return results;
1546
+ },
1547
+ blocked: (identity, code) => nativePackages(identity).flatMap((target) => blockPackages(target.pluginId, target.scope, code === 'dependencyInstallFailed' ? 'dependencyApplyFailed' : code)),
1548
+ };
1549
+ while (pending.length) {
1550
+ runtime.signal?.throwIfAborted();
1551
+ const index = pending.findIndex((node) => {
1552
+ const groups = node.targets.filter(({ child, agent }) => agent !== 'generic' && !executedNativeChildren.has(child));
1553
+ const members = new Set([node, ...groups.flatMap(({ child }) => pending.filter((candidate) => candidate.targets.some((target) => target.child === child)))]);
1554
+ return [...members].every((member) => [...member.dependencies].every((key) => !pending.some((candidate) => !members.has(candidate) && `${candidate.pluginId}\0${candidate.scope}` === key)));
1555
+ });
1556
+ if (index < 0) {
1557
+ plan.receipt.blockers.push(diagnostic('dependencyContractInvalid'));
1558
+ break;
1559
+ }
1560
+ const node = pending.splice(index, 1)[0];
1561
+ if (node.scope === 'project' && !retiredProjectCopies) {
1562
+ await retireVerified('project');
1563
+ retiredProjectCopies = true;
1564
+ }
1565
+ const key = `${node.pluginId}\0${node.scope}`;
1566
+ const standalonePackages = node.packages?.filter((target) => !consumesPackage(node, target)) ?? [];
1567
+ if (standalonePackages.length && packages) {
1568
+ if (failedNodes.has(key) || [...node.dependencies].some((dependency) => failedNodes.has(dependency))) {
1569
+ failedPackages.add(key);
1570
+ failedNodes.add(key);
1517
1571
  for (const target of standalonePackages)
1518
- produced.push(...await applyPackages(target.pluginId, target.scope));
1519
- if (!produced.every(commandPackageProviderSatisfied)) {
1572
+ blockPackages(target.pluginId, target.scope, 'dependencyApplyFailed');
1573
+ plan.receipt.blockers.push(diagnostic('commandPackageProviderNotSatisfied', node.pluginId));
1574
+ }
1575
+ else {
1576
+ try {
1577
+ const produced = [];
1578
+ for (const target of standalonePackages)
1579
+ produced.push(...await applyPackages(target.pluginId, target.scope));
1580
+ if (!produced.every(commandPackageProviderSatisfied)) {
1581
+ failedPackages.add(key);
1582
+ failedNodes.add(key);
1583
+ }
1584
+ }
1585
+ catch (error) {
1586
+ runtime.signal?.throwIfAborted();
1587
+ if (error instanceof Error && error.name === 'AbortError' || readSafeOperationError(error))
1588
+ throw error;
1520
1589
  failedPackages.add(key);
1521
1590
  failedNodes.add(key);
1591
+ plan.receipt.blockers.push(diagnostic('commandPackageApplyFailed', node.pluginId));
1522
1592
  }
1523
1593
  }
1524
- catch (error) {
1525
- runtime.signal?.throwIfAborted();
1526
- if (error instanceof Error && error.name === 'AbortError' || readSafeOperationError(error))
1527
- throw error;
1528
- failedPackages.add(key);
1529
- failedNodes.add(key);
1530
- plan.receipt.blockers.push(diagnostic('commandPackageApplyFailed', node.pluginId));
1531
- }
1594
+ }
1595
+ for (const { child, agent } of node.targets) {
1596
+ const native = agent !== 'generic';
1597
+ if (native && executedNativeChildren.has(child))
1598
+ continue;
1599
+ if (native)
1600
+ executedNativeChildren.add(child);
1601
+ const result = await executeChild(child, native ? child.receipt.requestedTargets.map((target) => target.pluginId) : node.pluginId, agent);
1602
+ for (const target of result.targetResults)
1603
+ if (target.blockers.length || !['applied', 'no-op'].includes(target.execution)) {
1604
+ failedNodes.add(`${target.pluginId}\0${target.scope}`);
1605
+ failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
1606
+ }
1532
1607
  }
1533
1608
  }
1534
- for (const { child, agent } of node.targets) {
1535
- const native = agent !== 'generic';
1536
- if (native && executedNativeChildren.has(child))
1609
+ if (!retiredProjectCopies)
1610
+ await retireVerified('project');
1611
+ await retireVerified('user');
1612
+ }
1613
+ catch (error) {
1614
+ const code = recoveryInterruptionCode(error, runtime.signal);
1615
+ if (!code)
1616
+ throw error;
1617
+ interrupted = error;
1618
+ if (error instanceof RecoveryInterruptedError)
1619
+ results.push(error.receipt);
1620
+ // Preserve settled child receipts. Replacement preApply runs before
1621
+ // child dispatch, so also retain its execution evidence and uncertainty.
1622
+ const reported = new Set(results.flatMap((result) => result.targetResults.map(targetKey)));
1623
+ for (const scope of ['user', 'project']) {
1624
+ const targetResults = plan.receipt.targetResults.filter((target) => target.scope === scope && !reported.has(targetKey(target)));
1625
+ if (!targetResults.length)
1537
1626
  continue;
1538
- if (native)
1539
- executedNativeChildren.add(child);
1540
- const result = await executeChild(child, native ? child.receipt.requestedTargets.map((target) => target.pluginId) : node.pluginId, agent);
1541
- for (const target of result.targetResults)
1542
- if (target.blockers.length || !['applied', 'no-op'].includes(target.execution)) {
1543
- failedNodes.add(`${target.pluginId}\0${target.scope}`);
1544
- failedProviders.add(`${target.pluginId}\0${target.agent}\0${target.scope}`);
1545
- }
1627
+ results.push(blockScopedRecoveryBeforeExecution(structuredClone({
1628
+ ...plan.receipt, scope, targetResults, commandResults: [], nativeToolChanges: [],
1629
+ outputsMayHaveChanged: joint.children.some((child) => child.receipt.scope === scope && child.receipt.outputsMayHaveChanged),
1630
+ }), diagnostic(code)));
1546
1631
  }
1547
1632
  }
1548
- if (!retiredProjectCopies)
1549
- await retireVerified('project');
1550
- await retireVerified('user');
1551
1633
  }
1552
1634
  const receipt = mergeReceipts(plan, results);
1553
1635
  completedReceipt = receipt;