owenloop 0.5.30 → 0.5.31

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 (51) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/packages/work/src/agent/loop.d.ts +5 -3
  3. package/dist/packages/work/src/agent/loop.js +24 -3
  4. package/dist/packages/work/src/agent/workdir.d.ts +17 -0
  5. package/dist/packages/work/src/agent/workdir.js +24 -0
  6. package/dist/packages/work/src/exec/loop.d.ts +8 -1
  7. package/dist/packages/work/src/exec/loop.js +24 -1
  8. package/dist/packages/work/src/hub/client.d.ts +10 -3
  9. package/dist/packages/work/src/hub/client.js +5 -4
  10. package/dist/packages/work/src/hub/deadline.d.ts +20 -0
  11. package/dist/packages/work/src/hub/deadline.js +49 -0
  12. package/dist/packages/work/src/roles/agent-run.js +1 -0
  13. package/dist/packages/work/src/roles/exec.js +1 -0
  14. package/dist/packages/work/src/settings/hub-roster-cache.js +5 -23
  15. package/dist/packages/work/src/shift/loop.d.ts +59 -0
  16. package/dist/packages/work/src/shift/loop.js +177 -19
  17. package/dist/packages/work/src/shift/protocol.d.ts +53 -1
  18. package/dist/packages/work/src/shift/runtime.js +10 -1
  19. package/dist/packages/work/src/shift/server.js +2 -0
  20. package/dist/src/bundle/manifest.d.ts +6 -1
  21. package/dist/src/bundle/manifest.js +38 -8
  22. package/dist/src/bundle/runtime.d.ts +1 -1
  23. package/dist/src/bundle/runtime.js +1 -0
  24. package/dist/src/bundle/types.d.ts +3 -2
  25. package/dist/src/cli.js +17 -3
  26. package/dist/src/defs.js +17 -4
  27. package/dist/src/engine.d.ts +3 -0
  28. package/dist/src/engine.js +42 -9
  29. package/dist/src/factory.d.ts +2 -0
  30. package/dist/src/factory.js +2 -0
  31. package/dist/src/index.d.ts +1 -1
  32. package/dist/src/index.js +1 -1
  33. package/dist/src/store/def-source.d.ts +1 -1
  34. package/dist/src/store/def-source.js +25 -0
  35. package/dist/src/store/gc.js +9 -7
  36. package/dist/src/store/index.d.ts +1 -0
  37. package/dist/src/store/index.js +1 -0
  38. package/dist/src/store/install.js +9 -3
  39. package/dist/src/store/instruction-source.js +9 -5
  40. package/dist/src/store/verified-lock.d.ts +4 -0
  41. package/dist/src/store/verified-lock.js +38 -0
  42. package/dist/src/store.js +4 -2
  43. package/docs/authoring.md +12 -0
  44. package/docs/bundles.md +3 -2
  45. package/docs/cli.md +39 -11
  46. package/docs/shift-logs.md +53 -4
  47. package/package.json +1 -1
  48. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  49. package/plugins/claude-code/plugin/.mcp.json +1 -1
  50. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  51. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
@@ -62,6 +62,7 @@ import { isCommandStep, resolveCommandRouting } from "./routing.js";
62
62
  import { cancelReservedChild, finalizeChildReservation, reconcileInFlight, reserveChild, startReservedChild, removeChildRecord, settleChildGate, ensureStateDir, } from "./state.js";
63
63
  import { DEFAULT_WORK_DIR_TTL_MS, sweepWorkDirs as sweepWorkDirsImpl } from "../agent/workdir.js";
64
64
  import { withHubRosterSyncTimeout } from "../settings/hub-roster-cache.js";
65
+ import { withHubCallTimeout } from "../hub/deadline.js";
65
66
  import { sessionsPath } from "../harness/session-store.js";
66
67
  import { checkHost } from "./host-preflight.js";
67
68
  import { formatBytes } from "./disk-floor.js";
@@ -212,6 +213,44 @@ const MAX_CAUSE_DEPTH = 4;
212
213
  * 30s poll interval three failures is about a minute and a half.
213
214
  */
214
215
  const HOST_PREFLIGHT_STREAK = 3;
216
+ /**
217
+ * Default per-call deadline for the poll loop's hub verbs (issue #300).
218
+ *
219
+ * 30 seconds, because: (1) none of these verbs long-polls — `wake` is the
220
+ * "cheap wake pre-check" the client documents, `presence_ping` and
221
+ * `whats_next` are single Durable Object round trips, and the hub answers a
222
+ * busy DO with an immediate "retry in 1s" error rather than by holding the
223
+ * request; so a legitimate call finishes in well under a second and 30s is a
224
+ * generous multiple of the slowest plausible one; (2) the failure this bounds
225
+ * lasted HOURS with no traffic at all, so any finite value fixes the bug and
226
+ * the question is only how much a tick may cost while it does — 30s is
227
+ * six default poll intervals, cheap next to the alternative; (3) it is
228
+ * deliberately longer than the 10s roster-sync deadline, which guards a
229
+ * low-priority refresh that may simply be skipped; these calls are the
230
+ * loop's whole purpose and deserve more patience before being counted as
231
+ * failed. Trade-off accepted: a `whats_next` that the hub committed but this
232
+ * side timed out leaves that claim to lapse through the hub's pickup window,
233
+ * exactly as a dropped connection after commit would.
234
+ */
235
+ export const DEFAULT_HUB_CALL_TIMEOUT_MS = 30_000;
236
+ /** Default cadence of the file-only `heartbeat` record: every five minutes. */
237
+ export const DEFAULT_HEARTBEAT_INTERVAL_MS = 5 * 60_000;
238
+ /** Floor for the watchdog's own check cadence. */
239
+ const MIN_WATCHDOG_CHECK_MS = 1_000;
240
+ /** The later of two optional monotonic timestamps; undefined only when both are. */
241
+ function latestDefined(a, b) {
242
+ if (a === undefined)
243
+ return b;
244
+ if (b === undefined)
245
+ return a;
246
+ return Math.max(a, b);
247
+ }
248
+ /** Production `schedule`: an interval that never keeps the process alive. */
249
+ function scheduleWithInterval(fn, everyMs) {
250
+ const timer = setInterval(fn, everyMs);
251
+ timer.unref();
252
+ return () => clearInterval(timer);
253
+ }
215
254
  /** The identity a storm repeats on. `key` is '' for an unfanned step. */
216
255
  function stepBrakeKey(workflow, step, key) {
217
256
  return `${workflow}\u0000${step}\u0000${key ?? ''}`;
@@ -277,6 +316,22 @@ export function createShiftLoop(opts) {
277
316
  }
278
317
  const isAlive = opts.isAlive;
279
318
  const monotonicNow = opts.monotonicNow ?? performance.now.bind(performance);
319
+ const hubCallTimeoutMs = opts.hubCallTimeoutMs ?? DEFAULT_HUB_CALL_TIMEOUT_MS;
320
+ const heartbeatIntervalMs = opts.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
321
+ const schedule = opts.schedule ?? scheduleWithInterval;
322
+ // Issue #300 liveness. Two clocks on purpose: the wall clock is what
323
+ // `shift status` and the records show, the monotonic one is what the
324
+ // watchdog measures staleness with (a wall-clock jump must not fake a stall).
325
+ let cyclesCompleted = 0;
326
+ let lastPollAt;
327
+ let lastCycleMono;
328
+ /** Last settled hub call, success or failure: one cycle may serialise many. */
329
+ let lastProgressMono;
330
+ let runStartedMono;
331
+ /** Edge trigger for `stalled`: one record per episode, re-armed by a completed cycle. */
332
+ let stalledReported = false;
333
+ let cancelWatchdog;
334
+ let cancelHeartbeat;
280
335
  // Live shift identity (MCP `clock_in`, D3-D7 of the plan). Seeded from opts,
281
336
  // which are now INITIAL values only. Arrays are copied so neither the loop
282
337
  // nor a caller of getShift/setShift can mutate the other's state afterward.
@@ -512,6 +567,94 @@ export function createShiftLoop(opts) {
512
567
  * as free text and stays free text: it is the sink's own failure report, and
513
568
  * turning it into an event would write it to the sink that just failed.
514
569
  */
570
+ /**
571
+ * One poll-loop hub call under the per-call deadline (issue #300). Every
572
+ * settlement — success, failure, or the deadline itself — is progress for
573
+ * the watchdog: a cycle serialises roster sync, presence, wake, the inbox
574
+ * and one targeted `whats_next` per workflow, so a slow-but-alive hub can
575
+ * legitimately take longer than the stall threshold per cycle.
576
+ */
577
+ async function hubCall(label, run) {
578
+ try {
579
+ return await withHubCallTimeout(label, run, hubCallTimeoutMs);
580
+ }
581
+ finally {
582
+ lastProgressMono = monotonicNow();
583
+ }
584
+ }
585
+ /**
586
+ * One poll cycle, accounted. Wraps `iteration()` so BOTH entry points — the
587
+ * daemon's `run` and the exported `iterate` — feed the same liveness facts
588
+ * and re-arm the watchdog. A cycle counts only when `iteration()` RETURNS:
589
+ * one that never settles is exactly what the watchdog below is for.
590
+ */
591
+ async function cycle() {
592
+ const dispatched = await iteration();
593
+ cyclesCompleted += 1;
594
+ lastPollAt = opts.now();
595
+ lastCycleMono = monotonicNow();
596
+ stalledReported = false;
597
+ return dispatched;
598
+ }
599
+ function stallThresholdMs() {
600
+ return opts.stallThresholdMs ?? 3 * opts.pollIntervalMs + hubCallTimeoutMs;
601
+ }
602
+ /**
603
+ * WATCHDOG (issue #300). Runs from its own timer, so it does not depend on
604
+ * `iteration()` ever returning — that dependency is the whole bug: a loop
605
+ * awaiting a call that never settles cannot report its own hang.
606
+ *
607
+ * Staleness is measured from the loop's last PROGRESS — the later of the
608
+ * last settled hub call and the last completed cycle (or the start of
609
+ * `run`, so a FIRST call that hangs is caught too). A cycle is many serial
610
+ * calls, so measuring from the cycle alone would report a slow-but-alive
611
+ * hub as a stall on every sweep. A Retry-After backoff parks the loop on
612
+ * the hub's instruction, so the reference is the later of that and the
613
+ * backoff's end: an honest, hub-instructed pause never reads as a stall.
614
+ * Edge-triggered: one record per episode.
615
+ */
616
+ function checkStall() {
617
+ if (stopped)
618
+ return;
619
+ const progressAt = latestDefined(lastProgressMono, lastCycleMono) ?? runStartedMono;
620
+ if (progressAt === undefined)
621
+ return;
622
+ const threshold = stallThresholdMs();
623
+ const now = monotonicNow();
624
+ if (now - Math.max(progressAt, backoffUntil) < threshold)
625
+ return;
626
+ if (stalledReported)
627
+ return;
628
+ stalledReported = true;
629
+ const sinceMs = Math.round(now - progressAt);
630
+ const last = lastPollAt === undefined ? 'never' : new Date(lastPollAt).toISOString();
631
+ opts.err(`poll loop stalled: no progress for ${sinceMs}ms (threshold ${threshold}ms; last completed cycle ${last})`);
632
+ emit({ type: 'stalled', lastPollAt: lastPollAt ?? null, sinceMs });
633
+ }
634
+ /** Periodic proof of life; file-only by the runtime's routing (issue #300). */
635
+ function heartbeat() {
636
+ if (stopped)
637
+ return;
638
+ emit({
639
+ type: 'heartbeat',
640
+ cyclesCompleted,
641
+ lastPollAt: lastPollAt ?? null,
642
+ hubFailureStreak,
643
+ stalled: stalledReported,
644
+ });
645
+ }
646
+ /** Daemon mode only: `once` runs one cycle and returns, so has nothing to watch. */
647
+ function startTimers() {
648
+ cancelWatchdog = schedule(checkStall, Math.max(MIN_WATCHDOG_CHECK_MS, opts.pollIntervalMs));
649
+ if (heartbeatIntervalMs > 0)
650
+ cancelHeartbeat = schedule(heartbeat, heartbeatIntervalMs);
651
+ }
652
+ function stopTimers() {
653
+ cancelWatchdog?.();
654
+ cancelWatchdog = undefined;
655
+ cancelHeartbeat?.();
656
+ cancelHeartbeat = undefined;
657
+ }
515
658
  function emit(body) {
516
659
  if (opts.onEvent === undefined)
517
660
  return;
@@ -1004,7 +1147,7 @@ export function createShiftLoop(opts) {
1004
1147
  }
1005
1148
  else {
1006
1149
  try {
1007
- const inbox = await opts.hub.whatsNext({ serve_capabilities: [...serveCapabilities] });
1150
+ const inbox = await hubCall('inbox whats_next', (signal) => opts.hub.whatsNext({ serve_capabilities: [...serveCapabilities] }, signal));
1008
1151
  instances = (inbox.instances ?? []).map((inbox) => ({ workflow: inbox.workflow, inbox }));
1009
1152
  }
1010
1153
  catch (e) {
@@ -1074,11 +1217,11 @@ export function createShiftLoop(opts) {
1074
1217
  let res;
1075
1218
  const requestStartedAt = monotonicNow();
1076
1219
  try {
1077
- res = await opts.hub.whatsNext({
1220
+ res = await hubCall(`whats_next ${wf}`, (signal) => opts.hub.whatsNext({
1078
1221
  workflow: wf,
1079
1222
  serve_crews: serveCrews,
1080
1223
  serve_capabilities: [...serveCapabilities],
1081
- });
1224
+ }, signal));
1082
1225
  }
1083
1226
  catch (e) {
1084
1227
  if (isNonServableRace(e)) {
@@ -1391,14 +1534,14 @@ export function createShiftLoop(opts) {
1391
1534
  // identity by a full presenceIntervalMs.
1392
1535
  const generation = ++presenceGeneration;
1393
1536
  try {
1394
- await opts.hub.presencePing({
1537
+ await hubCall('presence ping', (signal) => opts.hub.presencePing({
1395
1538
  name: shiftName,
1396
1539
  serve_crews: serveCrews,
1397
1540
  serve_capabilities: [...serveCapabilities],
1398
1541
  ...(opts.shiftId !== undefined ? { shift_id: opts.shiftId } : {}),
1399
1542
  ...(opts.startedAt !== undefined ? { started_at: opts.startedAt } : {}),
1400
1543
  ...(attendedAt !== undefined ? { attended_at: attendedAt } : {}),
1401
- });
1544
+ }, signal));
1402
1545
  if (generation === presenceGeneration)
1403
1546
  lastPresence = monotonicNow();
1404
1547
  }
@@ -1439,7 +1582,9 @@ export function createShiftLoop(opts) {
1439
1582
  let changed = false;
1440
1583
  let wakeSucceeded = false;
1441
1584
  try {
1442
- const w = await opts.hub.wake(cursor);
1585
+ // Under the per-call deadline: a timeout lands in the catch below on the
1586
+ // same terms as any other non-rate-limited failure (issue #300).
1587
+ const w = await hubCall('wake', (signal) => opts.hub.wake(cursor, signal));
1443
1588
  changed = w.changed;
1444
1589
  cursor = w.cursor;
1445
1590
  wakeSucceeded = true;
@@ -1567,29 +1712,40 @@ export function createShiftLoop(opts) {
1567
1712
  if (runHostPreflight(0))
1568
1713
  return 1;
1569
1714
  if (opts.once === true) {
1570
- await iteration();
1715
+ await cycle();
1571
1716
  return wedged ? 1 : 0;
1572
1717
  }
1573
- for (;;) {
1574
- if (stopped)
1575
- return wedged ? 1 : 0;
1576
- await iteration();
1577
- if (stopped)
1578
- return wedged ? 1 : 0;
1579
- const delay = Math.max(opts.pollIntervalMs, backoffUntil - monotonicNow());
1580
- await opts.sleep(delay);
1581
- // Re-check after the park so a stop during sleep makes no further hub call.
1582
- if (stopped)
1583
- return wedged ? 1 : 0;
1718
+ // The watchdog and heartbeat live OUTSIDE this loop (issue #300): they must
1719
+ // keep firing when `cycle()` never returns, which is the case they exist
1720
+ // for. Cleared on every exit path, including a throw out of `cycle()`.
1721
+ runStartedMono = monotonicNow();
1722
+ startTimers();
1723
+ try {
1724
+ for (;;) {
1725
+ if (stopped)
1726
+ return wedged ? 1 : 0;
1727
+ await cycle();
1728
+ if (stopped)
1729
+ return wedged ? 1 : 0;
1730
+ const delay = Math.max(opts.pollIntervalMs, backoffUntil - monotonicNow());
1731
+ await opts.sleep(delay);
1732
+ // Re-check after the park so a stop during sleep makes no further hub call.
1733
+ if (stopped)
1734
+ return wedged ? 1 : 0;
1735
+ }
1736
+ }
1737
+ finally {
1738
+ stopTimers();
1584
1739
  }
1585
1740
  }
1586
1741
  function stop() {
1587
1742
  stopped = true;
1743
+ stopTimers();
1588
1744
  }
1589
1745
  return {
1590
1746
  run,
1591
1747
  stop,
1592
- iterate: iteration,
1748
+ iterate: cycle,
1593
1749
  freeCapacity: () => {
1594
1750
  const current = reconcile();
1595
1751
  return cap - current.live.length - current.reserved.length;
@@ -1618,6 +1774,8 @@ export function createShiftLoop(opts) {
1618
1774
  presenceGeneration++; // survive an in-flight ping completing after this
1619
1775
  },
1620
1776
  getAttendedAt: () => attendedAt,
1777
+ getCyclesCompleted: () => cyclesCompleted,
1778
+ getLastPollAt: () => lastPollAt,
1621
1779
  noteRunEnded: (run) => {
1622
1780
  pendingCandidates.delete(run);
1623
1781
  // A run that ENDED is a run that progressed — the shift's MCP `submit`
@@ -207,6 +207,49 @@ export interface WedgedEvent {
207
207
  faults: HostFault[];
208
208
  streak: number;
209
209
  }
210
+ /**
211
+ * The poll loop has made no progress — no hub call settled and no cycle
212
+ * completed — for longer than the shift's stall threshold. WATCHDOG-EMITTED, from a timer that does not depend on the loop:
213
+ * issue #300 was a daemon whose loop sat awaiting one hub call for hours,
214
+ * writing nothing, while `shift status` still answered — the loop cannot
215
+ * report its own hang, so something outside it must.
216
+ *
217
+ * EDGE-TRIGGERED like `capacity` and `low-disk`: one record per stall episode,
218
+ * re-armed by the next completed cycle. `lastPollAt` is the wall-clock time
219
+ * of the last completed cycle (`null` if none has completed since start) —
220
+ * the same fact `shift status` reports as `last_poll_at`, so a reader can
221
+ * line the two up. `sinceMs` is how long the loop has made NO progress: no
222
+ * hub call settled and no cycle completed. A cycle serialises many calls, so
223
+ * it is measured from the last settled call, not the last cycle.
224
+ *
225
+ * ON THE SOCKET AS WELL AS IN THE FILE, for the reason `wedged` is: a parked
226
+ * `owenloop shift next` is waiting on a loop that is no longer polling, and
227
+ * that is the most report-worthy thing that can happen to it.
228
+ */
229
+ export interface StalledEvent {
230
+ type: 'stalled';
231
+ lastPollAt: number | null;
232
+ sinceMs: number;
233
+ }
234
+ /**
235
+ * Periodic proof of life. FILE-ONLY (see `ParkedEvent`): it carries nothing
236
+ * an operator has to act on, so it must not wake a parked `shift next`.
237
+ *
238
+ * Issue #300's daemon was silent for hours and NOTHING distinguished "idle and
239
+ * healthy" from "hung": an idle loop writes no lines either. This record makes
240
+ * the silence readable — a `shift.log` whose heartbeats stopped names the
241
+ * minute the process stopped doing anything, and one whose heartbeats
242
+ * continue with a frozen `cyclesCompleted` names a loop that is alive but not
243
+ * polling. `hubFailureStreak` is the same counter the host preflight reads,
244
+ * and `stalled` mirrors whether a `stalled` record is currently outstanding.
245
+ */
246
+ export interface HeartbeatEvent {
247
+ type: 'heartbeat';
248
+ cyclesCompleted: number;
249
+ lastPollAt: number | null;
250
+ hubFailureStreak: number;
251
+ stalled: boolean;
252
+ }
210
253
  /**
211
254
  * The socket event FIFO overflowed and discarded its oldest event. Written
212
255
  * STRAIGHT to the file sink, never through the loop's `emit()` — `emit()` feeds
@@ -222,7 +265,7 @@ export interface EventQueueOverflowEvent {
222
265
  * What a construction site builds: the event's own payload, with no identity
223
266
  * and no timestamp. Every consumer receives the stamped `ShiftEvent` instead.
224
267
  */
225
- export type ShiftEventBody = DispatchedEvent | ReapedEvent | FailedEvent | GateEvent | EndedEvent | ParkedEvent | CapacityEvent | HubErrorEvent | BundleMissEvent | OrderDroppedEvent | EventQueueOverflowEvent | WedgedEvent | LowDiskEvent;
268
+ export type ShiftEventBody = DispatchedEvent | ReapedEvent | FailedEvent | GateEvent | EndedEvent | ParkedEvent | CapacityEvent | HubErrorEvent | BundleMissEvent | OrderDroppedEvent | EventQueueOverflowEvent | WedgedEvent | LowDiskEvent | StalledEvent | HeartbeatEvent;
226
269
  /**
227
270
  * The identity every event carries, added once on a shared envelope rather than
228
271
  * per variant.
@@ -270,6 +313,15 @@ export interface ShiftStatus {
270
313
  agent_ceiling: number;
271
314
  attended_at: number | null;
272
315
  started_at: number;
316
+ /**
317
+ * Issue #300 liveness facts. `last_poll_at` is the wall-clock time the poll
318
+ * loop last COMPLETED a cycle (`null` before the first), and
319
+ * `cycles_completed` the running count. A status whose `started_at` is hours
320
+ * old and whose `last_poll_at` is also hours old names a hung loop — which a
321
+ * status made only of capacity numbers never could.
322
+ */
323
+ last_poll_at: number | null;
324
+ cycles_completed: number;
273
325
  }
274
326
  export interface ShiftError {
275
327
  error: string;
@@ -17,7 +17,7 @@ import { DEFAULT_HUB_ROSTER_SYNC_TIMEOUT_MS, syncHubRosterCache, withHubRosterSy
17
17
  import { computeServeCapabilities } from "../settings/serving.js";
18
18
  import { resolveCacheDir } from "../bundle/cache.js";
19
19
  import { checkDiskFloor, resolveDiskFloorBytes } from "./disk-floor.js";
20
- import { createLockedRemovalCallbacks, createShiftLoop } from "./loop.js";
20
+ import { createLockedRemovalCallbacks, createShiftLoop, DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_HUB_CALL_TIMEOUT_MS, } from "./loop.js";
21
21
  import { createHubBundleRecoveryHandler } from "../bundle/pull.js";
22
22
  import { createShiftLogSink } from "./logsink.js";
23
23
  import { prepareShiftLogDir, shiftLogFile } from "./logretention.js";
@@ -88,6 +88,12 @@ const DEFAULT_ROSTER_SYNC_MS = 15 * 60_000;
88
88
  * `event-queue-overflow` never reaches `consumeEvent` at all — `server.ts`
89
89
  * hands it straight to the log sink through `onSynthesized`, because the queue
90
90
  * is what overflowed. It is listed here so the category is stated in one place.
91
+ *
92
+ * `heartbeat` (issue #300) is periodic proof of life on a fixed cadence. It
93
+ * carries nothing to act on, so the blocking contract of `shift next` applies:
94
+ * a client parked for work must not be woken every five minutes by a record
95
+ * that says only "still here". `stalled`, the watchdog's edge-triggered
96
+ * counterpart, is NOT in this set for the reason `wedged` is not.
91
97
  */
92
98
  const FILE_ONLY_EVENTS = new Set([
93
99
  'parked',
@@ -95,6 +101,7 @@ const FILE_ONLY_EVENTS = new Set([
95
101
  'hub-error',
96
102
  'event-queue-overflow',
97
103
  'low-disk',
104
+ 'heartbeat',
98
105
  ]);
99
106
  /**
100
107
  * Does this event type reach the SOCKET consumer (a parked `owenloop shift
@@ -587,6 +594,8 @@ export async function runShiftRuntime(parsed, options = {}) {
587
594
  presenceIntervalMs: DEFAULT_PRESENCE_MS,
588
595
  rosterSyncIntervalMs: DEFAULT_ROSTER_SYNC_MS,
589
596
  rosterSyncTimeoutMs: DEFAULT_HUB_ROSTER_SYNC_TIMEOUT_MS,
597
+ hubCallTimeoutMs: DEFAULT_HUB_CALL_TIMEOUT_MS,
598
+ heartbeatIntervalMs: DEFAULT_HEARTBEAT_INTERVAL_MS,
590
599
  syncRosters: (signal) => syncHubRosterCache({ client: hub, env, origin, account, signal }),
591
600
  computeServeCapabilities: (crews) => computeServeCapabilities({
592
601
  env,
@@ -290,6 +290,8 @@ export function createShiftDaemon(opts) {
290
290
  agent_ceiling: opts.loop.agentCeiling(),
291
291
  attended_at: opts.loop.getAttendedAt() ?? null,
292
292
  started_at: opts.startedAt,
293
+ last_poll_at: opts.loop.getLastPollAt() ?? null,
294
+ cycles_completed: opts.loop.getCyclesCompleted(),
293
295
  };
294
296
  };
295
297
  const respond = (socket, response) => {
@@ -22,7 +22,12 @@ import type { BundleManifest } from './types.ts';
22
22
  export declare function sha256Hex(bytes: Uint8Array): string;
23
23
  /** Workflow map keys: lowercase-start, lowercase alphanumeric and hyphen. */
24
24
  export declare const WORKFLOW_NAME_RE: RegExp;
25
- /** True when `text` is the explicit `namespace/name@version` reference form. */
25
+ /** Parse an exact call. `#` cannot occur in a store coordinate, so the selector is unambiguous. */
26
+ export declare function parseVersionedCallTarget(text: string): {
27
+ coordinate: string;
28
+ workflow?: string;
29
+ };
30
+ /** True for a well-formed exact package call, optionally selecting a named workflow. */
26
31
  export declare function isVersionedReference(text: string): boolean;
27
32
  /**
28
33
  * Parse and validate `.wnlp` manifest bytes, fail-closed. Refuses non-UTF-8
@@ -20,6 +20,7 @@
20
20
  import { createHash } from 'node:crypto';
21
21
  import { isAlias, isMap, isPair, isScalar, isSeq, parseDocument, } from 'yaml';
22
22
  import { canonicalBundlePathViolation } from "../archive.js";
23
+ import { parseWorkflowCoordinate } from "../store/types.js";
23
24
  import { assertCurrentRuntimeCompatible, isCanonicalSemver } from "./runtime.js";
24
25
  import { BundleError } from "./types.js";
25
26
  /** Lowercase 64-hex SHA-256 of `bytes`. */
@@ -39,11 +40,33 @@ const RUNTIME_FEATURE_RE = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*\.v[1-9][0-9]*$/;
39
40
  const PLATFORM_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
40
41
  /** Capability class identifier. */
41
42
  const CAPABILITY_CLASS_RE = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/;
42
- /** Explicit cross-bundle reference: `namespace/name@version`. */
43
- const VERSIONED_REF_RE = /^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)@([!-~]+)$/;
44
- /** True when `text` is the explicit `namespace/name@version` reference form. */
43
+ /** Historical explicit-coordinate spelling; store parsing further excludes ambiguous separators. */
44
+ const VERSIONED_REF_RE = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+@[!-~]+$/;
45
+ /** Parse an exact call. `#` cannot occur in a store coordinate, so the selector is unambiguous. */
46
+ export function parseVersionedCallTarget(text) {
47
+ const hash = text.indexOf('#');
48
+ const coordinate = hash < 0 ? text : text.slice(0, hash);
49
+ if (!VERSIONED_REF_RE.test(coordinate)) {
50
+ throw new BundleError('MANIFEST_ERROR', `invalid exact versioned call target '${text}'`);
51
+ }
52
+ parseWorkflowCoordinate(coordinate);
53
+ if (hash < 0)
54
+ return { coordinate };
55
+ const workflow = text.slice(hash + 1);
56
+ if (!WORKFLOW_NAME_RE.test(workflow)) {
57
+ throw new BundleError('MANIFEST_ERROR', `invalid named workflow selector '${text}'`);
58
+ }
59
+ return { coordinate, workflow };
60
+ }
61
+ /** True for a well-formed exact package call, optionally selecting a named workflow. */
45
62
  export function isVersionedReference(text) {
46
- return VERSIONED_REF_RE.test(text);
63
+ try {
64
+ parseVersionedCallTarget(text);
65
+ return true;
66
+ }
67
+ catch {
68
+ return false;
69
+ }
47
70
  }
48
71
  /**
49
72
  * Walk a yaml AST into plain JS values, fail-closed: refuses aliases, merge
@@ -309,7 +332,7 @@ export function parseManifestBytes(bytes) {
309
332
  // lock — explicit versioned reference text → def digest.
310
333
  const lock = Object.create(null);
311
334
  for (const [ref, digestRaw] of Object.entries(asMap(root['lock'], 'bundle.yaml.lock'))) {
312
- if (!isVersionedReference(ref)) {
335
+ if (!isVersionedReference(ref) || ref.includes('#')) {
313
336
  throw new BundleError('MANIFEST_ERROR', `bundle.yaml.lock: key '${ref}' must be an explicit 'namespace/name@version' reference`);
314
337
  }
315
338
  const digest = asString(digestRaw, `bundle.yaml.lock['${ref}']`);
@@ -426,10 +449,17 @@ export function manifestIsCanonical(bytes) {
426
449
  */
427
450
  export function assertLockCoverage(manifest, callsTargets) {
428
451
  for (const target of callsTargets) {
429
- if (!isVersionedReference(target))
452
+ if (!target.includes('@') || !target.includes('/'))
430
453
  continue;
431
- if (!Object.prototype.hasOwnProperty.call(manifest.lock, target)) {
432
- throw new BundleError('MANIFEST_ERROR', `bundle.yaml.lock: calls: target '${target}' uses the explicit 'namespace/name@version' form and requires a lock entry`);
454
+ let coordinate;
455
+ try {
456
+ coordinate = parseVersionedCallTarget(target).coordinate;
457
+ }
458
+ catch {
459
+ throw new BundleError('MANIFEST_ERROR', `calls: target '${target}' is a malformed exact versioned reference`);
460
+ }
461
+ if (!Object.prototype.hasOwnProperty.call(manifest.lock, coordinate)) {
462
+ throw new BundleError('MANIFEST_ERROR', `bundle.yaml.lock: calls: target '${target}' requires a lock entry for '${coordinate}'`);
433
463
  }
434
464
  }
435
465
  }
@@ -1,6 +1,6 @@
1
1
  import type { BundleRuntimeRequirements } from './types.ts';
2
2
  /** Runtime features implemented by this Owenloop release. */
3
- export declare const SUPPORTED_RUNTIME_FEATURES: readonly ["harness-policy-enforcement.v1", "native-judge-policy-inheritance.v1", "neutral-approval-modes.v1", "command-payload-file.v1"];
3
+ export declare const SUPPORTED_RUNTIME_FEATURES: readonly ["exact-workflow-selector.v1", "harness-policy-enforcement.v1", "native-judge-policy-inheritance.v1", "neutral-approval-modes.v1", "command-payload-file.v1"];
4
4
  export interface RuntimeCompatibilityEnvironment {
5
5
  /** The running Owenloop package version. `0.0.0` is the unavailable-version sentinel. */
6
6
  version: string;
@@ -4,6 +4,7 @@ import { BundleError } from "./types.js";
4
4
  const semver = createRequire(import.meta.url)('semver');
5
5
  /** Runtime features implemented by this Owenloop release. */
6
6
  export const SUPPORTED_RUNTIME_FEATURES = Object.freeze([
7
+ 'exact-workflow-selector.v1',
7
8
  'harness-policy-enforcement.v1',
8
9
  'native-judge-policy-inheritance.v1',
9
10
  // A def may write `x.harness.permissionMode` as one of the three neutral
@@ -62,8 +62,9 @@ export interface BundleManifest {
62
62
  */
63
63
  capabilities: Record<string, string[]>;
64
64
  /**
65
- * Digest-pinned cross-bundle references: exact `namespace/name@version`
66
- * reference text → lowercase 64-hex def digest of the called bundle.
65
+ * Digest-pinned cross-bundle references: base `namespace/name@version`
66
+ * coordinate → lowercase 64-hex def digest of the called bundle, including
67
+ * `#workflow` calls into that bundle.
67
68
  */
68
69
  lock: Record<string, string>;
69
70
  }
package/dist/src/cli.js CHANGED
@@ -60,8 +60,9 @@ import { orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocation
60
60
  import { runMcpCommand } from "./mcp/serve.js";
61
61
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
62
62
  import { BundleError, digestBundle, inspectBundle, packBundle, unpackBundle } from "./bundle/index.js";
63
+ import { parseVersionedCallTarget } from "./bundle/manifest.js";
63
64
  import { acquireInstallLock, ADD_JOURNAL_FILENAME, archivePathViolation, commitInstall, finalizeInstallCommit, githubShaUrl, githubTarballUrl, installFolder, parkOldNameDir, parseRepoSpec, readLockfile, recoverInterruptedInstall, releaseInstallLock, removeAddJournal, rmRecursiveForce, rollbackInstallCommit, RollbackFailedError, stageFiles, STAGING_DIRNAME, writeAddJournal, writeLockfile, } from "./add.js";
64
- import { BundleIngestorUnavailableError, collectWorkflowStoreGarbage, compareStoreText, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, parseWorkflowCoordinate, projectStoreRoot, createBundleIngestor, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.js";
65
+ import { BundleIngestorUnavailableError, collectWorkflowStoreGarbage, compareStoreText, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, parseWorkflowCoordinate, projectStoreRoot, createBundleIngestor, createVerifiedBundleLockReader, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.js";
65
66
  import { recoverInterruptedWorkflowStoreGc } from "./store/gc-recovery.js";
66
67
  import { asAgentIdentities, asCreateWorkflowOk, capabilityPublishReportText, asCapabilityRerouteAdded, asCapabilityRerouteRemoved, asCapabilityReroutes, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asInterfaceCatalogList, asInterfaceCatalogVersion, asWorkflowCatalogVisibility, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, asRoutingAlerts, asRunRouting, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, DEFAULT_HUB, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
67
68
  import { fetchCapabilityMappings, recordCapabilityMappings } from "./capability-mapping-client.js";
@@ -534,6 +535,13 @@ function openCtx(io, args, tolerantCasInspection = false) {
534
535
  // path — one loaded-definition resolver seeds the instruction boundary
535
536
  // (emission digests + instruction resolution), never a second local path.
536
537
  const instructionSource = createDefInstructionSource(defs.values());
538
+ let verifiedGlobalRoot;
539
+ try {
540
+ verifiedGlobalRoot = globalStoreRoot(workflowHome(io));
541
+ }
542
+ catch {
543
+ verifiedGlobalRoot = join(defsDir, '.owenloop-global-store-unavailable');
544
+ }
537
545
  // WS-6: the resolver is SCOPE-AWARE. `from` is supplied only by the engine's
538
546
  // `calls:` spawn path; when it is present and carries CAS provenance, a bare
539
547
  // target resolves sibling-first inside that def's own bundle (the exact rule
@@ -547,7 +555,13 @@ function openCtx(io, args, tolerantCasInspection = false) {
547
555
  if (!d)
548
556
  throw new CliError(`unknown workflow definition '${name}' (looked in ${defsDir})`);
549
557
  return d;
550
- }, { instructionSource });
558
+ }, {
559
+ instructionSource,
560
+ readVerifiedBundleLock: createVerifiedBundleLockReader({
561
+ projectRoot: projectStoreRoot(defsDir),
562
+ globalRoot: verifiedGlobalRoot,
563
+ }),
564
+ });
551
565
  return { store, engine, defs, defsDir, dbPath, definitionDiscoveryComplete };
552
566
  }
553
567
  function print(io, value) {
@@ -2888,7 +2902,7 @@ function bundleGcExactCallsFromCurrentDefs(io, defsDir, defsOverride, verbose) {
2888
2902
  if (step.calls === undefined || !step.calls.includes('@'))
2889
2903
  continue;
2890
2904
  try {
2891
- parseWorkflowCoordinate(step.calls);
2905
+ parseVersionedCallTarget(step.calls);
2892
2906
  }
2893
2907
  catch (error) {
2894
2908
  throw new CliError(`owenloop bundle gc: malformed exact calls target ${JSON.stringify(step.calls)} ` +
package/dist/src/defs.js CHANGED
@@ -29,6 +29,7 @@ import { assertValidSchema } from "./schema.js";
29
29
  // The separator lives with composition/matching (capabilities.ts); the parser
30
30
  // only enforces that an AUTHORED name never contains it.
31
31
  import { MODIFIER_SEPARATOR } from "./capabilities.js";
32
+ import { parseVersionedCallTarget } from "./bundle/manifest.js";
32
33
  import { isCallStep } from "./types.js";
33
34
  /** Hand-maintained key allowlist for RawInput — kept next to the interface so
34
35
  * the two can't silently drift (§27 unknown-key rejection). */
@@ -2290,12 +2291,12 @@ export function digestScopedCallsTargetKey(digest, target) {
2290
2291
  * THREE CASES, checked in this order:
2291
2292
  *
2292
2293
  * 1. `target` contains `/` — an explicitly QUALIFIED reference. When the
2293
- * calling definition carries a lock digest for that exact target, prefer the
2294
+ * calling definition carries a lock digest for its base coordinate, prefer the
2294
2295
  * digest-scoped coordinate alias registered by the CAS loader. That preserves
2295
2296
  * an already-running parent's selection when a project coordinate later
2296
2297
  * shadows the global coordinate it originally pinned. Without a reachable
2297
- * pinned alias, use the direct coordinate/package key so new lookups retain
2298
- * project-over-global precedence and the engine can surface a pin mismatch.
2298
+ * pinned alias, a plain local caller may use the direct coordinate/package
2299
+ * key. A CAS caller's named exact target fails closed without its alias.
2299
2300
  * Never fall back to a bare lookup: an author who wrote a qualified name
2300
2301
  * asked for one specific definition.
2301
2302
  *
@@ -2315,12 +2316,24 @@ export function digestScopedCallsTargetKey(digest, target) {
2315
2316
  */
2316
2317
  function resolveCallsTargetKey(defs, target, from) {
2317
2318
  if (target.includes('/')) {
2318
- const pinnedDigest = from.bundleLock?.[target];
2319
+ let lockKey = target;
2320
+ if (target.includes('#')) {
2321
+ try {
2322
+ lockKey = parseVersionedCallTarget(target).coordinate;
2323
+ }
2324
+ catch {
2325
+ return undefined;
2326
+ }
2327
+ }
2328
+ const pinnedDigest = from.bundleLock?.[lockKey];
2319
2329
  if (pinnedDigest !== undefined) {
2320
2330
  const pinnedKey = digestScopedCallsTargetKey(pinnedDigest, target);
2321
2331
  if (defs.has(pinnedKey))
2322
2332
  return pinnedKey;
2323
2333
  }
2334
+ if (target.includes('#')) {
2335
+ return from.bundleDigest === undefined && defs.has(target) ? target : undefined;
2336
+ }
2324
2337
  return defs.has(target) ? target : undefined;
2325
2338
  }
2326
2339
  if (from.bundleDigest !== undefined) {
@@ -307,6 +307,7 @@ export declare class Engine {
307
307
  * compatibility mode). Public read-only facade: {@link Engine.resolver}.
308
308
  */
309
309
  private readonly instructionSource;
310
+ private readonly readVerifiedBundleLock;
310
311
  readonly resolver: OrderResolver;
311
312
  private readonly reapTtlMs;
312
313
  private readonly maxLeaseMs;
@@ -339,6 +340,8 @@ export declare class Engine {
339
340
  * no legacy fallback).
340
341
  */
341
342
  instructionSource?: OrderInstructionSource;
343
+ /** Verify a persisted CAS parent's manifest lock by bundle digest, without an index lookup. */
344
+ readVerifiedBundleLock?: (digest: string) => Readonly<Record<string, string>>;
342
345
  });
343
346
  /**
344
347
  * Register a synchronous observer of engine changes; returns an idempotent