@foldrun/core 23.0.4 → 23.1.1

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.
@@ -17,7 +17,7 @@ import { dataRoot, singleWorkspace, singleAccountRoot, MAX_EDITABLE_FILE } from
17
17
  import matter from "./matter.js";
18
18
  import { KINDS } from "./kinds.js";
19
19
  import { recordRevision, registerTreeReader } from "./history.js";
20
- import { assertSafeName, assertCanonicalCase, buildMemoryIndex, parseToolDef, readToolDir, syncBundleFor, listWorkspaces, listAgents, workspaceDir, deleteWorkspacePath, assertDeletable, } from "./store.js";
20
+ import { assertSafeName, assertCanonicalCase, buildMemoryIndex, parseToolDef, readToolDir, syncBundleFor, listWorkspaces, listAgents, workspaceDir, assertLandsInside, landsInside, deleteWorkspacePath, assertDeletable, } from "./store.js";
21
21
  // Same order as the workspace nav and asset pages — one list, one order.
22
22
  // Order matters and is asserted: it is the order every noun list in the
23
23
  // product uses. Tools then scripts, because a script is material a tool
@@ -81,6 +81,9 @@ export function listLibrary(tenant, kind) {
81
81
  const out = [];
82
82
  const describe = (file, fallback) => {
83
83
  try {
84
+ // a link out of the shelf is not read for its description
85
+ if (!landsInside(dir, file))
86
+ return { name: fallback, description: "" };
84
87
  const { data } = matter(fs.readFileSync(file, "utf8"));
85
88
  return { name: data.name ?? fallback, description: data.description ?? "" };
86
89
  }
@@ -162,7 +165,7 @@ export function listLibrary(tenant, kind) {
162
165
  for (const entry of fs.readdirSync(dir, { recursive: true })) {
163
166
  const rel = String(entry);
164
167
  const full = path.join(dir, rel);
165
- if (!fs.statSync(full).isFile() || !TEXT_EXT.test(rel))
168
+ if (!fs.statSync(full).isFile() || !TEXT_EXT.test(rel) || !landsInside(dir, full))
166
169
  continue;
167
170
  // The memory index is generated, so it isn't an entry in its own list.
168
171
  if ((kind === "memory" || kind === "knowledge") &&
@@ -196,6 +199,9 @@ export function readLibraryFile(tenant, kind, rel) {
196
199
  const p = path.join(libraryDir(tenant, kind), assertLibraryPath(kind, rel));
197
200
  if (!fs.existsSync(p))
198
201
  throw new Error(`not found: ${rel}`);
202
+ // The same rule as a workspace file (FOL-83): a link inside the shelf that
203
+ // leads out of it is not read through.
204
+ assertLandsInside(libraryDir(tenant, kind), p, rel);
199
205
  return fs.readFileSync(p, "utf8");
200
206
  }
201
207
  /** Is there already something here? For refusing to create over it. */
@@ -216,6 +222,9 @@ export function writeLibraryFile(tenant, kind, rel, content, meta = {}) {
216
222
  if (norm.endsWith(".md"))
217
223
  matter(content); // reject broken frontmatter
218
224
  const p = path.join(libraryDir(tenant, kind), norm);
225
+ // Before anything is created: mkdir below would otherwise make folders
226
+ // through a linked directory too.
227
+ assertLandsInside(libraryDir(tenant, kind), p, rel);
219
228
  const existed = fs.existsSync(p);
220
229
  const before = existed ? fs.readFileSync(p, "utf8") : null;
221
230
  fs.mkdirSync(path.dirname(p), { recursive: true });
@@ -239,6 +248,8 @@ export function deleteLibraryPath(tenant, kind, rel, meta = {}) {
239
248
  if (norm === "." || norm === "./")
240
249
  throw new Error(`illegal path: ${rel} — name the file or folder to delete, not the whole ${kind} shelf`);
241
250
  const target = path.join(libraryDir(tenant, kind), norm);
251
+ // The link itself may be removed; a linked folder above it may not be walked.
252
+ assertLandsInside(libraryDir(tenant, kind), target, rel, false);
242
253
  const gone = [];
243
254
  if (fs.existsSync(target)) {
244
255
  const entries = fs.statSync(target).isFile()
@@ -246,7 +257,7 @@ export function deleteLibraryPath(tenant, kind, rel, meta = {}) {
246
257
  : fs.readdirSync(target, { recursive: true }).map((e) => path.join(target, String(e)));
247
258
  for (const e of entries) {
248
259
  try {
249
- if (fs.statSync(e).isFile()) {
260
+ if (fs.statSync(e).isFile() && landsInside(libraryDir(tenant, kind), e)) {
250
261
  gone.push({ path: `${kind}/${path.relative(libraryDir(tenant, kind), e).split(path.sep).join("/")}`, before: fs.readFileSync(e, "utf8"), after: null });
251
262
  }
252
263
  }
@@ -337,7 +348,7 @@ registerTreeReader((tenant, scope) => {
337
348
  const rel = String(entry).split(path.sep).join("/");
338
349
  const full = path.join(dir, rel);
339
350
  try {
340
- if (!fs.statSync(full).isFile() || !TEXT_EXT.test(rel))
351
+ if (!fs.statSync(full).isFile() || !TEXT_EXT.test(rel) || !landsInside(dir, full))
341
352
  continue;
342
353
  out.push({ path: `${kind}/${rel}`, before: null, after: fs.readFileSync(full, "utf8") });
343
354
  }
@@ -36,6 +36,8 @@ export declare function sideOf(rel: string): Side | null;
36
36
  * `a/b` on another.
37
37
  */
38
38
  export declare const MAX_PATH_BYTES = 400;
39
+ /** The longest one name (a folder or a file) a filesystem holds. */
40
+ export declare const MAX_SEGMENT_BYTES = 255;
39
41
  /** Files per manifest (authored and state each). A manifest is read and
40
42
  * rewritten whole on every publish; this bounds that cost until manifests
41
43
  * are sharded. 50k files is ~5 MB of canonical JSON. */
@@ -88,6 +88,8 @@ export function sideOf(rel) {
88
88
  * `a/b` on another.
89
89
  */
90
90
  export const MAX_PATH_BYTES = 400;
91
+ /** The longest one name (a folder or a file) a filesystem holds. */
92
+ export const MAX_SEGMENT_BYTES = 255;
91
93
  /** Files per manifest (authored and state each). A manifest is read and
92
94
  * rewritten whole on every publish; this bounds that cost until manifests
93
95
  * are sharded. 50k files is ~5 MB of canonical JSON. */
@@ -101,6 +103,11 @@ export function assertManifestPath(rel, kind) {
101
103
  throw new Error(`illegal manifest path: ${rel}`);
102
104
  if (/[\u0000-\u001f\u007f]/.test(rel))
103
105
  throw new Error(`illegal manifest path: ${rel}`);
106
+ // One name is at most 255 bytes on every disk a manifest is extracted to; a
107
+ // longer one is a path no machine can create, and the extract of the whole
108
+ // manifest fails on it.
109
+ if (rel.split("/").some((s) => Buffer.byteLength(s) > MAX_SEGMENT_BYTES))
110
+ throw new Error(`illegal manifest path (a name is over ${MAX_SEGMENT_BYTES} bytes): ${rel.slice(0, 80)}`);
104
111
  // NFC only: "é" typed as one character and as e + a combining accent are one
105
112
  // name on a Mac and two on Linux. A manifest holds the composed form, so it
106
113
  // extracts the same everywhere. (Case is handled per manifest, below.)
package/dist/src/okf.js CHANGED
@@ -426,6 +426,17 @@ export function buildIndex(docs, title, isRoot, children = []) {
426
426
  });
427
427
  return `${head}# ${title}\n\n${sections.join("\n\n")}${sub}\n`;
428
428
  }
429
+ /** A generated file that is a link is replaced by a real file, never written
430
+ * through: the link's target is not the bundle's to overwrite. */
431
+ function unlinkIfLink(file) {
432
+ try {
433
+ if (fs.lstatSync(file).isSymbolicLink())
434
+ fs.unlinkSync(file);
435
+ }
436
+ catch {
437
+ /* not there */
438
+ }
439
+ }
429
440
  /**
430
441
  * Write index.md for a bundle and for every directory inside it. The spec puts
431
442
  * an index at each level, so a nested bundle is navigable without a full walk.
@@ -438,14 +449,18 @@ export function syncIndex(dir, title, isRoot = false, depth = 0) {
438
449
  .readdirSync(dir)
439
450
  .filter((e) => {
440
451
  try {
441
- return fs.statSync(path.join(dir, e)).isDirectory();
452
+ // lstat: a link to a folder is not a section. Following it wrote an
453
+ // index.md into whatever the link names, outside the bundle.
454
+ return fs.lstatSync(path.join(dir, e)).isDirectory();
442
455
  }
443
456
  catch {
444
457
  return false;
445
458
  }
446
459
  })
447
460
  .sort();
448
- fs.writeFileSync(path.join(dir, "index.md"), buildIndex(here, title, isRoot, children));
461
+ const indexFile = path.join(dir, "index.md");
462
+ unlinkIfLink(indexFile);
463
+ fs.writeFileSync(indexFile, buildIndex(here, title, isRoot, children));
449
464
  for (const child of children) {
450
465
  syncIndex(path.join(dir, child), child, false, depth + 1);
451
466
  }
@@ -596,6 +611,7 @@ export function appendLog(dir, file, kind, at = new Date()) {
596
611
  const day = at.toISOString().slice(0, 10);
597
612
  const entry = `- **${kind}** [${file.replace(/\.md$/, "")}](${file})`;
598
613
  const logFile = path.join(dir, "log.md");
614
+ unlinkIfLink(logFile);
599
615
  let body = fs.existsSync(logFile) ? fs.readFileSync(logFile, "utf8") : "# Log\n";
600
616
  if (body.includes(`## ${day}`)) {
601
617
  // Same day: add the line under today's heading, skipping exact repeats.
@@ -392,7 +392,10 @@ export async function openRunOutput(tenant, workspace, runId, agent, rel) {
392
392
  const rec = (await recordsOf(tenant, workspace, runId)).find((r) => r.agent === agent);
393
393
  if (rec && OUT.backend) {
394
394
  const m = await loadManifest(readDeps(OUT.backend), tenant, rec.manifest);
395
- const e = m.files[rel.normalize("NFC")];
395
+ // Own names only: `constructor` or `toString` is not an output, and the
396
+ // inherited function was read as one (a 500 where this answers 404).
397
+ const name = rel.normalize("NFC");
398
+ const e = Object.hasOwn(m.files, name) ? m.files[name] : undefined;
396
399
  if (!e)
397
400
  return null;
398
401
  const key = blobObjectKey(tenant, e.sha);
@@ -59,6 +59,17 @@ import { records } from "./records.js";
59
59
  * Declared in store.ts, where saveWorkspace also needs it; re-exported so
60
60
  * callers of this module do not need to know that. */
61
61
  export { STORAGE_DIR };
62
+ /** A file and a folder can not share a name: `reports` and `reports/q1.csv`
63
+ * were both accepted, and the next run's mirror then failed on the second
64
+ * (EEXIST/ENOTDIR) — every run of the workspace, until someone deleted one. */
65
+ function assertNoNameClash(files, norm) {
66
+ for (const f of files) {
67
+ if (f.path !== norm && norm.startsWith(`${f.path}/`))
68
+ throw new Error(`${norm}: "${f.path}" is already stored as a file — a file and a folder can not share a name`);
69
+ if (f.path !== norm && f.path.startsWith(`${norm}/`))
70
+ throw new Error(`${norm}: "${f.path}" is stored under that name as a folder — a file and a folder can not share a name`);
71
+ }
72
+ }
62
73
  // ---------- limits ----------
63
74
  const maxBytes = () => Number(process.env.FOLDRUN_STORAGE_MAX_MB ?? 512) * 1024 * 1024;
64
75
  const quotaBytes = () => Number(process.env.FOLDRUN_STORAGE_QUOTA_MB ?? 5120) * 1024 * 1024;
@@ -140,6 +151,10 @@ export function assertFilePath(rel) {
140
151
  // Control characters survive a normalize and break every header they touch.
141
152
  if (/[\u0000-\u001f\u007f]/.test(norm))
142
153
  throw new Error(`illegal file path: ${rel}`);
154
+ // The mirror writes this path onto a disk, where one name holds 255 bytes:
155
+ // a longer one stored fine and then failed the mirror of every run.
156
+ if (norm.split("/").some((s) => Buffer.byteLength(s) > 255))
157
+ throw new Error(`illegal file path (a name is over 255 bytes): ${rel.slice(0, 80)}`);
143
158
  return norm;
144
159
  }
145
160
  // ---------- foldrun's own records: a run's held inputs (FOL-163) ----------
@@ -958,6 +973,7 @@ async function putFileQuietly(tenant, workspace, rel, body, by) {
958
973
  // that counts, this one only saves uploading what will be refused.
959
974
  {
960
975
  const seen = readIndex(tenant, workspace);
976
+ assertNoNameClash(seen.files, norm);
961
977
  const before = seen.files.find((f) => f.path === norm);
962
978
  if (before?.sha !== sha && usedBytes(tenant, workspace) - (before?.size ?? 0) + body.length > quotaBytes()) {
963
979
  throw new Error(`workspace file quota exceeded (${quotaBytes() / 1e6}MB)`);
@@ -970,6 +986,7 @@ async function putFileQuietly(tenant, workspace, rel, body, by) {
970
986
  await driver.put(key, body, mimeFor(norm));
971
987
  return withFileStoreLock(tenant, workspace, async () => {
972
988
  const index = readIndex(tenant, workspace);
989
+ assertNoNameClash(index.files, norm);
973
990
  const previous = index.files.find((f) => f.path === norm);
974
991
  if (previous?.sha === sha)
975
992
  return previous; // same bytes, same name: nothing happened
@@ -1024,6 +1041,7 @@ export async function registerUpload(tenant, workspace, rel, sha, _claimed, by)
1024
1041
  throw new Error("no object at that key — the upload did not complete");
1025
1042
  }
1026
1043
  const index = readIndex(tenant, workspace);
1044
+ assertNoNameClash(index.files, norm);
1027
1045
  const previous = index.files.find((f) => f.path === norm);
1028
1046
  const record = {
1029
1047
  path: norm,
@@ -1155,6 +1173,7 @@ export async function uploadUrl(tenant, workspace, rel, sha, size) {
1155
1173
  // the bucket refuses any other (30 Oct 2026). registerUpload checks the
1156
1174
  // real object again; this is what keeps an oversized one from ever landing
1157
1175
  // — an object that is PUT and never registered was otherwise unbounded.
1176
+ assertNoNameClash(readIndex(tenant, workspace).files, norm);
1158
1177
  if (size !== undefined) {
1159
1178
  if (!Number.isSafeInteger(size) || size <= 0)
1160
1179
  throw new Error("size must be the file's length in bytes, a whole number above 0");
@@ -912,6 +912,13 @@ export declare function readAccountFile(tenant: string, rel: string): {
912
912
  sealed: string;
913
913
  };
914
914
  export declare function listWorkspaceFiles(tenant: string, workspace: string): string[];
915
+ /** Whether `full` stays in the workspace `dir` with symlinks followed (FOL-83).
916
+ * The string checks (assertEditablePath, runOutputPath's prefix) read the
917
+ * path as written; a link planted inside the workspace — `knowledge/x.md` →
918
+ * /etc/passwd, or a folder → / — passed them, and reads, writes and the run
919
+ * archive followed it out. */
920
+ export declare function landsInside(dir: string, full: string, followLast?: boolean): boolean;
921
+ export declare function assertLandsInside(dir: string, full: string, rel: string, followLast?: boolean): void;
915
922
  export declare function readWorkspaceFile(tenant: string, workspace: string, rel: string): string;
916
923
  /** Who made a change and why — recorded on its revision. */
917
924
  export interface ChangeMeta {
package/dist/src/store.js CHANGED
@@ -2245,15 +2245,30 @@ export function isEditablePath(rel) {
2245
2245
  return false;
2246
2246
  }
2247
2247
  }
2248
+ /** One name holds 255 bytes on a disk; a longer one failed in the filesystem call, as a 500. */
2249
+ function assertNameLengths(norm, rel) {
2250
+ if (norm.split("/").some((s) => Buffer.byteLength(s) > 255))
2251
+ throw new Error(`illegal path (a name is over 255 bytes): ${rel.slice(0, 80)}`);
2252
+ }
2248
2253
  export function assertEditablePath(rel) {
2254
+ // A NUL or other control character passed every check below and only failed
2255
+ // deep in the filesystem calls (a 500 from PUT /source, with the real cause in the log).
2256
+ if (/[\u0000-\u001f\u007f]/.test(rel))
2257
+ throw new Error(`illegal path: ${rel.replace(/[\u0000-\u001f\u007f]/g, "?")}`);
2249
2258
  const norm = path.normalize(rel);
2250
2259
  if (norm.startsWith("..") || path.isAbsolute(norm))
2251
2260
  throw new Error(`illegal path: ${rel}`);
2261
+ assertNameLengths(norm, rel);
2252
2262
  assertCanonicalCase(norm);
2253
2263
  if (norm === "project.md" || norm === "AGENTS.md")
2254
2264
  return norm;
2255
2265
  if (norm.includes("outputs/"))
2256
2266
  throw new Error(`not an editable path: ${rel}`);
2267
+ // What the listing and a deploy leave out (runs/, .results/ — generated) the
2268
+ // writer refuses too: knowledge/runs/x.md could be saved, was never shown,
2269
+ // and an agent still read it.
2270
+ if (/(^|\/)(runs|\.results)\//.test(norm.replaceAll("\\", "/")))
2271
+ throw new Error(`not an editable path: ${rel}`);
2257
2272
  if (/scripts\//.test(norm) && SCRIPT_EXT.test(norm))
2258
2273
  return norm;
2259
2274
  if (/^agents\/[^/]+\/skills\/[^/]+\//.test(norm) && SCRIPT_EXT.test(norm))
@@ -2447,7 +2462,7 @@ function realLanding(full, followLast = true) {
2447
2462
  * path as written; a link planted inside the workspace — `knowledge/x.md` →
2448
2463
  * /etc/passwd, or a folder → / — passed them, and reads, writes and the run
2449
2464
  * archive followed it out. */
2450
- function landsInside(dir, full, followLast = true) {
2465
+ export function landsInside(dir, full, followLast = true) {
2451
2466
  // Canonical the same way as the path: a workspace not made yet under a
2452
2467
  // linked ancestor (macOS /tmp → /private/tmp) is its nearest real
2453
2468
  // ancestor plus the rest, or a first write into it would read as leaving.
@@ -2455,7 +2470,7 @@ function landsInside(dir, full, followLast = true) {
2455
2470
  const at = realLanding(full, followLast);
2456
2471
  return at !== null && (at === root || at.startsWith(root + path.sep));
2457
2472
  }
2458
- function assertLandsInside(dir, full, rel, followLast = true) {
2473
+ export function assertLandsInside(dir, full, rel, followLast = true) {
2459
2474
  if (!landsInside(dir, full, followLast))
2460
2475
  throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
2461
2476
  }
@@ -2656,6 +2671,7 @@ export function assertDeletable(tenant, workspace, rel) {
2656
2671
  const norm = path.normalize(rel).replaceAll("\\", "/");
2657
2672
  if (norm.startsWith("..") || path.isAbsolute(norm))
2658
2673
  throw new Error(`illegal path: ${rel}`);
2674
+ assertNameLengths(norm, rel);
2659
2675
  const dir = workspaceDir(tenant, workspace);
2660
2676
  // The two files a workspace cannot exist without. assertEditablePath lets
2661
2677
  // them through — they are editable — but editable and deletable are
@@ -13,7 +13,7 @@ import { records } from "./records.js";
13
13
  import { revisionBackend } from "./workspace-revisions.js";
14
14
  import { blobObjectKey, sha256Hex } from "./manifest.js";
15
15
  import { readAll } from "./blob-types.js";
16
- import { registerRunRemovedHook } from "./store.js";
16
+ import { registerRunRemovedHook, landsInside } from "./store.js";
17
17
  import { opsError } from "./ops-log.js";
18
18
  import { processState } from "./process-state.js";
19
19
  const KIND = "test-writes";
@@ -40,7 +40,9 @@ function walk(root) {
40
40
  if (!e.isFile())
41
41
  continue; // links and the rest never leave the worker
42
42
  const abs = path.join(e.parentPath, e.name);
43
- out.push({ rel: path.relative(root, abs).replaceAll("\\", "/"), abs });
43
+ // split on the platform's separator, not every backslash: on Linux `a\b` is one
44
+ // file name, and turning it into a/b made two files one row and a folder of a file.
45
+ out.push({ rel: path.relative(root, abs).split(path.sep).join("/"), abs });
44
46
  }
45
47
  return out;
46
48
  }
@@ -128,6 +130,18 @@ export async function restoreTestWrites(tenant, workspace, runId, dir) {
128
130
  const abs = path.resolve(dir, f.path);
129
131
  if (!abs.startsWith(path.resolve(dir) + path.sep))
130
132
  continue; // names stay inside the folder
133
+ // …and a link in the folder is not a way out of it (a row through `state` -> /elsewhere).
134
+ if (!landsInside(dir, abs))
135
+ continue;
136
+ // A name a later step made a folder (or the other way round): the old row is
137
+ // stale, not a missing write — skipped, rather than failing every step after.
138
+ try {
139
+ if (fs.statSync(abs).isDirectory())
140
+ continue;
141
+ }
142
+ catch {
143
+ /* not there */
144
+ }
131
145
  const t = new Date(f.mtimeMs);
132
146
  const known = knownOf(dir);
133
147
  if (fs.existsSync(abs)) {
@@ -149,7 +163,14 @@ export async function restoreTestWrites(tenant, workspace, runId, dir) {
149
163
  const bytes = await readAll(deps.blobs, blobObjectKey(tenant, f.sha));
150
164
  if (sha256Hex(bytes) !== f.sha)
151
165
  throw new Error("a diverted file's object does not hash to its name — refused");
152
- fs.mkdirSync(path.dirname(abs), { recursive: true });
166
+ try {
167
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
168
+ }
169
+ catch (err) {
170
+ if (err.code === "EEXIST" || err.code === "ENOTDIR")
171
+ continue; // an ancestor is a file now
172
+ throw err;
173
+ }
153
174
  fs.writeFileSync(abs, bytes);
154
175
  fs.utimesSync(abs, t, t); // a verify that asks whether a file is fresh answers for the step that wrote it
155
176
  known.set(f.path, f.sha);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "23.0.4",
3
+ "version": "23.1.1",
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/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.)
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}`)) {
@@ -475,7 +475,10 @@ export async function openRunOutput(tenant: string, workspace: string, runId: st
475
475
  const rec = (await recordsOf(tenant, workspace, runId)).find((r) => r.agent === agent);
476
476
  if (rec && OUT.backend) {
477
477
  const m = await loadManifest(readDeps(OUT.backend), tenant, rec.manifest);
478
- 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;
479
482
  if (!e) return null;
480
483
  const key = blobObjectKey(tenant, e.sha);
481
484
  const blobs = OUT.backend.blobs;
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
@@ -2764,12 +2764,25 @@ export function isEditablePath(rel: string): boolean {
2764
2764
  }
2765
2765
  }
2766
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
+
2767
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, "?")}`);
2768
2776
  const norm = path.normalize(rel);
2769
2777
  if (norm.startsWith("..") || path.isAbsolute(norm)) throw new Error(`illegal path: ${rel}`);
2778
+ assertNameLengths(norm, rel);
2770
2779
  assertCanonicalCase(norm);
2771
2780
  if (norm === "project.md" || norm === "AGENTS.md") return norm;
2772
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}`);
2773
2786
  if (/scripts\//.test(norm) && SCRIPT_EXT.test(norm)) return norm;
2774
2787
  if (/^agents\/[^/]+\/skills\/[^/]+\//.test(norm) && SCRIPT_EXT.test(norm)) return norm;
2775
2788
  if (/^(skills|memory|knowledge|tools|state)\//.test(norm) && SCRIPT_EXT.test(norm)) return norm;
@@ -2943,7 +2956,7 @@ function realLanding(full: string, followLast = true): string | null {
2943
2956
  * path as written; a link planted inside the workspace — `knowledge/x.md` →
2944
2957
  * /etc/passwd, or a folder → / — passed them, and reads, writes and the run
2945
2958
  * archive followed it out. */
2946
- function landsInside(dir: string, full: string, followLast = true): boolean {
2959
+ export function landsInside(dir: string, full: string, followLast = true): boolean {
2947
2960
  // Canonical the same way as the path: a workspace not made yet under a
2948
2961
  // linked ancestor (macOS /tmp → /private/tmp) is its nearest real
2949
2962
  // ancestor plus the rest, or a first write into it would read as leaving.
@@ -2952,7 +2965,7 @@ function landsInside(dir: string, full: string, followLast = true): boolean {
2952
2965
  return at !== null && (at === root || at.startsWith(root + path.sep));
2953
2966
  }
2954
2967
 
2955
- function assertLandsInside(dir: string, full: string, rel: string, followLast = true) {
2968
+ export function assertLandsInside(dir: string, full: string, rel: string, followLast = true) {
2956
2969
  if (!landsInside(dir, full, followLast)) throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
2957
2970
  }
2958
2971
 
@@ -3166,6 +3179,7 @@ function deletionsUnder(dir: string, norm: string): RevisionFile[] {
3166
3179
  export function assertDeletable(tenant: string, workspace: string, rel: string): { norm: string; folder: boolean } {
3167
3180
  const norm = path.normalize(rel).replaceAll("\\", "/");
3168
3181
  if (norm.startsWith("..") || path.isAbsolute(norm)) throw new Error(`illegal path: ${rel}`);
3182
+ assertNameLengths(norm, rel);
3169
3183
  const dir = workspaceDir(tenant, workspace);
3170
3184
  // The two files a workspace cannot exist without. assertEditablePath lets
3171
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);