piroboros 0.1.0 → 0.3.2

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 (52) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/NOTICE +12 -0
  3. package/README.md +91 -167
  4. package/dist/chat/compactor.js +5 -4
  5. package/dist/chat/log.js +3 -2
  6. package/dist/chat/plan.js +1 -0
  7. package/dist/chat/tree.js +1 -0
  8. package/dist/chat/turn.js +0 -15
  9. package/dist/conclave/pipeline.js +222 -19
  10. package/dist/config.js +127 -12
  11. package/dist/diff.js +90 -0
  12. package/dist/durable.js +69 -4
  13. package/dist/guard.js +170 -14
  14. package/dist/learn.js +938 -0
  15. package/dist/main.js +3 -9
  16. package/dist/memory/akashic/tools.js +25 -28
  17. package/dist/memory/mnemosia/conflicts.js +0 -4
  18. package/dist/memory/mnemosia/orchestrator.js +1 -11
  19. package/dist/memory/mnemosia/policy.js +0 -3
  20. package/dist/memory/mnemosia/rank.js +0 -4
  21. package/dist/memory/mnemosia/rerank.js +3 -30
  22. package/dist/memory/mnemosia/rollback.js +1 -149
  23. package/dist/memory/mnemosia/tokens.js +1 -11
  24. package/dist/memory/mnemosia/tools.js +0 -10
  25. package/dist/memory/mnemosia/types.js +0 -2
  26. package/dist/runtime.js +80 -11
  27. package/dist/search.js +25 -12
  28. package/dist/shell.js +2 -2
  29. package/dist/telemetry.js +84 -0
  30. package/dist/tui/app.js +17 -3
  31. package/dist/tui/commands.js +6 -2
  32. package/dist/tui/settings.js +4 -1
  33. package/dist/tui/thinking/parse.js +0 -3
  34. package/dist/ws/apply.js +817 -0
  35. package/dist/ws/cas.js +144 -0
  36. package/dist/ws/confine.js +194 -0
  37. package/dist/ws/docker.js +151 -0
  38. package/dist/ws/git.js +162 -0
  39. package/dist/ws/lww.js +48 -0
  40. package/dist/ws/merge.js +129 -0
  41. package/dist/ws/workspace.js +1596 -0
  42. package/dist/ws/wsl.js +259 -0
  43. package/docs/conclave.md +35 -0
  44. package/docs/configuration.md +54 -0
  45. package/docs/development.md +25 -0
  46. package/docs/interface.md +33 -0
  47. package/docs/memory.md +11 -0
  48. package/docs/privacy.md +15 -0
  49. package/docs/tools.md +62 -0
  50. package/docs/web.md +38 -0
  51. package/package.json +23 -10
  52. package/settings.json.example +4 -1
@@ -0,0 +1,817 @@
1
+ import { createHash } from "node:crypto";
2
+ import fsp from "node:fs/promises";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { canonicalize, isInside } from "../paths.js";
5
+ import { BATCH_BYTES, Cas, OPEN_BATCH, pack, SNAPSHOT_MAX } from "./cas.js";
6
+ export const realFs = fsp;
7
+ /** A hold that needs no record: nothing live changed. `detail` is the hold code's argument. */
8
+ export class HoldError extends Error {
9
+ code;
10
+ detail;
11
+ constructor(code, detail) {
12
+ super(detail);
13
+ this.code = code;
14
+ this.detail = detail;
15
+ }
16
+ }
17
+ /** A pre-flight re-decision found a conflict: the merge writes nothing. */
18
+ export class ConflictFound extends Error {
19
+ constructor(path) { super(`conflict at ${path}`); }
20
+ }
21
+ const MARGIN = 64 * 1024 * 1024;
22
+ const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
23
+ const code = (error) => error?.code;
24
+ const message = (error) => (error instanceof Error ? error.message : String(error));
25
+ const eexist = (path) => Object.assign(new Error(`${path} already exists`), { code: "EEXIST" });
26
+ const slash = (rel) => rel.split("/");
27
+ /** ponytail: 6.3 s on win32 (a scanner can hold a fresh file), 350 ms elsewhere; the plan sets both and d1.38 measured the Windows hold. */
28
+ const WAITS = { win32: [100, 200, 400, 800, 1_600, 3_200], other: [50, 100, 200] };
29
+ export class Writer {
30
+ d;
31
+ db;
32
+ /** True once one call of the current pass used its whole retry budget: later calls get one attempt. */
33
+ exhausted = false;
34
+ linkable = new Map();
35
+ listings = new Map();
36
+ constructor(deps) { this.d = deps; this.db = deps.cas.db; }
37
+ /* --- io --------------------------------------------------------------------------------------------------- */
38
+ /** Drop the cached folder listings, so the next `name` reads the folder as it is now (a plan that follows the user's edits). */
39
+ forgetNames() { this.listings.clear(); }
40
+ startPass() { this.exhausted = false; this.linkable.clear(); this.listings.clear(); }
41
+ /** Link, rename, unlink and rmdir retry EBUSY, EPERM and EACCES with async waits; a wait past 1 s shows a notice. */
42
+ async retry(path, fn) {
43
+ const waits = (this.d.platform ?? process.platform) === "win32" ? WAITS.win32 : WAITS.other;
44
+ const sleep = this.d.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
45
+ let waited = 0;
46
+ for (let i = 0;; i += 1) {
47
+ try {
48
+ return await fn();
49
+ }
50
+ catch (error) {
51
+ if (!["EBUSY", "EPERM", "EACCES"].includes(code(error) ?? ""))
52
+ throw error;
53
+ if (this.exhausted || i >= waits.length) {
54
+ this.exhausted = true;
55
+ throw error;
56
+ }
57
+ if (waited + waits[i] > 1_000 && waited <= 1_000)
58
+ this.d.notice(`waiting for ${path}, which another program holds`);
59
+ waited += waits[i];
60
+ await sleep(waits[i]);
61
+ }
62
+ }
63
+ }
64
+ async live(abs) {
65
+ let info;
66
+ try {
67
+ info = await this.d.fs.lstat(abs);
68
+ }
69
+ catch (error) {
70
+ if (code(error) === "ENOENT" || code(error) === "ENOTDIR")
71
+ return { kind: "absent" };
72
+ throw error;
73
+ }
74
+ if (info.isDirectory())
75
+ return { kind: "dir" };
76
+ if (!info.isFile())
77
+ return { kind: "other" };
78
+ return { kind: "file", hash: await this.hashFile(abs, info.size), size: info.size, mode: info.mode & 0o777 };
79
+ }
80
+ /** `size`, when the caller has just stat-ed the file, starts a small file on a small read buffer (a full read grows it to 1 MiB); the hash does not depend on it. */
81
+ async hashFile(abs, size) {
82
+ const fh = await this.d.fs.open(abs, "r");
83
+ try {
84
+ const hash = createHash("sha256");
85
+ let buf = Buffer.allocUnsafe(size === undefined ? 1 << 20 : Math.min(1 << 20, size + 1));
86
+ for (;;) {
87
+ const { bytesRead } = await fh.read(buf, 0, buf.length, null);
88
+ if (bytesRead === 0)
89
+ return hash.digest("hex");
90
+ hash.update(buf.subarray(0, bytesRead));
91
+ if (bytesRead === buf.length && buf.length < 1 << 20)
92
+ buf = Buffer.allocUnsafe(1 << 20);
93
+ }
94
+ }
95
+ finally {
96
+ await fh.close();
97
+ }
98
+ }
99
+ /** Up to `max` bytes through one handle; `over` when the file is larger. */
100
+ async readBounded(abs, max) {
101
+ const fh = await this.d.fs.open(abs, "r");
102
+ try {
103
+ const chunks = [];
104
+ let total = 0;
105
+ for (;;) {
106
+ const buf = Buffer.allocUnsafe(Math.min(1 << 20, max + 1 - total));
107
+ const { bytesRead } = await fh.read(buf, 0, buf.length, null);
108
+ if (bytesRead === 0)
109
+ return { bytes: Buffer.concat(chunks) };
110
+ chunks.push(buf.subarray(0, bytesRead));
111
+ total += bytesRead;
112
+ if (total > max)
113
+ return { over: true };
114
+ }
115
+ }
116
+ finally {
117
+ await fh.close();
118
+ }
119
+ }
120
+ tmp = (abs, m, p) => join(dirname(abs), `.${basename(abs)}.piroboros-tmp-${m}-${p}`);
121
+ old = (abs, m, p) => join(dirname(abs), `.${basename(abs)}.piroboros-old-${m}-${p}`);
122
+ async absent(path) {
123
+ try {
124
+ await this.d.fs.lstat(path);
125
+ }
126
+ catch (error) {
127
+ if (code(error) === "ENOENT")
128
+ return;
129
+ throw error;
130
+ }
131
+ throw eexist(path);
132
+ }
133
+ /** The on-disk name of a live path: on a case-insensitive folder each component takes the case the folder holds. */
134
+ async name(project, rel, caseless) {
135
+ let cur = project;
136
+ for (const part of slash(rel)) {
137
+ let hit = part;
138
+ if (caseless) {
139
+ const names = await this.listing(cur);
140
+ hit = names.find((n) => n === part) ?? names.find((n) => n.toLowerCase() === part.toLowerCase()) ?? part;
141
+ }
142
+ cur = join(cur, hit);
143
+ }
144
+ return cur;
145
+ }
146
+ /** The name a row's path takes: for a rename's destination the row's own spelling of the last component, so a case-only rename changes the case. */
147
+ async target(project, row, caseless) {
148
+ const abs = await this.name(project, row.path, caseless);
149
+ return row.op === "rename" ? join(dirname(abs), basename(row.path)) : abs;
150
+ }
151
+ async listing(dir) {
152
+ let names = this.listings.get(dir);
153
+ if (names === undefined) {
154
+ try {
155
+ names = await this.d.fs.readdir(dir);
156
+ }
157
+ catch (error) {
158
+ if (code(error) !== "ENOENT" && code(error) !== "ENOTDIR")
159
+ throw error;
160
+ names = [];
161
+ }
162
+ this.listings.set(dir, names);
163
+ }
164
+ return names;
165
+ }
166
+ /** Exact-name presence from a fresh listing: on a case-insensitive folder `A` and `B` alias, so existence tests cannot be used. */
167
+ async exact(abs) {
168
+ try {
169
+ return (await this.d.fs.readdir(dirname(abs))).includes(basename(abs));
170
+ }
171
+ catch (error) {
172
+ if (code(error) === "ENOENT" || code(error) === "ENOTDIR")
173
+ return false;
174
+ throw error;
175
+ }
176
+ }
177
+ /** Whether hard links work on the volume of `dir`: one attempt, outside the retry wrapper, per volume and pass. */
178
+ async canLink(dir, m, p) {
179
+ const dev = String((await this.d.fs.lstat(dir, { bigint: true })).dev);
180
+ const known = this.linkable.get(dev);
181
+ if (known !== undefined)
182
+ return known;
183
+ const probe = join(dir, `.piroboros-tmp-${m}-${p}-probe`);
184
+ let ok = true;
185
+ try {
186
+ await (await this.d.fs.open(probe, "wx")).close();
187
+ try {
188
+ await this.d.fs.link(probe, `${probe}-link`);
189
+ }
190
+ catch {
191
+ ok = false;
192
+ }
193
+ }
194
+ finally {
195
+ await this.d.fs.unlink(`${probe}-link`).catch(() => undefined);
196
+ await this.d.fs.unlink(probe).catch(() => undefined);
197
+ }
198
+ this.linkable.set(dev, ok);
199
+ return ok;
200
+ }
201
+ /** Put a staged file at a name that must be absent: link then unlink, or lstat then rename on a volume without links. */
202
+ async place(src, dst, m, p, lines) {
203
+ this.listings.delete(dirname(dst));
204
+ if (await this.canLink(dirname(dst), m, p)) {
205
+ await this.retry(dst, () => this.d.fs.link(src, dst));
206
+ try {
207
+ await this.retry(src, () => this.d.fs.unlink(src));
208
+ }
209
+ catch (error) {
210
+ lines.push(`left behind: ${src} (${message(error)})`);
211
+ }
212
+ }
213
+ else {
214
+ await this.absent(dst);
215
+ await this.retry(dst, () => this.d.fs.rename(src, dst));
216
+ }
217
+ }
218
+ /** Write bytes to a new name (exclusive create, the file's mode, fsync) and check their hash. */
219
+ async stageBytes(tmp, bytes, mode, hash) {
220
+ const fh = await this.d.fs.open(tmp, "wx", mode ?? 0o644);
221
+ try {
222
+ await fh.writeFile(bytes);
223
+ await fh.datasync();
224
+ }
225
+ finally {
226
+ await fh.close();
227
+ }
228
+ if (await this.hashFile(tmp) !== hash)
229
+ throw new Error(`${tmp} does not hold the bytes it was written with`);
230
+ }
231
+ async stageCopy(src, tmp, mode, hash) {
232
+ const from = await this.d.fs.open(src, "r");
233
+ let to;
234
+ try {
235
+ to = await this.d.fs.open(tmp, "wx", mode ?? 0o644);
236
+ const buf = Buffer.allocUnsafe(1 << 20);
237
+ const h = createHash("sha256");
238
+ for (;;) {
239
+ const { bytesRead } = await from.read(buf, 0, buf.length, null);
240
+ if (bytesRead === 0)
241
+ break;
242
+ h.update(buf.subarray(0, bytesRead));
243
+ await to.write(buf, 0, bytesRead);
244
+ }
245
+ await to.datasync();
246
+ if (h.digest("hex") !== hash)
247
+ throw new Error(`${src} changed while it was staged`);
248
+ }
249
+ finally {
250
+ await from.close();
251
+ await to?.close();
252
+ }
253
+ }
254
+ /* --- the merge -------------------------------------------------------------------------------------------- */
255
+ /** Pre-flight and snapshot, the record, staging, the apply and the finish. Throws HoldError or ConflictFound before any record exists. */
256
+ async merge(input) {
257
+ this.startPass();
258
+ const prepared = await this.prepare(input);
259
+ const { id } = prepared;
260
+ const rows = prepared.rows;
261
+ const lines = [];
262
+ const olds = [];
263
+ const cancelled = (reason) => this.rollback(id, input, reason, lines);
264
+ // Stage: nothing live is replaced yet.
265
+ try {
266
+ const missing = this.d.cas.missing(rows.flatMap((r) => (r.pre === null ? [] : [r.pre])));
267
+ if (missing.length > 0)
268
+ return await cancelled(`the snapshot lacks ${missing.length} object${missing.length === 1 ? "" : "s"}`);
269
+ for (const row of rows.filter((r) => r.op === "mkdir")) {
270
+ const abs = await this.name(input.project, row.path, input.caseless);
271
+ await this.d.fs.mkdir(abs);
272
+ this.listings.delete(dirname(abs));
273
+ }
274
+ for (const row of rows.filter((r) => r.post !== null && r.op !== "mkdir")) {
275
+ const abs = await this.target(input.project, row, input.caseless);
276
+ if (row.body !== undefined)
277
+ await this.stageBytes(this.tmp(abs, id, 0), row.body, row.mode, row.post);
278
+ else
279
+ await this.stageCopy(join(input.folder, ...slash(row.path)), this.tmp(abs, id, 0), row.mode, row.post);
280
+ }
281
+ for (const row of rows.filter((r) => r.op !== "mkdir"))
282
+ await this.canLink(dirname(await this.name(input.project, row.path, input.caseless)), id, 0);
283
+ }
284
+ catch (error) {
285
+ return cancelled(`staging failed: ${message(error)}`);
286
+ }
287
+ this.db.prepare("UPDATE merges SET state = 'writing' WHERE id = ?").run(id);
288
+ // Apply in seq order: a delete or rename group, then writes and creates; mkdir rows were made at staging.
289
+ try {
290
+ for (const row of rows.filter((r) => r.op !== "mkdir")) {
291
+ if (row.op === "rename") {
292
+ const a = await this.name(input.project, row.from, input.caseless);
293
+ const b = await this.target(input.project, row, input.caseless);
294
+ await this.displace(a, row.pre, id, olds, lines);
295
+ this.listings.delete(dirname(a));
296
+ await this.place(this.tmp(b, id, 0), b, id, 0, lines);
297
+ continue;
298
+ }
299
+ const abs = await this.target(input.project, row, input.caseless);
300
+ if (row.pre !== null)
301
+ await this.displace(abs, row.pre, id, olds, lines);
302
+ if (row.post !== null)
303
+ await this.place(this.tmp(abs, id, 0), abs, id, 0, lines);
304
+ }
305
+ // Finish: an old file that changed since it was displaced held a write by a program that kept it open.
306
+ for (const o of olds) {
307
+ if (await this.live(o.old).then((s) => s.kind !== "file" || s.hash !== o.hash))
308
+ lines.push(`your edit during the merge is saved at ${o.old}`);
309
+ }
310
+ }
311
+ catch (error) {
312
+ return cancelled(message(error));
313
+ }
314
+ const summary = () => [input.head, ...lines].join("\n");
315
+ for (let attempt = 0;; attempt += 1) {
316
+ try {
317
+ this.d.cas.tx(() => {
318
+ this.db.prepare("UPDATE merges SET state = 'done', summary = ? WHERE id = ?").run(summary(), id);
319
+ this.db.prepare("UPDATE workspaces SET state = 'merged', hold = NULL, hold_detail = NULL WHERE id = ?").run(input.ws);
320
+ });
321
+ break;
322
+ }
323
+ catch (error) {
324
+ if (attempt >= 2)
325
+ return cancelled(`the merge record could not be finished: ${message(error)}`);
326
+ await (this.d.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(1_000);
327
+ }
328
+ }
329
+ let clean = true;
330
+ await this.cleanup(id, input.project, input.caseless, new Map(), true, lines).catch((error) => { clean = false; lines.push(`cleanup: ${message(error)}`); });
331
+ await this.d.removeFolder(input.folder).catch((error) => { clean = false; lines.push(`the Workspace folder could not be removed: ${message(error)}`); });
332
+ if (clean)
333
+ try {
334
+ this.db.prepare("UPDATE merges SET cleaned = 1 WHERE id = ?").run(id);
335
+ }
336
+ catch { /* recover cleans up again */ }
337
+ return { id, state: "done", summary: summary() };
338
+ }
339
+ /** Move a live path aside and check it is what the plan saw; put it back and stop when it is not. */
340
+ async displace(abs, expect, m, olds, lines) {
341
+ const old = this.old(abs, m, 0);
342
+ await this.absent(old);
343
+ try {
344
+ await this.retry(abs, () => this.d.fs.rename(abs, old));
345
+ }
346
+ catch (error) {
347
+ if (code(error) === "ENOENT")
348
+ throw new Error(`${abs} is gone: the live file changed during the merge`);
349
+ throw error;
350
+ }
351
+ this.listings.delete(dirname(abs));
352
+ const hash = await this.hashFile(old);
353
+ if (hash !== expect) {
354
+ try {
355
+ await this.place(old, abs, m, 0, lines);
356
+ }
357
+ catch (error) {
358
+ if (code(error) === "EEXIST")
359
+ lines.push(`kept: ${old} (your newer version of ${abs}; a file exists at that name now)`);
360
+ else
361
+ throw error;
362
+ }
363
+ throw new Error(`${abs} changed during the merge and was put back`);
364
+ }
365
+ olds.push({ abs, old, hash });
366
+ }
367
+ /** Step 1: checks, free space, the bounded snapshot reads, then the record by the loop that keeps every await outside the transaction. */
368
+ async prepare(input) {
369
+ const canonicalProject = canonicalize(input.project);
370
+ let rows = [...input.rows];
371
+ const hold = (reason) => new HoldError("preflight", reason);
372
+ // Path checks and the lock probe for every row that touches an existing live file.
373
+ for (const row of rows.filter((r) => r.op !== "mkdir")) {
374
+ const abs = await this.name(input.project, row.path, input.caseless);
375
+ await this.checkParents(input.project, canonicalProject, abs, row.path);
376
+ if (row.pre !== null) {
377
+ try {
378
+ await (await this.d.fs.open(abs, "r+")).close();
379
+ }
380
+ catch (error) {
381
+ if (code(error) !== "ENOENT")
382
+ throw hold(`${row.path} cannot be opened for writing (${message(error)})`);
383
+ }
384
+ }
385
+ }
386
+ await this.freeSpace(input, rows);
387
+ // Snapshot: each pre is read through one handle, at most SNAPSHOT_MAX + 1 bytes, and must hash to what the plan saw.
388
+ const packed = [];
389
+ let held = 0;
390
+ const flush = () => { if (packed.length > 0) {
391
+ const batch = packed.splice(0);
392
+ this.d.cas.tx(() => this.d.cas.insert(batch));
393
+ } held = 0; };
394
+ const modes = new Map();
395
+ for (let k = 0; k < rows.length; k += 1) {
396
+ for (let attempt = 0;; attempt += 1) {
397
+ const row = rows[k];
398
+ const abs = row.op === "mkdir" ? "" : await this.name(input.project, row.op === "rename" ? row.from : row.path, input.caseless);
399
+ if (row.op === "mkdir")
400
+ break;
401
+ let bytes;
402
+ try {
403
+ const r = await this.readBounded(abs, SNAPSHOT_MAX);
404
+ if ("over" in r)
405
+ throw new HoldError("oversize", row.path);
406
+ bytes = r.bytes;
407
+ }
408
+ catch (error) {
409
+ if (error instanceof HoldError)
410
+ throw error;
411
+ if (code(error) !== "ENOENT")
412
+ throw hold(`${row.path}: ${message(error)}`);
413
+ bytes = null;
414
+ }
415
+ const hash = bytes === null ? null : sha(bytes);
416
+ if (hash === row.pre) {
417
+ if (bytes !== null) {
418
+ if (held + bytes.length > BATCH_BYTES)
419
+ flush();
420
+ packed.push(pack(bytes));
421
+ held += bytes.length;
422
+ if (packed.length >= OPEN_BATCH)
423
+ flush();
424
+ const mode = await this.d.fs.lstat(abs).then((s) => s.mode & 0o777).catch(() => null);
425
+ if (mode !== null)
426
+ modes.set(row.seq, mode);
427
+ }
428
+ break;
429
+ }
430
+ // The live file changed after the plan: decide this path again, once, with the bytes just read.
431
+ if (attempt > 0)
432
+ throw hold(`${row.path} kept changing during the merge`);
433
+ const again = await input.redecide(row, bytes);
434
+ if (again === "conflict")
435
+ throw new ConflictFound(row.path);
436
+ if (again === "oversize")
437
+ throw new HoldError("oversize", row.path);
438
+ if (again === "drop") {
439
+ rows = rows.filter((r) => r !== row);
440
+ k -= 1;
441
+ break;
442
+ }
443
+ rows[k] = again.row;
444
+ }
445
+ }
446
+ flush();
447
+ rows = rows.map((r) => (modes.has(r.seq) ? { ...r, mode: modes.get(r.seq) } : r));
448
+ // The record loop: every await outside the transaction, at most three tries.
449
+ const pres = rows.flatMap((r) => (r.pre === null || r.op === "mkdir" ? [] : [r.pre]));
450
+ for (let attempt = 0; attempt < 3; attempt += 1) {
451
+ const lost = this.d.cas.missing(pres);
452
+ for (const hash of lost) {
453
+ const row = rows.find((r) => r.pre === hash);
454
+ const abs = await this.name(input.project, row.op === "rename" ? row.from : row.path, input.caseless);
455
+ const r = await this.readBounded(abs, SNAPSHOT_MAX).catch(() => undefined);
456
+ if (r === undefined || "over" in r || sha(r.bytes) !== hash)
457
+ throw hold(`${row.path} changed during the merge`);
458
+ this.d.cas.put(r.bytes);
459
+ }
460
+ const id = this.d.cas.tx(() => {
461
+ if (this.d.cas.missing(pres).length > 0)
462
+ return undefined;
463
+ const m = Number(this.db.prepare("INSERT INTO merges(workspace, run, project, state, at, pass) VALUES (?, ?, ?, 'planned', ?, 0)").run(input.ws, input.run, input.project, this.d.now()).lastInsertRowid);
464
+ const stmt = this.db.prepare("INSERT INTO merge_paths VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
465
+ for (const r of rows)
466
+ stmt.run(m, r.seq, r.path, r.from, r.op, r.pre, r.post, r.mode);
467
+ return m;
468
+ });
469
+ if (id !== undefined)
470
+ return { id, rows };
471
+ }
472
+ throw hold("the store kept dropping snapshot objects; /conclave merge tries again");
473
+ }
474
+ async checkParents(project, canonicalProject, abs, rel) {
475
+ let cur = project;
476
+ for (const part of dirname(abs).slice(project.length).split(/[\\/]/u).filter((s) => s !== "")) {
477
+ cur = join(cur, part);
478
+ let info;
479
+ try {
480
+ info = await this.d.fs.lstat(cur);
481
+ }
482
+ catch (error) {
483
+ if (code(error) === "ENOENT")
484
+ break;
485
+ throw error;
486
+ }
487
+ if (info.isSymbolicLink())
488
+ throw new HoldError("preflight", `${rel}: a link lies in its path`);
489
+ if (!info.isDirectory())
490
+ throw new HoldError("preflight", `${rel}: a parent is not a folder`);
491
+ }
492
+ if (!isInside(canonicalProject, canonicalize(abs)))
493
+ throw new HoldError("preflight", `${rel} resolves outside the project`);
494
+ if (!this.d.allowed(abs))
495
+ throw new HoldError("preflight", `${rel} is protected`);
496
+ }
497
+ /** Per volume: the tmp of every row, the rollback tmp of a displaced one, and the snapshot in the store, plus a margin. */
498
+ async freeSpace(input, rows) {
499
+ const need = new Map();
500
+ const volume = async (path) => {
501
+ let dir = dirname(path);
502
+ for (;;) {
503
+ try {
504
+ return { dev: String((await this.d.fs.lstat(dir, { bigint: true })).dev), dir };
505
+ }
506
+ catch (error) {
507
+ if (code(error) !== "ENOENT" || dirname(dir) === dir)
508
+ throw error;
509
+ dir = dirname(dir);
510
+ }
511
+ }
512
+ };
513
+ const add = (dev, dir, bytes) => { need.set(dev, { dir: need.get(dev)?.dir ?? dir, bytes: (need.get(dev)?.bytes ?? 0) + bytes }); };
514
+ for (const row of rows.filter((r) => r.op !== "mkdir")) {
515
+ const v = await volume(await this.name(input.project, row.path, input.caseless));
516
+ add(v.dev, v.dir, (row.postSize ?? 0) + (row.pre !== null ? row.preSize ?? 0 : 0));
517
+ }
518
+ const stored = new Set(this.d.cas.missing(rows.flatMap((r) => (r.pre === null ? [] : [r.pre]))));
519
+ const raw = rows.filter((r) => r.pre !== null && stored.has(r.pre)).reduce((sum, r) => sum + (r.preSize ?? 0), 0);
520
+ const s = await volume(join(this.d.storeDir, "x"));
521
+ add(s.dev, s.dir, raw);
522
+ for (const v of need.values()) {
523
+ let free;
524
+ try {
525
+ const st = await this.d.fs.statfs(v.dir);
526
+ free = Number(st.bavail) * Number(st.bsize);
527
+ }
528
+ catch (error) {
529
+ this.d.notice(`free space on ${v.dir} could not be read (${message(error)}); the merge goes on`);
530
+ continue;
531
+ }
532
+ if (free < v.bytes + MARGIN)
533
+ throw new HoldError("preflight", `not enough free space on the volume of ${v.dir}: needs ${v.bytes + MARGIN}, has ${free}`);
534
+ }
535
+ }
536
+ /* --- the reverse rule ------------------------------------------------------------------------------------- */
537
+ rowsOf(id) {
538
+ return this.db.prepare("SELECT seq, path, from_path AS \"from\", op, pre, post, mode FROM merge_paths WHERE merge = ? ORDER BY seq DESC").all(id);
539
+ }
540
+ nextPass(id) {
541
+ return this.d.cas.tx(() => {
542
+ this.db.prepare("UPDATE merges SET pass = pass + 1 WHERE id = ?").run(id);
543
+ return Number(this.db.prepare("SELECT pass FROM merges WHERE id = ?").get(id).pass);
544
+ });
545
+ }
546
+ /** What a reverse pass would do to one row, and why not when it would do nothing. */
547
+ async classify(row, project, caseless) {
548
+ const abs = await this.target(project, row, caseless);
549
+ const from = row.from === null ? undefined : join(dirname(await this.name(project, row.from, caseless)), basename(row.from));
550
+ const target = from ?? abs;
551
+ if (!this.d.allowed(abs) || (from !== undefined && !this.d.allowed(from)))
552
+ return { verdict: "protected", reason: "the path is protected", abs, ...(from === undefined ? {} : { from }) };
553
+ const out = (verdict, reason, fromAbsent) => ({ verdict, ...(reason === undefined ? {} : { reason }), abs, ...(from === undefined ? {} : { from }), ...(fromAbsent ? { fromAbsent } : {}) });
554
+ const at = async (p) => ((await this.exact(p)) || !caseless ? this.live(p) : { kind: "absent" });
555
+ switch (row.op) {
556
+ case "mkdir": {
557
+ const s = await this.live(abs);
558
+ return s.kind === "absent" ? out("unchanged") : s.kind === "dir" ? out("act") : out("changed", "a file is at the folder's path");
559
+ }
560
+ case "create": {
561
+ const s = await this.live(abs);
562
+ if (s.kind === "absent")
563
+ return out("unchanged");
564
+ return s.kind === "file" && s.hash === row.post ? out("act") : out("changed", "the live file holds other bytes");
565
+ }
566
+ case "delete": {
567
+ const s = await this.live(abs);
568
+ if (s.kind === "file" && s.hash === row.pre)
569
+ return out("unchanged");
570
+ return s.kind === "absent" ? out("act", undefined, true) : out("changed", "the live path holds other bytes");
571
+ }
572
+ case "write": {
573
+ const s = await this.live(abs);
574
+ if (s.kind === "file" && s.hash === row.pre)
575
+ return out("unchanged");
576
+ if (s.kind === "absent")
577
+ return out("act", undefined, true);
578
+ return s.kind === "file" && s.hash === row.post ? out("act") : out("changed", "the live file holds other bytes");
579
+ }
580
+ case "rename": {
581
+ const a = await at(target);
582
+ const b = await at(abs);
583
+ if (a.kind === "file" && a.hash === row.pre && b.kind === "absent")
584
+ return out("unchanged");
585
+ if (a.kind === "absent" && (b.kind === "absent" || (b.kind === "file" && b.hash === row.post)))
586
+ return out("act", undefined, a.kind === "absent" && b.kind === "absent");
587
+ return out("changed", "the live path holds other bytes");
588
+ }
589
+ }
590
+ }
591
+ /** What an undo would do, row by row (descending seq), without touching anything. */
592
+ async preview(id, project, caseless) {
593
+ this.startPass();
594
+ const out = [];
595
+ for (const row of this.rowsOf(id)) {
596
+ const c = await this.classify(row, project, caseless);
597
+ out.push({ row, verdict: c.verdict === "act" ? (row.op === "create" || row.op === "mkdir" ? "remove" : "restore") : c.verdict, ...(c.reason === undefined ? {} : { reason: c.reason }) });
598
+ }
599
+ return out;
600
+ }
601
+ /** Take a live file in its post state aside, check it, and put it back when it is not what the merge wrote. */
602
+ async removeLive(abs, post, m, p, lines) {
603
+ const old = this.old(abs, m, p);
604
+ await this.absent(old);
605
+ await this.retry(abs, () => this.d.fs.rename(abs, old));
606
+ this.listings.delete(dirname(abs));
607
+ if (post !== null && await this.hashFile(old) === post) {
608
+ // The merge's own output: nothing is lost by deleting it, and a folder it sat in can be removed in this pass.
609
+ await this.retry(old, () => this.d.fs.unlink(old)).catch(() => undefined);
610
+ return true;
611
+ }
612
+ try {
613
+ await this.place(old, abs, m, p, lines);
614
+ }
615
+ catch (error) {
616
+ if (code(error) !== "EEXIST")
617
+ throw error;
618
+ lines.push(`kept: ${old} (bytes that are not the merge's output; a file exists at ${abs})`);
619
+ }
620
+ return false;
621
+ }
622
+ async placePre(abs, row, m, p, lines) {
623
+ const bytes = this.d.cas.get(row.pre);
624
+ if (bytes === undefined)
625
+ throw new Error("the snapshot object is missing from the store");
626
+ const tmp = this.tmp(abs, m, p);
627
+ await this.stageBytes(tmp, bytes, row.mode, row.pre);
628
+ await this.place(tmp, abs, m, p, lines);
629
+ }
630
+ /** One reverse pass: `pass` is incremented first, rows run in descending seq, and a failing row never stops the next. */
631
+ async reverse(id, project, caseless) {
632
+ const pass = this.nextPass(id);
633
+ this.startPass();
634
+ const results = [];
635
+ const lines = [];
636
+ for (const row of this.rowsOf(id)) {
637
+ const result = { seq: row.seq, path: row.path, outcome: "failed" };
638
+ results.push(result);
639
+ try {
640
+ const c = await this.classify(row, project, caseless);
641
+ if (c.verdict === "unchanged") {
642
+ result.outcome = "unchanged";
643
+ continue;
644
+ }
645
+ if (c.verdict !== "act") {
646
+ result.outcome = c.verdict;
647
+ result.reason = c.reason;
648
+ continue;
649
+ }
650
+ if (c.fromAbsent)
651
+ result.fromAbsent = true;
652
+ if (row.op === "mkdir") {
653
+ try {
654
+ // The merge's own staged tmp files do not keep the folder it made.
655
+ for (const name of await this.d.fs.readdir(c.abs).catch(() => []))
656
+ if (name.includes(`.piroboros-tmp-${id}-`))
657
+ await this.d.fs.unlink(join(c.abs, name)).catch(() => undefined);
658
+ await this.retry(c.abs, () => this.d.fs.rmdir(c.abs));
659
+ result.outcome = "removed";
660
+ }
661
+ catch (error) {
662
+ if (code(error) === "ENOTEMPTY" || code(error) === "EEXIST") {
663
+ result.outcome = "kept";
664
+ result.reason = "kept: folder not empty";
665
+ }
666
+ else
667
+ throw error;
668
+ }
669
+ this.listings.delete(dirname(c.abs));
670
+ }
671
+ else if (row.op === "create") {
672
+ result.outcome = (await this.removeLive(c.abs, row.post, id, pass, lines)) ? "removed" : "changed";
673
+ if (result.outcome === "changed")
674
+ result.reason = "the live file changed while it was being removed";
675
+ }
676
+ else if (row.op === "rename") {
677
+ if (await this.exact(c.abs) && !(await this.removeLive(c.abs, row.post, id, pass, lines))) {
678
+ result.outcome = "changed";
679
+ result.reason = "the live file changed while it was being removed";
680
+ continue;
681
+ }
682
+ await this.placePre(c.from, row, id, pass, lines);
683
+ result.outcome = "restored";
684
+ }
685
+ else {
686
+ if ((await this.live(c.abs)).kind === "file" && !(await this.removeLive(c.abs, row.post, id, pass, lines))) {
687
+ result.outcome = "changed";
688
+ result.reason = "the live file changed while it was being removed";
689
+ continue;
690
+ }
691
+ if (row.op === "delete" || row.op === "write")
692
+ await this.placePre(c.abs, row, id, pass, lines);
693
+ result.outcome = "restored";
694
+ }
695
+ }
696
+ catch (error) {
697
+ result.outcome = "failed";
698
+ result.reason = message(error);
699
+ }
700
+ }
701
+ return { results, lines };
702
+ }
703
+ /** Delete the record's tmp files, and its old files whose bytes the snapshot or the merge's output still holds; keep and list the rest. */
704
+ async cleanup(id, project, caseless, ended, done, lines) {
705
+ const rows = this.rowsOf(id);
706
+ const folders = new Set();
707
+ for (const row of rows) {
708
+ for (const rel of row.op === "mkdir" ? [row.path] : row.op === "rename" ? [row.path, row.from] : [row.path]) {
709
+ folders.add(row.op === "mkdir" ? await this.name(project, rel, caseless) : dirname(await this.name(project, rel, caseless)));
710
+ }
711
+ }
712
+ const tmpRe = new RegExp(`\\.piroboros-tmp-${id}-`, "u");
713
+ const oldRe = new RegExp(`^\\.(.+)\\.piroboros-old-${id}-\\d+$`, "u");
714
+ for (const dir of folders) {
715
+ let names;
716
+ try {
717
+ names = await this.d.fs.readdir(dir);
718
+ }
719
+ catch {
720
+ continue;
721
+ }
722
+ for (const name of names) {
723
+ const abs = join(dir, name);
724
+ if (tmpRe.test(name)) {
725
+ await this.retry(abs, () => this.d.fs.unlink(abs)).catch((error) => lines.push(`left behind: ${abs} (${message(error)})`));
726
+ continue;
727
+ }
728
+ const match = oldRe.exec(name);
729
+ if (match === null)
730
+ continue;
731
+ const row = rows.find((r) => [r.path, r.from].some((p) => p !== null && basename(p).toLowerCase() === match[1].toLowerCase()));
732
+ const hash = await this.live(abs).then((s) => (s.kind === "file" ? s.hash : undefined)).catch(() => undefined);
733
+ const outcome = row === undefined ? undefined : ended.get(row.seq);
734
+ const safe = hash !== undefined && row !== undefined && (hash === row.pre || hash === row.post) && (done || outcome === "unchanged" || outcome === "restored" || outcome === "removed");
735
+ if (safe)
736
+ await this.retry(abs, () => this.d.fs.unlink(abs)).catch((error) => lines.push(`left behind: ${abs} (${message(error)})`));
737
+ else
738
+ lines.push(`kept: ${abs} (${row === undefined ? "no row names it" : `it holds bytes neither the snapshot nor the merge wrote, or row ${row.path} did not end restored`})`);
739
+ }
740
+ }
741
+ }
742
+ ends(results) {
743
+ return { failed: results.filter((r) => ["changed", "protected", "failed"].includes(r.outcome)), map: new Map(results.map((r) => [r.seq, r.outcome])) };
744
+ }
745
+ report(results) {
746
+ return results.flatMap((r) => (r.outcome === "unchanged" ? [] : [`${r.outcome}: ${r.path}${r.reason === undefined ? "" : ` (${r.reason})`}${r.fromAbsent ? " (restored from absent)" : ""}`]));
747
+ }
748
+ /** In-process rollback after a stop in steps 2 to 5; ends the record and holds the Workspace in one transaction. */
749
+ async rollback(id, input, reason, lines) {
750
+ let pass;
751
+ try {
752
+ pass = await this.reverse(id, input.project, input.caseless);
753
+ }
754
+ catch (error) {
755
+ return { id, state: "pending", summary: `merge ${id} stopped (${reason}) and its rollback did not start: ${message(error)}` };
756
+ }
757
+ const { failed, map } = this.ends(pass.results);
758
+ await this.cleanup(id, input.project, input.caseless, map, false, pass.lines);
759
+ const state = failed.length === 0 ? "rolled back" : "rollback failed";
760
+ const summary = [`merge ${id} stopped: ${reason}`, state === "rolled back" ? "Everything was put back." : `${failed.length} path${failed.length === 1 ? "" : "s"} could not be restored:`, ...this.report(pass.results), ...pass.lines, ...lines].join("\n");
761
+ try {
762
+ this.d.cas.tx(() => {
763
+ this.db.prepare("UPDATE merges SET state = ?, summary = ? WHERE id = ?").run(state, summary, id);
764
+ this.db.prepare("UPDATE workspaces SET state = 'held', hold = 'rollback', hold_detail = ? WHERE id = ?").run(String(id), input.ws);
765
+ });
766
+ }
767
+ catch (error) {
768
+ return { id, state: "pending", summary: `merge ${id} stopped (${reason}); its rollback ran but could not be recorded: ${message(error)}` };
769
+ }
770
+ return { id, state, summary };
771
+ }
772
+ /* --- recovery and undo ------------------------------------------------------------------------------------ */
773
+ /**
774
+ * At startup, before the scheduler: a `planned` or `writing` record is rolled back, a `done` one is cleaned up and its
775
+ * Workspace folder removed, an `undoing` one is run again. Returns one line per record.
776
+ */
777
+ async recover() {
778
+ const out = [];
779
+ const records = this.db.prepare("SELECT m.id, m.state, m.workspace AS ws, m.project, w.folder, w.live_caseless AS caseless FROM merges m LEFT JOIN workspaces w ON w.id = m.workspace WHERE m.state IN ('planned', 'writing', 'undoing') OR (m.state = 'done' AND m.cleaned IS NULL) ORDER BY m.id").all();
780
+ for (const r of records) {
781
+ const caseless = r.caseless === 1;
782
+ try {
783
+ if (r.state === "done") {
784
+ const lines = [];
785
+ await this.cleanup(r.id, r.project, caseless, new Map(), true, lines);
786
+ if (r.folder !== null)
787
+ await this.d.removeFolder(r.folder);
788
+ this.db.prepare("UPDATE merges SET cleaned = 1 WHERE id = ?").run(r.id);
789
+ out.push(`merge ${r.id}: finished cleaning up${lines.length === 0 ? "" : `; ${lines.join("; ")}`}`);
790
+ }
791
+ else if (r.state === "undoing") {
792
+ const res = await this.finishUndo(r.id, r.project, caseless);
793
+ out.push(`undo of merge ${r.id}: ${res.state}`);
794
+ }
795
+ else {
796
+ const res = await this.rollback(r.id, { ws: r.ws, project: r.project, caseless }, "the merge was interrupted", []);
797
+ out.push(`merge ${r.id} was interrupted and is ${res.state}`);
798
+ }
799
+ }
800
+ catch (error) {
801
+ out.push(`merge record ${r.id} was not recovered: ${message(error)}`);
802
+ }
803
+ }
804
+ return out;
805
+ }
806
+ /** `/conclave undo` over the newest record of a project: one reverse pass, the cleanup, and the end state. */
807
+ async finishUndo(id, project, caseless) {
808
+ this.db.prepare("UPDATE merges SET state = 'undoing' WHERE id = ?").run(id);
809
+ const pass = await this.reverse(id, project, caseless);
810
+ const { failed, map } = this.ends(pass.results);
811
+ await this.cleanup(id, project, caseless, map, false, pass.lines);
812
+ const state = failed.length === 0 ? "undone" : "undo failed";
813
+ this.db.prepare("UPDATE merges SET state = ? WHERE id = ?").run(state, id);
814
+ const text = [state === "undone" ? "Undo finished." : `Undo finished with ${failed.length} path${failed.length === 1 ? "" : "s"} skipped or failed; /conclave undo runs it again over every row.`, ...this.report(pass.results), ...pass.lines].join("\n");
815
+ return { state, text };
816
+ }
817
+ }