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,1596 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
+ import { checkPath, checkRead, WIDE_SECRET } from "../guard.js";
6
+ import { canonicalize, isInside, samePath } from "../paths.js";
7
+ import { ConflictFound, HoldError, realFs, Writer } from "./apply.js";
8
+ import { confineFor, nativeDeps } from "./confine.js";
9
+ import { dockerRemove, dockerSweep } from "./docker.js";
10
+ import { wslRemove, wslSweep } from "./wsl.js";
11
+ import { BATCH_BYTES, Cas, OPEN_BATCH, pack, SNAPSHOT_MAX } from "./cas.js";
12
+ import { HostGit, WsRefusal } from "./git.js";
13
+ import { lwwMatch, lwwRules } from "./lww.js";
14
+ import { decide, hasBlock, TEXT_MAX } from "./merge.js";
15
+ // Workspaces for Vesperia: one private copy of the git-visible files of a project per run, checkpointed into the CAS, merged
16
+ // back three-way when her run ends `done`. The merge writes through ./apply.ts. Unconfined in P27d1: the Workspace keeps her
17
+ // away from the live folder by convention and the start notice says so. P27e1 adds bubblewrap on Linux (./confine.ts).
18
+ export { WsRefusal } from "./git.js";
19
+ export const LINK_NAMES = ["node_modules"];
20
+ export const FILE_BOUND = 25_000;
21
+ export const BYTE_BOUND = 2 * 1024 ** 3;
22
+ export const BULK_DELETE = 20;
23
+ const SHELL_ACTIVE = [/\.lnk$/iu, /\.url$/iu, /\.scf$/iu, /^desktop\.ini$/iu, /^autorun\.inf$/iu, /\.library-ms$/iu, /\.searchConnector-ms$/iu];
24
+ const RESERVED = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/iu;
25
+ // ponytail: a scan walks every file; about 0.6 s at 25,000 files. fs.watch when a scan measures over 1 s.
26
+ const sha = (data) => createHash("sha256").update(data).digest("hex");
27
+ const posix = (p) => p.replaceAll("\\", "/");
28
+ const msg = (error) => (error instanceof Error ? error.message : String(error));
29
+ const code = (error) => error?.code;
30
+ /** Whether the Workspace is used from a WSL distro (bubblewrap there, or Docker through the runner): its place folders and line endings are prepared on Windows. */
31
+ const onWsl = (c) => c.wsl !== undefined || c.docker?.remote !== undefined;
32
+ /** What a `/conclave merge` prompt showed; the merge after the answer goes ahead only when its new plan shows the same. */
33
+ const shown = (p) => JSON.stringify([p.headMoved?.to ?? null, p.deletes >= BULK_DELETE, p.oversize.map((o) => o.path).sort(), p.conflicts.map((c) => `${c.kind} ${c.liveSize > SNAPSHOT_MAX} ${c.path}`).sort()]);
34
+ export const wsRootFor = (platform = process.platform, env = process.env) => platform === "win32" ? join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), "piroboros-ws")
35
+ : platform === "darwin" ? join(homedir(), "Library", "Application Support", "piroboros-ws")
36
+ : join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "piroboros-ws");
37
+ /** The text a hold shows, one per code. */
38
+ export function holdText(code, detail) {
39
+ const d = detail ?? "";
40
+ switch (code) {
41
+ case "verdict": return `Vesperia's run ended ${d}; /conclave merge applies her changes, /conclave discard drops them`;
42
+ case "cancelled": return "the run was cancelled";
43
+ case "conflicts": return `${d} conflicts`;
44
+ case "head-moved": {
45
+ const [a, b] = d.split(" ");
46
+ return `the live HEAD moved from ${a?.slice(0, 8)} to ${b?.slice(0, 8)} since the Workspace opened`;
47
+ }
48
+ case "bulk-delete": return `the merge would delete ${d} live files`;
49
+ case "oversize": return `${d.split("\n").length} of Vesperia's changes replace live files over 64 MiB, which cannot be snapshotted, so they are not merged: ${d.split("\n").join(", ")}; copy them yourself before /conclave merge, which removes the Workspace afterwards`;
50
+ case "preflight": return `the merge could not start at ${d}; nothing was changed`;
51
+ case "rollback": return `merge ${d} was rolled back`;
52
+ case "backend": return `confinement backend unavailable: ${d}`;
53
+ case "ignore-rules": return "the live ignore rules could not be read";
54
+ case "target-moved": return "the project folder is not the one the Workspace was opened for";
55
+ case "folder-missing": return "the Workspace folder is missing";
56
+ case "not-recovered": return `merge record ${d} was not recovered`;
57
+ case "parked": return "task parked by the restart limit";
58
+ case "ended": return `the run ended without closing its Workspace (${d})`;
59
+ default: return code === null ? "no hold" : `${code} ${d}`.trim();
60
+ }
61
+ }
62
+ const LIMITED = (items, max = 20) => (items.length > max ? [...items.slice(0, max), `and ${items.length - max} more`] : items);
63
+ export class Workspaces {
64
+ cas;
65
+ git;
66
+ writer;
67
+ wsRoot;
68
+ hash;
69
+ o;
70
+ fs;
71
+ now;
72
+ nextId;
73
+ byConv = new Map();
74
+ chains = new Map();
75
+ queued = new Set();
76
+ /** Workspaces whose confinement backend was found unavailable in this run, with the reason: no command spawns, and the run ends held with code `backend`. */
77
+ down = new Map();
78
+ chainKeys = new Map();
79
+ taskStatus;
80
+ constructor(options) {
81
+ this.o = options;
82
+ this.fs = options.fs ?? realFs;
83
+ this.now = options.now ?? Date.now;
84
+ this.taskStatus = options.taskStatus;
85
+ const dir = join(options.home, "ws");
86
+ mkdirSync(join(dir, "no-hooks"), { recursive: true });
87
+ this.cas = new Cas(join(dir, "store.sqlite"), this.now);
88
+ this.git = new HostGit(options.home, options.gitSpy);
89
+ this.hash = sha(canonicalize(options.home)).slice(0, 12);
90
+ this.wsRoot = options.wsRoot ?? wsRootFor(options.platform);
91
+ this.nextId = Number(this.cas.db.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM workspaces").get().m) + 1;
92
+ this.writer = new Writer({
93
+ cas: this.cas, fs: this.fs, storeDir: dir, now: this.now, notice: options.notice, removeFolder: (folder) => this.removeFolder(folder),
94
+ allowed: (abs) => checkPath(abs, undefined, options.guard(), true).allowed, ...(options.platform === undefined ? {} : { platform: options.platform }), ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
95
+ });
96
+ for (const row of this.rows("state IN ('open', 'held', 'conflicted')"))
97
+ if (row.conv !== null)
98
+ this.byConv.set(row.conv, row);
99
+ }
100
+ close() { this.cas.close(); }
101
+ /* --- rows --------------------------------------------------------------------------------------------------- */
102
+ rows(where, ...params) {
103
+ return this.cas.db.prepare(`SELECT * FROM workspaces WHERE ${where} ORDER BY created DESC, id DESC`).all(...params);
104
+ }
105
+ row(id) { return this.rows("id = ?", id)[0]; }
106
+ byKey(key) { return this.rows("key = ?", key)[0]; }
107
+ /** The newest Workspace of a project that is still in play. */
108
+ forProject(project) { return this.rows("project = ? AND state IN ('open', 'held', 'conflicted')", canonicalize(project))[0]; }
109
+ set(id, patch) {
110
+ const entries = Object.entries(patch);
111
+ this.cas.db.prepare(`UPDATE workspaces SET ${entries.map(([k]) => `${k} = ?`).join(", ")} WHERE id = ?`).run(...entries.map(([, v]) => v), id);
112
+ this.refresh(id);
113
+ }
114
+ /** Re-read a row into the conversation map (the writer changes some states in its own transactions). */
115
+ refresh(id) {
116
+ const row = this.row(id);
117
+ if (row?.conv != null) {
118
+ if (["open", "held", "conflicted"].includes(row.state))
119
+ this.byConv.set(row.conv, row);
120
+ else
121
+ this.byConv.delete(row.conv);
122
+ }
123
+ }
124
+ /** A hold removes the Workspace's container (best effort; the startup sweep finishes it). A parked task keeps it: `reopenParked` does not reopen through `open`. */
125
+ hold(id, code, detail = null, state = "held") {
126
+ this.set(id, { state, hold: code, hold_detail: detail });
127
+ const c = code === "parked" ? undefined : JSON.parse(this.row(id)?.confine ?? "{}").docker;
128
+ if (c !== undefined)
129
+ void dockerRemove(this.confineDeps(), c).catch(() => undefined);
130
+ }
131
+ /** The newest merge record of a Workspace for a run key. */
132
+ record(ws, run) {
133
+ return this.cas.db.prepare("SELECT id, state, summary FROM merges WHERE workspace = ? AND run = ? ORDER BY id DESC LIMIT 1").get(ws, run);
134
+ }
135
+ /** One promise chain per repository (or project folder), so an undo never runs during a merge of the same files. Each link catches. */
136
+ chain(key, fn) {
137
+ const run = (this.chains.get(key) ?? Promise.resolve()).then(fn);
138
+ this.chains.set(key, run.catch(() => undefined));
139
+ return run;
140
+ }
141
+ /** The chain key: the repository's top level when the project is inside one, else the project folder. */
142
+ async chainKey(project) {
143
+ let key = this.chainKeys.get(project);
144
+ if (key === undefined) {
145
+ key = project;
146
+ try {
147
+ const s = await this.git.state(project);
148
+ if (s.kind === "tree")
149
+ key = s.toplevel;
150
+ }
151
+ catch { /* the project folder is the key */ }
152
+ this.chainKeys.set(project, key);
153
+ }
154
+ return key;
155
+ }
156
+ chained(project, fn) { return this.chainKey(project).then((key) => this.chain(key, fn)); }
157
+ /* --- mode --------------------------------------------------------------------------------------------------- */
158
+ /**
159
+ * Fix the mode of a Vesperia run at approve: `git` (a Workspace with an allow-listed .git), `plain` (without .git) or `none`
160
+ * (in place). A nested project (a subfolder of a repository, a worktree or a submodule) takes the setting, the kept answer
161
+ * or one question through `ask`. A held Workspace of another mode refuses the approve.
162
+ */
163
+ async resolveMode(projectIn, ask) {
164
+ const project = canonicalize(projectIn);
165
+ const s = this.o.settings();
166
+ const held = this.rows("project = ? AND state IN ('held', 'conflicted')", project)[0];
167
+ let mode;
168
+ let from;
169
+ let setting;
170
+ let note;
171
+ try {
172
+ if (!s.enabled) {
173
+ mode = "none";
174
+ from = "workspace.enabled is false";
175
+ setting = "workspace.enabled";
176
+ }
177
+ else {
178
+ const state = await this.git.state(project);
179
+ if (state.kind === "none") {
180
+ mode = "plain";
181
+ from = "no git";
182
+ }
183
+ else {
184
+ const nested = !samePath(state.toplevel, project) || await this.fs.lstat(join(project, ".git")).then((i) => i.isFile()).catch(() => false);
185
+ if (!nested) {
186
+ mode = "git";
187
+ from = "not a nested project";
188
+ }
189
+ else if (s.nested === "copy") {
190
+ mode = "plain";
191
+ from = "the setting workspace.nested";
192
+ setting = "workspace.nested";
193
+ }
194
+ else if (s.nested === "inplace") {
195
+ mode = "none";
196
+ from = "the setting workspace.nested";
197
+ setting = "workspace.nested";
198
+ }
199
+ else {
200
+ const kept = this.cas.db.prepare("SELECT nested FROM projects WHERE project = ?").get(project);
201
+ if (kept !== undefined) {
202
+ mode = kept.nested === "inplace" ? "none" : "plain";
203
+ from = "your kept answer for this folder";
204
+ setting = "workspace.nested";
205
+ }
206
+ else if (held !== undefined) {
207
+ mode = held.mode;
208
+ from = "the held Workspace";
209
+ }
210
+ else {
211
+ if (ask === undefined)
212
+ return { ok: false, error: "this folder needs a one-time choice, which only the chat screen can ask; or set workspace.nested to copy or inplace" };
213
+ const what = state.kind === "tree" && samePath(state.toplevel, project) ? "a folder whose .git is a file (a worktree or a submodule)" : `a subfolder of the git repository ${state.toplevel}`;
214
+ const yes = await ask([
215
+ `${project} is ${what}.`,
216
+ "A Workspace here holds the folder's git-visible files without git: Vesperia's git commands see no repository, and her changes merge back as usual.",
217
+ "In place, Vesperia writes straight to your files as in 0.2.0: /conclave undo covers her write and edit calls, not bash, and her shell is not confined.",
218
+ "Your answer is kept for this folder; the setting workspace.nested overrides it.",
219
+ "Let Vesperia work in place, writing straight to your files?",
220
+ ].join("\n"));
221
+ mode = yes ? "none" : "plain";
222
+ from = "your answer";
223
+ this.cas.db.prepare("INSERT INTO projects VALUES (?, ?, ?) ON CONFLICT(project) DO UPDATE SET nested = excluded.nested, at = excluded.at").run(project, yes ? "inplace" : "copy", this.now());
224
+ }
225
+ }
226
+ }
227
+ }
228
+ }
229
+ catch (error) {
230
+ if (error instanceof WsRefusal)
231
+ return { ok: false, error: error.message };
232
+ throw error;
233
+ }
234
+ if (held !== undefined && held.mode !== mode) {
235
+ return { ok: false, error: `Vesperia's earlier Workspace for ${project} runs ${held.mode}, and this approve would run ${mode === "none" ? "in place" : mode} because ${setting ?? "the project"} changed; /conclave merge or /conclave discard it first, or set ${setting ?? "the project"} back.` };
236
+ }
237
+ if (mode === "none" && from !== "workspace.enabled is false")
238
+ note = `Vesperia works in place in ${project} (your choice for this folder; workspace.nested changes it)`;
239
+ return { ok: true, mode, from, ...(note === undefined ? {} : { note }) };
240
+ }
241
+ /* --- open --------------------------------------------------------------------------------------------------- */
242
+ async pool(items, size, fn) {
243
+ let next = 0;
244
+ await Promise.all(Array.from({ length: Math.min(size, items.length) }, async () => { for (let i = next++; i < items.length; i = next++)
245
+ await fn(items[i]); }));
246
+ }
247
+ /**
248
+ * Open the Workspace of a run key (pipeline `start` phase). A row for the key is reused (a replayed `start`); a held or
249
+ * conflicted Workspace of the project with the same plan is reopened in place; otherwise the copy is made. Returns the
250
+ * folder Vesperia's conversation gets as its cwd and the start notice.
251
+ */
252
+ async open(key, mode, projectIn, plan) {
253
+ const project = canonicalize(projectIn);
254
+ return this.chained(project, async () => {
255
+ const known = this.byKey(key);
256
+ if (known !== undefined && ["open", "held", "conflicted"].includes(known.state)) {
257
+ this.set(known.id, { state: "open", hold: null, hold_detail: null });
258
+ return { folder: known.folder, notice: [] };
259
+ }
260
+ await this.endedRule(project);
261
+ const same = this.rows("project = ? AND state IN ('open', 'held', 'conflicted')", project)[0];
262
+ if (same !== undefined) {
263
+ if (same.state === "open")
264
+ throw new WsRefusal("Vesperia is already working on this project in another conversation; wait for that run or /conclave cancel it there");
265
+ if (same.plan !== plan)
266
+ throw new WsRefusal(`Vesperia's earlier Workspace holds ${this.changedPaths(same.id).length} changed files; /conclave merge or /conclave discard first.`);
267
+ const refs = same.refs === null ? [] : JSON.parse(same.refs);
268
+ if (same.mode === "git" && refs.length > 0 && (await this.git.missingObjects(project, refs)).length > 0) {
269
+ throw new WsRefusal(`the live repository no longer has objects this Workspace's git needs (pruned since ${new Date(same.created).toISOString().slice(0, 10)}); its files are intact: /conclave merge or /conclave discard still work.`);
270
+ }
271
+ const earlier = JSON.parse(same.confine);
272
+ const prior = earlier.wsl ?? earlier.docker;
273
+ // The object folders come from the live repository, never from the Workspace's own alternates file (Vesperia can write it). If the live repository cannot be read, the stored list stands.
274
+ const live = same.mode === "git" ? await this.git.state(project).catch(() => undefined) : undefined;
275
+ const alt = same.mode !== "git" ? [] : live?.kind === "tree" ? await this.altLines(live.gitDir) : prior?.alt ?? earlier.alt ?? [];
276
+ const places = prior?.places ?? ["node_modules"];
277
+ const picked = await this.pick(same.folder, { places, alt, project, files: 0, prev: earlier.wsl, prevDocker: earlier.docker });
278
+ if (onWsl(picked.confine))
279
+ for (const place of places)
280
+ await this.fs.mkdir(join(same.folder, place), { recursive: true });
281
+ if (same.mode === "git")
282
+ await this.fs.writeFile(join(same.folder, ".git", "objects", "info", "alternates"), `${(picked.alt ?? alt).join("\n")}\n`);
283
+ this.down.delete(same.id);
284
+ const refreshed = await this.refreshLive(same).catch((error) => { this.o.notice(`the earlier Workspace could not be refreshed from ${project} (${msg(error)})`); return 0; });
285
+ this.cas.tx(() => { this.cas.db.prepare("UPDATE workspaces SET key = ?, conv = NULL, state = 'open', hold = NULL, hold_detail = NULL, confine = ? WHERE id = ?").run(key, JSON.stringify(picked.confine), same.id); });
286
+ if (same.conv !== null)
287
+ this.byConv.delete(same.conv);
288
+ return { folder: same.folder, notice: [`Vesperia continues in her earlier Workspace of ${project} (${this.changedPaths(same.id).length} changed files${refreshed > 0 ? `; ${refreshed} you changed in your folder were refreshed` : ""})`, `Shell confinement: ${picked.label}.`, ...picked.notice] };
289
+ }
290
+ return this.copyIn(key, mode, project, plan);
291
+ });
292
+ }
293
+ /**
294
+ * Reopen: every base path Vesperia never changed that the user changed live is copied into the Workspace (or removed when
295
+ * the user deleted it) and a `refresh` commit makes the live bytes its new base. Changed and conflicted paths keep their base.
296
+ */
297
+ async refreshLive(row) {
298
+ await this.scanNow(row);
299
+ const head = this.headOf(row.id);
300
+ const changed = [];
301
+ const deleted = [];
302
+ const wsPath = (p) => join(row.folder, ...p.split("/"));
303
+ const todo = [...this.baseOf(row.id)].filter(([p, b]) => b.kind === "file" && b.hash !== null && head.get(p)?.hash === b.hash);
304
+ await this.pool(todo, 16, async ([p, b]) => {
305
+ const live = await this.liveInfo(await this.writer.name(row.project, p, row.live_caseless === 1));
306
+ if (live.kind === "absent") {
307
+ await this.fs.unlink(wsPath(p)).catch(() => undefined);
308
+ deleted.push(p);
309
+ return;
310
+ }
311
+ if (live.kind !== "file" || live.hash === b.hash)
312
+ return;
313
+ if (live.bytes !== undefined)
314
+ await this.fs.writeFile(wsPath(p), live.bytes);
315
+ else
316
+ await this.fs.copyFile(join(row.project, ...p.split("/")), wsPath(p));
317
+ changed.push({ path: p, hash: live.hash, size: live.size, mtime: Math.floor((await this.fs.lstat(wsPath(p))).mtimeMs), link: false });
318
+ });
319
+ await this.checkpoint(row, changed, deleted, [], "refresh");
320
+ return changed.length + deleted.length;
321
+ }
322
+ /** Attach the Vesperia conversation to the Workspace of a key (inside the start commit, so a replay rewrites it). */
323
+ attach(key, conv) {
324
+ const row = this.byKey(key);
325
+ if (row === undefined)
326
+ return;
327
+ this.set(row.id, { conv });
328
+ }
329
+ async copyIn(key, mode, project, plan) {
330
+ const cfg = this.o.guard();
331
+ const refuse = (text) => { throw new WsRefusal(text); };
332
+ const read = checkRead(project, undefined, cfg);
333
+ if (!read.allowed)
334
+ refuse(`${project} is inside a protected location (${read.reason}); add it to guard.allow, or set workspace.enabled to false`);
335
+ const rootDir = join(this.wsRoot, this.hash);
336
+ if (!checkPath(rootDir, undefined, cfg, true).allowed)
337
+ refuse(`the Workspace folder ${rootDir} would be inside a protected location; change guard.deny or wsRoot`);
338
+ const state = await this.git.state(project);
339
+ if (state.kind === "tree") {
340
+ const op = this.git.operationInProgress(state.gitDir);
341
+ if (op !== undefined)
342
+ refuse(`finish or abort the ${op} in ${project} first`);
343
+ }
344
+ // The copy set.
345
+ const secrets = [];
346
+ const skipped = [];
347
+ const links = [];
348
+ let listed;
349
+ if (state.kind === "tree")
350
+ listed = await this.git.files(project);
351
+ else
352
+ listed = await this.walkProject(project, links);
353
+ const dev = (await this.fs.lstat(project, { bigint: true }));
354
+ const items = [];
355
+ const missing = [];
356
+ await this.pool(listed, 16, async (path) => {
357
+ if (WIDE_SECRET.some((p) => p.test(basename(path)))) {
358
+ secrets.push(path);
359
+ return;
360
+ }
361
+ try {
362
+ const info = await this.fs.lstat(join(project, path));
363
+ if (info.isDirectory()) {
364
+ skipped.push(`${path} (a folder: a nested repository or an uninitialized submodule)`);
365
+ return;
366
+ }
367
+ if (info.isSymbolicLink())
368
+ items.push({ path, size: 0, mode: 0, link: await this.fs.readlink(join(project, path)) });
369
+ else if (info.isFile())
370
+ items.push({ path, size: info.size, mode: info.mode & 0o777 });
371
+ else
372
+ skipped.push(`${path} (not a regular file)`);
373
+ }
374
+ catch (error) {
375
+ if (code(error) === "ENOENT")
376
+ missing.push(path);
377
+ else
378
+ skipped.push(`${path} (${code(error) ?? msg(error)})`);
379
+ }
380
+ });
381
+ // Case folding: probe the Workspace volume and the live folder without writing to the live one.
382
+ // The live folder's case sensitivity: lstat a case-swapped form of a path with a letter and compare inodes; nothing is written.
383
+ const first = items.find((i) => /[a-z]/iu.test(i.path));
384
+ const inode = async (path) => (await this.fs.lstat(join(project, path), { bigint: true }).catch(() => undefined))?.ino;
385
+ const liveCaseless = first !== undefined && (await inode(first.path.replace(/[a-z]/giu, (c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase())))) === (await inode(first.path)) && (await inode(first.path)) !== undefined;
386
+ const id = this.nextId++;
387
+ const folder = join(rootDir, String(id));
388
+ await this.fs.mkdir(folder, { recursive: true, mode: 0o700 });
389
+ const wsCaseless = await this.probeCaseless(folder);
390
+ if (wsCaseless) {
391
+ const groups = new Map();
392
+ for (const i of items)
393
+ groups.set(i.path.toLowerCase(), [...(groups.get(i.path.toLowerCase()) ?? []), i.path]);
394
+ for (const [, paths] of groups)
395
+ if (paths.length > 1) {
396
+ skipped.push(`${paths.join(", ")} (names equal under case folding)`);
397
+ for (const p of paths)
398
+ items.splice(items.findIndex((i) => i.path === p), 1);
399
+ }
400
+ }
401
+ let chosen;
402
+ try {
403
+ const gitFiles = mode === "git" && state.kind === "tree" ? await this.gitAllowList(state.gitDir) : [];
404
+ const total = items.length + gitFiles.length;
405
+ const bytes = items.reduce((n, i) => n + i.size, 0) + gitFiles.reduce((n, g) => n + g.size, 0);
406
+ if (total > FILE_BOUND)
407
+ refuse(`${project} has ${total} files to copy, over the limit of ${FILE_BOUND}; set workspace.enabled to false to run in place`);
408
+ if (bytes > BYTE_BOUND)
409
+ refuse(`${project} has ${bytes} bytes to copy, over the limit of 2 GiB; set workspace.enabled to false to run in place`);
410
+ if (state.kind === "tree") {
411
+ for (const dir of await this.git.ignoredDirs(project))
412
+ if (LINK_NAMES.includes(basename(dir.replace(/\/$/u, ""))))
413
+ links.push(dir.replace(/\/$/u, ""));
414
+ }
415
+ const objects = [];
416
+ let held = 0;
417
+ const flush = () => { if (objects.length > 0) {
418
+ const batch = objects.splice(0);
419
+ this.cas.tx(() => this.cas.insert(batch));
420
+ } held = 0; };
421
+ const made = new Set();
422
+ const ensure = async (dir) => { if (!made.has(dir)) {
423
+ await this.fs.mkdir(dir, { recursive: true });
424
+ made.add(dir);
425
+ } };
426
+ const ents = new Map();
427
+ const unreadable = [];
428
+ await this.pool(items, 8, async (item) => {
429
+ const src = join(project, item.path);
430
+ const dst = join(folder, item.path);
431
+ await ensure(dirname(dst));
432
+ if (item.link !== undefined) {
433
+ try {
434
+ await this.fs.symlink(item.link, dst);
435
+ ents.set(item.path, { path: item.path, hash: sha(item.link), object: null, size: 0, kind: "link" });
436
+ }
437
+ catch (error) {
438
+ skipped.push(`${item.path} (the symlink could not be recreated: ${code(error)})`);
439
+ }
440
+ return;
441
+ }
442
+ try {
443
+ if (item.size <= TEXT_MAX) {
444
+ const data = await this.fs.readFile(src);
445
+ await this.fs.writeFile(dst, data, { mode: item.mode });
446
+ const p = pack(data);
447
+ if (held + data.length > BATCH_BYTES)
448
+ flush();
449
+ objects.push(p);
450
+ held += data.length;
451
+ ents.set(item.path, { path: item.path, hash: p.id, object: p.id, size: data.length, kind: "file" });
452
+ if (objects.length >= OPEN_BATCH)
453
+ flush();
454
+ }
455
+ else {
456
+ await this.fs.copyFile(src, dst);
457
+ ents.set(item.path, { path: item.path, hash: await this.writer.hashFile(dst), object: null, size: item.size, kind: "file" });
458
+ }
459
+ }
460
+ catch (error) {
461
+ unreadable.push(`${item.path} (${code(error) ?? msg(error)})`);
462
+ }
463
+ });
464
+ flush();
465
+ skipped.push(...unreadable);
466
+ for (const path of missing)
467
+ ents.set(path, { path, hash: null, object: null, size: 0, kind: "skipped" });
468
+ // LINK_NAMES folders (node_modules) start as empty real folders: no link into the live project, ever.
469
+ for (const rel of links)
470
+ await ensure(join(folder, rel));
471
+ if (mode === "git" && state.kind === "tree")
472
+ await this.copyGit(state.gitDir, folder, gitFiles);
473
+ const alt = mode === "git" && state.kind === "tree" ? await this.altLines(state.gitDir) : [];
474
+ // Stat every copied path: a path missing or of another size after the copy becomes `skipped`.
475
+ const stats = new Map();
476
+ await this.pool([...ents.values()].filter((e) => e.kind !== "skipped"), 16, async (e) => {
477
+ try {
478
+ const info = await this.fs.lstat(join(folder, e.path));
479
+ if (e.kind === "file" && info.size !== e.size) {
480
+ ents.set(e.path, { ...e, hash: null, object: null, kind: "skipped" });
481
+ skipped.push(`${e.path} (it changed during the copy)`);
482
+ return;
483
+ }
484
+ stats.set(e.path, { size: info.size, mtime: Math.floor(info.mtimeMs) });
485
+ }
486
+ catch {
487
+ ents.set(e.path, { ...e, hash: null, object: null, kind: "skipped" });
488
+ skipped.push(`${e.path} (it vanished during the copy)`);
489
+ }
490
+ });
491
+ const head = state.kind === "tree" ? (await this.git.head(project)) ?? "" : null;
492
+ const refs = mode === "git" && state.kind === "tree" ? await this.git.refIds(project, head ?? "") : [];
493
+ if (refs.length > 0 && (await this.git.missingObjects(project, refs)).length > 0)
494
+ refuse("the live repository is missing objects that its own refs name; run git fsck there first");
495
+ const objectIds = [...ents.values()].flatMap((e) => (e.object === null ? [] : [e.object]));
496
+ const places = [...new Set([...links, "node_modules"])];
497
+ const picked = await this.pick(folder, { places, alt, project, files: items.length });
498
+ chosen = picked.confine;
499
+ if (onWsl(chosen))
500
+ for (const place of places)
501
+ await ensure(join(folder, place));
502
+ if (picked.alt !== undefined)
503
+ await this.fs.writeFile(join(folder, ".git", "objects", "info", "alternates"), `${picked.alt.join("\n")}\n`).catch(() => undefined);
504
+ if (onWsl(chosen) && mode === "git")
505
+ await this.liveLineEndings(project, folder);
506
+ let baseId = 0;
507
+ this.cas.tx(() => {
508
+ if (this.cas.missing(objectIds).length > 0)
509
+ throw new WsRefusal("the store dropped objects of this copy while it was made; approve again");
510
+ const confine = JSON.stringify(picked.confine);
511
+ this.cas.db.prepare("INSERT INTO workspaces(id, key, project, project_dev, project_ino, mode, git_head, refs, plan, folder, ws_caseless, live_caseless, confine, state, conv, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', NULL, ?)")
512
+ .run(id, key, project, String(dev.dev), String(dev.ino), mode, head, refs.length === 0 ? null : JSON.stringify(refs), plan, folder, wsCaseless ? 1 : 0, liveCaseless ? 1 : 0, confine, this.now());
513
+ baseId = Number(this.cas.db.prepare("INSERT INTO commits(workspace, parent, kind, at, note) VALUES (?, NULL, 'base', ?, 'open')").run(id, this.now()).lastInsertRowid);
514
+ const entry = this.cas.db.prepare('INSERT INTO entries("commit", path, object, hash, size, kind) VALUES (?, ?, ?, ?, ?, ?)');
515
+ const stat = this.cas.db.prepare("INSERT INTO ws_stat VALUES (?, ?, ?, ?, ?)");
516
+ for (const e of ents.values()) {
517
+ entry.run(baseId, e.path, e.object, e.hash, e.size, e.kind);
518
+ const st = stats.get(e.path);
519
+ if (st !== undefined)
520
+ stat.run(id, e.path, st.size, st.mtime, e.hash);
521
+ }
522
+ this.cas.db.prepare("UPDATE workspaces SET base = ?, head = ? WHERE id = ?").run(baseId, baseId, id);
523
+ });
524
+ const list = (names) => `${names.slice(0, 10).join(", ")}${names.length > 10 ? ` and ${names.length - 10} more` : ""}`;
525
+ const out = [
526
+ `Vesperia works in a Workspace copy of ${project} (${ents.size} files${links.length > 0 ? `, ${links.join(", ")} starts empty` : ""}${secrets.length > 0 ? `; left out: ${list(secrets)}` : ""}${skipped.length > 0 || missing.length > 0 ? `${secrets.length > 0 ? "," : "; left out:"} ${list([...skipped, ...missing.map((m) => `${m} (missing on disk)`)])}` : ""}; ${mode === "git" ? "with git" : state.kind === "tree" ? "without git: this folder is nested" : "without git"}). Shell confinement: ${picked.label}.`,
527
+ ...picked.notice,
528
+ ];
529
+ return { folder, notice: out };
530
+ }
531
+ catch (error) {
532
+ await this.removeFolder(folder, chosen).catch(() => undefined);
533
+ throw error;
534
+ }
535
+ }
536
+ async probeCaseless(folder) {
537
+ const probe = join(folder, ".piroboros-case-probe");
538
+ try {
539
+ await (await this.fs.open(probe, "wx")).close();
540
+ return await this.fs.lstat(probe.replace(/case-probe$/u, "CASE-PROBE")).then(() => true, () => false);
541
+ }
542
+ finally {
543
+ await this.fs.unlink(probe).catch(() => undefined);
544
+ }
545
+ }
546
+ async walkProject(project, links) {
547
+ const out = [];
548
+ const walk = async (dir, rel) => {
549
+ for (const e of await this.fs.readdir(dir, { withFileTypes: true })) {
550
+ const path = rel === "" ? e.name : `${rel}/${e.name}`;
551
+ if (e.name === ".git")
552
+ continue;
553
+ if (e.isDirectory() && LINK_NAMES.includes(e.name)) {
554
+ links.push(path);
555
+ continue;
556
+ }
557
+ if (e.isDirectory())
558
+ await walk(join(dir, e.name), path);
559
+ else
560
+ out.push(path);
561
+ }
562
+ };
563
+ await walk(project, "");
564
+ return out;
565
+ }
566
+ /** The files of the live .git that a git Workspace copies: an allow-list, no objects, hooks, lfs, modules or worktrees. */
567
+ async gitAllowList(gitDir) {
568
+ const out = [];
569
+ const walk = async (rel) => {
570
+ const abs = join(gitDir, rel);
571
+ let info;
572
+ try {
573
+ info = await this.fs.lstat(abs);
574
+ }
575
+ catch {
576
+ return;
577
+ }
578
+ if (info.isSymbolicLink() || rel.endsWith(".lock"))
579
+ return;
580
+ if (info.isDirectory()) {
581
+ for (const name of await this.fs.readdir(abs))
582
+ await walk(`${rel}/${name}`);
583
+ }
584
+ else if (info.isFile())
585
+ out.push({ rel, size: info.size });
586
+ };
587
+ for (const name of ["HEAD", "config", "index", "refs", "packed-refs", "info", "shallow", "logs", "reftable"])
588
+ await walk(name);
589
+ return out;
590
+ }
591
+ async copyGit(gitDir, folder, files) {
592
+ const dest = join(folder, ".git");
593
+ await this.fs.mkdir(join(dest, "objects", "pack"), { recursive: true });
594
+ await this.fs.mkdir(join(dest, "objects", "info"), { recursive: true });
595
+ for (const f of files) {
596
+ if (f.rel === "config") {
597
+ await this.fs.writeFile(join(dest, "config"), await this.git.copyConfig(gitDir));
598
+ continue;
599
+ }
600
+ await this.fs.mkdir(dirname(join(dest, f.rel)), { recursive: true });
601
+ await this.fs.copyFile(join(gitDir, f.rel), join(dest, f.rel));
602
+ }
603
+ await this.fs.writeFile(join(dest, "objects", "info", "alternates"), `${(await this.altLines(gitDir)).join("\n")}\n`);
604
+ }
605
+ /** Borrow the live repository's objects: its own object folder, then the alternates it already has. */
606
+ async altLines(gitDir) {
607
+ const own = join(gitDir, "objects");
608
+ const inherited = await this.fs.readFile(join(own, "info", "alternates"), "utf8").then((t) => t.split(/\r?\n/u).filter((l) => l !== ""), () => []);
609
+ return [own, ...inherited].map(posix);
610
+ }
611
+ /** Linux git does not read the Windows system config: copy the live repository's effective core.autocrlf and core.eol into the Workspace's own config. */
612
+ async liveLineEndings(project, folder) {
613
+ const lines = [];
614
+ for (const name of ["autocrlf", "eol"]) {
615
+ const r = await this.git.run(project, ["config", "--get", `core.${name}`]);
616
+ if (r.code === 0 && r.out.toString("utf8").trim() !== "")
617
+ lines.push(`\t${name} = ${JSON.stringify(r.out.toString("utf8").trim())}`);
618
+ }
619
+ if (lines.length > 0)
620
+ await this.fs.writeFile(join(folder, ".git", "config"), `${await this.fs.readFile(join(folder, ".git", "config"), "utf8")}[core]\n${lines.join("\n")}\n`);
621
+ }
622
+ /* --- manifests, scan and checkpoints ------------------------------------------------------------------------ */
623
+ manifest(ws, kinds) {
624
+ const out = new Map();
625
+ const rows = this.cas.db.prepare(`SELECT e.path, e.hash, e.object, e.size, e.kind FROM entries e JOIN commits c ON c.id = e."commit" WHERE c.workspace = ? AND c.kind IN (${kinds}) ORDER BY c.id ASC, e.rowid ASC`).all(ws);
626
+ for (const r of rows)
627
+ out.set(r.path, r);
628
+ return out;
629
+ }
630
+ headOf(ws) { return this.manifest(ws, "'base', 'refresh', 'checkpoint'"); }
631
+ baseOf(ws) { return this.manifest(ws, "'base', 'refresh'"); }
632
+ /** The paths Vesperia changed since the base. */
633
+ changedPaths(ws, head = this.headOf(ws), base = this.baseOf(ws)) {
634
+ return [...new Set([...head.keys(), ...base.keys()])].filter((p) => (head.get(p)?.hash ?? null) !== (base.get(p)?.hash ?? null) || (head.get(p)?.kind ?? null) !== (base.get(p)?.kind ?? null)).sort();
635
+ }
636
+ async walkWs(folder) {
637
+ const out = new Map();
638
+ const walk = async (dir, rel) => {
639
+ let list;
640
+ try {
641
+ list = await this.fs.readdir(dir, { withFileTypes: true });
642
+ }
643
+ catch (error) {
644
+ if (rel === "")
645
+ throw error;
646
+ return;
647
+ }
648
+ for (const e of list) {
649
+ const path = rel === "" ? e.name : `${rel}/${e.name}`;
650
+ if (e.name === ".git" || (e.name !== undefined && LINK_NAMES.includes(e.name) && (e.isDirectory() || e.isSymbolicLink())))
651
+ continue;
652
+ if (e.isDirectory())
653
+ await walk(join(dir, e.name), path);
654
+ else
655
+ out.set(path, e.isFile() ? "file" : "other");
656
+ }
657
+ };
658
+ await walk(folder, "");
659
+ return out;
660
+ }
661
+ /** Compare the Workspace with its stat rows and checkpoint what changed. Returns the new git-ignored paths and whether the ignore check failed. */
662
+ async scanNow(row, only, force = false) {
663
+ const stat = new Map(this.cas.db.prepare("SELECT path, size, mtime, hash FROM ws_stat WHERE workspace = ?").all(row.id).map((s) => [s.path, s]));
664
+ const onDisk = only === undefined ? await this.walkWs(row.folder) : new Map(only.map((p) => [p, "file"]));
665
+ const candidates = only ?? [...new Set([...onDisk.keys(), ...stat.keys()])];
666
+ const changed = [];
667
+ const deleted = [];
668
+ const touch = [];
669
+ const fresh = [];
670
+ await this.pool(candidates, 16, async (path) => {
671
+ // A full scan decides presence by the exact names the walk listed: lstat would find `Readme.md` under `README.md` on a case-insensitive folder.
672
+ if (only === undefined && !onDisk.has(path)) {
673
+ if (stat.has(path))
674
+ deleted.push(path);
675
+ return;
676
+ }
677
+ let info;
678
+ try {
679
+ info = await this.fs.lstat(join(row.folder, path));
680
+ }
681
+ catch (error) {
682
+ if (code(error) === "ENOENT" || code(error) === "ENOTDIR") {
683
+ if (stat.has(path))
684
+ deleted.push(path);
685
+ return;
686
+ }
687
+ throw error;
688
+ }
689
+ if (info.isDirectory()) {
690
+ if (stat.has(path))
691
+ deleted.push(path);
692
+ return;
693
+ }
694
+ const link = !info.isFile();
695
+ const known = stat.get(path);
696
+ const mtime = Math.floor(info.mtimeMs);
697
+ if (known !== undefined && !force && known.size === info.size && known.mtime === mtime)
698
+ return;
699
+ const hash = link ? sha(await this.fs.readlink(join(row.folder, path)).catch(() => "")) : await this.writer.hashFile(join(row.folder, path), info.size);
700
+ if (known === undefined)
701
+ fresh.push({ path, hash, size: info.size, mtime, link });
702
+ else if (known.hash === hash)
703
+ touch.push({ path, size: info.size, mtime, hash });
704
+ else
705
+ changed.push({ path, hash, size: info.size, mtime, link });
706
+ });
707
+ // New paths: secret names are never checkpointed; paths the live repository ignores are kept in memory for the merge notice.
708
+ let ignoredNew = [];
709
+ let ignoreFailed = false;
710
+ let adds = fresh.filter((f) => !WIDE_SECRET.some((p) => p.test(basename(f.path))));
711
+ if (adds.length > 0 && row.git_head !== null) {
712
+ try {
713
+ const hit = await this.git.ignored(row.project, adds.map((a) => a.path));
714
+ ignoredNew = [...hit];
715
+ adds = adds.filter((a) => !hit.has(a.path));
716
+ }
717
+ catch (error) {
718
+ ignoreFailed = true;
719
+ this.o.notice(`the live ignore rules could not be read (${msg(error)}); the merge will hold`);
720
+ }
721
+ }
722
+ await this.checkpoint(row, [...changed, ...adds], deleted, touch);
723
+ return { ignoredNew, ignoreFailed };
724
+ }
725
+ /** Insert the changed paths as `checkpoint` commits, in batches by the CAS rule, each batch with its objects in one transaction. */
726
+ async checkpoint(row, changed, deleted, touch, kind = "checkpoint") {
727
+ if (touch.length > 0)
728
+ this.cas.tx(() => { const st = this.cas.db.prepare("UPDATE ws_stat SET size = ?, mtime = ? WHERE workspace = ? AND path = ?"); for (const t of touch)
729
+ st.run(t.size, t.mtime, row.id, t.path); });
730
+ let batch = [];
731
+ let held = 0;
732
+ const commit = (list, gone) => {
733
+ this.cas.tx(() => {
734
+ this.cas.insert(list.flatMap((b) => (b.p === undefined ? [] : [b.p])));
735
+ const parent = this.cas.db.prepare("SELECT head FROM workspaces WHERE id = ?").get(row.id).head;
736
+ const id = Number(this.cas.db.prepare("INSERT INTO commits(workspace, parent, kind, at, note) VALUES (?, ?, ?, ?, NULL)").run(row.id, parent, kind, this.now()).lastInsertRowid);
737
+ const entry = this.cas.db.prepare('INSERT INTO entries("commit", path, object, hash, size, kind) VALUES (?, ?, ?, ?, ?, ?)');
738
+ const stat = this.cas.db.prepare("INSERT INTO ws_stat VALUES (?, ?, ?, ?, ?) ON CONFLICT(workspace, path) DO UPDATE SET size = excluded.size, mtime = excluded.mtime, hash = excluded.hash");
739
+ for (const b of list) {
740
+ entry.run(id, b.c.path, b.p?.id ?? null, b.c.hash, b.c.size, b.c.link ? "link" : "file");
741
+ stat.run(row.id, b.c.path, b.c.size, b.c.mtime, b.c.hash);
742
+ }
743
+ const unstat = this.cas.db.prepare("DELETE FROM ws_stat WHERE workspace = ? AND path = ?");
744
+ for (const path of gone) {
745
+ entry.run(id, path, null, null, 0, "file");
746
+ unstat.run(row.id, path);
747
+ }
748
+ this.cas.db.prepare("UPDATE workspaces SET head = ? WHERE id = ?").run(id, row.id);
749
+ });
750
+ };
751
+ for (const c of changed) {
752
+ let p;
753
+ if (!c.link && c.size <= TEXT_MAX) {
754
+ const data = await this.fs.readFile(join(row.folder, c.path));
755
+ if (sha(data) !== c.hash) {
756
+ c.hash = sha(data);
757
+ c.size = data.length;
758
+ }
759
+ if (held + data.length > BATCH_BYTES && batch.length > 0) {
760
+ commit(batch, []);
761
+ batch = [];
762
+ held = 0;
763
+ }
764
+ p = pack(data);
765
+ held += data.length;
766
+ }
767
+ batch.push({ c, ...(p === undefined ? {} : { p }) });
768
+ if (batch.length >= OPEN_BATCH) {
769
+ commit(batch, []);
770
+ batch = [];
771
+ held = 0;
772
+ }
773
+ }
774
+ if (batch.length > 0 || deleted.length > 0)
775
+ commit(batch, deleted);
776
+ }
777
+ /** After a tool call of a Workspace conversation: write and edit checkpoint their one path, bash starts a coalesced scan. */
778
+ async after(conv, tool, path, cwd) {
779
+ const row = this.byConv.get(conv);
780
+ if (row === undefined || row.state !== "open")
781
+ return;
782
+ try {
783
+ if (tool === "bash") {
784
+ if (this.queued.has(row.id))
785
+ return;
786
+ this.queued.add(row.id);
787
+ void this.chained(row.project, async () => { this.queued.delete(row.id); await this.scanNow(row); }).catch((error) => this.o.notice(`checkpoint: ${msg(error)}`));
788
+ return;
789
+ }
790
+ if (typeof path !== "string")
791
+ return;
792
+ const rel = posix(relative(canonicalize(row.folder), canonicalize(path, cwd)));
793
+ if (rel.startsWith("..") || rel === "" || rel.split("/").some((part) => part === ".git" || LINK_NAMES.includes(part)))
794
+ return;
795
+ await this.chained(row.project, () => this.scanNow(row, [rel], true));
796
+ }
797
+ catch (error) {
798
+ this.o.notice(`checkpoint: ${msg(error)}`);
799
+ }
800
+ }
801
+ /* --- guard glue --------------------------------------------------------------------------------------------- */
802
+ confineDeps() { return { ...nativeDeps(this.o.guard(), this.wsRoot), ...this.o.confineDeps }; }
803
+ /** The confinement backend for a Workspace folder, chosen at each open and reopen (4.3.1). */
804
+ pick(folder, plan) {
805
+ const s = this.o.settings();
806
+ return confineFor({ confine: s.confine ?? "auto", network: s.network ?? true, distro: s.wslDistro, docker: s.dockerImage }, this.confineDeps(), folder, plan);
807
+ }
808
+ /** The open Workspace a shell cwd lies in, when its row names a backend: what ConfinedShellEnv wraps the command with. */
809
+ shellFor(cwd) {
810
+ for (const row of this.byConv.values()) {
811
+ if (row.state !== "open")
812
+ continue;
813
+ try {
814
+ const confine = JSON.parse(row.confine);
815
+ if (confine.name !== "none" && isInside(canonicalize(row.folder), canonicalize(cwd)))
816
+ return { ws: row.folder, confine, deps: this.confineDeps(), down: this.down.get(row.id), mark: (reason) => { this.down.set(row.id, reason); } };
817
+ }
818
+ catch { /* not this row */ }
819
+ }
820
+ return undefined;
821
+ }
822
+ /** Whether the project's open Workspace runs its shell confined, and in a container (the brief says so). */
823
+ confinedFor(project, name) {
824
+ try {
825
+ const got = JSON.parse(this.rows("project = ? AND state = 'open'", canonicalize(project))[0]?.confine ?? "{}").name;
826
+ return name === undefined ? got === "bubblewrap" || got === "docker" : got === name;
827
+ }
828
+ catch {
829
+ return false;
830
+ }
831
+ }
832
+ /** Whether the conversation runs in a Workspace. */
833
+ has(conv) { return this.byConv.has(conv); }
834
+ /** GIT_CEILING_DIRECTORIES for a plain Workspace's shell: the Workspace folder's parent, so git never finds a repository above it. */
835
+ ceilingFor(cwd) {
836
+ for (const row of this.byConv.values())
837
+ if (row.mode === "plain" && row.state === "open") {
838
+ try {
839
+ if (isInside(canonicalize(row.folder), canonicalize(cwd)))
840
+ return dirname(row.folder);
841
+ }
842
+ catch { /* no ceiling */ }
843
+ }
844
+ return undefined;
845
+ }
846
+ /** The project folder for a path inside a Workspace folder (memory records go to the project, not the copy). */
847
+ projectOf(path) {
848
+ for (const row of this.byConv.values()) {
849
+ try {
850
+ if (isInside(canonicalize(row.folder), canonicalize(path)))
851
+ return join(row.project, relative(canonicalize(row.folder), canonicalize(path)));
852
+ }
853
+ catch { /* not inside */ }
854
+ }
855
+ return undefined;
856
+ }
857
+ /* --- plan ------------------------------------------------------------------------------------------------- */
858
+ async liveInfo(abs) {
859
+ let info;
860
+ try {
861
+ info = await this.fs.lstat(abs);
862
+ }
863
+ catch (error) {
864
+ if (code(error) === "ENOENT" || code(error) === "ENOTDIR")
865
+ return { kind: "absent" };
866
+ throw error;
867
+ }
868
+ if (info.isDirectory())
869
+ return { kind: "dir" };
870
+ if (!info.isFile())
871
+ return { kind: "link" };
872
+ const mtime = Math.floor(info.mtimeMs);
873
+ if (info.size <= TEXT_MAX) {
874
+ const bytes = await this.fs.readFile(abs);
875
+ return { kind: "file", hash: sha(bytes), size: bytes.length, mtime, bytes };
876
+ }
877
+ return { kind: "file", hash: await this.writer.hashFile(abs, info.size), size: info.size, mtime };
878
+ }
879
+ big(n) { return new Uint8Array(TEXT_MAX + 1).fill(n); }
880
+ /** The rules of the project folder's root `.lww` and its `%include` files (regular files inside the project, at most 64 KiB each). */
881
+ // ponytail: read with node:fs, not the injected fs; the file is small and only matched against paths.
882
+ lwwFor(project) {
883
+ const read = (file) => {
884
+ try {
885
+ const p = resolve(project, file);
886
+ if (!isInside(project, p) || !lstatSync(p).isFile())
887
+ return undefined;
888
+ const b = readFileSync(p);
889
+ return b.length <= 65_536 ? b.toString("utf8") : undefined;
890
+ }
891
+ catch {
892
+ return undefined;
893
+ }
894
+ };
895
+ const text = read(".lww");
896
+ return text === undefined ? [] : lwwRules(text, read);
897
+ }
898
+ /** Read the plan: the final scan, then a decision per path Vesperia changed. Housekeeping aside (resolved conflict rows are dropped), nothing is written. */
899
+ async plan(row) {
900
+ this.writer.forgetNames();
901
+ const scan = await this.scanNow(row);
902
+ const head = this.headOf(row.id);
903
+ const base = this.baseOf(row.id);
904
+ const caseless = row.live_caseless === 1;
905
+ const rows = [];
906
+ const conflicts = [];
907
+ const left = [];
908
+ const oversize = [];
909
+ const paths = this.changedPaths(row.id, head, base);
910
+ const label = `workspace ${row.id}`;
911
+ const rules = this.lwwFor(row.project);
912
+ const lww = [];
913
+ const rebased = new Set();
914
+ const old = new Map(this.cas.db.prepare("SELECT path, kind, ours, theirs FROM conflicts WHERE workspace = ?").all(row.id).map((c) => [c.path, c]));
915
+ const entryOf = (p) => { const e = head.get(p); return e === undefined || e.hash === null ? undefined : e; };
916
+ const baseEnt = (p) => { const e = base.get(p); return e === undefined || e.hash === null ? undefined : e; };
917
+ const wsAbs = (p) => join(row.folder, ...p.split("/"));
918
+ const items = new Map();
919
+ const sideOf = async (e, n, source, path) => {
920
+ if (e === undefined)
921
+ return undefined;
922
+ if (e.size > TEXT_MAX)
923
+ return this.big(n);
924
+ if (source === "base")
925
+ return e.object === null ? this.big(n) : this.cas.get(e.object) ?? this.big(n);
926
+ return await this.fs.readFile(join(row.folder, path)).catch(() => this.big(n));
927
+ };
928
+ const refuseReason = (p, e, b) => {
929
+ if (b?.kind === "skipped")
930
+ return "skipped at open";
931
+ if (e?.kind === "link")
932
+ return "link";
933
+ if (/[\\:*?"<>|-]/u.test(basename(p)) || /[. ]$/u.test(basename(p)))
934
+ return "name not portable";
935
+ if (WIDE_SECRET.some((x) => x.test(basename(p))))
936
+ return "secret name";
937
+ if (p.split("/").some((part) => RESERVED.test(part)))
938
+ return "reserved name";
939
+ if (e !== undefined && SHELL_ACTIVE.some((x) => x.test(basename(p))))
940
+ return "shell-active name";
941
+ if (!checkPath(join(row.project, p), row.project, this.o.guard(), true).allowed)
942
+ return "protected";
943
+ return undefined;
944
+ };
945
+ const todo = [];
946
+ for (const p of paths) {
947
+ const ours = entryOf(p);
948
+ let b = baseEnt(p);
949
+ const why = refuseReason(p, ours, base.get(p));
950
+ if (why !== undefined) {
951
+ left.push({ path: p, reason: why });
952
+ continue;
953
+ }
954
+ // A path with a conflict row: while its marker block stands, Vesperia's version is the stored one; once resolved, the recorded live text is its base.
955
+ let over;
956
+ const c = old.get(p);
957
+ if (c !== undefined && (c.kind === "content" || c.kind === "add/add") && c.theirs !== null) {
958
+ const mine = ours === undefined ? undefined : await this.fs.readFile(wsAbs(p)).catch(() => undefined);
959
+ const stored = c.ours === null ? undefined : this.cas.get(c.ours);
960
+ const recorded = this.cas.get(c.theirs);
961
+ if (mine !== undefined && stored !== undefined && hasBlock(mine.toString("utf8"), row.id))
962
+ over = stored;
963
+ else if (recorded !== undefined) {
964
+ b = { path: p, hash: c.theirs, object: c.theirs, size: recorded.length, kind: "file" };
965
+ rebased.add(p);
966
+ }
967
+ }
968
+ todo.push({ path: p, ours, base: b, ...(over === undefined ? {} : { over }) });
969
+ }
970
+ // Case-only renames: a delete of A and an add of B equal under case folding, with A unchanged live.
971
+ const renames = new Map();
972
+ if (caseless) {
973
+ const adds = todo.filter((t) => t.ours !== undefined && t.base === undefined);
974
+ for (const del of todo.filter((t) => t.ours === undefined && t.base !== undefined)) {
975
+ const add = adds.find((a) => a.path.toLowerCase() === del.path.toLowerCase() && a.path !== del.path);
976
+ if (add !== undefined)
977
+ renames.set(add.path, del.path);
978
+ }
979
+ }
980
+ const renamed = new Set(renames.values());
981
+ const mkdirs = new Set();
982
+ const dirFor = async (rel) => {
983
+ // A parent that is a live file is a type conflict; a missing parent is made by a mkdir row.
984
+ const parts = rel.split("/").slice(0, -1);
985
+ let cur = "";
986
+ for (const part of parts) {
987
+ cur = cur === "" ? part : `${cur}/${part}`;
988
+ const abs = await this.writer.name(row.project, cur, caseless);
989
+ const info = await this.liveInfo(abs);
990
+ if (info.kind === "absent") {
991
+ mkdirs.add(cur);
992
+ continue;
993
+ }
994
+ if (info.kind !== "dir")
995
+ return cur;
996
+ }
997
+ return undefined;
998
+ };
999
+ const conflict = (path, kind, ours, theirs, marked) => {
1000
+ conflicts.push({ path, kind, ours: null, oursSize: ours?.size ?? 0, theirsHash: theirs?.hash ?? null, theirs: theirs?.bytes ?? null, liveSize: theirs?.size ?? 0, wsPath: wsAbs(path), ...(marked === undefined ? {} : marked) });
1001
+ };
1002
+ const makeRow = (path, from, op, pre, post, extra = {}) => ({ seq: 0, path, from, op, pre, post, mode: null, ...extra });
1003
+ const decideFor = async (path, entry, b, theirs, over) => {
1004
+ const ours = over === undefined ? entry : { path, hash: sha(over), object: null, size: over.length, kind: "file" };
1005
+ const theirHash = theirs.kind === "file" ? theirs.hash : null;
1006
+ const theirSize = theirs.kind === "file" ? theirs.size : 0;
1007
+ if (theirs.kind === "link") {
1008
+ left.push({ path, reason: "link" });
1009
+ return "skip";
1010
+ }
1011
+ if ((ours?.hash ?? null) === theirHash && theirs.kind !== "dir")
1012
+ return "skip";
1013
+ const oursMode = ours === undefined ? null : await this.fs.lstat(join(row.folder, path)).then((s) => s.mode & 0o777).catch(() => null);
1014
+ const takeOurs = () => {
1015
+ if (theirs.kind === "file" && theirSize > SNAPSHOT_MAX) {
1016
+ oversize.push({ path, ws: join(row.folder, ...path.split("/")) });
1017
+ return "oversize";
1018
+ }
1019
+ if (ours === undefined)
1020
+ return makeRow(path, null, "delete", theirHash, null, { preSize: theirSize });
1021
+ if (theirs.kind === "absent")
1022
+ return makeRow(path, null, "create", null, ours.hash, { mode: oursMode, postSize: ours.size, ...(over === undefined ? {} : { body: over }) });
1023
+ return makeRow(path, null, "write", theirHash, ours.hash, { mode: oursMode, preSize: theirSize, postSize: ours.size, ...(over === undefined ? {} : { body: over }) });
1024
+ };
1025
+ if ((theirHash ?? null) === (b?.hash ?? null) && theirs.kind !== "dir")
1026
+ return takeOurs();
1027
+ if (theirs.kind === "dir" || (ours !== undefined && theirs.kind === "absent" && (await dirFor(path)) !== undefined)) {
1028
+ conflict(path, "type", ours, { hash: theirHash, size: theirSize });
1029
+ return "conflict";
1030
+ }
1031
+ // Both sides moved away from the base: the line merge, or a named conflict.
1032
+ const rule = rules.length > 0 ? lwwMatch(rules, path) : null;
1033
+ const times = rule === null ? undefined : { rules, ours: this.oursTime(row.id, path, ours !== undefined), theirs: theirs.kind === "file" ? theirs.mtime : -Infinity };
1034
+ const d = decide(path, await sideOf(b, 3, "base", path), over ?? await sideOf(ours, 1, "ws", path), theirs.kind === "file" ? (theirs.bytes ?? this.big(2)) : undefined, { labels: [label, `live ${row.id}`], ...(times === undefined ? {} : { lww: times }) });
1035
+ if ("lww" in d && d.lww !== undefined)
1036
+ lww.push({ path, ...d.lww });
1037
+ if (d.op === "skip")
1038
+ return "skip";
1039
+ if (d.op === "ours")
1040
+ return takeOurs();
1041
+ if (d.op === "merged") {
1042
+ const body = Buffer.from(d.text);
1043
+ if (theirs.kind === "file" && theirSize > SNAPSHOT_MAX) {
1044
+ oversize.push({ path, ws: join(row.folder, ...path.split("/")) });
1045
+ return "oversize";
1046
+ }
1047
+ return makeRow(path, null, theirs.kind === "absent" ? "create" : "write", theirHash, sha(body), { mode: oursMode, preSize: theirSize, postSize: body.length, body });
1048
+ }
1049
+ conflict(path, d.kind, ours, { hash: theirHash, bytes: theirs.kind === "file" ? theirs.bytes : undefined, size: theirSize }, d.text === undefined ? undefined : { text: d.text, lines: (d.hunks ?? []).map((h) => h.line) });
1050
+ return "conflict";
1051
+ };
1052
+ const processed = new Set();
1053
+ for (const t of todo) {
1054
+ if (renamed.has(t.path) || processed.has(t.path))
1055
+ continue;
1056
+ const abs = await this.writer.name(row.project, t.path, caseless);
1057
+ const theirs = await this.liveInfo(abs);
1058
+ items.set(t.path, { ours: t.ours, base: t.base, ...(t.over === undefined ? {} : { over: t.over }) });
1059
+ // A new path equal under case folding to a different live path is a case conflict.
1060
+ if (caseless && t.ours !== undefined && t.base === undefined && !renames.has(t.path) && theirs.kind !== "absent" && relative(row.project, abs).replaceAll("\\", "/") !== t.path) {
1061
+ conflict(t.path, "case", t.ours, { hash: theirs.kind === "file" ? theirs.hash : null, size: 0 });
1062
+ continue;
1063
+ }
1064
+ const outcome = await decideFor(t.path, t.ours, t.base, theirs, t.over);
1065
+ if (typeof outcome !== "string")
1066
+ rows.push(outcome);
1067
+ }
1068
+ for (const [bPath, aPath] of renames) {
1069
+ const a = todo.find((t) => t.path === aPath);
1070
+ const b = todo.find((t) => t.path === bPath);
1071
+ const absA = await this.writer.name(row.project, aPath, caseless);
1072
+ const theirs = await this.liveInfo(absA);
1073
+ items.set(bPath, { ours: b.ours, base: b.base });
1074
+ if (theirs.kind === "file" && theirs.hash === a.base.hash) {
1075
+ if (theirs.size > SNAPSHOT_MAX) {
1076
+ oversize.push({ path: aPath, ws: join(row.folder, ...bPath.split("/")) });
1077
+ continue;
1078
+ }
1079
+ rows.push(makeRow(bPath, aPath, "rename", theirs.hash, b.ours.hash, { mode: null, preSize: theirs.size, postSize: b.ours.size }));
1080
+ }
1081
+ else if (theirs.kind === "absent") {
1082
+ // A is gone live: B is a new file there.
1083
+ const out = await decideFor(bPath, b.ours, undefined, await this.liveInfo(await this.writer.name(row.project, bPath, caseless)));
1084
+ if (typeof out !== "string")
1085
+ rows.push(out);
1086
+ }
1087
+ else
1088
+ conflict(bPath, "case", b.ours, { hash: theirs.kind === "file" ? theirs.hash : null, size: 0 });
1089
+ }
1090
+ // Folder rows for every path the merge creates, parents before children; deletes and renames, then writes and creates.
1091
+ for (const r of [...rows])
1092
+ if (r.op === "write" || r.op === "create" || r.op === "rename") {
1093
+ const bad = await dirFor(r.path);
1094
+ if (bad !== undefined) {
1095
+ rows.splice(rows.indexOf(r), 1);
1096
+ conflict(r.path, "type", entryOf(r.path));
1097
+ }
1098
+ }
1099
+ const ordered = [...[...mkdirs].sort((a, b) => a.split("/").length - b.split("/").length).map((p) => makeRow(p, null, "mkdir", null, null)), ...rows.filter((r) => r.op === "delete" || r.op === "rename"), ...rows.filter((r) => r.op === "write" || r.op === "create")];
1100
+ ordered.forEach((r, i) => { r.seq = i + 1; });
1101
+ // Ours bytes for the conflicts, stored before anything else can change them.
1102
+ for (const c of conflicts) {
1103
+ const e = entryOf(c.path);
1104
+ if (e !== undefined)
1105
+ c.ours = items.get(c.path)?.over ?? await this.fs.readFile(wsAbs(c.path)).catch(() => null);
1106
+ }
1107
+ const plan = {
1108
+ rows: ordered, conflicts, left, oversize, deletes: ordered.filter((r) => r.op === "delete").length, ignored: scan.ignoredNew, ignoreFailed: scan.ignoreFailed, lww,
1109
+ redecide: async (r, bytes) => {
1110
+ const item = items.get(r.path);
1111
+ if (item === undefined || r.op === "rename" || r.op === "mkdir")
1112
+ return "conflict";
1113
+ const theirs = bytes === null ? { kind: "absent" } : { kind: "file", hash: sha(bytes), size: bytes.length, mtime: this.now(), bytes };
1114
+ const before = conflicts.length;
1115
+ const out = await decideFor(r.path, item.ours, item.base, theirs, item.over);
1116
+ if (conflicts.length > before) {
1117
+ conflicts.pop();
1118
+ return "conflict";
1119
+ }
1120
+ if (out === "oversize")
1121
+ return "oversize";
1122
+ if (typeof out === "string")
1123
+ return "drop";
1124
+ return { row: { ...out, seq: r.seq } };
1125
+ },
1126
+ };
1127
+ if (row.git_head !== null) {
1128
+ const now = await this.git.head(row.project);
1129
+ if ((now ?? "") !== row.git_head)
1130
+ plan.headMoved = { from: row.git_head, to: now ?? "" };
1131
+ }
1132
+ // A row whose path no longer conflicts (made equal to live, or Vesperia's change gone) is cleared; a resolved marker path keeps its row as the next base.
1133
+ const keep = new Set([...conflicts.map((c) => c.path), ...rebased]);
1134
+ const gone = [...old.keys()].filter((p) => !keep.has(p));
1135
+ if (gone.length > 0)
1136
+ this.cas.tx(() => { const del = this.cas.db.prepare("DELETE FROM conflicts WHERE workspace = ? AND path = ?"); for (const p of gone)
1137
+ del.run(row.id, p); });
1138
+ return plan;
1139
+ }
1140
+ /** The time Vesperia's side of a path was last modified, in integer milliseconds: its file's time at the last scan, or when the scan found it deleted. */
1141
+ oursTime(ws, path, present) {
1142
+ const sql = present ? "SELECT mtime AS t FROM ws_stat WHERE workspace = ? AND path = ?" : `SELECT c."at" AS t FROM entries e JOIN commits c ON c.id = e."commit" WHERE c.workspace = ? AND e.path = ? AND e.hash IS NULL ORDER BY c.id DESC LIMIT 1`;
1143
+ return Number(this.cas.db.prepare(sql).get(ws, path)?.t ?? 0);
1144
+ }
1145
+ /* --- merge ------------------------------------------------------------------------------------------------- */
1146
+ async execMerge(row, plan, run, rows) {
1147
+ const summaryHead = () => {
1148
+ const n = rows.filter((r) => r.op !== "mkdir").length;
1149
+ const out = [`Merged ${n} file${n === 1 ? "" : "s"} from the Workspace into ${row.project}`];
1150
+ for (const l of LIMITED(plan.left.map((x) => `not merged: ${x.reason}: ${x.path}`)))
1151
+ out.push(l);
1152
+ for (const o of plan.oversize)
1153
+ out.push(`not merged: over 64 MiB: ${o.path}`);
1154
+ out.push(...this.lwwLines(plan.lww).map((l) => l.trim()));
1155
+ if (plan.ignored.length > 0)
1156
+ out.push(`Vesperia also created ${plan.ignored.length} git-ignored paths (not merged): ${plan.ignored.slice(0, 10).join(", ")}`);
1157
+ return out.join("\n");
1158
+ };
1159
+ if (rows.filter((r) => r.op !== "mkdir").length === 0) {
1160
+ const oversized = plan.oversize.length > 0;
1161
+ this.cas.tx(() => { this.set(row.id, { state: oversized ? "discarded" : "merged", hold: null, hold_detail: oversized ? "nothing left to merge" : "no changes" }); });
1162
+ await this.removeFolder(row.folder).catch((error) => this.o.notice(`the Workspace folder could not be removed: ${msg(error)}`));
1163
+ return { text: [oversized ? `nothing merged: ${plan.oversize.length} changes over 64 MiB were left out; the Workspace was removed` : `Vesperia changed no files in ${row.project}; nothing was merged`, ...LIMITED(plan.left.map((x) => `not merged: ${x.reason}: ${x.path}`)), ...this.lwwLines(plan.lww).map((l) => l.trim())].join("\n"), state: oversized ? "discarded" : "merged" };
1164
+ }
1165
+ try {
1166
+ const r = await this.writer.merge({ ws: row.id, project: row.project, folder: row.folder, run, caseless: row.live_caseless === 1, rows, head: summaryHead(), redecide: plan.redecide });
1167
+ this.refresh(row.id);
1168
+ if (r.state === "done") {
1169
+ this.gc();
1170
+ return { text: r.summary, state: "merged", record: r.id };
1171
+ }
1172
+ if (r.state === "pending") {
1173
+ let held = "";
1174
+ try {
1175
+ this.hold(row.id, "not-recovered", String(r.id));
1176
+ }
1177
+ catch (error) {
1178
+ held = ` (its hold could not be written either: ${msg(error)})`;
1179
+ }
1180
+ return { text: `${r.summary}\nmerge record ${r.id} is still pending; restart piroboros to recover it${held}`, state: "held", record: r.id, code: "not-recovered" };
1181
+ }
1182
+ return { text: r.summary, state: "held", record: r.id, code: "rollback" };
1183
+ }
1184
+ catch (error) {
1185
+ if (error instanceof HoldError) {
1186
+ this.hold(row.id, error.code, error.detail.replaceAll(", ", "\n"));
1187
+ return { text: `Merge held: ${holdText(error.code, error.detail)}`, state: "held", code: error.code };
1188
+ }
1189
+ if (error instanceof ConflictFound)
1190
+ return await this.storeConflicts(row, await this.plan(row), "the live file changed again");
1191
+ this.hold(row.id, "preflight", `${row.project}: ${msg(error)}`);
1192
+ return { text: `Merge held: ${msg(error)}`, state: "held", code: "preflight" };
1193
+ }
1194
+ }
1195
+ /** Write nothing live: keep Vesperia's version of each conflicted path in the store, mark the Workspace conflicted, and write the marker text of each text conflict into the Workspace. */
1196
+ async storeConflicts(row, plan, why) {
1197
+ if (plan.conflicts.length === 0) {
1198
+ this.hold(row.id, "preflight", `${row.project}: ${why ?? "a path changed during the merge"}`);
1199
+ return { text: `Merge held: ${why ?? "a path changed during the merge"}`, state: "held", code: "preflight" };
1200
+ }
1201
+ const before = plan.conflicts.map((c) => this.cas.db.prepare("SELECT theirs FROM conflicts WHERE workspace = ? AND path = ?").get(row.id, c.path)?.theirs);
1202
+ const puts = plan.conflicts.map((c) => (c.ours === null ? undefined : pack(c.ours)));
1203
+ const theirs = plan.conflicts.map((c) => (c.theirs === null ? undefined : pack(c.theirs)));
1204
+ this.cas.tx(() => {
1205
+ this.cas.insert([...puts, ...theirs].filter((p) => p !== undefined));
1206
+ const stmt = this.cas.db.prepare("INSERT OR REPLACE INTO conflicts VALUES (?, ?, ?, ?, ?)");
1207
+ plan.conflicts.forEach((c, i) => stmt.run(row.id, c.path, c.kind, puts[i]?.id ?? null, c.theirsHash));
1208
+ this.hold(row.id, "conflicts", String(plan.conflicts.length), "conflicted");
1209
+ });
1210
+ // Markers go in after the store holds her version. A block the user is editing stays while the live text is the one it was made against.
1211
+ for (const [i, c] of plan.conflicts.entries()) {
1212
+ if (c.text === undefined || before[i] === c.theirsHash)
1213
+ continue;
1214
+ await this.fs.writeFile(c.wsPath, c.text);
1215
+ }
1216
+ return { text: this.conflictText(plan.conflicts, plan.lww), state: "conflicted", code: "conflicts" };
1217
+ }
1218
+ conflictText(conflicts, lww = []) {
1219
+ const at = (c) => (c.lines === undefined || c.lines.length === 0 ? "" : ` (marked at line${c.lines.length === 1 ? "" : "s"} ${c.lines.join(", ")})`);
1220
+ return [`Merge refused: ${conflicts.length} conflict${conflicts.length === 1 ? "" : "s"}; nothing was written to the live folder`, ...LIMITED(conflicts.map((c) => ` ${c.kind}: ${c.path}${at(c)}`)), ...this.lwwLines(lww), "Resolve them in the live folder or the Workspace (remove the marker blocks, or make the Workspace file equal the live one) and run /conclave merge again, or /conclave discard."].join("\n");
1221
+ }
1222
+ lwwLines(lww) {
1223
+ return LIMITED([...new Map(lww.map((l) => [l.path, l])).values()].map((l) => ` .lww ${l.rule}: ${l.path} kept the ${l.kept === "ours" ? "Workspace" : "live"} side`));
1224
+ }
1225
+ /** GC after each merge, undo or discard, and the store-size notice. */
1226
+ gc() {
1227
+ try {
1228
+ this.cas.gc();
1229
+ const db = this.cas.db;
1230
+ const size = Number(db.prepare("PRAGMA page_count").get().page_count) * Number(db.prepare("PRAGMA page_size").get().page_size);
1231
+ if (size > 1024 ** 3)
1232
+ this.o.notice(`the Workspace store is ${(size / 1024 ** 3).toFixed(1)} GiB after cleanup; /conclave discard held Workspaces you no longer need`);
1233
+ }
1234
+ catch (error) {
1235
+ this.o.notice(`workspace cleanup: ${msg(error)}`);
1236
+ }
1237
+ }
1238
+ /**
1239
+ * The merge of the `run` phase, by the replay table: W is the Workspace with this run key, R its newest merge record for
1240
+ * the key. Only an `open` Workspace with no record merges, and only on a `done` verdict. Nothing here asks the user.
1241
+ */
1242
+ async settle(key, verdict, failure) {
1243
+ const w = this.byKey(key);
1244
+ if (w === undefined)
1245
+ return { text: "the Workspace record for this run is missing; nothing was merged", merge: { state: "held" } };
1246
+ return this.chained(w.project, async () => {
1247
+ const row = this.row(w.id);
1248
+ const r = this.record(row.id, key);
1249
+ const out = (text, extra = {}) => { const now = this.row(row.id); return { text, merge: { state: now.state, ...(r === undefined ? {} : { record: r.id }), ...(now.hold === null ? {} : { code: now.hold }), ...extra } }; };
1250
+ if (r !== undefined && ["planned", "writing", "undoing"].includes(r.state)) {
1251
+ if (row.state === "open") {
1252
+ try {
1253
+ this.hold(row.id, "not-recovered", String(r.id));
1254
+ }
1255
+ catch {
1256
+ return out(`merge record ${r.id} is still ${r.state}; restart piroboros to recover it (its hold could not be written either)`);
1257
+ }
1258
+ }
1259
+ return out(`merge record ${r.id} is still ${r.state}; restart piroboros to recover it`);
1260
+ }
1261
+ if (row.state === "open" && r === undefined) {
1262
+ if (verdict !== "done") {
1263
+ this.hold(row.id, "verdict", failure ?? (verdict === "unknown" ? "without a verdict" : verdict));
1264
+ return out(holdText("verdict", failure ?? (verdict === "unknown" ? "without a verdict" : verdict)));
1265
+ }
1266
+ const down = this.down.get(row.id);
1267
+ if (down !== undefined) {
1268
+ this.hold(row.id, "backend", down);
1269
+ return out(holdText("backend", down));
1270
+ }
1271
+ const result = await this.mergeNow(row, key);
1272
+ return { text: result.text, merge: { state: result.state, ...(result.record === undefined ? {} : { record: result.record }), ...(result.code === undefined ? {} : { code: result.code }) } };
1273
+ }
1274
+ if (row.state === "open") {
1275
+ this.hold(row.id, "not-recovered", String(r.id));
1276
+ return out(`Workspace ${row.id} is open with merge record ${r.id} ${r.state}; nothing was merged`);
1277
+ }
1278
+ if ((row.state === "held" || row.state === "conflicted") && r === undefined)
1279
+ return out(row.state === "conflicted" ? this.conflictText(this.cas.db.prepare("SELECT path, kind FROM conflicts WHERE workspace = ?").all(row.id)) : holdText(row.hold, row.hold_detail));
1280
+ if (row.state === "held" && r !== undefined && (r.state === "rolled back" || r.state === "rollback failed"))
1281
+ return out(r.summary ?? holdText(row.hold, row.hold_detail));
1282
+ if (row.state === "merged" && r !== undefined && ["done", "undone", "undo failed"].includes(r.state)) {
1283
+ if (existsSync(row.folder))
1284
+ await this.removeFolder(row.folder).catch(() => undefined);
1285
+ return out(r.summary ?? "merged");
1286
+ }
1287
+ if ((row.state === "merged" || row.state === "discarded") && r === undefined)
1288
+ return out(row.state === "merged" ? (row.hold_detail === "no changes" ? "Vesperia changed no files; nothing was merged" : "the Workspace was merged by /conclave merge") : (row.hold_detail === "nothing left to merge" ? "ended after /conclave merge, which had nothing left to merge" : "the Workspace was discarded"));
1289
+ return out(`Workspace ${row.id} is ${row.state} with merge record ${r?.id ?? "none"} ${r?.state ?? ""}; nothing was merged`);
1290
+ });
1291
+ }
1292
+ /** Plan and merge an open or confirmed Workspace; holds and conflicts end as states. `confirmed` names the hold codes the user saw. */
1293
+ async mergeNow(row, run, confirmed = new Set(), force = false, seen) {
1294
+ const fail = (code, detail) => { this.hold(row.id, code, detail); return { text: `Merge held: ${holdText(code, detail)}`, state: "held", code }; };
1295
+ try {
1296
+ if (!existsSync(row.folder))
1297
+ return fail("folder-missing", "");
1298
+ }
1299
+ catch {
1300
+ return fail("folder-missing", "");
1301
+ }
1302
+ const info = await this.fs.lstat(row.project, { bigint: true }).catch(() => undefined);
1303
+ if (info === undefined || String(info.dev) !== row.project_dev || String(info.ino) !== row.project_ino)
1304
+ return fail("target-moved", "");
1305
+ const plan = await this.plan(row);
1306
+ if (plan.ignoreFailed)
1307
+ return fail("ignore-rules", "");
1308
+ if (seen !== undefined && shown(plan) !== seen)
1309
+ return { text: "The live folder or the Workspace changed while you answered; nothing was merged. Run /conclave merge again.", state: row.state };
1310
+ if (plan.conflicts.length > 0 && !force)
1311
+ return await this.storeConflicts(row, plan);
1312
+ if (plan.headMoved !== undefined && !confirmed.has("head-moved"))
1313
+ return fail("head-moved", `${plan.headMoved.from} ${plan.headMoved.to}`);
1314
+ if (plan.deletes >= BULK_DELETE && !confirmed.has("bulk-delete"))
1315
+ return fail("bulk-delete", String(plan.deletes));
1316
+ if (plan.oversize.length > 0 && !confirmed.has("oversize"))
1317
+ return fail("oversize", plan.oversize.map((o) => `${o.path} (her version: ${o.ws})`).join("\n"));
1318
+ let rows = plan.rows;
1319
+ if (force) {
1320
+ // Force: her version stored before the markers replaces the live path; her deletions delete. type and case rows are never forced.
1321
+ const extra = [];
1322
+ for (const c of plan.conflicts) {
1323
+ if (c.kind === "type" || c.kind === "case")
1324
+ continue;
1325
+ if (c.liveSize > SNAPSHOT_MAX) {
1326
+ plan.left.push({ path: c.path, reason: "over 64 MiB" });
1327
+ continue;
1328
+ }
1329
+ const live = await this.liveInfo(await this.writer.name(row.project, c.path, row.live_caseless === 1));
1330
+ const pre = live.kind === "file" ? live.hash : null;
1331
+ if (c.ours === null) {
1332
+ if (pre !== null)
1333
+ extra.push({ seq: 0, path: c.path, from: null, op: "delete", pre, post: null, mode: null, preSize: live.kind === "file" ? live.size : 0 });
1334
+ continue;
1335
+ }
1336
+ extra.push({ seq: 0, path: c.path, from: null, op: pre === null ? "create" : "write", pre, post: sha(c.ours), mode: null, preSize: live.kind === "file" ? live.size : 0, postSize: c.ours.length, body: c.ours });
1337
+ }
1338
+ rows = [...rows.filter((r) => r.op === "mkdir"), ...rows.filter((r) => r.op === "delete" || r.op === "rename"), ...extra.filter((r) => r.op === "delete"), ...rows.filter((r) => r.op === "write" || r.op === "create"), ...extra.filter((r) => r.op !== "delete")];
1339
+ rows.forEach((r, i) => { r.seq = i + 1; });
1340
+ }
1341
+ const out = await this.execMerge(row, plan, run, rows);
1342
+ return out;
1343
+ }
1344
+ /* --- commands ---------------------------------------------------------------------------------------------- */
1345
+ async taskState(row) {
1346
+ return (await this.taskStatus?.(row.key.split(":")[0])) ?? "missing";
1347
+ }
1348
+ /** An `open` Workspace whose task is terminal or missing never reached its hold: set it `held` with code `ended`. */
1349
+ async endedRule(project) {
1350
+ for (const row of this.rows("state = 'open'")) {
1351
+ if (project !== undefined && row.project !== project)
1352
+ continue;
1353
+ let state;
1354
+ try {
1355
+ state = await this.taskState(row);
1356
+ }
1357
+ catch (error) {
1358
+ this.o.notice(`the task of Workspace ${row.id} could not be read (${msg(error)}); it is left unchanged`);
1359
+ continue;
1360
+ }
1361
+ if (state === "terminal" || state === "missing")
1362
+ this.hold(row.id, "ended", state);
1363
+ else if (state === "parked")
1364
+ this.hold(row.id, "parked");
1365
+ }
1366
+ }
1367
+ /** Startup, after the harness opens: the ended rule for every Workspace, and a parked task of a `merged` or `discarded` one is returned for abortTask. */
1368
+ async startup(parkedTaskIds) {
1369
+ await this.endedRule();
1370
+ const abort = [];
1371
+ for (const id of parkedTaskIds) {
1372
+ const row = this.rows("key LIKE ?", `${id}:%`)[0];
1373
+ if (row !== undefined && (row.state === "merged" || row.state === "discarded"))
1374
+ abort.push(id);
1375
+ }
1376
+ const held = this.rows("state IN ('held', 'conflicted')");
1377
+ const old = held.filter((r) => this.now() - r.created > 7 * 86_400_000);
1378
+ if (held.length > 2 || old.length > 0)
1379
+ this.o.notice(`${held.length} held Workspaces${old.length > 0 ? `, ${old.length} older than 7 days` : ""}: /conclave merge or /conclave discard them`);
1380
+ await this.sweep();
1381
+ return { abort };
1382
+ }
1383
+ /** Remove folders of the own home hash that no open, held or conflicted Workspace names. */
1384
+ async sweep() {
1385
+ const dir = join(this.wsRoot, this.hash);
1386
+ const keep = new Set(this.rows("state IN ('open', 'held', 'conflicted')").map((r) => String(r.id)));
1387
+ let names;
1388
+ try {
1389
+ names = await this.fs.readdir(dir);
1390
+ }
1391
+ catch {
1392
+ return;
1393
+ }
1394
+ for (const name of names)
1395
+ if (!keep.has(name))
1396
+ await this.removeFolder(join(dir, name)).catch((error) => this.o.notice(`could not remove ${join(dir, name)}: ${msg(error)}`));
1397
+ // The ext4 folders of each distro a Workspace of this store used: ids with no open, held or conflicted row go (only the own home-hash folder is listed).
1398
+ const deps = this.confineDeps();
1399
+ const used = new Map();
1400
+ const engines = new Map();
1401
+ for (const row of this.rows("1 = 1")) {
1402
+ const confine = JSON.parse(row.confine);
1403
+ const c = confine.wsl ?? confine.docker?.remote;
1404
+ if (c !== undefined)
1405
+ used.set(`${c.distro}/${c.user}`, c);
1406
+ if (confine.docker !== undefined)
1407
+ engines.set(`${confine.docker.cli}/${confine.docker.remote?.distro}/${confine.docker.remote?.user}`, confine.docker);
1408
+ }
1409
+ if (deps.wsl !== undefined)
1410
+ for (const c of used.values())
1411
+ await wslSweep(deps.wsl, c, keep).catch((error) => this.o.notice(`could not sweep the sandbox folders in ${c.distro}: ${msg(error)}`));
1412
+ // Containers of this home hash with no `open` row. ponytail: an orphan is found only through an engine some row of this store used.
1413
+ const open = new Set(this.rows("state = 'open'").map((r) => String(r.id)));
1414
+ for (const c of engines.values())
1415
+ await dockerSweep(deps, c, this.hash, open).catch((error) => this.o.notice(`could not sweep the containers: ${msg(error)}`));
1416
+ }
1417
+ /** Never rmSync recursive over a Workspace: links are removed as links, then the real folders. */
1418
+ async removeFolder(dir, known) {
1419
+ const walk = async (d) => {
1420
+ let list;
1421
+ try {
1422
+ list = await this.fs.readdir(d, { withFileTypes: true });
1423
+ }
1424
+ catch {
1425
+ return;
1426
+ }
1427
+ for (const e of list) {
1428
+ const p = join(d, e.name);
1429
+ if (e.isSymbolicLink())
1430
+ await this.fs.unlink(p).catch(() => this.fs.rmdir(p));
1431
+ else if (e.isDirectory())
1432
+ await walk(p);
1433
+ }
1434
+ };
1435
+ await walk(dir);
1436
+ await this.fs.rm(dir, { recursive: true, force: true, maxRetries: 5 });
1437
+ let confine = known;
1438
+ try {
1439
+ confine ??= JSON.parse(this.rows("folder = ?", dir)[0]?.confine ?? "{}");
1440
+ }
1441
+ catch { /* no row */ }
1442
+ const deps = this.confineDeps();
1443
+ if (confine?.docker !== undefined)
1444
+ await dockerRemove(deps, confine.docker).catch((error) => this.o.notice(`the container ${confine.docker?.container.slice(0, 12)} could not be removed: ${msg(error)}`));
1445
+ const remote = confine?.wsl ?? confine?.docker?.remote;
1446
+ if (remote !== undefined && deps.wsl !== undefined)
1447
+ await wslRemove(deps.wsl, remote).catch((error) => this.o.notice(`the sandbox folder ${remote.ext4} could not be removed: ${msg(error)}`));
1448
+ }
1449
+ /**
1450
+ * `/conclave merge` on a held or conflicted Workspace: plan again, one prompt for every pending reason, then the merge (or
1451
+ * force). Returns the reply, and whether the Workspace ended (merged or discarded).
1452
+ */
1453
+ async mergeCommand(id, ask) {
1454
+ const first = this.row(id);
1455
+ if (first === undefined)
1456
+ return { text: "nothing to merge", ended: false };
1457
+ // The prompt is asked outside the chain, so a checkpoint or another Workspace's operation never waits for the user's answer; the merge re-enters the chain and plans again.
1458
+ const step = await this.chained(first.project, async () => {
1459
+ const row = this.row(id);
1460
+ if (row.state !== "held" && row.state !== "conflicted")
1461
+ return { text: "nothing to merge", ended: false };
1462
+ if (!existsSync(row.folder)) {
1463
+ this.hold(row.id, "folder-missing");
1464
+ return { text: `Merge held: ${holdText("folder-missing", null)}`, ended: false };
1465
+ }
1466
+ const plan = await this.plan(row);
1467
+ const reasons = [];
1468
+ const confirmed = new Set();
1469
+ if (row.state === "held" && row.hold !== "conflicts")
1470
+ reasons.push(holdText(row.hold, row.hold_detail));
1471
+ if (plan.headMoved !== undefined) {
1472
+ reasons.push(holdText("head-moved", `${plan.headMoved.from} ${plan.headMoved.to}`));
1473
+ confirmed.add("head-moved");
1474
+ }
1475
+ if (plan.deletes >= BULK_DELETE) {
1476
+ reasons.push(holdText("bulk-delete", String(plan.deletes)));
1477
+ confirmed.add("bulk-delete");
1478
+ }
1479
+ if (plan.oversize.length > 0) {
1480
+ reasons.push(holdText("oversize", plan.oversize.map((o) => `${o.path} (her version: ${o.ws})`).join("\n")));
1481
+ confirmed.add("oversize");
1482
+ }
1483
+ const over = plan.oversize.length > 0 || plan.conflicts.some((c) => c.liveSize > SNAPSHOT_MAX);
1484
+ const finish = (out) => ({ text: out.text, ended: out.state === "merged" || out.state === "discarded" });
1485
+ if (plan.conflicts.length > 0) {
1486
+ const stored = await this.storeConflicts(row, plan);
1487
+ if (plan.conflicts.some((c) => c.kind === "type" || c.kind === "case"))
1488
+ return { text: `${stored.text}\nForce is not offered while a type or case conflict is unresolved.`, ended: false };
1489
+ const lines = LIMITED(plan.conflicts.map((c) => `${c.kind} ${c.path}: ${c.liveSize > SNAPSHOT_MAX ? `not merged: over 64 MiB (her version: ${c.wsPath}); copy it yourself first: the Workspace is removed after the merge` : c.ours === null ? "her deletion deletes the live file" : "her version replaces the live file"}`));
1490
+ return { question: [...reasons, ...lines, `Replace your version of these ${plan.conflicts.length} paths with Vesperia's? (her version from before the markers; her deletions delete)`].join("\n"), no: { text: `${stored.text}\nmerge not run; nothing was changed`, ended: false }, go: async (r) => finish(await this.mergeNow(r, null, confirmed, true, shown(plan))) };
1491
+ }
1492
+ const question = over ? "Merge the other paths? The Workspace, with Vesperia's version of these files, is removed after the merge." : "Merge Vesperia's changes?";
1493
+ return { question: [...reasons, question].join("\n"), no: { text: "merge not run; the Workspace stays held", ended: false }, go: async (r) => finish(await this.mergeNow(r, null, confirmed, false, shown(plan))) };
1494
+ });
1495
+ if (!("question" in step))
1496
+ return step;
1497
+ if (!(await ask(step.question)))
1498
+ return step.no;
1499
+ return this.chained(first.project, async () => {
1500
+ const row = this.row(id);
1501
+ if (row === undefined || (row.state !== "held" && row.state !== "conflicted"))
1502
+ return { text: "nothing to merge", ended: false };
1503
+ return step.go(row);
1504
+ });
1505
+ }
1506
+ /** `/conclave discard`: ask (outside the chain), remove the folder, mark discarded. */
1507
+ async discardCommand(id, ask) {
1508
+ const first = this.row(id);
1509
+ if (first === undefined)
1510
+ return { text: "nothing to discard", ended: false };
1511
+ const question = await this.chained(first.project, async () => {
1512
+ const row = this.row(id);
1513
+ if (row.state !== "held" && row.state !== "conflicted")
1514
+ return undefined;
1515
+ const n = this.changedPaths(row.id).length;
1516
+ return `${holdText(row.hold, row.hold_detail)}\nDiscard Vesperia's Workspace, with ${n} changed file${n === 1 ? "" : "s"}? Nothing in the live folder changes.`;
1517
+ });
1518
+ if (question === undefined)
1519
+ return { text: "nothing to discard", ended: false };
1520
+ if (!(await ask(question)))
1521
+ return { text: "discard cancelled", ended: false };
1522
+ return this.chained(first.project, async () => {
1523
+ const row = this.row(id);
1524
+ if (row.state !== "held" && row.state !== "conflicted")
1525
+ return { text: "nothing to discard", ended: false };
1526
+ this.set(row.id, { state: "discarded", hold: null, hold_detail: null });
1527
+ await this.removeFolder(row.folder).catch((error) => this.o.notice(`the Workspace folder could not be removed: ${msg(error)}`));
1528
+ this.gc();
1529
+ return { text: `Workspace discarded; ${row.project} was not changed`, ended: true };
1530
+ });
1531
+ }
1532
+ /** `/conclave retry` on a parked task: a `parked` hold goes back to `open` first. */
1533
+ reopenParked(id) { const row = this.row(id); if (row?.state === "held" && row.hold === "parked")
1534
+ this.set(id, { state: "open", hold: null, hold_detail: null }); }
1535
+ /** The abort handler: hold an `open` Workspace as cancelled, and say what the Workspace state is. */
1536
+ cancelled(key) {
1537
+ const row = this.byKey(key);
1538
+ if (row === undefined)
1539
+ return undefined;
1540
+ if (row.state === "open")
1541
+ this.hold(row.id, "cancelled");
1542
+ const w = this.row(row.id);
1543
+ const r = this.record(w.id, key);
1544
+ const merge = { state: w.state, ...(r === undefined ? {} : { record: r.id }), ...(w.hold === null ? {} : { code: w.hold }) };
1545
+ if (row.state === "open")
1546
+ return { text: "", verdict: "failed", merge };
1547
+ if (w.state === "held" || w.state === "conflicted")
1548
+ return { text: `Vesperia's run was cancelled; its Workspace stays ${w.state}: ${w.state === "conflicted" ? holdText("conflicts", w.hold_detail) : holdText(w.hold, w.hold_detail)}`, verdict: "failed", merge };
1549
+ if (w.state === "merged" && r !== undefined && r.state === "done")
1550
+ return { text: `Vesperia's run was cancelled after its merge: ${r.summary}`, verdict: "done", merge };
1551
+ if (w.state === "merged")
1552
+ return { text: `ended after /conclave merge: ${this.cas.db.prepare("SELECT summary FROM merges WHERE workspace = ? ORDER BY id DESC LIMIT 1").get(w.id)?.summary ?? "nothing was merged"}`, verdict: "failed", merge };
1553
+ return { text: w.hold_detail === "nothing left to merge" ? "ended after /conclave merge, which had nothing left to merge" : "ended after /conclave discard", verdict: "failed", merge };
1554
+ }
1555
+ /** `/conclave status`: the Workspace state, hold text, mode and its source, folder, checkpoints and confinement. */
1556
+ statusLines(project, from, parked = false) {
1557
+ const w = this.rows("project = ?", canonicalize(project))[0];
1558
+ if (w === undefined)
1559
+ return [];
1560
+ const commits = Number(this.cas.db.prepare("SELECT COUNT(*) AS n FROM commits WHERE workspace = ? AND kind = 'checkpoint'").get(w.id).n);
1561
+ return [`Workspace ${w.id}: ${w.state}${w.hold === null ? "" : ` (${holdText(w.hold, w.hold_detail)})`}${parked ? " [task parked]" : ""}`, ` mode ${w.mode}${from === undefined ? "" : ` (${from})`}, folder ${w.folder}, ${commits} checkpoint${commits === 1 ? "" : "s"}`, (() => { const c = JSON.parse(w.confine); return c.name !== "none" ? ` shell confinement: ${c.name}${c.docker === undefined ? "" : ` (${c.docker.image})`}${c.wsl === undefined && c.docker?.remote === undefined ? "" : ` in WSL (${(c.wsl ?? c.docker.remote).distro})`}, network ${c.net === false ? "off" : "on"}` : ` shell confinement: none; commands are not confined${c.why === undefined ? "" : ` (${c.why})`}`; })()];
1562
+ }
1563
+ /* --- undo -------------------------------------------------------------------------------------------------- */
1564
+ /** The newest merge record of a project, for `/conclave undo`. */
1565
+ latestRecord(project) {
1566
+ const r = this.cas.db.prepare("SELECT m.id, m.state, m.workspace AS ws, w.live_caseless AS c FROM merges m JOIN workspaces w ON w.id = m.workspace WHERE m.project = ? ORDER BY m.id DESC LIMIT 1").get(canonicalize(project));
1567
+ return r === undefined ? undefined : { id: r.id, state: r.state, ws: r.ws, caseless: r.c === 1 };
1568
+ }
1569
+ /** `/conclave undo` of the newest merge record of a project. Returns the reply and whether files were restored. */
1570
+ async undoCommand(projectIn, ask) {
1571
+ const project = canonicalize(projectIn);
1572
+ const r = this.latestRecord(project);
1573
+ if (r === undefined)
1574
+ return undefined;
1575
+ return this.chained(project, async () => {
1576
+ const rec = this.latestRecord(project);
1577
+ if (rec.state === "undone")
1578
+ return { text: "already undone", restored: false };
1579
+ if (rec.state === "rolled back")
1580
+ return { text: "the last merge was rolled back; nothing to undo", restored: false };
1581
+ if (["planned", "writing", "undoing"].includes(rec.state))
1582
+ return { text: "a merge or undo was interrupted; restart piroboros to recover it", restored: false };
1583
+ const verdicts = await this.writer.preview(rec.id, project, rec.caseless);
1584
+ const pick = (v) => verdicts.filter((x) => x.verdict === v).map((x) => ` ${x.row.path}${x.reason === undefined ? "" : ` (${x.reason})`}`);
1585
+ const list = (title, lines) => (lines.length === 0 ? [] : [`${title} (${lines.length}):`, ...lines]);
1586
+ const preview = ["Undo of the last Vesperia merge.", ...list("Files to restore", pick("restore")), ...list("Files and folders to remove (created by the merge)", pick("remove")), ...list("Skipped, changed since the merge", pick("changed")), ...list("Skipped, protected", pick("protected")), ...list("Already as before the merge", pick("unchanged")), "Changes made through bash are covered: the merge applied them."].join("\n");
1587
+ if (!(await ask(`${preview}\nRestore these files?`)))
1588
+ return { text: "undo cancelled; nothing was changed", restored: false };
1589
+ const out = await this.writer.finishUndo(rec.id, project, rec.caseless);
1590
+ this.gc();
1591
+ return { text: out.text, restored: out.state === "undone" || verdicts.some((v) => v.verdict === "restore" || v.verdict === "remove") };
1592
+ });
1593
+ }
1594
+ /** Startup: roll back or finish every merge record the last run left behind, before the scheduler starts. */
1595
+ recover() { return this.writer.recover(); }
1596
+ }