owenloop 0.4.1 → 0.5.0

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 (154) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +58 -31
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{cli.d.ts → src/cli.d.ts} +18 -3
  109. package/dist/{cli.js → src/cli.js} +770 -114
  110. package/dist/{credentials.d.ts → src/credentials.d.ts} +18 -12
  111. package/dist/{credentials.js → src/credentials.js} +14 -12
  112. package/dist/{defs.js → src/defs.js} +36 -36
  113. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  114. package/dist/{engine.js → src/engine.js} +14 -14
  115. package/dist/{hub.d.ts → src/hub.d.ts} +205 -10
  116. package/dist/{hub.js → src/hub.js} +370 -12
  117. package/dist/{index.d.ts → src/index.d.ts} +1 -1
  118. package/dist/{index.js → src/index.js} +1 -1
  119. package/dist/{mcp → src/mcp}/serve.d.ts +5 -4
  120. package/dist/{mcp → src/mcp}/serve.js +168 -31
  121. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  122. package/dist/{mcp → src/mcp}/server.js +6 -9
  123. package/dist/{model.js → src/model.js} +1 -1
  124. package/dist/{types.d.ts → src/types.d.ts} +18 -18
  125. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  126. package/dist/{util.js → src/util.js} +3 -2
  127. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  128. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  129. package/docs/authoring.md +93 -53
  130. package/docs/cli.md +597 -76
  131. package/docs/design.md +33 -33
  132. package/docs/embedding.md +10 -9
  133. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  134. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  135. package/examples/workflows/judges/gate-sharpness.md +39 -0
  136. package/examples/workflows/judges/security.md +34 -0
  137. package/package.json +17 -8
  138. /package/dist/{add.d.ts → src/add.d.ts} +0 -0
  139. /package/dist/{add.js → src/add.js} +0 -0
  140. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  141. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  142. /package/dist/{factory.js → src/factory.js} +0 -0
  143. /package/dist/{lock.d.ts → src/lock.d.ts} +0 -0
  144. /package/dist/{lock.js → src/lock.js} +0 -0
  145. /package/dist/{model.d.ts → src/model.d.ts} +0 -0
  146. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  147. /package/dist/{paths.js → src/paths.js} +0 -0
  148. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  149. /package/dist/{schema.js → src/schema.js} +0 -0
  150. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  151. /package/dist/{store.js → src/store.js} +0 -0
  152. /package/dist/{types.js → src/types.js} +0 -0
  153. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  154. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The owenloop CLI — a thin, scriptable surface over the engine.
3
3
  *
4
- * Every data command prints JSON to stdout, so a *wiring* (the worker/automation
4
+ * Every data command prints JSON to stdout, so a *wiring* (the Step Agent/automation
5
5
  * that actually runs orders) can drive the engine programmatically: `tick` to
6
6
  * pull orders, run them, then `green` / `emit` / `seal` / `reject` / `close` to
7
7
  * report outcomes. The engine itself is domain-neutral; this binary just maps
@@ -47,8 +47,8 @@ import { authHeader, deleteCredential, discoverMetadata, ensureFreshOAuth, hubFe
47
47
  import { runMcpCommand } from "./mcp/serve.js";
48
48
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
49
49
  import { acquireInstallLock, ADD_JOURNAL_FILENAME, archivePathViolation, commitInstall, finalizeInstallCommit, githubShaUrl, githubTarballUrl, installFolder, parkOldNameDir, parseRepoSpec, readLockfile, recoverInterruptedInstall, releaseInstallLock, removeAddJournal, rollbackInstallCommit, RollbackFailedError, stageFiles, STAGING_DIRNAME, writeAddJournal, writeLockfile, } from "./add.js";
50
- import { asAgentIdentities, asCreateWorkflowOk, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
51
- import { owenworkSettingsPath, readOwenworkSettingsRaw, writeOwenworkHubOrigin } from "./owenwork.js";
50
+ import { asAgentIdentities, asCreateWorkflowOk, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
51
+ import { owenloopSettingsPath, readOwenloopSettingsRaw, writeOwenloopHubOrigin } from "./work-settings.js";
52
52
  function defaultIO() {
53
53
  return {
54
54
  cwd: process.cwd(),
@@ -380,17 +380,27 @@ Commands:
380
380
  connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
381
381
  push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)
382
382
  --as names the credential slot: human (default), agent, or agent:<account>
383
- agent new <name> [--pools <a,b>] [--hub <url>] mint a new agent identity on the hub and store its token in slot agent:<name> (the token is never printed)
384
- setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--pools <a,b>] converge this machine's install: human login, agent credential, owenwork settings, plugin (idempotent)
383
+ 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)
384
+ 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)
385
+ capability unbind <capability> <crew> [--hub <url>] remove one (capability, crew) route
386
+ capability list [--hub <url>] list the hub org's capability routes
387
+ crew list [--hub <url>] list the hub org's crews with their members (includes the orphan crew once one exists)
388
+ crew new <name> --kind personal|shared [--owner <memberId>] [--hub <url>] create a crew on the hub org (admin, or own personal crew; human credential)
389
+ crew rm <crewId> [--hub <url>] delete a crew; work stamped to it moves to the org's orphan crew
390
+ crew member add <crewId> <principalKind> <principalId> [--hub <url>] add a member or agent to a crew
391
+ crew member rm <crewId> <principalId> [--hub <url>] remove a principal from a crew
392
+ setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--crews <a,b>] [--scopes <a,b>] converge this machine's install: human login, agent credential, owenloop settings, plugin (idempotent)
385
393
  doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)
386
394
  mcp [--hub <url>] serve the hub control plane over stdio MCP (spawned by MCP hosts, not run by humans)
395
+ work <subcommand> [args] run execution-side shift/hold/exec/agent-run/... commands
396
+ shift start|next|status|end [args] run and attend a local Unix-socket shift daemon
387
397
  lint [<def-name>] check def(s) for wiring problems
388
398
  check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided] [--strict-inputs]
389
399
  bounded reachability check (stall states, true deadlocks, stuck, dead steps, declared invariants)
390
400
  create <def> [--title t] [--provide name=json ...] [--param k=v ...]
391
401
  provide <wf> <name> [--value json] supply an owed (seedOwed) input
392
402
  adopt <wf> re-pin an instance to the current def (§28); settles new debts
393
- tick <wf> [--now <ms>] [--shallow] [--label <l>]... pull eligible orders (deep: also from calls: children; --shallow for this instance only; --label filters to matching-label steps)
403
+ 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)
394
404
  reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)
395
405
  runs <wf> [--open] list this instance's runs (+ claim state for open ones)
396
406
  order <wf> <run> print the order packet issued at claim time (persisted in the claim txn)
@@ -419,6 +429,24 @@ function failureNote(failures) {
419
429
  return '';
420
430
  return `\n${failures.length} file(s) failed to load:\n - ${failures.map((f) => `${f.file}: ${f.error}`).join('\n - ')}`;
421
431
  }
432
+ /**
433
+ * The single "definite defect" predicate over a modelCheck `report`, shared by
434
+ * `check`, `add` (dispatchAdd) and `push` (dispatchPush) so all three
435
+ * accept-or-reject a def identically. A pure function of the report object — it
436
+ * does NOT read or change how any caller seeded its modelCheck (add/push seed
437
+ * `assumeProvided: true`; check seeds `assumeProvided: !strictInputs`).
438
+ *
439
+ * invariant violations and structurally-dead steps are ALWAYS definite (sound
440
+ * regardless of bounds); a true deadlock counts ONLY when the search was
441
+ * exhaustive (`!bounded`) because a tight maxCollectionSize cap can manufacture
442
+ * a spurious one. `unreachedSteps` is deliberately EXCLUDED — it is a bounds
443
+ * artifact ("raise --max-states/--max-depth"), never a definite defect.
444
+ */
445
+ export function hasDefiniteCheckDefect(report) {
446
+ return (report.invariantViolations.length > 0 ||
447
+ report.structurallyDeadSteps.length > 0 ||
448
+ (!report.bounded && report.deadlocks.length > 0));
449
+ }
422
450
  /**
423
451
  * Options accepted on EVERY command. docs/cli.md documents `--db`/`--defs` as
424
452
  * global ("pass both on every command"), so they are allowlisted everywhere —
@@ -449,16 +477,20 @@ export const COMMAND_OPTIONS = new Map([
449
477
  ['logout', cmdOpts('hub', 'as')],
450
478
  ['connect', cmdOpts('hub', 'as')],
451
479
  ['push', cmdOpts('dry-run', 'force', 'hub', 'as')],
452
- ['agent', cmdOpts('pools', 'hub')],
453
- ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'pools')],
480
+ ['agent', cmdOpts('crews', 'hub', 'scopes', 'shift')],
481
+ ['capability', cmdOpts('hub')],
482
+ ['crew', cmdOpts('hub', 'kind', 'owner')],
483
+ ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'crews', 'scopes')],
454
484
  ['doctor', cmdOpts('hub')],
455
485
  ['mcp', cmdOpts('hub')],
486
+ ['work', cmdOpts()],
487
+ ['shift', cmdOpts('all', 'origin', 'as', 'name', 'cap', 'max-agents', 'poll-interval', 'once', 'cache-dir', 'state-dir', 'wait')],
456
488
  ['lint', cmdOpts()],
457
489
  ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided', 'strict-inputs')],
458
490
  ['create', cmdOpts('title', 'provide', 'param')],
459
491
  ['provide', cmdOpts('value')],
460
492
  ['adopt', cmdOpts()],
461
- ['tick', cmdOpts('now', 'shallow', 'label')],
493
+ ['tick', cmdOpts('now', 'shallow', 'capability')],
462
494
  ['reap', cmdOpts('now')],
463
495
  ['status', cmdOpts('all')],
464
496
  ['wait', cmdOpts('until', 'timeout')],
@@ -724,9 +756,7 @@ function dispatch(command, io, args) {
724
756
  // one branch while the line still moves on another). Neither is a defect.
725
757
  // - truncated with no invariant violations / structurally-dead steps / true
726
758
  // deadlocks → 0
727
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
728
- report.structurallyDeadSteps.length > 0 ||
729
- (!report.bounded && report.deadlocks.length > 0);
759
+ const hasDefiniteDefect = hasDefiniteCheckDefect(report);
730
760
  if (hasDefiniteDefect) {
731
761
  throw new CliError(`definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
732
762
  `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
@@ -787,11 +817,11 @@ function dispatch(command, io, args) {
787
817
  tickOpts.now = now;
788
818
  if (flag(args, 'shallow'))
789
819
  tickOpts.deep = false;
790
- // A2: repeatable --label narrows the claim to steps whose labels
820
+ // A2: repeatable --capability narrows the claim to steps whose capabilities
791
821
  // intersect the caller's; absent = claim everything (today's behavior).
792
- const labels = all(args, 'label');
793
- if (labels.length > 0)
794
- tickOpts.labels = labels;
822
+ const capabilities = all(args, 'capability');
823
+ if (capabilities.length > 0)
824
+ tickOpts.capabilities = capabilities;
795
825
  print(io, engine.tick(wf, tickOpts));
796
826
  return 0;
797
827
  }
@@ -833,7 +863,7 @@ function dispatch(command, io, args) {
833
863
  return 0;
834
864
  }
835
865
  case 'wait': {
836
- // Blocking poll so an orchestrator/agent can wait for engine state
866
+ // Blocking poll so an orchestrator (Prime Agent or Shift) can wait for engine state
837
867
  // change without burning inference on a poll loop. Plain synchronous
838
868
  // poll of the local db (cheap — one process, no LLM calls). On
839
869
  // success, prints the exact `status()` shape (same as plain
@@ -1444,26 +1474,25 @@ async function dispatchAdd(io, args) {
1444
1474
  reasons.push(...lintResult.errors.map((e) => `${stagedDef.name}: ${e}`));
1445
1475
  const validationErrors = validateDef(stagedDef);
1446
1476
  reasons.push(...validationErrors.map((e) => `${stagedDef.name}: ${e}`));
1447
- // Mirror the `check` command's exact "definite defect" predicate — but,
1448
- // deliberately, WITH `assumeProvided: true`. Without it, a def with any
1449
- // `seedOwed` input (the norm — see e.g. `proposal` in delivery.yaml)
1450
- // deadlocks in the very first state, because the checker models "no
1451
- // `provide` has happened yet" by default (see `seedArts` in
1452
- // src/model.ts). `owenloop check <def>` behaves the same way absent
1453
- // `--assume-provided`; verified every def under examples/workflows/
1454
- // fails plain `check` for exactly this reason. Since `add` validates a
1455
- // def that a real user will `provide` into after install (that's the
1456
- // whole point of a seedOwed input), refusing every seedOwed def here
1457
- // would make `add` unable to install almost any real workflow,
1458
- // including this project's own examples — so this checks "is it
1459
- // completable once its owed inputs are supplied," the same bar a
1460
- // careful author would clear with `check --assume-provided` before
1461
- // publishing.
1477
+ // The definite-defect verdict here is the shared `hasDefiniteCheckDefect(report)`
1478
+ // helper — identical to `check`. What is deliberately different is only the
1479
+ // seeding of THIS modelCheck call: `assumeProvided: true` (below). Without it,
1480
+ // a def with any `seedOwed` input (the norm — see e.g. `proposal` in
1481
+ // delivery.yaml) deadlocks in the very first state, because the checker models
1482
+ // "no `provide` has happened yet" by default (see `seedArts` in src/model.ts).
1483
+ // `owenloop check <def>` behaves the same way absent `--assume-provided`;
1484
+ // verified every def under examples/workflows/ fails plain `check` for exactly
1485
+ // this reason. Since `add` validates a def that a real user will `provide` into
1486
+ // after install (that's the whole point of a seedOwed input), refusing every
1487
+ // seedOwed def here would make `add` unable to install almost any real
1488
+ // workflow, including this project's own examples — so this checks "is it
1489
+ // completable once its owed inputs are supplied," the same bar a careful author
1490
+ // would clear with `check --assume-provided` before publishing.
1462
1491
  const report = modelCheck(stagedDef, { assumeProvided: true });
1463
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
1464
- (!report.bounded && report.deadlocks.length > 0);
1492
+ const hasDefiniteDefect = hasDefiniteCheckDefect(report);
1465
1493
  if (hasDefiniteDefect) {
1466
1494
  reasons.push(`${stagedDef.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
1495
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
1467
1496
  `${report.deadlocks.length} true deadlock(s))`);
1468
1497
  }
1469
1498
  }
@@ -1785,6 +1814,38 @@ async function authedGet(io, origin, slot, cred, path, persist = true) {
1785
1814
  }
1786
1815
  return { res, cred: current };
1787
1816
  }
1817
+ /**
1818
+ * POST a JSON `body` to `path` on `origin` with a bearer credential — the
1819
+ * request-side sibling of `authedGet`, and the same chain `mintAgentCredential`
1820
+ * runs: refresh an expiring oauth token first (`persist` defaults to true, so a
1821
+ * rotated refresh token lands in the store), POST, and on a 401 with an oauth
1822
+ * credential refresh once and retry exactly once.
1823
+ *
1824
+ * Goes through `hubFetch`, never raw `fetch` — that is what supplies the 30s
1825
+ * deadline, the bounded body read, and `redirect: 'error'`.
1826
+ *
1827
+ * Returns the raw response plus the credential actually used, leaving ALL error
1828
+ * semantics (the final 401, a non-2xx, body parsing) to the caller, exactly like
1829
+ * `authedGet` — the wording differs by context.
1830
+ */
1831
+ async function authedPost(io, origin, slot, cred, path, body, persist = true) {
1832
+ let current = await ensureFreshOAuth(io, origin, slot, cred, persist);
1833
+ const doPost = (bearer) => hubFetch(io, resolveEndpoint(origin, path), {
1834
+ method: 'POST',
1835
+ headers: {
1836
+ Authorization: authHeader(bearer),
1837
+ 'Content-Type': 'application/json',
1838
+ Accept: 'application/json',
1839
+ },
1840
+ body: JSON.stringify(body),
1841
+ });
1842
+ let res = await doPost(current);
1843
+ if (res.status === 401 && current.kind === 'oauth') {
1844
+ current = await refreshOAuth(io, origin, slot, current, persist);
1845
+ res = await doPost(current);
1846
+ }
1847
+ return { res, cred: current };
1848
+ }
1788
1849
  /**
1789
1850
  * A 401 on an agent token is a hard "revoked/invalid" error; a 401 on any
1790
1851
  * other credential kind (after `authedGet`'s one refresh-and-retry) is a hard
@@ -2220,10 +2281,10 @@ async function dispatchPush(io, args) {
2220
2281
  reasons.push(...lintResult.errors.map((e) => `${def.name}: ${e}`));
2221
2282
  reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
2222
2283
  const report = modelCheck(def, { assumeProvided: true });
2223
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
2224
- (!report.bounded && report.deadlocks.length > 0);
2284
+ const hasDefiniteDefect = hasDefiniteCheckDefect(report);
2225
2285
  if (hasDefiniteDefect) {
2226
2286
  reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
2287
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
2227
2288
  `${report.deadlocks.length} true deadlock(s))`);
2228
2289
  }
2229
2290
  }
@@ -2273,7 +2334,7 @@ async function dispatchPush(io, args) {
2273
2334
  throw new CliError(`refusing to push — ${reasons.length} problem(s) found; nothing sent:\n - ${reasons.join('\n - ')}`);
2274
2335
  }
2275
2336
  // Fetch the server's own list once — the diff source of truth. Always
2276
- // fetched, even under --force, so the new/changed labels stay accurate.
2337
+ // fetched, even under --force, so the new/changed capabilities stay accurate.
2277
2338
  const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, cred, '/api/workflows');
2278
2339
  assertAuthOk(listRes, listCred, origin);
2279
2340
  cred = listCred;
@@ -2405,14 +2466,24 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2405
2466
  });
2406
2467
  }
2407
2468
  /**
2408
- * Resolve the hub `agent new` mints on: `--hub <origin>` (normalized via
2409
- * `normalizeOrigin`) → else the ONE hub the credential FILE knows → else a
2410
- * `CliError` with `exitCode: 2` naming both remedies.
2469
+ * Resolve the hub a mutating hub command acts on — shared by `agent new`,
2470
+ * `capability bind|unbind|list`, and `crew`'s five subcommands: `--hub <origin>`
2471
+ * (normalized via `normalizeOrigin`) → else the ONE hub the credential FILE
2472
+ * knows → else a `CliError` with `exitCode: 2` naming both remedies.
2473
+ *
2474
+ * `purpose` is the verb phrase spliced into both exit-2 messages ("cannot
2475
+ * determine which hub to <purpose> — …"). It defaults to `'mint on'` so
2476
+ * `dispatchAgent`'s two-argument call keeps `agent new`'s error strings
2477
+ * byte-identical; `dispatchCapability` passes `'manage capability routes on'`;
2478
+ * `dispatchCrew` passes `'manage crews on'`.
2411
2479
  *
2412
2480
  * Deliberately NOT `resolveHub` (`--hub → OWENLOOP_HUB → DEFAULT_HUB`): silently
2413
2481
  * defaulting a MINT to the production hub while the user is logged into a dev hub
2414
- * would mint on the wrong org, and a mint is not undone by a retry. `OWENLOOP_HUB`
2415
- * is intentionally excluded so this stays in parity with O2's `owenloop mcp`.
2482
+ * would mint on the wrong org, and a mint is not undone by a retry. The same
2483
+ * reasoning covers a capability route — writing one against the wrong org is not
2484
+ * undone by a retry either, and under live resolution it also moves in-flight
2485
+ * work. `OWENLOOP_HUB` is intentionally excluded so this stays in parity with
2486
+ * O2's `owenloop mcp`.
2416
2487
  *
2417
2488
  * `listStoredHubOrigins` is backend-aware (shared with O2's `owenloop mcp`): only
2418
2489
  * the FILE backend can enumerate, so it returns `null` on a keychain- or
@@ -2421,7 +2492,7 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2421
2492
  * (used automatically), or more than one (the non-secret origin keys are listed
2422
2493
  * back so the user can pick).
2423
2494
  */
2424
- function resolveAgentHub(io, args) {
2495
+ function resolveAgentHub(io, args, purpose = 'mint on') {
2425
2496
  const flagVal = last(args, 'hub');
2426
2497
  if (flagVal !== undefined) {
2427
2498
  try {
@@ -2435,24 +2506,30 @@ function resolveAgentHub(io, args) {
2435
2506
  if (origins === null) {
2436
2507
  const backend = credentialBackend(io.env, io.keychain);
2437
2508
  const which = backend.kind === 'external' ? 'external-command' : 'keychain';
2438
- throw new CliError(`cannot determine which hub to mint on — the ${which} credential store cannot be enumerated; ` +
2509
+ throw new CliError(`cannot determine which hub to ${purpose} — the ${which} credential store cannot be enumerated; ` +
2439
2510
  'pass --hub <origin>', { exitCode: 2 });
2440
2511
  }
2441
2512
  if (origins.length === 1)
2442
2513
  return origins[0];
2443
- throw new CliError('cannot determine which hub to mint on — pass --hub <origin>, or log in to exactly one hub first ' +
2514
+ throw new CliError(`cannot determine which hub to ${purpose} — pass --hub <origin>, or log in to exactly one hub first ` +
2444
2515
  '(owenloop login --hub <origin>)' +
2445
2516
  (origins.length > 1 ? `; stored hubs: ${origins.join(', ')}` : ''), { exitCode: 2 });
2446
2517
  }
2447
2518
  /**
2448
- * `owenloop agent new <name>` — mint a new agent identity on the hub and store
2519
+ * `owenloop agent new <name>` — mint a new Scoped Identity on the hub and store
2449
2520
  * its `olp_` token in slot `agent:<name>`.
2450
2521
  *
2451
2522
  * **Secret hygiene (identity model §6, "rule of gates"):** the minted token goes
2452
2523
  * process→store ONLY — it never appears on stdout, stderr, in an error, or in a
2453
2524
  * log. `mintAgentCredential` (credentials.ts) owns the token end to end and
2454
2525
  * returns none of it; the confirmation printed here is built from an explicit
2455
- * WHITELIST of non-secret fields (name, pools, storage backend, revocation ids).
2526
+ * WHITELIST of non-secret fields (name, crews, scopes, storage backend,
2527
+ * revocation ids).
2528
+ *
2529
+ * Flags: `--crews a,b` (the Scoped Identity's crews; default = minter's personal crew);
2530
+ * `--scopes a,b` (the minted token's scopes; default `work`); `--shift`
2531
+ * (sugar for `--scopes work,run`; mutually exclusive with `--scopes`); `--hub`.
2532
+ * `--scopes` is passed to the hub verbatim — no client-side scope-name check.
2456
2533
  *
2457
2534
  * Ordering is load-bearing (PR #69 lesson, carried by `mintAgentCredential`): the
2458
2535
  * client-side name validation and the external-command refusal both run BEFORE
@@ -2460,7 +2537,7 @@ function resolveAgentHub(io, args) {
2460
2537
  * mints a server-side token first — minting then failing to store would burn the
2461
2538
  * agent name permanently.
2462
2539
  *
2463
- * Exit codes: 0 ok; 1 generic failure (invalid name, name taken, pool/shape
2540
+ * Exit codes: 0 ok; 1 generic failure (invalid name, name taken, crew/shape
2464
2541
  * rejection, network timeout, minted-but-unstored); 2 the hub is unresolvable;
2465
2542
  * 3 the human credential is absent or irrecoverable (remedy names
2466
2543
  * `owenloop login --hub <origin>`).
@@ -2474,7 +2551,7 @@ async function dispatchAgent(io, args) {
2474
2551
  }
2475
2552
  const name = args.positionals[2];
2476
2553
  if (name === undefined) {
2477
- throw new CliError('missing required argument: <name> (usage: owenloop agent new <name> [--pools a,b] [--hub <url>])');
2554
+ throw new CliError('missing required argument: <name> (usage: owenloop agent new <name> [--crews a,b] [--scopes work,run | --shift] [--hub <url>])');
2478
2555
  }
2479
2556
  // Validate the agent name eagerly — before any I/O — with the store's own
2480
2557
  // wording, so a bad name never reaches the network or the store.
@@ -2484,21 +2561,47 @@ async function dispatchAgent(io, args) {
2484
2561
  catch (e) {
2485
2562
  throw new CliError(`agent new: invalid agent name — ${e.message}`);
2486
2563
  }
2487
- // --pools: split on `,`, trim, drop empties. Absent → undefined (key omitted
2488
- // from the request; the server then defaults to the minter's personal pool).
2489
- // Present but empty (`--pools ""` / `--pools ,`) → usage error, before any I/O.
2490
- // No client-side pool-name validation — the server is the enforcement of record.
2491
- const poolsRaw = last(args, 'pools');
2492
- let pools;
2493
- if (poolsRaw !== undefined) {
2494
- pools = poolsRaw
2564
+ // --crews: split on `,`, trim, drop empties. Absent → undefined (key omitted
2565
+ // from the request; the server then defaults to the minter's personal crew).
2566
+ // Present but empty (`--crews ""` / `--crews ,`) → usage error, before any I/O.
2567
+ // No client-side crew-name validation — the server is the enforcement of record.
2568
+ const crewsRaw = last(args, 'crews');
2569
+ let crews;
2570
+ if (crewsRaw !== undefined) {
2571
+ crews = crewsRaw
2495
2572
  .split(',')
2496
2573
  .map((p) => p.trim())
2497
2574
  .filter((p) => p !== '');
2498
- if (pools.length === 0) {
2499
- throw new CliError('--pools requires at least one pool name');
2575
+ if (crews.length === 0) {
2576
+ throw new CliError('--crews requires at least one crew name');
2577
+ }
2578
+ }
2579
+ // --scopes: same split/trim/filter shape as --crews. Absent → undefined (the
2580
+ // key is omitted from the mint params, so mintAgentCredential applies its own
2581
+ // `?? ['work']` default). Present but empty (`--scopes ""` / `--scopes ,`) →
2582
+ // usage error, before any I/O. No client-side scope-NAME validation — the hub
2583
+ // is the enforcement of record (same stance as crews).
2584
+ const scopesRaw = last(args, 'scopes');
2585
+ let scopes;
2586
+ if (scopesRaw !== undefined) {
2587
+ scopes = scopesRaw
2588
+ .split(',')
2589
+ .map((s) => s.trim())
2590
+ .filter((s) => s !== '');
2591
+ if (scopes.length === 0) {
2592
+ throw new CliError('--scopes requires at least one scope name');
2500
2593
  }
2501
2594
  }
2595
+ // --shift is sugar for --scopes work,run. It takes no value. Combining it
2596
+ // with an explicit --scopes is a usage error (two ways to say the same thing,
2597
+ // possibly conflicting) — refused before any I/O.
2598
+ const shift = flag(args, 'shift');
2599
+ if (shift) {
2600
+ if (scopes !== undefined) {
2601
+ throw new CliError('pass at most one of --scopes or --shift, not both');
2602
+ }
2603
+ scopes = ['work', 'run'];
2604
+ }
2502
2605
  // Refuse an external-command setup at the TOP of the dispatcher — before the
2503
2606
  // human-credential read (which would otherwise RUN the command) and before any
2504
2607
  // network call (PR #69 lesson; `mintAgentCredential` carries the same guard as
@@ -2517,7 +2620,7 @@ async function dispatchAgent(io, args) {
2517
2620
  }
2518
2621
  let result;
2519
2622
  try {
2520
- result = await mintAgentCredential(io, origin, { principal: 'human' }, cred, { name, pools });
2623
+ result = await mintAgentCredential(io, origin, { principal: 'human' }, cred, { name, crews, scopes });
2521
2624
  }
2522
2625
  catch (e) {
2523
2626
  // A refresh-failure-family error (the human oauth is irrecoverable, or a 401
@@ -2536,14 +2639,523 @@ async function dispatchAgent(io, args) {
2536
2639
  hub: origin,
2537
2640
  name,
2538
2641
  slot: `agent:${name}`,
2539
- pools: result.pools,
2540
- scopes: ['work'],
2642
+ crews: result.crews,
2643
+ scopes: result.scopes,
2541
2644
  storage: result.storage,
2542
2645
  agentId: result.agentId,
2543
2646
  tokenId: result.id,
2544
2647
  });
2545
2648
  return 0;
2546
2649
  }
2650
+ /**
2651
+ * `owenloop capability bind|unbind|list` — manage the hub org's **capability routes**, the
2652
+ * admin-owned table mapping a workflow-def `capabilities:` entry to a crew.
2653
+ *
2654
+ * A capability route is NOT the project↔hub route `owenloop connect` writes to
2655
+ * `.owenloop/hub.json` — different concept, same English word; every symbol in
2656
+ * this family is `CapabilityRoute`-prefixed to keep them apart.
2657
+ *
2658
+ * | subcommand | endpoint | auth principal |
2659
+ * |---|---|---|
2660
+ * | `capability bind <capability> <crew>` | `POST /api/add_capability_route` | human (admin role on the hub) |
2661
+ * | `capability unbind <capability> <crew>` | `POST /api/remove_capability_route` | human (admin role on the hub) |
2662
+ * | `capability list` | `GET /api/capability_routes` | human |
2663
+ *
2664
+ * **route is ADDITIVE, and idempotent per `(capability, crew)` PAIR.** A capability may
2665
+ * bind MANY crews. `capability bind` on an already-bound capability ADDS a crew; it never
2666
+ * displaces one already bound. Re-adding the same pair is a normal 200 no-op, so
2667
+ * there is no "already bound" rejection to handle and no client-side pre-check —
2668
+ * the response says which happened via `alreadyRouted`, and `routedCrewCount`
2669
+ * reports how many LIVE crews the capability binds afterwards.
2670
+ *
2671
+ * **`capability unbind` removes ONE pair**, which is why `<crew>` is required. Removing
2672
+ * the LAST LIVE route PARKS the capability: its in-flight steps are offered to no
2673
+ * shift until it is bound again. The response's `remainingCrewIds` is the
2674
+ * signal (`[]` = parked), and that case gets a **stderr** warning; so does the
2675
+ * tolerant `removed: false` case. stdout stays one parseable JSON document.
2676
+ *
2677
+ * **Retargeting is now two separate operator acts** — add the new crew, then
2678
+ * remove the old one, each separately audited on the hub, with BOTH crews serving
2679
+ * in between. The CLI deliberately does NOT synthesize a retarget by chaining the
2680
+ * two calls, and there is no back-compat fallback to the old routes. Resolution
2681
+ * on the hub is live, so both acts take effect on in-flight runs at their next
2682
+ * poll — documented in `docs/cli.md`.
2683
+ *
2684
+ * What is deliberately NOT copied from `dispatchAgent`: its
2685
+ * `OWENLOOP_CREDENTIAL_COMMAND` refusal. That guard exists because `agent new`
2686
+ * must STORE a minted token and an external-command backend has nowhere to write
2687
+ * it. `capability` stores nothing locally, so an external-command machine must be
2688
+ * able to run all three subcommands. (`resolveAgentHub` still exits 2 on such a
2689
+ * machine when `--hub` is absent, because that store cannot be enumerated —
2690
+ * inherited unchanged, and correct.)
2691
+ *
2692
+ * No client-side charset validation of `capability` or `crew`: the hub is the
2693
+ * enforcement of record, the same stance `agent new` takes for `--crews`.
2694
+ *
2695
+ * Exit codes: 0 ok; 1 runtime/hub error (an unknown crew name — `capability bind`
2696
+ * ONLY, since `capability unbind` answers a tolerant `removed: false` instead of a
2697
+ * 400; a capability that fails the hub's name rules, a 403 for a non-admin, a
2698
+ * malformed 2xx, a network timeout); 2 the hub is unresolvable; 3 the human
2699
+ * credential is absent or irrecoverable (the error names
2700
+ * `owenloop login --hub <origin>`).
2701
+ */
2702
+ async function dispatchCapability(io, args) {
2703
+ const USAGE_FORMS = 'usage: owenloop capability bind <capability> <crew> [--hub <url>] | owenloop capability unbind <capability> <crew> [--hub <url>] | owenloop capability list [--hub <url>]';
2704
+ // --- validation: everything below runs BEFORE any I/O, so a usage error on a
2705
+ // multi-hub machine reports the usage problem (exit 1), not exit 2.
2706
+ const sub = args.positionals[1];
2707
+ if (sub !== 'bind' && sub !== 'unbind' && sub !== 'list') {
2708
+ throw new CliError(`unknown capability subcommand '${sub ?? ''}' — ${USAGE_FORMS}`);
2709
+ }
2710
+ let capability = '';
2711
+ let crew = '';
2712
+ if (sub === 'bind' || sub === 'unbind') {
2713
+ // `<crew>` is required for BOTH now: one call adds or removes ONE
2714
+ // `(capability, crew)` pair, and a capability-only `unbind` would unbind more than
2715
+ // the operator named.
2716
+ const rawCapability = args.positionals[2];
2717
+ if (rawCapability === undefined || rawCapability === '') {
2718
+ throw new CliError(`missing required argument: <capability> (${USAGE_FORMS})`);
2719
+ }
2720
+ capability = rawCapability;
2721
+ const rawCrew = args.positionals[3];
2722
+ if (rawCrew === undefined || rawCrew === '') {
2723
+ throw new CliError(`missing required argument: <crew> (${USAGE_FORMS})`);
2724
+ }
2725
+ crew = rawCrew;
2726
+ }
2727
+ const origin = resolveAgentHub(io, args, 'manage capability routes on');
2728
+ const slot = { principal: 'human' };
2729
+ // The human bearer for the resolved origin. Absent → exit 3 with the same
2730
+ // remedy wording `agent new` uses.
2731
+ const cred = readCredential(io, origin, slot);
2732
+ if (cred === null) {
2733
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2734
+ }
2735
+ try {
2736
+ if (sub === 'list') {
2737
+ const { res, cred: used } = await authedGet(io, origin, slot, cred, '/api/capability_routes');
2738
+ // The GET deliberately uses `assertAuthOk` unchanged (frozen contract), so
2739
+ // a non-401 non-2xx surfaces its generic wording rather than the hub's
2740
+ // `message`. Message passthrough is a POST-path behavior below.
2741
+ assertAuthOk(res, used, origin);
2742
+ let body;
2743
+ try {
2744
+ body = (await res.json());
2745
+ }
2746
+ catch {
2747
+ throw new CliError('capability_routes: malformed response — body is not valid JSON');
2748
+ }
2749
+ let routes;
2750
+ try {
2751
+ routes = asCapabilityRoutes(body);
2752
+ }
2753
+ catch (e) {
2754
+ throw new CliError(e.message);
2755
+ }
2756
+ // The guard's output — a whitelisted typed array — never the raw body.
2757
+ print(io, { ok: true, hub: origin, routes });
2758
+ return 0;
2759
+ }
2760
+ // `bind` and `unbind` share one POST ladder AND one request body — `{capability, crew}`,
2761
+ // because each call adds or removes exactly one `(capability, crew)` pair. Only the
2762
+ // path, the guard, and the printed shape differ.
2763
+ const endpoint = sub === 'bind' ? 'add_capability_route' : 'remove_capability_route';
2764
+ const { res } = await authedPost(io, origin, slot, cred, `/api/${endpoint}`, { capability, crew });
2765
+ if (res.status === 401) {
2766
+ // A 401 that survived `authedPost`'s one refresh-and-retry. The human slot
2767
+ // never holds an agent kind, so `assertAuthOk`'s non-agent wording applies;
2768
+ // the catch below upgrades this to exit 3.
2769
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
2770
+ }
2771
+ if (!res.ok) {
2772
+ // Surface the hub's typed `message` VERBATIM (this is how an unknown crew
2773
+ // name, an invalid capability, and a non-admin 403 all surface uniformly).
2774
+ // Never include raw body text.
2775
+ let message;
2776
+ try {
2777
+ const errBody = (await res.json());
2778
+ if (typeof errBody === 'object' && errBody !== null) {
2779
+ const m = errBody.message;
2780
+ if (typeof m === 'string' && m !== '')
2781
+ message = m;
2782
+ }
2783
+ }
2784
+ catch {
2785
+ // Non-JSON body — fall through to the generic status message.
2786
+ }
2787
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
2788
+ }
2789
+ let body;
2790
+ try {
2791
+ body = (await res.json());
2792
+ }
2793
+ catch {
2794
+ // A FIXED string — never V8's SyntaxError message, which embeds a verbatim
2795
+ // snippet of the raw body.
2796
+ throw new CliError(`${endpoint}: malformed success response — body is not valid JSON`);
2797
+ }
2798
+ if (sub === 'bind') {
2799
+ let added;
2800
+ try {
2801
+ added = asCapabilityRouteAdded(body);
2802
+ }
2803
+ catch (e) {
2804
+ throw new CliError(e.message);
2805
+ }
2806
+ // The server-echoed capability/crew, not argv: if the hub normalized either,
2807
+ // stdout tells the truth about what the hub stored (same precedent as
2808
+ // `agent new` printing the server-resolved crews). `alreadyRouted` and
2809
+ // `routedCrewCount` carry the HUB's own field names verbatim, so an operator
2810
+ // correlating stdout against the hub's audit log never has to translate.
2811
+ // `createdBy`/`createdAt` are validated but not printed — `capability list` is
2812
+ // where a row's provenance belongs.
2813
+ print(io, {
2814
+ ok: true,
2815
+ hub: origin,
2816
+ capability: added.route.capability,
2817
+ crew: added.route.crewName,
2818
+ alreadyRouted: added.alreadyRouted,
2819
+ routedCrewCount: added.routedCrewCount,
2820
+ });
2821
+ // No stderr line on `bind`: an add never displaces a crew and never parks a
2822
+ // capability, so there is no consequence to warn about.
2823
+ return 0;
2824
+ }
2825
+ // `unbind`: the guard proves the 2xx really was the remove verb's answer.
2826
+ // `removedWire` (not `removed`) so `removedWire.removed` reads unambiguously —
2827
+ // the same naming `dispatchCrew` uses for `deletedWire`/`removedWire`.
2828
+ let removedWire;
2829
+ try {
2830
+ removedWire = asCapabilityRouteRemoved(body);
2831
+ }
2832
+ catch (e) {
2833
+ throw new CliError(e.message);
2834
+ }
2835
+ // `crewId` (not a crew name): `remove_capability_route` returns no `crewName`, so
2836
+ // printing one would be an invention. It is `null` on the tolerant path where
2837
+ // the argument matched no live crew name and no row of this capability's own.
2838
+ print(io, {
2839
+ ok: true,
2840
+ hub: origin,
2841
+ capability: removedWire.capability,
2842
+ crewId: removedWire.crewId,
2843
+ removed: removedWire.removed,
2844
+ remainingCrewIds: removedWire.remainingCrewIds,
2845
+ });
2846
+ // stderr only, so `| jq` on stdout is unaffected — mirroring `crew rm` /
2847
+ // `crew member rm`, which narrate their tolerant-false case and their
2848
+ // notable side effect the same way.
2849
+ if (!removedWire.removed) {
2850
+ io.err(`${removedWire.capability} was not bound to '${crew}' — nothing was removed`);
2851
+ }
2852
+ else if (removedWire.remainingCrewIds.length === 0) {
2853
+ io.err(`${removedWire.capability}: no live routes remain — runs waiting on this capability are parked until it is bound again`);
2854
+ }
2855
+ return 0;
2856
+ }
2857
+ catch (e) {
2858
+ // A refresh-failure-family error (the human oauth is irrecoverable, or a 401
2859
+ // survived the refresh-and-retry) is exit 3 with the login remedy; every
2860
+ // other CliError propagates as-is — a network timeout stays exit 1, because a
2861
+ // flaky network is not an irrecoverable credential.
2862
+ if (e instanceof CliError && /run `owenloop login`/.test(e.message)) {
2863
+ throw new CliError(`${e.message} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2864
+ }
2865
+ throw e;
2866
+ }
2867
+ }
2868
+ /**
2869
+ * `owenloop crew list|new|rm|member add|member rm` — administer hub crews.
2870
+ * Modeled directly on `dispatchCapability`: same validate-before-I/O discipline,
2871
+ * same helpers (`resolveAgentHub`, `readCredential`, `authedGet`/`authedPost`,
2872
+ * `assertAuthOk`), same error-wording shapes, same exit-code ladder.
2873
+ *
2874
+ * | subcommand | endpoint |
2875
+ * |--------------------|-------------------------------|
2876
+ * | `crew list` | `GET /api/crews` |
2877
+ * | `crew new` | `POST /api/create_crew` |
2878
+ * | `crew rm` | `POST /api/delete_crew` |
2879
+ * | `crew member add` | `POST /api/add_crew_member` |
2880
+ * | `crew member rm` | `POST /api/remove_crew_member`|
2881
+ *
2882
+ * All five use the **human** credential slot — `manage_crews` is absent from
2883
+ * the hub's agent scope table, so an agent token is refused on every one of
2884
+ * these routes regardless of scope; the CLI does not carry an agent-token path
2885
+ * for this family, unlike `binding`'s sibling commands.
2886
+ *
2887
+ * **The tolerant / absent-field semantics — the heart of this command.**
2888
+ * `delete_crew` on an unknown crew id, and `remove_crew_member` on a principal
2889
+ * that was never a member, are both ordinary 200 successes (`deleted: false` /
2890
+ * `removed: false`), never 404s — printed and echoed to stderr honestly rather
2891
+ * than invented as an error. `delete_crew`'s optional transfer fields
2892
+ * (`membersRemoved`, `orphanCrewId`, `orphanCrewName`, `stampsTransferred`,
2893
+ * `runsTransferred`, `runningRunsTransferred`) are on stdout IF AND ONLY IF the
2894
+ * wire carried them — never defaulted to `0`/`null`/`[]`, because their
2895
+ * absence is the hub's way of saying nothing moved. When a transfer did
2896
+ * happen, `crew rm` also writes a human-facing stderr summary naming the
2897
+ * orphan crew, because an operator who never sees that line will not go
2898
+ * looking for their moved work.
2899
+ *
2900
+ * Agrees with `capability unbind`: `crew rm` and `crew member rm` print their tolerant
2901
+ * booleans (`deleted`, `removed`) on stdout and narrate the tolerant-false case
2902
+ * on stderr — the same shape `capability unbind` uses for its own `removed` and
2903
+ * `remainingCrewIds`. One vocabulary across both families.
2904
+ *
2905
+ * Exit codes: 0 ok; 1 usage error, hub refusal (400/403), or malformed
2906
+ * response; 2 the hub is unresolvable; 3 the human credential is absent or
2907
+ * irrecoverable (remedy names `owenloop login --hub <origin>`).
2908
+ */
2909
+ async function dispatchCrew(io, args) {
2910
+ const USAGE_FORMS = 'usage: owenloop crew list [--hub <url>] | ' +
2911
+ 'owenloop crew new <name> --kind personal|shared [--owner <memberId>] [--hub <url>] | ' +
2912
+ 'owenloop crew rm <crewId> [--hub <url>] | ' +
2913
+ 'owenloop crew member add <crewId> <principalKind> <principalId> [--hub <url>] | ' +
2914
+ 'owenloop crew member rm <crewId> <principalId> [--hub <url>]';
2915
+ // --- validation: everything below runs BEFORE any I/O, so a usage error on a
2916
+ // multi-hub machine reports the usage problem (exit 1), not exit 2.
2917
+ const sub = args.positionals[1];
2918
+ if (sub !== 'list' && sub !== 'new' && sub !== 'rm' && sub !== 'member') {
2919
+ throw new CliError(`unknown crew subcommand '${sub ?? ''}' — ${USAGE_FORMS}`);
2920
+ }
2921
+ let memberSub;
2922
+ let name = '';
2923
+ let crewId = '';
2924
+ let principalKind = '';
2925
+ let principalId = '';
2926
+ let kind = '';
2927
+ let owner;
2928
+ if (sub === 'new') {
2929
+ const raw = args.positionals[2];
2930
+ if (raw === undefined || raw === '') {
2931
+ throw new CliError(`missing required argument: <name> (${USAGE_FORMS})`);
2932
+ }
2933
+ name = raw;
2934
+ const rawKind = last(args, 'kind');
2935
+ if (rawKind === undefined || rawKind === '') {
2936
+ throw new CliError(`missing required option: --kind personal|shared (${USAGE_FORMS})`);
2937
+ }
2938
+ kind = rawKind;
2939
+ const rawOwner = last(args, 'owner');
2940
+ if (rawOwner !== undefined) {
2941
+ if (rawOwner === '') {
2942
+ throw new CliError(`--owner requires a member id (${USAGE_FORMS})`);
2943
+ }
2944
+ owner = rawOwner;
2945
+ }
2946
+ }
2947
+ else if (sub === 'rm') {
2948
+ const raw = args.positionals[2];
2949
+ if (raw === undefined || raw === '') {
2950
+ throw new CliError(`missing required argument: <crewId> (${USAGE_FORMS})`);
2951
+ }
2952
+ crewId = raw;
2953
+ }
2954
+ else if (sub === 'member') {
2955
+ const msub = args.positionals[2];
2956
+ if (msub !== 'add' && msub !== 'rm') {
2957
+ throw new CliError(`unknown crew member subcommand '${msub ?? ''}' — ${USAGE_FORMS}`);
2958
+ }
2959
+ memberSub = msub;
2960
+ const rawCrewId = args.positionals[3];
2961
+ if (rawCrewId === undefined || rawCrewId === '') {
2962
+ throw new CliError(`missing required argument: <crewId> (${USAGE_FORMS})`);
2963
+ }
2964
+ crewId = rawCrewId;
2965
+ if (memberSub === 'add') {
2966
+ const rawKind = args.positionals[4];
2967
+ if (rawKind === undefined || rawKind === '') {
2968
+ throw new CliError(`missing required argument: <principalKind> (${USAGE_FORMS})`);
2969
+ }
2970
+ principalKind = rawKind;
2971
+ const rawId = args.positionals[5];
2972
+ if (rawId === undefined || rawId === '') {
2973
+ throw new CliError(`missing required argument: <principalId> (${USAGE_FORMS})`);
2974
+ }
2975
+ principalId = rawId;
2976
+ }
2977
+ else {
2978
+ const rawId = args.positionals[4];
2979
+ if (rawId === undefined || rawId === '') {
2980
+ throw new CliError(`missing required argument: <principalId> (${USAGE_FORMS})`);
2981
+ }
2982
+ principalId = rawId;
2983
+ }
2984
+ }
2985
+ const origin = resolveAgentHub(io, args, 'manage crews on');
2986
+ const slot = { principal: 'human' };
2987
+ // The human bearer for the resolved origin. Absent → exit 3 with the same
2988
+ // remedy wording `binding`/`agent new` use.
2989
+ const cred = readCredential(io, origin, slot);
2990
+ if (cred === null) {
2991
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2992
+ }
2993
+ try {
2994
+ if (sub === 'list') {
2995
+ const { res, cred: used } = await authedGet(io, origin, slot, cred, '/api/crews');
2996
+ // `assertAuthOk`'s generic wording (frozen contract, mirrors `binding
2997
+ // list`); message passthrough is a POST-path behavior below.
2998
+ assertAuthOk(res, used, origin);
2999
+ let body;
3000
+ try {
3001
+ body = (await res.json());
3002
+ }
3003
+ catch {
3004
+ throw new CliError('crews: malformed response — body is not valid JSON');
3005
+ }
3006
+ let crews;
3007
+ try {
3008
+ crews = asCrews(body);
3009
+ }
3010
+ catch (e) {
3011
+ throw new CliError(e.message);
3012
+ }
3013
+ print(io, { ok: true, hub: origin, crews });
3014
+ return 0;
3015
+ }
3016
+ // `new`, `rm`, `member add`, and `member rm` share one POST ladder; only the
3017
+ // path, the request body, the guard, and the printed shape differ.
3018
+ let endpoint;
3019
+ let reqBody;
3020
+ if (sub === 'new') {
3021
+ endpoint = 'create_crew';
3022
+ reqBody = { name, kind, ...(owner !== undefined ? { ownerMemberId: owner } : {}) };
3023
+ }
3024
+ else if (sub === 'rm') {
3025
+ endpoint = 'delete_crew';
3026
+ reqBody = { crewId };
3027
+ }
3028
+ else if (memberSub === 'add') {
3029
+ endpoint = 'add_crew_member';
3030
+ reqBody = { crewId, principalKind, principalId };
3031
+ }
3032
+ else {
3033
+ endpoint = 'remove_crew_member';
3034
+ reqBody = { crewId, principalId };
3035
+ }
3036
+ const { res } = await authedPost(io, origin, slot, cred, `/api/${endpoint}`, reqBody);
3037
+ if (res.status === 401) {
3038
+ // A 401 that survived `authedPost`'s one refresh-and-retry. The human slot
3039
+ // never holds an agent kind, so this generic wording applies; the catch
3040
+ // below upgrades this to exit 3.
3041
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
3042
+ }
3043
+ if (!res.ok) {
3044
+ // Surface the hub's typed `message` VERBATIM (an unknown crew id on
3045
+ // member add/rm, a non-admin 403, an active-workflow delete refusal, an
3046
+ // unvalidated --kind value all surface uniformly). Never include raw
3047
+ // body text.
3048
+ let message;
3049
+ try {
3050
+ const errBody = (await res.json());
3051
+ if (typeof errBody === 'object' && errBody !== null) {
3052
+ const m = errBody.message;
3053
+ if (typeof m === 'string' && m !== '')
3054
+ message = m;
3055
+ }
3056
+ }
3057
+ catch {
3058
+ // Non-JSON body — fall through to the generic status message.
3059
+ }
3060
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
3061
+ }
3062
+ let body;
3063
+ try {
3064
+ body = (await res.json());
3065
+ }
3066
+ catch {
3067
+ // A FIXED string — never V8's SyntaxError message, which embeds a
3068
+ // verbatim snippet of the raw body.
3069
+ throw new CliError(`${endpoint}: malformed success response — body is not valid JSON`);
3070
+ }
3071
+ if (sub === 'new') {
3072
+ let created;
3073
+ try {
3074
+ created = asCrewCreated(body);
3075
+ }
3076
+ catch (e) {
3077
+ throw new CliError(e.message);
3078
+ }
3079
+ print(io, {
3080
+ ok: true,
3081
+ hub: origin,
3082
+ crewId: created.id,
3083
+ name: created.name,
3084
+ kind: created.kind,
3085
+ ownerMemberId: created.ownerMemberId,
3086
+ });
3087
+ return 0;
3088
+ }
3089
+ if (sub === 'rm') {
3090
+ let deletedWire;
3091
+ try {
3092
+ deletedWire = asCrewDeleted(body);
3093
+ }
3094
+ catch (e) {
3095
+ throw new CliError(e.message);
3096
+ }
3097
+ // `deleted` (and every transfer field the wire carried) is printed, never
3098
+ // hidden — the same tolerant-boolean shape `capability unbind` prints. See the
3099
+ // function doc-comment.
3100
+ print(io, { ok: true, hub: origin, ...deletedWire });
3101
+ if (!deletedWire.deleted) {
3102
+ io.err(`no crew '${deletedWire.crewId}' to delete — nothing was removed`);
3103
+ }
3104
+ else if (deletedWire.orphanCrewName !== undefined) {
3105
+ const runs = deletedWire.runsTransferred?.length ?? 0;
3106
+ const stamps = deletedWire.stampsTransferred ?? 0;
3107
+ const running = deletedWire.runningRunsTransferred;
3108
+ const runningClause = running !== undefined && running.length > 0 ? ` (${running.length} still running)` : '';
3109
+ io.err(`crew '${deletedWire.crewId}' deleted — ${stamps} stamp(s) from ${runs} run(s)${runningClause} moved to '${deletedWire.orphanCrewName}' (${deletedWire.orphanCrewId})`);
3110
+ }
3111
+ return 0;
3112
+ }
3113
+ if (memberSub === 'add') {
3114
+ let added;
3115
+ try {
3116
+ added = asCrewMemberAdded(body);
3117
+ }
3118
+ catch (e) {
3119
+ throw new CliError(e.message);
3120
+ }
3121
+ // The argv crewId, not a wire value: `CrewMemberWire` deliberately does
3122
+ // not narrow a `crewId` field (it is reused for `crews[].members[]`,
3123
+ // where a per-member crewId would be redundant), so the request's own
3124
+ // crewId is the only one available to print.
3125
+ print(io, { ok: true, hub: origin, crewId, principalKind: added.principalKind, principalId: added.principalId });
3126
+ return 0;
3127
+ }
3128
+ // `member rm`
3129
+ let removedWire;
3130
+ try {
3131
+ removedWire = asCrewMemberRemoved(body);
3132
+ }
3133
+ catch (e) {
3134
+ throw new CliError(e.message);
3135
+ }
3136
+ print(io, {
3137
+ ok: true,
3138
+ hub: origin,
3139
+ crewId: removedWire.crewId,
3140
+ principalId: removedWire.principalId,
3141
+ removed: removedWire.removed,
3142
+ });
3143
+ if (!removedWire.removed) {
3144
+ io.err(`${removedWire.principalId} was not a member of crew '${removedWire.crewId}' — nothing was removed`);
3145
+ }
3146
+ return 0;
3147
+ }
3148
+ catch (e) {
3149
+ // A refresh-failure-family error (the human oauth is irrecoverable, or a 401
3150
+ // survived the refresh-and-retry) is exit 3 with the login remedy; every
3151
+ // other CliError propagates as-is — a network timeout stays exit 1, because a
3152
+ // flaky network is not an irrecoverable credential.
3153
+ if (e instanceof CliError && /run `owenloop login`/.test(e.message)) {
3154
+ throw new CliError(`${e.message} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
3155
+ }
3156
+ throw e;
3157
+ }
3158
+ }
2547
3159
  /**
2548
3160
  * The plugin check is rendered but NON-FATAL while the marketplace is not yet
2549
3161
  * fetchably published (the brief's open question): `doctor` shows ✓/✗ but the
@@ -2731,8 +3343,8 @@ function requirePrompt(io) {
2731
3343
  return io.prompt;
2732
3344
  if (process.stdin.isTTY)
2733
3345
  return defaultPrompt;
2734
- throw new CliError('setup needs to ask which agent to use, but stdin is not interactive — pass ' +
2735
- '--new-agent <name> to create a new agent, or --replace-agent <name> to replace an existing one');
3346
+ throw new CliError('setup needs to ask which Scoped Identity to use, but stdin is not interactive — pass ' +
3347
+ '--new-agent <name> to create a new Scoped Identity, or --replace-agent <name> to replace an existing one');
2736
3348
  }
2737
3349
  /**
2738
3350
  * Prompt for an agent name (Flow A). Offers `sanitizeAgentName(hostname())` as a
@@ -2742,7 +3354,7 @@ function requirePrompt(io) {
2742
3354
  async function promptAgentName(io) {
2743
3355
  const prompt = requirePrompt(io);
2744
3356
  const prefill = sanitizeAgentName(hostname());
2745
- const question = prefill ? `Name this agent [${prefill}]: ` : 'Name this agent: ';
3357
+ const question = prefill ? `Name this Scoped Identity [${prefill}]: ` : 'Name this Scoped Identity: ';
2746
3358
  for (let attempt = 0; attempt < 2; attempt++) {
2747
3359
  const raw = (await prompt(question)).trim();
2748
3360
  const answer = raw === '' ? prefill : raw;
@@ -2762,10 +3374,11 @@ async function promptAgentName(io) {
2762
3374
  }
2763
3375
  /**
2764
3376
  * Render the succession question (Flow B) and read a choice. The framing
2765
- * sentences are VERBATIM from the model doc; the radio glyphs become numbered
3377
+ * sentences are adapted from the model doc (§7 Flow B), restated in the settled
3378
+ * vocabulary; the radio glyphs become numbered
2766
3379
  * terminal choices (the honest line-input adaptation). `[1]` = new installation;
2767
3380
  * `[k]` = replace the (k-2)th non-disabled identity. Each Replace line shows the
2768
- * name, `last active <relative>`, and pools. Invalid input re-prompts once, then
3381
+ * name, `last active <relative>`, and crews. Invalid input re-prompts once, then
2769
3382
  * a `CliError`.
2770
3383
  */
2771
3384
  async function promptSuccession(io, identities) {
@@ -2775,16 +3388,16 @@ async function promptSuccession(io, identities) {
2775
3388
  const lines = [
2776
3389
  'Is this a new installation, or does it replace an existing one?',
2777
3390
  '',
2778
- ' [1] New installation → create a new agent',
3391
+ ' [1] New installation → create a new Scoped Identity',
2779
3392
  ];
2780
3393
  candidates.forEach((id, i) => {
2781
3394
  const active = lastActiveMs(id);
2782
3395
  const rel = formatLastActive(active === null ? null : now - active);
2783
- const pools = id.pools.length ? id.pools.join(', ') : '(none)';
2784
- lines.push(` [${i + 2}] Replace: ${id.name} last active ${rel} · pools: ${pools}`);
3396
+ const crews = id.crews.length ? id.crews.join(', ') : '(none)';
3397
+ lines.push(` [${i + 2}] Replace: ${id.name} last active ${rel} · crews: ${crews}`);
2785
3398
  });
2786
3399
  lines.push('');
2787
- lines.push('⚠ "Replace" revokes that agent\'s current credential. If it is still');
3400
+ lines.push('⚠ "Replace" revokes that Scoped Identity\'s current credential. If it is still');
2788
3401
  lines.push(' running somewhere, it will be disconnected there.');
2789
3402
  lines.push('');
2790
3403
  const max = candidates.length + 1;
@@ -2832,8 +3445,10 @@ function installPluginStep(io, state) {
2832
3445
  * only through its probe failing.
2833
3446
  *
2834
3447
  * Flags: `--hub <url>`; mutually-exclusive `--new-agent <name>` / `--replace-agent
2835
- * <name>` (bypass the interactive agent branches); `--pools <a,b>` (mint only —
2836
- * a usage error with `--replace-agent`, which preserves pools).
3448
+ * <name>` (bypass the interactive agent branches); `--crews <a,b>` (mint only —
3449
+ * a usage error with `--replace-agent`, which preserves crews); `--scopes <a,b>`
3450
+ * (mint only — the minted token's scopes, default `work`; a usage error with
3451
+ * `--replace-agent`, which preserves scopes).
2837
3452
  *
2838
3453
  * Exit: 0 when every step ended skipped/done/noted AND doctor's core (non-plugin)
2839
3454
  * checks pass; 1 otherwise. Any hard failure throws (mapped to an exit code by
@@ -2846,18 +3461,33 @@ async function dispatchSetup(io, args) {
2846
3461
  if (newAgent !== undefined && replaceAgent !== undefined) {
2847
3462
  throw new CliError('pass at most one of --new-agent or --replace-agent, not both');
2848
3463
  }
2849
- const poolsRaw = last(args, 'pools');
2850
- let pools;
2851
- if (poolsRaw !== undefined) {
2852
- pools = poolsRaw
3464
+ const crewsRaw = last(args, 'crews');
3465
+ let crews;
3466
+ if (crewsRaw !== undefined) {
3467
+ crews = crewsRaw
2853
3468
  .split(',')
2854
3469
  .map((p) => p.trim())
2855
3470
  .filter((p) => p !== '');
2856
- if (pools.length === 0)
2857
- throw new CliError('--pools requires at least one pool name');
3471
+ if (crews.length === 0)
3472
+ throw new CliError('--crews requires at least one crew name');
3473
+ }
3474
+ if (replaceAgent !== undefined && crews !== undefined) {
3475
+ throw new CliError("--crews cannot be combined with --replace-agent — re-keying preserves the agent's crews (manage crews in the console)");
3476
+ }
3477
+ // --scopes: same shape as --crews. Absent → undefined (mint inherits the
3478
+ // `?? ['work']` default). Present but empty → usage error, before any I/O.
3479
+ const scopesRaw = last(args, 'scopes');
3480
+ let scopes;
3481
+ if (scopesRaw !== undefined) {
3482
+ scopes = scopesRaw
3483
+ .split(',')
3484
+ .map((s) => s.trim())
3485
+ .filter((s) => s !== '');
3486
+ if (scopes.length === 0)
3487
+ throw new CliError('--scopes requires at least one scope name');
2858
3488
  }
2859
- if (replaceAgent !== undefined && pools !== undefined) {
2860
- throw new CliError("--pools cannot be combined with --replace-agent — re-keying preserves the agent's pools (manage pools in the console)");
3489
+ if (replaceAgent !== undefined && scopes !== undefined) {
3490
+ throw new CliError("--scopes cannot be combined with --replace-agent — re-keying preserves the agent's scopes (mint a new agent to change scopes)");
2861
3491
  }
2862
3492
  for (const [flagName, val] of [
2863
3493
  ['--new-agent', newAgent],
@@ -2887,14 +3517,14 @@ async function dispatchSetup(io, args) {
2887
3517
  // --- [1/6] inspect: zero writes, best-effort probes ---
2888
3518
  io.err('[1/6] inspect');
2889
3519
  io.err(` human credential: ${readCredential(io, origin, { principal: 'human' }) !== null ? 'present' : 'none — will log in'}`);
2890
- const inspectSettingsPath = owenworkSettingsPath(io.env);
3520
+ const inspectSettingsPath = owenloopSettingsPath(io.env);
2891
3521
  let settingsNote;
2892
3522
  if (!existsSync(inspectSettingsPath)) {
2893
3523
  settingsNote = 'missing — will write';
2894
3524
  }
2895
3525
  else {
2896
3526
  try {
2897
- const raw = readOwenworkSettingsRaw(inspectSettingsPath);
3527
+ const raw = readOwenloopSettingsRaw(inspectSettingsPath);
2898
3528
  const found = raw && typeof raw.hubOrigin === 'string' ? raw.hubOrigin : undefined;
2899
3529
  settingsNote = found === origin ? `hubOrigin already ${origin}` : `hubOrigin ${found ?? '(unset)'} — will update`;
2900
3530
  }
@@ -2902,7 +3532,7 @@ async function dispatchSetup(io, args) {
2902
3532
  settingsNote = 'present but unreadable — step 4 will error if still corrupt';
2903
3533
  }
2904
3534
  }
2905
- io.err(` owenwork settings: ${settingsNote}`);
3535
+ io.err(` owenloop settings: ${settingsNote}`);
2906
3536
  io.err(` claude on PATH: ${commandOnPath(io.env, 'claude') ? 'yes' : 'no'}`);
2907
3537
  const inspectAccts = enumerateAgentAccounts(io, origin);
2908
3538
  io.err(inspectAccts === null
@@ -2942,7 +3572,7 @@ async function dispatchSetup(io, args) {
2942
3572
  io.err('[3/6] agent');
2943
3573
  const { res: idRes } = await authedGet(io, origin, { principal: 'human' }, humanCred, '/api/agent_identities');
2944
3574
  if (idRes.status === 403) {
2945
- throw new CliError('setup needs an admin credential to manage agents (hub returned 403)');
3575
+ throw new CliError('setup needs an admin credential to manage Scoped Identities (hub returned 403)');
2946
3576
  }
2947
3577
  assertAuthOk(idRes, humanCred, origin);
2948
3578
  const identities = asAgentIdentities(await idRes.json());
@@ -2952,8 +3582,8 @@ async function dispatchSetup(io, args) {
2952
3582
  let agentAccount;
2953
3583
  if (probe.verified !== null) {
2954
3584
  agentAccount = probe.verified.name;
2955
- const poolsStr = probe.verified.identity ? ` (pools: ${probe.verified.identity.pools.join(', ') || 'none'})` : '';
2956
- io.err(`✓ agent: ${agentAccount}${poolsStr}`);
3585
+ const crewsStr = probe.verified.identity ? ` (crews: ${probe.verified.identity.crews.join(', ') || 'none'})` : '';
3586
+ io.err(`✓ agent: ${agentAccount}${crewsStr}`);
2957
3587
  steps.push({ step: 'agent', action: 'skipped', detail: `agent:${agentAccount} verified` });
2958
3588
  }
2959
3589
  else {
@@ -2965,7 +3595,7 @@ async function dispatchSetup(io, args) {
2965
3595
  else if (replaceAgent !== undefined) {
2966
3596
  const target = identities.find((i) => i.name === replaceAgent);
2967
3597
  if (target === undefined) {
2968
- throw new CliError(`no agent named '${replaceAgent}' on ${origin} — available: ${identities.map((i) => i.name).join(', ') || '(none)'}`);
3598
+ throw new CliError(`no Scoped Identity named '${replaceAgent}' on ${origin} — available: ${identities.map((i) => i.name).join(', ') || '(none)'}`);
2969
3599
  }
2970
3600
  action = { mode: 'rekey', agentId: target.id, name: replaceAgent };
2971
3601
  }
@@ -2982,9 +3612,9 @@ async function dispatchSetup(io, args) {
2982
3612
  : { mode: 'rekey', agentId: choice.identity.id, name: choice.identity.name };
2983
3613
  }
2984
3614
  if (action.mode === 'mint') {
2985
- const result = await mintAgentCredential(io, origin, { principal: 'human' }, humanCred, { name: action.name, pools });
3615
+ const result = await mintAgentCredential(io, origin, { principal: 'human' }, humanCred, { name: action.name, crews, scopes });
2986
3616
  agentAccount = action.name;
2987
- io.err(`✓ agent: minted agent:${agentAccount} (pools: ${result.pools.join(', ') || 'none'})`);
3617
+ io.err(`✓ agent: minted agent:${agentAccount} (crews: ${result.crews.join(', ') || 'none'}; scopes: ${result.scopes.join(', ')})`);
2988
3618
  steps.push({ step: 'agent', action: 'done', detail: `minted agent:${agentAccount}` });
2989
3619
  }
2990
3620
  else {
@@ -2994,22 +3624,22 @@ async function dispatchSetup(io, args) {
2994
3624
  steps.push({ step: 'agent', action: 'done', detail: `re-keyed agent:${agentAccount}` });
2995
3625
  }
2996
3626
  }
2997
- // --- [4/6] owenwork settings ---
2998
- io.err('[4/6] owenwork settings');
2999
- const settingsPath = owenworkSettingsPath(io.env);
3000
- const existingSettings = readOwenworkSettingsRaw(settingsPath); // corrupt file → hard CliError (never clobber)
3627
+ // --- [4/6] owenloop settings ---
3628
+ io.err('[4/6] owenloop settings');
3629
+ const settingsPath = owenloopSettingsPath(io.env);
3630
+ const existingSettings = readOwenloopSettingsRaw(settingsPath); // corrupt file → hard CliError (never clobber)
3001
3631
  const currentHub = existingSettings && typeof existingSettings.hubOrigin === 'string' ? existingSettings.hubOrigin : undefined;
3002
3632
  if (existingSettings !== null && currentHub === origin) {
3003
- io.err(`✓ owenwork settings: hubOrigin already ${origin}`);
3004
- steps.push({ step: 'owenwork settings', action: 'skipped', detail: settingsPath });
3633
+ io.err(`✓ owenloop settings: hubOrigin already ${origin}`);
3634
+ steps.push({ step: 'owenloop settings', action: 'skipped', detail: settingsPath });
3005
3635
  }
3006
3636
  else {
3007
- const written = writeOwenworkHubOrigin(io.env, origin);
3008
- io.err(`✓ owenwork settings: hubOrigin ${written.previous ?? '(unset)'} → ${origin}`);
3009
- steps.push({ step: 'owenwork settings', action: 'done', detail: `${written.previous ?? '(unset)'} → ${origin}` });
3637
+ const written = writeOwenloopHubOrigin(io.env, origin);
3638
+ io.err(`✓ owenloop settings: hubOrigin ${written.previous ?? '(unset)'} → ${origin}`);
3639
+ steps.push({ step: 'owenloop settings', action: 'done', detail: `${written.previous ?? '(unset)'} → ${origin}` });
3010
3640
  }
3011
3641
  if (agentAccount !== 'default') {
3012
- io.err(`non-default agent account — run owenwork with OWENWORK_ACCOUNT=${agentAccount}`);
3642
+ io.err(`non-default agent account — run owenloop work with OWENLOOP_ACCOUNT=${agentAccount}`);
3013
3643
  }
3014
3644
  // --- [5/6] plugin (non-fatal) ---
3015
3645
  io.err('[5/6] plugin');
@@ -3137,13 +3767,13 @@ async function runDoctor(io, origin) {
3137
3767
  record('agent slot', true, 'present', true);
3138
3768
  if (agentProbe.verified !== null) {
3139
3769
  const va = agentProbe.verified;
3140
- const pools = va.identity
3141
- ? `pools: ${va.identity.pools.join(', ') || 'none'}`
3770
+ const crews = va.identity
3771
+ ? `crews: ${va.identity.crews.join(', ') || 'none'}`
3142
3772
  : identitiesForbidden
3143
- ? '(pools not visible — requires an admin credential)'
3144
- : '(pools unknown)';
3773
+ ? '(crews not visible — requires an admin credential)'
3774
+ : '(crews unknown)';
3145
3775
  const idPart = va.identity ? va.identity.id : va.actorId;
3146
- record('agent plane', true, `${va.name} (agent id ${idPart}) · ${pools}`, true);
3776
+ record('agent plane', true, `${va.name} (agent id ${idPart}) · ${crews}`, true);
3147
3777
  }
3148
3778
  else if (agentProbe.sawRevoked) {
3149
3779
  record('agent plane', false, 'agent token revoked or invalid — re-run owenloop setup (Replace) or Reconnect in the console', true);
@@ -3152,29 +3782,29 @@ async function runDoctor(io, origin) {
3152
3782
  record('agent plane', false, 'agent credential present but could not be verified against the hub', true);
3153
3783
  }
3154
3784
  }
3155
- // 5. owenwork settings
3156
- const settingsPath = owenworkSettingsPath(io.env);
3785
+ // 5. owenloop settings
3786
+ const settingsPath = owenloopSettingsPath(io.env);
3157
3787
  let settingsRaw = null;
3158
3788
  let settingsError = null;
3159
3789
  try {
3160
- settingsRaw = readOwenworkSettingsRaw(settingsPath);
3790
+ settingsRaw = readOwenloopSettingsRaw(settingsPath);
3161
3791
  }
3162
3792
  catch (e) {
3163
3793
  settingsError = e instanceof Error ? e.message : String(e);
3164
3794
  }
3165
3795
  if (settingsError !== null) {
3166
- record('owenwork settings', false, settingsError, true);
3796
+ record('owenloop settings', false, settingsError, true);
3167
3797
  }
3168
3798
  else if (settingsRaw === null) {
3169
- record('owenwork settings', false, `missing (${settingsPath})`, true);
3799
+ record('owenloop settings', false, `missing (${settingsPath})`, true);
3170
3800
  }
3171
3801
  else {
3172
3802
  const found = typeof settingsRaw.hubOrigin === 'string' ? settingsRaw.hubOrigin : undefined;
3173
3803
  if (found !== origin) {
3174
- record('owenwork settings', false, `hubOrigin is ${found ?? '(unset)'}, expected ${origin}`, true);
3804
+ record('owenloop settings', false, `hubOrigin is ${found ?? '(unset)'}, expected ${origin}`, true);
3175
3805
  }
3176
3806
  else {
3177
- record('owenwork settings', true, settingsPath, true);
3807
+ record('owenloop settings', true, settingsPath, true);
3178
3808
  }
3179
3809
  }
3180
3810
  // 6. plugin (rendered; non-core while PLUGIN_CHECK_FATAL is false)
@@ -3198,8 +3828,26 @@ async function runDoctor(io, origin) {
3198
3828
  * the async path, so every existing command and test keeps working exactly as
3199
3829
  * before.
3200
3830
  */
3201
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push', 'agent', 'setup', 'doctor', 'mcp']);
3831
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push', 'agent', 'capability', 'crew', 'setup', 'doctor', 'mcp', 'shift']);
3202
3832
  export async function mainAsync(argv, io = defaultIO()) {
3833
+ // Delegate execution-side and shift argv tails before root parsing. Their
3834
+ // roles own their option grammars, including repeated/value forms that the
3835
+ // engine parser must not consume. These dynamic imports are cold-start
3836
+ // boundaries: ordinary root commands never evaluate execution adapters.
3837
+ if (argv[0] === 'work' || argv[0] === 'shift') {
3838
+ try {
3839
+ if (argv[0] === 'work') {
3840
+ const { mainAsync: runWork } = await import("../packages/work/src/main.js");
3841
+ return await runWork(argv.slice(1));
3842
+ }
3843
+ const { run: runShift } = await import("../packages/work/src/roles/shift.js");
3844
+ return await runShift(argv.slice(1));
3845
+ }
3846
+ catch (e) {
3847
+ io.err(`error: ${e.message}`);
3848
+ return 1;
3849
+ }
3850
+ }
3203
3851
  const args = parseArgs(argv);
3204
3852
  const command = args.positionals[0];
3205
3853
  if (command === undefined || !ASYNC_COMMANDS.has(command)) {
@@ -3222,6 +3870,10 @@ export async function mainAsync(argv, io = defaultIO()) {
3222
3870
  return await dispatchPush(io, args);
3223
3871
  case 'agent':
3224
3872
  return await dispatchAgent(io, args);
3873
+ case 'capability':
3874
+ return await dispatchCapability(io, args);
3875
+ case 'crew':
3876
+ return await dispatchCrew(io, args);
3225
3877
  case 'setup':
3226
3878
  return await dispatchSetup(io, args);
3227
3879
  case 'doctor':
@@ -3243,8 +3895,12 @@ export async function mainAsync(argv, io = defaultIO()) {
3243
3895
  return e instanceof CliError ? e.exitCode : 1;
3244
3896
  }
3245
3897
  }
3246
- /** Run the CLI. Returns a process exit code. */
3898
+ /** Run the synchronous engine CLI. The `work` and `shift` namespaces are async-only. */
3247
3899
  export function main(argv, io = defaultIO()) {
3900
+ if (argv[0] === 'work' || argv[0] === 'shift') {
3901
+ io.err(`error: owenloop ${argv[0]} requires the async entry point`);
3902
+ return 1;
3903
+ }
3248
3904
  const args = parseArgs(argv);
3249
3905
  const command = args.positionals[0];
3250
3906
  if (command === undefined) {