Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: split file utilities by responsibility (#4900)

Adam Eivy50dba78de0e1
diff --git a/server/lib/README.md b/server/lib/README.md
index 768b59bd2d..6d55346442 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -186,7 +186,13 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |
-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, and `isTopLevelEntryName(name)` is that shared traversal half on its own, for callers that can't allowlist extensions (arbitrary user assets, directory entries) but still must refuse separators so no intermediate component is left for a symlink to redirect, `readFileTail(path, maxBytes)` (bounded-memory tail read for append-only logs/spools with no size ceiling — null on error vs `''` for an empty file; shared by the agent-transcript cap, the TUI failure analyzer, and the Codex rollout scan), JSONL append/read/write helpers, `dirSize(path, { strict })` (forgiving by default; strict reporting mode rejects failed scans instead of forging zero), hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. `tryReadFileStrict(path, encoding?)` → `{ ok, value }` is the same distinction for RAW bytes (the strict twin of `tryReadFile`, #4115): `ok && value !== null` read, `ok && value === null` absent, `!ok` present-but-unreadable. Reach for either whenever the value is counted, displayed, OR written back — a read-modify-write that swallows an unreadable file persists the empty default over real data. Which call sites were audited and why the rest are safe: [docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md](../../docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md). Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. |
+| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
+| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
+| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore`. |
+| `mimeTypes.js` | MIME tables and extension allowlists, image format detection, and filename sanitization. |
+| `paths.js` | Canonical source/install `PATHS`, `dataPath`, and home-directory expansion. |
+| `pathSafety.js` | Filename/traversal validation, path containment, and approved image-asset resolvers. |
+| `uploads.js` | Upload staging/import, base64/image persistence, and safe local-file serving. |
| `icloudFile.js` | Guards against blocking reads of **evicted (dataless) cloud files**. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a `~/Library/CloudStorage` File Provider mount); the path and `size` remain but no blocks are local, and the first **data access** BLOCKS in the kernel until materialization completes — indefinitely and uncancellably when iCloud is wedged. Four such reads exhaust libuv's 4-thread fs pool and every later `fs` call in the process queues forever, including the `express.static` read that serves the UI bundle (the whole UI hangs while memory-only routes still answer). Retry-on-error can't help: the read doesn't fail, it hangs. `readIfMaterialized(path, {encoding, label})` screens with a `stat()` (safe — never materializes) and rejects with `err.code === ICLOUD_NOT_MATERIALIZED` instead of issuing the read, kicking a background `brctl download` so the next cycle succeeds; concurrent callers for one path+encoding share a single read. `isUbiquityPath(path)` resolves the containing directory's real path (memoized) rather than substring-matching, so a **symlinked** route into iCloud — `~/Documents/...` under "Desktop & Documents Folders" sync — is still recognized. `isDatalessStats(stats)` is the raw predicate (`size > 0 && blocks === 0`) and is **not safe alone** (a sparse or `decmpfs`-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via `isEvictedStats(path, stats)`, which is what a caller holding a `Stats` should use, or `isSuspectedDataless(path)` which does the `stat` itself. `requestMaterialization(path, {label, retryAfterExit, onFailure})` is the fire-and-forget `brctl download` every brctl caller shares — read paths kick it (default `retryAfterExit: true`) to heal an evicted file, per-path-deduped in a shared in-flight map capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at `DOWNLOAD_DEADLINE_MS` so a wedged `brctl` can't hold every slot for the life of the process; the boot/settings pin in `mortalLoomStore` passes `retryAfterExit: false` so it is NOT tracked in that shared map (it owns a single-sticky-path dedupe at its call site) plus an `onFailure` hook to clear that sticky path on a failed/killed download. `claimBrctlMissingWarning()` returns `true` on the first call only, so the "brctl not found on PATH" warning fires at most once per process across every brctl caller (the fire-and-forget path here and the awaited `materializeAndWait`). `materializeAndWait(path, {label, timeoutMs})` is the **awaited, bounded** counterpart used by WRITE paths (`mortalLoomStore` before overwriting its store, `obsidian.updateNote` before overwriting a note): a write must not silently skip, so it materializes and waits rather than firing and forgetting, bounded by `MATERIALIZE_TIMEOUT_MS` (20s — much tighter than the background `DOWNLOAD_DEADLINE_MS` because a caller is blocked on it) and run in a child process, which is what makes the wait cancellable when the kernel write it replaces would not be. It resolves `true` only on brctl exit-0, which means the download was **accepted, not completed** — always re-screen before trusting the file. Measured (#3706, #3713), and recorded in the module docblock's syscall table: `stat`/`open`/`rename`/`unlink` never materialize, while `read`, `write` (including after `O_TRUNC` — truncating does NOT skip the download), `link`, and `clonefile` all do. `unlink` being free is a measurement, not the POSIX inference — `link` is pure metadata too and it *does* materialize — so delete paths need no screen. The docblock also carries the reproduction recipe: `brctl evict <path>` works (undocumented, like `brctl download`), which is what makes the evict/measure/heal loop scriptable. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. |
| `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. |
| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |
diff --git a/server/lib/fileCore.js b/server/lib/fileCore.js
new file mode 100644
index 0000000000..6341d6a787
--- /dev/null
+++ b/server/lib/fileCore.js
@@ -0,0 +1,465 @@
+/** Cross-cutting filesystem, time, formatting, and hashing helpers. */
+import { access, chmod, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';
+import { createReadStream, existsSync, statSync, watch as watchFileSystem } from 'fs';
+import { createHash, randomUUID } from 'crypto';
+import { basename, dirname, extname, join } from 'path';
+import { promisify } from 'util';
+import { execFile } from './childProcess.js';
+
+export const execFileAsync = promisify(execFile);
+const IS_WIN = process.platform === 'win32';
+
+// Call-time platform probe. `IS_WIN` above is a module-load snapshot (fine for
+// the path-shape helper at the bottom of this file); the Windows retry paths
+// below read the platform on every call so a POSIX host never carries a stale
+// decision and so the retry behavior is exercisable in tests.
+const isWindows = () => process.platform === 'win32';
+
+// Windows-only retry knobs (#4095). A destination lock from a concurrent reader
+// or an AV scan clears in milliseconds, so a handful of short retries is enough
+// to avoid both the writer's destination-missing backup swap and the reader's
+// phantom "nothing here yet".
+const WIN_RETRY_ATTEMPTS = 5;
+const WIN_RETRY_DELAY_MS = 10;
+// rename(2) failures that mean "the destination is momentarily locked", not
+// "this rename can never work".
+const WIN_RENAME_LOCK_CODES = ['EPERM', 'EACCES', 'EEXIST'];
+// read failures with the same transient meaning on the reader side.
+const WIN_READ_LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY'];
+const FILE_WATCH_FALLBACK_POLL_MS = 5000;
+
+/** Watch for a file to appear without repeatedly stat'ing its parent directory. */
+export function watchForFile(filePath, onDetected, { settleMs = 50, pollMs = FILE_WATCH_FALLBACK_POLL_MS } = {}) {
+ const targetName = basename(filePath);
+ const targetDir = dirname(filePath);
+ let closed = false;
+ let detected = false;
+ let settleTimer = null;
+ let pollTimer = null;
+
+ const notify = () => {
+ Promise.resolve(onDetected()).catch((err) => {
+ console.error(`❌ File watcher callback failed: ${err.message}`);
+ });
+ };
+ const close = (onClosed) => {
+ if (closed) return;
+ closed = true;
+ if (settleTimer) clearTimeout(settleTimer);
+ if (pollTimer) clearInterval(pollTimer);
+ if (onClosed) watcher.once('close', onClosed);
+ watcher.close();
+ };
+ const detect = (settle = true) => {
+ if (closed || detected || !existsSync(filePath)) return;
+ detected = true;
+ if (!settle) {
+ close(notify);
+ return;
+ }
+ settleTimer = setTimeout(() => {
+ settleTimer = null;
+ if (closed) return;
+ close(notify);
+ }, settleMs);
+ };
+ const watcher = watchFileSystem(targetDir, (_eventType, changedName) => {
+ if (changedName == null || changedName.toString() === targetName) detect();
+ });
+ // fs.watch is low-latency but best-effort: native backends can miss a file
+ // creation or atomic rename. Keep a deliberately relaxed fallback so a
+ // missed event cannot strand an agent indefinitely.
+ pollTimer = setInterval(() => detect(), pollMs);
+ detect(false);
+ return close;
+}
+
+// Cache __dirname calculation for services importing this module
+/**
+ * Ensure a directory exists, creating it recursively if needed.
+ * Uses mkdir with recursive: true which is idempotent and avoids TOCTOU races.
+ *
+ * @param {string} dir - Directory path to ensure exists
+ * @returns {Promise<void>}
+ *
+ * @example
+ * await ensureDir(PATHS.data);
+ * await ensureDir('/custom/path/to/dir');
+ */
+export async function ensureDir(dir) {
+ // mkdir with recursive: true is idempotent - it succeeds if dir exists.
+ // BUT on Windows it can intermittently throw UNKNOWN/EPERM/EEXIST even when
+ // the directory already exists or is created concurrently — antivirus locks,
+ // OneDrive sync, and network/mapped drives all surface spurious failures that
+ // the POSIX-modeled `recursive: true` no-op contract doesn't anticipate.
+ // Swallow the error when the path is in fact a directory afterward.
+ await mkdir(dir, { recursive: true }).catch((err) => {
+ if (err?.code === 'EEXIST') return; // already exists — the intended state
+ const s = statSync(dir, { throwIfNoEntry: false });
+ if (s && s.isDirectory()) {
+ console.log(`⚠️ ensureDir swallowed spurious ${err?.code || 'error'} — dir exists: ${dir}`);
+ return;
+ }
+ throw err;
+ });
+}
+
+/**
+ * Async existence check — the non-blocking replacement for `existsSync` on
+ * request/hot paths. Resolves true iff `path` is accessible, false otherwise.
+ * Never throws (a missing path, permission error, etc. all resolve false), so
+ * it drops in wherever `existsSync` guarded a request handler.
+ *
+ * @param {string} path - File or directory path to test.
+ * @returns {Promise<boolean>}
+ *
+ * @example
+ * if (!(await pathExists(filepath))) throw new ServerError('Not found', { status: 404 });
+ */
+export async function pathExists(path) {
+ return access(path).then(() => true, () => false);
+}
+
+/**
+ * Ensure multiple directories exist.
+ *
+ * @param {string[]} dirs - Array of directory paths to ensure exist
+ * @returns {Promise<void>}
+ *
+ * @example
+ * await ensureDirs([PATHS.data, PATHS.cos, PATHS.memory]);
+ */
+export async function ensureDirs(dirs) {
+ for (const dir of dirs) {
+ await ensureDir(dir);
+ }
+}
+
+/**
+ * Atomically write data to a file via temp-file + rename.
+ * Guarantees readers never see a partial write. Accepts a string or any JSON-
+ * serializable value (objects are stringified with 2-space indentation).
+ *
+ * Symlink semantics (design decision, issue #1893): when `filePath` is a
+ * symlink, the temp+rename REPLACES the link with a regular file — it does NOT
+ * follow the link to update the backing file. This is the standard atomic-write
+ * contract (git, dpkg, rsync, `os.replace` all replace the link); following the
+ * link would reintroduce the non-atomic in-place truncate this helper exists to
+ * eliminate. PortOS ships no symlinked data files, so this is a documented
+ * property rather than a supported use case — do not pass a symlink you expect
+ * to be followed. Callers that genuinely need follow-the-link semantics must
+ * resolve `realpath(filePath)` themselves before calling.
+ *
+ * @param {string} filePath - Destination file path
+ * @param {string|object} data - String or JSON-serializable value
+ * @returns {Promise<void>}
+ *
+ * @example
+ * await atomicWrite(FILE, { version: 1, items: [] });
+ * await atomicWrite(LOG_FILE, 'raw string content');
+ */
+export async function atomicWrite(filePath, data) {
+ // Buffer must pass through unchanged — JSON.stringify on a Buffer produces
+ // `{"type":"Buffer","data":[...]}` which corrupts binary writes (PNG, etc.).
+ const payload = typeof data === 'string' || Buffer.isBuffer(data) ? data : JSON.stringify(data, null, 2);
+ await ensureDir(dirname(filePath));
+ // Preserve the destination's existing permission bits. A plain
+ // writeFile(existing) truncated the inode in place and kept its mode, but
+ // atomicWrite creates a fresh temp inode and renames it over the target —
+ // which would silently widen a hand-restricted file (e.g. a `chmod 600`
+ // OAuth tokens.json) to the umask default (typically 0644) on every rewrite.
+ // Read the destination's mode FIRST and create the temp file with it from
+ // the start, so the secret bytes are never written to a world-readable temp
+ // (a crash between write and chmod would otherwise leave a readable copy, and
+ // a local user could race-read it during the window). A trailing chmod pins
+ // the exact mode in case the umask tightened the create below it. New files
+ // (stat fails with ENOENT) keep the umask default, exactly as before.
+ const existingMode = await stat(filePath).then((s) => s.mode & 0o777, () => null);
+ const tmp = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
+ await writeFile(tmp, payload, existingMode !== null ? { mode: existingMode } : undefined);
+ if (existingMode !== null) {
+ await chmod(tmp, existingMode).catch(() => {});
+ }
+ // Node's fs.rename uses MoveFileExW with MOVEFILE_REPLACE_EXISTING on Windows (atomic
+ // overwrite), but still fails with EPERM/EACCES if the destination is locked (AV scan,
+ // concurrent reader). Fall back to a backup-swap so the original file is never lost.
+ const replace = async () => {
+ let err = await rename(tmp, filePath).then(() => null, (e) => e);
+ // Retry the ATOMIC rename before resorting to the backup swap (#4095). The
+ // swap below renames the destination away and back, so for that instant the
+ // destination DOES NOT EXIST — a concurrent read lands on ENOENT and reads
+ // it as a trustworthy "nothing here yet", silently handing the caller its
+ // default instead of the file's real contents. A transient lock clears in
+ // milliseconds, so retrying keeps almost every write on the atomic path and
+ // never opens that window.
+ if (isWindows()) {
+ for (let attempt = 1; err && attempt < WIN_RETRY_ATTEMPTS && WIN_RENAME_LOCK_CODES.includes(err.code); attempt += 1) {
+ await sleep(WIN_RETRY_DELAY_MS);
+ err = await rename(tmp, filePath).then(() => null, (e) => e);
+ if (!err) console.log(`⚠️ atomicWrite rename succeeded after ${attempt} retry(s): ${basename(filePath)}`);
+ }
+ }
+ if (!err) return;
+ if (isWindows() && WIN_RENAME_LOCK_CODES.includes(err.code)) {
+ const bak = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.bak`;
+ const hadExisting = await rename(filePath, bak).then(() => true, (e) => {
+ if (e.code === 'ENOENT') return false;
+ throw e;
+ });
+ const renameErr = await rename(tmp, filePath).then(() => null, (e) => e);
+ if (renameErr) {
+ if (hadExisting) await rename(bak, filePath).catch(() => {});
+ throw renameErr;
+ }
+ if (hadExisting) await unlink(bak).catch(() => {});
+ return;
+ }
+ throw err;
+ };
+ try {
+ await replace();
+ } catch (err) {
+ await unlink(tmp).catch(() => {});
+ throw err;
+ }
+}
+
+export const MINUTE = 60 * 1000;
+export const HOUR = 60 * MINUTE;
+export const DAY = 24 * HOUR;
+
+/**
+ * Promise-based delay. Canonical replacement for the per-module
+ * `const delay = (ms) => new Promise(...)` one-liners.
+ *
+ * @param {number} ms - Milliseconds to wait
+ * @returns {Promise<void>}
+ */
+export function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+/**
+ * Format a date as YYYY-MM-DD string.
+ *
+ * @param {Date} [date=new Date()] - Date to format
+ * @returns {string} ISO date string (e.g., "2026-03-05")
+ */
+export function getDateString(date = new Date()) {
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
+}
+
+/**
+ * UUID v4 regex pattern for validating account/entity IDs.
+ */
+export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/**
+ * Truncate an id to a fixed prefix for human-readable log lines. Null-safe
+ * so callers can pass a possibly-missing field directly (`shortId(run?.id)`)
+ * without an outer truthiness check.
+ *
+ * @param {*} id - id-like value; coerced to string
+ * @param {number} [n=8] - prefix length
+ * @returns {string} prefix of length `n`, or `''` when `id` is null/undefined
+ */
+export function shortId(id, n = 8) {
+ if (id == null) return '';
+ return String(id).slice(0, n);
+}
+
+/**
+ * Safely parse a date value to epoch milliseconds.
+ * Returns 0 for invalid/missing dates instead of NaN.
+ *
+ * @param {string|Date|number} d - Date value to parse
+ * @returns {number} Epoch milliseconds, or 0 if invalid
+ */
+export function safeDate(d) {
+ const t = new Date(d).getTime();
+ return Number.isNaN(t) ? 0 : t;
+}
+
+/**
+ * Generic search filter — returns items where any of the specified fields
+ * contain the search string (case-insensitive).
+ *
+ * @param {Array<Object>} items - Items to filter
+ * @param {string} search - Search query
+ * @param {Array<string>} fields - Dot-notation field paths to search (e.g., 'from.name')
+ * @returns {Array<Object>} Filtered items
+ */
+export function filterBySearch(items, search, fields) {
+ if (!search) return items;
+ const q = search.toLowerCase();
+ return items.filter(item =>
+ fields.some(field => {
+ const val = field.includes('.') ? field.split('.').reduce((o, k) => o?.[k], item) : item[field];
+ return val?.toLowerCase?.().includes(q);
+ })
+ );
+}
+
+/**
+ * Format a duration in milliseconds to a human-readable string.
+ * Outputs the most appropriate unit (minutes, hours, days) based on size.
+ *
+ * @param {number} ms - Duration in milliseconds
+ * @returns {string} Formatted duration (e.g., "5m", "2h 30m", "3d 5h")
+ *
+ * @example
+ * formatDuration(30000) // "0m"
+ * formatDuration(300000) // "5m"
+ * formatDuration(7200000) // "2h 0m"
+ * formatDuration(90000000) // "1d 1h"
+ */
+export function formatDuration(ms) {
+ if (!ms) return '0m';
+ const mins = Math.floor(ms / 60000);
+ const hours = Math.floor(mins / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) {
+ const remainingHours = hours % 24;
+ return `${days}d ${remainingHours}h`;
+ }
+ if (hours > 0) {
+ const remainingMins = mins % 60;
+ return `${hours}h ${remainingMins}m`;
+ }
+ return `${mins}m`;
+}
+
+export function formatBytes(bytes) {
+ if (!bytes) return '0 B';
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
+ return (bytes / Math.pow(1024, i)).toFixed(i > 1 ? 1 : 0) + ' ' + units[i];
+}
+
+// =============================================================================
+// FILENAME / MIME HELPERS (shared by uploads, attachments, screenshots routes)
+// =============================================================================
+
+/**
+ * List a directory, keep entries whose extension matches `extensions`, stat
+ * each, and project the survivors through `mapEntry(name, fullPath, stat)`.
+ * Three sibling helpers (listLoras / listGallery / listMusicLibrary) used to
+ * spell this loop out by hand — collapsed onto one primitive so the dir-
+ * missing fallback, extension filter, and stat-failure handling all stay in
+ * sync.
+ *
+ * - `extensions`: array of lowercased extensions including the leading dot
+ * (`['.png']`, `['.mp3', '.wav', ...]`). Matched against `extname(name)`
+ * case-insensitively so `FOO.PNG` and `foo.png` both pass.
+ * - `mapEntry`: async/sync `(name, fullPath, stat) => entry|null`. Return
+ * `null` to drop the entry. Final array preserves readdir order minus drops.
+ * - `requireRegularFile` (default `true`): when true, entries whose stat
+ * reports `!isFile()` are dropped before `mapEntry` runs (skips directories
+ * with matching extensions). Pass `false` to match the gallery's legacy
+ * behavior (only drops on stat failure).
+ *
+ * Missing directory → `[]` (no surprise 500 on a fresh install). Stat errors
+ * on individual entries → drop that entry (matches the prior per-site
+ * `.catch(() => null)` pattern).
+ */
+export async function listDirectoryByExtension(dir, { extensions, mapEntry, requireRegularFile = true } = {}) {
+ if (!Array.isArray(extensions) || extensions.length === 0) {
+ throw new Error('listDirectoryByExtension: extensions allowlist is required');
+ }
+ if (typeof mapEntry !== 'function') {
+ throw new Error('listDirectoryByExtension: mapEntry must be a function');
+ }
+ const allowed = new Set(extensions.map((e) => String(e).toLowerCase()));
+ const names = await readdir(dir).catch((err) => {
+ if (err?.code === 'ENOENT') return [];
+ throw err;
+ });
+ const filtered = names.filter((name) => allowed.has((extname(name) || '').toLowerCase()));
+ const entries = await Promise.all(filtered.map(async (name) => {
+ const fullPath = join(dir, name);
+ const s = await stat(fullPath).catch(() => null);
+ if (!s) return null;
+ if (requireRegularFile && !s.isFile()) return null;
+ return mapEntry(name, fullPath, s);
+ }));
+ return entries.filter((v) => v != null);
+}
+
+// Size in bytes of every file under `path`. Shells out to `du -sk` (or
+// PowerShell on Windows) — orders of magnitude faster than walking with
+// node's recursive readdir on large trees (hundreds of GB / 200k+ files).
+// Returns 0 + logs on failure (missing tool, permission denied, timeout) so
+// the Media Models endpoint stays responsive even on unusual systems instead
+// of throwing and 500ing the whole route. Counted/reporting callers can pass
+// `{ strict: true }` to reject instead, preserving failed-vs-legitimately-empty.
+export async function dirSize(path, { strict = false } = {}) {
+ if (strict) {
+ const present = await stat(path).then(
+ () => true,
+ (err) => {
+ if (err?.code === 'ENOENT') return false;
+ throw err;
+ },
+ );
+ if (!present) return 0;
+ } else if (!existsSync(path)) {
+ return 0;
+ }
+ if (IS_WIN) {
+ // Pass the path via an env var so a literal apostrophe in the path can't
+ // close the PowerShell string and inject commands.
+ const result = await execFileAsync('powershell', [
+ '-NoProfile', '-Command',
+ '(Get-ChildItem -Recurse -File $Env:DIRSIZE_TARGET | Measure-Object -Property Length -Sum).Sum',
+ ], { encoding: 'utf8', timeout: 60_000, env: { ...process.env, DIRSIZE_TARGET: path } }).catch((err) => ({ error: err }));
+ if (result.error) {
+ if (strict) throw result.error;
+ console.log(`⚠️ dirSize(${path}) failed: ${result.error.message}`);
+ return 0;
+ }
+ const bytes = parseInt(result.stdout.trim(), 10);
+ if (!Number.isFinite(bytes) || bytes < 0) {
+ if (strict) throw new Error(`Could not parse directory size for ${path}`);
+ return 0;
+ }
+ return bytes;
+ }
+ const result = await execFileAsync('du', ['-sk', path], { encoding: 'utf8', timeout: 60_000 }).catch((err) => ({ error: err }));
+ if (result.error) {
+ if (strict) throw result.error;
+ console.log(`⚠️ dirSize(${path}) failed: ${result.error.message}`);
+ return 0;
+ }
+ const kb = parseInt(result.stdout.split('\t')[0], 10);
+ if (!Number.isFinite(kb) || kb < 0) {
+ if (strict) throw new Error(`Could not parse directory size for ${path}`);
+ return 0;
+ }
+ return kb * 1024;
+}
+
+/** SHA-256 a string or Buffer as hex — `sha256File`'s in-memory twin. */
+export const sha256Text = (value) => createHash('sha256').update(value).digest('hex');
+
+/**
+ * SHA-256 a file as hex. One-shot read under 512 KB; streams above so multi-GB
+ * videos don't blow heap. Threshold matches `server/services/backup.js`'s
+ * snapshot manifest generator.
+ */
+const SHA256_STREAM_THRESHOLD = 512 * 1024;
+export async function sha256File(path) {
+ const info = await stat(path);
+ if (info.size < SHA256_STREAM_THRESHOLD) {
+ const buf = await readFile(path);
+ return createHash('sha256').update(buf).digest('hex');
+ }
+ return new Promise((resolve, reject) => {
+ const hasher = createHash('sha256');
+ const stream = createReadStream(path);
+ stream.on('error', reject);
+ stream.pipe(hasher);
+ hasher.on('finish', () => resolve(hasher.digest('hex')));
+ hasher.on('error', reject);
+ });
+}
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 0c3513ab2a..245ee2c645 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -1,1968 +1,12 @@
/**
- * File System Utilities
+ * Backward-compatible file utility facade.
*
- * Shared utilities for file operations used across services.
+ * New code should import from the focused module that owns the helper. Existing
+ * deep imports remain stable while callers migrate opportunistically.
*/
-
-import { access, appendFile, chmod, mkdir, open, readFile, readdir, stat, writeFile, rename, unlink, copyFile } from 'fs/promises';
-import { existsSync, statSync, createReadStream, watch as watchFileSystem } from 'fs';
-import { execFile } from './childProcess.js';
-import { promisify } from 'util';
-import { createHash, randomUUID } from 'crypto';
-import { join, dirname, basename, extname, resolve as resolvePath, sep as PATH_SEP } from 'path';
-import { fileURLToPath } from 'url';
-import { homedir } from 'os';
-import { ServerError } from './errorHandler.js';
-import { resolveInstallRoot } from './dataRoot.js';
-import { createFileWriteQueue } from './fileWriteQueue.js';
-
-// Promisified execFile — shared so callers (e.g. backup's pg_dump probing)
-// don't each re-wrap it. Returns { stdout, stderr }.
-export const execFileAsync = promisify(execFile);
-const IS_WIN = process.platform === 'win32';
-
-// Call-time platform probe. `IS_WIN` above is a module-load snapshot (fine for
-// the path-shape helper at the bottom of this file); the Windows retry paths
-// below read the platform on every call so a POSIX host never carries a stale
-// decision and so the retry behavior is exercisable in tests.
-const isWindows = () => process.platform === 'win32';
-
-// Windows-only retry knobs (#4095). A destination lock from a concurrent reader
-// or an AV scan clears in milliseconds, so a handful of short retries is enough
-// to avoid both the writer's destination-missing backup swap and the reader's
-// phantom "nothing here yet".
-const WIN_RETRY_ATTEMPTS = 5;
-const WIN_RETRY_DELAY_MS = 10;
-// rename(2) failures that mean "the destination is momentarily locked", not
-// "this rename can never work".
-const WIN_RENAME_LOCK_CODES = ['EPERM', 'EACCES', 'EEXIST'];
-// read failures with the same transient meaning on the reader side.
-const WIN_READ_LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY'];
-const FILE_WATCH_FALLBACK_POLL_MS = 5000;
-
-/** Watch for a file to appear without repeatedly stat'ing its parent directory. */
-export function watchForFile(filePath, onDetected, { settleMs = 50, pollMs = FILE_WATCH_FALLBACK_POLL_MS } = {}) {
- const targetName = basename(filePath);
- const targetDir = dirname(filePath);
- let closed = false;
- let detected = false;
- let settleTimer = null;
- let pollTimer = null;
-
- const notify = () => {
- Promise.resolve(onDetected()).catch((err) => {
- console.error(`❌ File watcher callback failed: ${err.message}`);
- });
- };
- const close = (onClosed) => {
- if (closed) return;
- closed = true;
- if (settleTimer) clearTimeout(settleTimer);
- if (pollTimer) clearInterval(pollTimer);
- if (onClosed) watcher.once('close', onClosed);
- watcher.close();
- };
- const detect = (settle = true) => {
- if (closed || detected || !existsSync(filePath)) return;
- detected = true;
- if (!settle) {
- close(notify);
- return;
- }
- settleTimer = setTimeout(() => {
- settleTimer = null;
- if (closed) return;
- close(notify);
- }, settleMs);
- };
- const watcher = watchFileSystem(targetDir, (_eventType, changedName) => {
- if (changedName == null || changedName.toString() === targetName) detect();
- });
- // fs.watch is low-latency but best-effort: native backends can miss a file
- // creation or atomic rename. Keep a deliberately relaxed fallback so a
- // missed event cannot strand an agent indefinitely.
- pollTimer = setInterval(() => detect(), pollMs);
- detect(false);
- return close;
-}
-
-// Cache __dirname calculation for services importing this module
-const __lib_filename = fileURLToPath(import.meta.url);
-const __lib_dirname = dirname(__lib_filename);
-
-// The executing checkout's root (where THIS file physically lives). Code/source
-// paths — the repo root for git ops, `lib/slashdo` — must stay anchored here so
-// they always point at the checkout that loaded the code.
-const CODE_ROOT = join(__lib_dirname, '../..');
-
-// The install root that holds the runtime `data/` tree. Prefer an explicit
-// PORTOS_DATA_ROOT env var over the executing-file location so a process booted
-// from inside a CoS agent git worktree resolves `data/` to the real install
-// instead of the worktree's empty checkout (#1947). Falls back to CODE_ROOT
-// when the env var is unset (the two coincide for a normal install). Only
-// `data/*` paths follow this — source/git paths stay on CODE_ROOT.
-const INSTALL_ROOT = resolveInstallRoot(CODE_ROOT);
-
-/**
- * MIME types that could execute scripts when served inline — force Content-Disposition: attachment
- */
-export const RISKY_MIME_TYPES = new Set(['text/html', 'image/svg+xml', 'application/javascript', 'text/javascript', 'application/xml']);
-
-/**
- * Base directories relative to project root
- */
-export const PATHS = {
- root: CODE_ROOT,
- // The data-bearing install root (parent of `data/`). Equals `root` for a
- // normal install; diverges only when PORTOS_DATA_ROOT pins a different tree
- // (worktree boot, #1947). Use this — not `root` — for anything anchored to
- // the `data/` tree but living one level above it (e.g. the migration ledger
- // `data/migrations.applied.json`), so its reader agrees with where boot wrote it.
- installRoot: INSTALL_ROOT,
- data: join(INSTALL_ROOT, 'data'),
- cos: join(INSTALL_ROOT, 'data/cos'),
- brain: join(INSTALL_ROOT, 'data/brain'),
- digitalTwin: join(INSTALL_ROOT, 'data/digital-twin'),
- health: join(INSTALL_ROOT, 'data/health'),
- runs: join(INSTALL_ROOT, 'data/runs'),
- memory: join(INSTALL_ROOT, 'data/cos/memory'),
- cosAgents: join(INSTALL_ROOT, 'data/cos/agents'), // CoS sub-agents
- scripts: join(INSTALL_ROOT, 'data/cos/scripts'),
- reports: join(INSTALL_ROOT, 'data/cos/reports'),
- // AI Agent Personalities data
- agentPersonalities: join(INSTALL_ROOT, 'data/agents'),
- meatspace: join(INSTALL_ROOT, 'data/meatspace'),
- calendar: join(INSTALL_ROOT, 'data/calendar'),
- messages: join(INSTALL_ROOT, 'data/messages'),
- screenshots: join(INSTALL_ROOT, 'data/screenshots'),
- uploads: join(INSTALL_ROOT, 'data/uploads'),
- cosAttachments: join(INSTALL_ROOT, 'data/cos/attachments'),
- worktrees: join(INSTALL_ROOT, 'data/cos/worktrees'),
- repos: join(INSTALL_ROOT, 'data/repos'),
- browserProfile: join(INSTALL_ROOT, 'data/browser-profile'),
- browserDownloads: join(homedir(), 'Downloads'),
- digests: join(INSTALL_ROOT, 'data/cos/digests'),
- promptSkills: join(INSTALL_ROOT, 'data/prompts/skills'),
- promptSkillsJobs: join(INSTALL_ROOT, 'data/prompts/skills/jobs'),
- decisions: join(INSTALL_ROOT, 'data/cos/decisions'),
- telegram: join(INSTALL_ROOT, 'data/telegram'),
- templates: join(INSTALL_ROOT, 'data/prompts/templates'),
- // Visual template assets (e.g. the character reference-sheet layout PNG used
- // as the init-image anchor by the universe-builder character sheet renderer).
- // Distinct from `templates` above, which is the legacy prompt-template dir.
- // Files here are shipped via data.reference/templates/ on first install.
- visualTemplates: join(INSTALL_ROOT, 'data/templates'),
- settings: join(INSTALL_ROOT, 'data/settings'),
- missions: join(INSTALL_ROOT, 'data/cos/missions'),
- tools: join(INSTALL_ROOT, 'data/tools'),
- images: join(INSTALL_ROOT, 'data/images'),
- // Uploaded multi-reference inputs for FLUX.2 multi-ref edits. Sibling of
- // `images/` rather than a subdir so the gallery's flat `.png` enumeration
- // never surfaces them, and so a future per-render cleanup pass can drop
- // the whole dir without touching the gallery.
- imageRefs: join(INSTALL_ROOT, 'data/image-refs'),
- // Ephemeral working dir for the Image Cleaner's GPU FLUX round-trip (issue
- // #2264). The sync-cleaned init bytes and the finished render land here as
- // `<jobId>-init.png` / `<jobId>-result.png` so the cleaner can render WITHOUT
- // writing a gallery file + sidecar (the default is not to keep the result).
- // A sibling of `images/` — never surfaced by the gallery's flat `.png`
- // enumeration; swept by imageCleanTmpGc.js on an age gate. Not federated.
- imageCleanTmp: join(INSTALL_ROOT, 'data/image-clean-tmp'),
- // PROVIDER-side staging for conditioning images an allowlisted peer uploaded
- // ahead of a federated render (ADR
- // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1). Files are
- // named `<callerHash>-<sha256>.<ext>` and swept on a TTL.
- //
- // Deliberately its own root rather than a corner of `images/` or `uploads/`:
- // these are ANOTHER machine's bytes, held briefly to run one job. Under
- // `images/` the gallery would enumerate them and the sync layer would federate
- // them onward (the failure this repo already hit once with temp files in
- // data/images). Excluded from backups for the same reason — restoring a peer's
- // half-hour-old init image is worth nothing.
- federatedMediaInbox: join(INSTALL_ROOT, 'data/federated-media-inbox'),
- loras: join(INSTALL_ROOT, 'data/loras'),
- // Per-character LoRA training datasets (collectionStore layout:
- // lora-datasets/<id>/index.json + lora-datasets/<id>/images/*.png).
- // Machine-local like `loras/` — datasets never federate.
- loraDatasets: join(INSTALL_ROOT, 'data/lora-datasets'),
- // LoRA training run artifacts (checkpoints/samples/cache per run). Run
- // RECORDS live in Postgres (lora_training_runs); only artifacts live here.
- trainingRuns: join(INSTALL_ROOT, 'data/training-runs'),
- videos: join(INSTALL_ROOT, 'data/videos'),
- videoThumbnails: join(INSTALL_ROOT, 'data/video-thumbnails'),
- // Sprite Manager (issue #2895): per-record asset trees
- // (sprites/<id>/{reference,walk,runs,runtime,atlas}/...). Records live in
- // Postgres (sprite_records); only binary artifacts + manifests live here.
- sprites: join(INSTALL_ROOT, 'data/sprites'),
- // Image-to-3D (issue #2952): per-record GLB meshes rendered locally by a
- // target (TRELLIS.2 today), stored as image-to-3d/<id>/model.glb. Records
- // live in Postgres (image_to_3d_models); only the binary GLB lives here.
- imageTo3d: join(INSTALL_ROOT, 'data/image-to-3d'),
- // Persisted audio renders (voice-over lines). Kept distinct from
- // the in-memory voice-agent synthesis path in services/voice/ — that path
- // streams WAV over Socket.IO without ever touching disk.
- audio: join(INSTALL_ROOT, 'data/audio'),
- // Uploaded + (eventually) generated background music tracks. Separate from
- // `audio/` so the user can browse + reuse a track across issues without
- // walking through the VO-line filenames.
- music: join(INSTALL_ROOT, 'data/music'),
- // Extracted assets from third-party imports (ChatGPT export images/audio/
- // PDFs). Served read-only at `/data/brain-imports/...` so the Memory
- // conversation viewer can render inline `![](url)` images and asset links.
- // Flat per-source dir keyed by the asset's globally-unique id, so the same
- // asset referenced from multiple conversations is stored once. The transcript
- // archive JSON lives one level up (data/brain/imports/<source>/) and is NOT
- // served — only this assets subtree is.
- brainImportAssets: join(INSTALL_ROOT, 'data/brain/imports/assets'),
- // SongBook attachment BYTES (PDF sheet music, images, MIDI). Machine-local —
- // only the metadata syncs inside the brain `songs` record; peers lacking a
- // file render "not on this machine". Covered by backup via data/brain/.
- brainSongbook: join(INSTALL_ROOT, 'data/brain/songbook'),
- slashdo: join(CODE_ROOT, 'lib/slashdo'),
- // Fully-resolved slashdo command bodies written for CoS agents to READ on
- // demand instead of receiving them pasted into the prompt (issue #3110).
- // Derived cache, never authored: regenerated on first use each process, safe
- // to delete. Anchored to INSTALL_ROOT (not CODE_ROOT) because the pointer
- // handed to an agent must name a path that exists on the running install.
- slashdoResolved: join(INSTALL_ROOT, 'data/cos/slashdo-resolved')
-};
-
-/**
- * Ensure a directory exists, creating it recursively if needed.
- * Uses mkdir with recursive: true which is idempotent and avoids TOCTOU races.
- *
- * @param {string} dir - Directory path to ensure exists
- * @returns {Promise<void>}
- *
- * @example
- * await ensureDir(PATHS.data);
- * await ensureDir('/custom/path/to/dir');
- */
-export async function ensureDir(dir) {
- // mkdir with recursive: true is idempotent - it succeeds if dir exists.
- // BUT on Windows it can intermittently throw UNKNOWN/EPERM/EEXIST even when
- // the directory already exists or is created concurrently — antivirus locks,
- // OneDrive sync, and network/mapped drives all surface spurious failures that
- // the POSIX-modeled `recursive: true` no-op contract doesn't anticipate.
- // Swallow the error when the path is in fact a directory afterward.
- await mkdir(dir, { recursive: true }).catch((err) => {
- if (err?.code === 'EEXIST') return; // already exists — the intended state
- const s = statSync(dir, { throwIfNoEntry: false });
- if (s && s.isDirectory()) {
- console.log(`⚠️ ensureDir swallowed spurious ${err?.code || 'error'} — dir exists: ${dir}`);
- return;
- }
- throw err;
- });
-}
-
-/**
- * Async existence check — the non-blocking replacement for `existsSync` on
- * request/hot paths. Resolves true iff `path` is accessible, false otherwise.
- * Never throws (a missing path, permission error, etc. all resolve false), so
- * it drops in wherever `existsSync` guarded a request handler.
- *
- * @param {string} path - File or directory path to test.
- * @returns {Promise<boolean>}
- *
- * @example
- * if (!(await pathExists(filepath))) throw new ServerError('Not found', { status: 404 });
- */
-export async function pathExists(path) {
- return access(path).then(() => true, () => false);
-}
-
-/**
- * Ensure multiple directories exist.
- *
- * @param {string[]} dirs - Array of directory paths to ensure exist
- * @returns {Promise<void>}
- *
- * @example
- * await ensureDirs([PATHS.data, PATHS.cos, PATHS.memory]);
- */
-export async function ensureDirs(dirs) {
- for (const dir of dirs) {
- await ensureDir(dir);
- }
-}
-
-/**
- * Atomically write data to a file via temp-file + rename.
- * Guarantees readers never see a partial write. Accepts a string or any JSON-
- * serializable value (objects are stringified with 2-space indentation).
- *
- * Symlink semantics (design decision, issue #1893): when `filePath` is a
- * symlink, the temp+rename REPLACES the link with a regular file — it does NOT
- * follow the link to update the backing file. This is the standard atomic-write
- * contract (git, dpkg, rsync, `os.replace` all replace the link); following the
- * link would reintroduce the non-atomic in-place truncate this helper exists to
- * eliminate. PortOS ships no symlinked data files, so this is a documented
- * property rather than a supported use case — do not pass a symlink you expect
- * to be followed. Callers that genuinely need follow-the-link semantics must
- * resolve `realpath(filePath)` themselves before calling.
- *
- * @param {string} filePath - Destination file path
- * @param {string|object} data - String or JSON-serializable value
- * @returns {Promise<void>}
- *
- * @example
- * await atomicWrite(FILE, { version: 1, items: [] });
- * await atomicWrite(LOG_FILE, 'raw string content');
- */
-export async function atomicWrite(filePath, data) {
- // Buffer must pass through unchanged — JSON.stringify on a Buffer produces
- // `{"type":"Buffer","data":[...]}` which corrupts binary writes (PNG, etc.).
- const payload = typeof data === 'string' || Buffer.isBuffer(data) ? data : JSON.stringify(data, null, 2);
- await ensureDir(dirname(filePath));
- // Preserve the destination's existing permission bits. A plain
- // writeFile(existing) truncated the inode in place and kept its mode, but
- // atomicWrite creates a fresh temp inode and renames it over the target —
- // which would silently widen a hand-restricted file (e.g. a `chmod 600`
- // OAuth tokens.json) to the umask default (typically 0644) on every rewrite.
- // Read the destination's mode FIRST and create the temp file with it from
- // the start, so the secret bytes are never written to a world-readable temp
- // (a crash between write and chmod would otherwise leave a readable copy, and
- // a local user could race-read it during the window). A trailing chmod pins
- // the exact mode in case the umask tightened the create below it. New files
- // (stat fails with ENOENT) keep the umask default, exactly as before.
- const existingMode = await stat(filePath).then((s) => s.mode & 0o777, () => null);
- const tmp = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
- await writeFile(tmp, payload, existingMode !== null ? { mode: existingMode } : undefined);
- if (existingMode !== null) {
- await chmod(tmp, existingMode).catch(() => {});
- }
- // Node's fs.rename uses MoveFileExW with MOVEFILE_REPLACE_EXISTING on Windows (atomic
- // overwrite), but still fails with EPERM/EACCES if the destination is locked (AV scan,
- // concurrent reader). Fall back to a backup-swap so the original file is never lost.
- const replace = async () => {
- let err = await rename(tmp, filePath).then(() => null, (e) => e);
- // Retry the ATOMIC rename before resorting to the backup swap (#4095). The
- // swap below renames the destination away and back, so for that instant the
- // destination DOES NOT EXIST — a concurrent read lands on ENOENT and reads
- // it as a trustworthy "nothing here yet", silently handing the caller its
- // default instead of the file's real contents. A transient lock clears in
- // milliseconds, so retrying keeps almost every write on the atomic path and
- // never opens that window.
- if (isWindows()) {
- for (let attempt = 1; err && attempt < WIN_RETRY_ATTEMPTS && WIN_RENAME_LOCK_CODES.includes(err.code); attempt += 1) {
- await sleep(WIN_RETRY_DELAY_MS);
- err = await rename(tmp, filePath).then(() => null, (e) => e);
- if (!err) console.log(`⚠️ atomicWrite rename succeeded after ${attempt} retry(s): ${basename(filePath)}`);
- }
- }
- if (!err) return;
- if (isWindows() && WIN_RENAME_LOCK_CODES.includes(err.code)) {
- const bak = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.bak`;
- const hadExisting = await rename(filePath, bak).then(() => true, (e) => {
- if (e.code === 'ENOENT') return false;
- throw e;
- });
- const renameErr = await rename(tmp, filePath).then(() => null, (e) => e);
- if (renameErr) {
- if (hadExisting) await rename(bak, filePath).catch(() => {});
- throw renameErr;
- }
- if (hadExisting) await unlink(bak).catch(() => {});
- return;
- }
- throw err;
- };
- try {
- await replace();
- } catch (err) {
- await unlink(tmp).catch(() => {});
- throw err;
- }
-}
-
-/**
- * Get a path relative to the data directory.
- *
- * @param {...string} segments - Path segments to join
- * @returns {string} Full path under data directory
- *
- * @example
- * const filePath = dataPath('cos', 'state.json');
- * // Returns: /path/to/project/data/cos/state.json
- */
-export function dataPath(...segments) {
- return join(PATHS.data, ...segments);
-}
-
-// `path.join(homedir(), '/.foo')` discards the homedir prefix because of
-// the leading slash, so strip the leading `~/` (or `~\` on Windows) before
-// joining. Only expands a leading `~` — embedded `~` chars in path segments
-// (e.g. `iCloud~md~obsidian`) are preserved.
-export function expandHome(p) {
- if (typeof p !== 'string' || !p) return p;
- if (p === '~') return homedir();
- if (p.startsWith('~/') || p.startsWith('~\\')) return join(homedir(), p.slice(2));
- return p;
-}
-
-/**
- * Check if a string is potentially valid JSON.
- * Performs quick structural validation before parsing.
- *
- * @param {string} str - String to validate
- * @param {Object} options - Validation options
- * @param {boolean} [options.allowArray=true] - Allow array JSON (default: true)
- * @returns {boolean} True if the string appears to be valid JSON
- *
- * @example
- * isValidJSON('{"key": "value"}') // true
- * isValidJSON('[1, 2, 3]') // true
- * isValidJSON('') // false
- * isValidJSON('{"incomplete":') // false
- */
-export function isValidJSON(str, { allowArray = true } = {}) {
- if (!str || !str.trim()) return false;
- const trimmed = str.trim();
-
- // Check for basic JSON structure (object or array)
- const isObject = trimmed.startsWith('{') && trimmed.endsWith('}');
- const isArray = trimmed.startsWith('[') && trimmed.endsWith(']');
-
- if (!isObject && !(allowArray && isArray)) return false;
-
- return true;
-}
-
-/**
- * Index of the first JSON array token in `str`, or -1 when it holds none.
- *
- * Split out of `extractJSONArray` so a caller can tell "found an array" from "found
- * nothing" — a distinction `extractJSONArray` erases by design (it manufactures a
- * literal '[]' for the not-found case). `readJSONFileStrict` needs it: for a
- * swallowing caller a manufactured '[]' is just the default, but for a strict one it
- * would forge a trustworthy-looking EMPTY out of unreadable bytes.
- *
- * @param {string} str
- * @returns {number} Index of the array start, or -1
- */
-function findJSONArrayStart(str) {
- if (!str) return -1;
- // Look for '[{' (array with objects) first
- const objectStart = str.indexOf('[{');
- if (objectStart >= 0) return objectStart;
- // Check for empty array - find '[]' that's not part of ANSI codes like [31m
- const emptyMatch = str.match(/\[\](?![0-9])/);
- return emptyMatch ? str.indexOf(emptyMatch[0]) : -1;
-}
-
-/**
- * Extract JSON array from string that may contain ANSI codes or other noise.
- * Useful for parsing pm2 jlist output which may include warnings before the JSON.
- *
- * @param {string} str - String potentially containing JSON array
- * @returns {string} Extracted JSON or '[]' if not found
- */
-export function extractJSONArray(str) {
- const jsonStart = findJSONArrayStart(str);
- return jsonStart >= 0 ? str.slice(jsonStart) : '[]';
-}
-
-/**
- * Safely parse JSON with validation and fallback.
- * Avoids "Unexpected end of JSON input" errors from empty/corrupted files.
- * For arrays, automatically extracts JSON from strings with ANSI codes/noise (e.g., pm2 output).
- *
- * @param {string} str - JSON string to parse
- * @param {*} defaultValue - Default value if parsing fails (default: null)
- * @param {Object} options - Parse options
- * @param {boolean} [options.allowArray=true] - Allow array JSON
- * @param {boolean} [options.logError=false] - Log parsing errors
- * @param {string} [options.context=''] - Context for error logging
- * @returns {*} Parsed JSON or default value
- *
- * @example
- * safeJSONParse('{"key": "value"}', {}) // { key: "value" }
- * safeJSONParse('', {}) // {}
- * safeJSONParse('invalid', []) // []
- * safeJSONParse(null, { default: true }) // { default: true }
- */
-export function safeJSONParse(str, defaultValue = null, { allowArray = true, logError = false, context = '' } = {}) {
- // For arrays, try to extract JSON from noisy output (e.g., pm2 with ANSI codes)
- if (allowArray && Array.isArray(defaultValue) && str && !str.trim().startsWith('[')) {
- str = extractJSONArray(str);
- }
-
- if (!isValidJSON(str, { allowArray })) {
- if (logError && str) {
- console.warn(`Invalid JSON${context ? ` in ${context}` : ''}: empty or malformed content`);
- }
- return defaultValue;
- }
-
- // Attempt actual parse - the validation above catches structural issues
- // but syntax errors like trailing commas still need handling
- try {
- return JSON.parse(str);
- } catch (err) {
- if (logError) {
- console.warn(`Failed to parse JSON${context ? ` in ${context}` : ''}: ${err.message}`);
- }
- return defaultValue;
- }
-}
-
-/**
- * Read a file, returning null on any error (missing file, permission denied, etc.).
- *
- * Collapses the inlined `readFile(path, encoding).catch(() => null)` pattern used
- * across services for "optional file — fall through if absent." For Buffer reads,
- * pass `encoding: null` (or omit when calling with no second arg, default 'utf8').
- *
- * NOTE: like `readJSONFile`, this conflates "absent" with "unreadable" — both
- * return null. When the caller derives a user-visible stat from the result (where
- * a fake empty is a lie, not a default), reach for `tryReadFileStrict` (raw bytes)
- * or `readJSONFileStrict` (parsed JSON) instead.
- *
- * @param {string} filePath - Path to read
- * @param {string|null} [encoding='utf8'] - Encoding (null for Buffer)
- * @returns {Promise<string|Buffer|null>} File contents or null on any read error
- */
-export async function tryReadFile(filePath, encoding = 'utf8') {
- return readFile(filePath, encoding).catch(() => null);
-}
-
-/**
- * `tryReadFile` that reports whether the read is TRUSTWORTHY — the raw-bytes
- * counterpart to `readJSONFileStrict`, for callers that parse (or count, or
- * display) the contents themselves rather than handing the file to JSON.parse.
- *
- * - ENOENT (never written) → `{ ok: true, value: null }` — a genuine "nothing
- * here yet". Safe to treat as a real empty.
- * - any other read error → `{ ok: false, value: null }` — EACCES, EIO,
- * EISDIR, a transient FS failure. We do NOT know the file is absent.
- * - read → `{ ok: true, value: contents }`
- *
- * So the three states `tryReadFile` collapses into one `null` stay separable:
- * `ok && value !== null` = read, `ok && value === null` = absent, `!ok` =
- * present-but-unreadable. Windows swap-window retries are shared with
- * `readJSONFileStrict`, so an `atomicWrite` in flight can't masquerade as ENOENT.
- *
- * @param {string} filePath - Path to read
- * @param {string|null} [encoding='utf8'] - Encoding (null for Buffer)
- * @returns {Promise<{ ok: boolean, value: string|Buffer|null }>}
- *
- * @example
- * const { ok, value } = await tryReadFileStrict(LEDGER_FILE);
- * if (!ok) throw new Error('ledger unreadable'); // never report a fake 0
- */
-export async function tryReadFileStrict(filePath, encoding = 'utf8') {
- return readWithSwapRetry(filePath, encoding).then(
- (value) => ({ ok: true, value }),
- // ENOENT is the ONLY errno that proves absence. Everything else — EACCES on
- // the file or a parent dir, ENOTDIR, EIO — means we could not confirm it,
- // which must stay distinct from "confirmed empty".
- (err) => ({ ok: err?.code === 'ENOENT', value: null })
- );
-}
-
-/**
- * Read at most `maxBytes` from the END of a file, as UTF-8.
- *
- * The bounded-memory counterpart to `tryReadFile` for append-only logs and
- * spools that have no upper size bound (agent transcripts, PTY spools, CLI
- * rollout JSONL). `readFile` on one of those loads the whole thing into heap;
- * this reads only the trailing window.
- *
- * Non-throwing, with the sentinel distinction the AGENTS.md rule demands:
- * - missing / unopenable / read error → `null`
- * - zero-byte file → `''`
- * so a caller can tell "nothing to read" from "couldn't read".
- *
- * The window starts at a BYTE offset, so when the file is larger than
- * `maxBytes` the first line comes back partial (and can begin mid-multibyte
- * character). Callers that split on newlines should drop that leading fragment.
- *
- * @param {string} path - File to read
- * @param {number} maxBytes - Maximum trailing bytes to read
- * @returns {Promise<string|null>} Trailing text, `''` for an empty file, or null on error
- */
-export async function readFileTail(path, maxBytes) {
- const info = await stat(path).catch(() => null);
- if (!info) return null;
- if (info.size === 0) return '';
- const start = Math.max(0, info.size - maxBytes);
- const length = info.size - start;
- const handle = await open(path, 'r').catch(() => null);
- if (!handle) return null;
- try {
- const buffer = Buffer.alloc(length);
- // Honour bytesRead — the file can shrink between stat and read, or the OS
- // can return a short read; decoding the whole `buffer` would append NULs.
- // A read failure surfaces as null so callers keep the ''-vs-null contract.
- const result = await handle.read(buffer, 0, length, start).catch(() => null);
- if (result === null) return null;
- return buffer.toString('utf8', 0, result.bytesRead);
- } finally {
- await handle.close().catch(() => {});
- }
-}
-
-// Private sentinel for "the parse produced nothing usable". A unique Symbol, NOT
-// null/undefined — a file whose real contents parse to the caller's defaultValue
-// must stay distinguishable from a file that failed to parse at all, and any
-// in-band marker could legitimately BE the parsed value.
-const PARSE_FAILED = Symbol('json-parse-failed');
-
-/**
- * True when a `<filePath>.*.bak` sibling is on disk — the signature of an
- * `atomicWrite` backup swap that is mid-flight for THIS file, i.e. the only
- * window in which the destination legitimately vanishes.
- *
- * Deliberately does NOT match `.tmp`: `atomicWrite` writes its temp file on
- * EVERY write, including the first-ever create of a file that has no
- * destination yet. Treating a `.tmp` sibling as evidence of a swap would turn a
- * plain "not written yet" read into a retry that waits for the in-flight write
- * and returns its brand-new contents — a different value than the read was
- * entitled to, and a behavior change on POSIX-shaped callers. The `.bak` only
- * exists between the swap's two renames.
- *
- * Non-throwing: an unreadable parent directory just means "no evidence of a
- * swap". Only consulted on win32, and only after a read already failed with
- * ENOENT, so the directory listing never lands on a POSIX read or a successful
- * one. A `.bak` orphaned by a crash mid-swap costs the bounded retry budget
- * (~50ms) on subsequent ENOENT reads of that path, never an incorrect answer.
- *
- * Matching is case-INSENSITIVE: NTFS/FAT are case-insensitive, so the reader's
- * `filePath` casing need not match the casing the writer used to create the
- * file (and therefore the casing `readdir` reports). A case-sensitive compare
- * would miss the sibling and let the phantom-empty through.
- *
- * @param {string} filePath
- * @returns {Promise<boolean>}
- */
-async function hasSwapSibling(filePath) {
- const entries = await readdir(dirname(filePath)).catch(() => null);
- if (!entries) return false;
- const prefix = `${basename(filePath).toLowerCase()}.`;
- return entries.some((entry) => {
- const name = entry.toLowerCase();
- return name.startsWith(prefix) && name.endsWith('.bak');
- });
-}
-
-/**
- * `readFile(filePath, encoding)` with the Windows-only retries that keep a read
- * racing `atomicWrite` from being mistaken for an empty/absent file (#4095).
- *
- * On POSIX this is a straight delegate — zero extra syscalls, zero delay.
- *
- * On win32 two transient failures are retried with a short backoff:
- * - EPERM/EACCES/EBUSY — the destination is momentarily locked (AV scan, the
- * writer's own open handle).
- * - ENOENT, but ONLY when `hasSwapSibling` shows a backup swap is mid-flight.
- * A file that was simply never written — or one whose first-ever write is
- * still in its temp stage — stays a silent "nothing here yet": one failed
- * read, no retry, no sleep.
- *
- * Rejects with the last error once the attempts are exhausted, so the caller's
- * existing errno handling is unchanged.
- *
- * @param {string} filePath
- * @param {string|null} [encoding='utf-8'] - Encoding (null for Buffer)
- * @returns {Promise<string|Buffer>}
- */
-async function readWithSwapRetry(filePath, encoding = 'utf-8') {
- if (!isWindows()) return readFile(filePath, encoding);
- for (let attempt = 0; ; attempt += 1) {
- const outcome = await readFile(filePath, encoding).then((content) => ({ content }), (err) => ({ err }));
- if (!outcome.err) {
- if (attempt > 0) console.log(`⚠️ read succeeded after ${attempt} retry(s) — write swap in flight: ${basename(filePath)}`);
- return outcome.content;
- }
- const last = attempt >= WIN_RETRY_ATTEMPTS - 1;
- const retriable = WIN_READ_LOCK_CODES.includes(outcome.err.code)
- || (outcome.err.code === 'ENOENT' && !last && await hasSwapSibling(filePath));
- if (last || !retriable) throw outcome.err;
- await sleep(WIN_RETRY_DELAY_MS);
- }
-}
-
-/**
- * Read a JSON file, reporting whether the read is TRUSTWORTHY rather than
- * collapsing every failure into the default (the `readJSONFile` behavior below).
- *
- * The absent-vs-unreadable distinction (see AGENTS.md's "Sentinel + validate"):
- *
- * - ENOENT (never written) → `{ ok: true, value: defaultValue }` — a genuine
- * empty. A caller counting records may trust this as a real zero.
- * - any other read error → `{ ok: false, value: defaultValue }` — EACCES,
- * EIO, EISDIR, a transient FS failure. We do NOT know the file is empty.
- * - unparseable / truncated → `{ ok: false, value: defaultValue }` — corrupt
- * bytes are not an empty collection.
- * - parsed → `{ ok: true, value: parsed }`
- *
- * `value` is always populated so an `ok`-indifferent caller can ignore the flag and
- * behave exactly like `readJSONFile` — which is how `readJSONFile` is implemented.
- *
- * Generalizes the local `{ ok, list }` precedent in
- * `services/mediaAssetIndex/db.js#readVideoHistoryStrict`, written because "corrupt
- * history" reading as "no videos exist" would have pruned every still-on-disk video
- * from the index. Same bug class, shared helper (#2726).
- *
- * @param {string} filePath - Path to JSON file
- * @param {*} defaultValue - Value returned whenever the file yields no parsed value
- * @param {Object} options - Options
- * @param {boolean} [options.allowArray=true] - Allow array JSON
- * @param {boolean} [options.logError=true] - Log read/parse errors
- * @returns {Promise<{ ok: boolean, value: * }>}
- *
- * @example
- * const { ok, value } = await readJSONFileStrict('./sessions.json', { sessions: [] });
- * if (!ok) throw new Error('sessions unreadable'); // never report a fake 0
- */
-export async function readJSONFileStrict(filePath, defaultValue = null, { allowArray = true, logError = true } = {}) {
- let content;
- try {
- content = await readWithSwapRetry(filePath);
- } catch (err) {
- // ENOENT = file doesn't exist → a trustworthy "nothing here yet", silently.
- // On win32 an ENOENT that was really an `atomicWrite` swap window has
- // already been retried above, so reaching here means genuinely absent.
- if (err.code === 'ENOENT') {
- return { ok: true, value: defaultValue };
- }
- if (logError) {
- console.warn(`Failed to read file ${filePath}: ${err.message}`);
- }
- return { ok: false, value: defaultValue };
- }
-
- // Mirror safeJSONParse's noisy-output affordance BEFORE delegating: it keys the
- // extraction off `Array.isArray(defaultValue)`, and the sentinel we pass as its
- // fallback below is not an array — so an array-defaulted caller (e.g. pm2 jlist
- // with ANSI codes) would silently lose the extraction if we left it to that call.
- //
- // Deliberately NOT via `extractJSONArray`: it returns a literal '[]' when the text
- // holds no array at all, which would parse cleanly and report `ok: true` — forging
- // a trustworthy empty out of unreadable bytes, the exact lie this function exists
- // to prevent. Only a real find rewrites `text`; otherwise the parse below fails and
- // the read is correctly reported as untrustworthy.
- let text = content;
- if (allowArray && Array.isArray(defaultValue) && text && !text.trim().startsWith('[')) {
- const arrayStart = findJSONArrayStart(text);
- if (arrayStart >= 0) text = text.slice(arrayStart);
- }
-
- const parsed = safeJSONParse(text, PARSE_FAILED, { allowArray, logError, context: filePath });
- if (parsed === PARSE_FAILED) return { ok: false, value: defaultValue };
-
- // An array `defaultValue` is the caller declaring "I expect a list" — every such
- // caller in-tree goes straight to `.filter`/`.find`/`.findIndex` on the result. A
- // parsed object root therefore isn't a usable read: swallowing callers must still
- // get their list back (a hand-edited or legacy-shaped file used to degrade to `[]`
- // here, via the manufactured-'[]' path above, and would now TypeError instead), and
- // a strict caller must refuse to count a shape it cannot count.
- if (allowArray && Array.isArray(defaultValue) && !Array.isArray(parsed)) {
- if (logError) {
- console.warn(`Expected a JSON array in ${filePath}, got ${parsed === null ? 'null' : typeof parsed}`);
- }
- return { ok: false, value: defaultValue };
- }
-
- return { ok: true, value: parsed };
-}
-
-/**
- * Read a JSON file safely with validation and default fallback.
- * Combines file reading with safe JSON parsing.
- *
- * By default this SWALLOWS every failure — a missing file, an unreadable one, and
- * corrupt JSON all return `defaultValue`. That is the right shape for config-ish
- * reads with a sensible fallback, and is the long-standing behavior of every
- * existing caller.
- *
- * It is the WRONG shape when the value is counted or shown to the user, because a
- * fake empty then reads as fact ("0 sessions logged" when the truth is "we could not
- * read your sessions"). Those callers pass `{ strict: true }` to convert an
- * untrustworthy read into a throw, or use `readJSONFileStrict` for the `{ ok, value }`
- * pair directly.
- *
- * @param {string} filePath - Path to JSON file
- * @param {*} defaultValue - Default value if file doesn't exist or is invalid
- * @param {Object} options - Options
- * @param {boolean} [options.allowArray=true] - Allow array JSON
- * @param {boolean} [options.logError=true] - Log errors
- * @param {boolean} [options.strict=false] - Throw instead of returning `defaultValue`
- * when the file exists but could not be read or parsed. A genuinely absent file
- * (ENOENT) still returns `defaultValue` — absent is a trustworthy empty.
- * @returns {Promise<*>} Parsed JSON or default value
- * @throws {Error} Only when `strict` and the file is present-but-unreadable/corrupt
- *
- * @example
- * const config = await readJSONFile('./config.json', { port: 3000 });
- * const items = await readJSONFile('./items.json', []);
- * const real = await readJSONFile('./sessions.json', [], { strict: true }); // throws if corrupt
- */
-export async function readJSONFile(filePath, defaultValue = null, { allowArray = true, logError = true, strict = false } = {}) {
- const { ok, value } = await readJSONFileStrict(filePath, defaultValue, { allowArray, logError });
- if (!ok && strict) {
- throw new Error(`Unreadable JSON file: ${filePath}`);
- }
- return value;
-}
-
-/**
- * Parse JSONL (JSON Lines) content safely.
- * Handles empty lines, whitespace, and malformed lines gracefully.
- *
- * @param {string} content - JSONL content (newline-separated JSON objects)
- * @param {Object} options - Options
- * @param {boolean} [options.logErrors=false] - Log individual line parsing errors
- * @param {string} [options.context=''] - Context for error logging
- * @returns {Array} Array of parsed objects (invalid lines are skipped)
- *
- * @example
- * const lines = safeJSONLParse('{"a":1}\n{"b":2}\n'); // [{ a: 1 }, { b: 2 }]
- * const lines = safeJSONLParse('{"a":1}\ninvalid\n{"b":2}'); // [{ a: 1 }, { b: 2 }]
- */
-export function safeJSONLParse(content, { logErrors = false, context = '' } = {}) {
- if (!content || !content.trim()) return [];
-
- // Split on CRLF or LF to handle both Windows and Unix line endings
- const lines = content
- .split(/\r?\n/)
- .map(line => line.trim())
- .filter(Boolean);
- const results = [];
-
- for (const line of lines) {
- const parsed = safeJSONParse(line, null, { allowArray: false, logError: logErrors, context });
- if (parsed !== null) {
- results.push(parsed);
- }
- }
-
- return results;
-}
-
-/**
- * Read a JSONL file safely.
- *
- * @param {string} filePath - Path to JSONL file
- * @param {Object} options - Options
- * @param {boolean} [options.logErrors=false] - Log individual line parsing errors
- * @returns {Promise<Array>} Array of parsed objects
- *
- * @example
- * const entries = await readJSONLFile('./logs.jsonl');
- */
-export async function readJSONLFile(filePath, { logErrors = false } = {}) {
- let content;
- try {
- content = await readFile(filePath, 'utf-8');
- } catch (err) {
- // ENOENT = file doesn't exist, return empty array silently
- if (err.code === 'ENOENT') {
- return [];
- }
- // Log other I/O errors if requested
- if (logErrors) {
- console.warn(`Failed to read file ${filePath}: ${err.message}`);
- }
- return [];
- }
- return safeJSONLParse(content, { logErrors, context: filePath });
-}
-
-/**
- * Append one JSON-serializable value to a JSON Lines file.
- * Creates the parent directory as needed and writes exactly one trailing
- * newline so readers can stream or split the file without special-casing the
- * final record.
- *
- * @param {string} filePath - Path to JSONL file
- * @param {*} value - JSON-serializable value to append
- * @returns {Promise<void>}
- */
-export async function appendJSONLine(filePath, value) {
- const serialized = JSON.stringify(value);
- if (serialized === undefined) {
- throw new TypeError('appendJSONLine value must be JSON-serializable');
- }
- await ensureDir(dirname(filePath));
- await appendFile(filePath, serialized + '\n');
-}
-
-/**
- * Read JSON Lines with optional offset/limit slicing.
- *
- * @param {string} filePath - Path to JSONL file
- * @param {Object} options - Options
- * @param {number} [options.from=0] - Zero-based record offset
- * @param {number} [options.limit] - Maximum number of records to return
- * @param {boolean} [options.logErrors=false] - Log malformed JSONL lines
- * @returns {Promise<Array>} Parsed records
- */
-export async function readJSONLines(filePath, { from = 0, limit, logErrors = false } = {}) {
- const entries = await readJSONLFile(filePath, { logErrors });
- const start = Number.isFinite(from) && from > 0 ? Math.floor(from) : 0;
- if (limit === undefined || limit === null) return entries.slice(start);
- const count = Number.isFinite(limit) && limit >= 0 ? Math.floor(limit) : 0;
- return entries.slice(start, start + count);
-}
-
-/**
- * Replace a JSON Lines file with the supplied records.
- * Intended for compaction/retention and delete/clear flows; hot append paths
- * should use appendJSONLine().
- *
- * @param {string} filePath - Path to JSONL file
- * @param {Array} values - JSON-serializable records
- * @returns {Promise<void>}
- */
-export async function writeJSONLines(filePath, values) {
- if (!Array.isArray(values)) {
- throw new TypeError('writeJSONLines values must be an array');
- }
- const lines = values.map((value) => {
- const serialized = JSON.stringify(value);
- if (serialized === undefined) {
- throw new TypeError('writeJSONLines values must be JSON-serializable');
- }
- return serialized;
- });
- await atomicWrite(filePath, lines.length > 0 ? `${lines.join('\n')}\n` : '');
-}
-
-/**
- * Time constants in milliseconds.
- * Single source of truth — import these instead of declaring inline.
- */
-/**
- * Create a cached JSON file store with TTL-based invalidation.
- * Eliminates the repeated cache/load/save/invalidate pattern across services.
- *
- * @param {string} filePath - Path to the JSON file
- * @param {*} defaultValue - Default value when file doesn't exist
- * @param {Object} options
- * @param {number} [options.ttl=2000] - Cache TTL in milliseconds
- * @param {string} [options.context=''] - Context label for error logging
- * @returns {{ load, save, mutate, invalidateCache }}
- *
- * Writes are serialized through a single-tail `createFileWriteQueue` so two
- * concurrent `save()` calls can't interleave their `atomicWrite` + cache
- * assignment. For read-modify-write, use `mutate(fn)` — it runs the whole
- * `load → fn → persist` cycle under the same tail, so a `load` always sees the
- * previous cycle's committed result and one writer can't clobber the other
- * (AGENTS.md: "serialize writes server-side… a single tail per shared file").
- * A bare `load()` + `save()` pair does NOT get that guarantee; reach for
- * `mutate()` whenever the new value depends on the current one.
- */
-export function createCachedStore(filePath, defaultValue, { ttl = 2000, context = '' } = {}) {
- let cache = null;
- let cacheTimestamp = 0;
- const dir = dirname(filePath);
- const queueWrite = createFileWriteQueue();
- // Safe clone for plain JSON defaults (structuredClone requires Node 17+)
- const cloneDefault = () => JSON.parse(JSON.stringify(defaultValue));
-
- const load = async () => {
- const now = Date.now();
- if (cache && (now - cacheTimestamp) < ttl) return cache;
- await ensureDir(dir);
- if (!existsSync(filePath)) {
- cache = cloneDefault();
- cacheTimestamp = now;
- return cache;
- }
- const content = await readFile(filePath, 'utf-8');
- cache = safeJSONParse(content, cloneDefault(), { context });
- cacheTimestamp = now;
- return cache;
- };
-
- // Persist `data` and refresh the cache — the shared write body. Callers reach
- // it via the serialized `save`/`mutate`, never directly.
- const persist = async (data) => {
- await atomicWrite(filePath, data);
- cache = data;
- cacheTimestamp = Date.now();
- return data;
- };
-
- const save = (data) => queueWrite(() => persist(data));
-
- // Serialized read-modify-write: load the freshest state under the tail, apply
- // `fn`, then persist. `fn` may mutate the loaded object in place and/or return
- // the value to write (returning `undefined` persists the mutated input).
- const mutate = (fn) => queueWrite(async () => {
- const data = await load();
- const result = await fn(data);
- return persist(result === undefined ? data : result);
- });
-
- const invalidateCache = () => {
- cache = null;
- cacheTimestamp = 0;
- };
-
- return { load, save, mutate, invalidateCache };
-}
-
-export const MINUTE = 60 * 1000;
-export const HOUR = 60 * MINUTE;
-export const DAY = 24 * HOUR;
-
-/**
- * Promise-based delay. Canonical replacement for the per-module
- * `const delay = (ms) => new Promise(...)` one-liners.
- *
- * @param {number} ms - Milliseconds to wait
- * @returns {Promise<void>}
- */
-export function sleep(ms) {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-/**
- * Format a date as YYYY-MM-DD string.
- *
- * @param {Date} [date=new Date()] - Date to format
- * @returns {string} ISO date string (e.g., "2026-03-05")
- */
-export function getDateString(date = new Date()) {
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
-}
-
-/**
- * UUID v4 regex pattern for validating account/entity IDs.
- */
-export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-
-/**
- * Truncate an id to a fixed prefix for human-readable log lines. Null-safe
- * so callers can pass a possibly-missing field directly (`shortId(run?.id)`)
- * without an outer truthiness check.
- *
- * @param {*} id - id-like value; coerced to string
- * @param {number} [n=8] - prefix length
- * @returns {string} prefix of length `n`, or `''` when `id` is null/undefined
- */
-export function shortId(id, n = 8) {
- if (id == null) return '';
- return String(id).slice(0, n);
-}
-
-/**
- * Safely parse a date value to epoch milliseconds.
- * Returns 0 for invalid/missing dates instead of NaN.
- *
- * @param {string|Date|number} d - Date value to parse
- * @returns {number} Epoch milliseconds, or 0 if invalid
- */
-export function safeDate(d) {
- const t = new Date(d).getTime();
- return Number.isNaN(t) ? 0 : t;
-}
-
-/**
- * Generic search filter — returns items where any of the specified fields
- * contain the search string (case-insensitive).
- *
- * @param {Array<Object>} items - Items to filter
- * @param {string} search - Search query
- * @param {Array<string>} fields - Dot-notation field paths to search (e.g., 'from.name')
- * @returns {Array<Object>} Filtered items
- */
-export function filterBySearch(items, search, fields) {
- if (!search) return items;
- const q = search.toLowerCase();
- return items.filter(item =>
- fields.some(field => {
- const val = field.includes('.') ? field.split('.').reduce((o, k) => o?.[k], item) : item[field];
- return val?.toLowerCase?.().includes(q);
- })
- );
-}
-
-/**
- * Format a duration in milliseconds to a human-readable string.
- * Outputs the most appropriate unit (minutes, hours, days) based on size.
- *
- * @param {number} ms - Duration in milliseconds
- * @returns {string} Formatted duration (e.g., "5m", "2h 30m", "3d 5h")
- *
- * @example
- * formatDuration(30000) // "0m"
- * formatDuration(300000) // "5m"
- * formatDuration(7200000) // "2h 0m"
- * formatDuration(90000000) // "1d 1h"
- */
-export function formatDuration(ms) {
- if (!ms) return '0m';
- const mins = Math.floor(ms / 60000);
- const hours = Math.floor(mins / 60);
- const days = Math.floor(hours / 24);
-
- if (days > 0) {
- const remainingHours = hours % 24;
- return `${days}d ${remainingHours}h`;
- }
- if (hours > 0) {
- const remainingMins = mins % 60;
- return `${hours}h ${remainingMins}m`;
- }
- return `${mins}m`;
-}
-
-export function formatBytes(bytes) {
- if (!bytes) return '0 B';
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
- return (bytes / Math.pow(1024, i)).toFixed(i > 1 ? 1 : 0) + ' ' + units[i];
-}
-
-// =============================================================================
-// FILENAME / MIME HELPERS (shared by uploads, attachments, screenshots routes)
-// =============================================================================
-
-/**
- * Full extension→MIME map covering documents, images, audio, video, code, and
- * archives accepted by the generic uploads route. The attachments route uses a
- * strict subset — see ATTACHMENT_ALLOWED_EXTENSIONS below.
- *
- * Exported so routes can serve the correct Content-Type header without keeping
- * their own copy. Unknown extensions fall back to 'application/octet-stream'.
- */
-export const EXTENSION_MIME_MAP = {
- // Documents
- '.txt': 'text/plain',
- '.md': 'text/markdown',
- '.json': 'application/json',
- '.csv': 'text/csv',
- '.xml': 'application/xml',
- '.yaml': 'application/x-yaml',
- '.yml': 'application/x-yaml',
- '.pdf': 'application/pdf',
- // Images
- '.png': 'image/png',
- '.jpg': 'image/jpeg',
- '.jpeg': 'image/jpeg',
- '.gif': 'image/gif',
- '.webp': 'image/webp',
- '.svg': 'image/svg+xml',
- '.ico': 'image/x-icon',
- '.bmp': 'image/bmp',
- // Audio
- '.mp3': 'audio/mpeg',
- '.wav': 'audio/wav',
- '.ogg': 'audio/ogg',
- '.m4a': 'audio/mp4',
- '.mid': 'audio/midi',
- '.midi': 'audio/midi',
- // Video
- '.mp4': 'video/mp4',
- '.webm': 'video/webm',
- '.mov': 'video/quicktime',
- // Code
- '.js': 'text/javascript',
- '.ts': 'text/typescript',
- '.jsx': 'text/javascript',
- '.tsx': 'text/typescript',
- '.py': 'text/x-python',
- '.sh': 'text/x-shellscript',
- '.sql': 'text/x-sql',
- '.html': 'text/html',
- '.css': 'text/css',
- '.go': 'text/x-go',
- '.rs': 'text/x-rust',
- '.java': 'text/x-java',
- '.c': 'text/x-c',
- '.cpp': 'text/x-c++',
- '.h': 'text/x-c',
- // Archives
- '.zip': 'application/zip',
- '.tar': 'application/x-tar',
- '.gz': 'application/gzip',
- '.7z': 'application/x-7z-compressed',
- '.rar': 'application/vnd.rar',
- // Other
- '.log': 'text/plain',
- '.env': 'text/plain',
- '.conf': 'text/plain',
- '.cfg': 'text/plain',
- '.ini': 'text/plain',
-};
-
-/**
- * Strict allowlist for file attachments (task attachments, CoS context files).
- * A subset of EXTENSION_MIME_MAP — excludes audio, video, ICO, BMP, and
- * miscellaneous text/config types that are not meaningful attachment types.
- * The attachments route validates against this set; uploads uses the full map.
- */
-export const ATTACHMENT_ALLOWED_EXTENSIONS = new Set([
- '.txt', '.md', '.json', '.csv', '.xml', '.yaml', '.yml',
- '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.pdf',
- '.js', '.ts', '.jsx', '.tsx', '.py', '.sh', '.sql', '.html', '.css',
- '.zip', '.tar', '.gz',
-]);
-
-/**
- * Curated allowlist for SongBook attachments (sheet-music PDFs, scans, MIDI,
- * practice audio). Deliberately NOT a superset of ATTACHMENT_ALLOWED_EXTENSIONS
- * — code/archive/config types make no sense on a song record, while MIDI and
- * audio (which the CoS attachment set excludes) are core sheet-music formats.
- */
-export const SONGBOOK_ATTACHMENT_EXTENSIONS = new Set([
- '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg',
- '.txt', '.md',
- '.mid', '.midi', '.mp3', '.wav', '.m4a', '.ogg',
-]);
-
-/**
- * Look up the MIME type for a file extension (including the leading dot, e.g.
- * ".png"). Returns 'application/octet-stream' for unknown extensions.
- *
- * @param {string} ext - Lowercased extension with leading dot (e.g. '.png')
- * @returns {string} MIME type string
- */
-export function getMimeType(ext) {
- return EXTENSION_MIME_MAP[ext] || 'application/octet-stream';
-}
-
-/**
- * Magic-byte sniff of an image buffer. The client-supplied extension / MIME is
- * not trustworthy, so when we persist uploaded image bytes (e.g. an author
- * headshot routed into the gallery) we derive the real format from the leading
- * bytes. Recognises PNG, JPEG, WebP, and GIF.
- *
- * @param {Buffer} buf - Raw decoded image bytes
- * @returns {{ format: 'png'|'jpeg'|'webp'|'gif', ext: string, mime: string } | null}
- * The detected format with its canonical extension + MIME, or null when the
- * bytes don't match a known image signature.
- */
-export function detectImageFormat(buf) {
- if (!Buffer.isBuffer(buf)) return null;
- if (buf.length >= 8 &&
- buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
- buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) {
- return { format: 'png', ext: '.png', mime: 'image/png' };
- }
- if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
- return { format: 'jpeg', ext: '.jpg', mime: 'image/jpeg' };
- }
- if (buf.length >= 12 &&
- buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
- buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
- return { format: 'webp', ext: '.webp', mime: 'image/webp' };
- }
- if (buf.length >= 6 &&
- buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38 &&
- (buf[4] === 0x37 || buf[4] === 0x39) && buf[5] === 0x61) {
- return { format: 'gif', ext: '.gif', mime: 'image/gif' };
- }
- return null;
-}
-
-/**
- * Get a file's extension, normalised to lowercase with a leading dot.
- * Returns null when the filename has no extension.
- *
- * @param {string} filename
- * @returns {string|null}
- */
-export function getFileExtension(filename) {
- return extname(filename).toLowerCase() || null;
-}
-
-/**
- * Sanitize a user-supplied filename to prevent path traversal and filesystem
- * surprises. Strips any directory component, replaces characters that are not
- * alphanumeric / dot / hyphen / underscore with `_`, and ensures the name
- * does not start with a dot (hidden-file prevention).
- *
- * Identical logic was copy-pasted across uploads.js, attachments.js, and
- * screenshots.js — consolidated here so fixes propagate to all callers.
- *
- * @param {string} filename - User-provided filename (possibly with path components)
- * @returns {string} Safe basename
- */
-export function sanitizeFilename(filename) {
- const base = basename(filename);
- const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');
- if (sanitized.startsWith('.')) {
- return '_' + sanitized.slice(1);
- }
- return sanitized;
-}
-
-/**
- * Move a temp file into `destDir` and return the persisted filename, using the
- * `/api/uploads` route's naming (`<uuid8>-<sanitized-name>`) so a
- * server-produced file is served and referenced exactly like a user upload.
- *
- * copyFile + unlink instead of rename — the source usually lives in
- * `os.tmpdir()`, which may sit on a different filesystem (rename across devices
- * throws EXDEV on Linux); copy works regardless. The temp unlink is best-effort
- * cleanup. Returns `{ filename, sizeBytes }`.
- */
-export async function importFileToDir(tempPath, originalName, destDir) {
- await ensureDir(destDir);
- const filename = `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalName)}`;
- const dest = join(destDir, filename);
- await copyFile(tempPath, dest);
- await unlink(tempPath).catch(() => {});
- const s = await stat(dest).catch(() => null);
- return { filename, sizeBytes: s?.size ?? 0 };
-}
-
-/**
- * `importFileToDir` pinned to the uploads dir (`PATHS.uploads`) — the common
- * case (e.g. a yt-dlp audio extraction, #2120).
- */
-export async function importFileToUploads(tempPath, originalName) {
- return importFileToDir(tempPath, originalName, PATHS.uploads);
-}
-
-// Widest supported image signature (WebP needs 12 bytes: `RIFF….WEBP`). A payload
-// shorter than this can't hold a complete header for any format we accept.
-const MIN_IMAGE_BYTES = 12;
-
-// POSIX NAME_MAX — the per-component filename limit on ext4/APFS/HFS+. A longer
-// component makes the write fail with ENAMETOOLONG.
-const MAX_FILENAME_BYTES = 255;
-
-/**
- * Persist a base64-encoded IMAGE into `dir`, deriving the format from the bytes
- * rather than trusting the client: decode → size cap → magic-byte sniff → force
- * the extension to the detected format → sanitize + containment guard → write.
- *
- * This is the sibling of `saveBase64Upload` for the paths that must be certain
- * they wrote an image (they hand the file to an image-gen backend or to an agent
- * that will read it), so an extension allowlist isn't enough. Naming is the
- * CALLER's call — pass a name that is already unique if later uploads must not
- * overwrite this one, since `dir` is a shared bucket.
- *
- * Throws ServerError with the status/code/message contract `routes/screenshots.js`
- * established (`FILE_TOO_LARGE`, `INVALID_FILE_TYPE`, `INVALID_FILENAME` — all
- * 400) so callers keep their pinned responses.
- *
- * @param {string} dir - Destination directory (created if missing).
- * @param {{ filename: string, data: string }} upload - Desired base name (the
- * extension is replaced with the detected one) + base64 payload.
- * @param {{ maxBytes: number }} opts
- * @returns {Promise<{ filename: string, filePath: string, size: number,
- * format: string, mime: string }>}
- */
-export async function saveImageUpload(dir, { filename, data }, { maxBytes }) {
- const buffer = Buffer.from(data, 'base64');
- if (buffer.length > maxBytes) {
- throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
- }
-
- // Floor before the sniff, because the per-format signatures are short (a JPEG is
- // 3 bytes, a GIF header 6) and would happily "detect" a truncated payload — which
- // then saves as a success and hands a consumer a path to an unreadable file. 12
- // bytes is the widest signature (WebP's RIFF….WEBP), so anything under it cannot
- // be a complete header for ANY supported format, let alone a complete image.
- if (buffer.length < MIN_IMAGE_BYTES) {
- throw new ServerError('Invalid image file - only PNG, JPEG, GIF, and WebP are supported', { status: 400, code: 'INVALID_FILE_TYPE' });
- }
-
- const detected = detectImageFormat(buffer);
- if (!detected) {
- throw new ServerError('Invalid image file - only PNG, JPEG, GIF, and WebP are supported', { status: 400, code: 'INVALID_FILE_TYPE' });
- }
-
- // The DETECTED extension always wins over whatever the client claimed, so the
- // file on disk can't advertise a type its bytes contradict. Strip a matching
- // extension off the base rather than appending a second one, then clamp the base
- // so `base + ext` fits NAME_MAX — a caller that prefixes the name (see
- // services/shellImageDrop.js) can otherwise push a legitimately-long client
- // filename past the limit and turn the write into an ENAMETOOLONG 500.
- const safeName = sanitizeFilename(filename);
- const base = safeName.toLowerCase().endsWith(detected.ext)
- ? safeName.slice(0, -detected.ext.length)
- : safeName;
- // sanitizeFilename leaves only ASCII, so slicing chars is slicing bytes.
- const fname = `${base.slice(0, MAX_FILENAME_BYTES - detected.ext.length)}${detected.ext}`;
- const filePath = join(dir, fname);
- if (!isPathInsideDir(dir, filePath)) {
- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
- }
-
- await ensureDir(dir);
- await writeFile(filePath, buffer);
-
- return { filename: fname, filePath, size: buffer.length, format: detected.format, mime: detected.mime };
-}
-
-/**
- * Persist a base64-encoded upload into `dir` with the shared attachment
- * pipeline: extension allowlist → base64 decode → size cap → ensureDir →
- * `<uuid8>-<sanitized-name>` naming → containment guard → write.
- *
- * Throws ServerError with the exact status/code/message contract the
- * attachment routes established (`INVALID_FILE_TYPE`, `FILE_TOO_LARGE`,
- * `INVALID_FILENAME` — all 400), so refactored routes keep their pinned
- * responses. Consolidates `routes/attachments.js`, `routes/brainSongbook.js`,
- * and `routes/uploads.js` — the last keeps its own richer response shape
- * (`originalName` / `sizeFormatted` / `createdAt`) around these fields.
- *
- * @param {string} dir - Destination directory (created if missing).
- * @param {{ filename: string, data: string }} upload - Original filename +
- * base64 payload (validated as present by the calling route).
- * @param {{ allowedExtensions: Set<string>, maxBytes: number }} opts
- * @returns {Promise<{ id: string, filename: string, filePath: string,
- * buffer: Buffer, size: number, mime: string }>} `id` is the full UUID whose
- * first 8 chars prefix `filename`.
- */
-export async function saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes }) {
- const ext = getFileExtension(filename);
- if (!ext || !allowedExtensions.has(ext)) {
- const allowedList = [...allowedExtensions].join(', ');
- throw new ServerError(`File type not allowed. Supported: ${allowedList}`, { status: 400, code: 'INVALID_FILE_TYPE' });
- }
-
- const buffer = Buffer.from(data, 'base64');
- if (buffer.length > maxBytes) {
- throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
- }
-
- await ensureDir(dir);
-
- // Unique uuid prefix avoids collisions; sanitize kills traversal characters.
- const id = randomUUID();
- const fname = `${id.slice(0, 8)}-${sanitizeFilename(filename)}`;
- const filePath = join(dir, fname);
- // Double-check the path is within the destination dir (defense in depth).
- if (!isPathInsideDir(dir, filePath)) {
- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
- }
-
- await writeFile(filePath, buffer);
-
- return { id, filename: fname, filePath, buffer, size: buffer.length, mime: getMimeType(getFileExtension(fname)) };
-}
-
-/**
- * Serve a machine-local file from `dir` by user-supplied filename with the
- * shared safety pipeline: sanitize → containment guard (400
- * `INVALID_FILENAME`) → existence check (404, message/code parametrized via
- * `missingError` so routes keep their contracts) → `X-Content-Type-Options:
- * nosniff` → attachment disposition for RISKY_MIME_TYPES → `res.sendFile`.
- *
- * Mirrors the exact serving behavior of `routes/attachments.js`.
- *
- * @param {import('express').Response} res
- * @param {string} dir - The containing directory.
- * @param {string} filename - Raw user-supplied filename.
- * @param {{ missingError?: { message: string, code: string } }} [opts]
- */
-export async function serveLocalFile(res, dir, filename, { missingError } = {}) {
- const safeFilename = sanitizeFilename(filename);
- const filePath = resolvePath(dir, safeFilename);
-
- if (!isPathInsideDir(dir, filePath)) {
- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
- }
-
- if (!(await pathExists(filePath))) {
- const { message = 'Attachment not found', code = 'NOT_FOUND' } = missingError || {};
- throw new ServerError(message, { status: 404, code });
- }
-
- const mimeType = getMimeType(getFileExtension(safeFilename));
- res.set('X-Content-Type-Options', 'nosniff');
- if (RISKY_MIME_TYPES.has(mimeType)) {
- res.set('Content-Disposition', `attachment; filename="${safeFilename}"`);
- }
- res.type(mimeType).sendFile(filePath);
-}
-
-/**
- * Validate a user-supplied filename is a safe basename with one of the
- * allowed extensions — refuses path-traversal, null bytes, separators, and
- * exact `.` / `..`. Throws a 400 ServerError with code VALIDATION_ERROR
- * so calling routes don't have to repeat the check.
- *
- * Consolidates the two near-identical assertions that used to live in
- * `services/loras.js#assertSafeLoraFilename` (`.safetensors` only) and
- * `services/imageGen/local.js#assertGalleryFilename` (`.png` only).
- *
- * Substring `..` is intentionally allowed (e.g. `foo..bar.png` is fine);
- * only the exact-string traversal cases are rejected. Path separators (`/`
- * and `\`) are rejected on every platform — the same input gets posted
- * from Windows clients too.
- *
- * @param {string} filename
- * @param {{ extensions: string[], subject?: string, requiredMessage?: string }} opts
- * - `extensions`: list of allowed extensions including the leading dot
- * (`['.png']`, `['.safetensors']`, etc.). Case-insensitive match. Each
- * entry MUST be a non-empty string starting with `.` — otherwise a bare
- * suffix like `'png'` would also match `'not-an-imagepng'` and weaken
- * the validation, so we treat that as a programmer error and throw.
- * - `subject`: optional noun for the error message ("LoRA filename" →
- * "Invalid LoRA filename"). Defaults to "filename".
- * - `requiredMessage`: optional exact message used when `filename` is
- * missing/empty — preserves backward-compat for wrappers that used to
- * throw a specific phrase. The gallery wrapper passes `'Invalid filename'`
- * (its pre-refactor implementation threw that for every failure, including
- * missing-input); the LoRA wrapper passes `'Filename required'` to match
- * its historical wording. When omitted, the message is derived from
- * `subject` (e.g. `'Filename required'` / `'LoRA filename required'`).
- */
-export function assertSafeFilename(filename, { extensions, subject = 'filename', requiredMessage } = {}) {
- if (!Array.isArray(extensions) || extensions.length === 0) {
- throw new Error('assertSafeFilename: extensions allowlist is required');
- }
- for (const ext of extensions) {
- if (typeof ext !== 'string' || ext.length < 2 || !ext.startsWith('.')) {
- throw new Error(`assertSafeFilename: each extension must be a non-empty string starting with "." (got ${JSON.stringify(ext)})`);
- }
- }
- const subjectText = subject || 'filename';
- if (!filename || typeof filename !== 'string') {
- const Subject = `${subjectText[0].toUpperCase()}${subjectText.slice(1)}`;
- const message = typeof requiredMessage === 'string' && requiredMessage.length > 0
- ? requiredMessage
- : `${Subject} required`;
- throw new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });
- }
- // Null bytes terminate C strings — some POSIX syscalls treat the prefix
- // as a separate path. Reject up front so it can't reach the FS layer.
- if (filename.includes('\0')) {
- throw new ServerError(`Invalid ${subjectText}`, { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (!isSafeFilename(filename, extensions)) {
- throw new ServerError(`Invalid ${subjectText}`, { status: 400, code: 'VALIDATION_ERROR' });
- }
-}
-
-/**
- * `assertSafeFilename`'s non-throwing twin: the same rule as a predicate, for
- * callers that must report a bad name as *data* rather than fail the request —
- * e.g. a read-only preflight that names one corrupt record as a blocked row
- * instead of 400-ing the whole sweep. Both share this implementation so the
- * thrown gate and the reported verdict can never disagree.
- *
- * Rejects: empty/non-string, null bytes (they terminate C strings, so some
- * POSIX syscalls treat the prefix as a separate path), `.`/`..`, any path
- * separator, anything that isn't already a pure basename, and any extension
- * outside `extensions`. The basename equality check is kept alongside the
- * separator check so e.g. `subdir\foo.png` is rejected on both counts.
- *
- * `extensions` must be dot-prefixed, and unlike `assertSafeFilename` this does
- * not police that for you — a bare suffix like `png` would also match
- * `not-an-imagepng`. Pass a module constant, never a caller-supplied list.
- */
-export function isSafeFilename(filename, extensions) {
- if (!isTopLevelEntryName(filename)) return false;
- const lower = filename.toLowerCase();
- return extensions.some((ext) => lower.endsWith(String(ext).toLowerCase()));
-}
-
-/**
- * `isSafeFilename`'s traversal half, without the extension gate: true when
- * `name` addresses exactly one entry directly inside some directory.
- *
- * For callers that legitimately cannot allowlist extensions — an arbitrary
- * user asset, or a directory entry — but must still refuse traversal. Naming
- * a single entry is what makes a subsequent `join(dir, name)` safe *in the
- * filesystem sense* and not just lexically: with no separator there is no
- * intermediate component left for a symlink to redirect, which a
- * `resolve`/`relative` containment check cannot see. The Data Manager's
- * per-item purge (`purgeCategory`) is the reference caller.
- *
- * `isSafeFilename` is layered on top of this, so the two can never disagree
- * about what "a single entry" means.
- */
-export function isTopLevelEntryName(name) {
- if (!name || typeof name !== 'string') return false;
- if (name.includes('\0')) return false;
- if (name === '.' || name === '..') return false;
- if (name.includes('/') || name.includes('\\')) return false;
- return basename(name) === name;
-}
-
-/**
- * True when `candidatePath` resolves to a location strictly inside `dir`.
- *
- * Uses the same anchored-prefix containment idiom as `makePathResolver`
- * (`resolvePath(dir) + PATH_SEP`): appending the platform separator to the
- * resolved root means a sibling directory whose name merely *starts with* the
- * root (e.g. `/data/uploads-evil` vs `/data/uploads`) can't slip past a bare
- * `startsWith(root)` check. This is stricter than the `resolvedPath.startsWith(DIR)`
- * guard the upload/attachment/screenshot routes used before. The root itself is
- * NOT reported as "inside" (there's no trailing separator on the bare root),
- * which is the desired behavior for file-containment checks.
- *
- * @param {string} dir - the containing directory (absolute or relative)
- * @param {string} candidatePath - the path to test
- * @returns {boolean}
- */
-export function isPathInsideDir(dir, candidatePath) {
- if (typeof dir !== 'string' || typeof candidatePath !== 'string' || !dir || !candidatePath) {
- return false;
- }
- const rootPrefix = resolvePath(dir) + PATH_SEP;
- return resolvePath(candidatePath).startsWith(rootPrefix);
-}
-
-/**
- * Build a single-root path resolver that returns a function with the same
- * signature as `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset`.
- *
- * Defense in depth (applied on every call):
- * 1. `basename()` strips dirs (so `../../etc/passwd` → `passwd`).
- * 2. Reject `.`/`..`/empty basenames outright.
- * 3. `resolve` + `startsWith(rootPrefix)` so unicode tricks can't escape.
- * 4. Optional extension allow-list (case-insensitive) before any FS syscall.
- * 5. When `mustExist`, `statSync({ throwIfNoEntry: false }).isFile()` rejects
- * directories (the root itself would otherwise pass an existsSync check
- * and flow into ffmpeg / image-gen as an "image path" where it'd fail in
- * confusing ways). Note: `statSync` follows symlinks, so a symlink under
- * the root pointing to a regular file outside still passes. PortOS is
- * single-user (see AGENTS.md "Security Model") so we accept that — for
- * symlink rejection, swap to `lstatSync`.
- *
- * Pass `{ mustExist: false }` at call time for code paths that intentionally
- * skip the existence check (e.g. when the path is resolved at request time
- * but read later — TOCTOU between resolve and use isn't worth the extra
- * syscall, and the downstream renderer surfaces a clear error if the file
- * vanished).
- *
- * @param {() => string} getRoot - Thunk returning the absolute directory.
- * A thunk (not a literal) so tests that mutate `PATHS.x` at mock-eval
- * time still steer the resolver — the value is captured on first call
- * and cached thereafter (recomputed only if the thunk later returns a
- * different value, which production code never does).
- * @param {object} [opts]
- * @param {string[]} [opts.extensions] - allowed extensions WITHOUT the leading
- * dot (`['png', 'jpg', 'jpeg', 'webp']`). When omitted, all extensions are
- * accepted (matches the legacy gallery/refs behavior — extension checks
- * happen elsewhere on those paths).
- * @param {boolean} [opts.cache=false] - Memoize successful resolutions. Only
- * safe for shipped/stable assets (templates) where the basename → path
- * binding is stable for the process lifetime; never enable for user-mutable
- * dirs (gallery, refs) since deletions would be masked.
- * @returns {(name: string, opts?: { mustExist?: boolean }) => string|null}
- */
-export function makePathResolver(getRoot, { extensions, cache = false } = {}) {
- if (typeof getRoot !== 'function') {
- throw new Error('makePathResolver: getRoot must be a function returning the root dir');
- }
- // Escape regex metacharacters in each extension before interpolating —
- // current callers pass plain alphanumeric tokens (png/jpg/jpeg/webp), but
- // the exported factory shouldn't behave incorrectly if a future caller
- // passes an extension containing `.`/`+`/etc.
- const extRegex = Array.isArray(extensions) && extensions.length > 0
- ? new RegExp(`\\.(${extensions
- .map((e) => String(e).replace(/^\./, '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
- .join('|')})$`, 'i')
- : null;
- const memo = cache ? new Map() : null;
- // Resolved-root cache so the hot path doesn't re-run `resolvePath(root) +
- // PATH_SEP` per call. Recomputes only when `getRoot()` returns a different
- // value — picks up test-time `PATHS.x = ...` mutation on first call, then
- // stays warm for the rest of the process.
- let _root = null;
- let _rootAbsPrefix = null;
-
- return (name, { mustExist = true } = {}) => {
- if (typeof name !== 'string' || !name) return null;
- const safe = basename(name);
- if (!safe || safe === '.' || safe === '..') return null;
- if (extRegex && !extRegex.test(safe)) return null;
- // Refresh the root cache BEFORE the memo lookup so a getRoot() that
- // suddenly returns a new value (e.g. a test re-mocks `PATHS.x` mid-run)
- // invalidates the memo too — otherwise the old root's cached
- // resolutions would shadow the new root forever.
- const root = getRoot();
- if (root !== _root) {
- _root = root;
- _rootAbsPrefix = resolvePath(root) + PATH_SEP;
- if (memo) memo.clear();
- }
- const cacheKey = memo ? (mustExist ? `must:${safe}` : `nostat:${safe}`) : null;
- if (memo && memo.has(cacheKey)) return memo.get(cacheKey);
- const localPath = resolvePath(join(root, safe));
- if (!localPath.startsWith(_rootAbsPrefix)) return null;
- if (!mustExist) {
- if (memo) memo.set(cacheKey, localPath);
- return localPath;
- }
- // throwIfNoEntry:false swallows ENOENT but not EACCES / transient I/O —
- // treat those as "not a valid reference" too rather than bubbling a 500
- // out of the route layer.
- let resolved = null;
- try {
- const stat = statSync(localPath, { throwIfNoEntry: false });
- resolved = stat?.isFile() ? localPath : null;
- } catch { /* falls through to null */ }
- // Only cache successful resolutions — a missing-then-installed asset
- // should pick up on the next call (e.g. setup-data.js racing a render).
- if (memo && resolved) memo.set(cacheKey, resolved);
- return resolved;
- };
-}
-
-/**
- * Resolve a user-supplied gallery image filename to an absolute path under
- * `PATHS.images`. Returns `null` on any failure so callers can decide whether
- * to throw, log-and-skip, or substitute a fallback. See `makePathResolver`
- * for the defense-in-depth checks. Late-binds via a thunk so tests that
- * mutate `PATHS.images` at mock-eval time still steer the resolver.
- */
-export const resolveGalleryImage = makePathResolver(() => PATHS.images);
-
-/**
- * Resolve a user-supplied reference-image filename to an absolute path under
- * `PATHS.imageRefs`. Multi-reference uploads land in a sibling dir to keep
- * them out of the gallery enumeration; same defense-in-depth as the gallery
- * resolver but anchored at the refs root.
- */
-export const resolveImageRef = makePathResolver(() => PATHS.imageRefs);
-
-/**
- * Resolve an Image Cleaner temp init/result filename to an absolute path under
- * `PATHS.imageCleanTmp` (issue #2264). The GPU FLUX round-trip stages the
- * sync-cleaned init bytes here and renders the result back here, so the runner
- * must accept this root as a valid `initImagePath` source. Same defense-in-depth
- * as the gallery/refs resolvers, anchored at the temp root.
- */
-export const resolveImageCleanTmp = makePathResolver(() => PATHS.imageCleanTmp);
-
-/**
- * Resolve a peer-uploaded conditioning image staged under
- * `PATHS.federatedMediaInbox` to an absolute path. The provider maps an
- * accepted asset id onto one of these before handing the job to the local
- * generator, so the runner must accept this root as a valid `initImagePath` /
- * reference / keyframe source.
- *
- * Extension-restricted at the resolver rather than only at upload: the upload
- * endpoint already MIME-allowlists, but this is the boundary the *runner*
- * crosses, and a second check here means a hand-written file in the inbox still
- * cannot become an arbitrary path argument to the generator.
- */
-export const resolveFederatedMediaAsset = makePathResolver(() => PATHS.federatedMediaInbox, {
- extensions: ['png', 'jpg', 'jpeg', 'webp'],
-});
-
-/**
- * Resolve a sprite reference asset used as an image-gen init image (issue
- * #2896 — anchors i2i from the locked main reference; uploaded design
- * references). `data/sprites/` is a server-managed NESTED tree, so unlike
- * the single-level basename resolvers above this accepts only an absolute
- * path already inside the sprites root (no basename fallback — a bare
- * filename is ambiguous across records) and validates containment.
- */
-export function resolveSpriteImageInput(rawPath) {
- if (typeof rawPath !== 'string' || !rawPath) return null;
- const resolved = resolvePath(rawPath);
- return isPathInsideDir(PATHS.sprites, resolved) ? resolved : null;
-}
-
-/**
- * Resolve a shipped visual template filename (e.g. character reference-sheet
- * layout PNG) to an absolute path under `PATHS.visualTemplates`. Caches
- * successful resolutions because the template assets are shipped and stable
- * for the lifetime of the process — keeps reference-sheet rendering off the
- * statSync hot path.
- */
-export const resolveTemplateAsset = makePathResolver(() => PATHS.visualTemplates, {
- extensions: ['png', 'jpg', 'jpeg', 'webp'],
- cache: true,
-});
-
-/**
- * Resolve a user-supplied screenshot filename to an absolute path under
- * `PATHS.screenshots`. Used by the vision-test endpoint, whose `imagePath`
- * comes straight from `req.body` — basenaming the input (and rejecting any
- * non-image extension or missing file) stops `../` traversal and absolute-path
- * escapes from reading arbitrary files off disk and forwarding their contents
- * to an external vision provider. Returns `null` on any failure so the caller
- * can surface a clean error. See `makePathResolver` for the defense-in-depth
- * checks. Late-binds via a thunk so tests that mutate `PATHS.screenshots` still
- * steer the resolver.
- */
-export const resolveScreenshot = makePathResolver(() => PATHS.screenshots, {
- extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'],
-});
-
-/**
- * Resolve any user-supplied image input (init image OR multi-reference image)
- * to an absolute path under one of PortOS's approved image roots — the
- * gallery (`PATHS.images`), the multi-ref upload dir (`PATHS.imageRefs`),
- * or the shipped visual-template dir (`PATHS.visualTemplates`). Used by the
- * image-gen runner to re-validate paths that originated from internal
- * features (gallery picks, reference-sheet renders) which may legitimately
- * cross dir boundaries.
- *
- * Accepts both basename input (`"foo.png"`) and already-resolved absolute
- * paths (the local image-gen runner re-validates the same input on every
- * call so we need to accept both shapes).
- *
- * @param {string} rawPath - basename or absolute path
- * @returns {string|null} validated absolute path, or null
- */
-// Pairs of (PATHS-key, resolver). Read PATHS at CALL time so tests that
-// mutate `PATHS.x` at mock-eval time still steer the prefix dispatch — a
-// module-load snapshot would freeze the pre-mock paths.
-const IMAGE_INPUT_RESOLVERS = [
- ['images', resolveGalleryImage],
- ['imageRefs', resolveImageRef],
- ['visualTemplates', resolveTemplateAsset],
- // Image Cleaner temp init images (issue #2264) — the GPU FLUX round-trip
- // stages sync-cleaned bytes here as the img2img init.
- ['imageCleanTmp', resolveImageCleanTmp],
- // Peer-uploaded conditioning images (#4348) — an allowlisted peer's init /
- // reference / keyframe bytes, staged for the one federated render they were
- // uploaded for.
- ['federatedMediaInbox', resolveFederatedMediaAsset],
- // Sprite reference assets (issue #2896) — the locked main reference /
- // uploaded design reference as the anchors' i2i init. Absolute-only
- // (returns null on basename input, so the fall-through loop skips it).
- ['sprites', resolveSpriteImageInput],
-];
-
-export function resolveImageInputPath(rawPath) {
- if (typeof rawPath !== 'string' || !rawPath) return null;
- // For ABSOLUTE inputs, dispatch by prefix. The single-root resolvers
- // basename their input for defense-in-depth, so trying them in order on an
- // absolute path can silently redirect a `/data/templates/foo.png` input
- // to `/data/images/foo.png` whenever a same-named file lives in the gallery.
- // Validate against the matching root only.
- const resolvedInput = resolvePath(rawPath);
- for (const [key, resolver] of IMAGE_INPUT_RESOLVERS) {
- const rootPrefix = resolvePath(PATHS[key]) + PATH_SEP;
- if (resolvedInput.startsWith(rootPrefix)) return resolver(rawPath);
- }
- // For basename / relative input (no matching prefix), fall through the
- // resolvers in order. First match wins; basename collisions across roots
- // are accepted as ambiguous and resolve to the first defined root.
- for (const [, resolver] of IMAGE_INPUT_RESOLVERS) {
- const candidate = resolver(rawPath);
- if (candidate) return candidate;
- }
- return null;
-}
-
-/**
- * List a directory, keep entries whose extension matches `extensions`, stat
- * each, and project the survivors through `mapEntry(name, fullPath, stat)`.
- * Three sibling helpers (listLoras / listGallery / listMusicLibrary) used to
- * spell this loop out by hand — collapsed onto one primitive so the dir-
- * missing fallback, extension filter, and stat-failure handling all stay in
- * sync.
- *
- * - `extensions`: array of lowercased extensions including the leading dot
- * (`['.png']`, `['.mp3', '.wav', ...]`). Matched against `extname(name)`
- * case-insensitively so `FOO.PNG` and `foo.png` both pass.
- * - `mapEntry`: async/sync `(name, fullPath, stat) => entry|null`. Return
- * `null` to drop the entry. Final array preserves readdir order minus drops.
- * - `requireRegularFile` (default `true`): when true, entries whose stat
- * reports `!isFile()` are dropped before `mapEntry` runs (skips directories
- * with matching extensions). Pass `false` to match the gallery's legacy
- * behavior (only drops on stat failure).
- *
- * Missing directory → `[]` (no surprise 500 on a fresh install). Stat errors
- * on individual entries → drop that entry (matches the prior per-site
- * `.catch(() => null)` pattern).
- */
-export async function listDirectoryByExtension(dir, { extensions, mapEntry, requireRegularFile = true } = {}) {
- if (!Array.isArray(extensions) || extensions.length === 0) {
- throw new Error('listDirectoryByExtension: extensions allowlist is required');
- }
- if (typeof mapEntry !== 'function') {
- throw new Error('listDirectoryByExtension: mapEntry must be a function');
- }
- const allowed = new Set(extensions.map((e) => String(e).toLowerCase()));
- const names = await readdir(dir).catch((err) => {
- if (err?.code === 'ENOENT') return [];
- throw err;
- });
- const filtered = names.filter((name) => allowed.has((extname(name) || '').toLowerCase()));
- const entries = await Promise.all(filtered.map(async (name) => {
- const fullPath = join(dir, name);
- const s = await stat(fullPath).catch(() => null);
- if (!s) return null;
- if (requireRegularFile && !s.isFile()) return null;
- return mapEntry(name, fullPath, s);
- }));
- return entries.filter((v) => v != null);
-}
-
-// Size in bytes of every file under `path`. Shells out to `du -sk` (or
-// PowerShell on Windows) — orders of magnitude faster than walking with
-// node's recursive readdir on large trees (hundreds of GB / 200k+ files).
-// Returns 0 + logs on failure (missing tool, permission denied, timeout) so
-// the Media Models endpoint stays responsive even on unusual systems instead
-// of throwing and 500ing the whole route. Counted/reporting callers can pass
-// `{ strict: true }` to reject instead, preserving failed-vs-legitimately-empty.
-export async function dirSize(path, { strict = false } = {}) {
- if (strict) {
- const present = await stat(path).then(
- () => true,
- (err) => {
- if (err?.code === 'ENOENT') return false;
- throw err;
- },
- );
- if (!present) return 0;
- } else if (!existsSync(path)) {
- return 0;
- }
- if (IS_WIN) {
- // Pass the path via an env var so a literal apostrophe in the path can't
- // close the PowerShell string and inject commands.
- const result = await execFileAsync('powershell', [
- '-NoProfile', '-Command',
- '(Get-ChildItem -Recurse -File $Env:DIRSIZE_TARGET | Measure-Object -Property Length -Sum).Sum',
- ], { encoding: 'utf8', timeout: 60_000, env: { ...process.env, DIRSIZE_TARGET: path } }).catch((err) => ({ error: err }));
- if (result.error) {
- if (strict) throw result.error;
- console.log(`⚠️ dirSize(${path}) failed: ${result.error.message}`);
- return 0;
- }
- const bytes = parseInt(result.stdout.trim(), 10);
- if (!Number.isFinite(bytes) || bytes < 0) {
- if (strict) throw new Error(`Could not parse directory size for ${path}`);
- return 0;
- }
- return bytes;
- }
- const result = await execFileAsync('du', ['-sk', path], { encoding: 'utf8', timeout: 60_000 }).catch((err) => ({ error: err }));
- if (result.error) {
- if (strict) throw result.error;
- console.log(`⚠️ dirSize(${path}) failed: ${result.error.message}`);
- return 0;
- }
- const kb = parseInt(result.stdout.split('\t')[0], 10);
- if (!Number.isFinite(kb) || kb < 0) {
- if (strict) throw new Error(`Could not parse directory size for ${path}`);
- return 0;
- }
- return kb * 1024;
-}
-
-/** SHA-256 a string or Buffer as hex — `sha256File`'s in-memory twin. */
-export const sha256Text = (value) => createHash('sha256').update(value).digest('hex');
-
-/**
- * SHA-256 a file as hex. One-shot read under 512 KB; streams above so multi-GB
- * videos don't blow heap. Threshold matches `server/services/backup.js`'s
- * snapshot manifest generator.
- */
-const SHA256_STREAM_THRESHOLD = 512 * 1024;
-export async function sha256File(path) {
- const info = await stat(path);
- if (info.size < SHA256_STREAM_THRESHOLD) {
- const buf = await readFile(path);
- return createHash('sha256').update(buf).digest('hex');
- }
- return new Promise((resolve, reject) => {
- const hasher = createHash('sha256');
- const stream = createReadStream(path);
- stream.on('error', reject);
- stream.pipe(hasher);
- hasher.on('finish', () => resolve(hasher.digest('hex')));
- hasher.on('error', reject);
- });
-}
+export * from './fileCore.js';
+export * from './jsonIo.js';
+export * from './mimeTypes.js';
+export * from './paths.js';
+export * from './pathSafety.js';
+export * from './uploads.js';
diff --git a/server/lib/index.js b/server/lib/index.js
index 5f42ccaec5..af7b354f30 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -187,8 +187,14 @@ export * from './createKeyCachedQueue.js';
export * from './createNewestWinsGuard.js';
export * from './dataRoot.js';
export * from './agentInstructionsFile.js';
-export * from './fileUtils.js';
+export * from './fileCore.js';
+export * as fileUtils from './fileUtils.js';
export * from './fileWriteQueue.js';
+export * from './jsonIo.js';
+export * from './mimeTypes.js';
+export * from './paths.js';
+export * from './pathSafety.js';
+export * from './uploads.js';
export * from './icloudFile.js';
export * from './spawnCwd.js';
export * from './schemaVersions.js';
diff --git a/server/lib/jsonIo.js b/server/lib/jsonIo.js
new file mode 100644
index 0000000000..f6869d1498
--- /dev/null
+++ b/server/lib/jsonIo.js
@@ -0,0 +1,615 @@
+/** JSON, JSONL, and cached-store file IO helpers. */
+import { existsSync } from 'fs';
+import { appendFile, open, readFile, readdir, stat } from 'fs/promises';
+import { basename, dirname } from 'path';
+import { atomicWrite, ensureDir, sleep } from './fileCore.js';
+import { createFileWriteQueue } from './fileWriteQueue.js';
+
+const isWindows = () => process.platform === 'win32';
+const WIN_RETRY_ATTEMPTS = 5;
+const WIN_RETRY_DELAY_MS = 10;
+const WIN_READ_LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY'];
+
+/**
+ * Check if a string is potentially valid JSON.
+ * Performs quick structural validation before parsing.
+ *
+ * @param {string} str - String to validate
+ * @param {Object} options - Validation options
+ * @param {boolean} [options.allowArray=true] - Allow array JSON (default: true)
+ * @returns {boolean} True if the string appears to be valid JSON
+ *
+ * @example
+ * isValidJSON('{"key": "value"}') // true
+ * isValidJSON('[1, 2, 3]') // true
+ * isValidJSON('') // false
+ * isValidJSON('{"incomplete":') // false
+ */
+export function isValidJSON(str, { allowArray = true } = {}) {
+ if (!str || !str.trim()) return false;
+ const trimmed = str.trim();
+
+ // Check for basic JSON structure (object or array)
+ const isObject = trimmed.startsWith('{') && trimmed.endsWith('}');
+ const isArray = trimmed.startsWith('[') && trimmed.endsWith(']');
+
+ if (!isObject && !(allowArray && isArray)) return false;
+
+ return true;
+}
+
+/**
+ * Index of the first JSON array token in `str`, or -1 when it holds none.
+ *
+ * Split out of `extractJSONArray` so a caller can tell "found an array" from "found
+ * nothing" — a distinction `extractJSONArray` erases by design (it manufactures a
+ * literal '[]' for the not-found case). `readJSONFileStrict` needs it: for a
+ * swallowing caller a manufactured '[]' is just the default, but for a strict one it
+ * would forge a trustworthy-looking EMPTY out of unreadable bytes.
+ *
+ * @param {string} str
+ * @returns {number} Index of the array start, or -1
+ */
+function findJSONArrayStart(str) {
+ if (!str) return -1;
+ // Look for '[{' (array with objects) first
+ const objectStart = str.indexOf('[{');
+ if (objectStart >= 0) return objectStart;
+ // Check for empty array - find '[]' that's not part of ANSI codes like [31m
+ const emptyMatch = str.match(/\[\](?![0-9])/);
+ return emptyMatch ? str.indexOf(emptyMatch[0]) : -1;
+}
+
+/**
+ * Extract JSON array from string that may contain ANSI codes or other noise.
+ * Useful for parsing pm2 jlist output which may include warnings before the JSON.
+ *
+ * @param {string} str - String potentially containing JSON array
+ * @returns {string} Extracted JSON or '[]' if not found
+ */
+export function extractJSONArray(str) {
+ const jsonStart = findJSONArrayStart(str);
+ return jsonStart >= 0 ? str.slice(jsonStart) : '[]';
+}
+
+/**
+ * Safely parse JSON with validation and fallback.
+ * Avoids "Unexpected end of JSON input" errors from empty/corrupted files.
+ * For arrays, automatically extracts JSON from strings with ANSI codes/noise (e.g., pm2 output).
+ *
+ * @param {string} str - JSON string to parse
+ * @param {*} defaultValue - Default value if parsing fails (default: null)
+ * @param {Object} options - Parse options
+ * @param {boolean} [options.allowArray=true] - Allow array JSON
+ * @param {boolean} [options.logError=false] - Log parsing errors
+ * @param {string} [options.context=''] - Context for error logging
+ * @returns {*} Parsed JSON or default value
+ *
+ * @example
+ * safeJSONParse('{"key": "value"}', {}) // { key: "value" }
+ * safeJSONParse('', {}) // {}
+ * safeJSONParse('invalid', []) // []
+ * safeJSONParse(null, { default: true }) // { default: true }
+ */
+export function safeJSONParse(str, defaultValue = null, { allowArray = true, logError = false, context = '' } = {}) {
+ // For arrays, try to extract JSON from noisy output (e.g., pm2 with ANSI codes)
+ if (allowArray && Array.isArray(defaultValue) && str && !str.trim().startsWith('[')) {
+ str = extractJSONArray(str);
+ }
+
+ if (!isValidJSON(str, { allowArray })) {
+ if (logError && str) {
+ console.warn(`Invalid JSON${context ? ` in ${context}` : ''}: empty or malformed content`);
+ }
+ return defaultValue;
+ }
+
+ // Attempt actual parse - the validation above catches structural issues
+ // but syntax errors like trailing commas still need handling
+ try {
+ return JSON.parse(str);
+ } catch (err) {
+ if (logError) {
+ console.warn(`Failed to parse JSON${context ? ` in ${context}` : ''}: ${err.message}`);
+ }
+ return defaultValue;
+ }
+}
+
+/**
+ * Read a file, returning null on any error (missing file, permission denied, etc.).
+ *
+ * Collapses the inlined `readFile(path, encoding).catch(() => null)` pattern used
+ * across services for "optional file — fall through if absent." For Buffer reads,
+ * pass `encoding: null` (or omit when calling with no second arg, default 'utf8').
+ *
+ * NOTE: like `readJSONFile`, this conflates "absent" with "unreadable" — both
+ * return null. When the caller derives a user-visible stat from the result (where
+ * a fake empty is a lie, not a default), reach for `tryReadFileStrict` (raw bytes)
+ * or `readJSONFileStrict` (parsed JSON) instead.
+ *
+ * @param {string} filePath - Path to read
+ * @param {string|null} [encoding='utf8'] - Encoding (null for Buffer)
+ * @returns {Promise<string|Buffer|null>} File contents or null on any read error
+ */
+export async function tryReadFile(filePath, encoding = 'utf8') {
+ return readFile(filePath, encoding).catch(() => null);
+}
+
+/**
+ * `tryReadFile` that reports whether the read is TRUSTWORTHY — the raw-bytes
+ * counterpart to `readJSONFileStrict`, for callers that parse (or count, or
+ * display) the contents themselves rather than handing the file to JSON.parse.
+ *
+ * - ENOENT (never written) → `{ ok: true, value: null }` — a genuine "nothing
+ * here yet". Safe to treat as a real empty.
+ * - any other read error → `{ ok: false, value: null }` — EACCES, EIO,
+ * EISDIR, a transient FS failure. We do NOT know the file is absent.
+ * - read → `{ ok: true, value: contents }`
+ *
+ * So the three states `tryReadFile` collapses into one `null` stay separable:
+ * `ok && value !== null` = read, `ok && value === null` = absent, `!ok` =
+ * present-but-unreadable. Windows swap-window retries are shared with
+ * `readJSONFileStrict`, so an `atomicWrite` in flight can't masquerade as ENOENT.
+ *
+ * @param {string} filePath - Path to read
+ * @param {string|null} [encoding='utf8'] - Encoding (null for Buffer)
+ * @returns {Promise<{ ok: boolean, value: string|Buffer|null }>}
+ *
+ * @example
+ * const { ok, value } = await tryReadFileStrict(LEDGER_FILE);
+ * if (!ok) throw new Error('ledger unreadable'); // never report a fake 0
+ */
+export async function tryReadFileStrict(filePath, encoding = 'utf8') {
+ return readWithSwapRetry(filePath, encoding).then(
+ (value) => ({ ok: true, value }),
+ // ENOENT is the ONLY errno that proves absence. Everything else — EACCES on
+ // the file or a parent dir, ENOTDIR, EIO — means we could not confirm it,
+ // which must stay distinct from "confirmed empty".
+ (err) => ({ ok: err?.code === 'ENOENT', value: null })
+ );
+}
+
+/**
+ * Read at most `maxBytes` from the END of a file, as UTF-8.
+ *
+ * The bounded-memory counterpart to `tryReadFile` for append-only logs and
+ * spools that have no upper size bound (agent transcripts, PTY spools, CLI
+ * rollout JSONL). `readFile` on one of those loads the whole thing into heap;
+ * this reads only the trailing window.
+ *
+ * Non-throwing, with the sentinel distinction the AGENTS.md rule demands:
+ * - missing / unopenable / read error → `null`
+ * - zero-byte file → `''`
+ * so a caller can tell "nothing to read" from "couldn't read".
+ *
+ * The window starts at a BYTE offset, so when the file is larger than
+ * `maxBytes` the first line comes back partial (and can begin mid-multibyte
+ * character). Callers that split on newlines should drop that leading fragment.
+ *
+ * @param {string} path - File to read
+ * @param {number} maxBytes - Maximum trailing bytes to read
+ * @returns {Promise<string|null>} Trailing text, `''` for an empty file, or null on error
+ */
+export async function readFileTail(path, maxBytes) {
+ const info = await stat(path).catch(() => null);
+ if (!info) return null;
+ if (info.size === 0) return '';
+ const start = Math.max(0, info.size - maxBytes);
+ const length = info.size - start;
+ const handle = await open(path, 'r').catch(() => null);
+ if (!handle) return null;
+ try {
+ const buffer = Buffer.alloc(length);
+ // Honour bytesRead — the file can shrink between stat and read, or the OS
+ // can return a short read; decoding the whole `buffer` would append NULs.
+ // A read failure surfaces as null so callers keep the ''-vs-null contract.
+ const result = await handle.read(buffer, 0, length, start).catch(() => null);
+ if (result === null) return null;
+ return buffer.toString('utf8', 0, result.bytesRead);
+ } finally {
+ await handle.close().catch(() => {});
+ }
+}
+
+// Private sentinel for "the parse produced nothing usable". A unique Symbol, NOT
+// null/undefined — a file whose real contents parse to the caller's defaultValue
+// must stay distinguishable from a file that failed to parse at all, and any
+// in-band marker could legitimately BE the parsed value.
+const PARSE_FAILED = Symbol('json-parse-failed');
+
+/**
+ * True when a `<filePath>.*.bak` sibling is on disk — the signature of an
+ * `atomicWrite` backup swap that is mid-flight for THIS file, i.e. the only
+ * window in which the destination legitimately vanishes.
+ *
+ * Deliberately does NOT match `.tmp`: `atomicWrite` writes its temp file on
+ * EVERY write, including the first-ever create of a file that has no
+ * destination yet. Treating a `.tmp` sibling as evidence of a swap would turn a
+ * plain "not written yet" read into a retry that waits for the in-flight write
+ * and returns its brand-new contents — a different value than the read was
+ * entitled to, and a behavior change on POSIX-shaped callers. The `.bak` only
+ * exists between the swap's two renames.
+ *
+ * Non-throwing: an unreadable parent directory just means "no evidence of a
+ * swap". Only consulted on win32, and only after a read already failed with
+ * ENOENT, so the directory listing never lands on a POSIX read or a successful
+ * one. A `.bak` orphaned by a crash mid-swap costs the bounded retry budget
+ * (~50ms) on subsequent ENOENT reads of that path, never an incorrect answer.
+ *
+ * Matching is case-INSENSITIVE: NTFS/FAT are case-insensitive, so the reader's
+ * `filePath` casing need not match the casing the writer used to create the
+ * file (and therefore the casing `readdir` reports). A case-sensitive compare
+ * would miss the sibling and let the phantom-empty through.
+ *
+ * @param {string} filePath
+ * @returns {Promise<boolean>}
+ */
+async function hasSwapSibling(filePath) {
+ const entries = await readdir(dirname(filePath)).catch(() => null);
+ if (!entries) return false;
+ const prefix = `${basename(filePath).toLowerCase()}.`;
+ return entries.some((entry) => {
+ const name = entry.toLowerCase();
+ return name.startsWith(prefix) && name.endsWith('.bak');
+ });
+}
+
+/**
+ * `readFile(filePath, encoding)` with the Windows-only retries that keep a read
+ * racing `atomicWrite` from being mistaken for an empty/absent file (#4095).
+ *
+ * On POSIX this is a straight delegate — zero extra syscalls, zero delay.
+ *
+ * On win32 two transient failures are retried with a short backoff:
+ * - EPERM/EACCES/EBUSY — the destination is momentarily locked (AV scan, the
+ * writer's own open handle).
+ * - ENOENT, but ONLY when `hasSwapSibling` shows a backup swap is mid-flight.
+ * A file that was simply never written — or one whose first-ever write is
+ * still in its temp stage — stays a silent "nothing here yet": one failed
+ * read, no retry, no sleep.
+ *
+ * Rejects with the last error once the attempts are exhausted, so the caller's
+ * existing errno handling is unchanged.
+ *
+ * @param {string} filePath
+ * @param {string|null} [encoding='utf-8'] - Encoding (null for Buffer)
+ * @returns {Promise<string|Buffer>}
+ */
+async function readWithSwapRetry(filePath, encoding = 'utf-8') {
+ if (!isWindows()) return readFile(filePath, encoding);
+ for (let attempt = 0; ; attempt += 1) {
+ const outcome = await readFile(filePath, encoding).then((content) => ({ content }), (err) => ({ err }));
+ if (!outcome.err) {
+ if (attempt > 0) console.log(`⚠️ read succeeded after ${attempt} retry(s) — write swap in flight: ${basename(filePath)}`);
+ return outcome.content;
+ }
+ const last = attempt >= WIN_RETRY_ATTEMPTS - 1;
+ const retriable = WIN_READ_LOCK_CODES.includes(outcome.err.code)
+ || (outcome.err.code === 'ENOENT' && !last && await hasSwapSibling(filePath));
+ if (last || !retriable) throw outcome.err;
+ await sleep(WIN_RETRY_DELAY_MS);
+ }
+}
+
+/**
+ * Read a JSON file, reporting whether the read is TRUSTWORTHY rather than
+ * collapsing every failure into the default (the `readJSONFile` behavior below).
+ *
+ * The absent-vs-unreadable distinction (see AGENTS.md's "Sentinel + validate"):
+ *
+ * - ENOENT (never written) → `{ ok: true, value: defaultValue }` — a genuine
+ * empty. A caller counting records may trust this as a real zero.
+ * - any other read error → `{ ok: false, value: defaultValue }` — EACCES,
+ * EIO, EISDIR, a transient FS failure. We do NOT know the file is empty.
+ * - unparseable / truncated → `{ ok: false, value: defaultValue }` — corrupt
+ * bytes are not an empty collection.
+ * - parsed → `{ ok: true, value: parsed }`
+ *
+ * `value` is always populated so an `ok`-indifferent caller can ignore the flag and
+ * behave exactly like `readJSONFile` — which is how `readJSONFile` is implemented.
+ *
+ * Generalizes the local `{ ok, list }` precedent in
+ * `services/mediaAssetIndex/db.js#readVideoHistoryStrict`, written because "corrupt
+ * history" reading as "no videos exist" would have pruned every still-on-disk video
+ * from the index. Same bug class, shared helper (#2726).
+ *
+ * @param {string} filePath - Path to JSON file
+ * @param {*} defaultValue - Value returned whenever the file yields no parsed value
+ * @param {Object} options - Options
+ * @param {boolean} [options.allowArray=true] - Allow array JSON
+ * @param {boolean} [options.logError=true] - Log read/parse errors
+ * @returns {Promise<{ ok: boolean, value: * }>}
+ *
+ * @example
+ * const { ok, value } = await readJSONFileStrict('./sessions.json', { sessions: [] });
+ * if (!ok) throw new Error('sessions unreadable'); // never report a fake 0
+ */
+export async function readJSONFileStrict(filePath, defaultValue = null, { allowArray = true, logError = true } = {}) {
+ let content;
+ try {
+ content = await readWithSwapRetry(filePath);
+ } catch (err) {
+ // ENOENT = file doesn't exist → a trustworthy "nothing here yet", silently.
+ // On win32 an ENOENT that was really an `atomicWrite` swap window has
+ // already been retried above, so reaching here means genuinely absent.
+ if (err.code === 'ENOENT') {
+ return { ok: true, value: defaultValue };
+ }
+ if (logError) {
+ console.warn(`Failed to read file ${filePath}: ${err.message}`);
+ }
+ return { ok: false, value: defaultValue };
+ }
+
+ // Mirror safeJSONParse's noisy-output affordance BEFORE delegating: it keys the
+ // extraction off `Array.isArray(defaultValue)`, and the sentinel we pass as its
+ // fallback below is not an array — so an array-defaulted caller (e.g. pm2 jlist
+ // with ANSI codes) would silently lose the extraction if we left it to that call.
+ //
+ // Deliberately NOT via `extractJSONArray`: it returns a literal '[]' when the text
+ // holds no array at all, which would parse cleanly and report `ok: true` — forging
+ // a trustworthy empty out of unreadable bytes, the exact lie this function exists
+ // to prevent. Only a real find rewrites `text`; otherwise the parse below fails and
+ // the read is correctly reported as untrustworthy.
+ let text = content;
+ if (allowArray && Array.isArray(defaultValue) && text && !text.trim().startsWith('[')) {
+ const arrayStart = findJSONArrayStart(text);
+ if (arrayStart >= 0) text = text.slice(arrayStart);
+ }
+
+ const parsed = safeJSONParse(text, PARSE_FAILED, { allowArray, logError, context: filePath });
+ if (parsed === PARSE_FAILED) return { ok: false, value: defaultValue };
+
+ // An array `defaultValue` is the caller declaring "I expect a list" — every such
+ // caller in-tree goes straight to `.filter`/`.find`/`.findIndex` on the result. A
+ // parsed object root therefore isn't a usable read: swallowing callers must still
+ // get their list back (a hand-edited or legacy-shaped file used to degrade to `[]`
+ // here, via the manufactured-'[]' path above, and would now TypeError instead), and
+ // a strict caller must refuse to count a shape it cannot count.
+ if (allowArray && Array.isArray(defaultValue) && !Array.isArray(parsed)) {
+ if (logError) {
+ console.warn(`Expected a JSON array in ${filePath}, got ${parsed === null ? 'null' : typeof parsed}`);
+ }
+ return { ok: false, value: defaultValue };
+ }
+
+ return { ok: true, value: parsed };
+}
+
+/**
+ * Read a JSON file safely with validation and default fallback.
+ * Combines file reading with safe JSON parsing.
+ *
+ * By default this SWALLOWS every failure — a missing file, an unreadable one, and
+ * corrupt JSON all return `defaultValue`. That is the right shape for config-ish
+ * reads with a sensible fallback, and is the long-standing behavior of every
+ * existing caller.
+ *
+ * It is the WRONG shape when the value is counted or shown to the user, because a
+ * fake empty then reads as fact ("0 sessions logged" when the truth is "we could not
+ * read your sessions"). Those callers pass `{ strict: true }` to convert an
+ * untrustworthy read into a throw, or use `readJSONFileStrict` for the `{ ok, value }`
+ * pair directly.
+ *
+ * @param {string} filePath - Path to JSON file
+ * @param {*} defaultValue - Default value if file doesn't exist or is invalid
+ * @param {Object} options - Options
+ * @param {boolean} [options.allowArray=true] - Allow array JSON
+ * @param {boolean} [options.logError=true] - Log errors
+ * @param {boolean} [options.strict=false] - Throw instead of returning `defaultValue`
+ * when the file exists but could not be read or parsed. A genuinely absent file
+ * (ENOENT) still returns `defaultValue` — absent is a trustworthy empty.
+ * @returns {Promise<*>} Parsed JSON or default value
+ * @throws {Error} Only when `strict` and the file is present-but-unreadable/corrupt
+ *
+ * @example
+ * const config = await readJSONFile('./config.json', { port: 3000 });
+ * const items = await readJSONFile('./items.json', []);
+ * const real = await readJSONFile('./sessions.json', [], { strict: true }); // throws if corrupt
+ */
+export async function readJSONFile(filePath, defaultValue = null, { allowArray = true, logError = true, strict = false } = {}) {
+ const { ok, value } = await readJSONFileStrict(filePath, defaultValue, { allowArray, logError });
+ if (!ok && strict) {
+ throw new Error(`Unreadable JSON file: ${filePath}`);
+ }
+ return value;
+}
+
+/**
+ * Parse JSONL (JSON Lines) content safely.
+ * Handles empty lines, whitespace, and malformed lines gracefully.
+ *
+ * @param {string} content - JSONL content (newline-separated JSON objects)
+ * @param {Object} options - Options
+ * @param {boolean} [options.logErrors=false] - Log individual line parsing errors
+ * @param {string} [options.context=''] - Context for error logging
+ * @returns {Array} Array of parsed objects (invalid lines are skipped)
+ *
+ * @example
+ * const lines = safeJSONLParse('{"a":1}\n{"b":2}\n'); // [{ a: 1 }, { b: 2 }]
+ * const lines = safeJSONLParse('{"a":1}\ninvalid\n{"b":2}'); // [{ a: 1 }, { b: 2 }]
+ */
+export function safeJSONLParse(content, { logErrors = false, context = '' } = {}) {
+ if (!content || !content.trim()) return [];
+
+ // Split on CRLF or LF to handle both Windows and Unix line endings
+ const lines = content
+ .split(/\r?\n/)
+ .map(line => line.trim())
+ .filter(Boolean);
+ const results = [];
+
+ for (const line of lines) {
+ const parsed = safeJSONParse(line, null, { allowArray: false, logError: logErrors, context });
+ if (parsed !== null) {
+ results.push(parsed);
+ }
+ }
+
+ return results;
+}
+
+/**
+ * Read a JSONL file safely.
+ *
+ * @param {string} filePath - Path to JSONL file
+ * @param {Object} options - Options
+ * @param {boolean} [options.logErrors=false] - Log individual line parsing errors
+ * @returns {Promise<Array>} Array of parsed objects
+ *
+ * @example
+ * const entries = await readJSONLFile('./logs.jsonl');
+ */
+export async function readJSONLFile(filePath, { logErrors = false } = {}) {
+ let content;
+ try {
+ content = await readFile(filePath, 'utf-8');
+ } catch (err) {
+ // ENOENT = file doesn't exist, return empty array silently
+ if (err.code === 'ENOENT') {
+ return [];
+ }
+ // Log other I/O errors if requested
+ if (logErrors) {
+ console.warn(`Failed to read file ${filePath}: ${err.message}`);
+ }
+ return [];
+ }
+ return safeJSONLParse(content, { logErrors, context: filePath });
+}
+
+/**
+ * Append one JSON-serializable value to a JSON Lines file.
+ * Creates the parent directory as needed and writes exactly one trailing
+ * newline so readers can stream or split the file without special-casing the
+ * final record.
+ *
+ * @param {string} filePath - Path to JSONL file
+ * @param {*} value - JSON-serializable value to append
+ * @returns {Promise<void>}
+ */
+export async function appendJSONLine(filePath, value) {
+ const serialized = JSON.stringify(value);
+ if (serialized === undefined) {
+ throw new TypeError('appendJSONLine value must be JSON-serializable');
+ }
+ await ensureDir(dirname(filePath));
+ await appendFile(filePath, serialized + '\n');
+}
+
+/**
+ * Read JSON Lines with optional offset/limit slicing.
+ *
+ * @param {string} filePath - Path to JSONL file
+ * @param {Object} options - Options
+ * @param {number} [options.from=0] - Zero-based record offset
+ * @param {number} [options.limit] - Maximum number of records to return
+ * @param {boolean} [options.logErrors=false] - Log malformed JSONL lines
+ * @returns {Promise<Array>} Parsed records
+ */
+export async function readJSONLines(filePath, { from = 0, limit, logErrors = false } = {}) {
+ const entries = await readJSONLFile(filePath, { logErrors });
+ const start = Number.isFinite(from) && from > 0 ? Math.floor(from) : 0;
+ if (limit === undefined || limit === null) return entries.slice(start);
+ const count = Number.isFinite(limit) && limit >= 0 ? Math.floor(limit) : 0;
+ return entries.slice(start, start + count);
+}
+
+/**
+ * Replace a JSON Lines file with the supplied records.
+ * Intended for compaction/retention and delete/clear flows; hot append paths
+ * should use appendJSONLine().
+ *
+ * @param {string} filePath - Path to JSONL file
+ * @param {Array} values - JSON-serializable records
+ * @returns {Promise<void>}
+ */
+export async function writeJSONLines(filePath, values) {
+ if (!Array.isArray(values)) {
+ throw new TypeError('writeJSONLines values must be an array');
+ }
+ const lines = values.map((value) => {
+ const serialized = JSON.stringify(value);
+ if (serialized === undefined) {
+ throw new TypeError('writeJSONLines values must be JSON-serializable');
+ }
+ return serialized;
+ });
+ await atomicWrite(filePath, lines.length > 0 ? `${lines.join('\n')}\n` : '');
+}
+
+/**
+ * Time constants in milliseconds.
+ * Single source of truth — import these instead of declaring inline.
+ */
+/**
+ * Create a cached JSON file store with TTL-based invalidation.
+ * Eliminates the repeated cache/load/save/invalidate pattern across services.
+ *
+ * @param {string} filePath - Path to the JSON file
+ * @param {*} defaultValue - Default value when file doesn't exist
+ * @param {Object} options
+ * @param {number} [options.ttl=2000] - Cache TTL in milliseconds
+ * @param {string} [options.context=''] - Context label for error logging
+ * @returns {{ load, save, mutate, invalidateCache }}
+ *
+ * Writes are serialized through a single-tail `createFileWriteQueue` so two
+ * concurrent `save()` calls can't interleave their `atomicWrite` + cache
+ * assignment. For read-modify-write, use `mutate(fn)` — it runs the whole
+ * `load → fn → persist` cycle under the same tail, so a `load` always sees the
+ * previous cycle's committed result and one writer can't clobber the other
+ * (AGENTS.md: "serialize writes server-side… a single tail per shared file").
+ * A bare `load()` + `save()` pair does NOT get that guarantee; reach for
+ * `mutate()` whenever the new value depends on the current one.
+ */
+export function createCachedStore(filePath, defaultValue, { ttl = 2000, context = '' } = {}) {
+ let cache = null;
+ let cacheTimestamp = 0;
+ const dir = dirname(filePath);
+ const queueWrite = createFileWriteQueue();
+ // Safe clone for plain JSON defaults (structuredClone requires Node 17+)
+ const cloneDefault = () => JSON.parse(JSON.stringify(defaultValue));
+
+ const load = async () => {
+ const now = Date.now();
+ if (cache && (now - cacheTimestamp) < ttl) return cache;
+ await ensureDir(dir);
+ if (!existsSync(filePath)) {
+ cache = cloneDefault();
+ cacheTimestamp = now;
+ return cache;
+ }
+ const content = await readFile(filePath, 'utf-8');
+ cache = safeJSONParse(content, cloneDefault(), { context });
+ cacheTimestamp = now;
+ return cache;
+ };
+
+ // Persist `data` and refresh the cache — the shared write body. Callers reach
+ // it via the serialized `save`/`mutate`, never directly.
+ const persist = async (data) => {
+ await atomicWrite(filePath, data);
+ cache = data;
+ cacheTimestamp = Date.now();
+ return data;
+ };
+
+ const save = (data) => queueWrite(() => persist(data));
+
+ // Serialized read-modify-write: load the freshest state under the tail, apply
+ // `fn`, then persist. `fn` may mutate the loaded object in place and/or return
+ // the value to write (returning `undefined` persists the mutated input).
+ const mutate = (fn) => queueWrite(async () => {
+ const data = await load();
+ const result = await fn(data);
+ return persist(result === undefined ? data : result);
+ });
+
+ const invalidateCache = () => {
+ cache = null;
+ cacheTimestamp = 0;
+ };
+
+ return { load, save, mutate, invalidateCache };
+}
diff --git a/server/lib/mimeTypes.js b/server/lib/mimeTypes.js
new file mode 100644
index 0000000000..5acc629342
--- /dev/null
+++ b/server/lib/mimeTypes.js
@@ -0,0 +1,177 @@
+/** MIME tables, extension policy, and lightweight image format detection. */
+import { basename, extname } from 'path';
+
+/**
+ * MIME types that could execute scripts when served inline — force Content-Disposition: attachment
+ */
+export const RISKY_MIME_TYPES = new Set(['text/html', 'image/svg+xml', 'application/javascript', 'text/javascript', 'application/xml']);
+
+/**
+ * Full extension→MIME map covering documents, images, audio, video, code, and
+ * archives accepted by the generic uploads route. The attachments route uses a
+ * strict subset — see ATTACHMENT_ALLOWED_EXTENSIONS below.
+ *
+ * Exported so routes can serve the correct Content-Type header without keeping
+ * their own copy. Unknown extensions fall back to 'application/octet-stream'.
+ */
+export const EXTENSION_MIME_MAP = {
+ // Documents
+ '.txt': 'text/plain',
+ '.md': 'text/markdown',
+ '.json': 'application/json',
+ '.csv': 'text/csv',
+ '.xml': 'application/xml',
+ '.yaml': 'application/x-yaml',
+ '.yml': 'application/x-yaml',
+ '.pdf': 'application/pdf',
+ // Images
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.svg': 'image/svg+xml',
+ '.ico': 'image/x-icon',
+ '.bmp': 'image/bmp',
+ // Audio
+ '.mp3': 'audio/mpeg',
+ '.wav': 'audio/wav',
+ '.ogg': 'audio/ogg',
+ '.m4a': 'audio/mp4',
+ '.mid': 'audio/midi',
+ '.midi': 'audio/midi',
+ // Video
+ '.mp4': 'video/mp4',
+ '.webm': 'video/webm',
+ '.mov': 'video/quicktime',
+ // Code
+ '.js': 'text/javascript',
+ '.ts': 'text/typescript',
+ '.jsx': 'text/javascript',
+ '.tsx': 'text/typescript',
+ '.py': 'text/x-python',
+ '.sh': 'text/x-shellscript',
+ '.sql': 'text/x-sql',
+ '.html': 'text/html',
+ '.css': 'text/css',
+ '.go': 'text/x-go',
+ '.rs': 'text/x-rust',
+ '.java': 'text/x-java',
+ '.c': 'text/x-c',
+ '.cpp': 'text/x-c++',
+ '.h': 'text/x-c',
+ // Archives
+ '.zip': 'application/zip',
+ '.tar': 'application/x-tar',
+ '.gz': 'application/gzip',
+ '.7z': 'application/x-7z-compressed',
+ '.rar': 'application/vnd.rar',
+ // Other
+ '.log': 'text/plain',
+ '.env': 'text/plain',
+ '.conf': 'text/plain',
+ '.cfg': 'text/plain',
+ '.ini': 'text/plain',
+};
+
+/**
+ * Strict allowlist for file attachments (task attachments, CoS context files).
+ * A subset of EXTENSION_MIME_MAP — excludes audio, video, ICO, BMP, and
+ * miscellaneous text/config types that are not meaningful attachment types.
+ * The attachments route validates against this set; uploads uses the full map.
+ */
+export const ATTACHMENT_ALLOWED_EXTENSIONS = new Set([
+ '.txt', '.md', '.json', '.csv', '.xml', '.yaml', '.yml',
+ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.pdf',
+ '.js', '.ts', '.jsx', '.tsx', '.py', '.sh', '.sql', '.html', '.css',
+ '.zip', '.tar', '.gz',
+]);
+
+/**
+ * Curated allowlist for SongBook attachments (sheet-music PDFs, scans, MIDI,
+ * practice audio). Deliberately NOT a superset of ATTACHMENT_ALLOWED_EXTENSIONS
+ * — code/archive/config types make no sense on a song record, while MIDI and
+ * audio (which the CoS attachment set excludes) are core sheet-music formats.
+ */
+export const SONGBOOK_ATTACHMENT_EXTENSIONS = new Set([
+ '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg',
+ '.txt', '.md',
+ '.mid', '.midi', '.mp3', '.wav', '.m4a', '.ogg',
+]);
+
+/**
+ * Look up the MIME type for a file extension (including the leading dot, e.g.
+ * ".png"). Returns 'application/octet-stream' for unknown extensions.
+ *
+ * @param {string} ext - Lowercased extension with leading dot (e.g. '.png')
+ * @returns {string} MIME type string
+ */
+export function getMimeType(ext) {
+ return EXTENSION_MIME_MAP[ext] || 'application/octet-stream';
+}
+
+/**
+ * Magic-byte sniff of an image buffer. The client-supplied extension / MIME is
+ * not trustworthy, so when we persist uploaded image bytes (e.g. an author
+ * headshot routed into the gallery) we derive the real format from the leading
+ * bytes. Recognises PNG, JPEG, WebP, and GIF.
+ *
+ * @param {Buffer} buf - Raw decoded image bytes
+ * @returns {{ format: 'png'|'jpeg'|'webp'|'gif', ext: string, mime: string } | null}
+ * The detected format with its canonical extension + MIME, or null when the
+ * bytes don't match a known image signature.
+ */
+export function detectImageFormat(buf) {
+ if (!Buffer.isBuffer(buf)) return null;
+ if (buf.length >= 8 &&
+ buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
+ buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) {
+ return { format: 'png', ext: '.png', mime: 'image/png' };
+ }
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
+ return { format: 'jpeg', ext: '.jpg', mime: 'image/jpeg' };
+ }
+ if (buf.length >= 12 &&
+ buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
+ buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
+ return { format: 'webp', ext: '.webp', mime: 'image/webp' };
+ }
+ if (buf.length >= 6 &&
+ buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38 &&
+ (buf[4] === 0x37 || buf[4] === 0x39) && buf[5] === 0x61) {
+ return { format: 'gif', ext: '.gif', mime: 'image/gif' };
+ }
+ return null;
+}
+
+/**
+ * Get a file's extension, normalised to lowercase with a leading dot.
+ * Returns null when the filename has no extension.
+ *
+ * @param {string} filename
+ * @returns {string|null}
+ */
+export function getFileExtension(filename) {
+ return extname(filename).toLowerCase() || null;
+}
+
+/**
+ * Sanitize a user-supplied filename to prevent path traversal and filesystem
+ * surprises. Strips any directory component, replaces characters that are not
+ * alphanumeric / dot / hyphen / underscore with `_`, and ensures the name
+ * does not start with a dot (hidden-file prevention).
+ *
+ * Identical logic was copy-pasted across uploads.js, attachments.js, and
+ * screenshots.js — consolidated here so fixes propagate to all callers.
+ *
+ * @param {string} filename - User-provided filename (possibly with path components)
+ * @returns {string} Safe basename
+ */
+export function sanitizeFilename(filename) {
+ const base = basename(filename);
+ const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');
+ if (sanitized.startsWith('.')) {
+ return '_' + sanitized.slice(1);
+ }
+ return sanitized;
+}
diff --git a/server/lib/pathSafety.js b/server/lib/pathSafety.js
new file mode 100644
index 0000000000..8e7304d054
--- /dev/null
+++ b/server/lib/pathSafety.js
@@ -0,0 +1,373 @@
+/** Filename validation, containment checks, and approved asset resolution. */
+import { existsSync, statSync } from 'fs';
+import { basename, join, resolve as resolvePath, sep as PATH_SEP } from 'path';
+import { ServerError } from './errorHandler.js';
+import { PATHS } from './paths.js';
+
+/**
+ * Validate a user-supplied filename is a safe basename with one of the
+ * allowed extensions — refuses path-traversal, null bytes, separators, and
+ * exact `.` / `..`. Throws a 400 ServerError with code VALIDATION_ERROR
+ * so calling routes don't have to repeat the check.
+ *
+ * Consolidates the two near-identical assertions that used to live in
+ * `services/loras.js#assertSafeLoraFilename` (`.safetensors` only) and
+ * `services/imageGen/local.js#assertGalleryFilename` (`.png` only).
+ *
+ * Substring `..` is intentionally allowed (e.g. `foo..bar.png` is fine);
+ * only the exact-string traversal cases are rejected. Path separators (`/`
+ * and `\`) are rejected on every platform — the same input gets posted
+ * from Windows clients too.
+ *
+ * @param {string} filename
+ * @param {{ extensions: string[], subject?: string, requiredMessage?: string }} opts
+ * - `extensions`: list of allowed extensions including the leading dot
+ * (`['.png']`, `['.safetensors']`, etc.). Case-insensitive match. Each
+ * entry MUST be a non-empty string starting with `.` — otherwise a bare
+ * suffix like `'png'` would also match `'not-an-imagepng'` and weaken
+ * the validation, so we treat that as a programmer error and throw.
+ * - `subject`: optional noun for the error message ("LoRA filename" →
+ * "Invalid LoRA filename"). Defaults to "filename".
+ * - `requiredMessage`: optional exact message used when `filename` is
+ * missing/empty — preserves backward-compat for wrappers that used to
+ * throw a specific phrase. The gallery wrapper passes `'Invalid filename'`
+ * (its pre-refactor implementation threw that for every failure, including
+ * missing-input); the LoRA wrapper passes `'Filename required'` to match
+ * its historical wording. When omitted, the message is derived from
+ * `subject` (e.g. `'Filename required'` / `'LoRA filename required'`).
+ */
+export function assertSafeFilename(filename, { extensions, subject = 'filename', requiredMessage } = {}) {
+ if (!Array.isArray(extensions) || extensions.length === 0) {
+ throw new Error('assertSafeFilename: extensions allowlist is required');
+ }
+ for (const ext of extensions) {
+ if (typeof ext !== 'string' || ext.length < 2 || !ext.startsWith('.')) {
+ throw new Error(`assertSafeFilename: each extension must be a non-empty string starting with "." (got ${JSON.stringify(ext)})`);
+ }
+ }
+ const subjectText = subject || 'filename';
+ if (!filename || typeof filename !== 'string') {
+ const Subject = `${subjectText[0].toUpperCase()}${subjectText.slice(1)}`;
+ const message = typeof requiredMessage === 'string' && requiredMessage.length > 0
+ ? requiredMessage
+ : `${Subject} required`;
+ throw new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ // Null bytes terminate C strings — some POSIX syscalls treat the prefix
+ // as a separate path. Reject up front so it can't reach the FS layer.
+ if (filename.includes('\0')) {
+ throw new ServerError(`Invalid ${subjectText}`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (!isSafeFilename(filename, extensions)) {
+ throw new ServerError(`Invalid ${subjectText}`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+}
+
+/**
+ * `assertSafeFilename`'s non-throwing twin: the same rule as a predicate, for
+ * callers that must report a bad name as *data* rather than fail the request —
+ * e.g. a read-only preflight that names one corrupt record as a blocked row
+ * instead of 400-ing the whole sweep. Both share this implementation so the
+ * thrown gate and the reported verdict can never disagree.
+ *
+ * Rejects: empty/non-string, null bytes (they terminate C strings, so some
+ * POSIX syscalls treat the prefix as a separate path), `.`/`..`, any path
+ * separator, anything that isn't already a pure basename, and any extension
+ * outside `extensions`. The basename equality check is kept alongside the
+ * separator check so e.g. `subdir\foo.png` is rejected on both counts.
+ *
+ * `extensions` must be dot-prefixed, and unlike `assertSafeFilename` this does
+ * not police that for you — a bare suffix like `png` would also match
+ * `not-an-imagepng`. Pass a module constant, never a caller-supplied list.
+ */
+export function isSafeFilename(filename, extensions) {
+ if (!isTopLevelEntryName(filename)) return false;
+ const lower = filename.toLowerCase();
+ return extensions.some((ext) => lower.endsWith(String(ext).toLowerCase()));
+}
+
+/**
+ * `isSafeFilename`'s traversal half, without the extension gate: true when
+ * `name` addresses exactly one entry directly inside some directory.
+ *
+ * For callers that legitimately cannot allowlist extensions — an arbitrary
+ * user asset, or a directory entry — but must still refuse traversal. Naming
+ * a single entry is what makes a subsequent `join(dir, name)` safe *in the
+ * filesystem sense* and not just lexically: with no separator there is no
+ * intermediate component left for a symlink to redirect, which a
+ * `resolve`/`relative` containment check cannot see. The Data Manager's
+ * per-item purge (`purgeCategory`) is the reference caller.
+ *
+ * `isSafeFilename` is layered on top of this, so the two can never disagree
+ * about what "a single entry" means.
+ */
+export function isTopLevelEntryName(name) {
+ if (!name || typeof name !== 'string') return false;
+ if (name.includes('\0')) return false;
+ if (name === '.' || name === '..') return false;
+ if (name.includes('/') || name.includes('\\')) return false;
+ return basename(name) === name;
+}
+
+/**
+ * True when `candidatePath` resolves to a location strictly inside `dir`.
+ *
+ * Uses the same anchored-prefix containment idiom as `makePathResolver`
+ * (`resolvePath(dir) + PATH_SEP`): appending the platform separator to the
+ * resolved root means a sibling directory whose name merely *starts with* the
+ * root (e.g. `/data/uploads-evil` vs `/data/uploads`) can't slip past a bare
+ * `startsWith(root)` check. This is stricter than the `resolvedPath.startsWith(DIR)`
+ * guard the upload/attachment/screenshot routes used before. The root itself is
+ * NOT reported as "inside" (there's no trailing separator on the bare root),
+ * which is the desired behavior for file-containment checks.
+ *
+ * @param {string} dir - the containing directory (absolute or relative)
+ * @param {string} candidatePath - the path to test
+ * @returns {boolean}
+ */
+export function isPathInsideDir(dir, candidatePath) {
+ if (typeof dir !== 'string' || typeof candidatePath !== 'string' || !dir || !candidatePath) {
+ return false;
+ }
+ const rootPrefix = resolvePath(dir) + PATH_SEP;
+ return resolvePath(candidatePath).startsWith(rootPrefix);
+}
+
+/**
+ * Build a single-root path resolver that returns a function with the same
+ * signature as `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset`.
+ *
+ * Defense in depth (applied on every call):
+ * 1. `basename()` strips dirs (so `../../etc/passwd` → `passwd`).
+ * 2. Reject `.`/`..`/empty basenames outright.
+ * 3. `resolve` + `startsWith(rootPrefix)` so unicode tricks can't escape.
+ * 4. Optional extension allow-list (case-insensitive) before any FS syscall.
+ * 5. When `mustExist`, `statSync({ throwIfNoEntry: false }).isFile()` rejects
+ * directories (the root itself would otherwise pass an existsSync check
+ * and flow into ffmpeg / image-gen as an "image path" where it'd fail in
+ * confusing ways). Note: `statSync` follows symlinks, so a symlink under
+ * the root pointing to a regular file outside still passes. PortOS is
+ * single-user (see AGENTS.md "Security Model") so we accept that — for
+ * symlink rejection, swap to `lstatSync`.
+ *
+ * Pass `{ mustExist: false }` at call time for code paths that intentionally
+ * skip the existence check (e.g. when the path is resolved at request time
+ * but read later — TOCTOU between resolve and use isn't worth the extra
+ * syscall, and the downstream renderer surfaces a clear error if the file
+ * vanished).
+ *
+ * @param {() => string} getRoot - Thunk returning the absolute directory.
+ * A thunk (not a literal) so tests that mutate `PATHS.x` at mock-eval
+ * time still steer the resolver — the value is captured on first call
+ * and cached thereafter (recomputed only if the thunk later returns a
+ * different value, which production code never does).
+ * @param {object} [opts]
+ * @param {string[]} [opts.extensions] - allowed extensions WITHOUT the leading
+ * dot (`['png', 'jpg', 'jpeg', 'webp']`). When omitted, all extensions are
+ * accepted (matches the legacy gallery/refs behavior — extension checks
+ * happen elsewhere on those paths).
+ * @param {boolean} [opts.cache=false] - Memoize successful resolutions. Only
+ * safe for shipped/stable assets (templates) where the basename → path
+ * binding is stable for the process lifetime; never enable for user-mutable
+ * dirs (gallery, refs) since deletions would be masked.
+ * @returns {(name: string, opts?: { mustExist?: boolean }) => string|null}
+ */
+export function makePathResolver(getRoot, { extensions, cache = false } = {}) {
+ if (typeof getRoot !== 'function') {
+ throw new Error('makePathResolver: getRoot must be a function returning the root dir');
+ }
+ // Escape regex metacharacters in each extension before interpolating —
+ // current callers pass plain alphanumeric tokens (png/jpg/jpeg/webp), but
+ // the exported factory shouldn't behave incorrectly if a future caller
+ // passes an extension containing `.`/`+`/etc.
+ const extRegex = Array.isArray(extensions) && extensions.length > 0
+ ? new RegExp(`\\.(${extensions
+ .map((e) => String(e).replace(/^\./, '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+ .join('|')})$`, 'i')
+ : null;
+ const memo = cache ? new Map() : null;
+ // Resolved-root cache so the hot path doesn't re-run `resolvePath(root) +
+ // PATH_SEP` per call. Recomputes only when `getRoot()` returns a different
+ // value — picks up test-time `PATHS.x = ...` mutation on first call, then
+ // stays warm for the rest of the process.
+ let _root = null;
+ let _rootAbsPrefix = null;
+
+ return (name, { mustExist = true } = {}) => {
+ if (typeof name !== 'string' || !name) return null;
+ const safe = basename(name);
+ if (!safe || safe === '.' || safe === '..') return null;
+ if (extRegex && !extRegex.test(safe)) return null;
+ // Refresh the root cache BEFORE the memo lookup so a getRoot() that
+ // suddenly returns a new value (e.g. a test re-mocks `PATHS.x` mid-run)
+ // invalidates the memo too — otherwise the old root's cached
+ // resolutions would shadow the new root forever.
+ const root = getRoot();
+ if (root !== _root) {
+ _root = root;
+ _rootAbsPrefix = resolvePath(root) + PATH_SEP;
+ if (memo) memo.clear();
+ }
+ const cacheKey = memo ? (mustExist ? `must:${safe}` : `nostat:${safe}`) : null;
+ if (memo && memo.has(cacheKey)) return memo.get(cacheKey);
+ const localPath = resolvePath(join(root, safe));
+ if (!localPath.startsWith(_rootAbsPrefix)) return null;
+ if (!mustExist) {
+ if (memo) memo.set(cacheKey, localPath);
+ return localPath;
+ }
+ // throwIfNoEntry:false swallows ENOENT but not EACCES / transient I/O —
+ // treat those as "not a valid reference" too rather than bubbling a 500
+ // out of the route layer.
+ let resolved = null;
+ try {
+ const stat = statSync(localPath, { throwIfNoEntry: false });
+ resolved = stat?.isFile() ? localPath : null;
+ } catch { /* falls through to null */ }
+ // Only cache successful resolutions — a missing-then-installed asset
+ // should pick up on the next call (e.g. setup-data.js racing a render).
+ if (memo && resolved) memo.set(cacheKey, resolved);
+ return resolved;
+ };
+}
+
+/**
+ * Resolve a user-supplied gallery image filename to an absolute path under
+ * `PATHS.images`. Returns `null` on any failure so callers can decide whether
+ * to throw, log-and-skip, or substitute a fallback. See `makePathResolver`
+ * for the defense-in-depth checks. Late-binds via a thunk so tests that
+ * mutate `PATHS.images` at mock-eval time still steer the resolver.
+ */
+export const resolveGalleryImage = makePathResolver(() => PATHS.images);
+
+/**
+ * Resolve a user-supplied reference-image filename to an absolute path under
+ * `PATHS.imageRefs`. Multi-reference uploads land in a sibling dir to keep
+ * them out of the gallery enumeration; same defense-in-depth as the gallery
+ * resolver but anchored at the refs root.
+ */
+export const resolveImageRef = makePathResolver(() => PATHS.imageRefs);
+
+/**
+ * Resolve an Image Cleaner temp init/result filename to an absolute path under
+ * `PATHS.imageCleanTmp` (issue #2264). The GPU FLUX round-trip stages the
+ * sync-cleaned init bytes here and renders the result back here, so the runner
+ * must accept this root as a valid `initImagePath` source. Same defense-in-depth
+ * as the gallery/refs resolvers, anchored at the temp root.
+ */
+export const resolveImageCleanTmp = makePathResolver(() => PATHS.imageCleanTmp);
+
+/**
+ * Resolve a peer-uploaded conditioning image staged under
+ * `PATHS.federatedMediaInbox` to an absolute path. The provider maps an
+ * accepted asset id onto one of these before handing the job to the local
+ * generator, so the runner must accept this root as a valid `initImagePath` /
+ * reference / keyframe source.
+ *
+ * Extension-restricted at the resolver rather than only at upload: the upload
+ * endpoint already MIME-allowlists, but this is the boundary the *runner*
+ * crosses, and a second check here means a hand-written file in the inbox still
+ * cannot become an arbitrary path argument to the generator.
+ */
+export const resolveFederatedMediaAsset = makePathResolver(() => PATHS.federatedMediaInbox, {
+ extensions: ['png', 'jpg', 'jpeg', 'webp'],
+});
+
+/**
+ * Resolve a sprite reference asset used as an image-gen init image (issue
+ * #2896 — anchors i2i from the locked main reference; uploaded design
+ * references). `data/sprites/` is a server-managed NESTED tree, so unlike
+ * the single-level basename resolvers above this accepts only an absolute
+ * path already inside the sprites root (no basename fallback — a bare
+ * filename is ambiguous across records) and validates containment.
+ */
+export function resolveSpriteImageInput(rawPath) {
+ if (typeof rawPath !== 'string' || !rawPath) return null;
+ const resolved = resolvePath(rawPath);
+ return isPathInsideDir(PATHS.sprites, resolved) ? resolved : null;
+}
+
+/**
+ * Resolve a shipped visual template filename (e.g. character reference-sheet
+ * layout PNG) to an absolute path under `PATHS.visualTemplates`. Caches
+ * successful resolutions because the template assets are shipped and stable
+ * for the lifetime of the process — keeps reference-sheet rendering off the
+ * statSync hot path.
+ */
+export const resolveTemplateAsset = makePathResolver(() => PATHS.visualTemplates, {
+ extensions: ['png', 'jpg', 'jpeg', 'webp'],
+ cache: true,
+});
+
+/**
+ * Resolve a user-supplied screenshot filename to an absolute path under
+ * `PATHS.screenshots`. Used by the vision-test endpoint, whose `imagePath`
+ * comes straight from `req.body` — basenaming the input (and rejecting any
+ * non-image extension or missing file) stops `../` traversal and absolute-path
+ * escapes from reading arbitrary files off disk and forwarding their contents
+ * to an external vision provider. Returns `null` on any failure so the caller
+ * can surface a clean error. See `makePathResolver` for the defense-in-depth
+ * checks. Late-binds via a thunk so tests that mutate `PATHS.screenshots` still
+ * steer the resolver.
+ */
+export const resolveScreenshot = makePathResolver(() => PATHS.screenshots, {
+ extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'],
+});
+
+/**
+ * Resolve any user-supplied image input (init image OR multi-reference image)
+ * to an absolute path under one of PortOS's approved image roots — the
+ * gallery (`PATHS.images`), the multi-ref upload dir (`PATHS.imageRefs`),
+ * or the shipped visual-template dir (`PATHS.visualTemplates`). Used by the
+ * image-gen runner to re-validate paths that originated from internal
+ * features (gallery picks, reference-sheet renders) which may legitimately
+ * cross dir boundaries.
+ *
+ * Accepts both basename input (`"foo.png"`) and already-resolved absolute
+ * paths (the local image-gen runner re-validates the same input on every
+ * call so we need to accept both shapes).
+ *
+ * @param {string} rawPath - basename or absolute path
+ * @returns {string|null} validated absolute path, or null
+ */
+// Pairs of (PATHS-key, resolver). Read PATHS at CALL time so tests that
+// mutate `PATHS.x` at mock-eval time still steer the prefix dispatch — a
+// module-load snapshot would freeze the pre-mock paths.
+const IMAGE_INPUT_RESOLVERS = [
+ ['images', resolveGalleryImage],
+ ['imageRefs', resolveImageRef],
+ ['visualTemplates', resolveTemplateAsset],
+ // Image Cleaner temp init images (issue #2264) — the GPU FLUX round-trip
+ // stages sync-cleaned bytes here as the img2img init.
+ ['imageCleanTmp', resolveImageCleanTmp],
+ // Peer-uploaded conditioning images (#4348) — an allowlisted peer's init /
+ // reference / keyframe bytes, staged for the one federated render they were
+ // uploaded for.
+ ['federatedMediaInbox', resolveFederatedMediaAsset],
+ // Sprite reference assets (issue #2896) — the locked main reference /
+ // uploaded design reference as the anchors' i2i init. Absolute-only
+ // (returns null on basename input, so the fall-through loop skips it).
+ ['sprites', resolveSpriteImageInput],
+];
+
+export function resolveImageInputPath(rawPath) {
+ if (typeof rawPath !== 'string' || !rawPath) return null;
+ // For ABSOLUTE inputs, dispatch by prefix. The single-root resolvers
+ // basename their input for defense-in-depth, so trying them in order on an
+ // absolute path can silently redirect a `/data/templates/foo.png` input
+ // to `/data/images/foo.png` whenever a same-named file lives in the gallery.
+ // Validate against the matching root only.
+ const resolvedInput = resolvePath(rawPath);
+ for (const [key, resolver] of IMAGE_INPUT_RESOLVERS) {
+ const rootPrefix = resolvePath(PATHS[key]) + PATH_SEP;
+ if (resolvedInput.startsWith(rootPrefix)) return resolver(rawPath);
+ }
+ // For basename / relative input (no matching prefix), fall through the
+ // resolvers in order. First match wins; basename collisions across roots
+ // are accepted as ambiguous and resolve to the first defined root.
+ for (const [, resolver] of IMAGE_INPUT_RESOLVERS) {
+ const candidate = resolver(rawPath);
+ if (candidate) return candidate;
+ }
+ return null;
+}
diff --git a/server/lib/paths.js b/server/lib/paths.js
new file mode 100644
index 0000000000..198216f698
--- /dev/null
+++ b/server/lib/paths.js
@@ -0,0 +1,165 @@
+/** Canonical install/source roots and path construction helpers. */
+import { homedir } from 'os';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { resolveInstallRoot } from './dataRoot.js';
+
+const __lib_filename = fileURLToPath(import.meta.url);
+const __lib_dirname = dirname(__lib_filename);
+
+// The executing checkout's root (where THIS file physically lives). Code/source
+// paths — the repo root for git ops, `lib/slashdo` — must stay anchored here so
+// they always point at the checkout that loaded the code.
+const CODE_ROOT = join(__lib_dirname, '../..');
+
+// The install root that holds the runtime `data/` tree. Prefer an explicit
+// PORTOS_DATA_ROOT env var over the executing-file location so a process booted
+// from inside a CoS agent git worktree resolves `data/` to the real install
+// instead of the worktree's empty checkout (#1947). Falls back to CODE_ROOT
+// when the env var is unset (the two coincide for a normal install). Only
+// `data/*` paths follow this — source/git paths stay on CODE_ROOT.
+const INSTALL_ROOT = resolveInstallRoot(CODE_ROOT);
+
+/**
+ * Base directories relative to project root
+ */
+export const PATHS = {
+ root: CODE_ROOT,
+ // The data-bearing install root (parent of `data/`). Equals `root` for a
+ // normal install; diverges only when PORTOS_DATA_ROOT pins a different tree
+ // (worktree boot, #1947). Use this — not `root` — for anything anchored to
+ // the `data/` tree but living one level above it (e.g. the migration ledger
+ // `data/migrations.applied.json`), so its reader agrees with where boot wrote it.
+ installRoot: INSTALL_ROOT,
+ data: join(INSTALL_ROOT, 'data'),
+ cos: join(INSTALL_ROOT, 'data/cos'),
+ brain: join(INSTALL_ROOT, 'data/brain'),
+ digitalTwin: join(INSTALL_ROOT, 'data/digital-twin'),
+ health: join(INSTALL_ROOT, 'data/health'),
+ runs: join(INSTALL_ROOT, 'data/runs'),
+ memory: join(INSTALL_ROOT, 'data/cos/memory'),
+ cosAgents: join(INSTALL_ROOT, 'data/cos/agents'), // CoS sub-agents
+ scripts: join(INSTALL_ROOT, 'data/cos/scripts'),
+ reports: join(INSTALL_ROOT, 'data/cos/reports'),
+ // AI Agent Personalities data
+ agentPersonalities: join(INSTALL_ROOT, 'data/agents'),
+ meatspace: join(INSTALL_ROOT, 'data/meatspace'),
+ calendar: join(INSTALL_ROOT, 'data/calendar'),
+ messages: join(INSTALL_ROOT, 'data/messages'),
+ screenshots: join(INSTALL_ROOT, 'data/screenshots'),
+ uploads: join(INSTALL_ROOT, 'data/uploads'),
+ cosAttachments: join(INSTALL_ROOT, 'data/cos/attachments'),
+ worktrees: join(INSTALL_ROOT, 'data/cos/worktrees'),
+ repos: join(INSTALL_ROOT, 'data/repos'),
+ browserProfile: join(INSTALL_ROOT, 'data/browser-profile'),
+ browserDownloads: join(homedir(), 'Downloads'),
+ digests: join(INSTALL_ROOT, 'data/cos/digests'),
+ promptSkills: join(INSTALL_ROOT, 'data/prompts/skills'),
+ promptSkillsJobs: join(INSTALL_ROOT, 'data/prompts/skills/jobs'),
+ decisions: join(INSTALL_ROOT, 'data/cos/decisions'),
+ telegram: join(INSTALL_ROOT, 'data/telegram'),
+ templates: join(INSTALL_ROOT, 'data/prompts/templates'),
+ // Visual template assets (e.g. the character reference-sheet layout PNG used
+ // as the init-image anchor by the universe-builder character sheet renderer).
+ // Distinct from `templates` above, which is the legacy prompt-template dir.
+ // Files here are shipped via data.reference/templates/ on first install.
+ visualTemplates: join(INSTALL_ROOT, 'data/templates'),
+ settings: join(INSTALL_ROOT, 'data/settings'),
+ missions: join(INSTALL_ROOT, 'data/cos/missions'),
+ tools: join(INSTALL_ROOT, 'data/tools'),
+ images: join(INSTALL_ROOT, 'data/images'),
+ // Uploaded multi-reference inputs for FLUX.2 multi-ref edits. Sibling of
+ // `images/` rather than a subdir so the gallery's flat `.png` enumeration
+ // never surfaces them, and so a future per-render cleanup pass can drop
+ // the whole dir without touching the gallery.
+ imageRefs: join(INSTALL_ROOT, 'data/image-refs'),
+ // Ephemeral working dir for the Image Cleaner's GPU FLUX round-trip (issue
+ // #2264). The sync-cleaned init bytes and the finished render land here as
+ // `<jobId>-init.png` / `<jobId>-result.png` so the cleaner can render WITHOUT
+ // writing a gallery file + sidecar (the default is not to keep the result).
+ // A sibling of `images/` — never surfaced by the gallery's flat `.png`
+ // enumeration; swept by imageCleanTmpGc.js on an age gate. Not federated.
+ imageCleanTmp: join(INSTALL_ROOT, 'data/image-clean-tmp'),
+ // PROVIDER-side staging for conditioning images an allowlisted peer uploaded
+ // ahead of a federated render (ADR
+ // docs/decisions/2026-08-22-federated-media-input-assets.md rule 1). Files are
+ // named `<callerHash>-<sha256>.<ext>` and swept on a TTL.
+ //
+ // Deliberately its own root rather than a corner of `images/` or `uploads/`:
+ // these are ANOTHER machine's bytes, held briefly to run one job. Under
+ // `images/` the gallery would enumerate them and the sync layer would federate
+ // them onward (the failure this repo already hit once with temp files in
+ // data/images). Excluded from backups for the same reason — restoring a peer's
+ // half-hour-old init image is worth nothing.
+ federatedMediaInbox: join(INSTALL_ROOT, 'data/federated-media-inbox'),
+ loras: join(INSTALL_ROOT, 'data/loras'),
+ // Per-character LoRA training datasets (collectionStore layout:
+ // lora-datasets/<id>/index.json + lora-datasets/<id>/images/*.png).
+ // Machine-local like `loras/` — datasets never federate.
+ loraDatasets: join(INSTALL_ROOT, 'data/lora-datasets'),
+ // LoRA training run artifacts (checkpoints/samples/cache per run). Run
+ // RECORDS live in Postgres (lora_training_runs); only artifacts live here.
+ trainingRuns: join(INSTALL_ROOT, 'data/training-runs'),
+ videos: join(INSTALL_ROOT, 'data/videos'),
+ videoThumbnails: join(INSTALL_ROOT, 'data/video-thumbnails'),
+ // Sprite Manager (issue #2895): per-record asset trees
+ // (sprites/<id>/{reference,walk,runs,runtime,atlas}/...). Records live in
+ // Postgres (sprite_records); only binary artifacts + manifests live here.
+ sprites: join(INSTALL_ROOT, 'data/sprites'),
+ // Image-to-3D (issue #2952): per-record GLB meshes rendered locally by a
+ // target (TRELLIS.2 today), stored as image-to-3d/<id>/model.glb. Records
+ // live in Postgres (image_to_3d_models); only the binary GLB lives here.
+ imageTo3d: join(INSTALL_ROOT, 'data/image-to-3d'),
+ // Persisted audio renders (voice-over lines). Kept distinct from
+ // the in-memory voice-agent synthesis path in services/voice/ — that path
+ // streams WAV over Socket.IO without ever touching disk.
+ audio: join(INSTALL_ROOT, 'data/audio'),
+ // Uploaded + (eventually) generated background music tracks. Separate from
+ // `audio/` so the user can browse + reuse a track across issues without
+ // walking through the VO-line filenames.
+ music: join(INSTALL_ROOT, 'data/music'),
+ // Extracted assets from third-party imports (ChatGPT export images/audio/
+ // PDFs). Served read-only at `/data/brain-imports/...` so the Memory
+ // conversation viewer can render inline `![](url)` images and asset links.
+ // Flat per-source dir keyed by the asset's globally-unique id, so the same
+ // asset referenced from multiple conversations is stored once. The transcript
+ // archive JSON lives one level up (data/brain/imports/<source>/) and is NOT
+ // served — only this assets subtree is.
+ brainImportAssets: join(INSTALL_ROOT, 'data/brain/imports/assets'),
+ // SongBook attachment BYTES (PDF sheet music, images, MIDI). Machine-local —
+ // only the metadata syncs inside the brain `songs` record; peers lacking a
+ // file render "not on this machine". Covered by backup via data/brain/.
+ brainSongbook: join(INSTALL_ROOT, 'data/brain/songbook'),
+ slashdo: join(CODE_ROOT, 'lib/slashdo'),
+ // Fully-resolved slashdo command bodies written for CoS agents to READ on
+ // demand instead of receiving them pasted into the prompt (issue #3110).
+ // Derived cache, never authored: regenerated on first use each process, safe
+ // to delete. Anchored to INSTALL_ROOT (not CODE_ROOT) because the pointer
+ // handed to an agent must name a path that exists on the running install.
+ slashdoResolved: join(INSTALL_ROOT, 'data/cos/slashdo-resolved')
+};
+
+/**
+ * Get a path relative to the data directory.
+ *
+ * @param {...string} segments - Path segments to join
+ * @returns {string} Full path under data directory
+ *
+ * @example
+ * const filePath = dataPath('cos', 'state.json');
+ * // Returns: /path/to/project/data/cos/state.json
+ */
+export function dataPath(...segments) {
+ return join(PATHS.data, ...segments);
+}
+
+// `path.join(homedir(), '/.foo')` discards the homedir prefix because of
+// the leading slash, so strip the leading `~/` (or `~\` on Windows) before
+// joining. Only expands a leading `~` — embedded `~` chars in path segments
+// (e.g. `iCloud~md~obsidian`) are preserved.
+export function expandHome(p) {
+ if (typeof p !== 'string' || !p) return p;
+ if (p === '~') return homedir();
+ if (p.startsWith('~/') || p.startsWith('~\\')) return join(homedir(), p.slice(2));
+ return p;
+}
diff --git a/server/lib/uploads.js b/server/lib/uploads.js
new file mode 100644
index 0000000000..6dd3480d03
--- /dev/null
+++ b/server/lib/uploads.js
@@ -0,0 +1,193 @@
+/** Upload staging, validation, persistence, and local-file serving helpers. */
+import { copyFile, readFile, stat, unlink, writeFile } from 'fs/promises';
+import { randomUUID } from 'crypto';
+import { join, resolve as resolvePath } from 'path';
+import { ServerError } from './errorHandler.js';
+import { atomicWrite, ensureDir, pathExists } from './fileCore.js';
+import { detectImageFormat, getFileExtension, getMimeType, RISKY_MIME_TYPES, sanitizeFilename } from './mimeTypes.js';
+import { PATHS } from './paths.js';
+import { assertSafeFilename, isPathInsideDir } from './pathSafety.js';
+
+/**
+ * Move a temp file into `destDir` and return the persisted filename, using the
+ * `/api/uploads` route's naming (`<uuid8>-<sanitized-name>`) so a
+ * server-produced file is served and referenced exactly like a user upload.
+ *
+ * copyFile + unlink instead of rename — the source usually lives in
+ * `os.tmpdir()`, which may sit on a different filesystem (rename across devices
+ * throws EXDEV on Linux); copy works regardless. The temp unlink is best-effort
+ * cleanup. Returns `{ filename, sizeBytes }`.
+ */
+export async function importFileToDir(tempPath, originalName, destDir) {
+ await ensureDir(destDir);
+ const filename = `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalName)}`;
+ const dest = join(destDir, filename);
+ await copyFile(tempPath, dest);
+ await unlink(tempPath).catch(() => {});
+ const s = await stat(dest).catch(() => null);
+ return { filename, sizeBytes: s?.size ?? 0 };
+}
+
+/**
+ * `importFileToDir` pinned to the uploads dir (`PATHS.uploads`) — the common
+ * case (e.g. a yt-dlp audio extraction, #2120).
+ */
+export async function importFileToUploads(tempPath, originalName) {
+ return importFileToDir(tempPath, originalName, PATHS.uploads);
+}
+
+// Widest supported image signature (WebP needs 12 bytes: `RIFF….WEBP`). A payload
+// shorter than this can't hold a complete header for any format we accept.
+const MIN_IMAGE_BYTES = 12;
+
+// POSIX NAME_MAX — the per-component filename limit on ext4/APFS/HFS+. A longer
+// component makes the write fail with ENAMETOOLONG.
+const MAX_FILENAME_BYTES = 255;
+
+/**
+ * Persist a base64-encoded IMAGE into `dir`, deriving the format from the bytes
+ * rather than trusting the client: decode → size cap → magic-byte sniff → force
+ * the extension to the detected format → sanitize + containment guard → write.
+ *
+ * This is the sibling of `saveBase64Upload` for the paths that must be certain
+ * they wrote an image (they hand the file to an image-gen backend or to an agent
+ * that will read it), so an extension allowlist isn't enough. Naming is the
+ * CALLER's call — pass a name that is already unique if later uploads must not
+ * overwrite this one, since `dir` is a shared bucket.
+ *
+ * Throws ServerError with the status/code/message contract `routes/screenshots.js`
+ * established (`FILE_TOO_LARGE`, `INVALID_FILE_TYPE`, `INVALID_FILENAME` — all
+ * 400) so callers keep their pinned responses.
+ *
+ * @param {string} dir - Destination directory (created if missing).
+ * @param {{ filename: string, data: string }} upload - Desired base name (the
+ * extension is replaced with the detected one) + base64 payload.
+ * @param {{ maxBytes: number }} opts
+ * @returns {Promise<{ filename: string, filePath: string, size: number,
+ * format: string, mime: string }>}
+ */
+export async function saveImageUpload(dir, { filename, data }, { maxBytes }) {
+ const buffer = Buffer.from(data, 'base64');
+ if (buffer.length > maxBytes) {
+ throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
+ }
+
+ // Floor before the sniff, because the per-format signatures are short (a JPEG is
+ // 3 bytes, a GIF header 6) and would happily "detect" a truncated payload — which
+ // then saves as a success and hands a consumer a path to an unreadable file. 12
+ // bytes is the widest signature (WebP's RIFF….WEBP), so anything under it cannot
+ // be a complete header for ANY supported format, let alone a complete image.
+ if (buffer.length < MIN_IMAGE_BYTES) {
+ throw new ServerError('Invalid image file - only PNG, JPEG, GIF, and WebP are supported', { status: 400, code: 'INVALID_FILE_TYPE' });
+ }
+
+ const detected = detectImageFormat(buffer);
+ if (!detected) {
+ throw new ServerError('Invalid image file - only PNG, JPEG, GIF, and WebP are supported', { status: 400, code: 'INVALID_FILE_TYPE' });
+ }
+
+ // The DETECTED extension always wins over whatever the client claimed, so the
+ // file on disk can't advertise a type its bytes contradict. Strip a matching
+ // extension off the base rather than appending a second one, then clamp the base
+ // so `base + ext` fits NAME_MAX — a caller that prefixes the name (see
+ // services/shellImageDrop.js) can otherwise push a legitimately-long client
+ // filename past the limit and turn the write into an ENAMETOOLONG 500.
+ const safeName = sanitizeFilename(filename);
+ const base = safeName.toLowerCase().endsWith(detected.ext)
+ ? safeName.slice(0, -detected.ext.length)
+ : safeName;
+ // sanitizeFilename leaves only ASCII, so slicing chars is slicing bytes.
+ const fname = `${base.slice(0, MAX_FILENAME_BYTES - detected.ext.length)}${detected.ext}`;
+ const filePath = join(dir, fname);
+ if (!isPathInsideDir(dir, filePath)) {
+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
+ }
+
+ await ensureDir(dir);
+ await writeFile(filePath, buffer);
+
+ return { filename: fname, filePath, size: buffer.length, format: detected.format, mime: detected.mime };
+}
+
+/**
+ * Persist a base64-encoded upload into `dir` with the shared attachment
+ * pipeline: extension allowlist → base64 decode → size cap → ensureDir →
+ * `<uuid8>-<sanitized-name>` naming → containment guard → write.
+ *
+ * Throws ServerError with the exact status/code/message contract the
+ * attachment routes established (`INVALID_FILE_TYPE`, `FILE_TOO_LARGE`,
+ * `INVALID_FILENAME` — all 400), so refactored routes keep their pinned
+ * responses. Consolidates `routes/attachments.js`, `routes/brainSongbook.js`,
+ * and `routes/uploads.js` — the last keeps its own richer response shape
+ * (`originalName` / `sizeFormatted` / `createdAt`) around these fields.
+ *
+ * @param {string} dir - Destination directory (created if missing).
+ * @param {{ filename: string, data: string }} upload - Original filename +
+ * base64 payload (validated as present by the calling route).
+ * @param {{ allowedExtensions: Set<string>, maxBytes: number }} opts
+ * @returns {Promise<{ id: string, filename: string, filePath: string,
+ * buffer: Buffer, size: number, mime: string }>} `id` is the full UUID whose
+ * first 8 chars prefix `filename`.
+ */
+export async function saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes }) {
+ const ext = getFileExtension(filename);
+ if (!ext || !allowedExtensions.has(ext)) {
+ const allowedList = [...allowedExtensions].join(', ');
+ throw new ServerError(`File type not allowed. Supported: ${allowedList}`, { status: 400, code: 'INVALID_FILE_TYPE' });
+ }
+
+ const buffer = Buffer.from(data, 'base64');
+ if (buffer.length > maxBytes) {
+ throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
+ }
+
+ await ensureDir(dir);
+
+ // Unique uuid prefix avoids collisions; sanitize kills traversal characters.
+ const id = randomUUID();
+ const fname = `${id.slice(0, 8)}-${sanitizeFilename(filename)}`;
+ const filePath = join(dir, fname);
+ // Double-check the path is within the destination dir (defense in depth).
+ if (!isPathInsideDir(dir, filePath)) {
+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
+ }
+
+ await writeFile(filePath, buffer);
+
+ return { id, filename: fname, filePath, buffer, size: buffer.length, mime: getMimeType(getFileExtension(fname)) };
+}
+
+/**
+ * Serve a machine-local file from `dir` by user-supplied filename with the
+ * shared safety pipeline: sanitize → containment guard (400
+ * `INVALID_FILENAME`) → existence check (404, message/code parametrized via
+ * `missingError` so routes keep their contracts) → `X-Content-Type-Options:
+ * nosniff` → attachment disposition for RISKY_MIME_TYPES → `res.sendFile`.
+ *
+ * Mirrors the exact serving behavior of `routes/attachments.js`.
+ *
+ * @param {import('express').Response} res
+ * @param {string} dir - The containing directory.
+ * @param {string} filename - Raw user-supplied filename.
+ * @param {{ missingError?: { message: string, code: string } }} [opts]
+ */
+export async function serveLocalFile(res, dir, filename, { missingError } = {}) {
+ const safeFilename = sanitizeFilename(filename);
+ const filePath = resolvePath(dir, safeFilename);
+
+ if (!isPathInsideDir(dir, filePath)) {
+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
+ }
+
+ if (!(await pathExists(filePath))) {
+ const { message = 'Attachment not found', code = 'NOT_FOUND' } = missingError || {};
+ throw new ServerError(message, { status: 404, code });
+ }
+
+ const mimeType = getMimeType(getFileExtension(safeFilename));
+ res.set('X-Content-Type-Options', 'nosniff');
+ if (RISKY_MIME_TYPES.has(mimeType)) {
+ res.set('Content-Disposition', `attachment; filename="${safeFilename}"`);
+ }
+ res.type(mimeType).sendFile(filePath);
+}