import * as fs from "fs" import * as path from "path" import { getConfigDir } from "../auth/config" export interface MemoryCategory { key: string filename: string description: string } export const MEMORY_CATEGORIES: MemoryCategory[] = [ { key: "preferences", filename: "preferences.md", description: "User preferences (language, style, conventions)" }, { key: "project", filename: "project-notes.md", description: "Project knowledge (architecture, patterns, key decisions)" }, { key: "decisions", filename: "decisions.md", description: "Past decisions and rationale" }, { key: "architecture", filename: "architecture.md", description: "System architecture notes" }, ] export function getMemoryDir(): string { return path.join(getConfigDir(), "memory") } export function ensureMemoryDir(): void { const dir = getMemoryDir() if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }) } for (const cat of MEMORY_CATEGORIES) { const filePath = path.join(dir, cat.filename) if (!fs.existsSync(filePath)) { fs.writeFileSync(filePath, `# ${cat.description}\n\n`, "utf-8") } } } export function readMemory(key: string): string { const cat = MEMORY_CATEGORIES.find((c) => c.key === key) if (!cat) return "" const filePath = path.join(getMemoryDir(), cat.filename) try { return fs.readFileSync(filePath, "utf-8").trim() } catch { return "" } } export function writeMemory(key: string, content: string): void { const cat = MEMORY_CATEGORIES.find((c) => c.key === key) if (!cat) return ensureMemoryDir() const filePath = path.join(getMemoryDir(), cat.filename) fs.writeFileSync(filePath, content, "utf-8") } export function appendMemory(key: string, line: string): void { const current = readMemory(key) writeMemory(key, current + "\n" + line) } export function readAllMemory(): Record { const result: Record = {} for (const cat of MEMORY_CATEGORIES) { const content = readMemory(cat.key) if (content) result[cat.key] = content } return result } export function buildMemoryPrompt(): string { const memories = readAllMemory() const entries = Object.entries(memories) if (entries.length === 0) return "" const lines = ["## User Memory"] for (const [key, content] of entries) { const cat = MEMORY_CATEGORIES.find((c) => c.key === key) if (cat && content.trim()) { lines.push(`### ${cat.description}`) lines.push(content) } } return lines.join("\n") }