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: upsert ChatGPT import memories by conversation id, keep earlier assets on failed re-import (#8452)

[._.]/ Adam Eivy24cc8b62221f
diff --git a/client/src/components/brain/tabs/ImportTab.jsx b/client/src/components/brain/tabs/ImportTab.jsx
index ea4b612426..bf539d6be3 100644
--- a/client/src/components/brain/tabs/ImportTab.jsx
+++ b/client/src/components/brain/tabs/ImportTab.jsx
@@ -568,7 +568,10 @@ function StepDone({ result, onExit, navigate }) {
<CheckCircle2 size={48} className="text-port-success mx-auto mb-3" aria-hidden="true" />
<h3 className="text-lg font-semibold text-white">Import complete</h3>
<p className="text-sm text-gray-400 mt-1">
- {result.imported} imported · {result.skipped} skipped · {result.archived} archived
+ {result.imported} imported
+ {result.updated ? ` · ${result.updated} updated` : ''}
+ {result.unchanged ? ` · ${result.unchanged} unchanged` : ''}
+ {' '}· {result.skipped} skipped · {result.archived} archived
{result.assetStats?.assetCount ? ` · ${result.assetStats.assetCount} assets` : ''}
</p>
</div>
@@ -594,9 +597,9 @@ function StepDone({ result, onExit, navigate }) {
{result.results.map((r, i) => (
<li key={r.id || i} className="px-2 py-1 flex items-center justify-between gap-2">
<span className="truncate text-gray-300">{r.title || '(untitled)'}</span>
- <span className={r.status === 'imported' ? 'text-port-success' : 'text-gray-500'}>
- {r.status === 'imported'
- ? `${r.messageCount} msg${r.assetCount ? ` · ${r.assetCount} assets` : ''}`
+ <span className={r.status === 'imported' || r.status === 'updated' ? 'text-port-success' : 'text-gray-500'}>
+ {r.status === 'imported' || r.status === 'updated'
+ ? `${r.status} · ${r.messageCount} msg${r.assetCount ? ` · ${r.assetCount} assets` : ''}`
: r.reason || r.status}
</span>
</li>
diff --git a/server/routes/brainImport.js b/server/routes/brainImport.js
index 352626dd90..46060f2c3e 100644
--- a/server/routes/brainImport.js
+++ b/server/routes/brainImport.js
@@ -76,7 +76,7 @@ router.post('/chatgpt', asyncHandler(async (req, res) => {
}
console.log(`📥 ChatGPT import start: ${parsed.summary.totalConversations} conversations`);
const result = await importConversations(parsed, { tags, skipEmpty });
- console.log(`✅ ChatGPT import complete: imported=${result.imported} skipped=${result.skipped} archived=${result.archived}`);
+ console.log(`✅ ChatGPT import complete: imported=${result.imported} updated=${result.updated} unchanged=${result.unchanged} skipped=${result.skipped} archived=${result.archived}`);
res.json(result);
}));
@@ -112,7 +112,7 @@ router.post('/chatgpt/zip', uploadZip, asyncHandler(async (req, res) => {
if (!result.ok) {
throw new ServerError(result.error, { status: 400, code: 'INVALID_CHATGPT_EXPORT' });
}
- console.log(`✅ ChatGPT ZIP import complete: imported=${result.imported} skipped=${result.skipped} assets=${result.assetStats?.assetCount}`);
+ console.log(`✅ ChatGPT ZIP import complete: imported=${result.imported} updated=${result.updated} unchanged=${result.unchanged} skipped=${result.skipped} assets=${result.assetStats?.assetCount}`);
res.json(result);
} finally {
await unlink(filePath).catch(() => {});
diff --git a/server/services/chatgptImport.js b/server/services/chatgptImport.js
index 34507164b7..53448debc5 100644
--- a/server/services/chatgptImport.js
+++ b/server/services/chatgptImport.js
@@ -22,8 +22,8 @@
import { join } from 'path';
import { stripChatgptCitations } from '../lib/chatgptText.js';
import { unlink } from 'fs/promises';
-import { atomicWrite, ensureDir, PATHS, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
-import { createMemoryEntry } from './brainStorage.js';
+import { atomicWrite, ensureDir, PATHS, tryReadFile, safeJSONParse, safeDate } from '../lib/fileUtils.js';
+import { createMemoryEntry, updateMemoryEntry, query as queryBrain } from './brainStorage.js';
const MAX_MEMORY_CONTENT = 9800;
const MAX_TITLE_LEN = 200;
@@ -376,11 +376,11 @@ const assetNamesForMemory = async (record) => {
*
* `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`.
+ * - `importConversations` now upserts by conversation id, so re-importing
+ * the same export can no longer CREATE a second memory sharing an
+ * archive. Installs that imported the same export twice before that fix
+ * shipped can still hold such a pair, so the survivor check stays: 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 — compared via the FULL archived transcript, not the
@@ -425,17 +425,26 @@ export async function deleteMemoryAssets(record, survivors = []) {
if (orphaned.length) console.log(`🧠 Removed ${orphaned.length} orphaned import asset(s) for memory ${record.id}`);
}
+/**
+ * The archive filename (and therefore the `sourceRef` a Memory entry carries)
+ * for one conversation summary. Deterministic when `summary.id` is present —
+ * that's the ChatGPT-assigned conversation id, so re-importing the same
+ * export (or a newer export that overlaps it) resolves to the same name and
+ * `importConversations` can upsert instead of duplicating. A summary with no
+ * id (malformed export row) falls back to a timestamp, which is NOT stable
+ * across calls — such a conversation always imports as new.
+ */
+const conversationArchiveName = (summary) => `${safeFilename(summary.id || `conv-${Date.now()}`)}.json`;
+
/**
* Persist one conversation's full transcript + structured messages to the
* import archive directory.
*/
-async function archiveConversation(summary) {
+async function archiveConversation(summary, fname = conversationArchiveName(summary)) {
await ensureDir(importRoot());
- const id = summary.id || `conv-${Date.now()}`;
- const fname = `${safeFilename(id)}.json`;
const filePath = join(importRoot(), fname);
const payload = {
- id,
+ id: summary.id || `conv-${Date.now()}`,
title: summary.title,
createTime: summary.createTime,
updateTime: summary.updateTime,
@@ -483,8 +492,19 @@ export async function importConversations(parsed, options = {}) {
await ensureDir(importRoot());
+ // Upsert by conversation id (sourceRef == archive filename), keyed BEFORE the
+ // loop so a re-import of the same export — or a newer export overlapping
+ // it — updates the existing memory instead of creating a duplicate. See
+ // `conversationArchiveName` for why a summary with no id can't be matched.
+ const existingBySourceRef = new Map();
+ for (const memory of await queryBrain('memories', { source: 'chatgpt-import' })) {
+ if (memory.sourceRef) existingBySourceRef.set(memory.sourceRef, memory);
+ }
+
const results = [];
let imported = 0;
+ let updated = 0;
+ let unchanged = 0;
let skipped = 0;
let archived = 0;
@@ -495,7 +515,26 @@ export async function importConversations(parsed, options = {}) {
continue;
}
- const archiveName = await archiveConversation(summary);
+ const archiveName = conversationArchiveName(summary);
+ const existingMemory = existingBySourceRef.get(archiveName);
+ const isNewer = existingMemory
+ && safeDate(summary.updateTime) > safeDate(existingMemory.sourceUpdatedAt);
+
+ if (existingMemory && !isNewer) {
+ results.push({
+ id: summary.id,
+ memoryId: existingMemory.id,
+ title: summary.title,
+ messageCount: summary.messageCount,
+ assetCount: summary.assetCount,
+ archiveName,
+ status: 'unchanged'
+ });
+ unchanged += 1;
+ continue;
+ }
+
+ await archiveConversation(summary, archiveName);
archived += 1;
const tags = [
@@ -503,7 +542,7 @@ export async function importConversations(parsed, options = {}) {
summary.gizmoId ? sanitizeTag(`gizmo-${summary.gizmoId}`) : null
].filter(Boolean);
- const entry = await createMemoryEntry({
+ const memoryData = {
title: summary.title,
content: buildContent(summary),
tags,
@@ -514,7 +553,24 @@ export async function importConversations(parsed, options = {}) {
// shared bulk-import timestamp. See `memoryRecencyMs` in brainStorage.js.
sourceCreatedAt: summary.createTime || null,
sourceUpdatedAt: summary.updateTime || null
- });
+ };
+
+ if (existingMemory) {
+ const entry = await updateMemoryEntry(existingMemory.id, memoryData);
+ results.push({
+ id: summary.id,
+ memoryId: entry.id,
+ title: summary.title,
+ messageCount: summary.messageCount,
+ assetCount: summary.assetCount,
+ archiveName,
+ status: 'updated'
+ });
+ updated += 1;
+ continue;
+ }
+
+ const entry = await createMemoryEntry(memoryData);
results.push({
id: summary.id,
@@ -531,6 +587,8 @@ export async function importConversations(parsed, options = {}) {
return {
ok: true,
imported,
+ updated,
+ unchanged,
skipped,
archived,
archiveDir: importRoot(),
diff --git a/server/services/chatgptImport.test.js b/server/services/chatgptImport.test.js
index ae59cd0c82..a67b819f69 100644
--- a/server/services/chatgptImport.test.js
+++ b/server/services/chatgptImport.test.js
@@ -9,6 +9,9 @@ import { join } from 'path';
// fresh per-test TMP before chatgptImport.js is (re-)loaded.
let TMP;
let createMemoryEntryMock;
+let updateMemoryEntryMock;
+let queryMock;
+let memoryStore;
let parseExport;
let importConversations;
@@ -29,8 +32,25 @@ describe('chatgptImport service', () => {
const actual = await vi.importActual('../lib/fileUtils.js');
return { ...actual, PATHS: { ...actual.PATHS, brain: TMP, brainImportAssets: ASSETS_DIR } };
});
+ // In-memory `memories` collection backing create/update/query, so
+ // `importConversations`' upsert-by-sourceRef lookup sees prior calls in the
+ // same test the way the real store would.
+ memoryStore = new Map();
vi.doMock('./brainStorage.js', () => ({
- createMemoryEntry: vi.fn(async (data) => ({ id: `mem-${Math.random().toString(36).slice(2, 8)}`, ...data }))
+ createMemoryEntry: vi.fn(async (data) => {
+ const id = `mem-${Math.random().toString(36).slice(2, 8)}`;
+ const record = { id, ...data };
+ memoryStore.set(id, record);
+ return record;
+ }),
+ updateMemoryEntry: vi.fn(async (id, data) => {
+ const record = { ...memoryStore.get(id), ...data, id };
+ memoryStore.set(id, record);
+ return record;
+ }),
+ query: vi.fn(async (_type, filters = {}) => [...memoryStore.values()].filter(
+ (record) => Object.entries(filters).every(([key, value]) => record[key] === value)
+ ))
}));
const mod = await import('./chatgptImport.js');
parseExport = mod.parseExport;
@@ -42,6 +62,8 @@ describe('chatgptImport service', () => {
extractAssetFileNames = mod.__test.extractAssetFileNames;
const storage = await import('./brainStorage.js');
createMemoryEntryMock = storage.createMemoryEntry;
+ updateMemoryEntryMock = storage.updateMemoryEntry;
+ queryMock = storage.query;
});
afterEach(async () => {
@@ -252,6 +274,45 @@ describe('chatgptImport service', () => {
expect(content.length).toBeLessThan(10000);
expect(content).toContain('truncated');
});
+
+ it('re-importing the same export upserts instead of duplicating (reports unchanged, no new memory)', async () => {
+ const parsed = parseExport([sampleConversation()]);
+ const first = await importConversations(parsed);
+ expect(first.imported).toBe(1);
+
+ const second = await importConversations(parseExport([sampleConversation()]));
+ expect(second.imported).toBe(0);
+ expect(second.updated).toBe(0);
+ expect(second.unchanged).toBe(1);
+ expect(second.results[0].status).toBe('unchanged');
+ expect(second.results[0].memoryId).toBe(first.results[0].memoryId);
+ // No duplicate memory was created — same id, still exactly one record.
+ expect(createMemoryEntryMock).toHaveBeenCalledTimes(1);
+ expect(queryMock).toHaveBeenCalled();
+ });
+
+ it('re-importing with a newer update_time updates the existing memory in place (same id)', async () => {
+ const first = await importConversations(parseExport([sampleConversation()]));
+ const memoryId = first.results[0].memoryId;
+
+ const newer = sampleConversation({ update_time: 1800000000 });
+ newer.mapping.n2.message.content.parts = ['4, revised'];
+ const second = await importConversations(parseExport([newer]));
+
+ expect(second.imported).toBe(0);
+ expect(second.updated).toBe(1);
+ expect(second.unchanged).toBe(0);
+ expect(second.results[0].status).toBe('updated');
+ expect(second.results[0].memoryId).toBe(memoryId);
+ expect(createMemoryEntryMock).toHaveBeenCalledTimes(1);
+ expect(updateMemoryEntryMock).toHaveBeenCalledTimes(1);
+ const updatedContent = updateMemoryEntryMock.mock.calls[0][1].content;
+ expect(updatedContent).toContain('4, revised');
+
+ // The archive on disk reflects the newer transcript, not the original.
+ const archived = await readArchivedConversation('conv-1.json');
+ expect(archived.transcript).toContain('4, revised');
+ });
});
describe('formatTranscript', () => {
diff --git a/server/services/chatgptZipImport.js b/server/services/chatgptZipImport.js
index 090bb2331d..e8d1fffd59 100644
--- a/server/services/chatgptZipImport.js
+++ b/server/services/chatgptZipImport.js
@@ -30,7 +30,7 @@
*/
import { createReadStream } from 'fs';
-import { rename } from 'fs/promises';
+import { rename, lstat } from 'fs/promises';
import { join } from 'path';
import { Writable } from 'stream';
import { PATHS, getMimeType, ensureDir, createWriteStreamGuarded, unlinkGuarded } from '../lib/fileUtils.js';
@@ -334,6 +334,25 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportA
continue;
}
const filePath = join(assetDir, fileName);
+ // Asset ids are content ids (ChatGPT reuses the same file-service id for
+ // the same bytes), so a file already at this name belongs to an earlier
+ // successful import — keep it rather than overwriting, and mark
+ // `created: false` so a later failure in THIS run's cleanup path never
+ // deletes a file THIS run didn't write.
+ // eslint-disable-next-line no-await-in-loop -- same sequential loop
+ const alreadyExists = await lstat(filePath).then(() => true, () => false);
+ if (alreadyExists) {
+ // eslint-disable-next-line no-await-in-loop -- same sequential loop
+ await unlinkGuarded(tempPath).catch(() => {});
+ assets.set(assetId, {
+ url: `/data/brain-imports/${fileName}`,
+ name: friendlyName || fileName,
+ mime: getMimeType(ext),
+ file: fileName,
+ created: false,
+ });
+ continue;
+ }
// eslint-disable-next-line no-await-in-loop -- sequential rename keeps peak
// disk/IO bounded; an export has a few hundred assets, not millions.
await rename(tempPath, filePath);
@@ -342,6 +361,7 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportA
name: friendlyName || fileName,
mime: getMimeType(ext),
file: fileName,
+ created: true,
});
}
} catch (err) {
@@ -393,14 +413,25 @@ export function makeAssetResolver(assets) {
};
}
-// Remove the asset files extractChatgptZip() wrote to the served dir. Called on
+// Remove the asset files THIS extraction run wrote to the served dir. Called on
// any FAILED import path: extraction writes assets to `/data/brain-imports/`
// before conversations are validated, so a ZIP with assets but no valid
// conversation shards (corrupt/wrong upload) would otherwise leave orphaned
// served files behind, and repeated bad uploads could fill the disk.
+//
+// Only unlinks entries with `created: true`. An asset id can recur across
+// separate imports (ChatGPT reuses a `file-service://` id for the same
+// bytes) — when the rename step above found the file already on disk, it
+// kept the earlier import's copy and marked `created: false`; deleting it
+// here on a LATER failure in this run would strand that earlier import's
+// memory with a broken image/audio link, which is exactly the data loss this
+// guards against. `created` defaults true for callers/fixtures built before
+// this distinction existed.
async function cleanupExtractedAssets(assets, assetDir = PATHS.brainImportAssets) {
await Promise.all(
- [...assets.values()].map((a) => unlinkGuarded(`${assetDir}/${a.file}`).catch(() => {}))
+ [...assets.values()]
+ .filter((a) => a.created !== false)
+ .map((a) => unlinkGuarded(`${assetDir}/${a.file}`).catch(() => {}))
);
}
diff --git a/server/services/chatgptZipImport.test.js b/server/services/chatgptZipImport.test.js
index 8ff5559cd1..53cabc2ad3 100644
--- a/server/services/chatgptZipImport.test.js
+++ b/server/services/chatgptZipImport.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtemp, rm, writeFile, readdir, readFile } from 'fs/promises';
+import { mkdtemp, rm, writeFile, readdir, readFile, mkdir } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -293,6 +293,60 @@ describe('chatgptZipImport service', () => {
const written = await readdir(assetDir).catch(() => []);
expect(written).toEqual([]);
});
+
+ it('marks a freshly-written asset created:true', async () => {
+ const assetDir = join(TMP, 'assets');
+ const zipPath = await writeZip([
+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],
+ ['file-IMG.dat', PNG],
+ ]);
+ const { assets } = await extractChatgptZip(zipPath, { assetDir });
+ expect(assets.get('file-IMG').created).toBe(true);
+ });
+
+ it('keeps (does not overwrite) an asset an earlier import already wrote, and marks it created:false', async () => {
+ // Asset ids are content ids — the same `file-service://` id recurs across
+ // separate exports of overlapping conversations. Simulate a prior
+ // successful import having already written the served file.
+ const assetDir = join(TMP, 'assets');
+ await mkdir(assetDir, { recursive: true });
+ await writeFile(join(assetDir, 'file-IMG.png'), 'earlier-import-bytes');
+
+ const zipPath = await writeZip([
+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],
+ ['file-IMG.dat', PNG],
+ ]);
+ const { assets } = await extractChatgptZip(zipPath, { assetDir });
+
+ expect(assets.get('file-IMG').created).toBe(false);
+ // The earlier import's bytes were left untouched, not overwritten by the
+ // (different) bytes this run streamed.
+ expect((await readFile(join(assetDir, 'file-IMG.png'), 'utf8'))).toBe('earlier-import-bytes');
+ });
+
+ it('a later failure in the SAME run never deletes an asset an EARLIER import owns (the reported data-loss bug)', async () => {
+ // Reproduces the issue: import #1 succeeds and writes file-IMG.png. A
+ // re-upload (import #2) reuses the same asset id but has a truncated
+ // conversations shard, so it fails after extraction. The cleanup path
+ // must remove nothing it didn't create — file-IMG.png must survive.
+ const assetDir = join(TMP, 'assets');
+ const firstZip = await writeZip([
+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],
+ ['file-IMG.dat', PNG],
+ ]);
+ await extractChatgptZip(firstZip, { assetDir });
+ expect(await readdir(assetDir)).toEqual(['file-IMG.png']);
+
+ const secondZip = await writeZip([
+ ['conversations-000.json', '[{ "id": "c1", "title": "A", "mapping": {} '], // truncated → throws
+ ['file-IMG.dat', PNG],
+ ]);
+ await expect(extractChatgptZip(secondZip, { assetDir }))
+ .rejects.toMatchObject({ status: 400, code: 'INVALID_CHATGPT_EXPORT' });
+
+ // Import #1's asset survives the failed re-import's cleanup.
+ expect(await readdir(assetDir)).toEqual(['file-IMG.png']);
+ });
});
describe('makeAssetResolver', () => {
@@ -320,7 +374,9 @@ describe('chatgptZipImport service', () => {
});
const created = [];
vi.doMock('./brainStorage.js', () => ({
- createMemoryEntry: vi.fn(async (d) => { created.push(d); return { id: `mem-${created.length}`, ...d }; })
+ createMemoryEntry: vi.fn(async (d) => { created.push(d); return { id: `mem-${created.length}`, ...d }; }),
+ updateMemoryEntry: vi.fn(async (id, d) => ({ id, ...d })),
+ query: vi.fn(async () => [])
}));
const { importChatgptZip: run } = await import('./chatgptZipImport.js');