/** Local-first memory manager: .dsh/brain layout, spaces, projections and summaries. */ import { AsyncLocalStorage } from 'node:async_hooks'; import { mkdir, readFile, writeFile, rename, rm, cp, stat, readdir } from 'node:fs/promises'; import { existsSync, readFileSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; import { dirname, join, resolve } from 'node:path'; import { dshHome } from "../store.js"; import { JsonDocumentStore, JsonMemoryStore, containsSecret, localMemoryHash, withFileLock } from "./storage.js"; export function globalBrainRoot() { return resolve(dshHome(), 'brain'); } /** Resolve a user-supplied workspace to its project base, accepting both the project root and its .dsh/brain path. */ export function projectBaseOf(value) { const normalized = resolve(value); const brainSuffix = join('.dsh', 'brain'); return normalized.endsWith(brainSuffix) ? dirname(dirname(normalized)) : normalized; } export function projectBrainRoot(cwd = process.cwd()) { return join(projectBaseOf(cwd), '.dsh', 'brain'); } export function projectIdFor(root) { return 'project_' + localMemoryHash(resolve(root)).slice(0, 16); } async function atomicWrite(path, content) { await mkdir(dirname(path), { recursive: true }); const tmp = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp'; try { await writeFile(tmp, content, { encoding: 'utf8', mode: 0o600 }); await rename(tmp, path); } catch (error) { await rm(tmp, { force: true }).catch(() => { }); throw error; } } async function treeDigest(root) { const files = []; const walk = async (dir, prefix) => { for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { const rel = prefix === '' ? entry.name : prefix + '/' + entry.name; const full = join(dir, entry.name); if (entry.isDirectory()) { await walk(full, rel); continue; } if (entry.isFile()) files.push(rel + ':' + localMemoryHash((await readFile(full)).toString('base64'))); } }; await walk(root, ''); return localMemoryHash(files.sort().join('\n')); } async function readJson(path, fallback) { let text; try { text = await readFile(path, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return fallback; throw new Error(`local_memory_state_read_failed: ${path}: ${error instanceof Error ? error.message : String(error)}`); } try { return JSON.parse(text); } catch { throw new Error(`local_memory_state_corrupt: ${path}`); } } async function writeGitIgnore(projectBase) { const dsh = join(projectBase, '.dsh'); await mkdir(dsh, { recursive: true }); const path = join(dsh, '.gitignore'); let text = ''; try { text = await readFile(path, 'utf8'); } catch { } if (!/^brain\/?$/m.test(text)) { text = text.trimEnd() + (text === '' ? '' : '\n') + 'brain/\n'; await atomicWrite(path, text); } } export class LocalMemoryManager { cwdOf; defaultWorkspaceOf; settingsOf; workspaceContext = new AsyncLocalStorage(); workspaces = new Map(); fixedGlobalRoot; fixedProjectRoot; constructor(options = {}) { this.cwdOf = options.cwd ?? (() => process.cwd()); this.defaultWorkspaceOf = options.workspace; this.settingsOf = options.settings ?? (() => ({})); this.fixedGlobalRoot = options.globalRoot; this.fixedProjectRoot = options.projectRoot; } /** Bind one operation to a workspace; AsyncLocalStorage keeps concurrent sessions isolated. */ withWorkspace(workspace, job) { return this.workspaceContext.run(workspace, job); } workspacePath(workspace) { const value = workspace ?? this.workspaceContext.getStore() ?? this.defaultWorkspaceOf?.() ?? this.cwdOf(); return resolve(value); } projectRootFor(workspace) { return this.fixedProjectRoot ?? projectBrainRoot(this.workspacePath(workspace)); } projectBaseFor(workspace) { return projectBaseOf(this.workspacePath(workspace)); } get globalRoot() { return this.fixedGlobalRoot ?? globalBrainRoot(); } get projectRoot() { return this.projectRootFor(); } get globalStore() { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global'); } projectStoreFor(workspace) { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))); } async storeFor(scope, workspace) { if (scope === 'global') return this.globalStore; return this.ensureProject(workspace); } projectionDirtyPath() { return join(this.globalRoot, 'state', 'projection.json'); } async markProjectionDirty(error) { const marker = String(Date.now()) + '-' + randomUUID(); await atomicWrite(this.projectionDirtyPath(), JSON.stringify({ dirty: true, marker, ...(error === undefined ? {} : { lastError: error instanceof Error ? error.message : String(error) }), updatedAt: new Date().toISOString() }, null, 2) + '\n'); return marker; } async clearProjectionDirty(marker) { try { const state = JSON.parse(await readFile(this.projectionDirtyPath(), 'utf8')); if (state.marker === marker) await rm(this.projectionDirtyPath(), { force: true }); } catch { } } /** Retry a projection left dirty by a committed memory write. */ async repairProjectionsIfDirty() { if (!existsSync(this.projectionDirtyPath())) return false; try { await this.regenerateProjections(); return true; } catch { return false; } } async tryRegenerateProjections() { try { await this.regenerateProjections(); return { projectionPending: false }; } catch (error) { return { projectionPending: true, projectionError: error instanceof Error ? error.message : String(error) }; } } /** Idempotently create the global space and its runtime projections. */ async ensureGlobal() { return withFileLock(join(this.globalRoot, 'state', '.init.lock'), async () => { await mkdir(join(this.globalRoot, 'runtime'), { recursive: true }); await mkdir(join(this.globalRoot, 'spaces', 'global'), { recursive: true }); await mkdir(join(this.globalRoot, 'backups'), { recursive: true }); await mkdir(join(this.globalRoot, 'state'), { recursive: true }); const meta = await this.globalStore.init('全局记忆'); const spaceMarker = join(this.globalRoot, 'spaces', 'global', 'space.json'); if (!(await stat(spaceMarker).catch(() => undefined))) await atomicWrite(spaceMarker, JSON.stringify(meta, null, 2) + '\n'); const userPath = join(this.globalRoot, 'runtime', 'USER.md'); const memoryPath = join(this.globalRoot, 'runtime', 'MEMORY.md'); if (!(await stat(userPath).catch(() => undefined))) await atomicWrite(userPath, '# USER\n\n'); if (!(await stat(memoryPath).catch(() => undefined))) await atomicWrite(memoryPath, '# MEMORY\n\n'); const initPath = join(this.globalRoot, 'state', 'init.json'); if (!(await stat(initPath).catch(() => undefined))) await atomicWrite(initPath, JSON.stringify({ version: 1, globalReady: true, createdAt: new Date().toISOString() }, null, 2) + '\n'); await this.repairProjectionsIfDirty(); return meta; }); } /** First use in a project creates its .dsh/brain and a stable project space. */ async ensureProject(workspace) { await this.ensureGlobal(); const root = this.fixedProjectRoot ?? join(this.projectBaseFor(workspace), '.dsh', 'brain'); const base = projectBaseOf(root); const cached = this.workspaces.get(root); if (cached !== undefined) return cached.store; return withFileLock(join(root, '.init.lock'), async () => { const again = this.workspaces.get(root); if (again !== undefined) return again.store; const id = projectIdFor(root); await mkdir(join(root, 'documents'), { recursive: true }); await mkdir(join(root, 'state'), { recursive: true }); const store = new JsonMemoryStore(join(root, 'memory-space'), 'project', id); await store.init('项目记忆'); const documents = new JsonDocumentStore(join(root, 'documents')); await documents.init(); await writeGitIgnore(base); const mappingPath = join(this.globalRoot, 'state', 'projects.json'); await withFileLock(join(this.globalRoot, 'state', '.projects.lock'), async () => { const mapping = await readJson(mappingPath, {}); mapping[id] = { root, updatedAt: new Date().toISOString() }; await atomicWrite(mappingPath, JSON.stringify(mapping, null, 2) + '\n'); }); const state = { root, store, documents }; this.workspaces.set(root, state); return store; }); } /** Public alias used by callers that initialize explicit local memory. */ async initialize(workspace) { return this.ensure(workspace); } async ensure(workspace) { const global = await this.ensureGlobal(); const projectStore = await this.ensureProject(workspace); const project = await projectStore.spaceMeta(); return { global, project: project ?? { id: projectStore.spaceId, scope: 'project', name: '项目记忆', root: projectStore.root, createdAt: new Date().toISOString(), active: true } }; } /** Add one memory and regenerate the compact projections. */ async remember(input) { const workspace = this.workspacePath(); const scope = input.scope ?? 'project'; const store = await this.storeFor(scope, workspace); await this.markProjectionDirty(); const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) }); if (result.duplicate) return result; return { ...result, ...(await this.tryRegenerateProjections()) }; } async add(input) { return this.remember(input); } async read(id, workspace) { const globalRecord = await this.globalStore.read(id); if (globalRecord !== undefined) return globalRecord; return (await this.ensureProject(workspace)).read(id); } async collectHits(query, workspace, projectId) { const projectStore = await this.ensureProject(workspace); const globalHits = await this.globalStore.search(query, 1000); const projectHits = await projectStore.search(query, 1000); const scoped = [...projectHits, ...globalHits].filter(({ record }) => { if (projectId === undefined || projectId === '') return true; if (projectId === 'global') return record.scope === 'global'; return record.scope === 'project' && record.projectId === projectId; }); const seen = new Set(); return scoped.filter(({ record }) => { if (seen.has(record.id)) return false; seen.add(record.id); return true; }) .sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)); } async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) { const hits = await this.collectHits(query, workspace, projectId); const limit = Math.max(1, Math.min(100, Math.trunc(k))); return hits.slice(0, limit); } async search(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) { return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record); } async list(options = {}, workspace, projectId) { const projectStore = await this.ensureProject(workspace); const records = [...(await this.globalStore.records()), ...(await projectStore.records())]; const scoped = records.filter((record) => { if (projectId === undefined || projectId === '') return true; if (projectId === 'global') return record.scope === 'global'; return record.scope === 'project' && record.projectId === projectId; }); const seen = new Set(); const ordered = scoped.filter((record) => { if (seen.has(record.id)) return false; seen.add(record.id); return true; }) .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id)); const offset = Math.max(0, Math.trunc(options.offset ?? 0)); const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50))); return { items: ordered.slice(offset, offset + limit), total: ordered.length }; } async forget(id, expectedRevision, workspace) { const globalRecord = await this.globalStore.read(id); await this.markProjectionDirty(); if (globalRecord !== undefined) { const removed = await this.globalStore.forget(id, expectedRevision); await this.tryRegenerateProjections(); return removed; } const store = await this.ensureProject(workspace); const removed = await store.forget(id, expectedRevision); await this.tryRegenerateProjections(); return removed; } async projects(workspace) { const global = await this.globalStore.spaceMeta(); const root = this.projectRootFor(workspace); const project = await this.projectStoreFor(workspace).spaceMeta(); return [...(global === undefined ? [] : [{ id: 'global', name: '全局记忆' }]), { id: project?.id ?? projectIdFor(root), name: '项目记忆' }]; } async documents(workspace) { const root = this.projectRootFor(workspace); return new JsonDocumentStore(join(root, 'documents')).list(); } async addDocument(input, workspace) { const store = await this.ensureProject(workspace); void store; const root = this.projectRootFor(workspace); const documents = this.workspaces.get(root)?.documents; if (documents === undefined) throw new Error('local_documents_unavailable'); return documents.add(input); } async storageStatus(workspace) { const projectRoot = this.projectRootFor(workspace); const global = await this.globalStore.spaceMeta(); const project = await this.projectStoreFor(workspace).spaceMeta(); return { provider: 'local', globalRoot: this.globalRoot, projectRoot, spaces: { global: global ?? null, project: project ?? null }, cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false }; } /** Return the compact per-turn projection used by the system prompt. */ projectionText(limit = 2000) { const read = (path) => { try { return readFileSync(path, 'utf8').trim(); } catch { return ''; } }; const user = read(join(this.globalRoot, 'runtime', 'USER.md')); const memory = read(join(this.globalRoot, 'runtime', 'MEMORY.md')); if (user === '' && memory === '') return ''; const cut = (text) => text.length > limit ? text.slice(0, limit) + '\n…' : text; return ['## dsh-brain local memory', '### USER.md', cut(user || '(empty)'), '### MEMORY.md', cut(memory || '(empty)')].join('\n'); } /** Generate USER.md/MEMORY.md from explicit profile/rule records only. */ async regenerateProjections() { const marker = await this.markProjectionDirty(); await withFileLock(join(this.globalRoot, 'state', '.projection.lock'), async () => { try { const runtimeFile = join(this.globalRoot, 'runtime', 'memories.json'); const mirrorFile = join(this.globalRoot, 'spaces', 'global', 'memories.json'); const data = await readFile(runtimeFile, 'utf8').catch((error) => { if (error.code === 'ENOENT') return undefined; throw error; }); if (data !== undefined) await atomicWrite(mirrorFile, data); const records = await this.globalStore.records(); const user = records.filter((record) => record.category === 'preference' || record.category === 'identity'); const rules = records.filter((record) => record.category === 'rule'); const render = (title, items) => '# ' + title + '\n\n' + items.map((record) => '- ' + record.content.replace(/\n/g, ' ') + ' *(rev ' + String(record.revision) + ', ' + record.source + ')*').join('\n') + (items.length === 0 ? '' : '\n'); await atomicWrite(join(this.globalRoot, 'runtime', 'USER.md'), render('USER', user)); await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules)); await this.clearProjectionDirty(marker); } catch (error) { await this.markProjectionDirty(error); throw error; } }); } /** Incremental, privacy-preserving summary: only explicit text is stored. */ async summarizeConversation(input, workspace) { if (this.settingsOf().autoSummaryEnabled === false) return { stored: 0, duplicates: 0, skipped: true }; await this.ensureProject(workspace); await this.markProjectionDirty(); return withFileLock(join(this.globalRoot, 'state', '.sessions.lock'), async () => { const checkpointPath = join(this.globalRoot, 'state', 'sessions.json'); const checkpoints = await readJson(checkpointPath, {}); const prior = checkpoints[input.sessionId]; const processed = new Set(prior?.processed ?? []); const fresh = input.turns.filter((turn) => turn.turnId === undefined || !processed.has(turn.turnId)); let stored = 0; let duplicates = 0; for (const turn of fresh) { const user = (turn.user ?? '').trim(); if (user === '' || containsSecret(user)) continue; for (const sentence of user.split(/[\n。!?!?]/).map((item) => item.trim()).filter((item) => item !== '')) { if (/(这次|本次|今天|暂时|临时|只此一次|一次性)/.test(sentence)) continue; if (!/(记住|长期|以后|今后|往后|每次|永远|始终|总是|从来不|我一向|我(?:喜欢|偏好|习惯|希望|要求)|规则|偏好|习惯|from now on|remember|prefer)/i.test(sentence)) continue; const category = /(总是|始终|必须|不要|别|规则|要求|always|never|must)/i.test(sentence) ? 'rule' : 'preference'; if (category === 'preference' && this.settingsOf().autoProfileEnabled === false) continue; const result = await this.globalStore.add({ content: sentence, category, source: 'session:' + input.sessionId, sessionId: input.sessionId, tags: ['auto-summary'] }); if (result.duplicate) duplicates += 1; else stored += 1; } } const nextCount = (prior?.count ?? 0) + fresh.length; const processedNext = new Set(processed); for (const turn of fresh) if (turn.turnId !== undefined) processedNext.add(turn.turnId); let documentId; if (fresh.length > 0) { const documents = this.workspaces.get(this.projectRootFor(workspace))?.documents; if (documents === undefined) throw new Error('local_documents_unavailable'); const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] }); documentId = document.id; } const lastTurn = prior?.lastTurn; const lastCandidate = fresh.map((turn) => turn.turnId).filter((value) => value !== undefined).at(-1); const lastValue = lastCandidate === undefined ? lastTurn : lastTurn === undefined ? lastCandidate : (Number.isFinite(Number(lastCandidate)) && Number.isFinite(Number(lastTurn)) ? (Number(lastCandidate) >= Number(lastTurn) ? lastCandidate : lastTurn) : lastTurn); checkpoints[input.sessionId] = { ...(lastValue === undefined ? {} : { lastTurn: lastValue }), count: nextCount, processed: [...processedNext].slice(-1000) }; await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n'); if (stored > 0) { const repair = await this.tryRegenerateProjections(); return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair }; } return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false }; }); } /** Add an explicit profile entry; inferred entries stay in the pending area. */ async proposeProfile(content, source = 'user', inferred = false) { if (this.settingsOf().autoProfileEnabled === false) throw new Error('auto_profile_disabled'); await this.ensureGlobal(); await this.markProjectionDirty(); const result = await this.globalStore.add({ content, category: inferred ? 'profile-pending' : 'preference', source, tags: ['profile'] }); if (!inferred) await this.tryRegenerateProjections(); return result.record; } async confirmProfile(id) { await this.ensureGlobal(); await this.markProjectionDirty(); const record = await this.globalStore.read(id); if (record === undefined) throw new Error('memory_not_found'); await this.globalStore.update(id, { category: 'preference' }); await this.tryRegenerateProjections(); } /** Correct an existing profile entry in place; the revision increments and prior text is not kept as a live entry. */ async correctProfile(id, content, expectedRevision) { await this.ensureGlobal(); await this.markProjectionDirty(); const record = await this.globalStore.update(id, { content, category: 'preference' }, expectedRevision); await this.tryRegenerateProjections(); return record; } /** Copy the whole global memory root into backups; no source file is removed. */ async createBackup() { await this.ensureGlobal(); const path = join(this.globalRoot, 'backups', 'backup-' + new Date().toISOString().replace(/[:.]/g, '-')); await mkdir(path, { recursive: true }); for (const entry of await readdir(this.globalRoot, { withFileTypes: true })) { if (entry.name === 'backups') continue; await cp(join(this.globalRoot, entry.name), join(path, entry.name), { recursive: true, force: false }); } return { path }; } /** Report legacy .mnemon locations without deleting anything. */ async legacyMigrationReport(workspace) { const found = []; for (const path of [join(this.projectBaseFor(workspace), '.mnemon'), join(dshHome(), '.mnemon')]) { if (await stat(path).catch(() => undefined) !== undefined) found.push(path); } return { found, targetGlobal: this.globalRoot, targetProject: this.projectRootFor(workspace) }; } async findLegacyMemoryFiles(root) { const out = []; const walk = async (dir) => { for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { const full = join(dir, entry.name); if (entry.isDirectory()) { await walk(full); continue; } if (/^(memories|memory)\.json$/i.test(entry.name) || /\.memory\.json$/i.test(entry.name)) out.push(full); } }; await walk(root); return out; } legacyRecordsFrom(value) { if (Array.isArray(value)) return value.filter((item) => item !== null && typeof item === 'object' && !Array.isArray(item)); if (value === null || typeof value !== 'object' || Array.isArray(value)) return []; const record = value; for (const key of ['records', 'memories', 'items']) { if (Array.isArray(record[key])) return this.legacyRecordsFrom(record[key]); } return record.content === undefined && record.text === undefined && record.memory === undefined ? [] : [record]; } async importLegacyRecords(sourcePath, workspace) { const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(sourcePath); const scope = projectLegacy ? 'project' : 'global'; const store = await this.storeFor(scope, workspace); let imported = 0; let duplicates = 0; let skipped = 0; const ids = []; for (const file of await this.findLegacyMemoryFiles(sourcePath)) { let parsed; try { parsed = JSON.parse(await readFile(file, 'utf8')); } catch { skipped += 1; continue; } for (const item of this.legacyRecordsFrom(parsed)) { const content = typeof item.content === 'string' ? item.content : typeof item.text === 'string' ? item.text : typeof item.memory === 'string' ? item.memory : ''; if (content.trim() === '') { skipped += 1; continue; } const category = typeof item.category === 'string' ? item.category : typeof item.sector === 'string' ? item.sector : undefined; const tags = Array.isArray(item.tags) ? item.tags.filter((tag) => typeof tag === 'string') : []; const legacyId = typeof item.id === 'string' ? item.id : ''; const operationId = 'legacy-' + localMemoryHash(file + '|' + legacyId + '|' + content); try { const result = await store.add({ content, ...(category === undefined ? {} : { category }), tags, source: 'legacy:' + file, operationId, scope, ...(scope === 'project' ? { projectId: projectIdFor(this.projectRootFor(workspace)) } : {}) }); if (result.duplicate) duplicates += 1; else imported += 1; // Content-only duplicates were present before this migration and // must never enter this migration's rollback ownership list. if ((!result.duplicate || result.duplicateKind === 'operation') && !ids.includes(result.record.id)) ids.push(result.record.id); } catch { skipped += 1; } } } return { imported, duplicates, skipped, ids, scope, ...(workspace === undefined ? {} : { workspace }) }; } /** Copy a legacy directory into backups; never moves or deletes the source. */ async migrateLegacy(path, workspace) { return withFileLock(join(this.globalRoot, 'state', '.migrations.lock'), async () => { const target = join(this.globalRoot, 'backups', 'migration-' + Date.now().toString(36) + '-' + randomUUID().slice(0, 8)); await mkdir(this.globalRoot, { recursive: true }); await cp(path, target, { recursive: true, force: false }); await this.markProjectionDirty(); const manifestPath = join(this.globalRoot, 'state', 'migrations.json'); const manifest = await readJson(manifestPath, []); const resolvedWorkspace = this.workspacePath(workspace); const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(path); const targetScope = projectLegacy ? 'project' : 'global'; const entry = { source: path, copiedTo: target, createdAt: new Date().toISOString(), status: 'importing', importedIds: [], targetScope, workspace: resolvedWorkspace }; manifest.push(entry); await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n'); try { const imported = await this.importLegacyRecords(path, workspace); entry.importedIds = imported.ids; entry.status = imported.skipped > 0 ? 'partial' : 'complete'; Object.assign(entry, { imported: imported.imported, duplicates: imported.duplicates, skipped: imported.skipped, partial: imported.skipped > 0 }); await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n'); return { copiedTo: target, imported: imported.imported, duplicates: imported.duplicates, skipped: imported.skipped, partial: imported.skipped > 0 }; } catch (error) { entry.status = 'error'; entry.error = error instanceof Error ? error.message : String(error); await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n').catch(() => { }); throw error; } }); } /** Restore a prepared backup first, then remove imported records; retries resume safely. */ async rollbackMigration(copiedTo, destination) { return withFileLock(join(this.globalRoot, 'state', '.migrations.lock'), async () => { const manifestPath = join(this.globalRoot, 'state', 'migrations.json'); const manifest = await readJson(manifestPath, []); const entry = manifest.find((item) => item.copiedTo === copiedTo); if (entry === undefined) throw new Error('migration_not_found'); const backupStat = await stat(copiedTo).catch(() => undefined); if (backupStat === undefined || !backupStat.isDirectory()) throw new Error('migration_backup_missing'); const completedDestination = entry.rollback?.destination; if (entry.rollback?.status === 'complete' && completedDestination !== undefined) { return { restoredTo: completedDestination, removedImported: 0 }; } if (completedDestination !== undefined && destination !== undefined && resolve(completedDestination) !== resolve(destination)) { throw new Error('restore_destination_mismatch'); } const restoredTo = completedDestination ?? destination ?? join(this.globalRoot, 'backups', 'restore-' + Date.now().toString(36)); const destinationStat = await stat(restoredTo).catch(() => undefined); if (destinationStat !== undefined && !destinationStat.isDirectory()) throw new Error('restore_destination_not_directory'); entry.rollback = entry.rollback ?? {}; entry.rollback.destination = restoredTo; if (entry.rollback.staging === undefined || !(await stat(entry.rollback.staging).catch(() => undefined))?.isDirectory()) { const staging = join(this.globalRoot, 'backups', '.restore-' + Date.now().toString(36) + '-' + randomUUID()); await cp(copiedTo, staging, { recursive: true, force: false }); entry.rollback.staging = staging; } const rollbackStatus = entry.rollback.status; if (rollbackStatus === 'complete') { if ((await readdir(restoredTo).catch(() => [])).length > 0) throw new Error('restore_destination_not_empty'); await cp(copiedTo, restoredTo, { recursive: true, force: false }); if (await treeDigest(copiedTo) !== await treeDigest(restoredTo)) throw new Error('restore_copy_incomplete'); return { restoredTo, removedImported: 0 }; } if (rollbackStatus === undefined || rollbackStatus === 'prepared') { entry.rollback.status = 'prepared'; await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n'); } // Land the restore copy before touching the active store. A conflicting // child in the destination therefore fails with the active store intact. if (rollbackStatus !== 'copied' && rollbackStatus !== 'records_removed' && rollbackStatus !== 'complete') { if ((await readdir(restoredTo).catch(() => [])).length > 0) throw new Error('restore_destination_not_empty'); await cp(entry.rollback.staging, restoredTo, { recursive: true, force: false }); if (await treeDigest(entry.rollback.staging) !== await treeDigest(restoredTo)) throw new Error('restore_copy_incomplete'); entry.rollback.status = 'copied'; await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n'); } if (rollbackStatus === 'copied') { const copyStat = await stat(restoredTo).catch(() => undefined); if (copyStat === undefined || !copyStat.isDirectory()) throw new Error('restore_copy_missing'); if (await treeDigest(restoredTo) !== await treeDigest(copiedTo)) throw new Error('restore_copy_incomplete'); } const store = entry.targetScope === 'project' ? await this.storeFor('project', entry.workspace) : this.globalStore; let removedImported = 0; if (rollbackStatus !== 'records_removed' && rollbackStatus !== 'complete') { for (const id of entry.importedIds ?? []) { try { await store.forget(id); removedImported += 1; } catch (error) { const message = error instanceof Error ? error.message : String(error); if (message.includes('memory_not_found')) continue; throw new Error('rollback_record_failed: ' + message); } } entry.rollback.status = 'records_removed'; await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n'); } await rm(entry.rollback.staging, { recursive: true, force: true }).catch(() => { }); entry.rollback.status = 'complete'; entry.status = 'rolled_back'; await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n'); const projection = removedImported > 0 ? await this.tryRegenerateProjections() : { projectionPending: false }; return { restoredTo, removedImported, ...projection }; }); } }