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

address review (codex): keep shared ChatGPT archive when a duplicate import still references it

Adam Eivyf9438eeb3967
diff --git a/server/services/brain.js b/server/services/brain.js
index bfdc2a8edf..c736cdf2fd 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -778,15 +778,15 @@ export const updateMemoryEntry = storage.updateMemoryEntry;
* `content`. The storage-level delete only tombstones the JSON record — without
* this wrapper those files orphan forever under `data/brain/imports/`. We load
* the record first (to know what it referenced) and the surviving import
- * memories (so a shared asset still in use isn't pulled out from under them).
+ * memories (so a shared transcript/asset still in use — e.g. the same export
+ * imported twice — isn't pulled out from under them).
*/
export async function deleteMemoryEntry(id) {
const record = await storage.getMemoryEntryById(id);
const deleted = await storage.deleteMemoryEntry(id);
if (deleted && record?.source === 'chatgpt-import') {
const survivors = (await storage.getMemoryEntries())
- .filter((m) => m.id !== id && m.source === 'chatgpt-import')
- .map((m) => m.content);
+ .filter((m) => m.id !== id && m.source === 'chatgpt-import');
await deleteMemoryAssets(record, survivors);
}
return deleted;
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index 3fb5512c52..c1237cdae6 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -1136,12 +1136,13 @@ describe('brain service', () => {
it('cleans up assets for a deleted chatgpt-import memory, passing the OTHER imports as survivors', async () => {
const deleted = { id: 'm1', source: 'chatgpt-import', sourceRef: 'c1.json', content: '![a](/data/brain-imports/file-a.png)' };
+ const survivor = { id: 'm2', source: 'chatgpt-import', sourceRef: 'c2.json', content: '![b](/data/brain-imports/file-b.png)' };
storage.getMemoryEntryById.mockResolvedValue(deleted);
storage.deleteMemoryEntry.mockResolvedValue(true);
// getMemoryEntries already strips the tombstoned record; include a hand-
// written (non-import) memory to prove the survivor filter keeps only imports.
storage.getMemoryEntries.mockResolvedValue([
- { id: 'm2', source: 'chatgpt-import', content: '![b](/data/brain-imports/file-b.png)' },
+ survivor,
{ id: 'm3', source: undefined, content: 'hand-written note' },
]);
@@ -1149,7 +1150,9 @@ describe('brain service', () => {
expect(result).toBe(true);
expect(deleteMemoryAssets).toHaveBeenCalledTimes(1);
- expect(deleteMemoryAssets).toHaveBeenCalledWith(deleted, ['![b](/data/brain-imports/file-b.png)']);
+ // Survivors are full records (so cleanup can guard a shared sourceRef too),
+ // and only the other chatgpt-import is passed — never the hand-written note.
+ expect(deleteMemoryAssets).toHaveBeenCalledWith(deleted, [survivor]);
});
it('skips asset cleanup when the record was already gone (delete returned false)', async () => {
diff --git a/server/services/chatgptImport.js b/server/services/chatgptImport.js
index 75fbd5c8ef..693ba918d5 100644
--- a/server/services/chatgptImport.js
+++ b/server/services/chatgptImport.js
@@ -348,22 +348,29 @@ export const extractAssetFileNames = (content) => {
* Delete the on-disk assets + archived transcript that belonged to a deleted
* `chatgpt-import` memory, leaving no orphans under `data/brain/imports/`.
*
- * `survivingContents` is the `content` of every OTHER live import memory — an
- * asset id can legitimately appear in more than one conversation (ChatGPT
- * reuses a `file-service://` id across chats), so an asset is only unlinked when
- * NO surviving memory still references it. The archived transcript JSON is keyed
- * 1:1 by `sourceRef`, so it's always safe to remove with its memory.
+ * `survivors` is every OTHER live import memory. Neither the archive nor an
+ * asset is unlinked while a survivor still references it:
+ * - The transcript JSON is keyed on the conversation id (`sourceRef`), so
+ * importing the same export twice yields two memories pointing at ONE
+ * archive — deleting one must not strand the other's "View full
+ * conversation" / re-summarize path. Keep the archive while any survivor
+ * shares its `sourceRef`.
+ * - An asset id can likewise recur across conversations (ChatGPT reuses a
+ * `file-service://` id), so an asset is only unlinked when NO survivor
+ * still references it.
*
* Best-effort: a missing file is a no-op (already gone), and any unlink failure
* is logged but never thrown — cleanup must not turn a successful delete into a
* request error.
*/
-export async function deleteMemoryAssets(record, survivingContents = []) {
+export async function deleteMemoryAssets(record, survivors = []) {
if (!record || record.source !== 'chatgpt-import') return;
- // 1. Archived transcript — 1:1 with this memory's sourceRef, always removable.
+ // 1. Archived transcript — remove only when no surviving import shares it (a
+ // re-import of the same conversation reuses the same `<id>.json` archive).
const ref = String(record.sourceRef || '');
- if (/^[a-zA-Z0-9-_]+\.json$/.test(ref)) {
+ const refStillUsed = survivors.some((m) => m?.sourceRef === ref);
+ if (/^[a-zA-Z0-9-_]+\.json$/.test(ref) && !refStillUsed) {
await unlink(join(importRoot(), ref)).catch((err) => {
if (err?.code !== 'ENOENT') console.error(`⚠️ Failed to remove archived transcript ${ref}: ${err.message}`);
});
@@ -381,8 +388,8 @@ export async function deleteMemoryAssets(record, survivingContents = []) {
const referenced = extractAssetFileNames(record.content);
if (referenced.size === 0) return;
const stillUsed = new Set();
- for (const content of survivingContents) {
- for (const name of extractAssetFileNames(content)) stillUsed.add(name);
+ for (const m of survivors) {
+ for (const name of extractAssetFileNames(m?.content)) stillUsed.add(name);
}
const orphaned = [...referenced].filter((name) => !stillUsed.has(name));
await Promise.all(orphaned.map((name) =>
diff --git a/server/services/chatgptImport.test.js b/server/services/chatgptImport.test.js
index 79cb7c5dc1..59ce94c62f 100644
--- a/server/services/chatgptImport.test.js
+++ b/server/services/chatgptImport.test.js
@@ -336,13 +336,29 @@ describe('chatgptImport service', () => {
source: 'chatgpt-import',
sourceRef: 'gone.json',
content: '![s](/data/brain-imports/file-shared.png)\n![x](/data/brain-imports/file-solo.png)',
- }, ['![still](/data/brain-imports/file-shared.png)']);
+ }, [{ id: 'mem-2', sourceRef: 'other.json', content: '![still](/data/brain-imports/file-shared.png)' }]);
// Shared asset survives (another memory uses it); solo asset is removed.
expect(existsSync(join(ASSETS_DIR, 'file-shared.png'))).toBe(true);
expect(existsSync(join(ASSETS_DIR, 'file-solo.png'))).toBe(false);
});
+ it('keeps the archived transcript when a surviving memory shares its sourceRef (same export imported twice)', async () => {
+ await importConversations(parseExport([sampleConversation()])); // writes conv-1.json archive
+ expect(existsSync(join(TMP, 'imports', 'chatgpt', 'conv-1.json'))).toBe(true);
+
+ await deleteMemoryAssets({
+ id: 'mem-1',
+ source: 'chatgpt-import',
+ sourceRef: 'conv-1.json',
+ content: '',
+ }, [{ id: 'mem-2', source: 'chatgpt-import', sourceRef: 'conv-1.json', content: '' }]);
+
+ // A duplicate import points at the same archive — it must survive so the
+ // surviving memory's "View full conversation" still resolves.
+ expect(existsSync(join(TMP, 'imports', 'chatgpt', 'conv-1.json'))).toBe(true);
+ });
+
it('is a no-op for non-import memories', async () => {
await writeAsset('file-keep.png');
await deleteMemoryAssets({