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
test: add coverage for sseUtils, tailscale, zipStream, execGit, agentDrafts, brainGraph + 5 routes
Adam Eivy6c11caae63f6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2a445cb05b..5a07d8d064 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,7 @@## Changed+- **Test coverage: +89 tests across 11 previously-uncovered modules.** Added focused unit tests for low-level utilities and route handlers that had 0% coverage in the baseline coverage report: `lib/sseUtils.js` (broadcast/attach/cleanup of SSE clients and the Python-noise filter), `lib/tailscale.js` (CLI-binary discovery across PATH and well-known install paths), `lib/zipStream.js` (streaming ZIP parser — stored + DEFLATE entries, multi-chunk arrival, path-traversal sanitization, autodrain), `lib/execGit.js` (timeout, maxBuffer overflow, ignoreExitCode, spawn-error paths), `routes/avatar.js` (404 + streaming + ENOENT/EIO mid-stream errors via deferred-emit Readable), `routes/agents.js` (kill/list/info with status + body-shape assertions), `routes/notifications.js` (full CRUD, 404 propagation), `routes/usage.js` (summary/raw/session/messages/tokens/reset), `routes/backup.js` (status, run with/without dest, snapshots, restore + zod validation), `services/agentDrafts.js` (per-agent CRUD, sort by createdAt via fake timers, scoping), `services/brainGraph.js` (Jaccard threshold, bridge remap, missing-bridge dropping, dedup with memory edges, getGraphData failure fallback). Total server suite: 2633 → 2722 tests across 103 → 114 files; all pass.- **Refactor: 19 files now use `fetchWithTimeout` instead of hand-rolled `AbortController + setTimeout + fetch + clearTimeout` blocks.** Net 75 lines deleted across `server/services/{browserService, calendarApiSync, digital-twin-helpers, feeds, insightsService, lmStudioManager, memoryClassifier, memoryEmbeddings, messageApiSync, messagePlaywrightSync, messageTokenExtractor, pm2Standardizer, syncOrchestrator, visionTest}.js`, `server/services/voice/{bootstrap, health, stt}.js`, and `server/integrations/{moltbook, moltworld}/api.js`. The helper at `server/lib/fetchWithTimeout.js` already existed and was tested — most call sites just hadn't been migrated. Each file also extracts its magic timeout numbers (3000, 10000, 30000, 60000, 120000, 180000, 300000) to named constants like `HEALTH_TIMEOUT_MS`, `GRAPH_API_TIMEOUT_MS`, `MODEL_LOAD_TIMEOUT_MS`, `DEFAULT_AI_TIMEOUT_MS` so the request lifecycle stops being four scattered statements per call. `browserService.js` additionally hoists three duplicate dynamic `await import('child_process')` / `await import('util')` blocks (one per PM2 helper) to a single top-level import + `execFileAsync` / `PM2_SHELL` constants, and `messageApiSync.js` lifts a per-401 dynamic `await import('./messageTokenExtractor.js')` to a top-level import. All 2633 server tests still pass.- **Vite dev proxy splits `/data` into per-subpath rules.** Replaced the single catch-all `/data` proxy with explicit `/data/images`, `/data/videos`, and `/data/video-thumbnails` entries so app-managed `data/` directories (CoS state, plans, etc.) are served by Vite from disk instead of being silently round-tripped to the API server. File: `client/vite.config.js`.- **Send to Video carries the source image's prompts.** Clicking "Send to Video" on an Image Gen result, gallery card, or lightbox — or the same action from Media History — now pre-populates the Video Gen prompt and negative prompt from the source image's metadata. Previously only the source image filename was passed, leaving the user to retype or paste the prompt to keep the same scene direction. The flow piggybacks on the existing `?sourceImageFile=` query-param hand-off: `?prompt=` and `?negativePrompt=` are added when the source has them, and `VideoGen.jsx` reads both on first render and re-syncs on subsequent navigations (mirroring the existing source-image effect). Files: `client/src/pages/ImageGen.jsx`, `client/src/pages/MediaHistory.jsx`, `client/src/pages/VideoGen.jsx`.diff --git a/server/lib/execGit.test.js b/server/lib/execGit.test.jsnew file mode 100644index 0000000000..5ca1788223--- /dev/null+++ b/server/lib/execGit.test.js@@ -0,0 +1,112 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++vi.mock('child_process', () => ({+ spawn: vi.fn()+}));++import { spawn } from 'child_process';+import { execGit } from './execGit.js';++const makeChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+};++describe('execGit', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('passes args, cwd, and shell:false to spawn', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['status'], '/repo');+ child.emit('close', 0);+ await promise;+ expect(spawn).toHaveBeenCalledWith('git', ['status'], expect.objectContaining({+ cwd: '/repo',+ shell: false,+ windowsHide: true+ }));+ });++ it('resolves with stdout/stderr/exitCode on successful exit', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['log'], '/repo');+ child.stdout.emit('data', Buffer.from('commit-hash'));+ child.stderr.emit('data', Buffer.from(''));+ child.emit('close', 0);+ await expect(promise).resolves.toEqual({+ stdout: 'commit-hash',+ stderr: '',+ exitCode: 0+ });+ });++ it('rejects with stderr on a non-zero exit', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['bogus'], '/repo');+ child.stderr.emit('data', Buffer.from('not a git command'));+ child.emit('close', 1);+ await expect(promise).rejects.toThrow(/not a git command/);+ });++ it('resolves on non-zero exit when ignoreExitCode is true', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['diff', '--exit-code'], '/repo', { ignoreExitCode: true });+ child.stdout.emit('data', Buffer.from('diff content'));+ child.emit('close', 1);+ await expect(promise).resolves.toEqual({+ stdout: 'diff content',+ stderr: '',+ exitCode: 1+ });+ });++ it('rejects with a timeout error and kills the child after the timeout', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['fetch'], '/repo', { timeout: 500 });+ vi.advanceTimersByTime(500);+ await expect(promise).rejects.toThrow(/timed out after 0\.5s/);+ expect(child.kill).toHaveBeenCalled();+ });++ it('rejects when output exceeds maxBuffer', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['log'], '/repo', { maxBuffer: 8 });+ child.stdout.emit('data', Buffer.from('a'.repeat(9)));+ await expect(promise).rejects.toThrow(/maxBuffer/);+ expect(child.kill).toHaveBeenCalled();+ });++ it('rejects on child spawn error', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['status'], '/repo');+ child.emit('error', new Error('spawn ENOENT'));+ await expect(promise).rejects.toThrow(/ENOENT/);+ });++ it('falls back to a generic error message when stderr is empty on non-zero exit', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGit(['x'], '/repo');+ child.emit('close', 2);+ await expect(promise).rejects.toThrow(/exited with code 2/);+ });+});+diff --git a/server/lib/sseUtils.test.js b/server/lib/sseUtils.test.jsnew file mode 100644index 0000000000..979930dac3--- /dev/null+++ b/server/lib/sseUtils.test.js@@ -0,0 +1,157 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ PYTHON_NOISE_RE,+ SSE_CLEANUP_DELAY_MS,+ broadcastSse,+ attachSseClient,+ closeJobAfterDelay+} from './sseUtils.js';++const makeRes = () => {+ const writes = [];+ const closeListeners = [];+ return {+ writes,+ closeListeners,+ writeHead: vi.fn(),+ write: vi.fn((msg) => writes.push(msg)),+ end: vi.fn(),+ req: {+ on: vi.fn((event, fn) => {+ if (event === 'close') closeListeners.push(fn);+ })+ }+ };+};++describe('PYTHON_NOISE_RE', () => {+ it('matches noisy framework warnings', () => {+ expect(PYTHON_NOISE_RE.test('xformers warning')).toBe(true);+ expect(PYTHON_NOISE_RE.test('UserWarning: deprecated')).toBe(true);+ expect(PYTHON_NOISE_RE.test('FutureWarning')).toBe(true);+ expect(PYTHON_NOISE_RE.test('DeprecationWarning')).toBe(true);+ expect(PYTHON_NOISE_RE.test('Set XFORMERS=1')).toBe(true);+ expect(PYTHON_NOISE_RE.test('NOTE: Redirects to ...')).toBe(true);+ });++ it('does not match real progress messages', () => {+ expect(PYTHON_NOISE_RE.test('Step 5/30')).toBe(false);+ expect(PYTHON_NOISE_RE.test('Generated image')).toBe(false);+ expect(PYTHON_NOISE_RE.test('100% complete')).toBe(false);+ });+});++describe('broadcastSse', () => {+ it('writes data: JSON\\n\\n format to all clients and caches lastPayload', () => {+ const c1 = makeRes();+ const c2 = makeRes();+ const job = { clients: [c1, c2] };+ const payload = { progress: 0.5, step: 5 };+ broadcastSse(job, payload);++ const expected = `data: ${JSON.stringify(payload)}\n\n`;+ expect(c1.write).toHaveBeenCalledWith(expected);+ expect(c2.write).toHaveBeenCalledWith(expected);+ expect(job.lastPayload).toEqual(payload);+ });++ it('handles empty client list without error', () => {+ const job = { clients: [] };+ broadcastSse(job, { ok: true });+ expect(job.lastPayload).toEqual({ ok: true });+ });+});++describe('attachSseClient', () => {+ it('returns false when jobId not found', () => {+ const jobs = new Map();+ const res = makeRes();+ expect(attachSseClient(jobs, 'missing', res)).toBe(false);+ expect(res.writeHead).not.toHaveBeenCalled();+ });++ it('writes SSE headers and pushes res into job clients', () => {+ const jobs = new Map();+ const job = { clients: [] };+ jobs.set('j1', job);+ const res = makeRes();++ expect(attachSseClient(jobs, 'j1', res)).toBe(true);+ expect(res.writeHead).toHaveBeenCalledWith(200, expect.objectContaining({+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive'+ }));+ expect(job.clients).toContain(res);+ });++ it('replays lastPayload to a late-joining client', () => {+ const jobs = new Map();+ const lastPayload = { state: 'complete' };+ jobs.set('j1', { clients: [], lastPayload });+ const res = makeRes();++ attachSseClient(jobs, 'j1', res);++ expect(res.write).toHaveBeenCalledWith(`data: ${JSON.stringify(lastPayload)}\n\n`);+ });++ it('skips replay when no lastPayload exists', () => {+ const jobs = new Map();+ jobs.set('j1', { clients: [] });+ const res = makeRes();++ attachSseClient(jobs, 'j1', res);+ expect(res.write).not.toHaveBeenCalled();+ });++ it('removes client from job.clients on req close', () => {+ const jobs = new Map();+ const job = { clients: [] };+ jobs.set('j1', job);+ const res = makeRes();++ attachSseClient(jobs, 'j1', res);+ expect(job.clients).toHaveLength(1);++ for (const fn of res.closeListeners) fn();+ expect(job.clients).toHaveLength(0);+ });+});++describe('closeJobAfterDelay', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('ends each client and deletes job after delay', () => {+ const jobs = new Map();+ const c1 = makeRes();+ const c2 = makeRes();+ jobs.set('j1', { clients: [c1, c2] });++ closeJobAfterDelay(jobs, 'j1', 100);+ expect(jobs.has('j1')).toBe(true);++ vi.advanceTimersByTime(100);+ expect(c1.end).toHaveBeenCalled();+ expect(c2.end).toHaveBeenCalled();+ expect(jobs.has('j1')).toBe(false);+ });++ it('uses the default SSE_CLEANUP_DELAY_MS when no delay is specified', () => {+ const jobs = new Map();+ jobs.set('j1', { clients: [] });++ closeJobAfterDelay(jobs, 'j1');+ vi.advanceTimersByTime(SSE_CLEANUP_DELAY_MS - 1);+ expect(jobs.has('j1')).toBe(true);+ vi.advanceTimersByTime(1);+ expect(jobs.has('j1')).toBe(false);+ });++ it('no-ops gracefully when job already removed', () => {+ const jobs = new Map();+ closeJobAfterDelay(jobs, 'missing', 10);+ expect(() => vi.advanceTimersByTime(10)).not.toThrow();+ });+});diff --git a/server/lib/tailscale.test.js b/server/lib/tailscale.test.jsnew file mode 100644index 0000000000..f6fed3fa47--- /dev/null+++ b/server/lib/tailscale.test.js@@ -0,0 +1,70 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('fs', () => ({+ existsSync: vi.fn()+}));++import { existsSync } from 'fs';+import { findTailscale } from './tailscale.js';++describe('findTailscale', () => {+ let originalPath;++ beforeEach(() => {+ originalPath = process.env.PATH;+ vi.clearAllMocks();+ });++ afterEach(() => {+ process.env.PATH = originalPath;+ });++ it('returns the first matching candidate path', () => {+ const isWin = process.platform === 'win32';+ const expected = isWin+ ? 'C:\\Program Files\\Tailscale\\tailscale.exe'+ : '/Applications/Tailscale.app/Contents/MacOS/Tailscale';+ existsSync.mockImplementation((p) => p === expected);+ expect(findTailscale()).toBe(expected);+ });++ it('falls back to a later candidate when earlier ones are missing', () => {+ const isWin = process.platform === 'win32';+ const target = isWin+ ? 'C:\\Program Files (x86)\\Tailscale\\tailscale.exe'+ : '/opt/homebrew/bin/tailscale';+ existsSync.mockImplementation((p) => p === target);+ expect(findTailscale()).toBe(target);+ });++ it('scans PATH directories when no candidate is found', () => {+ const isWin = process.platform === 'win32';+ const sep = isWin ? ';' : ':';+ const dir = isWin ? 'D:\\custom\\bin' : '/custom/bin';+ const bin = isWin ? 'tailscale.exe' : 'tailscale';+ process.env.PATH = `${dir}${sep}${isWin ? 'D:\\foo' : '/foo'}`;+ existsSync.mockImplementation((p) => p === `${dir}${isWin ? '\\' : '/'}${bin}`);+ expect(findTailscale()).toContain(bin);+ });++ it('returns null when no tailscale binary is anywhere on the system', () => {+ process.env.PATH = '/nowhere';+ existsSync.mockReturnValue(false);+ expect(findTailscale()).toBeNull();+ });++ it('handles an empty PATH gracefully', () => {+ process.env.PATH = '';+ existsSync.mockReturnValue(false);+ expect(findTailscale()).toBeNull();+ });++ it('skips empty path segments produced by adjacent separators', () => {+ const sep = process.platform === 'win32' ? ';' : ':';+ process.env.PATH = `${sep}${sep}`;+ existsSync.mockReturnValue(false);+ expect(findTailscale()).toBeNull();+ const callsWithBin = existsSync.mock.calls.filter(([p]) => /tailscale(\.exe)?$/.test(p));+ expect(callsWithBin.length).toBeGreaterThan(0);+ });+});diff --git a/server/lib/zipStream.test.js b/server/lib/zipStream.test.jsnew file mode 100644index 0000000000..9919a5d3f5--- /dev/null+++ b/server/lib/zipStream.test.js@@ -0,0 +1,141 @@+import { describe, it, expect } from 'vitest';+import { Readable, Writable } from 'stream';+import { deflateRawSync } from 'zlib';+import { parseZip } from './zipStream.js';++const LOCAL_SIG = 0x04034b50;+const CENTRAL_SIG = 0x02014b50;++// Build a minimal local file header for one entry — 30-byte fixed prefix + name + data.+function buildEntry(name, payload, { method = 0 } = {}) {+ const nameBuf = Buffer.from(name, 'utf-8');+ const header = Buffer.alloc(30);+ header.writeUInt32LE(LOCAL_SIG, 0);+ header.writeUInt16LE(20, 4); // version needed+ header.writeUInt16LE(0, 6); // flags (no data descriptor)+ header.writeUInt16LE(method, 8); // 0 = stored, 8 = deflate+ header.writeUInt16LE(0, 10); // mod time+ header.writeUInt16LE(0, 12); // mod date+ header.writeUInt32LE(0, 14); // crc32 (unused by reader)+ header.writeUInt32LE(payload.length, 18); // compressed size+ header.writeUInt32LE(payload.length, 22); // uncompressed size+ header.writeUInt16LE(nameBuf.length, 26);+ header.writeUInt16LE(0, 28); // extra length+ return Buffer.concat([header, nameBuf, payload]);+}++function buildEocd() {+ const buf = Buffer.alloc(4);+ buf.writeUInt32LE(CENTRAL_SIG, 0);+ return buf;+}++function collectEntries(zipBuf) {+ return new Promise((resolve, reject) => {+ const entryPromises = [];+ const parser = parseZip();+ parser.on('entry', (entry) => {+ entryPromises.push(new Promise((res) => {+ const chunks = [];+ const sink = new Writable({+ write(chunk, _, cb) { chunks.push(chunk); cb(); }+ });+ sink.on('finish', () => res({ path: entry.path, data: Buffer.concat(chunks) }));+ entry.pipe(sink);+ }));+ });+ parser.on('close', () => Promise.all(entryPromises).then(resolve, reject));+ parser.on('error', reject);+ Readable.from([zipBuf]).pipe(parser);+ });+}++describe('parseZip', () => {+ it('parses a single stored entry', async () => {+ const data = Buffer.from('hello world');+ const zip = Buffer.concat([buildEntry('hello.txt', data), buildEocd()]);+ const entries = await collectEntries(zip);+ expect(entries).toHaveLength(1);+ expect(entries[0].path).toBe('hello.txt');+ expect(entries[0].data.toString()).toBe('hello world');+ });++ it('parses a deflated entry by decompressing the stream', async () => {+ const original = Buffer.from('Compressed payload that should round-trip cleanly');+ const compressed = deflateRawSync(original);+ const zip = Buffer.concat([buildEntry('comp.txt', compressed, { method: 8 }), buildEocd()]);+ const entries = await collectEntries(zip);+ expect(entries).toHaveLength(1);+ expect(entries[0].data.toString()).toBe(original.toString());+ });++ it('parses multiple entries in order', async () => {+ const a = buildEntry('a.txt', Buffer.from('A'));+ const b = buildEntry('b.txt', Buffer.from('BB'));+ const c = buildEntry('c.txt', Buffer.from('CCC'));+ const zip = Buffer.concat([a, b, c, buildEocd()]);+ const entries = await collectEntries(zip);+ expect(entries.map(e => e.path)).toEqual(['a.txt', 'b.txt', 'c.txt']);+ expect(entries[2].data.toString()).toBe('CCC');+ });++ it('sanitizes path traversal segments in entry names', async () => {+ const data = Buffer.from('payload');+ const zip = Buffer.concat([buildEntry('../../etc/passwd', data), buildEocd()]);+ const entries = await collectEntries(zip);+ expect(entries[0].path).toBe('etc/passwd');+ });++ it('normalizes Windows-style backslash separators to forward slashes', async () => {+ const data = Buffer.from('x');+ const zip = Buffer.concat([buildEntry('dir\\sub\\file.txt', data), buildEocd()]);+ const entries = await collectEntries(zip);+ expect(entries[0].path).toBe('dir/sub/file.txt');+ });++ it('autodrains entries whose consumer never pipes', async () => {+ const data = Buffer.from('ignored');+ const zip = Buffer.concat([+ buildEntry('skip.txt', data),+ buildEntry('keep.txt', Buffer.from('kept')),+ buildEocd()+ ]);++ return new Promise((resolve, reject) => {+ const entryPromises = [];+ const parser = parseZip();+ parser.on('entry', (entry) => {+ if (entry.path === 'skip.txt') return;+ entryPromises.push(new Promise((res) => {+ const chunks = [];+ const sink = new Writable({+ write(c, _, cb) { chunks.push(c); cb(); }+ });+ sink.on('finish', () => res({ path: entry.path, data: Buffer.concat(chunks) }));+ entry.pipe(sink);+ }));+ });+ parser.on('close', () => Promise.all(entryPromises).then((out) => {+ try {+ expect(out).toHaveLength(1);+ expect(out[0].path).toBe('keep.txt');+ expect(out[0].data.toString()).toBe('kept');+ resolve();+ } catch (err) { reject(err); }+ }, reject));+ parser.on('error', reject);+ Readable.from([zip]).pipe(parser);+ });+ });++ it('handles multi-chunk arrival of the input buffer', async () => {+ const data = Buffer.from('split across chunks');+ const zip = Buffer.concat([buildEntry('chunked.txt', data), buildEocd()]);+ const pieces = [];+ for (let i = 0; i < zip.length; i += 5) {+ pieces.push(zip.slice(i, Math.min(i + 5, zip.length)));+ }+ const entries = await collectEntries(Buffer.concat(pieces));+ expect(entries[0].data.toString()).toBe(data.toString());+ });+});diff --git a/server/routes/agents.test.js b/server/routes/agents.test.jsnew file mode 100644index 0000000000..f095a3c325--- /dev/null+++ b/server/routes/agents.test.js@@ -0,0 +1,88 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/agents.js', () => ({+ getRunningAgents: vi.fn(),+ killProcess: vi.fn(),+ getProcessInfo: vi.fn()+}));++import { getRunningAgents, killProcess, getProcessInfo } from '../services/agents.js';+import agentsRoutes from './agents.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/agents', agentsRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('agents routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('GET /api/agents', () => {+ it('returns the list of running agents', async () => {+ getRunningAgents.mockResolvedValue([+ { pid: 100, agentName: 'Claude', command: 'claude --foo' },+ { pid: 200, agentName: 'Codex', command: 'codex run' }+ ]);+ const res = await request(buildApp()).get('/api/agents');+ expect(res.status).toBe(200);+ expect(res.body).toHaveLength(2);+ expect(res.body[0].agentName).toBe('Claude');+ });++ it('returns an empty array when no agents are running', async () => {+ getRunningAgents.mockResolvedValue([]);+ const res = await request(buildApp()).get('/api/agents');+ expect(res.status).toBe(200);+ expect(res.body).toEqual([]);+ });+ });++ describe('GET /api/agents/:pid', () => {+ it('returns process info for an existing pid', async () => {+ getProcessInfo.mockResolvedValue({ pid: 1234, cpu: 12.3, memory: 45.6 });+ const res = await request(buildApp()).get('/api/agents/1234');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ pid: 1234, cpu: 12.3, memory: 45.6 });+ expect(getProcessInfo).toHaveBeenCalledWith(1234);+ });++ it('returns 404 when the pid is not found', async () => {+ getProcessInfo.mockResolvedValue(null);+ const res = await request(buildApp()).get('/api/agents/9999');+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('NOT_FOUND');+ expect(res.body.error).toMatch(/process not found/i);+ });++ it('coerces the pid param to an integer before service lookup', async () => {+ getProcessInfo.mockResolvedValue({ pid: 42 });+ await request(buildApp()).get('/api/agents/42abc');+ expect(getProcessInfo).toHaveBeenCalledWith(42);+ });+ });++ describe('DELETE /api/agents/:pid', () => {+ it('kills the process and returns success with the parsed pid', async () => {+ killProcess.mockResolvedValue(true);+ const res = await request(buildApp()).delete('/api/agents/5555');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, pid: 5555 });+ expect(killProcess).toHaveBeenCalledWith(5555);+ });++ it('propagates a service error to the centralized error middleware', async () => {+ killProcess.mockRejectedValue(new Error('Invalid PID provided'));+ const res = await request(buildApp()).delete('/api/agents/-1');+ expect(res.status).toBe(500);+ expect(res.body.error).toMatch(/invalid pid/i);+ });+ });+});diff --git a/server/routes/avatar.test.js b/server/routes/avatar.test.jsnew file mode 100644index 0000000000..3feec9c7e4--- /dev/null+++ b/server/routes/avatar.test.js@@ -0,0 +1,89 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { Readable } from 'stream';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('fs', () => ({+ existsSync: vi.fn(),+ statSync: vi.fn(),+ createReadStream: vi.fn()+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { data: '/mock/data' }+}));++import { existsSync, statSync, createReadStream } from 'fs';+import avatarRoutes from './avatar.js';++const buildApp = () => {+ const app = express();+ app.use('/api/avatar', avatarRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('avatar routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('GET /model.glb', () => {+ it('returns 404 JSON when file is missing', async () => {+ existsSync.mockReturnValue(false);+ const res = await request(buildApp()).get('/api/avatar/model.glb');+ expect(res.status).toBe(404);+ expect(res.body.error).toMatch(/avatar model/i);+ });++ it('streams model.glb content with correct headers', async () => {+ existsSync.mockReturnValue(true);+ const fakeStream = Readable.from([Buffer.from('GLB-FAKE-CONTENT')]);+ createReadStream.mockReturnValue(fakeStream);++ const res = await request(buildApp()).get('/api/avatar/model.glb');+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toBe('model/gltf-binary');+ expect(res.headers['cache-control']).toBe('public, max-age=60');+ expect(res.text).toBe('GLB-FAKE-CONTENT');+ });++ it('responds with 404 when stream errors with ENOENT before headers sent', async () => {+ existsSync.mockReturnValue(true);+ const errStream = new Readable({+ read() {+ process.nextTick(() => {+ const err = new Error('not found');+ err.code = 'ENOENT';+ this.emit('error', err);+ });+ }+ });+ createReadStream.mockReturnValue(errStream);++ const res = await request(buildApp()).get('/api/avatar/model.glb');+ expect(res.status).toBe(404);+ // The route sets Content-Type to gltf-binary before piping; res.json() does+ // not overwrite an existing Content-Type, so the body arrives as text.+ expect(JSON.parse(res.text).error).toMatch(/unavailable/i);+ });++ it('responds with 500 on non-ENOENT stream error before headers sent', async () => {+ existsSync.mockReturnValue(true);+ const errStream = new Readable({+ read() {+ process.nextTick(() => {+ const err = new Error('disk read failed');+ err.code = 'EIO';+ this.emit('error', err);+ });+ }+ });+ createReadStream.mockReturnValue(errStream);++ const res = await request(buildApp()).get('/api/avatar/model.glb');+ expect(res.status).toBe(500);+ });+ });+});diff --git a/server/routes/backup.test.js b/server/routes/backup.test.jsnew file mode 100644index 0000000000..622eead7fa--- /dev/null+++ b/server/routes/backup.test.js@@ -0,0 +1,145 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/backup.js', () => ({+ getState: vi.fn(),+ getNextRunTime: vi.fn(),+ runBackup: vi.fn(),+ listSnapshots: vi.fn(),+ restoreSnapshot: vi.fn()+}));++vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn()+}));++import * as backup from '../services/backup.js';+import { getSettings } from '../services/settings.js';+import backupRoutes from './backup.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/backup', backupRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('backup routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('GET /api/backup/status', () => {+ it('returns merged state, configured destPath, and nextRun', async () => {+ backup.getState.mockResolvedValue({ lastRun: '2026-04-01T00:00:00Z', success: true });+ backup.getNextRunTime.mockReturnValue('2026-04-08T00:00:00Z');+ getSettings.mockResolvedValue({ backup: { destPath: '/backup/target' } });++ const res = await request(buildApp()).get('/api/backup/status');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({+ lastRun: '2026-04-01T00:00:00Z',+ success: true,+ destPath: '/backup/target',+ nextRun: '2026-04-08T00:00:00Z'+ });+ });++ it('returns null destPath when backup is not configured', async () => {+ backup.getState.mockResolvedValue({});+ backup.getNextRunTime.mockReturnValue(null);+ getSettings.mockResolvedValue({});+ const res = await request(buildApp()).get('/api/backup/status');+ expect(res.status).toBe(200);+ expect(res.body.destPath).toBeNull();+ });+ });++ describe('POST /api/backup/run', () => {+ it('returns 400 when no destination is configured', async () => {+ getSettings.mockResolvedValue({ backup: {} });+ const res = await request(buildApp()).post('/api/backup/run');+ expect(res.status).toBe(400);+ expect(res.body.error).toBe('BACKUP_NOT_CONFIGURED');+ expect(backup.runBackup).not.toHaveBeenCalled();+ });++ it('runs the backup and forwards excludePaths', async () => {+ getSettings.mockResolvedValue({+ backup: { destPath: '/dest', excludePaths: ['node_modules', '.git'] }+ });+ backup.runBackup.mockResolvedValue({ success: true, files: 100 });+ const res = await request(buildApp()).post('/api/backup/run');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, files: 100 });+ expect(backup.runBackup).toHaveBeenCalledWith(+ '/dest',+ undefined,+ { excludePaths: ['node_modules', '.git'] }+ );+ });++ it('passes empty excludePaths when not configured', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });+ backup.runBackup.mockResolvedValue({ success: true });+ await request(buildApp()).post('/api/backup/run');+ expect(backup.runBackup).toHaveBeenCalledWith(+ '/dest',+ undefined,+ { excludePaths: [] }+ );+ });+ });++ describe('GET /api/backup/snapshots', () => {+ it('returns the list of snapshots from the configured destPath', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });+ backup.listSnapshots.mockResolvedValue([{ id: 's1' }, { id: 's2' }]);+ const res = await request(buildApp()).get('/api/backup/snapshots');+ expect(res.status).toBe(200);+ expect(res.body).toHaveLength(2);+ expect(backup.listSnapshots).toHaveBeenCalledWith('/dest');+ });+ });++ describe('POST /api/backup/restore', () => {+ it('returns 400 when snapshotId is missing', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });+ const res = await request(buildApp()).post('/api/backup/restore').send({});+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(backup.restoreSnapshot).not.toHaveBeenCalled();+ });++ it('forwards a valid restore request to the service', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });+ backup.restoreSnapshot.mockResolvedValue({ success: true, restored: 42 });+ const res = await request(buildApp())+ .post('/api/backup/restore')+ .send({ snapshotId: 'snap-1', subdirFilter: 'data', dryRun: false });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, restored: 42 });+ expect(backup.restoreSnapshot).toHaveBeenCalledWith(+ '/dest',+ 'snap-1',+ { dryRun: false, subdirFilter: 'data' }+ );+ });++ it('defaults dryRun to true when omitted', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });+ backup.restoreSnapshot.mockResolvedValue({ success: true });+ await request(buildApp())+ .post('/api/backup/restore')+ .send({ snapshotId: 'snap-2' });+ expect(backup.restoreSnapshot).toHaveBeenCalledWith(+ '/dest',+ 'snap-2',+ expect.objectContaining({ dryRun: true })+ );+ });+ });+});diff --git a/server/routes/notifications.test.js b/server/routes/notifications.test.jsnew file mode 100644index 0000000000..9723b922d7--- /dev/null+++ b/server/routes/notifications.test.js@@ -0,0 +1,131 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/notifications.js', () => ({+ getNotifications: vi.fn(),+ getUnreadCount: vi.fn(),+ getCountsByType: vi.fn(),+ markAsRead: vi.fn(),+ markAllAsRead: vi.fn(),+ removeNotification: vi.fn(),+ clearAll: vi.fn(),+ NOTIFICATION_TYPES: {+ MEMORY_APPROVAL: 'memory_approval',+ TASK_APPROVAL: 'task_approval'+ }+}));++import * as notifications from '../services/notifications.js';+import notificationsRoutes from './notifications.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/notifications', notificationsRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('notifications routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('GET /api/notifications', () => {+ it('returns the notifications list with default options', async () => {+ notifications.getNotifications.mockResolvedValue({ items: [{ id: 'n1' }], total: 1 });+ const res = await request(buildApp()).get('/api/notifications');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ items: [{ id: 'n1' }], total: 1 });+ expect(notifications.getNotifications).toHaveBeenCalledWith({+ type: undefined,+ unreadOnly: false,+ limit: undefined+ });+ });++ it('parses query string options into the service call', async () => {+ notifications.getNotifications.mockResolvedValue({ items: [], total: 0 });+ const type = notifications.NOTIFICATION_TYPES.MEMORY_APPROVAL;+ await request(buildApp()).get(`/api/notifications?type=${type}&unreadOnly=true&limit=25`);+ expect(notifications.getNotifications).toHaveBeenCalledWith({+ type,+ unreadOnly: true,+ limit: 25+ });+ });+ });++ describe('GET /api/notifications/count', () => {+ it('returns the unread count', async () => {+ notifications.getUnreadCount.mockResolvedValue(7);+ const res = await request(buildApp()).get('/api/notifications/count');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ count: 7 });+ });+ });++ describe('GET /api/notifications/counts', () => {+ it('returns counts grouped by type', async () => {+ const grouped = {+ [notifications.NOTIFICATION_TYPES.MEMORY_APPROVAL]: 3,+ [notifications.NOTIFICATION_TYPES.TASK_APPROVAL]: 2+ };+ notifications.getCountsByType.mockResolvedValue(grouped);+ const res = await request(buildApp()).get('/api/notifications/counts');+ expect(res.status).toBe(200);+ expect(res.body).toEqual(grouped);+ });+ });++ describe('POST /api/notifications/:id/read', () => {+ it('marks a notification read on success', async () => {+ notifications.markAsRead.mockResolvedValue({ success: true, id: 'n1' });+ const res = await request(buildApp()).post('/api/notifications/n1/read');+ expect(res.status).toBe(200);+ expect(res.body.success).toBe(true);+ expect(notifications.markAsRead).toHaveBeenCalledWith('n1');+ });++ it('returns 404 when the notification is missing', async () => {+ notifications.markAsRead.mockResolvedValue({ success: false, error: 'Not found' });+ const res = await request(buildApp()).post('/api/notifications/missing/read');+ expect(res.status).toBe(404);+ });+ });++ describe('POST /api/notifications/read-all', () => {+ it('marks all notifications read', async () => {+ notifications.markAllAsRead.mockResolvedValue({ success: true, marked: 5 });+ const res = await request(buildApp()).post('/api/notifications/read-all');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, marked: 5 });+ });+ });++ describe('DELETE /api/notifications/:id', () => {+ it('removes the notification on success', async () => {+ notifications.removeNotification.mockResolvedValue({ success: true });+ const res = await request(buildApp()).delete('/api/notifications/n1');+ expect(res.status).toBe(200);+ expect(notifications.removeNotification).toHaveBeenCalledWith('n1');+ });++ it('returns 404 when the notification is missing', async () => {+ notifications.removeNotification.mockResolvedValue({ success: false, error: 'gone' });+ const res = await request(buildApp()).delete('/api/notifications/missing');+ expect(res.status).toBe(404);+ });+ });++ describe('DELETE /api/notifications', () => {+ it('clears all notifications', async () => {+ notifications.clearAll.mockResolvedValue({ success: true, cleared: 12 });+ const res = await request(buildApp()).delete('/api/notifications');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, cleared: 12 });+ });+ });+});diff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsnew file mode 100644index 0000000000..44913aecbb--- /dev/null+++ b/server/routes/usage.test.js@@ -0,0 +1,85 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/usage.js', () => ({+ getUsageSummary: vi.fn(),+ getUsage: vi.fn(),+ recordSession: vi.fn(),+ recordMessages: vi.fn(),+ recordTokens: vi.fn(),+ resetUsage: vi.fn()+}));++import * as usage from '../services/usage.js';+import usageRoutes from './usage.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/usage', usageRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('usage routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('GET /api/usage returns the usage summary', async () => {+ usage.getUsageSummary.mockReturnValue({ totalSessions: 4, providers: ['anthropic'] });+ const res = await request(buildApp()).get('/api/usage');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ totalSessions: 4, providers: ['anthropic'] });+ });++ it('GET /api/usage/raw returns the raw usage data', async () => {+ usage.getUsage.mockReturnValue({ sessions: [{ providerId: 'p1' }] });+ const res = await request(buildApp()).get('/api/usage/raw');+ expect(res.status).toBe(200);+ expect(res.body.sessions[0].providerId).toBe('p1');+ });++ it('POST /api/usage/session records a session and returns its number', async () => {+ usage.recordSession.mockResolvedValue(42);+ const res = await request(buildApp())+ .post('/api/usage/session')+ .send({ providerId: 'anthropic', providerName: 'Anthropic', model: 'opus' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ sessionNumber: 42 });+ expect(usage.recordSession).toHaveBeenCalledWith('anthropic', 'Anthropic', 'opus');+ });++ it('POST /api/usage/messages records messages and returns success', async () => {+ usage.recordMessages.mockResolvedValue();+ const res = await request(buildApp())+ .post('/api/usage/messages')+ .send({ providerId: 'p1', model: 'm', messageCount: 3, tokenCount: 1000 });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true });+ expect(usage.recordMessages).toHaveBeenCalledWith('p1', 'm', 3, 1000);+ });++ it('POST /api/usage/tokens defaults missing token counts to 0', async () => {+ usage.recordTokens.mockResolvedValue();+ const res = await request(buildApp()).post('/api/usage/tokens').send({});+ expect(res.status).toBe(200);+ expect(usage.recordTokens).toHaveBeenCalledWith(0, 0);+ });++ it('POST /api/usage/tokens passes through provided counts', async () => {+ usage.recordTokens.mockResolvedValue();+ await request(buildApp()).post('/api/usage/tokens').send({ inputTokens: 500, outputTokens: 200 });+ expect(usage.recordTokens).toHaveBeenCalledWith(500, 200);+ });++ it('DELETE /api/usage resets usage data', async () => {+ usage.resetUsage.mockResolvedValue();+ const res = await request(buildApp()).delete('/api/usage');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true });+ expect(usage.resetUsage).toHaveBeenCalled();+ });+});diff --git a/server/services/agentDrafts.test.js b/server/services/agentDrafts.test.jsnew file mode 100644index 0000000000..0c6979beb5--- /dev/null+++ b/server/services/agentDrafts.test.js@@ -0,0 +1,123 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const fileStore = new Map();++vi.mock('fs/promises', () => ({+ readFile: vi.fn(async (path) => {+ if (!fileStore.has(path)) {+ const err = new Error('ENOENT');+ err.code = 'ENOENT';+ throw err;+ }+ return fileStore.get(path);+ }),+ writeFile: vi.fn(async (path, data) => {+ fileStore.set(path, data);+ })+}));++vi.mock('../lib/uuid.js', () => {+ let counter = 0;+ return { v4: () => `uuid-${++counter}` };+});++vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn().mockResolvedValue(undefined),+ PATHS: { agentPersonalities: '/mock/agents' },+ safeJSONParse: (s, fallback) => { try { return JSON.parse(s); } catch { return fallback; } }+}));++const { listDrafts, getDraft, createDraft, updateDraft, deleteDraft } = await import('./agentDrafts.js');++describe('agentDrafts service', () => {+ beforeEach(() => {+ fileStore.clear();+ });++ it('listDrafts returns an empty array when no drafts file exists', async () => {+ expect(await listDrafts('agent-1')).toEqual([]);+ });++ it('createDraft persists the draft with generated id, timestamp, and defaults', async () => {+ const entry = await createDraft('agent-1', {+ type: 'post',+ title: 'Hello',+ content: 'Body here'+ });+ expect(entry.id).toMatch(/^uuid-/);+ expect(entry.type).toBe('post');+ expect(entry.title).toBe('Hello');+ expect(entry.content).toBe('Body here');+ expect(entry.status).toBe('draft');+ expect(entry.accountId).toBeNull();+ expect(typeof entry.createdAt).toBe('string');++ const persisted = await listDrafts('agent-1');+ expect(persisted).toHaveLength(1);+ expect(persisted[0].id).toBe(entry.id);+ });++ it('listDrafts returns drafts sorted by createdAt descending', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2020-01-01T00:00:00Z'));+ const older = await createDraft('agent-1', { type: 'post', content: 'first' });+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));+ const newer = await createDraft('agent-1', { type: 'comment', content: 'second' });+ vi.useRealTimers();++ const result = await listDrafts('agent-1');+ expect(result.map(d => d.id)).toEqual([newer.id, older.id]);+ });++ it('getDraft returns the matching draft or null', async () => {+ const entry = await createDraft('agent-2', { type: 'post', content: 'x' });+ const found = await getDraft('agent-2', entry.id);+ expect(found.id).toBe(entry.id);++ const missing = await getDraft('agent-2', 'nope');+ expect(missing).toBeNull();+ });++ it('updateDraft merges updates, stamps updatedAt, and returns the new record', async () => {+ const entry = await createDraft('agent-3', { type: 'post', content: 'original' });+ const updated = await updateDraft('agent-3', entry.id, {+ content: 'edited',+ status: 'queued'+ });+ expect(updated.id).toBe(entry.id);+ expect(updated.content).toBe('edited');+ expect(updated.status).toBe('queued');+ expect(typeof updated.updatedAt).toBe('string');++ const persisted = await getDraft('agent-3', entry.id);+ expect(persisted.content).toBe('edited');+ });++ it('updateDraft returns null when the draft id is unknown', async () => {+ await createDraft('agent-4', { type: 'post', content: 'a' });+ expect(await updateDraft('agent-4', 'missing', { content: 'b' })).toBeNull();+ });++ it('deleteDraft removes the draft and returns true', async () => {+ const entry = await createDraft('agent-5', { type: 'post', content: 'x' });+ expect(await deleteDraft('agent-5', entry.id)).toBe(true);+ expect(await listDrafts('agent-5')).toEqual([]);+ });++ it('deleteDraft returns false when the draft id does not exist', async () => {+ await createDraft('agent-6', { type: 'post', content: 'x' });+ expect(await deleteDraft('agent-6', 'nope')).toBe(false);+ expect(await listDrafts('agent-6')).toHaveLength(1);+ });++ it('drafts are scoped per agent — different agentIds do not share drafts', async () => {+ await createDraft('agent-A', { type: 'post', content: 'A' });+ await createDraft('agent-B', { type: 'post', content: 'B' });+ const a = await listDrafts('agent-A');+ const b = await listDrafts('agent-B');+ expect(a).toHaveLength(1);+ expect(b).toHaveLength(1);+ expect(a[0].content).toBe('A');+ expect(b[0].content).toBe('B');+ });+});diff --git a/server/services/brainGraph.test.js b/server/services/brainGraph.test.jsnew file mode 100644index 0000000000..8528e7b46c--- /dev/null+++ b/server/services/brainGraph.test.js@@ -0,0 +1,174 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./brainStorage.js', () => ({+ getAll: vi.fn()+}));++vi.mock('./memoryBackend.js', () => ({+ getGraphData: vi.fn()+}));++vi.mock('./brainMemoryBridge.js', () => ({+ loadBridgeMap: vi.fn(),+ bridgeKey: (type, id) => `${type}:${id}`+}));++import * as brainStorage from './brainStorage.js';+import * as memoryBackend from './memoryBackend.js';+import { loadBridgeMap } from './brainMemoryBridge.js';+import { getBrainGraphData } from './brainGraph.js';++describe('getBrainGraphData', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ loadBridgeMap.mockResolvedValue({});+ memoryBackend.getGraphData.mockResolvedValue(null);+ brainStorage.getAll.mockResolvedValue([]);+ });++ it('returns empty graph when no entities exist', async () => {+ const result = await getBrainGraphData();+ expect(result).toEqual({ nodes: [], edges: [], hasEmbeddings: false });+ });++ it('skips archived records and aggregates the remaining entities into nodes', async () => {+ brainStorage.getAll.mockImplementation(async (type) => {+ if (type === 'people') return [+ { id: 'p1', name: 'Alice', tags: ['friend'], archived: false },+ { id: 'p2', name: 'Bob', tags: [], archived: true }+ ];+ if (type === 'projects') return [+ { id: 'pr1', title: 'Phoenix', context: 'launch q4', tags: ['work'] }+ ];+ return [];+ });++ const result = await getBrainGraphData();+ expect(result.nodes).toHaveLength(2);+ const labels = result.nodes.map(n => n.label);+ expect(labels).toContain('Alice');+ expect(labels).toContain('Phoenix');+ });++ it('falls back to "(untitled)" when an entity has no name/title', async () => {+ brainStorage.getAll.mockImplementation(async (type) =>+ type === 'ideas' ? [{ id: 'i1', tags: [] }] : []+ );+ const result = await getBrainGraphData();+ expect(result.nodes[0].label).toBe('(untitled)');+ });++ it('emits shared_tag edges when Jaccard similarity meets the 0.3 threshold', async () => {+ brainStorage.getAll.mockImplementation(async (type) =>+ type === 'people' ? [+ { id: 'a', name: 'A', tags: ['x', 'y'] },+ { id: 'b', name: 'B', tags: ['x', 'y', 'z'] }+ ] : []+ );++ const result = await getBrainGraphData();+ const tagEdges = result.edges.filter(e => e.type === 'shared_tag');+ expect(tagEdges).toHaveLength(1);+ expect(tagEdges[0].weight).toBeCloseTo(2 / 3, 5);+ expect([tagEdges[0].source, tagEdges[0].target].sort()).toEqual(['a', 'b']);+ });++ it('does not emit shared_tag edges below the 0.3 Jaccard threshold', async () => {+ brainStorage.getAll.mockImplementation(async (type) =>+ type === 'people' ? [+ { id: 'a', name: 'A', tags: ['x', 'p', 'q'] },+ { id: 'b', name: 'B', tags: ['x', 'r', 's'] }+ ] : []+ );+ const result = await getBrainGraphData();+ expect(result.edges).toEqual([]);+ });++ it('remaps CoS memory edges through the bridge to brain ids', async () => {+ brainStorage.getAll.mockImplementation(async (type) =>+ type === 'people' ? [+ { id: 'p1', name: 'Alice' },+ { id: 'p2', name: 'Bob' }+ ] : []+ );+ loadBridgeMap.mockResolvedValue({+ 'people:p1': 'mem-1',+ 'people:p2': 'mem-2'+ });+ memoryBackend.getGraphData.mockResolvedValue({+ edges: [+ { source: 'mem-1', target: 'mem-2', type: 'similar', weight: 0.9 }+ ]+ });++ const result = await getBrainGraphData();+ expect(result.hasEmbeddings).toBe(true);+ expect(result.edges).toHaveLength(1);+ expect([result.edges[0].source, result.edges[0].target].sort()).toEqual(['p1', 'p2']);+ expect(result.edges[0].type).toBe('similar');+ expect(result.edges[0].weight).toBe(0.9);+ });++ it('preserves explicit "linked" type and does not flip hasEmbeddings on its own', async () => {+ brainStorage.getAll.mockImplementation(async (type) =>+ type === 'projects' ? [+ { id: 'a', title: 'A' },+ { id: 'b', title: 'B' }+ ] : []+ );+ loadBridgeMap.mockResolvedValue({+ 'projects:a': 'm-a',+ 'projects:b': 'm-b'+ });+ memoryBackend.getGraphData.mockResolvedValue({+ edges: [{ source: 'm-a', target: 'm-b', type: 'linked', weight: 1 }]+ });++ const result = await getBrainGraphData();+ expect(result.edges[0].type).toBe('linked');+ expect(result.hasEmbeddings).toBe(false);+ });++ it('drops cos edges whose endpoints are not in the bridge', async () => {+ brainStorage.getAll.mockImplementation(async (type) =>+ type === 'people' ? [{ id: 'p1', name: 'A' }] : []+ );+ loadBridgeMap.mockResolvedValue({});+ memoryBackend.getGraphData.mockResolvedValue({+ edges: [{ source: 'mem-X', target: 'mem-Y', type: 'similar', weight: 0.5 }]+ });+ const result = await getBrainGraphData();+ expect(result.edges).toEqual([]);+ });++ it('handles a memoryBackend.getGraphData failure by treating it as no edges', async () => {+ brainStorage.getAll.mockImplementation(async (type) =>+ type === 'people' ? [{ id: 'p1', name: 'A' }] : []+ );+ memoryBackend.getGraphData.mockRejectedValue(new Error('embeddings unavailable'));+ const result = await getBrainGraphData();+ expect(result.nodes).toHaveLength(1);+ expect(result.edges).toEqual([]);+ expect(result.hasEmbeddings).toBe(false);+ });++ it('does not duplicate an edge that exists both as a memory link and a tag overlap', async () => {+ brainStorage.getAll.mockImplementation(async (type) =>+ type === 'people' ? [+ { id: 'a', name: 'A', tags: ['x', 'y'] },+ { id: 'b', name: 'B', tags: ['x', 'y'] }+ ] : []+ );+ loadBridgeMap.mockResolvedValue({+ 'people:a': 'm-a',+ 'people:b': 'm-b'+ });+ memoryBackend.getGraphData.mockResolvedValue({+ edges: [{ source: 'm-a', target: 'm-b', type: 'similar', weight: 0.95 }]+ });++ const result = await getBrainGraphData();+ expect(result.edges).toHaveLength(1);+ expect(result.edges[0].type).toBe('similar');+ });+});