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

refactor([issue-750]): split memory.js into memoryStore + memoryQuery modules

[._.]/ Adam Eivy589c5bfd1ae8
diff --git a/server/lib/README.md b/server/lib/README.md
index c623739602..8554ed9333 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -144,6 +144,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `bm25.js` | BM25 ranking + inverted-index helpers. |
| `vectorMath.js` | Vector math utilities (cosine, etc.). |
+| `memoryQuery.js` | Pure memory-index helpers: meta projection, filter/sort, search/hybrid meta filters, RRF fusion. |
| `memoryStats.js` | macOS-correct memory accounting (handles "Pages free" quirk). |
## Extraction & parsing
diff --git a/server/lib/index.js b/server/lib/index.js
index 18477abb84..88b7d190d7 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -125,6 +125,7 @@ export * from './tailscale.js';
// === Search & indexing ===
export * from './bm25.js';
+export * from './memoryQuery.js';
export * from './memoryStats.js';
export * from './vectorMath.js';
diff --git a/server/lib/memoryQuery.js b/server/lib/memoryQuery.js
new file mode 100644
index 0000000000..bcf1e6676c
--- /dev/null
+++ b/server/lib/memoryQuery.js
@@ -0,0 +1,182 @@
+/**
+ * Memory Query Helpers
+ *
+ * Pure, side-effect-free helpers used by the file-based memory service to
+ * project index metadata, filter/sort index entries, apply post-search
+ * metadata filters, and fuse BM25 + vector rankings via Reciprocal Rank
+ * Fusion (RRF). No module state, no I/O — extracted from memory.js so the
+ * orchestration layer stays focused on persistence + event wiring.
+ */
+
+/**
+ * Project a full memory record down to the lightweight metadata stored in the
+ * index. Used on create/update so the index stays consistent everywhere.
+ *
+ * @param {Object} memory - Full memory record.
+ * @returns {Object} Lightweight index entry.
+ */
+export function projectIndexMeta(memory) {
+ return {
+ id: memory.id,
+ type: memory.type,
+ category: memory.category,
+ tags: memory.tags,
+ summary: memory.summary,
+ importance: memory.importance,
+ createdAt: memory.createdAt,
+ status: memory.status,
+ sourceAppId: memory.sourceAppId
+ };
+}
+
+/**
+ * Filter memory index entries by status/type/category/tags/app.
+ *
+ * @param {Array} memories - Index entries.
+ * @param {Object} options - Filter options.
+ * @returns {Array} Filtered entries.
+ */
+export function filterMemoryIndex(memories, options = {}) {
+ // Filter by status
+ const status = options.status || 'active';
+ let filtered = memories.filter(m => m.status === status);
+
+ // Filter by types
+ if (options.types && options.types.length > 0) {
+ filtered = filtered.filter(m => options.types.includes(m.type));
+ }
+
+ // Filter by categories
+ if (options.categories && options.categories.length > 0) {
+ filtered = filtered.filter(m => options.categories.includes(m.category));
+ }
+
+ // Filter by tags (any match)
+ if (options.tags && options.tags.length > 0) {
+ filtered = filtered.filter(m => m.tags.some(t => options.tags.includes(t)));
+ }
+
+ // Filter by app
+ if (options.appId === '__not_brain') {
+ filtered = filtered.filter(m => m.sourceAppId !== 'brain');
+ } else if (options.appId) {
+ filtered = filtered.filter(m => m.sourceAppId === options.appId);
+ }
+
+ return filtered;
+}
+
+/**
+ * Comparator for sorting index entries by an arbitrary field, treating values
+ * as dates when both parse, numbers when both numeric, strings otherwise.
+ * Missing values sort last. Returns a comparator bound to the sort field/order.
+ *
+ * @param {string} sortBy - Field name to sort by.
+ * @param {'asc'|'desc'} sortOrder - Sort direction.
+ * @returns {(a: Object, b: Object) => number}
+ */
+export function compareMemoryEntries(sortBy = 'createdAt', sortOrder = 'desc') {
+ return (a, b) => {
+ const aRaw = a[sortBy];
+ const bRaw = b[sortBy];
+
+ // Missing values sort last
+ const aMissing = aRaw === null || aRaw === undefined;
+ const bMissing = bRaw === null || bRaw === undefined;
+ if (aMissing && bMissing) return 0;
+ if (aMissing) return 1;
+ if (bMissing) return -1;
+
+ // Compare as dates if both parse as valid timestamps
+ const aTime = (typeof aRaw === 'string' || aRaw instanceof Date) ? Date.parse(aRaw) : NaN;
+ const bTime = (typeof bRaw === 'string' || bRaw instanceof Date) ? Date.parse(bRaw) : NaN;
+ if (!Number.isNaN(aTime) && !Number.isNaN(bTime)) {
+ const diff = aTime - bTime;
+ return sortOrder === 'desc' ? (diff === 0 ? 0 : diff < 0 ? 1 : -1) : (diff === 0 ? 0 : diff < 0 ? -1 : 1);
+ }
+
+ // Numeric comparison
+ if (typeof aRaw === 'number' && typeof bRaw === 'number') {
+ const diff = aRaw - bRaw;
+ return sortOrder === 'desc' ? (diff === 0 ? 0 : diff < 0 ? 1 : -1) : (diff === 0 ? 0 : diff < 0 ? -1 : 1);
+ }
+
+ // String fallback
+ const aStr = String(aRaw);
+ const bStr = String(bRaw);
+ if (aStr === bStr) return 0;
+ const cmp = aStr < bStr ? -1 : 1;
+ return sortOrder === 'desc' ? -cmp : cmp;
+ };
+}
+
+/**
+ * Post-search metadata filter for semantic (vector) search. Requires the entry
+ * to be active and pass any type/category/tag/app constraints. Handles the
+ * `__not_brain` app sentinel.
+ *
+ * @param {Object|undefined} meta - Index entry for a search hit.
+ * @param {Object} options - Search filter options.
+ * @returns {boolean} Whether the entry passes all filters.
+ */
+export function passesSearchMetaFilters(meta, options = {}) {
+ if (!meta || meta.status !== 'active') return false;
+ if (options.types && options.types.length > 0 && !options.types.includes(meta.type)) return false;
+ if (options.categories && options.categories.length > 0 && !options.categories.includes(meta.category)) return false;
+ if (options.tags && options.tags.length > 0 && !meta.tags.some(t => options.tags.includes(t))) return false;
+ if (options.appId === '__not_brain' && meta.sourceAppId === 'brain') return false;
+ if (options.appId && options.appId !== '__not_brain' && meta.sourceAppId !== options.appId) return false;
+ return true;
+}
+
+/**
+ * Post-search metadata filter for hybrid search. Requires the entry to be
+ * active and pass any type/category/tag/app constraints. Does NOT special-case
+ * the `__not_brain` sentinel (matches the original inline behavior).
+ *
+ * @param {Object|undefined} meta - Index entry for a search hit.
+ * @param {Object} options - Search filter options.
+ * @returns {boolean} Whether the entry passes all filters.
+ */
+export function passesHybridMetaFilters(meta, options = {}) {
+ if (!meta || meta.status !== 'active') return false;
+ if (options.types?.length > 0 && !options.types.includes(meta.type)) return false;
+ if (options.categories?.length > 0 && !options.categories.includes(meta.category)) return false;
+ if (options.tags?.length > 0 && !meta.tags.some(t => options.tags.includes(t))) return false;
+ if (options.appId && meta.sourceAppId !== options.appId) return false;
+ return true;
+}
+
+/** Standard RRF constant. */
+export const RRF_K = 60;
+
+/**
+ * Fuse BM25 and vector rankings via Reciprocal Rank Fusion (RRF).
+ * RRF score = sum(weight / (k + rank)) across all rankings.
+ *
+ * @param {Array<{id: string}>} bm25Results - BM25 hits in rank order.
+ * @param {Array<{id: string}>} vectorResults - Vector hits in rank order.
+ * @param {Object} weights - { ftsWeight, vectorWeight }.
+ * @returns {Map<string, {bm25Rank: number|null, vectorRank: number|null, rrfScore: number}>}
+ */
+export function fuseRankingsRRF(bm25Results, vectorResults, { ftsWeight, vectorWeight }) {
+ const rrfScores = new Map();
+
+ // Add BM25 contributions
+ bm25Results.forEach((result, rank) => {
+ const current = rrfScores.get(result.id) || { bm25Rank: null, vectorRank: null, rrfScore: 0 };
+ current.bm25Rank = rank + 1;
+ current.rrfScore += ftsWeight / (RRF_K + rank + 1);
+ rrfScores.set(result.id, current);
+ });
+
+ // Add vector contributions
+ vectorResults.forEach((result, rank) => {
+ const current = rrfScores.get(result.id) || { bm25Rank: null, vectorRank: null, rrfScore: 0 };
+ current.vectorRank = rank + 1;
+ current.rrfScore += vectorWeight / (RRF_K + rank + 1);
+ rrfScores.set(result.id, current);
+ });
+
+ return rrfScores;
+}
diff --git a/server/lib/memoryQuery.test.js b/server/lib/memoryQuery.test.js
new file mode 100644
index 0000000000..e402841a11
--- /dev/null
+++ b/server/lib/memoryQuery.test.js
@@ -0,0 +1,184 @@
+import { describe, it, expect } from 'vitest';
+import {
+ projectIndexMeta,
+ filterMemoryIndex,
+ compareMemoryEntries,
+ passesSearchMetaFilters,
+ passesHybridMetaFilters,
+ fuseRankingsRRF,
+ RRF_K
+} from './memoryQuery.js';
+
+describe('projectIndexMeta', () => {
+ it('projects only the lightweight index fields', () => {
+ const memory = {
+ id: 'm1', type: 'fact', category: 'work', tags: ['a'], summary: 's',
+ importance: 0.7, createdAt: '2024-01-01T00:00:00Z', status: 'active',
+ sourceAppId: 'brain',
+ // fields that must NOT leak into the index entry
+ content: 'long content', embedding: [1, 2, 3], confidence: 0.9, accessCount: 5
+ };
+ expect(projectIndexMeta(memory)).toEqual({
+ id: 'm1', type: 'fact', category: 'work', tags: ['a'], summary: 's',
+ importance: 0.7, createdAt: '2024-01-01T00:00:00Z', status: 'active',
+ sourceAppId: 'brain'
+ });
+ });
+});
+
+describe('filterMemoryIndex', () => {
+ const memories = [
+ { id: '1', type: 'fact', category: 'work', tags: ['x'], status: 'active', sourceAppId: 'brain' },
+ { id: '2', type: 'note', category: 'home', tags: ['y'], status: 'active', sourceAppId: 'app1' },
+ { id: '3', type: 'fact', category: 'work', tags: ['x', 'z'], status: 'archived', sourceAppId: 'app1' }
+ ];
+
+ it('defaults to active status', () => {
+ expect(filterMemoryIndex(memories).map(m => m.id)).toEqual(['1', '2']);
+ });
+
+ it('filters by explicit status', () => {
+ expect(filterMemoryIndex(memories, { status: 'archived' }).map(m => m.id)).toEqual(['3']);
+ });
+
+ it('filters by types', () => {
+ expect(filterMemoryIndex(memories, { types: ['fact'] }).map(m => m.id)).toEqual(['1']);
+ });
+
+ it('filters by categories', () => {
+ expect(filterMemoryIndex(memories, { categories: ['home'] }).map(m => m.id)).toEqual(['2']);
+ });
+
+ it('filters by tags (any match)', () => {
+ expect(filterMemoryIndex(memories, { tags: ['y'] }).map(m => m.id)).toEqual(['2']);
+ });
+
+ it('filters by appId', () => {
+ expect(filterMemoryIndex(memories, { appId: 'app1' }).map(m => m.id)).toEqual(['2']);
+ });
+
+ it('excludes brain entries with __not_brain sentinel', () => {
+ expect(filterMemoryIndex(memories, { appId: '__not_brain' }).map(m => m.id)).toEqual(['2']);
+ });
+});
+
+describe('compareMemoryEntries', () => {
+ it('sorts by date descending by default semantics', () => {
+ const cmp = compareMemoryEntries('createdAt', 'desc');
+ const arr = [
+ { createdAt: '2024-01-01T00:00:00Z' },
+ { createdAt: '2024-03-01T00:00:00Z' },
+ { createdAt: '2024-02-01T00:00:00Z' }
+ ].sort(cmp);
+ expect(arr.map(a => a.createdAt)).toEqual([
+ '2024-03-01T00:00:00Z', '2024-02-01T00:00:00Z', '2024-01-01T00:00:00Z'
+ ]);
+ });
+
+ it('sorts ascending', () => {
+ const cmp = compareMemoryEntries('importance', 'asc');
+ const arr = [{ importance: 0.9 }, { importance: 0.1 }, { importance: 0.5 }].sort(cmp);
+ expect(arr.map(a => a.importance)).toEqual([0.1, 0.5, 0.9]);
+ });
+
+ it('sorts numbers descending', () => {
+ const cmp = compareMemoryEntries('importance', 'desc');
+ const arr = [{ importance: 0.1 }, { importance: 0.9 }, { importance: 0.5 }].sort(cmp);
+ expect(arr.map(a => a.importance)).toEqual([0.9, 0.5, 0.1]);
+ });
+
+ it('places missing values last regardless of order', () => {
+ const cmp = compareMemoryEntries('importance', 'desc');
+ const arr = [{ importance: undefined }, { importance: 0.5 }, { importance: null }].sort(cmp);
+ expect(arr[0].importance).toBe(0.5);
+ expect(arr[1].importance == null).toBe(true);
+ expect(arr[2].importance == null).toBe(true);
+ });
+
+ it('falls back to string comparison', () => {
+ const cmp = compareMemoryEntries('type', 'asc');
+ const arr = [{ type: 'note' }, { type: 'fact' }, { type: 'decision' }].sort(cmp);
+ expect(arr.map(a => a.type)).toEqual(['decision', 'fact', 'note']);
+ });
+});
+
+describe('passesSearchMetaFilters', () => {
+ const meta = { type: 'fact', category: 'work', tags: ['x'], status: 'active', sourceAppId: 'app1' };
+
+ it('rejects missing meta', () => {
+ expect(passesSearchMetaFilters(undefined, {})).toBe(false);
+ });
+
+ it('rejects non-active meta', () => {
+ expect(passesSearchMetaFilters({ ...meta, status: 'archived' }, {})).toBe(false);
+ });
+
+ it('passes active meta with no filters', () => {
+ expect(passesSearchMetaFilters(meta, {})).toBe(true);
+ });
+
+ it('applies type/category/tag filters', () => {
+ expect(passesSearchMetaFilters(meta, { types: ['note'] })).toBe(false);
+ expect(passesSearchMetaFilters(meta, { categories: ['home'] })).toBe(false);
+ expect(passesSearchMetaFilters(meta, { tags: ['y'] })).toBe(false);
+ expect(passesSearchMetaFilters(meta, { types: ['fact'], categories: ['work'], tags: ['x'] })).toBe(true);
+ });
+
+ it('honors __not_brain sentinel', () => {
+ expect(passesSearchMetaFilters({ ...meta, sourceAppId: 'brain' }, { appId: '__not_brain' })).toBe(false);
+ expect(passesSearchMetaFilters(meta, { appId: '__not_brain' })).toBe(true);
+ });
+
+ it('filters by specific appId', () => {
+ expect(passesSearchMetaFilters(meta, { appId: 'other' })).toBe(false);
+ expect(passesSearchMetaFilters(meta, { appId: 'app1' })).toBe(true);
+ });
+});
+
+describe('passesHybridMetaFilters', () => {
+ const meta = { type: 'fact', category: 'work', tags: ['x'], status: 'active', sourceAppId: 'brain' };
+
+ it('does NOT special-case __not_brain (matches original behavior)', () => {
+ // With appId === '__not_brain', a brain entry's sourceAppId !== '__not_brain' -> filtered out
+ expect(passesHybridMetaFilters(meta, { appId: '__not_brain' })).toBe(false);
+ });
+
+ it('passes active meta with no filters', () => {
+ expect(passesHybridMetaFilters(meta, {})).toBe(true);
+ });
+
+ it('rejects non-active or missing', () => {
+ expect(passesHybridMetaFilters(undefined, {})).toBe(false);
+ expect(passesHybridMetaFilters({ ...meta, status: 'archived' }, {})).toBe(false);
+ });
+});
+
+describe('fuseRankingsRRF', () => {
+ it('uses the standard RRF constant of 60', () => {
+ expect(RRF_K).toBe(60);
+ });
+
+ it('computes weighted RRF scores across both rankings', () => {
+ const bm25 = [{ id: 'a' }, { id: 'b' }];
+ const vector = [{ id: 'b' }, { id: 'c' }];
+ const scores = fuseRankingsRRF(bm25, vector, { ftsWeight: 0.4, vectorWeight: 0.6 });
+
+ // a: only bm25 rank 1
+ expect(scores.get('a')).toEqual({
+ bm25Rank: 1, vectorRank: null, rrfScore: 0.4 / (60 + 1)
+ });
+ // c: only vector rank 2
+ expect(scores.get('c')).toEqual({
+ bm25Rank: null, vectorRank: 2, rrfScore: 0.6 / (60 + 2)
+ });
+ // b: bm25 rank 2 + vector rank 1
+ const b = scores.get('b');
+ expect(b.bm25Rank).toBe(2);
+ expect(b.vectorRank).toBe(1);
+ expect(b.rrfScore).toBeCloseTo(0.4 / (60 + 2) + 0.6 / (60 + 1), 12);
+ });
+
+ it('returns an empty map for empty inputs', () => {
+ expect(fuseRankingsRRF([], [], { ftsWeight: 0.4, vectorWeight: 0.6 }).size).toBe(0);
+ });
+});
diff --git a/server/services/memory.js b/server/services/memory.js
index df96bb5a1a..bbb0741836 100644
--- a/server/services/memory.js
+++ b/server/services/memory.js
@@ -3,114 +3,44 @@
*
* Core CRUD and search operations for the CoS memory system.
* Stores facts, learnings, observations, decisions, preferences, and context.
+ *
+ * Orchestration only: persistence + caches + the write mutex live in
+ * `memoryStore.js`; pure index projection/filter/sort/RRF helpers live in
+ * `../lib/memoryQuery.js`. This module wires those primitives into the public
+ * CRUD/search API and emits cosEvents. Public exports are unchanged so all
+ * import sites (and `memoryBackend.js`'s dynamic import) keep working.
*/
-import { writeFile, readdir, rm } from 'fs/promises';
-import { existsSync } from 'fs';
-import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { cosEvents } from './cosEvents.js';
import { findTopK, findAboveThreshold, clusterBySimilarity } from '../lib/vectorMath.js';
import * as notifications from './notifications.js';
-import { ensureDir, ensureDirs, readJSONFile, PATHS } from '../lib/fileUtils.js';
import * as memoryBM25 from './memoryBM25.js';
-import { createMutex } from '../lib/asyncMutex.js';
import { DEFAULT_MEMORY_CONFIG, generateSummary, decrementAgentPendingApproval } from './memoryConfig.js';
+import {
+ withMemoryLock,
+ loadIndex,
+ saveIndex,
+ loadEmbeddings,
+ saveEmbeddings,
+ loadMemory,
+ saveMemory,
+ deleteMemoryFiles,
+ invalidateCaches
+} from './memoryStore.js';
+import {
+ projectIndexMeta,
+ filterMemoryIndex,
+ compareMemoryEntries,
+ passesSearchMetaFilters,
+ passesHybridMetaFilters,
+ fuseRankingsRRF
+} from '../lib/memoryQuery.js';
export { DEFAULT_MEMORY_CONFIG };
-const MEMORY_DIR = PATHS.memory;
-const INDEX_FILE = join(MEMORY_DIR, 'index.json');
-const EMBEDDINGS_FILE = join(MEMORY_DIR, 'embeddings.json');
-const MEMORIES_DIR = join(MEMORY_DIR, 'memories');
-
-// In-memory caches
-let indexCache = null;
-let embeddingsCache = null;
-
-// Mutex lock for state operations
-const withMemoryLock = createMutex();
-
-/**
- * Ensure memory directories exist
- */
-async function ensureDirectories() {
- await ensureDirs([MEMORY_DIR, MEMORIES_DIR]);
-}
-
-/**
- * Load memory index
- */
-async function loadIndex() {
- if (indexCache) return indexCache;
-
- await ensureDirectories();
-
- const defaultIndex = { version: 1, lastUpdated: new Date().toISOString(), count: 0, memories: [] };
- indexCache = await readJSONFile(INDEX_FILE, defaultIndex);
- return indexCache;
-}
-
-/**
- * Save memory index
- */
-async function saveIndex(index) {
- await ensureDirectories();
- index.lastUpdated = new Date().toISOString();
- indexCache = index;
- await writeFile(INDEX_FILE, JSON.stringify(index, null, 2));
-}
-
-/**
- * Load embeddings
- */
-async function loadEmbeddings() {
- if (embeddingsCache) return embeddingsCache;
-
- await ensureDirectories();
-
- const defaultEmbeddings = { model: null, dimension: 0, vectors: {} };
- embeddingsCache = await readJSONFile(EMBEDDINGS_FILE, defaultEmbeddings);
- return embeddingsCache;
-}
-
-/**
- * Save embeddings
- */
-async function saveEmbeddings(embeddings) {
- await ensureDirectories();
- embeddingsCache = embeddings;
- await writeFile(EMBEDDINGS_FILE, JSON.stringify(embeddings));
-}
-
-/**
- * Load full memory by ID
- */
-async function loadMemory(id) {
- const memoryFile = join(MEMORIES_DIR, id, 'memory.json');
- return readJSONFile(memoryFile, null);
-}
-
-/**
- * Save full memory
- */
-async function saveMemory(memory) {
- const memoryDir = join(MEMORIES_DIR, memory.id);
- if (!existsSync(memoryDir)) {
- await ensureDir(memoryDir);
- }
- await writeFile(join(memoryDir, 'memory.json'), JSON.stringify(memory, null, 2));
-}
-
-/**
- * Delete memory files
- */
-async function deleteMemoryFiles(id) {
- const memoryDir = join(MEMORIES_DIR, id);
- if (existsSync(memoryDir)) {
- await rm(memoryDir, { recursive: true });
- }
-}
+// Re-export the cache invalidator so existing import sites keep working.
+export { invalidateCaches };
/**
* Create a new memory
@@ -150,17 +80,7 @@ export async function createMemory(data, embedding = null) {
await saveMemory(memory);
// Add to index (lightweight metadata only)
- index.memories.push({
- id: memory.id,
- type: memory.type,
- category: memory.category,
- tags: memory.tags,
- summary: memory.summary,
- importance: memory.importance,
- createdAt: memory.createdAt,
- status: memory.status,
- sourceAppId: memory.sourceAppId
- });
+ index.memories.push(projectIndexMeta(memory));
index.count = index.memories.length;
await saveIndex(index);
@@ -212,39 +132,6 @@ export async function getMemory(id) {
});
}
-/**
- * Filter memory index entries.
- */
-function filterMemoryIndex(memories, options = {}) {
- // Filter by status
- const status = options.status || 'active';
- let filtered = memories.filter(m => m.status === status);
-
- // Filter by types
- if (options.types && options.types.length > 0) {
- filtered = filtered.filter(m => options.types.includes(m.type));
- }
-
- // Filter by categories
- if (options.categories && options.categories.length > 0) {
- filtered = filtered.filter(m => options.categories.includes(m.category));
- }
-
- // Filter by tags (any match)
- if (options.tags && options.tags.length > 0) {
- filtered = filtered.filter(m => m.tags.some(t => options.tags.includes(t)));
- }
-
- // Filter by app
- if (options.appId === '__not_brain') {
- filtered = filtered.filter(m => m.sourceAppId !== 'brain');
- } else if (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;
@@ -260,38 +147,7 @@ export async function getMemories(options = {}) {
// Sort
const sortBy = options.sortBy || 'createdAt';
const sortOrder = options.sortOrder || 'desc';
- memories.sort((a, b) => {
- const aRaw = a[sortBy];
- const bRaw = b[sortBy];
-
- // Missing values sort last
- const aMissing = aRaw === null || aRaw === undefined;
- const bMissing = bRaw === null || bRaw === undefined;
- if (aMissing && bMissing) return 0;
- if (aMissing) return 1;
- if (bMissing) return -1;
-
- // Compare as dates if both parse as valid timestamps
- const aTime = (typeof aRaw === 'string' || aRaw instanceof Date) ? Date.parse(aRaw) : NaN;
- const bTime = (typeof bRaw === 'string' || bRaw instanceof Date) ? Date.parse(bRaw) : NaN;
- if (!Number.isNaN(aTime) && !Number.isNaN(bTime)) {
- const diff = aTime - bTime;
- return sortOrder === 'desc' ? (diff === 0 ? 0 : diff < 0 ? 1 : -1) : (diff === 0 ? 0 : diff < 0 ? -1 : 1);
- }
-
- // Numeric comparison
- if (typeof aRaw === 'number' && typeof bRaw === 'number') {
- const diff = aRaw - bRaw;
- return sortOrder === 'desc' ? (diff === 0 ? 0 : diff < 0 ? 1 : -1) : (diff === 0 ? 0 : diff < 0 ? -1 : 1);
- }
-
- // String fallback
- const aStr = String(aRaw);
- const bStr = String(bRaw);
- if (aStr === bStr) return 0;
- const cmp = aStr < bStr ? -1 : 1;
- return sortOrder === 'desc' ? -cmp : cmp;
- });
+ memories.sort(compareMemoryEntries(sortBy, sortOrder));
// Paginate
const offset = options.offset || 0;
@@ -330,17 +186,7 @@ export async function updateMemory(id, updates) {
const index = await loadIndex();
const idx = index.memories.findIndex(m => m.id === id);
if (idx !== -1) {
- index.memories[idx] = {
- id: memory.id,
- type: memory.type,
- category: memory.category,
- tags: memory.tags,
- summary: memory.summary,
- importance: memory.importance,
- createdAt: memory.createdAt,
- status: memory.status,
- sourceAppId: memory.sourceAppId
- };
+ index.memories[idx] = projectIndexMeta(memory);
await saveIndex(index);
}
@@ -545,15 +391,7 @@ export async function searchMemories(queryEmbedding, options = {}) {
results = results
.map(r => {
const meta = indexMap.get(r.id);
- if (!meta || meta.status !== 'active') return null;
-
- // Apply type/category/tag/app filters
- if (options.types && options.types.length > 0 && !options.types.includes(meta.type)) return null;
- if (options.categories && options.categories.length > 0 && !options.categories.includes(meta.category)) return null;
- if (options.tags && options.tags.length > 0 && !meta.tags.some(t => options.tags.includes(t))) return null;
- if (options.appId === '__not_brain' && meta.sourceAppId === 'brain') return null;
- if (options.appId && options.appId !== '__not_brain' && meta.sourceAppId !== options.appId) return null;
-
+ if (!passesSearchMetaFilters(meta, options)) return null;
return { ...meta, similarity: r.similarity };
})
.filter(Boolean);
@@ -592,38 +430,14 @@ export async function hybridSearchMemories(query, queryEmbedding, options = {})
}))
}
- // Apply Reciprocal Rank Fusion (RRF)
- // RRF score = sum(1 / (k + rank)) across all rankings
- const RRF_K = 60 // Standard RRF constant
- const rrfScores = new Map()
-
- // Add BM25 contributions
- bm25Results.forEach((result, rank) => {
- const current = rrfScores.get(result.id) || { bm25Rank: null, vectorRank: null, rrfScore: 0 }
- current.bm25Rank = rank + 1
- current.rrfScore += ftsWeight / (RRF_K + rank + 1)
- rrfScores.set(result.id, current)
- })
-
- // Add vector contributions
- vectorResults.forEach((result, rank) => {
- const current = rrfScores.get(result.id) || { bm25Rank: null, vectorRank: null, rrfScore: 0 }
- current.vectorRank = rank + 1
- current.rrfScore += vectorWeight / (RRF_K + rank + 1)
- rrfScores.set(result.id, current)
- })
+ // Apply Reciprocal Rank Fusion (RRF) to merge BM25 + vector rankings
+ const rrfScores = fuseRankingsRRF(bm25Results, vectorResults, { ftsWeight, vectorWeight })
// Filter and sort by RRF score
let results = Array.from(rrfScores.entries())
.map(([id, data]) => {
const meta = indexMap.get(id)
- if (!meta || meta.status !== 'active') return null
-
- // Apply type/category/tag/app filters
- if (options.types?.length > 0 && !options.types.includes(meta.type)) return null
- if (options.categories?.length > 0 && !options.categories.includes(meta.category)) return null
- if (options.tags?.length > 0 && !meta.tags.some(t => options.tags.includes(t))) return null
- if (options.appId && meta.sourceAppId !== options.appId) return null
+ if (!passesHybridMetaFilters(meta, options)) return null
return {
...meta,
@@ -1045,14 +859,6 @@ export async function getStats() {
};
}
-/**
- * Invalidate caches (call after external changes)
- */
-export function invalidateCaches() {
- indexCache = null;
- embeddingsCache = null;
-}
-
/**
* Flush BM25 index to disk
*/
diff --git a/server/services/memoryStore.js b/server/services/memoryStore.js
new file mode 100644
index 0000000000..b88491c6b8
--- /dev/null
+++ b/server/services/memoryStore.js
@@ -0,0 +1,116 @@
+/**
+ * Memory Store
+ *
+ * Persistence + cache layer for the file-based memory service. Owns the
+ * on-disk layout (index.json, embeddings.json, memories/<id>/memory.json),
+ * the in-memory caches, the per-process write mutex, and directory setup.
+ * Extracted from memory.js so the orchestration layer (memory.js) only wires
+ * CRUD/search logic and events on top of these primitives.
+ */
+
+import { writeFile, rm } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { ensureDir, ensureDirs, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { createMutex } from '../lib/asyncMutex.js';
+
+const MEMORY_DIR = PATHS.memory;
+const INDEX_FILE = join(MEMORY_DIR, 'index.json');
+const EMBEDDINGS_FILE = join(MEMORY_DIR, 'embeddings.json');
+const MEMORIES_DIR = join(MEMORY_DIR, 'memories');
+
+// In-memory caches
+let indexCache = null;
+let embeddingsCache = null;
+
+// Mutex lock for state operations
+export const withMemoryLock = createMutex();
+
+/**
+ * Ensure memory directories exist
+ */
+export async function ensureDirectories() {
+ await ensureDirs([MEMORY_DIR, MEMORIES_DIR]);
+}
+
+/**
+ * Load memory index
+ */
+export async function loadIndex() {
+ if (indexCache) return indexCache;
+
+ await ensureDirectories();
+
+ const defaultIndex = { version: 1, lastUpdated: new Date().toISOString(), count: 0, memories: [] };
+ indexCache = await readJSONFile(INDEX_FILE, defaultIndex);
+ return indexCache;
+}
+
+/**
+ * Save memory index
+ */
+export async function saveIndex(index) {
+ await ensureDirectories();
+ index.lastUpdated = new Date().toISOString();
+ indexCache = index;
+ await writeFile(INDEX_FILE, JSON.stringify(index, null, 2));
+}
+
+/**
+ * Load embeddings
+ */
+export async function loadEmbeddings() {
+ if (embeddingsCache) return embeddingsCache;
+
+ await ensureDirectories();
+
+ const defaultEmbeddings = { model: null, dimension: 0, vectors: {} };
+ embeddingsCache = await readJSONFile(EMBEDDINGS_FILE, defaultEmbeddings);
+ return embeddingsCache;
+}
+
+/**
+ * Save embeddings
+ */
+export async function saveEmbeddings(embeddings) {
+ await ensureDirectories();
+ embeddingsCache = embeddings;
+ await writeFile(EMBEDDINGS_FILE, JSON.stringify(embeddings));
+}
+
+/**
+ * Load full memory by ID
+ */
+export async function loadMemory(id) {
+ const memoryFile = join(MEMORIES_DIR, id, 'memory.json');
+ return readJSONFile(memoryFile, null);
+}
+
+/**
+ * Save full memory
+ */
+export async function saveMemory(memory) {
+ const memoryDir = join(MEMORIES_DIR, memory.id);
+ if (!existsSync(memoryDir)) {
+ await ensureDir(memoryDir);
+ }
+ await writeFile(join(memoryDir, 'memory.json'), JSON.stringify(memory, null, 2));
+}
+
+/**
+ * Delete memory files
+ */
+export async function deleteMemoryFiles(id) {
+ const memoryDir = join(MEMORIES_DIR, id);
+ if (existsSync(memoryDir)) {
+ await rm(memoryDir, { recursive: true });
+ }
+}
+
+/**
+ * Invalidate caches (call after external changes)
+ */
+export function invalidateCaches() {
+ indexCache = null;
+ embeddingsCache = null;
+}