Spaces:
Configuration error
Configuration error
Merge branch 'main' of https://huggingface.co/spaces/Yash030/agentmemory-python
Browse filesFiles changed (6)
- AGENTS.md+242-242
- README.md+494-494
- plugin/.claude-plugin/plugin.json+13-13
- plugin/plugin.json+15-15
- plugin/scripts/prompt_submit.py+56-56
- src/app.py
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242# agentmemory-python — Agent Instructions## What this project isA Python REST + WebSocket + MCP memory server backed by SQLite. No Node.js, no iii-engine, no Dolt. Agents use it to store observations, memories, lessons, and slots, and to retrieve context at session start.## Project layout```src/├── app.py Flask server — all endpoints, WebSocket broadcaster├── db.py SQLite StateKV — WAL mode, audit_log table├── functions.py Core business logic (observe, remember, search, context)├── search.py BM25 index + Gemini vector index + HybridSearch (RRF)└── viewer/└── index.html Single-file HTML dashboardsync.py HuggingFace dataset backup/restoreDockerfile HF Space container definitionstart.sh Boot: restore DB → start server → start sync looprequirements.txt flask, flask-sock, requests, websockets, python-dateutil, huggingface_hub```## Running```bashpip install -r requirements.txtpython src/app.py# Server on http://localhost:3111# Viewer at http://localhost:3111/viewer```No build step. No external database. SQLite file lives at `~/.agentmemory/agentmemory.db`.## Architecture### Storage — `src/db.py``StateKV` wraps a single SQLite file with two tables:- `kv_store(scope TEXT, key TEXT, value TEXT, PRIMARY KEY(scope, key))` — all data as JSON, namespaced by scope- `audit_log(id, ts, agent_id, message)` — write audit trail (replaces Dolt versioning)Key scopes (defined in `functions.py` `KV` class):| Scope | Content ||-------|---------|| `mem:sessions` | Session objects || `mem:obs:{session_id}` | Observations for a session || `mem:memories` | Long-term memories || `mem:lessons` | Lessons with confidence scores || `mem:slots` | Pinned memory slots || `mem:relations` | Knowledge graph edges || `mem:actions` | Work items / actions |### Business logic — `src/functions.py`Global state:- `_bm25_index` / `_vector_index` — in-memory search indexes, rebuilt from DB on startup if empty- `_hybrid_search` — combines BM25 + vector; only initialized when Gemini key is set- `_stream_broadcaster` — WebSocket broadcast callback injected by `app.py`**Observation pipeline:**```raw payload → strip_private_data() → build_synthetic_compression()→ stored in kv_store → BM25-indexed → vector-indexed (if key set)→ audit_log entry → WebSocket broadcast```**Memory versioning:** `remember()` checks Jaccard similarity against existing memories. If > 0.7 match found, new memory supersedes old (`isLatest=False` on old, `parentId` set on new).**Context compilation** (`context()`): assembles pinned slots → project profile → lessons (scored by confidence × project match) → past session summaries, capped at `TOKEN_BUDGET` tokens (estimated at `len/3`).**Lessons:** fingerprinted by SHA-256 of content. Duplicate saves strengthen confidence (`+0.1 × (1 - conf)`). Weekly decay reduces confidence by `decayRate × weeks`; soft-deleted at ≤ 0.1 confidence with 0 reinforcements.### Search — `src/search.py`- `SearchIndex`: BM25 with custom Porter stemmer. Persisted to `kv_store` in sharded 2MB chunks via `IndexPersistence`.- `VectorIndex`: cosine similarity over Gemini 768-dim embeddings stored as base64-encoded float32 arrays.- `HybridSearch`: fuses BM25 + vector scores with RRF (k=60, reciprocal rank fusion).### Server — `src/app.py`Boot order:1. Initialize `StateKV` (SQLite)2. Initialize embedding provider (Gemini if key set)3. Initialize `IndexPersistence`4. Rebuild BM25/vector index if empty (background thread)5. Start Flask on `III_REST_PORT` (default 3111)Auth: all endpoints check `AGENTMEMORY_SECRET` via timing-safe `hmac.compare_digest` Bearer token comparison if the env var is set. `/livez` is always open.WebSocket at `/stream/mem-live/viewer` broadcasts raw + compressed observations to connected viewers.## MCP ToolsThe server exposes 31 MCP tools via `GET /agentmemory/mcp/tools` (schema) and `POST /agentmemory/mcp/tools` (execution).| Tool | Description | Status ||------|-------------|--------|| `memory_recall` | Search past session observations | Working || `memory_save` | Save long-term memory (concepts/files as string or array) | Working || `memory_sessions` | List recent sessions | Working || `memory_sessions_list` | Retrieve all memory sessions | Working || `memory_smart_search` | Hybrid semantic+keyword search | Working || `memory_timeline` | Chronological observations | Working || `memory_observations` | Get observations for session | Working || `memory_profile` | User/project profile | Working || `memory_lessons` | List saved lessons | Working || `memory_lesson_save` | Save lesson from session | Working || `memory_lesson_recall` | Search lessons by query | Working || `memory_lesson_search` | Search lessons (keywords) | Working || `memory_consolidate` | Summarize sessions, extract memory | Working || `memory_reflect` | Reflect on session, update context | Working || `memory_diagnose` | Health check subsystems | Working || `memory_forget` | Delete memory/session/observations | Working || `memory_export` | Export all data as JSON | Working || `agent_observe` | Log agent execution observation | Working || `agent_remember` | Save agent memory to long-term | Working || `memory_antigravity_sync` | Sync Antigravity transcripts | Working || `memory_antigravity_sync_all` | Master sync: transcript + crystallize + reflect | Working || `memory_slot_list` | List all pinned memory slots | Working || `memory_slot_get` | Retrieve a specific pinned slot | Working || `memory_slot_create` | Create/overwrite pinned slot | Working || `memory_slot_append` | Append text content to slot | Working || `memory_slot_replace` | Replace slot content | Working || `memory_slot_delete` | Delete pinned memory slot | Working || `memory_action_create` | Create a new work item / action | Working || `memory_action_update` | Update fields of existing action | Working || `memory_frontier` | Get active/pending actions | Working || `memory_crystallize` | Summarize session observations | Working |**MCP stdio wrapper:** `src/mcp_stdio.py` reads `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET` from environment variables dynamically.## Consistency rules**When adding a REST endpoint:**1. Add the route in `src/app.py`2. Update `API Reference` section in `README.md`3. Add the MCP tool in `src/app.py` MCP dispatch if it should be agent-callable**When adding an MCP tool:**1. Add the schema to the `GET /mcp/tools` response in `src/app.py`2. Add the handler case to the `POST /mcp/tools` dispatch in `src/app.py`3. Update the tool table in `README.md`4. Update `AGENTS.md` tool list**When changing data scopes:**1. Update the `KV` class in `src/functions.py`2. Update the scope table in this file## Code patterns### Adding a new KV scope```pythonclass KV:your_scope = "mem:your-scope"@staticmethoddef your_dynamic_scope(id: str) -> str:return f"mem:your-scope:{id}"```### Adding a REST endpoint```python@app.route('/agentmemory/your-path', methods=['POST'])def your_endpoint():if AGENTMEMORY_SECRET:auth = request.headers.get('Authorization', '')if not hmac.compare_digest(auth, f'Bearer {AGENTMEMORY_SECRET}'):return jsonify({'error': 'Unauthorized'}), 401body = request.get_json(silent=True) or {}# validate fields explicitly — never pass raw body to functionsresult = your_function(kv, body.get('field'))return jsonify(result), 200```### Adding an MCP tool schemaIn the `GET /mcp/tools` handler, add to the tools list:```python{"name": "memory_your_tool","description": "What it does","inputSchema": {"type": "object","properties": {"query": {"type": "string", "description": "..."}},"required": ["query"]}}```In the `POST /mcp/tools` handler, add a case:```pythonelif tool_name == 'memory_your_tool':query = args.get('query', '')result = your_function(kv, query)return jsonify({'content': [{'type': 'text', 'text': json.dumps(result)}]})```## Environment variables| Variable | Default | Purpose ||----------|---------|---------|| `III_REST_PORT` / `PORT` | `3111` | Server port || `GEMINI_API_KEY` / `GOOGLE_API_KEY` | — | Enables vector search + Gemini LLM || `AGENTMEMORY_SECRET` | — | Bearer token auth || `AGENT_ID` | — | Default agent ID || `AGENTMEMORY_AGENT_SCOPE=isolated` | — | Filter data to current agent || `MAX_OBS_PER_SESSION` | `500` | Observations hard cap || `TOKEN_BUDGET` | `2000` | Context compilation cap || `GRAPH_EXTRACTION_ENABLED` | `false` | Graph extraction (needs LLM) || `CONSOLIDATION_ENABLED` | `false` | Consolidation (needs LLM) || `AGENTMEMORY_AUTO_COMPRESS` | `false` | LLM compression || `HF_TOKEN` | — | HuggingFace sync || `AGENTMEMORY_DATASET_REPO` | — | HF dataset repo for backup |## HuggingFace Space deploymentData flow: `agentmemory.db` (SQLite) ↔ `sync.py` ↔ HF dataset repo.`sync.py` uses mtime fingerprinting (`_quick_hash`) to detect changes before uploading. Backup only runs when the DB actually changed. Restore uses `hf_hub_download` for targeted file fetches rather than full `snapshot_download`.`start.sh` sequence:1. Restore `agentmemory.db` from dataset repo2. Start `python src/app.py` in background3. Run `sync.py` in a loop (backup every ~60s if changed)## Viewer — `src/viewer/index.html`Single-file HTML dashboard, served directly by Flask at `/viewer`. No build step, no bundler.Tabs: Dashboard, Sessions, Memories, Graph, Timeline, Lessons, Slots, Replay.**Graph tab** (`loadGraph()`): fetches sessions + memories, groups by `project` path into folder nodes. Edges connect folders that share concepts or parent path segments. Each folder node gets a unique color via `folderColor(id)` — a hash-to-hex function that converts the folder path string into a distinct HSL color. The simulation uses force-directed physics with per-node-count repulsion tuning.## No tests yetNo test runner is configured. When adding tests, use `pytest` — it's the standard Python choice and requires no extra config for basic test discovery (`test_*.py` files).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242# agentmemory-python — Agent Instructions## What this project isA Python REST + WebSocket + MCP memory server backed by SQLite. No Node.js, no iii-engine, no Dolt. Agents use it to store observations, memories, lessons, and slots, and to retrieve context at session start.## Project layout```src/├── app.py Flask server — all endpoints, WebSocket broadcaster├── db.py SQLite StateKV — WAL mode, audit_log table├── functions.py Core business logic (observe, remember, search, context)├── search.py BM25 index + Gemini vector index + HybridSearch (RRF)└── viewer/└── index.html Single-file HTML dashboardsync.py HuggingFace dataset backup/restoreDockerfile HF Space container definitionstart.sh Boot: restore DB → start server → start sync looprequirements.txt flask, flask-sock, requests, websockets, python-dateutil, huggingface_hub```## Running```bashpip install -r requirements.txtpython src/app.py# Server on http://localhost:3111# Viewer at http://localhost:3111/viewer```No build step. No external database. SQLite file lives at `~/.agentmemory/agentmemory.db`.## Architecture### Storage — `src/db.py``StateKV` wraps a single SQLite file with two tables:- `kv_store(scope TEXT, key TEXT, value TEXT, PRIMARY KEY(scope, key))` — all data as JSON, namespaced by scope- `audit_log(id, ts, agent_id, message)` — write audit trail (replaces Dolt versioning)Key scopes (defined in `functions.py` `KV` class):| Scope | Content ||-------|---------|| `mem:sessions` | Session objects || `mem:obs:{session_id}` | Observations for a session || `mem:memories` | Long-term memories || `mem:lessons` | Lessons with confidence scores || `mem:slots` | Pinned memory slots || `mem:relations` | Knowledge graph edges || `mem:actions` | Work items / actions |### Business logic — `src/functions.py`Global state:- `_bm25_index` / `_vector_index` — in-memory search indexes, rebuilt from DB on startup if empty- `_hybrid_search` — combines BM25 + vector; only initialized when Gemini key is set- `_stream_broadcaster` — WebSocket broadcast callback injected by `app.py`**Observation pipeline:**```raw payload → strip_private_data() → build_synthetic_compression()→ stored in kv_store → BM25-indexed → vector-indexed (if key set)→ audit_log entry → WebSocket broadcast```**Memory versioning:** `remember()` checks Jaccard similarity against existing memories. If > 0.7 match found, new memory supersedes old (`isLatest=False` on old, `parentId` set on new).**Context compilation** (`context()`): assembles pinned slots → project profile → lessons (scored by confidence × project match) → past session summaries, capped at `TOKEN_BUDGET` tokens (estimated at `len/3`).**Lessons:** fingerprinted by SHA-256 of content. Duplicate saves strengthen confidence (`+0.1 × (1 - conf)`). Weekly decay reduces confidence by `decayRate × weeks`; soft-deleted at ≤ 0.1 confidence with 0 reinforcements.### Search — `src/search.py`- `SearchIndex`: BM25 with custom Porter stemmer. Persisted to `kv_store` in sharded 2MB chunks via `IndexPersistence`.- `VectorIndex`: cosine similarity over Gemini 768-dim embeddings stored as base64-encoded float32 arrays.- `HybridSearch`: fuses BM25 + vector scores with RRF (k=60, reciprocal rank fusion).### Server — `src/app.py`Boot order:1. Initialize `StateKV` (SQLite)2. Initialize embedding provider (Gemini if key set)3. Initialize `IndexPersistence`4. Rebuild BM25/vector index if empty (background thread)5. Start Flask on `III_REST_PORT` (default 3111)Auth: all endpoints check `AGENTMEMORY_SECRET` via timing-safe `hmac.compare_digest` Bearer token comparison if the env var is set. `/livez` is always open.WebSocket at `/stream/mem-live/viewer` broadcasts raw + compressed observations to connected viewers.## MCP ToolsThe server exposes 31 MCP tools via `GET /agentmemory/mcp/tools` (schema) and `POST /agentmemory/mcp/tools` (execution).| Tool | Description | Status ||------|-------------|--------|| `memory_recall` | Search past session observations | Working || `memory_save` | Save long-term memory (concepts/files as string or array) | Working || `memory_sessions` | List recent sessions | Working || `memory_sessions_list` | Retrieve all memory sessions | Working || `memory_smart_search` | Hybrid semantic+keyword search | Working || `memory_timeline` | Chronological observations | Working || `memory_observations` | Get observations for session | Working || `memory_profile` | User/project profile | Working || `memory_lessons` | List saved lessons | Working || `memory_lesson_save` | Save lesson from session | Working || `memory_lesson_recall` | Search lessons by query | Working || `memory_lesson_search` | Search lessons (keywords) | Working || `memory_consolidate` | Summarize sessions, extract memory | Working || `memory_reflect` | Reflect on session, update context | Working || `memory_diagnose` | Health check subsystems | Working || `memory_forget` | Delete memory/session/observations | Working || `memory_export` | Export all data as JSON | Working || `agent_observe` | Log agent execution observation | Working || `agent_remember` | Save agent memory to long-term | Working || `memory_antigravity_sync` | Sync Antigravity transcripts | Working || `memory_antigravity_sync_all` | Master sync: transcript + crystallize + reflect | Working || `memory_slot_list` | List all pinned memory slots | Working || `memory_slot_get` | Retrieve a specific pinned slot | Working || `memory_slot_create` | Create/overwrite pinned slot | Working || `memory_slot_append` | Append text content to slot | Working || `memory_slot_replace` | Replace slot content | Working || `memory_slot_delete` | Delete pinned memory slot | Working || `memory_action_create` | Create a new work item / action | Working || `memory_action_update` | Update fields of existing action | Working || `memory_frontier` | Get active/pending actions | Working || `memory_crystallize` | Summarize session observations | Working |**MCP stdio wrapper:** `src/mcp_stdio.py` reads `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET` from environment variables dynamically.## Consistency rules**When adding a REST endpoint:**1. Add the route in `src/app.py`2. Update `API Reference` section in `README.md`3. Add the MCP tool in `src/app.py` MCP dispatch if it should be agent-callable**When adding an MCP tool:**1. Add the schema to the `GET /mcp/tools` response in `src/app.py`2. Add the handler case to the `POST /mcp/tools` dispatch in `src/app.py`3. Update the tool table in `README.md`4. Update `AGENTS.md` tool list**When changing data scopes:**1. Update the `KV` class in `src/functions.py`2. Update the scope table in this file## Code patterns### Adding a new KV scope```pythonclass KV:your_scope = "mem:your-scope"@staticmethoddef your_dynamic_scope(id: str) -> str:return f"mem:your-scope:{id}"```### Adding a REST endpoint```python@app.route('/agentmemory/your-path', methods=['POST'])def your_endpoint():if AGENTMEMORY_SECRET:auth = request.headers.get('Authorization', '')if not hmac.compare_digest(auth, f'Bearer {AGENTMEMORY_SECRET}'):return jsonify({'error': 'Unauthorized'}), 401body = request.get_json(silent=True) or {}# validate fields explicitly — never pass raw body to functionsresult = your_function(kv, body.get('field'))return jsonify(result), 200```### Adding an MCP tool schemaIn the `GET /mcp/tools` handler, add to the tools list:```python{"name": "memory_your_tool","description": "What it does","inputSchema": {"type": "object","properties": {"query": {"type": "string", "description": "..."}},"required": ["query"]}}```In the `POST /mcp/tools` handler, add a case:```pythonelif tool_name == 'memory_your_tool':query = args.get('query', '')result = your_function(kv, query)return jsonify({'content': [{'type': 'text', 'text': json.dumps(result)}]})```## Environment variables| Variable | Default | Purpose ||----------|---------|---------|| `III_REST_PORT` / `PORT` | `3111` | Server port || `GEMINI_API_KEY` / `GOOGLE_API_KEY` | — | Enables vector search + Gemini LLM || `AGENTMEMORY_SECRET` | — | Bearer token auth || `AGENT_ID` | — | Default agent ID || `AGENTMEMORY_AGENT_SCOPE=isolated` | — | Filter data to current agent || `MAX_OBS_PER_SESSION` | `500` | Observations hard cap || `TOKEN_BUDGET` | `2000` | Context compilation cap || `GRAPH_EXTRACTION_ENABLED` | `false` | Graph extraction (needs LLM) || `CONSOLIDATION_ENABLED` | `false` | Consolidation (needs LLM) || `AGENTMEMORY_AUTO_COMPRESS` | `false` | LLM compression || `HF_TOKEN` | — | HuggingFace sync || `AGENTMEMORY_DATASET_REPO` | — | HF dataset repo for backup |## HuggingFace Space deploymentData flow: `agentmemory.db` (SQLite) ↔ `sync.py` ↔ HF dataset repo.`sync.py` uses mtime fingerprinting (`_quick_hash`) to detect changes before uploading. Backup only runs when the DB actually changed. Restore uses `hf_hub_download` for targeted file fetches rather than full `snapshot_download`.`start.sh` sequence:1. Restore `agentmemory.db` from dataset repo2. Start `python src/app.py` in background3. Run `sync.py` in a loop (backup every ~60s if changed)## Viewer — `src/viewer/index.html`Single-file HTML dashboard, served directly by Flask at `/viewer`. No build step, no bundler.Tabs: Dashboard, Sessions, Memories, Graph, Timeline, Lessons, Slots, Replay.**Graph tab** (`loadGraph()`): fetches sessions + memories, groups by `project` path into folder nodes. Edges connect folders that share concepts or parent path segments. Each folder node gets a unique color via `folderColor(id)` — a hash-to-hex function that converts the folder path string into a distinct HSL color. The simulation uses force-directed physics with per-node-count repulsion tuning.## No tests yetNo test runner is configured. When adding tests, use `pytest` — it's the standard Python choice and requires no extra config for basic test discovery (`test_*.py` files).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494---title: AgentMemory Pythonemoji: 🧠colorFrom: bluecolorTo: indigosdk: dockerpinned: false---<h1 align="center">agentmemory-python</h1><p align="center"><strong>Persistent memory for AI coding agents — pure Python, zero external databases.</strong><br/>Works with Claude Code, Cursor, Cline, Windsurf, Gemini CLI, and any MCP client.</p><p align="center"><a href="README.md">English</a> |<a href="READMEs/README.zh-CN.md">简体中文</a> |<a href="READMEs/README.ja-JP.md">日本語</a> |<a href="READMEs/README.ko-KR.md">한국어</a> |<a href="READMEs/README.es-ES.md">Español</a> |<a href="READMEs/README.hi-IN.md">हिन्दी</a> |<a href="READMEs/README.pt-BR.md">Português</a> |<a href="READMEs/README.fr-FR.md">Français</a> |<a href="READMEs/README.de-DE.md">Deutsch</a></p><p align="center"><img src="https://img.shields.io/badge/Python-3.10%2B-3776AB?style=for-the-badge&logo=python&logoColor=white" alt="Python 3.10+" /><img src="https://img.shields.io/badge/SQLite-WAL-003B57?style=for-the-badge&logo=sqlite&logoColor=white" alt="SQLite WAL" /><img src="https://img.shields.io/badge/Flask-3.0-000000?style=for-the-badge&logo=flask&logoColor=white" alt="Flask 3.0" /><img src="https://img.shields.io/badge/MCP-Compatible-6B21A8?style=for-the-badge" alt="MCP Compatible" /><img src="https://img.shields.io/badge/HuggingFace-Space-FF9D00?style=for-the-badge&logo=huggingface&logoColor=white" alt="HuggingFace Space" /></p><p align="center"><a href="#quick-start">Quick Start</a> •<a href="#features">Features</a> •<a href="#mcp-integration">MCP</a> •<a href="#api-reference">API</a> •<a href="#configuration">Config</a> •<a href="#deploy-to-huggingface">Deploy</a> •<a href="#viewer">Viewer</a> •<a href="#architecture">Architecture</a></p>---## What Is This?**agentmemory-python** is a Python reimplementation of the [agentmemory](https://github.com/rohitg00/agentmemory) persistent memory server. It exposes a REST API, WebSocket stream, and MCP tools endpoint that AI coding agents use to store and retrieve session observations, long-term memories, lessons, and pinned memory slots.Key differences from the Node.js original:- **No Node.js or iii-engine** — runs with plain `python src/app.py`- **SQLite instead of Dolt** — single file, WAL mode, instant startup- **HuggingFace Space ready** — deploys in one click, data synced to an HF dataset repo- **Same REST + MCP wire format** — drop-in for any agent already wired to agentmemoryYour agent captures every tool call, stores them as observations, compresses them into searchable memory, and injects the right context at the start of every new session — automatically.---## Quick Start### Run locally```bash# Clonegit clone https://github.com/Yash030/agentmemory-python.gitcd agentmemory-python# Install dependencies (no build step)pip install -r requirements.txt# Start the serverpython src/app.py```Server starts on **http://localhost:3111**. Open the viewer at http://localhost:3111/viewer.### Verify it works```bash# Health checkcurl http://localhost:3111/agentmemory/livez# {"status": "ok"}# Save a memorycurl -X POST http://localhost:3111/agentmemory/remember \-H "Content-Type: application/json" \-d '{"content": "JWT auth uses jose middleware in src/middleware/auth.ts", "concepts": ["auth", "jwt"]}'# Recall itcurl -X POST http://localhost:3111/agentmemory/search \-H "Content-Type: application/json" \-d '{"query": "authentication middleware", "limit": 5}'```---## Features| Feature | Status | Notes ||---------|--------|-------|| REST API — sessions, memories, observations | ✅ | Full surface || WebSocket live stream | ✅ | `/stream/mem-live/viewer` || MCP tools endpoint | ✅ | 31 tools || Built-in HTML viewer | ✅ | Real-time dashboard at `/viewer` || BM25 keyword search | ✅ | Always on, no API key needed || Hybrid BM25 + vector search | ✅ | Requires `GEMINI_API_KEY` || 4-tier memory consolidation | ⚙️ | `CONSOLIDATION_ENABLED=true` + LLM key || Knowledge graph extraction | ⚙️ | `GRAPH_EXTRACTION_ENABLED=true` + LLM key || LLM observation compression | ⚙️ | `AGENTMEMORY_AUTO_COMPRESS=true` + LLM key || Lessons with confidence decay | ✅ | Fingerprinted, auto-strengthen on repeat || Memory slots (pinned context) | ✅ | CRUD + auto-reflect || Session replay | ✅ | Full timeline in viewer || Audit log | ✅ | Tracks every write with agent_id + timestamp || HuggingFace Space deploy | ✅ | One-click, data synced to dataset repo || Privacy filtering | ✅ | Strips API keys, tokens before storage |### 4-Tier Memory ModelInspired by how human memory works — raw experience → compressed episodes → extracted facts → learned patterns.| Tier | What | When ||------|------|------|| **Working** | Raw observations from tool use | Every tool call || **Episodic** | Compressed session summaries | Session end || **Semantic** | Extracted facts and patterns | Consolidation || **Procedural** | Workflows and decision patterns | Consolidation |---## MCP IntegrationWire agentmemory-python into your agent's MCP config. It speaks the same MCP protocol as the Node.js original.### Most agents (Cursor, Claude Desktop, Cline, Windsurf)```json{"mcpServers": {"agentmemory": {"command": "npx","args": ["-y", "@agentmemory/mcp"],"env": {"AGENTMEMORY_URL": "http://localhost:3111"}}}}```### Claude CodePaste this prompt and your agent will wire everything:```Start agentmemory-python: run `python src/app.py` from the agentmemory-python directory.Then add this MCP server to ~/.claude.json under mcpServers:{"agentmemory": {"command": "npx","args": ["-y", "@agentmemory/mcp"],"env": { "AGENTMEMORY_URL": "http://localhost:3111" }}}Verify with: curl http://localhost:3111/agentmemory/livezOpen the viewer at: http://localhost:3111/viewer```### Available MCP Tools (31)| Tool | Description ||------|-------------|| `memory_save` | Save a long-term insight, decision, or pattern || `memory_recall` | Search past observations by keyword || `memory_smart_search` | Hybrid BM25 + vector semantic search || `memory_sessions` | List recent sessions || `memory_sessions_list` | Retrieve all memory sessions || `memory_timeline` | Chronological observations for a session || `memory_observations` | Observations for a session || `memory_profile` | Per-project concept + file profile || `memory_lessons` | List active lessons with confidence scores || `memory_lesson_save` | Save a lesson (duplicate saves strengthen it) || `memory_lesson_recall` | Search lessons by query || `memory_lesson_search` | Search lessons by keywords || `memory_consolidate` | Run 4-tier memory consolidation || `memory_reflect` | Reflect on session, update context || `memory_diagnose` | Health check across all subsystems || `memory_forget` | Delete memory, session, or observations || `memory_export` | Export all memory data as JSON || `agent_observe` | Log agent execution observation || `agent_remember` | Save agent memory to long-term storage || `memory_antigravity_sync` | Sync Antigravity transcripts to memory || `memory_antigravity_sync_all` | Master sync: transcript + crystallize + reflect || `memory_slot_list` | List all pinned memory slots || `memory_slot_get` | Retrieve a specific pinned memory slot || `memory_slot_create` | Create/overwrite a pinned memory slot || `memory_slot_append` | Append text content to a pinned memory slot || `memory_slot_replace` | Replace pinned memory slot content || `memory_slot_delete` | Delete a pinned memory slot || `memory_action_create` | Create a new work item / action || `memory_action_update` | Update fields of an existing action || `memory_frontier` | Get active and pending actions sorted by priority || `memory_crystallize` | Crystallize/summarize observations in a session |---## API ReferenceBase URL: `http://localhost:3111/agentmemory`### Health| Method | Path | Description ||--------|------|-------------|| `GET` | `/livez` | Liveness probe — no auth required |### Sessions| Method | Path | Description ||--------|------|-------------|| `POST` | `/session/start` | Start a new session || `POST` | `/session/end` | End a session || `POST` | `/session/commit` | Commit session with summary || `GET` | `/sessions` | List all sessions |### Observations| Method | Path | Description ||--------|------|-------------|| `POST` | `/observe` | Ingest a hook event observation || `POST` | `/agent/observe` | Simplified observe for direct agent use || `GET` | `/observations` | List observations (`?session_id=`) || `POST` | `/timeline` | Chronological observation window |### Memories| Method | Path | Description ||--------|------|-------------|| `POST` | `/remember` | Save long-term memory || `POST` | `/agent/remember` | Simplified remember || `POST` | `/forget` | Delete memory / session / observations || `POST` | `/search` | BM25 + vector search || `POST` | `/context` | Compile context for a session + project || `GET` | `/memories` | List memories (`?latest=true&limit=N`) || `POST` | `/evolve` | Create a new memory version |### Lessons| Method | Path | Description ||--------|------|-------------|| `GET` | `/lessons` | List lessons || `POST` | `/lessons` | Create lesson || `POST` | `/lessons/search` | Search lessons || `POST` | `/lessons/strengthen` | Reinforce an existing lesson |### Slots| Method | Path | Description ||--------|------|-------------|| `GET` | `/slots` | List all pinned slots || `POST` | `/slot` | Create or update a slot || `GET` | `/slot` | Get slot by name || `DELETE` | `/slot` | Delete a slot || `POST` | `/slot/reflect` | Auto-populate from session observations |### Graph + Profile| Method | Path | Description ||--------|------|-------------|| `GET` | `/relations` | Knowledge graph edges || `POST` | `/relations` | Add a relation || `GET` | `/profile` | Project profile (top concepts, files) |### Actions| Method | Path | Description ||--------|------|-------------|| `GET` | `/actions` | List actions || `POST` | `/actions` | Create an action || `PATCH` | `/actions/<id>` | Update action status / fields || `GET` | `/frontier` | Pending actions sorted by priority || `GET` | `/insights` | List insights |### Replay| Method | Path | Description ||--------|------|-------------|| `GET` | `/replay/sessions` | Sessions list for replay tab || `GET` | `/replay/load` | Full session + observations (`?sessionId=`) |### MCP| Method | Path | Description ||--------|------|-------------|| `GET` | `/mcp/tools` | MCP tool schema list || `POST` | `/mcp/tools` | MCP tool call dispatch |---## ConfigurationCreate `~/.agentmemory/.env` (no `export` prefix needed):```env# Server portIII_REST_PORT=3111# Vector search — enables Gemini 768-dim embeddingsGEMINI_API_KEY=your-gemini-key# LLM for compression / consolidation / graph extraction# Any one of these enables LLM features:ANTHROPIC_API_KEY=your-anthropic-key# OPENAI_API_KEY=your-openai-key# GEMINI_API_KEY=your-key (same key as above works for both)# LLM-powered features (disabled by default — spend tokens)CONSOLIDATION_ENABLED=trueGRAPH_EXTRACTION_ENABLED=trueAGENTMEMORY_AUTO_COMPRESS=true# Context injection limitsTOKEN_BUDGET=2000MAX_OBS_PER_SESSION=500# Auth — set to require Bearer token on all endpointsAGENTMEMORY_SECRET=your-secret# Agent scope isolationAGENT_ID=my-agentAGENTMEMORY_AGENT_SCOPE=isolated # only see this agent's data# HuggingFace syncHF_TOKEN=your-hf-tokenAGENTMEMORY_DATASET_REPO=username/agentmemory-data```### Full Variable Reference| Variable | Default | Purpose ||----------|---------|---------|| `III_REST_PORT` / `PORT` | `3111` | API server port || `GEMINI_API_KEY` / `GOOGLE_API_KEY` | — | Enables 768-dim vector search || `AGENTMEMORY_SECRET` | — | Bearer token auth on all endpoints || `AGENT_ID` | — | Default agent ID for scope isolation || `AGENTMEMORY_AGENT_SCOPE=isolated` | — | Filters data to current `AGENT_ID` || `MAX_OBS_PER_SESSION` | `500` | Hard cap on observations per session || `TOKEN_BUDGET` | `2000` | Max tokens in compiled context || `GRAPH_EXTRACTION_ENABLED` | `false` | Knowledge graph (needs LLM) || `CONSOLIDATION_ENABLED` | `false` | Memory consolidation (needs LLM) || `AGENTMEMORY_AUTO_COMPRESS` | `false` | LLM observation compression |---## ViewerBuilt-in dashboard at **http://localhost:3111/viewer**.| Tab | What You See ||-----|-------------|| **Dashboard** | Session stats, memory counts, recent activity || **Sessions** | Browse sessions, inspect observations || **Memories** | Search, filter, and read long-term memories || **Graph** | Project folder visualization — nodes = folders, edges = shared concepts or parent path || **Timeline** | Per-session chronological observation view || **Lessons** | Confidence-scored lessons with decay tracking || **Slots** | Pinned memory slots editor || **Replay** | Scrub through past sessions frame by frame |---## Deploy to HuggingFaceThis project is designed to run as a HuggingFace Space. Data is stored in an HF dataset repo and restored on every boot — so no persistent disk is needed.### Setup1. Fork this repo as a HuggingFace Space (SDK: Docker)2. Create a dataset repo (e.g. `your-username/agentmemory-data`)3. Add Space secrets in the HF dashboard:| Secret | Value ||--------|-------|| `HF_TOKEN` | Your HF write token || `AGENTMEMORY_DATASET_REPO` | `your-username/agentmemory-data` || `AGENTMEMORY_SECRET` | A random secret (optional but recommended) || `GEMINI_API_KEY` | Gemini key (optional, enables vector search) |4. The Space boots, restores `agentmemory.db` from the dataset repo, and starts the server### How sync works`sync.py` uses mtime fingerprinting — it only uploads when the database actually changed, so there are no unnecessary uploads during idle periods.```bash# Manual backuppython sync.py# Environment for syncHF_TOKEN=...AGENTMEMORY_DATASET_REPO=username/agentmemory-data```---## Architecture```agentmemory-python/├── src/│ ├── app.py Flask server — all endpoints, WebSocket broadcaster│ ├── db.py SQLite StateKV — WAL mode, audit_log table│ ├── functions.py Core logic — observe, remember, search, context│ ├── search.py BM25 + Gemini vector index + HybridSearch (RRF)│ └── viewer/│ └── index.html Single-file HTML dashboard (no build step)├── sync.py HuggingFace dataset backup/restore├── Dockerfile HF Space container├── start.sh Boot script (restore → start server → start sync)└── requirements.txt 6 Python dependencies, no external DB required```### Database layoutTwo SQLite tables in `~/.agentmemory/agentmemory.db`:```sql-- All data lives here, namespaced by scopekv_store (scope TEXT NOT NULL, -- e.g. "mem:sessions", "mem:obs:{session_id}"key TEXT NOT NULL,value TEXT NOT NULL, -- JSON-serializedPRIMARY KEY (scope, key))-- Audit trail replaces Dolt git versioningaudit_log (id INTEGER PRIMARY KEY AUTOINCREMENT,ts INTEGER NOT NULL, -- unix millisagent_id TEXT NOT NULL,message TEXT NOT NULL)```### Search pipeline```Query→ BM25 (always) — Porter-stemmed keyword matching→ Vector (if Gemini key) — 768-dim cosine similarity→ RRF fusion — Reciprocal Rank Fusion (k=60)→ Session diversify — max 3 results per session→ Return top-K```---## vs Original agentmemory| | agentmemory (Node.js) | agentmemory-python ||---|---|---|| Runtime | Node.js 20+ | Python 3.10+ || Storage | Dolt SQL (git-versioned MySQL) | SQLite WAL (single file) || Engine dependency | iii-engine (separate binary) | None — just Flask || Embeddings | 6 providers + local `@xenova/transformers` | Gemini 768-dim || MCP tools | 53 | 31 || REST endpoints | 128 | ~50 || Deploy | npm, Docker, fly.io, Railway, Render | Docker, HuggingFace Spaces || Cold boot | ~7s (iii engine warm-up) | <2s || Database size | ~232MB (417 Dolt chunk files) | ~20MB (single `.db` file) || Setup | `npm install -g @agentmemory/agentmemory` | `pip install -r requirements.txt` |Choose the Python version for: simpler setup, HF Space deployment, single-file database, no Node.js, or Python ecosystem integration.Choose the Node.js version for: the full 53-tool MCP surface, iii-engine observability, production multi-agent deployments, or the full auto-hook suite.---## ContributingSee [CONTRIBUTING.md](CONTRIBUTING.md). Issues and PRs welcome.Priority areas: test coverage, additional embedding providers, more agent hook scripts.---## LicenseApache-2.0 — see [LICENSE](LICENSE).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494---title: AgentMemory Pythonemoji: 🧠colorFrom: bluecolorTo: indigosdk: dockerpinned: false---<h1 align="center">agentmemory-python</h1><p align="center"><strong>Persistent memory for AI coding agents — pure Python, zero external databases.</strong><br/>Works with Claude Code, Cursor, Cline, Windsurf, Gemini CLI, and any MCP client.</p><p align="center"><a href="README.md">English</a> |<a href="READMEs/README.zh-CN.md">简体中文</a> |<a href="READMEs/README.ja-JP.md">日本語</a> |<a href="READMEs/README.ko-KR.md">한국어</a> |<a href="READMEs/README.es-ES.md">Español</a> |<a href="READMEs/README.hi-IN.md">हिन्दी</a> |<a href="READMEs/README.pt-BR.md">Português</a> |<a href="READMEs/README.fr-FR.md">Français</a> |<a href="READMEs/README.de-DE.md">Deutsch</a></p><p align="center"><img src="https://img.shields.io/badge/Python-3.10%2B-3776AB?style=for-the-badge&logo=python&logoColor=white" alt="Python 3.10+" /><img src="https://img.shields.io/badge/SQLite-WAL-003B57?style=for-the-badge&logo=sqlite&logoColor=white" alt="SQLite WAL" /><img src="https://img.shields.io/badge/Flask-3.0-000000?style=for-the-badge&logo=flask&logoColor=white" alt="Flask 3.0" /><img src="https://img.shields.io/badge/MCP-Compatible-6B21A8?style=for-the-badge" alt="MCP Compatible" /><img src="https://img.shields.io/badge/HuggingFace-Space-FF9D00?style=for-the-badge&logo=huggingface&logoColor=white" alt="HuggingFace Space" /></p><p align="center"><a href="#quick-start">Quick Start</a> •<a href="#features">Features</a> •<a href="#mcp-integration">MCP</a> •<a href="#api-reference">API</a> •<a href="#configuration">Config</a> •<a href="#deploy-to-huggingface">Deploy</a> •<a href="#viewer">Viewer</a> •<a href="#architecture">Architecture</a></p>---## What Is This?**agentmemory-python** is a Python reimplementation of the [agentmemory](https://github.com/rohitg00/agentmemory) persistent memory server. It exposes a REST API, WebSocket stream, and MCP tools endpoint that AI coding agents use to store and retrieve session observations, long-term memories, lessons, and pinned memory slots.Key differences from the Node.js original:- **No Node.js or iii-engine** — runs with plain `python src/app.py`- **SQLite instead of Dolt** — single file, WAL mode, instant startup- **HuggingFace Space ready** — deploys in one click, data synced to an HF dataset repo- **Same REST + MCP wire format** — drop-in for any agent already wired to agentmemoryYour agent captures every tool call, stores them as observations, compresses them into searchable memory, and injects the right context at the start of every new session — automatically.---## Quick Start### Run locally```bash# Clonegit clone https://github.com/Yash030/agentmemory-python.gitcd agentmemory-python# Install dependencies (no build step)pip install -r requirements.txt# Start the serverpython src/app.py```Server starts on **http://localhost:3111**. Open the viewer at http://localhost:3111/viewer.### Verify it works```bash# Health checkcurl http://localhost:3111/agentmemory/livez# {"status": "ok"}# Save a memorycurl -X POST http://localhost:3111/agentmemory/remember \-H "Content-Type: application/json" \-d '{"content": "JWT auth uses jose middleware in src/middleware/auth.ts", "concepts": ["auth", "jwt"]}'# Recall itcurl -X POST http://localhost:3111/agentmemory/search \-H "Content-Type: application/json" \-d '{"query": "authentication middleware", "limit": 5}'```---## Features| Feature | Status | Notes ||---------|--------|-------|| REST API — sessions, memories, observations | ✅ | Full surface || WebSocket live stream | ✅ | `/stream/mem-live/viewer` || MCP tools endpoint | ✅ | 31 tools || Built-in HTML viewer | ✅ | Real-time dashboard at `/viewer` || BM25 keyword search | ✅ | Always on, no API key needed || Hybrid BM25 + vector search | ✅ | Requires `GEMINI_API_KEY` || 4-tier memory consolidation | ⚙️ | `CONSOLIDATION_ENABLED=true` + LLM key || Knowledge graph extraction | ⚙️ | `GRAPH_EXTRACTION_ENABLED=true` + LLM key || LLM observation compression | ⚙️ | `AGENTMEMORY_AUTO_COMPRESS=true` + LLM key || Lessons with confidence decay | ✅ | Fingerprinted, auto-strengthen on repeat || Memory slots (pinned context) | ✅ | CRUD + auto-reflect || Session replay | ✅ | Full timeline in viewer || Audit log | ✅ | Tracks every write with agent_id + timestamp || HuggingFace Space deploy | ✅ | One-click, data synced to dataset repo || Privacy filtering | ✅ | Strips API keys, tokens before storage |### 4-Tier Memory ModelInspired by how human memory works — raw experience → compressed episodes → extracted facts → learned patterns.| Tier | What | When ||------|------|------|| **Working** | Raw observations from tool use | Every tool call || **Episodic** | Compressed session summaries | Session end || **Semantic** | Extracted facts and patterns | Consolidation || **Procedural** | Workflows and decision patterns | Consolidation |---## MCP IntegrationWire agentmemory-python into your agent's MCP config. It speaks the same MCP protocol as the Node.js original.### Most agents (Cursor, Claude Desktop, Cline, Windsurf)```json{"mcpServers": {"agentmemory": {"command": "npx","args": ["-y", "@agentmemory/mcp"],"env": {"AGENTMEMORY_URL": "http://localhost:3111"}}}}```### Claude CodePaste this prompt and your agent will wire everything:```Start agentmemory-python: run `python src/app.py` from the agentmemory-python directory.Then add this MCP server to ~/.claude.json under mcpServers:{"agentmemory": {"command": "npx","args": ["-y", "@agentmemory/mcp"],"env": { "AGENTMEMORY_URL": "http://localhost:3111" }}}Verify with: curl http://localhost:3111/agentmemory/livezOpen the viewer at: http://localhost:3111/viewer```### Available MCP Tools (31)| Tool | Description ||------|-------------|| `memory_save` | Save a long-term insight, decision, or pattern || `memory_recall` | Search past observations by keyword || `memory_smart_search` | Hybrid BM25 + vector semantic search || `memory_sessions` | List recent sessions || `memory_sessions_list` | Retrieve all memory sessions || `memory_timeline` | Chronological observations for a session || `memory_observations` | Observations for a session || `memory_profile` | Per-project concept + file profile || `memory_lessons` | List active lessons with confidence scores || `memory_lesson_save` | Save a lesson (duplicate saves strengthen it) || `memory_lesson_recall` | Search lessons by query || `memory_lesson_search` | Search lessons by keywords || `memory_consolidate` | Run 4-tier memory consolidation || `memory_reflect` | Reflect on session, update context || `memory_diagnose` | Health check across all subsystems || `memory_forget` | Delete memory, session, or observations || `memory_export` | Export all memory data as JSON || `agent_observe` | Log agent execution observation || `agent_remember` | Save agent memory to long-term storage || `memory_antigravity_sync` | Sync Antigravity transcripts to memory || `memory_antigravity_sync_all` | Master sync: transcript + crystallize + reflect || `memory_slot_list` | List all pinned memory slots || `memory_slot_get` | Retrieve a specific pinned memory slot || `memory_slot_create` | Create/overwrite a pinned memory slot || `memory_slot_append` | Append text content to a pinned memory slot || `memory_slot_replace` | Replace pinned memory slot content || `memory_slot_delete` | Delete a pinned memory slot || `memory_action_create` | Create a new work item / action || `memory_action_update` | Update fields of an existing action || `memory_frontier` | Get active and pending actions sorted by priority || `memory_crystallize` | Crystallize/summarize observations in a session |---## API ReferenceBase URL: `http://localhost:3111/agentmemory`### Health| Method | Path | Description ||--------|------|-------------|| `GET` | `/livez` | Liveness probe — no auth required |### Sessions| Method | Path | Description ||--------|------|-------------|| `POST` | `/session/start` | Start a new session || `POST` | `/session/end` | End a session || `POST` | `/session/commit` | Commit session with summary || `GET` | `/sessions` | List all sessions |### Observations| Method | Path | Description ||--------|------|-------------|| `POST` | `/observe` | Ingest a hook event observation || `POST` | `/agent/observe` | Simplified observe for direct agent use || `GET` | `/observations` | List observations (`?session_id=`) || `POST` | `/timeline` | Chronological observation window |### Memories| Method | Path | Description ||--------|------|-------------|| `POST` | `/remember` | Save long-term memory || `POST` | `/agent/remember` | Simplified remember || `POST` | `/forget` | Delete memory / session / observations || `POST` | `/search` | BM25 + vector search || `POST` | `/context` | Compile context for a session + project || `GET` | `/memories` | List memories (`?latest=true&limit=N`) || `POST` | `/evolve` | Create a new memory version |### Lessons| Method | Path | Description ||--------|------|-------------|| `GET` | `/lessons` | List lessons || `POST` | `/lessons` | Create lesson || `POST` | `/lessons/search` | Search lessons || `POST` | `/lessons/strengthen` | Reinforce an existing lesson |### Slots| Method | Path | Description ||--------|------|-------------|| `GET` | `/slots` | List all pinned slots || `POST` | `/slot` | Create or update a slot || `GET` | `/slot` | Get slot by name || `DELETE` | `/slot` | Delete a slot || `POST` | `/slot/reflect` | Auto-populate from session observations |### Graph + Profile| Method | Path | Description ||--------|------|-------------|| `GET` | `/relations` | Knowledge graph edges || `POST` | `/relations` | Add a relation || `GET` | `/profile` | Project profile (top concepts, files) |### Actions| Method | Path | Description ||--------|------|-------------|| `GET` | `/actions` | List actions || `POST` | `/actions` | Create an action || `PATCH` | `/actions/<id>` | Update action status / fields || `GET` | `/frontier` | Pending actions sorted by priority || `GET` | `/insights` | List insights |### Replay| Method | Path | Description ||--------|------|-------------|| `GET` | `/replay/sessions` | Sessions list for replay tab || `GET` | `/replay/load` | Full session + observations (`?sessionId=`) |### MCP| Method | Path | Description ||--------|------|-------------|| `GET` | `/mcp/tools` | MCP tool schema list || `POST` | `/mcp/tools` | MCP tool call dispatch |---## ConfigurationCreate `~/.agentmemory/.env` (no `export` prefix needed):```env# Server portIII_REST_PORT=3111# Vector search — enables Gemini 768-dim embeddingsGEMINI_API_KEY=your-gemini-key# LLM for compression / consolidation / graph extraction# Any one of these enables LLM features:ANTHROPIC_API_KEY=your-anthropic-key# OPENAI_API_KEY=your-openai-key# GEMINI_API_KEY=your-key (same key as above works for both)# LLM-powered features (disabled by default — spend tokens)CONSOLIDATION_ENABLED=trueGRAPH_EXTRACTION_ENABLED=trueAGENTMEMORY_AUTO_COMPRESS=true# Context injection limitsTOKEN_BUDGET=2000MAX_OBS_PER_SESSION=500# Auth — set to require Bearer token on all endpointsAGENTMEMORY_SECRET=your-secret# Agent scope isolationAGENT_ID=my-agentAGENTMEMORY_AGENT_SCOPE=isolated # only see this agent's data# HuggingFace syncHF_TOKEN=your-hf-tokenAGENTMEMORY_DATASET_REPO=username/agentmemory-data```### Full Variable Reference| Variable | Default | Purpose ||----------|---------|---------|| `III_REST_PORT` / `PORT` | `3111` | API server port || `GEMINI_API_KEY` / `GOOGLE_API_KEY` | — | Enables 768-dim vector search || `AGENTMEMORY_SECRET` | — | Bearer token auth on all endpoints || `AGENT_ID` | — | Default agent ID for scope isolation || `AGENTMEMORY_AGENT_SCOPE=isolated` | — | Filters data to current `AGENT_ID` || `MAX_OBS_PER_SESSION` | `500` | Hard cap on observations per session || `TOKEN_BUDGET` | `2000` | Max tokens in compiled context || `GRAPH_EXTRACTION_ENABLED` | `false` | Knowledge graph (needs LLM) || `CONSOLIDATION_ENABLED` | `false` | Memory consolidation (needs LLM) || `AGENTMEMORY_AUTO_COMPRESS` | `false` | LLM observation compression |---## ViewerBuilt-in dashboard at **http://localhost:3111/viewer**.| Tab | What You See ||-----|-------------|| **Dashboard** | Session stats, memory counts, recent activity || **Sessions** | Browse sessions, inspect observations || **Memories** | Search, filter, and read long-term memories || **Graph** | Project folder visualization — nodes = folders, edges = shared concepts or parent path || **Timeline** | Per-session chronological observation view || **Lessons** | Confidence-scored lessons with decay tracking || **Slots** | Pinned memory slots editor || **Replay** | Scrub through past sessions frame by frame |---## Deploy to HuggingFaceThis project is designed to run as a HuggingFace Space. Data is stored in an HF dataset repo and restored on every boot — so no persistent disk is needed.### Setup1. Fork this repo as a HuggingFace Space (SDK: Docker)2. Create a dataset repo (e.g. `your-username/agentmemory-data`)3. Add Space secrets in the HF dashboard:| Secret | Value ||--------|-------|| `HF_TOKEN` | Your HF write token || `AGENTMEMORY_DATASET_REPO` | `your-username/agentmemory-data` || `AGENTMEMORY_SECRET` | A random secret (optional but recommended) || `GEMINI_API_KEY` | Gemini key (optional, enables vector search) |4. The Space boots, restores `agentmemory.db` from the dataset repo, and starts the server### How sync works`sync.py` uses mtime fingerprinting — it only uploads when the database actually changed, so there are no unnecessary uploads during idle periods.```bash# Manual backuppython sync.py# Environment for syncHF_TOKEN=...AGENTMEMORY_DATASET_REPO=username/agentmemory-data```---## Architecture```agentmemory-python/├── src/│ ├── app.py Flask server — all endpoints, WebSocket broadcaster│ ├── db.py SQLite StateKV — WAL mode, audit_log table│ ├── functions.py Core logic — observe, remember, search, context│ ├── search.py BM25 + Gemini vector index + HybridSearch (RRF)│ └── viewer/│ └── index.html Single-file HTML dashboard (no build step)├── sync.py HuggingFace dataset backup/restore├── Dockerfile HF Space container├── start.sh Boot script (restore → start server → start sync)└── requirements.txt 6 Python dependencies, no external DB required```### Database layoutTwo SQLite tables in `~/.agentmemory/agentmemory.db`:```sql-- All data lives here, namespaced by scopekv_store (scope TEXT NOT NULL, -- e.g. "mem:sessions", "mem:obs:{session_id}"key TEXT NOT NULL,value TEXT NOT NULL, -- JSON-serializedPRIMARY KEY (scope, key))-- Audit trail replaces Dolt git versioningaudit_log (id INTEGER PRIMARY KEY AUTOINCREMENT,ts INTEGER NOT NULL, -- unix millisagent_id TEXT NOT NULL,message TEXT NOT NULL)```### Search pipeline```Query→ BM25 (always) — Porter-stemmed keyword matching→ Vector (if Gemini key) — 768-dim cosine similarity→ RRF fusion — Reciprocal Rank Fusion (k=60)→ Session diversify — max 3 results per session→ Return top-K```---## vs Original agentmemory| | agentmemory (Node.js) | agentmemory-python ||---|---|---|| Runtime | Node.js 20+ | Python 3.10+ || Storage | Dolt SQL (git-versioned MySQL) | SQLite WAL (single file) || Engine dependency | iii-engine (separate binary) | None — just Flask || Embeddings | 6 providers + local `@xenova/transformers` | Gemini 768-dim || MCP tools | 53 | 31 || REST endpoints | 128 | ~50 || Deploy | npm, Docker, fly.io, Railway, Render | Docker, HuggingFace Spaces || Cold boot | ~7s (iii engine warm-up) | <2s || Database size | ~232MB (417 Dolt chunk files) | ~20MB (single `.db` file) || Setup | `npm install -g @agentmemory/agentmemory` | `pip install -r requirements.txt` |Choose the Python version for: simpler setup, HF Space deployment, single-file database, no Node.js, or Python ecosystem integration.Choose the Node.js version for: the full 53-tool MCP surface, iii-engine observability, production multi-agent deployments, or the full auto-hook suite.---## ContributingSee [CONTRIBUTING.md](CONTRIBUTING.md). Issues and PRs welcome.Priority areas: test coverage, additional embedding providers, more agent hook scripts.---## LicenseApache-2.0 — see [LICENSE](LICENSE).
12345678910111213{"name": "agentmemory","version": "0.9.27","description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 31 MCP tools, 16 skills, real-time viewer.","author": {"name": "Rohit Ghumare","url": "https://github.com/rohitg00"},"license": "Apache-2.0","homepage": "https://github.com/rohitg00/agentmemory","repository": "https://github.com/rohitg00/agentmemory","skills": ["./skills/"]}12345678910111213{"name": "agentmemory","version": "0.9.27","description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 31 MCP tools, 16 skills, real-time viewer.","author": {"name": "Rohit Ghumare","url": "https://github.com/rohitg00"},"license": "Apache-2.0","homepage": "https://github.com/rohitg00/agentmemory","repository": "https://github.com/rohitg00/agentmemory","skills": ["./skills/"]}
123456789101112131415{"name": "agentmemory","version": "0.9.27","description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 31 MCP tools, 16 skills, real-time viewer.","author": {"name": "Rohit Ghumare","url": "https://github.com/rohitg00"},"license": "Apache-2.0","homepage": "https://github.com/rohitg00/agentmemory","repository": "https://github.com/rohitg00/agentmemory","skills": "skills/","mcpServers": ".mcp.copilot.json","hooks": "hooks/hooks.copilot.json"}123456789101112131415{"name": "agentmemory","version": "0.9.27","description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 31 MCP tools, 16 skills, real-time viewer.","author": {"name": "Rohit Ghumare","url": "https://github.com/rohitg00"},"license": "Apache-2.0","homepage": "https://github.com/rohitg00/agentmemory","repository": "https://github.com/rohitg00/agentmemory","skills": "skills/","mcpServers": ".mcp.copilot.json","hooks": "hooks/hooks.copilot.json"}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#!/usr/bin/env pythonimport sysimport jsonimport timeimport osfrom datetime import datetime, timezonefrom hook_utils import resolve_project, is_sdk_child, api_call_bgdef main():# Log to file for debugging - write early before any potential errorslog_path = os.path.expanduser("~/.agentmemory/hook_log.txt")try:with open(log_path, "a", encoding="utf-8") as f:f.write(f"[{datetime.now(timezone.utc).isoformat()}] prompt_submit hook called\n")f.write(f"sys.argv: {sys.argv}\n")except Exception as e:passtry:input_data = sys.stdin.read()if not input_data:returndata = json.loads(input_data)except Exception as e:try:with open(log_path, "a", encoding="utf-8") as f:f.write(f"Error parsing stdin: {e}\n")except:passreturnif is_sdk_child(data):returnsession_id = data.get("session_id") or data.get("sessionId") or "unknown"cwd = data.get("cwd") or ""project = resolve_project(cwd)prompt = data.get("prompt") or data.get("userPrompt") or ""payload = {"hookType": "prompt_submit","sessionId": session_id,"project": project,"cwd": cwd,"timestamp": datetime.utcnow().isoformat() + "Z","data": {"prompt": prompt}}api_call_bg("observe", payload)# Allow background request to be flushedtime.sleep(0.5)if __name__ == "__main__":main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#!/usr/bin/env pythonimport sysimport jsonimport timeimport osfrom datetime import datetime, timezonefrom hook_utils import resolve_project, is_sdk_child, api_call_bgdef main():# Log to file for debugging - write early before any potential errorslog_path = os.path.expanduser("~/.agentmemory/hook_log.txt")try:with open(log_path, "a", encoding="utf-8") as f:f.write(f"[{datetime.now(timezone.utc).isoformat()}] prompt_submit hook called\n")f.write(f"sys.argv: {sys.argv}\n")except Exception as e:passtry:input_data = sys.stdin.read()if not input_data:returndata = json.loads(input_data)except Exception as e:try:with open(log_path, "a", encoding="utf-8") as f:f.write(f"Error parsing stdin: {e}\n")except:passreturnif is_sdk_child(data):returnsession_id = data.get("session_id") or data.get("sessionId") or "unknown"cwd = data.get("cwd") or ""project = resolve_project(cwd)prompt = data.get("prompt") or data.get("userPrompt") or ""payload = {"hookType": "prompt_submit","sessionId": session_id,"project": project,"cwd": cwd,"timestamp": datetime.utcnow().isoformat() + "Z","data": {"prompt": prompt}}api_call_bg("observe", payload)# Allow background request to be flushedtime.sleep(0.5)if __name__ == "__main__":main()
AGENTS.md+242-242
README.md+494-494
plugin/.claude-plugin/plugin.json+13-13
plugin/plugin.json+15-15
plugin/scripts/prompt_submit.py+56-56
src/app.py