import { constants as fsConstants } from 'node:fs'; import { copyFile, readFile, readdir } from 'node:fs/promises'; import { basename, dirname, join, relative } from 'node:path'; import { hydrateRecord, parseMemoryRecord, serializeMemoryRecord, } from './codec.js'; import { ALL_CATEGORIES, CATEGORY_DIR } from './constants.js'; import { acquireFileLock, atomicWriteFile, ensurePrivateDir, memoryRecordPath, memoryRootDir, pathExists, } from './fileStore.js'; import type { MemoryRecord } from './types.js'; interface LegacyMemoryStore { version: 1; revision: number; records: MemoryRecord[]; } function markerPath(): string { return join(memoryRootDir(), 'migration-v2.json'); } function parseLegacyStore(value: unknown, path: string): LegacyMemoryStore { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error(`旧记忆文件结构无效:${path}`); } const raw = value as Record; if (raw.version !== 1 || !Array.isArray(raw.records)) { throw new Error(`旧记忆文件结构无效:${path}`); } return { version: 1, revision: typeof raw.revision === 'number' ? raw.revision : 0, records: raw.records as MemoryRecord[], }; } async function legacyFiles(): Promise { const files: string[] = []; const personal = join(memoryRootDir(), 'personal.json'); if (await pathExists(personal)) files.push(personal); const workspaceRoot = join(memoryRootDir(), 'workspaces'); try { for (const entry of await readdir(workspaceRoot, { withFileTypes: true })) { if (entry.isFile() && entry.name.endsWith('.json')) files.push(join(workspaceRoot, entry.name)); } } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } return files; } async function v1MarkdownFiles(): Promise { const bases = [join(memoryRootDir(), 'global')]; const workspaces = join(memoryRootDir(), 'workspaces'); try { for (const entry of await readdir(workspaces, { withFileTypes: true })) { if (entry.isDirectory()) bases.push(join(workspaces, entry.name)); } } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } const files: string[] = []; for (const base of bases) { for (const category of ALL_CATEGORIES) { const dir = join(base, CATEGORY_DIR[category]); try { for (const entry of await readdir(dir, { withFileTypes: true })) { if (!entry.isFile() || !entry.name.endsWith('.md')) continue; const path = join(dir, entry.name); const raw = await readFile(path, 'utf8'); if (!/^schemaVersion:\s*2\s*$/m.test(raw)) files.push(path); } } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } } } return files; } export async function ensureMemoryMigrated(): Promise { if (await pathExists(markerPath())) return; const release = await acquireFileLock(markerPath()); try { if (await pathExists(markerPath())) return; const legacy = await legacyFiles(); const backupRoot = join( memoryRootDir(), 'legacy-backup', `v1-${Date.now()}`, ); for (const path of legacy) { const relativeName = path === join(memoryRootDir(), 'personal.json') ? 'personal.json' : join('workspaces', basename(path)); const backup = join(backupRoot, relativeName); await ensurePrivateDir(dirname(backup)); await copyFile(path, backup, fsConstants.COPYFILE_EXCL).catch((error) => { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; }); const parsed = parseLegacyStore( JSON.parse(await readFile(path, 'utf8')), path, ); for (const legacyRecord of parsed.records) { const record = hydrateRecord(legacyRecord); const target = memoryRecordPath(record); if (!(await pathExists(target))) { await atomicWriteFile(target, serializeMemoryRecord(record)); } } } const markdownV1 = await v1MarkdownFiles(); const markdownBackupRoot = join( memoryRootDir(), 'legacy-backup', `markdown-v1-${Date.now()}`, ); for (const path of markdownV1) { const raw = await readFile(path, 'utf8'); const backup = join(markdownBackupRoot, relative(memoryRootDir(), path)); await ensurePrivateDir(dirname(backup)); await copyFile(path, backup, fsConstants.COPYFILE_EXCL); await atomicWriteFile( path, serializeMemoryRecord(parseMemoryRecord(raw, path)), ); } await atomicWriteFile( markerPath(), `${JSON.stringify( { version: 2, migratedAt: Date.now(), legacyFiles: legacy.length, ...(legacy.length ? { backupDir: backupRoot } : {}), upgradedMarkdownFiles: markdownV1.length, ...(markdownV1.length ? { markdownBackupDir: markdownBackupRoot } : {}), }, null, 2, )}\n`, ); } finally { await release(); } }