import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises"; import { dirname, join, resolve } from "node:path"; export type MemoryFile = "memory" | "user"; export class MemoryStore { private readonly root: string; private readonly dailyDir: string; constructor(rootDir: string) { this.root = rootDir; this.dailyDir = join(rootDir, "daily"); } async ensure(): Promise { await mkdir(this.dailyDir, { recursive: true }); await this.ensureFile(this.pathFor("memory"), "# Memory\n\n"); await this.ensureFile(this.pathFor("user"), "# User\n\n"); } async read(file: MemoryFile): Promise { await this.ensure(); return await readFile(this.pathFor(file), "utf8"); } async append(file: MemoryFile, content: string): Promise { await this.ensure(); await appendFile(this.pathFor(file), `${content.trim()}\n\n`, "utf8"); } async appendDaily(content: string, date = new Date()): Promise { await this.ensure(); const filePath = this.dailyPath(date); await this.ensureFile(filePath, `# ${this.dayStamp(date)}\n\n`); await appendFile(filePath, `${content.trim()}\n\n`, "utf8"); return resolve(filePath); } getSummaryPaths(): { memory: string; user: string; dailyDir: string } { return { memory: resolve(this.pathFor("memory")), user: resolve(this.pathFor("user")), dailyDir: resolve(this.dailyDir) }; } private pathFor(file: MemoryFile): string { return join(this.root, file === "memory" ? "MEMORY.md" : "USER.md"); } private dailyPath(date: Date): string { return join(this.dailyDir, `${this.dayStamp(date)}.md`); } private dayStamp(date: Date): string { return date.toISOString().slice(0, 10); } private async ensureFile(filePath: string, initialContent: string): Promise { await mkdir(dirname(filePath), { recursive: true }); try { await readFile(filePath, "utf8"); } catch { await writeFile(filePath, initialContent, "utf8"); } } }