owenloop 0.5.7 → 0.5.8

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 (65) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +3 -6
  3. package/dist/packages/work/src/agent/capability-model.d.ts +64 -82
  4. package/dist/packages/work/src/agent/capability-model.js +94 -91
  5. package/dist/packages/work/src/agent/loop.d.ts +39 -25
  6. package/dist/packages/work/src/agent/loop.js +102 -50
  7. package/dist/packages/work/src/bundle/types.d.ts +3 -3
  8. package/dist/packages/work/src/exec/loop.js +37 -15
  9. package/dist/packages/work/src/harness/child-env.js +4 -5
  10. package/dist/packages/work/src/harness/codex.js +3 -4
  11. package/dist/packages/work/src/harness/session-store.d.ts +63 -3
  12. package/dist/packages/work/src/harness/session-store.js +104 -9
  13. package/dist/packages/work/src/hub/types.d.ts +3 -3
  14. package/dist/packages/work/src/roles/agent-run.js +48 -42
  15. package/dist/packages/work/src/roles/sessions.d.ts +3 -2
  16. package/dist/packages/work/src/roles/sessions.js +9 -2
  17. package/dist/packages/work/src/roles/settings.js +1 -1
  18. package/dist/packages/work/src/settings/roster.d.ts +21 -0
  19. package/dist/packages/work/src/settings/roster.js +80 -0
  20. package/dist/packages/work/src/settings/settings.d.ts +12 -24
  21. package/dist/packages/work/src/settings/settings.js +17 -35
  22. package/dist/packages/work/src/shift/runtime.js +2 -10
  23. package/dist/packages/work/src/shift/spawn.d.ts +6 -53
  24. package/dist/packages/work/src/shift/spawn.js +28 -66
  25. package/dist/packages/work/src/usage.d.ts +1 -1
  26. package/dist/packages/work/src/usage.js +3 -4
  27. package/dist/src/capabilities.d.ts +44 -0
  28. package/dist/src/capabilities.js +38 -0
  29. package/dist/src/cli.d.ts +1 -0
  30. package/dist/src/cli.js +460 -5
  31. package/dist/src/config-dir.d.ts +13 -18
  32. package/dist/src/config-dir.js +15 -23
  33. package/dist/src/credentials.d.ts +1 -1
  34. package/dist/src/credentials.js +1 -1
  35. package/dist/src/crypto/records.d.ts +1 -0
  36. package/dist/src/crypto/records.js +6 -0
  37. package/dist/src/crypto/trust-roots.d.ts +2 -2
  38. package/dist/src/crypto/trust-roots.js +2 -2
  39. package/dist/src/engine.d.ts +14 -0
  40. package/dist/src/engine.js +21 -13
  41. package/dist/src/global-config.d.ts +4 -7
  42. package/dist/src/global-config.js +4 -7
  43. package/dist/src/hub.d.ts +207 -5
  44. package/dist/src/hub.js +263 -3
  45. package/dist/src/index.d.ts +2 -2
  46. package/dist/src/index.js +1 -1
  47. package/dist/src/schemas/index.d.ts +8 -0
  48. package/dist/src/schemas/order.v1.schema.json +6 -1
  49. package/dist/src/store/pre-commit-verifier.js +1 -1
  50. package/dist/src/types.d.ts +24 -4
  51. package/dist/src/work-settings.d.ts +2 -4
  52. package/dist/src/work-settings.js +2 -4
  53. package/docs/agent-runner.md +2 -2
  54. package/docs/bundles.md +3 -1
  55. package/docs/cli.md +295 -101
  56. package/docs/crypto.md +14 -14
  57. package/docs/routing.md +607 -0
  58. package/docs/shift-logs.md +22 -6
  59. package/package.json +1 -1
  60. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  61. package/plugins/claude-code/plugin/.mcp.json +1 -1
  62. package/plugins/claude-code/plugin/skills/author/SKILL.md +1 -2
  63. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  64. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  65. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +1 -2
package/dist/src/cli.js CHANGED
@@ -32,7 +32,7 @@
32
32
  *
33
33
  * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
34
34
  */
35
- import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
35
+ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
36
36
  import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
37
37
  import { spawn, spawnSync } from 'node:child_process';
38
38
  import { createServer } from 'node:http';
@@ -61,8 +61,12 @@ import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
61
61
  import { BundleError, digestBundle, inspectBundle, packBundle, unpackBundle } from "./bundle/index.js";
62
62
  import { acquireInstallLock, ADD_JOURNAL_FILENAME, archivePathViolation, commitInstall, finalizeInstallCommit, githubShaUrl, githubTarballUrl, installFolder, parkOldNameDir, parseRepoSpec, readLockfile, recoverInterruptedInstall, releaseInstallLock, removeAddJournal, rmRecursiveForce, rollbackInstallCommit, RollbackFailedError, stageFiles, STAGING_DIRNAME, writeAddJournal, writeLockfile, } from "./add.js";
63
63
  import { BundleIngestorUnavailableError, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, projectStoreRoot, createBundleIngestor, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.js";
64
- import { asAgentIdentities, asCreateWorkflowOk, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, DEFAULT_HUB, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
64
+ import { asAgentIdentities, asCreateWorkflowOk, asCapabilityRerouteAdded, asCapabilityRerouteRemoved, asCapabilityReroutes, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, asRoutingAlerts, asRunRouting, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, DEFAULT_HUB, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
65
65
  import { loadSettings, settingsPath as executionSettingsPath } from "../packages/work/src/settings/settings.js";
66
+ import { machineRosterLayers, mergeRosterLayers } from "../packages/work/src/settings/roster.js";
67
+ import { adapterFor } from "../packages/work/src/harness/registry.js";
68
+ import "../packages/work/src/harnesses.js";
69
+ import { owenloopConfigDir } from "./config-dir.js";
66
70
  import { owenloopSettingsPath, readOwenloopSettingsRaw, writeOwenloopHubOrigin } from "./work-settings.js";
67
71
  import { globalConfigPath, writeGlobalConfig } from "./global-config.js";
68
72
  import { canonicalJsonBytes, defaultRecoveryMarkerDir, ensureDirectoryPathNoSymlink, guardStateFile } from "./install.js";
@@ -1132,11 +1136,22 @@ ${' '.repeat(41)}terminal status \`cancelled\`. Cancelling an already-terminal i
1132
1136
  instance show <workflow> [--hub <url>]
1133
1137
  ${' '.repeat(41)}print one instance's live state on the bound hub: whether it is done, what it
1134
1138
  ${' '.repeat(41)}owes, which steps are eligible or blocked, which runs are in flight, and whether
1135
- ${' '.repeat(41)}the loaded def has drifted from the version the instance is pinned to.
1139
+ ${' '.repeat(41)}the loaded def has drifted from the version the instance is pinned to, and whether
1140
+ ${' '.repeat(41)}the instance has reached a terminal status.
1136
1141
  agent new <name> [--crews <a,b>] [--scopes <a,b>] [--shift] [--hub <url>] mint a new Scoped Identity on the hub and store its token in slot agent:<name> (the token is never printed; --shift = --scopes work,run)
1137
1142
  capability bind <capability> <crew> [--hub <url>] add a crew to a workflow capability on the hub org — a capability may bind many crews (admin; human credential)
1138
1143
  capability unbind <capability> <crew> [--hub <url>] remove one (capability, crew) route
1139
1144
  capability list [--hub <url>] list the hub org's capability routes
1145
+ routing alerts [--workflow <wf>] [--limit <n>] [--hub <url>]
1146
+ ${' '.repeat(41)}list the hub org's routing alerts — newest first org-wide; --workflow scopes to
1147
+ ${' '.repeat(41)}one run and flips to oldest first. A \`binding-gap\` alert means the hub HELD an
1148
+ ${' '.repeat(41)}offer because its compound capability had no live crew binding.
1149
+ routing show <workflow> [--hub <url>]
1150
+ ${' '.repeat(41)}print one HUB run's routing: modifier, wait policy, alerts, resolution reports
1151
+ ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads a def from sqlite.
1152
+ routing rule list [--hub <url>] list the org's capability reroute rules in the order the hub tries them
1153
+ routing rule add <capability> <target> [--position <n>] [--hub <url>] add one reroute rule — offer <capability> as <target> when it has no live crew binding (admin; idempotent per pair; no --position appends)
1154
+ routing rule rm <capability> <target> [--hub <url>] remove one reroute rule (admin; a rule that was never there is a no-op)
1140
1155
  crew list [--hub <url>] list the hub org's crews with their members (includes the orphan crew once one exists)
1141
1156
  crew new <name> --kind personal|shared [--owner <memberId>] [--hub <url>] create a crew on the hub org (admin, or own personal crew; human credential)
1142
1157
  crew rm <crewId> [--hub <url>] delete a crew; work stamped to it moves to the org's orphan crew
@@ -1144,6 +1159,7 @@ ${' '.repeat(41)}the loaded def has drifted from the version the instance is pin
1144
1159
  crew member rm <crewId> <principalId> [--hub <url>] remove a principal from a crew
1145
1160
  setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--crews <a,b>] [--scopes <a,b>] [--reuse-ssh-key <path>] converge this machine's install: human login, agent credential, signing keys, owenloop settings, plugins (idempotent)
1146
1161
  doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)
1162
+ roster show [crew] print a merged crew roster and its layer provenance (read-only)
1147
1163
  enrollments [--hub <url>] list the hub's relayed machine enrollment grants (read-only)
1148
1164
  mcp [--hub <url>] serve the hub control plane over stdio MCP (spawned by MCP hosts, not run by humans)
1149
1165
  work <subcommand> [args] run execution-side shift/hold/exec/agent-run/... commands
@@ -1228,9 +1244,15 @@ export const COMMAND_OPTIONS = new Map([
1228
1244
  ['instance', cmdOpts('hub')],
1229
1245
  ['agent', cmdOpts('crews', 'hub', 'scopes', 'shift')],
1230
1246
  ['capability', cmdOpts('hub')],
1247
+ // Per-TOP-LEVEL-command allowlist, not per-subcommand: `--position` on
1248
+ // `routing alerts` is meaningless but accepted and ignored, exactly as
1249
+ // `--kind` is on `crew list`. Policing flags per subcommand is deliberately
1250
+ // not built here.
1251
+ ['routing', cmdOpts('hub', 'workflow', 'limit', 'position')],
1231
1252
  ['crew', cmdOpts('hub', 'kind', 'owner')],
1232
1253
  ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'crews', 'scopes', 'reuse-ssh-key')],
1233
1254
  ['doctor', cmdOpts('hub')],
1255
+ ['roster', cmdOpts()],
1234
1256
  ['enrollments', cmdOpts('hub')],
1235
1257
  ['mcp', cmdOpts('hub')],
1236
1258
  ['work', cmdOpts()],
@@ -1334,12 +1356,42 @@ function preflight(command, args, io) {
1334
1356
  assertKnownOptions(command, args);
1335
1357
  return undefined;
1336
1358
  }
1359
+ function dispatchRoster(io, args) {
1360
+ if (args.positionals[1] !== 'show' || args.positionals.length > 3) {
1361
+ throw new CliError('usage: owenloop roster show [crew]');
1362
+ }
1363
+ const crew = args.positionals[2];
1364
+ const layers = machineRosterLayers(io.env, crew);
1365
+ const merged = mergeRosterLayers(layers);
1366
+ const hasRoster = layers.some((layer) => layer.roster !== undefined);
1367
+ if (!hasRoster) {
1368
+ io.out(crew === undefined
1369
+ ? 'no machine-global crew roster found'
1370
+ : `no roster layers found for crew ${crew}`);
1371
+ }
1372
+ else {
1373
+ for (const capability of Object.keys(merged).sort()) {
1374
+ const entry = merged[capability];
1375
+ io.out(`${capability}:`);
1376
+ for (const [index, candidate] of entry.candidates.entries()) {
1377
+ io.out(` [${index}] harness=${candidate.harness} model=${candidate.model} effort=${candidate.effort} from ${entry.source}`);
1378
+ }
1379
+ }
1380
+ }
1381
+ io.out('layers inspected:');
1382
+ for (const layer of layers) {
1383
+ io.out(` ${layer.source}: ${layer.roster === undefined ? 'absent' : 'found'}${layer.path === undefined ? '' : ` (${layer.path})`}`);
1384
+ }
1385
+ return 0;
1386
+ }
1337
1387
  function dispatch(command, io, args) {
1338
1388
  // help and lint need no store
1339
1389
  if (command === 'help' || command === '--help' || command === '-h') {
1340
1390
  io.out(USAGE);
1341
1391
  return 0;
1342
1392
  }
1393
+ if (command === 'roster')
1394
+ return dispatchRoster(io, args);
1343
1395
  if (command === 'lint') {
1344
1396
  const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
1345
1397
  const failures = [];
@@ -4245,10 +4297,22 @@ async function dispatchInstance(io, args) {
4245
4297
  throw new CliError('get_status: malformed success response — missing done flag');
4246
4298
  }
4247
4299
  const arrayOr = (value) => (Array.isArray(value) ? value : []);
4300
+ // The hub's terminal INSTANCE STATUS verdict is optional on the wire: older
4301
+ // hubs predate these fields. Absent means absent — neither value is defaulted,
4302
+ // because `terminal: false` and `instanceStatus: 'unknown'` are real answers.
4303
+ // The status vocabulary belongs to the hub, so a future non-empty string is
4304
+ // forwarded verbatim instead of being rejected by a CLI-owned enum.
4305
+ const instanceStatus = typeof wire.instanceStatus === 'string' && wire.instanceStatus !== '' ? wire.instanceStatus : undefined;
4306
+ const terminal = typeof wire.terminal === 'boolean' ? wire.terminal : undefined;
4248
4307
  print(io, {
4249
4308
  ok: true,
4250
4309
  hub: origin,
4251
4310
  workflow,
4311
+ // These answer whether the instance is alive; `done` is the engine's
4312
+ // completion flag, and failed or cancelled instances are terminal without
4313
+ // being done.
4314
+ ...(instanceStatus === undefined ? {} : { instanceStatus }),
4315
+ ...(terminal === undefined ? {} : { terminal }),
4252
4316
  done: wire.done,
4253
4317
  // Owed inputs the instance is waiting on, each with its acceptance and
4254
4318
  // whether the engine considers it stalled.
@@ -4267,6 +4331,14 @@ async function dispatchInstance(io, args) {
4267
4331
  // looks identical to "nothing is picking this up" from the outside.
4268
4332
  ...(Array.isArray(wire.waitingOnCapabilities) ? { waitingOnCapabilities: wire.waitingOnCapabilities } : {}),
4269
4333
  });
4334
+ // The hub owns this mapping; do not derive terminality from its status label.
4335
+ // stderr preserves the JSON stdout contract while still reaching an operator
4336
+ // who is piping it to another command.
4337
+ if (terminal === true) {
4338
+ const terminalMessage = `instance ${workflow} is ${instanceStatus ?? 'in a terminal state'} — TERMINAL. ` +
4339
+ 'The hub will dispatch nothing further for it; an empty `eligible` here is a finished run, not an idle shift.';
4340
+ io.err(terminalMessage);
4341
+ }
4270
4342
  return 0;
4271
4343
  }
4272
4344
  /**
@@ -4738,6 +4810,357 @@ async function dispatchCapability(io, args) {
4738
4810
  throw e;
4739
4811
  }
4740
4812
  }
4813
+ /**
4814
+ * `owenloop routing alerts|show|rule list|rule add|rule rm` — read the hub's LIVE
4815
+ * routing state, and administer the org's **capability reroute rules**.
4816
+ *
4817
+ * | subcommand | endpoint | auth principal |
4818
+ * |---|---|---|
4819
+ * | `routing alerts [--workflow <wf>] [--limit <n>]` | `GET /api/routing_alerts` | human (any role) |
4820
+ * | `routing show <workflow>` | `GET /api/run_routing/:wf` | human (any role) |
4821
+ * | `routing rule list` | `GET /api/capability_reroutes` | human (any role) |
4822
+ * | `routing rule add <capability> <target> [--position <n>]` | `POST /api/add_capability_reroute` | human (admin role) |
4823
+ * | `routing rule rm <capability> <target>` | `POST /api/remove_capability_reroute` | human (admin role) |
4824
+ *
4825
+ * **Three different objects share the word "routing" in this CLI. They are not
4826
+ * interchangeable, and only one of them grants anybody work:**
4827
+ *
4828
+ * - A **capability route** (`owenloop capability bind`) is a `(capability, crew)`
4829
+ * BINDING. It is the only one of the three that makes a crew eligible to claim
4830
+ * work.
4831
+ * - A **capability reroute rule** (`owenloop routing rule add`) is an ordered
4832
+ * SUBSTITUTION — "when `<capability>` has no live crew binding, offer the work
4833
+ * as `<target>` instead". It names no crew and grants nobody access; whether
4834
+ * the target can actually be served is a `capability bind` question.
4835
+ * - A **routing alert** (`owenloop routing alerts`) is an immutable EVENT row the
4836
+ * hub wrote about one offer at one instant. `kind: 'binding-gap'` is the one to
4837
+ * watch: a step's compound capability (e.g. `build:express`) had no live crew
4838
+ * binding, so the hub HELD the offer rather than silently falling back to
4839
+ * name matching. Holding is the intended behavior; the alert is how a human
4840
+ * finds out it happened.
4841
+ *
4842
+ * **`routing show <workflow>` is NOT the local `show` command.** `owenloop show`
4843
+ * reads a workflow DEFINITION out of the local sqlite store and takes no `--hub`;
4844
+ * `routing show` reads one STARTED RUN's routing state off the hub. They share no
4845
+ * code path, and this deliberately did not arrive as a `--hub` flag on the local
4846
+ * command — the same separation `instance show` keeps.
4847
+ *
4848
+ * **Two orderings are SEMANTIC and are never re-sorted client-side.** `routing
4849
+ * alerts` unscoped returns the org's alerts NEWEST-FIRST (an inbox); adding
4850
+ * `--workflow` scopes to one run AND flips to OLDEST-FIRST (a timeline). `routing
4851
+ * rule list` returns rules in the order the hub TRIES them. Sorting any of these
4852
+ * for looks would misreport what the hub actually does.
4853
+ *
4854
+ * **`rule add` can fail where `rule rm` cannot** — the deliberate asymmetry
4855
+ * `capability bind`/`unbind` already has. `rule add` is idempotent per
4856
+ * `(capability, target)` pair (a repeat is a 200 no-op reporting
4857
+ * `alreadyPresent: true`), but the hub rejects a rule it considers invalid — a
4858
+ * capability rerouted to itself, a malformed name — with a 400 whose `message` is
4859
+ * surfaced verbatim, exit 1. `rule rm` answers a tolerant 200 `removed: false`
4860
+ * when there was no such rule, which is exit 0 plus a stderr line. None of the
4861
+ * hub's name rules are re-implemented here: the hub is the enforcement of record,
4862
+ * the same stance the capability family takes.
4863
+ *
4864
+ * `routing show` on a workflow id this org does not own does NOT come back with a
4865
+ * descriptive message: the hub verb throws an untyped error that its edge maps to
4866
+ * HTTP 500 `{"error":"internal_error","message":"internal server error"}`, and
4867
+ * that generic message is what this command prints (exit 1) — the same thing
4868
+ * `instance show` does with the same hub behavior. The ladder below surfaces
4869
+ * whatever `message` the hub sends, so a future typed 404 needs no change here.
4870
+ *
4871
+ * Exit codes: 0 ok — including `rule rm`'s tolerant `removed: false`; 1
4872
+ * runtime/hub error (a 400 on `rule add`, a 403 for a non-admin on `rule
4873
+ * add`/`rule rm`, an unknown workflow on `show`, a malformed 2xx, a network
4874
+ * timeout); 2 the hub is unresolvable; 3 the human credential is absent or
4875
+ * irrecoverable (the error names `owenloop login --hub <origin>`).
4876
+ */
4877
+ async function dispatchRouting(io, args) {
4878
+ const USAGE_FORMS = 'usage: owenloop routing alerts [--workflow <wf>] [--limit <n>] [--hub <url>]' +
4879
+ ' | owenloop routing show <workflow> [--hub <url>]' +
4880
+ ' | owenloop routing rule list [--hub <url>]' +
4881
+ ' | owenloop routing rule add <capability> <target> [--position <n>] [--hub <url>]' +
4882
+ ' | owenloop routing rule rm <capability> <target> [--hub <url>]';
4883
+ // --- validation: everything below runs BEFORE any I/O, so a usage error on a
4884
+ // multi-hub machine reports the usage problem (exit 1), not exit 2.
4885
+ const sub = args.positionals[1];
4886
+ if (sub !== 'alerts' && sub !== 'show' && sub !== 'rule') {
4887
+ throw new CliError(`unknown routing subcommand '${sub ?? ''}' — ${USAGE_FORMS}`);
4888
+ }
4889
+ let workflow = ''; // `show` only
4890
+ let ruleSub = ''; // `rule` only
4891
+ let capability = ''; // `rule add` / `rule rm`
4892
+ let target = ''; // `rule add` / `rule rm`
4893
+ let workflowFilter; // `alerts` only
4894
+ let limit; // `alerts` only
4895
+ let position; // `rule add` only
4896
+ if (sub === 'show') {
4897
+ const rawWorkflow = args.positionals[2];
4898
+ if (rawWorkflow === undefined || rawWorkflow === '') {
4899
+ throw new CliError(`missing required argument: <workflow> (${USAGE_FORMS})`);
4900
+ }
4901
+ workflow = rawWorkflow;
4902
+ }
4903
+ else if (sub === 'alerts') {
4904
+ // `--workflow` with no value, or with an empty one, is a usage error rather
4905
+ // than a silent org-wide listing. The hub treats `workflow=` as absent, so
4906
+ // accepting an empty value would print `"workflow": ""` over an UNSCOPED
4907
+ // result set — stdout claiming a filter that was never applied. OMITTING the
4908
+ // flag entirely is the org-wide listing; that difference is preserved.
4909
+ // (`dispatchStart`'s `requiredTextOption` makes the same distinction.)
4910
+ if (args.missingOptionValues.has('workflow')) {
4911
+ throw new CliError('missing value for --workflow: expected --workflow <wf>');
4912
+ }
4913
+ const rawFilter = last(args, 'workflow');
4914
+ if (rawFilter !== undefined && rawFilter.trim() === '') {
4915
+ throw new CliError('invalid empty value for --workflow: expected --workflow <wf>');
4916
+ }
4917
+ workflowFilter = rawFilter;
4918
+ // `numOpt` throws a CliError on a non-numeric value — including a bare
4919
+ // `--limit`, which the parser records as the string 'true'. This is flag
4920
+ // hygiene, not a copy of hub semantics: the hub silently DROPS a
4921
+ // non-positive-integer `limit` and applies its own default, which would
4922
+ // report a page size the operator never asked for.
4923
+ limit = numOpt(args, 'limit');
4924
+ }
4925
+ else {
4926
+ // Two-level subcommand, the `crew member add|rm` shape.
4927
+ const rawRuleSub = args.positionals[2];
4928
+ if (rawRuleSub !== 'list' && rawRuleSub !== 'add' && rawRuleSub !== 'rm') {
4929
+ throw new CliError(`unknown routing rule subcommand '${rawRuleSub ?? ''}' — ${USAGE_FORMS}`);
4930
+ }
4931
+ ruleSub = rawRuleSub;
4932
+ if (ruleSub === 'add' || ruleSub === 'rm') {
4933
+ // Both are required for BOTH verbs: one call writes or clears exactly ONE
4934
+ // `(capability, target)` rule, and a capability-only `rm` would drop every
4935
+ // substitution the operator ever wrote for that source.
4936
+ const rawCapability = args.positionals[3];
4937
+ if (rawCapability === undefined || rawCapability === '') {
4938
+ throw new CliError(`missing required argument: <capability> (${USAGE_FORMS})`);
4939
+ }
4940
+ capability = rawCapability;
4941
+ const rawTarget = args.positionals[4];
4942
+ if (rawTarget === undefined || rawTarget === '') {
4943
+ throw new CliError(`missing required argument: <target> (${USAGE_FORMS})`);
4944
+ }
4945
+ target = rawTarget;
4946
+ // Omitting `--position` APPENDS the rule; a non-numeric value is a
4947
+ // client-side CliError for the same reason `--limit` is.
4948
+ if (ruleSub === 'add')
4949
+ position = numOpt(args, 'position');
4950
+ }
4951
+ // No client-side charset validation of `capability` or `target` — the hub is
4952
+ // the enforcement of record, the same stance `capability bind` takes.
4953
+ }
4954
+ const origin = resolveAgentHub(io, args, 'manage routing on');
4955
+ const slot = { principal: 'human' };
4956
+ // The human bearer for the resolved origin. Absent → exit 3 with the same
4957
+ // remedy wording `capability` uses.
4958
+ const cred = readCredential(io, origin, slot);
4959
+ if (cred === null) {
4960
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
4961
+ }
4962
+ try {
4963
+ /**
4964
+ * The ONE GET ladder all three reads share, so they can never drift apart in
4965
+ * what they accept. It is `dispatchInstance`'s ladder — a 401 through
4966
+ * `assertAuthOk`, then the hub's typed `message` surfaced VERBATIM for any
4967
+ * other non-2xx — deliberately NOT `capability list`'s bare `assertAuthOk`,
4968
+ * whose own comment freezes that generic wording to that command. `prefix` is
4969
+ * the endpoint-qualified lead-in the narrower for this endpoint also uses, so
4970
+ * a non-JSON body reports a FIXED string rather than V8's `SyntaxError`,
4971
+ * which embeds a verbatim snippet of the raw body.
4972
+ */
4973
+ const readJson = async (path, prefix) => {
4974
+ const { res, cred: used } = await authedGet(io, origin, slot, cred, path);
4975
+ if (res.status === 401)
4976
+ assertAuthOk(res, used, origin);
4977
+ if (!res.ok) {
4978
+ const message = await hubRequestMessage(res);
4979
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
4980
+ }
4981
+ try {
4982
+ return (await res.json());
4983
+ }
4984
+ catch {
4985
+ throw new CliError(`${prefix} — body is not valid JSON`);
4986
+ }
4987
+ };
4988
+ if (sub === 'alerts') {
4989
+ // Both query params are optional and are sent ONLY when the operator asked
4990
+ // for them, so the default request carries no `?` at all and the hub
4991
+ // applies its own page size.
4992
+ const qs = new URLSearchParams();
4993
+ if (workflowFilter !== undefined)
4994
+ qs.set('workflow', workflowFilter);
4995
+ if (limit !== undefined)
4996
+ qs.set('limit', String(limit));
4997
+ const query = qs.toString();
4998
+ const body = await readJson(`/api/routing_alerts${query === '' ? '' : `?${query}`}`, 'routing_alerts: malformed response');
4999
+ let alerts;
5000
+ try {
5001
+ alerts = asRoutingAlerts(body);
5002
+ }
5003
+ catch (e) {
5004
+ throw new CliError(e.message);
5005
+ }
5006
+ // The guard's output — a whitelisted typed array — never the raw body, and
5007
+ // in RECEIVED order (see the ordering paragraph above). The `workflow` key
5008
+ // is echoed back only when a filter was applied, so a script can tell an
5009
+ // oldest-first timeline from a newest-first inbox without re-reading argv.
5010
+ print(io, {
5011
+ ok: true,
5012
+ hub: origin,
5013
+ ...(workflowFilter === undefined ? {} : { workflow: workflowFilter }),
5014
+ alerts,
5015
+ });
5016
+ return 0;
5017
+ }
5018
+ if (sub === 'show') {
5019
+ // The workflow id is a path segment, so it must be encoded — an id carrying
5020
+ // a slash would otherwise silently address a different route
5021
+ // (`dispatchInstance`'s precedent).
5022
+ const body = await readJson(`/api/run_routing/${encodeURIComponent(workflow)}`, 'run_routing: malformed success response');
5023
+ let wire;
5024
+ try {
5025
+ wire = asRunRouting(body);
5026
+ }
5027
+ catch (e) {
5028
+ throw new CliError(e.message);
5029
+ }
5030
+ print(io, {
5031
+ ok: true,
5032
+ hub: origin,
5033
+ // The SERVER-echoed id, not argv — the `capability bind` precedent.
5034
+ workflow: wire.workflow,
5035
+ defName: wire.defName,
5036
+ // OMITTED, never `null` or `''`: the absence of this key is how stdout
5037
+ // says "this run was started without a modifier". An empty string would
5038
+ // read as "a modifier named nothing", which is not a state that exists.
5039
+ ...(wire.modifier === undefined ? {} : { modifier: wire.modifier }),
5040
+ waitPolicy: wire.waitPolicy,
5041
+ alerts: wire.alerts,
5042
+ resolutionReports: wire.resolutionReports,
5043
+ escalations: wire.escalations,
5044
+ });
5045
+ return 0;
5046
+ }
5047
+ if (ruleSub === 'list') {
5048
+ const body = await readJson('/api/capability_reroutes', 'capability_reroutes: malformed response');
5049
+ let reroutes;
5050
+ try {
5051
+ reroutes = asCapabilityReroutes(body);
5052
+ }
5053
+ catch (e) {
5054
+ throw new CliError(e.message);
5055
+ }
5056
+ // Printed in the hub's own try-order and never re-sorted: the array order
5057
+ // IS which substitution the hub attempts first. Each row also carries its
5058
+ // `position`, so a reader can check that ordering for themselves.
5059
+ print(io, { ok: true, hub: origin, reroutes });
5060
+ return 0;
5061
+ }
5062
+ // `rule add` and `rule rm` share one POST ladder. The bodies differ by exactly
5063
+ // one optional field — `position`, add-only — because each call writes or
5064
+ // clears exactly one `(capability, target)` rule. Only the path, the guard,
5065
+ // and the printed shape differ.
5066
+ const endpoint = ruleSub === 'add' ? 'add_capability_reroute' : 'remove_capability_reroute';
5067
+ // The `position` KEY is omitted entirely when the flag is absent — that is
5068
+ // what tells the hub to APPEND. Sending `null` or `0` would each mean
5069
+ // something else.
5070
+ const payload = ruleSub === 'add' && position !== undefined ? { capability, target, position } : { capability, target };
5071
+ const { res } = await authedPost(io, origin, slot, cred, `/api/${endpoint}`, payload);
5072
+ if (res.status === 401) {
5073
+ // A 401 that survived `authedPost`'s one refresh-and-retry. The human slot
5074
+ // never holds an agent kind, so `assertAuthOk`'s non-agent wording applies;
5075
+ // the catch below upgrades this to exit 3.
5076
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
5077
+ }
5078
+ if (!res.ok) {
5079
+ // Surface the hub's typed `message` VERBATIM — this is how a rule the hub
5080
+ // refuses (400 `capability_reroute_invalid`) and a non-admin 403 both
5081
+ // surface uniformly. `hubRequestMessage` reads only the typed `message`
5082
+ // field, so raw body text is never included.
5083
+ const message = await hubRequestMessage(res);
5084
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5085
+ }
5086
+ let body;
5087
+ try {
5088
+ body = (await res.json());
5089
+ }
5090
+ catch {
5091
+ // A FIXED string — never V8's SyntaxError message, which embeds a verbatim
5092
+ // snippet of the raw body.
5093
+ throw new CliError(`${endpoint}: malformed success response — body is not valid JSON`);
5094
+ }
5095
+ if (ruleSub === 'add') {
5096
+ let added;
5097
+ try {
5098
+ added = asCapabilityRerouteAdded(body);
5099
+ }
5100
+ catch (e) {
5101
+ throw new CliError(e.message);
5102
+ }
5103
+ // SERVER-echoed capability/target/position, not argv. `position` especially:
5104
+ // omitting `--position` appends, so the rank printed here is usually one the
5105
+ // operator never typed. `alreadyPresent` and `ruleCount` carry the HUB's own
5106
+ // field names verbatim, so an operator correlating stdout against the hub's
5107
+ // audit log never has to translate. `createdAt` is validated but not printed
5108
+ // — `routing rule list` is where a row's provenance belongs (the
5109
+ // `capability bind` precedent).
5110
+ print(io, {
5111
+ ok: true,
5112
+ hub: origin,
5113
+ capability: added.reroute.capability,
5114
+ target: added.reroute.target,
5115
+ position: added.reroute.position,
5116
+ alreadyPresent: added.alreadyPresent,
5117
+ ruleCount: added.ruleCount,
5118
+ });
5119
+ // No stderr line on `add`: the write is idempotent per pair, so
5120
+ // `alreadyPresent: true` is a normal no-op, and an add never removes a rule
5121
+ // or parks a capability. There is no consequence to warn about.
5122
+ return 0;
5123
+ }
5124
+ // `rule rm`: the guard proves the 2xx really was the remove verb's answer.
5125
+ // `removedWire` (not `removed`) so `removedWire.removed` reads unambiguously —
5126
+ // the naming `dispatchCapability` and `dispatchCrew` already use.
5127
+ let removedWire;
5128
+ try {
5129
+ removedWire = asCapabilityRerouteRemoved(body);
5130
+ }
5131
+ catch (e) {
5132
+ throw new CliError(e.message);
5133
+ }
5134
+ print(io, {
5135
+ ok: true,
5136
+ hub: origin,
5137
+ capability: removedWire.capability,
5138
+ target: removedWire.target,
5139
+ removed: removedWire.removed,
5140
+ remainingTargets: removedWire.remainingTargets,
5141
+ });
5142
+ // stderr only, so `| jq` on stdout is unaffected — mirroring `capability
5143
+ // unbind`, which narrates its tolerant-false case and its notable side effect
5144
+ // the same way.
5145
+ if (!removedWire.removed) {
5146
+ io.err(`${removedWire.capability} had no reroute to '${removedWire.target}' — nothing was removed`);
5147
+ }
5148
+ else if (removedWire.remainingTargets.length === 0) {
5149
+ io.err(`${removedWire.capability}: no reroute rules remain — it now HOLDS whenever it has no live crew binding`);
5150
+ }
5151
+ return 0;
5152
+ }
5153
+ catch (e) {
5154
+ // A refresh-failure-family error (the human oauth is irrecoverable, or a 401
5155
+ // survived the refresh-and-retry) is exit 3 with the login remedy; every
5156
+ // other CliError propagates as-is — a network timeout stays exit 1, because a
5157
+ // flaky network is not an irrecoverable credential.
5158
+ if (e instanceof CliError && /run `owenloop login`/.test(e.message)) {
5159
+ throw new CliError(`${e.message} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5160
+ }
5161
+ throw e;
5162
+ }
5163
+ }
4741
5164
  /**
4742
5165
  * `owenloop crew list|new|rm|member add|member rm` — administer hub crews.
4743
5166
  * Modeled directly on `dispatchCapability`: same validate-before-I/O discipline,
@@ -6103,7 +6526,37 @@ async function runDoctor(io, origin) {
6103
6526
  record('owenloop settings', true, settingsPath, true);
6104
6527
  }
6105
6528
  }
6106
- // 6–7. plugins (rendered; non-core while PLUGIN_CHECK_FATAL is false)
6529
+ // Crew-roster diagnostics are informational per crew. The same registry
6530
+ // membership predicate the worker uses is intentionally reused here.
6531
+ try {
6532
+ const crewsDir = join(owenloopConfigDir(io.env), 'crews');
6533
+ const crews = existsSync(crewsDir)
6534
+ ? readdirSync(crewsDir, { withFileTypes: true })
6535
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
6536
+ .map((entry) => entry.name.slice(0, -'.json'.length))
6537
+ .sort()
6538
+ : [];
6539
+ for (const crew of crews) {
6540
+ try {
6541
+ const layers = machineRosterLayers(io.env, crew);
6542
+ const merged = mergeRosterLayers(layers);
6543
+ const found = layers
6544
+ .map((layer) => `${layer.source}=${layer.roster === undefined ? 'absent' : 'found'}`)
6545
+ .join(', ');
6546
+ const harnesses = [...new Set(Object.values(merged).flatMap((entry) => entry.candidates.map((candidate) => candidate.harness)))];
6547
+ const present = harnesses.filter((id) => adapterFor(id) !== undefined);
6548
+ const missing = harnesses.filter((id) => adapterFor(id) === undefined);
6549
+ record(`crew roster (${crew})`, true, `layers: ${found}; harnesses present: ${present.join(', ') || 'none'}; missing: ${missing.join(', ') || 'none'}`, false);
6550
+ }
6551
+ catch (error) {
6552
+ record(`crew roster (${crew})`, false, error instanceof Error ? error.message : String(error), false);
6553
+ }
6554
+ }
6555
+ }
6556
+ catch (error) {
6557
+ record('crew roster', false, error instanceof Error ? error.message : String(error), false);
6558
+ }
6559
+ // plugins (rendered; non-core while PLUGIN_CHECK_FATAL is false)
6107
6560
  for (const pluginState of probePlugin(io)) {
6108
6561
  const config = HARNESS_CONFIGS[pluginState.id];
6109
6562
  if (!pluginState.cliFound) {
@@ -6134,7 +6587,7 @@ async function runDoctor(io, origin) {
6134
6587
  * the async path, so every existing command and test keeps working exactly as
6135
6588
  * before.
6136
6589
  */
6137
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'cancel', 'instance', 'agent', 'capability', 'crew', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
6590
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'cancel', 'instance', 'agent', 'capability', 'routing', 'crew', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
6138
6591
  export async function mainAsync(argv, io = defaultIO()) {
6139
6592
  // Delegate execution-side and shift argv tails before root parsing. Their
6140
6593
  // roles own their option grammars, including repeated/value forms that the
@@ -6188,6 +6641,8 @@ export async function mainAsync(argv, io = defaultIO()) {
6188
6641
  return await dispatchAgent(io, args);
6189
6642
  case 'capability':
6190
6643
  return await dispatchCapability(io, args);
6644
+ case 'routing':
6645
+ return await dispatchRouting(io, args);
6191
6646
  case 'crew':
6192
6647
  return await dispatchCrew(io, args);
6193
6648
  case 'setup':
@@ -4,17 +4,11 @@
4
4
  * `allowed_signers`, `org-root.pub`, `roster/`, and `revocations/`.
5
5
  *
6
6
  * WHY THIS MODULE EXISTS. Until now four call sites each re-derived the same
7
- * ladder — `$XDG_CONFIG_HOME/owenloop` else `$HOME/.config/owenloop` — and
8
- * `XDG_CONFIG_HOME` was therefore the ONLY lever an operator had for pointing
9
- * one owenloop process at a different settings file than another. That lever is
10
- * not owenloop's to take. `XDG_CONFIG_HOME` is a machine-wide contract that
11
- * `gh`, `git`, `gcloud`, `npm`, and most of the rest of a developer's toolchain
12
- * also read, and `owenloop shift start` spreads its whole environment into
13
- * every worker it dispatches (`shift/spawn.ts`), which in turn passes it to
14
- * every command step's child process (`exec/` sets exactly three variables of
15
- * its own on top). So an operator running two shifts with different
16
- * `capabilityModels` had to set `XDG_CONFIG_HOME` per shift, and that silently
17
- * relocated the config of every other tool the workflow's scripts shell out to.
7
+ * ladder, which made it too easy for each subsystem to resolve a different
8
+ * directory. Owenloop now owns exactly one default: `$HOME/.owenloop`.
9
+ * Operators who need isolation can set the explicit, owenloop-specific
10
+ * `OWENLOOP_CONFIG_DIR`, without changing the configuration roots of unrelated
11
+ * tools that a workflow may invoke.
18
12
  *
19
13
  * MEASURED, not theorized. On run `wf_8b2abe6b` the delivery line's `merge-gate`
20
14
  * and `merger` steps both failed inside their `gh` probes, because `gh` looked
@@ -27,18 +21,19 @@
27
21
  *
28
22
  * THE FIX IS AN OWENLOOP-SPECIFIC VARIABLE. `OWENLOOP_CONFIG_DIR` names the
29
23
  * owenloop config directory ITSELF — no `owenloop` path segment is appended to
30
- * it — so an operator can scope owenloop's config per process while leaving
24
+ * it — so tests and throwaway experiments can scope owenloop's config while leaving
31
25
  * `XDG_CONFIG_HOME` alone for everything else:
32
26
  *
33
- * OWENLOOP_CONFIG_DIR=~/.config/owenloop-shifts/utility/owenloop \
34
- * owenloop shift start utility …
27
+ * OWENLOOP_CONFIG_DIR=/tmp/owenloop-test owenloop work settings
35
28
  *
36
29
  * PRECEDENCE, highest first:
37
30
  * 1. `OWENLOOP_CONFIG_DIR` → used verbatim
38
- * 2. `XDG_CONFIG_HOME` → `<xdg>/owenloop`
39
- * 3. `HOME` → `<home>/.config/owenloop`
40
- * Blank or whitespace-only values are treated as unset at every rung, matching
41
- * the behaviour the four previous copies already had for `XDG_CONFIG_HOME`.
31
+ * 2. `HOME` → `<home>/.owenloop`
32
+ * Blank or whitespace-only values are treated as unset at every rung.
33
+ *
34
+ * `OWENLOOP_CONFIG_DIR` is no longer an operator-facing knob. It survives
35
+ * only for test and throwaway isolation; normal operation uses the HOME-rooted
36
+ * directory above.
42
37
  *
43
38
  * ABSOLUTE PATHS ONLY. A relative `OWENLOOP_CONFIG_DIR` would resolve against
44
39
  * whatever the current working directory happens to be, and a worker's cwd