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

fix: stop unreadable data files from reporting — and persisting — as empty ones (#4115)

[._.]/ Adam Eivy475ce388207f
diff --git a/.changelog/next/fixed-issue-4115.md b/.changelog/next/fixed-issue-4115.md
new file mode 100644
index 0000000000..30b74df42b
--- /dev/null
+++ b/.changelog/next/fixed-issue-4115.md
@@ -0,0 +1 @@
+- An unreadable data file no longer reports as an empty one — usage totals, app/instance registries, notification and review counts, memory stats, decision-log stats, quota-burn dispatch counts, domain budgets and video history now refuse to publish a fake zero or overwrite themselves with it
diff --git a/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md b/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md
new file mode 100644
index 0000000000..d568ae4006
--- /dev/null
+++ b/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md
@@ -0,0 +1,139 @@
+# ADR: Strict JSON Reads Wherever a File-Backed Value Is Counted, Displayed, or Written Back
+
+- **Date:** 2026-08-14
+- **Status:** Accepted
+- **Related:** issue #4115 (this audit), issue #2726 (introduced
+ `readJSONFileStrict`, scoped to the Character sheet's file-backed signals),
+ [`server/lib/fileUtils.js`](../../server/lib/fileUtils.js),
+ [`server/lib/README.md`](../../server/lib/README.md), root `CLAUDE.md`
+ ("Sentinel + validate to distinguish 'not set / failed' from
+ 'present-but-empty / valid'").
+
+## Context
+
+`readJSONFile(path, default)` and `tryReadFile(path)` both collapse three
+distinct states into one value:
+
+| State | `readJSONFile` | `tryReadFile` |
+| --- | --- | --- |
+| Absent (ENOENT — never written) | `default` | `null` |
+| Present but unreadable (EACCES, EIO, EISDIR, …) | `default` | `null` |
+| Present but corrupt / truncated JSON | `default` | *(n/a — no parse)* |
+
+For a config-ish read with a sensible fallback that collapse is correct and is
+the long-standing behavior of ~230 call sites. It is **wrong** in two situations,
+and #2726 only fixed the first for one feature:
+
+1. **The value is counted or displayed.** A swallowed unreadable file reports a
+ confident `0` — "0 notifications", "0% aligned", "0/5 dispatches used" — which
+ the user reads as fact rather than as "we could not read your data".
+2. **The value is the base of a read-modify-write.** This is the more damaging
+ half and was not in the original framing. `load → mutate → save` over a
+ swallowed default writes the *empty default* back over the real file. The read
+ does not merely misreport the data; it destroys it on the next write.
+
+`tryReadFile` additionally had no strict counterpart at all, so two callers had
+hand-rolled their own — `settings.js#readSettingsStrict` re-probed with
+`access()` after the fact (a second syscall that can disagree with the read it is
+explaining), and `layeredIntelligence/sources.js#gatherPlannedWork` gated on
+`existsSync` before reading.
+
+## Decision
+
+1. **Add `tryReadFileStrict(path, encoding?)` → `{ ok, value }`** to
+ `server/lib/fileUtils.js`, the raw-bytes twin of `readJSONFileStrict`. ENOENT
+ — the only errno that *proves* absence — yields `{ ok: true, value: null }`;
+ every other read failure yields `{ ok: false, value: null }`. It shares the
+ Windows `atomicWrite` swap-window retries with `readJSONFileStrict`, so a
+ write in flight cannot masquerade as ENOENT.
+
+2. **Convert a `readJSONFile` call site to a strict read when *either* is true:**
+ its result feeds a count / a displayed stat / a gate threshold, **or** it is
+ the base of a write back to the same file. Leave it swallowing when the value
+ is a config fallback, a single-record lookup, or a derived cache that is
+ regenerated rather than merged.
+
+3. **Pick the failure shape from the caller's position, not mechanically:**
+ - *Request-path reader* → `readJSONFile(…, { strict: true })`, which throws and
+ bubbles to the error middleware. Prefer this where the function can already
+ reject (e.g. it awaits `ensureDir` first), so no caller contract changes.
+ - *Ledger/gate with a "skip this cycle" posture* → `readJSONFileStrict` and
+ return an explicit `null`, letting the write path refuse to overwrite. This
+ is the `quotaBurnCompletions.js` / `quotaBurnDenials.js` shape.
+ - *Status/display path reading the same file as a gate* → may degrade to the
+ empty default, because the cost of being wrong there is a stale label rather
+ than a destroyed ledger or re-spent quota. Say so at the call site.
+
+4. **Never re-swallow downstream.** A `.catch(() => [])` on a strict reader
+ cancels the whole fix; two such catches were removed in `videoDownload.js`.
+
+## Audit (#4115)
+
+`server/` holds ~237 non-test `readJSONFile` call sites and ~130 `tryReadFile`
+call sites. They were triaged by tracing each reader's wrapper function to its
+consumers (routes, widgets, schedulers) and to any write back to the same path.
+
+### Converted
+
+| Call site | Why |
+| --- | --- |
+| `services/usage.js#loadUsage` | The `!usageData` branch overwrites `usage.json` with zeros on the same tick — an unreadable file erased all historical usage/cost/rollups permanently. |
+| `services/apps.js#loadApps` | The reader itself writes: an empty `apps` map makes the baseline branch rewrite `apps.json` with a lone PortOS entry, deleting every registered app. Also feeds `getAppStatusSummary`'s total/online/unmanaged. |
+| `services/instances.js#loadData` | Every mutation runs through `withData`, which saves whatever was read. A swallowed read hands `ensureSelf` an identity-less record — it mints a new `instanceId` and wipes every peer. |
+| `services/quotaBurn.js#getQuotaBurnDispatches` | `dispatchesUsed` is both the `maxDispatchesPerWindow` gate and the family card's `N/M used`. Now returns `null` on a failed read (matching its two sibling ledgers); the cycle skips and the write refuses. The status path degrades to `{}` deliberately. |
+| `services/notifications.js#loadNotifications` | `getUnreadCount` is the bell badge (`GET /api/notifications/count`); also the base of every `saveNotifications`. |
+| `services/review.js#loadItems` | `getPendingCounts` reduces it into the Review Hub tiles; also the base of every `saveItems`. |
+| `services/memoryStore.js#loadIndex`, `#loadEmbeddings` | `index.count` and `Object.keys(vectors).length` *are* the Memory stats card, both values are cached for the process lifetime, and both are written back. |
+| `services/decisionLog.js#loadDecisions` | `getDecisionSummary` divides by `recentDecisions.length` for the transparency score; `stats.totalDecisions` is a lifetime counter that `saveDecisions` writes back. |
+| `services/domainUsage.js#readFreshLedger` | The fall-through resets the day's ledger to zeros and `recordDomainUsage` writes it back — zeroing the Domain Budgets panel *and* re-opening a domain that had spent its cap. |
+| `services/videoGen/history.js#loadHistory` | Every write goes `loadHistory → mutate → saveHistory`; a swallowed read persists `[]` over the whole render history. |
+| `services/dataSync.js#getVideoHistorySnapshot` | Would publish a valid checksum over an empty set, so peers conclude this machine holds no videos and the category thrashes forever. |
+| `services/dataSync.js#applyVideoHistoryRemote` | The merge base — an empty `local` makes the merged result the remote rows alone, deleting every local-only row. |
+| `services/videoDownload.js` (×2) | Removed `.catch(() => [])` wrappers that re-swallowed `loadHistory`'s new strict signal. |
+| `services/settings.js#readSettingsStrict` | Routed onto `tryReadFileStrict`, replacing a hand-rolled `access()` re-probe. Same three-state verdict, one syscall, no window in which the probe can disagree with the read. |
+
+### Reviewed and deliberately left swallowing
+
+- **Config / settings reads with a real default** — `openclaw/api.js`,
+ `dashboardLayouts.js`, `autobiography.js#loadConfig`, `browserService.js`,
+ `meatspaceAlcohol.js` config, `datadog.js`, `updateChecker.js#pkg`. A fallback
+ is the documented behavior; nothing is counted and nothing is written back over
+ the file.
+- **Single-record lookups** — `tools.js`, `dailyReview.js`, `jiraReports.js`,
+ `askConversations.js`, `bibleStore.js`, `goalCalendarScheduler.js`, the
+ `sprites/*` manifest/sidecar readers, `sharing/importer.js`'s per-record reads.
+ A miss surfaces as a 404 rather than a fabricated total.
+- **Sidecars and derived caches** — `assetHash.js`, `mediaSketches.js`,
+ `insightsService.js` theme/narrative caches, `calendarSync.js`. Regenerated on
+ a miss, never merged into.
+- **Federation cursors and bucket indexes** — `sharing/manifest.js`,
+ `sharing/subscriptions.js`, `sharing/buckets.js`, `sharing/exporter.js`,
+ `peerTombstoneCursors.js`. Add-only merges whose worst case on a failed read is
+ re-processing an already-seen item, not deleting one.
+- **One-shot migration scripts** — `server/scripts/migrate*ToDB.js`,
+ `pipeline/migrateSeriesCanon.js`. They read a legacy path that is *expected* to
+ be absent and are re-runnable.
+- **`layeredIntelligence/sources.js#gatherPlannedWork`** — already distinguishes
+ the three states via an `existsSync` gate plus a `typeof content !== 'string'`
+ check, and its `readFileFn` is an injected test seam. Correct as written.
+
+### Not yet converted (follow-up)
+
+These are genuine members of the class (count-feeding and/or destructive
+read-modify-write) but were left out to keep this change reviewable:
+`taskLearning/store.js` (`LEARNING_FILE`, `DISMISSED_RECS_FILE`),
+`goalScorecard.js` (`GOALS_FILE`, `SCORECARD_FILE`), `goalCheckIn.js`,
+`brainStorage.js#loadMeta`, `telegram.js#loadCheckins`, `appActivity.js`,
+`mediaJobQueue/index.js#initMediaJobQueue`.
+
+## Consequences
+
+- A present-but-unreadable file on a converted path now surfaces as an error
+ instead of a fake zero, and no longer gets overwritten by the next save.
+- **Exhaustive `vi.mock('../lib/fileUtils.js', () => ({ … }))` factories must
+ list every export the module under test transitively imports.** Adding
+ `tryReadFileStrict` to `settings.js` broke two such suites with a "not defined
+ on the mock" throw. Prefer the `importActual`-spread form in new tests.
+- The remaining ~200 swallowing call sites are documented above by category
+ rather than individually, so a future reader can classify a *new* call site
+ without re-deriving the rule.
diff --git a/server/lib/README.md b/server/lib/README.md
index 970a75974b..952c030290 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -156,7 +156,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `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`. |
-| `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, dir scans, 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. Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. |
+| `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, dir scans, 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`. |
| `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/fileUtils.js b/server/lib/fileUtils.js
index 217f70b562..bfe750948e 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -457,7 +457,8 @@ export function safeJSONParse(str, defaultValue = null, { allowArray = true, log
*
* 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 `readJSONFileStrict` instead.
+ * 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)
@@ -467,6 +468,40 @@ 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.
*
@@ -553,7 +588,7 @@ async function hasSwapSibling(filePath) {
}
/**
- * `readFile(filePath, 'utf-8')` with the Windows-only retries that keep a read
+ * `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.
@@ -570,12 +605,13 @@ async function hasSwapSibling(filePath) {
* existing errno handling is unchanged.
*
* @param {string} filePath
- * @returns {Promise<string>}
+ * @param {string|null} [encoding='utf-8'] - Encoding (null for Buffer)
+ * @returns {Promise<string|Buffer>}
*/
-async function readTextWithSwapRetry(filePath) {
- if (!isWindows()) return readFile(filePath, 'utf-8');
+async function readWithSwapRetry(filePath, encoding = 'utf-8') {
+ if (!isWindows()) return readFile(filePath, encoding);
for (let attempt = 0; ; attempt += 1) {
- const outcome = await readFile(filePath, 'utf-8').then((content) => ({ content }), (err) => ({ err }));
+ 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;
@@ -624,7 +660,7 @@ async function readTextWithSwapRetry(filePath) {
export async function readJSONFileStrict(filePath, defaultValue = null, { allowArray = true, logError = true } = {}) {
let content;
try {
- content = await readTextWithSwapRetry(filePath);
+ 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
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 7a2650ad81..e2de6d48f4 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -39,6 +39,8 @@ import {
createCachedStore,
readJSONFile,
readJSONFileStrict,
+ tryReadFile,
+ tryReadFileStrict,
readJSONLFile,
appendJSONLine,
readJSONLines,
@@ -517,6 +519,75 @@ describe('fileUtils', () => {
});
});
+ // #4115: `tryReadFile` had the same absent-vs-unreadable conflation as
+ // `readJSONFile` (a bare `.catch(() => null)`) but no strict counterpart at all.
+ // These pin the three-state contract for the raw-bytes variant.
+ describe('tryReadFileStrict', () => {
+ const testDir = join(tmpdir(), 'fileutils-tryreadstrict-test-' + Date.now());
+
+ beforeEach(async () => {
+ await mkdir(testDir, { recursive: true });
+ });
+
+ afterEach(async () => {
+ await rm(testDir, { recursive: true, force: true });
+ });
+
+ const eacces = () => Object.assign(new Error('permission denied'), { code: 'EACCES' });
+
+ it('reports ENOENT as a TRUSTWORTHY absence', async () => {
+ expect(await tryReadFileStrict(join(testDir, 'never-written.txt')))
+ .toEqual({ ok: true, value: null });
+ });
+
+ it('reports EACCES as NOT ok — an unreadable file is not an absent one', async () => {
+ const filePath = join(testDir, 'locked.txt');
+ await writeFile(filePath, 'real contents');
+
+ expect(await withUnreadableFile(eacces(), () => tryReadFileStrict(filePath)))
+ .toEqual({ ok: false, value: null });
+ });
+
+ it('reports a real non-ENOENT errno as NOT ok (reading a directory → EISDIR)', async () => {
+ // Unmocked, no synthetic errno: proves the classification keys off "not
+ // ENOENT" rather than a hard-coded list the real world can step outside of.
+ expect((await tryReadFileStrict(testDir)).ok).toBe(false);
+ });
+
+ it('returns the contents with ok when the read succeeds', async () => {
+ const filePath = join(testDir, 'present.txt');
+ await writeFile(filePath, 'hello');
+
+ expect(await tryReadFileStrict(filePath)).toEqual({ ok: true, value: 'hello' });
+ });
+
+ it('keeps an EMPTY file distinguishable from an absent one', async () => {
+ const filePath = join(testDir, 'empty.txt');
+ await writeFile(filePath, '');
+
+ expect(await tryReadFileStrict(filePath)).toEqual({ ok: true, value: '' });
+ expect(await tryReadFileStrict(join(testDir, 'gone.txt'))).toEqual({ ok: true, value: null });
+ });
+
+ it('honours a null encoding and returns a Buffer', async () => {
+ const filePath = join(testDir, 'bytes.bin');
+ await writeFile(filePath, Buffer.from([0x00, 0x01, 0xff]));
+
+ const { ok, value } = await tryReadFileStrict(filePath, null);
+ expect(ok).toBe(true);
+ expect(Buffer.isBuffer(value)).toBe(true);
+ expect([...value]).toEqual([0x00, 0x01, 0xff]);
+ });
+
+ it('matches tryReadFile on the value for every non-error case', async () => {
+ const filePath = join(testDir, 'parity.txt');
+ await writeFile(filePath, 'same bytes');
+
+ expect((await tryReadFileStrict(filePath)).value).toBe(await tryReadFile(filePath));
+ expect((await tryReadFileStrict(join(testDir, 'nope.txt'))).value).toBe(await tryReadFile(join(testDir, 'nope.txt')));
+ });
+ });
+
// The `strict` option is the same classification, surfaced as a throw — the shape
// the Character signal readers need, since a rejection is how every DB-backed
// getter already reports failure (#2726).
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 3324e774a7..1ec56d62b2 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -8,6 +8,11 @@ const fileStore = new Map();
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
+ // Strict twin (#4115) — `services/settings.js#readSettingsStrict` reads through
+ // it, and this factory is exhaustive (no `importActual` spread), so an omitted
+ // export is a hard "not defined on the mock" throw. `ok: true, value: null` is
+ // the absent-file shape, matching `tryReadFile`'s null above.
+ tryReadFileStrict: vi.fn().mockResolvedValue({ ok: true, value: null }),
// Series Autopilot gates on the cos autonomy domain, so the pipeline route
// graph now transitively imports `services/cosState.js`, which computes
// `join(PATHS.cos, …)` at module load. The mock must therefore carry the
diff --git a/server/services/apps.js b/server/services/apps.js
index d52b900fa7..90cf7fab9d 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -89,7 +89,12 @@ async function loadApps() {
await ensureDir(DATA_DIR);
- const data = await readJSONFile(APPS_FILE, { apps: {} });
+ // STRICT (#4115): this reader WRITES — an empty `data.apps` makes the baseline
+ // branch below rewrite apps.json with a lone PortOS entry, so a swallowed
+ // EACCES/EIO would delete every registered app. It also feeds displayed counts
+ // (`getAppStatusSummary`'s total/online/unmanaged), where a fake 0 reads as
+ // fact. Absent is still a legitimate first-run empty; unreadable is not.
+ const data = await readJSONFile(APPS_FILE, { apps: {} }, { strict: true });
// Normalize: ensure data.apps is always an object
if (!data.apps || typeof data.apps !== 'object') {
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index da3985ee00..d23372dc14 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -7,6 +7,11 @@ vi.mock('./cosEvents.js', () => ({
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
+ // Strict twin (#4115) — `services/settings.js#readSettingsStrict` reads through
+ // it, and this factory is exhaustive (no `importActual` spread), so an omitted
+ // export is a hard "not defined on the mock" throw. `ok: true, value: null` is
+ // the absent-file shape, matching `tryReadFile`'s null above.
+ tryReadFileStrict: vi.fn().mockResolvedValue({ ok: true, value: null }),
readJSONFile: vi.fn(),
ensureDir: vi.fn().mockResolvedValue(),
atomicWrite: vi.fn().mockResolvedValue(),
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 1c8f7e2a15..2ac7de3086 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -645,7 +645,10 @@ async function applyMediaCollectionsRemote(remoteData, source) {
const hasVideoRowId = (r) => typeof r?.id === 'string' && r.id;
async function getVideoHistorySnapshot() {
- const raw = await readJSONFile(VIDEO_HISTORY_FILE, []);
+ // STRICT (#4115): an unreadable history would publish a valid CHECKSUM over an
+ // empty set — peers conclude this machine holds no videos and the category
+ // thrashes forever. Absent is a real empty; unreadable must not go on the wire.
+ const raw = await readJSONFile(VIDEO_HISTORY_FILE, [], { strict: true });
// Exclude rows without a string `id`: applyVideoHistoryRemote can only merge
// id-keyed rows, so an id-less row in the wire snapshot/checksum would be
// un-appliable on the receiver — its recomputed checksum would never match the
@@ -677,7 +680,11 @@ async function applyVideoHistoryRemote(remoteData) {
const incoming = Array.isArray(remoteData.videos) ? remoteData.videos : [];
if (incoming.length === 0) return { applied: false, count: 0 };
- const localRaw = await readJSONFile(VIDEO_HISTORY_FILE, []);
+ // STRICT (#4115): this is the merge BASE, and the merged result is written
+ // back over the whole file below. A swallowed unreadable read makes `local`
+ // empty, so `next` becomes the remote rows alone — deleting every local-only
+ // row, including the id-less ones the code below goes out of its way to keep.
+ const localRaw = await readJSONFile(VIDEO_HISTORY_FILE, [], { strict: true });
const local = Array.isArray(localRaw) ? localRaw : [];
// Union by `id`, LWW on `createdAt` when both sides know the same row.
diff --git a/server/services/decisionLog.js b/server/services/decisionLog.js
index d444ad493e..e958042186 100644
--- a/server/services/decisionLog.js
+++ b/server/services/decisionLog.js
@@ -54,7 +54,12 @@ async function loadDecisions() {
await ensureDir(DATA_DIR);
- decisionCache = await readJSONFile(DECISION_FILE, { ...DEFAULT_DATA });
+ // STRICT (#4115): `getDecisionSummary()` divides by `recentDecisions.length`
+ // for the transparency score and reduces `count` into `totalOccurrences` — a
+ // swallowed unreadable read publishes those as real numbers over an empty set.
+ // `data.stats.totalDecisions` is also a LIFETIME counter that `saveDecisions`
+ // writes back, so the same read resets it to zero on the next recordDecision.
+ decisionCache = await readJSONFile(DECISION_FILE, { ...DEFAULT_DATA }, { strict: true });
cacheLoaded = true;
return decisionCache;
}
diff --git a/server/services/domainUsage.js b/server/services/domainUsage.js
index 6491ba007b..5c8bbc950b 100644
--- a/server/services/domainUsage.js
+++ b/server/services/domainUsage.js
@@ -40,7 +40,11 @@ function emptyUsageMap() {
// date isn't today (or the file is missing / hand-edited into a bad shape).
async function readFreshLedger() {
const today = todayKey();
- const stored = await readJSONFile(USAGE_FILE, null, { logError: false });
+ // STRICT (#4115): the fall-through below resets the ledger to an empty map,
+ // and `recordDomainUsage` writes that back — so a swallowed unreadable file
+ // both zeroes the Domain Budgets panel's actions/ms and re-opens a domain that
+ // had already spent its daily cap. Only ENOENT / a stale date are real rolls.
+ const stored = await readJSONFile(USAGE_FILE, null, { logError: false, strict: true });
if (!stored || stored.date !== today || typeof stored.usage !== 'object' || stored.usage === null) {
return { date: today, usage: emptyUsageMap() };
}
diff --git a/server/services/instances.js b/server/services/instances.js
index 5e6f418281..ba4565a8fc 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -138,8 +138,14 @@ const DEFAULT_DATA = {
// --- File I/O ---
+// STRICT (#4115): every mutation runs through `withData`, which writes whatever
+// this read returned straight back. Swallowing an unreadable instances.json into
+// DEFAULT_DATA therefore hands `ensureSelf` an identity-less record — it mints a
+// BRAND-NEW instanceId and `saveData` persists it over the real file, rotating
+// this node's federation identity and wiping every peer. ENOENT (never
+// federated) stays the trustworthy first-run empty.
async function loadData() {
- return await readJSONFile(INSTANCES_FILE, DEFAULT_DATA);
+ return await readJSONFile(INSTANCES_FILE, DEFAULT_DATA, { strict: true });
}
async function saveData(data) {
diff --git a/server/services/memoryStore.js b/server/services/memoryStore.js
index 2480b6159d..6e83be3cd2 100644
--- a/server/services/memoryStore.js
+++ b/server/services/memoryStore.js
@@ -42,7 +42,11 @@ export async function loadIndex() {
await ensureDirectories();
const defaultIndex = { version: 1, lastUpdated: new Date().toISOString(), count: 0, memories: [] };
- indexCache = await readJSONFile(INDEX_FILE, defaultIndex);
+ // STRICT (#4115): `index.count` and the byStatus tally ARE the Memory page's
+ // stat card (GET /api/memory/stats). Worse, the value is cached for the life of
+ // the process AND written back by `saveIndex` — one swallowed unreadable read
+ // would report 0 memories and then overwrite index.json with the empty default.
+ indexCache = await readJSONFile(INDEX_FILE, defaultIndex, { strict: true });
return indexCache;
}
@@ -65,7 +69,9 @@ export async function loadEmbeddings() {
await ensureDirectories();
const defaultEmbeddings = { model: null, dimension: 0, vectors: {} };
- embeddingsCache = await readJSONFile(EMBEDDINGS_FILE, defaultEmbeddings);
+ // Same contract as `loadIndex` — `Object.keys(vectors).length` is the stats
+ // card's `withEmbeddings`, and `saveEmbeddings` writes this value back.
+ embeddingsCache = await readJSONFile(EMBEDDINGS_FILE, defaultEmbeddings, { strict: true });
return embeddingsCache;
}
diff --git a/server/services/notifications.js b/server/services/notifications.js
index 06973cdb84..85874a1642 100644
--- a/server/services/notifications.js
+++ b/server/services/notifications.js
@@ -63,7 +63,12 @@ async function loadNotifications() {
await ensureDirectory();
- notificationsCache = await readJSONFile(NOTIFICATIONS_FILE, { version: 1, notifications: [] });
+ // STRICT (#4115): this feeds `getUnreadCount()`, the bell badge served by
+ // GET /api/notifications/count — a fake 0 there is a lie, not a default. It is
+ // also the base of every read-modify-write (`saveNotifications`), so a
+ // swallowed unreadable read would let the next markAsRead truncate the file.
+ // `ensureDirectory()` above can already reject, so callers tolerate a throw.
+ notificationsCache = await readJSONFile(NOTIFICATIONS_FILE, { version: 1, notifications: [] }, { strict: true });
return notificationsCache;
}
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index c44a4bae18..7ebb24d090 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -18,7 +18,7 @@
*/
import { join } from 'path';
-import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, readJSONFileStrict } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { familyHasRunnableJobs, familyIsConfigured, isUnlimitedDispatchCap, normalizeQuotaBurnFamily } from '../lib/quotaBurnConfig.js';
import { isPlainObject } from '../lib/objects.js';
@@ -34,10 +34,22 @@ const LEDGER_FILE = () => join(PATHS.cos, 'quota-burn-dispatches.json');
// install.
const LEDGER_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
-/** Dispatch counts per `<family>:<resetEpochMs>` window key. */
+/**
+ * Dispatch counts per `<family>:<resetEpochMs>` window key, or `null` when the
+ * ledger could not be read.
+ *
+ * The `null` is load-bearing, and matches `quotaBurnCompletions.js` /
+ * `quotaBurnDenials.js`, which read the sibling ledgers strictly for exactly this
+ * reason (#4115). A failed or corrupt read must not come back as "0 dispatches
+ * this window": `dispatchesUsed` is both the cap gate AND the number the family
+ * card shows as `N/M used`, so a swallowed read re-opens a spent window and then
+ * lets the next write persist the empty ledger over every surviving count — real
+ * quota overspend. Absent (never dispatched) is still a trustworthy `{}`.
+ */
export async function getQuotaBurnDispatches() {
- const loaded = await readJSONFile(LEDGER_FILE(), {});
- return isPlainObject(loaded) ? loaded : {};
+ const { ok, value } = await readJSONFileStrict(LEDGER_FILE(), {}, { logError: false });
+ if (!ok) return null;
+ return isPlainObject(value) ? value : {};
}
const windowEpoch = (key) => Number(String(key).split(':').pop());
@@ -61,7 +73,12 @@ const ledgerWriteQueue = createFileWriteQueue();
export async function recordQuotaBurnDispatch(key, { now = Date.now() } = {}) {
return ledgerWriteQueue(async () => {
- const ledger = pruneLedger(await getQuotaBurnDispatches(), now);
+ const loaded = await getQuotaBurnDispatches();
+ // Never overwrite a ledger we could not read — the same guard the sibling
+ // ledgers' `writeLedger` carries. Returning null tells the caller the
+ // dispatch went unrecorded rather than pretending the window is at 1.
+ if (!loaded) return null;
+ const ledger = pruneLedger(loaded, now);
const next = { ...ledger, [key]: Number(ledger[key] || 0) + 1 };
await atomicWrite(LEDGER_FILE(), next);
return next;
diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.js
index 26b1259c1b..bce2317af4 100644
--- a/server/services/quotaBurn.test.js
+++ b/server/services/quotaBurn.test.js
@@ -172,12 +172,14 @@ describe('selectBurnCandidates bypassGatesFor', () => {
describe('recordQuotaBurnDispatch', () => {
afterEach(() => { vi.doUnmock('../lib/fileUtils.js'); vi.resetModules(); });
- const withLedger = async (initial = {}) => {
+ // `readable: false` drives the present-but-unreadable case (#4115): the strict
+ // reader's `ok: false`, which must never be mistaken for an empty ledger.
+ const withLedger = async (initial = {}, { readable = true } = {}) => {
vi.resetModules();
let stored = { ...initial };
vi.doMock('../lib/fileUtils.js', async (importActual) => ({
...(await importActual()),
- readJSONFile: async () => ({ ...stored }),
+ readJSONFileStrict: async () => (readable ? { ok: true, value: { ...stored } } : { ok: false, value: {} }),
// The delay must sit on the WRITE: it holds each read-modify-write open
// long enough for the next caller's read to observe the pre-write state.
// (A delay on the read instead resolves in a macrotask whose continuation
@@ -210,6 +212,21 @@ describe('recordQuotaBurnDispatch', () => {
const next = await recordQuotaBurnDispatch(`grok:${NOW}`, { now: NOW });
expect(next).toEqual({ 'grok:not-a-number': 1, [`grok:${NOW}`]: 1 });
});
+
+ // #4115: an unreadable ledger used to read as "0 dispatches this window",
+ // which both under-reports the family card's `N/M used` badge and lets the
+ // next write persist an empty ledger over every surviving count.
+ it('reports an unreadable ledger as null rather than an empty one', async () => {
+ const { getQuotaBurnDispatches } = await withLedger({ 'grok:1': 4 }, { readable: false });
+ await expect(getQuotaBurnDispatches()).resolves.toBeNull();
+ });
+
+ it('refuses to write over a ledger it could not read', async () => {
+ const { recordQuotaBurnDispatch } = await withLedger({ [`grok:${NOW}`]: 4 }, { readable: false });
+ // No write, and a null return so the caller knows the dispatch went
+ // unrecorded instead of believing the window is now at 1.
+ await expect(recordQuotaBurnDispatch(`grok:${NOW}`, { now: NOW })).resolves.toBeNull();
+ });
});
describe('windowKey', () => {
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 42d79d7bc3..a254d891cc 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -287,6 +287,10 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
if (!quotas) return finish({ dispatched: false, reason: 'provider quota read failed' });
const [dispatches, blocks] = await Promise.all([getQuotaBurnDispatches(), getActiveQuotaBurnBlocks()]);
+ // An unreadable dispatch ledger reads as "0 used this window", which would
+ // walk straight past `maxDispatchesPerWindow` and spend quota the user already
+ // spent (#4115). Same posture as the provider-quota read above: skip the cycle.
+ if (!dispatches) return finish({ dispatched: false, reason: 'dispatch ledger read failed' });
// `force` is the page's per-job "Run now" — the window/reserve/cap/denial gates
// that bound UNATTENDED burns don't apply to a run the user just asked for. It
// goes through the same selection, so the candidate still carries the family's
@@ -416,7 +420,11 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {
console.error(`❌ Quota-burn status could not read provider quota: ${err.message}`);
return [];
}),
- getQuotaBurnDispatches(),
+ // Degrades to "no dispatches counted" on an unreadable ledger for the same
+ // reason the completions read below does: on the STATUS path the cost of
+ // being wrong is a stale `N/M used` label, not re-spent quota. The cycle's
+ // read of the same ledger refuses to run instead.
+ getQuotaBurnDispatches().then((ledger) => ledger || {}),
getActiveQuotaBurnBlocks(),
// An unreadable ledger degrades to "no badges" here rather than failing the
// whole status read — the opposite of the CYCLE's posture, and deliberately
diff --git a/server/services/review.js b/server/services/review.js
index bbadc1b76c..23586c60c9 100644
--- a/server/services/review.js
+++ b/server/services/review.js
@@ -24,8 +24,13 @@ const ITEM_STATUSES = ['pending', 'completed', 'dismissed'];
/**
* Load all review items from file
*/
+// STRICT (#4115): `getPendingCounts()` reduces this list into the Review Hub's
+// total/alert/todo/briefing/cos tiles, so a swallowed unreadable read reports a
+// confident "0 pending" that is simply false. It is also the base of every
+// read-modify-write (createItem/status updates → `saveItems`), where an
+// unreadable file collapsing to `[]` would destroy every stored review item.
async function loadItems() {
- return readJSONFile(ITEMS_FILE, []);
+ return readJSONFile(ITEMS_FILE, [], { strict: true });
}
/**
diff --git a/server/services/settings.js b/server/services/settings.js
index a603e19d84..37584992bb 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -1,7 +1,6 @@
import { join } from 'path';
-import { access } from 'fs/promises';
import { EventEmitter } from 'events';
-import { safeJSONParse, PATHS, atomicWrite, tryReadFile } from '../lib/fileUtils.js';
+import { safeJSONParse, PATHS, atomicWrite, tryReadFile, tryReadFileStrict } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { isPlainObject, POLLUTING_KEYS } from '../lib/objects.js';
@@ -95,24 +94,13 @@ const loadRaw = async () => {
* exists so unit tests can point it at a temp file without touching real data.
*/
export const readSettingsStrict = async (filePath = SETTINGS_FILE) => {
- const raw = await tryReadFile(filePath);
- if (raw === null) {
- // tryReadFile collapses BOTH an absent file (ENOENT) and a read failure
- // (EACCES / EIO / …) to null. Probe with access() to tell them apart: an
- // ABSENT file is the fresh-install default (auth off), while a file that
- // EXISTS but couldn't be read is corrupt (fail closed).
- try {
- await access(filePath);
- return { present: true, corrupt: true, settings: {} }; // exists but unreadable
- } catch (err) {
- // Only ENOENT proves the file is genuinely absent (fresh install → auth
- // off). Any OTHER access() failure — EACCES because the parent directory
- // lacks search permission, ENOTDIR, EIO — means we could NOT confirm
- // absence, so it must fail closed (corrupt), not be mistaken for absent.
- if (err?.code === 'ENOENT') return { present: false, corrupt: false, settings: {} };
- return { present: true, corrupt: true, settings: {} };
- }
- }
+ // `tryReadFileStrict` keeps the distinction `tryReadFile` collapses, straight
+ // off the read's own errno — no second `access()` probe, which could disagree
+ // with the read it is explaining. `ok: false` = we could NOT confirm absence
+ // (EACCES on the file or a parent dir, ENOTDIR, EIO) → fail closed.
+ const { ok, value: raw } = await tryReadFileStrict(filePath);
+ if (!ok) return { present: true, corrupt: true, settings: {} };
+ if (raw === null) return { present: false, corrupt: false, settings: {} };
// Present and read. safeJSONParse returns null for malformed/empty input; a
// valid-JSON but non-object root (array, string, number) is likewise not a
// settings document — either way, treat it as corrupt rather than reading
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
index 13c1e9d5c7..50b4118310 100644
--- a/server/services/settings.test.js
+++ b/server/services/settings.test.js
@@ -6,27 +6,25 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// serializer is exercised for real — writes are sequential in these tests anyway.
vi.mock('../lib/fileUtils.js', async (importActual) => {
const actual = await importActual();
+ const tryReadFile = vi.fn();
return {
...actual,
atomicWrite: vi.fn(),
- tryReadFile: vi.fn()
+ tryReadFile,
+ // readSettingsStrict reads through the strict twin (#4115) so the
+ // absent-vs-unreadable split comes off the read's own errno instead of a
+ // second access() probe. Default it to MIRROR the mocked tryReadFile — the
+ // per-test content stubs below then drive every read path unchanged, and a
+ // null (nothing on disk) reads as a trustworthy absence. The two tests that
+ // need the unreadable branch override this mock directly.
+ tryReadFileStrict: vi.fn(async (...args) => ({ ok: true, value: await tryReadFile(...args) }))
};
});
-// readSettingsStrict probes with a real access() for the absent-vs-unreadable
-// split, so keep the real implementation as the default and let a single test
-// override it to drive the non-ENOENT branch (see below for why it can't use a
-// real filesystem quirk).
-vi.mock('fs/promises', async (importActual) => {
- const actual = await importActual();
- return { ...actual, access: vi.fn(actual.access) };
-});
-
-import { access } from 'fs/promises';
-import { writeFileSync, mkdtempSync, rmSync } from 'fs';
+import { mkdtempSync, rmSync } from 'fs';
import { join as joinPath } from 'path';
import { tmpdir } from 'os';
-import { atomicWrite, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, tryReadFile, tryReadFileStrict } from '../lib/fileUtils.js';
import { getSettings, updateSettings, updateSettingsWith, reloadSettings, settingsEvents, __resetSettingsCache, readSettingsStrict } from './settings.js';
describe('settings.js', () => {
@@ -39,6 +37,10 @@ describe('settings.js', () => {
// override as needed.
tryReadFile.mockResolvedValue('{}');
atomicWrite.mockResolvedValue();
+ // Re-arm the mirroring default: `clearAllMocks` drops recorded calls but NOT
+ // an implementation a prior test installed via `mockResolvedValue`, so the
+ // unreadable-file stubs below would otherwise leak into every later test.
+ tryReadFileStrict.mockImplementation(async (...args) => ({ ok: true, value: await tryReadFile(...args) }));
});
describe('getSettings', () => {
@@ -533,44 +535,27 @@ describe('settings.js', () => {
// Strict read for the auth gate (#2684): distinguishes absent (auth off) from
// present-but-corrupt (fail closed), which loadRaw()/getSettings() collapse to {}.
// Content comes through the mocked tryReadFile; the absent-vs-unreadable split
- // uses a real access() probe, so those two cases drive a real temp file.
+ // rides `tryReadFileStrict`'s `ok` flag (#4115), so those cases stub it directly.
describe('readSettingsStrict', () => {
let dir;
beforeEach(() => { dir = mkdtempSync(joinPath(tmpdir(), 'portos-strict-')); });
afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
it('reports absent (not corrupt) when the file does not exist', async () => {
- // tryReadFile null + a path that isn't there → access() throws → absent.
- tryReadFile.mockResolvedValue(null);
+ // ENOENT is the one errno that PROVES absence → ok, with a null value.
+ tryReadFileStrict.mockResolvedValue({ ok: true, value: null });
const res = await readSettingsStrict(joinPath(dir, 'nope.json'));
expect(res).toEqual({ present: false, corrupt: false, settings: {} });
});
it('flags a present-but-unreadable file as corrupt (fail-closed signal)', async () => {
- // tryReadFile null (read failed) but the file EXISTS → access() succeeds → corrupt.
- const p = joinPath(dir, 'settings.json');
- writeFileSync(p, '{}');
- tryReadFile.mockResolvedValue(null);
- const res = await readSettingsStrict(p);
- expect(res).toEqual({ present: true, corrupt: true, settings: {} });
- });
-
- it('fails closed when access() errors for a non-ENOENT reason (only ENOENT is absent)', async () => {
- // access() failing does not by itself prove the file is absent — ENOTDIR (a
- // path component is a file), EACCES (parent lacks search permission) and EIO
- // all leave absence unconfirmed, so they must classify as corrupt (fail
- // closed), never as an absent fresh install.
- //
- // Driven through a stubbed access() rather than a real filesystem quirk: the
- // errno for "parent component is a file" is ENOTDIR on POSIX but ENOENT on
- // Windows, so a real path flipped this assertion by platform and failed CI.
- const notADirErr = new Error('ENOTDIR: not a directory');
- notADirErr.code = 'ENOTDIR';
- access.mockRejectedValueOnce(notADirErr);
- tryReadFile.mockResolvedValue(null);
+ // `ok: false` means the read failed for a reason that does NOT prove absence
+ // — EACCES on the file or a parent dir, ENOTDIR, EIO. Absence is unconfirmed,
+ // so it must classify as corrupt (fail closed), never as a fresh install.
+ // This is precisely the state the old access() re-probe had to reconstruct.
+ tryReadFileStrict.mockResolvedValue({ ok: false, value: null });
const res = await readSettingsStrict(joinPath(dir, 'settings.json'));
- expect(res.present).toBe(true);
- expect(res.corrupt).toBe(true);
+ expect(res).toEqual({ present: true, corrupt: true, settings: {} });
});
it('parses a clean settings file', async () => {
diff --git a/server/services/usage.js b/server/services/usage.js
index 2bd84fde45..d070bfa03b 100644
--- a/server/services/usage.js
+++ b/server/services/usage.js
@@ -125,7 +125,13 @@ export function rollupOldDailyActivity(dailyActivity, monthlyActivity, { retenti
export async function loadUsage() {
await ensureDir(DATA_DIR);
- usageData = await readJSONFile(USAGE_FILE, null);
+ // STRICT (#4115): the `!usageData` branch below does not just report an empty
+ // total — it atomically OVERWRITES usage.json with zeros on the same tick. A
+ // swallowed EACCES/EIO would therefore erase every historical session, cost,
+ // and rollup bucket permanently. Only a genuinely ABSENT file is a real fresh
+ // install; a present-but-unreadable one now throws before reaching the write
+ // (the module-load bootstrap at the bottom of this file already logs it).
+ usageData = await readJSONFile(USAGE_FILE, null, { strict: true });
if (!usageData) {
usageData = getEmptyUsage();
await saveUsage();
diff --git a/server/services/videoDownload.js b/server/services/videoDownload.js
index 528776baa0..322a32d033 100644
--- a/server/services/videoDownload.js
+++ b/server/services/videoDownload.js
@@ -82,7 +82,10 @@ export function cancelVideoDownload(jobId) {
/** List downloaded videos — the `source: 'download'` slice of video-history, newest first. */
export async function listDownloads() {
- const history = await loadHistory().catch(() => []);
+ // No `.catch(() => [])`: that re-swallowed exactly what `loadHistory`'s strict
+ // read exists to surface (#4115), turning an unreadable history into a
+ // confident "you have no downloads". Let it bubble to the error middleware.
+ const history = await loadHistory();
return (Array.isArray(history) ? history : []).filter((h) => h?.source === 'download');
}
@@ -93,7 +96,9 @@ export async function listDownloads() {
* (identical lifecycle to a deleted generation).
*/
export async function deleteDownload(id) {
- const history = await loadHistory().catch(() => []);
+ // Same reason as listDownloads: an unreadable history must not answer
+ // "not found" (a 404 the user would read as "already gone").
+ const history = await loadHistory();
const item = (Array.isArray(history) ? history : []).find((h) => h?.id === id);
if (!item || item.source !== 'download') {
throw new ServerError('Downloaded video not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/services/videoGen/history.js b/server/services/videoGen/history.js
index 5a4d8f9003..3a24ee0254 100644
--- a/server/services/videoGen/history.js
+++ b/server/services/videoGen/history.js
@@ -11,7 +11,12 @@ import { PATHS, readJSONFile, atomicWrite } from '../../lib/fileUtils.js';
const HISTORY_FILE = join(PATHS.data, 'video-history.json');
-export const loadHistory = () => readJSONFile(HISTORY_FILE, []);
+// STRICT (#4115): every write to this file goes `loadHistory` → mutate →
+// `saveHistory`, so a present-but-unreadable video-history.json swallowed to `[]`
+// makes the next completed download persist an empty array over the user's whole
+// render history. The Media History page also counts this list ("Show more (N
+// remaining)"), where a fake 0 reads as fact. Absent stays a real first-run empty.
+export const loadHistory = () => readJSONFile(HISTORY_FILE, [], { strict: true });
export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);
// Serialized read-modify-write for the shared history file. `loadHistory` +