@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
|
@@ -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, accountDir, 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";
|
|
@@ -87,7 +88,7 @@ const entryStore = () => S.primary ?? legacyFiles;
|
|
|
87
88
|
export function setRevisionBackend(deps, opts = {}) {
|
|
88
89
|
// Every commit asks, inside the store's workspace lock, whether the folder is
|
|
89
90
|
// still there: a delete or rename on another pod removes it under that lock.
|
|
90
|
-
S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(
|
|
91
|
+
S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(folderOf(ws.tenant, ws.workspace))) } : null;
|
|
91
92
|
S.gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
|
|
92
93
|
S.primary = opts.journalStore ?? null;
|
|
93
94
|
S.retention = opts.stateRetention ?? null;
|
|
@@ -138,6 +139,17 @@ const restoring = S.restoring;
|
|
|
138
139
|
const key = (tenant, workspace) => `${tenant}\0${workspace}`;
|
|
139
140
|
const split = (k) => k.split("\0");
|
|
140
141
|
const journalRoot = () => path.join(dataRoot(), ".revision-journal");
|
|
142
|
+
/** Where a scope's files are: a workspace's folder, or for the account shelf
|
|
143
|
+
* ("@library") the account's own — its AGENTS.md and library/ (FOL-126). */
|
|
144
|
+
function folderOf(tenant, workspace) {
|
|
145
|
+
return workspace === "@library" ? accountDir(tenant) : workspaceDir(tenant, workspace);
|
|
146
|
+
}
|
|
147
|
+
/** The account's AGENTS.md or library changed outside the journal (a route
|
|
148
|
+
* that writes the file itself): publish it, as any other change of a scope. */
|
|
149
|
+
export function noteAccountFilesChanged(tenant) {
|
|
150
|
+
if (S.backend && journalOn())
|
|
151
|
+
requestReconcile(tenant, "@library");
|
|
152
|
+
}
|
|
141
153
|
/** Write the entry down, atomically. A store that refuses leaves the entry in
|
|
142
154
|
* memory only (said once per failure), as the journal always was. */
|
|
143
155
|
function persist(tenant, workspace, e) {
|
|
@@ -163,8 +175,8 @@ function forget(tenant, workspace, e) {
|
|
|
163
175
|
/** Called by history.recordRevision for every change set. Synchronous and
|
|
164
176
|
* cheap; the commit happens in the background (flushRevisions waits for it). */
|
|
165
177
|
function journalChange(tenant, scope, files, meta) {
|
|
166
|
-
if (!S.backend
|
|
167
|
-
return;
|
|
178
|
+
if (!S.backend)
|
|
179
|
+
return;
|
|
168
180
|
const k = key(tenant, scope);
|
|
169
181
|
if (!safe(S.gate.journal)) {
|
|
170
182
|
verified.delete(k); // a change the head will not see: reconcile before trusting it again
|
|
@@ -173,7 +185,9 @@ function journalChange(tenant, scope, files, meta) {
|
|
|
173
185
|
}
|
|
174
186
|
// Only what the head needs: the new content. The old text is the writer's
|
|
175
187
|
// history record, not the journal's (it can be a quarter megabyte a file).
|
|
176
|
-
|
|
188
|
+
// The account shelf's paths are `<kind>/<file>` in its own history and
|
|
189
|
+
// `library/<kind>/<file>` in its revisions (its folder is the account's).
|
|
190
|
+
const slim = files.map((f) => ({ path: scope === "@library" ? `library/${f.path}` : f.path, before: null, after: f.after }));
|
|
177
191
|
enqueue(tenant, scope, { id: crypto.randomBytes(12).toString("hex"), files: slim, by: meta.by, message: meta.message, at: meta.at, restoredFrom: restoring.get(k) });
|
|
178
192
|
}
|
|
179
193
|
function enqueue(tenant, scope, entry) {
|
|
@@ -303,7 +317,7 @@ async function drainOne(k) {
|
|
|
303
317
|
const entry = q[0];
|
|
304
318
|
// The workspace was deleted while this waited (or retried): nothing to
|
|
305
319
|
// publish, and nothing for a later boot to replay.
|
|
306
|
-
if (!fs.existsSync(
|
|
320
|
+
if (!fs.existsSync(folderOf(tenant, workspace))) {
|
|
307
321
|
q.shift();
|
|
308
322
|
forget(tenant, workspace, entry);
|
|
309
323
|
continue;
|
|
@@ -353,10 +367,10 @@ async function drainOne(k) {
|
|
|
353
367
|
// journal was off for a while, a run wrote the folder directly) is brought
|
|
354
368
|
// to it. After the entries, never before: replaying an older change over a
|
|
355
369
|
// reconciled head would write it backwards.
|
|
356
|
-
if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(
|
|
370
|
+
if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(folderOf(tenant, workspace))) {
|
|
357
371
|
verified.add(k);
|
|
358
372
|
try {
|
|
359
|
-
await
|
|
373
|
+
await reconcileNow(tenant, workspace, "reconcile");
|
|
360
374
|
}
|
|
361
375
|
catch (err) {
|
|
362
376
|
verified.delete(k);
|
|
@@ -771,6 +785,10 @@ export async function cleanOrphanedHistory(marks, opts) {
|
|
|
771
785
|
const deps = S.backend;
|
|
772
786
|
if (!deps)
|
|
773
787
|
return out;
|
|
788
|
+
// Folders are a copy of the heads (revisions.mirror): a missing one says
|
|
789
|
+
// nothing about the workspace, so nothing is taken for orphaned.
|
|
790
|
+
if (mirrorOn())
|
|
791
|
+
return out;
|
|
774
792
|
const root = dataRoot();
|
|
775
793
|
let rootEntries = 0;
|
|
776
794
|
try {
|
|
@@ -855,7 +873,7 @@ export async function recoverJournal(opts = {}) {
|
|
|
855
873
|
const k = key(tenant, workspace);
|
|
856
874
|
const q = queues.get(k) ?? [];
|
|
857
875
|
const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
|
|
858
|
-
const gone = !fs.existsSync(
|
|
876
|
+
const gone = !fs.existsSync(folderOf(tenant, workspace));
|
|
859
877
|
const found = [];
|
|
860
878
|
let names = [];
|
|
861
879
|
try {
|
|
@@ -915,7 +933,9 @@ export async function reconcileAll(opts = {}) {
|
|
|
915
933
|
if (S.orphanMarks)
|
|
916
934
|
await cleanOrphanedHistory(S.orphanMarks, { graceMs: S.orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
|
|
917
935
|
for (const tenant of opts.tenants ?? listTenants()) {
|
|
918
|
-
|
|
936
|
+
// The account shelf too (account AGENTS.md + library/), as a scope of its own.
|
|
937
|
+
const shelf = ["AGENTS.md", "library"].some((n) => fs.existsSync(path.join(accountDir(tenant), n)));
|
|
938
|
+
for (const w of [...listWorkspaces(tenant), ...(shelf ? [{ name: "@library" }] : [])]) {
|
|
919
939
|
const k = key(tenant, w.name);
|
|
920
940
|
try {
|
|
921
941
|
verified.add(k); // reconciled explicitly below, and counted
|
|
@@ -924,7 +944,7 @@ export async function reconcileAll(opts = {}) {
|
|
|
924
944
|
verified.delete(k);
|
|
925
945
|
continue; // the store is not taking writes: leave it
|
|
926
946
|
}
|
|
927
|
-
const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() =>
|
|
947
|
+
const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() => reconcileNow(tenant, w.name, opts.by ?? "reconcile"));
|
|
928
948
|
chains.set(k, next);
|
|
929
949
|
const res = await next;
|
|
930
950
|
verified.add(k);
|
|
@@ -967,7 +987,7 @@ async function hashOf(abs, size) {
|
|
|
967
987
|
* not be read. Null when the folder is not there.
|
|
968
988
|
*/
|
|
969
989
|
async function scanFolder(tenant, workspace) {
|
|
970
|
-
const dir =
|
|
990
|
+
const dir = folderOf(tenant, workspace);
|
|
971
991
|
if (!fs.existsSync(dir))
|
|
972
992
|
return null;
|
|
973
993
|
const found = [];
|
|
@@ -1069,7 +1089,7 @@ async function uploadLarge(deps, tenant, changes, onDisk, opId) {
|
|
|
1069
1089
|
}
|
|
1070
1090
|
function modeOf(tenant, workspace, rel) {
|
|
1071
1091
|
try {
|
|
1072
|
-
return fs.statSync(path.join(
|
|
1092
|
+
return fs.statSync(path.join(folderOf(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
|
|
1073
1093
|
}
|
|
1074
1094
|
catch {
|
|
1075
1095
|
return MODE_FILE;
|
|
@@ -1126,6 +1146,13 @@ async function commitEntry(deps, tenant, workspace, entry) {
|
|
|
1126
1146
|
// run, a person) is a conflict on the path, and disjoint paths replay. Where
|
|
1127
1147
|
// the revision cannot be read any more, the folder's sha stands in.
|
|
1128
1148
|
const fromRev = await baseManifests(deps, tenant, workspace, entry.baseRev);
|
|
1149
|
+
// A pod whose folder is a copy of the heads (revisions.mirror): a change
|
|
1150
|
+
// written here was made against the version this pod last synced — its
|
|
1151
|
+
// base, so one made meanwhile on another pod is a conflict (both kept),
|
|
1152
|
+
// never overwritten (Codex review). Syncs wait while entries are queued, so
|
|
1153
|
+
// the record still says what the writer saw.
|
|
1154
|
+
const synced = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
|
|
1155
|
+
const plainBase = (rel, was) => synced ? (synced.files[rel] ? entryId(synced.files[rel]) : null) : was ? entryId(was) : null;
|
|
1129
1156
|
const put = (rel, buf, side, pinned, handed) => {
|
|
1130
1157
|
const sha = sha256Hex(buf);
|
|
1131
1158
|
bytes.set(sha, buf);
|
|
@@ -1139,7 +1166,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
|
|
|
1139
1166
|
const atRev = fromRev[side]?.files[rel];
|
|
1140
1167
|
const usable = fromRev[side] !== undefined && handed !== undefined && handed === (atRev ? atRev.sha : null);
|
|
1141
1168
|
const pinnedTo = pinned === undefined ? undefined : usable ? (atRev ? entryId(atRev) : null) : pinnedBase(pinned, was);
|
|
1142
|
-
changes[rel] = { op: "put", base: pinned === undefined ? (
|
|
1169
|
+
changes[rel] = { op: "put", base: pinned === undefined ? plainBase(rel, was) : pinnedTo, sha, size: buf.length, mode };
|
|
1143
1170
|
};
|
|
1144
1171
|
if (baseline.authored || baseline.state) {
|
|
1145
1172
|
// Nothing is recorded for (part of) this workspace yet: its tree, as the
|
|
@@ -1164,8 +1191,9 @@ async function commitEntry(deps, tenant, workspace, entry) {
|
|
|
1164
1191
|
continue; // in the baseline
|
|
1165
1192
|
const was = head[side].files[f.path];
|
|
1166
1193
|
if (f.after === null) {
|
|
1167
|
-
|
|
1168
|
-
|
|
1194
|
+
// A delete of a file this pod never synced deletes nothing elsewhere.
|
|
1195
|
+
if (was && (!synced || synced.files[f.path]))
|
|
1196
|
+
changes[f.path] = { op: "delete", base: plainBase(f.path, was) ?? entryId(was) };
|
|
1169
1197
|
}
|
|
1170
1198
|
else {
|
|
1171
1199
|
put(f.path, bytesOfEntry(f), side, f.base, f.handed);
|
|
@@ -1194,7 +1222,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
|
|
|
1194
1222
|
if (!Object.keys(todo).length)
|
|
1195
1223
|
return null;
|
|
1196
1224
|
try {
|
|
1197
|
-
return await publish(deps, {
|
|
1225
|
+
return await afterPublish(deps, ws, todo, await publish(deps, {
|
|
1198
1226
|
ws,
|
|
1199
1227
|
// The op id of a side that finished, when one did, so the other side's
|
|
1200
1228
|
// conflict copies are named the way the first attempt would have.
|
|
@@ -1209,7 +1237,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
|
|
|
1209
1237
|
throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
|
|
1210
1238
|
return b;
|
|
1211
1239
|
},
|
|
1212
|
-
});
|
|
1240
|
+
}));
|
|
1213
1241
|
}
|
|
1214
1242
|
catch (err) {
|
|
1215
1243
|
// Never "done" by itself: a side that finished is found by sidesDone on
|
|
@@ -1248,10 +1276,25 @@ async function sidesDone(deps, ws, id) {
|
|
|
1248
1276
|
* (until 13 Nov 2026: only the text files the editor lists, so a binary file
|
|
1249
1277
|
* never reached a head and one the importer had put there was never updated
|
|
1250
1278
|
* or removed — a run staged from the head was handed files deleted days ago). */
|
|
1251
|
-
|
|
1279
|
+
/** Bring the heads to this pod's folder (see reconcileNow), in turn with
|
|
1280
|
+
* everything else that commits this workspace here: two at once would diff
|
|
1281
|
+
* the same folder against the same head and race each other's publish. */
|
|
1282
|
+
export function reconcileWorkspace(tenant, workspace, by = "reconcile") {
|
|
1283
|
+
const k = key(tenant, workspace);
|
|
1284
|
+
const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() => reconcileNow(tenant, workspace, by));
|
|
1285
|
+
chains.set(k, next);
|
|
1286
|
+
return next;
|
|
1287
|
+
}
|
|
1288
|
+
async function reconcileNow(tenant, workspace, by = "reconcile") {
|
|
1252
1289
|
const deps = S.backend;
|
|
1253
1290
|
if (!deps)
|
|
1254
1291
|
return null;
|
|
1292
|
+
// A copy this pod has not synced yet is not the truth about anything: an
|
|
1293
|
+
// empty disk at start would otherwise publish every file as deleted. Its
|
|
1294
|
+
// own writes reach the head through the journal; the reconcile waits for a
|
|
1295
|
+
// sync to say what "changed here" means.
|
|
1296
|
+
if (mirrorOn() && !readMirrorBase(tenant, workspace))
|
|
1297
|
+
return null;
|
|
1255
1298
|
const ws = { tenant, workspace };
|
|
1256
1299
|
const k = key(tenant, workspace);
|
|
1257
1300
|
// The mark goes BEFORE the folder is read, so one set after the read (a run
|
|
@@ -1270,12 +1313,18 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
|
|
|
1270
1313
|
return null;
|
|
1271
1314
|
const head = await manifestsAt(deps, tenant, heads);
|
|
1272
1315
|
const onDisk = new Map();
|
|
1273
|
-
|
|
1274
|
-
|
|
1316
|
+
let want = emptyManifest();
|
|
1317
|
+
let have = { v: 1, files: { ...head.authored.files, ...head.state.files } };
|
|
1275
1318
|
for (const [rel, f] of scan.files) {
|
|
1276
1319
|
onDisk.set(f.sha, f.abs);
|
|
1277
1320
|
want.files[rel] = { sha: f.sha, size: f.size, mode: f.mode };
|
|
1278
1321
|
}
|
|
1322
|
+
// A pod whose folder is a copy of the heads (revisions.mirror): only what
|
|
1323
|
+
// differs from the last sync is this pod's change. A difference from the
|
|
1324
|
+
// head alone is someone else's change not copied here yet, never undone.
|
|
1325
|
+
const base = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
|
|
1326
|
+
if (base)
|
|
1327
|
+
({ have, want } = threeWay(have, scan, base, folderOf(tenant, workspace)));
|
|
1279
1328
|
// A path the scan could not take (unreadable now, a name the manifest
|
|
1280
1329
|
// refuses) but the folder still holds is neither added nor removed here;
|
|
1281
1330
|
// one that is gone from the folder is gone from the head.
|
|
@@ -1295,7 +1344,7 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
|
|
|
1295
1344
|
const opId = opIdOf("jx", requestDigest("reconcile", { changes, heads: [heads.workspace?.id ?? null, heads.state?.id ?? null] }).slice(0, 40));
|
|
1296
1345
|
const release = await uploadLarge(deps, tenant, changes, onDisk, opId);
|
|
1297
1346
|
try {
|
|
1298
|
-
return await publish(deps, {
|
|
1347
|
+
return await afterPublish(deps, ws, changes, await publish(deps, {
|
|
1299
1348
|
ws,
|
|
1300
1349
|
opId,
|
|
1301
1350
|
by,
|
|
@@ -1305,7 +1354,7 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
|
|
|
1305
1354
|
// the sha, so a file that changed since the scan fails this repair (the
|
|
1306
1355
|
// mark is put back and the next one sees the new bytes).
|
|
1307
1356
|
bytesOf: async (sha) => fs.promises.readFile(onDisk.get(sha)),
|
|
1308
|
-
});
|
|
1357
|
+
}));
|
|
1309
1358
|
}
|
|
1310
1359
|
finally {
|
|
1311
1360
|
await release();
|
|
@@ -1322,6 +1371,358 @@ export async function reconcileWorkspace(tenant, workspace, by = "reconcile") {
|
|
|
1322
1371
|
repairing.delete(k);
|
|
1323
1372
|
}
|
|
1324
1373
|
}
|
|
1374
|
+
/** After this pod published changes of its own (revisions.mirror): what it
|
|
1375
|
+
* published is now what the heads hold, so its copy is synced for those
|
|
1376
|
+
* paths. A path that conflicted kept the head's version (this pod's is the
|
|
1377
|
+
* conflict copy beside it), so this pod takes the head's version too — unless
|
|
1378
|
+
* the file changed here again since. Returns the result unchanged. */
|
|
1379
|
+
async function afterPublish(deps, ws, changes, r) {
|
|
1380
|
+
if (!mirrorOn())
|
|
1381
|
+
return r;
|
|
1382
|
+
try {
|
|
1383
|
+
const { tenant, workspace } = ws;
|
|
1384
|
+
const base = readMirrorBase(tenant, workspace) ?? { workspaceHead: null, stateHead: null, files: {}, at: new Date().toISOString() };
|
|
1385
|
+
const conflicted = new Set(r.conflicts.map((c) => c.path));
|
|
1386
|
+
const dir = folderOf(tenant, workspace);
|
|
1387
|
+
let head = null;
|
|
1388
|
+
for (const [p, c] of Object.entries(changes)) {
|
|
1389
|
+
if (!conflicted.has(p)) {
|
|
1390
|
+
if (c.op === "delete")
|
|
1391
|
+
delete base.files[p];
|
|
1392
|
+
else
|
|
1393
|
+
base.files[p] = { sha: c.sha, mode: c.mode };
|
|
1394
|
+
continue;
|
|
1395
|
+
}
|
|
1396
|
+
head ??= await (async () => {
|
|
1397
|
+
const m = await manifestsAt(deps, tenant, await headsOf(deps, ws));
|
|
1398
|
+
return { ...m.authored.files, ...m.state.files };
|
|
1399
|
+
})();
|
|
1400
|
+
const winner = head[p];
|
|
1401
|
+
const abs = path.join(dir, p);
|
|
1402
|
+
// Never through a link, on any branch below (Codex review).
|
|
1403
|
+
if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
|
|
1404
|
+
continue;
|
|
1405
|
+
const local = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
|
|
1406
|
+
// Only while the file is still what this pod published (or gone, for a delete).
|
|
1407
|
+
if (c.op === "delete" ? local !== null : local !== c.sha)
|
|
1408
|
+
continue;
|
|
1409
|
+
if (winner) {
|
|
1410
|
+
const b = await blobBytes(deps, tenant, winner.sha);
|
|
1411
|
+
if (!b)
|
|
1412
|
+
continue;
|
|
1413
|
+
// Again after the download: an edit made meanwhile is kept, and never
|
|
1414
|
+
// through a link — the file or a folder on its way (Codex review).
|
|
1415
|
+
if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
|
|
1416
|
+
continue;
|
|
1417
|
+
if ((fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null) !== local)
|
|
1418
|
+
continue;
|
|
1419
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
1420
|
+
// A new file renamed over the old one: replaces it, follows nothing.
|
|
1421
|
+
const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
|
|
1422
|
+
fs.writeFileSync(tmp, b, { mode: winner.mode === MODE_EXEC ? 0o755 : 0o644 });
|
|
1423
|
+
fs.chmodSync(tmp, winner.mode === MODE_EXEC ? 0o755 : 0o644);
|
|
1424
|
+
fs.renameSync(tmp, abs);
|
|
1425
|
+
base.files[p] = { sha: winner.sha, mode: winner.mode };
|
|
1426
|
+
}
|
|
1427
|
+
else {
|
|
1428
|
+
// The head deleted it; this pod's version is the conflict copy. The
|
|
1429
|
+
// original goes too, or the next reconcile would bring it back.
|
|
1430
|
+
fs.rmSync(abs, { force: true });
|
|
1431
|
+
delete base.files[p];
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
writeMirrorBase(tenant, workspace, { ...base, at: new Date().toISOString() });
|
|
1435
|
+
}
|
|
1436
|
+
catch (err) {
|
|
1437
|
+
opsError("revisions.mirror_note_failed", err, { tenant: ws.tenant, workspace: ws.workspace }, "warn");
|
|
1438
|
+
}
|
|
1439
|
+
return r;
|
|
1440
|
+
}
|
|
1441
|
+
/** The reconcile's diff for a mirrored folder: the head, with this pod's own
|
|
1442
|
+
* changes since its last sync on top — each path's base the version it was
|
|
1443
|
+
* synced at, so one someone else changed meanwhile is a conflict (both kept),
|
|
1444
|
+
* never a silent overwrite. */
|
|
1445
|
+
function threeWay(headM, scan, base, dir) {
|
|
1446
|
+
const have = { v: 1, files: { ...headM.files } };
|
|
1447
|
+
const want = { v: 1, files: { ...headM.files } };
|
|
1448
|
+
const same = (a, b) => !!a && !!b && a.sha === b.sha && a.mode === b.mode;
|
|
1449
|
+
for (const [p, f] of scan.files) {
|
|
1450
|
+
const synced = base.files[p];
|
|
1451
|
+
if (same(f, synced) || same(f, headM.files[p]))
|
|
1452
|
+
continue; // not changed here, or already the head's
|
|
1453
|
+
if (synced)
|
|
1454
|
+
have.files[p] = { sha: synced.sha, mode: synced.mode, size: headM.files[p]?.size ?? 0 };
|
|
1455
|
+
else
|
|
1456
|
+
delete have.files[p];
|
|
1457
|
+
want.files[p] = { sha: f.sha, size: f.size, mode: f.mode };
|
|
1458
|
+
}
|
|
1459
|
+
for (const [p, synced] of Object.entries(base.files)) {
|
|
1460
|
+
if (scan.files.has(p) || scan.left.has(p))
|
|
1461
|
+
continue;
|
|
1462
|
+
if (throughLink(dir, p))
|
|
1463
|
+
continue; // out of reach under a link, not deleted
|
|
1464
|
+
// Deleted here since the sync: gone from the head too, from the version
|
|
1465
|
+
// this pod had (a newer one elsewhere makes it a conflict).
|
|
1466
|
+
if (!headM.files[p])
|
|
1467
|
+
continue;
|
|
1468
|
+
have.files[p] = { sha: synced.sha, mode: synced.mode, size: headM.files[p].size };
|
|
1469
|
+
delete want.files[p];
|
|
1470
|
+
}
|
|
1471
|
+
return { have, want };
|
|
1472
|
+
}
|
|
1473
|
+
/**
|
|
1474
|
+
* Bring this pod's copy of a workspace to its heads (FOL-126, the shared
|
|
1475
|
+
* volume retired; revisions.mirror). What changed in the heads since the last
|
|
1476
|
+
* sync is written or removed; what changed HERE since then is left as it is
|
|
1477
|
+
* and handed to the reconcile, which publishes it against the version it was
|
|
1478
|
+
* synced at. Never while this pod has changes of its own still to publish.
|
|
1479
|
+
* A workspace whose heads are gone (deleted, renamed away) is removed here
|
|
1480
|
+
* only if this pod's copy came from them.
|
|
1481
|
+
*/
|
|
1482
|
+
export function syncFromHeads(tenant, workspace) {
|
|
1483
|
+
// In turn with this workspace's commits and reconciles here (the same
|
|
1484
|
+
// chain): a reconcile must never scan a folder a sync is half way through,
|
|
1485
|
+
// or the files it already brought would read as this pod's changes (Codex
|
|
1486
|
+
// review).
|
|
1487
|
+
if (!S.backend || !mirrorOn())
|
|
1488
|
+
return Promise.resolve("skipped");
|
|
1489
|
+
const k = key(tenant, workspace);
|
|
1490
|
+
const next = (chains.get(k) ?? Promise.resolve()).catch(() => { }).then(() => syncNow(tenant, workspace));
|
|
1491
|
+
chains.set(k, next);
|
|
1492
|
+
return next;
|
|
1493
|
+
}
|
|
1494
|
+
async function syncNow(tenant, workspace) {
|
|
1495
|
+
const deps = S.backend;
|
|
1496
|
+
if (!deps || !mirrorOn())
|
|
1497
|
+
return "skipped";
|
|
1498
|
+
const k = key(tenant, workspace);
|
|
1499
|
+
const busy = () => (queues.get(k)?.length ?? 0) > 0 || repairing.has(k) || frozen.has(k);
|
|
1500
|
+
if (busy())
|
|
1501
|
+
return "skipped";
|
|
1502
|
+
const dir = folderOf(tenant, workspace);
|
|
1503
|
+
// A copy whose folder is gone (the disk was cleared, a hand rm) starts again
|
|
1504
|
+
// from the heads: with the old record kept, every file would read as deleted
|
|
1505
|
+
// here and the reconcile would publish those deletes (Codex review).
|
|
1506
|
+
let base = readMirrorBase(tenant, workspace);
|
|
1507
|
+
if (base && !fs.existsSync(dir)) {
|
|
1508
|
+
dropMirrorBase(tenant, workspace);
|
|
1509
|
+
base = null;
|
|
1510
|
+
}
|
|
1511
|
+
const heads = await headsOf(deps, { tenant, workspace });
|
|
1512
|
+
if (!heads.workspace && !heads.state) {
|
|
1513
|
+
if (!base)
|
|
1514
|
+
return "absent";
|
|
1515
|
+
if (busy())
|
|
1516
|
+
return "skipped";
|
|
1517
|
+
if (workspace === "@library") {
|
|
1518
|
+
// The shelf's folder is the ACCOUNT's: only what the shelf owns goes —
|
|
1519
|
+
// never the account folder with every workspace in it (Codex review).
|
|
1520
|
+
fs.rmSync(path.join(dir, "AGENTS.md"), { force: true });
|
|
1521
|
+
fs.rmSync(path.join(dir, "library"), { recursive: true, force: true });
|
|
1522
|
+
}
|
|
1523
|
+
else
|
|
1524
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
1525
|
+
dropMirrorBase(tenant, workspace);
|
|
1526
|
+
if (workspace !== "@library")
|
|
1527
|
+
notifyWorkspaceChanged(tenant, workspace, "delete");
|
|
1528
|
+
return "removed";
|
|
1529
|
+
}
|
|
1530
|
+
const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
|
|
1531
|
+
if (base && base.workspaceHead === ids.workspaceHead && base.stateHead === ids.stateHead && fs.existsSync(dir))
|
|
1532
|
+
return "unchanged";
|
|
1533
|
+
const m = await manifestsAt(deps, tenant, heads);
|
|
1534
|
+
const target = { ...m.authored.files, ...m.state.files };
|
|
1535
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1536
|
+
const scan = (await scanFolder(tenant, workspace)) ?? { files: new Map(), left: new Set() };
|
|
1537
|
+
const synced = base?.files ?? {};
|
|
1538
|
+
const next = {};
|
|
1539
|
+
// What this pass has done so far, over the old base: kept if it stops early
|
|
1540
|
+
// (a download fails, a write lands), so what it wrote is not later taken for
|
|
1541
|
+
// this pod's own change. The head ids stay the old ones, so the next pass
|
|
1542
|
+
// runs again (Codex review).
|
|
1543
|
+
const progress = { ...synced };
|
|
1544
|
+
let finished = false;
|
|
1545
|
+
let touched = false;
|
|
1546
|
+
let blocked = false; // a head file could not be put in place: not counted as synced
|
|
1547
|
+
try {
|
|
1548
|
+
let ownChanges = false;
|
|
1549
|
+
let wrote = 0;
|
|
1550
|
+
// A file here that differs from what the last sync brought is this pod's
|
|
1551
|
+
// own: one the sync never brought (or the first sync of a folder that
|
|
1552
|
+
// already had files) counts as made here — kept, never overwritten.
|
|
1553
|
+
const mine = (p, f) => {
|
|
1554
|
+
const s = synced[p];
|
|
1555
|
+
return !s || f.sha !== s.sha || f.mode !== s.mode;
|
|
1556
|
+
};
|
|
1557
|
+
for (const [p, f] of scan.files) {
|
|
1558
|
+
if (p in target)
|
|
1559
|
+
continue;
|
|
1560
|
+
const s = synced[p];
|
|
1561
|
+
if (s && s.sha === f.sha && s.mode === f.mode) {
|
|
1562
|
+
if (busy())
|
|
1563
|
+
return "skipped";
|
|
1564
|
+
// Still untouched right now (a tool may have written it since the scan,
|
|
1565
|
+
// and such a write queues nothing): only then removed (Codex review).
|
|
1566
|
+
if (throughLink(dir, p) || (fs.existsSync(f.abs) && fs.lstatSync(f.abs).isSymbolicLink())) {
|
|
1567
|
+
blocked = true; // a link appeared on the way since the scan: never followed (Codex review)
|
|
1568
|
+
next[p] = s;
|
|
1569
|
+
continue;
|
|
1570
|
+
}
|
|
1571
|
+
if (fs.existsSync(f.abs) && (sha256Hex(fs.readFileSync(f.abs)) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
|
|
1572
|
+
ownChanges = true;
|
|
1573
|
+
next[p] = s;
|
|
1574
|
+
continue;
|
|
1575
|
+
}
|
|
1576
|
+
fs.rmSync(f.abs, { force: true }); // removed in the heads, untouched here
|
|
1577
|
+
delete progress[p];
|
|
1578
|
+
touched = true;
|
|
1579
|
+
wrote++;
|
|
1580
|
+
}
|
|
1581
|
+
else {
|
|
1582
|
+
// Made or changed here: the reconcile publishes it — against the version
|
|
1583
|
+
// it was synced at, so a delete elsewhere stays a conflict (Codex review).
|
|
1584
|
+
ownChanges = true;
|
|
1585
|
+
if (s)
|
|
1586
|
+
next[p] = s;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
for (const [p, e] of Object.entries(target)) {
|
|
1590
|
+
const f = scan.files.get(p);
|
|
1591
|
+
if (f && f.sha === e.sha && f.mode === e.mode) {
|
|
1592
|
+
next[p] = { sha: e.sha, mode: e.mode };
|
|
1593
|
+
continue;
|
|
1594
|
+
}
|
|
1595
|
+
// Under a folder that is now a link here, a file is out of reach — not
|
|
1596
|
+
// deleted: left, and retried, never published as gone (Codex review).
|
|
1597
|
+
if (!f && throughLink(dir, p)) {
|
|
1598
|
+
blocked = true;
|
|
1599
|
+
if (synced[p])
|
|
1600
|
+
next[p] = synced[p];
|
|
1601
|
+
continue;
|
|
1602
|
+
}
|
|
1603
|
+
if (scan.left.has(p) || (f ? mine(p, f) : !!synced[p])) {
|
|
1604
|
+
// This pod's own change (or a path the scan could not take): kept, and
|
|
1605
|
+
// its base stays what it was synced at. A path the scan could not take
|
|
1606
|
+
// (a link at the file itself) is retried next pass, like one under a
|
|
1607
|
+
// linked folder (Codex review).
|
|
1608
|
+
ownChanges = true;
|
|
1609
|
+
if (scan.left.has(p))
|
|
1610
|
+
blocked = true;
|
|
1611
|
+
if (synced[p])
|
|
1612
|
+
next[p] = synced[p];
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
if (busy())
|
|
1616
|
+
return "skipped"; // a write landed meanwhile: next round
|
|
1617
|
+
const bytes = await blobBytes(deps, tenant, e.sha);
|
|
1618
|
+
if (!bytes)
|
|
1619
|
+
throw new Error(`revisions: blob ${e.sha.slice(0, 12)} of ${tenant}/${workspace}/${p} is missing`);
|
|
1620
|
+
const abs = path.join(dir, p);
|
|
1621
|
+
// Never through a link: a folder on the way that is a symlink could lead
|
|
1622
|
+
// outside the workspace (Codex review). Such a path is left as it is.
|
|
1623
|
+
if (throughLink(dir, p)) {
|
|
1624
|
+
blocked = true; // tried again next pass: the heads are not counted as reached
|
|
1625
|
+
if (synced[p])
|
|
1626
|
+
next[p] = synced[p];
|
|
1627
|
+
continue;
|
|
1628
|
+
}
|
|
1629
|
+
// A folder where the file goes (the heads turned a folder into a file):
|
|
1630
|
+
// its files were removed above if they were the heads'; an empty one goes.
|
|
1631
|
+
if (fs.existsSync(abs) && fs.lstatSync(abs).isDirectory()) {
|
|
1632
|
+
if (fs.readdirSync(abs, { recursive: true }).some((n) => !fs.statSync(path.join(abs, String(n))).isDirectory())) {
|
|
1633
|
+
ownChanges = true;
|
|
1634
|
+
blocked = true;
|
|
1635
|
+
continue;
|
|
1636
|
+
}
|
|
1637
|
+
fs.rmSync(abs, { recursive: true, force: true });
|
|
1638
|
+
}
|
|
1639
|
+
// Again after the download: a writer may have queued a change or touched
|
|
1640
|
+
// this very file while it ran (Codex review). The file must still be what
|
|
1641
|
+
// the scan saw, or it is this pod's change now and is left alone.
|
|
1642
|
+
if (busy())
|
|
1643
|
+
return "skipped";
|
|
1644
|
+
const nowSha = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
|
|
1645
|
+
if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
|
|
1646
|
+
ownChanges = true;
|
|
1647
|
+
if (synced[p])
|
|
1648
|
+
next[p] = synced[p];
|
|
1649
|
+
continue;
|
|
1650
|
+
}
|
|
1651
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
1652
|
+
const tmp = `${abs}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.mirror-tmp`;
|
|
1653
|
+
fs.writeFileSync(tmp, bytes, { mode: e.mode === MODE_EXEC ? 0o755 : 0o644 });
|
|
1654
|
+
fs.chmodSync(tmp, e.mode === MODE_EXEC ? 0o755 : 0o644);
|
|
1655
|
+
fs.renameSync(tmp, abs);
|
|
1656
|
+
next[p] = { sha: e.sha, mode: e.mode };
|
|
1657
|
+
progress[p] = next[p];
|
|
1658
|
+
touched = true;
|
|
1659
|
+
wrote++;
|
|
1660
|
+
}
|
|
1661
|
+
// A file the heads have that could not be put in place (a link, a folder in
|
|
1662
|
+
// the way) keeps the old head ids, so every pass looks again rather than
|
|
1663
|
+
// answering "unchanged" until the next commit (Codex review).
|
|
1664
|
+
writeMirrorBase(tenant, workspace, { ...(blocked ? { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null } : ids), files: next, at: new Date().toISOString() });
|
|
1665
|
+
finished = true;
|
|
1666
|
+
if (ownChanges)
|
|
1667
|
+
requestReconcile(tenant, workspace);
|
|
1668
|
+
if (wrote && workspace !== "@library")
|
|
1669
|
+
notifyWorkspaceChanged(tenant, workspace, "write");
|
|
1670
|
+
return "synced";
|
|
1671
|
+
}
|
|
1672
|
+
finally {
|
|
1673
|
+
if (!finished && touched)
|
|
1674
|
+
writeMirrorBase(tenant, workspace, { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null, files: progress, at: new Date().toISOString() });
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
/** A file's mode as a manifest holds it. */
|
|
1678
|
+
function modeOfFile(abs) {
|
|
1679
|
+
return fs.statSync(abs).mode & 0o111 ? MODE_EXEC : MODE_FILE;
|
|
1680
|
+
}
|
|
1681
|
+
/** Does any folder on the way to `rel` (inside `dir`) exist as a symlink? */
|
|
1682
|
+
function throughLink(dir, rel) {
|
|
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;
|
|
1688
|
+
try {
|
|
1689
|
+
st = fs.lstatSync(at);
|
|
1690
|
+
}
|
|
1691
|
+
catch {
|
|
1692
|
+
return false; // not there yet: made below, as a real folder
|
|
1693
|
+
}
|
|
1694
|
+
if (st.isSymbolicLink())
|
|
1695
|
+
return true;
|
|
1696
|
+
if (!st.isDirectory())
|
|
1697
|
+
return false; // a file in the way: removed above or reported
|
|
1698
|
+
}
|
|
1699
|
+
return false;
|
|
1700
|
+
}
|
|
1701
|
+
/** Every workspace with heads, and every copy here whose heads are gone. One
|
|
1702
|
+
* failure does not stop the rest. */
|
|
1703
|
+
export async function syncAllFromHeads() {
|
|
1704
|
+
const deps = S.backend;
|
|
1705
|
+
const out = { synced: 0, removed: 0, failed: 0 };
|
|
1706
|
+
if (!deps?.revisions.allHeads || !mirrorOn())
|
|
1707
|
+
return out;
|
|
1708
|
+
const all = await deps.revisions.allHeads();
|
|
1709
|
+
const seen = new Set(all.map((h) => key(h.tenant, h.workspace)));
|
|
1710
|
+
const todo = [...all.map((h) => ({ tenant: h.tenant, workspace: h.workspace })), ...mirroredWorkspaces().filter((w) => !seen.has(key(w.tenant, w.workspace)))];
|
|
1711
|
+
for (const w of todo) {
|
|
1712
|
+
try {
|
|
1713
|
+
const r = await syncFromHeads(w.tenant, w.workspace);
|
|
1714
|
+
if (r === "synced")
|
|
1715
|
+
out.synced++;
|
|
1716
|
+
else if (r === "removed")
|
|
1717
|
+
out.removed++;
|
|
1718
|
+
}
|
|
1719
|
+
catch (err) {
|
|
1720
|
+
out.failed++;
|
|
1721
|
+
opsError("revisions.mirror_sync_failed", err, { tenant: w.tenant, workspace: w.workspace }, "warn");
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
return out;
|
|
1725
|
+
}
|
|
1325
1726
|
// ------------------------------------------------------------- reading
|
|
1326
1727
|
async function blobBytes(deps, tenant, sha) {
|
|
1327
1728
|
const hit = await S.cache?.get(tenant, sha);
|
package/package.json
CHANGED
package/src/agent-import.ts
CHANGED
|
@@ -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
|
}
|