@foldrun/core 20.2.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.
@@ -8,7 +8,9 @@
8
8
  * made a minute later has everything.
9
9
  */
10
10
  type TreeReader = (tenant: string, scope: string) => RevisionFile[] | null;
11
- export declare function registerTreeReader(fn: TreeReader): void;
11
+ /** `name` says which reader this is: every copy of a module registers its own,
12
+ * and the last one of a name replaces the others. */
13
+ export declare function registerTreeReader(fn: TreeReader, name?: string): void;
12
14
  /** The scope's tree as the registered readers see it (text files only), or null. */
13
15
  export declare function currentTree(tenant: string, scope: string): RevisionFile[] | null;
14
16
  /**
@@ -22,6 +24,8 @@ type Journal = (tenant: string, scope: string, files: RevisionFile[], meta: {
22
24
  at: string;
23
25
  }) => void;
24
26
  export declare function registerJournal(fn: Journal | null): void;
27
+ /** A workspace was deleted: whatever a registered journal still holds for it
28
+ * (queued changes, their files) goes too (FOL-126 phase 4). */
25
29
  export declare function registerWorkspaceGone(fn: ((tenant: string, workspace: string) => void) | null): void;
26
30
  export declare function workspaceGone(tenant: string, workspace: string): void;
27
31
  /**
@@ -34,45 +34,62 @@
34
34
  // change, and storing them again would be the whole tree
35
35
  // per save.
36
36
  import fs from "node:fs";
37
+ import { processState } from "./process-state.js";
37
38
  import path from "node:path";
38
39
  import crypto from "node:crypto";
39
40
  import { dataRoot } from "./paths.js";
40
- let readTree = () => null;
41
- export function registerTreeReader(fn) {
42
- const prev = readTree;
43
- readTree = (tenant, scope) => fn(tenant, scope) ?? prev(tenant, scope);
41
+ /** What is registered here is one per PROCESS (process-state.ts): the boot
42
+ * registers the journal and the view, and a route handler compiled apart from
43
+ * it must see them — until 13 Nov 2026 it did not, and a dashboard save was
44
+ * never journalled as a revision. */
45
+ const REG = processState("history", () => ({
46
+ readers: new Map(),
47
+ journal: null,
48
+ onGone: null,
49
+ lifecycle: null,
50
+ view: null,
51
+ }));
52
+ /** `name` says which reader this is: every copy of a module registers its own,
53
+ * and the last one of a name replaces the others. */
54
+ export function registerTreeReader(fn, name = "default") {
55
+ REG.readers.set(name, fn);
56
+ }
57
+ function readTree(tenant, scope) {
58
+ for (const fn of REG.readers.values()) {
59
+ const tree = fn(tenant, scope);
60
+ if (tree)
61
+ return tree;
62
+ }
63
+ return null;
44
64
  }
45
65
  /** The scope's tree as the registered readers see it (text files only), or null. */
46
66
  export function currentTree(tenant, scope) {
47
67
  return readTree(tenant, scope);
48
68
  }
49
- let journal = null;
50
69
  export function registerJournal(fn) {
51
- journal = fn;
70
+ REG.journal = fn;
52
71
  }
53
72
  /** A workspace was deleted: whatever a registered journal still holds for it
54
73
  * (queued changes, their files) goes too (FOL-126 phase 4). */
55
- let onGone = null;
56
74
  export function registerWorkspaceGone(fn) {
57
- onGone = fn;
75
+ REG.onGone = fn;
58
76
  }
59
77
  export function workspaceGone(tenant, workspace) {
60
78
  try {
61
- onGone?.(tenant, workspace);
79
+ REG.onGone?.(tenant, workspace);
62
80
  }
63
81
  catch {
64
82
  // a journal that cannot be cleared now is cleared at the next boot (the replay discards a missing workspace)
65
83
  }
66
84
  }
67
- let lifecycleHooks = null;
68
85
  export function registerWorkspaceLifecycle(l) {
69
- lifecycleHooks = l;
86
+ REG.lifecycle = l;
70
87
  }
71
- export const workspaceLifecycle = () => lifecycleHooks;
88
+ export const workspaceLifecycle = () => REG.lifecycle;
72
89
  /** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
73
90
  export function workspaceMoved(tenant, from, to) {
74
91
  try {
75
- lifecycleHooks?.moved(tenant, from, to);
92
+ REG.lifecycle?.moved(tenant, from, to);
76
93
  }
77
94
  catch {
78
95
  // finished by the next reconcile
@@ -154,7 +171,7 @@ export function recordRevision(tenant, scope, files, meta = {}) {
154
171
  snapshot(tenant, scope, rev.id);
155
172
  fs.appendFileSync(path.join(dir, "index.jsonl"), `${JSON.stringify(line)}\n`);
156
173
  try {
157
- journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
174
+ REG.journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
158
175
  }
159
176
  catch {
160
177
  // the revision store is not allowed to break a save; workspace-revisions logs and retries
@@ -450,9 +467,8 @@ function changedIn(revs, from, to) {
450
467
  export function latestRevisionIdLocal(tenant, scope) {
451
468
  return listRevisionsLocal(tenant, scope, { limit: 1 })[0]?.id ?? null;
452
469
  }
453
- let view = null;
454
470
  export function registerRevisionView(v) {
455
- view = v;
471
+ REG.view = v;
456
472
  }
457
473
  /** Revisions first, then the local entries older than the oldest of them.
458
474
  * `stored` is which rows came from the store (every one a restore point). */
@@ -460,7 +476,7 @@ async function combinedRows(tenant, scope, opts, restorableOnly = false) {
460
476
  const limit = opts.limit ?? 200;
461
477
  // The whole of `limit`, every page of it: the store's first page is not all
462
478
  // of history (FOL-152).
463
- const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit }) : null;
479
+ const mine = REG.view && scope !== "@library" ? await REG.view.list(tenant, scope, { ...opts, limit }) : null;
464
480
  let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
465
481
  if (restorableOnly) {
466
482
  const have = snapshotIds(tenant, scope);
@@ -489,25 +505,25 @@ export async function listRevisionsRestorable(tenant, scope, opts = {}) {
489
505
  }
490
506
  export async function readRevision(tenant, scope, id, forPath) {
491
507
  assertSafeName(id, "revision id");
492
- const fromStore = view && scope !== "@library" ? await view.read(tenant, scope, id, forPath) : null;
508
+ const fromStore = REG.view && scope !== "@library" ? await REG.view.read(tenant, scope, id, forPath) : null;
493
509
  return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
494
510
  }
495
511
  export async function snapshotAt(tenant, scope, id) {
496
512
  assertSafeName(id, "revision id");
497
- const fromStore = view && scope !== "@library" ? await view.snapshot(tenant, scope, id) : null;
513
+ const fromStore = REG.view && scope !== "@library" ? await REG.view.snapshot(tenant, scope, id) : null;
498
514
  return fromStore ?? snapshotAtLocal(tenant, scope, id);
499
515
  }
500
516
  export async function hasSnapshot(tenant, scope, id) {
501
517
  assertSafeName(id, "revision id");
502
518
  if (hasSnapshotLocal(tenant, scope, id))
503
519
  return true;
504
- if (!view || scope === "@library")
520
+ if (!REG.view || scope === "@library")
505
521
  return false;
506
522
  // Looked up by id: a listing stops at a page, and a revision older than it
507
523
  // was "not restorable" until 9 Nov 2026 (FOL-152).
508
- if (view.get)
509
- return (await view.get(tenant, scope, id)) !== null;
510
- return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
524
+ if (REG.view.get)
525
+ return (await REG.view.get(tenant, scope, id)) !== null;
526
+ return Boolean((await REG.view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
511
527
  }
512
528
  export async function headRevision(tenant, scope) {
513
529
  return (await combined(tenant, scope, { limit: 1 }, true))[0] ?? null;
@@ -517,8 +533,8 @@ export async function resolveRevision(tenant, scope, to, now = Date.now()) {
517
533
  // An id in the store is one lookup; anything else (a date, a local id, a
518
534
  // commit) is answered from ALL of history — every page of the store, without
519
535
  // the changed paths, then the local entries.
520
- if ("id" in want && view?.get && scope !== "@library") {
521
- const hit = await view.get(tenant, scope, want.id);
536
+ if ("id" in want && REG.view?.get && scope !== "@library") {
537
+ const hit = await REG.view.get(tenant, scope, want.id);
522
538
  if (hit)
523
539
  return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
524
540
  }
@@ -1,6 +1,7 @@
1
1
  /** What is stored: the whole entry (new content only, never the old text). */
2
2
  export interface JournalRecord {
3
- v: 1;
3
+ /** 2: some file is not text and rides as base64 (`enc`). */
4
+ v: 1 | 2;
4
5
  tenant: string;
5
6
  workspace: string;
6
7
  id: string;
@@ -10,6 +11,7 @@ export interface JournalRecord {
10
11
  after: string | null;
11
12
  base?: string | null;
12
13
  handed?: string | null;
14
+ enc?: "base64";
13
15
  }[];
14
16
  by: string;
15
17
  message: string;
@@ -347,7 +347,7 @@ registerTreeReader((tenant, scope) => {
347
347
  }
348
348
  }
349
349
  return out;
350
- });
350
+ }, "library");
351
351
  /** The workspace folders "Move to shared" applies to: the library's kinds
352
352
  * but hooks, whose run.mjs is code a shared hook is made for on purpose. */
353
353
  export const SHAREABLE_KINDS = ["skills", "tools", "scripts", "knowledge", "memory"];
@@ -0,0 +1,2 @@
1
+ /** The process's one object under `name`, made by `init` the first time. */
2
+ export declare function processState<T extends object>(name: string, init: () => T): T;
@@ -0,0 +1,20 @@
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
+ /** The process's one object under `name`, made by `init` the first time. */
16
+ export function processState(name, init) {
17
+ const g = globalThis;
18
+ const key = Symbol.for(`foldrun.state.${name}`);
19
+ return (g[key] ??= init());
20
+ }
@@ -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).
@@ -39,6 +39,13 @@ export declare function parseRuntime(raw: unknown): RuntimeSpec | null;
39
39
  * say so, loudly, at build time — better than one of them silently winning.
40
40
  */
41
41
  export declare function mergeRuntimes(...specs: (RuntimeSpec | null | undefined)[]): RuntimeSpec | null;
42
+ /**
43
+ * The file a platform drops in a cache entry it unpacked from its object store
44
+ * (foldrun-platform runtime-archives.ts), naming the archive it came from. A
45
+ * rebuild removes it with the rest of the entry, so "ready, and no marker" is
46
+ * an entry built here, which is the one worth keeping for the next sandbox.
47
+ */
48
+ export declare const RUNTIME_FROM_STORE = ".from-store";
42
49
  export declare function fingerprint(spec: RuntimeSpec): string;
43
50
  /**
44
51
  * A tenant name that is safe as one path segment. Tenants come from account
@@ -123,6 +123,13 @@ export function mergeRuntimes(...specs) {
123
123
  merged.ignored = ignored;
124
124
  return merged;
125
125
  }
126
+ /**
127
+ * The file a platform drops in a cache entry it unpacked from its object store
128
+ * (foldrun-platform runtime-archives.ts), naming the archive it came from. A
129
+ * rebuild removes it with the rest of the entry, so "ready, and no marker" is
130
+ * an entry built here, which is the one worth keeping for the next sandbox.
131
+ */
132
+ export const RUNTIME_FROM_STORE = ".from-store";
126
133
  export function fingerprint(spec) {
127
134
  const canonical = JSON.stringify({
128
135
  python: spec.python ?? null,
@@ -1142,7 +1149,7 @@ FOLDRUN_SNAPSHOT_JS
1142
1149
  $AS sh -c '${PRUNE_SH}' sh "$S" "${cacheDir}" 2>/dev/null
1143
1150
  fi
1144
1151
  fi
1145
- printf '{"ok": %s, "exit": %s, "seconds": %s, "mode": "%s", "stale": %s, "packages": "%s", "refused": "%s", "unsaved": "%s"}\n' "$([ $RC -eq 0 ] && echo true || echo false)" "$RC" "$(( $(date +%s) - T0 ))" "$MODE" "$STALE" "$SYS" "$WHY" "$UNSAVED" > ${logDir}/system-install.json
1152
+ printf '{"ok": %s, "exit": %s, "seconds": %s, "mode": "%s", "stale": %s, "packages": "%s", "refused": "%s", "unsaved": "%s", "key": "%s"}\n' "$([ $RC -eq 0 ] && echo true || echo false)" "$RC" "$(( $(date +%s) - T0 ))" "$MODE" "$STALE" "$SYS" "$WHY" "$UNSAVED" "$KEY" > ${logDir}/system-install.json
1146
1153
  [ -n "$W" ] && rm -rf "$W"
1147
1154
  rm -rf /var/lib/apt/lists/* 2>/dev/null || true
1148
1155
  fi`;
@@ -1287,7 +1294,7 @@ function prepareLanguageRuntime(tenant, spec) {
1287
1294
  if (stale || !fs.existsSync(path.join(shared, ".ready"))) {
1288
1295
  // A clean slate: whatever a stale or half-finished build left behind is
1289
1296
  // exactly what must not be built on top of.
1290
- for (const leftover of [".ready", "venv", "node_modules", "package.json", "package-lock.json"]) {
1297
+ for (const leftover of [".ready", RUNTIME_FROM_STORE, "venv", "node_modules", "package.json", "package-lock.json"]) {
1291
1298
  fs.rmSync(path.join(shared, leftover), { recursive: true, force: true });
1292
1299
  }
1293
1300
  }
@@ -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
  }
@@ -1714,12 +1714,11 @@ export declare function deleteRun(tenant: string, workspace: string, runId: stri
1714
1714
  pruned?: boolean;
1715
1715
  }): boolean;
1716
1716
  /** 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;
1717
+ type RunHook = (tenant: string, workspace: string, runId: string) => void;
1718
+ export declare function registerRunRemovedHook(fn: RunHook | null): void;
1719
1719
  /** ledger.ts registers here — store cannot import it without a cycle, and
1720
1720
  * 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;
1721
+ export declare function registerRunDeletionListener(fn: RunHook | undefined): void;
1723
1722
  export interface RunOutputFile {
1724
1723
  agent: string;
1725
1724
  /** Relative to that agent's outputs/ — the name the agent wrote. */
package/dist/src/store.js CHANGED
@@ -25,6 +25,7 @@ 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";
@@ -3013,25 +3014,25 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3013
3014
  }
3014
3015
  // Outputs published to the blob store (run-outputs.ts) are records and pins,
3015
3016
  // not files under dir: they go in the background, retried.
3016
- onRunRemoved?.(tenant, workspace, runId);
3017
+ RUN_HOOKS.removed?.(tenant, workspace, runId);
3017
3018
  if (!had)
3018
3019
  return true;
3019
3020
  // The retention window's prune (`pruned`) is policy, not a person erasing
3020
3021
  // history: no per-run ledger note. The charge stands either way.
3021
3022
  if (!opts.pruned)
3022
- onRunDeleted?.(tenant, workspace, runId);
3023
+ RUN_HOOKS.deleted?.(tenant, workspace, runId);
3023
3024
  return true;
3024
3025
  }
3025
- /** run-outputs.ts registers here (it imports this module). */
3026
- let onRunRemoved = null;
3026
+ /** One per process (process-state.ts): a run deleted from a route handler must
3027
+ * reach the hooks the boot registered. */
3028
+ const RUN_HOOKS = processState("run-hooks", () => ({ removed: null, deleted: undefined }));
3027
3029
  export function registerRunRemovedHook(fn) {
3028
- onRunRemoved = fn;
3030
+ RUN_HOOKS.removed = fn;
3029
3031
  }
3030
3032
  /** ledger.ts registers here — store cannot import it without a cycle, and
3031
3033
  * money must not depend on one. */
3032
- let onRunDeleted;
3033
3034
  export function registerRunDeletionListener(fn) {
3034
- onRunDeleted = fn;
3035
+ RUN_HOOKS.deleted = fn;
3035
3036
  }
3036
3037
  /**
3037
3038
  * What a run archived ON THE VOLUME: every file its agents left in outputs/,
@@ -3990,4 +3991,4 @@ registerTreeReader((tenant, scope) => {
3990
3991
  return [];
3991
3992
  }
3992
3993
  });
3993
- });
3994
+ }, "workspace");
@@ -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). */