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,332 @@
1
+ /**
2
+ * The exec orchestration core (C5) — the detached, self-leasing command worker.
3
+ *
4
+ * A command order the shift (C3) dispatched becomes a detached `owenloop work exec`
5
+ * process. This core drives its whole life against the hub, every side effect
6
+ * injected (hub client, command runner, sleep/clock, output sinks) so tests run
7
+ * it with a fake hub + fake runner and no real timers or child processes:
8
+ *
9
+ * 1. FIRST CONTACT — starts the shared lease loop (`src/lease/loop.ts`) with the
10
+ * exec holder tag `{kind:'exec', id}` (the B3 drain exemption: exec-held
11
+ * claims survive a session drain). The loop's first `get_order` beats the
12
+ * lease and delivers the order packet via `onOrder`; the loop then keeps the
13
+ * lease warm underneath everything below.
14
+ * 2. VALIDATE — a `null` packet, a non-`command` worker, or a missing/empty
15
+ * `owes` list is a MISROUTE (plan decision 3): not exec's to fail (a Step
16
+ * Agent could legitimately run it), so a targeted release, no submit, exit 1.
17
+ * A command worker's `defDigest` is then resolved through the verified local
18
+ * workflow store. Missing or corrupt instructions are a named refusal, not a
19
+ * misroute, and no child process is started.
20
+ * 3. RUN + RACE — the runner shells the command out while the lease loop runs.
21
+ * Whichever settles first wins (plan decision 9):
22
+ * - an ordinary command settles (any exit code, or a machinery error) ⇒
23
+ * build a receipt and `submit` it to every owed path. A payload reject
24
+ * follows those submits. Exit 0 means the receipt/reject delivery won;
25
+ * the receipt's exit code still carries the command result.
26
+ * - a judge command exits 0 ⇒ submit its receipt; a non-zero exit ⇒ send
27
+ * `reject` for `order.judge` without a receipt; signal or machinery
28
+ * failure ⇒ no verdict, leave the claim for the reap path.
29
+ * - lease goes terminal first (lease-lost / ownership-error / unreachable /
30
+ * the engine closed the run) ⇒ kill the command's process group, NO
31
+ * submit (a submit would race the re-offer), exit 1.
32
+ * 4. FINAL BREATH — a SIGINT/SIGTERM aimed at exec itself is an operator killing
33
+ * the work (drain only exempts exec from the SESSION's death): `stop()` kills
34
+ * the command group and takes a targeted release, exit 1 (plan decision 1).
35
+ * Killed work NEVER gets a receipt — even when the TERM'd command settles
36
+ * before the release round-trip resolves the lease (the common ordering),
37
+ * the submit path checks `signalled` and bails to `killed`.
38
+ *
39
+ * The role (`src/roles/exec.ts`) maps each `ExecOutcome` to an exit code.
40
+ */
41
+ import { createHash } from 'node:crypto';
42
+ import { createLeaseLoop } from "../lease/loop.js";
43
+ import { parsePayloadLine } from "./payload.js";
44
+ import { buildReceipt } from "./receipt.js";
45
+ import { buildSubmitProof } from "../submit-proof.js";
46
+ /** sha256 of the empty byte string — the hash for a run with no captured output. */
47
+ const EMPTY_HASH = createHash('sha256').digest('hex');
48
+ function errMsg(e) {
49
+ return e instanceof Error ? e.message : String(e);
50
+ }
51
+ export function createExecLoop(opts) {
52
+ const { hub, runner, workflow } = opts;
53
+ const runId = opts.run;
54
+ let running;
55
+ let signalled = false;
56
+ let leasePromise;
57
+ let resolveOrder;
58
+ const orderReady = new Promise((r) => {
59
+ resolveOrder = r;
60
+ });
61
+ const lease = createLeaseLoop({
62
+ hub,
63
+ workflow,
64
+ run: runId,
65
+ role: 'exec',
66
+ holder: opts.holder,
67
+ onOrder: (res) => resolveOrder?.(res),
68
+ sleep: opts.sleep,
69
+ now: opts.now,
70
+ out: opts.out,
71
+ err: opts.err,
72
+ ...(opts.random !== undefined ? { random: opts.random } : {}),
73
+ ...(opts.heartbeatIntervalMs !== undefined ? { heartbeatIntervalMs: opts.heartbeatIntervalMs } : {}),
74
+ ...(opts.jumpToleranceMs !== undefined ? { jumpToleranceMs: opts.jumpToleranceMs } : {}),
75
+ ...(opts.failureWindowMs !== undefined ? { failureWindowMs: opts.failureWindowMs } : {}),
76
+ });
77
+ /** A CommandResult standing in for a runner that threw before producing one. */
78
+ function machineryFailure(e) {
79
+ const t = opts.now();
80
+ return {
81
+ exitCode: null,
82
+ error: errMsg(e),
83
+ outputHash: `sha256:${EMPTY_HASH}`,
84
+ stdoutBytes: 0,
85
+ stderrBytes: 0,
86
+ outputTail: '',
87
+ startedAt: t,
88
+ finishedAt: t,
89
+ durationMs: 0,
90
+ };
91
+ }
92
+ /** A first-contact / no-hold lease outcome → exec outcome. */
93
+ function mapNoHold(o) {
94
+ switch (o) {
95
+ case 'completed':
96
+ return 'completed';
97
+ case 'ownership-error':
98
+ return 'ownership-error';
99
+ case 'hub-unreachable':
100
+ return 'hub-unreachable';
101
+ case 'lease-lost':
102
+ return 'lease-lost';
103
+ case 'stopped':
104
+ return signalled ? 'killed' : 'stopped';
105
+ case 'released':
106
+ case 'release-failed':
107
+ // stop() with release fired before the hold was ever established.
108
+ return 'killed';
109
+ }
110
+ }
111
+ /** A lease outcome observed while the command was running (exit 1 always). */
112
+ function mapLeaseDuringRun(o) {
113
+ if (o === 'ownership-error')
114
+ return 'ownership-error';
115
+ if (o === 'hub-unreachable')
116
+ return 'hub-unreachable';
117
+ return 'lease-lost';
118
+ }
119
+ /** Deliver one reject verb and settle the lease after the response arrives. */
120
+ async function issueReject(path, text, successOutcome) {
121
+ try {
122
+ const res = await hub.reject({ workflow, run: runId, path, text });
123
+ if (res.ok !== true) {
124
+ opts.err(`owenloop work exec: reject of ${path} was refused: ${res.text}`);
125
+ lease.stop('reject-failed', res.closed === true ? { release: false } : undefined);
126
+ await leasePromise;
127
+ return 'reject-failed';
128
+ }
129
+ // A closed response means the hub already ended the claiming run. For a
130
+ // non-closed reject, release the still-open claim before this worker exits.
131
+ lease.stop(successOutcome, res.closed === true ? { release: false } : undefined);
132
+ await leasePromise;
133
+ return successOutcome;
134
+ }
135
+ catch (e) {
136
+ opts.err(`owenloop work exec: reject of ${path} failed: ${errMsg(e)}`);
137
+ // Receipts, when any, are already committed. Do not retry blindly or
138
+ // pretend the reject landed.
139
+ lease.stop('reject-failed');
140
+ await leasePromise;
141
+ return 'reject-failed';
142
+ }
143
+ }
144
+ /** Build the receipt and submit it to every owed path. */
145
+ async function submitReceipt(result, order, resolvedCommand) {
146
+ if (signalled) {
147
+ // The operator killed the work and the command settled before the lease
148
+ // (the release HTTP round-trip is slower than a TERM'd child dying), so
149
+ // the done branch won the race. Plan decision 1: NO receipt for killed
150
+ // work — a submit here would race the release/re-offer. stop() already
151
+ // took the targeted release; just wait for it.
152
+ opts.err(`owenloop work exec: signalled — killed work gets no receipt, released ${workflow}/${runId}`);
153
+ await leasePromise;
154
+ return 'killed';
155
+ }
156
+ const parsedPayload = parsePayloadLine(result.payloadLine, result.payloadOverCap);
157
+ if (order.judge !== undefined) {
158
+ if (result.exitCode === null) {
159
+ // A signal or machinery failure is not a verdict. Leave the claim for
160
+ // the engine's reap path rather than releasing a silent judgement.
161
+ opts.err(`owenloop work exec: judge ${order.judge} ended without a verdict`);
162
+ lease.stop('judge-no-verdict', { release: false });
163
+ await leasePromise;
164
+ return 'judge-no-verdict';
165
+ }
166
+ if (result.exitCode !== 0) {
167
+ // Judge payload directives are deliberately ignored: one judge order
168
+ // has one verdict, and the command exit code supplies that verdict.
169
+ let text = result.outputTail;
170
+ if (parsedPayload.payload !== undefined && typeof parsedPayload.payload === 'object' && parsedPayload.payload !== null && !Array.isArray(parsedPayload.payload)) {
171
+ const reason = parsedPayload.payload['reason'];
172
+ if (typeof reason === 'string' && reason.trim() !== '')
173
+ text = reason;
174
+ }
175
+ if (text === '')
176
+ text = `judge command exited with code ${result.exitCode}`;
177
+ return issueReject(order.judge, text, 'judge-rejected');
178
+ }
179
+ }
180
+ const receipt = buildReceipt(result, {
181
+ command: resolvedCommand,
182
+ orchestrator: opts.holder.id,
183
+ workflow,
184
+ run: runId,
185
+ step: order.step,
186
+ }, parsedPayload);
187
+ for (const owe of order.owes) {
188
+ let res;
189
+ try {
190
+ let proof;
191
+ if (opts.origin !== undefined) {
192
+ // The immutable order can authorize a judge proof only when the owed
193
+ // path is the fingerprinted judged artifact. Producer command receipts
194
+ // remain unsigned until the hub issues a retry-safe target version.
195
+ proof = await buildSubmitProof({
196
+ origin: opts.origin,
197
+ order,
198
+ path: owe.path,
199
+ value: receipt,
200
+ now: opts.now,
201
+ warn: opts.err,
202
+ ...(opts.principalKeys !== undefined ? { principalKeys: opts.principalKeys } : {}),
203
+ ...(opts.env !== undefined ? { env: opts.env } : {}),
204
+ ...(opts.sshProcess !== undefined ? { sshProcess: opts.sshProcess } : {}),
205
+ });
206
+ }
207
+ res = await hub.submit({
208
+ workflow,
209
+ run: runId,
210
+ path: owe.path,
211
+ value: receipt,
212
+ ...(proof !== undefined ? { proof } : {}),
213
+ holder: opts.holder,
214
+ });
215
+ }
216
+ catch (e) {
217
+ opts.err(`owenloop work exec: submit to ${owe.path} failed: ${errMsg(e)}`);
218
+ lease.stop('submit-failed'); // targeted release (idempotent) — best effort
219
+ await leasePromise;
220
+ return 'submit-failed';
221
+ }
222
+ const outcome = res.outcome;
223
+ if (outcome !== 'green' && outcome !== 'submitted') {
224
+ opts.err(`owenloop work exec: submit to ${owe.path} rejected (${outcome ?? 'unknown'}): ${res.text}`);
225
+ // born-rejected ⇒ the claim is already gone, no release; otherwise a
226
+ // targeted release is idempotent and harmless.
227
+ lease.stop('submit-rejected', outcome === 'born-rejected' ? { release: false } : undefined);
228
+ await leasePromise;
229
+ return 'submit-rejected';
230
+ }
231
+ opts.out(`owenloop work exec: submitted receipt to ${owe.path} (${outcome})`);
232
+ }
233
+ if (order.judge === undefined && parsedPayload.reject !== undefined) {
234
+ // All owed submissions must land before invalidating a consumed input;
235
+ // rejection moves the consume fingerprint and would born-reject later
236
+ // submits from this run.
237
+ return issueReject(parsedPayload.reject.path, parsedPayload.reject.text, 'rejected');
238
+ }
239
+ // Every owed path landed — the run has closed, so stop WITHOUT releasing.
240
+ lease.stop('submitted', { release: false });
241
+ await leasePromise;
242
+ return 'submitted';
243
+ }
244
+ async function run() {
245
+ leasePromise = lease.run();
246
+ // First contact race: the order arrives (hold established), or the lease
247
+ // resolves terminally before we ever established it.
248
+ const first = await Promise.race([
249
+ orderReady.then((res) => ({ t: 'order', res })),
250
+ leasePromise.then((o) => ({ t: 'lease', o })),
251
+ ]);
252
+ if (first.t === 'lease')
253
+ return mapNoHold(first.o);
254
+ const order = first.res.order;
255
+ if (order === null ||
256
+ order.worker !== 'command' ||
257
+ !Array.isArray(order.owes) ||
258
+ order.owes.length === 0) {
259
+ opts.err(`owenloop work exec: ${workflow}/${runId} is not a command order (misroute) — releasing`);
260
+ lease.stop('misroute'); // targeted release — not exec's to fail
261
+ await leasePromise;
262
+ return 'misroute';
263
+ }
264
+ let resolvedCommand;
265
+ let resolvedBundleDir;
266
+ try {
267
+ const resolved = await opts.instructions.resolveCommand(order);
268
+ if (!resolved.ok) {
269
+ opts.err(`owenloop work exec: ${resolved.reason}`);
270
+ lease.stop('unresolved-instructions');
271
+ await leasePromise;
272
+ return 'unresolved-instructions';
273
+ }
274
+ resolvedCommand = resolved.command;
275
+ resolvedBundleDir = resolved.bundleDir;
276
+ }
277
+ catch (e) {
278
+ opts.err(`owenloop work exec: instruction refusal (integrity) for ${workflow}/${runId} ` +
279
+ `defDigest '${order.defDigest}': ${errMsg(e)}`);
280
+ lease.stop('unresolved-instructions');
281
+ await leasePromise;
282
+ return 'unresolved-instructions';
283
+ }
284
+ // Run the command and race it against the lease going terminal.
285
+ let cmd;
286
+ try {
287
+ // spawn's env replaces the child environment. Start from the actual exec
288
+ // process environment so config-only opts.env cannot strip PATH/HOME, then
289
+ // explicitly remove bundle provenance for loose definitions.
290
+ const childEnv = { ...process.env };
291
+ if (resolvedBundleDir === undefined)
292
+ delete childEnv['OWENLOOP_BUNDLE_DIR'];
293
+ else
294
+ childEnv['OWENLOOP_BUNDLE_DIR'] = resolvedBundleDir;
295
+ // Run identity is engine-derived from ExecLoopOptions, never a consumed
296
+ // artifact value, and always present. Overwrite inherited values so a
297
+ // nested exec sees its own identity rather than its parent's.
298
+ childEnv['OWENLOOP_WORKFLOW'] = workflow;
299
+ childEnv['OWENLOOP_RUN'] = runId;
300
+ const startOptions = { cwd: order.workdir ?? opts.cwd, env: childEnv };
301
+ cmd = runner.start(resolvedCommand, startOptions);
302
+ }
303
+ catch (e) {
304
+ return submitReceipt(machineryFailure(e), order, resolvedCommand);
305
+ }
306
+ running = cmd;
307
+ opts.out(`owenloop work exec: running ${workflow}/${runId} (step '${order.step}')`);
308
+ const outcome = await Promise.race([
309
+ cmd.done.then((r) => ({ t: 'done', r })).catch((e) => ({ t: 'done', r: machineryFailure(e) })),
310
+ leasePromise.then((o) => ({ t: 'lease', o })),
311
+ ]);
312
+ if (outcome.t === 'lease') {
313
+ await cmd.kill(); // no receipt — a submit now would race the re-offer
314
+ if (signalled) {
315
+ opts.err(`owenloop work exec: signalled mid-run — killed the command group, released ${workflow}/${runId}`);
316
+ return 'killed';
317
+ }
318
+ opts.err(`owenloop work exec: lease ${outcome.o} while the command ran — killed the command, no receipt submitted`);
319
+ return mapLeaseDuringRun(outcome.o);
320
+ }
321
+ return submitReceipt(outcome.r, order, resolvedCommand);
322
+ }
323
+ function stop(reason) {
324
+ if (signalled)
325
+ return;
326
+ signalled = true;
327
+ if (running !== undefined)
328
+ void running.kill();
329
+ lease.stop(reason ?? 'signal'); // release:true — hand the killed order back
330
+ }
331
+ return { run, stop };
332
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The command payload channel. The runner only captures the bounded raw text
3
+ * after the marker; this module parses that text and validates the one
4
+ * worker-to-hub directive supported by exec.
5
+ */
6
+ /** The exact line prefix a command must print on stdout to emit a payload. */
7
+ export declare const PAYLOAD_MARKER = "##owenloop:payload##";
8
+ /** Maximum UTF-8 byte length of the JSON text after the marker. */
9
+ export declare const PAYLOAD_MAX_BYTES: number;
10
+ export interface RejectDirective {
11
+ path: string;
12
+ text: string;
13
+ }
14
+ export interface ParsedPayload {
15
+ /** Present when the marker contained valid JSON, including `null`/primitives. */
16
+ payload?: unknown;
17
+ /** Present when the marker or its reject directive could not be used. */
18
+ payloadError?: string;
19
+ /** Present only for a strictly valid reject directive. */
20
+ reject?: RejectDirective;
21
+ }
22
+ /**
23
+ * Parse the raw text after `PAYLOAD_MARKER`.
24
+ *
25
+ * `overCap` comes from the runner's bounded scanner. It is separate from the
26
+ * string because the scanner must not retain more than the cap just to report
27
+ * that a later byte made the line too large.
28
+ */
29
+ export declare function parsePayloadLine(payloadLine?: string, overCap?: boolean): ParsedPayload;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The command payload channel. The runner only captures the bounded raw text
3
+ * after the marker; this module parses that text and validates the one
4
+ * worker-to-hub directive supported by exec.
5
+ */
6
+ /** The exact line prefix a command must print on stdout to emit a payload. */
7
+ export const PAYLOAD_MARKER = '##owenloop:payload##';
8
+ /** Maximum UTF-8 byte length of the JSON text after the marker. */
9
+ export const PAYLOAD_MAX_BYTES = 64 * 1024;
10
+ function isRecord(value) {
11
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
12
+ }
13
+ function hasNonEmptyString(value) {
14
+ return typeof value === 'string' && value.trim().length > 0;
15
+ }
16
+ /**
17
+ * Parse the raw text after `PAYLOAD_MARKER`.
18
+ *
19
+ * `overCap` comes from the runner's bounded scanner. It is separate from the
20
+ * string because the scanner must not retain more than the cap just to report
21
+ * that a later byte made the line too large.
22
+ */
23
+ export function parsePayloadLine(payloadLine, overCap = false) {
24
+ if (overCap)
25
+ return { payloadError: `payload JSON exceeds the ${PAYLOAD_MAX_BYTES / 1024} KiB cap` };
26
+ if (payloadLine === undefined)
27
+ return {};
28
+ const jsonText = payloadLine.trim();
29
+ if (jsonText === '')
30
+ return { payloadError: 'payload marker has no JSON text' };
31
+ if (Buffer.byteLength(jsonText, 'utf8') > PAYLOAD_MAX_BYTES) {
32
+ return { payloadError: `payload JSON exceeds the ${PAYLOAD_MAX_BYTES / 1024} KiB cap` };
33
+ }
34
+ let payload;
35
+ try {
36
+ payload = JSON.parse(jsonText);
37
+ }
38
+ catch (error) {
39
+ const message = error instanceof Error ? error.message : String(error);
40
+ return { payloadError: `payload JSON is malformed: ${message}` };
41
+ }
42
+ if (!isRecord(payload) || !('reject' in payload))
43
+ return { payload };
44
+ const rawReject = payload['reject'];
45
+ if (!isRecord(rawReject)) {
46
+ return { payload, payloadError: 'payload reject directive must be an object' };
47
+ }
48
+ const path = rawReject['path'];
49
+ const text = rawReject['text'];
50
+ if (!hasNonEmptyString(path) || !hasNonEmptyString(text)) {
51
+ return { payload, payloadError: 'payload reject directive requires non-empty string path and text' };
52
+ }
53
+ return { payload, reject: { path, text } };
54
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The command receipt (C5, plan decision 8) — the audit record exec submits for
3
+ * an ordinary command order, and for a judge order that exits 0. The hub `submit`
4
+ * verb has no failure channel, so a non-zero `exitCode` (or `exitCode: null` +
5
+ * `error` for machinery failure) carries the command result. A non-zero judge
6
+ * exit uses `reject` instead of a receipt, and signal-killed work submits neither.
7
+ * Pure construction so it is trivially asserted in tests.
8
+ */
9
+ import { type ParsedPayload } from './payload.ts';
10
+ import type { CommandResult } from './runner.ts';
11
+ /** The submitted artifact value for a command order. */
12
+ export interface CommandReceipt {
13
+ kind: 'command-receipt';
14
+ command: string;
15
+ exitCode: number | null;
16
+ signal?: string;
17
+ error?: string;
18
+ outputHash: string;
19
+ stdoutBytes: number;
20
+ stderrBytes: number;
21
+ outputTail: string;
22
+ payload?: unknown;
23
+ payloadError?: string;
24
+ startedAt: number;
25
+ finishedAt: number;
26
+ durationMs: number;
27
+ /** The holder id of the exec process that ran it (`<hostname>:<pid>`). */
28
+ orchestrator: string;
29
+ workflow: string;
30
+ run: string;
31
+ step: string;
32
+ }
33
+ export interface ReceiptContext {
34
+ command: string;
35
+ orchestrator: string;
36
+ workflow: string;
37
+ run: string;
38
+ step: string;
39
+ }
40
+ /** Fold a raw `CommandResult` and its order context into the submitted receipt. */
41
+ export declare function buildReceipt(result: CommandResult, ctx: ReceiptContext, parsedPayload?: ParsedPayload): CommandReceipt;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The command receipt (C5, plan decision 8) — the audit record exec submits for
3
+ * an ordinary command order, and for a judge order that exits 0. The hub `submit`
4
+ * verb has no failure channel, so a non-zero `exitCode` (or `exitCode: null` +
5
+ * `error` for machinery failure) carries the command result. A non-zero judge
6
+ * exit uses `reject` instead of a receipt, and signal-killed work submits neither.
7
+ * Pure construction so it is trivially asserted in tests.
8
+ */
9
+ import { parsePayloadLine } from "./payload.js";
10
+ /** Fold a raw `CommandResult` and its order context into the submitted receipt. */
11
+ export function buildReceipt(result, ctx, parsedPayload = parsePayloadLine(result.payloadLine, result.payloadOverCap)) {
12
+ return {
13
+ kind: 'command-receipt',
14
+ command: ctx.command,
15
+ exitCode: result.exitCode,
16
+ ...(result.signal !== undefined ? { signal: result.signal } : {}),
17
+ ...(result.error !== undefined ? { error: result.error } : {}),
18
+ outputHash: result.outputHash,
19
+ stdoutBytes: result.stdoutBytes,
20
+ stderrBytes: result.stderrBytes,
21
+ outputTail: result.outputTail,
22
+ ...('payload' in parsedPayload ? { payload: parsedPayload.payload } : {}),
23
+ ...(parsedPayload.payloadError !== undefined ? { payloadError: parsedPayload.payloadError } : {}),
24
+ startedAt: result.startedAt,
25
+ finishedAt: result.finishedAt,
26
+ durationMs: result.durationMs,
27
+ orchestrator: ctx.orchestrator,
28
+ workflow: ctx.workflow,
29
+ run: ctx.run,
30
+ step: ctx.step,
31
+ };
32
+ }
@@ -0,0 +1,71 @@
1
+ /** The raw execution facts a run produces; the loop wraps these into a receipt. */
2
+ export interface CommandResult {
3
+ /** The command's exit code, or `null` when killed by signal / machinery failed. */
4
+ exitCode: number | null;
5
+ /** The signal that terminated the command, when it was signalled. */
6
+ signal?: string;
7
+ /** Set only on execution-machinery failure (spawn/cwd/error) — not a non-zero exit. */
8
+ error?: string;
9
+ /**
10
+ * `sha256:<hex>` over full stdout bytes then full stderr bytes, or — when
11
+ * out-of-order stderr overflowed the 1 MiB buffer cap — the two-part
12
+ * `sha256:<stdout hex>+<stderr hex>` (each stream hashed fully on its own).
13
+ */
14
+ outputHash: string;
15
+ stdoutBytes: number;
16
+ stderrBytes: number;
17
+ /** Last ≤4 KiB of combined stdout+stderr, decoded lossily as UTF-8. */
18
+ outputTail: string;
19
+ /** Raw text after the last matching stdout payload marker, before JSON parsing. */
20
+ payloadLine?: string;
21
+ /** True when the last matching marker line exceeded the payload cap. */
22
+ payloadOverCap?: boolean;
23
+ startedAt: number;
24
+ finishedAt: number;
25
+ durationMs: number;
26
+ }
27
+ /** A command that is running (or has failed to start). */
28
+ export interface RunningCommand {
29
+ /** Resolves once the command settles (any exit code, kill, or machinery error). */
30
+ done: Promise<CommandResult>;
31
+ /** Idempotently take down the command's process group (TERM → grace → KILL). */
32
+ kill(): Promise<void>;
33
+ }
34
+ /** The runner seam. Injected into the exec loop; faked in the loop's tests. */
35
+ export interface CommandRunner {
36
+ start(command: string, opts: {
37
+ cwd: string;
38
+ env?: Record<string, string | undefined>;
39
+ }): RunningCommand;
40
+ }
41
+ /** The fully-resolved spawn arguments — pure data, asserted directly in tests. */
42
+ export interface CommandPlan {
43
+ command: string;
44
+ args: string[];
45
+ options: {
46
+ cwd: string;
47
+ detached: true;
48
+ stdio: ['ignore', 'pipe', 'pipe'];
49
+ env?: Record<string, string | undefined>;
50
+ };
51
+ }
52
+ /**
53
+ * Build the argv + options for a detached `/bin/sh -c <command>`. Pure — no
54
+ * spawn, no I/O — so tests assert the shape without launching anything. POSIX
55
+ * `/bin/sh` keeps the default runner portable (ubuntu-latest CI, macOS dev).
56
+ */
57
+ export declare function buildCommandPlan(command: string, cwd: string, env?: Record<string, string | undefined>): CommandPlan;
58
+ export interface DefaultRunnerOptions {
59
+ /** SIGTERM→SIGKILL grace on a group kill (default 5_000). */
60
+ graceMs?: number;
61
+ /** Clock seam (default `Date.now`). */
62
+ now?: () => number;
63
+ /** Timer seam for the kill grace (default real `setTimeout`). */
64
+ sleep?: (ms: number) => Promise<void>;
65
+ }
66
+ /**
67
+ * The default command runner: spawns `/bin/sh -c <command>` in its own process
68
+ * group and captures a bounded result. Every timing/timer seam is injectable so
69
+ * the kill-grace path is testable without wall-clock waits.
70
+ */
71
+ export declare function createDefaultRunner(opts?: DefaultRunnerOptions): CommandRunner;