@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.
- package/dist/src/approvals.js +3 -3
- package/dist/src/blob-cache.d.ts +58 -0
- package/dist/src/blob-cache.js +309 -0
- package/dist/src/blob-pins.d.ts +44 -0
- package/dist/src/blob-pins.js +61 -0
- package/dist/src/blob-store.d.ts +47 -0
- package/dist/src/blob-store.js +357 -0
- package/dist/src/blob-sweeper.d.ts +70 -0
- package/dist/src/blob-sweeper.js +254 -0
- package/dist/src/blob-types.d.ts +145 -0
- package/dist/src/blob-types.js +115 -0
- package/dist/src/browse-egress.d.ts +31 -0
- package/dist/src/browse-egress.js +43 -0
- package/dist/src/egress.d.ts +9 -0
- package/dist/src/evals.js +1 -1
- package/dist/src/history.d.ts +86 -9
- package/dist/src/history.js +132 -16
- package/dist/src/journal-store.d.ts +58 -0
- package/dist/src/journal-store.js +117 -0
- package/dist/src/manifest.d.ts +92 -0
- package/dist/src/manifest.js +239 -0
- package/dist/src/ops-log.js +26 -3
- package/dist/src/platform.d.ts +7 -0
- package/dist/src/platform.js +1 -0
- package/dist/src/publish.d.ts +134 -0
- package/dist/src/publish.js +434 -0
- package/dist/src/records.d.ts +72 -0
- package/dist/src/records.js +24 -0
- package/dist/src/revision-store.d.ts +161 -0
- package/dist/src/revision-store.js +378 -0
- package/dist/src/run-container.d.ts +20 -0
- package/dist/src/run-container.js +61 -0
- package/dist/src/runner.js +22 -4
- package/dist/src/s3-blob-store.d.ts +29 -0
- package/dist/src/s3-blob-store.js +458 -0
- package/dist/src/state-retention.d.ts +15 -0
- package/dist/src/state-retention.js +65 -0
- package/dist/src/storage.d.ts +29 -1
- package/dist/src/storage.js +331 -81
- package/dist/src/store.d.ts +41 -0
- package/dist/src/store.js +188 -5
- package/dist/src/trigger-log.js +17 -0
- package/dist/src/workspace-revisions.d.ts +259 -0
- package/dist/src/workspace-revisions.js +1274 -0
- package/package.json +1 -1
- package/src/approvals.ts +3 -3
- package/src/blob-cache.ts +354 -0
- package/src/blob-pins.ts +99 -0
- package/src/blob-store.ts +385 -0
- package/src/blob-sweeper.ts +308 -0
- package/src/blob-types.ts +216 -0
- package/src/browse-egress.ts +49 -1
- package/src/egress.ts +6 -0
- package/src/evals.ts +1 -1
- package/src/history.ts +182 -16
- package/src/journal-store.ts +152 -0
- package/src/manifest.ts +274 -0
- package/src/ops-log.ts +25 -3
- package/src/platform.ts +8 -0
- package/src/publish.ts +520 -0
- package/src/records.ts +105 -0
- package/src/revision-store.ts +513 -0
- package/src/run-container.ts +62 -0
- package/src/runner.ts +21 -4
- package/src/s3-blob-store.ts +489 -0
- package/src/state-retention.ts +83 -0
- package/src/storage.ts +335 -81
- package/src/store.ts +178 -5
- package/src/trigger-log.ts +15 -0
- package/src/workspace-revisions.ts +1324 -0
|
@@ -0,0 +1,513 @@
|
|
|
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
|
+
|
|
34
|
+
import fs from "node:fs";
|
|
35
|
+
import path from "node:path";
|
|
36
|
+
import crypto from "node:crypto";
|
|
37
|
+
import { dataRoot } from "./paths.ts";
|
|
38
|
+
import { assertSafeName } from "./store.ts";
|
|
39
|
+
import { assertFilePath, withFileLock } from "./storage.ts";
|
|
40
|
+
import type { ManifestId } from "./manifest.ts";
|
|
41
|
+
|
|
42
|
+
/** The two heads of a workspace (decided 6 Nov 2026): source and everything
|
|
43
|
+
* else authored move on the `workspace` head; `state/` moves on its own
|
|
44
|
+
* `state` head. A per-step state checkpoint therefore never makes a source
|
|
45
|
+
* save, or another run's checkpoint of different state, replay. */
|
|
46
|
+
export type Scope = "workspace" | "state";
|
|
47
|
+
|
|
48
|
+
export interface WorkspaceRef {
|
|
49
|
+
tenant: string;
|
|
50
|
+
workspace: string;
|
|
51
|
+
/** Which head. Unset = the workspace head. */
|
|
52
|
+
scope?: Scope;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const scopeOf = (ws: WorkspaceRef): Scope => ws.scope ?? "workspace";
|
|
56
|
+
|
|
57
|
+
export interface Revision {
|
|
58
|
+
/** Opaque, unique. */
|
|
59
|
+
id: string;
|
|
60
|
+
/** Which head this revision belongs to. */
|
|
61
|
+
scope: Scope;
|
|
62
|
+
/** 1, 2, 3… per workspace. Display and ordering only: never compare it for
|
|
63
|
+
* "is this the head" — the id is what compare-and-set uses. */
|
|
64
|
+
seq: number;
|
|
65
|
+
parent: string | null;
|
|
66
|
+
/** The authored manifest and the state manifest this revision points at. */
|
|
67
|
+
authored: ManifestId;
|
|
68
|
+
state: ManifestId;
|
|
69
|
+
/** `user:<email>`, `run:<runId>:<agent>`, `assistant`, `deploy`… */
|
|
70
|
+
by: string;
|
|
71
|
+
message: string;
|
|
72
|
+
at: string;
|
|
73
|
+
/** The idempotency key the publisher chose. Unique per workspace. */
|
|
74
|
+
opId: string;
|
|
75
|
+
/** Set when this revision is a restore: the revision whose content it
|
|
76
|
+
* re-points at. The history keeps both; nothing is rewritten. */
|
|
77
|
+
restoredFrom?: string;
|
|
78
|
+
/** Paths whose competing version was kept as a conflict copy by this
|
|
79
|
+
* revision's replay. Informational (the dashboard shows it). */
|
|
80
|
+
conflicts?: string[];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** What an operation id did. Recorded for EVERY finished operation, including
|
|
84
|
+
* one that turned out to change nothing: a retry after a lost answer must get
|
|
85
|
+
* the original outcome even if the head has moved on since. */
|
|
86
|
+
export interface OperationRecord {
|
|
87
|
+
opId: string;
|
|
88
|
+
/** Digest of the request (the caller's choice of bytes: publish uses a hash
|
|
89
|
+
* of the canonical changes, restore of its target and options). Reusing an
|
|
90
|
+
* op id with a different digest is a caller bug, never a retry. */
|
|
91
|
+
digest: string;
|
|
92
|
+
outcome: "committed" | "unchanged";
|
|
93
|
+
/** committed: the revision it made. unchanged: the head it found. */
|
|
94
|
+
revision: Revision | null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** An operation id was used before for a DIFFERENT request. */
|
|
98
|
+
export class OpIdReused extends Error {
|
|
99
|
+
readonly opId: string;
|
|
100
|
+
constructor(opId: string) {
|
|
101
|
+
super(`operation id ${opId} was already used for a different request`);
|
|
102
|
+
this.name = "OpIdReused";
|
|
103
|
+
this.opId = opId;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface CommitInput {
|
|
108
|
+
/** The head the writer built on: the revision id, or null for the first. */
|
|
109
|
+
base: string | null;
|
|
110
|
+
authored: ManifestId;
|
|
111
|
+
state: ManifestId;
|
|
112
|
+
opId: string;
|
|
113
|
+
/** See OperationRecord.digest. */
|
|
114
|
+
digest: string;
|
|
115
|
+
by: string;
|
|
116
|
+
message: string;
|
|
117
|
+
restoredFrom?: string;
|
|
118
|
+
conflicts?: string[];
|
|
119
|
+
/** Asked INSIDE the store's own exclusion (the workspace lock), right before
|
|
120
|
+
* the head moves: does the workspace still exist? A delete or rename on
|
|
121
|
+
* another pod holds that lock while it removes the history and the folder,
|
|
122
|
+
* so a commit that gets the lock afterwards finds the folder gone and is
|
|
123
|
+
* refused ("gone"), rather than recreating rows under a name that has
|
|
124
|
+
* none. Unset: no check (the contract tests, a laptop). */
|
|
125
|
+
guard?: () => boolean | Promise<boolean>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export type CommitResult =
|
|
129
|
+
| { status: "committed"; revision: Revision }
|
|
130
|
+
/** This opId committed before (maybe by an earlier attempt whose answer was
|
|
131
|
+
* lost). `revision` is what that attempt made. */
|
|
132
|
+
| { status: "duplicate"; revision: Revision }
|
|
133
|
+
/** The head is no longer `base`. `head` is what it is now. Nothing written. */
|
|
134
|
+
| { status: "stale"; head: Revision | null }
|
|
135
|
+
/** The guard said the workspace does not exist (any more). Nothing written. */
|
|
136
|
+
| { status: "gone" };
|
|
137
|
+
|
|
138
|
+
/** A row of the storage/ file index. */
|
|
139
|
+
export interface IndexedFile {
|
|
140
|
+
path: string;
|
|
141
|
+
sha: string;
|
|
142
|
+
size: number;
|
|
143
|
+
mime: string;
|
|
144
|
+
updatedAt: string;
|
|
145
|
+
by: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface RevisionStore {
|
|
149
|
+
readonly kind: "pg" | "local";
|
|
150
|
+
head(ws: WorkspaceRef): Promise<Revision | null>;
|
|
151
|
+
revision(ws: WorkspaceRef, id: string): Promise<Revision | null>;
|
|
152
|
+
/** Newest first. `before` is a seq: pass the last page's lowest seq. */
|
|
153
|
+
revisions(ws: WorkspaceRef, opts?: { limit?: number; before?: number }): Promise<Revision[]>;
|
|
154
|
+
commit(ws: WorkspaceRef, input: CommitInput): Promise<CommitResult>;
|
|
155
|
+
/** What an op id did, or null if it never finished. */
|
|
156
|
+
operation(ws: WorkspaceRef, opId: string): Promise<OperationRecord | null>;
|
|
157
|
+
/** Record that an operation finished without changing anything. Idempotent
|
|
158
|
+
* for the same digest; OpIdReused for another. */
|
|
159
|
+
recordNoop(ws: WorkspaceRef, opId: string, digest: string): Promise<OperationRecord>;
|
|
160
|
+
|
|
161
|
+
// The file index for storage/. Rows, not a document: two writers of
|
|
162
|
+
// different paths never touch each other's row, which is what the phase 0
|
|
163
|
+
// lock was standing in for.
|
|
164
|
+
files(ws: WorkspaceRef): Promise<IndexedFile[]>;
|
|
165
|
+
/** Upsert one row. `expectSha`: undefined = unconditional; null = only if
|
|
166
|
+
* the path has no row; a sha = only if the row still has it. Returns false
|
|
167
|
+
* when the expectation failed (nothing written). */
|
|
168
|
+
putFile(ws: WorkspaceRef, file: IndexedFile, expectSha?: string | null): Promise<boolean>;
|
|
169
|
+
/** Delete one row; same expectation rule. Returns whether a row went. */
|
|
170
|
+
deleteFile(ws: WorkspaceRef, path: string, expectSha?: string | null): Promise<boolean>;
|
|
171
|
+
|
|
172
|
+
// The lifecycle of a workspace's history (FOL-126 fixes, 8 Nov). A workspace
|
|
173
|
+
// is named by its folder, so what the store keeps under that name has to
|
|
174
|
+
// follow the folder: a delete takes it, a rename carries it.
|
|
175
|
+
|
|
176
|
+
/** Remove every head, revision and operation of one workspace (both heads),
|
|
177
|
+
* or of the whole account when `workspace` is omitted, with the pins its
|
|
178
|
+
* revisions held (so the objects can be collected). The next workspace of
|
|
179
|
+
* that name starts empty. Safe to repeat; returns how many revisions went. */
|
|
180
|
+
drop(target: { tenant: string; workspace?: string }): Promise<number>;
|
|
181
|
+
/** Re-key a workspace's heads, revisions and operations (both heads) from one
|
|
182
|
+
* name to another, in one step. Whatever the new name already holds belonged
|
|
183
|
+
* to a workspace that no longer exists and is removed first. Revision ids
|
|
184
|
+
* do not change. A name with nothing under it moves nothing. */
|
|
185
|
+
move(tenant: string, from: string, to: string): Promise<void>;
|
|
186
|
+
/** Remove these revisions of one head (and the pins they held on their
|
|
187
|
+
* manifests; the objects themselves are the sweeper's). The head itself is
|
|
188
|
+
* never removed. Returns how many went. */
|
|
189
|
+
prune(ws: WorkspaceRef, ids: readonly string[]): Promise<number>;
|
|
190
|
+
|
|
191
|
+
// What the sweeper and the orphan cleanup ask (blob-sweeper.ts).
|
|
192
|
+
|
|
193
|
+
/** Every manifest id a revision of this account names (both heads, all
|
|
194
|
+
* workspaces), or only those of revisions made at or after `since` (the
|
|
195
|
+
* sweeper's last look before a delete: what a publish committed meanwhile). */
|
|
196
|
+
manifestIds(tenant: string, opts?: { since?: Date }): Promise<string[]>;
|
|
197
|
+
/** Does the store hold any revision at all? A sweeper that finds none, with
|
|
198
|
+
* objects in the bucket, suspects a wiped database and refuses. */
|
|
199
|
+
anyRevisions(): Promise<boolean>;
|
|
200
|
+
/** Every workspace that has a head or a revision, any account. */
|
|
201
|
+
workspaces(): Promise<{ tenant: string; workspace: string }[]>;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const OP_ID = /^[A-Za-z0-9._:@=+-]{8,200}$/;
|
|
205
|
+
export function assertOpId(opId: string): string {
|
|
206
|
+
if (!OP_ID.test(opId)) throw new Error("an operation id is 8–200 characters of letters, digits and . _ : @ = + -");
|
|
207
|
+
return opId;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function newRevisionId(): string {
|
|
211
|
+
return `rev_${crypto.randomBytes(12).toString("hex")}`;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ---------- local ----------
|
|
215
|
+
//
|
|
216
|
+
// Layout, under <root>/<tenant>/<workspace>/ :
|
|
217
|
+
//
|
|
218
|
+
// revs/<seq, 10 digits>.json one revision each, created EXCLUSIVELY
|
|
219
|
+
// (link of a finished temp file): the create
|
|
220
|
+
// is the compare-and-set — two writers
|
|
221
|
+
// racing for seq N, one gets EEXIST.
|
|
222
|
+
// ops/<sha256(opId)>.json { opId, seq } — written BEFORE the revision.
|
|
223
|
+
// A crash between the two leaves a pointer to
|
|
224
|
+
// a revision that does not exist; it is
|
|
225
|
+
// checked on read and then overwritten.
|
|
226
|
+
// files.json the storage/ index, replaced atomically
|
|
227
|
+
//
|
|
228
|
+
// The head is the highest seq in revs/. There is no separate head file to get
|
|
229
|
+
// out of step with the history. A directory listing per call is fine for one
|
|
230
|
+
// host; the pg implementation is the one built for scale.
|
|
231
|
+
//
|
|
232
|
+
// Everything runs inside withFileLock (cross-process, fenced, renewed), so two
|
|
233
|
+
// processes on one host serialise; the exclusive create is the second line of
|
|
234
|
+
// defence if the lock is ever taken over.
|
|
235
|
+
|
|
236
|
+
export function localRevisionStore(root: string = path.join(dataRoot(), ".revisions")): RevisionStore {
|
|
237
|
+
const dirOf = (ws: WorkspaceRef) => {
|
|
238
|
+
assertSafeName(ws.tenant, "tenant");
|
|
239
|
+
assertSafeName(ws.workspace, "workspace");
|
|
240
|
+
// The state head is a separate history in a subfolder of its own; the
|
|
241
|
+
// workspace head's folder never lists it (seqs reads revs/ only).
|
|
242
|
+
return scopeOf(ws) === "state" ? path.join(root, ws.tenant, ws.workspace, "state-head") : path.join(root, ws.tenant, ws.workspace);
|
|
243
|
+
};
|
|
244
|
+
const lockOf = (ws: WorkspaceRef) => path.join(root, ws.tenant, `.${ws.workspace}${scopeOf(ws) === "state" ? ".state" : ""}.lock`);
|
|
245
|
+
const seqName = (n: number) => `${String(n).padStart(10, "0")}.json`;
|
|
246
|
+
const opFile = (ws: WorkspaceRef, opId: string) =>
|
|
247
|
+
path.join(dirOf(ws), "ops", `${crypto.createHash("sha256").update(opId).digest("hex")}.json`);
|
|
248
|
+
|
|
249
|
+
const readJson = <T>(file: string): T | null => {
|
|
250
|
+
try {
|
|
251
|
+
return JSON.parse(fs.readFileSync(file, "utf8")) as T;
|
|
252
|
+
} catch {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
const writeAtomic = (file: string, data: unknown) => {
|
|
257
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
258
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
259
|
+
fs.writeFileSync(tmp, JSON.stringify(data));
|
|
260
|
+
fs.renameSync(tmp, file);
|
|
261
|
+
};
|
|
262
|
+
const seqs = (ws: WorkspaceRef): number[] => {
|
|
263
|
+
try {
|
|
264
|
+
return fs
|
|
265
|
+
.readdirSync(path.join(dirOf(ws), "revs"))
|
|
266
|
+
.filter((n) => /^\d{10}\.json$/.test(n))
|
|
267
|
+
.map((n) => Number(n.slice(0, 10)))
|
|
268
|
+
.sort((a, b) => a - b);
|
|
269
|
+
} catch {
|
|
270
|
+
return [];
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
const bySeq = (ws: WorkspaceRef, seq: number) => readJson<Revision>(path.join(dirOf(ws), "revs", seqName(seq)));
|
|
274
|
+
const headOf = (ws: WorkspaceRef) => {
|
|
275
|
+
const all = seqs(ws);
|
|
276
|
+
return all.length ? bySeq(ws, all[all.length - 1]) : null;
|
|
277
|
+
};
|
|
278
|
+
type OpFile = { opId: string; digest: string; outcome: "committed" | "unchanged"; seq: number | null; headId: string | null };
|
|
279
|
+
const operationOf = (ws: WorkspaceRef, opId: string): OperationRecord | null => {
|
|
280
|
+
const op = readJson<OpFile>(opFile(ws, opId));
|
|
281
|
+
if (!op || op.opId !== opId) return null;
|
|
282
|
+
if (op.outcome === "unchanged") {
|
|
283
|
+
const head = op.seq ? bySeq(ws, op.seq) : null;
|
|
284
|
+
return { opId, digest: op.digest, outcome: "unchanged", revision: head };
|
|
285
|
+
}
|
|
286
|
+
const rev = op.seq ? bySeq(ws, op.seq) : null;
|
|
287
|
+
// A pointer whose revision never landed (a crash between the two writes)
|
|
288
|
+
// is not an operation.
|
|
289
|
+
return rev && rev.opId === opId ? { opId, digest: op.digest, outcome: "committed", revision: rev } : null;
|
|
290
|
+
};
|
|
291
|
+
const locked = <T>(ws: WorkspaceRef, fn: () => Promise<T>) => withFileLock(lockOf(ws), fn);
|
|
292
|
+
|
|
293
|
+
return {
|
|
294
|
+
kind: "local",
|
|
295
|
+
async head(ws) {
|
|
296
|
+
return headOf(ws);
|
|
297
|
+
},
|
|
298
|
+
async revision(ws, id) {
|
|
299
|
+
for (const seq of seqs(ws).reverse()) {
|
|
300
|
+
const r = bySeq(ws, seq);
|
|
301
|
+
if (r?.id === id) return r;
|
|
302
|
+
}
|
|
303
|
+
return null;
|
|
304
|
+
},
|
|
305
|
+
async revisions(ws, opts = {}) {
|
|
306
|
+
const limit = Math.min(Math.max(opts.limit ?? 50, 1), 500);
|
|
307
|
+
const out: Revision[] = [];
|
|
308
|
+
for (const seq of seqs(ws).reverse()) {
|
|
309
|
+
if (opts.before !== undefined && seq >= opts.before) continue;
|
|
310
|
+
const r = bySeq(ws, seq);
|
|
311
|
+
if (r) out.push(r);
|
|
312
|
+
if (out.length >= limit) break;
|
|
313
|
+
}
|
|
314
|
+
return out;
|
|
315
|
+
},
|
|
316
|
+
async operation(ws, opId) {
|
|
317
|
+
assertOpId(opId);
|
|
318
|
+
return operationOf(ws, opId);
|
|
319
|
+
},
|
|
320
|
+
async recordNoop(ws, opId, digest) {
|
|
321
|
+
assertOpId(opId);
|
|
322
|
+
return locked(ws, async () => {
|
|
323
|
+
const done = operationOf(ws, opId);
|
|
324
|
+
if (done) {
|
|
325
|
+
if (done.digest !== digest) throw new OpIdReused(opId);
|
|
326
|
+
return done;
|
|
327
|
+
}
|
|
328
|
+
const head = headOf(ws);
|
|
329
|
+
writeAtomic(opFile(ws, opId), { opId, digest, outcome: "unchanged", seq: head?.seq ?? null, headId: head?.id ?? null } satisfies OpFile);
|
|
330
|
+
return { opId, digest, outcome: "unchanged", revision: head } satisfies OperationRecord;
|
|
331
|
+
});
|
|
332
|
+
},
|
|
333
|
+
async commit(ws, input) {
|
|
334
|
+
assertOpId(input.opId);
|
|
335
|
+
return locked(ws, async () => {
|
|
336
|
+
if (input.guard && !(await input.guard())) return { status: "gone" };
|
|
337
|
+
const done = operationOf(ws, input.opId);
|
|
338
|
+
if (done) {
|
|
339
|
+
if (done.digest !== input.digest) throw new OpIdReused(input.opId);
|
|
340
|
+
if (done.revision && done.outcome === "committed") return { status: "duplicate", revision: done.revision };
|
|
341
|
+
throw new OpIdReused(input.opId); // it finished as "unchanged"; a commit is a different outcome
|
|
342
|
+
}
|
|
343
|
+
const head = headOf(ws);
|
|
344
|
+
if ((head?.id ?? null) !== input.base) return { status: "stale", head };
|
|
345
|
+
const seq = (head?.seq ?? 0) + 1;
|
|
346
|
+
const revision: Revision = {
|
|
347
|
+
id: newRevisionId(),
|
|
348
|
+
scope: scopeOf(ws),
|
|
349
|
+
seq,
|
|
350
|
+
parent: head?.id ?? null,
|
|
351
|
+
authored: input.authored,
|
|
352
|
+
state: input.state,
|
|
353
|
+
by: input.by,
|
|
354
|
+
message: input.message,
|
|
355
|
+
at: new Date().toISOString(),
|
|
356
|
+
opId: input.opId,
|
|
357
|
+
...(input.restoredFrom ? { restoredFrom: input.restoredFrom } : {}),
|
|
358
|
+
...(input.conflicts?.length ? { conflicts: input.conflicts } : {}),
|
|
359
|
+
};
|
|
360
|
+
// Op pointer first, then the revision: see the layout note.
|
|
361
|
+
writeAtomic(opFile(ws, input.opId), { opId: input.opId, digest: input.digest, outcome: "committed", seq, headId: null } satisfies OpFile);
|
|
362
|
+
const target = path.join(dirOf(ws), "revs", seqName(seq));
|
|
363
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
364
|
+
const tmp = `${target}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
365
|
+
fs.writeFileSync(tmp, JSON.stringify(revision));
|
|
366
|
+
try {
|
|
367
|
+
fs.linkSync(tmp, target); // EEXIST = someone else took this seq: stale
|
|
368
|
+
} catch (err) {
|
|
369
|
+
if ((err as NodeJS.ErrnoException).code === "EEXIST") return { status: "stale", head: headOf(ws) };
|
|
370
|
+
throw err;
|
|
371
|
+
} finally {
|
|
372
|
+
fs.rmSync(tmp, { force: true });
|
|
373
|
+
}
|
|
374
|
+
return { status: "committed", revision };
|
|
375
|
+
});
|
|
376
|
+
},
|
|
377
|
+
async files(ws) {
|
|
378
|
+
return readJson<IndexedFile[]>(path.join(dirOf(ws), "files.json")) ?? [];
|
|
379
|
+
},
|
|
380
|
+
async putFile(ws, file, expectSha) {
|
|
381
|
+
assertFilePath(file.path);
|
|
382
|
+
return locked(ws, async () => {
|
|
383
|
+
const all = readJson<IndexedFile[]>(path.join(dirOf(ws), "files.json")) ?? [];
|
|
384
|
+
const was = all.find((f) => f.path === file.path);
|
|
385
|
+
if (expectSha !== undefined && (was?.sha ?? null) !== expectSha) return false;
|
|
386
|
+
writeAtomic(path.join(dirOf(ws), "files.json"), [...all.filter((f) => f.path !== file.path), file]);
|
|
387
|
+
return true;
|
|
388
|
+
});
|
|
389
|
+
},
|
|
390
|
+
async deleteFile(ws, rel, expectSha) {
|
|
391
|
+
return locked(ws, async () => {
|
|
392
|
+
const all = readJson<IndexedFile[]>(path.join(dirOf(ws), "files.json")) ?? [];
|
|
393
|
+
const was = all.find((f) => f.path === rel);
|
|
394
|
+
if (!was) return false;
|
|
395
|
+
if (expectSha !== undefined && was.sha !== expectSha) return false;
|
|
396
|
+
writeAtomic(path.join(dirOf(ws), "files.json"), all.filter((f) => f.path !== rel));
|
|
397
|
+
return true;
|
|
398
|
+
});
|
|
399
|
+
},
|
|
400
|
+
async drop(target) {
|
|
401
|
+
assertSafeName(target.tenant, "tenant");
|
|
402
|
+
if (target.workspace === undefined) {
|
|
403
|
+
const dir = path.join(root, target.tenant);
|
|
404
|
+
const n = countRevs(dir);
|
|
405
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
406
|
+
return n;
|
|
407
|
+
}
|
|
408
|
+
const ws = { tenant: target.tenant, workspace: target.workspace };
|
|
409
|
+
return locked(ws, () => locked({ ...ws, scope: "state" }, async () => {
|
|
410
|
+
const n = seqs(ws).length + seqs({ ...ws, scope: "state" }).length;
|
|
411
|
+
fs.rmSync(dirOf(ws), { recursive: true, force: true }); // the state head's folder is inside it
|
|
412
|
+
return n;
|
|
413
|
+
}));
|
|
414
|
+
},
|
|
415
|
+
async move(tenant, from, to) {
|
|
416
|
+
const a = { tenant, workspace: from };
|
|
417
|
+
const b = { tenant, workspace: to };
|
|
418
|
+
// Both names, in a fixed order, so two crossing renames cannot wait on each other.
|
|
419
|
+
const [first, second] = from < to ? [a, b] : [b, a];
|
|
420
|
+
return locked(first, () => locked(second, async () => {
|
|
421
|
+
const src = dirOf(a);
|
|
422
|
+
const dest = dirOf(b);
|
|
423
|
+
fs.rmSync(dest, { recursive: true, force: true }); // stale: that name has no workspace
|
|
424
|
+
if (fs.existsSync(src)) fs.renameSync(src, dest);
|
|
425
|
+
}));
|
|
426
|
+
},
|
|
427
|
+
async manifestIds(tenant, opts = {}) {
|
|
428
|
+
assertSafeName(tenant, "tenant");
|
|
429
|
+
const out = new Set<string>();
|
|
430
|
+
const since = opts.since?.getTime() ?? -Infinity;
|
|
431
|
+
eachRevision(root, tenant, (_t, _w, r) => {
|
|
432
|
+
if (Date.parse(r.at) < since) return;
|
|
433
|
+
out.add(r.authored);
|
|
434
|
+
out.add(r.state);
|
|
435
|
+
});
|
|
436
|
+
return [...out];
|
|
437
|
+
},
|
|
438
|
+
async anyRevisions() {
|
|
439
|
+
let any = false;
|
|
440
|
+
eachRevision(root, null, () => (any = true));
|
|
441
|
+
return any;
|
|
442
|
+
},
|
|
443
|
+
async workspaces() {
|
|
444
|
+
const out = new Map<string, { tenant: string; workspace: string }>();
|
|
445
|
+
eachRevision(root, null, (tenant, workspace) => out.set(`${tenant}\0${workspace}`, { tenant, workspace }));
|
|
446
|
+
return [...out.values()];
|
|
447
|
+
},
|
|
448
|
+
async prune(ws, ids) {
|
|
449
|
+
if (!ids.length) return 0;
|
|
450
|
+
return locked(ws, async () => {
|
|
451
|
+
const head = headOf(ws);
|
|
452
|
+
const want = new Set(ids);
|
|
453
|
+
let n = 0;
|
|
454
|
+
for (const seq of seqs(ws)) {
|
|
455
|
+
const r = bySeq(ws, seq);
|
|
456
|
+
if (!r || !want.has(r.id) || r.id === head?.id) continue;
|
|
457
|
+
fs.rmSync(path.join(dirOf(ws), "revs", seqName(seq)), { force: true });
|
|
458
|
+
n++;
|
|
459
|
+
}
|
|
460
|
+
return n;
|
|
461
|
+
});
|
|
462
|
+
},
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function eachRevision(root: string, tenant: string | null, fn: (tenant: string, workspace: string, rev: Revision) => void): void {
|
|
467
|
+
const tenants = tenant ? [tenant] : safeDirs(root);
|
|
468
|
+
for (const t of tenants) {
|
|
469
|
+
for (const w of safeDirs(path.join(root, t))) {
|
|
470
|
+
for (const d of [path.join(root, t, w, "revs"), path.join(root, t, w, "state-head", "revs")]) {
|
|
471
|
+
let names: string[] = [];
|
|
472
|
+
try {
|
|
473
|
+
names = fs.readdirSync(d).filter((x) => /^\d{10}\.json$/.test(x));
|
|
474
|
+
} catch {
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
for (const n of names) {
|
|
478
|
+
try {
|
|
479
|
+
fn(t, w, JSON.parse(fs.readFileSync(path.join(d, n), "utf8")) as Revision);
|
|
480
|
+
} catch {
|
|
481
|
+
// torn: not a revision
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
function safeDirs(dir: string): string[] {
|
|
489
|
+
try {
|
|
490
|
+
return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
|
|
491
|
+
} catch {
|
|
492
|
+
return [];
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function countRevs(dir: string): number {
|
|
497
|
+
let n = 0;
|
|
498
|
+
try {
|
|
499
|
+
for (const w of fs.readdirSync(dir)) {
|
|
500
|
+
if (w.startsWith(".")) continue;
|
|
501
|
+
for (const d of [path.join(dir, w, "revs"), path.join(dir, w, "state-head", "revs")]) {
|
|
502
|
+
try {
|
|
503
|
+
n += fs.readdirSync(d).filter((x) => /^\d{10}\.json$/.test(x)).length;
|
|
504
|
+
} catch {
|
|
505
|
+
// none
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
} catch {
|
|
510
|
+
// none
|
|
511
|
+
}
|
|
512
|
+
return n;
|
|
513
|
+
}
|
package/src/run-container.ts
CHANGED
|
@@ -30,6 +30,7 @@ import { spawn, spawnSync } from "node:child_process";
|
|
|
30
30
|
import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
|
|
31
31
|
import { CAPTURE_CAP, isPlatformPath, type ApiSpec, type Effort, type ModelCall } from "./store.ts";
|
|
32
32
|
import { divertedSummary, isDivertedPath, overlayTestWrites } from "./test-mode.ts";
|
|
33
|
+
import { recordStepOutputs, pinRunBase, type RunBase, type StepWrite } from "./workspace-revisions.ts";
|
|
33
34
|
import { refusedBack, refusedLine, keptLine, type RefusedPath } from "./copy-back.ts";
|
|
34
35
|
import type { CallIo, EventExtra, ExecUsage } from "./step-exec.ts";
|
|
35
36
|
import type { TokenPrice } from "./catalog.ts";
|
|
@@ -369,6 +370,36 @@ export function readHandedIn(workspaceRoot: string, runId: string, ref: string):
|
|
|
369
370
|
export function dropHandedIn(workspaceRoot: string, runId: string, ref: string): void {
|
|
370
371
|
const file = handedInPath(workspaceRoot, runId, ref);
|
|
371
372
|
if (file) fs.rmSync(file, { force: true });
|
|
373
|
+
const base = baseRevisionPath(workspaceRoot, runId, ref);
|
|
374
|
+
if (base) fs.rmSync(base, { force: true });
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* The revisions a step's stage-in started from (FOL-126 fixes), kept on the host
|
|
379
|
+
* beside what it was handed, for the same reason: a driver that inherits the
|
|
380
|
+
* step publishes its copy-back against the SAME base, not against whatever the
|
|
381
|
+
* heads hold by then. Platform-owned, never staged, erased with the run.
|
|
382
|
+
*/
|
|
383
|
+
export function baseRevisionPath(workspaceRoot: string, runId: string, ref: string): string | null {
|
|
384
|
+
const file = handedInPath(workspaceRoot, runId, ref);
|
|
385
|
+
return file ? file.replace(/\.json$/, ".base.json") : null;
|
|
386
|
+
}
|
|
387
|
+
export function writeBaseRevision(workspaceRoot: string, runId: string, ref: string, base: RunBase): void {
|
|
388
|
+
const file = baseRevisionPath(workspaceRoot, runId, ref);
|
|
389
|
+
if (!file) return;
|
|
390
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
391
|
+
fs.writeFileSync(file, JSON.stringify(base));
|
|
392
|
+
}
|
|
393
|
+
export function readBaseRevision(workspaceRoot: string, runId: string, ref: string): RunBase | undefined {
|
|
394
|
+
const file = baseRevisionPath(workspaceRoot, runId, ref);
|
|
395
|
+
if (!file) return undefined;
|
|
396
|
+
try {
|
|
397
|
+
const m = JSON.parse(fs.readFileSync(file, "utf8")) as Partial<RunBase>;
|
|
398
|
+
const ok = (v: unknown) => v === null || typeof v === "string";
|
|
399
|
+
return m && ok(m.workspace) && ok(m.state) ? { workspace: m.workspace ?? null, state: m.state ?? null } : undefined;
|
|
400
|
+
} catch {
|
|
401
|
+
return undefined;
|
|
402
|
+
}
|
|
372
403
|
}
|
|
373
404
|
|
|
374
405
|
/**
|
|
@@ -463,6 +494,11 @@ export interface ApplyOptions {
|
|
|
463
494
|
* changed come back, each told to onKept instead of refused. */
|
|
464
495
|
allowConfig?: boolean;
|
|
465
496
|
onKept?: (kept: RefusedPath) => void;
|
|
497
|
+
/** Where the writes are recorded as a revision (FOL-126 phase 4): the
|
|
498
|
+
* account and the run/step the copy-back belongs to. The workspace is the
|
|
499
|
+
* folder's name. Without it the folder is written and nothing is recorded
|
|
500
|
+
* (a laptop, a scratch dir). */
|
|
501
|
+
revision?: { tenant: string; runId?: string; step?: string | number; base?: RunBase | null };
|
|
466
502
|
}
|
|
467
503
|
|
|
468
504
|
export function applyContainerChanges(
|
|
@@ -474,6 +510,7 @@ export function applyContainerChanges(
|
|
|
474
510
|
opts: ApplyOptions = {},
|
|
475
511
|
): string[] {
|
|
476
512
|
const applied: string[] = [];
|
|
513
|
+
const written: StepWrite[] = [];
|
|
477
514
|
// Files a sandbox: own job's reply copied into this sandbox mid-step
|
|
478
515
|
// (delegate-tools.ts copyBackFiles), path → sha256 of what was written: for
|
|
479
516
|
// those, that is what the step started from. The job's change is already on
|
|
@@ -556,10 +593,16 @@ export function applyContainerChanges(
|
|
|
556
593
|
// other run's ledger rows on 2026-09-14. Merge appends; keep both
|
|
557
594
|
// sides of anything else.
|
|
558
595
|
const hostMoved = was !== undefined && hostNow !== null && !same(hostNow);
|
|
596
|
+
// What the step was handed, as a sha (null: no such file; undefined: not
|
|
597
|
+
// known). It is the base the head is held to — unless the folder was
|
|
598
|
+
// merged, which already folded the other writer's change in.
|
|
599
|
+
const handed: string | null | undefined = was === undefined ? undefined : was === null ? null : typeof was === "string" ? was : sha(was);
|
|
600
|
+
let foldedIn = false;
|
|
559
601
|
if (hostMoved) {
|
|
560
602
|
const merged = mergeAppends(was ?? null, hostNow, next);
|
|
561
603
|
if (merged) {
|
|
562
604
|
next = merged;
|
|
605
|
+
foldedIn = true;
|
|
563
606
|
} else {
|
|
564
607
|
const ext = path.extname(rel);
|
|
565
608
|
const stem = rel.slice(0, rel.length - ext.length);
|
|
@@ -568,6 +611,7 @@ export function applyContainerChanges(
|
|
|
568
611
|
fs.mkdirSync(path.dirname(conflictAbs), { recursive: true });
|
|
569
612
|
fs.writeFileSync(conflictAbs, next);
|
|
570
613
|
applied.push(conflictRel);
|
|
614
|
+
written.push({ path: conflictRel.replaceAll("\\", "/"), base: null, after: next });
|
|
571
615
|
note?.(
|
|
572
616
|
`write-back conflict on ${rel.replaceAll("\\", "/")}: it changed on the workspace while this step ran, ` +
|
|
573
617
|
`and not only by appending — kept the workspace's version; this step's version is ${conflictRel.replaceAll("\\", "/")}`,
|
|
@@ -590,9 +634,21 @@ export function applyContainerChanges(
|
|
|
590
634
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
591
635
|
fs.writeFileSync(target, next);
|
|
592
636
|
applied.push(rel);
|
|
637
|
+
// The pinned base is what the folder held before this write (null: a new
|
|
638
|
+
// file) — for an untouched path that is what the step was handed.
|
|
639
|
+
written.push({ path: rel.replaceAll("\\", "/"), base: hostNow ? sha(hostNow) : null, after: next, handed: foldedIn ? undefined : handed });
|
|
593
640
|
}
|
|
594
641
|
};
|
|
595
642
|
walk(containerWs);
|
|
643
|
+
// The step's outputs as one revision (all its paths, or none). Never allowed
|
|
644
|
+
// to fail the copy-back: the folder is written already.
|
|
645
|
+
if (opts.revision && written.length) {
|
|
646
|
+
try {
|
|
647
|
+
recordStepOutputs(opts.revision.tenant, path.basename(hostWs), written, { runId: opts.revision.runId, step: opts.revision.step, base: opts.revision.base });
|
|
648
|
+
} catch (err) {
|
|
649
|
+
note?.(`the step's files were written to the workspace but not recorded as a revision yet: ${err instanceof Error ? err.message : String(err)}`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
596
652
|
return applied;
|
|
597
653
|
}
|
|
598
654
|
|
|
@@ -2065,7 +2121,11 @@ export async function runStepInContainer(args: RunInContainerArgs): Promise<Cont
|
|
|
2065
2121
|
|
|
2066
2122
|
const staging = fs.mkdtempSync(path.join(os.tmpdir(), "foldrun-run-"));
|
|
2067
2123
|
let containerId = "";
|
|
2124
|
+
// The revisions this step starts from (FOL-126 fixes): taken before the
|
|
2125
|
+
// folder is copied, held until the copy-back is done.
|
|
2126
|
+
let pinned: Awaited<ReturnType<typeof pinRunBase>> = null;
|
|
2068
2127
|
try {
|
|
2128
|
+
pinned = args.tenant ? await pinRunBase(args.tenant, path.basename(args.workspaceRoot), `${args.runId ?? "step"}:${crypto.randomBytes(4).toString("hex")}`) : null;
|
|
2069
2129
|
// Stage the workspace copy minus what the platform owns — the vault,
|
|
2070
2130
|
// hook state, run history. The container gets the trust boundary, not
|
|
2071
2131
|
// the bookkeeping. One definition of "platform-owned" for this filter,
|
|
@@ -2249,6 +2309,7 @@ export async function runStepInContainer(args: RunInContainerArgs): Promise<Cont
|
|
|
2249
2309
|
onRefused: (r) => refused.push(r),
|
|
2250
2310
|
allowConfig: args.configWrites === true,
|
|
2251
2311
|
onKept: (r) => kept.push(r),
|
|
2312
|
+
revision: args.tenant ? { tenant: args.tenant, runId: args.runId, step: containerId, base: pinned?.base ?? null } : undefined,
|
|
2252
2313
|
});
|
|
2253
2314
|
if (refused.length) args.emit("info", refusedLine(refused));
|
|
2254
2315
|
if (kept.length) args.emit("info", keptLine(kept));
|
|
@@ -2270,5 +2331,6 @@ export async function runStepInContainer(args: RunInContainerArgs): Promise<Cont
|
|
|
2270
2331
|
} finally {
|
|
2271
2332
|
if (containerId) spawnSync(cli(), ["rm", "-f", containerId], { stdio: "ignore" });
|
|
2272
2333
|
fs.rmSync(staging, { recursive: true, force: true });
|
|
2334
|
+
await pinned?.release();
|
|
2273
2335
|
}
|
|
2274
2336
|
}
|