import { MEMORY_TYPES } from './types' import type { MemoryType } from './types' /** * Memory file format codecs — the md ⇄ structured-fields translation shared * by every consumer of the memdir file shape: * * - pack.ts serializes store rows into the injection pack * - writeback.ts parses bridge write-back files into rows * - sqliteBackend.ts serves/ingests md content for the unified web UI * - src/memdir/service.ts (CLI) synthesizes files on structured create * * The format itself is the CLI memdir frontmatter contract * (MEMORY_FRONTMATTER_EXAMPLE in memoryTypes.ts): `---` fence with * name/description/type, blank line, body. */ export interface MemoryFileFields { name: string description: string | null type: MemoryType content: string } /** Serialize structured fields into the memdir md file shape. */ export function serializeMemoryFile(fields: MemoryFileFields): string { return [ '---', `name: ${fields.name}`, `description: ${fields.description ?? fields.name}`, `type: ${fields.type}`, '---', '', fields.content, '', ].join('\n') } export interface ParsedMemoryFile { name: string description?: string type: MemoryType content: string } const MEMORY_TYPE_SET = new Set(MEMORY_TYPES) /** Minimal frontmatter parse (name/description/type) — memdir file shape. * Returns null when the content is not a well-formed memory file. */ export function parseMemoryFrontmatter(raw: string): ParsedMemoryFile | null { if (!raw.startsWith('---')) return null const end = raw.indexOf('\n---', 3) if (end < 0) return null const header = raw.slice(3, end) const body = raw.slice(end + 4).replace(/^\n+/, '') const fields = new Map() for (const line of header.split('\n')) { const idx = line.indexOf(':') if (idx > 0) { fields.set(line.slice(0, idx).trim(), line.slice(idx + 1).trim()) } } const name = fields.get('name') const type = fields.get('type') if (!name || !type || !MEMORY_TYPE_SET.has(type)) return null if (!body.trim()) return null return { name, description: fields.get('description') || undefined, type: type as MemoryType, content: body, } }