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

fix: hard-delete the mapped vector row on a local brain memory delete (#1318)

[._.]/ Adam Eivyf5dbe1150da5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b21339cd05..f852dbf321 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -60,6 +60,8 @@
## Fixed
+- **Deleting a brain memory now hard-prunes its mapped vector row instead of leaving a dead embedding in Postgres forever.** A user-initiated brain delete used to flow through the bridge's archive path (`UPDATE memories SET status='archived'`), which correctly hides the entry from search but left the row and its 768-dim embedding in the database indefinitely — so clearing a large import (e.g. a 1,482-record ChatGPT export) orphaned ~1,482 vectors that nothing ever reclaimed. The bridge now distinguishes a **genuine local delete** (a `{type}:deleted` / `journals:deleted` event, emitted only by the local `remove()`/`deleteJournal` paths) from a **sync-driven archive** (a peer delete arriving via the event-silent `applyRemoteRecord` → `sync:applied`): a real local delete hard-deletes the mapped memory row + embedding and drops its bridge-map entry, while a synced delete stays soft-archived so a peer un-delete can still resurrect it. A present-but-archived record is always kept soft (archived ≠ deleted). (`server/services/brainMemoryBridge.js`, #1318)
+
- **The "Claim Issue" scheduled CoS task no longer reports an empty queue when there are claimable issues.** The task's prompt skipped any issue carrying the `plan` label, calling them "tracking/umbrella" issues. But `do-replan --issues` labels *every* migrated backlog item `plan` — atomic bug-fixes included — so that rule discarded the entire actionable backlog and the task always exited with "no eligible issue" even with dozens of ready-to-work issues open. The prompt now treats `plan` as the claimable-queue label (matching the `/do:next --issues` flow) and skips only true epics (an `epic` label or a "(epic)" title, which need per-slice shipping). Non-customized installs auto-upgrade to the corrected prompt on the next schedule load. (`server/services/taskPromptDefaults/`)
- **A late failure while finishing a local video render now fails the job cleanly instead of crashing the server (or leaving the job stuck "running").** When a render's child process exited and the final bookkeeping step (saving the clip to history, writing its thumbnail) threw, the error escaped the process-close handler as an unhandled rejection — which on modern Node can take down the whole server, and in any case left the media job wedged at "running" forever with no error ever reaching the UI. Both of `videoGen`'s child-close handlers (the main render finalizer and the last-frame extractor used by chained/extend renders) now catch such failures and surface them as a normal terminal error on the job, so the render is reported as failed and the next one proceeds. This path is newly exercised by LoRA-fused renders. (`server/services/videoGen/local.js`, #1334)
diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.js
index 56934c3b45..2d9dda4caf 100644
--- a/server/services/brainMemoryBridge.js
+++ b/server/services/brainMemoryBridge.js
@@ -366,7 +366,7 @@ export async function syncAllBrainData({ dryRun = false, refresh = false } = {})
// we re-read each record's canonical state and re-embed or archive accordingly.
const RESYNC_DEBOUNCE_MS = 250;
-const pendingResync = new Map(); // bridgeKey → { type, id } (dedups repeated touches)
+const pendingResync = new Map(); // bridgeKey → { type, id, hardDelete } (dedups repeated touches)
let resyncTimer = null;
let resyncFlushing = false; // single-flight guard so two flushes can't overlap
@@ -384,6 +384,27 @@ async function archiveMappedMemory(brainType, id) {
return true;
}
+/**
+ * Hard-delete the memory entry mapped to a brain record (issue #1318). Used for
+ * a GENUINE local user delete: archiving the row would hide it from search but
+ * leave the row + its 768-dim embedding in Postgres forever (e.g. ~1,482 dead
+ * vectors after a cleared ChatGPT import). A hard delete drops the row and its
+ * embedding and removes the bridge-map entry so a later create can't collide
+ * with a stale mapping. NOT used for synced-in deletes — those stay soft-
+ * archived (see resyncBrainRecord) so a peer un-delete can resurrect them.
+ */
+async function hardDeleteMappedMemory(brainType, id) {
+ const map = await loadBridgeMap();
+ const key = bridgeKey(brainType, id);
+ const memoryId = map[key];
+ if (!memoryId) return false;
+ await memory.deleteMemory(memoryId, true); // hard: DELETE row + drop embedding
+ delete map[key];
+ await saveBridgeMap();
+ console.log(`🧠🔗 Hard-deleted brain→memory: ${brainType}/${id} → ${memoryId}`);
+ return true;
+}
+
/**
* Re-vectorize (or archive) a single brain record from its CANONICAL stored
* state — used after a peer sync applies a change. Reading the store rather
@@ -391,17 +412,34 @@ async function archiveMappedMemory(brainType, id) {
* whatever the final converged state is (live record, archived, or tombstoned),
* the memory copy is brought into line.
* - record present & not archived → upsert + re-embed (syncBrainRecord)
- * - record absent (tombstoned) or archived → archive the mapped memory entry
+ * - record absent (tombstoned) → hard-delete on a genuine local delete
+ * (hardDelete), else archive the mapped memory entry (synced/recoverable)
+ * - record present but archived → archive (always soft — recoverable)
* - type not mirrored by the bridge (links/buckets/inbox) → no-op
+ *
+ * @param {object} [opts]
+ * @param {boolean} [opts.hardDelete=false] The trigger was a real local user
+ * delete (a `{type}:deleted` event), so a tombstoned record should hard-prune
+ * the mapped memory row + embedding rather than soft-archive it (issue #1318).
+ * Synced-in deletes (sync:applied) pass false so they stay resurrectable.
*/
-export async function resyncBrainRecord(brainType, id) {
+export async function resyncBrainRecord(brainType, id, { hardDelete = false } = {}) {
if (!id || !TYPE_MAP[brainType]) return;
// getById returns null for tombstones (deleted records), so a synced-in
- // delete naturally lands in the archive branch.
+ // delete naturally lands in the archive/hard-delete branch.
const record = brainType === 'journals'
? await getJournal(id)
: await brainStorage.getById(brainType, id);
- if (!record || record.archived) {
+ if (!record) {
+ // Truly gone (tombstoned). A genuine local user delete hard-prunes the row;
+ // a sync-driven delete stays soft so a peer un-delete can resurrect it.
+ if (hardDelete) await hardDeleteMappedMemory(brainType, id);
+ else await archiveMappedMemory(brainType, id);
+ return;
+ }
+ if (record.archived) {
+ // Present but archived (not deleted) — always soft, never hard-delete, even
+ // if the queued trigger carried a hardDelete intent.
await archiveMappedMemory(brainType, id);
return;
}
@@ -429,8 +467,8 @@ export async function flushPendingResync() {
while (pendingResync.size > 0) {
const batch = [...pendingResync.values()];
pendingResync.clear();
- for (const { type, id } of batch) {
- await resyncBrainRecord(type, id).catch((err) => {
+ for (const { type, id, hardDelete } of batch) {
+ await resyncBrainRecord(type, id, { hardDelete }).catch((err) => {
console.error(`❌ Brain bridge resync failed for ${type}/${id}: ${err.message}`);
});
}
@@ -448,9 +486,12 @@ export async function flushPendingResync() {
*/
export function queueResync(records) {
if (!Array.isArray(records)) return;
- for (const { type, id } of records) {
+ for (const { type, id, hardDelete } of records) {
if (!id || !TYPE_MAP[type]) continue;
- pendingResync.set(bridgeKey(type, id), { type, id });
+ // Last touch wins on coalesce. A real local `{type}:deleted` carries
+ // hardDelete:true; upserts and synced applies leave it false so a tombstone
+ // they reach stays soft-archived (resurrectable).
+ pendingResync.set(bridgeKey(type, id), { type, id, hardDelete: !!hardDelete });
}
if (pendingResync.size === 0 || resyncTimer || resyncFlushing) return;
resyncTimer = setTimeout(() => {
@@ -498,7 +539,10 @@ export function initBridge() {
// payload is already stale by flush time still converges correctly.
for (const type of ['people', 'projects', 'ideas', 'admin', 'memories']) {
brainEvents.on(`${type}:upserted`, ({ id }) => queueResync([{ type, id }]));
- brainEvents.on(`${type}:deleted`, ({ id }) => queueResync([{ type, id }]));
+ // A `:deleted` event is a genuine LOCAL user delete (remove() emits it;
+ // applyRemoteRecord is event-silent), so hard-prune the mapped vector row
+ // rather than soft-archive it forever (issue #1318).
+ brainEvents.on(`${type}:deleted`, ({ id }) => queueResync([{ type, id, hardDelete: true }]));
}
// JSONL appends (digests, reviews)
@@ -541,11 +585,9 @@ function handleJournalUpserted(entry) {
async function handleJournalDeleted(entry) {
if (!entry?.id) return;
- const map = await loadBridgeMap();
- const key = bridgeKey('journals', entry.id);
- const memoryId = map[key];
- if (!memoryId) return;
- memory.updateMemory(memoryId, { status: 'archived' }).catch((err) => {
- console.error(`❌ Brain bridge archive failed for journals/${entry.id}: ${err.message}`);
- });
+ // deleteJournal (the local user action) is the only emitter of
+ // 'journals:deleted'; synced-in journal deletes flow through sync:applied →
+ // resyncBrainRecord and stay soft-archived. So a local journal delete hard-
+ // prunes the mapped memory row + embedding (issue #1318).
+ await hardDeleteMappedMemory('journals', entry.id);
}
diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.js
index 77355287c9..4d08ec7b25 100644
--- a/server/services/brainMemoryBridge.test.js
+++ b/server/services/brainMemoryBridge.test.js
@@ -11,6 +11,7 @@ let bridgeFileContents = null; // null = file absent
const 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 generateMemoryEmbedding = vi.fn(async () => [0.1, 0.2, 0.3]);
const getById = vi.fn();
const getAll = vi.fn(async () => []);
@@ -28,7 +29,7 @@ vi.mock('../lib/fileUtils.js', () => ({
PATHS: { brain: '/tmp/test-brain' },
ensureDir: vi.fn(async () => {}),
}));
-vi.mock('./memoryBackend.js', () => ({ createMemory, updateMemory, updateMemoryEmbedding }));
+vi.mock('./memoryBackend.js', () => ({ createMemory, updateMemory, updateMemoryEmbedding, deleteMemory }));
vi.mock('./memoryEmbeddings.js', () => ({ generateMemoryEmbedding }));
vi.mock('./brainStorage.js', () => {
const { EventEmitter } = require('events');
@@ -111,6 +112,51 @@ describe('brainMemoryBridge — resyncBrainRecord (issue #1080)', () => {
expect(createMemory).not.toHaveBeenCalled();
});
+ it('hard-deletes the mapped memory for a tombstoned record when hardDelete:true (local delete, #1318)', async () => {
+ const bridge = await loadBridge();
+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p2')]: 'mem-existing' });
+ getById.mockResolvedValue(null); // tombstoned
+
+ await bridge.resyncBrainRecord('people', 'p2', { hardDelete: true });
+
+ expect(deleteMemory).toHaveBeenCalledWith('mem-existing', true);
+ expect(updateMemory).not.toHaveBeenCalled();
+ expect(createMemory).not.toHaveBeenCalled();
+ });
+
+ it('soft-archives (never hard-deletes) a tombstoned record when hardDelete is absent (synced delete stays recoverable)', async () => {
+ const bridge = await loadBridge();
+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p2')]: 'mem-existing' });
+ getById.mockResolvedValue(null);
+
+ await bridge.resyncBrainRecord('people', 'p2'); // sync:applied path — no hardDelete
+
+ expect(updateMemory).toHaveBeenCalledWith('mem-existing', { status: 'archived' });
+ expect(deleteMemory).not.toHaveBeenCalled();
+ });
+
+ it('soft-archives (never hard-deletes) a present-but-archived record even when hardDelete:true', async () => {
+ const bridge = await loadBridge();
+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('projects', 'pr1')]: 'mem-proj' });
+ getById.mockResolvedValue({ id: 'pr1', name: 'X', status: 'done', archived: true });
+
+ await bridge.resyncBrainRecord('projects', 'pr1', { hardDelete: true });
+
+ // Archived ≠ deleted — keep it recoverable, do not drop the row.
+ expect(updateMemory).toHaveBeenCalledWith('mem-proj', { status: 'archived' });
+ expect(deleteMemory).not.toHaveBeenCalled();
+ });
+
+ it('no hard-delete call when a deleted record was never mapped', async () => {
+ const bridge = await loadBridge();
+ getById.mockResolvedValue(null);
+
+ await bridge.resyncBrainRecord('people', 'never-seen', { hardDelete: true });
+
+ expect(deleteMemory).not.toHaveBeenCalled();
+ expect(updateMemory).not.toHaveBeenCalled();
+ });
+
it('reactivates an archived memory when its record comes back live (status:active)', async () => {
const bridge = await loadBridge();
// p1 is already mapped (memory was archived for a prior synced-in delete);
@@ -246,7 +292,7 @@ describe('brainMemoryBridge — entity :upserted/:deleted route through queueRes
expect(createMemory).toHaveBeenCalledTimes(50);
});
- it('routes :deleted through the resync path, archiving the mapped memory', async () => {
+ it('routes a local :deleted through the resync path, HARD-deleting the mapped memory (issue #1318)', async () => {
const bridge = await loadBridge();
const { brainEvents } = await import('./brainStorage.js');
bridge.initBridge();
@@ -256,9 +302,39 @@ describe('brainMemoryBridge — entity :upserted/:deleted route through queueRes
brainEvents.emit('people:deleted', { id: 'p9' });
await bridge.flushPendingResync();
- expect(updateMemory).toHaveBeenCalledWith('mem-del', { status: 'archived' });
+ // Real local delete → hard prune (drop row + embedding), NOT soft archive.
+ expect(deleteMemory).toHaveBeenCalledWith('mem-del', true);
+ expect(updateMemory).not.toHaveBeenCalledWith('mem-del', { status: 'archived' });
expect(createMemory).not.toHaveBeenCalled();
});
+
+ it('drops the bridge-map entry after a local hard-delete so a re-create starts fresh', async () => {
+ const bridge = await loadBridge();
+ const { brainEvents } = await import('./brainStorage.js');
+ bridge.initBridge();
+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p9')]: 'mem-del' });
+ getById.mockResolvedValue(null);
+
+ brainEvents.emit('people:deleted', { id: 'p9' });
+ await bridge.flushPendingResync();
+
+ const map = await bridge.loadBridgeMap();
+ expect(map[bridge.bridgeKey('people', 'p9')]).toBeUndefined();
+ });
+
+ it('hard-deletes the mapped memory on a local journals:deleted (issue #1318)', async () => {
+ const bridge = await loadBridge();
+ const { brainEvents } = await import('./brainStorage.js');
+ bridge.initBridge();
+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('journals', '2026-06-09')]: 'mem-day' });
+
+ brainEvents.emit('journals:deleted', { date: '2026-06-09', entry: { id: '2026-06-09' } });
+ // handleJournalDeleted is async; flush the microtask queue.
+ await new Promise((r) => setImmediate(r));
+
+ expect(deleteMemory).toHaveBeenCalledWith('mem-day', true);
+ expect(updateMemory).not.toHaveBeenCalled();
+ });
});
describe('brainMemoryBridge — syncAllBrainData refresh mode (issue #1080 recovery)', () => {