owenloop 0.5.9 → 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 (83) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +77 -37
  3. package/bin/owenloop.mjs +16 -1
  4. package/dist/packages/work/src/agent/loop.js +7 -0
  5. package/dist/packages/work/src/bundle/pull.d.ts +21 -0
  6. package/dist/packages/work/src/bundle/pull.js +118 -0
  7. package/dist/packages/work/src/exec/instructions.d.ts +4 -1
  8. package/dist/packages/work/src/exec/instructions.js +3 -0
  9. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  10. package/dist/packages/work/src/exec/loop.js +92 -14
  11. package/dist/packages/work/src/harness/claude.js +16 -0
  12. package/dist/packages/work/src/harness/codex.d.ts +8 -0
  13. package/dist/packages/work/src/harness/codex.js +27 -1
  14. package/dist/packages/work/src/harness/contract.d.ts +9 -0
  15. package/dist/packages/work/src/roles/agent-run.js +38 -10
  16. package/dist/packages/work/src/roles/exec.js +25 -8
  17. package/dist/packages/work/src/shift/loop.js +118 -4
  18. package/dist/packages/work/src/shift/runtime.d.ts +3 -0
  19. package/dist/packages/work/src/shift/runtime.js +10 -1
  20. package/dist/packages/work/src/submit-proof.d.ts +11 -8
  21. package/dist/packages/work/src/submit-proof.js +11 -8
  22. package/dist/src/capabilities.d.ts +70 -6
  23. package/dist/src/capabilities.js +49 -6
  24. package/dist/src/capability-mapping-client.d.ts +29 -0
  25. package/dist/src/capability-mapping-client.js +160 -0
  26. package/dist/src/cli.d.ts +2 -2
  27. package/dist/src/cli.js +1196 -164
  28. package/dist/src/defs.d.ts +32 -1
  29. package/dist/src/defs.js +391 -79
  30. package/dist/src/engine.d.ts +62 -19
  31. package/dist/src/engine.js +180 -70
  32. package/dist/src/hub.d.ts +77 -0
  33. package/dist/src/hub.js +162 -0
  34. package/dist/src/implements.d.ts +56 -0
  35. package/dist/src/implements.js +790 -0
  36. package/dist/src/index.d.ts +8 -6
  37. package/dist/src/index.js +4 -3
  38. package/dist/src/mcp/serve.js +254 -45
  39. package/dist/src/mcp/server.d.ts +10 -7
  40. package/dist/src/mcp/server.js +53 -8
  41. package/dist/src/model.d.ts +46 -10
  42. package/dist/src/model.js +220 -74
  43. package/dist/src/store/def-source.d.ts +19 -0
  44. package/dist/src/store/def-source.js +87 -17
  45. package/dist/src/store/gc-recovery.d.ts +46 -0
  46. package/dist/src/store/gc-recovery.js +258 -0
  47. package/dist/src/store/gc.d.ts +94 -0
  48. package/dist/src/store/gc.js +562 -0
  49. package/dist/src/store/index.d.ts +3 -1
  50. package/dist/src/store/index.js +2 -0
  51. package/dist/src/store/install.d.ts +34 -5
  52. package/dist/src/store/install.js +73 -11
  53. package/dist/src/store/pre-commit-verifier.js +42 -2
  54. package/dist/src/store/snapshot-guard.d.ts +18 -0
  55. package/dist/src/store/snapshot-guard.js +94 -0
  56. package/dist/src/store.d.ts +64 -4
  57. package/dist/src/store.js +211 -8
  58. package/dist/src/types.d.ts +61 -17
  59. package/dist/src/util.js +4 -1
  60. package/docs/authoring.md +145 -8
  61. package/docs/bundles.md +19 -0
  62. package/docs/cli.md +270 -30
  63. package/docs/crypto.md +13 -7
  64. package/docs/design.md +107 -46
  65. package/docs/evals/mcp-charter-baseline.json +428 -0
  66. package/docs/mcp-charter-eval.md +124 -0
  67. package/docs/shift-logs.md +18 -0
  68. package/docs/wire-contracts.md +28 -7
  69. package/examples/workflows/compile-dev-playbook.yaml +1 -1
  70. package/examples/workflows/ship.yaml +28 -2
  71. package/package.json +2 -1
  72. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  73. package/plugins/claude-code/plugin/.mcp.json +1 -1
  74. package/plugins/claude-code/plugin/skills/author/SKILL.md +22 -0
  75. package/plugins/claude-code/plugin/skills/ephemeral/SKILL.md +95 -0
  76. package/plugins/claude-code/plugin/skills/graduate/SKILL.md +156 -0
  77. package/plugins/claude-code/plugin/skills/plan/SKILL.md +236 -0
  78. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  79. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  80. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +22 -0
  81. package/plugins/codex/plugins/owenloop/skills/ephemeral/SKILL.md +95 -0
  82. package/plugins/codex/plugins/owenloop/skills/graduate/SKILL.md +156 -0
  83. package/plugins/codex/plugins/owenloop/skills/plan/SKILL.md +236 -0
package/dist/src/cli.js CHANGED
@@ -27,10 +27,10 @@
27
27
  * owenloop retract <wf> <path> --by <author> --text <msg>
28
28
  * owenloop skip <wf> <path> --by <author> --text <msg>
29
29
  * owenloop retry <wf> <path> [--by <author>] [--text <guidance>] clear a stall
30
- * owenloop close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]
30
+ * owenloop close <wf> <run> [--outcome ok|no_work|released|failed|skipped] [--summary s]
31
31
  * owenloop delete <wf> [--recursive]
32
32
  *
33
- * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
33
+ * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS), --verbose.
34
34
  */
35
35
  import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
36
36
  import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
@@ -42,8 +42,9 @@ import { fileURLToPath } from 'node:url';
42
42
  import { parse as parseYaml } from 'yaml';
43
43
  import { Engine } from "./engine.js";
44
44
  import { buildGraph, buildTrace, graphToDot, graphToMermaid, hasDefiniteCheckDefect, modelCheck } from "./model.js";
45
- import { openStore } from "./store.js";
46
- import { buildDef, DefError, finalizeDefs, lintDef, loadDefFile, loadDefs, loadDefsRaw, loadDefsUnfinalized, resolveCallsTarget, validateDef, } from "./defs.js";
45
+ import { openStore, readRuntimeSnapshotBundlePins } from "./store.js";
46
+ import { buildDef, DefError, finalizeDefs, lintDef, loadDefFile, loadDefs, loadDefsRaw, loadDefsUnfinalized, expandDefsRaw, reportCallsCycles, resolveCallsTarget, scanDefsRaw, validateCallsEdges, validateDef, } from "./defs.js";
47
+ import { implementsIssues } from "./implements.js";
47
48
  import { createDefInstructionSource } from "./order-resolver.js";
48
49
  import { CliError, dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
49
50
  import { packageVersion } from "./package-version.js";
@@ -60,8 +61,11 @@ import { runMcpCommand } from "./mcp/serve.js";
60
61
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
61
62
  import { BundleError, digestBundle, inspectBundle, packBundle, unpackBundle } from "./bundle/index.js";
62
63
  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
- import { BundleIngestorUnavailableError, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, projectStoreRoot, createBundleIngestor, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.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";
64
+ import { BundleIngestorUnavailableError, collectWorkflowStoreGarbage, compareStoreText, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, parseWorkflowCoordinate, projectStoreRoot, createBundleIngestor, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.js";
65
+ import { recoverInterruptedWorkflowStoreGc } from "./store/gc-recovery.js";
66
+ import { asAgentIdentities, asCreateWorkflowOk, capabilityPublishReportText, 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";
67
+ import { fetchCapabilityMappings, recordCapabilityMappings } from "./capability-mapping-client.js";
68
+ import { MODIFIER_SEPARATOR } from "./capabilities.js";
65
69
  import { loadSettings, settingsPath as executionSettingsPath } from "../packages/work/src/settings/settings.js";
66
70
  import { discoverCrewRosterFiles, crewRosterPath, effectiveRosterLayers, explainRosterShadows, mergeRosterLayers } from "../packages/work/src/settings/roster.js";
67
71
  import { readHubRosterCache, syncHubRosterCache } from "../packages/work/src/settings/hub-roster-cache.js";
@@ -162,6 +166,8 @@ const BOOLEAN_FLAGS = new Set([
162
166
  // bundle path/URL must stay a positional.
163
167
  'global',
164
168
  'unsigned',
169
+ 'verbose',
170
+ 'yes',
165
171
  ]);
166
172
  function parseArgs(argv) {
167
173
  const positionals = [];
@@ -223,6 +229,12 @@ function need(args, idx, label) {
223
229
  throw new CliError(`missing required argument: ${label}`);
224
230
  return v;
225
231
  }
232
+ const WORKFLOW_ID_RE = /^wf_[0-9a-f]{24}$/u;
233
+ function assertWorkflowIdShape(workflow) {
234
+ if (!WORKFLOW_ID_RE.test(workflow)) {
235
+ throw new CliError(`invalid workflow id '${workflow}': expected wf_ followed by 24 lowercase hexadecimal characters`);
236
+ }
237
+ }
226
238
  function needOpt(args, key) {
227
239
  const v = last(args, key);
228
240
  if (v === undefined)
@@ -321,19 +333,14 @@ function finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscove
321
333
  * fail-closed validation in add.ts is untouched — we consume `readLockfile`,
322
334
  * discovery merely refuses to act on a bad ledger rather than crashing.)
323
335
  */
324
- function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
325
- const merged = existsSync(defsDir) ? loadDefsUnfinalized(defsDir) : new Map();
336
+ function foldInstalledDefs(io, defsDir, merged, scan) {
326
337
  let lf;
327
338
  try {
328
339
  lf = readLockfile(join(io.cwd, '.owenloop', 'installed.json'));
329
340
  }
330
341
  catch (e) {
331
342
  io.err(`warning: skipping installed workflow defs: ${e.message}`);
332
- const definitionDiscoveryComplete = foldCasDefs(io, defsDir, merged, tolerantCasInspection);
333
- return {
334
- defs: finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscoveryComplete),
335
- definitionDiscoveryComplete,
336
- };
343
+ return;
337
344
  }
338
345
  for (const source of Object.keys(lf.installed).sort()) {
339
346
  const entry = lf.installed[source];
@@ -346,7 +353,7 @@ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
346
353
  }
347
354
  let entryRaw;
348
355
  try {
349
- entryRaw = loadDefsUnfinalized(entryDir);
356
+ entryRaw = scan(entryDir);
350
357
  }
351
358
  catch (e) {
352
359
  io.err(`warning: failed to load installed defs for ${source} (${entry.path}): ${e.message}`);
@@ -361,7 +368,13 @@ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
361
368
  merged.set(name, def);
362
369
  }
363
370
  }
364
- const definitionDiscoveryComplete = foldCasDefs(io, defsDir, merged, tolerantCasInspection);
371
+ }
372
+ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false, verbose = false) {
373
+ const merged = existsSync(defsDir) ? loadDefsUnfinalized(defsDir) : new Map();
374
+ // Preserve executable discovery's long-standing whole-folder policy: a bad
375
+ // installed folder is warned about and skipped rather than partially loaded.
376
+ foldInstalledDefs(io, defsDir, merged, loadDefsUnfinalized);
377
+ const definitionDiscoveryComplete = foldCasDefs(io, defsDir, merged, tolerantCasInspection, verbose);
365
378
  return {
366
379
  defs: finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscoveryComplete),
367
380
  definitionDiscoveryComplete,
@@ -391,7 +404,7 @@ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
391
404
  * When no store exists (no `index.json` at either root) this is a no-op and the
392
405
  * merged map is byte-identical to what it was before WS-6.
393
406
  */
394
- function foldCasDefs(io, defsDir, merged, tolerantInspection = false) {
407
+ function foldCasDefs(io, defsDir, merged, tolerantInspection = false, verbose = false) {
395
408
  // Without HOME/USERPROFILE, retain project discovery and consult a guaranteed
396
409
  // absent synthetic global root instead of silently dropping the project store.
397
410
  let globalRoot;
@@ -405,6 +418,7 @@ function foldCasDefs(io, defsDir, merged, tolerantInspection = false) {
405
418
  projectRoot: projectStoreRoot(defsDir),
406
419
  globalRoot,
407
420
  warn: (line) => io.err(line),
421
+ verbose,
408
422
  };
409
423
  const discovery = tolerantInspection
410
424
  ? inspectCasDefs(discoveryArgs)
@@ -421,6 +435,67 @@ function foldCasDefs(io, defsDir, merged, tolerantInspection = false) {
421
435
  }
422
436
  return discovery.complete;
423
437
  }
438
+ function loadDefsRawWithInstalled(io, defsDir, failures, verbose = false) {
439
+ const merged = existsSync(defsDir) ? scanDefsRaw(defsDir, failures) : new Map();
440
+ foldInstalledDefs(io, defsDir, merged, (dir) => {
441
+ try {
442
+ // Match executable discovery exactly: one malformed or duplicate member
443
+ // invalidates the installed folder. Retain the failed folder as a lint
444
+ // result while foldInstalledDefs emits the shared warning.
445
+ return loadDefsUnfinalized(dir);
446
+ }
447
+ catch (e) {
448
+ failures.push({ file: dir, error: e.message });
449
+ throw e;
450
+ }
451
+ });
452
+ foldCasDefs(io, defsDir, merged, false, verbose);
453
+ return { rawDefs: merged, defs: expandDefsRaw(merged) };
454
+ }
455
+ function loadDefsForAuthoring(io, args, failures) {
456
+ // This deliberately checks override *presence*, rather than whether its path
457
+ // happens to equal cwd/workflows, matching openCtx exactly.
458
+ const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
459
+ const defsDir = defsOverride ?? join(io.cwd, 'workflows');
460
+ let loaded;
461
+ if (defsOverride !== undefined) {
462
+ const rawDefs = existsSync(defsDir) ? scanDefsRaw(defsDir, failures) : new Map();
463
+ loaded = { rawDefs, defs: expandDefsRaw(rawDefs) };
464
+ }
465
+ else {
466
+ loaded = loadDefsRawWithInstalled(io, defsDir, failures, flag(args, 'verbose'));
467
+ }
468
+ return { defsDir, ...loaded };
469
+ }
470
+ function cycleErrorsByDefKey(defs) {
471
+ const errors = new Map();
472
+ const aliases = new Map();
473
+ for (const [key, def] of defs) {
474
+ // The CAS loader registers one physical def under coordinate, digest-scoped,
475
+ // and package/workflow aliases. Treat those aliases as one logical def so a
476
+ // cycle discovered through the resolver's first key is visible through every
477
+ // name an operator can select.
478
+ const identity = def.bundleDigest === undefined ? key : `${def.bundleDigest}\u0000${def.name}`;
479
+ const keys = aliases.get(identity) ?? [];
480
+ keys.push(key);
481
+ aliases.set(identity, keys);
482
+ }
483
+ for (const finding of reportCallsCycles(defs)) {
484
+ for (const key of finding.members) {
485
+ const def = defs.get(key);
486
+ if (def === undefined)
487
+ continue;
488
+ const identity = def.bundleDigest === undefined ? key : `${def.bundleDigest}\u0000${def.name}`;
489
+ for (const alias of aliases.get(identity) ?? []) {
490
+ const messages = errors.get(alias) ?? [];
491
+ if (!messages.includes(finding.message))
492
+ messages.push(finding.message);
493
+ errors.set(alias, messages);
494
+ }
495
+ }
496
+ }
497
+ return errors;
498
+ }
424
499
  function openCtx(io, args, tolerantCasInspection = false) {
425
500
  const dbOverride = last(args, 'db') ?? io.env.OWENLOOP_DB;
426
501
  const dbPath = dbOverride ?? join(io.cwd, '.owenloop', 'state.db');
@@ -439,7 +514,7 @@ function openCtx(io, args, tolerantCasInspection = false) {
439
514
  defs: existsSync(defsDir) ? loadDefs(defsDir) : new Map(),
440
515
  definitionDiscoveryComplete: true,
441
516
  }
442
- : loadDefsWithInstalled(io, defsDir, tolerantCasInspection);
517
+ : loadDefsWithInstalled(io, defsDir, tolerantCasInspection, flag(args, 'verbose'));
443
518
  const { defs, definitionDiscoveryComplete } = loaded;
444
519
  // Guard the built-in default (`cwd/.owenloop/state.db`) against a symlinked
445
520
  // `.owenloop` from a hostile checkout (SEC-3). Directory guard first, then the
@@ -525,10 +600,17 @@ function printBundleInspectResult(io, result) {
525
600
  * the stderr message so scripts can match on it.
526
601
  */
527
602
  function dispatchBundle(io, args) {
528
- const sub = need(args, 1, 'pack|unpack|inspect|digest');
603
+ const sub = need(args, 1, 'pack|unpack|inspect|digest|gc');
529
604
  if (sub !== 'pack' && args.options.has('output')) {
530
605
  throw new CliError(`owenloop bundle ${sub}: --output is only valid for pack`);
531
606
  }
607
+ if (sub !== 'gc') {
608
+ for (const option of ['keep', 'yes', 'global']) {
609
+ if (args.options.has(option)) {
610
+ throw new CliError(`owenloop bundle ${sub}: --${option} is only valid for bundle gc`);
611
+ }
612
+ }
613
+ }
532
614
  switch (sub) {
533
615
  case 'pack': {
534
616
  assertBundlePositionals(args, 3, 'owenloop bundle pack <source-dir> [--output <bundle.wnlp>]');
@@ -577,8 +659,10 @@ function dispatchBundle(io, args) {
577
659
  print(io, { digest: result.digest });
578
660
  return 0;
579
661
  }
662
+ case 'gc':
663
+ throw new CliError('owenloop bundle gc requires the async entry point');
580
664
  default:
581
- throw new CliError(`owenloop bundle: unknown subcommand '${sub}' (expected pack, unpack, inspect, or digest)`);
665
+ throw new CliError(`owenloop bundle: unknown subcommand '${sub}' (expected pack, unpack, inspect, digest, or gc)`);
582
666
  }
583
667
  }
584
668
  /** `--output` requires a following value; a bare flag is not a default path. */
@@ -1105,7 +1189,7 @@ function sleepMs(ms) {
1105
1189
  // ---- commands ----------------------------------------------------------------
1106
1190
  export const USAGE = `owenloop — a dataflow workflow engine
1107
1191
 
1108
- Usage: owenloop <command> [args] [--db <path>] [--defs <dir>]
1192
+ Usage: owenloop <command> [args] [--db <path>] [--defs <dir>] [--verbose]
1109
1193
 
1110
1194
  Commands:
1111
1195
  defs list available workflow definitions
@@ -1118,6 +1202,8 @@ Commands:
1118
1202
  bundle unpack <bundle.wnlp> <destination-dir> unpack a .wnlp bundle into a new directory
1119
1203
  bundle inspect <bundle.wnlp> strictly validate a .wnlp bundle and print its manifest/entries
1120
1204
  bundle digest <bundle.wnlp> print the bundle's def digest (SHA-256 of the canonical tar)
1205
+ bundle gc [--keep <n>] [--global] [--yes]
1206
+ ${' '.repeat(41)}dry-run or collect superseded content-addressed store objects
1121
1207
  publish <source-dir> [--output <bundle.wnlp>] [--source <json>] [--unsigned] [--hub <origin>]
1122
1208
  pack a bundle and sign its canonical digest (signed by default)
1123
1209
  trust init [--force] create the local Ed25519 enrollment root
@@ -1128,9 +1214,13 @@ Commands:
1128
1214
  login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)
1129
1215
  logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot
1130
1216
  connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
1131
- push [<defName>...] [--bundle <bundle.wnlp>] [--force] [--dry-run] [--hub <origin>] [--as <slot>]
1217
+ push [<defName>...] [--bundle <bundle.wnlp>] [--force] [--dry-run] [--hub <origin>] [--as <slot>] [--map <authored>=<org>]
1132
1218
  publish local workflow defs, or exact bundle-backed defs, to the safely resolved hub (server-diffed, idempotent)
1133
1219
  --as names the credential slot: human (default), agent, or agent:<account>
1220
+ --map records one authored=org capability mapping (repeatable); without it push records none
1221
+ install <owner>/<repo>[@ref] [<defName>...] [--map <authored>=<org>] [--accept-defaults] [--dry-run] [--hub <origin>] [--as <slot>]
1222
+ publish an OUTSIDE repo's defs to your hub under SCOPED capabilities (<defName>.<capability> by default)
1223
+ records the capability mapping BEFORE it publishes; it never writes into local workflows/ (that is \`add\`)
1134
1224
  start <defName> [--provide name=json ...] [--crew <name>] [--title <text>] [--modifier <name>] [--scope <label>] [--priority <low|normal|high>] [--hub <url>]
1135
1225
  ${' '.repeat(41)}start a published workflow on the bound hub (human credential)
1136
1226
  ${' '.repeat(41)}--modifier names one value from the def's declared \`modifiers:\` set; every
@@ -1139,6 +1229,7 @@ ${' '.repeat(41)}the run carries no modifier and its steps are offered on BARE c
1139
1229
  ${' '.repeat(41)}--scope is a free routing label recorded on the run — no registry, no fixed set.
1140
1230
  ${' '.repeat(41)}Omit it and the run is routed by the org's routes alone.
1141
1231
  ${' '.repeat(41)}--priority is one of low, normal, high. Omit it and the hub applies normal.
1232
+ pending-gates --hub <url> list human-input gates currently blocking hub-hosted workflows (no local-engine form)
1142
1233
  cancel <workflow> [--reason <text>] [--hub <url>]
1143
1234
  ${' '.repeat(41)}cancel a running instance on the bound hub (human credential; agents cannot cancel).
1144
1235
  ${' '.repeat(41)}Closes every open lease so the run stops being re-offered, and records the
@@ -1158,7 +1249,7 @@ ${' '.repeat(41)}one run and flips to oldest first. A \`binding-gap\` alert mean
1158
1249
  ${' '.repeat(41)}offer because its compound capability had no live crew binding.
1159
1250
  routing show <workflow> [--hub <url>]
1160
1251
  ${' '.repeat(41)}print one HUB run's routing: modifier, wait policy, alerts, resolution reports
1161
- ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads a def from sqlite.
1252
+ ${' '.repeat(41)}and escalations. Unrelated to the local \`show\`, which reads raw artifacts from sqlite.
1162
1253
  routing rule list [--hub <url>] list the org's capability reroute rules in the order the hub tries them
1163
1254
  routing rule add <capability> <target> [--position <n>] [--hub <url>] add one reroute rule — offer <capability> as <target> when it has no live crew binding (admin; idempotent per pair; no --position appends)
1164
1255
  routing rule rm <capability> <target> [--hub <url>] remove one reroute rule (admin; a rule that was never there is a no-op)
@@ -1188,7 +1279,7 @@ ${' '.repeat(41)}refresh the local hub-rosters cache with an agent credential
1188
1279
  check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided] [--strict-inputs]
1189
1280
  bounded reachability check (stall states, true deadlocks, stuck, dead steps, declared invariants)
1190
1281
  create <def> [--title t] [--provide name=json ...] [--param k=v ...]
1191
- provide <wf> <name> [--value json] supply an owed (seedOwed) input
1282
+ provide <wf> <name> [--value json] [--hub <url>] supply an owed (seedOwed) input
1192
1283
  adopt <wf> re-pin an instance to the current def (§28); settles new debts
1193
1284
  tick <wf> [--now <ms>] [--shallow] [--capability <c>]... pull eligible orders (deep: also from calls: children; --shallow for this instance only; --capability filters to matching-capability steps)
1194
1285
  reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)
@@ -1204,16 +1295,17 @@ ${' '.repeat(41)}refresh the local hub-rosters cache with an agent credential
1204
1295
  green <wf> <run> <path> [--value json] [--terminal]
1205
1296
  emit <wf> <run> --items '[{...}]' accrete collection elements
1206
1297
  seal <wf> <run> [--value json] signal a collection is complete
1207
- reject <wf> <path> --by <author> --text <msg>
1298
+ reject <wf> <path> --by <author> --text <msg> [--requested <modifier>] [--hub <url>]
1208
1299
  retract <wf> <path> --by <author> --text <msg>
1209
1300
  skip <wf> <path> --by <author> --text <msg>
1210
1301
  retry <wf> <path> [--by <author>] [--text <guidance>] [--hub <url>] clear a §6 stall, or ANSWER an ask
1211
1302
  ask <wf> <path> <question> [--by <author>] hold an owed artifact on a question for a human
1212
1303
  inbox every held question across all instances, with its answer command
1213
1304
  heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run
1214
- close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]
1305
+ close <wf> <run> [--outcome ok|no_work|released|failed|skipped] [--summary s]
1215
1306
  delete <wf> [--recursive] refuse if children exist unless --recursive (cascades)
1216
1307
 
1308
+ Global: --verbose lists detailed superseded bundle-version notices.
1217
1309
  Environment: OWENLOOP_DB, OWENLOOP_DEFS`;
1218
1310
  /** Append parse failures to a "definition not found" error — the def the user asked for may be in one of the broken files. */
1219
1311
  function failureNote(failures) {
@@ -1232,7 +1324,7 @@ export { hasDefiniteCheckDefect };
1232
1324
  * even on commands that ignore them — to avoid rejecting a documented
1233
1325
  * invocation.
1234
1326
  */
1235
- const GLOBAL_OPTIONS = ['db', 'defs'];
1327
+ const GLOBAL_OPTIONS = ['db', 'defs', 'verbose'];
1236
1328
  /** Build a command's option allowlist: the two globals plus its own long-form flags. */
1237
1329
  const cmdOpts = (...extra) => new Set([...GLOBAL_OPTIONS, ...extra]);
1238
1330
  /**
@@ -1252,14 +1344,16 @@ export const COMMAND_OPTIONS = new Map([
1252
1344
  ['help', cmdOpts()],
1253
1345
  ['defs', cmdOpts()],
1254
1346
  ['add', cmdOpts('recover', 'global')],
1255
- ['bundle', cmdOpts('output')],
1347
+ ['bundle', cmdOpts('output', 'keep', 'yes', 'global')],
1256
1348
  ['login', cmdOpts('hub', 'with-token', 'as')],
1257
1349
  ['logout', cmdOpts('hub', 'as')],
1258
1350
  ['connect', cmdOpts('hub', 'as')],
1259
1351
  ['publish', cmdOpts('unsigned', 'output', 'source', 'hub')],
1260
1352
  ['trust', cmdOpts('force', 'key', 'principal', 'pools', 'labels', 'namespaces', 'delegate', 'signing-key', 'output', 'reason', 'effective-from')],
1261
- ['push', cmdOpts('dry-run', 'force', 'hub', 'as', 'bundle')],
1353
+ ['push', cmdOpts('dry-run', 'force', 'hub', 'as', 'bundle', 'map')],
1354
+ ['install', cmdOpts('hub', 'as', 'map', 'accept-defaults', 'dry-run')],
1262
1355
  ['start', cmdOpts('hub', 'crew', 'title', 'provide', 'modifier', 'scope', 'priority')],
1356
+ ['pending-gates', cmdOpts('hub')],
1263
1357
  ['cancel', cmdOpts('hub', 'reason')],
1264
1358
  ['instance', cmdOpts('hub')],
1265
1359
  ['agent', cmdOpts('crews', 'hub', 'scopes', 'shift')],
@@ -1280,7 +1374,7 @@ export const COMMAND_OPTIONS = new Map([
1280
1374
  ['lint', cmdOpts()],
1281
1375
  ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided', 'strict-inputs')],
1282
1376
  ['create', cmdOpts('title', 'provide', 'param')],
1283
- ['provide', cmdOpts('value')],
1377
+ ['provide', cmdOpts('value', 'hub')],
1284
1378
  ['adopt', cmdOpts()],
1285
1379
  ['tick', cmdOpts('now', 'shallow', 'capability')],
1286
1380
  ['reap', cmdOpts('now')],
@@ -1294,7 +1388,7 @@ export const COMMAND_OPTIONS = new Map([
1294
1388
  ['green', cmdOpts('value', 'terminal')],
1295
1389
  ['emit', cmdOpts('items')],
1296
1390
  ['seal', cmdOpts('value')],
1297
- ['reject', cmdOpts('by', 'text', 'requested')],
1391
+ ['reject', cmdOpts('by', 'text', 'requested', 'hub')],
1298
1392
  ['retract', cmdOpts('by', 'text')],
1299
1393
  ['skip', cmdOpts('by', 'text')],
1300
1394
  ['retry', cmdOpts('by', 'text', 'hub')],
@@ -1830,6 +1924,17 @@ async function dispatchRoster(io, args) {
1830
1924
  print(io, { ok: true, hub: origin, result });
1831
1925
  return 0;
1832
1926
  }
1927
+ /**
1928
+ * Authoring-only lint additions belong here rather than in defs.ts: the
1929
+ * engine's vendored surface keeps extension contents opaque. Base hard errors
1930
+ * deliberately suppress advisory extension warnings just like lintDef does.
1931
+ */
1932
+ function lintForAuthoring(def) {
1933
+ const result = lintDef(def);
1934
+ return result.errors.length === 0
1935
+ ? { ...result, warnings: [...result.warnings, ...implementsIssues(def)] }
1936
+ : result;
1937
+ }
1833
1938
  function dispatch(command, io, args) {
1834
1939
  // help and lint need no store
1835
1940
  if (command === 'help' || command === '--help' || command === '-h') {
@@ -1837,26 +1942,28 @@ function dispatch(command, io, args) {
1837
1942
  return 0;
1838
1943
  }
1839
1944
  if (command === 'lint') {
1840
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
1841
1945
  const failures = [];
1842
- const defs = existsSync(defsDir) ? loadDefsRaw(defsDir, failures) : new Map();
1946
+ const { defsDir, rawDefs, defs } = loadDefsForAuthoring(io, args, failures);
1947
+ const cycleErrors = cycleErrorsByDefKey(defs);
1843
1948
  const defName = args.positionals[1];
1844
1949
  let hasErrors = false;
1845
1950
  if (defName !== undefined) {
1846
1951
  const def = defs.get(defName);
1847
1952
  if (!def)
1848
1953
  throw new CliError(`unknown workflow definition '${defName}' (looked in ${defsDir})${failureNote(failures)}`);
1849
- const result = lintDef(def);
1850
- if (result.errors.length)
1954
+ const result = lintForAuthoring(def);
1955
+ const errors = [...validateCallsEdges(def, rawDefs), ...result.errors, ...(cycleErrors.get(defName) ?? [])];
1956
+ if (errors.length)
1851
1957
  hasErrors = true;
1852
- print(io, { def: def.name, errors: result.errors, warnings: result.warnings });
1958
+ print(io, { def: def.name, errors, warnings: errors.length ? [] : result.warnings });
1853
1959
  }
1854
1960
  else {
1855
- const results = [...defs.values()].map((def) => {
1856
- const result = lintDef(def);
1857
- if (result.errors.length)
1961
+ const results = [...defs].map(([key, def]) => {
1962
+ const result = lintForAuthoring(def);
1963
+ const errors = [...validateCallsEdges(def, rawDefs), ...result.errors, ...(cycleErrors.get(key) ?? [])];
1964
+ if (errors.length)
1858
1965
  hasErrors = true;
1859
- return { def: def.name, errors: result.errors, warnings: result.warnings };
1966
+ return { def: def.name, errors, warnings: errors.length ? [] : result.warnings };
1860
1967
  });
1861
1968
  // Files that never became defs (malformed YAML / bad shape) are lint errors
1862
1969
  // too — omitting them makes `lint` claim a dir is clean when `create` would die.
@@ -1871,18 +1978,23 @@ function dispatch(command, io, args) {
1871
1978
  return 0;
1872
1979
  }
1873
1980
  if (command === 'check') {
1874
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
1875
1981
  const failures = [];
1876
- const defs = existsSync(defsDir) ? loadDefsRaw(defsDir, failures) : new Map();
1982
+ const { defsDir, rawDefs, defs } = loadDefsForAuthoring(io, args, failures);
1983
+ const cycleErrors = cycleErrorsByDefKey(defs);
1877
1984
  const defName = need(args, 1, 'def');
1878
1985
  const def = defs.get(defName);
1879
1986
  if (!def) {
1880
1987
  throw new CliError(`unknown workflow definition '${defName}' (looked in ${defsDir}).\n` +
1881
1988
  `Known definitions: ${[...defs.keys()].sort().join(', ') || '(none)'}${failureNote(failures)}`);
1882
1989
  }
1883
- // loadDefsRaw uses buildDef (no semantic validation); run validateDef here so
1884
- // invariant stem-reference / duplicate-name errors surface to the author.
1885
- const defErrors = validateDef(def);
1990
+ // Authoring discovery uses buildDef (no semantic validation); run
1991
+ // validateDef here so invariant stem-reference / duplicate-name errors
1992
+ // surface to the author.
1993
+ const defErrors = [
1994
+ ...validateCallsEdges(def, rawDefs),
1995
+ ...validateDef(def),
1996
+ ...(cycleErrors.get(defName) ?? []),
1997
+ ];
1886
1998
  if (defErrors.length > 0) {
1887
1999
  throw new CliError(`workflow '${def.name}' has validation errors:\n - ${defErrors.join('\n - ')}`);
1888
2000
  }
@@ -1918,9 +2030,13 @@ function dispatch(command, io, args) {
1918
2030
  io.out(`SEARCH INCOMPLETE — bounds hit: ${report.boundsHit.join(', ')}`);
1919
2031
  io.out('Verdicts apply only within the explored region.');
1920
2032
  }
2033
+ if (report.collectionCapApplied) {
2034
+ io.out('');
2035
+ io.out(`COLLECTION CAP APPLIED — --max-collection ${report.maxCollectionSize} limited each emit/seal fork to 0..${report.maxCollectionSize} members.`);
2036
+ }
1921
2037
  if (report.stallStates.length > 0) {
1922
2038
  io.out('');
1923
- io.out(`Stall states (expected — maxAttempts / human-escalation brakes) (${report.stallStates.length}):`);
2039
+ io.out(`Stall states (expected — retryable brakes / future idle waits) (${report.stallStates.length}):`);
1924
2040
  for (const s of report.stallStates) {
1925
2041
  io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
1926
2042
  }
@@ -1999,9 +2115,10 @@ function dispatch(command, io, args) {
1999
2115
  // - definite (true) deadlock only when EXHAUSTIVE (!bounded) → nonzero
2000
2116
  // - stall states and stuck states are by-design brakes and NEVER affect the
2001
2117
  // exit code — a stall state (report.stallStates) is EXPECTED (a human-
2002
- // escalation brake whose freeze, once lifted, re-arms a producer), and a
2003
- // stuck state (report.stuck) is purely informational (a brake tripped on
2004
- // one branch while the line still moves on another). Neither is a defect.
2118
+ // escalation brake whose freeze, once lifted, re-arms a producer, or an
2119
+ // idle wait that becomes eligible after time passes), and a stuck state
2120
+ // (report.stuck) is purely informational (a brake tripped on one branch
2121
+ // while the line still moves on another). Neither is a defect.
2005
2122
  // - truncated with no invariant violations / structurally-dead steps / true
2006
2123
  // deadlocks → 0
2007
2124
  const hasDefiniteDefect = hasDefiniteCheckDefect(report);
@@ -2012,13 +2129,17 @@ function dispatch(command, io, args) {
2012
2129
  }
2013
2130
  return 0;
2014
2131
  }
2015
- // The bundle namespace is pure filesystem work on the bytes the user
2016
- // points at — dispatched BEFORE openCtx so pack/inspect/digest neither
2017
- // open/create `.owenloop/state.db` nor touch a remote (same reasoning as
2018
- // lint/check above; see docs/cli.md).
2132
+ // Package-format bundle commands are pure filesystem work on bytes the user
2133
+ // points at. GC also dispatches before openCtx, but its async branch performs
2134
+ // its own read-only snapshot scan and targeted store collection.
2019
2135
  if (command === 'bundle') {
2020
2136
  return dispatchBundle(io, args);
2021
2137
  }
2138
+ // Pending gates exist only on the hub. Reject the local spelling before
2139
+ // openCtx() so this cannot create or inspect a local SQLite state database.
2140
+ if (command === 'pending-gates') {
2141
+ throw new CliError('owenloop pending-gates has no local-engine equivalent; pass --hub <url>');
2142
+ }
2022
2143
  const ctx = openCtx(io, args, command === 'status');
2023
2144
  const { engine, store } = ctx;
2024
2145
  if (command === 'status' && !ctx.definitionDiscoveryComplete) {
@@ -2032,6 +2153,11 @@ function dispatch(command, io, args) {
2032
2153
  title: d.title ?? null,
2033
2154
  inputs: d.inputs.map((i) => i.name),
2034
2155
  steps: d.steps.map((l) => l.name),
2156
+ inputSchemas: d.inputs.map((i) => ({
2157
+ name: i.name,
2158
+ ...(i.schema === undefined ? {} : { schema: i.schema }),
2159
+ })),
2160
+ ...(d.x === undefined ? {} : { x: d.x }),
2035
2161
  })));
2036
2162
  return 0;
2037
2163
  }
@@ -2174,6 +2300,9 @@ function dispatch(command, io, args) {
2174
2300
  }
2175
2301
  case 'show': {
2176
2302
  const wf = need(args, 1, 'workflow');
2303
+ if (store.getWorkflow(wf) === undefined) {
2304
+ throw new CliError(`no such workflow instance: ${wf}`);
2305
+ }
2177
2306
  print(io, store.listArtifacts(wf));
2178
2307
  return 0;
2179
2308
  }
@@ -2701,6 +2830,152 @@ function optionalWorkflowRecoveryMarkerDir(io) {
2701
2830
  const home = [io.env.HOME, io.env.USERPROFILE].find((value) => value !== undefined && value.trim() !== '');
2702
2831
  return home === undefined ? undefined : defaultRecoveryMarkerDir(home);
2703
2832
  }
2833
+ const DEFAULT_BUNDLE_GC_KEEP = 2;
2834
+ function bundleGcKeep(args) {
2835
+ if (args.missingOptionValues.has('keep')) {
2836
+ throw new CliError('owenloop bundle gc: --keep requires a positive integer value');
2837
+ }
2838
+ const raw = last(args, 'keep');
2839
+ if (raw === undefined)
2840
+ return DEFAULT_BUNDLE_GC_KEEP;
2841
+ if (!/^[1-9][0-9]*$/u.test(raw)) {
2842
+ throw new CliError(`owenloop bundle gc: invalid --keep '${raw}' (expected a positive integer)`);
2843
+ }
2844
+ const keep = Number(raw);
2845
+ if (!Number.isSafeInteger(keep)) {
2846
+ throw new CliError(`owenloop bundle gc: invalid --keep '${raw}' (expected a finite positive integer)`);
2847
+ }
2848
+ return keep;
2849
+ }
2850
+ function bundleGcPathOverride(args, key, environmentValue) {
2851
+ if (args.missingOptionValues.has(key)) {
2852
+ throw new CliError(`owenloop bundle gc: --${key} requires a non-empty path value`);
2853
+ }
2854
+ const optionValue = last(args, key);
2855
+ if (optionValue !== undefined) {
2856
+ if (optionValue.trim() === '') {
2857
+ throw new CliError(`owenloop bundle gc: --${key} requires a non-empty path value`);
2858
+ }
2859
+ return optionValue;
2860
+ }
2861
+ if (environmentValue !== undefined && environmentValue.trim() === '') {
2862
+ throw new CliError(`owenloop bundle gc: OWENLOOP_${key.toUpperCase()} must be a non-empty path`);
2863
+ }
2864
+ return environmentValue;
2865
+ }
2866
+ /** Collect exact CAS coordinates called by the currently executable non-CAS definitions. */
2867
+ function bundleGcExactCallsFromCurrentDefs(io, defsDir, defsOverride, verbose) {
2868
+ const defs = defsOverride === undefined
2869
+ ? loadDefsWithInstalled(io, defsDir, false, verbose).defs
2870
+ : (existsSync(defsDir) ? loadDefs(defsDir) : new Map());
2871
+ const exactCalls = new Set();
2872
+ for (const def of defs.values()) {
2873
+ // CAS definitions already root their own exact edges through bundleLock.
2874
+ // This scan supplies the missing roots for project, GitHub-add, and legacy
2875
+ // definitions whose snapshots intentionally carry no bundle provenance.
2876
+ if (def.bundleDigest !== undefined)
2877
+ continue;
2878
+ for (const step of def.steps) {
2879
+ if (step.calls === undefined || !step.calls.includes('@'))
2880
+ continue;
2881
+ try {
2882
+ parseWorkflowCoordinate(step.calls);
2883
+ }
2884
+ catch (error) {
2885
+ throw new CliError(`owenloop bundle gc: malformed exact calls target ${JSON.stringify(step.calls)} ` +
2886
+ `in workflow '${def.name}': ${error.message}`);
2887
+ }
2888
+ exactCalls.add(step.calls);
2889
+ }
2890
+ }
2891
+ return [...exactCalls].sort(compareStoreText);
2892
+ }
2893
+ /** Store-aware async branch of the otherwise filesystem-only bundle namespace. */
2894
+ async function dispatchBundleGc(io, args) {
2895
+ assertBundlePositionals(args, 2, 'owenloop bundle gc [--keep <n>] [--global] [--yes]');
2896
+ if (args.options.has('output')) {
2897
+ throw new CliError('owenloop bundle gc: --output is only valid for bundle pack');
2898
+ }
2899
+ const keep = bundleGcKeep(args);
2900
+ // Path selection determines both the destructive target and the snapshot pin
2901
+ // source. Validate every CLI/env override before deriving a root, probing a
2902
+ // DB, or acquiring a writer lock; parseArgs represents a missing value as the
2903
+ // literal string "true", which must never become a filesystem path here.
2904
+ const defsOverride = bundleGcPathOverride(args, 'defs', io.env.OWENLOOP_DEFS);
2905
+ const dbOverride = bundleGcPathOverride(args, 'db', io.env.OWENLOOP_DB);
2906
+ const globalFlag = flag(args, 'global');
2907
+ if (globalFlag && defsOverride !== undefined)
2908
+ throw new CliError(GLOBAL_DEFS_CONFLICT_MSG);
2909
+ const projectRoot = projectStoreRoot(defsOverride ?? join(io.cwd, 'workflows'));
2910
+ let globalRoot;
2911
+ if (globalFlag) {
2912
+ globalRoot = globalStoreRoot(workflowHome(io));
2913
+ }
2914
+ else {
2915
+ try {
2916
+ globalRoot = globalStoreRoot(workflowHome(io));
2917
+ }
2918
+ catch {
2919
+ // Match normal definition discovery: project-only operation remains
2920
+ // available when HOME is absent. No global install can derive a root
2921
+ // either, so model this as a single-root plan and avoid inventing a
2922
+ // coordination path inside the project store.
2923
+ globalRoot = projectRoot;
2924
+ }
2925
+ }
2926
+ const dbPath = dbOverride ?? join(io.cwd, '.owenloop', 'state.db');
2927
+ if (dbOverride === undefined) {
2928
+ const parent = dirname(dbPath);
2929
+ const parentState = lstatSync(parent, { throwIfNoEntry: false });
2930
+ if (parentState?.isSymbolicLink()) {
2931
+ throw new CliError(`refusing runtime database parent '${parent}': it is a symbolic link`);
2932
+ }
2933
+ if (parentState !== undefined && !parentState.isDirectory()) {
2934
+ throw new CliError(`refusing runtime database parent '${parent}': it is not a directory`);
2935
+ }
2936
+ dbPathRefusingSymlink(dbPath);
2937
+ }
2938
+ const readLedger = globalFlag
2939
+ ? undefined
2940
+ : () => {
2941
+ const lf = readLockfile(join(io.cwd, '.owenloop', 'installed.json'));
2942
+ return (source) => {
2943
+ const entry = lf.installed[source];
2944
+ return entry === undefined ? undefined : { sha: entry.sha, path: entry.path };
2945
+ };
2946
+ };
2947
+ const legacyRecovery = globalFlag
2948
+ ? undefined
2949
+ : {
2950
+ lockPath: join(io.cwd, '.owenloop', 'add.lock'),
2951
+ journalPath: join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME),
2952
+ lockfilePath: join(io.cwd, '.owenloop', 'installed.json'),
2953
+ readLedger: readLedger,
2954
+ };
2955
+ const legacyReadBarrier = globalFlag
2956
+ ? {
2957
+ lockPath: join(io.cwd, '.owenloop', 'add.lock'),
2958
+ journalPath: join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME),
2959
+ }
2960
+ : undefined;
2961
+ const result = await collectWorkflowStoreGarbage({
2962
+ projectRoot,
2963
+ globalRoot,
2964
+ level: globalFlag ? 'global' : 'project',
2965
+ keep,
2966
+ yes: flag(args, 'yes'),
2967
+ readSnapshotPins: () => readRuntimeSnapshotBundlePins(dbPath),
2968
+ readExactCalls: () => bundleGcExactCallsFromCurrentDefs(io, projectRoot, defsOverride, flag(args, 'verbose')),
2969
+ ...(readLedger === undefined ? {} : { readLedger }),
2970
+ ...(legacyRecovery === undefined ? {} : { legacyRecovery }),
2971
+ ...(legacyReadBarrier === undefined ? {} : { legacyReadBarrier }),
2972
+ ...(optionalWorkflowRecoveryMarkerDir(io) === undefined
2973
+ ? {}
2974
+ : { recoveryMarkerDir: optionalWorkflowRecoveryMarkerDir(io) }),
2975
+ });
2976
+ print(io, result);
2977
+ return 0;
2978
+ }
2704
2979
  /**
2705
2980
  * The `.wnlp` bundle route of `owenloop add` — the content-addressed store
2706
2981
  * counterpart of the GitHub route. `dispatchAdd` classifies the positional
@@ -2729,9 +3004,9 @@ async function dispatchAddBundle(io, args, source) {
2729
3004
  // A fresh bundle install also needs an external marker directory, so derive
2730
3005
  // that path from the same injected home and never from process state.
2731
3006
  const recoveryMarkerDir = workflowRecoveryMarkerDir(io);
2732
- const root = globalFlag
2733
- ? globalStoreRoot(workflowHome(io))
2734
- : projectStoreRoot(defsOverride ?? join(io.cwd, 'workflows'));
3007
+ const projectRoot = projectStoreRoot(defsOverride ?? join(io.cwd, 'workflows'));
3008
+ const globalRoot = globalStoreRoot(workflowHome(io));
3009
+ const root = globalFlag ? globalRoot : projectRoot;
2735
3010
  const statePaths = workflowStoreStatePaths(root);
2736
3011
  const lockPath = statePaths.lockPath;
2737
3012
  const journalPath = statePaths.journalPath;
@@ -2779,6 +3054,8 @@ async function dispatchAddBundle(io, args, source) {
2779
3054
  source: bundleSource,
2780
3055
  root,
2781
3056
  level: globalFlag ? 'global' : 'project',
3057
+ projectRoot,
3058
+ globalRoot,
2782
3059
  lockPath,
2783
3060
  journalPath,
2784
3061
  recoveryMarkerDir,
@@ -3013,7 +3290,7 @@ async function dispatchAdd(io, args) {
3013
3290
  mkdirRefusingSymlink(canonicalState.stateDir);
3014
3291
  guardStateFile(canonicalState.lockPath, 'canonical install lock');
3015
3292
  guardStateFile(canonicalState.journalPath, 'canonical crash-recovery journal');
3016
- const lockPaths = [...new Set([installLockPath, canonicalState.lockPath])].sort();
3293
+ const lockPaths = [...new Set([installLockPath, canonicalState.lockPath])].sort(compareStoreText);
3017
3294
  const locks = [];
3018
3295
  try {
3019
3296
  for (const path of lockPaths)
@@ -3029,13 +3306,10 @@ async function dispatchAdd(io, args) {
3029
3306
  // must NOT delete it (the error message tells the user to recover it).
3030
3307
  let preserveStagingRoot = false;
3031
3308
  try {
3032
- // Recover a crash-interrupted prior install FIRST — before the stale-staging
3033
- // clear, since the backups/parked dirs a rollback needs live UNDER the
3034
- // staging root, so clearing it first would destroy them. Any refusal (bad or
3035
- // mismatched or contradictory journal) must preserve the staging root and the
3036
- // journal as evidence: without this, the `finally` below would rmSync the
3037
- // staging root and take the backups a later recovery needs with it.
3309
+ // Recover crash-interrupted GC parking and installs FIRST — before the
3310
+ // stale-staging clear, since either can own evidence below that shared root.
3038
3311
  try {
3312
+ recoverInterruptedWorkflowStoreGc({ root: defsDir, stateDir: canonicalState.stateDir });
3039
3313
  recoverInterruptedInstall({
3040
3314
  defsDir,
3041
3315
  journalPath: canonicalState.journalPath,
@@ -3342,7 +3616,9 @@ async function dispatchAddRecover(io, args) {
3342
3616
  guardStateFile(canonicalState.lockPath, 'canonical install lock');
3343
3617
  guardStateFile(canonicalState.journalPath, 'canonical crash-recovery journal');
3344
3618
  }
3345
- const lockPaths = [...new Set([installLockPath, ...(canonicalStateExists ? [canonicalState.lockPath] : [])])].sort();
3619
+ const lockPaths = [
3620
+ ...new Set([installLockPath, ...(canonicalStateExists ? [canonicalState.lockPath] : [])]),
3621
+ ].sort(compareStoreText);
3346
3622
  const locks = [];
3347
3623
  try {
3348
3624
  for (const path of lockPaths)
@@ -3355,6 +3631,9 @@ async function dispatchAddRecover(io, args) {
3355
3631
  }
3356
3632
  let outcome = 'no-journal';
3357
3633
  try {
3634
+ if (canonicalStateExists) {
3635
+ recoverInterruptedWorkflowStoreGc({ root: defsDir, stateDir: canonicalState.stateDir });
3636
+ }
3358
3637
  const canonicalOutcome = recoverInterruptedInstall({
3359
3638
  defsDir,
3360
3639
  journalPath: canonicalState.journalPath,
@@ -3602,7 +3881,8 @@ async function authedPost(io, origin, slot, cred, path, body, persist = true) {
3602
3881
  /**
3603
3882
  * A 401 on an agent token is a hard "revoked/invalid" error; a 401 on any
3604
3883
  * other credential kind (after `authedGet`'s one refresh-and-retry) is a hard
3605
- * "credential rejected" error; any other non-2xx is a generic hub-rejected
3884
+ * "credential rejected" error; a 429 is a rate-limit error (including
3885
+ * `Retry-After` when present); any other non-2xx is a generic hub-rejected
3606
3886
  * error naming the status. Shared by `verifyCredential` and `dispatchPush`'s
3607
3887
  * server-list fetch so both surfaces the same wording for the same failure.
3608
3888
  */
@@ -3613,6 +3893,10 @@ function assertAuthOk(res, cred, origin) {
3613
3893
  }
3614
3894
  throw new CliError('credential rejected by the hub — run `owenloop login`');
3615
3895
  }
3896
+ if (res.status === 429) {
3897
+ const retryAfter = res.headers.get('retry-after');
3898
+ throw new CliError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
3899
+ }
3616
3900
  if (!res.ok) {
3617
3901
  throw new CliError(`hub ${origin} rejected the credential (HTTP ${res.status})`);
3618
3902
  }
@@ -4165,6 +4449,116 @@ function orderSelectedDefsByCalls(selected, currentPackage) {
4165
4449
  visit(def);
4166
4450
  return { ordered, dependencies };
4167
4451
  }
4452
+ /**
4453
+ * Publish an already-diffed, already-validated batch of defs — the shared
4454
+ * publish ladder behind BOTH `push` and `install`, so the two can never drift
4455
+ * apart in how they treat a 401, a 413, a 429, a `{ok:false}` 200, or a def
4456
+ * whose selected dependency failed.
4457
+ *
4458
+ * Behavior, unchanged from when this lived inline in `dispatchPush`:
4459
+ * - A def whose selected `calls:` dependency failed or was skipped is SKIPPED,
4460
+ * never published against a half-updated hub.
4461
+ * - A 401 refreshes an oauth credential once and retries once; a 401 that
4462
+ * survives that (or any 401 on an agent token) aborts the whole run by
4463
+ * re-throwing — already-published defs stand.
4464
+ * - A 429 halts the batch immediately (REL-10): this def is `failed`, the
4465
+ * not-yet-attempted remainder is `skipped`, and nothing else is sent.
4466
+ * - Any other per-def failure is recorded and the batch continues.
4467
+ *
4468
+ * `holder.cred` is read before every request and written back after a refresh,
4469
+ * so a mid-batch token rotation is not lost by the caller.
4470
+ */
4471
+ async function publishCandidates(io, origin, slot, holder, toPush, dependencies, bundleDigest) {
4472
+ const pushed = [];
4473
+ const noop = [];
4474
+ const failed = [];
4475
+ const skipped = [];
4476
+ const capabilities = {};
4477
+ const unsuccessful = new Set();
4478
+ for (let i = 0; i < toPush.length; i++) {
4479
+ const c = toPush[i];
4480
+ const label = c.status === 'new' ? '+' : '~';
4481
+ const blockedBy = [...(dependencies.get(c.name) ?? [])]
4482
+ .filter((dependency) => unsuccessful.has(dependency))
4483
+ .sort();
4484
+ if (blockedBy.length > 0) {
4485
+ skipped.push(c.name);
4486
+ unsuccessful.add(c.name);
4487
+ io.err(`- ${c.name} (skipped: selected dependency ${blockedBy.map((name) => `'${name}'`).join(', ')} failed or was skipped)`);
4488
+ continue;
4489
+ }
4490
+ try {
4491
+ let res = await createWorkflowRequest(io, origin, holder.cred, c.yaml, bundleDigest);
4492
+ if (res.status === 401 && holder.cred.kind === 'oauth') {
4493
+ holder.cred = await refreshOAuth(io, origin, slot, holder.cred);
4494
+ res = await createWorkflowRequest(io, origin, holder.cred, c.yaml, bundleDigest);
4495
+ }
4496
+ if (res.status === 401) {
4497
+ if (holder.cred.kind === 'agent') {
4498
+ throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
4499
+ }
4500
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
4501
+ }
4502
+ if (res.status === 413)
4503
+ throw new CliError('workflow yaml exceeds the hub 32MB request cap');
4504
+ if (res.status === 429) {
4505
+ const retryAfter = res.headers.get('retry-after');
4506
+ throw new RateLimitError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
4507
+ }
4508
+ if (!res.ok)
4509
+ throw new CliError(`hub returned HTTP ${res.status}`);
4510
+ const bodyJson = await res.json();
4511
+ const errText = createWorkflowError(bodyJson);
4512
+ if (errText !== null)
4513
+ throw new CliError(`hub rejected the def: ${errText}`);
4514
+ const okBody = asCreateWorkflowOk(bodyJson, c.name);
4515
+ if (okBody.unchanged) {
4516
+ noop.push(c.name);
4517
+ io.err(`= ${c.name} (server: unchanged, v${okBody.version})`);
4518
+ }
4519
+ else {
4520
+ pushed.push(c.name);
4521
+ io.err(`${label} ${c.name} (→ v${okBody.version})`);
4522
+ }
4523
+ // The hub sends the report on BOTH branches, `unchanged:true` included, so
4524
+ // an idempotent re-push still tells the pusher what the org vocabulary is.
4525
+ if (okBody.capabilityReport !== undefined) {
4526
+ capabilities[c.name] = okBody.capabilityReport;
4527
+ printCapabilityReport(io, c.name, okBody.capabilityReport);
4528
+ }
4529
+ }
4530
+ catch (e) {
4531
+ // A 429 halts the whole batch immediately (REL-10): record this def as
4532
+ // failed, then stop — the not-yet-attempted remainder is reported as
4533
+ // `skipped`, not silently hammered against a rate-limited server.
4534
+ // Handled before the generic path because RateLimitError extends CliError.
4535
+ if (e instanceof RateLimitError) {
4536
+ const msg = e.message;
4537
+ failed.push({ name: c.name, error: msg });
4538
+ unsuccessful.add(c.name);
4539
+ io.err(`! ${c.name} (failed: ${msg})`);
4540
+ const remainder = toPush.slice(i + 1).map((r) => r.name);
4541
+ skipped.push(...remainder);
4542
+ for (const name of remainder)
4543
+ unsuccessful.add(name);
4544
+ if (remainder.length > 0) {
4545
+ io.err(`stopping — rate limited by the hub; ${remainder.length} def(s) not attempted`);
4546
+ }
4547
+ break;
4548
+ }
4549
+ // A hard auth error aborts the whole run (re-throw); a per-def server
4550
+ // failure is recorded and the batch continues (already-pushed defs stand).
4551
+ if (e instanceof CliError && /run `owenloop login`|re-mint it/.test(e.message)) {
4552
+ throw e;
4553
+ }
4554
+ const msg = e.message;
4555
+ failed.push({ name: c.name, error: msg });
4556
+ unsuccessful.add(c.name);
4557
+ io.err(`! ${c.name} (failed: ${msg})`);
4558
+ }
4559
+ }
4560
+ return { pushed, noop, skipped, failed, capabilities };
4561
+ }
4168
4562
  /**
4169
4563
  * `owenloop push [<defName>...] [--bundle <bundle.wnlp>] [--force]
4170
4564
  * [--dry-run] [--hub <origin>]` — publish local workflow defs, or exact
@@ -4185,6 +4579,11 @@ async function dispatchPush(io, args) {
4185
4579
  }
4186
4580
  const dryRun = flag(args, 'dry-run');
4187
4581
  const force = flag(args, 'force');
4582
+ // `push` publishes defs the ORG authored, so their capabilities join the org's
4583
+ // SHARED vocabulary by default and NOTHING is recorded. `--map` is the only
4584
+ // way `push` writes a mapping at all — the deliberate asymmetry with
4585
+ // `install`, which scopes by default. See `dispatchInstall`.
4586
+ const requestedMap = parseCapabilityMapFlag(args);
4188
4587
  const slot = resolveSlot(args);
4189
4588
  const resolved = resolvePublishingHub(io, args, slot);
4190
4589
  const { origin } = resolved;
@@ -4244,6 +4643,18 @@ async function dispatchPush(io, args) {
4244
4643
  const selectedOrder = orderSelectedDefsByCalls(selected, bundle?.manifest.package.name);
4245
4644
  selected = selectedOrder.ordered;
4246
4645
  const selectedDependencies = selectedOrder.dependencies;
4646
+ assertMapCoversSelection(requestedMap, selected);
4647
+ // Per def, only the entries that def actually authors, and only the
4648
+ // non-identity ones — the hub's resolver drops an identity row anyway, so
4649
+ // posting one would be a write that changes nothing.
4650
+ const mappingWrites = selected
4651
+ .map((def) => ({
4652
+ name: def.name,
4653
+ entries: Object.fromEntries(authoredCapabilitiesOf(def)
4654
+ .filter((cap) => requestedMap[cap] !== undefined && requestedMap[cap] !== cap)
4655
+ .map((cap) => [cap, requestedMap[cap]])),
4656
+ }))
4657
+ .filter((w) => Object.keys(w.entries).length > 0);
4247
4658
  // Client-side validation gate — all-or-nothing, mirroring dispatchAdd exactly.
4248
4659
  // Any failure aborts the entire push; nothing is sent.
4249
4660
  const reasons = failures.map((f) => `${f.file}: ${f.error}`);
@@ -4337,110 +4748,600 @@ async function dispatchPush(io, args) {
4337
4748
  changed: toPush.filter((c) => c.status === 'changed').map((c) => c.name),
4338
4749
  unchanged: unchanged.map((c) => c.name),
4339
4750
  wouldPush: toPush.map((c) => c.name),
4751
+ wouldRecord: Object.fromEntries(mappingWrites.map((w) => [w.name, w.entries])),
4340
4752
  });
4341
4753
  return 0;
4342
4754
  }
4755
+ // `--map` records BEFORE anything is published, the same ordering `install`
4756
+ // uses and for the same reason: a hub that cannot record the mapping must
4757
+ // fail the command with nothing published, never leave the two halves apart.
4758
+ if (mappingWrites.length > 0) {
4759
+ const holder = { cred };
4760
+ const transport = capabilityMappingTransport(io, origin, slot, holder);
4761
+ for (const write of mappingWrites) {
4762
+ await recordCapabilityMappings(transport, write.name, write.entries, origin);
4763
+ for (const [authored, org] of Object.entries(write.entries)) {
4764
+ io.err(` recorded ${write.name}: ${authored} → ${org}`);
4765
+ }
4766
+ }
4767
+ cred = holder.cred;
4768
+ }
4343
4769
  // Refresh an expiring oauth token once up front (per-request 401 refresh below covers mid-batch expiry).
4344
4770
  cred = await ensureFreshOAuth(io, origin, slot, cred);
4345
4771
  if (bundle !== undefined) {
4346
4772
  cred = await uploadPushBundle(io, origin, slot, cred, bundle);
4347
4773
  }
4348
- const pushedNames = [];
4349
- const noopNames = [];
4350
- const failed = [];
4351
- const skipped = [];
4352
- const unsuccessful = new Set();
4353
- for (let i = 0; i < toPush.length; i++) {
4354
- const c = toPush[i];
4355
- const label = c.status === 'new' ? '+' : '~';
4356
- const blockedBy = [...(selectedDependencies.get(c.name) ?? [])]
4357
- .filter((dependency) => unsuccessful.has(dependency))
4358
- .sort();
4359
- if (blockedBy.length > 0) {
4360
- skipped.push(c.name);
4361
- unsuccessful.add(c.name);
4362
- io.err(`- ${c.name} (skipped: selected dependency ${blockedBy.map((name) => `'${name}'`).join(', ')} failed or was skipped)`);
4774
+ const holder = { cred };
4775
+ const published = await publishCandidates(io, origin, slot, holder, toPush, selectedDependencies, bundle?.digest);
4776
+ print(io, {
4777
+ ok: published.failed.length === 0,
4778
+ hub: origin,
4779
+ ...(bundle === undefined ? {} : { bundleDigest: bundle.digest, publication: bundle.publicationState }),
4780
+ pushed: published.pushed,
4781
+ noop: published.noop,
4782
+ unchanged: unchanged.map((c) => c.name),
4783
+ skipped: published.skipped,
4784
+ failed: published.failed,
4785
+ capabilities: published.capabilities,
4786
+ });
4787
+ return published.failed.length === 0 ? 0 : 1;
4788
+ }
4789
+ finally {
4790
+ if (bundle !== undefined)
4791
+ rmSync(bundle.cleanupRoot, { recursive: true, force: true });
4792
+ }
4793
+ }
4794
+ // ---- capability mapping (shared by `push --map` and `install`) ---------------
4795
+ /**
4796
+ * Every authored capability one def declares, deduped, in first-authored order.
4797
+ *
4798
+ * Judge steps are synthesized into `def.steps` by the def parser, so iterating
4799
+ * `steps` covers them — there is no second place capabilities can be written.
4800
+ * Order is the order an operator reads the YAML top-down, which is the order
4801
+ * the install prompt asks in.
4802
+ */
4803
+ function authoredCapabilitiesOf(def) {
4804
+ const names = [];
4805
+ for (const step of def.steps) {
4806
+ for (const cap of step.capabilities ?? []) {
4807
+ if (!names.includes(cap))
4808
+ names.push(cap);
4809
+ }
4810
+ }
4811
+ return names;
4812
+ }
4813
+ /**
4814
+ * The org capability name an OUTSIDE def's capability takes by default:
4815
+ * `<defName>.<authored>`.
4816
+ *
4817
+ * This needs no new separator and invents no escaping. A def name matches
4818
+ * `/^[a-z0-9][a-z0-9_-]*$/i`, so it can never contain a dot, while the def
4819
+ * parser's capability rule reserves only `:` — dots are already legal inside a
4820
+ * capability. So the dot splits the two halves unambiguously in one direction
4821
+ * (the first dot ends the def name) and collides with nothing.
4822
+ */
4823
+ function scopedCapabilityName(defName, authored) {
4824
+ return `${defName}.${authored}`;
4825
+ }
4826
+ /**
4827
+ * The same rule the def parser's `assertAuthoredCapability` applies, restated
4828
+ * for an ORG-side name supplied on the command line or at the prompt:
4829
+ * non-empty, not whitespace, and no `MODIFIER_SEPARATOR`.
4830
+ *
4831
+ * The separator ban is the load-bearing half. `:` is the suffix position the
4832
+ * engine composes the run modifier into at offer time (`wise` + `deep` →
4833
+ * `wise:deep`), so an authored-side value carrying one would be a capability
4834
+ * that can never be composed. The def parser refuses it in YAML; this refuses
4835
+ * it on the mapping's target, which reaches exactly the same position.
4836
+ */
4837
+ function assertMappingTarget(target, where) {
4838
+ if (target.trim().length === 0) {
4839
+ throw new CliError(`${where}: an org capability name must not be empty or whitespace`);
4840
+ }
4841
+ if (target.includes(MODIFIER_SEPARATOR)) {
4842
+ throw new CliError(`${where}: capability '${target}' must not contain '${MODIFIER_SEPARATOR}' — ` +
4843
+ 'the suffix position is reserved for the modifier the engine composes at offer time ' +
4844
+ "(a run carrying 'deep' turns the authored capability 'wise' into 'wise:deep')");
4845
+ }
4846
+ }
4847
+ /**
4848
+ * Parse the repeatable `--map <authored>=<org>` flag shared by `push` and
4849
+ * `install`. `parsePairs` supplies the `expected name=value, got: …` refusal;
4850
+ * every target is then validated by `assertMappingTarget`.
4851
+ */
4852
+ function parseCapabilityMapFlag(args) {
4853
+ const out = {};
4854
+ for (const [authored, target] of Object.entries(parsePairs(all(args, 'map'), false))) {
4855
+ if (authored.trim().length === 0) {
4856
+ throw new CliError('--map: the authored capability name must not be empty or whitespace');
4857
+ }
4858
+ assertMappingTarget(target, `--map ${authored}`);
4859
+ out[authored] = target;
4860
+ }
4861
+ return out;
4862
+ }
4863
+ /**
4864
+ * Refuse a `--map` naming a capability none of the selected defs authors — it
4865
+ * would otherwise be a silent no-op, and a typo in an authored name is exactly
4866
+ * the case where silence is worst (the operator believes a link was made).
4867
+ */
4868
+ function assertMapCoversSelection(map, selected) {
4869
+ const authored = new Set(selected.flatMap((def) => authoredCapabilitiesOf(def)));
4870
+ const unknown = Object.keys(map)
4871
+ .filter((name) => !authored.has(name))
4872
+ .sort();
4873
+ if (unknown.length === 0)
4874
+ return;
4875
+ const known = [...authored].sort();
4876
+ throw new CliError(`--map names ${unknown.length} capability(ies) no selected def authors: ${unknown.join(', ')} — ` +
4877
+ (known.length === 0 ? 'the selected defs author no capabilities' : `authored: ${known.join(', ')}`));
4878
+ }
4879
+ /**
4880
+ * Adapt `authedGet`/`authedPost` into the transport
4881
+ * `src/capability-mapping-client.ts` takes, threading the possibly-refreshed
4882
+ * credential back into `holder` so a mid-command oauth refresh is not lost.
4883
+ *
4884
+ * The client module cannot import these helpers directly — they are private to
4885
+ * `cli.ts`, and `cli.ts` imports the client, so a direct import would be a
4886
+ * cycle. Injecting the transport keeps the 30s deadline, the bounded body,
4887
+ * `redirect: 'error'` and the single 401-refresh-and-retry on the mapping calls
4888
+ * without one.
4889
+ */
4890
+ function capabilityMappingTransport(io, origin, slot, holder) {
4891
+ return {
4892
+ async get(path) {
4893
+ const { res, cred } = await authedGet(io, origin, slot, holder.cred, path);
4894
+ holder.cred = cred;
4895
+ return res;
4896
+ },
4897
+ async post(path, body) {
4898
+ const { res, cred } = await authedPost(io, origin, slot, holder.cred, path, body);
4899
+ holder.cred = cred;
4900
+ return res;
4901
+ },
4902
+ };
4903
+ }
4904
+ /**
4905
+ * The hub's capability publish report for one def, on STDERR — stdout stays
4906
+ * machine JSON. Silent for a hub that sent no report (older than the report) and
4907
+ * for a def that authors no capabilities, so neither case prints a dangling
4908
+ * header.
4909
+ */
4910
+ function printCapabilityReport(io, defName, report) {
4911
+ if (report === undefined)
4912
+ return;
4913
+ const text = capabilityPublishReportText(report);
4914
+ if (text !== '')
4915
+ io.err(`${defName}: ${text}`);
4916
+ }
4917
+ /**
4918
+ * Render the org's live capability vocabulary from `GET /api/capability_routes`
4919
+ * as one line — `review (reviewers), builder (builders), triage (unbound)`.
4920
+ *
4921
+ * The endpoint returns ONE ROW PER `(capability, crew)` pair, so rows are
4922
+ * grouped by capability here. A row whose `crewName` is `null` is a DANGLING
4923
+ * route (the crew is gone) and shows as `unbound`, because that is what it means
4924
+ * for routing: the capability exists in the vocabulary but nothing serves it.
4925
+ */
4926
+ function formatOrgVocabulary(routes) {
4927
+ const crewsByCapability = new Map();
4928
+ for (const route of routes) {
4929
+ const crews = crewsByCapability.get(route.capability);
4930
+ const name = route.crewName;
4931
+ if (crews === undefined)
4932
+ crewsByCapability.set(route.capability, new Set(name === null ? [] : [name]));
4933
+ else if (name !== null)
4934
+ crews.add(name);
4935
+ }
4936
+ return [...crewsByCapability.entries()]
4937
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
4938
+ .map(([capability, crews]) => `${capability} (${crews.size === 0 ? 'unbound' : [...crews].sort().join(', ')})`)
4939
+ .join(', ');
4940
+ }
4941
+ /**
4942
+ * Fetch a public GitHub repo's `workflows/**` at a pinned commit sha, into an
4943
+ * in-memory file map.
4944
+ *
4945
+ * Deliberately its own sequence rather than a refactor of `dispatchAdd`'s: `add`
4946
+ * interleaves this with a project install lock, a crash journal and an atomic
4947
+ * swap that `install` has no business acquiring, and its refusal wording names
4948
+ * `add`'s local install. Only the PRIMITIVES are shared (`parseRepoSpec`,
4949
+ * `githubShaUrl`, `githubTarballUrl`, `readBodyBounded`, `extractTarGz`,
4950
+ * `archivePathViolation`), which is where the security-relevant behavior lives:
4951
+ * the ref is pinned to a 40-char sha before the tarball is fetched, the body is
4952
+ * capped DURING the stream, and every archive path is checked for escape before
4953
+ * it is ever joined (SEC-1).
4954
+ */
4955
+ async function fetchGithubWorkflowFiles(io, spec) {
4956
+ const { owner, repo, ref } = parseRepoSpec(spec);
4957
+ const source = `${owner}/${repo}`;
4958
+ const fetchFn = io.fetch ?? globalThis.fetch;
4959
+ let shaRes;
4960
+ try {
4961
+ shaRes = await fetchFn(githubShaUrl(owner, repo, ref), {
4962
+ headers: { Accept: 'application/vnd.github.sha', 'User-Agent': 'owenloop' },
4963
+ signal: AbortSignal.timeout(ADD_SHA_TIMEOUT_MS),
4964
+ });
4965
+ }
4966
+ catch (e) {
4967
+ const err = e;
4968
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
4969
+ throw new CliError(`timed out after ${ADD_SHA_TIMEOUT_MS / 1000}s resolving ${source}@${ref}`);
4970
+ }
4971
+ throw e;
4972
+ }
4973
+ if (!shaRes.ok) {
4974
+ const notFoundNote = shaRes.status === 404 ? ' (repo or ref not found)' : '';
4975
+ throw new CliError(`could not resolve ${source}@${ref}: GitHub returned ${shaRes.status}${notFoundNote}`);
4976
+ }
4977
+ const shaBytes = await readBodyBounded(shaRes, hubMaxResponseBytes(io), `sha resolution for ${source}@${ref}`);
4978
+ const sha = new TextDecoder().decode(shaBytes).trim();
4979
+ if (!/^[0-9a-f]{40}$/i.test(sha)) {
4980
+ throw new CliError(`unexpected response resolving ${source}@${ref}: expected a 40-char commit sha, got "${sha}"`);
4981
+ }
4982
+ let bytes;
4983
+ try {
4984
+ const tarRes = await fetchFn(githubTarballUrl(owner, repo, sha), {
4985
+ headers: { 'User-Agent': 'owenloop' },
4986
+ signal: AbortSignal.timeout(ADD_TARBALL_TIMEOUT_MS),
4987
+ });
4988
+ if (!tarRes.ok) {
4989
+ throw new CliError(`could not fetch tarball for ${source}@${sha}: GitHub returned ${tarRes.status}`);
4990
+ }
4991
+ bytes = await readBodyBounded(tarRes, tarballMaxBytes(io), `tarball for ${source}@${sha}`);
4992
+ }
4993
+ catch (e) {
4994
+ const err = e;
4995
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
4996
+ throw new CliError(`timed out after ${ADD_TARBALL_TIMEOUT_MS / 1000}s downloading tarball for ${source}@${sha}`);
4997
+ }
4998
+ throw e;
4999
+ }
5000
+ let rawFiles;
5001
+ try {
5002
+ rawFiles = extractTarGz(bytes);
5003
+ }
5004
+ catch (e) {
5005
+ throw new CliError(`could not extract tarball for ${source}@${sha}: ${e.message}`);
5006
+ }
5007
+ const files = new Map();
5008
+ const pathViolations = [];
5009
+ for (const [rawPath, data] of rawFiles) {
5010
+ const firstSlash = rawPath.indexOf('/');
5011
+ const rest = firstSlash >= 0 ? rawPath.slice(firstSlash + 1) : '';
5012
+ if (!rest.startsWith('workflows/'))
5013
+ continue;
5014
+ const relPath = rest.slice('workflows/'.length);
5015
+ if (!relPath)
5016
+ continue;
5017
+ const violation = archivePathViolation(relPath);
5018
+ if (violation) {
5019
+ pathViolations.push(`${rawPath}: ${violation}`);
5020
+ continue;
5021
+ }
5022
+ files.set(relPath, data);
5023
+ }
5024
+ if (pathViolations.length > 0) {
5025
+ throw new CliError(`refusing to install ${source}@${sha} — ${pathViolations.length} unsafe archive path(s) found; nothing published:\n - ${pathViolations.join('\n - ')}`);
5026
+ }
5027
+ if (files.size === 0) {
5028
+ throw new CliError(`no workflows/ directory found in ${source}@${ref}`);
5029
+ }
5030
+ return { source, ref, sha, files };
5031
+ }
5032
+ /**
5033
+ * Ask the operator, one authored capability at a time, what the org should call
5034
+ * it. Enter accepts the prefilled SCOPED default; typing a name links the
5035
+ * capability into the org's existing vocabulary instead.
5036
+ *
5037
+ * Prompt style matches `promptAgentName` / `promptSuccession`: prefilled
5038
+ * default, empty answer accepts it, one re-prompt on an invalid answer, then a
5039
+ * `CliError`. All prompt I/O is stderr, so `| jq` on stdout is unaffected.
5040
+ *
5041
+ * `prompt` is passed in ALREADY RESOLVED by `requirePrompt`, which the caller
5042
+ * ran before any hub I/O — a piped run must fail with the flag names, never
5043
+ * block here after half the work is done.
5044
+ */
5045
+ async function promptCapabilityMapping(io, prompt, defName, authored) {
5046
+ const fallback = scopedCapabilityName(defName, authored);
5047
+ const question = ` ${authored} [${fallback}]: `;
5048
+ for (let attempt = 0; attempt < 2; attempt++) {
5049
+ const raw = (await prompt(question)).trim();
5050
+ if (raw === '')
5051
+ return fallback;
5052
+ try {
5053
+ assertMappingTarget(raw, `capability '${authored}'`);
5054
+ return raw;
5055
+ }
5056
+ catch (e) {
5057
+ io.err(e.message);
5058
+ }
5059
+ }
5060
+ throw new CliError(`no valid org capability name provided for '${authored}'`);
5061
+ }
5062
+ /**
5063
+ * `owenloop install <owner>/<repo>[@ref] [<defName>...] [--map <authored>=<org>]
5064
+ * [--accept-defaults] [--dry-run] [--hub <origin>] [--as <slot>]` — publish defs
5065
+ * authored OUTSIDE your org to your hub, under capability names your org
5066
+ * chooses.
5067
+ *
5068
+ * **This is a PUBLISH verb, a sibling of `push` — not of `add`.** It never
5069
+ * writes into the local `workflows/` directory: `add` already owns local
5070
+ * installation, with its install lock, crash journal and atomic swap, and
5071
+ * duplicating that here would be a second implementation of the same
5072
+ * transaction. `install` fetches the outside def, decides the org-side
5073
+ * capability vocabulary for it, records that mapping, and publishes.
5074
+ *
5075
+ * **Why the mapping is scoped by default.** `push` publishes defs YOU authored,
5076
+ * so their capabilities join the org's SHARED vocabulary — two of your own defs
5077
+ * both authoring `review` deliberately mean the same `review`, served by the
5078
+ * same crews. A def from an unrelated author making the same claim is not the
5079
+ * same claim. So every capability an installed def authors becomes
5080
+ * `<defName>.<capability>` unless the installer says otherwise, once, at install
5081
+ * time. The def content itself is never edited: the mapping is org-side data.
5082
+ *
5083
+ * **Order of operations, and it is the point: record, THEN publish.** Publishing
5084
+ * first would put an unscoped third-party def into the org's vocabulary for the
5085
+ * window between the two calls — exactly the trust-boundary breach this verb
5086
+ * exists to prevent. So a hub that cannot record the mapping fails the command
5087
+ * BEFORE anything is published, and nothing is left half-applied.
5088
+ *
5089
+ * **A hub that cannot record mappings.** The hub's mapping READ is live, but no
5090
+ * shipped `owenloop-service` build has the BATCH write this command needs — it
5091
+ * ships a singular one-row-per-call verb instead, which cannot give the
5092
+ * record-then-publish order its all-or-nothing guarantee (see
5093
+ * `src/capability-mapping-client.ts` for why the plural is not sugar over N
5094
+ * singular calls). Until the batch verb ships, only the IDENTITY case completes
5095
+ * end to end: when every capability keeps its authored name there is nothing to
5096
+ * record — the hub's resolver drops identity rows anyway — so the write is
5097
+ * skipped and the publish proceeds. Every other case stops at the missing verb
5098
+ * with exit 2.
5099
+ *
5100
+ * Exit codes: 0 ok; 1 runtime/hub error (a validation-gate refusal, a per-def
5101
+ * hub rejection, a refused source kind, an invalid `--map`); 2 the hub is
5102
+ * unresolvable, or it does not implement the mapping write; 3 the credential for
5103
+ * the slot is absent or irrecoverable.
5104
+ */
5105
+ async function dispatchInstall(io, args) {
5106
+ // 0. Argument-only work, before anything is fetched or resolved.
5107
+ const spec = need(args, 1, '<source>');
5108
+ const classified = classifyAddSource(spec);
5109
+ if (classified.kind !== 'github') {
5110
+ const what = classified.kind === 'file' ? 'a local .wnlp bundle' : 'an http(s) URL';
5111
+ throw new CliError(`owenloop install: ${what} is not an install source yet — only owner/repo[@ref] (GitHub) is. ` +
5112
+ `Run \`owenloop add ${spec}\` to install it into the local store, then ` +
5113
+ '`owenloop push --bundle <bundle.wnlp>` to publish it.');
5114
+ }
5115
+ const dryRun = flag(args, 'dry-run');
5116
+ const acceptDefaults = flag(args, 'accept-defaults');
5117
+ const requestedMap = parseCapabilityMapFlag(args);
5118
+ const slot = resolveSlot(args);
5119
+ const resolvedHub = resolvePublishingHub(io, args, slot);
5120
+ const { origin } = resolvedHub;
5121
+ const startingCredential = resolvedHub.credential ?? readCredential(io, origin, slot);
5122
+ if (!startingCredential) {
5123
+ throw new CliError(`${emptySlotMessage(origin, slot)} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5124
+ }
5125
+ // Threaded through every hub call so a mid-command oauth refresh is not lost.
5126
+ const holder = { cred: startingCredential };
5127
+ // 1. Fetch the outside repo and materialize its workflows/ into a temp dir.
5128
+ // Nothing under the user's cwd is touched, at any point.
5129
+ const fetched = await fetchGithubWorkflowFiles(io, spec);
5130
+ const sourceRef = `${fetched.source}@${fetched.sha}`;
5131
+ const workRoot = mkdtempSync(join(tmpdir(), 'owenloop-install-'));
5132
+ try {
5133
+ for (const [relPath, data] of fetched.files) {
5134
+ const dest = join(workRoot, relPath);
5135
+ mkdirSync(dirname(dest), { recursive: true });
5136
+ writeFileSync(dest, data);
5137
+ }
5138
+ // 2. Load, narrow to positionals, and order by `calls:` — same machinery push uses.
5139
+ const failures = [];
5140
+ const allDefs = loadDefsRaw(workRoot, failures);
5141
+ const requested = args.positionals.slice(2);
5142
+ let selected;
5143
+ if (requested.length > 0) {
5144
+ selected = [];
5145
+ for (const name of requested) {
5146
+ const def = allDefs.get(name);
5147
+ if (!def) {
5148
+ throw new CliError(`unknown workflow definition '${name}' in ${sourceRef} (found: ${[...allDefs.keys()].sort().join(', ') || 'none'})${failureNote(failures)}`);
5149
+ }
5150
+ selected.push(def);
5151
+ }
5152
+ }
5153
+ else {
5154
+ selected = [...allDefs.values()];
5155
+ }
5156
+ if (selected.length === 0) {
5157
+ throw new CliError(`nothing to install — no workflow definitions found in ${sourceRef}${failureNote(failures)}`);
5158
+ }
5159
+ const selectedOrder = orderSelectedDefsByCalls(selected);
5160
+ selected = selectedOrder.ordered;
5161
+ const selectedDependencies = selectedOrder.dependencies;
5162
+ assertMapCoversSelection(requestedMap, selected);
5163
+ // 3. Client-side validation gate — all-or-nothing, byte-for-byte push's.
5164
+ // Any failure aborts everything: nothing is mapped and nothing is sent.
5165
+ const reasons = failures.map((f) => `${f.file}: ${f.error}`);
5166
+ for (const def of selected) {
5167
+ reasons.push(...lintDef(def).errors.map((e) => `${def.name}: ${e}`));
5168
+ reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
5169
+ const report = modelCheck(def, { assumeProvided: true });
5170
+ if (hasDefiniteCheckDefect(report)) {
5171
+ reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
5172
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
5173
+ `${report.deadlocks.length} true deadlock(s))`);
5174
+ }
5175
+ }
5176
+ // 4. Push candidates: verbatim source yaml + the server-canonical hash.
5177
+ // include:/bodyFile: defs are not hub-pushable, exactly as in `push`.
5178
+ const candidates = [];
5179
+ for (const def of selected) {
5180
+ if (!def.dir) {
5181
+ reasons.push(`${def.name}: has no source file on disk to push`);
4363
5182
  continue;
4364
5183
  }
5184
+ const yaml = readFileSync(def.dir, 'utf8');
5185
+ let usesInclude = false;
4365
5186
  try {
4366
- let res = await createWorkflowRequest(io, origin, cred, c.yaml, bundle?.digest);
4367
- if (res.status === 401 && cred.kind === 'oauth') {
4368
- cred = await refreshOAuth(io, origin, slot, cred);
4369
- res = await createWorkflowRequest(io, origin, cred, c.yaml, bundle?.digest);
4370
- }
4371
- if (res.status === 401) {
4372
- if (cred.kind === 'agent') {
4373
- throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
4374
- }
4375
- throw new CliError('credential rejected by the hub — run `owenloop login`');
4376
- }
4377
- if (res.status === 413)
4378
- throw new CliError('workflow yaml exceeds the hub 32MB request cap');
4379
- if (res.status === 429) {
4380
- const retryAfter = res.headers.get('retry-after');
4381
- throw new RateLimitError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
4382
- }
4383
- if (!res.ok)
4384
- throw new CliError(`hub returned HTTP ${res.status}`);
4385
- const bodyJson = await res.json();
4386
- const errText = createWorkflowError(bodyJson);
4387
- if (errText !== null)
4388
- throw new CliError(`hub rejected the def: ${errText}`);
4389
- const okBody = asCreateWorkflowOk(bodyJson, c.name);
4390
- if (okBody.unchanged) {
4391
- noopNames.push(c.name);
4392
- io.err(`= ${c.name} (server: unchanged, v${okBody.version})`);
4393
- }
4394
- else {
4395
- pushedNames.push(c.name);
4396
- io.err(`${label} ${c.name} (→ v${okBody.version})`);
4397
- }
5187
+ usesInclude = (buildDef(parseYaml(yaml), basename(def.dir), dirname(def.dir))._includes?.length ?? 0) > 0;
5188
+ }
5189
+ catch {
5190
+ // A shape error would already have surfaced via the gate above.
5191
+ }
5192
+ if (usesInclude) {
5193
+ reasons.push(`${def.name}: uses include:, not hub-pushable yet`);
5194
+ continue;
5195
+ }
5196
+ try {
5197
+ candidates.push({ name: def.name, hash: hashDefForHub(yaml), yaml });
4398
5198
  }
4399
5199
  catch (e) {
4400
- // A 429 halts the whole batch immediately (REL-10): record this def as
4401
- // failed, then stop — the not-yet-attempted remainder is reported as
4402
- // `skipped`, not silently hammered against a rate-limited server.
4403
- // Handled before the generic path because RateLimitError extends CliError.
4404
- if (e instanceof RateLimitError) {
4405
- const msg = e.message;
4406
- failed.push({ name: c.name, error: msg });
4407
- unsuccessful.add(c.name);
4408
- io.err(`! ${c.name} (failed: ${msg})`);
4409
- const remainder = toPush.slice(i + 1).map((r) => r.name);
4410
- skipped.push(...remainder);
4411
- for (const name of remainder)
4412
- unsuccessful.add(name);
4413
- if (remainder.length > 0) {
4414
- io.err(`stopping — rate limited by the hub; ${remainder.length} def(s) not attempted`);
4415
- }
4416
- break;
5200
+ if (e instanceof DefError && /bodyFile/.test(e.message)) {
5201
+ reasons.push(`${def.name}: uses bodyFile:, not hub-pushable`);
5202
+ continue;
4417
5203
  }
4418
- // A hard auth error aborts the whole run (re-throw); a per-def server
4419
- // failure is recorded and the batch continues (already-pushed defs stand).
4420
- if (e instanceof CliError && /run `owenloop login`|re-mint it/.test(e.message)) {
4421
- throw e;
5204
+ throw e;
5205
+ }
5206
+ }
5207
+ if (reasons.length > 0) {
5208
+ throw new CliError(`refusing to install ${sourceRef} — ${reasons.length} problem(s) found; nothing mapped, nothing published:\n - ${reasons.join('\n - ')}`);
5209
+ }
5210
+ // 5. THE NON-INTERACTIVE GUARD, before a single hub request.
5211
+ // Resolved here rather than at the first question so a piped run fails
5212
+ // with the flag names while the request log is still empty — never after
5213
+ // a mapping read has already happened. If carry-forward later covers
5214
+ // every capability, this prompt is simply never called.
5215
+ const uncovered = selected.some((def) => authoredCapabilitiesOf(def).some((cap) => requestedMap[cap] === undefined));
5216
+ const prompt = !uncovered || acceptDefaults
5217
+ ? undefined
5218
+ : requirePrompt(io, 'owenloop install needs to ask what your org should call each capability this def authors, ' +
5219
+ 'but stdin is not interactive — pass --map <authored>=<org> for each one, ' +
5220
+ 'or --accept-defaults to take the scoped <defName>.<capability> name for all of them');
5221
+ // 6. The org's existing vocabulary, so an operator choosing to LINK is
5222
+ // choosing informed. Read-only; publishes nothing.
5223
+ const { res: routesRes, cred: routesCred } = await authedGet(io, origin, slot, holder.cred, '/api/capability_routes');
5224
+ assertAuthOk(routesRes, routesCred, origin);
5225
+ holder.cred = routesCred;
5226
+ let vocabulary;
5227
+ try {
5228
+ vocabulary = asCapabilityRoutes(await routesRes.json());
5229
+ }
5230
+ catch (e) {
5231
+ throw new CliError(e.message);
5232
+ }
5233
+ // 7. Decide the vocabulary for each def: --map wins, then carry-forward,
5234
+ // then --accept-defaults, then the prompt.
5235
+ const transport = capabilityMappingTransport(io, origin, slot, holder);
5236
+ const plans = [];
5237
+ for (const def of selected) {
5238
+ const authored = authoredCapabilitiesOf(def);
5239
+ const resolved = {};
5240
+ const toRecord = {};
5241
+ if (authored.length === 0) {
5242
+ plans.push({ def, resolved, toRecord });
5243
+ continue;
5244
+ }
5245
+ const existingOrUnsupported = await fetchCapabilityMappings(transport, def.name, origin);
5246
+ const existing = existingOrUnsupported === 'unsupported' ? {} : existingOrUnsupported;
5247
+ const unsupported = existingOrUnsupported === 'unsupported';
5248
+ const needsAsking = authored.filter((cap) => requestedMap[cap] === undefined && (unsupported || existing[cap] === undefined));
5249
+ if (needsAsking.length > 0 && !acceptDefaults) {
5250
+ if (unsupported) {
5251
+ // The risk the operator must see BEFORE the first question: pressing
5252
+ // Enter through the prompts overwrites a deliberate link this hub
5253
+ // cannot report.
5254
+ io.err(`${origin} cannot report capability mappings already recorded for ${def.name} — ` +
5255
+ 'every capability will be asked about again, and the answers overwrite whatever is recorded.');
4422
5256
  }
4423
- const msg = e.message;
4424
- failed.push({ name: c.name, error: msg });
4425
- unsuccessful.add(c.name);
4426
- io.err(`! ${c.name} (failed: ${msg})`);
5257
+ io.err(`\n${def.name} authors ${authored.length} capability(ies). Enter = keep the scoped name; ` +
5258
+ 'type an org capability to link it into your existing vocabulary.');
5259
+ const vocab = formatOrgVocabulary(vocabulary);
5260
+ io.err(vocab === '' ? 'Your org routes no capabilities yet.' : `Your org already routes: ${vocab}`);
5261
+ io.err('');
5262
+ }
5263
+ for (const cap of authored) {
5264
+ const chosen = requestedMap[cap] ??
5265
+ (unsupported ? undefined : existing[cap]) ??
5266
+ (acceptDefaults || prompt === undefined
5267
+ ? scopedCapabilityName(def.name, cap)
5268
+ : await promptCapabilityMapping(io, prompt, def.name, cap));
5269
+ resolved[cap] = chosen;
5270
+ // Identity rows are dropped hub-side, and a carried-forward row the hub
5271
+ // already holds needs no rewrite — so neither is worth a write.
5272
+ if (chosen !== cap && existing[cap] !== chosen)
5273
+ toRecord[cap] = chosen;
4427
5274
  }
5275
+ plans.push({ def, resolved, toRecord });
5276
+ }
5277
+ const mapped = Object.fromEntries(plans.map((p) => [p.def.name, p.resolved]));
5278
+ const wouldRecord = plans.filter((p) => Object.keys(p.toRecord).length > 0);
5279
+ // 8. The server diff, the same source of truth `push` uses.
5280
+ const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, holder.cred, '/api/workflows');
5281
+ assertAuthOk(listRes, listCred, origin);
5282
+ holder.cred = listCred;
5283
+ let serverMap;
5284
+ try {
5285
+ serverMap = parseWorkflowList(await listRes.json());
5286
+ }
5287
+ catch (e) {
5288
+ throw new CliError(e.message);
4428
5289
  }
5290
+ const { toPush, unchanged } = computeServerDiff(candidates, serverMap, false);
5291
+ for (const c of unchanged)
5292
+ io.err(`= ${c.name} (unchanged)`);
5293
+ if (dryRun) {
5294
+ for (const c of toPush)
5295
+ io.err(c.status === 'new' ? `+ ${c.name} (new)` : `~ ${c.name} (changed)`);
5296
+ for (const plan of wouldRecord) {
5297
+ for (const [authored, org] of Object.entries(plan.toRecord)) {
5298
+ io.err(` would record ${plan.def.name}: ${authored} → ${org}`);
5299
+ }
5300
+ }
5301
+ print(io, {
5302
+ ok: true,
5303
+ dryRun: true,
5304
+ hub: origin,
5305
+ source: sourceRef,
5306
+ mapped,
5307
+ wouldRecord: Object.fromEntries(wouldRecord.map((p) => [p.def.name, p.toRecord])),
5308
+ new: toPush.filter((c) => c.status === 'new').map((c) => c.name),
5309
+ changed: toPush.filter((c) => c.status === 'changed').map((c) => c.name),
5310
+ unchanged: unchanged.map((c) => c.name),
5311
+ wouldPush: toPush.map((c) => c.name),
5312
+ });
5313
+ return 0;
5314
+ }
5315
+ // 9. RECORD, THEN PUBLISH. A hub with no mapping writer throws here — with
5316
+ // zero create_workflow calls behind it.
5317
+ const recorded = [];
5318
+ for (const plan of wouldRecord) {
5319
+ await recordCapabilityMappings(transport, plan.def.name, plan.toRecord, origin);
5320
+ recorded.push(plan.def.name);
5321
+ for (const [authored, org] of Object.entries(plan.toRecord)) {
5322
+ io.err(` recorded ${plan.def.name}: ${authored} → ${org}`);
5323
+ }
5324
+ }
5325
+ // 10. Publish, on push's ladder.
5326
+ holder.cred = await ensureFreshOAuth(io, origin, slot, holder.cred);
5327
+ const published = await publishCandidates(io, origin, slot, holder, toPush, selectedDependencies);
4429
5328
  print(io, {
4430
- ok: failed.length === 0,
5329
+ ok: published.failed.length === 0,
4431
5330
  hub: origin,
4432
- ...(bundle === undefined ? {} : { bundleDigest: bundle.digest, publication: bundle.publicationState }),
4433
- pushed: pushedNames,
4434
- noop: noopNames,
5331
+ source: sourceRef,
5332
+ mapped,
5333
+ recorded,
5334
+ pushed: published.pushed,
5335
+ noop: published.noop,
4435
5336
  unchanged: unchanged.map((c) => c.name),
4436
- skipped,
4437
- failed,
5337
+ skipped: published.skipped,
5338
+ failed: published.failed,
5339
+ capabilities: published.capabilities,
4438
5340
  });
4439
- return failed.length === 0 ? 0 : 1;
5341
+ return published.failed.length === 0 ? 0 : 1;
4440
5342
  }
4441
5343
  finally {
4442
- if (bundle !== undefined)
4443
- rmSync(bundle.cleanupRoot, { recursive: true, force: true });
5344
+ rmSync(workRoot, { recursive: true, force: true });
4444
5345
  }
4445
5346
  }
4446
5347
  /**
@@ -4626,6 +5527,7 @@ async function dispatchStart(io, args) {
4626
5527
  */
4627
5528
  async function dispatchCancel(io, args) {
4628
5529
  const workflow = need(args, 1, 'workflow');
5530
+ assertWorkflowIdShape(workflow);
4629
5531
  if (args.missingOptionValues.has('reason')) {
4630
5532
  throw new CliError('missing value for --reason: expected --reason <text>');
4631
5533
  }
@@ -4688,6 +5590,7 @@ async function dispatchCancel(io, args) {
4688
5590
  async function dispatchRetry(io, args) {
4689
5591
  const workflow = need(args, 1, 'workflow');
4690
5592
  const path = need(args, 2, 'path');
5593
+ assertWorkflowIdShape(workflow);
4691
5594
  if (args.options.has('by')) {
4692
5595
  throw new CliError('owenloop retry: --by cannot be combined with --hub — the hub attributes the retry to the authenticated human principal');
4693
5596
  }
@@ -4718,6 +5621,116 @@ async function dispatchRetry(io, args) {
4718
5621
  print(io, { ok: true, action: 'retry', path, workflow, hub: origin });
4719
5622
  return 0;
4720
5623
  }
5624
+ /** List the hub's human-input gates without reshaping its response contract. */
5625
+ async function dispatchPendingGates(io, args) {
5626
+ if (args.positionals.length !== 1) {
5627
+ throw new CliError('invalid pending-gates arguments; usage: owenloop pending-gates --hub <url>');
5628
+ }
5629
+ if (args.missingOptionValues.has('hub') || last(args, 'hub') === undefined) {
5630
+ throw new CliError('missing value for --hub: expected --hub <url>');
5631
+ }
5632
+ const origin = resolveStartHub(io, args);
5633
+ const slot = { principal: 'human' };
5634
+ const cred = readCredential(io, origin, slot);
5635
+ if (cred === null) {
5636
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5637
+ }
5638
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/pending_gates', {});
5639
+ if (res.status === 401)
5640
+ assertAuthOk(res, used, origin);
5641
+ if (!res.ok) {
5642
+ const message = await hubRequestMessage(res);
5643
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5644
+ }
5645
+ let body;
5646
+ try {
5647
+ body = (await res.json());
5648
+ }
5649
+ catch {
5650
+ throw new CliError('pending_gates: malformed success response — body is not valid JSON');
5651
+ }
5652
+ print(io, body);
5653
+ return 0;
5654
+ }
5655
+ /**
5656
+ * `owenloop reject --hub` — the human control-plane counterpart to local
5657
+ * `engine.reject()`. The hub owns attribution, so a remote request cannot
5658
+ * carry the local-only `--by` authority input.
5659
+ */
5660
+ async function dispatchReject(io, args) {
5661
+ const workflow = need(args, 1, 'workflow');
5662
+ const path = need(args, 2, 'path');
5663
+ assertWorkflowIdShape(workflow);
5664
+ if (args.options.has('by')) {
5665
+ throw new CliError('owenloop reject: --by cannot be combined with --hub — the hub attributes the rejection to the authenticated human principal');
5666
+ }
5667
+ const text = last(args, 'text');
5668
+ if (args.missingOptionValues.has('text') || text === undefined) {
5669
+ throw new CliError('missing value for --text: expected --text <reason>');
5670
+ }
5671
+ if (text.trim() === '') {
5672
+ throw new CliError('invalid empty value for --text: expected --text <reason>');
5673
+ }
5674
+ if (args.missingOptionValues.has('requested')) {
5675
+ throw new CliError('missing value for --requested: expected --requested <modifier>');
5676
+ }
5677
+ const requested = last(args, 'requested');
5678
+ const origin = resolveStartHub(io, args);
5679
+ const slot = { principal: 'human' };
5680
+ const cred = readCredential(io, origin, slot);
5681
+ if (cred === null) {
5682
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5683
+ }
5684
+ const request = {
5685
+ workflow,
5686
+ path,
5687
+ reason: text,
5688
+ ...(requested !== undefined ? { requested } : {}),
5689
+ };
5690
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/reject_artifact', request);
5691
+ if (res.status === 401)
5692
+ assertAuthOk(res, used, origin);
5693
+ if (!res.ok) {
5694
+ const message = await hubRequestMessage(res);
5695
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5696
+ }
5697
+ print(io, {
5698
+ ok: true,
5699
+ action: 'reject',
5700
+ path,
5701
+ workflow,
5702
+ hub: origin,
5703
+ ...(requested !== undefined ? { requested } : {}),
5704
+ });
5705
+ return 0;
5706
+ }
5707
+ /**
5708
+ * `owenloop provide --hub` — supply a hosted workflow input using the human
5709
+ * control plane. Local input provisioning remains in `main()`.
5710
+ */
5711
+ async function dispatchProvide(io, args) {
5712
+ const workflow = need(args, 1, 'workflow');
5713
+ const name = need(args, 2, 'name');
5714
+ assertWorkflowIdShape(workflow);
5715
+ // Keep this ahead of binding, credentials, and fetch: malformed input has no
5716
+ // external effects, matching the local provide command's JSON contract.
5717
+ const value = parseJson(last(args, 'value'));
5718
+ const origin = resolveStartHub(io, args);
5719
+ const slot = { principal: 'human' };
5720
+ const cred = readCredential(io, origin, slot);
5721
+ if (cred === null) {
5722
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5723
+ }
5724
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/provide_input', { workflow, name, value });
5725
+ if (res.status === 401)
5726
+ assertAuthOk(res, used, origin);
5727
+ if (!res.ok) {
5728
+ const message = await hubRequestMessage(res);
5729
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
5730
+ }
5731
+ print(io, { ok: true, provided: name, workflow, hub: origin });
5732
+ return 0;
5733
+ }
4721
5734
  /**
4722
5735
  * `owenloop instance` — read a HUB instance's live state from the terminal.
4723
5736
  *
@@ -4761,14 +5774,15 @@ async function dispatchInstance(io, args) {
4761
5774
  if (workflow === undefined || workflow === '') {
4762
5775
  throw new CliError(`missing required argument: workflow (${USAGE_FORMS})`);
4763
5776
  }
5777
+ assertWorkflowIdShape(workflow);
4764
5778
  const origin = resolveStartHub(io, args);
4765
5779
  const slot = { principal: 'human' };
4766
5780
  const cred = readCredential(io, origin, slot);
4767
5781
  if (cred === null) {
4768
5782
  throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
4769
5783
  }
4770
- // The workflow id is a path segment, so it must be encoded — an id carrying a
4771
- // slash would otherwise silently address a different route.
5784
+ // Retain path-segment encoding as defense in depth: the validator currently
5785
+ // excludes slashes, but the hub remains a separate service boundary.
4772
5786
  const path = `/api/status/${encodeURIComponent(workflow)}`;
4773
5787
  const { res, cred: used } = await authedGet(io, origin, slot, cred, path);
4774
5788
  if (res.status === 401)
@@ -5177,8 +6191,8 @@ async function dispatchCapability(io, args) {
5177
6191
  if (sub === 'list') {
5178
6192
  const { res, cred: used } = await authedGet(io, origin, slot, cred, '/api/capability_routes');
5179
6193
  // The GET deliberately uses `assertAuthOk` unchanged (frozen contract), so
5180
- // a non-401 non-2xx surfaces its generic wording rather than the hub's
5181
- // `message`. Message passthrough is a POST-path behavior below.
6194
+ // a non-401/non-429 non-2xx surfaces its generic wording while a 429 uses
6195
+ // the helper's rate-limit wording. Message passthrough is a POST-path behavior below.
5182
6196
  assertAuthOk(res, used, origin);
5183
6197
  let body;
5184
6198
  try {
@@ -5338,7 +6352,7 @@ async function dispatchCapability(io, args) {
5338
6352
  * finds out it happened.
5339
6353
  *
5340
6354
  * **`routing show <workflow>` is NOT the local `show` command.** `owenloop show`
5341
- * reads a workflow DEFINITION out of the local sqlite store and takes no `--hub`;
6355
+ * reads raw workflow artifacts out of the local sqlite store and takes no `--hub`;
5342
6356
  * `routing show` reads one STARTED RUN's routing state off the hub. They share no
5343
6357
  * code path, and this deliberately did not arrive as a `--hub` flag on the local
5344
6358
  * command — the same separation `instance show` keeps.
@@ -5396,6 +6410,7 @@ async function dispatchRouting(io, args) {
5396
6410
  if (rawWorkflow === undefined || rawWorkflow === '') {
5397
6411
  throw new CliError(`missing required argument: <workflow> (${USAGE_FORMS})`);
5398
6412
  }
6413
+ assertWorkflowIdShape(rawWorkflow);
5399
6414
  workflow = rawWorkflow;
5400
6415
  }
5401
6416
  else if (sub === 'alerts') {
@@ -5514,9 +6529,8 @@ async function dispatchRouting(io, args) {
5514
6529
  return 0;
5515
6530
  }
5516
6531
  if (sub === 'show') {
5517
- // The workflow id is a path segment, so it must be encoded — an id carrying
5518
- // a slash would otherwise silently address a different route
5519
- // (`dispatchInstance`'s precedent).
6532
+ // Retain path-segment encoding as defense in depth: the validator currently
6533
+ // excludes slashes, but the hub remains a separate service boundary.
5520
6534
  const body = await readJson(`/api/run_routing/${encodeURIComponent(workflow)}`, 'run_routing: malformed success response');
5521
6535
  let wire;
5522
6536
  try {
@@ -5787,8 +6801,9 @@ async function dispatchCrew(io, args) {
5787
6801
  try {
5788
6802
  if (sub === 'list') {
5789
6803
  const { res, cred: used } = await authedGet(io, origin, slot, cred, '/api/crews');
5790
- // `assertAuthOk`'s generic wording (frozen contract, mirrors `binding
5791
- // list`); message passthrough is a POST-path behavior below.
6804
+ // `assertAuthOk`'s generic wording for non-401/non-429 errors (frozen
6805
+ // contract, mirrors `binding list`); a 429 uses its rate-limit wording.
6806
+ // Message passthrough is a POST-path behavior below.
5792
6807
  assertAuthOk(res, used, origin);
5793
6808
  let body;
5794
6809
  try {
@@ -6200,18 +7215,24 @@ async function probeAgentSlots(io, origin, names, identities) {
6200
7215
  return { verified, sawSlot, sawRevoked };
6201
7216
  }
6202
7217
  /**
6203
- * The interactive prompt for setup, or the non-interactive guard. Returns
6204
- * `io.prompt` when injected; else, when stdin is a real TTY, the default
6205
- * readline prompt; else a `CliError` naming the two bypass flags — thrown BEFORE
6206
- * any mutation so a scripted/piped run never blocks or half-applies.
7218
+ * The interactive prompt for a verb that must ask, or the non-interactive
7219
+ * guard. Returns `io.prompt` when injected; else, when stdin is a real TTY, the
7220
+ * default readline prompt; else a `CliError` naming that verb's bypass flags —
7221
+ * thrown BEFORE any mutation (and, for `install`, before any hub I/O at all) so
7222
+ * a scripted/piped run never blocks and never half-applies.
7223
+ *
7224
+ * `unavailable` is the refusal wording. It defaults to `setup`'s, so `setup`'s
7225
+ * callers keep their message byte-for-byte; `install` passes its own, which
7226
+ * must name `--map` and `--accept-defaults`.
6207
7227
  */
6208
- function requirePrompt(io) {
7228
+ function requirePrompt(io, unavailable) {
6209
7229
  if (io.prompt)
6210
7230
  return io.prompt;
6211
7231
  if (process.stdin.isTTY)
6212
7232
  return defaultPrompt;
6213
- throw new CliError('setup needs to ask which Scoped Identity to use, but stdin is not interactive — pass ' +
6214
- '--new-agent <name> to create a new Scoped Identity, or --replace-agent <name> to replace an existing one');
7233
+ throw new CliError(unavailable ??
7234
+ 'setup needs to ask which Scoped Identity to use, but stdin is not interactive — pass ' +
7235
+ '--new-agent <name> to create a new Scoped Identity, or --replace-agent <name> to replace an existing one');
6215
7236
  }
6216
7237
  /**
6217
7238
  * Prompt for an agent name (Flow A). Offers `sanitizeAgentName(hostname())` as a
@@ -7188,7 +8209,7 @@ async function runDoctor(io, origin) {
7188
8209
  * the async path, so every existing command and test keeps working exactly as
7189
8210
  * before.
7190
8211
  */
7191
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'cancel', 'retry', 'instance', 'agent', 'capability', 'routing', 'crew', 'roster', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
8212
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'install', 'start', 'pending-gates', 'cancel', 'provide', 'reject', 'retry', 'instance', 'agent', 'capability', 'routing', 'crew', 'roster', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
7192
8213
  export async function mainAsync(argv, io = defaultIO()) {
7193
8214
  // Delegate execution-side and shift argv tails before root parsing. Their
7194
8215
  // roles own their option grammars, including repeated/value forms that the
@@ -7214,13 +8235,16 @@ export async function mainAsync(argv, io = defaultIO()) {
7214
8235
  }
7215
8236
  const args = parseArgs(argv);
7216
8237
  const command = args.positionals[0];
7217
- if (command === undefined || !ASYNC_COMMANDS.has(command)) {
8238
+ const asyncBundleGc = command === 'bundle' && args.positionals[1] === 'gc';
8239
+ if (command === undefined || (!ASYNC_COMMANDS.has(command) && !asyncBundleGc)) {
7218
8240
  return main(argv, io);
7219
8241
  }
7220
8242
  try {
7221
8243
  const short = preflight(command, args, io);
7222
8244
  if (short !== undefined)
7223
8245
  return short;
8246
+ if (asyncBundleGc)
8247
+ return await dispatchBundleGc(io, args);
7224
8248
  switch (command) {
7225
8249
  case 'add':
7226
8250
  return await dispatchAdd(io, args);
@@ -7236,10 +8260,18 @@ export async function mainAsync(argv, io = defaultIO()) {
7236
8260
  return await dispatchTrust(io, args);
7237
8261
  case 'push':
7238
8262
  return await dispatchPush(io, args);
8263
+ case 'install':
8264
+ return await dispatchInstall(io, args);
7239
8265
  case 'start':
7240
8266
  return await dispatchStart(io, args);
8267
+ case 'pending-gates':
8268
+ return args.options.has('hub') ? await dispatchPendingGates(io, args) : main(argv, io);
7241
8269
  case 'cancel':
7242
8270
  return await dispatchCancel(io, args);
8271
+ case 'provide':
8272
+ return args.options.has('hub') ? await dispatchProvide(io, args) : main(argv, io);
8273
+ case 'reject':
8274
+ return args.options.has('hub') ? await dispatchReject(io, args) : main(argv, io);
7243
8275
  case 'retry':
7244
8276
  // Local engine store unless --hub; only the hub half is async, and
7245
8277
  // main()'s own `case 'retry'` stays the local implementation so the