{"id":48538851,"url":"https://github.com/shenchengtsi/cortiloop","last_synced_at":"2026-04-13T13:01:13.717Z","repository":{"id":349893347,"uuid":"1204000638","full_name":"shenchengtsi/CortiLoop","owner":"shenchengtsi","description":"Bioinspired Agent Memory Engine — 7-layer brain-modeled memory lifecycle for AI agents. Just pass your LLM: CortiLoop(llm=agent.llm). Built-in embedding (bge-m3) + reranking (cross-encoder). 92% on LongMemEval.","archived":false,"fork":false,"pushed_at":"2026-04-08T02:26:04.000Z","size":121,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-08T03:26:44.129Z","etag":null,"topics":["agent-memory","bioinspired","hebbian-learning","knowledge-graph","llm","mcp","memory-management","nanobot","openclaw","vector-search"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/shenchengtsi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-04-07T15:39:59.000Z","updated_at":"2026-04-08T02:32:33.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/shenchengtsi/CortiLoop","commit_stats":null,"previous_names":["shenchengtsi/cortiloop"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/shenchengtsi/CortiLoop","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenchengtsi%2FCortiLoop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenchengtsi%2FCortiLoop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenchengtsi%2FCortiLoop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenchengtsi%2FCortiLoop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shenchengtsi","download_url":"https://codeload.github.com/shenchengtsi/CortiLoop/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenchengtsi%2FCortiLoop/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31753551,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-13T09:16:15.125Z","status":"ssl_error","status_checked_at":"2026-04-13T09:16:05.023Z","response_time":93,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent-memory","bioinspired","hebbian-learning","knowledge-graph","llm","mcp","memory-management","nanobot","openclaw","vector-search"],"created_at":"2026-04-08T03:09:08.397Z","updated_at":"2026-04-13T13:01:13.694Z","avatar_url":"https://github.com/shenchengtsi.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CortiLoop\n\n**Bioinspired Agent Memory Engine** — modeled after the full lifecycle of human brain memory.\n\n[Chinese Version / 中文文档](README_zh.md)\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)\n[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)\n[![Tests](https://img.shields.io/badge/tests-48%20passed-brightgreen.svg)]()\n[![Benchmark](https://img.shields.io/badge/LongMemEval-92%25-blue.svg)]()\n\n\u003e A memory plugin for AI agents. Works with [nanobot](https://github.com/HKUDS/nanobot), [openclaw](https://github.com/openclaw/openclaw), and any MCP-compatible agent framework.\n\n---\n\n## Why CortiLoop?\n\nMost agent memory systems are flat key-value stores or simple RAG. Real brains manage memories through **encoding, consolidation, retrieval, association, forgetting, and reconsolidation** — a full lifecycle that keeps knowledge accurate, relevant, and manageable over time.\n\nCortiLoop implements this full lifecycle:\n\n| Problem | How the brain solves it | How CortiLoop implements it |\n|---------|------------------------|---------------------------|\n| Noise flooding | Prefrontal attention gate | 5-dimension importance scoring — corrections \u0026 explicit marks get highest weight |\n| Stale knowledge | Reconsolidation window | Conflict detection with supersede / merge / coexist resolution |\n| Retrieval degradation | Forgetting curve | Ebbinghaus decay with differential rates per memory tier |\n| Fragmented recall | Pattern completion (CA3) | 4-route multi-probe search + Reciprocal Rank Fusion |\n| No association | Hebbian learning | Dynamic knowledge graph with spreading activation |\n| Information overload | Sleep consolidation | Background worker for periodic deep consolidation + pruning |\n\n## Architecture\n\n```\nAgent Input → [Attention Gate] → [Encoder] → [Hippocampal Store]\n                                                    │\n                                    ┌───────────────┤\n                                    ↓               ↓\n                            [Synaptic Consol.]  [Association Graph]\n                            (units→observations) (Hebbian edges)\n                                    │\n                                    ↓ (periodic)\n                            [Systems Consol.]\n                            (mental models, procedural detection)\n                                    │\n            [Multi-Probe Recall] ←──┘\n            (semantic+keyword+graph+temporal → RRF fusion)\n                                    │\n                            [Reconsolidation]     [Forgetting]\n                            (conflict detection)  (decay+prune)\n```\n\n### 7 Bioinspired Layers\n\n| Layer | Brain Analogy | What It Does |\n|-------|--------------|--------------|\n| **Attention Gate** | Prefrontal cortex + dopamine novelty signal | Scores importance; filters noise before encoding |\n| **Encoder** | Hippocampal encoding + entity binding | Extracts structured facts, entities, embeddings |\n| **Consolidation** | Sleep-driven hippocampus→neocortex transfer | Synaptic (immediate) + Systems (deep/periodic) |\n| **Association** | Hebbian learning + spreading activation | Knowledge graph with co-occurrence/temporal/causal edges |\n| **Retrieval** | CA3 pattern completion + multi-modal fusion | 4-route search + RRF + cross-encoder reranking |\n| **Forgetting** | Ebbinghaus curve + microglia pruning | Strength decay, deduplication, capacity management |\n| **Reconsolidation** | Memory destabilization + restabilization | Conflict detection, safe update, history preservation |\n\n## Features\n\n### Core (v0.1)\n- 7-layer bioinspired memory lifecycle\n- MCP server + nanobot plugin + openclaw skill\n- SQLite zero-dependency storage\n- Bilingual attention gate (English + Chinese)\n\n### Scale (v0.2)\n- Pluggable vector index (usearch HNSW / numpy fallback)\n- Ollama local LLM support (fully offline)\n- litellm universal adapter (100+ LLM providers)\n- Cross-encoder reranking\n- Background consolidation worker\n\n### Production (v0.3)\n- PostgreSQL + pgvector storage backend\n- Multi-tenant authentication (API key → namespace isolation)\n- LongMemEval benchmark harness (5 dimensions, 13 test cases)\n- Web visualization panel (D3.js knowledge graph + dashboard)\n- `BaseStore` abstraction for custom storage backends\n\n### Agent-First (v0.4)\n- **`MemoryLLM` Protocol** — Agent only provides `complete()` + `complete_json()`, nothing else\n- **Separated `Embedder` / `Reranker` Protocols** — chat, embedding, reranking are independent concerns\n- **Local sentence-transformers** — `BAAI/bge-m3` embedding + `BAAI/bge-reranker-v2-m3` cross-encoder, auto-downloads from HuggingFace, no API key needed\n- **4-level auto-detection** — user-provided → LLM built-in → sentence-transformers → hash fallback\n- **Environment variable config** — `CORTILOOP_EMBEDDING_MODEL` / `CORTILOOP_RERANKER_MODEL`\n- **48 tests** passing, **92% LongMemEval** benchmark score\n\n## Quick Start\n\n```bash\npip install cortiloop\n\n# Optional:\npip install cortiloop[local]       # sentence-transformers (recommended for quality)\npip install cortiloop[usearch]     # HNSW vector index\npip install cortiloop[postgres]    # PostgreSQL + pgvector\npip install cortiloop[all]         # Everything\n```\n\n### Use Your Agent's LLM (Recommended)\n\n```python\nfrom cortiloop import CortiLoop\n\n# Your agent already has an LLM — just pass it in\nloop = CortiLoop(llm=agent.llm)\n\nawait loop.retain(\"Alice is the PM of ProjectX, using React + TypeScript\")\nawait loop.retain(\"ok\")  # filtered out by attention gate\n\nresults = await loop.recall(\"What's Alice's project?\")\nfor r in results:\n    print(f\"[{r['type']}] {r['content']} (score: {r['score']:.3f})\")\n```\n\nYour LLM only needs **chat completion** — just 2 methods:\n\n```python\nfrom cortiloop import MemoryLLM\n\nclass MyAgentLLM:  # implements MemoryLLM protocol\n    async def complete(self, system: str, user: str, response_format: str = \"json\") -\u003e str: ...\n    async def complete_json(self, system: str, user: str) -\u003e dict: ...\n```\n\n**Embedding and reranking are handled automatically.** CortiLoop selects the best available backend:\n\n| Priority | Embedding | Reranking | When |\n|----------|-----------|-----------|------|\n| 1 | User-provided `embedder=` | User-provided `reranker=` | Explicit override |\n| 2 | LLM's built-in `embed()` | LLM's built-in `rerank()` | LLM supports it (e.g. LLMClient) |\n| 3 | `BAAI/bge-m3` (local) | `BAAI/bge-reranker-v2-m3` (local) | `sentence-transformers` installed |\n| 4 | Hash-based n-gram | Word-overlap scoring | Zero dependencies (fallback) |\n\nOverride with environment variables:\n\n```bash\nCORTILOOP_EMBEDDING_MODEL=BAAI/bge-small-en-v1.5      # lighter English-only model\nCORTILOOP_RERANKER_MODEL=cross-encoder/ms-marco-MiniLM-L-6-v2  # faster reranker\n```\n\nOr pass explicitly:\n\n```python\nloop = CortiLoop(llm=agent.llm, embedder=my_embedder, reranker=my_reranker)\n```\n\n### Standalone (with built-in LLM config)\n\n```python\nfrom cortiloop import CortiLoop, CortiLoopConfig\n\n# No existing LLM? CortiLoop can create one from config\nconfig = CortiLoopConfig(db_path=\"memory.db\")\nconfig.llm.provider = \"openai\"  # or \"ollama\", \"anthropic\", \"litellm\"\nloop = CortiLoop(config=config)\n```\n\n### With Ollama (fully local, no API key)\n\n```python\nconfig = CortiLoopConfig(db_path=\"memory.db\")\nconfig.llm.provider = \"ollama\"\nconfig.llm.model = \"llama3.1\"\nloop = CortiLoop(config=config)\n# Embedding handled by sentence-transformers or hash fallback — no config needed\n```\n\n### With PostgreSQL (production scale)\n\n```bash\npip install cortiloop[postgres]\n```\n\n```python\nconfig = CortiLoopConfig(\n    db_path=\"postgresql://user:pass@localhost:5432/cortiloop\",\n    storage_backend=\"postgres\",  # uses pgvector HNSW natively\n)\nloop = CortiLoop(config=config)\n```\n\n### MCP Server\n\n```bash\nexport OPENAI_API_KEY=sk-...\ncortiloop-mcp\n```\n\n### Visualization Panel\n\n```bash\ncortiloop-viz --db cortiloop.db --port 8765\n# Open http://localhost:8765\n```\n\nFeatures: force-directed knowledge graph, statistics dashboard, memory timeline, decay curve charts.\n\n### Benchmark\n\n```bash\n# Quick smoke test (13 hand-crafted cases, offline)\npython -m benchmarks.longmemeval --provider local\n\n# Official LongMemEval (500 questions from ICLR 2025 paper)\npython -m benchmarks.download_longmemeval --variant s   # download dataset first\npython -m benchmarks.longmemeval_official --variant s --provider openai\n\n# Run specific question types\npython -m benchmarks.longmemeval_official --variant s --types knowledge-update temporal-reasoning\n\n# Run a subset for quick iteration\npython -m benchmarks.longmemeval_official --variant s --max-items 20\n\n# Save results as JSON\npython -m benchmarks.longmemeval_official --variant s --output results.json\n```\n\n**Quick benchmark** (13 cases): Information Extraction, Temporal Reasoning, Knowledge Update, Associative Retrieval, Multi-Session Reasoning.\n\n**Official LongMemEval** (500 questions, 3 variants):\n| Variant | Sessions/Question | Tokens | Use Case |\n|---------|-------------------|--------|----------|\n| oracle | Answer-relevant only | ~small | Debugging |\n| s | ~40 | ~115K | Recommended |\n| m | ~500 | ~1.5M | Stress test |\n\n6 question types: single-session-user, single-session-assistant, single-session-preference, temporal-reasoning, knowledge-update, multi-session.\n\n## Integration\n\n### nanobot\n\n```json\n{\n  \"mcp\": {\n    \"servers\": {\n      \"cortiloop\": {\n        \"command\": \"python\",\n        \"args\": [\"-m\", \"cortiloop.adapters.mcp_server\"],\n        \"env\": { \"CORTILOOP_DB_PATH\": \"~/.nanobot/cortiloop.db\" }\n      }\n    }\n  }\n}\n```\n\n### openclaw\n\n```json\n{\n  \"cortiloop\": {\n    \"command\": \"python\",\n    \"args\": [\"-m\", \"cortiloop.adapters.mcp_server\"],\n    \"env\": { \"CORTILOOP_DB_PATH\": \"~/.openclaw/cortiloop.db\" }\n  }\n}\n```\n\n### nanobot Direct Plugin (Python)\n\n```python\nfrom cortiloop.adapters.nanobot_plugin import NanobotMemoryPlugin\n\nmemory = NanobotMemoryPlugin({\"db_path\": \"memory.db\"})\nawait memory.on_user_message(\"I prefer TypeScript strict mode\")\ncontext = await memory.on_before_response(\"Write a React component\")\n# context contains relevant memories to inject into prompt\n```\n\n## MCP Tools\n\n| Tool | Description |\n|------|-------------|\n| `cortiloop_retain` | Store text into long-term memory with attention gating |\n| `cortiloop_recall` | Multi-probe retrieval with RRF fusion |\n| `cortiloop_reflect` | Deep consolidation cycle (procedural detection + decay + pruning) |\n| `cortiloop_stats` | Memory system statistics |\n\n## Configuration\n\nSee [config.example.yaml](config.example.yaml) for all options.\n\n```yaml\nstorage_backend: \"sqlite\"       # \"sqlite\" | \"postgres\"\nvector_backend: \"auto\"          # \"auto\" | \"numpy\" | \"usearch\"\n\nattention_gate:\n  threshold: 0.2\n  weights:\n    correction: 0.30            # strongest signal\n    novelty: 0.25\n    explicit_mark: 0.20\n\nretrieval:\n  rerank_enabled: false         # cross-encoder reranking\n  rerank_top_k: 50\n\ndecay:\n  episodic_rate: 0.1            # fast: conversation details\n  semantic_rate: 0.03           # moderate: extracted knowledge\n  procedural_rate: 0.005        # slow: learned habits\n\nauth:\n  enabled: false\n  api_keys: {}                  # key → namespace mapping\n```\n\nEnvironment variables for embedding/reranking model selection:\n\n```bash\nCORTILOOP_EMBEDDING_MODEL=BAAI/bge-m3                    # default, multilingual\nCORTILOOP_RERANKER_MODEL=BAAI/bge-reranker-v2-m3         # default, multilingual\n```\n\n## Design Principles\n\n1. **Not everything is worth remembering** — attention gate filters noise\n2. **Write fast, refine slow** — immediate encoding + async consolidation\n3. **Accumulate, don't overwrite** — raw facts are immutable; observations evolve\n4. **Use it or lose it** — retrieval strengthens; disuse decays\n5. **Forgetting is a feature** — active pruning prevents retrieval degradation\n6. **Partial cue, full recall** — multi-probe search maximizes recall\n7. **Neurons that fire together wire together** — Hebbian graph strengthening\n8. **Safe updates, never delete originals** — reconsolidation with full history\n9. **Agent-first** — zero config when used as a plugin; Agent's LLM is the only requirement\n\n## Project Structure\n\n```\ncortiloop/\n├── encoding/          # Attention gate + encoder\n├── consolidation/     # Synaptic (immediate) + Systems (deep)\n├── retrieval/         # Multi-probe + RRF + reranking\n├── association/       # Hebbian knowledge graph\n├── forgetting/        # Ebbinghaus decay + pruner\n├── reconsolidation/   # Conflict detection + safe update\n├── storage/           # BaseStore ABC + SQLite + PostgreSQL\n├── llm/\n│   ├── protocol.py        # MemoryLLM / Embedder / Reranker protocols\n│   ├── client.py          # Built-in LLM client (OpenAI/Anthropic/Ollama/litellm)\n│   ├── local_client.py    # Offline rule-based client (for testing/benchmark)\n│   ├── local_embedder.py  # sentence-transformers embedding + cross-encoder\n│   └── builtin_embedder.py # Hash-based embedding fallback (zero deps)\n├── workers/           # Background consolidation worker\n├── adapters/          # MCP server + nanobot plugin + openclaw skill\n├── viz/               # Web visualization panel\n└── auth.py            # Multi-tenant authentication\nbenchmarks/\n├── longmemeval.py             # Quick benchmark (5 dimensions, 13 cases)\n├── longmemeval_official.py    # Official LongMemEval (500 questions, ICLR 2025)\n├── download_longmemeval.py    # Dataset downloader (HuggingFace)\n└── data/                      # Downloaded datasets (gitignored)\n```\n\n## Development\n\n```bash\ngit clone https://github.com/shenchengtsi/CortiLoop.git\ncd CortiLoop\npip install -e \".[dev]\"\npytest  # 48 tests\npython -m benchmarks.longmemeval --provider local  # 92% benchmark\n```\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshenchengtsi%2Fcortiloop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshenchengtsi%2Fcortiloop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshenchengtsi%2Fcortiloop/lists"}