@foldrun/core 17.3.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 (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 +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/evals.js +1 -1
  13. package/dist/src/history.d.ts +86 -9
  14. package/dist/src/history.js +132 -16
  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 +458 -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 +259 -0
  41. package/dist/src/workspace-revisions.js +1274 -0
  42. package/package.json +1 -1
  43. package/src/approvals.ts +3 -3
  44. package/src/blob-cache.ts +354 -0
  45. package/src/blob-pins.ts +99 -0
  46. package/src/blob-store.ts +385 -0
  47. package/src/blob-sweeper.ts +308 -0
  48. package/src/blob-types.ts +216 -0
  49. package/src/evals.ts +1 -1
  50. package/src/history.ts +182 -16
  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 +489 -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 +1324 -0
@@ -0,0 +1,145 @@
1
+ export declare class BlobNotFound extends Error {
2
+ readonly key: string;
3
+ constructor(key: string);
4
+ }
5
+ /** A failure the caller may retry: the network, a timeout, a 5xx, a 429, a
6
+ * conditional-write conflict, an expired token. Everything else (403, 400,
7
+ * 404, a bad bucket name) is final. */
8
+ export declare class BlobTransientError extends Error {
9
+ readonly status?: number;
10
+ /** The store's own error code when it gave one (S3: `SlowDown`, ...). */
11
+ readonly code?: string;
12
+ constructor(message: string, status?: number, code?: string);
13
+ }
14
+ /** The store said no and will say no again: wrong credentials, no such bucket,
15
+ * a malformed request. Carries the HTTP status and the store's error code. */
16
+ export declare class BlobStoreError extends Error {
17
+ readonly status: number;
18
+ readonly code?: string;
19
+ constructor(message: string, status: number, code?: string);
20
+ }
21
+ /** The bytes being uploaded stopped matching what was announced (the file was
22
+ * truncated, rewritten, or does not hash to the name it was given). Not
23
+ * retried: reading it again would give the same answer. */
24
+ export declare class BlobSourceError extends Error {
25
+ constructor(message: string);
26
+ }
27
+ export interface PutOptions {
28
+ contentType?: string;
29
+ signal?: AbortSignal;
30
+ }
31
+ export interface PutSourceOptions extends PutOptions {
32
+ /** Hex sha256 of the whole content, when the caller has it (a blob key is
33
+ * one). It is signed into the request, so the store verifies it; without it
34
+ * the source is read once more to find it. */
35
+ sha256?: string;
36
+ }
37
+ export interface PutResult {
38
+ created: boolean;
39
+ /** The store's ETag for the object that is there, unquoted, when it said.
40
+ * For a single-request upload that is the md5 of the content on S3, R2 and
41
+ * MinIO; for a multipart upload it is `<hash>-<parts>`. */
42
+ etag?: string;
43
+ }
44
+ export interface HeadResult {
45
+ size: number;
46
+ /** When the object was last written, when the store says (whole seconds on
47
+ * S3). The garbage collector's grace period is measured from here. NOTE: a
48
+ * conditional put that finds the object already there does NOT refresh it,
49
+ * so an old blob that a new publish reuses looks old to a sweeper — the
50
+ * grace period alone does not protect it (see publish.ts, "the GC window"). */
51
+ modifiedAt?: Date;
52
+ etag?: string;
53
+ }
54
+ /**
55
+ * A re-readable source of bytes. Streaming upload needs to read the same bytes
56
+ * more than once: to hash them before they are sent, and again for every retry
57
+ * or resumed part. So it is a *range reader*, not a one-shot stream.
58
+ */
59
+ export interface BlobSource {
60
+ readonly size: number;
61
+ /** The bytes [start, end) as a stream. Throws BlobSourceError if the source
62
+ * turns out shorter than `size`. */
63
+ read(start: number, end: number, signal?: AbortSignal): AsyncIterable<Uint8Array>;
64
+ }
65
+ /**
66
+ * What every caller gets: create-only, read, ask. There is deliberately no
67
+ * overwrite and no delete here — an object is named by its content, so the only
68
+ * write that makes sense is "put it if it is not there", and removing one is
69
+ * the garbage collector's job alone (BlobSweeper, below). A missed option
70
+ * cannot corrupt a shared object because the option does not exist.
71
+ */
72
+ export interface BlobStore {
73
+ readonly kind: "fs" | "s3";
74
+ /** Write only if nothing is at the key. `created: false` means it was
75
+ * already there; for a content-addressed key that is success. The existing
76
+ * object is NOT verified against `body` — callers that need that compare the
77
+ * returned `etag` or read it back. After a retry, `created: false` can also
78
+ * mean "my first attempt landed and its answer was lost". */
79
+ putIfAbsent(key: string, body: Uint8Array, opts?: PutOptions): Promise<PutResult>;
80
+ /** The same, for content that should not be held in memory: streamed from the
81
+ * source, and — on s3, past the multipart threshold — uploaded in parts that
82
+ * survive an interruption and are picked up again by the next call. */
83
+ putSourceIfAbsent(key: string, source: BlobSource, opts?: PutSourceOptions): Promise<PutResult>;
84
+ /** The object as a stream, optionally one inclusive byte range. Throws BlobNotFound. */
85
+ get(key: string, opts?: {
86
+ range?: {
87
+ start: number;
88
+ end: number;
89
+ };
90
+ signal?: AbortSignal;
91
+ }): Promise<ReadableStream<Uint8Array>>;
92
+ head(key: string, opts?: {
93
+ signal?: AbortSignal;
94
+ }): Promise<HeadResult | null>;
95
+ }
96
+ /** Removal. Held by the garbage collector and by tests; not passed to publish. */
97
+ export interface BlobSweeper {
98
+ /** Idempotent: a missing key is the end state asked for. */
99
+ delete(key: string, opts?: {
100
+ signal?: AbortSignal;
101
+ }): Promise<void>;
102
+ /** Throw away uploads that were started and never finished (s3 multipart
103
+ * uploads; fs temp files) and are older than `olderThanMs`. Returns how many.
104
+ * A bucket lifecycle rule (AbortIncompleteMultipartUpload) does the same on
105
+ * AWS and R2; this is for stores that have none, and for tests. */
106
+ abortStaleUploads(opts: {
107
+ olderThanMs: number;
108
+ prefix?: string;
109
+ signal?: AbortSignal;
110
+ }): Promise<number>;
111
+ /** An account is gone: remove everything under its prefix. Only a store that
112
+ * can enumerate has it (the folder one); a bucket's objects are the
113
+ * sweeper's once the account's pins are released. */
114
+ purgeTenant?(tenant: string): Promise<void>;
115
+ /** Every object under a key prefix, with its size and last-modified time —
116
+ * what the sweeper walks. */
117
+ list?(prefix: string, opts?: {
118
+ signal?: AbortSignal;
119
+ }): AsyncIterable<ListedObject>;
120
+ /** The accounts that have objects (the first key segment under `t/`). */
121
+ tenants?(opts?: {
122
+ signal?: AbortSignal;
123
+ }): Promise<string[]>;
124
+ }
125
+ export interface ListedObject {
126
+ key: string;
127
+ size: number;
128
+ modifiedAt: Date;
129
+ }
130
+ /** Read a whole object. For manifests and small blobs; a large file is
131
+ * streamed with `get`. */
132
+ export declare function readAll(store: BlobStore, key: string): Promise<Buffer>;
133
+ /** A key is slash-separated safe segments. Checked in every driver, because a
134
+ * key reaches the fs driver as a path. */
135
+ export declare function assertKey(key: string): string;
136
+ export declare function bufferSource(buf: Uint8Array): BlobSource;
137
+ /** A file on disk. The size is taken now; if the file is shorter (or longer)
138
+ * when it is read, the read throws BlobSourceError rather than send a body
139
+ * that no longer matches what was announced. */
140
+ export declare function fileSource(filePath: string): BlobSource;
141
+ /** sha256 (and md5, which is what a single-request ETag is) of a range. */
142
+ export declare function hashRange(source: BlobSource, start: number, end: number, signal?: AbortSignal): Promise<{
143
+ sha256: string;
144
+ md5: string;
145
+ }>;
@@ -0,0 +1,115 @@
1
+ // The BlobStore contract and the pieces every driver shares (FOL-126).
2
+ // Split out of blob-store.ts so the s3 driver (s3-blob-store.ts) and the fs
3
+ // driver can both use the errors and the source type without importing each
4
+ // other.
5
+ import fs from "node:fs";
6
+ import crypto from "node:crypto";
7
+ export class BlobNotFound extends Error {
8
+ key;
9
+ constructor(key) {
10
+ super(`no object at ${key}`);
11
+ this.name = "BlobNotFound";
12
+ this.key = key;
13
+ }
14
+ }
15
+ /** A failure the caller may retry: the network, a timeout, a 5xx, a 429, a
16
+ * conditional-write conflict, an expired token. Everything else (403, 400,
17
+ * 404, a bad bucket name) is final. */
18
+ export class BlobTransientError extends Error {
19
+ status;
20
+ /** The store's own error code when it gave one (S3: `SlowDown`, ...). */
21
+ code;
22
+ constructor(message, status, code) {
23
+ super(message);
24
+ this.name = "BlobTransientError";
25
+ this.status = status;
26
+ this.code = code;
27
+ }
28
+ }
29
+ /** The store said no and will say no again: wrong credentials, no such bucket,
30
+ * a malformed request. Carries the HTTP status and the store's error code. */
31
+ export class BlobStoreError extends Error {
32
+ status;
33
+ code;
34
+ constructor(message, status, code) {
35
+ super(message);
36
+ this.name = "BlobStoreError";
37
+ this.status = status;
38
+ this.code = code;
39
+ }
40
+ }
41
+ /** The bytes being uploaded stopped matching what was announced (the file was
42
+ * truncated, rewritten, or does not hash to the name it was given). Not
43
+ * retried: reading it again would give the same answer. */
44
+ export class BlobSourceError extends Error {
45
+ constructor(message) {
46
+ super(message);
47
+ this.name = "BlobSourceError";
48
+ }
49
+ }
50
+ /** Read a whole object. For manifests and small blobs; a large file is
51
+ * streamed with `get`. */
52
+ export async function readAll(store, key) {
53
+ const chunks = [];
54
+ const reader = (await store.get(key)).getReader();
55
+ for (;;) {
56
+ const { done, value } = await reader.read();
57
+ if (done)
58
+ break;
59
+ chunks.push(Buffer.from(value));
60
+ }
61
+ return Buffer.concat(chunks);
62
+ }
63
+ // ---------- keys ----------
64
+ /** A key is slash-separated safe segments. Checked in every driver, because a
65
+ * key reaches the fs driver as a path. */
66
+ export function assertKey(key) {
67
+ if (!key || key.length > 600 || key.startsWith("/") || key.split("/").some((s) => !/^[A-Za-z0-9._=-]{1,200}$/.test(s) || s === "." || s === "..")) {
68
+ throw new Error(`illegal object key: ${key.slice(0, 80)}`);
69
+ }
70
+ return key;
71
+ }
72
+ // ---------- sources ----------
73
+ export function bufferSource(buf) {
74
+ return {
75
+ size: buf.byteLength,
76
+ async *read(start, end) {
77
+ const hi = Math.min(end, buf.byteLength);
78
+ // Slices of at most 1 MiB, so a consumer sees a stream either way.
79
+ for (let at = start; at < hi; at += 1 << 20)
80
+ yield buf.subarray(at, Math.min(at + (1 << 20), hi));
81
+ },
82
+ };
83
+ }
84
+ /** A file on disk. The size is taken now; if the file is shorter (or longer)
85
+ * when it is read, the read throws BlobSourceError rather than send a body
86
+ * that no longer matches what was announced. */
87
+ export function fileSource(filePath) {
88
+ const size = fs.statSync(filePath).size;
89
+ return {
90
+ size,
91
+ async *read(start, end, signal) {
92
+ const hi = Math.min(end, size);
93
+ if (hi <= start)
94
+ return;
95
+ const stream = fs.createReadStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal });
96
+ let got = 0;
97
+ for await (const chunk of stream) {
98
+ got += chunk.length;
99
+ yield chunk;
100
+ }
101
+ if (got !== hi - start)
102
+ throw new BlobSourceError(`${filePath} changed while it was being uploaded: expected ${hi - start} bytes at ${start}, read ${got}`);
103
+ },
104
+ };
105
+ }
106
+ /** sha256 (and md5, which is what a single-request ETag is) of a range. */
107
+ export async function hashRange(source, start, end, signal) {
108
+ const sha = crypto.createHash("sha256");
109
+ const md5 = crypto.createHash("md5");
110
+ for await (const chunk of source.read(start, end, signal)) {
111
+ sha.update(chunk);
112
+ md5.update(chunk);
113
+ }
114
+ return { sha256: sha.digest("hex"), md5: md5.digest("hex") };
115
+ }
package/dist/src/evals.js CHANGED
@@ -37,7 +37,7 @@ import fs from "node:fs";
37
37
  import crypto from "node:crypto";
38
38
  import path from "node:path";
39
39
  import { deployedCommit } from "./deploy.js";
40
- import { latestRevisionId } from "./history.js";
40
+ import { latestRevisionIdLocal as latestRevisionId } from "./history.js";
41
41
  import matter from "./matter.js";
42
42
  import { spawn } from "node:child_process";
43
43
  import { hostSafeEnv } from "./host-env.js";
@@ -9,6 +9,39 @@
9
9
  */
10
10
  type TreeReader = (tenant: string, scope: string) => RevisionFile[] | null;
11
11
  export declare function registerTreeReader(fn: TreeReader): void;
12
+ /** The scope's tree as the registered readers see it (text files only), or null. */
13
+ export declare function currentTree(tenant: string, scope: string): RevisionFile[] | null;
14
+ /**
15
+ * Where a committed change set is also handed (workspace-revisions.ts registers
16
+ * here: this module cannot import it, it imports the store which imports this).
17
+ * Called after the legacy record is written; never throws into the writer.
18
+ */
19
+ type Journal = (tenant: string, scope: string, files: RevisionFile[], meta: {
20
+ by: string;
21
+ message: string;
22
+ at: string;
23
+ }) => void;
24
+ export declare function registerJournal(fn: Journal | null): void;
25
+ export declare function registerWorkspaceGone(fn: ((tenant: string, workspace: string) => void) | null): void;
26
+ export declare function workspaceGone(tenant: string, workspace: string): void;
27
+ /**
28
+ * What follows a workspace through a delete or a rename (workspace-revisions.ts
29
+ * registers it): its journal and its history in the revision store. The async
30
+ * forms run the folder's own change INSIDE them (`remove`, `rename`), so that
31
+ * a store which cannot be reached stops the change before anything is removed
32
+ * or moved, and a writer racing the change is held off until it is done. The
33
+ * sync forms are for a caller that cannot wait: they do what can be done now
34
+ * and finish in the background.
35
+ */
36
+ export interface WorkspaceLifecycle {
37
+ drop(tenant: string, workspace: string, remove: () => void): Promise<void>;
38
+ move(tenant: string, from: string, to: string, rename: () => void): Promise<void>;
39
+ moved(tenant: string, from: string, to: string): void;
40
+ }
41
+ export declare function registerWorkspaceLifecycle(l: WorkspaceLifecycle | null): void;
42
+ export declare const workspaceLifecycle: () => WorkspaceLifecycle | null;
43
+ /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
44
+ export declare function workspaceMoved(tenant: string, from: string, to: string): void;
12
45
  export interface RevisionFile {
13
46
  path: string;
14
47
  /** Null when the file did not exist before. */
@@ -56,14 +89,14 @@ export declare function recordRevision(tenant: string, scope: string, files: Rev
56
89
  commit?: string | null;
57
90
  }): Revision | null;
58
91
  /** Whether a revision can be restored to: it has a snapshot. */
59
- export declare function hasSnapshot(tenant: string, scope: string, id: string): boolean;
92
+ export declare function hasSnapshotLocal(tenant: string, scope: string, id: string): boolean;
60
93
  /** The whole tree at revision `id`, or null when it has no snapshot. */
61
- export declare function snapshotAt(tenant: string, scope: string, id: string): {
94
+ export declare function snapshotAtLocal(tenant: string, scope: string, id: string): {
62
95
  path: string;
63
96
  content: string;
64
97
  }[] | null;
65
98
  /** The newest revision that can be restored to — what "now" is in history. */
66
- export declare function headRevision(tenant: string, scope: string): RevisionSummary | null;
99
+ export declare function headRevisionLocal(tenant: string, scope: string): RevisionSummary | null;
67
100
  /**
68
101
  * A scope with no snapshot yet gets one: its tree as it stands, recorded as
69
102
  * a revision of its own — where its history starts. Every workspace that
@@ -71,7 +104,7 @@ export declare function headRevision(tenant: string, scope: string): RevisionSum
71
104
  * by a path that never recorded a change. Returns the head's id, or null
72
105
  * when there is nothing to snapshot.
73
106
  */
74
- export declare function ensureBaseline(tenant: string, scope: string, by?: string): string | null;
107
+ export declare function ensureBaselineLocal(tenant: string, scope: string, by?: string): string | null;
75
108
  /**
76
109
  * The revision a restore means: an id (or the commit a deploy recorded), a
77
110
  * date (`2026-10-17`, `2026-10-17T09:00Z`) or a span back from now (`90m`,
@@ -79,25 +112,69 @@ export declare function ensureBaseline(tenant: string, scope: string, by?: strin
79
112
  * moment. Null when history holds nothing that old. Throws (status 400) on
80
113
  * something that is none of those.
81
114
  */
82
- export declare function resolveRevision(tenant: string, scope: string, to: string, now?: number): {
115
+ export declare function resolveRevisionLocal(tenant: string, scope: string, to: string, now?: number): {
83
116
  id: string;
84
117
  at: string;
85
118
  by: string;
86
119
  message: string;
87
120
  } | null;
88
121
  /** Newest first. `forPath` narrows to revisions that touched one file. */
89
- export declare function listRevisions(tenant: string, scope: string, opts?: {
122
+ export declare function listRevisionsLocal(tenant: string, scope: string, opts?: {
90
123
  forPath?: string;
91
124
  limit?: number;
92
125
  }): RevisionSummary[];
93
- export declare function readRevision(tenant: string, scope: string, id: string, forPath?: string): Revision | null;
126
+ export declare function readRevisionLocal(tenant: string, scope: string, id: string, forPath?: string): Revision | null;
94
127
  /** The files changed after revision `from` up to and including `to`, in a
95
128
  * scope — what differs between the versions two runs ran (FOL-72). Null
96
129
  * when either is unknown or `to` is not after `from`. */
97
- export declare function changedPathsBetween(tenant: string, scope: string, from: string | null, to: string | null): string[] | null;
130
+ export declare function changedPathsBetweenLocal(tenant: string, scope: string, from: string | null, to: string | null): string[] | null;
98
131
  /** The most recent revision id for a scope — what a change is attributed
99
132
  * to when nothing more specific (a deployed commit) is on record. */
100
- export declare function latestRevisionId(tenant: string, scope: string): string | null;
133
+ export declare function latestRevisionIdLocal(tenant: string, scope: string): string | null;
134
+ export interface RevisionView {
135
+ /** Newest first, or null when revisions do not serve this scope. */
136
+ list(tenant: string, scope: string, opts: {
137
+ forPath?: string;
138
+ limit?: number;
139
+ }): Promise<RevisionSummary[] | null>;
140
+ read(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null>;
141
+ snapshot(tenant: string, scope: string, id: string): Promise<{
142
+ path: string;
143
+ content: string;
144
+ }[] | null>;
145
+ }
146
+ export declare function registerRevisionView(v: RevisionView | null): void;
147
+ export declare function listRevisions(tenant: string, scope: string, opts?: {
148
+ forPath?: string;
149
+ limit?: number;
150
+ }): Promise<RevisionSummary[]>;
151
+ /** The list the history page shows: each row with whether it can be restored
152
+ * to. One listing answers both — every revision in the store is restorable;
153
+ * a local entry is when it has a snapshot — where asking per row would list
154
+ * the store once per row. */
155
+ export declare function listRevisionsRestorable(tenant: string, scope: string, opts?: {
156
+ forPath?: string;
157
+ limit?: number;
158
+ }): Promise<(RevisionSummary & {
159
+ restorable: boolean;
160
+ })[]>;
161
+ export declare function readRevision(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null>;
162
+ export declare function snapshotAt(tenant: string, scope: string, id: string): Promise<{
163
+ path: string;
164
+ content: string;
165
+ }[] | null>;
166
+ export declare function hasSnapshot(tenant: string, scope: string, id: string): Promise<boolean>;
167
+ export declare function headRevision(tenant: string, scope: string): Promise<RevisionSummary | null>;
168
+ export declare function resolveRevision(tenant: string, scope: string, to: string, now?: number): Promise<{
169
+ id: string;
170
+ at: string;
171
+ by: string;
172
+ message: string;
173
+ } | null>;
174
+ export declare function changedPathsBetween(tenant: string, scope: string, from: string | null, to: string | null): Promise<string[] | null>;
175
+ export declare function latestRevisionId(tenant: string, scope: string): Promise<string | null>;
176
+ /** A scope with no revision at all gets a local baseline, as before. */
177
+ export declare function ensureBaseline(tenant: string, scope: string, by?: string): Promise<string | null>;
101
178
  export type DiffOp = {
102
179
  kind: "same" | "add" | "del";
103
180
  text: string;
@@ -42,6 +42,42 @@ export function registerTreeReader(fn) {
42
42
  const prev = readTree;
43
43
  readTree = (tenant, scope) => fn(tenant, scope) ?? prev(tenant, scope);
44
44
  }
45
+ /** The scope's tree as the registered readers see it (text files only), or null. */
46
+ export function currentTree(tenant, scope) {
47
+ return readTree(tenant, scope);
48
+ }
49
+ let journal = null;
50
+ export function registerJournal(fn) {
51
+ journal = fn;
52
+ }
53
+ /** A workspace was deleted: whatever a registered journal still holds for it
54
+ * (queued changes, their files) goes too (FOL-126 phase 4). */
55
+ let onGone = null;
56
+ export function registerWorkspaceGone(fn) {
57
+ onGone = fn;
58
+ }
59
+ export function workspaceGone(tenant, workspace) {
60
+ try {
61
+ onGone?.(tenant, workspace);
62
+ }
63
+ catch {
64
+ // a journal that cannot be cleared now is cleared at the next boot (the replay discards a missing workspace)
65
+ }
66
+ }
67
+ let lifecycleHooks = null;
68
+ export function registerWorkspaceLifecycle(l) {
69
+ lifecycleHooks = l;
70
+ }
71
+ export const workspaceLifecycle = () => lifecycleHooks;
72
+ /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
73
+ export function workspaceMoved(tenant, from, to) {
74
+ try {
75
+ lifecycleHooks?.moved(tenant, from, to);
76
+ }
77
+ catch {
78
+ // finished by the next reconcile
79
+ }
80
+ }
45
81
  function assertSafeName(v, what) {
46
82
  if (!/^[A-Za-z0-9][A-Za-z0-9._@-]{0,120}$/.test(v))
47
83
  throw new Error(`illegal ${what}: ${v}`);
@@ -117,6 +153,12 @@ export function recordRevision(tenant, scope, files, meta = {}) {
117
153
  // outside this call, such as a bundle's generated index.
118
154
  snapshot(tenant, scope, rev.id);
119
155
  fs.appendFileSync(path.join(dir, "index.jsonl"), `${JSON.stringify(line)}\n`);
156
+ try {
157
+ journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
158
+ }
159
+ catch {
160
+ // the revision store is not allowed to break a save; workspace-revisions logs and retries
161
+ }
120
162
  return rev;
121
163
  }
122
164
  // ----------------------------------------------------------------- snapshots
@@ -158,12 +200,12 @@ function snapshot(tenant, scope, id) {
158
200
  return true;
159
201
  }
160
202
  /** Whether a revision can be restored to: it has a snapshot. */
161
- export function hasSnapshot(tenant, scope, id) {
203
+ export function hasSnapshotLocal(tenant, scope, id) {
162
204
  assertSafeName(id, "revision id");
163
205
  return fs.existsSync(treePath(tenant, scope, id));
164
206
  }
165
207
  /** The whole tree at revision `id`, or null when it has no snapshot. */
166
- export function snapshotAt(tenant, scope, id) {
208
+ export function snapshotAtLocal(tenant, scope, id) {
167
209
  assertSafeName(id, "revision id");
168
210
  let manifest;
169
211
  try {
@@ -187,7 +229,7 @@ function snapshotIds(tenant, scope) {
187
229
  }
188
230
  }
189
231
  /** The newest revision that can be restored to — what "now" is in history. */
190
- export function headRevision(tenant, scope) {
232
+ export function headRevisionLocal(tenant, scope) {
191
233
  const have = snapshotIds(tenant, scope);
192
234
  return journalRevisions(tenant, scope, { limit: Infinity }).find((r) => have.has(r.id)) ?? null;
193
235
  }
@@ -198,8 +240,8 @@ export function headRevision(tenant, scope) {
198
240
  * by a path that never recorded a change. Returns the head's id, or null
199
241
  * when there is nothing to snapshot.
200
242
  */
201
- export function ensureBaseline(tenant, scope, by = "foldrun") {
202
- const head = headRevision(tenant, scope);
243
+ export function ensureBaselineLocal(tenant, scope, by = "foldrun") {
244
+ const head = headRevisionLocal(tenant, scope);
203
245
  if (head)
204
246
  return head.id;
205
247
  const tree = readTree(tenant, scope);
@@ -215,7 +257,7 @@ export function ensureBaseline(tenant, scope, by = "foldrun") {
215
257
  fs.writeFileSync(marker, id, { flag: "wx" });
216
258
  }
217
259
  catch {
218
- const held = headRevision(tenant, scope)?.id ?? null;
260
+ const held = headRevisionLocal(tenant, scope)?.id ?? null;
219
261
  // A marker with no baseline behind it, minutes old, is a process that
220
262
  // died writing one: clear it, and the next call writes the baseline.
221
263
  try {
@@ -249,12 +291,15 @@ export function ensureBaseline(tenant, scope, by = "foldrun") {
249
291
  * moment. Null when history holds nothing that old. Throws (status 400) on
250
292
  * something that is none of those.
251
293
  */
252
- export function resolveRevision(tenant, scope, to, now = Date.now()) {
294
+ export function resolveRevisionLocal(tenant, scope, to, now = Date.now()) {
295
+ const have = snapshotIds(tenant, scope);
296
+ return resolveIn(journalRevisions(tenant, scope, { limit: Infinity }).filter((r) => have.has(r.id)), to, now);
297
+ }
298
+ /** The pick of resolveRevision over a newest-first list of restorable revisions. */
299
+ function resolveIn(all, to, now) {
253
300
  const t = to.trim();
254
301
  if (!t || t.startsWith("-"))
255
302
  throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
256
- const have = snapshotIds(tenant, scope);
257
- const all = journalRevisions(tenant, scope, { limit: Infinity }).filter((r) => have.has(r.id));
258
303
  const rel = /^(\d+)\s*(m|h|d|w)$/.exec(t);
259
304
  const moment = rel
260
305
  ? now - Number(rel[1]) * { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[rel[2]]
@@ -294,7 +339,7 @@ function describe(files) {
294
339
  .join(", ") + ` file${files.length === 1 ? "" : "s"}`;
295
340
  }
296
341
  /** Newest first. `forPath` narrows to revisions that touched one file. */
297
- export function listRevisions(tenant, scope, opts = {}) {
342
+ export function listRevisionsLocal(tenant, scope, opts = {}) {
298
343
  return journalRevisions(tenant, scope, opts);
299
344
  }
300
345
  function journalRevisions(tenant, scope, opts = {}) {
@@ -358,7 +403,7 @@ function rebuildIndex(dir) {
358
403
  }
359
404
  return rows.map(({ written: _w, ...r }) => r).reverse();
360
405
  }
361
- export function readRevision(tenant, scope, id, forPath) {
406
+ export function readRevisionLocal(tenant, scope, id, forPath) {
362
407
  assertSafeName(id, "revision id");
363
408
  const file = path.join(historyDir(tenant, scope), `${id}.json`);
364
409
  if (!fs.existsSync(file))
@@ -369,13 +414,15 @@ export function readRevision(tenant, scope, id, forPath) {
369
414
  /** The files changed after revision `from` up to and including `to`, in a
370
415
  * scope — what differs between the versions two runs ran (FOL-72). Null
371
416
  * when either is unknown or `to` is not after `from`. */
372
- export function changedPathsBetween(tenant, scope, from, to) {
417
+ export function changedPathsBetweenLocal(tenant, scope, from, to) {
373
418
  if (!from || !to)
374
419
  return null;
375
420
  if (from === to)
376
421
  return [];
377
- const revs = listRevisions(tenant, scope, { limit: 500 }); // newest first
378
- // An exact id before a commit, as resolveRevision.
422
+ return changedIn(listRevisionsLocal(tenant, scope, { limit: 500 }), from, to);
423
+ }
424
+ function changedIn(revs, from, to) {
425
+ // newest first. An exact id before a commit, as resolveRevision.
379
426
  const at = (x) => {
380
427
  const byId = revs.findIndex((r) => r.id === x);
381
428
  return byId >= 0 ? byId : revs.findIndex((r) => r.commit === x);
@@ -388,8 +435,77 @@ export function changedPathsBetween(tenant, scope, from, to) {
388
435
  }
389
436
  /** The most recent revision id for a scope — what a change is attributed
390
437
  * to when nothing more specific (a deployed commit) is on record. */
391
- export function latestRevisionId(tenant, scope) {
392
- return listRevisions(tenant, scope, { limit: 1 })[0]?.id ?? null;
438
+ export function latestRevisionIdLocal(tenant, scope) {
439
+ return listRevisionsLocal(tenant, scope, { limit: 1 })[0]?.id ?? null;
440
+ }
441
+ let view = null;
442
+ export function registerRevisionView(v) {
443
+ view = v;
444
+ }
445
+ /** Revisions first, then the local entries older than the oldest of them. */
446
+ async function combined(tenant, scope, opts, restorableOnly = false) {
447
+ const limit = opts.limit ?? 200;
448
+ const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit: Number.isFinite(limit) ? limit : 500 }) : null;
449
+ let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
450
+ if (restorableOnly) {
451
+ const have = snapshotIds(tenant, scope);
452
+ local = local.filter((r) => have.has(r.id));
453
+ }
454
+ if (!mine || !mine.length)
455
+ return local.slice(0, limit);
456
+ const oldest = mine[mine.length - 1].at;
457
+ const seen = new Set(mine.map((r) => r.id));
458
+ return [...mine, ...local.filter((r) => !seen.has(r.id) && r.at < oldest)].slice(0, limit);
459
+ }
460
+ export async function listRevisions(tenant, scope, opts = {}) {
461
+ return combined(tenant, scope, opts);
462
+ }
463
+ /** The list the history page shows: each row with whether it can be restored
464
+ * to. One listing answers both — every revision in the store is restorable;
465
+ * a local entry is when it has a snapshot — where asking per row would list
466
+ * the store once per row. */
467
+ export async function listRevisionsRestorable(tenant, scope, opts = {}) {
468
+ const rows = await combined(tenant, scope, opts);
469
+ const have = snapshotIds(tenant, scope);
470
+ const stored = view && scope !== "@library" ? new Set(((await view.list(tenant, scope, { limit: 500 })) ?? []).map((r) => r.id)) : new Set();
471
+ return rows.map((r) => ({ ...r, restorable: have.has(r.id) || stored.has(r.id) }));
472
+ }
473
+ export async function readRevision(tenant, scope, id, forPath) {
474
+ assertSafeName(id, "revision id");
475
+ const fromStore = view && scope !== "@library" ? await view.read(tenant, scope, id, forPath) : null;
476
+ return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
477
+ }
478
+ export async function snapshotAt(tenant, scope, id) {
479
+ assertSafeName(id, "revision id");
480
+ const fromStore = view && scope !== "@library" ? await view.snapshot(tenant, scope, id) : null;
481
+ return fromStore ?? snapshotAtLocal(tenant, scope, id);
482
+ }
483
+ export async function hasSnapshot(tenant, scope, id) {
484
+ assertSafeName(id, "revision id");
485
+ if (hasSnapshotLocal(tenant, scope, id))
486
+ return true;
487
+ return Boolean(view && scope !== "@library" && (await view.list(tenant, scope, { limit: 500 }))?.some((r) => r.id === id));
488
+ }
489
+ export async function headRevision(tenant, scope) {
490
+ return (await combined(tenant, scope, { limit: 1 }, true))[0] ?? null;
491
+ }
492
+ export async function resolveRevision(tenant, scope, to, now = Date.now()) {
493
+ return resolveIn(await combined(tenant, scope, { limit: Infinity }, true), to, now);
494
+ }
495
+ export async function changedPathsBetween(tenant, scope, from, to) {
496
+ if (!from || !to)
497
+ return null;
498
+ if (from === to)
499
+ return [];
500
+ return changedIn(await combined(tenant, scope, { limit: 500 }), from, to);
501
+ }
502
+ export async function latestRevisionId(tenant, scope) {
503
+ return (await combined(tenant, scope, { limit: 1 }))[0]?.id ?? null;
504
+ }
505
+ /** A scope with no revision at all gets a local baseline, as before. */
506
+ export async function ensureBaseline(tenant, scope, by = "foldrun") {
507
+ const head = await headRevision(tenant, scope);
508
+ return head ? head.id : ensureBaselineLocal(tenant, scope, by);
393
509
  }
394
510
  /**
395
511
  * A line diff, for showing a revision. Plain LCS — quadratic, and fine: the