owenloop 0.5.8 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +81 -39
  3. package/bin/owenloop.mjs +16 -1
  4. package/dist/packages/work/src/agent/loop.d.ts +23 -8
  5. package/dist/packages/work/src/agent/loop.js +55 -6
  6. package/dist/packages/work/src/bundle/pull.d.ts +21 -0
  7. package/dist/packages/work/src/bundle/pull.js +118 -0
  8. package/dist/packages/work/src/consumed-verifier.js +6 -17
  9. package/dist/packages/work/src/exec/instructions.d.ts +4 -1
  10. package/dist/packages/work/src/exec/instructions.js +3 -0
  11. package/dist/packages/work/src/exec/loop.d.ts +2 -2
  12. package/dist/packages/work/src/exec/loop.js +273 -46
  13. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  14. package/dist/packages/work/src/exec/receipt.js +6 -6
  15. package/dist/packages/work/src/harness/claude.js +116 -0
  16. package/dist/packages/work/src/harness/codex.d.ts +8 -0
  17. package/dist/packages/work/src/harness/codex.js +27 -1
  18. package/dist/packages/work/src/harness/contract.d.ts +9 -0
  19. package/dist/packages/work/src/hub/client.d.ts +19 -4
  20. package/dist/packages/work/src/hub/client.js +7 -3
  21. package/dist/packages/work/src/hub/types.d.ts +84 -0
  22. package/dist/packages/work/src/main.js +1 -0
  23. package/dist/packages/work/src/roles/agent-run.js +57 -32
  24. package/dist/packages/work/src/roles/exec.js +27 -8
  25. package/dist/packages/work/src/roles/settings.js +2 -0
  26. package/dist/packages/work/src/roles/shift.js +14 -2
  27. package/dist/packages/work/src/roles/util.d.ts +1 -0
  28. package/dist/packages/work/src/roles/util.js +10 -0
  29. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  30. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  31. package/dist/packages/work/src/settings/roster.d.ts +84 -0
  32. package/dist/packages/work/src/settings/roster.js +364 -5
  33. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  34. package/dist/packages/work/src/settings/serving.js +79 -0
  35. package/dist/packages/work/src/settings/settings.d.ts +14 -1
  36. package/dist/packages/work/src/settings/settings.js +14 -0
  37. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  38. package/dist/packages/work/src/shift/loop.js +416 -54
  39. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  40. package/dist/packages/work/src/shift/runtime.d.ts +18 -0
  41. package/dist/packages/work/src/shift/runtime.js +104 -5
  42. package/dist/packages/work/src/shift/server.js +2 -0
  43. package/dist/packages/work/src/shift/spawn.d.ts +17 -2
  44. package/dist/packages/work/src/shift/spawn.js +16 -13
  45. package/dist/packages/work/src/shift/state.d.ts +29 -2
  46. package/dist/packages/work/src/shift/state.js +45 -15
  47. package/dist/packages/work/src/submit-proof.d.ts +11 -8
  48. package/dist/packages/work/src/submit-proof.js +11 -8
  49. package/dist/packages/work/src/usage.d.ts +1 -1
  50. package/dist/packages/work/src/usage.js +7 -1
  51. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  52. package/dist/packages/work/src/util/modifier-init.js +73 -0
  53. package/dist/src/bundle/tar.d.ts +9 -4
  54. package/dist/src/bundle/tar.js +9 -4
  55. package/dist/src/capabilities.d.ts +76 -6
  56. package/dist/src/capabilities.js +49 -6
  57. package/dist/src/capability-mapping-client.d.ts +29 -0
  58. package/dist/src/capability-mapping-client.js +160 -0
  59. package/dist/src/cli.d.ts +16 -3
  60. package/dist/src/cli.js +1925 -281
  61. package/dist/src/config-dir.d.ts +1 -1
  62. package/dist/src/config-dir.js +1 -1
  63. package/dist/src/crypto/index.d.ts +1 -1
  64. package/dist/src/crypto/index.js +1 -1
  65. package/dist/src/crypto/org-root.d.ts +30 -12
  66. package/dist/src/crypto/org-root.js +162 -14
  67. package/dist/src/crypto/records.d.ts +2 -0
  68. package/dist/src/crypto/records.js +2 -0
  69. package/dist/src/defs.d.ts +38 -2
  70. package/dist/src/defs.js +593 -86
  71. package/dist/src/engine.d.ts +103 -25
  72. package/dist/src/engine.js +331 -79
  73. package/dist/src/hub.d.ts +77 -0
  74. package/dist/src/hub.js +162 -0
  75. package/dist/src/implements.d.ts +56 -0
  76. package/dist/src/implements.js +790 -0
  77. package/dist/src/index.d.ts +11 -9
  78. package/dist/src/index.js +6 -5
  79. package/dist/src/mcp/serve.d.ts +22 -0
  80. package/dist/src/mcp/serve.js +330 -41
  81. package/dist/src/mcp/server.d.ts +10 -7
  82. package/dist/src/mcp/server.js +53 -8
  83. package/dist/src/model.d.ts +48 -10
  84. package/dist/src/model.js +252 -99
  85. package/dist/src/order-resolver.d.ts +1 -0
  86. package/dist/src/order-resolver.js +8 -1
  87. package/dist/src/schemas/index.d.ts +11 -0
  88. package/dist/src/schemas/order.v1.schema.json +7 -1
  89. package/dist/src/store/def-source.d.ts +19 -0
  90. package/dist/src/store/def-source.js +87 -17
  91. package/dist/src/store/gc-recovery.d.ts +46 -0
  92. package/dist/src/store/gc-recovery.js +258 -0
  93. package/dist/src/store/gc.d.ts +94 -0
  94. package/dist/src/store/gc.js +562 -0
  95. package/dist/src/store/index.d.ts +3 -1
  96. package/dist/src/store/index.js +2 -0
  97. package/dist/src/store/install.d.ts +34 -5
  98. package/dist/src/store/install.js +73 -11
  99. package/dist/src/store/pre-commit-verifier.js +42 -2
  100. package/dist/src/store/snapshot-guard.d.ts +18 -0
  101. package/dist/src/store/snapshot-guard.js +94 -0
  102. package/dist/src/store.d.ts +69 -4
  103. package/dist/src/store.js +254 -16
  104. package/dist/src/types.d.ts +101 -20
  105. package/dist/src/util.js +4 -1
  106. package/docs/authoring.md +235 -10
  107. package/docs/bundles.md +45 -2
  108. package/docs/cli.md +437 -55
  109. package/docs/crypto.md +32 -10
  110. package/docs/design.md +177 -47
  111. package/docs/evals/mcp-charter-baseline.json +428 -0
  112. package/docs/mcp-charter-eval.md +124 -0
  113. package/docs/routing.md +189 -34
  114. package/docs/shift-logs.md +38 -9
  115. package/docs/wire-contracts.md +78 -14
  116. package/examples/workflows/compile-dev-playbook.yaml +1 -1
  117. package/examples/workflows/delivery.yaml +31 -14
  118. package/examples/workflows/ship.yaml +38 -4
  119. package/package.json +2 -1
  120. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  121. package/plugins/claude-code/plugin/.mcp.json +1 -1
  122. package/plugins/claude-code/plugin/skills/author/SKILL.md +22 -0
  123. package/plugins/claude-code/plugin/skills/ephemeral/SKILL.md +95 -0
  124. package/plugins/claude-code/plugin/skills/graduate/SKILL.md +156 -0
  125. package/plugins/claude-code/plugin/skills/plan/SKILL.md +236 -0
  126. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  127. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  128. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +22 -0
  129. package/plugins/codex/plugins/owenloop/skills/ephemeral/SKILL.md +95 -0
  130. package/plugins/codex/plugins/owenloop/skills/graduate/SKILL.md +156 -0
  131. package/plugins/codex/plugins/owenloop/skills/plan/SKILL.md +236 -0
@@ -78,14 +78,17 @@ function submissionFingerprint(order, warn) {
78
78
  * the proof against.
79
79
  *
80
80
  * Retry-safety comes from the hub, not from this function. The target is
81
- * computed once inside the claim transaction and persisted with the immutable
82
- * order, so every retry of the same claim — a reconnect, a lost response, a
83
- * restarted holder — reads the same number. The engine's refusal paths that
84
- * leave the run open (schema-reject) do not bump the artifact, so the target
85
- * survives in-claim retries; a refinement is a NEW claim and therefore a newly
86
- * issued target. If a target ever did go stale, the consumer's version check
87
- * refuses the artifact. The failure mode is a refusal, never an admitted
88
- * unverified value.
81
+ * issued inside the claim transaction and persisted with the order, so a
82
+ * reconnect, a lost response, or a restarted holder re-reads the same number
83
+ * rather than guessing one; a refinement is a NEW claim and therefore a newly
84
+ * issued target. It is not, however, frozen for the life of the claim. A
85
+ * refusal that leaves the run open without bumping the artifact (a schema
86
+ * reject) leaves the target correct, but a judgment/human reject FOLLOWS a
87
+ * commit that already bumped it, so the engine re-stamps the target on the
88
+ * still-open claim at the reject site — this function simply re-reads whatever
89
+ * the current order says, which is why it must never cache one. If a target
90
+ * does go stale anyway, the consumer's version check refuses the artifact. The
91
+ * failure mode is a refusal, never an admitted unverified value.
89
92
  *
90
93
  * A hub that projects no `owes[].version` (pre-version-aware) yields
91
94
  * `undefined`, and the caller submits unsigned rather than signing a guess.
@@ -3,4 +3,4 @@
3
3
  * exit 0) and on a dispatch error (to stderr, exit 2). Keeping it in one place
4
4
  * means the help output and the error output never drift apart.
5
5
  */
6
- export declare const USAGE = "owenloop work \u2014 execution-side CLI companion to owenloop\n\nUsage:\n owenloop work hold --order <id> [options] hold an order with a heartbeating lease\n owenloop work exec <order-id> [options] run a command order in a self-leasing loop\n owenloop work agent-run <order-id> [options] host an agent order's step agent in a\n harness, in a self-leasing loop\n owenloop work prepare <workflow> [--origin <url>]\n fetch, cache & normalize step specs\n owenloop work lint <workflow-name | path> lint x.harness option bags in a def\n owenloop work sessions [--all] [--json] list this machine's recorded harness\n sessions and how to re-open them\n owenloop work approvals [--json] every tool call a worker is blocked on\n RIGHT NOW, waiting for a person\n owenloop work approvals approve|deny <wf>/<run> <tool-use-id> [--note <text>]\n answer one; the answer goes back to the\n still-blocked call, not to a later attempt\n owenloop work release --session <id> [options] drain a session's held claims\n owenloop work settings print the resolved settings file\n owenloop work join <code> [--hub <origin>] [--as <account>]\n redeem a join code and store the Scoped\n Identity credential (one-time provisioning)\n\nOptions:\n -h, --help show this help and exit 0\n --version print the owenloop work version and exit 0\n\n root shift options (run as owenloop shift start <crew...> | --all):\n <crew...> serve only these crews (positional, space\n separated); or --all for every crew on the key\n --all serve every crew on the key\n --origin <url> hub origin (else settings.hubOrigin)\n --as <account> Scoped Identity credential account to read + hand\n to dispatched holds/execs (default 'default')\n --name <n> Shift name (default <hostname>/<cwd>)\n --cap <n> max in-flight exec children (default 3)\n --poll-interval <ms> wake poll cadence (default 5000)\n --once bootstrap wake + one sweep, then exit (demo/e2e)\n --max-agents <n> max in-flight agent-run children, separate from\n --cap (default 4; else settings.maxConcurrentAgents)\n --cache-dir/--state-dir <p> override the resolved dirs\n\n hold options:\n --order <workflow>/<run> the order to hold (or --order <run> --workflow)\n --workflow <wf> required when --order is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --as <account> Scoped Identity credential account (default\n 'default'; the shift stamps this into born-bound\n holds)\n --session <id> session-holder tag (else env OWENLOOP_SESSION;\n else an anon:<hostname>:<pid> fallback \u2014 a\n holder is always sent)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n --ignore-stdin don't final-breath on stdin EOF (detached use)\n --never-release another process holds the claim; stop without\n releasing it (agent-run spawns its --mcp child\n this way \u2014 see hold.ts HOLDER OF RECORD)\n --mcp run as a stdio-MCP work-holder: tools get_order /\n submit, lease kept warm underneath (mutually\n exclusive with --ignore-stdin \u2014 stdin is the\n transport)\n\n exec options (usually spawned by shift, not run by hand):\n <workflow>/<run> the command order to run (positional order-id;\n or a bare <run> plus --workflow <wf>)\n --workflow <wf> required when the order-id is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n\n agent-run options (spawned by the shift, not run by hand):\n <workflow>/<run> the agent order to host (positional order-id;\n or a bare <run> plus --workflow <wf>)\n --workflow <wf> required when the order-id is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --harness <id> which registered harness hosts the step agent\n (below a selected roster candidate; else the\n step def's 'harness' field, then the first\n registered one)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n --submit-grace <ms> after the turn ends, how long to keep asking the\n hub whether the agent's submit landed (default\n 15000). Task completion comes from the HUB, never\n from the harness stream.\n --confirm-interval <ms> poll cadence inside that grace (default 1000)\n\n release options:\n --session <id> session whose claims to drain (else env\n OWENLOOP_SESSION). Agent-held claims re-offer;\n exec-held claims are drain-exempt (B3).\n --origin <url> hub origin (else settings.hubOrigin)\n\n settings (no options in v1):\n prints the resolved settings file path, whether it exists, each known\n knob (hubOrigin, cacheDir, stateDir, dispatchCap, commandRouting,\n maxConcurrentAgents, workRoot, workRepo) with its value + provenance,\n and any unrecognized keys.\n settings.dispatchCap/stateDir are the lowest-precedence\n fallbacks for shift's --cap/--state-dir. NO secrets ever\n live in settings \u2014 credentials stay in owenloop's own store.\n\n sessions options:\n --all include 'dead' sessions (hidden by default \u2014\n a dead session can no longer be resumed)\n --json print the raw newest-per-step records, tokens\n included, instead of the table\n --cache-dir <p> override the resolved cache dir\n\n join options:\n --hub <origin> hub to redeem against (else settings.hubOrigin;\n one of the two is REQUIRED \u2014 the code never\n chooses the hub)\n --as <account> credential account to store under (default:\n the Scoped Identity name the hub returns)\n\n shift/hold/exec/prepare/release env:\n credentials come from owenloop's store \u2014 each role reads the\n agent:<account> slot for its origin (never the human slot); a\n missing slot refuses with a runnable 'owenloop login' command.\n OWENLOOP_ACCOUNT Scoped Identity account for exec/prepare/release\n (default 'default'; shift uses --as, and\n stamps it onto dispatched holds/execs)\n OWENLOOP_TOKEN dev-only bearer override \u2014 when set, used\n verbatim and the store + account are\n bypassed (NOT the primary path)\n OWENLOOP_CACHE_DIR cache root\n OWENLOOP_STATE_DIR shift in-flight state dir\n OWENLOOP_SHIFT_LOG_DIR dir for the shift's shift.log and each\n worker's <run>.log; below --log-dir, above\n settings.shiftLogDir, default the state dir\n OWENLOOP_SHIFT_LOG_MAX_AGE_MS\n how long a worker's <run>.log is kept, in ms;\n below --log-max-age, above\n settings.shiftLogMaxAgeMs, default 14 days.\n Worker logs only \u2014 shift.log is never reaped\n OWENLOOP_SESSION hold session-holder tag / release drain target\n OWENLOOP_SHIFT_ID dispatching Shift's self-declared id for\n hold/exec/agent-run's --shift (advisory\n only, never for auth/routing/dispatch)\n OWENLOOP_WORK_ROOT root for per-RUN agent work dirs\n (<workRoot>/<workflow>/<run>); above\n settings.workRoot, default <cacheDir>/work.\n A hub-supplied OrderPacket.workdir still\n wins, and is never reaped.\n OWENLOOP_WORK_REPO local git repo to cut per-run work dirs from\n as worktrees instead of plain dirs; above\n settings.workRepo, default off\n\n Credentials / accounts:\n owenloop work's RUNTIME roles (shift/hold/exec/prepare/release) are READ-ONLY\n over owenloop's credential store \u2014 they never write credentials. Each\n role reads the agent:<account> slot for its origin (never the human\n slot); the account defaults to 'default'. 'owenloop work join' is the one\n deliberate provisioning-time writer: it stores the Scoped Identity token a hub\n redeem returns via owenloop's public storeCredential, once, at join time\n \u2014 not a runtime write.\n store / connect an account (run owenloop; owenloop work never writes it):\n owenloop login --hub <origin> --as agent:<account>\n (use --as agent for the default account)\n or provision a fresh box from a hub-issued join code:\n owenloop work join <code> --hub <origin>\n select an account at run time:\n --as <account> on shift / hold\n OWENLOOP_ACCOUNT on exec / prepare / release\n (shift resolves once and threads both channels)\n owenloop work does NOT list stored accounts \u2014 enumerating an origin's accounts\n is an owenloop-side capability; check owenloop for which slots are stored.\n\nExit codes:\n 0 success / help / version / lint clean or warnings-only\n 1 runtime failure (fetch/hub error, cache write) / lint found an error\n 2 usage error (unknown or missing role, missing required arg)\n 3 role not implemented yet (skeleton stub \u2014 lands in a later delivery)\n";
6
+ export declare const USAGE = "owenloop work \u2014 execution-side CLI companion to owenloop\n\nUsage:\n owenloop work hold --order <id> [options] hold an order with a heartbeating lease\n owenloop work exec <order-id> [options] run a command order in a self-leasing loop\n owenloop work agent-run <order-id> [options] host an agent order's step agent in a\n harness, in a self-leasing loop\n owenloop work prepare <workflow> [--origin <url>]\n fetch, cache & normalize step specs\n owenloop work lint <workflow-name | path> lint x.harness option bags in a def\n owenloop work sessions [--all] [--json] list this machine's recorded harness\n sessions and how to re-open them\n owenloop work approvals [--json] every tool call a worker is blocked on\n RIGHT NOW, waiting for a person\n owenloop work approvals approve|deny <wf>/<run> <tool-use-id> [--note <text>]\n answer one; the answer goes back to the\n still-blocked call, not to a later attempt\n owenloop work release --session <id> [options] drain a session's held claims\n owenloop work settings print the resolved settings file\n owenloop work join <code> [--hub <origin>] [--as <account>]\n redeem a join code and store the Scoped\n Identity credential (one-time provisioning)\n\nOptions:\n -h, --help show this help and exit 0\n --version print the owenloop work version and exit 0\n\n root shift options (run as owenloop shift start <crew...> | --all):\n <crew...> serve only these crews (positional, space\n separated); or --all for every crew on the key\n --all serve every crew on the key\n --origin <url> hub origin (else settings.hubOrigin)\n --as <account> Scoped Identity credential account to read + hand\n to dispatched holds/execs (default 'default')\n --name <n> Shift name (default <hostname>/<cwd>)\n --cap <n> max in-flight exec children (default 3)\n --poll-interval <ms> wake poll cadence (default 5000)\n --once bootstrap wake + one sweep, then exit (demo/e2e)\n --max-agents <n> max in-flight agent-run children, separate from\n --cap (default 4; else settings.maxConcurrentAgents)\n\t\t--exec-reserve <n> slots inside --cap that agent-run children may\n\t\t\t\t\tnot occupy, so exec orders always have room\n\t\t\t\t\t(default 1; else settings.execReserve; 0 disables)\n --local-queue-hold <ms> retain an undispatchable claim locally before\n\t\t\t\t\treturning it to the hub (default 0; else\n\t\t\t\t\tsettings.localQueueHoldMs; capped at 90000)\n --cache-dir/--state-dir <p> override the resolved dirs\n\n hold options:\n --order <workflow>/<run> the order to hold (or --order <run> --workflow)\n --workflow <wf> required when --order is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --as <account> Scoped Identity credential account (default\n 'default'; the shift stamps this into born-bound\n holds)\n --session <id> session-holder tag (else env OWENLOOP_SESSION;\n else an anon:<hostname>:<pid> fallback \u2014 a\n holder is always sent)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n --ignore-stdin don't final-breath on stdin EOF (detached use)\n --never-release another process holds the claim; stop without\n releasing it (agent-run spawns its --mcp child\n this way \u2014 see hold.ts HOLDER OF RECORD)\n --mcp run as a stdio-MCP work-holder: tools get_order /\n submit, lease kept warm underneath (mutually\n exclusive with --ignore-stdin \u2014 stdin is the\n transport)\n\n exec options (usually spawned by shift, not run by hand):\n <workflow>/<run> the command order to run (positional order-id;\n or a bare <run> plus --workflow <wf>)\n --workflow <wf> required when the order-id is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n\n agent-run options (spawned by the shift, not run by hand):\n <workflow>/<run> the agent order to host (positional order-id;\n or a bare <run> plus --workflow <wf>)\n --workflow <wf> required when the order-id is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --harness <id> which registered harness hosts the step agent\n (below a selected roster candidate; else the\n step def's 'harness' field, then the first\n registered one)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n --submit-grace <ms> after the turn ends, how long to keep asking the\n hub whether the agent's submit landed (default\n 15000). Task completion comes from the HUB, never\n from the harness stream.\n --confirm-interval <ms> poll cadence inside that grace (default 1000)\n\n release options:\n --session <id> session whose claims to drain (else env\n OWENLOOP_SESSION). Agent-held claims re-offer;\n exec-held claims are drain-exempt (B3).\n --origin <url> hub origin (else settings.hubOrigin)\n\n settings (no options in v1):\n prints the resolved settings file path, whether it exists, each known\n knob (hubOrigin, cacheDir, stateDir, dispatchCap, commandRouting,\n maxConcurrentAgents, execReserve, localQueueHoldMs, workRoot, workRepo) with its value + provenance,\n and any unrecognized keys.\n settings.dispatchCap/stateDir are the lowest-precedence\n fallbacks for shift's --cap/--state-dir. NO secrets ever\n live in settings \u2014 credentials stay in owenloop's own store.\n\n sessions options:\n --all include 'dead' sessions (hidden by default \u2014\n a dead session can no longer be resumed)\n --json print the raw newest-per-step records, tokens\n included, instead of the table\n --cache-dir <p> override the resolved cache dir\n\n join options:\n --hub <origin> hub to redeem against (else settings.hubOrigin;\n one of the two is REQUIRED \u2014 the code never\n chooses the hub)\n --as <account> credential account to store under (default:\n the Scoped Identity name the hub returns)\n\n shift/hold/exec/prepare/release env:\n credentials come from owenloop's store \u2014 each role reads the\n agent:<account> slot for its origin (never the human slot); a\n missing slot refuses with a runnable 'owenloop login' command.\n OWENLOOP_ACCOUNT Scoped Identity account for exec/prepare/release\n (default 'default'; shift uses --as, and\n stamps it onto dispatched holds/execs)\n OWENLOOP_TOKEN dev-only bearer override \u2014 when set, used\n verbatim and the store + account are\n bypassed (NOT the primary path)\n OWENLOOP_CACHE_DIR cache root\n OWENLOOP_STATE_DIR shift in-flight state dir\n OWENLOOP_SHIFT_LOG_DIR dir for the shift's shift.log and each\n worker's <run>.log; below --log-dir, above\n settings.shiftLogDir, default the state dir\n OWENLOOP_SHIFT_LOG_MAX_AGE_MS\n how long a worker's <run>.log is kept, in ms;\n below --log-max-age, above\n settings.shiftLogMaxAgeMs, default 14 days.\n Worker logs only \u2014 shift.log is never reaped\n OWENLOOP_SESSION hold session-holder tag / release drain target\n OWENLOOP_SHIFT_ID dispatching Shift's self-declared id for\n hold/exec/agent-run's --shift (advisory\n only, never for auth/routing/dispatch)\n OWENLOOP_WORK_ROOT root for per-RUN agent work dirs\n (<workRoot>/<workflow>/<run>); above\n settings.workRoot, default <cacheDir>/work.\n A hub-supplied OrderPacket.workdir still\n wins, and is never reaped.\n OWENLOOP_WORK_REPO local git repo to cut per-run work dirs from\n as worktrees instead of plain dirs; above\n settings.workRepo, default off\n\n Credentials / accounts:\n owenloop work's RUNTIME roles (shift/hold/exec/prepare/release) are READ-ONLY\n over owenloop's credential store \u2014 they never write credentials. Each\n role reads the agent:<account> slot for its origin (never the human\n slot); the account defaults to 'default'. 'owenloop work join' is the one\n deliberate provisioning-time writer: it stores the Scoped Identity token a hub\n redeem returns via owenloop's public storeCredential, once, at join time\n \u2014 not a runtime write.\n store / connect an account (run owenloop; owenloop work never writes it):\n owenloop login --hub <origin> --as agent:<account>\n (use --as agent for the default account)\n or provision a fresh box from a hub-issued join code:\n owenloop work join <code> --hub <origin>\n select an account at run time:\n --as <account> on shift / hold\n OWENLOOP_ACCOUNT on exec / prepare / release\n (shift resolves once and threads both channels)\n owenloop work does NOT list stored accounts \u2014 enumerating an origin's accounts\n is an owenloop-side capability; check owenloop for which slots are stored.\n\nExit codes:\n 0 success / help / version / lint clean or warnings-only\n 1 runtime failure (fetch/hub error, cache write) / lint found an error\n 2 usage error (unknown or missing role, missing required arg)\n 3 role not implemented yet (skeleton stub \u2014 lands in a later delivery)\n";
@@ -43,6 +43,12 @@ Options:
43
43
  --once bootstrap wake + one sweep, then exit (demo/e2e)
44
44
  --max-agents <n> max in-flight agent-run children, separate from
45
45
  --cap (default 4; else settings.maxConcurrentAgents)
46
+ --exec-reserve <n> slots inside --cap that agent-run children may
47
+ not occupy, so exec orders always have room
48
+ (default 1; else settings.execReserve; 0 disables)
49
+ --local-queue-hold <ms> retain an undispatchable claim locally before
50
+ returning it to the hub (default 0; else
51
+ settings.localQueueHoldMs; capped at 90000)
46
52
  --cache-dir/--state-dir <p> override the resolved dirs
47
53
 
48
54
  hold options:
@@ -109,7 +115,7 @@ Options:
109
115
  settings (no options in v1):
110
116
  prints the resolved settings file path, whether it exists, each known
111
117
  knob (hubOrigin, cacheDir, stateDir, dispatchCap, commandRouting,
112
- maxConcurrentAgents, workRoot, workRepo) with its value + provenance,
118
+ maxConcurrentAgents, execReserve, localQueueHoldMs, workRoot, workRepo) with its value + provenance,
113
119
  and any unrecognized keys.
114
120
  settings.dispatchCap/stateDir are the lowest-precedence
115
121
  fallbacks for shift's --cap/--state-dir. NO secrets ever
@@ -0,0 +1,7 @@
1
+ /** Resolve requested feedback first, then the order modifier hint, then default. */
2
+ export declare function resolveModifierInit(args: string[], env?: Record<string, string | undefined>): {
3
+ value?: string;
4
+ error?: string;
5
+ usage?: true;
6
+ };
7
+ export declare function runModifierInit(args: string[], env?: Record<string, string | undefined>): number;
@@ -0,0 +1,73 @@
1
+ import { readFileSync } from 'node:fs';
2
+ function usage(message) {
3
+ process.stderr.write(`owenloop util modifier-init: ${message}\n`);
4
+ process.stderr.write('usage: owenloop util modifier-init --default <value>\n');
5
+ return 2;
6
+ }
7
+ function feedbackRequested(env) {
8
+ const inline = env['OWENLOOP_FEEDBACK'];
9
+ const file = env['OWENLOOP_FEEDBACK_FILE'];
10
+ let raw;
11
+ if (inline !== undefined)
12
+ raw = inline;
13
+ else if (file !== undefined)
14
+ raw = readFileSync(file, 'utf8');
15
+ if (raw === undefined)
16
+ return undefined;
17
+ const feedback = JSON.parse(raw);
18
+ if (!Array.isArray(feedback))
19
+ throw new Error('OWENLOOP_FEEDBACK must be a JSON feedback array');
20
+ let newest;
21
+ let position = 0;
22
+ for (const owed of feedback) {
23
+ if (!Array.isArray(owed.reasons))
24
+ continue;
25
+ const rejection = [...owed.reasons].reverse().find((reason) => reason.action === 'reject');
26
+ position++;
27
+ if (typeof rejection?.requested !== 'string')
28
+ continue;
29
+ const at = typeof rejection.at === 'number' ? rejection.at : Number.NEGATIVE_INFINITY;
30
+ if (newest === undefined
31
+ || at > newest.at
32
+ || (at === newest.at && position > newest.position)) {
33
+ newest = { requested: rejection.requested, at, position };
34
+ }
35
+ }
36
+ return newest?.requested;
37
+ }
38
+ /** Resolve requested feedback first, then the order modifier hint, then default. */
39
+ export function resolveModifierInit(args, env = process.env) {
40
+ let fallback;
41
+ for (let i = 0; i < args.length; i++) {
42
+ const arg = args[i];
43
+ if (arg !== '--default')
44
+ return { error: `unknown argument '${arg}'`, usage: true };
45
+ if (fallback !== undefined)
46
+ return { error: '--default may only be specified once', usage: true };
47
+ fallback = args[++i];
48
+ if (fallback === undefined)
49
+ return { error: 'missing value for --default', usage: true };
50
+ }
51
+ if (fallback === undefined)
52
+ return { error: 'missing required option: --default', usage: true };
53
+ try {
54
+ const value = feedbackRequested(env) ?? env['OWENLOOP_MODIFIER'] ?? fallback;
55
+ if (value === '' || /\s/.test(value))
56
+ return { error: 'resolved modifier must be a single word' };
57
+ return { value };
58
+ }
59
+ catch (e) {
60
+ return { error: e instanceof Error ? e.message : String(e) };
61
+ }
62
+ }
63
+ export function runModifierInit(args, env = process.env) {
64
+ const result = resolveModifierInit(args, env);
65
+ if (result.error !== undefined) {
66
+ if (result.usage)
67
+ return usage(result.error);
68
+ process.stderr.write(`owenloop util modifier-init: ${result.error}\n`);
69
+ return 3;
70
+ }
71
+ process.stdout.write(`${result.value}\n`);
72
+ return 0;
73
+ }
@@ -30,10 +30,15 @@ export declare const BUNDLE_GZIP_LEVEL = 9;
30
30
  */
31
31
  export declare function buildCanonicalTar(files: CanonicalFile[], limits?: TarLimits): Buffer;
32
32
  /**
33
- * Gzip `tar` with fixed options and a normalized header: no FEXTRA/FNAME/
34
- * FCOMMENT, mtime bytes zeroed, OS byte forced to 0. Node's zlib reports
35
- * OS 19 on Darwin and embeds the clock in mtime by default — patch both so
36
- * the output is byte-identical across platforms and times.
33
+ * Gzip `tar` with fixed options and controlled header ranges: magic (bytes
34
+ * 0-1), CM (2), FLG (3), MTIME (4-7), and OS (9). No FEXTRA/FNAME/FCOMMENT
35
+ * fields are emitted. Node's zlib reports OS 19 on Darwin and embeds the clock
36
+ * in mtime by default, so patch bytes 4-7 and 9 to fixed values. XFL (byte 8)
37
+ * is supplied by zlib and deliberately left unnormalized.
38
+ *
39
+ * The compressed DEFLATE payload is not normalized: linked zlib builds can
40
+ * emit different valid streams for the same input. Bundle identity is the
41
+ * SHA-256 digest of the uncompressed canonical tar.
37
42
  */
38
43
  export declare function gzipDeterministic(tar: Uint8Array): Buffer;
39
44
  /** A file collected from a bundle source tree. */
@@ -146,10 +146,15 @@ export function buildCanonicalTar(files, limits = DEFAULT_TAR_LIMITS) {
146
146
  return tar;
147
147
  }
148
148
  /**
149
- * Gzip `tar` with fixed options and a normalized header: no FEXTRA/FNAME/
150
- * FCOMMENT, mtime bytes zeroed, OS byte forced to 0. Node's zlib reports
151
- * OS 19 on Darwin and embeds the clock in mtime by default — patch both so
152
- * the output is byte-identical across platforms and times.
149
+ * Gzip `tar` with fixed options and controlled header ranges: magic (bytes
150
+ * 0-1), CM (2), FLG (3), MTIME (4-7), and OS (9). No FEXTRA/FNAME/FCOMMENT
151
+ * fields are emitted. Node's zlib reports OS 19 on Darwin and embeds the clock
152
+ * in mtime by default, so patch bytes 4-7 and 9 to fixed values. XFL (byte 8)
153
+ * is supplied by zlib and deliberately left unnormalized.
154
+ *
155
+ * The compressed DEFLATE payload is not normalized: linked zlib builds can
156
+ * emit different valid streams for the same input. Bundle identity is the
157
+ * SHA-256 digest of the uncompressed canonical tar.
153
158
  */
154
159
  export function gzipDeterministic(tar) {
155
160
  const gz = gzipSync(Buffer.from(tar), { level: BUNDLE_GZIP_LEVEL });
@@ -1,18 +1,23 @@
1
1
  /**
2
2
  * Routing capabilities: composition at offer time, and the claim-side match.
3
3
  *
4
- * Three vocabularies meet here and must not be confused:
4
+ * Four vocabularies meet here and must not be confused:
5
5
  *
6
6
  * - **Authored capability** — what a def writes on a step (`wise`). Never
7
7
  * contains the separator; the parser rejects one that does.
8
+ * - **Org capability** — the name this org actually routes on, which for a
9
+ * def installed from elsewhere may be a scoped form of the authored name.
10
+ * Substituted for the authored one BEFORE composition, and only when the
11
+ * caller supplies a mapping; absent a mapping the two are the same string.
8
12
  * - **Modifier** — the ONE plain name a run carries (`deep`). Optional. The
9
13
  * engine attaches no meaning, no order and no arithmetic to it.
10
- * - **Compound capability** — `<authored>:<modifier>` (`wise:deep`), composed
11
- * by the engine when it builds an order. Only the engine composes it.
14
+ * - **Compound capability** — `<org>:<modifier>` (`wise:deep`), composed by
15
+ * the engine when it builds an order. Only the engine composes it.
12
16
  *
13
- * Nothing here reads the store, the def or the clock. Composition is a pure
14
- * function of (authored capabilities, modifier); matching is a pure function of
15
- * (offered capabilities, caller capabilities, per-capability match mode).
17
+ * Nothing here reads the store, the def or the clock. Mapping is a pure
18
+ * function of (authored capabilities, mappings); composition is a pure function
19
+ * of (capabilities, modifier); matching is a pure function of (offered
20
+ * capabilities, caller capabilities, per-capability match mode).
16
21
  */
17
22
  /**
18
23
  * The character the engine reserves as the capability/modifier separator.
@@ -62,6 +67,41 @@ export declare function capabilityName(capability: string): string;
62
67
  * compose onto, and inventing a lone `:deep` would be meaningless.
63
68
  */
64
69
  export declare function composeCapabilities(authored: readonly string[] | undefined, modifier: string | undefined): string[];
70
+ /**
71
+ * A per-run substitution from an AUTHORED capability to the capability string
72
+ * this org actually routes on, applied BEFORE composition.
73
+ *
74
+ * `{ coding: 'repo-a-flow.coding' }` means: wherever a step of this run
75
+ * authored `coding`, offer the org's `repo-a-flow.coding` instead — so under
76
+ * modifier `deep` the offer composes to `repo-a-flow.coding:deep`, never
77
+ * `coding:deep`. Two vocabularies meet in one entry: the KEY is the authored
78
+ * name a def wrote, the VALUE is the name the org's crews are bound to.
79
+ *
80
+ * The reason it exists: a def that entered the org from a third party must be
81
+ * scoped by default, because two unrelated defs may both author `coding` and
82
+ * nothing should make them share crews by accident. Scoping is expressed as a
83
+ * mapping rather than a def edit so the def content stays byte-exact with its
84
+ * source and re-installs cleanly.
85
+ *
86
+ * The engine ENFORCES a mapping, it never CHOOSES one — same doctrine as
87
+ * `matchModes` and `capabilityRewrites`, and for the same reason: choosing
88
+ * means reading an install-scoped routing table the pure engine has never seen.
89
+ * The caller that owns that table hands the map down per tick.
90
+ *
91
+ * DISTINCT FROM `CapabilityRewrites`, which must not be reused for this. A
92
+ * mapping is applied BEFORE composition and is keyed by the AUTHORED name, so
93
+ * one entry covers every modifier including escalation targets and the
94
+ * no-modifier case. A rewrite is applied AFTER composition and is keyed by the
95
+ * COMPOSED string, so the same intent would need one entry per
96
+ * (capability x modifier) pair, and would collide with the reroute decisions
97
+ * that already own that key space. Both may apply within a single tick, in
98
+ * that order: authored → mapped → composed → rewritten → offered.
99
+ *
100
+ * SINGLE HOP, BY CONTRACT, exactly as for a rewrite: a mapped value is never
101
+ * itself looked up in the map, and is never inspected or validated. The caller
102
+ * resolves any chain and validates any target before calling.
103
+ */
104
+ export type CapabilityMappings = Readonly<Record<string, string>>;
65
105
  /**
66
106
  * A reroute decision the caller has already made, keyed by the composed
67
107
  * capability the engine would otherwise offer.
@@ -79,6 +119,36 @@ export declare function composeCapabilities(authored: readonly string[] | undefi
79
119
  * bounded.
80
120
  */
81
121
  export type CapabilityRewrites = Readonly<Record<string, string>>;
122
+ /**
123
+ * Crews matched per SERVED capability, supplied by the caller that owns the
124
+ * routing table. Keys are post-reroute capability strings; values are crew
125
+ * names in match order. Hub → worker; unrelated to `serve_crews`.
126
+ */
127
+ export type CrewStamps = Readonly<Record<string, readonly string[]>>;
128
+ /**
129
+ * Substitute a caller's capability mappings into a step's AUTHORED list, before
130
+ * that list is composed with the run's modifier. See `CapabilityMappings` for
131
+ * what a mapping is and why it is not a rewrite.
132
+ *
133
+ * An authored list no entry applies to is returned BY REFERENCE — the identical
134
+ * array, not a copy — and `undefined` and `[]` fall straight through. That is
135
+ * what makes an absent or empty map exact identity rather than merely
136
+ * equivalent: with `{}` the composition downstream receives byte-for-byte what
137
+ * it received before this pass existed, so no caller can observe the pass at
138
+ * all. It also preserves multiplicity, which matters: a step may author
139
+ * `capabilities: ['a', 'a']` (the parser validates each entry but never rejects
140
+ * a duplicate) and an untouched offer must still stamp both.
141
+ *
142
+ * Duplicates ARE removed once an entry actually fires, mirroring
143
+ * `applyCapabilityRewrites`: two authored names may map onto one org name, and
144
+ * an offer listing it twice would read as a mistake. Dedup is a consequence of
145
+ * mapping, never a tidy-up applied on the way past.
146
+ *
147
+ * Lookup is by OWN property. Keys here are arbitrary authored words, so a step
148
+ * authoring `constructor` or `toString` must resolve to "no entry" rather than
149
+ * to an inherited `Object.prototype` member.
150
+ */
151
+ export declare function applyCapabilityMappings(authored: readonly string[] | undefined, mappings: CapabilityMappings): readonly string[] | undefined;
82
152
  /**
83
153
  * Substitute a caller's reroute decisions into a composed offer.
84
154
  *
@@ -1,18 +1,23 @@
1
1
  /**
2
2
  * Routing capabilities: composition at offer time, and the claim-side match.
3
3
  *
4
- * Three vocabularies meet here and must not be confused:
4
+ * Four vocabularies meet here and must not be confused:
5
5
  *
6
6
  * - **Authored capability** — what a def writes on a step (`wise`). Never
7
7
  * contains the separator; the parser rejects one that does.
8
+ * - **Org capability** — the name this org actually routes on, which for a
9
+ * def installed from elsewhere may be a scoped form of the authored name.
10
+ * Substituted for the authored one BEFORE composition, and only when the
11
+ * caller supplies a mapping; absent a mapping the two are the same string.
8
12
  * - **Modifier** — the ONE plain name a run carries (`deep`). Optional. The
9
13
  * engine attaches no meaning, no order and no arithmetic to it.
10
- * - **Compound capability** — `<authored>:<modifier>` (`wise:deep`), composed
11
- * by the engine when it builds an order. Only the engine composes it.
14
+ * - **Compound capability** — `<org>:<modifier>` (`wise:deep`), composed by
15
+ * the engine when it builds an order. Only the engine composes it.
12
16
  *
13
- * Nothing here reads the store, the def or the clock. Composition is a pure
14
- * function of (authored capabilities, modifier); matching is a pure function of
15
- * (offered capabilities, caller capabilities, per-capability match mode).
17
+ * Nothing here reads the store, the def or the clock. Mapping is a pure
18
+ * function of (authored capabilities, mappings); composition is a pure function
19
+ * of (capabilities, modifier); matching is a pure function of (offered
20
+ * capabilities, caller capabilities, per-capability match mode).
16
21
  */
17
22
  /**
18
23
  * The character the engine reserves as the capability/modifier separator.
@@ -55,6 +60,44 @@ export function composeCapabilities(authored, modifier) {
55
60
  return [...authored];
56
61
  return authored.map((c) => `${c}${MODIFIER_SEPARATOR}${modifier}`);
57
62
  }
63
+ /**
64
+ * Substitute a caller's capability mappings into a step's AUTHORED list, before
65
+ * that list is composed with the run's modifier. See `CapabilityMappings` for
66
+ * what a mapping is and why it is not a rewrite.
67
+ *
68
+ * An authored list no entry applies to is returned BY REFERENCE — the identical
69
+ * array, not a copy — and `undefined` and `[]` fall straight through. That is
70
+ * what makes an absent or empty map exact identity rather than merely
71
+ * equivalent: with `{}` the composition downstream receives byte-for-byte what
72
+ * it received before this pass existed, so no caller can observe the pass at
73
+ * all. It also preserves multiplicity, which matters: a step may author
74
+ * `capabilities: ['a', 'a']` (the parser validates each entry but never rejects
75
+ * a duplicate) and an untouched offer must still stamp both.
76
+ *
77
+ * Duplicates ARE removed once an entry actually fires, mirroring
78
+ * `applyCapabilityRewrites`: two authored names may map onto one org name, and
79
+ * an offer listing it twice would read as a mistake. Dedup is a consequence of
80
+ * mapping, never a tidy-up applied on the way past.
81
+ *
82
+ * Lookup is by OWN property. Keys here are arbitrary authored words, so a step
83
+ * authoring `constructor` or `toString` must resolve to "no entry" rather than
84
+ * to an inherited `Object.prototype` member.
85
+ */
86
+ export function applyCapabilityMappings(authored, mappings) {
87
+ if (authored === undefined || authored.length === 0)
88
+ return authored;
89
+ let changed = false;
90
+ const out = [];
91
+ for (const c of authored) {
92
+ const target = Object.prototype.hasOwnProperty.call(mappings, c) ? mappings[c] : undefined;
93
+ const next = target ?? c;
94
+ if (target !== undefined && target !== c)
95
+ changed = true;
96
+ if (!out.includes(next))
97
+ out.push(next);
98
+ }
99
+ return changed ? out : authored;
100
+ }
58
101
  /**
59
102
  * Substitute a caller's reroute decisions into a composed offer.
60
103
  *
@@ -0,0 +1,29 @@
1
+ /** `GET`/`POST` against the resolved hub with a bearer credential already applied. */
2
+ export interface CapabilityMappingTransport {
3
+ get(path: string): Promise<Response>;
4
+ post(path: string, body: unknown): Promise<Response>;
5
+ }
6
+ /** Read half of the contract — shipped. */
7
+ export declare const CAPABILITY_MAPPINGS_READ_PATH = "/api/capability_mappings";
8
+ /** Write half of the contract — the PLURAL verb no shipped hub has yet. */
9
+ export declare const CAPABILITY_MAPPINGS_WRITE_PATH = "/api/set_capability_mappings";
10
+ /**
11
+ * Read the `authored → org` mappings already recorded for `defName`.
12
+ *
13
+ * Returns `'unsupported'` — a sentinel, not an empty map — when the hub has no
14
+ * such endpoint. The distinction is load-bearing: an empty map means "this def
15
+ * has no mapping recorded", so nothing needs carrying forward, while
16
+ * `'unsupported'` means "this hub cannot tell you", and the caller must warn
17
+ * before it asks the operator about capabilities that may already be linked.
18
+ */
19
+ export declare function fetchCapabilityMappings(transport: CapabilityMappingTransport, defName: string, origin: string): Promise<Record<string, string> | 'unsupported'>;
20
+ /**
21
+ * Record `authored → org` mappings for `defName`, replacing what is stored for
22
+ * the authored names it names.
23
+ *
24
+ * A hub without the endpoint is a **hard, exit-2 failure naming the missing
25
+ * verb** — never a warning and never a silent skip. `install` calls this BEFORE
26
+ * it publishes precisely so this failure leaves nothing half-applied: no def
27
+ * has been pushed, so the org vocabulary is untouched.
28
+ */
29
+ export declare function recordCapabilityMappings(transport: CapabilityMappingTransport, defName: string, mappings: Record<string, string>, origin: string): Promise<void>;
@@ -0,0 +1,160 @@
1
+ /**
2
+ * The two hub endpoints `owenloop install` needs, deliberately confined to this
3
+ * one file.
4
+ *
5
+ * ## Read this before changing a path or a body key
6
+ *
7
+ * The READ half is LIVE. `owenloop-service` ships
8
+ * `GET /api/capability_mappings` (optional `?def=<name>`), backed by the
9
+ * `capability_mappings` table PR #222 built and the offer-time resolver that
10
+ * consumes it. Its body is a ROW ARRAY, not the compact map this file first
11
+ * proposed — `asCapabilityMappings` accepts both and the difference is
12
+ * explained there, not here.
13
+ *
14
+ * The WRITE half `install` needs is STILL MISSING, and the gap is narrower than
15
+ * it looks. The hub ships `POST /api/set_capability_mapping` — SINGULAR, ONE
16
+ * ROW per call, `{defName, authored, target}` — which is the right shape for an
17
+ * operator repointing one capability by hand. `install` needs the PLURAL
18
+ * `POST /api/set_capability_mappings` `{def, mappings}` instead, and the plural
19
+ * is not sugar over N singular calls:
20
+ *
21
+ * - **One transaction or none.** `install` publishes the def the instant this
22
+ * returns. A loop that fails on its fourth capability leaves three rows
23
+ * written and then either publishes a half-scoped def or must unwind writes
24
+ * it cannot unwind atomically. The whole reason the mapping is recorded
25
+ * BEFORE the publish is that a failure must leave NOTHING applied.
26
+ * - **One audit act.** An install remaps a def's whole vocabulary in one
27
+ * operator decision. N audit rows for one act is a worse record of it.
28
+ *
29
+ * `POST /api/create_workflow`'s input surface is `yaml`, `bundle_digest`,
30
+ * `owner_crew_id`. An extra body key on it would be **silently ignored, not
31
+ * rejected** — the mapping would vanish with no error, the worst available
32
+ * failure mode. That is why the mapping travels as its own call and why this
33
+ * module is a single reconciliation point.
34
+ *
35
+ * ## Contract
36
+ *
37
+ * ```
38
+ * GET /api/capability_mappings?def=<name> ← LIVE
39
+ * 200 { mappings: [ { defName, authored, target, … }, … ] }
40
+ * 200 { ok: true, mappings: { <authored>: <orgName>, … } } (older hubs)
41
+ * 404 | 501 → the hub does not implement it
42
+ *
43
+ * POST /api/set_capability_mappings ← NOT YET SHIPPED
44
+ * body { def: <name>, mappings: { <authored>: <orgName>, … } }
45
+ * 200 { ok: true }
46
+ * 404 | 501 → the hub does not implement it
47
+ * ```
48
+ *
49
+ * Identity entries (`orgName === authored`) are dropped hub-side by the
50
+ * resolver, so a caller whose every entry is the identity must skip the write
51
+ * entirely rather than post a no-op — see `dispatchInstall`.
52
+ *
53
+ * ## Transport
54
+ *
55
+ * Both calls take an injected `CapabilityMappingTransport` rather than
56
+ * importing a fetch helper: `cli.ts` builds it from `authedGet` / `authedPost`,
57
+ * so these calls inherit `ensureFreshOAuth`, the single 401-refresh-and-retry,
58
+ * `hubFetch`'s 30s deadline, its bounded body read and `redirect: 'error'`,
59
+ * without this module importing `cli.ts` (which would be an import cycle and a
60
+ * boundary violation).
61
+ *
62
+ * Error discipline mirrors `dispatchCapability`: a 401 that survived the retry
63
+ * is the "credential rejected" wording the caller upgrades to exit 3; any other
64
+ * non-2xx surfaces the hub's typed `message` VERBATIM and never raw body text;
65
+ * a malformed JSON body is a FIXED string, never V8's `SyntaxError` (which
66
+ * embeds a snippet of the body).
67
+ */
68
+ import { asCapabilityMappings } from "./hub.js";
69
+ import { CliError } from "./util.js";
70
+ /** Read half of the contract — shipped. */
71
+ export const CAPABILITY_MAPPINGS_READ_PATH = '/api/capability_mappings';
72
+ /** Write half of the contract — the PLURAL verb no shipped hub has yet. */
73
+ export const CAPABILITY_MAPPINGS_WRITE_PATH = '/api/set_capability_mappings';
74
+ /**
75
+ * A status that means "this hub build does not have the endpoint at all",
76
+ * as distinct from "the endpoint rejected this request".
77
+ *
78
+ * `404` is what a hub edge with no such route answers; `501` is what one that
79
+ * knows the route but has not implemented the verb would answer. Both are
80
+ * capability probes, never request-level failures — no other status is treated
81
+ * as one, so a `400` or `403` stays a loud error.
82
+ */
83
+ function isUnimplemented(status) {
84
+ return status === 404 || status === 501;
85
+ }
86
+ /** The hub's typed `message`, or `undefined` when the body carries none. */
87
+ async function hubMessage(res) {
88
+ try {
89
+ const body = (await res.json());
90
+ if (typeof body === 'object' && body !== null) {
91
+ const m = body.message;
92
+ if (typeof m === 'string' && m !== '')
93
+ return m;
94
+ }
95
+ }
96
+ catch {
97
+ // Non-JSON body — the caller falls through to a generic status message.
98
+ }
99
+ return undefined;
100
+ }
101
+ /** The 401-then-non-2xx ladder both calls share, worded per endpoint. */
102
+ async function assertCallOk(res, origin) {
103
+ if (res.status === 401) {
104
+ // Survived the transport's one refresh-and-retry. The caller's catch
105
+ // upgrades this exact wording to exit 3, the way `dispatchCapability` does.
106
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
107
+ }
108
+ if (!res.ok) {
109
+ throw new CliError((await hubMessage(res)) ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
110
+ }
111
+ }
112
+ /**
113
+ * Read the `authored → org` mappings already recorded for `defName`.
114
+ *
115
+ * Returns `'unsupported'` — a sentinel, not an empty map — when the hub has no
116
+ * such endpoint. The distinction is load-bearing: an empty map means "this def
117
+ * has no mapping recorded", so nothing needs carrying forward, while
118
+ * `'unsupported'` means "this hub cannot tell you", and the caller must warn
119
+ * before it asks the operator about capabilities that may already be linked.
120
+ */
121
+ export async function fetchCapabilityMappings(transport, defName, origin) {
122
+ const res = await transport.get(`${CAPABILITY_MAPPINGS_READ_PATH}?def=${encodeURIComponent(defName)}`);
123
+ if (isUnimplemented(res.status))
124
+ return 'unsupported';
125
+ await assertCallOk(res, origin);
126
+ let body;
127
+ try {
128
+ body = (await res.json());
129
+ }
130
+ catch {
131
+ throw new CliError('capability_mappings: malformed success response — body is not valid JSON');
132
+ }
133
+ try {
134
+ return asCapabilityMappings(body, defName);
135
+ }
136
+ catch (e) {
137
+ throw new CliError(e.message);
138
+ }
139
+ }
140
+ /**
141
+ * Record `authored → org` mappings for `defName`, replacing what is stored for
142
+ * the authored names it names.
143
+ *
144
+ * A hub without the endpoint is a **hard, exit-2 failure naming the missing
145
+ * verb** — never a warning and never a silent skip. `install` calls this BEFORE
146
+ * it publishes precisely so this failure leaves nothing half-applied: no def
147
+ * has been pushed, so the org vocabulary is untouched.
148
+ */
149
+ export async function recordCapabilityMappings(transport, defName, mappings, origin) {
150
+ const res = await transport.post(CAPABILITY_MAPPINGS_WRITE_PATH, { def: defName, mappings });
151
+ if (isUnimplemented(res.status)) {
152
+ throw new CliError(`hub ${origin} does not implement POST ${CAPABILITY_MAPPINGS_WRITE_PATH} (HTTP ${res.status}) — ` +
153
+ 'it cannot record a def\'s mapping in one transaction, so this def was NOT published. ' +
154
+ 'This hub may still have the SINGULAR /api/set_capability_mapping, which writes one row per ' +
155
+ 'call; install does not use it, because a partial write followed by a publish is exactly the ' +
156
+ 'half-applied state recording-before-publishing exists to prevent. Until the batch verb ships, ' +
157
+ 'only an identity mapping (every capability keeping its authored name) can be installed.', { exitCode: 2 });
158
+ }
159
+ await assertCallOk(res, origin);
160
+ }