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
package/dist/add.js DELETED
@@ -1,834 +0,0 @@
1
- /**
2
- * Pure helpers for the `owenloop add <owner>/<repo>[@ref]` CLI verb (workflow
3
- * distribution Stage 1 — see the design doc this implements,
4
- * `docs/workflow-distribution.md` §3 in the companion hub repo).
5
- *
6
- * These are the network-free, filesystem-adjacent pieces: spec parsing, URL
7
- * building, lockfile read/write, and file installation. The network fetch and
8
- * arg glue live in `src/cli.ts` (`dispatchAdd`) so this module stays trivially
9
- * unit-testable and `cli.ts` doesn't widen its export surface just to reuse
10
- * `Args`/`CliError`/etc.
11
- */
12
- import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
13
- import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
14
- import { createHash } from 'node:crypto';
15
- import { acquireFileLock, releaseFileLock } from "./lock.js";
16
- /** Max length for an in-archive relative path we are willing to join and write. */
17
- const MAX_ARCHIVE_PATH_LENGTH = 1024;
18
- /**
19
- * Returns `undefined` if `relPath` is safe to `join()` under a destination
20
- * directory, else a human-readable reason it must be rejected. This is
21
- * reject-don't-normalize: a synthetic archive entry like
22
- * `workflows/../../victim` is refused outright, never canonicalized into a
23
- * "safe" path. Part of SEC-1 — an unnormalized entry name must never escape
24
- * the staging or install directory.
25
- */
26
- export function archivePathViolation(relPath) {
27
- if (relPath === '')
28
- return 'empty path';
29
- if (relPath.includes('\0'))
30
- return 'contains a NUL byte';
31
- if (isAbsolute(relPath) || /^[\\/]/.test(relPath) || /^[A-Za-z]:/.test(relPath)) {
32
- return 'is an absolute path';
33
- }
34
- // Split on both separators so '..\\' tricks and doubled separators can't
35
- // smuggle a traversal segment past the check.
36
- const segments = relPath.split(/[\\/]+/);
37
- if (segments.some((s) => s === '.' || s === '..')) {
38
- return "contains a '.' or '..' segment";
39
- }
40
- if (relPath.length > MAX_ARCHIVE_PATH_LENGTH) {
41
- return `exceeds ${MAX_ARCHIVE_PATH_LENGTH}-char path length limit`;
42
- }
43
- return undefined;
44
- }
45
- /**
46
- * Returns `undefined` if `relPath` is a safe SINGLE-SEGMENT lockfile install
47
- * path, else a human-readable reason it must be rejected. Stricter than
48
- * {@link archivePathViolation}: a lockfile entry's `path` is one on-disk path
49
- * segment by construction — both the current `<owner>-<repo>-<hash>` scheme and
50
- * the only legacy scheme this tool ever wrote (`<owner>-<repo>`, see
51
- * {@link installFolder}) — so ANY separator is refused outright. That single
52
- * rule makes `..` traversal, `.owenloop/../../x`, and nested escape shapes
53
- * unrepresentable before any `join`/`rename` ever touches the path. Like
54
- * `archivePathViolation` this is reject-don't-normalize: a bad path is refused,
55
- * never canonicalized into a "safe" one.
56
- */
57
- export function lockfilePathViolation(relPath) {
58
- // Reuse the shared checks (empty, NUL, absolute, '.'/'..' segments, length).
59
- const base = archivePathViolation(relPath);
60
- if (base)
61
- return base;
62
- // A lockfile install path additionally must be a single segment: no
63
- // separators at all, so a multi-segment on-disk path like 'legacy/olddir'
64
- // (which passes archivePathViolation) is still refused here.
65
- if (/[\\/]/.test(relPath))
66
- return 'contains a path separator';
67
- return undefined;
68
- }
69
- /** Parse `owner/repo` or `owner/repo@ref` into its parts; `ref` defaults to `'HEAD'`. */
70
- export function parseRepoSpec(spec) {
71
- const atIdx = spec.lastIndexOf('@');
72
- const ownerRepo = atIdx >= 0 ? spec.slice(0, atIdx) : spec;
73
- const ref = atIdx >= 0 ? spec.slice(atIdx + 1) : 'HEAD';
74
- const slashIdx = ownerRepo.indexOf('/');
75
- if (slashIdx < 0) {
76
- throw new Error(`malformed repo spec '${spec}' — expected owner/repo[@ref]`);
77
- }
78
- const owner = ownerRepo.slice(0, slashIdx);
79
- const repo = ownerRepo.slice(slashIdx + 1);
80
- if (!owner || !repo) {
81
- throw new Error(`malformed repo spec '${spec}' — expected owner/repo[@ref]`);
82
- }
83
- if (repo.includes('/')) {
84
- throw new Error(`malformed repo spec '${spec}' — expected owner/repo[@ref]`);
85
- }
86
- if (!ref) {
87
- throw new Error(`malformed repo spec '${spec}' — empty ref after '@'`);
88
- }
89
- // Owner and repo become a single on-disk path segment (see `installFolder`),
90
- // so restrict them to the GitHub-legal charset (a superset — letters, digits,
91
- // '.', '_', '-'). This guarantees no '/', '\\', or NUL can reach the folder
92
- // name on any platform — defense-in-depth alongside `archivePathViolation`.
93
- if (!REPO_NAME_RE.test(owner) || !REPO_NAME_RE.test(repo)) {
94
- throw new Error(`malformed repo spec '${spec}' — owner and repo may only contain letters, digits, '.', '_', '-'`);
95
- }
96
- return { owner, repo, ref };
97
- }
98
- /** GitHub-legal (superset) charset for an owner/repo name — see `parseRepoSpec`. */
99
- const REPO_NAME_RE = /^[A-Za-z0-9._-]+$/;
100
- /**
101
- * The single-path-segment install folder for a package, derived from its
102
- * `owner/repo` identity: `<owner>-<repo>-<sha256(owner/repo)[:8]>`. The 8-hex
103
- * suffix makes the (owner,repo)→folder mapping injective in practice — the old
104
- * `<owner>-<repo>` scheme collided (`a-b/c` and `a/b-c` both mapped to
105
- * `a-b-c`, and the second install clobbered the first). Keying on the source
106
- * (matching the lockfile key) keeps the folder STABLE across versions, so a
107
- * user's documented `--defs workflows/<folder>` pointer survives upgrades.
108
- */
109
- export function installFolder(owner, repo) {
110
- const hash = createHash('sha256').update(`${owner}/${repo}`).digest('hex').slice(0, 8);
111
- return `${owner}-${repo}-${hash}`;
112
- }
113
- export function githubShaUrl(owner, repo, ref) {
114
- return `https://api.github.com/repos/${owner}/${repo}/commits/${ref}`;
115
- }
116
- export function githubTarballUrl(owner, repo, sha) {
117
- return `https://api.github.com/repos/${owner}/${repo}/tarball/${sha}`;
118
- }
119
- /** A 40-char hex commit sha (case-insensitive), as GitHub returns. */
120
- const SHA_HEX_RE = /^[0-9a-f]{40}$/i;
121
- function isPlainObject(value) {
122
- return typeof value === 'object' && value !== null && !Array.isArray(value);
123
- }
124
- /**
125
- * Structurally validate a parsed `installed.json`, fail-closed. A
126
- * parseable-but-schema-invalid lockfile is a hard error naming the offending
127
- * entry+field — never silently reset to `{}` (which would erase ownership
128
- * records and re-enable the clobbering {@link installFolder} was hardened
129
- * against) and never normalized. This is the trust boundary for the lockfile:
130
- * downstream code (`dispatchAdd`, `parkOldNameDir`) may only act on entries
131
- * that have passed through here. Critically, EVERY entry is validated, not just
132
- * the one being installed — `dispatchAdd` re-serializes the whole lockfile on
133
- * success, so acting while carrying a poisoned sibling entry would re-persist
134
- * it. Unknown extra keys (on the lockfile or an entry) are tolerated for
135
- * forward compatibility; required shape is enforced, additions are not
136
- * forbidden. Returns the value narrowed to {@link Lockfile}. `path` appears
137
- * only in error messages.
138
- */
139
- export function validateLockfile(parsed, path) {
140
- const fail = (detail) => {
141
- throw new Error(`invalid lockfile at ${path}: ${detail} — fix or remove it manually`);
142
- };
143
- if (!isPlainObject(parsed))
144
- return fail('top-level value is not an object');
145
- if (parsed.version !== 1) {
146
- return fail(`unsupported lockfile version ${JSON.stringify(parsed.version)} (expected 1)`);
147
- }
148
- if (!isPlainObject(parsed.installed))
149
- return fail("'installed' is not an object");
150
- for (const [key, entry] of Object.entries(parsed.installed)) {
151
- const at = (field) => `installed[${JSON.stringify(key)}].${field}`;
152
- if (!isPlainObject(entry))
153
- return fail(`installed[${JSON.stringify(key)}] is not an object`);
154
- if (typeof entry.source !== 'string' || entry.source === '') {
155
- return fail(`${at('source')} is not a non-empty string`);
156
- }
157
- if (entry.source !== key) {
158
- return fail(`${at('source')} '${entry.source}' does not match its key '${key}'`);
159
- }
160
- if (typeof entry.ref !== 'string' || entry.ref === '') {
161
- return fail(`${at('ref')} is not a non-empty string`);
162
- }
163
- if (typeof entry.sha !== 'string' || !SHA_HEX_RE.test(entry.sha)) {
164
- return fail(`${at('sha')} is not a 40-char hex commit sha`);
165
- }
166
- if (typeof entry.installedAt !== 'number' || !Number.isFinite(entry.installedAt)) {
167
- return fail(`${at('installedAt')} is not a finite number`);
168
- }
169
- if (typeof entry.path !== 'string')
170
- return fail(`${at('path')} is not a string`);
171
- const pathViolation = lockfilePathViolation(entry.path);
172
- if (pathViolation)
173
- return fail(`${at('path')} ${pathViolation}`);
174
- if (!Array.isArray(entry.files))
175
- return fail(`${at('files')} is not an array`);
176
- entry.files.forEach((file, i) => {
177
- if (typeof file !== 'string')
178
- return fail(`${at(`files[${i}]`)} is not a string`);
179
- const fileViolation = archivePathViolation(file);
180
- if (fileViolation)
181
- return fail(`${at(`files[${i}]`)} ${fileViolation}`);
182
- });
183
- }
184
- return parsed;
185
- }
186
- /**
187
- * Read `.owenloop/installed.json`; a missing file is an empty lockfile, not an
188
- * error. A file that exists but does not parse is a hard error naming the path
189
- * — never silently reset to `{}`, which would erase ownership records and
190
- * re-enable the clobbering `installFolder` was hardened against. A file that
191
- * parses but is structurally invalid (bad version, malformed entry, a `path`
192
- * that is not a safe single segment, a bad `sha`/`files`) is likewise a
193
- * fail-closed hard error — see {@link validateLockfile}. The lockfile is never
194
- * trusted for filesystem paths.
195
- */
196
- export function readLockfile(path) {
197
- if (!existsSync(path))
198
- return { version: 1, installed: {} };
199
- const raw = readFileSync(path, 'utf8');
200
- let parsed;
201
- try {
202
- parsed = JSON.parse(raw);
203
- }
204
- catch (e) {
205
- throw new Error(`corrupt lockfile at ${path}: ${e.message} — fix or remove it manually`);
206
- }
207
- return validateLockfile(parsed, path);
208
- }
209
- /**
210
- * Serialize `value` as pretty JSON into a sibling temp file, then `renameSync`
211
- * over `path` — the same atomic tmp+rename discipline {@link writeLockfile} has
212
- * always used, extracted so the crash-recovery journal writer
213
- * ({@link writeAddJournal}) shares one implementation of it (and its
214
- * double-fault cleanup semantics) rather than duplicating the seam. A crash or
215
- * a concurrent reader never sees a half-written file (rename is atomic within a
216
- * directory).
217
- *
218
- * If the final `renameSync` throws (EACCES, EISDIR on `path`, a full disk), the
219
- * temp sibling is removed on a best-effort basis before the error propagates so
220
- * a failed write cannot leak a `<path>.tmp.<pid>` file. The original rename
221
- * error is surfaced unchanged — never swallowed, and never masked by a failure
222
- * of that cleanup removal (if the removal itself throws, that error is swallowed
223
- * and the tmp sibling may remain in that double fault).
224
- */
225
- function writeJsonAtomic(path, value, opts = {}) {
226
- const rm = opts.rm ?? ((p, o) => rmSync(p, o));
227
- mkdirSync(dirname(path), { recursive: true });
228
- const tmp = `${path}.tmp.${process.pid}`;
229
- writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
230
- try {
231
- renameSync(tmp, path);
232
- }
233
- catch (e) {
234
- // Best-effort cleanup: the temp sibling should not leak on a failed write,
235
- // but if the removal ITSELF throws (e.g. unlink EACCES) we must not let that
236
- // replace the original rename error — swallow the cleanup error and rethrow
237
- // `e`. A tmp sibling may survive in that double fault.
238
- try {
239
- rm(tmp, { force: true });
240
- }
241
- catch {
242
- // ignore — surfacing the original rename error matters more than cleanup.
243
- }
244
- throw e;
245
- }
246
- }
247
- export function writeLockfile(path, lf, opts = {}) {
248
- writeJsonAtomic(path, lf, opts);
249
- }
250
- // ---- staging + atomic commit -----------------------------------------------
251
- /** The staging root under a defs dir where installs are assembled + validated. */
252
- export const STAGING_DIRNAME = '.owenloop-staging';
253
- /**
254
- * Write `files` (relative path → bytes) into `targetDir` (a staging dir), NOT
255
- * the final install destination. Unlike a direct install, this never clears a
256
- * live folder: the caller stages here, validates, then `commitInstall`s with an
257
- * atomic rename, so a failure mid-write can only ever corrupt throwaway staging
258
- * content. Returns the sorted list of relative paths written.
259
- */
260
- export function stageFiles(targetDir, files) {
261
- const written = [];
262
- for (const [relPath, bytes] of files) {
263
- // Defense-in-depth: this function is exported and writes whole directory
264
- // trees, so it must not trust its caller to have validated keys.
265
- const violation = archivePathViolation(relPath);
266
- if (violation) {
267
- throw new Error(`refusing to write unsafe archive path '${relPath}': ${violation}`);
268
- }
269
- const full = join(targetDir, relPath);
270
- mkdirSync(dirname(full), { recursive: true });
271
- writeFileSync(full, bytes);
272
- written.push(relPath);
273
- }
274
- return written.sort();
275
- }
276
- /**
277
- * Thrown by `commitInstall` when the atomic swap fails AND the rollback of it
278
- * fails too — a near-impossible same-filesystem double-fault. Carries the path
279
- * where the previous version was left so the caller can preserve it (its
280
- * `preservedAt` sits under the staging root, which the caller would otherwise
281
- * clean up as debris). A distinguishable type so the caller can tell this
282
- * "must-preserve" double-fault apart from an ordinary swap failure.
283
- */
284
- export class RollbackFailedError extends Error {
285
- preservedAt;
286
- constructor(message, preservedAt) {
287
- super(message);
288
- this.name = 'RollbackFailedError';
289
- this.preservedAt = preservedAt;
290
- }
291
- }
292
- /**
293
- * Atomically swap a validated `stagingDir` into place at `defsDir/folder`,
294
- * rolling back to the previous install if the swap itself fails. Both dirs live
295
- * on the same filesystem by construction (staging is under `defsDir`), so the
296
- * renames are atomic and `EXDEV` is impossible.
297
- *
298
- * Two-phase commit: unlike a one-shot swap, this does NOT delete the displaced
299
- * previous install on success — it returns an {@link InstallCommitHandle} whose
300
- * `backupDir` still holds it. The caller must then either
301
- * {@link finalizeInstallCommit} (discard the backup, making the swap permanent)
302
- * once its follow-on work — the lockfile write — has durably succeeded, or
303
- * {@link rollbackInstallCommit} to restore the previous directory state if that
304
- * work fails. This is what lets "commit the directory + write the lockfile" be
305
- * one recoverable operation.
306
- *
307
- * Sequence: back up any existing install (rename dest → `<stagingDir>-old`) — if
308
- * that fails nothing has changed; rename staging → dest; on failure rename the
309
- * backup back (throwing {@link RollbackFailedError} if even that fails, so the
310
- * caller can preserve the named copy).
311
- */
312
- export function commitInstall(defsDir, folder, stagingDir) {
313
- mkdirSync(defsDir, { recursive: true });
314
- const dest = join(defsDir, folder);
315
- const backupDir = `${stagingDir}-old`;
316
- const undoDir = `${stagingDir}-undo`;
317
- let backedUp = false;
318
- if (existsSync(dest)) {
319
- // Ownership is verified by the caller before we get here. If this rename
320
- // throws, nothing has changed — dest is still the previous install.
321
- renameSync(dest, backupDir);
322
- backedUp = true;
323
- }
324
- try {
325
- renameSync(stagingDir, dest);
326
- }
327
- catch (e) {
328
- if (backedUp) {
329
- try {
330
- renameSync(backupDir, dest);
331
- }
332
- catch (rollbackErr) {
333
- // Near-impossible (same dir, same fs), but if even the rollback fails,
334
- // name the backup so the previous version is recoverable by hand — and
335
- // signal (via the type) that the caller must preserve it.
336
- throw new RollbackFailedError(`install of '${folder}' failed and rollback failed too; ` +
337
- `previous version preserved at ${backupDir}: ${rollbackErr.message}`, backupDir);
338
- }
339
- }
340
- throw e;
341
- }
342
- return { dest, backupDir: backedUp ? backupDir : undefined, undoDir };
343
- }
344
- /**
345
- * Migrate a source off its old `<owner>-<repo>` install directory by PARKING it
346
- * (rename → `<stagingDir>-undo-oldname`) instead of deleting it, so a later
347
- * rollback can put it back where the (still-unchanged) lockfile expects it.
348
- * Records the move on `handle.oldName`. If the old dir does not exist on disk
349
- * (the lockfile names a path that is already gone), records nothing — matching
350
- * the previous `rmSync(..., { force: true })` tolerance of absence.
351
- *
352
- * Defense-in-depth (Layer 3): even though `readLockfile`/`validateLockfile` and
353
- * the use-site in `dispatchAdd` already constrain `oldRelPath` to a safe single
354
- * segment, the authoritative containment check is re-asserted HERE, at the
355
- * mutation site, before any rename — a poisoned `existing.path` must never move
356
- * a directory outside `defsDir` (which `finalizeInstallCommit` would then
357
- * recursively delete). Following this project's TOCTOU discipline, the check
358
- * that matters is the one at the filesystem operation, not only up front:
359
- * `oldRelPath` must be a single segment AND resolve under `defsDir`, and the
360
- * target must be a real directory — a symlink at the legacy path is refused (a
361
- * symlinked segment must never be parked/finalized, since finalize deletes it).
362
- * Deliberate behavior change vs. the old `existsSync` probe: a DANGLING symlink
363
- * at the old path was previously silently ignored (existsSync follows links);
364
- * it is now refused, which is fail-closed and correct.
365
- */
366
- export function parkOldNameDir(handle, defsDir, oldRelPath) {
367
- const violation = lockfilePathViolation(oldRelPath);
368
- if (violation) {
369
- throw new Error(`refusing old-name migration path '${oldRelPath}': ${violation}`);
370
- }
371
- const originalPath = join(defsDir, oldRelPath);
372
- // Resolved-path containment: '..'-free by the single-segment rule above, but
373
- // recompute at the rename site so no path outside defsDir can ever be moved.
374
- if (!resolve(originalPath).startsWith(resolve(defsDir) + sep)) {
375
- throw new Error(`refusing old-name migration path '${oldRelPath}': escapes the defs directory`);
376
- }
377
- let st;
378
- try {
379
- st = lstatSync(originalPath); // lstat, not stat: never follow a symlink here.
380
- }
381
- catch (e) {
382
- if (e.code === 'ENOENT')
383
- return; // already gone — nothing to park
384
- throw e;
385
- }
386
- if (st.isSymbolicLink()) {
387
- throw new Error(`refusing old-name migration: '${originalPath}' is a symlink`);
388
- }
389
- if (!st.isDirectory()) {
390
- throw new Error(`refusing old-name migration: '${originalPath}' is not a directory`);
391
- }
392
- const parkedAt = `${handle.undoDir}-oldname`;
393
- renameSync(originalPath, parkedAt);
394
- handle.oldName = { originalPath, parkedAt };
395
- }
396
- /**
397
- * Make the commit permanent: discard the retained previous install and any
398
- * parked old-name dir. Call ONLY after the follow-on lockfile write has durably
399
- * succeeded — this is the point of no return.
400
- */
401
- export function finalizeInstallCommit(handle) {
402
- if (handle.backupDir)
403
- rmSync(handle.backupDir, { recursive: true, force: true });
404
- if (handle.oldName)
405
- rmSync(handle.oldName.parkedAt, { recursive: true, force: true });
406
- }
407
- /**
408
- * Undo a `commitInstall` (plus any `parkOldNameDir`), restoring the pre-commit
409
- * directory state. Order matters:
410
- * 1. park the new content out of `dest` (rename dest → undoDir) — for a fresh
411
- * install, this alone restores "nothing installed";
412
- * 2. if a previous install was displaced, rename its backup back over `dest`;
413
- * 3. if an old-name dir was parked, rename it back to where the lockfile says.
414
- * The parked new content under `undoDir` is left for the caller's staging-root
415
- * cleanup to dispose of. Any throw propagates to the caller.
416
- *
417
- * Safe to call from a FAILED `parkOldNameDir`: that helper records
418
- * `handle.oldName` only after its single rename succeeds, so a park failure
419
- * leaves `oldName` unset and step 3 self-skips — there is no "park partially
420
- * happened" state to reconcile (the park is one atomic rename).
421
- */
422
- export function rollbackInstallCommit(handle) {
423
- renameSync(handle.dest, handle.undoDir);
424
- if (handle.backupDir)
425
- renameSync(handle.backupDir, handle.dest);
426
- if (handle.oldName)
427
- renameSync(handle.oldName.parkedAt, handle.oldName.originalPath);
428
- }
429
- /**
430
- * Acquire the per-project install lock at `lockPath`. A 1-line adapter over the
431
- * generic `acquireFileLock`, pinning `label` so the timeout message reads
432
- * "another owenloop add is in progress …" byte-for-byte as before. Always pair
433
- * with `releaseInstallLock` in a `finally`.
434
- */
435
- export function acquireInstallLock(lockPath, opts = {}) {
436
- return acquireFileLock(lockPath, { label: 'owenloop add', ...opts });
437
- }
438
- /** Release a lock acquired by `acquireInstallLock` — the generic `releaseFileLock`. */
439
- export const releaseInstallLock = releaseFileLock;
440
- // ---- crash-recovery journal ------------------------------------------------
441
- //
442
- // A process that dies (crash, SIGKILL — see docs/cli.md on power-loss limits)
443
- // partway through the destructive part of an install — the `commitInstall` swap,
444
- // the old-name park, or the ledger write — must leave `.owenloop` recoverable to a consistent
445
- // (defs-on-disk ⇔ ledger) state by the NEXT `add`, never a half-applied tree.
446
- // Today's failure arms in `dispatchAdd` only cover IN-PROCESS failures (a throw
447
- // we catch and roll back); a hard kill skips them entirely. This journal closes
448
- // that gap: `dispatchAdd` writes a one-record intent file before the first
449
- // destructive step and advances/removes it as the install progresses, and the
450
- // next `add` runs `recoverInterruptedInstall` under the same A3 install lock,
451
- // BEFORE the stale-staging cleanup, to roll a leftover install forward or back.
452
- //
453
- // The journal is attacker-influenceable input, exactly like the lockfile (a
454
- // hostile checkout can ship a crafted `.owenloop/add.journal`). It is validated
455
- // fail-closed with the A1 discipline (`lockfilePathViolation` on every path
456
- // field, single-segment ⇒ traversal unrepresentable), every mutation path is
457
- // re-derived from the CURRENT run's resolved `defsDir` plus those validated
458
- // segments — never from a recorded absolute path — and A2's symlink rule is
459
- // re-asserted at each mutation site. Any bad shape, unknown phase, defsDir
460
- // mismatch, or contradictory disk state REFUSES with no filesystem mutation and
461
- // leaves the journal in place as evidence.
462
- /** Journal filename under `.owenloop/` (sibling of `installed.json`/`add.lock`). */
463
- export const ADD_JOURNAL_FILENAME = 'add.journal';
464
- /**
465
- * Structurally validate a parsed `add.journal`, fail-closed — the trust
466
- * boundary for the journal, mirroring {@link validateLockfile}. A
467
- * parseable-but-invalid journal is a hard error naming the file and the manual
468
- * remedy; recovery NEVER acts on a field that has not passed through here. Every
469
- * path field must be a safe single segment so a crafted journal cannot represent
470
- * traversal before any `join`/`rename`. Unknown extra keys are tolerated
471
- * (forward compatibility, same as the lockfile). `ref`/`startedAt` are
472
- * diagnostics: validated for type when present, but not required. `path`
473
- * appears only in error messages.
474
- */
475
- export function validateAddJournal(parsed, path) {
476
- const fail = (detail) => {
477
- throw new Error(`invalid crash-recovery journal at ${path}: ${detail} — ` +
478
- `inspect and remove it manually, then re-run add`);
479
- };
480
- if (!isPlainObject(parsed))
481
- return fail('top-level value is not an object');
482
- if (parsed.version !== 1) {
483
- return fail(`unsupported journal version ${JSON.stringify(parsed.version)} (expected 1)`);
484
- }
485
- if (parsed.phase !== 'applying' && parsed.phase !== 'finalizing') {
486
- return fail(`unknown phase ${JSON.stringify(parsed.phase)} (expected 'applying' or 'finalizing')`);
487
- }
488
- if (typeof parsed.source !== 'string' || parsed.source === '') {
489
- return fail("'source' is not a non-empty string");
490
- }
491
- if (typeof parsed.sha !== 'string' || !SHA_HEX_RE.test(parsed.sha)) {
492
- return fail("'sha' is not a 40-char hex commit sha");
493
- }
494
- const segment = (field, value) => {
495
- if (typeof value !== 'string')
496
- fail(`'${field}' is not a string`);
497
- const violation = lockfilePathViolation(value);
498
- if (violation)
499
- fail(`'${field}' ${violation}`);
500
- };
501
- segment('folder', parsed.folder);
502
- segment('stagingId', parsed.stagingId);
503
- if (parsed.oldNamePath !== undefined)
504
- segment('oldNamePath', parsed.oldNamePath);
505
- if (typeof parsed.hadDest !== 'boolean')
506
- return fail("'hadDest' is not a boolean");
507
- if (typeof parsed.defsDir !== 'string' || parsed.defsDir === '') {
508
- return fail("'defsDir' is not a non-empty string");
509
- }
510
- if (parsed.ref !== undefined && typeof parsed.ref !== 'string')
511
- return fail("'ref' is not a string");
512
- if (parsed.startedAt !== undefined && typeof parsed.startedAt !== 'number') {
513
- return fail("'startedAt' is not a number");
514
- }
515
- return parsed;
516
- }
517
- /**
518
- * Read `.owenloop/add.journal`. Absent ⇒ `null` (the happy path — no
519
- * interrupted install to recover). Present-but-unparseable ⇒ a hard error;
520
- * present-but-schema-invalid ⇒ a hard error via {@link validateAddJournal}.
521
- * Never silently ignores a malformed journal (that would let a crafted file
522
- * quietly disable recovery) and never trusts it for filesystem paths.
523
- */
524
- export function readAddJournal(path) {
525
- if (!existsSync(path))
526
- return null;
527
- const raw = readFileSync(path, 'utf8');
528
- let parsed;
529
- try {
530
- parsed = JSON.parse(raw);
531
- }
532
- catch (e) {
533
- throw new Error(`corrupt crash-recovery journal at ${path}: ${e.message} — ` +
534
- `inspect and remove it manually, then re-run add`);
535
- }
536
- return validateAddJournal(parsed, path);
537
- }
538
- /** Write the journal atomically (tmp+rename), same discipline as the lockfile. */
539
- export function writeAddJournal(path, journal, opts = {}) {
540
- writeJsonAtomic(path, journal, opts);
541
- }
542
- /** Remove the journal (force: absence is not an error — clean-completion / idempotent). */
543
- export function removeAddJournal(path) {
544
- rmSync(path, { force: true });
545
- }
546
- /** Build a fail-closed recovery-refusal error naming the journal + manual remedy. */
547
- function recoveryRefusal(journalPath, detail) {
548
- return new Error(`refusing crash-recovery: ${detail} — inspect ${journalPath} and the defs dir, ` +
549
- `resolve the state by hand, then re-run add`);
550
- }
551
- /**
552
- * `lstat`-probe a recovery path: `'dir'` if it is a real directory, `'absent'`
553
- * if it does not exist. Fail-closed on anything else — a symlink (A2 rule: a
554
- * symlinked segment must never be renamed/rm'd, since finalize/rollback would
555
- * act through it) or a non-directory file is refused. `lstat`, never `stat`, so
556
- * a symlink is seen as a symlink, not followed to its target.
557
- *
558
- * The PARENT is checked too, not just the leaf: `lstat` on the leaf sees a
559
- * symlinked leaf, but a symlinked *parent* directory would be silently followed
560
- * by the `rename`/`rm` that acts on the leaf, redirecting the whole mutation
561
- * outside `defsDir` (a hostile checkout planting `.owenloop-staging` as a
562
- * symlink is exactly this). Refuse a symlinked immediate parent before trusting
563
- * the leaf probe. (Absent parent ⇒ the leaf is absent too; nothing to refuse.)
564
- */
565
- function probeRecoveryDir(p, journalPath, label) {
566
- const parent = dirname(p);
567
- const parentSt = lstatSync(parent, { throwIfNoEntry: false });
568
- if (parentSt?.isSymbolicLink()) {
569
- throw recoveryRefusal(journalPath, `${label} parent '${parent}' is a symlink`);
570
- }
571
- let st;
572
- try {
573
- st = lstatSync(p);
574
- }
575
- catch (e) {
576
- if (e.code === 'ENOENT')
577
- return 'absent';
578
- throw e;
579
- }
580
- if (st.isSymbolicLink())
581
- throw recoveryRefusal(journalPath, `${label} at '${p}' is a symlink`);
582
- if (!st.isDirectory())
583
- throw recoveryRefusal(journalPath, `${label} at '${p}' is not a directory`);
584
- return 'dir';
585
- }
586
- /** Re-assert resolved-path containment at a mutation target (belt-and-braces). */
587
- function assertUnderDefs(p, defsDir, journalPath) {
588
- if (!resolve(p).startsWith(resolve(defsDir) + sep)) {
589
- throw recoveryRefusal(journalPath, `path '${p}' escapes the defs directory`);
590
- }
591
- }
592
- /**
593
- * Bring an interrupted install back to a consistent (defs ⇔ ledger) state, then
594
- * remove the journal. Called by `dispatchAdd` under the A3 install lock,
595
- * BEFORE the stale-staging cleanup (the backups a rollback needs live under the
596
- * staging root). No journal ⇒ returns immediately (happy path unchanged).
597
- *
598
- * Roll-forward vs roll-back rule: the durable ledger write is the commit point.
599
- * At or past it, roll FORWARD (finish the discard); before it, roll BACK
600
- * (restore the previous state). Concretely:
601
- *
602
- * 1. `finalizing` ⇒ roll forward: the ledger is durably new; only finalize's
603
- * discards may be missing. Clear the retained backup + parked old-name and
604
- * the staging root. Trivially idempotent.
605
- * 2. `applying` + the ledger already records this source at `journal.sha`/
606
- * `journal.folder` ⇒ the commit MAY have landed, but the ledger match alone
607
- * does not prove it — branch on disk: dest present ⇒ the swap completed ⇒
608
- * roll forward; dest ABSENT ⇒ a same-sha re-add crashed inside commitInstall's
609
- * dest→backup / staging→dest window and backupDir holds the only copy ⇒ roll
610
- * back (restore it) rather than discarding it (which would be silent data
611
- * loss against a ledger that still records the install).
612
- * 3. `applying`, no ledger match (or ledger match with dest absent) ⇒ roll back
613
- * through the guarded, idempotent decision table below (mirroring
614
- * `rollbackInstallCommit`'s order) — EXCEPT the case-(c) fresh-install
615
- * discard, which acts on the journal alone (staging + backup both absent) and
616
- * so requires LEDGER corroboration of an interrupted old-name migration
617
- * (`installed.path === journal.oldNamePath`) before it will delete an
618
- * existing dest; uncorroborated ⇒ refuse fail-closed, mutate nothing, leave
619
- * the journal and dest in place (the journal is repo-committable, so a forged
620
- * one must never drive a deletion).
621
- *
622
- * Crash-safety of recovery itself: the journal is removed LAST, after all
623
- * restore/discard renames, and every step is a single atomic rename guarded by
624
- * existence probes — so a crash mid-recovery leaves the journal intact and a
625
- * strict subset of the work done; the next attempt re-derives state from disk
626
- * and continues (the dest-absent arm of case (b), the touch-nothing arm of
627
- * case (c), and the case-(c) uncorroborated refusal ARE the mid-rollback resume
628
- * / fail-closed states). Running it twice is a no-op the second time.
629
- *
630
- * Any refusal (invalid journal, defsDir mismatch, symlink where a directory is
631
- * expected, contradictory disk state) throws WITHOUT mutating anything and
632
- * leaves the journal in place; `dispatchAdd` sets `preserveStagingRoot` so its
633
- * `finally` cannot then destroy the backups a later attempt needs.
634
- */
635
- export function recoverInterruptedInstall(args) {
636
- const { defsDir, journalPath, lockfilePath } = args;
637
- const journal = readAddJournal(journalPath);
638
- if (journal === null)
639
- return 'no-journal'; // no interrupted install — happy path, unchanged.
640
- // An interrupted install in a DIFFERENT defs tree: recovering "here" would act
641
- // on paths this invocation was never pointed at, and trusting the recorded
642
- // absolute path would let a crafted journal point mutations anywhere. Fail
643
- // closed — the operator must re-run with the same --defs/OWENLOOP_DEFS.
644
- if (resolve(journal.defsDir) !== resolve(defsDir)) {
645
- throw recoveryRefusal(journalPath, `journal records defs dir '${journal.defsDir}', but this add resolved '${resolve(defsDir)}' ` +
646
- `(re-run add with the same --defs/OWENLOOP_DEFS)`);
647
- }
648
- // Every mutation path is derived HERE from the current defsDir + the validated
649
- // single segments — never from the recorded absolute defsDir. These are
650
- // exactly the derivations commitInstall/parkOldNameDir use.
651
- const stagingRoot = join(defsDir, STAGING_DIRNAME);
652
- const stagingDir = join(stagingRoot, journal.stagingId);
653
- const backupDir = `${stagingDir}-old`;
654
- const undoDir = `${stagingDir}-undo`;
655
- const parkedOldName = `${undoDir}-oldname`;
656
- const dest = join(defsDir, journal.folder);
657
- const oldNameOriginal = journal.oldNamePath !== undefined ? join(defsDir, journal.oldNamePath) : undefined;
658
- // Symlink-guard the staging ROOT itself before deriving any mutation from it.
659
- // `dispatchAdd`'s `mkdirRefusingSymlink` guards `.owenloop` and the default
660
- // defsDir, but NOT `<defsDir>/.owenloop-staging` — and stagingDir/backupDir/
661
- // undoDir/parkedOldName all hang off it, so a hostile checkout that ships
662
- // `.owenloop-staging` as a symlink would make every rename/rm below act
663
- // through it, moving/deleting dirs OUTSIDE defsDir. `lstat` (never `stat`) so
664
- // the link is seen as a link; a non-dir squatting there is refused too; absent
665
- // is fine (a fresh recovery mkdirs it). This runs BEFORE any fs mutation, and
666
- // recovery now precedes dispatchAdd's `rmSync(stagingRoot)`, so nothing else
667
- // clears it first.
668
- const stagingRootSt = lstatSync(stagingRoot, { throwIfNoEntry: false });
669
- if (stagingRootSt?.isSymbolicLink()) {
670
- throw recoveryRefusal(journalPath, `staging root '${stagingRoot}' is a symlink`);
671
- }
672
- if (stagingRootSt && !stagingRootSt.isDirectory()) {
673
- throw recoveryRefusal(journalPath, `staging root '${stagingRoot}' is not a directory`);
674
- }
675
- // Belt-and-braces containment: re-assert that EVERY rename/rm source and target
676
- // resolves under defsDir — not just dest/oldNameOriginal, but every staging-
677
- // root-derived path too (a crafted journal + a symlinked staging root must not
678
- // drive a mutation outside the tree). Single-segment folder/oldNamePath/
679
- // stagingId already make lexical traversal unrepresentable; this is the extra
680
- // guard the review asked for on the staging-derived paths.
681
- for (const p of [stagingRoot, stagingDir, backupDir, undoDir, parkedOldName, dest]) {
682
- assertUnderDefs(p, defsDir, journalPath);
683
- }
684
- if (oldNameOriginal !== undefined)
685
- assertUnderDefs(oldNameOriginal, defsDir, journalPath);
686
- // Roll forward: the ledger is durably new; discard the retained backup + parked
687
- // old-name dir and clear the staging root, then drop the journal. Symlink-
688
- // guarded before each rm; both dirs live under the staging root, so the final
689
- // clear is the real cleanup — the explicit rms honor "refuse a symlink" first.
690
- const rollForward = () => {
691
- if (probeRecoveryDir(backupDir, journalPath, 'backup dir') === 'dir') {
692
- rmSync(backupDir, { recursive: true, force: true });
693
- }
694
- if (probeRecoveryDir(parkedOldName, journalPath, 'parked old-name dir') === 'dir') {
695
- rmSync(parkedOldName, { recursive: true, force: true });
696
- }
697
- rmSync(stagingRoot, { recursive: true, force: true });
698
- removeAddJournal(journalPath);
699
- };
700
- if (journal.phase === 'finalizing') {
701
- rollForward();
702
- return 'rolled-forward';
703
- }
704
- // phase === 'applying': the ledger write may or may not have landed. Read it
705
- // (fail-closed validation applies — a corrupt ledger aborts the add exactly as
706
- // it does today) and check whether it already records this exact install.
707
- const lf = readLockfile(lockfilePath);
708
- const installed = lf.installed[journal.source];
709
- if (installed && installed.sha === journal.sha && installed.path === journal.folder) {
710
- // The ledger records this exact source@sha — but a ledger match ALONE does
711
- // NOT prove the commit swap landed. Branch on ACTUAL disk state:
712
- // - dest PRESENT ⇒ the swap completed (a crash in the writeLockfile→phase-
713
- // rewrite window, or a same-sha re-add already past the swap): dest holds
714
- // that sha's content, so (defs ⇔ ledger) is consistent ⇒ roll forward
715
- // (discard the now-stale backup).
716
- // - dest ABSENT ⇒ we are inside commitInstall's 4a→4b window of a SAME-sha
717
- // re-add (dest was renamed to backupDir, and the staging→dest swap never
718
- // ran). backupDir now holds the ONLY copy of the content. Rolling forward
719
- // would `rmSync` it — silent data loss, leaving the ledger claiming an
720
- // install that is gone from disk. Fall THROUGH to the roll-back table,
721
- // which restores backupDir → dest; the ledger already records this sha, so
722
- // the restored state is consistent. The two cases are distinguishable by
723
- // disk, so branch on it rather than trusting the ledger match alone.
724
- if (probeRecoveryDir(dest, journalPath, 'destination') === 'dir') {
725
- rollForward();
726
- return 'rolled-forward';
727
- }
728
- }
729
- // ROLL BACK — restore the pre-commit directory state. Guarded idempotent
730
- // renames mirroring rollbackInstallCommit's order; a symlinked source is
731
- // refused fail-closed at each probe.
732
- mkdirSync(stagingRoot, { recursive: true }); // ensure undo/backup renames have a home
733
- const stagingState = probeRecoveryDir(stagingDir, journalPath, 'staging dir');
734
- const backupState = probeRecoveryDir(backupDir, journalPath, 'backup dir');
735
- if (stagingState === 'dir') {
736
- // (a) Swap 4b (staging → dest) never happened.
737
- if (backupState === 'dir') {
738
- // Crash between 4a (dest → backup) and 4b: dest is necessarily absent.
739
- // Restore the backup. Fail closed if dest unexpectedly exists too.
740
- if (probeRecoveryDir(dest, journalPath, 'destination') === 'dir') {
741
- throw recoveryRefusal(journalPath, `both the backup dir and destination '${dest}' exist`);
742
- }
743
- renameSync(backupDir, dest);
744
- }
745
- // else backup absent: dest still holds the original (upgrade, pre-backup) or
746
- // is absent (fresh install, pre-swap) — already consistent, nothing to move.
747
- }
748
- else if (backupState === 'dir') {
749
- // (b) Staging gone, backup present — an upgrade crashed AFTER the swap.
750
- if (probeRecoveryDir(dest, journalPath, 'destination') === 'dir') {
751
- // Park the new content aside, then restore the backup over dest.
752
- if (probeRecoveryDir(undoDir, journalPath, 'undo dir') === 'dir') {
753
- throw recoveryRefusal(journalPath, `undo dir '${undoDir}' already exists`);
754
- }
755
- renameSync(dest, undoDir);
756
- renameSync(backupDir, dest);
757
- }
758
- else {
759
- // dest absent: a prior rollback/recovery died between its two renames (the
760
- // new content is already parked under undoDir) — just restore the backup.
761
- renameSync(backupDir, dest);
762
- }
763
- }
764
- else {
765
- // (c) Staging gone, backup gone.
766
- if (!journal.hadDest) {
767
- // Fresh install: the swap may have put new content at dest. Discarding it
768
- // (rename → undoDir, then rm with the staging root at step (e)) is the ONLY
769
- // destructive arm that acts on the word of the journal alone — staging and
770
- // backup are both absent by definition of case (c), so the journal is the
771
- // only thing asserting this dir is a crash orphan. But the journal lives in
772
- // repository-controlled content (`.owenloop/add.journal` is committable), so
773
- // a hostile checkout can forge a schema-VALID `applying`/`hadDest:false`
774
- // journal naming an existing UNRELATED workflow dir and drive its deletion.
775
- // Fail closed: only delete when the LEDGER corroborates that this dest is a
776
- // fresh hashed dir left by an interrupted OLD-NAME MIGRATION — i.e. the
777
- // ledger still records `journal.source` at the migration's old-name path
778
- // (`installed.path === journal.oldNamePath`). That is exactly the state of
779
- // the corroborated old-name-migration crash; the parked old-name dir is NOT
780
- // required as evidence (a crash in the swap→park window legitimately has no
781
- // parked dir yet). Anything else — no ledger entry, or an entry at some
782
- // other path (including `journal.folder` itself, which contradicts
783
- // `hadDest:false`) — is uncorroborated: refuse, mutate nothing, leave the
784
- // journal AND dest in place as evidence.
785
- //
786
- // Deliberate, documented regression: the genuine fresh-install crash between
787
- // the swap and the ledger write (dest present, no ledger, no staging, no
788
- // backup) is on-disk INDISTINGUISHABLE from the forgery — every
789
- // distinguishing artifact is itself repo-committable and therefore forgeable
790
- // — so it now fails closed here instead of auto-discarding. The error names
791
- // the manual remedy. Raising the bar from "journal alone" to "journal +
792
- // corroborating ledger" is the scope; moving/authenticating recovery state
793
- // OUTSIDE repository-controlled content is the tracked follow-up (an attacker
794
- // who forges BOTH the journal and a matching ledger old-name entry — or a
795
- // backup dir, reaching case (b) — can still drive destructive recovery).
796
- if (probeRecoveryDir(dest, journalPath, 'destination') === 'dir') {
797
- const migrationCorroborated = journal.oldNamePath !== undefined &&
798
- installed !== undefined &&
799
- installed.path === journal.oldNamePath;
800
- if (!migrationCorroborated) {
801
- throw recoveryRefusal(journalPath, `journal claims an interrupted fresh install of '${journal.folder}', but nothing ` +
802
- `corroborates it (no ledger entry for this source at the journal's old-name path, ` +
803
- `no staging dir, no backup) while '${dest}' exists — refusing to discard that ` +
804
- `directory. If you did not run an interrupted add in this checkout, remove the ` +
805
- `journal; if a fresh install really was interrupted, remove '${dest}' as well`);
806
- }
807
- if (probeRecoveryDir(undoDir, journalPath, 'undo dir') === 'dir') {
808
- throw recoveryRefusal(journalPath, `undo dir '${undoDir}' already exists`);
809
- }
810
- renameSync(dest, undoDir);
811
- }
812
- }
813
- // hadDest === true: the backup was already restored (a completed in-process
814
- // rollback whose journal-remove failed, or a prior recovery attempt) — dirs
815
- // are consistent; touch nothing.
816
- }
817
- // (d) Restore a parked old-name dir to where the (unchanged) ledger expects it.
818
- if (oldNameOriginal !== undefined) {
819
- if (probeRecoveryDir(parkedOldName, journalPath, 'parked old-name dir') === 'dir') {
820
- if (probeRecoveryDir(oldNameOriginal, journalPath, 'old-name original') === 'dir') {
821
- // Both present is contradictory — unreachable under the single-writer
822
- // lock, so don't guess which to keep.
823
- throw recoveryRefusal(journalPath, `both the parked old-name dir and its original '${oldNameOriginal}' exist`);
824
- }
825
- renameSync(parkedOldName, oldNameOriginal);
826
- }
827
- // parked absent ⇒ already restored (idempotent re-run) — skip.
828
- }
829
- // (e) The undo/backup leftovers are debris now; clear the staging root and
830
- // remove the journal LAST so a crash before this leaves everything replayable.
831
- rmSync(stagingRoot, { recursive: true, force: true });
832
- removeAddJournal(journalPath);
833
- return 'rolled-back';
834
- }