@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,161 @@
1
+ import type { ManifestId } from "./manifest.ts";
2
+ /** The two heads of a workspace (decided 6 Nov 2026): source and everything
3
+ * else authored move on the `workspace` head; `state/` moves on its own
4
+ * `state` head. A per-step state checkpoint therefore never makes a source
5
+ * save, or another run's checkpoint of different state, replay. */
6
+ export type Scope = "workspace" | "state";
7
+ export interface WorkspaceRef {
8
+ tenant: string;
9
+ workspace: string;
10
+ /** Which head. Unset = the workspace head. */
11
+ scope?: Scope;
12
+ }
13
+ export declare const scopeOf: (ws: WorkspaceRef) => Scope;
14
+ export interface Revision {
15
+ /** Opaque, unique. */
16
+ id: string;
17
+ /** Which head this revision belongs to. */
18
+ scope: Scope;
19
+ /** 1, 2, 3… per workspace. Display and ordering only: never compare it for
20
+ * "is this the head" — the id is what compare-and-set uses. */
21
+ seq: number;
22
+ parent: string | null;
23
+ /** The authored manifest and the state manifest this revision points at. */
24
+ authored: ManifestId;
25
+ state: ManifestId;
26
+ /** `user:<email>`, `run:<runId>:<agent>`, `assistant`, `deploy`… */
27
+ by: string;
28
+ message: string;
29
+ at: string;
30
+ /** The idempotency key the publisher chose. Unique per workspace. */
31
+ opId: string;
32
+ /** Set when this revision is a restore: the revision whose content it
33
+ * re-points at. The history keeps both; nothing is rewritten. */
34
+ restoredFrom?: string;
35
+ /** Paths whose competing version was kept as a conflict copy by this
36
+ * revision's replay. Informational (the dashboard shows it). */
37
+ conflicts?: string[];
38
+ }
39
+ /** What an operation id did. Recorded for EVERY finished operation, including
40
+ * one that turned out to change nothing: a retry after a lost answer must get
41
+ * the original outcome even if the head has moved on since. */
42
+ export interface OperationRecord {
43
+ opId: string;
44
+ /** Digest of the request (the caller's choice of bytes: publish uses a hash
45
+ * of the canonical changes, restore of its target and options). Reusing an
46
+ * op id with a different digest is a caller bug, never a retry. */
47
+ digest: string;
48
+ outcome: "committed" | "unchanged";
49
+ /** committed: the revision it made. unchanged: the head it found. */
50
+ revision: Revision | null;
51
+ }
52
+ /** An operation id was used before for a DIFFERENT request. */
53
+ export declare class OpIdReused extends Error {
54
+ readonly opId: string;
55
+ constructor(opId: string);
56
+ }
57
+ export interface CommitInput {
58
+ /** The head the writer built on: the revision id, or null for the first. */
59
+ base: string | null;
60
+ authored: ManifestId;
61
+ state: ManifestId;
62
+ opId: string;
63
+ /** See OperationRecord.digest. */
64
+ digest: string;
65
+ by: string;
66
+ message: string;
67
+ restoredFrom?: string;
68
+ conflicts?: string[];
69
+ /** Asked INSIDE the store's own exclusion (the workspace lock), right before
70
+ * the head moves: does the workspace still exist? A delete or rename on
71
+ * another pod holds that lock while it removes the history and the folder,
72
+ * so a commit that gets the lock afterwards finds the folder gone and is
73
+ * refused ("gone"), rather than recreating rows under a name that has
74
+ * none. Unset: no check (the contract tests, a laptop). */
75
+ guard?: () => boolean | Promise<boolean>;
76
+ }
77
+ export type CommitResult = {
78
+ status: "committed";
79
+ revision: Revision;
80
+ }
81
+ /** This opId committed before (maybe by an earlier attempt whose answer was
82
+ * lost). `revision` is what that attempt made. */
83
+ | {
84
+ status: "duplicate";
85
+ revision: Revision;
86
+ }
87
+ /** The head is no longer `base`. `head` is what it is now. Nothing written. */
88
+ | {
89
+ status: "stale";
90
+ head: Revision | null;
91
+ }
92
+ /** The guard said the workspace does not exist (any more). Nothing written. */
93
+ | {
94
+ status: "gone";
95
+ };
96
+ /** A row of the storage/ file index. */
97
+ export interface IndexedFile {
98
+ path: string;
99
+ sha: string;
100
+ size: number;
101
+ mime: string;
102
+ updatedAt: string;
103
+ by: string;
104
+ }
105
+ export interface RevisionStore {
106
+ readonly kind: "pg" | "local";
107
+ head(ws: WorkspaceRef): Promise<Revision | null>;
108
+ revision(ws: WorkspaceRef, id: string): Promise<Revision | null>;
109
+ /** Newest first. `before` is a seq: pass the last page's lowest seq. */
110
+ revisions(ws: WorkspaceRef, opts?: {
111
+ limit?: number;
112
+ before?: number;
113
+ }): Promise<Revision[]>;
114
+ commit(ws: WorkspaceRef, input: CommitInput): Promise<CommitResult>;
115
+ /** What an op id did, or null if it never finished. */
116
+ operation(ws: WorkspaceRef, opId: string): Promise<OperationRecord | null>;
117
+ /** Record that an operation finished without changing anything. Idempotent
118
+ * for the same digest; OpIdReused for another. */
119
+ recordNoop(ws: WorkspaceRef, opId: string, digest: string): Promise<OperationRecord>;
120
+ files(ws: WorkspaceRef): Promise<IndexedFile[]>;
121
+ /** Upsert one row. `expectSha`: undefined = unconditional; null = only if
122
+ * the path has no row; a sha = only if the row still has it. Returns false
123
+ * when the expectation failed (nothing written). */
124
+ putFile(ws: WorkspaceRef, file: IndexedFile, expectSha?: string | null): Promise<boolean>;
125
+ /** Delete one row; same expectation rule. Returns whether a row went. */
126
+ deleteFile(ws: WorkspaceRef, path: string, expectSha?: string | null): Promise<boolean>;
127
+ /** Remove every head, revision and operation of one workspace (both heads),
128
+ * or of the whole account when `workspace` is omitted, with the pins its
129
+ * revisions held (so the objects can be collected). The next workspace of
130
+ * that name starts empty. Safe to repeat; returns how many revisions went. */
131
+ drop(target: {
132
+ tenant: string;
133
+ workspace?: string;
134
+ }): Promise<number>;
135
+ /** Re-key a workspace's heads, revisions and operations (both heads) from one
136
+ * name to another, in one step. Whatever the new name already holds belonged
137
+ * to a workspace that no longer exists and is removed first. Revision ids
138
+ * do not change. A name with nothing under it moves nothing. */
139
+ move(tenant: string, from: string, to: string): Promise<void>;
140
+ /** Remove these revisions of one head (and the pins they held on their
141
+ * manifests; the objects themselves are the sweeper's). The head itself is
142
+ * never removed. Returns how many went. */
143
+ prune(ws: WorkspaceRef, ids: readonly string[]): Promise<number>;
144
+ /** Every manifest id a revision of this account names (both heads, all
145
+ * workspaces), or only those of revisions made at or after `since` (the
146
+ * sweeper's last look before a delete: what a publish committed meanwhile). */
147
+ manifestIds(tenant: string, opts?: {
148
+ since?: Date;
149
+ }): Promise<string[]>;
150
+ /** Does the store hold any revision at all? A sweeper that finds none, with
151
+ * objects in the bucket, suspects a wiped database and refuses. */
152
+ anyRevisions(): Promise<boolean>;
153
+ /** Every workspace that has a head or a revision, any account. */
154
+ workspaces(): Promise<{
155
+ tenant: string;
156
+ workspace: string;
157
+ }[]>;
158
+ }
159
+ export declare function assertOpId(opId: string): string;
160
+ export declare function newRevisionId(): string;
161
+ export declare function localRevisionStore(root?: string): RevisionStore;
@@ -0,0 +1,378 @@
1
+ // RevisionStore: the pointers (FOL-126, phase 1).
2
+ //
3
+ // The BlobStore holds bytes and never changes them. This holds the small
4
+ // transactional facts around them: which revision is a workspace's head, the
5
+ // history that led to it, which operation ids already happened, and the file
6
+ // index for storage/.
7
+ //
8
+ // One commit is one atomic step:
9
+ //
10
+ // commit(ws, { base, authored, state, opId, ... })
11
+ // - the head must still be `base` (compare-and-set), else `stale` and
12
+ // nothing is written;
13
+ // - an `opId` that already committed answers `duplicate` with the
14
+ // revision it made, and writes nothing — a retry whose first attempt's
15
+ // answer was lost cannot publish twice;
16
+ // - otherwise the revision row exists and the head points at it, together
17
+ // or not at all.
18
+ //
19
+ // Two implementations behind this one interface, proven by ONE contract suite
20
+ // (tests/revision-contract.ts):
21
+ //
22
+ // pg hosted. One transaction: CAS the head row, insert the revision,
23
+ // record the op id. Lives in foldrun-platform (core has no database).
24
+ // local one host, no FOLDRUN_DATABASE_URL: self-host Compose, which has no
25
+ // Postgres. Files under the data root, serialised by a cross-process
26
+ // lock; the revision file is created exclusively and IS the
27
+ // compare-and-set. Below.
28
+ //
29
+ // `db.ts` stays optional by design; nothing here makes Postgres required.
30
+ //
31
+ // Not in this interface yet, on purpose: runs, run events and logs. They move
32
+ // in phase 2 with their own shapes; sketching them now would be a guess.
33
+ import fs from "node:fs";
34
+ import path from "node:path";
35
+ import crypto from "node:crypto";
36
+ import { dataRoot } from "./paths.js";
37
+ import { assertSafeName } from "./store.js";
38
+ import { assertFilePath, withFileLock } from "./storage.js";
39
+ export const scopeOf = (ws) => ws.scope ?? "workspace";
40
+ /** An operation id was used before for a DIFFERENT request. */
41
+ export class OpIdReused extends Error {
42
+ opId;
43
+ constructor(opId) {
44
+ super(`operation id ${opId} was already used for a different request`);
45
+ this.name = "OpIdReused";
46
+ this.opId = opId;
47
+ }
48
+ }
49
+ const OP_ID = /^[A-Za-z0-9._:@=+-]{8,200}$/;
50
+ export function assertOpId(opId) {
51
+ if (!OP_ID.test(opId))
52
+ throw new Error("an operation id is 8–200 characters of letters, digits and . _ : @ = + -");
53
+ return opId;
54
+ }
55
+ export function newRevisionId() {
56
+ return `rev_${crypto.randomBytes(12).toString("hex")}`;
57
+ }
58
+ // ---------- local ----------
59
+ //
60
+ // Layout, under <root>/<tenant>/<workspace>/ :
61
+ //
62
+ // revs/<seq, 10 digits>.json one revision each, created EXCLUSIVELY
63
+ // (link of a finished temp file): the create
64
+ // is the compare-and-set — two writers
65
+ // racing for seq N, one gets EEXIST.
66
+ // ops/<sha256(opId)>.json { opId, seq } — written BEFORE the revision.
67
+ // A crash between the two leaves a pointer to
68
+ // a revision that does not exist; it is
69
+ // checked on read and then overwritten.
70
+ // files.json the storage/ index, replaced atomically
71
+ //
72
+ // The head is the highest seq in revs/. There is no separate head file to get
73
+ // out of step with the history. A directory listing per call is fine for one
74
+ // host; the pg implementation is the one built for scale.
75
+ //
76
+ // Everything runs inside withFileLock (cross-process, fenced, renewed), so two
77
+ // processes on one host serialise; the exclusive create is the second line of
78
+ // defence if the lock is ever taken over.
79
+ export function localRevisionStore(root = path.join(dataRoot(), ".revisions")) {
80
+ const dirOf = (ws) => {
81
+ assertSafeName(ws.tenant, "tenant");
82
+ assertSafeName(ws.workspace, "workspace");
83
+ // The state head is a separate history in a subfolder of its own; the
84
+ // workspace head's folder never lists it (seqs reads revs/ only).
85
+ return scopeOf(ws) === "state" ? path.join(root, ws.tenant, ws.workspace, "state-head") : path.join(root, ws.tenant, ws.workspace);
86
+ };
87
+ const lockOf = (ws) => path.join(root, ws.tenant, `.${ws.workspace}${scopeOf(ws) === "state" ? ".state" : ""}.lock`);
88
+ const seqName = (n) => `${String(n).padStart(10, "0")}.json`;
89
+ const opFile = (ws, opId) => path.join(dirOf(ws), "ops", `${crypto.createHash("sha256").update(opId).digest("hex")}.json`);
90
+ const readJson = (file) => {
91
+ try {
92
+ return JSON.parse(fs.readFileSync(file, "utf8"));
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ };
98
+ const writeAtomic = (file, data) => {
99
+ fs.mkdirSync(path.dirname(file), { recursive: true });
100
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
101
+ fs.writeFileSync(tmp, JSON.stringify(data));
102
+ fs.renameSync(tmp, file);
103
+ };
104
+ const seqs = (ws) => {
105
+ try {
106
+ return fs
107
+ .readdirSync(path.join(dirOf(ws), "revs"))
108
+ .filter((n) => /^\d{10}\.json$/.test(n))
109
+ .map((n) => Number(n.slice(0, 10)))
110
+ .sort((a, b) => a - b);
111
+ }
112
+ catch {
113
+ return [];
114
+ }
115
+ };
116
+ const bySeq = (ws, seq) => readJson(path.join(dirOf(ws), "revs", seqName(seq)));
117
+ const headOf = (ws) => {
118
+ const all = seqs(ws);
119
+ return all.length ? bySeq(ws, all[all.length - 1]) : null;
120
+ };
121
+ const operationOf = (ws, opId) => {
122
+ const op = readJson(opFile(ws, opId));
123
+ if (!op || op.opId !== opId)
124
+ return null;
125
+ if (op.outcome === "unchanged") {
126
+ const head = op.seq ? bySeq(ws, op.seq) : null;
127
+ return { opId, digest: op.digest, outcome: "unchanged", revision: head };
128
+ }
129
+ const rev = op.seq ? bySeq(ws, op.seq) : null;
130
+ // A pointer whose revision never landed (a crash between the two writes)
131
+ // is not an operation.
132
+ return rev && rev.opId === opId ? { opId, digest: op.digest, outcome: "committed", revision: rev } : null;
133
+ };
134
+ const locked = (ws, fn) => withFileLock(lockOf(ws), fn);
135
+ return {
136
+ kind: "local",
137
+ async head(ws) {
138
+ return headOf(ws);
139
+ },
140
+ async revision(ws, id) {
141
+ for (const seq of seqs(ws).reverse()) {
142
+ const r = bySeq(ws, seq);
143
+ if (r?.id === id)
144
+ return r;
145
+ }
146
+ return null;
147
+ },
148
+ async revisions(ws, opts = {}) {
149
+ const limit = Math.min(Math.max(opts.limit ?? 50, 1), 500);
150
+ const out = [];
151
+ for (const seq of seqs(ws).reverse()) {
152
+ if (opts.before !== undefined && seq >= opts.before)
153
+ continue;
154
+ const r = bySeq(ws, seq);
155
+ if (r)
156
+ out.push(r);
157
+ if (out.length >= limit)
158
+ break;
159
+ }
160
+ return out;
161
+ },
162
+ async operation(ws, opId) {
163
+ assertOpId(opId);
164
+ return operationOf(ws, opId);
165
+ },
166
+ async recordNoop(ws, opId, digest) {
167
+ assertOpId(opId);
168
+ return locked(ws, async () => {
169
+ const done = operationOf(ws, opId);
170
+ if (done) {
171
+ if (done.digest !== digest)
172
+ throw new OpIdReused(opId);
173
+ return done;
174
+ }
175
+ const head = headOf(ws);
176
+ writeAtomic(opFile(ws, opId), { opId, digest, outcome: "unchanged", seq: head?.seq ?? null, headId: head?.id ?? null });
177
+ return { opId, digest, outcome: "unchanged", revision: head };
178
+ });
179
+ },
180
+ async commit(ws, input) {
181
+ assertOpId(input.opId);
182
+ return locked(ws, async () => {
183
+ if (input.guard && !(await input.guard()))
184
+ return { status: "gone" };
185
+ const done = operationOf(ws, input.opId);
186
+ if (done) {
187
+ if (done.digest !== input.digest)
188
+ throw new OpIdReused(input.opId);
189
+ if (done.revision && done.outcome === "committed")
190
+ return { status: "duplicate", revision: done.revision };
191
+ throw new OpIdReused(input.opId); // it finished as "unchanged"; a commit is a different outcome
192
+ }
193
+ const head = headOf(ws);
194
+ if ((head?.id ?? null) !== input.base)
195
+ return { status: "stale", head };
196
+ const seq = (head?.seq ?? 0) + 1;
197
+ const revision = {
198
+ id: newRevisionId(),
199
+ scope: scopeOf(ws),
200
+ seq,
201
+ parent: head?.id ?? null,
202
+ authored: input.authored,
203
+ state: input.state,
204
+ by: input.by,
205
+ message: input.message,
206
+ at: new Date().toISOString(),
207
+ opId: input.opId,
208
+ ...(input.restoredFrom ? { restoredFrom: input.restoredFrom } : {}),
209
+ ...(input.conflicts?.length ? { conflicts: input.conflicts } : {}),
210
+ };
211
+ // Op pointer first, then the revision: see the layout note.
212
+ writeAtomic(opFile(ws, input.opId), { opId: input.opId, digest: input.digest, outcome: "committed", seq, headId: null });
213
+ const target = path.join(dirOf(ws), "revs", seqName(seq));
214
+ fs.mkdirSync(path.dirname(target), { recursive: true });
215
+ const tmp = `${target}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
216
+ fs.writeFileSync(tmp, JSON.stringify(revision));
217
+ try {
218
+ fs.linkSync(tmp, target); // EEXIST = someone else took this seq: stale
219
+ }
220
+ catch (err) {
221
+ if (err.code === "EEXIST")
222
+ return { status: "stale", head: headOf(ws) };
223
+ throw err;
224
+ }
225
+ finally {
226
+ fs.rmSync(tmp, { force: true });
227
+ }
228
+ return { status: "committed", revision };
229
+ });
230
+ },
231
+ async files(ws) {
232
+ return readJson(path.join(dirOf(ws), "files.json")) ?? [];
233
+ },
234
+ async putFile(ws, file, expectSha) {
235
+ assertFilePath(file.path);
236
+ return locked(ws, async () => {
237
+ const all = readJson(path.join(dirOf(ws), "files.json")) ?? [];
238
+ const was = all.find((f) => f.path === file.path);
239
+ if (expectSha !== undefined && (was?.sha ?? null) !== expectSha)
240
+ return false;
241
+ writeAtomic(path.join(dirOf(ws), "files.json"), [...all.filter((f) => f.path !== file.path), file]);
242
+ return true;
243
+ });
244
+ },
245
+ async deleteFile(ws, rel, expectSha) {
246
+ return locked(ws, async () => {
247
+ const all = readJson(path.join(dirOf(ws), "files.json")) ?? [];
248
+ const was = all.find((f) => f.path === rel);
249
+ if (!was)
250
+ return false;
251
+ if (expectSha !== undefined && was.sha !== expectSha)
252
+ return false;
253
+ writeAtomic(path.join(dirOf(ws), "files.json"), all.filter((f) => f.path !== rel));
254
+ return true;
255
+ });
256
+ },
257
+ async drop(target) {
258
+ assertSafeName(target.tenant, "tenant");
259
+ if (target.workspace === undefined) {
260
+ const dir = path.join(root, target.tenant);
261
+ const n = countRevs(dir);
262
+ fs.rmSync(dir, { recursive: true, force: true });
263
+ return n;
264
+ }
265
+ const ws = { tenant: target.tenant, workspace: target.workspace };
266
+ return locked(ws, () => locked({ ...ws, scope: "state" }, async () => {
267
+ const n = seqs(ws).length + seqs({ ...ws, scope: "state" }).length;
268
+ fs.rmSync(dirOf(ws), { recursive: true, force: true }); // the state head's folder is inside it
269
+ return n;
270
+ }));
271
+ },
272
+ async move(tenant, from, to) {
273
+ const a = { tenant, workspace: from };
274
+ const b = { tenant, workspace: to };
275
+ // Both names, in a fixed order, so two crossing renames cannot wait on each other.
276
+ const [first, second] = from < to ? [a, b] : [b, a];
277
+ return locked(first, () => locked(second, async () => {
278
+ const src = dirOf(a);
279
+ const dest = dirOf(b);
280
+ fs.rmSync(dest, { recursive: true, force: true }); // stale: that name has no workspace
281
+ if (fs.existsSync(src))
282
+ fs.renameSync(src, dest);
283
+ }));
284
+ },
285
+ async manifestIds(tenant, opts = {}) {
286
+ assertSafeName(tenant, "tenant");
287
+ const out = new Set();
288
+ const since = opts.since?.getTime() ?? -Infinity;
289
+ eachRevision(root, tenant, (_t, _w, r) => {
290
+ if (Date.parse(r.at) < since)
291
+ return;
292
+ out.add(r.authored);
293
+ out.add(r.state);
294
+ });
295
+ return [...out];
296
+ },
297
+ async anyRevisions() {
298
+ let any = false;
299
+ eachRevision(root, null, () => (any = true));
300
+ return any;
301
+ },
302
+ async workspaces() {
303
+ const out = new Map();
304
+ eachRevision(root, null, (tenant, workspace) => out.set(`${tenant}\0${workspace}`, { tenant, workspace }));
305
+ return [...out.values()];
306
+ },
307
+ async prune(ws, ids) {
308
+ if (!ids.length)
309
+ return 0;
310
+ return locked(ws, async () => {
311
+ const head = headOf(ws);
312
+ const want = new Set(ids);
313
+ let n = 0;
314
+ for (const seq of seqs(ws)) {
315
+ const r = bySeq(ws, seq);
316
+ if (!r || !want.has(r.id) || r.id === head?.id)
317
+ continue;
318
+ fs.rmSync(path.join(dirOf(ws), "revs", seqName(seq)), { force: true });
319
+ n++;
320
+ }
321
+ return n;
322
+ });
323
+ },
324
+ };
325
+ }
326
+ function eachRevision(root, tenant, fn) {
327
+ const tenants = tenant ? [tenant] : safeDirs(root);
328
+ for (const t of tenants) {
329
+ for (const w of safeDirs(path.join(root, t))) {
330
+ for (const d of [path.join(root, t, w, "revs"), path.join(root, t, w, "state-head", "revs")]) {
331
+ let names = [];
332
+ try {
333
+ names = fs.readdirSync(d).filter((x) => /^\d{10}\.json$/.test(x));
334
+ }
335
+ catch {
336
+ continue;
337
+ }
338
+ for (const n of names) {
339
+ try {
340
+ fn(t, w, JSON.parse(fs.readFileSync(path.join(d, n), "utf8")));
341
+ }
342
+ catch {
343
+ // torn: not a revision
344
+ }
345
+ }
346
+ }
347
+ }
348
+ }
349
+ }
350
+ function safeDirs(dir) {
351
+ try {
352
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
353
+ }
354
+ catch {
355
+ return [];
356
+ }
357
+ }
358
+ function countRevs(dir) {
359
+ let n = 0;
360
+ try {
361
+ for (const w of fs.readdirSync(dir)) {
362
+ if (w.startsWith("."))
363
+ continue;
364
+ for (const d of [path.join(dir, w, "revs"), path.join(dir, w, "state-head", "revs")]) {
365
+ try {
366
+ n += fs.readdirSync(d).filter((x) => /^\d{10}\.json$/.test(x)).length;
367
+ }
368
+ catch {
369
+ // none
370
+ }
371
+ }
372
+ }
373
+ }
374
+ catch {
375
+ // none
376
+ }
377
+ return n;
378
+ }
@@ -3,6 +3,7 @@ import type { PeerInfo } from "./operator.ts";
3
3
  import { type HookRecord } from "./hooks.ts";
4
4
  import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
5
5
  import { type ApiSpec, type Effort, type ModelCall } from "./store.ts";
6
+ import { type RunBase } from "./workspace-revisions.ts";
6
7
  import { type RefusedPath } from "./copy-back.ts";
7
8
  import type { CallIo, EventExtra, ExecUsage } from "./step-exec.ts";
8
9
  import type { TokenPrice } from "./catalog.ts";
@@ -248,6 +249,15 @@ export declare function writeHandedIn(workspaceRoot: string, runId: string, ref:
248
249
  export declare function readHandedIn(workspaceRoot: string, runId: string, ref: string): Record<string, string> | undefined;
249
250
  /** Forget it once the step's copy-out is done. */
250
251
  export declare function dropHandedIn(workspaceRoot: string, runId: string, ref: string): void;
252
+ /**
253
+ * The revisions a step's stage-in started from (FOL-126 fixes), kept on the host
254
+ * beside what it was handed, for the same reason: a driver that inherits the
255
+ * step publishes its copy-back against the SAME base, not against whatever the
256
+ * heads hold by then. Platform-owned, never staged, erased with the run.
257
+ */
258
+ export declare function baseRevisionPath(workspaceRoot: string, runId: string, ref: string): string | null;
259
+ export declare function writeBaseRevision(workspaceRoot: string, runId: string, ref: string, base: RunBase): void;
260
+ export declare function readBaseRevision(workspaceRoot: string, runId: string, ref: string): RunBase | undefined;
251
261
  /**
252
262
  * Every file's mtime under `dir`, relative path to milliseconds — so a copy
253
263
  * that cannot carry times can have them put back. `kubectl cp` unpacks with
@@ -281,6 +291,16 @@ export interface ApplyOptions {
281
291
  * changed come back, each told to onKept instead of refused. */
282
292
  allowConfig?: boolean;
283
293
  onKept?: (kept: RefusedPath) => void;
294
+ /** Where the writes are recorded as a revision (FOL-126 phase 4): the
295
+ * account and the run/step the copy-back belongs to. The workspace is the
296
+ * folder's name. Without it the folder is written and nothing is recorded
297
+ * (a laptop, a scratch dir). */
298
+ revision?: {
299
+ tenant: string;
300
+ runId?: string;
301
+ step?: string | number;
302
+ base?: RunBase | null;
303
+ };
284
304
  }
285
305
  export declare function applyContainerChanges(hostWs: string, containerWs: string, baseline?: string | Record<string, string>, note?: (message: string) => void, divert?: WriteDivert, opts?: ApplyOptions): string[];
286
306
  /**