owenloop 0.3.1 → 0.4.1

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/CHANGELOG.md CHANGED
@@ -4,6 +4,38 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.4.1](https://github.com/typicalday/owenloop/compare/v0.4.0...v0.4.1) (2026-07-22)
8
+
9
+
10
+ ### Features
11
+
12
+ * **check:** default seedOwed inputs to assumed-provided, add --strict-inputs ([#80](https://github.com/typicalday/owenloop/issues/80)) ([1a0891f](https://github.com/typicalday/owenloop/commit/1a0891f280c5d0ccb942cb29ad734480238d652d))
13
+ * **check:** split dead steps into structurally-dead vs unreached-within-bounds ([#77](https://github.com/typicalday/owenloop/issues/77)) ([f7efb10](https://github.com/typicalday/owenloop/commit/f7efb10f922ea5a0baf04df839ce36fd0c626e82))
14
+ * **check:** split EXPECTED stall states from TRUE deadlocks in owenloop check ([#78](https://github.com/typicalday/owenloop/issues/78)) ([5933a67](https://github.com/typicalday/owenloop/commit/5933a67eeee9e654d3e4ba4c48854f6ef04b83b0))
15
+ * **cli:** agent new — mint an agent token into the credential store ([#75](https://github.com/typicalday/owenloop/issues/75)) ([f115cb9](https://github.com/typicalday/owenloop/commit/f115cb9739be28e29de5a7e1debd1155e4ab4a9f))
16
+ * **cli:** owenloop setup + doctor — shipped auth/setup experience (O4) ([#79](https://github.com/typicalday/owenloop/issues/79)) ([9a10d9a](https://github.com/typicalday/owenloop/commit/9a10d9ac618b6f31a5db5c106e3ae91bf44a3c6d))
17
+ * **defs:** flag silently-dead reduce and evaluator steps in validateDef ([#73](https://github.com/typicalday/owenloop/issues/73)) ([84c81f4](https://github.com/typicalday/owenloop/commit/84c81f46197792fe741bff7d74f5e30a537598d7))
18
+ * **hub:** credential write API + concurrency-safe OAuth refresh ([#71](https://github.com/typicalday/owenloop/issues/71)) ([9514571](https://github.com/typicalday/owenloop/commit/95145718492882cfd1088d540f54d639773e82a7))
19
+ * **mcp:** `owenloop mcp` stdio control-plane server (O2) ([#76](https://github.com/typicalday/owenloop/issues/76)) ([0daa66c](https://github.com/typicalday/owenloop/commit/0daa66c5fd32a64a40ab08ba9b393b77350fb91c))
20
+
21
+
22
+ ### Bug Fixes
23
+
24
+ * **engine:** distinguish absent-from-fingerprint vs moved-version in born-reject reasons ([#74](https://github.com/typicalday/owenloop/issues/74)) ([1567b80](https://github.com/typicalday/owenloop/commit/1567b807accc11a71eb9f2cfd7930224577a67a0))
25
+
26
+ ## [0.4.0](https://github.com/typicalday/owenloop/compare/v0.3.1...v0.4.0) (2026-07-21)
27
+
28
+
29
+ ### ⚠ BREAKING CHANGES
30
+
31
+ * `Keychain` methods take `(service, account)`, the `readStoredCredential` options argument is required and must carry a principal, and credentials stored under the previous keying are not read. There is deliberately no migration path — re-run `owenloop login`.
32
+
33
+ ### Features
34
+
35
+ * **hub:** optional external command for hub credentials ([#69](https://github.com/typicalday/owenloop/issues/69)) ([bd52654](https://github.com/typicalday/owenloop/commit/bd526545983e055a479be2f93e1e644a2ee37131))
36
+ * principal-namespaced credential slots for hub credentials ([#68](https://github.com/typicalday/owenloop/issues/68)) ([253174f](https://github.com/typicalday/owenloop/commit/253174f33d51f90f1e051e85ff21a15b4d11e031))
37
+ * **store:** export read-only credential surface (readStoredCredential) ([#66](https://github.com/typicalday/owenloop/issues/66)) ([ed43efd](https://github.com/typicalday/owenloop/commit/ed43efdc7f305ca231f35f251c9d13886898d41a))
38
+
7
39
  ## [0.3.1](https://github.com/typicalday/owenloop/compare/v0.3.0...v0.3.1) (2026-07-17)
8
40
 
9
41
 
package/README.md CHANGED
@@ -370,9 +370,25 @@ the CLI (loopback OAuth, or a pasted token via `--with-token`; the credential
370
370
  goes into the macOS Keychain or a `0600` file, never the repo, and is verified
371
371
  against the hub before it's ever stored), `owenloop connect` binds the project
372
372
  to a hub, and `owenloop push` publishes your defs — idempotent against the
373
- hub's own def hashes, so an unchanged re-push is a no-op. See the
373
+ hub's own def hashes, so an unchanged re-push is a no-op. `owenloop agent new
374
+ <name>` mints an agent identity on the hub and stores its token in slot
375
+ `agent:<name>` without ever printing it. See the
374
376
  [Hub](docs/cli.md#hub-login--connect--push--logout) section in `docs/cli.md`.
375
377
 
378
+ Setting up a machine from scratch? `owenloop setup` converges the whole install
379
+ in one idempotent pass — human login, agent credential, owenwork settings, and
380
+ the Claude Code plugin — so a re-run on an already-set-up machine writes
381
+ nothing. `owenloop doctor` is its read-only counterpart: it checks each piece
382
+ and prints a `✓`/`✗` line with the remedy. See
383
+ [`setup`](docs/cli.md#setup--converge-a-machines-install) and
384
+ [`doctor`](docs/cli.md#doctor--check-a-machines-install) in `docs/cli.md`.
385
+
386
+ Driving the hub from an MCP host instead? `owenloop mcp` serves the hub control
387
+ plane to a local MCP host (Claude Code) over stdio — MCP hosts spawn it, you
388
+ don't run it yourself — authenticating as your logged-in human credential and
389
+ never surfacing a token to the model. See the
390
+ [`mcp`](docs/cli.md#mcp--stdio-control-plane-server-for-mcp-hosts) section in `docs/cli.md`.
391
+
376
392
  ---
377
393
 
378
394
  ## Requirements
@@ -428,6 +444,20 @@ since. The changes that need operator or embedder attention:
428
444
  and store a credential in the macOS Keychain or a `0600` file — see the
429
445
  [Hub](docs/cli.md#hub-login--connect--push--logout) section and the `add`
430
446
  [trust model](docs/cli.md#add--installing-shared-workflow-defs-from-github).
447
+ A hub origin now holds one credential per named **slot** (`--as
448
+ human|agent|agent:<account>`), and credentials stored under the earlier keying
449
+ are not read — there is no migration, so re-run `owenloop login`. `owenloop
450
+ agent new <name>` mints an agent token straight into slot `agent:<name>`
451
+ without ever printing the secret. Setting
452
+ `OWENLOOP_CREDENTIAL_COMMAND` instead supplies the credential from a command
453
+ of your own (a secret manager, or any host without a keychain); it takes
454
+ precedence over both stores and fails loudly rather than falling back.
455
+ Embedders can now read, write, and refresh a hub credential programmatically
456
+ through the package's exported credential surface (`readStoredCredential`,
457
+ `storeCredential`, `deleteCredential`, `ensureFreshOAuth`, `CredentialIO`);
458
+ concurrent OAuth refreshes are serialized by a `credentials.lock` file so a
459
+ token rotation can't clobber a fresher one — see
460
+ [What's exported](docs/embedding.md#whats-exported).
431
461
  - **Max-lease cap is now opt-in.** There is no default lease ceiling; anyone who
432
462
  relied on the brief post-0.2.1 default cap must set `maxLeaseMs` (or a
433
463
  per-step `maxLease`) explicitly.
@@ -547,6 +577,28 @@ a re-provided input while leaving a healthy graph and a terminal output untouche
547
577
  a malformed value is rejected rather than greened, a corrected value greens on the same
548
578
  open job, repeated failures trip the stall and a `retry` clears it.
549
579
 
580
+ `owenloop check <def>` runs a bounded static reachability search over a workflow
581
+ definition and reports dead steps (never seen firing) split by severity: steps that
582
+ can NEVER fire regardless of search bounds are **structurally dead** — a real wiring
583
+ defect, reported nonzero exit — while steps that CAN fire but the bounded search
584
+ just didn't reach are **unreached within bounds** — informational only, exit 0.
585
+ It also splits every reachable non-done, no-moves state into exactly one of two
586
+ buckets: a **stall state** — the state's only blocker is a frozen/stalled debt
587
+ (maxAttempts / maxSchemaFailures / held); recomputing eligibility with the freeze
588
+ lifted (a human `retry` = unlimited attempts) shows a producer would re-arm and the
589
+ line could move — this is an EXPECTED, by-design human-escalation brake and never
590
+ fails the check — versus a **true deadlock** — the same recompute STILL yields no
591
+ moves, a genuine structural dead-end, which fails the check nonzero when the search
592
+ is exhaustive. See [`docs/design.md` §25](docs/design.md#25-the-model-checker-owenloop-check--scope)
593
+ for the full breakdown.
594
+
595
+ By default, `seedOwed` inputs are assumed provided (modeling the operator's `provide`
596
+ already having run at create), so a def whose only initial gate is an unprovided seeded
597
+ input no longer reports a false `True deadlocks ... (initial state)` and nonzero exit.
598
+ `--strict-inputs` restores the seeded-inputs-start-owed behavior; when that's the sole
599
+ blocker, it also prints a one-line hint naming the seedOwed input(s) responsible.
600
+ `--assume-provided` is still accepted but is now a no-op (redundant with the default).
601
+
550
602
  ---
551
603
 
552
604
  ## Design reference
package/dist/add.d.ts CHANGED
@@ -9,6 +9,8 @@
9
9
  * unit-testable and `cli.ts` doesn't widen its export surface just to reuse
10
10
  * `Args`/`CliError`/etc.
11
11
  */
12
+ import { releaseFileLock } from './lock.ts';
13
+ import type { AcquireFileLockOpts, FileLockHandle } from './lock.ts';
12
14
  /**
13
15
  * Returns `undefined` if `relPath` is safe to `join()` under a destination
14
16
  * directory, else a human-readable reason it must be rejected. This is
@@ -234,49 +236,19 @@ export declare function finalizeInstallCommit(handle: InstallCommitHandle): void
234
236
  * happened" state to reconcile (the park is one atomic rename).
235
237
  */
236
238
  export declare function rollbackInstallCommit(handle: InstallCommitHandle): void;
237
- export interface InstallLockHandle {
238
- lockPath: string;
239
- acquired: boolean;
240
- /** Per-acquisition ownership token — present when `acquired`; proof of ownership for release. */
241
- token?: string;
242
- }
243
- export interface AcquireLockOpts {
244
- /** Max time to wait for a live lock before failing cleanly (default 10s). */
245
- waitMs?: number;
246
- /**
247
- * Age (by mtime) past which an *unparseable/abandoned* lock may be reclaimed
248
- * (default 10m). Age NEVER reclaims a lock whose recorded pid is alive on
249
- * this host — it only governs the fail-closed fallback for a lock we cannot
250
- * attribute to a live owner (unparseable payload, or one without a pid).
251
- */
252
- staleMs?: number;
253
- /** Poll interval while waiting on a live lock (default 100ms). */
254
- pollMs?: number;
255
- /** Liveness probe for the holder pid — injectable so tests are deterministic. */
256
- isPidAlive?: (pid: number) => boolean;
257
- /** Clock — injectable so tests are deterministic. */
258
- now?: () => number;
259
- /** Current hostname — injectable so cross-host tests are deterministic (default `os.hostname`). */
260
- hostname?: () => string;
261
- }
239
+ /** The install lock handle — now the generic `FileLockHandle` from `lock.ts`. */
240
+ export type InstallLockHandle = FileLockHandle;
241
+ /** The install lock acquire options — now the generic `AcquireFileLockOpts` from `lock.ts`. */
242
+ export type AcquireLockOpts = AcquireFileLockOpts;
262
243
  /**
263
- * Acquire the per-project install lock at `lockPath` (an exclusive-create of the
264
- * file, `openSync(..,'wx')` — the O_EXCL create is the real serialization point).
265
- * The payload carries an ownership token, the owner pid, a start timestamp, and
266
- * the host. If another process holds it: reclaim it only when liveness-aware
267
- * staleness says its owner is gone (see `lockIsStale`), otherwise poll until it
268
- * frees, and if it does not free within `waitMs` fail cleanly with a clear
269
- * in-progress message. Always pair with `releaseInstallLock` in a `finally`.
244
+ * Acquire the per-project install lock at `lockPath`. A 1-line adapter over the
245
+ * generic `acquireFileLock`, pinning `label` so the timeout message reads
246
+ * "another owenloop add is in progress …" byte-for-byte as before. Always pair
247
+ * with `releaseInstallLock` in a `finally`.
270
248
  */
271
249
  export declare function acquireInstallLock(lockPath: string, opts?: AcquireLockOpts): Promise<InstallLockHandle>;
272
- /**
273
- * Release a lock acquired by `acquireInstallLock`. Token-checked and
274
- * best-effort: a no-op if not acquired, if the lock is already gone/unparseable,
275
- * or if its token no longer matches this handle (someone else legitimately
276
- * re-acquired it — deleting would steal *their* lock). Never throws; it runs in
277
- * `dispatchAdd`'s `finally` and must not mask the real error.
278
- */
279
- export declare function releaseInstallLock(handle: InstallLockHandle): void;
250
+ /** Release a lock acquired by `acquireInstallLock` — the generic `releaseFileLock`. */
251
+ export declare const releaseInstallLock: typeof releaseFileLock;
280
252
  /** Journal filename under `.owenloop/` (sibling of `installed.json`/`add.lock`). */
281
253
  export declare const ADD_JOURNAL_FILENAME = "add.journal";
282
254
  /**
package/dist/add.js CHANGED
@@ -9,11 +9,10 @@
9
9
  * unit-testable and `cli.ts` doesn't widen its export surface just to reuse
10
10
  * `Args`/`CliError`/etc.
11
11
  */
12
- import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
12
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
13
13
  import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
14
- import { createHash, randomBytes } from 'node:crypto';
15
- import { hostname } from 'node:os';
16
- import { setTimeout as sleep } from 'node:timers/promises';
14
+ import { createHash } from 'node:crypto';
15
+ import { acquireFileLock, releaseFileLock } from "./lock.js";
17
16
  /** Max length for an in-archive relative path we are willing to join and write. */
18
17
  const MAX_ARCHIVE_PATH_LENGTH = 1024;
19
18
  /**
@@ -427,181 +426,17 @@ export function rollbackInstallCommit(handle) {
427
426
  if (handle.oldName)
428
427
  renameSync(handle.oldName.parkedAt, handle.oldName.originalPath);
429
428
  }
430
- // ---- per-project install lock ----------------------------------------------
431
- /** Default wait/stale/poll timings for the install lock (overridable in tests). */
432
- const LOCK_WAIT_MS = 10_000;
433
- const LOCK_STALE_MS = 10 * 60_000;
434
- const LOCK_POLL_MS = 100;
435
- /** `true` if a process with `pid` exists (signal 0 probes without delivering). */
436
- function defaultIsPidAlive(pid) {
437
- try {
438
- process.kill(pid, 0);
439
- return true;
440
- }
441
- catch (e) {
442
- // EPERM: the process exists but we may not signal it — treat as alive.
443
- // ESRCH (and anything else): no such process — dead.
444
- return e.code === 'EPERM';
445
- }
446
- }
447
- /** Read the lock file's raw bytes, or `null` if it is gone/unreadable. */
448
- function readLockRaw(lockPath) {
449
- try {
450
- return readFileSync(lockPath, 'utf8');
451
- }
452
- catch {
453
- return null;
454
- }
455
- }
456
- /** Parse raw lock bytes into a holder, or `null` if absent/unparseable. */
457
- function parseLockHolder(raw) {
458
- if (raw === null)
459
- return null;
460
- try {
461
- return JSON.parse(raw);
462
- }
463
- catch {
464
- return null;
465
- }
466
- }
467
- /** Read + parse the lock file in one step (fresh read). Used off the hot loop. */
468
- function readLockHolder(lockPath) {
469
- return parseLockHolder(readLockRaw(lockPath));
470
- }
471
429
  /**
472
- * Decide whether the lock described by `holder` (parsed from a raw read) may be
473
- * reclaimed, given the current host. Liveness-aware, not age-based:
474
- *
475
- * 1. `statSync` fails — the lock vanished mid-judgment → treat as reclaimable
476
- * (the acquire loop re-verifies and simply retries the exclusive create).
477
- * 2. Holder records a `host` that differs from ours → NOT stale, ever. A
478
- * foreign PID space means `process.kill(pid, 0)` proves nothing; a shared
479
- * filesystem could be locked by another machine. Held; caller refuses.
480
- * 3. Holder has a numeric `pid` and either matches our host or omits `host`
481
- * (a legacy same-machine payload) → stale iff that pid is dead. Age never
482
- * reclaims a live-pid lock — this is the core safety policy.
483
- * 4. Unparseable, or parses without a numeric pid → fail closed: held until
484
- * `now() - mtimeMs > staleMs` (age is the only abandonment signal left).
430
+ * Acquire the per-project install lock at `lockPath`. A 1-line adapter over the
431
+ * generic `acquireFileLock`, pinning `label` so the timeout message reads
432
+ * "another owenloop add is in progress …" byte-for-byte as before. Always pair
433
+ * with `releaseInstallLock` in a `finally`.
485
434
  */
486
- function lockIsStale(lockPath, holder, staleMs, isPidAlive, now, currentHost) {
487
- let mtimeMs;
488
- try {
489
- mtimeMs = statSync(lockPath).mtimeMs;
490
- }
491
- catch {
492
- // Vanished between the EEXIST and here — someone else reclaimed it; retry.
493
- return true;
494
- }
495
- // Case 2: recorded on a different host — its pid tells us nothing. Held.
496
- if (holder && typeof holder.host === 'string' && holder.host !== currentHost) {
497
- return false;
498
- }
499
- // Case 3: same host (or legacy no-host payload) with a numeric pid — liveness decides.
500
- if (holder && typeof holder.pid === 'number') {
501
- return !isPidAlive(holder.pid);
502
- }
503
- // Case 4: no attributable live owner — age is the only abandonment signal.
504
- return now() - mtimeMs > staleMs;
505
- }
506
- /**
507
- * Acquire the per-project install lock at `lockPath` (an exclusive-create of the
508
- * file, `openSync(..,'wx')` — the O_EXCL create is the real serialization point).
509
- * The payload carries an ownership token, the owner pid, a start timestamp, and
510
- * the host. If another process holds it: reclaim it only when liveness-aware
511
- * staleness says its owner is gone (see `lockIsStale`), otherwise poll until it
512
- * frees, and if it does not free within `waitMs` fail cleanly with a clear
513
- * in-progress message. Always pair with `releaseInstallLock` in a `finally`.
514
- */
515
- export async function acquireInstallLock(lockPath, opts = {}) {
516
- const waitMs = opts.waitMs ?? LOCK_WAIT_MS;
517
- const staleMs = opts.staleMs ?? LOCK_STALE_MS;
518
- const pollMs = opts.pollMs ?? LOCK_POLL_MS;
519
- const isPidAlive = opts.isPidAlive ?? defaultIsPidAlive;
520
- const now = opts.now ?? Date.now;
521
- const host = (opts.hostname ?? hostname)();
522
- mkdirSync(dirname(lockPath), { recursive: true });
523
- const deadline = now() + waitMs;
524
- for (;;) {
525
- try {
526
- const fd = openSync(lockPath, 'wx');
527
- const token = randomBytes(16).toString('hex');
528
- try {
529
- writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: now(), token, host }));
530
- }
531
- finally {
532
- closeSync(fd);
533
- }
534
- return { lockPath, acquired: true, token };
535
- }
536
- catch (e) {
537
- if (e.code !== 'EEXIST')
538
- throw e;
539
- }
540
- // Judge staleness from a single captured raw read...
541
- const raw = readLockRaw(lockPath);
542
- const holder = parseLockHolder(raw);
543
- if (lockIsStale(lockPath, holder, staleMs, isPidAlive, now, host)) {
544
- // ...then re-verify the bytes are unchanged immediately before deleting.
545
- // Between judging stale and rmSync a third process could reclaim and
546
- // re-create the lock; deleting then would destroy a *fresh* owner's lock.
547
- // Residual window is a few syscalls (read-compare-delete) rather than the
548
- // poll interval — and the `wx` create below is the true arbiter: if two
549
- // reclaimers race, one wins the create and the other loops on EEXIST. A
550
- // rename-based reclaim was rejected: POSIX rename clobbers its target, so
551
- // any "rename back on mismatch" arm can itself destroy a newer lock.
552
- const raw2 = readLockRaw(lockPath);
553
- if (raw2 !== null && raw2 === raw) {
554
- rmSync(lockPath, { force: true });
555
- continue; // reclaimed — retry the exclusive create
556
- }
557
- // Bytes changed under us, or the lock is stat-able but unreadable (a
558
- // root-owned 0600 lock: statSync needs only dir perms, readFileSync
559
- // EACCES → raw/raw2 null). Do NOT delete — fall through to the deadline
560
- // check and poll sleep below. Never `continue` here: with an unreadable,
561
- // backdated lock this branch would otherwise spin sleeplessly, starving
562
- // the event loop and never enforcing `waitMs`.
563
- }
564
- if (now() >= deadline) {
565
- throw new Error(inProgressMessage(lockPath, holder, waitMs));
566
- }
567
- await sleep(pollMs);
568
- }
569
- }
570
- /** Build the clear "another add is in progress" timeout error, with graceful fallbacks. */
571
- function inProgressMessage(lockPath, holder, waitMs) {
572
- const who = typeof holder?.pid === 'number' ? `pid ${holder.pid}` : 'another process';
573
- // Lock content is untrusted input: a finite `startedAt` outside the ECMAScript
574
- // Date range (|t| > 8.64e15 ms) makes `new Date(t).toISOString()` throw
575
- // RangeError. Only render held-since when the value is a valid time value;
576
- // otherwise omit it (same graceful fallback as an absent startedAt).
577
- const heldSince = typeof holder?.startedAt === 'number' &&
578
- Number.isFinite(holder.startedAt) &&
579
- Math.abs(holder.startedAt) <= 8.64e15
580
- ? `, held since ${new Date(holder.startedAt).toISOString()}`
581
- : '';
582
- const s = Math.round(waitMs / 1000);
583
- return `another owenloop add is in progress (${who}${heldSince}) — holds ${lockPath}; timed out waiting after ${s}s`;
584
- }
585
- /**
586
- * Release a lock acquired by `acquireInstallLock`. Token-checked and
587
- * best-effort: a no-op if not acquired, if the lock is already gone/unparseable,
588
- * or if its token no longer matches this handle (someone else legitimately
589
- * re-acquired it — deleting would steal *their* lock). Never throws; it runs in
590
- * `dispatchAdd`'s `finally` and must not mask the real error.
591
- */
592
- export function releaseInstallLock(handle) {
593
- if (!handle.acquired)
594
- return;
595
- try {
596
- const holder = readLockHolder(handle.lockPath);
597
- if (!holder || holder.token !== handle.token)
598
- return;
599
- rmSync(handle.lockPath, { force: true });
600
- }
601
- catch {
602
- // Already reclaimed/replaced, or an unexpected fs error — swallow.
603
- }
435
+ export function acquireInstallLock(lockPath, opts = {}) {
436
+ return acquireFileLock(lockPath, { label: 'owenloop add', ...opts });
604
437
  }
438
+ /** Release a lock acquired by `acquireInstallLock` — the generic `releaseFileLock`. */
439
+ export const releaseInstallLock = releaseFileLock;
605
440
  // ---- crash-recovery journal ------------------------------------------------
606
441
  //
607
442
  // A process that dies (crash, SIGKILL — see docs/cli.md on power-loss limits)
package/dist/cli.d.ts CHANGED
@@ -31,12 +31,9 @@
31
31
  *
32
32
  * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
33
33
  */
34
- /** An OS keychain backend, keyed by hub origin (the `account`). */
35
- export interface Keychain {
36
- get(account: string): string | null;
37
- set(account: string, value: string): void;
38
- delete(account: string): void;
39
- }
34
+ import type { LineStream } from './mcp/server.ts';
35
+ import type { AgentIdentitySummary, Keychain } from './hub.ts';
36
+ export type { Keychain } from './hub.ts';
40
37
  export interface CliIO {
41
38
  cwd: string;
42
39
  env: Record<string, string | undefined>;
@@ -57,8 +54,35 @@ export interface CliIO {
57
54
  keychain?: Keychain;
58
55
  /** Read a secret from stdin (`login --with-token`). Default: drain `process.stdin`. */
59
56
  readStdin?: () => Promise<string>;
57
+ /**
58
+ * The newline-delimited transport `owenloop mcp` pumps JSON-RPC frames from.
59
+ * Injectable for hermetic tests (a `PassThrough`); `undefined` here so the
60
+ * command falls back to `process.stdin`. Only the `mcp` verb reads it.
61
+ */
62
+ stdinStream?: LineStream;
63
+ /**
64
+ * Ask the user a question and read a line back. Used only by `setup`'s
65
+ * interactive branches (name-this-agent, succession choice). Default: a
66
+ * `node:readline/promises` interface over `process.stdin`/`process.stderr` —
67
+ * the question and echo go to STDERR so stdout stays a clean machine-parseable
68
+ * JSON document (the repo's diagnostics-to-stderr convention). Injectable so
69
+ * tests script answers without a TTY.
70
+ */
71
+ prompt?: (question: string) => Promise<string>;
72
+ /**
73
+ * Run a local command and capture its result — used ONLY by `setup`/`doctor`'s
74
+ * Claude Code plugin probe (`claude plugin list`). Default: a `spawnSync`
75
+ * wrapper with `shell: false` (never interpolates argv into a shell) that
76
+ * never inherits stdio. Injectable so tests model the plugin state without a
77
+ * real `claude` binary.
78
+ */
79
+ runCommand?: (cmd: string, args: string[]) => {
80
+ status: number | null;
81
+ stdout: string;
82
+ stderr: string;
83
+ };
60
84
  }
61
- export declare const USAGE = "owenloop \u2014 a dataflow workflow engine\n\nUsage: owenloop <command> [args] [--db <path>] [--defs <dir>]\n\nCommands:\n defs list available workflow definitions\n add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)\n add --recover finish or undo a crash-interrupted install (offline; no network)\n login [--hub <url>] [--with-token] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)\n logout [--hub <url>] delete the stored credential for a hub\n connect [--hub <url>] bind this project to a hub and verify the stored credential (whoami)\n push [<defName>...] [--force] [--dry-run] publish local workflow defs to the bound hub (server-diffed, idempotent)\n lint [<def-name>] check def(s) for wiring problems\n check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided]\n bounded reachability check (deadlocks, stuck, dead steps, declared invariants)\n create <def> [--title t] [--provide name=json ...] [--param k=v ...]\n provide <wf> <name> [--value json] supply an owed (seedOwed) input\n adopt <wf> re-pin an instance to the current def (\u00A728); settles new debts\n 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)\n reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)\n runs <wf> [--open] list this instance's runs (+ claim state for open ones)\n order <wf> <run> print the order packet issued at claim time (persisted in the claim txn)\n status <wf> derive debts / eligible / blocked\n status --all every instance's status in one call (fleet read)\n wait <wf> --until eligible|done [--timeout <dur>] block until engine state matches\n show <wf> dump raw artifacts\n trace <wf> [--format text] causal timeline + artifact biographies\n graph <def-or-wf> [--format dot|mermaid|json] wiring graph (+ live overlay if wf id)\n list list workflow instances\n green <wf> <run> <path> [--value json] [--terminal]\n emit <wf> <run> --items '[{...}]' accrete collection elements\n seal <wf> <run> [--value json] signal a collection is complete\n reject <wf> <path> --by <author> --text <msg>\n retract <wf> <path> --by <author> --text <msg>\n skip <wf> <path> --by <author> --text <msg>\n retry <wf> <path> [--by <author>] [--text <guidance>] clear a \u00A76 stall\n heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run\n close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]\n delete <wf> [--recursive] refuse if children exist unless --recursive (cascades)\n\nEnvironment: OWENLOOP_DB, OWENLOOP_DEFS";
85
+ export declare const USAGE = "owenloop \u2014 a dataflow workflow engine\n\nUsage: owenloop <command> [args] [--db <path>] [--defs <dir>]\n\nCommands:\n defs list available workflow definitions\n add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)\n add --recover finish or undo a crash-interrupted install (offline; no network)\n login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)\n logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot\n connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)\n push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)\n --as names the credential slot: human (default), agent, or agent:<account>\n agent new <name> [--pools <a,b>] [--hub <url>] mint a new agent identity on the hub and store its token in slot agent:<name> (the token is never printed)\n setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--pools <a,b>] converge this machine's install: human login, agent credential, owenwork settings, plugin (idempotent)\n doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)\n mcp [--hub <url>] serve the hub control plane over stdio MCP (spawned by MCP hosts, not run by humans)\n lint [<def-name>] check def(s) for wiring problems\n check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided] [--strict-inputs]\n bounded reachability check (stall states, true deadlocks, stuck, dead steps, declared invariants)\n create <def> [--title t] [--provide name=json ...] [--param k=v ...]\n provide <wf> <name> [--value json] supply an owed (seedOwed) input\n adopt <wf> re-pin an instance to the current def (\u00A728); settles new debts\n 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)\n reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)\n runs <wf> [--open] list this instance's runs (+ claim state for open ones)\n order <wf> <run> print the order packet issued at claim time (persisted in the claim txn)\n status <wf> derive debts / eligible / blocked\n status --all every instance's status in one call (fleet read)\n wait <wf> --until eligible|done [--timeout <dur>] block until engine state matches\n show <wf> dump raw artifacts\n trace <wf> [--format text] causal timeline + artifact biographies\n graph <def-or-wf> [--format dot|mermaid|json] wiring graph (+ live overlay if wf id)\n list list workflow instances\n green <wf> <run> <path> [--value json] [--terminal]\n emit <wf> <run> --items '[{...}]' accrete collection elements\n seal <wf> <run> [--value json] signal a collection is complete\n reject <wf> <path> --by <author> --text <msg>\n retract <wf> <path> --by <author> --text <msg>\n skip <wf> <path> --by <author> --text <msg>\n retry <wf> <path> [--by <author>] [--text <guidance>] clear a \u00A76 stall\n heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run\n close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]\n delete <wf> [--recursive] refuse if children exist unless --recursive (cascades)\n\nEnvironment: OWENLOOP_DB, OWENLOOP_DEFS";
62
86
  /**
63
87
  * Single source of truth for the `--options` each command accepts, consulted by
64
88
  * `preflight` before any side effect. Unknown-OPTION rejection AND
@@ -73,6 +97,27 @@ export declare const USAGE = "owenloop \u2014 a dataflow workflow engine\n\nUsag
73
97
  * `last/all/flag/needOpt/numOpt` call site.
74
98
  */
75
99
  export declare const COMMAND_OPTIONS: ReadonlyMap<string, ReadonlySet<string>>;
100
+ /**
101
+ * Coerce a raw string (a hostname) into a valid agent account name, or `''` when
102
+ * nothing usable survives. Lowercase; drop every character outside the account
103
+ * body class `[a-z0-9._-]`; strip leading non-alphanumerics (the account MUST
104
+ * start alphanumeric); clamp to 64 chars. A suggestion only — never parsed or
105
+ * matched (§2); the user may accept it or type any valid label.
106
+ */
107
+ export declare function sanitizeAgentName(raw: string): string;
108
+ /**
109
+ * The identity's last-active instant in epoch-ms: `max` of its two non-null
110
+ * timestamps (`lastUsedAt`, the rekey-surviving token-level max; `lastContactAt`,
111
+ * the identity-level any-protocol contact), or `null` when both are absent. Both
112
+ * recording paths are monotone, so `max` is the correct "most recent activity".
113
+ */
114
+ export declare function lastActiveMs(identity: AgentIdentitySummary): number | null;
115
+ /**
116
+ * Render an elapsed-time delta (ms) as a short relative string: `just now`,
117
+ * `<n>m ago`, `<n>h ago`, `<n>d ago`. A `null` delta (no recorded activity)
118
+ * renders `never`. Negative deltas (clock skew) clamp to `just now`.
119
+ */
120
+ export declare function formatLastActive(deltaMs: number | null): string;
76
121
  /**
77
122
  * Async entry point that adds network I/O for `add` and the hub commands on top
78
123
  * of the otherwise fully-synchronous engine/CLI (see the doc comment on