augment17/claude-code-backend
0
1# -*- coding: utf-8 -*-2"""3context_engine.py — Agentic Context Engine (ACE) & Auto-Compactor4━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━5Implements the 3-agent self-improvement loop:6 1. Generator: Space 3 (Forge) executes code based on prompt.7 2. Reflector: Analyzes the test log and verdict from Space 6 (Sandbox).8 Determines what succeeded, what failed, and why.9 3. Curator: Updates the persistent "playbook" in the Second Brain10 with actionable instructions to avoid repeating mistakes.11 12Also implements the Auto-Compactor:13 - Scans playbooks and logs.14 - Summarises and merges duplicate rules to keep context within15 the Bell Curve apex (preventing context poisoning).16"""17 18import json19import logging20import time21from second_brain import SecondBrainWrapper22from swarm_llm import swarm23 24logger = logging.getLogger("context_engine")25 26class ContextEngine:27 def __init__(self, brain: SecondBrainWrapper):28 self.brain = brain29 30 # ── ACE Reflect & Curate ──────────────────────────────────────────────────31 32 async def reflect_and_curate(33 self,34 project_name: str,35 task_prompt: str,36 result_summary: str,37 verdict: str,38 reason: str39 ) -> str:40 """41 Runs after an execution cycle.42 If failed, reflects on why and updates the project playbook.43 If succeeded, records the success pattern.44 """45 playbook_path = f"space3-forge/debugging/{project_name}_playbook.md"46 current_playbook = self.brain.read(playbook_path, "brain")47 48 if verdict == "FAIL":49 logger.info(f"[ACE] Project '{project_name}' failed verification. Reflecting…")50 reflection_prompt = f"""Task attempted:51"{task_prompt}"52 53Execution summary:54"{result_summary}"55 56Test Failure Reason:57"{reason}"58 59Current Playbook rules:60{current_playbook if current_playbook else "_No rules yet._"}61 62---63What went wrong? Write exactly 1 or 2 new concrete guidelines for the coder agent to prevent this specific failure in the future.64Keep guidelines extremely brief, specific, and actionable. Do NOT repeat existing rules.65"""66 # Use local SwarmLLM to reflect (saving NIM quota)67 new_rules = await swarm.infer(reflection_prompt, system="You are a senior code architect reflecting on test failures.")68 69 # Curate: Append new rules to playbook70 updated_playbook = current_playbook + f"\n\n### Failure Correction ({time.strftime('%Y-%m-%d')})\n{new_rules.strip()}"71 self.brain.write(playbook_path, updated_playbook, f"[ACE] Add failure corrections for {project_name}")72 logger.info(f"[ACE] Curated playbook for '{project_name}' updated on GitHub.")73 return new_rules74 75 elif verdict == "PASS" and not current_playbook:76 # Seed the playbook with success patterns77 logger.info(f"[ACE] Project '{project_name}' passed. Seeding playbook.")78 seed_content = f"""# Playbook: {project_name}79_Self-improving ruleset curated by ACE (Agentic Context Engine)_80 81## Success Rules82- Initial implementation passed test suite successfully. Keep code simple and modular.83"""84 self.brain.write(playbook_path, seed_content, f"[ACE] Seed playbook for {project_name}")85 return "Seed rules created"86 87 return "No curation required"88 89 # ── Auto-Compactor ────────────────────────────────────────────────────────90 91 async def compact_wiki(self):92 """93 Auto-Compaction Protocol.94 Scans all files in the Second Brain.95 If a playbook or log exceeds its slot budget, consolidates and merges96 duplicate rules to prevent context poisoning.97 """98 logger.info("[Compactor] Running wiki compaction sweep…")99 100 # 1. Compact playbooks in space3-forge/debugging/101 playbooks = self.brain.list_files("space3-forge/debugging")102 for p in playbooks:103 content = self.brain.read(p, "brain")104 if len(content) > 3000:105 logger.info(f"[Compactor] Playbook '{p}' is large ({len(content)} chars). Compacting…")106 compaction_prompt = f"""The following is a coding playbook with rules collected over multiple cycles:107{content}108 109---110Consolidate the rules above. Remove duplicates, merge similar guidelines, and output a clean, highly condensed list of rules.111Maintain the markdown header structure. Do NOT lose important technical details.112"""113 compacted = await swarm.infer(compaction_prompt, system="You are an expert compiler that deduplicates and condenses playbooks.")114 self.brain.write(p, compacted, f"[Compactor] Compacted playbook {p}")115 logger.info(f"[Compactor] Compacted '{p}' down to {len(compacted)} chars.")116 117 # 2. Compact loop logs in space2-cerebrum/loop_log.md118 log_path = "space2-cerebrum/loop_log.md"119 log_content = self.brain.read(log_path, "brain")120 if len(log_content) > 4000:121 logger.info(f"[Compactor] Log '{log_path}' exceeds limit. Archiving old entries…")122 lines = log_content.splitlines()123 # Keep only the last 30 lines, archive the rest124 recent = "\n".join(lines[-30:])125 self.brain.write(log_path, recent, "[Compactor] Trim and archive old loop logs")126 logger.info(f"[Compactor] Loop log trimmed.")127 128 logger.info("[Compactor] Compaction sweep complete.")129 