@foldrun/core 22.0.0 → 22.2.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/captured-calls.d.ts +10 -0
- package/dist/src/captured-calls.js +25 -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/manifest.js +3 -1
- 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/revision-store.d.ts +12 -0
- package/dist/src/revision-store.js +29 -1
- package/dist/src/runner.d.ts +3 -0
- package/dist/src/runner.js +28 -2
- 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.js +19 -1
- package/dist/src/workspace-revisions.d.ts +23 -0
- package/dist/src/workspace-revisions.js +424 -23
- package/package.json +1 -1
- package/src/agent-import.ts +3 -0
- package/src/captured-calls.ts +22 -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/manifest.ts +3 -1
- package/src/mirror-base.ts +91 -0
- package/src/network.ts +28 -0
- package/src/revision-store.ts +38 -1
- package/src/runner.ts +30 -2
- package/src/script-tools.ts +6 -0
- package/src/starter.ts +2 -2
- package/src/store.ts +19 -1
- package/src/workspace-revisions.ts +382 -21
|
@@ -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, accountDir, 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";
|
|
@@ -132,7 +134,7 @@ const entryStore = (): JournalStore => S.primary ?? legacyFiles;
|
|
|
132
134
|
export function setRevisionBackend(deps: Deps | null, opts: BackendOptions = {}): void {
|
|
133
135
|
// Every commit asks, inside the store's workspace lock, whether the folder is
|
|
134
136
|
// still there: a delete or rename on another pod removes it under that lock.
|
|
135
|
-
S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(
|
|
137
|
+
S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(folderOf(ws.tenant, ws.workspace))) } : null;
|
|
136
138
|
S.gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
|
|
137
139
|
S.primary = opts.journalStore ?? null;
|
|
138
140
|
S.retention = opts.stateRetention ?? null;
|
|
@@ -235,6 +237,18 @@ const split = (k: string): [string, string] => k.split("\0") as [string, string]
|
|
|
235
237
|
|
|
236
238
|
const journalRoot = () => path.join(dataRoot(), ".revision-journal");
|
|
237
239
|
|
|
240
|
+
/** Where a scope's files are: a workspace's folder, or for the account shelf
|
|
241
|
+
* ("@library") the account's own — its AGENTS.md and library/ (FOL-126). */
|
|
242
|
+
function folderOf(tenant: string, workspace: string): string {
|
|
243
|
+
return workspace === "@library" ? accountDir(tenant) : workspaceDir(tenant, workspace);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The account's AGENTS.md or library changed outside the journal (a route
|
|
247
|
+
* that writes the file itself): publish it, as any other change of a scope. */
|
|
248
|
+
export function noteAccountFilesChanged(tenant: string): void {
|
|
249
|
+
if (S.backend && journalOn()) requestReconcile(tenant, "@library");
|
|
250
|
+
}
|
|
251
|
+
|
|
238
252
|
/** Write the entry down, atomically. A store that refuses leaves the entry in
|
|
239
253
|
* memory only (said once per failure), as the journal always was. */
|
|
240
254
|
function persist(tenant: string, workspace: string, e: Entry): void {
|
|
@@ -259,7 +273,7 @@ function forget(tenant: string, workspace: string, e: Entry): void {
|
|
|
259
273
|
/** Called by history.recordRevision for every change set. Synchronous and
|
|
260
274
|
* cheap; the commit happens in the background (flushRevisions waits for it). */
|
|
261
275
|
function journalChange(tenant: string, scope: string, files: RevisionFile[], meta: { by: string; message: string; at: string }): void {
|
|
262
|
-
if (!S.backend
|
|
276
|
+
if (!S.backend) return;
|
|
263
277
|
const k = key(tenant, scope);
|
|
264
278
|
if (!safe(S.gate.journal)) {
|
|
265
279
|
verified.delete(k); // a change the head will not see: reconcile before trusting it again
|
|
@@ -268,7 +282,9 @@ function journalChange(tenant: string, scope: string, files: RevisionFile[], met
|
|
|
268
282
|
}
|
|
269
283
|
// Only what the head needs: the new content. The old text is the writer's
|
|
270
284
|
// history record, not the journal's (it can be a quarter megabyte a file).
|
|
271
|
-
|
|
285
|
+
// The account shelf's paths are `<kind>/<file>` in its own history and
|
|
286
|
+
// `library/<kind>/<file>` in its revisions (its folder is the account's).
|
|
287
|
+
const slim = files.map((f) => ({ path: scope === "@library" ? `library/${f.path}` : f.path, before: null, after: f.after }));
|
|
272
288
|
enqueue(tenant, scope, { id: crypto.randomBytes(12).toString("hex"), files: slim, by: meta.by, message: meta.message, at: meta.at, restoredFrom: restoring.get(k) });
|
|
273
289
|
}
|
|
274
290
|
|
|
@@ -415,7 +431,7 @@ async function drainOne(k: string): Promise<void> {
|
|
|
415
431
|
const entry = q[0];
|
|
416
432
|
// The workspace was deleted while this waited (or retried): nothing to
|
|
417
433
|
// publish, and nothing for a later boot to replay.
|
|
418
|
-
if (!fs.existsSync(
|
|
434
|
+
if (!fs.existsSync(folderOf(tenant, workspace))) {
|
|
419
435
|
q.shift();
|
|
420
436
|
forget(tenant, workspace, entry);
|
|
421
437
|
continue;
|
|
@@ -461,10 +477,10 @@ async function drainOne(k: string): Promise<void> {
|
|
|
461
477
|
// journal was off for a while, a run wrote the folder directly) is brought
|
|
462
478
|
// to it. After the entries, never before: replaying an older change over a
|
|
463
479
|
// reconciled head would write it backwards.
|
|
464
|
-
if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(
|
|
480
|
+
if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(folderOf(tenant, workspace))) {
|
|
465
481
|
verified.add(k);
|
|
466
482
|
try {
|
|
467
|
-
await
|
|
483
|
+
await reconcileNow(tenant, workspace, "reconcile");
|
|
468
484
|
} catch (err) {
|
|
469
485
|
verified.delete(k);
|
|
470
486
|
opsError("revisions.reconcile_failed", err, { tenant, workspace }, "warn");
|
|
@@ -874,6 +890,9 @@ export async function cleanOrphanedHistory(
|
|
|
874
890
|
const out = { checked: 0, orphans: 0, marked: 0, dropped: 0, skipped: 0 };
|
|
875
891
|
const deps = S.backend;
|
|
876
892
|
if (!deps) return out;
|
|
893
|
+
// Folders are a copy of the heads (revisions.mirror): a missing one says
|
|
894
|
+
// nothing about the workspace, so nothing is taken for orphaned.
|
|
895
|
+
if (mirrorOn()) return out;
|
|
877
896
|
const root = dataRoot();
|
|
878
897
|
let rootEntries = 0;
|
|
879
898
|
try {
|
|
@@ -949,7 +968,7 @@ export async function recoverJournal(opts: { minAgeMs?: number } = {}): Promise<
|
|
|
949
968
|
const k = key(tenant, workspace);
|
|
950
969
|
const q = queues.get(k) ?? [];
|
|
951
970
|
const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
|
|
952
|
-
const gone = !fs.existsSync(
|
|
971
|
+
const gone = !fs.existsSync(folderOf(tenant, workspace));
|
|
953
972
|
const found: Entry[] = [];
|
|
954
973
|
let names: { handle: string; ageMs: number }[] = [];
|
|
955
974
|
try {
|
|
@@ -1001,7 +1020,9 @@ export async function reconcileAll(opts: { by?: string; tenants?: string[] } = {
|
|
|
1001
1020
|
// workspace of the same name.
|
|
1002
1021
|
if (S.orphanMarks) await cleanOrphanedHistory(S.orphanMarks, { graceMs: S.orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
|
|
1003
1022
|
for (const tenant of opts.tenants ?? listTenants()) {
|
|
1004
|
-
|
|
1023
|
+
// The account shelf too (account AGENTS.md + library/), as a scope of its own.
|
|
1024
|
+
const shelf = ["AGENTS.md", "library"].some((n) => fs.existsSync(path.join(accountDir(tenant), n)));
|
|
1025
|
+
for (const w of [...listWorkspaces(tenant), ...(shelf ? [{ name: "@library" }] : [])]) {
|
|
1005
1026
|
const k = key(tenant, w.name);
|
|
1006
1027
|
try {
|
|
1007
1028
|
verified.add(k); // reconciled explicitly below, and counted
|
|
@@ -1010,7 +1031,7 @@ export async function reconcileAll(opts: { by?: string; tenants?: string[] } = {
|
|
|
1010
1031
|
verified.delete(k);
|
|
1011
1032
|
continue; // the store is not taking writes: leave it
|
|
1012
1033
|
}
|
|
1013
|
-
const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() =>
|
|
1034
|
+
const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() => reconcileNow(tenant, w.name, opts.by ?? "reconcile"));
|
|
1014
1035
|
chains.set(k, next);
|
|
1015
1036
|
const res = await next;
|
|
1016
1037
|
verified.add(k);
|
|
@@ -1061,7 +1082,7 @@ async function hashOf(abs: string, size: number): Promise<string> {
|
|
|
1061
1082
|
* not be read. Null when the folder is not there.
|
|
1062
1083
|
*/
|
|
1063
1084
|
async function scanFolder(tenant: string, workspace: string): Promise<{ files: Map<string, FolderFile>; left: Set<string> } | null> {
|
|
1064
|
-
const dir =
|
|
1085
|
+
const dir = folderOf(tenant, workspace);
|
|
1065
1086
|
if (!fs.existsSync(dir)) return null;
|
|
1066
1087
|
const found: { rel: string; abs: string; st: fs.Stats }[] = [];
|
|
1067
1088
|
const left = new Set<string>();
|
|
@@ -1146,7 +1167,7 @@ async function uploadLarge(deps: Deps, tenant: string, changes: Changes, onDisk:
|
|
|
1146
1167
|
|
|
1147
1168
|
function modeOf(tenant: string, workspace: string, rel: string): number {
|
|
1148
1169
|
try {
|
|
1149
|
-
return fs.statSync(path.join(
|
|
1170
|
+
return fs.statSync(path.join(folderOf(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
|
|
1150
1171
|
} catch {
|
|
1151
1172
|
return MODE_FILE;
|
|
1152
1173
|
}
|
|
@@ -1201,6 +1222,14 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1201
1222
|
// run, a person) is a conflict on the path, and disjoint paths replay. Where
|
|
1202
1223
|
// the revision cannot be read any more, the folder's sha stands in.
|
|
1203
1224
|
const fromRev = await baseManifests(deps, tenant, workspace, entry.baseRev);
|
|
1225
|
+
// A pod whose folder is a copy of the heads (revisions.mirror): a change
|
|
1226
|
+
// written here was made against the version this pod last synced — its
|
|
1227
|
+
// base, so one made meanwhile on another pod is a conflict (both kept),
|
|
1228
|
+
// never overwritten (Codex review). Syncs wait while entries are queued, so
|
|
1229
|
+
// the record still says what the writer saw.
|
|
1230
|
+
const synced = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
|
|
1231
|
+
const plainBase = (rel: string, was: ManifestEntry | undefined): string | null =>
|
|
1232
|
+
synced ? (synced.files[rel] ? entryId(synced.files[rel]) : null) : was ? entryId(was) : null;
|
|
1204
1233
|
|
|
1205
1234
|
const put = (rel: string, buf: Buffer, side: "authored" | "state", pinned?: string | null, handed?: string | null) => {
|
|
1206
1235
|
const sha = sha256Hex(buf);
|
|
@@ -1214,7 +1243,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1214
1243
|
const atRev = fromRev[side]?.files[rel];
|
|
1215
1244
|
const usable = fromRev[side] !== undefined && handed !== undefined && handed === (atRev ? atRev.sha : null);
|
|
1216
1245
|
const pinnedTo = pinned === undefined ? undefined : usable ? (atRev ? entryId(atRev) : null) : pinnedBase(pinned, was);
|
|
1217
|
-
changes[rel] = { op: "put", base: pinned === undefined ? (
|
|
1246
|
+
changes[rel] = { op: "put", base: pinned === undefined ? plainBase(rel, was) : pinnedTo!, sha, size: buf.length, mode };
|
|
1218
1247
|
};
|
|
1219
1248
|
|
|
1220
1249
|
if (baseline.authored || baseline.state) {
|
|
@@ -1237,7 +1266,8 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1237
1266
|
if ((side === "authored" && baseline.authored) || (side === "state" && baseline.state)) continue; // in the baseline
|
|
1238
1267
|
const was = head[side].files[f.path];
|
|
1239
1268
|
if (f.after === null) {
|
|
1240
|
-
|
|
1269
|
+
// A delete of a file this pod never synced deletes nothing elsewhere.
|
|
1270
|
+
if (was && (!synced || synced.files[f.path])) changes[f.path] = { op: "delete", base: plainBase(f.path, was) ?? entryId(was) };
|
|
1241
1271
|
} else {
|
|
1242
1272
|
put(f.path, bytesOfEntry(f), side, f.base, f.handed);
|
|
1243
1273
|
}
|
|
@@ -1261,7 +1291,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1261
1291
|
for (const [p, c] of Object.entries(changes)) if (!done[sideOf(p)!]) todo[p] = c;
|
|
1262
1292
|
if (!Object.keys(todo).length) return null;
|
|
1263
1293
|
try {
|
|
1264
|
-
return await publish(deps, {
|
|
1294
|
+
return await afterPublish(deps, ws, todo, await publish(deps, {
|
|
1265
1295
|
ws,
|
|
1266
1296
|
// The op id of a side that finished, when one did, so the other side's
|
|
1267
1297
|
// conflict copies are named the way the first attempt would have.
|
|
@@ -1275,7 +1305,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
|
|
|
1275
1305
|
if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
|
|
1276
1306
|
return b;
|
|
1277
1307
|
},
|
|
1278
|
-
});
|
|
1308
|
+
}));
|
|
1279
1309
|
} catch (err) {
|
|
1280
1310
|
// Never "done" by itself: a side that finished is found by sidesDone on
|
|
1281
1311
|
// the next look. One that keeps answering OpIdReused without having
|
|
@@ -1312,9 +1342,24 @@ async function sidesDone(deps: Deps, ws: WorkspaceRef, id: string): Promise<{ au
|
|
|
1312
1342
|
* (until 13 Nov 2026: only the text files the editor lists, so a binary file
|
|
1313
1343
|
* never reached a head and one the importer had put there was never updated
|
|
1314
1344
|
* or removed — a run staged from the head was handed files deleted days ago). */
|
|
1315
|
-
|
|
1345
|
+
/** Bring the heads to this pod's folder (see reconcileNow), in turn with
|
|
1346
|
+
* everything else that commits this workspace here: two at once would diff
|
|
1347
|
+
* the same folder against the same head and race each other's publish. */
|
|
1348
|
+
export function reconcileWorkspace(tenant: string, workspace: string, by = "reconcile"): Promise<PublishResult | null> {
|
|
1349
|
+
const k = key(tenant, workspace);
|
|
1350
|
+
const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() => reconcileNow(tenant, workspace, by));
|
|
1351
|
+
chains.set(k, next);
|
|
1352
|
+
return next;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
async function reconcileNow(tenant: string, workspace: string, by = "reconcile"): Promise<PublishResult | null> {
|
|
1316
1356
|
const deps = S.backend;
|
|
1317
1357
|
if (!deps) return null;
|
|
1358
|
+
// A copy this pod has not synced yet is not the truth about anything: an
|
|
1359
|
+
// empty disk at start would otherwise publish every file as deleted. Its
|
|
1360
|
+
// own writes reach the head through the journal; the reconcile waits for a
|
|
1361
|
+
// sync to say what "changed here" means.
|
|
1362
|
+
if (mirrorOn() && !readMirrorBase(tenant, workspace)) return null;
|
|
1318
1363
|
const ws: WorkspaceRef = { tenant, workspace };
|
|
1319
1364
|
const k = key(tenant, workspace);
|
|
1320
1365
|
// The mark goes BEFORE the folder is read, so one set after the read (a run
|
|
@@ -1332,12 +1377,17 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
|
|
|
1332
1377
|
if (!scan) return null;
|
|
1333
1378
|
const head = await manifestsAt(deps, tenant, heads);
|
|
1334
1379
|
const onDisk = new Map<string, string>();
|
|
1335
|
-
|
|
1336
|
-
|
|
1380
|
+
let want: Manifest = emptyManifest();
|
|
1381
|
+
let have: Manifest = { v: 1, files: { ...head.authored.files, ...head.state.files } };
|
|
1337
1382
|
for (const [rel, f] of scan.files) {
|
|
1338
1383
|
onDisk.set(f.sha, f.abs);
|
|
1339
1384
|
want.files[rel] = { sha: f.sha, size: f.size, mode: f.mode };
|
|
1340
1385
|
}
|
|
1386
|
+
// A pod whose folder is a copy of the heads (revisions.mirror): only what
|
|
1387
|
+
// differs from the last sync is this pod's change. A difference from the
|
|
1388
|
+
// head alone is someone else's change not copied here yet, never undone.
|
|
1389
|
+
const base = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
|
|
1390
|
+
if (base) ({ have, want } = threeWay(have, scan, base, folderOf(tenant, workspace)));
|
|
1341
1391
|
// A path the scan could not take (unreadable now, a name the manifest
|
|
1342
1392
|
// refuses) but the folder still holds is neither added nor removed here;
|
|
1343
1393
|
// one that is gone from the folder is gone from the head.
|
|
@@ -1355,7 +1405,7 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
|
|
|
1355
1405
|
const opId = opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40));
|
|
1356
1406
|
const release = await uploadLarge(deps, tenant, changes, onDisk, opId);
|
|
1357
1407
|
try {
|
|
1358
|
-
return await publish(deps, {
|
|
1408
|
+
return await afterPublish(deps, ws, changes, await publish(deps, {
|
|
1359
1409
|
ws,
|
|
1360
1410
|
opId,
|
|
1361
1411
|
by,
|
|
@@ -1365,7 +1415,7 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
|
|
|
1365
1415
|
// the sha, so a file that changed since the scan fails this repair (the
|
|
1366
1416
|
// mark is put back and the next one sees the new bytes).
|
|
1367
1417
|
bytesOf: async (sha) => fs.promises.readFile(onDisk.get(sha)!),
|
|
1368
|
-
});
|
|
1418
|
+
}));
|
|
1369
1419
|
} finally {
|
|
1370
1420
|
await release();
|
|
1371
1421
|
}
|
|
@@ -1378,6 +1428,317 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
|
|
|
1378
1428
|
}
|
|
1379
1429
|
}
|
|
1380
1430
|
|
|
1431
|
+
/** After this pod published changes of its own (revisions.mirror): what it
|
|
1432
|
+
* published is now what the heads hold, so its copy is synced for those
|
|
1433
|
+
* paths. A path that conflicted kept the head's version (this pod's is the
|
|
1434
|
+
* conflict copy beside it), so this pod takes the head's version too — unless
|
|
1435
|
+
* the file changed here again since. Returns the result unchanged. */
|
|
1436
|
+
async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: PublishResult): Promise<PublishResult> {
|
|
1437
|
+
if (!mirrorOn()) return r;
|
|
1438
|
+
try {
|
|
1439
|
+
const { tenant, workspace } = ws;
|
|
1440
|
+
const base: MirrorBase = readMirrorBase(tenant, workspace) ?? { workspaceHead: null, stateHead: null, files: {}, at: new Date().toISOString() };
|
|
1441
|
+
const conflicted = new Set(r.conflicts.map((c) => c.path));
|
|
1442
|
+
const dir = folderOf(tenant, workspace);
|
|
1443
|
+
let head: Record<string, ManifestEntry> | null = null;
|
|
1444
|
+
for (const [p, c] of Object.entries(changes)) {
|
|
1445
|
+
if (!conflicted.has(p)) {
|
|
1446
|
+
if (c.op === "delete") delete base.files[p];
|
|
1447
|
+
else base.files[p] = { sha: c.sha, mode: c.mode };
|
|
1448
|
+
continue;
|
|
1449
|
+
}
|
|
1450
|
+
head ??= await (async () => {
|
|
1451
|
+
const m = await manifestsAt(deps, tenant, await headsOf(deps, ws));
|
|
1452
|
+
return { ...m.authored.files, ...m.state.files };
|
|
1453
|
+
})();
|
|
1454
|
+
const winner = head[p];
|
|
1455
|
+
const abs = path.join(dir, p);
|
|
1456
|
+
// Never through a link, on any branch below (Codex review).
|
|
1457
|
+
if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink())) continue;
|
|
1458
|
+
const local = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
|
|
1459
|
+
// Only while the file is still what this pod published (or gone, for a delete).
|
|
1460
|
+
if (c.op === "delete" ? local !== null : local !== c.sha) continue;
|
|
1461
|
+
if (winner) {
|
|
1462
|
+
const b = await blobBytes(deps, tenant, winner.sha);
|
|
1463
|
+
if (!b) continue;
|
|
1464
|
+
// Again after the download: an edit made meanwhile is kept, and never
|
|
1465
|
+
// through a link — the file or a folder on its way (Codex review).
|
|
1466
|
+
if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink())) continue;
|
|
1467
|
+
if ((fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null) !== local) continue;
|
|
1468
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
1469
|
+
// A new file renamed over the old one: replaces it, follows nothing.
|
|
1470
|
+
const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
|
|
1471
|
+
fs.writeFileSync(tmp, b, { mode: winner.mode === MODE_EXEC ? 0o755 : 0o644 });
|
|
1472
|
+
fs.chmodSync(tmp, winner.mode === MODE_EXEC ? 0o755 : 0o644);
|
|
1473
|
+
fs.renameSync(tmp, abs);
|
|
1474
|
+
base.files[p] = { sha: winner.sha, mode: winner.mode };
|
|
1475
|
+
} else {
|
|
1476
|
+
// The head deleted it; this pod's version is the conflict copy. The
|
|
1477
|
+
// original goes too, or the next reconcile would bring it back.
|
|
1478
|
+
fs.rmSync(abs, { force: true });
|
|
1479
|
+
delete base.files[p];
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
writeMirrorBase(tenant, workspace, { ...base, at: new Date().toISOString() });
|
|
1483
|
+
} catch (err) {
|
|
1484
|
+
opsError("revisions.mirror_note_failed", err, { tenant: ws.tenant, workspace: ws.workspace }, "warn");
|
|
1485
|
+
}
|
|
1486
|
+
return r;
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/** The reconcile's diff for a mirrored folder: the head, with this pod's own
|
|
1490
|
+
* changes since its last sync on top — each path's base the version it was
|
|
1491
|
+
* synced at, so one someone else changed meanwhile is a conflict (both kept),
|
|
1492
|
+
* never a silent overwrite. */
|
|
1493
|
+
function threeWay(headM: Manifest, scan: { files: Map<string, FolderFile>; left: Set<string> }, base: MirrorBase, dir: string): { have: Manifest; want: Manifest } {
|
|
1494
|
+
const have: Manifest = { v: 1, files: { ...headM.files } };
|
|
1495
|
+
const want: Manifest = { v: 1, files: { ...headM.files } };
|
|
1496
|
+
const same = (a: { sha: string; mode: number } | undefined, b: { sha: string; mode: number } | undefined) => !!a && !!b && a.sha === b.sha && a.mode === b.mode;
|
|
1497
|
+
for (const [p, f] of scan.files) {
|
|
1498
|
+
const synced = base.files[p];
|
|
1499
|
+
if (same(f, synced) || same(f, headM.files[p])) continue; // not changed here, or already the head's
|
|
1500
|
+
if (synced) have.files[p] = { sha: synced.sha, mode: synced.mode, size: headM.files[p]?.size ?? 0 };
|
|
1501
|
+
else delete have.files[p];
|
|
1502
|
+
want.files[p] = { sha: f.sha, size: f.size, mode: f.mode };
|
|
1503
|
+
}
|
|
1504
|
+
for (const [p, synced] of Object.entries(base.files)) {
|
|
1505
|
+
if (scan.files.has(p) || scan.left.has(p)) continue;
|
|
1506
|
+
if (throughLink(dir, p)) continue; // out of reach under a link, not deleted
|
|
1507
|
+
// Deleted here since the sync: gone from the head too, from the version
|
|
1508
|
+
// this pod had (a newer one elsewhere makes it a conflict).
|
|
1509
|
+
if (!headM.files[p]) continue;
|
|
1510
|
+
have.files[p] = { sha: synced.sha, mode: synced.mode, size: headM.files[p].size };
|
|
1511
|
+
delete want.files[p];
|
|
1512
|
+
}
|
|
1513
|
+
return { have, want };
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
/**
|
|
1517
|
+
* Bring this pod's copy of a workspace to its heads (FOL-126, the shared
|
|
1518
|
+
* volume retired; revisions.mirror). What changed in the heads since the last
|
|
1519
|
+
* sync is written or removed; what changed HERE since then is left as it is
|
|
1520
|
+
* and handed to the reconcile, which publishes it against the version it was
|
|
1521
|
+
* synced at. Never while this pod has changes of its own still to publish.
|
|
1522
|
+
* A workspace whose heads are gone (deleted, renamed away) is removed here
|
|
1523
|
+
* only if this pod's copy came from them.
|
|
1524
|
+
*/
|
|
1525
|
+
export function syncFromHeads(tenant: string, workspace: string): Promise<"unchanged" | "synced" | "skipped" | "removed" | "absent"> {
|
|
1526
|
+
// In turn with this workspace's commits and reconciles here (the same
|
|
1527
|
+
// chain): a reconcile must never scan a folder a sync is half way through,
|
|
1528
|
+
// or the files it already brought would read as this pod's changes (Codex
|
|
1529
|
+
// review).
|
|
1530
|
+
if (!S.backend || !mirrorOn()) return Promise.resolve("skipped");
|
|
1531
|
+
const k = key(tenant, workspace);
|
|
1532
|
+
const next = (chains.get(k) ?? Promise.resolve()).catch(() => {}).then(() => syncNow(tenant, workspace));
|
|
1533
|
+
chains.set(k, next);
|
|
1534
|
+
return next;
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
async function syncNow(tenant: string, workspace: string): Promise<"unchanged" | "synced" | "skipped" | "removed" | "absent"> {
|
|
1538
|
+
const deps = S.backend;
|
|
1539
|
+
if (!deps || !mirrorOn()) return "skipped";
|
|
1540
|
+
const k = key(tenant, workspace);
|
|
1541
|
+
const busy = () => (queues.get(k)?.length ?? 0) > 0 || repairing.has(k) || frozen.has(k);
|
|
1542
|
+
if (busy()) return "skipped";
|
|
1543
|
+
const dir = folderOf(tenant, workspace);
|
|
1544
|
+
// A copy whose folder is gone (the disk was cleared, a hand rm) starts again
|
|
1545
|
+
// from the heads: with the old record kept, every file would read as deleted
|
|
1546
|
+
// here and the reconcile would publish those deletes (Codex review).
|
|
1547
|
+
let base = readMirrorBase(tenant, workspace);
|
|
1548
|
+
if (base && !fs.existsSync(dir)) {
|
|
1549
|
+
dropMirrorBase(tenant, workspace);
|
|
1550
|
+
base = null;
|
|
1551
|
+
}
|
|
1552
|
+
const heads = await headsOf(deps, { tenant, workspace });
|
|
1553
|
+
if (!heads.workspace && !heads.state) {
|
|
1554
|
+
if (!base) return "absent";
|
|
1555
|
+
if (busy()) return "skipped";
|
|
1556
|
+
if (workspace === "@library") {
|
|
1557
|
+
// The shelf's folder is the ACCOUNT's: only what the shelf owns goes —
|
|
1558
|
+
// never the account folder with every workspace in it (Codex review).
|
|
1559
|
+
fs.rmSync(path.join(dir, "AGENTS.md"), { force: true });
|
|
1560
|
+
fs.rmSync(path.join(dir, "library"), { recursive: true, force: true });
|
|
1561
|
+
} else fs.rmSync(dir, { recursive: true, force: true });
|
|
1562
|
+
dropMirrorBase(tenant, workspace);
|
|
1563
|
+
if (workspace !== "@library") notifyWorkspaceChanged(tenant, workspace, "delete");
|
|
1564
|
+
return "removed";
|
|
1565
|
+
}
|
|
1566
|
+
const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
|
|
1567
|
+
if (base && base.workspaceHead === ids.workspaceHead && base.stateHead === ids.stateHead && fs.existsSync(dir)) return "unchanged";
|
|
1568
|
+
const m = await manifestsAt(deps, tenant, heads);
|
|
1569
|
+
const target: Record<string, ManifestEntry> = { ...m.authored.files, ...m.state.files };
|
|
1570
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1571
|
+
const scan = (await scanFolder(tenant, workspace)) ?? { files: new Map<string, FolderFile>(), left: new Set<string>() };
|
|
1572
|
+
const synced = base?.files ?? {};
|
|
1573
|
+
const next: MirrorBase["files"] = {};
|
|
1574
|
+
// What this pass has done so far, over the old base: kept if it stops early
|
|
1575
|
+
// (a download fails, a write lands), so what it wrote is not later taken for
|
|
1576
|
+
// this pod's own change. The head ids stay the old ones, so the next pass
|
|
1577
|
+
// runs again (Codex review).
|
|
1578
|
+
const progress: MirrorBase["files"] = { ...synced };
|
|
1579
|
+
let finished = false;
|
|
1580
|
+
let touched = false;
|
|
1581
|
+
let blocked = false; // a head file could not be put in place: not counted as synced
|
|
1582
|
+
try {
|
|
1583
|
+
let ownChanges = false;
|
|
1584
|
+
let wrote = 0;
|
|
1585
|
+
// A file here that differs from what the last sync brought is this pod's
|
|
1586
|
+
// own: one the sync never brought (or the first sync of a folder that
|
|
1587
|
+
// already had files) counts as made here — kept, never overwritten.
|
|
1588
|
+
const mine = (p: string, f: FolderFile) => {
|
|
1589
|
+
const s = synced[p];
|
|
1590
|
+
return !s || f.sha !== s.sha || f.mode !== s.mode;
|
|
1591
|
+
};
|
|
1592
|
+
for (const [p, f] of scan.files) {
|
|
1593
|
+
if (p in target) continue;
|
|
1594
|
+
const s = synced[p];
|
|
1595
|
+
if (s && s.sha === f.sha && s.mode === f.mode) {
|
|
1596
|
+
if (busy()) return "skipped";
|
|
1597
|
+
// Still untouched right now (a tool may have written it since the scan,
|
|
1598
|
+
// and such a write queues nothing): only then removed (Codex review).
|
|
1599
|
+
if (throughLink(dir, p) || (fs.existsSync(f.abs) && fs.lstatSync(f.abs).isSymbolicLink())) {
|
|
1600
|
+
blocked = true; // a link appeared on the way since the scan: never followed (Codex review)
|
|
1601
|
+
next[p] = s;
|
|
1602
|
+
continue;
|
|
1603
|
+
}
|
|
1604
|
+
if (fs.existsSync(f.abs) && (sha256Hex(fs.readFileSync(f.abs)) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
|
|
1605
|
+
ownChanges = true;
|
|
1606
|
+
next[p] = s;
|
|
1607
|
+
continue;
|
|
1608
|
+
}
|
|
1609
|
+
fs.rmSync(f.abs, { force: true }); // removed in the heads, untouched here
|
|
1610
|
+
delete progress[p];
|
|
1611
|
+
touched = true;
|
|
1612
|
+
wrote++;
|
|
1613
|
+
} else {
|
|
1614
|
+
// Made or changed here: the reconcile publishes it — against the version
|
|
1615
|
+
// it was synced at, so a delete elsewhere stays a conflict (Codex review).
|
|
1616
|
+
ownChanges = true;
|
|
1617
|
+
if (s) next[p] = s;
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
for (const [p, e] of Object.entries(target)) {
|
|
1621
|
+
const f = scan.files.get(p);
|
|
1622
|
+
if (f && f.sha === e.sha && f.mode === e.mode) {
|
|
1623
|
+
next[p] = { sha: e.sha, mode: e.mode };
|
|
1624
|
+
continue;
|
|
1625
|
+
}
|
|
1626
|
+
// Under a folder that is now a link here, a file is out of reach — not
|
|
1627
|
+
// deleted: left, and retried, never published as gone (Codex review).
|
|
1628
|
+
if (!f && throughLink(dir, p)) {
|
|
1629
|
+
blocked = true;
|
|
1630
|
+
if (synced[p]) next[p] = synced[p];
|
|
1631
|
+
continue;
|
|
1632
|
+
}
|
|
1633
|
+
if (scan.left.has(p) || (f ? mine(p, f) : !!synced[p])) {
|
|
1634
|
+
// This pod's own change (or a path the scan could not take): kept, and
|
|
1635
|
+
// its base stays what it was synced at. A path the scan could not take
|
|
1636
|
+
// (a link at the file itself) is retried next pass, like one under a
|
|
1637
|
+
// linked folder (Codex review).
|
|
1638
|
+
ownChanges = true;
|
|
1639
|
+
if (scan.left.has(p)) blocked = true;
|
|
1640
|
+
if (synced[p]) next[p] = synced[p];
|
|
1641
|
+
continue;
|
|
1642
|
+
}
|
|
1643
|
+
if (busy()) return "skipped"; // a write landed meanwhile: next round
|
|
1644
|
+
const bytes = await blobBytes(deps, tenant, e.sha);
|
|
1645
|
+
if (!bytes) throw new Error(`revisions: blob ${e.sha.slice(0, 12)} of ${tenant}/${workspace}/${p} is missing`);
|
|
1646
|
+
const abs = path.join(dir, p);
|
|
1647
|
+
// Never through a link: a folder on the way that is a symlink could lead
|
|
1648
|
+
// outside the workspace (Codex review). Such a path is left as it is.
|
|
1649
|
+
if (throughLink(dir, p)) {
|
|
1650
|
+
blocked = true; // tried again next pass: the heads are not counted as reached
|
|
1651
|
+
if (synced[p]) next[p] = synced[p];
|
|
1652
|
+
continue;
|
|
1653
|
+
}
|
|
1654
|
+
// A folder where the file goes (the heads turned a folder into a file):
|
|
1655
|
+
// its files were removed above if they were the heads'; an empty one goes.
|
|
1656
|
+
if (fs.existsSync(abs) && fs.lstatSync(abs).isDirectory()) {
|
|
1657
|
+
if (fs.readdirSync(abs, { recursive: true }).some((n) => !fs.statSync(path.join(abs, String(n))).isDirectory())) {
|
|
1658
|
+
ownChanges = true;
|
|
1659
|
+
blocked = true;
|
|
1660
|
+
continue;
|
|
1661
|
+
}
|
|
1662
|
+
fs.rmSync(abs, { recursive: true, force: true });
|
|
1663
|
+
}
|
|
1664
|
+
// Again after the download: a writer may have queued a change or touched
|
|
1665
|
+
// this very file while it ran (Codex review). The file must still be what
|
|
1666
|
+
// the scan saw, or it is this pod's change now and is left alone.
|
|
1667
|
+
if (busy()) return "skipped";
|
|
1668
|
+
const nowSha = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
|
|
1669
|
+
if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
|
|
1670
|
+
ownChanges = true;
|
|
1671
|
+
if (synced[p]) next[p] = synced[p];
|
|
1672
|
+
continue;
|
|
1673
|
+
}
|
|
1674
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
1675
|
+
const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
|
|
1676
|
+
fs.writeFileSync(tmp, bytes, { mode: e.mode === MODE_EXEC ? 0o755 : 0o644 });
|
|
1677
|
+
fs.chmodSync(tmp, e.mode === MODE_EXEC ? 0o755 : 0o644);
|
|
1678
|
+
fs.renameSync(tmp, abs);
|
|
1679
|
+
next[p] = { sha: e.sha, mode: e.mode };
|
|
1680
|
+
progress[p] = next[p];
|
|
1681
|
+
touched = true;
|
|
1682
|
+
wrote++;
|
|
1683
|
+
}
|
|
1684
|
+
// A file the heads have that could not be put in place (a link, a folder in
|
|
1685
|
+
// the way) keeps the old head ids, so every pass looks again rather than
|
|
1686
|
+
// answering "unchanged" until the next commit (Codex review).
|
|
1687
|
+
writeMirrorBase(tenant, workspace, { ...(blocked ? { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null } : ids), files: next, at: new Date().toISOString() });
|
|
1688
|
+
finished = true;
|
|
1689
|
+
if (ownChanges) requestReconcile(tenant, workspace);
|
|
1690
|
+
if (wrote && workspace !== "@library") notifyWorkspaceChanged(tenant, workspace, "write");
|
|
1691
|
+
return "synced";
|
|
1692
|
+
} finally {
|
|
1693
|
+
if (!finished && touched) writeMirrorBase(tenant, workspace, { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null, files: progress, at: new Date().toISOString() });
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
/** A file's mode as a manifest holds it. */
|
|
1698
|
+
function modeOfFile(abs: string): number {
|
|
1699
|
+
return fs.statSync(abs).mode & 0o111 ? MODE_EXEC : MODE_FILE;
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
/** Does any folder on the way to `rel` (inside `dir`) exist as a symlink? */
|
|
1703
|
+
function throughLink(dir: string, rel: string): boolean {
|
|
1704
|
+
const parts = rel.split("/").slice(0, -1);
|
|
1705
|
+
let at = dir;
|
|
1706
|
+
for (const part of parts) {
|
|
1707
|
+
at = path.join(at, part);
|
|
1708
|
+
let st: fs.Stats;
|
|
1709
|
+
try {
|
|
1710
|
+
st = fs.lstatSync(at);
|
|
1711
|
+
} catch {
|
|
1712
|
+
return false; // not there yet: made below, as a real folder
|
|
1713
|
+
}
|
|
1714
|
+
if (st.isSymbolicLink()) return true;
|
|
1715
|
+
if (!st.isDirectory()) return false; // a file in the way: removed above or reported
|
|
1716
|
+
}
|
|
1717
|
+
return false;
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
/** Every workspace with heads, and every copy here whose heads are gone. One
|
|
1721
|
+
* failure does not stop the rest. */
|
|
1722
|
+
export async function syncAllFromHeads(): Promise<{ synced: number; removed: number; failed: number }> {
|
|
1723
|
+
const deps = S.backend;
|
|
1724
|
+
const out = { synced: 0, removed: 0, failed: 0 };
|
|
1725
|
+
if (!deps?.revisions.allHeads || !mirrorOn()) return out;
|
|
1726
|
+
const all = await deps.revisions.allHeads();
|
|
1727
|
+
const seen = new Set(all.map((h) => key(h.tenant, h.workspace)));
|
|
1728
|
+
const todo = [...all.map((h) => ({ tenant: h.tenant, workspace: h.workspace })), ...mirroredWorkspaces().filter((w) => !seen.has(key(w.tenant, w.workspace)))];
|
|
1729
|
+
for (const w of todo) {
|
|
1730
|
+
try {
|
|
1731
|
+
const r = await syncFromHeads(w.tenant, w.workspace);
|
|
1732
|
+
if (r === "synced") out.synced++;
|
|
1733
|
+
else if (r === "removed") out.removed++;
|
|
1734
|
+
} catch (err) {
|
|
1735
|
+
out.failed++;
|
|
1736
|
+
opsError("revisions.mirror_sync_failed", err, { tenant: w.tenant, workspace: w.workspace }, "warn");
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
return out;
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1381
1742
|
// ------------------------------------------------------------- reading
|
|
1382
1743
|
|
|
1383
1744
|
async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffer | null> {
|