owenloop 0.5.8 → 0.5.10

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 (131) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +81 -39
  3. package/bin/owenloop.mjs +16 -1
  4. package/dist/packages/work/src/agent/loop.d.ts +23 -8
  5. package/dist/packages/work/src/agent/loop.js +55 -6
  6. package/dist/packages/work/src/bundle/pull.d.ts +21 -0
  7. package/dist/packages/work/src/bundle/pull.js +118 -0
  8. package/dist/packages/work/src/consumed-verifier.js +6 -17
  9. package/dist/packages/work/src/exec/instructions.d.ts +4 -1
  10. package/dist/packages/work/src/exec/instructions.js +3 -0
  11. package/dist/packages/work/src/exec/loop.d.ts +2 -2
  12. package/dist/packages/work/src/exec/loop.js +273 -46
  13. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  14. package/dist/packages/work/src/exec/receipt.js +6 -6
  15. package/dist/packages/work/src/harness/claude.js +116 -0
  16. package/dist/packages/work/src/harness/codex.d.ts +8 -0
  17. package/dist/packages/work/src/harness/codex.js +27 -1
  18. package/dist/packages/work/src/harness/contract.d.ts +9 -0
  19. package/dist/packages/work/src/hub/client.d.ts +19 -4
  20. package/dist/packages/work/src/hub/client.js +7 -3
  21. package/dist/packages/work/src/hub/types.d.ts +84 -0
  22. package/dist/packages/work/src/main.js +1 -0
  23. package/dist/packages/work/src/roles/agent-run.js +57 -32
  24. package/dist/packages/work/src/roles/exec.js +27 -8
  25. package/dist/packages/work/src/roles/settings.js +2 -0
  26. package/dist/packages/work/src/roles/shift.js +14 -2
  27. package/dist/packages/work/src/roles/util.d.ts +1 -0
  28. package/dist/packages/work/src/roles/util.js +10 -0
  29. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  30. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  31. package/dist/packages/work/src/settings/roster.d.ts +84 -0
  32. package/dist/packages/work/src/settings/roster.js +364 -5
  33. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  34. package/dist/packages/work/src/settings/serving.js +79 -0
  35. package/dist/packages/work/src/settings/settings.d.ts +14 -1
  36. package/dist/packages/work/src/settings/settings.js +14 -0
  37. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  38. package/dist/packages/work/src/shift/loop.js +416 -54
  39. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  40. package/dist/packages/work/src/shift/runtime.d.ts +18 -0
  41. package/dist/packages/work/src/shift/runtime.js +104 -5
  42. package/dist/packages/work/src/shift/server.js +2 -0
  43. package/dist/packages/work/src/shift/spawn.d.ts +17 -2
  44. package/dist/packages/work/src/shift/spawn.js +16 -13
  45. package/dist/packages/work/src/shift/state.d.ts +29 -2
  46. package/dist/packages/work/src/shift/state.js +45 -15
  47. package/dist/packages/work/src/submit-proof.d.ts +11 -8
  48. package/dist/packages/work/src/submit-proof.js +11 -8
  49. package/dist/packages/work/src/usage.d.ts +1 -1
  50. package/dist/packages/work/src/usage.js +7 -1
  51. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  52. package/dist/packages/work/src/util/modifier-init.js +73 -0
  53. package/dist/src/bundle/tar.d.ts +9 -4
  54. package/dist/src/bundle/tar.js +9 -4
  55. package/dist/src/capabilities.d.ts +76 -6
  56. package/dist/src/capabilities.js +49 -6
  57. package/dist/src/capability-mapping-client.d.ts +29 -0
  58. package/dist/src/capability-mapping-client.js +160 -0
  59. package/dist/src/cli.d.ts +16 -3
  60. package/dist/src/cli.js +1925 -281
  61. package/dist/src/config-dir.d.ts +1 -1
  62. package/dist/src/config-dir.js +1 -1
  63. package/dist/src/crypto/index.d.ts +1 -1
  64. package/dist/src/crypto/index.js +1 -1
  65. package/dist/src/crypto/org-root.d.ts +30 -12
  66. package/dist/src/crypto/org-root.js +162 -14
  67. package/dist/src/crypto/records.d.ts +2 -0
  68. package/dist/src/crypto/records.js +2 -0
  69. package/dist/src/defs.d.ts +38 -2
  70. package/dist/src/defs.js +593 -86
  71. package/dist/src/engine.d.ts +103 -25
  72. package/dist/src/engine.js +331 -79
  73. package/dist/src/hub.d.ts +77 -0
  74. package/dist/src/hub.js +162 -0
  75. package/dist/src/implements.d.ts +56 -0
  76. package/dist/src/implements.js +790 -0
  77. package/dist/src/index.d.ts +11 -9
  78. package/dist/src/index.js +6 -5
  79. package/dist/src/mcp/serve.d.ts +22 -0
  80. package/dist/src/mcp/serve.js +330 -41
  81. package/dist/src/mcp/server.d.ts +10 -7
  82. package/dist/src/mcp/server.js +53 -8
  83. package/dist/src/model.d.ts +48 -10
  84. package/dist/src/model.js +252 -99
  85. package/dist/src/order-resolver.d.ts +1 -0
  86. package/dist/src/order-resolver.js +8 -1
  87. package/dist/src/schemas/index.d.ts +11 -0
  88. package/dist/src/schemas/order.v1.schema.json +7 -1
  89. package/dist/src/store/def-source.d.ts +19 -0
  90. package/dist/src/store/def-source.js +87 -17
  91. package/dist/src/store/gc-recovery.d.ts +46 -0
  92. package/dist/src/store/gc-recovery.js +258 -0
  93. package/dist/src/store/gc.d.ts +94 -0
  94. package/dist/src/store/gc.js +562 -0
  95. package/dist/src/store/index.d.ts +3 -1
  96. package/dist/src/store/index.js +2 -0
  97. package/dist/src/store/install.d.ts +34 -5
  98. package/dist/src/store/install.js +73 -11
  99. package/dist/src/store/pre-commit-verifier.js +42 -2
  100. package/dist/src/store/snapshot-guard.d.ts +18 -0
  101. package/dist/src/store/snapshot-guard.js +94 -0
  102. package/dist/src/store.d.ts +69 -4
  103. package/dist/src/store.js +254 -16
  104. package/dist/src/types.d.ts +101 -20
  105. package/dist/src/util.js +4 -1
  106. package/docs/authoring.md +235 -10
  107. package/docs/bundles.md +45 -2
  108. package/docs/cli.md +437 -55
  109. package/docs/crypto.md +32 -10
  110. package/docs/design.md +177 -47
  111. package/docs/evals/mcp-charter-baseline.json +428 -0
  112. package/docs/mcp-charter-eval.md +124 -0
  113. package/docs/routing.md +189 -34
  114. package/docs/shift-logs.md +38 -9
  115. package/docs/wire-contracts.md +78 -14
  116. package/examples/workflows/compile-dev-playbook.yaml +1 -1
  117. package/examples/workflows/delivery.yaml +31 -14
  118. package/examples/workflows/ship.yaml +38 -4
  119. package/package.json +2 -1
  120. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  121. package/plugins/claude-code/plugin/.mcp.json +1 -1
  122. package/plugins/claude-code/plugin/skills/author/SKILL.md +22 -0
  123. package/plugins/claude-code/plugin/skills/ephemeral/SKILL.md +95 -0
  124. package/plugins/claude-code/plugin/skills/graduate/SKILL.md +156 -0
  125. package/plugins/claude-code/plugin/skills/plan/SKILL.md +236 -0
  126. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  127. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  128. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +22 -0
  129. package/plugins/codex/plugins/owenloop/skills/ephemeral/SKILL.md +95 -0
  130. package/plugins/codex/plugins/owenloop/skills/graduate/SKILL.md +156 -0
  131. package/plugins/codex/plugins/owenloop/skills/plan/SKILL.md +236 -0
package/dist/src/cli.js CHANGED
@@ -27,12 +27,12 @@
27
27
  * owenloop retract <wf> <path> --by <author> --text <msg>
28
28
  * owenloop skip <wf> <path> --by <author> --text <msg>
29
29
  * owenloop retry <wf> <path> [--by <author>] [--text <guidance>] clear a stall
30
- * owenloop close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]
30
+ * owenloop close <wf> <run> [--outcome ok|no_work|released|failed|skipped] [--summary s]
31
31
  * owenloop delete <wf> [--recursive]
32
32
  *
33
- * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
33
+ * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS), --verbose.
34
34
  */
35
- import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
35
+ import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
36
36
  import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
37
37
  import { spawn, spawnSync } from 'node:child_process';
38
38
  import { createServer } from 'node:http';
@@ -42,28 +42,33 @@ import { fileURLToPath } from 'node:url';
42
42
  import { parse as parseYaml } from 'yaml';
43
43
  import { Engine } from "./engine.js";
44
44
  import { buildGraph, buildTrace, graphToDot, graphToMermaid, hasDefiniteCheckDefect, modelCheck } from "./model.js";
45
- import { openStore } from "./store.js";
46
- import { buildDef, DefError, finalizeDefs, lintDef, loadDefFile, loadDefs, loadDefsRaw, loadDefsUnfinalized, resolveCallsTarget, validateDef, } from "./defs.js";
45
+ import { openStore, readRuntimeSnapshotBundlePins } from "./store.js";
46
+ import { buildDef, DefError, finalizeDefs, lintDef, loadDefFile, loadDefs, loadDefsRaw, loadDefsUnfinalized, expandDefsRaw, reportCallsCycles, resolveCallsTarget, scanDefsRaw, validateCallsEdges, validateDef, } from "./defs.js";
47
+ import { implementsIssues } from "./implements.js";
47
48
  import { createDefInstructionSource } from "./order-resolver.js";
48
49
  import { CliError, dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
49
50
  import { packageVersion } from "./package-version.js";
50
51
  import { authHeader, deleteCredential, discoverMetadata, ensureFreshOAuth, hubFetch, hubMaxResponseBytes, mintAgentCredential, readBodyBounded, refreshOAuth, rekeyAgentCredential, storeCredential, } from "./credentials.js";
51
52
  import { PrincipalKeyManager } from "./crypto/keys.js";
52
- import { createHash } from 'node:crypto';
53
+ import { createHash, randomUUID } from 'node:crypto';
53
54
  import { DSSE_SSH_NAMESPACE, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignOrigin, dsseSignPublication, dsseSignRevocation, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_PUBLICATION, } from "./crypto/dsse.js";
54
55
  import { assertEd25519PubText, createSshSigner, SshSignerError } from "./crypto/ssh.js";
55
56
  import { publicKeyDescriptor } from "./crypto/keys.js";
56
57
  import { DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry } from "./crypto/enrollment.js";
57
58
  import { resolveAllowedSigners } from "./crypto/trust-roots.js";
58
- import { orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, rosterDir, } from "./crypto/org-root.js";
59
+ import { orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, assertNoStrandedLegacyGrants, grantsDir, } from "./crypto/org-root.js";
59
60
  import { runMcpCommand } from "./mcp/serve.js";
60
61
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
61
62
  import { BundleError, digestBundle, inspectBundle, packBundle, unpackBundle } from "./bundle/index.js";
62
63
  import { acquireInstallLock, ADD_JOURNAL_FILENAME, archivePathViolation, commitInstall, finalizeInstallCommit, githubShaUrl, githubTarballUrl, installFolder, parkOldNameDir, parseRepoSpec, readLockfile, recoverInterruptedInstall, releaseInstallLock, removeAddJournal, rmRecursiveForce, rollbackInstallCommit, RollbackFailedError, stageFiles, STAGING_DIRNAME, writeAddJournal, writeLockfile, } from "./add.js";
63
- import { BundleIngestorUnavailableError, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, projectStoreRoot, createBundleIngestor, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.js";
64
- import { asAgentIdentities, asCreateWorkflowOk, asCapabilityRerouteAdded, asCapabilityRerouteRemoved, asCapabilityReroutes, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, asRoutingAlerts, asRunRouting, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, DEFAULT_HUB, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
64
+ import { BundleIngestorUnavailableError, collectWorkflowStoreGarbage, compareStoreText, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, parseWorkflowCoordinate, projectStoreRoot, createBundleIngestor, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.js";
65
+ import { recoverInterruptedWorkflowStoreGc } from "./store/gc-recovery.js";
66
+ import { asAgentIdentities, asCreateWorkflowOk, capabilityPublishReportText, asCapabilityRerouteAdded, asCapabilityRerouteRemoved, asCapabilityReroutes, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, asRoutingAlerts, asRunRouting, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, DEFAULT_HUB, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
67
+ import { fetchCapabilityMappings, recordCapabilityMappings } from "./capability-mapping-client.js";
68
+ import { MODIFIER_SEPARATOR } from "./capabilities.js";
65
69
  import { loadSettings, settingsPath as executionSettingsPath } from "../packages/work/src/settings/settings.js";
66
- import { machineRosterLayers, mergeRosterLayers } from "../packages/work/src/settings/roster.js";
70
+ import { discoverCrewRosterFiles, crewRosterPath, effectiveRosterLayers, explainRosterShadows, mergeRosterLayers } from "../packages/work/src/settings/roster.js";
71
+ import { readHubRosterCache, syncHubRosterCache } from "../packages/work/src/settings/hub-roster-cache.js";
67
72
  import { adapterFor } from "../packages/work/src/harness/registry.js";
68
73
  import "../packages/work/src/harnesses.js";
69
74
  import { owenloopConfigDir } from "./config-dir.js";
@@ -161,6 +166,8 @@ const BOOLEAN_FLAGS = new Set([
161
166
  // bundle path/URL must stay a positional.
162
167
  'global',
163
168
  'unsigned',
169
+ 'verbose',
170
+ 'yes',
164
171
  ]);
165
172
  function parseArgs(argv) {
166
173
  const positionals = [];
@@ -222,6 +229,12 @@ function need(args, idx, label) {
222
229
  throw new CliError(`missing required argument: ${label}`);
223
230
  return v;
224
231
  }
232
+ const WORKFLOW_ID_RE = /^wf_[0-9a-f]{24}$/u;
233
+ function assertWorkflowIdShape(workflow) {
234
+ if (!WORKFLOW_ID_RE.test(workflow)) {
235
+ throw new CliError(`invalid workflow id '${workflow}': expected wf_ followed by 24 lowercase hexadecimal characters`);
236
+ }
237
+ }
225
238
  function needOpt(args, key) {
226
239
  const v = last(args, key);
227
240
  if (v === undefined)
@@ -320,19 +333,14 @@ function finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscove
320
333
  * fail-closed validation in add.ts is untouched — we consume `readLockfile`,
321
334
  * discovery merely refuses to act on a bad ledger rather than crashing.)
322
335
  */
323
- function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
324
- const merged = existsSync(defsDir) ? loadDefsUnfinalized(defsDir) : new Map();
336
+ function foldInstalledDefs(io, defsDir, merged, scan) {
325
337
  let lf;
326
338
  try {
327
339
  lf = readLockfile(join(io.cwd, '.owenloop', 'installed.json'));
328
340
  }
329
341
  catch (e) {
330
342
  io.err(`warning: skipping installed workflow defs: ${e.message}`);
331
- const definitionDiscoveryComplete = foldCasDefs(io, defsDir, merged, tolerantCasInspection);
332
- return {
333
- defs: finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscoveryComplete),
334
- definitionDiscoveryComplete,
335
- };
343
+ return;
336
344
  }
337
345
  for (const source of Object.keys(lf.installed).sort()) {
338
346
  const entry = lf.installed[source];
@@ -345,7 +353,7 @@ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
345
353
  }
346
354
  let entryRaw;
347
355
  try {
348
- entryRaw = loadDefsUnfinalized(entryDir);
356
+ entryRaw = scan(entryDir);
349
357
  }
350
358
  catch (e) {
351
359
  io.err(`warning: failed to load installed defs for ${source} (${entry.path}): ${e.message}`);
@@ -360,7 +368,13 @@ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
360
368
  merged.set(name, def);
361
369
  }
362
370
  }
363
- const definitionDiscoveryComplete = foldCasDefs(io, defsDir, merged, tolerantCasInspection);
371
+ }
372
+ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false, verbose = false) {
373
+ const merged = existsSync(defsDir) ? loadDefsUnfinalized(defsDir) : new Map();
374
+ // Preserve executable discovery's long-standing whole-folder policy: a bad
375
+ // installed folder is warned about and skipped rather than partially loaded.
376
+ foldInstalledDefs(io, defsDir, merged, loadDefsUnfinalized);
377
+ const definitionDiscoveryComplete = foldCasDefs(io, defsDir, merged, tolerantCasInspection, verbose);
364
378
  return {
365
379
  defs: finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscoveryComplete),
366
380
  definitionDiscoveryComplete,
@@ -390,7 +404,7 @@ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
390
404
  * When no store exists (no `index.json` at either root) this is a no-op and the
391
405
  * merged map is byte-identical to what it was before WS-6.
392
406
  */
393
- function foldCasDefs(io, defsDir, merged, tolerantInspection = false) {
407
+ function foldCasDefs(io, defsDir, merged, tolerantInspection = false, verbose = false) {
394
408
  // Without HOME/USERPROFILE, retain project discovery and consult a guaranteed
395
409
  // absent synthetic global root instead of silently dropping the project store.
396
410
  let globalRoot;
@@ -404,6 +418,7 @@ function foldCasDefs(io, defsDir, merged, tolerantInspection = false) {
404
418
  projectRoot: projectStoreRoot(defsDir),
405
419
  globalRoot,
406
420
  warn: (line) => io.err(line),
421
+ verbose,
407
422
  };
408
423
  const discovery = tolerantInspection
409
424
  ? inspectCasDefs(discoveryArgs)
@@ -420,6 +435,67 @@ function foldCasDefs(io, defsDir, merged, tolerantInspection = false) {
420
435
  }
421
436
  return discovery.complete;
422
437
  }
438
+ function loadDefsRawWithInstalled(io, defsDir, failures, verbose = false) {
439
+ const merged = existsSync(defsDir) ? scanDefsRaw(defsDir, failures) : new Map();
440
+ foldInstalledDefs(io, defsDir, merged, (dir) => {
441
+ try {
442
+ // Match executable discovery exactly: one malformed or duplicate member
443
+ // invalidates the installed folder. Retain the failed folder as a lint
444
+ // result while foldInstalledDefs emits the shared warning.
445
+ return loadDefsUnfinalized(dir);
446
+ }
447
+ catch (e) {
448
+ failures.push({ file: dir, error: e.message });
449
+ throw e;
450
+ }
451
+ });
452
+ foldCasDefs(io, defsDir, merged, false, verbose);
453
+ return { rawDefs: merged, defs: expandDefsRaw(merged) };
454
+ }
455
+ function loadDefsForAuthoring(io, args, failures) {
456
+ // This deliberately checks override *presence*, rather than whether its path
457
+ // happens to equal cwd/workflows, matching openCtx exactly.
458
+ const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
459
+ const defsDir = defsOverride ?? join(io.cwd, 'workflows');
460
+ let loaded;
461
+ if (defsOverride !== undefined) {
462
+ const rawDefs = existsSync(defsDir) ? scanDefsRaw(defsDir, failures) : new Map();
463
+ loaded = { rawDefs, defs: expandDefsRaw(rawDefs) };
464
+ }
465
+ else {
466
+ loaded = loadDefsRawWithInstalled(io, defsDir, failures, flag(args, 'verbose'));
467
+ }
468
+ return { defsDir, ...loaded };
469
+ }
470
+ function cycleErrorsByDefKey(defs) {
471
+ const errors = new Map();
472
+ const aliases = new Map();
473
+ for (const [key, def] of defs) {
474
+ // The CAS loader registers one physical def under coordinate, digest-scoped,
475
+ // and package/workflow aliases. Treat those aliases as one logical def so a
476
+ // cycle discovered through the resolver's first key is visible through every
477
+ // name an operator can select.
478
+ const identity = def.bundleDigest === undefined ? key : `${def.bundleDigest}\u0000${def.name}`;
479
+ const keys = aliases.get(identity) ?? [];
480
+ keys.push(key);
481
+ aliases.set(identity, keys);
482
+ }
483
+ for (const finding of reportCallsCycles(defs)) {
484
+ for (const key of finding.members) {
485
+ const def = defs.get(key);
486
+ if (def === undefined)
487
+ continue;
488
+ const identity = def.bundleDigest === undefined ? key : `${def.bundleDigest}\u0000${def.name}`;
489
+ for (const alias of aliases.get(identity) ?? []) {
490
+ const messages = errors.get(alias) ?? [];
491
+ if (!messages.includes(finding.message))
492
+ messages.push(finding.message);
493
+ errors.set(alias, messages);
494
+ }
495
+ }
496
+ }
497
+ return errors;
498
+ }
423
499
  function openCtx(io, args, tolerantCasInspection = false) {
424
500
  const dbOverride = last(args, 'db') ?? io.env.OWENLOOP_DB;
425
501
  const dbPath = dbOverride ?? join(io.cwd, '.owenloop', 'state.db');
@@ -438,7 +514,7 @@ function openCtx(io, args, tolerantCasInspection = false) {
438
514
  defs: existsSync(defsDir) ? loadDefs(defsDir) : new Map(),
439
515
  definitionDiscoveryComplete: true,
440
516
  }
441
- : loadDefsWithInstalled(io, defsDir, tolerantCasInspection);
517
+ : loadDefsWithInstalled(io, defsDir, tolerantCasInspection, flag(args, 'verbose'));
442
518
  const { defs, definitionDiscoveryComplete } = loaded;
443
519
  // Guard the built-in default (`cwd/.owenloop/state.db`) against a symlinked
444
520
  // `.owenloop` from a hostile checkout (SEC-3). Directory guard first, then the
@@ -524,10 +600,17 @@ function printBundleInspectResult(io, result) {
524
600
  * the stderr message so scripts can match on it.
525
601
  */
526
602
  function dispatchBundle(io, args) {
527
- const sub = need(args, 1, 'pack|unpack|inspect|digest');
603
+ const sub = need(args, 1, 'pack|unpack|inspect|digest|gc');
528
604
  if (sub !== 'pack' && args.options.has('output')) {
529
605
  throw new CliError(`owenloop bundle ${sub}: --output is only valid for pack`);
530
606
  }
607
+ if (sub !== 'gc') {
608
+ for (const option of ['keep', 'yes', 'global']) {
609
+ if (args.options.has(option)) {
610
+ throw new CliError(`owenloop bundle ${sub}: --${option} is only valid for bundle gc`);
611
+ }
612
+ }
613
+ }
531
614
  switch (sub) {
532
615
  case 'pack': {
533
616
  assertBundlePositionals(args, 3, 'owenloop bundle pack <source-dir> [--output <bundle.wnlp>]');
@@ -576,8 +659,10 @@ function dispatchBundle(io, args) {
576
659
  print(io, { digest: result.digest });
577
660
  return 0;
578
661
  }
662
+ case 'gc':
663
+ throw new CliError('owenloop bundle gc requires the async entry point');
579
664
  default:
580
- throw new CliError(`owenloop bundle: unknown subcommand '${sub}' (expected pack, unpack, inspect, or digest)`);
665
+ throw new CliError(`owenloop bundle: unknown subcommand '${sub}' (expected pack, unpack, inspect, digest, or gc)`);
581
666
  }
582
667
  }
583
668
  /** `--output` requires a following value; a bare flag is not a default path. */
@@ -961,6 +1046,12 @@ async function dispatchTrust(io, args) {
961
1046
  throw new CliError(`owenloop trust grant: ${error instanceof Error ? error.message : String(error)}`);
962
1047
  }
963
1048
  const signer = signingKeyInfo(io, signingPath);
1049
+ try {
1050
+ assertNoStrandedLegacyGrants(io.env);
1051
+ }
1052
+ catch (error) {
1053
+ throw new CliError(`owenloop trust grant: ${error instanceof Error ? error.message : String(error)}`);
1054
+ }
964
1055
  const record = {
965
1056
  newKey: {
966
1057
  keyid: newKey.keyid,
@@ -976,7 +1067,7 @@ async function dispatchTrust(io, args) {
976
1067
  const sshSigner = createSshSigner({ namespace: DSSE_SSH_NAMESPACE, signKeyPath: signer.path });
977
1068
  try {
978
1069
  const signed = await dsseSignEnrollmentGrant(Buffer.from(canonicalJsonBytes(record)), sshSigner);
979
- const output = trustEnvelopeOutput(args, io.cwd, join(rosterDir(io.env), `${trustKeyHash(newKey.keyid)}.grant.dsse`));
1070
+ const output = trustEnvelopeOutput(args, io.cwd, join(grantsDir(io.env), `${trustKeyHash(newKey.keyid)}.grant.dsse`));
980
1071
  writeTrustEnvelope(output, signed.envelope);
981
1072
  print(io, { ok: true, path: output, keyid: newKey.keyid, grantedBy: signer.keyid, principal, validFrom: record.validFrom });
982
1073
  }
@@ -1098,7 +1189,7 @@ function sleepMs(ms) {
1098
1189
  // ---- commands ----------------------------------------------------------------
1099
1190
  export const USAGE = `owenloop — a dataflow workflow engine
1100
1191
 
1101
- Usage: owenloop <command> [args] [--db <path>] [--defs <dir>]
1192
+ Usage: owenloop <command> [args] [--db <path>] [--defs <dir>] [--verbose]
1102
1193
 
1103
1194
  Commands:
1104
1195
  defs list available workflow definitions
@@ -1111,6 +1202,8 @@ Commands:
1111
1202
  bundle unpack <bundle.wnlp> <destination-dir> unpack a .wnlp bundle into a new directory
1112
1203
  bundle inspect <bundle.wnlp> strictly validate a .wnlp bundle and print its manifest/entries
1113
1204
  bundle digest <bundle.wnlp> print the bundle's def digest (SHA-256 of the canonical tar)
1205
+ bundle gc [--keep <n>] [--global] [--yes]
1206
+ ${' '.repeat(41)}dry-run or collect superseded content-addressed store objects
1114
1207
  publish <source-dir> [--output <bundle.wnlp>] [--source <json>] [--unsigned] [--hub <origin>]
1115
1208
  pack a bundle and sign its canonical digest (signed by default)
1116
1209
  trust init [--force] create the local Ed25519 enrollment root
@@ -1121,14 +1214,22 @@ Commands:
1121
1214
  login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)
1122
1215
  logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot
1123
1216
  connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
1124
- push [<defName>...] [--bundle <bundle.wnlp>] [--force] [--dry-run] [--hub <origin>] [--as <slot>]
1217
+ push [<defName>...] [--bundle <bundle.wnlp>] [--force] [--dry-run] [--hub <origin>] [--as <slot>] [--map <authored>=<org>]
1125
1218
  publish local workflow defs, or exact bundle-backed defs, to the safely resolved hub (server-diffed, idempotent)
1126
1219
  --as names the credential slot: human (default), agent, or agent:<account>
1127
- start <defName> [--provide name=json ...] [--crew <name>] [--title <text>] [--modifier <name>] [--hub <url>]
1220
+ --map records one authored=org capability mapping (repeatable); without it push records none
1221
+ install <owner>/<repo>[@ref] [<defName>...] [--map <authored>=<org>] [--accept-defaults] [--dry-run] [--hub <origin>] [--as <slot>]
1222
+ publish an OUTSIDE repo's defs to your hub under SCOPED capabilities (<defName>.<capability> by default)
1223
+ records the capability mapping BEFORE it publishes; it never writes into local workflows/ (that is \`add\`)
1224
+ start <defName> [--provide name=json ...] [--crew <name>] [--title <text>] [--modifier <name>] [--scope <label>] [--priority <low|normal|high>] [--hub <url>]
1128
1225
  ${' '.repeat(41)}start a published workflow on the bound hub (human credential)
1129
1226
  ${' '.repeat(41)}--modifier names one value from the def's declared \`modifiers:\` set; every
1130
1227
  ${' '.repeat(41)}step's capability is then offered as \`<capability>:<modifier>\`. Omit it and
1131
1228
  ${' '.repeat(41)}the run carries no modifier and its steps are offered on BARE capabilities.
1229
+ ${' '.repeat(41)}--scope is a free routing label recorded on the run — no registry, no fixed set.
1230
+ ${' '.repeat(41)}Omit it and the run is routed by the org's routes alone.
1231
+ ${' '.repeat(41)}--priority is one of low, normal, high. Omit it and the hub applies normal.
1232
+ pending-gates --hub <url> list human-input gates currently blocking hub-hosted workflows (no local-engine form)
1132
1233
  cancel <workflow> [--reason <text>] [--hub <url>]
1133
1234
  ${' '.repeat(41)}cancel a running instance on the bound hub (human credential; agents cannot cancel).
1134
1235
  ${' '.repeat(41)}Closes every open lease so the run stops being re-offered, and records the
@@ -1148,7 +1249,7 @@ ${' '.repeat(41)}one run and flips to oldest first. A \`binding-gap\` alert mean
1148
1249
  ${' '.repeat(41)}offer because its compound capability had no live crew binding.
1149
1250
  routing show <workflow> [--hub <url>]
1150
1251
  ${' '.repeat(41)}print one HUB run's routing: modifier, wait policy, alerts, resolution reports
1151
- ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads a def from sqlite.
1252
+ ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads raw artifacts from sqlite.
1152
1253
  routing rule list [--hub <url>] list the org's capability reroute rules in the order the hub tries them
1153
1254
  routing rule add <capability> <target> [--position <n>] [--hub <url>] add one reroute rule — offer <capability> as <target> when it has no live crew binding (admin; idempotent per pair; no --position appends)
1154
1255
  routing rule rm <capability> <target> [--hub <url>] remove one reroute rule (admin; a rule that was never there is a no-op)
@@ -1159,7 +1260,17 @@ ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads a
1159
1260
  crew member rm <crewId> <principalId> [--hub <url>] remove a principal from a crew
1160
1261
  setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--crews <a,b>] [--scopes <a,b>] [--reuse-ssh-key <path>] converge this machine's install: human login, agent credential, signing keys, owenloop settings, plugins (idempotent)
1161
1262
  doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)
1162
- roster show [crew] print a merged crew roster and its layer provenance (read-only)
1263
+ roster show [crew] print the offline four-layer roster cascade and provenance
1264
+ roster org [--hub <url>] read the live hub org-global and per-crew rosters (human credential)
1265
+ roster org put <capability> --candidate <harness>:<model>:<effort> [--crew <name>] [--hub <url>]
1266
+ ${' '.repeat(41)}replace one hub roster row (human admin credential)
1267
+ roster org rm <capability> [--crew <name>] [--hub <url>]
1268
+ ${' '.repeat(41)}remove one hub roster row (human admin credential)
1269
+ roster registry [--hub <url>] list hub harnesses, models, and supported efforts (human credential)
1270
+ roster registry put <harness> [--model <model>:<effort,effort…>]… [--display-name <text>] [--hub <url>]
1271
+ ${' '.repeat(41)}replace a harness's hub model snapshot (human admin credential)
1272
+ roster sync [--hub <url>] [--as agent|agent:<account>]
1273
+ ${' '.repeat(41)}refresh the local hub-rosters cache with an agent credential
1163
1274
  enrollments [--hub <url>] list the hub's relayed machine enrollment grants (read-only)
1164
1275
  mcp [--hub <url>] serve the hub control plane over stdio MCP (spawned by MCP hosts, not run by humans)
1165
1276
  work <subcommand> [args] run execution-side shift/hold/exec/agent-run/... commands
@@ -1168,7 +1279,7 @@ ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads a
1168
1279
  check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided] [--strict-inputs]
1169
1280
  bounded reachability check (stall states, true deadlocks, stuck, dead steps, declared invariants)
1170
1281
  create <def> [--title t] [--provide name=json ...] [--param k=v ...]
1171
- provide <wf> <name> [--value json] supply an owed (seedOwed) input
1282
+ provide <wf> <name> [--value json] [--hub <url>] supply an owed (seedOwed) input
1172
1283
  adopt <wf> re-pin an instance to the current def (§28); settles new debts
1173
1284
  tick <wf> [--now <ms>] [--shallow] [--capability <c>]... pull eligible orders (deep: also from calls: children; --shallow for this instance only; --capability filters to matching-capability steps)
1174
1285
  reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)
@@ -1184,16 +1295,17 @@ ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads a
1184
1295
  green <wf> <run> <path> [--value json] [--terminal]
1185
1296
  emit <wf> <run> --items '[{...}]' accrete collection elements
1186
1297
  seal <wf> <run> [--value json] signal a collection is complete
1187
- reject <wf> <path> --by <author> --text <msg>
1298
+ reject <wf> <path> --by <author> --text <msg> [--requested <modifier>] [--hub <url>]
1188
1299
  retract <wf> <path> --by <author> --text <msg>
1189
1300
  skip <wf> <path> --by <author> --text <msg>
1190
- retry <wf> <path> [--by <author>] [--text <guidance>] clear a §6 stall, or ANSWER an ask
1301
+ retry <wf> <path> [--by <author>] [--text <guidance>] [--hub <url>] clear a §6 stall, or ANSWER an ask
1191
1302
  ask <wf> <path> <question> [--by <author>] hold an owed artifact on a question for a human
1192
1303
  inbox every held question across all instances, with its answer command
1193
1304
  heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run
1194
- close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]
1305
+ close <wf> <run> [--outcome ok|no_work|released|failed|skipped] [--summary s]
1195
1306
  delete <wf> [--recursive] refuse if children exist unless --recursive (cascades)
1196
1307
 
1308
+ Global: --verbose lists detailed superseded bundle-version notices.
1197
1309
  Environment: OWENLOOP_DB, OWENLOOP_DEFS`;
1198
1310
  /** Append parse failures to a "definition not found" error — the def the user asked for may be in one of the broken files. */
1199
1311
  function failureNote(failures) {
@@ -1212,7 +1324,7 @@ export { hasDefiniteCheckDefect };
1212
1324
  * even on commands that ignore them — to avoid rejecting a documented
1213
1325
  * invocation.
1214
1326
  */
1215
- const GLOBAL_OPTIONS = ['db', 'defs'];
1327
+ const GLOBAL_OPTIONS = ['db', 'defs', 'verbose'];
1216
1328
  /** Build a command's option allowlist: the two globals plus its own long-form flags. */
1217
1329
  const cmdOpts = (...extra) => new Set([...GLOBAL_OPTIONS, ...extra]);
1218
1330
  /**
@@ -1232,14 +1344,16 @@ export const COMMAND_OPTIONS = new Map([
1232
1344
  ['help', cmdOpts()],
1233
1345
  ['defs', cmdOpts()],
1234
1346
  ['add', cmdOpts('recover', 'global')],
1235
- ['bundle', cmdOpts('output')],
1347
+ ['bundle', cmdOpts('output', 'keep', 'yes', 'global')],
1236
1348
  ['login', cmdOpts('hub', 'with-token', 'as')],
1237
1349
  ['logout', cmdOpts('hub', 'as')],
1238
1350
  ['connect', cmdOpts('hub', 'as')],
1239
1351
  ['publish', cmdOpts('unsigned', 'output', 'source', 'hub')],
1240
1352
  ['trust', cmdOpts('force', 'key', 'principal', 'pools', 'labels', 'namespaces', 'delegate', 'signing-key', 'output', 'reason', 'effective-from')],
1241
- ['push', cmdOpts('dry-run', 'force', 'hub', 'as', 'bundle')],
1242
- ['start', cmdOpts('hub', 'crew', 'title', 'provide', 'modifier')],
1353
+ ['push', cmdOpts('dry-run', 'force', 'hub', 'as', 'bundle', 'map')],
1354
+ ['install', cmdOpts('hub', 'as', 'map', 'accept-defaults', 'dry-run')],
1355
+ ['start', cmdOpts('hub', 'crew', 'title', 'provide', 'modifier', 'scope', 'priority')],
1356
+ ['pending-gates', cmdOpts('hub')],
1243
1357
  ['cancel', cmdOpts('hub', 'reason')],
1244
1358
  ['instance', cmdOpts('hub')],
1245
1359
  ['agent', cmdOpts('crews', 'hub', 'scopes', 'shift')],
@@ -1252,7 +1366,7 @@ export const COMMAND_OPTIONS = new Map([
1252
1366
  ['crew', cmdOpts('hub', 'kind', 'owner')],
1253
1367
  ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'crews', 'scopes', 'reuse-ssh-key')],
1254
1368
  ['doctor', cmdOpts('hub')],
1255
- ['roster', cmdOpts()],
1369
+ ['roster', cmdOpts('hub', 'crew', 'candidate', 'display-name', 'model', 'as')],
1256
1370
  ['enrollments', cmdOpts('hub')],
1257
1371
  ['mcp', cmdOpts('hub')],
1258
1372
  ['work', cmdOpts()],
@@ -1260,7 +1374,7 @@ export const COMMAND_OPTIONS = new Map([
1260
1374
  ['lint', cmdOpts()],
1261
1375
  ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided', 'strict-inputs')],
1262
1376
  ['create', cmdOpts('title', 'provide', 'param')],
1263
- ['provide', cmdOpts('value')],
1377
+ ['provide', cmdOpts('value', 'hub')],
1264
1378
  ['adopt', cmdOpts()],
1265
1379
  ['tick', cmdOpts('now', 'shallow', 'capability')],
1266
1380
  ['reap', cmdOpts('now')],
@@ -1274,10 +1388,10 @@ export const COMMAND_OPTIONS = new Map([
1274
1388
  ['green', cmdOpts('value', 'terminal')],
1275
1389
  ['emit', cmdOpts('items')],
1276
1390
  ['seal', cmdOpts('value')],
1277
- ['reject', cmdOpts('by', 'text')],
1391
+ ['reject', cmdOpts('by', 'text', 'requested', 'hub')],
1278
1392
  ['retract', cmdOpts('by', 'text')],
1279
1393
  ['skip', cmdOpts('by', 'text')],
1280
- ['retry', cmdOpts('by', 'text')],
1394
+ ['retry', cmdOpts('by', 'text', 'hub')],
1281
1395
  ['ask', cmdOpts('by', 'question')],
1282
1396
  ['inbox', cmdOpts()],
1283
1397
  ['close', cmdOpts('outcome', 'summary')],
@@ -1356,20 +1470,259 @@ function preflight(command, args, io) {
1356
1470
  assertKnownOptions(command, args);
1357
1471
  return undefined;
1358
1472
  }
1359
- function dispatchRoster(io, args) {
1360
- if (args.positionals[1] !== 'show' || args.positionals.length > 3) {
1361
- throw new CliError('usage: owenloop roster show [crew]');
1473
+ function rosterAge(fetchedAt) {
1474
+ const seconds = Math.max(0, Math.floor((Date.now() - fetchedAt) / 1_000));
1475
+ if (seconds < 60)
1476
+ return `${seconds}s ago`;
1477
+ if (seconds < 3_600)
1478
+ return `${Math.floor(seconds / 60)}m ago`;
1479
+ if (seconds < 86_400)
1480
+ return `${Math.floor(seconds / 3_600)}h ago`;
1481
+ return `${Math.floor(seconds / 86_400)}d ago`;
1482
+ }
1483
+ // Keep these wire checks aligned with hub-core's roster and harness verbs.
1484
+ // This CLI is a separately deployable client, so it mirrors the public
1485
+ // contract rather than importing the service implementation.
1486
+ const MAX_ROSTER_IDENTIFIER_LENGTH = 200;
1487
+ const MAX_ROSTER_CAPABILITY_LENGTH = 64;
1488
+ const MAX_ROSTER_CANDIDATES = 32;
1489
+ const MAX_HARNESS_MODELS = 256;
1490
+ const ROSTER_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
1491
+ /**
1492
+ * The run's rate-limit priority band. Fixed by the routing plan's §4.8 wire
1493
+ * contract, not by hub discretion, so an out-of-set value is a local usage
1494
+ * error rather than a forwarded request the hub has to refuse.
1495
+ */
1496
+ const START_PRIORITIES = new Set(['low', 'normal', 'high']);
1497
+ function isRosterIdentifier(value) {
1498
+ return typeof value === 'string' && value.length > 0 && value.length <= MAX_ROSTER_IDENTIFIER_LENGTH && value.trim() === value;
1499
+ }
1500
+ function parseRosterIdentifier(value, label) {
1501
+ if (!isRosterIdentifier(value)) {
1502
+ throw new CliError(`${label} must be a trimmed, non-empty string of at most ${MAX_ROSTER_IDENTIFIER_LENGTH} characters`);
1362
1503
  }
1363
- const crew = args.positionals[2];
1364
- const layers = machineRosterLayers(io.env, crew);
1365
- const merged = mergeRosterLayers(layers);
1366
- const hasRoster = layers.some((layer) => layer.roster !== undefined);
1367
- if (!hasRoster) {
1368
- io.out(crew === undefined
1369
- ? 'no machine-global crew roster found'
1370
- : `no roster layers found for crew ${crew}`);
1504
+ return value;
1505
+ }
1506
+ function parseRosterCapability(value) {
1507
+ const capability = value.trim();
1508
+ if (capability === '')
1509
+ throw new CliError('capability must not be empty');
1510
+ if (capability.length > MAX_ROSTER_CAPABILITY_LENGTH) {
1511
+ throw new CliError(`capability must be at most ${MAX_ROSTER_CAPABILITY_LENGTH} characters`);
1371
1512
  }
1372
- else {
1513
+ if (capability.startsWith('personal:'))
1514
+ throw new CliError("capability must not start with the reserved prefix 'personal:'");
1515
+ return capability;
1516
+ }
1517
+ function isRosterCapability(value) {
1518
+ return typeof value === 'string' && value === value.trim() && value.length > 0 &&
1519
+ value.length <= MAX_ROSTER_CAPABILITY_LENGTH && !value.startsWith('personal:');
1520
+ }
1521
+ function isRosterCrewName(value) {
1522
+ // `personal:<id>`, slash, backslash, and `..` are all valid hub names. Only
1523
+ // the service's ordinary non-empty, trimmed, 64-character crew invariant is
1524
+ // relevant at this transport boundary.
1525
+ return typeof value === 'string' && value === value.trim() && value.length > 0 && value.length <= 64;
1526
+ }
1527
+ function isRosterEffort(value) {
1528
+ return typeof value === 'string' && ROSTER_EFFORTS.has(value);
1529
+ }
1530
+ function parseRosterDisplayName(value) {
1531
+ if (value.length > MAX_ROSTER_IDENTIFIER_LENGTH) {
1532
+ throw new CliError(`displayName must be a string of at most ${MAX_ROSTER_IDENTIFIER_LENGTH} characters`);
1533
+ }
1534
+ return value;
1535
+ }
1536
+ function parseRosterCandidate(value) {
1537
+ const first = value.indexOf(':');
1538
+ const lastColon = value.lastIndexOf(':');
1539
+ if (first <= 0 || lastColon <= first || lastColon === value.length - 1) {
1540
+ throw new CliError(`invalid --candidate '${value}' — expected <harness>:<model>:<effort>`);
1541
+ }
1542
+ const harness = parseRosterIdentifier(value.slice(0, first), 'candidate harness');
1543
+ const model = parseRosterIdentifier(value.slice(first + 1, lastColon), 'candidate model');
1544
+ const effort = value.slice(lastColon + 1);
1545
+ if (!isRosterEffort(effort)) {
1546
+ throw new CliError(`invalid --candidate '${value}' — effort must be one of low, medium, high, xhigh, max`);
1547
+ }
1548
+ return { harness, model, effort };
1549
+ }
1550
+ function parseRegistryModel(value) {
1551
+ const colon = value.lastIndexOf(':');
1552
+ if (colon <= 0) {
1553
+ throw new CliError(`invalid --model '${value}' — expected <model>:<effort,effort…>`);
1554
+ }
1555
+ const model = parseRosterIdentifier(value.slice(0, colon), 'model');
1556
+ const rawEfforts = value.slice(colon + 1);
1557
+ // The service permits an empty effort list. A malformed member (including
1558
+ // `high,`) still fails before hub/credential I/O, matching its `isEffort`.
1559
+ const efforts = rawEfforts === '' ? [] : rawEfforts.split(',');
1560
+ if (efforts.some((effort) => !isRosterEffort(effort))) {
1561
+ throw new CliError(`invalid --model '${value}' — efforts must be drawn from low, medium, high, xhigh, max`);
1562
+ }
1563
+ return { model, efforts };
1564
+ }
1565
+ function nullableId(value, prefix, field) {
1566
+ if (value === null)
1567
+ return null;
1568
+ if (typeof value !== 'string' || value === '')
1569
+ throw new CliError(`${prefix} — ${field} must be a non-empty string or null`);
1570
+ return value;
1571
+ }
1572
+ /** Narrow each mutation response before stdout claims the write succeeded. */
1573
+ function validateRosterMutationSuccess(endpoint, body) {
1574
+ const prefix = `${endpoint}: malformed success response`;
1575
+ const row = recordOf(body);
1576
+ if (row === null)
1577
+ throw new CliError(`${prefix} — not an object`);
1578
+ if (endpoint === 'put_roster') {
1579
+ const crewId = nullableId(row.crewId, prefix, 'crewId');
1580
+ const crewName = nullableId(row.crewName, prefix, 'crewName');
1581
+ if (!isRosterCapability(row.capability))
1582
+ throw new CliError(`${prefix} — missing valid capability`);
1583
+ if (!Array.isArray(row.candidates))
1584
+ throw new CliError(`${prefix} — missing array candidates`);
1585
+ const candidates = row.candidates.map((candidate, index) => {
1586
+ const value = recordOf(candidate);
1587
+ if (value === null)
1588
+ throw new CliError(`${prefix} — candidates[${index}] is not an object`);
1589
+ if (!isRosterIdentifier(value.harness) || !isRosterIdentifier(value.model) || !isRosterEffort(value.effort)) {
1590
+ throw new CliError(`${prefix} — candidates[${index}] has an invalid harness, model, or effort`);
1591
+ }
1592
+ return { harness: value.harness, model: value.model, effort: value.effort };
1593
+ });
1594
+ if (!Array.isArray(row.warnings) || row.warnings.some((warning) => typeof warning !== 'string')) {
1595
+ throw new CliError(`${prefix} — missing array warnings`);
1596
+ }
1597
+ return { crewId, crewName, capability: row.capability, candidates, warnings: row.warnings };
1598
+ }
1599
+ if (endpoint === 'delete_roster_row') {
1600
+ const crewId = nullableId(row.crewId, prefix, 'crewId');
1601
+ if (!isRosterCapability(row.capability))
1602
+ throw new CliError(`${prefix} — missing valid capability`);
1603
+ if (typeof row.removed !== 'boolean')
1604
+ throw new CliError(`${prefix} — missing boolean removed`);
1605
+ return { crewId, capability: row.capability, removed: row.removed };
1606
+ }
1607
+ if (!isRosterIdentifier(row.harness))
1608
+ throw new CliError(`${prefix} — missing valid harness`);
1609
+ if (typeof row.displayName !== 'string' || row.displayName.length > MAX_ROSTER_IDENTIFIER_LENGTH) {
1610
+ throw new CliError(`${prefix} — displayName must be a string of at most ${MAX_ROSTER_IDENTIFIER_LENGTH} characters`);
1611
+ }
1612
+ if (!Array.isArray(row.models))
1613
+ throw new CliError(`${prefix} — missing array models`);
1614
+ const models = row.models.map((model, index) => {
1615
+ const value = recordOf(model);
1616
+ if (value === null)
1617
+ throw new CliError(`${prefix} — models[${index}] is not an object`);
1618
+ if (!isRosterIdentifier(value.model))
1619
+ throw new CliError(`${prefix} — models[${index}] missing valid model`);
1620
+ if (!Array.isArray(value.efforts) || value.efforts.some((effort) => !isRosterEffort(effort))) {
1621
+ throw new CliError(`${prefix} — models[${index}] missing array efforts`);
1622
+ }
1623
+ if (typeof value.updatedAt !== 'number' || !Number.isFinite(value.updatedAt))
1624
+ throw new CliError(`${prefix} — models[${index}] missing finite number updatedAt`);
1625
+ if (typeof value.updatedBy !== 'string' || value.updatedBy === '')
1626
+ throw new CliError(`${prefix} — models[${index}] missing non-empty string updatedBy`);
1627
+ return { model: value.model, efforts: value.efforts, updatedAt: value.updatedAt, updatedBy: value.updatedBy };
1628
+ });
1629
+ return { harness: row.harness, displayName: row.displayName, models };
1630
+ }
1631
+ function validateRosterRows(value, prefix) {
1632
+ const row = recordOf(value);
1633
+ if (row === null)
1634
+ throw new CliError(`${prefix} — roster must be an object`);
1635
+ // Hub capability names may legally collide with Object.prototype (notably
1636
+ // `__proto__`). A normal object assignment would mutate/drop that row.
1637
+ const result = Object.create(null);
1638
+ for (const [capability, candidates] of Object.entries(row)) {
1639
+ if (!isRosterCapability(capability))
1640
+ throw new CliError(`${prefix} — invalid capability ${JSON.stringify(capability)}`);
1641
+ if (!Array.isArray(candidates))
1642
+ throw new CliError(`${prefix} — ${capability} must be an array`);
1643
+ result[capability] = candidates.map((candidate, index) => {
1644
+ const item = recordOf(candidate);
1645
+ if (item === null || !isRosterIdentifier(item.harness) || !isRosterIdentifier(item.model) || !isRosterEffort(item.effort)) {
1646
+ throw new CliError(`${prefix} — ${capability}[${index}] must contain valid harness, model, and effort`);
1647
+ }
1648
+ return { harness: item.harness, model: item.model, effort: item.effort };
1649
+ });
1650
+ }
1651
+ return result;
1652
+ }
1653
+ function validateGetRostersSuccess(body) {
1654
+ const prefix = 'rosters: malformed success response';
1655
+ const row = recordOf(body);
1656
+ if (row === null || !Array.isArray(row.crews))
1657
+ throw new CliError(`${prefix} — expected global object and crews array`);
1658
+ return {
1659
+ global: validateRosterRows(row.global, prefix),
1660
+ crews: row.crews.map((crew, index) => {
1661
+ const item = recordOf(crew);
1662
+ if (item === null || typeof item.crewId !== 'string' || item.crewId === '' || !(isRosterCrewName(item.crewName) || item.crewName === null)) {
1663
+ throw new CliError(`${prefix} — crews[${index}] has an invalid identity`);
1664
+ }
1665
+ return { crewId: item.crewId, crewName: item.crewName, roster: validateRosterRows(item.roster, `${prefix} — crews[${index}].roster`) };
1666
+ }),
1667
+ };
1668
+ }
1669
+ function validateHarnessModelsSuccess(body) {
1670
+ const prefix = 'harness_models: malformed success response';
1671
+ const row = recordOf(body);
1672
+ if (row === null || !Array.isArray(row.harnesses) || !Array.isArray(row.models))
1673
+ throw new CliError(`${prefix} — expected harnesses and models arrays`);
1674
+ return {
1675
+ harnesses: row.harnesses.map((harness, index) => {
1676
+ const item = recordOf(harness);
1677
+ if (item === null || !isRosterIdentifier(item.harness) || typeof item.displayName !== 'string' || item.displayName.length > MAX_ROSTER_IDENTIFIER_LENGTH)
1678
+ throw new CliError(`${prefix} — harnesses[${index}] is invalid`);
1679
+ return { harness: item.harness, displayName: item.displayName };
1680
+ }),
1681
+ models: row.models.map((model, index) => {
1682
+ const item = recordOf(model);
1683
+ if (item === null || !isRosterIdentifier(item.harness) || !isRosterIdentifier(item.model) || !Array.isArray(item.efforts) || item.efforts.some((effort) => !isRosterEffort(effort)) || typeof item.updatedAt !== 'number' || !Number.isFinite(item.updatedAt) || typeof item.updatedBy !== 'string' || item.updatedBy === '')
1684
+ throw new CliError(`${prefix} — models[${index}] is invalid`);
1685
+ return { harness: item.harness, model: item.model, efforts: item.efforts, updatedAt: item.updatedAt, updatedBy: item.updatedBy };
1686
+ }),
1687
+ };
1688
+ }
1689
+ /** `roster` uses the same authenticated REST ladders as `routing`; show stays
1690
+ * fully offline so it reports exactly what an agent-run child would route. */
1691
+ async function dispatchRoster(io, args) {
1692
+ const USAGE_FORMS = 'usage: owenloop roster show [crew] | owenloop roster org [--hub <url>] | ' +
1693
+ 'owenloop roster org put <capability> [--crew <name>] --candidate <harness>:<model>:<effort>… [--hub <url>] | ' +
1694
+ 'owenloop roster org rm <capability> [--crew <name>] [--hub <url>] | ' +
1695
+ 'owenloop roster registry [--hub <url>] | owenloop roster registry put <harness> [--display-name <text>] [--model <model>:<effort,effort…>]… [--hub <url>] | ' +
1696
+ 'owenloop roster sync [--hub <url>] [--as agent|agent:<account>]';
1697
+ const sub = args.positionals[1];
1698
+ if (sub !== 'show' && sub !== 'org' && sub !== 'registry' && sub !== 'sync') {
1699
+ throw new CliError(`unknown roster subcommand '${sub ?? ''}' — ${USAGE_FORMS}`);
1700
+ }
1701
+ // `COMMAND_OPTIONS` admits the union of every roster flag. Narrow it again
1702
+ // by command form before even an offline read or credential lookup, so a
1703
+ // typo never looks like a successful command that silently ignored intent.
1704
+ const assertFormOptions = (allowed) => {
1705
+ // `--db` and `--defs` are global CLI options. They are admitted before
1706
+ // dispatch for every command and must remain accepted here too; this
1707
+ // narrower check is only for roster-form-specific flags.
1708
+ const allowedSet = new Set([...GLOBAL_OPTIONS, ...allowed]);
1709
+ const disallowed = [...args.options.keys()].filter((option) => !allowedSet.has(option));
1710
+ if (disallowed.length > 0) {
1711
+ throw new CliError(`${disallowed.map((option) => `--${option}`).join(', ')} ${disallowed.length === 1 ? 'is' : 'are'} not valid for this roster command (${USAGE_FORMS})`);
1712
+ }
1713
+ };
1714
+ if (sub === 'show') {
1715
+ assertFormOptions([]);
1716
+ if (args.positionals.length > 3)
1717
+ throw new CliError(USAGE_FORMS);
1718
+ const crew = args.positionals[2];
1719
+ const settings = loadSettings(io.env);
1720
+ const account = io.env.OWENLOOP_ACCOUNT ?? 'default';
1721
+ const layers = effectiveRosterLayers(io.env, crew, { origin: settings.hubOrigin, account });
1722
+ const merged = mergeRosterLayers(layers);
1723
+ const cache = settings.hubOrigin === undefined ? undefined : readHubRosterCache(io.env, settings.hubOrigin, account);
1724
+ if (Object.keys(merged).length === 0)
1725
+ io.out(crew === undefined ? 'no roster layers found' : `no roster rows found for crew ${crew}`);
1373
1726
  for (const capability of Object.keys(merged).sort()) {
1374
1727
  const entry = merged[capability];
1375
1728
  io.out(`${capability}:`);
@@ -1377,42 +1730,240 @@ function dispatchRoster(io, args) {
1377
1730
  io.out(` [${index}] harness=${candidate.harness} model=${candidate.model} effort=${candidate.effort} from ${entry.source}`);
1378
1731
  }
1379
1732
  }
1733
+ io.out('layers inspected:');
1734
+ for (const layer of layers) {
1735
+ const age = layer.source.startsWith('hub ') && cache?.kind === 'hit' ? `; ${rosterAge(cache.data.fetchedAt)}` : '';
1736
+ io.out(` ${layer.source}: ${layer.roster === undefined ? 'absent' : 'found'}${layer.path === undefined ? '' : ` (${layer.path})`}${age}`);
1737
+ }
1738
+ const shadows = explainRosterShadows(layers);
1739
+ const shadowed = Object.entries(shadows).filter(([, detail]) => detail.shadowed.length > 0).sort(([a], [b]) => a.localeCompare(b));
1740
+ if (shadowed.length > 0) {
1741
+ io.out('shadowed:');
1742
+ for (const [capability, detail] of shadowed) {
1743
+ io.out(` ${capability}: ${detail.winner} wins; ${detail.shadowed.map((row) => `${row.source} (${row.candidateCount} candidate${row.candidateCount === 1 ? '' : 's'})`).join(', ')} shadowed`);
1744
+ }
1745
+ }
1746
+ return 0;
1747
+ }
1748
+ let orgSub;
1749
+ let registrySub;
1750
+ let capability = '';
1751
+ let harness = '';
1752
+ if (sub === 'org') {
1753
+ const nested = args.positionals[2];
1754
+ if (nested === undefined)
1755
+ orgSub = 'get';
1756
+ else if (nested === 'put' || nested === 'rm')
1757
+ orgSub = nested;
1758
+ else
1759
+ throw new CliError(`unknown roster org subcommand '${nested}' — ${USAGE_FORMS}`);
1760
+ if (orgSub === 'put' || orgSub === 'rm') {
1761
+ capability = parseRosterCapability(args.positionals[3] ?? '');
1762
+ }
1763
+ const maxPositionals = orgSub === 'get' ? 2 : 4;
1764
+ if (args.positionals.length > maxPositionals)
1765
+ throw new CliError(USAGE_FORMS);
1766
+ assertFormOptions(orgSub === 'get' ? ['hub'] : orgSub === 'put' ? ['hub', 'crew', 'candidate'] : ['hub', 'crew']);
1767
+ if (orgSub === 'put' && all(args, 'candidate').length === 0)
1768
+ throw new CliError(`missing required --candidate (${USAGE_FORMS})`);
1769
+ }
1770
+ else if (sub === 'registry') {
1771
+ const nested = args.positionals[2];
1772
+ if (nested === undefined)
1773
+ registrySub = 'get';
1774
+ else if (nested === 'put')
1775
+ registrySub = 'put';
1776
+ else
1777
+ throw new CliError(`unknown roster registry subcommand '${nested}' — ${USAGE_FORMS}`);
1778
+ if (registrySub === 'put')
1779
+ harness = parseRosterIdentifier(args.positionals[3] ?? '', 'harness');
1780
+ const maxPositionals = registrySub === 'get' ? 2 : 4;
1781
+ if (args.positionals.length > maxPositionals)
1782
+ throw new CliError(USAGE_FORMS);
1783
+ assertFormOptions(registrySub === 'get' ? ['hub'] : ['hub', 'display-name', 'model']);
1784
+ }
1785
+ else if (args.positionals.length > 2) {
1786
+ throw new CliError(USAGE_FORMS);
1787
+ }
1788
+ else {
1789
+ assertFormOptions(['hub', 'as']);
1790
+ }
1791
+ const crewOption = last(args, 'crew');
1792
+ if (crewOption !== undefined && (args.missingOptionValues.has('crew') || crewOption.trim() === '')) {
1793
+ throw new CliError(`--crew requires a non-empty crew name (${USAGE_FORMS})`);
1794
+ }
1795
+ if (crewOption !== undefined && !isRosterCrewName(crewOption)) {
1796
+ throw new CliError('--crew must be a trimmed, non-empty crew name of at most 64 characters');
1797
+ }
1798
+ // Finish every command-local parse before resolving a hub or consulting the
1799
+ // credential backend. An invalid payload is a usage error, not a reason to
1800
+ // run an external credential helper or mask it as a missing credential.
1801
+ let parsedCandidates;
1802
+ let parsedModels;
1803
+ let parsedDisplayName;
1804
+ if (sub === 'org' && orgSub === 'put') {
1805
+ const rawCandidates = all(args, 'candidate');
1806
+ if (rawCandidates.length > MAX_ROSTER_CANDIDATES) {
1807
+ throw new CliError(`--candidate may be supplied at most ${MAX_ROSTER_CANDIDATES} times`);
1808
+ }
1809
+ parsedCandidates = rawCandidates.map(parseRosterCandidate);
1810
+ const candidateKeys = new Set();
1811
+ for (const candidate of parsedCandidates) {
1812
+ const key = JSON.stringify([candidate.harness, candidate.model, candidate.effort]);
1813
+ if (candidateKeys.has(key))
1814
+ throw new CliError('duplicate --candidate harness, model, and effort triple');
1815
+ candidateKeys.add(key);
1816
+ }
1817
+ }
1818
+ if (sub === 'registry' && registrySub === 'put') {
1819
+ const displayNames = all(args, 'display-name');
1820
+ if (displayNames.length > 1)
1821
+ throw new CliError('--display-name may be supplied at most once');
1822
+ if (displayNames.length > 0 && args.missingOptionValues.has('display-name')) {
1823
+ throw new CliError('--display-name requires a value');
1824
+ }
1825
+ if (displayNames.length === 1)
1826
+ parsedDisplayName = parseRosterDisplayName(displayNames[0]);
1827
+ const rawModels = all(args, 'model');
1828
+ if (rawModels.length > MAX_HARNESS_MODELS)
1829
+ throw new CliError(`--model may be supplied at most ${MAX_HARNESS_MODELS} times`);
1830
+ // A zero-model full snapshot is a supported way to clear the advisory
1831
+ // registry. An empty display label is likewise a deliberate service value.
1832
+ parsedModels = rawModels.map(parseRegistryModel);
1833
+ const modelNames = new Set();
1834
+ for (const model of parsedModels) {
1835
+ if (modelNames.has(model.model))
1836
+ throw new CliError(`duplicate --model '${model.model}'`);
1837
+ modelNames.add(model.model);
1838
+ }
1839
+ }
1840
+ // `roster sync` is an agent-owned cache refresh. Unlike the other roster
1841
+ // verbs, its omitted `--as` deliberately means the default agent slot.
1842
+ const slot = sub === 'sync'
1843
+ ? (!args.options.has('as') ? { principal: 'agent' } : resolveSlot(args))
1844
+ : { principal: 'human' };
1845
+ if (sub === 'sync' && slot.principal !== 'agent') {
1846
+ throw new CliError(`roster sync requires an agent credential — pass --as agent or --as agent:<account> (${USAGE_FORMS})`);
1847
+ }
1848
+ const origin = resolveAgentHub(io, args, sub === 'sync' ? 'sync rosters from' : 'manage rosters on');
1849
+ const cred = readCredential(io, origin, slot);
1850
+ if (cred === null)
1851
+ throw new CliError(emptySlotMessage(origin, slot), { exitCode: 3 });
1852
+ const getJson = async (path, prefix) => {
1853
+ const { res, cred: used } = await authedGet(io, origin, slot, cred, path);
1854
+ if (res.status === 401) {
1855
+ throw new CliError(used.kind === 'agent'
1856
+ ? 'token revoked or invalid — re-mint it in the console or run `owenloop login`'
1857
+ : 'credential rejected by the hub — run `owenloop login`', { exitCode: 3 });
1858
+ }
1859
+ if (!res.ok)
1860
+ throw new CliError((await hubRequestMessage(res)) ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
1861
+ try {
1862
+ return await res.json();
1863
+ }
1864
+ catch {
1865
+ throw new CliError(`${prefix}: malformed response — body is not valid JSON`);
1866
+ }
1867
+ };
1868
+ if (sub === 'sync') {
1869
+ const account = slot.principal === 'agent' ? slot.account ?? 'default' : 'default';
1870
+ // Use the same sync helper as shift start and periodic refresh. The local
1871
+ // adapter preserves the CLI's credential-refresh/error ladder rather than
1872
+ // bypassing it with a second raw-fetch implementation.
1873
+ const cacheClient = {
1874
+ whoami: async () => getJson('/api/whoami', 'whoami'),
1875
+ getRosters: async () => getJson('/api/rosters', 'rosters'),
1876
+ };
1877
+ await syncHubRosterCache({
1878
+ client: cacheClient,
1879
+ env: io.env,
1880
+ origin,
1881
+ account,
1882
+ });
1883
+ const cache = readHubRosterCache(io.env, origin, account);
1884
+ if (cache.kind !== 'hit')
1885
+ throw new CliError(`roster sync wrote no readable cache: ${cache.reason}`);
1886
+ print(io, { ok: true, hub: origin, cachePath: cache.path, fetchedAt: cache.data.fetchedAt });
1887
+ return 0;
1888
+ }
1889
+ if (sub === 'org' && orgSub === 'get') {
1890
+ print(io, { ok: true, hub: origin, rosters: validateGetRostersSuccess(await getJson('/api/rosters', 'rosters')) });
1891
+ return 0;
1892
+ }
1893
+ if (sub === 'registry' && registrySub === 'get') {
1894
+ print(io, { ok: true, hub: origin, registry: validateHarnessModelsSuccess(await getJson('/api/harness_models', 'harness_models')) });
1895
+ return 0;
1896
+ }
1897
+ let endpoint;
1898
+ let payload;
1899
+ if (sub === 'org' && orgSub === 'put') {
1900
+ endpoint = 'put_roster';
1901
+ payload = { capability, candidates: parsedCandidates, ...(crewOption === undefined ? {} : { crew: crewOption }) };
1380
1902
  }
1381
- io.out('layers inspected:');
1382
- for (const layer of layers) {
1383
- io.out(` ${layer.source}: ${layer.roster === undefined ? 'absent' : 'found'}${layer.path === undefined ? '' : ` (${layer.path})`}`);
1903
+ else if (sub === 'org') {
1904
+ endpoint = 'delete_roster_row';
1905
+ payload = { capability, ...(crewOption === undefined ? {} : { crew: crewOption }) };
1384
1906
  }
1907
+ else {
1908
+ endpoint = 'put_harness_models';
1909
+ payload = { harness, models: parsedModels, ...(parsedDisplayName === undefined ? {} : { displayName: parsedDisplayName }) };
1910
+ }
1911
+ const { res } = await authedPost(io, origin, slot, cred, `/api/${endpoint}`, payload);
1912
+ if (res.status === 401)
1913
+ throw new CliError('credential rejected by the hub — run `owenloop login`', { exitCode: 3 });
1914
+ if (!res.ok)
1915
+ throw new CliError((await hubRequestMessage(res)) ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
1916
+ let body;
1917
+ try {
1918
+ body = await res.json();
1919
+ }
1920
+ catch {
1921
+ throw new CliError(`${endpoint}: malformed success response — body is not valid JSON`);
1922
+ }
1923
+ const result = validateRosterMutationSuccess(endpoint, body);
1924
+ print(io, { ok: true, hub: origin, result });
1385
1925
  return 0;
1386
1926
  }
1927
+ /**
1928
+ * Authoring-only lint additions belong here rather than in defs.ts: the
1929
+ * engine's vendored surface keeps extension contents opaque. Base hard errors
1930
+ * deliberately suppress advisory extension warnings just like lintDef does.
1931
+ */
1932
+ function lintForAuthoring(def) {
1933
+ const result = lintDef(def);
1934
+ return result.errors.length === 0
1935
+ ? { ...result, warnings: [...result.warnings, ...implementsIssues(def)] }
1936
+ : result;
1937
+ }
1387
1938
  function dispatch(command, io, args) {
1388
1939
  // help and lint need no store
1389
1940
  if (command === 'help' || command === '--help' || command === '-h') {
1390
1941
  io.out(USAGE);
1391
1942
  return 0;
1392
1943
  }
1393
- if (command === 'roster')
1394
- return dispatchRoster(io, args);
1395
1944
  if (command === 'lint') {
1396
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
1397
1945
  const failures = [];
1398
- const defs = existsSync(defsDir) ? loadDefsRaw(defsDir, failures) : new Map();
1946
+ const { defsDir, rawDefs, defs } = loadDefsForAuthoring(io, args, failures);
1947
+ const cycleErrors = cycleErrorsByDefKey(defs);
1399
1948
  const defName = args.positionals[1];
1400
1949
  let hasErrors = false;
1401
1950
  if (defName !== undefined) {
1402
1951
  const def = defs.get(defName);
1403
1952
  if (!def)
1404
1953
  throw new CliError(`unknown workflow definition '${defName}' (looked in ${defsDir})${failureNote(failures)}`);
1405
- const result = lintDef(def);
1406
- if (result.errors.length)
1954
+ const result = lintForAuthoring(def);
1955
+ const errors = [...validateCallsEdges(def, rawDefs), ...result.errors, ...(cycleErrors.get(defName) ?? [])];
1956
+ if (errors.length)
1407
1957
  hasErrors = true;
1408
- print(io, { def: def.name, errors: result.errors, warnings: result.warnings });
1958
+ print(io, { def: def.name, errors, warnings: errors.length ? [] : result.warnings });
1409
1959
  }
1410
1960
  else {
1411
- const results = [...defs.values()].map((def) => {
1412
- const result = lintDef(def);
1413
- if (result.errors.length)
1961
+ const results = [...defs].map(([key, def]) => {
1962
+ const result = lintForAuthoring(def);
1963
+ const errors = [...validateCallsEdges(def, rawDefs), ...result.errors, ...(cycleErrors.get(key) ?? [])];
1964
+ if (errors.length)
1414
1965
  hasErrors = true;
1415
- return { def: def.name, errors: result.errors, warnings: result.warnings };
1966
+ return { def: def.name, errors, warnings: errors.length ? [] : result.warnings };
1416
1967
  });
1417
1968
  // Files that never became defs (malformed YAML / bad shape) are lint errors
1418
1969
  // too — omitting them makes `lint` claim a dir is clean when `create` would die.
@@ -1427,18 +1978,23 @@ function dispatch(command, io, args) {
1427
1978
  return 0;
1428
1979
  }
1429
1980
  if (command === 'check') {
1430
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
1431
1981
  const failures = [];
1432
- const defs = existsSync(defsDir) ? loadDefsRaw(defsDir, failures) : new Map();
1982
+ const { defsDir, rawDefs, defs } = loadDefsForAuthoring(io, args, failures);
1983
+ const cycleErrors = cycleErrorsByDefKey(defs);
1433
1984
  const defName = need(args, 1, 'def');
1434
1985
  const def = defs.get(defName);
1435
1986
  if (!def) {
1436
1987
  throw new CliError(`unknown workflow definition '${defName}' (looked in ${defsDir}).\n` +
1437
1988
  `Known definitions: ${[...defs.keys()].sort().join(', ') || '(none)'}${failureNote(failures)}`);
1438
1989
  }
1439
- // loadDefsRaw uses buildDef (no semantic validation); run validateDef here so
1440
- // invariant stem-reference / duplicate-name errors surface to the author.
1441
- const defErrors = validateDef(def);
1990
+ // Authoring discovery uses buildDef (no semantic validation); run
1991
+ // validateDef here so invariant stem-reference / duplicate-name errors
1992
+ // surface to the author.
1993
+ const defErrors = [
1994
+ ...validateCallsEdges(def, rawDefs),
1995
+ ...validateDef(def),
1996
+ ...(cycleErrors.get(defName) ?? []),
1997
+ ];
1442
1998
  if (defErrors.length > 0) {
1443
1999
  throw new CliError(`workflow '${def.name}' has validation errors:\n - ${defErrors.join('\n - ')}`);
1444
2000
  }
@@ -1474,9 +2030,13 @@ function dispatch(command, io, args) {
1474
2030
  io.out(`SEARCH INCOMPLETE — bounds hit: ${report.boundsHit.join(', ')}`);
1475
2031
  io.out('Verdicts apply only within the explored region.');
1476
2032
  }
2033
+ if (report.collectionCapApplied) {
2034
+ io.out('');
2035
+ io.out(`COLLECTION CAP APPLIED — --max-collection ${report.maxCollectionSize} limited each emit/seal fork to 0..${report.maxCollectionSize} members.`);
2036
+ }
1477
2037
  if (report.stallStates.length > 0) {
1478
2038
  io.out('');
1479
- io.out(`Stall states (expected — maxAttempts / human-escalation brakes) (${report.stallStates.length}):`);
2039
+ io.out(`Stall states (expected — retryable brakes / future idle waits) (${report.stallStates.length}):`);
1480
2040
  for (const s of report.stallStates) {
1481
2041
  io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
1482
2042
  }
@@ -1555,9 +2115,10 @@ function dispatch(command, io, args) {
1555
2115
  // - definite (true) deadlock only when EXHAUSTIVE (!bounded) → nonzero
1556
2116
  // - stall states and stuck states are by-design brakes and NEVER affect the
1557
2117
  // exit code — a stall state (report.stallStates) is EXPECTED (a human-
1558
- // escalation brake whose freeze, once lifted, re-arms a producer), and a
1559
- // stuck state (report.stuck) is purely informational (a brake tripped on
1560
- // one branch while the line still moves on another). Neither is a defect.
2118
+ // escalation brake whose freeze, once lifted, re-arms a producer, or an
2119
+ // idle wait that becomes eligible after time passes), and a stuck state
2120
+ // (report.stuck) is purely informational (a brake tripped on one branch
2121
+ // while the line still moves on another). Neither is a defect.
1561
2122
  // - truncated with no invariant violations / structurally-dead steps / true
1562
2123
  // deadlocks → 0
1563
2124
  const hasDefiniteDefect = hasDefiniteCheckDefect(report);
@@ -1568,13 +2129,17 @@ function dispatch(command, io, args) {
1568
2129
  }
1569
2130
  return 0;
1570
2131
  }
1571
- // The bundle namespace is pure filesystem work on the bytes the user
1572
- // points at — dispatched BEFORE openCtx so pack/inspect/digest neither
1573
- // open/create `.owenloop/state.db` nor touch a remote (same reasoning as
1574
- // lint/check above; see docs/cli.md).
2132
+ // Package-format bundle commands are pure filesystem work on bytes the user
2133
+ // points at. GC also dispatches before openCtx, but its async branch performs
2134
+ // its own read-only snapshot scan and targeted store collection.
1575
2135
  if (command === 'bundle') {
1576
2136
  return dispatchBundle(io, args);
1577
2137
  }
2138
+ // Pending gates exist only on the hub. Reject the local spelling before
2139
+ // openCtx() so this cannot create or inspect a local SQLite state database.
2140
+ if (command === 'pending-gates') {
2141
+ throw new CliError('owenloop pending-gates has no local-engine equivalent; pass --hub <url>');
2142
+ }
1578
2143
  const ctx = openCtx(io, args, command === 'status');
1579
2144
  const { engine, store } = ctx;
1580
2145
  if (command === 'status' && !ctx.definitionDiscoveryComplete) {
@@ -1588,6 +2153,11 @@ function dispatch(command, io, args) {
1588
2153
  title: d.title ?? null,
1589
2154
  inputs: d.inputs.map((i) => i.name),
1590
2155
  steps: d.steps.map((l) => l.name),
2156
+ inputSchemas: d.inputs.map((i) => ({
2157
+ name: i.name,
2158
+ ...(i.schema === undefined ? {} : { schema: i.schema }),
2159
+ })),
2160
+ ...(d.x === undefined ? {} : { x: d.x }),
1591
2161
  })));
1592
2162
  return 0;
1593
2163
  }
@@ -1730,6 +2300,9 @@ function dispatch(command, io, args) {
1730
2300
  }
1731
2301
  case 'show': {
1732
2302
  const wf = need(args, 1, 'workflow');
2303
+ if (store.getWorkflow(wf) === undefined) {
2304
+ throw new CliError(`no such workflow instance: ${wf}`);
2305
+ }
1733
2306
  print(io, store.listArtifacts(wf));
1734
2307
  return 0;
1735
2308
  }
@@ -1899,8 +2472,9 @@ function dispatch(command, io, args) {
1899
2472
  const path = need(args, 2, 'path');
1900
2473
  const by = needOpt(args, 'by');
1901
2474
  const text = needOpt(args, 'text');
1902
- const rejectRes = engine.reject(wf, path, by, text);
1903
- print(io, { ok: true, action: 'reject', path, outcome: rejectRes.outcome });
2475
+ const requested = last(args, 'requested');
2476
+ const rejectRes = engine.reject(wf, path, by, text, requested);
2477
+ print(io, { ok: true, action: 'reject', path, outcome: rejectRes.outcome, ...(requested !== undefined ? { requested } : {}) });
1904
2478
  // §24.4/§4.6: a judge's reject can itself be born-rejected by the CAS
1905
2479
  // guard (stale verdict against a submission that already moved on) —
1906
2480
  // mirror the 'green' handler above: that is a failure, not a success,
@@ -2256,6 +2830,152 @@ function optionalWorkflowRecoveryMarkerDir(io) {
2256
2830
  const home = [io.env.HOME, io.env.USERPROFILE].find((value) => value !== undefined && value.trim() !== '');
2257
2831
  return home === undefined ? undefined : defaultRecoveryMarkerDir(home);
2258
2832
  }
2833
+ const DEFAULT_BUNDLE_GC_KEEP = 2;
2834
+ function bundleGcKeep(args) {
2835
+ if (args.missingOptionValues.has('keep')) {
2836
+ throw new CliError('owenloop bundle gc: --keep requires a positive integer value');
2837
+ }
2838
+ const raw = last(args, 'keep');
2839
+ if (raw === undefined)
2840
+ return DEFAULT_BUNDLE_GC_KEEP;
2841
+ if (!/^[1-9][0-9]*$/u.test(raw)) {
2842
+ throw new CliError(`owenloop bundle gc: invalid --keep '${raw}' (expected a positive integer)`);
2843
+ }
2844
+ const keep = Number(raw);
2845
+ if (!Number.isSafeInteger(keep)) {
2846
+ throw new CliError(`owenloop bundle gc: invalid --keep '${raw}' (expected a finite positive integer)`);
2847
+ }
2848
+ return keep;
2849
+ }
2850
+ function bundleGcPathOverride(args, key, environmentValue) {
2851
+ if (args.missingOptionValues.has(key)) {
2852
+ throw new CliError(`owenloop bundle gc: --${key} requires a non-empty path value`);
2853
+ }
2854
+ const optionValue = last(args, key);
2855
+ if (optionValue !== undefined) {
2856
+ if (optionValue.trim() === '') {
2857
+ throw new CliError(`owenloop bundle gc: --${key} requires a non-empty path value`);
2858
+ }
2859
+ return optionValue;
2860
+ }
2861
+ if (environmentValue !== undefined && environmentValue.trim() === '') {
2862
+ throw new CliError(`owenloop bundle gc: OWENLOOP_${key.toUpperCase()} must be a non-empty path`);
2863
+ }
2864
+ return environmentValue;
2865
+ }
2866
+ /** Collect exact CAS coordinates called by the currently executable non-CAS definitions. */
2867
+ function bundleGcExactCallsFromCurrentDefs(io, defsDir, defsOverride, verbose) {
2868
+ const defs = defsOverride === undefined
2869
+ ? loadDefsWithInstalled(io, defsDir, false, verbose).defs
2870
+ : (existsSync(defsDir) ? loadDefs(defsDir) : new Map());
2871
+ const exactCalls = new Set();
2872
+ for (const def of defs.values()) {
2873
+ // CAS definitions already root their own exact edges through bundleLock.
2874
+ // This scan supplies the missing roots for project, GitHub-add, and legacy
2875
+ // definitions whose snapshots intentionally carry no bundle provenance.
2876
+ if (def.bundleDigest !== undefined)
2877
+ continue;
2878
+ for (const step of def.steps) {
2879
+ if (step.calls === undefined || !step.calls.includes('@'))
2880
+ continue;
2881
+ try {
2882
+ parseWorkflowCoordinate(step.calls);
2883
+ }
2884
+ catch (error) {
2885
+ throw new CliError(`owenloop bundle gc: malformed exact calls target ${JSON.stringify(step.calls)} ` +
2886
+ `in workflow '${def.name}': ${error.message}`);
2887
+ }
2888
+ exactCalls.add(step.calls);
2889
+ }
2890
+ }
2891
+ return [...exactCalls].sort(compareStoreText);
2892
+ }
2893
+ /** Store-aware async branch of the otherwise filesystem-only bundle namespace. */
2894
+ async function dispatchBundleGc(io, args) {
2895
+ assertBundlePositionals(args, 2, 'owenloop bundle gc [--keep <n>] [--global] [--yes]');
2896
+ if (args.options.has('output')) {
2897
+ throw new CliError('owenloop bundle gc: --output is only valid for bundle pack');
2898
+ }
2899
+ const keep = bundleGcKeep(args);
2900
+ // Path selection determines both the destructive target and the snapshot pin
2901
+ // source. Validate every CLI/env override before deriving a root, probing a
2902
+ // DB, or acquiring a writer lock; parseArgs represents a missing value as the
2903
+ // literal string "true", which must never become a filesystem path here.
2904
+ const defsOverride = bundleGcPathOverride(args, 'defs', io.env.OWENLOOP_DEFS);
2905
+ const dbOverride = bundleGcPathOverride(args, 'db', io.env.OWENLOOP_DB);
2906
+ const globalFlag = flag(args, 'global');
2907
+ if (globalFlag && defsOverride !== undefined)
2908
+ throw new CliError(GLOBAL_DEFS_CONFLICT_MSG);
2909
+ const projectRoot = projectStoreRoot(defsOverride ?? join(io.cwd, 'workflows'));
2910
+ let globalRoot;
2911
+ if (globalFlag) {
2912
+ globalRoot = globalStoreRoot(workflowHome(io));
2913
+ }
2914
+ else {
2915
+ try {
2916
+ globalRoot = globalStoreRoot(workflowHome(io));
2917
+ }
2918
+ catch {
2919
+ // Match normal definition discovery: project-only operation remains
2920
+ // available when HOME is absent. No global install can derive a root
2921
+ // either, so model this as a single-root plan and avoid inventing a
2922
+ // coordination path inside the project store.
2923
+ globalRoot = projectRoot;
2924
+ }
2925
+ }
2926
+ const dbPath = dbOverride ?? join(io.cwd, '.owenloop', 'state.db');
2927
+ if (dbOverride === undefined) {
2928
+ const parent = dirname(dbPath);
2929
+ const parentState = lstatSync(parent, { throwIfNoEntry: false });
2930
+ if (parentState?.isSymbolicLink()) {
2931
+ throw new CliError(`refusing runtime database parent '${parent}': it is a symbolic link`);
2932
+ }
2933
+ if (parentState !== undefined && !parentState.isDirectory()) {
2934
+ throw new CliError(`refusing runtime database parent '${parent}': it is not a directory`);
2935
+ }
2936
+ dbPathRefusingSymlink(dbPath);
2937
+ }
2938
+ const readLedger = globalFlag
2939
+ ? undefined
2940
+ : () => {
2941
+ const lf = readLockfile(join(io.cwd, '.owenloop', 'installed.json'));
2942
+ return (source) => {
2943
+ const entry = lf.installed[source];
2944
+ return entry === undefined ? undefined : { sha: entry.sha, path: entry.path };
2945
+ };
2946
+ };
2947
+ const legacyRecovery = globalFlag
2948
+ ? undefined
2949
+ : {
2950
+ lockPath: join(io.cwd, '.owenloop', 'add.lock'),
2951
+ journalPath: join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME),
2952
+ lockfilePath: join(io.cwd, '.owenloop', 'installed.json'),
2953
+ readLedger: readLedger,
2954
+ };
2955
+ const legacyReadBarrier = globalFlag
2956
+ ? {
2957
+ lockPath: join(io.cwd, '.owenloop', 'add.lock'),
2958
+ journalPath: join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME),
2959
+ }
2960
+ : undefined;
2961
+ const result = await collectWorkflowStoreGarbage({
2962
+ projectRoot,
2963
+ globalRoot,
2964
+ level: globalFlag ? 'global' : 'project',
2965
+ keep,
2966
+ yes: flag(args, 'yes'),
2967
+ readSnapshotPins: () => readRuntimeSnapshotBundlePins(dbPath),
2968
+ readExactCalls: () => bundleGcExactCallsFromCurrentDefs(io, projectRoot, defsOverride, flag(args, 'verbose')),
2969
+ ...(readLedger === undefined ? {} : { readLedger }),
2970
+ ...(legacyRecovery === undefined ? {} : { legacyRecovery }),
2971
+ ...(legacyReadBarrier === undefined ? {} : { legacyReadBarrier }),
2972
+ ...(optionalWorkflowRecoveryMarkerDir(io) === undefined
2973
+ ? {}
2974
+ : { recoveryMarkerDir: optionalWorkflowRecoveryMarkerDir(io) }),
2975
+ });
2976
+ print(io, result);
2977
+ return 0;
2978
+ }
2259
2979
  /**
2260
2980
  * The `.wnlp` bundle route of `owenloop add` — the content-addressed store
2261
2981
  * counterpart of the GitHub route. `dispatchAdd` classifies the positional
@@ -2284,9 +3004,9 @@ async function dispatchAddBundle(io, args, source) {
2284
3004
  // A fresh bundle install also needs an external marker directory, so derive
2285
3005
  // that path from the same injected home and never from process state.
2286
3006
  const recoveryMarkerDir = workflowRecoveryMarkerDir(io);
2287
- const root = globalFlag
2288
- ? globalStoreRoot(workflowHome(io))
2289
- : projectStoreRoot(defsOverride ?? join(io.cwd, 'workflows'));
3007
+ const projectRoot = projectStoreRoot(defsOverride ?? join(io.cwd, 'workflows'));
3008
+ const globalRoot = globalStoreRoot(workflowHome(io));
3009
+ const root = globalFlag ? globalRoot : projectRoot;
2290
3010
  const statePaths = workflowStoreStatePaths(root);
2291
3011
  const lockPath = statePaths.lockPath;
2292
3012
  const journalPath = statePaths.journalPath;
@@ -2334,6 +3054,8 @@ async function dispatchAddBundle(io, args, source) {
2334
3054
  source: bundleSource,
2335
3055
  root,
2336
3056
  level: globalFlag ? 'global' : 'project',
3057
+ projectRoot,
3058
+ globalRoot,
2337
3059
  lockPath,
2338
3060
  journalPath,
2339
3061
  recoveryMarkerDir,
@@ -2568,7 +3290,7 @@ async function dispatchAdd(io, args) {
2568
3290
  mkdirRefusingSymlink(canonicalState.stateDir);
2569
3291
  guardStateFile(canonicalState.lockPath, 'canonical install lock');
2570
3292
  guardStateFile(canonicalState.journalPath, 'canonical crash-recovery journal');
2571
- const lockPaths = [...new Set([installLockPath, canonicalState.lockPath])].sort();
3293
+ const lockPaths = [...new Set([installLockPath, canonicalState.lockPath])].sort(compareStoreText);
2572
3294
  const locks = [];
2573
3295
  try {
2574
3296
  for (const path of lockPaths)
@@ -2584,13 +3306,10 @@ async function dispatchAdd(io, args) {
2584
3306
  // must NOT delete it (the error message tells the user to recover it).
2585
3307
  let preserveStagingRoot = false;
2586
3308
  try {
2587
- // Recover a crash-interrupted prior install FIRST — before the stale-staging
2588
- // clear, since the backups/parked dirs a rollback needs live UNDER the
2589
- // staging root, so clearing it first would destroy them. Any refusal (bad or
2590
- // mismatched or contradictory journal) must preserve the staging root and the
2591
- // journal as evidence: without this, the `finally` below would rmSync the
2592
- // staging root and take the backups a later recovery needs with it.
3309
+ // Recover crash-interrupted GC parking and installs FIRST — before the
3310
+ // stale-staging clear, since either can own evidence below that shared root.
2593
3311
  try {
3312
+ recoverInterruptedWorkflowStoreGc({ root: defsDir, stateDir: canonicalState.stateDir });
2594
3313
  recoverInterruptedInstall({
2595
3314
  defsDir,
2596
3315
  journalPath: canonicalState.journalPath,
@@ -2897,7 +3616,9 @@ async function dispatchAddRecover(io, args) {
2897
3616
  guardStateFile(canonicalState.lockPath, 'canonical install lock');
2898
3617
  guardStateFile(canonicalState.journalPath, 'canonical crash-recovery journal');
2899
3618
  }
2900
- const lockPaths = [...new Set([installLockPath, ...(canonicalStateExists ? [canonicalState.lockPath] : [])])].sort();
3619
+ const lockPaths = [
3620
+ ...new Set([installLockPath, ...(canonicalStateExists ? [canonicalState.lockPath] : [])]),
3621
+ ].sort(compareStoreText);
2901
3622
  const locks = [];
2902
3623
  try {
2903
3624
  for (const path of lockPaths)
@@ -2910,6 +3631,9 @@ async function dispatchAddRecover(io, args) {
2910
3631
  }
2911
3632
  let outcome = 'no-journal';
2912
3633
  try {
3634
+ if (canonicalStateExists) {
3635
+ recoverInterruptedWorkflowStoreGc({ root: defsDir, stateDir: canonicalState.stateDir });
3636
+ }
2913
3637
  const canonicalOutcome = recoverInterruptedInstall({
2914
3638
  defsDir,
2915
3639
  journalPath: canonicalState.journalPath,
@@ -3157,7 +3881,8 @@ async function authedPost(io, origin, slot, cred, path, body, persist = true) {
3157
3881
  /**
3158
3882
  * A 401 on an agent token is a hard "revoked/invalid" error; a 401 on any
3159
3883
  * other credential kind (after `authedGet`'s one refresh-and-retry) is a hard
3160
- * "credential rejected" error; any other non-2xx is a generic hub-rejected
3884
+ * "credential rejected" error; a 429 is a rate-limit error (including
3885
+ * `Retry-After` when present); any other non-2xx is a generic hub-rejected
3161
3886
  * error naming the status. Shared by `verifyCredential` and `dispatchPush`'s
3162
3887
  * server-list fetch so both surfaces the same wording for the same failure.
3163
3888
  */
@@ -3168,6 +3893,10 @@ function assertAuthOk(res, cred, origin) {
3168
3893
  }
3169
3894
  throw new CliError('credential rejected by the hub — run `owenloop login`');
3170
3895
  }
3896
+ if (res.status === 429) {
3897
+ const retryAfter = res.headers.get('retry-after');
3898
+ throw new CliError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
3899
+ }
3171
3900
  if (!res.ok) {
3172
3901
  throw new CliError(`hub ${origin} rejected the credential (HTTP ${res.status})`);
3173
3902
  }
@@ -3720,6 +4449,116 @@ function orderSelectedDefsByCalls(selected, currentPackage) {
3720
4449
  visit(def);
3721
4450
  return { ordered, dependencies };
3722
4451
  }
4452
+ /**
4453
+ * Publish an already-diffed, already-validated batch of defs — the shared
4454
+ * publish ladder behind BOTH `push` and `install`, so the two can never drift
4455
+ * apart in how they treat a 401, a 413, a 429, a `{ok:false}` 200, or a def
4456
+ * whose selected dependency failed.
4457
+ *
4458
+ * Behavior, unchanged from when this lived inline in `dispatchPush`:
4459
+ * - A def whose selected `calls:` dependency failed or was skipped is SKIPPED,
4460
+ * never published against a half-updated hub.
4461
+ * - A 401 refreshes an oauth credential once and retries once; a 401 that
4462
+ * survives that (or any 401 on an agent token) aborts the whole run by
4463
+ * re-throwing — already-published defs stand.
4464
+ * - A 429 halts the batch immediately (REL-10): this def is `failed`, the
4465
+ * not-yet-attempted remainder is `skipped`, and nothing else is sent.
4466
+ * - Any other per-def failure is recorded and the batch continues.
4467
+ *
4468
+ * `holder.cred` is read before every request and written back after a refresh,
4469
+ * so a mid-batch token rotation is not lost by the caller.
4470
+ */
4471
+ async function publishCandidates(io, origin, slot, holder, toPush, dependencies, bundleDigest) {
4472
+ const pushed = [];
4473
+ const noop = [];
4474
+ const failed = [];
4475
+ const skipped = [];
4476
+ const capabilities = {};
4477
+ const unsuccessful = new Set();
4478
+ for (let i = 0; i < toPush.length; i++) {
4479
+ const c = toPush[i];
4480
+ const label = c.status === 'new' ? '+' : '~';
4481
+ const blockedBy = [...(dependencies.get(c.name) ?? [])]
4482
+ .filter((dependency) => unsuccessful.has(dependency))
4483
+ .sort();
4484
+ if (blockedBy.length > 0) {
4485
+ skipped.push(c.name);
4486
+ unsuccessful.add(c.name);
4487
+ io.err(`- ${c.name} (skipped: selected dependency ${blockedBy.map((name) => `'${name}'`).join(', ')} failed or was skipped)`);
4488
+ continue;
4489
+ }
4490
+ try {
4491
+ let res = await createWorkflowRequest(io, origin, holder.cred, c.yaml, bundleDigest);
4492
+ if (res.status === 401 && holder.cred.kind === 'oauth') {
4493
+ holder.cred = await refreshOAuth(io, origin, slot, holder.cred);
4494
+ res = await createWorkflowRequest(io, origin, holder.cred, c.yaml, bundleDigest);
4495
+ }
4496
+ if (res.status === 401) {
4497
+ if (holder.cred.kind === 'agent') {
4498
+ throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
4499
+ }
4500
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
4501
+ }
4502
+ if (res.status === 413)
4503
+ throw new CliError('workflow yaml exceeds the hub 32MB request cap');
4504
+ if (res.status === 429) {
4505
+ const retryAfter = res.headers.get('retry-after');
4506
+ throw new RateLimitError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
4507
+ }
4508
+ if (!res.ok)
4509
+ throw new CliError(`hub returned HTTP ${res.status}`);
4510
+ const bodyJson = await res.json();
4511
+ const errText = createWorkflowError(bodyJson);
4512
+ if (errText !== null)
4513
+ throw new CliError(`hub rejected the def: ${errText}`);
4514
+ const okBody = asCreateWorkflowOk(bodyJson, c.name);
4515
+ if (okBody.unchanged) {
4516
+ noop.push(c.name);
4517
+ io.err(`= ${c.name} (server: unchanged, v${okBody.version})`);
4518
+ }
4519
+ else {
4520
+ pushed.push(c.name);
4521
+ io.err(`${label} ${c.name} (→ v${okBody.version})`);
4522
+ }
4523
+ // The hub sends the report on BOTH branches, `unchanged:true` included, so
4524
+ // an idempotent re-push still tells the pusher what the org vocabulary is.
4525
+ if (okBody.capabilityReport !== undefined) {
4526
+ capabilities[c.name] = okBody.capabilityReport;
4527
+ printCapabilityReport(io, c.name, okBody.capabilityReport);
4528
+ }
4529
+ }
4530
+ catch (e) {
4531
+ // A 429 halts the whole batch immediately (REL-10): record this def as
4532
+ // failed, then stop — the not-yet-attempted remainder is reported as
4533
+ // `skipped`, not silently hammered against a rate-limited server.
4534
+ // Handled before the generic path because RateLimitError extends CliError.
4535
+ if (e instanceof RateLimitError) {
4536
+ const msg = e.message;
4537
+ failed.push({ name: c.name, error: msg });
4538
+ unsuccessful.add(c.name);
4539
+ io.err(`! ${c.name} (failed: ${msg})`);
4540
+ const remainder = toPush.slice(i + 1).map((r) => r.name);
4541
+ skipped.push(...remainder);
4542
+ for (const name of remainder)
4543
+ unsuccessful.add(name);
4544
+ if (remainder.length > 0) {
4545
+ io.err(`stopping — rate limited by the hub; ${remainder.length} def(s) not attempted`);
4546
+ }
4547
+ break;
4548
+ }
4549
+ // A hard auth error aborts the whole run (re-throw); a per-def server
4550
+ // failure is recorded and the batch continues (already-pushed defs stand).
4551
+ if (e instanceof CliError && /run `owenloop login`|re-mint it/.test(e.message)) {
4552
+ throw e;
4553
+ }
4554
+ const msg = e.message;
4555
+ failed.push({ name: c.name, error: msg });
4556
+ unsuccessful.add(c.name);
4557
+ io.err(`! ${c.name} (failed: ${msg})`);
4558
+ }
4559
+ }
4560
+ return { pushed, noop, skipped, failed, capabilities };
4561
+ }
3723
4562
  /**
3724
4563
  * `owenloop push [<defName>...] [--bundle <bundle.wnlp>] [--force]
3725
4564
  * [--dry-run] [--hub <origin>]` — publish local workflow defs, or exact
@@ -3740,6 +4579,11 @@ async function dispatchPush(io, args) {
3740
4579
  }
3741
4580
  const dryRun = flag(args, 'dry-run');
3742
4581
  const force = flag(args, 'force');
4582
+ // `push` publishes defs the ORG authored, so their capabilities join the org's
4583
+ // SHARED vocabulary by default and NOTHING is recorded. `--map` is the only
4584
+ // way `push` writes a mapping at all — the deliberate asymmetry with
4585
+ // `install`, which scopes by default. See `dispatchInstall`.
4586
+ const requestedMap = parseCapabilityMapFlag(args);
3743
4587
  const slot = resolveSlot(args);
3744
4588
  const resolved = resolvePublishingHub(io, args, slot);
3745
4589
  const { origin } = resolved;
@@ -3799,6 +4643,18 @@ async function dispatchPush(io, args) {
3799
4643
  const selectedOrder = orderSelectedDefsByCalls(selected, bundle?.manifest.package.name);
3800
4644
  selected = selectedOrder.ordered;
3801
4645
  const selectedDependencies = selectedOrder.dependencies;
4646
+ assertMapCoversSelection(requestedMap, selected);
4647
+ // Per def, only the entries that def actually authors, and only the
4648
+ // non-identity ones — the hub's resolver drops an identity row anyway, so
4649
+ // posting one would be a write that changes nothing.
4650
+ const mappingWrites = selected
4651
+ .map((def) => ({
4652
+ name: def.name,
4653
+ entries: Object.fromEntries(authoredCapabilitiesOf(def)
4654
+ .filter((cap) => requestedMap[cap] !== undefined && requestedMap[cap] !== cap)
4655
+ .map((cap) => [cap, requestedMap[cap]])),
4656
+ }))
4657
+ .filter((w) => Object.keys(w.entries).length > 0);
3802
4658
  // Client-side validation gate — all-or-nothing, mirroring dispatchAdd exactly.
3803
4659
  // Any failure aborts the entire push; nothing is sent.
3804
4660
  const reasons = failures.map((f) => `${f.file}: ${f.error}`);
@@ -3892,155 +4748,645 @@ async function dispatchPush(io, args) {
3892
4748
  changed: toPush.filter((c) => c.status === 'changed').map((c) => c.name),
3893
4749
  unchanged: unchanged.map((c) => c.name),
3894
4750
  wouldPush: toPush.map((c) => c.name),
4751
+ wouldRecord: Object.fromEntries(mappingWrites.map((w) => [w.name, w.entries])),
3895
4752
  });
3896
4753
  return 0;
3897
4754
  }
4755
+ // `--map` records BEFORE anything is published, the same ordering `install`
4756
+ // uses and for the same reason: a hub that cannot record the mapping must
4757
+ // fail the command with nothing published, never leave the two halves apart.
4758
+ if (mappingWrites.length > 0) {
4759
+ const holder = { cred };
4760
+ const transport = capabilityMappingTransport(io, origin, slot, holder);
4761
+ for (const write of mappingWrites) {
4762
+ await recordCapabilityMappings(transport, write.name, write.entries, origin);
4763
+ for (const [authored, org] of Object.entries(write.entries)) {
4764
+ io.err(` recorded ${write.name}: ${authored} → ${org}`);
4765
+ }
4766
+ }
4767
+ cred = holder.cred;
4768
+ }
3898
4769
  // Refresh an expiring oauth token once up front (per-request 401 refresh below covers mid-batch expiry).
3899
4770
  cred = await ensureFreshOAuth(io, origin, slot, cred);
3900
4771
  if (bundle !== undefined) {
3901
4772
  cred = await uploadPushBundle(io, origin, slot, cred, bundle);
3902
4773
  }
3903
- const pushedNames = [];
3904
- const noopNames = [];
3905
- const failed = [];
3906
- const skipped = [];
3907
- const unsuccessful = new Set();
3908
- for (let i = 0; i < toPush.length; i++) {
3909
- const c = toPush[i];
3910
- const label = c.status === 'new' ? '+' : '~';
3911
- const blockedBy = [...(selectedDependencies.get(c.name) ?? [])]
3912
- .filter((dependency) => unsuccessful.has(dependency))
3913
- .sort();
3914
- if (blockedBy.length > 0) {
3915
- skipped.push(c.name);
3916
- unsuccessful.add(c.name);
3917
- io.err(`- ${c.name} (skipped: selected dependency ${blockedBy.map((name) => `'${name}'`).join(', ')} failed or was skipped)`);
3918
- continue;
3919
- }
3920
- try {
3921
- let res = await createWorkflowRequest(io, origin, cred, c.yaml, bundle?.digest);
3922
- if (res.status === 401 && cred.kind === 'oauth') {
3923
- cred = await refreshOAuth(io, origin, slot, cred);
3924
- res = await createWorkflowRequest(io, origin, cred, c.yaml, bundle?.digest);
3925
- }
3926
- if (res.status === 401) {
3927
- if (cred.kind === 'agent') {
3928
- throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
3929
- }
3930
- throw new CliError('credential rejected by the hub — run `owenloop login`');
3931
- }
3932
- if (res.status === 413)
3933
- throw new CliError('workflow yaml exceeds the hub 32MB request cap');
3934
- if (res.status === 429) {
3935
- const retryAfter = res.headers.get('retry-after');
3936
- throw new RateLimitError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
3937
- }
3938
- if (!res.ok)
3939
- throw new CliError(`hub returned HTTP ${res.status}`);
3940
- const bodyJson = await res.json();
3941
- const errText = createWorkflowError(bodyJson);
3942
- if (errText !== null)
3943
- throw new CliError(`hub rejected the def: ${errText}`);
3944
- const okBody = asCreateWorkflowOk(bodyJson, c.name);
3945
- if (okBody.unchanged) {
3946
- noopNames.push(c.name);
3947
- io.err(`= ${c.name} (server: unchanged, v${okBody.version})`);
3948
- }
3949
- else {
3950
- pushedNames.push(c.name);
3951
- io.err(`${label} ${c.name} (→ v${okBody.version})`);
3952
- }
3953
- }
3954
- catch (e) {
3955
- // A 429 halts the whole batch immediately (REL-10): record this def as
3956
- // failed, then stop — the not-yet-attempted remainder is reported as
3957
- // `skipped`, not silently hammered against a rate-limited server.
3958
- // Handled before the generic path because RateLimitError extends CliError.
3959
- if (e instanceof RateLimitError) {
3960
- const msg = e.message;
3961
- failed.push({ name: c.name, error: msg });
3962
- unsuccessful.add(c.name);
3963
- io.err(`! ${c.name} (failed: ${msg})`);
3964
- const remainder = toPush.slice(i + 1).map((r) => r.name);
3965
- skipped.push(...remainder);
3966
- for (const name of remainder)
3967
- unsuccessful.add(name);
3968
- if (remainder.length > 0) {
3969
- io.err(`stopping — rate limited by the hub; ${remainder.length} def(s) not attempted`);
3970
- }
3971
- break;
3972
- }
3973
- // A hard auth error aborts the whole run (re-throw); a per-def server
3974
- // failure is recorded and the batch continues (already-pushed defs stand).
3975
- if (e instanceof CliError && /run `owenloop login`|re-mint it/.test(e.message)) {
3976
- throw e;
3977
- }
3978
- const msg = e.message;
3979
- failed.push({ name: c.name, error: msg });
3980
- unsuccessful.add(c.name);
3981
- io.err(`! ${c.name} (failed: ${msg})`);
3982
- }
3983
- }
4774
+ const holder = { cred };
4775
+ const published = await publishCandidates(io, origin, slot, holder, toPush, selectedDependencies, bundle?.digest);
3984
4776
  print(io, {
3985
- ok: failed.length === 0,
4777
+ ok: published.failed.length === 0,
3986
4778
  hub: origin,
3987
4779
  ...(bundle === undefined ? {} : { bundleDigest: bundle.digest, publication: bundle.publicationState }),
3988
- pushed: pushedNames,
3989
- noop: noopNames,
4780
+ pushed: published.pushed,
4781
+ noop: published.noop,
3990
4782
  unchanged: unchanged.map((c) => c.name),
3991
- skipped,
3992
- failed,
4783
+ skipped: published.skipped,
4784
+ failed: published.failed,
4785
+ capabilities: published.capabilities,
3993
4786
  });
3994
- return failed.length === 0 ? 0 : 1;
4787
+ return published.failed.length === 0 ? 0 : 1;
3995
4788
  }
3996
4789
  finally {
3997
4790
  if (bundle !== undefined)
3998
4791
  rmSync(bundle.cleanupRoot, { recursive: true, force: true });
3999
4792
  }
4000
4793
  }
4794
+ // ---- capability mapping (shared by `push --map` and `install`) ---------------
4001
4795
  /**
4002
- * Resolve the hub for the per-run commands (`start`, `cancel`) without ever
4003
- * falling through to the production default or an ambient `OWENLOOP_HUB`. A
4004
- * connected project supplies the durable default. `--hub` is allowed for an
4005
- * unbound directory, but must agree with an existing binding so a copied
4006
- * command cannot silently start — or cancel — a run on the wrong control plane.
4796
+ * Every authored capability one def declares, deduped, in first-authored order.
4797
+ *
4798
+ * Judge steps are synthesized into `def.steps` by the def parser, so iterating
4799
+ * `steps` covers them — there is no second place capabilities can be written.
4800
+ * Order is the order an operator reads the YAML top-down, which is the order
4801
+ * the install prompt asks in.
4007
4802
  */
4008
- function resolveStartHub(io, args) {
4009
- const binding = readHubBinding(hubBindingPath(io.cwd));
4010
- let bound;
4011
- if (binding !== null) {
4012
- try {
4013
- bound = normalizeOrigin(binding.hub);
4014
- }
4015
- catch (e) {
4016
- throw new CliError(`${e.message} — re-run \`owenloop connect\` to rebind`);
4017
- }
4018
- }
4019
- const hubArg = last(args, 'hub');
4020
- if (hubArg !== undefined) {
4021
- let requested;
4022
- try {
4023
- requested = normalizeOrigin(hubArg);
4024
- }
4025
- catch (e) {
4026
- throw new CliError(e.message);
4027
- }
4028
- if (bound !== undefined && requested !== bound) {
4029
- throw new CliError(`this project is bound to ${bound}, not ${requested} — re-run \`owenloop connect\` to rebind`);
4803
+ function authoredCapabilitiesOf(def) {
4804
+ const names = [];
4805
+ for (const step of def.steps) {
4806
+ for (const cap of step.capabilities ?? []) {
4807
+ if (!names.includes(cap))
4808
+ names.push(cap);
4030
4809
  }
4031
- return requested;
4032
4810
  }
4033
- if (bound !== undefined)
4034
- return bound;
4035
- throw new CliError('this project is not bound to a hub — run `owenloop connect`, or pass --hub <url>');
4811
+ return names;
4036
4812
  }
4037
- /** Extract the stable hub message without ever echoing an untyped raw body. */
4038
- async function hubRequestMessage(res) {
4039
- try {
4040
- const body = (await res.json());
4041
- if (typeof body !== 'object' || body === null)
4042
- return undefined;
4043
- const message = body.message;
4813
+ /**
4814
+ * The org capability name an OUTSIDE def's capability takes by default:
4815
+ * `<defName>.<authored>`.
4816
+ *
4817
+ * This needs no new separator and invents no escaping. A def name matches
4818
+ * `/^[a-z0-9][a-z0-9_-]*$/i`, so it can never contain a dot, while the def
4819
+ * parser's capability rule reserves only `:` — dots are already legal inside a
4820
+ * capability. So the dot splits the two halves unambiguously in one direction
4821
+ * (the first dot ends the def name) and collides with nothing.
4822
+ */
4823
+ function scopedCapabilityName(defName, authored) {
4824
+ return `${defName}.${authored}`;
4825
+ }
4826
+ /**
4827
+ * The same rule the def parser's `assertAuthoredCapability` applies, restated
4828
+ * for an ORG-side name supplied on the command line or at the prompt:
4829
+ * non-empty, not whitespace, and no `MODIFIER_SEPARATOR`.
4830
+ *
4831
+ * The separator ban is the load-bearing half. `:` is the suffix position the
4832
+ * engine composes the run modifier into at offer time (`wise` + `deep` →
4833
+ * `wise:deep`), so an authored-side value carrying one would be a capability
4834
+ * that can never be composed. The def parser refuses it in YAML; this refuses
4835
+ * it on the mapping's target, which reaches exactly the same position.
4836
+ */
4837
+ function assertMappingTarget(target, where) {
4838
+ if (target.trim().length === 0) {
4839
+ throw new CliError(`${where}: an org capability name must not be empty or whitespace`);
4840
+ }
4841
+ if (target.includes(MODIFIER_SEPARATOR)) {
4842
+ throw new CliError(`${where}: capability '${target}' must not contain '${MODIFIER_SEPARATOR}' — ` +
4843
+ 'the suffix position is reserved for the modifier the engine composes at offer time ' +
4844
+ "(a run carrying 'deep' turns the authored capability 'wise' into 'wise:deep')");
4845
+ }
4846
+ }
4847
+ /**
4848
+ * Parse the repeatable `--map <authored>=<org>` flag shared by `push` and
4849
+ * `install`. `parsePairs` supplies the `expected name=value, got: …` refusal;
4850
+ * every target is then validated by `assertMappingTarget`.
4851
+ */
4852
+ function parseCapabilityMapFlag(args) {
4853
+ const out = {};
4854
+ for (const [authored, target] of Object.entries(parsePairs(all(args, 'map'), false))) {
4855
+ if (authored.trim().length === 0) {
4856
+ throw new CliError('--map: the authored capability name must not be empty or whitespace');
4857
+ }
4858
+ assertMappingTarget(target, `--map ${authored}`);
4859
+ out[authored] = target;
4860
+ }
4861
+ return out;
4862
+ }
4863
+ /**
4864
+ * Refuse a `--map` naming a capability none of the selected defs authors — it
4865
+ * would otherwise be a silent no-op, and a typo in an authored name is exactly
4866
+ * the case where silence is worst (the operator believes a link was made).
4867
+ */
4868
+ function assertMapCoversSelection(map, selected) {
4869
+ const authored = new Set(selected.flatMap((def) => authoredCapabilitiesOf(def)));
4870
+ const unknown = Object.keys(map)
4871
+ .filter((name) => !authored.has(name))
4872
+ .sort();
4873
+ if (unknown.length === 0)
4874
+ return;
4875
+ const known = [...authored].sort();
4876
+ throw new CliError(`--map names ${unknown.length} capability(ies) no selected def authors: ${unknown.join(', ')} — ` +
4877
+ (known.length === 0 ? 'the selected defs author no capabilities' : `authored: ${known.join(', ')}`));
4878
+ }
4879
+ /**
4880
+ * Adapt `authedGet`/`authedPost` into the transport
4881
+ * `src/capability-mapping-client.ts` takes, threading the possibly-refreshed
4882
+ * credential back into `holder` so a mid-command oauth refresh is not lost.
4883
+ *
4884
+ * The client module cannot import these helpers directly — they are private to
4885
+ * `cli.ts`, and `cli.ts` imports the client, so a direct import would be a
4886
+ * cycle. Injecting the transport keeps the 30s deadline, the bounded body,
4887
+ * `redirect: 'error'` and the single 401-refresh-and-retry on the mapping calls
4888
+ * without one.
4889
+ */
4890
+ function capabilityMappingTransport(io, origin, slot, holder) {
4891
+ return {
4892
+ async get(path) {
4893
+ const { res, cred } = await authedGet(io, origin, slot, holder.cred, path);
4894
+ holder.cred = cred;
4895
+ return res;
4896
+ },
4897
+ async post(path, body) {
4898
+ const { res, cred } = await authedPost(io, origin, slot, holder.cred, path, body);
4899
+ holder.cred = cred;
4900
+ return res;
4901
+ },
4902
+ };
4903
+ }
4904
+ /**
4905
+ * The hub's capability publish report for one def, on STDERR — stdout stays
4906
+ * machine JSON. Silent for a hub that sent no report (older than the report) and
4907
+ * for a def that authors no capabilities, so neither case prints a dangling
4908
+ * header.
4909
+ */
4910
+ function printCapabilityReport(io, defName, report) {
4911
+ if (report === undefined)
4912
+ return;
4913
+ const text = capabilityPublishReportText(report);
4914
+ if (text !== '')
4915
+ io.err(`${defName}: ${text}`);
4916
+ }
4917
+ /**
4918
+ * Render the org's live capability vocabulary from `GET /api/capability_routes`
4919
+ * as one line — `review (reviewers), builder (builders), triage (unbound)`.
4920
+ *
4921
+ * The endpoint returns ONE ROW PER `(capability, crew)` pair, so rows are
4922
+ * grouped by capability here. A row whose `crewName` is `null` is a DANGLING
4923
+ * route (the crew is gone) and shows as `unbound`, because that is what it means
4924
+ * for routing: the capability exists in the vocabulary but nothing serves it.
4925
+ */
4926
+ function formatOrgVocabulary(routes) {
4927
+ const crewsByCapability = new Map();
4928
+ for (const route of routes) {
4929
+ const crews = crewsByCapability.get(route.capability);
4930
+ const name = route.crewName;
4931
+ if (crews === undefined)
4932
+ crewsByCapability.set(route.capability, new Set(name === null ? [] : [name]));
4933
+ else if (name !== null)
4934
+ crews.add(name);
4935
+ }
4936
+ return [...crewsByCapability.entries()]
4937
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
4938
+ .map(([capability, crews]) => `${capability} (${crews.size === 0 ? 'unbound' : [...crews].sort().join(', ')})`)
4939
+ .join(', ');
4940
+ }
4941
+ /**
4942
+ * Fetch a public GitHub repo's `workflows/**` at a pinned commit sha, into an
4943
+ * in-memory file map.
4944
+ *
4945
+ * Deliberately its own sequence rather than a refactor of `dispatchAdd`'s: `add`
4946
+ * interleaves this with a project install lock, a crash journal and an atomic
4947
+ * swap that `install` has no business acquiring, and its refusal wording names
4948
+ * `add`'s local install. Only the PRIMITIVES are shared (`parseRepoSpec`,
4949
+ * `githubShaUrl`, `githubTarballUrl`, `readBodyBounded`, `extractTarGz`,
4950
+ * `archivePathViolation`), which is where the security-relevant behavior lives:
4951
+ * the ref is pinned to a 40-char sha before the tarball is fetched, the body is
4952
+ * capped DURING the stream, and every archive path is checked for escape before
4953
+ * it is ever joined (SEC-1).
4954
+ */
4955
+ async function fetchGithubWorkflowFiles(io, spec) {
4956
+ const { owner, repo, ref } = parseRepoSpec(spec);
4957
+ const source = `${owner}/${repo}`;
4958
+ const fetchFn = io.fetch ?? globalThis.fetch;
4959
+ let shaRes;
4960
+ try {
4961
+ shaRes = await fetchFn(githubShaUrl(owner, repo, ref), {
4962
+ headers: { Accept: 'application/vnd.github.sha', 'User-Agent': 'owenloop' },
4963
+ signal: AbortSignal.timeout(ADD_SHA_TIMEOUT_MS),
4964
+ });
4965
+ }
4966
+ catch (e) {
4967
+ const err = e;
4968
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
4969
+ throw new CliError(`timed out after ${ADD_SHA_TIMEOUT_MS / 1000}s resolving ${source}@${ref}`);
4970
+ }
4971
+ throw e;
4972
+ }
4973
+ if (!shaRes.ok) {
4974
+ const notFoundNote = shaRes.status === 404 ? ' (repo or ref not found)' : '';
4975
+ throw new CliError(`could not resolve ${source}@${ref}: GitHub returned ${shaRes.status}${notFoundNote}`);
4976
+ }
4977
+ const shaBytes = await readBodyBounded(shaRes, hubMaxResponseBytes(io), `sha resolution for ${source}@${ref}`);
4978
+ const sha = new TextDecoder().decode(shaBytes).trim();
4979
+ if (!/^[0-9a-f]{40}$/i.test(sha)) {
4980
+ throw new CliError(`unexpected response resolving ${source}@${ref}: expected a 40-char commit sha, got "${sha}"`);
4981
+ }
4982
+ let bytes;
4983
+ try {
4984
+ const tarRes = await fetchFn(githubTarballUrl(owner, repo, sha), {
4985
+ headers: { 'User-Agent': 'owenloop' },
4986
+ signal: AbortSignal.timeout(ADD_TARBALL_TIMEOUT_MS),
4987
+ });
4988
+ if (!tarRes.ok) {
4989
+ throw new CliError(`could not fetch tarball for ${source}@${sha}: GitHub returned ${tarRes.status}`);
4990
+ }
4991
+ bytes = await readBodyBounded(tarRes, tarballMaxBytes(io), `tarball for ${source}@${sha}`);
4992
+ }
4993
+ catch (e) {
4994
+ const err = e;
4995
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
4996
+ throw new CliError(`timed out after ${ADD_TARBALL_TIMEOUT_MS / 1000}s downloading tarball for ${source}@${sha}`);
4997
+ }
4998
+ throw e;
4999
+ }
5000
+ let rawFiles;
5001
+ try {
5002
+ rawFiles = extractTarGz(bytes);
5003
+ }
5004
+ catch (e) {
5005
+ throw new CliError(`could not extract tarball for ${source}@${sha}: ${e.message}`);
5006
+ }
5007
+ const files = new Map();
5008
+ const pathViolations = [];
5009
+ for (const [rawPath, data] of rawFiles) {
5010
+ const firstSlash = rawPath.indexOf('/');
5011
+ const rest = firstSlash >= 0 ? rawPath.slice(firstSlash + 1) : '';
5012
+ if (!rest.startsWith('workflows/'))
5013
+ continue;
5014
+ const relPath = rest.slice('workflows/'.length);
5015
+ if (!relPath)
5016
+ continue;
5017
+ const violation = archivePathViolation(relPath);
5018
+ if (violation) {
5019
+ pathViolations.push(`${rawPath}: ${violation}`);
5020
+ continue;
5021
+ }
5022
+ files.set(relPath, data);
5023
+ }
5024
+ if (pathViolations.length > 0) {
5025
+ throw new CliError(`refusing to install ${source}@${sha} — ${pathViolations.length} unsafe archive path(s) found; nothing published:\n - ${pathViolations.join('\n - ')}`);
5026
+ }
5027
+ if (files.size === 0) {
5028
+ throw new CliError(`no workflows/ directory found in ${source}@${ref}`);
5029
+ }
5030
+ return { source, ref, sha, files };
5031
+ }
5032
+ /**
5033
+ * Ask the operator, one authored capability at a time, what the org should call
5034
+ * it. Enter accepts the prefilled SCOPED default; typing a name links the
5035
+ * capability into the org's existing vocabulary instead.
5036
+ *
5037
+ * Prompt style matches `promptAgentName` / `promptSuccession`: prefilled
5038
+ * default, empty answer accepts it, one re-prompt on an invalid answer, then a
5039
+ * `CliError`. All prompt I/O is stderr, so `| jq` on stdout is unaffected.
5040
+ *
5041
+ * `prompt` is passed in ALREADY RESOLVED by `requirePrompt`, which the caller
5042
+ * ran before any hub I/O — a piped run must fail with the flag names, never
5043
+ * block here after half the work is done.
5044
+ */
5045
+ async function promptCapabilityMapping(io, prompt, defName, authored) {
5046
+ const fallback = scopedCapabilityName(defName, authored);
5047
+ const question = ` ${authored} [${fallback}]: `;
5048
+ for (let attempt = 0; attempt < 2; attempt++) {
5049
+ const raw = (await prompt(question)).trim();
5050
+ if (raw === '')
5051
+ return fallback;
5052
+ try {
5053
+ assertMappingTarget(raw, `capability '${authored}'`);
5054
+ return raw;
5055
+ }
5056
+ catch (e) {
5057
+ io.err(e.message);
5058
+ }
5059
+ }
5060
+ throw new CliError(`no valid org capability name provided for '${authored}'`);
5061
+ }
5062
+ /**
5063
+ * `owenloop install <owner>/<repo>[@ref] [<defName>...] [--map <authored>=<org>]
5064
+ * [--accept-defaults] [--dry-run] [--hub <origin>] [--as <slot>]` — publish defs
5065
+ * authored OUTSIDE your org to your hub, under capability names your org
5066
+ * chooses.
5067
+ *
5068
+ * **This is a PUBLISH verb, a sibling of `push` — not of `add`.** It never
5069
+ * writes into the local `workflows/` directory: `add` already owns local
5070
+ * installation, with its install lock, crash journal and atomic swap, and
5071
+ * duplicating that here would be a second implementation of the same
5072
+ * transaction. `install` fetches the outside def, decides the org-side
5073
+ * capability vocabulary for it, records that mapping, and publishes.
5074
+ *
5075
+ * **Why the mapping is scoped by default.** `push` publishes defs YOU authored,
5076
+ * so their capabilities join the org's SHARED vocabulary — two of your own defs
5077
+ * both authoring `review` deliberately mean the same `review`, served by the
5078
+ * same crews. A def from an unrelated author making the same claim is not the
5079
+ * same claim. So every capability an installed def authors becomes
5080
+ * `<defName>.<capability>` unless the installer says otherwise, once, at install
5081
+ * time. The def content itself is never edited: the mapping is org-side data.
5082
+ *
5083
+ * **Order of operations, and it is the point: record, THEN publish.** Publishing
5084
+ * first would put an unscoped third-party def into the org's vocabulary for the
5085
+ * window between the two calls — exactly the trust-boundary breach this verb
5086
+ * exists to prevent. So a hub that cannot record the mapping fails the command
5087
+ * BEFORE anything is published, and nothing is left half-applied.
5088
+ *
5089
+ * **A hub that cannot record mappings.** The hub's mapping READ is live, but no
5090
+ * shipped `owenloop-service` build has the BATCH write this command needs — it
5091
+ * ships a singular one-row-per-call verb instead, which cannot give the
5092
+ * record-then-publish order its all-or-nothing guarantee (see
5093
+ * `src/capability-mapping-client.ts` for why the plural is not sugar over N
5094
+ * singular calls). Until the batch verb ships, only the IDENTITY case completes
5095
+ * end to end: when every capability keeps its authored name there is nothing to
5096
+ * record — the hub's resolver drops identity rows anyway — so the write is
5097
+ * skipped and the publish proceeds. Every other case stops at the missing verb
5098
+ * with exit 2.
5099
+ *
5100
+ * Exit codes: 0 ok; 1 runtime/hub error (a validation-gate refusal, a per-def
5101
+ * hub rejection, a refused source kind, an invalid `--map`); 2 the hub is
5102
+ * unresolvable, or it does not implement the mapping write; 3 the credential for
5103
+ * the slot is absent or irrecoverable.
5104
+ */
5105
+ async function dispatchInstall(io, args) {
5106
+ // 0. Argument-only work, before anything is fetched or resolved.
5107
+ const spec = need(args, 1, '<source>');
5108
+ const classified = classifyAddSource(spec);
5109
+ if (classified.kind !== 'github') {
5110
+ const what = classified.kind === 'file' ? 'a local .wnlp bundle' : 'an http(s) URL';
5111
+ throw new CliError(`owenloop install: ${what} is not an install source yet — only owner/repo[@ref] (GitHub) is. ` +
5112
+ `Run \`owenloop add ${spec}\` to install it into the local store, then ` +
5113
+ '`owenloop push --bundle <bundle.wnlp>` to publish it.');
5114
+ }
5115
+ const dryRun = flag(args, 'dry-run');
5116
+ const acceptDefaults = flag(args, 'accept-defaults');
5117
+ const requestedMap = parseCapabilityMapFlag(args);
5118
+ const slot = resolveSlot(args);
5119
+ const resolvedHub = resolvePublishingHub(io, args, slot);
5120
+ const { origin } = resolvedHub;
5121
+ const startingCredential = resolvedHub.credential ?? readCredential(io, origin, slot);
5122
+ if (!startingCredential) {
5123
+ throw new CliError(`${emptySlotMessage(origin, slot)} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5124
+ }
5125
+ // Threaded through every hub call so a mid-command oauth refresh is not lost.
5126
+ const holder = { cred: startingCredential };
5127
+ // 1. Fetch the outside repo and materialize its workflows/ into a temp dir.
5128
+ // Nothing under the user's cwd is touched, at any point.
5129
+ const fetched = await fetchGithubWorkflowFiles(io, spec);
5130
+ const sourceRef = `${fetched.source}@${fetched.sha}`;
5131
+ const workRoot = mkdtempSync(join(tmpdir(), 'owenloop-install-'));
5132
+ try {
5133
+ for (const [relPath, data] of fetched.files) {
5134
+ const dest = join(workRoot, relPath);
5135
+ mkdirSync(dirname(dest), { recursive: true });
5136
+ writeFileSync(dest, data);
5137
+ }
5138
+ // 2. Load, narrow to positionals, and order by `calls:` — same machinery push uses.
5139
+ const failures = [];
5140
+ const allDefs = loadDefsRaw(workRoot, failures);
5141
+ const requested = args.positionals.slice(2);
5142
+ let selected;
5143
+ if (requested.length > 0) {
5144
+ selected = [];
5145
+ for (const name of requested) {
5146
+ const def = allDefs.get(name);
5147
+ if (!def) {
5148
+ throw new CliError(`unknown workflow definition '${name}' in ${sourceRef} (found: ${[...allDefs.keys()].sort().join(', ') || 'none'})${failureNote(failures)}`);
5149
+ }
5150
+ selected.push(def);
5151
+ }
5152
+ }
5153
+ else {
5154
+ selected = [...allDefs.values()];
5155
+ }
5156
+ if (selected.length === 0) {
5157
+ throw new CliError(`nothing to install — no workflow definitions found in ${sourceRef}${failureNote(failures)}`);
5158
+ }
5159
+ const selectedOrder = orderSelectedDefsByCalls(selected);
5160
+ selected = selectedOrder.ordered;
5161
+ const selectedDependencies = selectedOrder.dependencies;
5162
+ assertMapCoversSelection(requestedMap, selected);
5163
+ // 3. Client-side validation gate — all-or-nothing, byte-for-byte push's.
5164
+ // Any failure aborts everything: nothing is mapped and nothing is sent.
5165
+ const reasons = failures.map((f) => `${f.file}: ${f.error}`);
5166
+ for (const def of selected) {
5167
+ reasons.push(...lintDef(def).errors.map((e) => `${def.name}: ${e}`));
5168
+ reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
5169
+ const report = modelCheck(def, { assumeProvided: true });
5170
+ if (hasDefiniteCheckDefect(report)) {
5171
+ reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
5172
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
5173
+ `${report.deadlocks.length} true deadlock(s))`);
5174
+ }
5175
+ }
5176
+ // 4. Push candidates: verbatim source yaml + the server-canonical hash.
5177
+ // include:/bodyFile: defs are not hub-pushable, exactly as in `push`.
5178
+ const candidates = [];
5179
+ for (const def of selected) {
5180
+ if (!def.dir) {
5181
+ reasons.push(`${def.name}: has no source file on disk to push`);
5182
+ continue;
5183
+ }
5184
+ const yaml = readFileSync(def.dir, 'utf8');
5185
+ let usesInclude = false;
5186
+ try {
5187
+ usesInclude = (buildDef(parseYaml(yaml), basename(def.dir), dirname(def.dir))._includes?.length ?? 0) > 0;
5188
+ }
5189
+ catch {
5190
+ // A shape error would already have surfaced via the gate above.
5191
+ }
5192
+ if (usesInclude) {
5193
+ reasons.push(`${def.name}: uses include:, not hub-pushable yet`);
5194
+ continue;
5195
+ }
5196
+ try {
5197
+ candidates.push({ name: def.name, hash: hashDefForHub(yaml), yaml });
5198
+ }
5199
+ catch (e) {
5200
+ if (e instanceof DefError && /bodyFile/.test(e.message)) {
5201
+ reasons.push(`${def.name}: uses bodyFile:, not hub-pushable`);
5202
+ continue;
5203
+ }
5204
+ throw e;
5205
+ }
5206
+ }
5207
+ if (reasons.length > 0) {
5208
+ throw new CliError(`refusing to install ${sourceRef} — ${reasons.length} problem(s) found; nothing mapped, nothing published:\n - ${reasons.join('\n - ')}`);
5209
+ }
5210
+ // 5. THE NON-INTERACTIVE GUARD, before a single hub request.
5211
+ // Resolved here rather than at the first question so a piped run fails
5212
+ // with the flag names while the request log is still empty — never after
5213
+ // a mapping read has already happened. If carry-forward later covers
5214
+ // every capability, this prompt is simply never called.
5215
+ const uncovered = selected.some((def) => authoredCapabilitiesOf(def).some((cap) => requestedMap[cap] === undefined));
5216
+ const prompt = !uncovered || acceptDefaults
5217
+ ? undefined
5218
+ : requirePrompt(io, 'owenloop install needs to ask what your org should call each capability this def authors, ' +
5219
+ 'but stdin is not interactive — pass --map <authored>=<org> for each one, ' +
5220
+ 'or --accept-defaults to take the scoped <defName>.<capability> name for all of them');
5221
+ // 6. The org's existing vocabulary, so an operator choosing to LINK is
5222
+ // choosing informed. Read-only; publishes nothing.
5223
+ const { res: routesRes, cred: routesCred } = await authedGet(io, origin, slot, holder.cred, '/api/capability_routes');
5224
+ assertAuthOk(routesRes, routesCred, origin);
5225
+ holder.cred = routesCred;
5226
+ let vocabulary;
5227
+ try {
5228
+ vocabulary = asCapabilityRoutes(await routesRes.json());
5229
+ }
5230
+ catch (e) {
5231
+ throw new CliError(e.message);
5232
+ }
5233
+ // 7. Decide the vocabulary for each def: --map wins, then carry-forward,
5234
+ // then --accept-defaults, then the prompt.
5235
+ const transport = capabilityMappingTransport(io, origin, slot, holder);
5236
+ const plans = [];
5237
+ for (const def of selected) {
5238
+ const authored = authoredCapabilitiesOf(def);
5239
+ const resolved = {};
5240
+ const toRecord = {};
5241
+ if (authored.length === 0) {
5242
+ plans.push({ def, resolved, toRecord });
5243
+ continue;
5244
+ }
5245
+ const existingOrUnsupported = await fetchCapabilityMappings(transport, def.name, origin);
5246
+ const existing = existingOrUnsupported === 'unsupported' ? {} : existingOrUnsupported;
5247
+ const unsupported = existingOrUnsupported === 'unsupported';
5248
+ const needsAsking = authored.filter((cap) => requestedMap[cap] === undefined && (unsupported || existing[cap] === undefined));
5249
+ if (needsAsking.length > 0 && !acceptDefaults) {
5250
+ if (unsupported) {
5251
+ // The risk the operator must see BEFORE the first question: pressing
5252
+ // Enter through the prompts overwrites a deliberate link this hub
5253
+ // cannot report.
5254
+ io.err(`${origin} cannot report capability mappings already recorded for ${def.name} — ` +
5255
+ 'every capability will be asked about again, and the answers overwrite whatever is recorded.');
5256
+ }
5257
+ io.err(`\n${def.name} authors ${authored.length} capability(ies). Enter = keep the scoped name; ` +
5258
+ 'type an org capability to link it into your existing vocabulary.');
5259
+ const vocab = formatOrgVocabulary(vocabulary);
5260
+ io.err(vocab === '' ? 'Your org routes no capabilities yet.' : `Your org already routes: ${vocab}`);
5261
+ io.err('');
5262
+ }
5263
+ for (const cap of authored) {
5264
+ const chosen = requestedMap[cap] ??
5265
+ (unsupported ? undefined : existing[cap]) ??
5266
+ (acceptDefaults || prompt === undefined
5267
+ ? scopedCapabilityName(def.name, cap)
5268
+ : await promptCapabilityMapping(io, prompt, def.name, cap));
5269
+ resolved[cap] = chosen;
5270
+ // Identity rows are dropped hub-side, and a carried-forward row the hub
5271
+ // already holds needs no rewrite — so neither is worth a write.
5272
+ if (chosen !== cap && existing[cap] !== chosen)
5273
+ toRecord[cap] = chosen;
5274
+ }
5275
+ plans.push({ def, resolved, toRecord });
5276
+ }
5277
+ const mapped = Object.fromEntries(plans.map((p) => [p.def.name, p.resolved]));
5278
+ const wouldRecord = plans.filter((p) => Object.keys(p.toRecord).length > 0);
5279
+ // 8. The server diff, the same source of truth `push` uses.
5280
+ const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, holder.cred, '/api/workflows');
5281
+ assertAuthOk(listRes, listCred, origin);
5282
+ holder.cred = listCred;
5283
+ let serverMap;
5284
+ try {
5285
+ serverMap = parseWorkflowList(await listRes.json());
5286
+ }
5287
+ catch (e) {
5288
+ throw new CliError(e.message);
5289
+ }
5290
+ const { toPush, unchanged } = computeServerDiff(candidates, serverMap, false);
5291
+ for (const c of unchanged)
5292
+ io.err(`= ${c.name} (unchanged)`);
5293
+ if (dryRun) {
5294
+ for (const c of toPush)
5295
+ io.err(c.status === 'new' ? `+ ${c.name} (new)` : `~ ${c.name} (changed)`);
5296
+ for (const plan of wouldRecord) {
5297
+ for (const [authored, org] of Object.entries(plan.toRecord)) {
5298
+ io.err(` would record ${plan.def.name}: ${authored} → ${org}`);
5299
+ }
5300
+ }
5301
+ print(io, {
5302
+ ok: true,
5303
+ dryRun: true,
5304
+ hub: origin,
5305
+ source: sourceRef,
5306
+ mapped,
5307
+ wouldRecord: Object.fromEntries(wouldRecord.map((p) => [p.def.name, p.toRecord])),
5308
+ new: toPush.filter((c) => c.status === 'new').map((c) => c.name),
5309
+ changed: toPush.filter((c) => c.status === 'changed').map((c) => c.name),
5310
+ unchanged: unchanged.map((c) => c.name),
5311
+ wouldPush: toPush.map((c) => c.name),
5312
+ });
5313
+ return 0;
5314
+ }
5315
+ // 9. RECORD, THEN PUBLISH. A hub with no mapping writer throws here — with
5316
+ // zero create_workflow calls behind it.
5317
+ const recorded = [];
5318
+ for (const plan of wouldRecord) {
5319
+ await recordCapabilityMappings(transport, plan.def.name, plan.toRecord, origin);
5320
+ recorded.push(plan.def.name);
5321
+ for (const [authored, org] of Object.entries(plan.toRecord)) {
5322
+ io.err(` recorded ${plan.def.name}: ${authored} → ${org}`);
5323
+ }
5324
+ }
5325
+ // 10. Publish, on push's ladder.
5326
+ holder.cred = await ensureFreshOAuth(io, origin, slot, holder.cred);
5327
+ const published = await publishCandidates(io, origin, slot, holder, toPush, selectedDependencies);
5328
+ print(io, {
5329
+ ok: published.failed.length === 0,
5330
+ hub: origin,
5331
+ source: sourceRef,
5332
+ mapped,
5333
+ recorded,
5334
+ pushed: published.pushed,
5335
+ noop: published.noop,
5336
+ unchanged: unchanged.map((c) => c.name),
5337
+ skipped: published.skipped,
5338
+ failed: published.failed,
5339
+ capabilities: published.capabilities,
5340
+ });
5341
+ return published.failed.length === 0 ? 0 : 1;
5342
+ }
5343
+ finally {
5344
+ rmSync(workRoot, { recursive: true, force: true });
5345
+ }
5346
+ }
5347
+ /**
5348
+ * Resolve the hub for the per-run commands (`start`, `cancel`) without ever
5349
+ * falling through to the production default or an ambient `OWENLOOP_HUB`. A
5350
+ * connected project supplies the durable default. `--hub` is allowed for an
5351
+ * unbound directory, but must agree with an existing binding so a copied
5352
+ * command cannot silently start — or cancel — a run on the wrong control plane.
5353
+ */
5354
+ function resolveStartHub(io, args) {
5355
+ const binding = readHubBinding(hubBindingPath(io.cwd));
5356
+ let bound;
5357
+ if (binding !== null) {
5358
+ try {
5359
+ bound = normalizeOrigin(binding.hub);
5360
+ }
5361
+ catch (e) {
5362
+ throw new CliError(`${e.message} — re-run \`owenloop connect\` to rebind`);
5363
+ }
5364
+ }
5365
+ const hubArg = last(args, 'hub');
5366
+ if (hubArg !== undefined) {
5367
+ let requested;
5368
+ try {
5369
+ requested = normalizeOrigin(hubArg);
5370
+ }
5371
+ catch (e) {
5372
+ throw new CliError(e.message);
5373
+ }
5374
+ if (bound !== undefined && requested !== bound) {
5375
+ throw new CliError(`this project is bound to ${bound}, not ${requested} — re-run \`owenloop connect\` to rebind`);
5376
+ }
5377
+ return requested;
5378
+ }
5379
+ if (bound !== undefined)
5380
+ return bound;
5381
+ throw new CliError('this project is not bound to a hub — run `owenloop connect`, or pass --hub <url>');
5382
+ }
5383
+ /** Extract the stable hub message without ever echoing an untyped raw body. */
5384
+ async function hubRequestMessage(res) {
5385
+ try {
5386
+ const body = (await res.json());
5387
+ if (typeof body !== 'object' || body === null)
5388
+ return undefined;
5389
+ const message = body.message;
4044
5390
  return typeof message === 'string' && message !== '' ? message : undefined;
4045
5391
  }
4046
5392
  catch {
@@ -4076,6 +5422,14 @@ async function dispatchStart(io, args) {
4076
5422
  // than a silent unmodified run. Omitting the flag entirely IS the unmodified
4077
5423
  // run — that is the difference `requiredTextOption` preserves.
4078
5424
  const modifier = requiredTextOption('modifier', 'name');
5425
+ // Free routing label. No registry and no enumeration by design (§4.8), so the
5426
+ // only shape check is the one every text option gets: present-but-valueless and
5427
+ // explicitly-empty are usage errors; omitted is omitted.
5428
+ const scope = requiredTextOption('scope', 'label');
5429
+ const priority = requiredTextOption('priority', 'low|normal|high');
5430
+ if (priority !== undefined && !START_PRIORITIES.has(priority)) {
5431
+ throw new CliError(`invalid --priority '${priority}' — must be one of low, normal, high`);
5432
+ }
4079
5433
  const origin = resolveStartHub(io, args);
4080
5434
  const slot = { principal: 'human' };
4081
5435
  const cred = readCredential(io, origin, slot);
@@ -4092,6 +5446,8 @@ async function dispatchStart(io, args) {
4092
5446
  // absent as the same thing, but sending an explicit `undefined` would put a
4093
5447
  // `modifier` key in the JSON body with a null value. Omitted means omitted.
4094
5448
  ...(modifier !== undefined ? { modifier } : {}),
5449
+ ...(scope !== undefined ? { scope } : {}),
5450
+ ...(priority !== undefined ? { priority } : {}),
4095
5451
  };
4096
5452
  const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/start_run', request);
4097
5453
  if (res.status === 401)
@@ -4133,6 +5489,11 @@ async function dispatchStart(io, args) {
4133
5489
  // accepted exactly this value. Printed only when the flag was passed, so an
4134
5490
  // unmodified run's output is byte-identical to what it was before.
4135
5491
  ...(modifier !== undefined ? { modifier } : {}),
5492
+ // Echoed from the request, like `modifier` above, and only when the flag
5493
+ // was passed. A run started without these flags prints exactly what it did
5494
+ // before, while a hub refusal prevents this success output entirely.
5495
+ ...(scope !== undefined ? { scope } : {}),
5496
+ ...(priority !== undefined ? { priority } : {}),
4136
5497
  ...(Array.isArray(wire.stampedCrews) ? { stampedCrews: wire.stampedCrews } : {}),
4137
5498
  ...(Array.isArray(wire.validatedCrews) ? { validatedCrews: wire.validatedCrews } : {}),
4138
5499
  });
@@ -4166,6 +5527,7 @@ async function dispatchStart(io, args) {
4166
5527
  */
4167
5528
  async function dispatchCancel(io, args) {
4168
5529
  const workflow = need(args, 1, 'workflow');
5530
+ assertWorkflowIdShape(workflow);
4169
5531
  if (args.missingOptionValues.has('reason')) {
4170
5532
  throw new CliError('missing value for --reason: expected --reason <text>');
4171
5533
  }
@@ -4220,6 +5582,155 @@ async function dispatchCancel(io, args) {
4220
5582
  });
4221
5583
  return 0;
4222
5584
  }
5585
+ /**
5586
+ * `owenloop retry --hub` — the human stall-clear / answer path for a hub-hosted
5587
+ * run. Local retry remains synchronous in `main()`; this dispatch owns only
5588
+ * the network half so direct synchronous callers keep their existing contract.
5589
+ */
5590
+ async function dispatchRetry(io, args) {
5591
+ const workflow = need(args, 1, 'workflow');
5592
+ const path = need(args, 2, 'path');
5593
+ assertWorkflowIdShape(workflow);
5594
+ if (args.options.has('by')) {
5595
+ throw new CliError('owenloop retry: --by cannot be combined with --hub — the hub attributes the retry to the authenticated human principal');
5596
+ }
5597
+ if (args.missingOptionValues.has('text')) {
5598
+ throw new CliError('missing value for --text: expected --text <guidance>');
5599
+ }
5600
+ const text = last(args, 'text');
5601
+ if (text !== undefined && text.trim() === '') {
5602
+ throw new CliError('invalid empty value for --text: expected --text <guidance>');
5603
+ }
5604
+ const origin = resolveStartHub(io, args);
5605
+ const slot = { principal: 'human' };
5606
+ const cred = readCredential(io, origin, slot);
5607
+ if (cred === null) {
5608
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5609
+ }
5610
+ const request = { workflow, path, ...(text !== undefined ? { text } : {}) };
5611
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/retry_artifact', request);
5612
+ if (res.status === 401)
5613
+ assertAuthOk(res, used, origin);
5614
+ if (!res.ok) {
5615
+ const message = await hubRequestMessage(res);
5616
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5617
+ }
5618
+ // The hub owns the response body contract. Any successful response has
5619
+ // completed the state transition, so expose a stable CLI receipt instead of
5620
+ // assuming fields the server has not promised this client.
5621
+ print(io, { ok: true, action: 'retry', path, workflow, hub: origin });
5622
+ return 0;
5623
+ }
5624
+ /** List the hub's human-input gates without reshaping its response contract. */
5625
+ async function dispatchPendingGates(io, args) {
5626
+ if (args.positionals.length !== 1) {
5627
+ throw new CliError('invalid pending-gates arguments; usage: owenloop pending-gates --hub <url>');
5628
+ }
5629
+ if (args.missingOptionValues.has('hub') || last(args, 'hub') === undefined) {
5630
+ throw new CliError('missing value for --hub: expected --hub <url>');
5631
+ }
5632
+ const origin = resolveStartHub(io, args);
5633
+ const slot = { principal: 'human' };
5634
+ const cred = readCredential(io, origin, slot);
5635
+ if (cred === null) {
5636
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5637
+ }
5638
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/pending_gates', {});
5639
+ if (res.status === 401)
5640
+ assertAuthOk(res, used, origin);
5641
+ if (!res.ok) {
5642
+ const message = await hubRequestMessage(res);
5643
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5644
+ }
5645
+ let body;
5646
+ try {
5647
+ body = (await res.json());
5648
+ }
5649
+ catch {
5650
+ throw new CliError('pending_gates: malformed success response — body is not valid JSON');
5651
+ }
5652
+ print(io, body);
5653
+ return 0;
5654
+ }
5655
+ /**
5656
+ * `owenloop reject --hub` — the human control-plane counterpart to local
5657
+ * `engine.reject()`. The hub owns attribution, so a remote request cannot
5658
+ * carry the local-only `--by` authority input.
5659
+ */
5660
+ async function dispatchReject(io, args) {
5661
+ const workflow = need(args, 1, 'workflow');
5662
+ const path = need(args, 2, 'path');
5663
+ assertWorkflowIdShape(workflow);
5664
+ if (args.options.has('by')) {
5665
+ throw new CliError('owenloop reject: --by cannot be combined with --hub — the hub attributes the rejection to the authenticated human principal');
5666
+ }
5667
+ const text = last(args, 'text');
5668
+ if (args.missingOptionValues.has('text') || text === undefined) {
5669
+ throw new CliError('missing value for --text: expected --text <reason>');
5670
+ }
5671
+ if (text.trim() === '') {
5672
+ throw new CliError('invalid empty value for --text: expected --text <reason>');
5673
+ }
5674
+ if (args.missingOptionValues.has('requested')) {
5675
+ throw new CliError('missing value for --requested: expected --requested <modifier>');
5676
+ }
5677
+ const requested = last(args, 'requested');
5678
+ const origin = resolveStartHub(io, args);
5679
+ const slot = { principal: 'human' };
5680
+ const cred = readCredential(io, origin, slot);
5681
+ if (cred === null) {
5682
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5683
+ }
5684
+ const request = {
5685
+ workflow,
5686
+ path,
5687
+ reason: text,
5688
+ ...(requested !== undefined ? { requested } : {}),
5689
+ };
5690
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/reject_artifact', request);
5691
+ if (res.status === 401)
5692
+ assertAuthOk(res, used, origin);
5693
+ if (!res.ok) {
5694
+ const message = await hubRequestMessage(res);
5695
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5696
+ }
5697
+ print(io, {
5698
+ ok: true,
5699
+ action: 'reject',
5700
+ path,
5701
+ workflow,
5702
+ hub: origin,
5703
+ ...(requested !== undefined ? { requested } : {}),
5704
+ });
5705
+ return 0;
5706
+ }
5707
+ /**
5708
+ * `owenloop provide --hub` — supply a hosted workflow input using the human
5709
+ * control plane. Local input provisioning remains in `main()`.
5710
+ */
5711
+ async function dispatchProvide(io, args) {
5712
+ const workflow = need(args, 1, 'workflow');
5713
+ const name = need(args, 2, 'name');
5714
+ assertWorkflowIdShape(workflow);
5715
+ // Keep this ahead of binding, credentials, and fetch: malformed input has no
5716
+ // external effects, matching the local provide command's JSON contract.
5717
+ const value = parseJson(last(args, 'value'));
5718
+ const origin = resolveStartHub(io, args);
5719
+ const slot = { principal: 'human' };
5720
+ const cred = readCredential(io, origin, slot);
5721
+ if (cred === null) {
5722
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5723
+ }
5724
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/provide_input', { workflow, name, value });
5725
+ if (res.status === 401)
5726
+ assertAuthOk(res, used, origin);
5727
+ if (!res.ok) {
5728
+ const message = await hubRequestMessage(res);
5729
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5730
+ }
5731
+ print(io, { ok: true, provided: name, workflow, hub: origin });
5732
+ return 0;
5733
+ }
4223
5734
  /**
4224
5735
  * `owenloop instance` — read a HUB instance's live state from the terminal.
4225
5736
  *
@@ -4263,14 +5774,15 @@ async function dispatchInstance(io, args) {
4263
5774
  if (workflow === undefined || workflow === '') {
4264
5775
  throw new CliError(`missing required argument: workflow (${USAGE_FORMS})`);
4265
5776
  }
5777
+ assertWorkflowIdShape(workflow);
4266
5778
  const origin = resolveStartHub(io, args);
4267
5779
  const slot = { principal: 'human' };
4268
5780
  const cred = readCredential(io, origin, slot);
4269
5781
  if (cred === null) {
4270
5782
  throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
4271
5783
  }
4272
- // The workflow id is a path segment, so it must be encoded — an id carrying a
4273
- // slash would otherwise silently address a different route.
5784
+ // Retain path-segment encoding as defense in depth: the validator currently
5785
+ // excludes slashes, but the hub remains a separate service boundary.
4274
5786
  const path = `/api/status/${encodeURIComponent(workflow)}`;
4275
5787
  const { res, cred: used } = await authedGet(io, origin, slot, cred, path);
4276
5788
  if (res.status === 401)
@@ -4679,8 +6191,8 @@ async function dispatchCapability(io, args) {
4679
6191
  if (sub === 'list') {
4680
6192
  const { res, cred: used } = await authedGet(io, origin, slot, cred, '/api/capability_routes');
4681
6193
  // The GET deliberately uses `assertAuthOk` unchanged (frozen contract), so
4682
- // a non-401 non-2xx surfaces its generic wording rather than the hub's
4683
- // `message`. Message passthrough is a POST-path behavior below.
6194
+ // a non-401/non-429 non-2xx surfaces its generic wording while a 429 uses
6195
+ // the helper's rate-limit wording. Message passthrough is a POST-path behavior below.
4684
6196
  assertAuthOk(res, used, origin);
4685
6197
  let body;
4686
6198
  try {
@@ -4840,7 +6352,7 @@ async function dispatchCapability(io, args) {
4840
6352
  * finds out it happened.
4841
6353
  *
4842
6354
  * **`routing show <workflow>` is NOT the local `show` command.** `owenloop show`
4843
- * reads a workflow DEFINITION out of the local sqlite store and takes no `--hub`;
6355
+ * reads raw workflow artifacts out of the local sqlite store and takes no `--hub`;
4844
6356
  * `routing show` reads one STARTED RUN's routing state off the hub. They share no
4845
6357
  * code path, and this deliberately did not arrive as a `--hub` flag on the local
4846
6358
  * command — the same separation `instance show` keeps.
@@ -4898,6 +6410,7 @@ async function dispatchRouting(io, args) {
4898
6410
  if (rawWorkflow === undefined || rawWorkflow === '') {
4899
6411
  throw new CliError(`missing required argument: <workflow> (${USAGE_FORMS})`);
4900
6412
  }
6413
+ assertWorkflowIdShape(rawWorkflow);
4901
6414
  workflow = rawWorkflow;
4902
6415
  }
4903
6416
  else if (sub === 'alerts') {
@@ -5016,9 +6529,8 @@ async function dispatchRouting(io, args) {
5016
6529
  return 0;
5017
6530
  }
5018
6531
  if (sub === 'show') {
5019
- // The workflow id is a path segment, so it must be encoded — an id carrying
5020
- // a slash would otherwise silently address a different route
5021
- // (`dispatchInstance`'s precedent).
6532
+ // Retain path-segment encoding as defense in depth: the validator currently
6533
+ // excludes slashes, but the hub remains a separate service boundary.
5022
6534
  const body = await readJson(`/api/run_routing/${encodeURIComponent(workflow)}`, 'run_routing: malformed success response');
5023
6535
  let wire;
5024
6536
  try {
@@ -5289,8 +6801,9 @@ async function dispatchCrew(io, args) {
5289
6801
  try {
5290
6802
  if (sub === 'list') {
5291
6803
  const { res, cred: used } = await authedGet(io, origin, slot, cred, '/api/crews');
5292
- // `assertAuthOk`'s generic wording (frozen contract, mirrors `binding
5293
- // list`); message passthrough is a POST-path behavior below.
6804
+ // `assertAuthOk`'s generic wording for non-401/non-429 errors (frozen
6805
+ // contract, mirrors `binding list`); a 429 uses its rate-limit wording.
6806
+ // Message passthrough is a POST-path behavior below.
5294
6807
  assertAuthOk(res, used, origin);
5295
6808
  let body;
5296
6809
  try {
@@ -5452,6 +6965,79 @@ async function dispatchCrew(io, args) {
5452
6965
  throw e;
5453
6966
  }
5454
6967
  }
6968
+ /** Probe before any mkdir or temporary write. An existing operator file is a
6969
+ * successful no-op; every other existing filesystem object remains an error. */
6970
+ function hasExistingCrewRosterTarget(path) {
6971
+ try {
6972
+ const target = lstatSync(path);
6973
+ if (!target.isFile())
6974
+ throw new Error(`crew roster target exists but is not a regular file: ${path}`);
6975
+ return true;
6976
+ }
6977
+ catch (error) {
6978
+ if (error.code === 'ENOENT')
6979
+ return false;
6980
+ throw error;
6981
+ }
6982
+ }
6983
+ /**
6984
+ * Install a fully-written strongest-layer roster without replacing an
6985
+ * operator's file. Only EEXIST from the final exclusive link is interpreted
6986
+ * as an existing target; failures creating its parent or temporary file stay
6987
+ * failures instead of being misreported as a harmless skip.
6988
+ */
6989
+ export function installCrewRosterIfAbsent(path, contents, options = {}) {
6990
+ // This is deliberately before mkdir/temp creation: a setup rerun must be a
6991
+ // zero-write no-op even in a read-only or full directory.
6992
+ if (hasExistingCrewRosterTarget(path))
6993
+ return 'existing';
6994
+ const dir = dirname(path);
6995
+ mkdirSync(dir, { recursive: true });
6996
+ const temp = join(dir, options.tempName?.() ?? `.${randomUUID()}.roster.tmp`);
6997
+ let tempWritten = false;
6998
+ try {
6999
+ try {
7000
+ (options.writeTemp ?? ((candidate, body) => writeFileSync(candidate, body, { encoding: 'utf8', flag: 'wx' })))(temp, contents);
7001
+ tempWritten = true;
7002
+ }
7003
+ catch (error) {
7004
+ // `writeFileSync` can throw after creating a partial file (ENOSPC,
7005
+ // interruption). EEXIST is the one exception: that temp was never ours
7006
+ // and must not be removed. Every other failed write gets its partial
7007
+ // cleanup before the error reaches setup.
7008
+ if (error.code !== 'EEXIST') {
7009
+ try {
7010
+ unlinkSync(temp);
7011
+ }
7012
+ catch {
7013
+ // Nothing was created, or cleanup has no recovery path.
7014
+ }
7015
+ }
7016
+ throw error;
7017
+ }
7018
+ try {
7019
+ linkSync(temp, path);
7020
+ return 'created';
7021
+ }
7022
+ catch (error) {
7023
+ if (error.code !== 'EEXIST')
7024
+ throw error;
7025
+ // EEXIST is meaningful only for the target installation. Verify that it
7026
+ // is a real roster file before calling it an intentional operator file.
7027
+ if (!hasExistingCrewRosterTarget(path))
7028
+ throw error;
7029
+ return 'existing';
7030
+ }
7031
+ }
7032
+ finally {
7033
+ if (tempWritten) {
7034
+ try {
7035
+ unlinkSync(temp);
7036
+ }
7037
+ catch { /* target installation already decided; cleanup is best-effort */ }
7038
+ }
7039
+ }
7040
+ }
5455
7041
  /**
5456
7042
  * The plugin checks are rendered but NON-FATAL: a developer may use either
5457
7043
  * Claude Code or Codex, and a missing harness or failed plugin convergence must
@@ -5629,18 +7215,24 @@ async function probeAgentSlots(io, origin, names, identities) {
5629
7215
  return { verified, sawSlot, sawRevoked };
5630
7216
  }
5631
7217
  /**
5632
- * The interactive prompt for setup, or the non-interactive guard. Returns
5633
- * `io.prompt` when injected; else, when stdin is a real TTY, the default
5634
- * readline prompt; else a `CliError` naming the two bypass flags — thrown BEFORE
5635
- * any mutation so a scripted/piped run never blocks or half-applies.
7218
+ * The interactive prompt for a verb that must ask, or the non-interactive
7219
+ * guard. Returns `io.prompt` when injected; else, when stdin is a real TTY, the
7220
+ * default readline prompt; else a `CliError` naming that verb's bypass flags —
7221
+ * thrown BEFORE any mutation (and, for `install`, before any hub I/O at all) so
7222
+ * a scripted/piped run never blocks and never half-applies.
7223
+ *
7224
+ * `unavailable` is the refusal wording. It defaults to `setup`'s, so `setup`'s
7225
+ * callers keep their message byte-for-byte; `install` passes its own, which
7226
+ * must name `--map` and `--accept-defaults`.
5636
7227
  */
5637
- function requirePrompt(io) {
7228
+ function requirePrompt(io, unavailable) {
5638
7229
  if (io.prompt)
5639
7230
  return io.prompt;
5640
7231
  if (process.stdin.isTTY)
5641
7232
  return defaultPrompt;
5642
- throw new CliError('setup needs to ask which Scoped Identity to use, but stdin is not interactive — pass ' +
5643
- '--new-agent <name> to create a new Scoped Identity, or --replace-agent <name> to replace an existing one');
7233
+ throw new CliError(unavailable ??
7234
+ 'setup needs to ask which Scoped Identity to use, but stdin is not interactive — pass ' +
7235
+ '--new-agent <name> to create a new Scoped Identity, or --replace-agent <name> to replace an existing one');
5644
7236
  }
5645
7237
  /**
5646
7238
  * Prompt for an agent name (Flow A). Offers `sanitizeAgentName(hostname())` as a
@@ -5752,7 +7344,7 @@ export function resolveBundledMarketplaceRoot(harness) {
5752
7344
  return null;
5753
7345
  }
5754
7346
  function recordOf(value) {
5755
- return value !== null && typeof value === 'object' ? value : null;
7347
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
5756
7348
  }
5757
7349
  function normalizedPluginVersion(value) {
5758
7350
  if (typeof value !== 'string')
@@ -6076,7 +7668,7 @@ async function registerMachineEnrollment(io, origin, humanCred, keys, humanRef,
6076
7668
  return done('machine key registered');
6077
7669
  }
6078
7670
  /**
6079
- * `owenloop setup` — converge this machine's install in seven probe→(skip|act)
7671
+ * `owenloop setup` — converge this machine's install in eight probe→(skip|act)
6080
7672
  * steps, idempotently: a second run performs ZERO writes (no store mutation, no
6081
7673
  * key generation, no settings write, no browser, no mint/rekey/register POST).
6082
7674
  * Each ACT is reached only through its probe failing.
@@ -6163,8 +7755,8 @@ async function dispatchSetup(io, args) {
6163
7755
  }
6164
7756
  const origin = resolveSetupHub(io, args);
6165
7757
  const steps = [];
6166
- // --- [1/7] inspect: zero writes, best-effort probes ---
6167
- io.err('[1/7] inspect');
7758
+ // --- [1/8] inspect: zero writes, best-effort probes ---
7759
+ io.err('[1/8] inspect');
6168
7760
  io.err(` human credential: ${readCredential(io, origin, { principal: 'human' }) !== null ? 'present' : 'none — will log in'}`);
6169
7761
  const inspectSettingsPath = owenloopSettingsPath(io.env);
6170
7762
  let settingsNote;
@@ -6189,8 +7781,8 @@ async function dispatchSetup(io, args) {
6189
7781
  ? ' agent slots: checked in step 3'
6190
7782
  : ` agent slots: ${inspectAccts.length ? inspectAccts.map((a) => `agent:${a}`).join(', ') : 'none'}`);
6191
7783
  steps.push({ step: 'inspect', action: 'done', detail: 'probed local state' });
6192
- // --- [2/7] human login: the hard gate that makes step 3's rekey legal ---
6193
- io.err('[2/7] human login');
7784
+ // --- [2/8] human login: the hard gate that makes step 3's rekey legal ---
7785
+ io.err('[2/8] human login');
6194
7786
  let humanCred = readCredential(io, origin, { principal: 'human' });
6195
7787
  let humanIdentity;
6196
7788
  if (humanCred !== null) {
@@ -6218,8 +7810,8 @@ async function dispatchSetup(io, args) {
6218
7810
  io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
6219
7811
  steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
6220
7812
  }
6221
- // --- [3/7] agent ---
6222
- io.err('[3/7] agent');
7813
+ // --- [3/8] agent ---
7814
+ io.err('[3/8] agent');
6223
7815
  const { res: idRes } = await authedGet(io, origin, { principal: 'human' }, humanCred, '/api/agent_identities');
6224
7816
  if (idRes.status === 403) {
6225
7817
  throw new CliError('setup needs an admin credential to manage Scoped Identities (hub returned 403)');
@@ -6230,12 +7822,14 @@ async function dispatchSetup(io, args) {
6230
7822
  candidateNames.add('default');
6231
7823
  const probe = await probeAgentSlots(io, origin, [...candidateNames], identities);
6232
7824
  let agentAccount;
7825
+ let agentCrews;
6233
7826
  // The stable principal id for the agent signing key: the hub's agent actor
6234
7827
  // id (`agentId`), which rekey preserves and mint mints fresh.
6235
7828
  let agentPrincipalId;
6236
7829
  if (probe.verified !== null) {
6237
7830
  agentAccount = probe.verified.name;
6238
7831
  agentPrincipalId = probe.verified.actorId;
7832
+ agentCrews = probe.verified.identity?.crews;
6239
7833
  const crewsStr = probe.verified.identity ? ` (crews: ${probe.verified.identity.crews.join(', ') || 'none'})` : '';
6240
7834
  io.err(`✓ agent: ${agentAccount}${crewsStr}`);
6241
7835
  steps.push({ step: 'agent', action: 'skipped', detail: `agent:${agentAccount} verified` });
@@ -6269,6 +7863,7 @@ async function dispatchSetup(io, args) {
6269
7863
  const result = await mintAgentCredential(io, origin, { principal: 'human' }, humanCred, { name: action.name, crews, scopes });
6270
7864
  agentAccount = action.name;
6271
7865
  agentPrincipalId = result.agentId;
7866
+ agentCrews = result.crews;
6272
7867
  io.err(`✓ agent: minted agent:${agentAccount} (crews: ${result.crews.join(', ') || 'none'}; scopes: ${result.scopes.join(', ')})`);
6273
7868
  steps.push({ step: 'agent', action: 'done', detail: `minted agent:${agentAccount}` });
6274
7869
  }
@@ -6280,10 +7875,10 @@ async function dispatchSetup(io, args) {
6280
7875
  steps.push({ step: 'agent', action: 'done', detail: `re-keyed agent:${agentAccount}` });
6281
7876
  }
6282
7877
  }
6283
- // --- [4/7] signing keys: human → machine → agent, idempotently ---
7878
+ // --- [4/8] signing keys: human → machine → agent, idempotently ---
6284
7879
  // Prints kind + state + backend ONLY. Never key bytes, fingerprints,
6285
7880
  // secret-store values, or reused private-key paths.
6286
- io.err('[4/7] signing keys');
7881
+ io.err('[4/8] signing keys');
6287
7882
  const keys = io.principalKeys ?? new PrincipalKeyManager({ env: io.env });
6288
7883
  const humanRef = { origin, kind: 'human', id: humanIdentity.actor.id };
6289
7884
  const machineRef = { origin, kind: 'machine', id: 'local' };
@@ -6306,8 +7901,8 @@ async function dispatchSetup(io, args) {
6306
7901
  const enrollment = await registerMachineEnrollment(io, origin, humanCred, keys, humanRef, machine.publicKey);
6307
7902
  io.err(`${enrollment.action === 'noted' ? '!' : '✓'} enrollment: ${enrollment.detail}`);
6308
7903
  steps.push(enrollment);
6309
- // --- [5/7] owenloop settings ---
6310
- io.err('[5/7] owenloop settings');
7904
+ // --- [5/8] owenloop settings ---
7905
+ io.err('[5/8] owenloop settings');
6311
7906
  const settingsPath = owenloopSettingsPath(io.env);
6312
7907
  const existingSettings = readOwenloopSettingsRaw(settingsPath); // corrupt file → hard CliError (never clobber)
6313
7908
  const currentHub = existingSettings && typeof existingSettings.hubOrigin === 'string' ? existingSettings.hubOrigin : undefined;
@@ -6323,16 +7918,40 @@ async function dispatchSetup(io, args) {
6323
7918
  if (agentAccount !== 'default') {
6324
7919
  io.err(`non-default agent account — run owenloop work with OWENLOOP_ACCOUNT=${agentAccount}`);
6325
7920
  }
6326
- // --- [6/7] plugin (non-fatal) ---
6327
- io.err('[6/7] plugin');
7921
+ // --- [6/8] crew rosters ---
7922
+ io.err('[6/8] crew rosters');
7923
+ if (agentCrews === undefined || agentCrews.length === 0) {
7924
+ const detail = 'no crews known for this agent';
7925
+ io.err(`! crew rosters: ${detail}`);
7926
+ steps.push({ step: 'crew rosters', action: 'noted', detail });
7927
+ }
7928
+ else {
7929
+ for (const crew of agentCrews) {
7930
+ const path = crewRosterPath(io.env, crew);
7931
+ // Write a complete private temp first, then install it with link(2): the
7932
+ // link is exclusive (EEXIST leaves an operator file untouched), while a
7933
+ // short write can only leave a removable temp, never a corrupt roster.
7934
+ const installed = installCrewRosterIfAbsent(path, `${JSON.stringify({ crew, note: `machine-local overrides for crew ${crew}; wins over settings.json and hub rosters — see docs/cli.md`, roster: {} }, null, 2)}\n`);
7935
+ if (installed === 'created') {
7936
+ io.err(`✓ crew roster ${crew}: created`);
7937
+ steps.push({ step: 'crew rosters', action: 'done', detail: `${crew}: ${path}` });
7938
+ }
7939
+ else {
7940
+ io.err(`✓ crew roster ${crew}: existing file left untouched`);
7941
+ steps.push({ step: 'crew rosters', action: 'skipped', detail: `${crew}: ${path}` });
7942
+ }
7943
+ }
7944
+ }
7945
+ // --- [7/8] plugin (non-fatal) ---
7946
+ io.err('[7/8] plugin');
6328
7947
  for (const pluginState of probePlugin(io)) {
6329
7948
  const outcome = installPluginStep(io, pluginState);
6330
7949
  const marker = outcome.action === 'noted' ? '!' : '✓';
6331
7950
  io.err(`${marker} plugin (${pluginState.id}): ${outcome.detail}`);
6332
7951
  steps.push({ step: `plugin (${pluginState.id})`, ...outcome });
6333
7952
  }
6334
- // --- [7/7] doctor pass ---
6335
- io.err('[7/7] doctor');
7953
+ // --- [8/8] doctor pass ---
7954
+ io.err('[8/8] doctor');
6336
7955
  const doctor = await runDoctor(io, origin);
6337
7956
  print(io, { ok: doctor.ok, hub: origin, steps, doctor: { ok: doctor.ok, checks: doctor.checks } });
6338
7957
  return doctor.ok ? 0 : 1;
@@ -6526,35 +8145,38 @@ async function runDoctor(io, origin) {
6526
8145
  record('owenloop settings', true, settingsPath, true);
6527
8146
  }
6528
8147
  }
6529
- // Crew-roster diagnostics are informational per crew. The same registry
6530
- // membership predicate the worker uses is intentionally reused here.
8148
+ // Crew-roster diagnostics are informational per crew. Global disk discovery
8149
+ // complements the verified agent's authoritative crew list: a malformed
8150
+ // bounded-hash file cannot decode its own identity, but the worker still
8151
+ // resolves that requested deterministic target and must fail closed on it.
8152
+ const crewNames = new Set();
6531
8153
  try {
6532
- const crewsDir = join(owenloopConfigDir(io.env), 'crews');
6533
- const crews = existsSync(crewsDir)
6534
- ? readdirSync(crewsDir, { withFileTypes: true })
6535
- .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
6536
- .map((entry) => entry.name.slice(0, -'.json'.length))
6537
- .sort()
6538
- : [];
6539
- for (const crew of crews) {
6540
- try {
6541
- const layers = machineRosterLayers(io.env, crew);
6542
- const merged = mergeRosterLayers(layers);
6543
- const found = layers
6544
- .map((layer) => `${layer.source}=${layer.roster === undefined ? 'absent' : 'found'}`)
6545
- .join(', ');
6546
- const harnesses = [...new Set(Object.values(merged).flatMap((entry) => entry.candidates.map((candidate) => candidate.harness)))];
6547
- const present = harnesses.filter((id) => adapterFor(id) !== undefined);
6548
- const missing = harnesses.filter((id) => adapterFor(id) === undefined);
6549
- record(`crew roster (${crew})`, true, `layers: ${found}; harnesses present: ${present.join(', ') || 'none'}; missing: ${missing.join(', ') || 'none'}`, false);
6550
- }
6551
- catch (error) {
6552
- record(`crew roster (${crew})`, false, error instanceof Error ? error.message : String(error), false);
6553
- }
6554
- }
8154
+ for (const file of discoverCrewRosterFiles(io.env))
8155
+ crewNames.add(file.crew);
6555
8156
  }
6556
8157
  catch (error) {
6557
- record('crew roster', false, error instanceof Error ? error.message : String(error), false);
8158
+ record('crew roster discovery', false, error instanceof Error ? error.message : String(error), false);
8159
+ }
8160
+ if (agentProbe.verified?.identity !== undefined) {
8161
+ for (const crew of agentProbe.verified.identity.crews)
8162
+ crewNames.add(crew);
8163
+ }
8164
+ for (const crew of [...crewNames].sort()) {
8165
+ try {
8166
+ const settings = loadSettings(io.env);
8167
+ const layers = effectiveRosterLayers(io.env, crew, { origin: settings.hubOrigin, account: io.env.OWENLOOP_ACCOUNT ?? 'default' });
8168
+ const merged = mergeRosterLayers(layers);
8169
+ const found = layers
8170
+ .map((layer) => `${layer.source}=${layer.roster === undefined ? 'absent' : 'found'}`)
8171
+ .join(', ');
8172
+ const harnesses = [...new Set(Object.values(merged).flatMap((entry) => entry.candidates.map((candidate) => candidate.harness)))];
8173
+ const present = harnesses.filter((id) => adapterFor(id) !== undefined);
8174
+ const missing = harnesses.filter((id) => adapterFor(id) === undefined);
8175
+ record(`crew roster (${crew})`, true, `layers: ${found}; harnesses present: ${present.join(', ') || 'none'}; missing: ${missing.join(', ') || 'none'}`, false);
8176
+ }
8177
+ catch (error) {
8178
+ record(`crew roster (${crew})`, false, error instanceof Error ? error.message : String(error), false);
8179
+ }
6558
8180
  }
6559
8181
  // plugins (rendered; non-core while PLUGIN_CHECK_FATAL is false)
6560
8182
  for (const pluginState of probePlugin(io)) {
@@ -6587,18 +8209,22 @@ async function runDoctor(io, origin) {
6587
8209
  * the async path, so every existing command and test keeps working exactly as
6588
8210
  * before.
6589
8211
  */
6590
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'cancel', 'instance', 'agent', 'capability', 'routing', 'crew', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
8212
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'install', 'start', 'pending-gates', 'cancel', 'provide', 'reject', 'retry', 'instance', 'agent', 'capability', 'routing', 'crew', 'roster', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
6591
8213
  export async function mainAsync(argv, io = defaultIO()) {
6592
8214
  // Delegate execution-side and shift argv tails before root parsing. Their
6593
8215
  // roles own their option grammars, including repeated/value forms that the
6594
8216
  // engine parser must not consume. These dynamic imports are cold-start
6595
8217
  // boundaries: ordinary root commands never evaluate execution adapters.
6596
- if (argv[0] === 'work' || argv[0] === 'shift') {
8218
+ if (argv[0] === 'work' || argv[0] === 'shift' || argv[0] === 'util') {
6597
8219
  try {
6598
8220
  if (argv[0] === 'work') {
6599
8221
  const { mainAsync: runWork } = await import("../packages/work/src/main.js");
6600
8222
  return await runWork(argv.slice(1));
6601
8223
  }
8224
+ if (argv[0] === 'util') {
8225
+ const { mainAsync: runWork } = await import("../packages/work/src/main.js");
8226
+ return await runWork(['util', ...argv.slice(1)]);
8227
+ }
6602
8228
  const { run: runShift } = await import("../packages/work/src/roles/shift.js");
6603
8229
  return await runShift(argv.slice(1));
6604
8230
  }
@@ -6609,13 +8235,16 @@ export async function mainAsync(argv, io = defaultIO()) {
6609
8235
  }
6610
8236
  const args = parseArgs(argv);
6611
8237
  const command = args.positionals[0];
6612
- if (command === undefined || !ASYNC_COMMANDS.has(command)) {
8238
+ const asyncBundleGc = command === 'bundle' && args.positionals[1] === 'gc';
8239
+ if (command === undefined || (!ASYNC_COMMANDS.has(command) && !asyncBundleGc)) {
6613
8240
  return main(argv, io);
6614
8241
  }
6615
8242
  try {
6616
8243
  const short = preflight(command, args, io);
6617
8244
  if (short !== undefined)
6618
8245
  return short;
8246
+ if (asyncBundleGc)
8247
+ return await dispatchBundleGc(io, args);
6619
8248
  switch (command) {
6620
8249
  case 'add':
6621
8250
  return await dispatchAdd(io, args);
@@ -6631,10 +8260,23 @@ export async function mainAsync(argv, io = defaultIO()) {
6631
8260
  return await dispatchTrust(io, args);
6632
8261
  case 'push':
6633
8262
  return await dispatchPush(io, args);
8263
+ case 'install':
8264
+ return await dispatchInstall(io, args);
6634
8265
  case 'start':
6635
8266
  return await dispatchStart(io, args);
8267
+ case 'pending-gates':
8268
+ return args.options.has('hub') ? await dispatchPendingGates(io, args) : main(argv, io);
6636
8269
  case 'cancel':
6637
8270
  return await dispatchCancel(io, args);
8271
+ case 'provide':
8272
+ return args.options.has('hub') ? await dispatchProvide(io, args) : main(argv, io);
8273
+ case 'reject':
8274
+ return args.options.has('hub') ? await dispatchReject(io, args) : main(argv, io);
8275
+ case 'retry':
8276
+ // Local engine store unless --hub; only the hub half is async, and
8277
+ // main()'s own `case 'retry'` stays the local implementation so the
8278
+ // synchronous callers of main() keep working.
8279
+ return args.options.has('hub') ? await dispatchRetry(io, args) : main(argv, io);
6638
8280
  case 'instance':
6639
8281
  return await dispatchInstance(io, args);
6640
8282
  case 'agent':
@@ -6645,6 +8287,8 @@ export async function mainAsync(argv, io = defaultIO()) {
6645
8287
  return await dispatchRouting(io, args);
6646
8288
  case 'crew':
6647
8289
  return await dispatchCrew(io, args);
8290
+ case 'roster':
8291
+ return await dispatchRoster(io, args);
6648
8292
  case 'setup':
6649
8293
  return await dispatchSetup(io, args);
6650
8294
  case 'doctor':