@foldrun/core 17.3.0 → 18.0.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.
Files changed (65) hide show
  1. package/dist/src/approvals.js +3 -3
  2. package/dist/src/blob-cache.d.ts +58 -0
  3. package/dist/src/blob-cache.js +312 -0
  4. package/dist/src/blob-pins.d.ts +44 -0
  5. package/dist/src/blob-pins.js +61 -0
  6. package/dist/src/blob-store.d.ts +47 -0
  7. package/dist/src/blob-store.js +362 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +282 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/evals.js +1 -1
  13. package/dist/src/history.d.ts +92 -9
  14. package/dist/src/history.js +168 -20
  15. package/dist/src/journal-store.d.ts +58 -0
  16. package/dist/src/journal-store.js +117 -0
  17. package/dist/src/manifest.d.ts +92 -0
  18. package/dist/src/manifest.js +239 -0
  19. package/dist/src/ops-log.js +26 -3
  20. package/dist/src/platform.d.ts +7 -0
  21. package/dist/src/platform.js +1 -0
  22. package/dist/src/publish.d.ts +134 -0
  23. package/dist/src/publish.js +434 -0
  24. package/dist/src/records.d.ts +72 -0
  25. package/dist/src/records.js +24 -0
  26. package/dist/src/revision-store.d.ts +161 -0
  27. package/dist/src/revision-store.js +378 -0
  28. package/dist/src/run-container.d.ts +20 -0
  29. package/dist/src/run-container.js +61 -0
  30. package/dist/src/runner.js +1 -1
  31. package/dist/src/s3-blob-store.d.ts +29 -0
  32. package/dist/src/s3-blob-store.js +531 -0
  33. package/dist/src/state-retention.d.ts +15 -0
  34. package/dist/src/state-retention.js +65 -0
  35. package/dist/src/storage.d.ts +29 -1
  36. package/dist/src/storage.js +331 -81
  37. package/dist/src/store.d.ts +41 -0
  38. package/dist/src/store.js +188 -5
  39. package/dist/src/trigger-log.js +17 -0
  40. package/dist/src/workspace-revisions.d.ts +269 -0
  41. package/dist/src/workspace-revisions.js +1382 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +357 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +389 -0
  47. package/src/blob-sweeper.ts +336 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +226 -19
  51. package/src/journal-store.ts +152 -0
  52. package/src/manifest.ts +274 -0
  53. package/src/ops-log.ts +25 -3
  54. package/src/platform.ts +8 -0
  55. package/src/publish.ts +520 -0
  56. package/src/records.ts +105 -0
  57. package/src/revision-store.ts +513 -0
  58. package/src/run-container.ts +62 -0
  59. package/src/runner.ts +1 -1
  60. package/src/s3-blob-store.ts +560 -0
  61. package/src/state-retention.ts +83 -0
  62. package/src/storage.ts +335 -81
  63. package/src/store.ts +178 -5
  64. package/src/trigger-log.ts +15 -0
  65. package/src/workspace-revisions.ts +1423 -0
@@ -9,6 +9,39 @@
9
9
  */
10
10
  type TreeReader = (tenant: string, scope: string) => RevisionFile[] | null;
11
11
  export declare function registerTreeReader(fn: TreeReader): void;
12
+ /** The scope's tree as the registered readers see it (text files only), or null. */
13
+ export declare function currentTree(tenant: string, scope: string): RevisionFile[] | null;
14
+ /**
15
+ * Where a committed change set is also handed (workspace-revisions.ts registers
16
+ * here: this module cannot import it, it imports the store which imports this).
17
+ * Called after the legacy record is written; never throws into the writer.
18
+ */
19
+ type Journal = (tenant: string, scope: string, files: RevisionFile[], meta: {
20
+ by: string;
21
+ message: string;
22
+ at: string;
23
+ }) => void;
24
+ export declare function registerJournal(fn: Journal | null): void;
25
+ export declare function registerWorkspaceGone(fn: ((tenant: string, workspace: string) => void) | null): void;
26
+ export declare function workspaceGone(tenant: string, workspace: string): void;
27
+ /**
28
+ * What follows a workspace through a delete or a rename (workspace-revisions.ts
29
+ * registers it): its journal and its history in the revision store. The async
30
+ * forms run the folder's own change INSIDE them (`remove`, `rename`), so that
31
+ * a store which cannot be reached stops the change before anything is removed
32
+ * or moved, and a writer racing the change is held off until it is done. The
33
+ * sync forms are for a caller that cannot wait: they do what can be done now
34
+ * and finish in the background.
35
+ */
36
+ export interface WorkspaceLifecycle {
37
+ drop(tenant: string, workspace: string, remove: () => void): Promise<void>;
38
+ move(tenant: string, from: string, to: string, rename: () => void): Promise<void>;
39
+ moved(tenant: string, from: string, to: string): void;
40
+ }
41
+ export declare function registerWorkspaceLifecycle(l: WorkspaceLifecycle | null): void;
42
+ export declare const workspaceLifecycle: () => WorkspaceLifecycle | null;
43
+ /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
44
+ export declare function workspaceMoved(tenant: string, from: string, to: string): void;
12
45
  export interface RevisionFile {
13
46
  path: string;
14
47
  /** Null when the file did not exist before. */
@@ -56,14 +89,14 @@ export declare function recordRevision(tenant: string, scope: string, files: Rev
56
89
  commit?: string | null;
57
90
  }): Revision | null;
58
91
  /** Whether a revision can be restored to: it has a snapshot. */
59
- export declare function hasSnapshot(tenant: string, scope: string, id: string): boolean;
92
+ export declare function hasSnapshotLocal(tenant: string, scope: string, id: string): boolean;
60
93
  /** The whole tree at revision `id`, or null when it has no snapshot. */
61
- export declare function snapshotAt(tenant: string, scope: string, id: string): {
94
+ export declare function snapshotAtLocal(tenant: string, scope: string, id: string): {
62
95
  path: string;
63
96
  content: string;
64
97
  }[] | null;
65
98
  /** The newest revision that can be restored to — what "now" is in history. */
66
- export declare function headRevision(tenant: string, scope: string): RevisionSummary | null;
99
+ export declare function headRevisionLocal(tenant: string, scope: string): RevisionSummary | null;
67
100
  /**
68
101
  * A scope with no snapshot yet gets one: its tree as it stands, recorded as
69
102
  * a revision of its own — where its history starts. Every workspace that
@@ -71,7 +104,7 @@ export declare function headRevision(tenant: string, scope: string): RevisionSum
71
104
  * by a path that never recorded a change. Returns the head's id, or null
72
105
  * when there is nothing to snapshot.
73
106
  */
74
- export declare function ensureBaseline(tenant: string, scope: string, by?: string): string | null;
107
+ export declare function ensureBaselineLocal(tenant: string, scope: string, by?: string): string | null;
75
108
  /**
76
109
  * The revision a restore means: an id (or the commit a deploy recorded), a
77
110
  * date (`2026-10-17`, `2026-10-17T09:00Z`) or a span back from now (`90m`,
@@ -79,25 +112,75 @@ export declare function ensureBaseline(tenant: string, scope: string, by?: strin
79
112
  * moment. Null when history holds nothing that old. Throws (status 400) on
80
113
  * something that is none of those.
81
114
  */
82
- export declare function resolveRevision(tenant: string, scope: string, to: string, now?: number): {
115
+ export declare function resolveRevisionLocal(tenant: string, scope: string, to: string, now?: number): {
83
116
  id: string;
84
117
  at: string;
85
118
  by: string;
86
119
  message: string;
87
120
  } | null;
88
121
  /** Newest first. `forPath` narrows to revisions that touched one file. */
89
- export declare function listRevisions(tenant: string, scope: string, opts?: {
122
+ export declare function listRevisionsLocal(tenant: string, scope: string, opts?: {
90
123
  forPath?: string;
91
124
  limit?: number;
92
125
  }): RevisionSummary[];
93
- export declare function readRevision(tenant: string, scope: string, id: string, forPath?: string): Revision | null;
126
+ export declare function readRevisionLocal(tenant: string, scope: string, id: string, forPath?: string): Revision | null;
94
127
  /** The files changed after revision `from` up to and including `to`, in a
95
128
  * scope — what differs between the versions two runs ran (FOL-72). Null
96
129
  * when either is unknown or `to` is not after `from`. */
97
- export declare function changedPathsBetween(tenant: string, scope: string, from: string | null, to: string | null): string[] | null;
130
+ export declare function changedPathsBetweenLocal(tenant: string, scope: string, from: string | null, to: string | null): string[] | null;
98
131
  /** The most recent revision id for a scope — what a change is attributed
99
132
  * to when nothing more specific (a deployed commit) is on record. */
100
- export declare function latestRevisionId(tenant: string, scope: string): string | null;
133
+ export declare function latestRevisionIdLocal(tenant: string, scope: string): string | null;
134
+ export interface RevisionView {
135
+ /** Newest first, or null when revisions do not serve this scope. Every page
136
+ * of the store up to `limit` (Infinity: all of it); `paths: false` leaves
137
+ * the changed paths out (rows say []), which is what makes "all" cheap. */
138
+ list(tenant: string, scope: string, opts: {
139
+ forPath?: string;
140
+ limit?: number;
141
+ paths?: boolean;
142
+ }): Promise<RevisionSummary[] | null>;
143
+ read(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null>;
144
+ snapshot(tenant: string, scope: string, id: string): Promise<{
145
+ path: string;
146
+ content: string;
147
+ }[] | null>;
148
+ /** One revision by id, looked up rather than listed (paths []); null when
149
+ * the store has none. Optional: a view without it is asked through `list`. */
150
+ get?(tenant: string, scope: string, id: string): Promise<RevisionSummary | null>;
151
+ }
152
+ export declare function registerRevisionView(v: RevisionView | null): void;
153
+ export declare function listRevisions(tenant: string, scope: string, opts?: {
154
+ forPath?: string;
155
+ limit?: number;
156
+ }): Promise<RevisionSummary[]>;
157
+ /** The list the history page shows: each row with whether it can be restored
158
+ * to. One listing answers both — every revision in the store is restorable;
159
+ * a local entry is when it has a snapshot — where asking per row would list
160
+ * the store once per row. */
161
+ export declare function listRevisionsRestorable(tenant: string, scope: string, opts?: {
162
+ forPath?: string;
163
+ limit?: number;
164
+ }): Promise<(RevisionSummary & {
165
+ restorable: boolean;
166
+ })[]>;
167
+ export declare function readRevision(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null>;
168
+ export declare function snapshotAt(tenant: string, scope: string, id: string): Promise<{
169
+ path: string;
170
+ content: string;
171
+ }[] | null>;
172
+ export declare function hasSnapshot(tenant: string, scope: string, id: string): Promise<boolean>;
173
+ export declare function headRevision(tenant: string, scope: string): Promise<RevisionSummary | null>;
174
+ export declare function resolveRevision(tenant: string, scope: string, to: string, now?: number): Promise<{
175
+ id: string;
176
+ at: string;
177
+ by: string;
178
+ message: string;
179
+ } | null>;
180
+ export declare function changedPathsBetween(tenant: string, scope: string, from: string | null, to: string | null): Promise<string[] | null>;
181
+ export declare function latestRevisionId(tenant: string, scope: string): Promise<string | null>;
182
+ /** A scope with no revision at all gets a local baseline, as before. */
183
+ export declare function ensureBaseline(tenant: string, scope: string, by?: string): Promise<string | null>;
101
184
  export type DiffOp = {
102
185
  kind: "same" | "add" | "del";
103
186
  text: string;
@@ -42,6 +42,42 @@ export function registerTreeReader(fn) {
42
42
  const prev = readTree;
43
43
  readTree = (tenant, scope) => fn(tenant, scope) ?? prev(tenant, scope);
44
44
  }
45
+ /** The scope's tree as the registered readers see it (text files only), or null. */
46
+ export function currentTree(tenant, scope) {
47
+ return readTree(tenant, scope);
48
+ }
49
+ let journal = null;
50
+ export function registerJournal(fn) {
51
+ journal = fn;
52
+ }
53
+ /** A workspace was deleted: whatever a registered journal still holds for it
54
+ * (queued changes, their files) goes too (FOL-126 phase 4). */
55
+ let onGone = null;
56
+ export function registerWorkspaceGone(fn) {
57
+ onGone = fn;
58
+ }
59
+ export function workspaceGone(tenant, workspace) {
60
+ try {
61
+ onGone?.(tenant, workspace);
62
+ }
63
+ catch {
64
+ // a journal that cannot be cleared now is cleared at the next boot (the replay discards a missing workspace)
65
+ }
66
+ }
67
+ let lifecycleHooks = null;
68
+ export function registerWorkspaceLifecycle(l) {
69
+ lifecycleHooks = l;
70
+ }
71
+ export const workspaceLifecycle = () => lifecycleHooks;
72
+ /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
73
+ export function workspaceMoved(tenant, from, to) {
74
+ try {
75
+ lifecycleHooks?.moved(tenant, from, to);
76
+ }
77
+ catch {
78
+ // finished by the next reconcile
79
+ }
80
+ }
45
81
  function assertSafeName(v, what) {
46
82
  if (!/^[A-Za-z0-9][A-Za-z0-9._@-]{0,120}$/.test(v))
47
83
  throw new Error(`illegal ${what}: ${v}`);
@@ -117,6 +153,12 @@ export function recordRevision(tenant, scope, files, meta = {}) {
117
153
  // outside this call, such as a bundle's generated index.
118
154
  snapshot(tenant, scope, rev.id);
119
155
  fs.appendFileSync(path.join(dir, "index.jsonl"), `${JSON.stringify(line)}\n`);
156
+ try {
157
+ journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
158
+ }
159
+ catch {
160
+ // the revision store is not allowed to break a save; workspace-revisions logs and retries
161
+ }
120
162
  return rev;
121
163
  }
122
164
  // ----------------------------------------------------------------- snapshots
@@ -158,12 +200,12 @@ function snapshot(tenant, scope, id) {
158
200
  return true;
159
201
  }
160
202
  /** Whether a revision can be restored to: it has a snapshot. */
161
- export function hasSnapshot(tenant, scope, id) {
203
+ export function hasSnapshotLocal(tenant, scope, id) {
162
204
  assertSafeName(id, "revision id");
163
205
  return fs.existsSync(treePath(tenant, scope, id));
164
206
  }
165
207
  /** The whole tree at revision `id`, or null when it has no snapshot. */
166
- export function snapshotAt(tenant, scope, id) {
208
+ export function snapshotAtLocal(tenant, scope, id) {
167
209
  assertSafeName(id, "revision id");
168
210
  let manifest;
169
211
  try {
@@ -187,7 +229,7 @@ function snapshotIds(tenant, scope) {
187
229
  }
188
230
  }
189
231
  /** The newest revision that can be restored to — what "now" is in history. */
190
- export function headRevision(tenant, scope) {
232
+ export function headRevisionLocal(tenant, scope) {
191
233
  const have = snapshotIds(tenant, scope);
192
234
  return journalRevisions(tenant, scope, { limit: Infinity }).find((r) => have.has(r.id)) ?? null;
193
235
  }
@@ -198,8 +240,8 @@ export function headRevision(tenant, scope) {
198
240
  * by a path that never recorded a change. Returns the head's id, or null
199
241
  * when there is nothing to snapshot.
200
242
  */
201
- export function ensureBaseline(tenant, scope, by = "foldrun") {
202
- const head = headRevision(tenant, scope);
243
+ export function ensureBaselineLocal(tenant, scope, by = "foldrun") {
244
+ const head = headRevisionLocal(tenant, scope);
203
245
  if (head)
204
246
  return head.id;
205
247
  const tree = readTree(tenant, scope);
@@ -215,7 +257,7 @@ export function ensureBaseline(tenant, scope, by = "foldrun") {
215
257
  fs.writeFileSync(marker, id, { flag: "wx" });
216
258
  }
217
259
  catch {
218
- const held = headRevision(tenant, scope)?.id ?? null;
260
+ const held = headRevisionLocal(tenant, scope)?.id ?? null;
219
261
  // A marker with no baseline behind it, minutes old, is a process that
220
262
  // died writing one: clear it, and the next call writes the baseline.
221
263
  try {
@@ -249,27 +291,42 @@ export function ensureBaseline(tenant, scope, by = "foldrun") {
249
291
  * moment. Null when history holds nothing that old. Throws (status 400) on
250
292
  * something that is none of those.
251
293
  */
252
- export function resolveRevision(tenant, scope, to, now = Date.now()) {
294
+ export function resolveRevisionLocal(tenant, scope, to, now = Date.now()) {
295
+ const have = snapshotIds(tenant, scope);
296
+ return resolveIn(journalRevisions(tenant, scope, { limit: Infinity }).filter((r) => have.has(r.id)), to, now);
297
+ }
298
+ /** The pick of resolveRevision over a newest-first list of restorable revisions. */
299
+ function resolveIn(all, to, now) {
300
+ return pick(all, target(to, now));
301
+ }
302
+ /** What a restore's `to` names: a moment, or an id (or a commit). Throws 400
303
+ * on something that is neither. */
304
+ function target(to, now) {
253
305
  const t = to.trim();
254
306
  if (!t || t.startsWith("-"))
255
307
  throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
256
- const have = snapshotIds(tenant, scope);
257
- const all = journalRevisions(tenant, scope, { limit: Infinity }).filter((r) => have.has(r.id));
258
308
  const rel = /^(\d+)\s*(m|h|d|w)$/.exec(t);
259
309
  const moment = rel
260
310
  ? now - Number(rel[1]) * { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[rel[2]]
261
311
  : /^\d{4}-\d{2}-\d{2}/.test(t)
262
312
  ? Date.parse(t)
263
313
  : null;
264
- let hit;
265
314
  if (moment !== null) {
266
315
  if (Number.isNaN(moment))
267
316
  throw Object.assign(new Error(`not a date: ${to}`), { status: 400 });
268
- hit = all.find((r) => Date.parse(r.at) <= moment);
317
+ return { moment };
318
+ }
319
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(t))
320
+ throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
321
+ return { id: t };
322
+ }
323
+ function pick(all, want) {
324
+ let hit;
325
+ if ("moment" in want) {
326
+ hit = all.find((r) => Date.parse(r.at) <= want.moment);
269
327
  }
270
328
  else {
271
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(t))
272
- throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
329
+ const t = want.id;
273
330
  // An exact id first, then a commit: a commit deployed twice is recorded
274
331
  // once under its own id and again under a fresh one naming it (30 Oct
275
332
  // 2026, recordRevision), and newest-first with one predicate answered
@@ -294,7 +351,7 @@ function describe(files) {
294
351
  .join(", ") + ` file${files.length === 1 ? "" : "s"}`;
295
352
  }
296
353
  /** Newest first. `forPath` narrows to revisions that touched one file. */
297
- export function listRevisions(tenant, scope, opts = {}) {
354
+ export function listRevisionsLocal(tenant, scope, opts = {}) {
298
355
  return journalRevisions(tenant, scope, opts);
299
356
  }
300
357
  function journalRevisions(tenant, scope, opts = {}) {
@@ -358,7 +415,7 @@ function rebuildIndex(dir) {
358
415
  }
359
416
  return rows.map(({ written: _w, ...r }) => r).reverse();
360
417
  }
361
- export function readRevision(tenant, scope, id, forPath) {
418
+ export function readRevisionLocal(tenant, scope, id, forPath) {
362
419
  assertSafeName(id, "revision id");
363
420
  const file = path.join(historyDir(tenant, scope), `${id}.json`);
364
421
  if (!fs.existsSync(file))
@@ -369,13 +426,15 @@ export function readRevision(tenant, scope, id, forPath) {
369
426
  /** The files changed after revision `from` up to and including `to`, in a
370
427
  * scope — what differs between the versions two runs ran (FOL-72). Null
371
428
  * when either is unknown or `to` is not after `from`. */
372
- export function changedPathsBetween(tenant, scope, from, to) {
429
+ export function changedPathsBetweenLocal(tenant, scope, from, to) {
373
430
  if (!from || !to)
374
431
  return null;
375
432
  if (from === to)
376
433
  return [];
377
- const revs = listRevisions(tenant, scope, { limit: 500 }); // newest first
378
- // An exact id before a commit, as resolveRevision.
434
+ return changedIn(listRevisionsLocal(tenant, scope, { limit: 500 }), from, to);
435
+ }
436
+ function changedIn(revs, from, to) {
437
+ // newest first. An exact id before a commit, as resolveRevision.
379
438
  const at = (x) => {
380
439
  const byId = revs.findIndex((r) => r.id === x);
381
440
  return byId >= 0 ? byId : revs.findIndex((r) => r.commit === x);
@@ -388,8 +447,97 @@ export function changedPathsBetween(tenant, scope, from, to) {
388
447
  }
389
448
  /** The most recent revision id for a scope — what a change is attributed
390
449
  * to when nothing more specific (a deployed commit) is on record. */
391
- export function latestRevisionId(tenant, scope) {
392
- return listRevisions(tenant, scope, { limit: 1 })[0]?.id ?? null;
450
+ export function latestRevisionIdLocal(tenant, scope) {
451
+ return listRevisionsLocal(tenant, scope, { limit: 1 })[0]?.id ?? null;
452
+ }
453
+ let view = null;
454
+ export function registerRevisionView(v) {
455
+ view = v;
456
+ }
457
+ /** Revisions first, then the local entries older than the oldest of them.
458
+ * `stored` is which rows came from the store (every one a restore point). */
459
+ async function combinedRows(tenant, scope, opts, restorableOnly = false) {
460
+ const limit = opts.limit ?? 200;
461
+ // The whole of `limit`, every page of it: the store's first page is not all
462
+ // of history (FOL-152).
463
+ const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit }) : null;
464
+ let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
465
+ if (restorableOnly) {
466
+ const have = snapshotIds(tenant, scope);
467
+ local = local.filter((r) => have.has(r.id));
468
+ }
469
+ if (!mine || !mine.length)
470
+ return { rows: local.slice(0, limit), stored: new Set() };
471
+ const oldest = mine[mine.length - 1].at;
472
+ const seen = new Set(mine.map((r) => r.id));
473
+ return { rows: [...mine, ...local.filter((r) => !seen.has(r.id) && r.at < oldest)].slice(0, limit), stored: seen };
474
+ }
475
+ async function combined(tenant, scope, opts, restorableOnly = false) {
476
+ return (await combinedRows(tenant, scope, opts, restorableOnly)).rows;
477
+ }
478
+ export async function listRevisions(tenant, scope, opts = {}) {
479
+ return combined(tenant, scope, opts);
480
+ }
481
+ /** The list the history page shows: each row with whether it can be restored
482
+ * to. One listing answers both — every revision in the store is restorable;
483
+ * a local entry is when it has a snapshot — where asking per row would list
484
+ * the store once per row. */
485
+ export async function listRevisionsRestorable(tenant, scope, opts = {}) {
486
+ const { rows, stored } = await combinedRows(tenant, scope, opts);
487
+ const have = snapshotIds(tenant, scope);
488
+ return rows.map((r) => ({ ...r, restorable: have.has(r.id) || stored.has(r.id) }));
489
+ }
490
+ export async function readRevision(tenant, scope, id, forPath) {
491
+ assertSafeName(id, "revision id");
492
+ const fromStore = view && scope !== "@library" ? await view.read(tenant, scope, id, forPath) : null;
493
+ return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
494
+ }
495
+ export async function snapshotAt(tenant, scope, id) {
496
+ assertSafeName(id, "revision id");
497
+ const fromStore = view && scope !== "@library" ? await view.snapshot(tenant, scope, id) : null;
498
+ return fromStore ?? snapshotAtLocal(tenant, scope, id);
499
+ }
500
+ export async function hasSnapshot(tenant, scope, id) {
501
+ assertSafeName(id, "revision id");
502
+ if (hasSnapshotLocal(tenant, scope, id))
503
+ return true;
504
+ if (!view || scope === "@library")
505
+ return false;
506
+ // Looked up by id: a listing stops at a page, and a revision older than it
507
+ // was "not restorable" until 9 Nov 2026 (FOL-152).
508
+ if (view.get)
509
+ return (await view.get(tenant, scope, id)) !== null;
510
+ return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
511
+ }
512
+ export async function headRevision(tenant, scope) {
513
+ return (await combined(tenant, scope, { limit: 1 }, true))[0] ?? null;
514
+ }
515
+ export async function resolveRevision(tenant, scope, to, now = Date.now()) {
516
+ const want = target(to, now);
517
+ // An id in the store is one lookup; anything else (a date, a local id, a
518
+ // commit) is answered from ALL of history — every page of the store, without
519
+ // the changed paths, then the local entries.
520
+ if ("id" in want && view?.get && scope !== "@library") {
521
+ const hit = await view.get(tenant, scope, want.id);
522
+ if (hit)
523
+ return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
524
+ }
525
+ return pick(await combined(tenant, scope, { limit: Infinity, paths: false }, true), want);
526
+ }
527
+ export async function changedPathsBetween(tenant, scope, from, to) {
528
+ if (!from || !to)
529
+ return null;
530
+ if (from === to)
531
+ return [];
532
+ return changedIn(await combined(tenant, scope, { limit: 500 }), from, to);
533
+ }
534
+ export async function latestRevisionId(tenant, scope) {
535
+ return (await combined(tenant, scope, { limit: 1 }))[0]?.id ?? null;
536
+ }
537
+ /** A scope with no revision at all gets a local baseline, as before. */
538
+ export async function ensureBaseline(tenant, scope, by = "foldrun") {
539
+ const head = await headRevision(tenant, scope);
540
+ return head ? head.id : ensureBaselineLocal(tenant, scope, by);
393
541
  }
394
542
  /**
395
543
  * A line diff, for showing a revision. Plain LCS — quadratic, and fine: the
@@ -0,0 +1,58 @@
1
+ /** What is stored: the whole entry (new content only, never the old text). */
2
+ export interface JournalRecord {
3
+ v: 1;
4
+ tenant: string;
5
+ workspace: string;
6
+ id: string;
7
+ files: {
8
+ path: string;
9
+ before: null;
10
+ after: string | null;
11
+ base?: string | null;
12
+ handed?: string | null;
13
+ }[];
14
+ by: string;
15
+ message: string;
16
+ at: string;
17
+ restoredFrom?: string;
18
+ /** A run's copy-back: the revisions (workspace head, state head) its stage-in
19
+ * started from. Each file's base is read from these, not from the folder. */
20
+ baseRev?: {
21
+ workspace: string | null;
22
+ state: string | null;
23
+ };
24
+ }
25
+ export interface JournalStore {
26
+ /** Which store this is, for logs ("files", "database"). */
27
+ readonly kind: string;
28
+ /** Write the entry down; throws if it cannot. Returns its handle. Putting an
29
+ * id that is already there answers the existing handle. */
30
+ put(rec: JournalRecord): string;
31
+ /** Forget one entry. Safe to repeat. */
32
+ remove(tenant: string, workspace: string, handle: string): void;
33
+ /** Every workspace that has entries. */
34
+ workspaces(): {
35
+ tenant: string;
36
+ workspace: string;
37
+ }[];
38
+ /** One workspace's entries, oldest first, with how long each has been there. */
39
+ entries(tenant: string, workspace: string): {
40
+ handle: string;
41
+ ageMs: number;
42
+ }[];
43
+ /** Read one entry; throws for one that is torn or foreign. */
44
+ read(tenant: string, workspace: string, handle: string): JournalRecord;
45
+ /** Keep an unreadable entry out of every later replay, without destroying it. */
46
+ setAside(tenant: string, workspace: string, handle: string): void;
47
+ /** Housekeeping before a replay: debris of a write that died half way (files only). */
48
+ sweep(tenant: string, workspace: string, olderThanMs: number): void;
49
+ /** Remove everything of one workspace, or of the whole account. Safe to repeat. */
50
+ drop(tenant: string, workspace?: string): void;
51
+ /** A workspace was renamed: its entries not held by a live queue (a dead
52
+ * process's) now belong to the new name. Handles of entries that were
53
+ * moved are NOT promised to stay valid: a caller holding some forgets them
54
+ * first and puts them again under the new name. */
55
+ move(tenant: string, from: string, to: string): void;
56
+ }
57
+ /** The files: <root>/<tenant>/<workspace>/<time>-<seq>-<id>.json, tmp + rename. */
58
+ export declare function fsJournalStore(root: () => string): JournalStore;
@@ -0,0 +1,117 @@
1
+ // Where the revision journal's entries are kept (FOL-126 phase 4, item 3).
2
+ //
3
+ // The journal (workspace-revisions.ts) writes every change down BEFORE it is
4
+ // queued for a commit, and removes it once committed. Until now "written down"
5
+ // meant a file under <data>/.revision-journal/ — on the shared volume, which
6
+ // the storage refactor retires. So the place is a seam:
7
+ //
8
+ // fsJournalStore the files, as before: the default, and the only one a
9
+ // laptop or a Compose install without a database ever has.
10
+ // A hosted install keeps it as a LEGACY source, replayed at
11
+ // boot and drained, so switching loses nothing.
12
+ // (platform) pgJournalStore (src/journal-pg.ts): a table, behind the
13
+ // same calls, registered where there is a database.
14
+ //
15
+ // The calls are synchronous (the writers that journal are), and an entry's
16
+ // `handle` is whatever the store needs to find it again.
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ /** The files: <root>/<tenant>/<workspace>/<time>-<seq>-<id>.json, tmp + rename. */
20
+ export function fsJournalStore(root) {
21
+ let seq = 0;
22
+ const dirOf = (tenant, workspace) => path.join(root(), tenant, workspace);
23
+ return {
24
+ kind: "files",
25
+ put(rec) {
26
+ const dir = dirOf(rec.tenant, rec.workspace);
27
+ fs.mkdirSync(dir, { recursive: true });
28
+ const name = `${Date.now().toString().padStart(14, "0")}-${String(seq++ % 1_000_000).padStart(6, "0")}-${rec.id}.json`;
29
+ const file = path.join(dir, name);
30
+ fs.writeFileSync(`${file}.tmp`, JSON.stringify(rec));
31
+ fs.renameSync(`${file}.tmp`, file);
32
+ return file;
33
+ },
34
+ remove(tenant, workspace, handle) {
35
+ try {
36
+ fs.rmSync(handle, { force: true });
37
+ fs.rmdirSync(dirOf(tenant, workspace)); // only when empty
38
+ }
39
+ catch {
40
+ // not empty, or already gone
41
+ }
42
+ },
43
+ workspaces() {
44
+ const out = [];
45
+ let tenants = [];
46
+ try {
47
+ tenants = fs.readdirSync(root());
48
+ }
49
+ catch {
50
+ return out;
51
+ }
52
+ for (const tenant of tenants) {
53
+ try {
54
+ for (const workspace of fs.readdirSync(path.join(root(), tenant)))
55
+ out.push({ tenant, workspace });
56
+ }
57
+ catch {
58
+ // not a directory
59
+ }
60
+ }
61
+ return out;
62
+ },
63
+ entries(tenant, workspace) {
64
+ const dir = dirOf(tenant, workspace);
65
+ let names = [];
66
+ try {
67
+ names = fs.readdirSync(dir).filter((n) => n.endsWith(".json")).sort();
68
+ }
69
+ catch {
70
+ return [];
71
+ }
72
+ const out = [];
73
+ for (const n of names) {
74
+ const file = path.join(dir, n);
75
+ try {
76
+ out.push({ handle: file, ageMs: Date.now() - fs.statSync(file).mtimeMs });
77
+ }
78
+ catch {
79
+ // gone meanwhile
80
+ }
81
+ }
82
+ return out;
83
+ },
84
+ read(_t, _w, handle) {
85
+ return JSON.parse(fs.readFileSync(handle, "utf8"));
86
+ },
87
+ setAside(_t, _w, handle) {
88
+ fs.renameSync(handle, `${handle}.unreadable`);
89
+ },
90
+ sweep(tenant, workspace, olderThanMs) {
91
+ const dir = dirOf(tenant, workspace);
92
+ try {
93
+ for (const n of fs.readdirSync(dir)) {
94
+ // a write that died before its rename leaves a .tmp: nothing to replay
95
+ if (n.endsWith(".json.tmp") && olderThanMs > 0 && Date.now() - fs.statSync(path.join(dir, n)).mtimeMs > olderThanMs)
96
+ fs.rmSync(path.join(dir, n), { force: true });
97
+ }
98
+ }
99
+ catch {
100
+ // nothing there
101
+ }
102
+ },
103
+ drop(tenant, workspace) {
104
+ fs.rmSync(workspace === undefined ? path.join(root(), tenant) : dirOf(tenant, workspace), { recursive: true, force: true });
105
+ },
106
+ move(tenant, from, to) {
107
+ const src = dirOf(tenant, from);
108
+ if (!fs.existsSync(src))
109
+ return;
110
+ const dest = dirOf(tenant, to);
111
+ fs.mkdirSync(dest, { recursive: true });
112
+ for (const n of fs.readdirSync(src))
113
+ fs.renameSync(path.join(src, n), path.join(dest, n));
114
+ fs.rmSync(src, { recursive: true, force: true });
115
+ },
116
+ };
117
+ }