import { exec } from "child_process"; import { promisify } from "util"; import fs from "fs/promises"; import path from "path"; const execAsync = promisify(exec); /** * Memory management for the HackingFactory using ChromaDB via Python bridge. * This allows storing successful code snippets and retrieving them based on semantic similarity. */ export class ProjectMemory { private static instance: ProjectMemory; private pythonBridgePath: string; private constructor() { this.pythonBridgePath = path.join(process.cwd(), "server", "memory_bridge.py"); this.ensurePythonBridge(); } public static getInstance(): ProjectMemory { if (!ProjectMemory.instance) { ProjectMemory.instance = new ProjectMemory(); } return ProjectMemory.instance; } private async ensurePythonBridge() { const bridgeCode = ` import chromadb import sys import json client = chromadb.PersistentClient(path="./chroma_db") collection = client.get_or_create_collection(name="hacking_factory_memory") def add_memory(id, content, metadata): collection.add( documents=[content], metadatas=[metadata], ids=[id] ) return {"status": "success"} def query_memory(query_text, n_results=3): results = collection.query( query_texts=[query_text], n_results=n_results ) return results if __name__ == "__main__": action = sys.argv[1] if action == "add": data = json.loads(sys.argv[2]) print(json.dumps(add_memory(data["id"], data["content"], data["metadata"]))) elif action == "query": query = sys.argv[2] print(json.dumps(query_memory(query))) `; await fs.writeFile(this.pythonBridgePath, bridgeCode); } public async addSuccessfulCode(projectId: number, code: string, prompt: string, score: number) { const data = JSON.stringify({ id: `proj_${projectId}_${Date.now()}`, content: code, metadata: { projectId, prompt, score, type: "successful_code" } }); try { const { stdout } = await execAsync(`python3 ${this.pythonBridgePath} add '${data}'`); return JSON.parse(stdout); } catch (error) { console.error("Memory add error:", error); return null; } } public async findSimilarSolutions(query: string) { try { const { stdout } = await execAsync(`python3 ${this.pythonBridgePath} query '${query}'`); return JSON.parse(stdout); } catch (error) { console.error("Memory query error:", error); return null; } } }