@foldrun/core 23.0.3 → 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.
@@ -104,7 +104,15 @@ export function encodedForms(v) {
104
104
  const bytes = Buffer.from(v, "utf8");
105
105
  const forms = new Set([bytes.toString("hex"), bytes.toString("hex").toUpperCase()]);
106
106
  try {
107
- forms.add(encodeURIComponent(v));
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));
108
116
  }
109
117
  catch {
110
118
  // a lone surrogate: no URL form
@@ -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 {
@@ -24,6 +24,9 @@ export declare const mirrorBaseFile: (tenant: string, workspace: string) => stri
24
24
  export declare function readMirrorBase(tenant: string, workspace: string): MirrorBase | null;
25
25
  export declare function writeMirrorBase(tenant: string, workspace: string, base: MirrorBase): void;
26
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;
27
30
  /** Every workspace this pod holds a copy of, by its base files. */
28
31
  export declare function mirroredWorkspaces(): {
29
32
  tenant: string;
@@ -69,6 +69,32 @@ export function dropMirrorBase(tenant, workspace) {
69
69
  const f = mirrorBaseFile(tenant, workspace);
70
70
  if (f)
71
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 });
72
98
  }
73
99
  /** Every workspace this pod holds a copy of, by its base files. */
74
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, localDisk, 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";
@@ -560,6 +560,7 @@ export async function dropWorkspaceRevisions(tenant, workspace, remove) {
560
560
  await dropWorkspaceOutputs(tenant, workspace);
561
561
  marked.delete(k);
562
562
  verified.delete(k);
563
+ dropHeadsSeen(tenant, workspace); // a new workspace of this name starts unseen
563
564
  }
564
565
  finally {
565
566
  lifecycleBusy.delete(k);
@@ -631,6 +632,7 @@ export async function moveWorkspaceRevisions(tenant, from, to, rename) {
631
632
  }
632
633
  }
633
634
  rekeyQueue(tenant, from, to);
635
+ dropHeadsSeen(tenant, from);
634
636
  if (rename) {
635
637
  // A commit on another pod that passed its guard between the move and the
636
638
  // folder rename left rows under the OLD name; its content is in the
@@ -1163,6 +1165,24 @@ async function baseManifests(deps, tenant, workspace, base) {
1163
1165
  }
1164
1166
  return out;
1165
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
+ }
1166
1186
  /** One journal entry → one publish. The first commit of a workspace is its
1167
1187
  * whole tree. */
1168
1188
  async function commitEntry(deps, tenant, workspace, entry) {
@@ -1174,6 +1194,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
1174
1194
  let releaseLarge = async () => { };
1175
1195
  const changes = {};
1176
1196
  const baseline = { authored: !heads.workspace, state: !heads.state };
1197
+ staleFolder(tenant, workspace, heads);
1177
1198
  // A run's copy-back is pinned to the revisions its stage-in started from: a
1178
1199
  // path's base is what THAT revision held, so a head that moved since (another
1179
1200
  // run, a person) is a conflict on the path, and disjoint paths replay. Where
@@ -1348,6 +1369,9 @@ async function reconcileNow(tenant, workspace, by = "reconcile") {
1348
1369
  // would diff a stale copy against a newer head, and with that head as each
1349
1370
  // path's base the publish would undo the newer write without a conflict.
1350
1371
  const heads = await headsOf(deps, ws);
1372
+ if (!heads.workspace && !heads.state && isStale(tenant, workspace))
1373
+ return null;
1374
+ noteHeads(tenant, workspace, heads);
1351
1375
  const scan = await scanFolder(tenant, workspace);
1352
1376
  if (!scan)
1353
1377
  return null;
@@ -1417,6 +1441,7 @@ async function reconcileNow(tenant, workspace, by = "reconcile") {
1417
1441
  * conflict copy beside it), so this pod takes the head's version too — unless
1418
1442
  * the file changed here again since. Returns the result unchanged. */
1419
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
1420
1445
  if (!mirrorOn())
1421
1446
  return r;
1422
1447
  try {
@@ -1567,6 +1592,7 @@ async function syncNow(tenant, workspace) {
1567
1592
  notifyWorkspaceChanged(tenant, workspace, "delete");
1568
1593
  return "removed";
1569
1594
  }
1595
+ noteHeadsSeen(tenant, workspace);
1570
1596
  const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
1571
1597
  if (base && base.workspaceHead === ids.workspaceHead && base.stateHead === ids.stateHead && fs.existsSync(dir))
1572
1598
  return "unchanged";
@@ -1740,6 +1766,47 @@ function throughLink(dir, rel) {
1740
1766
  }
1741
1767
  /** Every workspace with heads, and every copy here whose heads are gone. One
1742
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
+ }
1743
1810
  export async function syncAllFromHeads() {
1744
1811
  const deps = S.backend;
1745
1812
  const out = { synced: 0, removed: 0, failed: 0 };
@@ -1763,6 +1830,30 @@ export async function syncAllFromHeads() {
1763
1830
  }
1764
1831
  return out;
1765
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
+ }
1766
1857
  // ------------------------------------------------------------- reading
1767
1858
  async function blobBytes(deps, tenant, sha) {
1768
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.3",
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
@@ -97,7 +97,15 @@ export function encodedForms(v: string): string[] {
97
97
  const bytes = Buffer.from(v, "utf8");
98
98
  const forms = new Set<string>([bytes.toString("hex"), bytes.toString("hex").toUpperCase()]);
99
99
  try {
100
- forms.add(encodeURIComponent(v));
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));
101
109
  } catch {
102
110
  // a lone surrogate: no URL form
103
111
  }
@@ -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 {
@@ -84,6 +84,34 @@ export function writeMirrorBase(tenant: string, workspace: string, base: MirrorB
84
84
  export function dropMirrorBase(tenant: string, workspace: string): void {
85
85
  const f = mirrorBaseFile(tenant, workspace);
86
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 });
87
115
  }
88
116
 
89
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, localDisk, 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";
@@ -665,6 +665,7 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
665
665
  await dropWorkspaceOutputs(tenant, workspace);
666
666
  marked.delete(k);
667
667
  verified.delete(k);
668
+ dropHeadsSeen(tenant, workspace); // a new workspace of this name starts unseen
668
669
  } finally {
669
670
  lifecycleBusy.delete(k);
670
671
  release();
@@ -735,6 +736,7 @@ export async function moveWorkspaceRevisions(tenant: string, from: string, to: s
735
736
  }
736
737
  }
737
738
  rekeyQueue(tenant, from, to);
739
+ dropHeadsSeen(tenant, from);
738
740
  if (rename) {
739
741
  // A commit on another pod that passed its guard between the move and the
740
742
  // folder rename left rows under the OLD name; its content is in the
@@ -1235,6 +1237,24 @@ async function baseManifests(deps: Deps, tenant: string, workspace: string, base
1235
1237
  return out;
1236
1238
  }
1237
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
+
1238
1258
  /** One journal entry → one publish. The first commit of a workspace is its
1239
1259
  * whole tree. */
1240
1260
  async function commitEntry(deps: Deps, tenant: string, workspace: string, entry: Entry): Promise<PublishResult | null> {
@@ -1246,6 +1266,7 @@ async function commitEntry(deps: Deps, tenant: string, workspace: string, entry:
1246
1266
  let releaseLarge: () => Promise<void> = async () => {};
1247
1267
  const changes: Changes = {};
1248
1268
  const baseline: { authored: boolean; state: boolean } = { authored: !heads.workspace, state: !heads.state };
1269
+ staleFolder(tenant, workspace, heads);
1249
1270
 
1250
1271
  // A run's copy-back is pinned to the revisions its stage-in started from: a
1251
1272
  // path's base is what THAT revision held, so a head that moved since (another
@@ -1410,6 +1431,8 @@ async function reconcileNow(tenant: string, workspace: string, by = "reconcile")
1410
1431
  // would diff a stale copy against a newer head, and with that head as each
1411
1432
  // path's base the publish would undo the newer write without a conflict.
1412
1433
  const heads = await headsOf(deps, ws);
1434
+ if (!heads.workspace && !heads.state && isStale(tenant, workspace)) return null;
1435
+ noteHeads(tenant, workspace, heads);
1413
1436
  const scan = await scanFolder(tenant, workspace);
1414
1437
  if (!scan) return null;
1415
1438
  const head = await manifestsAt(deps, tenant, heads);
@@ -1471,6 +1494,7 @@ async function reconcileNow(tenant: string, workspace: string, by = "reconcile")
1471
1494
  * conflict copy beside it), so this pod takes the head's version too — unless
1472
1495
  * the file changed here again since. Returns the result unchanged. */
1473
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
1474
1498
  if (!mirrorOn()) return r;
1475
1499
  try {
1476
1500
  const { tenant, workspace } = ws;
@@ -1600,6 +1624,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1600
1624
  if (workspace !== "@library") notifyWorkspaceChanged(tenant, workspace, "delete");
1601
1625
  return "removed";
1602
1626
  }
1627
+ noteHeadsSeen(tenant, workspace);
1603
1628
  const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
1604
1629
  if (base && base.workspaceHead === ids.workspaceHead && base.stateHead === ids.stateHead && fs.existsSync(dir)) return "unchanged";
1605
1630
  const m = await manifestsAt(deps, tenant, heads);
@@ -1756,6 +1781,43 @@ function throughLink(dir: string, rel: string): boolean {
1756
1781
 
1757
1782
  /** Every workspace with heads, and every copy here whose heads are gone. One
1758
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
+
1759
1821
  export async function syncAllFromHeads(): Promise<{ synced: number; removed: number; failed: number }> {
1760
1822
  const deps = S.backend;
1761
1823
  const out = { synced: 0, removed: 0, failed: 0 };
@@ -1776,6 +1838,24 @@ export async function syncAllFromHeads(): Promise<{ synced: number; removed: num
1776
1838
  return out;
1777
1839
  }
1778
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
+
1779
1859
  // ------------------------------------------------------------- reading
1780
1860
 
1781
1861
  async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffer | null> {