/** 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.ts' import { JsonDocumentStore, JsonMemoryStore, containsSecret, localMemoryHash, withFileLock } from './storage.ts' import type { LocalDocument, LocalMemoryAddInput, LocalMemoryRecord, LocalMemoryScope, LocalMemorySettings, LocalSpaceMeta } from './types.ts' import type { BrainLogger, BrainLogEvent } from '../diagnostics.ts' export function globalBrainRoot(): string { 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: string): string { const normalized = resolve(value) const brainSuffix = join('.dsh', 'brain') return normalized.endsWith(brainSuffix) ? dirname(dirname(normalized)) : normalized } export function projectBrainRoot(cwd: string = process.cwd()): string { return join(projectBaseOf(cwd), '.dsh', 'brain') } export function projectIdFor(root: string): string { return 'project_' + localMemoryHash(resolve(root)).slice(0, 16) } async function atomicWrite(path: string, content: string): Promise { 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: string): Promise { const files: string[] = [] const walk = async (dir: string, prefix: string): Promise => { 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: string, fallback: T): Promise { let text: string try { text = await readFile(path, 'utf8') } catch (error) { if ((error as NodeJS.ErrnoException).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) as T } catch { throw new Error(`local_memory_state_corrupt: ${path}`) } } async function writeGitIgnore(projectBase: string): Promise { 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 interface LocalMemoryManagerOptions { cwd?: () => string /** Optional per-instance workspace provider; a tool/session workspace overrides it. */ workspace?: () => string | undefined settings?: () => LocalMemorySettings /** Optional explicit global root (tests/embedding); defaults to $DSH_HOME/brain. */ globalRoot?: string /** Optional explicit project root; defaults to /.dsh/brain. */ projectRoot?: string /** Optional diagnostic logger; absent means a byte-equivalent no-op. */ logger?: BrainLogger } export interface LocalTurn { turnId?: string; user?: string; assistant?: string } interface WorkspaceStores { root: string; store: JsonMemoryStore; documents: JsonDocumentStore } interface SessionCheckpoint { lastTurn?: string; count: number; processed?: string[] } export class LocalMemoryManager { private readonly cwdOf: () => string private readonly defaultWorkspaceOf: (() => string | undefined) | undefined private readonly settingsOf: () => LocalMemorySettings private readonly workspaceContext = new AsyncLocalStorage() private readonly workspaces = new Map() private readonly fixedGlobalRoot: string | undefined private readonly fixedProjectRoot: string | undefined private readonly loggerOf: Pick | undefined constructor(options: LocalMemoryManagerOptions = {}) { this.cwdOf = options.cwd ?? (() => process.cwd()) this.defaultWorkspaceOf = options.workspace this.settingsOf = options.settings ?? (() => ({})) this.fixedGlobalRoot = options.globalRoot this.fixedProjectRoot = options.projectRoot this.loggerOf = options.logger === undefined ? undefined : { log: (event: BrainLogEvent) => { try { options.logger!.log(event) } catch { /* diagnostics must never break memory operations */ } } } } /** Bind one operation to a workspace; AsyncLocalStorage keeps concurrent sessions isolated. */ withWorkspace(workspace: string | undefined, job: () => Promise): Promise { return this.workspaceContext.run(workspace, job) } private workspacePath(workspace?: string): string { const value = workspace ?? this.workspaceContext.getStore() ?? this.defaultWorkspaceOf?.() ?? this.cwdOf() return resolve(value) } private projectRootFor(workspace?: string): string { return this.fixedProjectRoot ?? projectBrainRoot(this.workspacePath(workspace)) } private projectBaseFor(workspace?: string): string { return projectBaseOf(this.workspacePath(workspace)) } get globalRoot(): string { return this.fixedGlobalRoot ?? globalBrainRoot() } get projectRoot(): string { return this.projectRootFor() } private get globalStore(): JsonMemoryStore { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global') } private projectStoreFor(workspace?: string): JsonMemoryStore { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))) } private scopedStore(scope: LocalMemoryScope, workspace?: string): JsonMemoryStore { return scope === 'global' ? this.globalStore : this.projectStoreFor(workspace) } private async storeFor(scope: LocalMemoryScope, workspace?: string): Promise { if (scope === 'global') return this.globalStore return this.ensureProject(workspace) } private projectionDirtyPath(): string { return join(this.globalRoot, 'state', 'projection.json') } private async markProjectionDirty(error?: unknown): Promise { 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 } private async clearProjectionDirty(marker: string): Promise { try { const state = JSON.parse(await readFile(this.projectionDirtyPath(), 'utf8')) as { marker?: unknown }; if (state.marker === marker) await rm(this.projectionDirtyPath(), { force: true }) } catch {} } /** Retry a projection left dirty by a committed memory write. */ async repairProjectionsIfDirty(): Promise { if (!existsSync(this.projectionDirtyPath())) return false try { await this.regenerateProjections(); return true } catch { return false } } private async tryRegenerateProjections(): Promise<{ projectionPending: boolean; projectionError?: string }> { 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(): Promise { 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() this.loggerOf?.log({ event: 'memory.ensure', detail: { scope: 'global', root: this.globalRoot } }) return meta }) } /** First use in a project creates its .dsh/brain and a stable project space. */ async ensureProject(workspace?: string): Promise { 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) this.loggerOf?.log({ event: 'memory.ensure', scope: 'project', workspace: base, detail: { scope: 'project', root } }) return store }) } /** Public alias used by callers that initialize explicit local memory. */ async initialize(workspace?: string): Promise<{ global: LocalSpaceMeta; project: LocalSpaceMeta }> { return this.ensure(workspace) } async ensure(workspace?: string): Promise<{ global: LocalSpaceMeta; project: LocalSpaceMeta }> { 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: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; projectionPending?: boolean; projectionError?: string }> { const startedAt = Date.now() 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) { this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: result.record.id, duplicate: true, category: input.category, durationMs: Date.now() - startedAt } }) return result } const outcome = { ...result, ...(await this.tryRegenerateProjections()) } this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: outcome.record.id, duplicate: false, category: input.category, durationMs: Date.now() - startedAt } }) return outcome } async add(input: LocalMemoryAddInput): Promise<{ record: LocalMemoryRecord; duplicate: boolean; projectionPending?: boolean; projectionError?: string }> { return this.remember(input) } async read(id: string, workspace?: string): Promise { const globalRecord = await this.globalStore.read(id) if (globalRecord !== undefined) return globalRecord return (await this.ensureProject(workspace)).read(id) } private async collectHits(query: string, workspace?: string, projectId?: string): Promise<{ record: LocalMemoryRecord; score: number }[]> { 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: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string, scope?: LocalMemoryScope): Promise<{ record: LocalMemoryRecord; score: number }[]> { const startedAt = Date.now() const limit = Math.max(1, Math.min(100, Math.trunc(k))) const result = scope === undefined ? (await this.collectHits(query, workspace, projectId)).slice(0, limit) : await this.scopedStore(scope, workspace).search(query, limit) const sources: Record = {} for (const hit of result) sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1 this.loggerOf?.log({ event: 'memory.search', scope: scope ?? 'project', workspace: scope === 'global' ? undefined : this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }) return result } async search(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise { return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record) } async list(options: { limit?: number; offset?: number; scope?: LocalMemoryScope } = {}, workspace?: string, projectId?: string): Promise<{ items: LocalMemoryRecord[]; total: number }> { if (options.scope !== undefined) return this.scopedStore(options.scope, workspace).list(options) 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: string, expectedRevision?: number, workspace?: string, scope?: LocalMemoryScope): Promise { const targetScope = scope ?? ((await this.globalStore.read(id)) === undefined ? 'project' : 'global') const scopedStore = scope === undefined ? undefined : this.scopedStore(scope, workspace) if (scopedStore !== undefined) { const record = await scopedStore.read(id) if (record === undefined) throw new Error('memory_not_found') if (expectedRevision !== undefined && record.revision !== expectedRevision) throw new Error('revision_conflict') } // The runtime projections are built exclusively from the global store. if (scope !== 'project') await this.markProjectionDirty() const store = scopedStore ?? await this.storeFor(targetScope, workspace) const removed = await store.forget(id, expectedRevision) if (scope !== 'project') await this.tryRegenerateProjections() this.loggerOf?.log({ event: 'memory.forget', scope: targetScope, workspace: targetScope === 'project' ? this.workspacePath(workspace) : undefined, detail: { recordId: id, revision: removed.revision } }) return removed } async projects(workspace?: string): Promise<{ id: string; name: string }[]> { 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?: string): Promise { const root = this.projectRootFor(workspace) return new JsonDocumentStore(join(root, 'documents')).list() } async addDocument(input: { title: string; content: string; source?: string; tags?: string[] }, workspace?: string): Promise { await this.ensureProject(workspace) // ensureProject guarantees the workspace entry exists (the map is never pruned). const documents = this.workspaces.get(this.projectRootFor(workspace))!.documents return documents.add(input) } async storageStatus(workspace?: string, scope?: LocalMemoryScope): Promise> { const projectRoot = scope === 'global' ? undefined : this.projectRootFor(workspace) const global = scope === 'project' ? undefined : await this.globalStore.spaceMeta() const project = scope === 'global' ? undefined : await this.projectStoreFor(workspace).spaceMeta() return { provider: 'local', ...(scope === 'project' ? {} : { globalRoot: this.globalRoot }), ...(projectRoot === undefined ? {} : { projectRoot }), spaces: { ...(scope === 'project' ? {} : { global: global ?? null }), ...(scope === 'global' ? {} : { 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): string { const read = (path: string): string => { 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: string): string => 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(): Promise { 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: NodeJS.ErrnoException) => { 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: string, items: LocalMemoryRecord[]): string => '# ' + 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) this.loggerOf?.log({ event: 'memory.projection', detail: { root: this.globalRoot } }) } catch (error) { await this.markProjectionDirty(error) throw error } }) } /** Incremental, privacy-preserving summary: only explicit text is stored. */ async summarizeConversation(input: { sessionId: string; turns: LocalTurn[]; summary?: string }, workspace?: string): Promise<{ stored: number; duplicates: number; documentId?: string; skipped: boolean; projectionPending?: boolean; projectionError?: string }> { 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: string | undefined if (fresh.length > 0) { // ensureProject above guarantees the workspace entry exists (the map is never pruned). const documents = this.workspaces.get(this.projectRootFor(workspace))!.documents 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 is string => 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(); this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } }); return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair } } this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } }) return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false } }) } /** Add an explicit profile entry; inferred entries stay in the pending area. */ async proposeProfile(content: string, source = 'user', inferred = false): Promise { 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: string): Promise { 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: string, content: string, expectedRevision?: number): Promise { 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(): Promise<{ path: string }> { 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 }) } this.loggerOf?.log({ event: 'memory.backup', detail: { path } }) return { path } } /** Report legacy .mnemon locations without deleting anything. */ async legacyMigrationReport(workspace?: string): Promise<{ found: string[]; targetGlobal: string; targetProject: string }> { const found: string[] = [] 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) } } private async findLegacyMemoryFiles(root: string): Promise { const out: string[] = [] const walk = async (dir: string): Promise => { 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 } private legacyRecordsFrom(value: unknown): Record[] { if (Array.isArray(value)) return value.filter((item): item is Record => item !== null && typeof item === 'object' && !Array.isArray(item)) if (value === null || typeof value !== 'object' || Array.isArray(value)) return [] const record = value as Record 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] } private async importLegacyRecords(sourcePath: string, workspace?: string): Promise<{ imported: number; duplicates: number; skipped: number; ids: string[]; scope: LocalMemoryScope; workspace?: string }> { const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(sourcePath) const scope: LocalMemoryScope = projectLegacy ? 'project' : 'global' const store = await this.storeFor(scope, workspace) let imported = 0; let duplicates = 0; let skipped = 0; const ids: string[] = [] for (const file of await this.findLegacyMemoryFiles(sourcePath)) { let parsed: unknown 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): tag is string => 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: string, workspace?: string): Promise<{ copiedTo: string; imported: number; duplicates: number; skipped: number; partial: boolean }> { 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: LocalMemoryScope = projectLegacy ? 'project' : 'global' const entry: any = { source: path, copiedTo: target, createdAt: new Date().toISOString(), status: 'importing', importedIds: [] as string[], 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: string, destination?: string): Promise<{ restoredTo: string; removedImported: number; projectionPending?: boolean; projectionError?: string }> { 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 } }) } }