@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
@@ -39,6 +39,7 @@ import { Readable } from "node:stream";
39
39
  import path from "node:path";
40
40
  import crypto from "node:crypto";
41
41
  import { dataRoot } from "./paths.ts";
42
+ import { processState } from "./process-state.ts";
42
43
  import { BlobNotFound, type BlobStore } from "./blob-store.ts";
43
44
  import { PUBLISH_PIN_TTL_MS, noPins, type BlobPins, type PinHolder } from "./blob-pins.ts";
44
45
  import {
@@ -181,14 +182,16 @@ export interface RunOutputsBackend {
181
182
  runMaxBytes: () => number;
182
183
  }
183
184
 
184
- let backend: RunOutputsBackend | null = null;
185
+ /** One per process (process-state.ts): the store the boot registered, and the
186
+ * clean-ups in flight, whichever copy of this module started them. */
187
+ const OUT = processState("run-outputs", () => ({ backend: null as RunOutputsBackend | null, background: new Set<Promise<unknown>>() }));
185
188
 
186
189
  /** Where run outputs are published, or null (every run archives to the volume). */
187
190
  export function setRunOutputsBackend(b: RunOutputsBackend | null): void {
188
- backend = b;
191
+ OUT.backend = b;
189
192
  registerRunRemovedHook(b ? runDeleted : null);
190
193
  }
191
- export const runOutputsBackend = (): RunOutputsBackend | null => backend;
194
+ export const runOutputsBackend = (): RunOutputsBackend | null => OUT.backend;
192
195
  function safeCall<T>(fn: () => T, fallback: T): T {
193
196
  try {
194
197
  return fn();
@@ -197,7 +200,7 @@ function safeCall<T>(fn: () => T, fallback: T): T {
197
200
  }
198
201
  }
199
202
  /** Publishing is on: a backend is registered and the operator has said so. */
200
- export const runOutputsOn = (): boolean => !!backend && safeCall(backend.enabled, false);
203
+ export const runOutputsOn = (): boolean => !!OUT.backend && safeCall(OUT.backend.enabled, false);
201
204
 
202
205
  const pinsOf = (b: RunOutputsBackend): BlobPins => b.pins ?? noPins;
203
206
 
@@ -407,7 +410,7 @@ export async function archiveRunOutputs(
407
410
  agent: string,
408
411
  dir: string,
409
412
  ): Promise<{ where: "store"; refused: RefusedOutput[] } | { where: "volume" }> {
410
- const b = backend;
413
+ const b = OUT.backend;
411
414
  if (!b || !runOutputsOn()) return { where: "volume" };
412
415
  try {
413
416
  const r = await publishRunOutputs(b, tenant, workspace, runId, agent, dir);
@@ -427,9 +430,9 @@ export async function archiveRunOutputs(
427
430
  const readDeps = (b: RunOutputsBackend): Deps => ({ blobs: b.blobs, revisions: undefined as unknown as Deps["revisions"] });
428
431
 
429
432
  async function recordsOf(tenant: string, workspace: string, runId: string): Promise<RunOutputRecord[]> {
430
- if (!backend) return [];
433
+ if (!OUT.backend) return [];
431
434
  try {
432
- return await backend.store.list(tenant, workspace, runId);
435
+ return await OUT.backend.store.list(tenant, workspace, runId);
433
436
  } catch (err) {
434
437
  opsError("run_outputs.list_failed", err, { tenant, workspace, run: runId });
435
438
  throw err;
@@ -442,7 +445,7 @@ export async function listRunOutputs(tenant: string, workspace: string, runId: s
442
445
  const recs = await recordsOf(tenant, workspace, runId);
443
446
  const out: RunOutputFile[] = [];
444
447
  for (const r of recs) {
445
- const m = await loadManifest(readDeps(backend!), tenant, r.manifest);
448
+ const m = await loadManifest(readDeps(OUT.backend!), tenant, r.manifest);
446
449
  for (const [p, e] of Object.entries(m.files)) out.push({ agent: r.agent, path: p, bytes: e.size });
447
450
  }
448
451
  const mine = new Set(recs.map((r) => r.agent));
@@ -461,12 +464,12 @@ export interface OpenedOutput {
461
464
  export async function openRunOutput(tenant: string, workspace: string, runId: string, agent: string, rel: string): Promise<OpenedOutput | null> {
462
465
  if (!agent || !rel || agent.includes("/") || agent.includes("\\") || agent.startsWith(".")) return null;
463
466
  const rec = (await recordsOf(tenant, workspace, runId)).find((r) => r.agent === agent);
464
- if (rec && backend) {
465
- const m = await loadManifest(readDeps(backend), tenant, rec.manifest);
467
+ if (rec && OUT.backend) {
468
+ const m = await loadManifest(readDeps(OUT.backend), tenant, rec.manifest);
466
469
  const e = m.files[rel.normalize("NFC")];
467
470
  if (!e) return null;
468
471
  const key = blobObjectKey(tenant, e.sha);
469
- const blobs = backend.blobs;
472
+ const blobs = OUT.backend.blobs;
470
473
  // A blob that is gone is an explicit failure (never an empty file); heading
471
474
  // here makes it one error before any byte is sent.
472
475
  if (!(await blobs.head(key))) throw new BlobMissing(`${agent}/${rel}`, e.sha);
@@ -524,14 +527,14 @@ export async function readRunOutput(tenant: string, workspace: string, runId: st
524
527
  /** A run is deleted: its records and their pins go. Throws when the store
525
528
  * cannot be reached (deleteRun's caller retries in the background). */
526
529
  export async function dropRunOutputs(tenant: string, workspace: string, runId: string): Promise<void> {
527
- const b = backend;
530
+ const b = OUT.backend;
528
531
  if (!b) return;
529
532
  await releaseRecords(b, await b.store.drop({ tenant, workspace, runId }));
530
533
  }
531
534
 
532
535
  /** A workspace is deleted: every run's records of it. */
533
536
  export async function dropWorkspaceOutputs(tenant: string, workspace: string): Promise<void> {
534
- const b = backend;
537
+ const b = OUT.backend;
535
538
  if (!b) return;
536
539
  await releaseRecords(b, await b.store.drop({ tenant, workspace }));
537
540
  }
@@ -539,7 +542,7 @@ export async function dropWorkspaceOutputs(tenant: string, workspace: string): P
539
542
  /** An account is deleted. Its pins are released by dropTenantRevisions (all pins
540
543
  * of the account); the records go here. */
541
544
  export async function dropTenantOutputs(tenant: string): Promise<void> {
542
- await backend?.store.drop({ tenant });
545
+ await OUT.backend?.store.drop({ tenant });
543
546
  }
544
547
 
545
548
  /** A workspace was renamed: the records follow (the pins are not keyed by
@@ -548,7 +551,7 @@ export async function dropTenantOutputs(tenant: string): Promise<void> {
548
551
  * store does both in its move too; the file store did not — review, 12 Nov
549
552
  * 2026). */
550
553
  export async function moveWorkspaceOutputs(tenant: string, from: string, to: string): Promise<void> {
551
- const b = backend;
554
+ const b = OUT.backend;
552
555
  if (!b) return;
553
556
  await releaseRecords(b, await b.store.drop({ tenant, workspace: to }));
554
557
  await b.store.move(tenant, from, to);
@@ -559,14 +562,14 @@ export async function moveWorkspaceOutputs(tenant: string, from: string, to: str
559
562
  * store that cannot say, or cannot be reached, counts 0 (a statement must not fail). */
560
563
  export function runOutputBytes(tenant: string, workspace: string): number {
561
564
  try {
562
- return backend?.store.bytes?.(tenant, workspace) ?? 0;
565
+ return OUT.backend?.store.bytes?.(tenant, workspace) ?? 0;
563
566
  } catch (err) {
564
567
  opsError("run_outputs.bytes_failed", err, { tenant, workspace }, "warn");
565
568
  return 0;
566
569
  }
567
570
  }
568
571
 
569
- const background = new Set<Promise<unknown>>();
572
+ const background = OUT.background;
570
573
  /** Wait for the retries a sync caller started (tests, process end). */
571
574
  export async function settleRunOutputs(): Promise<void> {
572
575
  while (background.size) await Promise.allSettled([...background]);
@@ -575,8 +578,8 @@ export async function settleRunOutputs(): Promise<void> {
575
578
  /** deleteRun cannot wait: do it now, and on a failure try again 1, 2, 4, 8 s
576
579
  * later, then say so (`run_outputs.drop_failed`; the blobs stay until a human looks). */
577
580
  export function runDeleted(tenant: string, workspace: string, runId: string): void {
578
- if (!backend) return;
579
- const b = backend;
581
+ if (!OUT.backend) return;
582
+ const b = OUT.backend;
580
583
  // The records dropped are kept across the retries: a release that fails
581
584
  // after the drop must not leave the next try with nothing to release
582
585
  // (review, 12 Nov 2026).
package/src/runner.ts CHANGED
@@ -118,7 +118,7 @@ import { buildScriptTools, parseScripts, type ExecutionContext, type ScriptSpec
118
118
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.ts";
119
119
  import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv, type PreparedRuntime, type RuntimeSpec } from "./runtime.ts";
120
120
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.ts";
121
- import { dataRoot } from "./paths.ts";
121
+ import { dataRoot, singleWorkspace } from "./paths.ts";
122
122
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.ts";
123
123
  import { readStorageBaseline, writeStorageBaseline } from "./step-state.ts";
124
124
  import { chooseExecutor, ensureImage } from "./container.ts";
@@ -2346,7 +2346,7 @@ async function runStep(
2346
2346
  captureFull = true;
2347
2347
  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` });
2348
2348
  }
2349
- if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact)) {
2349
+ 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, "..", "..")) })) {
2350
2350
  capturedChars += size;
2351
2351
  rest = { ...others, captured: true };
2352
2352
  }
@@ -24,6 +24,7 @@ import fs from "node:fs";
24
24
  import path from "node:path";
25
25
  import crypto from "node:crypto";
26
26
  import { accountDir } from "./store.ts";
27
+ import { processState } from "./process-state.ts";
27
28
 
28
29
  /** How a credential is identified here. A name alone is not enough: the
29
30
  * account and each workspace can hold a secret by the same name, and they
@@ -112,11 +113,12 @@ const fileStore: SecretHealthStore = {
112
113
  },
113
114
  };
114
115
 
115
- let store: SecretHealthStore = fileStore;
116
+ /** One per process (process-state.ts), so every bundle writes to the store the boot chose. */
117
+ const HEALTH = processState("secret-health", () => ({ store: fileStore as SecretHealthStore }));
116
118
 
117
119
  /** The platform's store (Postgres), or back to files with null. */
118
120
  export function setSecretHealthStore(next: SecretHealthStore | null): void {
119
- store = next ?? fileStore;
121
+ HEALTH.store = next ?? fileStore;
120
122
  }
121
123
 
122
124
  // Writes are queued and coalesced off the caller's path. The egress proxy
@@ -135,7 +137,7 @@ function drain(): void {
135
137
  for (const [tenant, updates] of pending) {
136
138
  pending.delete(tenant);
137
139
  try {
138
- await store.apply(tenant, updates);
140
+ await HEALTH.store.apply(tenant, updates);
139
141
  } catch {
140
142
  // best effort, always
141
143
  }
@@ -201,14 +203,14 @@ export function flushSecretHealth(): Promise<void> {
201
203
  * vault holds but nothing has used are simply absent, which is the honest
202
204
  * answer: unused is not the same as broken. */
203
205
  export async function secretHealth(tenant: string): Promise<HealthFile> {
204
- return store.read(tenant);
206
+ return HEALTH.store.read(tenant);
205
207
  }
206
208
 
207
209
  /** The credentials worth saying something about: refused the last time they
208
210
  * were used. Sorted worst first — most consecutive refusals, then oldest
209
211
  * last-success, which is the order someone would work through them. */
210
212
  export async function failingSecrets(tenant: string): Promise<{ name: string; record: SecretRecord }[]> {
211
- return Object.entries(await store.read(tenant))
213
+ return Object.entries(await HEALTH.store.read(tenant))
212
214
  .filter(([, r]) => r.last.outcome === "refused")
213
215
  .map(([name, record]) => ({ name, record }))
214
216
  .sort((a, b) => b.record.refusals - a.record.refusals || (a.record.lastAccepted ?? "").localeCompare(b.record.lastAccepted ?? ""));
@@ -218,7 +220,7 @@ export async function failingSecrets(tenant: string): Promise<{ name: string; re
218
220
  * where the old key's refusals say nothing about the new one. */
219
221
  export async function forgetSecretHealth(tenant: string, name: string): Promise<void> {
220
222
  try {
221
- await store.forget(tenant, name);
223
+ await HEALTH.store.forget(tenant, name);
222
224
  } catch {
223
225
  // best effort
224
226
  }
package/src/secrets.ts CHANGED
@@ -47,6 +47,7 @@ const tenantKey = (tenant: string) => platform.tenantKey(tenant);
47
47
  import crypto from "node:crypto";
48
48
  import { assertSafeName } from "./store.ts";
49
49
  import { trimSlashes } from "./paths.ts";
50
+ import { processState } from "./process-state.ts";
50
51
  import { SITE, siteCovers } from "./network.ts";
51
52
 
52
53
  const keyFile = () => path.join(dataRoot(), ".secret-key");
@@ -278,12 +279,13 @@ export interface VaultStore {
278
279
  forget?(tenant: string, workspace?: string): void;
279
280
  }
280
281
 
281
- let vaultStore: VaultStore | null = null;
282
+ /** One per process (process-state.ts): the dashboard's routes must see the store the boot registered. */
283
+ const VAULT = processState("vault", () => ({ store: null as VaultStore | null }));
282
284
  /** Register (or, with null, remove) the platform's vault store. None: files. */
283
285
  export function setVaultStore(store: VaultStore | null): void {
284
- vaultStore = store;
286
+ VAULT.store = store;
285
287
  }
286
- const inStore = (tenant: string, workspace?: string): VaultStore | null => (vaultStore?.on(tenant, workspace) ? vaultStore : null);
288
+ const inStore = (tenant: string, workspace?: string): VaultStore | null => (VAULT.store?.on(tenant, workspace) ? VAULT.store : null);
287
289
 
288
290
  function read(tenant: string, workspace?: string): SecretsFile {
289
291
  const store = inStore(tenant, workspace);
@@ -300,7 +302,7 @@ function mutateVault(tenant: string, workspace: string | undefined, change: (all
300
302
  wrote = next !== null;
301
303
  return next;
302
304
  });
303
- if (wrote) vaultStore?.forget?.(tenant, workspace);
305
+ if (wrote) VAULT.store?.forget?.(tenant, workspace);
304
306
  return after;
305
307
  }
306
308
 
@@ -877,7 +879,7 @@ function secretFiles(tenant: string): { file: string; workspace?: string }[] {
877
879
  }
878
880
  // Scopes in the platform's store have no file; they are named by where
879
881
  // the file would be (the result's `file` is a label, never opened).
880
- for (const workspace of vaultStore?.workspaces(tenant) ?? []) {
882
+ for (const workspace of VAULT.store?.workspaces(tenant) ?? []) {
881
883
  if (!out.some((x) => x.workspace === workspace)) out.push({ file: secretsFile(tenant, workspace), workspace });
882
884
  }
883
885
  return out;
@@ -1255,7 +1257,7 @@ function workspacesWithSecrets(tenant: string): string[] {
1255
1257
  }
1256
1258
  for (const n of names) if (fs.existsSync(path.join(base, n, "secrets.json"))) out.add(n);
1257
1259
  }
1258
- for (const n of vaultStore?.workspaces(tenant) ?? []) out.add(n);
1260
+ for (const n of VAULT.store?.workspaces(tenant) ?? []) out.add(n);
1259
1261
  return [...out];
1260
1262
  }
1261
1263
 
package/src/store.ts CHANGED
@@ -27,9 +27,11 @@ import type { BrowserPodOutcome } from "./browser-pod.ts";
27
27
  import fs from "node:fs";
28
28
  import path from "node:path";
29
29
  import { recordRevision, registerTreeReader, assertCommitId, workspaceGone, workspaceMoved, workspaceLifecycle, type RevisionFile } from "./history.ts";
30
+ import { processState } from "./process-state.ts";
30
31
  import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.ts";
31
32
  import { platform } from "./platform.ts";
32
33
  import { records } from "./records.ts";
34
+ import { docRows, docStore, quietly } from "./workspace-docs.ts";
33
35
  import { toLF, asRaw } from "./eol.ts";
34
36
  import type { TestEffect } from "./test-mode.ts";
35
37
  import type { OperatorEvent } from "./operator.ts";
@@ -4064,6 +4066,7 @@ export interface RunRecord {
4064
4066
  // runs/<run>/). The runner writes them, secrets already masked.
4065
4067
 
4066
4068
  const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
4069
+ const CALL_KIND = "call";
4067
4070
 
4068
4071
  function capturedCallFile(workspaceRoot: string, runId: string, callId: string): string | null {
4069
4072
  if (!SAFE_ID.test(runId) || !SAFE_ID.test(callId) || callId.startsWith(".") || runId.startsWith(".")) return null;
@@ -4072,9 +4075,14 @@ function capturedCallFile(workspaceRoot: string, runId: string, callId: string):
4072
4075
 
4073
4076
  /** Merge one part (the input, on the call; the output, on its completion)
4074
4077
  * into the call's file. */
4075
- export function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall): void {
4078
+ export function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall, scope?: { tenant: string; workspace: string }): void {
4076
4079
  const file = capturedCallFile(workspaceRoot, runId, part.id);
4077
4080
  if (!file) return;
4081
+ // A row when the platform keeps them (FOL-126): the two parts of a call
4082
+ // merge in one statement, and the web's copies read it wherever they run.
4083
+ // `truncated` is only ever sent true, so a merge keeps it once set.
4084
+ const store = scope ? docStore(scope.tenant, scope.workspace) : null;
4085
+ if (store && scope) return store.merge(scope.tenant, scope.workspace, CALL_KIND, `${runId}/${part.id}`, part as unknown as Record<string, unknown>);
4078
4086
  let prev: Partial<CapturedCall> = {};
4079
4087
  try {
4080
4088
  prev = JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
@@ -4093,11 +4101,20 @@ export function writeCapturedCall(workspaceRoot: string, runId: string, part: Ca
4093
4101
  export function readCapturedCall(tenant: string, workspace: string, runId: string, callId: string): CapturedCall | null {
4094
4102
  const file = capturedCallFile(workspaceDir(tenant, workspace), runId, callId);
4095
4103
  if (!file) return null;
4104
+ const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, CALL_KIND, `${runId}/${callId}`), undefined) as CapturedCall | undefined;
4105
+ let onFile: CapturedCall | undefined;
4096
4106
  try {
4097
- return JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
4107
+ onFile = JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
4098
4108
  } catch {
4099
- return null;
4109
+ /* none */
4110
+ }
4111
+ // A switch between a call's two parts leaves one part in each place: both, merged.
4112
+ if (row && onFile) {
4113
+ const merged: CapturedCall = { ...onFile, ...row, truncated: Boolean(onFile.truncated || row.truncated) || undefined };
4114
+ if (!merged.truncated) delete merged.truncated;
4115
+ return merged;
4100
4116
  }
4117
+ return row ?? onFile ?? null;
4101
4118
  }
4102
4119
 
4103
4120
  export function runFilePath(tenant: string, workspace: string, runId: string) {
@@ -4137,6 +4154,8 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4137
4154
  // and finishes — the other order left the content with nothing pointing
4138
4155
  // at it (Codex review, FOL-124).
4139
4156
  fs.rmSync(dir, { recursive: true, force: true });
4157
+ // Its captured calls kept as rows go the same way, before the record.
4158
+ if (SAFE_ID.test(runId)) docRows(tenant, workspace)?.dropPrefix(tenant, workspace, CALL_KIND, `${runId}/`);
4140
4159
  if (port) port.runDelete(tenant, workspace, runId);
4141
4160
  else {
4142
4161
  fs.rmSync(file, { force: true });
@@ -4150,25 +4169,27 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4150
4169
  }
4151
4170
  // Outputs published to the blob store (run-outputs.ts) are records and pins,
4152
4171
  // not files under dir: they go in the background, retried.
4153
- onRunRemoved?.(tenant, workspace, runId);
4172
+ RUN_HOOKS.removed?.(tenant, workspace, runId);
4154
4173
  if (!had) return true;
4155
4174
  // The retention window's prune (`pruned`) is policy, not a person erasing
4156
4175
  // history: no per-run ledger note. The charge stands either way.
4157
- if (!opts.pruned) onRunDeleted?.(tenant, workspace, runId);
4176
+ if (!opts.pruned) RUN_HOOKS.deleted?.(tenant, workspace, runId);
4158
4177
  return true;
4159
4178
  }
4160
4179
 
4161
4180
  /** run-outputs.ts registers here (it imports this module). */
4162
- let onRunRemoved: ((tenant: string, workspace: string, runId: string) => void) | null = null;
4163
- export function registerRunRemovedHook(fn: typeof onRunRemoved) {
4164
- onRunRemoved = fn;
4181
+ type RunHook = (tenant: string, workspace: string, runId: string) => void;
4182
+ /** One per process (process-state.ts): a run deleted from a route handler must
4183
+ * reach the hooks the boot registered. */
4184
+ const RUN_HOOKS = processState("run-hooks", () => ({ removed: null as RunHook | null, deleted: undefined as RunHook | undefined }));
4185
+ export function registerRunRemovedHook(fn: RunHook | null) {
4186
+ RUN_HOOKS.removed = fn;
4165
4187
  }
4166
4188
 
4167
4189
  /** ledger.ts registers here — store cannot import it without a cycle, and
4168
4190
  * money must not depend on one. */
4169
- let onRunDeleted: ((tenant: string, workspace: string, runId: string) => void) | undefined;
4170
- export function registerRunDeletionListener(fn: typeof onRunDeleted) {
4171
- onRunDeleted = fn;
4191
+ export function registerRunDeletionListener(fn: RunHook | undefined) {
4192
+ RUN_HOOKS.deleted = fn;
4172
4193
  }
4173
4194
 
4174
4195
  export interface RunOutputFile {
@@ -5312,4 +5333,4 @@ registerTreeReader((tenant, scope) => {
5312
5333
  return [];
5313
5334
  }
5314
5335
  });
5315
- });
5336
+ }, "workspace");
package/src/webhook.ts CHANGED
@@ -8,6 +8,8 @@ import path from "node:path";
8
8
  import { workspaceDir } from "./store.ts";
9
9
  import { installKeyMaterial } from "./secrets.ts";
10
10
  import crypto from "node:crypto";
11
+ import { docRows, docStore, quietly } from "./workspace-docs.ts";
12
+ import type { DocsPort } from "./records.ts";
11
13
 
12
14
  /**
13
15
  * The install's secret key. Every derived token — flow hooks, git secrets,
@@ -49,19 +51,37 @@ function readHooks(tenant: string, workspace: string): Record<string, HookState>
49
51
  }
50
52
  }
51
53
 
54
+ /** The hook's generation: the greater of the row's and the file's, so a
55
+ * rotation made while `records.docs_store` was on (a row) or off (the file)
56
+ * holds whichever way the switch stands now — an old URL never comes back.
57
+ * A database that cannot answer fails the call: guessing from the file could
58
+ * accept a token that was rotated away. */
52
59
  export function hookGeneration(tenant: string, workspace: string, flow: string): number {
53
- return readHooks(tenant, workspace)[flow]?.gen ?? 0;
60
+ const file = readHooks(tenant, workspace)[flow]?.gen ?? 0;
61
+ const row = (docRows(tenant, workspace)?.get(tenant, workspace, HOOK_KIND, flow) as HookState | undefined)?.gen ?? 0;
62
+ return Math.max(file, row);
54
63
  }
55
64
 
65
+ const HOOK_KIND = "hook";
66
+ const DELIVERY_KIND = "hook-delivery";
67
+
56
68
  /** Invalidate a hook's URL and mint the next one. Returns the new path. */
57
69
  export function rotateWebhook(tenant: string, workspace: string, flow: string): string {
58
70
  const hooks = readHooks(tenant, workspace);
59
- hooks[flow] = { gen: (hooks[flow]?.gen ?? 0) + 1, rotatedAt: new Date().toISOString() };
60
71
  const file = hooksFile(tenant, workspace);
61
72
  // Into a workspace that exists, never making one (30 Oct 2026): the mkdir
62
73
  // here turned a rotate under a mistyped name into a workspace holding only
63
74
  // hooks.json, past the plan's workspace count.
64
75
  if (!fs.existsSync(path.dirname(file))) throw Object.assign(new Error(`workspace ${workspace} not found`), { status: 404 });
76
+ const rotatedAt = new Date().toISOString();
77
+ const store = docStore(tenant, workspace);
78
+ if (store) {
79
+ // One statement moves the row past both its own value and the file's.
80
+ store.raise(tenant, workspace, HOOK_KIND, flow, "gen", (hooks[flow]?.gen ?? 0) + 1, { rotatedAt });
81
+ return webhookPath(tenant, workspace, flow);
82
+ }
83
+ // On the file: still past whatever a row holds (hookGeneration reads both).
84
+ hooks[flow] = { gen: hookGeneration(tenant, workspace, flow) + 1, rotatedAt };
65
85
  fs.writeFileSync(file, JSON.stringify(hooks, null, 2));
66
86
  return webhookPath(tenant, workspace, flow);
67
87
  }
@@ -184,6 +204,8 @@ const KEEP_DELIVERIES = 500;
184
204
  export function recordDelivery(tenant: string, workspace: string, delivery: HookDelivery) {
185
205
  const file = deliveriesFile(tenant, workspace);
186
206
  if (!fs.existsSync(path.dirname(file))) return; // no workspace, nothing to log against
207
+ const store = docStore(tenant, workspace);
208
+ if (store) return recordDeliveryRow(store, tenant, workspace, delivery);
187
209
  if (UNAUTHENTICATED.includes(delivery.outcome)) return recordRefusal(file, tenant, workspace, delivery);
188
210
  fs.appendFileSync(file, JSON.stringify(delivery) + "\n");
189
211
  // Bounded: compact to the newest KEEP when it doubles. Amortised cheap,
@@ -200,6 +222,34 @@ export function recordDelivery(tenant: string, workspace: string, delivery: Hook
200
222
  }
201
223
  }
202
224
 
225
+ /** The same log as rows: an append that keeps the newest KEEP, and a refusal
226
+ * folded into the newest entry when that is a refusal too (so a flood is one
227
+ * row). The fold is read-then-replace: two refusals at once may count one
228
+ * short, never push a real delivery out. */
229
+ function recordDeliveryRow(store: DocsPort, tenant: string, workspace: string, delivery: HookDelivery) {
230
+ if (UNAUTHENTICATED.includes(delivery.outcome)) {
231
+ const [last] = store.tail(tenant, workspace, DELIVERY_KIND, 1);
232
+ const prev = last?.data as HookDelivery | undefined;
233
+ if (last && prev && UNAUTHENTICATED.includes(prev.outcome)) {
234
+ store.replace(tenant, workspace, DELIVERY_KIND, last.id, foldRefusal(prev, delivery));
235
+ return;
236
+ }
237
+ }
238
+ store.append(tenant, workspace, DELIVERY_KIND, delivery, KEEP_DELIVERIES);
239
+ }
240
+
241
+ /** A refusal folded into the refusal before it. The flow name is not part of
242
+ * the match: it comes from the URL, so a flood that varies it would
243
+ * otherwise never collapse. */
244
+ function foldRefusal(last: HookDelivery, delivery: HookDelivery): HookDelivery {
245
+ return {
246
+ ...delivery,
247
+ count: (last.count ?? 1) + 1,
248
+ first: last.first ?? last.t,
249
+ ...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
250
+ };
251
+ }
252
+
203
253
  /**
204
254
  * A refusal — anyone's to send — never changes the workspace's directory: no
205
255
  * new file, no tmp file, no rename. The directory's mtime is the workspace's
@@ -252,12 +302,7 @@ function collapseInto(file: string, delivery: HookDelivery): boolean {
252
302
  return false;
253
303
  }
254
304
  if (!UNAUTHENTICATED.includes(last.outcome)) return false;
255
- const merged: HookDelivery = {
256
- ...delivery,
257
- count: (last.count ?? 1) + 1,
258
- first: last.first ?? last.t,
259
- ...(last.detail === "more than one flow name" || last.flow !== delivery.flow ? { detail: "more than one flow name" } : {}),
260
- };
305
+ const merged = foldRefusal(last, delivery);
261
306
  const line = Buffer.from(JSON.stringify(merged) + "\n");
262
307
  const at = Buffer.byteLength(end.slice(0, cut));
263
308
  const fd = fs.openSync(file, "r+");
@@ -271,6 +316,16 @@ function collapseInto(file: string, delivery: HookDelivery): boolean {
271
316
  }
272
317
 
273
318
  export function readDeliveries(tenant: string, workspace: string, limit = 20): HookDelivery[] {
319
+ // Rows and the file both: the log may have been written either way.
320
+ const rows = quietly(() => docRows(tenant, workspace)?.tail(tenant, workspace, DELIVERY_KIND, limit) ?? [], []).map((r) => r.data as HookDelivery);
321
+ const lines = readDeliveryLines(tenant, workspace, limit);
322
+ if (!rows.length) return lines;
323
+ if (!lines.length) return rows;
324
+ // Stable: equal times keep each source's own newest-first order.
325
+ return [...rows, ...lines].sort((a, b) => String(b.t).localeCompare(String(a.t))).slice(0, limit);
326
+ }
327
+
328
+ function readDeliveryLines(tenant: string, workspace: string, limit: number): HookDelivery[] {
274
329
  const file = deliveriesFile(tenant, workspace);
275
330
  if (!fs.existsSync(file)) return [];
276
331
  return fs
@@ -0,0 +1,33 @@
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
+
10
+ import { records, type DocsPort } from "./records.ts";
11
+
12
+ /** Rows to read: the port's, whatever the switch says. Null on a laptop, the
13
+ * CLI, and for a workspace whose records are still files. */
14
+ export function docRows(tenant: string, workspace: string): DocsPort | null {
15
+ return records(tenant, workspace)?.docs ?? null;
16
+ }
17
+
18
+ /** Rows to write to, or null: write the folder. */
19
+ export function docStore(tenant: string, workspace: string): DocsPort | null {
20
+ const port = records(tenant, workspace);
21
+ if (!port?.docs || !port.docsOn?.()) return null;
22
+ return port.docs;
23
+ }
24
+
25
+ /** A read that must not take the caller down with the database: these are
26
+ * logs and markers beside the work, never the work. */
27
+ export function quietly<T>(fn: () => T, fallback: T): T {
28
+ try {
29
+ return fn();
30
+ } catch {
31
+ return fallback;
32
+ }
33
+ }