@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
@@ -951,6 +951,14 @@ export declare function assertDeletable(tenant: string, workspace: string, rel:
951
951
  };
952
952
  export declare function deleteWorkspacePath(tenant: string, workspace: string, rel: string, meta?: ChangeMeta): void;
953
953
  export declare function deleteWorkspace(tenant: string, workspace: string): void;
954
+ /**
955
+ * deleteWorkspace, with the workspace's revisions: its history is dropped
956
+ * BEFORE the folder goes (a store that cannot be reached refuses the delete
957
+ * while it can still be retried) and once more after, for whatever a racing
958
+ * write made in between. A new workspace of the same name starts empty.
959
+ * Where nothing records revisions this is deleteWorkspace.
960
+ */
961
+ export declare function deleteWorkspaceAsync(tenant: string, workspace: string): Promise<void>;
954
962
  /**
955
963
  * What a rename would break, so the caller can say so before doing it.
956
964
  *
@@ -971,6 +979,14 @@ export declare function renameImpact(tenant: string, workspace: string): {
971
979
  * there is nothing to migrate and nothing to lose.
972
980
  */
973
981
  export declare function renameWorkspace(tenant: string, from: string, to: string): void;
982
+ /**
983
+ * renameWorkspace, with the workspace's revisions: queued changes are held
984
+ * while its history is re-keyed to the new name, then the folder moves; if the
985
+ * folder cannot move the history goes back. A store that cannot be reached
986
+ * refuses the rename before anything moved. Where nothing records revisions
987
+ * this is renameWorkspace.
988
+ */
989
+ export declare function renameWorkspaceAsync(tenant: string, from: string, to: string): Promise<void>;
974
990
  /** Set a workspace's description, in AGENTS.md, without touching anything else.
975
991
  *
976
992
  * 30 Oct 2026: the value was spliced in as `description: ${text}`, so a
@@ -1668,7 +1684,28 @@ export declare function listRunOutputs(tenant: string, workspace: string, runId:
1668
1684
  * the archive or names nothing — the API serves only what this returns. */
1669
1685
  export declare function runOutputPath(tenant: string, workspace: string, runId: string, agent: string, rel: string): string | null;
1670
1686
  export declare function readRun(tenant: string, workspace: string, runId: string): RunRecord | null;
1687
+ /** readRun without holding the event loop: asked of the database directly
1688
+ * where the port has async reads, otherwise the synchronous read. */
1689
+ export declare function readRunAsync(tenant: string, workspace: string, runId: string): Promise<RunRecord | null>;
1690
+ /** writeRun without holding the event loop (FOL-126 phase 4): for the callers
1691
+ * that are async anyway. Where the port writes asynchronously the record is
1692
+ * written when this resolves; everywhere else (files, a port without the
1693
+ * async write) it IS writeRun. The sync callers (the runner's save) are
1694
+ * untouched. */
1695
+ export declare function writeRunAsync(tenant: string, workspace: string, run: RunRecord): Promise<void>;
1671
1696
  export declare function writeRun(tenant: string, workspace: string, run: RunRecord): void;
1697
+ /** When a run's record last changed, as a string that differs whenever it
1698
+ * does — what a poller compares instead of a file's stat. Null: no such run
1699
+ * (or, for a file, gone for a moment — read to find out). */
1700
+ export declare function runStamp(tenant: string, workspace: string, runId: string): string | null;
1701
+ /** When a run's record was last written (epoch ms), or null when there is none. */
1702
+ export declare function runUpdatedMs(tenant: string, workspace: string, runId: string): number | null;
1703
+ /** A run's record as the JSON text a stream sends, or null when there is none. */
1704
+ export declare function readRunText(tenant: string, workspace: string, runId: string): string | null;
1705
+ /** Runs of one workspace that started at or after `sinceMs`, whole, newest
1706
+ * first. Off the records where there are any; the files otherwise read only
1707
+ * the names that say when they began. */
1708
+ export declare function runsStartedSince(tenant: string, workspace: string, sinceMs: number): RunRecord[];
1672
1709
  /**
1673
1710
  * The workspace's live runs — queued, running, or parked at a gate — read
1674
1711
  * whole, newest first. Off the run index: only the live records are opened,
@@ -1676,6 +1713,8 @@ export declare function writeRun(tenant: string, workspace: string, run: RunReco
1676
1713
  * periodic sweeps want (reconcile, the watchdog), and on a box that keeps
1677
1714
  * ninety days of runs that is a handful of files instead of thousands.
1678
1715
  */
1716
+ /** liveRuns without holding the event loop (see readRunAsync). */
1717
+ export declare function liveRunsAsync(tenant: string, workspace: string): Promise<RunRecord[]>;
1679
1718
  export declare function liveRuns(tenant: string, workspace: string): RunRecord[];
1680
1719
  export interface RunWithWorkspace extends RunRecord {
1681
1720
  workspace: string;
@@ -1763,6 +1802,8 @@ export declare function runFromSummary(s: RunSummary): RunRecord;
1763
1802
  * are re-read, and the index is rewritten if anything changed. A missing
1764
1803
  * or unreadable index is a full scan that leaves one behind.
1765
1804
  */
1805
+ /** listRunSummaries without holding the event loop (see readRunAsync). */
1806
+ export declare function listRunSummariesAsync(tenant: string, workspace: string): Promise<RunSummary[]>;
1766
1807
  export declare function listRunSummaries(tenant: string, workspace: string): RunSummary[];
1767
1808
  /** Every workspace's runs as summaries, tagged with the workspace. */
1768
1809
  export declare function listAllRunSummaries(tenant: string): (RunSummary & {
package/dist/src/store.js CHANGED
@@ -24,9 +24,10 @@ import { expandPlatformVars } from "./host-env.js";
24
24
  import { FLOW_TRIGGERS } from "./frontmatter-fields.js";
25
25
  import fs from "node:fs";
26
26
  import path from "node:path";
27
- import { recordRevision, registerTreeReader, assertCommitId } from "./history.js";
27
+ import { recordRevision, registerTreeReader, assertCommitId, workspaceGone, workspaceMoved, workspaceLifecycle } from "./history.js";
28
28
  import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.js";
29
29
  import { platform } from "./platform.js";
30
+ import { records } from "./records.js";
30
31
  import { toLF, asRaw } from "./eol.js";
31
32
  import matter, { frontmatterErrorText, configMatter } from "./matter.js";
32
33
  import { readAgentsMdKeys, patchFrontmatter } from "./agents-md.js";
@@ -2150,6 +2151,7 @@ export function listWorkspaces(tenant) {
2150
2151
  const dir = workspacesRoot(tenant);
2151
2152
  if (!fs.existsSync(dir))
2152
2153
  return [];
2154
+ const recordCounts = records()?.runCounts(tenant) ?? null;
2153
2155
  return fs
2154
2156
  .readdirSync(dir)
2155
2157
  .filter((n) => fs.statSync(path.join(dir, n)).isDirectory())
@@ -2183,7 +2185,7 @@ export function listWorkspaces(tenant) {
2183
2185
  agents: listAgents(tenant, name).length,
2184
2186
  flows: listFlows(tenant, name).length,
2185
2187
  deployedAt: fs.statSync(pDir).mtime.toISOString(),
2186
- runCount: fs.existsSync(runsDir) ? fs.readdirSync(runsDir).filter((f) => f.endsWith(".json") && !f.startsWith(".")).length : 0,
2188
+ runCount: recordCounts && records(tenant, name) ? (recordCounts[name] ?? 0) : (fs.existsSync(runsDir) ? fs.readdirSync(runsDir).filter((f) => f.endsWith(".json") && !f.startsWith(".")).length : 0),
2187
2189
  };
2188
2190
  })
2189
2191
  .sort((a, b) => b.deployedAt.localeCompare(a.deployedAt));
@@ -2681,7 +2683,14 @@ export function deleteWorkspace(tenant, workspace) {
2681
2683
  const dir = workspaceDir(tenant, workspace);
2682
2684
  if (!fs.existsSync(dir))
2683
2685
  throw new Error(`workspace ${workspace} not found`);
2686
+ // Its records in the database (runs, trigger log, file index) go BEFORE the
2687
+ // folder: if that throws, nothing was removed and the delete can be retried;
2688
+ // after the folder is gone a retry would answer "not found" with rows left.
2689
+ records()?.workspaceDrop(tenant, workspace);
2684
2690
  fs.rmSync(dir, { recursive: true, force: true });
2691
+ // Its revision journal: queued changes must not commit (or replay at the
2692
+ // next boot) for a workspace that is gone (FOL-126 phase 4).
2693
+ workspaceGone(tenant, workspace);
2685
2694
  // Its file store too, kept by name beside the folder (storage.ts). Until
2686
2695
  // 30 Oct 2026 the store outlived the delete: its files stayed downloadable
2687
2696
  // and shared, and the next workspace given this name inherited them. The
@@ -2693,6 +2702,21 @@ export function deleteWorkspace(tenant, workspace) {
2693
2702
  }
2694
2703
  workspaceChanged(tenant, workspace, "delete");
2695
2704
  }
2705
+ /**
2706
+ * deleteWorkspace, with the workspace's revisions: its history is dropped
2707
+ * BEFORE the folder goes (a store that cannot be reached refuses the delete
2708
+ * while it can still be retried) and once more after, for whatever a racing
2709
+ * write made in between. A new workspace of the same name starts empty.
2710
+ * Where nothing records revisions this is deleteWorkspace.
2711
+ */
2712
+ export async function deleteWorkspaceAsync(tenant, workspace) {
2713
+ const lc = workspaceLifecycle();
2714
+ if (!lc)
2715
+ return deleteWorkspace(tenant, workspace);
2716
+ if (!fs.existsSync(workspaceDir(tenant, workspace)))
2717
+ throw new Error(`workspace ${workspace} not found`);
2718
+ await lc.drop(tenant, workspace, () => deleteWorkspace(tenant, workspace));
2719
+ }
2696
2720
  /**
2697
2721
  * What a rename would break, so the caller can say so before doing it.
2698
2722
  *
@@ -2732,12 +2756,45 @@ export function renameWorkspace(tenant, from, to) {
2732
2756
  throw new Error(`workspace ${to} already exists`);
2733
2757
  fs.mkdirSync(path.dirname(dest), { recursive: true });
2734
2758
  fs.renameSync(src, dest);
2759
+ // Its runs and trigger log in the database follow the name; if they cannot,
2760
+ // the folder goes back, so the two never disagree about where the workspace is.
2761
+ try {
2762
+ records()?.workspaceMove(tenant, from, to);
2763
+ }
2764
+ catch (err) {
2765
+ fs.renameSync(dest, src);
2766
+ throw err;
2767
+ }
2768
+ // Its queued revisions and its history follow the name (workspace-revisions.ts).
2769
+ workspaceMoved(tenant, from, to);
2735
2770
  const agentsMd = path.join(dest, "AGENTS.md");
2736
2771
  if (fs.existsSync(agentsMd)) {
2737
2772
  const raw = fs.readFileSync(agentsMd, "utf8");
2738
2773
  fs.writeFileSync(agentsMd, raw.replace(/^name:.*$/m, `name: ${to}`));
2739
2774
  }
2740
2775
  }
2776
+ /**
2777
+ * renameWorkspace, with the workspace's revisions: queued changes are held
2778
+ * while its history is re-keyed to the new name, then the folder moves; if the
2779
+ * folder cannot move the history goes back. A store that cannot be reached
2780
+ * refuses the rename before anything moved. Where nothing records revisions
2781
+ * this is renameWorkspace.
2782
+ */
2783
+ export async function renameWorkspaceAsync(tenant, from, to) {
2784
+ const lc = workspaceLifecycle();
2785
+ if (!lc || from === to)
2786
+ return renameWorkspace(tenant, from, to);
2787
+ assertSafeName(to, "workspace");
2788
+ if (!fs.existsSync(workspaceDir(tenant, from)))
2789
+ throw new Error(`workspace ${from} not found`);
2790
+ // The checks renameWorkspace makes, BEFORE the history moves: a name that is
2791
+ // taken must never have its history replaced by this one's.
2792
+ if (singleWorkspace())
2793
+ return renameWorkspace(tenant, from, to); // throws
2794
+ if (fs.existsSync(workspaceDir(tenant, to)) || fs.existsSync(path.join(dataRoot(), tenant, WORKSPACES, to)))
2795
+ throw new Error(`workspace ${to} already exists`);
2796
+ await lc.move(tenant, from, to, () => renameWorkspace(tenant, from, to));
2797
+ }
2741
2798
  /** Set a workspace's description, in AGENTS.md, without touching anything else.
2742
2799
  *
2743
2800
  * 30 Oct 2026: the value was spliced in as `description: ${text}`, so a
@@ -2926,7 +2983,8 @@ export function runFilePath(tenant, workspace, runId) {
2926
2983
  export function deleteRun(tenant, workspace, runId, opts = {}) {
2927
2984
  const file = runFilePath(tenant, workspace, runId);
2928
2985
  const dir = path.join(workspaceDir(tenant, workspace), "runs", runId);
2929
- const had = fs.existsSync(file);
2986
+ const port = records(tenant, workspace);
2987
+ const had = port ? port.runGet(tenant, workspace, runId) !== null : fs.existsSync(file);
2930
2988
  if (!had && !fs.existsSync(dir))
2931
2989
  return false;
2932
2990
  // The folder first (archived outputs, captured calls), the record last:
@@ -2934,8 +2992,12 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
2934
2992
  // and finishes — the other order left the content with nothing pointing
2935
2993
  // at it (Codex review, FOL-124).
2936
2994
  fs.rmSync(dir, { recursive: true, force: true });
2937
- fs.rmSync(file, { force: true });
2938
- noteRunDeleted(path.dirname(file), runId);
2995
+ if (port)
2996
+ port.runDelete(tenant, workspace, runId);
2997
+ else {
2998
+ fs.rmSync(file, { force: true });
2999
+ noteRunDeleted(path.dirname(file), runId);
3000
+ }
2939
3001
  if (!had)
2940
3002
  return true;
2941
3003
  // The retention window's prune (`pruned`) is policy, not a person erasing
@@ -2996,6 +3058,9 @@ export function runOutputPath(tenant, workspace, runId, agent, rel) {
2996
3058
  }
2997
3059
  export function readRun(tenant, workspace, runId) {
2998
3060
  const p = runFilePath(tenant, workspace, runId);
3061
+ const port = records(tenant, workspace);
3062
+ if (port)
3063
+ return port.runGet(tenant, workspace, runId);
2999
3064
  // EFS/NFS: writeRun() replaces this file by rename, so an open()+read()
3000
3065
  // here can land on the just-unlinked inode and come back ESTALE (errno
3001
3066
  // -116, surfaced by Node as "Unknown system error -116", syscall read).
@@ -3016,8 +3081,34 @@ export function readRun(tenant, workspace, runId) {
3016
3081
  }
3017
3082
  }
3018
3083
  }
3084
+ /** readRun without holding the event loop: asked of the database directly
3085
+ * where the port has async reads, otherwise the synchronous read. */
3086
+ export async function readRunAsync(tenant, workspace, runId) {
3087
+ runFilePath(tenant, workspace, runId); // the same name checks as readRun
3088
+ const port = records(tenant, workspace);
3089
+ return port?.async ? port.async.runGet(tenant, workspace, runId) : readRun(tenant, workspace, runId);
3090
+ }
3091
+ /** writeRun without holding the event loop (FOL-126 phase 4): for the callers
3092
+ * that are async anyway. Where the port writes asynchronously the record is
3093
+ * written when this resolves; everywhere else (files, a port without the
3094
+ * async write) it IS writeRun. The sync callers (the runner's save) are
3095
+ * untouched. */
3096
+ export async function writeRunAsync(tenant, workspace, run) {
3097
+ const port = records(tenant, workspace);
3098
+ if (port?.async?.runPut) {
3099
+ runFilePath(tenant, workspace, run.id); // the same name checks as writeRun
3100
+ await port.async.runPut(tenant, workspace, run, summarizeRun(run), LIVE_STATUSES.has(run.status));
3101
+ return;
3102
+ }
3103
+ writeRun(tenant, workspace, run);
3104
+ }
3019
3105
  export function writeRun(tenant, workspace, run) {
3020
3106
  const p = runFilePath(tenant, workspace, run.id);
3107
+ const port = records(tenant, workspace);
3108
+ if (port) {
3109
+ port.runPut(tenant, workspace, run, summarizeRun(run), LIVE_STATUSES.has(run.status));
3110
+ return;
3111
+ }
3021
3112
  fs.mkdirSync(path.dirname(p), { recursive: true });
3022
3113
  // Atomic write — runs are re-read while running (dashboard polls, CLI
3023
3114
  // tails), and a plain writeFileSync can be caught half-written.
@@ -3026,6 +3117,79 @@ export function writeRun(tenant, workspace, run) {
3026
3117
  fs.renameSync(tmp, p);
3027
3118
  noteRunWritten(path.dirname(p), run, p);
3028
3119
  }
3120
+ /** When a run's record last changed, as a string that differs whenever it
3121
+ * does — what a poller compares instead of a file's stat. Null: no such run
3122
+ * (or, for a file, gone for a moment — read to find out). */
3123
+ export function runStamp(tenant, workspace, runId) {
3124
+ const port = records(tenant, workspace);
3125
+ if (port) {
3126
+ const at = port.runStamp(tenant, workspace, runId);
3127
+ return at === null ? null : String(at);
3128
+ }
3129
+ try {
3130
+ return fileStamp(fs.statSync(runFilePath(tenant, workspace, runId)));
3131
+ }
3132
+ catch {
3133
+ return null;
3134
+ }
3135
+ }
3136
+ /** When a run's record was last written (epoch ms), or null when there is none. */
3137
+ export function runUpdatedMs(tenant, workspace, runId) {
3138
+ const port = records(tenant, workspace);
3139
+ if (port) {
3140
+ const us = port.runStamp(tenant, workspace, runId);
3141
+ return us === null ? null : us / 1000;
3142
+ }
3143
+ try {
3144
+ return fs.statSync(runFilePath(tenant, workspace, runId)).mtimeMs;
3145
+ }
3146
+ catch {
3147
+ return null;
3148
+ }
3149
+ }
3150
+ /** A run's record as the JSON text a stream sends, or null when there is none. */
3151
+ export function readRunText(tenant, workspace, runId) {
3152
+ if (records(tenant, workspace)) {
3153
+ const run = readRun(tenant, workspace, runId);
3154
+ return run ? JSON.stringify(run, null, 2) : null;
3155
+ }
3156
+ try {
3157
+ return fs.readFileSync(runFilePath(tenant, workspace, runId), "utf8");
3158
+ }
3159
+ catch {
3160
+ return null;
3161
+ }
3162
+ }
3163
+ /** Runs of one workspace that started at or after `sinceMs`, whole, newest
3164
+ * first. Off the records where there are any; the files otherwise read only
3165
+ * the names that say when they began. */
3166
+ export function runsStartedSince(tenant, workspace, sinceMs) {
3167
+ const port = records(tenant, workspace);
3168
+ if (port)
3169
+ return port.runsSince(tenant, workspace, sinceMs);
3170
+ const dir = path.join(workspaceDir(tenant, workspace), "runs");
3171
+ let names;
3172
+ try {
3173
+ names = fs.readdirSync(dir);
3174
+ }
3175
+ catch {
3176
+ return [];
3177
+ }
3178
+ const out = [];
3179
+ for (const f of names) {
3180
+ if (!f.endsWith(".json") || f.startsWith("."))
3181
+ continue;
3182
+ try {
3183
+ const run = JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
3184
+ if (Date.parse(run.startedAt) >= sinceMs)
3185
+ out.push(run);
3186
+ }
3187
+ catch {
3188
+ // mid-write or foreign: not a run
3189
+ }
3190
+ }
3191
+ return out.sort((a, b) => b.startedAt.localeCompare(a.startedAt));
3192
+ }
3029
3193
  /**
3030
3194
  * The workspace's live runs — queued, running, or parked at a gate — read
3031
3195
  * whole, newest first. Off the run index: only the live records are opened,
@@ -3033,7 +3197,15 @@ export function writeRun(tenant, workspace, run) {
3033
3197
  * periodic sweeps want (reconcile, the watchdog), and on a box that keeps
3034
3198
  * ninety days of runs that is a handful of files instead of thousands.
3035
3199
  */
3200
+ /** liveRuns without holding the event loop (see readRunAsync). */
3201
+ export async function liveRunsAsync(tenant, workspace) {
3202
+ const port = records(tenant, workspace);
3203
+ return port?.async ? port.async.runLive(tenant, workspace) : liveRuns(tenant, workspace);
3204
+ }
3036
3205
  export function liveRuns(tenant, workspace) {
3206
+ const port = records(tenant, workspace);
3207
+ if (port)
3208
+ return port.runLive(tenant, workspace);
3037
3209
  const out = [];
3038
3210
  for (const s of listRunSummaries(tenant, workspace)) {
3039
3211
  if (!LIVE_STATUSES.has(s.status))
@@ -3243,7 +3415,15 @@ function noteRunDeleted(dir, runId) {
3243
3415
  * are re-read, and the index is rewritten if anything changed. A missing
3244
3416
  * or unreadable index is a full scan that leaves one behind.
3245
3417
  */
3418
+ /** listRunSummaries without holding the event loop (see readRunAsync). */
3419
+ export async function listRunSummariesAsync(tenant, workspace) {
3420
+ const port = records(tenant, workspace);
3421
+ return port?.async ? port.async.runSummaries(tenant, workspace) : listRunSummaries(tenant, workspace);
3422
+ }
3246
3423
  export function listRunSummaries(tenant, workspace) {
3424
+ const port = records(tenant, workspace);
3425
+ if (port)
3426
+ return port.runSummaries(tenant, workspace);
3247
3427
  const dir = path.join(workspaceDir(tenant, workspace), "runs");
3248
3428
  if (!fs.existsSync(dir))
3249
3429
  return [];
@@ -3580,6 +3760,9 @@ export function listAgentSteps(tenant, workspace, agent) {
3580
3760
  /** Every run of the workspace, whole, newest first. Parses every record;
3581
3761
  * a list that needs only what a list needs reads listRunSummaries. */
3582
3762
  export function listRuns(tenant, workspace) {
3763
+ const port = records(tenant, workspace);
3764
+ if (port)
3765
+ return port.runAll(tenant, workspace);
3583
3766
  const dir = path.join(workspaceDir(tenant, workspace), "runs");
3584
3767
  if (!fs.existsSync(dir))
3585
3768
  return [];
@@ -27,6 +27,7 @@
27
27
  import fs from "node:fs";
28
28
  import path from "node:path";
29
29
  import { workspaceDir } from "./store.js";
30
+ import { records } from "./records.js";
30
31
  /** A refused start's own code, for rollbackTrigger: a lowercase word an
31
32
  * error that carries an HTTP status also carries (`waiting_cap`), never a
32
33
  * system errno (`ENOENT`). Undefined for anything else. */
@@ -47,6 +48,13 @@ const KEEP = 500;
47
48
  * diagnostic: the whole point is to be reading it on the bad morning. */
48
49
  export function recordTriggerEvent(tenant, workspace, event) {
49
50
  try {
51
+ const port = records(tenant, workspace);
52
+ if (port) {
53
+ // Only a workspace that is there: a delivery for one that is not leaves no row.
54
+ if (fs.existsSync(workspaceDir(tenant, workspace)))
55
+ port.triggerAppend(tenant, workspace, event);
56
+ return;
57
+ }
50
58
  const file = logFile(tenant, workspace);
51
59
  if (!fs.existsSync(path.dirname(file)))
52
60
  return;
@@ -63,6 +71,15 @@ export function recordTriggerEvent(tenant, workspace, event) {
63
71
  }
64
72
  }
65
73
  export function readTriggerEvents(tenant, workspace, limit = 200) {
74
+ const port = records(tenant, workspace);
75
+ if (port) {
76
+ try {
77
+ return port.triggerRead(tenant, workspace, limit);
78
+ }
79
+ catch {
80
+ return [];
81
+ }
82
+ }
66
83
  let lines;
67
84
  try {
68
85
  lines = fs.readFileSync(logFile(tenant, workspace), "utf8").split("\n").filter(Boolean);
@@ -0,0 +1,259 @@
1
+ import { type RevisionSummary, type Revision as HistoryRevision } from "./history.ts";
2
+ import { type JournalStore } from "./journal-store.ts";
3
+ import { type Deps, type PublishResult } from "./publish.ts";
4
+ import { type StateRetention } from "./state-retention.ts";
5
+ import type { SweepMarks } from "./blob-sweeper.ts";
6
+ /** Two switches the host decides on every call (the settings registry's
7
+ * `revisions.journal` and `revisions.read`): the journal and history from
8
+ * revisions; reads of file content from heads. Both default to off in a host
9
+ * that gives no answer, so registering a backend alone changes nothing. */
10
+ export interface BackendOptions {
11
+ journal?: () => boolean;
12
+ read?: () => boolean;
13
+ /** Where the journal's entries are written down (journal-store.ts). Unset:
14
+ * files under <data>/.revision-journal (a laptop, Compose). A hosted install
15
+ * gives the database, so the journal does not depend on the shared volume. */
16
+ journalStore?: JournalStore;
17
+ /** How many `state/` checkpoints to keep, and for how long (state-retention.ts).
18
+ * Unset: none is ever pruned. */
19
+ stateRetention?: () => StateRetention;
20
+ /** How often a workspace's checkpoints are looked at after a commit (ms). */
21
+ retentionEveryMs?: number;
22
+ /** Where "first seen" is kept: lets the boot reconcile remove the history of
23
+ * workspaces whose folder is gone (cleanOrphanedHistory). Unset: it never does. */
24
+ sweepMarks?: SweepMarks;
25
+ /** How long a workspace must have been seen without its folder before its
26
+ * history is removed. Default one hour. */
27
+ orphanGraceMs?: number;
28
+ }
29
+ /** Where revisions live, or null (no journal, nothing changes). */
30
+ export declare function setRevisionBackend(deps: Deps | null, opts?: BackendOptions): void;
31
+ export declare const revisionBackend: () => Deps | null;
32
+ /** Reads of content from heads (and run stage-in): its own switch, and only
33
+ * where the journal runs too (a head that is not kept current is not a source). */
34
+ export declare const revisionReadsOn: () => boolean;
35
+ /** The bounded node-local cache of blobs, keyed by sha (built elsewhere). A
36
+ * miss falls through to the BlobStore and fills the cache. */
37
+ export interface BlobCache {
38
+ get(tenant: string, sha: string): Promise<Buffer | null>;
39
+ put(tenant: string, sha: string, bytes: Buffer): Promise<void>;
40
+ }
41
+ export declare function setBlobCache(c: BlobCache | null): void;
42
+ /** One file a step wrote back to the workspace (run-container.ts
43
+ * applyContainerChanges): `base` is the sha of the folder's copy before the
44
+ * write (null: new file), `after` the bytes now on the folder. */
45
+ export interface StepWrite {
46
+ path: string;
47
+ base: string | null;
48
+ after: Buffer;
49
+ /** The sha of what the step was HANDED (null: no such file; undefined: not
50
+ * known, or the folder was merged with another writer's change). The head is
51
+ * held to the pinned revision's copy of the path only where the two agree. */
52
+ handed?: string | null;
53
+ }
54
+ /**
55
+ * FOL-126 phase 4. A step's copy-back lands as ONE revision (one journal
56
+ * entry, one publish): the paths it wrote on the workspace head and the ones
57
+ * under state/ on the state head (two commits, each idempotent, as decided on
58
+ * 6 Nov). Never a half-written tree: the entry is on disk before anything is
59
+ * queued, and a commit is all of the step's paths or none.
60
+ *
61
+ * Pinned base: each path carries the sha the folder held before the write, so
62
+ * a head that moved since (another run, a person) is a CONFLICT on that path —
63
+ * the head's version stays, the step's is kept beside it as
64
+ * `<stem>.conflict-<op>.<ext>` — while paths nobody else touched go through.
65
+ * The id is derived from the run and step, so a step whose copy-back is
66
+ * applied twice (a resumed driver) publishes once.
67
+ *
68
+ * The rule for a failed step, written down: applyContainerChanges runs after a
69
+ * failure too (a failed step's partial outputs are usually the interesting
70
+ * ones), so they are committed as well, as today's folder gets them. A step
71
+ * whose copy-out itself failed wrote nothing and commits nothing. A test run's
72
+ * diverted state/ and storage/ writes never reach the folder and never here.
73
+ *
74
+ * Text only: a binary file is not versioned yet (see phase 3). Returns the
75
+ * number of paths queued.
76
+ */
77
+ export declare function recordStepOutputs(tenant: string, workspace: string, writes: StepWrite[], meta: {
78
+ runId?: string;
79
+ step?: string | number;
80
+ by?: string;
81
+ base?: RunBase | null;
82
+ }): number;
83
+ /** Run `fn` (a synchronous writer) so that the change it records is committed
84
+ * as a restore of `revisionId` — the history then says "restored from". */
85
+ export declare function asRestoreOf<T>(tenant: string, workspace: string, revisionId: string | null | undefined, fn: () => T): T;
86
+ export declare function pendingRevisions(): number;
87
+ /** Wait until every queued change (of one workspace, or all) is committed.
88
+ * A barrier for an edge that wants "committed" before it answers. Returns
89
+ * what is still queued (a database that is down leaves some). */
90
+ export declare function flushRevisions(only?: {
91
+ tenant: string;
92
+ workspace: string;
93
+ }): Promise<{
94
+ pending: number;
95
+ }>;
96
+ /** Tests: forget every queued change and pending retry (journal FILES stay:
97
+ * that is what a crash leaves). */
98
+ export declare function resetJournalForTests(): void;
99
+ /** An account is gone (or one workspace is): forget its queued changes and
100
+ * remove its journal files, so nothing of it is replayed or committed later
101
+ * and no workspace text outlives it outside the folder. Safe to repeat. */
102
+ export declare function dropJournal(tenant: string, workspace?: string): void;
103
+ export declare function settleLifecycle(): Promise<void>;
104
+ /**
105
+ * A workspace is being deleted: its queued changes, its journal entries and
106
+ * its history (both heads, every revision, the operations, the pins on their
107
+ * manifests) go, so that nothing of it can be seen by, or committed under, the
108
+ * next workspace of that name. `remove` is the folder's own removal. Order:
109
+ * hold the commits; drop; remove the folder; drop again for whatever slipped
110
+ * in between. A store that cannot be reached throws BEFORE `remove` runs.
111
+ */
112
+ export declare function dropWorkspaceRevisions(tenant: string, workspace: string, remove?: () => void): Promise<void>;
113
+ /** An account is gone: its journal, its history and the blobs under its name.
114
+ * Throws when the store cannot be reached (the caller says so; nothing of the
115
+ * rest depends on it). */
116
+ export declare function dropTenantRevisions(tenant: string): Promise<void>;
117
+ /**
118
+ * A workspace is being renamed: its queued changes wait, its history is
119
+ * re-keyed to the new name (whatever the new name held belonged to a workspace
120
+ * that no longer exists), `rename` moves the folder, and the queue and the
121
+ * journal entries follow. If the folder cannot move, the history goes back. A
122
+ * store that cannot be reached throws BEFORE `rename` runs.
123
+ */
124
+ export declare function moveWorkspaceRevisions(tenant: string, from: string, to: string, rename?: () => void): Promise<void>;
125
+ /** The revisions a run's stage-in started from, one per head (null: that head
126
+ * had no revision yet). */
127
+ export interface RunBase {
128
+ workspace: string | null;
129
+ state: string | null;
130
+ }
131
+ /**
132
+ * FOL-126 fixes (8 Nov). At stage-in: record which revisions the run starts
133
+ * from and pin their manifests (holder kind `run`, a lease renewed while the
134
+ * step lives), so retention and the sweeper leave them alone. The copy-back is
135
+ * then published against THIS base: a path the head changed since is a
136
+ * conflict, not an overwrite, whatever the folder holds by then.
137
+ *
138
+ * The queue is flushed first, so the head is not behind a save made a moment
139
+ * ago (a head behind the folder would make every such path look conflicting).
140
+ * Null — and the caller carries on as before, with the folder as the base —
141
+ * when revisions are off, there is no head yet (the baseline will hold the
142
+ * whole tree), changes are still queued (the store is down), or the pin cannot
143
+ * be taken.
144
+ */
145
+ export declare function pinRunBase(tenant: string, workspace: string, holder: string): Promise<{
146
+ base: RunBase;
147
+ release(): Promise<void>;
148
+ } | null>;
149
+ /** The same pin for a base that was recorded earlier (a driver that took over a
150
+ * step): null when either revision is gone. */
151
+ export declare function repinRunBase(tenant: string, workspace: string, base: RunBase, holder: string): Promise<{
152
+ base: RunBase;
153
+ release(): Promise<void>;
154
+ } | null>;
155
+ /** Look at one workspace's `state/` checkpoints now (the host's window). */
156
+ export declare function pruneStateNow(tenant: string, workspace: string): Promise<{
157
+ pruned: number;
158
+ kept: number;
159
+ held: number;
160
+ } | null>;
161
+ /**
162
+ * FOL-126 fixes (8 Nov 2026), once and idempotent: before the delete took the
163
+ * history with it, the heads and revisions of a deleted workspace stayed, and a
164
+ * new workspace of that name started on them. Any workspace the store has
165
+ * rows for and the volume has no folder for is such a leftover.
166
+ *
167
+ * Removing history is not undone, so it is done carefully: a workspace is
168
+ * RECORDED the first time it is seen without a folder and removed only when it
169
+ * has been seen without one for `graceMs` (a volume that is briefly not
170
+ * mounted, or a listing that came back short, passes); an account whose
171
+ * folders are mostly missing is left alone and said (a partial mount looks
172
+ * exactly like that); nothing is done when the data root itself is empty or
173
+ * absent. A workspace whose folder is back is forgotten. Each removal takes the
174
+ * same lock as a delete (dropWorkspaceRevisions).
175
+ */
176
+ export declare function cleanOrphanedHistory(marks: SweepMarks, opts: {
177
+ graceMs: number;
178
+ force?: boolean;
179
+ dryRun?: boolean;
180
+ }): Promise<{
181
+ checked: number;
182
+ orphans: number;
183
+ marked: number;
184
+ dropped: number;
185
+ skipped: number;
186
+ }>;
187
+ /** Does this workspace need a reconcile (its journal overflowed)? */
188
+ export declare const needsReconcile: (tenant: string, workspace: string) => boolean;
189
+ /** Boot: replay what a dead process left in the journal directory, oldest
190
+ * first, then wait for it to commit. Entries of a workspace that no longer
191
+ * exists are discarded. `minAgeMs` keeps clear of a live process's files. */
192
+ export declare function recoverJournal(opts?: {
193
+ minAgeMs?: number;
194
+ }): Promise<{
195
+ entries: number;
196
+ workspaces: number;
197
+ }>;
198
+ /** Boot: bring every workspace's heads to its folder (reconcile each, one at
199
+ * a time, yielding between). A workspace with changes still queued is left
200
+ * to its queue. Returns how many were checked and how many needed repair. */
201
+ export declare function reconcileAll(opts?: {
202
+ by?: string;
203
+ tenants?: string[];
204
+ }): Promise<{
205
+ checked: number;
206
+ repaired: number;
207
+ failed: number;
208
+ }>;
209
+ /** Bring the heads to the folder's content in one revision: the way in for a
210
+ * workspace that predates the journal (the importer, phase 8), and the repair
211
+ * after a journal overflow. Text files only, as the tree reader lists them. */
212
+ export declare function reconcileWorkspace(tenant: string, workspace: string, by?: string): Promise<PublishResult | null>;
213
+ /** One file of the workspace as its heads hold it: head → manifest → blob.
214
+ * Null when there is no such file (or no head yet). */
215
+ export declare function readAtHead(tenant: string, workspace: string, rel: string): Promise<Buffer | null>;
216
+ /** The history page's rows, newest first: the workspace head's revisions in
217
+ * history.ts's summary shape. `commit` is null (a deploy's commit id rides in
218
+ * the message); the id is the revision's. */
219
+ export declare function listRevisionSummaries(tenant: string, workspace: string, opts?: {
220
+ limit?: number;
221
+ forPath?: string;
222
+ }): Promise<RevisionSummary[]>;
223
+ /** One revision with what changed, in history.ts's Revision shape (text
224
+ * before/after, clipped). */
225
+ export declare function readRevisionDetail(tenant: string, workspace: string, id: string, forPath?: string): Promise<HistoryRevision | null>;
226
+ /** The whole tree at a revision (the files a restore would bring back), text. */
227
+ export declare function snapshotFiles(tenant: string, workspace: string, id: string): Promise<{
228
+ path: string;
229
+ content: string;
230
+ }[] | null>;
231
+ /** Restore = a NEW revision pointing at an old one's blobs. History is kept;
232
+ * `state/` is rewound only when `stateTo` names a state revision. The caller
233
+ * then writes the files to the folder (snapshotFiles) as the restore route
234
+ * always did; the journal sees that write as a no-op because the head already
235
+ * holds the content. */
236
+ export declare function restoreRevision(tenant: string, workspace: string, to: string, opts: {
237
+ by: string;
238
+ opId: string;
239
+ message?: string;
240
+ stateTo?: string;
241
+ }): Promise<PublishResult | null>;
242
+ /** One workspace file, from its head when reads through revisions are on and
243
+ * the head has it; null otherwise, and the caller reads the folder (the
244
+ * fallback is the point: a head behind the folder, a missing blob, a store
245
+ * that is down, a binary file the tree reader never recorded). */
246
+ export declare function readHeadText(tenant: string, workspace: string, rel: string): Promise<string | null>;
247
+ /** Every file of the workspace head with its bytes and mode (both heads), for
248
+ * a stage-in; null when reads through revisions are off, there is no head,
249
+ * or any blob could not be had (the caller then stages from the folder). */
250
+ export declare function readHeadTree(tenant: string, workspace: string): Promise<{
251
+ path: string;
252
+ bytes: Buffer;
253
+ mode: number;
254
+ }[] | null>;
255
+ /** The dashboard's and the API's read of one editable file: the head's bytes
256
+ * when reads through revisions are on and the head has the file, otherwise
257
+ * the folder exactly as readWorkspaceFile answers (same path rules, same
258
+ * "file not found"). */
259
+ export declare function readWorkspaceFileVia(tenant: string, workspace: string, rel: string): Promise<string>;