from afk_developer.backends.registry import BackendRegistry from afk_developer.config import Config from afk_developer.cortex.db import CortexDB from afk_developer.utils import extract_json def run_reflection(db: CortexDB, config: Config) -> str: fading_memories = db.read_recent_fading(limit=50) if not fading_memories: return "No fading memories to reflect on." fading_text = "\n".join(f"[{m.key}] {m.content}" for m in fading_memories) permanent_text = "\n".join(f"[{m.key}] {m.content}" for m in db.list_permanent()) response = ( BackendRegistry(config) .get_reasoner() .complete( system_prompt=( "You are a memory consolidation system for an autonomous coding agent. " "Analyze the fading (recent, temporary) memories below. Identify insights " "that are durable and should be promoted to permanent memory (e.g., user " "preferences, architectural decisions, lessons learned). Return a JSON object:\n" '{"summary": "one-paragraph synthesis of recent activity", ' '"promotions": [{"key": "...", "content": "..."}]}\n' "Only promote truly durable insights. Most fading memories should be discarded." ), user_prompt=( f"=== PERMANENT MEMORIES ===\n{permanent_text}\n\n" f"=== FADING MEMORIES (to review) ===\n{fading_text}\n\n" "Identify insights worth promoting to permanent memory." ), temperature=0.0, ) ) config.record_usage(response.usage, role="reasoner") result = extract_json(response.content) summary = result.get("summary", "") promotions = result.get("promotions", []) promoted_ids: list[int] = [] for promo in promotions: mem = db.write_permanent(key=promo["key"], content=promo["content"]) promoted_ids.append(mem.id) fading_ids = [m.id for m in fading_memories if m.id is not None] discarded = db.delete_fading_by_ids(fading_ids) + db.delete_expired_fading() db.record_reflection( summary=summary, promoted_ids=promoted_ids, discarded_count=discarded, ) return summary