owenloop 0.5.0 → 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 (211) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +137 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +8 -4
  5. package/dist/packages/work/src/agent/brief.js +7 -3
  6. package/dist/packages/work/src/agent/loop.d.ts +13 -7
  7. package/dist/packages/work/src/agent/loop.js +136 -9
  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/bundle/cache.d.ts +7 -5
  11. package/dist/packages/work/src/bundle/cache.js +20 -6
  12. package/dist/packages/work/src/bundle/fetch.d.ts +7 -5
  13. package/dist/packages/work/src/bundle/fetch.js +27 -7
  14. package/dist/packages/work/src/bundle/types.d.ts +8 -4
  15. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  16. package/dist/packages/work/src/consumed-verifier.js +205 -0
  17. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  18. package/dist/packages/work/src/exec/instructions.js +323 -0
  19. package/dist/packages/work/src/exec/loop.d.ts +12 -1
  20. package/dist/packages/work/src/exec/loop.js +137 -20
  21. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  22. package/dist/packages/work/src/exec/payload.js +54 -0
  23. package/dist/packages/work/src/exec/receipt.d.ts +9 -6
  24. package/dist/packages/work/src/exec/receipt.js +12 -1
  25. package/dist/packages/work/src/exec/runner.d.ts +7 -1
  26. package/dist/packages/work/src/exec/runner.js +74 -3
  27. package/dist/packages/work/src/harness/child-env.js +7 -0
  28. package/dist/packages/work/src/harness/claude.d.ts +20 -8
  29. package/dist/packages/work/src/harness/claude.js +260 -58
  30. package/dist/packages/work/src/harness/codex.d.ts +5 -4
  31. package/dist/packages/work/src/harness/codex.js +169 -41
  32. package/dist/packages/work/src/harness/contract.d.ts +36 -11
  33. package/dist/packages/work/src/harness/fake.js +1 -0
  34. package/dist/packages/work/src/harness/jsonrpc-stdio.js +7 -0
  35. package/dist/packages/work/src/harness/permissions.d.ts +16 -3
  36. package/dist/packages/work/src/harness/permissions.js +102 -13
  37. package/dist/packages/work/src/harness/session-store.d.ts +27 -9
  38. package/dist/packages/work/src/harness/session-store.js +271 -67
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +126 -11
  41. package/dist/packages/work/src/hub/client.d.ts +2 -1
  42. package/dist/packages/work/src/hub/client.js +14 -1
  43. package/dist/packages/work/src/hub/types.d.ts +69 -33
  44. package/dist/packages/work/src/hub/types.js +8 -10
  45. package/dist/packages/work/src/mcp/server.js +1 -1
  46. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  47. package/dist/packages/work/src/owenloop-bin.js +18 -0
  48. package/dist/packages/work/src/roles/agent-run.d.ts +12 -6
  49. package/dist/packages/work/src/roles/agent-run.js +116 -34
  50. package/dist/packages/work/src/roles/exec.d.ts +8 -0
  51. package/dist/packages/work/src/roles/exec.js +27 -2
  52. package/dist/packages/work/src/roles/hold.d.ts +4 -0
  53. package/dist/packages/work/src/roles/hold.js +44 -5
  54. package/dist/packages/work/src/roles/lint.d.ts +3 -4
  55. package/dist/packages/work/src/roles/lint.js +41 -7
  56. package/dist/packages/work/src/roles/settings.js +5 -0
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +23 -1
  59. package/dist/packages/work/src/settings/settings.d.ts +17 -1
  60. package/dist/packages/work/src/settings/settings.js +39 -0
  61. package/dist/packages/work/src/shift/loop.d.ts +14 -3
  62. package/dist/packages/work/src/shift/loop.js +447 -164
  63. package/dist/packages/work/src/shift/protocol.d.ts +4 -0
  64. package/dist/packages/work/src/shift/runtime.d.ts +2 -0
  65. package/dist/packages/work/src/shift/runtime.js +66 -3
  66. package/dist/packages/work/src/shift/spawn.d.ts +41 -18
  67. package/dist/packages/work/src/shift/spawn.js +89 -31
  68. package/dist/packages/work/src/shift/state.d.ts +53 -51
  69. package/dist/packages/work/src/shift/state.js +325 -102
  70. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  71. package/dist/packages/work/src/submit-proof.js +93 -0
  72. package/dist/src/add.d.ts +64 -259
  73. package/dist/src/add.js +81 -615
  74. package/dist/src/archive.d.ts +97 -0
  75. package/dist/src/archive.js +591 -0
  76. package/dist/src/bundle/index.d.ts +64 -0
  77. package/dist/src/bundle/index.js +508 -0
  78. package/dist/src/bundle/manifest.d.ts +50 -0
  79. package/dist/src/bundle/manifest.js +435 -0
  80. package/dist/src/bundle/runtime.d.ts +26 -0
  81. package/dist/src/bundle/runtime.js +64 -0
  82. package/dist/src/bundle/tar.d.ts +62 -0
  83. package/dist/src/bundle/tar.js +238 -0
  84. package/dist/src/bundle/types.d.ts +105 -0
  85. package/dist/src/bundle/types.js +21 -0
  86. package/dist/src/cli.d.ts +90 -20
  87. package/dist/src/cli.js +2407 -365
  88. package/dist/src/credentials.d.ts +4 -3
  89. package/dist/src/credentials.js +21 -19
  90. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  91. package/dist/src/crypto/allowed-signers.js +307 -0
  92. package/dist/src/crypto/canonical.d.ts +8 -0
  93. package/dist/src/crypto/canonical.js +92 -0
  94. package/dist/src/crypto/chain.d.ts +65 -0
  95. package/dist/src/crypto/chain.js +377 -0
  96. package/dist/src/crypto/dsse.d.ts +209 -0
  97. package/dist/src/crypto/dsse.js +282 -0
  98. package/dist/src/crypto/enrollment.d.ts +78 -0
  99. package/dist/src/crypto/enrollment.js +186 -0
  100. package/dist/src/crypto/index.d.ts +48 -0
  101. package/dist/src/crypto/index.js +44 -0
  102. package/dist/src/crypto/keys.d.ts +258 -0
  103. package/dist/src/crypto/keys.js +908 -0
  104. package/dist/src/crypto/org-root.d.ts +33 -0
  105. package/dist/src/crypto/org-root.js +78 -0
  106. package/dist/src/crypto/origin-rules.d.ts +56 -0
  107. package/dist/src/crypto/origin-rules.js +143 -0
  108. package/dist/src/crypto/policy-floor.d.ts +98 -0
  109. package/dist/src/crypto/policy-floor.js +353 -0
  110. package/dist/src/crypto/records.d.ts +316 -0
  111. package/dist/src/crypto/records.js +157 -0
  112. package/dist/src/crypto/scope.d.ts +49 -0
  113. package/dist/src/crypto/scope.js +83 -0
  114. package/dist/src/crypto/ssh.d.ts +171 -0
  115. package/dist/src/crypto/ssh.js +396 -0
  116. package/dist/src/crypto/submission.d.ts +33 -0
  117. package/dist/src/crypto/submission.js +47 -0
  118. package/dist/src/crypto/trust-roots.d.ts +29 -0
  119. package/dist/src/crypto/trust-roots.js +39 -0
  120. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  121. package/dist/src/crypto/verify-consumed.js +259 -0
  122. package/dist/src/crypto/verify-origin.d.ts +50 -0
  123. package/dist/src/crypto/verify-origin.js +151 -0
  124. package/dist/src/crypto/verify-publication.d.ts +60 -0
  125. package/dist/src/crypto/verify-publication.js +150 -0
  126. package/dist/src/defs.d.ts +24 -1
  127. package/dist/src/defs.js +145 -25
  128. package/dist/src/engine.d.ts +99 -3
  129. package/dist/src/engine.js +238 -34
  130. package/dist/src/factory.d.ts +16 -0
  131. package/dist/src/factory.js +16 -4
  132. package/dist/src/global-config.d.ts +59 -0
  133. package/dist/src/global-config.js +84 -0
  134. package/dist/src/hub.d.ts +75 -21
  135. package/dist/src/hub.js +123 -40
  136. package/dist/src/index.d.ts +17 -2
  137. package/dist/src/index.js +20 -2
  138. package/dist/src/install.d.ts +538 -0
  139. package/dist/src/install.js +1981 -0
  140. package/dist/src/lock.d.ts +15 -57
  141. package/dist/src/lock.js +251 -143
  142. package/dist/src/mcp/serve.d.ts +46 -22
  143. package/dist/src/mcp/serve.js +167 -44
  144. package/dist/src/mcp/server.js +12 -1
  145. package/dist/src/model.d.ts +15 -0
  146. package/dist/src/model.js +111 -1
  147. package/dist/src/order-resolver.d.ts +184 -0
  148. package/dist/src/order-resolver.js +252 -0
  149. package/dist/src/package-version.d.ts +10 -0
  150. package/dist/src/package-version.js +42 -0
  151. package/dist/src/paths.d.ts +14 -1
  152. package/dist/src/paths.js +18 -0
  153. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  154. package/dist/src/schemas/index.d.ts +1416 -0
  155. package/dist/src/schemas/index.js +31 -0
  156. package/dist/src/schemas/order.v1.schema.json +106 -0
  157. package/dist/src/schemas/origin.v1.schema.json +68 -0
  158. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  159. package/dist/src/schemas/publication.v1.schema.json +31 -0
  160. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  161. package/dist/src/schemas/submission.v1.schema.json +61 -0
  162. package/dist/src/store/def-source.d.ts +52 -0
  163. package/dist/src/store/def-source.js +335 -0
  164. package/dist/src/store/index-file.d.ts +69 -0
  165. package/dist/src/store/index-file.js +151 -0
  166. package/dist/src/store/index.d.ts +27 -0
  167. package/dist/src/store/index.js +22 -0
  168. package/dist/src/store/ingestor.d.ts +43 -0
  169. package/dist/src/store/ingestor.js +211 -0
  170. package/dist/src/store/install.d.ts +228 -0
  171. package/dist/src/store/install.js +555 -0
  172. package/dist/src/store/instruction-source.d.ts +49 -0
  173. package/dist/src/store/instruction-source.js +298 -0
  174. package/dist/src/store/origin-evidence.d.ts +21 -0
  175. package/dist/src/store/origin-evidence.js +66 -0
  176. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  177. package/dist/src/store/pre-commit-verifier.js +418 -0
  178. package/dist/src/store/resolve.d.ts +138 -0
  179. package/dist/src/store/resolve.js +363 -0
  180. package/dist/src/store/types.d.ts +288 -0
  181. package/dist/src/store/types.js +356 -0
  182. package/dist/src/types.d.ts +45 -11
  183. package/dist/src/untar.d.ts +8 -23
  184. package/dist/src/untar.js +10 -136
  185. package/docs/agent-runner.md +86 -0
  186. package/docs/authoring.md +57 -6
  187. package/docs/bundles.md +250 -0
  188. package/docs/cli.md +1171 -97
  189. package/docs/crypto.md +816 -0
  190. package/docs/design.md +342 -20
  191. package/docs/embedding.md +132 -25
  192. package/docs/wire-contracts.md +380 -0
  193. package/package.json +6 -1
  194. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  195. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  196. package/plugins/claude-code/plugin/.mcp.json +14 -0
  197. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  198. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  199. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  200. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  201. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  202. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  203. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  204. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  205. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  206. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  207. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  208. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  209. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  210. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  211. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
@@ -0,0 +1,1981 @@
1
+ /**
2
+ * The host-neutral install transaction shared by every route that swaps a
3
+ * validated staging tree into place atomically: safe staging, the atomic
4
+ * destination→backup / staging→destination swap with a retained backup,
5
+ * finalize/rollback, the atomic metadata write, the per-root install lock, the
6
+ * base applying/finalizing crash-journal phases, the v2 repair substates, and
7
+ * recovery driven by durable phase, metadata, and actual filesystem state.
8
+ *
9
+ * Two consumers share it today:
10
+ * - `src/add.ts` (the GitHub `owenloop add` route): metadata = `installed.json`,
11
+ * destination segment = a single folder directly under the defs dir, v1
12
+ * journal schema (a 40-char GitHub sha + source/ref ledger corroboration).
13
+ * - `src/store/install.ts` (the content-addressed workflow store): metadata =
14
+ * `index.json`, destination segment = a three-segment object path
15
+ * (`objects/sha256/<digest>`), v2 journal schema (identity = a
16
+ * metadata-hash match, no route-specific fields).
17
+ *
18
+ * For v1, fresh v2 installs, and v2 dedupe, the durable COMMIT POINT is the
19
+ * atomic METADATA write. Same-digest v2 repair is different: the metadata may
20
+ * already contain the target digest before replacement starts, so a matching
21
+ * metadata hash is never enough to accept the replacement. Repair recovery
22
+ * restores the prior backup or resumes recursive hardening plus exact content
23
+ * and mode verification; only `finalizing` makes the prior backup disposable.
24
+ * The journal is removed LAST so recovery stays idempotent (running it again
25
+ * changes nothing).
26
+ *
27
+ * The journal is attacker-influenceable input (it may sit in a repo checkout):
28
+ * every path field is validated fail-closed as a safe single segment, and every
29
+ * mutation path is re-derived from the CURRENT run's resolved root plus those
30
+ * validated segments — never from a recorded absolute path. A bad shape,
31
+ * unknown phase, root mismatch, or contradictory disk state REFUSES with no
32
+ * filesystem mutation and leaves the journal in place as evidence.
33
+ *
34
+ * Engine core: this module imports Node builtins and core helpers only — it
35
+ * never imports `cli.ts`, `add.ts`, `untar.ts`, or a hub module.
36
+ */
37
+ import { chmodSync, closeSync, constants as fsConstants, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, writeFileSync, } from 'node:fs';
38
+ import { dirname, join, parse, relative, resolve, sep } from 'node:path';
39
+ import { createHash, randomUUID } from 'node:crypto';
40
+ import { acquireFileLock, releaseFileLock } from "./lock.js";
41
+ import { archivePathViolation } from "./archive.js";
42
+ import { mkdirRefusingSymlink } from "./util.js";
43
+ // ---- safe paths --------------------------------------------------------------
44
+ // Re-export the neutral archive policy so add callers retain their historical
45
+ // import path while add, untar, and bundle all use the same function identity.
46
+ export { archivePathViolation } from "./archive.js";
47
+ /**
48
+ * Returns `undefined` if `relPath` is a safe SINGLE-SEGMENT path, else a
49
+ * human-readable reason it must be rejected. Stricter than
50
+ * {@link archivePathViolation}: ANY separator is refused outright. That one
51
+ * rule makes `..` traversal and nested escape shapes unrepresentable before
52
+ * any `join`/`rename` ever touches the path. Used for the GitHub route's
53
+ * top-level destination segment and every journal path segment field.
54
+ * Reject-don't-normalize, like {@link archivePathViolation}.
55
+ */
56
+ export function lockfilePathViolation(relPath) {
57
+ const base = archivePathViolation(relPath);
58
+ if (base)
59
+ return base;
60
+ if (/[\\/]/.test(relPath))
61
+ return 'contains a path separator';
62
+ return undefined;
63
+ }
64
+ /**
65
+ * Returns `undefined` if `relPath` is a safe MULTI-SEGMENT path under a store
66
+ * root (the CAS object path `objects/sha256/<digest>` is three segments), else
67
+ * a human-readable reason it must be rejected. Applies
68
+ * {@link archivePathViolation} to the whole path and to EVERY segment — the
69
+ * CAS destination segment set is never trusted from disk; it is validated
70
+ * fail-closed before any join or rename.
71
+ */
72
+ export function multiSegmentPathViolation(relPath) {
73
+ const whole = archivePathViolation(relPath);
74
+ if (whole)
75
+ return whole;
76
+ const segments = relPath.split(/[\\/]+/);
77
+ if (segments.length === 0)
78
+ return 'empty path';
79
+ for (const segment of segments) {
80
+ const violation = lockfilePathViolation(segment);
81
+ if (violation)
82
+ return `segment '${segment}' ${violation}`;
83
+ }
84
+ return undefined;
85
+ }
86
+ /**
87
+ * Ensure a state directory is real before a caller creates or writes below it.
88
+ * The final directory and its immediate parent are checked with `lstat`; the
89
+ * caller's existing filesystem root may contain an operator/system symlink
90
+ * (for example macOS's `/var`), which is outside the state directory boundary.
91
+ * Missing directories are created recursively and the final leaf is checked
92
+ * again before the caller proceeds.
93
+ */
94
+ export function ensureDirectoryPathNoSymlink(dir, label = 'directory') {
95
+ const absolute = resolve(dir);
96
+ const parent = dirname(absolute);
97
+ const parentSt = lstatSync(parent, { throwIfNoEntry: false });
98
+ if (parentSt?.isSymbolicLink()) {
99
+ throw new Error(`refusing to use ${label} '${absolute}': its parent '${parent}' is a symbolic link`);
100
+ }
101
+ if (parentSt && !parentSt.isDirectory()) {
102
+ throw new Error(`refusing to use ${label} '${absolute}': its parent '${parent}' is not a directory`);
103
+ }
104
+ let st = lstatSync(absolute, { throwIfNoEntry: false });
105
+ if (st === undefined) {
106
+ mkdirSync(absolute, { recursive: true });
107
+ st = lstatSync(absolute, { throwIfNoEntry: false });
108
+ }
109
+ if (st === undefined) {
110
+ throw new Error(`refusing to use ${label} '${absolute}': it disappeared during creation`);
111
+ }
112
+ if (st.isSymbolicLink()) {
113
+ throw new Error(`refusing to use ${label} '${absolute}': it is a symlink`);
114
+ }
115
+ if (!st.isDirectory()) {
116
+ throw new Error(`refusing to use ${label} '${absolute}': it is not a directory`);
117
+ }
118
+ }
119
+ /** Refuse a symlink or non-regular-file state leaf; an absent leaf is allowed. */
120
+ export function guardStateFile(path, label = 'state file') {
121
+ const st = lstatSync(path, { throwIfNoEntry: false });
122
+ if (st === undefined)
123
+ return;
124
+ if (st.isSymbolicLink()) {
125
+ throw new Error(`refusing to use ${label} '${path}': it is a symlink`);
126
+ }
127
+ if (!st.isFile()) {
128
+ throw new Error(`refusing to use ${label} '${path}': it is not a regular file`);
129
+ }
130
+ }
131
+ /**
132
+ * Read one regular file without following a symlink during the open. The
133
+ * initial `lstat` rejects a planted link or non-file, and `O_NOFOLLOW` closes
134
+ * the replace-between-check-and-open window. An absent file returns undefined
135
+ * so callers can distinguish an empty file (which still needs parsing) from a
136
+ * never-created metadata file.
137
+ */
138
+ export function readRegularFileNoFollow(path, label = 'file') {
139
+ const st = lstatSync(path, { throwIfNoEntry: false });
140
+ if (st === undefined)
141
+ return undefined;
142
+ if (st.isSymbolicLink()) {
143
+ throw new Error(`refusing to read ${label} '${path}': it is a symlink`);
144
+ }
145
+ if (!st.isFile()) {
146
+ throw new Error(`refusing to read ${label} '${path}': it is not a regular file`);
147
+ }
148
+ let fd;
149
+ try {
150
+ fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
151
+ }
152
+ catch (e) {
153
+ const code = e.code;
154
+ if (code === 'ENOENT')
155
+ return undefined;
156
+ if (code === 'ELOOP') {
157
+ throw new Error(`refusing to read ${label} '${path}': it is a symlink`);
158
+ }
159
+ throw e;
160
+ }
161
+ try {
162
+ return readFileSync(fd);
163
+ }
164
+ finally {
165
+ closeSync(fd);
166
+ }
167
+ }
168
+ /**
169
+ * Probe a directory path without following symlinks through any component.
170
+ * Missing components mean the path is absent; an existing symlink or non-dir
171
+ * component is an integrity failure. This is used for CAS object ownership and
172
+ * recovery probes, where `existsSync` would incorrectly follow links.
173
+ */
174
+ export function probeDirectoryPath(path, label = 'directory', trustedBoundary) {
175
+ const absolute = resolve(path);
176
+ const start = trustedBoundary === undefined ? parse(absolute).root : resolve(trustedBoundary);
177
+ const remainder = relative(start, absolute);
178
+ if (remainder === '' || (!trustedBoundary && remainder.startsWith('..')))
179
+ return 'dir';
180
+ if (trustedBoundary && (remainder === '..' || remainder.startsWith(`..${sep}`))) {
181
+ throw new Error(`refusing to use ${label} '${absolute}': it escapes trusted boundary '${start}'`);
182
+ }
183
+ let current = start;
184
+ for (const segment of remainder.split(sep).filter(Boolean)) {
185
+ current = join(current, segment);
186
+ const st = lstatSync(current, { throwIfNoEntry: false });
187
+ if (st === undefined)
188
+ return 'absent';
189
+ if (st.isSymbolicLink()) {
190
+ throw new Error(`refusing to use ${label} '${current}': it is a symlink`);
191
+ }
192
+ if (!st.isDirectory()) {
193
+ throw new Error(`refusing to use ${label} '${current}': it is not a directory`);
194
+ }
195
+ }
196
+ return 'dir';
197
+ }
198
+ /**
199
+ * Serialize `value` as pretty JSON into a sibling temp file, then `renameSync`
200
+ * over `path` — one atomic tmp+rename discipline shared by the lockfile, the
201
+ * crash-recovery journal, and the workflow-store index. A crash or a
202
+ * concurrent reader never sees a half-written file (rename is atomic within a
203
+ * directory).
204
+ *
205
+ * If the final `renameSync` throws (EACCES, EISDIR on `path`, a full disk),
206
+ * the temp sibling is removed on a best-effort basis before the error
207
+ * propagates so a failed write cannot leak a `<path>.tmp.<pid>` file. The
208
+ * original rename error is surfaced unchanged — never swallowed, and never
209
+ * masked by a failure of that cleanup removal (if the removal itself throws,
210
+ * that error is swallowed and the tmp sibling may remain in that double fault).
211
+ */
212
+ export function writeJsonAtomic(path, value, opts = {}) {
213
+ const rm = opts.rm ?? ((p, o) => rmSync(p, o));
214
+ mkdirSync(dirname(path), { recursive: true });
215
+ const tmp = `${path}.tmp.${process.pid}`;
216
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
217
+ try {
218
+ renameSync(tmp, path);
219
+ }
220
+ catch (e) {
221
+ try {
222
+ rm(tmp, { force: true });
223
+ }
224
+ catch {
225
+ // ignore — surfacing the original rename error matters more than cleanup.
226
+ }
227
+ throw e;
228
+ }
229
+ }
230
+ // ---- staging + atomic commit --------------------------------------------------
231
+ /** The staging root under a root dir where installs are assembled + validated. */
232
+ export const STAGING_DIRNAME = '.owenloop-staging';
233
+ /**
234
+ * Recursively remove `dir` WITHOUT requiring write permission inside it.
235
+ * Content-addressed objects are committed read-only + non-writable (files
236
+ * 0o444, dirs 0o555) — hardening is defense in depth, and it means a plain
237
+ * `rmSync` (which unlinks each entry through its PARENT dir's write mode)
238
+ * dies with EACCES as soon as a swapped-out backup or staging debris holds a
239
+ * hardened object. Each directory restores its own write+search modes BEFORE
240
+ * its entries are unlinked, so no level ever removes through a 0o555 dir —
241
+ * and a STORED object is never made transiently writable, only its doomed
242
+ * staging/undo/backup copy. Absent ⇒ no-op (idempotent). Every throw
243
+ * propagates: a half-removed staging root is the caller's error, never a
244
+ * silent leak.
245
+ */
246
+ export function rmRecursiveForce(dir) {
247
+ let st;
248
+ try {
249
+ st = lstatSync(dir);
250
+ }
251
+ catch (e) {
252
+ if (e.code === 'ENOENT')
253
+ return;
254
+ throw e;
255
+ }
256
+ if (st.isSymbolicLink() || !st.isDirectory()) {
257
+ rmSync(dir, { force: true });
258
+ return;
259
+ }
260
+ chmodSync(dir, 0o755); // writable/searchable BEFORE any of its entries leave
261
+ for (const entry of readdirSync(dir)) {
262
+ const full = join(dir, entry);
263
+ const entrySt = lstatSync(full);
264
+ if (entrySt.isDirectory()) {
265
+ rmRecursiveForce(full);
266
+ }
267
+ else {
268
+ rmSync(full, { force: true });
269
+ }
270
+ }
271
+ rmdirSync(dir); // empty now — rmSync refuses directories outright
272
+ }
273
+ /**
274
+ * Write `files` (relative path → bytes) into `targetDir` (a staging dir), NOT
275
+ * the final install destination. Unlike a direct install, this never clears a
276
+ * live folder: the caller stages here, validates, then `commitInstall`s with an
277
+ * atomic rename, so a failure mid-write can only ever corrupt throwaway staging
278
+ * content. Returns the sorted list of relative paths written.
279
+ */
280
+ export function stageFiles(targetDir, files) {
281
+ const written = [];
282
+ for (const [relPath, bytes] of files) {
283
+ // Defense-in-depth: this function is exported and writes whole directory
284
+ // trees, so it must not trust its caller to have validated keys.
285
+ const violation = archivePathViolation(relPath);
286
+ if (violation) {
287
+ throw new Error(`refusing to write unsafe archive path '${relPath}': ${violation}`);
288
+ }
289
+ const full = join(targetDir, relPath);
290
+ mkdirSync(dirname(full), { recursive: true });
291
+ writeFileSync(full, bytes);
292
+ written.push(relPath);
293
+ }
294
+ return written.sort();
295
+ }
296
+ /**
297
+ * Thrown by `commitInstall` when the atomic swap fails AND the rollback of it
298
+ * fails too — a near-impossible same-filesystem double-fault. Carries the path
299
+ * where the previous version was left so the caller can preserve it (its
300
+ * `preservedAt` sits under the staging root, which the caller would otherwise
301
+ * clean up as debris). A distinguishable type so the caller can tell this
302
+ * "must-preserve" double-fault apart from an ordinary swap failure.
303
+ */
304
+ export class RollbackFailedError extends Error {
305
+ preservedAt;
306
+ constructor(message, preservedAt) {
307
+ super(message);
308
+ this.name = 'RollbackFailedError';
309
+ this.preservedAt = preservedAt;
310
+ }
311
+ }
312
+ /**
313
+ * Atomically swap a validated `stagingDir` into place at `root/<destRelPath>`.
314
+ * Both live on the same filesystem by construction (staging is under `root`),
315
+ * so the renames are atomic and `EXDEV` is impossible. `destRelPath` is a
316
+ * MULTI-SEGMENT path (a top-level folder for the GitHub route,
317
+ * `objects/sha256/<digest>` for the CAS route) and is re-validated HERE, at
318
+ * the mutation site — defense-in-depth alongside the callers' checks.
319
+ *
320
+ * Two-phase commit: unlike a one-shot swap, this does NOT delete the displaced
321
+ * previous install on success — it returns an {@link InstallCommitHandle} whose
322
+ * `backupDir` still holds it. The caller must then either
323
+ * {@link finalizeInstallCommit} (discard the backup, making the swap permanent)
324
+ * once its follow-on work — the metadata write — has durably succeeded, or
325
+ * {@link rollbackInstallCommit} to restore the previous directory state if that
326
+ * work fails. This is what lets "commit the directory + write the metadata" be
327
+ * one recoverable operation.
328
+ *
329
+ * Sequence: back up any existing install (rename dest → `<stagingDir>-old`) —
330
+ * if that fails nothing has changed; rename staging → dest; on failure rename
331
+ * the backup back (throwing {@link RollbackFailedError} if even that fails, so
332
+ * the caller can preserve the named copy).
333
+ */
334
+ export function commitInstall(root, destRelPath, stagingDir, options = {}) {
335
+ const violation = multiSegmentPathViolation(destRelPath);
336
+ if (violation) {
337
+ throw new Error(`refusing to install unsafe destination path '${destRelPath}': ${violation}`);
338
+ }
339
+ // Permissive on `root`: whether a symlinked root is operator intent
340
+ // (the GitHub route's explicit --defs) or a refusal (the CAS route) is the
341
+ // CALLER's decision — this mutation site does not second-guess it.
342
+ mkdirSync(root, { recursive: true });
343
+ const dest = join(root, destRelPath);
344
+ // The CAS destination is MULTI-SEGMENT (`objects/sha256/<digest>`): its
345
+ // intermediate parents may not exist yet, and `renameSync` does not create
346
+ // them (ENOENT). Each MISSING intermediate is created symlink-guarded
347
+ // (SEC-3), and an EXISTING intermediate that is a symlink or non-directory
348
+ // is refused fail-closed — a hostile `objects/sha256 -> /elsewhere` would
349
+ // otherwise redirect the swap. The GitHub route's single-segment dest has no
350
+ // intermediates, so this loop is a no-op there and the operator-intent
351
+ // symlinked root above stays honored.
352
+ const segments = destRelPath.split('/');
353
+ let parent = root;
354
+ for (let i = 0; i < segments.length - 1; i++) {
355
+ const seg = segments[i];
356
+ if (seg === undefined) {
357
+ // Unreachable — the loop bound guarantees `i < segments.length - 1`.
358
+ throw new Error('internal error: missing path segment during install commit');
359
+ }
360
+ parent = join(parent, seg);
361
+ const st = lstatSync(parent, { throwIfNoEntry: false });
362
+ if (st === undefined) {
363
+ mkdirRefusingSymlink(parent);
364
+ }
365
+ else if (st.isSymbolicLink()) {
366
+ throw new Error(`refusing to install below '${parent}': an intermediate destination parent is a symlink`);
367
+ }
368
+ else if (!st.isDirectory()) {
369
+ throw new Error(`refusing to install below '${parent}': an intermediate destination parent is not a directory`);
370
+ }
371
+ }
372
+ const backupDir = `${stagingDir}-old`;
373
+ const undoDir = `${stagingDir}-undo`;
374
+ let backedUp = false;
375
+ try {
376
+ if (probeDirectoryPath(dest, 'install destination', root) === 'dir') {
377
+ // Ownership is verified by the caller before we get here. If this rename
378
+ // throws, nothing has changed — dest is still the previous install. The
379
+ // rename restores write modes first: the displaced dir may hold a hardened
380
+ // CAS object (an index-less object dir being overwritten is rare, but the
381
+ // move must work when it happens).
382
+ renameDirRestoringWrite(dest, backupDir);
383
+ backedUp = true;
384
+ options.afterBackupRename?.();
385
+ }
386
+ renameSync(stagingDir, dest);
387
+ }
388
+ catch (e) {
389
+ if (backedUp) {
390
+ try {
391
+ renameDirRestoringWrite(backupDir, dest);
392
+ }
393
+ catch (rollbackErr) {
394
+ // Near-impossible (same fs), but if even the rollback fails, name the
395
+ // backup so the previous version is recoverable by hand — and signal
396
+ // (via the type) that the caller must preserve it.
397
+ throw new RollbackFailedError(`install of '${destRelPath}' failed and rollback failed too; ` +
398
+ `previous version preserved at ${backupDir}: ${rollbackErr.message}`, backupDir);
399
+ }
400
+ }
401
+ throw e;
402
+ }
403
+ return { dest, destRelPath, backupDir: backedUp ? backupDir : undefined, undoDir };
404
+ }
405
+ /**
406
+ * Make the commit permanent: discard the retained previous install. Call ONLY
407
+ * after the follow-on metadata write has durably succeeded — this is the point
408
+ * of no return.
409
+ */
410
+ export function finalizeInstallCommit(handle) {
411
+ // The backup may hold a hardened CAS object (0o444/0o555) — force-remove it
412
+ // without requiring write permission inside it (see `rmRecursiveForce`).
413
+ if (handle.backupDir)
414
+ rmRecursiveForce(handle.backupDir);
415
+ }
416
+ /**
417
+ * Rename a real directory while preserving its exact 0o7777 root mode. macOS
418
+ * requires owner-write on a non-writable directory for rename even though the
419
+ * source and destination parents are writable. The optional `persistedMode`
420
+ * comes from durable transaction identity evidence written before the first
421
+ * chmod; recovery passes that value instead of inferring an original mode from
422
+ * a path that may still carry the temporary owner-write bit after a crash.
423
+ */
424
+ export function renameDirRestoringWrite(src, dst, persistedMode) {
425
+ const sourceStat = lstatSync(src);
426
+ if (sourceStat.isSymbolicLink() || !sourceStat.isDirectory()) {
427
+ throw new Error(`refusing to rename '${src}': source is not a real directory`);
428
+ }
429
+ const sourceMode = sourceStat.mode & 0o7777;
430
+ const originalMode = persistedMode ?? sourceMode;
431
+ if (!Number.isInteger(originalMode) || originalMode < 0 || originalMode > 0o7777) {
432
+ throw new Error(`refusing to rename '${src}': persisted mode is invalid`);
433
+ }
434
+ const temporaryMode = originalMode | 0o200;
435
+ if (sourceMode !== temporaryMode)
436
+ chmodSync(src, temporaryMode);
437
+ try {
438
+ renameSync(src, dst);
439
+ }
440
+ catch (renameError) {
441
+ if (temporaryMode !== originalMode) {
442
+ try {
443
+ chmodSync(src, originalMode);
444
+ }
445
+ catch (restoreError) {
446
+ throw new AggregateError([renameError, restoreError], `rename of '${src}' to '${dst}' failed and restoring source mode ${originalMode.toString(8)} failed`);
447
+ }
448
+ }
449
+ throw renameError;
450
+ }
451
+ if (temporaryMode === originalMode)
452
+ return;
453
+ try {
454
+ chmodSync(dst, originalMode);
455
+ }
456
+ catch (restoreError) {
457
+ // Do not leave a moved object writable. Best-effort move it back and restore
458
+ // the persisted source mode; preserve both faults if that rollback fails.
459
+ try {
460
+ renameSync(dst, src);
461
+ chmodSync(src, originalMode);
462
+ }
463
+ catch (rollbackError) {
464
+ throw new AggregateError([restoreError, rollbackError], `renamed '${src}' to '${dst}' but could not restore mode ${originalMode.toString(8)} or move it back`);
465
+ }
466
+ throw restoreError;
467
+ }
468
+ }
469
+ /**
470
+ * Undo a `commitInstall`, restoring the pre-commit directory state. Order
471
+ * matters: (1) durably record rollback intent when the caller supplies a
472
+ * `beforeRollback` hook; (2) park the new content out of `dest` (rename dest →
473
+ * undoDir) — for a fresh install, this alone restores "nothing installed";
474
+ * (3) if a previous install was displaced, rename its backup back over `dest`;
475
+ * (4) optionally delete the parked replacement after the prior object is back.
476
+ *
477
+ * Every transition hook runs AFTER the transition named by the hook. A hook
478
+ * failure stops the state machine immediately and leaves the previous durable
479
+ * journal phase plus the newly observable filesystem state for recovery. The
480
+ * default options retain the historical generic behavior: no journal hooks and
481
+ * the undo directory left for the caller's staging-root cleanup.
482
+ *
483
+ * Renames go through {@link renameDirRestoringWrite}: the CAS route hardens
484
+ * objects at their committed location, so `dest` may already be non-writable
485
+ * when a late rollback (the index write failing) runs. Any throw propagates.
486
+ */
487
+ export function rollbackInstallCommit(handle, options = {}) {
488
+ options.beforeRollback?.();
489
+ const undoState = lstatSync(handle.undoDir, { throwIfNoEntry: false });
490
+ if (undoState !== undefined) {
491
+ throw new Error(`refusing rollback because undo path '${handle.undoDir}' already exists`);
492
+ }
493
+ renameDirRestoringWrite(handle.dest, handle.undoDir);
494
+ options.afterDestinationParked?.();
495
+ if (handle.backupDir) {
496
+ renameDirRestoringWrite(handle.backupDir, handle.dest);
497
+ options.afterPriorRestored?.();
498
+ }
499
+ if (options.cleanupUndo) {
500
+ rmRecursiveForce(handle.undoDir);
501
+ options.afterUndoCleanup?.();
502
+ }
503
+ }
504
+ /**
505
+ * Acquire the install lock at `lockPath`. A 1-line adapter over the generic
506
+ * `acquireFileLock`, pinning `label` so the timeout message reads "another
507
+ * owenloop add is in progress …" byte-for-byte as before. Always pair with
508
+ * `releaseInstallLock` in a `finally`.
509
+ */
510
+ export function acquireInstallLock(lockPath, opts = {}) {
511
+ mkdirRefusingSymlink(dirname(lockPath));
512
+ guardStateFile(lockPath, 'install lock');
513
+ return acquireFileLock(lockPath, { label: 'owenloop add', ...opts });
514
+ }
515
+ /** Release a lock acquired by `acquireInstallLock` — the generic `releaseFileLock`. */
516
+ export const releaseInstallLock = releaseFileLock;
517
+ // ---- crash-recovery journal ------------------------------------------------
518
+ //
519
+ // A process that dies (crash, SIGKILL) partway through the destructive part of
520
+ // an install — the commit swap or the metadata write — must leave the root
521
+ // recoverable to a consistent (tree ⇔ metadata) state by the NEXT install,
522
+ // never a half-applied tree. The journal is written before the first
523
+ // destructive step, advanced/removed as the install progresses, and the next
524
+ // install runs `recoverInterruptedInstall` under the same lock BEFORE the
525
+ // stale-staging cleanup (the backups a rollback needs live under the staging
526
+ // root).
527
+ //
528
+ // Two journal versions:
529
+ // - v1 (the GitHub route): `sha` is a 40-char GitHub commit sha and
530
+ // commit-point detection matches the `installed.json` ledger on
531
+ // source+sha+path (with old-name migration corroboration).
532
+ // - v2 (the CAS route and any future route): identity-free except for the
533
+ // destination segment set; ordinary commit-point detection hashes the
534
+ // CURRENT metadata bytes against the journal's `metadataHash`. Same-digest
535
+ // repair instead uses explicit replacement phases because the index hash may
536
+ // match before the replacement starts. No route-specific schema (no 40-char
537
+ // sha) is baked into the generic transaction.
538
+ //
539
+ // `recoverInterruptedInstall` reads BOTH versions and dispatches on `version`,
540
+ // so `owenloop add --recover` recovers a journal written by an older release
541
+ // (v1) or by the CAS route (v2) identically.
542
+ /** The crash-recovery journal filename (a sibling of the lock + metadata file). */
543
+ export const ADD_JOURNAL_FILENAME = 'add.journal';
544
+ function isPlainObject(value) {
545
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
546
+ }
547
+ /** A 40-char hex commit sha (case-insensitive), as GitHub returns. */
548
+ const SHA_HEX_RE = /^[0-9a-f]{40}$/i;
549
+ /** A lowercase 64-char SHA-256 hex digest — v2 metadata hashes and CAS digests. */
550
+ const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
551
+ /** The shared "fix it by hand" journal error. `path` appears only in the message. */
552
+ function journalValidationError(path, detail) {
553
+ return new Error(`invalid crash-recovery journal at ${path}: ${detail} — ` +
554
+ `inspect and remove it manually, then re-run add`);
555
+ }
556
+ /**
557
+ * Structurally validate a parsed v1 `add.journal`, fail-closed — the trust
558
+ * boundary for v1 journals, mirroring the lockfile's validator. A
559
+ * parseable-but-invalid journal is a hard error naming the file and the manual
560
+ * remedy; recovery NEVER acts on a field that has not passed through here.
561
+ * Every path field must be a safe single segment so a crafted journal cannot
562
+ * represent traversal before any `join`/`rename`. Unknown extra keys are
563
+ * tolerated (forward compatibility, same as the lockfile). `ref`/`startedAt`
564
+ * are diagnostics: validated for type when present, but not required. `path`
565
+ * appears only in error messages.
566
+ */
567
+ export function validateAddJournal(parsed, path) {
568
+ const fail = (detail) => {
569
+ throw journalValidationError(path, detail);
570
+ };
571
+ if (!isPlainObject(parsed))
572
+ return fail('top-level value is not an object');
573
+ if (parsed.version !== 1) {
574
+ return fail(`unsupported journal version ${JSON.stringify(parsed.version)} (expected 1)`);
575
+ }
576
+ if (parsed.phase !== 'applying' && parsed.phase !== 'finalizing') {
577
+ return fail(`unknown phase ${JSON.stringify(parsed.phase)} (expected 'applying' or 'finalizing')`);
578
+ }
579
+ if (typeof parsed.source !== 'string' || parsed.source === '') {
580
+ return fail("'source' is not a non-empty string");
581
+ }
582
+ if (typeof parsed.sha !== 'string' || !SHA_HEX_RE.test(parsed.sha)) {
583
+ return fail("'sha' is not a 40-char hex commit sha");
584
+ }
585
+ const segment = (field, value) => {
586
+ if (typeof value !== 'string')
587
+ fail(`'${field}' is not a string`);
588
+ const violation = lockfilePathViolation(value);
589
+ if (violation)
590
+ fail(`'${field}' ${violation}`);
591
+ };
592
+ segment('folder', parsed.folder);
593
+ segment('stagingId', parsed.stagingId);
594
+ if (parsed.oldNamePath !== undefined)
595
+ segment('oldNamePath', parsed.oldNamePath);
596
+ if (typeof parsed.hadDest !== 'boolean')
597
+ return fail("'hadDest' is not a boolean");
598
+ if (typeof parsed.defsDir !== 'string' || parsed.defsDir === '') {
599
+ return fail("'defsDir' is not a non-empty string");
600
+ }
601
+ if (parsed.ref !== undefined && typeof parsed.ref !== 'string')
602
+ return fail("'ref' is not a string");
603
+ if (parsed.startedAt !== undefined && typeof parsed.startedAt !== 'number') {
604
+ return fail("'startedAt' is not a number");
605
+ }
606
+ return parsed;
607
+ }
608
+ /**
609
+ * Structurally validate a parsed v2 journal, fail-closed — the trust boundary
610
+ * for route-neutral journals, same discipline as {@link validateAddJournal}:
611
+ * hard error naming the file on any bad shape, unknown extra keys tolerated,
612
+ * path fields validated as safe single segments, `root` equality-only,
613
+ * `metadataHash` a strict lowercase 64-hex value (never normalized).
614
+ */
615
+ export function validateInstallJournalV2(parsed, path) {
616
+ const fail = (detail) => {
617
+ throw journalValidationError(path, detail);
618
+ };
619
+ if (!isPlainObject(parsed))
620
+ return fail('top-level value is not an object');
621
+ if (parsed.version !== 2) {
622
+ return fail(`unsupported journal version ${JSON.stringify(parsed.version)} (expected 2)`);
623
+ }
624
+ if (parsed.phase !== 'applying' &&
625
+ parsed.phase !== 'replacement-swapped' &&
626
+ parsed.phase !== 'replacement-hardened' &&
627
+ parsed.phase !== 'replacement-verified' &&
628
+ parsed.phase !== 'rollback-started' &&
629
+ parsed.phase !== 'rollback-replacement-parked' &&
630
+ parsed.phase !== 'rollback-prior-restored' &&
631
+ parsed.phase !== 'rollback-complete' &&
632
+ parsed.phase !== 'finalizing') {
633
+ return fail(`unknown phase ${JSON.stringify(parsed.phase)} ` +
634
+ `(expected 'applying', replacement/rollback repair phases, or 'finalizing')`);
635
+ }
636
+ if (parsed.operation !== undefined &&
637
+ parsed.operation !== 'install' &&
638
+ parsed.operation !== 'dedupe' &&
639
+ parsed.operation !== 'repair') {
640
+ return fail("'operation' is not 'install', 'dedupe', or 'repair'");
641
+ }
642
+ const repairOnlyPhase = typeof parsed.phase === 'string' &&
643
+ (parsed.phase.startsWith('replacement-') || parsed.phase.startsWith('rollback-'));
644
+ if (repairOnlyPhase && parsed.operation !== 'repair') {
645
+ return fail(`phase '${parsed.phase}' requires operation 'repair'`);
646
+ }
647
+ if (parsed.operation === 'repair' && parsed.hadDest !== true) {
648
+ return fail("operation 'repair' requires 'hadDest' true");
649
+ }
650
+ if (parsed.operation === 'dedupe' && parsed.hadDest !== true) {
651
+ return fail("operation 'dedupe' requires 'hadDest' true");
652
+ }
653
+ if (parsed.operation === 'install' && parsed.hadDest !== false) {
654
+ return fail("operation 'install' requires 'hadDest' false");
655
+ }
656
+ if (!Array.isArray(parsed.destSegments) || parsed.destSegments.length === 0) {
657
+ return fail("'destSegments' is not a non-empty array");
658
+ }
659
+ parsed.destSegments.forEach((segmentValue, i) => {
660
+ if (typeof segmentValue !== 'string')
661
+ fail(`'destSegments[${i}]' is not a string`);
662
+ const violation = lockfilePathViolation(segmentValue);
663
+ if (violation)
664
+ fail(`'destSegments[${i}]' ${violation}`);
665
+ });
666
+ if (typeof parsed.stagingId !== 'string')
667
+ return fail("'stagingId' is not a string");
668
+ const stagingViolation = lockfilePathViolation(parsed.stagingId);
669
+ if (stagingViolation)
670
+ return fail(`'stagingId' ${stagingViolation}`);
671
+ if (typeof parsed.hadDest !== 'boolean')
672
+ return fail("'hadDest' is not a boolean");
673
+ if (typeof parsed.root !== 'string' || parsed.root === '') {
674
+ return fail("'root' is not a non-empty string");
675
+ }
676
+ if (typeof parsed.metadataHash !== 'string' || !SHA256_HEX_RE.test(parsed.metadataHash)) {
677
+ return fail("'metadataHash' is not a lowercase 64-char sha256 hex digest");
678
+ }
679
+ if (parsed.label !== undefined && typeof parsed.label !== 'string') {
680
+ return fail("'label' is not a string");
681
+ }
682
+ if (parsed.startedAt !== undefined && typeof parsed.startedAt !== 'number') {
683
+ return fail("'startedAt' is not a number");
684
+ }
685
+ if (parsed.recoveryMarkerId !== undefined) {
686
+ if (typeof parsed.recoveryMarkerId !== 'string')
687
+ return fail("'recoveryMarkerId' is not a string");
688
+ const markerViolation = lockfilePathViolation(parsed.recoveryMarkerId);
689
+ if (markerViolation)
690
+ return fail(`'recoveryMarkerId' ${markerViolation}`);
691
+ }
692
+ if (parsed.rollbackReplacementMode !== undefined &&
693
+ (typeof parsed.rollbackReplacementMode !== 'number' ||
694
+ !Number.isInteger(parsed.rollbackReplacementMode) ||
695
+ parsed.rollbackReplacementMode < 0 ||
696
+ parsed.rollbackReplacementMode > 0o7777)) {
697
+ return fail("'rollbackReplacementMode' is not an integer 0..4095");
698
+ }
699
+ if (typeof parsed.phase === 'string' &&
700
+ parsed.phase.startsWith('rollback-') &&
701
+ parsed.recoveryMarkerId === undefined) {
702
+ return fail(`phase '${parsed.phase}' requires a recovery marker`);
703
+ }
704
+ return parsed;
705
+ }
706
+ /**
707
+ * Validate a parsed journal of EITHER version (fail-closed, per-version).
708
+ * `readAddJournal` dispatches here on the raw `version` field, so a v2 journal
709
+ * is validated by the v2 rules and a v1 journal by the v1 rules — an older
710
+ * release's journal and a CAS route's journal both recover.
711
+ */
712
+ export function validateAnyInstallJournal(parsed, path) {
713
+ const version = isPlainObject(parsed) ? parsed.version : undefined;
714
+ if (version === 1)
715
+ return validateAddJournal(parsed, path);
716
+ if (version === 2)
717
+ return validateInstallJournalV2(parsed, path);
718
+ throw journalValidationError(path, `unsupported journal version ${JSON.stringify(version)} (expected 1 or 2)`);
719
+ }
720
+ /** Derive the external marker directory from the caller's injected home. */
721
+ export function defaultRecoveryMarkerDir(home) {
722
+ if (home.trim() === '')
723
+ throw new Error('cannot derive recovery marker directory from an empty home');
724
+ return join(home, '.owenloop', 'recovery-markers');
725
+ }
726
+ function markerFilePath(markerDir, id) {
727
+ const violation = lockfilePathViolation(id);
728
+ if (violation)
729
+ throw new Error(`invalid recovery marker id '${id}': ${violation}`);
730
+ return join(markerDir, `${id}.json`);
731
+ }
732
+ function validateRecoveryDirectoryIdentity(value, field, fail) {
733
+ if (!isPlainObject(value))
734
+ return fail(`'${field}' is not an object`);
735
+ if (typeof value.dev !== 'string' || !/^\d+$/.test(value.dev)) {
736
+ return fail(`'${field}.dev' is not a decimal string`);
737
+ }
738
+ if (typeof value.ino !== 'string' || !/^\d+$/.test(value.ino)) {
739
+ return fail(`'${field}.ino' is not a decimal string`);
740
+ }
741
+ if (value.mode !== undefined &&
742
+ (typeof value.mode !== 'number' || !Number.isInteger(value.mode) || value.mode < 0 || value.mode > 0o7777)) {
743
+ return fail(`'${field}.mode' is not an integer 0..4095`);
744
+ }
745
+ return value;
746
+ }
747
+ function recoveryDirectoryIdentity(path, label) {
748
+ const st = lstatSync(path, { bigint: true });
749
+ if (st.isSymbolicLink() || !st.isDirectory()) {
750
+ throw new Error(`cannot record ${label} identity at '${path}': path is not a real directory`);
751
+ }
752
+ return { dev: String(st.dev), ino: String(st.ino), mode: Number(st.mode & 4095n) };
753
+ }
754
+ function validateRecoveryMarker(parsed, path) {
755
+ const fail = (detail) => {
756
+ throw new Error(`invalid recovery marker at ${path}: ${detail}`);
757
+ };
758
+ if (!isPlainObject(parsed))
759
+ return fail('top-level value is not an object');
760
+ if (parsed.version !== 1)
761
+ return fail('unsupported marker version');
762
+ if (typeof parsed.root !== 'string' || parsed.root === '')
763
+ return fail("'root' is not a non-empty string");
764
+ if (parsed.rootIdentity !== undefined) {
765
+ validateRecoveryDirectoryIdentity(parsed.rootIdentity, 'rootIdentity', fail);
766
+ }
767
+ if (!Array.isArray(parsed.destSegments) || parsed.destSegments.length === 0) {
768
+ return fail("'destSegments' is not a non-empty array");
769
+ }
770
+ for (const [i, value] of parsed.destSegments.entries()) {
771
+ if (typeof value !== 'string')
772
+ return fail(`'destSegments[${i}]' is not a string`);
773
+ const violation = lockfilePathViolation(value);
774
+ if (violation)
775
+ return fail(`'destSegments[${i}]' ${violation}`);
776
+ }
777
+ if (typeof parsed.stagingId !== 'string')
778
+ return fail("'stagingId' is not a string");
779
+ const stagingViolation = lockfilePathViolation(parsed.stagingId);
780
+ if (stagingViolation)
781
+ return fail(`'stagingId' ${stagingViolation}`);
782
+ if (typeof parsed.hadDest !== 'boolean')
783
+ return fail("'hadDest' is not a boolean");
784
+ if (parsed.operation !== undefined &&
785
+ parsed.operation !== 'install' &&
786
+ parsed.operation !== 'repair') {
787
+ return fail("'operation' is not 'install' or 'repair'");
788
+ }
789
+ if (parsed.operation === undefined && parsed.hadDest !== false) {
790
+ return fail("a legacy marker without 'operation' requires 'hadDest' false");
791
+ }
792
+ if (parsed.operation === 'install' && parsed.hadDest !== false) {
793
+ return fail("operation 'install' requires 'hadDest' false");
794
+ }
795
+ if (parsed.operation === 'repair' && parsed.hadDest !== true) {
796
+ return fail("operation 'repair' requires 'hadDest' true");
797
+ }
798
+ if (parsed.replacementIdentity !== undefined) {
799
+ validateRecoveryDirectoryIdentity(parsed.replacementIdentity, 'replacementIdentity', fail);
800
+ }
801
+ if (parsed.priorIdentity !== undefined) {
802
+ validateRecoveryDirectoryIdentity(parsed.priorIdentity, 'priorIdentity', fail);
803
+ }
804
+ if (parsed.priorIdentity !== undefined && parsed.operation !== 'repair') {
805
+ return fail("'priorIdentity' requires operation 'repair'");
806
+ }
807
+ if (parsed.operation === 'repair' && parsed.replacementIdentity === undefined) {
808
+ return fail("operation 'repair' requires 'replacementIdentity'");
809
+ }
810
+ return parsed;
811
+ }
812
+ export function createRecoveryMarker(input) {
813
+ const markerDir = input.markerDir;
814
+ ensureDirectoryPathNoSymlink(markerDir, 'recovery marker directory');
815
+ if (input.operation === 'repair' && input.replacementDir === undefined) {
816
+ throw new Error('cannot create a repair recovery marker without the staged replacement directory');
817
+ }
818
+ const record = {
819
+ version: 1,
820
+ root: resolve(input.root),
821
+ rootIdentity: recoveryDirectoryIdentity(input.root, 'store root'),
822
+ destSegments: [...input.destSegments],
823
+ stagingId: input.stagingId,
824
+ hadDest: input.operation === 'repair',
825
+ ...(input.operation === undefined ? {} : { operation: input.operation }),
826
+ ...(input.replacementDir === undefined
827
+ ? {}
828
+ : { replacementIdentity: recoveryDirectoryIdentity(input.replacementDir, 'replacement directory') }),
829
+ };
830
+ const id = `mkr_${randomUUID().replaceAll('-', '')}`;
831
+ const path = markerFilePath(markerDir, id);
832
+ writeFileSync(path, `${JSON.stringify(record, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
833
+ return { id, path, markerDir, record };
834
+ }
835
+ /**
836
+ * Add the retained prior-directory identity after destination → backup. The
837
+ * marker is outside the store root, so a repository-controlled journal cannot
838
+ * forge which inode is the prior object or which inode is the replacement.
839
+ */
840
+ export function recordRecoveryMarkerPriorIdentity(handle, priorDir) {
841
+ const current = readRecoveryMarker(handle.id, handle.markerDir);
842
+ if (current === null)
843
+ throw new Error(`recovery marker '${handle.path}' disappeared`);
844
+ if (current.operation !== 'repair' || current.hadDest !== true) {
845
+ throw new Error(`recovery marker '${handle.path}' does not describe a repair`);
846
+ }
847
+ if (current.priorIdentity !== undefined) {
848
+ throw new Error(`recovery marker '${handle.path}' already records a prior object`);
849
+ }
850
+ const record = {
851
+ ...current,
852
+ priorIdentity: recoveryDirectoryIdentity(priorDir, 'retained prior directory'),
853
+ };
854
+ guardStateFile(handle.path, 'recovery marker');
855
+ const tmp = `${handle.path}.tmp.${process.pid}.${randomUUID()}`;
856
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
857
+ try {
858
+ renameSync(tmp, handle.path);
859
+ }
860
+ catch (error) {
861
+ rmSync(tmp, { force: true });
862
+ throw error;
863
+ }
864
+ handle.record = record;
865
+ return handle;
866
+ }
867
+ export function readRecoveryMarker(id, markerDir) {
868
+ // The marker directory is an operator-selected external path. Check the
869
+ // directory leaf and immediate parent, while allowing platform-managed
870
+ // aliases such as macOS /var → /private/var above that boundary.
871
+ if (probeDirectoryPath(markerDir, 'recovery marker directory', dirname(markerDir)) === 'absent')
872
+ return null;
873
+ const path = markerFilePath(markerDir, id);
874
+ const st = lstatSync(path, { throwIfNoEntry: false });
875
+ if (st === undefined)
876
+ return null;
877
+ guardStateFile(path, 'recovery marker');
878
+ let parsed;
879
+ try {
880
+ parsed = JSON.parse(readFileSync(path, 'utf8'));
881
+ }
882
+ catch (e) {
883
+ throw new Error(`corrupt recovery marker at ${path}: ${e.message}`);
884
+ }
885
+ return validateRecoveryMarker(parsed, path);
886
+ }
887
+ export function removeRecoveryMarker(handle) {
888
+ const markerDir = handle.markerDir;
889
+ if (probeDirectoryPath(markerDir, 'recovery marker directory', dirname(markerDir)) === 'absent')
890
+ return;
891
+ const path = markerFilePath(markerDir, handle.id);
892
+ guardStateFile(path, 'recovery marker');
893
+ rmSync(path, { force: true });
894
+ }
895
+ /**
896
+ * Read the crash-recovery journal (either version). Absent ⇒ `null` (the happy
897
+ * path — no interrupted install to recover). Present-but-unparseable ⇒ a hard
898
+ * error; present-but-schema-invalid ⇒ a hard error via
899
+ * {@link validateAnyInstallJournal}. Never silently ignores a malformed journal
900
+ * (that would let a crafted file quietly disable recovery) and never trusts it
901
+ * for filesystem paths.
902
+ */
903
+ export function readAddJournal(path) {
904
+ const st = lstatSync(path, { throwIfNoEntry: false });
905
+ if (st === undefined)
906
+ return null;
907
+ guardStateFile(path, 'crash-recovery journal');
908
+ const raw = readFileSync(path, 'utf8');
909
+ let parsed;
910
+ try {
911
+ parsed = JSON.parse(raw);
912
+ }
913
+ catch (e) {
914
+ throw new Error(`corrupt crash-recovery journal at ${path}: ${e.message} — ` +
915
+ `inspect and remove it manually, then re-run add`);
916
+ }
917
+ return validateAnyInstallJournal(parsed, path);
918
+ }
919
+ /** Write a journal record atomically (tmp+rename), same discipline as the metadata file. */
920
+ export function writeAddJournal(path, journal, opts = {}) {
921
+ guardStateFile(path, 'crash-recovery journal');
922
+ writeJsonAtomic(path, journal, opts);
923
+ }
924
+ /** Remove the journal (force: absence is not an error — clean-completion / idempotent). */
925
+ export function removeAddJournal(path) {
926
+ guardStateFile(path, 'crash-recovery journal');
927
+ rmSync(path, { force: true });
928
+ }
929
+ /** SHA-256 hex of raw bytes — the v2 journal's commit-point test primitive. */
930
+ export function sha256Hex(data) {
931
+ return createHash('sha256').update(data).digest('hex');
932
+ }
933
+ /** Serialize metadata canonically before hashing/writing (same bytes both times). */
934
+ export function canonicalJsonBytes(value) {
935
+ return new TextEncoder().encode(`${JSON.stringify(value, null, 2)}\n`);
936
+ }
937
+ // ---- recovery ------------------------------------------------------------------
938
+ /** Build a fail-closed recovery-refusal error naming the journal + manual remedy. */
939
+ function recoveryRefusal(journalPath, detail) {
940
+ return new Error(`refusing crash-recovery: ${detail} — inspect ${journalPath} and the defs dir, ` +
941
+ `resolve the state by hand, then re-run add`);
942
+ }
943
+ function sameRecoveryDirectoryIdentity(left, right) {
944
+ return left.dev === right.dev && left.ino === right.ino;
945
+ }
946
+ function currentRecoveryRootIdentity(defsDir, journalPath) {
947
+ try {
948
+ return recoveryDirectoryIdentity(defsDir, 'current store root');
949
+ }
950
+ catch (error) {
951
+ throw recoveryRefusal(journalPath, error.message);
952
+ }
953
+ }
954
+ function verifyMarkerRootIdentityWhenPresent(marker, defsDir, journalPath, markerPath) {
955
+ if (marker.rootIdentity === undefined)
956
+ return;
957
+ const actual = currentRecoveryRootIdentity(defsDir, journalPath);
958
+ if (!sameRecoveryDirectoryIdentity(marker.rootIdentity, actual)) {
959
+ throw recoveryRefusal(journalPath, `external recovery marker '${markerPath}' does not belong to the current store-root inode ` +
960
+ `(expected dev ${marker.rootIdentity.dev} inode ${marker.rootIdentity.ino}, ` +
961
+ `got dev ${actual.dev} inode ${actual.ino})`);
962
+ }
963
+ }
964
+ function requireMarkerRootIdentity(marker, defsDir, journalPath, markerPath) {
965
+ if (marker.rootIdentity === undefined) {
966
+ throw recoveryRefusal(journalPath, `external recovery marker '${markerPath}' for the current root lacks store-root identity evidence`);
967
+ }
968
+ verifyMarkerRootIdentityWhenPresent(marker, defsDir, journalPath, markerPath);
969
+ }
970
+ /**
971
+ * Reconcile markers created before their journal write. Callers hold the
972
+ * per-store install lock, and this function runs only after proving the current
973
+ * journal is absent, so no active same-root transaction can own one of these
974
+ * markers. A marker is removable only when its resolved root plus exact root
975
+ * inode identify this store and its derived transaction topology still matches
976
+ * the pre-journal state. Unattributable evidence (other roots, malformed JSON,
977
+ * unknown filenames, symlinks, and non-files) is preserved untouched.
978
+ */
979
+ function reconcileOrphanRecoveryMarkers(args) {
980
+ const markerDir = args.recoveryMarkerDir;
981
+ if (markerDir === undefined)
982
+ return;
983
+ let markerDirState;
984
+ try {
985
+ markerDirState = probeDirectoryPath(markerDir, 'recovery marker directory', dirname(markerDir));
986
+ }
987
+ catch (error) {
988
+ throw recoveryRefusal(args.journalPath, error.message);
989
+ }
990
+ if (markerDirState === 'absent')
991
+ return;
992
+ const root = resolve(args.defsDir);
993
+ const plans = [];
994
+ const entries = readdirSync(markerDir, { withFileTypes: true })
995
+ .sort((left, right) => Buffer.compare(Buffer.from(left.name, 'utf8'), Buffer.from(right.name, 'utf8')));
996
+ for (const entry of entries) {
997
+ const match = /^(mkr_[0-9a-f]{32})\.json$/.exec(entry.name);
998
+ if (match === null || !entry.isFile())
999
+ continue;
1000
+ const id = match[1];
1001
+ if (id === undefined)
1002
+ continue;
1003
+ const path = join(markerDir, entry.name);
1004
+ let parsed;
1005
+ try {
1006
+ const raw = readRegularFileNoFollow(path, 'recovery marker');
1007
+ if (raw === undefined)
1008
+ continue;
1009
+ parsed = JSON.parse(Buffer.from(raw).toString('utf8'));
1010
+ }
1011
+ catch {
1012
+ // Without a validated root field, this evidence cannot safely be assigned
1013
+ // to the current root. Preserve it for manual inspection without blocking
1014
+ // unrelated stores that share the external marker directory.
1015
+ continue;
1016
+ }
1017
+ if (!isPlainObject(parsed) || typeof parsed.root !== 'string' || resolve(parsed.root) !== root) {
1018
+ continue;
1019
+ }
1020
+ let marker;
1021
+ try {
1022
+ marker = validateRecoveryMarker(parsed, path);
1023
+ }
1024
+ catch (error) {
1025
+ throw recoveryRefusal(args.journalPath, `external recovery marker '${path}' attributed to the current root is invalid: ${error.message}`);
1026
+ }
1027
+ requireMarkerRootIdentity(marker, args.defsDir, args.journalPath, path);
1028
+ if (marker.operation === undefined ||
1029
+ marker.replacementIdentity === undefined) {
1030
+ throw recoveryRefusal(args.journalPath, `external recovery marker '${path}' lacks complete pre-journal transaction identity evidence`);
1031
+ }
1032
+ const stagingRoot = join(args.defsDir, STAGING_DIRNAME);
1033
+ const stagingDir = join(stagingRoot, marker.stagingId);
1034
+ const backupDir = `${stagingDir}-old`;
1035
+ const undoDir = `${stagingDir}-undo`;
1036
+ const destination = join(args.defsDir, ...marker.destSegments);
1037
+ for (const candidate of [stagingRoot, stagingDir, backupDir, undoDir, destination]) {
1038
+ assertUnderRoot(candidate, args.defsDir, args.journalPath);
1039
+ }
1040
+ const state = {
1041
+ staging: probeRecoveryDir(stagingDir, args.journalPath, 'orphan marker staging dir', args.defsDir),
1042
+ backup: probeRecoveryDir(backupDir, args.journalPath, 'orphan marker backup dir', args.defsDir),
1043
+ undo: probeRecoveryDir(undoDir, args.journalPath, 'orphan marker undo dir', args.defsDir),
1044
+ destination: probeRecoveryDir(destination, args.journalPath, 'orphan marker destination', args.defsDir),
1045
+ };
1046
+ if (state.backup !== 'absent' || state.undo !== 'absent') {
1047
+ throw recoveryRefusal(args.journalPath, `external recovery marker '${path}' has destructive transaction residue without a journal ` +
1048
+ `(backup=${state.backup}, undo=${state.undo})`);
1049
+ }
1050
+ let stagingIdentity;
1051
+ if (state.staging === 'dir') {
1052
+ try {
1053
+ stagingIdentity = recoveryDirectoryIdentity(stagingDir, 'orphan marker staging directory');
1054
+ }
1055
+ catch (error) {
1056
+ throw recoveryRefusal(args.journalPath, error.message);
1057
+ }
1058
+ if (!sameRecoveryDirectoryIdentity(stagingIdentity, marker.replacementIdentity)) {
1059
+ throw recoveryRefusal(args.journalPath, `external recovery marker '${path}' staging directory does not belong to the transaction ` +
1060
+ `(expected dev ${marker.replacementIdentity.dev} inode ${marker.replacementIdentity.ino}, ` +
1061
+ `got dev ${stagingIdentity.dev} inode ${stagingIdentity.ino})`);
1062
+ }
1063
+ }
1064
+ if (marker.operation === 'install') {
1065
+ if (state.destination !== 'absent') {
1066
+ throw recoveryRefusal(args.journalPath, `external install recovery marker '${path}' has a destination without a journal; ` +
1067
+ `refusing to remove either path`);
1068
+ }
1069
+ }
1070
+ else {
1071
+ if (state.destination !== 'dir') {
1072
+ throw recoveryRefusal(args.journalPath, `external repair recovery marker '${path}' has no unchanged prior destination`);
1073
+ }
1074
+ if (marker.priorIdentity !== undefined) {
1075
+ let actualPrior;
1076
+ try {
1077
+ actualPrior = recoveryDirectoryIdentity(destination, 'orphan marker prior destination');
1078
+ }
1079
+ catch (error) {
1080
+ throw recoveryRefusal(args.journalPath, error.message);
1081
+ }
1082
+ if (!sameRecoveryDirectoryIdentity(actualPrior, marker.priorIdentity)) {
1083
+ throw recoveryRefusal(args.journalPath, `external recovery marker '${path}' prior destination does not belong to the transaction ` +
1084
+ `(expected dev ${marker.priorIdentity.dev} inode ${marker.priorIdentity.ino}, ` +
1085
+ `got dev ${actualPrior.dev} inode ${actualPrior.ino})`);
1086
+ }
1087
+ }
1088
+ }
1089
+ if (plans.some((plan) => plan.stagingDir === stagingDir)) {
1090
+ throw recoveryRefusal(args.journalPath, `multiple external recovery markers claim staging directory '${stagingDir}'`);
1091
+ }
1092
+ plans.push({ id, path, stagingDir, stagingIdentity });
1093
+ }
1094
+ // Validation above is all-or-nothing: contradictory same-root evidence refuses
1095
+ // before any cleanup. Each mutation below is exact and replayable. If a crash
1096
+ // lands after staging removal but before marker removal, the next pass sees an
1097
+ // absent staging path and completes marker cleanup.
1098
+ for (const plan of plans) {
1099
+ if (plan.stagingIdentity !== undefined) {
1100
+ const current = recoveryDirectoryIdentity(plan.stagingDir, 'orphan marker staging directory');
1101
+ if (!sameRecoveryDirectoryIdentity(current, plan.stagingIdentity)) {
1102
+ throw recoveryRefusal(args.journalPath, `orphan marker staging directory '${plan.stagingDir}' changed before cleanup`);
1103
+ }
1104
+ rmRecursiveForce(plan.stagingDir);
1105
+ }
1106
+ removeRecoveryMarker({ id: plan.id, markerDir });
1107
+ }
1108
+ const stagingRoot = join(args.defsDir, STAGING_DIRNAME);
1109
+ if (probeRecoveryDir(stagingRoot, args.journalPath, 'staging root', args.defsDir) === 'dir' &&
1110
+ readdirSync(stagingRoot).length === 0) {
1111
+ rmdirSync(stagingRoot);
1112
+ }
1113
+ }
1114
+ /**
1115
+ * `lstat`-probe a recovery path: `'dir'` if it is a real directory, `'absent'`
1116
+ * if it does not exist. Fail-closed on anything else — a symlink (SEC-3: a
1117
+ * symlinked segment must never be renamed/rm'd, since finalize/rollback would
1118
+ * act through it) or a non-directory file is refused. `lstat`, never `stat`,
1119
+ * so a symlink is seen as a symlink, not followed to its target.
1120
+ *
1121
+ * The PARENT is checked too, not just the leaf: `lstat` on the leaf sees a
1122
+ * symlinked leaf, but a symlinked *parent* directory would be silently followed
1123
+ * by the `rename`/`rm` that acts on the leaf, redirecting the whole mutation
1124
+ * outside the root (a hostile checkout planting `.owenloop-staging` as a
1125
+ * symlink is exactly this). Refuse a symlinked immediate parent before trusting
1126
+ * the leaf probe. (Absent parent ⇒ the leaf is absent too; nothing to refuse.)
1127
+ */
1128
+ function probeRecoveryDir(p, journalPath, label, trustedBoundary) {
1129
+ try {
1130
+ return probeDirectoryPath(p, label, trustedBoundary);
1131
+ }
1132
+ catch (e) {
1133
+ throw recoveryRefusal(journalPath, e.message);
1134
+ }
1135
+ }
1136
+ /** Re-assert resolved-path containment at a mutation target (belt-and-braces). */
1137
+ function assertUnderRoot(p, root, journalPath) {
1138
+ if (!resolve(p).startsWith(resolve(root) + sep)) {
1139
+ throw recoveryRefusal(journalPath, `path '${p}' escapes the install root`);
1140
+ }
1141
+ }
1142
+ /**
1143
+ * Bring an interrupted install back to a consistent (tree ⇔ metadata) state,
1144
+ * then remove the journal. Called by install dispatchers under the root's
1145
+ * install lock, BEFORE the stale-staging cleanup (the backups a rollback needs
1146
+ * live under the staging root). With no journal, recovery first reconciles only
1147
+ * same-root external markers whose inode evidence and untouched pre-journal
1148
+ * topology prove a crash between marker creation and the journal write, then
1149
+ * returns `no-journal`. Reads BOTH journal versions and dispatches on `version`.
1150
+ *
1151
+ * Ordinary v1/v2 transactions use the durable metadata write as the commit
1152
+ * point. Same-digest v2 repair cannot: the index may already match before the
1153
+ * replacement starts, so explicit replacement phases control recovery.
1154
+ * Concretely:
1155
+ *
1156
+ * 1. `finalizing` ⇒ roll forward. V2 first re-verifies the exact destination's
1157
+ * canonical bytes and hardened modes; only then may recovery discard the
1158
+ * retained backup and staging root. V1 has no CAS verifier and performs the
1159
+ * original cleanup behavior.
1160
+ * 2. V2 repair in `applying`, `replacement-swapped`,
1161
+ * `replacement-hardened`, or `replacement-verified` ⇒ use an exhaustive
1162
+ * phase/topology table. Every accepted arm requires the matching external
1163
+ * marker and exact directory identities before mutation. Proven pre-swap or
1164
+ * interrupted legacy rollback states first enter `rollback-started`; the
1165
+ * durable rollback phases perform every rename and cleanup. A replacement at
1166
+ * destination with the retained prior backup resumes hardening/verification
1167
+ * and advances to `finalizing`. Every other combination refuses unchanged.
1168
+ * 3. Ordinary `applying` + the commit-point test passes (v1: ledger records
1169
+ * this exact source@sha/path; v2: `hash(current metadata bytes) ===
1170
+ * metadataHash`) ⇒ the commit MAY have landed, but the test alone does not
1171
+ * prove it. Destination present means the swap completed and recovery rolls
1172
+ * forward. Destination absent means recovery is inside the destination →
1173
+ * backup / staging → destination window, so recovery restores the backup
1174
+ * instead of deleting the only copy.
1175
+ * 4. Ordinary `applying`, commit point not reached ⇒ roll back through the
1176
+ * guarded, idempotent decision table below (mirroring
1177
+ * `rollbackInstallCommit`'s order) — EXCEPT the v1 case-(c) fresh-install
1178
+ * discard, which acts on the journal alone and therefore requires ledger
1179
+ * corroboration of an interrupted old-name migration. V2 has no
1180
+ * journal-alone destructive arm, so a forged v2 journal cannot delete an
1181
+ * unrelated destination.
1182
+ *
1183
+ * Crash-safety of recovery itself: the journal is removed LAST, after all
1184
+ * restore/discard renames, and every step is a single atomic rename guarded by
1185
+ * existence probes — so a crash mid-recovery leaves the journal intact and a
1186
+ * strict subset of the work done; the next attempt re-derives state from disk
1187
+ * and continues. Running it twice is a no-op the second time.
1188
+ *
1189
+ * Any refusal (invalid journal, root mismatch, symlink where a directory is
1190
+ * expected, contradictory disk state) throws WITHOUT mutating anything and
1191
+ * leaves the journal in place; callers must preserve the staging root on
1192
+ * refusal so the `finally` cannot destroy the backups a later attempt needs.
1193
+ */
1194
+ export function recoverInterruptedInstall(args) {
1195
+ const { defsDir, journalPath, lockfilePath } = args;
1196
+ const journal = readAddJournal(journalPath);
1197
+ if (journal === null) {
1198
+ reconcileOrphanRecoveryMarkers(args);
1199
+ return 'no-journal';
1200
+ }
1201
+ // An interrupted install in a DIFFERENT root: recovering "here" would act on
1202
+ // paths this invocation was never pointed at, and trusting the recorded
1203
+ // absolute path would let a crafted journal point mutations anywhere. Fail
1204
+ // closed — the operator must re-run with the same --defs/OWENLOOP_DEFS (v1)
1205
+ // or the same store root (v2).
1206
+ if (journal.version === 1) {
1207
+ if (resolve(journal.defsDir) !== resolve(defsDir)) {
1208
+ throw recoveryRefusal(journalPath, `journal records defs dir '${journal.defsDir}', but this add resolved '${resolve(defsDir)}' ` +
1209
+ `(re-run add with the same --defs/OWENLOOP_DEFS)`);
1210
+ }
1211
+ }
1212
+ else if (resolve(journal.root) !== resolve(defsDir)) {
1213
+ throw recoveryRefusal(journalPath, `journal records store root '${journal.root}', but this run resolved '${resolve(defsDir)}' ` +
1214
+ `(re-run against the same store root)`);
1215
+ }
1216
+ // Every mutation path is derived HERE from the current root + the validated
1217
+ // segments — never from the recorded absolute root.
1218
+ const destSegments = journal.version === 1 ? [journal.folder] : journal.destSegments;
1219
+ const stagingRoot = join(defsDir, STAGING_DIRNAME);
1220
+ const stagingDir = join(stagingRoot, journal.stagingId);
1221
+ const backupDir = `${stagingDir}-old`;
1222
+ const undoDir = `${stagingDir}-undo`;
1223
+ const dest = join(defsDir, ...destSegments);
1224
+ // v1-only extra paths.
1225
+ const parkedOldName = journal.version === 1 && journal.oldNamePath !== undefined
1226
+ ? `${undoDir}-oldname`
1227
+ : undefined;
1228
+ const oldNameOriginal = journal.version === 1 && journal.oldNamePath !== undefined
1229
+ ? join(defsDir, journal.oldNamePath)
1230
+ : undefined;
1231
+ // Symlink-guard the staging ROOT itself before deriving any mutation from it.
1232
+ // A hostile checkout that ships `.owenloop-staging` as a symlink would make
1233
+ // every rename/rm below act through it, moving/deleting dirs OUTSIDE the
1234
+ // root. `lstat` (never `stat`) so the link is seen as a link; a non-dir
1235
+ // squatting there is refused too; absent is fine (a fresh recovery mkdirs
1236
+ // it). This runs BEFORE any fs mutation, and recovery precedes the caller's
1237
+ // staging-root clear, so nothing else clears it first.
1238
+ const stagingRootSt = lstatSync(stagingRoot, { throwIfNoEntry: false });
1239
+ if (stagingRootSt?.isSymbolicLink()) {
1240
+ throw recoveryRefusal(journalPath, `staging root '${stagingRoot}' is a symlink`);
1241
+ }
1242
+ if (stagingRootSt && !stagingRootSt.isDirectory()) {
1243
+ throw recoveryRefusal(journalPath, `staging root '${stagingRoot}' is not a directory`);
1244
+ }
1245
+ // Belt-and-braces containment: re-assert that EVERY rename/rm source and
1246
+ // target resolves under the root — not just dest, but every staging-derived
1247
+ // path too (a crafted journal + a symlinked staging root must not drive a
1248
+ // mutation outside the tree). Validated segments already make lexical
1249
+ // traversal unrepresentable; this is the extra guard on the derived paths.
1250
+ for (const p of [stagingRoot, stagingDir, backupDir, undoDir, dest]) {
1251
+ assertUnderRoot(p, defsDir, journalPath);
1252
+ }
1253
+ if (parkedOldName !== undefined)
1254
+ assertUnderRoot(parkedOldName, defsDir, journalPath);
1255
+ if (oldNameOriginal !== undefined)
1256
+ assertUnderRoot(oldNameOriginal, defsDir, journalPath);
1257
+ const removeRecoveryMarkerAfterJournal = () => {
1258
+ if (journal.version === 2 && journal.recoveryMarkerId !== undefined) {
1259
+ if (args.recoveryMarkerDir === undefined) {
1260
+ throw recoveryRefusal(journalPath, 'external recovery marker directory was not supplied');
1261
+ }
1262
+ removeRecoveryMarker({ id: journal.recoveryMarkerId, markerDir: args.recoveryMarkerDir });
1263
+ }
1264
+ };
1265
+ const readMatchingV2Marker = () => {
1266
+ if (journal.version !== 2 || journal.recoveryMarkerId === undefined)
1267
+ return null;
1268
+ if (args.recoveryMarkerDir === undefined) {
1269
+ throw recoveryRefusal(journalPath, 'external recovery marker directory was not supplied');
1270
+ }
1271
+ let marker;
1272
+ try {
1273
+ marker = readRecoveryMarker(journal.recoveryMarkerId, args.recoveryMarkerDir);
1274
+ }
1275
+ catch (error) {
1276
+ throw recoveryRefusal(journalPath, `external recovery marker could not be read: ${error.message}`);
1277
+ }
1278
+ if (marker !== null) {
1279
+ verifyMarkerRootIdentityWhenPresent(marker, defsDir, journalPath, markerFilePath(args.recoveryMarkerDir, journal.recoveryMarkerId));
1280
+ }
1281
+ const markerMatches = marker !== null &&
1282
+ resolve(marker.root) === resolve(defsDir) &&
1283
+ marker.stagingId === journal.stagingId &&
1284
+ marker.hadDest === journal.hadDest &&
1285
+ marker.destSegments.length === journal.destSegments.length &&
1286
+ marker.destSegments.every((segment, i) => segment === journal.destSegments[i]);
1287
+ if (!markerMatches) {
1288
+ throw recoveryRefusal(journalPath, 'external recovery marker does not match the journal transaction');
1289
+ }
1290
+ return marker;
1291
+ };
1292
+ const requireRepairMarker = () => {
1293
+ if (journal.version !== 2 || journal.operation !== 'repair') {
1294
+ throw recoveryRefusal(journalPath, 'internal recovery error: repair marker requested for a non-repair journal');
1295
+ }
1296
+ const marker = readMatchingV2Marker();
1297
+ if (marker === null ||
1298
+ marker.operation !== 'repair' ||
1299
+ marker.hadDest !== true ||
1300
+ marker.replacementIdentity === undefined ||
1301
+ marker.priorIdentity === undefined) {
1302
+ throw recoveryRefusal(journalPath, 'repair recovery state lacks complete replacement/prior directory identity evidence');
1303
+ }
1304
+ return marker;
1305
+ };
1306
+ const requireIdentity = (path, expected, label) => {
1307
+ let actual;
1308
+ try {
1309
+ actual = recoveryDirectoryIdentity(path, label);
1310
+ }
1311
+ catch (error) {
1312
+ throw recoveryRefusal(journalPath, error.message);
1313
+ }
1314
+ if (actual.dev !== expected.dev || actual.ino !== expected.ino) {
1315
+ throw recoveryRefusal(journalPath, `${label} '${path}' does not belong to this transaction ` +
1316
+ `(expected dev ${expected.dev} inode ${expected.ino}, got dev ${actual.dev} inode ${actual.ino})`);
1317
+ }
1318
+ };
1319
+ const restoreIdentityMode = (path, expected, label) => {
1320
+ if (expected.mode === undefined)
1321
+ return;
1322
+ let actual;
1323
+ try {
1324
+ actual = recoveryDirectoryIdentity(path, label);
1325
+ if (actual.mode !== expected.mode)
1326
+ chmodSync(path, expected.mode);
1327
+ actual = recoveryDirectoryIdentity(path, label);
1328
+ }
1329
+ catch (error) {
1330
+ throw recoveryRefusal(journalPath, `could not restore exact ${label} mode ${expected.mode.toString(8)} at '${path}': ${error.message}`);
1331
+ }
1332
+ if (actual.mode !== expected.mode) {
1333
+ throw recoveryRefusal(journalPath, `could not restore exact ${label} mode ${expected.mode.toString(8)} at '${path}'`);
1334
+ }
1335
+ };
1336
+ // Roll forward: the metadata is durably new; discard the retained backup (+
1337
+ // parked old-name dir, v1) and clear the staging root, then drop the journal.
1338
+ // Symlink-guarded before each rm; both dirs live under the staging root, so
1339
+ // the final clear is the real cleanup — the explicit rms honor "refuse a
1340
+ // symlink" first.
1341
+ const rollForward = () => {
1342
+ if (probeRecoveryDir(backupDir, journalPath, 'backup dir', defsDir) === 'dir') {
1343
+ rmRecursiveForce(backupDir);
1344
+ }
1345
+ if (parkedOldName !== undefined) {
1346
+ if (probeRecoveryDir(parkedOldName, journalPath, 'parked old-name dir', defsDir) === 'dir') {
1347
+ rmRecursiveForce(parkedOldName);
1348
+ }
1349
+ }
1350
+ rmRecursiveForce(stagingRoot);
1351
+ removeAddJournal(journalPath);
1352
+ removeRecoveryMarkerAfterJournal();
1353
+ };
1354
+ const requireV2ReplacementActions = () => {
1355
+ if (args.v2Replacement === undefined) {
1356
+ throw recoveryRefusal(journalPath, 'a v2 content-addressed replacement requires canonical and hardened-mode recovery verification');
1357
+ }
1358
+ return args.v2Replacement;
1359
+ };
1360
+ const verifyV2Destination = () => {
1361
+ if (journal.version !== 2)
1362
+ return;
1363
+ const digest = journal.destSegments.at(-1);
1364
+ if (digest === undefined) {
1365
+ throw recoveryRefusal(journalPath, 'v2 destination has no digest segment');
1366
+ }
1367
+ try {
1368
+ requireV2ReplacementActions().verify(dest, digest);
1369
+ }
1370
+ catch (e) {
1371
+ throw recoveryRefusal(journalPath, `replacement at '${dest}' failed canonical or hardened-mode verification: ${e.message}`);
1372
+ }
1373
+ };
1374
+ const refusedRepairTopologies = {
1375
+ 'absent/absent/absent/absent': 'refuse',
1376
+ 'absent/absent/absent/dir': 'refuse',
1377
+ 'absent/absent/dir/absent': 'refuse',
1378
+ 'absent/absent/dir/dir': 'refuse',
1379
+ 'absent/dir/absent/absent': 'refuse',
1380
+ 'absent/dir/absent/dir': 'refuse',
1381
+ 'absent/dir/dir/absent': 'refuse',
1382
+ 'absent/dir/dir/dir': 'refuse',
1383
+ 'dir/absent/absent/absent': 'refuse',
1384
+ 'dir/absent/absent/dir': 'refuse',
1385
+ 'dir/absent/dir/absent': 'refuse',
1386
+ 'dir/absent/dir/dir': 'refuse',
1387
+ 'dir/dir/absent/absent': 'refuse',
1388
+ 'dir/dir/absent/dir': 'refuse',
1389
+ 'dir/dir/dir/absent': 'refuse',
1390
+ 'dir/dir/dir/dir': 'refuse',
1391
+ };
1392
+ const repairReplacementStateTable = {
1393
+ applying: {
1394
+ ...refusedRepairTopologies,
1395
+ // Before destination → backup: park the owned staging replacement, then
1396
+ // advance through the durable rollback phases without moving destination.
1397
+ 'dir/absent/absent/dir': 'begin-rollback',
1398
+ // After destination → backup but before staging → destination: park the
1399
+ // owned staging replacement, then restore the exact retained prior object.
1400
+ 'dir/dir/absent/absent': 'begin-rollback',
1401
+ // The swap completed before the applying → replacement-swapped rewrite.
1402
+ 'absent/dir/absent/dir': 'roll-forward',
1403
+ // Positively identified rollback states written by legacy releases.
1404
+ 'absent/dir/dir/absent': 'upgrade-legacy-rollback-parked',
1405
+ 'absent/absent/dir/dir': 'upgrade-legacy-rollback-restored',
1406
+ },
1407
+ 'replacement-swapped': {
1408
+ ...refusedRepairTopologies,
1409
+ 'absent/dir/absent/dir': 'roll-forward',
1410
+ 'absent/dir/dir/absent': 'upgrade-legacy-rollback-parked',
1411
+ 'absent/absent/dir/dir': 'upgrade-legacy-rollback-restored',
1412
+ },
1413
+ 'replacement-hardened': {
1414
+ ...refusedRepairTopologies,
1415
+ 'absent/dir/absent/dir': 'roll-forward',
1416
+ 'absent/dir/dir/absent': 'upgrade-legacy-rollback-parked',
1417
+ 'absent/absent/dir/dir': 'upgrade-legacy-rollback-restored',
1418
+ },
1419
+ 'replacement-verified': {
1420
+ ...refusedRepairTopologies,
1421
+ 'absent/dir/absent/dir': 'roll-forward',
1422
+ 'absent/dir/dir/absent': 'upgrade-legacy-rollback-parked',
1423
+ 'absent/absent/dir/dir': 'upgrade-legacy-rollback-restored',
1424
+ },
1425
+ };
1426
+ const repairTopology = (state) => `${state.staging}/${state.backup}/${state.undo}/${state.destination}`;
1427
+ const resumeV2Repair = () => {
1428
+ if (journal.version !== 2 || journal.operation !== 'repair') {
1429
+ throw recoveryRefusal(journalPath, 'internal recovery error: attempted v2 repair recovery for a non-repair journal');
1430
+ }
1431
+ const phase = journal.phase;
1432
+ if (phase !== 'applying' &&
1433
+ phase !== 'replacement-swapped' &&
1434
+ phase !== 'replacement-hardened' &&
1435
+ phase !== 'replacement-verified') {
1436
+ throw recoveryRefusal(journalPath, `internal recovery error: unexpected repair replacement phase '${phase}'`);
1437
+ }
1438
+ // Probe every transaction path before choosing an action. probeRecoveryDir
1439
+ // rejects symlinks and non-directories, so no state-table arm can mutate a
1440
+ // path whose type or containment has not already been validated.
1441
+ const state = {
1442
+ staging: probeRecoveryDir(stagingDir, journalPath, 'staging dir', defsDir),
1443
+ backup: probeRecoveryDir(backupDir, journalPath, 'backup dir', defsDir),
1444
+ undo: probeRecoveryDir(undoDir, journalPath, 'undo dir', defsDir),
1445
+ destination: probeRecoveryDir(dest, journalPath, 'destination', defsDir),
1446
+ };
1447
+ const topology = repairTopology(state);
1448
+ const action = repairReplacementStateTable[phase][topology];
1449
+ const refuseTopology = () => {
1450
+ throw recoveryRefusal(journalPath, `repair replacement phase '${phase}' contradicts filesystem state ` +
1451
+ `(staging=${state.staging}, backup=${state.backup}, undo=${state.undo}, ` +
1452
+ `destination=${state.destination})`);
1453
+ };
1454
+ if (action === 'refuse')
1455
+ refuseTopology();
1456
+ if (action === 'upgrade-legacy-rollback-restored') {
1457
+ // Compatibility for a repair rolled back by a release that pre-dates the
1458
+ // durable rollback phases: destination is already the prior object, backup
1459
+ // was consumed, and undo still holds the replacement. Never infer ownership
1460
+ // from this topology. A current marker must identify both directories. The
1461
+ // one marker-less legacy upgrade is accepted only when the hardened undo
1462
+ // object verifies canonically; recovery then records both exact identities
1463
+ // before writing a durable rollback phase or deleting anything.
1464
+ const marker = readMatchingV2Marker();
1465
+ let rollbackMarkerId = journal.recoveryMarkerId;
1466
+ let createdRollbackMarker;
1467
+ if (marker !== null) {
1468
+ if (marker.operation !== 'repair' ||
1469
+ marker.replacementIdentity === undefined ||
1470
+ marker.priorIdentity === undefined) {
1471
+ throw recoveryRefusal(journalPath, 'legacy repair rollback marker lacks complete replacement/prior identity evidence');
1472
+ }
1473
+ requireIdentity(undoDir, marker.replacementIdentity, 'parked replacement');
1474
+ requireIdentity(dest, marker.priorIdentity, 'restored prior object');
1475
+ }
1476
+ else {
1477
+ if (args.recoveryMarkerDir === undefined) {
1478
+ throw recoveryRefusal(journalPath, 'legacy completed repair rollback requires the external recovery marker directory');
1479
+ }
1480
+ const actions = requireV2ReplacementActions();
1481
+ const digest = journal.destSegments.at(-1);
1482
+ if (digest === undefined) {
1483
+ throw recoveryRefusal(journalPath, 'v2 destination has no digest segment');
1484
+ }
1485
+ try {
1486
+ actions.verify(undoDir, digest);
1487
+ }
1488
+ catch (error) {
1489
+ throw recoveryRefusal(journalPath, `could not prove legacy rollback debris at '${undoDir}' is this transaction's replacement: ` +
1490
+ `${error.message}`);
1491
+ }
1492
+ const rollbackMarker = createRecoveryMarker({
1493
+ root: defsDir,
1494
+ destSegments: journal.destSegments,
1495
+ stagingId: journal.stagingId,
1496
+ markerDir: args.recoveryMarkerDir,
1497
+ operation: 'repair',
1498
+ replacementDir: undoDir,
1499
+ });
1500
+ try {
1501
+ recordRecoveryMarkerPriorIdentity(rollbackMarker, dest);
1502
+ }
1503
+ catch (error) {
1504
+ removeRecoveryMarker(rollbackMarker);
1505
+ throw recoveryRefusal(journalPath, `could not record legacy repair rollback identity evidence: ${error.message}`);
1506
+ }
1507
+ createdRollbackMarker = rollbackMarker;
1508
+ rollbackMarkerId = rollbackMarker.id;
1509
+ }
1510
+ if (rollbackMarkerId === undefined || args.recoveryMarkerDir === undefined) {
1511
+ throw recoveryRefusal(journalPath, 'legacy repair rollback could not establish durable identity evidence');
1512
+ }
1513
+ try {
1514
+ writeAddJournal(journalPath, {
1515
+ ...journal,
1516
+ phase: 'rollback-prior-restored',
1517
+ operation: 'repair',
1518
+ recoveryMarkerId: rollbackMarkerId,
1519
+ });
1520
+ }
1521
+ catch (error) {
1522
+ if (createdRollbackMarker !== undefined)
1523
+ removeRecoveryMarker(createdRollbackMarker);
1524
+ throw error;
1525
+ }
1526
+ rmRecursiveForce(undoDir);
1527
+ writeAddJournal(journalPath, {
1528
+ ...journal,
1529
+ phase: 'rollback-complete',
1530
+ operation: 'repair',
1531
+ recoveryMarkerId: rollbackMarkerId,
1532
+ });
1533
+ if (readdirSync(stagingRoot).length === 0)
1534
+ rmdirSync(stagingRoot);
1535
+ removeAddJournal(journalPath);
1536
+ removeRecoveryMarker({ id: rollbackMarkerId, markerDir: args.recoveryMarkerDir });
1537
+ return 'rolled-back';
1538
+ }
1539
+ const marker = requireRepairMarker();
1540
+ if (action === 'roll-forward') {
1541
+ requireIdentity(dest, marker.replacementIdentity, 'replacement destination');
1542
+ requireIdentity(backupDir, marker.priorIdentity, 'retained prior object');
1543
+ const actions = requireV2ReplacementActions();
1544
+ const digest = journal.destSegments.at(-1);
1545
+ if (digest === undefined) {
1546
+ throw recoveryRefusal(journalPath, 'v2 destination has no digest segment');
1547
+ }
1548
+ if (phase === 'applying' || phase === 'replacement-swapped') {
1549
+ try {
1550
+ actions.harden(dest);
1551
+ }
1552
+ catch (e) {
1553
+ throw recoveryRefusal(journalPath, `could not finish replacement hardening: ${e.message}`);
1554
+ }
1555
+ writeAddJournal(journalPath, { ...journal, phase: 'replacement-hardened', operation: 'repair' });
1556
+ }
1557
+ // Re-run verification even when the durable phase already says verified.
1558
+ // The journal proves ordering, not that the object was not modified after a
1559
+ // crash. No backup is discarded until both invariants pass again now.
1560
+ try {
1561
+ actions.verify(dest, digest);
1562
+ }
1563
+ catch (e) {
1564
+ throw recoveryRefusal(journalPath, `replacement at '${dest}' failed canonical or hardened-mode verification: ${e.message}`);
1565
+ }
1566
+ writeAddJournal(journalPath, { ...journal, phase: 'replacement-verified', operation: 'repair' });
1567
+ writeAddJournal(journalPath, { ...journal, phase: 'finalizing', operation: 'repair' });
1568
+ rollForward();
1569
+ return 'rolled-forward';
1570
+ }
1571
+ if (action === 'begin-rollback') {
1572
+ if (state.staging !== 'dir' || state.undo !== 'absent')
1573
+ refuseTopology();
1574
+ requireIdentity(stagingDir, marker.replacementIdentity, 'staged replacement');
1575
+ if (state.backup === 'dir') {
1576
+ requireIdentity(backupDir, marker.priorIdentity, 'retained prior object');
1577
+ }
1578
+ else {
1579
+ requireIdentity(dest, marker.priorIdentity, 'unchanged prior destination');
1580
+ }
1581
+ }
1582
+ else if (action === 'upgrade-legacy-rollback-parked') {
1583
+ requireIdentity(undoDir, marker.replacementIdentity, 'parked replacement');
1584
+ requireIdentity(backupDir, marker.priorIdentity, 'retained prior object');
1585
+ }
1586
+ else {
1587
+ return refuseTopology();
1588
+ }
1589
+ // A replacement phase may enter rollback only after the complete state table
1590
+ // and marker identities prove the exact safe transition. Persist the exact
1591
+ // replacement-root mode before the first rollback rename so recovery never
1592
+ // infers that mode from a path left owner-writable by a killed rename.
1593
+ const rollbackReplacementMode = marker.replacementIdentity.mode ?? (() => {
1594
+ const replacementPath = action === 'begin-rollback' ? stagingDir : undoDir;
1595
+ try {
1596
+ return recoveryDirectoryIdentity(replacementPath, 'rollback replacement').mode;
1597
+ }
1598
+ catch (error) {
1599
+ throw recoveryRefusal(journalPath, error.message);
1600
+ }
1601
+ })();
1602
+ const rollbackJournal = {
1603
+ ...journal,
1604
+ phase: 'rollback-started',
1605
+ operation: 'repair',
1606
+ rollbackReplacementMode,
1607
+ };
1608
+ writeAddJournal(journalPath, rollbackJournal);
1609
+ return resumeDurableV2RepairRollback(rollbackJournal, 'rollback-started');
1610
+ };
1611
+ function resumeDurableV2RepairRollback(repairJournal, initialPhase = repairJournal.phase) {
1612
+ const marker = requireRepairMarker();
1613
+ const replacementIdentity = marker.replacementIdentity;
1614
+ const priorIdentity = marker.priorIdentity;
1615
+ const rollbackReplacementIdentity = {
1616
+ ...replacementIdentity,
1617
+ ...(repairJournal.rollbackReplacementMode === undefined
1618
+ ? {}
1619
+ : { mode: repairJournal.rollbackReplacementMode }),
1620
+ };
1621
+ let phase = initialPhase;
1622
+ const states = () => ({
1623
+ staging: probeRecoveryDir(stagingDir, journalPath, 'staging dir', defsDir),
1624
+ backup: probeRecoveryDir(backupDir, journalPath, 'backup dir', defsDir),
1625
+ undo: probeRecoveryDir(undoDir, journalPath, 'undo dir', defsDir),
1626
+ destination: probeRecoveryDir(dest, journalPath, 'destination', defsDir),
1627
+ });
1628
+ const refuseCombination = (state) => {
1629
+ throw recoveryRefusal(journalPath, `repair rollback phase '${phase}' contradicts filesystem state ` +
1630
+ `(staging=${state.staging}, backup=${state.backup}, undo=${state.undo}, destination=${state.destination})`);
1631
+ };
1632
+ const writePhase = (next) => {
1633
+ writeAddJournal(journalPath, { ...repairJournal, phase: next, operation: 'repair' });
1634
+ phase = next;
1635
+ };
1636
+ for (;;) {
1637
+ const state = states();
1638
+ if (phase === 'rollback-started') {
1639
+ if (state.staging === 'dir' &&
1640
+ state.destination === 'dir' &&
1641
+ state.backup === 'absent' &&
1642
+ state.undo === 'absent') {
1643
+ requireIdentity(stagingDir, replacementIdentity, 'staged replacement');
1644
+ requireIdentity(dest, priorIdentity, 'unchanged prior destination');
1645
+ restoreIdentityMode(dest, priorIdentity, 'unchanged prior destination');
1646
+ renameDirRestoringWrite(stagingDir, undoDir, rollbackReplacementIdentity.mode);
1647
+ writePhase('rollback-replacement-parked');
1648
+ continue;
1649
+ }
1650
+ if (state.staging === 'dir' &&
1651
+ state.destination === 'absent' &&
1652
+ state.backup === 'dir' &&
1653
+ state.undo === 'absent') {
1654
+ requireIdentity(stagingDir, replacementIdentity, 'staged replacement');
1655
+ requireIdentity(backupDir, priorIdentity, 'retained prior object');
1656
+ renameDirRestoringWrite(stagingDir, undoDir, rollbackReplacementIdentity.mode);
1657
+ writePhase('rollback-replacement-parked');
1658
+ continue;
1659
+ }
1660
+ if (state.staging === 'absent' &&
1661
+ state.destination === 'dir' &&
1662
+ state.backup === 'dir' &&
1663
+ state.undo === 'absent') {
1664
+ requireIdentity(dest, replacementIdentity, 'replacement destination');
1665
+ requireIdentity(backupDir, priorIdentity, 'retained prior object');
1666
+ renameDirRestoringWrite(dest, undoDir, rollbackReplacementIdentity.mode);
1667
+ writePhase('rollback-replacement-parked');
1668
+ continue;
1669
+ }
1670
+ if (state.staging === 'absent' &&
1671
+ state.destination === 'absent' &&
1672
+ state.backup === 'dir' &&
1673
+ state.undo === 'dir') {
1674
+ requireIdentity(undoDir, replacementIdentity, 'parked replacement');
1675
+ requireIdentity(backupDir, priorIdentity, 'retained prior object');
1676
+ restoreIdentityMode(undoDir, rollbackReplacementIdentity, 'parked replacement');
1677
+ writePhase('rollback-replacement-parked');
1678
+ continue;
1679
+ }
1680
+ if (state.staging === 'absent' &&
1681
+ state.destination === 'dir' &&
1682
+ state.backup === 'absent' &&
1683
+ state.undo === 'dir') {
1684
+ requireIdentity(undoDir, replacementIdentity, 'parked replacement');
1685
+ requireIdentity(dest, priorIdentity, 'unchanged prior destination');
1686
+ restoreIdentityMode(undoDir, rollbackReplacementIdentity, 'parked replacement');
1687
+ restoreIdentityMode(dest, priorIdentity, 'unchanged prior destination');
1688
+ writePhase('rollback-replacement-parked');
1689
+ continue;
1690
+ }
1691
+ refuseCombination(state);
1692
+ }
1693
+ if (state.staging !== 'absent')
1694
+ refuseCombination(state);
1695
+ if (phase === 'rollback-replacement-parked') {
1696
+ if (state.destination === 'absent' && state.backup === 'dir' && state.undo === 'dir') {
1697
+ requireIdentity(undoDir, replacementIdentity, 'parked replacement');
1698
+ requireIdentity(backupDir, priorIdentity, 'retained prior object');
1699
+ restoreIdentityMode(undoDir, rollbackReplacementIdentity, 'parked replacement');
1700
+ renameDirRestoringWrite(backupDir, dest, priorIdentity.mode);
1701
+ writePhase('rollback-prior-restored');
1702
+ continue;
1703
+ }
1704
+ if (state.destination === 'dir' && state.backup === 'absent' && state.undo === 'dir') {
1705
+ requireIdentity(dest, priorIdentity, 'restored prior object');
1706
+ requireIdentity(undoDir, replacementIdentity, 'parked replacement');
1707
+ restoreIdentityMode(dest, priorIdentity, 'restored prior object');
1708
+ restoreIdentityMode(undoDir, rollbackReplacementIdentity, 'parked replacement');
1709
+ writePhase('rollback-prior-restored');
1710
+ continue;
1711
+ }
1712
+ refuseCombination(state);
1713
+ }
1714
+ if (phase === 'rollback-prior-restored') {
1715
+ if (state.destination !== 'dir' || state.backup !== 'absent')
1716
+ refuseCombination(state);
1717
+ requireIdentity(dest, priorIdentity, 'restored prior object');
1718
+ restoreIdentityMode(dest, priorIdentity, 'restored prior object');
1719
+ if (state.undo === 'dir') {
1720
+ requireIdentity(undoDir, replacementIdentity, 'parked replacement');
1721
+ restoreIdentityMode(undoDir, rollbackReplacementIdentity, 'parked replacement');
1722
+ rmRecursiveForce(undoDir);
1723
+ }
1724
+ writePhase('rollback-complete');
1725
+ continue;
1726
+ }
1727
+ if (phase === 'rollback-complete') {
1728
+ if (state.destination !== 'dir' ||
1729
+ state.backup !== 'absent' ||
1730
+ state.undo !== 'absent') {
1731
+ refuseCombination(state);
1732
+ }
1733
+ requireIdentity(dest, priorIdentity, 'restored prior object');
1734
+ restoreIdentityMode(dest, priorIdentity, 'restored prior object');
1735
+ const currentStagingRoot = probeRecoveryDir(stagingRoot, journalPath, 'staging root', defsDir);
1736
+ if (currentStagingRoot === 'dir' && readdirSync(stagingRoot).length === 0)
1737
+ rmdirSync(stagingRoot);
1738
+ removeAddJournal(journalPath);
1739
+ removeRecoveryMarkerAfterJournal();
1740
+ return 'rolled-back';
1741
+ }
1742
+ throw recoveryRefusal(journalPath, `internal recovery error: unexpected rollback phase '${phase}'`);
1743
+ }
1744
+ }
1745
+ if (journal.version === 2 && journal.phase.startsWith('rollback-')) {
1746
+ if (journal.operation !== 'repair') {
1747
+ throw recoveryRefusal(journalPath, 'internal recovery error: repair rollback phase has a non-repair operation');
1748
+ }
1749
+ return resumeDurableV2RepairRollback(journal);
1750
+ }
1751
+ if (journal.phase === 'finalizing') {
1752
+ // A v2 finalizing journal may be left after the index commit but before the
1753
+ // backup was deleted. Re-verify the exact destination, including immutable
1754
+ // store modes, before accepting it and deleting the retained prior object.
1755
+ if (journal.version === 2 && journal.operation === 'repair') {
1756
+ const state = {
1757
+ staging: probeRecoveryDir(stagingDir, journalPath, 'staging dir', defsDir),
1758
+ backup: probeRecoveryDir(backupDir, journalPath, 'backup dir', defsDir),
1759
+ undo: probeRecoveryDir(undoDir, journalPath, 'undo dir', defsDir),
1760
+ destination: probeRecoveryDir(dest, journalPath, 'destination', defsDir),
1761
+ };
1762
+ if (state.staging !== 'absent' ||
1763
+ state.undo !== 'absent' ||
1764
+ state.destination !== 'dir') {
1765
+ throw recoveryRefusal(journalPath, `finalizing repair contradicts filesystem state ` +
1766
+ `(staging=${state.staging}, backup=${state.backup}, undo=${state.undo}, ` +
1767
+ `destination=${state.destination})`);
1768
+ }
1769
+ const marker = requireRepairMarker();
1770
+ requireIdentity(dest, marker.replacementIdentity, 'replacement destination');
1771
+ if (state.backup === 'dir') {
1772
+ requireIdentity(backupDir, marker.priorIdentity, 'retained prior object');
1773
+ }
1774
+ }
1775
+ verifyV2Destination();
1776
+ rollForward();
1777
+ return 'rolled-forward';
1778
+ }
1779
+ if (journal.version === 2 && journal.phase !== 'applying') {
1780
+ return resumeV2Repair();
1781
+ }
1782
+ // phase === 'applying': the metadata write may or may not have landed. The
1783
+ // commit-point test is version-specific: v1 matches the ledger on
1784
+ // source+sha+path; v2 hashes the CURRENT metadata bytes against the
1785
+ // journal's metadataHash. A corrupt metadata file aborts exactly as the
1786
+ // route's own read would (fail-closed).
1787
+ let commitPointReached = false;
1788
+ let v1Lookup;
1789
+ if (journal.version === 2) {
1790
+ let metaBytes;
1791
+ try {
1792
+ metaBytes = readRegularFileNoFollow(lockfilePath, 'install metadata');
1793
+ }
1794
+ catch (e) {
1795
+ throw recoveryRefusal(journalPath, e.message);
1796
+ }
1797
+ commitPointReached = sha256Hex(metaBytes ?? new Uint8Array()) === journal.metadataHash;
1798
+ }
1799
+ else {
1800
+ if (args.readLedger === undefined) {
1801
+ throw recoveryRefusal(journalPath, 'a v1 (GitHub-route) journal requires the GitHub recovery entry point (owenloop add --recover)');
1802
+ }
1803
+ v1Lookup = args.readLedger();
1804
+ const installed = v1Lookup(journal.source);
1805
+ commitPointReached =
1806
+ installed !== undefined && installed.sha === journal.sha && installed.path === journal.folder;
1807
+ }
1808
+ const applyingRepair = journal.version === 2 &&
1809
+ journal.hadDest &&
1810
+ journal.operation === 'repair';
1811
+ if (applyingRepair)
1812
+ return resumeV2Repair();
1813
+ if (commitPointReached) {
1814
+ // The metadata records this exact install — but the test ALONE does NOT
1815
+ // prove the commit swap landed. Branch on ACTUAL disk state:
1816
+ // - dest PRESENT ⇒ the swap completed (a crash in the metadata-write→
1817
+ // phase-rewrite window, or a same-content re-install already past the
1818
+ // swap): dest holds that content, so (tree ⇔ metadata) is consistent ⇒
1819
+ // roll forward (discard the now-stale backup).
1820
+ // - dest ABSENT ⇒ we are inside commitInstall's backup→swap window of a
1821
+ // SAME-content re-install (dest was renamed to backupDir, and the
1822
+ // staging→dest swap never ran). backupDir now holds the ONLY copy of
1823
+ // the content. Rolling forward would `rmSync` it — silent data loss,
1824
+ // leaving the metadata claiming an install that is gone from disk. Fall
1825
+ // THROUGH to the roll-back table, which restores backupDir → dest; the
1826
+ // metadata already records this content, so the restored state is
1827
+ // consistent. The two cases are distinguishable by disk, so branch on
1828
+ // it rather than trusting the commit-point test alone.
1829
+ if (probeRecoveryDir(dest, journalPath, 'destination', defsDir) === 'dir') {
1830
+ rollForward();
1831
+ return 'rolled-forward';
1832
+ }
1833
+ }
1834
+ // ROLL BACK — restore the pre-commit directory state. Guarded idempotent
1835
+ // renames mirroring rollbackInstallCommit's order; a symlinked source is
1836
+ // refused fail-closed at each probe.
1837
+ mkdirSync(stagingRoot, { recursive: true }); // ensure undo/backup renames have a home
1838
+ const stagingState = probeRecoveryDir(stagingDir, journalPath, 'staging dir', defsDir);
1839
+ const backupState = probeRecoveryDir(backupDir, journalPath, 'backup dir', defsDir);
1840
+ // Every rename here moves a directory that may hold a hardened CAS object
1841
+ // (the backup of a previous install, or the swapped-in new content) — they
1842
+ // go through renameDirRestoringWrite so a 0o555 dir can still be moved.
1843
+ if (stagingState === 'dir') {
1844
+ // (a) Swap 4b (staging → dest) never happened.
1845
+ if (backupState === 'dir') {
1846
+ // Crash between 4a (dest → backup) and 4b: dest is necessarily absent.
1847
+ // Restore the backup. Fail closed if dest unexpectedly exists too.
1848
+ if (probeRecoveryDir(dest, journalPath, 'destination', defsDir) === 'dir') {
1849
+ throw recoveryRefusal(journalPath, `both the backup dir and destination '${dest}' exist`);
1850
+ }
1851
+ renameDirRestoringWrite(backupDir, dest);
1852
+ }
1853
+ // else backup absent: dest still holds the original (upgrade, pre-backup) or
1854
+ // is absent (fresh install, pre-swap) — already consistent, nothing to move.
1855
+ }
1856
+ else if (backupState === 'dir') {
1857
+ // (b) Staging gone, backup present — an upgrade crashed AFTER the swap.
1858
+ if (probeRecoveryDir(dest, journalPath, 'destination', defsDir) === 'dir') {
1859
+ // Park the new content aside, then restore the backup over dest.
1860
+ if (probeRecoveryDir(undoDir, journalPath, 'undo dir', defsDir) === 'dir') {
1861
+ throw recoveryRefusal(journalPath, `undo dir '${undoDir}' already exists`);
1862
+ }
1863
+ renameDirRestoringWrite(dest, undoDir);
1864
+ renameDirRestoringWrite(backupDir, dest);
1865
+ }
1866
+ else {
1867
+ // dest absent: a prior rollback/recovery died between its two renames (the
1868
+ // new content is already parked under undoDir) — just restore the backup.
1869
+ renameDirRestoringWrite(backupDir, dest);
1870
+ }
1871
+ }
1872
+ else {
1873
+ // (c) Staging gone, backup gone.
1874
+ if (!journal.hadDest && journal.version === 1) {
1875
+ // Fresh install: the swap may have put new content at dest. Discarding it
1876
+ // (rename → undoDir, then rm with the staging root at step (e)) is the ONLY
1877
+ // destructive arm that acts on the word of the journal alone — staging and
1878
+ // backup are both absent by definition of case (c), so the journal is the
1879
+ // only thing asserting this dir is a crash orphan. But the journal lives in
1880
+ // repository-controlled content (the journal is committable), so a hostile
1881
+ // checkout can forge a schema-VALID `applying`/`hadDest:false` journal
1882
+ // naming an existing UNRELATED workflow dir and drive its deletion. Fail
1883
+ // closed: only delete when the LEDGER corroborates that this dest is a
1884
+ // fresh hashed dir left by an interrupted OLD-NAME MIGRATION — i.e. the
1885
+ // ledger still records `journal.source` at the migration's old-name path.
1886
+ // That is exactly the state of the corroborated old-name-migration crash;
1887
+ // the parked old-name dir is NOT required as evidence (a crash in the
1888
+ // swap→park window legitimately has no parked dir yet). Anything else — no
1889
+ // ledger entry, or an entry at some other path (including `journal.folder`
1890
+ // itself, which contradicts `hadDest:false`) — is uncorroborated: refuse,
1891
+ // mutate nothing, leave the journal AND dest in place as evidence.
1892
+ //
1893
+ // Deliberate, documented regression: the genuine fresh-install crash between
1894
+ // the swap and the metadata write (dest present, no ledger, no staging, no
1895
+ // backup) is on-disk INDISTINGUISHABLE from the forgery — every
1896
+ // distinguishing artifact is itself repo-committable and therefore forgeable
1897
+ // — so it now fails closed here instead of auto-discarding. The error names
1898
+ // the manual remedy.
1899
+ if (probeRecoveryDir(dest, journalPath, 'destination', defsDir) === 'dir') {
1900
+ const installedAtSource = v1Lookup?.(journal.source);
1901
+ const migrationCorroborated = journal.oldNamePath !== undefined &&
1902
+ installedAtSource !== undefined &&
1903
+ installedAtSource.path === journal.oldNamePath;
1904
+ if (!migrationCorroborated) {
1905
+ throw recoveryRefusal(journalPath, `journal claims an interrupted fresh install of '${journal.folder}', but nothing ` +
1906
+ `corroborates it (no ledger entry for this source at the journal's old-name path, ` +
1907
+ `no staging dir, no backup) while '${dest}' exists — refusing to discard that ` +
1908
+ `directory. If you did not run an interrupted add in this checkout, remove the ` +
1909
+ `journal; if a fresh install really was interrupted, remove '${dest}' as well`);
1910
+ }
1911
+ if (probeRecoveryDir(undoDir, journalPath, 'undo dir', defsDir) === 'dir') {
1912
+ throw recoveryRefusal(journalPath, `undo dir '${undoDir}' already exists`);
1913
+ }
1914
+ renameDirRestoringWrite(dest, undoDir);
1915
+ }
1916
+ }
1917
+ // v2 case (c): staging gone, backup gone. A fresh v2 install (hadDest
1918
+ // false) may have completed the swap immediately before the process died.
1919
+ // The external marker is the only corroboration trusted for discarding the
1920
+ // orphaned destination; a journal without an exact marker match remains a
1921
+ // forged-journal refusal and is never allowed to delete an unrelated dir.
1922
+ if (!journal.hadDest && journal.version === 2) {
1923
+ if (probeRecoveryDir(dest, journalPath, 'destination', defsDir) === 'dir') {
1924
+ let marker = null;
1925
+ if (journal.recoveryMarkerId !== undefined) {
1926
+ if (args.recoveryMarkerDir === undefined) {
1927
+ throw recoveryRefusal(journalPath, 'external recovery marker directory was not supplied');
1928
+ }
1929
+ try {
1930
+ marker = readRecoveryMarker(journal.recoveryMarkerId, args.recoveryMarkerDir);
1931
+ }
1932
+ catch (e) {
1933
+ throw recoveryRefusal(journalPath, `external recovery marker could not be read: ${e.message}`);
1934
+ }
1935
+ if (marker !== null) {
1936
+ verifyMarkerRootIdentityWhenPresent(marker, defsDir, journalPath, markerFilePath(args.recoveryMarkerDir, journal.recoveryMarkerId));
1937
+ }
1938
+ }
1939
+ const markerMatches = marker !== null &&
1940
+ resolve(marker.root) === resolve(defsDir) &&
1941
+ marker.stagingId === journal.stagingId &&
1942
+ marker.hadDest === false &&
1943
+ marker.destSegments.length === journal.destSegments.length &&
1944
+ marker.destSegments.every((segment, i) => segment === journal.destSegments[i]);
1945
+ if (!markerMatches) {
1946
+ throw recoveryRefusal(journalPath, `journal claims an interrupted fresh install of '${journal.destSegments.join('/')}', but no ` +
1947
+ `matching external recovery marker corroborates it (no staging dir, no backup, and the ` +
1948
+ `metadata does not match this journal) while '${dest}' exists — refusing to discard that ` +
1949
+ `directory. If you did not run an interrupted install in this store, remove the journal; if ` +
1950
+ `an install really was interrupted, remove '${dest}' as well`);
1951
+ }
1952
+ if (probeRecoveryDir(undoDir, journalPath, 'undo dir', defsDir) === 'dir') {
1953
+ throw recoveryRefusal(journalPath, `undo dir '${undoDir}' already exists`);
1954
+ }
1955
+ renameDirRestoringWrite(dest, undoDir);
1956
+ }
1957
+ }
1958
+ // v1/v2 hadDest === true: the backup was already restored (a completed
1959
+ // in-process rollback whose journal-remove failed, or a prior recovery
1960
+ // attempt) — dirs are consistent; touch nothing.
1961
+ }
1962
+ // (d) Restore a parked old-name dir to where the (unchanged) ledger expects
1963
+ // it (v1 only — v2 journals never migrate an old name).
1964
+ if (parkedOldName !== undefined && oldNameOriginal !== undefined) {
1965
+ if (probeRecoveryDir(parkedOldName, journalPath, 'parked old-name dir', defsDir) === 'dir') {
1966
+ if (probeRecoveryDir(oldNameOriginal, journalPath, 'old-name original', defsDir) === 'dir') {
1967
+ // Both present is contradictory — unreachable under the single-writer
1968
+ // lock, so don't guess which to keep.
1969
+ throw recoveryRefusal(journalPath, `both the parked old-name dir and its original '${oldNameOriginal}' exist`);
1970
+ }
1971
+ renameDirRestoringWrite(parkedOldName, oldNameOriginal);
1972
+ }
1973
+ // parked absent ⇒ already restored (idempotent re-run) — skip.
1974
+ }
1975
+ // (e) The undo/backup leftovers are debris now; clear the staging root and
1976
+ // remove the journal LAST so a crash before this leaves everything replayable.
1977
+ rmRecursiveForce(stagingRoot);
1978
+ removeAddJournal(journalPath);
1979
+ removeRecoveryMarkerAfterJournal();
1980
+ return 'rolled-back';
1981
+ }