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
refactor: split deleteMemory(id, hard) into archiveMemory and purgeMemory (#9199)
Adam Eivy292ceae2aa82
diff --git a/server/routes/memory.js b/server/routes/memory.jsindex c6dea7d778..99a08710ed 100644--- a/server/routes/memory.js+++ b/server/routes/memory.js@@ -220,7 +220,7 @@ router.post('/:id/reject', asyncHandler(async (req, res) => {router.delete('/:id', asyncHandler(async (req, res) => {const { id } = validateRequest(memoryIdParamSchema, req.params);const hard = req.query.hard === 'true';- const result = await memory.deleteMemory(id, hard);+ const result = await (hard ? memory.purgeMemory(id) : memory.archiveMemory(id));res.json(result);}));diff --git a/server/routes/memory.test.js b/server/routes/memory.test.jsindex 41b7f3389b..51b685f909 100644--- a/server/routes/memory.test.js+++ b/server/routes/memory.test.js@@ -17,7 +17,8 @@ vi.mock('../services/memoryBackend.js', () => ({createMemory: vi.fn(),updateMemory: vi.fn(),updateMemoryEmbedding: vi.fn(),- deleteMemory: vi.fn(),+ archiveMemory: vi.fn(),+ purgeMemory: vi.fn(),searchMemories: vi.fn(),consolidateMemories: vi.fn(),linkMemories: vi.fn(),@@ -45,7 +46,7 @@ vi.mock('../services/memorySync.js', () => ({applyRemoteChanges: vi.fn()}));-import { ensureBackend, getMemories, getTimeline, deleteMemory, applyDecay } from '../services/memoryBackend.js';+import { ensureBackend, getMemories, getTimeline, archiveMemory, purgeMemory, applyDecay } from '../services/memoryBackend.js';import { checkHealth } from '../lib/db.js';import * as memorySync from '../services/memorySync.js';@@ -68,23 +69,36 @@ describe('Memory Routes', () => {const response = await request(app).delete(`/api/memory/${id}`);expect(response.status).toBe(status);- expect(deleteMemory).not.toHaveBeenCalled();+ expect(archiveMemory).not.toHaveBeenCalled();+ expect(purgeMemory).not.toHaveBeenCalled();});it('does not route an empty memory id to deletion', async () => {const response = await request(app).delete('/api/memory/');expect(response.status).toBe(404);- expect(deleteMemory).not.toHaveBeenCalled();+ expect(archiveMemory).not.toHaveBeenCalled();+ expect(purgeMemory).not.toHaveBeenCalled();});- it('deletes a valid memory id', async () => {- deleteMemory.mockResolvedValue({ success: true });+ it('purges a valid memory id when hard=true', async () => {+ purgeMemory.mockResolvedValue({ success: true });const response = await request(app).delete('/api/memory/mem-42?hard=true');expect(response.status).toBe(200);- expect(deleteMemory).toHaveBeenCalledWith('mem-42', true);+ expect(purgeMemory).toHaveBeenCalledWith('mem-42');+ expect(archiveMemory).not.toHaveBeenCalled();+ });++ it('archives a valid memory id by default', async () => {+ archiveMemory.mockResolvedValue({ success: true });++ const response = await request(app).delete('/api/memory/mem-42');++ expect(response.status).toBe(200);+ expect(archiveMemory).toHaveBeenCalledWith('mem-42');+ expect(purgeMemory).not.toHaveBeenCalled();});});diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex 9049148c06..441992bf68 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -543,7 +543,7 @@ async function hardDeleteMappedMemory(brainType, id) {const key = bridgeKey(brainType, id);const memoryId = map[key];if (!memoryId) return false;- await memory.deleteMemory(memoryId, true); // hard: DELETE row + drop embedding+ await memory.purgeMemory(memoryId);delete map[key];await saveBridgeMap();console.log(`🧠🔗 Hard-deleted brain→memory: ${brainType}/${id} → ${memoryId}`);diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.jsindex eda3624f92..0b7213dd53 100644--- a/server/services/brainMemoryBridge.test.js+++ b/server/services/brainMemoryBridge.test.js@@ -11,7 +11,7 @@ let bridgeFileContents = null; // null = file absentconst createMemory = vi.fn(async (data) => ({ id: `mem-${data.content?.slice(0, 6) || 'x'}` }));const updateMemory = vi.fn(async () => ({ id: 'updated' }));const updateMemoryEmbedding = vi.fn(async () => {});-const deleteMemory = vi.fn(async () => ({ success: true }));+const purgeMemory = vi.fn(async () => ({ success: true }));const generateMemoryEmbedding = vi.fn(async () => [0.1, 0.2, 0.3]);const getMemoryIdsMissingEmbedding = vi.fn(async () => new Set());const getById = vi.fn();@@ -40,7 +40,7 @@ vi.mock('../lib/fileUtils.js', () => ({atomicWrite,}));vi.mock('./memoryBackend.js', () => ({- createMemory, updateMemory, updateMemoryEmbedding, deleteMemory, getMemoryIdsMissingEmbedding,+ createMemory, updateMemory, updateMemoryEmbedding, purgeMemory, getMemoryIdsMissingEmbedding,}));vi.mock('./memoryEmbeddings.js', () => ({ generateMemoryEmbedding }));vi.mock('./brainStorage.js', () => {@@ -138,7 +138,7 @@ describe('brainMemoryBridge — resyncBrainRecord (issue #1080)', () => {await bridge.resyncBrainRecord('people', 'p2', { hardDelete: true });- expect(deleteMemory).toHaveBeenCalledWith('mem-existing', true);+ expect(purgeMemory).toHaveBeenCalledWith('mem-existing');expect(updateMemory).not.toHaveBeenCalled();expect(createMemory).not.toHaveBeenCalled();});@@ -151,7 +151,7 @@ describe('brainMemoryBridge — resyncBrainRecord (issue #1080)', () => {await bridge.resyncBrainRecord('people', 'p2'); // sync:applied path — no hardDeleteexpect(updateMemory).toHaveBeenCalledWith('mem-existing', { status: 'archived' });- expect(deleteMemory).not.toHaveBeenCalled();+ expect(purgeMemory).not.toHaveBeenCalled();});it('soft-archives (never hard-deletes) a present-but-archived record even when hardDelete:true', async () => {@@ -163,7 +163,7 @@ describe('brainMemoryBridge — resyncBrainRecord (issue #1080)', () => {// Archived ≠ deleted — keep it recoverable, do not drop the row.expect(updateMemory).toHaveBeenCalledWith('mem-proj', { status: 'archived' });- expect(deleteMemory).not.toHaveBeenCalled();+ expect(purgeMemory).not.toHaveBeenCalled();});it('no hard-delete call when a deleted record was never mapped', async () => {@@ -172,7 +172,7 @@ describe('brainMemoryBridge — resyncBrainRecord (issue #1080)', () => {await bridge.resyncBrainRecord('people', 'never-seen', { hardDelete: true });- expect(deleteMemory).not.toHaveBeenCalled();+ expect(purgeMemory).not.toHaveBeenCalled();expect(updateMemory).not.toHaveBeenCalled();});@@ -218,7 +218,7 @@ describe('brainMemoryBridge — queueResync debounce + dedup', () => {bridge.queueResync([{ type: 'people', id: 'p1' }]);await bridge.flushPendingResync();- expect(deleteMemory).toHaveBeenCalledWith('mem-del', true);+ expect(purgeMemory).toHaveBeenCalledWith('mem-del');expect(updateMemory).not.toHaveBeenCalledWith('mem-del', { status: 'archived' });});@@ -337,7 +337,7 @@ describe('brainMemoryBridge — entity :upserted/:deleted route through queueResawait bridge.flushPendingResync();// Real local delete → hard prune (drop row + embedding), NOT soft archive.- expect(deleteMemory).toHaveBeenCalledWith('mem-del', true);+ expect(purgeMemory).toHaveBeenCalledWith('mem-del');expect(updateMemory).not.toHaveBeenCalledWith('mem-del', { status: 'archived' });expect(createMemory).not.toHaveBeenCalled();});@@ -366,7 +366,7 @@ describe('brainMemoryBridge — entity :upserted/:deleted route through queueRes// handleJournalDeleted is async; flush the microtask queue.await new Promise((r) => setImmediate(r));- expect(deleteMemory).toHaveBeenCalledWith('mem-day', true);+ expect(purgeMemory).toHaveBeenCalledWith('mem-day');expect(updateMemory).not.toHaveBeenCalled();});});@@ -438,7 +438,7 @@ describe('brainMemoryBridge — journal re-embed debounce (daily-log autosave)',await vi.advanceTimersByTimeAsync(31_000);await bridge.flushPendingResync();- expect(deleteMemory).toHaveBeenCalledWith('mem-day', true);+ expect(purgeMemory).toHaveBeenCalledWith('mem-day');expect(generateMemoryEmbedding).not.toHaveBeenCalled();});});@@ -671,7 +671,7 @@ describe('brainMemoryBridge — SongBook enrollment (issue #4105)', () => {brainEvents.emit('songs:deleted', { id: 's1' });await bridge.flushPendingResync();- expect(deleteMemory).toHaveBeenCalledWith('mem-song', true);+ expect(purgeMemory).toHaveBeenCalledWith('mem-song');});it('includes songs in the bulk sync and the embedding-coverage tally', async () => {diff --git a/server/services/memory.js b/server/services/memory.jsindex 839bdfd638..49cb703a6c 100644--- a/server/services/memory.js+++ b/server/services/memory.js@@ -243,50 +243,58 @@ export async function updateMemoryEmbedding(id, embedding) {}/**- * Delete a memory (soft delete by default)+ * Archive a memory: mark it archived; the row and embedding stay, so it is restorable.*/-export async function deleteMemory(id, hard = false) {+export async function archiveMemory(id) {return withMemoryLock(async () => {- if (hard) {- // Hard delete - remove files- await deleteMemoryFiles(id);+ // Note: We can't call updateMemory here as it would cause deadlock (both use withMemoryLock)+ // Instead, we handle the archive logic directly within this lock+ const memory = await loadMemory(id);+ if (memory) {+ memory.status = 'archived';+ memory.updatedAt = new Date().toISOString();+ await saveMemory(memory);- // Remove from index+ // Update indexconst index = await loadIndex();- index.memories = index.memories.filter(m => m.id !== id);- index.count = index.memories.length;- await saveIndex(index);-- // Remove embedding- const embeddings = await loadEmbeddings();- delete embeddings.vectors[id];- await saveEmbeddings(embeddings);-- // Remove from BM25 index- memoryBM25.removeMemoryFromIndex(id)- .catch(err => console.error(`⚠️ BM25 remove error: ${err.message}`));- } else {- // Soft delete - mark as archived- // Note: We can't call updateMemory here as it would cause deadlock (both use withMemoryLock)- // Instead, we handle the soft delete logic directly within this lock- const memory = await loadMemory(id);- if (memory) {- memory.status = 'archived';- memory.updatedAt = new Date().toISOString();- await saveMemory(memory);-- // Update index- const index = await loadIndex();- const idx = index.memories.findIndex(m => m.id === id);- if (idx !== -1) {- index.memories[idx].status = 'archived';- await saveIndex(index);- }+ const idx = index.memories.findIndex(m => m.id === id);+ if (idx !== -1) {+ index.memories[idx].status = 'archived';+ await saveIndex(index);}}- console.log(`🧠 Memory deleted: ${id} (hard: ${hard})`);- cosEvents.emit('memory:deleted', { id, hard });+ console.log(`🧠 Memory archived: ${id}`);+ cosEvents.emit('memory:deleted', { id, hard: false });++ return { success: true, id };+ });+}++/**+ * Purge a memory: destroy its files, index entry, embedding and BM25 entry. Not restorable.+ */+export async function purgeMemory(id) {+ return withMemoryLock(async () => {+ await deleteMemoryFiles(id);++ // Remove from index+ const index = await loadIndex();+ index.memories = index.memories.filter(m => m.id !== id);+ index.count = index.memories.length;+ await saveIndex(index);++ // Remove embedding+ const embeddings = await loadEmbeddings();+ delete embeddings.vectors[id];+ await saveEmbeddings(embeddings);++ // Remove from BM25 index+ memoryBM25.removeMemoryFromIndex(id)+ .catch(err => console.error(`⚠️ BM25 remove error: ${err.message}`));++ console.log(`🧠 Memory purged: ${id}`);+ cosEvents.emit('memory:deleted', { id, hard: true });return { success: true, id };});diff --git a/server/services/memory.test.js b/server/services/memory.test.jsindex 2a01c62eb0..c39b431585 100644--- a/server/services/memory.test.js+++ b/server/services/memory.test.js@@ -88,7 +88,8 @@ import {getMemories,updateMemory,updateMemoryEmbedding,- deleteMemory,+ archiveMemory,+ purgeMemory,approveMemory,rejectMemory,searchMemories,@@ -653,16 +654,16 @@ describe('memory service', () => {});// ===========================================================================- // deleteMemory+ // archiveMemory / purgeMemory// ===========================================================================- describe('deleteMemory', () => {- it('should soft delete (archive) by default', async () => {+ describe('archiveMemory / purgeMemory', () => {+ it('should archive', async () => {const mockMemory = { id: 'mem-1', status: 'active', updatedAt: '' };const mockIndex = { version: 1, lastUpdated: '', count: 1, memories: [{ id: 'mem-1', status: 'active' }] };readJSONFile.mockImplementation(makeReadMock(mockMemory, mockIndex));- const result = await deleteMemory('mem-1');+ const result = await archiveMemory('mem-1');expect(result).toEqual({ success: true, id: 'mem-1' });expect(rmGuarded).not.toHaveBeenCalled();@@ -673,12 +674,12 @@ describe('memory service', () => {expect(savedMemory.status).toBe('archived');});- it('should hard delete when hard=true', async () => {+ it('should purge', async () => {const mockIndex = { version: 1, lastUpdated: '', count: 1, memories: [{ id: 'mem-1', status: 'active' }] };const mockEmbeddings = { model: 'test', dimension: 3, vectors: { 'mem-1': [0.1, 0.2, 0.3] } };readJSONFile.mockImplementation(makeReadMock(null, mockIndex, mockEmbeddings));- const result = await deleteMemory('mem-1', true);+ const result = await purgeMemory('mem-1');expect(result).toEqual({ success: true, id: 'mem-1' });expect(rmGuarded).toHaveBeenCalled();@@ -691,17 +692,17 @@ describe('memory service', () => {const mockIndex = { version: 1, lastUpdated: '', count: 1, memories: [{ id: 'mem-1', status: 'active' }] };readJSONFile.mockImplementation(makeReadMock(mockMemory, mockIndex));- await deleteMemory('mem-1');+ await archiveMemory('mem-1');expect(emitSpy).toHaveBeenCalledWith('memory:deleted', { id: 'mem-1', hard: false });});- it('should emit memory:deleted with hard=true', async () => {+ it('should emit memory:deleted with hard=true on purge', async () => {const emitSpy = vi.spyOn(cosEvents, 'emit');const mockIndex = { version: 1, lastUpdated: '', count: 1, memories: [{ id: 'mem-1', status: 'active' }] };readJSONFile.mockImplementation(makeReadMock(null, mockIndex));- await deleteMemory('mem-1', true);+ await purgeMemory('mem-1');expect(emitSpy).toHaveBeenCalledWith('memory:deleted', { id: 'mem-1', hard: true });});diff --git a/server/services/memoryBackend.js b/server/services/memoryBackend.jsindex e846c45895..9f43a724af 100644--- a/server/services/memoryBackend.js+++ b/server/services/memoryBackend.js@@ -140,9 +140,19 @@ export async function updateMemoryEmbedding(id, embedding) {return b.updateMemoryEmbedding(id, embedding);}-export async function deleteMemory(id, hard) {+export async function archiveMemory(id) {+ const b = await getBackend();+ return b.archiveMemory(id);+}++export async function purgeMemory(id) {const b = await getBackend();- return b.deleteMemory(id, hard);+ return b.purgeMemory(id);+}++/** @deprecated Call archiveMemory or purgeMemory so the call site says whether it destroys data. */+export async function deleteMemory(id, hard) {+ return hard ? purgeMemory(id) : archiveMemory(id);}export async function approveMemory(id) {diff --git a/server/services/memoryDB.db.test.js b/server/services/memoryDB.db.test.jsindex eb289926c1..4cefa46626 100644--- a/server/services/memoryDB.db.test.js+++ b/server/services/memoryDB.db.test.js@@ -271,13 +271,13 @@ describe.skipIf(!runDb)('memoryDB CRUD (#3447)', () => {expect(missing).toEqual({ success: false, error: 'Memory not found' });});- it('soft-deletes by default and hard-deletes on request', async () => {+ it('archives and purges', async () => {const soft = await memoryDB.createMemory({ type: 'fact', content: 'Soft delete me.' });- await memoryDB.deleteMemory(soft.id);+ await memoryDB.archiveMemory(soft.id);expect(await statusOf(soft.id)).toBe('archived');const hard = await memoryDB.createMemory({ type: 'fact', content: 'Hard delete me.' });- await memoryDB.deleteMemory(hard.id, true);+ await memoryDB.purgeMemory(hard.id);expect(await memoryDB.peekMemory(hard.id)).toBeNull();});diff --git a/server/services/memoryDB.js b/server/services/memoryDB.jsindex 01a9ddddf7..14e5c306e8 100644--- a/server/services/memoryDB.js+++ b/server/services/memoryDB.js@@ -390,19 +390,25 @@ export async function updateMemoryEmbedding(id, embedding) {}/**- * Delete a memory (soft delete by default)+ * Archive a memory: mark it archived; the row and embedding stay, so it is restorable.*/-export async function deleteMemory(id, hard = false) {- if (hard) {- // Hard delete — cascades to memory_links via ON DELETE CASCADE- await query('DELETE FROM memories WHERE id = $1', [id]);- } else {- // Soft delete — mark as archived- await query("UPDATE memories SET status = 'archived' WHERE id = $1", [id]);- }+export async function archiveMemory(id) {+ await query("UPDATE memories SET status = 'archived' WHERE id = $1", [id]);++ console.log(`🧠 Memory archived: ${id}`);+ cosEvents.emit('memory:deleted', { id, hard: false });++ return { success: true, id };+}++/**+ * Purge a memory: DELETE the row (cascades to memory_links) and its embedding. Not restorable.+ */+export async function purgeMemory(id) {+ await query('DELETE FROM memories WHERE id = $1', [id]);- console.log(`🧠 Memory deleted: ${id} (hard: ${hard})`);- cosEvents.emit('memory:deleted', { id, hard });+ console.log(`🧠 Memory purged: ${id}`);+ cosEvents.emit('memory:deleted', { id, hard: true });return { success: true, id };}diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.jsindex 6bdfaa2c57..d965b13e58 100644--- a/server/services/persistentMindContext.js+++ b/server/services/persistentMindContext.js@@ -134,7 +134,7 @@ export function archivePersistentMindMemories(mindId = PERSISTENT_MIND_ID) {preserved += 1;continue;}- await memoryBackend.deleteMemory(memory.id, false);+ await memoryBackend.archiveMemory(memory.id);archived += 1;batchArchived += 1;}diff --git a/server/services/persistentMindContext.test.js b/server/services/persistentMindContext.test.jsindex d5b51bdcfe..0fea74c07e 100644--- a/server/services/persistentMindContext.test.js+++ b/server/services/persistentMindContext.test.js@@ -10,7 +10,7 @@ const mock = vi.hoisted(() => ({getMemories: vi.fn(async () => ({ memories: [] })),peekMemory: vi.fn(),createMemory: vi.fn(async (input) => ({ id: 'memory-automatic-1', ...input })),- deleteMemory: vi.fn(async (id) => ({ success: true, id })),+ archiveMemory: vi.fn(async (id) => ({ success: true, id })),updateMemory: vi.fn(),},}));@@ -76,7 +76,7 @@ beforeEach(() => {mock.memoryApi.peekMemory.mockReset();mock.memoryApi.updateMemory.mockReset();mock.memoryApi.createMemory.mockClear();- mock.memoryApi.deleteMemory.mockReset().mockImplementation(async (id) => ({ success: true, id }));+ mock.memoryApi.archiveMemory.mockReset().mockImplementation(async (id) => ({ success: true, id }));});afterAll(() => rmSync(CONTEXT_DIR, { recursive: true, force: true }));@@ -358,11 +358,11 @@ describe('persistent mind memory cleanup', () => {memories: [...records.values()].filter((memory) => memory.status === 'active' && (!tags || tags.some((tag) => memory.tags.includes(tag)))).sort((a, b) => sortBy === 'importance' ? b.importance - a.importance : 0).slice(offset, offset + limit),}));mock.memoryApi.peekMemory.mockImplementation(async (id) => structuredClone(records.get(id)));- mock.memoryApi.deleteMemory.mockImplementation(async (id) => { records.get(id).status = 'archived'; });+ mock.memoryApi.archiveMemory.mockImplementation(async (id) => { records.get(id).status = 'archived'; });await expect(archivePersistentMindMemories()).resolves.toEqual({ archived: 1, preserved: 102 });- expect(mock.memoryApi.deleteMemory).toHaveBeenCalledTimes(1);- expect(mock.memoryApi.deleteMemory).toHaveBeenCalledWith('ordinary', false);+ expect(mock.memoryApi.archiveMemory).toHaveBeenCalledTimes(1);+ expect(mock.memoryApi.archiveMemory).toHaveBeenCalledWith('ordinary');await expect(archivePersistentMindMemories()).resolves.toEqual({ archived: 0, preserved: 102 });const memories = await readPersistentMindMemories();expect(memories[0]).toMatchObject({ id: 'memory-0', protection: 'core-identity' });@@ -397,8 +397,8 @@ describe('persistent mind memory cleanup', () => {.mockResolvedValueOnce({ id: 'memory-foreign', status: 'active', sourceAgentId: 'other-agent' });await expect(archivePersistentMindMemories()).resolves.toEqual({ archived: 1, preserved: 0 });- expect(mock.memoryApi.deleteMemory).toHaveBeenCalledWith('memory-owned', false);- expect(mock.memoryApi.deleteMemory).not.toHaveBeenCalledWith('memory-foreign', expect.anything());+ expect(mock.memoryApi.archiveMemory).toHaveBeenCalledWith('memory-owned');+ expect(mock.memoryApi.archiveMemory).not.toHaveBeenCalledWith('memory-foreign', expect.anything());});});