Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
fix(import): retain the destination of renamed export projects (#6706)
ZedingZhang97d9a9e87b64
diff --git a/src/services/history-import/cli.ts b/src/services/history-import/cli.tsindex fd222895c..dbe7737d4 100644--- a/src/services/history-import/cli.ts+++ b/src/services/history-import/cli.ts@@ -88,7 +88,7 @@ export async function runHistoricalChatImport(args: string[]): Promise<void> {}));}}- });+ }, excluded);console.log(`${result.stored} new observations, ${result.existing} previously processed turns, ${result.skipped} turns without a new observation; ${result.calls} model calls.`);if (result.unverified) {console.log(`Partial import. ${result.unverified} turns lacked a verified observation and remain retryable. Rerun with --model NAME to fill the gaps with another installed local chat model.`);diff --git a/src/services/history-import/content-id.ts b/src/services/history-import/content-id.tsnew file mode 100644index 000000000..400eb83e7--- /dev/null+++ b/src/services/history-import/content-id.ts@@ -0,0 +1,14 @@+import { createHash } from 'node:crypto';++/**+ * The local session identity of one imported export group. Its rows carry this+ * as `memory_session_id`, or this plus `-<deletedAt>` after a session deletion.+ */+export function historyContentId(source: string, conversationId: string, projectId: string | null, project: string): string {+ return 'history-' + createHash('sha256').update(JSON.stringify([source, conversationId, projectId, project])).digest('hex');+}++/** True when `memorySessionId` was written for the group identified by `contentId`. */+export function isHistoryMemorySessionOf(contentId: string, memorySessionId: string): boolean {+ return memorySessionId === contentId || memorySessionId.startsWith(contentId + '-');+}diff --git a/src/services/history-import/replay.ts b/src/services/history-import/replay.tsindex 47eaa37aa..a751b1d83 100644--- a/src/services/history-import/replay.ts+++ b/src/services/history-import/replay.ts@@ -4,6 +4,7 @@ import {decodeXmlReferences, hasUnfinishedObservationBlock, maskXmlLiteralMarkup, OBSERVATION_BLOCK,SKIP_SUMMARY_TAG, stripCodeFences, type ParsedObservation,} from '../../sdk/parser.js';+import { isProjectExcluded } from '../../utils/project-filter.js';import { stripMemoryTags } from '../../utils/tag-stripping.js';import type { ModeConfig } from '../domain/types.js';import type { HistoricalChat, HistoricalMessage } from './sources.js';@@ -23,6 +24,7 @@ export interface ReplayUnit {export interface ReplayReceipt { ids: number[]; titles: string[]; existing?: boolean }interface ReplayStore {+ exportProject(chat: HistoricalChat, verifyUnboundReceipts: () => void): string;lookup(key: string, sourceDigest: string): ReplayReceipt | undefined;commit(unit: ReplayUnit, observations: ParsedObservation[], model: string): ReplayReceipt;}@@ -195,14 +197,23 @@ export function observationsFromReply(reply: string, currentText: string, role:}+function replayUnit(chat: HistoricalChat, project: string, message: HistoricalMessage, text: string): ReplayUnit {+ return {+ key: hash([chat.source, chat.id, message.id]), source: chat.source, conversationId: chat.id,+ messageId: message.id, project, projectId: chat.projectId, projectOrigin: chat.projectOrigin,+ at: message.timestampMs, sourceDigest: hash([project, chat.projectId ?? null, message.role, message.timestampMs, text]),+ };+}+/** Per-conversation reconstruction boundary: preceding turns and completed memories, then the one new event. */export async function replayHistoricalChats(chats: HistoricalChat[], store: ReplayStore,observerForRun: () => Promise<ChatObserver>, mode: ModeConfig, limit: number,- report: (unit: ReplayUnit, receipt: ReplayReceipt) => void) {+ report: (unit: ReplayUnit, receipt: ReplayReceipt) => void, excludedProjects = '') {const system = historicalObserverInstructions(mode);let observer: ChatObserver | undefined;let turnNumber = 0;let calls = 0, stored = 0, existing = 0, skipped = 0, unverified = 0;+ const projects = new Map<HistoricalChat, string>();for (const turns of chronologicalConversations(chats)) {const previous: Array<{role: string; at: string; text: string}> = [];const remembered: string[] = [];@@ -210,11 +221,18 @@ export async function replayHistoricalChats(chats: HistoricalChat[], store: ReplturnNumber++;const text = stripMemoryTags(message.text);if (!text.trim()) { skipped++; continue; }- const unit: ReplayUnit = {- key: hash([chat.source, chat.id, message.id]), source: chat.source, conversationId: chat.id,- messageId: message.id, project: chat.project, projectId: chat.projectId, projectOrigin: chat.projectOrigin,- at: message.timestampMs, sourceDigest: hash([chat.project, chat.projectId ?? null, message.role, message.timestampMs, text]),- };+ let project = projects.get(chat);+ if (project === undefined) {+ project = store.exportProject(chat, () => {+ for (const prior of chat.messages) {+ const candidate = replayUnit(chat, chat.project, prior, stripMemoryTags(prior.text));+ store.lookup(candidate.key, candidate.sourceDigest);+ }+ });+ projects.set(chat, project);+ }+ if (project !== chat.project && isProjectExcluded(project, excludedProjects)) { skipped++; continue; }+ const unit = replayUnit(chat, project, message, text);// Prompt budget (see NUM_CTX in local-observer.ts): 8,000 characters of the current turn, 1,200 of each// of the 4 previous turns, and the 8 latest remembered titles. truncatePromptText marks what it elides.const event = { role: message.role, at: new Date(unit.at).toISOString(), text: truncatePromptText(text, CURRENT_TURN_CHARS) };diff --git a/src/services/history-import/store.ts b/src/services/history-import/store.tsindex a7d7d063b..9ef22b0ca 100644--- a/src/services/history-import/store.ts+++ b/src/services/history-import/store.ts@@ -1,8 +1,9 @@-import { createHash } from 'node:crypto';import type { ParsedObservation } from '../../sdk/parser.js';import { normalizePlatformSource } from '../../shared/platform-source.js';import type { SessionStore } from '../sqlite/SessionStore.js';import { hasStorableTitle } from '../sqlite/observations/store.js';+import type { HistoricalChat } from './chat-shape.js';+import { historyContentId } from './content-id.js';import type { ReplayReceipt, ReplayUnit } from './replay.js';type DatedSource = Pick<ReplayUnit, 'key' | 'source' | 'conversationId' | 'messageId' | 'project' | 'projectId' | 'projectOrigin' | 'at' | 'sourceDigest'>;@@ -13,6 +14,32 @@ export class HistoryReplayStore {// The history_replay_receipts table is SessionStore migration v76.constructor(private readonly store: SessionStore) {}+ /** Resolve once per export group. Competing imports must agree on its first local destination. */+ exportProject(chat: HistoricalChat, verifyUnboundReceipts: () => void): string {+ if (!chat.projectId || (chat.source !== 'claude' && chat.source !== 'chatgpt')) return chat.project;+ const key = [chat.source, chat.id, chat.projectId] as const;+ const read = () => this.store.db.query<{ project: string }, [string, string, string]>(+ 'SELECT project FROM history_replay_projects WHERE provider = ? AND conversation_id = ? AND project_id = ?'+ ).get(...key)?.project;+ const existing = read();+ if (existing !== undefined) return existing;+ // An old receipt can outlive all its observations. Before claiming a name for+ // that group, verify it against any overlapping receipts. Use a read snapshot+ // for the preflight so hashing a long export never holds the SQLite writer lock.+ const verified = this.store.db.transaction(() => {+ const bound = read();+ if (bound === undefined && this.store.db.query('SELECT 1 FROM history_replay_receipts LIMIT 1').get()) {+ verifyUnboundReceipts();+ }+ return bound;+ })();+ if (verified !== undefined) return verified;+ return this.store.db.transaction(() => {+ this.store.db.query('INSERT OR IGNORE INTO history_replay_projects VALUES (?, ?, ?, ?)').run(...key, chat.project);+ return read()!;+ }).immediate();+ }+lookup(key: string, sourceDigest?: string): ReplayReceipt | undefined {const row = this.store.db.query<ReceiptRow, [string]>('SELECT source_digest, observation_ids FROM history_replay_receipts WHERE source_key = ?'@@ -40,9 +67,7 @@ export class HistoryReplayStore {}const platform = normalizePlatformSource(unit.source);- const contentId = 'history-' + createHash('sha256').update(JSON.stringify([- unit.source, unit.conversationId, unit.projectId ?? null, unit.project,- ])).digest('hex');+ const contentId = historyContentId(unit.source, unit.conversationId, unit.projectId ?? null, unit.project);const deletedAt = this.store.getSessionDeletedAtEpochMs(platform, contentId);let ids: number[] = [];if (observations.length && (deletedAt === null || unit.at > deletedAt)) {diff --git a/src/services/sqlite/SessionStore.ts b/src/services/sqlite/SessionStore.tsindex 4e18b2fd1..6fa92b468 100644--- a/src/services/sqlite/SessionStore.ts+++ b/src/services/sqlite/SessionStore.ts@@ -3,6 +3,7 @@ import { Database, type SQLQueryBindings, type Statement } from 'bun:sqlite';import { createHash, randomUUID } from 'crypto';import { DATA_DIR, DB_PATH, ensurePrivateDir, OBSERVER_SESSIONS_PROJECT, USER_SETTINGS_PATH } from '../../shared/paths.js';import { logger } from '../../utils/logger.js';+import { historyContentId, isHistoryMemorySessionOf } from '../history-import/content-id.js';import type { ProjectKeySource } from '../../utils/project-name.js';import type { ProjectExclusionCatalog } from '../../shared/project-list.js';import { projectReadKeys, projectScopeSql, scopedProjects } from './project-read-keys.js';@@ -376,6 +377,7 @@ export class SessionStore {this.ensureObservationFileIndex();this.ensureHistoryReplayReceiptsTable();this.ensurePrivatePromptTurnsTable();+ this.ensureHistoryReplayProjects();ensureMediaSchema(this.db);}@@ -393,6 +395,49 @@ export class SessionStore {this.db.prepare('INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)').run(76, new Date().toISOString());}+ /** v78: pin the local destination of an exported project across catalog renames. */+ private ensureHistoryReplayProjects(): void {+ if (this.db.query('SELECT 1 FROM schema_versions WHERE version = 78').get()) return;+ this.db.transaction(() => {+ this.db.run(`CREATE TABLE IF NOT EXISTS history_replay_projects (+ provider TEXT NOT NULL, conversation_id TEXT NOT NULL, project_id TEXT NOT NULL, project TEXT NOT NULL,+ PRIMARY KEY (provider, conversation_id, project_id)+ ) WITHOUT ROWID`);+ // Recover the original destination from observations still owned by a v76 receipt.+ // A row's project can be renamed after import, so a name counts only when it+ // reproduces the row's session identity. Skips, deletions or a remap can leave no+ // proof of the former name; such a group stays unbound and is verified on import.+ const rows = this.db.query<{+ provider: string; conversation_id: string; project_id: string; project: string; memory_session_id: string | null;+ }, []>(`SELECT o.metadata ->> '$.importSource.provider' AS provider,+ o.metadata ->> '$.importSource.conversationId' AS conversation_id,+ o.metadata ->> '$.importSource.projectId' AS project_id,+ o.project, o.memory_session_id+ FROM history_replay_receipts r+ JOIN json_each(r.observation_ids) ids+ JOIN observations o ON o.id = ids.value+ WHERE CASE WHEN json_valid(o.metadata) THEN o.metadata ->> '$.sourceFingerprint' END = 'history:' || r.source_key+ AND o.metadata ->> '$.importSource.provider' IN ('claude', 'chatgpt')+ AND o.metadata ->> '$.importSource.projectId' IS NOT NULL`).all();+ const groups = new Map<string, { key: [string, string, string]; names: Set<string | null> }>();+ for (const row of rows) {+ const key: [string, string, string] = [row.provider, row.conversation_id, row.project_id];+ const id = JSON.stringify(key);+ const group = groups.get(id) ?? { key, names: new Set() };+ groups.set(id, group);+ const proven = row.memory_session_id !== null && isHistoryMemorySessionOf(+ historyContentId(row.provider, row.conversation_id, row.project_id, row.project), row.memory_session_id);+ group.names.add(proven ? row.project : null);+ }+ const bind = this.db.prepare('INSERT OR IGNORE INTO history_replay_projects VALUES (?, ?, ?, ?)');+ for (const { key, names } of groups.values()) {+ const [name] = names;+ if (names.size === 1 && name !== null) bind.run(...key, name);+ }+ this.db.prepare('INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)').run(78, new Date().toISOString());+ }).immediate();+ }+/*** v77: the numbering anchor for a fully-private turn. A turn whose whole* prompt is private saves no `user_prompts` row — every reader of thatdiff --git a/src/services/sqlite/connection.ts b/src/services/sqlite/connection.tsindex 22b015797..cc731a69f 100644--- a/src/services/sqlite/connection.ts+++ b/src/services/sqlite/connection.ts@@ -16,7 +16,7 @@ export const SQLITE_JOURNAL_SIZE_LIMIT_BYTES = 4194304;* can't land without it. Kept in this leaf module — both SessionStore and* SessionSearch already import from here, and they import each other.*/-export const LATEST_SCHEMA_VERSION = 77;+export const LATEST_SCHEMA_VERSION = 78;export function readSchemaWriterStamp(db: Database): number {const statement = db.prepare('PRAGMA user_version');diff --git a/tests/services/history-import/project-rename.test.ts b/tests/services/history-import/project-rename.test.tsnew file mode 100644index 000000000..52fb6ec93--- /dev/null+++ b/tests/services/history-import/project-rename.test.ts@@ -0,0 +1,100 @@+import { expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { ModeConfig } from '../../../src/services/domain/types.js';+import { replayHistoricalChats } from '../../../src/services/history-import/replay.js';+import type { HistoricalChat } from '../../../src/services/history-import/sources.js';+import { HistoryReplayStore } from '../../../src/services/history-import/store.js';+import { SessionStore } from '../../../src/services/sqlite/SessionStore.js';++const mode: ModeConfig = JSON.parse(readFileSync(new URL('../../../plugin/modes/code.json', import.meta.url), 'utf8'));+const first = 'The release will use the new database format.';+const second = 'The team will validate the migration on Friday.';++function replay(sessions: SessionStore, project: string, texts: string[], projectId = 'p1', excludedProjects = '') {+ const chat: HistoricalChat = { source: 'claude', id: 'c1', project, projectId, projectOrigin: 'export',+ messages: texts.map((text, i) => ({ id: String(i), timestampMs: 1000 + i, role: 'user', text })) };+ return replayHistoricalChats([chat], new HistoryReplayStore(sessions), async () => ({+ model: 'test', async observe(_system, evidence) {+ const passage = JSON.parse(evidence).current.passages[0];+ return `<observation><source_id>${passage.id}</source_id><type>discovery</type></observation>`;+ },+ }), mode, Infinity, () => {}, excludedProjects);+}++for (const legacy of [false, true]) {+ test(`resumes into the original project after a catalog rename (v77 upgrade: ${legacy})`, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'cmem-project-rename-'));+ const path = join(dir, 'history.db');+ let store = new SessionStore(path);+ try {+ expect((await replay(store, 'Alpha', [first])).stored).toBe(1);+ const initial = store.db.query('SELECT id, memory_session_id, project FROM observations').get();+ if (legacy) {+ store.db.exec('DROP TABLE IF EXISTS history_replay_projects; DELETE FROM schema_versions WHERE version = 78; PRAGMA user_version = 77');+ }+ store.close();+ store = new SessionStore(path);+ expect(await replay(store, 'Beta', [first, second])).toMatchObject({ existing: 1, stored: 1, calls: 1 });+ const rows = store.db.query('SELECT id, memory_session_id, project FROM observations ORDER BY id').all();+ expect(rows).toHaveLength(2);+ expect(rows[0]).toEqual(initial);+ expect(rows[1]).toMatchObject({ memory_session_id: (initial as {memory_session_id: string}).memory_session_id, project: 'Alpha' });+ expect(await replay(store, 'Gamma', [first, second])).toMatchObject({ existing: 2, calls: 0 });+ await expect(replay(store, 'Beta', ['The previous decision was revised.'])).rejects.toThrow('changed');+ await expect(replay(store, 'Beta', [first], 'another-project')).rejects.toThrow('changed');+ } finally { store.close(); rmSync(dir, { recursive: true, force: true }); }+ });+}++test('an upgrade does not bind a group to a project renamed after import', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'cmem-project-remap-'));+ const path = join(dir, 'history.db');+ let store = new SessionStore(path);+ try {+ await replay(store, 'Alpha', [first]);+ store.db.run(`UPDATE observations SET project = 'Renamed'`);+ store.db.exec('DROP TABLE IF EXISTS history_replay_projects; DELETE FROM schema_versions WHERE version = 78; PRAGMA user_version = 77');+ store.close();+ store = new SessionStore(path);+ expect(store.db.query('SELECT COUNT(*) AS n FROM history_replay_projects').get()).toEqual({ n: 0 });+ expect(await replay(store, 'Alpha', [first, second])).toMatchObject({ existing: 1, stored: 1 });+ expect(store.db.query('SELECT project FROM history_replay_projects').all()).toEqual([{ project: 'Alpha' }]);+ } finally { store.close(); rmSync(dir, { recursive: true, force: true }); }+});++test('remembers the project when the first imported turn was a skip', async () => {+ const store = new SessionStore(':memory:');+ try {+ expect(await replay(store, 'Alpha', ['thanks'])).toMatchObject({ calls: 0, skipped: 1 });+ expect(await replay(store, 'Beta', ['thanks', second])).toMatchObject({ calls: 1, existing: 1, stored: 1 });+ } finally { store.close(); }+});++test('a retained destination still honors exclusions and the session deletion cutoff', async () => {+ const store = new SessionStore(':memory:');+ try {+ await replay(store, 'Alpha', [first]);+ expect(await replay(store, 'Beta', [first, second], 'p1', 'Alpha')).toMatchObject({ calls: 0, stored: 0 });+ const session = store.db.query<{ content_session_id: string; memory_session_id: string }, []>(+ 'SELECT content_session_id, memory_session_id FROM sdk_sessions'+ ).get()!;+ store.markSessionDeleted('claude', session.content_session_id, session.memory_session_id);+ store.db.run('DELETE FROM sdk_sessions');+ expect(await replay(store, 'Beta', [first, second])).toMatchObject({ stored: 0 });+ expect(store.db.query('SELECT COUNT(*) AS n FROM sdk_sessions').get()).toEqual({ n: 0 });+ } finally { store.close(); }+});++test('an unprovable legacy skip can still be resumed with the original catalog', async () => {+ const store = new SessionStore(':memory:');+ try {+ await replay(store, 'Alpha', ['thanks']);+ store.db.run('DELETE FROM history_replay_projects');+ await expect(replay(store, 'Beta', ['thanks', second])).rejects.toThrow('changed');+ expect(store.db.query('SELECT COUNT(*) AS n FROM history_replay_projects').get()).toEqual({ n: 0 });+ expect(await replay(store, 'Alpha', ['thanks', second])).toMatchObject({ calls: 1, existing: 1, stored: 1 });+ expect(await replay(store, 'Beta', ['thanks', second])).toMatchObject({ calls: 0, existing: 2 });+ } finally { store.close(); }+});