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

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 +131 -45
  45. package/dist/src/commands/rebuild-command.js.map +1 -1
  46. package/dist/src/commands/rebuild-integration.d.ts +11 -3
  47. package/dist/src/commands/rebuild-integration.js +47 -164
  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 +7 -0
  97. package/dist/src/platforms/layout.js +46 -5
  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,27 +1,19 @@
1
1
  import crypto from 'node:crypto';
2
2
  import * as fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { getCommandPackageId, getPluginCommandId, isManagedCommandId, normalizeCommandIdentity, normalizeCommandLaunch, normalizeInstalledCommandProducer as normalizeCoreProducer, normalizeUserCommandDefinition, normalizeProducerIdentity, COMMAND_PRODUCER_RECORD_FILE, validateNativeToolClosureFiles, } from '@lesliechan721/aw-plugin-core/manifest';
4
+ import { getCommandPackageId, isCommandPackageId as isCoreCommandPackageId, isUserCommandId as isCoreUserCommandId, normalizeCommandSelector, normalizeCommandLaunch, normalizeInstalledCommandProducer as normalizeCoreProducer, normalizeUserCommandDefinition, normalizeProducerIdentity, COMMAND_PRODUCER_RECORD_FILE, validateNativeToolClosureFiles, } from '@lesliechan721/aw-plugin-core/manifest';
5
5
  import { calculateFileDigest } from './bundle-integrity.js';
6
- import { verifyManagedCommandArtifactEvidence } from './managed-command-evidence.js';
6
+ import { calculateCatalogSourceIdentity } from './catalog-source-identity.js';
7
+ import { readCatalogSourcesConfig, resolveCatalogSourcesConfigPath } from './catalog-sources.js';
8
+ import { CatalogGenerationError } from './catalog-generation-error.js';
9
+ import { calculateManagedCommandResourceDigest } from './managed-command-closure.js';
10
+ import { ManagedCommandError } from './managed-command-errors.js';
11
+ import { validateManagedCommandRuntimeConfigFiles } from './managed-command-snapshots.js';
7
12
  import { atomicReplaceSafeFile } from './safe-fs.js';
8
13
  import { canonicalizePathThroughExistingAncestor, ensureRegularDirectoryPath, resolveAwHome, } from './state-paths.js';
9
14
  export const COMMAND_PRODUCER_RECORD = COMMAND_PRODUCER_RECORD_FILE;
10
- const USER_ID = /^cmdu_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
11
- const PACKAGE_ID = /^pkg_[0-9a-f]{64}$/u;
12
- export class ManagedCommandError extends Error {
13
- code;
14
- argumentError;
15
- constructor(code, message, argumentError = false) {
16
- super(message);
17
- this.code = code;
18
- this.argumentError = argumentError;
19
- }
20
- }
21
- class DamagedCommandBindingError extends ManagedCommandError {
22
- constructor() { super('commandBindingInvalid', 'The command binding is not valid JSON.'); }
23
- }
24
- const bindingRecoveryIdentities = Symbol('verified native command identities');
15
+ export { ManagedCommandError };
16
+ const REVISION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
25
17
  function fail(code, message) { throw new ManagedCommandError(code, message); }
26
18
  function object(value, keys, code) {
27
19
  if (!value || typeof value !== 'object' || Array.isArray(value)
@@ -84,10 +76,22 @@ async function writeJson(root, target, value) {
84
76
  await ensureRegularDirectoryPath(root, 'Managed commands root');
85
77
  await atomicReplaceSafeFile({ allowedRoot: root, filePath: target, content: `${JSON.stringify(value, null, 2)}\n`, label: 'Managed command record' });
86
78
  }
79
+ export function isUserCommandId(selector) { return isCoreUserCommandId(selector); }
80
+ export function isManagedCommandPackageId(selector) { return isCoreCommandPackageId(selector); }
81
+ export function parsePluginCommandSelector(selector) {
82
+ try {
83
+ return normalizeCommandSelector(selector);
84
+ }
85
+ catch {
86
+ throw new ManagedCommandError('invalidArguments', 'A canonical source/plugin selector is required.', true);
87
+ }
88
+ }
87
89
  export function assertUserCommandId(id) {
88
- if (/^cmdp_[0-9a-f]{16}$/u.test(id))
89
- fail('commandOwnerMismatch', 'Plugin commands must be maintained with their producer sync, reinstall, or package remove command.');
90
- if (!USER_ID.test(id))
90
+ if (id.includes('/')) {
91
+ parsePluginCommandSelector(id);
92
+ fail('commandOwnerMismatch', 'Plugin commands must be maintained with plugin sync or command package sync/remove.');
93
+ }
94
+ if (!isUserCommandId(id))
91
95
  throw new ManagedCommandError('invalidArguments', 'A canonical user command ID is required.', true);
92
96
  }
93
97
  export function validateManagedCommandName(value) {
@@ -146,7 +150,12 @@ export async function validateManagedCommandResource(resourceRoot, launch) {
146
150
  const stat = await fs.lstat(directory).catch(() => null);
147
151
  if (!stat?.isDirectory() || stat.isSymbolicLink())
148
152
  fail('commandResourceInvalid', 'The command resource root must be a regular directory.');
149
- for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
153
+ const entries = await fs.readdir(directory, { withFileTypes: true }).catch((error) => {
154
+ if (error.code === 'ENOENT')
155
+ fail('commandResourceInvalid', 'The command resource changed before it could be read.');
156
+ throw error;
157
+ });
158
+ for (const entry of entries) {
150
159
  if (entry.name === '.git' || entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) {
151
160
  fail('commandResourceInvalid', 'Command resources cannot contain links, special nodes, or .git directories.');
152
161
  }
@@ -155,8 +164,10 @@ export async function validateManagedCommandResource(resourceRoot, launch) {
155
164
  }
156
165
  }
157
166
  await visit(root);
158
- if (!launch)
159
- return;
167
+ if (launch)
168
+ await validateCommandLaunchFile(root, launch);
169
+ }
170
+ async function validateCommandLaunchFile(root, launch) {
160
171
  const entry = path.resolve(root, launch.entry);
161
172
  if (!contains(root, entry) || entry === root)
162
173
  fail('commandResourceInvalid', 'The command entry escapes its resource root.');
@@ -283,6 +294,55 @@ export async function removeUserCommand(id, env = process.env) {
283
294
  const userRoot = await assertUserOwner(root, id);
284
295
  await fs.rm(userRoot, { recursive: true, force: true });
285
296
  }
297
+ async function lstatIfExists(target) {
298
+ try {
299
+ return await fs.lstat(target);
300
+ }
301
+ catch (error) {
302
+ if (error.code === 'ENOENT')
303
+ return null;
304
+ throw error;
305
+ }
306
+ }
307
+ async function entriesAt(directory) {
308
+ try {
309
+ return await fs.readdir(directory);
310
+ }
311
+ catch (error) {
312
+ if (error.code === 'ENOENT')
313
+ return [];
314
+ throw error;
315
+ }
316
+ }
317
+ async function readConfiguredSources(env) {
318
+ try {
319
+ const sourceFile = resolveCatalogSourcesConfigPath(env);
320
+ const stat = await lstatIfExists(sourceFile);
321
+ if (stat && !stat.isFile())
322
+ fail('catalogSourcesConfigInvalid', 'Catalog sources config must be a regular file.');
323
+ const { sources } = await readCatalogSourcesConfig(env);
324
+ const identities = await Promise.all(sources.map(async (source) => [source.id, await calculateCatalogSourceIdentity(source)]));
325
+ return new Map(identities);
326
+ }
327
+ catch (error) {
328
+ if (error instanceof CatalogGenerationError)
329
+ fail(error.code, error.message);
330
+ fail('catalogSourcesConfigInvalid', 'Catalog sources config is unreadable or invalid. Repair catalog-sources.json, then run aw source sync.');
331
+ }
332
+ }
333
+ async function resolvePluginCommandProducer(selector, env) {
334
+ const { sourceId, pluginName } = parsePluginCommandSelector(selector);
335
+ const sourceIdentity = (await readConfiguredSources(env)).get(sourceId);
336
+ if (sourceIdentity === undefined)
337
+ fail('commandNotFound', 'The command source is no longer configured. Run aw command list to find packages by ID.');
338
+ return { sourceId, sourceIdentity, pluginName };
339
+ }
340
+ export async function resolveManagedCommandPackageId(selector, env = process.env) {
341
+ const producer = await resolvePluginCommandProducer(selector, env);
342
+ const id = getCommandPackageId(producer);
343
+ await assertExpectedPackage(await managedCommandRoot(env), id, producer);
344
+ return id;
345
+ }
286
346
  export function normalizeInstalledCommandProducer(value) {
287
347
  try {
288
348
  const record = normalizeCoreProducer(value);
@@ -291,447 +351,450 @@ export function normalizeInstalledCommandProducer(value) {
291
351
  return record;
292
352
  }
293
353
  catch {
294
- fail('commandBindingInvalid', 'The installed command producer record is invalid.');
354
+ fail('commandBindingInvalid', 'The installed command producer record is invalid. Run aw command package sync.');
295
355
  }
296
356
  }
297
357
  export async function readInstalledCommandProducer(resourceRoot) {
298
- const record = normalizeInstalledCommandProducer(await readJson(resourceRoot, path.join(resourceRoot, COMMAND_PRODUCER_RECORD), 'commandBindingInvalid'));
358
+ return normalizeInstalledCommandProducer(await readJson(resourceRoot, path.join(resourceRoot, COMMAND_PRODUCER_RECORD), 'commandBindingInvalid'));
359
+ }
360
+ async function readPackageOwner(root, id) {
361
+ if (!isManagedCommandPackageId(id))
362
+ throw new ManagedCommandError('invalidArguments', 'A canonical package ID is required.', true);
363
+ const packageRoot = path.join(root, 'packages', id);
364
+ await safePath(root, packageRoot);
365
+ const stat = await lstatIfExists(packageRoot);
366
+ if (!stat)
367
+ fail('commandNotFound', 'The command package is not installed. Run aw command package sync.');
368
+ if (!stat.isDirectory())
369
+ fail('commandOwnerMismatch', 'The command package root must be a regular directory.');
370
+ const owner = object(await readJson(root, path.join(packageRoot, 'owner.json'), 'commandOwnerMismatch'), ['schemaVersion', 'owner', 'kind', 'producer'], 'commandOwnerMismatch');
371
+ let producer;
372
+ try {
373
+ producer = normalizeProducerIdentity(owner.producer);
374
+ }
375
+ catch {
376
+ fail('commandOwnerMismatch', 'The package owner identity is invalid.');
377
+ }
378
+ if (owner.schemaVersion !== 2 || owner.owner !== 'agent-workflows' || owner.kind !== 'plugin-command-package'
379
+ || !equal(owner.producer, producer) || getCommandPackageId(producer) !== id) {
380
+ fail('commandOwnerMismatch', 'The command package owner marker does not match its directory.');
381
+ }
382
+ return { producer, packageRoot };
383
+ }
384
+ export async function readManagedCommandPackageOwner(id, env = process.env) {
385
+ return readPackageOwner(await managedCommandRoot(env), id);
386
+ }
387
+ async function readCurrentRevision(packageRoot) {
388
+ const current = object(await readJson(packageRoot, path.join(packageRoot, 'current.json'), 'commandBindingInvalid'), ['schemaVersion', 'revision'], 'commandBindingInvalid');
389
+ if (current.schemaVersion !== 2 || typeof current.revision !== 'string' || !REVISION_ID.test(current.revision)) {
390
+ fail('commandBindingInvalid', 'The current command package revision is invalid. Run aw command package sync.');
391
+ }
392
+ return current.revision;
393
+ }
394
+ async function currentResourceRoot(owner) {
395
+ const revision = await readCurrentRevision(owner.packageRoot);
396
+ return path.join(owner.packageRoot, 'revisions', revision);
397
+ }
398
+ async function readPinnedPackage(owner, resourceRoot) {
399
+ await safePath(owner.packageRoot, resourceRoot);
400
+ const record = await readInstalledCommandProducer(resourceRoot);
401
+ if (!equal(owner.producer, record.producer))
402
+ fail('commandIdentityConflict', 'The command package revision does not match its owner.');
403
+ return { resourceRoot, record };
404
+ }
405
+ async function validateInstalledNativeTools({ resourceRoot, record }) {
299
406
  if (record.nativeTools) {
300
407
  try {
301
408
  await validateNativeToolClosureFiles(resourceRoot, record.nativeTools);
302
409
  }
303
410
  catch {
304
- fail('commandBindingInvalid', 'The installed native tool closure does not match its files. Run producer sync or reinstall.');
411
+ fail('commandBindingInvalid', 'The installed native tool closure does not match its files. Run aw command package sync.');
305
412
  }
306
413
  }
307
- return record;
308
414
  }
309
- export async function writeInstalledCommandProducer(resourceRoot, record) {
310
- await writeJson(resourceRoot, path.join(resourceRoot, COMMAND_PRODUCER_RECORD), normalizeInstalledCommandProducer(record));
415
+ async function validatePackageResources({ resourceRoot, record }) {
416
+ await validateManagedCommandResource(resourceRoot);
417
+ for (const launch of record.routes.subcommands)
418
+ await validateCommandLaunchFile(resourceRoot, launch);
419
+ if (record.routes.fallback)
420
+ await validateCommandLaunchFile(resourceRoot, record.routes.fallback);
421
+ await validateInstalledNativeTools({ resourceRoot, record });
422
+ await validateManagedCommandRuntimeConfigFiles(resourceRoot, record);
311
423
  }
312
- /** Capture the installed Native producer before replacing its canonical payload. */
313
- export async function captureManagedCommandBindingRecoveryEvidence(options) {
314
- const producer = normalizeProducerIdentity(options.producer);
315
- if (producer.kind === 'package')
316
- fail('commandOwnerMismatch', 'Binding recovery requires an installed Native Skill producer.');
317
- const root = await managedCommandRoot(options.env);
318
- const resourceRoot = path.resolve(options.resourceRoot);
319
- const record = await readInstalledCommandProducer(resourceRoot);
320
- if (!equal(record.producer, producer))
321
- fail('commandOwnerMismatch', 'The installed producer does not match the recovery request.');
322
- await assertManagedCommandProducerOwnership(producer, resourceRoot, options.env);
323
- const identities = new Map();
324
- for (const set of record.sets)
325
- for (const entry of set.entries) {
326
- await validateManagedCommandResource(resourceRoot, entry);
327
- const identity = { schemaVersion: 2, producer, set: set.set, key: entry.key, variant: entry.variant };
328
- identities.set(getPluginCommandId(identity), identity);
329
- }
330
- return { [bindingRecoveryIdentities]: { root, identities } };
331
- }
332
- async function readBinding(root, id) {
333
- const bindingPath = path.join(root, 'bindings', `${id}.json`);
334
- await safePath(root, bindingPath);
335
- if (!(await fs.lstat(bindingPath)).isFile())
336
- fail('commandBindingInvalid', 'The command binding must be a regular file.');
337
- const content = await fs.readFile(bindingPath, 'utf8');
338
- let parsed;
424
+ function assertExpectedProducer(expected, actual) {
425
+ if (!equal(expected, actual))
426
+ fail('commandIdentityConflict', 'The command package belongs to a different source or plugin.');
427
+ }
428
+ export async function readManagedCommandPackage(producer, env = process.env, options = {}) {
429
+ const id = getCommandPackageId(producer);
430
+ let owner;
339
431
  try {
340
- parsed = JSON.parse(content);
432
+ owner = await readManagedCommandPackageOwner(id, env);
341
433
  }
342
434
  catch (error) {
343
- if (error instanceof SyntaxError)
344
- throw new DamagedCommandBindingError();
435
+ if (error instanceof ManagedCommandError && error.code === 'commandNotFound')
436
+ return undefined;
345
437
  throw error;
346
438
  }
347
- const value = object(parsed, ['schemaVersion', 'id', 'identity', 'resourceRoot'], 'commandBindingInvalid');
348
- let identity;
349
- try {
350
- identity = normalizeCommandIdentity(value.identity);
351
- }
352
- catch {
353
- fail('commandBindingInvalid', 'The command binding identity is invalid.');
354
- }
355
- if (value.schemaVersion !== 1 || value.id !== id || getPluginCommandId(identity) !== id || typeof value.resourceRoot !== 'string' || !path.isAbsolute(value.resourceRoot))
356
- fail('commandIdentityConflict', 'The command binding does not match its identity.');
357
- return { schemaVersion: 1, id, identity, resourceRoot: value.resourceRoot };
439
+ assertExpectedProducer(producer, owner.producer);
440
+ const pinned = await readPinnedPackage(owner, await currentResourceRoot(owner));
441
+ if (options.validateFiles !== false)
442
+ await validatePackageResources(pinned);
443
+ return pinned;
358
444
  }
359
- async function entriesAt(directory) {
445
+ function packageView(owner, packageId, record, resourceRoot = null) {
446
+ const selector = `${owner.producer.sourceId}/${owner.producer.pluginName}`;
447
+ const routes = record?.routes ?? null;
448
+ return {
449
+ selector, packageId, owner: { kind: 'plugin', producer: owner.producer },
450
+ pluginVersion: record?.pluginVersion ?? null,
451
+ sourceContentDigest: record?.sourceContentDigest ?? null,
452
+ availability: routes ? (routes.subcommands.length || routes.fallback ? 'ready' : 'empty') : 'unavailable',
453
+ resourceRoot,
454
+ routes,
455
+ subcommands: routes?.subcommands.map((entry) => entry.name) ?? [],
456
+ hasFallback: routes?.fallback !== undefined,
457
+ runtimeConfigPlatforms: record?.runtimeConfigPlatforms ?? [],
458
+ nativeTools: record?.nativeTools ?? null,
459
+ errors: [],
460
+ recoveryActions: [],
461
+ };
462
+ }
463
+ async function inspectOwnedPackage(owner, id) {
464
+ let pinned;
465
+ let resourceRoot = null;
360
466
  try {
361
- return await fs.readdir(directory);
467
+ resourceRoot = await currentResourceRoot(owner);
468
+ pinned = await readPinnedPackage(owner, resourceRoot);
469
+ await validatePackageResources(pinned);
470
+ return packageView(owner, id, pinned.record, resourceRoot);
362
471
  }
363
472
  catch (error) {
364
- if (error.code === 'ENOENT')
365
- return [];
366
- throw error;
473
+ const view = packageView(owner, id, pinned?.record, resourceRoot);
474
+ view.availability = 'unavailable';
475
+ view.errors.push(managedCommandDiagnostic(error));
476
+ view.recoveryActions.push(`aw command package sync ${view.selector}`, `aw command package remove ${id} --force --yes`);
477
+ return view;
367
478
  }
368
479
  }
369
- export async function revokeManagedCommandBindings(producer, env = process.env) {
370
- producer = normalizeProducerIdentity(producer);
371
- const root = await managedCommandRoot(env);
372
- const removed = [];
373
- await safePath(root, path.join(root, 'bindings'));
374
- for (const file of await entriesAt(path.join(root, 'bindings'))) {
375
- if (!/^cmdp_[0-9a-f]{16}\.json$/u.test(file))
376
- continue;
377
- const id = file.slice(0, -5);
378
- try {
379
- const binding = await readBinding(root, id);
380
- if (!equal(binding.identity.producer, producer))
381
- continue;
382
- await fs.unlink(path.join(root, 'bindings', file));
383
- removed.push(id);
384
- }
385
- catch { /* Corrupt indexes cannot authorize removal of other producers. */ }
386
- }
387
- return removed;
388
- }
389
- async function prepareManagedCommandIdentities(root, records, bindingRecoveryEvidence = []) {
390
- const candidates = new Map();
391
- for (const record of records)
392
- for (const set of record.sets)
393
- for (const entry of set.entries) {
394
- const identity = { schemaVersion: 2, producer: record.producer, set: set.set, key: entry.key, variant: entry.variant };
395
- const id = getPluginCommandId(identity);
396
- const candidate = candidates.get(id);
397
- if (candidate && !equal(candidate, identity))
398
- fail('commandIdentityConflict', 'commandIdentityConflict: the command ID already belongs to another identity.');
399
- const existingPath = path.join(root, 'bindings', `${id}.json`);
400
- const stats = await fs.lstat(existingPath).catch((error) => {
401
- if (error.code === 'ENOENT')
402
- return null;
403
- throw error;
404
- });
405
- if (stats) {
406
- try {
407
- const existing = await readBinding(root, id);
408
- if (!equal(existing.identity, identity))
409
- fail('commandIdentityConflict', 'commandIdentityConflict: the command ID already belongs to another identity.');
410
- }
411
- catch (error) {
412
- // Only malformed JSON can use the old canonical producer's exact identity.
413
- // Path, I/O and readable identity conflicts still stop publication.
414
- if (!(error instanceof DamagedCommandBindingError)
415
- || !bindingRecoveryEvidence.some((evidence) => {
416
- const verified = evidence[bindingRecoveryIdentities];
417
- return verified?.root === root && equal(verified.identities.get(id), identity);
418
- }))
419
- throw error;
420
- }
421
- }
422
- candidates.set(id, identity);
423
- }
424
- return candidates;
480
+ export async function readManagedCommandPackageView(id, env = process.env) {
481
+ return inspectOwnedPackage(await readManagedCommandPackageOwner(id, env), id);
425
482
  }
426
- export async function assertManagedCommandBindingIdentities(options) {
427
- if (options.producers.length === 0)
428
- return;
429
- const records = options.producers.map((record) => normalizeInstalledCommandProducer({ schemaVersion: 1, producer: record.producer, sets: record.sets, ...(record.nativeTools ? { nativeTools: record.nativeTools } : {}) }));
430
- await prepareManagedCommandIdentities(await managedCommandRoot(options.env), records, options.bindingRecoveryEvidence);
483
+ // Hash only the live pointer and its revision. Unreachable staging and old revisions are not publication evidence.
484
+ export async function captureManagedCommandPackageEvidence(view, env = process.env, options = {}) {
485
+ const owner = await readManagedCommandPackageOwner(view.packageId, env);
486
+ assertExpectedProducer(view.owner.producer, owner.producer);
487
+ return capturePackageEvidence(owner, { reviewedRoot: view.resourceRoot, force: options.force });
431
488
  }
432
- export async function publishManagedCommandBindings(options) {
433
- const record = normalizeInstalledCommandProducer({ schemaVersion: 1, producer: options.producer, sets: options.sets, ...(options.nativeTools ? { nativeTools: options.nativeTools } : {}) });
434
- const root = await managedCommandRoot(options.env);
435
- const resourceRoot = path.resolve(options.resourceRoot);
436
- for (const set of record.sets)
437
- for (const entry of set.entries)
438
- await validateManagedCommandResource(resourceRoot, entry);
439
- const candidates = await prepareManagedCommandIdentities(root, [record], options.bindingRecoveryEvidence);
440
- if (record.nativeTools)
441
- await validateNativeToolClosureFiles(resourceRoot, record.nativeTools);
442
- await assertManagedCommandProducerOwnership(record.producer, resourceRoot, options.env);
443
- let previous;
444
- const recordPath = path.join(resourceRoot, COMMAND_PRODUCER_RECORD);
445
- await safePath(resourceRoot, recordPath);
446
- const recordStats = await fs.lstat(recordPath).catch((error) => { if (error.code === 'ENOENT')
447
- return null; throw error; });
448
- if (recordStats) {
449
- if (!recordStats.isFile())
450
- fail('commandBindingInvalid', 'The installed producer record must be a regular file.');
451
- const content = await fs.readFile(recordPath, 'utf8');
489
+ async function capturePackageEvidence(owner, options = {}) {
490
+ const { packageRoot } = owner;
491
+ async function observedResourceRoot() {
452
492
  try {
453
- previous = normalizeInstalledCommandProducer(JSON.parse(content));
493
+ return await currentResourceRoot(owner);
454
494
  }
455
495
  catch (error) {
456
- if (!(error instanceof SyntaxError) && (!(error instanceof ManagedCommandError) || error.code !== 'commandBindingInvalid'))
457
- throw error;
496
+ if (error instanceof ManagedCommandError)
497
+ return null;
498
+ throw error;
458
499
  }
459
500
  }
460
- if (previous && !equal(previous.producer, record.producer))
461
- fail('commandIdentityConflict', 'The resource root already contains another complete producer identity.');
462
- await writeInstalledCommandProducer(resourceRoot, record);
463
- await revokeManagedCommandBindings(record.producer, options.env);
464
- for (const [id, identity] of candidates)
465
- await writeJson(root, path.join(root, 'bindings', `${id}.json`), { schemaVersion: 1, id, identity, resourceRoot });
466
- return [...candidates.keys()];
467
- }
468
- export async function readManagedCommandPackageOwner(id, env = process.env) {
469
- if (!PACKAGE_ID.test(id))
470
- throw new ManagedCommandError('invalidArguments', 'A canonical package ID is required.', true);
501
+ const resourceRoot = await observedResourceRoot();
502
+ if (options.reviewedRoot !== undefined && resourceRoot !== options.reviewedRoot)
503
+ fail('operationReviewStale', 'The reviewed command package revision changed. Run the operation again.');
504
+ const hash = crypto.createHash('sha256');
505
+ const add = (fields) => hash.update(JSON.stringify(fields)).update('\n');
506
+ const modeMask = process.platform === 'win32' ? 0o200 : 0o777;
507
+ async function visit(file, descend) {
508
+ const relative = path.relative(packageRoot, file).split(path.sep).join('/');
509
+ const stat = await lstatIfExists(file);
510
+ if (!stat)
511
+ add(['missing', relative]);
512
+ else if (stat.isSymbolicLink())
513
+ add(['symlink', relative, await fs.readlink(file)]);
514
+ else if (stat.isDirectory()) {
515
+ add(['directory', relative, stat.mode & modeMask, ...(descend ? [] : [stat.dev, stat.ino])]);
516
+ if (descend)
517
+ for (const name of (await fs.readdir(file)).sort())
518
+ await visit(path.join(file, name), true);
519
+ }
520
+ else if (stat.isFile()) {
521
+ try {
522
+ add(['file', relative, stat.mode & modeMask, await calculateFileDigest(file)]);
523
+ }
524
+ catch (error) {
525
+ if (!options.force || relative !== 'current.json')
526
+ throw error;
527
+ // The owner still authorizes deletion if the weak pointer itself is unreadable.
528
+ add(['unreadable', relative, stat.mode, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs]);
529
+ }
530
+ }
531
+ else
532
+ add(['special', relative, stat.mode, stat.ino]);
533
+ }
534
+ add([options.force ? 'owner-and-pointer' : 'revision']);
535
+ await visit(packageRoot, false);
536
+ await visit(path.join(packageRoot, 'owner.json'), false);
537
+ await visit(path.join(packageRoot, 'current.json'), false);
538
+ if (resourceRoot && !options.force) {
539
+ const revisions = path.dirname(resourceRoot);
540
+ const stat = await lstatIfExists(revisions);
541
+ await visit(stat?.isDirectory() ? resourceRoot : revisions, true);
542
+ }
543
+ if (await observedResourceRoot() !== resourceRoot)
544
+ fail('operationReviewStale', 'The reviewed command package revision changed. Run the operation again.');
545
+ return { packageDigest: `sha256:${hash.digest('hex')}` };
546
+ }
547
+ async function assertExpectedPackage(root, id, producer, expected, force = false) {
548
+ let owner;
549
+ try {
550
+ owner = await readPackageOwner(root, id);
551
+ }
552
+ catch (error) {
553
+ if (!(error instanceof ManagedCommandError) || error.code !== 'commandNotFound')
554
+ throw error;
555
+ }
556
+ if (owner)
557
+ assertExpectedProducer(producer, owner.producer);
558
+ if (expected === undefined)
559
+ return owner;
560
+ const current = owner ? await capturePackageEvidence(owner, { force }) : null;
561
+ if (!equal(current, expected))
562
+ fail('operationReviewStale', 'The reviewed command package changed before publication or removal.');
563
+ return owner;
564
+ }
565
+ /** Called with the AW_HOME mutation lock held. */
566
+ export async function removeManagedCommandPackage(id, env = process.env, options = {}) {
471
567
  const root = await managedCommandRoot(env);
472
- const packageRoot = path.join(root, 'packages', id);
473
- const owner = object(await readJson(root, path.join(packageRoot, 'owner.json'), 'commandOwnerMismatch'), ['schemaVersion', 'owner', 'kind', 'producer'], 'commandOwnerMismatch');
474
- let producer;
568
+ const owner = await readPackageOwner(root, id);
569
+ const verified = await assertExpectedPackage(root, id, owner.producer, options.expectedPackage, options.force);
570
+ if (!verified)
571
+ fail('commandNotFound', 'The command package is no longer installed.');
572
+ if (!options.force && (await inspectOwnedPackage(verified, id)).availability === 'unavailable') {
573
+ fail('commandPackageUnavailable', 'The command package is damaged. Review and repeat package remove with --force.');
574
+ }
575
+ // Keep independent ownership evidence until all potentially busy revisions are gone.
475
576
  try {
476
- producer = normalizeProducerIdentity(owner.producer);
577
+ for (const name of await fs.readdir(verified.packageRoot)) {
578
+ if (name !== 'owner.json')
579
+ await fs.rm(path.join(verified.packageRoot, name), { recursive: true, force: true });
580
+ }
581
+ await fs.unlink(path.join(verified.packageRoot, 'owner.json'));
582
+ await fs.rmdir(verified.packageRoot);
477
583
  }
478
584
  catch {
479
- fail('commandOwnerMismatch', 'The package owner identity is invalid.');
585
+ fail('commandPackageRemovalFailed', `Could not finish removing the command package. Release its files and retry aw command package remove ${id} --force --yes.`);
480
586
  }
481
- if (owner.schemaVersion !== 1 || owner.owner !== 'agent-workflows' || owner.kind !== 'plugin-command-package' || producer.kind !== 'package' || getCommandPackageId(producer) !== id)
482
- fail('commandOwnerMismatch', 'The package owner marker does not match its directory.');
483
- return { producer, resourceRoot: path.join(packageRoot, 'resource') };
484
- }
485
- export async function removeManagedCommandPackage(id, env = process.env) {
486
- const { producer } = await readManagedCommandPackageOwner(id, env);
487
- const root = await managedCommandRoot(env);
488
- const removedCommandIds = await revokeManagedCommandBindings(producer, env);
489
- await fs.rm(path.join(root, 'packages', id), { recursive: true, force: true });
490
- return { producer, removedCommandIds };
587
+ return { producer: verified.producer };
491
588
  }
589
+ /** Called with the AW_HOME mutation lock held. */
492
590
  export async function syncManagedCommandPackage(options) {
591
+ const env = options.env ?? process.env;
592
+ const root = await managedCommandRoot(env);
493
593
  const producer = normalizeProducerIdentity(options.producer);
494
- if (producer.kind !== 'package')
495
- fail('commandOwnerMismatch', 'A package producer is required.');
496
- const root = await managedCommandRoot(options.env);
594
+ const record = normalizeInstalledCommandProducer(options.record);
595
+ assertExpectedProducer(producer, record.producer);
497
596
  const id = getCommandPackageId(producer);
498
- const packagesRoot = path.join(root, 'packages');
499
- await ensureRegularDirectoryPath(packagesRoot, 'Managed command packages');
500
- const packageRoot = path.join(packagesRoot, id);
501
- const staging = path.join(packagesRoot, `.${id}.${crypto.randomUUID()}.tmp`);
502
- if (await fs.lstat(packageRoot).catch(() => null))
503
- await readManagedCommandPackageOwner(id, options.env);
504
- await ensureRegularDirectoryPath(staging, 'Managed command package staging');
597
+ const packageRoot = path.join(root, 'packages', id);
598
+ await ensureRegularDirectoryPath(path.dirname(packageRoot), 'Managed command packages');
599
+ const revision = crypto.randomUUID();
600
+ const staging = await fs.mkdtemp(path.join(path.dirname(packageRoot), `.${id}.`));
601
+ const stagedRevision = path.join(staging, 'revisions', revision);
602
+ const resourceRoot = path.join(packageRoot, 'revisions', revision);
603
+ let unpublishedRevision;
505
604
  try {
506
- const resourceRoot = path.join(staging, 'resource');
507
- await copyManagedCommandDirectory(options.sourceDirectory, resourceRoot, options.env);
508
- const record = normalizeInstalledCommandProducer({ schemaVersion: 1, producer, sets: options.sets, ...(options.nativeTools ? { nativeTools: options.nativeTools } : {}) });
509
- for (const set of record.sets)
510
- for (const entry of set.entries)
511
- await validateManagedCommandResource(resourceRoot, entry);
512
- await prepareManagedCommandIdentities(root, [record]);
513
- if (record.nativeTools)
514
- await validateNativeToolClosureFiles(resourceRoot, record.nativeTools);
515
- await writeInstalledCommandProducer(resourceRoot, record);
516
- await writeJson(root, path.join(staging, 'owner.json'), { schemaVersion: 1, owner: 'agent-workflows', kind: 'plugin-command-package', producer });
517
- if (options.expectedPackage) {
518
- const current = await fs.lstat(packageRoot).catch((error) => {
519
- if (error.code === 'ENOENT')
520
- return null;
521
- throw error;
522
- });
523
- if (!current)
524
- fail('configApplyRequiresExistingOutput', 'The reviewed command package is no longer installed. Run package sync first.');
525
- const view = await readManagedCommandPackageView(id, options.env ?? process.env);
526
- const evidence = await captureManagedCommandPackageEvidence(view, options.env);
527
- if (!equal(evidence, options.expectedPackage))
528
- fail('operationReviewStale', 'The reviewed command package changed before publication.');
605
+ await copyManagedCommandDirectory(options.sourceDirectory, stagedRevision, env, { trustedPluginSource: true });
606
+ if (options.expectedResourceDigest !== undefined
607
+ && await calculateManagedCommandResourceDigest(stagedRevision) !== options.expectedResourceDigest) {
608
+ fail('operationReviewStale', 'The prepared command package files changed after review. Run the operation again.');
529
609
  }
530
- const removed = await revokeManagedCommandBindings(producer, options.env);
531
- if (await fs.lstat(packageRoot).catch(() => null)) {
532
- await readManagedCommandPackageOwner(id, options.env);
533
- await fs.rm(packageRoot, { recursive: true, force: true });
610
+ await writeJson(stagedRevision, path.join(stagedRevision, COMMAND_PRODUCER_RECORD), record);
611
+ await validatePackageResources({ resourceRoot: stagedRevision, record });
612
+ const pointer = { schemaVersion: 2, revision };
613
+ const owner = await assertExpectedPackage(root, id, producer, options.expectedPackage);
614
+ if (owner) {
615
+ await ensureRegularDirectoryPath(path.dirname(resourceRoot), 'Managed command revisions');
616
+ await fs.rename(stagedRevision, resourceRoot);
617
+ unpublishedRevision = resourceRoot;
618
+ // Readers pin this pointer once. Earlier revisions can be removed only after the switch.
619
+ await writeJson(packageRoot, path.join(packageRoot, 'current.json'), pointer);
620
+ unpublishedRevision = undefined;
621
+ }
622
+ else {
623
+ await writeJson(staging, path.join(staging, 'owner.json'), { schemaVersion: 2, owner: 'agent-workflows', kind: 'plugin-command-package', producer });
624
+ await writeJson(staging, path.join(staging, 'current.json'), pointer);
625
+ if (await lstatIfExists(packageRoot))
626
+ fail('operationReviewStale', 'The command package directory appeared before publication. Run the operation again.');
627
+ await fs.rename(staging, packageRoot);
534
628
  }
535
- await fs.rename(staging, packageRoot);
536
- const installedRoot = path.join(packageRoot, 'resource');
537
- const commandIds = await publishManagedCommandBindings({ producer, resourceRoot: installedRoot, sets: record.sets, nativeTools: record.nativeTools, env: options.env });
538
- return { id, resourceRoot: installedRoot, commandIds, removedCommandIds: removed.filter((commandId) => !commandIds.includes(commandId)) };
539
629
  }
540
630
  finally {
541
- await safePath(root, staging);
542
- await fs.rm(staging, { recursive: true, force: true });
543
- }
544
- }
545
- export async function assertManagedCommandProducerOwnership(producer, resourceRoot, env = process.env) {
546
- if (producer.kind === 'package') {
547
- const owned = await readManagedCommandPackageOwner(getCommandPackageId(producer), env);
548
- if (!equal(owned.producer, producer) || owned.resourceRoot !== resourceRoot)
549
- fail('commandOwnerMismatch', 'The command package root does not match its owner.');
550
- return;
631
+ for (const directory of [staging, ...(unpublishedRevision ? [unpublishedRevision] : [])]) {
632
+ try {
633
+ await safePath(root, directory);
634
+ await fs.rm(directory, { recursive: true, force: true });
635
+ }
636
+ catch { /* Best effort for a private, unpublished directory. */ }
637
+ }
551
638
  }
639
+ const errors = [];
552
640
  try {
553
- await verifyManagedCommandArtifactEvidence({ producer, resourceRoot, env });
641
+ for (const name of await entriesAt(path.dirname(resourceRoot))) {
642
+ if (name === revision || !REVISION_ID.test(name))
643
+ continue;
644
+ const oldRoot = path.join(path.dirname(resourceRoot), name);
645
+ try {
646
+ await safePath(root, oldRoot);
647
+ if ((await lstatIfExists(oldRoot))?.isDirectory())
648
+ await fs.rm(oldRoot, { recursive: true, force: true });
649
+ }
650
+ catch (error) {
651
+ errors.push(managedCommandDiagnostic(error, name));
652
+ }
653
+ }
554
654
  }
555
- catch {
556
- fail('commandOwnerMismatch', 'The command producer has no matching live ownership or native receipt evidence.');
655
+ catch (error) {
656
+ errors.push(managedCommandDiagnostic(error));
557
657
  }
658
+ return { id, resourceRoot, errors, recoveryActions: errors.length ? [`aw command package sync ${producer.sourceId}/${producer.pluginName}`] : [] };
558
659
  }
559
- export async function resolveManagedCommand(id, env = process.env) {
560
- if (!isManagedCommandId(id))
561
- throw new ManagedCommandError('invalidArguments', 'A canonical managed command ID is required.', true);
660
+ async function resolveUserCommand(id, env) {
562
661
  const root = await managedCommandRoot(env);
563
- if (USER_ID.test(id)) {
564
- if (!(await fs.lstat(path.join(root, 'users', id)).catch(() => null)))
565
- fail('commandNotFound', 'The command ID is not installed.');
566
- const definition = await readUserCommandDefinition(id, env);
567
- const resourceRoot = path.join(root, 'users', id, 'packages', definition.packageRevision);
568
- await safePath(root, resourceRoot);
569
- await validateManagedCommandResource(resourceRoot, definition.launch);
570
- return { resourceRoot, launch: definition.launch, view: { id, name: definition.name, owner: { kind: 'user' }, availability: 'ready', resourceRoot, launch: definition.launch, errors: [], recoveryActions: [] } };
571
- }
572
- if (!(await fs.lstat(path.join(root, 'bindings', `${id}.json`)).catch(() => null)))
573
- fail('commandNotFound', 'The command binding is missing. Use sync, reinstall, or package sync.');
574
- const binding = await readBinding(root, id);
575
- await assertManagedCommandProducerOwnership(binding.identity.producer, binding.resourceRoot, env);
576
- const record = await readInstalledCommandProducer(binding.resourceRoot);
577
- if (!equal(record.producer, binding.identity.producer))
578
- fail('commandIdentityConflict', 'The installed producer does not match the command binding.');
579
- const set = record.sets.find((candidate) => candidate.set === binding.identity.set && candidate.state === 'present');
580
- const entry = set?.entries.find((candidate) => candidate.key === binding.identity.key && candidate.variant === binding.identity.variant);
581
- if (!entry)
582
- fail('commandBindingInvalid', 'The command is absent or disabled in the installed producer.');
583
- const { key: _key, variant: _variant, ...launch } = entry;
584
- await validateManagedCommandResource(binding.resourceRoot, launch);
585
- return { resourceRoot: binding.resourceRoot, launch, producer: record, set: binding.identity.set, view: { id, name: `${binding.identity.set}/${entry.key}/${entry.variant}`, owner: { kind: 'plugin', producer: record.producer }, availability: 'ready', resourceRoot: binding.resourceRoot, launch, errors: [], recoveryActions: [] } };
586
- }
587
- export async function inspectManagedCommand(id, env = process.env) {
662
+ const definition = await readUserCommandDefinition(id, env);
663
+ const resourceRoot = path.join(root, 'users', id, 'packages', definition.packageRevision);
664
+ await safePath(root, resourceRoot);
665
+ await validateManagedCommandResource(resourceRoot, definition.launch);
666
+ return { resourceRoot, launch: definition.launch, view: { id, name: definition.name, owner: { kind: 'user' }, availability: 'ready', resourceRoot, launch: definition.launch, errors: [], recoveryActions: [] } };
667
+ }
668
+ async function inspectUserCommand(id, env) {
588
669
  try {
589
- return (await resolveManagedCommand(id, env)).view;
670
+ return (await resolveUserCommand(id, env)).view;
590
671
  }
591
672
  catch (error) {
592
673
  if (error instanceof ManagedCommandError && (error.code === 'commandNotFound' || error.argumentError))
593
674
  throw error;
594
675
  const root = await managedCommandRoot(env);
595
- let owner;
676
+ const userRoot = await assertUserOwner(root, id);
596
677
  let name = id;
597
678
  let resourceRoot = null;
598
679
  let launch = null;
599
- if (USER_ID.test(id)) {
600
- await assertUserOwner(root, id);
601
- owner = { kind: 'user' };
602
- try {
603
- const definition = await readUserCommandDefinition(id, env);
604
- name = definition.name;
605
- launch = definition.launch;
606
- resourceRoot = path.join(root, 'users', id, 'packages', definition.packageRevision);
607
- }
608
- catch { /* Owner evidence still permits a diagnostic view and safe removal. */ }
609
- }
610
- else {
611
- const binding = await readBinding(root, id);
612
- owner = { kind: 'plugin', producer: binding.identity.producer };
613
- name = `${binding.identity.set}/${binding.identity.key}/${binding.identity.variant}`;
614
- resourceRoot = binding.resourceRoot;
615
- }
616
- return { id, name, owner, availability: 'unavailable', resourceRoot, launch, errors: [managedCommandDiagnostic(error)], recoveryActions: [owner.kind === 'user' ? `aw command remove ${id} --force --yes` : 'Run producer sync, reinstall, or package sync.'] };
617
- }
618
- }
619
- async function readManagedCommandPackageView(id, env) {
620
- const { producer, resourceRoot } = await readManagedCommandPackageOwner(id, env);
621
- const view = { id, producer, resourceRoot, availability: 'unavailable', sets: [], errors: [], recoveryActions: [] };
622
- try {
623
- const record = await readInstalledCommandProducer(resourceRoot);
624
- if (!equal(record.producer, producer))
625
- fail('commandIdentityConflict', 'The package content and owner identities differ.');
626
- await validateManagedCommandResource(resourceRoot);
627
- view.sets = record.sets.map((set) => ({ set: set.set, state: set.state, commandIds: set.entries.map((entry) => getPluginCommandId({ schemaVersion: 2, producer, set: set.set, key: entry.key, variant: entry.variant })) }));
628
- for (const set of view.sets)
629
- for (const commandId of set.commandIds)
630
- await resolveManagedCommand(commandId, env);
631
- view.availability = view.sets.some((set) => set.commandIds.length) ? 'ready' : 'empty';
632
- }
633
- catch (error) {
634
- view.errors.push(managedCommandDiagnostic(error));
635
- view.recoveryActions.push(`aw command package remove ${id} --force --yes`, 'Run package sync.');
636
- }
637
- return view;
638
- }
639
- export async function captureManagedCommandPackageEvidence(view, env = process.env) {
640
- const packageRoot = path.dirname(view.resourceRoot);
641
- const commandsRoot = await managedCommandRoot(env);
642
- await safePath(commandsRoot, packageRoot);
643
- const rootStat = await fs.lstat(packageRoot);
644
- if (!rootStat.isDirectory())
645
- fail('commandOwnerMismatch', 'The command package root must be a regular directory.');
646
- const hash = crypto.createHash('sha256');
647
- const add = (fields) => hash.update(JSON.stringify(fields)).update('\n');
648
- // Windows chmod supports the writable bit. POSIX publication can restore all permission bits.
649
- const modeMask = process.platform === 'win32' ? 0o200 : 0o777;
650
- add(['directory', '', rootStat.mode & modeMask]);
651
- async function visit(directory) {
652
- for (const name of (await fs.readdir(directory)).sort()) {
653
- const file = path.join(directory, name);
654
- const relative = path.relative(packageRoot, file).split(path.sep).join('/');
655
- const stat = await fs.lstat(file);
656
- if (stat.isDirectory()) {
657
- add(['directory', relative, stat.mode & modeMask]);
658
- await visit(file);
659
- }
660
- else if (stat.isFile()) {
661
- add(['file', relative, stat.mode & modeMask, await calculateFileDigest(file)]);
662
- }
663
- else if (stat.isSymbolicLink()) {
664
- add(['symlink', relative, await fs.readlink(file)]);
665
- }
666
- else
667
- fail('commandResourceInvalid', 'Command packages cannot contain special nodes.');
668
- }
669
- }
670
- await visit(packageRoot);
671
- // A single missing binding makes the whole package unavailable. Keep each installed entry distinguishable.
672
- const record = await readInstalledCommandProducer(view.resourceRoot);
673
- if (!equal(record.producer, view.producer))
674
- fail('commandIdentityConflict', 'The package content and owner identities differ.');
675
- for (const set of record.sets)
676
- for (const entry of set.entries) {
677
- const id = getPluginCommandId({ schemaVersion: 2, producer: record.producer, set: set.set, key: entry.key, variant: entry.variant });
678
- try {
679
- const binding = await readBinding(commandsRoot, id);
680
- const stat = await fs.lstat(path.join(commandsRoot, 'bindings', id + '.json'));
681
- add(['binding', id, binding, stat.mode & modeMask]);
682
- }
683
- catch (error) {
684
- if (error.code === 'ENOENT')
685
- add(['missingBinding', id]);
686
- else if (error instanceof ManagedCommandError)
687
- add(['invalidBinding', id, error.code]);
688
- else
689
- throw error;
690
- }
680
+ try {
681
+ const definition = await readUserCommandDefinition(id, env);
682
+ name = definition.name;
683
+ launch = definition.launch;
684
+ resourceRoot = path.join(userRoot, 'packages', definition.packageRevision);
691
685
  }
692
- return { availability: view.availability, packageDigest: `sha256:${hash.digest('hex')}` };
686
+ catch { /* Owner evidence still permits a diagnostic view and safe removal. */ }
687
+ return { id, name, owner: { kind: 'user' }, availability: 'unavailable', resourceRoot, launch, errors: [managedCommandDiagnostic(error)], recoveryActions: [`aw command remove ${id} --force --yes`] };
688
+ }
689
+ }
690
+ async function lookupNamedPackage(selector, env) {
691
+ const producer = await resolvePluginCommandProducer(selector, env);
692
+ const packageId = getCommandPackageId(producer);
693
+ const owner = await readManagedCommandPackageOwner(packageId, env);
694
+ assertExpectedProducer(producer, owner.producer);
695
+ return { packageId, owner };
696
+ }
697
+ export async function resolveManagedCommand(selector, env = process.env, options = { args: [] }) {
698
+ if (isUserCommandId(selector)) {
699
+ if (options.noFallback)
700
+ throw new ManagedCommandError('invalidArguments', '--no-fallback requires a plugin command and a subcommand argument.', true);
701
+ return { ...await resolveUserCommand(selector, env), args: options.args };
702
+ }
703
+ if (options.noFallback && options.args.length === 0) {
704
+ throw new ManagedCommandError('invalidArguments', '--no-fallback requires a subcommand argument.', true);
705
+ }
706
+ const { packageId, owner } = await lookupNamedPackage(selector, env);
707
+ const pinned = await readPinnedPackage(owner, await currentResourceRoot(owner));
708
+ const { resourceRoot, record } = pinned;
709
+ const subcommand = record.routes.subcommands.find((entry) => entry.name === options.args[0]);
710
+ const fallback = options.noFallback ? undefined : record.routes.fallback;
711
+ let launch;
712
+ if (subcommand) {
713
+ const { name: _name, ...selected } = subcommand;
714
+ launch = selected;
715
+ }
716
+ else if (fallback) {
717
+ launch = fallback;
718
+ }
719
+ else {
720
+ const names = record.routes.subcommands.map((entry) => entry.name);
721
+ const hint = names.length ? `Available subcommands: ${names.join(', ')}.` : 'There are no enabled subcommands.';
722
+ throw new ManagedCommandError('commandRouteNotFound', `No command route matched ${selector}. ${hint}`, true);
723
+ }
724
+ await validateManagedCommandResource(resourceRoot, launch);
725
+ await validateInstalledNativeTools(pinned);
726
+ return { view: packageView(owner, packageId, record, resourceRoot), launch, resourceRoot, producer: record, args: subcommand ? options.args.slice(1) : options.args };
727
+ }
728
+ export async function inspectManagedCommand(selector, env = process.env) {
729
+ if (isUserCommandId(selector))
730
+ return inspectUserCommand(selector, env);
731
+ const { packageId, owner } = await lookupNamedPackage(selector, env);
732
+ return inspectOwnedPackage(owner, packageId);
693
733
  }
694
734
  export async function listManagedCommandPackages(env = process.env) {
695
735
  const root = await managedCommandRoot(env);
696
736
  const packages = [];
737
+ const orphanedPackages = [];
697
738
  const errors = [];
698
- await safePath(root, path.join(root, 'packages'));
699
- for (const id of (await entriesAt(path.join(root, 'packages'))).sort()) {
700
- if (!PACKAGE_ID.test(id)) {
739
+ const directory = path.join(root, 'packages');
740
+ await safePath(root, directory);
741
+ const ids = (await entriesAt(directory)).sort();
742
+ let sources;
743
+ let sourceError;
744
+ if (ids.some(isManagedCommandPackageId)) {
745
+ try {
746
+ sources = await readConfiguredSources(env);
747
+ }
748
+ catch (error) {
749
+ sourceError = managedCommandDiagnostic(error);
750
+ errors.push(sourceError);
751
+ }
752
+ }
753
+ for (const id of ids) {
754
+ if (!isManagedCommandPackageId(id)) {
701
755
  if (!id.startsWith('.'))
702
756
  errors.push({ code: 'commandOwnerMismatch', message: 'An unrecognized command package was retained.', subject: `commands/packages/${id}` });
703
757
  continue;
704
758
  }
705
759
  try {
706
- packages.push(await readManagedCommandPackageView(id, env));
760
+ const owner = await readPackageOwner(root, id);
761
+ const view = await inspectOwnedPackage(owner, id);
762
+ if (sources?.get(owner.producer.sourceId) === owner.producer.sourceIdentity) {
763
+ packages.push(view);
764
+ }
765
+ else {
766
+ const wasDamaged = view.availability === 'unavailable';
767
+ view.availability = 'unavailable';
768
+ view.errors.push(sourceError ?? { code: 'commandNotFound', message: 'This command package belongs to a source that was removed or changed.' });
769
+ view.recoveryActions = [`aw command package remove ${id}${wasDamaged ? ' --force' : ''} --yes`];
770
+ orphanedPackages.push(view);
771
+ }
707
772
  }
708
773
  catch (error) {
709
774
  errors.push(managedCommandDiagnostic(error, `commands/packages/${id}`));
710
775
  }
711
776
  }
712
- return { packages, errors };
777
+ return { packages, orphanedPackages, errors };
713
778
  }
714
779
  export async function listManagedCommands(env = process.env) {
715
780
  const root = await managedCommandRoot(env);
716
781
  const commands = [];
717
782
  const errors = [];
718
- for (const kind of ['users', 'bindings']) {
719
- await safePath(root, path.join(root, kind));
720
- for (const file of (await entriesAt(path.join(root, kind))).sort()) {
721
- const id = kind === 'bindings' ? file.replace(/\.json$/u, '') : file;
722
- if (!(kind === 'users' ? USER_ID.test(id) : /^cmdp_[0-9a-f]{16}\.json$/u.test(file))) {
723
- errors.push({ code: 'commandBindingInvalid', message: 'An unrecognized command record was retained.', subject: `commands/${kind}/${file}` });
724
- continue;
725
- }
726
- try {
727
- commands.push(await inspectManagedCommand(id, env));
728
- }
729
- catch (error) {
730
- errors.push(managedCommandDiagnostic(error, `commands/${kind}/${file}`));
731
- }
783
+ const usersRoot = path.join(root, 'users');
784
+ await safePath(root, usersRoot);
785
+ for (const id of (await entriesAt(usersRoot)).sort()) {
786
+ if (!isUserCommandId(id)) {
787
+ errors.push({ code: 'commandBindingInvalid', message: 'An unrecognized command record was retained.', subject: `commands/users/${id}` });
788
+ continue;
789
+ }
790
+ try {
791
+ commands.push(await inspectUserCommand(id, env));
792
+ }
793
+ catch (error) {
794
+ errors.push(managedCommandDiagnostic(error, `commands/users/${id}`));
732
795
  }
733
796
  }
734
- const packageResult = await listManagedCommandPackages(env);
735
- return { commands, packages: packageResult.packages, errors: [...errors, ...packageResult.errors] };
797
+ const packages = await listManagedCommandPackages(env);
798
+ return { ...packages, commands, errors: [...errors, ...packages.errors] };
736
799
  }
737
800
  //# sourceMappingURL=managed-command-store.js.map