owenloop 0.4.0 → 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 (155) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +98 -25
  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/{add.d.ts → src/add.d.ts} +12 -40
  109. package/dist/{add.js → src/add.js} +11 -176
  110. package/dist/src/cli.d.ts +147 -0
  111. package/dist/{cli.js → src/cli.js} +1643 -353
  112. package/dist/src/credentials.d.ts +280 -0
  113. package/dist/src/credentials.js +697 -0
  114. package/dist/{defs.js → src/defs.js} +59 -36
  115. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  116. package/dist/{engine.js → src/engine.js} +29 -20
  117. package/dist/{hub.d.ts → src/hub.d.ts} +330 -2
  118. package/dist/{hub.js → src/hub.js} +531 -1
  119. package/dist/{index.d.ts → src/index.d.ts} +3 -1
  120. package/dist/{index.js → src/index.js} +2 -1
  121. package/dist/src/lock.d.ts +80 -0
  122. package/dist/src/lock.js +217 -0
  123. package/dist/src/mcp/serve.d.ts +85 -0
  124. package/dist/src/mcp/serve.js +702 -0
  125. package/dist/src/mcp/server.d.ts +132 -0
  126. package/dist/src/mcp/server.js +327 -0
  127. package/dist/{model.d.ts → src/model.d.ts} +59 -4
  128. package/dist/{model.js → src/model.js} +149 -22
  129. package/dist/{types.d.ts → src/types.d.ts} +66 -24
  130. package/dist/{util.d.ts → src/util.d.ts} +25 -0
  131. package/dist/{util.js → src/util.js} +26 -0
  132. package/dist/src/work-settings.d.ts +57 -0
  133. package/dist/src/work-settings.js +84 -0
  134. package/docs/authoring.md +102 -53
  135. package/docs/cli.md +883 -29
  136. package/docs/design.md +119 -45
  137. package/docs/embedding.md +39 -14
  138. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  139. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  140. package/examples/workflows/judges/gate-sharpness.md +39 -0
  141. package/examples/workflows/judges/security.md +34 -0
  142. package/package.json +17 -8
  143. package/dist/cli.d.ts +0 -83
  144. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  145. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  146. /package/dist/{factory.js → src/factory.js} +0 -0
  147. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  148. /package/dist/{paths.js → src/paths.js} +0 -0
  149. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  150. /package/dist/{schema.js → src/schema.js} +0 -0
  151. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  152. /package/dist/{store.js → src/store.js} +0 -0
  153. /package/dist/{types.js → src/types.js} +0 -0
  154. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  155. /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
@@ -31,19 +31,24 @@
31
31
  *
32
32
  * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
33
33
  */
34
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
35
- import { basename, dirname, join, resolve } from 'node:path';
36
- import { spawn } from 'node:child_process';
34
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
35
+ import { basename, delimiter, dirname, join, resolve } from 'node:path';
36
+ import { spawn, spawnSync } from 'node:child_process';
37
37
  import { createServer } from 'node:http';
38
+ import { createInterface } from 'node:readline/promises';
39
+ import { hostname } from 'node:os';
38
40
  import { parse as parseYaml } from 'yaml';
39
41
  import { Engine } from "./engine.js";
40
42
  import { buildGraph, buildTrace, graphToDot, graphToMermaid, modelCheck } from "./model.js";
41
43
  import { openStore } from "./store.js";
42
44
  import { buildDef, DefError, finalizeDefs, lintDef, loadDefs, loadDefsRaw, loadDefsUnfinalized, validateDef, } from "./defs.js";
43
- import { dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
45
+ import { CliError, dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
46
+ import { authHeader, deleteCredential, discoverMetadata, ensureFreshOAuth, hubFetch, hubMaxResponseBytes, mintAgentCredential, readBodyBounded, refreshOAuth, rekeyAgentCredential, storeCredential, } from "./credentials.js";
47
+ import { runMcpCommand } from "./mcp/serve.js";
44
48
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
45
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";
46
- import { asCreateWorkflowOk, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.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";
47
52
  function defaultIO() {
48
53
  return {
49
54
  cwd: process.cwd(),
@@ -53,8 +58,33 @@ function defaultIO() {
53
58
  fetch: globalThis.fetch,
54
59
  openUrl: defaultOpenUrl,
55
60
  readStdin: defaultReadStdin,
61
+ prompt: defaultPrompt,
62
+ runCommand: defaultRunCommand,
56
63
  };
57
64
  }
65
+ /**
66
+ * The default interactive prompt: a one-shot `node:readline/promises` question
67
+ * whose text and echo go to STDERR (so stdout remains the parseable JSON
68
+ * document). Closed immediately after the single read.
69
+ */
70
+ async function defaultPrompt(question) {
71
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
72
+ try {
73
+ return await rl.question(question);
74
+ }
75
+ finally {
76
+ rl.close();
77
+ }
78
+ }
79
+ /**
80
+ * The default local-command runner: `spawnSync` with `shell: false` (argv is
81
+ * passed as a vector, never interpolated into a shell) and captured, not
82
+ * inherited, stdio. Only the plugin probe uses it.
83
+ */
84
+ function defaultRunCommand(cmd, args) {
85
+ const r = spawnSync(cmd, args, { encoding: 'utf8' });
86
+ return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
87
+ }
58
88
  /** Fire-and-forget browser open — never blocks the login flow on the child. */
59
89
  function defaultOpenUrl(url) {
60
90
  const platform = process.platform;
@@ -84,6 +114,7 @@ async function defaultReadStdin() {
84
114
  */
85
115
  const BOOLEAN_FLAGS = new Set([
86
116
  'assume-provided',
117
+ 'strict-inputs',
87
118
  'shallow',
88
119
  'now',
89
120
  'all',
@@ -139,8 +170,6 @@ const flag = (args, key) => {
139
170
  const v = last(args, key);
140
171
  return v === 'true' || v === '' || (v !== undefined && v !== 'false');
141
172
  };
142
- class CliError extends Error {
143
- }
144
173
  /**
145
174
  * A 429 from the hub during a push batch (REL-10). Thrown from the batch loop
146
175
  * and handled by an explicit `instanceof` branch that halts the rest of the
@@ -351,13 +380,27 @@ Commands:
351
380
  connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
352
381
  push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)
353
382
  --as names the credential slot: human (default), agent, or agent:<account>
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)
393
+ doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)
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
354
397
  lint [<def-name>] check def(s) for wiring problems
355
- check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided]
356
- bounded reachability check (deadlocks, stuck, dead steps, declared invariants)
398
+ check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided] [--strict-inputs]
399
+ bounded reachability check (stall states, true deadlocks, stuck, dead steps, declared invariants)
357
400
  create <def> [--title t] [--provide name=json ...] [--param k=v ...]
358
401
  provide <wf> <name> [--value json] supply an owed (seedOwed) input
359
402
  adopt <wf> re-pin an instance to the current def (§28); settles new debts
360
- 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)
361
404
  reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)
362
405
  runs <wf> [--open] list this instance's runs (+ claim state for open ones)
363
406
  order <wf> <run> print the order packet issued at claim time (persisted in the claim txn)
@@ -386,6 +429,24 @@ function failureNote(failures) {
386
429
  return '';
387
430
  return `\n${failures.length} file(s) failed to load:\n - ${failures.map((f) => `${f.file}: ${f.error}`).join('\n - ')}`;
388
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
+ }
389
450
  /**
390
451
  * Options accepted on EVERY command. docs/cli.md documents `--db`/`--defs` as
391
452
  * global ("pass both on every command"), so they are allowlisted everywhere —
@@ -416,12 +477,20 @@ export const COMMAND_OPTIONS = new Map([
416
477
  ['logout', cmdOpts('hub', 'as')],
417
478
  ['connect', cmdOpts('hub', 'as')],
418
479
  ['push', cmdOpts('dry-run', 'force', 'hub', 'as')],
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')],
484
+ ['doctor', cmdOpts('hub')],
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')],
419
488
  ['lint', cmdOpts()],
420
- ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided')],
489
+ ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided', 'strict-inputs')],
421
490
  ['create', cmdOpts('title', 'provide', 'param')],
422
491
  ['provide', cmdOpts('value')],
423
492
  ['adopt', cmdOpts()],
424
- ['tick', cmdOpts('now', 'shallow', 'label')],
493
+ ['tick', cmdOpts('now', 'shallow', 'capability')],
425
494
  ['reap', cmdOpts('now')],
426
495
  ['status', cmdOpts('all')],
427
496
  ['wait', cmdOpts('until', 'timeout')],
@@ -573,19 +642,24 @@ function dispatch(command, io, args) {
573
642
  const maxDepth = numOpt(args, 'max-depth');
574
643
  const maxStates = numOpt(args, 'max-states');
575
644
  const maxCollection = numOpt(args, 'max-collection');
576
- const report = modelCheck(def, {
645
+ // `--strict-inputs` restores the pre-existing seedOwed-starts-owed behavior;
646
+ // it takes precedence over `--assume-provided` when both are passed (the
647
+ // newer explicit opt-out wins; `--assume-provided` is otherwise redundant
648
+ // with the new default and is kept only so it never errors as unknown).
649
+ const strictInputs = flag(args, 'strict-inputs');
650
+ const bounds = {
577
651
  ...(maxDepth !== undefined ? { maxDepth } : {}),
578
652
  ...(maxStates !== undefined ? { maxStates } : {}),
579
653
  ...(maxCollection !== undefined ? { maxCollectionSize: maxCollection } : {}),
580
- ...(flag(args, 'assume-provided') ? { assumeProvided: true } : {}),
581
- });
654
+ };
655
+ const report = modelCheck(def, { ...bounds, assumeProvided: !strictInputs });
582
656
  if (format === 'json') {
583
657
  print(io, report);
584
658
  }
585
659
  else {
586
660
  // text format
587
- const clean = report.deadlocks.length === 0 && report.stuck.length === 0
588
- && report.invariantViolations.length === 0;
661
+ const clean = report.deadlocks.length === 0
662
+ && report.invariantViolations.length === 0 && report.structurallyDeadSteps.length === 0;
589
663
  const status = clean && report.completable ? 'OK' : clean ? 'INCOMPLETE' : 'DEFECTS FOUND';
590
664
  io.out(`=== owenloop check: ${def.name} ===`);
591
665
  io.out(`Status: ${status}`);
@@ -596,16 +670,42 @@ function dispatch(command, io, args) {
596
670
  io.out(`SEARCH INCOMPLETE — bounds hit: ${report.boundsHit.join(', ')}`);
597
671
  io.out('Verdicts apply only within the explored region.');
598
672
  }
673
+ if (report.stallStates.length > 0) {
674
+ io.out('');
675
+ io.out(`Stall states (expected — maxAttempts / human-escalation brakes) (${report.stallStates.length}):`);
676
+ for (const s of report.stallStates) {
677
+ io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
678
+ }
679
+ }
599
680
  if (report.deadlocks.length > 0) {
600
681
  io.out('');
601
- io.out(`Deadlocks (${report.deadlocks.length}):`);
682
+ io.out(`True deadlocks (no path to completion at unlimited attempts) (${report.deadlocks.length}):`);
602
683
  for (const d of report.deadlocks) {
603
684
  io.out(` path: ${d.path.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(initial state)'}`);
604
685
  }
605
686
  }
687
+ if (strictInputs) {
688
+ const seedOwedNames = def.inputs.filter((i) => i.seedOwed).map((i) => i.name);
689
+ const initialDeadlock = report.deadlocks.some((d) => d.path.length === 0);
690
+ if (seedOwedNames.length > 0 && initialDeadlock) {
691
+ // precision: would treating seedOwed inputs as provided dissolve the
692
+ // initial-state deadlock? If so, it's caused solely by unprovided
693
+ // seedOwed inputs, not a structural defect — print a hint pointing at
694
+ // the new default. This never fires for a deadlock that survives
695
+ // providing the seeded inputs (a structural one).
696
+ const probe = modelCheck(def, { ...bounds, assumeProvided: true });
697
+ const clearedByProvide = !probe.deadlocks.some((d) => d.path.length === 0);
698
+ if (clearedByProvide) {
699
+ io.out('');
700
+ io.out(`Hint: the initial-state deadlock is caused solely by unprovided seedOwed input(s): ${seedOwedNames.join(', ')}.`);
701
+ io.out(` Seeded inputs are assumed provided by default; this appears only because --strict-inputs was passed.`);
702
+ io.out(` Re-run 'owenloop check ${def.name}' without --strict-inputs to check the real reachable space.`);
703
+ }
704
+ }
705
+ }
606
706
  if (report.stuck.length > 0) {
607
707
  io.out('');
608
- io.out(`Stuck states (${report.stuck.length}):`);
708
+ io.out(`Stuck states (brake tripped; other branches still moving — informational) (${report.stuck.length}):`);
609
709
  for (const s of report.stuck) {
610
710
  io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
611
711
  }
@@ -618,9 +718,13 @@ function dispatch(command, io, args) {
618
718
  io.out(` path: ${v.path.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(initial state)'}`);
619
719
  }
620
720
  }
621
- if (report.deadSteps.length > 0) {
721
+ if (report.structurallyDeadSteps.length > 0) {
622
722
  io.out('');
623
- io.out(`Dead steps (never fire in explored space): ${report.deadSteps.join(', ')}`);
723
+ io.out(`Structurally dead steps (can never fire — wiring defect): ${report.structurallyDeadSteps.join(', ')}`);
724
+ }
725
+ if (report.unreachedSteps.length > 0) {
726
+ io.out('');
727
+ io.out(`Unreached within bounds (raise --max-states/--max-depth): ${report.unreachedSteps.join(', ')}`);
624
728
  }
625
729
  if (report.completePath) {
626
730
  io.out('');
@@ -633,16 +737,30 @@ function dispatch(command, io, args) {
633
737
  // counterexample path was produced by real applyOutcome/settleInMemory
634
738
  // transitions (pinned to the live Engine by the conformance test). The path
635
739
  // is a genuine executable witness; bounds only cause MISSES, never
636
- // fabrications. Contrast deadlocks/stuck, where the maxCollectionSize cap can
637
- // manufacture a spurious "no moves" state — hence those require !bounded.
740
+ // fabrications. Contrast true deadlocks, where the maxCollectionSize cap can
741
+ // manufacture a spurious "no moves" state — hence that requires !bounded.
638
742
  // Do NOT remove this asymmetry; it encodes a real soundness distinction.
639
- // - definite deadlock/stuck only when EXHAUSTIVE (!bounded) → nonzero
640
- // - truncated with no invariant violations → 0
641
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
642
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
743
+ // - structurally-dead steps → ALWAYS nonzero, regardless of bounded. Unlike
744
+ // true deadlocks (found by the bounded BFS, so a tighter maxCollectionSize
745
+ // can manufacture a spurious one), structurally-dead is a STATIC canEverFire
746
+ // finding that needs no search bounds at all — it is sound and bounds-
747
+ // independent by construction (model.ts's canEverFire only ever returns
748
+ // false when certain), so it belongs with invariant violations, not with
749
+ // true deadlocks. unreachedSteps (the other dead-step bucket) must NEVER
750
+ // affect the exit code — it is purely a bounds artifact.
751
+ // - definite (true) deadlock only when EXHAUSTIVE (!bounded) → nonzero
752
+ // - stall states and stuck states are by-design brakes and NEVER affect the
753
+ // exit code — a stall state (report.stallStates) is EXPECTED (a human-
754
+ // escalation brake whose freeze, once lifted, re-arms a producer), and a
755
+ // stuck state (report.stuck) is purely informational (a brake tripped on
756
+ // one branch while the line still moves on another). Neither is a defect.
757
+ // - truncated with no invariant violations / structurally-dead steps / true
758
+ // deadlocks → 0
759
+ const hasDefiniteDefect = hasDefiniteCheckDefect(report);
643
760
  if (hasDefiniteDefect) {
644
761
  throw new CliError(`definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
645
- `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
762
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
763
+ `${report.deadlocks.length} true deadlock(s))`);
646
764
  }
647
765
  return 0;
648
766
  }
@@ -699,11 +817,11 @@ function dispatch(command, io, args) {
699
817
  tickOpts.now = now;
700
818
  if (flag(args, 'shallow'))
701
819
  tickOpts.deep = false;
702
- // A2: repeatable --label narrows the claim to steps whose labels
820
+ // A2: repeatable --capability narrows the claim to steps whose capabilities
703
821
  // intersect the caller's; absent = claim everything (today's behavior).
704
- const labels = all(args, 'label');
705
- if (labels.length > 0)
706
- tickOpts.labels = labels;
822
+ const capabilities = all(args, 'capability');
823
+ if (capabilities.length > 0)
824
+ tickOpts.capabilities = capabilities;
707
825
  print(io, engine.tick(wf, tickOpts));
708
826
  return 0;
709
827
  }
@@ -745,7 +863,7 @@ function dispatch(command, io, args) {
745
863
  return 0;
746
864
  }
747
865
  case 'wait': {
748
- // 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
749
867
  // change without burning inference on a poll loop. Plain synchronous
750
868
  // poll of the local db (cheap — one process, no LLM calls). On
751
869
  // success, prints the exact `status()` shape (same as plain
@@ -1124,57 +1242,6 @@ function statusEntry(engine, w) {
1124
1242
  // one if ever needed).
1125
1243
  const ADD_SHA_TIMEOUT_MS = 30_000;
1126
1244
  const ADD_TARBALL_TIMEOUT_MS = 300_000;
1127
- /**
1128
- * Read a `Response` body while enforcing a byte `cap`, so a hostile server can
1129
- * never make us allocate an oversized body. Rejects UP FRONT on a declared
1130
- * oversize `Content-Length`; otherwise streams the body in chunks, counting the
1131
- * bytes that actually land in memory, and cancels the stream the moment the
1132
- * running total crosses the cap — the chunk buffer never holds more than `cap`
1133
- * plus one chunk. `label` names the request in the error and is origin+path or
1134
- * `owner/repo@sha` only — never a token. Counting post-decode bytes (what lands
1135
- * in memory) is deliberate: the cap protects memory, not wire bytes.
1136
- *
1137
- * `res.body === null` (empty/no-body response) yields empty bytes, so callers
1138
- * behave exactly as they did under `arrayBuffer()`. An absent, malformed, or
1139
- * multi-valued `Content-Length` skips the header check — the counting path is
1140
- * the real guard (GitHub codeload tarballs are typically chunked, no header). A
1141
- * `TimeoutError`/`AbortError` from `read()` (the abort signal fired mid-body)
1142
- * propagates untouched, so each call site's existing timeout mapping still
1143
- * fires exactly as it did for `arrayBuffer()` rejections. `cancel()` may reject
1144
- * on an already-errored stream — swallowed; the cap `CliError` is the story.
1145
- */
1146
- async function readBodyBounded(res, cap, label) {
1147
- const declared = Number(res.headers.get('content-length'));
1148
- if (Number.isFinite(declared) && declared > cap) {
1149
- await res.body?.cancel().catch(() => { });
1150
- throw new CliError(`response body for ${label} exceeds the ${cap}-byte cap (declared Content-Length ${declared})`);
1151
- }
1152
- if (res.body === null)
1153
- return new Uint8Array(0);
1154
- const reader = res.body.getReader();
1155
- const chunks = [];
1156
- let total = 0;
1157
- for (;;) {
1158
- const { done, value } = await reader.read();
1159
- if (done)
1160
- break;
1161
- if (value === undefined)
1162
- continue;
1163
- total += value.byteLength;
1164
- chunks.push(value);
1165
- if (total > cap) {
1166
- await reader.cancel().catch(() => { });
1167
- throw new CliError(`response body for ${label} exceeds the ${cap}-byte cap`);
1168
- }
1169
- }
1170
- const out = new Uint8Array(total);
1171
- let offset = 0;
1172
- for (const chunk of chunks) {
1173
- out.set(chunk, offset);
1174
- offset += chunk.byteLength;
1175
- }
1176
- return out;
1177
- }
1178
1245
  /**
1179
1246
  * Cap on the `add` tarball download body, enforced DURING the stream by
1180
1247
  * `readBodyBounded` — defense in depth with `extractTarGz`'s own post-hoc
@@ -1407,27 +1474,26 @@ async function dispatchAdd(io, args) {
1407
1474
  reasons.push(...lintResult.errors.map((e) => `${stagedDef.name}: ${e}`));
1408
1475
  const validationErrors = validateDef(stagedDef);
1409
1476
  reasons.push(...validationErrors.map((e) => `${stagedDef.name}: ${e}`));
1410
- // Mirror the `check` command's exact "definite defect" predicate — but,
1411
- // deliberately, WITH `assumeProvided: true`. Without it, a def with any
1412
- // `seedOwed` input (the norm — see e.g. `proposal` in delivery.yaml)
1413
- // deadlocks in the very first state, because the checker models "no
1414
- // `provide` has happened yet" by default (see `seedArts` in
1415
- // src/model.ts). `owenloop check <def>` behaves the same way absent
1416
- // `--assume-provided`; verified every def under examples/workflows/
1417
- // fails plain `check` for exactly this reason. Since `add` validates a
1418
- // def that a real user will `provide` into after install (that's the
1419
- // whole point of a seedOwed input), refusing every seedOwed def here
1420
- // would make `add` unable to install almost any real workflow,
1421
- // including this project's own examples — so this checks "is it
1422
- // completable once its owed inputs are supplied," the same bar a
1423
- // careful author would clear with `check --assume-provided` before
1424
- // 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.
1425
1491
  const report = modelCheck(stagedDef, { assumeProvided: true });
1426
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
1427
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
1492
+ const hasDefiniteDefect = hasDefiniteCheckDefect(report);
1428
1493
  if (hasDefiniteDefect) {
1429
1494
  reasons.push(`${stagedDef.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
1430
- `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
1495
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
1496
+ `${report.deadlocks.length} true deadlock(s))`);
1431
1497
  }
1432
1498
  }
1433
1499
  // Strict backstop: only if the aggregate pass found nothing, run the FULL
@@ -1727,232 +1793,6 @@ function emptySlotMessage(origin, slot) {
1727
1793
  function readCredential(io, origin, slot) {
1728
1794
  return readStoredCredential(origin, { ...slot, env: io.env, keychain: io.keychain });
1729
1795
  }
1730
- /**
1731
- * Store a credential for `origin` in `slot`, in the chosen backend ONLY;
1732
- * returns which one. A failed keychain write is a hard error (REL-6), never a
1733
- * silent fall-through to the file — the escape hatch is to choose the file
1734
- * backend up front with `OWENLOOP_NO_KEYCHAIN=1`. Backend selection is the
1735
- * shared `credentialBackend` from `hub.ts`, so read and write agree on one
1736
- * choice. That shared selection now has a third variant: when an external
1737
- * credential command is configured this throws, because the command — not the
1738
- * local store — is what reads will consult.
1739
- *
1740
- * The file backend MERGES into the origin's slot map: writing `agent:ci` must
1741
- * leave a `human` credential for the same origin intact.
1742
- */
1743
- function storeCredential(io, origin, slot, cred) {
1744
- const account = credentialSlot(slot);
1745
- const backend = credentialBackend(io.env, io.keychain);
1746
- if (backend.kind === 'external') {
1747
- // Writing to a store that reads will never consult is exactly the
1748
- // "half-working setup hands back a stale key" failure the external command
1749
- // exists to prevent, so refuse loudly instead.
1750
- throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
1751
- 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
1752
- }
1753
- if (backend.kind === 'keychain') {
1754
- try {
1755
- backend.kc.set(keychainServiceFor(origin), account, JSON.stringify(cred));
1756
- }
1757
- catch (e) {
1758
- throw new CliError(`could not write the credential to the OS keychain: ${e.message}. ` +
1759
- 'Fix the keychain, or set OWENLOOP_NO_KEYCHAIN=1 to use the 0600 file store');
1760
- }
1761
- return 'keychain';
1762
- }
1763
- const path = credentialFilePath(io.env);
1764
- const file = readCredentialFile(path);
1765
- file.hubs[origin] = { ...file.hubs[origin], [account]: cred };
1766
- writeCredentialFile(path, file);
1767
- return 'file';
1768
- }
1769
- /**
1770
- * Delete the stored credential for `(origin, slot)` from BOTH backends.
1771
- * Deliberately not routed through `credentialBackend`: logout is a defensive
1772
- * dual-clear (the proposal explicitly blesses it), so a live refresh token can
1773
- * never be stranded in the store that wasn't the currently-chosen one. Returns
1774
- * whether anything was removed.
1775
- *
1776
- * Only the NAMED slot is removed. A blanket "clear every slot for this origin"
1777
- * is not implementable — the keychain cannot enumerate its accounts — and
1778
- * faking it on the file backend alone would be a half-truth, so the slot is
1779
- * always explicit (defaulting to `human`).
1780
- */
1781
- function deleteCredential(io, origin, slot) {
1782
- const account = credentialSlot(slot);
1783
- let removed = false;
1784
- const kc = resolveKeychain(io.env, io.keychain);
1785
- const service = keychainServiceFor(origin);
1786
- if (kc && kc.get(service, account) !== null) {
1787
- kc.delete(service, account);
1788
- removed = true;
1789
- }
1790
- const path = credentialFilePath(io.env);
1791
- const file = readCredentialFile(path);
1792
- const slots = file.hubs[origin];
1793
- if (slots !== undefined && slots[account] !== undefined) {
1794
- delete slots[account];
1795
- // Drop the origin key once its last slot is gone, so the file never keeps
1796
- // an empty husk that a later read would have to special-case.
1797
- if (Object.keys(slots).length === 0)
1798
- delete file.hubs[origin];
1799
- writeCredentialFile(path, file);
1800
- removed = true;
1801
- }
1802
- return removed;
1803
- }
1804
- /** The Bearer value for an authenticated request. Never logged. */
1805
- function authHeader(cred) {
1806
- return `Bearer ${cred.accessToken}`;
1807
- }
1808
- // Request deadline for EVERY hub/auth call — OAuth discovery, DCR, code
1809
- // exchange, token refresh, whoami, workflow list, and push (REL-7). These are
1810
- // all small JSON round-trips, so one budget fits them all;
1811
- // OWENLOOP_HUB_TIMEOUT_MS overrides it (a test knob, consistent with
1812
- // OWENLOOP_LOGIN_TIMEOUT_MS and the project's other OWENLOOP_* test-only knobs).
1813
- const HUB_TIMEOUT_MS = 30_000;
1814
- function hubTimeoutMs(io) {
1815
- const override = Number(io.env.OWENLOOP_HUB_TIMEOUT_MS);
1816
- return Number.isFinite(override) && override > 0 ? override : HUB_TIMEOUT_MS;
1817
- }
1818
- // Cap on any hub/auth JSON RESPONSE body (OAuth discovery, DCR, code exchange,
1819
- // token refresh, whoami, the workflow list, create_workflow). Hub responses are
1820
- // small round-trips — the largest realistic body is a workflows summary list,
1821
- // far below 8 MiB. This is a RESPONSE cap; the hub's 32MB figure (the 413 path)
1822
- // is a REQUEST cap and responses never echo YAML. OWENLOOP_HUB_MAX_RESPONSE_BYTES
1823
- // overrides it (a test-only knob, consistent with OWENLOOP_HUB_TIMEOUT_MS).
1824
- const HUB_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
1825
- function hubMaxResponseBytes(io) {
1826
- const override = Number(io.env.OWENLOOP_HUB_MAX_RESPONSE_BYTES);
1827
- return Number.isFinite(override) && override > 0 ? override : HUB_MAX_RESPONSE_BYTES;
1828
- }
1829
- /**
1830
- * `fetch` wrapper putting a deadline on every hub/auth call (REL-7). The abort
1831
- * signal is threaded into `fetch` AND the body is read (via `readBodyBounded`,
1832
- * which caps the response size — see HUB_MAX_RESPONSE_BYTES) inside the same
1833
- * try, so the deadline covers a stalled BODY read too — the exact undici
1834
- * behavior the two `add` fetches document (`AbortSignal.timeout` ties the
1835
- * signal to the body stream). The returned `Response` re-exposes the read
1836
- * body, so every call site's `res.json()` / `res.status` /
1837
- * `res.headers.get(...)` usage is byte-for-byte unchanged. A
1838
- * `TimeoutError`/`AbortError` becomes a clear `CliError` (naming the request,
1839
- * which is origin+path only — never a token); anything else is rethrown
1840
- * untouched.
1841
- *
1842
- * `redirect: 'error'` is forced on every call — after the `...init` spread, so
1843
- * no caller can override it — to close the redirect gap `resolveEndpoint`
1844
- * (SEC-4) cannot see: same-origin validation covers only the INITIAL URL, but a
1845
- * validated endpoint answering 307/308 would re-send the POST body (refresh
1846
- * token, PKCE verifier, auth code, workflow YAML) to a foreign origin — undici
1847
- * strips the Authorization header on a cross-origin redirect but RESENDS the
1848
- * body. The hub protocol has no redirects, so any 3xx is a hard, loud failure
1849
- * mapped to a `CliError` (again naming origin+path only, never a token).
1850
- */
1851
- async function hubFetch(io, url, init) {
1852
- const fetchFn = io.fetch ?? globalThis.fetch;
1853
- const ms = hubTimeoutMs(io);
1854
- const method = (init?.method ?? 'GET').toUpperCase();
1855
- try {
1856
- const res = await fetchFn(url, { ...init, signal: AbortSignal.timeout(ms), redirect: 'error' });
1857
- // 204/304 carry no body — reading one would be a spec violation.
1858
- if (res.status === 204 || res.status === 304) {
1859
- return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers });
1860
- }
1861
- const body = await readBodyBounded(res, hubMaxResponseBytes(io), `${method} ${url}`);
1862
- return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });
1863
- }
1864
- catch (e) {
1865
- const err = e;
1866
- if (err.name === 'TimeoutError' || err.name === 'AbortError') {
1867
- throw new CliError(`hub did not respond within ${ms / 1000}s (${method} ${url})`);
1868
- }
1869
- // `redirect: 'error'` makes undici reject a 3xx with a TypeError whose
1870
- // cause message is 'unexpected redirect' (verified on Node 22.22.3 and 26).
1871
- // Substring-match for slack against undici wording drift — if it ever stops
1872
- // matching, the raw TypeError still surfaces (fail-closed, just less pretty).
1873
- const cause = String(err.cause?.message ?? '');
1874
- if (err.name === 'TypeError' && cause.includes('unexpected redirect')) {
1875
- throw new CliError(`hub responded with a redirect — refusing to follow it (${method} ${url}); redirects are not part of the hub protocol`);
1876
- }
1877
- throw e;
1878
- }
1879
- }
1880
- /**
1881
- * Ensure an `oauth` credential's access token is fresh: if it expires within
1882
- * 60s, refresh once (grant_type=refresh_token) and persist the new token. No-op
1883
- * for `agent`/`oauth-pasted` credentials (they don't refresh). Returns the
1884
- * possibly-updated credential.
1885
- *
1886
- * `slot` is the slot the credential was READ from — a refreshed token must be
1887
- * written back to that same slot, never to a default one.
1888
- */
1889
- async function ensureFreshOAuth(io, origin, slot, cred, persist = true) {
1890
- if (cred.kind !== 'oauth')
1891
- return cred;
1892
- if (cred.expiresAt - nowMs() > 60_000)
1893
- return cred;
1894
- return refreshOAuth(io, origin, slot, cred, persist);
1895
- }
1896
- /**
1897
- * `persist` defaults to true — the normal case is refreshing an ALREADY
1898
- * stored, trusted credential (push/connect), where persisting immediately
1899
- * matters because refresh tokens can be single-use/rotating: losing the new
1900
- * one to a later crash would strand the user. `verifyCredential`'s login-time
1901
- * use passes `persist: false` — a not-yet-stored credential must never be
1902
- * written to disk/keychain before it is proven to work end to end (a 401 on
1903
- * the retry after this refresh still fails the overall login), matching the
1904
- * "never store an unverified token" rule enforced at every login call site.
1905
- */
1906
- async function refreshOAuth(io, origin, slot, cred, persist = true) {
1907
- const tokenEndpoint = await discoverTokenEndpoint(io, origin);
1908
- const body = new URLSearchParams({
1909
- grant_type: 'refresh_token',
1910
- refresh_token: cred.refreshToken,
1911
- client_id: cred.clientId,
1912
- });
1913
- const res = await hubFetch(io, tokenEndpoint, {
1914
- method: 'POST',
1915
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1916
- body: body.toString(),
1917
- });
1918
- if (!res.ok) {
1919
- throw new CliError('credential expired and refresh failed — run `owenloop login`');
1920
- }
1921
- const json = (await res.json());
1922
- if (typeof json.access_token !== 'string') {
1923
- throw new CliError('credential expired and refresh returned no access token — run `owenloop login`');
1924
- }
1925
- const expiresIn = typeof json.expires_in === 'number' ? json.expires_in : 3600;
1926
- const refreshed = {
1927
- kind: 'oauth',
1928
- accessToken: json.access_token,
1929
- refreshToken: typeof json.refresh_token === 'string' ? json.refresh_token : cred.refreshToken,
1930
- expiresAt: nowMs() + expiresIn * 1000,
1931
- clientId: cred.clientId,
1932
- };
1933
- // When an external command supplies credentials it owns the credential's
1934
- // whole lifecycle; owenloop must not write a refreshed token into a store it
1935
- // will never read (and `storeCredential` refuses in that mode anyway).
1936
- if (persist && externalCredentialCommand(io.env) === undefined) {
1937
- storeCredential(io, origin, slot, refreshed);
1938
- }
1939
- return refreshed;
1940
- }
1941
- async function discoverMetadata(io, origin) {
1942
- const res = await hubFetch(io, resolveEndpoint(origin, '/.well-known/oauth-authorization-server'), {
1943
- headers: { Accept: 'application/json' },
1944
- });
1945
- if (!res.ok) {
1946
- throw new CliError(`could not read OAuth metadata from ${origin} (HTTP ${res.status})`);
1947
- }
1948
- return (await res.json());
1949
- }
1950
- async function discoverTokenEndpoint(io, origin) {
1951
- const meta = await discoverMetadata(io, origin);
1952
- if (!meta.token_endpoint)
1953
- throw new CliError(`hub ${origin} advertises no token_endpoint`);
1954
- return resolveEndpoint(origin, meta.token_endpoint);
1955
- }
1956
1796
  /**
1957
1797
  * GET `path` on `origin` with a bearer credential, refreshing an expiring
1958
1798
  * oauth token first and retrying exactly once after a 401→refresh for oauth.
@@ -1974,6 +1814,38 @@ async function authedGet(io, origin, slot, cred, path, persist = true) {
1974
1814
  }
1975
1815
  return { res, cred: current };
1976
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
+ }
1977
1849
  /**
1978
1850
  * A 401 on an agent token is a hard "revoked/invalid" error; a 401 on any
1979
1851
  * other credential kind (after `authedGet`'s one refresh-and-retry) is a hard
@@ -2068,7 +1940,7 @@ async function dispatchLogin(io, args) {
2068
1940
  const slot = cred.kind === 'agent' ? { principal: 'agent', ...(asked.principal === 'agent' && asked.account !== undefined ? { account: asked.account } : {}) } : { principal: 'human' };
2069
1941
  const existed = readCredential(io, origin, slot) !== null;
2070
1942
  const { identity } = await verifyCredential(io, origin, slot, cred); // never store an unverified token
2071
- const storage = storeCredential(io, origin, slot, cred);
1943
+ const storage = await storeCredential(io, origin, slot, cred);
2072
1944
  print(io, {
2073
1945
  ok: true,
2074
1946
  hub: origin,
@@ -2088,6 +1960,35 @@ async function dispatchLogin(io, args) {
2088
1960
  if (asked.principal === 'agent') {
2089
1961
  throw new CliError(`the loopback OAuth login produces a human credential and cannot be stored in the \`${credentialSlot(asked)}\` slot — drop \`--as\`, or use \`login --with-token\` with an \`olp_\` agent token`);
2090
1962
  }
1963
+ const r = await runLoopbackOAuth(io, origin);
1964
+ print(io, {
1965
+ ok: true,
1966
+ hub: origin,
1967
+ kind: r.cred.kind,
1968
+ slot: credentialSlot({ principal: 'human' }),
1969
+ storage: r.storage,
1970
+ replaced: r.replaced,
1971
+ org: r.identity.orgName,
1972
+ orgId: r.identity.orgId,
1973
+ identity: r.identity.actor,
1974
+ ...(r.identity.email ? { email: r.identity.email } : {}),
1975
+ });
1976
+ return 0;
1977
+ }
1978
+ /**
1979
+ * The loopback OAuth auth-code + PKCE(S256) round-trip, extracted verbatim from
1980
+ * `dispatchLogin` so `setup`'s human-login gate (step 2) runs the exact same
1981
+ * flow — one implementation, one behavior. Always targets the **human** slot
1982
+ * (the only slot loopback OAuth can produce). Binds a single-use 127.0.0.1:0
1983
+ * catcher, discovers the hub's OAuth metadata, dynamically registers a client
1984
+ * for the concrete redirect URI, opens the browser, waits for the callback,
1985
+ * exchanges the code, verifies the resulting credential against `whoami`
1986
+ * (persist=false — an unverified token must never reach storage ahead of its
1987
+ * pass/fail verdict), then stores it. Returns whether a human credential was
1988
+ * already present (`replaced`), the stored credential, the verified identity,
1989
+ * and the storage backend actually used.
1990
+ */
1991
+ async function runLoopbackOAuth(io, origin) {
2091
1992
  const slot = { principal: 'human' };
2092
1993
  const existed = readCredential(io, origin, slot) !== null;
2093
1994
  // Loopback OAuth: bind the port FIRST (the service matches redirect URIs by
@@ -2122,20 +2023,8 @@ async function dispatchLogin(io, args) {
2122
2023
  verifier,
2123
2024
  });
2124
2025
  const { cred, identity } = await verifyCredential(io, origin, slot, exchanged, false); // never store an unverified token
2125
- const storage = storeCredential(io, origin, slot, cred);
2126
- print(io, {
2127
- ok: true,
2128
- hub: origin,
2129
- kind: cred.kind,
2130
- slot: credentialSlot(slot),
2131
- storage,
2132
- replaced: existed,
2133
- org: identity.orgName,
2134
- orgId: identity.orgId,
2135
- identity: identity.actor,
2136
- ...(identity.email ? { email: identity.email } : {}),
2137
- });
2138
- return 0;
2026
+ const storage = await storeCredential(io, origin, slot, cred);
2027
+ return { cred, identity, storage, replaced: existed };
2139
2028
  }
2140
2029
  finally {
2141
2030
  void server;
@@ -2275,7 +2164,7 @@ async function exchangeCode(io, origin, tokenEndpoint, p) {
2275
2164
  async function dispatchLogout(io, args) {
2276
2165
  const origin = resolveHub(io, args);
2277
2166
  const slot = resolveSlot(args);
2278
- const removed = deleteCredential(io, origin, slot);
2167
+ const removed = await deleteCredential(io, origin, slot);
2279
2168
  const slotName = credentialSlot(slot);
2280
2169
  if (!removed) {
2281
2170
  io.err(`no stored credential for ${origin} in slot \`${slotName}\` — another slot may hold one (see --as)`);
@@ -2392,11 +2281,11 @@ async function dispatchPush(io, args) {
2392
2281
  reasons.push(...lintResult.errors.map((e) => `${def.name}: ${e}`));
2393
2282
  reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
2394
2283
  const report = modelCheck(def, { assumeProvided: true });
2395
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
2396
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
2284
+ const hasDefiniteDefect = hasDefiniteCheckDefect(report);
2397
2285
  if (hasDefiniteDefect) {
2398
2286
  reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
2399
- `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
2287
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
2288
+ `${report.deadlocks.length} true deadlock(s))`);
2400
2289
  }
2401
2290
  }
2402
2291
  // Assemble the push candidates: verbatim source yaml + the server-canonical
@@ -2445,7 +2334,7 @@ async function dispatchPush(io, args) {
2445
2334
  throw new CliError(`refusing to push — ${reasons.length} problem(s) found; nothing sent:\n - ${reasons.join('\n - ')}`);
2446
2335
  }
2447
2336
  // Fetch the server's own list once — the diff source of truth. Always
2448
- // fetched, even under --force, so the new/changed labels stay accurate.
2337
+ // fetched, even under --force, so the new/changed capabilities stay accurate.
2449
2338
  const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, cred, '/api/workflows');
2450
2339
  assertAuthOk(listRes, listCred, origin);
2451
2340
  cred = listCred;
@@ -2555,6 +2444,16 @@ async function dispatchPush(io, args) {
2555
2444
  });
2556
2445
  return failed.length === 0 ? 0 : 1;
2557
2446
  }
2447
+ /**
2448
+ * `owenloop mcp` — serve the human control plane to a local MCP host over stdio.
2449
+ * A thin adapter: read the optional `--hub <url>` flag and hand `io` (which
2450
+ * satisfies the module's `McpIo`) to `runMcpCommand`, which resolves the origin,
2451
+ * builds the tool list, and pumps stdin until EOF. All the logic lives in
2452
+ * `src/mcp/serve.ts`; this stays a two-line dispatch like every other verb.
2453
+ */
2454
+ async function dispatchMcp(io, args) {
2455
+ return runMcpCommand(io, { hubFlag: last(args, 'hub') });
2456
+ }
2558
2457
  function createWorkflowRequest(io, origin, cred, yaml) {
2559
2458
  return hubFetch(io, resolveEndpoint(origin, '/api/create_workflow'), {
2560
2459
  method: 'POST',
@@ -2566,6 +2465,1361 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2566
2465
  body: JSON.stringify({ yaml }),
2567
2466
  });
2568
2467
  }
2468
+ /**
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'`.
2479
+ *
2480
+ * Deliberately NOT `resolveHub` (`--hub → OWENLOOP_HUB → DEFAULT_HUB`): silently
2481
+ * defaulting a MINT to the production hub while the user is logged into a dev hub
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`.
2487
+ *
2488
+ * `listStoredHubOrigins` is backend-aware (shared with O2's `owenloop mcp`): only
2489
+ * the FILE backend can enumerate, so it returns `null` on a keychain- or
2490
+ * external-command-backed machine — those must pass `--hub`. A file-backed store
2491
+ * returns the origins with a valid `human` slot: `[]` (log in first), exactly one
2492
+ * (used automatically), or more than one (the non-secret origin keys are listed
2493
+ * back so the user can pick).
2494
+ */
2495
+ function resolveAgentHub(io, args, purpose = 'mint on') {
2496
+ const flagVal = last(args, 'hub');
2497
+ if (flagVal !== undefined) {
2498
+ try {
2499
+ return normalizeOrigin(flagVal);
2500
+ }
2501
+ catch (e) {
2502
+ throw new CliError(e.message);
2503
+ }
2504
+ }
2505
+ const origins = listStoredHubOrigins(io.env, io.keychain);
2506
+ if (origins === null) {
2507
+ const backend = credentialBackend(io.env, io.keychain);
2508
+ const which = backend.kind === 'external' ? 'external-command' : 'keychain';
2509
+ throw new CliError(`cannot determine which hub to ${purpose} — the ${which} credential store cannot be enumerated; ` +
2510
+ 'pass --hub <origin>', { exitCode: 2 });
2511
+ }
2512
+ if (origins.length === 1)
2513
+ return origins[0];
2514
+ throw new CliError(`cannot determine which hub to ${purpose} — pass --hub <origin>, or log in to exactly one hub first ` +
2515
+ '(owenloop login --hub <origin>)' +
2516
+ (origins.length > 1 ? `; stored hubs: ${origins.join(', ')}` : ''), { exitCode: 2 });
2517
+ }
2518
+ /**
2519
+ * `owenloop agent new <name>` — mint a new Scoped Identity on the hub and store
2520
+ * its `olp_` token in slot `agent:<name>`.
2521
+ *
2522
+ * **Secret hygiene (identity model §6, "rule of gates"):** the minted token goes
2523
+ * process→store ONLY — it never appears on stdout, stderr, in an error, or in a
2524
+ * log. `mintAgentCredential` (credentials.ts) owns the token end to end and
2525
+ * returns none of it; the confirmation printed here is built from an explicit
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.
2533
+ *
2534
+ * Ordering is load-bearing (PR #69 lesson, carried by `mintAgentCredential`): the
2535
+ * client-side name validation and the external-command refusal both run BEFORE
2536
+ * any network call, so a refusal that would make the credential unstorable never
2537
+ * mints a server-side token first — minting then failing to store would burn the
2538
+ * agent name permanently.
2539
+ *
2540
+ * Exit codes: 0 ok; 1 generic failure (invalid name, name taken, crew/shape
2541
+ * rejection, network timeout, minted-but-unstored); 2 the hub is unresolvable;
2542
+ * 3 the human credential is absent or irrecoverable (remedy names
2543
+ * `owenloop login --hub <origin>`).
2544
+ *
2545
+ * A subcommand switch (`new` only today) leaves room for `agent list`/etc. later.
2546
+ */
2547
+ async function dispatchAgent(io, args) {
2548
+ const sub = args.positionals[1];
2549
+ if (sub !== 'new') {
2550
+ throw new CliError(`unknown agent subcommand '${sub ?? ''}' — expected: agent new <name>`);
2551
+ }
2552
+ const name = args.positionals[2];
2553
+ if (name === undefined) {
2554
+ throw new CliError('missing required argument: <name> (usage: owenloop agent new <name> [--crews a,b] [--scopes work,run | --shift] [--hub <url>])');
2555
+ }
2556
+ // Validate the agent name eagerly — before any I/O — with the store's own
2557
+ // wording, so a bad name never reaches the network or the store.
2558
+ try {
2559
+ credentialSlot({ principal: 'agent', account: name });
2560
+ }
2561
+ catch (e) {
2562
+ throw new CliError(`agent new: invalid agent name — ${e.message}`);
2563
+ }
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
2572
+ .split(',')
2573
+ .map((p) => p.trim())
2574
+ .filter((p) => p !== '');
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');
2593
+ }
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
+ }
2605
+ // Refuse an external-command setup at the TOP of the dispatcher — before the
2606
+ // human-credential read (which would otherwise RUN the command) and before any
2607
+ // network call (PR #69 lesson; `mintAgentCredential` carries the same guard as
2608
+ // a library backstop). Refusing only at store time would mint a server-side
2609
+ // token we could never store locally, permanently burning the agent name.
2610
+ if (externalCredentialCommand(io.env) !== undefined) {
2611
+ throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
2612
+ 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
2613
+ }
2614
+ const origin = resolveAgentHub(io, args);
2615
+ // The human bearer for the resolved origin. Absent → exit 3 with the verbatim
2616
+ // remedy the brief mandates.
2617
+ const cred = readCredential(io, origin, { principal: 'human' });
2618
+ if (cred === null) {
2619
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2620
+ }
2621
+ let result;
2622
+ try {
2623
+ result = await mintAgentCredential(io, origin, { principal: 'human' }, cred, { name, crews, scopes });
2624
+ }
2625
+ catch (e) {
2626
+ // A refresh-failure-family error (the human oauth is irrecoverable, or a 401
2627
+ // survived the refresh-and-retry) is exit 3 with the login remedy; every
2628
+ // other CliError propagates as-is — a network timeout stays exit 1, because a
2629
+ // flaky network is not an irrecoverable credential.
2630
+ if (e instanceof CliError && /run `owenloop login`/.test(e.message)) {
2631
+ throw new CliError(`${e.message} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2632
+ }
2633
+ throw e;
2634
+ }
2635
+ // Confirmation: whitelisted, non-secret fields ONLY. `text`/`token` are
2636
+ // structurally absent from `result`, so there is nothing here to leak.
2637
+ print(io, {
2638
+ ok: true,
2639
+ hub: origin,
2640
+ name,
2641
+ slot: `agent:${name}`,
2642
+ crews: result.crews,
2643
+ scopes: result.scopes,
2644
+ storage: result.storage,
2645
+ agentId: result.agentId,
2646
+ tokenId: result.id,
2647
+ });
2648
+ return 0;
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
+ }
3159
+ /**
3160
+ * The plugin check is rendered but NON-FATAL while the marketplace is not yet
3161
+ * fetchably published (the brief's open question): `doctor` shows ✓/✗ but the
3162
+ * plugin never flips the exit code, and `setup` PRINTS install instructions
3163
+ * instead of failing. Flip to `true` once the shell-out install lands.
3164
+ */
3165
+ const PLUGIN_CHECK_FATAL = false;
3166
+ /**
3167
+ * Resolve the hub `setup`/`doctor` target. Deviates from `resolveAgentHub` in
3168
+ * exactly ONE way (documented in the plan §4): a fresh machine — which is the
3169
+ * Flow A mainline — has NO stored hub, so instead of `resolveAgentHub`'s exit-2
3170
+ * it falls back to the production `DEFAULT_HUB` with a printed notice. The
3171
+ * wrong-hub-mint risk `resolveAgentHub` guards against does not apply: the mint
3172
+ * happens only AFTER the human logs in through this hub's own browser consent,
3173
+ * and the target line is printed first.
3174
+ *
3175
+ * - `--hub <origin>` → `normalizeOrigin`.
3176
+ * - else `listStoredHubOrigins`: exactly one → use it; more than one → `CliError`
3177
+ * exitCode 2 listing them; zero or `null` (keychain/external cannot enumerate)
3178
+ * → `DEFAULT_HUB` + notice.
3179
+ *
3180
+ * `OWENLOOP_HUB` stays excluded (O2/O3 parity). Shared by both commands so they
3181
+ * agree on the target.
3182
+ */
3183
+ function resolveSetupHub(io, args) {
3184
+ const flagVal = last(args, 'hub');
3185
+ if (flagVal !== undefined) {
3186
+ try {
3187
+ return normalizeOrigin(flagVal);
3188
+ }
3189
+ catch (e) {
3190
+ throw new CliError(e.message);
3191
+ }
3192
+ }
3193
+ const origins = listStoredHubOrigins(io.env, io.keychain);
3194
+ if (origins !== null && origins.length === 1)
3195
+ return origins[0];
3196
+ if (origins !== null && origins.length > 1) {
3197
+ throw new CliError(`more than one hub is configured on this machine — pass --hub <origin> to pick one; stored hubs: ${origins.join(', ')}`, { exitCode: 2 });
3198
+ }
3199
+ io.err(`targeting ${DEFAULT_HUB} (pass --hub to override)`);
3200
+ return DEFAULT_HUB;
3201
+ }
3202
+ /**
3203
+ * Is `cmd` an executable file on `env.PATH`? A pure PATH scan (no exec), so it is
3204
+ * hermetic-testable by pointing `PATH` at a fixture dir with a chmod +x stub.
3205
+ * A directory entry, a non-executable file, or an unreadable dir is skipped.
3206
+ */
3207
+ function commandOnPath(env, cmd) {
3208
+ const path = env.PATH;
3209
+ if (!path)
3210
+ return false;
3211
+ for (const dir of path.split(delimiter)) {
3212
+ if (dir === '')
3213
+ continue;
3214
+ const full = join(dir, cmd);
3215
+ try {
3216
+ const st = statSync(full);
3217
+ if (st.isFile() && (st.mode & 0o111) !== 0)
3218
+ return true;
3219
+ }
3220
+ catch {
3221
+ // not here — keep scanning
3222
+ }
3223
+ }
3224
+ return false;
3225
+ }
3226
+ /**
3227
+ * Coerce a raw string (a hostname) into a valid agent account name, or `''` when
3228
+ * nothing usable survives. Lowercase; drop every character outside the account
3229
+ * body class `[a-z0-9._-]`; strip leading non-alphanumerics (the account MUST
3230
+ * start alphanumeric); clamp to 64 chars. A suggestion only — never parsed or
3231
+ * matched (§2); the user may accept it or type any valid label.
3232
+ */
3233
+ export function sanitizeAgentName(raw) {
3234
+ let s = raw.toLowerCase().replace(/[^a-z0-9._-]/g, '');
3235
+ s = s.replace(/^[^a-z0-9]+/, '');
3236
+ if (s.length > 64)
3237
+ s = s.slice(0, 64);
3238
+ return s;
3239
+ }
3240
+ /**
3241
+ * The identity's last-active instant in epoch-ms: `max` of its two non-null
3242
+ * timestamps (`lastUsedAt`, the rekey-surviving token-level max; `lastContactAt`,
3243
+ * the identity-level any-protocol contact), or `null` when both are absent. Both
3244
+ * recording paths are monotone, so `max` is the correct "most recent activity".
3245
+ */
3246
+ export function lastActiveMs(identity) {
3247
+ const c = identity.lastContactAt;
3248
+ const u = identity.lastUsedAt;
3249
+ if (c === null)
3250
+ return u;
3251
+ if (u === null)
3252
+ return c;
3253
+ return Math.max(c, u);
3254
+ }
3255
+ /**
3256
+ * Render an elapsed-time delta (ms) as a short relative string: `just now`,
3257
+ * `<n>m ago`, `<n>h ago`, `<n>d ago`. A `null` delta (no recorded activity)
3258
+ * renders `never`. Negative deltas (clock skew) clamp to `just now`.
3259
+ */
3260
+ export function formatLastActive(deltaMs) {
3261
+ if (deltaMs === null)
3262
+ return 'never';
3263
+ const ms = Math.max(0, deltaMs);
3264
+ const min = Math.floor(ms / 60_000);
3265
+ if (min < 1)
3266
+ return 'just now';
3267
+ if (min < 60)
3268
+ return `${min}m ago`;
3269
+ const hr = Math.floor(min / 60);
3270
+ if (hr < 24)
3271
+ return `${hr}h ago`;
3272
+ return `${Math.floor(hr / 24)}d ago`;
3273
+ }
3274
+ /**
3275
+ * File-backend agent account names stored for `origin`, or `null` when the
3276
+ * backend cannot enumerate (keychain/external) — mirrors `listStoredHubOrigins`'
3277
+ * backend-awareness. The keychain interface is get/set/delete only, so the real
3278
+ * agent probe on a keychain machine is the identity-name-keyed reads in step 3.
3279
+ */
3280
+ function enumerateAgentAccounts(io, origin) {
3281
+ if (credentialBackend(io.env, io.keychain).kind !== 'file')
3282
+ return null;
3283
+ const file = readCredentialFile(credentialFilePath(io.env));
3284
+ return Object.keys(file.hubs[origin] ?? {})
3285
+ .filter((k) => k.startsWith('agent:'))
3286
+ .map((k) => k.slice('agent:'.length));
3287
+ }
3288
+ /**
3289
+ * Probe local agent slots (`names`) for one that verifies live against the hub's
3290
+ * `whoami`. Reads each `agent:<name>` slot; a hit is verified with `authedGet`
3291
+ * (ensureFreshOAuth no-ops on the `agent` kind; a 401 = revoked → `sawRevoked`).
3292
+ * Prefers a slot whose `whoami actor.id` matches a listed identity id; falls back
3293
+ * to the first otherwise-verified slot (id/name mismatch is tolerated, never a
3294
+ * hard fail — see plan §5). Never a write.
3295
+ */
3296
+ async function probeAgentSlots(io, origin, names, identities) {
3297
+ let verified = null;
3298
+ let sawSlot = false;
3299
+ let sawRevoked = false;
3300
+ for (const name of names) {
3301
+ const cred = readCredential(io, origin, { principal: 'agent', account: name });
3302
+ if (cred === null)
3303
+ continue;
3304
+ sawSlot = true;
3305
+ let res;
3306
+ try {
3307
+ ({ res } = await authedGet(io, origin, { principal: 'agent', account: name }, cred, '/api/whoami'));
3308
+ }
3309
+ catch {
3310
+ continue;
3311
+ }
3312
+ if (res.status === 401) {
3313
+ sawRevoked = true;
3314
+ continue;
3315
+ }
3316
+ if (!res.ok)
3317
+ continue;
3318
+ let actorId = '';
3319
+ try {
3320
+ actorId = asWhoami(await res.json()).actor.id;
3321
+ }
3322
+ catch {
3323
+ continue;
3324
+ }
3325
+ const byId = identities.find((i) => i.id === actorId);
3326
+ const byName = identities.find((i) => i.name === name);
3327
+ const va = { name, actorId, identity: byId ?? byName };
3328
+ if (byId)
3329
+ return { verified: va, sawSlot, sawRevoked };
3330
+ if (verified === null)
3331
+ verified = va;
3332
+ }
3333
+ return { verified, sawSlot, sawRevoked };
3334
+ }
3335
+ /**
3336
+ * The interactive prompt for setup, or the non-interactive guard. Returns
3337
+ * `io.prompt` when injected; else, when stdin is a real TTY, the default
3338
+ * readline prompt; else a `CliError` naming the two bypass flags — thrown BEFORE
3339
+ * any mutation so a scripted/piped run never blocks or half-applies.
3340
+ */
3341
+ function requirePrompt(io) {
3342
+ if (io.prompt)
3343
+ return io.prompt;
3344
+ if (process.stdin.isTTY)
3345
+ return defaultPrompt;
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');
3348
+ }
3349
+ /**
3350
+ * Prompt for an agent name (Flow A). Offers `sanitizeAgentName(hostname())` as a
3351
+ * prefill an empty answer accepts; an invalid answer re-prompts once, then a
3352
+ * `CliError`. The name is a SUGGESTION only — any valid label is accepted.
3353
+ */
3354
+ async function promptAgentName(io) {
3355
+ const prompt = requirePrompt(io);
3356
+ const prefill = sanitizeAgentName(hostname());
3357
+ const question = prefill ? `Name this Scoped Identity [${prefill}]: ` : 'Name this Scoped Identity: ';
3358
+ for (let attempt = 0; attempt < 2; attempt++) {
3359
+ const raw = (await prompt(question)).trim();
3360
+ const answer = raw === '' ? prefill : raw;
3361
+ if (answer === '') {
3362
+ io.err('an agent name is required');
3363
+ continue;
3364
+ }
3365
+ try {
3366
+ credentialSlot({ principal: 'agent', account: answer });
3367
+ return answer;
3368
+ }
3369
+ catch {
3370
+ io.err(`invalid agent name '${answer}' — expected 1-64 chars matching [A-Za-z0-9][A-Za-z0-9._-]*`);
3371
+ }
3372
+ }
3373
+ throw new CliError('no valid agent name provided');
3374
+ }
3375
+ /**
3376
+ * Render the succession question (Flow B) and read a choice. The framing
3377
+ * sentences are adapted from the model doc (§7 Flow B), restated in the settled
3378
+ * vocabulary; the radio glyphs become numbered
3379
+ * terminal choices (the honest line-input adaptation). `[1]` = new installation;
3380
+ * `[k]` = replace the (k-2)th non-disabled identity. Each Replace line shows the
3381
+ * name, `last active <relative>`, and crews. Invalid input re-prompts once, then
3382
+ * a `CliError`.
3383
+ */
3384
+ async function promptSuccession(io, identities) {
3385
+ const prompt = requirePrompt(io);
3386
+ const candidates = identities.filter((i) => !i.disabled);
3387
+ const now = nowMs();
3388
+ const lines = [
3389
+ 'Is this a new installation, or does it replace an existing one?',
3390
+ '',
3391
+ ' [1] New installation → create a new Scoped Identity',
3392
+ ];
3393
+ candidates.forEach((id, i) => {
3394
+ const active = lastActiveMs(id);
3395
+ const rel = formatLastActive(active === null ? null : now - active);
3396
+ const crews = id.crews.length ? id.crews.join(', ') : '(none)';
3397
+ lines.push(` [${i + 2}] Replace: ${id.name} last active ${rel} · crews: ${crews}`);
3398
+ });
3399
+ lines.push('');
3400
+ lines.push('⚠ "Replace" revokes that Scoped Identity\'s current credential. If it is still');
3401
+ lines.push(' running somewhere, it will be disconnected there.');
3402
+ lines.push('');
3403
+ const max = candidates.length + 1;
3404
+ const question = `${lines.join('\n')}\nChoose [1-${max}]: `;
3405
+ for (let attempt = 0; attempt < 2; attempt++) {
3406
+ const raw = (await prompt(attempt === 0 ? question : `Choose [1-${max}]: `)).trim();
3407
+ const n = Number(raw);
3408
+ if (Number.isInteger(n) && n >= 1 && n <= max) {
3409
+ if (n === 1)
3410
+ return { kind: 'new' };
3411
+ return { kind: 'replace', identity: candidates[n - 2] };
3412
+ }
3413
+ io.err(`please enter a number between 1 and ${max}`);
3414
+ }
3415
+ throw new CliError('no valid choice provided');
3416
+ }
3417
+ /** Probe the Claude Code plugin state: is `claude` on PATH, and does `plugin list` mention owenloop? */
3418
+ function probePlugin(io) {
3419
+ if (!commandOnPath(io.env, 'claude'))
3420
+ return { claudeFound: false, installed: false };
3421
+ const run = io.runCommand ?? defaultRunCommand;
3422
+ try {
3423
+ return { claudeFound: true, installed: run('claude', ['plugin', 'list']).stdout.includes('owenloop') };
3424
+ }
3425
+ catch {
3426
+ return { claudeFound: true, installed: false };
3427
+ }
3428
+ }
3429
+ /**
3430
+ * The plugin ACT step. While the marketplace is unpublished this PRINTS the
3431
+ * manual install instructions instead of shelling out — the single seam a real
3432
+ * shell-out install would replace later. Never fails setup.
3433
+ */
3434
+ function installPluginStep(io, state) {
3435
+ if (!state.claudeFound)
3436
+ io.err('Claude Code (claude) not detected on PATH.');
3437
+ io.err('Claude Code plugin — install manually:');
3438
+ io.err(' claude plugin marketplace add owenloop');
3439
+ io.err(' claude plugin install owenloop@owenloop');
3440
+ }
3441
+ /**
3442
+ * `owenloop setup` — converge this machine's install in six probe→(skip|act)
3443
+ * steps, idempotently: a second run performs ZERO writes (no store mutation, no
3444
+ * settings write, no browser, no mint/rekey/register POST). Each ACT is reached
3445
+ * only through its probe failing.
3446
+ *
3447
+ * Flags: `--hub <url>`; mutually-exclusive `--new-agent <name>` / `--replace-agent
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).
3452
+ *
3453
+ * Exit: 0 when every step ended skipped/done/noted AND doctor's core (non-plugin)
3454
+ * checks pass; 1 otherwise. Any hard failure throws (mapped to an exit code by
3455
+ * `mainAsync`).
3456
+ */
3457
+ async function dispatchSetup(io, args) {
3458
+ // --- usage validation, before any I/O ---
3459
+ const newAgent = last(args, 'new-agent');
3460
+ const replaceAgent = last(args, 'replace-agent');
3461
+ if (newAgent !== undefined && replaceAgent !== undefined) {
3462
+ throw new CliError('pass at most one of --new-agent or --replace-agent, not both');
3463
+ }
3464
+ const crewsRaw = last(args, 'crews');
3465
+ let crews;
3466
+ if (crewsRaw !== undefined) {
3467
+ crews = crewsRaw
3468
+ .split(',')
3469
+ .map((p) => p.trim())
3470
+ .filter((p) => p !== '');
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');
3488
+ }
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)");
3491
+ }
3492
+ for (const [flagName, val] of [
3493
+ ['--new-agent', newAgent],
3494
+ ['--replace-agent', replaceAgent],
3495
+ ]) {
3496
+ if (val !== undefined) {
3497
+ try {
3498
+ credentialSlot({ principal: 'agent', account: val });
3499
+ }
3500
+ catch (e) {
3501
+ throw new CliError(`${flagName}: invalid agent name — ${e.message}`);
3502
+ }
3503
+ }
3504
+ }
3505
+ // Symmetric with `dispatchLogin`: when an external credential command supplies
3506
+ // this hub's credentials, the local store is never consulted, so setup's
3507
+ // human-login step (step 2, which opens the loopback OAuth browser) and its
3508
+ // agent mint would strand keys nobody reads. Refuse BEFORE any browser opens —
3509
+ // otherwise setup completes the full OAuth round-trip only to fail at
3510
+ // storeCredential's backstop, wasting a browser trip on the flagship command.
3511
+ if (externalCredentialCommand(io.env) !== undefined) {
3512
+ throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
3513
+ 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
3514
+ }
3515
+ const origin = resolveSetupHub(io, args);
3516
+ const steps = [];
3517
+ // --- [1/6] inspect: zero writes, best-effort probes ---
3518
+ io.err('[1/6] inspect');
3519
+ io.err(` human credential: ${readCredential(io, origin, { principal: 'human' }) !== null ? 'present' : 'none — will log in'}`);
3520
+ const inspectSettingsPath = owenloopSettingsPath(io.env);
3521
+ let settingsNote;
3522
+ if (!existsSync(inspectSettingsPath)) {
3523
+ settingsNote = 'missing — will write';
3524
+ }
3525
+ else {
3526
+ try {
3527
+ const raw = readOwenloopSettingsRaw(inspectSettingsPath);
3528
+ const found = raw && typeof raw.hubOrigin === 'string' ? raw.hubOrigin : undefined;
3529
+ settingsNote = found === origin ? `hubOrigin already ${origin}` : `hubOrigin ${found ?? '(unset)'} — will update`;
3530
+ }
3531
+ catch {
3532
+ settingsNote = 'present but unreadable — step 4 will error if still corrupt';
3533
+ }
3534
+ }
3535
+ io.err(` owenloop settings: ${settingsNote}`);
3536
+ io.err(` claude on PATH: ${commandOnPath(io.env, 'claude') ? 'yes' : 'no'}`);
3537
+ const inspectAccts = enumerateAgentAccounts(io, origin);
3538
+ io.err(inspectAccts === null
3539
+ ? ' agent slots: checked in step 3'
3540
+ : ` agent slots: ${inspectAccts.length ? inspectAccts.map((a) => `agent:${a}`).join(', ') : 'none'}`);
3541
+ steps.push({ step: 'inspect', action: 'done', detail: 'probed local state' });
3542
+ // --- [2/6] human login: the hard gate that makes step 3's rekey legal ---
3543
+ io.err('[2/6] human login');
3544
+ let humanCred = readCredential(io, origin, { principal: 'human' });
3545
+ let humanIdentity;
3546
+ if (humanCred !== null) {
3547
+ try {
3548
+ const verified = await verifyCredential(io, origin, { principal: 'human' }, humanCred);
3549
+ humanCred = verified.cred;
3550
+ humanIdentity = verified.identity;
3551
+ io.err(`✓ human: ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
3552
+ steps.push({ step: 'human login', action: 'skipped', detail: `${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}` });
3553
+ }
3554
+ catch (e) {
3555
+ if (!(e instanceof CliError))
3556
+ throw e; // a genuine non-credential error is not a re-login trigger
3557
+ const r = await runLoopbackOAuth(io, origin);
3558
+ humanCred = r.cred;
3559
+ humanIdentity = r.identity;
3560
+ io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
3561
+ steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
3562
+ }
3563
+ }
3564
+ else {
3565
+ const r = await runLoopbackOAuth(io, origin);
3566
+ humanCred = r.cred;
3567
+ humanIdentity = r.identity;
3568
+ io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
3569
+ steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
3570
+ }
3571
+ // --- [3/6] agent ---
3572
+ io.err('[3/6] agent');
3573
+ const { res: idRes } = await authedGet(io, origin, { principal: 'human' }, humanCred, '/api/agent_identities');
3574
+ if (idRes.status === 403) {
3575
+ throw new CliError('setup needs an admin credential to manage Scoped Identities (hub returned 403)');
3576
+ }
3577
+ assertAuthOk(idRes, humanCred, origin);
3578
+ const identities = asAgentIdentities(await idRes.json());
3579
+ const candidateNames = new Set(identities.map((i) => i.name));
3580
+ candidateNames.add('default');
3581
+ const probe = await probeAgentSlots(io, origin, [...candidateNames], identities);
3582
+ let agentAccount;
3583
+ if (probe.verified !== null) {
3584
+ agentAccount = probe.verified.name;
3585
+ const crewsStr = probe.verified.identity ? ` (crews: ${probe.verified.identity.crews.join(', ') || 'none'})` : '';
3586
+ io.err(`✓ agent: ${agentAccount}${crewsStr}`);
3587
+ steps.push({ step: 'agent', action: 'skipped', detail: `agent:${agentAccount} verified` });
3588
+ }
3589
+ else {
3590
+ // ACT — resolve which agent to connect, then mint or rekey.
3591
+ let action;
3592
+ if (newAgent !== undefined) {
3593
+ action = { mode: 'mint', name: newAgent };
3594
+ }
3595
+ else if (replaceAgent !== undefined) {
3596
+ const target = identities.find((i) => i.name === replaceAgent);
3597
+ if (target === undefined) {
3598
+ throw new CliError(`no Scoped Identity named '${replaceAgent}' on ${origin} — available: ${identities.map((i) => i.name).join(', ') || '(none)'}`);
3599
+ }
3600
+ action = { mode: 'rekey', agentId: target.id, name: replaceAgent };
3601
+ }
3602
+ else if (identities.length === 0) {
3603
+ // Flow A — fresh org, prompt for a name.
3604
+ action = { mode: 'mint', name: await promptAgentName(io) };
3605
+ }
3606
+ else {
3607
+ // Flow B — succession.
3608
+ const choice = await promptSuccession(io, identities);
3609
+ action =
3610
+ choice.kind === 'new'
3611
+ ? { mode: 'mint', name: await promptAgentName(io) }
3612
+ : { mode: 'rekey', agentId: choice.identity.id, name: choice.identity.name };
3613
+ }
3614
+ if (action.mode === 'mint') {
3615
+ const result = await mintAgentCredential(io, origin, { principal: 'human' }, humanCred, { name: action.name, crews, scopes });
3616
+ agentAccount = action.name;
3617
+ io.err(`✓ agent: minted agent:${agentAccount} (crews: ${result.crews.join(', ') || 'none'}; scopes: ${result.scopes.join(', ')})`);
3618
+ steps.push({ step: 'agent', action: 'done', detail: `minted agent:${agentAccount}` });
3619
+ }
3620
+ else {
3621
+ const result = await rekeyAgentCredential(io, origin, { principal: 'human' }, humanCred, { agentId: action.agentId, name: action.name });
3622
+ agentAccount = action.name;
3623
+ io.err(`✓ agent: re-keyed agent:${agentAccount} (revoked ${result.revokedTokenIds.length} old token(s))`);
3624
+ steps.push({ step: 'agent', action: 'done', detail: `re-keyed agent:${agentAccount}` });
3625
+ }
3626
+ }
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)
3631
+ const currentHub = existingSettings && typeof existingSettings.hubOrigin === 'string' ? existingSettings.hubOrigin : undefined;
3632
+ if (existingSettings !== null && currentHub === origin) {
3633
+ io.err(`✓ owenloop settings: hubOrigin already ${origin}`);
3634
+ steps.push({ step: 'owenloop settings', action: 'skipped', detail: settingsPath });
3635
+ }
3636
+ else {
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}` });
3640
+ }
3641
+ if (agentAccount !== 'default') {
3642
+ io.err(`non-default agent account — run owenloop work with OWENLOOP_ACCOUNT=${agentAccount}`);
3643
+ }
3644
+ // --- [5/6] plugin (non-fatal) ---
3645
+ io.err('[5/6] plugin');
3646
+ const pluginState = probePlugin(io);
3647
+ if (pluginState.installed) {
3648
+ io.err('✓ plugin: owenloop installed');
3649
+ steps.push({ step: 'plugin', action: 'skipped', detail: 'installed' });
3650
+ }
3651
+ else {
3652
+ installPluginStep(io, pluginState);
3653
+ steps.push({
3654
+ step: 'plugin',
3655
+ action: 'noted',
3656
+ detail: pluginState.claudeFound ? 'not installed — printed manual instructions' : 'claude not on PATH — printed manual instructions',
3657
+ });
3658
+ }
3659
+ // --- [6/6] doctor pass ---
3660
+ io.err('[6/6] doctor');
3661
+ const doctor = await runDoctor(io, origin);
3662
+ print(io, { ok: doctor.ok, hub: origin, steps, doctor: { ok: doctor.ok, checks: doctor.checks } });
3663
+ return doctor.ok ? 0 : 1;
3664
+ }
3665
+ /**
3666
+ * `owenloop doctor` — the read-only probe of the five install surfaces plus the
3667
+ * plugin, rendering one distinct ✓/✗ line each. NO configuration writes (no
3668
+ * mint, rekey, slot create/delete, settings write, or browser). The one
3669
+ * carve-out: `authedGet`'s persist=true MAY rotate-and-persist an expiring human
3670
+ * oauth token — as every authed verb does — because a refresh WITHOUT persisting
3671
+ * would strand the rotated refresh token and corrupt the install (worse than a
3672
+ * write). Tests use non-expiring tokens so the strict zero-write assertion holds.
3673
+ */
3674
+ async function dispatchDoctor(io, args) {
3675
+ const origin = resolveSetupHub(io, args);
3676
+ const doctor = await runDoctor(io, origin);
3677
+ print(io, { ok: doctor.ok, hub: origin, checks: doctor.checks });
3678
+ return doctor.ok ? 0 : 1;
3679
+ }
3680
+ /**
3681
+ * Run the six doctor checks in order, printing each ✓/✗ line to stderr and
3682
+ * returning the structured result. Never short-circuits — a machine with no
3683
+ * working human credential still renders lines 3–6 (the agent probe degrades
3684
+ * honestly). `ok` reflects checks 1–5 only; the plugin check (6) renders but,
3685
+ * while `PLUGIN_CHECK_FATAL` is false, never affects `ok`.
3686
+ */
3687
+ async function runDoctor(io, origin) {
3688
+ const checks = [];
3689
+ let coreOk = true;
3690
+ const record = (label, ok, detail, core) => {
3691
+ io.err(`${ok ? '✓' : '✗'} ${label}: ${detail}`);
3692
+ checks.push({ label, ok, detail });
3693
+ if (core && !ok)
3694
+ coreOk = false;
3695
+ };
3696
+ // 1. human slot
3697
+ const humanCred = readCredential(io, origin, { principal: 'human' });
3698
+ if (humanCred === null) {
3699
+ record('human credential', false, `none stored for ${origin} — run owenloop setup (or owenloop login --hub ${origin})`, true);
3700
+ }
3701
+ else {
3702
+ record('human credential', true, 'present', true);
3703
+ }
3704
+ // 2. human plane
3705
+ let humanOk = false;
3706
+ let usableHumanCred = null;
3707
+ if (humanCred !== null) {
3708
+ try {
3709
+ const { cred, identity } = await verifyCredential(io, origin, { principal: 'human' }, humanCred);
3710
+ humanOk = true;
3711
+ usableHumanCred = cred;
3712
+ record('human plane', true, `${identity.email ?? identity.actor.id} @ ${identity.orgName}`, true);
3713
+ }
3714
+ catch (e) {
3715
+ const msg = e instanceof Error ? e.message : String(e);
3716
+ if (/refresh/i.test(msg)) {
3717
+ record('human plane', false, 'human credential present but irrecoverable (refresh failed) — run owenloop login', true);
3718
+ }
3719
+ else if (/rejected by the hub|revoked or invalid/.test(msg)) {
3720
+ record('human plane', false, 'human credential rejected by the hub — run owenloop login', true);
3721
+ }
3722
+ else {
3723
+ record('human plane', false, `could not reach the hub — ${msg}`, true);
3724
+ }
3725
+ }
3726
+ }
3727
+ else {
3728
+ record('human plane', false, 'not checked — no human credential to verify', true);
3729
+ }
3730
+ // Best-effort identities listing for the agent checks (soft: a 403/failure degrades, never throws).
3731
+ let identities = [];
3732
+ let identitiesForbidden = false;
3733
+ let identitiesAvailable = false;
3734
+ if (humanOk && usableHumanCred !== null) {
3735
+ try {
3736
+ const { res } = await authedGet(io, origin, { principal: 'human' }, usableHumanCred, '/api/agent_identities');
3737
+ if (res.status === 403) {
3738
+ identitiesForbidden = true;
3739
+ }
3740
+ else if (res.ok) {
3741
+ identities = asAgentIdentities(await res.json());
3742
+ identitiesAvailable = true;
3743
+ }
3744
+ }
3745
+ catch {
3746
+ // leave degraded
3747
+ }
3748
+ }
3749
+ // 3. agent slot (presence) + 4. agent plane (verification)
3750
+ const candidateNames = new Set(identities.map((i) => i.name));
3751
+ const fileAccts = enumerateAgentAccounts(io, origin);
3752
+ if (fileAccts !== null)
3753
+ for (const a of fileAccts)
3754
+ candidateNames.add(a);
3755
+ candidateNames.add('default');
3756
+ const agentProbe = await probeAgentSlots(io, origin, [...candidateNames], identities);
3757
+ if (!agentProbe.sawSlot) {
3758
+ if (!identitiesAvailable && !humanOk && fileAccts === null) {
3759
+ record('agent slot', false, 'not probeable without a working human credential', true);
3760
+ }
3761
+ else {
3762
+ record('agent slot', false, `no agent credential stored for ${origin} — run owenloop setup`, true);
3763
+ }
3764
+ record('agent plane', false, 'no agent credential to verify — run owenloop setup', true);
3765
+ }
3766
+ else {
3767
+ record('agent slot', true, 'present', true);
3768
+ if (agentProbe.verified !== null) {
3769
+ const va = agentProbe.verified;
3770
+ const crews = va.identity
3771
+ ? `crews: ${va.identity.crews.join(', ') || 'none'}`
3772
+ : identitiesForbidden
3773
+ ? '(crews not visible — requires an admin credential)'
3774
+ : '(crews unknown)';
3775
+ const idPart = va.identity ? va.identity.id : va.actorId;
3776
+ record('agent plane', true, `${va.name} (agent id ${idPart}) · ${crews}`, true);
3777
+ }
3778
+ else if (agentProbe.sawRevoked) {
3779
+ record('agent plane', false, 'agent token revoked or invalid — re-run owenloop setup (Replace) or Reconnect in the console', true);
3780
+ }
3781
+ else {
3782
+ record('agent plane', false, 'agent credential present but could not be verified against the hub', true);
3783
+ }
3784
+ }
3785
+ // 5. owenloop settings
3786
+ const settingsPath = owenloopSettingsPath(io.env);
3787
+ let settingsRaw = null;
3788
+ let settingsError = null;
3789
+ try {
3790
+ settingsRaw = readOwenloopSettingsRaw(settingsPath);
3791
+ }
3792
+ catch (e) {
3793
+ settingsError = e instanceof Error ? e.message : String(e);
3794
+ }
3795
+ if (settingsError !== null) {
3796
+ record('owenloop settings', false, settingsError, true);
3797
+ }
3798
+ else if (settingsRaw === null) {
3799
+ record('owenloop settings', false, `missing (${settingsPath})`, true);
3800
+ }
3801
+ else {
3802
+ const found = typeof settingsRaw.hubOrigin === 'string' ? settingsRaw.hubOrigin : undefined;
3803
+ if (found !== origin) {
3804
+ record('owenloop settings', false, `hubOrigin is ${found ?? '(unset)'}, expected ${origin}`, true);
3805
+ }
3806
+ else {
3807
+ record('owenloop settings', true, settingsPath, true);
3808
+ }
3809
+ }
3810
+ // 6. plugin (rendered; non-core while PLUGIN_CHECK_FATAL is false)
3811
+ const pluginState = probePlugin(io);
3812
+ if (!pluginState.claudeFound) {
3813
+ record('plugin', false, 'Claude Code (claude) not on PATH', PLUGIN_CHECK_FATAL);
3814
+ }
3815
+ else if (!pluginState.installed) {
3816
+ record('plugin', false, 'plugin not installed — claude plugin marketplace add owenloop && claude plugin install owenloop@owenloop', PLUGIN_CHECK_FATAL);
3817
+ }
3818
+ else {
3819
+ record('plugin', true, 'owenloop installed', PLUGIN_CHECK_FATAL);
3820
+ }
3821
+ return { ok: coreOk, checks };
3822
+ }
2569
3823
  /**
2570
3824
  * Async entry point that adds network I/O for `add` and the hub commands on top
2571
3825
  * of the otherwise fully-synchronous engine/CLI (see the doc comment on
@@ -2574,8 +3828,26 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2574
3828
  * the async path, so every existing command and test keeps working exactly as
2575
3829
  * before.
2576
3830
  */
2577
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push']);
3831
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push', 'agent', 'capability', 'crew', 'setup', 'doctor', 'mcp', 'shift']);
2578
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
+ }
2579
3851
  const args = parseArgs(argv);
2580
3852
  const command = args.positionals[0];
2581
3853
  if (command === undefined || !ASYNC_COMMANDS.has(command)) {
@@ -2596,6 +3868,18 @@ export async function mainAsync(argv, io = defaultIO()) {
2596
3868
  return await dispatchConnect(io, args);
2597
3869
  case 'push':
2598
3870
  return await dispatchPush(io, args);
3871
+ case 'agent':
3872
+ return await dispatchAgent(io, args);
3873
+ case 'capability':
3874
+ return await dispatchCapability(io, args);
3875
+ case 'crew':
3876
+ return await dispatchCrew(io, args);
3877
+ case 'setup':
3878
+ return await dispatchSetup(io, args);
3879
+ case 'doctor':
3880
+ return await dispatchDoctor(io, args);
3881
+ case 'mcp':
3882
+ return await dispatchMcp(io, args);
2599
3883
  default:
2600
3884
  return main(argv, io); // unreachable — ASYNC_COMMANDS guards the switch
2601
3885
  }
@@ -2607,11 +3891,16 @@ export async function mainAsync(argv, io = defaultIO()) {
2607
3891
  else {
2608
3892
  io.err(`error: ${e.message}`);
2609
3893
  }
2610
- return 1;
3894
+ // A CliError carries its own exit code (default 1); everything else is 1.
3895
+ return e instanceof CliError ? e.exitCode : 1;
2611
3896
  }
2612
3897
  }
2613
- /** Run the CLI. Returns a process exit code. */
3898
+ /** Run the synchronous engine CLI. The `work` and `shift` namespaces are async-only. */
2614
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
+ }
2615
3904
  const args = parseArgs(argv);
2616
3905
  const command = args.positionals[0];
2617
3906
  if (command === undefined) {
@@ -2631,6 +3920,7 @@ export function main(argv, io = defaultIO()) {
2631
3920
  else {
2632
3921
  io.err(`error: ${e.message}`);
2633
3922
  }
2634
- return 1;
3923
+ // A CliError carries its own exit code (default 1); everything else is 1.
3924
+ return e instanceof CliError ? e.exitCode : 1;
2635
3925
  }
2636
3926
  }