@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.
@@ -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 {
@@ -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.)
@@ -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() {
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.
@@ -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.
@@ -383,7 +392,10 @@ export async function openRunOutput(tenant, workspace, runId, agent, rel) {
383
392
  const rec = (await recordsOf(tenant, workspace, runId)).find((r) => r.agent === agent);
384
393
  if (rec && OUT.backend) {
385
394
  const m = await loadManifest(readDeps(OUT.backend), tenant, rec.manifest);
386
- 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;
387
399
  if (!e)
388
400
  return null;
389
401
  const key = blobObjectKey(tenant, e.sha);
@@ -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
@@ -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
@@ -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/");
@@ -2240,15 +2245,30 @@ export function isEditablePath(rel) {
2240
2245
  return false;
2241
2246
  }
2242
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
+ }
2243
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, "?")}`);
2244
2258
  const norm = path.normalize(rel);
2245
2259
  if (norm.startsWith("..") || path.isAbsolute(norm))
2246
2260
  throw new Error(`illegal path: ${rel}`);
2261
+ assertNameLengths(norm, rel);
2247
2262
  assertCanonicalCase(norm);
2248
2263
  if (norm === "project.md" || norm === "AGENTS.md")
2249
2264
  return norm;
2250
2265
  if (norm.includes("outputs/"))
2251
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}`);
2252
2272
  if (/scripts\//.test(norm) && SCRIPT_EXT.test(norm))
2253
2273
  return norm;
2254
2274
  if (/^agents\/[^/]+\/skills\/[^/]+\//.test(norm) && SCRIPT_EXT.test(norm))
@@ -2298,7 +2318,7 @@ export function accountFileSealed(rel) {
2298
2318
  * function is to refuse the person who clicked them, which is noise wearing
2299
2319
  * honesty's clothes. `accountFileSealed` still refuses these if a path is
2300
2320
  * 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(\.[^/]+)?$/;
2321
+ 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
2322
  /**
2303
2323
  * The account directory as it actually is on disk.
2304
2324
  *
@@ -2442,7 +2462,7 @@ function realLanding(full, followLast = true) {
2442
2462
  * path as written; a link planted inside the workspace — `knowledge/x.md` →
2443
2463
  * /etc/passwd, or a folder → / — passed them, and reads, writes and the run
2444
2464
  * archive followed it out. */
2445
- function landsInside(dir, full, followLast = true) {
2465
+ export function landsInside(dir, full, followLast = true) {
2446
2466
  // Canonical the same way as the path: a workspace not made yet under a
2447
2467
  // linked ancestor (macOS /tmp → /private/tmp) is its nearest real
2448
2468
  // ancestor plus the rest, or a first write into it would read as leaving.
@@ -2450,7 +2470,7 @@ function landsInside(dir, full, followLast = true) {
2450
2470
  const at = realLanding(full, followLast);
2451
2471
  return at !== null && (at === root || at.startsWith(root + path.sep));
2452
2472
  }
2453
- function assertLandsInside(dir, full, rel, followLast = true) {
2473
+ export function assertLandsInside(dir, full, rel, followLast = true) {
2454
2474
  if (!landsInside(dir, full, followLast))
2455
2475
  throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
2456
2476
  }
@@ -2651,6 +2671,7 @@ export function assertDeletable(tenant, workspace, rel) {
2651
2671
  const norm = path.normalize(rel).replaceAll("\\", "/");
2652
2672
  if (norm.startsWith("..") || path.isAbsolute(norm))
2653
2673
  throw new Error(`illegal path: ${rel}`);
2674
+ assertNameLengths(norm, rel);
2654
2675
  const dir = workspaceDir(tenant, workspace);
2655
2676
  // The two files a workspace cannot exist without. assertEditablePath lets
2656
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);
@@ -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>;