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

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 (189) hide show
  1. package/dist/index.js +2 -6
  2. package/dist/index.js.map +1 -1
  3. package/dist/src/commands/public-lifecycle-result.d.ts +3 -8
  4. package/dist/src/commands/public-lifecycle-result.js +85 -30
  5. package/dist/src/commands/public-lifecycle-result.js.map +1 -1
  6. package/dist/src/commands/public-plugin-query.js +21 -5
  7. package/dist/src/commands/public-plugin-query.js.map +1 -1
  8. package/dist/src/commands/rebuild-command.js +19 -3
  9. package/dist/src/commands/rebuild-command.js.map +1 -1
  10. package/dist/src/commands/rebuild-integration.d.ts +1 -0
  11. package/dist/src/commands/rebuild-integration.js +5 -0
  12. package/dist/src/commands/rebuild-integration.js.map +1 -1
  13. package/dist/src/commands/rebuild-operations.js +5 -2
  14. package/dist/src/commands/rebuild-operations.js.map +1 -1
  15. package/dist/src/commands/rebuild-platform-integration.d.ts +7 -2
  16. package/dist/src/commands/rebuild-platform-integration.js +539 -65
  17. package/dist/src/commands/rebuild-platform-integration.js.map +1 -1
  18. package/dist/src/generators/permissions.d.ts +7 -1
  19. package/dist/src/generators/permissions.js +56 -0
  20. package/dist/src/generators/permissions.js.map +1 -1
  21. package/dist/src/index.d.ts +1 -0
  22. package/dist/src/index.js +7 -4
  23. package/dist/src/index.js.map +1 -1
  24. package/dist/src/intent/scope-context.d.ts +4 -2
  25. package/dist/src/intent/scope-context.js +37 -7
  26. package/dist/src/intent/scope-context.js.map +1 -1
  27. package/dist/src/output/component-delivery.d.ts +21 -0
  28. package/dist/src/output/component-delivery.js +82 -0
  29. package/dist/src/output/component-delivery.js.map +1 -0
  30. package/dist/src/output/public-result.d.ts +2 -0
  31. package/dist/src/output/public-result.js +49 -16
  32. package/dist/src/output/public-result.js.map +1 -1
  33. package/dist/src/output/receipt-projection.js +13 -5
  34. package/dist/src/output/receipt-projection.js.map +1 -1
  35. package/dist/src/output/skill-invocation-notices.d.ts +2 -0
  36. package/dist/src/output/skill-invocation-notices.js +40 -4
  37. package/dist/src/output/skill-invocation-notices.js.map +1 -1
  38. package/dist/src/platforms/capabilities.d.ts +4 -1
  39. package/dist/src/platforms/capabilities.js +93 -9
  40. package/dist/src/platforms/capabilities.js.map +1 -1
  41. package/dist/src/platforms/contracts.d.ts +36 -1
  42. package/dist/src/platforms/discovery.d.ts +11 -0
  43. package/dist/src/platforms/discovery.js +170 -30
  44. package/dist/src/platforms/discovery.js.map +1 -1
  45. package/dist/src/platforms/inspection-grok.js +121 -9
  46. package/dist/src/platforms/inspection-grok.js.map +1 -1
  47. package/dist/src/platforms/inspection-native.js +53 -18
  48. package/dist/src/platforms/inspection-native.js.map +1 -1
  49. package/dist/src/platforms/inspection-pi.d.ts +7 -1
  50. package/dist/src/platforms/inspection-pi.js +295 -95
  51. package/dist/src/platforms/inspection-pi.js.map +1 -1
  52. package/dist/src/platforms/inspection-query.d.ts +4 -2
  53. package/dist/src/platforms/inspection-query.js +24 -8
  54. package/dist/src/platforms/inspection-query.js.map +1 -1
  55. package/dist/src/platforms/inspection.d.ts +4 -1
  56. package/dist/src/platforms/inspection.js +36 -4
  57. package/dist/src/platforms/inspection.js.map +1 -1
  58. package/dist/src/platforms/layout.d.ts +6 -0
  59. package/dist/src/platforms/layout.js +44 -7
  60. package/dist/src/platforms/layout.js.map +1 -1
  61. package/dist/src/platforms/lifecycle-native.d.ts +1 -0
  62. package/dist/src/platforms/lifecycle-native.js +25 -1
  63. package/dist/src/platforms/lifecycle-native.js.map +1 -1
  64. package/dist/src/platforms/lifecycle.d.ts +2 -0
  65. package/dist/src/platforms/lifecycle.js +67 -16
  66. package/dist/src/platforms/lifecycle.js.map +1 -1
  67. package/dist/src/platforms/projection-code-extension.js +2 -1
  68. package/dist/src/platforms/projection-code-extension.js.map +1 -1
  69. package/dist/src/platforms/projection.js +70 -22
  70. package/dist/src/platforms/projection.js.map +1 -1
  71. package/dist/src/platforms/supplement-layout.d.ts +5 -1
  72. package/dist/src/platforms/supplement-layout.js +23 -1
  73. package/dist/src/platforms/supplement-layout.js.map +1 -1
  74. package/dist/src/platforms/supplement-state.d.ts +1 -1
  75. package/dist/src/platforms/supplement-state.js +18 -7
  76. package/dist/src/platforms/supplement-state.js.map +1 -1
  77. package/dist/src/portable/commands.js +1 -1
  78. package/dist/src/portable/commands.js.map +1 -1
  79. package/dist/src/portable/materializer.d.ts +4 -0
  80. package/dist/src/portable/materializer.js +8 -1
  81. package/dist/src/portable/materializer.js.map +1 -1
  82. package/dist/src/portable/recovery.d.ts +2 -0
  83. package/dist/src/portable/recovery.js +45 -8
  84. package/dist/src/portable/recovery.js.map +1 -1
  85. package/dist/src/recovery/coordinator.d.ts +1 -1
  86. package/dist/src/recovery/coordinator.js +77 -10
  87. package/dist/src/recovery/coordinator.js.map +1 -1
  88. package/dist/src/recovery/install-concurrency.js +3 -2
  89. package/dist/src/recovery/install-concurrency.js.map +1 -1
  90. package/dist/src/recovery/joint-coordinator.d.ts +7 -0
  91. package/dist/src/recovery/joint-coordinator.js +173 -23
  92. package/dist/src/recovery/joint-coordinator.js.map +1 -1
  93. package/dist/src/recovery/joint-demand.d.ts +14 -2
  94. package/dist/src/recovery/joint-demand.js +54 -7
  95. package/dist/src/recovery/joint-demand.js.map +1 -1
  96. package/dist/src/recovery/receipt.d.ts +15 -4
  97. package/dist/src/recovery/receipt.js +23 -0
  98. package/dist/src/recovery/receipt.js.map +1 -1
  99. package/dist/src/recovery/status.d.ts +20 -8
  100. package/dist/src/recovery/status.js +380 -90
  101. package/dist/src/recovery/status.js.map +1 -1
  102. package/dist/src/review/platform-profile.js +2 -1
  103. package/dist/src/review/platform-profile.js.map +1 -1
  104. package/dist/src/review/skill-materialization.d.ts +1 -0
  105. package/dist/src/review/skill-materialization.js +45 -39
  106. package/dist/src/review/skill-materialization.js.map +1 -1
  107. package/dist/src/review/source-binding.js +5 -1
  108. package/dist/src/review/source-binding.js.map +1 -1
  109. package/dist/src/tui/console-app-v4.js +67 -30
  110. package/dist/src/tui/console-app-v4.js.map +1 -1
  111. package/dist/src/tui/controller-runtime.js +1 -1
  112. package/dist/src/tui/controller-runtime.js.map +1 -1
  113. package/dist/src/tui/controller.d.ts +2 -1
  114. package/dist/src/tui/controller.js +17 -4
  115. package/dist/src/tui/controller.js.map +1 -1
  116. package/dist/src/tui/deployment-view.d.ts +6 -3
  117. package/dist/src/tui/deployment-view.js +39 -10
  118. package/dist/src/tui/deployment-view.js.map +1 -1
  119. package/dist/src/tui/diagnostic-projection.d.ts +7 -1
  120. package/dist/src/tui/diagnostic-projection.js +47 -2
  121. package/dist/src/tui/diagnostic-projection.js.map +1 -1
  122. package/dist/src/tui/entity-cards.d.ts +2 -1
  123. package/dist/src/tui/entity-cards.js +34 -11
  124. package/dist/src/tui/entity-cards.js.map +1 -1
  125. package/dist/src/tui/glossary.js +5 -0
  126. package/dist/src/tui/glossary.js.map +1 -1
  127. package/dist/src/tui/model.js +2 -1
  128. package/dist/src/tui/model.js.map +1 -1
  129. package/dist/src/tui/operation-diagnostic-screens.js +3 -1
  130. package/dist/src/tui/operation-diagnostic-screens.js.map +1 -1
  131. package/dist/src/tui/operation-history.d.ts +6 -0
  132. package/dist/src/tui/operation-history.js +20 -2
  133. package/dist/src/tui/operation-history.js.map +1 -1
  134. package/dist/src/tui/plugin-detail.d.ts +4 -1
  135. package/dist/src/tui/plugin-detail.js +9 -2
  136. package/dist/src/tui/plugin-detail.js.map +1 -1
  137. package/dist/src/tui/scoped-flow.js +34 -16
  138. package/dist/src/tui/scoped-flow.js.map +1 -1
  139. package/dist/src/tui/scoped-inventory.d.ts +6 -2
  140. package/dist/src/tui/scoped-inventory.js +29 -7
  141. package/dist/src/tui/scoped-inventory.js.map +1 -1
  142. package/dist/src/types.d.ts +2 -1
  143. package/dist/src/types.js.map +1 -1
  144. package/dist/src/utils/artifact-plan.js +5 -1
  145. package/dist/src/utils/artifact-plan.js.map +1 -1
  146. package/dist/src/utils/artifact-renderer.d.ts +1 -1
  147. package/dist/src/utils/artifact-renderer.js +29 -8
  148. package/dist/src/utils/artifact-renderer.js.map +1 -1
  149. package/dist/src/utils/catalog-source-references.js +12 -3
  150. package/dist/src/utils/catalog-source-references.js.map +1 -1
  151. package/dist/src/utils/codex-native-observation.d.ts +6 -0
  152. package/dist/src/utils/codex-native-observation.js +32 -3
  153. package/dist/src/utils/codex-native-observation.js.map +1 -1
  154. package/dist/src/utils/component-command-preparation.d.ts +2 -0
  155. package/dist/src/utils/component-command-preparation.js +23 -4
  156. package/dist/src/utils/component-command-preparation.js.map +1 -1
  157. package/dist/src/utils/component-gap.d.ts +4 -0
  158. package/dist/src/utils/component-gap.js +20 -0
  159. package/dist/src/utils/component-gap.js.map +1 -0
  160. package/dist/src/utils/component-resources.js +2 -4
  161. package/dist/src/utils/component-resources.js.map +1 -1
  162. package/dist/src/utils/dynamic-skill-tree.js +2 -32
  163. package/dist/src/utils/dynamic-skill-tree.js.map +1 -1
  164. package/dist/src/utils/native-cli-interruption.d.ts +8 -0
  165. package/dist/src/utils/native-cli-interruption.js +65 -0
  166. package/dist/src/utils/native-cli-interruption.js.map +1 -0
  167. package/dist/src/utils/native-cli.d.ts +5 -0
  168. package/dist/src/utils/native-cli.js +166 -53
  169. package/dist/src/utils/native-cli.js.map +1 -1
  170. package/dist/src/utils/ownership.d.ts +1 -0
  171. package/dist/src/utils/ownership.js +17 -3
  172. package/dist/src/utils/ownership.js.map +1 -1
  173. package/dist/src/utils/package-content.d.ts +7 -0
  174. package/dist/src/utils/package-content.js +70 -0
  175. package/dist/src/utils/package-content.js.map +1 -0
  176. package/dist/src/utils/platform-empty-state.d.ts +31 -6
  177. package/dist/src/utils/platform-empty-state.js +135 -65
  178. package/dist/src/utils/platform-empty-state.js.map +1 -1
  179. package/dist/src/utils/plugin-config-write.js +5 -1
  180. package/dist/src/utils/plugin-config-write.js.map +1 -1
  181. package/dist/src/utils/plugin-scripts.js +19 -8
  182. package/dist/src/utils/plugin-scripts.js.map +1 -1
  183. package/dist/src/utils/process-tree.d.ts +1 -1
  184. package/dist/src/utils/process-tree.js +1 -1
  185. package/dist/src/utils/process-tree.js.map +1 -1
  186. package/dist/src/utils/skill-invocation-warning.d.ts +8 -3
  187. package/dist/src/utils/skill-invocation-warning.js +27 -1
  188. package/dist/src/utils/skill-invocation-warning.js.map +1 -1
  189. package/package.json +3 -3
@@ -2,23 +2,28 @@ import crypto from 'node:crypto';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import fs from 'fs-extra';
5
- import { createMarketplaceManifestEntry, getComponentFeatureRequirements, normalizeStaticPluginComponents, resolveInvocationPolicy } from '@lesliechan721/aw-plugin-core/manifest';
5
+ import { createMarketplaceManifestEntry, getComponentFeatureRequirements, normalizeStaticPluginComponents } from '@lesliechan721/aw-plugin-core/manifest';
6
+ import { selectNativeProduct, supportsSharedNativeProbe } from '../platforms/discovery.js';
6
7
  import { getAgentPluginAdapter } from '../platforms/registry.js';
7
- import { getQualifiedPlatformProfile } from '../platforms/capabilities.js';
8
- import { getDeploymentLayout, getDeploymentResourceKey, getInvocationPolicyPhysicalKey } from '../platforms/layout.js';
9
- import { deploymentPackageComponent, inspectStaticSupplements, requiredDeploymentActivation } from '../platforms/inspection.js';
10
- import { piProjectRegistrationHidden, piProjectRemovalConfirmed } from '../platforms/lifecycle-native.js';
8
+ import { getAntigravityUnsupportedSkillControls, getQualifiedPlatformProfile } from '../platforms/capabilities.js';
9
+ import { getDeploymentLayout, getDeploymentResourceKey, getInvocationPolicyPhysicalKey, isAntigravityProjectDirectory } from '../platforms/layout.js';
10
+ import { getPhysicalKey } from '../platforms/identity.js';
11
+ import { antigravityLegacyProjectComponent, deploymentPackageComponent, inspectStaticSupplements, requiredDeploymentActivation } from '../platforms/inspection.js';
12
+ import { hasCompleteDeliveryDeclaration } from '../platforms/lifecycle.js';
13
+ import { piAgentConsumerDiagnostic, piProjectListContainsOnly } from '../platforms/inspection-pi.js';
14
+ import { grokRegistrationOwned, piProjectEmptyDeliveryObserved, piProjectRegistrationHidden, piProjectRemovalConfirmed } from '../platforms/lifecycle-native.js';
11
15
  import { createNativeLifecycleServices } from '../platforms/lifecycle-native-services.js';
12
16
  import { cursorWorkspaceOpenCommand } from '../platforms/projection.js';
13
17
  import { cursorHookEntryCommand, cursorHooks } from '../platforms/cursor-workspace-hook.js';
14
- import { ownedSupplementFile, staticSupplementFiles } from '../platforms/supplement-layout.js';
18
+ import { gapSupplementFiles, ownedSupplementFile, staticSupplementFiles } from '../platforms/supplement-layout.js';
15
19
  import { projectPlatformMarketplace } from '../platforms/projection-marketplace.js';
16
20
  import { readStrictNamespacedMarketplaceRoot } from '../utils/local-marketplace.js';
21
+ import { isDeliveryCapabilityGap } from '../utils/component-gap.js';
17
22
  import { artifactValueDigest, mergeExpectedComponentSets } from '../utils/artifact-plan.js';
18
23
  import { preparePlatformComponents, resolveArtifactRenderConfig } from '../utils/artifact-renderer.js';
19
24
  import { finalizePlatformSkillProducers } from '../utils/component-command-preparation.js';
20
25
  import { cleanupOwnedComponents, createSharedOwnerToken, inspectOwnedComponents, renderOwnedTextFile, writeOwnedTextFile, writeSkillOwnerMarker } from '../utils/ownership.js';
21
- import { createPlatformInputEvidence, platformPackageInputDigest, readPlatformPackageContentDigest, writePlatformEmptyState } from '../utils/platform-empty-state.js';
26
+ import { createPlatformInputEvidence, platformPackageInputDigest, platformPermissionNotices, readPlatformPackageContentDigest, writePlatformEmptyState } from '../utils/platform-empty-state.js';
22
27
  import { writePlatformSupplementState } from '../platforms/supplement-state.js';
23
28
  import { atomicReplaceSafeFile, assertSafeFileMutationPath } from '../utils/safe-fs.js';
24
29
  import { assertManagedCommandBindingIdentities, captureManagedCommandBindingRecoveryEvidence, publishManagedCommandBindings, listManagedCommands, readInstalledCommandProducer, revokeManagedCommandBindings } from '../utils/managed-command-store.js';
@@ -55,9 +60,16 @@ export function nativeInstallResources(plans) {
55
60
  for (const file of evidence.marketplace?.files ?? [])
56
61
  paths.add(path.join(layout.marketplaceRoot, file.relativePath));
57
62
  }
63
+ // Grok inspects the entire project's packages and rules in one inventory.
64
+ // Keep peers out until this write and its confirming inspection finish.
65
+ if (binding.route === 'grok-directory') {
66
+ if (plan.effects.length)
67
+ paths.add(layout.activationPath);
68
+ continue;
69
+ }
58
70
  // These routes publish an entire, plugin-specific directory. activationPath
59
71
  // is its parent and is never replaced by the directory publisher.
60
- if (binding.route === 'opencode-directory' || binding.route === 'antigravity-directory' || binding.route === 'grok-directory')
72
+ if (binding.route === 'opencode-directory' || binding.route === 'antigravity-directory')
61
73
  continue;
62
74
  paths.add(layout.activationPath);
63
75
  if (binding.route === 'pi-package' || binding.route === 'cursor-workspace-hook')
@@ -70,10 +82,70 @@ export function nativeInstallResources(plans) {
70
82
  }
71
83
  return [...paths].map((value) => ({ kind: 'path', value }));
72
84
  }
85
+ function matchesGrokComponentOrder(before, after, publishedRoots) {
86
+ // Leave newly added or removed identities out of both sides. Every other
87
+ // row, including a surviving component of an upgraded package, anchors order.
88
+ const retained = (order, other) => {
89
+ const otherKeys = new Set(other.map(({ key }) => key));
90
+ return order.filter(({ sourceRoot, key }) => sourceRoot === null || !publishedRoots.has(sourceRoot) || otherKeys.has(key));
91
+ };
92
+ const previous = retained(before, after);
93
+ const current = retained(after, before);
94
+ return previous.length === current.length && previous.every((row, index) => row.key === current[index].key);
95
+ }
96
+ function grokSourceDigest(sources, root, name, scope, version) {
97
+ const index = sources.sources.findIndex((source) => path.normalize(source.path) === root);
98
+ const source = sources.sources[index];
99
+ if (!sources.overlaps.includes(name) && source?.name === name && source.version
100
+ && (!version || source.version === version) && source.scope === scope && source.origin === 'native' && source.enabled === true) {
101
+ return sources.grokScopeEvidence?.sourceDigests[index];
102
+ }
103
+ }
104
+ async function grokUserContentDigest({ installedRoot, owner, hasPackageHook }) {
105
+ try {
106
+ await assertSafeFileMutationPath({ filePath: path.join(installedRoot, '.grok-plugin', 'plugin.json'),
107
+ allowedRoot: path.dirname(path.dirname(installedRoot)), label: 'Grok installed package' });
108
+ const marker = await readSkillOwnerMarker({ skillRoot: owner.path, allowedRoot: owner.allowedRoot, expectedIdentity: owner.identity });
109
+ const projection = marker?.nativeProjection;
110
+ if (hasPackageHook && !projection?.components.some((component) => component.relativeOutputs.includes('hooks/hooks.json')))
111
+ return;
112
+ const digest = projection?.contentDigest;
113
+ if (digest && (await Promise.all([owner.path, installedRoot].map(readPlatformPackageContentDigest))).every((value) => value === digest))
114
+ return digest;
115
+ }
116
+ catch { /* Unverified bytes cannot explain the change of visible source. */ }
117
+ }
118
+ async function grokUserBehindProject(ctx, binding, before) {
119
+ const sources = before.prerequisites.nativeSources;
120
+ const evidence = sources?.grokScopeEvidence;
121
+ if (binding.route !== 'grok-directory' || before.package !== 'absent' || before.ownership !== 'absent'
122
+ || sources?.observation !== 'complete' || !evidence?.userRegistrationDigest)
123
+ return;
124
+ const name = before.nativeIdentity?.packageId;
125
+ const user = sources.sources.find((source) => source.name === name && source.scope === 'user');
126
+ if (!user)
127
+ return;
128
+ const nativeDigest = grokSourceDigest(sources, user.path, user.name, 'user', binding.plugin.version);
129
+ if (!nativeDigest)
130
+ return;
131
+ const personal = { ...binding, route: 'grok-cli', scope: { kind: 'user' } };
132
+ const layout = await getDeploymentLayout(ctx, personal);
133
+ if (evidence.userRegistrationDigest !== artifactValueDigest([user.path, layout.packageRoot]))
134
+ return;
135
+ const owner = deploymentPackageComponent({ ...personal, physicalKey: getPhysicalKey(layout.physicalIdentity) }, layout);
136
+ const hasPackageHook = evidence.hookOrder.some((row) => row.sourceRoot === user.path);
137
+ return { installedRoot: user.path, owner, nativeDigest, hasPackageHook };
138
+ }
73
139
  function nativeCopyIncomplete(binding, after, contentDigest) {
74
140
  return ['antigravity-cli', 'grok-cli'].includes(binding.route)
75
141
  && after.nativePackageContentDigest !== contentDigest;
76
142
  }
143
+ function piProjectInventoryKey(binding, settingsPath) {
144
+ if (binding.route !== 'pi-package' || binding.scope.kind !== 'project')
145
+ return undefined;
146
+ const product = selectNativeProduct(binding.consumers);
147
+ return product ? JSON.stringify([binding.scope.projectRoot, settingsPath, product.id]) : undefined;
148
+ }
77
149
  function packageDeliveryConfirmed(binding, after, contentDigest, requireIndependentActivation) {
78
150
  return after.package === 'present' && ['aw', 'shared'].includes(after.ownership)
79
151
  && !nativeCopyIncomplete(binding, after, contentDigest)
@@ -91,7 +163,7 @@ export function nativeDeploymentHasVerifiedComponentWrite(plan, receipt) {
91
163
  if (receipt.bindingId !== plan.binding.id || after.physicalKey !== plan.binding.physicalKey)
92
164
  return false;
93
165
  const delivered = after.components.filter(({ id, presence, reasonCodes }) => presence === 'present' && !reasonCodes.length
94
- && !unmet.some((gap) => (gap.componentId ?? gap.id) === id));
166
+ && !unmet.some((gap) => !isDeliveryCapabilityGap(gap) && (gap.componentId ?? gap.id) === id));
95
167
  if (!delivered.length)
96
168
  return false;
97
169
  const bundle = plan.projections.find((projection) => projection.bundle)?.bundle;
@@ -265,8 +337,10 @@ export const platformOwnership = {
265
337
  };
266
338
  async function requireWritable(component, executor = platformOwnership) {
267
339
  const inspection = await inspectOwnedComponents({ components: [component], executor });
268
- if (!['present', 'absent'].includes(inspection.components[0].state))
340
+ const state = inspection.components[0].state;
341
+ if (state !== 'present' && state !== 'absent')
269
342
  throw new Error('operationPlanStale: deployment ownership changed.');
343
+ return state;
270
344
  }
271
345
  async function publishDirectory(source, component, nativeProjection, staged) {
272
346
  if (component.kind !== 'owned-directory')
@@ -276,7 +350,9 @@ async function publishDirectory(source, component, nativeProjection, staged) {
276
350
  allowedRoot: component.allowedRoot, label: 'Native package', createParent: true });
277
351
  const staging = await fs.mkdtemp(path.join(component.allowedRoot, '.aw-package-'));
278
352
  const candidate = path.join(staging, component.identity.artifactKey);
279
- const backup = `${staging}.previous`;
353
+ const verifiesContents = component.identity.platform === 'antigravity' && component.identity.scope === 'project';
354
+ const backupRoot = `${staging}.previous`;
355
+ const backup = verifiesContents ? path.join(backupRoot, component.identity.artifactKey) : backupRoot;
280
356
  let moved = false;
281
357
  try {
282
358
  if (staged && nativeProjection) {
@@ -297,12 +373,15 @@ async function publishDirectory(source, component, nativeProjection, staged) {
297
373
  else
298
374
  await fs.copy(source, candidate, { dereference: false });
299
375
  await writeSkillOwnerMarker({ skillRoot: candidate, allowedRoot: staging, identity: component.identity, nativeProjection });
300
- await requireWritable(component);
301
- if (await fs.pathExists(component.path)) {
376
+ const state = await requireWritable(component);
377
+ if (verifiesContents ? state === 'present' : await fs.pathExists(component.path)) {
302
378
  await fs.move(component.path, backup);
303
379
  moved = true;
304
380
  }
305
381
  try {
382
+ if (verifiesContents && moved && await requireWritable({ ...component, path: backup, allowedRoot: backupRoot }) !== 'present') {
383
+ throw new Error('operationPlanStale: deployment backup could not be verified.');
384
+ }
306
385
  await fs.move(candidate, component.path);
307
386
  }
308
387
  catch (error) {
@@ -315,6 +394,8 @@ async function publishDirectory(source, component, nativeProjection, staged) {
315
394
  }
316
395
  finally {
317
396
  await fs.remove(staging);
397
+ if (verifiesContents)
398
+ await fs.rmdir(backupRoot).catch(() => undefined);
318
399
  }
319
400
  }
320
401
  async function sharedReferences(context, binding, observation, layout) {
@@ -393,6 +474,9 @@ export class PlatformRebuildSession {
393
474
  units = new Map();
394
475
  published = new Map();
395
476
  nativeEffects = new Map();
477
+ piProjectRegisteredRoots = new Map();
478
+ grokPublications = new Map();
479
+ grokProjectRetirements = new Map();
396
480
  exclusions = new Map();
397
481
  contexts = new Set();
398
482
  mutableChecks = new Map();
@@ -422,6 +506,86 @@ export class PlatformRebuildSession {
422
506
  ? batch !== this.closedObservationBatch : this.targets.size === 0 && platform !== 'codex';
423
507
  return open && batch ? { ...ctx, ...batch } : ctx;
424
508
  }
509
+ recordGrokWrites(prepared, receipt, packagePublished, writtenFiles, shadowedUser) {
510
+ const { binding, operation, evidence: { layout } } = prepared.plan;
511
+ const sources = receipt.after.prerequisites.nativeSources;
512
+ const evidence = sources?.grokScopeEvidence;
513
+ if (!['grok-cli', 'grok-directory'].includes(binding.route) || operation !== 'ensure'
514
+ || receipt.diagnostics.some((item) => item.severity === 'error') || sources?.observation !== 'complete' || !evidence)
515
+ return;
516
+ const scope = binding.scope.kind;
517
+ const scopeRoot = binding.scope.kind === 'project' ? binding.scope.projectRoot : layout.activationPath;
518
+ const { before, packageComponent: owner, bundle, contributions } = prepared.driverState;
519
+ const priorSources = before.prerequisites.nativeSources;
520
+ const identity = receipt.after.nativeIdentity;
521
+ const registrationId = identity?.registrationId;
522
+ const refreshed = binding.route === 'grok-cli' && registrationId && bundle
523
+ && before.grokScopeAuthorization === 'granted' && receipt.after.grokScopeAuthorization === 'granted'
524
+ && grokRegistrationOwned(binding, prepared.plan.evidence, before, identity)
525
+ && grokRegistrationOwned(binding, prepared.plan.evidence, receipt.after, identity)
526
+ && receipt.after.nativePackageContentDigest === bundle.contentDigest
527
+ && prepared.plan.effects.some((effect) => effect.kind === 'refresh' && receipt.effects.some((result) => result.id === effect.id && result.status === 'applied' && result.mutation === 'confirmed'));
528
+ // A previous refusal can leave the AW source up to date. Only the confirmed
529
+ // native refresh explains a change to the User inventory in this operation.
530
+ const installedRoot = refreshed ? path.join(scopeRoot, 'installed-plugins', registrationId) : undefined;
531
+ const root = installedRoot ?? path.normalize(layout.packageRoot);
532
+ if ((refreshed || binding.route === 'grok-directory' && packagePublished) && priorSources?.observation === 'complete'
533
+ && receipt.after.package === 'present' && receipt.after.ownership === 'aw' && bundle
534
+ && owner?.kind === 'owned-directory' && owner.path === layout.packageRoot && identity?.route === binding.route
535
+ && identity.sourceLocation === layout.packageRoot) {
536
+ const newlyInstalled = binding.route === 'grok-directory' && before.package === 'absent' && before.ownership === 'absent'
537
+ && !priorSources.sources.some((source) => path.normalize(source.path) === root
538
+ || source.name === identity.packageId && source.path !== shadowedUser?.installedRoot)
539
+ && (!shadowedUser || !sources.sources.some((source) => source.path === shadowedUser.installedRoot));
540
+ const priorNativeDigest = before.package === 'present' && before.ownership === 'aw' && (refreshed || before.packageVersion)
541
+ ? grokSourceDigest(priorSources, root, identity.packageId, scope, refreshed ? undefined : before.packageVersion) : undefined;
542
+ const nativeDigest = grokSourceDigest(sources, root, identity.packageId, scope, binding.plugin.version);
543
+ const knownHooks = !evidence.hookOrder.some((row) => row.sourceRoot === root) || prepared.plan.projections.some((projection) => projection.bundle
544
+ && projection.components.some((component) => component.relativeOutputs.includes('hooks/hooks.json')));
545
+ if ((newlyInstalled || priorNativeDigest) && nativeDigest && knownHooks) {
546
+ this.grokPublications.set(root, { scope, scopeRoot, installedRoot, nativeDigest, priorNativeDigest, contentDigest: bundle.contentDigest,
547
+ owner, orderAfter: evidence, shadowedUser,
548
+ sourceOrderAfter: shadowedUser && sources.sources.map((source) => path.normalize(source.path)) });
549
+ }
550
+ }
551
+ const prior = priorSources?.grokScopeEvidence?.instructions;
552
+ for (const { effectId, component } of contributions) {
553
+ if (component.kind !== 'owned-text-file' || !prior)
554
+ continue;
555
+ const written = writtenFiles.get(component.path);
556
+ const rows = evidence.instructions.filter((row) => row.rulePath === component.path);
557
+ const previous = prior.filter((row) => row.rulePath === component.path);
558
+ if (written && rows.length === 1 && previous.length <= 1 && receipt.effects.some((effect) => effect.id === effectId && effect.status === 'applied' && effect.mutation === 'confirmed')) {
559
+ this.grokPublications.set(component.path, { scope, scopeRoot, nativeDigest: rows[0].digest,
560
+ priorNativeDigest: previous[0]?.digest, contentDigest: written.digest, owner: component });
561
+ }
562
+ }
563
+ }
564
+ recordGrokProjectRetirement(projectRoot, project, user, removed) {
565
+ const old = project.nativeIdentity;
566
+ const replacement = user.nativeIdentity;
567
+ if (old?.route !== 'grok-directory' || project.ownership !== 'aw' || project.package !== 'present'
568
+ || replacement?.route !== 'grok-cli' || replacement.packageId !== old.packageId || !replacement.registrationId
569
+ || user.ownership !== 'aw' || user.registration !== 'present' || user.nativePackage !== 'present' || !user.nativePackageContentDigest
570
+ || path.dirname(old.sourceLocation) !== path.join(projectRoot, '.grok', 'plugins') || !removed.includes(path.basename(old.sourceLocation)))
571
+ return;
572
+ const before = project.prerequisites.nativeSources;
573
+ const personal = user.prerequisites.nativeSources;
574
+ if (before?.observation !== 'complete' || personal?.observation !== 'complete')
575
+ return;
576
+ const source = personal.sources.find(({ name, path: location }) => name === old.packageId
577
+ && path.basename(location) === replacement.registrationId && path.basename(path.dirname(location)) === 'installed-plugins');
578
+ const projectDigest = grokSourceDigest(before, old.sourceLocation, old.packageId, 'project');
579
+ const userDigest = source && grokSourceDigest(personal, source.path, old.packageId, 'user');
580
+ if (!projectDigest || !source || !userDigest)
581
+ return;
582
+ // Retirement can reveal an inherited static Skill provider only.
583
+ if (personal.grokScopeEvidence?.hookOrder.some((row) => row.sourceRoot === source.path))
584
+ return;
585
+ this.grokProjectRetirements.set(old.sourceLocation, { projectRoot, name: old.packageId, projectPackage: old.sourceLocation,
586
+ projectDigest, userPackage: source.path, userDigest, userSource: replacement.sourceLocation,
587
+ userContentDigest: user.nativePackageContentDigest, userPhysicalKey: user.physicalKey });
588
+ }
425
589
  async dispose() {
426
590
  for (const result of await Promise.allSettled(this.units.values()))
427
591
  if (result.status === 'fulfilled')
@@ -434,7 +598,10 @@ export class PlatformRebuildSession {
434
598
  this.units.clear();
435
599
  this.published.clear();
436
600
  this.nativeEffects.clear();
601
+ this.piProjectRegisteredRoots.clear();
437
602
  this.exclusions.clear();
603
+ this.grokPublications.clear();
604
+ this.grokProjectRetirements.clear();
438
605
  this.contexts.clear();
439
606
  this.mutableChecks.clear();
440
607
  this.requestedOperations.clear();
@@ -444,7 +611,7 @@ export class PlatformRebuildSession {
444
611
  }
445
612
  freezeMarketplaceCandidates() { this.marketplaceCandidatesFrozen = true; }
446
613
  key(input) { return artifactValueDigest({ plugin: sourceIdentity(input), platform: input.platform, scope: input.scope, cwd: input.scope === 'project' ? input.cwd : null, operation: operation(input) }); }
447
- resolve(input) {
614
+ resolve(input, placementProbeGroup) {
448
615
  const key = this.key(input);
449
616
  // Inspection of a shared package does not request activation in that scope.
450
617
  if (!input.readOnlyInspectionPlan)
@@ -460,7 +627,7 @@ export class PlatformRebuildSession {
460
627
  && candidate.binding.plugin.sourceIdentity === plugin.sourceIdentity && candidate.binding.plugin.pluginId === plugin.pluginId
461
628
  && candidate.binding.scope.kind === input.scope && (candidate.binding.scope.kind !== 'project' || candidate.binding.scope.projectRoot === input.cwd));
462
629
  const scope = input.scope === 'project' ? { kind: 'project', projectRoot: input.cwd } : { kind: 'user' };
463
- const discovery = await adapter.discover(ctx);
630
+ const discovery = await adapter.discover(placementProbeGroup ? { ...ctx, placementProbeGroup } : ctx);
464
631
  const resolution = await adapter.resolve(ctx, { plugin, scope, operation: operation(input), discovery, recoveryCandidates });
465
632
  this.exclusions.set(key, resolution.exclusions.flatMap((exclusion) => {
466
633
  if (!exclusion.productId)
@@ -487,7 +654,13 @@ export class PlatformRebuildSession {
487
654
  }
488
655
  /** Resolve the whole selected scope before any physical unit is rendered. */
489
656
  async resolveAll(inputs) {
490
- await Promise.allSettled(inputs.map((input) => this.resolve(input)));
657
+ const first = inputs[0];
658
+ const samePlacement = supportsSharedNativeProbe && first && inputs.length > 1
659
+ && this.context.batchInstallPlatform === first.platform && this.context.nativeObservationBatch?.scriptFreePlacement === true
660
+ && inputs.every((input) => input.platform === first.platform && input.scope === first.scope && input.cwd === first.cwd
661
+ && operation(input) === 'ensure');
662
+ const group = samePlacement ? { scope: first.scope, probes: new Map() } : undefined;
663
+ await Promise.allSettled(inputs.map((input) => this.resolve(input, group)));
491
664
  }
492
665
  async freezeSharedPreApplyActions(targets) {
493
666
  const prepared = (await Promise.allSettled(this.targets.values())).flatMap((result) => result.status === 'fulfilled' ? [result.value] : []);
@@ -729,8 +902,13 @@ export class PlatformRebuildSession {
729
902
  env: this.context.env, referencePlugins: this.context.referencePlugins });
730
903
  const platformRoot = path.join(input.plugin.rootDir, input.platform);
731
904
  const staticResourceRoot = await fs.pathExists(platformRoot) ? platformRoot : input.plugin.rootDir;
905
+ // Grok prepares the package before its rules. Only roles prepared for this same target can receive the text.
906
+ const grokRoleUnit = input.platform === 'grok' && unit.output === 'supplement'
907
+ ? bindingEntry.layout.renderUnits.find((candidate) => candidate.output === 'package'
908
+ && artifactValueDigest(candidate.renderScope) === artifactValueDigest(unit.renderScope)) : undefined;
732
909
  const prepared = await preparePlatformComponents({ plugin: input.plugin, platform: input.platform, staticResourceRoot,
733
910
  renderScope: unit.renderScope.kind, kinds: unit.kinds, capabilities, config, cwd: input.cwd,
911
+ hasInstructionAgentRecipients: grokRoleUnit && preparedUnits.get(grokRoleUnit.id)?.prepared.expected.components.some(({ kind }) => kind === 'agent'),
734
912
  commandEnv: this.context.env, signal: this.context.signal, scriptTimeoutMs: this.context.scriptTimeoutMs,
735
913
  preparedResults: this.context.preparedArtifactRenderResults });
736
914
  const finalized = await finalizePlatformSkillProducers({ plugin: input.plugin, plugins: this.context.referencePlugins,
@@ -749,11 +927,13 @@ export class PlatformRebuildSession {
749
927
  const blockedReceipts = [];
750
928
  const cleanupResults = [];
751
929
  const checks = new Map();
930
+ const shadowedUsers = new Map();
752
931
  let initialDiscoveryCheck;
753
932
  const priorProducers = new Map();
754
933
  const priorResourceRoots = new Map();
755
934
  const bindingRecoveryEvidence = [];
756
935
  const emptyStates = new Map();
936
+ const gapStates = new Map();
757
937
  const inputDigests = new Map();
758
938
  const supplementInputDigests = new Map();
759
939
  const commandInventory = await listManagedCommands(this.context.env);
@@ -808,16 +988,26 @@ export class PlatformRebuildSession {
808
988
  files: sameScope.flatMap((candidate) => candidate.prepared.resources.files),
809
989
  commandResources: sameScope.flatMap((candidate) => candidate.prepared.resources.commandResources),
810
990
  digest: artifactValueDigest(sameScope.map((candidate) => candidate.prepared.resources.digest)) };
811
- projections.push(await adapter.project({ ...ctx, stagingRoot: path.join(await this.root(), 'projection'), commandResolver: unit.finalized.commandResolver }, {
991
+ const projection = await adapter.project({ ...ctx, stagingRoot: path.join(await this.root(), 'projection'), commandResolver: unit.finalized.commandResolver }, {
812
992
  binding: entry.binding, renderUnit: unit.unit, capabilities: adapter.capabilities({ ...entry, renderUnit: unit.unit, profile: getQualifiedPlatformProfile(input.platform) }),
813
- components, resources, policy: components.length ? resolveInvocationPolicy(input.plugin.manifest, input.platform) : { ...resolveInvocationPolicy(input.plugin.manifest, input.platform), permissions: [] }
814
- }));
993
+ components, resources, policy: components.length ? unit.finalized.invocationPolicy.policy : { platform: input.platform, permissions: [] }
994
+ });
995
+ for (const notice of unit.finalized.invocationPolicy.diagnostics) {
996
+ projection.diagnostics.push({ ...notice, subject: { ...notice.subject, scope: entry.binding.scope.kind } });
997
+ }
998
+ projections.push(projection);
815
999
  }
816
1000
  const policyKey = input.platform === 'codex' || input.platform === 'claude' ? await getInvocationPolicyPhysicalKey(ctx, entry.binding) : undefined;
1001
+ const expected = mergeExpectedComponentSets(units.map((unit) => unit.prepared.expected));
817
1002
  const currentComponents = [deploymentPackageComponent(entry.binding, entry.layout),
818
1003
  ...projections.flatMap((projection) => projection.supplements.map((contribution) => contributionComponent(entry.binding, contribution, policyKey && (contribution.mergeKey?.startsWith('claude-permissions:') || input.platform === 'codex' && contribution.destination.endsWith('.rules'))
819
1004
  ? policyKey : entry.layout.renderUnits.find((unit) => unit.id === projection.renderUnitId).physicalKey)))];
820
1005
  const historical = await ownedSupplements(entry.binding, entry.layout.supplementRoot, entry.layout.renderUnits.find((unit) => unit.output === 'supplement')?.physicalKey);
1006
+ const antigravityProject = isAntigravityProjectDirectory(entry.binding);
1007
+ const legacyPackage = entry.observation.antigravityLegacyProjectPackage?.state === 'owned'
1008
+ ? antigravityLegacyProjectComponent(entry.binding, entry.layout) : undefined;
1009
+ if (legacyPackage)
1010
+ historical.push(legacyPackage);
821
1011
  if (entry.binding.platform === 'codex' && policyKey)
822
1012
  historical.push(...await ownedSupplements(entry.binding, path.join(entry.layout.activationPath, 'rules'), policyKey));
823
1013
  if (entry.binding.platform === 'claude' && policyKey) {
@@ -832,6 +1022,10 @@ export class PlatformRebuildSession {
832
1022
  component.locator.command = cursorWorkspaceOpenCommand(entry.binding, ctx.platform);
833
1023
  historical.push(component);
834
1024
  }
1025
+ for (const slot of gapSupplementFiles(entry.binding, entry.layout, expected.unmet)) {
1026
+ if (!historical.some((component) => 'path' in component && component.path === slot.path))
1027
+ historical.push(slot);
1028
+ }
835
1029
  const components = [...currentComponents, ...historical.filter((component) => !currentComponents.some((current) => 'path' in current && 'path' in component && current.path === component.path
836
1030
  || current.kind === 'shared-config' && component.kind === 'shared-config' && artifactValueDigest(current.locator) === artifactValueDigest(component.locator)))];
837
1031
  for (const component of components)
@@ -856,10 +1050,12 @@ export class PlatformRebuildSession {
856
1050
  ownership: await inspectOwnedComponents({ components: [component], executor: this.ownership }), contentDigest: await ownedContentDigest(component),
857
1051
  })) };
858
1052
  };
859
- const fingerprintParts = async (discovery, batch) => ({
1053
+ const shadowedUser = operation(input) === 'ensure' ? await grokUserBehindProject(ctx, entry.binding, entry.observation) : undefined;
1054
+ const fingerprintParts = async (discovery) => ({
1055
+ ...(shadowedUser && { grokUserContent: await grokUserContentDigest(shadowedUser) }),
860
1056
  managedCommandReview,
861
1057
  source: removing ? null : await pathEvidence(input.plugin.rootDir),
862
- discovery: discovery ? discovery.value : removing ? { consumers: entry.binding.consumers, executables: await Promise.all(entry.binding.consumers.map((consumer) => consumer.entry?.kind === 'cli' ? pathEvidence(consumer.entry.executable) : null)) } : await adapter.discover(batch ? { ...ctx, ...batch } : ctx),
1058
+ discovery: discovery ? discovery.value : removing ? { consumers: entry.binding.consumers, executables: await Promise.all(entry.binding.consumers.map((consumer) => consumer.entry?.kind === 'cli' ? pathEvidence(consumer.entry.executable) : null)) } : await adapter.discover(ctx),
863
1059
  sharedReferenceView: this.context.sharedReferenceView,
864
1060
  layout: await getDeploymentLayout(ctx, entry.binding),
865
1061
  config: await Promise.all(units.map((unit) => resolveArtifactRenderConfig({ ...sourceIdentity(input), pluginName: input.plugin.manifest.name,
@@ -878,11 +1074,14 @@ export class PlatformRebuildSession {
878
1074
  if (initialReads?.[0].status === 'rejected')
879
1075
  throw initialReads[0].reason;
880
1076
  const initialParts = initialReads?.[0].status === 'fulfilled' ? initialReads[0].value : await fingerprintParts();
1077
+ if (shadowedUser && initialParts.grokUserContent) {
1078
+ shadowedUsers.set(entry.binding.id, { ...shadowedUser, contentDigest: initialParts.grokUserContent });
1079
+ }
881
1080
  if (!removing && ordinaryEvidence && ordinaryEvidence.discovery !== artifactValueDigest(initialParts.discovery)) {
882
1081
  throw new Error('operationPlanStale: client discovery changed after the ordinary observation.');
883
1082
  }
884
1083
  const initial = artifactValueDigest(initialParts);
885
- const fingerprint = async (discovery, batch) => artifactValueDigest(await fingerprintParts(discovery, batch));
1084
+ const fingerprint = async (discovery) => artifactValueDigest(await fingerprintParts(discovery));
886
1085
  if (initialReads?.[1].status === 'rejected')
887
1086
  throw initialReads[1].reason;
888
1087
  let mutableBaseline = initialReads?.[1].status === 'fulfilled' ? initialReads[1].value : await currentMutable();
@@ -890,20 +1089,205 @@ export class PlatformRebuildSession {
890
1089
  if (ordinaryObservation !== undefined && ordinaryObservation !== artifactValueDigest(mutableBaseline.observation)) {
891
1090
  throw new Error('operationPlanStale: deployment evidence changed after the ordinary observation.');
892
1091
  }
893
- const preparationObservation = entry.binding.route === 'antigravity-cli'
1092
+ const preparationObservation = entry.binding.route === 'antigravity-cli' || antigravityProject
894
1093
  ? mutableBaseline.observation : entry.observation;
895
- const check = async (discovery, batch) => {
896
- if (!parallelNativeReads)
897
- return await fingerprint(discovery, batch) === initial
898
- && artifactValueDigest(await currentMutable(batch)) === artifactValueDigest(mutableBaseline);
899
- const [immutableRead, mutableRead] = await Promise.allSettled([fingerprint(discovery, batch), currentMutable(batch)]);
900
- if (immutableRead.status === 'rejected')
901
- throw immutableRead.reason;
902
- if (immutableRead.value !== initial)
1094
+ const piInventoryKey = piProjectInventoryKey(entry.binding, entry.layout.activationPath);
1095
+ const matchesMutable = (current) => {
1096
+ const currentDigest = artifactValueDigest(current);
1097
+ if (currentDigest === artifactValueDigest(mutableBaseline))
1098
+ return true;
1099
+ const registered = piInventoryKey && this.piProjectRegisteredRoots.get(piInventoryKey);
1100
+ if (!registered || operation(input) !== 'ensure' || !piProjectEmptyDeliveryObserved(entry.binding, mutableBaseline.observation)
1101
+ || current.observation.registration !== 'absent' || !piProjectListContainsOnly(current.observation, registered))
903
1102
  return false;
904
- if (mutableRead.status === 'rejected')
905
- throw mutableRead.reason;
906
- return artifactValueDigest(mutableRead.value) === artifactValueDigest(mutableBaseline);
1103
+ // The first successful register in an empty Project can expose its
1104
+ // section. Compare every other fact with the original empty target.
1105
+ const { observation: before, ...baseline } = mutableBaseline;
1106
+ return currentDigest === artifactValueDigest({ ...baseline,
1107
+ observation: { ...before, registration: 'absent',
1108
+ diagnostics: before.diagnostics.filter(({ code }) => code !== 'piProjectRegistrationNotVisible') } });
1109
+ };
1110
+ const matchesAfterGrokPublications = async (current) => {
1111
+ const { binding } = entry;
1112
+ const scopeRoot = binding.route === 'grok-cli' ? entry.layout.activationPath
1113
+ : binding.route === 'grok-directory' && binding.scope.kind === 'project' ? binding.scope.projectRoot : null;
1114
+ const publications = scopeRoot && operation(input) === 'ensure' ? [...this.grokPublications.values()].filter((item) => item.scope === binding.scope.kind && item.scopeRoot === scopeRoot && item.owner.identity.pluginId !== binding.plugin.pluginId) : [];
1115
+ const retirements = binding.route === 'grok-directory' && operation(input) === 'ensure'
1116
+ ? [...this.grokProjectRetirements.values()].filter((item) => item.projectRoot === scopeRoot) : [];
1117
+ const baselineDigest = artifactValueDigest(mutableBaseline);
1118
+ if (!publications.length && !retirements.length)
1119
+ return artifactValueDigest(current) === baselineDigest;
1120
+ const before = mutableBaseline.observation.prerequisites.nativeSources;
1121
+ const after = current.observation.prerequisites.nativeSources;
1122
+ const priorEvidence = before?.grokScopeEvidence;
1123
+ const scopeEvidence = after?.grokScopeEvidence;
1124
+ if (before?.observation !== 'complete' || after?.observation !== 'complete' || !scopeEvidence || !priorEvidence
1125
+ || scopeEvidence.scopeDigest !== priorEvidence.scopeDigest)
1126
+ return false;
1127
+ const paths = after.sources.map((source) => path.normalize(source.path));
1128
+ const priorPaths = before.sources.map((source) => path.normalize(source.path));
1129
+ if (new Set(paths).size !== paths.length || new Set(priorPaths).size !== priorPaths.length)
1130
+ return false;
1131
+ const sources = [...after.sources];
1132
+ const sourceDigests = [...scopeEvidence.sourceDigests];
1133
+ const addedSources = new Set();
1134
+ const publishedRoots = new Set();
1135
+ const orderChecks = [priorEvidence];
1136
+ const instructions = [...scopeEvidence.instructions];
1137
+ const retiredSources = new Set();
1138
+ let adjusted = false;
1139
+ for (const retirement of retirements) {
1140
+ const { name, projectPackage, projectDigest, userPackage, userDigest, userSource, userContentDigest, userPhysicalKey } = retirement;
1141
+ if (!priorPaths.includes(projectPackage))
1142
+ continue;
1143
+ if (name === entry.layout.nativeIdentity.packageId || priorPaths.includes(userPackage) || paths.includes(projectPackage)
1144
+ || grokSourceDigest(before, projectPackage, name, 'project') !== projectDigest
1145
+ || grokSourceDigest(after, userPackage, name, 'user') !== userDigest
1146
+ || await pathEvidence(projectPackage) !== null)
1147
+ return false;
1148
+ await assertSafeFileMutationPath({ filePath: path.join(userPackage, '.grok-plugin', 'plugin.json'),
1149
+ allowedRoot: path.dirname(path.dirname(userPackage)), label: 'Grok installed package' });
1150
+ const [installed, source, marker] = await Promise.all([readPlatformPackageContentDigest(userPackage), readPlatformPackageContentDigest(userSource),
1151
+ readSkillOwnerMarker({ skillRoot: userSource, allowedRoot: path.dirname(userSource) })]);
1152
+ if (installed !== userContentDigest || source !== userContentDigest || marker?.physicalKey !== userPhysicalKey)
1153
+ return false;
1154
+ // The Project copy hid this exact User copy. Both may leave their
1155
+ // old positions, and the remaining sources and components keep theirs.
1156
+ retiredSources.add(projectPackage);
1157
+ addedSources.add(userPackage);
1158
+ publishedRoots.add(projectPackage);
1159
+ publishedRoots.add(userPackage);
1160
+ adjusted = true;
1161
+ }
1162
+ for (const { owner, scopeRoot: publishedRoot, installedRoot, nativeDigest, contentDigest, priorNativeDigest, orderAfter, shadowedUser } of publications) {
1163
+ ctx.signal?.throwIfAborted();
1164
+ if (owner.kind === 'owned-directory') {
1165
+ const root = installedRoot ?? owner.path;
1166
+ const index = paths.indexOf(root);
1167
+ if (scopeEvidence.sourceDigests[index] !== nativeDigest || after.sources[index]?.name === entry.layout.nativeIdentity.packageId)
1168
+ return false;
1169
+ const priorIndex = priorPaths.indexOf(root);
1170
+ const priorDigest = priorEvidence.sourceDigests[priorIndex];
1171
+ if (shadowedUser) {
1172
+ const hidden = shadowedUser.installedRoot;
1173
+ if (paths.includes(hidden) || await grokUserContentDigest(shadowedUser) !== shadowedUser.contentDigest)
1174
+ return false;
1175
+ if (priorIndex < 0) {
1176
+ if (grokSourceDigest(before, hidden, owner.identity.plugin, 'user') !== shadowedUser.nativeDigest)
1177
+ return false;
1178
+ retiredSources.add(hidden);
1179
+ publishedRoots.add(hidden);
1180
+ }
1181
+ }
1182
+ if (priorDigest !== nativeDigest) {
1183
+ if (priorDigest !== priorNativeDigest)
1184
+ return false;
1185
+ publishedRoots.add(root);
1186
+ if (orderAfter)
1187
+ orderChecks.push(orderAfter);
1188
+ // Restore the frozen source at its current position. Moving a
1189
+ // source or changing any other source still invalidates the plan.
1190
+ if (priorIndex < 0)
1191
+ addedSources.add(root);
1192
+ else {
1193
+ sources[index] = before.sources[priorIndex];
1194
+ sourceDigests[index] = priorDigest;
1195
+ }
1196
+ adjusted = true;
1197
+ }
1198
+ const marker = await readSkillOwnerMarker({ skillRoot: owner.path, allowedRoot: owner.allowedRoot,
1199
+ expectedIdentity: owner.identity }).catch(() => null);
1200
+ const observedContent = marker?.nativeProjection?.contentDigest === contentDigest
1201
+ ? await readPlatformPackageContentDigest(owner.path).catch(() => undefined) : undefined;
1202
+ if (observedContent !== contentDigest)
1203
+ return false;
1204
+ if (installedRoot) {
1205
+ try {
1206
+ await assertSafeFileMutationPath({ filePath: path.join(installedRoot, '.grok-plugin', 'plugin.json'),
1207
+ allowedRoot: publishedRoot, label: 'Grok installed package' });
1208
+ if (await readPlatformPackageContentDigest(installedRoot) !== contentDigest)
1209
+ return false;
1210
+ }
1211
+ catch {
1212
+ ctx.signal?.throwIfAborted();
1213
+ return false;
1214
+ }
1215
+ }
1216
+ }
1217
+ else {
1218
+ const matches = instructions.filter((row) => row.rulePath === owner.path);
1219
+ if (matches.length !== 1 || matches[0].digest !== nativeDigest)
1220
+ return false;
1221
+ const index = instructions.indexOf(matches[0]);
1222
+ const prior = priorEvidence.instructions.find((row) => row.rulePath === owner.path);
1223
+ if (prior?.digest !== nativeDigest) {
1224
+ if (prior?.digest !== priorNativeDigest)
1225
+ return false;
1226
+ instructions.splice(index, 1, ...(prior ? [prior] : []));
1227
+ adjusted = true;
1228
+ }
1229
+ // The written hash includes the exact owner header. Grok's size
1230
+ // and token count alone cannot detect a same-length external edit.
1231
+ try {
1232
+ await assertSafeFileMutationPath({ filePath: owner.path, allowedRoot: publishedRoot, label: 'Grok rule' });
1233
+ const bytes = await fs.readFile(owner.path);
1234
+ if (crypto.createHash('sha256').update(bytes).digest('hex') !== contentDigest)
1235
+ return false;
1236
+ }
1237
+ catch {
1238
+ ctx.signal?.throwIfAborted();
1239
+ return false;
1240
+ }
1241
+ }
1242
+ }
1243
+ ctx.signal?.throwIfAborted();
1244
+ if (!adjusted)
1245
+ return artifactValueDigest(current) === baselineDigest;
1246
+ for (const { sourceOrderAfter } of publications) {
1247
+ if (!sourceOrderAfter)
1248
+ continue;
1249
+ // Sources that remained visible since the Project publication keep their receipt order.
1250
+ if (artifactValueDigest(sourceOrderAfter.filter((root) => paths.includes(root)))
1251
+ !== artifactValueDigest(paths.filter((root) => sourceOrderAfter.includes(root))))
1252
+ return false;
1253
+ }
1254
+ // The reviewed order anchors surviving rows. Each publication's receipt
1255
+ // also anchors its new rows against later cross-package moves.
1256
+ for (const previous of orderChecks) {
1257
+ if (!matchesGrokComponentOrder(previous.hookOrder, scopeEvidence.hookOrder, publishedRoots)
1258
+ || !scopeEvidence.resourceOrder.every((order, index) => matchesGrokComponentOrder(previous.resourceOrder[index], order, publishedRoots)))
1259
+ return false;
1260
+ }
1261
+ const normalizedSources = { ...after, sources: sources.filter((_, index) => !addedSources.has(paths[index])),
1262
+ configurationEvidence: before.configurationEvidence, grokScopeEvidence: { ...scopeEvidence, instructions,
1263
+ hookOrder: priorEvidence.hookOrder, resourceOrder: priorEvidence.resourceOrder,
1264
+ sourceDigests: sourceDigests.filter((_, index) => !addedSources.has(paths[index])) } };
1265
+ const observation = { ...current.observation, prerequisites: { ...current.observation.prerequisites, nativeSources: normalizedSources } };
1266
+ const normalizedBefore = { ...before, sources: before.sources.filter((_, index) => !retiredSources.has(priorPaths[index])),
1267
+ grokScopeEvidence: { ...priorEvidence, sourceDigests: priorEvidence.sourceDigests.filter((_, index) => !retiredSources.has(priorPaths[index])) } };
1268
+ const baselineObservation = { ...mutableBaseline.observation, prerequisites: { ...mutableBaseline.observation.prerequisites,
1269
+ nativeSources: normalizedBefore } };
1270
+ return artifactValueDigest({ ...current, observation }) === artifactValueDigest({ ...mutableBaseline, observation: baselineObservation });
1271
+ };
1272
+ const check = async (discovery, batch) => {
1273
+ const reads = parallelNativeReads ? await Promise.allSettled([fingerprintParts(discovery), currentMutable(batch)]) : null;
1274
+ if (reads?.[0].status === 'rejected')
1275
+ throw reads[0].reason;
1276
+ const parts = reads?.[0].status === 'fulfilled' ? reads[0].value : await fingerprintParts(discovery);
1277
+ if (artifactValueDigest(parts) !== initial) {
1278
+ return artifactValueDigest(parts.discovery) !== artifactValueDigest(initialParts.discovery)
1279
+ ? 'clientDiscoveryChanged' : 'deploymentInputsChanged';
1280
+ }
1281
+ if (reads?.[1].status === 'rejected')
1282
+ throw reads[1].reason;
1283
+ const current = reads?.[1].status === 'fulfilled' ? reads[1].value : await currentMutable(batch);
1284
+ if (parallelNativeReads ? matchesMutable(current) : await matchesAfterGrokPublications(current))
1285
+ return true;
1286
+ if (current.references !== mutableBaseline.references)
1287
+ return 'deploymentReferencesChanged';
1288
+ if (artifactValueDigest(current.paths) !== artifactValueDigest(mutableBaseline.paths))
1289
+ return 'deploymentPathsChanged';
1290
+ return 'deploymentObservationChanged';
907
1291
  };
908
1292
  checks.set(entry.binding.id, (batch) => check(undefined, batch));
909
1293
  if (resolution.bindings.length === 1 && entry.binding.route === 'pi-package') {
@@ -913,7 +1297,7 @@ export class PlatformRebuildSession {
913
1297
  marketplaceRoot: entry.layout.marketplaceRoot, sourceId: entry.binding.plugin.sourceId,
914
1298
  sourceIdentity: entry.binding.plugin.sourceIdentity,
915
1299
  assertStable: async () => {
916
- if (!await checks.get(entry.binding.id)())
1300
+ if (await checks.get(entry.binding.id)() !== true)
917
1301
  throw new Error('operationPlanStale: deployment evidence changed before source registration.');
918
1302
  },
919
1303
  acceptMarketplaceRegistration: async () => {
@@ -973,6 +1357,7 @@ export class PlatformRebuildSession {
973
1357
  sharedReferences: await sharedReferences(this.context, entry.binding, preparationObservation, entry.layout),
974
1358
  nativeIdentity: preparationObservation.nativeIdentity ?? entry.layout.nativeIdentity,
975
1359
  contentMatches: projections.some((projection) => projection.bundle !== null)
1360
+ && (!antigravityProject || preparationObservation.ownership === 'aw')
976
1361
  && await readPlatformPackageContentDigest(entry.layout.packageRoot) === projections.find((projection) => projection.bundle !== null)?.bundle?.contentDigest };
977
1362
  if (entry.binding.platform === 'codex') {
978
1363
  const hostEntry = entry.binding.consumers.find((consumer) => consumer.entry?.kind === 'cli'
@@ -999,22 +1384,46 @@ export class PlatformRebuildSession {
999
1384
  evidence.userActivationEnabled = !['remove', 'cleanup'].includes(operation(plannedUser));
1000
1385
  }
1001
1386
  }
1002
- const expected = mergeExpectedComponentSets(units.map((unit) => unit.prepared.expected));
1003
- evidence.retainPackage = !removing && expected.unmet.length > 0 && inspected.components.some((slot) => 'path' in slot.component && slot.component.path === entry.layout.packageRoot && ['present', 'partial'].includes(slot.state));
1387
+ const priorPackage = inspected.components.find((slot) => 'path' in slot.component
1388
+ && slot.component.path === entry.layout.packageRoot && ['present', 'partial'].includes(slot.state))?.component;
1389
+ if (!removing && expected.unmet.length && priorPackage?.kind === 'owned-directory') {
1390
+ const complete = hasCompleteDeliveryDeclaration(expected);
1391
+ const old = await readSkillOwnerMarker({ skillRoot: priorPackage.path, allowedRoot: priorPackage.allowedRoot,
1392
+ expectedIdentity: priorPackage.identity }).catch(() => null);
1393
+ const next = new Set(projections.filter((item) => item.bundle).flatMap((item) => item.components.map(({ id }) => id)));
1394
+ const dropsPriorComponent = !old?.nativeProjection || old.nativeProjection.components.some(({ id }) => !next.has(id));
1395
+ const currentDigest = evidence.ownership.find((slot) => slot.component === priorPackage)?.contentDigest;
1396
+ // The marker identifies the directory. Only its recorded digest proves
1397
+ // that replacing or withdrawing the whole tree would discard exclusively AW bytes.
1398
+ const previousContentsVerified = !!old?.nativeProjection && old.nativeProjection.contentDigest === currentDigest;
1399
+ const hasNativeCopy = ['grok-cli', 'antigravity-cli'].includes(entry.binding.route) && preparationObservation.registration === 'present';
1400
+ const previousCopyUnconfirmed = hasNativeCopy && (!old?.nativeProjection
1401
+ || old.nativeProjection.contentDigest !== preparationObservation.nativePackageContentDigest);
1402
+ evidence.retainPackage = expected.unmet.some((gap) => !isDeliveryCapabilityGap(gap)) || previousCopyUnconfirmed
1403
+ || !evidence.contentMatches && (!previousContentsVerified || dropsPriorComponent
1404
+ && (!complete || evidence.sharedReferences !== 'none' || preparationObservation.ownership !== 'aw'));
1405
+ }
1004
1406
  if (!removing) {
1005
1407
  const inputEvidence = await createPlatformInputEvidence({ plugin: input.plugin, binding: entry.binding, units: units.map((unit) => unit.evidenceInput) });
1006
- inputDigests.set(entry.binding.id, platformPackageInputDigest(inputEvidence));
1007
- if (expected.unmet.length === 0) {
1008
- if (expected.components.length === 0) {
1009
- emptyStates.set(entry.binding.id, { ...inputEvidence, kind: 'aw-platform-empty-state', result: 'intentional-empty' });
1408
+ const packageComponents = projections.find((projection) => projection.bundle)?.components;
1409
+ inputDigests.set(entry.binding.id, platformPackageInputDigest(inputEvidence, packageComponents));
1410
+ if (expected.unmet.every(isDeliveryCapabilityGap)) {
1411
+ const permissionNotices = platformPermissionNotices(projections.flatMap(({ diagnostics }) => diagnostics));
1412
+ const noticeFields = permissionNotices.length ? { permissionNotices } : {};
1413
+ if (expected.unmet.length || expected.components.length && permissionNotices.length)
1414
+ gapStates.set(entry.binding.id, { ...inputEvidence,
1415
+ kind: 'aw-platform-empty-state', result: 'capability-gaps', gaps: expected.unmet,
1416
+ installedComponentIds: expected.components.map(({ id }) => id), ...noticeFields });
1417
+ if (expected.components.length === 0 && expected.unmet.length === 0) {
1418
+ emptyStates.set(entry.binding.id, { ...inputEvidence, kind: 'aw-platform-empty-state', result: 'intentional-empty', ...noticeFields });
1010
1419
  }
1011
1420
  else if (entry.layout.supplementRoot && input.plugin.manifest.artifacts) {
1012
1421
  const supplement = inputEvidence.units.find((unit) => unit.output === 'supplement');
1013
1422
  if (supplement) {
1014
1423
  supplementInputDigests.set(entry.binding.id, supplement.inputDigest);
1015
- if (entry.binding.route === 'codex-marketplace' && !projections.some((projection) => projection.bundle)) {
1016
- emptyStates.set(entry.binding.id, { ...inputEvidence, kind: 'aw-platform-empty-state', result: 'intentional-empty',
1017
- units: inputEvidence.units.filter((unit) => unit.output === 'package') });
1424
+ if (!expected.unmet.length && !projections.some((projection) => projection.bundle)) {
1425
+ emptyStates.set(entry.binding.id, { ...inputEvidence, kind: 'aw-platform-empty-state',
1426
+ result: 'intentional-empty-package', installedComponentIds: expected.components.map(({ id }) => id).sort(), ...noticeFields });
1018
1427
  }
1019
1428
  }
1020
1429
  }
@@ -1038,7 +1447,7 @@ export class PlatformRebuildSession {
1038
1447
  let frozenNativeTools;
1039
1448
  const verifyChecks = async (selected, batch) => {
1040
1449
  for (const check of selected)
1041
- if (!await check(batch))
1450
+ if (await check(batch) !== true)
1042
1451
  throw new Error('operationPlanStale: deployment evidence changed.');
1043
1452
  for (const plan of plans)
1044
1453
  if (!await this.verifyMarketplace(plan))
@@ -1057,7 +1466,7 @@ export class PlatformRebuildSession {
1057
1466
  && plan.effects.every((effect) => ['publish-package', 'register'].includes(effect.kind));
1058
1467
  const checkedBatch = this.context.batchInstallPlatform === plan.binding.platform && plan.binding.platform !== 'codex';
1059
1468
  return plan.operation === 'ensure' && (checkedBatch || ['copilot-marketplace', 'pi-package'].includes(plan.binding.route))
1060
- && plan.binding.platform === target.identity.platform && plan.expected.components.length > 0 && !plan.expected.unmet.length
1469
+ && plan.binding.platform === target.identity.platform && plan.expected.components.length > 0 && plan.expected.unmet.every(isDeliveryCapabilityGap)
1061
1470
  && driverState.before.package !== 'unknown' && (driverState.before.registration !== 'unknown' || hiddenEmptyPiProject)
1062
1471
  && ['absent', 'aw', 'shared'].includes(driverState.before.ownership)
1063
1472
  && plan.effects.every((effect) => ['publish-package', 'register', 'refresh', 'activate'].includes(effect.kind));
@@ -1146,6 +1555,11 @@ export class PlatformRebuildSession {
1146
1555
  : await readPlatformPackageContentDigest(plan.evidence.layout.packageRoot) !== bundle.contentDigest));
1147
1556
  const delivered = new Set(after.components.filter((component) => component.presence === 'present' && !component.reasonCodes.length)
1148
1557
  .map((component) => component.id));
1558
+ const roleIds = plan.expected.components.filter((component) => component.kind === 'agent' && delivered.has(component.id)
1559
+ && packageIds.has(component.id) && !packageIncomplete && !plan.evidence.retainPackage).map(({ id }) => id);
1560
+ const roleDiagnostic = piAgentConsumerDiagnostic(plan.binding, after, roleIds);
1561
+ if (roleDiagnostic)
1562
+ receipt.diagnostics.push(roleDiagnostic);
1149
1563
  const gaps = plan.expected.components.filter((component) => packageIncomplete && packageIds.has(component.id) || !delivered.has(component.id));
1150
1564
  if (bundle && !packageIncomplete && !plan.evidence.retainPackage) {
1151
1565
  for (const unitId of plan.binding.renderUnitIds) {
@@ -1164,12 +1578,19 @@ export class PlatformRebuildSession {
1164
1578
  && unit.unit.consumers.every(({ product, availability, entry }) => product === 'app'
1165
1579
  || product === 'cli' && availability === 'available' && entry?.kind === 'cli')
1166
1580
  ? adapter.capabilities({ ...capabilityInput, renderUnit: { ...unit.unit, consumers: cliReaders } }) : undefined;
1581
+ const antigravityReaders = plan.binding.platform === 'antigravity'
1582
+ ? unit.unit.consumers.flatMap((reader) => reader.availability === 'available' && reader.product !== 'generic'
1583
+ ? [{ id: reader.id, product: reader.product,
1584
+ unsupported: getAntigravityUnsupportedSkillControls(capabilityInput.profile, plan.binding.scope.kind, reader) }]
1585
+ : []) : [];
1167
1586
  for (const skill of unit.finalized.skills) {
1168
1587
  if (!packageIds.has(skill.componentId) || !delivered.has(skill.componentId))
1169
1588
  continue;
1170
1589
  const component = unit.prepared.expected.components.find((item) => item.id === skill.componentId);
1171
1590
  const requested = getComponentFeatureRequirements(component, { skillText: skill.tree.files['SKILL.md'].toString('utf8') });
1172
- const warning = skillInvocationWarning(component.name, requested, { pluginId: plan.binding.plugin.pluginId, target: plan.binding.platform, scope: plan.binding.scope.kind }, capabilities, codexCliCapabilities);
1591
+ const warning = skillInvocationWarning(component.name, requested, { pluginId: plan.binding.plugin.pluginId, target: plan.binding.platform, scope: plan.binding.scope.kind }, capabilities, codexCliCapabilities, antigravityReaders.map((reader) => ({ ...reader,
1592
+ observed: after.skillInvocationPolicies?.find(({ componentId, productId }) => componentId === component.id
1593
+ && productId === reader.id)?.features })));
1173
1594
  if (warning)
1174
1595
  receipt.diagnostics.push(warning);
1175
1596
  }
@@ -1179,14 +1600,19 @@ export class PlatformRebuildSession {
1179
1600
  continue;
1180
1601
  const inputDigest = supplementInputDigests.get(plan.binding.id);
1181
1602
  if (inputDigest && [...supplementIds].every((id) => delivered.has(id))
1182
- && !receipt.unmet.length && !receipt.diagnostics.some((diagnostic) => diagnostic.severity === 'error')) {
1603
+ && receipt.unmet.every(isDeliveryCapabilityGap) && !receipt.diagnostics.some((diagnostic) => diagnostic.severity === 'error')) {
1183
1604
  try {
1184
1605
  await writePlatformSupplementState(ctx, plan.binding, inputDigest, supplementFiles.map((file) => ({
1185
1606
  id: file.id, fileName: path.basename(file.destination), contentDigest: file.contentDigest,
1186
1607
  })));
1187
1608
  const emptyPackage = emptyStates.get(plan.binding.id);
1188
- if (!gaps.length && emptyPackage && after.package === 'absent' && after.registration === 'absent') {
1609
+ if (!gaps.length && emptyPackage?.result === 'intentional-empty-package'
1610
+ && supplementIds.size === emptyPackage.installedComponentIds.length
1611
+ && emptyPackage.installedComponentIds.every((id) => supplementIds.has(id))
1612
+ && after.package === 'absent' && ['absent', 'not-applicable'].includes(after.registration)) {
1613
+ // The package absence and permission notices describe the same binding.
1189
1614
  await writePlatformEmptyState({ state: emptyPackage, env: this.context.env });
1615
+ continue;
1190
1616
  }
1191
1617
  }
1192
1618
  catch {
@@ -1196,8 +1622,19 @@ export class PlatformRebuildSession {
1196
1622
  subject: { target: plan.binding.platform, pluginId: plan.binding.plugin.pluginId, scope: plan.binding.scope.kind } });
1197
1623
  }
1198
1624
  }
1199
- if (!gaps.length)
1625
+ if (!gaps.length) {
1626
+ const gapState = gapStates.get(plan.binding.id);
1627
+ if (gapState && !receipt.diagnostics.some((entry) => entry.severity === 'error')) {
1628
+ if (gapState.result === 'capability-gaps' && !gapState.gaps.length) {
1629
+ // A notice alone is optional status evidence. Failure to retain it does not undo verified delivery.
1630
+ await writePlatformEmptyState({ state: gapState, env: this.context.env }).catch(() => ctx.signal?.throwIfAborted());
1631
+ }
1632
+ else {
1633
+ await writePlatformEmptyState({ state: gapState, env: this.context.env });
1634
+ }
1635
+ }
1200
1636
  continue;
1637
+ }
1201
1638
  incomplete = true;
1202
1639
  const code = plan.binding.route === 'grok-directory' && requiredActivation === 'blocked' ? 'grokProjectAuthorizationDenied'
1203
1640
  : plan.binding.route === 'codex-marketplace' && requireIndependentActivation && after.scopeActivation === 'unknown'
@@ -1235,7 +1672,7 @@ export class PlatformRebuildSession {
1235
1672
  const supplementFiles = componentSupplementFiles(prepared.plan);
1236
1673
  const writtenFiles = new Map();
1237
1674
  const commandPreparationFailed = prepared.plan.binding.renderUnitIds.some((unitId) => preparedUnits.get(unitId)?.finalized.producerResolutions
1238
- .some((resolution) => resolution.state === 'failed' || resolution.state === 'unmet'));
1675
+ .some((resolution) => resolution.state === 'failed'));
1239
1676
  let receipt;
1240
1677
  const peers = prepared.plan.binding.route === 'codex-marketplace' ? [...this.mutableChecks.values()].filter((check) => check.physicalKey !== prepared.plan.binding.physicalKey && check.marketplaceRoot === prepared.plan.evidence.layout.marketplaceRoot
1241
1678
  && check.sourceId === prepared.plan.binding.plugin.sourceId && check.sourceIdentity === prepared.plan.binding.plugin.sourceIdentity) : [];
@@ -1258,7 +1695,12 @@ export class PlatformRebuildSession {
1258
1695
  verifyEvidence: async (plan) => {
1259
1696
  const verified = verifiedPlan === plan;
1260
1697
  verifiedPlan = undefined;
1261
- return verified || await checks.get(plan.binding.id)() && await this.verifyMarketplace(plan);
1698
+ if (verified)
1699
+ return true;
1700
+ const evidence = await checks.get(plan.binding.id)();
1701
+ if (evidence !== true)
1702
+ return evidence;
1703
+ return await this.verifyMarketplace(plan) || 'marketplaceChanged';
1262
1704
  },
1263
1705
  publishPackage: async (_binding, bundle, _destination, component) => {
1264
1706
  if (!('path' in component) || component.path !== _destination)
@@ -1269,7 +1711,8 @@ export class PlatformRebuildSession {
1269
1711
  publication = publishDirectory(bundle.stagingRoot, component, {
1270
1712
  components: prepared.plan.projections.filter((projection) => projection.bundle !== null).flatMap((projection) => projection.components),
1271
1713
  inputDigest: inputDigests.get(prepared.plan.binding.id), contentDigest: bundle.contentDigest,
1272
- preparation: prepared.plan.expected.unmet.length || commandPreparationFailed ? 'partial' : 'complete',
1714
+ ...(bundle.piExtensionDigest ? { piExtensionDigest: bundle.piExtensionDigest } : {}),
1715
+ preparation: prepared.plan.expected.unmet.some((gap) => !isDeliveryCapabilityGap(gap)) || commandPreparationFailed ? 'partial' : 'complete',
1273
1716
  physicalIdentity: (await getDeploymentLayout(ctx, prepared.plan.binding)).physicalIdentity,
1274
1717
  }, stagedPackage);
1275
1718
  this.published.set(prepared.plan.binding.physicalKey, publication);
@@ -1308,7 +1751,17 @@ export class PlatformRebuildSession {
1308
1751
  throw new Error('platformContributionUnsupported');
1309
1752
  return { mutation: 'confirmed', changed: true };
1310
1753
  },
1311
- removeOwned: async (_binding, component) => {
1754
+ removeOwned: async (binding, component) => {
1755
+ if (isAntigravityProjectDirectory(binding) && component.kind === 'owned-directory'
1756
+ && component.path !== prepared.plan.evidence.layout.packageRoot && prepared.driverState.bundle) {
1757
+ const replacement = prepared.driverState.packageComponent;
1758
+ if (replacement?.kind !== 'owned-directory' || await requireWritable(replacement, this.ownership) !== 'present'
1759
+ || await readPlatformPackageContentDigest(replacement.path) !== prepared.driverState.bundle.contentDigest) {
1760
+ throw Object.assign(new Error('The Antigravity replacement package could not be verified.'), {
1761
+ code: 'operationPlanStale', mutation: 'none',
1762
+ });
1763
+ }
1764
+ }
1312
1765
  const result = await cleanupOwnedComponents({ components: [component], executor: this.ownership });
1313
1766
  cleanupResults.push(result);
1314
1767
  if (result.failures.length || result.residual.length || result.quarantined.length) {
@@ -1327,7 +1780,8 @@ export class PlatformRebuildSession {
1327
1780
  id: effect.id, status: 'unknown', mutation: 'possible', diagnostics: [diagnostic]
1328
1781
  })),
1329
1782
  after: await adapter.inspect(ctx, prepared.plan.binding).catch(() => prepared.driverState.before),
1330
- unmet: [], reload: 'unknown', diagnostics: [diagnostic] };
1783
+ unmet: prepared.plan.expected.unmet.map((gap) => ({ ...gap, productIds: prepared.plan.binding.consumers.map(({ id }) => id) })),
1784
+ reload: 'unknown', diagnostics: [diagnostic] };
1331
1785
  }
1332
1786
  receipts.push(receipt);
1333
1787
  if (receipt.diagnostics.some(({ code }) => code === 'processCleanupUnconfirmed'))
@@ -1376,6 +1830,15 @@ export class PlatformRebuildSession {
1376
1830
  if (prepared.plan.evidence.retainPackage || receipt.diagnostics.some((diagnostic) => diagnostic.code === 'operationPlanStale')
1377
1831
  || receipt.effects.some((effect) => ['failed', 'unknown', 'blocked', 'skipped'].includes(effect.status)))
1378
1832
  continue;
1833
+ this.recordGrokWrites(prepared, receipt, publication?.mutation === 'confirmed', writtenFiles, shadowedUsers.get(prepared.plan.binding.id));
1834
+ const piInventoryKey = piProjectInventoryKey(prepared.plan.binding, prepared.plan.evidence.layout.activationPath);
1835
+ if (piInventoryKey && piProjectEmptyDeliveryObserved(prepared.plan.binding, prepared.driverState.before)
1836
+ && receipt.after.registration === 'present' && receipt.after.ownership === 'aw' && receipt.after.configuration?.activation === 'enabled'
1837
+ && prepared.plan.effects.some((effect) => effect.kind === 'register' && receipt.effects.some((result) => result.id === effect.id && result.status === 'applied' && result.mutation === 'confirmed'))) {
1838
+ const registered = this.piProjectRegisteredRoots.get(piInventoryKey) ?? new Set();
1839
+ registered.add(prepared.plan.evidence.layout.packageRoot);
1840
+ this.piProjectRegisteredRoots.set(piInventoryKey, registered);
1841
+ }
1379
1842
  try {
1380
1843
  const candidates = [...preparedUnits.values()].flatMap((unit) => unit.finalized.commandCandidates)
1381
1844
  .filter((candidate) => candidate.producer.kind !== 'package' && candidate.producer.placementKey === prepared.plan.binding.physicalKey);
@@ -1395,10 +1858,12 @@ export class PlatformRebuildSession {
1395
1858
  && !receipt.diagnostics.some((diagnostic) => diagnostic.severity === 'error')
1396
1859
  && packageDeliveryConfirmed(prepared.plan.binding, receipt.after, bundle.contentDigest, requireIndependentActivation)
1397
1860
  && await readPlatformPackageContentDigest(root) === bundle.contentDigest) {
1861
+ const marker = await readSkillOwnerMarker({ skillRoot: root, allowedRoot: packageOwner.allowedRoot, expectedIdentity: packageOwner.identity });
1398
1862
  const projection = { components: mappings, contentDigest: bundle.contentDigest,
1399
- inputDigest: inputDigests.get(prepared.plan.binding.id), preparation: prepared.plan.expected.unmet.length || commandPreparationFailed ? 'partial' : 'complete',
1863
+ inputDigest: inputDigests.get(prepared.plan.binding.id), preparation: prepared.plan.expected.unmet.some((gap) => !isDeliveryCapabilityGap(gap)) || commandPreparationFailed ? 'partial' : 'complete',
1864
+ ...(bundle.piExtensionDigest && marker?.nativeProjection?.piExtensionDigest === bundle.piExtensionDigest
1865
+ ? { piExtensionDigest: bundle.piExtensionDigest } : {}),
1400
1866
  physicalIdentity: (await getDeploymentLayout(ctx, prepared.plan.binding)).physicalIdentity };
1401
- const marker = await readSkillOwnerMarker({ skillRoot: root, allowedRoot: packageOwner.allowedRoot, expectedIdentity: packageOwner.identity });
1402
1867
  if (marker && (!marker.nativeProjection || artifactValueDigest(marker.nativeProjection) !== artifactValueDigest(projection))) {
1403
1868
  await writeSkillOwnerMarker({ skillRoot: root, allowedRoot: packageOwner.allowedRoot, identity: packageOwner.identity, nativeProjection: projection });
1404
1869
  for (const check of this.mutableChecks.values())
@@ -1416,7 +1881,7 @@ export class PlatformRebuildSession {
1416
1881
  await revokeManagedCommandBindings(producer, this.context.env);
1417
1882
  }
1418
1883
  }
1419
- const emptyState = emptyStates.get(prepared.plan.binding.id);
1884
+ const emptyState = gapStates.get(prepared.plan.binding.id) ?? emptyStates.get(prepared.plan.binding.id);
1420
1885
  const removedByCommand = piProjectRemovalConfirmed(prepared.plan, receipt);
1421
1886
  const inactiveScope = removedByCommand || receipt.after.registration === 'absent'
1422
1887
  || receipt.after.package === 'absent' && receipt.after.registration === 'not-applicable'
@@ -1425,16 +1890,25 @@ export class PlatformRebuildSession {
1425
1890
  && ['codex-marketplace', 'copilot-marketplace'].includes(prepared.plan.binding.route)
1426
1891
  && receipt.after.configuration?.activation === 'absent'
1427
1892
  || receipt.after.consumers.every((consumer) => ['disabled', 'not-applicable'].includes(consumer.activation));
1428
- if (emptyState && !prepared.plan.expected.components.length && !receipt.unmet.length
1429
- && !receipt.diagnostics.some((diagnostic) => diagnostic.severity === 'error')
1430
- && (receipt.after.registration !== 'unknown' || removedByCommand) && receipt.after.package !== 'unknown'
1431
- && !['foreign', 'unknown'].includes(receipt.after.ownership)
1432
- && inactiveScope) {
1893
+ if (emptyState && !prepared.plan.expected.components.length && receipt.unmet.every(isDeliveryCapabilityGap)
1894
+ && !receipt.diagnostics.some((diagnostic) => diagnostic.severity === 'error')) {
1433
1895
  const residual = await inspectOwnedComponents({ components: prepared.plan.evidence.ownership
1434
- .filter((slot) => !('path' in slot.component) || slot.component.path !== prepared.plan.evidence.layout.packageRoot)
1896
+ .filter((slot) => !('path' in slot.component) || slot.component.path !== root)
1435
1897
  .map((slot) => slot.component), executor: this.ownership });
1436
- if (residual.components.every((component) => component.state === 'absent'))
1898
+ const hiddenEmptyPi = emptyState.result === 'capability-gaps' && piProjectEmptyDeliveryObserved(prepared.plan.binding, receipt.after);
1899
+ const clear = (receipt.after.registration !== 'unknown' || removedByCommand || hiddenEmptyPi)
1900
+ && (emptyState.result !== 'capability-gaps' || prepared.plan.binding.route !== 'pi-package' || receipt.after.configuration?.activation === 'absent')
1901
+ && receipt.after.package !== 'unknown' && !['foreign', 'unknown'].includes(receipt.after.ownership)
1902
+ && (inactiveScope || hiddenEmptyPi)
1903
+ && (emptyState.result === 'intentional-empty' || receipt.after.package === 'absent')
1904
+ && residual.components.every((slot) => slot.state === 'absent');
1905
+ if (clear)
1437
1906
  await writePlatformEmptyState({ state: emptyState, env: this.context.env });
1907
+ else if (emptyState.result === 'capability-gaps')
1908
+ receipt.diagnostics.push({ code: 'previousDeploymentRetained', severity: 'error',
1909
+ message: 'Previous output or registration could not be confirmed absent. Check the scoped deployment before retrying.',
1910
+ subject: { target: prepared.plan.binding.platform, pluginId: prepared.plan.binding.plugin.pluginId, scope: prepared.plan.binding.scope.kind },
1911
+ detail: { reasonCode: 'previousDeploymentRetained', path: root } });
1438
1912
  }
1439
1913
  }
1440
1914
  catch (error) {