@foldrun/core 21.2.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.
- package/dist/src/agent-import.js +3 -0
- package/dist/src/capture.d.ts +3 -6
- package/dist/src/capture.js +7 -5
- package/dist/src/captured-calls.d.ts +30 -0
- package/dist/src/captured-calls.js +219 -0
- package/dist/src/completions.js +2 -0
- package/dist/src/confine.d.ts +6 -0
- package/dist/src/confine.js +33 -0
- package/dist/src/frontmatter-fields.js +1 -0
- package/dist/src/frontmatter-schema.js +2 -0
- package/dist/src/mirror-base.d.ts +24 -0
- package/dist/src/mirror-base.js +82 -0
- package/dist/src/network.d.ts +13 -0
- package/dist/src/network.js +27 -0
- package/dist/src/records.d.ts +6 -1
- package/dist/src/revision-store.d.ts +12 -0
- package/dist/src/revision-store.js +27 -0
- package/dist/src/runner.d.ts +3 -0
- package/dist/src/runner.js +43 -5
- package/dist/src/script-tools.d.ts +4 -0
- package/dist/src/script-tools.js +2 -0
- package/dist/src/starter.js +2 -2
- package/dist/src/store.d.ts +5 -6
- package/dist/src/store.js +53 -30
- package/dist/src/workspace-revisions.d.ts +20 -0
- package/dist/src/workspace-revisions.js +397 -13
- package/package.json +1 -1
- package/src/agent-import.ts +3 -0
- package/src/capture.ts +7 -6
- package/src/captured-calls.ts +226 -0
- package/src/completions.ts +2 -0
- package/src/confine.ts +31 -0
- package/src/frontmatter-fields.ts +1 -0
- package/src/frontmatter-schema.ts +2 -0
- package/src/mirror-base.ts +91 -0
- package/src/network.ts +28 -0
- package/src/records.ts +6 -1
- package/src/revision-store.ts +37 -0
- package/src/runner.ts +45 -5
- package/src/script-tools.ts +6 -0
- package/src/starter.ts +2 -2
- package/src/store.ts +50 -29
- package/src/workspace-revisions.ts +358 -12
|
@@ -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,11 +59,14 @@ 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";
|
|
66
68
|
import type { SweepMarks } from "./blob-sweeper.ts";
|
|
69
|
+
import { setCallsBackend, dropWorkspaceCalls, settleCalls } from "./captured-calls.ts";
|
|
67
70
|
import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.ts";
|
|
68
71
|
|
|
69
72
|
// ------------------------------------------------------------- the backend
|
|
@@ -138,6 +141,7 @@ export function setRevisionBackend(deps: Deps | null, opts: BackendOptions = {})
|
|
|
138
141
|
S.retentionEvery = opts.retentionEveryMs ?? 10 * 60_000;
|
|
139
142
|
S.orphanMarks = opts.sweepMarks ?? null;
|
|
140
143
|
S.orphanGrace = opts.orphanGraceMs ?? 3_600_000;
|
|
144
|
+
setCallsBackend(deps);
|
|
141
145
|
registerJournal(deps ? journalChange : null);
|
|
142
146
|
registerWorkspaceGone(deps ? (t, w) => goneNow(t, w) : null);
|
|
143
147
|
registerWorkspaceLifecycle(deps ? { drop: dropWorkspaceRevisions, move: moveWorkspaceRevisions, moved: movedNow } : null);
|
|
@@ -462,7 +466,7 @@ async function drainOne(k: string): Promise<void> {
|
|
|
462
466
|
if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
|
|
463
467
|
verified.add(k);
|
|
464
468
|
try {
|
|
465
|
-
await
|
|
469
|
+
await reconcileNow(tenant, workspace, "reconcile");
|
|
466
470
|
} catch (err) {
|
|
467
471
|
verified.delete(k);
|
|
468
472
|
opsError("revisions.reconcile_failed", err, { tenant, workspace }, "warn");
|
|
@@ -557,6 +561,7 @@ const background = S.background;
|
|
|
557
561
|
export async function settleLifecycle(): Promise<void> {
|
|
558
562
|
while (background.size) await Promise.allSettled([...background]);
|
|
559
563
|
await settleRunOutputs();
|
|
564
|
+
await settleCalls();
|
|
560
565
|
}
|
|
561
566
|
function inBackground(p: Promise<unknown>): void {
|
|
562
567
|
const q = p.finally(() => background.delete(q));
|
|
@@ -608,6 +613,8 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
|
|
|
608
613
|
dropJournal(tenant, workspace);
|
|
609
614
|
await before?.catch(() => {});
|
|
610
615
|
try {
|
|
616
|
+
// Its captured calls' pins, while the rows that name the runs are still there.
|
|
617
|
+
await dropWorkspaceCalls(tenant, workspace);
|
|
611
618
|
await deps.revisions.drop({ tenant, workspace });
|
|
612
619
|
// The run outputs published to the blob store (run-outputs.ts) are this workspace's too.
|
|
613
620
|
await dropWorkspaceOutputs(tenant, workspace);
|
|
@@ -619,6 +626,7 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
|
|
|
619
626
|
}
|
|
620
627
|
remove?.();
|
|
621
628
|
dropJournal(tenant, workspace);
|
|
629
|
+
await dropWorkspaceCalls(tenant, workspace);
|
|
622
630
|
await deps.revisions.drop({ tenant, workspace });
|
|
623
631
|
await dropWorkspaceOutputs(tenant, workspace);
|
|
624
632
|
marked.delete(k);
|
|
@@ -868,6 +876,9 @@ export async function cleanOrphanedHistory(
|
|
|
868
876
|
const out = { checked: 0, orphans: 0, marked: 0, dropped: 0, skipped: 0 };
|
|
869
877
|
const deps = S.backend;
|
|
870
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;
|
|
871
882
|
const root = dataRoot();
|
|
872
883
|
let rootEntries = 0;
|
|
873
884
|
try {
|
|
@@ -1004,7 +1015,7 @@ export async function reconcileAll(opts: { by?: string; tenants?: string[] } = {
|
|
|
1004
1015
|
verified.delete(k);
|
|
1005
1016
|
continue; // the store is not taking writes: leave it
|
|
1006
1017
|
}
|
|
1007
|
-
const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() =>
|
|
1018
|
+
const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() => reconcileNow(tenant, w.name, opts.by ?? "reconcile"));
|
|
1008
1019
|
chains.set(k, next);
|
|
1009
1020
|
const res = await next;
|
|
1010
1021
|
verified.add(k);
|
|
@@ -1195,6 +1206,14 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1195
1206
|
// run, a person) is a conflict on the path, and disjoint paths replay. Where
|
|
1196
1207
|
// the revision cannot be read any more, the folder's sha stands in.
|
|
1197
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;
|
|
1198
1217
|
|
|
1199
1218
|
const put = (rel: string, buf: Buffer, side: "authored" | "state", pinned?: string | null, handed?: string | null) => {
|
|
1200
1219
|
const sha = sha256Hex(buf);
|
|
@@ -1208,7 +1227,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1208
1227
|
const atRev = fromRev[side]?.files[rel];
|
|
1209
1228
|
const usable = fromRev[side] !== undefined && handed !== undefined && handed === (atRev ? atRev.sha : null);
|
|
1210
1229
|
const pinnedTo = pinned === undefined ? undefined : usable ? (atRev ? entryId(atRev) : null) : pinnedBase(pinned, was);
|
|
1211
|
-
changes[rel] = { op: "put", base: pinned === undefined ? (
|
|
1230
|
+
changes[rel] = { op: "put", base: pinned === undefined ? plainBase(rel, was) : pinnedTo!, sha, size: buf.length, mode };
|
|
1212
1231
|
};
|
|
1213
1232
|
|
|
1214
1233
|
if (baseline.authored || baseline.state) {
|
|
@@ -1231,7 +1250,8 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1231
1250
|
if ((side === "authored" && baseline.authored) || (side === "state" && baseline.state)) continue; // in the baseline
|
|
1232
1251
|
const was = head[side].files[f.path];
|
|
1233
1252
|
if (f.after === null) {
|
|
1234
|
-
|
|
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) };
|
|
1235
1255
|
} else {
|
|
1236
1256
|
put(f.path, bytesOfEntry(f), side, f.base, f.handed);
|
|
1237
1257
|
}
|
|
@@ -1255,7 +1275,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1255
1275
|
for (const [p, c] of Object.entries(changes)) if (!done[sideOf(p)!]) todo[p] = c;
|
|
1256
1276
|
if (!Object.keys(todo).length) return null;
|
|
1257
1277
|
try {
|
|
1258
|
-
return await publish(deps, {
|
|
1278
|
+
return await afterPublish(deps, ws, todo, await publish(deps, {
|
|
1259
1279
|
ws,
|
|
1260
1280
|
// The op id of a side that finished, when one did, so the other side's
|
|
1261
1281
|
// conflict copies are named the way the first attempt would have.
|
|
@@ -1269,7 +1289,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1269
1289
|
if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
|
|
1270
1290
|
return b;
|
|
1271
1291
|
},
|
|
1272
|
-
});
|
|
1292
|
+
}));
|
|
1273
1293
|
} catch (err) {
|
|
1274
1294
|
// Never "done" by itself: a side that finished is found by sidesDone on
|
|
1275
1295
|
// the next look. One that keeps answering OpIdReused without having
|
|
@@ -1306,9 +1326,24 @@ async function sidesDone(deps: Deps, ws: WorkspaceRef, id: string): Promise<{ au
|
|
|
1306
1326
|
* (until 13 Nov 2026: only the text files the editor lists, so a binary file
|
|
1307
1327
|
* never reached a head and one the importer had put there was never updated
|
|
1308
1328
|
* or removed — a run staged from the head was handed files deleted days ago). */
|
|
1309
|
-
|
|
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> {
|
|
1310
1340
|
const deps = S.backend;
|
|
1311
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;
|
|
1312
1347
|
const ws: WorkspaceRef = { tenant, workspace };
|
|
1313
1348
|
const k = key(tenant, workspace);
|
|
1314
1349
|
// The mark goes BEFORE the folder is read, so one set after the read (a run
|
|
@@ -1326,12 +1361,17 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
|
|
|
1326
1361
|
if (!scan) return null;
|
|
1327
1362
|
const head = await manifestsAt(deps, tenant, heads);
|
|
1328
1363
|
const onDisk = new Map<string, string>();
|
|
1329
|
-
|
|
1330
|
-
|
|
1364
|
+
let want: Manifest = emptyManifest();
|
|
1365
|
+
let have: Manifest = { v: 1, files: { ...head.authored.files, ...head.state.files } };
|
|
1331
1366
|
for (const [rel, f] of scan.files) {
|
|
1332
1367
|
onDisk.set(f.sha, f.abs);
|
|
1333
1368
|
want.files[rel] = { sha: f.sha, size: f.size, mode: f.mode };
|
|
1334
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)));
|
|
1335
1375
|
// A path the scan could not take (unreadable now, a name the manifest
|
|
1336
1376
|
// refuses) but the folder still holds is neither added nor removed here;
|
|
1337
1377
|
// one that is gone from the folder is gone from the head.
|
|
@@ -1349,7 +1389,7 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
|
|
|
1349
1389
|
const opId = opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40));
|
|
1350
1390
|
const release = await uploadLarge(deps, tenant, changes, onDisk, opId);
|
|
1351
1391
|
try {
|
|
1352
|
-
return await publish(deps, {
|
|
1392
|
+
return await afterPublish(deps, ws, changes, await publish(deps, {
|
|
1353
1393
|
ws,
|
|
1354
1394
|
opId,
|
|
1355
1395
|
by,
|
|
@@ -1359,7 +1399,7 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
|
|
|
1359
1399
|
// the sha, so a file that changed since the scan fails this repair (the
|
|
1360
1400
|
// mark is put back and the next one sees the new bytes).
|
|
1361
1401
|
bytesOf: async (sha) => fs.promises.readFile(onDisk.get(sha)!),
|
|
1362
|
-
});
|
|
1402
|
+
}));
|
|
1363
1403
|
} finally {
|
|
1364
1404
|
await release();
|
|
1365
1405
|
}
|
|
@@ -1372,6 +1412,312 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
|
|
|
1372
1412
|
}
|
|
1373
1413
|
}
|
|
1374
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
|
+
|
|
1375
1721
|
// ------------------------------------------------------------- reading
|
|
1376
1722
|
|
|
1377
1723
|
async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffer | null> {
|