owenloop 0.5.7 → 0.5.9

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 (111) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +7 -8
  3. package/dist/packages/work/src/agent/capability-model.d.ts +64 -82
  4. package/dist/packages/work/src/agent/capability-model.js +94 -91
  5. package/dist/packages/work/src/agent/loop.d.ts +55 -26
  6. package/dist/packages/work/src/agent/loop.js +144 -50
  7. package/dist/packages/work/src/bundle/types.d.ts +3 -3
  8. package/dist/packages/work/src/consumed-verifier.js +6 -17
  9. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  10. package/dist/packages/work/src/exec/loop.js +206 -35
  11. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  12. package/dist/packages/work/src/exec/receipt.js +6 -6
  13. package/dist/packages/work/src/harness/child-env.js +4 -5
  14. package/dist/packages/work/src/harness/claude.js +100 -0
  15. package/dist/packages/work/src/harness/codex.js +3 -4
  16. package/dist/packages/work/src/harness/session-store.d.ts +63 -3
  17. package/dist/packages/work/src/harness/session-store.js +104 -9
  18. package/dist/packages/work/src/hub/client.d.ts +19 -4
  19. package/dist/packages/work/src/hub/client.js +7 -3
  20. package/dist/packages/work/src/hub/types.d.ts +87 -3
  21. package/dist/packages/work/src/main.js +1 -0
  22. package/dist/packages/work/src/roles/agent-run.js +46 -43
  23. package/dist/packages/work/src/roles/exec.js +2 -0
  24. package/dist/packages/work/src/roles/sessions.d.ts +3 -2
  25. package/dist/packages/work/src/roles/sessions.js +9 -2
  26. package/dist/packages/work/src/roles/settings.js +3 -1
  27. package/dist/packages/work/src/roles/shift.js +14 -2
  28. package/dist/packages/work/src/roles/util.d.ts +1 -0
  29. package/dist/packages/work/src/roles/util.js +10 -0
  30. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  31. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  32. package/dist/packages/work/src/settings/roster.d.ts +105 -0
  33. package/dist/packages/work/src/settings/roster.js +439 -0
  34. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  35. package/dist/packages/work/src/settings/serving.js +79 -0
  36. package/dist/packages/work/src/settings/settings.d.ts +25 -24
  37. package/dist/packages/work/src/settings/settings.js +29 -33
  38. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  39. package/dist/packages/work/src/shift/loop.js +299 -51
  40. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  41. package/dist/packages/work/src/shift/runtime.d.ts +15 -0
  42. package/dist/packages/work/src/shift/runtime.js +95 -13
  43. package/dist/packages/work/src/shift/server.js +2 -0
  44. package/dist/packages/work/src/shift/spawn.d.ts +18 -50
  45. package/dist/packages/work/src/shift/spawn.js +30 -65
  46. package/dist/packages/work/src/shift/state.d.ts +29 -2
  47. package/dist/packages/work/src/shift/state.js +45 -15
  48. package/dist/packages/work/src/usage.d.ts +1 -1
  49. package/dist/packages/work/src/usage.js +10 -5
  50. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  51. package/dist/packages/work/src/util/modifier-init.js +73 -0
  52. package/dist/src/bundle/tar.d.ts +9 -4
  53. package/dist/src/bundle/tar.js +9 -4
  54. package/dist/src/capabilities.d.ts +50 -0
  55. package/dist/src/capabilities.js +38 -0
  56. package/dist/src/cli.d.ts +15 -1
  57. package/dist/src/cli.js +1099 -32
  58. package/dist/src/config-dir.d.ts +14 -19
  59. package/dist/src/config-dir.js +16 -24
  60. package/dist/src/credentials.d.ts +1 -1
  61. package/dist/src/credentials.js +1 -1
  62. package/dist/src/crypto/index.d.ts +1 -1
  63. package/dist/src/crypto/index.js +1 -1
  64. package/dist/src/crypto/org-root.d.ts +30 -12
  65. package/dist/src/crypto/org-root.js +162 -14
  66. package/dist/src/crypto/records.d.ts +3 -0
  67. package/dist/src/crypto/records.js +8 -0
  68. package/dist/src/crypto/trust-roots.d.ts +2 -2
  69. package/dist/src/crypto/trust-roots.js +2 -2
  70. package/dist/src/defs.d.ts +6 -1
  71. package/dist/src/defs.js +203 -8
  72. package/dist/src/engine.d.ts +55 -6
  73. package/dist/src/engine.js +172 -22
  74. package/dist/src/global-config.d.ts +4 -7
  75. package/dist/src/global-config.js +4 -7
  76. package/dist/src/hub.d.ts +207 -5
  77. package/dist/src/hub.js +263 -3
  78. package/dist/src/index.d.ts +5 -5
  79. package/dist/src/index.js +3 -3
  80. package/dist/src/mcp/serve.d.ts +22 -0
  81. package/dist/src/mcp/serve.js +88 -8
  82. package/dist/src/model.d.ts +2 -0
  83. package/dist/src/model.js +32 -25
  84. package/dist/src/order-resolver.d.ts +1 -0
  85. package/dist/src/order-resolver.js +8 -1
  86. package/dist/src/schemas/index.d.ts +19 -0
  87. package/dist/src/schemas/order.v1.schema.json +13 -2
  88. package/dist/src/store/pre-commit-verifier.js +1 -1
  89. package/dist/src/store.d.ts +5 -0
  90. package/dist/src/store.js +43 -8
  91. package/dist/src/types.d.ts +64 -7
  92. package/dist/src/work-settings.d.ts +2 -4
  93. package/dist/src/work-settings.js +2 -4
  94. package/docs/agent-runner.md +2 -2
  95. package/docs/authoring.md +90 -2
  96. package/docs/bundles.md +29 -3
  97. package/docs/cli.md +456 -120
  98. package/docs/crypto.md +32 -16
  99. package/docs/design.md +70 -1
  100. package/docs/routing.md +762 -0
  101. package/docs/shift-logs.md +37 -10
  102. package/docs/wire-contracts.md +50 -7
  103. package/examples/workflows/delivery.yaml +31 -14
  104. package/examples/workflows/ship.yaml +10 -2
  105. package/package.json +1 -1
  106. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  107. package/plugins/claude-code/plugin/.mcp.json +1 -1
  108. package/plugins/claude-code/plugin/skills/author/SKILL.md +1 -2
  109. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  110. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  111. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +1 -2
package/dist/src/cli.js CHANGED
@@ -32,7 +32,7 @@
32
32
  *
33
33
  * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
34
34
  */
35
- import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, 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';
@@ -49,20 +49,25 @@ import { CliError, dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, pa
49
49
  import { packageVersion } from "./package-version.js";
50
50
  import { authHeader, deleteCredential, discoverMetadata, ensureFreshOAuth, hubFetch, hubMaxResponseBytes, mintAgentCredential, readBodyBounded, refreshOAuth, rekeyAgentCredential, storeCredential, } from "./credentials.js";
51
51
  import { PrincipalKeyManager } from "./crypto/keys.js";
52
- import { createHash } from 'node:crypto';
52
+ import { createHash, randomUUID } from 'node:crypto';
53
53
  import { DSSE_SSH_NAMESPACE, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignOrigin, dsseSignPublication, dsseSignRevocation, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_PUBLICATION, } from "./crypto/dsse.js";
54
54
  import { assertEd25519PubText, createSshSigner, SshSignerError } from "./crypto/ssh.js";
55
55
  import { publicKeyDescriptor } from "./crypto/keys.js";
56
56
  import { DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry } from "./crypto/enrollment.js";
57
57
  import { resolveAllowedSigners } from "./crypto/trust-roots.js";
58
- import { orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, rosterDir, } from "./crypto/org-root.js";
58
+ import { orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, assertNoStrandedLegacyGrants, grantsDir, } from "./crypto/org-root.js";
59
59
  import { runMcpCommand } from "./mcp/serve.js";
60
60
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
61
61
  import { BundleError, digestBundle, inspectBundle, packBundle, unpackBundle } from "./bundle/index.js";
62
62
  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
63
  import { BundleIngestorUnavailableError, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, projectStoreRoot, createBundleIngestor, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.js";
64
- import { asAgentIdentities, asCreateWorkflowOk, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, 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 { 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";
65
65
  import { loadSettings, settingsPath as executionSettingsPath } from "../packages/work/src/settings/settings.js";
66
+ import { discoverCrewRosterFiles, crewRosterPath, effectiveRosterLayers, explainRosterShadows, mergeRosterLayers } from "../packages/work/src/settings/roster.js";
67
+ import { readHubRosterCache, syncHubRosterCache } from "../packages/work/src/settings/hub-roster-cache.js";
68
+ import { adapterFor } from "../packages/work/src/harness/registry.js";
69
+ import "../packages/work/src/harnesses.js";
70
+ import { owenloopConfigDir } from "./config-dir.js";
66
71
  import { owenloopSettingsPath, readOwenloopSettingsRaw, writeOwenloopHubOrigin } from "./work-settings.js";
67
72
  import { globalConfigPath, writeGlobalConfig } from "./global-config.js";
68
73
  import { canonicalJsonBytes, defaultRecoveryMarkerDir, ensureDirectoryPathNoSymlink, guardStateFile } from "./install.js";
@@ -957,6 +962,12 @@ async function dispatchTrust(io, args) {
957
962
  throw new CliError(`owenloop trust grant: ${error instanceof Error ? error.message : String(error)}`);
958
963
  }
959
964
  const signer = signingKeyInfo(io, signingPath);
965
+ try {
966
+ assertNoStrandedLegacyGrants(io.env);
967
+ }
968
+ catch (error) {
969
+ throw new CliError(`owenloop trust grant: ${error instanceof Error ? error.message : String(error)}`);
970
+ }
960
971
  const record = {
961
972
  newKey: {
962
973
  keyid: newKey.keyid,
@@ -972,7 +983,7 @@ async function dispatchTrust(io, args) {
972
983
  const sshSigner = createSshSigner({ namespace: DSSE_SSH_NAMESPACE, signKeyPath: signer.path });
973
984
  try {
974
985
  const signed = await dsseSignEnrollmentGrant(Buffer.from(canonicalJsonBytes(record)), sshSigner);
975
- const output = trustEnvelopeOutput(args, io.cwd, join(rosterDir(io.env), `${trustKeyHash(newKey.keyid)}.grant.dsse`));
986
+ const output = trustEnvelopeOutput(args, io.cwd, join(grantsDir(io.env), `${trustKeyHash(newKey.keyid)}.grant.dsse`));
976
987
  writeTrustEnvelope(output, signed.envelope);
977
988
  print(io, { ok: true, path: output, keyid: newKey.keyid, grantedBy: signer.keyid, principal, validFrom: record.validFrom });
978
989
  }
@@ -1120,11 +1131,14 @@ Commands:
1120
1131
  push [<defName>...] [--bundle <bundle.wnlp>] [--force] [--dry-run] [--hub <origin>] [--as <slot>]
1121
1132
  publish local workflow defs, or exact bundle-backed defs, to the safely resolved hub (server-diffed, idempotent)
1122
1133
  --as names the credential slot: human (default), agent, or agent:<account>
1123
- start <defName> [--provide name=json ...] [--crew <name>] [--title <text>] [--modifier <name>] [--hub <url>]
1134
+ start <defName> [--provide name=json ...] [--crew <name>] [--title <text>] [--modifier <name>] [--scope <label>] [--priority <low|normal|high>] [--hub <url>]
1124
1135
  ${' '.repeat(41)}start a published workflow on the bound hub (human credential)
1125
1136
  ${' '.repeat(41)}--modifier names one value from the def's declared \`modifiers:\` set; every
1126
1137
  ${' '.repeat(41)}step's capability is then offered as \`<capability>:<modifier>\`. Omit it and
1127
1138
  ${' '.repeat(41)}the run carries no modifier and its steps are offered on BARE capabilities.
1139
+ ${' '.repeat(41)}--scope is a free routing label recorded on the run — no registry, no fixed set.
1140
+ ${' '.repeat(41)}Omit it and the run is routed by the org's routes alone.
1141
+ ${' '.repeat(41)}--priority is one of low, normal, high. Omit it and the hub applies normal.
1128
1142
  cancel <workflow> [--reason <text>] [--hub <url>]
1129
1143
  ${' '.repeat(41)}cancel a running instance on the bound hub (human credential; agents cannot cancel).
1130
1144
  ${' '.repeat(41)}Closes every open lease so the run stops being re-offered, and records the
@@ -1132,11 +1146,22 @@ ${' '.repeat(41)}terminal status \`cancelled\`. Cancelling an already-terminal i
1132
1146
  instance show <workflow> [--hub <url>]
1133
1147
  ${' '.repeat(41)}print one instance's live state on the bound hub: whether it is done, what it
1134
1148
  ${' '.repeat(41)}owes, which steps are eligible or blocked, which runs are in flight, and whether
1135
- ${' '.repeat(41)}the loaded def has drifted from the version the instance is pinned to.
1149
+ ${' '.repeat(41)}the loaded def has drifted from the version the instance is pinned to, and whether
1150
+ ${' '.repeat(41)}the instance has reached a terminal status.
1136
1151
  agent new <name> [--crews <a,b>] [--scopes <a,b>] [--shift] [--hub <url>] mint a new Scoped Identity on the hub and store its token in slot agent:<name> (the token is never printed; --shift = --scopes work,run)
1137
1152
  capability bind <capability> <crew> [--hub <url>] add a crew to a workflow capability on the hub org — a capability may bind many crews (admin; human credential)
1138
1153
  capability unbind <capability> <crew> [--hub <url>] remove one (capability, crew) route
1139
1154
  capability list [--hub <url>] list the hub org's capability routes
1155
+ routing alerts [--workflow <wf>] [--limit <n>] [--hub <url>]
1156
+ ${' '.repeat(41)}list the hub org's routing alerts — newest first org-wide; --workflow scopes to
1157
+ ${' '.repeat(41)}one run and flips to oldest first. A \`binding-gap\` alert means the hub HELD an
1158
+ ${' '.repeat(41)}offer because its compound capability had no live crew binding.
1159
+ routing show <workflow> [--hub <url>]
1160
+ ${' '.repeat(41)}print one HUB run's routing: modifier, wait policy, alerts, resolution reports
1161
+ ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads a def from sqlite.
1162
+ routing rule list [--hub <url>] list the org's capability reroute rules in the order the hub tries them
1163
+ 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)
1164
+ routing rule rm <capability> <target> [--hub <url>] remove one reroute rule (admin; a rule that was never there is a no-op)
1140
1165
  crew list [--hub <url>] list the hub org's crews with their members (includes the orphan crew once one exists)
1141
1166
  crew new <name> --kind personal|shared [--owner <memberId>] [--hub <url>] create a crew on the hub org (admin, or own personal crew; human credential)
1142
1167
  crew rm <crewId> [--hub <url>] delete a crew; work stamped to it moves to the org's orphan crew
@@ -1144,6 +1169,17 @@ ${' '.repeat(41)}the loaded def has drifted from the version the instance is pin
1144
1169
  crew member rm <crewId> <principalId> [--hub <url>] remove a principal from a crew
1145
1170
  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)
1146
1171
  doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)
1172
+ roster show [crew] print the offline four-layer roster cascade and provenance
1173
+ roster org [--hub <url>] read the live hub org-global and per-crew rosters (human credential)
1174
+ roster org put <capability> --candidate <harness>:<model>:<effort> [--crew <name>] [--hub <url>]
1175
+ ${' '.repeat(41)}replace one hub roster row (human admin credential)
1176
+ roster org rm <capability> [--crew <name>] [--hub <url>]
1177
+ ${' '.repeat(41)}remove one hub roster row (human admin credential)
1178
+ roster registry [--hub <url>] list hub harnesses, models, and supported efforts (human credential)
1179
+ roster registry put <harness> [--model <model>:<effort,effort…>]… [--display-name <text>] [--hub <url>]
1180
+ ${' '.repeat(41)}replace a harness's hub model snapshot (human admin credential)
1181
+ roster sync [--hub <url>] [--as agent|agent:<account>]
1182
+ ${' '.repeat(41)}refresh the local hub-rosters cache with an agent credential
1147
1183
  enrollments [--hub <url>] list the hub's relayed machine enrollment grants (read-only)
1148
1184
  mcp [--hub <url>] serve the hub control plane over stdio MCP (spawned by MCP hosts, not run by humans)
1149
1185
  work <subcommand> [args] run execution-side shift/hold/exec/agent-run/... commands
@@ -1171,7 +1207,7 @@ ${' '.repeat(41)}the loaded def has drifted from the version the instance is pin
1171
1207
  reject <wf> <path> --by <author> --text <msg>
1172
1208
  retract <wf> <path> --by <author> --text <msg>
1173
1209
  skip <wf> <path> --by <author> --text <msg>
1174
- retry <wf> <path> [--by <author>] [--text <guidance>] clear a §6 stall, or ANSWER an ask
1210
+ retry <wf> <path> [--by <author>] [--text <guidance>] [--hub <url>] clear a §6 stall, or ANSWER an ask
1175
1211
  ask <wf> <path> <question> [--by <author>] hold an owed artifact on a question for a human
1176
1212
  inbox every held question across all instances, with its answer command
1177
1213
  heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run
@@ -1223,14 +1259,20 @@ export const COMMAND_OPTIONS = new Map([
1223
1259
  ['publish', cmdOpts('unsigned', 'output', 'source', 'hub')],
1224
1260
  ['trust', cmdOpts('force', 'key', 'principal', 'pools', 'labels', 'namespaces', 'delegate', 'signing-key', 'output', 'reason', 'effective-from')],
1225
1261
  ['push', cmdOpts('dry-run', 'force', 'hub', 'as', 'bundle')],
1226
- ['start', cmdOpts('hub', 'crew', 'title', 'provide', 'modifier')],
1262
+ ['start', cmdOpts('hub', 'crew', 'title', 'provide', 'modifier', 'scope', 'priority')],
1227
1263
  ['cancel', cmdOpts('hub', 'reason')],
1228
1264
  ['instance', cmdOpts('hub')],
1229
1265
  ['agent', cmdOpts('crews', 'hub', 'scopes', 'shift')],
1230
1266
  ['capability', cmdOpts('hub')],
1267
+ // Per-TOP-LEVEL-command allowlist, not per-subcommand: `--position` on
1268
+ // `routing alerts` is meaningless but accepted and ignored, exactly as
1269
+ // `--kind` is on `crew list`. Policing flags per subcommand is deliberately
1270
+ // not built here.
1271
+ ['routing', cmdOpts('hub', 'workflow', 'limit', 'position')],
1231
1272
  ['crew', cmdOpts('hub', 'kind', 'owner')],
1232
1273
  ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'crews', 'scopes', 'reuse-ssh-key')],
1233
1274
  ['doctor', cmdOpts('hub')],
1275
+ ['roster', cmdOpts('hub', 'crew', 'candidate', 'display-name', 'model', 'as')],
1234
1276
  ['enrollments', cmdOpts('hub')],
1235
1277
  ['mcp', cmdOpts('hub')],
1236
1278
  ['work', cmdOpts()],
@@ -1252,10 +1294,10 @@ export const COMMAND_OPTIONS = new Map([
1252
1294
  ['green', cmdOpts('value', 'terminal')],
1253
1295
  ['emit', cmdOpts('items')],
1254
1296
  ['seal', cmdOpts('value')],
1255
- ['reject', cmdOpts('by', 'text')],
1297
+ ['reject', cmdOpts('by', 'text', 'requested')],
1256
1298
  ['retract', cmdOpts('by', 'text')],
1257
1299
  ['skip', cmdOpts('by', 'text')],
1258
- ['retry', cmdOpts('by', 'text')],
1300
+ ['retry', cmdOpts('by', 'text', 'hub')],
1259
1301
  ['ask', cmdOpts('by', 'question')],
1260
1302
  ['inbox', cmdOpts()],
1261
1303
  ['close', cmdOpts('outcome', 'summary')],
@@ -1334,6 +1376,460 @@ function preflight(command, args, io) {
1334
1376
  assertKnownOptions(command, args);
1335
1377
  return undefined;
1336
1378
  }
1379
+ function rosterAge(fetchedAt) {
1380
+ const seconds = Math.max(0, Math.floor((Date.now() - fetchedAt) / 1_000));
1381
+ if (seconds < 60)
1382
+ return `${seconds}s ago`;
1383
+ if (seconds < 3_600)
1384
+ return `${Math.floor(seconds / 60)}m ago`;
1385
+ if (seconds < 86_400)
1386
+ return `${Math.floor(seconds / 3_600)}h ago`;
1387
+ return `${Math.floor(seconds / 86_400)}d ago`;
1388
+ }
1389
+ // Keep these wire checks aligned with hub-core's roster and harness verbs.
1390
+ // This CLI is a separately deployable client, so it mirrors the public
1391
+ // contract rather than importing the service implementation.
1392
+ const MAX_ROSTER_IDENTIFIER_LENGTH = 200;
1393
+ const MAX_ROSTER_CAPABILITY_LENGTH = 64;
1394
+ const MAX_ROSTER_CANDIDATES = 32;
1395
+ const MAX_HARNESS_MODELS = 256;
1396
+ const ROSTER_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
1397
+ /**
1398
+ * The run's rate-limit priority band. Fixed by the routing plan's §4.8 wire
1399
+ * contract, not by hub discretion, so an out-of-set value is a local usage
1400
+ * error rather than a forwarded request the hub has to refuse.
1401
+ */
1402
+ const START_PRIORITIES = new Set(['low', 'normal', 'high']);
1403
+ function isRosterIdentifier(value) {
1404
+ return typeof value === 'string' && value.length > 0 && value.length <= MAX_ROSTER_IDENTIFIER_LENGTH && value.trim() === value;
1405
+ }
1406
+ function parseRosterIdentifier(value, label) {
1407
+ if (!isRosterIdentifier(value)) {
1408
+ throw new CliError(`${label} must be a trimmed, non-empty string of at most ${MAX_ROSTER_IDENTIFIER_LENGTH} characters`);
1409
+ }
1410
+ return value;
1411
+ }
1412
+ function parseRosterCapability(value) {
1413
+ const capability = value.trim();
1414
+ if (capability === '')
1415
+ throw new CliError('capability must not be empty');
1416
+ if (capability.length > MAX_ROSTER_CAPABILITY_LENGTH) {
1417
+ throw new CliError(`capability must be at most ${MAX_ROSTER_CAPABILITY_LENGTH} characters`);
1418
+ }
1419
+ if (capability.startsWith('personal:'))
1420
+ throw new CliError("capability must not start with the reserved prefix 'personal:'");
1421
+ return capability;
1422
+ }
1423
+ function isRosterCapability(value) {
1424
+ return typeof value === 'string' && value === value.trim() && value.length > 0 &&
1425
+ value.length <= MAX_ROSTER_CAPABILITY_LENGTH && !value.startsWith('personal:');
1426
+ }
1427
+ function isRosterCrewName(value) {
1428
+ // `personal:<id>`, slash, backslash, and `..` are all valid hub names. Only
1429
+ // the service's ordinary non-empty, trimmed, 64-character crew invariant is
1430
+ // relevant at this transport boundary.
1431
+ return typeof value === 'string' && value === value.trim() && value.length > 0 && value.length <= 64;
1432
+ }
1433
+ function isRosterEffort(value) {
1434
+ return typeof value === 'string' && ROSTER_EFFORTS.has(value);
1435
+ }
1436
+ function parseRosterDisplayName(value) {
1437
+ if (value.length > MAX_ROSTER_IDENTIFIER_LENGTH) {
1438
+ throw new CliError(`displayName must be a string of at most ${MAX_ROSTER_IDENTIFIER_LENGTH} characters`);
1439
+ }
1440
+ return value;
1441
+ }
1442
+ function parseRosterCandidate(value) {
1443
+ const first = value.indexOf(':');
1444
+ const lastColon = value.lastIndexOf(':');
1445
+ if (first <= 0 || lastColon <= first || lastColon === value.length - 1) {
1446
+ throw new CliError(`invalid --candidate '${value}' — expected <harness>:<model>:<effort>`);
1447
+ }
1448
+ const harness = parseRosterIdentifier(value.slice(0, first), 'candidate harness');
1449
+ const model = parseRosterIdentifier(value.slice(first + 1, lastColon), 'candidate model');
1450
+ const effort = value.slice(lastColon + 1);
1451
+ if (!isRosterEffort(effort)) {
1452
+ throw new CliError(`invalid --candidate '${value}' — effort must be one of low, medium, high, xhigh, max`);
1453
+ }
1454
+ return { harness, model, effort };
1455
+ }
1456
+ function parseRegistryModel(value) {
1457
+ const colon = value.lastIndexOf(':');
1458
+ if (colon <= 0) {
1459
+ throw new CliError(`invalid --model '${value}' — expected <model>:<effort,effort…>`);
1460
+ }
1461
+ const model = parseRosterIdentifier(value.slice(0, colon), 'model');
1462
+ const rawEfforts = value.slice(colon + 1);
1463
+ // The service permits an empty effort list. A malformed member (including
1464
+ // `high,`) still fails before hub/credential I/O, matching its `isEffort`.
1465
+ const efforts = rawEfforts === '' ? [] : rawEfforts.split(',');
1466
+ if (efforts.some((effort) => !isRosterEffort(effort))) {
1467
+ throw new CliError(`invalid --model '${value}' — efforts must be drawn from low, medium, high, xhigh, max`);
1468
+ }
1469
+ return { model, efforts };
1470
+ }
1471
+ function nullableId(value, prefix, field) {
1472
+ if (value === null)
1473
+ return null;
1474
+ if (typeof value !== 'string' || value === '')
1475
+ throw new CliError(`${prefix} — ${field} must be a non-empty string or null`);
1476
+ return value;
1477
+ }
1478
+ /** Narrow each mutation response before stdout claims the write succeeded. */
1479
+ function validateRosterMutationSuccess(endpoint, body) {
1480
+ const prefix = `${endpoint}: malformed success response`;
1481
+ const row = recordOf(body);
1482
+ if (row === null)
1483
+ throw new CliError(`${prefix} — not an object`);
1484
+ if (endpoint === 'put_roster') {
1485
+ const crewId = nullableId(row.crewId, prefix, 'crewId');
1486
+ const crewName = nullableId(row.crewName, prefix, 'crewName');
1487
+ if (!isRosterCapability(row.capability))
1488
+ throw new CliError(`${prefix} — missing valid capability`);
1489
+ if (!Array.isArray(row.candidates))
1490
+ throw new CliError(`${prefix} — missing array candidates`);
1491
+ const candidates = row.candidates.map((candidate, index) => {
1492
+ const value = recordOf(candidate);
1493
+ if (value === null)
1494
+ throw new CliError(`${prefix} — candidates[${index}] is not an object`);
1495
+ if (!isRosterIdentifier(value.harness) || !isRosterIdentifier(value.model) || !isRosterEffort(value.effort)) {
1496
+ throw new CliError(`${prefix} — candidates[${index}] has an invalid harness, model, or effort`);
1497
+ }
1498
+ return { harness: value.harness, model: value.model, effort: value.effort };
1499
+ });
1500
+ if (!Array.isArray(row.warnings) || row.warnings.some((warning) => typeof warning !== 'string')) {
1501
+ throw new CliError(`${prefix} — missing array warnings`);
1502
+ }
1503
+ return { crewId, crewName, capability: row.capability, candidates, warnings: row.warnings };
1504
+ }
1505
+ if (endpoint === 'delete_roster_row') {
1506
+ const crewId = nullableId(row.crewId, prefix, 'crewId');
1507
+ if (!isRosterCapability(row.capability))
1508
+ throw new CliError(`${prefix} — missing valid capability`);
1509
+ if (typeof row.removed !== 'boolean')
1510
+ throw new CliError(`${prefix} — missing boolean removed`);
1511
+ return { crewId, capability: row.capability, removed: row.removed };
1512
+ }
1513
+ if (!isRosterIdentifier(row.harness))
1514
+ throw new CliError(`${prefix} — missing valid harness`);
1515
+ if (typeof row.displayName !== 'string' || row.displayName.length > MAX_ROSTER_IDENTIFIER_LENGTH) {
1516
+ throw new CliError(`${prefix} — displayName must be a string of at most ${MAX_ROSTER_IDENTIFIER_LENGTH} characters`);
1517
+ }
1518
+ if (!Array.isArray(row.models))
1519
+ throw new CliError(`${prefix} — missing array models`);
1520
+ const models = row.models.map((model, index) => {
1521
+ const value = recordOf(model);
1522
+ if (value === null)
1523
+ throw new CliError(`${prefix} — models[${index}] is not an object`);
1524
+ if (!isRosterIdentifier(value.model))
1525
+ throw new CliError(`${prefix} — models[${index}] missing valid model`);
1526
+ if (!Array.isArray(value.efforts) || value.efforts.some((effort) => !isRosterEffort(effort))) {
1527
+ throw new CliError(`${prefix} — models[${index}] missing array efforts`);
1528
+ }
1529
+ if (typeof value.updatedAt !== 'number' || !Number.isFinite(value.updatedAt))
1530
+ throw new CliError(`${prefix} — models[${index}] missing finite number updatedAt`);
1531
+ if (typeof value.updatedBy !== 'string' || value.updatedBy === '')
1532
+ throw new CliError(`${prefix} — models[${index}] missing non-empty string updatedBy`);
1533
+ return { model: value.model, efforts: value.efforts, updatedAt: value.updatedAt, updatedBy: value.updatedBy };
1534
+ });
1535
+ return { harness: row.harness, displayName: row.displayName, models };
1536
+ }
1537
+ function validateRosterRows(value, prefix) {
1538
+ const row = recordOf(value);
1539
+ if (row === null)
1540
+ throw new CliError(`${prefix} — roster must be an object`);
1541
+ // Hub capability names may legally collide with Object.prototype (notably
1542
+ // `__proto__`). A normal object assignment would mutate/drop that row.
1543
+ const result = Object.create(null);
1544
+ for (const [capability, candidates] of Object.entries(row)) {
1545
+ if (!isRosterCapability(capability))
1546
+ throw new CliError(`${prefix} — invalid capability ${JSON.stringify(capability)}`);
1547
+ if (!Array.isArray(candidates))
1548
+ throw new CliError(`${prefix} — ${capability} must be an array`);
1549
+ result[capability] = candidates.map((candidate, index) => {
1550
+ const item = recordOf(candidate);
1551
+ if (item === null || !isRosterIdentifier(item.harness) || !isRosterIdentifier(item.model) || !isRosterEffort(item.effort)) {
1552
+ throw new CliError(`${prefix} — ${capability}[${index}] must contain valid harness, model, and effort`);
1553
+ }
1554
+ return { harness: item.harness, model: item.model, effort: item.effort };
1555
+ });
1556
+ }
1557
+ return result;
1558
+ }
1559
+ function validateGetRostersSuccess(body) {
1560
+ const prefix = 'rosters: malformed success response';
1561
+ const row = recordOf(body);
1562
+ if (row === null || !Array.isArray(row.crews))
1563
+ throw new CliError(`${prefix} — expected global object and crews array`);
1564
+ return {
1565
+ global: validateRosterRows(row.global, prefix),
1566
+ crews: row.crews.map((crew, index) => {
1567
+ const item = recordOf(crew);
1568
+ if (item === null || typeof item.crewId !== 'string' || item.crewId === '' || !(isRosterCrewName(item.crewName) || item.crewName === null)) {
1569
+ throw new CliError(`${prefix} — crews[${index}] has an invalid identity`);
1570
+ }
1571
+ return { crewId: item.crewId, crewName: item.crewName, roster: validateRosterRows(item.roster, `${prefix} — crews[${index}].roster`) };
1572
+ }),
1573
+ };
1574
+ }
1575
+ function validateHarnessModelsSuccess(body) {
1576
+ const prefix = 'harness_models: malformed success response';
1577
+ const row = recordOf(body);
1578
+ if (row === null || !Array.isArray(row.harnesses) || !Array.isArray(row.models))
1579
+ throw new CliError(`${prefix} — expected harnesses and models arrays`);
1580
+ return {
1581
+ harnesses: row.harnesses.map((harness, index) => {
1582
+ const item = recordOf(harness);
1583
+ if (item === null || !isRosterIdentifier(item.harness) || typeof item.displayName !== 'string' || item.displayName.length > MAX_ROSTER_IDENTIFIER_LENGTH)
1584
+ throw new CliError(`${prefix} — harnesses[${index}] is invalid`);
1585
+ return { harness: item.harness, displayName: item.displayName };
1586
+ }),
1587
+ models: row.models.map((model, index) => {
1588
+ const item = recordOf(model);
1589
+ 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 === '')
1590
+ throw new CliError(`${prefix} — models[${index}] is invalid`);
1591
+ return { harness: item.harness, model: item.model, efforts: item.efforts, updatedAt: item.updatedAt, updatedBy: item.updatedBy };
1592
+ }),
1593
+ };
1594
+ }
1595
+ /** `roster` uses the same authenticated REST ladders as `routing`; show stays
1596
+ * fully offline so it reports exactly what an agent-run child would route. */
1597
+ async function dispatchRoster(io, args) {
1598
+ const USAGE_FORMS = 'usage: owenloop roster show [crew] | owenloop roster org [--hub <url>] | ' +
1599
+ 'owenloop roster org put <capability> [--crew <name>] --candidate <harness>:<model>:<effort>… [--hub <url>] | ' +
1600
+ 'owenloop roster org rm <capability> [--crew <name>] [--hub <url>] | ' +
1601
+ 'owenloop roster registry [--hub <url>] | owenloop roster registry put <harness> [--display-name <text>] [--model <model>:<effort,effort…>]… [--hub <url>] | ' +
1602
+ 'owenloop roster sync [--hub <url>] [--as agent|agent:<account>]';
1603
+ const sub = args.positionals[1];
1604
+ if (sub !== 'show' && sub !== 'org' && sub !== 'registry' && sub !== 'sync') {
1605
+ throw new CliError(`unknown roster subcommand '${sub ?? ''}' — ${USAGE_FORMS}`);
1606
+ }
1607
+ // `COMMAND_OPTIONS` admits the union of every roster flag. Narrow it again
1608
+ // by command form before even an offline read or credential lookup, so a
1609
+ // typo never looks like a successful command that silently ignored intent.
1610
+ const assertFormOptions = (allowed) => {
1611
+ // `--db` and `--defs` are global CLI options. They are admitted before
1612
+ // dispatch for every command and must remain accepted here too; this
1613
+ // narrower check is only for roster-form-specific flags.
1614
+ const allowedSet = new Set([...GLOBAL_OPTIONS, ...allowed]);
1615
+ const disallowed = [...args.options.keys()].filter((option) => !allowedSet.has(option));
1616
+ if (disallowed.length > 0) {
1617
+ throw new CliError(`${disallowed.map((option) => `--${option}`).join(', ')} ${disallowed.length === 1 ? 'is' : 'are'} not valid for this roster command (${USAGE_FORMS})`);
1618
+ }
1619
+ };
1620
+ if (sub === 'show') {
1621
+ assertFormOptions([]);
1622
+ if (args.positionals.length > 3)
1623
+ throw new CliError(USAGE_FORMS);
1624
+ const crew = args.positionals[2];
1625
+ const settings = loadSettings(io.env);
1626
+ const account = io.env.OWENLOOP_ACCOUNT ?? 'default';
1627
+ const layers = effectiveRosterLayers(io.env, crew, { origin: settings.hubOrigin, account });
1628
+ const merged = mergeRosterLayers(layers);
1629
+ const cache = settings.hubOrigin === undefined ? undefined : readHubRosterCache(io.env, settings.hubOrigin, account);
1630
+ if (Object.keys(merged).length === 0)
1631
+ io.out(crew === undefined ? 'no roster layers found' : `no roster rows found for crew ${crew}`);
1632
+ for (const capability of Object.keys(merged).sort()) {
1633
+ const entry = merged[capability];
1634
+ io.out(`${capability}:`);
1635
+ for (const [index, candidate] of entry.candidates.entries()) {
1636
+ io.out(` [${index}] harness=${candidate.harness} model=${candidate.model} effort=${candidate.effort} from ${entry.source}`);
1637
+ }
1638
+ }
1639
+ io.out('layers inspected:');
1640
+ for (const layer of layers) {
1641
+ const age = layer.source.startsWith('hub ') && cache?.kind === 'hit' ? `; ${rosterAge(cache.data.fetchedAt)}` : '';
1642
+ io.out(` ${layer.source}: ${layer.roster === undefined ? 'absent' : 'found'}${layer.path === undefined ? '' : ` (${layer.path})`}${age}`);
1643
+ }
1644
+ const shadows = explainRosterShadows(layers);
1645
+ const shadowed = Object.entries(shadows).filter(([, detail]) => detail.shadowed.length > 0).sort(([a], [b]) => a.localeCompare(b));
1646
+ if (shadowed.length > 0) {
1647
+ io.out('shadowed:');
1648
+ for (const [capability, detail] of shadowed) {
1649
+ io.out(` ${capability}: ${detail.winner} wins; ${detail.shadowed.map((row) => `${row.source} (${row.candidateCount} candidate${row.candidateCount === 1 ? '' : 's'})`).join(', ')} shadowed`);
1650
+ }
1651
+ }
1652
+ return 0;
1653
+ }
1654
+ let orgSub;
1655
+ let registrySub;
1656
+ let capability = '';
1657
+ let harness = '';
1658
+ if (sub === 'org') {
1659
+ const nested = args.positionals[2];
1660
+ if (nested === undefined)
1661
+ orgSub = 'get';
1662
+ else if (nested === 'put' || nested === 'rm')
1663
+ orgSub = nested;
1664
+ else
1665
+ throw new CliError(`unknown roster org subcommand '${nested}' — ${USAGE_FORMS}`);
1666
+ if (orgSub === 'put' || orgSub === 'rm') {
1667
+ capability = parseRosterCapability(args.positionals[3] ?? '');
1668
+ }
1669
+ const maxPositionals = orgSub === 'get' ? 2 : 4;
1670
+ if (args.positionals.length > maxPositionals)
1671
+ throw new CliError(USAGE_FORMS);
1672
+ assertFormOptions(orgSub === 'get' ? ['hub'] : orgSub === 'put' ? ['hub', 'crew', 'candidate'] : ['hub', 'crew']);
1673
+ if (orgSub === 'put' && all(args, 'candidate').length === 0)
1674
+ throw new CliError(`missing required --candidate (${USAGE_FORMS})`);
1675
+ }
1676
+ else if (sub === 'registry') {
1677
+ const nested = args.positionals[2];
1678
+ if (nested === undefined)
1679
+ registrySub = 'get';
1680
+ else if (nested === 'put')
1681
+ registrySub = 'put';
1682
+ else
1683
+ throw new CliError(`unknown roster registry subcommand '${nested}' — ${USAGE_FORMS}`);
1684
+ if (registrySub === 'put')
1685
+ harness = parseRosterIdentifier(args.positionals[3] ?? '', 'harness');
1686
+ const maxPositionals = registrySub === 'get' ? 2 : 4;
1687
+ if (args.positionals.length > maxPositionals)
1688
+ throw new CliError(USAGE_FORMS);
1689
+ assertFormOptions(registrySub === 'get' ? ['hub'] : ['hub', 'display-name', 'model']);
1690
+ }
1691
+ else if (args.positionals.length > 2) {
1692
+ throw new CliError(USAGE_FORMS);
1693
+ }
1694
+ else {
1695
+ assertFormOptions(['hub', 'as']);
1696
+ }
1697
+ const crewOption = last(args, 'crew');
1698
+ if (crewOption !== undefined && (args.missingOptionValues.has('crew') || crewOption.trim() === '')) {
1699
+ throw new CliError(`--crew requires a non-empty crew name (${USAGE_FORMS})`);
1700
+ }
1701
+ if (crewOption !== undefined && !isRosterCrewName(crewOption)) {
1702
+ throw new CliError('--crew must be a trimmed, non-empty crew name of at most 64 characters');
1703
+ }
1704
+ // Finish every command-local parse before resolving a hub or consulting the
1705
+ // credential backend. An invalid payload is a usage error, not a reason to
1706
+ // run an external credential helper or mask it as a missing credential.
1707
+ let parsedCandidates;
1708
+ let parsedModels;
1709
+ let parsedDisplayName;
1710
+ if (sub === 'org' && orgSub === 'put') {
1711
+ const rawCandidates = all(args, 'candidate');
1712
+ if (rawCandidates.length > MAX_ROSTER_CANDIDATES) {
1713
+ throw new CliError(`--candidate may be supplied at most ${MAX_ROSTER_CANDIDATES} times`);
1714
+ }
1715
+ parsedCandidates = rawCandidates.map(parseRosterCandidate);
1716
+ const candidateKeys = new Set();
1717
+ for (const candidate of parsedCandidates) {
1718
+ const key = JSON.stringify([candidate.harness, candidate.model, candidate.effort]);
1719
+ if (candidateKeys.has(key))
1720
+ throw new CliError('duplicate --candidate harness, model, and effort triple');
1721
+ candidateKeys.add(key);
1722
+ }
1723
+ }
1724
+ if (sub === 'registry' && registrySub === 'put') {
1725
+ const displayNames = all(args, 'display-name');
1726
+ if (displayNames.length > 1)
1727
+ throw new CliError('--display-name may be supplied at most once');
1728
+ if (displayNames.length > 0 && args.missingOptionValues.has('display-name')) {
1729
+ throw new CliError('--display-name requires a value');
1730
+ }
1731
+ if (displayNames.length === 1)
1732
+ parsedDisplayName = parseRosterDisplayName(displayNames[0]);
1733
+ const rawModels = all(args, 'model');
1734
+ if (rawModels.length > MAX_HARNESS_MODELS)
1735
+ throw new CliError(`--model may be supplied at most ${MAX_HARNESS_MODELS} times`);
1736
+ // A zero-model full snapshot is a supported way to clear the advisory
1737
+ // registry. An empty display label is likewise a deliberate service value.
1738
+ parsedModels = rawModels.map(parseRegistryModel);
1739
+ const modelNames = new Set();
1740
+ for (const model of parsedModels) {
1741
+ if (modelNames.has(model.model))
1742
+ throw new CliError(`duplicate --model '${model.model}'`);
1743
+ modelNames.add(model.model);
1744
+ }
1745
+ }
1746
+ // `roster sync` is an agent-owned cache refresh. Unlike the other roster
1747
+ // verbs, its omitted `--as` deliberately means the default agent slot.
1748
+ const slot = sub === 'sync'
1749
+ ? (!args.options.has('as') ? { principal: 'agent' } : resolveSlot(args))
1750
+ : { principal: 'human' };
1751
+ if (sub === 'sync' && slot.principal !== 'agent') {
1752
+ throw new CliError(`roster sync requires an agent credential — pass --as agent or --as agent:<account> (${USAGE_FORMS})`);
1753
+ }
1754
+ const origin = resolveAgentHub(io, args, sub === 'sync' ? 'sync rosters from' : 'manage rosters on');
1755
+ const cred = readCredential(io, origin, slot);
1756
+ if (cred === null)
1757
+ throw new CliError(emptySlotMessage(origin, slot), { exitCode: 3 });
1758
+ const getJson = async (path, prefix) => {
1759
+ const { res, cred: used } = await authedGet(io, origin, slot, cred, path);
1760
+ if (res.status === 401) {
1761
+ throw new CliError(used.kind === 'agent'
1762
+ ? 'token revoked or invalid — re-mint it in the console or run `owenloop login`'
1763
+ : 'credential rejected by the hub — run `owenloop login`', { exitCode: 3 });
1764
+ }
1765
+ if (!res.ok)
1766
+ throw new CliError((await hubRequestMessage(res)) ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
1767
+ try {
1768
+ return await res.json();
1769
+ }
1770
+ catch {
1771
+ throw new CliError(`${prefix}: malformed response — body is not valid JSON`);
1772
+ }
1773
+ };
1774
+ if (sub === 'sync') {
1775
+ const account = slot.principal === 'agent' ? slot.account ?? 'default' : 'default';
1776
+ // Use the same sync helper as shift start and periodic refresh. The local
1777
+ // adapter preserves the CLI's credential-refresh/error ladder rather than
1778
+ // bypassing it with a second raw-fetch implementation.
1779
+ const cacheClient = {
1780
+ whoami: async () => getJson('/api/whoami', 'whoami'),
1781
+ getRosters: async () => getJson('/api/rosters', 'rosters'),
1782
+ };
1783
+ await syncHubRosterCache({
1784
+ client: cacheClient,
1785
+ env: io.env,
1786
+ origin,
1787
+ account,
1788
+ });
1789
+ const cache = readHubRosterCache(io.env, origin, account);
1790
+ if (cache.kind !== 'hit')
1791
+ throw new CliError(`roster sync wrote no readable cache: ${cache.reason}`);
1792
+ print(io, { ok: true, hub: origin, cachePath: cache.path, fetchedAt: cache.data.fetchedAt });
1793
+ return 0;
1794
+ }
1795
+ if (sub === 'org' && orgSub === 'get') {
1796
+ print(io, { ok: true, hub: origin, rosters: validateGetRostersSuccess(await getJson('/api/rosters', 'rosters')) });
1797
+ return 0;
1798
+ }
1799
+ if (sub === 'registry' && registrySub === 'get') {
1800
+ print(io, { ok: true, hub: origin, registry: validateHarnessModelsSuccess(await getJson('/api/harness_models', 'harness_models')) });
1801
+ return 0;
1802
+ }
1803
+ let endpoint;
1804
+ let payload;
1805
+ if (sub === 'org' && orgSub === 'put') {
1806
+ endpoint = 'put_roster';
1807
+ payload = { capability, candidates: parsedCandidates, ...(crewOption === undefined ? {} : { crew: crewOption }) };
1808
+ }
1809
+ else if (sub === 'org') {
1810
+ endpoint = 'delete_roster_row';
1811
+ payload = { capability, ...(crewOption === undefined ? {} : { crew: crewOption }) };
1812
+ }
1813
+ else {
1814
+ endpoint = 'put_harness_models';
1815
+ payload = { harness, models: parsedModels, ...(parsedDisplayName === undefined ? {} : { displayName: parsedDisplayName }) };
1816
+ }
1817
+ const { res } = await authedPost(io, origin, slot, cred, `/api/${endpoint}`, payload);
1818
+ if (res.status === 401)
1819
+ throw new CliError('credential rejected by the hub — run `owenloop login`', { exitCode: 3 });
1820
+ if (!res.ok)
1821
+ throw new CliError((await hubRequestMessage(res)) ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
1822
+ let body;
1823
+ try {
1824
+ body = await res.json();
1825
+ }
1826
+ catch {
1827
+ throw new CliError(`${endpoint}: malformed success response — body is not valid JSON`);
1828
+ }
1829
+ const result = validateRosterMutationSuccess(endpoint, body);
1830
+ print(io, { ok: true, hub: origin, result });
1831
+ return 0;
1832
+ }
1337
1833
  function dispatch(command, io, args) {
1338
1834
  // help and lint need no store
1339
1835
  if (command === 'help' || command === '--help' || command === '-h') {
@@ -1847,8 +2343,9 @@ function dispatch(command, io, args) {
1847
2343
  const path = need(args, 2, 'path');
1848
2344
  const by = needOpt(args, 'by');
1849
2345
  const text = needOpt(args, 'text');
1850
- const rejectRes = engine.reject(wf, path, by, text);
1851
- print(io, { ok: true, action: 'reject', path, outcome: rejectRes.outcome });
2346
+ const requested = last(args, 'requested');
2347
+ const rejectRes = engine.reject(wf, path, by, text, requested);
2348
+ print(io, { ok: true, action: 'reject', path, outcome: rejectRes.outcome, ...(requested !== undefined ? { requested } : {}) });
1852
2349
  // §24.4/§4.6: a judge's reject can itself be born-rejected by the CAS
1853
2350
  // guard (stale verdict against a submission that already moved on) —
1854
2351
  // mirror the 'green' handler above: that is a failure, not a success,
@@ -4024,6 +4521,14 @@ async function dispatchStart(io, args) {
4024
4521
  // than a silent unmodified run. Omitting the flag entirely IS the unmodified
4025
4522
  // run — that is the difference `requiredTextOption` preserves.
4026
4523
  const modifier = requiredTextOption('modifier', 'name');
4524
+ // Free routing label. No registry and no enumeration by design (§4.8), so the
4525
+ // only shape check is the one every text option gets: present-but-valueless and
4526
+ // explicitly-empty are usage errors; omitted is omitted.
4527
+ const scope = requiredTextOption('scope', 'label');
4528
+ const priority = requiredTextOption('priority', 'low|normal|high');
4529
+ if (priority !== undefined && !START_PRIORITIES.has(priority)) {
4530
+ throw new CliError(`invalid --priority '${priority}' — must be one of low, normal, high`);
4531
+ }
4027
4532
  const origin = resolveStartHub(io, args);
4028
4533
  const slot = { principal: 'human' };
4029
4534
  const cred = readCredential(io, origin, slot);
@@ -4040,6 +4545,8 @@ async function dispatchStart(io, args) {
4040
4545
  // absent as the same thing, but sending an explicit `undefined` would put a
4041
4546
  // `modifier` key in the JSON body with a null value. Omitted means omitted.
4042
4547
  ...(modifier !== undefined ? { modifier } : {}),
4548
+ ...(scope !== undefined ? { scope } : {}),
4549
+ ...(priority !== undefined ? { priority } : {}),
4043
4550
  };
4044
4551
  const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/start_run', request);
4045
4552
  if (res.status === 401)
@@ -4081,6 +4588,11 @@ async function dispatchStart(io, args) {
4081
4588
  // accepted exactly this value. Printed only when the flag was passed, so an
4082
4589
  // unmodified run's output is byte-identical to what it was before.
4083
4590
  ...(modifier !== undefined ? { modifier } : {}),
4591
+ // Echoed from the request, like `modifier` above, and only when the flag
4592
+ // was passed. A run started without these flags prints exactly what it did
4593
+ // before, while a hub refusal prevents this success output entirely.
4594
+ ...(scope !== undefined ? { scope } : {}),
4595
+ ...(priority !== undefined ? { priority } : {}),
4084
4596
  ...(Array.isArray(wire.stampedCrews) ? { stampedCrews: wire.stampedCrews } : {}),
4085
4597
  ...(Array.isArray(wire.validatedCrews) ? { validatedCrews: wire.validatedCrews } : {}),
4086
4598
  });
@@ -4168,6 +4680,44 @@ async function dispatchCancel(io, args) {
4168
4680
  });
4169
4681
  return 0;
4170
4682
  }
4683
+ /**
4684
+ * `owenloop retry --hub` — the human stall-clear / answer path for a hub-hosted
4685
+ * run. Local retry remains synchronous in `main()`; this dispatch owns only
4686
+ * the network half so direct synchronous callers keep their existing contract.
4687
+ */
4688
+ async function dispatchRetry(io, args) {
4689
+ const workflow = need(args, 1, 'workflow');
4690
+ const path = need(args, 2, 'path');
4691
+ if (args.options.has('by')) {
4692
+ throw new CliError('owenloop retry: --by cannot be combined with --hub — the hub attributes the retry to the authenticated human principal');
4693
+ }
4694
+ if (args.missingOptionValues.has('text')) {
4695
+ throw new CliError('missing value for --text: expected --text <guidance>');
4696
+ }
4697
+ const text = last(args, 'text');
4698
+ if (text !== undefined && text.trim() === '') {
4699
+ throw new CliError('invalid empty value for --text: expected --text <guidance>');
4700
+ }
4701
+ const origin = resolveStartHub(io, args);
4702
+ const slot = { principal: 'human' };
4703
+ const cred = readCredential(io, origin, slot);
4704
+ if (cred === null) {
4705
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
4706
+ }
4707
+ const request = { workflow, path, ...(text !== undefined ? { text } : {}) };
4708
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/retry_artifact', request);
4709
+ if (res.status === 401)
4710
+ assertAuthOk(res, used, origin);
4711
+ if (!res.ok) {
4712
+ const message = await hubRequestMessage(res);
4713
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
4714
+ }
4715
+ // The hub owns the response body contract. Any successful response has
4716
+ // completed the state transition, so expose a stable CLI receipt instead of
4717
+ // assuming fields the server has not promised this client.
4718
+ print(io, { ok: true, action: 'retry', path, workflow, hub: origin });
4719
+ return 0;
4720
+ }
4171
4721
  /**
4172
4722
  * `owenloop instance` — read a HUB instance's live state from the terminal.
4173
4723
  *
@@ -4245,10 +4795,22 @@ async function dispatchInstance(io, args) {
4245
4795
  throw new CliError('get_status: malformed success response — missing done flag');
4246
4796
  }
4247
4797
  const arrayOr = (value) => (Array.isArray(value) ? value : []);
4798
+ // The hub's terminal INSTANCE STATUS verdict is optional on the wire: older
4799
+ // hubs predate these fields. Absent means absent — neither value is defaulted,
4800
+ // because `terminal: false` and `instanceStatus: 'unknown'` are real answers.
4801
+ // The status vocabulary belongs to the hub, so a future non-empty string is
4802
+ // forwarded verbatim instead of being rejected by a CLI-owned enum.
4803
+ const instanceStatus = typeof wire.instanceStatus === 'string' && wire.instanceStatus !== '' ? wire.instanceStatus : undefined;
4804
+ const terminal = typeof wire.terminal === 'boolean' ? wire.terminal : undefined;
4248
4805
  print(io, {
4249
4806
  ok: true,
4250
4807
  hub: origin,
4251
4808
  workflow,
4809
+ // These answer whether the instance is alive; `done` is the engine's
4810
+ // completion flag, and failed or cancelled instances are terminal without
4811
+ // being done.
4812
+ ...(instanceStatus === undefined ? {} : { instanceStatus }),
4813
+ ...(terminal === undefined ? {} : { terminal }),
4252
4814
  done: wire.done,
4253
4815
  // Owed inputs the instance is waiting on, each with its acceptance and
4254
4816
  // whether the engine considers it stalled.
@@ -4267,6 +4829,14 @@ async function dispatchInstance(io, args) {
4267
4829
  // looks identical to "nothing is picking this up" from the outside.
4268
4830
  ...(Array.isArray(wire.waitingOnCapabilities) ? { waitingOnCapabilities: wire.waitingOnCapabilities } : {}),
4269
4831
  });
4832
+ // The hub owns this mapping; do not derive terminality from its status label.
4833
+ // stderr preserves the JSON stdout contract while still reaching an operator
4834
+ // who is piping it to another command.
4835
+ if (terminal === true) {
4836
+ const terminalMessage = `instance ${workflow} is ${instanceStatus ?? 'in a terminal state'} — TERMINAL. ` +
4837
+ 'The hub will dispatch nothing further for it; an empty `eligible` here is a finished run, not an idle shift.';
4838
+ io.err(terminalMessage);
4839
+ }
4270
4840
  return 0;
4271
4841
  }
4272
4842
  /**
@@ -4738,6 +5308,357 @@ async function dispatchCapability(io, args) {
4738
5308
  throw e;
4739
5309
  }
4740
5310
  }
5311
+ /**
5312
+ * `owenloop routing alerts|show|rule list|rule add|rule rm` — read the hub's LIVE
5313
+ * routing state, and administer the org's **capability reroute rules**.
5314
+ *
5315
+ * | subcommand | endpoint | auth principal |
5316
+ * |---|---|---|
5317
+ * | `routing alerts [--workflow <wf>] [--limit <n>]` | `GET /api/routing_alerts` | human (any role) |
5318
+ * | `routing show <workflow>` | `GET /api/run_routing/:wf` | human (any role) |
5319
+ * | `routing rule list` | `GET /api/capability_reroutes` | human (any role) |
5320
+ * | `routing rule add <capability> <target> [--position <n>]` | `POST /api/add_capability_reroute` | human (admin role) |
5321
+ * | `routing rule rm <capability> <target>` | `POST /api/remove_capability_reroute` | human (admin role) |
5322
+ *
5323
+ * **Three different objects share the word "routing" in this CLI. They are not
5324
+ * interchangeable, and only one of them grants anybody work:**
5325
+ *
5326
+ * - A **capability route** (`owenloop capability bind`) is a `(capability, crew)`
5327
+ * BINDING. It is the only one of the three that makes a crew eligible to claim
5328
+ * work.
5329
+ * - A **capability reroute rule** (`owenloop routing rule add`) is an ordered
5330
+ * SUBSTITUTION — "when `<capability>` has no live crew binding, offer the work
5331
+ * as `<target>` instead". It names no crew and grants nobody access; whether
5332
+ * the target can actually be served is a `capability bind` question.
5333
+ * - A **routing alert** (`owenloop routing alerts`) is an immutable EVENT row the
5334
+ * hub wrote about one offer at one instant. `kind: 'binding-gap'` is the one to
5335
+ * watch: a step's compound capability (e.g. `build:express`) had no live crew
5336
+ * binding, so the hub HELD the offer rather than silently falling back to
5337
+ * name matching. Holding is the intended behavior; the alert is how a human
5338
+ * finds out it happened.
5339
+ *
5340
+ * **`routing show <workflow>` is NOT the local `show` command.** `owenloop show`
5341
+ * reads a workflow DEFINITION out of the local sqlite store and takes no `--hub`;
5342
+ * `routing show` reads one STARTED RUN's routing state off the hub. They share no
5343
+ * code path, and this deliberately did not arrive as a `--hub` flag on the local
5344
+ * command — the same separation `instance show` keeps.
5345
+ *
5346
+ * **Two orderings are SEMANTIC and are never re-sorted client-side.** `routing
5347
+ * alerts` unscoped returns the org's alerts NEWEST-FIRST (an inbox); adding
5348
+ * `--workflow` scopes to one run AND flips to OLDEST-FIRST (a timeline). `routing
5349
+ * rule list` returns rules in the order the hub TRIES them. Sorting any of these
5350
+ * for looks would misreport what the hub actually does.
5351
+ *
5352
+ * **`rule add` can fail where `rule rm` cannot** — the deliberate asymmetry
5353
+ * `capability bind`/`unbind` already has. `rule add` is idempotent per
5354
+ * `(capability, target)` pair (a repeat is a 200 no-op reporting
5355
+ * `alreadyPresent: true`), but the hub rejects a rule it considers invalid — a
5356
+ * capability rerouted to itself, a malformed name — with a 400 whose `message` is
5357
+ * surfaced verbatim, exit 1. `rule rm` answers a tolerant 200 `removed: false`
5358
+ * when there was no such rule, which is exit 0 plus a stderr line. None of the
5359
+ * hub's name rules are re-implemented here: the hub is the enforcement of record,
5360
+ * the same stance the capability family takes.
5361
+ *
5362
+ * `routing show` on a workflow id this org does not own does NOT come back with a
5363
+ * descriptive message: the hub verb throws an untyped error that its edge maps to
5364
+ * HTTP 500 `{"error":"internal_error","message":"internal server error"}`, and
5365
+ * that generic message is what this command prints (exit 1) — the same thing
5366
+ * `instance show` does with the same hub behavior. The ladder below surfaces
5367
+ * whatever `message` the hub sends, so a future typed 404 needs no change here.
5368
+ *
5369
+ * Exit codes: 0 ok — including `rule rm`'s tolerant `removed: false`; 1
5370
+ * runtime/hub error (a 400 on `rule add`, a 403 for a non-admin on `rule
5371
+ * add`/`rule rm`, an unknown workflow on `show`, a malformed 2xx, a network
5372
+ * timeout); 2 the hub is unresolvable; 3 the human credential is absent or
5373
+ * irrecoverable (the error names `owenloop login --hub <origin>`).
5374
+ */
5375
+ async function dispatchRouting(io, args) {
5376
+ const USAGE_FORMS = 'usage: owenloop routing alerts [--workflow <wf>] [--limit <n>] [--hub <url>]' +
5377
+ ' | owenloop routing show <workflow> [--hub <url>]' +
5378
+ ' | owenloop routing rule list [--hub <url>]' +
5379
+ ' | owenloop routing rule add <capability> <target> [--position <n>] [--hub <url>]' +
5380
+ ' | owenloop routing rule rm <capability> <target> [--hub <url>]';
5381
+ // --- validation: everything below runs BEFORE any I/O, so a usage error on a
5382
+ // multi-hub machine reports the usage problem (exit 1), not exit 2.
5383
+ const sub = args.positionals[1];
5384
+ if (sub !== 'alerts' && sub !== 'show' && sub !== 'rule') {
5385
+ throw new CliError(`unknown routing subcommand '${sub ?? ''}' — ${USAGE_FORMS}`);
5386
+ }
5387
+ let workflow = ''; // `show` only
5388
+ let ruleSub = ''; // `rule` only
5389
+ let capability = ''; // `rule add` / `rule rm`
5390
+ let target = ''; // `rule add` / `rule rm`
5391
+ let workflowFilter; // `alerts` only
5392
+ let limit; // `alerts` only
5393
+ let position; // `rule add` only
5394
+ if (sub === 'show') {
5395
+ const rawWorkflow = args.positionals[2];
5396
+ if (rawWorkflow === undefined || rawWorkflow === '') {
5397
+ throw new CliError(`missing required argument: <workflow> (${USAGE_FORMS})`);
5398
+ }
5399
+ workflow = rawWorkflow;
5400
+ }
5401
+ else if (sub === 'alerts') {
5402
+ // `--workflow` with no value, or with an empty one, is a usage error rather
5403
+ // than a silent org-wide listing. The hub treats `workflow=` as absent, so
5404
+ // accepting an empty value would print `"workflow": ""` over an UNSCOPED
5405
+ // result set — stdout claiming a filter that was never applied. OMITTING the
5406
+ // flag entirely is the org-wide listing; that difference is preserved.
5407
+ // (`dispatchStart`'s `requiredTextOption` makes the same distinction.)
5408
+ if (args.missingOptionValues.has('workflow')) {
5409
+ throw new CliError('missing value for --workflow: expected --workflow <wf>');
5410
+ }
5411
+ const rawFilter = last(args, 'workflow');
5412
+ if (rawFilter !== undefined && rawFilter.trim() === '') {
5413
+ throw new CliError('invalid empty value for --workflow: expected --workflow <wf>');
5414
+ }
5415
+ workflowFilter = rawFilter;
5416
+ // `numOpt` throws a CliError on a non-numeric value — including a bare
5417
+ // `--limit`, which the parser records as the string 'true'. This is flag
5418
+ // hygiene, not a copy of hub semantics: the hub silently DROPS a
5419
+ // non-positive-integer `limit` and applies its own default, which would
5420
+ // report a page size the operator never asked for.
5421
+ limit = numOpt(args, 'limit');
5422
+ }
5423
+ else {
5424
+ // Two-level subcommand, the `crew member add|rm` shape.
5425
+ const rawRuleSub = args.positionals[2];
5426
+ if (rawRuleSub !== 'list' && rawRuleSub !== 'add' && rawRuleSub !== 'rm') {
5427
+ throw new CliError(`unknown routing rule subcommand '${rawRuleSub ?? ''}' — ${USAGE_FORMS}`);
5428
+ }
5429
+ ruleSub = rawRuleSub;
5430
+ if (ruleSub === 'add' || ruleSub === 'rm') {
5431
+ // Both are required for BOTH verbs: one call writes or clears exactly ONE
5432
+ // `(capability, target)` rule, and a capability-only `rm` would drop every
5433
+ // substitution the operator ever wrote for that source.
5434
+ const rawCapability = args.positionals[3];
5435
+ if (rawCapability === undefined || rawCapability === '') {
5436
+ throw new CliError(`missing required argument: <capability> (${USAGE_FORMS})`);
5437
+ }
5438
+ capability = rawCapability;
5439
+ const rawTarget = args.positionals[4];
5440
+ if (rawTarget === undefined || rawTarget === '') {
5441
+ throw new CliError(`missing required argument: <target> (${USAGE_FORMS})`);
5442
+ }
5443
+ target = rawTarget;
5444
+ // Omitting `--position` APPENDS the rule; a non-numeric value is a
5445
+ // client-side CliError for the same reason `--limit` is.
5446
+ if (ruleSub === 'add')
5447
+ position = numOpt(args, 'position');
5448
+ }
5449
+ // No client-side charset validation of `capability` or `target` — the hub is
5450
+ // the enforcement of record, the same stance `capability bind` takes.
5451
+ }
5452
+ const origin = resolveAgentHub(io, args, 'manage routing on');
5453
+ const slot = { principal: 'human' };
5454
+ // The human bearer for the resolved origin. Absent → exit 3 with the same
5455
+ // remedy wording `capability` uses.
5456
+ const cred = readCredential(io, origin, slot);
5457
+ if (cred === null) {
5458
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5459
+ }
5460
+ try {
5461
+ /**
5462
+ * The ONE GET ladder all three reads share, so they can never drift apart in
5463
+ * what they accept. It is `dispatchInstance`'s ladder — a 401 through
5464
+ * `assertAuthOk`, then the hub's typed `message` surfaced VERBATIM for any
5465
+ * other non-2xx — deliberately NOT `capability list`'s bare `assertAuthOk`,
5466
+ * whose own comment freezes that generic wording to that command. `prefix` is
5467
+ * the endpoint-qualified lead-in the narrower for this endpoint also uses, so
5468
+ * a non-JSON body reports a FIXED string rather than V8's `SyntaxError`,
5469
+ * which embeds a verbatim snippet of the raw body.
5470
+ */
5471
+ const readJson = async (path, prefix) => {
5472
+ const { res, cred: used } = await authedGet(io, origin, slot, cred, path);
5473
+ if (res.status === 401)
5474
+ assertAuthOk(res, used, origin);
5475
+ if (!res.ok) {
5476
+ const message = await hubRequestMessage(res);
5477
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5478
+ }
5479
+ try {
5480
+ return (await res.json());
5481
+ }
5482
+ catch {
5483
+ throw new CliError(`${prefix} — body is not valid JSON`);
5484
+ }
5485
+ };
5486
+ if (sub === 'alerts') {
5487
+ // Both query params are optional and are sent ONLY when the operator asked
5488
+ // for them, so the default request carries no `?` at all and the hub
5489
+ // applies its own page size.
5490
+ const qs = new URLSearchParams();
5491
+ if (workflowFilter !== undefined)
5492
+ qs.set('workflow', workflowFilter);
5493
+ if (limit !== undefined)
5494
+ qs.set('limit', String(limit));
5495
+ const query = qs.toString();
5496
+ const body = await readJson(`/api/routing_alerts${query === '' ? '' : `?${query}`}`, 'routing_alerts: malformed response');
5497
+ let alerts;
5498
+ try {
5499
+ alerts = asRoutingAlerts(body);
5500
+ }
5501
+ catch (e) {
5502
+ throw new CliError(e.message);
5503
+ }
5504
+ // The guard's output — a whitelisted typed array — never the raw body, and
5505
+ // in RECEIVED order (see the ordering paragraph above). The `workflow` key
5506
+ // is echoed back only when a filter was applied, so a script can tell an
5507
+ // oldest-first timeline from a newest-first inbox without re-reading argv.
5508
+ print(io, {
5509
+ ok: true,
5510
+ hub: origin,
5511
+ ...(workflowFilter === undefined ? {} : { workflow: workflowFilter }),
5512
+ alerts,
5513
+ });
5514
+ return 0;
5515
+ }
5516
+ if (sub === 'show') {
5517
+ // The workflow id is a path segment, so it must be encoded — an id carrying
5518
+ // a slash would otherwise silently address a different route
5519
+ // (`dispatchInstance`'s precedent).
5520
+ const body = await readJson(`/api/run_routing/${encodeURIComponent(workflow)}`, 'run_routing: malformed success response');
5521
+ let wire;
5522
+ try {
5523
+ wire = asRunRouting(body);
5524
+ }
5525
+ catch (e) {
5526
+ throw new CliError(e.message);
5527
+ }
5528
+ print(io, {
5529
+ ok: true,
5530
+ hub: origin,
5531
+ // The SERVER-echoed id, not argv — the `capability bind` precedent.
5532
+ workflow: wire.workflow,
5533
+ defName: wire.defName,
5534
+ // OMITTED, never `null` or `''`: the absence of this key is how stdout
5535
+ // says "this run was started without a modifier". An empty string would
5536
+ // read as "a modifier named nothing", which is not a state that exists.
5537
+ ...(wire.modifier === undefined ? {} : { modifier: wire.modifier }),
5538
+ waitPolicy: wire.waitPolicy,
5539
+ alerts: wire.alerts,
5540
+ resolutionReports: wire.resolutionReports,
5541
+ escalations: wire.escalations,
5542
+ });
5543
+ return 0;
5544
+ }
5545
+ if (ruleSub === 'list') {
5546
+ const body = await readJson('/api/capability_reroutes', 'capability_reroutes: malformed response');
5547
+ let reroutes;
5548
+ try {
5549
+ reroutes = asCapabilityReroutes(body);
5550
+ }
5551
+ catch (e) {
5552
+ throw new CliError(e.message);
5553
+ }
5554
+ // Printed in the hub's own try-order and never re-sorted: the array order
5555
+ // IS which substitution the hub attempts first. Each row also carries its
5556
+ // `position`, so a reader can check that ordering for themselves.
5557
+ print(io, { ok: true, hub: origin, reroutes });
5558
+ return 0;
5559
+ }
5560
+ // `rule add` and `rule rm` share one POST ladder. The bodies differ by exactly
5561
+ // one optional field — `position`, add-only — because each call writes or
5562
+ // clears exactly one `(capability, target)` rule. Only the path, the guard,
5563
+ // and the printed shape differ.
5564
+ const endpoint = ruleSub === 'add' ? 'add_capability_reroute' : 'remove_capability_reroute';
5565
+ // The `position` KEY is omitted entirely when the flag is absent — that is
5566
+ // what tells the hub to APPEND. Sending `null` or `0` would each mean
5567
+ // something else.
5568
+ const payload = ruleSub === 'add' && position !== undefined ? { capability, target, position } : { capability, target };
5569
+ const { res } = await authedPost(io, origin, slot, cred, `/api/${endpoint}`, payload);
5570
+ if (res.status === 401) {
5571
+ // A 401 that survived `authedPost`'s one refresh-and-retry. The human slot
5572
+ // never holds an agent kind, so `assertAuthOk`'s non-agent wording applies;
5573
+ // the catch below upgrades this to exit 3.
5574
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
5575
+ }
5576
+ if (!res.ok) {
5577
+ // Surface the hub's typed `message` VERBATIM — this is how a rule the hub
5578
+ // refuses (400 `capability_reroute_invalid`) and a non-admin 403 both
5579
+ // surface uniformly. `hubRequestMessage` reads only the typed `message`
5580
+ // field, so raw body text is never included.
5581
+ const message = await hubRequestMessage(res);
5582
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5583
+ }
5584
+ let body;
5585
+ try {
5586
+ body = (await res.json());
5587
+ }
5588
+ catch {
5589
+ // A FIXED string — never V8's SyntaxError message, which embeds a verbatim
5590
+ // snippet of the raw body.
5591
+ throw new CliError(`${endpoint}: malformed success response — body is not valid JSON`);
5592
+ }
5593
+ if (ruleSub === 'add') {
5594
+ let added;
5595
+ try {
5596
+ added = asCapabilityRerouteAdded(body);
5597
+ }
5598
+ catch (e) {
5599
+ throw new CliError(e.message);
5600
+ }
5601
+ // SERVER-echoed capability/target/position, not argv. `position` especially:
5602
+ // omitting `--position` appends, so the rank printed here is usually one the
5603
+ // operator never typed. `alreadyPresent` and `ruleCount` carry the HUB's own
5604
+ // field names verbatim, so an operator correlating stdout against the hub's
5605
+ // audit log never has to translate. `createdAt` is validated but not printed
5606
+ // — `routing rule list` is where a row's provenance belongs (the
5607
+ // `capability bind` precedent).
5608
+ print(io, {
5609
+ ok: true,
5610
+ hub: origin,
5611
+ capability: added.reroute.capability,
5612
+ target: added.reroute.target,
5613
+ position: added.reroute.position,
5614
+ alreadyPresent: added.alreadyPresent,
5615
+ ruleCount: added.ruleCount,
5616
+ });
5617
+ // No stderr line on `add`: the write is idempotent per pair, so
5618
+ // `alreadyPresent: true` is a normal no-op, and an add never removes a rule
5619
+ // or parks a capability. There is no consequence to warn about.
5620
+ return 0;
5621
+ }
5622
+ // `rule rm`: the guard proves the 2xx really was the remove verb's answer.
5623
+ // `removedWire` (not `removed`) so `removedWire.removed` reads unambiguously —
5624
+ // the naming `dispatchCapability` and `dispatchCrew` already use.
5625
+ let removedWire;
5626
+ try {
5627
+ removedWire = asCapabilityRerouteRemoved(body);
5628
+ }
5629
+ catch (e) {
5630
+ throw new CliError(e.message);
5631
+ }
5632
+ print(io, {
5633
+ ok: true,
5634
+ hub: origin,
5635
+ capability: removedWire.capability,
5636
+ target: removedWire.target,
5637
+ removed: removedWire.removed,
5638
+ remainingTargets: removedWire.remainingTargets,
5639
+ });
5640
+ // stderr only, so `| jq` on stdout is unaffected — mirroring `capability
5641
+ // unbind`, which narrates its tolerant-false case and its notable side effect
5642
+ // the same way.
5643
+ if (!removedWire.removed) {
5644
+ io.err(`${removedWire.capability} had no reroute to '${removedWire.target}' — nothing was removed`);
5645
+ }
5646
+ else if (removedWire.remainingTargets.length === 0) {
5647
+ io.err(`${removedWire.capability}: no reroute rules remain — it now HOLDS whenever it has no live crew binding`);
5648
+ }
5649
+ return 0;
5650
+ }
5651
+ catch (e) {
5652
+ // A refresh-failure-family error (the human oauth is irrecoverable, or a 401
5653
+ // survived the refresh-and-retry) is exit 3 with the login remedy; every
5654
+ // other CliError propagates as-is — a network timeout stays exit 1, because a
5655
+ // flaky network is not an irrecoverable credential.
5656
+ if (e instanceof CliError && /run `owenloop login`/.test(e.message)) {
5657
+ throw new CliError(`${e.message} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5658
+ }
5659
+ throw e;
5660
+ }
5661
+ }
4741
5662
  /**
4742
5663
  * `owenloop crew list|new|rm|member add|member rm` — administer hub crews.
4743
5664
  * Modeled directly on `dispatchCapability`: same validate-before-I/O discipline,
@@ -5029,6 +5950,79 @@ async function dispatchCrew(io, args) {
5029
5950
  throw e;
5030
5951
  }
5031
5952
  }
5953
+ /** Probe before any mkdir or temporary write. An existing operator file is a
5954
+ * successful no-op; every other existing filesystem object remains an error. */
5955
+ function hasExistingCrewRosterTarget(path) {
5956
+ try {
5957
+ const target = lstatSync(path);
5958
+ if (!target.isFile())
5959
+ throw new Error(`crew roster target exists but is not a regular file: ${path}`);
5960
+ return true;
5961
+ }
5962
+ catch (error) {
5963
+ if (error.code === 'ENOENT')
5964
+ return false;
5965
+ throw error;
5966
+ }
5967
+ }
5968
+ /**
5969
+ * Install a fully-written strongest-layer roster without replacing an
5970
+ * operator's file. Only EEXIST from the final exclusive link is interpreted
5971
+ * as an existing target; failures creating its parent or temporary file stay
5972
+ * failures instead of being misreported as a harmless skip.
5973
+ */
5974
+ export function installCrewRosterIfAbsent(path, contents, options = {}) {
5975
+ // This is deliberately before mkdir/temp creation: a setup rerun must be a
5976
+ // zero-write no-op even in a read-only or full directory.
5977
+ if (hasExistingCrewRosterTarget(path))
5978
+ return 'existing';
5979
+ const dir = dirname(path);
5980
+ mkdirSync(dir, { recursive: true });
5981
+ const temp = join(dir, options.tempName?.() ?? `.${randomUUID()}.roster.tmp`);
5982
+ let tempWritten = false;
5983
+ try {
5984
+ try {
5985
+ (options.writeTemp ?? ((candidate, body) => writeFileSync(candidate, body, { encoding: 'utf8', flag: 'wx' })))(temp, contents);
5986
+ tempWritten = true;
5987
+ }
5988
+ catch (error) {
5989
+ // `writeFileSync` can throw after creating a partial file (ENOSPC,
5990
+ // interruption). EEXIST is the one exception: that temp was never ours
5991
+ // and must not be removed. Every other failed write gets its partial
5992
+ // cleanup before the error reaches setup.
5993
+ if (error.code !== 'EEXIST') {
5994
+ try {
5995
+ unlinkSync(temp);
5996
+ }
5997
+ catch {
5998
+ // Nothing was created, or cleanup has no recovery path.
5999
+ }
6000
+ }
6001
+ throw error;
6002
+ }
6003
+ try {
6004
+ linkSync(temp, path);
6005
+ return 'created';
6006
+ }
6007
+ catch (error) {
6008
+ if (error.code !== 'EEXIST')
6009
+ throw error;
6010
+ // EEXIST is meaningful only for the target installation. Verify that it
6011
+ // is a real roster file before calling it an intentional operator file.
6012
+ if (!hasExistingCrewRosterTarget(path))
6013
+ throw error;
6014
+ return 'existing';
6015
+ }
6016
+ }
6017
+ finally {
6018
+ if (tempWritten) {
6019
+ try {
6020
+ unlinkSync(temp);
6021
+ }
6022
+ catch { /* target installation already decided; cleanup is best-effort */ }
6023
+ }
6024
+ }
6025
+ }
5032
6026
  /**
5033
6027
  * The plugin checks are rendered but NON-FATAL: a developer may use either
5034
6028
  * Claude Code or Codex, and a missing harness or failed plugin convergence must
@@ -5329,7 +6323,7 @@ export function resolveBundledMarketplaceRoot(harness) {
5329
6323
  return null;
5330
6324
  }
5331
6325
  function recordOf(value) {
5332
- return value !== null && typeof value === 'object' ? value : null;
6326
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
5333
6327
  }
5334
6328
  function normalizedPluginVersion(value) {
5335
6329
  if (typeof value !== 'string')
@@ -5653,7 +6647,7 @@ async function registerMachineEnrollment(io, origin, humanCred, keys, humanRef,
5653
6647
  return done('machine key registered');
5654
6648
  }
5655
6649
  /**
5656
- * `owenloop setup` — converge this machine's install in seven probe→(skip|act)
6650
+ * `owenloop setup` — converge this machine's install in eight probe→(skip|act)
5657
6651
  * steps, idempotently: a second run performs ZERO writes (no store mutation, no
5658
6652
  * key generation, no settings write, no browser, no mint/rekey/register POST).
5659
6653
  * Each ACT is reached only through its probe failing.
@@ -5740,8 +6734,8 @@ async function dispatchSetup(io, args) {
5740
6734
  }
5741
6735
  const origin = resolveSetupHub(io, args);
5742
6736
  const steps = [];
5743
- // --- [1/7] inspect: zero writes, best-effort probes ---
5744
- io.err('[1/7] inspect');
6737
+ // --- [1/8] inspect: zero writes, best-effort probes ---
6738
+ io.err('[1/8] inspect');
5745
6739
  io.err(` human credential: ${readCredential(io, origin, { principal: 'human' }) !== null ? 'present' : 'none — will log in'}`);
5746
6740
  const inspectSettingsPath = owenloopSettingsPath(io.env);
5747
6741
  let settingsNote;
@@ -5766,8 +6760,8 @@ async function dispatchSetup(io, args) {
5766
6760
  ? ' agent slots: checked in step 3'
5767
6761
  : ` agent slots: ${inspectAccts.length ? inspectAccts.map((a) => `agent:${a}`).join(', ') : 'none'}`);
5768
6762
  steps.push({ step: 'inspect', action: 'done', detail: 'probed local state' });
5769
- // --- [2/7] human login: the hard gate that makes step 3's rekey legal ---
5770
- io.err('[2/7] human login');
6763
+ // --- [2/8] human login: the hard gate that makes step 3's rekey legal ---
6764
+ io.err('[2/8] human login');
5771
6765
  let humanCred = readCredential(io, origin, { principal: 'human' });
5772
6766
  let humanIdentity;
5773
6767
  if (humanCred !== null) {
@@ -5795,8 +6789,8 @@ async function dispatchSetup(io, args) {
5795
6789
  io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
5796
6790
  steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
5797
6791
  }
5798
- // --- [3/7] agent ---
5799
- io.err('[3/7] agent');
6792
+ // --- [3/8] agent ---
6793
+ io.err('[3/8] agent');
5800
6794
  const { res: idRes } = await authedGet(io, origin, { principal: 'human' }, humanCred, '/api/agent_identities');
5801
6795
  if (idRes.status === 403) {
5802
6796
  throw new CliError('setup needs an admin credential to manage Scoped Identities (hub returned 403)');
@@ -5807,12 +6801,14 @@ async function dispatchSetup(io, args) {
5807
6801
  candidateNames.add('default');
5808
6802
  const probe = await probeAgentSlots(io, origin, [...candidateNames], identities);
5809
6803
  let agentAccount;
6804
+ let agentCrews;
5810
6805
  // The stable principal id for the agent signing key: the hub's agent actor
5811
6806
  // id (`agentId`), which rekey preserves and mint mints fresh.
5812
6807
  let agentPrincipalId;
5813
6808
  if (probe.verified !== null) {
5814
6809
  agentAccount = probe.verified.name;
5815
6810
  agentPrincipalId = probe.verified.actorId;
6811
+ agentCrews = probe.verified.identity?.crews;
5816
6812
  const crewsStr = probe.verified.identity ? ` (crews: ${probe.verified.identity.crews.join(', ') || 'none'})` : '';
5817
6813
  io.err(`✓ agent: ${agentAccount}${crewsStr}`);
5818
6814
  steps.push({ step: 'agent', action: 'skipped', detail: `agent:${agentAccount} verified` });
@@ -5846,6 +6842,7 @@ async function dispatchSetup(io, args) {
5846
6842
  const result = await mintAgentCredential(io, origin, { principal: 'human' }, humanCred, { name: action.name, crews, scopes });
5847
6843
  agentAccount = action.name;
5848
6844
  agentPrincipalId = result.agentId;
6845
+ agentCrews = result.crews;
5849
6846
  io.err(`✓ agent: minted agent:${agentAccount} (crews: ${result.crews.join(', ') || 'none'}; scopes: ${result.scopes.join(', ')})`);
5850
6847
  steps.push({ step: 'agent', action: 'done', detail: `minted agent:${agentAccount}` });
5851
6848
  }
@@ -5857,10 +6854,10 @@ async function dispatchSetup(io, args) {
5857
6854
  steps.push({ step: 'agent', action: 'done', detail: `re-keyed agent:${agentAccount}` });
5858
6855
  }
5859
6856
  }
5860
- // --- [4/7] signing keys: human → machine → agent, idempotently ---
6857
+ // --- [4/8] signing keys: human → machine → agent, idempotently ---
5861
6858
  // Prints kind + state + backend ONLY. Never key bytes, fingerprints,
5862
6859
  // secret-store values, or reused private-key paths.
5863
- io.err('[4/7] signing keys');
6860
+ io.err('[4/8] signing keys');
5864
6861
  const keys = io.principalKeys ?? new PrincipalKeyManager({ env: io.env });
5865
6862
  const humanRef = { origin, kind: 'human', id: humanIdentity.actor.id };
5866
6863
  const machineRef = { origin, kind: 'machine', id: 'local' };
@@ -5883,8 +6880,8 @@ async function dispatchSetup(io, args) {
5883
6880
  const enrollment = await registerMachineEnrollment(io, origin, humanCred, keys, humanRef, machine.publicKey);
5884
6881
  io.err(`${enrollment.action === 'noted' ? '!' : '✓'} enrollment: ${enrollment.detail}`);
5885
6882
  steps.push(enrollment);
5886
- // --- [5/7] owenloop settings ---
5887
- io.err('[5/7] owenloop settings');
6883
+ // --- [5/8] owenloop settings ---
6884
+ io.err('[5/8] owenloop settings');
5888
6885
  const settingsPath = owenloopSettingsPath(io.env);
5889
6886
  const existingSettings = readOwenloopSettingsRaw(settingsPath); // corrupt file → hard CliError (never clobber)
5890
6887
  const currentHub = existingSettings && typeof existingSettings.hubOrigin === 'string' ? existingSettings.hubOrigin : undefined;
@@ -5900,16 +6897,40 @@ async function dispatchSetup(io, args) {
5900
6897
  if (agentAccount !== 'default') {
5901
6898
  io.err(`non-default agent account — run owenloop work with OWENLOOP_ACCOUNT=${agentAccount}`);
5902
6899
  }
5903
- // --- [6/7] plugin (non-fatal) ---
5904
- io.err('[6/7] plugin');
6900
+ // --- [6/8] crew rosters ---
6901
+ io.err('[6/8] crew rosters');
6902
+ if (agentCrews === undefined || agentCrews.length === 0) {
6903
+ const detail = 'no crews known for this agent';
6904
+ io.err(`! crew rosters: ${detail}`);
6905
+ steps.push({ step: 'crew rosters', action: 'noted', detail });
6906
+ }
6907
+ else {
6908
+ for (const crew of agentCrews) {
6909
+ const path = crewRosterPath(io.env, crew);
6910
+ // Write a complete private temp first, then install it with link(2): the
6911
+ // link is exclusive (EEXIST leaves an operator file untouched), while a
6912
+ // short write can only leave a removable temp, never a corrupt roster.
6913
+ 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`);
6914
+ if (installed === 'created') {
6915
+ io.err(`✓ crew roster ${crew}: created`);
6916
+ steps.push({ step: 'crew rosters', action: 'done', detail: `${crew}: ${path}` });
6917
+ }
6918
+ else {
6919
+ io.err(`✓ crew roster ${crew}: existing file left untouched`);
6920
+ steps.push({ step: 'crew rosters', action: 'skipped', detail: `${crew}: ${path}` });
6921
+ }
6922
+ }
6923
+ }
6924
+ // --- [7/8] plugin (non-fatal) ---
6925
+ io.err('[7/8] plugin');
5905
6926
  for (const pluginState of probePlugin(io)) {
5906
6927
  const outcome = installPluginStep(io, pluginState);
5907
6928
  const marker = outcome.action === 'noted' ? '!' : '✓';
5908
6929
  io.err(`${marker} plugin (${pluginState.id}): ${outcome.detail}`);
5909
6930
  steps.push({ step: `plugin (${pluginState.id})`, ...outcome });
5910
6931
  }
5911
- // --- [7/7] doctor pass ---
5912
- io.err('[7/7] doctor');
6932
+ // --- [8/8] doctor pass ---
6933
+ io.err('[8/8] doctor');
5913
6934
  const doctor = await runDoctor(io, origin);
5914
6935
  print(io, { ok: doctor.ok, hub: origin, steps, doctor: { ok: doctor.ok, checks: doctor.checks } });
5915
6936
  return doctor.ok ? 0 : 1;
@@ -6103,7 +7124,40 @@ async function runDoctor(io, origin) {
6103
7124
  record('owenloop settings', true, settingsPath, true);
6104
7125
  }
6105
7126
  }
6106
- // 6–7. plugins (rendered; non-core while PLUGIN_CHECK_FATAL is false)
7127
+ // Crew-roster diagnostics are informational per crew. Global disk discovery
7128
+ // complements the verified agent's authoritative crew list: a malformed
7129
+ // bounded-hash file cannot decode its own identity, but the worker still
7130
+ // resolves that requested deterministic target and must fail closed on it.
7131
+ const crewNames = new Set();
7132
+ try {
7133
+ for (const file of discoverCrewRosterFiles(io.env))
7134
+ crewNames.add(file.crew);
7135
+ }
7136
+ catch (error) {
7137
+ record('crew roster discovery', false, error instanceof Error ? error.message : String(error), false);
7138
+ }
7139
+ if (agentProbe.verified?.identity !== undefined) {
7140
+ for (const crew of agentProbe.verified.identity.crews)
7141
+ crewNames.add(crew);
7142
+ }
7143
+ for (const crew of [...crewNames].sort()) {
7144
+ try {
7145
+ const settings = loadSettings(io.env);
7146
+ const layers = effectiveRosterLayers(io.env, crew, { origin: settings.hubOrigin, account: io.env.OWENLOOP_ACCOUNT ?? 'default' });
7147
+ const merged = mergeRosterLayers(layers);
7148
+ const found = layers
7149
+ .map((layer) => `${layer.source}=${layer.roster === undefined ? 'absent' : 'found'}`)
7150
+ .join(', ');
7151
+ const harnesses = [...new Set(Object.values(merged).flatMap((entry) => entry.candidates.map((candidate) => candidate.harness)))];
7152
+ const present = harnesses.filter((id) => adapterFor(id) !== undefined);
7153
+ const missing = harnesses.filter((id) => adapterFor(id) === undefined);
7154
+ record(`crew roster (${crew})`, true, `layers: ${found}; harnesses present: ${present.join(', ') || 'none'}; missing: ${missing.join(', ') || 'none'}`, false);
7155
+ }
7156
+ catch (error) {
7157
+ record(`crew roster (${crew})`, false, error instanceof Error ? error.message : String(error), false);
7158
+ }
7159
+ }
7160
+ // plugins (rendered; non-core while PLUGIN_CHECK_FATAL is false)
6107
7161
  for (const pluginState of probePlugin(io)) {
6108
7162
  const config = HARNESS_CONFIGS[pluginState.id];
6109
7163
  if (!pluginState.cliFound) {
@@ -6134,18 +7188,22 @@ async function runDoctor(io, origin) {
6134
7188
  * the async path, so every existing command and test keeps working exactly as
6135
7189
  * before.
6136
7190
  */
6137
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'cancel', 'instance', 'agent', 'capability', 'crew', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
7191
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'cancel', 'retry', 'instance', 'agent', 'capability', 'routing', 'crew', 'roster', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
6138
7192
  export async function mainAsync(argv, io = defaultIO()) {
6139
7193
  // Delegate execution-side and shift argv tails before root parsing. Their
6140
7194
  // roles own their option grammars, including repeated/value forms that the
6141
7195
  // engine parser must not consume. These dynamic imports are cold-start
6142
7196
  // boundaries: ordinary root commands never evaluate execution adapters.
6143
- if (argv[0] === 'work' || argv[0] === 'shift') {
7197
+ if (argv[0] === 'work' || argv[0] === 'shift' || argv[0] === 'util') {
6144
7198
  try {
6145
7199
  if (argv[0] === 'work') {
6146
7200
  const { mainAsync: runWork } = await import("../packages/work/src/main.js");
6147
7201
  return await runWork(argv.slice(1));
6148
7202
  }
7203
+ if (argv[0] === 'util') {
7204
+ const { mainAsync: runWork } = await import("../packages/work/src/main.js");
7205
+ return await runWork(['util', ...argv.slice(1)]);
7206
+ }
6149
7207
  const { run: runShift } = await import("../packages/work/src/roles/shift.js");
6150
7208
  return await runShift(argv.slice(1));
6151
7209
  }
@@ -6182,14 +7240,23 @@ export async function mainAsync(argv, io = defaultIO()) {
6182
7240
  return await dispatchStart(io, args);
6183
7241
  case 'cancel':
6184
7242
  return await dispatchCancel(io, args);
7243
+ case 'retry':
7244
+ // Local engine store unless --hub; only the hub half is async, and
7245
+ // main()'s own `case 'retry'` stays the local implementation so the
7246
+ // synchronous callers of main() keep working.
7247
+ return args.options.has('hub') ? await dispatchRetry(io, args) : main(argv, io);
6185
7248
  case 'instance':
6186
7249
  return await dispatchInstance(io, args);
6187
7250
  case 'agent':
6188
7251
  return await dispatchAgent(io, args);
6189
7252
  case 'capability':
6190
7253
  return await dispatchCapability(io, args);
7254
+ case 'routing':
7255
+ return await dispatchRouting(io, args);
6191
7256
  case 'crew':
6192
7257
  return await dispatchCrew(io, args);
7258
+ case 'roster':
7259
+ return await dispatchRoster(io, args);
6193
7260
  case 'setup':
6194
7261
  return await dispatchSetup(io, args);
6195
7262
  case 'doctor':