dsh-brain/verify-local-memory-round4.mjs

68 lines
7.4 KiB
JavaScript

// Fourth-round transactional regressions for migration rollback and summary documents.
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const root = mkdtempSync(join(tmpdir(), 'brain-r4-'))
process.env.DSH_HOME = join(root, 'home')
const project = join(root, 'project'); mkdirSync(project, { recursive: true })
const results = []
function check(name, ok, detail = '') { results.push({ name, ok }); console.log((ok ? 'PASS ' : 'FAIL ') + name + (detail ? ' :: ' + detail : '')) }
const { LocalMemoryManager } = await import('./lib/local-memory/index.js')
const settings = () => ({ localMemoryEnabled: true, cloudMemoryEnabled: false, autoMemorySpaces: true, autoSummaryEnabled: true, autoProfileEnabled: true, localMemoryK: 5 })
const manager = new LocalMemoryManager({ cwd: () => project, settings })
await manager.ensure()
const legacy = join(project, '.mnemon'); mkdirSync(legacy, { recursive: true }); writeFileSync(join(legacy, 'memories.json'), JSON.stringify({ records: [{ id: 'legacy-r4', content: 'rollback durable fact', category: 'project' }] }))
const migration = await manager.withWorkspace(project, () => manager.migrateLegacy(legacy, project))
const occupied = join(root, 'occupied-target'); writeFileSync(occupied, 'not a directory')
let rollbackError = ''
try { await manager.withWorkspace(project, () => manager.rollbackMigration(migration.copiedTo, occupied)) } catch (error) { rollbackError = String(error) }
const stillThere = await manager.withWorkspace(project, () => manager.search('rollback durable', 5, project))
check('failed rollback leaves active records untouched', rollbackError.includes('restore_destination_not_directory') && stillThere.length === 1)
const restored = await manager.withWorkspace(project, () => manager.rollbackMigration(migration.copiedTo, join(root, 'restored-good')))
const gone = await manager.withWorkspace(project, () => manager.search('rollback durable', 5, project))
check('retry rollback succeeds and restores the backup', restored.removedImported === 1 && gone.length === 0 && existsSync(join(root, 'restored-good', 'memories.json')))
check('original legacy data remains readable', readFileSync(join(legacy, 'memories.json'), 'utf8').includes('rollback durable fact'))
const repeated = await manager.withWorkspace(project, () => manager.rollbackMigration(migration.copiedTo, join(root, 'restored-again')))
check('repeated rollback returns the completed restore path', repeated.removedImported === 0 && repeated.restoredTo === join(root, 'restored-good') && existsSync(join(repeated.restoredTo, 'memories.json')))
const parallelLegacy = join(project, '.mnemon-parallel'); mkdirSync(parallelLegacy, { recursive: true }); writeFileSync(join(parallelLegacy, 'memories.json'), JSON.stringify({ records: [{ id: 'legacy-parallel', content: 'parallel migration fact', category: 'project' }] }))
const parallel = await Promise.all(Array.from({ length: 4 }, () => manager.withWorkspace(project, () => manager.migrateLegacy(parallelLegacy, project))))
const parallelRecords = await manager.withWorkspace(project, () => manager.search('parallel migration', 5, project))
check('parallel migrations keep receipts and one active record', parallel.length === 4 && parallelRecords.length === 1)
// Summary document recovery: corrupt index must not advance the checkpoint.
const summaryManager = new LocalMemoryManager({ globalRoot: join(root, 'summary-home'), projectRoot: join(root, 'summary-project'), settings })
await summaryManager.ensure()
const index = join(root, 'summary-project', 'documents', 'index.json'); writeFileSync(index, '{broken index')
let indexError = ''
try { await summaryManager.withWorkspace(join(root, 'summary-project'), () => summaryManager.summarizeConversation({ sessionId: 'doc-recovery', turns: [{ turnId: '1', user: '记住:我偏好深色主题。' }] }, join(root, 'summary-project'))) } catch (error) { indexError = String(error) }
check('document index failure is reported', indexError.includes('local_documents_corrupt'), indexError.slice(0, 80))
writeFileSync(index, JSON.stringify({ version: 1, nextRevision: 1, documents: [] }) + '\n')
const retry = await summaryManager.withWorkspace(join(root, 'summary-project'), () => summaryManager.summarizeConversation({ sessionId: 'doc-recovery', turns: [{ turnId: '1', user: '记住:我偏好深色主题。' }] }, join(root, 'summary-project')))
check('retry after index repair advances from the same turn', retry.documentId !== undefined && retry.duplicates === 1)
const replay = await summaryManager.withWorkspace(join(root, 'summary-project'), () => summaryManager.summarizeConversation({ sessionId: 'doc-recovery', turns: [{ turnId: '1', user: '记住:我偏好深色主题。' }] }, join(root, 'summary-project')))
check('replayed turn after repair is not duplicated', replay.stored === 0 && (await summaryManager.withWorkspace(join(root, 'summary-project'), () => summaryManager.list({ limit: 100 }, join(root, 'summary-project')))).items.filter((item) => item.content === '记住:我偏好深色主题').length === 1)
// Markdown failure after index commit must be repairable on retry.
const markdownManager = new LocalMemoryManager({ globalRoot: join(root, 'markdown-home'), projectRoot: join(root, 'markdown-project'), settings })
await markdownManager.ensure()
const filesDir = join(root, 'markdown-project', 'documents', 'files'); rmSync(filesDir, { recursive: true, force: true }); writeFileSync(filesDir, 'not a directory')
let markdownError = ''
try { await markdownManager.withWorkspace(join(root, 'markdown-project'), () => markdownManager.summarizeConversation({ sessionId: 'markdown-recovery', turns: [{ turnId: '1', user: '记住:我偏好浅色主题。' }] }, join(root, 'markdown-project'))) } catch (error) { markdownError = String(error) }
check('Markdown failure after index commit is reported', markdownError !== '')
rmSync(filesDir, { force: true }); mkdirSync(filesDir, { recursive: true })
const markdownRetry = await markdownManager.withWorkspace(join(root, 'markdown-project'), () => markdownManager.summarizeConversation({ sessionId: 'markdown-recovery', turns: [{ turnId: '1', user: '记住:我偏好浅色主题。' }] }, join(root, 'markdown-project')))
const markdownFiles = (await import('node:fs')).readdirSync(filesDir).filter((name) => String(name).endsWith('.md'))
check('Markdown retry repairs the missing file', markdownRetry.documentId !== undefined && markdownFiles.length === 1)
const profile = await manager.proposeProfile('legacy preference', 'user')
let profileEmpty = ''
try { await manager.correctProfile(profile.id, ' ') } catch (error) { profileEmpty = String(error) }
const profileAfterEmpty = await manager.read(profile.id)
check('profile update rejects empty content and preserves the old record', profileEmpty !== '' && profileAfterEmpty?.content === 'legacy preference')
let profileSecret = ''
try { await manager.correctProfile(profile.id, 'password=abcdef123456') } catch (error) { profileSecret = String(error) }
check('profile update rejects secrets and preserves the old record', profileSecret !== '' && (await manager.read(profile.id))?.content === 'legacy preference')
const failed = results.filter((result) => !result.ok)
console.log('')
console.log(failed.length ? 'FAILED ' + failed.length + '/' + results.length + ': ' + failed.map((result) => result.name).join(', ') : 'ALL ' + results.length + ' CHECKS PASSED')
rmSync(root, { recursive: true, force: true })
process.exit(failed.length ? 1 : 0)