owenloop 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * argv to engine calls.
9
9
  *
10
10
  * owenloop defs list available workflow definitions
11
+ * owenloop add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)
11
12
  * owenloop create <def> [--provide n=json] [--title t] start an instance
12
13
  * owenloop provide <wf> <name> [--value json] supply an owed input
13
14
  * owenloop tick <wf> [--now ms] pull eligible orders
@@ -30,21 +31,73 @@
30
31
  *
31
32
  * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
32
33
  */
33
- import { existsSync, mkdirSync } from 'node:fs';
34
- import { dirname, join } from 'node:path';
34
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
35
+ import { basename, dirname, join, resolve } from 'node:path';
36
+ import { spawn } from 'node:child_process';
37
+ import { createServer } from 'node:http';
38
+ import { parse as parseYaml } from 'yaml';
35
39
  import { Engine } from "./engine.js";
36
40
  import { buildGraph, buildTrace, graphToDot, graphToMermaid, modelCheck } from "./model.js";
37
41
  import { openStore } from "./store.js";
38
- import { DefError, lintDef, loadDefs, loadDefsRaw, validateDef } from "./defs.js";
39
- import { detId, nowMs, parseDurationMs } from "./util.js";
42
+ import { buildDef, DefError, finalizeDefs, lintDef, loadDefs, loadDefsRaw, loadDefsUnfinalized, validateDef, } from "./defs.js";
43
+ import { dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
44
+ import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
45
+ import { acquireInstallLock, ADD_JOURNAL_FILENAME, archivePathViolation, commitInstall, finalizeInstallCommit, githubShaUrl, githubTarballUrl, installFolder, parkOldNameDir, parseRepoSpec, readLockfile, recoverInterruptedInstall, releaseInstallLock, removeAddJournal, rollbackInstallCommit, RollbackFailedError, stageFiles, STAGING_DIRNAME, writeAddJournal, writeLockfile, } from "./add.js";
46
+ import { asCreateWorkflowOk, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
40
47
  function defaultIO() {
41
48
  return {
42
49
  cwd: process.cwd(),
43
50
  env: process.env,
44
51
  out: (s) => process.stdout.write(`${s}\n`),
45
52
  err: (s) => process.stderr.write(`${s}\n`),
53
+ fetch: globalThis.fetch,
54
+ openUrl: defaultOpenUrl,
55
+ readStdin: defaultReadStdin,
46
56
  };
47
57
  }
58
+ /** Fire-and-forget browser open — never blocks the login flow on the child. */
59
+ function defaultOpenUrl(url) {
60
+ const platform = process.platform;
61
+ const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'start' : 'xdg-open';
62
+ try {
63
+ spawn(cmd, [url], { stdio: 'ignore', detached: true }).unref();
64
+ }
65
+ catch {
66
+ // Non-fatal: the URL is also printed to stderr for the user to open manually.
67
+ }
68
+ }
69
+ async function defaultReadStdin() {
70
+ const chunks = [];
71
+ for await (const chunk of process.stdin)
72
+ chunks.push(chunk);
73
+ return Buffer.concat(chunks).toString('utf8');
74
+ }
75
+ /**
76
+ * Flags that are always boolean and must never consume the following token as
77
+ * a value — `owenloop push --force foo` must force-push only `foo`, not treat
78
+ * `foo` as `--force`'s value and swallow it from the positionals. Audited
79
+ * against every `flag(args, ...)` call site in this file. `now` is dual-mode:
80
+ * a bare boolean for `reap`, but `tick` reads it as `--now=<ms>` (the `=` form
81
+ * bypasses this set entirely, handled by the `eq >= 0` branch below); the
82
+ * space-separated `--now 123` form intentionally no longer binds `123` as
83
+ * `now`'s value — docs/cli.md documents only `--now=<ms>`.
84
+ */
85
+ const BOOLEAN_FLAGS = new Set([
86
+ 'assume-provided',
87
+ 'shallow',
88
+ 'now',
89
+ 'all',
90
+ 'open',
91
+ 'terminal',
92
+ 'recursive',
93
+ 'with-token',
94
+ 'dry-run',
95
+ 'force',
96
+ // `add --recover` takes NO value: `add --recover acme/widgets` must keep
97
+ // `acme/widgets` as a positional so the recover branch can refuse it, rather
98
+ // than binding it as `--recover`'s value and silently dropping it.
99
+ 'recover',
100
+ ]);
48
101
  function parseArgs(argv) {
49
102
  const positionals = [];
50
103
  const options = new Map();
@@ -58,6 +111,9 @@ function parseArgs(argv) {
58
111
  val = key.slice(eq + 1);
59
112
  key = key.slice(0, eq);
60
113
  }
114
+ else if (BOOLEAN_FLAGS.has(key)) {
115
+ val = 'true'; // never consume the next token for a known-boolean flag
116
+ }
61
117
  else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) {
62
118
  val = argv[++i];
63
119
  }
@@ -85,6 +141,17 @@ const flag = (args, key) => {
85
141
  };
86
142
  class CliError extends Error {
87
143
  }
144
+ /**
145
+ * A 429 from the hub during a push batch (REL-10). Thrown from the batch loop
146
+ * and handled by an explicit `instanceof` branch that halts the rest of the
147
+ * batch and surfaces `Retry-After` — NOT folded into the generic per-def
148
+ * failure path or matched by message regex. Keeping it a distinct class is the
149
+ * fix for the shared-catch gotcha (knowledge node "CLI: split a shared
150
+ * switch-case when one verb's return type changes"): branch on the type, never
151
+ * on the message text.
152
+ */
153
+ class RateLimitError extends CliError {
154
+ }
88
155
  function need(args, idx, label) {
89
156
  const v = args.positionals[idx];
90
157
  if (v === undefined)
@@ -97,6 +164,17 @@ function needOpt(args, key) {
97
164
  throw new CliError(`missing required option: --${key}`);
98
165
  return v;
99
166
  }
167
+ /** Read an optional numeric flag; throw a CliError (never NaN) on a non-finite value. */
168
+ function numOpt(args, key) {
169
+ const raw = last(args, key);
170
+ if (raw === undefined)
171
+ return undefined;
172
+ const n = Number(raw);
173
+ if (!Number.isFinite(n)) {
174
+ throw new CliError(`invalid value for --${key}: expected --${key}=<number> (got "${raw}")`);
175
+ }
176
+ return n;
177
+ }
100
178
  function parseJson(s, fallback = {}) {
101
179
  if (s === undefined)
102
180
  return fallback;
@@ -135,12 +213,109 @@ function parsePairs(entries, jsonValue) {
135
213
  }
136
214
  return out;
137
215
  }
216
+ /**
217
+ * Load the DEFAULT def set, folding in the defs `owenloop add` installed under
218
+ * ledger-recorded subfolders of `defsDir` so `defs`/`create`/`tick`/etc. see
219
+ * them by name with NO `--defs` flag. Called ONLY when the operator did not
220
+ * override the defs dir (see {@link openCtx}) — an explicit `--defs`/`OWENLOOP_DEFS`
221
+ * targets a specific literal dir and keeps today's pure-scan behavior, including
222
+ * `--defs workflows/<owner>-<repo>-<hash>` pointed straight at an install folder.
223
+ *
224
+ * The composition is ledger-DRIVEN and BOUNDED: it only folds in folders named
225
+ * by fail-closed-validated `installed.json` entries (never a raw tree recurse),
226
+ * and it stays in the CLI layer (where both cwd and defsDir are known) so
227
+ * `loadDefs`/`loadDefsUnfinalized` in defs.ts hold no ledger knowledge.
228
+ *
229
+ * Two-phase discipline: it merges the RAW (unfinalized) maps of the base dir and
230
+ * each install folder, then runs ONE `finalizeDefs` over the union. That single
231
+ * finalize is what lets a project-local def `calls:` an installed def across the
232
+ * boundary — finalizing each dir independently would throw "does not exist"
233
+ * before the merge. When the ledger is empty/missing the result is exactly
234
+ * `finalizeDefs(loadDefsUnfinalized(defsDir))` === today's `loadDefs(defsDir)`:
235
+ * zero behavior drift on the no-installs path.
236
+ *
237
+ * Precedence: project-local (base) defs WIN over installed defs; among installed
238
+ * entries, ledger sources are iterated in sorted order and the FIRST-loaded def
239
+ * with a given name wins. Every shadowed def is surfaced as a warning on stderr,
240
+ * never a silent clobber. Note the outer base scan ALREADY loads an install
241
+ * folder's `workflow.yaml` via its immediate-subdir rule, while the fold-in
242
+ * loads that folder's top-level `*.yaml` (excluding `workflow.yaml`) — the two
243
+ * scans are disjoint per file, so no file is ever loaded twice and any name
244
+ * collision is a genuine two-file collision.
245
+ *
246
+ * Fail-OPEN: the fold-in never breaks base loading. A corrupt/invalid ledger, a
247
+ * missing install folder, or an install folder that fails to load each emits a
248
+ * warning on stderr and is skipped; base defs still load. (The add-time
249
+ * fail-closed validation in add.ts is untouched — we consume `readLockfile`,
250
+ * discovery merely refuses to act on a bad ledger rather than crashing.)
251
+ */
252
+ function loadDefsWithInstalled(io, defsDir) {
253
+ const merged = existsSync(defsDir) ? loadDefsUnfinalized(defsDir) : new Map();
254
+ let lf;
255
+ try {
256
+ lf = readLockfile(join(io.cwd, '.owenloop', 'installed.json'));
257
+ }
258
+ catch (e) {
259
+ io.err(`warning: skipping installed workflow defs: ${e.message}`);
260
+ return finalizeDefs(merged);
261
+ }
262
+ for (const source of Object.keys(lf.installed).sort()) {
263
+ const entry = lf.installed[source];
264
+ if (entry === undefined)
265
+ continue; // unreachable — keys come from lf.installed
266
+ const entryDir = join(defsDir, entry.path);
267
+ if (!existsSync(entryDir)) {
268
+ io.err(`warning: installed defs folder missing for ${source}: ${entry.path}`);
269
+ continue;
270
+ }
271
+ let entryRaw;
272
+ try {
273
+ entryRaw = loadDefsUnfinalized(entryDir);
274
+ }
275
+ catch (e) {
276
+ io.err(`warning: failed to load installed defs for ${source} (${entry.path}): ${e.message}`);
277
+ continue;
278
+ }
279
+ for (const [name, def] of entryRaw) {
280
+ const winner = merged.get(name);
281
+ if (winner !== undefined) {
282
+ io.err(`warning: workflow '${name}' from ${def.dir ?? entryDir} is shadowed by ${winner.dir ?? 'project defs'} (project defs take precedence over installed defs)`);
283
+ continue;
284
+ }
285
+ merged.set(name, def);
286
+ }
287
+ }
288
+ return finalizeDefs(merged);
289
+ }
138
290
  function openCtx(io, args) {
139
- const dbPath = last(args, 'db') ?? io.env.OWENLOOP_DB ?? join(io.cwd, '.owenloop', 'state.db');
140
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
141
- mkdirSync(dirname(dbPath), { recursive: true });
291
+ const dbOverride = last(args, 'db') ?? io.env.OWENLOOP_DB;
292
+ const dbPath = dbOverride ?? join(io.cwd, '.owenloop', 'state.db');
293
+ // An explicit `--defs`/`OWENLOOP_DEFS` is the operator targeting a literal dir
294
+ // (keep pure-scan behavior, no ledger fold-in); its ABSENCE means the default
295
+ // dir, where `add` installs and the ledger's folders live — fold installed
296
+ // defs in there. The rule is "was an override given", not path equality: even
297
+ // `OWENLOOP_DEFS=<cwd>/workflows` counts as an override and stays literal.
298
+ const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
299
+ const defsDir = defsOverride ?? join(io.cwd, 'workflows');
300
+ // Guard the built-in default (`cwd/.owenloop/state.db`) against a symlinked
301
+ // `.owenloop` from a hostile checkout (SEC-3). Directory guard first, then the
302
+ // file-level guard on `state.db` and its SQLite sidecars — a symlinked db file
303
+ // inside a REAL `.owenloop` would otherwise redirect writes SQLite follows. An
304
+ // explicit `--db`/`OWENLOOP_DB` comes from the operator, not the repo —
305
+ // deliberately pointing state through a symlink is intent, so keep today's
306
+ // behavior for overrides.
307
+ if (dbOverride === undefined) {
308
+ mkdirRefusingSymlink(dirname(dbPath));
309
+ dbPathRefusingSymlink(dbPath);
310
+ }
311
+ else
312
+ mkdirSync(dirname(dbPath), { recursive: true });
142
313
  const store = openStore(dbPath);
143
- const defs = existsSync(defsDir) ? loadDefs(defsDir) : new Map();
314
+ const defs = defsOverride !== undefined
315
+ ? existsSync(defsDir)
316
+ ? loadDefs(defsDir)
317
+ : new Map()
318
+ : loadDefsWithInstalled(io, defsDir);
144
319
  const engine = new Engine(store, (name) => {
145
320
  const d = defs.get(name);
146
321
  if (!d)
@@ -163,21 +338,29 @@ function sleepMs(ms) {
163
338
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
164
339
  }
165
340
  // ---- commands ----------------------------------------------------------------
166
- const USAGE = `owenloop — a dataflow workflow engine
341
+ export const USAGE = `owenloop — a dataflow workflow engine
167
342
 
168
343
  Usage: owenloop <command> [args] [--db <path>] [--defs <dir>]
169
344
 
170
345
  Commands:
171
346
  defs list available workflow definitions
347
+ add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)
348
+ add --recover finish or undo a crash-interrupted install (offline; no network)
349
+ login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)
350
+ logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot
351
+ connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
352
+ push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)
353
+ --as names the credential slot: human (default), agent, or agent:<account>
172
354
  lint [<def-name>] check def(s) for wiring problems
173
355
  check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided]
174
356
  bounded reachability check (deadlocks, stuck, dead steps, declared invariants)
175
357
  create <def> [--title t] [--provide name=json ...] [--param k=v ...]
176
358
  provide <wf> <name> [--value json] supply an owed (seedOwed) input
177
359
  adopt <wf> re-pin an instance to the current def (§28); settles new debts
178
- tick <wf> [--now <ms>] pull eligible orders
360
+ tick <wf> [--now <ms>] [--shallow] [--label <l>]... pull eligible orders (deep: also from calls: children; --shallow for this instance only; --label filters to matching-label steps)
179
361
  reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)
180
362
  runs <wf> [--open] list this instance's runs (+ claim state for open ones)
363
+ order <wf> <run> print the order packet issued at claim time (persisted in the claim txn)
181
364
  status <wf> derive debts / eligible / blocked
182
365
  status --all every instance's status in one call (fleet read)
183
366
  wait <wf> --until eligible|done [--timeout <dur>] block until engine state matches
@@ -203,6 +386,133 @@ function failureNote(failures) {
203
386
  return '';
204
387
  return `\n${failures.length} file(s) failed to load:\n - ${failures.map((f) => `${f.file}: ${f.error}`).join('\n - ')}`;
205
388
  }
389
+ /**
390
+ * Options accepted on EVERY command. docs/cli.md documents `--db`/`--defs` as
391
+ * global ("pass both on every command"), so they are allowlisted everywhere —
392
+ * even on commands that ignore them — to avoid rejecting a documented
393
+ * invocation.
394
+ */
395
+ const GLOBAL_OPTIONS = ['db', 'defs'];
396
+ /** Build a command's option allowlist: the two globals plus its own long-form flags. */
397
+ const cmdOpts = (...extra) => new Set([...GLOBAL_OPTIONS, ...extra]);
398
+ /**
399
+ * Single source of truth for the `--options` each command accepts, consulted by
400
+ * `preflight` before any side effect. Unknown-OPTION rejection AND
401
+ * unknown-COMMAND detection both derive from this table: a developer who adds a
402
+ * new `dispatch`/`ASYNC_COMMANDS` case without a matching entry here gets
403
+ * `unknown command` on the very first invocation, so the command cannot run
404
+ * until its flags are declared. That is the forcing function that stops the
405
+ * silently-dropped-flag hole (a misspelled `push --dryrn` doing a real push)
406
+ * from reappearing — keep this table in lockstep with the dispatch verbs and
407
+ * the USAGE string. All names are long-form: this CLI has no short options
408
+ * (`-h` reaches dispatch as a positional). Values are audited against every
409
+ * `last/all/flag/needOpt/numOpt` call site.
410
+ */
411
+ export const COMMAND_OPTIONS = new Map([
412
+ ['help', cmdOpts()],
413
+ ['defs', cmdOpts()],
414
+ ['add', cmdOpts('recover')],
415
+ ['login', cmdOpts('hub', 'with-token', 'as')],
416
+ ['logout', cmdOpts('hub', 'as')],
417
+ ['connect', cmdOpts('hub', 'as')],
418
+ ['push', cmdOpts('dry-run', 'force', 'hub', 'as')],
419
+ ['lint', cmdOpts()],
420
+ ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided')],
421
+ ['create', cmdOpts('title', 'provide', 'param')],
422
+ ['provide', cmdOpts('value')],
423
+ ['adopt', cmdOpts()],
424
+ ['tick', cmdOpts('now', 'shallow', 'label')],
425
+ ['reap', cmdOpts('now')],
426
+ ['status', cmdOpts('all')],
427
+ ['wait', cmdOpts('until', 'timeout')],
428
+ ['show', cmdOpts()],
429
+ ['trace', cmdOpts('format')],
430
+ ['runs', cmdOpts('open')],
431
+ ['order', cmdOpts()],
432
+ ['list', cmdOpts()],
433
+ ['green', cmdOpts('value', 'terminal')],
434
+ ['emit', cmdOpts('items')],
435
+ ['seal', cmdOpts('value')],
436
+ ['reject', cmdOpts('by', 'text')],
437
+ ['retract', cmdOpts('by', 'text')],
438
+ ['skip', cmdOpts('by', 'text')],
439
+ ['retry', cmdOpts('by', 'text')],
440
+ ['close', cmdOpts('outcome', 'summary')],
441
+ ['heartbeat', cmdOpts('now')],
442
+ ['delete', cmdOpts('recursive')],
443
+ ['graph', cmdOpts('format')],
444
+ ]);
445
+ /** Levenshtein edit distance (small DP, no deps) — used only for "did you mean" hints. */
446
+ function editDistance(a, b) {
447
+ const m = a.length;
448
+ const n = b.length;
449
+ let prev = new Array(n + 1);
450
+ let curr = new Array(n + 1);
451
+ for (let j = 0; j <= n; j++)
452
+ prev[j] = j;
453
+ for (let i = 1; i <= m; i++) {
454
+ curr[0] = i;
455
+ for (let j = 1; j <= n; j++) {
456
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
457
+ const del = prev[j] + 1;
458
+ const ins = curr[j - 1] + 1;
459
+ const sub = prev[j - 1] + cost;
460
+ curr[j] = Math.min(del, ins, sub);
461
+ }
462
+ [prev, curr] = [curr, prev];
463
+ }
464
+ return prev[n];
465
+ }
466
+ /**
467
+ * Reject any `--option` the target command does not declare in
468
+ * `COMMAND_OPTIONS`. Names each offender with its `--` prefix, suggests the
469
+ * nearest valid option (edit distance ≤ 2), and lists the command's valid
470
+ * options. Throws `CliError` (exit 1 via the entry-point catch). Runs BEFORE
471
+ * any side effect — see `preflight`.
472
+ */
473
+ function assertKnownOptions(command, args) {
474
+ const allowed = COMMAND_OPTIONS.get(command);
475
+ if (!allowed)
476
+ return; // unknown command is handled separately (in preflight)
477
+ const unknown = [...args.options.keys()].filter((k) => !allowed.has(k));
478
+ if (unknown.length === 0)
479
+ return;
480
+ const lines = unknown.map((k) => {
481
+ const base = `unknown option --${k} for '${command}'`;
482
+ const near = k.length > 0
483
+ ? [...allowed]
484
+ .map((o) => ({ o, d: editDistance(k, o) }))
485
+ .filter((c) => c.d <= 2)
486
+ .sort((a, b) => a.d - b.d)[0]
487
+ : undefined;
488
+ return near ? `${base} (did you mean --${near.o}?)` : base;
489
+ });
490
+ const validSorted = [...allowed].map((o) => `--${o}`).sort();
491
+ throw new CliError(`${lines.join('\n')}\nvalid options for '${command}': ${validSorted.join(', ')}`);
492
+ }
493
+ /**
494
+ * Pre-dispatch guard shared by both entry points (`main` and `mainAsync`) so
495
+ * the sync and async paths cannot drift. In order: the help escape hatch
496
+ * (`help`/`--help`/`-h`, or `--help` given anywhere e.g. `push --help`) prints
497
+ * usage and short-circuits with exit 0; an unrecognized command throws the same
498
+ * `unknown command` error dispatch's `default:` produces (but now before
499
+ * `openCtx`, so it no longer creates `.owenloop/state.db`); then unknown
500
+ * options are rejected. All of this runs ahead of any filesystem, keychain, or
501
+ * network I/O. Returns an exit code to short-circuit on, or `undefined` to
502
+ * proceed to dispatch. `command` is always defined here — callers own the
503
+ * no-command usage branch.
504
+ */
505
+ function preflight(command, args, io) {
506
+ if (command === 'help' || command === '--help' || command === '-h' || args.options.has('help')) {
507
+ io.out(USAGE);
508
+ return 0;
509
+ }
510
+ if (!COMMAND_OPTIONS.has(command)) {
511
+ throw new CliError(`unknown command: ${command}\n\n${USAGE}`);
512
+ }
513
+ assertKnownOptions(command, args);
514
+ return undefined;
515
+ }
206
516
  function dispatch(command, io, args) {
207
517
  // help and lint need no store
208
518
  if (command === 'help' || command === '--help' || command === '-h') {
@@ -260,9 +570,9 @@ function dispatch(command, io, args) {
260
570
  throw new CliError(`workflow '${def.name}' has validation errors:\n - ${defErrors.join('\n - ')}`);
261
571
  }
262
572
  const format = last(args, 'format') ?? 'text';
263
- const maxDepth = last(args, 'max-depth') !== undefined ? Number(last(args, 'max-depth')) : undefined;
264
- const maxStates = last(args, 'max-states') !== undefined ? Number(last(args, 'max-states')) : undefined;
265
- const maxCollection = last(args, 'max-collection') !== undefined ? Number(last(args, 'max-collection')) : undefined;
573
+ const maxDepth = numOpt(args, 'max-depth');
574
+ const maxStates = numOpt(args, 'max-states');
575
+ const maxCollection = numOpt(args, 'max-collection');
266
576
  const report = modelCheck(def, {
267
577
  ...(maxDepth !== undefined ? { maxDepth } : {}),
268
578
  ...(maxStates !== undefined ? { maxStates } : {}),
@@ -381,8 +691,19 @@ function dispatch(command, io, args) {
381
691
  }
382
692
  case 'tick': {
383
693
  const wf = need(args, 1, 'workflow');
384
- const nowRaw = last(args, 'now');
385
- const tickOpts = nowRaw !== undefined ? { now: Number(nowRaw) } : {};
694
+ const now = numOpt(args, 'now');
695
+ // §23.6.8: tick is deep by default (descends into calls: children and
696
+ // returns their orders too); --shallow restores single-instance ticking.
697
+ const tickOpts = {};
698
+ if (now !== undefined)
699
+ tickOpts.now = now;
700
+ if (flag(args, 'shallow'))
701
+ tickOpts.deep = false;
702
+ // A2: repeatable --label narrows the claim to steps whose labels
703
+ // intersect the caller's; absent = claim everything (today's behavior).
704
+ const labels = all(args, 'label');
705
+ if (labels.length > 0)
706
+ tickOpts.labels = labels;
386
707
  print(io, engine.tick(wf, tickOpts));
387
708
  return 0;
388
709
  }
@@ -409,8 +730,9 @@ function dispatch(command, io, args) {
409
730
  // `--all` is the whole-fleet read; a workflow argument is
410
731
  // contradictory (one or all?). Reject it in both orderings rather
411
732
  // than silently ignoring the caller's intent:
412
- // `status wf --all` → the wf lands in positionals[1]
413
- // `status --all wf` → the parser binds wf as `--all`'s value
733
+ // `status wf --all` / `status --all wf` → the wf lands in positionals[1]
734
+ // (`all` is a boolean flag and never consumes the next token)
735
+ // `status --all=wf` → the `=` form binds wf as `--all`'s value
414
736
  const v = last(args, 'all');
415
737
  const stray = args.positionals[1] ?? (v !== 'true' && v !== '' ? v : undefined);
416
738
  if (stray !== undefined) {
@@ -565,6 +887,19 @@ function dispatch(command, io, args) {
565
887
  print(io, rows);
566
888
  return 0;
567
889
  }
890
+ case 'order': {
891
+ const wf = need(args, 1, 'workflow');
892
+ const run = need(args, 2, 'run');
893
+ const r = store.getRun(run);
894
+ if (!r)
895
+ throw new CliError(`run not found: ${run}`);
896
+ if (r.workflow !== wf)
897
+ throw new CliError(`run ${run} belongs to workflow ${r.workflow}, not ${wf}`);
898
+ if (r.order === undefined)
899
+ throw new CliError(`run ${run} has no persisted order (created before order persistence, schema v7)`);
900
+ print(io, r.order);
901
+ return 0;
902
+ }
568
903
  case 'list': {
569
904
  print(io, store.listWorkflows().map((w) => {
570
905
  const s = safeStatus(engine, w.id);
@@ -672,8 +1007,7 @@ function dispatch(command, io, args) {
672
1007
  case 'heartbeat': {
673
1008
  const wf = need(args, 1, 'workflow');
674
1009
  const run = need(args, 2, 'run');
675
- const nowRaw = last(args, 'now');
676
- engine.heartbeat(wf, run, nowRaw !== undefined ? Number(nowRaw) : undefined);
1010
+ engine.heartbeat(wf, run, numOpt(args, 'now'));
677
1011
  print(io, { ok: true, workflow: wf, run });
678
1012
  return 0;
679
1013
  }
@@ -767,6 +1101,1515 @@ function statusEntry(engine, w) {
767
1101
  return { ...base, error: e.message };
768
1102
  }
769
1103
  }
1104
+ /**
1105
+ * `owenloop add <owner>/<repo>[@ref]` — the one network-touching CLI verb
1106
+ * (workflow-distribution Stage 1). Fetches a public GitHub repo's tarball,
1107
+ * validates its `workflows/**` defs with the same lint/check machinery
1108
+ * `owenloop lint`/`owenloop check` use, and — only if everything passes —
1109
+ * installs them under `<defsDir>/<installFolder(owner,repo)>/` and records
1110
+ * provenance in `.owenloop/installed.json`. A partial install is never left
1111
+ * behind: any refusal (parse/lint/validate/check failure) writes nothing, and
1112
+ * even a failure of the lockfile write after the directory swap rolls the
1113
+ * directory state back — the commit point is the durable lockfile write.
1114
+ *
1115
+ * Kept inside cli.ts (rather than add.ts) so it can reuse `Args`/`need`/
1116
+ * `last`/`CliError`/`parseJson`/`print`/`failureNote` without exporting them
1117
+ * from this module — the pure, unit-tested logic (spec parsing, lockfile
1118
+ * I/O, file install) lives in `src/add.ts`; this function is just the async
1119
+ * network + arg glue.
1120
+ */
1121
+ // Request deadlines for the two `add` fetches. A small JSON/text sha lookup
1122
+ // should be quick; the whole-repo tarball may be large on a slow link, so it
1123
+ // gets a much longer budget. Constants only — no env knob (a follow-up can add
1124
+ // one if ever needed).
1125
+ const ADD_SHA_TIMEOUT_MS = 30_000;
1126
+ const ADD_TARBALL_TIMEOUT_MS = 300_000;
1127
+ /**
1128
+ * Read a `Response` body while enforcing a byte `cap`, so a hostile server can
1129
+ * never make us allocate an oversized body. Rejects UP FRONT on a declared
1130
+ * oversize `Content-Length`; otherwise streams the body in chunks, counting the
1131
+ * bytes that actually land in memory, and cancels the stream the moment the
1132
+ * running total crosses the cap — the chunk buffer never holds more than `cap`
1133
+ * plus one chunk. `label` names the request in the error and is origin+path or
1134
+ * `owner/repo@sha` only — never a token. Counting post-decode bytes (what lands
1135
+ * in memory) is deliberate: the cap protects memory, not wire bytes.
1136
+ *
1137
+ * `res.body === null` (empty/no-body response) yields empty bytes, so callers
1138
+ * behave exactly as they did under `arrayBuffer()`. An absent, malformed, or
1139
+ * multi-valued `Content-Length` skips the header check — the counting path is
1140
+ * the real guard (GitHub codeload tarballs are typically chunked, no header). A
1141
+ * `TimeoutError`/`AbortError` from `read()` (the abort signal fired mid-body)
1142
+ * propagates untouched, so each call site's existing timeout mapping still
1143
+ * fires exactly as it did for `arrayBuffer()` rejections. `cancel()` may reject
1144
+ * on an already-errored stream — swallowed; the cap `CliError` is the story.
1145
+ */
1146
+ async function readBodyBounded(res, cap, label) {
1147
+ const declared = Number(res.headers.get('content-length'));
1148
+ if (Number.isFinite(declared) && declared > cap) {
1149
+ await res.body?.cancel().catch(() => { });
1150
+ throw new CliError(`response body for ${label} exceeds the ${cap}-byte cap (declared Content-Length ${declared})`);
1151
+ }
1152
+ if (res.body === null)
1153
+ return new Uint8Array(0);
1154
+ const reader = res.body.getReader();
1155
+ const chunks = [];
1156
+ let total = 0;
1157
+ for (;;) {
1158
+ const { done, value } = await reader.read();
1159
+ if (done)
1160
+ break;
1161
+ if (value === undefined)
1162
+ continue;
1163
+ total += value.byteLength;
1164
+ chunks.push(value);
1165
+ if (total > cap) {
1166
+ await reader.cancel().catch(() => { });
1167
+ throw new CliError(`response body for ${label} exceeds the ${cap}-byte cap`);
1168
+ }
1169
+ }
1170
+ const out = new Uint8Array(total);
1171
+ let offset = 0;
1172
+ for (const chunk of chunks) {
1173
+ out.set(chunk, offset);
1174
+ offset += chunk.byteLength;
1175
+ }
1176
+ return out;
1177
+ }
1178
+ /**
1179
+ * Cap on the `add` tarball download body, enforced DURING the stream by
1180
+ * `readBodyBounded` — defense in depth with `extractTarGz`'s own post-hoc
1181
+ * `maxCompressedBytes` check (kept intact). `OWENLOOP_TARBALL_MAX_BYTES`
1182
+ * overrides it (a test-only knob, validated `Number.isFinite && > 0`,
1183
+ * consistent with the project's other `OWENLOOP_*` knobs) so a mid-stream test
1184
+ * need not buffer the real 256 MiB cap in CI.
1185
+ */
1186
+ function tarballMaxBytes(io) {
1187
+ const override = Number(io.env.OWENLOOP_TARBALL_MAX_BYTES);
1188
+ return Number.isFinite(override) && override > 0 ? override : DEFAULT_TAR_LIMITS.maxCompressedBytes;
1189
+ }
1190
+ /**
1191
+ * `owenloop add <owner>/<repo>[@ref]` — fetch a repo's `workflows/**`, validate
1192
+ * it, and install it under `<defsDir>/<installFolder(owner,repo)>`.
1193
+ *
1194
+ * The network fetch/extract/path-filter runs FIRST, unlocked (a tarball can
1195
+ * take minutes and holding a lock that long would needlessly serialize
1196
+ * unrelated adds). Everything that touches project state then runs under the
1197
+ * per-project `.owenloop/add.lock`: crash-recovery pass → stale-staging cleanup
1198
+ * → lockfile read → ownership check → stage → strict validation → atomic commit
1199
+ * (backups retained) → journal write → lockfile write → journal advance →
1200
+ * finalize (backups discarded) → journal remove. Deciding ownership and reading
1201
+ * the lockfile INSIDE the lock is deliberate (TOCTOU discipline — see the
1202
+ * store-migration knowledge node). The install is staged on the destination
1203
+ * filesystem and swapped in with an atomic rename, but the displaced previous
1204
+ * install and any old-name dir are kept until the lockfile write succeeds — the
1205
+ * directory commit and the ledger write are one recoverable operation. Any
1206
+ * failure before the lockfile is durably written rolls the directory state back
1207
+ * and leaves the previous install and lockfile exactly as they were, with no
1208
+ * staging debris.
1209
+ *
1210
+ * A `.owenloop/add.journal` intent record closes the crash-recovery gap the
1211
+ * in-process rollback arms can't: it is written (phase `applying`) right before
1212
+ * the destructive `commitInstall`, advanced (phase `finalizing`) right after the
1213
+ * durable ledger write, and removed on clean completion. A process killed
1214
+ * mid-install leaves the journal behind; the NEXT add runs
1215
+ * `recoverInterruptedInstall` FIRST inside the lock — before the stale-staging
1216
+ * clear, since the backups a rollback needs live under the staging root — to
1217
+ * roll the interrupted install forward (past the commit point) or back (before
1218
+ * it) to a consistent (defs ⇔ ledger) state. The journal is attacker-
1219
+ * influenceable input, validated fail-closed with the same A1 discipline as the
1220
+ * lockfile; a bad/mismatched/contradictory journal REFUSES with no fs mutation
1221
+ * (and, via `preserveStagingRoot`, without the `finally` clearing the evidence).
1222
+ */
1223
+ async function dispatchAdd(io, args) {
1224
+ // Offline crash-recovery branch. This sits at the VERY TOP — before `need`/
1225
+ // `parseRepoSpec` and before either network fetch — so `--recover` is
1226
+ // structurally incapable of reaching the SHA/tarball fetches. A machine that
1227
+ // crashed mid-install and is now offline can finish or undo the interrupted
1228
+ // install with no network (recovery is purely local filesystem work).
1229
+ if (flag(args, 'recover'))
1230
+ return dispatchAddRecover(io, args);
1231
+ const spec = need(args, 1, 'owner/repo[@ref]');
1232
+ const { owner, repo, ref } = parseRepoSpec(spec);
1233
+ const source = `${owner}/${repo}`;
1234
+ const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
1235
+ const defsDir = defsOverride ?? join(io.cwd, 'workflows');
1236
+ const lockfilePath = join(io.cwd, '.owenloop', 'installed.json');
1237
+ const installLockPath = join(io.cwd, '.owenloop', 'add.lock');
1238
+ const journalPath = join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME);
1239
+ const fetchFn = io.fetch ?? globalThis.fetch;
1240
+ // 1. Resolve the ref to a pinned commit sha.
1241
+ let shaRes;
1242
+ try {
1243
+ shaRes = await fetchFn(githubShaUrl(owner, repo, ref), {
1244
+ headers: { Accept: 'application/vnd.github.sha', 'User-Agent': 'owenloop' },
1245
+ signal: AbortSignal.timeout(ADD_SHA_TIMEOUT_MS),
1246
+ });
1247
+ }
1248
+ catch (e) {
1249
+ const err = e;
1250
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
1251
+ throw new CliError(`timed out after ${ADD_SHA_TIMEOUT_MS / 1000}s resolving ${source}@${ref}`);
1252
+ }
1253
+ throw e;
1254
+ }
1255
+ if (!shaRes.ok) {
1256
+ const notFoundNote = shaRes.status === 404 ? ' (repo or ref not found)' : '';
1257
+ throw new CliError(`could not resolve ${source}@${ref}: GitHub returned ${shaRes.status}${notFoundNote}`);
1258
+ }
1259
+ const shaBytes = await readBodyBounded(shaRes, hubMaxResponseBytes(io), `sha resolution for ${source}@${ref}`);
1260
+ const shaBody = new TextDecoder().decode(shaBytes).trim();
1261
+ if (!/^[0-9a-f]{40}$/i.test(shaBody)) {
1262
+ throw new CliError(`unexpected response resolving ${source}@${ref}: expected a 40-char commit sha, got "${shaBody}"`);
1263
+ }
1264
+ const sha = shaBody;
1265
+ // 2. Fetch the tarball for that pinned sha. The timeout must cover the body
1266
+ // read too — undici ties the abort signal to the body stream — so the
1267
+ // fetch AND the bounded read live in the same try. readBodyBounded caps the
1268
+ // download DURING the stream (cancelling at the cap), so an oversized
1269
+ // tarball is never fully allocated; extractTarGz still re-checks the size
1270
+ // post-hoc (defense in depth).
1271
+ let bytes;
1272
+ try {
1273
+ const tarRes = await fetchFn(githubTarballUrl(owner, repo, sha), {
1274
+ headers: { 'User-Agent': 'owenloop' },
1275
+ signal: AbortSignal.timeout(ADD_TARBALL_TIMEOUT_MS),
1276
+ });
1277
+ if (!tarRes.ok) {
1278
+ throw new CliError(`could not fetch tarball for ${source}@${sha}: GitHub returned ${tarRes.status}`);
1279
+ }
1280
+ bytes = await readBodyBounded(tarRes, tarballMaxBytes(io), `tarball for ${source}@${sha}`);
1281
+ }
1282
+ catch (e) {
1283
+ const err = e;
1284
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
1285
+ throw new CliError(`timed out after ${ADD_TARBALL_TIMEOUT_MS / 1000}s downloading tarball for ${source}@${sha}`);
1286
+ }
1287
+ throw e;
1288
+ }
1289
+ // 3. Extract, strip the single leading '<owner>-<repo>-<sha>/' root-dir
1290
+ // component GitHub tarballs always have, and keep only workflows/**
1291
+ // (re-keyed relative to that dir).
1292
+ let rawFiles;
1293
+ try {
1294
+ rawFiles = extractTarGz(bytes);
1295
+ }
1296
+ catch (e) {
1297
+ throw new CliError(`could not extract tarball for ${source}@${sha}: ${e.message}`);
1298
+ }
1299
+ const files = new Map();
1300
+ const pathViolations = [];
1301
+ for (const [rawPath, data] of rawFiles) {
1302
+ const firstSlash = rawPath.indexOf('/');
1303
+ const rest = firstSlash >= 0 ? rawPath.slice(firstSlash + 1) : '';
1304
+ if (rest.startsWith('workflows/')) {
1305
+ const relPath = rest.slice('workflows/'.length);
1306
+ if (relPath) {
1307
+ // Reject any entry that would escape the staging/install dir BEFORE it
1308
+ // is ever joined and written (SEC-1). Collect every offender so the
1309
+ // refusal names them all.
1310
+ const violation = archivePathViolation(relPath);
1311
+ if (violation) {
1312
+ pathViolations.push(`${rawPath}: ${violation}`);
1313
+ continue;
1314
+ }
1315
+ files.set(relPath, data);
1316
+ }
1317
+ }
1318
+ }
1319
+ if (pathViolations.length > 0) {
1320
+ throw new CliError(`refusing to install ${source}@${sha} — ${pathViolations.length} unsafe archive path(s) found; nothing written:\n - ${pathViolations.join('\n - ')}`);
1321
+ }
1322
+ // Note: git (and so GitHub's tarball export) never tracks a truly empty
1323
+ // directory, so "no workflows/ dir at all" and "workflows/ dir exists but
1324
+ // is untracked-empty" are indistinguishable from the archive's contents —
1325
+ // both land here as files.size === 0. A `workflows/` dir that is tracked
1326
+ // but genuinely has zero yaml defs in it (e.g. holds only a .gitkeep)
1327
+ // takes the success/`installed: 0` path below instead, since it has at
1328
+ // least one file under the prefix.
1329
+ if (files.size === 0) {
1330
+ throw new CliError(`no workflows/ directory found in ${source}@${ref}`);
1331
+ }
1332
+ // 4. Everything that touches project state runs under the per-project install
1333
+ // lock: concurrent `add` runs serialize instead of interleaving. The lock
1334
+ // is acquired only now — AFTER the (potentially slow) network fetch — so a
1335
+ // tarball download never blocks an unrelated add.
1336
+ const folder = installFolder(owner, repo);
1337
+ const stagingRoot = join(defsDir, STAGING_DIRNAME);
1338
+ const stagingId = randId('stg');
1339
+ const stagingDir = join(stagingRoot, stagingId);
1340
+ // SEC-3, add's half: refuse a symlinked project `.owenloop` (the parent of
1341
+ // add.lock and installed.json — always cwd-derived in add, no override
1342
+ // exists) and a symlinked DEFAULT defs dir before any state write. Both must
1343
+ // precede acquireInstallLock: `.owenloop` is written by the lock acquire and
1344
+ // the ledger; defsDir is DELETED-through by the stale-staging rmSync below and
1345
+ // then written by staging/commit. An explicit --defs/OWENLOOP_DEFS is operator
1346
+ // intent, not repo content — deliberately installing through a symlink keeps
1347
+ // today's behavior, matching the --db/OWENLOOP_DB rule.
1348
+ mkdirRefusingSymlink(join(io.cwd, '.owenloop'));
1349
+ if (defsOverride === undefined)
1350
+ mkdirRefusingSymlink(defsDir);
1351
+ const lock = await acquireInstallLock(installLockPath);
1352
+ // Set true only on a rollback double-fault, where the ONLY copy of the
1353
+ // previous content ends up parked under the staging root — then the `finally`
1354
+ // must NOT delete it (the error message tells the user to recover it).
1355
+ let preserveStagingRoot = false;
1356
+ try {
1357
+ // Recover a crash-interrupted prior install FIRST — before the stale-staging
1358
+ // clear, since the backups/parked dirs a rollback needs live UNDER the
1359
+ // staging root, so clearing it first would destroy them. Any refusal (bad or
1360
+ // mismatched or contradictory journal) must preserve the staging root and the
1361
+ // journal as evidence: without this, the `finally` below would rmSync the
1362
+ // staging root and take the backups a later recovery needs with it.
1363
+ try {
1364
+ recoverInterruptedInstall({ defsDir, journalPath, lockfilePath });
1365
+ }
1366
+ catch (e) {
1367
+ preserveStagingRoot = true;
1368
+ throw e;
1369
+ }
1370
+ // The lock holder is the only legitimate writer under the staging root, so
1371
+ // anything already there is debris from a crashed/killed prior run — clear
1372
+ // it. Keeps "no staging debris" true even across a Ctrl-C.
1373
+ rmSync(stagingRoot, { recursive: true, force: true });
1374
+ // Read the lockfile and decide ownership INSIDE the lock (TOCTOU: a pre-lock
1375
+ // read could be stale by the time we act on it). A corrupt lockfile is a
1376
+ // hard error (readLockfile), never a silent reset.
1377
+ const lf = readLockfile(lockfilePath);
1378
+ const dest = join(defsDir, folder);
1379
+ const existing = lf.installed[source];
1380
+ // Use-site exact-match (Layer 2): the entry being installed may only record
1381
+ // the currently computed folder OR the exact legacy `<owner>-<repo>` name
1382
+ // (the only pre-hash scheme this tool ever wrote). `readLockfile` has
1383
+ // already refused any structurally unsafe `path`; this additionally refuses
1384
+ // a structurally-valid-but-WRONG segment (e.g. 'not-the-right-folder')
1385
+ // before any staging/commit mutation, so the later `existing.path !== folder`
1386
+ // migration branch is guaranteed to see only the exact legacy name.
1387
+ const legacyFolder = `${owner}-${repo}`;
1388
+ if (existing && existing.path !== folder && existing.path !== legacyFolder) {
1389
+ throw new CliError(`refusing to install ${source}: lockfile records install path '${existing.path}', ` +
1390
+ `which is neither the expected '${folder}' nor the legacy '${legacyFolder}' — fix ${lockfilePath} manually`);
1391
+ }
1392
+ if (existsSync(dest) && !(existing && existing.path === folder)) {
1393
+ throw new CliError(`refusing to install ${source}: destination '${folder}' already exists and is not owned by ${source} — ` +
1394
+ `remove it manually or fix ${lockfilePath}`);
1395
+ }
1396
+ // Stage the incoming files onto the DESTINATION filesystem (under defsDir),
1397
+ // so the commit is an atomic same-fs rename. Two-level layout keeps the
1398
+ // staged content invisible to loadDefs(defsDir).
1399
+ const written = stageFiles(stagingDir, files);
1400
+ // 5. Validate the STAGED tree — the exact bytes that will be renamed into
1401
+ // place, with no re-write after validation.
1402
+ const failures = [];
1403
+ const staged = loadDefsRaw(stagingDir, failures);
1404
+ const reasons = failures.map((f) => `${f.file}: ${f.error}`);
1405
+ for (const stagedDef of staged.values()) {
1406
+ const lintResult = lintDef(stagedDef);
1407
+ reasons.push(...lintResult.errors.map((e) => `${stagedDef.name}: ${e}`));
1408
+ const validationErrors = validateDef(stagedDef);
1409
+ reasons.push(...validationErrors.map((e) => `${stagedDef.name}: ${e}`));
1410
+ // Mirror the `check` command's exact "definite defect" predicate — but,
1411
+ // deliberately, WITH `assumeProvided: true`. Without it, a def with any
1412
+ // `seedOwed` input (the norm — see e.g. `proposal` in delivery.yaml)
1413
+ // deadlocks in the very first state, because the checker models "no
1414
+ // `provide` has happened yet" by default (see `seedArts` in
1415
+ // src/model.ts). `owenloop check <def>` behaves the same way absent
1416
+ // `--assume-provided`; verified every def under examples/workflows/
1417
+ // fails plain `check` for exactly this reason. Since `add` validates a
1418
+ // def that a real user will `provide` into after install (that's the
1419
+ // whole point of a seedOwed input), refusing every seedOwed def here
1420
+ // would make `add` unable to install almost any real workflow,
1421
+ // including this project's own examples — so this checks "is it
1422
+ // completable once its owed inputs are supplied," the same bar a
1423
+ // careful author would clear with `check --assume-provided` before
1424
+ // publishing.
1425
+ const report = modelCheck(stagedDef, { assumeProvided: true });
1426
+ const hasDefiniteDefect = report.invariantViolations.length > 0 ||
1427
+ (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
1428
+ if (hasDefiniteDefect) {
1429
+ reasons.push(`${stagedDef.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
1430
+ `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
1431
+ }
1432
+ }
1433
+ // Strict backstop: only if the aggregate pass found nothing, run the FULL
1434
+ // loadDefs on the staged tree. `loadDefsRaw` is best-effort — it swallows
1435
+ // include-expansion failures and cross-def `calls:` errors that strict
1436
+ // `loadDefs` (via finalizeDefs) throws on. Every later command loads the
1437
+ // installed dir with strict `loadDefs`, so this guarantees whatever we
1438
+ // commit cannot make a subsequent `loadDefs` of that dir throw.
1439
+ if (reasons.length === 0) {
1440
+ try {
1441
+ loadDefs(stagingDir);
1442
+ }
1443
+ catch (e) {
1444
+ if (e instanceof DefError) {
1445
+ reasons.push(`cross-definition validation failed: ${e.message}`);
1446
+ }
1447
+ else {
1448
+ throw e;
1449
+ }
1450
+ }
1451
+ }
1452
+ if (reasons.length > 0) {
1453
+ throw new CliError(`refusing to install ${source}@${sha} — ${reasons.length} problem(s) found; nothing written:\n - ${reasons.join('\n - ')}`);
1454
+ }
1455
+ // 6. Commit as one recoverable operation: atomically swap the validated
1456
+ // staging dir into place (backups RETAINED, not dropped), park any
1457
+ // old-naming dir this source used to occupy, write the lockfile, and only
1458
+ // then finalize (discard the retained backups). If the lockfile write
1459
+ // fails after the swap, roll the directory state back so the previous
1460
+ // install and lockfile are left exactly as they were.
1461
+ //
1462
+ // Write the crash-recovery journal (phase `applying`) BEFORE the first
1463
+ // destructive step. `hadDest` is captured here, under the lock, right before
1464
+ // commitInstall reads the same fact — so recovery knows whether a backup dir
1465
+ // will exist. A migration off the old `<owner>-<repo>` name records that
1466
+ // path so recovery can restore the parked old-name dir. If the process is
1467
+ // killed anywhere past this point, the next add's recovery pass uses this
1468
+ // record to roll forward or back.
1469
+ const migratingOldName = existing !== undefined && existing.path !== folder;
1470
+ const journalBase = {
1471
+ version: 1,
1472
+ phase: 'applying',
1473
+ source,
1474
+ sha,
1475
+ folder,
1476
+ stagingId,
1477
+ hadDest: existsSync(dest),
1478
+ ...(migratingOldName ? { oldNamePath: existing.path } : {}),
1479
+ defsDir: resolve(defsDir),
1480
+ ref,
1481
+ startedAt: nowMs(),
1482
+ };
1483
+ writeAddJournal(journalPath, journalBase);
1484
+ let handle;
1485
+ try {
1486
+ handle = commitInstall(defsDir, folder, stagingDir);
1487
+ }
1488
+ catch (e) {
1489
+ // commitInstall's own swap-then-rollback double-fault left the only copy
1490
+ // of previous content under the staging root — keep it (see the `finally`).
1491
+ if (e instanceof RollbackFailedError)
1492
+ preserveStagingRoot = true;
1493
+ throw e;
1494
+ }
1495
+ if (existing && existing.path !== folder) {
1496
+ // Migrating off the old `<owner>-<repo>` scheme: park (not delete) the old
1497
+ // dir so a failure below can restore it. Finalized away on success. This
1498
+ // park now sits INSIDE the recoverable region — a park failure must roll
1499
+ // the committed swap back too, exactly like the lockfile-write failure
1500
+ // below (a bare park could otherwise strand the swap and leave the next
1501
+ // `add` refusing on an ownership mismatch).
1502
+ try {
1503
+ parkOldNameDir(handle, defsDir, existing.path);
1504
+ }
1505
+ catch (e) {
1506
+ try {
1507
+ rollbackInstallCommit(handle);
1508
+ }
1509
+ catch (rollbackErr) {
1510
+ // Double fault: parking the old dir failed AND rolling the committed
1511
+ // swap back failed. Nothing of value sits under the staging root here —
1512
+ // the staging dir was consumed by the swap, and this migration branch
1513
+ // never has a backup (`dest` cannot pre-exist; see the ownership refusal
1514
+ // above). The old-name dir was never moved (the park is a single atomic
1515
+ // rename recorded only on success) so it stays intact at its original
1516
+ // path, and the stranded item is the NEW content still at `dest`. LEAVE
1517
+ // the journal (phase `applying`) so the next add's recovery rolls the
1518
+ // swap back (case (c): discards `dest`) before anything clears the
1519
+ // staging root, mirroring the lockfile-write double fault below.
1520
+ preserveStagingRoot = true;
1521
+ throw new CliError(`could not migrate ${source} off old-name directory '${existing.path}' (${e.message}) ` +
1522
+ `and rolling the install back failed too (${rollbackErr.message}); ` +
1523
+ `the old-name directory was never moved and is intact at ${join(defsDir, existing.path)}, ` +
1524
+ `and the newly installed content is stranded at ${dest} — ` +
1525
+ `the next owenloop add will recover automatically (discarding the stranded content and leaving the previous install in place)`);
1526
+ }
1527
+ // Directory state restored in-process — nothing left to recover, so drop
1528
+ // the journal before surfacing the (single-fault) failure.
1529
+ removeAddJournal(journalPath);
1530
+ throw new CliError(`could not migrate ${source} off old-name directory '${existing.path}': ${e.message} — ` +
1531
+ `install rolled back, previous state restored`);
1532
+ }
1533
+ }
1534
+ const entry = { source, ref, sha, installedAt: nowMs(), path: folder, files: written };
1535
+ lf.installed[source] = entry;
1536
+ try {
1537
+ writeLockfile(lockfilePath, lf);
1538
+ }
1539
+ catch (e) {
1540
+ try {
1541
+ rollbackInstallCommit(handle);
1542
+ }
1543
+ catch (rollbackErr) {
1544
+ // Double fault: the ledger write failed AND restoring the directory
1545
+ // failed. The previous content is now parked under the staging root —
1546
+ // preserve it past the `finally` and LEAVE the journal (phase
1547
+ // `applying`, ledger not committed) so the next add's recovery restores
1548
+ // the previous state before anything clears the staging root.
1549
+ preserveStagingRoot = true;
1550
+ throw new CliError(`could not record install of ${source} in ${lockfilePath} (${e.message}) ` +
1551
+ `and rolling the install back failed too (${rollbackErr.message}); ` +
1552
+ `previous content preserved under ${stagingRoot} — recover it before running add again ` +
1553
+ `(the next owenloop add will attempt recovery automatically; leaving it, that dir is cleared as debris)`);
1554
+ }
1555
+ // Directory state restored in-process — drop the journal before surfacing
1556
+ // the (single-fault) failure.
1557
+ removeAddJournal(journalPath);
1558
+ throw new CliError(`could not record install of ${source} in ${lockfilePath}: ${e.message} — ` +
1559
+ `install rolled back, previous state restored`);
1560
+ }
1561
+ // The ledger write is the durable commit point: past here a crash rolls
1562
+ // FORWARD. Record that in the journal (phase `finalizing`) so recovery
1563
+ // finishes the install rather than tearing it down, then finalize and drop
1564
+ // the journal now that there is nothing left to recover.
1565
+ writeAddJournal(journalPath, { ...journalBase, phase: 'finalizing' });
1566
+ finalizeInstallCommit(handle);
1567
+ removeAddJournal(journalPath);
1568
+ // 7. Report.
1569
+ print(io, {
1570
+ ok: true,
1571
+ source,
1572
+ ref,
1573
+ sha,
1574
+ path: folder,
1575
+ installed: written.length,
1576
+ defs: [...staged.values()].map((d) => d.name).sort(),
1577
+ hint: `installed workflows are now discoverable by default — run e.g. \`owenloop create ${[...staged.values()].map((d) => d.name).sort()[0] ?? '<def-name>'}\` with no --defs flag; for an explicit --defs, point it at ${folder}`,
1578
+ });
1579
+ return 0;
1580
+ }
1581
+ finally {
1582
+ // On success the staging dir was renamed away and its retained backups
1583
+ // finalized; on failure this clears whatever staging debris is left. The one
1584
+ // exception is a rollback double-fault (`preserveStagingRoot`), where the
1585
+ // only surviving copy of the previous content is parked here — leave it for
1586
+ // the user to recover (the next add clears it as debris). Then release the lock.
1587
+ if (!preserveStagingRoot)
1588
+ rmSync(stagingRoot, { recursive: true, force: true });
1589
+ releaseInstallLock(lock);
1590
+ }
1591
+ }
1592
+ /**
1593
+ * `owenloop add --recover`: an OFFLINE, network-free entry point to the same
1594
+ * `recoverInterruptedInstall` the normal add path runs inline. `dispatchAdd`
1595
+ * branches here at its very top, before `parseRepoSpec` and before the SHA and
1596
+ * tarball fetches — so this path can never touch the network. The normal add
1597
+ * path already runs recovery inline (belt-and-suspenders); this exists only so a
1598
+ * machine that crashed mid-install and is now offline can finish/undo the
1599
+ * interrupted install without waiting for the network to return.
1600
+ *
1601
+ * The lock scope here is recovery-ONLY: acquire `.owenloop/add.lock`, run
1602
+ * recovery, release. There is no fetch to keep outside the lock (the reason the
1603
+ * normal path acquires the lock only after the download), so the whole
1604
+ * short local operation runs under it. No `--db`/store open — recovery never
1605
+ * reads the store. Refusals (bad/mismatched/contradictory journal) throw and
1606
+ * propagate to `mainAsync`'s catch as `error: ...`, exit 1, mutating nothing —
1607
+ * and unlike the inline path there is no `preserveStagingRoot` dance, because
1608
+ * this path never rmSyncs the staging root itself, so a refusal naturally leaves
1609
+ * the journal, staging root, and dest untouched as evidence.
1610
+ */
1611
+ async function dispatchAddRecover(io, args) {
1612
+ // With --recover the owner/repo positional is optional; a supplied spec is
1613
+ // ambiguous ("recover then install"?), so refuse rather than guess — the
1614
+ // normal add path runs recovery inline anyway, so "recover then install" is
1615
+ // just `owenloop add owner/repo`.
1616
+ if (args.positionals[1] !== undefined) {
1617
+ throw new CliError('--recover takes no repository argument — run recovery alone, then re-run add');
1618
+ }
1619
+ // Resolve paths EXACTLY as dispatchAdd does — same defsDir/lock/journal
1620
+ // derivation — so recovery acts on the same tree a real add would. No fetch
1621
+ // reference, no store open.
1622
+ const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
1623
+ const defsDir = defsOverride ?? join(io.cwd, 'workflows');
1624
+ const lockfilePath = join(io.cwd, '.owenloop', 'installed.json');
1625
+ const installLockPath = join(io.cwd, '.owenloop', 'add.lock');
1626
+ const journalPath = join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME);
1627
+ // Mirror the SEC-3 symlink guards from the normal path (same order, same
1628
+ // rationale): `.owenloop` is written by the lock acquire; the default defsDir
1629
+ // is mutated-through by recovery. An explicit --defs/OWENLOOP_DEFS is operator
1630
+ // intent, not repo content, so it is not symlink-guarded (matching dispatchAdd).
1631
+ mkdirRefusingSymlink(join(io.cwd, '.owenloop'));
1632
+ if (defsOverride === undefined)
1633
+ mkdirRefusingSymlink(defsDir);
1634
+ const lock = await acquireInstallLock(installLockPath);
1635
+ let outcome;
1636
+ try {
1637
+ outcome = recoverInterruptedInstall({ defsDir, journalPath, lockfilePath });
1638
+ }
1639
+ finally {
1640
+ releaseInstallLock(lock);
1641
+ }
1642
+ switch (outcome) {
1643
+ case 'no-journal':
1644
+ print(io, { ok: true, recovered: false, message: 'nothing to recover — no interrupted install found' });
1645
+ return 0;
1646
+ case 'rolled-forward':
1647
+ print(io, {
1648
+ ok: true,
1649
+ recovered: true,
1650
+ outcome: 'rolled-forward',
1651
+ message: 'interrupted install completed (rolled forward)',
1652
+ });
1653
+ return 0;
1654
+ case 'rolled-back':
1655
+ print(io, {
1656
+ ok: true,
1657
+ recovered: true,
1658
+ outcome: 'rolled-back',
1659
+ message: 'interrupted install undone — previous state restored (or already consistent)',
1660
+ });
1661
+ return 0;
1662
+ }
1663
+ }
1664
+ // ---- hub onboarding: login / logout / connect / push -------------------------
1665
+ /**
1666
+ * Resolve the target hub origin: `--hub` > `OWENLOOP_HUB` env > the default
1667
+ * production hub. Normalized (scheme required, trailing slash/path stripped) so
1668
+ * it can serve as a stable credential-store key and project binding value.
1669
+ */
1670
+ const DEFAULT_HUB = 'https://api.owenloop.com';
1671
+ function resolveHub(io, args) {
1672
+ const raw = last(args, 'hub') ?? io.env.OWENLOOP_HUB ?? DEFAULT_HUB;
1673
+ try {
1674
+ return normalizeOrigin(raw);
1675
+ }
1676
+ catch (e) {
1677
+ throw new CliError(e.message);
1678
+ }
1679
+ }
1680
+ /**
1681
+ * Parse `--as <human | agent | agent:NAME>` into a `CredentialSlotSelector`.
1682
+ * Absent `--as` means the **human** slot — the everyday interactive case.
1683
+ * A malformed value (or an invalid account name, validated by `credentialSlot`)
1684
+ * is a usage error, never a silent coercion to some other slot.
1685
+ */
1686
+ function resolveSlot(args) {
1687
+ const raw = last(args, 'as');
1688
+ const sel = parseSlotArg(raw);
1689
+ // Validate eagerly so a bad account name fails before any network or store
1690
+ // access, with the same wording every later call site would produce.
1691
+ try {
1692
+ credentialSlot(sel);
1693
+ }
1694
+ catch (e) {
1695
+ throw new CliError(`--as: ${e.message}`);
1696
+ }
1697
+ return sel;
1698
+ }
1699
+ function parseSlotArg(raw) {
1700
+ if (raw === undefined)
1701
+ return { principal: 'human' };
1702
+ if (raw === 'human')
1703
+ return { principal: 'human' };
1704
+ if (raw === 'agent')
1705
+ return { principal: 'agent' };
1706
+ if (raw.startsWith('agent:'))
1707
+ return { principal: 'agent', account: raw.slice('agent:'.length) };
1708
+ throw new CliError(`--as: unrecognized slot '${raw}' — expected 'human', 'agent', or 'agent:<account>'`);
1709
+ }
1710
+ /**
1711
+ * The "nothing stored here" message for a read that missed. It names the SLOT,
1712
+ * not just the origin — a credential may well exist for this hub under another
1713
+ * principal, and the fix is `--as`, not another `login`.
1714
+ */
1715
+ function emptySlotMessage(origin, slot) {
1716
+ const name = credentialSlot(slot);
1717
+ return `no stored credential for ${origin} in slot \`${name}\` — run \`owenloop login\` (or pass --as agent:<name>)`;
1718
+ }
1719
+ /**
1720
+ * Read the stored credential for `origin` in `slot`. Thin wrapper over the
1721
+ * shared `readStoredCredential` in `hub.ts` (the same implementation the public
1722
+ * package export uses), threading the CLI's injected `env`/`keychain`. Callers
1723
+ * pass a pre-normalized origin (`resolveHub` output); the wrapper's
1724
+ * normalization is idempotent, so CLI behavior is unchanged. REL-6 no-fallback
1725
+ * and corrupt-entry-as-absent semantics live in `hub.ts`.
1726
+ */
1727
+ function readCredential(io, origin, slot) {
1728
+ return readStoredCredential(origin, { ...slot, env: io.env, keychain: io.keychain });
1729
+ }
1730
+ /**
1731
+ * Store a credential for `origin` in `slot`, in the chosen backend ONLY;
1732
+ * returns which one. A failed keychain write is a hard error (REL-6), never a
1733
+ * silent fall-through to the file — the escape hatch is to choose the file
1734
+ * backend up front with `OWENLOOP_NO_KEYCHAIN=1`. Backend selection is the
1735
+ * shared `credentialBackend` from `hub.ts`, so read and write agree on one
1736
+ * choice. That shared selection now has a third variant: when an external
1737
+ * credential command is configured this throws, because the command — not the
1738
+ * local store — is what reads will consult.
1739
+ *
1740
+ * The file backend MERGES into the origin's slot map: writing `agent:ci` must
1741
+ * leave a `human` credential for the same origin intact.
1742
+ */
1743
+ function storeCredential(io, origin, slot, cred) {
1744
+ const account = credentialSlot(slot);
1745
+ const backend = credentialBackend(io.env, io.keychain);
1746
+ if (backend.kind === 'external') {
1747
+ // Writing to a store that reads will never consult is exactly the
1748
+ // "half-working setup hands back a stale key" failure the external command
1749
+ // exists to prevent, so refuse loudly instead.
1750
+ throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
1751
+ 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
1752
+ }
1753
+ if (backend.kind === 'keychain') {
1754
+ try {
1755
+ backend.kc.set(keychainServiceFor(origin), account, JSON.stringify(cred));
1756
+ }
1757
+ catch (e) {
1758
+ throw new CliError(`could not write the credential to the OS keychain: ${e.message}. ` +
1759
+ 'Fix the keychain, or set OWENLOOP_NO_KEYCHAIN=1 to use the 0600 file store');
1760
+ }
1761
+ return 'keychain';
1762
+ }
1763
+ const path = credentialFilePath(io.env);
1764
+ const file = readCredentialFile(path);
1765
+ file.hubs[origin] = { ...file.hubs[origin], [account]: cred };
1766
+ writeCredentialFile(path, file);
1767
+ return 'file';
1768
+ }
1769
+ /**
1770
+ * Delete the stored credential for `(origin, slot)` from BOTH backends.
1771
+ * Deliberately not routed through `credentialBackend`: logout is a defensive
1772
+ * dual-clear (the proposal explicitly blesses it), so a live refresh token can
1773
+ * never be stranded in the store that wasn't the currently-chosen one. Returns
1774
+ * whether anything was removed.
1775
+ *
1776
+ * Only the NAMED slot is removed. A blanket "clear every slot for this origin"
1777
+ * is not implementable — the keychain cannot enumerate its accounts — and
1778
+ * faking it on the file backend alone would be a half-truth, so the slot is
1779
+ * always explicit (defaulting to `human`).
1780
+ */
1781
+ function deleteCredential(io, origin, slot) {
1782
+ const account = credentialSlot(slot);
1783
+ let removed = false;
1784
+ const kc = resolveKeychain(io.env, io.keychain);
1785
+ const service = keychainServiceFor(origin);
1786
+ if (kc && kc.get(service, account) !== null) {
1787
+ kc.delete(service, account);
1788
+ removed = true;
1789
+ }
1790
+ const path = credentialFilePath(io.env);
1791
+ const file = readCredentialFile(path);
1792
+ const slots = file.hubs[origin];
1793
+ if (slots !== undefined && slots[account] !== undefined) {
1794
+ delete slots[account];
1795
+ // Drop the origin key once its last slot is gone, so the file never keeps
1796
+ // an empty husk that a later read would have to special-case.
1797
+ if (Object.keys(slots).length === 0)
1798
+ delete file.hubs[origin];
1799
+ writeCredentialFile(path, file);
1800
+ removed = true;
1801
+ }
1802
+ return removed;
1803
+ }
1804
+ /** The Bearer value for an authenticated request. Never logged. */
1805
+ function authHeader(cred) {
1806
+ return `Bearer ${cred.accessToken}`;
1807
+ }
1808
+ // Request deadline for EVERY hub/auth call — OAuth discovery, DCR, code
1809
+ // exchange, token refresh, whoami, workflow list, and push (REL-7). These are
1810
+ // all small JSON round-trips, so one budget fits them all;
1811
+ // OWENLOOP_HUB_TIMEOUT_MS overrides it (a test knob, consistent with
1812
+ // OWENLOOP_LOGIN_TIMEOUT_MS and the project's other OWENLOOP_* test-only knobs).
1813
+ const HUB_TIMEOUT_MS = 30_000;
1814
+ function hubTimeoutMs(io) {
1815
+ const override = Number(io.env.OWENLOOP_HUB_TIMEOUT_MS);
1816
+ return Number.isFinite(override) && override > 0 ? override : HUB_TIMEOUT_MS;
1817
+ }
1818
+ // Cap on any hub/auth JSON RESPONSE body (OAuth discovery, DCR, code exchange,
1819
+ // token refresh, whoami, the workflow list, create_workflow). Hub responses are
1820
+ // small round-trips — the largest realistic body is a workflows summary list,
1821
+ // far below 8 MiB. This is a RESPONSE cap; the hub's 32MB figure (the 413 path)
1822
+ // is a REQUEST cap and responses never echo YAML. OWENLOOP_HUB_MAX_RESPONSE_BYTES
1823
+ // overrides it (a test-only knob, consistent with OWENLOOP_HUB_TIMEOUT_MS).
1824
+ const HUB_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
1825
+ function hubMaxResponseBytes(io) {
1826
+ const override = Number(io.env.OWENLOOP_HUB_MAX_RESPONSE_BYTES);
1827
+ return Number.isFinite(override) && override > 0 ? override : HUB_MAX_RESPONSE_BYTES;
1828
+ }
1829
+ /**
1830
+ * `fetch` wrapper putting a deadline on every hub/auth call (REL-7). The abort
1831
+ * signal is threaded into `fetch` AND the body is read (via `readBodyBounded`,
1832
+ * which caps the response size — see HUB_MAX_RESPONSE_BYTES) inside the same
1833
+ * try, so the deadline covers a stalled BODY read too — the exact undici
1834
+ * behavior the two `add` fetches document (`AbortSignal.timeout` ties the
1835
+ * signal to the body stream). The returned `Response` re-exposes the read
1836
+ * body, so every call site's `res.json()` / `res.status` /
1837
+ * `res.headers.get(...)` usage is byte-for-byte unchanged. A
1838
+ * `TimeoutError`/`AbortError` becomes a clear `CliError` (naming the request,
1839
+ * which is origin+path only — never a token); anything else is rethrown
1840
+ * untouched.
1841
+ *
1842
+ * `redirect: 'error'` is forced on every call — after the `...init` spread, so
1843
+ * no caller can override it — to close the redirect gap `resolveEndpoint`
1844
+ * (SEC-4) cannot see: same-origin validation covers only the INITIAL URL, but a
1845
+ * validated endpoint answering 307/308 would re-send the POST body (refresh
1846
+ * token, PKCE verifier, auth code, workflow YAML) to a foreign origin — undici
1847
+ * strips the Authorization header on a cross-origin redirect but RESENDS the
1848
+ * body. The hub protocol has no redirects, so any 3xx is a hard, loud failure
1849
+ * mapped to a `CliError` (again naming origin+path only, never a token).
1850
+ */
1851
+ async function hubFetch(io, url, init) {
1852
+ const fetchFn = io.fetch ?? globalThis.fetch;
1853
+ const ms = hubTimeoutMs(io);
1854
+ const method = (init?.method ?? 'GET').toUpperCase();
1855
+ try {
1856
+ const res = await fetchFn(url, { ...init, signal: AbortSignal.timeout(ms), redirect: 'error' });
1857
+ // 204/304 carry no body — reading one would be a spec violation.
1858
+ if (res.status === 204 || res.status === 304) {
1859
+ return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers });
1860
+ }
1861
+ const body = await readBodyBounded(res, hubMaxResponseBytes(io), `${method} ${url}`);
1862
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });
1863
+ }
1864
+ catch (e) {
1865
+ const err = e;
1866
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
1867
+ throw new CliError(`hub did not respond within ${ms / 1000}s (${method} ${url})`);
1868
+ }
1869
+ // `redirect: 'error'` makes undici reject a 3xx with a TypeError whose
1870
+ // cause message is 'unexpected redirect' (verified on Node 22.22.3 and 26).
1871
+ // Substring-match for slack against undici wording drift — if it ever stops
1872
+ // matching, the raw TypeError still surfaces (fail-closed, just less pretty).
1873
+ const cause = String(err.cause?.message ?? '');
1874
+ if (err.name === 'TypeError' && cause.includes('unexpected redirect')) {
1875
+ throw new CliError(`hub responded with a redirect — refusing to follow it (${method} ${url}); redirects are not part of the hub protocol`);
1876
+ }
1877
+ throw e;
1878
+ }
1879
+ }
1880
+ /**
1881
+ * Ensure an `oauth` credential's access token is fresh: if it expires within
1882
+ * 60s, refresh once (grant_type=refresh_token) and persist the new token. No-op
1883
+ * for `agent`/`oauth-pasted` credentials (they don't refresh). Returns the
1884
+ * possibly-updated credential.
1885
+ *
1886
+ * `slot` is the slot the credential was READ from — a refreshed token must be
1887
+ * written back to that same slot, never to a default one.
1888
+ */
1889
+ async function ensureFreshOAuth(io, origin, slot, cred, persist = true) {
1890
+ if (cred.kind !== 'oauth')
1891
+ return cred;
1892
+ if (cred.expiresAt - nowMs() > 60_000)
1893
+ return cred;
1894
+ return refreshOAuth(io, origin, slot, cred, persist);
1895
+ }
1896
+ /**
1897
+ * `persist` defaults to true — the normal case is refreshing an ALREADY
1898
+ * stored, trusted credential (push/connect), where persisting immediately
1899
+ * matters because refresh tokens can be single-use/rotating: losing the new
1900
+ * one to a later crash would strand the user. `verifyCredential`'s login-time
1901
+ * use passes `persist: false` — a not-yet-stored credential must never be
1902
+ * written to disk/keychain before it is proven to work end to end (a 401 on
1903
+ * the retry after this refresh still fails the overall login), matching the
1904
+ * "never store an unverified token" rule enforced at every login call site.
1905
+ */
1906
+ async function refreshOAuth(io, origin, slot, cred, persist = true) {
1907
+ const tokenEndpoint = await discoverTokenEndpoint(io, origin);
1908
+ const body = new URLSearchParams({
1909
+ grant_type: 'refresh_token',
1910
+ refresh_token: cred.refreshToken,
1911
+ client_id: cred.clientId,
1912
+ });
1913
+ const res = await hubFetch(io, tokenEndpoint, {
1914
+ method: 'POST',
1915
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1916
+ body: body.toString(),
1917
+ });
1918
+ if (!res.ok) {
1919
+ throw new CliError('credential expired and refresh failed — run `owenloop login`');
1920
+ }
1921
+ const json = (await res.json());
1922
+ if (typeof json.access_token !== 'string') {
1923
+ throw new CliError('credential expired and refresh returned no access token — run `owenloop login`');
1924
+ }
1925
+ const expiresIn = typeof json.expires_in === 'number' ? json.expires_in : 3600;
1926
+ const refreshed = {
1927
+ kind: 'oauth',
1928
+ accessToken: json.access_token,
1929
+ refreshToken: typeof json.refresh_token === 'string' ? json.refresh_token : cred.refreshToken,
1930
+ expiresAt: nowMs() + expiresIn * 1000,
1931
+ clientId: cred.clientId,
1932
+ };
1933
+ // When an external command supplies credentials it owns the credential's
1934
+ // whole lifecycle; owenloop must not write a refreshed token into a store it
1935
+ // will never read (and `storeCredential` refuses in that mode anyway).
1936
+ if (persist && externalCredentialCommand(io.env) === undefined) {
1937
+ storeCredential(io, origin, slot, refreshed);
1938
+ }
1939
+ return refreshed;
1940
+ }
1941
+ async function discoverMetadata(io, origin) {
1942
+ const res = await hubFetch(io, resolveEndpoint(origin, '/.well-known/oauth-authorization-server'), {
1943
+ headers: { Accept: 'application/json' },
1944
+ });
1945
+ if (!res.ok) {
1946
+ throw new CliError(`could not read OAuth metadata from ${origin} (HTTP ${res.status})`);
1947
+ }
1948
+ return (await res.json());
1949
+ }
1950
+ async function discoverTokenEndpoint(io, origin) {
1951
+ const meta = await discoverMetadata(io, origin);
1952
+ if (!meta.token_endpoint)
1953
+ throw new CliError(`hub ${origin} advertises no token_endpoint`);
1954
+ return resolveEndpoint(origin, meta.token_endpoint);
1955
+ }
1956
+ /**
1957
+ * GET `path` on `origin` with a bearer credential, refreshing an expiring
1958
+ * oauth token first and retrying exactly once after a 401→refresh for oauth.
1959
+ * Returns the raw response plus the credential actually used (possibly
1960
+ * refreshed), so the caller can both persist it and apply its own hard-error
1961
+ * semantics on the final status (a 401 after the retry, a non-2xx, etc. —
1962
+ * left to the caller since the wording differs slightly by context).
1963
+ */
1964
+ async function authedGet(io, origin, slot, cred, path, persist = true) {
1965
+ let current = await ensureFreshOAuth(io, origin, slot, cred, persist);
1966
+ let res = await hubFetch(io, resolveEndpoint(origin, path), {
1967
+ headers: { Authorization: authHeader(current), Accept: 'application/json' },
1968
+ });
1969
+ if (res.status === 401 && current.kind === 'oauth') {
1970
+ current = await refreshOAuth(io, origin, slot, current, persist);
1971
+ res = await hubFetch(io, resolveEndpoint(origin, path), {
1972
+ headers: { Authorization: authHeader(current), Accept: 'application/json' },
1973
+ });
1974
+ }
1975
+ return { res, cred: current };
1976
+ }
1977
+ /**
1978
+ * A 401 on an agent token is a hard "revoked/invalid" error; a 401 on any
1979
+ * other credential kind (after `authedGet`'s one refresh-and-retry) is a hard
1980
+ * "credential rejected" error; any other non-2xx is a generic hub-rejected
1981
+ * error naming the status. Shared by `verifyCredential` and `dispatchPush`'s
1982
+ * server-list fetch so both surfaces the same wording for the same failure.
1983
+ */
1984
+ function assertAuthOk(res, cred, origin) {
1985
+ if (res.status === 401) {
1986
+ if (cred.kind === 'agent') {
1987
+ throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
1988
+ }
1989
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
1990
+ }
1991
+ if (!res.ok) {
1992
+ throw new CliError(`hub ${origin} rejected the credential (HTTP ${res.status})`);
1993
+ }
1994
+ }
1995
+ /**
1996
+ * Verify a credential works against the hub's `GET /api/whoami` (any 2xx =
1997
+ * authenticated) and return the identity it names. Whoami carries no RBAC
1998
+ * verb, so this proves *authentication*, not any particular scope (e.g.
1999
+ * `list`) — a token lacking a scope `push` later needs still fails there,
2000
+ * with the hub's own 401/403, which is acceptable and honest. Refreshes an
2001
+ * expiring oauth token first, and retries exactly once after a 401→refresh
2002
+ * for oauth; a 401 on an agent token is a hard "revoked/invalid" error.
2003
+ * Returns the credential actually used (possibly refreshed), so the caller
2004
+ * can persist it, alongside the parsed identity.
2005
+ *
2006
+ * `persist` (default true) controls whether an in-flight refresh writes its
2007
+ * new token to storage immediately (see `refreshOAuth`'s doc comment) —
2008
+ * `dispatchLogin`'s OAuth branch passes `false` because the credential being
2009
+ * verified here hasn't been stored yet at all; a refresh mid-verify must not
2010
+ * sneak a not-yet-proven credential onto disk ahead of the pass/fail verdict.
2011
+ */
2012
+ async function verifyCredential(io, origin, slot, cred, persist = true) {
2013
+ const { res, cred: current } = await authedGet(io, origin, slot, cred, '/api/whoami', persist);
2014
+ assertAuthOk(res, current, origin);
2015
+ const body = await res.json();
2016
+ return { cred: current, identity: asWhoami(body) };
2017
+ }
2018
+ /**
2019
+ * `owenloop login` — authenticate the CLI against a hub. Primary flow is a
2020
+ * loopback OAuth auth-code + PKCE(S256) exchange; `--with-token` reads an
2021
+ * `olp_`/`mcpat_` token from stdin instead (never argv). Either way the
2022
+ * credential is verified before it is stored, and stored in the OS keychain or
2023
+ * a 0600 file — never plaintext in the repo or `.env`.
2024
+ *
2025
+ * The SLOT the credential lands in follows the credential KIND, with `--as`
2026
+ * naming the agent account: a human credential (loopback `oauth`, or a pasted
2027
+ * `mcpat_`) writes `human`; a pasted `olp_` agent token writes
2028
+ * `agent:<account>` (`default` unless `--as agent:NAME`). A `--as` that
2029
+ * contradicts the credential kind is a usage error, not a silent coercion —
2030
+ * that is what keeps the agent slot holding agent keys.
2031
+ *
2032
+ * Refused outright while an external credential command is configured: that
2033
+ * command, not the local store, is what every read consults, so there is nothing
2034
+ * for `login` to usefully write. The check is here — before the "did a
2035
+ * credential already exist?" probe, which would otherwise RUN the command and
2036
+ * report its failure instead of this far more actionable reason — with
2037
+ * `storeCredential`'s own throw kept as the invariant backstop for any other
2038
+ * write path.
2039
+ */
2040
+ async function dispatchLogin(io, args) {
2041
+ const origin = resolveHub(io, args);
2042
+ const asked = resolveSlot(args);
2043
+ const asGiven = last(args, 'as') !== undefined;
2044
+ if (externalCredentialCommand(io.env) !== undefined) {
2045
+ throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
2046
+ 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
2047
+ }
2048
+ if (flag(args, 'with-token')) {
2049
+ const readStdin = io.readStdin ?? defaultReadStdin;
2050
+ const token = (await readStdin()).trim();
2051
+ if (token === '')
2052
+ throw new CliError('no token on stdin (pipe the token in, e.g. `pbpaste | owenloop login --with-token`)');
2053
+ let cred;
2054
+ if (token.startsWith('olp_'))
2055
+ cred = { kind: 'agent', accessToken: token };
2056
+ else if (token.startsWith('mcpat_'))
2057
+ cred = { kind: 'oauth-pasted', accessToken: token };
2058
+ else
2059
+ throw new CliError('unrecognized token — expected an `olp_` agent token or an `mcpat_` access token');
2060
+ // Contradictions are usage errors, refused BEFORE any network call so
2061
+ // nothing is verified or stored under a slot the token does not belong in.
2062
+ if (cred.kind === 'agent' && asGiven && asked.principal === 'human') {
2063
+ throw new CliError('an `olp_` agent token cannot be stored in the `human` slot — drop `--as human`, or pass `--as agent[:<account>]`');
2064
+ }
2065
+ if (cred.kind !== 'agent' && asked.principal === 'agent') {
2066
+ throw new CliError(`a ${cred.kind} credential is a human credential and cannot be stored in the \`${credentialSlot(asked)}\` slot — drop \`--as\`, or paste an \`olp_\` agent token`);
2067
+ }
2068
+ const slot = cred.kind === 'agent' ? { principal: 'agent', ...(asked.principal === 'agent' && asked.account !== undefined ? { account: asked.account } : {}) } : { principal: 'human' };
2069
+ const existed = readCredential(io, origin, slot) !== null;
2070
+ const { identity } = await verifyCredential(io, origin, slot, cred); // never store an unverified token
2071
+ const storage = storeCredential(io, origin, slot, cred);
2072
+ print(io, {
2073
+ ok: true,
2074
+ hub: origin,
2075
+ kind: cred.kind,
2076
+ slot: credentialSlot(slot),
2077
+ storage,
2078
+ replaced: existed,
2079
+ org: identity.orgName,
2080
+ orgId: identity.orgId,
2081
+ identity: identity.actor,
2082
+ ...(identity.email ? { email: identity.email } : {}),
2083
+ });
2084
+ return 0;
2085
+ }
2086
+ // Loopback OAuth always yields a HUMAN credential — `--as agent*` on this
2087
+ // flow is a contradiction, refused before the browser is opened.
2088
+ if (asked.principal === 'agent') {
2089
+ throw new CliError(`the loopback OAuth login produces a human credential and cannot be stored in the \`${credentialSlot(asked)}\` slot — drop \`--as\`, or use \`login --with-token\` with an \`olp_\` agent token`);
2090
+ }
2091
+ const slot = { principal: 'human' };
2092
+ const existed = readCredential(io, origin, slot) !== null;
2093
+ // Loopback OAuth: bind the port FIRST (the service matches redirect URIs by
2094
+ // exact string — no RFC 8252 variable-port allowance — so the DCR must carry
2095
+ // the concrete 127.0.0.1:<port> callback).
2096
+ const { verifier, challenge } = pkcePair();
2097
+ const state = randomState();
2098
+ const timeoutOverride = Number(io.env.OWENLOOP_LOGIN_TIMEOUT_MS);
2099
+ const timeoutMs = Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : undefined;
2100
+ const { server, port, waitForCallback, close } = await startLoopbackServer(state, timeoutMs);
2101
+ try {
2102
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
2103
+ const meta = await discoverMetadata(io, origin);
2104
+ if (!meta.authorization_endpoint || !meta.token_endpoint || !meta.registration_endpoint) {
2105
+ throw new CliError(`hub ${origin} does not advertise the OAuth endpoints login needs`);
2106
+ }
2107
+ const clientId = await registerClient(io, origin, meta.registration_endpoint, redirectUri);
2108
+ const authUrl = new URL(resolveEndpoint(origin, meta.authorization_endpoint));
2109
+ authUrl.searchParams.set('response_type', 'code');
2110
+ authUrl.searchParams.set('client_id', clientId);
2111
+ authUrl.searchParams.set('redirect_uri', redirectUri);
2112
+ authUrl.searchParams.set('code_challenge', challenge);
2113
+ authUrl.searchParams.set('code_challenge_method', 'S256');
2114
+ authUrl.searchParams.set('state', state);
2115
+ io.err(`Opening your browser to sign in. If it does not open, visit:\n ${authUrl.toString()}`);
2116
+ (io.openUrl ?? defaultOpenUrl)(authUrl.toString());
2117
+ const { code } = await waitForCallback;
2118
+ const exchanged = await exchangeCode(io, origin, meta.token_endpoint, {
2119
+ code,
2120
+ clientId,
2121
+ redirectUri,
2122
+ verifier,
2123
+ });
2124
+ const { cred, identity } = await verifyCredential(io, origin, slot, exchanged, false); // never store an unverified token
2125
+ const storage = storeCredential(io, origin, slot, cred);
2126
+ print(io, {
2127
+ ok: true,
2128
+ hub: origin,
2129
+ kind: cred.kind,
2130
+ slot: credentialSlot(slot),
2131
+ storage,
2132
+ replaced: existed,
2133
+ org: identity.orgName,
2134
+ orgId: identity.orgId,
2135
+ identity: identity.actor,
2136
+ ...(identity.email ? { email: identity.email } : {}),
2137
+ });
2138
+ return 0;
2139
+ }
2140
+ finally {
2141
+ void server;
2142
+ close();
2143
+ }
2144
+ }
2145
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
2146
+ /**
2147
+ * Bind a single-use loopback catcher on 127.0.0.1:0 that resolves on the OAuth
2148
+ * callback. `timeoutMs` overrides the 5-minute default (test knob, threaded
2149
+ * from `OWENLOOP_LOGIN_TIMEOUT_MS` by `dispatchLogin`, consistent with the
2150
+ * project's other `OWENLOOP_*` test-only env knobs).
2151
+ */
2152
+ async function startLoopbackServer(expectedState, timeoutMs = LOGIN_TIMEOUT_MS) {
2153
+ const loginHtml = (msg) => `<!doctype html><meta charset="utf-8"><title>owenloop</title><body style="font-family:system-ui;padding:2rem"><p>${msg}</p></body>`;
2154
+ let resolveCb;
2155
+ let rejectCb;
2156
+ const waitForCallback = new Promise((res, rej) => {
2157
+ resolveCb = res;
2158
+ rejectCb = rej;
2159
+ });
2160
+ // The timeout timer (below) can fire — and reject waitForCallback — before
2161
+ // dispatchLogin reaches its `await waitForCallback` (it awaits
2162
+ // discoverMetadata/registerClient first), which would otherwise surface as
2163
+ // an unhandled rejection and crash the process. This no-op .catch marks the
2164
+ // rejection handled without consuming it; the later real `await
2165
+ // waitForCallback` in dispatchLogin still sees and throws the same error.
2166
+ waitForCallback.catch(() => { });
2167
+ const server = createServer((req, res) => {
2168
+ const u = new URL(req.url ?? '/', 'http://127.0.0.1');
2169
+ if (u.pathname !== '/callback') {
2170
+ res.writeHead(404);
2171
+ res.end();
2172
+ return;
2173
+ }
2174
+ const error = u.searchParams.get('error');
2175
+ const code = u.searchParams.get('code');
2176
+ const gotState = u.searchParams.get('state');
2177
+ if (error) {
2178
+ res.writeHead(400, { 'Content-Type': 'text/html' });
2179
+ res.end(loginHtml('Login failed. You can close this tab.'));
2180
+ rejectCb(new CliError(`login denied by the hub: ${error}`));
2181
+ return;
2182
+ }
2183
+ if (gotState !== expectedState) {
2184
+ res.writeHead(400, { 'Content-Type': 'text/html' });
2185
+ res.end(loginHtml('State mismatch. You can close this tab.'));
2186
+ rejectCb(new CliError('state mismatch on the OAuth callback — possible CSRF; aborting login'));
2187
+ return;
2188
+ }
2189
+ if (!code) {
2190
+ res.writeHead(400, { 'Content-Type': 'text/html' });
2191
+ res.end(loginHtml('Missing authorization code. You can close this tab.'));
2192
+ rejectCb(new CliError('OAuth callback carried no authorization code'));
2193
+ return;
2194
+ }
2195
+ res.writeHead(200, { 'Content-Type': 'text/html' });
2196
+ res.end(loginHtml('Login complete — return to your terminal.'));
2197
+ resolveCb({ code });
2198
+ });
2199
+ const timer = setTimeout(() => {
2200
+ const human = timeoutMs % 60_000 === 0 ? `${timeoutMs / 60_000} minutes` : `${timeoutMs}ms`;
2201
+ rejectCb(new CliError(`login timed out after ${human} waiting for the browser callback`));
2202
+ }, timeoutMs);
2203
+ timer.unref?.();
2204
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
2205
+ const port = server.address().port;
2206
+ return {
2207
+ server,
2208
+ port,
2209
+ waitForCallback,
2210
+ close: () => {
2211
+ clearTimeout(timer);
2212
+ server.close();
2213
+ },
2214
+ };
2215
+ }
2216
+ /** DCR a public client (no client secret) with the exact loopback redirect URI. */
2217
+ async function registerClient(io, origin, registrationEndpoint, redirectUri) {
2218
+ const res = await hubFetch(io, resolveEndpoint(origin, registrationEndpoint), {
2219
+ method: 'POST',
2220
+ headers: { 'Content-Type': 'application/json' },
2221
+ body: JSON.stringify({
2222
+ client_name: 'owenloop CLI',
2223
+ redirect_uris: [redirectUri],
2224
+ token_endpoint_auth_method: 'none',
2225
+ grant_types: ['authorization_code', 'refresh_token'],
2226
+ response_types: ['code'],
2227
+ }),
2228
+ });
2229
+ if (!res.ok) {
2230
+ throw new CliError(`dynamic client registration failed at ${origin} (HTTP ${res.status})`);
2231
+ }
2232
+ const json = (await res.json());
2233
+ if (typeof json.client_id !== 'string') {
2234
+ throw new CliError('dynamic client registration returned no client_id');
2235
+ }
2236
+ return json.client_id;
2237
+ }
2238
+ /** Exchange an auth code for tokens (form-encoded, with the PKCE verifier). */
2239
+ async function exchangeCode(io, origin, tokenEndpoint, p) {
2240
+ const body = new URLSearchParams({
2241
+ grant_type: 'authorization_code',
2242
+ code: p.code,
2243
+ client_id: p.clientId,
2244
+ redirect_uri: p.redirectUri,
2245
+ code_verifier: p.verifier,
2246
+ });
2247
+ const res = await hubFetch(io, resolveEndpoint(origin, tokenEndpoint), {
2248
+ method: 'POST',
2249
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
2250
+ body: body.toString(),
2251
+ });
2252
+ if (!res.ok) {
2253
+ throw new CliError(`token exchange failed at ${origin} (HTTP ${res.status})`);
2254
+ }
2255
+ const json = (await res.json());
2256
+ if (typeof json.access_token !== 'string' || typeof json.refresh_token !== 'string') {
2257
+ throw new CliError('token exchange returned an incomplete token set');
2258
+ }
2259
+ const expiresIn = typeof json.expires_in === 'number' ? json.expires_in : 3600;
2260
+ return {
2261
+ kind: 'oauth',
2262
+ accessToken: json.access_token,
2263
+ refreshToken: json.refresh_token,
2264
+ expiresAt: nowMs() + expiresIn * 1000,
2265
+ clientId: p.clientId,
2266
+ };
2267
+ }
2268
+ /**
2269
+ * `owenloop logout` — delete the stored credential for a hub, in ONE slot
2270
+ * (`--as`, default `human`), from both the keychain and the file store. Cheap;
2271
+ * completes the credential lifecycle. Other slots for the same origin are left
2272
+ * alone: the keychain cannot enumerate its accounts, so a blanket
2273
+ * clear-everything is not implementable and is not faked.
2274
+ */
2275
+ async function dispatchLogout(io, args) {
2276
+ const origin = resolveHub(io, args);
2277
+ const slot = resolveSlot(args);
2278
+ const removed = deleteCredential(io, origin, slot);
2279
+ const slotName = credentialSlot(slot);
2280
+ if (!removed) {
2281
+ io.err(`no stored credential for ${origin} in slot \`${slotName}\` — another slot may hold one (see --as)`);
2282
+ }
2283
+ print(io, { ok: true, hub: origin, slot: slotName, removed });
2284
+ return 0;
2285
+ }
2286
+ /**
2287
+ * `owenloop connect` — bind the current project to a hub (writes
2288
+ * `.owenloop/hub.json`) and verify the stored credential works. Requires a
2289
+ * prior `owenloop login` for the resolved origin. `.owenloop/hub.json` is a
2290
+ * pure binding — there's no push state to preserve or reset across a rebind
2291
+ * (see `HubBinding`); `switchedFrom` is still reported when the origin
2292
+ * changes so the caller notices the rebind.
2293
+ */
2294
+ async function dispatchConnect(io, args) {
2295
+ const origin = resolveHub(io, args);
2296
+ const slot = resolveSlot(args);
2297
+ const cred = readCredential(io, origin, slot);
2298
+ if (!cred)
2299
+ throw new CliError(emptySlotMessage(origin, slot));
2300
+ const { identity } = await verifyCredential(io, origin, slot, cred);
2301
+ const path = hubBindingPath(io.cwd);
2302
+ const existing = readHubBinding(path);
2303
+ const switched = existing !== null && existing.hub !== origin;
2304
+ const binding = { version: 1, hub: origin };
2305
+ writeHubBinding(path, binding);
2306
+ print(io, {
2307
+ ok: true,
2308
+ hub: origin,
2309
+ ...(switched ? { switchedFrom: existing.hub } : {}),
2310
+ org: identity.orgName,
2311
+ orgId: identity.orgId,
2312
+ identity: identity.actor,
2313
+ ...(identity.email ? { email: identity.email } : {}),
2314
+ });
2315
+ return 0;
2316
+ }
2317
+ /**
2318
+ * `owenloop push [<defName>...] [--force] [--dry-run]` — publish local workflow
2319
+ * defs to the bound hub, diffed against the hub's own def `hash`
2320
+ * (`GET /api/workflows` — see `computeServerDiff`), never a client-side
2321
+ * ledger. Mirrors `add`'s all-or-nothing client-side validation gate before
2322
+ * any network write; server-side failures mid-batch record what landed and
2323
+ * exit 1. `POST /api/create_workflow` is itself idempotent, so even a wrong
2324
+ * "changed" verdict (e.g. from engine-version drift between this CLI and the
2325
+ * hub) is harmless — it just costs one extra round-trip that the server
2326
+ * reports back as a no-op.
2327
+ */
2328
+ async function dispatchPush(io, args) {
2329
+ const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
2330
+ const dryRun = flag(args, 'dry-run');
2331
+ const force = flag(args, 'force');
2332
+ const slot = resolveSlot(args);
2333
+ // Require a project binding.
2334
+ const bindingPath = hubBindingPath(io.cwd);
2335
+ const binding = readHubBinding(bindingPath);
2336
+ if (!binding)
2337
+ throw new CliError('this project is not bound to a hub — run `owenloop connect` first');
2338
+ // Defense in depth (SEC-2): a hub.json written by an older CLI could carry a
2339
+ // remote-http origin that predates the transport policy, and dispatchPush uses
2340
+ // it verbatim as the request origin. Validate the persisted binding at USE
2341
+ // time — normalizeOrigin enforces https-except-loopback. This check lives
2342
+ // here, NOT inside readHubBinding: dispatchConnect reads the existing binding
2343
+ // only to report switchedFrom, and a read-time throw would deadlock rebinding
2344
+ // AWAY from a bad origin. Leave readHubBinding shape-validation-only.
2345
+ let origin;
2346
+ try {
2347
+ origin = normalizeOrigin(binding.hub);
2348
+ }
2349
+ catch (e) {
2350
+ throw new CliError(`${e.message} — re-run \`owenloop connect\` to rebind`);
2351
+ }
2352
+ // A --hub that disagrees with the binding is a mistake, not a silent override.
2353
+ const hubArg = last(args, 'hub');
2354
+ if (hubArg !== undefined) {
2355
+ const requested = normalizeOrigin(hubArg);
2356
+ if (requested !== origin) {
2357
+ throw new CliError(`this project is bound to ${origin}, not ${requested} — re-run \`owenloop connect\` to rebind`);
2358
+ }
2359
+ }
2360
+ let cred = readCredential(io, origin, slot);
2361
+ if (!cred)
2362
+ throw new CliError(emptySlotMessage(origin, slot));
2363
+ // Load defs (same machinery as lint/add).
2364
+ if (!existsSync(defsDir))
2365
+ throw new CliError(`defs directory not found: ${defsDir}`);
2366
+ const failures = [];
2367
+ const allDefs = loadDefsRaw(defsDir, failures);
2368
+ // Narrow to positional names, if any (error on an unknown name).
2369
+ const requested = args.positionals.slice(1);
2370
+ let selected;
2371
+ if (requested.length > 0) {
2372
+ selected = [];
2373
+ for (const name of requested) {
2374
+ const def = allDefs.get(name);
2375
+ if (!def) {
2376
+ throw new CliError(`unknown workflow definition '${name}' (looked in ${defsDir})${failureNote(failures)}`);
2377
+ }
2378
+ selected.push(def);
2379
+ }
2380
+ }
2381
+ else {
2382
+ selected = [...allDefs.values()];
2383
+ }
2384
+ if (selected.length === 0) {
2385
+ throw new CliError(`nothing to push — no workflow definitions found in ${defsDir}`);
2386
+ }
2387
+ // Client-side validation gate — all-or-nothing, mirroring dispatchAdd exactly.
2388
+ // Any failure aborts the entire push; nothing is sent.
2389
+ const reasons = failures.map((f) => `${f.file}: ${f.error}`);
2390
+ for (const def of selected) {
2391
+ const lintResult = lintDef(def);
2392
+ reasons.push(...lintResult.errors.map((e) => `${def.name}: ${e}`));
2393
+ reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
2394
+ const report = modelCheck(def, { assumeProvided: true });
2395
+ const hasDefiniteDefect = report.invariantViolations.length > 0 ||
2396
+ (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
2397
+ if (hasDefiniteDefect) {
2398
+ reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
2399
+ `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
2400
+ }
2401
+ }
2402
+ // Assemble the push candidates: verbatim source yaml + the server-canonical
2403
+ // content hash (hashDefForHub). Defs whose file uses include: are not
2404
+ // hub-pushable (the service's create_workflow parses without include
2405
+ // expansion, and a re-serialized expanded def is not round-trippable) —
2406
+ // refuse them with a clear per-def reason. Same for bodyFile: — hashDefForHub
2407
+ // parses with no baseDir (matching the server's own computation), which
2408
+ // throws a DefError naming bodyFile for such a def; catch that specific
2409
+ // failure and refuse the def pre-push rather than letting it read as a
2410
+ // generic error (the server would reject the raw-YAML push anyway).
2411
+ const candidates = [];
2412
+ for (const def of selected) {
2413
+ if (!def.dir) {
2414
+ reasons.push(`${def.name}: has no source file on disk to push`);
2415
+ continue;
2416
+ }
2417
+ const yaml = readFileSync(def.dir, 'utf8');
2418
+ let usesInclude = false;
2419
+ try {
2420
+ const rawDef = buildDef(parseYaml(yaml), basename(def.dir), dirname(def.dir));
2421
+ usesInclude = (rawDef._includes?.length ?? 0) > 0;
2422
+ }
2423
+ catch {
2424
+ // A shape error here would already have surfaced via the validation gate;
2425
+ // treat an unexpected re-parse failure conservatively as pushable-as-is.
2426
+ }
2427
+ if (usesInclude) {
2428
+ reasons.push(`${def.name}: uses include:, not hub-pushable yet`);
2429
+ continue;
2430
+ }
2431
+ let hash;
2432
+ try {
2433
+ hash = hashDefForHub(yaml);
2434
+ }
2435
+ catch (e) {
2436
+ if (e instanceof DefError && /bodyFile/.test(e.message)) {
2437
+ reasons.push(`${def.name}: uses bodyFile:, not hub-pushable`);
2438
+ continue;
2439
+ }
2440
+ throw e;
2441
+ }
2442
+ candidates.push({ name: def.name, hash, yaml });
2443
+ }
2444
+ if (reasons.length > 0) {
2445
+ throw new CliError(`refusing to push — ${reasons.length} problem(s) found; nothing sent:\n - ${reasons.join('\n - ')}`);
2446
+ }
2447
+ // Fetch the server's own list once — the diff source of truth. Always
2448
+ // fetched, even under --force, so the new/changed labels stay accurate.
2449
+ const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, cred, '/api/workflows');
2450
+ assertAuthOk(listRes, listCred, origin);
2451
+ cred = listCred;
2452
+ let serverMap;
2453
+ try {
2454
+ serverMap = parseWorkflowList(await listRes.json());
2455
+ }
2456
+ catch (e) {
2457
+ throw new CliError(e.message);
2458
+ }
2459
+ const { toPush, unchanged } = computeServerDiff(candidates, serverMap, force);
2460
+ // Diff-style human lines go to stderr so stdout stays machine-parseable JSON.
2461
+ for (const c of unchanged)
2462
+ io.err(`= ${c.name} (unchanged)`);
2463
+ if (dryRun) {
2464
+ for (const c of toPush) {
2465
+ io.err(c.status === 'new' ? `+ ${c.name} (new)` : `~ ${c.name} (changed)`);
2466
+ }
2467
+ print(io, {
2468
+ ok: true,
2469
+ dryRun: true,
2470
+ hub: origin,
2471
+ new: toPush.filter((c) => c.status === 'new').map((c) => c.name),
2472
+ changed: toPush.filter((c) => c.status === 'changed').map((c) => c.name),
2473
+ unchanged: unchanged.map((c) => c.name),
2474
+ wouldPush: toPush.map((c) => c.name),
2475
+ });
2476
+ return 0;
2477
+ }
2478
+ // Refresh an expiring oauth token once up front (per-request 401 refresh below covers mid-batch expiry).
2479
+ cred = await ensureFreshOAuth(io, origin, slot, cred);
2480
+ const pushedNames = [];
2481
+ const noopNames = [];
2482
+ const failed = [];
2483
+ const skipped = [];
2484
+ for (let i = 0; i < toPush.length; i++) {
2485
+ const c = toPush[i];
2486
+ const label = c.status === 'new' ? '+' : '~';
2487
+ try {
2488
+ let res = await createWorkflowRequest(io, origin, cred, c.yaml);
2489
+ if (res.status === 401 && cred.kind === 'oauth') {
2490
+ cred = await refreshOAuth(io, origin, slot, cred);
2491
+ res = await createWorkflowRequest(io, origin, cred, c.yaml);
2492
+ }
2493
+ if (res.status === 401) {
2494
+ if (cred.kind === 'agent') {
2495
+ throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
2496
+ }
2497
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
2498
+ }
2499
+ if (res.status === 413)
2500
+ throw new CliError('workflow yaml exceeds the hub 32MB request cap');
2501
+ if (res.status === 429) {
2502
+ const retryAfter = res.headers.get('retry-after');
2503
+ throw new RateLimitError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
2504
+ }
2505
+ if (!res.ok)
2506
+ throw new CliError(`hub returned HTTP ${res.status}`);
2507
+ const bodyJson = await res.json();
2508
+ const errText = createWorkflowError(bodyJson);
2509
+ if (errText !== null)
2510
+ throw new CliError(`hub rejected the def: ${errText}`);
2511
+ const okBody = asCreateWorkflowOk(bodyJson, c.name);
2512
+ if (okBody.unchanged) {
2513
+ noopNames.push(c.name);
2514
+ io.err(`= ${c.name} (server: unchanged, v${okBody.version})`);
2515
+ }
2516
+ else {
2517
+ pushedNames.push(c.name);
2518
+ io.err(`${label} ${c.name} (→ v${okBody.version})`);
2519
+ }
2520
+ }
2521
+ catch (e) {
2522
+ // A 429 halts the whole batch immediately (REL-10): record this def as
2523
+ // failed, then stop — the not-yet-attempted remainder is reported as
2524
+ // `skipped`, not silently hammered against a rate-limited server.
2525
+ // Handled before the generic path because RateLimitError extends CliError.
2526
+ if (e instanceof RateLimitError) {
2527
+ const msg = e.message;
2528
+ failed.push({ name: c.name, error: msg });
2529
+ io.err(`! ${c.name} (failed: ${msg})`);
2530
+ const remainder = toPush.slice(i + 1).map((r) => r.name);
2531
+ skipped.push(...remainder);
2532
+ if (remainder.length > 0) {
2533
+ io.err(`stopping — rate limited by the hub; ${remainder.length} def(s) not attempted`);
2534
+ }
2535
+ break;
2536
+ }
2537
+ // A hard auth error aborts the whole run (re-throw); a per-def server
2538
+ // failure is recorded and the batch continues (already-pushed defs stand).
2539
+ if (e instanceof CliError && /run `owenloop login`|re-mint it/.test(e.message)) {
2540
+ throw e;
2541
+ }
2542
+ const msg = e.message;
2543
+ failed.push({ name: c.name, error: msg });
2544
+ io.err(`! ${c.name} (failed: ${msg})`);
2545
+ }
2546
+ }
2547
+ print(io, {
2548
+ ok: failed.length === 0,
2549
+ hub: origin,
2550
+ pushed: pushedNames,
2551
+ noop: noopNames,
2552
+ unchanged: unchanged.map((c) => c.name),
2553
+ skipped,
2554
+ failed,
2555
+ });
2556
+ return failed.length === 0 ? 0 : 1;
2557
+ }
2558
+ function createWorkflowRequest(io, origin, cred, yaml) {
2559
+ return hubFetch(io, resolveEndpoint(origin, '/api/create_workflow'), {
2560
+ method: 'POST',
2561
+ headers: {
2562
+ Authorization: authHeader(cred),
2563
+ 'Content-Type': 'application/json',
2564
+ Accept: 'application/json',
2565
+ },
2566
+ body: JSON.stringify({ yaml }),
2567
+ });
2568
+ }
2569
+ /**
2570
+ * Async entry point that adds network I/O for `add` and the hub commands on top
2571
+ * of the otherwise fully-synchronous engine/CLI (see the doc comment on
2572
+ * `sleepMs` above and README "sync end to end"). `main`/`dispatch` stay sync and
2573
+ * unchanged — this wraps them, routing only the network-touching verbs through
2574
+ * the async path, so every existing command and test keeps working exactly as
2575
+ * before.
2576
+ */
2577
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push']);
2578
+ export async function mainAsync(argv, io = defaultIO()) {
2579
+ const args = parseArgs(argv);
2580
+ const command = args.positionals[0];
2581
+ if (command === undefined || !ASYNC_COMMANDS.has(command)) {
2582
+ return main(argv, io);
2583
+ }
2584
+ try {
2585
+ const short = preflight(command, args, io);
2586
+ if (short !== undefined)
2587
+ return short;
2588
+ switch (command) {
2589
+ case 'add':
2590
+ return await dispatchAdd(io, args);
2591
+ case 'login':
2592
+ return await dispatchLogin(io, args);
2593
+ case 'logout':
2594
+ return await dispatchLogout(io, args);
2595
+ case 'connect':
2596
+ return await dispatchConnect(io, args);
2597
+ case 'push':
2598
+ return await dispatchPush(io, args);
2599
+ default:
2600
+ return main(argv, io); // unreachable — ASYNC_COMMANDS guards the switch
2601
+ }
2602
+ }
2603
+ catch (e) {
2604
+ if (e instanceof CliError || e instanceof DefError) {
2605
+ io.err(`error: ${e.message}`);
2606
+ }
2607
+ else {
2608
+ io.err(`error: ${e.message}`);
2609
+ }
2610
+ return 1;
2611
+ }
2612
+ }
770
2613
  /** Run the CLI. Returns a process exit code. */
771
2614
  export function main(argv, io = defaultIO()) {
772
2615
  const args = parseArgs(argv);
@@ -776,6 +2619,9 @@ export function main(argv, io = defaultIO()) {
776
2619
  return 0;
777
2620
  }
778
2621
  try {
2622
+ const short = preflight(command, args, io);
2623
+ if (short !== undefined)
2624
+ return short;
779
2625
  return dispatch(command, io, args);
780
2626
  }
781
2627
  catch (e) {