Skip to content

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

test: remove mock members their modules do not export and guard against drift (#11891)

Adam Eivy52ebdc265f6f
diff --git a/client/src/components/media/Image3dHfAccessNotice.test.jsx b/client/src/components/media/Image3dHfAccessNotice.test.jsx
index 4ddf02e360..20f3d24e1f 100644
--- a/client/src/components/media/Image3dHfAccessNotice.test.jsx
+++ b/client/src/components/media/Image3dHfAccessNotice.test.jsx
@@ -13,7 +13,7 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
-vi.mock('../../services/api', () => ({ setHfToken: vi.fn() }));
+vi.mock('../../services/api', () => ({}));
import Image3dHfAccessNotice from './Image3dHfAccessNotice';
diff --git a/client/src/components/musicVideo/MusicVideoAutomationNaming.test.jsx b/client/src/components/musicVideo/MusicVideoAutomationNaming.test.jsx
index c550ababa1..6a812a8f26 100644
--- a/client/src/components/musicVideo/MusicVideoAutomationNaming.test.jsx
+++ b/client/src/components/musicVideo/MusicVideoAutomationNaming.test.jsx
@@ -13,10 +13,6 @@ vi.mock('../../services/apiMusicVideo.js', () => ({
resumeMusicVideoProduction: vi.fn(),
stopMusicVideoProduction: vi.fn(),
cancelMusicVideoProduction: vi.fn(),
- startAutoReview: vi.fn(),
- resumeAutoReview: vi.fn(),
- stopAutoReview: vi.fn(),
- cancelAutoReview: vi.fn(),
}));
vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));
vi.mock('../../hooks/useProviderModels.js', () => ({
diff --git a/client/src/hooks/useItermSession.test.jsx b/client/src/hooks/useItermSession.test.jsx
index 1cbfa0bcd8..0c44228767 100644
--- a/client/src/hooks/useItermSession.test.jsx
+++ b/client/src/hooks/useItermSession.test.jsx
@@ -32,7 +32,7 @@ const { handlers, emitted, socketMock, terminalHarness } = vi.hoisted(() => {
};
return { handlers, emitted, socketMock, terminalHarness };
});
-vi.mock('../services/socket', () => ({ default: socketMock, getSocket: () => socketMock }));
+vi.mock('../services/socket', () => ({ default: socketMock }));
vi.mock('../components/ThemeContext', () => ({
useThemeContext: () => ({ themeId: 'test', theme: { mode: 'night' } }),
}));
diff --git a/client/src/hooks/useShellSession.test.jsx b/client/src/hooks/useShellSession.test.jsx
index 6b9a118046..81d14469b5 100644
--- a/client/src/hooks/useShellSession.test.jsx
+++ b/client/src/hooks/useShellSession.test.jsx
@@ -21,7 +21,7 @@ const { handlers, emitted, socketMock } = vi.hoisted(() => {
};
return { handlers, emitted, socketMock };
});
-vi.mock('../services/socket', () => ({ default: socketMock, getSocket: () => socketMock }));
+vi.mock('../services/socket', () => ({ default: socketMock }));
vi.mock('../components/ThemeContext', () => ({
useThemeContext: () => ({ themeId: 'test', theme: { mode: 'night' } }),
}));
diff --git a/client/src/moduleContractConventions.test.js b/client/src/moduleContractConventions.test.js
index 6859602780..6894a2fc80 100644
--- a/client/src/moduleContractConventions.test.js
+++ b/client/src/moduleContractConventions.test.js
@@ -17,7 +17,11 @@
* takes that shape.
* 2. A test's `vi.mock` factory for one of those modules defines only members
* the real export has, so a mock cannot paper over a missing member again.
- * 3. No browser `alert`/`confirm`/`prompt` (client/src/AGENTS.md: inline
+ * 3. Every other literal `vi.mock` factory (notably `services/api*.js` and
+ * `services/socket.js`) defines only members its target exports, via the
+ * static scanner in scripts/lib/mockContractScan.js shared with the server.
+ * `MOCK_ADAPTERS` allowlists deliberate fixture adapters, with a reason.
+ * 4. No browser `alert`/`confirm`/`prompt` (client/src/AGENTS.md: inline
* confirmations or toasts instead). Blocking dialogs freeze the tab and are
* unusable from a PWA or a remote session.
*
@@ -31,6 +35,7 @@ import { fileURLToPath } from 'url';
import { execSync } from 'child_process';
import { trackedSourceFiles } from './test/trackedFiles.js';
import { lineOf, maskComments } from './test/classNameScan.js';
+import { mockDrift as scanMockDriftIn } from '../../scripts/lib/mockContractScan.js';
const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -48,6 +53,11 @@ const CONTRACT_MODULES = [
},
];
+/** `<test file>|<module specifier>|<key>` -> reason, for mock keys that are deliberate adapters. */
+const MOCK_ADAPTERS = new Map([
+ ['src/pages/MusicVideo.test.jsx|../services/apiMusicVideo.js|listMusicVideoProjects', 'in-test project store: the suite backs listMusicVideoProjectSummaries and getMusicVideoProject with it'],
+]);
+
const IMPORT_RE = /import\s+([^'"]+?)\s+from\s+['"]([^'"]+)['"]/g;
/** Local bindings that refer to the module's object API in one file. */
@@ -124,6 +134,8 @@ export function blockingDialogs(rawSource, file) {
.map((match) => `${file}:${lineOf(source, match.index)} — ${match[0].replace(/\s*\($/, '')}()`);
}
+const scanMockDrift = (testFile, source) => scanMockDriftIn(testFile, source, { root: CLIENT_ROOT, allowed: MOCK_ADAPTERS });
+
const read = (file) => readFileSync(join(CLIENT_ROOT, file), 'utf8');
const trackedTestFiles = () => execSync('git ls-files src', { cwd: CLIENT_ROOT, encoding: 'utf8' })
@@ -164,6 +176,17 @@ describe('module contract conventions', () => {
});
}
+ it('flags a planted mock key the real module does not export', () => {
+ const probe = join(CLIENT_ROOT, 'src/__probe.test.jsx');
+ expect(scanMockDrift(probe, "vi.mock('./services/socket.js', () => ({ default: {}, plantedDeadKey: vi.fn() }));"))
+ .toEqual(['src/__probe.test.jsx:1 — ./services/socket.js mocks plantedDeadKey']);
+ });
+
+ it('mocks only members the real modules export', () => {
+ const drift = trackedTestFiles().flatMap((file) => scanMockDrift(join(CLIENT_ROOT, file), read(file)));
+ expect(drift, 'delete the dead key, or mock the module that really exports it').toEqual([]);
+ });
+
it('never calls the browser alert/confirm/prompt dialogs', () => {
const violations = files.flatMap((file) => blockingDialogs(read(file), file));
expect(violations, 'use an inline confirmation (useConfirmDelete + ConfirmButtonPair) or a toast').toEqual([]);
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 634102ef9a..a39d007be9 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -66,7 +66,6 @@ vi.mock('../services/apiMusicVideo.js', () => ({
deleteMusicVideoProject: vi.fn(),
analyzeMusicVideoProject: vi.fn(),
prepareMusicVideoSong: vi.fn((id) => Promise.resolve({ project: { id }, analyzed: false, alignJobId: null })),
- getMusicVideoLyricPlaythroughPreview: vi.fn(() => new Promise(() => {})),
getMusicVideoLyricOverlayPreview: vi.fn(() => new Promise(() => {})),
planMusicVideoProject: vi.fn(),
addMusicVideoScene: vi.fn(),
@@ -152,9 +151,7 @@ vi.mock('../services/apiMusicVideo.js', () => ({
resolveMusicVideoDevArtifactNote: vi.fn(),
reviewMusicVideoDevArtifact: vi.fn(),
deleteMusicVideoDevArtifact: vi.fn(),
- getMusicVideoCompositionPreview: vi.fn(async () => ({ html: '<!doctype html><p>preview</p>', assets: [], width: 1920, height: 1080, fps: 24, durationSec: 60 })),
getMusicVideoCompositionDocument: vi.fn(),
- fetchMusicVideoPreviewAsset: vi.fn(),
startMusicVideoCompositionTemplate: vi.fn(),
importMusicVideoCompositionZip: vi.fn(),
importMusicVideoCompositionDirectory: vi.fn(),
@@ -202,7 +199,6 @@ vi.mock('../services/apiSystem.js', () => ({
getInstances: vi.fn(async () => ({ peers: [] })),
generateImage: vi.fn(async () => ({ status: 'queued', jobId: 'example-frame-job' })),
uploadGalleryImage: vi.fn(),
- listImageModels: vi.fn(async () => []),
getSettings: vi.fn(async () => ({})),
}));
vi.mock('../services/apiMoodBoard.js', () => ({
@@ -219,6 +215,7 @@ vi.mock('../hooks/useMidiNotes.js', () => ({
default: () => ({ status: 'idle', data: null, error: null, reload: vi.fn() }),
}));
vi.mock('../services/apiImageVideo.js', () => ({
+ listImageModels: vi.fn(async () => []),
getVideoGenModelContext: vi.fn(async () => null),
generateVideo: vi.fn(),
uploadGalleryVideo: vi.fn(),
diff --git a/scripts/lib/mockContractScan.js b/scripts/lib/mockContractScan.js
new file mode 100644
index 0000000000..4af2d4cfcc
--- /dev/null
+++ b/scripts/lib/mockContractScan.js
@@ -0,0 +1,204 @@
+/**
+ * Static scanner behind the server and client `mockContractConventions` guards:
+ * a `vi.mock('<relative module>', () => ({ ... }))` factory must define only
+ * members the real module exports.
+ *
+ * A key the target does not export is a dead stub: it intercepts nothing, so a
+ * `.not.toHaveBeenCalled()` on it is vacuous, and a renamed export leaves its
+ * mock silently watching a function production no longer calls (the
+ * `peerAdministration` `pm2.restartProcess` shape).
+ *
+ * Only literal `() => ({ ... })` factories are read; a factory that spreads
+ * `importOriginal()` / `vi.importActual()` inherits the real surface and is
+ * skipped. Exports are collected statically (`export *` followed) so the module
+ * under test is never evaluated. Pure Node, test-time only.
+ */
+
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { dirname, join, resolve, relative } from 'node:path';
+
+/** A `/` after an operator, opener or `return` begins a regex literal, not a division. */
+function startsRegex(source, at) {
+ const before = source.slice(0, at).trimEnd();
+ return before === '' || /[(,=:[!&|?{};>]$/.test(before) || /\breturn$/.test(before);
+}
+
+/** Blank comments and string/template text (keeping `${}` code), preserving offsets. */
+export function mask(source) {
+ const out = source.split('');
+ const blank = (from, to) => {
+ for (let k = from; k < to; k += 1) if (out[k] !== '\n') out[k] = ' ';
+ };
+ // Scans code from `i`; in expression mode returns at the `}` closing a `${`.
+ const scan = (start, inExpression) => {
+ let i = start;
+ let depth = 0;
+ while (i < source.length) {
+ const ch = source[i];
+ const next = source[i + 1];
+ if (ch === '/' && next === '/') {
+ const end = source.indexOf('\n', i);
+ const stop = end === -1 ? source.length : end;
+ blank(i, stop);
+ i = stop;
+ } else if (ch === '/' && next === '*') {
+ const end = source.indexOf('*/', i + 2);
+ const stop = end === -1 ? source.length : end + 2;
+ blank(i, stop);
+ i = stop;
+ } else if (ch === '/' && startsRegex(source, i)) {
+ // Regex literal: its quotes and brackets must not reach the string scanner.
+ let j = i + 1;
+ let inClass = false;
+ while (j < source.length && (inClass || source[j] !== '/') && source[j] !== '\n') {
+ if (source[j] === '\\') j += 1;
+ else if (source[j] === '[') inClass = true;
+ else if (source[j] === ']') inClass = false;
+ j += 1;
+ }
+ blank(i + 1, j);
+ i = j + 1;
+ } else if (ch === '\'' || ch === '"') {
+ let j = i + 1;
+ while (j < source.length && source[j] !== ch) j += source[j] === '\\' ? 2 : 1;
+ blank(i + 1, j);
+ i = j + 1;
+ } else if (ch === '`') {
+ let j = i + 1;
+ let textStart = j;
+ while (j < source.length && source[j] !== '`') {
+ if (source[j] === '\\') j += 2;
+ else if (source[j] === '$' && source[j + 1] === '{') {
+ blank(textStart, j);
+ j = scan(j + 2, true) + 1;
+ textStart = j;
+ } else j += 1;
+ }
+ blank(textStart, j);
+ i = j + 1;
+ } else {
+ if (ch === '{') depth += 1;
+ else if (ch === '}') {
+ if (inExpression && depth === 0) return i;
+ depth -= 1;
+ }
+ i += 1;
+ }
+ }
+ return i;
+ };
+ scan(0, false);
+ return out.join('');
+}
+
+function resolveModule(fromFile, specifier) {
+ if (!specifier.startsWith('.')) return null;
+ const base = resolve(dirname(fromFile), specifier);
+ for (const candidate of [base, `${base}.js`, `${base}.jsx`, `${base}.mjs`, `${base}.cjs`, join(base, 'index.js'), join(base, 'index.jsx')]) {
+ if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
+ }
+ return null;
+}
+
+/** Static export names of a module, following `export * from`. */
+export function exportNames(file, seen = new Set(), names = new Set()) {
+ if (seen.has(file)) return names;
+ seen.add(file);
+ const raw = readFileSync(file, 'utf8');
+ const source = mask(raw);
+ for (const m of source.matchAll(/\bexport\s+(?:async\s+)?function\s*\*?\s*([\w$]+)/g)) names.add(m[1]);
+ for (const m of source.matchAll(/\bexport\s+(?:const|let|var|class)\s+([\w$]+)/g)) names.add(m[1]);
+ for (const m of source.matchAll(/\bexport\s+(?:const|let|var)\s*[{[]([^=]*)[}\]]\s*=/g)) {
+ // Destructured declaration: `export const { a, b: c } = factory()` exports a and c.
+ for (const part of m[1].split(',')) {
+ const bound = part.split(':').pop().split('=')[0].replace(/[.\s]/g, '');
+ if (bound) names.add(bound);
+ }
+ }
+ if (/\bexport\s+default\b/.test(source)) names.add('default');
+ for (const m of source.matchAll(/\bexport\s*\{([^}]*)\}(?:\s*from\s*['"`]([^'"`]*)['"`])?/g)) {
+ for (const part of m[1].split(',')) {
+ const exported = part.trim().split(/\s+as\s+/).pop();
+ if (exported) names.add(exported);
+ }
+ }
+ // Specifiers are masked in `source`; read them from the same offsets in `raw`.
+ for (const m of source.matchAll(/\bexport\s*\*\s*(?:as\s+([\w$]+)\s*)?from\s*(['"`])/g)) {
+ if (m[1]) { names.add(m[1]); continue; }
+ const start = m.index + m[0].length;
+ const target = resolveModule(file, raw.slice(start, raw.indexOf(m[2], start)));
+ if (target) exportNames(target, seen, names);
+ }
+ return names;
+}
+
+/** Index of the matching close for the bracket at `open`. */
+function closeOf(masked, open) {
+ let depth = 0;
+ for (let i = open; i < masked.length; i += 1) {
+ if ('({['.includes(masked[i])) depth += 1;
+ else if (')}]'.includes(masked[i])) {
+ depth -= 1;
+ if (depth === 0) return i;
+ }
+ }
+ return -1;
+}
+
+/** Top-level keys of the object literal opening at `open`, or null when it spreads. */
+function literalKeys(raw, masked, open) {
+ const close = closeOf(masked, open);
+ if (close === -1) return null;
+ const keys = [];
+ let depth = 0;
+ let segStart = open + 1;
+ const flush = (end) => {
+ const seg = masked.slice(segStart, end).trim();
+ if (!seg) return true;
+ if (seg.startsWith('...')) return false;
+ const offset = segStart + masked.slice(segStart, end).indexOf(seg);
+ const quoted = /^(['"`])/.exec(seg);
+ if (quoted) {
+ keys.push(raw.slice(offset + 1, raw.indexOf(quoted[1], offset + 1)));
+ return true;
+ }
+ const ident = /^(?:async\s+|get\s+|set\s+|\*\s*)?([\w$]+)/.exec(seg);
+ if (ident) keys.push(ident[1]);
+ return true;
+ };
+ for (let i = open + 1; i <= close; i += 1) {
+ const ch = masked[i];
+ if (i === close || (ch === ',' && depth === 0)) {
+ if (!flush(i)) return null;
+ segStart = i + 1;
+ } else if ('({['.includes(ch)) depth += 1;
+ else if (')}]'.includes(ch)) depth -= 1;
+ }
+ return keys;
+}
+
+const FACTORY_RE = /\bvi\.mock\(\s*(['"])([^'"]+)\1\s*,\s*(?:async\s*)?\(\s*\)\s*=>\s*\(\s*\{/g;
+
+/** `file:line — spec mocks <key>` for each key the real module does not export. */
+export function mockDrift(testFile, rawSource, { root, allowed = new Map() }) {
+ const masked = mask(rawSource);
+ const rel = relative(root, testFile);
+ const violations = [];
+ // The specifier is a string, so it is blanked in `masked`; match on raw and
+ // require the call itself to be live code (not inside a comment).
+ for (const m of rawSource.matchAll(FACTORY_RE)) {
+ if (masked[m.index] !== 'v') continue;
+ const target = resolveModule(testFile, m[2]);
+ if (!target) continue;
+ const open = m.index + m[0].length - 1;
+ const keys = literalKeys(rawSource, masked, open);
+ if (!keys) continue;
+ const exported = exportNames(target);
+ for (const key of keys) {
+ if (key === '__esModule' || exported.has(key) || allowed.has(`${rel}|${m[2]}|${key}`)) continue;
+ const line = rawSource.slice(0, m.index).split('\n').length;
+ violations.push(`${rel}:${line} — ${m[2]} mocks ${key}`);
+ }
+ }
+ return violations;
+}
diff --git a/server/mockContractConventions.test.js b/server/mockContractConventions.test.js
new file mode 100644
index 0000000000..7d8abf905f
--- /dev/null
+++ b/server/mockContractConventions.test.js
@@ -0,0 +1,50 @@
+/**
+ * Every `vi.mock` literal factory under the server-side test trees defines only
+ * members its target exports. Scanner and rationale: scripts/lib/mockContractScan.js.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportNames, mockDrift } from '../scripts/lib/mockContractScan.js';
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+/** Deliberate fixture adapters: `<test file>|<module specifier>|<key>` -> reason. */
+const ALLOWED = new Map([
+ ['server/services/memoryBackend.test.js|./memory.js|__backend', 'sentinel the suite reads to assert which backend was selected'],
+ ['server/services/memoryBackend.test.js|./memoryDB.js|__backend', 'sentinel the suite reads to assert which backend was selected'],
+ ['server/routes/peerAdministration.test.js|../services/pm2.js|restartProcess', 'dead guard double; replacing it is tracked in #11873'],
+]);
+
+const drift = (testFile, source) => mockDrift(testFile, source, { root: ROOT, allowed: ALLOWED });
+
+function trackedTests() {
+ return execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard', 'server', 'scripts', 'lib', 'autofixer'], { cwd: ROOT, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
+ .split('\0').filter((f) => /\.test\.[cm]?js$/.test(f) && existsSync(join(ROOT, f)));
+}
+
+describe('vi.mock factory contract conventions', () => {
+ it('flags a planted key the real module does not export', () => {
+ const probe = join(ROOT, 'server/lib/__probe.test.js');
+ const src = [
+ "vi.mock('./validation.js', () => ({ validateRequest: vi.fn(), plantedDeadKey: vi.fn() }));",
+ "// vi.mock('./validation.js', () => ({ commentedDeadKey: vi.fn() }));",
+ "vi.mock('./validation.js', async () => ({ ...(await vi.importActual('./validation.js')), spreadKey: vi.fn() }));",
+ ].join('\n');
+ expect(drift(probe, src)).toEqual(['server/lib/__probe.test.js:1 — ./validation.js mocks plantedDeadKey']);
+ });
+
+ it('follows export * when collecting real exports', () => {
+ expect(exportNames(join(ROOT, 'server/lib/index.js')).size).toBeGreaterThan(50);
+ });
+
+ it('mocks only members the real modules export', () => {
+ const files = trackedTests();
+ expect(files.length).toBeGreaterThan(100);
+ const violations = files.flatMap((f) => drift(join(ROOT, f), readFileSync(join(ROOT, f), 'utf8')));
+ expect(violations, 'delete the dead key, or point the mock at the module that really exports it').toEqual([]);
+ });
+});
diff --git a/server/routes/browser.test.js b/server/routes/browser.test.js
index 0fe99f3c32..9f045bb068 100644
--- a/server/routes/browser.test.js
+++ b/server/routes/browser.test.js
@@ -38,8 +38,6 @@ vi.mock('../services/browserService.js', () => ({
// other exports are referenced by sibling routes but not by these tests
restartBrowser: vi.fn(),
getHealthStatus: vi.fn(),
- getBrowserStatus: vi.fn(),
- getBrowserLogs: vi.fn(),
getRecentLogs: vi.fn(async () => ({ stdout: '', stderr: '' })),
}));
diff --git a/server/routes/git.test.js b/server/routes/git.test.js
index a890e22492..c784bff736 100644
--- a/server/routes/git.test.js
+++ b/server/routes/git.test.js
@@ -14,7 +14,6 @@ vi.mock('../services/git.js', () => ({
push: vi.fn().mockResolvedValue({ pushed: true }),
getGitInfo: vi.fn().mockResolvedValue({}),
getBranches: vi.fn().mockResolvedValue([]),
- getAppById: vi.fn(),
updateBranches: vi.fn().mockResolvedValue({}),
getBranchComparison: vi.fn().mockResolvedValue({}),
pushAll: vi.fn().mockResolvedValue({}),
diff --git a/server/routes/hostControlMediaGeneration.test.js b/server/routes/hostControlMediaGeneration.test.js
index 0a6a50f993..fe9bbfacc1 100644
--- a/server/routes/hostControlMediaGeneration.test.js
+++ b/server/routes/hostControlMediaGeneration.test.js
@@ -70,7 +70,7 @@ vi.mock('../services/userActions.js', () => ({ recordUserAction: vi.fn() }));
vi.mock('../services/character.js', () => ({ setAvatar: vi.fn() }));
vi.mock('../services/videoGen/submitJob.js', () => ({ submitVideoGenJob: effects.video }));
vi.mock('../services/videoGen/local.js', () => ({
- BYOV_RUNTIME_INFO: {}, getHistoryItem: vi.fn(async id => ({ id, filename: 'example.mp4' })), checkConnection: vi.fn(async () => ({})),
+ BYOV_RUNTIME_INFO: {}, getHistoryItem: vi.fn(async id => ({ id, filename: 'example.mp4' })),
}));
vi.mock('../services/videoGen/batch.js', () => ({ MAX_VIDEO_BATCH_SIZE: 8 }));
vi.mock('../services/sprites/records.js', () => ({
diff --git a/server/routes/imageGen.clean.test.js b/server/routes/imageGen.clean.test.js
index 42a9591e0c..6c435f5de1 100644
--- a/server/routes/imageGen.clean.test.js
+++ b/server/routes/imageGen.clean.test.js
@@ -41,7 +41,6 @@ vi.mock('../services/imageGen/index.js', async () => {
});
vi.mock('../services/settings.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
getSettings: vi.fn(async () => ({ imageGen: { mode: 'external' } })),
settingsEvents: { on: () => {}, emit: () => {} },
}));
diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.js
index 07d890f53b..fea125b30d 100644
--- a/server/routes/imageGen.multipart.test.js
+++ b/server/routes/imageGen.multipart.test.js
@@ -68,7 +68,6 @@ vi.mock('../services/imageGen/index.js', async () => {
// reference-image gate. Default: `mode: 'local'` with a fake pythonPath.
let mockedSettings = { imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } };
vi.mock('../services/settings.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
getSettings: vi.fn(async () => mockedSettings),
settingsEvents: { on: () => {}, emit: () => {} },
}));
diff --git a/server/routes/importerSessions.test.js b/server/routes/importerSessions.test.js
index 26a8e648ec..a70c7d354c 100644
--- a/server/routes/importerSessions.test.js
+++ b/server/routes/importerSessions.test.js
@@ -27,7 +27,6 @@ const arc = { logline: 'A logline.', summary: 'A summary.', shape: 'man-in-hole'
const issues = { issues: [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed.' }] };
vi.mock('../services/stageRunner.js', () => ({
- tryReadFile: vi.fn().mockResolvedValue(null),
runStagedLLM: vi.fn(async (stage) => ({
content: { 'importer-canon-extract': canon, 'importer-arc-extract': arc, 'importer-issue-proposal': issues }[stage],
model: 'mock', providerId: 'mock', runId: `run-${stage}`,
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index fa816575b7..9630543593 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -79,7 +79,6 @@ vi.mock('../lib/slashdoLoader.js', async (importOriginal) => {
};
});
vi.mock('./jira.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
createTicket: vi.fn().mockResolvedValue(null),
}));
// Code Review Defaults resolver — mocked so tests can control the install-wide
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 1c7762e364..cfcd01c9c5 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -79,7 +79,6 @@ vi.mock('./ollamaAgentContext.js', () => ({
}));
vi.mock('./agentFinalization.js', () => ({
- persistSimplifySummaries: vi.fn().mockResolvedValue(undefined),
finalizeAgent: vi.fn().mockResolvedValue(undefined),
releaseAgentLane: vi.fn()
}));
diff --git a/server/services/autonomousJobs.syncSkillTemplates.test.js b/server/services/autonomousJobs.syncSkillTemplates.test.js
index c82b208cf5..6e0548a185 100644
--- a/server/services/autonomousJobs.syncSkillTemplates.test.js
+++ b/server/services/autonomousJobs.syncSkillTemplates.test.js
@@ -31,7 +31,7 @@ vi.mock('../lib/fileUtils.js', async () => {
// These mocks satisfy the module's top-level side-effect imports that are
// irrelevant to syncSkillTemplatesFromSample — avoids loading PM2, etc.
vi.mock('./cosEvents.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null), cosEvents: { emit: vi.fn() } }))
+cosEvents: { emit: vi.fn() } }))
vi.mock('./autobiography.js', () => ({ checkAndPrompt: vi.fn() }))
vi.mock('./goalCheckIn.js', () => ({ runGoalCheckIn: vi.fn() }))
vi.mock('./eventScheduler.js', () => ({ parseCronToNextRun: vi.fn() }))
diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.js
index d0ee30cd72..d6d53d5613 100644
--- a/server/services/brainJournal.test.js
+++ b/server/services/brainJournal.test.js
@@ -21,7 +21,6 @@ vi.mock('../lib/fileUtils.js', async () => {
});
vi.mock('../lib/timezone.js', () => ({
- tryReadFile: vi.fn().mockResolvedValue(null),
todayInTimezone: () => '2026-04-17',
}));
vi.mock('./userTimezone.js', () => ({
diff --git a/server/services/calendarGoogleSync.test.js b/server/services/calendarGoogleSync.test.js
index 0679427703..af5f357d1b 100644
--- a/server/services/calendarGoogleSync.test.js
+++ b/server/services/calendarGoogleSync.test.js
@@ -17,13 +17,16 @@ vi.mock('./calendarAccounts.js', () => ({
mergeDiscoveredSubcalendars: vi.fn((existing, discovered) => discovered),
}));
+// The real mutateCache persists the mutated cache after the callback; this spy
+// records that write so tests assert on what mutateCache would have saved.
+const persistedCache = vi.hoisted(() => vi.fn(async () => {}));
+
vi.mock('./calendarSync.js', () => ({
loadCache: vi.fn(),
- saveCache: vi.fn(async () => {}),
mutateCache: vi.fn(async (id, mutate) => {
const cache = await loadCache(id);
const result = await mutate(cache, await getAccount(id));
- await saveCache(id, cache);
+ await persistedCache(id, cache);
return result;
}),
logCalendarTouchpoints: vi.fn(async () => {}),
@@ -36,7 +39,7 @@ vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
import { mcpSyncAccount, mcpDiscoverCalendars, pushSyncEvents } from './calendarGoogleSync.js';
import { runCliProviderPrompt } from '../lib/cliProviderRun.js';
import { getAccount, updateSyncStatus, updateSubcalendars } from './calendarAccounts.js';
-import { loadCache, saveCache, logCalendarTouchpoints } from './calendarSync.js';
+import { loadCache, logCalendarTouchpoints } from './calendarSync.js';
const ACCOUNT_ID = '22222222-2222-2222-2222-222222222222';
const CAL_ID = '[email protected]';
@@ -67,7 +70,7 @@ const rawEvent = (id, summary) => ({
end: { dateTime: '2026-03-02T11:00:00Z' },
});
-const savedCache = () => saveCache.mock.calls.at(-1)[1];
+const savedCache = () => persistedCache.mock.calls.at(-1)[1];
// The completion contract (#10869): a zero-exit reply only licenses a prune for a
// calendar that echoes the requested window, carries `complete: true` and has no
@@ -152,7 +155,7 @@ describe('mcpSyncAccount CLI exit-status agreement (#5302)', () => {
status: 502,
message: expect.stringContaining('MCP server not connected'),
});
- expect(saveCache).not.toHaveBeenCalled();
+ expect(persistedCache).not.toHaveBeenCalled();
expect(updateSyncStatus).toHaveBeenCalledWith(ACCOUNT_ID, 'error');
});
});
@@ -220,17 +223,17 @@ describe('MCP transcript extraction', () => {
runCliProviderPrompt.mockImplementation(cliReply([{ calendarId: CAL_ID, events: [] }]));
expect((await mcpSyncAccount(ACCOUNT_ID, null)).pruned).toBe(1);
expect(savedCache().events).toEqual([]);
- saveCache.mockClear();
+ persistedCache.mockClear();
runCliProviderPrompt.mockResolvedValue({ text: '{"calendars":[]}', exitCode: 0 });
// Nothing was described, so nothing was reconciled: not a success.
expect(await mcpSyncAccount(ACCOUNT_ID, null)).toMatchObject({ calendars: [], status: 'partial' });
- expect(saveCache).not.toHaveBeenCalled();
+ expect(persistedCache).not.toHaveBeenCalled();
});
it.each(['{"calendars":{}}', '{"calendars":[{"calendarId":"example","events":[null]}]}', 'not JSON', 'prompt only'])('rejects invalid sync payload %s before touching events', async text => {
runCliProviderPrompt.mockImplementation(async ({ prompt }) => ({ text: text === 'prompt only' ? `${prompt}\n${prompt}` : text, exitCode: 0 }));
await expect(mcpSyncAccount(ACCOUNT_ID, null)).rejects.toMatchObject({ status: 502 });
- expect(saveCache).not.toHaveBeenCalled();
+ expect(persistedCache).not.toHaveBeenCalled();
expect(updateSyncStatus).toHaveBeenCalledWith(ACCOUNT_ID, 'error');
});
diff --git a/server/services/character.test.js b/server/services/character.test.js
index bdf5f1d7b9..d23f906a28 100644
--- a/server/services/character.test.js
+++ b/server/services/character.test.js
@@ -18,7 +18,6 @@ vi.mock('../lib/fileUtils.js', () => ({
// Independent snapshots, like the real JSON read — a shared object reference would hide the
// lost-update race by letting concurrent writers mutate the same record.
readJSONFile: vi.fn(async (_file, fallback) => (store.value ? JSON.parse(JSON.stringify(store.value)) : fallback)),
- writeFile: vi.fn(),
// atomicWrite replaced the raw writeFile(JSON.stringify) site (#1837); route
// it through the mocked fs/promises.writeFile so the in-memory store update
// (and read-modify-save round-trip) keeps working unchanged.
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
index 77a07c984d..b89437733d 100644
--- a/server/services/importer.test.js
+++ b/server/services/importer.test.js
@@ -58,7 +58,6 @@ vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());
// LLM call resolves to a canned JSON shape we control per-test.
const mockRunStagedLLM = vi.fn();
vi.mock('./stageRunner.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
runStagedLLM: (...args) => mockRunStagedLLM(...args),
}));
diff --git a/server/services/pipeline/audio.test.js b/server/services/pipeline/audio.test.js
index a45ae4466f..7473397040 100644
--- a/server/services/pipeline/audio.test.js
+++ b/server/services/pipeline/audio.test.js
@@ -18,7 +18,6 @@ vi.mock('../../lib/fileUtils.js', async () => {
const synthesizeMock = vi.fn();
const listVoicesMock = vi.fn();
vi.mock('../voice/tts.js', () => ({
- tryReadFile: vi.fn().mockResolvedValue(null),
synthesize: (...a) => synthesizeMock(...a),
listVoices: (...a) => listVoicesMock(...a),
normalizeVoiceEngine: (engine) => engine === 'qwen3' ? 'qwen3-tts' : engine,
diff --git a/server/services/pipeline/comicPdf.test.js b/server/services/pipeline/comicPdf.test.js
index 8c706f5d62..f87f142756 100644
--- a/server/services/pipeline/comicPdf.test.js
+++ b/server/services/pipeline/comicPdf.test.js
@@ -52,7 +52,6 @@ const mockSeries = {
const getIssueMock = vi.fn(async () => structuredClone(mockIssue));
const getSeriesMock = vi.fn(async () => structuredClone(mockSeries));
vi.mock('./issues.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
getIssue: (...a) => getIssueMock(...a),
VISUAL_STAGE_IDS: ['comicPages', 'storyboards', 'episodeVideo'],
STAGE_IDS: ['idea', 'prose', 'comicScript', 'teleplay', 'comicPages', 'storyboards', 'episodeVideo'],
diff --git a/server/services/pipeline/coverFilenameHooks.integration.test.js b/server/services/pipeline/coverFilenameHooks.integration.test.js
index 5d70795ca3..b391e917e0 100644
--- a/server/services/pipeline/coverFilenameHooks.integration.test.js
+++ b/server/services/pipeline/coverFilenameHooks.integration.test.js
@@ -64,7 +64,6 @@ const seasonsOf = (seriesId) => [...seasonStore.entries()]
.map(([key, season]) => ({ id: key.split('::')[1], ...season }));
vi.mock('./series.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
getSeries: vi.fn(async (id) => {
const series = seriesStore.get(id);
return series ? { ...series, seasons: seasonsOf(id) } : null;