Skip to content

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

perf([capabilities-cheap-memory-count]): count memories without sorting

[._.]/ Adam Eivyee3271707c9c
diff --git a/server/routes/capabilities.js b/server/routes/capabilities.js
index 8aa9253a17..94d2268f64 100644
--- a/server/routes/capabilities.js
+++ b/server/routes/capabilities.js
@@ -5,7 +5,7 @@ import { getAllProviders, getProviderById } from '../services/providers.js';
import { getAllProviderStatuses } from '../services/providerStatus.js';
import { listAccounts as listCalendarAccounts } from '../services/calendarAccounts.js';
import { listAccounts as listMessageAccounts } from '../services/messageAccounts.js';
-import { getMemories } from '../services/memory.js';
+import { countMemories } from '../services/memory.js';
import { getConfig as getCosConfig } from '../services/cos.js';
import { getVoiceConfig } from '../services/voice/config.js';
import { getNetworkExposureStatus } from '../lib/networkExposure.js';
@@ -54,7 +54,7 @@ router.get('/', asyncHandler(async (req, res) => {
providerStatuses,
calendarAccounts,
messageAccounts,
- memories,
+ memoryCount,
embeddingProviderConfigured,
voiceConfig,
genome,
@@ -66,7 +66,7 @@ router.get('/', asyncHandler(async (req, res) => {
Promise.resolve().then(() => getAllProviderStatuses()).catch(() => ({})),
listCalendarAccounts().catch(() => []),
listMessageAccounts().catch(() => []),
- getMemories({ status: 'active' }).catch(() => ({ total: 0 })),
+ countMemories({ status: 'active' }).catch(() => 0),
resolveEmbeddingProviderConfigured().catch(() => false),
getVoiceConfig().catch(() => ({})),
getGenomeSummary().catch(() => ({ uploaded: false })),
@@ -82,8 +82,7 @@ router.get('/', asyncHandler(async (req, res) => {
providerStatuses,
calendarAccounts,
messageAccounts,
- // getMemories returns { total, memories } — use the count, not the wrapper.
- memoryCount: Number(memories?.total) || 0,
+ memoryCount: Number(memoryCount) || 0,
embeddingProviderConfigured,
voiceConfig,
network,
diff --git a/server/routes/capabilities.test.js b/server/routes/capabilities.test.js
index ca07984684..16204733c8 100644
--- a/server/routes/capabilities.test.js
+++ b/server/routes/capabilities.test.js
@@ -19,8 +19,7 @@ vi.mock('../services/messageAccounts.js', () => ({
listAccounts: vi.fn(async () => [{ enabled: true, lastSyncStatus: 'success' }]),
}));
vi.mock('../services/memory.js', () => ({
- // The real getMemories returns { total, memories } — NOT an array.
- getMemories: vi.fn(async () => ({ total: 7, memories: [] })),
+ countMemories: vi.fn(async () => 7),
}));
vi.mock('../services/cos.js', () => ({
getConfig: vi.fn(async () => ({ embeddingProviderId: 'lmstudio' })),
@@ -47,7 +46,7 @@ vi.mock('../services/apps.js', () => ({
getAppStatusSummary: vi.fn(async () => ({ total: 2, online: 2, stopped: 0, notStarted: 0, unmanaged: 0 })),
}));
-const { getMemories } = await import('../services/memory.js');
+const { countMemories } = await import('../services/memory.js');
const { getGenomeSummary } = await import('../services/genome.js');
const { default: capabilitiesRoutes } = await import('./capabilities.js');
@@ -76,14 +75,13 @@ describe('GET /api/capabilities', () => {
}
});
- it('reads the memory COUNT from getMemories().total, not the wrapper object', async () => {
- // Regression guard: getMemories returns { total, memories }; an Array.isArray
- // check would report 0 here. The brain row must reflect the real count.
+ it('reads the active memory count from the lightweight count helper', async () => {
const res = await request(makeApp()).get('/api/capabilities');
const brain = byId(res.body, 'brain');
expect(brain.detail.memoryCount).toBe(7);
expect(brain.summary).toContain('7 memories');
expect(brain.status).toBe('ok');
+ expect(countMemories).toHaveBeenCalledWith({ status: 'active' });
});
it('degrades to fail-soft (200) when a single source throws', async () => {
@@ -96,8 +94,8 @@ describe('GET /api/capabilities', () => {
expect(byId(res.body, 'providers').configured).toBe(true);
});
- it('handles getMemories rejecting (memory count 0, page still renders)', async () => {
- getMemories.mockRejectedValueOnce(new Error('boom'));
+ it('handles countMemories rejecting (memory count 0, page still renders)', async () => {
+ countMemories.mockRejectedValueOnce(new Error('boom'));
const res = await request(makeApp()).get('/api/capabilities');
expect(res.status).toBe(200);
expect(byId(res.body, 'brain').detail.memoryCount).toBe(0);
diff --git a/server/services/memory.js b/server/services/memory.js
index 636c2389a0..df96bb5a1a 100644
--- a/server/services/memory.js
+++ b/server/services/memory.js
@@ -213,38 +213,50 @@ export async function getMemory(id) {
}
/**
- * Get memories with filters
+ * Filter memory index entries.
*/
-export async function getMemories(options = {}) {
- const index = await loadIndex();
- let memories = [...index.memories];
-
+function filterMemoryIndex(memories, options = {}) {
// Filter by status
const status = options.status || 'active';
- memories = memories.filter(m => m.status === status);
+ let filtered = memories.filter(m => m.status === status);
// Filter by types
if (options.types && options.types.length > 0) {
- memories = memories.filter(m => options.types.includes(m.type));
+ filtered = filtered.filter(m => options.types.includes(m.type));
}
// Filter by categories
if (options.categories && options.categories.length > 0) {
- memories = memories.filter(m => options.categories.includes(m.category));
+ filtered = filtered.filter(m => options.categories.includes(m.category));
}
// Filter by tags (any match)
if (options.tags && options.tags.length > 0) {
- memories = memories.filter(m => m.tags.some(t => options.tags.includes(t)));
+ filtered = filtered.filter(m => m.tags.some(t => options.tags.includes(t)));
}
// Filter by app
if (options.appId === '__not_brain') {
- memories = memories.filter(m => m.sourceAppId !== 'brain');
+ filtered = filtered.filter(m => m.sourceAppId !== 'brain');
} else if (options.appId) {
- memories = memories.filter(m => m.sourceAppId === options.appId);
+ filtered = filtered.filter(m => m.sourceAppId === options.appId);
}
+ return filtered;
+}
+
+export async function countMemories(options = {}) {
+ const index = await loadIndex();
+ return filterMemoryIndex(index.memories, options).length;
+}
+
+/**
+ * Get memories with filters
+ */
+export async function getMemories(options = {}) {
+ const index = await loadIndex();
+ let memories = filterMemoryIndex(index.memories, options);
+
// Sort
const sortBy = options.sortBy || 'createdAt';
const sortOrder = options.sortOrder || 'desc';
diff --git a/server/services/memory.test.js b/server/services/memory.test.js
index 63dd9aa58c..8e5abfc4be 100644
--- a/server/services/memory.test.js
+++ b/server/services/memory.test.js
@@ -84,6 +84,7 @@ import { cosEvents } from './cosEvents.js';
import {
createMemory,
getMemory,
+ countMemories,
getMemories,
updateMemory,
updateMemoryEmbedding,
@@ -403,6 +404,53 @@ describe('memory service', () => {
});
});
+ // ===========================================================================
+ // countMemories
+ // ===========================================================================
+
+ describe('countMemories', () => {
+ const makeIndex = (memories) => ({
+ version: 1,
+ lastUpdated: '2025-01-01T00:00:00.000Z',
+ count: memories.length,
+ memories
+ });
+
+ const mem1 = { id: 'm1', type: 'fact', category: 'science', tags: ['physics'], summary: 'Gravity', importance: 0.8, createdAt: '2025-01-01T00:00:00.000Z', status: 'active', sourceAppId: 'app1' };
+ const mem2 = { id: 'm2', type: 'decision', category: 'engineering', tags: ['react'], summary: 'Use React', importance: 0.6, createdAt: '2025-01-02T00:00:00.000Z', status: 'active', sourceAppId: 'brain' };
+ const mem3 = { id: 'm3', type: 'fact', category: 'science', tags: ['math'], summary: 'Pi', importance: 0.9, createdAt: '2025-01-03T00:00:00.000Z', status: 'archived', sourceAppId: 'app1' };
+
+ beforeEach(() => {
+ readJSONFile.mockImplementation((path, def) => {
+ if (path.includes('index.json')) return Promise.resolve(makeIndex([mem1, mem2, mem3]));
+ return Promise.resolve(def);
+ });
+ });
+
+ it('counts active memories by default', async () => {
+ await expect(countMemories()).resolves.toBe(2);
+ });
+
+ it('applies the same filters as getMemories without sorting or paginating', async () => {
+ const sortSpy = vi.spyOn(Array.prototype, 'sort');
+
+ try {
+ const result = await countMemories({
+ status: 'active',
+ tags: ['physics', 'react'],
+ limit: 1,
+ offset: 1,
+ sortBy: 'importance'
+ });
+
+ expect(result).toBe(2);
+ expect(sortSpy).not.toHaveBeenCalled();
+ } finally {
+ sortSpy.mockRestore();
+ }
+ });
+ });
+
// ===========================================================================
// updateMemory
// ===========================================================================