import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; import { hyperframesConfigDir } from "./configDir.js"; /** * Lasting preferences in the person's own words ("always 9:16"), kept for every project on this * machine: agents read them before starting, so the person says it once, not once per chat. */ export interface MemoryItem { id: number; text: string; addedAt: string; } /** Long enough for a sentence or two; a pasted document is not a preference. */ export const MEMORY_TEXT_MAX = 500; export const memoryPath = () => hyperframesConfigDir("memory.json"); const isItem = (value: unknown): value is MemoryItem => { if (typeof value !== "object" || value === null) return false; const { id, text, addedAt } = value as Record; return ( Number.isInteger(id) && typeof text === "string" && text !== "" && typeof addedAt === "string" ); }; const field = (parsed: unknown, key: string): unknown => typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, key) : undefined; // `nextId` outlives removals, so a number the person was shown never names a different item. function readMemoryFile(): { items: MemoryItem[]; nextId: number } { let parsed: unknown; try { parsed = JSON.parse(readFileSync(memoryPath(), "utf-8")); } catch { parsed = undefined; } const raw = field(parsed, "items"); const items = Array.isArray(raw) ? raw.filter(isItem) : []; const stored = field(parsed, "nextId"); const highest = items.reduce((max, item) => Math.max(max, item.id), 0); return { items, nextId: Math.max(highest + 1, Number.isInteger(stored) ? Number(stored) : 1) }; } export const readMemory = (): MemoryItem[] => readMemoryFile().items; function writeMemory(items: MemoryItem[], nextId: number): void { const file = memoryPath(); const tmp = `${file}.${process.pid}.tmp`; mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); try { writeFileSync(tmp, `${JSON.stringify({ version: 1, nextId, items }, null, 2)}\n`, { mode: 0o600, }); renameSync(tmp, file); } catch (error) { rmSync(tmp, { force: true }); throw error; } } const tidyText = (text: string) => text.trim().replace(/\s+/g, " "); const sameText = (a: string, b: string) => tidyText(a).toLowerCase() === tidyText(b).toLowerCase(); export type AddMemoryResult = | { added: true; item: MemoryItem } | { added: false; item: MemoryItem }; /** Why this text cannot be remembered, or undefined when it can. */ export function memoryTextProblem(text: string): string | undefined { const clean = tidyText(text); if (clean === "") return "Nothing to remember: the text is empty."; if (clean.length > MEMORY_TEXT_MAX) { return `That is ${clean.length} characters; keep one preference under ${MEMORY_TEXT_MAX}.`; } return undefined; } /** Adds the item, or returns the one already holding the same words. */ export function addMemory(text: string, at = new Date()): AddMemoryResult { const problem = memoryTextProblem(text); if (problem) throw new Error(problem); const clean = tidyText(text); const { items, nextId } = readMemoryFile(); const existing = items.find((item) => sameText(item.text, clean)); if (existing) return { added: false, item: existing }; const item: MemoryItem = { id: nextId, text: clean, addedAt: at.toISOString() }; writeMemory([...items, item], nextId + 1); return { added: true, item }; } /** Removes the item with that id; undefined when there is none. */ export function removeMemory(id: number): MemoryItem | undefined { const { items, nextId } = readMemoryFile(); const removed = items.find((item) => item.id === id); const kept = items.filter((item) => item.id !== id); if (removed) writeMemory(kept, nextId); return removed; }