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

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 (233) hide show
  1. package/dist/authoring/assets/command-runtime-config.d.mts +9 -0
  2. package/dist/authoring/assets/command-runtime-config.mjs +106 -0
  3. package/dist/authoring/assets/command-runtime-config.mjs.map +1 -0
  4. package/dist/authoring/scripts/validate-plugin.mjs +17 -22
  5. package/dist/authoring/scripts/validate-plugin.mjs.map +1 -1
  6. package/dist/scripts/aw-skill-eval-materializer.d.ts +4 -0
  7. package/dist/scripts/aw-skill-eval-materializer.js +27 -0
  8. package/dist/scripts/aw-skill-eval-materializer.js.map +1 -1
  9. package/dist/scripts/bundle-plugins.js +1 -1
  10. package/dist/scripts/bundle-plugins.js.map +1 -1
  11. package/dist/scripts/test-plugin-scripts.js +13 -2
  12. package/dist/scripts/test-plugin-scripts.js.map +1 -1
  13. package/dist/src/commands/aw-capabilities.d.ts +1 -1
  14. package/dist/src/commands/aw-capabilities.js +2 -2
  15. package/dist/src/commands/catalog-source.d.ts +2 -1
  16. package/dist/src/commands/catalog-source.js +8 -7
  17. package/dist/src/commands/catalog-source.js.map +1 -1
  18. package/dist/src/commands/deployment-confirmation.d.ts +8 -1
  19. package/dist/src/commands/deployment-confirmation.js +79 -11
  20. package/dist/src/commands/deployment-confirmation.js.map +1 -1
  21. package/dist/src/commands/lifecycle-command-package.d.ts +44 -0
  22. package/dist/src/commands/lifecycle-command-package.js +195 -0
  23. package/dist/src/commands/lifecycle-command-package.js.map +1 -0
  24. package/dist/src/commands/managed-commands.d.ts +6 -0
  25. package/dist/src/commands/managed-commands.js +203 -152
  26. package/dist/src/commands/managed-commands.js.map +1 -1
  27. package/dist/src/commands/operation-plan.d.ts +22 -21
  28. package/dist/src/commands/operation-plan.js +2 -5
  29. package/dist/src/commands/operation-plan.js.map +1 -1
  30. package/dist/src/commands/permission-batch.d.ts +5 -0
  31. package/dist/src/commands/permission-batch.js +80 -0
  32. package/dist/src/commands/permission-batch.js.map +1 -0
  33. package/dist/src/commands/plugin-capabilities.js +17 -13
  34. package/dist/src/commands/plugin-capabilities.js.map +1 -1
  35. package/dist/src/commands/public-config-confirmation.d.ts +8 -2
  36. package/dist/src/commands/public-config-confirmation.js +22 -5
  37. package/dist/src/commands/public-config-confirmation.js.map +1 -1
  38. package/dist/src/commands/public-lifecycle-result.d.ts +4 -4
  39. package/dist/src/commands/public-lifecycle-result.js +55 -14
  40. package/dist/src/commands/public-lifecycle-result.js.map +1 -1
  41. package/dist/src/commands/public-lifecycle.js +49 -8
  42. package/dist/src/commands/public-lifecycle.js.map +1 -1
  43. package/dist/src/commands/rebuild-command.d.ts +4 -0
  44. package/dist/src/commands/rebuild-command.js +160 -101
  45. package/dist/src/commands/rebuild-command.js.map +1 -1
  46. package/dist/src/commands/rebuild-integration.d.ts +17 -6
  47. package/dist/src/commands/rebuild-integration.js +76 -183
  48. package/dist/src/commands/rebuild-integration.js.map +1 -1
  49. package/dist/src/commands/rebuild-operations.d.ts +2 -1
  50. package/dist/src/commands/rebuild-operations.js +2 -0
  51. package/dist/src/commands/rebuild-operations.js.map +1 -1
  52. package/dist/src/commands/rebuild-platform-integration.d.ts +5 -3
  53. package/dist/src/commands/rebuild-platform-integration.js +166 -135
  54. package/dist/src/commands/rebuild-platform-integration.js.map +1 -1
  55. package/dist/src/commands/skill-eval.js +10 -1
  56. package/dist/src/commands/skill-eval.js.map +1 -1
  57. package/dist/src/generators/local-plugin.js +14 -15
  58. package/dist/src/generators/local-plugin.js.map +1 -1
  59. package/dist/src/generators/permissions.d.ts +14 -6
  60. package/dist/src/generators/permissions.js +59 -61
  61. package/dist/src/generators/permissions.js.map +1 -1
  62. package/dist/src/index.js +77 -40
  63. package/dist/src/index.js.map +1 -1
  64. package/dist/src/output/command-receipt.js +7 -8
  65. package/dist/src/output/command-receipt.js.map +1 -1
  66. package/dist/src/output/component-delivery.d.ts +7 -0
  67. package/dist/src/output/component-delivery.js +59 -3
  68. package/dist/src/output/component-delivery.js.map +1 -1
  69. package/dist/src/output/public-result.d.ts +15 -0
  70. package/dist/src/output/public-result.js +75 -12
  71. package/dist/src/output/public-result.js.map +1 -1
  72. package/dist/src/output/rebuild-progress.js +7 -4
  73. package/dist/src/output/rebuild-progress.js.map +1 -1
  74. package/dist/src/output/receipt-projection.js +39 -27
  75. package/dist/src/output/receipt-projection.js.map +1 -1
  76. package/dist/src/platforms/antigravity-permissions.d.ts +50 -0
  77. package/dist/src/platforms/antigravity-permissions.js +388 -0
  78. package/dist/src/platforms/antigravity-permissions.js.map +1 -0
  79. package/dist/src/platforms/contracts.d.ts +10 -1
  80. package/dist/src/platforms/discovery.d.ts +2 -0
  81. package/dist/src/platforms/discovery.js.map +1 -1
  82. package/dist/src/platforms/grok-permission-config.d.ts +22 -0
  83. package/dist/src/platforms/grok-permission-config.js +184 -0
  84. package/dist/src/platforms/grok-permission-config.js.map +1 -0
  85. package/dist/src/platforms/grok-permission-document.d.ts +4 -0
  86. package/dist/src/platforms/grok-permission-document.js +145 -0
  87. package/dist/src/platforms/grok-permission-document.js.map +1 -0
  88. package/dist/src/platforms/grok-permissions.d.ts +17 -0
  89. package/dist/src/platforms/grok-permissions.js +311 -0
  90. package/dist/src/platforms/grok-permissions.js.map +1 -0
  91. package/dist/src/platforms/host-permission-policy.d.ts +38 -0
  92. package/dist/src/platforms/host-permission-policy.js +86 -0
  93. package/dist/src/platforms/host-permission-policy.js.map +1 -0
  94. package/dist/src/platforms/inspection-grok.js +47 -5
  95. package/dist/src/platforms/inspection-grok.js.map +1 -1
  96. package/dist/src/platforms/layout.d.ts +8 -0
  97. package/dist/src/platforms/layout.js +53 -8
  98. package/dist/src/platforms/layout.js.map +1 -1
  99. package/dist/src/platforms/lifecycle.js +39 -17
  100. package/dist/src/platforms/lifecycle.js.map +1 -1
  101. package/dist/src/platforms/opencode-permission-config.d.ts +13 -0
  102. package/dist/src/platforms/opencode-permission-config.js +253 -0
  103. package/dist/src/platforms/opencode-permission-config.js.map +1 -0
  104. package/dist/src/platforms/opencode-permissions.d.ts +39 -0
  105. package/dist/src/platforms/opencode-permissions.js +212 -0
  106. package/dist/src/platforms/opencode-permissions.js.map +1 -0
  107. package/dist/src/platforms/opencode-related-permissions.d.ts +40 -0
  108. package/dist/src/platforms/opencode-related-permissions.js +177 -0
  109. package/dist/src/platforms/opencode-related-permissions.js.map +1 -0
  110. package/dist/src/platforms/permission-ownership.d.ts +89 -0
  111. package/dist/src/platforms/permission-ownership.js +543 -0
  112. package/dist/src/platforms/permission-ownership.js.map +1 -0
  113. package/dist/src/platforms/permission-sidecar.d.ts +70 -0
  114. package/dist/src/platforms/permission-sidecar.js +215 -0
  115. package/dist/src/platforms/permission-sidecar.js.map +1 -0
  116. package/dist/src/platforms/projection.js +58 -8
  117. package/dist/src/platforms/projection.js.map +1 -1
  118. package/dist/src/recovery/coordinator.d.ts +2 -0
  119. package/dist/src/recovery/coordinator.js +24 -27
  120. package/dist/src/recovery/coordinator.js.map +1 -1
  121. package/dist/src/recovery/joint-coordinator.js +103 -47
  122. package/dist/src/recovery/joint-coordinator.js.map +1 -1
  123. package/dist/src/recovery/joint-demand.js +1 -1
  124. package/dist/src/recovery/joint-demand.js.map +1 -1
  125. package/dist/src/recovery/joint-install-execution.js +2 -1
  126. package/dist/src/recovery/joint-install-execution.js.map +1 -1
  127. package/dist/src/recovery/retirement.js +11 -17
  128. package/dist/src/recovery/retirement.js.map +1 -1
  129. package/dist/src/recovery/status.js +32 -2
  130. package/dist/src/recovery/status.js.map +1 -1
  131. package/dist/src/review/eval-source-input.d.ts +1 -0
  132. package/dist/src/review/eval-source-input.js +7 -1
  133. package/dist/src/review/eval-source-input.js.map +1 -1
  134. package/dist/src/review/review-selection.js +12 -5
  135. package/dist/src/review/review-selection.js.map +1 -1
  136. package/dist/src/review/skill-materialization.d.ts +1 -1
  137. package/dist/src/review/skill-materialization.js +3 -7
  138. package/dist/src/review/skill-materialization.js.map +1 -1
  139. package/dist/src/tui/console-app-v4.js +37 -30
  140. package/dist/src/tui/console-app-v4.js.map +1 -1
  141. package/dist/src/tui/controller-runtime.js +71 -6
  142. package/dist/src/tui/controller-runtime.js.map +1 -1
  143. package/dist/src/tui/controller.d.ts +4 -1
  144. package/dist/src/tui/controller.js.map +1 -1
  145. package/dist/src/tui/deployment-view.d.ts +1 -1
  146. package/dist/src/tui/deployment-view.js +16 -3
  147. package/dist/src/tui/deployment-view.js.map +1 -1
  148. package/dist/src/tui/diagnostic-projection.js +11 -6
  149. package/dist/src/tui/diagnostic-projection.js.map +1 -1
  150. package/dist/src/tui/entity-cards.js +1 -1
  151. package/dist/src/tui/entity-cards.js.map +1 -1
  152. package/dist/src/tui/operation-review-planner.js +130 -70
  153. package/dist/src/tui/operation-review-planner.js.map +1 -1
  154. package/dist/src/types.d.ts +8 -20
  155. package/dist/src/types.js.map +1 -1
  156. package/dist/src/utils/artifact-plan.d.ts +3 -36
  157. package/dist/src/utils/artifact-plan.js +11 -77
  158. package/dist/src/utils/artifact-plan.js.map +1 -1
  159. package/dist/src/utils/artifact-renderer.d.ts +0 -59
  160. package/dist/src/utils/artifact-renderer.js +2 -49
  161. package/dist/src/utils/artifact-renderer.js.map +1 -1
  162. package/dist/src/utils/artifact-request.d.ts +3 -26
  163. package/dist/src/utils/artifact-request.js +13 -36
  164. package/dist/src/utils/artifact-request.js.map +1 -1
  165. package/dist/src/utils/artifact-sources.d.ts +0 -8
  166. package/dist/src/utils/artifact-sources.js +0 -8
  167. package/dist/src/utils/artifact-sources.js.map +1 -1
  168. package/dist/src/utils/bundle-layout.js +2 -7
  169. package/dist/src/utils/bundle-layout.js.map +1 -1
  170. package/dist/src/utils/catalog-source-references.js +10 -0
  171. package/dist/src/utils/catalog-source-references.js.map +1 -1
  172. package/dist/src/utils/component-command-preparation.d.ts +6 -11
  173. package/dist/src/utils/component-command-preparation.js +109 -228
  174. package/dist/src/utils/component-command-preparation.js.map +1 -1
  175. package/dist/src/utils/managed-command-cli-review.d.ts +43 -0
  176. package/dist/src/utils/managed-command-cli-review.js +389 -0
  177. package/dist/src/utils/managed-command-cli-review.js.map +1 -0
  178. package/dist/src/utils/managed-command-closure.d.ts +14 -3
  179. package/dist/src/utils/managed-command-closure.js +144 -23
  180. package/dist/src/utils/managed-command-closure.js.map +1 -1
  181. package/dist/src/utils/managed-command-errors.d.ts +5 -0
  182. package/dist/src/utils/managed-command-errors.js +10 -0
  183. package/dist/src/utils/managed-command-errors.js.map +1 -0
  184. package/dist/src/utils/managed-command-materialization.d.ts +77 -113
  185. package/dist/src/utils/managed-command-materialization.js +324 -323
  186. package/dist/src/utils/managed-command-materialization.js.map +1 -1
  187. package/dist/src/utils/managed-command-preparation.d.ts +28 -65
  188. package/dist/src/utils/managed-command-preparation.js +33 -140
  189. package/dist/src/utils/managed-command-preparation.js.map +1 -1
  190. package/dist/src/utils/managed-command-review.d.ts +11 -4
  191. package/dist/src/utils/managed-command-review.js +33 -21
  192. package/dist/src/utils/managed-command-review.js.map +1 -1
  193. package/dist/src/utils/managed-command-runtime.d.ts +1 -0
  194. package/dist/src/utils/managed-command-runtime.js +6 -3
  195. package/dist/src/utils/managed-command-runtime.js.map +1 -1
  196. package/dist/src/utils/managed-command-snapshots.d.ts +17 -0
  197. package/dist/src/utils/managed-command-snapshots.js +84 -0
  198. package/dist/src/utils/managed-command-snapshots.js.map +1 -0
  199. package/dist/src/utils/managed-command-store.d.ts +65 -78
  200. package/dist/src/utils/managed-command-store.js +446 -383
  201. package/dist/src/utils/managed-command-store.js.map +1 -1
  202. package/dist/src/utils/multi-source-catalog.d.ts +2 -0
  203. package/dist/src/utils/multi-source-catalog.js +3 -1
  204. package/dist/src/utils/multi-source-catalog.js.map +1 -1
  205. package/dist/src/utils/native-tool-context.d.ts +6 -3
  206. package/dist/src/utils/native-tool-context.js +3 -1
  207. package/dist/src/utils/native-tool-context.js.map +1 -1
  208. package/dist/src/utils/native-tool-review.d.ts +2 -12
  209. package/dist/src/utils/native-tool-review.js +6 -108
  210. package/dist/src/utils/native-tool-review.js.map +1 -1
  211. package/dist/src/utils/ownership.d.ts +7 -0
  212. package/dist/src/utils/ownership.js.map +1 -1
  213. package/dist/src/utils/platform-empty-state.d.ts +2 -1
  214. package/dist/src/utils/platform-empty-state.js +13 -12
  215. package/dist/src/utils/platform-empty-state.js.map +1 -1
  216. package/dist/src/utils/plugin-config-command-apply.d.ts +33 -0
  217. package/dist/src/utils/plugin-config-command-apply.js +134 -0
  218. package/dist/src/utils/plugin-config-command-apply.js.map +1 -0
  219. package/dist/src/utils/plugin-config-impact.d.ts +19 -9
  220. package/dist/src/utils/plugin-config-impact.js +56 -37
  221. package/dist/src/utils/plugin-config-impact.js.map +1 -1
  222. package/dist/src/utils/plugin-config-write.d.ts +19 -19
  223. package/dist/src/utils/plugin-config-write.js +194 -772
  224. package/dist/src/utils/plugin-config-write.js.map +1 -1
  225. package/dist/src/utils/rendered-contract.js +12 -6
  226. package/dist/src/utils/rendered-contract.js.map +1 -1
  227. package/package.json +4 -3
  228. package/dist/src/platforms/managed-command-placement.d.ts +0 -8
  229. package/dist/src/platforms/managed-command-placement.js +0 -79
  230. package/dist/src/platforms/managed-command-placement.js.map +0 -1
  231. package/dist/src/utils/managed-command-evidence.d.ts +0 -7
  232. package/dist/src/utils/managed-command-evidence.js +0 -10
  233. package/dist/src/utils/managed-command-evidence.js.map +0 -1
@@ -1,369 +1,370 @@
1
1
  import os from 'node:os';
2
2
  import path from 'node:path';
3
3
  import fs from 'fs-extra';
4
- import { getCommandPackageId, canonicalizeIdentityValue, getNativeToolConsumerClosure, loadPluginNativeToolClosure, materializeNativeToolClosureFiles, getManagedCommandArtifactTargets, getPluginCommandId, normalizeProducerIdentity, normalizeCommandRelativeFile, replaceManagedCommandPlaceholders, validateCommandEntryFiles, } from '@lesliechan721/aw-plugin-core/manifest';
5
- import { resolveArtifactRenderConfig, runArtifactRenderer } from './artifact-renderer.js';
6
- import { resolveCommandSourceDirectory } from './artifact-sources.js';
7
- import { inspectManagedCommand, listManagedCommandPackages, listManagedCommands, managedCommandDiagnostic, ManagedCommandError, readInstalledCommandProducer, syncManagedCommandPackage, validateManagedCommandResource, } from './managed-command-store.js';
8
- import { resolveCanonicalRepoProjectKey } from './state-paths.js';
9
- import { validateManagedCommandPackageClosure } from './managed-command-closure.js';
10
- import { isSkillAuthorOnlyPath } from './skill-authoring.js';
11
- import { recoveryInterruptionCode } from '../recovery/interruption.js';
12
- import { readSafeOperationError } from './safe-operation-diagnostic.js';
13
- import { AW_RUNTIME_CONFIG_BINDING_PATH, AW_RUNTIME_CONFIG_READER_PATH, AW_RUNTIME_NATIVE_RECEIPT_PATH } from '@lesliechan721/aw-plugin-core';
14
- export async function discoverRetainedManagedCommandPackages(options) {
15
- const listed = await listManagedCommandPackages(options.env).catch(() => ({ packages: [], errors: [] }));
16
- const selected = listed.packages.filter(({ producer }) => options.all === true || options.selectors.some((selector) => selector.pluginName === producer.pluginName && selector.sourceId === producer.sourceId));
17
- let projectRoot;
18
- if (options.scope === 'project' && selected.some(({ producer }) => producer.scope === 'project')) {
19
- projectRoot = path.normalize(await fs.realpath(await resolveCanonicalRepoProjectKey(options.cwd)));
20
- if (process.platform === 'win32')
21
- projectRoot = projectRoot.replace(/^[a-z]:/u, (drive) => drive.toUpperCase());
4
+ import { canonicalizeIdentityValue, getCommandPackageId, getNativeToolConsumerClosure, getPluginConfigDependencyFields, getPluginConfigDependencyKeys, loadPluginNativeToolClosure, materializeNativeToolClosureFiles, normalizeCommandRoutes, normalizeProducerIdentity, selectPluginConfigProfile, validateCommandEntryFiles, validatePluginConfigCandidate, validatePluginConfigValue, } from '@lesliechan721/aw-plugin-core/manifest';
5
+ import { resolveArtifactRenderConfig } from './artifact-renderer.js';
6
+ import { selectManagedCommandRenderConfig } from './artifact-request.js';
7
+ import { calculateManagedCommandResourceDigest, commandInputDigest, commandRouteEntries, readManagedCommandSource, validateManagedCommandPackageClosure, } from './managed-command-closure.js';
8
+ import { COMMAND_RUNTIME_CONFIG_READER, commandRuntimeConfigSnapshotPath, readCommandRuntimeConfigReaderSource, readManagedCommandRuntimeConfigSnapshot, } from './managed-command-snapshots.js';
9
+ import { captureManagedCommandPackageEvidence, copyManagedCommandDirectory, ManagedCommandError, readManagedCommandPackage, readManagedCommandPackageView, syncManagedCommandPackage, validateManagedCommandResource, } from './managed-command-store.js';
10
+ import { assertReadyPluginConfigStore, readPluginConfigStore, resolveEffectivePluginConfig, } from './plugin-config.js';
11
+ export { readManagedCommandSource } from './managed-command-closure.js';
12
+ export function managedCommandProducerIdentity(options) {
13
+ const { sourceId, sourceIdentity, manifest } = options.plugin;
14
+ if (!sourceId || !sourceIdentity) {
15
+ throw new ManagedCommandError('commandIdentityConflict', 'A verified source identity is required for the command package.');
22
16
  }
23
- return selected.filter(({ producer }) => producer.scope === 'user'
24
- || (options.scope === 'project' && producer.projectRoot === projectRoot)).map((entry) => ({
25
- producer: entry.producer, packageId: entry.id, commandIds: entry.sets.flatMap((set) => set.commandIds),
26
- availability: entry.availability, errors: entry.errors,
27
- recoveryAction: `aw command package remove ${entry.id} --yes`,
28
- }));
17
+ return normalizeProducerIdentity({ sourceId, sourceIdentity, pluginName: manifest.name });
29
18
  }
30
- export function retainedManagedCommandPackageResult(entry) {
31
- return { producer: entry.producer,
32
- state: entry.availability === 'unavailable' ? 'partial' : 'completed', commandIds: entry.commandIds,
33
- removedCommandIds: [], errors: entry.errors, recoveryActions: [entry.recoveryAction] };
19
+ function declaredCommand(plugin) {
20
+ if (!plugin.manifest.command) {
21
+ throw new ManagedCommandError('commandPackageDeclarationMissing', 'The active plugin no longer declares a command package. Run aw command package remove or aw plugin sync.');
22
+ }
23
+ return plugin.manifest.command;
34
24
  }
35
- export async function prepareManagedCommandPackageFiles(options) {
36
- await validateManagedCommandResource(options.sourceRoot);
37
- const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'aw-command-package-'));
38
- const resourceRoot = path.join(tempRoot, 'resource');
25
+ async function nativeToolFiles(plugin) {
26
+ if (!plugin.manifest.nativeTools?.consumers.some((consumer) => consumer.kind === 'plugin-command'))
27
+ return undefined;
28
+ const closure = getNativeToolConsumerClosure(await loadPluginNativeToolClosure(plugin.rootDir, plugin.manifest), 'plugin-command');
29
+ return closure === undefined ? undefined : materializeNativeToolClosureFiles(closure);
30
+ }
31
+ export async function nativeToolsForPluginCommand(plugin) {
32
+ return (await nativeToolFiles(plugin))?.closure;
33
+ }
34
+ async function previousPackage(producer, env, requireKnownSnapshots) {
35
+ let view;
39
36
  try {
40
- await fs.copy(options.sourceRoot, resourceRoot, { dereference: false, errorOnExist: true });
41
- for (const [relative, content] of Object.entries(options.files)) {
42
- normalizeCommandRelativeFile(relative, 'command package generated file');
43
- if (isSkillAuthorOnlyPath(relative) || relative.split('/').some((segment) => ['.git', 'node_modules', '.agents-plugin', '.codex-plugin', '.claude-plugin', '.release', '.tmp', 'evals', 'reports', '.aw-command-producer.json', '.agent-workflows-owner.json', 'owner.json', 'aw-plugin-requirements.json'].includes(segment)) || [AW_RUNTIME_CONFIG_BINDING_PATH, AW_RUNTIME_CONFIG_READER_PATH, AW_RUNTIME_NATIVE_RECEIPT_PATH].includes(relative) || options.entries.some((entry) => entry.entry === relative))
44
- throw new ManagedCommandError('commandResourceInvalid', 'Generated files cannot replace protected resources or command entries.');
45
- const destination = path.join(resourceRoot, ...relative.split('/'));
46
- const existing = await fs.lstat(destination).catch(() => null);
47
- if (existing && !existing.isFile())
48
- throw new ManagedCommandError('commandResourceInvalid', 'A generated file conflicts with a directory.');
49
- if (existing && ((existing.mode & 0o111) !== 0 || /\.(?:[cm]?js|[cm]?ts|sh|bash|zsh|py|rb|exe|com|cmd|bat|ps1)$/iu.test(relative)))
50
- throw new ManagedCommandError('commandResourceInvalid', 'Generated configuration cannot replace executable code.');
51
- await fs.ensureDir(path.dirname(destination));
52
- await fs.writeFile(destination, content, { mode: 0o600 });
53
- await fs.chmod(destination, 0o600);
54
- }
55
- for (const reserved of ['.aw-command-producer.json', '.agent-workflows-owner.json', 'owner.json']) {
56
- if (await fs.pathExists(path.join(resourceRoot, reserved)))
57
- throw new ManagedCommandError('commandResourceInvalid', 'The package source contains an AW reserved resource.');
58
- }
59
- await validateManagedCommandResource(resourceRoot);
60
- await validateCommandEntryFiles(resourceRoot, options.entries);
61
- await validateManagedCommandPackageClosure(resourceRoot, options.entries);
62
- for (const entry of options.entries)
63
- await validateManagedCommandResource(resourceRoot, entry);
64
- return { resourceRoot, cleanup: () => fs.remove(tempRoot) };
37
+ view = await readManagedCommandPackageView(getCommandPackageId(producer), env);
65
38
  }
66
39
  catch (error) {
67
- await fs.remove(tempRoot);
40
+ if (error instanceof ManagedCommandError && error.code === 'commandNotFound')
41
+ return { expectedPackage: null };
68
42
  throw error;
69
43
  }
70
- }
71
- function sameProducer(left, right) {
72
- return getCommandPackageId(left) === getCommandPackageId(right);
73
- }
74
- export async function managedCommandProducerIdentity(options) {
75
- const { plugin, producer } = options;
76
- if (!plugin.sourceId || !plugin.sourceIdentity)
77
- throw new Error('commandReferenceInvalid: managed commands require verified source identity.');
78
- let scope = options.scope;
79
- let platform = null;
80
- let placementKey = null;
81
- let key;
82
- if (producer.kind === 'package') {
83
- const declaration = plugin.manifest.managedCommands?.packages.find((entry) => entry.key === producer.packageKey);
84
- if (!declaration)
85
- throw new Error('commandReferenceInvalid: command package is not declared.');
86
- key = declaration.key;
87
- scope = declaration.scope;
88
- platform = null;
89
- }
90
- else {
91
- if (!options.renderUnit)
92
- throw new Error('commandReferenceInvalid: a Skill producer requires its verified render unit.');
93
- key = producer.kind === 'static-skill' ? producer.skillKey : producer.artifactId;
94
- platform = producer.platform;
95
- scope = options.renderUnit.renderScope.kind;
96
- placementKey = options.renderUnit.physicalKey;
44
+ if (requireKnownSnapshots && view.routes === null) {
45
+ throw new ManagedCommandError('commandRuntimeConfigInvalid', `The previously applied platforms cannot be verified. Run aw command package remove ${view.packageId} --force, then sync the package again.`);
97
46
  }
98
- let projectRoot = null;
99
- if (scope === 'project') {
100
- const root = producer.kind === 'package' ? await resolveCanonicalRepoProjectKey(options.cwd)
101
- : options.renderUnit.renderScope.kind === 'project' ? options.renderUnit.renderScope.projectRoot : undefined;
102
- if (!root)
103
- throw new Error('commandReferenceInvalid: a project producer requires its canonical project root.');
104
- projectRoot = path.normalize(await fs.realpath(root));
105
- if (process.platform === 'win32')
106
- projectRoot = projectRoot.replace(/^[a-z]:/u, (drive) => drive.toUpperCase());
47
+ const expectedPackage = await captureManagedCommandPackageEvidence(view, env);
48
+ if (!view.resourceRoot || view.routes === null)
49
+ return { view, expectedPackage };
50
+ const previous = await readManagedCommandPackage(producer, env, { validateFiles: false });
51
+ if (previous?.resourceRoot !== view.resourceRoot) {
52
+ throw new ManagedCommandError('operationReviewStale', 'The installed command package changed during preparation.');
107
53
  }
108
- return normalizeProducerIdentity({ sourceId: plugin.sourceId, sourceIdentity: plugin.sourceIdentity, pluginName: plugin.manifest.name, kind: producer.kind, key, platform, scope, projectRoot, placementKey });
109
- }
110
- export function commandSetsForProducer(options) {
111
- const requested = (options.plugin.manifest.managedCommands?.sets ?? []).filter((set) => canonicalizeIdentityValue(set.producer) === canonicalizeIdentityValue(options.producer)
112
- && (options.requestedSetNames === undefined || options.requestedSetNames.has(set.set))).map((set) => {
113
- if (set.mode === 'static')
114
- return { set: set.set, state: 'present', entries: set.entries };
115
- const artifact = options.artifacts?.find((entry) => entry.target === 'aw.command-set' && entry.id === `command-set.${set.set}`);
116
- if (!artifact || artifact.target !== 'aw.command-set')
117
- throw new Error(`commandReferenceInvalid: dynamic command set ${set.set} was not prepared.`);
118
- return { set: set.set, state: artifact.state, entries: artifact.entries };
119
- });
120
- return options.requestedSetNames === undefined ? requested : [
121
- ...(options.previousSets ?? []).filter((set) => !options.requestedSetNames.has(set.set)),
122
- ...requested,
123
- ];
54
+ return { view, previous, expectedPackage };
124
55
  }
125
- export async function nativeToolsForCommandSets(plugin, sets) {
126
- return getNativeToolConsumerClosure(await loadPluginNativeToolClosure(plugin.rootDir, plugin.manifest), 'managed-command-set', sets.map((set) => set.set));
56
+ function configReadOptions(options) {
57
+ return {
58
+ sourceId: options.plugin.sourceId, sourceIdentity: options.plugin.sourceIdentity,
59
+ logicalIdentity: options.plugin.catalogLogicalIdentity, pluginName: options.plugin.manifest.name,
60
+ manifest: options.plugin.manifest, referencePlugins: options.referencePlugins,
61
+ cwd: options.cwd, env: options.env,
62
+ };
127
63
  }
128
- function assertUnchangedNativeToolClosure(before, after) {
129
- if (JSON.stringify(before) !== JSON.stringify(after)) {
130
- throw new ManagedCommandError('nativeToolSyncRequired', 'Native tool changes require a reviewed producer sync or package sync before configuration apply.');
64
+ async function commonRouteConfig(options) {
65
+ if (options.resolveConfig && options.plugin.manifest.config) {
66
+ return { ...await options.resolveConfig(), mode: 'artifact-render', targetScope: 'user' };
131
67
  }
68
+ return resolveArtifactRenderConfig({ ...configReadOptions(options), scope: 'user' });
132
69
  }
133
- /** Config refresh cannot adopt native declarations that its config Review did not show. */
134
- export async function assertManagedCommandPackageNativeToolsUnchanged(options) {
135
- const installed = (await listManagedCommandPackages(options.env)).packages.find((entry) => entry.id === getCommandPackageId(options.producer));
136
- const before = installed ? await readInstalledCommandProducer(installed.resourceRoot) : undefined;
137
- if (before && !sameProducer(before.producer, options.producer))
138
- throw new ManagedCommandError('commandIdentityConflict', 'The installed command package belongs to another producer.');
139
- const declaration = options.plugin.manifest.managedCommands?.packages.find((entry) => entry.key === options.producer.key && entry.scope === options.producer.scope);
140
- const sets = declaration ? (options.plugin.manifest.managedCommands?.sets ?? []).filter((set) => set.producer.kind === 'package' && set.producer.packageKey === declaration.key) : [];
141
- const closure = sets.length > 0 ? await nativeToolsForCommandSets(options.plugin, sets) : undefined;
142
- const after = closure ? materializeNativeToolClosureFiles(closure).closure : undefined;
143
- assertUnchangedNativeToolClosure(before?.nativeTools, after);
70
+ function routeConfigDigest(plugin, config) {
71
+ const command = declaredCommand(plugin);
72
+ return commandInputDigest(selectManagedCommandRenderConfig(config, command.mode === 'dynamic' ? command.refreshKeys : []));
144
73
  }
145
- export function injectNativeToolClosureFiles(files, closure) {
146
- if (!closure)
147
- return undefined;
148
- const generated = materializeNativeToolClosureFiles(closure);
149
- for (const [relative, content] of Object.entries(generated.files)) {
150
- if (files[relative] && !files[relative].equals(Buffer.from(content)))
151
- throw new ManagedCommandError('commandResourceInvalid', 'The producer contains conflicting native tool files.');
152
- files[relative] = Buffer.from(content);
153
- }
154
- return generated.closure;
74
+ function routeConfigKeyDigests(config) {
75
+ return Object.fromEntries(Object.entries(config.sources).map(([key, source]) => [
76
+ key, commandInputDigest({ field: config.schema?.[key], value: config.values[key], source,
77
+ issues: config.issues.filter((issue) => issue.key === key) }),
78
+ ]));
155
79
  }
156
- export async function prepareManagedCommandPackage(options) {
157
- options.signal?.throwIfAborted();
158
- const declaration = options.plugin.manifest.managedCommands?.packages.find((entry) => entry.key === options.packageKey);
159
- if (!declaration || declaration.scope !== options.scope)
160
- throw new ManagedCommandError('commandDefinitionInvalid', 'The requested package and scope are not declared.');
161
- const renderConfig = await resolveArtifactRenderConfig({
162
- sourceId: options.plugin.sourceId, sourceIdentity: options.plugin.sourceIdentity,
163
- logicalIdentity: options.plugin.catalogLogicalIdentity, pluginName: options.plugin.manifest.name,
164
- manifest: options.plugin.manifest, scope: declaration.scope, cwd: options.cwd, env: options.env,
165
- referencePlugins: options.referencePlugins,
80
+ async function resolvePlatformRuntimeConfig(options, platform) {
81
+ return options.resolveConfig?.(platform)
82
+ ?? resolveEffectivePluginConfig({ ...configReadOptions(options), platform, targetScope: 'user' });
83
+ }
84
+ function selectConfigValues(values, keys) {
85
+ return Object.fromEntries(keys.filter((key) => Object.hasOwn(values, key)).map((key) => [key, values[key]]));
86
+ }
87
+ function runtimeConfigEvidence(config, keys) {
88
+ const dependencies = getPluginConfigDependencyKeys(config.definition, keys, config.referenceContext);
89
+ return commandInputDigest({
90
+ values: selectConfigValues(config.values, dependencies),
91
+ issues: config.issues.filter((issue) => dependencies.includes(issue.key)),
166
92
  });
167
- if (renderConfig.issues.length > 0)
168
- throw new ManagedCommandError('commandDefinitionInvalid', 'Resolve the plugin configuration issues before refreshing its command package.');
169
- const producerRef = { kind: 'package', packageKey: declaration.key };
170
- const producer = await managedCommandProducerIdentity({ ...options, producer: producerRef });
171
- const allTargets = getManagedCommandArtifactTargets(options.plugin.manifest).filter((target) => target.producer.kind === 'package' && target.producer.packageKey === declaration.key);
172
- const explicitSubset = options.requestedArtifactIds !== undefined;
173
- const requestedIds = new Set(options.requestedArtifactIds);
174
- if (explicitSubset && (requestedIds.size === 0 || requestedIds.size !== options.requestedArtifactIds.length || [...requestedIds].some((id) => !allTargets.some((target) => target.id === id)))) {
175
- throw new ManagedCommandError('commandDefinitionInvalid', 'A partial package request must contain unique declared targets of this producer.');
176
- }
177
- const targets = explicitSubset ? allTargets.filter((target) => requestedIds.has(target.id)) : allTargets;
178
- const requestedSetNames = explicitSubset ? new Set(targets.flatMap((target) => target.set ? [target.set] : [])) : undefined;
179
- let previous;
180
- if (explicitSubset) {
181
- const installed = (await listManagedCommandPackages(options.env)).packages.find((entry) => entry.id === getCommandPackageId(producer));
182
- if (installed) {
183
- if (installed.availability === 'unavailable')
184
- throw new ManagedCommandError('commandBindingInvalid', 'Partial refresh requires a verified installed command package. Run a complete package sync.');
185
- const record = await readInstalledCommandProducer(installed.resourceRoot);
186
- if (!sameProducer(record.producer, producer))
187
- throw new ManagedCommandError('commandIdentityConflict', 'The installed command package belongs to another producer.');
188
- previous = { resourceRoot: installed.resourceRoot, sets: record.sets, nativeTools: record.nativeTools };
189
- }
190
- const hasUnrequestedSets = (options.plugin.manifest.managedCommands?.sets ?? []).some((set) => set.producer.kind === 'package' && set.producer.packageKey === declaration.key && !requestedSetNames.has(set.set));
191
- if (!previous && (hasUnrequestedSets || (declaration.render && !targets.some((target) => target.target === 'aw.command-package'))))
192
- throw new ManagedCommandError('commandBindingInvalid', 'Partial refresh cannot reconstruct unrequested producer content. Run a complete package sync.');
193
- }
194
- let artifacts = [];
195
- let generatedFiles = {};
196
- if (targets.length > 0) {
197
- const rendered = await runArtifactRenderer({ plugin: options.plugin, referencePlugins: options.referencePlugins, event: options.event ?? 'install', platform: 'managed-commands', scope: declaration.scope, cwd: options.cwd, commandEnv: options.env, requestedArtifactIds: targets.map((target) => target.id), signal: options.signal, scriptTimeoutMs: options.scriptTimeoutMs, ...(options.event === 'refresh' ? { changedConfigKeys: options.changedConfigKeys ?? [] } : {}) });
198
- artifacts = rendered.plan.artifacts;
199
- for (const artifact of artifacts)
200
- if (artifact.target === 'aw.command-package')
201
- generatedFiles = artifact.files;
93
+ }
94
+ function commonRuntimeConfigDigest(plugin, platform, store, keys) {
95
+ assertReadyPluginConfigStore(store);
96
+ const definition = selectPluginConfigProfile(plugin.manifest.config, platform);
97
+ const dependencies = getPluginConfigDependencyKeys(definition, keys);
98
+ return commandInputDigest(selectConfigValues(store.common ?? (store.platform ? {} : store.values), dependencies));
99
+ }
100
+ async function readCommandCommonStore(options) {
101
+ return options.resolveConfig ? (await options.resolveConfig()).stores.user
102
+ : readPluginConfigStore({ ...configReadOptions(options), scope: 'user' });
103
+ }
104
+ function applyRuntimeConfig(config, keys) {
105
+ const dependencies = getPluginConfigDependencyKeys(config.definition, keys, config.referenceContext);
106
+ if (config.issues.some((issue) => dependencies.includes(issue.key))
107
+ || validatePluginConfigCandidate(config.definition, config.values, keys, config.referenceContext).length > 0) {
108
+ throw new ManagedCommandError('commandRuntimeConfigInvalid', 'The effective command runtime config is invalid. Fix the configuration and sync again.');
202
109
  }
203
- const sets = commandSetsForProducer({ plugin: options.plugin, producer: producerRef, artifacts, ...(requestedSetNames ? { requestedSetNames, previousSets: previous?.sets } : {}) });
204
- let source = await resolveCommandSourceDirectory({ bundleRoot: options.plugin.rootDir, pluginRelativePath: declaration.sourceDir });
205
- let temporarySource;
206
- try {
207
- if (previous && !targets.some((target) => target.target === 'aw.command-package')) {
208
- temporarySource = await fs.mkdtemp(path.join(os.tmpdir(), 'aw-command-previous-'));
209
- source = path.join(temporarySource, 'resource');
210
- await fs.copy(previous.resourceRoot, source, { dereference: false, errorOnExist: true });
211
- await fs.remove(path.join(source, '.aw-command-producer.json'));
110
+ return selectConfigValues(config.values, keys);
111
+ }
112
+ function previousConfigCompatible(definition, keys, old) {
113
+ return keys.every((key) => {
114
+ const field = definition.fields[key];
115
+ if (!Object.hasOwn(old.effectiveValues, key))
116
+ return field.required !== true;
117
+ if (validatePluginConfigValue(field, old.effectiveValues[key], key).length > 0)
118
+ return false;
119
+ // Validate references with the applied values when the previous snapshot includes the full dependency closure.
120
+ // Unpublished dependencies must not draw this platform's pending Config Store values into an unrelated sync.
121
+ let dependencies;
122
+ try {
123
+ dependencies = getPluginConfigDependencyFields(definition, [key]);
212
124
  }
213
- const prepared = await prepareManagedCommandPackageFiles({ sourceRoot: source, files: generatedFiles, entries: sets.flatMap((set) => set.entries) });
214
- const closure = await nativeToolsForCommandSets(options.plugin, sets);
215
- const generated = closure ? materializeNativeToolClosureFiles(closure) : undefined;
125
+ catch {
126
+ return true;
127
+ } // Cross-plugin providers are outside this snapshot.
128
+ if (dependencies.some(({ field }) => !old.allowedKeys.includes(field)))
129
+ return true;
130
+ return validatePluginConfigCandidate(definition, old.effectiveValues, [key]).length === 0;
131
+ });
132
+ }
133
+ async function readPreviousSnapshots(previous) {
134
+ const snapshots = new Map();
135
+ if (!previous)
136
+ return snapshots;
137
+ for (const platform of previous.record.runtimeConfigPlatforms) {
216
138
  try {
217
- if (explicitSubset && previous)
218
- assertUnchangedNativeToolClosure(previous.nativeTools, generated?.closure);
219
- for (const [relative, content] of Object.entries(generated?.files ?? {})) {
220
- const destination = path.join(prepared.resourceRoot, relative);
221
- const existing = await fs.readFile(destination).catch((error) => { if (error.code === 'ENOENT')
222
- return undefined; throw error; });
223
- if (existing && !existing.equals(Buffer.from(content)))
224
- throw new ManagedCommandError('commandResourceInvalid', 'The producer contains conflicting native tool files.');
225
- await fs.outputFile(destination, content);
226
- }
227
- return { producer, sets, ...(generated ? { nativeTools: generated.closure } : {}), ...prepared };
139
+ snapshots.set(platform, await readManagedCommandRuntimeConfigSnapshot(previous.resourceRoot, previous.record, platform));
228
140
  }
229
141
  catch (error) {
230
- await prepared.cleanup();
231
- throw error;
142
+ if (!(error instanceof ManagedCommandError))
143
+ throw error;
144
+ // The package record still identifies the platform. A sync can rebuild a damaged snapshot.
232
145
  }
233
146
  }
234
- finally {
235
- if (temporarySource)
236
- await fs.remove(temporarySource);
237
- }
147
+ return snapshots;
238
148
  }
239
- export async function syncPluginManagedCommandPackage(options) {
240
- const producer = await managedCommandProducerIdentity({ ...options, producer: { kind: 'package', packageKey: options.packageKey } });
241
- const key = getCommandPackageId(producer);
242
- let result = options.managedCommandProducerCache?.get(key);
243
- if (!result) {
244
- result = (async () => {
245
- let candidate;
246
- try {
247
- candidate = await prepareManagedCommandPackage(options);
248
- const old = await listManagedCommandPackages(options.env);
249
- const previousIds = old.packages.find((entry) => entry.id === key)?.sets.flatMap((set) => set.commandIds) ?? [];
250
- const synced = await syncManagedCommandPackage({ producer, sourceDirectory: candidate.resourceRoot, sets: candidate.sets, nativeTools: candidate.nativeTools, env: options.env, expectedPackage: options.expectedPackage });
251
- return { producer, state: 'completed', commandIds: synced.commandIds, removedCommandIds: previousIds.filter((id) => !synced.commandIds.includes(id)), errors: [], recoveryActions: [] };
149
+ async function prepareRuntimeConfig(options) {
150
+ const { operation, previous, record } = options;
151
+ const command = declaredCommand(options.plugin);
152
+ const oldSnapshots = await readPreviousSnapshots(previous);
153
+ const oldPlatforms = previous?.record.runtimeConfigPlatforms ?? [];
154
+ const keys = record.runtimeConfigKeys;
155
+ const snapshots = new Map();
156
+ const evidence = new Map();
157
+ const commonDigests = {};
158
+ const refresh = new Set(operation.kind === 'explicit-sync'
159
+ ? options.packageExists ? oldPlatforms : command.platforms
160
+ : 'platforms' in operation ? operation.platforms : []);
161
+ if (keys)
162
+ for (const platform of command.platforms) {
163
+ const old = oldSnapshots.get(platform);
164
+ if (!refresh.has(platform) && !oldPlatforms.includes(platform))
165
+ continue;
166
+ let effectiveValues;
167
+ if (!refresh.has(platform) && !old) {
168
+ throw new ManagedCommandError('commandRuntimeConfigInvalid', 'A previously applied snapshot is damaged. Run aw command package sync to refresh it.');
252
169
  }
253
- catch (error) {
254
- if (recoveryInterruptionCode(error, options.signal) || readSafeOperationError(error))
255
- throw error;
256
- return { producer, state: 'failed', commandIds: [], removedCommandIds: [], errors: [managedCommandDiagnostic(error)], recoveryActions: [`aw command package sync ${producer.sourceId}/${producer.pluginName} ${producer.key} --scope ${producer.scope} --yes`] };
170
+ if (old && !refresh.has(platform) && (old.sourceContentDigest === record.sourceContentDigest
171
+ || previousConfigCompatible(selectPluginConfigProfile(options.plugin.manifest.config, platform), keys, old))) {
172
+ effectiveValues = selectConfigValues(old.effectiveValues, keys);
257
173
  }
258
- finally {
259
- await candidate?.cleanup();
174
+ else {
175
+ const config = await resolvePlatformRuntimeConfig(options, platform);
176
+ effectiveValues = applyRuntimeConfig(config, keys);
177
+ evidence.set(platform, runtimeConfigEvidence(config, keys));
178
+ commonDigests[platform] = commonRuntimeConfigDigest(options.plugin, platform, config.stores.user, keys);
260
179
  }
261
- })();
262
- options.managedCommandProducerCache?.set(key, result);
180
+ const previousDigest = previous?.record.runtimeConfigCommonDigests?.[platform];
181
+ if (previousDigest !== undefined)
182
+ commonDigests[platform] ??= previousDigest;
183
+ snapshots.set(platform, {
184
+ schemaVersion: 1, kind: 'aw-command-runtime-config',
185
+ producer: record.producer, pluginVersion: record.pluginVersion, sourceContentDigest: record.sourceContentDigest,
186
+ platform, allowedKeys: keys, effectiveValues,
187
+ });
188
+ }
189
+ const changes = [];
190
+ for (const platform of new Set([...oldPlatforms, ...snapshots.keys()])) {
191
+ const before = oldSnapshots.get(platform)?.effectiveValues;
192
+ const after = snapshots.get(platform)?.effectiveValues;
193
+ if (canonicalizeIdentityValue(before) !== canonicalizeIdentityValue(after)) {
194
+ changes.push({ platform, ...(before === undefined ? {} : { before }), ...(after === undefined ? {} : { after }) });
195
+ }
263
196
  }
264
- return result;
197
+ if (Object.keys(commonDigests).length)
198
+ record.runtimeConfigCommonDigests = commonDigests;
199
+ return { snapshots, changes, evidence };
265
200
  }
266
- export async function discoverInstalledPluginManagedCommandPackages(options) {
267
- const listed = await listManagedCommandPackages(options.env);
268
- let currentProject;
269
- const relevant = listed.packages.filter((entry) => entry.producer.sourceId === options.plugin.sourceId && entry.producer.pluginName === options.plugin.manifest.name);
270
- const installedPackageIds = new Set(relevant.map((entry) => entry.id));
271
- const errors = [...listed.errors];
272
- if (options.scope === 'project' && (relevant.some((entry) => entry.producer.scope === 'project')
273
- || (options.platformTargets?.length && options.plugin.manifest.managedCommands?.packages.some((entry) => entry.scope === 'project')))) {
274
- currentProject = path.normalize(await fs.realpath(await resolveCanonicalRepoProjectKey(options.cwd)));
201
+ async function verifyCommandConfigApplySource(plugin, previous, view, native) {
202
+ if (!previous) {
203
+ throw new ManagedCommandError('commandBindingInvalid', 'Configuration apply requires a usable installed command package. Run aw command package sync.');
275
204
  }
276
- const producers = new Map();
277
- for (const entry of relevant) {
278
- const identity = entry.producer;
279
- if (identity.scope !== options.scope || (identity.scope === 'project' && identity.projectRoot !== currentProject))
280
- continue;
281
- if (identity.sourceIdentity !== options.plugin.sourceIdentity) {
282
- errors.push({ code: 'commandSourceIdentityChanged', message: `The retained command package belongs to a previous source identity; remove it with aw command package remove ${entry.id} --yes.`, subject: entry.id });
283
- continue;
284
- }
285
- producers.set(entry.id, identity);
205
+ if (canonicalizeIdentityValue(previous.record.nativeTools) !== canonicalizeIdentityValue(native)) {
206
+ throw new ManagedCommandError('nativeToolSyncRequired', 'Native tool changes require aw plugin sync or aw command package sync before configuration apply.');
286
207
  }
287
- for (const declaration of options.plugin.manifest.managedCommands?.packages ?? []) {
288
- if (declaration.scope !== options.scope)
289
- continue;
290
- if (!options.platformTargets?.some((target) => declaration.platforms.includes(target.platform)))
291
- continue;
292
- const producer = await managedCommandProducerIdentity({ ...options, producer: { kind: 'package', packageKey: declaration.key } });
293
- producers.set(getCommandPackageId(producer), producer);
208
+ const mismatch = () => new ManagedCommandError('configApplyVersionMismatch', 'The installed command package differs from Active Catalog. Run aw plugin sync or aw command package sync.');
209
+ if (!plugin.manifest.command || previous.record.pluginVersion !== plugin.manifest.version)
210
+ throw mismatch();
211
+ const source = await readManagedCommandSource(plugin);
212
+ if (previous.record.sourceContentDigest !== source.sourceContentDigest)
213
+ throw mismatch();
214
+ if (view?.availability === 'unavailable') {
215
+ throw new ManagedCommandError('commandBindingInvalid', 'Configuration apply requires a usable installed command package. Run aw command package sync.');
294
216
  }
295
- return { packages: [...producers].map(([packageId, producer]) => {
296
- const declaration = options.plugin.manifest.managedCommands?.packages.find((entry) => entry.key === producer.key && entry.scope === producer.scope);
297
- const setKeys = (options.plugin.manifest.managedCommands?.sets ?? []).flatMap((set) => set.producer.kind === 'package' && set.producer.packageKey === producer.key && set.mode === 'dynamic' ? set.refreshKeys : []);
298
- return { producer, packageId, packageKey: producer.key, refreshKeys: [...new Set([...(declaration?.refreshKeys ?? []), ...setKeys])], declared: declaration !== undefined, installed: installedPackageIds.has(packageId) };
299
- }), errors };
217
+ return source;
300
218
  }
301
- export async function createManagedCommandReferenceResolver(options) {
302
- const resolved = new Map();
303
- for (const set of options.plugin.manifest.managedCommands?.sets ?? []) {
304
- if (set.producer.kind !== 'package' && set.producer.platform !== options.platform)
305
- continue;
306
- if (set.producer.kind === 'package') {
307
- const declaration = options.plugin.manifest.managedCommands?.packages.find((entry) => set.producer.kind === 'package' && entry.key === set.producer.packageKey);
308
- if (!declaration?.platforms.includes(options.platform) || (options.scope === 'user' && declaration.scope === 'project'))
309
- continue;
219
+ /** Select only the snapshots and routes whose applied inputs differ. */
220
+ export async function inspectManagedCommandConfigApply(options) {
221
+ const { plugin, platform } = options;
222
+ const { previous, view } = await previousPackage(managedCommandProducerIdentity(options), options.env, false);
223
+ if (!view)
224
+ return undefined;
225
+ await verifyCommandConfigApplySource(plugin, previous, view, await nativeToolsForPluginCommand(plugin));
226
+ const record = previous.record;
227
+ const command = declaredCommand(plugin);
228
+ const keys = command.runtimeConfig?.keys;
229
+ const platforms = [];
230
+ if (platform && keys && command.platforms.includes(platform)) {
231
+ const config = await resolvePlatformRuntimeConfig(options, platform);
232
+ const values = applyRuntimeConfig(config, keys);
233
+ const snapshot = record.runtimeConfigPlatforms.includes(platform)
234
+ ? await readManagedCommandRuntimeConfigSnapshot(previous.resourceRoot, record, platform) : undefined;
235
+ if (canonicalizeIdentityValue(values) !== canonicalizeIdentityValue(snapshot?.effectiveValues))
236
+ platforms.push(platform);
237
+ }
238
+ else if (!platform && keys && record.runtimeConfigPlatforms.length) {
239
+ const store = await readCommandCommonStore(options);
240
+ for (const target of record.runtimeConfigPlatforms) {
241
+ if (command.platforms.includes(target)
242
+ && record.runtimeConfigCommonDigests?.[target] !== commonRuntimeConfigDigest(plugin, target, store, keys))
243
+ platforms.push(target);
310
244
  }
311
- const producer = await managedCommandProducerIdentity({ ...options, producer: set.producer });
312
- if (options.unavailableProducers?.some((unavailable) => sameProducer(unavailable, producer)))
313
- continue;
314
- if (producer.platform && producer.platform !== options.platform)
315
- continue;
316
- if (options.scope === 'user' && producer.scope === 'project')
317
- continue;
318
- if (set.producer.kind === 'package') {
319
- const declaration = options.plugin.manifest.managedCommands?.packages.find((entry) => entry.key === producer.key);
320
- if (!declaration?.platforms.includes(options.platform))
321
- continue;
245
+ }
246
+ const refreshRoutes = !platform && command.mode === 'dynamic' && command.refreshKeys.length > 0
247
+ && record.routeConfigDigest !== routeConfigDigest(plugin, await commonRouteConfig(options));
248
+ return platforms.length || refreshRoutes ? { kind: 'config-apply', platforms, refreshRoutes } : undefined;
249
+ }
250
+ export async function prepareManagedCommandPackage(options) {
251
+ options.signal?.throwIfAborted();
252
+ const { plugin, operation } = options;
253
+ const declaration = declaredCommand(plugin);
254
+ if (operation.kind === 'platform-sync' && !operation.platforms.some((platform) => declaration.platforms.includes(platform))) {
255
+ throw new ManagedCommandError('commandDefinitionInvalid', 'No selected platform supports this command package.');
256
+ }
257
+ const producer = managedCommandProducerIdentity(options);
258
+ const requireKnownSnapshots = operation.kind === 'explicit-sync' && declaration.runtimeConfig !== undefined;
259
+ // Author profiles validate the route and closure without applying platform config.
260
+ const { previous, view, expectedPackage } = operation.kind === 'materialize'
261
+ ? { expectedPackage: null } : await previousPackage(producer, options.env, requireKnownSnapshots);
262
+ const native = await nativeToolFiles(plugin);
263
+ const source = operation.kind === 'config-apply'
264
+ ? await verifyCommandConfigApplySource(plugin, previous, view, native?.closure)
265
+ : await readManagedCommandSource(plugin);
266
+ let routes;
267
+ let routeEvidence;
268
+ const previousKeyDigests = previous?.record.routeConfigKeyDigests;
269
+ let appliedKeyDigests = previousKeyDigests;
270
+ if (declaration.mode === 'static')
271
+ routes = declaration.routes;
272
+ else if (operation.kind === 'config-apply' && !operation.refreshRoutes && previous)
273
+ routes = previous.record.routes;
274
+ else {
275
+ const renderRoutes = options.renderRoutes ?? (await import('./managed-command-preparation.js')).renderManagedCommandRoutes;
276
+ const commonConfig = await commonRouteConfig(options);
277
+ const selectedConfig = selectManagedCommandRenderConfig(commonConfig, declaration.refreshKeys);
278
+ routeEvidence = commandInputDigest(selectedConfig);
279
+ appliedKeyDigests = routeConfigKeyDigests(selectedConfig);
280
+ const changedConfigKeys = operation.kind === 'config-apply' && previousKeyDigests
281
+ ? Object.entries(appliedKeyDigests).filter(([key, digest]) => previousKeyDigests[key] !== digest).map(([key]) => key)
282
+ : [];
283
+ routes = normalizeCommandRoutes(await renderRoutes({ ...options, sourceDir: source.sourceRoot, previous: previous?.record,
284
+ commonConfig, changedConfigKeys,
285
+ event: operation.kind === 'config-apply' ? 'refresh' : operation.kind === 'platform-sync' ? 'install' : 'materialize' }));
286
+ if (routeEvidence !== routeConfigDigest(plugin, await commonRouteConfig(options))) {
287
+ throw new ManagedCommandError('operationReviewStale', 'Command configuration changed while preparing its routes.');
322
288
  }
323
- const candidates = (options.candidates ?? []).filter((entry) => sameProducer(entry.producer, producer));
324
- const candidateContent = (candidate) => canonicalizeIdentityValue({ producer: candidate.producer, sets: candidate.sets, nativeTools: candidate.nativeTools ?? null });
325
- if (candidates.some((entry) => candidateContent(entry) !== candidateContent(candidates[0])))
326
- throw new Error('commandReferenceInvalid: conflicting candidates identify the same command producer.');
327
- const candidate = candidates[0];
328
- const entries = candidate?.sets.find((entry) => entry.set === set.set);
329
- if (candidate) {
330
- if (entries?.state !== 'present')
331
- continue;
332
- for (const entry of entries.entries)
333
- resolved.set(`${set.set}/${entry.key}/${entry.variant}`, getPluginCommandId({ schemaVersion: 2, producer, set: set.set, key: entry.key, variant: entry.variant }));
289
+ }
290
+ const appliedRouteDigest = routeEvidence ?? previous?.record.routeConfigDigest;
291
+ const record = {
292
+ schemaVersion: 2, producer, pluginVersion: plugin.manifest.version, sourceContentDigest: source.sourceContentDigest, routes,
293
+ ...(declaration.mode === 'dynamic' ? { dynamicRefreshKeys: declaration.refreshKeys } : {}),
294
+ ...(declaration.mode === 'dynamic' && appliedRouteDigest ? { routeConfigDigest: appliedRouteDigest } : {}),
295
+ ...(declaration.mode === 'dynamic' && appliedKeyDigests ? { routeConfigKeyDigests: appliedKeyDigests } : {}),
296
+ ...(native ? { nativeTools: native.closure } : {}),
297
+ ...(declaration.runtimeConfig ? { runtimeConfigKeys: declaration.runtimeConfig.keys } : {}),
298
+ runtimeConfigPlatforms: [],
299
+ };
300
+ const runtime = await prepareRuntimeConfig({ ...options, record, previous, packageExists: view !== undefined });
301
+ record.runtimeConfigPlatforms = [...runtime.snapshots.keys()];
302
+ const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'aw-command-package-'));
303
+ const resourceRoot = path.join(tempRoot, 'resource');
304
+ const cleanup = () => fs.remove(tempRoot);
305
+ try {
306
+ await copyManagedCommandDirectory(source.sourceRoot, resourceRoot, options.env, { trustedPluginSource: true });
307
+ if (source.sourceTreeDigest !== await calculateManagedCommandResourceDigest(resourceRoot)) {
308
+ throw new ManagedCommandError('operationReviewStale', 'Command package resources changed while staging.');
334
309
  }
335
- else if (set.mode === 'static') {
336
- for (const entry of set.entries) {
337
- const id = getPluginCommandId({ schemaVersion: 2, producer, set: set.set, key: entry.key, variant: entry.variant });
338
- try {
339
- if ((await inspectManagedCommand(id, options.env)).availability === 'ready')
340
- resolved.set(`${set.set}/${entry.key}/${entry.variant}`, id);
341
- }
342
- catch (error) {
343
- if (!(error instanceof ManagedCommandError) || error.code !== 'commandNotFound')
344
- throw error;
345
- }
346
- }
310
+ const entries = commandRouteEntries(record.routes);
311
+ // An entry must come from the author package, even when the script imports AW's helper files.
312
+ await validateCommandEntryFiles(resourceRoot, entries);
313
+ if (record.runtimeConfigKeys) {
314
+ await fs.outputFile(path.join(resourceRoot, COMMAND_RUNTIME_CONFIG_READER), await readCommandRuntimeConfigReaderSource(), { flag: 'wx' });
347
315
  }
348
- else {
349
- const installed = await listManagedCommands(options.env);
350
- for (const command of installed.commands)
351
- if (command.availability === 'ready' && command.owner.kind === 'plugin' && sameProducer(command.owner.producer, producer) && command.name.startsWith(`${set.set}/`))
352
- resolved.set(command.name, command.id);
316
+ for (const [platform, snapshot] of runtime.snapshots) {
317
+ await fs.outputFile(path.join(resourceRoot, commandRuntimeConfigSnapshotPath(platform)), `${JSON.stringify(snapshot, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
353
318
  }
319
+ for (const [relative, content] of Object.entries(native?.files ?? {})) {
320
+ await fs.outputFile(path.join(resourceRoot, relative), content, { flag: 'wx' });
321
+ }
322
+ await validateManagedCommandPackageClosure(resourceRoot, entries);
323
+ for (const entry of entries)
324
+ await validateManagedCommandResource(resourceRoot, entry);
325
+ options.signal?.throwIfAborted();
326
+ const resourceDigest = await calculateManagedCommandResourceDigest(resourceRoot);
327
+ return { resourceRoot, resourceDigest, record, previous, expectedPackage, cleanup,
328
+ runtimeConfigChanges: runtime.changes, runtimeConfigEvidence: runtime.evidence, routeConfigEvidence: routeEvidence };
329
+ }
330
+ catch (error) {
331
+ await cleanup();
332
+ throw error;
333
+ }
334
+ }
335
+ /** Recheck inputs under the caller's existing write lock, without repeating the renderer. */
336
+ export async function verifyPreparedManagedCommandPackage(options) {
337
+ const { candidate } = options;
338
+ const stale = () => new ManagedCommandError('operationReviewStale', 'The reviewed command source or configuration changed. Review the command package again.');
339
+ try {
340
+ const producer = managedCommandProducerIdentity(options);
341
+ const native = await nativeToolsForPluginCommand(options.plugin);
342
+ const source = await readManagedCommandSource(options.plugin);
343
+ if (canonicalizeIdentityValue(producer) !== canonicalizeIdentityValue(candidate.record.producer)
344
+ || canonicalizeIdentityValue(native) !== canonicalizeIdentityValue(candidate.record.nativeTools)
345
+ || candidate.record.pluginVersion !== options.plugin.manifest.version
346
+ || candidate.record.sourceContentDigest !== source.sourceContentDigest)
347
+ throw stale();
348
+ if (candidate.routeConfigEvidence !== undefined && candidate.routeConfigEvidence !== routeConfigDigest(options.plugin, await commonRouteConfig(options)))
349
+ throw stale();
350
+ for (const [platform, digest] of candidate.runtimeConfigEvidence) {
351
+ const config = await resolvePlatformRuntimeConfig(options, platform);
352
+ const keys = candidate.record.runtimeConfigKeys;
353
+ if (digest !== runtimeConfigEvidence(config, keys)
354
+ || candidate.record.runtimeConfigCommonDigests?.[platform] !== commonRuntimeConfigDigest(options.plugin, platform, config.stores.user, keys))
355
+ throw stale();
356
+ }
357
+ }
358
+ catch (error) {
359
+ if (error instanceof ManagedCommandError && error.code === 'operationReviewStale')
360
+ throw error;
361
+ throw stale();
354
362
  }
355
- return (reference) => {
356
- if (!options.plugin.manifest.requires?.aw.capabilities?.includes('aw.managed-commands.v1'))
357
- throw new Error('commandReferenceInvalid: managed command references require aw.managed-commands.v1.');
358
- const id = resolved.get(`${reference.set}/${reference.key}/${reference.variant ?? 'default'}`);
359
- if (!id)
360
- throw new Error(`commandReferenceInvalid: command ${reference.set}/${reference.key}/${reference.variant ?? 'default'} has no verified producer for this consumer.`);
361
- return id;
362
- };
363
363
  }
364
- export function resolveSkillManagedCommandReferences(tree, resolve) {
365
- for (const [relative, content] of Object.entries(tree.files))
366
- if (relative.endsWith('.md'))
367
- tree.files[relative] = Buffer.from(replaceManagedCommandPlaceholders(content.toString('utf8'), resolve), 'utf8');
364
+ export async function publishPreparedManagedCommandPackage(options) {
365
+ await verifyPreparedManagedCommandPackage(options);
366
+ return syncManagedCommandPackage({ producer: options.candidate.record.producer, record: options.candidate.record,
367
+ sourceDirectory: options.candidate.resourceRoot, expectedPackage: options.candidate.expectedPackage,
368
+ expectedResourceDigest: options.candidate.resourceDigest, env: options.env });
368
369
  }
369
370
  //# sourceMappingURL=managed-command-materialization.js.map