Self-Reflective Dynamic Episodic Memory & Autonomous Self-Healing Agent Engine with Reflexion, ChromaDB & Rich REPL.
Python
0
8 commits
updated Oct 11, 2026
A production-grade, self-reflective autonomic AI architecture that intercepts runtime exceptions, performs multi-stage AST & log root cause analysis (RCA), persists error-fix-constraint quadruplets across a hybrid ChromaDB/SQLite memory substrate, and autonomously repairs code failures without human intervention.
Key Features โข System Architecture โข Execution State Machine โข Mathematical Foundations โข Quickstart โข CLI Reference โข Python SDK โข Memory Subsystem โข Chaos Benchmark โข Security Model โข Configuration โข Roadmap & Citations
Modern Large Language Model (LLM) coding agents (e.g. sweepers, autonomous software engineers, execution bots) suffer from three critical architectural flaws:
CogniHeal-Engine solves this by establishing a closed-loop episodic memory and verbal reinforcement engine. Inspired by cognitive psychology (Tulving's Episodic Memory Theory) and advanced agent reflection (Noah Shinn's Reflexion framework), CogniHeal parses runtime traces using Abstract Syntax Trees (AST), produces structured Root Cause Analysis (RCA), derives permanent Hard Constraint Rules, and queries past error memories via dense vector retrieval before code is even generated.
Dynamic AST & Traceback Decompiler (engine/ast_analyzer.py):
ast module.except: clauses, mutable default arguments, uncontrolled global mutations, and wildcard imports (from x import *).Dual-Tier Hybrid Episodic Memory (memory/episodic_engine.py):
Reflexion & Critique-and-Refine Loop (engine/reflection.py):
Defense-in-Depth Sandbox Execution (sandbox/executor.py):
--network=none), memory-capped (256MB), single-core container execution for untrusted multi-tenant code.Autonomous Orchestration Agent (agent/orchestrator.py):
"Past Lessons Learned" and "Active Hard Constraints" into system prompts.Terminal Telemetry & Rich UI (cli.py):
The following ASCII diagram illustrates the internal dataflow across all five subsystem layers:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER / CLI LAYER โ
โ cogniheal run --task "..." โ cogniheal benchmark โ cogniheal memory โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AUTONOMOUS ORCHESTRATOR LAYER โ
โ (cogniheal/agent/orchestrator.py) โ
โ โ
โ 1. Memory Scan Request 2. Enriched Prompt Gen 3. Subprocess Dispatch โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Semantic Query Engine โโโโโถโ Prompt Injector โโโโโโโโถโ Sandbox Controller โ โ
โ โ (Task & Error Vector) โ โ Lessons + Constraints โ โ Timeout & Env limits โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโฌโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโฒโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโ
โ โ
โ Vector Recall โ Dispatch Code
โ & Constraints โผ
โโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ EPISODIC MEMORY ENGINE โ โ EXECUTION SANDBOX โ
โ (cogniheal/memory/episodic_engine.py) โ โ (cogniheal/sandbox/ โ
โ โ โ executor.py) โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ ChromaDB HNSW โ โ SQLite WAL DB โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Vector Store โโโโโโโถโ Relational Storage โ โ โ โ Subprocess / Docker โ โ
โ โ (Cosine Metric) โ โ + FTS5 Full-Text โ โ โ โ Isolation Boundary โ โ
โ โ 1536-dim Embed โ โ Episodic Records โ โ โ โโโโโโโโโโโโโฌโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
โ โฒ โ โ
โ โ Upsert Episode โ โ Exit Code &
โ โ (Vector + Metadata) โ โ Raw Traceback
โ โ โ โผ
โ โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ REFLECTION & RCA LAYER โโโโโโโโ Execution Failure โ
โ โ (cogniheal/engine/reflection.py & rca.py) โ โ (exit_code != 0) โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โข AST Static Tree Parsing (Anti-patterns & Frames) โ
โ โ โข Root Cause Analysis (Taxonomy & Causal Chain) โ
โ โ โข Reflexion Self-Critique & Chain-of-Thought โ
โ โ โข Patch Synthesis & Invariant Rule Derivation โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INITIALIZE โ
โ Task Prompt / Source File โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STAGE 1: MEMORY SCAN โ
โ Cosine similarity query โ
โ Fetch active constraints โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STAGE 2: PROMPT SYNTHESIS โ
โ Inject: Lessons Learned โ
โ Inject: Hard Constraints โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโถโ STAGE 3: CODE EXECUTION โ
โ โ Subprocess / Docker Jail โ
โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ โ
โ Is Exit Code == 0?
โ / \
โ YES/ \NO
โ โผ โผ
โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ STATE: SUCCESS โ โ STAGE 4: AST & RCA PARSING โ
โ โ Return Result โ โ Parse frames, locate symbols โ
โ โโโโโโโโโโฌโโโโโโโโโ โ Static anti-pattern analysis โ
โ โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โ โผ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ STAGE 5: REFLEXION ENGINE โ
โ โ โ Chain-of-Thought Self-Critiqueโ
โ โ โ Formulate patch + constraint โ
โ โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โ Iter < MaxIter?
โ โ / \
โ โ YES/ \NO
โ โ โผ โผ
โ Apply Patch to Code โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Record Rule Candidate โ STATE: BUDGET EXHAUSTED โ
โ Iter = Iter + 1 โ Mark episode unsuccessfulโ
โ โ โโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ
โ โ
โ โผ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ STAGE 6: MEMORY UPSERT โ
โ โ Vectorize Error & Solution โ
โ โ Write to ChromaDB & SQLite โ
โ โโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ
โ โ
โ โผ
โโโโโโโโโโโโโโโโโโโ TERMINATE
Let an error episode $\mathcal{E}$ be mapped to a composite semantic textual representation $\mathcal{T}(\mathcal{E})$:
$$\mathcal{T}(\mathcal{E}) = \text{Summary}(\mathcal{RCA}) \parallel \text{Category} \parallel \bigoplus_{i=1}^k \text{CausalNode}_i \parallel \text{FixDescription} \parallel \text{Constraint}$$
The semantic embedding vector $\mathbf{v}_{\mathcal{E}} \in \mathbb{R}^d$ ($d = 1536$ for text-embedding-3-small) is generated via:
$$\mathbf{v}{\mathcal{E}} = \frac{f{\text{embed}}(\mathcal{T}(\mathcal{E}))}{|f_{\text{embed}}(\mathcal{T}(\mathcal{E}))|_2}$$
Given a runtime failure or incoming task query $\mathbf{q} \in \mathbb{R}^d$, the nearest historical episodes in the vector space $\mathcal{V}$ are retrieved according to the Cosine Metric $\mathcal{S}_{\cos}$:
$$\mathcal{S}{\cos}(\mathbf{q}, \mathbf{v}{\mathcal{E}}) = \frac{\mathbf{q} \cdot \mathbf{v}_{\mathcal{E}}}{|\mathbf{q}|2 |\mathbf{v}{\mathcal{E}}|_2}$$
Episodes are filtered subject to the similarity threshold parameter $\tau$:
$$\mathcal{M}{\text{recalled}} = \left{ \mathcal{E} \in \mathcal{V} ;\middle|; \mathcal{S}{\cos}(\mathbf{q}, \mathbf{v}_{\mathcal{E}}) \ge \tau \right}, \quad \text{where } \tau = 0.78$$
Following Shinn et al. (2023), CogniHeal defines the optimization of the agent policy $\pi_\theta$ over iterative episodes $t \in {1, \dots, N}$. Rather than scalar gradient updates, the policy is conditioned on an expanding verbal buffer of semantic memories $\mathcal{H}_t$:
$$\mathcal{H}t = \mathcal{H}{t-1} \cup \left{ \left( c_{t-1}, e_{t-1}, \mathcal{R}{t-1}, \mathcal{K}{t-1} \right) \right}$$
Where:
The code generator synthesizes the next candidate patch $c_t$:
$$c_t \sim \pi_\theta\left( \cdot ;\middle|; \text{Prompt}, \mathcal{H}_t, \bigcup \mathcal{K} \right)$$
>= 3.11 (Tested on 3.11 and 3.12)--sandbox-mode docker)# Clone the repository
git clone https://github.com/EvoderDev/CogniHeal-Engine.git
cd CogniHeal-Engine
# Create and activate virtual environment
python -m venv venv
# On Linux/macOS:
source venv/bin/activate
# On Windows PowerShell:
.\venv\Scripts\Activate.ps1
# Install requirements
pip install -r requirements.txt
# Install CogniHeal in editable development mode (registers global commands: cogni, cg, cogniheal)
pip install -e .
[!TIP] Once installed with
pip install -e ., the executablescogniandcgare automatically registered in your global system PATH! You can simply typecogniorcganywhere in your terminal to launch the interactive REPL.
Create a .env file in the project root (or set system environment variables):
# Optional: OpenAI API Key for deep LLM reasoning and OpenAI embeddings
# (If omitted, CogniHeal automatically falls back to its deterministic pseudo-embedding and heuristic rule engine)
COGNIHEAL_OPENAI_API_KEY=sk-proj-your-api-key-here
# LLM Tunables
COGNIHEAL_LLM_MODEL=gpt-4o
COGNIHEAL_EMBEDDING_MODEL=text-embedding-3-small
COGNIHEAL_LLM_TEMPERATURE=0.2
# Self-Healing Bounds
COGNIHEAL_MAX_HEAL_ITERATIONS=5
COGNIHEAL_SIMILARITY_THRESHOLD=0.78
COGNIHEAL_TOP_K_MEMORIES=5
# Sandbox Security
COGNIHEAL_SANDBOX_MODE=subprocess
COGNIHEAL_SANDBOX_TIMEOUT_SECONDS=30
CogniHeal provides an interactive REPL modeled after modern autonomous coding tools, equipped with a persistent session context, live status spinners, and memory querying.
Type either of the global commands directly in your terminal:
cogni # Full brand command
# or:
cg # Ultra-fast short alias
# or:
cogniheal # Canonical package entrypoint
In the interactive REPL, the session stays active continuously across multiple turns without exiting:
Write a thread-safe LRU cache with TTL)./load <path> โ Load a Python file into active session memory/memory โ View recently stored episodic error memories/search <query> โ Dense semantic search across historical errors/stats โ View SQLite and ChromaDB persistence statistics/constraints โ List active hard constraint rules/history โ Review current session conversational turns/reset โ Clear current conversation context/benchmark โ Execute the 12-scenario chaos benchmark/clear โ Clear terminal screen/exit โ End the session gracefullyRun self-healing on a Python file that fails at runtime:
cogniheal run --code-file examples/sample_fix.py
____ _ _ _ _
/ ___|___ __ _ _ __ (_) | | | ___ __ _| |
| | / _ \ / _` | '_ \| | |_| |/ _ \/ _` | |
| |__| (_) | (_| | | | | | _ | __/ (_| | |
\____\___/ \__, |_| |_|_|_| |_|\___|\__,_|_|
|___/
โโ Self-Reflective Dynamic Episodic Memory Engine โโ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโ ๐ Source: sample_fix.py โโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ 1 import nonexistent_secret_package โ
โ 2 def calculate(): return 42 โ
โ 3 print(calculate()) โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โก EXECUTE (iter 1) โโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ Executing code (attempt 1/5)โฆ โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ ๐ REFLECT (iter 1) โโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ Execution failed. Running Reflexion analysisโฆ โ
โ stderr: ModuleNotFoundError: No module named 'nonexistent_secret_package' โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ ๐ง FIX (iter 1) โโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ ๐ง Applying fix (confidence: 30%) โ
โ Constraint: Always handle import_error errors explicitly. โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โก EXECUTE (iter 2) โโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ Executing code (attempt 2/5)โฆ โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
SUCCESS (iter 2) โโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ
Code executed successfully on attempt 2! โ
โ stdout: 42 โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
cogniheal run --task "Write a thread-safe singleton cache with TTL expiration"
Inspect the contents of the hybrid SQLite + ChromaDB memory store:
# Print high-level memory statistics
cogniheal memory stats
# List recent error episodes
cogniheal memory list --limit 10
# Perform dense semantic vector search
cogniheal memory search "IndexError list index out of range in loop"
# Display all active hard negative constraint rules
cogniheal memory constraints
Execute the built-in stress test against all 12 deliberate bug patterns:
cogniheal benchmark --max-iterations 5
Integrate CogniHeal-Engine directly into your existing agent pipelines, testing frameworks, or LLM evaluation harnesses:
from pathlib import Path
from cogniheal.config import settings
from cogniheal.memory.episodic_engine import EpisodicMemoryEngine
from cogniheal.agent.orchestrator import HealingOrchestrator, HealCycleEvent
# 1. Initialize the episodic memory substrate
settings.ensure_dirs()
memory = EpisodicMemoryEngine()
memory.initialise()
# 2. Define an event listener for live UI or logging
def telemetry_listener(event: HealCycleEvent) -> None:
print(f"[{event.stage.upper()}] Iteration {event.iteration}: {event.message}")
# 3. Instantiate the orchestrator
orchestrator = HealingOrchestrator(
memory_engine=memory,
max_iterations=5,
on_event=telemetry_listener,
)
# 4. Execute self-healing on buggy code
buggy_snippet = """
def parse_records(raw_data: list[dict]) -> float:
# Bug: missing key and potential zero division
total = sum(item["metric"] for item in raw_data)
return total / len(raw_data)
print(parse_records([]))
"""
result = orchestrator.run(
task_prompt="Safely parse and average metrics from dictionary list",
initial_code=buggy_snippet,
)
# 5. Access structured outputs
print(f"Heal Succeeded: {result.success}")
print(f"Total Iterations: {result.total_iterations}")
print(f"Final Sanitized Code:\n{result.final_code}")
print(f"Stdout:\n{result.final_result.stdout}")
# 6. Query memory for lessons stored from this run
related_episodes = memory.query("zero division in parse_records", top_k=1)
for ep in related_episodes:
print(f"Learned Rule: {ep.hard_constraint.description}")
memory.close()
CogniHeal combines the best of Vector Databases (associative semantic recall) and Relational ACID Databases (exact relational queries and auditability).
-- Main episodic records table
CREATE TABLE IF NOT EXISTS episodes (
episode_id TEXT PRIMARY KEY,
timestamp TEXT NOT NULL,
original_code TEXT NOT NULL,
task_prompt TEXT NOT NULL DEFAULT '',
raw_error TEXT NOT NULL,
stack_frames_json TEXT NOT NULL DEFAULT '[]',
rca_json TEXT NOT NULL,
reflection TEXT NOT NULL DEFAULT '',
fix_json TEXT NOT NULL,
constraint_json TEXT NOT NULL,
tags_json TEXT NOT NULL DEFAULT '[]',
success INTEGER NOT NULL DEFAULT 0,
total_iterations INTEGER NOT NULL DEFAULT 1
);
-- Normalized table for fast constraint queries
CREATE TABLE IF NOT EXISTS hard_constraints (
rule_id TEXT PRIMARY KEY,
episode_id TEXT NOT NULL,
description TEXT NOT NULL,
code_pattern TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
FOREIGN KEY (episode_id) REFERENCES episodes(episode_id) ON DELETE CASCADE
);
-- SQLite Full-Text Search (FTS5) index for rapid exact keyword matching
CREATE VIRTUAL TABLE IF NOT EXISTS episodes_fts
USING fts5(episode_id, raw_error, rca_summary, fix_description);
cogniheal_episodesCosineError: <RCA Summary>
Category: <syntax_error | type_error | runtime_error | import_error | logic_error | ...>
Root cause chain: <Cause Step 1> -> <Cause Step 2>
Fix: <Applied Patch Description>
Constraint: <Hard Negative Rule>
category: Taxonomy stringseverity: low | medium | high | criticalsuccess: "True" | "False"timestamp: ISO-8601 stringLocated at examples/benchmark_chaos.py, this test suite includes 12 deliberate, real-world runtime anomalies designed to stress-test every facet of CogniHeal:
| # | Scenario Title | Primary Failure | Root Cause Mechanism | Verification Condition |
|---|---|---|---|---|
| 01 | Type Mismatch Arithmetic | TypeError | Concatenating string literal to integer accumulator | Numbers parsed to float, correct sum |
| 02 | Missing Package Import | ModuleNotFoundError | Attempting to import non-existent package supercalc | Import eliminated or gracefully handled |
| 03 | Off-by-One Index Error | IndexError | Loop access items[i + 1] exceeding bounds | Array bound clamped to len(items) - 1 |
| 04 | Missing Dictionary Key | KeyError | Direct key subscript on sparse dictionary | Safe retrieval via .get() or key validation |
| 05 | Infinite Recursion | RecursionError | Missing base-case condition in recursive factorial | Guard clause if n <= 1: return 1 added |
| 06 | Attribute Error on String | AttributeError | Calling non-existent method .trimmed() on string | Correct method .strip() invoked |
| 07 | Invalid String to Int | ValueError | int("unknown") type conversion exception | Numeric validation with try-except fallback |
| 08 | Async Race Condition | RuntimeError | Multi-threaded shared counter corruption without lock | Threading lock threading.Lock() synchronisation |
| 09 | Division by Zero | ZeroDivisionError | Empty array passed into arithmetic average | Non-empty denominator validation check |
| 10 | File Not Found | FileNotFoundError | Opening non-existent configuration file path | Path.exists() check or fallback defaults |
| 11 | Unbound Local Variable | UnboundLocalError | Variable referenced before conditional assignment | Default variable initialisation before loop |
| 12 | Mutable Default Argument | RuntimeError | def f(x, target=[]) state leakage across calls | Default set to None with internal list allocation |
Running LLM-generated code poses severe host security risks. CogniHeal enforces a multi-tier defense-in-depth model:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HOST OPERATING SYSTEM โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ COGNIHEAL APPLICATION โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ โ SANDBOX CONTROLLER (executor.py) โ โ โ
โ โ โ โ โ โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ โ โ MODE: SUBPROCESS โ โ โ โ
โ โ โ โ โข Stripped Environment (Path/System only)โ โ โ โ
โ โ โ โ โข Process Group Timeout Kill โ โ โ โ
โ โ โ โ โข Ephemeral Temp Directory Disposal โ โ โ โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ โ โ MODE: DOCKER CONTAINER โ โ โ โ
โ โ โ โ โข --network=none (Full Network Airgap) โ โ โ โ
โ โ โ โ โข --memory=256m (OOM Protection) โ โ โ โ
โ โ โ โ โข --cpus=1 (CPU Starvation Prevention) โ โ โ โ
โ โ โ โ โข --pids-limit=64 (Fork Bomb Prevention) โ โ โ โ
โ โ โ โ โข Read-Only Volume Mount (/sandbox:ro) โ โ โ โ
โ โ โ โ โข Ephemeral Container Auto-Cleanup (--rm)โ โ โ โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
subprocess, all credentials, API tokens, and secret environment variables (AWS_*, OPENAI_*, GITHUB_*) are stripped.--network=none, completely preventing socket creation, data exfiltration, or botnet staging.while True: os.fork()) or infinite memory allocations.sandbox_timeout_seconds (default: 30s). Rogue threads or infinite loops are forcefully terminated with SIGKILL.All configuration keys can be supplied via environment variables prefixed with COGNIHEAL_ or via a .env file:
| Environment Variable | Python Type | Default Value | Validation Constraints | Functional Description |
|---|---|---|---|---|
COGNIHEAL_OPENAI_API_KEY | str | "" | Optional | OpenAI API key for LLM reflection and embeddings |
COGNIHEAL_LLM_MODEL | str | "gpt-4o" | Valid Model ID | LLM model for critique, reflection, and code generation |
COGNIHEAL_EMBEDDING_MODEL | str | "text-embedding-3-small" | Valid Model ID | Model used for semantic error vector generation |
COGNIHEAL_LLM_TEMPERATURE | float | 0.2 | $0.0 \le T \le 2.0$ | Sampling temperature for reflection synthesis |
COGNIHEAL_LLM_MAX_TOKENS | int | 4096 | $\ge 256$ | Maximum token output limit for LLM responses |
COGNIHEAL_MAX_HEAL_ITERATIONS | int | 5 | $1 \le N \le 20$ | Maximum self-healing loops before giving up |
COGNIHEAL_SIMILARITY_THRESHOLD | float | 0.78 | $0.0 \le \tau \le 1.0$ | Minimum cosine similarity to inject past memories |
COGNIHEAL_TOP_K_MEMORIES | int | 5 | $\ge 1$ | Maximum number of episodic memories injected per prompt |
COGNIHEAL_SANDBOX_MODE | str | "subprocess" | "subprocess" | "docker" | Code execution backend |
COGNIHEAL_SANDBOX_TIMEOUT_SECONDS | int | 30 | $\ge 5$ | Hard wall-clock execution timeout in seconds |
COGNIHEAL_DOCKER_IMAGE | str | "python:3.12-slim" | Valid Docker tag | Base image used when Docker sandbox mode is active |
COGNIHEAL_DATA_DIR | Path | "cogniheal_data" | Path string | Base directory for SQLite and ChromaDB data |
COGNIHEAL_SQLITE_FILENAME | str | "episodic_memory.db" | File name | SQLite database file name |
COGNIHEAL_CHROMA_COLLECTION_NAME | str | "cogniheal_episodes" | Alphanumeric string | ChromaDB collection name |
COGNIHEAL_LOG_LEVEL | str | "INFO" | "DEBUG" | "INFO" | "WARNING" | CLI and internal logger verbosity |
CogniHeal maintains a comprehensive, zero-dependency unit test suite compatible with both unittest and pytest.
# Run tests with Python standard library runner:
python -m unittest discover -s tests -v
# Or run with pytest (if installed):
pytest tests/ -v --cov=cogniheal
test_analyse_source_syntax_error (test_ast_analyzer.TestASTAnalyzer) ... ok
test_analyse_source_valid_ast (test_ast_analyzer.TestASTAnalyzer) ... ok
test_detect_bare_except (test_ast_analyzer.TestASTAnalyzer) ... ok
test_detect_global_usage (test_ast_analyzer.TestASTAnalyzer) ... ok
test_detect_mutable_default (test_ast_analyzer.TestASTAnalyzer) ... ok
test_extract_error_type (test_ast_analyzer.TestASTAnalyzer) ... ok
test_get_function_source (test_ast_analyzer.TestASTAnalyzer) ... ok
test_parse_traceback_multiframe (test_ast_analyzer.TestASTAnalyzer) ... ok
test_embedding_fallback_deterministic (test_memory.TestMemorySubsystem) ... ok
test_memory_engine_crud (test_memory.TestMemorySubsystem) ... ok
test_models_to_semantic_text (test_memory.TestMemorySubsystem) ... ok
test_orchestrator_healing_flow (test_orchestrator.TestOrchestrator) ... ok
test_orchestrator_successful_code (test_orchestrator.TestOrchestrator) ... ok
test_sandbox_failure_captures_stderr (test_sandbox.TestSandboxExecutor) ... ok
test_sandbox_successful_execution (test_sandbox.TestSandboxExecutor) ... ok
test_sandbox_timeout_handling (test_sandbox.TestSandboxExecutor) ... ok
----------------------------------------------------------------------
Ran 16 tests in 2.497s โ OK (All tests passing)
If you use CogniHeal-Engine in your research, agent benchmarks, or production systems, please cite the following foundational literature:
@article{shinn2023reflexion,
title = {Reflexion: Language Agents with Verbal Reinforcement Learning},
author = {Noah Shinn and Federico Cassano and Edward Berman and Ashwin Gopinath and Karthik Narasimhan and Shunyu Yao},
journal = {Advances in Neural Information Processing Systems (NeurIPS)},
volume = {36},
year = {2023}
}
@article{tulving1972episodic,
title = {Episodic and Semantic Memory},
author = {Endel Tulving},
journal = {Organization of Memory},
pages = {381--403},
year = {1972},
publisher = {Academic Press}
}
@article{wei2022chain,
title = {Chain-of-Thought Prompting Elicits Reasoning in Large Language Models},
author = {Jason Wei and Xuezhi Wang and Dale Schuurmans and Maarten Bosma and Brian Ichter and Fei Xia and Ed Chi and Quoc Le and Denny Zhou},
journal = {Advances in Neural Information Processing Systems (NeurIPS)},
volume = {35},
pages = {24824--24837},
year = {2022}
}
This project is open-source under the MIT License.
Developed for autonomous AI engineering teams, agent developers, and researchers building resilient software architectures.
CogniHeal-Engine โ Because the best debugger is one that never forgets its mistakes.
โญ Star us on GitHub to support the project!
Self-Reflective Dynamic Episodic Memory & Autonomous Self-Healing Agent Engine with Reflexion, ChromaDB & Rich REPL.
Python
0
8 commits
updated Oct 11, 2026
A production-grade, self-reflective autonomic AI architecture that intercepts runtime exceptions, performs multi-stage AST & log root cause analysis (RCA), persists error-fix-constraint quadruplets across a hybrid ChromaDB/SQLite memory substrate, and autonomously repairs code failures without human intervention.
Key Features โข System Architecture โข Execution State Machine โข Mathematical Foundations โข Quickstart โข CLI Reference โข Python SDK โข Memory Subsystem โข Chaos Benchmark โข Security Model โข Configuration โข Roadmap & Citations
Modern Large Language Model (LLM) coding agents (e.g. sweepers, autonomous software engineers, execution bots) suffer from three critical architectural flaws:
CogniHeal-Engine solves this by establishing a closed-loop episodic memory and verbal reinforcement engine. Inspired by cognitive psychology (Tulving's Episodic Memory Theory) and advanced agent reflection (Noah Shinn's Reflexion framework), CogniHeal parses runtime traces using Abstract Syntax Trees (AST), produces structured Root Cause Analysis (RCA), derives permanent Hard Constraint Rules, and queries past error memories via dense vector retrieval before code is even generated.
Dynamic AST & Traceback Decompiler (engine/ast_analyzer.py):
ast module.except: clauses, mutable default arguments, uncontrolled global mutations, and wildcard imports (from x import *).Dual-Tier Hybrid Episodic Memory (memory/episodic_engine.py):
Reflexion & Critique-and-Refine Loop (engine/reflection.py):
Defense-in-Depth Sandbox Execution (sandbox/executor.py):
--network=none), memory-capped (256MB), single-core container execution for untrusted multi-tenant code.Autonomous Orchestration Agent (agent/orchestrator.py):
"Past Lessons Learned" and "Active Hard Constraints" into system prompts.Terminal Telemetry & Rich UI (cli.py):
The following ASCII diagram illustrates the internal dataflow across all five subsystem layers:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER / CLI LAYER โ
โ cogniheal run --task "..." โ cogniheal benchmark โ cogniheal memory โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AUTONOMOUS ORCHESTRATOR LAYER โ
โ (cogniheal/agent/orchestrator.py) โ
โ โ
โ 1. Memory Scan Request 2. Enriched Prompt Gen 3. Subprocess Dispatch โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Semantic Query Engine โโโโโถโ Prompt Injector โโโโโโโโถโ Sandbox Controller โ โ
โ โ (Task & Error Vector) โ โ Lessons + Constraints โ โ Timeout & Env limits โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโฌโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโฒโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโ
โ โ
โ Vector Recall โ Dispatch Code
โ & Constraints โผ
โโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ EPISODIC MEMORY ENGINE โ โ EXECUTION SANDBOX โ
โ (cogniheal/memory/episodic_engine.py) โ โ (cogniheal/sandbox/ โ
โ โ โ executor.py) โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ ChromaDB HNSW โ โ SQLite WAL DB โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Vector Store โโโโโโโถโ Relational Storage โ โ โ โ Subprocess / Docker โ โ
โ โ (Cosine Metric) โ โ + FTS5 Full-Text โ โ โ โ Isolation Boundary โ โ
โ โ 1536-dim Embed โ โ Episodic Records โ โ โ โโโโโโโโโโโโโฌโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
โ โฒ โ โ
โ โ Upsert Episode โ โ Exit Code &
โ โ (Vector + Metadata) โ โ Raw Traceback
โ โ โ โผ
โ โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ REFLECTION & RCA LAYER โโโโโโโโ Execution Failure โ
โ โ (cogniheal/engine/reflection.py & rca.py) โ โ (exit_code != 0) โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โข AST Static Tree Parsing (Anti-patterns & Frames) โ
โ โ โข Root Cause Analysis (Taxonomy & Causal Chain) โ
โ โ โข Reflexion Self-Critique & Chain-of-Thought โ
โ โ โข Patch Synthesis & Invariant Rule Derivation โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INITIALIZE โ
โ Task Prompt / Source File โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STAGE 1: MEMORY SCAN โ
โ Cosine similarity query โ
โ Fetch active constraints โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STAGE 2: PROMPT SYNTHESIS โ
โ Inject: Lessons Learned โ
โ Inject: Hard Constraints โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโถโ STAGE 3: CODE EXECUTION โ
โ โ Subprocess / Docker Jail โ
โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ โ
โ Is Exit Code == 0?
โ / \
โ YES/ \NO
โ โผ โผ
โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ STATE: SUCCESS โ โ STAGE 4: AST & RCA PARSING โ
โ โ Return Result โ โ Parse frames, locate symbols โ
โ โโโโโโโโโโฌโโโโโโโโโ โ Static anti-pattern analysis โ
โ โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โ โผ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ STAGE 5: REFLEXION ENGINE โ
โ โ โ Chain-of-Thought Self-Critiqueโ
โ โ โ Formulate patch + constraint โ
โ โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โ Iter < MaxIter?
โ โ / \
โ โ YES/ \NO
โ โ โผ โผ
โ Apply Patch to Code โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Record Rule Candidate โ STATE: BUDGET EXHAUSTED โ
โ Iter = Iter + 1 โ Mark episode unsuccessfulโ
โ โ โโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ
โ โ
โ โผ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ STAGE 6: MEMORY UPSERT โ
โ โ Vectorize Error & Solution โ
โ โ Write to ChromaDB & SQLite โ
โ โโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ
โ โ
โ โผ
โโโโโโโโโโโโโโโโโโโ TERMINATE
Let an error episode $\mathcal{E}$ be mapped to a composite semantic textual representation $\mathcal{T}(\mathcal{E})$:
$$\mathcal{T}(\mathcal{E}) = \text{Summary}(\mathcal{RCA}) \parallel \text{Category} \parallel \bigoplus_{i=1}^k \text{CausalNode}_i \parallel \text{FixDescription} \parallel \text{Constraint}$$
The semantic embedding vector $\mathbf{v}_{\mathcal{E}} \in \mathbb{R}^d$ ($d = 1536$ for text-embedding-3-small) is generated via:
$$\mathbf{v}{\mathcal{E}} = \frac{f{\text{embed}}(\mathcal{T}(\mathcal{E}))}{|f_{\text{embed}}(\mathcal{T}(\mathcal{E}))|_2}$$
Given a runtime failure or incoming task query $\mathbf{q} \in \mathbb{R}^d$, the nearest historical episodes in the vector space $\mathcal{V}$ are retrieved according to the Cosine Metric $\mathcal{S}_{\cos}$:
$$\mathcal{S}{\cos}(\mathbf{q}, \mathbf{v}{\mathcal{E}}) = \frac{\mathbf{q} \cdot \mathbf{v}_{\mathcal{E}}}{|\mathbf{q}|2 |\mathbf{v}{\mathcal{E}}|_2}$$
Episodes are filtered subject to the similarity threshold parameter $\tau$:
$$\mathcal{M}{\text{recalled}} = \left{ \mathcal{E} \in \mathcal{V} ;\middle|; \mathcal{S}{\cos}(\mathbf{q}, \mathbf{v}_{\mathcal{E}}) \ge \tau \right}, \quad \text{where } \tau = 0.78$$
Following Shinn et al. (2023), CogniHeal defines the optimization of the agent policy $\pi_\theta$ over iterative episodes $t \in {1, \dots, N}$. Rather than scalar gradient updates, the policy is conditioned on an expanding verbal buffer of semantic memories $\mathcal{H}_t$:
$$\mathcal{H}t = \mathcal{H}{t-1} \cup \left{ \left( c_{t-1}, e_{t-1}, \mathcal{R}{t-1}, \mathcal{K}{t-1} \right) \right}$$
Where:
The code generator synthesizes the next candidate patch $c_t$:
$$c_t \sim \pi_\theta\left( \cdot ;\middle|; \text{Prompt}, \mathcal{H}_t, \bigcup \mathcal{K} \right)$$
>= 3.11 (Tested on 3.11 and 3.12)--sandbox-mode docker)# Clone the repository
git clone https://github.com/EvoderDev/CogniHeal-Engine.git
cd CogniHeal-Engine
# Create and activate virtual environment
python -m venv venv
# On Linux/macOS:
source venv/bin/activate
# On Windows PowerShell:
.\venv\Scripts\Activate.ps1
# Install requirements
pip install -r requirements.txt
# Install CogniHeal in editable development mode (registers global commands: cogni, cg, cogniheal)
pip install -e .
[!TIP] Once installed with
pip install -e ., the executablescogniandcgare automatically registered in your global system PATH! You can simply typecogniorcganywhere in your terminal to launch the interactive REPL.
Create a .env file in the project root (or set system environment variables):
# Optional: OpenAI API Key for deep LLM reasoning and OpenAI embeddings
# (If omitted, CogniHeal automatically falls back to its deterministic pseudo-embedding and heuristic rule engine)
COGNIHEAL_OPENAI_API_KEY=sk-proj-your-api-key-here
# LLM Tunables
COGNIHEAL_LLM_MODEL=gpt-4o
COGNIHEAL_EMBEDDING_MODEL=text-embedding-3-small
COGNIHEAL_LLM_TEMPERATURE=0.2
# Self-Healing Bounds
COGNIHEAL_MAX_HEAL_ITERATIONS=5
COGNIHEAL_SIMILARITY_THRESHOLD=0.78
COGNIHEAL_TOP_K_MEMORIES=5
# Sandbox Security
COGNIHEAL_SANDBOX_MODE=subprocess
COGNIHEAL_SANDBOX_TIMEOUT_SECONDS=30
CogniHeal provides an interactive REPL modeled after modern autonomous coding tools, equipped with a persistent session context, live status spinners, and memory querying.
Type either of the global commands directly in your terminal:
cogni # Full brand command
# or:
cg # Ultra-fast short alias
# or:
cogniheal # Canonical package entrypoint
In the interactive REPL, the session stays active continuously across multiple turns without exiting:
Write a thread-safe LRU cache with TTL)./load <path> โ Load a Python file into active session memory/memory โ View recently stored episodic error memories/search <query> โ Dense semantic search across historical errors/stats โ View SQLite and ChromaDB persistence statistics/constraints โ List active hard constraint rules/history โ Review current session conversational turns/reset โ Clear current conversation context/benchmark โ Execute the 12-scenario chaos benchmark/clear โ Clear terminal screen/exit โ End the session gracefullyRun self-healing on a Python file that fails at runtime:
cogniheal run --code-file examples/sample_fix.py
____ _ _ _ _
/ ___|___ __ _ _ __ (_) | | | ___ __ _| |
| | / _ \ / _` | '_ \| | |_| |/ _ \/ _` | |
| |__| (_) | (_| | | | | | _ | __/ (_| | |
\____\___/ \__, |_| |_|_|_| |_|\___|\__,_|_|
|___/
โโ Self-Reflective Dynamic Episodic Memory Engine โโ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโ ๐ Source: sample_fix.py โโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ 1 import nonexistent_secret_package โ
โ 2 def calculate(): return 42 โ
โ 3 print(calculate()) โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โก EXECUTE (iter 1) โโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ Executing code (attempt 1/5)โฆ โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ ๐ REFLECT (iter 1) โโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ Execution failed. Running Reflexion analysisโฆ โ
โ stderr: ModuleNotFoundError: No module named 'nonexistent_secret_package' โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ ๐ง FIX (iter 1) โโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ ๐ง Applying fix (confidence: 30%) โ
โ Constraint: Always handle import_error errors explicitly. โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โก EXECUTE (iter 2) โโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ Executing code (attempt 2/5)โฆ โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
SUCCESS (iter 2) โโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ
Code executed successfully on attempt 2! โ
โ stdout: 42 โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
cogniheal run --task "Write a thread-safe singleton cache with TTL expiration"
Inspect the contents of the hybrid SQLite + ChromaDB memory store:
# Print high-level memory statistics
cogniheal memory stats
# List recent error episodes
cogniheal memory list --limit 10
# Perform dense semantic vector search
cogniheal memory search "IndexError list index out of range in loop"
# Display all active hard negative constraint rules
cogniheal memory constraints
Execute the built-in stress test against all 12 deliberate bug patterns:
cogniheal benchmark --max-iterations 5
Integrate CogniHeal-Engine directly into your existing agent pipelines, testing frameworks, or LLM evaluation harnesses:
from pathlib import Path
from cogniheal.config import settings
from cogniheal.memory.episodic_engine import EpisodicMemoryEngine
from cogniheal.agent.orchestrator import HealingOrchestrator, HealCycleEvent
# 1. Initialize the episodic memory substrate
settings.ensure_dirs()
memory = EpisodicMemoryEngine()
memory.initialise()
# 2. Define an event listener for live UI or logging
def telemetry_listener(event: HealCycleEvent) -> None:
print(f"[{event.stage.upper()}] Iteration {event.iteration}: {event.message}")
# 3. Instantiate the orchestrator
orchestrator = HealingOrchestrator(
memory_engine=memory,
max_iterations=5,
on_event=telemetry_listener,
)
# 4. Execute self-healing on buggy code
buggy_snippet = """
def parse_records(raw_data: list[dict]) -> float:
# Bug: missing key and potential zero division
total = sum(item["metric"] for item in raw_data)
return total / len(raw_data)
print(parse_records([]))
"""
result = orchestrator.run(
task_prompt="Safely parse and average metrics from dictionary list",
initial_code=buggy_snippet,
)
# 5. Access structured outputs
print(f"Heal Succeeded: {result.success}")
print(f"Total Iterations: {result.total_iterations}")
print(f"Final Sanitized Code:\n{result.final_code}")
print(f"Stdout:\n{result.final_result.stdout}")
# 6. Query memory for lessons stored from this run
related_episodes = memory.query("zero division in parse_records", top_k=1)
for ep in related_episodes:
print(f"Learned Rule: {ep.hard_constraint.description}")
memory.close()
CogniHeal combines the best of Vector Databases (associative semantic recall) and Relational ACID Databases (exact relational queries and auditability).
-- Main episodic records table
CREATE TABLE IF NOT EXISTS episodes (
episode_id TEXT PRIMARY KEY,
timestamp TEXT NOT NULL,
original_code TEXT NOT NULL,
task_prompt TEXT NOT NULL DEFAULT '',
raw_error TEXT NOT NULL,
stack_frames_json TEXT NOT NULL DEFAULT '[]',
rca_json TEXT NOT NULL,
reflection TEXT NOT NULL DEFAULT '',
fix_json TEXT NOT NULL,
constraint_json TEXT NOT NULL,
tags_json TEXT NOT NULL DEFAULT '[]',
success INTEGER NOT NULL DEFAULT 0,
total_iterations INTEGER NOT NULL DEFAULT 1
);
-- Normalized table for fast constraint queries
CREATE TABLE IF NOT EXISTS hard_constraints (
rule_id TEXT PRIMARY KEY,
episode_id TEXT NOT NULL,
description TEXT NOT NULL,
code_pattern TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
FOREIGN KEY (episode_id) REFERENCES episodes(episode_id) ON DELETE CASCADE
);
-- SQLite Full-Text Search (FTS5) index for rapid exact keyword matching
CREATE VIRTUAL TABLE IF NOT EXISTS episodes_fts
USING fts5(episode_id, raw_error, rca_summary, fix_description);
cogniheal_episodesCosineError: <RCA Summary>
Category: <syntax_error | type_error | runtime_error | import_error | logic_error | ...>
Root cause chain: <Cause Step 1> -> <Cause Step 2>
Fix: <Applied Patch Description>
Constraint: <Hard Negative Rule>
category: Taxonomy stringseverity: low | medium | high | criticalsuccess: "True" | "False"timestamp: ISO-8601 stringLocated at examples/benchmark_chaos.py, this test suite includes 12 deliberate, real-world runtime anomalies designed to stress-test every facet of CogniHeal:
| # | Scenario Title | Primary Failure | Root Cause Mechanism | Verification Condition |
|---|---|---|---|---|
| 01 | Type Mismatch Arithmetic | TypeError | Concatenating string literal to integer accumulator | Numbers parsed to float, correct sum |
| 02 | Missing Package Import | ModuleNotFoundError | Attempting to import non-existent package supercalc | Import eliminated or gracefully handled |
| 03 | Off-by-One Index Error | IndexError | Loop access items[i + 1] exceeding bounds | Array bound clamped to len(items) - 1 |
| 04 | Missing Dictionary Key | KeyError | Direct key subscript on sparse dictionary | Safe retrieval via .get() or key validation |
| 05 | Infinite Recursion | RecursionError | Missing base-case condition in recursive factorial | Guard clause if n <= 1: return 1 added |
| 06 | Attribute Error on String | AttributeError | Calling non-existent method .trimmed() on string | Correct method .strip() invoked |
| 07 | Invalid String to Int | ValueError | int("unknown") type conversion exception | Numeric validation with try-except fallback |
| 08 | Async Race Condition | RuntimeError | Multi-threaded shared counter corruption without lock | Threading lock threading.Lock() synchronisation |
| 09 | Division by Zero | ZeroDivisionError | Empty array passed into arithmetic average | Non-empty denominator validation check |
| 10 | File Not Found | FileNotFoundError | Opening non-existent configuration file path | Path.exists() check or fallback defaults |
| 11 | Unbound Local Variable | UnboundLocalError | Variable referenced before conditional assignment | Default variable initialisation before loop |
| 12 | Mutable Default Argument | RuntimeError | def f(x, target=[]) state leakage across calls | Default set to None with internal list allocation |
Running LLM-generated code poses severe host security risks. CogniHeal enforces a multi-tier defense-in-depth model:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HOST OPERATING SYSTEM โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ COGNIHEAL APPLICATION โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ โ SANDBOX CONTROLLER (executor.py) โ โ โ
โ โ โ โ โ โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ โ โ MODE: SUBPROCESS โ โ โ โ
โ โ โ โ โข Stripped Environment (Path/System only)โ โ โ โ
โ โ โ โ โข Process Group Timeout Kill โ โ โ โ
โ โ โ โ โข Ephemeral Temp Directory Disposal โ โ โ โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ โ โ MODE: DOCKER CONTAINER โ โ โ โ
โ โ โ โ โข --network=none (Full Network Airgap) โ โ โ โ
โ โ โ โ โข --memory=256m (OOM Protection) โ โ โ โ
โ โ โ โ โข --cpus=1 (CPU Starvation Prevention) โ โ โ โ
โ โ โ โ โข --pids-limit=64 (Fork Bomb Prevention) โ โ โ โ
โ โ โ โ โข Read-Only Volume Mount (/sandbox:ro) โ โ โ โ
โ โ โ โ โข Ephemeral Container Auto-Cleanup (--rm)โ โ โ โ
โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
subprocess, all credentials, API tokens, and secret environment variables (AWS_*, OPENAI_*, GITHUB_*) are stripped.--network=none, completely preventing socket creation, data exfiltration, or botnet staging.while True: os.fork()) or infinite memory allocations.sandbox_timeout_seconds (default: 30s). Rogue threads or infinite loops are forcefully terminated with SIGKILL.All configuration keys can be supplied via environment variables prefixed with COGNIHEAL_ or via a .env file:
| Environment Variable | Python Type | Default Value | Validation Constraints | Functional Description |
|---|---|---|---|---|
COGNIHEAL_OPENAI_API_KEY | str | "" | Optional | OpenAI API key for LLM reflection and embeddings |
COGNIHEAL_LLM_MODEL | str | "gpt-4o" | Valid Model ID | LLM model for critique, reflection, and code generation |
COGNIHEAL_EMBEDDING_MODEL | str | "text-embedding-3-small" | Valid Model ID | Model used for semantic error vector generation |
COGNIHEAL_LLM_TEMPERATURE | float | 0.2 | $0.0 \le T \le 2.0$ | Sampling temperature for reflection synthesis |
COGNIHEAL_LLM_MAX_TOKENS | int | 4096 | $\ge 256$ | Maximum token output limit for LLM responses |
COGNIHEAL_MAX_HEAL_ITERATIONS | int | 5 | $1 \le N \le 20$ | Maximum self-healing loops before giving up |
COGNIHEAL_SIMILARITY_THRESHOLD | float | 0.78 | $0.0 \le \tau \le 1.0$ | Minimum cosine similarity to inject past memories |
COGNIHEAL_TOP_K_MEMORIES | int | 5 | $\ge 1$ | Maximum number of episodic memories injected per prompt |
COGNIHEAL_SANDBOX_MODE | str | "subprocess" | "subprocess" | "docker" | Code execution backend |
COGNIHEAL_SANDBOX_TIMEOUT_SECONDS | int | 30 | $\ge 5$ | Hard wall-clock execution timeout in seconds |
COGNIHEAL_DOCKER_IMAGE | str | "python:3.12-slim" | Valid Docker tag | Base image used when Docker sandbox mode is active |
COGNIHEAL_DATA_DIR | Path | "cogniheal_data" | Path string | Base directory for SQLite and ChromaDB data |
COGNIHEAL_SQLITE_FILENAME | str | "episodic_memory.db" | File name | SQLite database file name |
COGNIHEAL_CHROMA_COLLECTION_NAME | str | "cogniheal_episodes" | Alphanumeric string | ChromaDB collection name |
COGNIHEAL_LOG_LEVEL | str | "INFO" | "DEBUG" | "INFO" | "WARNING" | CLI and internal logger verbosity |
CogniHeal maintains a comprehensive, zero-dependency unit test suite compatible with both unittest and pytest.
# Run tests with Python standard library runner:
python -m unittest discover -s tests -v
# Or run with pytest (if installed):
pytest tests/ -v --cov=cogniheal
test_analyse_source_syntax_error (test_ast_analyzer.TestASTAnalyzer) ... ok
test_analyse_source_valid_ast (test_ast_analyzer.TestASTAnalyzer) ... ok
test_detect_bare_except (test_ast_analyzer.TestASTAnalyzer) ... ok
test_detect_global_usage (test_ast_analyzer.TestASTAnalyzer) ... ok
test_detect_mutable_default (test_ast_analyzer.TestASTAnalyzer) ... ok
test_extract_error_type (test_ast_analyzer.TestASTAnalyzer) ... ok
test_get_function_source (test_ast_analyzer.TestASTAnalyzer) ... ok
test_parse_traceback_multiframe (test_ast_analyzer.TestASTAnalyzer) ... ok
test_embedding_fallback_deterministic (test_memory.TestMemorySubsystem) ... ok
test_memory_engine_crud (test_memory.TestMemorySubsystem) ... ok
test_models_to_semantic_text (test_memory.TestMemorySubsystem) ... ok
test_orchestrator_healing_flow (test_orchestrator.TestOrchestrator) ... ok
test_orchestrator_successful_code (test_orchestrator.TestOrchestrator) ... ok
test_sandbox_failure_captures_stderr (test_sandbox.TestSandboxExecutor) ... ok
test_sandbox_successful_execution (test_sandbox.TestSandboxExecutor) ... ok
test_sandbox_timeout_handling (test_sandbox.TestSandboxExecutor) ... ok
----------------------------------------------------------------------
Ran 16 tests in 2.497s โ OK (All tests passing)
If you use CogniHeal-Engine in your research, agent benchmarks, or production systems, please cite the following foundational literature:
@article{shinn2023reflexion,
title = {Reflexion: Language Agents with Verbal Reinforcement Learning},
author = {Noah Shinn and Federico Cassano and Edward Berman and Ashwin Gopinath and Karthik Narasimhan and Shunyu Yao},
journal = {Advances in Neural Information Processing Systems (NeurIPS)},
volume = {36},
year = {2023}
}
@article{tulving1972episodic,
title = {Episodic and Semantic Memory},
author = {Endel Tulving},
journal = {Organization of Memory},
pages = {381--403},
year = {1972},
publisher = {Academic Press}
}
@article{wei2022chain,
title = {Chain-of-Thought Prompting Elicits Reasoning in Large Language Models},
author = {Jason Wei and Xuezhi Wang and Dale Schuurmans and Maarten Bosma and Brian Ichter and Fei Xia and Ed Chi and Quoc Le and Denny Zhou},
journal = {Advances in Neural Information Processing Systems (NeurIPS)},
volume = {35},
pages = {24824--24837},
year = {2022}
}
This project is open-source under the MIT License.
Developed for autonomous AI engineering teams, agent developers, and researchers building resilient software architectures.
CogniHeal-Engine โ Because the best debugger is one that never forgets its mistakes.
โญ Star us on GitHub to support the project!