import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { ALL_CATEGORIES } from './constants.js'; import { atomicWriteFile, scopeDirectory } from './fileStore.js'; import { sha256 } from './codec.js'; import type { MemoryRecordV2, MemoryScope, MemorySnapshot, } from './types.js'; const GENERATED_HEADER = '`, '# Memory Topics', '', '> 自动生成、禁止编辑。UUID Markdown 记录是唯一权威来源;删除本文件后会自动重建。', ]; for (const category of ALL_CATEGORIES) { const records = snapshot.records.filter((record) => record.category === category); if (!records.length) continue; lines.push('', `## ${category}`); const grouped = topicRecords(records); for (const topicKey of [...grouped.keys()].sort((a, b) => a.localeCompare(b, 'zh-CN'))) { lines.push('', `### ${topicKey}`); const values = grouped.get(topicKey)!; const current = values.filter((record) => record.status !== 'superseded'); const superseded = values.filter((record) => record.status === 'superseded'); for (const record of current) lines.push(...recordLine(record)); if (superseded.length) { lines.push('- 被替代记录:'); for (const record of superseded) { lines.push(` - \`${record.id}\` revision ${record.revision}, updated ${new Date(record.updatedAt).toISOString()}`); } } } } if (!snapshot.records.length) lines.push('', '_当前没有记忆记录。_'); return `${lines.join('\n')}\n`; } export async function ensureTopicView( snapshot: MemorySnapshot, scope: MemoryScope, workspaceId?: string, ): Promise { const path = topicViewPath(scope, workspaceId); const expectedPrefix = `${GENERATED_HEADER}; generation:${viewGeneration(snapshot)} -->`; const current = await readFile(path, 'utf8').catch(() => ''); if (current.startsWith(expectedPrefix)) return; await atomicWriteFile(path, renderTopicView(snapshot)); }