@foldrun/core 17.2.0 → 17.4.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 (70) 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 +309 -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 +357 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +254 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/browse-egress.d.ts +31 -0
  13. package/dist/src/browse-egress.js +43 -0
  14. package/dist/src/egress.d.ts +9 -0
  15. package/dist/src/evals.js +1 -1
  16. package/dist/src/history.d.ts +86 -9
  17. package/dist/src/history.js +132 -16
  18. package/dist/src/journal-store.d.ts +58 -0
  19. package/dist/src/journal-store.js +117 -0
  20. package/dist/src/manifest.d.ts +92 -0
  21. package/dist/src/manifest.js +239 -0
  22. package/dist/src/ops-log.js +26 -3
  23. package/dist/src/platform.d.ts +7 -0
  24. package/dist/src/platform.js +1 -0
  25. package/dist/src/publish.d.ts +134 -0
  26. package/dist/src/publish.js +434 -0
  27. package/dist/src/records.d.ts +72 -0
  28. package/dist/src/records.js +24 -0
  29. package/dist/src/revision-store.d.ts +161 -0
  30. package/dist/src/revision-store.js +378 -0
  31. package/dist/src/run-container.d.ts +20 -0
  32. package/dist/src/run-container.js +61 -0
  33. package/dist/src/runner.js +22 -4
  34. package/dist/src/s3-blob-store.d.ts +29 -0
  35. package/dist/src/s3-blob-store.js +458 -0
  36. package/dist/src/state-retention.d.ts +15 -0
  37. package/dist/src/state-retention.js +65 -0
  38. package/dist/src/storage.d.ts +29 -1
  39. package/dist/src/storage.js +331 -81
  40. package/dist/src/store.d.ts +41 -0
  41. package/dist/src/store.js +188 -5
  42. package/dist/src/trigger-log.js +17 -0
  43. package/dist/src/workspace-revisions.d.ts +259 -0
  44. package/dist/src/workspace-revisions.js +1274 -0
  45. package/package.json +1 -1
  46. package/src/approvals.ts +3 -3
  47. package/src/blob-cache.ts +354 -0
  48. package/src/blob-pins.ts +99 -0
  49. package/src/blob-store.ts +385 -0
  50. package/src/blob-sweeper.ts +308 -0
  51. package/src/blob-types.ts +216 -0
  52. package/src/browse-egress.ts +49 -1
  53. package/src/egress.ts +6 -0
  54. package/src/evals.ts +1 -1
  55. package/src/history.ts +182 -16
  56. package/src/journal-store.ts +152 -0
  57. package/src/manifest.ts +274 -0
  58. package/src/ops-log.ts +25 -3
  59. package/src/platform.ts +8 -0
  60. package/src/publish.ts +520 -0
  61. package/src/records.ts +105 -0
  62. package/src/revision-store.ts +513 -0
  63. package/src/run-container.ts +62 -0
  64. package/src/runner.ts +21 -4
  65. package/src/s3-blob-store.ts +489 -0
  66. package/src/state-retention.ts +83 -0
  67. package/src/storage.ts +335 -81
  68. package/src/store.ts +178 -5
  69. package/src/trigger-log.ts +15 -0
  70. package/src/workspace-revisions.ts +1324 -0
@@ -0,0 +1,216 @@
1
+ // The BlobStore contract and the pieces every driver shares (FOL-126).
2
+ // Split out of blob-store.ts so the s3 driver (s3-blob-store.ts) and the fs
3
+ // driver can both use the errors and the source type without importing each
4
+ // other.
5
+
6
+ import fs from "node:fs";
7
+ import crypto from "node:crypto";
8
+
9
+ export class BlobNotFound extends Error {
10
+ readonly key: string;
11
+ constructor(key: string) {
12
+ super(`no object at ${key}`);
13
+ this.name = "BlobNotFound";
14
+ this.key = key;
15
+ }
16
+ }
17
+
18
+ /** A failure the caller may retry: the network, a timeout, a 5xx, a 429, a
19
+ * conditional-write conflict, an expired token. Everything else (403, 400,
20
+ * 404, a bad bucket name) is final. */
21
+ export class BlobTransientError extends Error {
22
+ readonly status?: number;
23
+ /** The store's own error code when it gave one (S3: `SlowDown`, ...). */
24
+ readonly code?: string;
25
+ constructor(message: string, status?: number, code?: string) {
26
+ super(message);
27
+ this.name = "BlobTransientError";
28
+ this.status = status;
29
+ this.code = code;
30
+ }
31
+ }
32
+
33
+ /** The store said no and will say no again: wrong credentials, no such bucket,
34
+ * a malformed request. Carries the HTTP status and the store's error code. */
35
+ export class BlobStoreError extends Error {
36
+ readonly status: number;
37
+ readonly code?: string;
38
+ constructor(message: string, status: number, code?: string) {
39
+ super(message);
40
+ this.name = "BlobStoreError";
41
+ this.status = status;
42
+ this.code = code;
43
+ }
44
+ }
45
+
46
+ /** The bytes being uploaded stopped matching what was announced (the file was
47
+ * truncated, rewritten, or does not hash to the name it was given). Not
48
+ * retried: reading it again would give the same answer. */
49
+ export class BlobSourceError extends Error {
50
+ constructor(message: string) {
51
+ super(message);
52
+ this.name = "BlobSourceError";
53
+ }
54
+ }
55
+
56
+ export interface PutOptions {
57
+ contentType?: string;
58
+ signal?: AbortSignal;
59
+ }
60
+
61
+ export interface PutSourceOptions extends PutOptions {
62
+ /** Hex sha256 of the whole content, when the caller has it (a blob key is
63
+ * one). It is signed into the request, so the store verifies it; without it
64
+ * the source is read once more to find it. */
65
+ sha256?: string;
66
+ }
67
+
68
+ export interface PutResult {
69
+ created: boolean;
70
+ /** The store's ETag for the object that is there, unquoted, when it said.
71
+ * For a single-request upload that is the md5 of the content on S3, R2 and
72
+ * MinIO; for a multipart upload it is `<hash>-<parts>`. */
73
+ etag?: string;
74
+ }
75
+
76
+ export interface HeadResult {
77
+ size: number;
78
+ /** When the object was last written, when the store says (whole seconds on
79
+ * S3). The garbage collector's grace period is measured from here. NOTE: a
80
+ * conditional put that finds the object already there does NOT refresh it,
81
+ * so an old blob that a new publish reuses looks old to a sweeper — the
82
+ * grace period alone does not protect it (see publish.ts, "the GC window"). */
83
+ modifiedAt?: Date;
84
+ etag?: string;
85
+ }
86
+
87
+ /**
88
+ * A re-readable source of bytes. Streaming upload needs to read the same bytes
89
+ * more than once: to hash them before they are sent, and again for every retry
90
+ * or resumed part. So it is a *range reader*, not a one-shot stream.
91
+ */
92
+ export interface BlobSource {
93
+ readonly size: number;
94
+ /** The bytes [start, end) as a stream. Throws BlobSourceError if the source
95
+ * turns out shorter than `size`. */
96
+ read(start: number, end: number, signal?: AbortSignal): AsyncIterable<Uint8Array>;
97
+ }
98
+
99
+ /**
100
+ * What every caller gets: create-only, read, ask. There is deliberately no
101
+ * overwrite and no delete here — an object is named by its content, so the only
102
+ * write that makes sense is "put it if it is not there", and removing one is
103
+ * the garbage collector's job alone (BlobSweeper, below). A missed option
104
+ * cannot corrupt a shared object because the option does not exist.
105
+ */
106
+ export interface BlobStore {
107
+ readonly kind: "fs" | "s3";
108
+ /** Write only if nothing is at the key. `created: false` means it was
109
+ * already there; for a content-addressed key that is success. The existing
110
+ * object is NOT verified against `body` — callers that need that compare the
111
+ * returned `etag` or read it back. After a retry, `created: false` can also
112
+ * mean "my first attempt landed and its answer was lost". */
113
+ putIfAbsent(key: string, body: Uint8Array, opts?: PutOptions): Promise<PutResult>;
114
+ /** The same, for content that should not be held in memory: streamed from the
115
+ * source, and — on s3, past the multipart threshold — uploaded in parts that
116
+ * survive an interruption and are picked up again by the next call. */
117
+ putSourceIfAbsent(key: string, source: BlobSource, opts?: PutSourceOptions): Promise<PutResult>;
118
+ /** The object as a stream, optionally one inclusive byte range. Throws BlobNotFound. */
119
+ get(key: string, opts?: { range?: { start: number; end: number }; signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>>;
120
+ head(key: string, opts?: { signal?: AbortSignal }): Promise<HeadResult | null>;
121
+ }
122
+
123
+ /** Removal. Held by the garbage collector and by tests; not passed to publish. */
124
+ export interface BlobSweeper {
125
+ /** Idempotent: a missing key is the end state asked for. */
126
+ delete(key: string, opts?: { signal?: AbortSignal }): Promise<void>;
127
+ /** Throw away uploads that were started and never finished (s3 multipart
128
+ * uploads; fs temp files) and are older than `olderThanMs`. Returns how many.
129
+ * A bucket lifecycle rule (AbortIncompleteMultipartUpload) does the same on
130
+ * AWS and R2; this is for stores that have none, and for tests. */
131
+ abortStaleUploads(opts: { olderThanMs: number; prefix?: string; signal?: AbortSignal }): Promise<number>;
132
+ /** An account is gone: remove everything under its prefix. Only a store that
133
+ * can enumerate has it (the folder one); a bucket's objects are the
134
+ * sweeper's once the account's pins are released. */
135
+ purgeTenant?(tenant: string): Promise<void>;
136
+ /** Every object under a key prefix, with its size and last-modified time —
137
+ * what the sweeper walks. */
138
+ list?(prefix: string, opts?: { signal?: AbortSignal }): AsyncIterable<ListedObject>;
139
+ /** The accounts that have objects (the first key segment under `t/`). */
140
+ tenants?(opts?: { signal?: AbortSignal }): Promise<string[]>;
141
+ }
142
+
143
+ export interface ListedObject {
144
+ key: string;
145
+ size: number;
146
+ modifiedAt: Date;
147
+ }
148
+
149
+ /** Read a whole object. For manifests and small blobs; a large file is
150
+ * streamed with `get`. */
151
+ export async function readAll(store: BlobStore, key: string): Promise<Buffer> {
152
+ const chunks: Buffer[] = [];
153
+ const reader = (await store.get(key)).getReader();
154
+ for (;;) {
155
+ const { done, value } = await reader.read();
156
+ if (done) break;
157
+ chunks.push(Buffer.from(value));
158
+ }
159
+ return Buffer.concat(chunks);
160
+ }
161
+
162
+ // ---------- keys ----------
163
+
164
+ /** A key is slash-separated safe segments. Checked in every driver, because a
165
+ * key reaches the fs driver as a path. */
166
+ export function assertKey(key: string): string {
167
+ if (!key || key.length > 600 || key.startsWith("/") || key.split("/").some((s) => !/^[A-Za-z0-9._=-]{1,200}$/.test(s) || s === "." || s === "..")) {
168
+ throw new Error(`illegal object key: ${key.slice(0, 80)}`);
169
+ }
170
+ return key;
171
+ }
172
+
173
+ // ---------- sources ----------
174
+
175
+ export function bufferSource(buf: Uint8Array): BlobSource {
176
+ return {
177
+ size: buf.byteLength,
178
+ async *read(start, end) {
179
+ const hi = Math.min(end, buf.byteLength);
180
+ // Slices of at most 1 MiB, so a consumer sees a stream either way.
181
+ for (let at = start; at < hi; at += 1 << 20) yield buf.subarray(at, Math.min(at + (1 << 20), hi));
182
+ },
183
+ };
184
+ }
185
+
186
+ /** A file on disk. The size is taken now; if the file is shorter (or longer)
187
+ * when it is read, the read throws BlobSourceError rather than send a body
188
+ * that no longer matches what was announced. */
189
+ export function fileSource(filePath: string): BlobSource {
190
+ const size = fs.statSync(filePath).size;
191
+ return {
192
+ size,
193
+ async *read(start, end, signal) {
194
+ const hi = Math.min(end, size);
195
+ if (hi <= start) return;
196
+ const stream = fs.createReadStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal });
197
+ let got = 0;
198
+ for await (const chunk of stream) {
199
+ got += (chunk as Buffer).length;
200
+ yield chunk as Buffer;
201
+ }
202
+ if (got !== hi - start) throw new BlobSourceError(`${filePath} changed while it was being uploaded: expected ${hi - start} bytes at ${start}, read ${got}`);
203
+ },
204
+ };
205
+ }
206
+
207
+ /** sha256 (and md5, which is what a single-request ETag is) of a range. */
208
+ export async function hashRange(source: BlobSource, start: number, end: number, signal?: AbortSignal): Promise<{ sha256: string; md5: string }> {
209
+ const sha = crypto.createHash("sha256");
210
+ const md5 = crypto.createHash("md5");
211
+ for await (const chunk of source.read(start, end, signal)) {
212
+ sha.update(chunk);
213
+ md5.update(chunk);
214
+ }
215
+ return { sha256: sha.digest("hex"), md5: md5.digest("hex") };
216
+ }
@@ -68,6 +68,10 @@ export function browseTier(vendor: string | null | undefined): { tier: BrowseTie
68
68
  export type BrowseVerdict =
69
69
  | { kind: "legacy" }
70
70
  | { kind: "hosted" }
71
+ /** FOL-145: a vendor's browser held to the list through foldrun's vendor
72
+ * door — the vendor's key bound to its API, the proxy's session rules on
73
+ * every call, the door its only proxy. */
74
+ | { kind: "vendor"; vendor: string }
71
75
  | { kind: "refuse"; message: string };
72
76
 
73
77
  export function browseVerdict(o: {
@@ -79,10 +83,13 @@ export function browseVerdict(o: {
79
83
  vendor: string | null | undefined;
80
84
  /** Can this executor wall the step's network (Platform.confinesBrowsing)? */
81
85
  confines: boolean;
86
+ /** The step's grant carries a vendor door for this vendor (vendorDoorFor). */
87
+ door?: boolean;
82
88
  }): BrowseVerdict {
83
89
  if (o.level === "open" || !o.enforce || !o.confines) return { kind: "legacy" };
84
90
  const { tier, title } = browseTier(o.vendor);
85
91
  if (tier === "hosted") return { kind: "hosted" };
92
+ if (tier === "vendor" && o.door) return { kind: "vendor", vendor: (o.vendor ?? "").trim().toLowerCase() };
86
93
  const why =
87
94
  tier === "vendor"
88
95
  ? `${title} browses from its own network, and foldrun cannot hold it to network: until that vendor is qualified (FOL-110 phase 4)`
@@ -100,8 +107,12 @@ export function browseVerdict(o: {
100
107
  * an egress proxy: the step's list, and whether it holds — `hosted` when
101
108
  * browseVerdict put the step under the wall, else the plain fact that it
102
109
  * does not hold yet, for the browser or anything else in the step. */
103
- export function browseNetworkLine(policy: NetworkPolicy, vendor: string | null | undefined, opts: { hosted?: boolean } = {}): string {
110
+ export function browseNetworkLine(policy: NetworkPolicy, vendor: string | null | undefined, opts: { hosted?: boolean; vendorDoor?: boolean } = {}): string {
104
111
  const what = networkLine(policy, true);
112
+ if (opts.vendorDoor) {
113
+ const { title } = browseTier(vendor);
114
+ return `${what} — enforced — through foldrun's vendor door: ${title}'s browser runs on the vendor's machines, and the session it starts has foldrun's door as its only proxy, so its pages are held to this list (no site a secret is bound to: a vendor's browser cannot trust foldrun's certificate, FOL-145).`;
115
+ }
105
116
  if (opts.hosted) {
106
117
  return `${what} — enforced — hosted: the browser runs inside this step's sandbox, whose network reaches only the egress proxy (which holds the list), so a page, a script or a changed proxy setting reaches no site off the list.`;
107
118
  }
@@ -117,3 +128,40 @@ export function browseNetworkLine(policy: NetworkPolicy, vendor: string | null |
117
128
  : `. Its browser (${title}) always browses through its own network and cannot be held to network: — a restricted, enforced network: will refuse it (FOL-110)`;
118
129
  return `${what}${now}${later}.`;
119
130
  }
131
+
132
+ // ------------------------------------------------ FOL-145: the vendor door
133
+
134
+ /** Set to "1" for a step whose vendor browser is held through the door:
135
+ * the web tool sends the vendor's API calls and its remote-control
136
+ * WebSocket through the egress proxy's /e/ door (Playwright's
137
+ * connectOverCDP ignores HTTPS_PROXY, so a walled sandbox has no other way). */
138
+ export const VENDOR_DOOR_ENV = "FOLDRUN_VENDOR_DOOR";
139
+
140
+ /** The hosts a vendor's key is bound to in door mode: its API, and the
141
+ * remote-control hosts known so far. Browserbase's and Hyperbrowser's
142
+ * remote-control hosts come back in their session answers and are added as
143
+ * FOL-151 qualifies them; until then those vendors fail closed there. */
144
+ export const VENDOR_DOOR_HOSTS: Readonly<Record<string, readonly string[]>> = {
145
+ browserbase: ["api.browserbase.com"],
146
+ steel: ["api.steel.dev", "connect.steel.dev"],
147
+ hyperbrowser: ["api.hyperbrowser.ai"],
148
+ browserless: ["production-sfo.browserless.io", "production-lon.browserless.io", "production-ams.browserless.io"],
149
+ };
150
+
151
+ /**
152
+ * The vendor door for a step's vendor, or null. On only when the install
153
+ * says so — FOLDRUN_VENDOR_EGRESS=1, FOLDRUN_VENDOR_EGRESS_URL (the door's
154
+ * public address) — and the vendor is in FOLDRUN_VENDOR_EGRESS_VENDORS (the
155
+ * vendors qualified, or on trial while FOL-151 qualifies them; empty by
156
+ * default, so nothing changes until a vendor is listed).
157
+ */
158
+ export function vendorDoorFor(vendor: string | null | undefined, env: Record<string, string | undefined> = process.env): { vendor: string; server: string } | null {
159
+ const name = (vendor ?? "").trim().toLowerCase();
160
+ if (!name || env.FOLDRUN_VENDOR_EGRESS !== "1") return null;
161
+ const server = (env.FOLDRUN_VENDOR_EGRESS_URL ?? "").trim();
162
+ if (!/^https?:\/\/[^/\s]+$/.test(server.replace(/\/$/, ""))) return null;
163
+ const listed = (env.FOLDRUN_VENDOR_EGRESS_VENDORS ?? "").split(",").map((v) => v.trim().toLowerCase()).filter(Boolean);
164
+ if (!listed.includes(name) || !VENDOR_DOOR_HOSTS[name]) return null;
165
+ if (browseTier(name).tier !== "vendor") return null;
166
+ return { vendor: name, server: server.replace(/\/$/, "") };
167
+ }
package/src/egress.ts CHANGED
@@ -132,6 +132,12 @@ export interface EgressGrant {
132
132
  * searchDoorWanted): a held step's way to the account's search engine.
133
133
  * `max` caps how many searches go through it. Absent: the door refuses. */
134
134
  search?: { max?: number };
135
+ /** FOL-145: a step whose vendor browser is held to its list. The proxy
136
+ * applies the vendor's session rules (foldrun-platform
137
+ * vendor-session-policy.ts) to that vendor's API calls on the /e/ door —
138
+ * the call that starts a browser gets `server`, foldrun's vendor egress
139
+ * door, as its only proxy. Absent: nothing changes. */
140
+ vendorDoor?: { vendor: string; server: string };
135
141
  }
136
142
 
137
143
  export interface EgressLease {
package/src/evals.ts CHANGED
@@ -39,7 +39,7 @@ import fs from "node:fs";
39
39
  import crypto from "node:crypto";
40
40
  import path from "node:path";
41
41
  import { deployedCommit } from "./deploy.ts";
42
- import { latestRevisionId } from "./history.ts";
42
+ import { latestRevisionIdLocal as latestRevisionId } from "./history.ts";
43
43
  import matter from "./matter.ts";
44
44
  import { spawn } from "node:child_process";
45
45
  import { hostSafeEnv } from "./host-env.ts";
package/src/history.ts CHANGED
@@ -55,6 +55,64 @@ export function registerTreeReader(fn: TreeReader) {
55
55
  readTree = (tenant, scope) => fn(tenant, scope) ?? prev(tenant, scope);
56
56
  }
57
57
 
58
+ /** The scope's tree as the registered readers see it (text files only), or null. */
59
+ export function currentTree(tenant: string, scope: string): RevisionFile[] | null {
60
+ return readTree(tenant, scope);
61
+ }
62
+
63
+ /**
64
+ * Where a committed change set is also handed (workspace-revisions.ts registers
65
+ * here: this module cannot import it, it imports the store which imports this).
66
+ * Called after the legacy record is written; never throws into the writer.
67
+ */
68
+ type Journal = (tenant: string, scope: string, files: RevisionFile[], meta: { by: string; message: string; at: string }) => void;
69
+ let journal: Journal | null = null;
70
+ export function registerJournal(fn: Journal | null) {
71
+ journal = fn;
72
+ }
73
+
74
+ /** A workspace was deleted: whatever a registered journal still holds for it
75
+ * (queued changes, their files) goes too (FOL-126 phase 4). */
76
+ let onGone: ((tenant: string, workspace: string) => void) | null = null;
77
+ export function registerWorkspaceGone(fn: ((tenant: string, workspace: string) => void) | null) {
78
+ onGone = fn;
79
+ }
80
+ export function workspaceGone(tenant: string, workspace: string): void {
81
+ try {
82
+ onGone?.(tenant, workspace);
83
+ } catch {
84
+ // a journal that cannot be cleared now is cleared at the next boot (the replay discards a missing workspace)
85
+ }
86
+ }
87
+
88
+ /**
89
+ * What follows a workspace through a delete or a rename (workspace-revisions.ts
90
+ * registers it): its journal and its history in the revision store. The async
91
+ * forms run the folder's own change INSIDE them (`remove`, `rename`), so that
92
+ * a store which cannot be reached stops the change before anything is removed
93
+ * or moved, and a writer racing the change is held off until it is done. The
94
+ * sync forms are for a caller that cannot wait: they do what can be done now
95
+ * and finish in the background.
96
+ */
97
+ export interface WorkspaceLifecycle {
98
+ drop(tenant: string, workspace: string, remove: () => void): Promise<void>;
99
+ move(tenant: string, from: string, to: string, rename: () => void): Promise<void>;
100
+ moved(tenant: string, from: string, to: string): void;
101
+ }
102
+ let lifecycleHooks: WorkspaceLifecycle | null = null;
103
+ export function registerWorkspaceLifecycle(l: WorkspaceLifecycle | null) {
104
+ lifecycleHooks = l;
105
+ }
106
+ export const workspaceLifecycle = (): WorkspaceLifecycle | null => lifecycleHooks;
107
+ /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
108
+ export function workspaceMoved(tenant: string, from: string, to: string): void {
109
+ try {
110
+ lifecycleHooks?.moved(tenant, from, to);
111
+ } catch {
112
+ // finished by the next reconcile
113
+ }
114
+ }
115
+
58
116
  function assertSafeName(v: string, what: string) {
59
117
  if (!/^[A-Za-z0-9][A-Za-z0-9._@-]{0,120}$/.test(v)) throw new Error(`illegal ${what}: ${v}`);
60
118
  }
@@ -166,6 +224,11 @@ export function recordRevision(
166
224
  // outside this call, such as a bundle's generated index.
167
225
  snapshot(tenant, scope, rev.id);
168
226
  fs.appendFileSync(path.join(dir, "index.jsonl"), `${JSON.stringify(line)}\n`);
227
+ try {
228
+ journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
229
+ } catch {
230
+ // the revision store is not allowed to break a save; workspace-revisions logs and retries
231
+ }
169
232
  return rev;
170
233
  }
171
234
 
@@ -209,13 +272,13 @@ function snapshot(tenant: string, scope: string, id: string): boolean {
209
272
  }
210
273
 
211
274
  /** Whether a revision can be restored to: it has a snapshot. */
212
- export function hasSnapshot(tenant: string, scope: string, id: string): boolean {
275
+ export function hasSnapshotLocal(tenant: string, scope: string, id: string): boolean {
213
276
  assertSafeName(id, "revision id");
214
277
  return fs.existsSync(treePath(tenant, scope, id));
215
278
  }
216
279
 
217
280
  /** The whole tree at revision `id`, or null when it has no snapshot. */
218
- export function snapshotAt(tenant: string, scope: string, id: string): { path: string; content: string }[] | null {
281
+ export function snapshotAtLocal(tenant: string, scope: string, id: string): { path: string; content: string }[] | null {
219
282
  assertSafeName(id, "revision id");
220
283
  let manifest: { v: number; files: Record<string, string> };
221
284
  try {
@@ -239,7 +302,7 @@ function snapshotIds(tenant: string, scope: string): Set<string> {
239
302
  }
240
303
 
241
304
  /** The newest revision that can be restored to — what "now" is in history. */
242
- export function headRevision(tenant: string, scope: string): RevisionSummary | null {
305
+ export function headRevisionLocal(tenant: string, scope: string): RevisionSummary | null {
243
306
  const have = snapshotIds(tenant, scope);
244
307
  return journalRevisions(tenant, scope, { limit: Infinity }).find((r) => have.has(r.id)) ?? null;
245
308
  }
@@ -251,8 +314,8 @@ export function headRevision(tenant: string, scope: string): RevisionSummary | n
251
314
  * by a path that never recorded a change. Returns the head's id, or null
252
315
  * when there is nothing to snapshot.
253
316
  */
254
- export function ensureBaseline(tenant: string, scope: string, by = "foldrun"): string | null {
255
- const head = headRevision(tenant, scope);
317
+ export function ensureBaselineLocal(tenant: string, scope: string, by = "foldrun"): string | null {
318
+ const head = headRevisionLocal(tenant, scope);
256
319
  if (head) return head.id;
257
320
  const tree = readTree(tenant, scope);
258
321
  if (!tree || tree.length === 0) return null;
@@ -265,7 +328,7 @@ export function ensureBaseline(tenant: string, scope: string, by = "foldrun"): s
265
328
  try {
266
329
  fs.writeFileSync(marker, id, { flag: "wx" });
267
330
  } catch {
268
- const held = headRevision(tenant, scope)?.id ?? null;
331
+ const held = headRevisionLocal(tenant, scope)?.id ?? null;
269
332
  // A marker with no baseline behind it, minutes old, is a process that
270
333
  // died writing one: clear it, and the next call writes the baseline.
271
334
  try {
@@ -297,16 +360,20 @@ export function ensureBaseline(tenant: string, scope: string, by = "foldrun"): s
297
360
  * moment. Null when history holds nothing that old. Throws (status 400) on
298
361
  * something that is none of those.
299
362
  */
300
- export function resolveRevision(
363
+ export function resolveRevisionLocal(
301
364
  tenant: string,
302
365
  scope: string,
303
366
  to: string,
304
367
  now = Date.now(),
305
368
  ): { id: string; at: string; by: string; message: string } | null {
369
+ const have = snapshotIds(tenant, scope);
370
+ return resolveIn(journalRevisions(tenant, scope, { limit: Infinity }).filter((r) => have.has(r.id)), to, now);
371
+ }
372
+
373
+ /** The pick of resolveRevision over a newest-first list of restorable revisions. */
374
+ function resolveIn(all: RevisionSummary[], to: string, now: number): { id: string; at: string; by: string; message: string } | null {
306
375
  const t = to.trim();
307
376
  if (!t || t.startsWith("-")) throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
308
- const have = snapshotIds(tenant, scope);
309
- const all = journalRevisions(tenant, scope, { limit: Infinity }).filter((r) => have.has(r.id));
310
377
  const rel = /^(\d+)\s*(m|h|d|w)$/.exec(t);
311
378
  const moment = rel
312
379
  ? now - Number(rel[1]) * { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[rel[2] as "m" | "h" | "d" | "w"]
@@ -347,7 +414,7 @@ function describe(files: RevisionFile[]): string {
347
414
  }
348
415
 
349
416
  /** Newest first. `forPath` narrows to revisions that touched one file. */
350
- export function listRevisions(
417
+ export function listRevisionsLocal(
351
418
  tenant: string,
352
419
  scope: string,
353
420
  opts: { forPath?: string; limit?: number } = {},
@@ -416,7 +483,7 @@ function rebuildIndex(dir: string): RevisionSummary[] {
416
483
  return rows.map(({ written: _w, ...r }) => r).reverse();
417
484
  }
418
485
 
419
- export function readRevision(tenant: string, scope: string, id: string, forPath?: string): Revision | null {
486
+ export function readRevisionLocal(tenant: string, scope: string, id: string, forPath?: string): Revision | null {
420
487
  assertSafeName(id, "revision id");
421
488
  const file = path.join(historyDir(tenant, scope), `${id}.json`);
422
489
  if (!fs.existsSync(file)) return null;
@@ -427,11 +494,14 @@ export function readRevision(tenant: string, scope: string, id: string, forPath?
427
494
  /** The files changed after revision `from` up to and including `to`, in a
428
495
  * scope — what differs between the versions two runs ran (FOL-72). Null
429
496
  * when either is unknown or `to` is not after `from`. */
430
- export function changedPathsBetween(tenant: string, scope: string, from: string | null, to: string | null): string[] | null {
497
+ export function changedPathsBetweenLocal(tenant: string, scope: string, from: string | null, to: string | null): string[] | null {
431
498
  if (!from || !to) return null;
432
499
  if (from === to) return [];
433
- const revs = listRevisions(tenant, scope, { limit: 500 }); // newest first
434
- // An exact id before a commit, as resolveRevision.
500
+ return changedIn(listRevisionsLocal(tenant, scope, { limit: 500 }), from, to);
501
+ }
502
+
503
+ function changedIn(revs: RevisionSummary[], from: string, to: string): string[] | null {
504
+ // newest first. An exact id before a commit, as resolveRevision.
435
505
  const at = (x: string) => {
436
506
  const byId = revs.findIndex((r) => r.id === x);
437
507
  return byId >= 0 ? byId : revs.findIndex((r) => r.commit === x);
@@ -444,8 +514,104 @@ export function changedPathsBetween(tenant: string, scope: string, from: string
444
514
 
445
515
  /** The most recent revision id for a scope — what a change is attributed
446
516
  * to when nothing more specific (a deployed commit) is on record. */
447
- export function latestRevisionId(tenant: string, scope: string): string | null {
448
- return listRevisions(tenant, scope, { limit: 1 })[0]?.id ?? null;
517
+ export function latestRevisionIdLocal(tenant: string, scope: string): string | null {
518
+ return listRevisionsLocal(tenant, scope, { limit: 1 })[0]?.id ?? null;
519
+ }
520
+
521
+
522
+ // ------------------------------------------------- history from revisions
523
+ //
524
+ // FOL-126 phase 3: where the install keeps revisions (workspace-revisions.ts
525
+ // registers a view), the history page, a revision's diff, the restore points
526
+ // and run-to-run compare are answered from them — the same shapes this file
527
+ // has always returned. Everything is async because a revision lives in a
528
+ // store, not on this disk. Where nothing is registered (a laptop, the CLI, an
529
+ // install with the journal off) or a workspace has no revisions yet, the
530
+ // local `.history/` answers, exactly as before; where both exist the list is
531
+ // the revisions followed by the older local entries, so turning revisions on
532
+ // loses no history. The account shelf ("@library") is never in revisions.
533
+
534
+ export interface RevisionView {
535
+ /** Newest first, or null when revisions do not serve this scope. */
536
+ list(tenant: string, scope: string, opts: { forPath?: string; limit?: number }): Promise<RevisionSummary[] | null>;
537
+ read(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null>;
538
+ snapshot(tenant: string, scope: string, id: string): Promise<{ path: string; content: string }[] | null>;
539
+ }
540
+ let view: RevisionView | null = null;
541
+ export function registerRevisionView(v: RevisionView | null) {
542
+ view = v;
543
+ }
544
+
545
+ /** Revisions first, then the local entries older than the oldest of them. */
546
+ async function combined(tenant: string, scope: string, opts: { forPath?: string; limit?: number }, restorableOnly = false): Promise<RevisionSummary[]> {
547
+ const limit = opts.limit ?? 200;
548
+ const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit: Number.isFinite(limit) ? limit : 500 }) : null;
549
+ let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
550
+ if (restorableOnly) {
551
+ const have = snapshotIds(tenant, scope);
552
+ local = local.filter((r) => have.has(r.id));
553
+ }
554
+ if (!mine || !mine.length) return local.slice(0, limit);
555
+ const oldest = mine[mine.length - 1].at;
556
+ const seen = new Set(mine.map((r) => r.id));
557
+ return [...mine, ...local.filter((r) => !seen.has(r.id) && r.at < oldest)].slice(0, limit);
558
+ }
559
+
560
+ export async function listRevisions(tenant: string, scope: string, opts: { forPath?: string; limit?: number } = {}): Promise<RevisionSummary[]> {
561
+ return combined(tenant, scope, opts);
562
+ }
563
+
564
+ /** The list the history page shows: each row with whether it can be restored
565
+ * to. One listing answers both — every revision in the store is restorable;
566
+ * a local entry is when it has a snapshot — where asking per row would list
567
+ * the store once per row. */
568
+ export async function listRevisionsRestorable(tenant: string, scope: string, opts: { forPath?: string; limit?: number } = {}): Promise<(RevisionSummary & { restorable: boolean })[]> {
569
+ const rows = await combined(tenant, scope, opts);
570
+ const have = snapshotIds(tenant, scope);
571
+ const stored = view && scope !== "@library" ? new Set(((await view.list(tenant, scope, { limit: 500 })) ?? []).map((r) => r.id)) : new Set<string>();
572
+ return rows.map((r) => ({ ...r, restorable: have.has(r.id) || stored.has(r.id) }));
573
+ }
574
+
575
+ export async function readRevision(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null> {
576
+ assertSafeName(id, "revision id");
577
+ const fromStore = view && scope !== "@library" ? await view.read(tenant, scope, id, forPath) : null;
578
+ return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
579
+ }
580
+
581
+ export async function snapshotAt(tenant: string, scope: string, id: string): Promise<{ path: string; content: string }[] | null> {
582
+ assertSafeName(id, "revision id");
583
+ const fromStore = view && scope !== "@library" ? await view.snapshot(tenant, scope, id) : null;
584
+ return fromStore ?? snapshotAtLocal(tenant, scope, id);
585
+ }
586
+
587
+ export async function hasSnapshot(tenant: string, scope: string, id: string): Promise<boolean> {
588
+ assertSafeName(id, "revision id");
589
+ if (hasSnapshotLocal(tenant, scope, id)) return true;
590
+ return Boolean(view && scope !== "@library" && (await view.list(tenant, scope, { limit: 500 }))?.some((r) => r.id === id));
591
+ }
592
+
593
+ export async function headRevision(tenant: string, scope: string): Promise<RevisionSummary | null> {
594
+ return (await combined(tenant, scope, { limit: 1 }, true))[0] ?? null;
595
+ }
596
+
597
+ export async function resolveRevision(tenant: string, scope: string, to: string, now = Date.now()): Promise<{ id: string; at: string; by: string; message: string } | null> {
598
+ return resolveIn(await combined(tenant, scope, { limit: Infinity }, true), to, now);
599
+ }
600
+
601
+ export async function changedPathsBetween(tenant: string, scope: string, from: string | null, to: string | null): Promise<string[] | null> {
602
+ if (!from || !to) return null;
603
+ if (from === to) return [];
604
+ return changedIn(await combined(tenant, scope, { limit: 500 }), from, to);
605
+ }
606
+
607
+ export async function latestRevisionId(tenant: string, scope: string): Promise<string | null> {
608
+ return (await combined(tenant, scope, { limit: 1 }))[0]?.id ?? null;
609
+ }
610
+
611
+ /** A scope with no revision at all gets a local baseline, as before. */
612
+ export async function ensureBaseline(tenant: string, scope: string, by = "foldrun"): Promise<string | null> {
613
+ const head = await headRevision(tenant, scope);
614
+ return head ? head.id : ensureBaselineLocal(tenant, scope, by);
449
615
  }
450
616
 
451
617
  // ------------------------------------------------------------------- diff