@andorra-labs/code 0.1.8 → 0.1.10

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 (187) hide show
  1. package/THIRD_PARTY_NOTICES.md +2 -1
  2. package/dist/src/account-presentation.d.ts +11 -0
  3. package/dist/src/account-presentation.js +29 -2
  4. package/dist/src/agent-execution.js +57 -4
  5. package/dist/src/agent-mcp.d.ts +12 -0
  6. package/dist/src/agent-mcp.js +81 -2
  7. package/dist/src/app-server/protocol.d.ts +120 -1
  8. package/dist/src/app-server/protocol.js +8 -1
  9. package/dist/src/app-server/reasoning.d.ts +0 -8
  10. package/dist/src/app-server/reasoning.js +15 -28
  11. package/dist/src/app-server.d.ts +32 -0
  12. package/dist/src/app-server.js +214 -21
  13. package/dist/src/auth/AuthManager.d.ts +15 -0
  14. package/dist/src/auth/AuthManager.js +66 -7
  15. package/dist/src/auth/index.d.ts +1 -1
  16. package/dist/src/auth/index.js +1 -1
  17. package/dist/src/auth/store.d.ts +17 -1
  18. package/dist/src/auth/store.js +25 -2
  19. package/dist/src/browser-runner.js +1 -2
  20. package/dist/src/browser-server.js +10 -2
  21. package/dist/src/browser-session.js +6 -2
  22. package/dist/src/browser-stealth.d.ts +29 -0
  23. package/dist/src/browser-stealth.js +166 -0
  24. package/dist/src/browser-ui/app.js +123 -28
  25. package/dist/src/browser-ui/icons/chevron-right.svg +8 -0
  26. package/dist/src/browser-ui/index.html +8 -8
  27. package/dist/src/browser-ui/style.css +199 -171
  28. package/dist/src/browser-ui/tokens.css +198 -0
  29. package/dist/src/browser-view.d.ts +57 -9
  30. package/dist/src/browser-view.js +187 -36
  31. package/dist/src/cli.js +31 -9
  32. package/dist/src/coding-tools.js +9 -5
  33. package/dist/src/command-screens.js +4 -4
  34. package/dist/src/commands.d.ts +1 -1
  35. package/dist/src/commands.js +3 -2
  36. package/dist/src/completion-gates.d.ts +35 -0
  37. package/dist/src/completion-gates.js +25 -0
  38. package/dist/src/completion.d.ts +7 -1
  39. package/dist/src/completion.js +37 -4
  40. package/dist/src/config.d.ts +1 -1
  41. package/dist/src/config.js +2 -2
  42. package/dist/src/context-budget.d.ts +11 -0
  43. package/dist/src/context-budget.js +13 -0
  44. package/dist/src/decision/DecisionEngine.d.ts +5 -1
  45. package/dist/src/decision/DecisionManager.d.ts +1 -0
  46. package/dist/src/decision/DecisionManager.js +14 -3
  47. package/dist/src/decision/FactContinuations.d.ts +6 -0
  48. package/dist/src/decision/FactContinuations.js +9 -1
  49. package/dist/src/decision/FactServiceGate.js +1 -1
  50. package/dist/src/decision/checks.js +1 -1
  51. package/dist/src/decision/hostedSkills.d.ts +37 -0
  52. package/dist/src/decision/hostedSkills.js +64 -0
  53. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +10 -2
  54. package/dist/src/decision/providers/AndorraDecisionProvider.js +121 -10
  55. package/dist/src/default-graph.d.ts +11 -0
  56. package/dist/src/default-graph.js +20 -0
  57. package/dist/src/duration.d.ts +13 -2
  58. package/dist/src/duration.js +27 -3
  59. package/dist/src/file-diff.d.ts +105 -0
  60. package/dist/src/file-diff.js +244 -0
  61. package/dist/src/graph-manager-chat.d.ts +302 -0
  62. package/dist/src/graph-manager-chat.js +940 -0
  63. package/dist/src/graph-runner.js +6 -0
  64. package/dist/src/graph-server.d.ts +9 -0
  65. package/dist/src/graph-server.js +171 -20
  66. package/dist/src/graph-studio-features.js +2 -2
  67. package/dist/src/graph-sync.js +5 -2
  68. package/dist/src/graph-ui/app.js +369 -183
  69. package/dist/src/graph-ui/controls.css +55 -32
  70. package/dist/src/graph-ui/controls.js +85 -9
  71. package/dist/src/graph-ui/edge-router.js +114 -13
  72. package/dist/src/graph-ui/embed.js +32 -17
  73. package/dist/src/graph-ui/icons.js +1 -0
  74. package/dist/src/graph-ui/index.html +4 -4
  75. package/dist/src/graph-ui/library.css +4 -10
  76. package/dist/src/graph-ui/manager-markdown.js +155 -0
  77. package/dist/src/graph-ui/manager-state.js +191 -0
  78. package/dist/src/graph-ui/manager.css +161 -0
  79. package/dist/src/graph-ui/manager.js +700 -0
  80. package/dist/src/graph-ui/skill-picker.js +6 -6
  81. package/dist/src/graph-ui/studio-canvas.js +17 -15
  82. package/dist/src/graph-ui/studio.css +24 -23
  83. package/dist/src/graph-ui/studio.js +69 -48
  84. package/dist/src/graph-ui/style.css +128 -93
  85. package/dist/src/graph-ui/theme.js +2 -2
  86. package/dist/src/graph-ui/tokens.css +217 -151
  87. package/dist/src/graphs.d.ts +76 -2
  88. package/dist/src/graphs.js +172 -9
  89. package/dist/src/hardened-runtime.js +8 -2
  90. package/dist/src/mcp.d.ts +75 -0
  91. package/dist/src/mcp.js +240 -8
  92. package/dist/src/membership-errors.d.ts +14 -0
  93. package/dist/src/membership-errors.js +24 -1
  94. package/dist/src/membership.d.ts +20 -0
  95. package/dist/src/membership.js +45 -16
  96. package/dist/src/palette.d.ts +25 -8
  97. package/dist/src/palette.js +26 -8
  98. package/dist/src/provider-engine.d.ts +4 -4
  99. package/dist/src/provider-engine.js +39 -22
  100. package/dist/src/provider-keys.d.ts +5 -1
  101. package/dist/src/provider-keys.js +7 -3
  102. package/dist/src/provider-settings.d.ts +4 -1
  103. package/dist/src/provider-settings.js +46 -5
  104. package/dist/src/providers.d.ts +24 -0
  105. package/dist/src/providers.js +47 -2
  106. package/dist/src/qa/guidance.d.ts +26 -0
  107. package/dist/src/qa/guidance.js +46 -0
  108. package/dist/src/qa/index.d.ts +1 -8
  109. package/dist/src/qa/index.js +1 -16
  110. package/dist/src/qa/profile/QaProfile.d.ts +5 -1
  111. package/dist/src/qa/profile/QaProfile.js +6 -2
  112. package/dist/src/qa/runtime/ProcessManager.d.ts +20 -2
  113. package/dist/src/qa/runtime/ProcessManager.js +69 -13
  114. package/dist/src/qa/tools.d.ts +19 -1
  115. package/dist/src/qa/tools.js +20 -145
  116. package/dist/src/react-runtime.d.ts +11 -0
  117. package/dist/src/react-runtime.js +203 -53
  118. package/dist/src/remote/engine-pool.js +21 -6
  119. package/dist/src/run-progress.d.ts +6 -0
  120. package/dist/src/run-progress.js +7 -0
  121. package/dist/src/runtime.d.ts +8 -0
  122. package/dist/src/screen-selection.d.ts +38 -0
  123. package/dist/src/screen-selection.js +103 -0
  124. package/dist/src/session-changes.d.ts +117 -0
  125. package/dist/src/session-changes.js +796 -0
  126. package/dist/src/session-skills.d.ts +75 -0
  127. package/dist/src/session-skills.js +151 -0
  128. package/dist/src/side-panel.d.ts +1 -1
  129. package/dist/src/side-panel.js +6 -12
  130. package/dist/src/skill-commands.js +1 -1
  131. package/dist/src/skills/bundled/control-browser/SKILL.md +9 -1
  132. package/dist/src/skills/bundled/graph-manager/SKILL.md +8 -0
  133. package/dist/src/skills/bundled/provenance.json +3 -3
  134. package/dist/src/skills/bundled/web-gui-tester/SKILL.md +1 -1
  135. package/dist/src/stall-recovery.d.ts +33 -0
  136. package/dist/src/stall-recovery.js +83 -0
  137. package/dist/src/subagent-run.js +1 -2
  138. package/dist/src/telemetry/schema.d.ts +1 -1
  139. package/dist/src/telemetry/schema.js +1 -2
  140. package/dist/src/terminal-ui.d.ts +66 -22
  141. package/dist/src/terminal-ui.js +327 -92
  142. package/dist/src/tool-diff-stats.d.ts +9 -0
  143. package/dist/src/tool-diff-stats.js +20 -0
  144. package/dist/src/tool-names.d.ts +1 -1
  145. package/dist/src/tool-result-filter.js +1 -1
  146. package/dist/src/tools.js +26 -2
  147. package/dist/src/transcript.d.ts +11 -0
  148. package/dist/src/transcript.js +23 -3
  149. package/dist/src/types.d.ts +24 -4
  150. package/dist/src/usage-analytics.d.ts +7 -0
  151. package/dist/src/usage-analytics.js +55 -15
  152. package/docs/concepts/README.md +1 -1
  153. package/docs/concepts/limits.md +9 -0
  154. package/docs/guides/desktop-app.md +1 -1
  155. package/docs/guides/graph-builder.md +16 -1
  156. package/docs/guides/tui.md +9 -9
  157. package/docs/reference/slash-commands.md +2 -1
  158. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +203 -0
  159. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +79 -0
  160. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +182 -0
  161. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +156 -0
  162. package/package.json +1 -1
  163. package/tests/chat-side-panel-test-plan.md +1 -1
  164. package/dist/src/qa/api/http-runner.d.ts +0 -3
  165. package/dist/src/qa/api/http-runner.js +0 -47
  166. package/dist/src/qa/git/ChangeDetector.d.ts +0 -26
  167. package/dist/src/qa/git/ChangeDetector.js +0 -177
  168. package/dist/src/qa/git/DiffReviewer.d.ts +0 -28
  169. package/dist/src/qa/git/DiffReviewer.js +0 -115
  170. package/dist/src/qa/orchestrator/ChangeClassifier.d.ts +0 -14
  171. package/dist/src/qa/orchestrator/ChangeClassifier.js +0 -28
  172. package/dist/src/qa/orchestrator/MergeGate.d.ts +0 -14
  173. package/dist/src/qa/orchestrator/MergeGate.js +0 -40
  174. package/dist/src/qa/orchestrator/QaOrchestrator.d.ts +0 -79
  175. package/dist/src/qa/orchestrator/QaOrchestrator.js +0 -373
  176. package/dist/src/qa/runners/CommandRunner.d.ts +0 -22
  177. package/dist/src/qa/runners/CommandRunner.js +0 -96
  178. package/dist/src/qa/runners/TestRunner.d.ts +0 -21
  179. package/dist/src/qa/runners/TestRunner.js +0 -66
  180. package/dist/src/qa/runtime/RuntimeSmoke.d.ts +0 -11
  181. package/dist/src/qa/runtime/RuntimeSmoke.js +0 -78
  182. package/dist/src/qa/runtime-detect.d.ts +0 -10
  183. package/dist/src/qa/runtime-detect.js +0 -72
  184. package/dist/src/qa/security/DependencyScanner.d.ts +0 -19
  185. package/dist/src/qa/security/DependencyScanner.js +0 -167
  186. package/dist/src/qa/security/SecretScanner.d.ts +0 -3
  187. package/dist/src/qa/security/SecretScanner.js +0 -55
@@ -0,0 +1,796 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { chmod, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir, unlink, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { acquireSaveLock, SaveLockBusyError } from './save-lock.js';
5
+ import { fileDiff } from './file-diff.js';
6
+ /**
7
+ * The files an agent changed in a session since the person last reviewed them, with Keep and Undo.
8
+ *
9
+ * Every write an agent makes to a workspace file passes one function (`atomicWrite` in `tools.ts`), and a
10
+ * delegated change lands through one more (`applyLanding`). Both report here, before and after: before, so
11
+ * the content the file held can be kept as its baseline the first time the agent touches it; after, so the
12
+ * store knows what the agent's write left. Between two reviews the baseline never moves — a file edited ten
13
+ * times has one entry, and its diff is the file's whole change, not the last call's.
14
+ *
15
+ * Keep makes the file as it is the new baseline: it leaves the pending set and its stored original is
16
+ * dropped. Undo puts the baseline back — the earlier content, or no file at all for one the agent created,
17
+ * or the file again for one a landing removed — but only while the file is still what the agent left: a file
18
+ * something else changed afterwards is reported as a conflict instead of being overwritten, unless the
19
+ * caller asks with `force`.
20
+ *
21
+ * The record lives in the configuration home beside the session (`session-changes/<id>/`), not in the
22
+ * workspace and not in Git: it works for a folder that is no repository, needs no index, and survives an
23
+ * app restart and a resumed session. Engines sharing a home can all read and change it — the desktop runs a
24
+ * process per task and browses with another — so every change happens under the session's store lock, and
25
+ * the revision it carries orders every answer and event across those processes.
26
+ */
27
+ /** Past this size a file's earlier content is not kept: the change is listed, and Undo refuses the file. */
28
+ export const BASELINE_BYTE_LIMIT = 16 * 1024 * 1024;
29
+ /** Diff lines `list` returns per file unless asked for another bound. */
30
+ export const LIST_DIFF_LINES = 200;
31
+ /** The most diff lines one answer may ask for per file. */
32
+ export const MAX_DIFF_LINES = 20_000;
33
+ /** Characters of diff text per file, so a minified rewrite cannot fill an answer. */
34
+ const DIFF_CHARS = 1024 * 1024;
35
+ const LINE_CHARS = 2_000;
36
+ const LOCK_WAIT_MS = 60_000;
37
+ /** Bytes of originals one write holds in memory while it lands; the rest wait in the store of originals. */
38
+ const BEGIN_MEMORY = 64 * 1024 * 1024;
39
+ /** Diff lines and characters one `list` answer carries across all its files; past them a file lists its counts and `hiddenLines`. */
40
+ const LIST_TOTAL_LINES = 20_000;
41
+ const LIST_TOTAL_CHARS = 4 * 1024 * 1024;
42
+ /** Session ids name files, so only the characters a session id is made of are accepted. */
43
+ export function sessionChangesId(id) {
44
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(id))
45
+ throw new Error(`Invalid session id: ${id}`);
46
+ return id;
47
+ }
48
+ export const sessionChangesRoot = (home) => path.join(home, 'session-changes');
49
+ const sessionFolder = (home, sessionId) => path.join(sessionChangesRoot(home), sessionChangesId(sessionId));
50
+ const stateFile = (home, sessionId) => path.join(sessionFolder(home, sessionId), 'state.json');
51
+ const blobFolder = (home, sessionId) => path.join(sessionFolder(home, sessionId), 'blobs');
52
+ const blobFile = (home, sessionId, hash) => path.join(blobFolder(home, sessionId), hash);
53
+ const hashOf = (bytes) => createHash('sha256').update(bytes).digest('hex');
54
+ const missing = (error) => error.code === 'ENOENT';
55
+ const errorText = (error) => error instanceof Error ? error.message : String(error);
56
+ const keyOf = (root, relative) => {
57
+ const key = `${root}\0${relative}`;
58
+ return process.platform === 'win32' ? key.toLowerCase() : key;
59
+ };
60
+ function within(root, target) {
61
+ const relative = path.relative(root, target);
62
+ return relative === '' || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`));
63
+ }
64
+ function validState(value) {
65
+ if (!value || typeof value !== 'object')
66
+ return false;
67
+ const record = value;
68
+ return record.version === 1 && Number.isSafeInteger(record.revision) && Array.isArray(record.changes)
69
+ && record.changes.every(change => change && typeof change.path === 'string' && typeof change.root === 'string'
70
+ && typeof change.baseline === 'object' && typeof change.written === 'object' && Number.isSafeInteger(change.version));
71
+ }
72
+ async function readState(home, sessionId) {
73
+ let text;
74
+ try {
75
+ text = await readFile(stateFile(home, sessionId), 'utf8');
76
+ }
77
+ catch (error) {
78
+ if (missing(error))
79
+ return { version: 1, revision: 0, changes: [] };
80
+ throw error;
81
+ }
82
+ try {
83
+ const value = JSON.parse(text);
84
+ if (validState(value))
85
+ return value;
86
+ }
87
+ catch { /* an unreadable record is reported below */ }
88
+ throw new Error(`The review record of session ${sessionId} is not readable`);
89
+ }
90
+ /** Through a temporary file and a rename, so a reader in another engine never sees half a record. */
91
+ async function writeState(home, sessionId, state) {
92
+ const target = stateFile(home, sessionId);
93
+ await mkdir(path.dirname(target), { recursive: true });
94
+ const temporary = `${target}.${randomUUID()}.tmp`;
95
+ await writeFile(temporary, `${JSON.stringify(state)}\n`, 'utf8');
96
+ try {
97
+ await rename(temporary, target);
98
+ }
99
+ catch (error) {
100
+ await rm(temporary, { force: true });
101
+ throw error;
102
+ }
103
+ }
104
+ async function writeBlob(home, sessionId, hash, bytes) {
105
+ const target = blobFile(home, sessionId, hash);
106
+ try {
107
+ await lstat(target);
108
+ return;
109
+ }
110
+ catch (error) {
111
+ if (!missing(error))
112
+ throw error;
113
+ }
114
+ await mkdir(path.dirname(target), { recursive: true });
115
+ const temporary = `${target}.${randomUUID()}.tmp`;
116
+ await writeFile(temporary, bytes, { mode: 0o600 });
117
+ try {
118
+ await rename(temporary, target);
119
+ }
120
+ catch (error) {
121
+ await rm(temporary, { force: true });
122
+ throw error;
123
+ }
124
+ }
125
+ async function readBlob(home, sessionId, hash) {
126
+ const bytes = await readFile(blobFile(home, sessionId, hash));
127
+ if (hashOf(bytes) !== hash)
128
+ throw new Error('The stored original of this file is damaged');
129
+ return bytes;
130
+ }
131
+ /** Removes every stored original no entry refers to any more. Best effort: a leftover blob is only disk. */
132
+ async function collectBlobs(home, sessionId, state) {
133
+ const referenced = new Set(state.changes.flatMap(change => change.baseline.kind === 'file' ? [change.baseline.hash] : []));
134
+ let names;
135
+ try {
136
+ names = await readdir(blobFolder(home, sessionId));
137
+ }
138
+ catch (error) {
139
+ if (missing(error))
140
+ return;
141
+ throw error;
142
+ }
143
+ await Promise.all(names.filter(name => !referenced.has(name)).map(name => unlink(blobFile(home, sessionId, name)).catch(() => { })));
144
+ if (!referenced.size)
145
+ await rmdir(blobFolder(home, sessionId)).catch(() => { });
146
+ }
147
+ /** The file at `target` as it stands, read only when it is a regular file small enough to keep. */
148
+ async function observe(target, limit) {
149
+ let info;
150
+ try {
151
+ info = await lstat(target);
152
+ }
153
+ catch (error) {
154
+ if (missing(error) || error.code === 'ENOTDIR')
155
+ return { kind: 'absent' };
156
+ throw error;
157
+ }
158
+ if (!info.isFile())
159
+ return { kind: 'other' };
160
+ const mode = info.mode & 0o777;
161
+ if (info.size > limit)
162
+ return { kind: 'large', size: info.size, mode };
163
+ const handle = await open(target, 'r');
164
+ try {
165
+ const bytes = await handle.readFile();
166
+ return bytes.length > limit ? { kind: 'large', size: bytes.length, mode } : { kind: 'file', bytes, mode };
167
+ }
168
+ finally {
169
+ await handle.close();
170
+ }
171
+ }
172
+ const queues = new Map();
173
+ /**
174
+ * Runs `work` as the only holder of the store lock in `folder`, across every engine sharing the home: an
175
+ * in-process queue keeps one engine's callers in order, and the store lock (the one graph saves use, which
176
+ * recovers an abandoned owner) covers the other processes.
177
+ */
178
+ function withLock(folder, work) {
179
+ const previous = queues.get(folder) ?? Promise.resolve();
180
+ const next = previous.catch(() => { }).then(async () => {
181
+ const release = await lock(folder);
182
+ try {
183
+ return await work();
184
+ }
185
+ finally {
186
+ await release();
187
+ }
188
+ });
189
+ const settled = next.catch(() => { });
190
+ queues.set(folder, settled);
191
+ void settled.then(() => { if (queues.get(folder) === settled)
192
+ queues.delete(folder); });
193
+ return next;
194
+ }
195
+ /** Takes the lock `withLock` takes and answers its release: for a critical section that is not one callback. */
196
+ function holdLock(folder) {
197
+ return new Promise((resolve, reject) => {
198
+ let open;
199
+ const held = new Promise(done => { open = done; });
200
+ let entered = false;
201
+ const finished = withLock(folder, async () => {
202
+ entered = true;
203
+ resolve(async () => { open(); await finished.catch(() => { }); });
204
+ await held;
205
+ });
206
+ finished.catch(error => { if (!entered)
207
+ reject(error); });
208
+ });
209
+ }
210
+ async function lock(folder) {
211
+ const deadline = Date.now() + LOCK_WAIT_MS;
212
+ for (let delay = 20;; delay = Math.min(delay * 2, 500)) {
213
+ try {
214
+ return await acquireSaveLock(folder);
215
+ }
216
+ catch (error) {
217
+ // Windows answers a lock directory created while the previous holder's is being removed with EPERM
218
+ // (or EACCES/EBUSY): the same "someone else is mid-change" as a busy lock, and it clears the same way.
219
+ // ENOENT is a file lock's folder being removed by its last holder between this taker's two mkdirs.
220
+ const transient = error instanceof SaveLockBusyError || ['EPERM', 'EACCES', 'EBUSY', 'ENOENT'].includes(error.code ?? '');
221
+ if (!transient || Date.now() >= deadline)
222
+ throw error;
223
+ await new Promise(resolve => setTimeout(resolve, delay));
224
+ }
225
+ }
226
+ }
227
+ /*
228
+ * Two kinds of lock, always taken in this order, which is what keeps them free of deadlock:
229
+ *
230
+ * 1. File locks, one per canonical file path, taken in sorted order. Every recorded agent write holds the lock
231
+ * of each file it writes from just before its rename until it is recorded, whatever its session, and an Undo
232
+ * holds the locks of the files it restores from its check until its restore. Two sessions can edit the
233
+ * same folder, so the session's own lock alone would let session B's write land between session A's check
234
+ * and A's restore.
235
+ * 2. The session lock, which guards one session's record (`state.json` and its originals). Keep, Undo and
236
+ * the record of a write take it last and hold no other session's.
237
+ */
238
+ const sessionLockFolder = (home, sessionId) => path.join(sessionChangesRoot(home), '.locks', sessionChangesId(sessionId));
239
+ const fileLockFolder = (home, key) => path.join(sessionChangesRoot(home), '.file-locks', key);
240
+ /** The identity a file is locked by: its canonical absolute path (case folded on Windows), hashed to a name. */
241
+ function fileLockKey(root, relative) {
242
+ const absolute = path.join(root, ...relative.split('/'));
243
+ return createHash('sha256').update(process.platform === 'win32' ? absolute.toLowerCase() : absolute).digest('hex');
244
+ }
245
+ function withSession(home, sessionId, work) {
246
+ return withLock(sessionLockFolder(home, sessionId), work);
247
+ }
248
+ const holdSession = (home, sessionId) => holdLock(sessionLockFolder(home, sessionId));
249
+ /** Takes the locks of these files, in sorted order, and answers the release of all of them. */
250
+ async function holdFiles(home, keys) {
251
+ const releases = [];
252
+ const releaseAll = async () => { for (const release of releases.splice(0).reverse())
253
+ await release().catch(() => { }); };
254
+ try {
255
+ for (const key of [...new Set(keys)].sort()) {
256
+ const folder = fileLockFolder(home, key);
257
+ const release = await holdLock(folder);
258
+ // One folder per file ever written would pile up in the home, so the last holder removes it. A taker
259
+ // that is between its own mkdirs then finds no folder and retries; a held lock keeps it non-empty.
260
+ releases.push(async () => { await release(); await rmdir(folder).catch(() => { }); });
261
+ }
262
+ }
263
+ catch (error) {
264
+ await releaseAll();
265
+ throw error;
266
+ }
267
+ return releaseAll;
268
+ }
269
+ function statusOf(baseline, current) {
270
+ if (baseline.kind === 'absent')
271
+ return 'added';
272
+ return current.kind === 'absent' ? 'deleted' : 'modified';
273
+ }
274
+ function wireDiff(result) {
275
+ return result.kind === 'text' ? { hunks: result.diff.hunks, hiddenLines: result.diff.hiddenLines } : null;
276
+ }
277
+ /**
278
+ * Permission bits are part of a file's state where the file system keeps them: a landing can change only a
279
+ * file's executable bit, and that is a change to review and to undo. Windows reports a mode that stands
280
+ * for nothing the tools change, so there it is not compared.
281
+ */
282
+ const MODES_COMPARABLE = process.platform !== 'win32';
283
+ const octal = (mode) => (mode & 0o777).toString(8).padStart(3, '0');
284
+ /** `from` → `to` permission bits when the file exists on both sides with different modes. */
285
+ function modeChangeOf(baseline, current) {
286
+ if (!MODES_COMPARABLE || baseline.kind !== 'file' || (current.kind !== 'file' && current.kind !== 'large'))
287
+ return undefined;
288
+ return baseline.mode === current.mode ? undefined : { from: octal(baseline.mode), to: octal(current.mode) };
289
+ }
290
+ /** A text's line terminators: all LF, all CRLF, or both; nothing for text with no line break. */
291
+ function lineEndingOf(bytes) {
292
+ let lf = 0, crlf = 0;
293
+ for (let at = bytes.indexOf(0x0a); at >= 0; at = bytes.indexOf(0x0a, at + 1)) {
294
+ if (at > 0 && bytes[at - 1] === 0x0d)
295
+ crlf++;
296
+ else
297
+ lf++;
298
+ }
299
+ if (!lf && !crlf)
300
+ return undefined;
301
+ return lf && crlf ? 'mixed' : crlf ? 'crlf' : 'lf';
302
+ }
303
+ /**
304
+ * The line terminators changed between the sides — a conversion every line of which reads the same once the
305
+ * terminator is dropped, which is what the diff lines show. Said once for the file so a view can explain why
306
+ * a line is removed and added with the same text.
307
+ */
308
+ function lineEndingsOf(result, before, after) {
309
+ if (result.kind !== 'text' || !before || !after)
310
+ return undefined;
311
+ const from = lineEndingOf(before), to = lineEndingOf(after);
312
+ return from && to && from !== to ? { from, to } : undefined;
313
+ }
314
+ function measured(result) {
315
+ if (result.kind === 'text')
316
+ return { linesAdded: result.diff.linesAdded, linesRemoved: result.diff.linesRemoved };
317
+ if (result.kind === 'binary')
318
+ return { linesAdded: 0, linesRemoved: 0, binary: true };
319
+ return { linesAdded: result.linesAdded ?? 0, linesRemoved: result.linesRemoved ?? 0, tooLarge: true };
320
+ }
321
+ function summary(change) {
322
+ return {
323
+ path: change.path, status: change.status, linesAdded: change.linesAdded, linesRemoved: change.linesRemoved,
324
+ ...(change.binary ? { binary: true } : {}), ...(change.tooLarge ? { tooLarge: true } : {}),
325
+ ...(change.modeChange ? { modeChange: change.modeChange } : {}), ...(change.lineEndings ? { lineEndings: change.lineEndings } : {}),
326
+ undoable: change.baseline.kind !== 'unavailable', version: change.version,
327
+ firstChangedAt: change.firstChangedAt, updatedAt: change.updatedAt,
328
+ };
329
+ }
330
+ function snapshot(sessionId, state) {
331
+ return { sessionId, revision: state.revision, changes: state.changes.map(summary) };
332
+ }
333
+ /** Whether the file on disk is still what the agent's last write left: its bytes and, where kept, its mode. */
334
+ function sameAsWritten(written, current) {
335
+ if (written.kind === 'absent')
336
+ return current.kind === 'absent';
337
+ if (current.kind !== 'file')
338
+ return false;
339
+ if (MODES_COMPARABLE && written.mode !== undefined && written.mode !== current.mode)
340
+ return false;
341
+ return current.bytes.length === written.size && hashOf(current.bytes) === written.hash;
342
+ }
343
+ /** Whether the file is back to its baseline: the same bytes and, where modes mean something, the same mode. */
344
+ function sameAsBaseline(baseline, current) {
345
+ if (baseline.kind === 'absent')
346
+ return current.kind === 'absent';
347
+ if (baseline.kind !== 'file' || current.kind !== 'file')
348
+ return false;
349
+ if (MODES_COMPARABLE && baseline.mode !== current.mode)
350
+ return false;
351
+ return current.bytes.length === baseline.size && hashOf(current.bytes) === baseline.hash;
352
+ }
353
+ export class SessionChangeStore {
354
+ home;
355
+ baselineLimit;
356
+ beforeRestore;
357
+ /**
358
+ * Both options exist for tests: `baselineLimit` is the size past which an original is not kept, and
359
+ * `beforeRestore` runs inside an Undo, under its lock, after it has checked the files and before it writes.
360
+ */
361
+ constructor(home, options = {}) {
362
+ this.home = home;
363
+ this.baselineLimit = options.baselineLimit ?? BASELINE_BYTE_LIMIT;
364
+ this.beforeRestore = options.beforeRestore;
365
+ this.beginMemory = options.beginMemory ?? BEGIN_MEMORY;
366
+ }
367
+ /** Test seam: the bytes of originals one write holds in memory before the rest go to the store. */
368
+ beginMemory;
369
+ /**
370
+ * The recorder a run's tools report their writes to. Only files inside `root` (the run's workspace folder)
371
+ * are tracked: a delegated subagent writes in a worktree of its own, and its change reaches the workspace
372
+ * through the landing, which reports the files it lands.
373
+ */
374
+ recorder(sessionId, workspace, onChange, onError) {
375
+ sessionChangesId(sessionId);
376
+ let rootPromise;
377
+ const root = () => rootPromise ??= realpath(workspace).catch(() => path.resolve(workspace));
378
+ return {
379
+ beforeWrite: async (targets) => {
380
+ try {
381
+ const canonicalRoot = await root();
382
+ // The paths this recorder tracks, and the folders a write to each would create (Undo of a created
383
+ // file removes them again when they are empty). Read now, before the writer makes any folder.
384
+ const tracked = [];
385
+ for (const target of typeof targets === 'string' ? [targets] : targets) {
386
+ const resolved = path.resolve(target);
387
+ if (!within(canonicalRoot, resolved) || resolved === canonicalRoot)
388
+ continue;
389
+ const created = [];
390
+ for (let folder = path.dirname(resolved); within(canonicalRoot, folder) && folder !== canonicalRoot; folder = path.dirname(folder)) {
391
+ const exists = await lstat(folder).then(() => true, error => { if (missing(error) || error.code === 'ENOTDIR')
392
+ return false; throw error; });
393
+ if (exists)
394
+ break;
395
+ created.unshift(path.relative(canonicalRoot, folder).split(path.sep).join('/'));
396
+ }
397
+ tracked.push({ relative: path.relative(canonicalRoot, resolved).split(path.sep).join('/'), created });
398
+ }
399
+ if (!tracked.length)
400
+ return undefined;
401
+ let release;
402
+ let before = [];
403
+ let spilled = false;
404
+ const letGo = async () => { const done = release; release = undefined; await done?.(); };
405
+ return {
406
+ begin: async () => {
407
+ if (release)
408
+ throw new Error('This write is already begun');
409
+ // The files' locks first (sorted), then the session's: the order every holder uses.
410
+ const releaseFiles = await holdFiles(this.home, tracked.map(entry => fileLockKey(canonicalRoot, entry.relative)));
411
+ let releaseSession;
412
+ try {
413
+ releaseSession = await holdSession(this.home, sessionId);
414
+ }
415
+ catch (error) {
416
+ await releaseFiles();
417
+ throw error;
418
+ }
419
+ release = async () => { try {
420
+ await releaseSession();
421
+ }
422
+ finally {
423
+ await releaseFiles();
424
+ } };
425
+ try {
426
+ // One file at a time, and past the budget straight into the store of originals: a landing of many
427
+ // large files must not hold all of them in memory until it is recorded.
428
+ before = [];
429
+ let held = 0;
430
+ for (const entry of tracked) {
431
+ const seen = await observe(path.join(canonicalRoot, ...entry.relative.split('/')), this.baselineLimit);
432
+ if (seen.kind === 'file' && held + seen.bytes.length > this.beginMemory) {
433
+ const hash = hashOf(seen.bytes);
434
+ await writeBlob(this.home, sessionId, hash, seen.bytes);
435
+ before.push({ kind: 'stored', hash, size: seen.bytes.length, mode: seen.mode });
436
+ spilled = true;
437
+ continue;
438
+ }
439
+ if (seen.kind === 'file')
440
+ held += seen.bytes.length;
441
+ before.push(seen);
442
+ }
443
+ }
444
+ catch (error) {
445
+ before = [];
446
+ onError?.(error);
447
+ }
448
+ },
449
+ commit: async () => {
450
+ if (!release)
451
+ return;
452
+ try {
453
+ if (before.length) {
454
+ const changes = await this.recordWrites(sessionId, canonicalRoot, tracked.map((entry, index) => ({ ...entry, before: before[index] })), spilled);
455
+ if (changes)
456
+ onChange(changes);
457
+ }
458
+ }
459
+ catch (error) {
460
+ onError?.(error);
461
+ }
462
+ finally {
463
+ await letGo().catch(onError);
464
+ }
465
+ },
466
+ abort: async () => {
467
+ // Originals stored for a write that did not land are referenced by nothing.
468
+ if (spilled && release)
469
+ await readState(this.home, sessionId).then(state => collectBlobs(this.home, sessionId, state)).catch(onError);
470
+ await letGo().catch(onError);
471
+ },
472
+ };
473
+ }
474
+ catch (error) {
475
+ onError?.(error);
476
+ return undefined;
477
+ }
478
+ },
479
+ };
480
+ }
481
+ /** Records what a landed write left, for each file it wrote. The caller holds the session's lock. */
482
+ async recordWrites(sessionId, root, files, spilled = false) {
483
+ const state = await readState(this.home, sessionId);
484
+ let changed = false;
485
+ for (const file of files)
486
+ changed = await this.recordWrite(sessionId, state, root, file.relative, file.before, file.created) || changed;
487
+ if (!changed) {
488
+ // Originals stored while the write began, for files it left as they were, are referenced by nothing.
489
+ if (spilled)
490
+ await collectBlobs(this.home, sessionId, state);
491
+ return undefined;
492
+ }
493
+ state.revision += 1;
494
+ await writeState(this.home, sessionId, state);
495
+ await collectBlobs(this.home, sessionId, state);
496
+ return snapshot(sessionId, state);
497
+ }
498
+ /** Updates one file's entry in `state`; answers whether the pending set changed. */
499
+ async recordWrite(sessionId, state, root, relative, before, created) {
500
+ const target = path.join(root, ...relative.split('/'));
501
+ if (before.kind === 'other')
502
+ return false;
503
+ const after = await observe(target, this.baselineLimit);
504
+ if (after.kind === 'other')
505
+ return false;
506
+ const written = after.kind === 'absent' ? { kind: 'absent' }
507
+ : after.kind === 'file' ? { kind: 'file', hash: hashOf(after.bytes), size: after.bytes.length, mode: after.mode }
508
+ // Too large to hash in the record's terms: a size no real write produces stands in, so a later
509
+ // Undo sees "changed since" and asks before it overwrites anything.
510
+ : { kind: 'file', hash: 'unmeasured', size: -1 };
511
+ const key = keyOf(root, relative);
512
+ const index = state.changes.findIndex(change => keyOf(change.root, change.path) === key);
513
+ const now = new Date().toISOString();
514
+ let entry = index < 0 ? undefined : state.changes[index];
515
+ if (!entry) {
516
+ const baseline = before.kind === 'absent' ? { kind: 'absent' }
517
+ : before.kind === 'file' ? { kind: 'file', hash: hashOf(before.bytes), size: before.bytes.length, mode: before.mode }
518
+ : before.kind === 'stored' ? { kind: 'file', hash: before.hash, size: before.size, mode: before.mode }
519
+ : { kind: 'unavailable', size: before.kind === 'large' ? before.size : 0 };
520
+ entry = { path: relative, root, baseline, written, status: 'modified', linesAdded: 0, linesRemoved: 0, version: 0, firstChangedAt: now, updatedAt: now,
521
+ ...(baseline.kind === 'absent' && created.length ? { createdDirectories: created } : {}) };
522
+ }
523
+ if (sameAsBaseline(entry.baseline, after)) {
524
+ // The agent wrote the file back to what it was (or a write changed nothing): there is nothing to review.
525
+ if (index < 0)
526
+ return false;
527
+ state.changes.splice(index, 1);
528
+ return true;
529
+ }
530
+ // A new entry's original is stored only now that there is a change to keep it for.
531
+ if (index < 0 && entry.baseline.kind === 'file' && before.kind === 'file')
532
+ await writeBlob(this.home, sessionId, entry.baseline.hash, before.bytes);
533
+ const baselineBytes = entry.baseline.kind !== 'file' ? null
534
+ : index < 0 && before.kind === 'file' ? before.bytes : await readBlob(this.home, sessionId, entry.baseline.hash);
535
+ const result = entry.baseline.kind === 'unavailable' || after.kind === 'large'
536
+ ? { kind: 'too-large' }
537
+ : fileDiff(baselineBytes, after.kind === 'file' ? after.bytes : null, { maxLines: 0 });
538
+ const { binary: _binary, tooLarge: _tooLarge, modeChange: _modeChange, lineEndings: _lineEndings, diffLines: _diffLines, ...rest } = entry;
539
+ const modeChange = modeChangeOf(entry.baseline, after);
540
+ const lineEndings = lineEndingsOf(result, baselineBytes, after.kind === 'file' ? after.bytes : null);
541
+ // The version is the revision this write gives the record, so it never repeats for a path — not even when
542
+ // the file was kept or undone and the agent changes it again: a client's cached diff of an earlier
543
+ // generation can never pass for this one.
544
+ entry = { ...rest, ...measured(result), ...(modeChange ? { modeChange } : {}), ...(lineEndings ? { lineEndings } : {}),
545
+ ...(result.kind === 'text' ? { diffLines: result.diff.hiddenLines } : {}),
546
+ written, status: statusOf(entry.baseline, after), version: state.revision + 1, updatedAt: now };
547
+ if (index < 0)
548
+ state.changes.push(entry);
549
+ else
550
+ state.changes[index] = entry;
551
+ return true;
552
+ }
553
+ /** The pending set as the last write, Keep or Undo left it, without reading the files. */
554
+ async pending(sessionId) {
555
+ return snapshot(sessionId, await readState(this.home, sessionId));
556
+ }
557
+ /** Each pending file with its diff from the earlier content to the file as it is now, `maxLines` per file. */
558
+ async list(sessionId, maxLines = LIST_DIFF_LINES) {
559
+ const state = await readState(this.home, sessionId);
560
+ const changes = [];
561
+ // One answer carries a bounded amount of diff whatever the number of files: once it is spent, a file still
562
+ // lists its counts, and its `hiddenLines` says there is a diff to read with `get`.
563
+ let lines = LIST_TOTAL_LINES, chars = LIST_TOTAL_CHARS;
564
+ for (const stored of state.changes) {
565
+ const fresh = await this.fresh(sessionId, stored, Math.min(maxLines, lines), Math.min(DIFF_CHARS, chars));
566
+ if (!fresh)
567
+ continue;
568
+ changes.push(fresh.change);
569
+ for (const hunk of fresh.change.diff?.hunks ?? []) {
570
+ lines -= hunk.lines.length;
571
+ for (const line of hunk.lines)
572
+ chars -= line.text.length;
573
+ }
574
+ }
575
+ return { sessionId, revision: state.revision, changes };
576
+ }
577
+ /** One pending file with its diff, up to `maxLines`; null when the file is not pending. */
578
+ async get(sessionId, relative, maxLines = MAX_DIFF_LINES) {
579
+ const state = await readState(this.home, sessionId);
580
+ const stored = state.changes.find(change => change.path === relative);
581
+ const fresh = stored ? await this.fresh(sessionId, stored, maxLines) : undefined;
582
+ return { revision: state.revision, change: fresh?.change ?? null };
583
+ }
584
+ /** A stored entry measured against the disk now; nothing when the file is back to its baseline. */
585
+ async fresh(sessionId, stored, maxLines, maxChars = DIFF_CHARS) {
586
+ const target = path.join(stored.root, ...stored.path.split('/'));
587
+ let current;
588
+ // Read up to the size an original is kept at, so "changed since the agent wrote it" stays exact for
589
+ // every file Undo could restore; past the diff bound the change is still listed, without a diff.
590
+ try {
591
+ current = await observe(target, this.baselineLimit);
592
+ }
593
+ catch {
594
+ return { change: summary(stored), current: { kind: 'other' } };
595
+ }
596
+ if (sameAsBaseline(stored.baseline, current))
597
+ return undefined;
598
+ // A listing whose diff budget is spent shows only counts. While the file is what the agent left, the
599
+ // figures measured at that write are exact, so the diff is not computed again just to be thrown away.
600
+ if (maxLines <= 0 && stored.diffLines !== undefined && sameAsWritten(stored.written, current)) {
601
+ return { change: { ...summary(stored), diff: { hunks: [], hiddenLines: stored.diffLines } }, current };
602
+ }
603
+ let result;
604
+ let baselineBytes = null;
605
+ if (stored.baseline.kind === 'unavailable' || current.kind === 'large' || current.kind === 'other')
606
+ result = { kind: 'too-large' };
607
+ else {
608
+ if (stored.baseline.kind === 'file') {
609
+ try {
610
+ baselineBytes = await readBlob(this.home, sessionId, stored.baseline.hash);
611
+ }
612
+ catch {
613
+ return { change: { ...summary(stored), undoable: false, diff: null }, current };
614
+ }
615
+ }
616
+ result = fileDiff(baselineBytes, current.kind === 'file' ? current.bytes : null, { maxLines: Math.max(0, maxLines), maxChars: Math.max(0, maxChars), lineChars: LINE_CHARS });
617
+ }
618
+ const { binary: _binary, tooLarge: _tooLarge, modeChange: _modeChange, lineEndings: _lineEndings, ...base } = summary(stored);
619
+ const modeChange = modeChangeOf(stored.baseline, current);
620
+ const lineEndings = lineEndingsOf(result, baselineBytes, current.kind === 'file' ? current.bytes : null);
621
+ const change = {
622
+ ...base, ...measured(result), ...(modeChange ? { modeChange } : {}), ...(lineEndings ? { lineEndings } : {}),
623
+ status: statusOf(stored.baseline, current),
624
+ ...(sameAsWritten(stored.written, current) ? {} : { changedOnDisk: true }),
625
+ diff: wireDiff(result),
626
+ };
627
+ // `measured` reports 0/0 for a too-large side it could not count; keep the figures the write measured.
628
+ if (result.kind === 'too-large' && result.linesAdded === undefined) {
629
+ change.linesAdded = stored.linesAdded;
630
+ change.linesRemoved = stored.linesRemoved;
631
+ }
632
+ return { change, current };
633
+ }
634
+ /** Accepts the named files (every pending file when `paths` is omitted): each leaves the pending set as it is. */
635
+ async keep(sessionId, paths) {
636
+ return withSession(this.home, sessionId, async () => {
637
+ const state = await readState(this.home, sessionId);
638
+ const chosen = new Set(paths ?? state.changes.map(change => change.path));
639
+ const kept = state.changes.filter(change => chosen.has(change.path)).map(change => change.path);
640
+ if (kept.length) {
641
+ state.changes = state.changes.filter(change => !chosen.has(change.path));
642
+ state.revision += 1;
643
+ await writeState(this.home, sessionId, state);
644
+ await collectBlobs(this.home, sessionId, state);
645
+ }
646
+ return { ...snapshot(sessionId, state), kept };
647
+ });
648
+ }
649
+ /**
650
+ * Restores the named files (every pending file when `paths` is omitted) to their content before the first
651
+ * unreviewed change. A file whose disk content is no longer what the agent left is a conflict: without
652
+ * `force` one such conflict reverts nothing, so a multi-file Undo never leaves the folder half restored by
653
+ * choice. A file whose original was too large to keep is reported and stays pending either way.
654
+ *
655
+ * The check and the restore run under the lock of every file restored, the lock any session's agent write
656
+ * holds from just before its rename until it is recorded (`FileWriteRecording`), so no write — of this
657
+ * session or another one editing the same folder — can land between them.
658
+ */
659
+ async undo(sessionId, paths, force = false) {
660
+ const chosenOf = (state) => {
661
+ const chosen = new Set(paths ?? state.changes.map(change => change.path));
662
+ return state.changes.filter(change => chosen.has(change.path));
663
+ };
664
+ // The files' locks are taken before the session's, so which files to lock is read first; a file that
665
+ // became pending meanwhile sends the Undo round again, and after a few rounds it is left for the next one.
666
+ for (let attempt = 1;; attempt++) {
667
+ const keys = chosenOf(await readState(this.home, sessionId)).map(change => fileLockKey(change.root, change.path));
668
+ const releaseFiles = await holdFiles(this.home, keys);
669
+ try {
670
+ const held = new Set(keys);
671
+ const answer = await withSession(this.home, sessionId, async () => {
672
+ const state = await readState(this.home, sessionId);
673
+ const chosen = chosenOf(state);
674
+ const unlocked = chosen.filter(change => !held.has(fileLockKey(change.root, change.path)));
675
+ if (unlocked.length && attempt < 3)
676
+ return undefined;
677
+ return this.undoLocked(sessionId, state, chosen.filter(change => held.has(fileLockKey(change.root, change.path))), force);
678
+ });
679
+ if (answer)
680
+ return answer;
681
+ }
682
+ finally {
683
+ await releaseFiles();
684
+ }
685
+ }
686
+ }
687
+ /** Undo of `targets`, whose file locks and the session's lock the caller holds. */
688
+ async undoLocked(sessionId, state, targets, force) {
689
+ const conflicts = [];
690
+ const failed = [];
691
+ const ready = [];
692
+ for (const change of targets) {
693
+ if (change.baseline.kind === 'unavailable') {
694
+ conflicts.push({ path: change.path, reason: 'no-baseline', message: 'The file was too large to keep a copy of before it changed, so it cannot be restored.' });
695
+ continue;
696
+ }
697
+ let current;
698
+ try {
699
+ current = await observe(path.join(change.root, ...change.path.split('/')), this.baselineLimit);
700
+ }
701
+ catch (error) {
702
+ failed.push({ path: change.path, message: errorText(error) });
703
+ continue;
704
+ }
705
+ if (!force && !sameAsWritten(change.written, current)) {
706
+ conflicts.push({ path: change.path, reason: 'changed-on-disk', message: current.kind === 'absent'
707
+ ? 'The file was deleted after the agent last wrote it.'
708
+ : change.written.kind === 'absent' ? 'The file was created again after the agent removed it.'
709
+ : 'The file changed after the agent last wrote it.' });
710
+ continue;
711
+ }
712
+ ready.push({ change, current });
713
+ }
714
+ const blocked = !force && conflicts.some(conflict => conflict.reason === 'changed-on-disk');
715
+ const reverted = [];
716
+ if (!blocked) {
717
+ if (ready.length)
718
+ await this.beforeRestore?.();
719
+ for (const { change, current } of ready) {
720
+ try {
721
+ await this.restore(sessionId, change, current);
722
+ reverted.push(change.path);
723
+ }
724
+ catch (error) {
725
+ failed.push({ path: change.path, message: errorText(error) });
726
+ }
727
+ }
728
+ }
729
+ if (reverted.length) {
730
+ const done = new Set(reverted);
731
+ state.changes = state.changes.filter(change => !done.has(change.path));
732
+ state.revision += 1;
733
+ await writeState(this.home, sessionId, state);
734
+ await collectBlobs(this.home, sessionId, state);
735
+ }
736
+ return { ...snapshot(sessionId, state), reverted, conflicts, failed };
737
+ }
738
+ /** Puts one file back to its baseline. Refuses a path whose folders now lead outside the workspace. */
739
+ async restore(sessionId, change, current) {
740
+ const root = await realpath(change.root);
741
+ const target = path.join(root, ...change.path.split('/'));
742
+ if (!within(root, target) || target === root)
743
+ throw new Error('The file is outside the workspace');
744
+ if (current.kind === 'other')
745
+ throw new Error('The path is no longer a regular file');
746
+ const parent = path.dirname(target);
747
+ // A folder on the way that became a link must not carry the restore out of the workspace.
748
+ const existing = await nearestExisting(parent, root);
749
+ if (!within(root, await realpath(existing)))
750
+ throw new Error('A folder on the file’s path now leads outside the workspace');
751
+ if (change.baseline.kind === 'absent') {
752
+ if (current.kind !== 'absent')
753
+ await unlink(target);
754
+ for (const folder of [...(change.createdDirectories ?? [])].reverse()) {
755
+ await rmdir(path.join(root, ...folder.split('/'))).catch(() => { });
756
+ }
757
+ return;
758
+ }
759
+ if (change.baseline.kind !== 'file')
760
+ throw new Error('No earlier content is stored for this file');
761
+ const bytes = await readBlob(this.home, sessionId, change.baseline.hash);
762
+ await mkdir(parent, { recursive: true });
763
+ if (!within(root, await realpath(parent)))
764
+ throw new Error('A folder on the file’s path now leads outside the workspace');
765
+ const temporary = path.join(parent, `.andorracode-${randomUUID()}.tmp`);
766
+ try {
767
+ await writeFile(temporary, bytes, { mode: change.baseline.mode, flag: 'wx' });
768
+ await chmod(temporary, change.baseline.mode);
769
+ await rename(temporary, target);
770
+ }
771
+ catch (error) {
772
+ await rm(temporary, { force: true });
773
+ throw error;
774
+ }
775
+ }
776
+ /** Forgets the session's record and its stored originals, as a deleted session must. */
777
+ async remove(sessionId) {
778
+ await withSession(this.home, sessionId, async () => {
779
+ await rm(sessionFolder(this.home, sessionId), { recursive: true, force: true });
780
+ });
781
+ }
782
+ }
783
+ async function nearestExisting(folder, root) {
784
+ for (let current = folder;; current = path.dirname(current)) {
785
+ try {
786
+ await lstat(current);
787
+ return current;
788
+ }
789
+ catch (error) {
790
+ if (!missing(error))
791
+ throw error;
792
+ }
793
+ if (current === root || path.dirname(current) === current)
794
+ return root;
795
+ }
796
+ }