owenloop 0.5.8 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +4 -2
  3. package/dist/packages/work/src/agent/loop.d.ts +23 -8
  4. package/dist/packages/work/src/agent/loop.js +48 -6
  5. package/dist/packages/work/src/consumed-verifier.js +6 -17
  6. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  7. package/dist/packages/work/src/exec/loop.js +181 -32
  8. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  9. package/dist/packages/work/src/exec/receipt.js +6 -6
  10. package/dist/packages/work/src/harness/claude.js +100 -0
  11. package/dist/packages/work/src/hub/client.d.ts +19 -4
  12. package/dist/packages/work/src/hub/client.js +7 -3
  13. package/dist/packages/work/src/hub/types.d.ts +84 -0
  14. package/dist/packages/work/src/main.js +1 -0
  15. package/dist/packages/work/src/roles/agent-run.js +19 -22
  16. package/dist/packages/work/src/roles/exec.js +2 -0
  17. package/dist/packages/work/src/roles/settings.js +2 -0
  18. package/dist/packages/work/src/roles/shift.js +14 -2
  19. package/dist/packages/work/src/roles/util.d.ts +1 -0
  20. package/dist/packages/work/src/roles/util.js +10 -0
  21. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  22. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  23. package/dist/packages/work/src/settings/roster.d.ts +84 -0
  24. package/dist/packages/work/src/settings/roster.js +364 -5
  25. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  26. package/dist/packages/work/src/settings/serving.js +79 -0
  27. package/dist/packages/work/src/settings/settings.d.ts +14 -1
  28. package/dist/packages/work/src/settings/settings.js +14 -0
  29. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  30. package/dist/packages/work/src/shift/loop.js +299 -51
  31. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  32. package/dist/packages/work/src/shift/runtime.d.ts +15 -0
  33. package/dist/packages/work/src/shift/runtime.js +94 -4
  34. package/dist/packages/work/src/shift/server.js +2 -0
  35. package/dist/packages/work/src/shift/spawn.d.ts +17 -2
  36. package/dist/packages/work/src/shift/spawn.js +16 -13
  37. package/dist/packages/work/src/shift/state.d.ts +29 -2
  38. package/dist/packages/work/src/shift/state.js +45 -15
  39. package/dist/packages/work/src/usage.d.ts +1 -1
  40. package/dist/packages/work/src/usage.js +7 -1
  41. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  42. package/dist/packages/work/src/util/modifier-init.js +73 -0
  43. package/dist/src/bundle/tar.d.ts +9 -4
  44. package/dist/src/bundle/tar.js +9 -4
  45. package/dist/src/capabilities.d.ts +6 -0
  46. package/dist/src/cli.d.ts +14 -1
  47. package/dist/src/cli.js +687 -75
  48. package/dist/src/config-dir.d.ts +1 -1
  49. package/dist/src/config-dir.js +1 -1
  50. package/dist/src/crypto/index.d.ts +1 -1
  51. package/dist/src/crypto/index.js +1 -1
  52. package/dist/src/crypto/org-root.d.ts +30 -12
  53. package/dist/src/crypto/org-root.js +162 -14
  54. package/dist/src/crypto/records.d.ts +2 -0
  55. package/dist/src/crypto/records.js +2 -0
  56. package/dist/src/defs.d.ts +6 -1
  57. package/dist/src/defs.js +203 -8
  58. package/dist/src/engine.d.ts +42 -7
  59. package/dist/src/engine.js +158 -16
  60. package/dist/src/index.d.ts +4 -4
  61. package/dist/src/index.js +2 -2
  62. package/dist/src/mcp/serve.d.ts +22 -0
  63. package/dist/src/mcp/serve.js +88 -8
  64. package/dist/src/model.d.ts +2 -0
  65. package/dist/src/model.js +32 -25
  66. package/dist/src/order-resolver.d.ts +1 -0
  67. package/dist/src/order-resolver.js +8 -1
  68. package/dist/src/schemas/index.d.ts +11 -0
  69. package/dist/src/schemas/order.v1.schema.json +7 -1
  70. package/dist/src/store.d.ts +5 -0
  71. package/dist/src/store.js +43 -8
  72. package/dist/src/types.d.ts +40 -3
  73. package/docs/authoring.md +90 -2
  74. package/docs/bundles.md +26 -2
  75. package/docs/cli.md +170 -28
  76. package/docs/crypto.md +19 -3
  77. package/docs/design.md +70 -1
  78. package/docs/routing.md +189 -34
  79. package/docs/shift-logs.md +20 -9
  80. package/docs/wire-contracts.md +50 -7
  81. package/examples/workflows/delivery.yaml +31 -14
  82. package/examples/workflows/ship.yaml +10 -2
  83. package/package.json +1 -1
  84. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/claude-code/plugin/.mcp.json +1 -1
  86. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  87. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
@@ -1,4 +1,6 @@
1
1
  import { type ShiftEventBody } from './protocol.ts';
2
+ import { type Liveness, type Reconciliation } from './state.ts';
3
+ import { type AcquireFileLockOpts } from '../../../../src/lock.ts';
2
4
  import { installSignalHandlers, type SignalHost } from '../roles/signals.ts';
3
5
  export { installSignalHandlers, type SignalHost };
4
6
  /**
@@ -13,6 +15,8 @@ export declare function reachesSocketConsumer(type: ShiftEventBody['type']): boo
13
15
  export declare function resolveCap(flagCap: number | undefined, settingsCap: number | undefined): number;
14
16
  export declare function resolveStateDirOverride(flag: string | undefined, env: Record<string, string | undefined>, settingsStateDir: string | undefined): string | undefined;
15
17
  export declare function resolveMaxConcurrentAgents(flagMax: number | undefined, settingsMax: number | undefined): number;
18
+ export declare function resolveExecReserve(flagReserve: number | undefined, settingsReserve: number | undefined): number;
19
+ export declare function resolveLocalQueueHoldMs(flagHold: number | undefined, settingsHold: number | undefined): number;
16
20
  export declare function resolveShiftName(flagName: string | undefined, opts?: {
17
21
  shiftId?: string;
18
22
  hostname?: string;
@@ -29,6 +33,8 @@ export interface ParsedArgs {
29
33
  pollIntervalMs?: number;
30
34
  once?: boolean;
31
35
  maxAgents?: number;
36
+ execReserve?: number;
37
+ localQueueHoldMs?: number;
32
38
  cacheDir?: string;
33
39
  stateDir?: string;
34
40
  /** `--log-dir` — where `shift.log` and `<run>.log` are written. */
@@ -46,6 +52,15 @@ export interface ParsedArgs {
46
52
  }
47
53
  /** Parse shift's internal `--flag value` and `--flag=value` forms. */
48
54
  export declare function parseArgs(args: string[]): ParsedArgs;
55
+ /**
56
+ * Reconcile startup state under the same per-removal dispatch lock as the live
57
+ * loop. A busy neighbour is recoverable: the first poll-loop iteration retries
58
+ * shortly, whereas failing the entire Shift startup would strand its work.
59
+ */
60
+ export declare function reconcileStartupState(stateDir: string, report: (line: string) => void, options?: {
61
+ dispatchLockOptions?: Pick<AcquireFileLockOpts, 'beforeOpen'>;
62
+ isAlive?: Liveness;
63
+ }): Reconciliation | undefined;
49
64
  export interface ShiftRuntimeOptions {
50
65
  /** Build the Unix-socket shift daemon around the same loop instead of self-driving directly. */
51
66
  daemon?: boolean;
@@ -13,13 +13,16 @@ import { performance } from 'node:perf_hooks';
13
13
  import { createHubClient } from "../hub/client.js";
14
14
  import { resolveBearer } from "../credentials/resolve.js";
15
15
  import { loadSettings } from "../settings/settings.js";
16
+ import { DEFAULT_HUB_ROSTER_SYNC_TIMEOUT_MS, syncHubRosterCache, withHubRosterSyncTimeout } from "../settings/hub-roster-cache.js";
17
+ import { computeServeCapabilities } from "../settings/serving.js";
16
18
  import { resolveCacheDir } from "../bundle/cache.js";
17
- import { createShiftLoop } from "./loop.js";
19
+ import { createLockedRemovalCallbacks, createShiftLoop } from "./loop.js";
18
20
  import { createShiftLogSink } from "./logsink.js";
19
21
  import { prepareShiftLogDir, shiftLogFile } from "./logretention.js";
20
22
  import { stampShiftEvent } from "./protocol.js";
21
23
  import { createDefaultSpawner } from "./spawn.js";
22
24
  import { resolveStateDir, ensureStateDir, reconcileInFlight } from "./state.js";
25
+ import { FileLockTimeoutError } from "../../../../src/lock.js";
23
26
  import { reconcileActiveSessions, sessionsPath } from "../harness/session-store.js";
24
27
  import { resolveAllowedWorkdirRoots, resolveWorkRepo, resolveWorkRoot, } from "../agent/workdir.js";
25
28
  import { installSignalHandlers } from "../roles/signals.js";
@@ -31,7 +34,9 @@ export { installSignalHandlers };
31
34
  const DEFAULT_CAP = 3;
32
35
  const DEFAULT_POLL_MS = 5_000;
33
36
  const DEFAULT_MAX_AGENTS = 4;
37
+ const DEFAULT_EXEC_RESERVE = 1;
34
38
  const DEFAULT_PRESENCE_MS = 60_000;
39
+ const DEFAULT_ROSTER_SYNC_MS = 15 * 60_000;
35
40
  /**
36
41
  * Record types written to the LOG FILE but never delivered over the socket.
37
42
  *
@@ -108,6 +113,12 @@ export function resolveStateDirOverride(flag, env, settingsStateDir) {
108
113
  export function resolveMaxConcurrentAgents(flagMax, settingsMax) {
109
114
  return flagMax ?? settingsMax ?? DEFAULT_MAX_AGENTS;
110
115
  }
116
+ export function resolveExecReserve(flagReserve, settingsReserve) {
117
+ return flagReserve ?? settingsReserve ?? DEFAULT_EXEC_RESERVE;
118
+ }
119
+ export function resolveLocalQueueHoldMs(flagHold, settingsHold) {
120
+ return flagHold ?? settingsHold ?? 0;
121
+ }
111
122
  export function resolveShiftName(flagName, opts = {}) {
112
123
  if (flagName !== undefined && flagName !== '')
113
124
  return flagName;
@@ -148,6 +159,8 @@ export function parseArgs(args) {
148
159
  case '--serve-crews':
149
160
  case '--cap':
150
161
  case '--max-agents':
162
+ case '--exec-reserve':
163
+ case '--local-queue-hold':
151
164
  case '--workflow':
152
165
  case '--poll-interval':
153
166
  case '--cache-dir':
@@ -197,6 +210,18 @@ export function parseArgs(args) {
197
210
  return { error: n.error };
198
211
  parsed.maxAgents = n;
199
212
  }
213
+ else if (name === '--exec-reserve') {
214
+ const n = intFlag(r.value, '--exec-reserve');
215
+ if (typeof n !== 'number')
216
+ return { error: n.error };
217
+ parsed.execReserve = n;
218
+ }
219
+ else if (name === '--local-queue-hold') {
220
+ const n = intFlag(r.value, '--local-queue-hold');
221
+ if (typeof n !== 'number')
222
+ return { error: n.error };
223
+ parsed.localQueueHoldMs = n;
224
+ }
200
225
  else if (name === '--poll-interval') {
201
226
  const n = intFlag(r.value, '--poll-interval');
202
227
  if (typeof n !== 'number')
@@ -221,12 +246,35 @@ export function parseArgs(args) {
221
246
  function usage() {
222
247
  process.stderr.write('usage: owenloop work shift [--origin <url>] [--as <account>] [--name <n>] [--serve-crews a,b] [--cap <n>]\n' +
223
248
  ' [--workflow <id>] [--poll-interval <ms>] [--once]\n' +
224
- ' [--max-agents <n>] [--cache-dir <p>] [--state-dir <p>]\n' +
249
+ ' [--max-agents <n>] [--exec-reserve <n>] [--local-queue-hold <ms>] [--cache-dir <p>] [--state-dir <p>]\n' +
225
250
  ' [--log-dir <p>] [--log-max-age <ms>] [--work-root <dir>]...\n');
226
251
  }
227
252
  function errMsg(err) {
228
253
  return err instanceof Error ? err.message : String(err);
229
254
  }
255
+ /**
256
+ * Reconcile startup state under the same per-removal dispatch lock as the live
257
+ * loop. A busy neighbour is recoverable: the first poll-loop iteration retries
258
+ * shortly, whereas failing the entire Shift startup would strand its work.
259
+ */
260
+ export function reconcileStartupState(stateDir, report, options = {}) {
261
+ try {
262
+ return reconcileInFlight(stateDir, {
263
+ ...(options.isAlive === undefined ? {} : { isAlive: options.isAlive }),
264
+ ...createLockedRemovalCallbacks(stateDir, {
265
+ dispatchLockOptions: options.dispatchLockOptions,
266
+ waitMs: 1_000,
267
+ label: 'owenloop Shift startup reaper',
268
+ }),
269
+ });
270
+ }
271
+ catch (error) {
272
+ if (!(error instanceof FileLockTimeoutError))
273
+ throw error;
274
+ report(`startup dispatch-state reconciliation deferred: ${errMsg(error)} (the poll-loop reconciliation will retry)`);
275
+ return undefined;
276
+ }
277
+ }
230
278
  /** Public Shift daemon transport is a Unix-domain socket on macOS and Linux. */
231
279
  export function assertShiftDaemonPlatform(platform = process.platform) {
232
280
  if (platform === 'win32') {
@@ -306,7 +354,7 @@ export async function runShiftRuntime(parsed, options = {}) {
306
354
  // Reconcile the Shift's own dispatch records for capacity housekeeping. The
307
355
  // session sweep below must use the session row's PID and ownership fields,
308
356
  // not this run-id set, because every Shift on the machine shares the store.
309
- reconcileInFlight(stateDir);
357
+ reconcileStartupState(stateDir, (line) => process.stderr.write(`${roleLabel}: ${line}\n`));
310
358
  try {
311
359
  const retired = reconcileActiveSessions(sessionsPath(cacheDir), { shiftName: name, shiftOwner }, Date.now());
312
360
  for (const rec of retired) {
@@ -353,6 +401,8 @@ export async function runShiftRuntime(parsed, options = {}) {
353
401
  : undefined;
354
402
  const cap = resolveCap(parsed.cap, settings.dispatchCap);
355
403
  const maxConcurrentAgents = resolveMaxConcurrentAgents(parsed.maxAgents, settings.maxConcurrentAgents);
404
+ const execReserve = resolveExecReserve(parsed.execReserve, settings.execReserve);
405
+ const localQueueHoldMs = resolveLocalQueueHoldMs(parsed.localQueueHoldMs, settings.localQueueHoldMs);
356
406
  const workRoot = resolveWorkRoot(env, settings.workRoot, cacheDir);
357
407
  const workRepo = resolveWorkRepo(env, settings.workRepo);
358
408
  /**
@@ -447,6 +497,18 @@ export async function runShiftRuntime(parsed, options = {}) {
447
497
  process.stderr.write(`${roleLabel}: shift event sink failed: ${errMsg(err)} (continuing)\n`);
448
498
  }
449
499
  };
500
+ // The agent-run child must stay completely offline. Refresh before entering
501
+ // the park loop, but let an unavailable hub degrade to machine layers. The
502
+ // durable error is buffered until after `parked`: a parked shift's first log
503
+ // record is its self-describing identity, even when this refresh fails.
504
+ let startupRosterSyncFailure;
505
+ try {
506
+ await withHubRosterSyncTimeout((signal) => syncHubRosterCache({ client: hub, env, origin, account, signal }));
507
+ }
508
+ catch (error) {
509
+ startupRosterSyncFailure = `roster sync failed at shift start: ${errMsg(error)} (continuing)`;
510
+ process.stderr.write(`${roleLabel}: ${startupRosterSyncFailure}\n`);
511
+ }
450
512
  const reportWorkerFailure = (failure) => {
451
513
  // A worker failure is detected by the SPAWNER's `exit`/`error` listener, not
452
514
  // inside the loop's sweep, so it never passes through the loop's `emit()`.
@@ -471,13 +533,16 @@ export async function runShiftRuntime(parsed, options = {}) {
471
533
  // way forever is re-dispatched on a backoff instead of once per poll.
472
534
  loopRef.current?.noteWorkerFailure(failure);
473
535
  };
536
+ const reportWorkerExit = (exit) => {
537
+ loopRef.current?.noteChildExited(exit);
538
+ };
474
539
  const spawner = createDefaultSpawner(origin, account, undefined, shiftId, reportWorkerFailure,
475
540
  // `undefined` when the log directory could not be created, which is what
476
541
  // makes `buildSpawnPlan` emit no `logFile` and the worker launch with its
477
542
  // output discarded exactly as it did before this change.
478
543
  logDirReady
479
544
  ? { dir: logDir, err: (line) => process.stderr.write(`${line}\n`) }
480
- : undefined, allowedWorkdirRoots, parsed.serveCrews);
545
+ : undefined, allowedWorkdirRoots, reportWorkerExit);
481
546
  const pollIntervalMs = parsed.pollIntervalMs ?? DEFAULT_POLL_MS;
482
547
  const loop = createShiftLoop({
483
548
  hub,
@@ -501,7 +566,18 @@ export async function runShiftRuntime(parsed, options = {}) {
501
566
  resolveOrderStep,
502
567
  pollIntervalMs,
503
568
  presenceIntervalMs: DEFAULT_PRESENCE_MS,
569
+ rosterSyncIntervalMs: DEFAULT_ROSTER_SYNC_MS,
570
+ rosterSyncTimeoutMs: DEFAULT_HUB_ROSTER_SYNC_TIMEOUT_MS,
571
+ syncRosters: (signal) => syncHubRosterCache({ client: hub, env, origin, account, signal }),
572
+ computeServeCapabilities: (crews) => computeServeCapabilities({
573
+ env,
574
+ crews,
575
+ hub: { origin, account },
576
+ warn: (message) => process.stderr.write(`${roleLabel}: shift: ${message}\n`),
577
+ }),
504
578
  maxConcurrentAgents,
579
+ execReserve,
580
+ localQueueHoldMs,
505
581
  workRoot,
506
582
  ...(workRepo !== undefined ? { workRepo } : {}),
507
583
  shiftId,
@@ -542,6 +618,12 @@ export async function runShiftRuntime(parsed, options = {}) {
542
618
  cwd: process.cwd(),
543
619
  }));
544
620
  };
621
+ const emitStartupRosterSyncFailure = () => {
622
+ if (startupRosterSyncFailure === undefined)
623
+ return;
624
+ consumeEvent(stamp({ type: 'hub-error', op: 'roster_sync', message: startupRosterSyncFailure }));
625
+ startupRosterSyncFailure = undefined;
626
+ };
545
627
  if (daemonMode) {
546
628
  daemon = createShiftDaemon({
547
629
  socketPath: options.socketPath ?? join(stateDir, 'shift.sock'),
@@ -567,6 +649,10 @@ export async function runShiftRuntime(parsed, options = {}) {
567
649
  if (parsed.once !== true) {
568
650
  process.stdout.write(`owenloop shift: parked as '${name}' @ ${origin} (cap ${cap})\n`);
569
651
  emitParked();
652
+ emitStartupRosterSyncFailure();
653
+ }
654
+ else {
655
+ emitStartupRosterSyncFailure();
570
656
  }
571
657
  return daemon.run();
572
658
  }
@@ -574,6 +660,10 @@ export async function runShiftRuntime(parsed, options = {}) {
574
660
  if (parsed.once !== true) {
575
661
  process.stdout.write(`owenloop work shift: parked as '${name}' @ ${origin} (cap ${cap})\n`);
576
662
  emitParked();
663
+ emitStartupRosterSyncFailure();
664
+ }
665
+ else {
666
+ emitStartupRosterSyncFailure();
577
667
  }
578
668
  return loop.run();
579
669
  }
@@ -287,6 +287,7 @@ export function createShiftDaemon(opts) {
287
287
  name: shift.name,
288
288
  serve_crews: shift.serveCrews,
289
289
  ...capacity(),
290
+ agent_ceiling: opts.loop.agentCeiling(),
290
291
  attended_at: opts.loop.getAttendedAt() ?? null,
291
292
  started_at: opts.startedAt,
292
293
  };
@@ -430,6 +431,7 @@ export function createShiftDaemon(opts) {
430
431
  await opts.hub.presencePing({
431
432
  name: shift.name,
432
433
  serve_crews: shift.serveCrews,
434
+ serve_capabilities: opts.loop.getServeCapabilities(),
433
435
  ...(opts.shiftId !== undefined ? { shift_id: opts.shiftId } : {}),
434
436
  started_at: opts.startedAt,
435
437
  // Deliberately omit attended_at. The merged hub contract interprets
@@ -68,6 +68,21 @@ export interface WorkerFailure {
68
68
  message: string;
69
69
  }
70
70
  export type WorkerFailureReporter = (failure: WorkerFailure) => void;
71
+ /**
72
+ * A dispatched worker process ENDED. Fired for every terminal outcome —
73
+ * a clean exit (including an agent-run that completed mid-turn and exited 0),
74
+ * a nonzero exit, a signal kill, and a failure to spawn. The shift frees the
75
+ * dispatch slot from this, so it must never be conditional on the exit code.
76
+ */
77
+ export interface WorkerExit {
78
+ workflow: string;
79
+ run: string;
80
+ kind: 'exec' | 'agent-run';
81
+ pid: number;
82
+ exitStatus: number | null;
83
+ signal: NodeJS.Signals | null;
84
+ }
85
+ export type WorkerExitReporter = (exit: WorkerExit) => void;
71
86
  /**
72
87
  * The stdio topology of a detached worker.
73
88
  *
@@ -137,7 +152,7 @@ export interface SpawnPlan {
137
152
  * is pure, and `createDefaultSpawner` substitutes the descriptors. Omitted ⇒ no
138
153
  * `logFile` key at all, and the plan is byte-identical to the pre-logging shape.
139
154
  */
140
- export declare function buildSpawnPlan(spec: SpawnSpec, origin: string, account: string, binPath: string, execPath?: string, shiftId?: string, logDir?: string, allowedWorkdirRoots?: string[], serveCrews?: string[]): SpawnPlan;
155
+ export declare function buildSpawnPlan(spec: SpawnSpec, origin: string, account: string, binPath: string, execPath?: string, shiftId?: string, logDir?: string, allowedWorkdirRoots?: string[]): SpawnPlan;
141
156
  /**
142
157
  * The default detached spawner. Captures the resolved hub `origin`, the
143
158
  * resolved `account`, the packaged bin path, and the dispatching Shift's
@@ -146,4 +161,4 @@ export declare function buildSpawnPlan(spec: SpawnSpec, origin: string, account:
146
161
  * relying on `buildSpawnPlan`'s default) so `shiftId` — trailing after it
147
162
  * — can be supplied positionally.
148
163
  */
149
- export declare function createDefaultSpawner(origin: string, account: string, binPath?: string, shiftId?: string, onFailure?: WorkerFailureReporter, logging?: WorkerLogOptions, allowedWorkdirRoots?: string[], serveCrews?: string[]): Spawner;
164
+ export declare function createDefaultSpawner(origin: string, account: string, binPath?: string, shiftId?: string, onFailure?: WorkerFailureReporter, logging?: WorkerLogOptions, allowedWorkdirRoots?: string[], onExit?: WorkerExitReporter): Spawner;
@@ -107,13 +107,9 @@ function err(e) {
107
107
  * is pure, and `createDefaultSpawner` substitutes the descriptors. Omitted ⇒ no
108
108
  * `logFile` key at all, and the plan is byte-identical to the pre-logging shape.
109
109
  */
110
- export function buildSpawnPlan(spec, origin, account, binPath, execPath = process.execPath, shiftId, logDir, allowedWorkdirRoots, serveCrews) {
110
+ export function buildSpawnPlan(spec, origin, account, binPath, execPath = process.execPath, shiftId, logDir, allowedWorkdirRoots) {
111
111
  const role = spec.kind === 'agent-run' ? 'agent-run' : 'exec';
112
- // `OWENLOOP_SERVE_CREWS` is Shift-owned routing plumbing, never ambient
113
- // configuration. A child for --all must not inherit a stale named-crew list
114
- // from the Shift process that launched it.
115
112
  const env = { ...process.env };
116
- delete env['OWENLOOP_SERVE_CREWS'];
117
113
  env['OWENLOOP_ACCOUNT'] = account;
118
114
  if (spec.startGate !== undefined)
119
115
  env['OWENLOOP_START_GATE'] = spec.startGate;
@@ -124,11 +120,6 @@ export function buildSpawnPlan(spec, origin, account, binPath, execPath = proces
124
120
  if (allowedWorkdirRoots !== undefined && allowedWorkdirRoots.length > 0) {
125
121
  env['OWENLOOP_ALLOWED_WORKDIR_ROOTS'] = allowedWorkdirRoots.join(':');
126
122
  }
127
- // Shift-internal roster handoff only. It is deliberately not passed to the
128
- // harness child and is absent for command workers.
129
- if (role === 'agent-run' && serveCrews !== undefined && serveCrews.length > 0) {
130
- env['OWENLOOP_SERVE_CREWS'] = serveCrews.join(',');
131
- }
132
123
  return {
133
124
  command: execPath,
134
125
  args: [
@@ -156,7 +147,7 @@ export function buildSpawnPlan(spec, origin, account, binPath, execPath = proces
156
147
  * relying on `buildSpawnPlan`'s default) so `shiftId` — trailing after it
157
148
  * — can be supplied positionally.
158
149
  */
159
- export function createDefaultSpawner(origin, account, binPath = resolveOwenloopBin(), shiftId, onFailure, logging, allowedWorkdirRoots, serveCrews) {
150
+ export function createDefaultSpawner(origin, account, binPath = resolveOwenloopBin(), shiftId, onFailure, logging, allowedWorkdirRoots, onExit) {
160
151
  // ONE report per shift, not one per dispatch. Every condition that stops a
161
152
  // worker log from opening — a full disk, a read-only log directory, an
162
153
  // operator deleting it underneath a running shift — PERSISTS across the
@@ -172,7 +163,7 @@ export function createDefaultSpawner(origin, account, binPath = resolveOwenloopB
172
163
  logging?.err?.(line);
173
164
  };
174
165
  return (spec) => {
175
- const plan = buildSpawnPlan(spec, origin, account, binPath, process.execPath, shiftId, logging?.dir, allowedWorkdirRoots, serveCrews);
166
+ const plan = buildSpawnPlan(spec, origin, account, binPath, process.execPath, shiftId, logging?.dir, allowedWorkdirRoots);
176
167
  // Open the log ONCE and hand the SAME descriptor to slots 1 and 2. Opening
177
168
  // it twice would create two independent file offsets, and the two streams
178
169
  // would overwrite each other's bytes — silent corruption no unit test on the
@@ -226,6 +217,7 @@ export function createDefaultSpawner(origin, account, binPath = resolveOwenloopB
226
217
  // discard them before an operator can read them — reading them is the whole
227
218
  // point of `<run>.log`.
228
219
  let failureReported = false;
220
+ let exitReported = false;
229
221
  const report = (exitStatus, signal, message) => {
230
222
  if (failureReported || onFailure === undefined)
231
223
  return;
@@ -241,8 +233,18 @@ export function createDefaultSpawner(origin, account, binPath = resolveOwenloopB
241
233
  message,
242
234
  });
243
235
  };
244
- child.once('error', () => report(null, null, 'worker process failed to start'));
236
+ const reportExit = (exitStatus, signal) => {
237
+ if (exitReported || onExit === undefined || child.pid === undefined)
238
+ return;
239
+ exitReported = true;
240
+ onExit({ workflow: spec.workflow, run: spec.run, kind, pid: child.pid, exitStatus, signal });
241
+ };
242
+ child.once('error', () => {
243
+ report(null, null, 'worker process failed to start');
244
+ reportExit(null, null);
245
+ });
245
246
  child.once('exit', (code, signal) => {
247
+ reportExit(code, signal);
246
248
  if (code === 0)
247
249
  return;
248
250
  report(code, signal, 'worker exited without completing successfully');
@@ -261,6 +263,7 @@ export function createDefaultSpawner(origin, account, binPath = resolveOwenloopB
261
263
  // registered above fires afterwards and emits a SECOND `failed` event —
262
264
  // two daemon events for one dispatch attempt.
263
265
  failureReported = true;
266
+ exitReported = true;
264
267
  throw new Error(`spawn of 'owenloop work ${kind} ${spec.workflow}/${spec.run}' returned no pid`);
265
268
  }
266
269
  const kill = () => {
@@ -74,13 +74,15 @@ export declare function finalizeChildReservation(stateDir: string, reservation:
74
74
  /** Open a child's gate only after the PID-bearing record is durable. */
75
75
  export declare function startReservedChild(stateDir: string, record: ChildRecord): void;
76
76
  /** Cancel a gated child and remove the matching reservation/record. */
77
- export declare function cancelReservedChild(stateDir: string, reservation: ChildReservation): void;
77
+ export declare function cancelReservedChild(stateDir: string, reservation: ChildReservation): boolean;
78
78
  /**
79
79
  * Delete one run's in-flight state. A still-gated reservation or finalized child
80
80
  * is cancelled first so an external run-ended signal cannot leave a worker gate
81
81
  * behind that later opens without a capacity record.
82
82
  */
83
- export declare function removeChildRecord(stateDir: string, run: string): void;
83
+ export declare function removeChildRecord(stateDir: string, run: string, options?: {
84
+ pid?: number;
85
+ }): boolean;
84
86
  export type Liveness = (pid: number) => boolean;
85
87
  export declare const defaultIsAlive: Liveness;
86
88
  export interface Reconciliation {
@@ -93,7 +95,32 @@ export interface ReconcileOptions {
93
95
  isAlive?: Liveness;
94
96
  now?: number;
95
97
  reservationMaxAgeMs?: number;
98
+ /**
99
+ * Called before a stale reservation is removed. The Shift loop uses this to
100
+ * share its dispatch lock with reservation creation; standalone state callers
101
+ * intentionally retain the direct removal default.
102
+ */
103
+ removeAbandonedReservation?: (reservation: ChildReservation) => boolean;
104
+ /**
105
+ * Called before a dead child record is removed. The Shift loop uses this to
106
+ * serialize the read/guard/unlink sequence with a later re-dispatch.
107
+ */
108
+ removeDeadChild?: (record: ChildRecord) => boolean;
109
+ /**
110
+ * Finish a persisted PID record's start-gate handoff. The Shift daemon uses
111
+ * this to serialize the re-read/identity-check/write sequence with a later
112
+ * re-dispatch; standalone state callers intentionally retain the direct
113
+ * settlement default.
114
+ */
115
+ settleLiveChild?: (record: ChildRecord) => ChildRecord | undefined;
96
116
  }
117
+ /**
118
+ * Open and clear a persisted child's start gate only if the record is still
119
+ * the same PID and gate-token pair the reconciler observed. A re-dispatch can
120
+ * replace either identity between an unlocked observation and this settlement;
121
+ * in that case it owns the record and nothing is changed.
122
+ */
123
+ export declare function settleChildGate(stateDir: string, record: ChildRecord): ChildRecord | undefined;
97
124
  /**
98
125
  * Reconcile live children and durable reservations. Fresh reservations count as
99
126
  * occupied capacity. An expired reservation is cancelled before its record is
@@ -297,6 +297,7 @@ export function startReservedChild(stateDir, record) {
297
297
  /** Cancel a gated child and remove the matching reservation/record. */
298
298
  export function cancelReservedChild(stateDir, reservation) {
299
299
  const path = gateFile(stateDir, reservation.token);
300
+ let removed = false;
300
301
  try {
301
302
  signalGate(path, 'cancel', true);
302
303
  }
@@ -309,22 +310,29 @@ export function cancelReservedChild(stateDir, reservation) {
309
310
  const matchesFinalized = current !== undefined &&
310
311
  !isReservation(current) &&
311
312
  current.gateToken === reservation.token;
312
- if (matchesReservation || matchesFinalized)
313
+ if (matchesReservation || matchesFinalized) {
313
314
  durableRemove(recordFile(stateDir, reservation.run));
315
+ removed = true;
316
+ }
314
317
  }
318
+ return removed;
315
319
  }
316
320
  /**
317
321
  * Delete one run's in-flight state. A still-gated reservation or finalized child
318
322
  * is cancelled first so an external run-ended signal cannot leave a worker gate
319
323
  * behind that later opens without a capacity record.
320
324
  */
321
- export function removeChildRecord(stateDir, run) {
325
+ export function removeChildRecord(stateDir, run, options) {
322
326
  const path = recordFile(stateDir, run);
323
327
  const current = readOneStateRecord(path);
324
- if (current !== undefined && isReservation(current)) {
325
- cancelReservedChild(stateDir, current);
326
- return;
327
- }
328
+ if (current === undefined)
329
+ return false;
330
+ // A late exit report must never remove a record written by a re-dispatch of
331
+ // the same run. Reservations have no pid, so they are likewise newer owners.
332
+ if (options?.pid !== undefined && (isReservation(current) || current.pid !== options.pid))
333
+ return false;
334
+ if (current !== undefined && isReservation(current))
335
+ return cancelReservedChild(stateDir, current);
328
336
  if (current?.gateToken !== undefined) {
329
337
  const gatePath = gateFile(stateDir, current.gateToken);
330
338
  try {
@@ -335,6 +343,7 @@ export function removeChildRecord(stateDir, run) {
335
343
  }
336
344
  }
337
345
  durableRemove(path);
346
+ return true;
338
347
  }
339
348
  export const defaultIsAlive = (pid) => {
340
349
  if (!Number.isInteger(pid) || pid <= 0)
@@ -347,6 +356,27 @@ export const defaultIsAlive = (pid) => {
347
356
  return error.code !== 'ESRCH';
348
357
  }
349
358
  };
359
+ /**
360
+ * Open and clear a persisted child's start gate only if the record is still
361
+ * the same PID and gate-token pair the reconciler observed. A re-dispatch can
362
+ * replace either identity between an unlocked observation and this settlement;
363
+ * in that case it owns the record and nothing is changed.
364
+ */
365
+ export function settleChildGate(stateDir, record) {
366
+ if (record.gateToken === undefined)
367
+ return record;
368
+ const current = readOneStateRecord(recordFile(stateDir, record.run));
369
+ if (current === undefined ||
370
+ isReservation(current) ||
371
+ current.pid !== record.pid ||
372
+ current.gateToken !== record.gateToken)
373
+ return undefined;
374
+ signalGate(gateFile(stateDir, current.gateToken), 'start', true);
375
+ const settled = { ...current };
376
+ delete settled.gateToken;
377
+ writeStateRecord(stateDir, settled);
378
+ return settled;
379
+ }
350
380
  /**
351
381
  * Reconcile live children and durable reservations. Fresh reservations count as
352
382
  * occupied capacity. An expired reservation is cancelled before its record is
@@ -377,23 +407,23 @@ export function reconcileInFlight(stateDir, arg) {
377
407
  reserved.push(record);
378
408
  continue;
379
409
  }
380
- cancelReservedChild(stateDir, record);
381
- abandoned.push(record);
410
+ const removed = options.removeAbandonedReservation?.(record) ?? cancelReservedChild(stateDir, record);
411
+ if (removed)
412
+ abandoned.push(record);
382
413
  continue;
383
414
  }
384
415
  if (!isAlive(record.pid)) {
385
- removeChildRecord(stateDir, record.run);
386
- reaped.push(record);
416
+ const removed = options.removeDeadChild?.(record) ?? removeChildRecord(stateDir, record.run, { pid: record.pid });
417
+ if (removed)
418
+ reaped.push(record);
387
419
  continue;
388
420
  }
389
421
  if (record.gateToken !== undefined) {
390
422
  // A restart after PID persistence but before the parent opened the gate can
391
423
  // safely finish the handoff: the durable PID record is the prerequisite.
392
- signalGate(gateFile(stateDir, record.gateToken), 'start', true);
393
- const settled = { ...record };
394
- delete settled.gateToken;
395
- writeStateRecord(stateDir, settled);
396
- live.push(settled);
424
+ const settled = options.settleLiveChild === undefined ? settleChildGate(stateDir, record) : options.settleLiveChild(record);
425
+ if (settled !== undefined)
426
+ live.push(settled);
397
427
  }
398
428
  else {
399
429
  live.push(record);
@@ -3,4 +3,4 @@
3
3
  * exit 0) and on a dispatch error (to stderr, exit 2). Keeping it in one place
4
4
  * means the help output and the error output never drift apart.
5
5
  */
6
- export declare const USAGE = "owenloop work \u2014 execution-side CLI companion to owenloop\n\nUsage:\n owenloop work hold --order <id> [options] hold an order with a heartbeating lease\n owenloop work exec <order-id> [options] run a command order in a self-leasing loop\n owenloop work agent-run <order-id> [options] host an agent order's step agent in a\n harness, in a self-leasing loop\n owenloop work prepare <workflow> [--origin <url>]\n fetch, cache & normalize step specs\n owenloop work lint <workflow-name | path> lint x.harness option bags in a def\n owenloop work sessions [--all] [--json] list this machine's recorded harness\n sessions and how to re-open them\n owenloop work approvals [--json] every tool call a worker is blocked on\n RIGHT NOW, waiting for a person\n owenloop work approvals approve|deny <wf>/<run> <tool-use-id> [--note <text>]\n answer one; the answer goes back to the\n still-blocked call, not to a later attempt\n owenloop work release --session <id> [options] drain a session's held claims\n owenloop work settings print the resolved settings file\n owenloop work join <code> [--hub <origin>] [--as <account>]\n redeem a join code and store the Scoped\n Identity credential (one-time provisioning)\n\nOptions:\n -h, --help show this help and exit 0\n --version print the owenloop work version and exit 0\n\n root shift options (run as owenloop shift start <crew...> | --all):\n <crew...> serve only these crews (positional, space\n separated); or --all for every crew on the key\n --all serve every crew on the key\n --origin <url> hub origin (else settings.hubOrigin)\n --as <account> Scoped Identity credential account to read + hand\n to dispatched holds/execs (default 'default')\n --name <n> Shift name (default <hostname>/<cwd>)\n --cap <n> max in-flight exec children (default 3)\n --poll-interval <ms> wake poll cadence (default 5000)\n --once bootstrap wake + one sweep, then exit (demo/e2e)\n --max-agents <n> max in-flight agent-run children, separate from\n --cap (default 4; else settings.maxConcurrentAgents)\n --cache-dir/--state-dir <p> override the resolved dirs\n\n hold options:\n --order <workflow>/<run> the order to hold (or --order <run> --workflow)\n --workflow <wf> required when --order is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --as <account> Scoped Identity credential account (default\n 'default'; the shift stamps this into born-bound\n holds)\n --session <id> session-holder tag (else env OWENLOOP_SESSION;\n else an anon:<hostname>:<pid> fallback \u2014 a\n holder is always sent)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n --ignore-stdin don't final-breath on stdin EOF (detached use)\n --never-release another process holds the claim; stop without\n releasing it (agent-run spawns its --mcp child\n this way \u2014 see hold.ts HOLDER OF RECORD)\n --mcp run as a stdio-MCP work-holder: tools get_order /\n submit, lease kept warm underneath (mutually\n exclusive with --ignore-stdin \u2014 stdin is the\n transport)\n\n exec options (usually spawned by shift, not run by hand):\n <workflow>/<run> the command order to run (positional order-id;\n or a bare <run> plus --workflow <wf>)\n --workflow <wf> required when the order-id is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n\n agent-run options (spawned by the shift, not run by hand):\n <workflow>/<run> the agent order to host (positional order-id;\n or a bare <run> plus --workflow <wf>)\n --workflow <wf> required when the order-id is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --harness <id> which registered harness hosts the step agent\n (below a selected roster candidate; else the\n step def's 'harness' field, then the first\n registered one)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n --submit-grace <ms> after the turn ends, how long to keep asking the\n hub whether the agent's submit landed (default\n 15000). Task completion comes from the HUB, never\n from the harness stream.\n --confirm-interval <ms> poll cadence inside that grace (default 1000)\n\n release options:\n --session <id> session whose claims to drain (else env\n OWENLOOP_SESSION). Agent-held claims re-offer;\n exec-held claims are drain-exempt (B3).\n --origin <url> hub origin (else settings.hubOrigin)\n\n settings (no options in v1):\n prints the resolved settings file path, whether it exists, each known\n knob (hubOrigin, cacheDir, stateDir, dispatchCap, commandRouting,\n maxConcurrentAgents, workRoot, workRepo) with its value + provenance,\n and any unrecognized keys.\n settings.dispatchCap/stateDir are the lowest-precedence\n fallbacks for shift's --cap/--state-dir. NO secrets ever\n live in settings \u2014 credentials stay in owenloop's own store.\n\n sessions options:\n --all include 'dead' sessions (hidden by default \u2014\n a dead session can no longer be resumed)\n --json print the raw newest-per-step records, tokens\n included, instead of the table\n --cache-dir <p> override the resolved cache dir\n\n join options:\n --hub <origin> hub to redeem against (else settings.hubOrigin;\n one of the two is REQUIRED \u2014 the code never\n chooses the hub)\n --as <account> credential account to store under (default:\n the Scoped Identity name the hub returns)\n\n shift/hold/exec/prepare/release env:\n credentials come from owenloop's store \u2014 each role reads the\n agent:<account> slot for its origin (never the human slot); a\n missing slot refuses with a runnable 'owenloop login' command.\n OWENLOOP_ACCOUNT Scoped Identity account for exec/prepare/release\n (default 'default'; shift uses --as, and\n stamps it onto dispatched holds/execs)\n OWENLOOP_TOKEN dev-only bearer override \u2014 when set, used\n verbatim and the store + account are\n bypassed (NOT the primary path)\n OWENLOOP_CACHE_DIR cache root\n OWENLOOP_STATE_DIR shift in-flight state dir\n OWENLOOP_SHIFT_LOG_DIR dir for the shift's shift.log and each\n worker's <run>.log; below --log-dir, above\n settings.shiftLogDir, default the state dir\n OWENLOOP_SHIFT_LOG_MAX_AGE_MS\n how long a worker's <run>.log is kept, in ms;\n below --log-max-age, above\n settings.shiftLogMaxAgeMs, default 14 days.\n Worker logs only \u2014 shift.log is never reaped\n OWENLOOP_SESSION hold session-holder tag / release drain target\n OWENLOOP_SHIFT_ID dispatching Shift's self-declared id for\n hold/exec/agent-run's --shift (advisory\n only, never for auth/routing/dispatch)\n OWENLOOP_WORK_ROOT root for per-RUN agent work dirs\n (<workRoot>/<workflow>/<run>); above\n settings.workRoot, default <cacheDir>/work.\n A hub-supplied OrderPacket.workdir still\n wins, and is never reaped.\n OWENLOOP_WORK_REPO local git repo to cut per-run work dirs from\n as worktrees instead of plain dirs; above\n settings.workRepo, default off\n\n Credentials / accounts:\n owenloop work's RUNTIME roles (shift/hold/exec/prepare/release) are READ-ONLY\n over owenloop's credential store \u2014 they never write credentials. Each\n role reads the agent:<account> slot for its origin (never the human\n slot); the account defaults to 'default'. 'owenloop work join' is the one\n deliberate provisioning-time writer: it stores the Scoped Identity token a hub\n redeem returns via owenloop's public storeCredential, once, at join time\n \u2014 not a runtime write.\n store / connect an account (run owenloop; owenloop work never writes it):\n owenloop login --hub <origin> --as agent:<account>\n (use --as agent for the default account)\n or provision a fresh box from a hub-issued join code:\n owenloop work join <code> --hub <origin>\n select an account at run time:\n --as <account> on shift / hold\n OWENLOOP_ACCOUNT on exec / prepare / release\n (shift resolves once and threads both channels)\n owenloop work does NOT list stored accounts \u2014 enumerating an origin's accounts\n is an owenloop-side capability; check owenloop for which slots are stored.\n\nExit codes:\n 0 success / help / version / lint clean or warnings-only\n 1 runtime failure (fetch/hub error, cache write) / lint found an error\n 2 usage error (unknown or missing role, missing required arg)\n 3 role not implemented yet (skeleton stub \u2014 lands in a later delivery)\n";
6
+ export declare const USAGE = "owenloop work \u2014 execution-side CLI companion to owenloop\n\nUsage:\n owenloop work hold --order <id> [options] hold an order with a heartbeating lease\n owenloop work exec <order-id> [options] run a command order in a self-leasing loop\n owenloop work agent-run <order-id> [options] host an agent order's step agent in a\n harness, in a self-leasing loop\n owenloop work prepare <workflow> [--origin <url>]\n fetch, cache & normalize step specs\n owenloop work lint <workflow-name | path> lint x.harness option bags in a def\n owenloop work sessions [--all] [--json] list this machine's recorded harness\n sessions and how to re-open them\n owenloop work approvals [--json] every tool call a worker is blocked on\n RIGHT NOW, waiting for a person\n owenloop work approvals approve|deny <wf>/<run> <tool-use-id> [--note <text>]\n answer one; the answer goes back to the\n still-blocked call, not to a later attempt\n owenloop work release --session <id> [options] drain a session's held claims\n owenloop work settings print the resolved settings file\n owenloop work join <code> [--hub <origin>] [--as <account>]\n redeem a join code and store the Scoped\n Identity credential (one-time provisioning)\n\nOptions:\n -h, --help show this help and exit 0\n --version print the owenloop work version and exit 0\n\n root shift options (run as owenloop shift start <crew...> | --all):\n <crew...> serve only these crews (positional, space\n separated); or --all for every crew on the key\n --all serve every crew on the key\n --origin <url> hub origin (else settings.hubOrigin)\n --as <account> Scoped Identity credential account to read + hand\n to dispatched holds/execs (default 'default')\n --name <n> Shift name (default <hostname>/<cwd>)\n --cap <n> max in-flight exec children (default 3)\n --poll-interval <ms> wake poll cadence (default 5000)\n --once bootstrap wake + one sweep, then exit (demo/e2e)\n --max-agents <n> max in-flight agent-run children, separate from\n --cap (default 4; else settings.maxConcurrentAgents)\n\t\t--exec-reserve <n> slots inside --cap that agent-run children may\n\t\t\t\t\tnot occupy, so exec orders always have room\n\t\t\t\t\t(default 1; else settings.execReserve; 0 disables)\n --local-queue-hold <ms> retain an undispatchable claim locally before\n\t\t\t\t\treturning it to the hub (default 0; else\n\t\t\t\t\tsettings.localQueueHoldMs; capped at 90000)\n --cache-dir/--state-dir <p> override the resolved dirs\n\n hold options:\n --order <workflow>/<run> the order to hold (or --order <run> --workflow)\n --workflow <wf> required when --order is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --as <account> Scoped Identity credential account (default\n 'default'; the shift stamps this into born-bound\n holds)\n --session <id> session-holder tag (else env OWENLOOP_SESSION;\n else an anon:<hostname>:<pid> fallback \u2014 a\n holder is always sent)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n --ignore-stdin don't final-breath on stdin EOF (detached use)\n --never-release another process holds the claim; stop without\n releasing it (agent-run spawns its --mcp child\n this way \u2014 see hold.ts HOLDER OF RECORD)\n --mcp run as a stdio-MCP work-holder: tools get_order /\n submit, lease kept warm underneath (mutually\n exclusive with --ignore-stdin \u2014 stdin is the\n transport)\n\n exec options (usually spawned by shift, not run by hand):\n <workflow>/<run> the command order to run (positional order-id;\n or a bare <run> plus --workflow <wf>)\n --workflow <wf> required when the order-id is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n\n agent-run options (spawned by the shift, not run by hand):\n <workflow>/<run> the agent order to host (positional order-id;\n or a bare <run> plus --workflow <wf>)\n --workflow <wf> required when the order-id is a bare run id\n --origin <url> hub origin (else settings.hubOrigin)\n --harness <id> which registered harness hosts the step agent\n (below a selected roster candidate; else the\n step def's 'harness' field, then the first\n registered one)\n --shift <id> dispatching Shift's self-declared id (else\n env OWENLOOP_SHIFT_ID); advisory only\n --heartbeat-interval <ms> lease renew cadence (default 60000)\n --jump-tolerance <ms> wall-gap slack before a tick is treated as a\n clock jump / laptop sleep (default 30000)\n --submit-grace <ms> after the turn ends, how long to keep asking the\n hub whether the agent's submit landed (default\n 15000). Task completion comes from the HUB, never\n from the harness stream.\n --confirm-interval <ms> poll cadence inside that grace (default 1000)\n\n release options:\n --session <id> session whose claims to drain (else env\n OWENLOOP_SESSION). Agent-held claims re-offer;\n exec-held claims are drain-exempt (B3).\n --origin <url> hub origin (else settings.hubOrigin)\n\n settings (no options in v1):\n prints the resolved settings file path, whether it exists, each known\n knob (hubOrigin, cacheDir, stateDir, dispatchCap, commandRouting,\n maxConcurrentAgents, execReserve, localQueueHoldMs, workRoot, workRepo) with its value + provenance,\n and any unrecognized keys.\n settings.dispatchCap/stateDir are the lowest-precedence\n fallbacks for shift's --cap/--state-dir. NO secrets ever\n live in settings \u2014 credentials stay in owenloop's own store.\n\n sessions options:\n --all include 'dead' sessions (hidden by default \u2014\n a dead session can no longer be resumed)\n --json print the raw newest-per-step records, tokens\n included, instead of the table\n --cache-dir <p> override the resolved cache dir\n\n join options:\n --hub <origin> hub to redeem against (else settings.hubOrigin;\n one of the two is REQUIRED \u2014 the code never\n chooses the hub)\n --as <account> credential account to store under (default:\n the Scoped Identity name the hub returns)\n\n shift/hold/exec/prepare/release env:\n credentials come from owenloop's store \u2014 each role reads the\n agent:<account> slot for its origin (never the human slot); a\n missing slot refuses with a runnable 'owenloop login' command.\n OWENLOOP_ACCOUNT Scoped Identity account for exec/prepare/release\n (default 'default'; shift uses --as, and\n stamps it onto dispatched holds/execs)\n OWENLOOP_TOKEN dev-only bearer override \u2014 when set, used\n verbatim and the store + account are\n bypassed (NOT the primary path)\n OWENLOOP_CACHE_DIR cache root\n OWENLOOP_STATE_DIR shift in-flight state dir\n OWENLOOP_SHIFT_LOG_DIR dir for the shift's shift.log and each\n worker's <run>.log; below --log-dir, above\n settings.shiftLogDir, default the state dir\n OWENLOOP_SHIFT_LOG_MAX_AGE_MS\n how long a worker's <run>.log is kept, in ms;\n below --log-max-age, above\n settings.shiftLogMaxAgeMs, default 14 days.\n Worker logs only \u2014 shift.log is never reaped\n OWENLOOP_SESSION hold session-holder tag / release drain target\n OWENLOOP_SHIFT_ID dispatching Shift's self-declared id for\n hold/exec/agent-run's --shift (advisory\n only, never for auth/routing/dispatch)\n OWENLOOP_WORK_ROOT root for per-RUN agent work dirs\n (<workRoot>/<workflow>/<run>); above\n settings.workRoot, default <cacheDir>/work.\n A hub-supplied OrderPacket.workdir still\n wins, and is never reaped.\n OWENLOOP_WORK_REPO local git repo to cut per-run work dirs from\n as worktrees instead of plain dirs; above\n settings.workRepo, default off\n\n Credentials / accounts:\n owenloop work's RUNTIME roles (shift/hold/exec/prepare/release) are READ-ONLY\n over owenloop's credential store \u2014 they never write credentials. Each\n role reads the agent:<account> slot for its origin (never the human\n slot); the account defaults to 'default'. 'owenloop work join' is the one\n deliberate provisioning-time writer: it stores the Scoped Identity token a hub\n redeem returns via owenloop's public storeCredential, once, at join time\n \u2014 not a runtime write.\n store / connect an account (run owenloop; owenloop work never writes it):\n owenloop login --hub <origin> --as agent:<account>\n (use --as agent for the default account)\n or provision a fresh box from a hub-issued join code:\n owenloop work join <code> --hub <origin>\n select an account at run time:\n --as <account> on shift / hold\n OWENLOOP_ACCOUNT on exec / prepare / release\n (shift resolves once and threads both channels)\n owenloop work does NOT list stored accounts \u2014 enumerating an origin's accounts\n is an owenloop-side capability; check owenloop for which slots are stored.\n\nExit codes:\n 0 success / help / version / lint clean or warnings-only\n 1 runtime failure (fetch/hub error, cache write) / lint found an error\n 2 usage error (unknown or missing role, missing required arg)\n 3 role not implemented yet (skeleton stub \u2014 lands in a later delivery)\n";
@@ -43,6 +43,12 @@ Options:
43
43
  --once bootstrap wake + one sweep, then exit (demo/e2e)
44
44
  --max-agents <n> max in-flight agent-run children, separate from
45
45
  --cap (default 4; else settings.maxConcurrentAgents)
46
+ --exec-reserve <n> slots inside --cap that agent-run children may
47
+ not occupy, so exec orders always have room
48
+ (default 1; else settings.execReserve; 0 disables)
49
+ --local-queue-hold <ms> retain an undispatchable claim locally before
50
+ returning it to the hub (default 0; else
51
+ settings.localQueueHoldMs; capped at 90000)
46
52
  --cache-dir/--state-dir <p> override the resolved dirs
47
53
 
48
54
  hold options:
@@ -109,7 +115,7 @@ Options:
109
115
  settings (no options in v1):
110
116
  prints the resolved settings file path, whether it exists, each known
111
117
  knob (hubOrigin, cacheDir, stateDir, dispatchCap, commandRouting,
112
- maxConcurrentAgents, workRoot, workRepo) with its value + provenance,
118
+ maxConcurrentAgents, execReserve, localQueueHoldMs, workRoot, workRepo) with its value + provenance,
113
119
  and any unrecognized keys.
114
120
  settings.dispatchCap/stateDir are the lowest-precedence
115
121
  fallbacks for shift's --cap/--state-dir. NO secrets ever
@@ -0,0 +1,7 @@
1
+ /** Resolve requested feedback first, then the order modifier hint, then default. */
2
+ export declare function resolveModifierInit(args: string[], env?: Record<string, string | undefined>): {
3
+ value?: string;
4
+ error?: string;
5
+ usage?: true;
6
+ };
7
+ export declare function runModifierInit(args: string[], env?: Record<string, string | undefined>): number;