piroboros 0.3.2 → 0.3.4

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.
@@ -1,12 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
2
+ import { constants, existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { basename, dirname, join, relative, resolve } from "node:path";
5
- import { checkPath, checkRead, WIDE_SECRET } from "../guard.js";
5
+ import { checkPath, checkRead, denyRoots, WIDE_SECRET } from "../guard.js";
6
6
  import { canonicalize, isInside, samePath } from "../paths.js";
7
7
  import { ConflictFound, HoldError, realFs, Writer } from "./apply.js";
8
- import { confineFor, nativeDeps } from "./confine.js";
9
- import { dockerRemove, dockerSweep } from "./docker.js";
8
+ import { needsRepick, confineFor, nativeDeps } from "./confine.js";
9
+ import { dockerKill, dockerRemove, dockerSweep } from "./docker.js";
10
10
  import { wslRemove, wslSweep } from "./wsl.js";
11
11
  import { BATCH_BYTES, Cas, OPEN_BATCH, pack, SNAPSHOT_MAX } from "./cas.js";
12
12
  import { HostGit, WsRefusal } from "./git.js";
@@ -51,6 +51,7 @@ export function holdText(code, detail) {
51
51
  case "rollback": return `merge ${d} was rolled back`;
52
52
  case "backend": return `confinement backend unavailable: ${d}`;
53
53
  case "ignore-rules": return "the live ignore rules could not be read";
54
+ case "unreadable": return `folders in the Workspace could not be read (${d.split("\n").join(", ")}), so what they hold cannot be merged or told deleted; fix their permissions, then /conclave merge`;
54
55
  case "target-moved": return "the project folder is not the one the Workspace was opened for";
55
56
  case "folder-missing": return "the Workspace folder is missing";
56
57
  case "not-recovered": return `merge record ${d} was not recovered`;
@@ -60,6 +61,100 @@ export function holdText(code, detail) {
60
61
  }
61
62
  }
62
63
  const LIMITED = (items, max = 20) => (items.length > max ? [...items.slice(0, max), `and ${items.length - max} more`] : items);
64
+ /**
65
+ * Host access below a Workspace folder after Vesperia has had it: she can replace any folder in it with a link. Every component
66
+ * from the folder down to the parent of the leaf is lstat-ed and must be a real folder (`make` creates a missing one), and a
67
+ * leaf that exists must be a regular file. A write goes to a new name in the same folder and is renamed over the leaf, which
68
+ * replaces a link and never follows it; a delete unlinks the leaf only. A link or a non-folder refuses with a WsRefusal.
69
+ */
70
+ async function wsDir(fs, folder, parts, make) {
71
+ let cur = folder;
72
+ for (const part of parts) {
73
+ cur = join(cur, part);
74
+ let info = await fs.lstat(cur).catch((error) => { if (make && code(error) === "ENOENT")
75
+ return undefined; throw error; });
76
+ if (info === undefined) {
77
+ await fs.mkdir(cur);
78
+ info = await fs.lstat(cur);
79
+ }
80
+ if (!info.isDirectory())
81
+ throw new WsRefusal(`${cur} in the Workspace is a link or not a folder`);
82
+ }
83
+ return cur;
84
+ }
85
+ /**
86
+ * `refused(rel)`: whether the guard refuses reading `rel` under `project` (nested guard.deny, a credential folder inside a guard.allow folder). A checkRead costs about
87
+ * 0.8 ms, which was 20 s over 24,000 files, and below a folder the verdict does not depend on the file name (secret names are filtered before this), so it is asked once
88
+ * per folder. Under a deny root that lies inside the project, and when a root cannot be evaluated, each path is asked itself.
89
+ */
90
+ function readRefuser(project, cfg) {
91
+ const inner = [];
92
+ let each = false;
93
+ for (const root of denyRoots(cfg)) {
94
+ try {
95
+ const c = canonicalize(root);
96
+ if (isInside(project, c))
97
+ inner.push(c);
98
+ }
99
+ catch {
100
+ each = true;
101
+ }
102
+ }
103
+ const folders = new Map();
104
+ return (rel) => {
105
+ const abs = join(project, ...rel.split("/"));
106
+ if (each || inner.some((r) => isInside(r, abs)))
107
+ return !checkRead(abs, undefined, cfg).allowed;
108
+ const dir = dirname(abs);
109
+ let allowed = folders.get(dir);
110
+ if (allowed === undefined) {
111
+ allowed = checkRead(join(dir, ".piroboros-folder"), undefined, cfg).allowed;
112
+ folders.set(dir, allowed);
113
+ }
114
+ return !allowed;
115
+ };
116
+ }
117
+ let putSeq = 0;
118
+ async function wsPut(fs, folder, rel, src) {
119
+ const parts = rel.split("/");
120
+ const dir = await wsDir(fs, folder, parts.slice(0, -1), false);
121
+ const leaf = join(dir, parts.at(-1));
122
+ const old = await fs.lstat(leaf).catch(() => undefined);
123
+ if (old !== undefined && !old.isFile())
124
+ throw new WsRefusal(`${leaf} in the Workspace is a link or not a regular file`);
125
+ const tmp = join(dir, `.${parts.at(-1)}.piroboros-new-${process.pid}-${++putSeq}`);
126
+ try {
127
+ if ("file" in src)
128
+ await fs.copyFile(src.file, tmp, constants.COPYFILE_EXCL);
129
+ else {
130
+ const fh = await fs.open(tmp, "wx", (old?.mode ?? 0o644) & 0o777);
131
+ try {
132
+ await fh.writeFile(src.bytes);
133
+ }
134
+ finally {
135
+ await fh.close();
136
+ }
137
+ }
138
+ await fs.rename(tmp, leaf);
139
+ }
140
+ catch (error) {
141
+ await fs.unlink(tmp).catch(() => undefined);
142
+ throw error;
143
+ }
144
+ }
145
+ /** Whether a file was removed (false: it or a parent was not there). */
146
+ async function wsUnlink(fs, folder, rel) {
147
+ const parts = rel.split("/");
148
+ try {
149
+ await fs.unlink(join(await wsDir(fs, folder, parts.slice(0, -1), false), parts.at(-1)));
150
+ return true;
151
+ }
152
+ catch (error) {
153
+ if (code(error) === "ENOENT")
154
+ return false;
155
+ throw error;
156
+ }
157
+ }
63
158
  export class Workspaces {
64
159
  cas;
65
160
  git;
@@ -75,6 +170,7 @@ export class Workspaces {
75
170
  queued = new Set();
76
171
  /** 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
172
  down = new Map();
173
+ upgrades = new Map();
78
174
  chainKeys = new Map();
79
175
  taskStatus;
80
176
  constructor(options) {
@@ -264,28 +360,22 @@ export class Workspaces {
264
360
  throw new WsRefusal("Vesperia is already working on this project in another conversation; wait for that run or /conclave cancel it there");
265
361
  if (same.plan !== plan)
266
362
  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
363
  const earlier = JSON.parse(same.confine);
364
+ await this.quiet(same);
272
365
  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
366
  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 });
367
+ const picked = await this.pick(same.folder, { places, project, files: 0, prev: earlier.wsl, prevDocker: earlier.docker });
278
368
  if (onWsl(picked.confine))
279
369
  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`);
370
+ await wsDir(this.fs, same.folder, place.split("/"), true);
371
+ // A Workspace of 0.3.2 or earlier borrowed the live repository's objects through this file. It goes (the leaf only, through no link), and no object folder is bound or mounted any more.
372
+ const history = same.mode === "git" ? await wsUnlink(this.fs, same.folder, ".git/objects/info/alternates").catch((error) => { this.o.notice(`the Workspace's git alternates file could not be removed (${msg(error)})`); return false; }) : false;
283
373
  this.down.delete(same.id);
284
374
  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
375
  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
376
  if (same.conv !== null)
287
377
  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] };
378
+ 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, ...(history ? ["Git history is no longer available in this Workspace; its files are unchanged."] : [])] };
289
379
  }
290
380
  return this.copyIn(key, mode, project, plan);
291
381
  });
@@ -300,22 +390,34 @@ export class Workspaces {
300
390
  const changed = [];
301
391
  const deleted = [];
302
392
  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);
393
+ const denied = readRefuser(row.project, this.o.guard());
394
+ const todo = [...this.baseOf(row.id)].filter(([p, b]) => b.kind === "file" && b.hash !== null && head.get(p)?.hash === b.hash && !p.split("/").some((part) => LINK_NAMES.includes(part)));
395
+ const refused = [];
304
396
  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;
397
+ // Every write below goes through the link-safe helpers: Vesperia may have replaced a folder of the Workspace with a link. A path refused there is skipped.
398
+ try {
399
+ const live = await this.liveInfo(await this.writer.name(row.project, p, row.live_caseless === 1));
400
+ if (live.kind === "absent") {
401
+ await wsUnlink(this.fs, row.folder, p).catch((error) => { if (error instanceof WsRefusal)
402
+ throw error; });
403
+ deleted.push(p);
404
+ return;
405
+ }
406
+ if (live.kind !== "file" || live.hash === b.hash)
407
+ return;
408
+ if (denied(p))
409
+ return;
410
+ await wsPut(this.fs, row.folder, p, live.bytes !== undefined ? { bytes: live.bytes } : { file: join(row.project, ...p.split("/")) });
411
+ changed.push({ path: p, hash: live.hash, size: live.size, mtime: Math.floor((await this.fs.lstat(wsPath(p))).mtimeMs), link: false });
412
+ }
413
+ catch (error) {
414
+ if (!(error instanceof WsRefusal))
415
+ throw error;
416
+ refused.push(msg(error));
310
417
  }
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
418
  });
419
+ if (refused.length > 0)
420
+ this.o.notice(`the refresh skipped ${refused.length} path${refused.length === 1 ? "" : "s"} of the Workspace: ${LIMITED(refused, 3).join("; ")}`);
319
421
  await this.checkpoint(row, changed, deleted, [], "refresh");
320
422
  return changed.length + deleted.length;
321
423
  }
@@ -353,11 +455,21 @@ export class Workspaces {
353
455
  const dev = (await this.fs.lstat(project, { bigint: true }));
354
456
  const items = [];
355
457
  const missing = [];
458
+ const denied = readRefuser(project, cfg);
356
459
  await this.pool(listed, 16, async (path) => {
357
460
  if (WIDE_SECRET.some((p) => p.test(basename(path)))) {
358
461
  secrets.push(path);
359
462
  return;
360
463
  }
464
+ // A path with a node_modules component starts empty (the scan never looks there, so a copied file would read as deleted); a path guard.deny holds stays out.
465
+ if (path.split("/").some((part) => LINK_NAMES.includes(part))) {
466
+ skipped.push(`${path} (inside a folder that starts empty)`);
467
+ return;
468
+ }
469
+ if (denied(path)) {
470
+ skipped.push(`${path} (protected)`);
471
+ return;
472
+ }
361
473
  try {
362
474
  const info = await this.fs.lstat(join(project, path));
363
475
  if (info.isDirectory()) {
@@ -400,9 +512,8 @@ export class Workspaces {
400
512
  }
401
513
  let chosen;
402
514
  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);
515
+ const total = items.length;
516
+ const bytes = items.reduce((n, i) => n + i.size, 0);
406
517
  if (total > FILE_BOUND)
407
518
  refuse(`${project} has ${total} files to copy, over the limit of ${FILE_BOUND}; set workspace.enabled to false to run in place`);
408
519
  if (bytes > BYTE_BOUND)
@@ -468,9 +579,6 @@ export class Workspaces {
468
579
  // LINK_NAMES folders (node_modules) start as empty real folders: no link into the live project, ever.
469
580
  for (const rel of links)
470
581
  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
582
  // Stat every copied path: a path missing or of another size after the copy becomes `skipped`.
475
583
  const stats = new Map();
476
584
  await this.pool([...ents.values()].filter((e) => e.kind !== "skipped"), 16, async (e) => {
@@ -489,27 +597,28 @@ export class Workspaces {
489
597
  }
490
598
  });
491
599
  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
600
  const objectIds = [...ents.values()].flatMap((e) => (e.object === null ? [] : [e.object]));
496
601
  const places = [...new Set([...links, "node_modules"])];
497
- const picked = await this.pick(folder, { places, alt, project, files: items.length });
602
+ const picked = await this.pick(folder, { places, project, files: items.length });
498
603
  chosen = picked.confine;
499
604
  if (onWsl(chosen))
500
605
  for (const place of places)
501
606
  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")
607
+ // A git Workspace is its own repository: one commit of the files just copied. Nothing of the live .git comes along (no object, ref, index or reflog), so a credential committed once and deleted since is not in it.
608
+ if (mode === "git" && state.kind === "tree") {
609
+ await this.git.init(folder, await this.git.branch(project));
610
+ await this.fs.writeFile(join(folder, ".git", "config"), await this.git.copyConfig(state.gitDir));
505
611
  await this.liveLineEndings(project, folder);
612
+ const copied = new Map(items.map((i) => [i.path, i]));
613
+ await this.git.baseCommit(folder, [...ents.values()].filter((e) => e.kind !== "skipped").map((e) => { const i = copied.get(e.path); return { path: e.path, mode: e.kind === "link" ? "120000" : i.mode & 0o111 ? "100755" : "100644", size: stats.get(e.path).size, ...(i.link === undefined ? {} : { link: i.link }) }; }));
614
+ }
506
615
  let baseId = 0;
507
616
  this.cas.tx(() => {
508
617
  if (this.cas.missing(objectIds).length > 0)
509
618
  throw new WsRefusal("the store dropped objects of this copy while it was made; approve again");
510
619
  const confine = JSON.stringify(picked.confine);
511
620
  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());
621
+ .run(id, key, project, String(dev.dev), String(dev.ino), mode, head, null, plan, folder, wsCaseless ? 1 : 0, liveCaseless ? 1 : 0, confine, this.now());
513
622
  baseId = Number(this.cas.db.prepare("INSERT INTO commits(workspace, parent, kind, at, note) VALUES (?, NULL, 'base', ?, 'open')").run(id, this.now()).lastInsertRowid);
514
623
  const entry = this.cas.db.prepare('INSERT INTO entries("commit", path, object, hash, size, kind) VALUES (?, ?, ?, ?, ?, ?)');
515
624
  const stat = this.cas.db.prepare("INSERT INTO ws_stat VALUES (?, ?, ?, ?, ?)");
@@ -563,52 +672,7 @@ export class Workspaces {
563
672
  await walk(project, "");
564
673
  return out;
565
674
  }
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. */
675
+ /** The Workspace's repository does not read the host's system and global config (Linux git in a sandbox never does): copy the live repository's effective core.autocrlf and core.eol into its own config, before the base commit. */
612
676
  async liveLineEndings(project, folder) {
613
677
  const lines = [];
614
678
  for (const name of ["autocrlf", "eol"]) {
@@ -633,8 +697,10 @@ export class Workspaces {
633
697
  changedPaths(ws, head = this.headOf(ws), base = this.baseOf(ws)) {
634
698
  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
699
  }
700
+ /** The files of the Workspace by their paths, and the folders below the root that could not be listed (a folder that vanished during the walk is not one of them). */
636
701
  async walkWs(folder) {
637
702
  const out = new Map();
703
+ const unreadable = [];
638
704
  const walk = async (dir, rel) => {
639
705
  let list;
640
706
  try {
@@ -643,6 +709,8 @@ export class Workspaces {
643
709
  catch (error) {
644
710
  if (rel === "")
645
711
  throw error;
712
+ if (code(error) !== "ENOENT" && code(error) !== "ENOTDIR")
713
+ unreadable.push(rel);
646
714
  return;
647
715
  }
648
716
  for (const e of list) {
@@ -656,12 +724,14 @@ export class Workspaces {
656
724
  }
657
725
  };
658
726
  await walk(folder, "");
659
- return out;
727
+ return { out, unreadable };
660
728
  }
661
- /** Compare the Workspace with its stat rows and checkpoint what changed. Returns the new git-ignored paths and whether the ignore check failed. */
729
+ /** Compare the Workspace with its stat rows and checkpoint what changed. Returns the new git-ignored paths, whether the ignore check failed, and the folders that could not be read (what they hold is neither changed nor deleted here). */
662
730
  async scanNow(row, only, force = false) {
663
731
  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"]));
732
+ const walked = only === undefined ? await this.walkWs(row.folder) : undefined;
733
+ const onDisk = walked?.out ?? new Map(only.map((p) => [p, "file"]));
734
+ const unreadable = walked?.unreadable ?? [];
665
735
  const candidates = only ?? [...new Set([...onDisk.keys(), ...stat.keys()])];
666
736
  const changed = [];
667
737
  const deleted = [];
@@ -670,7 +740,7 @@ export class Workspaces {
670
740
  await this.pool(candidates, 16, async (path) => {
671
741
  // 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
742
  if (only === undefined && !onDisk.has(path)) {
673
- if (stat.has(path))
743
+ if (stat.has(path) && !unreadable.some((dir) => path.startsWith(`${dir}/`)))
674
744
  deleted.push(path);
675
745
  return;
676
746
  }
@@ -720,7 +790,7 @@ export class Workspaces {
720
790
  }
721
791
  }
722
792
  await this.checkpoint(row, [...changed, ...adds], deleted, touch);
723
- return { ignoredNew, ignoreFailed };
793
+ return { ignoredNew, ignoreFailed, unreadable };
724
794
  }
725
795
  /** Insert the changed paths as `checkpoint` commits, in batches by the CAS rule, each batch with its objects in one transaction. */
726
796
  async checkpoint(row, changed, deleted, touch, kind = "checkpoint") {
@@ -805,6 +875,58 @@ export class Workspaces {
805
875
  const s = this.o.settings();
806
876
  return confineFor({ confine: s.confine ?? "auto", network: s.network ?? true, distro: s.wslDistro, docker: s.dockerImage }, this.confineDeps(), folder, plan);
807
877
  }
878
+ /**
879
+ * Before a host pass over a Workspace: end every process in its container. bubblewrap (native and in WSL) already ends every
880
+ * process with its command (--die-with-parent --unshare-all: the sandbox's PID namespace goes with it), but a `docker exec`
881
+ * process can outlive its command in the long-lived container and race the host's reads and writes.
882
+ */
883
+ async quiet(row) {
884
+ try {
885
+ const c = JSON.parse(row.confine).docker;
886
+ if (c !== undefined)
887
+ await dockerKill(this.confineDeps(), c);
888
+ }
889
+ catch { /* no container, or an engine that does not answer: the pass goes on */ }
890
+ }
891
+ /**
892
+ * A Workspace of 0.3.1 or 0.3.2 (a sandbox that bound the live git objects) or of 0.3.3 before the system-folders view (a WSL argv that binds the whole root), resumed without a reopen (a retry or a restart), still stores an old sandbox. Before its first command: the backend is picked again
893
+ * (the code reopen uses; a Docker container is replaced by a fresh one), which drops the stored `alt` and the object binds, and the alternates file is removed once with a notice. A replacement that fails marks the Workspace
894
+ * down, so the run ends held with code `backend`.
895
+ */
896
+ upgradeOld(id) {
897
+ let done = this.upgrades.get(id);
898
+ if (done === undefined) {
899
+ done = (async () => {
900
+ const row = this.row(id);
901
+ if (row === undefined)
902
+ return;
903
+ await this.chained(row.project, async () => {
904
+ const old = JSON.parse(row.confine);
905
+ try {
906
+ // The stored WSL argv and the Docker mounts hold the object binds, so the backend is picked again as a reopen does (a Docker container is removed and a fresh one made first).
907
+ const places = (old.wsl ?? old.docker).places;
908
+ const picked = await this.pick(row.folder, { places, project: row.project, files: 0, prev: old.wsl, prevDocker: old.docker });
909
+ if (picked.confine.name !== old.name)
910
+ throw new Error(picked.confine.why ?? `${old.name} could not be started again`);
911
+ if (onWsl(picked.confine))
912
+ for (const place of places)
913
+ await wsDir(this.fs, row.folder, place.split("/"), true);
914
+ this.o.notice(`Shell confinement of this Workspace: ${picked.label}.`);
915
+ const history = row.mode === "git" ? await wsUnlink(this.fs, row.folder, ".git/objects/info/alternates").catch((error) => { this.o.notice(`the Workspace's git alternates file could not be removed (${msg(error)})`); return false; }) : false;
916
+ this.cas.db.prepare("UPDATE workspaces SET confine = ? WHERE id = ?").run(JSON.stringify(picked.confine), id);
917
+ this.refresh(id);
918
+ if (history)
919
+ this.o.notice("Git history is no longer available in this Workspace; its files are unchanged.");
920
+ }
921
+ catch (error) {
922
+ this.down.set(id, `this Workspace's stored sandbox is out of date and could not be replaced (${msg(error)}); approve the run again to reopen it`);
923
+ }
924
+ });
925
+ })();
926
+ this.upgrades.set(id, done);
927
+ }
928
+ return done;
929
+ }
808
930
  /** The open Workspace a shell cwd lies in, when its row names a backend: what ConfinedShellEnv wraps the command with. */
809
931
  shellFor(cwd) {
810
932
  for (const row of this.byConv.values()) {
@@ -813,7 +935,7 @@ export class Workspaces {
813
935
  try {
814
936
  const confine = JSON.parse(row.confine);
815
937
  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); } };
938
+ return { ws: row.folder, project: row.project, confine, deps: this.confineDeps(), down: this.down.get(row.id), mark: (reason) => { this.down.set(row.id, reason); }, ...(needsRepick(confine) && !this.down.has(row.id) ? { upgrade: () => this.upgradeOld(row.id) } : {}) };
817
939
  }
818
940
  catch { /* not this row */ }
819
941
  }
@@ -928,6 +1050,8 @@ export class Workspaces {
928
1050
  const refuseReason = (p, e, b) => {
929
1051
  if (b?.kind === "skipped")
930
1052
  return "skipped at open";
1053
+ if (p.split("/").some((part) => LINK_NAMES.includes(part)))
1054
+ return "inside node_modules";
931
1055
  if (e?.kind === "link")
932
1056
  return "link";
933
1057
  if (/[\\:*?"<>|-]/u.test(basename(p)) || /[. ]$/u.test(basename(p)))
@@ -1105,7 +1229,7 @@ export class Workspaces {
1105
1229
  c.ours = items.get(c.path)?.over ?? await this.fs.readFile(wsAbs(c.path)).catch(() => null);
1106
1230
  }
1107
1231
  const plan = {
1108
- rows: ordered, conflicts, left, oversize, deletes: ordered.filter((r) => r.op === "delete").length, ignored: scan.ignoredNew, ignoreFailed: scan.ignoreFailed, lww,
1232
+ rows: ordered, conflicts, left, oversize, deletes: ordered.filter((r) => r.op === "delete").length, ignored: scan.ignoredNew, ignoreFailed: scan.ignoreFailed, unreadable: scan.unreadable, lww,
1109
1233
  redecide: async (r, bytes) => {
1110
1234
  const item = items.get(r.path);
1111
1235
  if (item === undefined || r.op === "rename" || r.op === "mkdir")
@@ -1211,7 +1335,14 @@ export class Workspaces {
1211
1335
  for (const [i, c] of plan.conflicts.entries()) {
1212
1336
  if (c.text === undefined || before[i] === c.theirsHash)
1213
1337
  continue;
1214
- await this.fs.writeFile(c.wsPath, c.text);
1338
+ try {
1339
+ await wsPut(this.fs, row.folder, c.path, { bytes: c.text });
1340
+ }
1341
+ catch (error) {
1342
+ if (!(error instanceof WsRefusal))
1343
+ throw error;
1344
+ this.o.notice(`the conflict markers for ${c.path} were not written: ${msg(error)}`);
1345
+ }
1215
1346
  }
1216
1347
  return { text: this.conflictText(plan.conflicts, plan.lww), state: "conflicted", code: "conflicts" };
1217
1348
  }
@@ -1302,9 +1433,12 @@ export class Workspaces {
1302
1433
  const info = await this.fs.lstat(row.project, { bigint: true }).catch(() => undefined);
1303
1434
  if (info === undefined || String(info.dev) !== row.project_dev || String(info.ino) !== row.project_ino)
1304
1435
  return fail("target-moved", "");
1436
+ await this.quiet(row);
1305
1437
  const plan = await this.plan(row);
1306
1438
  if (plan.ignoreFailed)
1307
1439
  return fail("ignore-rules", "");
1440
+ if (plan.unreadable.length > 0)
1441
+ return fail("unreadable", LIMITED(plan.unreadable).join("\n"));
1308
1442
  if (seen !== undefined && shown(plan) !== seen)
1309
1443
  return { text: "The live folder or the Workspace changed while you answered; nothing was merged. Run /conclave merge again.", state: row.state };
1310
1444
  if (plan.conflicts.length > 0 && !force)
@@ -1463,7 +1597,13 @@ export class Workspaces {
1463
1597
  this.hold(row.id, "folder-missing");
1464
1598
  return { text: `Merge held: ${holdText("folder-missing", null)}`, ended: false };
1465
1599
  }
1600
+ await this.quiet(row);
1466
1601
  const plan = await this.plan(row);
1602
+ if (plan.unreadable.length > 0) {
1603
+ const detail = LIMITED(plan.unreadable).join("\n");
1604
+ this.hold(row.id, "unreadable", detail);
1605
+ return { text: `Merge held: ${holdText("unreadable", detail)}`, ended: false };
1606
+ }
1467
1607
  const reasons = [];
1468
1608
  const confirmed = new Set();
1469
1609
  if (row.state === "held" && row.hold !== "conflicts")
package/dist/ws/wsl.js CHANGED
@@ -42,14 +42,7 @@ export function wslDeps() {
42
42
  }) };
43
43
  }
44
44
  export const via = (w, argv) => [...(w.distro === undefined ? [] : ["--distribution", w.distro]), ...(w.user === undefined ? [] : ["--user", w.user]), "--exec", ...argv];
45
- const key = (p) => win32.resolve(p).replaceAll("\\", "/").toLowerCase();
46
45
  export const posixOf = (p) => p.replaceAll("\\", "/");
47
- /** A Windows path that may not be bound or mounted: protected, the profile or a direct child of it, or something holding the Workspace root, PIROBOROS_HOME or a deny root. */
48
- export function wslBad(d, path) {
49
- const k = key(path);
50
- const above = (root) => key(root) === k || key(root).startsWith(`${k}/`);
51
- return !d.allowed(path) || above(d.home) || key(win32.dirname(path)) === key(d.home) || [d.wsRoot, d.piroHome, ...d.deny].some(above);
52
- }
53
46
  /** One call of a constant script; a refusal names the call, the distro or user, or what wsl.exe said. */
54
47
  export async function call(d, w, what, script, args = [], timeoutMs = 20_000) {
55
48
  const r = await d.run(via(w, ["sh", "-c", script, "sh", ...args]), { timeoutMs });
@@ -69,9 +62,9 @@ export const WSLPATH = 'for p; do wslpath -a -u "$p" || echo; done';
69
62
  const REALPATH = 'for p; do realpath -e -- "$p" 2>/dev/null || echo; done';
70
63
  const PIDRUN = 'echo $$ > "$1"; shift; exec "$@"';
71
64
  const KILL = 'kill -KILL "$(cat -- "$1")" 2>/dev/null; rm -f -- "$1"';
72
- // Runs inside the sandbox: write and remove a file in the Workspace, no auth.json, a readable resolv.conf, no Windows program, no System32, then the
65
+ // Runs inside the sandbox: write and remove a file in the Workspace, no auth.json, a readable resolv.conf, no Windows program, no System32, nothing listed in the live project folder, then the
73
66
  // node version and what each masked mount lists.
74
- const SELF_TEST = 'm="$1/.piroboros-selftest"; : > "$m" || { echo "the Workspace is not writable"; exit 1; }; rm -f "$m"; [ ! -e "$2/auth.json" ] || { echo "auth.json is visible"; exit 1; }; [ "$3" = 0 ] || [ -r /etc/resolv.conf ] || { echo "resolv.conf is not readable"; exit 1; }; command -v perl >/dev/null && { perl -e \'socket(S,40,1,0) and exit 1; exit($!+0==97?0:2)\' || { echo "an AF_VSOCK socket can be created"; exit 1; }; }; if "$4" >/dev/null 2>&1; then echo "a Windows program ran"; exit 1; fi; [ ! -e "$5" ] || { echo "the Windows System32 folder is visible"; exit 1; }; echo "node $(node --version 2>/dev/null || echo none)"; shift 5; for m; do echo "mount $m"; ls -A "$m" 2>/dev/null; done; true';
67
+ const SELF_TEST = 'm="$1/.piroboros-selftest"; : > "$m" || { echo "the Workspace is not writable"; exit 1; }; rm -f "$m"; [ ! -e "$2/auth.json" ] || { echo "auth.json is visible"; exit 1; }; [ "$3" = 0 ] || [ -r /etc/resolv.conf ] || { echo "resolv.conf is not readable"; exit 1; }; command -v perl >/dev/null && { perl -e \'socket(S,40,1,0) and exit 1; exit($!+0==97?0:2)\' || { echo "an AF_VSOCK socket can be created"; exit 1; }; }; if "$4" >/dev/null 2>&1; then echo "a Windows program ran"; exit 1; fi; [ ! -e "$5" ] || { echo "the Windows System32 folder is visible"; exit 1; }; [ -z "$6" ] || [ -z "$(ls -A -- "$6" 2>/dev/null)" ] || { echo "the live project is visible"; exit 1; }; echo "node $(node --version 2>/dev/null || echo none)"; shift 6; for m; do echo "mount $m"; ls -A "$m" 2>/dev/null; done; true';
75
68
  export const WRAPPER = 'IFS= read -rd "" c; exec bash -c "$c"';
76
69
  /** The distro and user (the pinned ones, or the default), refused when bubblewrap (unless `bwrap` is false, for Docker) cannot work there. Also reads the Windows-backed mounts. */
77
70
  export async function resolveWsl(d, who, bwrapNeeded = true) {
@@ -144,11 +137,8 @@ export async function wslPick(s, d, ws, p) {
144
137
  const notice = [];
145
138
  if (p.prev !== undefined && (p.prev.distro !== info.distro || p.prev.user !== info.user))
146
139
  notice.push(`The earlier sandbox folders of this Workspace stay in ${p.prev.distro} as ${p.prev.user} at ${p.prev.ext4}; remove them there.`);
147
- // Deny-root check of each Windows path before it is translated.
148
- for (const x of [ws, ...p.alt])
149
- if (win32.isAbsolute(x) && !/^[A-Za-z]:[\\/]/u.test(x))
150
- throw new Error(`${x} is not on a local Windows drive`);
151
- const alt = p.alt.filter((a) => win32.isAbsolute(a) && !wslBad(d, a));
140
+ if (win32.isAbsolute(ws) && !/^[A-Za-z]:[\\/]/u.test(ws))
141
+ throw new Error(`${ws} is not on a local Windows drive`);
152
142
  const hash = win32.basename(win32.dirname(ws));
153
143
  const selftest = win32.join(d.wsRoot, hash, "selftest");
154
144
  if (!existsSync(win32.join(selftest, "w.exe"))) {
@@ -156,21 +146,20 @@ export async function wslPick(s, d, ws, p) {
156
146
  copyFileSync(win32.join(w.systemRoot, "System32", "whoami.exe"), win32.join(selftest, "w.exe"));
157
147
  }
158
148
  const system32 = win32.join(w.systemRoot, "System32");
159
- const wins = [...new Set([ws, d.wsRoot, d.piroHome, ...d.deny, selftest, system32, ...alt])];
149
+ const wins = [...new Set([ws, d.wsRoot, d.piroHome, ...d.deny, selftest, system32, ...(p.project === "" ? [] : [p.project])])];
160
150
  const out = (await call(w, who, "translating paths", WSLPATH, wins.map((x) => win32.resolve(x)))).split("\n");
161
151
  const to = new Map(wins.map((x, i) => [x, out[i] ?? ""]));
162
152
  const lin = (x) => to.get(x) ?? "";
163
- for (const x of [ws, ...alt])
164
- if (!info.mounts.some((m) => within(m, lin(x))))
165
- throw new Error(`${x} is not on a local Windows drive`);
153
+ if (!info.mounts.some((m) => within(m, lin(ws))))
154
+ throw new Error(`${ws} is not on a local Windows drive`);
166
155
  const login = await loginValues(w, who, info.mounts);
167
156
  const wsLin = lin(ws);
168
157
  const ext4 = `${info.home}/.local/state/piroboros-ws/${hash}/${win32.basename(ws)}`;
169
158
  const nm = p.places.map((place, i) => [`${ext4}/nm/${i}`, `${wsLin}/${place}`]);
170
159
  await call(w, who, "creating the sandbox folders", 'mkdir -p -m 0700 -- "$@"', [`${ext4}/run`, ...nm.map(([src]) => src)]);
171
160
  const env = [["PATH", login.path.join(":")], ["HOME", info.home], ["USER", info.user], ["LOGNAME", info.user], ["LANG", login.lang], ["TMPDIR", "/tmp"], ["NO_COLOR", "1"], ["TERM", "dumb"]];
172
- const c = { ws: wsLin, cwd: wsLin, net: s.network, path: login.path.join(":"), wsl: { mounts: info.mounts, alt: alt.map(lin), nm, env, extra: [] } };
173
- const test = ["sh", "-c", SELF_TEST, "sh", wsLin, lin(d.piroHome), s.network ? "1" : "0", `${lin(selftest)}/w.exe`, lin(system32), ...info.mounts];
161
+ const c = { ws: wsLin, cwd: wsLin, net: s.network, path: login.path.join(":"), project: p.project === "" ? undefined : lin(p.project), wsl: { mounts: info.mounts, nm, env, extra: [] } };
162
+ const test = ["sh", "-c", SELF_TEST, "sh", wsLin, lin(d.piroHome), s.network ? "1" : "0", `${lin(selftest)}/w.exe`, lin(system32), c.project ?? "", ...info.mounts];
174
163
  const built = await settled(w, who, (real) => {
175
164
  const dl = { ...d, platform: "linux", home: info.home, piroHome: lin(d.piroHome), wsRoot: lin(d.wsRoot), deny: d.deny.map(lin).filter((x) => x !== ""), allowed: () => true, real, read: () => undefined };
176
165
  return { real: bwrapArgs(dl, c, []), test: bwrapArgs(dl, { ...c, wsl: { ...c.wsl, extra: [lin(selftest)] } }, test) };
@@ -180,7 +169,7 @@ export async function wslPick(s, d, ws, p) {
180
169
  if (ran.timedOut || ran.code !== 0)
181
170
  throw new SelfTestError(ran.timedOut ? "the self-test did not finish within 20 s" : lines[0] || ran.err.trim().split("\n")[0] || "bwrap did not start");
182
171
  // Each masked mount may list only the first folder of a bound path inside it.
183
- const bound = [wsLin, ...c.wsl.alt, lin(selftest), ...nm.map(([, dst]) => dst), login.resolv];
172
+ const bound = [wsLin, lin(selftest), ...nm.map(([, dst]) => dst), login.resolv];
184
173
  let mount = "";
185
174
  for (const line of lines.slice(1)) {
186
175
  if (line.startsWith("mount ")) {
@@ -207,12 +196,11 @@ export async function wslPick(s, d, ws, p) {
207
196
  notice.push(`Network: on. Confined commands can reach the WSL VM's network, which includes the Windows host (${info.net === "nat" || info.net === "mirrored" ? `networking mode: ${info.net}` : "through the NAT gateway, or on Windows localhost with mirrored networking"}), and can send any file they can see.`);
208
197
  if (p.files > 1000)
209
198
  notice.push(`git in the sandbox reads this project through drvfs: the first git status takes about ${Math.round(p.files * 0.0057)} s, later ones about ${(0.5 + p.files * 0.0003).toFixed(1)} s.`);
210
- const left = [...p.alt.filter((a) => !alt.includes(a)), ...built.real.refused];
211
- if (left.length > 0)
212
- notice.push(`Left hidden in the sandbox because they are protected: ${left.join(", ")}`);
199
+ if (built.real.refused.length > 0)
200
+ notice.push(`Left hidden in the sandbox because they are protected: ${built.real.refused.join(", ")}`);
213
201
  if (login.fallback)
214
202
  notice.push(`The login shell of ${info.distro} did not answer, so PATH comes from wsl.exe itself; put toolchain PATH lines in ~/.profile.`);
215
- return { confine: { name: "bubblewrap", bwrap: "/usr/bin/bwrap", net: s.network, wsl: { ...who, ws: wsLin, ext4, argv: built.real.args, alt: p.alt, places: p.places } }, label: `bubblewrap in WSL (${info.distro})`, notice, alt: alt.map(lin) };
203
+ return { confine: { name: "bubblewrap", bwrap: "/usr/bin/bwrap", net: s.network, wsl: { ...who, ws: wsLin, ext4, argv: built.real.args, places: p.places } }, label: `bubblewrap in WSL (${info.distro})`, notice };
216
204
  }
217
205
  /** The sandbox folders of a Workspace, removed with the Workspace (exactly the computed path, never one read from Workspace content). */
218
206
  export const wslRemove = (d, c) => call(d, c, "removing the sandbox folders", 'rm -rf --one-file-system -- "$1"', [c.ext4]);