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
address review: fix autobiography notification, skip logic, deps, and add tests
Adam Eivydf6c2542ff1b
diff --git a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx b/client/src/components/digital-twin/tabs/AutobiographyTab.jsxindex 9a4ce2f903..99650f433e 100644--- a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx+++ b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx@@ -67,7 +67,7 @@ export default function AutobiographyTab({ onRefresh }) {loadPromptById(promptParam);setSearchParams({}, { replace: true });}- }, [loading, searchParams]);+ }, [loading, searchParams, setSearchParams]);const loadPromptById = async (promptId) => {const prompt = await api.getAutobiographyPromptById(promptId).catch(() => null);@@ -91,7 +91,7 @@ export default function AutobiographyTab({ onRefresh }) {};const skipPrompt = async () => {- const prompt = await api.getAutobiographyPrompt().catch(() => null);+ const prompt = await api.getAutobiographyPrompt(currentPrompt?.id).catch(() => null);if (prompt && prompt.id !== currentPrompt?.id) {setCurrentPrompt(prompt);setStoryContent('');diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 28b70ce4b8..517befec19 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1084,7 +1084,8 @@ export const updateAutobiographyConfig = (config) => request('/digital-twin/autobody: JSON.stringify(config)});export const getAutobiographyThemes = () => request('/digital-twin/autobiography/themes');-export const getAutobiographyPrompt = () => request('/digital-twin/autobiography/prompt');+export const getAutobiographyPrompt = (exclude) =>+ request(`/digital-twin/autobiography/prompt${exclude ? `?exclude=${exclude}` : ''}`);export const getAutobiographyPromptById = (id) => request(`/digital-twin/autobiography/prompt/${id}`);export const getAutobiographyStories = (theme = null) =>request(`/digital-twin/autobiography/stories${theme ? `?theme=${theme}` : ''}`);diff --git a/package-lock.json b/package-lock.jsonindex 289f65a13d..5e1d7ddc15 100644--- a/package-lock.json+++ b/package-lock.json@@ -102,6 +102,7 @@"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.27.1","@babel/generator": "^7.28.5",@@ -395,6 +396,7 @@"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz","integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==","license": "MIT",+ "peer": true,"dependencies": {"@dnd-kit/accessibility": "^3.1.1","@dnd-kit/utilities": "^3.2.2",@@ -437,7 +439,6 @@"integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==","license": "MIT","optional": true,- "peer": true,"dependencies": {"tslib": "^2.4.0"}@@ -890,7 +891,6 @@"integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==","license": "MIT","optional": true,- "peer": true,"engines": {"node": ">=18"}@@ -907,7 +907,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -930,7 +929,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -953,7 +951,6 @@"os": ["darwin"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -970,7 +967,6 @@"os": ["darwin"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -987,7 +983,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1004,7 +999,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1021,7 +1015,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1038,7 +1031,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1055,7 +1047,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1072,7 +1063,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1089,7 +1079,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1106,7 +1095,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1123,7 +1111,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1146,7 +1133,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1169,7 +1155,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1192,7 +1177,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1215,7 +1199,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1238,7 +1221,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1261,7 +1243,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1284,7 +1265,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1304,7 +1284,6 @@],"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT","optional": true,- "peer": true,"dependencies": {"@emnapi/runtime": "^1.7.0"},@@ -1327,7 +1306,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1347,7 +1325,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1367,7 +1344,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1447,8 +1423,7 @@"version": "16.1.6","resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.6.tgz","integrity": "sha512-N1ySLuZjnAtN3kFnwhAwPvZah8RJxKasD7x1f8shFqhncnWZn4JMfg37diLNuoHsLAlrDfM3g4mawVdtAG8XLQ==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@next/swc-darwin-arm64": {"version": "16.1.6",@@ -1462,7 +1437,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 10"}@@ -1479,7 +1453,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 10"}@@ -1496,7 +1469,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1513,7 +1485,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1530,7 +1501,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1547,7 +1517,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1564,7 +1533,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 10"}@@ -1581,7 +1549,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 10"}@@ -2015,6 +1982,7 @@"resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.18.0.tgz","integrity": "sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==","license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.17.8","@types/react-reconciler": "^0.26.7",@@ -2460,7 +2428,6 @@"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz","integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==","license": "Apache-2.0",- "peer": true,"dependencies": {"tslib": "^2.8.0"}@@ -2608,6 +2575,7 @@"resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.6.tgz","integrity": "sha512-NNu0sjyNxpoiW3YuVFfNz7mxSQ+S4X2G28uqg2s+CzoqoQjLPsWSbsFFyztIAqt2vb8kfEAsJNepMGPTxFDx3Q==","license": "MIT",+ "peer": true,"dependencies": {"undici-types": "~7.16.0"}@@ -2623,6 +2591,7 @@"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.13.tgz","integrity": "sha512-KkiJeU6VbYbUOp5ITMIc7kBfqlYkKA5KhEHVrGMmUUMt7NeaZg65ojdPk+FtNrBAOXNVM5QM72jnADjM+XVRAQ==","license": "MIT",+ "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -2647,6 +2616,7 @@"resolved": "https://registry.npmjs.org/@types/three/-/three-0.182.0.tgz","integrity": "sha512-WByN9V3Sbwbe2OkWuSGyoqQO8Du6yhYaXtXLoA5FkKTUJorZ+yOHBZ35zUUPQXlAKABZmbYp5oAqpA4RBjtJ/Q==","license": "MIT",+ "peer": true,"dependencies": {"@dimforge/rapier3d-compat": "~0.12.0","@tweenjs/tween.js": "~23.1.3",@@ -3269,6 +3239,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -3550,8 +3521,7 @@"version": "0.0.1","resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz","integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/cliui": {"version": "8.0.1",@@ -3774,7 +3744,8 @@"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/culvert": {"version": "0.1.2",@@ -3910,7 +3881,6 @@"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==","license": "Apache-2.0","optional": true,- "peer": true,"engines": {"node": ">=8"}@@ -5190,6 +5160,7 @@"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==","dev": true,"license": "MIT",+ "peer": true,"bin": {"jiti": "bin/jiti.js"}@@ -6216,7 +6187,6 @@"resolved": "https://registry.npmjs.org/next/-/next-16.1.6.tgz","integrity": "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==","license": "MIT",- "peer": true,"dependencies": {"@next/env": "16.1.6","@swc/helpers": "0.5.15",@@ -6284,7 +6254,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"nanoid": "^3.3.6","picocolors": "^1.0.0",@@ -6783,6 +6752,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -7090,6 +7060,7 @@"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -7114,6 +7085,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"@@ -7642,7 +7614,6 @@"hasInstallScript": true,"license": "Apache-2.0","optional": true,- "peer": true,"dependencies": {"@img/colour": "^1.0.0","detect-libc": "^2.1.2",@@ -7687,7 +7658,6 @@"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==","license": "ISC","optional": true,- "peer": true,"bin": {"semver": "bin/semver.js"},@@ -8099,7 +8069,6 @@"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz","integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==","license": "MIT",- "peer": true,"dependencies": {"client-only": "0.0.1"},@@ -8329,7 +8298,8 @@"version": "0.182.0","resolved": "https://registry.npmjs.org/three/-/three-0.182.0.tgz","integrity": "sha512-GbHabT+Irv+ihI1/f5kIIsZ+Ef9Sl5A1Y7imvS5RQjWgtTPfPnZ43JmlYI7NtCRDK9zir20lQpfg8/9Yd02OvQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/three-mesh-bvh": {"version": "0.7.8",@@ -8422,6 +8392,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -8834,6 +8805,7 @@"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.25.0","fdir": "^6.4.4",@@ -8927,6 +8899,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -8940,6 +8913,7 @@"integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@vitest/expect": "4.0.16","@vitest/mocker": "4.0.16",diff --git a/server/routes/autobiography.js b/server/routes/autobiography.jsindex bf1d0f1801..b1d7c4ed10 100644--- a/server/routes/autobiography.js+++ b/server/routes/autobiography.js@@ -81,7 +81,7 @@ router.get('/themes', asyncHandler(async (req, res) => {* Get the next prompt*/router.get('/prompt', asyncHandler(async (req, res) => {- const prompt = await autobiographyService.getNextPrompt();+ const prompt = await autobiographyService.getNextPrompt(req.query.exclude || undefined);res.json(prompt);}));diff --git a/server/services/autobiography.js b/server/services/autobiography.jsindex 015686b4b5..f4ae28cb7a 100644--- a/server/services/autobiography.js+++ b/server/services/autobiography.js@@ -202,9 +202,10 @@ export function getThemes() {}/**- * Pick the next prompt, cycling through themes and avoiding repeats+ * Pick the next prompt, cycling through themes and avoiding repeats.+ * @param {string} [excludePromptId] - Prompt ID to exclude (used by skip to avoid returning the same prompt)*/-export async function getNextPrompt() {+export async function getNextPrompt(excludePromptId) {const data = await loadStories();const usedPrompts = data.usedPrompts || [];@@ -228,6 +229,14 @@ export async function getNextPrompt() {available = allPrompts;}+ // Exclude the currently displayed prompt so skip returns a different one+ if (excludePromptId) {+ const filtered = available.filter(p => p.id !== excludePromptId);+ if (filtered.length > 0) {+ available = filtered;+ }+ }+// Pick from the least-used theme to keep balanceconst themeCounts = {};for (const story of data.stories) {@@ -414,9 +423,7 @@ export async function checkAndPrompt() {// Check if there's already an unread autobiography notificationconst alreadyNotified = await notificationExists(- NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT,- 'type',- 'autobiography_prompt'+ NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT);if (alreadyNotified) {@@ -432,7 +439,6 @@ export async function checkAndPrompt() {priority: 'low',link: `/digital-twin/autobiography?prompt=${prompt.id}`,metadata: {- type: 'autobiography_prompt',promptId: prompt.id,themeId: prompt.themeId}diff --git a/server/services/autobiography.test.js b/server/services/autobiography.test.jsnew file mode 100644index 0000000000..41482c0cf4--- /dev/null+++ b/server/services/autobiography.test.js@@ -0,0 +1,608 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock fs/promises and fs+vi.mock('fs/promises', () => ({+ readFile: vi.fn(),+ writeFile: vi.fn(),+ mkdir: vi.fn()+}));++vi.mock('fs', () => ({+ existsSync: vi.fn(() => true)+}));++// Track notification calls+const mockAddNotification = vi.fn();+const mockNotificationExists = vi.fn(() => false);++vi.mock('./notifications.js', () => ({+ addNotification: (...args) => mockAddNotification(...args),+ NOTIFICATION_TYPES: { AUTOBIOGRAPHY_PROMPT: 'autobiography_prompt' },+ exists: (...args) => mockNotificationExists(...args)+}));++// Mock uuid+let uuidCounter = 0;+vi.mock('uuid', () => ({+ v4: () => `test-uuid-${++uuidCounter}`+}));++// Mock fileUtils.js+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const fsPromises = await import('fs/promises');+ const fs = await import('fs');+ return {+ ensureDir: vi.fn(),+ PATHS: { digitalTwin: '/mock/data/digital-twin' },+ readJSONFile: vi.fn(async (filePath, defaultValue) => {+ if (!fs.existsSync(filePath)) return defaultValue;+ const content = await fsPromises.readFile(filePath, 'utf-8');+ if (!content || !content.trim()) return defaultValue;+ return JSON.parse(content);+ })+ };+});++import { readFile, writeFile } from 'fs/promises';+import {+ getThemes,+ getNextPrompt,+ getPromptById,+ saveStory,+ updateStory,+ deleteStory,+ getStories,+ getStats,+ getConfig,+ updateConfig,+ checkAndPrompt+} from './autobiography.js';++// Helper: build stories data+const makeStoriesData = (overrides = {}) => ({+ version: 1,+ stories: [],+ usedPrompts: [],+ ...overrides+});++// Helper: build config data+const makeConfigData = (overrides = {}) => ({+ intervalHours: 24,+ enabled: true,+ lastPromptAt: null,+ lastPromptId: null,+ ...overrides+});++// The service reads two files: stories.json and config.json+// We route readFile responses based on call order or path content+const setupMocks = (storiesData, configData) => {+ readFile.mockImplementation(async (filePath) => {+ if (filePath.includes('config.json')) return JSON.stringify(configData);+ return JSON.stringify(storiesData);+ });+};++describe('Autobiography - getThemes', () => {+ it('should return all 12 themes with prompt counts', () => {+ const themes = getThemes();++ expect(themes).toHaveLength(12);+ expect(themes[0]).toHaveProperty('id');+ expect(themes[0]).toHaveProperty('label');+ expect(themes[0]).toHaveProperty('promptCount');+ expect(themes.every(t => t.promptCount === 5)).toBe(true);+ });++ it('should include expected theme IDs', () => {+ const themes = getThemes();+ const ids = themes.map(t => t.id);++ expect(ids).toContain('childhood');+ expect(ids).toContain('family');+ expect(ids).toContain('career');+ expect(ids).toContain('turning_point');+ });+});++describe('Autobiography - getNextPrompt', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should return a prompt with expected fields', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const prompt = await getNextPrompt();++ expect(prompt).toHaveProperty('id');+ expect(prompt).toHaveProperty('themeId');+ expect(prompt).toHaveProperty('themeLabel');+ expect(prompt).toHaveProperty('text');+ });++ it('should prefer prompts from least-used themes', async () => {+ const data = makeStoriesData({+ stories: [+ { themeId: 'childhood', wordCount: 100 },+ { themeId: 'childhood', wordCount: 200 },+ { themeId: 'childhood', wordCount: 150 }+ ]+ });+ setupMocks(data, makeConfigData());++ const prompt = await getNextPrompt();++ // Should not pick childhood since it has the most stories+ expect(prompt.themeId).not.toBe('childhood');+ });++ it('should skip used prompts', async () => {+ const data = makeStoriesData({+ usedPrompts: ['childhood-0']+ });+ setupMocks(data, makeConfigData());++ const prompt = await getNextPrompt();++ expect(prompt.id).not.toBe('childhood-0');+ });++ it('should reset used prompts when all are used', async () => {+ // Build a usedPrompts list with all 60 prompts (12 themes x 5 prompts)+ const themes = getThemes();+ const allIds = themes.flatMap(t =>+ Array.from({ length: t.promptCount }, (_, i) => `${t.id}-${i}`)+ );++ let savedData = null;+ writeFile.mockImplementation(async (_path, content) => {+ savedData = JSON.parse(content);+ });++ const data = makeStoriesData({ usedPrompts: allIds });+ setupMocks(data, makeConfigData());++ const prompt = await getNextPrompt();++ expect(prompt).toBeTruthy();+ // usedPrompts should have been reset+ expect(savedData.usedPrompts).toEqual([]);+ });++ it('should exclude the specified prompt ID when skipping', async () => {+ // Use a fresh data set where childhood-0 would normally be first+ setupMocks(makeStoriesData(), makeConfigData());++ const firstPrompt = await getNextPrompt();+ const skippedPrompt = await getNextPrompt(firstPrompt.id);++ expect(skippedPrompt.id).not.toBe(firstPrompt.id);+ });++ it('should fall back to excluded prompt if it is the only one left', async () => {+ // Mark all prompts as used except one+ const themes = getThemes();+ const allIds = themes.flatMap(t =>+ Array.from({ length: t.promptCount }, (_, i) => `${t.id}-${i}`)+ );+ const remaining = allIds[0]; // Only this one is unused+ const usedExceptOne = allIds.filter(id => id !== remaining);++ writeFile.mockImplementation(async () => {});+ const data = makeStoriesData({ usedPrompts: usedExceptOne });+ setupMocks(data, makeConfigData());++ // Exclude the only remaining prompt; should still return it as fallback+ const prompt = await getNextPrompt(remaining);++ expect(prompt.id).toBe(remaining);+ });+});++describe('Autobiography - getPromptById', () => {+ it('should return the correct prompt for a valid ID', () => {+ const prompt = getPromptById('childhood-0');++ expect(prompt).not.toBeNull();+ expect(prompt.id).toBe('childhood-0');+ expect(prompt.themeId).toBe('childhood');+ expect(prompt.themeLabel).toBe('Childhood');+ expect(prompt.text).toBeTruthy();+ });++ it('should return null for an invalid ID', () => {+ const prompt = getPromptById('nonexistent-99');++ expect(prompt).toBeNull();+ });++ it('should return the right prompt text for a specific index', () => {+ const prompt = getPromptById('family-2');++ expect(prompt.themeId).toBe('family');+ expect(prompt.text).toContain('family tells about you');+ });+});++describe('Autobiography - saveStory', () => {+ let savedData;++ beforeEach(() => {+ vi.clearAllMocks();+ uuidCounter = 0;+ savedData = null;+ writeFile.mockImplementation(async (_path, content) => {+ savedData = JSON.parse(content);+ });+ });++ it('should save a story with correct fields', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const story = await saveStory({ promptId: 'childhood-0', content: 'My first memory is the old red house.' });++ expect(story.id).toBe('test-uuid-1');+ expect(story.promptId).toBe('childhood-0');+ expect(story.themeId).toBe('childhood');+ expect(story.themeLabel).toBe('Childhood');+ expect(story.content).toBe('My first memory is the old red house.');+ expect(story.wordCount).toBe(8);+ expect(story.createdAt).toBeTruthy();+ });++ it('should add the prompt to usedPrompts', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ await saveStory({ promptId: 'childhood-0', content: 'A story about childhood.' });++ expect(savedData.usedPrompts).toContain('childhood-0');+ });++ it('should not duplicate prompt in usedPrompts', async () => {+ const data = makeStoriesData({ usedPrompts: ['childhood-0'] });+ setupMocks(data, makeConfigData());++ await saveStory({ promptId: 'childhood-0', content: 'Another childhood story.' });++ const count = savedData.usedPrompts.filter(id => id === 'childhood-0').length;+ expect(count).toBe(1);+ });++ it('should handle unknown prompt gracefully', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const story = await saveStory({ promptId: 'nonexistent-99', content: 'Some content' });++ expect(story.themeId).toBe('unknown');+ expect(story.themeLabel).toBe('Unknown');+ expect(story.promptText).toBe('');+ });++ it('should calculate word count correctly', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const story = await saveStory({+ promptId: 'childhood-0',+ content: ' Hello world this is a test '+ });++ expect(story.wordCount).toBe(6);+ });+});++describe('Autobiography - updateStory', () => {+ let savedData;++ beforeEach(() => {+ vi.clearAllMocks();+ savedData = null;+ writeFile.mockImplementation(async (_path, content) => {+ savedData = JSON.parse(content);+ });+ });++ it('should update content and word count', async () => {+ const data = makeStoriesData({+ stories: [{+ id: 'story-1',+ promptId: 'childhood-0',+ themeId: 'childhood',+ themeLabel: 'Childhood',+ content: 'Original content',+ wordCount: 2,+ createdAt: '2026-01-01T00:00:00.000Z'+ }]+ });+ setupMocks(data, makeConfigData());++ const updated = await updateStory('story-1', 'Updated content with more words');++ expect(updated.content).toBe('Updated content with more words');+ expect(updated.wordCount).toBe(5);+ expect(updated.updatedAt).toBeTruthy();+ });++ it('should return null for non-existent story', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const result = await updateStory('nonexistent', 'New content');++ expect(result).toBeNull();+ });+});++describe('Autobiography - deleteStory', () => {+ let savedData;++ beforeEach(() => {+ vi.clearAllMocks();+ savedData = null;+ writeFile.mockImplementation(async (_path, content) => {+ savedData = JSON.parse(content);+ });+ });++ it('should remove the story from data', async () => {+ const data = makeStoriesData({+ stories: [+ { id: 'story-1', themeId: 'childhood', themeLabel: 'Childhood', content: 'First' },+ { id: 'story-2', themeId: 'family', themeLabel: 'Family', content: 'Second' }+ ]+ });+ setupMocks(data, makeConfigData());++ const removed = await deleteStory('story-1');++ expect(removed.id).toBe('story-1');+ expect(savedData.stories).toHaveLength(1);+ expect(savedData.stories[0].id).toBe('story-2');+ });++ it('should return null for non-existent story', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const result = await deleteStory('nonexistent');++ expect(result).toBeNull();+ });+});++describe('Autobiography - getStories', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should return all stories sorted newest first', async () => {+ const data = makeStoriesData({+ stories: [+ { id: 's1', themeId: 'childhood', createdAt: '2026-01-01T00:00:00.000Z' },+ { id: 's2', themeId: 'family', createdAt: '2026-01-03T00:00:00.000Z' },+ { id: 's3', themeId: 'childhood', createdAt: '2026-01-02T00:00:00.000Z' }+ ]+ });+ setupMocks(data, makeConfigData());++ const stories = await getStories();++ expect(stories).toHaveLength(3);+ expect(stories[0].id).toBe('s2');+ expect(stories[1].id).toBe('s3');+ expect(stories[2].id).toBe('s1');+ });++ it('should filter by theme when specified', async () => {+ const data = makeStoriesData({+ stories: [+ { id: 's1', themeId: 'childhood', createdAt: '2026-01-01T00:00:00.000Z' },+ { id: 's2', themeId: 'family', createdAt: '2026-01-02T00:00:00.000Z' },+ { id: 's3', themeId: 'childhood', createdAt: '2026-01-03T00:00:00.000Z' }+ ]+ });+ setupMocks(data, makeConfigData());++ const stories = await getStories('childhood');++ expect(stories).toHaveLength(2);+ expect(stories.every(s => s.themeId === 'childhood')).toBe(true);+ });++ it('should return empty array when no stories exist', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const stories = await getStories();++ expect(stories).toEqual([]);+ });+});++describe('Autobiography - getStats', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should return correct stats for existing stories', async () => {+ const data = makeStoriesData({+ stories: [+ { themeId: 'childhood', wordCount: 100 },+ { themeId: 'childhood', wordCount: 200 },+ { themeId: 'family', wordCount: 150 }+ ],+ usedPrompts: ['childhood-0', 'childhood-1', 'family-0']+ });+ const config = makeConfigData({ lastPromptAt: '2026-01-01T00:00:00.000Z' });+ setupMocks(data, config);++ const stats = await getStats();++ expect(stats.totalStories).toBe(3);+ expect(stats.totalWords).toBe(450);+ expect(stats.byTheme.childhood).toBe(2);+ expect(stats.byTheme.family).toBe(1);+ expect(stats.usedPrompts).toBe(3);+ expect(stats.totalPrompts).toBe(60); // 12 themes x 5 prompts+ expect(stats.promptsRemaining).toBe(57);+ expect(stats.config.enabled).toBe(true);+ expect(stats.config.intervalHours).toBe(24);+ expect(stats.config.lastPromptAt).toBe('2026-01-01T00:00:00.000Z');+ });++ it('should return zeroes for empty data', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const stats = await getStats();++ expect(stats.totalStories).toBe(0);+ expect(stats.totalWords).toBe(0);+ expect(stats.usedPrompts).toBe(0);+ expect(stats.promptsRemaining).toBe(60);+ });+});++describe('Autobiography - config', () => {+ let savedConfig;++ beforeEach(() => {+ vi.clearAllMocks();+ savedConfig = null;+ writeFile.mockImplementation(async (filePath, content) => {+ if (filePath.includes('config.json')) {+ savedConfig = JSON.parse(content);+ }+ });+ });++ it('should return default config when none exists', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const config = await getConfig();++ expect(config.enabled).toBe(true);+ expect(config.intervalHours).toBe(24);+ expect(config.lastPromptAt).toBeNull();+ });++ it('should merge updates into existing config', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const updated = await updateConfig({ intervalHours: 48 });++ expect(updated.intervalHours).toBe(48);+ expect(updated.enabled).toBe(true); // preserved from default+ expect(savedConfig.intervalHours).toBe(48);+ });++ it('should allow disabling prompts', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const updated = await updateConfig({ enabled: false });++ expect(updated.enabled).toBe(false);+ });+});++describe('Autobiography - checkAndPrompt', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockAddNotification.mockResolvedValue({});+ mockNotificationExists.mockResolvedValue(false);+ writeFile.mockImplementation(async () => {});+ });++ it('should return disabled when config.enabled is false', async () => {+ setupMocks(makeStoriesData(), makeConfigData({ enabled: false }));++ const result = await checkAndPrompt();++ expect(result.prompted).toBe(false);+ expect(result.reason).toBe('disabled');+ expect(mockAddNotification).not.toHaveBeenCalled();+ });++ it('should return not_due when interval has not elapsed', async () => {+ const recentTime = new Date(Date.now() - 1000).toISOString(); // 1 second ago+ setupMocks(makeStoriesData(), makeConfigData({ lastPromptAt: recentTime }));++ const result = await checkAndPrompt();++ expect(result.prompted).toBe(false);+ expect(result.reason).toBe('not_due');+ });++ it('should return pending_notification when one already exists', async () => {+ mockNotificationExists.mockResolvedValue(true);+ const oldTime = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString(); // 48 hours ago+ setupMocks(makeStoriesData(), makeConfigData({ lastPromptAt: oldTime }));++ const result = await checkAndPrompt();++ expect(result.prompted).toBe(false);+ expect(result.reason).toBe('pending_notification');+ expect(mockNotificationExists).toHaveBeenCalledWith('autobiography_prompt');+ });++ it('should create notification when prompt is due', async () => {+ const oldTime = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();+ setupMocks(makeStoriesData(), makeConfigData({ lastPromptAt: oldTime }));++ const result = await checkAndPrompt();++ expect(result.prompted).toBe(true);+ expect(result.prompt).toHaveProperty('id');+ expect(result.prompt).toHaveProperty('themeId');+ expect(mockAddNotification).toHaveBeenCalledTimes(1);++ const notification = mockAddNotification.mock.calls[0][0];+ expect(notification.type).toBe('autobiography_prompt');+ expect(notification.title).toBe('5-Minute Story Time');+ expect(notification.priority).toBe('low');+ expect(notification.link).toContain('/digital-twin/autobiography?prompt=');+ expect(notification.metadata).toHaveProperty('promptId');+ expect(notification.metadata).toHaveProperty('themeId');+ // Verify no redundant type in metadata+ expect(notification.metadata).not.toHaveProperty('type');+ });++ it('should prompt when lastPromptAt is null (first time)', async () => {+ setupMocks(makeStoriesData(), makeConfigData({ lastPromptAt: null }));++ const result = await checkAndPrompt();++ expect(result.prompted).toBe(true);+ expect(mockAddNotification).toHaveBeenCalledTimes(1);+ });++ it('should update config with lastPromptAt after sending notification', async () => {+ let savedConfig = null;+ writeFile.mockImplementation(async (filePath, content) => {+ if (filePath.includes('config.json')) {+ savedConfig = JSON.parse(content);+ }+ });++ const oldTime = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();+ setupMocks(makeStoriesData(), makeConfigData({ lastPromptAt: oldTime }));++ const result = await checkAndPrompt();++ expect(result.prompted).toBe(true);+ expect(savedConfig).not.toBeNull();+ expect(savedConfig.lastPromptAt).toBeTruthy();+ expect(savedConfig.lastPromptId).toBe(result.prompt.id);+ });++ it('should respect custom intervalHours', async () => {+ // 6 hours ago, interval is 12h => not due yet+ const sixHoursAgo = new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString();+ setupMocks(makeStoriesData(), makeConfigData({+ intervalHours: 12,+ lastPromptAt: sixHoursAgo+ }));++ const result = await checkAndPrompt();++ expect(result.prompted).toBe(false);+ expect(result.reason).toBe('not_due');+ });+});diff --git a/server/services/notifications.js b/server/services/notifications.jsindex 9faad329c9..dc49d6420f 100644--- a/server/services/notifications.js+++ b/server/services/notifications.js@@ -255,10 +255,14 @@ export async function clearAll() {}/**- * Check if a notification already exists (prevent duplicates)+ * Check if a notification already exists (prevent duplicates).+ * When metadataField/metadataValue are omitted, matches by type alone.*/export async function exists(type, metadataField, metadataValue) {const data = await loadNotifications();+ if (!metadataField) {+ return data.notifications.some(n => n.type === type);+ }return data.notifications.some(n => n.type === type && n.metadata[metadataField] === metadataValue);