@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.
@@ -36,13 +36,14 @@ import path from "node:path";
36
36
  import crypto from "node:crypto";
37
37
  import { pipeline } from "node:stream/promises";
38
38
  import { registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle } from "./history.js";
39
- import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath } from "./store.js";
39
+ import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.js";
40
40
  import { dataRoot } from "./paths.js";
41
41
  import { processState } from "./process-state.js";
42
42
  import { opsError, opsLog } from "./ops-log.js";
43
43
  import { readAll, fileSource, BlobNotFound } from "./blob-store.js";
44
44
  import { fsJournalStore } from "./journal-store.js";
45
45
  import { AUTHORED_DIRS, AUTHORED_ROOT_FILES, STATE_DIRS, assertManifestPath, blobObjectKey, diffManifests, emptyManifest, entryId, EMPTY_MANIFEST_ID, MODE_EXEC, MODE_FILE, sha256Hex, sideOf, } from "./manifest.js";
46
+ import { mirrorOn, readMirrorBase, writeMirrorBase, dropMirrorBase, mirroredWorkspaces } from "./mirror-base.js";
46
47
  import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError } from "./publish.js";
47
48
  import { OpIdReused } from "./revision-store.js";
48
49
  import { pruneStateRevisions } from "./state-retention.js";
@@ -356,7 +357,7 @@ async function drainOne(k) {
356
357
  if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
357
358
  verified.add(k);
358
359
  try {
359
- await reconcileWorkspace(tenant, workspace, "reconcile");
360
+ await reconcileNow(tenant, workspace, "reconcile");
360
361
  }
361
362
  catch (err) {
362
363
  verified.delete(k);
@@ -771,6 +772,10 @@ export async function cleanOrphanedHistory(marks, opts) {
771
772
  const deps = S.backend;
772
773
  if (!deps)
773
774
  return out;
775
+ // Folders are a copy of the heads (revisions.mirror): a missing one says
776
+ // nothing about the workspace, so nothing is taken for orphaned.
777
+ if (mirrorOn())
778
+ return out;
774
779
  const root = dataRoot();
775
780
  let rootEntries = 0;
776
781
  try {
@@ -924,7 +929,7 @@ export async function reconcileAll(opts = {}) {
924
929
  verified.delete(k);
925
930
  continue; // the store is not taking writes: leave it
926
931
  }
927
- const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() => reconcileWorkspace(tenant, w.name, opts.by ?? "reconcile"));
932
+ const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() => reconcileNow(tenant, w.name, opts.by ?? "reconcile"));
928
933
  chains.set(k, next);
929
934
  const res = await next;
930
935
  verified.add(k);
@@ -1126,6 +1131,13 @@ async function commitEntry(deps, tenant, workspace, entry) {
1126
1131
  // run, a person) is a conflict on the path, and disjoint paths replay. Where
1127
1132
  // the revision cannot be read any more, the folder's sha stands in.
1128
1133
  const fromRev = await baseManifests(deps, tenant, workspace, entry.baseRev);
1134
+ // A pod whose folder is a copy of the heads (revisions.mirror): a change
1135
+ // written here was made against the version this pod last synced — its
1136
+ // base, so one made meanwhile on another pod is a conflict (both kept),
1137
+ // never overwritten (Codex review). Syncs wait while entries are queued, so
1138
+ // the record still says what the writer saw.
1139
+ const synced = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
1140
+ const plainBase = (rel, was) => synced ? (synced.files[rel] ? entryId(synced.files[rel]) : null) : was ? entryId(was) : null;
1129
1141
  const put = (rel, buf, side, pinned, handed) => {
1130
1142
  const sha = sha256Hex(buf);
1131
1143
  bytes.set(sha, buf);
@@ -1139,7 +1151,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
1139
1151
  const atRev = fromRev[side]?.files[rel];
1140
1152
  const usable = fromRev[side] !== undefined && handed !== undefined && handed === (atRev ? atRev.sha : null);
1141
1153
  const pinnedTo = pinned === undefined ? undefined : usable ? (atRev ? entryId(atRev) : null) : pinnedBase(pinned, was);
1142
- changes[rel] = { op: "put", base: pinned === undefined ? (was ? entryId(was) : null) : pinnedTo, sha, size: buf.length, mode };
1154
+ changes[rel] = { op: "put", base: pinned === undefined ? plainBase(rel, was) : pinnedTo, sha, size: buf.length, mode };
1143
1155
  };
1144
1156
  if (baseline.authored || baseline.state) {
1145
1157
  // Nothing is recorded for (part of) this workspace yet: its tree, as the
@@ -1164,8 +1176,9 @@ async function commitEntry(deps, tenant, workspace, entry) {
1164
1176
  continue; // in the baseline
1165
1177
  const was = head[side].files[f.path];
1166
1178
  if (f.after === null) {
1167
- if (was)
1168
- changes[f.path] = { op: "delete", base: entryId(was) };
1179
+ // A delete of a file this pod never synced deletes nothing elsewhere.
1180
+ if (was && (!synced || synced.files[f.path]))
1181
+ changes[f.path] = { op: "delete", base: plainBase(f.path, was) ?? entryId(was) };
1169
1182
  }
1170
1183
  else {
1171
1184
  put(f.path, bytesOfEntry(f), side, f.base, f.handed);
@@ -1194,7 +1207,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
1194
1207
  if (!Object.keys(todo).length)
1195
1208
  return null;
1196
1209
  try {
1197
- return await publish(deps, {
1210
+ return await afterPublish(deps, ws, todo, await publish(deps, {
1198
1211
  ws,
1199
1212
  // The op id of a side that finished, when one did, so the other side's
1200
1213
  // conflict copies are named the way the first attempt would have.
@@ -1209,7 +1222,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
1209
1222
  throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1210
1223
  return b;
1211
1224
  },
1212
- });
1225
+ }));
1213
1226
  }
1214
1227
  catch (err) {
1215
1228
  // Never "done" by itself: a side that finished is found by sidesDone on
@@ -1248,10 +1261,25 @@ async function sidesDone(deps, ws, id) {
1248
1261
  * (until 13 Nov 2026: only the text files the editor lists, so a binary file
1249
1262
  * never reached a head and one the importer had put there was never updated
1250
1263
  * or removed — a run staged from the head was handed files deleted days ago). */
1251
- export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1264
+ /** Bring the heads to this pod's folder (see reconcileNow), in turn with
1265
+ * everything else that commits this workspace here: two at once would diff
1266
+ * the same folder against the same head and race each other's publish. */
1267
+ export function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1268
+ const k = key(tenant, workspace);
1269
+ const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() => reconcileNow(tenant, workspace, by));
1270
+ chains.set(k, next);
1271
+ return next;
1272
+ }
1273
+ async function reconcileNow(tenant, workspace, by = "reconcile") {
1252
1274
  const deps = S.backend;
1253
1275
  if (!deps)
1254
1276
  return null;
1277
+ // A copy this pod has not synced yet is not the truth about anything: an
1278
+ // empty disk at start would otherwise publish every file as deleted. Its
1279
+ // own writes reach the head through the journal; the reconcile waits for a
1280
+ // sync to say what "changed here" means.
1281
+ if (mirrorOn() && !readMirrorBase(tenant, workspace))
1282
+ return null;
1255
1283
  const ws = { tenant, workspace };
1256
1284
  const k = key(tenant, workspace);
1257
1285
  // The mark goes BEFORE the folder is read, so one set after the read (a run
@@ -1270,12 +1298,18 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1270
1298
  return null;
1271
1299
  const head = await manifestsAt(deps, tenant, heads);
1272
1300
  const onDisk = new Map();
1273
- const want = emptyManifest();
1274
- const have = { v: 1, files: { ...head.authored.files, ...head.state.files } };
1301
+ let want = emptyManifest();
1302
+ let have = { v: 1, files: { ...head.authored.files, ...head.state.files } };
1275
1303
  for (const [rel, f] of scan.files) {
1276
1304
  onDisk.set(f.sha, f.abs);
1277
1305
  want.files[rel] = { sha: f.sha, size: f.size, mode: f.mode };
1278
1306
  }
1307
+ // A pod whose folder is a copy of the heads (revisions.mirror): only what
1308
+ // differs from the last sync is this pod's change. A difference from the
1309
+ // head alone is someone else's change not copied here yet, never undone.
1310
+ const base = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
1311
+ if (base)
1312
+ ({ have, want } = threeWay(have, scan, base, workspaceDir(tenant, workspace)));
1279
1313
  // A path the scan could not take (unreadable now, a name the manifest
1280
1314
  // refuses) but the folder still holds is neither added nor removed here;
1281
1315
  // one that is gone from the folder is gone from the head.
@@ -1295,7 +1329,7 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1295
1329
  const opId = opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40));
1296
1330
  const release = await uploadLarge(deps, tenant, changes, onDisk, opId);
1297
1331
  try {
1298
- return await publish(deps, {
1332
+ return await afterPublish(deps, ws, changes, await publish(deps, {
1299
1333
  ws,
1300
1334
  opId,
1301
1335
  by,
@@ -1305,7 +1339,7 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1305
1339
  // the sha, so a file that changed since the scan fails this repair (the
1306
1340
  // mark is put back and the next one sees the new bytes).
1307
1341
  bytesOf: async (sha) => fs.promises.readFile(onDisk.get(sha)),
1308
- });
1342
+ }));
1309
1343
  }
1310
1344
  finally {
1311
1345
  await release();
@@ -1322,6 +1356,350 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
1322
1356
  repairing.delete(k);
1323
1357
  }
1324
1358
  }
1359
+ /** After this pod published changes of its own (revisions.mirror): what it
1360
+ * published is now what the heads hold, so its copy is synced for those
1361
+ * paths. A path that conflicted kept the head's version (this pod's is the
1362
+ * conflict copy beside it), so this pod takes the head's version too — unless
1363
+ * the file changed here again since. Returns the result unchanged. */
1364
+ async function afterPublish(deps, ws, changes, r) {
1365
+ if (!mirrorOn())
1366
+ return r;
1367
+ try {
1368
+ const { tenant, workspace } = ws;
1369
+ const base = readMirrorBase(tenant, workspace) ?? { workspaceHead: null, stateHead: null, files: {}, at: new Date().toISOString() };
1370
+ const conflicted = new Set(r.conflicts.map((c) => c.path));
1371
+ const dir = workspaceDir(tenant, workspace);
1372
+ let head = null;
1373
+ for (const [p, c] of Object.entries(changes)) {
1374
+ if (!conflicted.has(p)) {
1375
+ if (c.op === "delete")
1376
+ delete base.files[p];
1377
+ else
1378
+ base.files[p] = { sha: c.sha, mode: c.mode };
1379
+ continue;
1380
+ }
1381
+ head ??= await (async () => {
1382
+ const m = await manifestsAt(deps, tenant, await headsOf(deps, ws));
1383
+ return { ...m.authored.files, ...m.state.files };
1384
+ })();
1385
+ const winner = head[p];
1386
+ const abs = path.join(dir, p);
1387
+ // Never through a link, on any branch below (Codex review).
1388
+ if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
1389
+ continue;
1390
+ const local = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1391
+ // Only while the file is still what this pod published (or gone, for a delete).
1392
+ if (c.op === "delete" ? local !== null : local !== c.sha)
1393
+ continue;
1394
+ if (winner) {
1395
+ const b = await blobBytes(deps, tenant, winner.sha);
1396
+ if (!b)
1397
+ continue;
1398
+ // Again after the download: an edit made meanwhile is kept, and never
1399
+ // through a link — the file or a folder on its way (Codex review).
1400
+ if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
1401
+ continue;
1402
+ if ((fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null) !== local)
1403
+ continue;
1404
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1405
+ // A new file renamed over the old one: replaces it, follows nothing.
1406
+ const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
1407
+ fs.writeFileSync(tmp, b, { mode: winner.mode === MODE_EXEC ? 0o755 : 0o644 });
1408
+ fs.chmodSync(tmp, winner.mode === MODE_EXEC ? 0o755 : 0o644);
1409
+ fs.renameSync(tmp, abs);
1410
+ base.files[p] = { sha: winner.sha, mode: winner.mode };
1411
+ }
1412
+ else {
1413
+ // The head deleted it; this pod's version is the conflict copy. The
1414
+ // original goes too, or the next reconcile would bring it back.
1415
+ fs.rmSync(abs, { force: true });
1416
+ delete base.files[p];
1417
+ }
1418
+ }
1419
+ writeMirrorBase(tenant, workspace, { ...base, at: new Date().toISOString() });
1420
+ }
1421
+ catch (err) {
1422
+ opsError("revisions.mirror_note_failed", err, { tenant: ws.tenant, workspace: ws.workspace }, "warn");
1423
+ }
1424
+ return r;
1425
+ }
1426
+ /** The reconcile's diff for a mirrored folder: the head, with this pod's own
1427
+ * changes since its last sync on top — each path's base the version it was
1428
+ * synced at, so one someone else changed meanwhile is a conflict (both kept),
1429
+ * never a silent overwrite. */
1430
+ function threeWay(headM, scan, base, dir) {
1431
+ const have = { v: 1, files: { ...headM.files } };
1432
+ const want = { v: 1, files: { ...headM.files } };
1433
+ const same = (a, b) => !!a && !!b && a.sha === b.sha && a.mode === b.mode;
1434
+ for (const [p, f] of scan.files) {
1435
+ const synced = base.files[p];
1436
+ if (same(f, synced) || same(f, headM.files[p]))
1437
+ continue; // not changed here, or already the head's
1438
+ if (synced)
1439
+ have.files[p] = { sha: synced.sha, mode: synced.mode, size: headM.files[p]?.size ?? 0 };
1440
+ else
1441
+ delete have.files[p];
1442
+ want.files[p] = { sha: f.sha, size: f.size, mode: f.mode };
1443
+ }
1444
+ for (const [p, synced] of Object.entries(base.files)) {
1445
+ if (scan.files.has(p) || scan.left.has(p))
1446
+ continue;
1447
+ if (throughLink(dir, p))
1448
+ continue; // out of reach under a link, not deleted
1449
+ // Deleted here since the sync: gone from the head too, from the version
1450
+ // this pod had (a newer one elsewhere makes it a conflict).
1451
+ if (!headM.files[p])
1452
+ continue;
1453
+ have.files[p] = { sha: synced.sha, mode: synced.mode, size: headM.files[p].size };
1454
+ delete want.files[p];
1455
+ }
1456
+ return { have, want };
1457
+ }
1458
+ /**
1459
+ * Bring this pod's copy of a workspace to its heads (FOL-126, the shared
1460
+ * volume retired; revisions.mirror). What changed in the heads since the last
1461
+ * sync is written or removed; what changed HERE since then is left as it is
1462
+ * and handed to the reconcile, which publishes it against the version it was
1463
+ * synced at. Never while this pod has changes of its own still to publish.
1464
+ * A workspace whose heads are gone (deleted, renamed away) is removed here
1465
+ * only if this pod's copy came from them.
1466
+ */
1467
+ export function syncFromHeads(tenant, workspace) {
1468
+ // In turn with this workspace's commits and reconciles here (the same
1469
+ // chain): a reconcile must never scan a folder a sync is half way through,
1470
+ // or the files it already brought would read as this pod's changes (Codex
1471
+ // review).
1472
+ if (!S.backend || !mirrorOn())
1473
+ return Promise.resolve("skipped");
1474
+ const k = key(tenant, workspace);
1475
+ const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() => syncNow(tenant, workspace));
1476
+ chains.set(k, next);
1477
+ return next;
1478
+ }
1479
+ async function syncNow(tenant, workspace) {
1480
+ const deps = S.backend;
1481
+ if (!deps || !mirrorOn())
1482
+ return "skipped";
1483
+ const k = key(tenant, workspace);
1484
+ const busy = () => (queues.get(k)?.length ?? 0) > 0 || repairing.has(k) || frozen.has(k);
1485
+ if (busy())
1486
+ return "skipped";
1487
+ const dir = workspaceDir(tenant, workspace);
1488
+ // A copy whose folder is gone (the disk was cleared, a hand rm) starts again
1489
+ // from the heads: with the old record kept, every file would read as deleted
1490
+ // here and the reconcile would publish those deletes (Codex review).
1491
+ let base = readMirrorBase(tenant, workspace);
1492
+ if (base && !fs.existsSync(dir)) {
1493
+ dropMirrorBase(tenant, workspace);
1494
+ base = null;
1495
+ }
1496
+ const heads = await headsOf(deps, { tenant, workspace });
1497
+ if (!heads.workspace && !heads.state) {
1498
+ if (!base)
1499
+ return "absent";
1500
+ if (busy())
1501
+ return "skipped";
1502
+ fs.rmSync(dir, { recursive: true, force: true });
1503
+ dropMirrorBase(tenant, workspace);
1504
+ notifyWorkspaceChanged(tenant, workspace, "delete");
1505
+ return "removed";
1506
+ }
1507
+ const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
1508
+ if (base && base.workspaceHead === ids.workspaceHead && base.stateHead === ids.stateHead && fs.existsSync(dir))
1509
+ return "unchanged";
1510
+ const m = await manifestsAt(deps, tenant, heads);
1511
+ const target = { ...m.authored.files, ...m.state.files };
1512
+ fs.mkdirSync(dir, { recursive: true });
1513
+ const scan = (await scanFolder(tenant, workspace)) ?? { files: new Map(), left: new Set() };
1514
+ const synced = base?.files ?? {};
1515
+ const next = {};
1516
+ // What this pass has done so far, over the old base: kept if it stops early
1517
+ // (a download fails, a write lands), so what it wrote is not later taken for
1518
+ // this pod's own change. The head ids stay the old ones, so the next pass
1519
+ // runs again (Codex review).
1520
+ const progress = { ...synced };
1521
+ let finished = false;
1522
+ let touched = false;
1523
+ let blocked = false; // a head file could not be put in place: not counted as synced
1524
+ try {
1525
+ let ownChanges = false;
1526
+ let wrote = 0;
1527
+ // A file here that differs from what the last sync brought is this pod's
1528
+ // own: one the sync never brought (or the first sync of a folder that
1529
+ // already had files) counts as made here — kept, never overwritten.
1530
+ const mine = (p, f) => {
1531
+ const s = synced[p];
1532
+ return !s || f.sha !== s.sha || f.mode !== s.mode;
1533
+ };
1534
+ for (const [p, f] of scan.files) {
1535
+ if (p in target)
1536
+ continue;
1537
+ const s = synced[p];
1538
+ if (s && s.sha === f.sha && s.mode === f.mode) {
1539
+ if (busy())
1540
+ return "skipped";
1541
+ // Still untouched right now (a tool may have written it since the scan,
1542
+ // and such a write queues nothing): only then removed (Codex review).
1543
+ if (throughLink(dir, p) || (fs.existsSync(f.abs) && fs.lstatSync(f.abs).isSymbolicLink())) {
1544
+ blocked = true; // a link appeared on the way since the scan: never followed (Codex review)
1545
+ next[p] = s;
1546
+ continue;
1547
+ }
1548
+ if (fs.existsSync(f.abs) && (sha256Hex(fs.readFileSync(f.abs)) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1549
+ ownChanges = true;
1550
+ next[p] = s;
1551
+ continue;
1552
+ }
1553
+ fs.rmSync(f.abs, { force: true }); // removed in the heads, untouched here
1554
+ delete progress[p];
1555
+ touched = true;
1556
+ wrote++;
1557
+ }
1558
+ else {
1559
+ // Made or changed here: the reconcile publishes it — against the version
1560
+ // it was synced at, so a delete elsewhere stays a conflict (Codex review).
1561
+ ownChanges = true;
1562
+ if (s)
1563
+ next[p] = s;
1564
+ }
1565
+ }
1566
+ for (const [p, e] of Object.entries(target)) {
1567
+ const f = scan.files.get(p);
1568
+ if (f && f.sha === e.sha && f.mode === e.mode) {
1569
+ next[p] = { sha: e.sha, mode: e.mode };
1570
+ continue;
1571
+ }
1572
+ // Under a folder that is now a link here, a file is out of reach — not
1573
+ // deleted: left, and retried, never published as gone (Codex review).
1574
+ if (!f && throughLink(dir, p)) {
1575
+ blocked = true;
1576
+ if (synced[p])
1577
+ next[p] = synced[p];
1578
+ continue;
1579
+ }
1580
+ if (scan.left.has(p) || (f ? mine(p, f) : !!synced[p])) {
1581
+ // This pod's own change (or a path the scan could not take): kept, and
1582
+ // its base stays what it was synced at. A path the scan could not take
1583
+ // (a link at the file itself) is retried next pass, like one under a
1584
+ // linked folder (Codex review).
1585
+ ownChanges = true;
1586
+ if (scan.left.has(p))
1587
+ blocked = true;
1588
+ if (synced[p])
1589
+ next[p] = synced[p];
1590
+ continue;
1591
+ }
1592
+ if (busy())
1593
+ return "skipped"; // a write landed meanwhile: next round
1594
+ const bytes = await blobBytes(deps, tenant, e.sha);
1595
+ if (!bytes)
1596
+ throw new Error(`revisions: blob ${e.sha.slice(0, 12)} of ${tenant}/${workspace}/${p} is missing`);
1597
+ const abs = path.join(dir, p);
1598
+ // Never through a link: a folder on the way that is a symlink could lead
1599
+ // outside the workspace (Codex review). Such a path is left as it is.
1600
+ if (throughLink(dir, p)) {
1601
+ blocked = true; // tried again next pass: the heads are not counted as reached
1602
+ if (synced[p])
1603
+ next[p] = synced[p];
1604
+ continue;
1605
+ }
1606
+ // A folder where the file goes (the heads turned a folder into a file):
1607
+ // its files were removed above if they were the heads'; an empty one goes.
1608
+ if (fs.existsSync(abs) && fs.lstatSync(abs).isDirectory()) {
1609
+ if (fs.readdirSync(abs, { recursive: true }).some((n) => !fs.statSync(path.join(abs, String(n))).isDirectory())) {
1610
+ ownChanges = true;
1611
+ blocked = true;
1612
+ continue;
1613
+ }
1614
+ fs.rmSync(abs, { recursive: true, force: true });
1615
+ }
1616
+ // Again after the download: a writer may have queued a change or touched
1617
+ // this very file while it ran (Codex review). The file must still be what
1618
+ // the scan saw, or it is this pod's change now and is left alone.
1619
+ if (busy())
1620
+ return "skipped";
1621
+ const nowSha = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1622
+ if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
1623
+ ownChanges = true;
1624
+ if (synced[p])
1625
+ next[p] = synced[p];
1626
+ continue;
1627
+ }
1628
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1629
+ const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
1630
+ fs.writeFileSync(tmp, bytes, { mode: e.mode === MODE_EXEC ? 0o755 : 0o644 });
1631
+ fs.chmodSync(tmp, e.mode === MODE_EXEC ? 0o755 : 0o644);
1632
+ fs.renameSync(tmp, abs);
1633
+ next[p] = { sha: e.sha, mode: e.mode };
1634
+ progress[p] = next[p];
1635
+ touched = true;
1636
+ wrote++;
1637
+ }
1638
+ // A file the heads have that could not be put in place (a link, a folder in
1639
+ // the way) keeps the old head ids, so every pass looks again rather than
1640
+ // answering "unchanged" until the next commit (Codex review).
1641
+ writeMirrorBase(tenant, workspace, { ...(blocked ? { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null } : ids), files: next, at: new Date().toISOString() });
1642
+ finished = true;
1643
+ if (ownChanges)
1644
+ requestReconcile(tenant, workspace);
1645
+ if (wrote)
1646
+ notifyWorkspaceChanged(tenant, workspace, "write");
1647
+ return "synced";
1648
+ }
1649
+ finally {
1650
+ if (!finished && touched)
1651
+ writeMirrorBase(tenant, workspace, { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null, files: progress, at: new Date().toISOString() });
1652
+ }
1653
+ }
1654
+ /** A file's mode as a manifest holds it. */
1655
+ function modeOfFile(abs) {
1656
+ return fs.statSync(abs).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1657
+ }
1658
+ /** Does any folder on the way to `rel` (inside `dir`) exist as a symlink? */
1659
+ function throughLink(dir, rel) {
1660
+ const parts = rel.split("/").slice(0, -1);
1661
+ let at = dir;
1662
+ for (const part of parts) {
1663
+ at = path.join(at, part);
1664
+ let st;
1665
+ try {
1666
+ st = fs.lstatSync(at);
1667
+ }
1668
+ catch {
1669
+ return false; // not there yet: made below, as a real folder
1670
+ }
1671
+ if (st.isSymbolicLink())
1672
+ return true;
1673
+ if (!st.isDirectory())
1674
+ return false; // a file in the way: removed above or reported
1675
+ }
1676
+ return false;
1677
+ }
1678
+ /** Every workspace with heads, and every copy here whose heads are gone. One
1679
+ * failure does not stop the rest. */
1680
+ export async function syncAllFromHeads() {
1681
+ const deps = S.backend;
1682
+ const out = { synced: 0, removed: 0, failed: 0 };
1683
+ if (!deps?.revisions.allHeads || !mirrorOn())
1684
+ return out;
1685
+ const all = await deps.revisions.allHeads();
1686
+ const seen = new Set(all.map((h) => key(h.tenant, h.workspace)));
1687
+ const todo = [...all.map((h) => ({ tenant: h.tenant, workspace: h.workspace })), ...mirroredWorkspaces().filter((w) => !seen.has(key(w.tenant, w.workspace)))];
1688
+ for (const w of todo) {
1689
+ try {
1690
+ const r = await syncFromHeads(w.tenant, w.workspace);
1691
+ if (r === "synced")
1692
+ out.synced++;
1693
+ else if (r === "removed")
1694
+ out.removed++;
1695
+ }
1696
+ catch (err) {
1697
+ out.failed++;
1698
+ opsError("revisions.mirror_sync_failed", err, { tenant: w.tenant, workspace: w.workspace }, "warn");
1699
+ }
1700
+ }
1701
+ return out;
1702
+ }
1325
1703
  // ------------------------------------------------------------- reading
1326
1704
  async function blobBytes(deps, tenant, sha) {
1327
1705
  const hit = await S.cache?.get(tenant, sha);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "22.0.0",
3
+ "version": "22.1.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -29,6 +29,7 @@ import { libraryDir, libraryTools } from "./library.ts";
29
29
  import { isRuntimeTool, toolEntryName } from "./tool-names.ts";
30
30
  import { discoverSkills } from "./runner.ts";
31
31
  import { listSecrets } from "./secrets.ts";
32
+ import { platform } from "./platform.ts";
32
33
 
33
34
  export interface AgentImportResult {
34
35
  /** The name the agent has in the target workspace. */
@@ -127,6 +128,8 @@ function missingFor(tenant: string, to: string, name: string, front: Record<stri
127
128
  [ws, "skills"],
128
129
  [ws, ".agents/skills"],
129
130
  [libraryDir(tenant), "skills"],
131
+ // The platform's gallery skills are in every account.
132
+ ...(platform.galleryDir() ? [[platform.galleryDir()!, "skills"] as const] : []),
130
133
  ] as const) {
131
134
  for (const s of discoverSkills(base, sub)) skills.add(s.name);
132
135
  }
@@ -76,6 +76,8 @@ const TOOL_GROUPS: Completion[] = [
76
76
  { label: "write", hint: "Read, Write, Edit, Glob, Grep" },
77
77
  { label: "code", hint: "Bash — runs anything in the sandbox" },
78
78
  { label: "web", hint: "search, fetch, browse, crawl, map, extract, answer, monitor — providers under web:" },
79
+ { label: "docs", hint: "a library's current docs and code examples, pinned to a version (Context7) — gallery" },
80
+ { label: "video", hint: "motion graphics and video from React code: new, compositions, still, render (Remotion) — gallery" },
79
81
  { label: "ask", hint: "ask_person — ask the person running the desk mid-step, and wait for the answer" },
80
82
  { label: "peers", hint: "peers_list + peers_message — the colleagues running beside it in its parallel group, and a message to one of them" },
81
83
  { label: "text", hint: "extract_text — an image, scanned PDF, office file, audio or video as text (Persian + English OCR, speech)" },
package/src/confine.ts CHANGED
@@ -31,6 +31,7 @@
31
31
  import fs from "node:fs";
32
32
  import path from "node:path";
33
33
  import { refusedBack } from "./copy-back.ts";
34
+ import { platform } from "./platform.ts";
34
35
 
35
36
  /**
36
37
  * A path with its symlinks resolved, as far as it exists.
@@ -226,6 +227,24 @@ function linkedWorkspace(roots: Roots): boolean {
226
227
  }
227
228
  }
228
229
 
230
+ /**
231
+ * The platform shelf's copy of a library skill file the account does not
232
+ * have: `<library>/skills/<rest>` missing on disk, `<gallery>/skills/<rest>`
233
+ * there. Null otherwise — the account's own copy always wins.
234
+ */
235
+ export function gallerySkillFile(abs: string, library: string): string | null {
236
+ const gallery = platform.galleryDir();
237
+ if (!gallery) return null;
238
+ const rel = path.relative(library, abs);
239
+ if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
240
+ const parts = rel.split(path.sep);
241
+ if (parts[0] !== "skills" || parts.length < 2 || fs.existsSync(abs)) return null;
242
+ const shelfSkills = real(path.resolve(gallery, "skills"));
243
+ const candidate = real(path.resolve(shelfSkills, ...parts.slice(1)));
244
+ if (path.relative(shelfSkills, candidate).startsWith("..")) return null;
245
+ return fs.existsSync(candidate) ? candidate : null;
246
+ }
247
+
229
248
  export function checkPaths(
230
249
  toolName: string,
231
250
  input: Record<string, unknown>,
@@ -253,6 +272,18 @@ export function checkPaths(
253
272
  const virtual = expandVirtual(raw, roots);
254
273
  const abs = real(virtual ? virtual.abs : path.resolve(roots.agentDir, raw));
255
274
 
275
+ // A gallery skill on a step with no sandbox. The prompt names every
276
+ // gallery skill under the account library (`../../../../library/skills/
277
+ // <name>/…`), because a sandbox has the gallery laid down there; on this
278
+ // host the library holds only the account's own files, so a read that
279
+ // finds nothing there is served from the platform's shelf. Reads only:
280
+ // the shelf is the platform's.
281
+ const shelf = !isWrite ? gallerySkillFile(abs, library) : null;
282
+ if (shelf) {
283
+ rewritten = { ...(rewritten ?? input), [key]: shelf };
284
+ continue;
285
+ }
286
+
256
287
  // Knowledge is given, not learned: an agent that rewrites the price list
257
288
  // it was handed has corrupted its own source of truth. What it discovers
258
289
  // goes to memory/, which it owns.
@@ -200,6 +200,7 @@ const TOOL: FieldSpec[] = [
200
200
  { key: "test_mode", type: "string", values: ["allow"], help: "script: allow — it may run in a test run" },
201
201
  { key: "secrets", type: ["list", "string"], help: "script: secret names, or proxied | materialised" },
202
202
  { key: "runtime", type: "object", help: "script: packages it needs" },
203
+ { key: "network", type: ["list", "string"], help: "script: the sites its program reaches, added to the granting step's network: list — [api.example.com]" },
203
204
  { key: "code", type: "string", help: "script: the program inline" },
204
205
  { key: "command", type: "string", help: "mcp: the server's command" },
205
206
  { key: "env", type: "object", help: "mcp: its environment" },
@@ -12,6 +12,7 @@ import { modelSecretCollision } from "./model-credential.ts";
12
12
  import { resourcesProblem, computeProblem } from "./resources.ts";
13
13
  import { remotesProblem } from "./a2a-remotes.ts";
14
14
  import { a2aPublishProblem } from "./a2a-publish.ts";
15
+ import { toolSiteProblems } from "./network.ts";
15
16
 
16
17
  export { FRONTMATTER, schemaKindOf, type FieldSpec, type FieldType, type SchemaKind } from "./frontmatter-fields.ts";
17
18
 
@@ -74,6 +75,7 @@ const CHECKS: Partial<Record<SchemaKind, Record<string, (value: unknown) => stri
74
75
  methods: methodsProblem,
75
76
  rate: (v) => (parseRate(v) ? null : `"${shown(v)}" is not a rate — N/s, N/minute, N/hour, or a number per second, above 0`),
76
77
  secrets: modelSecretCollision,
78
+ network: (v) => toolSiteProblems(v)[0] ?? null,
77
79
  },
78
80
  "eval": {
79
81
  effort: (v) => (resolveEffort(v) ? null : `"${String(v)}" is not an effort — low, medium, high, xhigh or max; the judge runs at none`),