@foldrun/core 20.3.0 → 21.0.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "20.3.0",
3
+ "version": "21.0.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/history.ts CHANGED
@@ -35,6 +35,7 @@
35
35
  // per save.
36
36
 
37
37
  import fs from "node:fs";
38
+ import { processState } from "./process-state.ts";
38
39
  import path from "node:path";
39
40
  import crypto from "node:crypto";
40
41
  import { dataRoot } from "./paths.ts";
@@ -49,10 +50,28 @@ import { dataRoot } from "./paths.ts";
49
50
  * made a minute later has everything.
50
51
  */
51
52
  type TreeReader = (tenant: string, scope: string) => RevisionFile[] | null;
52
- let readTree: TreeReader = () => null;
53
- export function registerTreeReader(fn: TreeReader) {
54
- const prev = readTree;
55
- readTree = (tenant, scope) => fn(tenant, scope) ?? prev(tenant, scope);
53
+ /** What is registered here is one per PROCESS (process-state.ts): the boot
54
+ * registers the journal and the view, and a route handler compiled apart from
55
+ * it must see them — until 13 Nov 2026 it did not, and a dashboard save was
56
+ * never journalled as a revision. */
57
+ const REG = processState("history", () => ({
58
+ readers: new Map<string, TreeReader>(),
59
+ journal: null as Journal | null,
60
+ onGone: null as ((tenant: string, workspace: string) => void) | null,
61
+ lifecycle: null as WorkspaceLifecycle | null,
62
+ view: null as RevisionView | null,
63
+ }));
64
+ /** `name` says which reader this is: every copy of a module registers its own,
65
+ * and the last one of a name replaces the others. */
66
+ export function registerTreeReader(fn: TreeReader, name = "default") {
67
+ REG.readers.set(name, fn);
68
+ }
69
+ function readTree(tenant: string, scope: string): RevisionFile[] | null {
70
+ for (const fn of REG.readers.values()) {
71
+ const tree = fn(tenant, scope);
72
+ if (tree) return tree;
73
+ }
74
+ return null;
56
75
  }
57
76
 
58
77
  /** The scope's tree as the registered readers see it (text files only), or null. */
@@ -66,20 +85,18 @@ export function currentTree(tenant: string, scope: string): RevisionFile[] | nul
66
85
  * Called after the legacy record is written; never throws into the writer.
67
86
  */
68
87
  type Journal = (tenant: string, scope: string, files: RevisionFile[], meta: { by: string; message: string; at: string }) => void;
69
- let journal: Journal | null = null;
70
88
  export function registerJournal(fn: Journal | null) {
71
- journal = fn;
89
+ REG.journal = fn;
72
90
  }
73
91
 
74
92
  /** A workspace was deleted: whatever a registered journal still holds for it
75
93
  * (queued changes, their files) goes too (FOL-126 phase 4). */
76
- let onGone: ((tenant: string, workspace: string) => void) | null = null;
77
94
  export function registerWorkspaceGone(fn: ((tenant: string, workspace: string) => void) | null) {
78
- onGone = fn;
95
+ REG.onGone = fn;
79
96
  }
80
97
  export function workspaceGone(tenant: string, workspace: string): void {
81
98
  try {
82
- onGone?.(tenant, workspace);
99
+ REG.onGone?.(tenant, workspace);
83
100
  } catch {
84
101
  // a journal that cannot be cleared now is cleared at the next boot (the replay discards a missing workspace)
85
102
  }
@@ -99,15 +116,14 @@ export interface WorkspaceLifecycle {
99
116
  move(tenant: string, from: string, to: string, rename: () => void): Promise<void>;
100
117
  moved(tenant: string, from: string, to: string): void;
101
118
  }
102
- let lifecycleHooks: WorkspaceLifecycle | null = null;
103
119
  export function registerWorkspaceLifecycle(l: WorkspaceLifecycle | null) {
104
- lifecycleHooks = l;
120
+ REG.lifecycle = l;
105
121
  }
106
- export const workspaceLifecycle = (): WorkspaceLifecycle | null => lifecycleHooks;
122
+ export const workspaceLifecycle = (): WorkspaceLifecycle | null => REG.lifecycle;
107
123
  /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
108
124
  export function workspaceMoved(tenant: string, from: string, to: string): void {
109
125
  try {
110
- lifecycleHooks?.moved(tenant, from, to);
126
+ REG.lifecycle?.moved(tenant, from, to);
111
127
  } catch {
112
128
  // finished by the next reconcile
113
129
  }
@@ -225,7 +241,7 @@ export function recordRevision(
225
241
  snapshot(tenant, scope, rev.id);
226
242
  fs.appendFileSync(path.join(dir, "index.jsonl"), `${JSON.stringify(line)}\n`);
227
243
  try {
228
- journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
244
+ REG.journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
229
245
  } catch {
230
246
  // the revision store is not allowed to break a save; workspace-revisions logs and retries
231
247
  }
@@ -556,9 +572,8 @@ export interface RevisionView {
556
572
  * the store has none. Optional: a view without it is asked through `list`. */
557
573
  get?(tenant: string, scope: string, id: string): Promise<RevisionSummary | null>;
558
574
  }
559
- let view: RevisionView | null = null;
560
575
  export function registerRevisionView(v: RevisionView | null) {
561
- view = v;
576
+ REG.view = v;
562
577
  }
563
578
 
564
579
  /** Revisions first, then the local entries older than the oldest of them.
@@ -572,7 +587,7 @@ async function combinedRows(
572
587
  const limit = opts.limit ?? 200;
573
588
  // The whole of `limit`, every page of it: the store's first page is not all
574
589
  // of history (FOL-152).
575
- const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit }) : null;
590
+ const mine = REG.view && scope !== "@library" ? await REG.view.list(tenant, scope, { ...opts, limit }) : null;
576
591
  let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
577
592
  if (restorableOnly) {
578
593
  const have = snapshotIds(tenant, scope);
@@ -603,24 +618,24 @@ export async function listRevisionsRestorable(tenant: string, scope: string, opt
603
618
 
604
619
  export async function readRevision(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null> {
605
620
  assertSafeName(id, "revision id");
606
- const fromStore = view && scope !== "@library" ? await view.read(tenant, scope, id, forPath) : null;
621
+ const fromStore = REG.view && scope !== "@library" ? await REG.view.read(tenant, scope, id, forPath) : null;
607
622
  return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
608
623
  }
609
624
 
610
625
  export async function snapshotAt(tenant: string, scope: string, id: string): Promise<{ path: string; content: string }[] | null> {
611
626
  assertSafeName(id, "revision id");
612
- const fromStore = view && scope !== "@library" ? await view.snapshot(tenant, scope, id) : null;
627
+ const fromStore = REG.view && scope !== "@library" ? await REG.view.snapshot(tenant, scope, id) : null;
613
628
  return fromStore ?? snapshotAtLocal(tenant, scope, id);
614
629
  }
615
630
 
616
631
  export async function hasSnapshot(tenant: string, scope: string, id: string): Promise<boolean> {
617
632
  assertSafeName(id, "revision id");
618
633
  if (hasSnapshotLocal(tenant, scope, id)) return true;
619
- if (!view || scope === "@library") return false;
634
+ if (!REG.view || scope === "@library") return false;
620
635
  // Looked up by id: a listing stops at a page, and a revision older than it
621
636
  // was "not restorable" until 9 Nov 2026 (FOL-152).
622
- if (view.get) return (await view.get(tenant, scope, id)) !== null;
623
- return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
637
+ if (REG.view.get) return (await REG.view.get(tenant, scope, id)) !== null;
638
+ return Boolean((await REG.view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
624
639
  }
625
640
 
626
641
  export async function headRevision(tenant: string, scope: string): Promise<RevisionSummary | null> {
@@ -632,8 +647,8 @@ export async function resolveRevision(tenant: string, scope: string, to: string,
632
647
  // An id in the store is one lookup; anything else (a date, a local id, a
633
648
  // commit) is answered from ALL of history — every page of the store, without
634
649
  // the changed paths, then the local entries.
635
- if ("id" in want && view?.get && scope !== "@library") {
636
- const hit = await view.get(tenant, scope, want.id);
650
+ if ("id" in want && REG.view?.get && scope !== "@library") {
651
+ const hit = await REG.view.get(tenant, scope, want.id);
637
652
  if (hit) return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
638
653
  }
639
654
  return pick(await combined(tenant, scope, { limit: Infinity, paths: false }, true), want);
@@ -20,11 +20,12 @@ import path from "node:path";
20
20
 
21
21
  /** What is stored: the whole entry (new content only, never the old text). */
22
22
  export interface JournalRecord {
23
- v: 1;
23
+ /** 2: some file is not text and rides as base64 (`enc`). */
24
+ v: 1 | 2;
24
25
  tenant: string;
25
26
  workspace: string;
26
27
  id: string;
27
- files: { path: string; before: null; after: string | null; base?: string | null; handed?: string | null }[];
28
+ files: { path: string; before: null; after: string | null; base?: string | null; handed?: string | null; enc?: "base64" }[];
28
29
  by: string;
29
30
  message: string;
30
31
  at: string;
package/src/library.ts CHANGED
@@ -437,7 +437,7 @@ registerTreeReader((tenant, scope) => {
437
437
  }
438
438
  }
439
439
  return out;
440
- });
440
+ }, "library");
441
441
 
442
442
 
443
443
 
@@ -0,0 +1,21 @@
1
+ // State that must be ONE per process, not one per copy of a module.
2
+ //
3
+ // A bundler that compiles the boot file and the route handlers apart (Next
4
+ // does) gives each bundle its own copy of every module they share. A
5
+ // registration made at boot — "revisions go to this store", "the vault is in
6
+ // the database" — then fills the boot bundle's copy, and a route handler reads
7
+ // its own, still empty: on dev (12 Nov 2026) a dashboard save was never
8
+ // journalled as a revision, and a run's outputs published to the object store
9
+ // answered "no such output" from the API, because only the worker (one bundle)
10
+ // saw the stores. platform.ts met this first, for its hooks.
11
+ //
12
+ // globalThis is the one thing every bundle in a process shares; a module keeps
13
+ // what it is told at boot (and the queues that go with it) in an object made
14
+ // here once.
15
+
16
+ /** The process's one object under `name`, made by `init` the first time. */
17
+ export function processState<T extends object>(name: string, init: () => T): T {
18
+ const g = globalThis as unknown as Record<symbol, object | undefined>;
19
+ const key = Symbol.for(`foldrun.state.${name}`);
20
+ return (g[key] ??= init()) as T;
21
+ }
@@ -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).
@@ -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,6 +27,7 @@ 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";
@@ -4150,25 +4151,27 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4150
4151
  }
4151
4152
  // Outputs published to the blob store (run-outputs.ts) are records and pins,
4152
4153
  // not files under dir: they go in the background, retried.
4153
- onRunRemoved?.(tenant, workspace, runId);
4154
+ RUN_HOOKS.removed?.(tenant, workspace, runId);
4154
4155
  if (!had) return true;
4155
4156
  // The retention window's prune (`pruned`) is policy, not a person erasing
4156
4157
  // history: no per-run ledger note. The charge stands either way.
4157
- if (!opts.pruned) onRunDeleted?.(tenant, workspace, runId);
4158
+ if (!opts.pruned) RUN_HOOKS.deleted?.(tenant, workspace, runId);
4158
4159
  return true;
4159
4160
  }
4160
4161
 
4161
4162
  /** 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;
4163
+ type RunHook = (tenant: string, workspace: string, runId: string) => void;
4164
+ /** One per process (process-state.ts): a run deleted from a route handler must
4165
+ * reach the hooks the boot registered. */
4166
+ const RUN_HOOKS = processState("run-hooks", () => ({ removed: null as RunHook | null, deleted: undefined as RunHook | undefined }));
4167
+ export function registerRunRemovedHook(fn: RunHook | null) {
4168
+ RUN_HOOKS.removed = fn;
4165
4169
  }
4166
4170
 
4167
4171
  /** ledger.ts registers here — store cannot import it without a cycle, and
4168
4172
  * 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;
4173
+ export function registerRunDeletionListener(fn: RunHook | undefined) {
4174
+ RUN_HOOKS.deleted = fn;
4172
4175
  }
4173
4176
 
4174
4177
  export interface RunOutputFile {
@@ -5312,4 +5315,4 @@ registerTreeReader((tenant, scope) => {
5312
5315
  return [];
5313
5316
  }
5314
5317
  });
5315
- });
5318
+ }, "workspace");