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: finish the unreadable-file audit — the last seven load/mutate/save readers (#4115)
[._.]/ Adam Eivy56e8ac2a3c56
diff --git a/.changelog/next/fixed-issue-4115.md b/.changelog/next/fixed-issue-4115.mdindex 30b74df42b..0eb835078a 100644--- a/.changelog/next/fixed-issue-4115.md+++ b/.changelog/next/fixed-issue-4115.md@@ -1 +1,2 @@- 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+- Finished the unreadable-data-file audit: goal scorecard/check-in, brain settings, CoS task learning, app activity, Telegram check-ins and the media job queue no longer read a corrupt file as empty — and no longer overwrite it with that empty defaultdiff --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.mdindex d568ae4006..b3305ee6ff 100644--- 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@@ -91,6 +91,17 @@ consumers (routes, widgets, schedulers) and to any write back to the same path.| `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. |+| `services/taskLearning/store.js#loadLearningData` | Every routing outcome, duration sample and failure signature is recorded by `load → mutate → saveLearningData`; the next save wrote a fresh `DEFAULT_LEARNING_DATA` over the entire learning history. The 5s cache also re-served the fabricated default. |+| `services/taskLearning/store.js#loadDismissedRecommendations` | `dismissRecommendation` / `restoreRecommendation` change one key and write the whole map back — an unreadable file silently un-dismissed every recommendation on the next dismissal. |+| `services/goalScorecard.js#getSettings` | The base of `updateSettings` (`get → merge → write`), so a corrupt file wrote `DEFAULT_SETTINGS` over the user's provider, model and week-start on the next PATCH. |+| `services/goalScorecard.js#getRuleOverrides` | Hand-authored overrides that are never regenerated. An empty read presented an empty rules editor whose next save persisted the emptiness. |+| `services/goalScorecard.js#loadGoals` | Goals are what every event is scored *against*. Zero rules means every hour buckets as unaligned, and `computeWeeklyScorecard` persists — and splices into the Brain daily log — a confident "0% goal-aligned". |+| `services/goalScorecard.js#getScorecard`, `#refreshScorecardNarrative` | Both reported `not_computed` — the UI's "click Compute" state — for an artifact that exists but could not be read. The narrative path is additionally the base of a write back to the same artifact. |+| `services/goalCheckIn.js#runGoalCheckIn` | Reported `{ checked: 0 }` off a fake empty `goals.json`, indistinguishable from a user with no active goals; the run also writes the whole file back. |+| `services/brainStorage.js#loadMeta` | `updateMeta` is `load → spread → saveMeta`, so a corrupt `meta.json` wrote the shipped defaults over every brain setting — and the result was cached for `CACHE_TTL_MS`, outliving the read that produced it. |+| `services/appActivity.js#loadAppActivity` | Every writer is `load → mutate → save`; a swallowed read wrote `DEFAULT_ACTIVITY` over every app's cooldown, agent binding and lifetime review stats, *and* dropped the whole fleet off cooldown so the CoS immediately re-reviewed all of it. The shallow `{ ...DEFAULT_ACTIVITY }` spread was replaced with a `structuredClone` in the same pass — the default's `apps`/`global` were shared objects that the first write against an absent file mutated in place. |+| `services/telegram.js#loadCheckins` | `handleCheckinResponse` is `load → push → atomicWrite`, so answering one check-in against a fake empty log wrote a one-entry file over the whole history. Uses a **null sentinel rather than a throw**: every caller runs inside a `bot.on(...)` handler that node-telegram-bot-api never awaits, so a rejection would leak as an unhandled rejection instead of reaching a caller. Callers bail and tell the user nothing was overwritten. A readable-but-shapeless file (no `checkins` array) gets the same `null` — we can't interpret it, so we must not replace it either. |+| `services/mediaJobQueue/index.js#initMediaJobQueue` | Init ends with `await persist()`, which writes the FULL in-memory snapshot — so an unreadable `media-jobs.json` booted an empty queue and immediately wrote `{"jobs":[]}` over the real one, losing the archive and orphaning every job the reconcile would have reattached. Cannot throw: init is an awaited step of `runPostRouteSequence`, where a rejection is fatal (`process.exit`). Instead it boots empty, reports, and **latches persistence off** for the process so the file survives for recovery. |### Reviewed and deliberately left swallowing@@ -117,14 +128,43 @@ consumers (routes, widgets, schedulers) and to any write back to the same path.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`.+### Audit status++Complete. The first pass converted the 14 sites in the upper half of the table+and named seven more as follow-ups; the second pass worked through all seven —+`taskLearning/store.js` (both files), `goalScorecard.js` (all four files),+`goalCheckIn.js`, `brainStorage.js#loadMeta`, `telegram.js#loadCheckins`,+`appActivity.js`, `mediaJobQueue/index.js#initMediaJobQueue` — and every one+turned out to be a genuine member of the class, so all seven are converted+above. Nothing from the original triage remains unclassified: every+`readJSONFile` / `tryReadFile` call site in `server/` is now either in the+converted table, in a documented-safe category above, or covered by the+category rule for classifying a new one.++### Failure shapes, and when a throw is the wrong answer++The second pass added two postures the first pass had no instance of, both+driven by *where the caller runs* rather than by what the value feeds:++- **A caller outside the request lifecycle that nothing awaits** must use a+ null sentinel, not a throw. `telegram.js`'s readers run inside+ `bot.on(...)` handlers that node-telegram-bot-api never awaits, so a+ rejection becomes an unhandled rejection instead of reaching anyone who could+ act on it.+- **A boot step whose rejection is fatal** must degrade rather than throw.+ `initMediaJobQueue` is an awaited step of `runPostRouteSequence`, where any+ rejection calls `onFatal` (`process.exit(1)`) — so a bad permission bit on one+ snapshot file would take the whole server down. It reports, boots empty, and+ latches its writer off so the unreadable file is preserved rather than+ overwritten. **"Refuse to write" is the fallback whenever "refuse to+ continue" is too expensive.**++A related trap worth stating once: **the default value must not be shared+mutable state.** `loadAppActivity` returned `{ ...DEFAULT_ACTIVITY }`, whose+`apps` and `global` were the module-level objects themselves, so the first+write against an *absent* file mutated the default in place and leaked into+every later load. Deep-clone a default that callers mutate (the neighbouring+`loadLearningData` already did, via `structuredClone`).## Consequences@@ -133,7 +173,21 @@ read-modify-write) but were left out to keep this change reviewable:- **Exhaustive `vi.mock('../lib/fileUtils.js', () => ({ … }))` factories mustlist 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.+ on the mock" throw, and the second pass had to add `readJSONFileStrict` to+ three (`routes/pipeline.test.js`, `services/autonomousJobs.test.js`,+ `services/telegram.test.js`). Prefer the `importActual`-spread form in new+ tests.+- **A `makePathsProxy` temp-root mock in a suite with static imports needs a+ lazily-allocated root.** `vi.mock` is hoisted above the file's `import`+ statements, so a `const TEST_DATA_ROOT = mkdtempSync(…)` is still in its TDZ+ when the module under test resolves its file paths at load. Use the `var` ++ hoisted-function-declaration form (`dataRoot: () => getTempRoot()`), as+ `brainStorage.test.js` does. Suites that `await import(...)` the module under+ test after the top-level `const` are unaffected.+- **Corrupt JSON — not a `chmod`/EACCES fixture — is how these tests produce+ "present but unreadable".** It exercises the identical `ok: false` branch,+ fails the parse the same way on every platform including Windows CI, and needs+ no privileges.- The remaining ~200 swallowing call sites are documented above by categoryrather than individually, so a future reader can classify a *new* call sitewithout re-deriving the rule.diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 1ec56d62b2..5869800ad9 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -23,6 +23,11 @@ tryReadFile: vi.fn().mockResolvedValue(null),safeJSONParse: vi.fn((s, fallback) => { try { return JSON.parse(s); } catch { return fallback; } }),atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+ // Strict twin of readJSONFile (#4115). Same exhaustive-factory constraint as+ // tryReadFileStrict above: several services in this route graph now read+ // through it, so an omitted export is a hard throw. `ok: true` mirrors the+ // swallowing reader — this fake store never fails a read.+ readJSONFileStrict: vi.fn(async (path, fallback) => ({ ok: true, value: fileStore.has(path) ? fileStore.get(path) : fallback })),}));// Both mocks needed: vitest.setup.js's global `instances.js` mock uses importOriginal, which leaves the per-file `peerSync.js` mock unable to suppress the createSeries dynamic-import hoist error alone.diff --git a/server/services/appActivity.js b/server/services/appActivity.jsindex 39ef3bebdf..9c25f54d08 100644--- a/server/services/appActivity.js+++ b/server/services/appActivity.js@@ -25,8 +25,20 @@ const DEFAULT_ACTIVITY = {export async function loadAppActivity() {await ensureDir(DATA_DIR);- const loaded = await readJSONFile(ACTIVITY_FILE, null);- return loaded ? { ...DEFAULT_ACTIVITY, ...loaded } : { ...DEFAULT_ACTIVITY };+ // Strict (#4115): every writer here is `loadAppActivity → mutate →+ // saveAppActivity`, so a swallowed unreadable file writes DEFAULT_ACTIVITY+ // over every app's cooldown, active-agent binding and lifetime review stats —+ // which also drops every app off cooldown at once, so the CoS immediately+ // re-reviews the whole fleet. Throwing skips the cycle and keeps the file.+ const loaded = await readJSONFile(ACTIVITY_FILE, null, { strict: true });+ // structuredClone, not a spread. `{ ...DEFAULT_ACTIVITY }` is shallow, so the+ // returned `apps` and `global` were the SAME objects on every call: on an+ // absent file the first `updateAppActivity`/`markIdleReviewStarted` mutated+ // the module-level default in place, and every later load inherited that+ // app map and its incremented totalReviews. Same "the default must never+ // become shared mutable state" family as the strict read above.+ const base = structuredClone(DEFAULT_ACTIVITY);+ return loaded ? { ...base, ...loaded } : base;}/**diff --git a/server/services/appActivity.test.js b/server/services/appActivity.test.jsindex b41973e830..81a80e1322 100644--- a/server/services/appActivity.test.js+++ b/server/services/appActivity.test.js@@ -13,7 +13,7 @@*/import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';-import { mkdtempSync, rmSync, mkdirSync } from 'fs';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { makePathsProxy } from '../lib/mockPathsDataRoot.js';@@ -152,3 +152,79 @@ describe('releaseAppReviewMarker (issue #989)', () => {expect(result).toBeNull();});});++/**+ * Strict-read regression (#4115).+ *+ * Every writer in appActivity.js is `loadAppActivity → mutate →+ * saveAppActivity`. While the loader swallowed unreadable files, a corrupt+ * app-activity.json read as DEFAULT_ACTIVITY, so the very next marker write+ * atomicWrote a one-app file over the whole fleet's cooldowns, agent bindings+ * and lifetime review stats — and, because every app then read as off-cooldown,+ * the CoS immediately re-reviewed all of them.+ *+ * Corrupt JSON (rather than a chmod/EACCES setup) is the portable way to+ * produce the present-but-unreadable state: it fails the parse identically on+ * every platform and needs no privileges.+ */+describe('appActivity strict reads (#4115)', () => {+ const ACTIVITY_FILE = join(TEST_DATA_ROOT, 'cos', 'app-activity.json');+ const CORRUPT = '{"apps": {"app-1": {"cooldownUntil"';++ beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(join(TEST_DATA_ROOT, 'cos'), { recursive: true });+ writeFileSync(ACTIVITY_FILE, CORRUPT);+ });++ it('loadAppActivity rejects instead of reporting an empty fleet', async () => {+ await expect(appActivity.loadAppActivity()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('a marker write leaves the unreadable file byte-for-byte intact', async () => {+ await expect(appActivity.markAppReviewCooldown('app-1')).rejects.toThrow(/Unreadable JSON file/);+ expect(+ readFileSync(ACTIVITY_FILE, 'utf8'),+ 'the corrupt file must survive — overwriting it is the data loss this fixes'+ ).toBe(CORRUPT);+ });++ it('isAppOnCooldown rejects rather than reporting every app as free to re-review', async () => {+ await expect(appActivity.isAppOnCooldown('app-1', 60_000)).rejects.toThrow(/Unreadable JSON file/);+ });++ it('markIdleReviewStarted does not reset the lifetime totalReviews counter', async () => {+ await expect(appActivity.markIdleReviewStarted()).rejects.toThrow(/Unreadable JSON file/);+ expect(readFileSync(ACTIVITY_FILE, 'utf8')).toBe(CORRUPT);+ });++ it('still treats a genuinely absent file as a real empty fleet', async () => {+ rmSync(ACTIVITY_FILE, { force: true });+ const activity = await appActivity.loadAppActivity();+ expect(activity.apps, 'ENOENT is the one errno that proves absence').toEqual({});+ expect(activity.global.totalReviews).toBe(0);+ });+});++/**+ * The default value must not become shared mutable state (#4115).+ *+ * `loadAppActivity` used to return `{ ...DEFAULT_ACTIVITY }` — a shallow copy+ * whose `apps` / `global` were the module-level objects themselves, so the+ * first write against an absent file mutated the default in place and leaked+ * into every later load.+ */+describe('appActivity default isolation (#4115)', () => {+ beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });+ });++ it('a write against an absent file does not leak into the next load', async () => {+ await appActivity.markAppReviewCooldown('app-leak');+ rmSync(join(TEST_DATA_ROOT, 'cos', 'app-activity.json'), { force: true });+ const fresh = await appActivity.loadAppActivity();+ expect(fresh.apps, 'the default app map must be a fresh object each load').toEqual({});+ expect(fresh.global.totalReviews).toBe(0);+ });+});diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.jsindex d23372dc14..588ca056d9 100644--- a/server/services/autonomousJobs.test.js+++ b/server/services/autonomousJobs.test.js@@ -13,6 +13,10 @@ tryReadFile: vi.fn().mockResolvedValue(null),// the absent-file shape, matching `tryReadFile`'s null above.tryReadFileStrict: vi.fn().mockResolvedValue({ ok: true, value: null }),readJSONFile: vi.fn(),+ // Strict twin of readJSONFile (#4115). Same exhaustive-factory constraint as+ // tryReadFileStrict above. Left un-stubbed by default (undefined value) to+ // match readJSONFile's bare vi.fn(); tests that need a value set it per case.+ readJSONFileStrict: vi.fn().mockResolvedValue({ ok: true, value: undefined }),ensureDir: vi.fn().mockResolvedValue(),atomicWrite: vi.fn().mockResolvedValue(),safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw) } catch { return fallback } },diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex ffbea3d2ed..5b9267cded 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -206,7 +206,11 @@ export async function loadMeta() {await ensureBrainDir();- const loaded = await readJSONFile(FILES.meta, null);+ // Strict (#4115): `updateMeta` is `loadMeta → spread updates → saveMeta`, so a+ // swallowed unreadable meta.json writes DEFAULT_META over every brain setting+ // on the next update — and the result is cached for CACHE_TTL_MS, so the fake+ // default outlives the read that produced it.+ const loaded = await readJSONFile(FILES.meta, null, { strict: true });cache.data = loaded ? { ...DEFAULT_META, ...loaded } : { ...DEFAULT_META };cache.timestamp = Date.now();return cache.data;diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex 1fd33bdbcf..25045c0d4c 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -1,5 +1,5 @@-import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';-import { mkdtempSync, rmSync } from 'fs';+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { makePathsProxy } from '../lib/mockPathsDataRoot.js';@@ -540,3 +540,57 @@ async function rawRecord(type, id) {const map = await brainStorage.getRawRecords(type);return map[id];}++/**+ * Strict-read regression (#4115).+ *+ * `updateMeta` is `loadMeta → spread updates → saveMeta`. While the loader+ * swallowed unreadable files, a corrupt meta.json read as DEFAULT_META, so the+ * next settings update atomicWrote the shipped defaults over the user's+ * configured provider, model, digest times and review schedule. The result was+ * also cached for CACHE_TTL_MS, so the fabricated default outlived the read+ * that produced it.+ *+ * Corrupt JSON is the portable way to produce "present but unreadable" — it+ * fails the parse identically on every platform and needs no privileges.+ */+describe('brainStorage meta strict reads (#4115)', () => {+ const CORRUPT = '{"defaultProvider": "ollama",';+ const metaPath = () => join(getTempRoot(), 'brain', 'meta.json');++ beforeEach(() => {+ mkdirSync(join(getTempRoot(), 'brain'), { recursive: true });+ writeFileSync(metaPath(), CORRUPT);+ brainStorage.invalidateAllCaches();+ });++ afterEach(() => {+ rmSync(metaPath(), { force: true });+ brainStorage.invalidateAllCaches();+ });++ it('loadMeta rejects instead of fabricating the shipped defaults', async () => {+ await expect(brainStorage.loadMeta()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('updateMeta leaves the unreadable file byte-for-byte intact', async () => {+ await expect(brainStorage.updateMeta({ confidenceThreshold: 0.9 })).rejects.toThrow(/Unreadable JSON file/);+ expect(+ readFileSync(metaPath(), 'utf8'),+ 'overwriting the user settings we failed to read is the data loss this fixes'+ ).toBe(CORRUPT);+ });++ it('does not cache a fabricated default for later readers', async () => {+ await expect(brainStorage.loadMeta()).rejects.toThrow();+ // A cached default would make this second call resolve with DEFAULT_META.+ await expect(brainStorage.loadMeta()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('still treats a genuinely absent meta.json as first-run defaults', async () => {+ rmSync(metaPath(), { force: true });+ brainStorage.invalidateAllCaches();+ const meta = await brainStorage.loadMeta();+ expect(meta.confidenceThreshold, 'ENOENT is the one errno that proves absence').toBe(0.6);+ });+});diff --git a/server/services/goalCheckIn.js b/server/services/goalCheckIn.jsindex 129381ddda..9fab6a9acd 100644--- a/server/services/goalCheckIn.js+++ b/server/services/goalCheckIn.js@@ -40,7 +40,11 @@ Respond with JSON only (no markdown fences): { "assessment": "string", "recommenexport async function runGoalCheckIn({ background = false } = {}) {const { getActiveProvider } = await import('./providers.js');- const goals = await readJSONFile(GOALS_FILE, { goals: [] });+ // Strict (#4115): a swallowed unreadable goals.json reports "no active goals"+ // and the check-in reports `{ checked: 0 }` — indistinguishable from a user+ // who genuinely has none. The run also writes `goals` straight back, so any+ // future non-empty path off a fake default would persist the emptiness.+ const goals = await readJSONFile(GOALS_FILE, { goals: [] }, { strict: true });const activeGoals = goals.goals.filter(g => g.status === 'active' && g.targetDate);if (!activeGoals.length) {diff --git a/server/services/goalCheckIn.test.js b/server/services/goalCheckIn.test.jsnew file mode 100644index 0000000000..c4ba2c4e65--- /dev/null+++ b/server/services/goalCheckIn.test.js@@ -0,0 +1,96 @@+/**+ * Strict-read regression for the weekly goal check-in (#4115).+ *+ * `runGoalCheckIn` reads goals.json, appends a check-in to each active goal,+ * and writes the whole file back. While the read swallowed unreadable files, a+ * corrupt goals.json read as `{ goals: [] }` and the run reported+ * `{ checked: 0 }` — indistinguishable from a user who genuinely has no active+ * goals, and the check-in silently never happened.+ *+ * Corrupt JSON is the portable way to produce "present but unreadable": it+ * fails the parse identically on every platform and needs no privileges.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++// Allocate lazily: `vi.mock` is hoisted above this file's static imports, so a+// `const` here would still be in its TDZ when goalCheckIn.js resolves+// GOALS_FILE at module load. `var` + a function declaration both hoist without+// a TDZ, so the factory can call it.+var tempRoot; // eslint-disable-line no-var+function getTempRoot() {+ if (!tempRoot) tempRoot = mkdtempSync(join(tmpdir(), 'goal-checkin-test-'));+ return tempRoot;+}++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => getTempRoot() }));++const provider = { id: 'p1', defaultModel: 'test-model' };+vi.mock('./providers.js', () => ({ getActiveProvider: vi.fn(async () => provider) }));++vi.mock('../lib/aiProvider.js', () => ({+ callProviderAISimple: vi.fn(async () => ({ text: '{"assessment":"ok","recommendations":["keep going"]}' })),+ parseLLMJSON: (text) => JSON.parse(text),+}));++vi.mock('./notifications.js', () => ({+ addNotification: vi.fn(async () => {}),+ NOTIFICATION_TYPES: { HEALTH_ISSUE: 'health_issue' },+}));++import { runGoalCheckIn } from './goalCheckIn.js';++afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });++describe('runGoalCheckIn strict reads (#4115)', () => {+ const CORRUPT = '{"goals": [{"id": "g1", "status": "active"';+ const goalsFile = () => join(getTempRoot(), 'digital-twin', 'goals.json');++ const activeGoal = {+ id: 'g1',+ title: 'Example Goal',+ status: 'active',+ targetDate: '2027-01-01',+ createdAt: '2026-01-01T00:00:00.000Z',+ progress: 40,+ };++ beforeEach(() => {+ rmSync(getTempRoot(), { recursive: true, force: true });+ mkdirSync(join(getTempRoot(), 'digital-twin'), { recursive: true });+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });++ it('rejects instead of reporting a check-in over zero goals', async () => {+ writeFileSync(goalsFile(), CORRUPT);+ await expect(runGoalCheckIn()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('leaves the unreadable goals file byte-for-byte intact', async () => {+ writeFileSync(goalsFile(), CORRUPT);+ await expect(runGoalCheckIn()).rejects.toThrow(/Unreadable JSON file/);+ expect(+ readFileSync(goalsFile(), 'utf8'),+ 'goals.json is the digital twin — a failed read must never rewrite it'+ ).toBe(CORRUPT);+ });++ it('still reports a genuine zero when the file is absent', async () => {+ const result = await runGoalCheckIn();+ expect(result, 'ENOENT is the one errno that proves absence').toEqual({ checked: 0 });+ });++ it('runs and persists normally when the file is readable', async () => {+ writeFileSync(goalsFile(), JSON.stringify({ goals: [activeGoal] }));+ const result = await runGoalCheckIn();+ expect(result.checked).toBe(1);+ const written = JSON.parse(readFileSync(goalsFile(), 'utf8'));+ expect(written.goals[0].checkIns).toHaveLength(1);+ expect(written.goals[0].checkIns[0].assessment).toBe('ok');+ });+});diff --git a/server/services/goalScorecard.js b/server/services/goalScorecard.jsindex 382fbc8873..6865d71c93 100644--- a/server/services/goalScorecard.js+++ b/server/services/goalScorecard.js@@ -381,7 +381,10 @@ export function formatScorecardDigestLine(scorecard) {export async function getSettings() {await ensureDir(INSIGHTS_DIR);- const loaded = await readJSONFile(SETTINGS_FILE, null);+ // Strict (#4115): `updateSettings` is `getSettings → merge → atomicWrite`, so a+ // swallowed unreadable file writes DEFAULT_SETTINGS over the user's configured+ // provider/model/week-start on the next settings PATCH.+ const loaded = await readJSONFile(SETTINGS_FILE, null, { strict: true });return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };}@@ -399,7 +402,10 @@ export async function updateSettings(partial = {}) {// User-editable per-goal mapping overrides. Shape: { [goalId]: { keywords?,// personIds?, subcalendarIds?, enabled? } }. Stored locally, never federated.export async function getRuleOverrides() {- const loaded = await readJSONFile(RULES_FILE, null);+ // Strict (#4115): these overrides are hand-authored and never regenerated. An+ // unreadable file would present the rules editor with an empty override set,+ // and the very next save from that editor would persist the emptiness.+ const loaded = await readJSONFile(RULES_FILE, null, { strict: true });return loaded && typeof loaded === 'object' ? loaded : {};}@@ -411,8 +417,12 @@ export async function saveRuleOverrides(overrides = {}) {}// Load active goals from digital-twin. Returns [] when the file is missing.+// Strict (#4115): goals are what every event is scored AGAINST. An unreadable+// goals.json yields zero mapping rules, so every hour buckets as unaligned and+// `computeWeeklyScorecard` persists — and splices into the Brain daily log — a+// confident "0% goal-aligned" that is a read failure, not a real week.async function loadGoals() {- const data = await readJSONFile(GOALS_FILE, null);+ const data = await readJSONFile(GOALS_FILE, null, { strict: true });return Array.isArray(data?.goals) ? data.goals : [];}@@ -426,7 +436,10 @@ export async function getEffectiveRules() {// ─── Read path (disk-only) ───────────────────────────────────────────────────export async function getScorecard() {- const cached = await readJSONFile(SCORECARD_FILE, null);+ // Strict (#4115): `not_computed` is the UI's "click Compute" state. Reporting+ // it for a present-but-corrupt artifact tells the user their scorecard was+ // never built, when the truth is that we could not read it.+ const cached = await readJSONFile(SCORECARD_FILE, null, { strict: true });if (!cached) return { available: false, reason: 'not_computed' };return { ...cached, available: true };}@@ -541,7 +554,11 @@ function buildNarrativePrompt(scorecard) {* @param {string} [model]*/export async function refreshScorecardNarrative(providerId, model) {- const scorecard = await readJSONFile(SCORECARD_FILE, null);+ // Strict (#4115): this is the base of a read-modify-write — the narrative is+ // spliced onto the artifact and the whole thing is written back. A swallowed+ // read cannot reach the write (the `!scorecard` guard returns first), but it+ // would report `not_computed` for a corrupt artifact and invite a recompute.+ const scorecard = await readJSONFile(SCORECARD_FILE, null, { strict: true });if (!scorecard) return { available: false, reason: 'not_computed' };if (!scorecard.totals || scorecard.totals.totalSeconds === 0) {return { available: false, reason: 'no_activity' };diff --git a/server/services/goalScorecard.test.js b/server/services/goalScorecard.test.jsindex 8d8356a0fa..ae571e3c82 100644--- a/server/services/goalScorecard.test.js+++ b/server/services/goalScorecard.test.js@@ -1,4 +1,25 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++// Allocate the temp dir lazily on first PATHS read. `vi.mock` is hoisted above+// this file's static imports, so a `const` initialized here would still be in+// its TDZ when goalScorecard.js resolves its file paths at module load. `var` ++// a function declaration both hoist without a TDZ, so the factory can call it.+var tempRoot; // eslint-disable-line no-var+function getTempRoot() {+ if (!tempRoot) tempRoot = mkdtempSync(join(tmpdir(), 'goal-scorecard-test-'));+ return tempRoot;+}++// The pure helpers below touch no disk, but the strict-read block at the end of+// this file exercises the real file-backed loaders — so re-root every data/-+// rooted PATHS member (insights/, digital-twin/) into a temp tree.+vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => getTempRoot() }));+import {shiftIsoDate,isoWeekStart,@@ -13,8 +34,15 @@ import {formatScorecardDigestLine,NOMINAL_SECONDS,TREND_WEEKS,+ getSettings,+ updateSettings,+ getRuleOverrides,+ getEffectiveRules,+ getScorecard,} from './goalScorecard.js';+afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });+const UTC = 'UTC';const ev = (over = {}) => ({@@ -333,3 +361,78 @@ describe('constants', () => {expect(TREND_WEEKS).toBeGreaterThanOrEqual(2);});});++/**+ * Strict-read regression (#4115).+ *+ * Four file-backed loaders here fed either a displayed number or a write back+ * to the same file while they swallowed unreadable files:+ *+ * - `getSettings` is the base of `updateSettings` (`get → merge → write`), so+ * a corrupt settings file wrote DEFAULT_SETTINGS over the user's provider,+ * model and week-start on the next PATCH.+ * - `getRuleOverrides` holds hand-authored overrides that are never+ * regenerated; an empty read presented an empty rules editor whose next+ * save persisted the emptiness.+ * - `loadGoals` (reached via `getEffectiveRules`) supplies the goals every+ * hour is scored AGAINST — zero rules means every hour buckets as+ * unaligned, and computeWeeklyScorecard persists (and splices into the+ * Brain daily log) a confident "0% goal-aligned".+ * - `getScorecard` reported `not_computed` — the UI's "click Compute" state —+ * for an artifact that exists but could not be read.+ *+ * Corrupt JSON is the portable way to produce "present but unreadable": it+ * fails the parse identically on every platform and needs no privileges.+ */+describe('goalScorecard strict reads (#4115)', () => {+ const CORRUPT = '{"weekStartsOn": 1,';+ const INSIGHTS = () => join(getTempRoot(), 'insights');+ const TWIN = () => join(getTempRoot(), 'digital-twin');+ const settingsFile = () => join(INSIGHTS(), 'goal-scorecard-settings.json');+ const rulesFile = () => join(INSIGHTS(), 'goal-scorecard-rules.json');+ const scorecardFile = () => join(INSIGHTS(), 'goal-scorecard.json');+ const goalsFile = () => join(TWIN(), 'goals.json');++ beforeEach(() => {+ rmSync(getTempRoot(), { recursive: true, force: true });+ mkdirSync(INSIGHTS(), { recursive: true });+ mkdirSync(TWIN(), { recursive: true });+ });++ it('getSettings rejects instead of fabricating the shipped defaults', async () => {+ writeFileSync(settingsFile(), CORRUPT);+ await expect(getSettings()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('updateSettings leaves the unreadable settings file byte-for-byte intact', async () => {+ writeFileSync(settingsFile(), CORRUPT);+ await expect(updateSettings({ weekStartsOn: 0 })).rejects.toThrow(/Unreadable JSON file/);+ expect(+ readFileSync(settingsFile(), 'utf8'),+ 'writing defaults over settings we failed to read is the data loss this fixes'+ ).toBe(CORRUPT);+ });++ it('getRuleOverrides rejects instead of reporting "no overrides configured"', async () => {+ writeFileSync(rulesFile(), CORRUPT);+ await expect(getRuleOverrides()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('getEffectiveRules rejects rather than scoring every hour against zero goals', async () => {+ writeFileSync(goalsFile(), CORRUPT);+ await expect(getEffectiveRules()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('getScorecard rejects instead of reporting the artifact was never computed', async () => {+ writeFileSync(scorecardFile(), CORRUPT);+ await expect(getScorecard()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('still treats genuinely absent files as real first-run empties', async () => {+ const settings = await getSettings();+ expect(settings, 'ENOENT is the one errno that proves absence').toBeTruthy();+ expect(await getRuleOverrides()).toEqual({});+ expect(await getScorecard()).toEqual({ available: false, reason: 'not_computed' });+ expect((await getEffectiveRules()).rules).toEqual([]);+ });+});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex e2506219ee..1db2f6b7e3 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -32,7 +32,7 @@ import { EventEmitter } from 'events';import { randomUUID } from 'crypto';import { unlink } from 'fs/promises';import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';-import { PATHS, readJSONFile, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';+import { PATHS, readJSONFileStrict, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';import { SSE_HEADERS } from '../../lib/sseHeaders.js';import { reapAndCleanDetachedDirs } from '../../lib/detachedSpawn.js';import {@@ -268,7 +268,15 @@ export function listJobs({ status, kind, owner } = {}) {// (e.g. completed→running). Chaining ensures every snapshot reflects the// state at its enqueue time, in submission order.let persistChain = Promise.resolve();+// Set when the boot read of JOBS_FILE was untrustworthy (#4115). Every persist()+// writes the FULL in-memory snapshot, so persisting on top of a queue we failed+// to restore would replace the real jobs file with whatever this process happens+// to hold — the classic "unreadable read becomes an empty write". Latching the+// writer off preserves the file for the user to recover or delete; the queue+// still runs normally in memory for the life of the process.+let persistBlocked = false;function persist() {+ if (persistBlocked) return persistChain;persistChain = persistChain.then(persistImpl, persistImpl);return persistChain;}@@ -304,7 +312,18 @@ export async function initMediaJobQueue() {// Read the codex parallel limit before the worker starts so the first// drain tick honors the user's configured value, not the default.await refreshCodexParallelLimit().catch(() => {});- const data = await readJSONFile(JOBS_FILE, { jobs: [] });+ // Strict (#4115). A swallowed unreadable jobs file boots an empty queue and+ // the `await persist()` at the end of this init writes that emptiness over+ // the real snapshot — losing the archive and orphaning every job the reload+ // below would have reconciled. This init is an awaited step of+ // `runPostRouteSequence`, where a rejection is FATAL (process.exit), so a+ // bad permission bit on one snapshot file must not take the server down:+ // report it, boot an empty queue, and latch persistence off instead.+ const { ok, value: data } = await readJSONFileStrict(JOBS_FILE, { jobs: [] });+ if (!ok) {+ persistBlocked = true;+ console.error(`❌ media-job queue: ${JOBS_FILE} is present but unreadable — starting empty and NOT persisting, so the file is preserved`);+ }const persistedJobs = Array.isArray(data?.jobs) ? data.jobs : [];const restartedFailedIds = [];// #1332: training jobs whose detached trainer survived the restart, to be@@ -1117,6 +1136,9 @@ export function __resetForTests() {// Reset the persist chain so a leftover rejection from a previous test's// ENOENT writes doesn't poison subsequent persist() calls.persistChain = Promise.resolve();+ // Un-latch the persistence block (#4115) — a test that booted on an unreadable+ // jobs file would otherwise leave every later test's queue unable to persist.+ persistBlocked = false;}// Test-only deterministic settle hook. EventEmitter terminal handlers anddiff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex ea6c5884a1..4883c35f48 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -1074,6 +1074,65 @@ describe('cancelJob running-Codex branch', () => {});});+/**+ * Strict-read regression (#4115).+ *+ * `initMediaJobQueue` ends with `await persist()`, and persist() writes the+ * FULL in-memory snapshot. While the boot read swallowed unreadable files, a+ * corrupt media-jobs.json booted an empty queue and that first persist+ * atomicWrote `{"jobs":[]}` over the real snapshot — losing the archive and+ * orphaning every job the reconcile would have reattached or failed.+ *+ * Init is an AWAITED step of runPostRouteSequence, where a rejection is fatal+ * (process.exit), so the fix cannot simply throw: it boots empty, reports, and+ * latches persistence off so the file survives for recovery.+ *+ * Corrupt JSON is the portable way to produce "present but unreadable" — it+ * fails the parse identically on every platform and needs no privileges.+ */+describe('mediaJobQueue unreadable snapshot (#4115)', () => {+ const CORRUPT = '{"jobs": [{"id": "00000000-0000-4000-8000-0000000000aa",';++ it('boots without throwing, so an unreadable snapshot cannot kill the server', async () => {+ writeFileSync(join(tempDataDir, 'media-jobs.json'), CORRUPT);+ await importFresh();+ await expect(mediaJobQueue.initMediaJobQueue()).resolves.toBeUndefined();+ expect(mediaJobQueue.listJobs()).toEqual([]);+ });++ it('does NOT overwrite the unreadable file — at boot or on a later enqueue', async () => {+ const file = join(tempDataDir, 'media-jobs.json');+ writeFileSync(file, CORRUPT);+ await importFresh();+ await mediaJobQueue.initMediaJobQueue();++ // The boot persist is the first chance to clobber it.+ expect(readFileSync(file, 'utf8'), 'boot persist must be suppressed').toBe(CORRUPT);++ // …and so is every write the running queue would normally make.+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));+ mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'after a bad boot' } });+ await flush();+ expect(+ readFileSync(file, 'utf8'),+ 'persistence stays latched off for the process lifetime'+ ).toBe(CORRUPT);+ });++ it('a readable snapshot still persists normally (the latch is not sticky across boots)', async () => {+ const file = join(tempDataDir, 'media-jobs.json');+ writeFileSync(file, JSON.stringify({ jobs: [] }));+ await importFresh();+ await mediaJobQueue.initMediaJobQueue();++ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'good boot' } });+ await flush();+ const written = JSON.parse(readFileSync(file, 'utf8'));+ expect(written.jobs.map((j) => j.id)).toContain(job.jobId);+ });+});+async function waitFor(predicate, { timeoutMs = 3000, intervalMs = 30 } = {}) {const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.jsindex 5b14e4ee76..8401f2cce3 100644--- a/server/services/taskLearning/store.js+++ b/server/services/taskLearning/store.js@@ -320,7 +320,12 @@ export async function loadLearningData() {await ensureDir(DATA_DIR);- const data = await readJSONFile(LEARNING_FILE, structuredClone(DEFAULT_LEARNING_DATA));+ // Strict (#4115): every mutation is `loadLearningData → mutate →+ // saveLearningData`, so a swallowed unreadable file hands the caller a fresh+ // DEFAULT_LEARNING_DATA and the next save atomicWrites it over the whole+ // routing/outcome history. It also feeds the CoS learning counts. Throwing+ // skips the cycle and leaves the file intact.+ const data = await readJSONFile(LEARNING_FILE, structuredClone(DEFAULT_LEARNING_DATA), { strict: true });_learningCache = structuredClone(data);_learningCacheTime = Date.now();return data;@@ -649,7 +654,10 @@ export function extractTaskType(task) {*/export async function loadDismissedRecommendations() {await ensureDir(DATA_DIR);- return await readJSONFile(DISMISSED_RECS_FILE, {});+ // Strict (#4115): `dismissRecommendation` / `restoreRecommendation` load this+ // map, mutate one key, and write the whole thing back — an unreadable file+ // would silently un-dismiss every recommendation on the next dismissal.+ return await readJSONFile(DISMISSED_RECS_FILE, {}, { strict: true });}export async function saveDismissedRecommendations(map) {diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.jsindex 03a34f514e..995427d41a 100644--- a/server/services/taskLearning/store.test.js+++ b/server/services/taskLearning/store.test.js@@ -1,4 +1,23 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';++// Allocate the temp dir lazily on first PATHS read. `vi.mock` is hoisted above+// this file's static imports, so a `const` initialized here would still be in+// its TDZ when store.js resolves LEARNING_FILE at module load. `var` + a+// function declaration both hoist without a TDZ, so the factory can call it.+var tempRoot; // eslint-disable-line no-var+function getTempRoot() {+ if (!tempRoot) tempRoot = mkdtempSync(join(tmpdir(), 'task-learning-test-'));+ return tempRoot;+}++// Only the strict-read block at the end of this file touches disk; every other+// test here is pure. Re-rooting PATHS keeps it off the real data/cos tree.+vi.mock('../../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => getTempRoot() }));import {extractTaskType,calculateDurationETA,@@ -17,9 +36,16 @@ import {isSkipCandidate,EFFECTIVE_RATE_MIN_WINDOW_SAMPLES,RECENT_OUTCOMES_CAP,- DEFAULT_WINDOW_MAX_COUNT+ DEFAULT_WINDOW_MAX_COUNT,+ loadLearningData,+ saveLearningData,+ clearLearningCache,+ loadDismissedRecommendations,+ saveDismissedRecommendations} from './store.js';+afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });+// These two helpers are the pure foundation every other taskLearning submodule// builds on (duration math + task-type classification). They take no I/O, so we// exercise every branch arm directly without mocking the persistence layer.@@ -599,3 +625,75 @@ describe('store.isSkipCandidate (issue #2617)', () => {expect(isSkipCandidate(null)).toBe(false);});});++/**+ * Strict-read regression (#4115).+ *+ * Both file-backed loaders here are the base of a read-modify-write:+ *+ * - `loadLearningData → mutate → saveLearningData` is how every routing+ * outcome, duration sample and failure signature is recorded. While the+ * read swallowed unreadable files, a corrupt learning.json handed the+ * caller a fresh DEFAULT_LEARNING_DATA and the next save atomicWrote it+ * over the entire learning history.+ * - `dismissRecommendation` / `restoreRecommendation` load the dismissed map,+ * change one key, and write the whole map back — so an unreadable file+ * silently un-dismissed every recommendation on the next dismissal.+ *+ * Corrupt JSON is the portable way to produce "present but unreadable": it+ * fails the parse identically on every platform and needs no privileges.+ */+describe('taskLearning store strict reads (#4115)', () => {+ const CORRUPT = '{"byTaskType": {"docs": {"completed": 12';+ const cosDir = () => join(getTempRoot(), 'cos');+ const learningFile = () => join(cosDir(), 'learning.json');+ const dismissedFile = () => join(cosDir(), 'dismissed-recommendations.json');++ beforeEach(() => {+ rmSync(getTempRoot(), { recursive: true, force: true });+ mkdirSync(cosDir(), { recursive: true });+ clearLearningCache();+ });++ it('loadLearningData rejects instead of handing back a blank history', async () => {+ writeFileSync(learningFile(), CORRUPT);+ await expect(loadLearningData()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('a failed load cannot be followed by a save that erases the history', async () => {+ writeFileSync(learningFile(), CORRUPT);+ await expect(loadLearningData()).rejects.toThrow(/Unreadable JSON file/);+ expect(+ readFileSync(learningFile(), 'utf8'),+ 'the caller never got a default to write back, so the file is untouched'+ ).toBe(CORRUPT);+ });++ it('does not cache a fabricated default for the next reader in the TTL window', async () => {+ writeFileSync(learningFile(), CORRUPT);+ await expect(loadLearningData()).rejects.toThrow();+ await expect(loadLearningData()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('loadDismissedRecommendations rejects instead of un-dismissing everything', async () => {+ writeFileSync(dismissedFile(), CORRUPT);+ await expect(loadDismissedRecommendations()).rejects.toThrow(/Unreadable JSON file/);+ expect(readFileSync(dismissedFile(), 'utf8')).toBe(CORRUPT);+ });++ it('still treats genuinely absent files as real first-run empties', async () => {+ const data = await loadLearningData();+ expect(data.byTaskType, 'ENOENT is the one errno that proves absence').toEqual({});+ clearLearningCache();+ expect(await loadDismissedRecommendations()).toEqual({});+ });++ it('round-trips a readable file (the strict flag does not break the happy path)', async () => {+ await saveLearningData({ byTaskType: { docs: { completed: 3 } } });+ clearLearningCache();+ expect((await loadLearningData()).byTaskType.docs.completed).toBe(3);++ await saveDismissedRecommendations({ 'rec-1': { dismissedAt: '2026-08-14T00:00:00.000Z' } });+ expect(await loadDismissedRecommendations()).toHaveProperty('rec-1');+ });+});diff --git a/server/services/telegram.js b/server/services/telegram.jsindex 958d0ed686..2dd5cf90eb 100644--- a/server/services/telegram.js+++ b/server/services/telegram.js@@ -13,7 +13,7 @@ import { notificationEvents, NOTIFICATION_TYPES, getNotifications } from './notiimport { getDomainAutonomyMode } from './cosState.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';import { approveMemory, rejectMemory, peekMemory } from './memoryBackend.js';-import { ensureDir, PATHS, readJSONFile, formatDuration, atomicWrite } from '../lib/fileUtils.js';+import { ensureDir, PATHS, readJSONFileStrict, formatDuration, atomicWrite } from '../lib/fileUtils.js';import { getActiveAgents } from './agentManagement.js';import { getGoals } from './identity.js';@@ -523,6 +523,10 @@ async function handleCheckinCommand(msg) {// Pick goal with oldest check-in or no check-insconst checkins = await loadCheckins();+ if (!checkins) {+ await bot.sendMessage(chatId, "⚠️ Couldn't read your check-in history, so I can't pick the most overdue goal. Try again once it's readable.", { parse_mode: 'HTML' });+ return;+ }let targetGoal = null;let oldestCheckinTime = Infinity;@@ -557,6 +561,13 @@ async function handleCheckinResponse(msg) {if (!pending) return;const checkins = await loadCheckins();+ // Bail rather than write: pushing onto the empty default would atomicWrite a+ // one-entry log over the whole history. The pending check-in stays pending so+ // the answer can be re-sent once the file is readable again.+ if (!checkins) {+ await bot.sendMessage(chatId, "⚠️ Couldn't read your check-in history, so I didn't record that. Nothing was overwritten — send it again once it's readable.", { parse_mode: 'HTML' });+ return;+ }checkins.checkins.push({id: uuidv4(),question: pending.question,@@ -591,8 +602,11 @@ export async function sendCheckin(goalId) {if (goalId) {targetGoal = activeGoals.find(g => g.id === goalId);} else {- // Pick most stale goal+ // Pick most stale goal. An unreadable log can't rank staleness, and asking+ // about an arbitrary goal would then record an answer against it — skip the+ // send instead (the scheduled job simply retries next window).const checkins = await loadCheckins();+ if (!checkins) return;let oldestTime = Infinity;for (const goal of activeGoals) {const last = checkins.checkins@@ -617,8 +631,29 @@ export async function sendCheckin(goalId) {// === Check-in persistence ===+/**+ * Load the check-in log, or `null` when the file is present but unreadable.+ *+ * Strict (#4115) with a null sentinel rather than a throw: every caller runs+ * inside a `bot.on(...)` handler that node-telegram-bot-api never awaits, so a+ * rejection would leak as an unhandled rejection instead of reaching a caller.+ * Callers must bail on `null` — `handleCheckinResponse` is a+ * `load → push → atomicWrite`, so treating an unreadable file as "no check-ins+ * yet" would write a one-entry log over the user's entire check-in history.+ *+ * A file that reads cleanly but has no `checkins` array is untrustworthy for the+ * same reason and gets the same `null`: we can't interpret it, so we must not+ * replace it. Only ENOENT yields the real empty log (the default below).+ *+ * @returns {Promise<{checkins: Array}|null>} the log, or null if untrustworthy+ */async function loadCheckins() {- return readJSONFile(CHECKINS_FILE, { checkins: [] });+ const { ok, value } = await readJSONFileStrict(CHECKINS_FILE, { checkins: [] });+ if (!ok || !Array.isArray(value?.checkins)) {+ console.error(`📱 Telegram: check-in log at ${CHECKINS_FILE} is unreadable — refusing to overwrite it`);+ return null;+ }+ return value;}async function saveCheckins(data) {diff --git a/server/services/telegram.test.js b/server/services/telegram.test.jsindex e963120030..a8d85293b8 100644--- a/server/services/telegram.test.js+++ b/server/services/telegram.test.js@@ -96,12 +96,21 @@ vi.mock('./memoryBackend.js', () => ({peekMemory: vi.fn(async () => null),}));+// Mutable disk stand-in. `strictRead` is what `readJSONFileStrict` returns+// (null = "behave like a normal absent file"); `writes` records every+// atomicWrite so a test can assert that NOTHING was written. Held in a hoisted+// holder because loadTelegram() calls vi.resetModules(), which re-evaluates+// this factory and would otherwise hand each test fresh, unreachable spies.+const fu = vi.hoisted(() => ({ strictRead: null, writes: [] }));++// Exhaustive factory (no importActual spread) — every export telegram.js+// imports must be listed here or the access throws "not defined on the mock".vi.mock('../lib/fileUtils.js', () => ({ensureDir: vi.fn(async () => {}),PATHS: { data: '/mock/data' },- readJSONFile: vi.fn(async (_path, def) => def),+ readJSONFileStrict: vi.fn(async (_path, def) => fu.strictRead ?? { ok: true, value: def }),formatDuration: vi.fn(() => '1m'),- atomicWrite: vi.fn(async () => {}),+ atomicWrite: vi.fn(async (path, data) => { fu.writes.push({ path, data }); }),}));vi.mock('./agentManagement.js', () => ({ getActiveAgents: vi.fn(() => []) }));@@ -124,6 +133,8 @@ describe('telegram service', () => {beforeEach(() => {cfg.settings = defaultSettings();+ fu.strictRead = null;+ fu.writes = [];active = null;h.textHandlers = [];h.eventHandlers = {};@@ -254,4 +265,85 @@ describe('telegram service', () => {expect(h.editMessageText).not.toHaveBeenCalled();});});++ /**+ * Strict-read regression (#4115).+ *+ * `handleCheckinResponse` is `loadCheckins → push → atomicWrite`. While the+ * read swallowed unreadable files, a corrupt checkins.json read as+ * { checkins: [] }, so answering one check-in wrote a ONE-entry log over the+ * user's whole check-in history.+ *+ * The fix uses a null sentinel rather than a throw: every caller runs inside a+ * `bot.on(...)` handler that node-telegram-bot-api never awaits, so a+ * rejection would leak as an unhandled rejection instead of reaching a caller.+ */+ describe('check-in log strict reads (#4115)', () => {+ async function armPendingCheckin(telegram) {+ const { getGoals } = await import('./identity.js');+ getGoals.mockResolvedValue({ goals: [{ id: 'g1', title: 'Example Goal', status: 'active', progress: 40 }] });+ await telegram.init(false);+ await telegram.sendCheckin();+ h.sendMessage.mockClear();+ }++ it('does not overwrite an unreadable check-in log when an answer arrives', async () => {+ const telegram = await loadTelegramActive();+ await armPendingCheckin(telegram);++ // The log becomes unreadable between asking and answering.+ fu.strictRead = { ok: false, value: { checkins: [] } };+ fu.writes = [];++ const msgHandler = h.eventHandlers.message[0];+ await msgHandler({ chat: { id: 42 }, text: 'Made good progress' });++ expect(fu.writes, 'a one-entry log must never replace the real history').toEqual([]);+ expect(h.sendMessage).toHaveBeenCalledWith(+ '42',+ expect.stringContaining('Nothing was overwritten'),+ expect.anything(),+ );+ });++ it('records the answer normally when the log is readable', async () => {+ const telegram = await loadTelegramActive();+ await armPendingCheckin(telegram);+ fu.writes = [];++ const msgHandler = h.eventHandlers.message[0];+ await msgHandler({ chat: { id: 42 }, text: 'Made good progress' });++ expect(fu.writes).toHaveLength(1);+ expect(fu.writes[0].data.checkins[0]).toMatchObject({ goalId: 'g1', response: 'Made good progress' });+ });++ it('skips the scheduled send rather than asking about an arbitrary goal', async () => {+ const telegram = await loadTelegramActive();+ const { getGoals } = await import('./identity.js');+ getGoals.mockResolvedValue({ goals: [{ id: 'g1', title: 'Example Goal', status: 'active', progress: 40 }] });+ await telegram.init(false);+ h.sendMessage.mockClear();++ fu.strictRead = { ok: false, value: { checkins: [] } };+ await telegram.sendCheckin();++ expect(h.sendMessage, 'staleness is unrankable without the log').not.toHaveBeenCalled();+ });++ it('treats a readable-but-shapeless log as untrustworthy rather than replacing it', async () => {+ const telegram = await loadTelegramActive();+ await armPendingCheckin(telegram);++ // Parses fine, but there is no `checkins` array to append to. We cannot+ // interpret the file, so we must not write over it either.+ fu.strictRead = { ok: true, value: { unexpected: 'shape' } };+ fu.writes = [];++ const msgHandler = h.eventHandlers.message[0];+ await msgHandler({ chat: { id: 42 }, text: 'Made good progress' });++ expect(fu.writes).toEqual([]);+ });+ });});