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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: let file-backed character skills report a failed read instead of a fake 0 (#2726)
[._.]/ Adam Eivyc44d6e531790
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 99ce478ccd..c0d9174ab2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,7 +2,7 @@## Added-- [issue-2674] **Your Character sheet now has skills that reflect how you actually use PortOS.** Six skills — Wordsmith (universes, Writers Room works, and catalog records), Mentalist (POST), Vitalist (health logging), Strategist (goal discipline), Archivist (Brain/memory), and Auteur (media) — level up from the work you've already done, on a curve where each doubling of use earns a level, so they climb quickly at first and then ask for real commitment. Nothing new is tracked to make this work: each skill reads the stats its domain already keeps, so the skills are accurate from the moment you upgrade rather than starting everyone at zero. A domain you've never touched is honestly level 0, and a domain whose stats can't be read says "Unavailable" rather than pretending it's zero — currently for Wordsmith, Archivist, and Auteur, whose sources report failures; the three file-backed skills can't yet tell an unreadable file from an empty one, which is tracked separately. Skills are computed fresh on every read and never saved or synced between your machines — usage differs per machine, so syncing them would let the laptop you barely open overwrite the desktop you live in.+- [issue-2674] **Your Character sheet now has skills that reflect how you actually use PortOS.** Six skills — Wordsmith (universes, Writers Room works, and catalog records), Mentalist (POST), Vitalist (health logging), Strategist (goal discipline), Archivist (Brain/memory), and Auteur (media) — level up from the work you've already done, on a curve where each doubling of use earns a level, so they climb quickly at first and then ask for real commitment. Nothing new is tracked to make this work: each skill reads the stats its domain already keeps, so the skills are accurate from the moment you upgrade rather than starting everyone at zero. A domain you've never touched is honestly level 0, and a domain whose stats can't be read says "Unavailable" rather than pretending it's zero. Skills are computed fresh on every read and never saved or synced between your machines — usage differs per machine, so syncing them would let the laptop you barely open overwrite the desktop you live in.- [issue-2675] **Your Character sheet now shows the goals you're actually working toward.** A new Life Goals card sits under your metrics and lists your four most urgent active goals with their progress, each linking straight through to Goals. It's a read-only mirror of the goals you already keep — nothing is stored or duplicated on the Character surface, so there's still exactly one place your goals live and one place to change them. Goals are ranked by the same urgency the Goals page uses; if you haven't set a birth date there's no horizon to rank against, so your goals are listed as-is rather than given a made-up order. Completed and abandoned goals drop off, and if you have no active goals the card invites you to set some instead of rendering an empty block. A card that can't reach your goals says so plainly rather than claiming you have none.@@ -30,6 +30,8 @@## Fixed+- [issue-2726] **Your Character sheet's Mentalist, Vitalist, and Strategist can now tell an unreadable file from an empty one.** The sheet promises that a domain it can't read says "Unavailable" rather than pretending you've done nothing — but the three skills backed by files (POST practice, health logging, and goals) couldn't keep that promise: the shared file reader returned an empty default for *every* failure, not just for a file that was never written, so a corrupt or unreadable `post-sessions.json` scored a real-looking "Mentalist — Lv 0, 0 logged". Health was the worst case: all five of its logs could fail and still add up to a perfectly plausible zero. Those reads are now strict — a file that's genuinely absent still counts as the honest zero it is, while one that's present but unreadable or corrupt reports as Unavailable, the same way the database-backed skills always have. The Metrics grid gets the fix for free, since both read the same signals. Nothing else changes behavior: every other screen that reads these files still degrades gracefully to an empty list rather than breaking, which is the right call for a view you're using rather than a number you're being told.+- [issue-2700] **Layered Intelligence runs were being recorded as failures even when they succeeded.** An LI run is a *reasoning* run: it's explicitly told not to commit or open a PR, and hands its result back through a sentinel file instead. But the shared success check only knows how to look for a code commit, and its verdict overrides the run's actual exit code — so every correct LI run was filed as a failure, dragging the loop's success rate toward 0% and skewing anything built on it (task routing, the CoS Learning card, duration estimates). Task types that hand back results programmatically rather than as a commit are now exempt from the commit check, the same way pipeline and media jobs already were. Ordinary code tasks are still held to it. Because the mis-recorded history can't be reconstructed after the fact, installs that already ran the loop get that one bucket cleared on upgrade, so it starts from an honest "no runs recorded yet" rather than a fabricated 0% — no other task type's stats are touched.- [issue-2727] **A Layered Intelligence run that finished cleanly but produced nothing is no longer recorded as a success.** Exempting these reasoning runs from the code-commit check (above) left them judged purely on whether the process exited cleanly — so a run that exited fine but wrote back a missing or unreadable result, or whose follow-up step crashed, still counted as a win and quietly inflated the loop's success rate. These runs are now judged on what they actually hand back: the result was readable and the follow-up step could act on it. A run that returns nothing usable is recorded as the failure it is, a run that delivers is recorded as a success with no commit required, and the "nothing filed this time" outcomes (no proposal, duplicate, out of scope) still count as successes — the run did its job. Output that isn't a real answer at all (a stray sentence where a structured result belongs) is now told apart from a genuine "I looked and there's nothing to propose", instead of both counting as a win. A run whose reasoning was sound but whose issue tracker was simply unreachable still counts as a success — an outage at GitHub isn't the run's fault, and shouldn't drag the loop's score down or pause it. Ordinary code tasks are still held to the commit check, and pipeline and media jobs are unchanged.diff --git a/PLAN.md b/PLAN.mdindex 12de2a6106..447d556218 100644--- a/PLAN.md+++ b/PLAN.md@@ -192,7 +192,10 @@ by `/do:replan --issues`:- [ ] **Re-derive (or clock-adjust) `longevity.timeHorizons` on read, so goal urgency stops decaying silently.** `computeGoalUrgency` (`server/services/identity/goals.js:65-81`) ranks off `timeHorizons.yearsRemaining`, but `getGoalsTree()` (:345) reads the *persisted* horizons via `loadJSON(LONGEVITY_FILE, …)` — and only `deriveLongevity()` (`server/services/identity/longevity.js:22`) ever consults the current date. So `yearsRemaining` is frozen as of the last derive (`setBirthDate`, or an explicit `/longevity/derive`), and every urgency in the app drifts further from the truth the longer that goes unrun — silently, since nothing surfaces when the horizons were last computed. Affects every consumer that ranks or gates on urgency (`getGoalsTree`, `jobGates.js:57`, `goalCheckIn.js:44`, `identity/insights.js`, `telegram.js`, and the Character sheet's Life Goals card), so all of them are consistently stale rather than any one being wrong. Fix shape: either recompute horizons from `birthDate` + today inside `getGoalsTree`/`getLongevity` (cheap — it's arithmetic, not I/O) rather than trusting the stored snapshot, or stamp `derivedAt` and re-derive lazily when it's older than a day. Deferred from #2675: the Character card is a read-only mirror of the goals service and deliberately ranks off the exact source `/goals` uses, so it must not re-derive longevity on its own (that would write on a read path and make the sheet disagree with the page it links to) — this is the goals/longevity feature's own fix, and it wants its own tests.- [ ] **Decide one active-goal predicate and apply it everywhere.** The codebase disagrees on whether a goal with no `status` is active. `server/services/voice/tools/goals.js:26,49` and `client/src/components/character/GoalsCard.jsx` (`isActive`) treat a missing status as active; `jobGates.js:57`, `telegram.js:475,517,588`, `goalCheckIn.js:44`, `identity/insights.js:104,127`, `identity/status.js:89`, and `goals.js:224` / `getGoalsTree`'s own enrichment (:352) all use a strict `status === 'active'` and silently skip it. The shape is reachable: MortalLoom-synced goals are normalized only through `normalizeGoal` (`server/services/identity/store.js:23`), whose `PORTOS_GOAL_DEFAULTS` backfills every field **except** `status`. Consequence today: a MortalLoom user with status-less goals gets them ranked by the voice tool and the Character card, but skipped by check-in scheduling, Telegram digests, insights, and — notably — `getGoalsTree`'s urgency enrichment, so those goals reach the UI un-ranked. Fix shape: either add `status: 'active'` to `PORTOS_GOAL_DEFAULTS` (normalizes at the boundary, one line, makes every strict consumer correct at once — preferred) or export a shared `isActiveGoal(goal)` predicate and route all ten call sites through it. Deferred from #2675 because backfilling the default touches the MortalLoom sync boundary shared with the goals/identity services and deserves its own PR + tests; the card defends itself locally in the meantime.+### Strict-read follow-ups (#2726)+- [ ] **De-dup the three identical `daily-log.json` readers.** `server/services/meatspaceAlcohol.js` (`loadDailyLog`, ~line 142) and `server/services/meatspaceNicotine.js` (`loadDailyLog`, ~line 101) are now character-for-character identical apart from the error label — same `readDailyLogIfEnabled()` MortalLoom probe, same `{ entries: [], lastEntryDate: null }` default, same shape validation — and `server/services/meatspaceHealth.js#getBodyHistory` reads *the same file* (`join(PATHS.meatspace, 'daily-log.json')`) with a third, slightly different inline read. All three now carry a parallel `{ strict }` branch, so the duplication tripled in this PR rather than being introduced by it. Fix shape: extract one `loadMeatspaceDailyLog({ strict })` (a new `server/services/meatspaceDailyLog.js`, or an export from one of the three) and have all three delegate. Deferred from #2726 because each of the three modules' test suites mocks `readJSONFile` at its own module boundary, so the extraction needs those suites re-pointed at the shared module in the same change — a mechanical but wide edit that would have buried the actual strict-read fix under test churn.+- [ ] **Audit the remaining `readJSONFile` callers for the same absent-vs-unreadable conflation.** #2726 explicitly scoped itself to the Character sheet's file-backed signals (`meatspacePost`, `meatspacePostTraining`, `identity/goals`, `meatspaceLoggingStats` + its five domain loaders) and left the rest of the ~100 `readJSONFile` call sites alone. `readJSONFileStrict` / `readJSONFile(…, { strict: true })` now exist in `server/lib/fileUtils.js` for any of them. The ones worth checking first are those whose result is COUNTED or shown as a stat (rather than used as a config fallback, where swallowing is correct) — grep for `readJSONFile` results feeding a `.length`, a `reduce`, or a dashboard/widget number. Also note `tryReadFile` has the same conflation (bare `.catch(() => null)`) and no strict counterpart.### CoS stat-card follow-ups- [ ] **Retire or wire up `StatCard`'s never-passed `activeLabel` prop, and de-dup the two hand-rolled Learning cards.** `activeLabel` (`client/src/components/cos/StatCard.jsx:1`) has **zero callers** across the client — no `activeLabel=` usage and no spread props into `<StatCard>`. It is *visually* rendered only by the default variant (:59-63); the `compact` (:4-22) and `mini` (:24-42) variants honor it only through the `ariaLabel` interpolation at :2 (consumed via `aria-label` at :8 / :28) — i.e. it reaches the accessible name but is never displayed. So it is not fully inert: deleting it changes the accname on two variants. Either delete the prop + its render branch + the `ariaLabel` clause together, or make compact/mini render it. Related: the two Learning cards (`client/src/pages/ChiefOfStaff.jsx` ~512-540 compact, ~836-862 ascii `mini`) are hand-rolled buttons rather than `StatCard`s precisely because StatCard supports neither `onClick` nor a status-driven border color nor a visible sub-label on the compact variant — and each duplicates the same `status === 'critical' ? … : 'warning' ? …` color ternary twice (once for the border, once for the icon). Wiring a visible sub-label slot through all variants plus `onClick`/border-tone props would let both collapse onto StatCard. Deferred from the mobile-overflow fix (which only restructured the compact card's value/label stacking): removing or re-speccing a prop on a shared component used by every CoS stat card is a distinct refactor deserving its own PR + tests, and the overflow fix must not ride on it.diff --git a/server/lib/README.md b/server/lib/README.mdindex 2917e2ee1a..73ef17f0c2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -126,7 +126,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`), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |+| `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`), JSONL append/read/write helpers, dir scans, hashes, 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. || `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. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 1baa622c07..ec5b0891aa 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -314,6 +314,28 @@ export function isValidJSON(str, { allowArray = true } = {}) {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.@@ -322,14 +344,7 @@ export function isValidJSON(str, { allowArray = true } = {}) {* @returns {string} Extracted JSON or '[]' if not found*/export function extractJSONArray(str) {- if (!str) return '[]';- // Look for '[{' (array with objects) first- let jsonStart = str.indexOf('[{');- if (jsonStart < 0) {- // Check for empty array - find '[]' that's not part of ANSI codes like [31m- const emptyMatch = str.match(/\[\](?![0-9])/);- jsonStart = emptyMatch ? str.indexOf(emptyMatch[0]) : -1;- }+ const jsonStart = findJSONArrayStart(str);return jsonStart >= 0 ? str.slice(jsonStart) : '[]';}@@ -377,21 +392,6 @@ export function safeJSONParse(str, defaultValue = null, { allowArray = true, log}}-/**- * Read a JSON file safely with validation and default fallback.- * Combines file reading with safe JSON parsing.- *- * @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- * @returns {Promise<*>} Parsed JSON or default value- *- * @example- * const config = await readJSONFile('./config.json', { port: 3000 });- * const items = await readJSONFile('./items.json', []);- *//*** Read a file, returning null on any error (missing file, permission denied, etc.).*@@ -399,6 +399,10 @@ export function safeJSONParse(str, defaultValue = null, { allowArray = true, log* 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 `readJSONFileStrict` 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@@ -407,22 +411,118 @@ export async function tryReadFile(filePath, encoding = 'utf8') {return readFile(filePath, encoding).catch(() => null);}-export async function readJSONFile(filePath, defaultValue = null, { allowArray = true, logError = true } = {}) {+// 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');++/**+ * 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 CLAUDE.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 readFile(filePath, 'utf-8');} catch (err) {- // ENOENT = file doesn't exist, return default silently+ // ENOENT = file doesn't exist → a trustworthy "nothing here yet", silently.if (err.code === 'ENOENT') {- return defaultValue;+ return { ok: true, value: defaultValue };}- // Log other I/O errors if requestedif (logError) {console.warn(`Failed to read file ${filePath}: ${err.message}`);}- return defaultValue;+ 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 };+ 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 safeJSONParse(content, defaultValue, { allowArray, logError, context: filePath });+ return value;}/**diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 9bae612348..edb24804b7 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -6,12 +6,18 @@ import { tmpdir, homedir } from 'os';import { createHash } from 'crypto';import * as fsPromises from 'fs/promises';// Mock fs/promises so the `ensureDir` regression test can force `mkdir` to-// throw a spurious Windows error. `mkdir` defaults to delegating to the real-// implementation (so every other test in this file is unaffected); individual-// tests override it with `mockRejectedValueOnce`.+// throw a spurious Windows error, and the readJSONFileStrict tests can force a+// specific `readFile` errno (EACCES can't be provoked portably — chmod 000 is a+// no-op for root, which is how the container CI runs). Both default to delegating+// to the real implementation (so every other test in this file is unaffected);+// individual tests override with `mockRejectedValueOnce`.vi.mock('fs/promises', async (importOriginal) => {const actual = await importOriginal();- return { ...actual, mkdir: vi.fn((...args) => actual.mkdir(...args)) };+ return {+ ...actual,+ mkdir: vi.fn((...args) => actual.mkdir(...args)),+ readFile: vi.fn((...args) => actual.readFile(...args)),+ };});import {assertSafeFilename,@@ -25,6 +31,7 @@ import {safeJSONLParse,createCachedStore,readJSONFile,+ readJSONFileStrict,readJSONLFile,appendJSONLine,readJSONLines,@@ -302,6 +309,207 @@ describe('fileUtils', () => {const result = await readJSONFile(filePath, {}, { allowArray: false });expect(result).toEqual({});});++ it('returns the caller’s array default for garbage, not a manufactured []', async () => {+ // The noisy-output extraction used to manufacture a literal '[]' from text+ // holding no array, so a non-empty array default was silently replaced by an+ // empty one. The documented contract is "default value if the file is+ // invalid" — every in-tree caller passes `[]`, where the two agree.+ const filePath = join(testDir, 'garbage.json');+ await writeFile(filePath, 'not json at all');++ expect(await readJSONFile(filePath, ['fallback'])).toEqual(['fallback']);+ });++ it('still extracts an array out of noisy output (pm2 jlist with ANSI codes)', async () => {+ // Real ANSI output leads with ESC, not '[' — the extraction is deliberately+ // skipped for text already starting with '[' (it would be self-defeating on a+ // genuine JSON array), so `\x1b` here is load-bearing, not decoration.+ const filePath = join(testDir, 'noisy.json');+ await writeFile(filePath, '\x1b[31mwarn\x1b[0m [{"pid":1}]');++ expect(await readJSONFile(filePath, [])).toEqual([{ pid: 1 }]);+ });+ });++ // #2726: `readJSONFile` collapses "absent", "unreadable", and "corrupt" into the+ // same default, so a caller counting records can't tell a real empty from a failed+ // read and reports a fake 0. These pin the distinction the strict variant restores.+ describe('readJSONFileStrict', () => {+ const testDir = join(tmpdir(), 'fileutils-strict-test-' + Date.now());+ let warnSpy;++ beforeEach(async () => {+ await mkdir(testDir, { recursive: true });+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(async () => {+ warnSpy.mockRestore();+ await rm(testDir, { recursive: true, force: true });+ });++ const eacces = () => Object.assign(new Error('permission denied'), { code: 'EACCES' });++ it('reports ENOENT as a TRUSTWORTHY empty — absent is not a failure', async () => {+ const result = await readJSONFileStrict(join(testDir, 'never-written.json'), { sessions: [] });+ expect(result).toEqual({ ok: true, value: { sessions: [] } });+ });++ it('does not log for a genuinely absent file', async () => {+ await readJSONFileStrict(join(testDir, 'never-written.json'), []);+ expect(warnSpy).not.toHaveBeenCalled();+ });++ it('reports EACCES as NOT ok — an unreadable file is not an empty one', async () => {+ const filePath = join(testDir, 'locked.json');+ await writeFile(filePath, '{"sessions": [{"id": "s1"}]}');+ fsPromises.readFile.mockRejectedValueOnce(eacces());++ const result = await readJSONFileStrict(filePath, { sessions: [] });+ // `value` still carries the default so an ok-indifferent caller behaves as+ // before; `ok: false` is what makes the failure legible.+ expect(result).toEqual({ ok: false, value: { sessions: [] } });+ });++ 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.+ const result = await readJSONFileStrict(testDir, []);+ expect(result.ok).toBe(false);+ });++ it('reports malformed JSON as NOT ok — corrupt bytes are not an empty collection', async () => {+ const filePath = join(testDir, 'corrupt.json');+ await writeFile(filePath, '{"incomplete":');++ expect(await readJSONFileStrict(filePath, { fallback: true }))+ .toEqual({ ok: false, value: { fallback: true } });+ });++ it('reports a truncated (empty) file as NOT ok', async () => {+ const filePath = join(testDir, 'empty.json');+ await writeFile(filePath, '');++ expect((await readJSONFileStrict(filePath, [])).ok).toBe(false);+ });++ it('reports a parsed file as ok with its value', async () => {+ const filePath = join(testDir, 'valid.json');+ await writeFile(filePath, '{"sessions": [{"id": "s1"}]}');++ expect(await readJSONFileStrict(filePath, { sessions: [] }))+ .toEqual({ ok: true, value: { sessions: [{ id: 's1' }] } });+ });++ it('reports a legitimately empty collection as ok — the whole point', async () => {+ const filePath = join(testDir, 'empty-list.json');+ await writeFile(filePath, '[]');++ expect(await readJSONFileStrict(filePath, ['fallback'])).toEqual({ ok: true, value: [] });+ });++ it('distinguishes a file that legitimately CONTAINS the default from a failed read', async () => {+ const filePath = join(testDir, 'same-as-default.json');+ await writeFile(filePath, '{"sessions":[]}');++ // Both return the same `value`; only `ok` tells them apart — which is why the+ // parse sentinel can't be an in-band marker like null.+ expect(await readJSONFileStrict(filePath, { sessions: [] })).toEqual({ ok: true, value: { sessions: [] } });+ fsPromises.readFile.mockRejectedValueOnce(eacces());+ expect(await readJSONFileStrict(filePath, { sessions: [] })).toEqual({ ok: false, value: { sessions: [] } });+ });++ it('keeps readJSONFile’s noisy-output extraction for array defaults', async () => {+ // safeJSONParse keys extraction off `Array.isArray(defaultValue)`, and the+ // strict path passes a non-array sentinel as its fallback — so this pins that+ // the extraction still runs against the caller's real default (pm2 jlist).+ const filePath = join(testDir, 'noisy.json');+ await writeFile(filePath, '\x1b[31mwarning\x1b[0m [{"id":1}]');++ expect(await readJSONFileStrict(filePath, [])).toEqual({ ok: true, value: [{ id: 1 }] });+ });++ it('does NOT manufacture a trustworthy empty from noise holding no array', async () => {+ // extractJSONArray returns a literal '[]' when it finds nothing, which parses+ // cleanly — an array-defaulted strict read would otherwise report corrupt bytes+ // as `ok: true, value: []`, silently un-stricting itself.+ const filePath = join(testDir, 'garbage.json');+ await writeFile(filePath, 'not json at all');++ expect(await readJSONFileStrict(filePath, [])).toEqual({ ok: false, value: [] });+ });++ it('honours allowArray: false', async () => {+ const filePath = join(testDir, 'array.json');+ await writeFile(filePath, '[1, 2, 3]');++ expect(await readJSONFileStrict(filePath, {}, { allowArray: false }))+ .toEqual({ ok: false, value: {} });+ });++ it('stays silent when logError is false', async () => {+ const filePath = join(testDir, 'corrupt.json');+ await writeFile(filePath, '{"incomplete":');+ await readJSONFileStrict(filePath, {}, { logError: false });+ expect(warnSpy).not.toHaveBeenCalled();+ });+ });++ // 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).+ describe('readJSONFile with { strict: true }', () => {+ const testDir = join(tmpdir(), 'fileutils-strictopt-test-' + Date.now());+ let warnSpy;++ beforeEach(async () => {+ await mkdir(testDir, { recursive: true });+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(async () => {+ warnSpy.mockRestore();+ await rm(testDir, { recursive: true, force: true });+ });++ it('returns the default for an absent file — strict does not mean paranoid', async () => {+ const result = await readJSONFile(join(testDir, 'never-written.json'), { sessions: [] }, { strict: true });+ expect(result).toEqual({ sessions: [] });+ });++ it('throws for an unreadable file instead of returning a fake empty', async () => {+ const filePath = join(testDir, 'locked.json');+ await writeFile(filePath, '{"sessions": []}');+ fsPromises.readFile.mockRejectedValueOnce(Object.assign(new Error('permission denied'), { code: 'EACCES' }));++ await expect(readJSONFile(filePath, { sessions: [] }, { strict: true }))+ .rejects.toThrow(/Unreadable JSON file/);+ });++ it('throws for corrupt JSON', async () => {+ const filePath = join(testDir, 'corrupt.json');+ await writeFile(filePath, 'not json at all');++ await expect(readJSONFile(filePath, [], { strict: true })).rejects.toThrow(/Unreadable JSON file/);+ });++ it('returns the parsed value when the read succeeds', async () => {+ const filePath = join(testDir, 'valid.json');+ await writeFile(filePath, '{"sessions":[{"id":"s1"}]}');++ expect(await readJSONFile(filePath, { sessions: [] }, { strict: true }))+ .toEqual({ sessions: [{ id: 's1' }] });+ });++ it('leaves every existing (non-strict) caller swallowing exactly as before', async () => {+ const filePath = join(testDir, 'corrupt.json');+ await writeFile(filePath, '{"incomplete":');++ expect(await readJSONFile(filePath, { fallback: true })).toEqual({ fallback: true });+ fsPromises.readFile.mockRejectedValueOnce(Object.assign(new Error('nope'), { code: 'EACCES' }));+ expect(await readJSONFile(filePath, { fallback: true })).toEqual({ fallback: true });+ });});describe('readJSONLFile', () => {diff --git a/server/services/characterSignals.js b/server/services/characterSignals.jsindex 78c330a91b..2847007762 100644--- a/server/services/characterSignals.js+++ b/server/services/characterSignals.js@@ -22,13 +22,15 @@* downed Postgres is hit once per request rather than once per skill AND once per metric* that reads it.*- * **Known gap (#2726).** Only the DB-backed readers (`universeCount`, `workCount`,- * `catalogStats`, `memoryCount`, `assetCount`) actually reject on failure. `postSessions`,- * `postTraining`, `loggingStats`, and `goals` bottom out in `readJSONFile`, which returns its- * default on *every* read error — so an unreadable file is indistinguishable here from an- * empty one. Documented at length in `characterSkills.js`; the strict-read variants that- * close it are tracked in #2726. Nothing here changes when they land — the moment a getter- * starts rejecting, both registries already classify it correctly.+ * **Every reader must be able to report failure (#2726).** That propagation is only worth+ * anything if the readers actually reject when they can't read. The DB-backed ones always+ * did (a failed `query()` throws), but the file-backed four bottom out in `readJSONFile`,+ * which returns its default on *every* read error — so an unreadable file arrived here+ * indistinguishable from an empty one and scored a real-looking 0. They now pass+ * `{ strict: true }`, which throws on a present-but-unreadable/corrupt file while still+ * treating a genuinely absent one (ENOENT) as the trustworthy empty it is. This is the ONLY+ * place that opts in: every other caller of those getters keeps the swallow-and-default+ * behavior, which is correct for a UI that should degrade rather than break.*/import { countUniverses } from './universeBuilder.js';@@ -50,20 +52,24 @@ import { userLocalToday } from '../lib/timezone.js';* All nine are tallies or already-aggregated summaries, never listings: `countUniverses` /* `countWorks` / `countMemories` / `countAssets` are `COUNT(*)`s (#2729), so no consumer can* accidentally materialize every record just to read a `.length`.+ *+ * The file-backed readers pass `{ strict: true }` — see the header. Keep it on any reader+ * added here whose source can swallow a read error, or the signal silently becomes a lie+ * the consumers have no way to detect.*/export const SIGNAL_READERS = {universeCount: () => countUniverses(),workCount: () => countWorks(),catalogStats: () => getCatalogStats(),- postSessions: () => getPostSessions(),- postTraining: () => getAllTrainingEntries(),+ postSessions: () => getPostSessions(undefined, undefined, { strict: true }),+ postTraining: () => getAllTrainingEntries({ strict: true }),// Today's `YYYY-MM-DD` in the USER's configured timezone — the same day boundary// meatspacePost.js anchors its streaks to. Deriving "today" from the server's local clock// instead would let the Character sheet's POST streak disagree with the Progress page's by// a day for any user whose configured timezone isn't the server's.postToday: () => userLocalToday(),- loggingStats: () => getLoggingStats(),- goals: () => getGoals(),+ loggingStats: () => getLoggingStats({ strict: true }),+ goals: () => getGoals({ strict: true }),memoryCount: () => countMemories({}),assetCount: () => countAssets(),};diff --git a/server/services/characterSkills.js b/server/services/characterSkills.jsindex bca238a9f9..e9b959485c 100644--- a/server/services/characterSkills.js+++ b/server/services/characterSkills.js@@ -25,22 +25,10 @@* the metrics grid (#2676) — which derive from the same nine signals — cost ONE read per* signal per request, not one per consumer.*- * **Known gap in that guarantee (#2726).** `readSkill` honours whatever a domain- * reports, but it can only *detect* a failure the getter actually surfaces — by- * rejecting, or by resolving something non-countable. Today only the DB-backed- * getters do that:- *- * - reports failure → `wordsmith`, `archivist`, `auteur` (a failed `query()` throws)- * - SWALLOWS failure → `mentalist`, `vitalist`, `strategist`- *- * The swallowing three bottom out in `readJSONFile`, which returns its default on- * *every* read error and not just ENOENT — so a corrupt or unreadable- * `post-sessions.json` is indistinguishable here from "no sessions yet" and reports a- * real-looking level 0. Closing it needs strict-read variants threaded through the- * shared file getters (the `readVideoHistoryStrict` `{ ok, list }` precedent in- * `mediaAssetIndex/db.js`), which is a wider change than this registry — tracked in- * #2726. Nothing here needs to change when it lands: the moment a getter starts- * reporting failure, `readSkill` already classifies it correctly.+ * That guarantee holds for all six domains, DB- and file-backed alike: `readSkill` can only+ * classify a failure the getter actually surfaces, so the file-backed signals read strictly+ * (#2726) and reject on a present-but-unreadable file rather than returning the empty+ * default that would score as a real level 0. See `characterSignals.js`.*/import { createSignalContext } from './characterSignals.js';diff --git a/server/services/characterSkills.test.js b/server/services/characterSkills.test.jsindex bc5ff576bc..fa8009c12e 100644--- a/server/services/characterSkills.test.js+++ b/server/services/characterSkills.test.js@@ -1,4 +1,32 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';+import { EventEmitter } from 'events';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++// Anchor the real data files the "real read path" suite at the bottom drives at a+// temp tree. Only that suite reads them — every other test here runs against the+// stubbed getters below and never touches a file.+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'character-skills-test-'));+const MEATSPACE_DIR = join(TEST_DATA_ROOT, 'meatspace');+const IDENTITY_DIR = join(TEST_DATA_ROOT, 'digital-twin');++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), {+ dataRoot: TEST_DATA_ROOT,+ extraOverrides: () => ({ meatspace: MEATSPACE_DIR, digitalTwin: IDENTITY_DIR }),+ }));++// MortalLoom gates every health/goals read on settings. Pin it OFF so the loaders+// deterministically fall through to the local files this suite controls — otherwise+// a real settings read decides whether the test exercises the file path at all.+vi.mock('./settings.js', () => ({+ getSettings: () => Promise.resolve({}),+ settingsEvents: new EventEmitter(),+}));++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));// Each domain's stat getter is stubbed so the registry can be driven to its three// interesting states — populated, empty, and read-failure — without any of the real@@ -312,3 +340,125 @@ describe('getCharacterSkills — stat-read failure (must NOT collapse into a fak});});});++// ============================================================================+// #2726 — the REAL read path+//+// Every failure test above drives a stubbed getter that rejects. That proves+// "IF a getter reports failure THEN the skill is unavailable" — but it says+// nothing about whether a getter EVER reports failure, and until #2726 the three+// file-backed ones could not: they bottomed out in `readJSONFile`, which returns+// its default on every read error, so an unreadable post-sessions.json scored a+// real-looking level 0. The stub was a mode the real code could not enter, and+// the suite passed anyway.+//+// These tests close that gap by unmocking the domain modules and driving real+// files off disk. Each case is asserted as a PAIR — absent vs corrupt — because+// only the pair is honest: a corrupt-file test alone would also pass if the+// module graph were throwing for some unrelated reason, and the absent case+// proves the read genuinely reaches (and trusts) the file.+// ============================================================================+describe('the real read path: an unreadable file is unavailable, an absent one is 0 (#2726)', () => {+ // Load the registry against the REAL file-backed domain modules. The DB-backed+ // getters stay mocked (they need Postgres); only the file-backed graph is real,+ // which is exactly the wiring under test.+ const loadRealRegistry = async () => {+ vi.doUnmock('./meatspacePost.js');+ vi.doUnmock('./meatspacePostTraining.js');+ vi.doUnmock('./meatspaceLoggingStats.js');+ vi.doUnmock('./identity/goals.js');+ vi.resetModules();+ return (await import('./characterSkills.js')).getCharacterSkills();+ };++ const skillOf = async (id) => byId(await loadRealRegistry(), id);++ beforeEach(() => {+ // A clean tree per test: no file exists, so every read is a genuine ENOENT.+ rmSync(MEATSPACE_DIR, { recursive: true, force: true });+ rmSync(IDENTITY_DIR, { recursive: true, force: true });+ mkdirSync(MEATSPACE_DIR, { recursive: true });+ mkdirSync(IDENTITY_DIR, { recursive: true });+ });++ describe('mentalist (POST sessions + training log)', () => {+ it('is a real level 0 when the files were never written', async () => {+ expect(await skillOf('mentalist')).toMatchObject({ level: 0, value: 0, unavailable: false });+ });++ it('is unavailable when post-sessions.json is corrupt', async () => {+ writeFileSync(join(MEATSPACE_DIR, 'post-sessions.json'), '{"sessions": [{"id":');+ expect(await skillOf('mentalist')).toMatchObject({ level: null, value: null, unavailable: true });+ });++ it('is unavailable when the training log is corrupt', async () => {+ writeFileSync(join(MEATSPACE_DIR, 'post-training-log.json'), 'not json at all');+ expect(await skillOf('mentalist')).toMatchObject({ level: null, value: null, unavailable: true });+ });++ it('counts real sessions off disk — the read reaches the file it claims to', async () => {+ // Without this, "level 0" above could mean the read never happened at all.+ writeFileSync(join(MEATSPACE_DIR, 'post-sessions.json'), JSON.stringify({+ sessions: [{ id: 's1', date: '2026-01-01' }, { id: 's2', date: '2026-01-02' }],+ }));+ expect(await skillOf('mentalist')).toMatchObject({ value: 2, unavailable: false });+ });+ });++ describe('vitalist (five health domains)', () => {+ it('is a real level 0 when no health file was ever written', async () => {+ expect(await skillOf('vitalist')).toMatchObject({ level: 0, value: 0, unavailable: false });+ });++ // The structurally worst case: all five domains could fail and still produce a+ // perfectly plausible totalLogged: 0, because getLoggingStats caught each one.+ it.each([+ ['daily-log.json', 'alcohol/nicotine/body'],+ ['workouts.json', 'workouts'],+ ['health-metrics.json', 'blood pressure'],+ ])('is unavailable when %s is corrupt (%s)', async (filename) => {+ writeFileSync(join(MEATSPACE_DIR, filename), '{"entries": [');+ expect(await skillOf('vitalist')).toMatchObject({ level: null, value: null, unavailable: true });+ });++ it('counts real health logs off disk', async () => {+ writeFileSync(join(MEATSPACE_DIR, 'workouts.json'), JSON.stringify({+ workouts: [{ date: '2026-01-01', type: 'run' }, { date: '2026-01-02', type: 'run' }],+ }));+ expect(await skillOf('vitalist')).toMatchObject({ value: 2, unavailable: false });+ });+ });++ describe('strategist (goals)', () => {+ it('is a real level 0 when goals.json was never written', async () => {+ expect(await skillOf('strategist')).toMatchObject({ level: 0, value: 0, unavailable: false });+ });++ it('is unavailable when goals.json is corrupt', async () => {+ writeFileSync(join(IDENTITY_DIR, 'goals.json'), '{"goals": [{"id"');+ expect(await skillOf('strategist')).toMatchObject({ level: null, value: null, unavailable: true });+ });++ it('is unavailable when goals.json is truncated to empty', async () => {+ // A 0-byte file is a partial write, not "no goals" — the pre-#2726 read+ // reported it as an empty goals list.+ writeFileSync(join(IDENTITY_DIR, 'goals.json'), '');+ expect(await skillOf('strategist')).toMatchObject({ level: null, value: null, unavailable: true });+ });++ it('counts real goal discipline off disk', async () => {+ writeFileSync(join(IDENTITY_DIR, 'goals.json'), JSON.stringify({+ goals: [{ id: 'g1', title: 'Example goal', checkIns: [{ id: 'c1' }, { id: 'c2' }], progressHistory: [{ id: 'p1' }] }],+ }));+ expect(await skillOf('strategist')).toMatchObject({ value: 3, unavailable: false });+ });+ });++ it('contains a failure to its own skill — one corrupt file does not blank the sheet', async () => {+ writeFileSync(join(MEATSPACE_DIR, 'post-sessions.json'), 'corrupt');+ const skills = await loadRealRegistry();+ expect(byId(skills, 'mentalist').unavailable).toBe(true);+ expect(byId(skills, 'vitalist')).toMatchObject({ level: 0, unavailable: false });+ expect(byId(skills, 'strategist')).toMatchObject({ level: 0, unavailable: false });+ });+});diff --git a/server/services/identity/goals.js b/server/services/identity/goals.jsindex a79590cf4b..e131342007 100644--- a/server/services/identity/goals.js+++ b/server/services/identity/goals.js@@ -176,8 +176,19 @@ function hasAncestorCycle(goals, goalId, newParentId) {// === Service Functions ===-export async function getGoals() {- const data = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when goals.json is+ * present-but-unreadable/corrupt rather than reporting it as "no goals filed"+ * (#2726). Off by default — every existing caller wants the empty fallback.+ */+export async function getGoals(options) {+ const data = await loadJSON(GOALS_FILE, DEFAULT_GOALS, options);+ // A goals.json that parsed but carries no goals array is as untrustworthy as one+ // that failed to parse — validate before the count downstream trusts it. Only+ // under strict: the non-strict path keeps its existing behavior for this shape.+ if (options?.strict && !Array.isArray(data?.goals)) {+ throw new Error(`Goals malformed: ${GOALS_FILE}`);+ }// Lazy migration: backfill parentId, tags, linkedActivities on goals missing themlet needsSave = false;for (const goal of data.goals) {diff --git a/server/services/identity/store.js b/server/services/identity/store.jsindex 18bf3481fb..52b17e27ec 100644--- a/server/services/identity/store.js+++ b/server/services/identity/store.js@@ -1,5 +1,5 @@import { join } from 'path';-import { atomicWrite, PATHS, ensureDir, safeJSONParse, tryReadFile } from '../../lib/fileUtils.js';+import { atomicWrite, PATHS, ensureDir, readJSONFileStrict } from '../../lib/fileUtils.js';import { isMortalLoomEnabled, mlArrayIfEnabled, mlReplace } from '../mortalLoomStore.js';// === Goal normalization defaults ===@@ -85,9 +85,26 @@ export async function ensureIdentityDir() {await ensureDir(IDENTITY_DIR);}-export async function loadJSON(filePath, defaultVal) {- const raw = await tryReadFile(filePath);- const data = raw ? safeJSONParse(raw, structuredClone(defaultVal)) : structuredClone(defaultVal);+/**+ * @param {string} filePath+ * @param {*} defaultVal+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when `filePath`+ * exists but can't be read or parsed, instead of silently returning `defaultVal`.+ * Off by default so every existing caller keeps the fallback. Callers that COUNT+ * what they load opt in, so an unreadable file can't report as an empty one+ * (#2726). A genuinely absent file (never written) still returns `defaultVal`+ * under strict — that IS a trustworthy empty.+ */+export async function loadJSON(filePath, defaultVal, { strict = false } = {}) {+ // `readJSONFileStrict` rather than tryReadFile+safeJSONParse: both of those+ // swallow, so together they can't tell "no goals yet" from "goals.json is+ // corrupt" — and this is the read the Strategist skill counts. Passing `null` as+ // its default (rather than `defaultVal`) keeps "the file gave us nothing" legible+ // here: a parsed file can never BE null (bare `null` fails validation), so `value`+ // is null exactly when the file was absent, unreadable, or corrupt.+ const { ok, value } = await readJSONFileStrict(filePath, null);+ if (strict && !ok) throw new Error(`Unreadable identity file: ${filePath}`);+ const data = value ?? structuredClone(defaultVal);// When MortalLoom iCloud sync is enabled, the goals array is sourced from// MortalLoom.json; birthDate and lifeExpectancy metadata stay in local PortOS.if (filePath === GOALS_FILE) {diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.jsindex 043559a4ea..548c11f4d2 100644--- a/server/services/meatspaceAlcohol.js+++ b/server/services/meatspaceAlcohol.js@@ -139,12 +139,24 @@ export function computeRollingAverages(entries, sex = 'male') {// === File I/O ===-async function loadDailyLog() {+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when the daily log+ * is present-but-unreadable/corrupt instead of substituting an empty log. Off by+ * default so the UI keeps degrading gracefully; the health-logging COUNT opts in,+ * because a fake 0 there reads as "you have never logged anything" (#2726).+ */+async function loadDailyLog({ strict = false } = {}) {const ml = await readDailyLogIfEnabled();if (ml) return ml;- const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false });- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { entries: [], lastEntryDate: null };- if (!Array.isArray(raw.entries)) raw.entries = [];+ const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false, strict });+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ if (strict) throw new Error(`Alcohol daily log malformed: ${DAILY_LOG_FILE}`);+ return { entries: [], lastEntryDate: null };+ }+ if (!Array.isArray(raw.entries)) {+ if (strict) throw new Error(`Alcohol daily log malformed: ${DAILY_LOG_FILE}`);+ raw.entries = [];+ }return raw;}@@ -185,8 +197,11 @@ export async function getAlcoholSummary() {return averageCache;}-export async function getDailyAlcohol(from, to) {- const log = await loadDailyLog();+/**+ * @param {{ strict?: boolean }} [options] - see `loadDailyLog` (#2726).+ */+export async function getDailyAlcohol(from, to, options) {+ const log = await loadDailyLog(options);let entries = (log.entries || []).filter(e => e.alcohol?.drinks?.length > 0);if (from) entries = entries.filter(e => e.date >= from);diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.jsindex f647b274d7..34d84d21d4 100644--- a/server/services/meatspaceHealth.js+++ b/server/services/meatspaceHealth.js@@ -67,10 +67,18 @@ export async function saveBloodTests(data) {// === Body Composition ===-export async function getBodyHistory() {+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when the daily log+ * is present-but-unreadable/corrupt rather than reporting zero body entries+ * (#2726). Off by default — existing callers keep the empty fallback.+ */+export async function getBodyHistory({ strict = false } = {}) {const ml = await mlArrayIfEnabled('bodyEntries');if (ml) return ml.map(({ id, ...rest }) => rest).sort(byDate);- const log = await readJSONFile(DAILY_LOG_FILE, { entries: [] });+ const log = await readJSONFile(DAILY_LOG_FILE, { entries: [] }, { strict });+ if (strict && !Array.isArray(log?.entries)) {+ throw new Error(`Health daily log malformed: ${DAILY_LOG_FILE}`);+ }return (log.entries || []).filter(e => e.body && Object.keys(e.body).length > 0).map(e => ({ date: e.date, ...e.body }))@@ -185,8 +193,15 @@ export async function removeEyeExam(index) {// `workouts` array key, and adding one would need a coordinated MortalLoom// schema change). Voice/CoS log workouts here via addWorkout().-export async function getWorkouts() {- const data = await readJSONFile(WORKOUTS_FILE, { workouts: [] });+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when workouts.json+ * is present-but-unreadable/corrupt rather than reporting zero workouts (#2726).+ */+export async function getWorkouts({ strict = false } = {}) {+ const data = await readJSONFile(WORKOUTS_FILE, { workouts: [] }, { strict });+ if (strict && !Array.isArray(data?.workouts)) {+ throw new Error(`Workouts malformed: ${WORKOUTS_FILE}`);+ }return (data.workouts || []).slice().sort(byDate);}@@ -215,9 +230,17 @@ export async function addWorkout({ date, type, durationMinutes, intensity, notes// upserted by date so multiple readings on the same day (e.g. from Apple Health// sync + manual entry) merge into one row.-export async function getBloodPressureHistory() {+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when the health+ * metrics file is present-but-unreadable/corrupt rather than reporting zero blood+ * pressure readings (#2726).+ */+export async function getBloodPressureHistory({ strict = false } = {}) {const ml = await mlArrayIfEnabled('healthMetrics');- const source = ml ?? (await readJSONFile(HEALTH_METRICS_FILE, { entries: [] })).entries;+ const source = ml ?? (await readJSONFile(HEALTH_METRICS_FILE, { entries: [] }, { strict })).entries;+ if (strict && !Array.isArray(source)) {+ throw new Error(`Health metrics malformed: ${HEALTH_METRICS_FILE}`);+ }return source.filter(m => m?.bloodPressureSystolic != null && m?.bloodPressureDiastolic != null).map(m => ({diff --git a/server/services/meatspaceLoggingStats.js b/server/services/meatspaceLoggingStats.jsindex 1a003ce58a..caad97d721 100644--- a/server/services/meatspaceLoggingStats.js+++ b/server/services/meatspaceLoggingStats.js@@ -16,12 +16,14 @@ import { getWorkouts, getBodyHistory, getBloodPressureHistory } from './meatspac// Each domain contributes an array of `{ date: 'YYYY-MM-DD', ... }` records.// `label` is the human-facing name shown per-domain in the widget.+// `load(options)` forwards `{ strict }` so a caller that counts these can refuse an+// unreadable file rather than a fake empty one (#2726).const DOMAINS = [- { key: 'alcohol', label: 'Alcohol', load: () => getDailyAlcohol() },- { key: 'nicotine', label: 'Nicotine', load: () => getDailyNicotine() },- { key: 'workouts', label: 'Workouts', load: () => getWorkouts() },- { key: 'body', label: 'Body', load: () => getBodyHistory() },- { key: 'bloodPressure', label: 'Blood Pressure', load: () => getBloodPressureHistory() },+ { key: 'alcohol', label: 'Alcohol', load: (o) => getDailyAlcohol(undefined, undefined, o) },+ { key: 'nicotine', label: 'Nicotine', load: (o) => getDailyNicotine(undefined, undefined, o) },+ { key: 'workouts', label: 'Workouts', load: (o) => getWorkouts(o) },+ { key: 'body', label: 'Body', load: (o) => getBodyHistory(o) },+ { key: 'bloodPressure', label: 'Blood Pressure', load: (o) => getBloodPressureHistory(o) },];// Consecutive days (ending today, or yesterday if today is empty) that have at@@ -69,9 +71,28 @@ function calculateLongestStreak(loggedDates) {return longest;}-export async function getLoggingStats() {+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` propagates a domain's read+ * failure instead of substituting an empty entry list for it (#2726).+ *+ * The default per-domain `.catch(() => [])` is right for the dashboard widget: one+ * unreadable file shouldn't blank the whole streak card. It is wrong for anything+ * that COUNTS these — all five domains can fail and still produce a perfectly+ * plausible `totalLogged: 0`, which reads as "you have never logged anything"+ * rather than "we could not tell". Under strict the first failure rejects, and the+ * caller renders that as explicitly unavailable.+ */+export async function getLoggingStats({ strict = false } = {}) {+ const loadEntries = async (d) => {+ if (!strict) return (await d.load().catch(() => [])) || [];+ const entries = await d.load({ strict: true });+ // Validate, don't coerce: a non-array here means the loader returned something+ // uncountable, which under strict must not silently become a zero.+ if (!Array.isArray(entries)) throw new Error(`${d.key} logs unreadable`);+ return entries;+ };const perDomain = await Promise.all(- DOMAINS.map(async (d) => ({ ...d, entries: (await d.load().catch(() => [])) || [] }))+ DOMAINS.map(async (d) => ({ ...d, entries: await loadEntries(d) })));const today = new Date();diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.jsindex 2399af1ce2..ad302295d5 100644--- a/server/services/meatspaceNicotine.js+++ b/server/services/meatspaceNicotine.js@@ -98,12 +98,24 @@ function recalcDayTotal(entry) {// === File I/O ===-async function loadDailyLog() {+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when the daily log+ * is present-but-unreadable/corrupt instead of substituting an empty log. Off by+ * default so the UI keeps degrading gracefully; the health-logging COUNT opts in,+ * because a fake 0 there reads as "you have never logged anything" (#2726).+ */+async function loadDailyLog({ strict = false } = {}) {const ml = await readDailyLogIfEnabled();if (ml) return ml;- const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false });- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { entries: [], lastEntryDate: null };- if (!Array.isArray(raw.entries)) raw.entries = [];+ const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false, strict });+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ if (strict) throw new Error(`Nicotine daily log malformed: ${DAILY_LOG_FILE}`);+ return { entries: [], lastEntryDate: null };+ }+ if (!Array.isArray(raw.entries)) {+ if (strict) throw new Error(`Nicotine daily log malformed: ${DAILY_LOG_FILE}`);+ raw.entries = [];+ }return raw;}@@ -140,8 +152,11 @@ export async function getNicotineSummary() {return averageCache;}-export async function getDailyNicotine(from, to) {- const log = await loadDailyLog();+/**+ * @param {{ strict?: boolean }} [options] - see `loadDailyLog` (#2726).+ */+export async function getDailyNicotine(from, to, options) {+ const log = await loadDailyLog(options);let entries = (log.entries || []).filter(e => e.nicotine?.items?.length > 0);if (from) entries = entries.filter(e => e.date >= from);diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 6cf7e59335..db981783d5 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -192,15 +192,27 @@ export async function updatePostConfig(updates) {// SESSIONS// =============================================================================-async function loadSessions() {- const raw = await readJSONFile(SESSIONS_FILE, { sessions: [] }, { allowArray: false });+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when+ * post-sessions.json is present-but-unreadable/corrupt instead of falling back to+ * an empty session list. Off by default: every existing caller wants the fallback+ * (an unreadable file shouldn't break a drill you're mid-way through). Callers+ * that COUNT sessions opt in — a fake 0 there is a lie, not a default (#2726).+ */+async function loadSessions({ strict = false } = {}) {+ const raw = await readJSONFile(SESSIONS_FILE, { sessions: [] }, { allowArray: false, strict });+ // Under strict, a file that parsed to a non-countable shape is as untrustworthy as+ // one that failed to parse — validate rather than silently substituting an empty.+ if (strict && (!isPlainObject(raw) || !Array.isArray(raw.sessions))) {+ throw new Error(`POST sessions malformed: ${SESSIONS_FILE}`);+ }const data = isPlainObject(raw) ? raw : { sessions: [] };if (!Array.isArray(data.sessions)) data.sessions = [];return data;}-export async function getPostSessions(from, to) {- const data = await loadSessions();+export async function getPostSessions(from, to, options) {+ const data = await loadSessions(options);let sessions = data.sessions;if (from) sessions = sessions.filter(s => s.date >= from);if (to) sessions = sessions.filter(s => s.date <= to);diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.jsindex f853751789..2d5561412a 100644--- a/server/services/meatspacePostTraining.js+++ b/server/services/meatspacePostTraining.js@@ -15,8 +15,16 @@ import { getUnifiedActivityStreak } from './meatspacePost.js';const MEATSPACE_DIR = PATHS.meatspace;const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');-async function loadTrainingLog() {- const data = await readJSONFile(TRAINING_LOG_FILE, { entries: [] }, { allowArray: false });+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when the training+ * log is present-but-unreadable/corrupt rather than falling back to an empty log.+ * See `loadSessions` in meatspacePost.js for the rationale (#2726).+ */+async function loadTrainingLog({ strict = false } = {}) {+ const data = await readJSONFile(TRAINING_LOG_FILE, { entries: [] }, { allowArray: false, strict });+ if (strict && !Array.isArray(data?.entries)) {+ throw new Error(`POST training log malformed: ${TRAINING_LOG_FILE}`);+ }if (!Array.isArray(data.entries)) data.entries = [];return data;}@@ -137,8 +145,11 @@ export async function getTrainingEntries(limit = 20) {* All training-log entries in chronological (append) order — the raw feed the* unified progress aggregation reads (both meatspacePostTraining and* meatspacePostMemory practice write to the same `post-training-log.json`).+ *+ * @param {{ strict?: boolean }} [options] - `strict: true` throws rather than+ * reporting an unreadable log as zero entries (#2726).*/-export async function getAllTrainingEntries() {- const data = await loadTrainingLog();+export async function getAllTrainingEntries(options) {+ const data = await loadTrainingLog(options);return data.entries;}