@foldrun/core 22.0.0 → 22.1.0

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.
@@ -37,7 +37,7 @@ import path from "node:path";
37
37
  import crypto from "node:crypto";
38
38
  import { pipeline } from "node:stream/promises";
39
39
  import { registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle, type RevisionView, type RevisionFile, type RevisionSummary, type Revision as HistoryRevision } from "./history.ts";
40
- import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath } from "./store.ts";
40
+ import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.ts";
41
41
  import { dataRoot } from "./paths.ts";
42
42
  import { processState } from "./process-state.ts";
43
43
  import { opsError, opsLog } from "./ops-log.ts";
@@ -59,7 +59,9 @@ import {
59
59
  sideOf,
60
60
  type Changes,
61
61
  type Manifest,
62
+ type ManifestEntry,
62
63
  } from "./manifest.ts";
64
+ import { mirrorOn, readMirrorBase, writeMirrorBase, dropMirrorBase, mirroredWorkspaces, type MirrorBase } from "./mirror-base.ts";
63
65
  import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError, type Deps, type Heads, type PublishResult } from "./publish.ts";
64
66
  import { OpIdReused, type Revision, type WorkspaceRef } from "./revision-store.ts";
65
67
  import { pruneStateRevisions, type StateRetention } from "./state-retention.ts";
@@ -464,7 +466,7 @@ async function drainOne(k: string): Promise<void> {
464
466
  if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
465
467
  verified.add(k);
466
468
  try {
467
- await reconcileWorkspace(tenant, workspace, "reconcile");
469
+ await reconcileNow(tenant, workspace, "reconcile");
468
470
  } catch (err) {
469
471
  verified.delete(k);
470
472
  opsError("revisions.reconcile_failed", err, { tenant, workspace }, "warn");
@@ -874,6 +876,9 @@ export async function cleanOrphanedHistory(
874
876
  const out = { checked: 0, orphans: 0, marked: 0, dropped: 0, skipped: 0 };
875
877
  const deps = S.backend;
876
878
  if (!deps) return out;
879
+ // Folders are a copy of the heads (revisions.mirror): a missing one says
880
+ // nothing about the workspace, so nothing is taken for orphaned.
881
+ if (mirrorOn()) return out;
877
882
  const root = dataRoot();
878
883
  let rootEntries = 0;
879
884
  try {
@@ -1010,7 +1015,7 @@ export async function reconcileAll(opts: { by?: string; tenants?: string[] } = {
1010
1015
  verified.delete(k);
1011
1016
  continue; // the store is not taking writes: leave it
1012
1017
  }
1013
- const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() => reconcileWorkspace(tenant, w.name, opts.by ?? "reconcile"));
1018
+ const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() => reconcileNow(tenant, w.name, opts.by ?? "reconcile"));
1014
1019
  chains.set(k, next);
1015
1020
  const res = await next;
1016
1021
  verified.add(k);
@@ -1201,6 +1206,14 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1201
1206
  // run, a person) is a conflict on the path, and disjoint paths replay. Where
1202
1207
  // the revision cannot be read any more, the folder's sha stands in.
1203
1208
  const fromRev = await baseManifests(deps, tenant, workspace, entry.baseRev);
1209
+ // A pod whose folder is a copy of the heads (revisions.mirror): a change
1210
+ // written here was made against the version this pod last synced — its
1211
+ // base, so one made meanwhile on another pod is a conflict (both kept),
1212
+ // never overwritten (Codex review). Syncs wait while entries are queued, so
1213
+ // the record still says what the writer saw.
1214
+ const synced = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
1215
+ const plainBase = (rel: string, was: ManifestEntry | undefined): string | null =>
1216
+ synced ? (synced.files[rel] ? entryId(synced.files[rel]) : null) : was ? entryId(was) : null;
1204
1217
 
1205
1218
  const put = (rel: string, buf: Buffer, side: "authored" | "state", pinned?: string | null, handed?: string | null) => {
1206
1219
  const sha = sha256Hex(buf);
@@ -1214,7 +1227,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1214
1227
  const atRev = fromRev[side]?.files[rel];
1215
1228
  const usable = fromRev[side] !== undefined && handed !== undefined && handed === (atRev ? atRev.sha : null);
1216
1229
  const pinnedTo = pinned === undefined ? undefined : usable ? (atRev ? entryId(atRev) : null) : pinnedBase(pinned, was);
1217
- changes[rel] = { op: "put", base: pinned === undefined ? (was ? entryId(was) : null) : pinnedTo!, sha, size: buf.length, mode };
1230
+ changes[rel] = { op: "put", base: pinned === undefined ? plainBase(rel, was) : pinnedTo!, sha, size: buf.length, mode };
1218
1231
  };
1219
1232
 
1220
1233
  if (baseline.authored || baseline.state) {
@@ -1237,7 +1250,8 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1237
1250
  if ((side === "authored" && baseline.authored) || (side === "state" && baseline.state)) continue; // in the baseline
1238
1251
  const was = head[side].files[f.path];
1239
1252
  if (f.after === null) {
1240
- if (was) changes[f.path] = { op: "delete", base: entryId(was) };
1253
+ // A delete of a file this pod never synced deletes nothing elsewhere.
1254
+ if (was && (!synced || synced.files[f.path])) changes[f.path] = { op: "delete", base: plainBase(f.path, was) ?? entryId(was) };
1241
1255
  } else {
1242
1256
  put(f.path, bytesOfEntry(f), side, f.base, f.handed);
1243
1257
  }
@@ -1261,7 +1275,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1261
1275
  for (const [p, c] of Object.entries(changes)) if (!done[sideOf(p)!]) todo[p] = c;
1262
1276
  if (!Object.keys(todo).length) return null;
1263
1277
  try {
1264
- return await publish(deps, {
1278
+ return await afterPublish(deps, ws, todo, await publish(deps, {
1265
1279
  ws,
1266
1280
  // The op id of a side that finished, when one did, so the other side's
1267
1281
  // conflict copies are named the way the first attempt would have.
@@ -1275,7 +1289,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1275
1289
  if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1276
1290
  return b;
1277
1291
  },
1278
- });
1292
+ }));
1279
1293
  } catch (err) {
1280
1294
  // Never "done" by itself: a side that finished is found by sidesDone on
1281
1295
  // the next look. One that keeps answering OpIdReused without having
@@ -1312,9 +1326,24 @@ async function sidesDone(deps: Deps, ws: WorkspaceRef, id: string): Promise<{ au
1312
1326
  * (until 13 Nov 2026: only the text files the editor lists, so a binary file
1313
1327
  * never reached a head and one the importer had put there was never updated
1314
1328
  * or removed — a run staged from the head was handed files deleted days ago). */
1315
- export async function reconcileWorkspace(tenant: string, workspace: string, by = "reconcile"): Promise<PublishResult | null> {
1329
+ /** Bring the heads to this pod's folder (see reconcileNow), in turn with
1330
+ * everything else that commits this workspace here: two at once would diff
1331
+ * the same folder against the same head and race each other's publish. */
1332
+ export function reconcileWorkspace(tenant: string, workspace: string, by = "reconcile"): Promise<PublishResult | null> {
1333
+ const k = key(tenant, workspace);
1334
+ const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() => reconcileNow(tenant, workspace, by));
1335
+ chains.set(k, next);
1336
+ return next;
1337
+ }
1338
+
1339
+ async function reconcileNow(tenant: string, workspace: string, by = "reconcile"): Promise<PublishResult | null> {
1316
1340
  const deps = S.backend;
1317
1341
  if (!deps) return null;
1342
+ // A copy this pod has not synced yet is not the truth about anything: an
1343
+ // empty disk at start would otherwise publish every file as deleted. Its
1344
+ // own writes reach the head through the journal; the reconcile waits for a
1345
+ // sync to say what "changed here" means.
1346
+ if (mirrorOn() && !readMirrorBase(tenant, workspace)) return null;
1318
1347
  const ws: WorkspaceRef = { tenant, workspace };
1319
1348
  const k = key(tenant, workspace);
1320
1349
  // The mark goes BEFORE the folder is read, so one set after the read (a run
@@ -1332,12 +1361,17 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1332
1361
  if (!scan) return null;
1333
1362
  const head = await manifestsAt(deps, tenant, heads);
1334
1363
  const onDisk = new Map<string, string>();
1335
- const want: Manifest = emptyManifest();
1336
- const have: Manifest = { v: 1, files: { ...head.authored.files, ...head.state.files } };
1364
+ let want: Manifest = emptyManifest();
1365
+ let have: Manifest = { v: 1, files: { ...head.authored.files, ...head.state.files } };
1337
1366
  for (const [rel, f] of scan.files) {
1338
1367
  onDisk.set(f.sha, f.abs);
1339
1368
  want.files[rel] = { sha: f.sha, size: f.size, mode: f.mode };
1340
1369
  }
1370
+ // A pod whose folder is a copy of the heads (revisions.mirror): only what
1371
+ // differs from the last sync is this pod's change. A difference from the
1372
+ // head alone is someone else's change not copied here yet, never undone.
1373
+ const base = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
1374
+ if (base) ({ have, want } = threeWay(have, scan, base, workspaceDir(tenant, workspace)));
1341
1375
  // A path the scan could not take (unreadable now, a name the manifest
1342
1376
  // refuses) but the folder still holds is neither added nor removed here;
1343
1377
  // one that is gone from the folder is gone from the head.
@@ -1355,7 +1389,7 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1355
1389
  const opId = opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40));
1356
1390
  const release = await uploadLarge(deps, tenant, changes, onDisk, opId);
1357
1391
  try {
1358
- return await publish(deps, {
1392
+ return await afterPublish(deps, ws, changes, await publish(deps, {
1359
1393
  ws,
1360
1394
  opId,
1361
1395
  by,
@@ -1365,7 +1399,7 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1365
1399
  // the sha, so a file that changed since the scan fails this repair (the
1366
1400
  // mark is put back and the next one sees the new bytes).
1367
1401
  bytesOf: async (sha) => fs.promises.readFile(onDisk.get(sha)!),
1368
- });
1402
+ }));
1369
1403
  } finally {
1370
1404
  await release();
1371
1405
  }
@@ -1378,6 +1412,312 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1378
1412
  }
1379
1413
  }
1380
1414
 
1415
+ /** After this pod published changes of its own (revisions.mirror): what it
1416
+ * published is now what the heads hold, so its copy is synced for those
1417
+ * paths. A path that conflicted kept the head's version (this pod's is the
1418
+ * conflict copy beside it), so this pod takes the head's version too — unless
1419
+ * the file changed here again since. Returns the result unchanged. */
1420
+ async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: PublishResult): Promise<PublishResult> {
1421
+ if (!mirrorOn()) return r;
1422
+ try {
1423
+ const { tenant, workspace } = ws;
1424
+ const base: MirrorBase = readMirrorBase(tenant, workspace) ?? { workspaceHead: null, stateHead: null, files: {}, at: new Date().toISOString() };
1425
+ const conflicted = new Set(r.conflicts.map((c) => c.path));
1426
+ const dir = workspaceDir(tenant, workspace);
1427
+ let head: Record<string, ManifestEntry> | null = null;
1428
+ for (const [p, c] of Object.entries(changes)) {
1429
+ if (!conflicted.has(p)) {
1430
+ if (c.op === "delete") delete base.files[p];
1431
+ else base.files[p] = { sha: c.sha, mode: c.mode };
1432
+ continue;
1433
+ }
1434
+ head ??= await (async () => {
1435
+ const m = await manifestsAt(deps, tenant, await headsOf(deps, ws));
1436
+ return { ...m.authored.files, ...m.state.files };
1437
+ })();
1438
+ const winner = head[p];
1439
+ const abs = path.join(dir, p);
1440
+ // Never through a link, on any branch below (Codex review).
1441
+ if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink())) continue;
1442
+ const local = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1443
+ // Only while the file is still what this pod published (or gone, for a delete).
1444
+ if (c.op === "delete" ? local !== null : local !== c.sha) continue;
1445
+ if (winner) {
1446
+ const b = await blobBytes(deps, tenant, winner.sha);
1447
+ if (!b) continue;
1448
+ // Again after the download: an edit made meanwhile is kept, and never
1449
+ // through a link — the file or a folder on its way (Codex review).
1450
+ if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink())) continue;
1451
+ if ((fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null) !== local) continue;
1452
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1453
+ // A new file renamed over the old one: replaces it, follows nothing.
1454
+ const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
1455
+ fs.writeFileSync(tmp, b, { mode: winner.mode === MODE_EXEC ? 0o755 : 0o644 });
1456
+ fs.chmodSync(tmp, winner.mode === MODE_EXEC ? 0o755 : 0o644);
1457
+ fs.renameSync(tmp, abs);
1458
+ base.files[p] = { sha: winner.sha, mode: winner.mode };
1459
+ } else {
1460
+ // The head deleted it; this pod's version is the conflict copy. The
1461
+ // original goes too, or the next reconcile would bring it back.
1462
+ fs.rmSync(abs, { force: true });
1463
+ delete base.files[p];
1464
+ }
1465
+ }
1466
+ writeMirrorBase(tenant, workspace, { ...base, at: new Date().toISOString() });
1467
+ } catch (err) {
1468
+ opsError("revisions.mirror_note_failed", err, { tenant: ws.tenant, workspace: ws.workspace }, "warn");
1469
+ }
1470
+ return r;
1471
+ }
1472
+
1473
+ /** The reconcile's diff for a mirrored folder: the head, with this pod's own
1474
+ * changes since its last sync on top — each path's base the version it was
1475
+ * synced at, so one someone else changed meanwhile is a conflict (both kept),
1476
+ * never a silent overwrite. */
1477
+ function threeWay(headM: Manifest, scan: { files: Map<string, FolderFile>; left: Set<string> }, base: MirrorBase, dir: string): { have: Manifest; want: Manifest } {
1478
+ const have: Manifest = { v: 1, files: { ...headM.files } };
1479
+ const want: Manifest = { v: 1, files: { ...headM.files } };
1480
+ const same = (a: { sha: string; mode: number } | undefined, b: { sha: string; mode: number } | undefined) => !!a && !!b && a.sha === b.sha && a.mode === b.mode;
1481
+ for (const [p, f] of scan.files) {
1482
+ const synced = base.files[p];
1483
+ if (same(f, synced) || same(f, headM.files[p])) continue; // not changed here, or already the head's
1484
+ if (synced) have.files[p] = { sha: synced.sha, mode: synced.mode, size: headM.files[p]?.size ?? 0 };
1485
+ else delete have.files[p];
1486
+ want.files[p] = { sha: f.sha, size: f.size, mode: f.mode };
1487
+ }
1488
+ for (const [p, synced] of Object.entries(base.files)) {
1489
+ if (scan.files.has(p) || scan.left.has(p)) continue;
1490
+ if (throughLink(dir, p)) continue; // out of reach under a link, not deleted
1491
+ // Deleted here since the sync: gone from the head too, from the version
1492
+ // this pod had (a newer one elsewhere makes it a conflict).
1493
+ if (!headM.files[p]) continue;
1494
+ have.files[p] = { sha: synced.sha, mode: synced.mode, size: headM.files[p].size };
1495
+ delete want.files[p];
1496
+ }
1497
+ return { have, want };
1498
+ }
1499
+
1500
+ /**
1501
+ * Bring this pod's copy of a workspace to its heads (FOL-126, the shared
1502
+ * volume retired; revisions.mirror). What changed in the heads since the last
1503
+ * sync is written or removed; what changed HERE since then is left as it is
1504
+ * and handed to the reconcile, which publishes it against the version it was
1505
+ * synced at. Never while this pod has changes of its own still to publish.
1506
+ * A workspace whose heads are gone (deleted, renamed away) is removed here
1507
+ * only if this pod's copy came from them.
1508
+ */
1509
+ export function syncFromHeads(tenant: string, workspace: string): Promise<"unchanged" | "synced" | "skipped" | "removed" | "absent"> {
1510
+ // In turn with this workspace's commits and reconciles here (the same
1511
+ // chain): a reconcile must never scan a folder a sync is half way through,
1512
+ // or the files it already brought would read as this pod's changes (Codex
1513
+ // review).
1514
+ if (!S.backend || !mirrorOn()) return Promise.resolve("skipped");
1515
+ const k = key(tenant, workspace);
1516
+ const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() => syncNow(tenant, workspace));
1517
+ chains.set(k, next);
1518
+ return next;
1519
+ }
1520
+
1521
+ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" | "synced" | "skipped" | "removed" | "absent"> {
1522
+ const deps = S.backend;
1523
+ if (!deps || !mirrorOn()) return "skipped";
1524
+ const k = key(tenant, workspace);
1525
+ const busy = () => (queues.get(k)?.length ?? 0) > 0 || repairing.has(k) || frozen.has(k);
1526
+ if (busy()) return "skipped";
1527
+ const dir = workspaceDir(tenant, workspace);
1528
+ // A copy whose folder is gone (the disk was cleared, a hand rm) starts again
1529
+ // from the heads: with the old record kept, every file would read as deleted
1530
+ // here and the reconcile would publish those deletes (Codex review).
1531
+ let base = readMirrorBase(tenant, workspace);
1532
+ if (base && !fs.existsSync(dir)) {
1533
+ dropMirrorBase(tenant, workspace);
1534
+ base = null;
1535
+ }
1536
+ const heads = await headsOf(deps, { tenant, workspace });
1537
+ if (!heads.workspace && !heads.state) {
1538
+ if (!base) return "absent";
1539
+ if (busy()) return "skipped";
1540
+ fs.rmSync(dir, { recursive: true, force: true });
1541
+ dropMirrorBase(tenant, workspace);
1542
+ notifyWorkspaceChanged(tenant, workspace, "delete");
1543
+ return "removed";
1544
+ }
1545
+ const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
1546
+ if (base && base.workspaceHead === ids.workspaceHead && base.stateHead === ids.stateHead && fs.existsSync(dir)) return "unchanged";
1547
+ const m = await manifestsAt(deps, tenant, heads);
1548
+ const target: Record<string, ManifestEntry> = { ...m.authored.files, ...m.state.files };
1549
+ fs.mkdirSync(dir, { recursive: true });
1550
+ const scan = (await scanFolder(tenant, workspace)) ?? { files: new Map<string, FolderFile>(), left: new Set<string>() };
1551
+ const synced = base?.files ?? {};
1552
+ const next: MirrorBase["files"] = {};
1553
+ // What this pass has done so far, over the old base: kept if it stops early
1554
+ // (a download fails, a write lands), so what it wrote is not later taken for
1555
+ // this pod's own change. The head ids stay the old ones, so the next pass
1556
+ // runs again (Codex review).
1557
+ const progress: MirrorBase["files"] = { ...synced };
1558
+ let finished = false;
1559
+ let touched = false;
1560
+ let blocked = false; // a head file could not be put in place: not counted as synced
1561
+ try {
1562
+ let ownChanges = false;
1563
+ let wrote = 0;
1564
+ // A file here that differs from what the last sync brought is this pod's
1565
+ // own: one the sync never brought (or the first sync of a folder that
1566
+ // already had files) counts as made here — kept, never overwritten.
1567
+ const mine = (p: string, f: FolderFile) => {
1568
+ const s = synced[p];
1569
+ return !s || f.sha !== s.sha || f.mode !== s.mode;
1570
+ };
1571
+ for (const [p, f] of scan.files) {
1572
+ if (p in target) continue;
1573
+ const s = synced[p];
1574
+ if (s && s.sha === f.sha && s.mode === f.mode) {
1575
+ if (busy()) return "skipped";
1576
+ // Still untouched right now (a tool may have written it since the scan,
1577
+ // and such a write queues nothing): only then removed (Codex review).
1578
+ if (throughLink(dir, p) || (fs.existsSync(f.abs) && fs.lstatSync(f.abs).isSymbolicLink())) {
1579
+ blocked = true; // a link appeared on the way since the scan: never followed (Codex review)
1580
+ next[p] = s;
1581
+ continue;
1582
+ }
1583
+ if (fs.existsSync(f.abs) && (sha256Hex(fs.readFileSync(f.abs)) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1584
+ ownChanges = true;
1585
+ next[p] = s;
1586
+ continue;
1587
+ }
1588
+ fs.rmSync(f.abs, { force: true }); // removed in the heads, untouched here
1589
+ delete progress[p];
1590
+ touched = true;
1591
+ wrote++;
1592
+ } else {
1593
+ // Made or changed here: the reconcile publishes it — against the version
1594
+ // it was synced at, so a delete elsewhere stays a conflict (Codex review).
1595
+ ownChanges = true;
1596
+ if (s) next[p] = s;
1597
+ }
1598
+ }
1599
+ for (const [p, e] of Object.entries(target)) {
1600
+ const f = scan.files.get(p);
1601
+ if (f && f.sha === e.sha && f.mode === e.mode) {
1602
+ next[p] = { sha: e.sha, mode: e.mode };
1603
+ continue;
1604
+ }
1605
+ // Under a folder that is now a link here, a file is out of reach — not
1606
+ // deleted: left, and retried, never published as gone (Codex review).
1607
+ if (!f && throughLink(dir, p)) {
1608
+ blocked = true;
1609
+ if (synced[p]) next[p] = synced[p];
1610
+ continue;
1611
+ }
1612
+ if (scan.left.has(p) || (f ? mine(p, f) : !!synced[p])) {
1613
+ // This pod's own change (or a path the scan could not take): kept, and
1614
+ // its base stays what it was synced at. A path the scan could not take
1615
+ // (a link at the file itself) is retried next pass, like one under a
1616
+ // linked folder (Codex review).
1617
+ ownChanges = true;
1618
+ if (scan.left.has(p)) blocked = true;
1619
+ if (synced[p]) next[p] = synced[p];
1620
+ continue;
1621
+ }
1622
+ if (busy()) return "skipped"; // a write landed meanwhile: next round
1623
+ const bytes = await blobBytes(deps, tenant, e.sha);
1624
+ if (!bytes) throw new Error(`revisions: blob ${e.sha.slice(0, 12)} of ${tenant}/${workspace}/${p} is missing`);
1625
+ const abs = path.join(dir, p);
1626
+ // Never through a link: a folder on the way that is a symlink could lead
1627
+ // outside the workspace (Codex review). Such a path is left as it is.
1628
+ if (throughLink(dir, p)) {
1629
+ blocked = true; // tried again next pass: the heads are not counted as reached
1630
+ if (synced[p]) next[p] = synced[p];
1631
+ continue;
1632
+ }
1633
+ // A folder where the file goes (the heads turned a folder into a file):
1634
+ // its files were removed above if they were the heads'; an empty one goes.
1635
+ if (fs.existsSync(abs) && fs.lstatSync(abs).isDirectory()) {
1636
+ if (fs.readdirSync(abs, { recursive: true }).some((n) => !fs.statSync(path.join(abs, String(n))).isDirectory())) {
1637
+ ownChanges = true;
1638
+ blocked = true;
1639
+ continue;
1640
+ }
1641
+ fs.rmSync(abs, { recursive: true, force: true });
1642
+ }
1643
+ // Again after the download: a writer may have queued a change or touched
1644
+ // this very file while it ran (Codex review). The file must still be what
1645
+ // the scan saw, or it is this pod's change now and is left alone.
1646
+ if (busy()) return "skipped";
1647
+ const nowSha = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1648
+ if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
1649
+ ownChanges = true;
1650
+ if (synced[p]) next[p] = synced[p];
1651
+ continue;
1652
+ }
1653
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1654
+ const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
1655
+ fs.writeFileSync(tmp, bytes, { mode: e.mode === MODE_EXEC ? 0o755 : 0o644 });
1656
+ fs.chmodSync(tmp, e.mode === MODE_EXEC ? 0o755 : 0o644);
1657
+ fs.renameSync(tmp, abs);
1658
+ next[p] = { sha: e.sha, mode: e.mode };
1659
+ progress[p] = next[p];
1660
+ touched = true;
1661
+ wrote++;
1662
+ }
1663
+ // A file the heads have that could not be put in place (a link, a folder in
1664
+ // the way) keeps the old head ids, so every pass looks again rather than
1665
+ // answering "unchanged" until the next commit (Codex review).
1666
+ writeMirrorBase(tenant, workspace, { ...(blocked ? { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null } : ids), files: next, at: new Date().toISOString() });
1667
+ finished = true;
1668
+ if (ownChanges) requestReconcile(tenant, workspace);
1669
+ if (wrote) notifyWorkspaceChanged(tenant, workspace, "write");
1670
+ return "synced";
1671
+ } finally {
1672
+ if (!finished && touched) writeMirrorBase(tenant, workspace, { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null, files: progress, at: new Date().toISOString() });
1673
+ }
1674
+ }
1675
+
1676
+ /** A file's mode as a manifest holds it. */
1677
+ function modeOfFile(abs: string): number {
1678
+ return fs.statSync(abs).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1679
+ }
1680
+
1681
+ /** Does any folder on the way to `rel` (inside `dir`) exist as a symlink? */
1682
+ function throughLink(dir: string, rel: string): boolean {
1683
+ const parts = rel.split("/").slice(0, -1);
1684
+ let at = dir;
1685
+ for (const part of parts) {
1686
+ at = path.join(at, part);
1687
+ let st: fs.Stats;
1688
+ try {
1689
+ st = fs.lstatSync(at);
1690
+ } catch {
1691
+ return false; // not there yet: made below, as a real folder
1692
+ }
1693
+ if (st.isSymbolicLink()) return true;
1694
+ if (!st.isDirectory()) return false; // a file in the way: removed above or reported
1695
+ }
1696
+ return false;
1697
+ }
1698
+
1699
+ /** Every workspace with heads, and every copy here whose heads are gone. One
1700
+ * failure does not stop the rest. */
1701
+ export async function syncAllFromHeads(): Promise<{ synced: number; removed: number; failed: number }> {
1702
+ const deps = S.backend;
1703
+ const out = { synced: 0, removed: 0, failed: 0 };
1704
+ if (!deps?.revisions.allHeads || !mirrorOn()) return out;
1705
+ const all = await deps.revisions.allHeads();
1706
+ const seen = new Set(all.map((h) => key(h.tenant, h.workspace)));
1707
+ const todo = [...all.map((h) => ({ tenant: h.tenant, workspace: h.workspace })), ...mirroredWorkspaces().filter((w) => !seen.has(key(w.tenant, w.workspace)))];
1708
+ for (const w of todo) {
1709
+ try {
1710
+ const r = await syncFromHeads(w.tenant, w.workspace);
1711
+ if (r === "synced") out.synced++;
1712
+ else if (r === "removed") out.removed++;
1713
+ } catch (err) {
1714
+ out.failed++;
1715
+ opsError("revisions.mirror_sync_failed", err, { tenant: w.tenant, workspace: w.workspace }, "warn");
1716
+ }
1717
+ }
1718
+ return out;
1719
+ }
1720
+
1381
1721
  // ------------------------------------------------------------- reading
1382
1722
 
1383
1723
  async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffer | null> {