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,175 @@
1
+ /**
2
+ * Single source of the CLI usage text. Printed by `--help`/`help` (to stdout,
3
+ * exit 0) and on a dispatch error (to stderr, exit 2). Keeping it in one place
4
+ * means the help output and the error output never drift apart.
5
+ */
6
+ export const USAGE = `owenloop work — execution-side CLI companion to owenloop
7
+
8
+ Usage:
9
+ owenloop work hold --order <id> [options] hold an order with a heartbeating lease
10
+ owenloop work exec <order-id> [options] run a command order in a self-leasing loop
11
+ owenloop work agent-run <order-id> [options] host an agent order's step agent in a
12
+ harness, in a self-leasing loop
13
+ owenloop work prepare <workflow> [--origin <url>]
14
+ fetch, cache & normalize step specs
15
+ owenloop work lint <workflow-name | path> lint x.harness option bags in a def
16
+ owenloop work sessions [--all] [--json] list this machine's recorded harness
17
+ sessions and how to re-open them
18
+ owenloop work release --session <id> [options] drain a session's held claims
19
+ owenloop work settings print the resolved settings file
20
+ owenloop work join <code> [--hub <origin>] [--as <account>]
21
+ redeem a join code and store the Scoped
22
+ Identity credential (one-time provisioning)
23
+
24
+ Options:
25
+ -h, --help show this help and exit 0
26
+ --version print the owenloop work version and exit 0
27
+
28
+ root shift options (run as owenloop shift start <crew...> | --all):
29
+ <crew...> serve only these crews (positional, space
30
+ separated); or --all for every crew on the key
31
+ --all serve every crew on the key
32
+ --origin <url> hub origin (else settings.hubOrigin)
33
+ --as <account> Scoped Identity credential account to read + hand
34
+ to dispatched holds/execs (default 'default')
35
+ --name <n> Shift name (default <hostname>/<cwd>)
36
+ --cap <n> max in-flight exec children (default 3)
37
+ --poll-interval <ms> wake poll cadence (default 5000)
38
+ --once bootstrap wake + one sweep, then exit (demo/e2e)
39
+ --max-agents <n> max in-flight agent-run children, separate from
40
+ --cap (default 4; else settings.maxConcurrentAgents)
41
+ --cache-dir/--state-dir <p> override the resolved dirs
42
+
43
+ hold options:
44
+ --order <workflow>/<run> the order to hold (or --order <run> --workflow)
45
+ --workflow <wf> required when --order is a bare run id
46
+ --origin <url> hub origin (else settings.hubOrigin)
47
+ --as <account> Scoped Identity credential account (default
48
+ 'default'; the shift stamps this into born-bound
49
+ holds)
50
+ --session <id> session-holder tag (else env OWENLOOP_SESSION;
51
+ else an anon:<hostname>:<pid> fallback — a
52
+ holder is always sent)
53
+ --shift <id> dispatching Shift's self-declared id (else
54
+ env OWENLOOP_SHIFT_ID); advisory only
55
+ --heartbeat-interval <ms> lease renew cadence (default 60000)
56
+ --jump-tolerance <ms> wall-gap slack before a tick is treated as a
57
+ clock jump / laptop sleep (default 30000)
58
+ --ignore-stdin don't final-breath on stdin EOF (detached use)
59
+ --mcp run as a stdio-MCP work-holder: tools get_order /
60
+ submit, lease kept warm underneath (mutually
61
+ exclusive with --ignore-stdin — stdin is the
62
+ transport)
63
+
64
+ exec options (usually spawned by shift, not run by hand):
65
+ <workflow>/<run> the command order to run (positional order-id;
66
+ or a bare <run> plus --workflow <wf>)
67
+ --workflow <wf> required when the order-id is a bare run id
68
+ --origin <url> hub origin (else settings.hubOrigin)
69
+ --shift <id> dispatching Shift's self-declared id (else
70
+ env OWENLOOP_SHIFT_ID); advisory only
71
+ --heartbeat-interval <ms> lease renew cadence (default 60000)
72
+ --jump-tolerance <ms> wall-gap slack before a tick is treated as a
73
+ clock jump / laptop sleep (default 30000)
74
+
75
+ agent-run options (spawned by the shift, not run by hand):
76
+ <workflow>/<run> the agent order to host (positional order-id;
77
+ or a bare <run> plus --workflow <wf>)
78
+ --workflow <wf> required when the order-id is a bare run id
79
+ --origin <url> hub origin (else settings.hubOrigin)
80
+ --harness <id> which registered harness hosts the step agent
81
+ (else env OWENLOOP_HARNESS, else the step def's
82
+ 'harness' field, else the first registered one)
83
+ --shift <id> dispatching Shift's self-declared id (else
84
+ env OWENLOOP_SHIFT_ID); advisory only
85
+ --heartbeat-interval <ms> lease renew cadence (default 60000)
86
+ --jump-tolerance <ms> wall-gap slack before a tick is treated as a
87
+ clock jump / laptop sleep (default 30000)
88
+ --submit-grace <ms> after the turn ends, how long to keep asking the
89
+ hub whether the agent's submit landed (default
90
+ 15000). Task completion comes from the HUB, never
91
+ from the harness stream.
92
+ --confirm-interval <ms> poll cadence inside that grace (default 1000)
93
+
94
+ release options:
95
+ --session <id> session whose claims to drain (else env
96
+ OWENLOOP_SESSION). Agent-held claims re-offer;
97
+ exec-held claims are drain-exempt (B3).
98
+ --origin <url> hub origin (else settings.hubOrigin)
99
+
100
+ settings (no options in v1):
101
+ prints the resolved settings file path, whether it exists, each known
102
+ knob (hubOrigin, cacheDir, stateDir, dispatchCap, commandRouting,
103
+ maxConcurrentAgents, workRoot, workRepo) with its value + provenance,
104
+ and any unrecognized keys.
105
+ settings.dispatchCap/stateDir are the lowest-precedence
106
+ fallbacks for shift's --cap/--state-dir. NO secrets ever
107
+ live in settings — credentials stay in owenloop's own store.
108
+
109
+ sessions options:
110
+ --all include 'dead' sessions (hidden by default —
111
+ a dead session can no longer be resumed)
112
+ --json print the raw newest-per-step records, tokens
113
+ included, instead of the table
114
+ --cache-dir <p> override the resolved cache dir
115
+
116
+ join options:
117
+ --hub <origin> hub to redeem against (else settings.hubOrigin;
118
+ one of the two is REQUIRED — the code never
119
+ chooses the hub)
120
+ --as <account> credential account to store under (default:
121
+ the Scoped Identity name the hub returns)
122
+
123
+ shift/hold/exec/prepare/release env:
124
+ credentials come from owenloop's store — each role reads the
125
+ agent:<account> slot for its origin (never the human slot); a
126
+ missing slot refuses with a runnable 'owenloop login' command.
127
+ OWENLOOP_ACCOUNT Scoped Identity account for exec/prepare/release
128
+ (default 'default'; shift uses --as, and
129
+ stamps it onto dispatched holds/execs)
130
+ OWENLOOP_TOKEN dev-only bearer override — when set, used
131
+ verbatim and the store + account are
132
+ bypassed (NOT the primary path)
133
+ OWENLOOP_CACHE_DIR cache root
134
+ OWENLOOP_STATE_DIR shift in-flight state dir
135
+ OWENLOOP_SESSION hold session-holder tag / release drain target
136
+ OWENLOOP_SHIFT_ID dispatching Shift's self-declared id for
137
+ hold/exec/agent-run's --shift (advisory
138
+ only, never for auth/routing/dispatch)
139
+ OWENLOOP_HARNESS agent-run harness id; below --harness, above
140
+ the step def's 'harness' field
141
+ OWENLOOP_WORK_ROOT root for per-RUN agent work dirs
142
+ (<workRoot>/<workflow>/<run>); above
143
+ settings.workRoot, default <cacheDir>/work.
144
+ A hub-supplied OrderPacket.workdir still
145
+ wins, and is never reaped.
146
+ OWENLOOP_WORK_REPO local git repo to cut per-run work dirs from
147
+ as worktrees instead of plain dirs; above
148
+ settings.workRepo, default off
149
+
150
+ Credentials / accounts:
151
+ owenloop work's RUNTIME roles (shift/hold/exec/prepare/release) are READ-ONLY
152
+ over owenloop's credential store — they never write credentials. Each
153
+ role reads the agent:<account> slot for its origin (never the human
154
+ slot); the account defaults to 'default'. 'owenloop work join' is the one
155
+ deliberate provisioning-time writer: it stores the Scoped Identity token a hub
156
+ redeem returns via owenloop's public storeCredential, once, at join time
157
+ — not a runtime write.
158
+ store / connect an account (run owenloop; owenloop work never writes it):
159
+ owenloop login --hub <origin> --as agent:<account>
160
+ (use --as agent for the default account)
161
+ or provision a fresh box from a hub-issued join code:
162
+ owenloop work join <code> --hub <origin>
163
+ select an account at run time:
164
+ --as <account> on shift / hold
165
+ OWENLOOP_ACCOUNT on exec / prepare / release
166
+ (shift resolves once and threads both channels)
167
+ owenloop work does NOT list stored accounts — enumerating an origin's accounts
168
+ is an owenloop-side capability; check owenloop for which slots are stored.
169
+
170
+ Exit codes:
171
+ 0 success / help / version / lint clean or warnings-only
172
+ 1 runtime failure (fetch/hub error, cache write) / lint found an error
173
+ 2 usage error (unknown or missing role, missing required arg)
174
+ 3 role not implemented yet (skeleton stub — lands in a later delivery)
175
+ `;
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The GitHub route for `owenloop add <owner>/<repo>[@ref]`: spec parsing, URL
3
+ * building, the `installed.json` ledger, old-name migration parking, and the
4
+ * v1 crash-recovery adapter. The host-neutral filesystem transaction this
5
+ * route rides on — safe staging, the atomic swap with a retained backup,
6
+ * finalize/rollback, the atomic metadata write, the install lock, and the
7
+ * two-phase journal + recovery — lives in `src/install.ts` (engine core);
8
+ * this module keeps only what is GitHub-specific and re-exports the shared
9
+ * names callers and tests have always imported from here.
10
+ *
11
+ * The network fetch and arg glue live in `src/cli.ts` (`dispatchAdd`) so this
12
+ * module stays trivially unit-testable.
13
+ */
14
+ import type { InstallCommitHandle as GenericInstallCommitHandle, InstallLockHandle, AcquireLockOpts, CommitInstallOptions, RecoveryOutcome, V2ReplacementRecoveryActions } from './install.ts';
15
+ export { archivePathViolation, lockfilePathViolation, stageFiles, rmRecursiveForce, RollbackFailedError, STAGING_DIRNAME, ADD_JOURNAL_FILENAME, releaseInstallLock, validateAddJournal, readAddJournal, writeAddJournal, removeAddJournal, } from './install.ts';
16
+ export type { AddJournal, AddJournalPhase, RecoveryOutcome, InstallLockHandle, AcquireLockOpts } from './install.ts';
17
+ export interface RepoSpec {
18
+ owner: string;
19
+ repo: string;
20
+ ref: string;
21
+ }
22
+ /** Parse `owner/repo` or `owner/repo@ref` into its parts; `ref` defaults to `'HEAD'`. */
23
+ export declare function parseRepoSpec(spec: string): RepoSpec;
24
+ /**
25
+ * The single-path-segment install folder for a package, derived from its
26
+ * `owner/repo` identity: `<owner>-<repo>-<sha256(owner/repo)[:8]>`. The 8-hex
27
+ * suffix makes the (owner,repo)→folder mapping injective in practice — the old
28
+ * `<owner>-<repo>` scheme collided (`a-b/c` and `a/b-c` both mapped to
29
+ * `a-b-c`, and the second install clobbered the first). Keying on the source
30
+ * (matching the lockfile key) keeps the folder STABLE across versions, so a
31
+ * user's documented `--defs workflows/<folder>` pointer survives upgrades.
32
+ */
33
+ export declare function installFolder(owner: string, repo: string): string;
34
+ export declare function githubShaUrl(owner: string, repo: string, ref: string): string;
35
+ export declare function githubTarballUrl(owner: string, repo: string, sha: string): string;
36
+ /**
37
+ * One installed-package record. `path` is a single on-disk folder segment (see
38
+ * `lockfilePathViolation`); `sha` is a 40-char hex commit sha; `source` equals
39
+ * the record's key in `Lockfile.installed`. These invariants are NOT trusted
40
+ * from disk — `validateLockfile` enforces every one on read, fail-closed,
41
+ * before any consumer acts on an entry.
42
+ */
43
+ export interface InstalledEntry {
44
+ source: string;
45
+ ref: string;
46
+ sha: string;
47
+ installedAt: number;
48
+ path: string;
49
+ files: string[];
50
+ }
51
+ export interface Lockfile {
52
+ version: 1;
53
+ installed: Record<string, InstalledEntry>;
54
+ }
55
+ /**
56
+ * Structurally validate a parsed `installed.json`, fail-closed. A
57
+ * parseable-but-schema-invalid lockfile is a hard error naming the offending
58
+ * entry+field — never silently reset to `{}` (which would erase ownership
59
+ * records and re-enable the clobbering `installFolder` was hardened against)
60
+ * and never normalized. This is the trust boundary for the lockfile:
61
+ * downstream code (`dispatchAdd`, `parkOldNameDir`) may only act on entries
62
+ * that have passed through here. Critically, EVERY entry is validated, not just
63
+ * the one being installed — `dispatchAdd` re-serializes the whole lockfile on
64
+ * success, so acting while carrying a poisoned sibling entry would re-persist
65
+ * it. Unknown extra keys (on the lockfile or an entry) are tolerated for
66
+ * forward compatibility; required shape is enforced, additions are not
67
+ * forbidden. Returns the value narrowed to `Lockfile`. `path` appears only in
68
+ * error messages.
69
+ */
70
+ export declare function validateLockfile(parsed: unknown, path: string): Lockfile;
71
+ /**
72
+ * Read `.owenloop/installed.json`; a missing file is an empty lockfile, not an
73
+ * error. A file that exists but does not parse is a hard error naming the path
74
+ * — never silently reset to `{}`, which would erase ownership records and
75
+ * re-enable the clobbering `installFolder` was hardened against. A file that
76
+ * parses but is structurally invalid (bad version, malformed entry, a `path`
77
+ * that is not a safe single segment, a bad `sha`/`files`) is likewise a
78
+ * fail-closed hard error — see `validateLockfile`. The lockfile is never
79
+ * trusted for filesystem paths.
80
+ */
81
+ export declare function readLockfile(path: string): Lockfile;
82
+ export interface WriteLockfileOpts {
83
+ /**
84
+ * Removal op used to clean up the temp sibling when the atomic rename fails.
85
+ * Defaults to `rmSync`; injectable so a test can force the cleanup itself to
86
+ * throw and prove the ORIGINAL rename error still surfaces.
87
+ */
88
+ rm?: (path: string, opts: {
89
+ force: true;
90
+ }) => void;
91
+ }
92
+ /**
93
+ * Write the lockfile atomically: serialize into a sibling temp file, then
94
+ * rename over the destination — the shared atomic tmp+rename discipline from
95
+ * `src/install.ts`. A crash or a concurrent reader never sees a half-written
96
+ * `installed.json`, and two racing writers can only ever leave a fully-formed
97
+ * file. On a failed rename the temp sibling is removed best-effort and the
98
+ * ORIGINAL rename error is surfaced unchanged.
99
+ */
100
+ export declare function writeLockfile(path: string, lf: Lockfile, opts?: WriteLockfileOpts): void;
101
+ /**
102
+ * A handle to a committed-but-not-yet-finalized GitHub install — the generic
103
+ * transaction handle plus the old-name migration record `parkOldNameDir` sets.
104
+ * The caller MUST eventually either `finalizeInstallCommit` (discard the
105
+ * retained dirs) or `rollbackInstallCommit` (restore the previous state).
106
+ */
107
+ export interface InstallCommitHandle extends GenericInstallCommitHandle {
108
+ /** Set by `parkOldNameDir` when an old-naming dir was migrated off. */
109
+ oldName?: {
110
+ originalPath: string;
111
+ parkedAt: string;
112
+ };
113
+ }
114
+ /**
115
+ * Atomically swap a validated `stagingDir` into place at `defsDir/folder`,
116
+ * retaining the displaced previous install on the returned handle (see
117
+ * `src/install.ts:commitInstall` for the full two-phase semantics). This is a
118
+ * typed pass-through: `folder` is a SINGLE on-disk segment, and the returned
119
+ * handle carries the GitHub-only `oldName` migration field once
120
+ * `parkOldNameDir` runs.
121
+ */
122
+ export declare function commitInstall(defsDir: string, folder: string, stagingDir: string, options?: CommitInstallOptions): InstallCommitHandle;
123
+ /**
124
+ * Migrate a source off its old `<owner>-<repo>` install directory by PARKING it
125
+ * (rename → `<stagingDir>-undo-oldname`) instead of deleting it, so a later
126
+ * rollback can put it back where the (still-unchanged) lockfile expects it.
127
+ * Records the move on `handle.oldName`. If the old dir does not exist on disk
128
+ * (the lockfile names a path that is already gone), records nothing — matching
129
+ * the previous tolerance of absence.
130
+ *
131
+ * Defense-in-depth (Layer 3): even though `readLockfile`/`validateLockfile` and
132
+ * the use-site in `dispatchAdd` already constrain `oldRelPath` to a safe single
133
+ * segment, the authoritative containment check is re-asserted HERE, at the
134
+ * mutation site, before any rename — a poisoned `existing.path` must never move
135
+ * a directory outside `defsDir` (which `finalizeInstallCommit` would then
136
+ * recursively delete). Following this project's TOCTOU discipline, the check
137
+ * that matters is the one at the filesystem operation, not only up front:
138
+ * `oldRelPath` must be a single segment AND resolve under `defsDir`, and the
139
+ * target must be a real directory — a symlink at the legacy path is refused (a
140
+ * symlinked segment must never be parked/finalized, since finalize deletes it).
141
+ * Deliberate behavior change vs. a bare `existsSync` probe: a DANGLING symlink
142
+ * at the old path is refused, which is fail-closed and correct.
143
+ */
144
+ export declare function parkOldNameDir(handle: InstallCommitHandle, defsDir: string, oldRelPath: string): void;
145
+ /**
146
+ * Make the commit permanent: discard the retained previous install AND any
147
+ * parked old-name dir (the GitHub-only half the generic finalizer does not
148
+ * know about). Call ONLY after the follow-on lockfile write has durably
149
+ * succeeded — this is the point of no return.
150
+ */
151
+ export declare function finalizeInstallCommit(handle: InstallCommitHandle): void;
152
+ /**
153
+ * Restore the previous directory state after a failed commit: the GitHub-only
154
+ * counterpart of `finalizeInstallCommit`. Restores the swapped-out destination
155
+ * exactly as the generic rollback does, THEN renames the parked old-name dir
156
+ * back to its original name — the same order as before the transaction was
157
+ * generalized. Call ONLY before the follow-on lockfile write has succeeded.
158
+ */
159
+ export declare function rollbackInstallCommit(handle: InstallCommitHandle): void;
160
+ /**
161
+ * Acquire the per-project install lock at `lockPath`. A 1-line adapter over the
162
+ * generic `acquireFileLock`, pinning `label` so the timeout message reads
163
+ * "another owenloop add is in progress …" byte-for-byte as before. Always pair
164
+ * with `releaseInstallLock` in a `finally`.
165
+ */
166
+ export declare function acquireInstallLock(lockPath: string, opts?: AcquireLockOpts): Promise<InstallLockHandle>;
167
+ export interface RecoverInterruptedInstallArgs {
168
+ /** The CURRENT run's resolved defs dir — every mutation path derives from it. */
169
+ defsDir: string;
170
+ /** Path to `.owenloop/add.journal`. */
171
+ journalPath: string;
172
+ /** Path to `.owenloop/installed.json` — read to decide the commit-point boundary. */
173
+ lockfilePath: string;
174
+ /** External marker directory for fresh v2 recovery corroboration. */
175
+ recoveryMarkerDir?: string;
176
+ /** CAS-only hardening and verification actions when a shared v2 journal is found. */
177
+ v2Replacement?: V2ReplacementRecoveryActions;
178
+ }
179
+ /**
180
+ * Bring an interrupted GitHub-route install back to a consistent (defs ⇔
181
+ * lockfile) state, then remove the journal. Called by `dispatchAdd` under the
182
+ * per-project install lock, BEFORE the stale-staging cleanup. Also recovers a
183
+ * v2 (workflow-store) journal found at the same location — the generic
184
+ * recovery dispatches on journal version. See `src/install.ts`
185
+ * `recoverInterruptedInstall` for the full roll-forward/roll-back decision
186
+ * table and crash-safety argument. Refusals throw without mutating anything
187
+ * and leave the journal in place.
188
+ */
189
+ export declare function recoverInterruptedInstall(args: RecoverInterruptedInstallArgs): RecoveryOutcome;
@@ -0,0 +1,300 @@
1
+ /**
2
+ * The GitHub route for `owenloop add <owner>/<repo>[@ref]`: spec parsing, URL
3
+ * building, the `installed.json` ledger, old-name migration parking, and the
4
+ * v1 crash-recovery adapter. The host-neutral filesystem transaction this
5
+ * route rides on — safe staging, the atomic swap with a retained backup,
6
+ * finalize/rollback, the atomic metadata write, the install lock, and the
7
+ * two-phase journal + recovery — lives in `src/install.ts` (engine core);
8
+ * this module keeps only what is GitHub-specific and re-exports the shared
9
+ * names callers and tests have always imported from here.
10
+ *
11
+ * The network fetch and arg glue live in `src/cli.ts` (`dispatchAdd`) so this
12
+ * module stays trivially unit-testable.
13
+ */
14
+ import { existsSync, lstatSync, readFileSync, renameSync, rmSync } from 'node:fs';
15
+ import { join, resolve, sep } from 'node:path';
16
+ import { createHash } from 'node:crypto';
17
+ import { commitInstall as commitInstallGeneric, finalizeInstallCommit as finalizeInstallCommitGeneric, acquireInstallLock as acquireInstallLockGeneric, lockfilePathViolation, archivePathViolation, recoverInterruptedInstall as recoverInterruptedInstallGeneric, rollbackInstallCommit as rollbackInstallCommitGeneric, writeJsonAtomic, } from "./install.js";
18
+ // Re-export the shared transaction surface under the names callers/tests have
19
+ // always imported from this module (the move to src/install.ts was
20
+ // logic-preserving). `finalizeInstallCommit` and `rollbackInstallCommit` are
21
+ // NOT re-exported: this module defines the GitHub-aware versions — they also
22
+ // handle the parked old-name dir, which the generic ones do not know about —
23
+ // and they shadow the generic versions.
24
+ export { archivePathViolation, lockfilePathViolation, stageFiles, rmRecursiveForce, RollbackFailedError, STAGING_DIRNAME, ADD_JOURNAL_FILENAME, releaseInstallLock, validateAddJournal, readAddJournal, writeAddJournal, removeAddJournal, } from "./install.js";
25
+ /** GitHub-legal (superset) charset for an owner/repo name — see `parseRepoSpec`. */
26
+ const REPO_NAME_RE = /^[A-Za-z0-9._-]+$/;
27
+ /** Parse `owner/repo` or `owner/repo@ref` into its parts; `ref` defaults to `'HEAD'`. */
28
+ export function parseRepoSpec(spec) {
29
+ const atIdx = spec.lastIndexOf('@');
30
+ const ownerRepo = atIdx >= 0 ? spec.slice(0, atIdx) : spec;
31
+ const ref = atIdx >= 0 ? spec.slice(atIdx + 1) : 'HEAD';
32
+ const slashIdx = ownerRepo.indexOf('/');
33
+ if (slashIdx < 0) {
34
+ throw new Error(`malformed repo spec '${spec}' — expected owner/repo[@ref]`);
35
+ }
36
+ const owner = ownerRepo.slice(0, slashIdx);
37
+ const repo = ownerRepo.slice(slashIdx + 1);
38
+ if (!owner || !repo) {
39
+ throw new Error(`malformed repo spec '${spec}' — expected owner/repo[@ref]`);
40
+ }
41
+ if (repo.includes('/')) {
42
+ throw new Error(`malformed repo spec '${spec}' — expected owner/repo[@ref]`);
43
+ }
44
+ if (!ref) {
45
+ throw new Error(`malformed repo spec '${spec}' — empty ref after '@'`);
46
+ }
47
+ // Owner and repo become a single on-disk path segment (see `installFolder`),
48
+ // so restrict them to the GitHub-legal charset (a superset — letters, digits,
49
+ // '.', '_', '-'). This guarantees no '/', '\\', or NUL can reach the folder
50
+ // name on any platform — defense-in-depth alongside `archivePathViolation`.
51
+ if (!REPO_NAME_RE.test(owner) || !REPO_NAME_RE.test(repo)) {
52
+ throw new Error(`malformed repo spec '${spec}' — owner and repo may only contain letters, digits, '.', '_', '-'`);
53
+ }
54
+ return { owner, repo, ref };
55
+ }
56
+ /**
57
+ * The single-path-segment install folder for a package, derived from its
58
+ * `owner/repo` identity: `<owner>-<repo>-<sha256(owner/repo)[:8]>`. The 8-hex
59
+ * suffix makes the (owner,repo)→folder mapping injective in practice — the old
60
+ * `<owner>-<repo>` scheme collided (`a-b/c` and `a/b-c` both mapped to
61
+ * `a-b-c`, and the second install clobbered the first). Keying on the source
62
+ * (matching the lockfile key) keeps the folder STABLE across versions, so a
63
+ * user's documented `--defs workflows/<folder>` pointer survives upgrades.
64
+ */
65
+ export function installFolder(owner, repo) {
66
+ const hash = createHash('sha256').update(`${owner}/${repo}`).digest('hex').slice(0, 8);
67
+ return `${owner}-${repo}-${hash}`;
68
+ }
69
+ export function githubShaUrl(owner, repo, ref) {
70
+ return `https://api.github.com/repos/${owner}/${repo}/commits/${ref}`;
71
+ }
72
+ export function githubTarballUrl(owner, repo, sha) {
73
+ return `https://api.github.com/repos/${owner}/${repo}/tarball/${sha}`;
74
+ }
75
+ /** A 40-char hex commit sha (case-insensitive), as GitHub returns. */
76
+ const SHA_HEX_RE = /^[0-9a-f]{40}$/i;
77
+ function isPlainObject(value) {
78
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
79
+ }
80
+ /**
81
+ * Structurally validate a parsed `installed.json`, fail-closed. A
82
+ * parseable-but-schema-invalid lockfile is a hard error naming the offending
83
+ * entry+field — never silently reset to `{}` (which would erase ownership
84
+ * records and re-enable the clobbering `installFolder` was hardened against)
85
+ * and never normalized. This is the trust boundary for the lockfile:
86
+ * downstream code (`dispatchAdd`, `parkOldNameDir`) may only act on entries
87
+ * that have passed through here. Critically, EVERY entry is validated, not just
88
+ * the one being installed — `dispatchAdd` re-serializes the whole lockfile on
89
+ * success, so acting while carrying a poisoned sibling entry would re-persist
90
+ * it. Unknown extra keys (on the lockfile or an entry) are tolerated for
91
+ * forward compatibility; required shape is enforced, additions are not
92
+ * forbidden. Returns the value narrowed to `Lockfile`. `path` appears only in
93
+ * error messages.
94
+ */
95
+ export function validateLockfile(parsed, path) {
96
+ const fail = (detail) => {
97
+ throw new Error(`invalid lockfile at ${path}: ${detail} — fix or remove it manually`);
98
+ };
99
+ if (!isPlainObject(parsed))
100
+ return fail('top-level value is not an object');
101
+ if (parsed.version !== 1) {
102
+ return fail(`unsupported lockfile version ${JSON.stringify(parsed.version)} (expected 1)`);
103
+ }
104
+ if (!isPlainObject(parsed.installed))
105
+ return fail("'installed' is not an object");
106
+ for (const [key, entry] of Object.entries(parsed.installed)) {
107
+ const at = (field) => `installed[${JSON.stringify(key)}].${field}`;
108
+ if (!isPlainObject(entry))
109
+ return fail(`installed[${JSON.stringify(key)}] is not an object`);
110
+ if (typeof entry.source !== 'string' || entry.source === '') {
111
+ return fail(`${at('source')} is not a non-empty string`);
112
+ }
113
+ if (entry.source !== key) {
114
+ return fail(`${at('source')} '${entry.source}' does not match its key '${key}'`);
115
+ }
116
+ if (typeof entry.ref !== 'string' || entry.ref === '') {
117
+ return fail(`${at('ref')} is not a non-empty string`);
118
+ }
119
+ if (typeof entry.sha !== 'string' || !SHA_HEX_RE.test(entry.sha)) {
120
+ return fail(`${at('sha')} is not a 40-char hex commit sha`);
121
+ }
122
+ if (typeof entry.installedAt !== 'number' || !Number.isFinite(entry.installedAt)) {
123
+ return fail(`${at('installedAt')} is not a finite number`);
124
+ }
125
+ if (typeof entry.path !== 'string')
126
+ return fail(`${at('path')} is not a string`);
127
+ const pathViolation = lockfilePathViolation(entry.path);
128
+ if (pathViolation)
129
+ return fail(`${at('path')} ${pathViolation}`);
130
+ if (!Array.isArray(entry.files))
131
+ return fail(`${at('files')} is not an array`);
132
+ entry.files.forEach((file, i) => {
133
+ if (typeof file !== 'string')
134
+ return fail(`${at(`files[${i}]`)} is not a string`);
135
+ const fileViolation = archivePathViolation(file);
136
+ if (fileViolation)
137
+ return fail(`${at(`files[${i}]`)} ${fileViolation}`);
138
+ });
139
+ }
140
+ return parsed;
141
+ }
142
+ /**
143
+ * Read `.owenloop/installed.json`; a missing file is an empty lockfile, not an
144
+ * error. A file that exists but does not parse is a hard error naming the path
145
+ * — never silently reset to `{}`, which would erase ownership records and
146
+ * re-enable the clobbering `installFolder` was hardened against. A file that
147
+ * parses but is structurally invalid (bad version, malformed entry, a `path`
148
+ * that is not a safe single segment, a bad `sha`/`files`) is likewise a
149
+ * fail-closed hard error — see `validateLockfile`. The lockfile is never
150
+ * trusted for filesystem paths.
151
+ */
152
+ export function readLockfile(path) {
153
+ if (!existsSync(path))
154
+ return { version: 1, installed: {} };
155
+ const raw = readFileSync(path, 'utf8');
156
+ let parsed;
157
+ try {
158
+ parsed = JSON.parse(raw);
159
+ }
160
+ catch (e) {
161
+ throw new Error(`corrupt lockfile at ${path}: ${e.message} — fix or remove it manually`);
162
+ }
163
+ return validateLockfile(parsed, path);
164
+ }
165
+ /**
166
+ * Write the lockfile atomically: serialize into a sibling temp file, then
167
+ * rename over the destination — the shared atomic tmp+rename discipline from
168
+ * `src/install.ts`. A crash or a concurrent reader never sees a half-written
169
+ * `installed.json`, and two racing writers can only ever leave a fully-formed
170
+ * file. On a failed rename the temp sibling is removed best-effort and the
171
+ * ORIGINAL rename error is surfaced unchanged.
172
+ */
173
+ export function writeLockfile(path, lf, opts = {}) {
174
+ writeJsonAtomic(path, lf, opts);
175
+ }
176
+ /**
177
+ * Atomically swap a validated `stagingDir` into place at `defsDir/folder`,
178
+ * retaining the displaced previous install on the returned handle (see
179
+ * `src/install.ts:commitInstall` for the full two-phase semantics). This is a
180
+ * typed pass-through: `folder` is a SINGLE on-disk segment, and the returned
181
+ * handle carries the GitHub-only `oldName` migration field once
182
+ * `parkOldNameDir` runs.
183
+ */
184
+ export function commitInstall(defsDir, folder, stagingDir, options = {}) {
185
+ return commitInstallGeneric(defsDir, folder, stagingDir, options);
186
+ }
187
+ /**
188
+ * Migrate a source off its old `<owner>-<repo>` install directory by PARKING it
189
+ * (rename → `<stagingDir>-undo-oldname`) instead of deleting it, so a later
190
+ * rollback can put it back where the (still-unchanged) lockfile expects it.
191
+ * Records the move on `handle.oldName`. If the old dir does not exist on disk
192
+ * (the lockfile names a path that is already gone), records nothing — matching
193
+ * the previous tolerance of absence.
194
+ *
195
+ * Defense-in-depth (Layer 3): even though `readLockfile`/`validateLockfile` and
196
+ * the use-site in `dispatchAdd` already constrain `oldRelPath` to a safe single
197
+ * segment, the authoritative containment check is re-asserted HERE, at the
198
+ * mutation site, before any rename — a poisoned `existing.path` must never move
199
+ * a directory outside `defsDir` (which `finalizeInstallCommit` would then
200
+ * recursively delete). Following this project's TOCTOU discipline, the check
201
+ * that matters is the one at the filesystem operation, not only up front:
202
+ * `oldRelPath` must be a single segment AND resolve under `defsDir`, and the
203
+ * target must be a real directory — a symlink at the legacy path is refused (a
204
+ * symlinked segment must never be parked/finalized, since finalize deletes it).
205
+ * Deliberate behavior change vs. a bare `existsSync` probe: a DANGLING symlink
206
+ * at the old path is refused, which is fail-closed and correct.
207
+ */
208
+ export function parkOldNameDir(handle, defsDir, oldRelPath) {
209
+ const violation = lockfilePathViolation(oldRelPath);
210
+ if (violation) {
211
+ throw new Error(`refusing old-name migration path '${oldRelPath}': ${violation}`);
212
+ }
213
+ const originalPath = join(defsDir, oldRelPath);
214
+ // Resolved-path containment: '..'-free by the single-segment rule above, but
215
+ // recompute at the rename site so no path outside defsDir can ever be moved.
216
+ if (!resolve(originalPath).startsWith(resolve(defsDir) + sep)) {
217
+ throw new Error(`refusing old-name migration path '${oldRelPath}': escapes the defs directory`);
218
+ }
219
+ let st;
220
+ try {
221
+ st = lstatSync(originalPath); // lstat, not stat: never follow a symlink here.
222
+ }
223
+ catch (e) {
224
+ if (e.code === 'ENOENT')
225
+ return; // already gone — nothing to park
226
+ throw e;
227
+ }
228
+ if (st.isSymbolicLink()) {
229
+ throw new Error(`refusing old-name migration: '${originalPath}' is a symlink`);
230
+ }
231
+ if (!st.isDirectory()) {
232
+ throw new Error(`refusing old-name migration: '${originalPath}' is not a directory`);
233
+ }
234
+ const parkedAt = `${handle.undoDir}-oldname`;
235
+ renameSync(originalPath, parkedAt);
236
+ handle.oldName = { originalPath, parkedAt };
237
+ }
238
+ /**
239
+ * Make the commit permanent: discard the retained previous install AND any
240
+ * parked old-name dir (the GitHub-only half the generic finalizer does not
241
+ * know about). Call ONLY after the follow-on lockfile write has durably
242
+ * succeeded — this is the point of no return.
243
+ */
244
+ export function finalizeInstallCommit(handle) {
245
+ finalizeInstallCommitGeneric(handle);
246
+ if (handle.oldName)
247
+ rmSync(handle.oldName.parkedAt, { recursive: true, force: true });
248
+ }
249
+ /**
250
+ * Restore the previous directory state after a failed commit: the GitHub-only
251
+ * counterpart of `finalizeInstallCommit`. Restores the swapped-out destination
252
+ * exactly as the generic rollback does, THEN renames the parked old-name dir
253
+ * back to its original name — the same order as before the transaction was
254
+ * generalized. Call ONLY before the follow-on lockfile write has succeeded.
255
+ */
256
+ export function rollbackInstallCommit(handle) {
257
+ rollbackInstallCommitGeneric(handle);
258
+ if (handle.oldName)
259
+ renameSync(handle.oldName.parkedAt, handle.oldName.originalPath);
260
+ }
261
+ // ---- per-project install lock --------------------------------------------------
262
+ /**
263
+ * Acquire the per-project install lock at `lockPath`. A 1-line adapter over the
264
+ * generic `acquireFileLock`, pinning `label` so the timeout message reads
265
+ * "another owenloop add is in progress …" byte-for-byte as before. Always pair
266
+ * with `releaseInstallLock` in a `finally`.
267
+ */
268
+ export function acquireInstallLock(lockPath, opts = {}) {
269
+ return acquireInstallLockGeneric(lockPath, opts);
270
+ }
271
+ /**
272
+ * Bring an interrupted GitHub-route install back to a consistent (defs ⇔
273
+ * lockfile) state, then remove the journal. Called by `dispatchAdd` under the
274
+ * per-project install lock, BEFORE the stale-staging cleanup. Also recovers a
275
+ * v2 (workflow-store) journal found at the same location — the generic
276
+ * recovery dispatches on journal version. See `src/install.ts`
277
+ * `recoverInterruptedInstall` for the full roll-forward/roll-back decision
278
+ * table and crash-safety argument. Refusals throw without mutating anything
279
+ * and leave the journal in place.
280
+ */
281
+ export function recoverInterruptedInstall(args) {
282
+ return recoverInterruptedInstallGeneric({
283
+ defsDir: args.defsDir,
284
+ journalPath: args.journalPath,
285
+ lockfilePath: args.lockfilePath,
286
+ recoveryMarkerDir: args.recoveryMarkerDir,
287
+ v2Replacement: args.v2Replacement,
288
+ readLedger: () => {
289
+ // readLockfile validates fail-closed; a corrupt lockfile aborts the add
290
+ // exactly as it does on the normal path.
291
+ const lf = readLockfile(args.lockfilePath);
292
+ return (source) => {
293
+ const entry = lf.installed[source];
294
+ if (entry === undefined)
295
+ return undefined;
296
+ return { sha: entry.sha, path: entry.path };
297
+ };
298
+ },
299
+ });
300
+ }