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 search deep-links, backend-aware search, sync validation, config dedup, add tests
Adam Eivyb600ab8a5b9c
diff --git a/server/lib/memoryValidation.js b/server/lib/memoryValidation.jsindex e630e4998b..05d669d951 100644--- a/server/lib/memoryValidation.js+++ b/server/lib/memoryValidation.js@@ -110,3 +110,32 @@ export const memoryLinkSchema = z.object({sourceId: z.string().uuid(),targetId: z.string().uuid()});++// Single sync memory item schema (incoming from remote peer)+const syncMemoryItemSchema = z.object({+ id: z.string().uuid(),+ type: memoryTypeEnum,+ content: z.string().min(1).max(10240),+ summary: z.string().max(500).nullable().optional(),+ category: z.string().max(100).nullable().optional(),+ tags: z.array(z.string().max(50)).optional().default([]),+ embedding: z.union([z.array(z.number()), z.string()]).nullable().optional(),+ embeddingModel: z.string().max(200).nullable().optional(),+ confidence: z.number().min(0).max(1).nullable().optional(),+ importance: z.number().min(0).max(1).nullable().optional(),+ accessCount: z.number().int().min(0).optional().default(0),+ lastAccessed: z.string().datetime().nullable().optional(),+ status: memoryStatusEnum.optional().default('active'),+ sourceTaskId: z.string().nullable().optional(),+ sourceAgentId: z.string().nullable().optional(),+ sourceAppId: z.string().nullable().optional(),+ expiresAt: z.string().datetime().nullable().optional(),+ createdAt: z.string().datetime(),+ updatedAt: z.string().datetime(),+ syncSequence: z.number().int().optional()+});++// Sync request body schema+export const memorySyncSchema = z.object({+ memories: z.array(syncMemoryItemSchema).min(1).max(1000)+});diff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex c8dfd51260..f9c50966b4 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -37,6 +37,12 @@ vi.mock('../services/brain.js', () => ({createAdminItem: vi.fn(),updateAdminItem: vi.fn(),deleteAdminItem: vi.fn(),+ // Memories+ getMemoryEntries: vi.fn(),+ getMemoryEntryById: vi.fn(),+ createMemoryEntry: vi.fn(),+ updateMemoryEntry: vi.fn(),+ deleteMemoryEntry: vi.fn(),// Digest & ReviewgetLatestDigest: vi.fn(),getDigests: vi.fn(),@@ -489,6 +495,121 @@ describe('Brain Routes', () => {});});+ // ===========================================================================+ // MEMORIES CRUD+ // ===========================================================================++ describe('GET /api/brain/memories', () => {+ it('should return all memories', async () => {+ brainService.getMemoryEntries.mockResolvedValue([+ { id: 'mem-001', title: 'Morning jog' },+ { id: 'mem-002', title: 'Dinner with family' }+ ]);++ const response = await request(app).get('/api/brain/memories');++ expect(response.status).toBe(200);+ expect(response.body).toHaveLength(2);+ });+ });++ describe('GET /api/brain/memories/:id', () => {+ it('should return memory by ID', async () => {+ brainService.getMemoryEntryById.mockResolvedValue({+ id: 'mem-001',+ title: 'Morning jog',+ content: 'Ran 5k in the park',+ mood: 'energized',+ tags: ['fitness']+ });++ const response = await request(app).get('/api/brain/memories/mem-001');++ expect(response.status).toBe(200);+ expect(response.body.title).toBe('Morning jog');+ });++ it('should return 404 if not found', async () => {+ brainService.getMemoryEntryById.mockResolvedValue(null);++ const response = await request(app).get('/api/brain/memories/mem-999');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/brain/memories', () => {+ it('should create a memory', async () => {+ brainService.createMemoryEntry.mockResolvedValue({+ id: 'mem-001',+ title: 'Morning jog',+ content: 'Ran 5k in the park',+ mood: 'energized',+ tags: ['fitness']+ });++ const response = await request(app)+ .post('/api/brain/memories')+ .send({ title: 'Morning jog', content: 'Ran 5k in the park', mood: 'energized', tags: ['fitness'] });++ expect(response.status).toBe(201);+ expect(response.body.id).toBe('mem-001');+ });++ it('should return 400 if title is missing', async () => {+ const response = await request(app)+ .post('/api/brain/memories')+ .send({ content: 'No title provided' });++ expect(response.status).toBe(400);+ });+ });++ describe('PUT /api/brain/memories/:id', () => {+ it('should update a memory', async () => {+ brainService.updateMemoryEntry.mockResolvedValue({+ id: 'mem-001',+ title: 'Morning jog updated',+ content: 'Ran 10k today'+ });++ const response = await request(app)+ .put('/api/brain/memories/mem-001')+ .send({ title: 'Morning jog updated' });++ expect(response.status).toBe(200);+ expect(response.body.title).toBe('Morning jog updated');+ });++ it('should return 404 if not found', async () => {+ brainService.updateMemoryEntry.mockResolvedValue(null);++ const response = await request(app)+ .put('/api/brain/memories/mem-999')+ .send({ title: 'Test' });++ expect(response.status).toBe(404);+ });+ });++ describe('DELETE /api/brain/memories/:id', () => {+ it('should delete a memory', async () => {+ brainService.deleteMemoryEntry.mockResolvedValue(true);++ const response = await request(app).delete('/api/brain/memories/mem-001');++ expect(response.status).toBe(204);+ });++ it('should return 404 if not found', async () => {+ brainService.deleteMemoryEntry.mockResolvedValue(false);++ const response = await request(app).delete('/api/brain/memories/mem-999');++ expect(response.status).toBe(404);+ });+ });+// ===========================================================================// DIGEST & REVIEW// ===========================================================================diff --git a/server/routes/memory.js b/server/routes/memory.jsindex 392da8bf9a..fc92716196 100644--- a/server/routes/memory.js+++ b/server/routes/memory.js@@ -17,7 +17,8 @@ import {memoryListSchema,memoryTimelineSchema,memoryConsolidateSchema,- memoryLinkSchema+ memoryLinkSchema,+ memorySyncSchema} from '../lib/memoryValidation.js';const router = Router();@@ -101,10 +102,7 @@ router.post('/sync', asyncHandler(async (req, res) => {if (name !== 'postgres') {throw new ServerError('Sync requires PostgreSQL backend', { status: 400 });}- const { memories } = req.body;- if (!Array.isArray(memories)) {- throw new ServerError('Request body must contain a memories array', { status: 400 });- }+ const { memories } = validateRequest(memorySyncSchema, req.body);const result = await memorySync.applyRemoteChanges(memories);res.json(result);}));diff --git a/server/routes/memory.test.js b/server/routes/memory.test.jsnew file mode 100644index 0000000000..e023f56b65--- /dev/null+++ b/server/routes/memory.test.js@@ -0,0 +1,208 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import request from 'supertest';+import memoryRoutes from './memory.js';++// Mock the memory backend service+vi.mock('../services/memoryBackend.js', () => ({+ ensureBackend: vi.fn(),+ getMemories: vi.fn(),+ getStats: vi.fn(),+ getCategories: vi.fn(),+ getTags: vi.fn(),+ getTimeline: vi.fn(),+ getGraphData: vi.fn(),+ getMemory: vi.fn(),+ getRelatedMemories: vi.fn(),+ createMemory: vi.fn(),+ updateMemory: vi.fn(),+ updateMemoryEmbedding: vi.fn(),+ deleteMemory: vi.fn(),+ searchMemories: vi.fn(),+ consolidateMemories: vi.fn(),+ linkMemories: vi.fn(),+ applyDecay: vi.fn(),+ clearExpired: vi.fn(),+ approveMemory: vi.fn(),+ rejectMemory: vi.fn()+}));++// Mock the db health check+vi.mock('../lib/db.js', () => ({+ checkHealth: vi.fn()+}));++// Mock the embedding service+vi.mock('../services/memoryEmbeddings.js', () => ({+ generateQueryEmbedding: vi.fn(),+ generateMemoryEmbedding: vi.fn(),+ checkAvailability: vi.fn()+}));++// Mock the sync service+vi.mock('../services/memorySync.js', () => ({+ getChangesSince: vi.fn(),+ applyRemoteChanges: vi.fn()+}));++import { ensureBackend } from '../services/memoryBackend.js';+import { checkHealth } from '../lib/db.js';+import * as memorySync from '../services/memorySync.js';++describe('Memory Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/memory', memoryRoutes);+ vi.clearAllMocks();+ });++ // ===========================================================================+ // BACKEND STATUS+ // ===========================================================================++ describe('GET /api/memory/backend/status', () => {+ it('should return backend name and health info', async () => {+ ensureBackend.mockResolvedValue('postgres');+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });++ const response = await request(app).get('/api/memory/backend/status');++ expect(response.status).toBe(200);+ expect(response.body.backend).toBe('postgres');+ expect(response.body.db.connected).toBe(true);+ });++ it('should return file backend when postgres is unavailable', async () => {+ ensureBackend.mockResolvedValue('file');+ checkHealth.mockResolvedValue({ connected: false, error: 'connection refused' });++ const response = await request(app).get('/api/memory/backend/status');++ expect(response.status).toBe(200);+ expect(response.body.backend).toBe('file');+ expect(response.body.db.connected).toBe(false);+ });+ });++ // ===========================================================================+ // SYNC - GET+ // ===========================================================================++ describe('GET /api/memory/sync', () => {+ it('should return 400 when backend is not postgres', async () => {+ ensureBackend.mockResolvedValue('file');++ const response = await request(app).get('/api/memory/sync');++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/PostgreSQL/);+ });++ it('should return changes since sequence when backend is postgres', async () => {+ ensureBackend.mockResolvedValue('postgres');+ memorySync.getChangesSince.mockResolvedValue({+ memories: [{ id: 'mem-001' }],+ maxSequence: 42+ });++ const response = await request(app).get('/api/memory/sync?since=10&limit=50');++ expect(response.status).toBe(200);+ expect(response.body.maxSequence).toBe(42);+ expect(memorySync.getChangesSince).toHaveBeenCalledWith(10, 50);+ });++ it('should default since to 0 and limit to 100', async () => {+ ensureBackend.mockResolvedValue('postgres');+ memorySync.getChangesSince.mockResolvedValue({ memories: [], maxSequence: 0 });++ await request(app).get('/api/memory/sync');++ expect(memorySync.getChangesSince).toHaveBeenCalledWith(0, 100);+ });++ it('should cap limit at 1000', async () => {+ ensureBackend.mockResolvedValue('postgres');+ memorySync.getChangesSince.mockResolvedValue({ memories: [], maxSequence: 0 });++ await request(app).get('/api/memory/sync?limit=5000');++ expect(memorySync.getChangesSince).toHaveBeenCalledWith(0, 1000);+ });+ });++ // ===========================================================================+ // SYNC - POST+ // ===========================================================================++ describe('POST /api/memory/sync', () => {+ it('should return 400 when backend is not postgres', async () => {+ ensureBackend.mockResolvedValue('file');++ const response = await request(app)+ .post('/api/memory/sync')+ .send({ memories: [] });++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/PostgreSQL/);+ });++ it('should return 400 when body is not an array', async () => {+ ensureBackend.mockResolvedValue('postgres');++ const response = await request(app)+ .post('/api/memory/sync')+ .send({ memories: 'not-an-array' });++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/Validation failed/);+ });++ it('should return 400 when memories key is missing', async () => {+ ensureBackend.mockResolvedValue('postgres');++ const response = await request(app)+ .post('/api/memory/sync')+ .send({});++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/Validation failed/);+ });++ it('should return 400 when memory item has invalid id', async () => {+ ensureBackend.mockResolvedValue('postgres');++ const response = await request(app)+ .post('/api/memory/sync')+ .send({ memories: [{ id: 'not-a-uuid', type: 'fact', content: 'test', createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-01T00:00:00.000Z' }] });++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/Validation failed/);+ });++ it('should apply remote changes when body is valid', async () => {+ ensureBackend.mockResolvedValue('postgres');+ const remoteMems = [{+ id: '00000000-0000-0000-0000-000000000001',+ type: 'fact',+ content: 'synced memory',+ createdAt: '2024-01-01T00:00:00.000Z',+ updatedAt: '2024-01-01T00:00:00.000Z'+ }];+ memorySync.applyRemoteChanges.mockResolvedValue({ applied: 1, conflicts: 0 });++ const response = await request(app)+ .post('/api/memory/sync')+ .send({ memories: remoteMems });++ expect(response.status).toBe(200);+ expect(response.body.applied).toBe(1);+ expect(memorySync.applyRemoteChanges).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ id: '00000000-0000-0000-0000-000000000001', type: 'fact', content: 'synced memory' })])+ );+ });+ });+});diff --git a/server/services/memory.js b/server/services/memory.jsindex 25918d5e18..a441f9bf97 100644--- a/server/services/memory.js+++ b/server/services/memory.js@@ -16,6 +16,9 @@ import * as notifications from './notifications.js';import { readJSONFile } from '../lib/fileUtils.js';import * as memoryBM25 from './memoryBM25.js';import { createMutex } from '../lib/asyncMutex.js';+import { DEFAULT_MEMORY_CONFIG } from './memoryConfig.js';++export { DEFAULT_MEMORY_CONFIG };const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -25,21 +28,6 @@ const INDEX_FILE = join(MEMORY_DIR, 'index.json');const EMBEDDINGS_FILE = join(MEMORY_DIR, 'embeddings.json');const MEMORIES_DIR = join(MEMORY_DIR, 'memories');-// Default memory configuration-export const DEFAULT_MEMORY_CONFIG = {- enabled: true,- embeddingProvider: 'lmstudio',- embeddingEndpoint: 'http://localhost:1234/v1/embeddings',- embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',- embeddingDimension: 768,- maxMemories: 10000,- maxContextTokens: 2000,- minRelevanceThreshold: 0.7,- autoExtractEnabled: true,- consolidationIntervalMs: 86400000,- decayIntervalMs: 86400000-};-// In-memory cacheslet indexCache = null;let embeddingsCache = null;diff --git a/server/services/memoryBackend.js b/server/services/memoryBackend.jsindex 4909bce677..1789bc21cb 100644--- a/server/services/memoryBackend.js+++ b/server/services/memoryBackend.js@@ -10,6 +10,9 @@*/import { checkHealth } from '../lib/db.js';+import { DEFAULT_MEMORY_CONFIG } from './memoryConfig.js';++export { DEFAULT_MEMORY_CONFIG };let backend = null;let backendName = null;@@ -190,17 +193,3 @@ export async function flushBM25Index() {return b.flushBM25Index();}-// Default memory configuration (shared across backends)-export const DEFAULT_MEMORY_CONFIG = {- enabled: true,- embeddingProvider: 'lmstudio',- embeddingEndpoint: 'http://localhost:1234/v1/embeddings',- embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',- embeddingDimension: 768,- maxMemories: 10000,- maxContextTokens: 2000,- minRelevanceThreshold: 0.7,- autoExtractEnabled: true,- consolidationIntervalMs: 86400000,- decayIntervalMs: 86400000-};diff --git a/server/services/memoryConfig.js b/server/services/memoryConfig.jsnew file mode 100644index 0000000000..4b640368fc--- /dev/null+++ b/server/services/memoryConfig.js@@ -0,0 +1,21 @@+/**+ * Shared memory configuration defaults.+ *+ * Extracted into its own module to avoid circular dependencies between+ * memoryBackend.js (which re-exports both backends) and the backend+ * implementations (memory.js, memoryDB.js) that it imports.+ */++export const DEFAULT_MEMORY_CONFIG = {+ enabled: true,+ embeddingProvider: 'lmstudio',+ embeddingEndpoint: 'http://localhost:1234/v1/embeddings',+ embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',+ embeddingDimension: 768,+ maxMemories: 10000,+ maxContextTokens: 2000,+ minRelevanceThreshold: 0.7,+ autoExtractEnabled: true,+ consolidationIntervalMs: 86400000,+ decayIntervalMs: 86400000+};diff --git a/server/services/memoryDB.js b/server/services/memoryDB.jsindex 8b2b9b2573..c5dc5a9470 100644--- a/server/services/memoryDB.js+++ b/server/services/memoryDB.js@@ -11,21 +11,7 @@ import { v4 as uuidv4 } from 'uuid';import { query, withTransaction } from '../lib/db.js';import { cosEvents, updateAgent } from './cos.js';import * as notifications from './notifications.js';--// Default memory configuration (local copy — canonical export is in memoryBackend.js)-const DEFAULT_MEMORY_CONFIG = {- enabled: true,- embeddingProvider: 'lmstudio',- embeddingEndpoint: 'http://localhost:1234/v1/embeddings',- embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',- embeddingDimension: 768,- maxMemories: 10000,- maxContextTokens: 2000,- minRelevanceThreshold: 0.7,- autoExtractEnabled: true,- consolidationIntervalMs: 86400000,- decayIntervalMs: 86400000-};+import { DEFAULT_MEMORY_CONFIG } from './memoryConfig.js';/*** Generate summary from content using simple truncationdiff --git a/server/services/memorySync.js b/server/services/memorySync.jsindex e50a826af1..3403227ea4 100644--- a/server/services/memorySync.js+++ b/server/services/memorySync.js@@ -35,6 +35,7 @@ function toPgvector(embedding) {* @returns {Promise<{memories: Array, maxSequence: number, hasMore: boolean}>}*/export async function getChangesSince(sinceSequence = 0, limit = 100) {+ // Fetch limit+1 rows to detect whether more records exist beyond this batchconst result = await query(`SELECT id, type, content, summary, category, tags,embedding, embedding_model, confidence, importance,@@ -45,10 +46,13 @@ export async function getChangesSince(sinceSequence = 0, limit = 100) {WHERE sync_sequence > $1ORDER BY sync_sequence ASCLIMIT $2`,- [sinceSequence, limit]+ [sinceSequence, limit + 1]);- const memories = result.rows.map(row => ({+ const hasMore = result.rows.length > limit;+ const rows = hasMore ? result.rows.slice(0, limit) : result.rows;++ const memories = rows.map(row => ({id: row.id,type: row.type,content: row.content,@@ -75,13 +79,6 @@ export async function getChangesSince(sinceSequence = 0, limit = 100) {? memories[memories.length - 1].syncSequence: sinceSequence;- // Check if there are more records beyond this batch- const countResult = await query(- 'SELECT COUNT(*) AS remaining FROM memories WHERE sync_sequence > $1',- [maxSequence]- );- const hasMore = parseInt(countResult.rows[0].remaining, 10) > 0;-return { memories, maxSequence, hasMore };}@@ -140,12 +137,14 @@ export async function applyRemoteChanges(incomingMemories) {`UPDATE memories SETtype = $2, content = $3, summary = $4, category = $5, tags = $6,embedding = $7, embedding_model = $8, confidence = $9, importance = $10,- status = $11, expires_at = $12, updated_at = $13+ status = $11, expires_at = $12, updated_at = $13,+ source_task_id = $14, source_agent_id = $15, source_app_id = $16WHERE id = $1`,[mem.id, mem.type, mem.content, mem.summary, mem.category, mem.tags || [],toPgvector(mem.embedding), mem.embeddingModel, mem.confidence, mem.importance,- mem.status, mem.expiresAt, mem.updatedAt+ mem.status, mem.expiresAt, mem.updatedAt,+ mem.sourceTaskId, mem.sourceAgentId, mem.sourceAppId]);applied++;diff --git a/server/services/search.js b/server/services/search.jsindex 9599644334..03537e5c32 100644--- a/server/services/search.js+++ b/server/services/search.js@@ -11,7 +11,7 @@import { getInboxLog, getPeople, getProjects, getIdeas, getAdminItems, getMemoryEntries, getLinks } from './brainStorage.js';import { searchBM25 } from './memoryBM25.js';-import { getMemories } from './memoryBackend.js';+import { getMemories, getBackendName, hybridSearchMemories } from './memoryBackend.js';import { getAllApps } from './apps.js';import { getHistory } from './history.js';@@ -73,7 +73,7 @@ async function searchBrain(query) {id: p.id,title: p.name,snippet: extractSnippet(p.context, query),- url: '/brain/memory',+ url: '/brain/memory?type=people',type: 'person'})): [];@@ -85,7 +85,7 @@ async function searchBrain(query) {id: p.id,title: p.name,snippet: extractSnippet(p.notes, query),- url: '/brain/memory',+ url: '/brain/memory?type=projects',type: 'project'})): [];@@ -97,7 +97,7 @@ async function searchBrain(query) {id: i.id,title: i.title,snippet: extractSnippet(i.oneLiner || i.notes, query),- url: '/brain/memory',+ url: '/brain/memory?type=ideas',type: 'idea'})): [];@@ -109,7 +109,7 @@ async function searchBrain(query) {id: a.id,title: a.title,snippet: extractSnippet(a.notes || a.nextAction, query),- url: '/brain/memory',+ url: '/brain/memory?type=admin',type: 'admin'})): [];@@ -121,7 +121,7 @@ async function searchBrain(query) {id: m.id,title: m.title,snippet: extractSnippet(m.content, query),- url: '/brain/memory',+ url: '/brain/memory?type=memories',type: 'memory-entry'})): [];@@ -156,6 +156,27 @@ async function searchBrain(query) {}async function searchMemory(query) {+ const activeBackend = getBackendName();++ // Postgres backend: use hybrid search (tsvector full-text, no embedding needed)+ if (activeBackend === 'postgres') {+ const searchResult = await hybridSearchMemories(query, null, { limit: 10 });+ const results = (searchResult?.memories ?? [])+ .map(mem => {+ const summary = mem.summary ?? '';+ return {+ id: mem.id,+ title: summary.substring(0, 60),+ snippet: summary,+ url: '/cos/memory',+ type: 'memory'+ };+ })+ .slice(0, 5);+ return { id: 'memory', label: 'Memory', icon: 'Cpu', results };+ }++ // File backend: use BM25 index + getMemories for metadataconst [bm25Results, memoriesResult] = await Promise.allSettled([searchBM25(query, { limit: 10, threshold: 0.1 }),getMemories()