@foldrun/core 17.3.0 → 18.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/src/approvals.js +3 -3
  2. package/dist/src/blob-cache.d.ts +58 -0
  3. package/dist/src/blob-cache.js +312 -0
  4. package/dist/src/blob-pins.d.ts +44 -0
  5. package/dist/src/blob-pins.js +61 -0
  6. package/dist/src/blob-store.d.ts +47 -0
  7. package/dist/src/blob-store.js +362 -0
  8. package/dist/src/blob-sweeper.d.ts +70 -0
  9. package/dist/src/blob-sweeper.js +282 -0
  10. package/dist/src/blob-types.d.ts +145 -0
  11. package/dist/src/blob-types.js +115 -0
  12. package/dist/src/evals.js +1 -1
  13. package/dist/src/history.d.ts +92 -9
  14. package/dist/src/history.js +168 -20
  15. package/dist/src/journal-store.d.ts +58 -0
  16. package/dist/src/journal-store.js +117 -0
  17. package/dist/src/manifest.d.ts +92 -0
  18. package/dist/src/manifest.js +239 -0
  19. package/dist/src/ops-log.js +26 -3
  20. package/dist/src/platform.d.ts +7 -0
  21. package/dist/src/platform.js +1 -0
  22. package/dist/src/publish.d.ts +134 -0
  23. package/dist/src/publish.js +434 -0
  24. package/dist/src/records.d.ts +72 -0
  25. package/dist/src/records.js +24 -0
  26. package/dist/src/revision-store.d.ts +161 -0
  27. package/dist/src/revision-store.js +378 -0
  28. package/dist/src/run-container.d.ts +20 -0
  29. package/dist/src/run-container.js +61 -0
  30. package/dist/src/runner.js +1 -1
  31. package/dist/src/s3-blob-store.d.ts +29 -0
  32. package/dist/src/s3-blob-store.js +531 -0
  33. package/dist/src/state-retention.d.ts +15 -0
  34. package/dist/src/state-retention.js +65 -0
  35. package/dist/src/storage.d.ts +29 -1
  36. package/dist/src/storage.js +331 -81
  37. package/dist/src/store.d.ts +41 -0
  38. package/dist/src/store.js +188 -5
  39. package/dist/src/trigger-log.js +17 -0
  40. package/dist/src/workspace-revisions.d.ts +269 -0
  41. package/dist/src/workspace-revisions.js +1382 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +357 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +389 -0
  47. package/src/blob-sweeper.ts +336 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +226 -19
  51. package/src/journal-store.ts +152 -0
  52. package/src/manifest.ts +274 -0
  53. package/src/ops-log.ts +25 -3
  54. package/src/platform.ts +8 -0
  55. package/src/publish.ts +520 -0
  56. package/src/records.ts +105 -0
  57. package/src/revision-store.ts +513 -0
  58. package/src/run-container.ts +62 -0
  59. package/src/runner.ts +1 -1
  60. package/src/s3-blob-store.ts +560 -0
  61. package/src/state-retention.ts +83 -0
  62. package/src/storage.ts +335 -81
  63. package/src/store.ts +178 -5
  64. package/src/trigger-log.ts +15 -0
  65. package/src/workspace-revisions.ts +1423 -0
@@ -0,0 +1,274 @@
1
+ // The manifest: what a workspace revision is made of (FOL-126, phase 1).
2
+ //
3
+ // A revision does not hold files. It points at two manifests — one for what
4
+ // people author, one for state — and a manifest maps each path to an
5
+ // immutable blob:
6
+ //
7
+ // { v: 1, files: { "agents/writer/agent.md": { sha, size, mode } } }
8
+ //
9
+ // Content-addressed twice over: a blob is named by the hash of its bytes, and
10
+ // a manifest by the hash of its canonical JSON. Equal content is the same
11
+ // object, so a re-publish of an unchanged tree uploads nothing and a restore
12
+ // is just a new pointer at old objects.
13
+ //
14
+ // What a manifest cannot say (by decision, phase 1):
15
+ // symlinks not representable. A scanner that meets one must REFUSE it
16
+ // (lstat, never follow), not store its target's bytes: following
17
+ // a link out of the workspace is how a file outside it gets
18
+ // published. (The laptop's agents/<a>/workspace link is a CLI
19
+ // thing; the hosted copy-back already skips symlinks.)
20
+ // empty folders not representable; a folder exists while it holds a file.
21
+ // rename there is no rename entry: a move is a delete plus a put, so a
22
+ // concurrent edit to the old path survives beside the new one.
23
+ // owner/times not kept.
24
+ // case two names that differ only by case cannot share a manifest;
25
+ // paths must be NFC. Both are enforced on write and on read.
26
+ // size at most MAX_MANIFEST_FILES per manifest; a manifest is read
27
+ // and rewritten whole on every publish, so very large trees
28
+ // want a sharded manifest (open, phase 3/4).
29
+ //
30
+ // Nothing here touches a disk or a network. It is the vocabulary the
31
+ // BlobStore, the RevisionStore and the publish protocol share.
32
+
33
+ import crypto from "node:crypto";
34
+
35
+ export interface ManifestEntry {
36
+ /** sha256 of the bytes, lower-case hex. The blob's name. */
37
+ sha: string;
38
+ size: number;
39
+ /** 0o644, or 0o755 when the file is executable (store.ts marks scripts so).
40
+ * Stored as the number, so JSON carries 420 or 493. Nothing else is kept:
41
+ * owner, times and extended attributes are not part of a workspace. */
42
+ mode: number;
43
+ }
44
+
45
+ export interface Manifest {
46
+ v: 1;
47
+ /** Forward-slashed paths, relative to the workspace root. */
48
+ files: Record<string, ManifestEntry>;
49
+ }
50
+
51
+ export const MODE_FILE = 0o644;
52
+ export const MODE_EXEC = 0o755;
53
+
54
+ /** A manifest id: the sha256 of its canonical JSON. */
55
+ export type ManifestId = string;
56
+
57
+ // ---------- which top-level names are what ----------
58
+ //
59
+ // The two manifests split a workspace by lifetime, not by file type:
60
+ //
61
+ // authored what a person (or a deploy, or the assistant) wrote on purpose.
62
+ // Reviewed, diffed, restored. Everything in WORKSPACE_DIRS except
63
+ // state/, plus the two root files.
64
+ // state what runs accumulate: state/. Checkpointed per step, restorable
65
+ // separately and only on request (restoring source must not
66
+ // rewind a week of an agent's memory-of-work).
67
+ //
68
+ // Everything else a workspace directory holds is somebody else's record and is
69
+ // refused here on purpose, because it already has an owner:
70
+ //
71
+ // storage/ its own file index (uploads; FileRecord, not a manifest)
72
+ // runs/ run records and outputs (Postgres + S3 in phase 2/5)
73
+ // secrets the vault (phase 6), outside every manifest and every restore
74
+ // once/, trigger-log.jsonl, hook-deliveries.jsonl, history* records
75
+ // .git, node_modules, .venv never workspace content
76
+ //
77
+ // A path that is in none of these lists is refused rather than guessed at: a
78
+ // new top-level folder is a decision (add it here and say which side it is
79
+ // on), not an accident that silently starts being versioned.
80
+
81
+ // FROZEN for manifest v1. These are literals, not derived from WORKSPACE_DIRS:
82
+ // a manifest already written must keep meaning what it meant, so adding a
83
+ // folder to store.ts later must not silently change which old paths are valid.
84
+ // tests/manifest.test.ts compares this list with WORKSPACE_DIRS and fails when
85
+ // they differ — the failure is the prompt to decide which side the new folder
86
+ // is on, and whether that needs manifest v2.
87
+ export const AUTHORED_DIRS: readonly string[] = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks"];
88
+ export const STATE_DIRS: readonly string[] = ["state"];
89
+ export const AUTHORED_ROOT_FILES: readonly string[] = ["AGENTS.md", "project.md"];
90
+ /** A conflict copy of a root file (conflictPath) is a root file too. */
91
+ const ROOT_CONFLICT = /^(AGENTS|project)\.conflict-[0-9a-f]{12}(-\d+)?\.md$/;
92
+
93
+ export type Side = "authored" | "state";
94
+
95
+ /** Which manifest a path belongs in, or null when it belongs in neither. */
96
+ export function sideOf(rel: string): Side | null {
97
+ if (AUTHORED_ROOT_FILES.includes(rel) || ROOT_CONFLICT.test(rel)) return "authored";
98
+ const top = rel.split("/")[0];
99
+ if (rel.includes("/") && AUTHORED_DIRS.includes(top)) return "authored";
100
+ if (rel.includes("/") && STATE_DIRS.includes(top)) return "state";
101
+ return null;
102
+ }
103
+
104
+ /**
105
+ * A manifest path: relative, forward-slashed, no empty / `.` / `..` segment,
106
+ * no control characters, at most 400 characters (the same bounds as a storage
107
+ * path), and on one of the two sides. Throws; returns the path unchanged when
108
+ * it is fine. Backslashes are REFUSED rather than converted: a manifest must
109
+ * round-trip byte for byte, and `a\b` on one machine is a different name from
110
+ * `a/b` on another.
111
+ */
112
+ export const MAX_PATH_BYTES = 400;
113
+ /** Files per manifest (authored and state each). A manifest is read and
114
+ * rewritten whole on every publish; this bounds that cost until manifests
115
+ * are sharded. 50k files is ~5 MB of canonical JSON. */
116
+ export const MAX_MANIFEST_FILES = 50_000;
117
+
118
+ export function assertManifestPath(rel: string): string {
119
+ if (typeof rel !== "string" || !rel || Buffer.byteLength(rel) > MAX_PATH_BYTES) throw new Error(`illegal manifest path: ${String(rel).slice(0, 80)}`);
120
+ if (rel.includes("\\") || rel.startsWith("/") || /^[a-zA-Z]:/.test(rel)) throw new Error(`illegal manifest path: ${rel}`);
121
+ if (rel.split("/").some((s) => s === "" || s === "." || s === "..")) throw new Error(`illegal manifest path: ${rel}`);
122
+ if (/[\u0000-\u001f\u007f]/.test(rel)) throw new Error(`illegal manifest path: ${rel}`);
123
+ // NFC only: "é" typed as one character and as e + a combining accent are one
124
+ // name on a Mac and two on Linux. A manifest holds the composed form, so it
125
+ // extracts the same everywhere. (Case is handled per manifest, below.)
126
+ if (rel !== rel.normalize("NFC")) throw new Error(`illegal manifest path (not NFC-normalised): ${rel}`);
127
+ if (sideOf(rel) === null) throw new Error(`${rel} is not workspace content (authored: ${[...AUTHORED_DIRS, ...AUTHORED_ROOT_FILES].join(", ")}; state: state/)`);
128
+ return rel;
129
+ }
130
+
131
+ /** Two paths that differ only by case cannot both be extracted on a
132
+ * case-insensitive disk (macOS and Windows laptops, Docker Desktop volumes).
133
+ * Display casing is kept; a collision inside one manifest is refused. */
134
+ export function assertNoCaseCollisions(m: Manifest): void {
135
+ const seen = new Map<string, string>();
136
+ for (const p of Object.keys(m.files)) {
137
+ const k = p.toLowerCase();
138
+ const was = seen.get(k);
139
+ if (was !== undefined && was !== p) throw new Error(`${p} and ${was} differ only by case`);
140
+ seen.set(k, p);
141
+ }
142
+ if (seen.size > MAX_MANIFEST_FILES) throw new Error(`a manifest holds at most ${MAX_MANIFEST_FILES} files`);
143
+ }
144
+
145
+ export const sha256Hex = (b: string | Uint8Array) => crypto.createHash("sha256").update(b).digest("hex");
146
+
147
+ /** What "the same entry" means: bytes AND mode. A chmod +x is a change even
148
+ * though the sha is the same. Changes record this as their `base`. */
149
+ export const entryId = (e: Pick<ManifestEntry, "sha" | "mode">) => `${e.sha}:${e.mode.toString(8)}`;
150
+
151
+ export function assertEntry(p: string, e: ManifestEntry): void {
152
+ if (!/^[0-9a-f]{64}$/.test(e?.sha) || !Number.isSafeInteger(e.size) || e.size < 0 || (e.mode !== MODE_FILE && e.mode !== MODE_EXEC)) {
153
+ throw new Error(`manifest entry for ${p} is malformed`);
154
+ }
155
+ }
156
+
157
+ /** Everything parseManifest would refuse, checked on a manifest we are about
158
+ * to WRITE — a revision must never point at a manifest it cannot read back. */
159
+ export function assertManifest(m: Manifest): void {
160
+ for (const [p, e] of Object.entries(m.files)) {
161
+ assertManifestPath(p);
162
+ assertEntry(p, e);
163
+ }
164
+ assertNoCaseCollisions(m);
165
+ }
166
+
167
+ export function emptyManifest(): Manifest {
168
+ return { v: 1, files: {} };
169
+ }
170
+
171
+ /** Bytes → the mode a manifest records: executable stays executable. */
172
+ export function modeFor(executable: boolean): number {
173
+ return executable ? MODE_EXEC : MODE_FILE;
174
+ }
175
+
176
+ /** Sorted keys at every level, no whitespace: one tree, one byte string, one
177
+ * id — whichever machine wrote it. */
178
+ export function canonicalManifest(m: Manifest): string {
179
+ const files: Record<string, ManifestEntry> = {};
180
+ for (const p of Object.keys(m.files).sort()) {
181
+ const e = m.files[p];
182
+ files[p] = { sha: e.sha, size: e.size, mode: e.mode };
183
+ }
184
+ return JSON.stringify({ v: 1, files });
185
+ }
186
+
187
+ export function manifestId(m: Manifest): ManifestId {
188
+ return sha256Hex(canonicalManifest(m));
189
+ }
190
+
191
+ /** The id of a manifest with no files. A revision on one head names this for
192
+ * the side that head does not own (the workspace head carries no state, the
193
+ * state head carries no authored files); it is never stored, loadManifest
194
+ * answers it. */
195
+ export const EMPTY_MANIFEST_ID: ManifestId = sha256Hex(JSON.stringify({ v: 1, files: {} }));
196
+
197
+ /** Parse and validate a manifest read from a store. A manifest that does not
198
+ * say so cleanly is a broken revision, not an empty one. */
199
+ export function parseManifest(text: string): Manifest {
200
+ const raw = JSON.parse(text) as Manifest;
201
+ if (raw?.v !== 1 || typeof raw.files !== "object" || raw.files === null || Array.isArray(raw.files)) {
202
+ throw new Error("not a manifest (v1)");
203
+ }
204
+ assertManifest(raw);
205
+ return raw;
206
+ }
207
+
208
+ // ---------- object keys ----------
209
+ //
210
+ // Tenant-first, so a bucket policy can be written per tenant, and nothing in a
211
+ // key depends on the workspace's name: renaming a workspace moves no object.
212
+
213
+ const SEG = /^[A-Za-z0-9._-]{1,128}$/;
214
+ function seg(v: string, what: string): string {
215
+ if (!SEG.test(v) || v === "." || v === "..") throw new Error(`illegal ${what} in an object key`);
216
+ return v;
217
+ }
218
+ export const blobObjectKey = (tenant: string, sha: string) => {
219
+ if (!/^[0-9a-f]{64}$/.test(sha)) throw new Error("expected a sha256");
220
+ return `t/${seg(tenant, "tenant")}/blobs/${sha}`;
221
+ };
222
+ export const manifestObjectKey = (tenant: string, id: ManifestId) => {
223
+ if (!/^[0-9a-f]{64}$/.test(id)) throw new Error("expected a manifest id");
224
+ return `t/${seg(tenant, "tenant")}/manifests/${id}.json`;
225
+ };
226
+
227
+ // ---------- change sets ----------
228
+
229
+ /** One path's change, as a writer saw it. `base` is the entryId (sha + mode)
230
+ * the writer STARTED from (null: the path did not exist) — the fact that makes "disjoint paths
231
+ * replay, the same path conflicts" decidable without a merge. */
232
+ export type PathChange =
233
+ | { op: "put"; base: string | null; sha: string; size: number; mode: number }
234
+ | { op: "delete"; base: string };
235
+
236
+ export type Changes = Record<string, PathChange>;
237
+
238
+ /** Apply changes to a manifest, ignoring `base` (the caller decided). */
239
+ export function applyChanges(m: Manifest, changes: Changes): Manifest {
240
+ const files = { ...m.files };
241
+ for (const [p, c] of Object.entries(changes)) {
242
+ if (c.op === "delete") delete files[p];
243
+ else files[p] = { sha: c.sha, size: c.size, mode: c.mode };
244
+ }
245
+ return { v: 1, files };
246
+ }
247
+
248
+ /** The changes that turn `from` into `to`, with `from`'s shas as the bases. */
249
+ export function diffManifests(from: Manifest, to: Manifest): Changes {
250
+ const out: Changes = {};
251
+ for (const [p, e] of Object.entries(to.files)) {
252
+ const was = from.files[p];
253
+ if (!was) out[p] = { op: "put", base: null, ...e };
254
+ else if (entryId(was) !== entryId(e)) out[p] = { op: "put", base: entryId(was), ...e };
255
+ }
256
+ for (const [p, e] of Object.entries(from.files)) if (!to.files[p]) out[p] = { op: "delete", base: entryId(e) };
257
+ return out;
258
+ }
259
+
260
+ /** The copy a conflicting writer's version is kept as. Deterministic in the
261
+ * operation id — a retried publish names the same file, so a retry cannot
262
+ * leave two copies — and next to the original, like today's
263
+ * `.conflict-<stamp>` copy in applyContainerChanges. 48 bits of the op id's
264
+ * hash; `attempt` > 0 is the caller stepping aside when that name is already
265
+ * taken by something else (publish never overwrites an occupied name). */
266
+ export function conflictPath(rel: string, opId: string, attempt = 0): string {
267
+ const slash = rel.lastIndexOf("/");
268
+ const dir = slash >= 0 ? rel.slice(0, slash + 1) : "";
269
+ const name = slash >= 0 ? rel.slice(slash + 1) : rel;
270
+ const dot = name.lastIndexOf(".");
271
+ const stem = dot > 0 ? name.slice(0, dot) : name;
272
+ const ext = dot > 0 ? name.slice(dot) : "";
273
+ return `${dir}${stem}.conflict-${sha256Hex(opId).slice(0, 12)}${attempt ? `-${attempt}` : ""}${ext}`;
274
+ }
package/src/ops-log.ts CHANGED
@@ -42,6 +42,8 @@
42
42
 
43
43
  import fs from "node:fs";
44
44
  import os from "node:os";
45
+ import path from "node:path";
46
+ import { fileURLToPath } from "node:url";
45
47
 
46
48
  /** Why something failed, in one word an operator can count. Small on
47
49
  * purpose: a class is a bucket on a dashboard, not a diagnosis. */
@@ -225,6 +227,26 @@ export function errorClass(err: unknown): ErrorClass {
225
227
  }
226
228
  }
227
229
 
230
+ /** The checkout this file runs from, found from where it is, not from what
231
+ * the folder is called: a copy under another name (the pre-push hook's
232
+ * `.prepush-foldrun-core-<sha>`, a worktree, a CI workspace) is still ours. */
233
+ const OWN_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
234
+ function ownTree(p: string): boolean {
235
+ if (!p.startsWith(OWN_ROOT + path.sep)) return false;
236
+ return /^(src|server|app|lib|dist|tests|scripts|instrumentation)\//.test(p.slice(OWN_ROOT.length + 1));
237
+ }
238
+
239
+ /** A frame's file as a path: V8 writes an ES module as a file: URL, with a
240
+ * space or a non-ASCII letter percent-encoded. */
241
+ function framePath(raw: string): string {
242
+ if (!raw.startsWith("file://")) return raw;
243
+ try {
244
+ return fileURLToPath(raw);
245
+ } catch {
246
+ return raw.slice(7);
247
+ }
248
+ }
249
+
228
250
  /** Is this source path the platform's own code (core, platform, web, their
229
251
  * dependencies), not something an account brought — and a file that is
230
252
  * really there? A stack is a settable string; a frame naming a file that
@@ -234,7 +256,7 @@ function ourPath(p: string): boolean {
234
256
  if (/^node:[a-z_/]+$/.test(p)) return true;
235
257
  // A checkout (the image runs core and platform from source), the web's
236
258
  // build, or the published package (`node_modules/@foldrun/core/dist`).
237
- if (!/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p)) return false;
259
+ if (!ownTree(p) && !/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p)) return false;
238
260
  let known = seenPaths.get(p);
239
261
  if (known === undefined) {
240
262
  try {
@@ -258,7 +280,7 @@ export function stackFrames(stack: unknown, max = 5, skip = 0): string[] {
258
280
  for (const raw of stack.slice(0, 20_000).split("\n")) {
259
281
  const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
260
282
  if (!m) continue;
261
- const where = m[1].replace(/^file:\/\//, "");
283
+ const where = framePath(m[1]);
262
284
  if (!ourPath(where)) continue;
263
285
  if (seen++ < skip) continue;
264
286
  const frame = `${where.split("/").pop()}:${m[2]}`;
@@ -327,7 +349,7 @@ function callsite(): string | undefined {
327
349
  for (const raw of stack.split("\n").slice(1)) {
328
350
  const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
329
351
  if (!m || /\/ops-log\.(ts|js)$/.test(m[1])) continue;
330
- const where = m[1].replace(/^file:\/\//, "");
352
+ const where = framePath(m[1]);
331
353
  if (!ourPath(where)) return undefined;
332
354
  const frame = `${where.split("/").pop()}:${m[2]}`;
333
355
  return FRAME.test(frame) ? frame : undefined;
package/src/platform.ts CHANGED
@@ -17,6 +17,7 @@ import type { FlowInfo, FlowStep, RunRecord } from "./store.ts";
17
17
  import type { RunInContainerArgs, ContainerStepOutcome } from "./run-container.ts";
18
18
  import type { EgressHooks } from "./egress.ts";
19
19
  import { matchFilter } from "./trigger-filter.ts";
20
+ import type { RecordsPort } from "./records.ts";
20
21
 
21
22
  export type IsolatedStepRunner = (args: RunInContainerArgs) => Promise<ContainerStepOutcome>;
22
23
 
@@ -241,6 +242,12 @@ export interface PlatformHooks {
241
242
  * preferences and sends what it always sent.
242
243
  */
243
244
  mailPreference(tenant: string, email: string, category: string, workspace: string | null): Promise<boolean>;
245
+ /**
246
+ * Where runs, the run index, the trigger log and the storage file index
247
+ * live (records.ts). Absent: files under the workspace, which is what a
248
+ * laptop and a self-hosted install with no database have.
249
+ */
250
+ records?: RecordsPort;
244
251
  }
245
252
 
246
253
  /** What handing a webhook over came to: the delivery's id (the
@@ -360,4 +367,5 @@ export function platformQueues(): boolean {
360
367
  /** Back to the local defaults — for tests that register and must not leak. */
361
368
  export function resetPlatform(): void {
362
369
  Object.assign(platform, local, { isolation: {} });
370
+ delete platform.records;
363
371
  }