@foldrun/core 20.3.0 → 21.1.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 (43) hide show
  1. package/dist/src/capture.d.ts +7 -1
  2. package/dist/src/capture.js +5 -2
  3. package/dist/src/deploy.js +12 -2
  4. package/dist/src/evals.d.ts +1 -0
  5. package/dist/src/evals.js +60 -13
  6. package/dist/src/grades.js +78 -24
  7. package/dist/src/history.d.ts +5 -1
  8. package/dist/src/history.js +41 -25
  9. package/dist/src/journal-store.d.ts +3 -1
  10. package/dist/src/library.js +1 -1
  11. package/dist/src/process-state.d.ts +2 -0
  12. package/dist/src/process-state.js +20 -0
  13. package/dist/src/records.d.ts +41 -0
  14. package/dist/src/run-outputs.js +22 -19
  15. package/dist/src/runner.js +2 -2
  16. package/dist/src/secret-health.js +8 -6
  17. package/dist/src/secrets.js +8 -6
  18. package/dist/src/store.d.ts +7 -5
  19. package/dist/src/store.js +33 -11
  20. package/dist/src/webhook.d.ts +5 -0
  21. package/dist/src/webhook.js +61 -8
  22. package/dist/src/workspace-docs.d.ts +9 -0
  23. package/dist/src/workspace-docs.js +31 -0
  24. package/dist/src/workspace-revisions.d.ts +10 -3
  25. package/dist/src/workspace-revisions.js +336 -146
  26. package/package.json +1 -1
  27. package/src/capture.ts +4 -1
  28. package/src/deploy.ts +10 -2
  29. package/src/evals.ts +54 -13
  30. package/src/grades.ts +75 -21
  31. package/src/history.ts +39 -24
  32. package/src/journal-store.ts +3 -2
  33. package/src/library.ts +1 -1
  34. package/src/process-state.ts +21 -0
  35. package/src/records.ts +36 -0
  36. package/src/run-outputs.ts +22 -19
  37. package/src/runner.ts +2 -2
  38. package/src/secret-health.ts +8 -6
  39. package/src/secrets.ts +8 -6
  40. package/src/store.ts +33 -12
  41. package/src/webhook.ts +63 -8
  42. package/src/workspace-docs.ts +33 -0
  43. package/src/workspace-revisions.ts +323 -132
@@ -38,6 +38,7 @@ import { Readable } from "node:stream";
38
38
  import path from "node:path";
39
39
  import crypto from "node:crypto";
40
40
  import { dataRoot } from "./paths.js";
41
+ import { processState } from "./process-state.js";
41
42
  import { BlobNotFound } from "./blob-store.js";
42
43
  import { PUBLISH_PIN_TTL_MS, noPins } from "./blob-pins.js";
43
44
  import { MAX_MANIFEST_FILES, MODE_EXEC, MODE_FILE, assertManifest, assertManifestPath, blobObjectKey, canonicalManifest, manifestId, manifestObjectKey, sha256Hex, } from "./manifest.js";
@@ -127,13 +128,15 @@ export function localRunOutputStore(root = path.join(dataRoot(), ".run-outputs")
127
128
  },
128
129
  };
129
130
  }
130
- let backend = null;
131
+ /** One per process (process-state.ts): the store the boot registered, and the
132
+ * clean-ups in flight, whichever copy of this module started them. */
133
+ const OUT = processState("run-outputs", () => ({ backend: null, background: new Set() }));
131
134
  /** Where run outputs are published, or null (every run archives to the volume). */
132
135
  export function setRunOutputsBackend(b) {
133
- backend = b;
136
+ OUT.backend = b;
134
137
  registerRunRemovedHook(b ? runDeleted : null);
135
138
  }
136
- export const runOutputsBackend = () => backend;
139
+ export const runOutputsBackend = () => OUT.backend;
137
140
  function safeCall(fn, fallback) {
138
141
  try {
139
142
  return fn();
@@ -143,7 +146,7 @@ function safeCall(fn, fallback) {
143
146
  }
144
147
  }
145
148
  /** Publishing is on: a backend is registered and the operator has said so. */
146
- export const runOutputsOn = () => !!backend && safeCall(backend.enabled, false);
149
+ export const runOutputsOn = () => !!OUT.backend && safeCall(OUT.backend.enabled, false);
147
150
  const pinsOf = (b) => b.pins ?? noPins;
148
151
  /** The permanent pin on one record's manifest. The manifest id is part of the
149
152
  * holder, so a re-archive (a resumed run) can pin the new manifest before it
@@ -327,7 +330,7 @@ export function noteRefused(run, refused) {
327
330
  * fails) say "volume" and the caller copies the folder as before.
328
331
  */
329
332
  export async function archiveRunOutputs(tenant, workspace, runId, agent, dir) {
330
- const b = backend;
333
+ const b = OUT.backend;
331
334
  if (!b || !runOutputsOn())
332
335
  return { where: "volume" };
333
336
  try {
@@ -346,10 +349,10 @@ export async function archiveRunOutputs(tenant, workspace, runId, agent, dir) {
346
349
  /** loadManifest reads blobs only; there is no revision store behind a run's outputs. */
347
350
  const readDeps = (b) => ({ blobs: b.blobs, revisions: undefined });
348
351
  async function recordsOf(tenant, workspace, runId) {
349
- if (!backend)
352
+ if (!OUT.backend)
350
353
  return [];
351
354
  try {
352
- return await backend.store.list(tenant, workspace, runId);
355
+ return await OUT.backend.store.list(tenant, workspace, runId);
353
356
  }
354
357
  catch (err) {
355
358
  opsError("run_outputs.list_failed", err, { tenant, workspace, run: runId });
@@ -362,7 +365,7 @@ export async function listRunOutputs(tenant, workspace, runId) {
362
365
  const recs = await recordsOf(tenant, workspace, runId);
363
366
  const out = [];
364
367
  for (const r of recs) {
365
- const m = await loadManifest(readDeps(backend), tenant, r.manifest);
368
+ const m = await loadManifest(readDeps(OUT.backend), tenant, r.manifest);
366
369
  for (const [p, e] of Object.entries(m.files))
367
370
  out.push({ agent: r.agent, path: p, bytes: e.size });
368
371
  }
@@ -378,13 +381,13 @@ export async function openRunOutput(tenant, workspace, runId, agent, rel) {
378
381
  if (!agent || !rel || agent.includes("/") || agent.includes("\\") || agent.startsWith("."))
379
382
  return null;
380
383
  const rec = (await recordsOf(tenant, workspace, runId)).find((r) => r.agent === agent);
381
- if (rec && backend) {
382
- const m = await loadManifest(readDeps(backend), tenant, rec.manifest);
384
+ if (rec && OUT.backend) {
385
+ const m = await loadManifest(readDeps(OUT.backend), tenant, rec.manifest);
383
386
  const e = m.files[rel.normalize("NFC")];
384
387
  if (!e)
385
388
  return null;
386
389
  const key = blobObjectKey(tenant, e.sha);
387
- const blobs = backend.blobs;
390
+ const blobs = OUT.backend.blobs;
388
391
  // A blob that is gone is an explicit failure (never an empty file); heading
389
392
  // here makes it one error before any byte is sent.
390
393
  if (!(await blobs.head(key)))
@@ -446,14 +449,14 @@ export async function readRunOutput(tenant, workspace, runId, agent, rel) {
446
449
  /** A run is deleted: its records and their pins go. Throws when the store
447
450
  * cannot be reached (deleteRun's caller retries in the background). */
448
451
  export async function dropRunOutputs(tenant, workspace, runId) {
449
- const b = backend;
452
+ const b = OUT.backend;
450
453
  if (!b)
451
454
  return;
452
455
  await releaseRecords(b, await b.store.drop({ tenant, workspace, runId }));
453
456
  }
454
457
  /** A workspace is deleted: every run's records of it. */
455
458
  export async function dropWorkspaceOutputs(tenant, workspace) {
456
- const b = backend;
459
+ const b = OUT.backend;
457
460
  if (!b)
458
461
  return;
459
462
  await releaseRecords(b, await b.store.drop({ tenant, workspace }));
@@ -461,7 +464,7 @@ export async function dropWorkspaceOutputs(tenant, workspace) {
461
464
  /** An account is deleted. Its pins are released by dropTenantRevisions (all pins
462
465
  * of the account); the records go here. */
463
466
  export async function dropTenantOutputs(tenant) {
464
- await backend?.store.drop({ tenant });
467
+ await OUT.backend?.store.drop({ tenant });
465
468
  }
466
469
  /** A workspace was renamed: the records follow (the pins are not keyed by
467
470
  * it). What the new name held belonged to a workspace that no longer
@@ -469,7 +472,7 @@ export async function dropTenantOutputs(tenant) {
469
472
  * store does both in its move too; the file store did not — review, 12 Nov
470
473
  * 2026). */
471
474
  export async function moveWorkspaceOutputs(tenant, from, to) {
472
- const b = backend;
475
+ const b = OUT.backend;
473
476
  if (!b)
474
477
  return;
475
478
  await releaseRecords(b, await b.store.drop({ tenant, workspace: to }));
@@ -480,14 +483,14 @@ export async function moveWorkspaceOutputs(tenant, from, to) {
480
483
  * store that cannot say, or cannot be reached, counts 0 (a statement must not fail). */
481
484
  export function runOutputBytes(tenant, workspace) {
482
485
  try {
483
- return backend?.store.bytes?.(tenant, workspace) ?? 0;
486
+ return OUT.backend?.store.bytes?.(tenant, workspace) ?? 0;
484
487
  }
485
488
  catch (err) {
486
489
  opsError("run_outputs.bytes_failed", err, { tenant, workspace }, "warn");
487
490
  return 0;
488
491
  }
489
492
  }
490
- const background = new Set();
493
+ const background = OUT.background;
491
494
  /** Wait for the retries a sync caller started (tests, process end). */
492
495
  export async function settleRunOutputs() {
493
496
  while (background.size)
@@ -496,9 +499,9 @@ export async function settleRunOutputs() {
496
499
  /** deleteRun cannot wait: do it now, and on a failure try again 1, 2, 4, 8 s
497
500
  * later, then say so (`run_outputs.drop_failed`; the blobs stay until a human looks). */
498
501
  export function runDeleted(tenant, workspace, runId) {
499
- if (!backend)
502
+ if (!OUT.backend)
500
503
  return;
501
- const b = backend;
504
+ const b = OUT.backend;
502
505
  // The records dropped are kept across the retries: a release that fails
503
506
  // after the drop must not leave the next try with nothing to release
504
507
  // (review, 12 Nov 2026).
@@ -65,7 +65,7 @@ import { buildScriptTools, parseScripts } from "./script-tools.js";
65
65
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.js";
66
66
  import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv } from "./runtime.js";
67
67
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.js";
68
- import { dataRoot } from "./paths.js";
68
+ import { dataRoot, singleWorkspace } from "./paths.js";
69
69
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.js";
70
70
  import { readStorageBaseline, writeStorageBaseline } from "./step-state.js";
71
71
  import { chooseExecutor, ensureImage } from "./container.js";
@@ -2158,7 +2158,7 @@ conversation) {
2158
2158
  captureFull = true;
2159
2159
  step.events.push({ t, type: "info", text: `capture: this step recorded ${Math.round(capturedChars / 1000)}k characters of tool content — the rest of its calls keep only their names, sizes and times` });
2160
2160
  }
2161
- if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact)) {
2161
+ if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact, singleWorkspace() ? undefined : { tenant, workspace: path.basename(path.resolve(agentDir, "..", "..")) })) {
2162
2162
  capturedChars += size;
2163
2163
  rest = { ...others, captured: true };
2164
2164
  }
@@ -23,6 +23,7 @@ import fs from "node:fs";
23
23
  import path from "node:path";
24
24
  import crypto from "node:crypto";
25
25
  import { accountDir } from "./store.js";
26
+ import { processState } from "./process-state.js";
26
27
  /** How a credential is identified here. A name alone is not enough: the
27
28
  * account and each workspace can hold a secret by the same name, and they
28
29
  * are different credentials with different health. */
@@ -65,10 +66,11 @@ const fileStore = {
65
66
  write(tenant, data);
66
67
  },
67
68
  };
68
- let store = fileStore;
69
+ /** One per process (process-state.ts), so every bundle writes to the store the boot chose. */
70
+ const HEALTH = processState("secret-health", () => ({ store: fileStore }));
69
71
  /** The platform's store (Postgres), or back to files with null. */
70
72
  export function setSecretHealthStore(next) {
71
- store = next ?? fileStore;
73
+ HEALTH.store = next ?? fileStore;
72
74
  }
73
75
  // Writes are queued and coalesced off the caller's path. The egress proxy
74
76
  // notes a use per secret per request, before it streams the response body,
@@ -86,7 +88,7 @@ function drain() {
86
88
  for (const [tenant, updates] of pending) {
87
89
  pending.delete(tenant);
88
90
  try {
89
- await store.apply(tenant, updates);
91
+ await HEALTH.store.apply(tenant, updates);
90
92
  }
91
93
  catch {
92
94
  // best effort, always
@@ -150,13 +152,13 @@ export function flushSecretHealth() {
150
152
  * vault holds but nothing has used are simply absent, which is the honest
151
153
  * answer: unused is not the same as broken. */
152
154
  export async function secretHealth(tenant) {
153
- return store.read(tenant);
155
+ return HEALTH.store.read(tenant);
154
156
  }
155
157
  /** The credentials worth saying something about: refused the last time they
156
158
  * were used. Sorted worst first — most consecutive refusals, then oldest
157
159
  * last-success, which is the order someone would work through them. */
158
160
  export async function failingSecrets(tenant) {
159
- return Object.entries(await store.read(tenant))
161
+ return Object.entries(await HEALTH.store.read(tenant))
160
162
  .filter(([, r]) => r.last.outcome === "refused")
161
163
  .map(([name, record]) => ({ name, record }))
162
164
  .sort((a, b) => b.record.refusals - a.record.refusals || (a.record.lastAccepted ?? "").localeCompare(b.record.lastAccepted ?? ""));
@@ -165,7 +167,7 @@ export async function failingSecrets(tenant) {
165
167
  * where the old key's refusals say nothing about the new one. */
166
168
  export async function forgetSecretHealth(tenant, name) {
167
169
  try {
168
- await store.forget(tenant, name);
170
+ await HEALTH.store.forget(tenant, name);
169
171
  }
170
172
  catch {
171
173
  // best effort
@@ -43,6 +43,7 @@ const tenantKey = (tenant) => platform.tenantKey(tenant);
43
43
  import crypto from "node:crypto";
44
44
  import { assertSafeName } from "./store.js";
45
45
  import { trimSlashes } from "./paths.js";
46
+ import { processState } from "./process-state.js";
46
47
  import { SITE, siteCovers } from "./network.js";
47
48
  const keyFile = () => path.join(dataRoot(), ".secret-key");
48
49
  /**
@@ -195,12 +196,13 @@ function openRecord(tenant, workspace, name, rec) {
195
196
  }
196
197
  return requireBound() ? null : decrypt(tenant, rec);
197
198
  }
198
- let vaultStore = null;
199
+ /** One per process (process-state.ts): the dashboard's routes must see the store the boot registered. */
200
+ const VAULT = processState("vault", () => ({ store: null }));
199
201
  /** Register (or, with null, remove) the platform's vault store. None: files. */
200
202
  export function setVaultStore(store) {
201
- vaultStore = store;
203
+ VAULT.store = store;
202
204
  }
203
- const inStore = (tenant, workspace) => (vaultStore?.on(tenant, workspace) ? vaultStore : null);
205
+ const inStore = (tenant, workspace) => (VAULT.store?.on(tenant, workspace) ? VAULT.store : null);
204
206
  function read(tenant, workspace) {
205
207
  const store = inStore(tenant, workspace);
206
208
  return store ? store.read(tenant, workspace) : readFile(secretsFile(tenant, workspace));
@@ -217,7 +219,7 @@ function mutateVault(tenant, workspace, change) {
217
219
  return next;
218
220
  });
219
221
  if (wrote)
220
- vaultStore?.forget?.(tenant, workspace);
222
+ VAULT.store?.forget?.(tenant, workspace);
221
223
  return after;
222
224
  }
223
225
  /** Where a scope's vault file is (a platform store imports from it and keeps
@@ -751,7 +753,7 @@ function secretFiles(tenant) {
751
753
  }
752
754
  // Scopes in the platform's store have no file; they are named by where
753
755
  // the file would be (the result's `file` is a label, never opened).
754
- for (const workspace of vaultStore?.workspaces(tenant) ?? []) {
756
+ for (const workspace of VAULT.store?.workspaces(tenant) ?? []) {
755
757
  if (!out.some((x) => x.workspace === workspace))
756
758
  out.push({ file: secretsFile(tenant, workspace), workspace });
757
759
  }
@@ -1055,7 +1057,7 @@ function workspacesWithSecrets(tenant) {
1055
1057
  if (fs.existsSync(path.join(base, n, "secrets.json")))
1056
1058
  out.add(n);
1057
1059
  }
1058
- for (const n of vaultStore?.workspaces(tenant) ?? [])
1060
+ for (const n of VAULT.store?.workspaces(tenant) ?? [])
1059
1061
  out.add(n);
1060
1062
  return [...out];
1061
1063
  }
@@ -1691,7 +1691,10 @@ export interface RunRecord {
1691
1691
  }
1692
1692
  /** Merge one part (the input, on the call; the output, on its completion)
1693
1693
  * into the call's file. */
1694
- export declare function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall): void;
1694
+ export declare function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall, scope?: {
1695
+ tenant: string;
1696
+ workspace: string;
1697
+ }): void;
1695
1698
  /** One recorded call of a run, or null (not recorded, or not a call). */
1696
1699
  export declare function readCapturedCall(tenant: string, workspace: string, runId: string, callId: string): CapturedCall | null;
1697
1700
  export declare function runFilePath(tenant: string, workspace: string, runId: string): string;
@@ -1714,12 +1717,11 @@ export declare function deleteRun(tenant: string, workspace: string, runId: stri
1714
1717
  pruned?: boolean;
1715
1718
  }): boolean;
1716
1719
  /** run-outputs.ts registers here (it imports this module). */
1717
- declare let onRunRemoved: ((tenant: string, workspace: string, runId: string) => void) | null;
1718
- export declare function registerRunRemovedHook(fn: typeof onRunRemoved): void;
1720
+ type RunHook = (tenant: string, workspace: string, runId: string) => void;
1721
+ export declare function registerRunRemovedHook(fn: RunHook | null): void;
1719
1722
  /** ledger.ts registers here — store cannot import it without a cycle, and
1720
1723
  * money must not depend on one. */
1721
- declare let onRunDeleted: ((tenant: string, workspace: string, runId: string) => void) | undefined;
1722
- export declare function registerRunDeletionListener(fn: typeof onRunDeleted): void;
1724
+ export declare function registerRunDeletionListener(fn: RunHook | undefined): void;
1723
1725
  export interface RunOutputFile {
1724
1726
  agent: string;
1725
1727
  /** Relative to that agent's outputs/ — the name the agent wrote. */
package/dist/src/store.js CHANGED
@@ -25,9 +25,11 @@ import { FLOW_TRIGGERS } from "./frontmatter-fields.js";
25
25
  import fs from "node:fs";
26
26
  import path from "node:path";
27
27
  import { recordRevision, registerTreeReader, assertCommitId, workspaceGone, workspaceMoved, workspaceLifecycle } from "./history.js";
28
+ import { processState } from "./process-state.js";
28
29
  import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.js";
29
30
  import { platform } from "./platform.js";
30
31
  import { records } from "./records.js";
32
+ import { docRows, docStore, quietly } from "./workspace-docs.js";
31
33
  import { toLF, asRaw } from "./eol.js";
32
34
  import matter, { frontmatterErrorText, configMatter } from "./matter.js";
33
35
  import { readAgentsMdKeys, patchFrontmatter } from "./agents-md.js";
@@ -2923,6 +2925,7 @@ export function isSplicedRecord(step) {
2923
2925
  // and every page reads whole, and gone with the run (deleteRun removes
2924
2926
  // runs/<run>/). The runner writes them, secrets already masked.
2925
2927
  const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
2928
+ const CALL_KIND = "call";
2926
2929
  function capturedCallFile(workspaceRoot, runId, callId) {
2927
2930
  if (!SAFE_ID.test(runId) || !SAFE_ID.test(callId) || callId.startsWith(".") || runId.startsWith("."))
2928
2931
  return null;
@@ -2930,10 +2933,16 @@ function capturedCallFile(workspaceRoot, runId, callId) {
2930
2933
  }
2931
2934
  /** Merge one part (the input, on the call; the output, on its completion)
2932
2935
  * into the call's file. */
2933
- export function writeCapturedCall(workspaceRoot, runId, part) {
2936
+ export function writeCapturedCall(workspaceRoot, runId, part, scope) {
2934
2937
  const file = capturedCallFile(workspaceRoot, runId, part.id);
2935
2938
  if (!file)
2936
2939
  return;
2940
+ // A row when the platform keeps them (FOL-126): the two parts of a call
2941
+ // merge in one statement, and the web's copies read it wherever they run.
2942
+ // `truncated` is only ever sent true, so a merge keeps it once set.
2943
+ const store = scope ? docStore(scope.tenant, scope.workspace) : null;
2944
+ if (store && scope)
2945
+ return store.merge(scope.tenant, scope.workspace, CALL_KIND, `${runId}/${part.id}`, part);
2937
2946
  let prev = {};
2938
2947
  try {
2939
2948
  prev = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -2954,12 +2963,22 @@ export function readCapturedCall(tenant, workspace, runId, callId) {
2954
2963
  const file = capturedCallFile(workspaceDir(tenant, workspace), runId, callId);
2955
2964
  if (!file)
2956
2965
  return null;
2966
+ const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, CALL_KIND, `${runId}/${callId}`), undefined);
2967
+ let onFile;
2957
2968
  try {
2958
- return JSON.parse(fs.readFileSync(file, "utf8"));
2969
+ onFile = JSON.parse(fs.readFileSync(file, "utf8"));
2959
2970
  }
2960
2971
  catch {
2961
- return null;
2972
+ /* none */
2973
+ }
2974
+ // A switch between a call's two parts leaves one part in each place: both, merged.
2975
+ if (row && onFile) {
2976
+ const merged = { ...onFile, ...row, truncated: Boolean(onFile.truncated || row.truncated) || undefined };
2977
+ if (!merged.truncated)
2978
+ delete merged.truncated;
2979
+ return merged;
2962
2980
  }
2981
+ return row ?? onFile ?? null;
2963
2982
  }
2964
2983
  export function runFilePath(tenant, workspace, runId) {
2965
2984
  assertSafeName(runId, "run id");
@@ -2999,6 +3018,9 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
2999
3018
  // and finishes — the other order left the content with nothing pointing
3000
3019
  // at it (Codex review, FOL-124).
3001
3020
  fs.rmSync(dir, { recursive: true, force: true });
3021
+ // Its captured calls kept as rows go the same way, before the record.
3022
+ if (SAFE_ID.test(runId))
3023
+ docRows(tenant, workspace)?.dropPrefix(tenant, workspace, CALL_KIND, `${runId}/`);
3002
3024
  if (port)
3003
3025
  port.runDelete(tenant, workspace, runId);
3004
3026
  else {
@@ -3013,25 +3035,25 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3013
3035
  }
3014
3036
  // Outputs published to the blob store (run-outputs.ts) are records and pins,
3015
3037
  // not files under dir: they go in the background, retried.
3016
- onRunRemoved?.(tenant, workspace, runId);
3038
+ RUN_HOOKS.removed?.(tenant, workspace, runId);
3017
3039
  if (!had)
3018
3040
  return true;
3019
3041
  // The retention window's prune (`pruned`) is policy, not a person erasing
3020
3042
  // history: no per-run ledger note. The charge stands either way.
3021
3043
  if (!opts.pruned)
3022
- onRunDeleted?.(tenant, workspace, runId);
3044
+ RUN_HOOKS.deleted?.(tenant, workspace, runId);
3023
3045
  return true;
3024
3046
  }
3025
- /** run-outputs.ts registers here (it imports this module). */
3026
- let onRunRemoved = null;
3047
+ /** One per process (process-state.ts): a run deleted from a route handler must
3048
+ * reach the hooks the boot registered. */
3049
+ const RUN_HOOKS = processState("run-hooks", () => ({ removed: null, deleted: undefined }));
3027
3050
  export function registerRunRemovedHook(fn) {
3028
- onRunRemoved = fn;
3051
+ RUN_HOOKS.removed = fn;
3029
3052
  }
3030
3053
  /** ledger.ts registers here — store cannot import it without a cycle, and
3031
3054
  * money must not depend on one. */
3032
- let onRunDeleted;
3033
3055
  export function registerRunDeletionListener(fn) {
3034
- onRunDeleted = fn;
3056
+ RUN_HOOKS.deleted = fn;
3035
3057
  }
3036
3058
  /**
3037
3059
  * What a run archived ON THE VOLUME: every file its agents left in outputs/,
@@ -3990,4 +4012,4 @@ registerTreeReader((tenant, scope) => {
3990
4012
  return [];
3991
4013
  }
3992
4014
  });
3993
- });
4015
+ }, "workspace");
@@ -10,6 +10,11 @@
10
10
  * of them silently changed the first time a secret was stored.
11
11
  */
12
12
  export declare function installKey(): string;
13
+ /** The hook's generation: the greater of the row's and the file's, so a
14
+ * rotation made while `records.docs_store` was on (a row) or off (the file)
15
+ * holds whichever way the switch stands now — an old URL never comes back.
16
+ * A database that cannot answer fails the call: guessing from the file could
17
+ * accept a token that was rotated away. */
13
18
  export declare function hookGeneration(tenant: string, workspace: string, flow: string): number;
14
19
  /** Invalidate a hook's URL and mint the next one. Returns the new path. */
15
20
  export declare function rotateWebhook(tenant: string, workspace: string, flow: string): string;
@@ -7,6 +7,7 @@ import path from "node:path";
7
7
  import { workspaceDir } from "./store.js";
8
8
  import { installKeyMaterial } from "./secrets.js";
9
9
  import crypto from "node:crypto";
10
+ import { docRows, docStore, quietly } from "./workspace-docs.js";
10
11
  /**
11
12
  * The install's secret key. Every derived token — flow hooks, git secrets,
12
13
  * approval links — hangs off this one value, so rotating it invalidates all
@@ -35,19 +36,36 @@ function readHooks(tenant, workspace) {
35
36
  return {};
36
37
  }
37
38
  }
39
+ /** The hook's generation: the greater of the row's and the file's, so a
40
+ * rotation made while `records.docs_store` was on (a row) or off (the file)
41
+ * holds whichever way the switch stands now — an old URL never comes back.
42
+ * A database that cannot answer fails the call: guessing from the file could
43
+ * accept a token that was rotated away. */
38
44
  export function hookGeneration(tenant, workspace, flow) {
39
- return readHooks(tenant, workspace)[flow]?.gen ?? 0;
45
+ const file = readHooks(tenant, workspace)[flow]?.gen ?? 0;
46
+ const row = docRows(tenant, workspace)?.get(tenant, workspace, HOOK_KIND, flow)?.gen ?? 0;
47
+ return Math.max(file, row);
40
48
  }
49
+ const HOOK_KIND = "hook";
50
+ const DELIVERY_KIND = "hook-delivery";
41
51
  /** Invalidate a hook's URL and mint the next one. Returns the new path. */
42
52
  export function rotateWebhook(tenant, workspace, flow) {
43
53
  const hooks = readHooks(tenant, workspace);
44
- hooks[flow] = { gen: (hooks[flow]?.gen ?? 0) + 1, rotatedAt: new Date().toISOString() };
45
54
  const file = hooksFile(tenant, workspace);
46
55
  // Into a workspace that exists, never making one (30 Oct 2026): the mkdir
47
56
  // here turned a rotate under a mistyped name into a workspace holding only
48
57
  // hooks.json, past the plan's workspace count.
49
58
  if (!fs.existsSync(path.dirname(file)))
50
59
  throw Object.assign(new Error(`workspace ${workspace} not found`), { status: 404 });
60
+ const rotatedAt = new Date().toISOString();
61
+ const store = docStore(tenant, workspace);
62
+ if (store) {
63
+ // One statement moves the row past both its own value and the file's.
64
+ store.raise(tenant, workspace, HOOK_KIND, flow, "gen", (hooks[flow]?.gen ?? 0) + 1, { rotatedAt });
65
+ return webhookPath(tenant, workspace, flow);
66
+ }
67
+ // On the file: still past whatever a row holds (hookGeneration reads both).
68
+ hooks[flow] = { gen: hookGeneration(tenant, workspace, flow) + 1, rotatedAt };
51
69
  fs.writeFileSync(file, JSON.stringify(hooks, null, 2));
52
70
  return webhookPath(tenant, workspace, flow);
53
71
  }
@@ -129,6 +147,9 @@ export function recordDelivery(tenant, workspace, delivery) {
129
147
  const file = deliveriesFile(tenant, workspace);
130
148
  if (!fs.existsSync(path.dirname(file)))
131
149
  return; // no workspace, nothing to log against
150
+ const store = docStore(tenant, workspace);
151
+ if (store)
152
+ return recordDeliveryRow(store, tenant, workspace, delivery);
132
153
  if (UNAUTHENTICATED.includes(delivery.outcome))
133
154
  return recordRefusal(file, tenant, workspace, delivery);
134
155
  fs.appendFileSync(file, JSON.stringify(delivery) + "\n");
@@ -146,6 +167,32 @@ export function recordDelivery(tenant, workspace, delivery) {
146
167
  // compaction is best-effort; the append already landed
147
168
  }
148
169
  }
170
+ /** The same log as rows: an append that keeps the newest KEEP, and a refusal
171
+ * folded into the newest entry when that is a refusal too (so a flood is one
172
+ * row). The fold is read-then-replace: two refusals at once may count one
173
+ * short, never push a real delivery out. */
174
+ function recordDeliveryRow(store, tenant, workspace, delivery) {
175
+ if (UNAUTHENTICATED.includes(delivery.outcome)) {
176
+ const [last] = store.tail(tenant, workspace, DELIVERY_KIND, 1);
177
+ const prev = last?.data;
178
+ if (last && prev && UNAUTHENTICATED.includes(prev.outcome)) {
179
+ store.replace(tenant, workspace, DELIVERY_KIND, last.id, foldRefusal(prev, delivery));
180
+ return;
181
+ }
182
+ }
183
+ store.append(tenant, workspace, DELIVERY_KIND, delivery, KEEP_DELIVERIES);
184
+ }
185
+ /** A refusal folded into the refusal before it. The flow name is not part of
186
+ * the match: it comes from the URL, so a flood that varies it would
187
+ * otherwise never collapse. */
188
+ function foldRefusal(last, delivery) {
189
+ return {
190
+ ...delivery,
191
+ count: (last.count ?? 1) + 1,
192
+ first: last.first ?? last.t,
193
+ ...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
194
+ };
195
+ }
149
196
  /**
150
197
  * A refusal — anyone's to send — never changes the workspace's directory: no
151
198
  * new file, no tmp file, no rename. The directory's mtime is the workspace's
@@ -201,12 +248,7 @@ function collapseInto(file, delivery) {
201
248
  }
202
249
  if (!UNAUTHENTICATED.includes(last.outcome))
203
250
  return false;
204
- const merged = {
205
- ...delivery,
206
- count: (last.count ?? 1) + 1,
207
- first: last.first ?? last.t,
208
- ...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
209
- };
251
+ const merged = foldRefusal(last, delivery);
210
252
  const line = Buffer.from(JSON.stringify(merged) + "\n");
211
253
  const at = Buffer.byteLength(end.slice(0, cut));
212
254
  const fd = fs.openSync(file, "r+");
@@ -220,6 +262,17 @@ function collapseInto(file, delivery) {
220
262
  return true;
221
263
  }
222
264
  export function readDeliveries(tenant, workspace, limit = 20) {
265
+ // Rows and the file both: the log may have been written either way.
266
+ const rows = quietly(() => docRows(tenant, workspace)?.tail(tenant, workspace, DELIVERY_KIND, limit) ?? [], []).map((r) => r.data);
267
+ const lines = readDeliveryLines(tenant, workspace, limit);
268
+ if (!rows.length)
269
+ return lines;
270
+ if (!lines.length)
271
+ return rows;
272
+ // Stable: equal times keep each source's own newest-first order.
273
+ return [...rows, ...lines].sort((a, b) => String(b.t).localeCompare(String(a.t))).slice(0, limit);
274
+ }
275
+ function readDeliveryLines(tenant, workspace, limit) {
223
276
  const file = deliveriesFile(tenant, workspace);
224
277
  if (!fs.existsSync(file))
225
278
  return [];
@@ -0,0 +1,9 @@
1
+ import { type DocsPort } from "./records.ts";
2
+ /** Rows to read: the port's, whatever the switch says. Null on a laptop, the
3
+ * CLI, and for a workspace whose records are still files. */
4
+ export declare function docRows(tenant: string, workspace: string): DocsPort | null;
5
+ /** Rows to write to, or null: write the folder. */
6
+ export declare function docStore(tenant: string, workspace: string): DocsPort | null;
7
+ /** A read that must not take the caller down with the database: these are
8
+ * logs and markers beside the work, never the work. */
9
+ export declare function quietly<T>(fn: () => T, fallback: T): T;
@@ -0,0 +1,31 @@
1
+ // Where a workspace's small state lives (FOL-126): rows through the records
2
+ // port when the platform registered one that has them, the folder otherwise.
3
+ //
4
+ // Two answers, because a switch must never lose what is already written:
5
+ // `docStore` is where a WRITE goes (rows only while `records.docs_store` is
6
+ // on), `docRows` is what a READ also asks (rows whenever the port has them,
7
+ // on or off). Every caller reads both places and keeps the newer; nothing is
8
+ // copied between them.
9
+ import { records } from "./records.js";
10
+ /** Rows to read: the port's, whatever the switch says. Null on a laptop, the
11
+ * CLI, and for a workspace whose records are still files. */
12
+ export function docRows(tenant, workspace) {
13
+ return records(tenant, workspace)?.docs ?? null;
14
+ }
15
+ /** Rows to write to, or null: write the folder. */
16
+ export function docStore(tenant, workspace) {
17
+ const port = records(tenant, workspace);
18
+ if (!port?.docs || !port.docsOn?.())
19
+ return null;
20
+ return port.docs;
21
+ }
22
+ /** A read that must not take the caller down with the database: these are
23
+ * logs and markers beside the work, never the work. */
24
+ export function quietly(fn, fallback) {
25
+ try {
26
+ return fn();
27
+ }
28
+ catch {
29
+ return fallback;
30
+ }
31
+ }
@@ -71,8 +71,9 @@ export interface StepWrite {
71
71
  * whose copy-out itself failed wrote nothing and commits nothing. A test run's
72
72
  * diverted state/ and storage/ writes never reach the folder and never here.
73
73
  *
74
- * Text only: a binary file is not versioned yet (see phase 3). Returns the
75
- * number of paths queued.
74
+ * Every file, whatever it holds: one that is not text rides as base64 (13 Nov
75
+ * 2026; until then a binary file was left out, and the head went stale against
76
+ * the folder). Returns the number of paths queued.
76
77
  */
77
78
  export declare function recordStepOutputs(tenant: string, workspace: string, writes: StepWrite[], meta: {
78
79
  runId?: string;
@@ -208,7 +209,10 @@ export declare function reconcileAll(opts?: {
208
209
  }>;
209
210
  /** Bring the heads to the folder's content in one revision: the way in for a
210
211
  * 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
+ * after a journal overflow. Every file scanFolder lists, whatever it holds
213
+ * (until 13 Nov 2026: only the text files the editor lists, so a binary file
214
+ * never reached a head and one the importer had put there was never updated
215
+ * or removed — a run staged from the head was handed files deleted days ago). */
212
216
  export declare function reconcileWorkspace(tenant: string, workspace: string, by?: string): Promise<PublishResult | null>;
213
217
  /** One file of the workspace as its heads hold it: head → manifest → blob.
214
218
  * Null when there is no such file (or no head yet). */
@@ -253,6 +257,9 @@ export declare function restoreRevision(tenant: string, workspace: string, to: s
253
257
  * fallback is the point: a head behind the folder, a missing blob, a store
254
258
  * that is down, a binary file the tree reader never recorded). */
255
259
  export declare function readHeadText(tenant: string, workspace: string, rel: string): Promise<string | null>;
260
+ /** The folder and the head were seen to disagree (a run's stage-in compares
261
+ * them): bring the head to the folder, in the background. */
262
+ export declare function requestReconcile(tenant: string, workspace: string): void;
256
263
  /** Every file of the workspace head with its bytes and mode (both heads), for
257
264
  * a stage-in; null when reads through revisions are off, there is no head,
258
265
  * or any blob could not be had (the caller then stages from the folder). */