@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,239 @@
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
+ import crypto from "node:crypto";
33
+ export const MODE_FILE = 0o644;
34
+ export const MODE_EXEC = 0o755;
35
+ // ---------- which top-level names are what ----------
36
+ //
37
+ // The two manifests split a workspace by lifetime, not by file type:
38
+ //
39
+ // authored what a person (or a deploy, or the assistant) wrote on purpose.
40
+ // Reviewed, diffed, restored. Everything in WORKSPACE_DIRS except
41
+ // state/, plus the two root files.
42
+ // state what runs accumulate: state/. Checkpointed per step, restorable
43
+ // separately and only on request (restoring source must not
44
+ // rewind a week of an agent's memory-of-work).
45
+ //
46
+ // Everything else a workspace directory holds is somebody else's record and is
47
+ // refused here on purpose, because it already has an owner:
48
+ //
49
+ // storage/ its own file index (uploads; FileRecord, not a manifest)
50
+ // runs/ run records and outputs (Postgres + S3 in phase 2/5)
51
+ // secrets the vault (phase 6), outside every manifest and every restore
52
+ // once/, trigger-log.jsonl, hook-deliveries.jsonl, history* records
53
+ // .git, node_modules, .venv never workspace content
54
+ //
55
+ // A path that is in none of these lists is refused rather than guessed at: a
56
+ // new top-level folder is a decision (add it here and say which side it is
57
+ // on), not an accident that silently starts being versioned.
58
+ // FROZEN for manifest v1. These are literals, not derived from WORKSPACE_DIRS:
59
+ // a manifest already written must keep meaning what it meant, so adding a
60
+ // folder to store.ts later must not silently change which old paths are valid.
61
+ // tests/manifest.test.ts compares this list with WORKSPACE_DIRS and fails when
62
+ // they differ — the failure is the prompt to decide which side the new folder
63
+ // is on, and whether that needs manifest v2.
64
+ export const AUTHORED_DIRS = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks"];
65
+ export const STATE_DIRS = ["state"];
66
+ export const AUTHORED_ROOT_FILES = ["AGENTS.md", "project.md"];
67
+ /** A conflict copy of a root file (conflictPath) is a root file too. */
68
+ const ROOT_CONFLICT = /^(AGENTS|project)\.conflict-[0-9a-f]{12}(-\d+)?\.md$/;
69
+ /** Which manifest a path belongs in, or null when it belongs in neither. */
70
+ export function sideOf(rel) {
71
+ if (AUTHORED_ROOT_FILES.includes(rel) || ROOT_CONFLICT.test(rel))
72
+ return "authored";
73
+ const top = rel.split("/")[0];
74
+ if (rel.includes("/") && AUTHORED_DIRS.includes(top))
75
+ return "authored";
76
+ if (rel.includes("/") && STATE_DIRS.includes(top))
77
+ return "state";
78
+ return null;
79
+ }
80
+ /**
81
+ * A manifest path: relative, forward-slashed, no empty / `.` / `..` segment,
82
+ * no control characters, at most 400 characters (the same bounds as a storage
83
+ * path), and on one of the two sides. Throws; returns the path unchanged when
84
+ * it is fine. Backslashes are REFUSED rather than converted: a manifest must
85
+ * round-trip byte for byte, and `a\b` on one machine is a different name from
86
+ * `a/b` on another.
87
+ */
88
+ export const MAX_PATH_BYTES = 400;
89
+ /** Files per manifest (authored and state each). A manifest is read and
90
+ * rewritten whole on every publish; this bounds that cost until manifests
91
+ * are sharded. 50k files is ~5 MB of canonical JSON. */
92
+ export const MAX_MANIFEST_FILES = 50_000;
93
+ export function assertManifestPath(rel) {
94
+ if (typeof rel !== "string" || !rel || Buffer.byteLength(rel) > MAX_PATH_BYTES)
95
+ throw new Error(`illegal manifest path: ${String(rel).slice(0, 80)}`);
96
+ if (rel.includes("\\") || rel.startsWith("/") || /^[a-zA-Z]:/.test(rel))
97
+ throw new Error(`illegal manifest path: ${rel}`);
98
+ if (rel.split("/").some((s) => s === "" || s === "." || s === ".."))
99
+ throw new Error(`illegal manifest path: ${rel}`);
100
+ if (/[\u0000-\u001f\u007f]/.test(rel))
101
+ throw new Error(`illegal manifest path: ${rel}`);
102
+ // NFC only: "é" typed as one character and as e + a combining accent are one
103
+ // name on a Mac and two on Linux. A manifest holds the composed form, so it
104
+ // extracts the same everywhere. (Case is handled per manifest, below.)
105
+ if (rel !== rel.normalize("NFC"))
106
+ throw new Error(`illegal manifest path (not NFC-normalised): ${rel}`);
107
+ if (sideOf(rel) === null)
108
+ throw new Error(`${rel} is not workspace content (authored: ${[...AUTHORED_DIRS, ...AUTHORED_ROOT_FILES].join(", ")}; state: state/)`);
109
+ return rel;
110
+ }
111
+ /** Two paths that differ only by case cannot both be extracted on a
112
+ * case-insensitive disk (macOS and Windows laptops, Docker Desktop volumes).
113
+ * Display casing is kept; a collision inside one manifest is refused. */
114
+ export function assertNoCaseCollisions(m) {
115
+ const seen = new Map();
116
+ for (const p of Object.keys(m.files)) {
117
+ const k = p.toLowerCase();
118
+ const was = seen.get(k);
119
+ if (was !== undefined && was !== p)
120
+ throw new Error(`${p} and ${was} differ only by case`);
121
+ seen.set(k, p);
122
+ }
123
+ if (seen.size > MAX_MANIFEST_FILES)
124
+ throw new Error(`a manifest holds at most ${MAX_MANIFEST_FILES} files`);
125
+ }
126
+ export const sha256Hex = (b) => crypto.createHash("sha256").update(b).digest("hex");
127
+ /** What "the same entry" means: bytes AND mode. A chmod +x is a change even
128
+ * though the sha is the same. Changes record this as their `base`. */
129
+ export const entryId = (e) => `${e.sha}:${e.mode.toString(8)}`;
130
+ export function assertEntry(p, e) {
131
+ if (!/^[0-9a-f]{64}$/.test(e?.sha) || !Number.isSafeInteger(e.size) || e.size < 0 || (e.mode !== MODE_FILE && e.mode !== MODE_EXEC)) {
132
+ throw new Error(`manifest entry for ${p} is malformed`);
133
+ }
134
+ }
135
+ /** Everything parseManifest would refuse, checked on a manifest we are about
136
+ * to WRITE — a revision must never point at a manifest it cannot read back. */
137
+ export function assertManifest(m) {
138
+ for (const [p, e] of Object.entries(m.files)) {
139
+ assertManifestPath(p);
140
+ assertEntry(p, e);
141
+ }
142
+ assertNoCaseCollisions(m);
143
+ }
144
+ export function emptyManifest() {
145
+ return { v: 1, files: {} };
146
+ }
147
+ /** Bytes → the mode a manifest records: executable stays executable. */
148
+ export function modeFor(executable) {
149
+ return executable ? MODE_EXEC : MODE_FILE;
150
+ }
151
+ /** Sorted keys at every level, no whitespace: one tree, one byte string, one
152
+ * id — whichever machine wrote it. */
153
+ export function canonicalManifest(m) {
154
+ const files = {};
155
+ for (const p of Object.keys(m.files).sort()) {
156
+ const e = m.files[p];
157
+ files[p] = { sha: e.sha, size: e.size, mode: e.mode };
158
+ }
159
+ return JSON.stringify({ v: 1, files });
160
+ }
161
+ export function manifestId(m) {
162
+ return sha256Hex(canonicalManifest(m));
163
+ }
164
+ /** The id of a manifest with no files. A revision on one head names this for
165
+ * the side that head does not own (the workspace head carries no state, the
166
+ * state head carries no authored files); it is never stored, loadManifest
167
+ * answers it. */
168
+ export const EMPTY_MANIFEST_ID = sha256Hex(JSON.stringify({ v: 1, files: {} }));
169
+ /** Parse and validate a manifest read from a store. A manifest that does not
170
+ * say so cleanly is a broken revision, not an empty one. */
171
+ export function parseManifest(text) {
172
+ const raw = JSON.parse(text);
173
+ if (raw?.v !== 1 || typeof raw.files !== "object" || raw.files === null || Array.isArray(raw.files)) {
174
+ throw new Error("not a manifest (v1)");
175
+ }
176
+ assertManifest(raw);
177
+ return raw;
178
+ }
179
+ // ---------- object keys ----------
180
+ //
181
+ // Tenant-first, so a bucket policy can be written per tenant, and nothing in a
182
+ // key depends on the workspace's name: renaming a workspace moves no object.
183
+ const SEG = /^[A-Za-z0-9._-]{1,128}$/;
184
+ function seg(v, what) {
185
+ if (!SEG.test(v) || v === "." || v === "..")
186
+ throw new Error(`illegal ${what} in an object key`);
187
+ return v;
188
+ }
189
+ export const blobObjectKey = (tenant, sha) => {
190
+ if (!/^[0-9a-f]{64}$/.test(sha))
191
+ throw new Error("expected a sha256");
192
+ return `t/${seg(tenant, "tenant")}/blobs/${sha}`;
193
+ };
194
+ export const manifestObjectKey = (tenant, id) => {
195
+ if (!/^[0-9a-f]{64}$/.test(id))
196
+ throw new Error("expected a manifest id");
197
+ return `t/${seg(tenant, "tenant")}/manifests/${id}.json`;
198
+ };
199
+ /** Apply changes to a manifest, ignoring `base` (the caller decided). */
200
+ export function applyChanges(m, changes) {
201
+ const files = { ...m.files };
202
+ for (const [p, c] of Object.entries(changes)) {
203
+ if (c.op === "delete")
204
+ delete files[p];
205
+ else
206
+ files[p] = { sha: c.sha, size: c.size, mode: c.mode };
207
+ }
208
+ return { v: 1, files };
209
+ }
210
+ /** The changes that turn `from` into `to`, with `from`'s shas as the bases. */
211
+ export function diffManifests(from, to) {
212
+ const out = {};
213
+ for (const [p, e] of Object.entries(to.files)) {
214
+ const was = from.files[p];
215
+ if (!was)
216
+ out[p] = { op: "put", base: null, ...e };
217
+ else if (entryId(was) !== entryId(e))
218
+ out[p] = { op: "put", base: entryId(was), ...e };
219
+ }
220
+ for (const [p, e] of Object.entries(from.files))
221
+ if (!to.files[p])
222
+ out[p] = { op: "delete", base: entryId(e) };
223
+ return out;
224
+ }
225
+ /** The copy a conflicting writer's version is kept as. Deterministic in the
226
+ * operation id — a retried publish names the same file, so a retry cannot
227
+ * leave two copies — and next to the original, like today's
228
+ * `.conflict-<stamp>` copy in applyContainerChanges. 48 bits of the op id's
229
+ * hash; `attempt` > 0 is the caller stepping aside when that name is already
230
+ * taken by something else (publish never overwrites an occupied name). */
231
+ export function conflictPath(rel, opId, attempt = 0) {
232
+ const slash = rel.lastIndexOf("/");
233
+ const dir = slash >= 0 ? rel.slice(0, slash + 1) : "";
234
+ const name = slash >= 0 ? rel.slice(slash + 1) : rel;
235
+ const dot = name.lastIndexOf(".");
236
+ const stem = dot > 0 ? name.slice(0, dot) : name;
237
+ const ext = dot > 0 ? name.slice(dot) : "";
238
+ return `${dir}${stem}.conflict-${sha256Hex(opId).slice(0, 12)}${attempt ? `-${attempt}` : ""}${ext}`;
239
+ }
@@ -41,6 +41,8 @@
41
41
  // infra's tests refuse it in any manifest.
42
42
  import fs from "node:fs";
43
43
  import os from "node:os";
44
+ import path from "node:path";
45
+ import { fileURLToPath } from "node:url";
44
46
  /** Why something failed, in one word an operator can count. Small on
45
47
  * purpose: a class is a bucket on a dashboard, not a diagnosis. */
46
48
  export const ERROR_CLASSES = [
@@ -218,6 +220,27 @@ export function errorClass(err) {
218
220
  return "platform_error";
219
221
  }
220
222
  }
223
+ /** The checkout this file runs from, found from where it is, not from what
224
+ * the folder is called: a copy under another name (the pre-push hook's
225
+ * `.prepush-foldrun-core-<sha>`, a worktree, a CI workspace) is still ours. */
226
+ const OWN_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
227
+ function ownTree(p) {
228
+ if (!p.startsWith(OWN_ROOT + path.sep))
229
+ return false;
230
+ return /^(src|server|app|lib|dist|tests|scripts|instrumentation)\//.test(p.slice(OWN_ROOT.length + 1));
231
+ }
232
+ /** A frame's file as a path: V8 writes an ES module as a file: URL, with a
233
+ * space or a non-ASCII letter percent-encoded. */
234
+ function framePath(raw) {
235
+ if (!raw.startsWith("file://"))
236
+ return raw;
237
+ try {
238
+ return fileURLToPath(raw);
239
+ }
240
+ catch {
241
+ return raw.slice(7);
242
+ }
243
+ }
221
244
  /** Is this source path the platform's own code (core, platform, web, their
222
245
  * dependencies), not something an account brought — and a file that is
223
246
  * really there? A stack is a settable string; a frame naming a file that
@@ -228,7 +251,7 @@ function ourPath(p) {
228
251
  return true;
229
252
  // A checkout (the image runs core and platform from source), the web's
230
253
  // build, or the published package (`node_modules/@foldrun/core/dist`).
231
- if (!/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p))
254
+ if (!ownTree(p) && !/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p))
232
255
  return false;
233
256
  let known = seenPaths.get(p);
234
257
  if (known === undefined) {
@@ -256,7 +279,7 @@ export function stackFrames(stack, max = 5, skip = 0) {
256
279
  const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
257
280
  if (!m)
258
281
  continue;
259
- const where = m[1].replace(/^file:\/\//, "");
282
+ const where = framePath(m[1]);
260
283
  if (!ourPath(where))
261
284
  continue;
262
285
  if (seen++ < skip)
@@ -326,7 +349,7 @@ function callsite() {
326
349
  const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
327
350
  if (!m || /\/ops-log\.(ts|js)$/.test(m[1]))
328
351
  continue;
329
- const where = m[1].replace(/^file:\/\//, "");
352
+ const where = framePath(m[1]);
330
353
  if (!ourPath(where))
331
354
  return undefined;
332
355
  const frame = `${where.split("/").pop()}:${m[2]}`;
@@ -2,6 +2,7 @@ import type { SupplyAnswer } from "./model-supply.ts";
2
2
  import type { FlowInfo, FlowStep, RunRecord } from "./store.ts";
3
3
  import type { RunInContainerArgs, ContainerStepOutcome } from "./run-container.ts";
4
4
  import type { EgressHooks } from "./egress.ts";
5
+ import type { RecordsPort } from "./records.ts";
5
6
  export type IsolatedStepRunner = (args: RunInContainerArgs) => Promise<ContainerStepOutcome>;
6
7
  /** Who this install is for. `hosted` means someone is paying the operator
7
8
  * for it — a wallet, a plan, a bill. `self-hosted` is everything else: a
@@ -248,6 +249,12 @@ export interface PlatformHooks {
248
249
  * preferences and sends what it always sent.
249
250
  */
250
251
  mailPreference(tenant: string, email: string, category: string, workspace: string | null): Promise<boolean>;
252
+ /**
253
+ * Where runs, the run index, the trigger log and the storage file index
254
+ * live (records.ts). Absent: files under the workspace, which is what a
255
+ * laptop and a self-hosted install with no database have.
256
+ */
257
+ records?: RecordsPort;
251
258
  }
252
259
  /** What handing a webhook over came to: the delivery's id (the
253
260
  * X-Foldrun-Delivery header) and its first attempt, when one was made. */
@@ -114,4 +114,5 @@ export function platformQueues() {
114
114
  /** Back to the local defaults — for tests that register and must not leak. */
115
115
  export function resetPlatform() {
116
116
  Object.assign(platform, local, { isolation: {} });
117
+ delete platform.records;
117
118
  }
@@ -0,0 +1,134 @@
1
+ import type { BlobStore } from "./blob-store.ts";
2
+ import { type BlobPins } from "./blob-pins.ts";
3
+ import { type Changes, type Manifest, type ManifestId } from "./manifest.ts";
4
+ import { type RevisionStore, type Revision, type WorkspaceRef } from "./revision-store.ts";
5
+ export interface Deps {
6
+ blobs: BlobStore;
7
+ revisions: RevisionStore;
8
+ /** Durable pins for GC. Unset = none (an install with no database has no sweeper). */
9
+ pins?: BlobPins;
10
+ /** Does this workspace exist right now? Handed to every commit as its guard
11
+ * (revision-store.ts CommitInput.guard). Unset: commits are not guarded. */
12
+ workspaceExists?: (ws: WorkspaceRef) => boolean | Promise<boolean>;
13
+ }
14
+ /** A revision (or a publish) names a blob the store does not have. Explicit,
15
+ * never an empty file: the caller decides whether this is a repair or a
16
+ * refusal. */
17
+ export declare class BlobMissing extends Error {
18
+ readonly path: string;
19
+ readonly sha: string;
20
+ constructor(path: string, sha: string);
21
+ }
22
+ export declare class PublishError extends Error {
23
+ readonly code: "too_many_replays" | "bad_change" | "gone";
24
+ constructor(message: string, code: "too_many_replays" | "bad_change" | "gone");
25
+ }
26
+ export interface PublishInput {
27
+ ws: WorkspaceRef;
28
+ /** Idempotency key for THIS logical publish; the same on every retry. */
29
+ opId: string;
30
+ by: string;
31
+ message: string;
32
+ /** Per path, as the writer saw it. */
33
+ changes: Changes;
34
+ /** The bytes behind every `put` (by sha). Called only for blobs that must be
35
+ * uploaded or re-uploaded; may read a staged file lazily. */
36
+ bytesOf: (sha: string) => Promise<Uint8Array>;
37
+ /** Replay attempts before giving up under sustained contention. Default 8. */
38
+ maxReplays?: number;
39
+ /** This publish carries a restore: the revision whose content the changes
40
+ * bring back (the workspace head only; the history shows the link). */
41
+ restoredFrom?: string;
42
+ }
43
+ export interface Conflict {
44
+ path: string;
45
+ /** Where the writer's version was kept; null when the writer deleted the
46
+ * path and the head's newer version simply stayed. */
47
+ keptAs: string | null;
48
+ }
49
+ export type PublishResult = {
50
+ status: "committed";
51
+ revision: Revision;
52
+ conflicts: Conflict[];
53
+ stateRevision?: Revision | null;
54
+ } | {
55
+ status: "duplicate";
56
+ revision: Revision;
57
+ conflicts: Conflict[];
58
+ stateRevision?: Revision | null;
59
+ }
60
+ /** The head already holds all of it; no revision was made. */
61
+ | {
62
+ status: "unchanged";
63
+ revision: Revision | null;
64
+ conflicts: Conflict[];
65
+ stateRevision?: Revision | null;
66
+ };
67
+ /** Both heads of a workspace, read together. */
68
+ export interface Heads {
69
+ workspace: Revision | null;
70
+ state: Revision | null;
71
+ }
72
+ export declare function headsOf(deps: Deps, ws: WorkspaceRef): Promise<Heads>;
73
+ /** The revision that owns a path: the state head for `state/…`, the workspace
74
+ * head for everything else. null when the path is on neither side. */
75
+ export declare function revisionFor(heads: Heads, rel: string): Revision | null;
76
+ /** The two manifests as the pair of heads defines them. */
77
+ export declare function manifestsAt(deps: Deps, tenant: string, heads: Heads): Promise<{
78
+ authored: Manifest;
79
+ state: Manifest;
80
+ }>;
81
+ export declare function loadManifest(deps: Deps, tenant: string, id: ManifestId): Promise<Manifest>;
82
+ /** The two manifests a revision names (one of them is empty: a revision lives
83
+ * on one head; see manifestsAt for the workspace as a whole). */
84
+ export declare function manifestsOf(deps: Deps, tenant: string, rev: Revision | null): Promise<{
85
+ authored: Manifest;
86
+ state: Manifest;
87
+ }>;
88
+ /** One file of a revision, as a stream. Pass the revision of the head that
89
+ * owns the path (revisionFor); a path on the other side is simply absent. */
90
+ export declare function openPath(deps: Deps, tenant: string, rev: Revision, rel: string): Promise<{
91
+ size: number;
92
+ body: ReadableStream<Uint8Array>;
93
+ } | null>;
94
+ /** Every blob a revision names, checked present. Returns the missing ones. */
95
+ export declare function missingBlobs(deps: Deps, tenant: string, rev: Revision, opts?: {
96
+ state?: boolean;
97
+ authored?: boolean;
98
+ parallel?: number;
99
+ }): Promise<{
100
+ path: string;
101
+ sha: string;
102
+ }[]>;
103
+ /** The request's identity, for the operation record. Same changes, author and
104
+ * message → same digest; the op id alone does not say "this is a retry". */
105
+ export declare function requestDigest(kind: string, parts: unknown): string;
106
+ /** Fold `changes` onto `head`'s manifests. Pure. */
107
+ export declare function fold(head: {
108
+ authored: Manifest;
109
+ state: Manifest;
110
+ }, changes: Changes, opId: string): {
111
+ authored: Manifest;
112
+ state: Manifest;
113
+ conflicts: Conflict[];
114
+ applied: Changes;
115
+ };
116
+ /** The op id of the state half of a publish/restore: derived, so a retry
117
+ * makes the same one, and kept within the op-id length limit. */
118
+ export declare function stateOpId(opId: string): string;
119
+ export declare function publish(deps: Deps, input: PublishInput): Promise<PublishResult>;
120
+ export interface RestoreInput {
121
+ ws: WorkspaceRef;
122
+ /** The workspace-head revision whose content to bring back. */
123
+ to: string;
124
+ opId: string;
125
+ by: string;
126
+ message?: string;
127
+ /** Rewind state/ too, to this state-head revision. Unset: state stays —
128
+ * restoring source must not erase what agents have accumulated. */
129
+ stateTo?: string;
130
+ maxReplays?: number;
131
+ }
132
+ /** A new revision with an old one's content. History is untouched. Refuses,
133
+ * before committing anything, when a blob the old revision names is gone. */
134
+ export declare function restore(deps: Deps, input: RestoreInput): Promise<PublishResult>;