@foldrun/core 23.0.3 → 23.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.1.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/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 {
package/src/library.ts CHANGED
@@ -28,6 +28,8 @@ import {
28
28
  listWorkspaces,
29
29
  listAgents,
30
30
  workspaceDir,
31
+ assertLandsInside,
32
+ landsInside,
31
33
  deleteWorkspacePath,
32
34
  assertDeletable,
33
35
  type ToolDef,
@@ -126,6 +128,8 @@ export function listLibrary(tenant: string, kind: LibraryKind): LibraryEntry[] {
126
128
 
127
129
  const describe = (file: string, fallback: string) => {
128
130
  try {
131
+ // a link out of the shelf is not read for its description
132
+ if (!landsInside(dir, file)) return { name: fallback, description: "" };
129
133
  const { data } = matter(fs.readFileSync(file, "utf8"));
130
134
  return { name: data.name ?? fallback, description: data.description ?? "" };
131
135
  } catch {
@@ -205,7 +209,7 @@ export function listLibrary(tenant: string, kind: LibraryKind): LibraryEntry[] {
205
209
  for (const entry of fs.readdirSync(dir, { recursive: true })) {
206
210
  const rel = String(entry);
207
211
  const full = path.join(dir, rel);
208
- if (!fs.statSync(full).isFile() || !TEXT_EXT.test(rel)) continue;
212
+ if (!fs.statSync(full).isFile() || !TEXT_EXT.test(rel) || !landsInside(dir, full)) continue;
209
213
  // The memory index is generated, so it isn't an entry in its own list.
210
214
  if ((kind === "memory" || kind === "knowledge") &&
211
215
  ["index.md", "log.md"].includes(rel)) continue;
@@ -236,6 +240,9 @@ function toolShape(file: string, rel: string): { transport?: LibraryEntry["trans
236
240
  export function readLibraryFile(tenant: string, kind: LibraryKind, rel: string): string {
237
241
  const p = path.join(libraryDir(tenant, kind), assertLibraryPath(kind, rel));
238
242
  if (!fs.existsSync(p)) throw new Error(`not found: ${rel}`);
243
+ // The same rule as a workspace file (FOL-83): a link inside the shelf that
244
+ // leads out of it is not read through.
245
+ assertLandsInside(libraryDir(tenant, kind), p, rel);
239
246
  return fs.readFileSync(p, "utf8");
240
247
  }
241
248
 
@@ -261,6 +268,9 @@ export function writeLibraryFile(
261
268
  const norm = assertLibraryPath(kind, rel);
262
269
  if (norm.endsWith(".md")) matter(content); // reject broken frontmatter
263
270
  const p = path.join(libraryDir(tenant, kind), norm);
271
+ // Before anything is created: mkdir below would otherwise make folders
272
+ // through a linked directory too.
273
+ assertLandsInside(libraryDir(tenant, kind), p, rel);
264
274
  const existed = fs.existsSync(p);
265
275
  const before = existed ? fs.readFileSync(p, "utf8") : null;
266
276
  fs.mkdirSync(path.dirname(p), { recursive: true });
@@ -288,6 +298,8 @@ export function deleteLibraryPath(
288
298
  // tool or skill from every workspace (30 Oct 2026). Name what goes.
289
299
  if (norm === "." || norm === "./") throw new Error(`illegal path: ${rel} — name the file or folder to delete, not the whole ${kind} shelf`);
290
300
  const target = path.join(libraryDir(tenant, kind), norm);
301
+ // The link itself may be removed; a linked folder above it may not be walked.
302
+ assertLandsInside(libraryDir(tenant, kind), target, rel, false);
291
303
  const gone: { path: string; before: string | null; after: null }[] = [];
292
304
  if (fs.existsSync(target)) {
293
305
  const entries = fs.statSync(target).isFile()
@@ -295,7 +307,7 @@ export function deleteLibraryPath(
295
307
  : fs.readdirSync(target, { recursive: true }).map((e) => path.join(target, String(e)));
296
308
  for (const e of entries) {
297
309
  try {
298
- if (fs.statSync(e).isFile()) {
310
+ if (fs.statSync(e).isFile() && landsInside(libraryDir(tenant, kind), e)) {
299
311
  gone.push({ path: `${kind}/${path.relative(libraryDir(tenant, kind), e).split(path.sep).join("/")}`, before: fs.readFileSync(e, "utf8"), after: null });
300
312
  }
301
313
  } catch {
@@ -429,7 +441,7 @@ registerTreeReader((tenant, scope) => {
429
441
  const rel = String(entry).split(path.sep).join("/");
430
442
  const full = path.join(dir, rel);
431
443
  try {
432
- if (!fs.statSync(full).isFile() || !TEXT_EXT.test(rel)) continue;
444
+ if (!fs.statSync(full).isFile() || !TEXT_EXT.test(rel) || !landsInside(dir, full)) continue;
433
445
  out.push({ path: `${kind}/${rel}`, before: null, after: fs.readFileSync(full, "utf8") });
434
446
  } catch {
435
447
  // skip
package/src/manifest.ts CHANGED
@@ -117,6 +117,8 @@ export function sideOf(rel: string): Side | null {
117
117
  * `a/b` on another.
118
118
  */
119
119
  export const MAX_PATH_BYTES = 400;
120
+ /** The longest one name (a folder or a file) a filesystem holds. */
121
+ export const MAX_SEGMENT_BYTES = 255;
120
122
  /** Files per manifest (authored and state each). A manifest is read and
121
123
  * rewritten whole on every publish; this bounds that cost until manifests
122
124
  * are sharded. 50k files is ~5 MB of canonical JSON. */
@@ -127,6 +129,10 @@ export function assertManifestPath(rel: string, kind?: Manifest["kind"]): string
127
129
  if (rel.includes("\\") || rel.startsWith("/") || /^[a-zA-Z]:/.test(rel)) throw new Error(`illegal manifest path: ${rel}`);
128
130
  if (rel.split("/").some((s) => s === "" || s === "." || s === "..")) throw new Error(`illegal manifest path: ${rel}`);
129
131
  if (/[\u0000-\u001f\u007f]/.test(rel)) throw new Error(`illegal manifest path: ${rel}`);
132
+ // One name is at most 255 bytes on every disk a manifest is extracted to; a
133
+ // longer one is a path no machine can create, and the extract of the whole
134
+ // manifest fails on it.
135
+ if (rel.split("/").some((s) => Buffer.byteLength(s) > MAX_SEGMENT_BYTES)) throw new Error(`illegal manifest path (a name is over ${MAX_SEGMENT_BYTES} bytes): ${rel.slice(0, 80)}`);
130
136
  // NFC only: "é" typed as one character and as e + a combining accent are one
131
137
  // name on a Mac and two on Linux. A manifest holds the composed form, so it
132
138
  // extracts the same everywhere. (Case is handled per manifest, below.)
@@ -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. */
package/src/okf.ts CHANGED
@@ -527,6 +527,16 @@ export function buildIndex(
527
527
  return `${head}# ${title}\n\n${sections.join("\n\n")}${sub}\n`;
528
528
  }
529
529
 
530
+ /** A generated file that is a link is replaced by a real file, never written
531
+ * through: the link's target is not the bundle's to overwrite. */
532
+ function unlinkIfLink(file: string) {
533
+ try {
534
+ if (fs.lstatSync(file).isSymbolicLink()) fs.unlinkSync(file);
535
+ } catch {
536
+ /* not there */
537
+ }
538
+ }
539
+
530
540
  /**
531
541
  * Write index.md for a bundle and for every directory inside it. The spec puts
532
542
  * an index at each level, so a nested bundle is navigable without a full walk.
@@ -539,14 +549,18 @@ export function syncIndex(dir: string, title: string, isRoot = false, depth = 0)
539
549
  .readdirSync(dir)
540
550
  .filter((e) => {
541
551
  try {
542
- return fs.statSync(path.join(dir, e)).isDirectory();
552
+ // lstat: a link to a folder is not a section. Following it wrote an
553
+ // index.md into whatever the link names, outside the bundle.
554
+ return fs.lstatSync(path.join(dir, e)).isDirectory();
543
555
  } catch {
544
556
  return false;
545
557
  }
546
558
  })
547
559
  .sort();
548
560
 
549
- fs.writeFileSync(path.join(dir, "index.md"), buildIndex(here, title, isRoot, children));
561
+ const indexFile = path.join(dir, "index.md");
562
+ unlinkIfLink(indexFile);
563
+ fs.writeFileSync(indexFile, buildIndex(here, title, isRoot, children));
550
564
  for (const child of children) {
551
565
  syncIndex(path.join(dir, child), child, false, depth + 1);
552
566
  }
@@ -706,6 +720,7 @@ export function appendLog(dir: string, file: string, kind: "Creation" | "Update"
706
720
  const day = at.toISOString().slice(0, 10);
707
721
  const entry = `- **${kind}** [${file.replace(/\.md$/, "")}](${file})`;
708
722
  const logFile = path.join(dir, "log.md");
723
+ unlinkIfLink(logFile);
709
724
 
710
725
  let body = fs.existsSync(logFile) ? fs.readFileSync(logFile, "utf8") : "# Log\n";
711
726
  if (body.includes(`## ${day}`)) {
@@ -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.
@@ -466,7 +475,10 @@ export async function openRunOutput(tenant: string, workspace: string, runId: st
466
475
  const rec = (await recordsOf(tenant, workspace, runId)).find((r) => r.agent === agent);
467
476
  if (rec && OUT.backend) {
468
477
  const m = await loadManifest(readDeps(OUT.backend), tenant, rec.manifest);
469
- const e = m.files[rel.normalize("NFC")];
478
+ // Own names only: `constructor` or `toString` is not an output, and the
479
+ // inherited function was read as one (a 500 where this answers 404).
480
+ const name = rel.normalize("NFC");
481
+ const e = Object.hasOwn(m.files, name) ? m.files[name] : undefined;
470
482
  if (!e) return null;
471
483
  const key = blobObjectKey(tenant, e.sha);
472
484
  const blobs = OUT.backend.blobs;
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/storage.ts CHANGED
@@ -83,6 +83,16 @@ interface Index {
83
83
  files: FileRecord[];
84
84
  }
85
85
 
86
+ /** A file and a folder can not share a name: `reports` and `reports/q1.csv`
87
+ * were both accepted, and the next run's mirror then failed on the second
88
+ * (EEXIST/ENOTDIR) — every run of the workspace, until someone deleted one. */
89
+ function assertNoNameClash(files: Pick<FileRecord, "path">[], norm: string): void {
90
+ for (const f of files) {
91
+ if (f.path !== norm && norm.startsWith(`${f.path}/`)) throw new Error(`${norm}: "${f.path}" is already stored as a file — a file and a folder can not share a name`);
92
+ if (f.path !== norm && f.path.startsWith(`${norm}/`)) throw new Error(`${norm}: "${f.path}" is stored under that name as a folder — a file and a folder can not share a name`);
93
+ }
94
+ }
95
+
86
96
  // ---------- limits ----------
87
97
 
88
98
  const maxBytes = () => Number(process.env.FOLDRUN_STORAGE_MAX_MB ?? 512) * 1024 * 1024;
@@ -169,6 +179,9 @@ export function assertFilePath(rel: string): string {
169
179
  }
170
180
  // Control characters survive a normalize and break every header they touch.
171
181
  if (/[\u0000-\u001f\u007f]/.test(norm)) throw new Error(`illegal file path: ${rel}`);
182
+ // The mirror writes this path onto a disk, where one name holds 255 bytes:
183
+ // a longer one stored fine and then failed the mirror of every run.
184
+ if (norm.split("/").some((s) => Buffer.byteLength(s) > 255)) throw new Error(`illegal file path (a name is over 255 bytes): ${rel.slice(0, 80)}`);
172
185
  return norm;
173
186
  }
174
187
 
@@ -1105,6 +1118,7 @@ async function putFileQuietly(
1105
1118
  // that counts, this one only saves uploading what will be refused.
1106
1119
  {
1107
1120
  const seen = readIndex(tenant, workspace);
1121
+ assertNoNameClash(seen.files, norm);
1108
1122
  const before = seen.files.find((f) => f.path === norm);
1109
1123
  if (before?.sha !== sha && usedBytes(tenant, workspace) - (before?.size ?? 0) + body.length > quotaBytes()) {
1110
1124
  throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
@@ -1118,6 +1132,7 @@ async function putFileQuietly(
1118
1132
 
1119
1133
  return withFileStoreLock(tenant, workspace, async () => {
1120
1134
  const index = readIndex(tenant, workspace);
1135
+ assertNoNameClash(index.files, norm);
1121
1136
  const previous = index.files.find((f) => f.path === norm);
1122
1137
  if (previous?.sha === sha) return previous; // same bytes, same name: nothing happened
1123
1138
 
@@ -1177,6 +1192,7 @@ export async function registerUpload(
1177
1192
  throw new Error("no object at that key — the upload did not complete");
1178
1193
  }
1179
1194
  const index = readIndex(tenant, workspace);
1195
+ assertNoNameClash(index.files, norm);
1180
1196
  const previous = index.files.find((f) => f.path === norm);
1181
1197
  const record: FileRecord = {
1182
1198
  path: norm,
@@ -1332,6 +1348,7 @@ export async function uploadUrl(
1332
1348
  // the bucket refuses any other (30 Oct 2026). registerUpload checks the
1333
1349
  // real object again; this is what keeps an oversized one from ever landing
1334
1350
  // — an object that is PUT and never registered was otherwise unbounded.
1351
+ assertNoNameClash(readIndex(tenant, workspace).files, norm);
1335
1352
  if (size !== undefined) {
1336
1353
  if (!Number.isSafeInteger(size) || size <= 0) throw new Error("size must be the file's length in bytes, a whole number above 0");
1337
1354
  if (size > maxBytes()) throw new Error(`${norm} is ${Math.round(size / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
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
  }
@@ -2760,12 +2764,25 @@ export function isEditablePath(rel: string): boolean {
2760
2764
  }
2761
2765
  }
2762
2766
 
2767
+ /** One name holds 255 bytes on a disk; a longer one failed in the filesystem call, as a 500. */
2768
+ function assertNameLengths(norm: string, rel: string) {
2769
+ if (norm.split("/").some((s) => Buffer.byteLength(s) > 255)) throw new Error(`illegal path (a name is over 255 bytes): ${rel.slice(0, 80)}`);
2770
+ }
2771
+
2763
2772
  export function assertEditablePath(rel: string) {
2773
+ // A NUL or other control character passed every check below and only failed
2774
+ // deep in the filesystem calls (a 500 from PUT /source, with the real cause in the log).
2775
+ if (/[\u0000-\u001f\u007f]/.test(rel)) throw new Error(`illegal path: ${rel.replace(/[\u0000-\u001f\u007f]/g, "?")}`);
2764
2776
  const norm = path.normalize(rel);
2765
2777
  if (norm.startsWith("..") || path.isAbsolute(norm)) throw new Error(`illegal path: ${rel}`);
2778
+ assertNameLengths(norm, rel);
2766
2779
  assertCanonicalCase(norm);
2767
2780
  if (norm === "project.md" || norm === "AGENTS.md") return norm;
2768
2781
  if (norm.includes("outputs/")) throw new Error(`not an editable path: ${rel}`);
2782
+ // What the listing and a deploy leave out (runs/, .results/ — generated) the
2783
+ // writer refuses too: knowledge/runs/x.md could be saved, was never shown,
2784
+ // and an agent still read it.
2785
+ if (/(^|\/)(runs|\.results)\//.test(norm.replaceAll("\\", "/"))) throw new Error(`not an editable path: ${rel}`);
2769
2786
  if (/scripts\//.test(norm) && SCRIPT_EXT.test(norm)) return norm;
2770
2787
  if (/^agents\/[^/]+\/skills\/[^/]+\//.test(norm) && SCRIPT_EXT.test(norm)) return norm;
2771
2788
  if (/^(skills|memory|knowledge|tools|state)\//.test(norm) && SCRIPT_EXT.test(norm)) return norm;
@@ -2813,7 +2830,7 @@ export function accountFileSealed(rel: string): string | null {
2813
2830
  * honesty's clothes. `accountFileSealed` still refuses these if a path is
2814
2831
  * constructed directly — the listing hides them, the reader guards them. */
2815
2832
  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(\.[^/]+)?$/;
2833
+ /^(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
2834
 
2818
2835
  /**
2819
2836
  * The account directory as it actually is on disk.
@@ -2939,7 +2956,7 @@ function realLanding(full: string, followLast = true): string | null {
2939
2956
  * path as written; a link planted inside the workspace — `knowledge/x.md` →
2940
2957
  * /etc/passwd, or a folder → / — passed them, and reads, writes and the run
2941
2958
  * archive followed it out. */
2942
- function landsInside(dir: string, full: string, followLast = true): boolean {
2959
+ export function landsInside(dir: string, full: string, followLast = true): boolean {
2943
2960
  // Canonical the same way as the path: a workspace not made yet under a
2944
2961
  // linked ancestor (macOS /tmp → /private/tmp) is its nearest real
2945
2962
  // ancestor plus the rest, or a first write into it would read as leaving.
@@ -2948,7 +2965,7 @@ function landsInside(dir: string, full: string, followLast = true): boolean {
2948
2965
  return at !== null && (at === root || at.startsWith(root + path.sep));
2949
2966
  }
2950
2967
 
2951
- function assertLandsInside(dir: string, full: string, rel: string, followLast = true) {
2968
+ export function assertLandsInside(dir: string, full: string, rel: string, followLast = true) {
2952
2969
  if (!landsInside(dir, full, followLast)) throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
2953
2970
  }
2954
2971
 
@@ -3162,6 +3179,7 @@ function deletionsUnder(dir: string, norm: string): RevisionFile[] {
3162
3179
  export function assertDeletable(tenant: string, workspace: string, rel: string): { norm: string; folder: boolean } {
3163
3180
  const norm = path.normalize(rel).replaceAll("\\", "/");
3164
3181
  if (norm.startsWith("..") || path.isAbsolute(norm)) throw new Error(`illegal path: ${rel}`);
3182
+ assertNameLengths(norm, rel);
3165
3183
  const dir = workspaceDir(tenant, workspace);
3166
3184
  // The two files a workspace cannot exist without. assertEditablePath lets
3167
3185
  // them through — they are editable — but editable and deletable are
@@ -14,7 +14,7 @@ import { records } from "./records.ts";
14
14
  import { revisionBackend } from "./workspace-revisions.ts";
15
15
  import { blobObjectKey, sha256Hex } from "./manifest.ts";
16
16
  import { readAll } from "./blob-types.ts";
17
- import { registerRunRemovedHook } from "./store.ts";
17
+ import { registerRunRemovedHook, landsInside } from "./store.ts";
18
18
  import { opsError } from "./ops-log.ts";
19
19
  import { processState } from "./process-state.ts";
20
20
 
@@ -46,7 +46,9 @@ function walk(root: string): { rel: string; abs: string }[] {
46
46
  for (const e of fs.readdirSync(root, { recursive: true, withFileTypes: true })) {
47
47
  if (!e.isFile()) continue; // links and the rest never leave the worker
48
48
  const abs = path.join(e.parentPath, e.name);
49
- out.push({ rel: path.relative(root, abs).replaceAll("\\", "/"), abs });
49
+ // split on the platform's separator, not every backslash: on Linux `a\b` is one
50
+ // file name, and turning it into a/b made two files one row and a folder of a file.
51
+ out.push({ rel: path.relative(root, abs).split(path.sep).join("/"), abs });
50
52
  }
51
53
  return out;
52
54
  }
@@ -136,6 +138,15 @@ export async function restoreTestWrites(tenant: string, workspace: string, runId
136
138
  if (typeof f?.path !== "string" || refOf(f.path) !== row.ref) continue;
137
139
  const abs = path.resolve(dir, f.path);
138
140
  if (!abs.startsWith(path.resolve(dir) + path.sep)) continue; // names stay inside the folder
141
+ // …and a link in the folder is not a way out of it (a row through `state` -> /elsewhere).
142
+ if (!landsInside(dir, abs)) continue;
143
+ // A name a later step made a folder (or the other way round): the old row is
144
+ // stale, not a missing write — skipped, rather than failing every step after.
145
+ try {
146
+ if (fs.statSync(abs).isDirectory()) continue;
147
+ } catch {
148
+ /* not there */
149
+ }
139
150
  const t = new Date(f.mtimeMs);
140
151
  const known = knownOf(dir);
141
152
  if (fs.existsSync(abs)) {
@@ -154,7 +165,12 @@ export async function restoreTestWrites(tenant: string, workspace: string, runId
154
165
  }
155
166
  const bytes = await readAll(deps.blobs, blobObjectKey(tenant, f.sha));
156
167
  if (sha256Hex(bytes) !== f.sha) throw new Error("a diverted file's object does not hash to its name — refused");
157
- fs.mkdirSync(path.dirname(abs), { recursive: true });
168
+ try {
169
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
170
+ } catch (err) {
171
+ if ((err as NodeJS.ErrnoException).code === "EEXIST" || (err as NodeJS.ErrnoException).code === "ENOTDIR") continue; // an ancestor is a file now
172
+ throw err;
173
+ }
158
174
  fs.writeFileSync(abs, bytes);
159
175
  fs.utimesSync(abs, t, t); // a verify that asks whether a file is fresh answers for the step that wrote it
160
176
  known.set(f.path, f.sha);