owenloop 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +182 -53
  3. package/bin/owenloop.mjs +50 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +176 -0
  5. package/dist/packages/work/src/agent/brief.js +197 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +141 -0
  7. package/dist/packages/work/src/agent/loop.js +669 -0
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  11. package/dist/packages/work/src/agent/workdir.js +319 -0
  12. package/dist/packages/work/src/bundle/cache.d.ts +92 -0
  13. package/dist/packages/work/src/bundle/cache.js +338 -0
  14. package/dist/packages/work/src/bundle/fetch.d.ts +87 -0
  15. package/dist/packages/work/src/bundle/fetch.js +345 -0
  16. package/dist/packages/work/src/bundle/types.d.ts +164 -0
  17. package/dist/packages/work/src/bundle/types.js +1 -0
  18. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  19. package/dist/packages/work/src/consumed-verifier.js +205 -0
  20. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  21. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  22. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  23. package/dist/packages/work/src/credentials/reader.js +32 -0
  24. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  25. package/dist/packages/work/src/credentials/resolve.js +56 -0
  26. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  27. package/dist/packages/work/src/exec/instructions.js +323 -0
  28. package/dist/packages/work/src/exec/loop.d.ts +40 -0
  29. package/dist/packages/work/src/exec/loop.js +332 -0
  30. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  31. package/dist/packages/work/src/exec/payload.js +54 -0
  32. package/dist/packages/work/src/exec/receipt.d.ts +41 -0
  33. package/dist/packages/work/src/exec/receipt.js +32 -0
  34. package/dist/packages/work/src/exec/runner.d.ts +71 -0
  35. package/dist/packages/work/src/exec/runner.js +256 -0
  36. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  37. package/dist/packages/work/src/harness/child-env.js +134 -0
  38. package/dist/packages/work/src/harness/claude.d.ts +140 -0
  39. package/dist/packages/work/src/harness/claude.js +837 -0
  40. package/dist/packages/work/src/harness/codex.d.ts +111 -0
  41. package/dist/packages/work/src/harness/codex.js +1024 -0
  42. package/dist/packages/work/src/harness/contract.d.ts +308 -0
  43. package/dist/packages/work/src/harness/contract.js +32 -0
  44. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  45. package/dist/packages/work/src/harness/fake.js +91 -0
  46. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  47. package/dist/packages/work/src/harness/jsonrpc-stdio.js +351 -0
  48. package/dist/packages/work/src/harness/permissions.d.ts +75 -0
  49. package/dist/packages/work/src/harness/permissions.js +182 -0
  50. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  51. package/dist/packages/work/src/harness/registry.js +45 -0
  52. package/dist/packages/work/src/harness/session-store.d.ts +181 -0
  53. package/dist/packages/work/src/harness/session-store.js +523 -0
  54. package/dist/packages/work/src/harness/types.d.ts +29 -0
  55. package/dist/packages/work/src/harness/types.js +14 -0
  56. package/dist/packages/work/src/harnesses.d.ts +38 -0
  57. package/dist/packages/work/src/harnesses.js +38 -0
  58. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  59. package/dist/packages/work/src/hold/loop.js +23 -0
  60. package/dist/packages/work/src/hold/mcp.d.ts +75 -0
  61. package/dist/packages/work/src/hold/mcp.js +264 -0
  62. package/dist/packages/work/src/hub/client.d.ts +23 -0
  63. package/dist/packages/work/src/hub/client.js +91 -0
  64. package/dist/packages/work/src/hub/types.d.ts +326 -0
  65. package/dist/packages/work/src/hub/types.js +26 -0
  66. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  67. package/dist/packages/work/src/lease/loop.js +277 -0
  68. package/dist/packages/work/src/main.d.ts +1 -0
  69. package/dist/packages/work/src/main.js +48 -0
  70. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  71. package/dist/packages/work/src/mcp/server.js +320 -0
  72. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  73. package/dist/packages/work/src/owenloop-bin.js +18 -0
  74. package/dist/packages/work/src/roles/agent-run.d.ts +124 -0
  75. package/dist/packages/work/src/roles/agent-run.js +529 -0
  76. package/dist/packages/work/src/roles/exec.d.ts +48 -0
  77. package/dist/packages/work/src/roles/exec.js +228 -0
  78. package/dist/packages/work/src/roles/hold.d.ts +72 -0
  79. package/dist/packages/work/src/roles/hold.js +363 -0
  80. package/dist/packages/work/src/roles/join.d.ts +18 -0
  81. package/dist/packages/work/src/roles/join.js +204 -0
  82. package/dist/packages/work/src/roles/lint.d.ts +58 -0
  83. package/dist/packages/work/src/roles/lint.js +234 -0
  84. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  85. package/dist/packages/work/src/roles/prepare.js +249 -0
  86. package/dist/packages/work/src/roles/release.d.ts +48 -0
  87. package/dist/packages/work/src/roles/release.js +137 -0
  88. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  89. package/dist/packages/work/src/roles/sessions.js +180 -0
  90. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  91. package/dist/packages/work/src/roles/settings.js +71 -0
  92. package/dist/packages/work/src/roles/shift.d.ts +13 -0
  93. package/dist/packages/work/src/roles/shift.js +250 -0
  94. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  95. package/dist/packages/work/src/roles/signals.js +62 -0
  96. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  97. package/dist/packages/work/src/settings/provision.js +47 -0
  98. package/dist/packages/work/src/settings/settings.d.ts +136 -0
  99. package/dist/packages/work/src/settings/settings.js +155 -0
  100. package/dist/packages/work/src/shift/client.d.ts +24 -0
  101. package/dist/packages/work/src/shift/client.js +124 -0
  102. package/dist/packages/work/src/shift/loop.d.ts +131 -0
  103. package/dist/packages/work/src/shift/loop.js +751 -0
  104. package/dist/packages/work/src/shift/protocol.d.ts +95 -0
  105. package/dist/packages/work/src/shift/protocol.js +24 -0
  106. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  107. package/dist/packages/work/src/shift/routing.js +50 -0
  108. package/dist/packages/work/src/shift/runtime.d.ts +45 -0
  109. package/dist/packages/work/src/shift/runtime.js +337 -0
  110. package/dist/packages/work/src/shift/server.d.ts +23 -0
  111. package/dist/packages/work/src/shift/server.js +716 -0
  112. package/dist/packages/work/src/shift/spawn.d.ts +109 -0
  113. package/dist/packages/work/src/shift/spawn.js +158 -0
  114. package/dist/packages/work/src/shift/state.d.ts +79 -0
  115. package/dist/packages/work/src/shift/state.js +385 -0
  116. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  117. package/dist/packages/work/src/submit-proof.js +93 -0
  118. package/dist/packages/work/src/usage.d.ts +6 -0
  119. package/dist/packages/work/src/usage.js +175 -0
  120. package/dist/src/add.d.ts +189 -0
  121. package/dist/src/add.js +300 -0
  122. package/dist/src/archive.d.ts +97 -0
  123. package/dist/src/archive.js +591 -0
  124. package/dist/src/bundle/index.d.ts +64 -0
  125. package/dist/src/bundle/index.js +508 -0
  126. package/dist/src/bundle/manifest.d.ts +50 -0
  127. package/dist/src/bundle/manifest.js +435 -0
  128. package/dist/src/bundle/runtime.d.ts +26 -0
  129. package/dist/src/bundle/runtime.js +64 -0
  130. package/dist/src/bundle/tar.d.ts +62 -0
  131. package/dist/src/bundle/tar.js +238 -0
  132. package/dist/src/bundle/types.d.ts +105 -0
  133. package/dist/src/bundle/types.js +21 -0
  134. package/dist/{cli.d.ts → src/cli.d.ts} +92 -7
  135. package/dist/src/cli.js +5968 -0
  136. package/dist/{credentials.d.ts → src/credentials.d.ts} +22 -15
  137. package/dist/{credentials.js → src/credentials.js} +35 -31
  138. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  139. package/dist/src/crypto/allowed-signers.js +307 -0
  140. package/dist/src/crypto/canonical.d.ts +8 -0
  141. package/dist/src/crypto/canonical.js +92 -0
  142. package/dist/src/crypto/chain.d.ts +65 -0
  143. package/dist/src/crypto/chain.js +377 -0
  144. package/dist/src/crypto/dsse.d.ts +209 -0
  145. package/dist/src/crypto/dsse.js +282 -0
  146. package/dist/src/crypto/enrollment.d.ts +78 -0
  147. package/dist/src/crypto/enrollment.js +186 -0
  148. package/dist/src/crypto/index.d.ts +48 -0
  149. package/dist/src/crypto/index.js +44 -0
  150. package/dist/src/crypto/keys.d.ts +258 -0
  151. package/dist/src/crypto/keys.js +908 -0
  152. package/dist/src/crypto/org-root.d.ts +33 -0
  153. package/dist/src/crypto/org-root.js +78 -0
  154. package/dist/src/crypto/origin-rules.d.ts +56 -0
  155. package/dist/src/crypto/origin-rules.js +143 -0
  156. package/dist/src/crypto/policy-floor.d.ts +98 -0
  157. package/dist/src/crypto/policy-floor.js +353 -0
  158. package/dist/src/crypto/records.d.ts +316 -0
  159. package/dist/src/crypto/records.js +157 -0
  160. package/dist/src/crypto/scope.d.ts +49 -0
  161. package/dist/src/crypto/scope.js +83 -0
  162. package/dist/src/crypto/ssh.d.ts +171 -0
  163. package/dist/src/crypto/ssh.js +396 -0
  164. package/dist/src/crypto/submission.d.ts +33 -0
  165. package/dist/src/crypto/submission.js +47 -0
  166. package/dist/src/crypto/trust-roots.d.ts +29 -0
  167. package/dist/src/crypto/trust-roots.js +39 -0
  168. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  169. package/dist/src/crypto/verify-consumed.js +259 -0
  170. package/dist/src/crypto/verify-origin.d.ts +50 -0
  171. package/dist/src/crypto/verify-origin.js +151 -0
  172. package/dist/src/crypto/verify-publication.d.ts +60 -0
  173. package/dist/src/crypto/verify-publication.js +150 -0
  174. package/dist/{defs.d.ts → src/defs.d.ts} +24 -1
  175. package/dist/{defs.js → src/defs.js} +181 -61
  176. package/dist/{engine.d.ts → src/engine.d.ts} +105 -9
  177. package/dist/{engine.js → src/engine.js} +251 -47
  178. package/dist/{factory.d.ts → src/factory.d.ts} +16 -0
  179. package/dist/{factory.js → src/factory.js} +16 -4
  180. package/dist/src/global-config.d.ts +59 -0
  181. package/dist/src/global-config.js +84 -0
  182. package/dist/{hub.d.ts → src/hub.d.ts} +280 -31
  183. package/dist/{hub.js → src/hub.js} +493 -52
  184. package/dist/src/index.d.ts +47 -0
  185. package/dist/src/index.js +41 -0
  186. package/dist/src/install.d.ts +538 -0
  187. package/dist/src/install.js +1981 -0
  188. package/dist/src/lock.d.ts +38 -0
  189. package/dist/src/lock.js +325 -0
  190. package/dist/src/mcp/serve.d.ts +109 -0
  191. package/dist/{mcp → src/mcp}/serve.js +335 -75
  192. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  193. package/dist/{mcp → src/mcp}/server.js +18 -10
  194. package/dist/{model.d.ts → src/model.d.ts} +15 -0
  195. package/dist/{model.js → src/model.js} +112 -2
  196. package/dist/src/order-resolver.d.ts +184 -0
  197. package/dist/src/order-resolver.js +252 -0
  198. package/dist/src/package-version.d.ts +10 -0
  199. package/dist/src/package-version.js +42 -0
  200. package/dist/{paths.d.ts → src/paths.d.ts} +14 -1
  201. package/dist/{paths.js → src/paths.js} +18 -0
  202. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  203. package/dist/src/schemas/index.d.ts +1416 -0
  204. package/dist/src/schemas/index.js +31 -0
  205. package/dist/src/schemas/order.v1.schema.json +106 -0
  206. package/dist/src/schemas/origin.v1.schema.json +68 -0
  207. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  208. package/dist/src/schemas/publication.v1.schema.json +31 -0
  209. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  210. package/dist/src/schemas/submission.v1.schema.json +61 -0
  211. package/dist/src/store/def-source.d.ts +52 -0
  212. package/dist/src/store/def-source.js +335 -0
  213. package/dist/src/store/index-file.d.ts +69 -0
  214. package/dist/src/store/index-file.js +151 -0
  215. package/dist/src/store/index.d.ts +27 -0
  216. package/dist/src/store/index.js +22 -0
  217. package/dist/src/store/ingestor.d.ts +43 -0
  218. package/dist/src/store/ingestor.js +211 -0
  219. package/dist/src/store/install.d.ts +228 -0
  220. package/dist/src/store/install.js +555 -0
  221. package/dist/src/store/instruction-source.d.ts +49 -0
  222. package/dist/src/store/instruction-source.js +298 -0
  223. package/dist/src/store/origin-evidence.d.ts +21 -0
  224. package/dist/src/store/origin-evidence.js +66 -0
  225. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  226. package/dist/src/store/pre-commit-verifier.js +418 -0
  227. package/dist/src/store/resolve.d.ts +138 -0
  228. package/dist/src/store/resolve.js +363 -0
  229. package/dist/src/store/types.d.ts +288 -0
  230. package/dist/src/store/types.js +356 -0
  231. package/dist/{types.d.ts → src/types.d.ts} +58 -24
  232. package/dist/{untar.d.ts → src/untar.d.ts} +8 -23
  233. package/dist/src/untar.js +38 -0
  234. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  235. package/dist/{util.js → src/util.js} +3 -2
  236. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  237. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  238. package/docs/agent-runner.md +86 -0
  239. package/docs/authoring.md +150 -59
  240. package/docs/bundles.md +250 -0
  241. package/docs/cli.md +1758 -163
  242. package/docs/crypto.md +816 -0
  243. package/docs/design.md +374 -52
  244. package/docs/embedding.md +135 -27
  245. package/docs/wire-contracts.md +380 -0
  246. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  247. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  248. package/examples/workflows/judges/gate-sharpness.md +39 -0
  249. package/examples/workflows/judges/security.md +34 -0
  250. package/package.json +22 -8
  251. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  252. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  253. package/plugins/claude-code/plugin/.mcp.json +14 -0
  254. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  255. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  256. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  257. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  258. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  259. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  260. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  261. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  262. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  263. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  264. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  265. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  266. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  267. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  268. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
  269. package/dist/add.d.ts +0 -384
  270. package/dist/add.js +0 -834
  271. package/dist/cli.js +0 -3270
  272. package/dist/index.d.ts +0 -32
  273. package/dist/index.js +0 -23
  274. package/dist/lock.d.ts +0 -80
  275. package/dist/lock.js +0 -217
  276. package/dist/mcp/serve.d.ts +0 -84
  277. package/dist/untar.js +0 -164
  278. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  279. /package/dist/{schema.js → src/schema.js} +0 -0
  280. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  281. /package/dist/{store.js → src/store.js} +0 -0
  282. /package/dist/{types.js → src/types.js} +0 -0
@@ -0,0 +1,751 @@
1
+ /**
2
+ * The self-driven shift loop core (D2 dispatch split).
3
+ *
4
+ * `createShiftLoop` is a standing Shift loop with every side-effecting
5
+ * dependency injected (hub client, spawner, sleep/clock, output streams, dirs),
6
+ * so the same core can run behind the local shift daemon. Per iteration it: pings
7
+ * presence when due → reconciles local children → dispatches any already-claimed
8
+ * orders waiting for local capacity → checks `wake(cursor)` → sweeps `whats_next`
9
+ * when the hub changed or a prior sweep was skipped/failed → classifies/meters
10
+ * new orders → reaps work dirs → adopts the cursor → sleeps the poll interval.
11
+ *
12
+ * DISPATCH SPLIT (D2 decision 3 — the D12 routing contract). BOTH kinds spawn a
13
+ * detached child; there is exactly ONE way each kind runs, and no flag selects
14
+ * between paths:
15
+ * - COMMAND orders spawn a detached `owenloop work exec <wf>/<run> --origin <url>`
16
+ * child that self-leases (unchanged from C3).
17
+ * - AGENT orders spawn a detached `owenloop work agent-run <wf>/<run>` child that
18
+ * hosts the step agent itself through a harness adapter. The child resolves the
19
+ * order-pinned instruction digest and selects the verified step and harness;
20
+ * Shift never substitutes definition-name cache metadata for modern orders.
21
+ * - The shift makes NO first-contact `get_order` for any kind. It holds no
22
+ * leases; the spawned child makes first contact and closes the B2 pickup
23
+ * window. A failed hand-off lapses back via that window instead of sitting
24
+ * claimed.
25
+ *
26
+ * METERING (decision 3): free capacity `k = cap − liveInFlight`, where
27
+ * liveInFlight counts every live child record, each one pid-probed (see
28
+ * state.ts). When `k <= 0` the loop skips `whats_next` but remembers that the
29
+ * adopted wake still needs a sweep. Orders already returned by `whats_next`
30
+ * are already claimed, so over-cap orders enter an in-memory queue and dispatch
31
+ * as soon as local child capacity frees; waiting for another hub wake would
32
+ * strand those claims until pickup expiry.
33
+ *
34
+ * RESILIENCE: presence/wake/whats_next failures are logged and never kill the
35
+ * loop. `stop()` flips a flag checked between awaits; the in-flight sweep
36
+ * finishes, `run()` resolves 0, and no hub call is made afterward. Detached
37
+ * children are never killed on shutdown — that is the drain semantic.
38
+ *
39
+ * LEGACY PINNED-HASH DISPATCH (E, DD-4): the old wire shape omits both `worker`
40
+ * and `defDigest` and serves only a def NAME. Only that explicitly legacy shape
41
+ * uses `readDispatchBundle(cacheDir, defName)`: 0 pins → latest; exactly 1 pinned
42
+ * hash → that frozen version; >1 conflicting pins → refuse and leave the orders
43
+ * for the pickup window. Modern orders route from authoritative `worker` plus
44
+ * exact `defDigest`; modern command metadata is verified through
45
+ * `resolveOrderStep`, and modern agent metadata is resolved by `agent-run`.
46
+ *
47
+ * LIVE SHIFT IDENTITY: `name`/`serveCrews` on `ShiftLoopOptions` are INITIAL
48
+ * values only. The loop holds them as live closure state (`getShift`/`setShift`
49
+ * on `ShiftLoop`) so the shift socket's `clock_in` operation can change what a
50
+ * shift is called and which crews it serves without rebuilding the loop —
51
+ * `setShift` also resets the presence timer so the new identity reaches the hub
52
+ * on the very next `iterate()`.
53
+ */
54
+ import { join } from 'node:path';
55
+ import { performance } from 'node:perf_hooks';
56
+ import { acquireFileLockSync, releaseFileLock } from "../../../../src/lock.js";
57
+ import { readDispatchBundle } from "../bundle/cache.js";
58
+ import { HubError } from "../hub/types.js";
59
+ import { isCommandStep, resolveCommandRouting } from "./routing.js";
60
+ import { cancelReservedChild, finalizeChildReservation, reconcileInFlight, reserveChild, startReservedChild, removeChildRecord, ensureStateDir, } from "./state.js";
61
+ import { DEFAULT_WORK_DIR_TTL_MS, sweepWorkDirs as sweepWorkDirsImpl } from "../agent/workdir.js";
62
+ import { sessionsPath } from "../harness/session-store.js";
63
+ /** The `maxConcurrentAgents` fallback when the option is absent. */
64
+ const DEFAULT_MAX_AGENTS = 4;
65
+ /**
66
+ * The hub reaps a never-contacted claim after 120 seconds. Stop local queueing
67
+ * after 90 seconds so a detached child retains 30 seconds to make first contact.
68
+ */
69
+ export const MAX_PENDING_CANDIDATE_AGE_MS = 90_000;
70
+ function errMsg(e) {
71
+ return e instanceof Error ? e.message : String(e);
72
+ }
73
+ /** The explicit hub refusal produced when an inbox row becomes terminal after
74
+ * the inbox snapshot but before its targeted serving call. This is a normal
75
+ * stale-candidate race, not a Shift failure worth retrying forever. */
76
+ function isNonServableRace(e) {
77
+ return e instanceof HubError
78
+ && e.status === 403
79
+ && e.code === 'forbidden'
80
+ && e.message.includes('non-running instance is not servable');
81
+ }
82
+ export function createShiftLoop(opts) {
83
+ let stopped = false;
84
+ let cap = opts.cap;
85
+ const isAlive = opts.isAlive;
86
+ const monotonicNow = opts.monotonicNow ?? performance.now.bind(performance);
87
+ // Live shift identity (MCP `clock_in`, D3-D7 of the plan). Seeded from opts,
88
+ // which are now INITIAL values only. Arrays are copied so neither the loop
89
+ // nor a caller of getShift/setShift can mutate the other's state afterward.
90
+ let shiftName = opts.name;
91
+ let serveCrews = [...opts.serveCrews];
92
+ // Park state persists across `iterate()` calls (the MCP park reuses it).
93
+ let cursor;
94
+ let lastPresence = Number.NEGATIVE_INFINITY;
95
+ let attendedAt;
96
+ /**
97
+ * Orders returned by `whats_next` are already claimed. If the hub returns more
98
+ * orders than this process can spawn, retain those claims locally until a child
99
+ * exits and capacity opens. Waiting for another wake cannot work: no hub event
100
+ * is required when a local child exits, and `tick` will not re-return a claim
101
+ * that is already in flight.
102
+ */
103
+ const pendingCandidates = new Map();
104
+ /** A changed wake whose sweep was skipped or failed must be retried after the
105
+ * cursor is adopted; otherwise the next unchanged wake hides that work. */
106
+ let sweepOwed = false;
107
+ /** Earliest server-approved time for the next polling iteration. */
108
+ let backoffUntil = Number.NEGATIVE_INFINITY;
109
+ /** Bumped whenever a ping starts or is forced due, so a ping that completes
110
+ * after a force does not stamp the cadence over that force. */
111
+ let presenceGeneration = 0;
112
+ function noteServerBackoff(error) {
113
+ if (!(error instanceof HubError) || error.status !== 429)
114
+ return false;
115
+ const delay = error.retryAfterMs ?? opts.pollIntervalMs;
116
+ backoffUntil = Math.max(backoffUntil, monotonicNow() + delay);
117
+ return true;
118
+ }
119
+ function emit(event) {
120
+ if (opts.onEvent === undefined)
121
+ return;
122
+ try {
123
+ opts.onEvent(event);
124
+ }
125
+ catch (e) {
126
+ opts.err(`shift event sink failed: ${errMsg(e)} (continuing)`);
127
+ }
128
+ }
129
+ function reconcile() {
130
+ const result = reconcileInFlight(opts.stateDir, {
131
+ ...(isAlive !== undefined ? { isAlive } : {}),
132
+ now: opts.now(),
133
+ });
134
+ for (const rec of result.reaped) {
135
+ emit({
136
+ type: 'reaped',
137
+ workflow: rec.workflow,
138
+ run: rec.run,
139
+ kind: rec.kind ?? 'exec',
140
+ pid: rec.pid,
141
+ });
142
+ }
143
+ for (const reservation of result.abandoned) {
144
+ opts.err(`[${reservation.workflow}/${reservation.run}] abandoned ${reservation.childKind} dispatch reservation expired and was cancelled`);
145
+ }
146
+ return result;
147
+ }
148
+ /**
149
+ * Recheck shared capacity and create the per-run reservation while holding one
150
+ * state-directory-wide lock. The lock ends before spawn: the durable
151
+ * reservation, not a long critical section, protects capacity during spawn.
152
+ */
153
+ function reserveCandidate(c) {
154
+ const childKind = c.kind === 'command' ? 'exec' : 'agent-run';
155
+ const dispatchLock = acquireFileLockSync(join(opts.stateDir, '.dispatch.lock'), {
156
+ waitMs: 30_000,
157
+ label: 'owenloop Shift dispatch',
158
+ });
159
+ try {
160
+ const fresh = reconcileInFlight(opts.stateDir, {
161
+ ...(isAlive === undefined ? {} : { isAlive }),
162
+ now: opts.now(),
163
+ });
164
+ if (fresh.live.some((record) => record.run === c.order.run) ||
165
+ fresh.reserved.some((record) => record.run === c.order.run))
166
+ return 'duplicate';
167
+ if (fresh.live.length + fresh.reserved.length >= cap)
168
+ return 'total-capacity';
169
+ if (childKind === 'agent-run') {
170
+ const agents = fresh.live.filter((record) => record.kind === 'agent-run').length +
171
+ fresh.reserved.filter((record) => record.childKind === 'agent-run').length;
172
+ if (agents >= (opts.maxConcurrentAgents ?? DEFAULT_MAX_AGENTS))
173
+ return 'agent-capacity';
174
+ }
175
+ return reserveChild(opts.stateDir, {
176
+ workflow: c.workflow,
177
+ run: c.order.run,
178
+ reservedAt: opts.now(),
179
+ childKind,
180
+ step: c.order.step,
181
+ });
182
+ }
183
+ finally {
184
+ releaseFileLock(dispatchLock);
185
+ }
186
+ }
187
+ function dispatchCandidate(c) {
188
+ const childKind = c.kind === 'command' ? 'exec' : 'agent-run';
189
+ let reservation;
190
+ let cancel;
191
+ try {
192
+ const reserved = reserveCandidate(c);
193
+ if (typeof reserved === 'string')
194
+ return reserved;
195
+ reservation = reserved.reservation;
196
+ const spawned = opts.spawner({
197
+ workflow: c.workflow,
198
+ run: c.order.run,
199
+ step: c.order.step,
200
+ ...(childKind === 'agent-run' ? { kind: 'agent-run' } : {}),
201
+ startGate: reserved.gatePath,
202
+ });
203
+ cancel = spawned.cancel ?? spawned.terminate;
204
+ const rec = finalizeChildReservation(opts.stateDir, reservation, {
205
+ pid: spawned.pid,
206
+ spawnedAt: opts.now(),
207
+ kind: childKind,
208
+ ...(childKind === 'agent-run' && c.defName !== undefined ? { def: c.defName } : {}),
209
+ ...(childKind === 'agent-run' && c.defHash !== undefined ? { hash: c.defHash } : {}),
210
+ ...(childKind === 'agent-run' ? { step: c.order.step } : {}),
211
+ });
212
+ startReservedChild(opts.stateDir, rec);
213
+ emit({
214
+ type: 'dispatched',
215
+ workflow: c.workflow,
216
+ run: c.order.run,
217
+ step: c.order.step,
218
+ kind: childKind,
219
+ pid: spawned.pid,
220
+ });
221
+ opts.out(`dispatched ${c.kind === 'command' ? 'command' : 'agent-run'} ${c.workflow}/${c.order.run} ` +
222
+ `(step '${c.order.step}', pid ${spawned.pid})`);
223
+ return 'dispatched';
224
+ }
225
+ catch (e) {
226
+ cancel?.();
227
+ if (reservation !== undefined) {
228
+ try {
229
+ cancelReservedChild(opts.stateDir, reservation);
230
+ }
231
+ catch (cleanupError) {
232
+ opts.err(`[${c.workflow}/${c.order.run}] failed to cancel dispatch reservation: ${errMsg(cleanupError)}`);
233
+ }
234
+ }
235
+ const message = errMsg(e);
236
+ emit({
237
+ type: 'failed',
238
+ workflow: c.workflow,
239
+ run: c.order.run,
240
+ step: c.order.step,
241
+ kind: childKind,
242
+ message,
243
+ });
244
+ const prefix = c.kind === 'command' ? 'spawn' : 'agent-run spawn';
245
+ opts.err(`${prefix} for ${c.workflow}/${c.order.run} failed: ${message}`);
246
+ return 'failed';
247
+ }
248
+ }
249
+ function discardExpiredCandidate(candidate, queued) {
250
+ if (monotonicNow() - candidate.requestStartedAt < MAX_PENDING_CANDIDATE_AGE_MS)
251
+ return false;
252
+ const prefix = queued ? 'queued claim' : 'claim';
253
+ opts.err(`[${candidate.workflow}/${candidate.order.run}] ${prefix} expired before local dispatch — leaving the hub pickup window to re-offer it`);
254
+ return true;
255
+ }
256
+ /** Dispatch already-claimed orders when local child capacity becomes free. */
257
+ function drainPending(live, reserved) {
258
+ let remaining = cap - live.length - reserved.length;
259
+ if (remaining <= 0 || pendingCandidates.size === 0)
260
+ return 0;
261
+ const maxAgents = opts.maxConcurrentAgents ?? DEFAULT_MAX_AGENTS;
262
+ let agentRoom = maxAgents -
263
+ live.filter((r) => r.kind === 'agent-run').length -
264
+ reserved.filter((r) => r.childKind === 'agent-run').length;
265
+ const liveRuns = new Set([...live.map((r) => r.run), ...reserved.map((r) => r.run)]);
266
+ let dispatched = 0;
267
+ for (const [run, candidate] of pendingCandidates) {
268
+ if (remaining <= 0)
269
+ break;
270
+ if (discardExpiredCandidate(candidate, true)) {
271
+ pendingCandidates.delete(run);
272
+ continue;
273
+ }
274
+ if (liveRuns.has(run)) {
275
+ pendingCandidates.delete(run);
276
+ continue;
277
+ }
278
+ // The agent lane's second budget can be full while the dispatch cap still
279
+ // has room. Skip this entry and KEEP it queued (a command entry further
280
+ // down the map is still dispatchable) — `continue`, never `break`, so one
281
+ // blocked agent does not head-of-line-block the whole queue.
282
+ if (candidate.kind === 'agent' && agentRoom <= 0)
283
+ continue;
284
+ const result = dispatchCandidate(candidate);
285
+ if (result === 'total-capacity')
286
+ break;
287
+ if (result === 'agent-capacity')
288
+ continue;
289
+ pendingCandidates.delete(run);
290
+ if (result !== 'dispatched')
291
+ continue;
292
+ dispatched++;
293
+ remaining--;
294
+ liveRuns.add(run);
295
+ if (candidate.kind === 'agent')
296
+ agentRoom--;
297
+ }
298
+ return dispatched;
299
+ }
300
+ /**
301
+ * One sweep. Collects dispatch candidates across the target instance(s)
302
+ * within the free-capacity `budget`, then dispatches by kind: a command order
303
+ * spawns a detached `owenloop work exec` child, an agent order a detached
304
+ * `owenloop work agent-run` child. Returns how many children were spawned, plus the
305
+ * polled/open-run sets the work-dir reaper needs.
306
+ */
307
+ async function sweep(budget, live, reserved) {
308
+ let dispatched = 0;
309
+ /**
310
+ * PHASE 4, for the work-dir reaper only. `polled` is the set of workflows
311
+ * whose `whats_next` SUCCEEDED this sweep — a workflow whose call threw is
312
+ * deliberately left out, because a failed call is not evidence that a run
313
+ * has no open order, and the reaper must never treat silence as absence.
314
+ * `openRuns` is every run those calls reported an order for, including ones
315
+ * this shift declined to dispatch (capacity, routing, an in-flight worker):
316
+ * an order the shift left alone is still an open order, and its run's work
317
+ * directory must survive.
318
+ */
319
+ const polled = new Set();
320
+ const openRuns = new Set();
321
+ let complete = true;
322
+ let remaining = budget;
323
+ const liveRuns = new Set([...live.map((r) => r.run), ...reserved.map((r) => r.run)]);
324
+ // The agent lane's SECOND budget (D7). Counted from live records and durable
325
+ // reservations, so a crash between reservation and spawn cannot overbook it.
326
+ // A child or reservation that is reaped frees the slot on the next reconcile.
327
+ const maxAgents = opts.maxConcurrentAgents ?? DEFAULT_MAX_AGENTS;
328
+ let agentRoom = maxAgents -
329
+ live.filter((r) => r.kind === 'agent-run').length -
330
+ reserved.filter((r) => r.childKind === 'agent-run').length;
331
+ /**
332
+ * Runs that ALREADY have a live `agent-run` child. An agent-run child is a
333
+ * PROCESS: re-dispatching one would put a second harness session on a single
334
+ * claim — two step agents briefed for the same order, racing to submit. So a
335
+ * re-offer for a run a worker already holds is skipped outright, the way the
336
+ * command lane does it.
337
+ */
338
+ const workerRuns = new Set([
339
+ ...live.filter((r) => r.kind === 'agent-run').map((r) => r.run),
340
+ ...reserved.filter((r) => r.childKind === 'agent-run').map((r) => r.run),
341
+ ]);
342
+ // Resolve which instances to poll.
343
+ let instances;
344
+ if (opts.workflow !== undefined) {
345
+ instances = [opts.workflow];
346
+ }
347
+ else {
348
+ try {
349
+ const inbox = await opts.hub.whatsNext();
350
+ instances = (inbox.instances ?? []).map((i) => i.workflow);
351
+ }
352
+ catch (e) {
353
+ noteServerBackoff(e);
354
+ opts.err(`inbox whats_next failed: ${errMsg(e)}`);
355
+ return { dispatched, polled, openRuns, complete: false };
356
+ }
357
+ }
358
+ // Collect candidates, metering NEW dispatches and deduping in-flight.
359
+ const claimed = new Set();
360
+ const candidates = [];
361
+ for (const wf of instances) {
362
+ let res;
363
+ const requestStartedAt = monotonicNow();
364
+ try {
365
+ res = await opts.hub.whatsNext({ workflow: wf, serve_crews: serveCrews });
366
+ }
367
+ catch (e) {
368
+ if (isNonServableRace(e)) {
369
+ // Treat the targeted call as a successful empty observation for the
370
+ // work-dir reaper and consume this wake. A later hub event may list
371
+ // new work, but this stale terminal row must not force every poll to
372
+ // repeat the same ForbiddenError.
373
+ polled.add(wf);
374
+ opts.out(`[${wf}] skipped stale terminal inbox candidate`);
375
+ continue;
376
+ }
377
+ const rateLimited = noteServerBackoff(e);
378
+ complete = false;
379
+ opts.err(`whats_next for ${wf} failed: ${errMsg(e)}`);
380
+ if (rateLimited)
381
+ break;
382
+ continue;
383
+ }
384
+ const orders = res.orders ?? [];
385
+ polled.add(wf);
386
+ for (const o of orders)
387
+ openRuns.add(o.run);
388
+ const defName = res.def;
389
+ const legacyOrders = orders.filter((order) => !Object.prototype.hasOwnProperty.call(order, 'worker') &&
390
+ !Object.prototype.hasOwnProperty.call(order, 'defDigest'));
391
+ // The definition-name cache exists only for the explicitly identified old
392
+ // wire shape. Modern orders route from `worker` and exact `defDigest`.
393
+ const dispatch = legacyOrders.length > 0 && defName !== undefined
394
+ ? readDispatchBundle(opts.cacheDir, defName)
395
+ : { bundle: null };
396
+ const bundle = dispatch.bundle;
397
+ if (legacyOrders.length > 0 && dispatch.warning !== undefined) {
398
+ opts.err(`[${wf}] ${dispatch.warning}`);
399
+ }
400
+ else if (legacyOrders.length > 0 && bundle === null && defName !== undefined) {
401
+ opts.err(`no cached bundle for def '${defName}' — run \`owenloop work prepare ${defName}\` (legacy orders left for pickup)`);
402
+ }
403
+ for (const order of orders) {
404
+ if (claimed.has(order.run))
405
+ continue; // seen this sweep
406
+ if (pendingCandidates.has(order.run))
407
+ continue; // already claimed and queued locally
408
+ const reoffer = liveRuns.has(order.run);
409
+ const workerPresent = Object.prototype.hasOwnProperty.call(order, 'worker');
410
+ const digestPresent = Object.prototype.hasOwnProperty.call(order, 'defDigest');
411
+ const legacy = !workerPresent && !digestPresent;
412
+ let step;
413
+ let kind;
414
+ let candidateDefName;
415
+ let candidateDefHash;
416
+ if (legacy) {
417
+ step = bundle?.def.steps.find((candidate) => candidate.name === order.step);
418
+ if (step === undefined || bundle === null)
419
+ continue;
420
+ kind = isCommandStep(step) ? 'command' : 'agent';
421
+ candidateDefName = defName;
422
+ candidateDefHash = bundle.def.hash;
423
+ }
424
+ else {
425
+ if (typeof order.defDigest !== 'string' || order.defDigest.trim() === '') {
426
+ opts.err(`[${wf}/${order.run}] malformed modern work order: non-empty defDigest is required whenever modern routing metadata is present — leaving for manual pickup`);
427
+ claimed.add(order.run);
428
+ continue;
429
+ }
430
+ // The deployed projection omits `worker` for the default executor. That
431
+ // shape is a modern AGENT order because `defDigest` pins the exact step;
432
+ // only an explicitly authored executor produces `worker` on the wire.
433
+ if (!workerPresent || order.worker === 'agent') {
434
+ kind = 'agent';
435
+ }
436
+ else if (order.worker === 'command') {
437
+ kind = 'command';
438
+ try {
439
+ step = await opts.resolveOrderStep?.(order);
440
+ }
441
+ catch (error) {
442
+ opts.err(`[${wf}/${order.run}] exact command instructions for digest '${order.defDigest}' failed verification: ${errMsg(error)} — leaving for manual pickup`);
443
+ claimed.add(order.run);
444
+ continue;
445
+ }
446
+ if (step === undefined) {
447
+ opts.err(`[${wf}/${order.run}] exact command routing metadata for digest '${order.defDigest}' is unavailable — leaving for manual pickup`);
448
+ claimed.add(order.run);
449
+ continue;
450
+ }
451
+ }
452
+ else if (typeof order.worker !== 'string' || order.worker.trim() === '') {
453
+ opts.err(`[${wf}/${order.run}] malformed modern work order: worker must be absent, 'agent', or 'command' — leaving for manual pickup`);
454
+ claimed.add(order.run);
455
+ continue;
456
+ }
457
+ else {
458
+ opts.err(`[${wf}/${order.run}] unsupported worker '${order.worker}' — leaving for manual pickup`);
459
+ claimed.add(order.run);
460
+ continue;
461
+ }
462
+ }
463
+ if (kind === 'command') {
464
+ // A command already in flight (or durably reserved) is never respawned.
465
+ if (reoffer)
466
+ continue;
467
+ if (step === undefined)
468
+ continue;
469
+ const routing = resolveCommandRouting(opts.commandRouting, step);
470
+ for (const warning of routing.warnings)
471
+ opts.err(`[${wf}/${order.run}] ${warning}`);
472
+ if (!routing.autoDispatch) {
473
+ opts.out(`[${wf}/${order.run}] command step '${order.step}' routed to manual — leaving for pickup window`);
474
+ continue;
475
+ }
476
+ const candidate = {
477
+ order,
478
+ workflow: wf,
479
+ step,
480
+ defName: candidateDefName,
481
+ defHash: candidateDefHash,
482
+ kind,
483
+ requestStartedAt,
484
+ reoffer,
485
+ };
486
+ if (discardExpiredCandidate(candidate, false)) {
487
+ claimed.add(order.run);
488
+ continue;
489
+ }
490
+ if (remaining <= 0) {
491
+ pendingCandidates.set(order.run, candidate);
492
+ opts.out(`[${wf}/${order.run}] at the dispatch cap (${cap}) — queued for local dispatch`);
493
+ }
494
+ else {
495
+ remaining--;
496
+ candidates.push(candidate);
497
+ }
498
+ claimed.add(order.run);
499
+ continue;
500
+ }
501
+ // Agent wire routing is authoritative. The detached agent-run resolves its
502
+ // own exact step and harness from the order digest, never from this cache.
503
+ if (workerRuns.has(order.run))
504
+ continue;
505
+ const candidate = {
506
+ order,
507
+ workflow: wf,
508
+ step: legacy ? step : undefined,
509
+ defName: candidateDefName,
510
+ defHash: candidateDefHash,
511
+ kind,
512
+ requestStartedAt,
513
+ reoffer,
514
+ };
515
+ if (discardExpiredCandidate(candidate, false)) {
516
+ claimed.add(order.run);
517
+ continue;
518
+ }
519
+ if (!reoffer && remaining <= 0) {
520
+ pendingCandidates.set(order.run, candidate);
521
+ opts.out(`[${wf}/${order.run}] at the dispatch cap (${cap}) — queued for local dispatch`);
522
+ }
523
+ else if (!reoffer && agentRoom <= 0) {
524
+ pendingCandidates.set(order.run, candidate);
525
+ opts.out(`[${wf}/${order.run}] at the agent-run cap (${maxAgents}) — queued for local dispatch`);
526
+ }
527
+ else {
528
+ if (!reoffer) {
529
+ remaining--;
530
+ agentRoom--;
531
+ }
532
+ candidates.push(candidate);
533
+ }
534
+ claimed.add(order.run);
535
+ }
536
+ }
537
+ for (const candidate of candidates) {
538
+ if (discardExpiredCandidate(candidate, false))
539
+ continue;
540
+ const result = dispatchCandidate(candidate);
541
+ if (result === 'dispatched') {
542
+ dispatched++;
543
+ continue;
544
+ }
545
+ if (result === 'total-capacity' || result === 'agent-capacity') {
546
+ pendingCandidates.set(candidate.order.run, candidate);
547
+ const limit = result === 'total-capacity'
548
+ ? `dispatch cap (${cap})`
549
+ : `agent-run cap (${opts.maxConcurrentAgents ?? DEFAULT_MAX_AGENTS})`;
550
+ opts.out(`[${candidate.workflow}/${candidate.order.run}] lost a shared-capacity race at the ${limit} — queued for local dispatch`);
551
+ }
552
+ }
553
+ return { dispatched, polled, openRuns, complete };
554
+ }
555
+ /**
556
+ * PHASE 4 — remove the per-run work directories of runs that are over.
557
+ *
558
+ * The three inputs, and where each comes from:
559
+ * - `workflows` = `swept.polled`, the workflows whose `whats_next` succeeded.
560
+ * - `openRunIds` = `swept.openRuns`, every run those calls reported an order
561
+ * for, dispatched or not.
562
+ * - `liveRunIds` = the runs of live `agent-run` records, pid-probed by
563
+ * `reconcileInFlight`. Only `agent-run` records are counted: those are the
564
+ * only children that hold a work directory — an `exec` child works in the
565
+ * shift's own cwd.
566
+ *
567
+ * The fourth input is `sessionsFile`: `<cacheDir>/sessions.jsonl`, the same
568
+ * path `owenloop work agent-run` writes its session records to (`src/roles/
569
+ * agent-run.ts` builds it from the SAME `resolveCacheDir`). The sweep marks
570
+ * every session of a reaped run `dead` there BEFORE removing its directory —
571
+ * session lifetime equals cwd lifetime, and without that write the next firing
572
+ * of the step would resume into a recreated, empty directory.
573
+ *
574
+ * Best effort throughout — a removal failure is reported and the sweep goes on.
575
+ * Disabled entirely when `workRoot` is unset.
576
+ */
577
+ function reapWorkDirs(swept, liveAfter) {
578
+ const workRoot = opts.workRoot;
579
+ if (workRoot === undefined || workRoot === '' || swept === undefined)
580
+ return;
581
+ if (swept.polled.size === 0)
582
+ return;
583
+ const doSweep = opts.sweepWorkDirs ?? sweepWorkDirsImpl;
584
+ const liveRunIds = new Set(liveAfter.filter((r) => r.kind === 'agent-run').map((r) => r.run));
585
+ let removed;
586
+ try {
587
+ removed = doSweep({
588
+ workRoot,
589
+ workflows: swept.polled,
590
+ openRunIds: swept.openRuns,
591
+ liveRunIds,
592
+ now: opts.now(),
593
+ ttlMs: opts.workDirTtlMs ?? DEFAULT_WORK_DIR_TTL_MS,
594
+ sessionsFile: sessionsPath(opts.cacheDir),
595
+ ...(opts.workRepo !== undefined ? { workRepo: opts.workRepo } : {}),
596
+ err: opts.err,
597
+ });
598
+ }
599
+ catch (e) {
600
+ opts.err(`work-dir reaper failed: ${errMsg(e)} (ignored)`);
601
+ return;
602
+ }
603
+ for (const dir of removed)
604
+ opts.out(`reaped work directory ${dir}`);
605
+ }
606
+ async function iteration() {
607
+ const backoffActiveAtStart = monotonicNow() < backoffUntil;
608
+ let rateLimitedThisIteration = false;
609
+ // Presence when due (starts immediately — this shift exists to conduct).
610
+ // A server backoff suppresses every hub poll, including presence, while local
611
+ // reconciliation and queued dispatch continue below.
612
+ if (!backoffActiveAtStart &&
613
+ monotonicNow() - lastPresence >= opts.presenceIntervalMs) {
614
+ // `setShift` and `noteAttended` force the next ping by setting
615
+ // lastPresence to -Infinity. Either can land WHILE this ping is awaiting
616
+ // the hub, so record the generation first: on completion, only stamp the
617
+ // cadence if no force arrived in the meantime. Stamping unconditionally
618
+ // would swallow that sentinel and defer the newly recorded attendance or
619
+ // identity by a full presenceIntervalMs.
620
+ const generation = ++presenceGeneration;
621
+ try {
622
+ await opts.hub.presencePing({
623
+ name: shiftName,
624
+ serve_crews: serveCrews,
625
+ ...(opts.shiftId !== undefined ? { shift_id: opts.shiftId } : {}),
626
+ ...(opts.startedAt !== undefined ? { started_at: opts.startedAt } : {}),
627
+ ...(attendedAt !== undefined ? { attended_at: attendedAt } : {}),
628
+ });
629
+ if (generation === presenceGeneration)
630
+ lastPresence = monotonicNow();
631
+ }
632
+ catch (e) {
633
+ rateLimitedThisIteration = noteServerBackoff(e);
634
+ opts.err(`presence ping failed: ${errMsg(e)} (continuing)`);
635
+ }
636
+ }
637
+ // Reconcile in-flight first. A child exit is local state, not a hub event,
638
+ // so use the freed slot to dispatch claims retained from an earlier sweep
639
+ // before consulting the wake cursor.
640
+ let inFlight = reconcile();
641
+ let dispatched = drainPending(inFlight.live, inFlight.reserved);
642
+ if (dispatched > 0)
643
+ inFlight = reconcile();
644
+ const live = inFlight.live;
645
+ const reserved = inFlight.reserved;
646
+ const occupied = live.length + reserved.length;
647
+ const k = cap - occupied;
648
+ // Retry-After suppresses every remaining hub call in the iteration that
649
+ // received it, and every hub call in later iterations before the deadline.
650
+ // Local child reconciliation and queued-claim dispatch above still run.
651
+ if (backoffActiveAtStart ||
652
+ rateLimitedThisIteration ||
653
+ monotonicNow() < backoffUntil) {
654
+ return dispatched;
655
+ }
656
+ // Cheap wake pre-check. A failed call also suppresses a forced retry for this
657
+ // tick: a rate-limited wake should not immediately be followed by whats_next.
658
+ let changed = false;
659
+ let wakeSucceeded = false;
660
+ try {
661
+ const w = await opts.hub.wake(cursor);
662
+ changed = w.changed;
663
+ cursor = w.cursor;
664
+ wakeSucceeded = true;
665
+ }
666
+ catch (e) {
667
+ noteServerBackoff(e);
668
+ opts.err(`wake failed: ${errMsg(e)} (retrying next tick)`);
669
+ }
670
+ // A changed cursor is not sufficient by itself: if the prior changed tick
671
+ // had no local capacity, or its sweep failed, the adopted cursor will be
672
+ // unchanged next time. `sweepOwed` preserves that unconsumed work signal.
673
+ let swept;
674
+ if (wakeSucceeded && (changed || sweepOwed) && k > 0) {
675
+ swept = await sweep(k, live, reserved);
676
+ sweepOwed = !swept.complete;
677
+ }
678
+ else if (changed && k <= 0) {
679
+ sweepOwed = true;
680
+ opts.out(`at capacity (${occupied}/${cap} in flight) — deferring whats_next until capacity is free`);
681
+ }
682
+ const liveAfter = reconcile().live;
683
+ // PHASE 4 — the work-directory reaper.
684
+ //
685
+ // ONLY ON A TICK THAT ACTUALLY SWEPT. The gate's first condition is "the hub
686
+ // reports no open order for this run", and the only thing that can support
687
+ // that claim is a fresh `whats_next` order list. A tick that skipped the
688
+ // sweep (nothing changed, or no free capacity) has no such list, and running
689
+ // the gate against a stale or empty one would read "no orders" as "no open
690
+ // orders" and delete live work. Skipping costs nothing: the next sweeping
691
+ // tick reaps whatever is still reapable.
692
+ reapWorkDirs(swept, liveAfter);
693
+ dispatched += swept?.dispatched ?? 0;
694
+ return dispatched;
695
+ }
696
+ async function run() {
697
+ ensureStateDir(opts.stateDir);
698
+ if (opts.once === true) {
699
+ await iteration();
700
+ return 0;
701
+ }
702
+ for (;;) {
703
+ if (stopped)
704
+ return 0;
705
+ await iteration();
706
+ if (stopped)
707
+ return 0;
708
+ const delay = Math.max(opts.pollIntervalMs, backoffUntil - monotonicNow());
709
+ await opts.sleep(delay);
710
+ // Re-check after the park so a stop during sleep makes no further hub call.
711
+ if (stopped)
712
+ return 0;
713
+ }
714
+ }
715
+ function stop() {
716
+ stopped = true;
717
+ }
718
+ return {
719
+ run,
720
+ stop,
721
+ iterate: iteration,
722
+ freeCapacity: () => {
723
+ const current = reconcile();
724
+ return cap - current.live.length - current.reserved.length;
725
+ },
726
+ getCap: () => cap,
727
+ setCap: (next) => {
728
+ cap = next;
729
+ },
730
+ getShift: () => ({ name: shiftName, serveCrews: [...serveCrews] }),
731
+ setShift: (next) => {
732
+ if (next.name !== undefined)
733
+ shiftName = next.name;
734
+ if (next.serveCrews !== undefined)
735
+ serveCrews = [...next.serveCrews];
736
+ lastPresence = Number.NEGATIVE_INFINITY; // D6: next iterate() pings immediately
737
+ presenceGeneration++; // survive an in-flight ping completing after this
738
+ return { name: shiftName, serveCrews: [...serveCrews] };
739
+ },
740
+ noteAttended: (at) => {
741
+ attendedAt = at;
742
+ lastPresence = Number.NEGATIVE_INFINITY;
743
+ presenceGeneration++; // survive an in-flight ping completing after this
744
+ },
745
+ getAttendedAt: () => attendedAt,
746
+ noteRunEnded: (run) => {
747
+ pendingCandidates.delete(run);
748
+ removeChildRecord(opts.stateDir, run);
749
+ },
750
+ };
751
+ }