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,319 @@
1
+ /**
2
+ * Phase 4 — per-RUN agent working directories, and the gate that removes them.
3
+ *
4
+ * ── WHAT A WORK DIRECTORY IS ──
5
+ *
6
+ * One directory per RUN, at `<workRoot>/<workflow>/<run>/`. Every step of a run
7
+ * shares it. That is deliberate and load-bearing twice over:
8
+ *
9
+ * 1. A downstream step can read what an upstream step wrote, which per-STEP
10
+ * directories would make impossible without copying.
11
+ * 2. The removal question collapses from "does any pending downstream step
12
+ * consume this output?" (a `consumes` / `expected_outputs` walk, with a false
13
+ * negative for any step the hub has not offered yet) into "does this run
14
+ * still have an open order?" — one set membership test.
15
+ *
16
+ * ── THE THREE-STEP CWD PRECEDENCE ──
17
+ *
18
+ * 1. `OrderPacket.workdir`, when the hub set it. The hub always wins.
19
+ * 2. Otherwise `<workRoot>/<workflow>/<run>/`, created on first use.
20
+ * 3. Otherwise (no `workRoot` resolvable) the dispatching process's own cwd,
21
+ * which is the pre-Phase-4 behaviour.
22
+ *
23
+ * A directory reached by rule 1 is the HUB's, not owenloop's, and `reapWorkDir`
24
+ * refuses to touch it — see `isUnderWorkRoot`.
25
+ *
26
+ * ── PLAIN DIR VS GIT WORKTREE ──
27
+ *
28
+ * `workRepo` (a settings key, machine-local) decides. Unset ⇒ `mkdir -p`. Set ⇒
29
+ * `git worktree add`. It is machine-local rather than workflow-declared because
30
+ * nothing in `src/bundle/types.ts` or `src/hub/types.ts` lets a workflow declare
31
+ * a repo, and adding a field there would be a hub protocol change — an explicit
32
+ * effort non-goal.
33
+ *
34
+ * Failure stance: provisioning propagates its failure (a worker with no place to
35
+ * work should say so); REMOVAL is best-effort and never throws, because it runs
36
+ * inside the shift sweep and a sweep must not die over a directory.
37
+ */
38
+ import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs';
39
+ import { spawnSync } from 'node:child_process';
40
+ import { isAbsolute, join, relative, resolve } from 'node:path';
41
+ import { markRunSessionsDead } from "../harness/session-store.js";
42
+ /**
43
+ * `<workRoot>/<workflow>/<run>` — the one place the layout is spelled out.
44
+ * Pure: no I/O, so callers can compute a path without creating anything.
45
+ */
46
+ export function runWorkDir(workRoot, workflow, run) {
47
+ return join(workRoot, workflow, run);
48
+ }
49
+ /**
50
+ * Resolve the work root: `OWENLOOP_WORK_ROOT` > `settings.workRoot` >
51
+ * `<cacheDir>/work`. Mirrors `resolveCacheDir`'s precedence shape exactly, so
52
+ * there is one rule to remember for both.
53
+ */
54
+ export function resolveWorkRoot(env, settingsWorkRoot, cacheDir) {
55
+ const override = env['OWENLOOP_WORK_ROOT'];
56
+ if (override !== undefined && override.trim() !== '')
57
+ return override;
58
+ if (settingsWorkRoot !== undefined && settingsWorkRoot.trim() !== '')
59
+ return settingsWorkRoot;
60
+ return join(cacheDir, 'work');
61
+ }
62
+ /** `OWENLOOP_WORK_REPO` > `settings.workRepo` > none. */
63
+ export function resolveWorkRepo(env, settingsWorkRepo) {
64
+ const override = env['OWENLOOP_WORK_REPO'];
65
+ if (override !== undefined && override.trim() !== '')
66
+ return override;
67
+ if (settingsWorkRepo !== undefined && settingsWorkRepo.trim() !== '')
68
+ return settingsWorkRepo;
69
+ return undefined;
70
+ }
71
+ /**
72
+ * Is `dir` inside `root`? The guard that keeps removal to directories owenloop
73
+ * created.
74
+ *
75
+ * Both paths are resolved to absolutes first, so a relative `workRoot` or a
76
+ * `..`-bearing directory cannot smuggle a path outside the root past the check.
77
+ * `dir === root` returns FALSE on purpose: the root itself holds every other
78
+ * run's directory and must never be removed.
79
+ */
80
+ export function isUnderWorkRoot(dir, workRoot) {
81
+ const rel = relative(resolve(workRoot), resolve(dir));
82
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
83
+ }
84
+ function defaultRunGit(args, cwd) {
85
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8' });
86
+ return { status: r.status, output: `${r.stdout ?? ''}${r.stderr ?? ''}`.trim() };
87
+ }
88
+ /**
89
+ * Create (or adopt) the per-run work directory and return its absolute path.
90
+ *
91
+ * IDEMPOTENT. Every step of a run calls this, and the second and later calls
92
+ * must be no-ops that hand back the same directory — that is the whole point of
93
+ * a per-run directory. An existing directory is therefore adopted, never
94
+ * recreated and never cleaned.
95
+ *
96
+ * WORKTREE MODE. `git worktree add -b <branch> <dir>` against `workRepo`. A
97
+ * failure DEGRADES to a plain directory rather than failing the order: the agent
98
+ * can still work, it just does not get git isolation, and the reason is reported.
99
+ * The alternative — refusing the order — would turn a misconfigured `workRepo`
100
+ * into a stuck run, which is strictly worse than a degraded one.
101
+ */
102
+ export function ensureWorkDir(o) {
103
+ const dir = runWorkDir(o.workRoot, o.workflow, o.run);
104
+ if (existsSync(dir))
105
+ return dir;
106
+ if (o.workRepo !== undefined && o.workRepo !== '') {
107
+ mkdirSync(join(dir, '..'), { recursive: true });
108
+ const branch = o.branch ?? `owenloop/${o.workflow}/${o.run}`;
109
+ const git = o.runGit ?? defaultRunGit;
110
+ const added = git(['worktree', 'add', '-b', branch, dir], o.workRepo);
111
+ if (added.status === 0)
112
+ return dir;
113
+ // A re-run against an existing branch is the common second failure; try once
114
+ // without `-b` before giving up on worktree mode.
115
+ const reused = git(['worktree', 'add', dir, branch], o.workRepo);
116
+ if (reused.status === 0)
117
+ return dir;
118
+ o.err?.(`owenloop work: git worktree add for ${o.workflow}/${o.run} failed (${added.output || 'no output'}) — using a plain directory instead`);
119
+ }
120
+ mkdirSync(dir, { recursive: true });
121
+ return dir;
122
+ }
123
+ // ---- the removal gate -------------------------------------------------------
124
+ /**
125
+ * Default grace window before an idle work directory may be reaped: 1 hour.
126
+ *
127
+ * A run momentarily between orders (delivered, waiting on the next step) still
128
+ * owns its directory, so the sweep must not remove it the instant the child
129
+ * exits. One hour is deliberately coarse — the cost of keeping a stale directory
130
+ * an hour longer is disk, while the cost of removing a live one is a lost
131
+ * working tree.
132
+ */
133
+ export const DEFAULT_WORK_DIR_TTL_MS = 60 * 60 * 1000;
134
+ /**
135
+ * May this run's work directory be removed?
136
+ *
137
+ * PURE — no filesystem, no hub, no clock. That is what lets the truth table be a
138
+ * unit test instead of an integration test.
139
+ *
140
+ * True only when ALL THREE hold:
141
+ * - the hub reports NO open order for the run (`!openRunIds.has(runId)`), and
142
+ * - no live `agent-run` child holds it (`!liveRunIds.has(runId)`), and
143
+ * - the grace window has elapsed (`now - lastSeenAt >= ttlMs`).
144
+ *
145
+ * WHY THE GRACE WINDOW. At the instant a step submits, its downstream orders
146
+ * usually are not open yet. A gate with no TTL would see "no open orders, no live
147
+ * child" in exactly that gap and delete the directory a moment before the next
148
+ * step needs it.
149
+ *
150
+ * WHY THIS RUNS IN THE SHIFT SWEEP AND NOT IN THE WORKER AT EXIT: same reason,
151
+ * from the other side. A worker asking "is anything still open?" as it exits is
152
+ * asking during that gap, every time.
153
+ */
154
+ export function isWorkDirReapable(g) {
155
+ if (g.openRunIds.has(g.runId))
156
+ return false;
157
+ if (g.liveRunIds.has(g.runId))
158
+ return false;
159
+ return g.now - g.lastSeenAt >= g.ttlMs;
160
+ }
161
+ /**
162
+ * Remove one per-run work directory. BEST EFFORT — never throws, so a sweep can
163
+ * call it in a loop without a try/catch per entry.
164
+ *
165
+ * - `'refused'`: the path is not under `workRoot`. This is the guard that keeps
166
+ * a hub-supplied `OrderPacket.workdir` — someone else's directory, which
167
+ * owenloop did not create — out of reach no matter what the gate said.
168
+ * - `'absent'`: nothing there; already gone.
169
+ * - `'removed'` / `'failed'`: the removal ran and did or did not succeed.
170
+ *
171
+ * Worktree mode removes with `git worktree remove --force`; if git refuses (a
172
+ * dirty tree it will not discard, a repo that has forgotten the worktree), it
173
+ * falls back to `git worktree prune` plus `rm -rf`, so the directory goes away
174
+ * and the repo's worktree list does not keep a dangling entry.
175
+ */
176
+ export function reapWorkDir(o) {
177
+ if (!isUnderWorkRoot(o.dir, o.workRoot))
178
+ return 'refused';
179
+ if (!existsSync(o.dir))
180
+ return 'absent';
181
+ if (o.workRepo !== undefined && o.workRepo !== '') {
182
+ const git = o.runGit ?? defaultRunGit;
183
+ try {
184
+ const removed = git(['worktree', 'remove', '--force', o.dir], o.workRepo);
185
+ if (removed.status === 0)
186
+ return 'removed';
187
+ git(['worktree', 'prune'], o.workRepo);
188
+ }
189
+ catch (e) {
190
+ o.err?.(`owenloop work: git worktree remove ${o.dir} failed (${String(e)}) — falling back to rm`);
191
+ }
192
+ }
193
+ try {
194
+ rmSync(o.dir, { recursive: true, force: true });
195
+ return 'removed';
196
+ }
197
+ catch (e) {
198
+ o.err?.(`owenloop work: could not remove work directory ${o.dir}: ${String(e)} (ignored)`);
199
+ return 'failed';
200
+ }
201
+ }
202
+ /**
203
+ * Every `<workRoot>/<workflow>/<run>` directory for the given workflows.
204
+ *
205
+ * SCOPED TO `workflows` ON PURPOSE, not a blind walk of `workRoot`. A shift
206
+ * started with `--workflow wf1` only ever learns which of wf1's orders are open;
207
+ * it knows nothing about wf2's. Letting it consider wf2's directories would mean
208
+ * judging them against an order list that structurally cannot mention them —
209
+ * every one would look abandoned. So the sweep sees only what the caller has
210
+ * evidence about.
211
+ *
212
+ * Unreadable directories are skipped rather than thrown over; the sweep is
213
+ * best-effort throughout.
214
+ */
215
+ export function listWorkDirs(workRoot, workflows) {
216
+ const out = [];
217
+ for (const workflow of workflows) {
218
+ const wfDir = join(workRoot, workflow);
219
+ let runs;
220
+ try {
221
+ runs = readdirSync(wfDir);
222
+ }
223
+ catch {
224
+ continue; // no directory for this workflow yet
225
+ }
226
+ for (const runId of runs) {
227
+ const dir = join(wfDir, runId);
228
+ try {
229
+ const st = statSync(dir);
230
+ if (!st.isDirectory())
231
+ continue;
232
+ out.push({ workflow, runId, dir, lastSeenAt: st.mtimeMs });
233
+ }
234
+ catch {
235
+ continue;
236
+ }
237
+ }
238
+ }
239
+ return out;
240
+ }
241
+ /**
242
+ * Apply `isWorkDirReapable` to every candidate, RETIRE that run's sessions, and
243
+ * remove the ones that pass. Returns the directories actually removed, so a
244
+ * caller can log a count.
245
+ *
246
+ * ── SESSION LIFETIME = CWD LIFETIME (the teardown gate) ──
247
+ *
248
+ * Removing the directory is only half the gate. A session record for the same
249
+ * `(workflow, run, step)` outlives the directory in `sessions.jsonl`, and the
250
+ * next firing of that step RECREATES the directory at the same path
251
+ * (`ensureWorkDir` is idempotent by design), which defeats the worker's
252
+ * `dirExists(prev.cwd)` and `prev.cwd === recordCwd` guards on its own. So every
253
+ * session of the run is marked `dead` here — `src/agent/loop.ts` refuses to
254
+ * resume a `dead` record, which is what makes resume impossible past this point
255
+ * BY CONSTRUCTION rather than by a liveness check that can be raced.
256
+ *
257
+ * ORDER IS FAIL-SAFE, RETIRE FIRST: if the retire write fails, the directory is
258
+ * LEFT IN PLACE and the entry is skipped for this sweep, so the invariant "a
259
+ * removed work directory has no live session record" cannot be broken by a
260
+ * crash between the two writes. The opposite order (remove, then retire) has a
261
+ * window in which the invariant is already false. A retire that succeeds and a
262
+ * removal that then fails costs only a cold replay next firing — the safe
263
+ * direction to be wrong.
264
+ *
265
+ * KNOWN LIMITATION, stated rather than hidden: `lastSeenAt` is the run
266
+ * directory's own mtime, which a write deep inside a subdirectory does not
267
+ * update. It is therefore a weak "last touched" signal, and it is deliberately
268
+ * only the THIRD condition — a run with an open order or a live child is already
269
+ * protected by the first two regardless of how stale its mtime looks.
270
+ */
271
+ export function sweepWorkDirs(o) {
272
+ const list = o.list ?? listWorkDirs;
273
+ const remove = o.remove ?? reapWorkDir;
274
+ const retire = o.retire ?? markRunSessionsDead;
275
+ const removed = [];
276
+ let entries;
277
+ try {
278
+ entries = list(o.workRoot, o.workflows);
279
+ }
280
+ catch (e) {
281
+ o.err?.(`owenloop work: could not scan work directories under ${o.workRoot}: ${String(e)} (ignored)`);
282
+ return removed;
283
+ }
284
+ for (const e of entries) {
285
+ const reapable = isWorkDirReapable({
286
+ runId: e.runId,
287
+ openRunIds: o.openRunIds,
288
+ liveRunIds: o.liveRunIds,
289
+ lastSeenAt: e.lastSeenAt,
290
+ now: o.now,
291
+ ttlMs: o.ttlMs,
292
+ });
293
+ if (!reapable)
294
+ continue;
295
+ if (o.sessionsFile !== undefined && o.sessionsFile !== '') {
296
+ try {
297
+ const steps = retire(o.sessionsFile, e.workflow, e.runId, o.now, {
298
+ ...(o.err !== undefined ? { warn: o.err } : {}),
299
+ });
300
+ if (steps.length > 0) {
301
+ o.err?.(`owenloop work: retired ${String(steps.length)} session record${steps.length === 1 ? '' : 's'} for ${e.workflow}/${e.runId} (${steps.join(', ')}) — its work directory is being removed`);
302
+ }
303
+ }
304
+ catch (err) {
305
+ o.err?.(`owenloop work: could not retire the sessions for ${e.workflow}/${e.runId}: ${String(err)} — leaving ${e.dir} in place this sweep`);
306
+ continue; // fail-safe: never remove a directory whose sessions still read live
307
+ }
308
+ }
309
+ const result = remove({
310
+ dir: e.dir,
311
+ workRoot: o.workRoot,
312
+ ...(o.workRepo !== undefined ? { workRepo: o.workRepo } : {}),
313
+ ...(o.err !== undefined ? { err: o.err } : {}),
314
+ });
315
+ if (result === 'removed')
316
+ removed.push(e.dir);
317
+ }
318
+ return removed;
319
+ }
@@ -0,0 +1,92 @@
1
+ import type { CachedBundle, FetchedDef, NormalizedStepSpec } from './types.ts';
2
+ /** Resolve the cache root from env → settings → XDG → HOME. */
3
+ export declare function resolveCacheDir(env: Record<string, string | undefined>, settingsCacheDir?: string): string;
4
+ /** `<cacheDir>/bundles/<name>` — the dir holding every hash for one workflow. */
5
+ export declare function workflowDir(cacheDir: string, name: string): string;
6
+ /** `<cacheDir>/bundles/<name>/<hash>` — one specific cached def revision. */
7
+ export declare function hashDir(cacheDir: string, name: string, hash: string): string;
8
+ /**
9
+ * Write a cached bundle + its normalized step specs under the hash dir. Returns
10
+ * the hash dir path. Overwrites are fine — atomic per file. Each spec lands at
11
+ * `steps/<spec.step>.json`.
12
+ */
13
+ export declare function writeBundle(cacheDir: string, bundle: CachedBundle, specs: NormalizedStepSpec[]): string;
14
+ /**
15
+ * Read a cached bundle for `(name, hash)`, or `null` when absent or corrupt.
16
+ * A corrupt `bundle.json` is treated as absent (refetch), not an error — a
17
+ * cache read must never harden into a failure the user cannot clear by
18
+ * re-fetching.
19
+ */
20
+ export declare function readBundle(cacheDir: string, name: string, hash: string): CachedBundle | null;
21
+ /**
22
+ * Read the most-recently-fetched cached bundle for `name`, or `null` when none
23
+ * is cached. After a prepare only one hash dir survives (the others are pruned),
24
+ * but if several exist the newest by `fetchedAt` wins. Corrupt `bundle.json`
25
+ * files are skipped, not fatal.
26
+ */
27
+ export declare function readLatestBundle(cacheDir: string, name: string): CachedBundle | null;
28
+ /**
29
+ * Read the normalized step spec for `(name, hash, step)`, or `null` when it is
30
+ * absent, unreadable, or not valid JSON. Layout mirrors `writeBundle`:
31
+ * `<cacheDir>/bundles/<name>/<hash>/steps/<step>.json`.
32
+ *
33
+ * A missing or corrupt spec returns `null` — a command step has no spec by
34
+ * design, and a hash dir prepared before Phase 5 has none at all. The one
35
+ * deliberate exception is a structurally valid old normalized spec that leaves
36
+ * `filesystem` or `network` buried under `permissions.extensions`: that cache
37
+ * throws with an explicit `owenloop work prepare` repair because returning it
38
+ * would silently discard an authored restriction. There is no fallback to the
39
+ * legacy `templates/<step>.md`.
40
+ */
41
+ export declare function readStepSpec(cacheDir: string, name: string, hash: string, step: string): NormalizedStepSpec | null;
42
+ /**
43
+ * Every distinct hash of workflow `name` that some still-cached bundle (any
44
+ * name, including a parent, a sibling child, or `name` itself) currently pins.
45
+ * The protected set for pruning and the pin-index for dispatch resolution.
46
+ * Fail-open via `scanCachedPins`.
47
+ */
48
+ export declare function collectPinnedHashes(cacheDir: string, name: string): Set<string>;
49
+ /**
50
+ * Delete hash dirs under `<name>` except the protected set (DD-3): `keepHash`
51
+ * plus every hash of `name` pinned by any still-cached bundle (pinned-is-immortal
52
+ * — the consumer mirror of the hub's INV-96). Signature unchanged from D2, so
53
+ * every existing call site inherits the rule. Fail-open: a prune error is
54
+ * swallowed (the fresh bundle is already written; a leftover stale dir is
55
+ * harmless), and a corrupt bundle.json in the pin scan is skipped rather than
56
+ * fatal.
57
+ */
58
+ export declare function pruneSupersededHashes(cacheDir: string, name: string, keepHash: string): string[];
59
+ /**
60
+ * The dispatch-time bundle selection for `name` (DD-4), used by the shift sweep
61
+ * in place of a bare `readLatestBundle`. `whats_next` serves only the def NAME
62
+ * (no hash, no parent linkage), so per-instance pin disambiguation must come
63
+ * from the local cache's pin index:
64
+ * - 0 pinned hashes for `name` → `readLatestBundle` (today's behavior, byte
65
+ * for byte for the common, unpinned case).
66
+ * - exactly 1 pinned hash h → the bundle AT that hash (single-resolution
67
+ * honored, even when a NEWER unpinned hash of `name` is cached). If that
68
+ * bundle is missing/corrupt we do NOT fall back to latest (that would
69
+ * silently run the wrong version): return `{ bundle: null, warning }` naming
70
+ * `owenloop work prepare <parent>` as the fix — orders lapse via the pickup window.
71
+ * - >1 distinct pinned hashes (two cached parents pin DIFFERENT versions of
72
+ * one child name — legal across parents; the hub only forbids it inside one
73
+ * parent's tree) → ambiguous per-instance, so refuse: `{ bundle: null,
74
+ * warning }`, leave orders for the pickup window. Deliberate fail-safe —
75
+ * never guess a version. Reversible once the hub enriches `whats_next` with a
76
+ * def hash (owenloop-service follow-up, out of scope here).
77
+ */
78
+ export declare function readDispatchBundle(cacheDir: string, name: string): {
79
+ bundle: CachedBundle | null;
80
+ warning?: string;
81
+ };
82
+ /**
83
+ * Resolve the pinned child target for a parent's `calls:` step (pure). Matches
84
+ * `def.pins[].call` against `callStep`, returning `{name, hash}` for the frozen
85
+ * child that step must dispatch, or `null` when the def has no matching pin. The
86
+ * parent-pin → child-bundle resolvable path (item 3 of the brief); D-work builds
87
+ * child-run spawning on top of it.
88
+ */
89
+ export declare function resolvePinnedChild(def: FetchedDef, callStep: string): {
90
+ name: string;
91
+ hash: string;
92
+ } | null;