@foldrun/core 17.4.0 → 18.0.1

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.
@@ -54,7 +54,7 @@ import {
54
54
  type Changes,
55
55
  type Manifest,
56
56
  } from "./manifest.ts";
57
- import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, PublishError, type Deps, type Heads, type PublishResult } from "./publish.ts";
57
+ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError, type Deps, type Heads, type PublishResult } from "./publish.ts";
58
58
  import { OpIdReused, type Revision, type WorkspaceRef } from "./revision-store.ts";
59
59
  import { pruneStateRevisions, type StateRetention } from "./state-retention.ts";
60
60
  import type { SweepMarks } from "./blob-sweeper.ts";
@@ -181,6 +181,8 @@ const queues = new Map<string, Entry[]>();
181
181
  const chains = new Map<string, Promise<unknown>>();
182
182
  const marked = new Set<string>(); // overflowed or dropped: needs reconcileWorkspace
183
183
  const verified = new Set<string>(); // reconciled once in this process
184
+ const unjournalled = new Set<string>(); // changed here while the journal was off: the head has not seen it
185
+ const repairing = new Set<string>(); // a reconcile is publishing: the head is about to change
184
186
  const retryAt = new Map<string, number>();
185
187
  const wantPrune = new Set<string>(); // a state checkpoint was committed since the last look
186
188
  const prunedAt = new Map<string, number>();
@@ -220,6 +222,7 @@ function journalChange(tenant: string, scope: string, files: RevisionFile[], met
220
222
  const k = key(tenant, scope);
221
223
  if (!safe(gate.journal)) {
222
224
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
225
+ unjournalled.add(k);
223
226
  return;
224
227
  }
225
228
  // Only what the head needs: the new content. The old text is the writer's
@@ -297,6 +300,7 @@ export function recordStepOutputs(
297
300
  const k = key(tenant, workspace);
298
301
  if (!safe(gate.journal)) {
299
302
  verified.delete(k); // the head will not see this: reconcile before trusting it again
303
+ unjournalled.add(k);
300
304
  return 0;
301
305
  }
302
306
  const files: EntryFile[] = [];
@@ -428,6 +432,7 @@ async function drainOne(k: string): Promise<void> {
428
432
  /** An error that retrying will not cure: the manifest refused the content. */
429
433
  function permanent(err: unknown): boolean {
430
434
  if (err instanceof PublishError) return err.code === "bad_change";
435
+ if (err instanceof OpIdReused) return true; // commitEntry asked again and it still is: see there
431
436
  const m = err instanceof Error ? err.message : "";
432
437
  return /^illegal manifest path|differ only by case|a manifest holds at most|is not workspace content/.test(m);
433
438
  }
@@ -448,6 +453,8 @@ export function resetJournalForTests(): void {
448
453
  chains.clear();
449
454
  marked.clear();
450
455
  verified.clear();
456
+ unjournalled.clear();
457
+ repairing.clear();
451
458
  retryAt.clear();
452
459
  restoring.clear();
453
460
  wantPrune.clear();
@@ -467,6 +474,7 @@ export function dropJournal(tenant: string, workspace?: string): void {
467
474
  queues.delete(k);
468
475
  marked.delete(k);
469
476
  verified.delete(k);
477
+ unjournalled.delete(k);
470
478
  retryAt.delete(k);
471
479
  }
472
480
  }
@@ -1062,29 +1070,63 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1062
1070
  if (!Object.keys(changes).length) return null;
1063
1071
  // A restore tag only counts when that revision is in the store.
1064
1072
  const restoredFrom = entry.restoredFrom && (await deps.revisions.revision(ws, entry.restoredFrom)) ? entry.restoredFrom : undefined;
1065
- try {
1066
- return await publish(deps, {
1067
- ws,
1068
- opId: opIdOf(baseline.authored || baseline.state ? "jb" : "jr", entry.id),
1069
- by: entry.by,
1070
- message: entry.message,
1071
- changes,
1072
- restoredFrom,
1073
- bytesOf: async (sha) => {
1074
- const b = bytes.get(sha);
1075
- if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1076
- return b;
1077
- },
1078
- });
1079
- } catch (err) {
1080
- // This entry's id was used before for a different set of changes: an
1081
- // earlier attempt committed it (its answer was lost) and the head has
1082
- // moved on, so the changes computed now differ. It is done.
1083
- if (err instanceof OpIdReused) return null;
1084
- throw err;
1073
+ const prefix = baseline.authored || baseline.state ? "jb" : "jr";
1074
+ // An entry is two commits (workspace head, then state head), each with its
1075
+ // own op id. A retry after only the first landed must still make the second:
1076
+ // so a side whose op id has finished is left out, rather than recomputed —
1077
+ // recomputed, its changes differ (what landed now matches the head and drops
1078
+ // out, a conflict does not), the op id would be "reused", and until 9 Nov
1079
+ // 2026 that was taken as the whole entry being done and the state half was
1080
+ // never committed (FOL-152). Asked again after an OpIdReused: another pod
1081
+ // replaying the same entry may finish a side between the look and the publish.
1082
+ for (let attempt = 0; ; attempt++) {
1083
+ const done = await sidesDone(deps, ws, entry.id);
1084
+ const todo: Changes = {};
1085
+ for (const [p, c] of Object.entries(changes)) if (!done[sideOf(p)!]) todo[p] = c;
1086
+ if (!Object.keys(todo).length) return null;
1087
+ try {
1088
+ return await publish(deps, {
1089
+ ws,
1090
+ // The op id of a side that finished, when one did, so the other side's
1091
+ // conflict copies are named the way the first attempt would have.
1092
+ opId: done.opId ?? opIdOf(prefix, entry.id),
1093
+ by: entry.by,
1094
+ message: entry.message,
1095
+ changes: todo,
1096
+ restoredFrom: done.authored ? undefined : restoredFrom,
1097
+ bytesOf: async (sha) => {
1098
+ const b = bytes.get(sha);
1099
+ if (!b) throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1100
+ return b;
1101
+ },
1102
+ });
1103
+ } catch (err) {
1104
+ // Never "done" by itself: a side that finished is found by sidesDone on
1105
+ // the next look. One that keeps answering OpIdReused without having
1106
+ // finished is a bug, and permanent(): the entry is dropped and the
1107
+ // workspace reconciled from the folder, so nothing is lost silently.
1108
+ if (!(err instanceof OpIdReused) || attempt >= 2) throw err;
1109
+ }
1085
1110
  }
1086
1111
  }
1087
1112
 
1113
+ /** Which halves of a journal entry finished in an earlier attempt (an
1114
+ * operation is recorded for each, committed or unchanged). Both prefixes are
1115
+ * asked: an entry that was a baseline when it first ran is not one on retry. */
1116
+ async function sidesDone(deps: Deps, ws: WorkspaceRef, id: string): Promise<{ authored: boolean; state: boolean; opId?: string }> {
1117
+ const out: { authored: boolean; state: boolean; opId?: string } = { authored: false, state: false };
1118
+ const ids = ["jb", "jr"].map((prefix) => opIdOf(prefix, id));
1119
+ const found = await Promise.all(
1120
+ ids.map((opId) => Promise.all([deps.revisions.operation({ ...ws, scope: "workspace" }, opId), deps.revisions.operation({ ...ws, scope: "state" }, stateOpId(opId))])),
1121
+ );
1122
+ found.forEach(([a, s], i) => {
1123
+ if (a) out.authored = true;
1124
+ if (s) out.state = true;
1125
+ if ((a || s) && !out.opId) out.opId = ids[i];
1126
+ });
1127
+ return out;
1128
+ }
1129
+
1088
1130
  /** Bring the heads to the folder's content in one revision: the way in for a
1089
1131
  * workspace that predates the journal (the importer, phase 8), and the repair
1090
1132
  * after a journal overflow. Text files only, as the tree reader lists them. */
@@ -1097,6 +1139,8 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1097
1139
  // writing a file too big to journal while this publishes) asks for another
1098
1140
  // repair; a repair that fails puts it back for the next one.
1099
1141
  const wasMarked = marked.delete(k);
1142
+ const wasUnjournalled = unjournalled.delete(k);
1143
+ repairing.add(k);
1100
1144
  try {
1101
1145
  // The heads first, then the folder: a folder read older than the heads
1102
1146
  // would diff a stale copy against a newer head, and with that head as each
@@ -1138,7 +1182,10 @@ export async function reconcileWorkspace(tenant: string, workspace: string, by =
1138
1182
  });
1139
1183
  } catch (err) {
1140
1184
  if (wasMarked) marked.add(k);
1185
+ if (wasUnjournalled) unjournalled.add(k);
1141
1186
  throw err;
1187
+ } finally {
1188
+ repairing.delete(k);
1142
1189
  }
1143
1190
  }
1144
1191
 
@@ -1183,28 +1230,58 @@ async function parentManifest(deps: Deps, tenant: string, workspace: string, rev
1183
1230
  /** The history page's rows, newest first: the workspace head's revisions in
1184
1231
  * history.ts's summary shape. `commit` is null (a deploy's commit id rides in
1185
1232
  * the message); the id is the revision's. */
1186
- export async function listRevisionSummaries(tenant: string, workspace: string, opts: { limit?: number; forPath?: string } = {}): Promise<RevisionSummary[]> {
1233
+ export async function listRevisionSummaries(tenant: string, workspace: string, opts: { limit?: number; forPath?: string; paths?: boolean } = {}): Promise<RevisionSummary[]> {
1187
1234
  const deps = backend;
1188
1235
  if (!deps) return [];
1189
- const revs = await deps.revisions.revisions({ tenant, workspace }, { limit: opts.forPath ? 500 : (opts.limit ?? 200) });
1190
- const out: RevisionSummary[] = [];
1191
1236
  const want = opts.limit ?? 200;
1192
- // Eight at a time: each revision is two manifest reads, and a history page
1193
- // asks for hundreds.
1194
- for (let i = 0; i < revs.length && out.length < want; i += 8) {
1195
- const rows = await Promise.all(
1196
- revs.slice(i, i + 8).map(async (r) => {
1197
- const [mine, before] = await Promise.all([loadManifest(deps, tenant, r.authored), parentManifest(deps, tenant, workspace, r)]);
1198
- return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: Object.keys(diffManifests(before, mine)).sort() } as RevisionSummary;
1199
- }),
1200
- );
1201
- for (const row of rows) {
1202
- if (opts.forPath && !row.paths.includes(opts.forPath)) continue;
1203
- if (out.length < want) out.push(row);
1237
+ // `paths: false` (resolving a restore point) needs only who, when and why:
1238
+ // no manifest is read, and every row says paths [].
1239
+ const withPaths = opts.paths !== false || !!opts.forPath;
1240
+ // Page by page: the store answers at most PAGE revisions a call, and until
1241
+ // 9 Nov 2026 that first page was taken as the whole history, so a revision
1242
+ // older than the 500th could not be listed or resolved (FOL-152). A search
1243
+ // for one path still looks at no more than FOR_PATH_SCAN of them: each is two
1244
+ // manifest reads.
1245
+ const scanUpTo = opts.forPath ? FOR_PATH_SCAN : Infinity;
1246
+ const out: RevisionSummary[] = [];
1247
+ let before: number | undefined;
1248
+ for (let scanned = 0; out.length < want && scanned < scanUpTo; ) {
1249
+ const ask = opts.forPath ? Math.min(PAGE, scanUpTo - scanned) : Math.min(PAGE, want - out.length);
1250
+ const revs = await deps.revisions.revisions({ tenant, workspace }, { limit: ask, ...(before !== undefined ? { before } : {}) });
1251
+ if (!revs.length) break;
1252
+ scanned += revs.length;
1253
+ // Eight at a time: each revision is two manifest reads, and a history page
1254
+ // asks for hundreds.
1255
+ for (let i = 0; i < revs.length && out.length < want; i += 8) {
1256
+ const rows = await Promise.all(
1257
+ revs.slice(i, i + 8).map(async (r) => {
1258
+ if (!withPaths) return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] } as RevisionSummary;
1259
+ const [mine, parent] = await Promise.all([loadManifest(deps, tenant, r.authored), parentManifest(deps, tenant, workspace, r)]);
1260
+ return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: Object.keys(diffManifests(parent, mine)).sort() } as RevisionSummary;
1261
+ }),
1262
+ );
1263
+ for (const row of rows) {
1264
+ if (opts.forPath && !row.paths.includes(opts.forPath)) continue;
1265
+ if (out.length < want) out.push(row);
1266
+ }
1204
1267
  }
1268
+ before = revs[revs.length - 1].seq;
1269
+ if (before <= 1) break; // that was the first revision: nothing older to ask for
1205
1270
  }
1206
1271
  return out;
1207
1272
  }
1273
+ /** The most revisions the store answers in one call (revision-store.ts). */
1274
+ const PAGE = 500;
1275
+ const FOR_PATH_SCAN = 500;
1276
+
1277
+ /** One revision of the workspace head, by id, without listing: the history's
1278
+ * "is this a restore point" and "which revision is that id". */
1279
+ export async function revisionSummary(tenant: string, workspace: string, id: string): Promise<RevisionSummary | null> {
1280
+ const deps = backend;
1281
+ if (!deps) return null;
1282
+ const r = await deps.revisions.revision({ tenant, workspace }, id);
1283
+ return r ? { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, paths: [] } : null;
1284
+ }
1208
1285
 
1209
1286
  /** One revision with what changed, in history.ts's Revision shape (text
1210
1287
  * before/after, clipped). */
@@ -1226,7 +1303,12 @@ export async function readRevisionDetail(tenant: string, workspace: string, id:
1226
1303
  return { id: r.id, at: r.at, by: r.by, message: r.message, commit: null, files };
1227
1304
  }
1228
1305
 
1229
- /** The whole tree at a revision (the files a restore would bring back), text. */
1306
+ /** The whole tree at a revision (the files a restore would bring back), text.
1307
+ * All of it or an error: a file whose blob cannot be had throws BlobMissing.
1308
+ * Until 9 Nov 2026 such a file was left out, and a tree that lacks a file is
1309
+ * indistinguishable from one where it was deleted — a restore from it would
1310
+ * have removed the file from the folder (FOL-152). Through history.ts the
1311
+ * error answers "no snapshot", and the restore refuses. */
1230
1312
  export async function snapshotFiles(tenant: string, workspace: string, id: string): Promise<{ path: string; content: string }[] | null> {
1231
1313
  const deps = backend;
1232
1314
  if (!deps) return null;
@@ -1236,7 +1318,8 @@ export async function snapshotFiles(tenant: string, workspace: string, id: strin
1236
1318
  const out: { path: string; content: string }[] = [];
1237
1319
  for (const [p, e] of Object.entries(m.files).sort(([a], [b]) => a.localeCompare(b))) {
1238
1320
  const b = await blobBytes(deps, tenant, e.sha);
1239
- if (b) out.push({ path: p, content: b.toString("utf8") });
1321
+ if (!b) throw new BlobMissing(p, e.sha);
1322
+ out.push({ path: p, content: b.toString("utf8") });
1240
1323
  }
1241
1324
  return out;
1242
1325
  }
@@ -1269,6 +1352,7 @@ const view: RevisionView = {
1269
1352
  list: (t, w, o) => guarded("list", t, w, () => listRevisionSummaries(t, w, o)),
1270
1353
  read: (t, w, id, p) => guarded("read", t, w, () => readRevisionDetail(t, w, id, p)),
1271
1354
  snapshot: (t, w, id) => guarded("snapshot", t, w, () => snapshotFiles(t, w, id)),
1355
+ get: (t, w, id) => guarded("get", t, w, () => revisionSummary(t, w, id)),
1272
1356
  };
1273
1357
 
1274
1358
  // ------------------------------------------------------------- reads through heads
@@ -1278,7 +1362,7 @@ const view: RevisionView = {
1278
1362
  * fallback is the point: a head behind the folder, a missing blob, a store
1279
1363
  * that is down, a binary file the tree reader never recorded). */
1280
1364
  export async function readHeadText(tenant: string, workspace: string, rel: string): Promise<string | null> {
1281
- if (!revisionReadsOn()) return null;
1365
+ if (!revisionReadsOn() || headBehind(tenant, workspace, rel)) return null;
1282
1366
  try {
1283
1367
  const b = await readAtHead(tenant, workspace, rel);
1284
1368
  return b ? b.toString("utf8") : null;
@@ -1288,6 +1372,20 @@ export async function readHeadText(tenant: string, workspace: string, rel: strin
1288
1372
  }
1289
1373
  }
1290
1374
 
1375
+ /** Is the head known, in this process, not to hold the folder's copy of `rel`?
1376
+ * A change to it is queued (its commit failed or has not run yet), the
1377
+ * workspace is marked for a repair or being repaired, or it was written while
1378
+ * the journal was off. The folder is the working copy and what a save's
1379
+ * `ifMatch` is checked against, so a read that answered the older head there
1380
+ * would tell the client a hash its next save can never match (FOL-152).
1381
+ * In-memory only, so it costs nothing per read; a change another process
1382
+ * has queued is not seen here. */
1383
+ function headBehind(tenant: string, workspace: string, rel: string): boolean {
1384
+ const k = key(tenant, workspace);
1385
+ if (marked.has(k) || unjournalled.has(k) || repairing.has(k)) return true;
1386
+ return !!queues.get(k)?.some((e) => e.files.some((f) => f.path === rel));
1387
+ }
1388
+
1291
1389
  /** Every file of the workspace head with its bytes and mode (both heads), for
1292
1390
  * a stage-in; null when reads through revisions are off, there is no head,
1293
1391
  * or any blob could not be had (the caller then stages from the folder). */
@@ -1314,7 +1412,8 @@ export async function readHeadTree(tenant: string, workspace: string): Promise<{
1314
1412
  }
1315
1413
 
1316
1414
  /** The dashboard's and the API's read of one editable file: the head's bytes
1317
- * when reads through revisions are on and the head has the file, otherwise
1415
+ * when reads through revisions are on, the head has the file and nothing in
1416
+ * this process says the head is behind the folder for it (headBehind), otherwise
1318
1417
  * the folder exactly as readWorkspaceFile answers (same path rules, same
1319
1418
  * "file not found"). */
1320
1419
  export async function readWorkspaceFileVia(tenant: string, workspace: string, rel: string): Promise<string> {