@foldrun/core 23.0.2 → 23.0.4

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.
@@ -14,6 +14,11 @@ export declare const CAPTURE_SLACK = 4096;
14
14
  * secret would redact half the language, and anything that short is not one.
15
15
  */
16
16
  export declare function redactionsFor(secrets: Record<string, string | undefined>): [string, string][];
17
+ /** A value's encoded forms, each long enough to be its own and nothing else's
18
+ * (12 characters or more). Base64: the characters that come from the value's
19
+ * bytes alone at each alignment, so the form matches inside a longer
20
+ * encoding whatever came before or after the value. */
21
+ export declare function encodedForms(v: string): string[];
17
22
  /** Masked, then cut to the cap. */
18
23
  export declare function maskCall(text: string, redactSecrets: (text: string) => string): {
19
24
  text: string;
@@ -23,10 +23,21 @@ export const CAPTURE_SLACK = 4096;
23
23
  */
24
24
  export function redactionsFor(secrets) {
25
25
  const out = new Map();
26
- const add = (v, name) => {
26
+ const put = (v, name) => {
27
27
  if (v.length >= 8 && !out.has(v))
28
28
  out.set(v, name);
29
29
  };
30
+ // Every value also as a tool prints it encoded (Kousha's review, 14 Nov
31
+ // 2026): hex, URL-encoded, and base64 — standard and URL-safe, at each of
32
+ // the three byte alignments it can take inside a longer encoded text
33
+ // (`base64 <<< "user:$TOKEN"`, a JWT segment, a Basic header the agent built).
34
+ const add = (v, name) => {
35
+ if (v.length < 8)
36
+ return;
37
+ put(v, name);
38
+ for (const e of encodedForms(v))
39
+ put(e, name);
40
+ };
30
41
  for (const [name, raw] of Object.entries(secrets)) {
31
42
  if (typeof raw !== "string")
32
43
  continue;
@@ -85,6 +96,39 @@ export function redactionsFor(secrets) {
85
96
  }
86
97
  return [...out.entries()].sort((a, b) => b[0].length - a[0].length);
87
98
  }
99
+ /** A value's encoded forms, each long enough to be its own and nothing else's
100
+ * (12 characters or more). Base64: the characters that come from the value's
101
+ * bytes alone at each alignment, so the form matches inside a longer
102
+ * encoding whatever came before or after the value. */
103
+ export function encodedForms(v) {
104
+ const bytes = Buffer.from(v, "utf8");
105
+ const forms = new Set([bytes.toString("hex"), bytes.toString("hex").toUpperCase()]);
106
+ try {
107
+ const pct = encodeURIComponent(v);
108
+ forms.add(pct);
109
+ // a form body writes a space as `+`, and some encoders write the escapes
110
+ // in lower case (`%2f`); all four spellings are the same secret
111
+ const plus = pct.replace(/%20/g, "+");
112
+ forms.add(plus);
113
+ const lower = (t) => t.replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase());
114
+ forms.add(lower(pct));
115
+ forms.add(lower(plus));
116
+ }
117
+ catch {
118
+ // a lone surrogate: no URL form
119
+ }
120
+ for (let pad = 0; pad < 3; pad++) {
121
+ const b64 = Buffer.concat([Buffer.alloc(pad), bytes]).toString("base64").replace(/=+$/, "");
122
+ // character i holds bits [6i, 6i + 6); the value's are [8·pad, 8·(pad + n))
123
+ const first = Math.ceil((8 * pad) / 6);
124
+ const last = Math.floor((8 * (pad + bytes.length)) / 6); // exclusive
125
+ const part = b64.slice(first, last);
126
+ forms.add(part);
127
+ forms.add(part.replace(/\+/g, "-").replace(/\//g, "_"));
128
+ }
129
+ forms.delete(v);
130
+ return [...forms].filter((f) => f.length >= 12);
131
+ }
88
132
  // A private key's whole block — scan.ts names a key header and leaves the
89
133
  // body, which is right for a finding and wrong for a stored output.
90
134
  // Unterminated too: a key cut short, or printed without its END line, is
@@ -17,10 +17,14 @@
17
17
  // TEMPORARY, remove at cutover (phase 9): a write that fails with an error
18
18
  // (store down, database refuses) falls back to the volume file and logs
19
19
  // `captured_calls.fallback`. At cutover that branch becomes "the call is not
20
- // recorded, and the event says so".
20
+ // recorded, and the event says so". Already so on a pod whose data root is its
21
+ // own disk (localDisk()): the volume file would be lost with the pod, so the
22
+ // call is logged `captured_calls.not_recorded` and not written (ops log only;
23
+ // the capture sink has no run to put an event on).
21
24
  import { records } from "./records.js";
22
25
  import { blobObjectKey, sha256Hex } from "./manifest.js";
23
26
  import { opsError } from "./ops-log.js";
27
+ import { localDisk } from "./mirror-base.js";
24
28
  import { BlobNotFound, readAll } from "./blob-store.js";
25
29
  import { writeCapturedCall, readCapturedCall, registerRunRemovedHook } from "./store.js";
26
30
  import { processState } from "./process-state.js";
@@ -75,6 +79,8 @@ const sessions = new WeakMap();
75
79
  async function storeCall(ctx, call) {
76
80
  const a = active(ctx.tenant, ctx.workspace);
77
81
  const fall = (err) => {
82
+ if (localDisk())
83
+ return opsError("captured_calls.not_recorded", err, { tenant: ctx.tenant, workspace: ctx.workspace, runId: ctx.runId, callId: call.id });
78
84
  // TEMPORARY (see the header): the volume copy, so the call is not lost.
79
85
  opsError("captured_calls.fallback", err, { tenant: ctx.tenant, workspace: ctx.workspace, runId: ctx.runId, callId: call.id });
80
86
  try {
@@ -13,10 +13,20 @@ export interface MirrorBase {
13
13
  * (`revisions.mirror`). Off on a laptop, in the CLI and until switched on. */
14
14
  export declare function setMirrorGate(fn: (() => boolean) | null): void;
15
15
  export declare function mirrorOn(): boolean;
16
+ /** The platform says whether this pod's data root is its own disk
17
+ * (FOLDRUN_DATA_LOCAL=1, an emptyDir) rather than a volume every pod shares.
18
+ * On such a disk a folder that is missing or older than the heads says
19
+ * nothing about the workspace: it may simply not be synced here, or (mirror
20
+ * off) never will be. Off on a laptop, in the CLI and on the shared volume. */
21
+ export declare function setLocalDiskGate(fn: (() => boolean) | null): void;
22
+ export declare function localDisk(): boolean;
16
23
  export declare const mirrorBaseFile: (tenant: string, workspace: string) => string | null;
17
24
  export declare function readMirrorBase(tenant: string, workspace: string): MirrorBase | null;
18
25
  export declare function writeMirrorBase(tenant: string, workspace: string, base: MirrorBase): void;
19
26
  export declare function dropMirrorBase(tenant: string, workspace: string): void;
27
+ export declare function headsSeen(tenant: string, workspace: string): boolean;
28
+ export declare function noteHeadsSeen(tenant: string, workspace: string): void;
29
+ export declare function dropHeadsSeen(tenant: string, workspace: string): void;
20
30
  /** Every workspace this pod holds a copy of, by its base files. */
21
31
  export declare function mirroredWorkspaces(): {
22
32
  tenant: string;
@@ -26,6 +26,23 @@ export function mirrorOn() {
26
26
  return false;
27
27
  }
28
28
  }
29
+ const LOCAL = processState("local-disk-gate", () => ({ on: (() => false) }));
30
+ /** The platform says whether this pod's data root is its own disk
31
+ * (FOLDRUN_DATA_LOCAL=1, an emptyDir) rather than a volume every pod shares.
32
+ * On such a disk a folder that is missing or older than the heads says
33
+ * nothing about the workspace: it may simply not be synced here, or (mirror
34
+ * off) never will be. Off on a laptop, in the CLI and on the shared volume. */
35
+ export function setLocalDiskGate(fn) {
36
+ LOCAL.on = fn ?? (() => false);
37
+ }
38
+ export function localDisk() {
39
+ try {
40
+ return LOCAL.on();
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
29
46
  const SAFE = /^(?:@library|[A-Za-z0-9][A-Za-z0-9_.-]{0,127})$/;
30
47
  export const mirrorBaseFile = (tenant, workspace) => SAFE.test(tenant) && SAFE.test(workspace) ? path.join(dataRoot(), ".mirror", tenant, `${workspace}.json`) : null;
31
48
  export function readMirrorBase(tenant, workspace) {
@@ -52,6 +69,32 @@ export function dropMirrorBase(tenant, workspace) {
52
69
  const f = mirrorBaseFile(tenant, workspace);
53
70
  if (f)
54
71
  fs.rmSync(f, { force: true });
72
+ dropHeadsSeen(tenant, workspace);
73
+ }
74
+ // "This pod has seen heads for the workspace": a marker beside the base, kept
75
+ // whether or not the mirror is on (own disk, mirror off, has no base). A folder
76
+ // here whose heads are gone and which carries it is a stale copy of a workspace
77
+ // deleted elsewhere, not a new workspace: its first revision is not published.
78
+ // A workspace made on this pod has no marker until its first revision lands.
79
+ const seenFile = (tenant, workspace) => {
80
+ const f = mirrorBaseFile(tenant, workspace);
81
+ return f ? f.replace(/\.json$/, ".seen") : null;
82
+ };
83
+ export function headsSeen(tenant, workspace) {
84
+ const f = seenFile(tenant, workspace);
85
+ return !!f && fs.existsSync(f);
86
+ }
87
+ export function noteHeadsSeen(tenant, workspace) {
88
+ const f = seenFile(tenant, workspace);
89
+ if (!f || fs.existsSync(f))
90
+ return;
91
+ fs.mkdirSync(path.dirname(f), { recursive: true });
92
+ fs.writeFileSync(f, "");
93
+ }
94
+ export function dropHeadsSeen(tenant, workspace) {
95
+ const f = seenFile(tenant, workspace);
96
+ if (f)
97
+ fs.rmSync(f, { force: true });
55
98
  }
56
99
  /** Every workspace this pod holds a copy of, by its base files. */
57
100
  export function mirroredWorkspaces() {
@@ -29,6 +29,9 @@
29
29
  // are copied to the volume as before and the failure is logged
30
30
  // (`run_outputs.fallback`). A laptop or an install with no backend always
31
31
  // uses the volume: it is a local disk there, not the thing being retired.
32
+ // Not on a pod whose data root is its own disk (localDisk(), an emptyDir): the
33
+ // volume goes with the pod, so there a failed publish fails the archive
34
+ // (`run_outputs.publish_failed`) instead of keeping nothing.
32
35
  //
33
36
  // Reads (`listRunOutputs`, `openRunOutput`) ask the records first and the
34
37
  // volume second, per agent, so a run archived either way stays readable
@@ -44,6 +47,7 @@ import { PUBLISH_PIN_TTL_MS, noPins } from "./blob-pins.js";
44
47
  import { MAX_MANIFEST_FILES, MODE_EXEC, MODE_FILE, assertManifest, assertManifestPath, blobObjectKey, canonicalManifest, manifestId, manifestObjectKey, sha256Hex, } from "./manifest.js";
45
48
  import { BlobMissing, loadManifest } from "./publish.js";
46
49
  import { opsError } from "./ops-log.js";
50
+ import { localDisk } from "./mirror-base.js";
47
51
  import { refusalText } from "./run-output-refusal.js";
48
52
  export { refusalText };
49
53
  import { listRunOutputsOnVolume, registerRunRemovedHook, runOutputPathOnVolume } from "./store.js";
@@ -338,6 +342,11 @@ export async function archiveRunOutputs(tenant, workspace, runId, agent, dir) {
338
342
  return { where: "store", refused: r.refused };
339
343
  }
340
344
  catch (err) {
345
+ // On a pod's own disk the volume copy would be lost with the pod: fail.
346
+ if (localDisk()) {
347
+ opsError("run_outputs.publish_failed", err, { tenant, workspace, run: runId, agent });
348
+ throw err;
349
+ }
341
350
  // TEMPORARY (EFS cutover, FOL-126 phase 9): an error publishing is not a
342
351
  // reason to lose the run's outputs while the volume still exists. Remove
343
352
  // this branch with the volume; then a failed publish fails the archive.
@@ -4792,7 +4792,16 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
4792
4792
  const from = path.join(runRoot, "agents", agent, "outputs");
4793
4793
  if (!fs.existsSync(from) || fs.readdirSync(from).length === 0)
4794
4794
  continue;
4795
- const done = await archiveRunOutputs(tenant, workspace, run.id, agent, from);
4795
+ let done;
4796
+ try {
4797
+ done = await archiveRunOutputs(tenant, workspace, run.id, agent, from);
4798
+ }
4799
+ catch {
4800
+ // Only on a pod's own disk (localDisk()), where there is no volume to keep them on.
4801
+ const last = run.steps.findLast((s) => s.status !== "pending") ?? run.steps[0];
4802
+ last?.events.push({ t: new Date().toISOString(), type: "error", text: `outputs: ${agent}'s outputs were not kept: the store refused them` });
4803
+ continue;
4804
+ }
4796
4805
  if (done.where === "store")
4797
4806
  noteRefused(run, done.refused);
4798
4807
  else
package/dist/src/store.js CHANGED
@@ -339,6 +339,11 @@ export function isPlatformPath(rel) {
339
339
  return true;
340
340
  if (norm === "trigger-log.jsonl.tmp")
341
341
  return true;
342
+ // The revision mirror's in-flight file (`<name>.<pid>.<hex>.mirror-tmp`,
343
+ // workspace-revisions.ts): a crash between its write and its rename leaves
344
+ // it, and the next scan would publish half a file as the author's.
345
+ if (norm.endsWith(".mirror-tmp"))
346
+ return true;
342
347
  if (ENGINE_HOME_RE.test(norm))
343
348
  return true;
344
349
  return norm === "runs" || norm.startsWith("runs/") || norm === ".foldrun" || norm.startsWith(".foldrun/");
@@ -2298,7 +2303,7 @@ export function accountFileSealed(rel) {
2298
2303
  * function is to refuse the person who clicked them, which is noise wearing
2299
2304
  * honesty's clothes. `accountFileSealed` still refuses these if a path is
2300
2305
  * constructed directly — the listing hides them, the reader guards them. */
2301
- const ACCOUNT_BOOKKEEPING = /^(billed\/|once\/|topups\/|ledger\.jsonl$|oauth-clients\.json$|billing\.json$|oauth-connections\.json$|secret-health\.json$|[^/]+\.json\.imported-[\d-]+$)|(^|\/)runs\/|(^|\/)secrets\.json(\.[^/]+)?$/;
2306
+ const ACCOUNT_BOOKKEEPING = /^(billed\/|once\/|topups\/|ledger\.jsonl$|oauth-clients\.json$|billing\.json$|oauth-connections\.json$|secret-health\.json$|[^/]+\.json\.imported-[\d-]+$)|(^|\/)runs\/|(^|\/)secrets\.json(\.[^/]+)?$|\.mirror-tmp$/;
2302
2307
  /**
2303
2308
  * The account directory as it actually is on disk.
2304
2309
  *
@@ -232,11 +232,31 @@ export declare function reconcileWorkspace(tenant: string, workspace: string, by
232
232
  export declare function syncFromHeads(tenant: string, workspace: string): Promise<"unchanged" | "synced" | "skipped" | "removed" | "absent">;
233
233
  /** Every workspace with heads, and every copy here whose heads are gone. One
234
234
  * failure does not stop the rest. */
235
+ /**
236
+ * One account's folders brought level with the heads, now — for a request
237
+ * that must see what another pod just wrote (14 Nov 2026: a workspace made
238
+ * on one web pod answered 404 on the other for up to the mirror's poll; a
239
+ * deleted one stayed listed ~10 s). The same per-workspace sync the loop
240
+ * runs, for this tenant only: its heads, and its mirrored folders with no
241
+ * head (deleted elsewhere). A failure is logged and counted, never thrown —
242
+ * the caller answers from the copy it has.
243
+ */
244
+ export declare function syncTenantFromHeads(tenant: string): Promise<{
245
+ synced: number;
246
+ removed: number;
247
+ failed: number;
248
+ }>;
235
249
  export declare function syncAllFromHeads(): Promise<{
236
250
  synced: number;
237
251
  removed: number;
238
252
  failed: number;
239
253
  }>;
254
+ /** Every account that still has revision state: a head in the store, a journal
255
+ * entry in any journal store, or changes queued in this process. A pod that is
256
+ * about to remove an account's folder asks first — such an account has work
257
+ * not yet in a head, or a history somebody can still read. Throws when a store
258
+ * cannot be read: the caller must then remove nothing. */
259
+ export declare function tenantsWithRevisionState(): Promise<Set<string>>;
240
260
  /** One file of the workspace as its heads hold it: head → manifest → blob.
241
261
  * Null when there is no such file (or no head yet). */
242
262
  export declare function readAtHead(tenant: string, workspace: string, rel: string): Promise<Buffer | null>;
@@ -43,7 +43,7 @@ import { opsError, opsLog } from "./ops-log.js";
43
43
  import { readAll, fileSource, BlobNotFound } from "./blob-store.js";
44
44
  import { fsJournalStore } from "./journal-store.js";
45
45
  import { AUTHORED_DIRS, AUTHORED_ROOT_FILES, STATE_DIRS, assertManifestPath, blobObjectKey, diffManifests, emptyManifest, entryId, EMPTY_MANIFEST_ID, MODE_EXEC, MODE_FILE, sha256Hex, sideOf, } from "./manifest.js";
46
- import { mirrorOn, readMirrorBase, writeMirrorBase, dropMirrorBase, mirroredWorkspaces } from "./mirror-base.js";
46
+ import { mirrorOn, localDisk, readMirrorBase, writeMirrorBase, dropMirrorBase, mirroredWorkspaces, headsSeen, noteHeadsSeen, dropHeadsSeen } from "./mirror-base.js";
47
47
  import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError } from "./publish.js";
48
48
  import { OpIdReused } from "./revision-store.js";
49
49
  import { pruneStateRevisions } from "./state-retention.js";
@@ -323,10 +323,15 @@ async function drainOne(k) {
323
323
  while (q && q.length && S.backend) {
324
324
  const entry = q[0];
325
325
  // The workspace was deleted while this waited (or retried): nothing to
326
- // publish, and nothing for a later boot to replay.
326
+ // publish, and nothing for a later boot to replay. On this pod's own disk
327
+ // (FOLDRUN_DATA_LOCAL=1) a missing folder is only one not synced here: the
328
+ // entry leaves this pod's queue but stays in the shared store, for a pod
329
+ // that has the folder (Kousha's review, 14 Nov 2026). A real delete takes
330
+ // the store's entries with it (dropJournal).
327
331
  if (!fs.existsSync(folderOf(tenant, workspace))) {
328
332
  q.shift();
329
- forget(tenant, workspace, entry);
333
+ if (!localDisk())
334
+ forget(tenant, workspace, entry);
330
335
  continue;
331
336
  }
332
337
  try {
@@ -341,8 +346,10 @@ async function drainOne(k) {
341
346
  if (err instanceof PublishError && err.code === "gone") {
342
347
  // The folder is gone (deleted or renamed, here or on another pod): the
343
348
  // change has nowhere to go, and nothing should be recorded under the name.
349
+ // On this pod's own disk, kept in the store as above.
344
350
  q.shift();
345
- forget(tenant, workspace, entry);
351
+ if (!localDisk())
352
+ forget(tenant, workspace, entry);
346
353
  continue;
347
354
  }
348
355
  if (permanent(err)) {
@@ -553,6 +560,7 @@ export async function dropWorkspaceRevisions(tenant, workspace, remove) {
553
560
  await dropWorkspaceOutputs(tenant, workspace);
554
561
  marked.delete(k);
555
562
  verified.delete(k);
563
+ dropHeadsSeen(tenant, workspace); // a new workspace of this name starts unseen
556
564
  }
557
565
  finally {
558
566
  lifecycleBusy.delete(k);
@@ -624,6 +632,7 @@ export async function moveWorkspaceRevisions(tenant, from, to, rename) {
624
632
  }
625
633
  }
626
634
  rekeyQueue(tenant, from, to);
635
+ dropHeadsSeen(tenant, from);
627
636
  if (rename) {
628
637
  // A commit on another pod that passed its guard between the move and the
629
638
  // folder rename left rows under the OLD name; its content is in the
@@ -801,9 +810,12 @@ export async function cleanOrphanedHistory(marks, opts) {
801
810
  const deps = S.backend;
802
811
  if (!deps)
803
812
  return out;
804
- // Folders are a copy of the heads (revisions.mirror): a missing one says
805
- // nothing about the workspace, so nothing is taken for orphaned.
806
- if (mirrorOn())
813
+ // Folders are a copy of the heads (revisions.mirror), or this pod's own
814
+ // disk (FOLDRUN_DATA_LOCAL=1, with the mirror on or off): a missing one says
815
+ // nothing about the workspace, so nothing is taken for orphaned. Until
816
+ // 14 Nov 2026 only the mirror was asked, so turning it off on a pod with its
817
+ // own empty disk would have dropped every workspace's history (Kousha's review).
818
+ if (mirrorOn() || localDisk())
807
819
  return out;
808
820
  const root = dataRoot();
809
821
  let rootEntries = 0;
@@ -889,7 +901,11 @@ export async function recoverJournal(opts = {}) {
889
901
  const k = key(tenant, workspace);
890
902
  const q = queues.get(k) ?? [];
891
903
  const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
892
- const gone = !fs.existsSync(folderOf(tenant, workspace));
904
+ // A folder missing from this pod's own disk (FOLDRUN_DATA_LOCAL=1) is
905
+ // one not synced here yet, not a deleted workspace: the database store
906
+ // is shared, and those entries may be another live pod's (Kousha's
907
+ // review, 14 Nov 2026). Only a shared volume's absence is believed.
908
+ const gone = !localDisk() && !fs.existsSync(folderOf(tenant, workspace));
893
909
  const found = [];
894
910
  let names = [];
895
911
  try {
@@ -903,13 +919,16 @@ export async function recoverJournal(opts = {}) {
903
919
  for (const { handle, ageMs } of names) {
904
920
  if (held.has(handle))
905
921
  continue;
922
+ // Young entries are a live process's, whatever the folder says: the
923
+ // age is asked before anything is removed (until 14 Nov 2026 a missing
924
+ // folder removed even a fresh entry).
925
+ if (minAge > 0 && ageMs < minAge)
926
+ continue;
906
927
  try {
907
928
  if (gone) {
908
929
  store.remove(tenant, workspace, handle);
909
930
  continue;
910
931
  }
911
- if (minAge > 0 && ageMs < minAge)
912
- continue;
913
932
  const e = store.read(tenant, workspace, handle);
914
933
  if ((e.v !== 1 && e.v !== 2) || !Array.isArray(e.files))
915
934
  throw new Error("not a journal entry");
@@ -1146,6 +1165,24 @@ async function baseManifests(deps, tenant, workspace, base) {
1146
1165
  }
1147
1166
  return out;
1148
1167
  }
1168
+ /** On a pod's own disk (the mirror, or FOLDRUN_DATA_LOCAL) a folder with no
1169
+ * heads is either a workspace made here (no first revision yet) or the stale
1170
+ * copy of one deleted elsewhere. The marker tells them apart: once this pod
1171
+ * has seen heads for the name, their absence is a delete, and the folder is
1172
+ * not published as a first revision. The sync removes it, as it always did. */
1173
+ function isStale(tenant, workspace) {
1174
+ return (mirrorOn() || localDisk()) && headsSeen(tenant, workspace);
1175
+ }
1176
+ function noteHeads(tenant, workspace, heads) {
1177
+ if (heads.workspace || heads.state)
1178
+ noteHeadsSeen(tenant, workspace);
1179
+ }
1180
+ function staleFolder(tenant, workspace, heads) {
1181
+ if (!heads.workspace && !heads.state && isStale(tenant, workspace)) {
1182
+ throw new PublishError(`${workspace} was deleted elsewhere; this pod's folder is a stale copy`, "gone");
1183
+ }
1184
+ noteHeads(tenant, workspace, heads);
1185
+ }
1149
1186
  /** One journal entry → one publish. The first commit of a workspace is its
1150
1187
  * whole tree. */
1151
1188
  async function commitEntry(deps, tenant, workspace, entry) {
@@ -1157,6 +1194,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
1157
1194
  let releaseLarge = async () => { };
1158
1195
  const changes = {};
1159
1196
  const baseline = { authored: !heads.workspace, state: !heads.state };
1197
+ staleFolder(tenant, workspace, heads);
1160
1198
  // A run's copy-back is pinned to the revisions its stage-in started from: a
1161
1199
  // path's base is what THAT revision held, so a head that moved since (another
1162
1200
  // run, a person) is a conflict on the path, and disjoint paths replay. Where
@@ -1311,6 +1349,13 @@ async function reconcileNow(tenant, workspace, by = "reconcile") {
1311
1349
  // sync to say what "changed here" means.
1312
1350
  if (mirrorOn() && !readMirrorBase(tenant, workspace))
1313
1351
  return null;
1352
+ // This pod's own disk with the mirror off: nothing brings the folder to the
1353
+ // heads, so it is not the truth about anything either — an emptyDir after a
1354
+ // restart would publish every file as deleted (Kousha's review, 14 Nov 2026).
1355
+ if (!mirrorOn() && localDisk()) {
1356
+ opsLog("warn", "revisions.reconcile_skipped", { tenant, workspace, reason: "local_disk_without_mirror" });
1357
+ return null;
1358
+ }
1314
1359
  const ws = { tenant, workspace };
1315
1360
  const k = key(tenant, workspace);
1316
1361
  // The mark goes BEFORE the folder is read, so one set after the read (a run
@@ -1324,6 +1369,9 @@ async function reconcileNow(tenant, workspace, by = "reconcile") {
1324
1369
  // would diff a stale copy against a newer head, and with that head as each
1325
1370
  // path's base the publish would undo the newer write without a conflict.
1326
1371
  const heads = await headsOf(deps, ws);
1372
+ if (!heads.workspace && !heads.state && isStale(tenant, workspace))
1373
+ return null;
1374
+ noteHeads(tenant, workspace, heads);
1327
1375
  const scan = await scanFolder(tenant, workspace);
1328
1376
  if (!scan)
1329
1377
  return null;
@@ -1393,6 +1441,7 @@ async function reconcileNow(tenant, workspace, by = "reconcile") {
1393
1441
  * conflict copy beside it), so this pod takes the head's version too — unless
1394
1442
  * the file changed here again since. Returns the result unchanged. */
1395
1443
  async function afterPublish(deps, ws, changes, r) {
1444
+ noteHeadsSeen(ws.tenant, ws.workspace); // it has heads now, whether or not the mirror is on
1396
1445
  if (!mirrorOn())
1397
1446
  return r;
1398
1447
  try {
@@ -1543,6 +1592,7 @@ async function syncNow(tenant, workspace) {
1543
1592
  notifyWorkspaceChanged(tenant, workspace, "delete");
1544
1593
  return "removed";
1545
1594
  }
1595
+ noteHeadsSeen(tenant, workspace);
1546
1596
  const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
1547
1597
  if (base && base.workspaceHead === ids.workspaceHead && base.stateHead === ids.stateHead && fs.existsSync(dir))
1548
1598
  return "unchanged";
@@ -1716,6 +1766,47 @@ function throughLink(dir, rel) {
1716
1766
  }
1717
1767
  /** Every workspace with heads, and every copy here whose heads are gone. One
1718
1768
  * failure does not stop the rest. */
1769
+ /**
1770
+ * One account's folders brought level with the heads, now — for a request
1771
+ * that must see what another pod just wrote (14 Nov 2026: a workspace made
1772
+ * on one web pod answered 404 on the other for up to the mirror's poll; a
1773
+ * deleted one stayed listed ~10 s). The same per-workspace sync the loop
1774
+ * runs, for this tenant only: its heads, and its mirrored folders with no
1775
+ * head (deleted elsewhere). A failure is logged and counted, never thrown —
1776
+ * the caller answers from the copy it has.
1777
+ */
1778
+ export async function syncTenantFromHeads(tenant) {
1779
+ const deps = S.backend;
1780
+ const out = { synced: 0, removed: 0, failed: 0 };
1781
+ if (!deps?.revisions.allHeads || !mirrorOn())
1782
+ return out;
1783
+ let mine;
1784
+ try {
1785
+ mine = (await deps.revisions.allHeads()).filter((h) => h.tenant === tenant);
1786
+ }
1787
+ catch (err) {
1788
+ // Fail open, as documented: the caller answers from the copy it has (Codex).
1789
+ opsError("revisions.mirror_sync_failed", err, { tenant }, "warn");
1790
+ out.failed++;
1791
+ return out;
1792
+ }
1793
+ const seen = new Set(mine.map((h) => h.workspace));
1794
+ const todo = [...mine.map((h) => h.workspace), ...mirroredWorkspaces().filter((w) => w.tenant === tenant && !seen.has(w.workspace)).map((w) => w.workspace)];
1795
+ for (const workspace of todo) {
1796
+ try {
1797
+ const r = await syncFromHeads(tenant, workspace);
1798
+ if (r === "synced")
1799
+ out.synced++;
1800
+ else if (r === "removed")
1801
+ out.removed++;
1802
+ }
1803
+ catch (err) {
1804
+ out.failed++;
1805
+ opsError("revisions.mirror_sync_failed", err, { tenant, workspace }, "warn");
1806
+ }
1807
+ }
1808
+ return out;
1809
+ }
1719
1810
  export async function syncAllFromHeads() {
1720
1811
  const deps = S.backend;
1721
1812
  const out = { synced: 0, removed: 0, failed: 0 };
@@ -1739,6 +1830,30 @@ export async function syncAllFromHeads() {
1739
1830
  }
1740
1831
  return out;
1741
1832
  }
1833
+ /** Every account that still has revision state: a head in the store, a journal
1834
+ * entry in any journal store, or changes queued in this process. A pod that is
1835
+ * about to remove an account's folder asks first — such an account has work
1836
+ * not yet in a head, or a history somebody can still read. Throws when a store
1837
+ * cannot be read: the caller must then remove nothing. */
1838
+ export async function tenantsWithRevisionState() {
1839
+ const out = new Set();
1840
+ const deps = S.backend;
1841
+ if (deps) {
1842
+ if (!deps.revisions.allHeads)
1843
+ throw new Error("revisions: the store cannot list its heads");
1844
+ for (const h of await deps.revisions.allHeads())
1845
+ out.add(h.tenant);
1846
+ }
1847
+ for (const st of journalStores())
1848
+ for (const w of st.workspaces())
1849
+ out.add(w.tenant);
1850
+ for (const [k, q] of queues)
1851
+ if (q.length)
1852
+ out.add(k.split("\0")[0]);
1853
+ for (const k of marked)
1854
+ out.add(k.split("\0")[0]);
1855
+ return out;
1856
+ }
1742
1857
  // ------------------------------------------------------------- reading
1743
1858
  async function blobBytes(deps, tenant, sha) {
1744
1859
  // An object is named by its content: bytes that do not hash to the name
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "23.0.2",
3
+ "version": "23.0.4",
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/capture.ts CHANGED
@@ -27,9 +27,18 @@ export const CAPTURE_SLACK = 4096;
27
27
  */
28
28
  export function redactionsFor(secrets: Record<string, string | undefined>): [string, string][] {
29
29
  const out = new Map<string, string>();
30
- const add = (v: string, name: string) => {
30
+ const put = (v: string, name: string) => {
31
31
  if (v.length >= 8 && !out.has(v)) out.set(v, name);
32
32
  };
33
+ // Every value also as a tool prints it encoded (Kousha's review, 14 Nov
34
+ // 2026): hex, URL-encoded, and base64 — standard and URL-safe, at each of
35
+ // the three byte alignments it can take inside a longer encoded text
36
+ // (`base64 <<< "user:$TOKEN"`, a JWT segment, a Basic header the agent built).
37
+ const add = (v: string, name: string) => {
38
+ if (v.length < 8) return;
39
+ put(v, name);
40
+ for (const e of encodedForms(v)) put(e, name);
41
+ };
33
42
  for (const [name, raw] of Object.entries(secrets)) {
34
43
  if (typeof raw !== "string") continue;
35
44
  // An API connection's header values are each a secret in their own right
@@ -80,6 +89,39 @@ export function redactionsFor(secrets: Record<string, string | undefined>): [str
80
89
  return [...out.entries()].sort((a, b) => b[0].length - a[0].length);
81
90
  }
82
91
 
92
+ /** A value's encoded forms, each long enough to be its own and nothing else's
93
+ * (12 characters or more). Base64: the characters that come from the value's
94
+ * bytes alone at each alignment, so the form matches inside a longer
95
+ * encoding whatever came before or after the value. */
96
+ export function encodedForms(v: string): string[] {
97
+ const bytes = Buffer.from(v, "utf8");
98
+ const forms = new Set<string>([bytes.toString("hex"), bytes.toString("hex").toUpperCase()]);
99
+ try {
100
+ const pct = encodeURIComponent(v);
101
+ forms.add(pct);
102
+ // a form body writes a space as `+`, and some encoders write the escapes
103
+ // in lower case (`%2f`); all four spellings are the same secret
104
+ const plus = pct.replace(/%20/g, "+");
105
+ forms.add(plus);
106
+ const lower = (t: string) => t.replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase());
107
+ forms.add(lower(pct));
108
+ forms.add(lower(plus));
109
+ } catch {
110
+ // a lone surrogate: no URL form
111
+ }
112
+ for (let pad = 0; pad < 3; pad++) {
113
+ const b64 = Buffer.concat([Buffer.alloc(pad), bytes]).toString("base64").replace(/=+$/, "");
114
+ // character i holds bits [6i, 6i + 6); the value's are [8·pad, 8·(pad + n))
115
+ const first = Math.ceil((8 * pad) / 6);
116
+ const last = Math.floor((8 * (pad + bytes.length)) / 6); // exclusive
117
+ const part = b64.slice(first, last);
118
+ forms.add(part);
119
+ forms.add(part.replace(/\+/g, "-").replace(/\//g, "_"));
120
+ }
121
+ forms.delete(v);
122
+ return [...forms].filter((f) => f.length >= 12);
123
+ }
124
+
83
125
  // A private key's whole block — scan.ts names a key header and leaves the
84
126
  // body, which is right for a finding and wrong for a stored output.
85
127
  // Unterminated too: a key cut short, or printed without its END line, is
@@ -17,11 +17,15 @@
17
17
  // TEMPORARY, remove at cutover (phase 9): a write that fails with an error
18
18
  // (store down, database refuses) falls back to the volume file and logs
19
19
  // `captured_calls.fallback`. At cutover that branch becomes "the call is not
20
- // recorded, and the event says so".
20
+ // recorded, and the event says so". Already so on a pod whose data root is its
21
+ // own disk (localDisk()): the volume file would be lost with the pod, so the
22
+ // call is logged `captured_calls.not_recorded` and not written (ops log only;
23
+ // the capture sink has no run to put an event on).
21
24
 
22
25
  import { records } from "./records.ts";
23
26
  import { blobObjectKey, sha256Hex } from "./manifest.ts";
24
27
  import { opsError } from "./ops-log.ts";
28
+ import { localDisk } from "./mirror-base.ts";
25
29
  import { BlobNotFound, readAll } from "./blob-store.ts";
26
30
  import type { Deps } from "./publish.ts";
27
31
  import { writeCapturedCall, readCapturedCall, registerRunRemovedHook, type CapturedCall } from "./store.ts";
@@ -94,6 +98,7 @@ const sessions = new WeakMap<object, Session>();
94
98
  async function storeCall(ctx: Ctx, call: CapturedCall): Promise<void> {
95
99
  const a = active(ctx.tenant, ctx.workspace);
96
100
  const fall = (err: unknown) => {
101
+ if (localDisk()) return opsError("captured_calls.not_recorded", err, { tenant: ctx.tenant, workspace: ctx.workspace, runId: ctx.runId, callId: call.id });
97
102
  // TEMPORARY (see the header): the volume copy, so the call is not lost.
98
103
  opsError("captured_calls.fallback", err, { tenant: ctx.tenant, workspace: ctx.workspace, runId: ctx.runId, callId: call.id });
99
104
  try {
@@ -39,6 +39,25 @@ export function mirrorOn(): boolean {
39
39
  }
40
40
  }
41
41
 
42
+ const LOCAL = processState("local-disk-gate", () => ({ on: (() => false) as () => boolean }));
43
+
44
+ /** The platform says whether this pod's data root is its own disk
45
+ * (FOLDRUN_DATA_LOCAL=1, an emptyDir) rather than a volume every pod shares.
46
+ * On such a disk a folder that is missing or older than the heads says
47
+ * nothing about the workspace: it may simply not be synced here, or (mirror
48
+ * off) never will be. Off on a laptop, in the CLI and on the shared volume. */
49
+ export function setLocalDiskGate(fn: (() => boolean) | null): void {
50
+ LOCAL.on = fn ?? (() => false);
51
+ }
52
+
53
+ export function localDisk(): boolean {
54
+ try {
55
+ return LOCAL.on();
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
42
61
  const SAFE = /^(?:@library|[A-Za-z0-9][A-Za-z0-9_.-]{0,127})$/;
43
62
  export const mirrorBaseFile = (tenant: string, workspace: string): string | null =>
44
63
  SAFE.test(tenant) && SAFE.test(workspace) ? path.join(dataRoot(), ".mirror", tenant, `${workspace}.json`) : null;
@@ -65,6 +84,34 @@ export function writeMirrorBase(tenant: string, workspace: string, base: MirrorB
65
84
  export function dropMirrorBase(tenant: string, workspace: string): void {
66
85
  const f = mirrorBaseFile(tenant, workspace);
67
86
  if (f) fs.rmSync(f, { force: true });
87
+ dropHeadsSeen(tenant, workspace);
88
+ }
89
+
90
+ // "This pod has seen heads for the workspace": a marker beside the base, kept
91
+ // whether or not the mirror is on (own disk, mirror off, has no base). A folder
92
+ // here whose heads are gone and which carries it is a stale copy of a workspace
93
+ // deleted elsewhere, not a new workspace: its first revision is not published.
94
+ // A workspace made on this pod has no marker until its first revision lands.
95
+ const seenFile = (tenant: string, workspace: string): string | null => {
96
+ const f = mirrorBaseFile(tenant, workspace);
97
+ return f ? f.replace(/\.json$/, ".seen") : null;
98
+ };
99
+
100
+ export function headsSeen(tenant: string, workspace: string): boolean {
101
+ const f = seenFile(tenant, workspace);
102
+ return !!f && fs.existsSync(f);
103
+ }
104
+
105
+ export function noteHeadsSeen(tenant: string, workspace: string): void {
106
+ const f = seenFile(tenant, workspace);
107
+ if (!f || fs.existsSync(f)) return;
108
+ fs.mkdirSync(path.dirname(f), { recursive: true });
109
+ fs.writeFileSync(f, "");
110
+ }
111
+
112
+ export function dropHeadsSeen(tenant: string, workspace: string): void {
113
+ const f = seenFile(tenant, workspace);
114
+ if (f) fs.rmSync(f, { force: true });
68
115
  }
69
116
 
70
117
  /** Every workspace this pod holds a copy of, by its base files. */
@@ -29,6 +29,9 @@
29
29
  // are copied to the volume as before and the failure is logged
30
30
  // (`run_outputs.fallback`). A laptop or an install with no backend always
31
31
  // uses the volume: it is a local disk there, not the thing being retired.
32
+ // Not on a pod whose data root is its own disk (localDisk(), an emptyDir): the
33
+ // volume goes with the pod, so there a failed publish fails the archive
34
+ // (`run_outputs.publish_failed`) instead of keeping nothing.
32
35
  //
33
36
  // Reads (`listRunOutputs`, `openRunOutput`) ask the records first and the
34
37
  // volume second, per agent, so a run archived either way stays readable
@@ -58,6 +61,7 @@ import {
58
61
  } from "./manifest.ts";
59
62
  import { BlobMissing, loadManifest, type Deps } from "./publish.ts";
60
63
  import { opsError } from "./ops-log.ts";
64
+ import { localDisk } from "./mirror-base.ts";
61
65
  import { refusalText } from "./run-output-refusal.ts";
62
66
  export { refusalText };
63
67
  import { listRunOutputsOnVolume, registerRunRemovedHook, runOutputPathOnVolume, type RefusedOutput, type RunOutputFile } from "./store.ts";
@@ -416,6 +420,11 @@ export async function archiveRunOutputs(
416
420
  const r = await publishRunOutputs(b, tenant, workspace, runId, agent, dir);
417
421
  return { where: "store", refused: r.refused };
418
422
  } catch (err) {
423
+ // On a pod's own disk the volume copy would be lost with the pod: fail.
424
+ if (localDisk()) {
425
+ opsError("run_outputs.publish_failed", err, { tenant, workspace, run: runId, agent });
426
+ throw err;
427
+ }
419
428
  // TEMPORARY (EFS cutover, FOL-126 phase 9): an error publishing is not a
420
429
  // reason to lose the run's outputs while the volume still exists. Remove
421
430
  // this branch with the volume; then a failed publish fails the archive.
package/src/runner.ts CHANGED
@@ -5022,7 +5022,15 @@ function driveRunInner(
5022
5022
  for (const agent of new Set(run.steps.map((s) => s.agent))) {
5023
5023
  const from = path.join(runRoot, "agents", agent, "outputs");
5024
5024
  if (!fs.existsSync(from) || fs.readdirSync(from).length === 0) continue;
5025
- const done = await archiveRunOutputs(tenant, workspace, run.id, agent, from);
5025
+ let done: Awaited<ReturnType<typeof archiveRunOutputs>>;
5026
+ try {
5027
+ done = await archiveRunOutputs(tenant, workspace, run.id, agent, from);
5028
+ } catch {
5029
+ // Only on a pod's own disk (localDisk()), where there is no volume to keep them on.
5030
+ const last = run.steps.findLast((s) => s.status !== "pending") ?? run.steps[0];
5031
+ last?.events.push({ t: new Date().toISOString(), type: "error", text: `outputs: ${agent}'s outputs were not kept: the store refused them` });
5032
+ continue;
5033
+ }
5026
5034
  if (done.where === "store") noteRefused(run, done.refused);
5027
5035
  else copyTreeBytes(from, path.join(runRoot, "runs", run.id, "outputs", agent));
5028
5036
  }
package/src/store.ts CHANGED
@@ -369,6 +369,10 @@ export function isPlatformPath(rel: string): boolean {
369
369
  // are the vault, as far as anything outside the platform is concerned.
370
370
  if (/(^|\/)secrets\.json\./.test(norm)) return true;
371
371
  if (norm === "trigger-log.jsonl.tmp") return true;
372
+ // The revision mirror's in-flight file (`<name>.<pid>.<hex>.mirror-tmp`,
373
+ // workspace-revisions.ts): a crash between its write and its rename leaves
374
+ // it, and the next scan would publish half a file as the author's.
375
+ if (norm.endsWith(".mirror-tmp")) return true;
372
376
  if (ENGINE_HOME_RE.test(norm)) return true;
373
377
  return norm === "runs" || norm.startsWith("runs/") || norm === ".foldrun" || norm.startsWith(".foldrun/");
374
378
  }
@@ -2813,7 +2817,7 @@ export function accountFileSealed(rel: string): string | null {
2813
2817
  * honesty's clothes. `accountFileSealed` still refuses these if a path is
2814
2818
  * constructed directly — the listing hides them, the reader guards them. */
2815
2819
  const ACCOUNT_BOOKKEEPING =
2816
- /^(billed\/|once\/|topups\/|ledger\.jsonl$|oauth-clients\.json$|billing\.json$|oauth-connections\.json$|secret-health\.json$|[^/]+\.json\.imported-[\d-]+$)|(^|\/)runs\/|(^|\/)secrets\.json(\.[^/]+)?$/;
2820
+ /^(billed\/|once\/|topups\/|ledger\.jsonl$|oauth-clients\.json$|billing\.json$|oauth-connections\.json$|secret-health\.json$|[^/]+\.json\.imported-[\d-]+$)|(^|\/)runs\/|(^|\/)secrets\.json(\.[^/]+)?$|\.mirror-tmp$/;
2817
2821
 
2818
2822
  /**
2819
2823
  * The account directory as it actually is on disk.
@@ -61,7 +61,7 @@ import {
61
61
  type Manifest,
62
62
  type ManifestEntry,
63
63
  } from "./manifest.ts";
64
- import { mirrorOn, readMirrorBase, writeMirrorBase, dropMirrorBase, mirroredWorkspaces, type MirrorBase } from "./mirror-base.ts";
64
+ import { mirrorOn, localDisk, readMirrorBase, writeMirrorBase, dropMirrorBase, mirroredWorkspaces, headsSeen, noteHeadsSeen, dropHeadsSeen, type MirrorBase } from "./mirror-base.ts";
65
65
  import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError, type Deps, type Heads, type PublishResult } from "./publish.ts";
66
66
  import { OpIdReused, type Revision, type WorkspaceRef } from "./revision-store.ts";
67
67
  import { pruneStateRevisions, type StateRetention } from "./state-retention.ts";
@@ -437,10 +437,14 @@ async function drainOne(k: string): Promise<void> {
437
437
  while (q && q.length && S.backend) {
438
438
  const entry = q[0];
439
439
  // The workspace was deleted while this waited (or retried): nothing to
440
- // publish, and nothing for a later boot to replay.
440
+ // publish, and nothing for a later boot to replay. On this pod's own disk
441
+ // (FOLDRUN_DATA_LOCAL=1) a missing folder is only one not synced here: the
442
+ // entry leaves this pod's queue but stays in the shared store, for a pod
443
+ // that has the folder (Kousha's review, 14 Nov 2026). A real delete takes
444
+ // the store's entries with it (dropJournal).
441
445
  if (!fs.existsSync(folderOf(tenant, workspace))) {
442
446
  q.shift();
443
- forget(tenant, workspace, entry);
447
+ if (!localDisk()) forget(tenant, workspace, entry);
444
448
  continue;
445
449
  }
446
450
  try {
@@ -453,8 +457,9 @@ async function drainOne(k: string): Promise<void> {
453
457
  if (err instanceof PublishError && err.code === "gone") {
454
458
  // The folder is gone (deleted or renamed, here or on another pod): the
455
459
  // change has nowhere to go, and nothing should be recorded under the name.
460
+ // On this pod's own disk, kept in the store as above.
456
461
  q.shift();
457
- forget(tenant, workspace, entry);
462
+ if (!localDisk()) forget(tenant, workspace, entry);
458
463
  continue;
459
464
  }
460
465
  if (permanent(err)) {
@@ -660,6 +665,7 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
660
665
  await dropWorkspaceOutputs(tenant, workspace);
661
666
  marked.delete(k);
662
667
  verified.delete(k);
668
+ dropHeadsSeen(tenant, workspace); // a new workspace of this name starts unseen
663
669
  } finally {
664
670
  lifecycleBusy.delete(k);
665
671
  release();
@@ -730,6 +736,7 @@ export async function moveWorkspaceRevisions(tenant: string, from: string, to: s
730
736
  }
731
737
  }
732
738
  rekeyQueue(tenant, from, to);
739
+ dropHeadsSeen(tenant, from);
733
740
  if (rename) {
734
741
  // A commit on another pod that passed its guard between the move and the
735
742
  // folder rename left rows under the OLD name; its content is in the
@@ -905,9 +912,12 @@ export async function cleanOrphanedHistory(
905
912
  const out = { checked: 0, orphans: 0, marked: 0, dropped: 0, skipped: 0 };
906
913
  const deps = S.backend;
907
914
  if (!deps) return out;
908
- // Folders are a copy of the heads (revisions.mirror): a missing one says
909
- // nothing about the workspace, so nothing is taken for orphaned.
910
- if (mirrorOn()) return out;
915
+ // Folders are a copy of the heads (revisions.mirror), or this pod's own
916
+ // disk (FOLDRUN_DATA_LOCAL=1, with the mirror on or off): a missing one says
917
+ // nothing about the workspace, so nothing is taken for orphaned. Until
918
+ // 14 Nov 2026 only the mirror was asked, so turning it off on a pod with its
919
+ // own empty disk would have dropped every workspace's history (Kousha's review).
920
+ if (mirrorOn() || localDisk()) return out;
911
921
  const root = dataRoot();
912
922
  let rootEntries = 0;
913
923
  try {
@@ -983,7 +993,11 @@ export async function recoverJournal(opts: { minAgeMs?: number } = {}): Promise<
983
993
  const k = key(tenant, workspace);
984
994
  const q = queues.get(k) ?? [];
985
995
  const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
986
- const gone = !fs.existsSync(folderOf(tenant, workspace));
996
+ // A folder missing from this pod's own disk (FOLDRUN_DATA_LOCAL=1) is
997
+ // one not synced here yet, not a deleted workspace: the database store
998
+ // is shared, and those entries may be another live pod's (Kousha's
999
+ // review, 14 Nov 2026). Only a shared volume's absence is believed.
1000
+ const gone = !localDisk() && !fs.existsSync(folderOf(tenant, workspace));
987
1001
  const found: Entry[] = [];
988
1002
  let names: { handle: string; ageMs: number }[] = [];
989
1003
  try {
@@ -995,12 +1009,15 @@ export async function recoverJournal(opts: { minAgeMs?: number } = {}): Promise<
995
1009
  }
996
1010
  for (const { handle, ageMs } of names) {
997
1011
  if (held.has(handle)) continue;
1012
+ // Young entries are a live process's, whatever the folder says: the
1013
+ // age is asked before anything is removed (until 14 Nov 2026 a missing
1014
+ // folder removed even a fresh entry).
1015
+ if (minAge > 0 && ageMs < minAge) continue;
998
1016
  try {
999
1017
  if (gone) {
1000
1018
  store.remove(tenant, workspace, handle);
1001
1019
  continue;
1002
1020
  }
1003
- if (minAge > 0 && ageMs < minAge) continue;
1004
1021
  const e = store.read(tenant, workspace, handle);
1005
1022
  if ((e.v !== 1 && e.v !== 2) || !Array.isArray(e.files)) throw new Error("not a journal entry");
1006
1023
  found.push({ id: e.id, files: e.files, by: e.by, message: e.message, at: e.at, restoredFrom: e.restoredFrom, baseRev: e.baseRev, store, handle });
@@ -1220,6 +1237,24 @@ async function baseManifests(deps: Deps, tenant: string, workspace: string, base
1220
1237
  return out;
1221
1238
  }
1222
1239
 
1240
+ /** On a pod's own disk (the mirror, or FOLDRUN_DATA_LOCAL) a folder with no
1241
+ * heads is either a workspace made here (no first revision yet) or the stale
1242
+ * copy of one deleted elsewhere. The marker tells them apart: once this pod
1243
+ * has seen heads for the name, their absence is a delete, and the folder is
1244
+ * not published as a first revision. The sync removes it, as it always did. */
1245
+ function isStale(tenant: string, workspace: string): boolean {
1246
+ return (mirrorOn() || localDisk()) && headsSeen(tenant, workspace);
1247
+ }
1248
+ function noteHeads(tenant: string, workspace: string, heads: Heads): void {
1249
+ if (heads.workspace || heads.state) noteHeadsSeen(tenant, workspace);
1250
+ }
1251
+ function staleFolder(tenant: string, workspace: string, heads: Heads): void {
1252
+ if (!heads.workspace && !heads.state && isStale(tenant, workspace)) {
1253
+ throw new PublishError(`${workspace} was deleted elsewhere; this pod's folder is a stale copy`, "gone");
1254
+ }
1255
+ noteHeads(tenant, workspace, heads);
1256
+ }
1257
+
1223
1258
  /** One journal entry → one publish. The first commit of a workspace is its
1224
1259
  * whole tree. */
1225
1260
  async function commitEntry(deps: Deps, tenant: string, workspace: string, entry: Entry): Promise<PublishResult | null> {
@@ -1231,6 +1266,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1231
1266
  let releaseLarge: () => Promise<void> = async () => {};
1232
1267
  const changes: Changes = {};
1233
1268
  const baseline: { authored: boolean; state: boolean } = { authored: !heads.workspace, state: !heads.state };
1269
+ staleFolder(tenant, workspace, heads);
1234
1270
 
1235
1271
  // A run's copy-back is pinned to the revisions its stage-in started from: a
1236
1272
  // path's base is what THAT revision held, so a head that moved since (another
@@ -1375,6 +1411,13 @@ async function reconcileNow(tenant: string, workspace: string, by = "reconcile")
1375
1411
  // own writes reach the head through the journal; the reconcile waits for a
1376
1412
  // sync to say what "changed here" means.
1377
1413
  if (mirrorOn() && !readMirrorBase(tenant, workspace)) return null;
1414
+ // This pod's own disk with the mirror off: nothing brings the folder to the
1415
+ // heads, so it is not the truth about anything either — an emptyDir after a
1416
+ // restart would publish every file as deleted (Kousha's review, 14 Nov 2026).
1417
+ if (!mirrorOn() && localDisk()) {
1418
+ opsLog("warn", "revisions.reconcile_skipped", { tenant, workspace, reason: "local_disk_without_mirror" });
1419
+ return null;
1420
+ }
1378
1421
  const ws: WorkspaceRef = { tenant, workspace };
1379
1422
  const k = key(tenant, workspace);
1380
1423
  // The mark goes BEFORE the folder is read, so one set after the read (a run
@@ -1388,6 +1431,8 @@ async function reconcileNow(tenant: string, workspace: string, by = "reconcile")
1388
1431
  // would diff a stale copy against a newer head, and with that head as each
1389
1432
  // path's base the publish would undo the newer write without a conflict.
1390
1433
  const heads = await headsOf(deps, ws);
1434
+ if (!heads.workspace && !heads.state && isStale(tenant, workspace)) return null;
1435
+ noteHeads(tenant, workspace, heads);
1391
1436
  const scan = await scanFolder(tenant, workspace);
1392
1437
  if (!scan) return null;
1393
1438
  const head = await manifestsAt(deps, tenant, heads);
@@ -1449,6 +1494,7 @@ async function reconcileNow(tenant: string, workspace: string, by = "reconcile")
1449
1494
  * conflict copy beside it), so this pod takes the head's version too — unless
1450
1495
  * the file changed here again since. Returns the result unchanged. */
1451
1496
  async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: PublishResult): Promise<PublishResult> {
1497
+ noteHeadsSeen(ws.tenant, ws.workspace); // it has heads now, whether or not the mirror is on
1452
1498
  if (!mirrorOn()) return r;
1453
1499
  try {
1454
1500
  const { tenant, workspace } = ws;
@@ -1578,6 +1624,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1578
1624
  if (workspace !== "@library") notifyWorkspaceChanged(tenant, workspace, "delete");
1579
1625
  return "removed";
1580
1626
  }
1627
+ noteHeadsSeen(tenant, workspace);
1581
1628
  const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
1582
1629
  if (base && base.workspaceHead === ids.workspaceHead && base.stateHead === ids.stateHead && fs.existsSync(dir)) return "unchanged";
1583
1630
  const m = await manifestsAt(deps, tenant, heads);
@@ -1734,6 +1781,43 @@ function throughLink(dir: string, rel: string): boolean {
1734
1781
 
1735
1782
  /** Every workspace with heads, and every copy here whose heads are gone. One
1736
1783
  * failure does not stop the rest. */
1784
+ /**
1785
+ * One account's folders brought level with the heads, now — for a request
1786
+ * that must see what another pod just wrote (14 Nov 2026: a workspace made
1787
+ * on one web pod answered 404 on the other for up to the mirror's poll; a
1788
+ * deleted one stayed listed ~10 s). The same per-workspace sync the loop
1789
+ * runs, for this tenant only: its heads, and its mirrored folders with no
1790
+ * head (deleted elsewhere). A failure is logged and counted, never thrown —
1791
+ * the caller answers from the copy it has.
1792
+ */
1793
+ export async function syncTenantFromHeads(tenant: string): Promise<{ synced: number; removed: number; failed: number }> {
1794
+ const deps = S.backend;
1795
+ const out = { synced: 0, removed: 0, failed: 0 };
1796
+ if (!deps?.revisions.allHeads || !mirrorOn()) return out;
1797
+ let mine: { tenant: string; workspace: string }[];
1798
+ try {
1799
+ mine = (await deps.revisions.allHeads()).filter((h) => h.tenant === tenant);
1800
+ } catch (err) {
1801
+ // Fail open, as documented: the caller answers from the copy it has (Codex).
1802
+ opsError("revisions.mirror_sync_failed", err, { tenant }, "warn");
1803
+ out.failed++;
1804
+ return out;
1805
+ }
1806
+ const seen = new Set(mine.map((h) => h.workspace));
1807
+ const todo = [...mine.map((h) => h.workspace), ...mirroredWorkspaces().filter((w) => w.tenant === tenant && !seen.has(w.workspace)).map((w) => w.workspace)];
1808
+ for (const workspace of todo) {
1809
+ try {
1810
+ const r = await syncFromHeads(tenant, workspace);
1811
+ if (r === "synced") out.synced++;
1812
+ else if (r === "removed") out.removed++;
1813
+ } catch (err) {
1814
+ out.failed++;
1815
+ opsError("revisions.mirror_sync_failed", err, { tenant, workspace }, "warn");
1816
+ }
1817
+ }
1818
+ return out;
1819
+ }
1820
+
1737
1821
  export async function syncAllFromHeads(): Promise<{ synced: number; removed: number; failed: number }> {
1738
1822
  const deps = S.backend;
1739
1823
  const out = { synced: 0, removed: 0, failed: 0 };
@@ -1754,6 +1838,24 @@ export async function syncAllFromHeads(): Promise<{ synced: number; removed: num
1754
1838
  return out;
1755
1839
  }
1756
1840
 
1841
+ /** Every account that still has revision state: a head in the store, a journal
1842
+ * entry in any journal store, or changes queued in this process. A pod that is
1843
+ * about to remove an account's folder asks first — such an account has work
1844
+ * not yet in a head, or a history somebody can still read. Throws when a store
1845
+ * cannot be read: the caller must then remove nothing. */
1846
+ export async function tenantsWithRevisionState(): Promise<Set<string>> {
1847
+ const out = new Set<string>();
1848
+ const deps = S.backend;
1849
+ if (deps) {
1850
+ if (!deps.revisions.allHeads) throw new Error("revisions: the store cannot list its heads");
1851
+ for (const h of await deps.revisions.allHeads()) out.add(h.tenant);
1852
+ }
1853
+ for (const st of journalStores()) for (const w of st.workspaces()) out.add(w.tenant);
1854
+ for (const [k, q] of queues) if (q.length) out.add(k.split("\0")[0]);
1855
+ for (const k of marked) out.add(k.split("\0")[0]);
1856
+ return out;
1857
+ }
1858
+
1757
1859
  // ------------------------------------------------------------- reading
1758
1860
 
1759
1861
  async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffer | null> {