Spaces:
Configuration error
Configuration error
docs: rewrite all MD files for Python project + fix graph node colors
Browse files- README.md: full rewrite for the Python reimplementation (SQLite,
Flask, HF Space deploy, API reference, architecture, vs comparison)
- AGENTS.md: Python-accurate architecture guide replacing Node.js/iii docs
- CHANGELOG.md: v1.0.0 entry documenting the migration from Dolt/Node
- CONTRIBUTING.md: Python-specific contribution guide
- INSTALL_FOR_AGENTS.md: agent runbook for Python server setup
- ROADMAP.md: Python-focused roadmap replacing Node.js roadmap
- viewer/index.html: fix folderColor() returning hsl() string instead
of hex β gradient code expected parseInt(color.slice(1,3),16) so all
folder nodes rendered black; also fix missing isSelected declaration
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Files changed (7)
- AGENTS.md+185-107
- CHANGELOG.md
- CONTRIBUTING.md+69-87
- INSTALL_FOR_AGENTS.md+104-90
- README.md
- ROADMAP.md+44-70
- src/viewer/index.html+33-10
112345678910111213141516171819202122232425262728293031323334355678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565736373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123606162636465666768697071727374757677124125126127128129130131132133134135136137138808182838485868788891391401411421431441451461471481491501511521531541559394156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186969718718818919019199192193101102103104105106107108194195110196197112113114115198199117200201119120121122123124202# agentmemory β Agent Instructions# agentmemory-python β Agent Instructions
## What this project is
A 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
agentmemory is a persistent memory system for AI coding agents, built on iii-engine's three primitives (Worker/Function/Trigger). Everything goes through `registerFunction`/`registerTrigger`/`sdk.trigger()` β never bypass iii-engine with standalone SQLite or in-process alternatives.
- **Engine**: iii-sdk (WebSocket to iii-engine on port 49134)- **State**: File-based SQLite via iii-engine's StateModule (`./data/state_store.db`)- **Build**: TypeScript β ESM via tsdown, output to `dist/`- **Test**: vitest (`npm test` excludes integration tests)
## Consistency Rules
**When adding or removing MCP tools, you MUST update ALL of the following:**1. `src/mcp/tools-registry.ts` β tool definition + `getAllTools()` array2. `src/mcp/server.ts` β handler case in the `mcp::tools::call` switch3. `src/triggers/api.ts` β REST endpoint registration4. `src/index.ts` β function registration + endpoint count in the log line5. `test/mcp-standalone.test.ts` β tool count assertion6. `README.md` β tool counts (search for "MCP tools")7. `plugin/.claude-plugin/plugin.json` β tool count in description8. `plugin/plugin.json` and `plugin/.mcp.copilot.json` (when present) β tool count or MCP exposure
**When adding REST endpoints, you MUST update:**1. `src/triggers/api.ts` β endpoint registration2. `src/index.ts` β endpoint count in the log line3. `README.md` β endpoint count (search for "REST endpoints" and "endpoints on port")
**When bumping version, you MUST update ALL of the following:**1. `package.json` β version field2. `src/version.ts` β VERSION constant and type union3. `src/types.ts` β ExportData version union4. `src/functions/export-import.ts` β supportedVersions set5. `test/export-import.test.ts` β version assertion6. `plugin/.claude-plugin/plugin.json` β version field7. `plugin/plugin.json` (when present) β version field
**When adding new KV scopes:**1. `src/state/schema.ts` β add to the KV object2. `src/types.ts` β add the corresponding interface
**When adding new audit operations:**1. `src/types.ts` β add to AuditEntry.operation union type
## Code Patterns
### Function Registration```typescriptsdk.registerFunction( "mem::your-function", async (data: { ... }) => { // validate inputs // do work via kv.get/kv.set/kv.list // record audit via recordAudit() return { success: true, ... }; },);### 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.
## 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"
@staticmethod def your_dynamic_scope(id: str) -> str: return f"mem:your-scope:{id}"```
### REST Endpoint Registration```typescriptsdk.registerFunction("api::your-endpoint", async (req: ApiRequest) => { const denied = checkAuth(req, secret); if (denied) return denied; const body = req.body as Record<string, unknown>; // validate + whitelist fields (never pass raw body to sdk.trigger) const result = await sdk.trigger({ function_id: "mem::your-function", payload: { ... }, }); return { status_code: 200, body: result };});sdk.registerTrigger({ type: "http", function_id: "api::your-endpoint", config: { api_path: "/agentmemory/your-path", http_method: "POST" },});### 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'}), 401 body = request.get_json(silent=True) or {} # validate fields explicitly β never pass raw body to functions result = your_function(kv, body.get('field')) return jsonify(result), 200```
### MCP Tool Handler```typescriptcase "memory_your_tool": { // validate args with typeof checks // parse CSV args: args.field.split(",").map(t => t.trim()).filter(Boolean) const result = await sdk.trigger({ function_id: "mem::your-function", payload: { ... }, }); return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };### Adding an MCP tool schema
In 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"] }}```
### Hook ScriptsHook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. There are two patterns depending on whether Claude Code consumes the script's stdout: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 deployment
Data 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`.
- **Context-injecting hooks** (`pre-tool-use`, `pre-compact`, `session-start`) write recalled context to stdout for Claude Code to inject. These MUST use `try/catch` with `await fetch(..., { signal: AbortSignal.timeout(N) })` β the script has to wait for the response before exiting, and the timeout is the only bound on hang time.- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough for single-request hooks; use 1500ms for multi-request hooks like `stop` and `session-end` so all fetches have time to start, especially when `AGENTMEMORY_URL` points to a remote daemon). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration β exactly the bug fire-and-forget is meant to fix.`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)
## Coding Standards## Viewer β `src/viewer/index.html`
- TypeScript, ESM only (`"type": "module"`)- No code comments explaining WHAT β use clear naming instead- Use `fingerprintId()` for content-addressable dedup, `generateId()` for unique IDs- Parallel operations where possible (`Promise.all` for independent kv writes/reads)- Input validation at system boundaries (MCP handlers, REST endpoints)- REST endpoints must whitelist fields β never pass raw request body to `sdk.trigger()`- Use `recordAudit()` for state-changing operations- Timestamps: capture once with `new Date().toISOString()` and reuseSingle-file HTML dashboard, served directly by Flask at `/viewer`. No build step, no bundler.
## TestingTabs: Dashboard, Sessions, Memories, Graph, Timeline, Lessons, Slots, Replay.
- All tests must pass before PR: `npm test` (950+ tests)- Mock pattern: `vi.mock("iii-sdk")` with mock `sdk.trigger`, `kv.get/set/list`- Test files go in `test/` with `.test.ts` extension- Follow existing patterns in `test/crystallize.test.ts` for function tests**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.
## Current Stats (v0.9.16)## No tests yet
- 53 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all)- 128 REST endpoints- 6 MCP resources, 3 MCP prompts- 12 hooks, 4 skills- 50+ iii functions- 950+ testsNo 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).1123345567891078129101411121617131415161718191920212122232223242625262829303132333435363738394041424327282945303132333447353649505137383940414253434445464748554950515253545557585960615657636465666768697071727374757677787980818283848558596061628763648990916566676869709371729573747576979899100101102103104777879808182106838485861088788110899091929394112959611411597# Contributing to agentmemory# Contributing to agentmemory-python
Thanks for taking an interest. This file is the short path from "I have an idea" to "it's in main."Thanks for your interest. This covers the path from "I have an idea" to "it's merged."
## Ground rules## License
- Apache-2.0 license applies to every contribution.- Sign-off is required on every commit (see [DCO](#developer-certificate-of-origin) below).- Be civil. [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) applies.- No attribution headers ("Generated with Claude Code", "Co-Authored-By: Claude", etc.) in commits or PR descriptions.Apache-2.0. Every contribution is covered by it.
## Before you open an issue## Before opening an issue
Search existing issues first:Search [open issues](https://github.com/Yash030/agentmemory-python/issues?q=is%3Aopen) and [closed issues](https://github.com/Yash030/agentmemory-python/issues?q=is%3Aclosed) first.
- [open issues](https://github.com/rohitg00/agentmemory/issues?q=is%3Aissue+is%3Aopen)- [closed issues](https://github.com/rohitg00/agentmemory/issues?q=is%3Aissue+is%3Aclosed)**Bug reports** β include:- Python version (`python --version`)- OS- Exact steps to reproduce- What you expected vs. what happened- Any relevant log lines from the server
If it's a bug: provide the repro steps, your Node version, OS, agentmemory version (`npm view @agentmemory/agentmemory version`), and what you expected vs. what you saw.**Feature requests** β describe the user problem before the implementation. "I couldn't X because Y" is more useful than "please add Z."
If it's a feature: describe the user problem before the implementation. "I couldn't X because Y" beats "please add X."
## Before you open a PR## Before opening a PR
1. Fork the repo and create a branch off `main`: - `feat/<short-name>` for features - `feat/<short-name>` for new features - `fix/<issue-number>-<short-name>` for bug fixes - `docs/<topic>`, `refactor/<topic>`, `chore/<topic>` for the rest2. `npm install` β you need Node >=20.3. `npm run build` β TypeScript must compile clean.4. `npm test` β the full test suite must pass. The one integration test under `test/integration.test.ts` needs a live server on `:3111` and is fine to skip locally.5. Commit with sign-off. Rebase over tiny fixup commits so the history stays readable.
## Pull request flow
- Keep PRs small and focused. One logical change per PR.- Write a clear description: what it does, why, and how to verify.- Link the issue the PR resolves (`Fixes #NNN` / `Closes #NNN`).- Expect CodeRabbit to review automatically. Address its comments before asking a human.- Address review feedback in new commits (do not force-push to the same branch). Maintainers may squash on merge.- A maintainer will merge when tests pass, CodeRabbit is green, and any review comments are addressed.
## Developer Certificate of Origin - `docs/<topic>` for documentation - `refactor/<topic>`, `chore/<topic>` for everything else
Every commit must carry a `Signed-off-by` trailer stating you have the right to submit the contribution under Apache-2.0. The full text of the DCO is at <https://developercertificate.org>.2. Install dependencies: ```bash pip install -r requirements.txt ```
Add it automatically:3. Make your change. Keep it focused β one logical change per PR.
```bashgit commit -s -m "feat: your message"```4. Run the server and test manually: ```bash python src/app.py curl http://localhost:3111/agentmemory/livez ```
PRs with commits lacking sign-off will not merge.5. No test runner is configured yet. If you're adding tests, use `pytest`: ```bash pip install pytest pytest ```
## Coding style6. Run linting before submitting: ```bash pip install ruff ruff check src/ ruff format src/ ```
- TypeScript strict mode. No `any` unless justified in a comment.- Prettier-compatible formatting (editor on save is fine; no repo-wide hook).- No code comments that restate what the code does. Only write a comment when the *why* is non-obvious β a hidden constraint, an invariant, a workaround for a specific bug.- No dead code, no commented-out imports.- Tests live next to the feature in `test/<feature>.test.ts`. Name the test after the behavior, not the implementation.## Pull request guidelines
## Subsystems at a glance
| Directory | What lives here ||-|-|| `src/triggers/api.ts` | Every HTTP endpoint under `/agentmemory/*`. Adding an MCP tool? Add the REST twin here too. || `src/mcp/` | Standalone MCP server (`@agentmemory/mcp`), tools registry, transport, in-memory KV. || `src/functions/` | Core memory operations β observe, compress, consolidate, retention, forget, graph, smart-search, export-import, governance. || `src/hooks/` | The 12 auto-hooks that capture sessions in agents. || `src/health/` | Liveness + readiness + alert thresholds. || `src/state/` | KV schema, keyed mutex, access log. || `integrations/` | First-party plugins: `hermes/`, `openclaw/`, `filesystem-watcher/`. || `plugin/` | Claude Code plugin (`agentmemory@agentmemory`). || `website/` | Marketing site (Next.js 16). || `test/` | Vitest test suite. |
## Adding an MCP tool
1. Register the function in `src/functions/<area>.ts`.2. Register the HTTP trigger in `src/triggers/api.ts` with a matching `api_path`.3. Add the tool entry in `src/mcp/tools-registry.ts`.4. Implement in `src/mcp/standalone.ts` if the standalone MCP package should also expose it.5. Write a test under `test/`.6. No CHANGELOG touch in the PR itself β release PRs are the only place CHANGELOG changes.- Write a clear description: what it does, why, and how to verify.- Link the issue the PR resolves (`Fixes #NNN` or `Closes #NNN`).- Keep PRs small β large PRs are harder to review and slower to merge.- Address review feedback in new commits, not force-pushes.
## Adding an auto-hook## Code style
1. Add the new `HookType` string to the union in `src/types.ts`.2. Wire the handler in `src/hooks/<hook-name>.ts`.3. Add a Vitest case that fires the hook and asserts the observation gets written.- Python 3.10+. No walrus operator or match/case unless there's a real reason.- No comments that restate what the code does. Only comment the *why* β a hidden constraint, a workaround for a specific bug, a non-obvious invariant.- No dead code or commented-out blocks.- Validate inputs at system boundaries (REST endpoints, MCP handlers). Never pass raw request bodies to internal functions.- Use `hmac.compare_digest` for secret comparisons β never `==`.
## Release process## Architecture rules
Maintainers cut releases. Every bump touches 8 files in lockstep:When adding a REST endpoint, also update:- `README.md` API Reference table- `AGENTS.md` if it's agent-callable
1. `package.json`2. `package-lock.json` (top + `packages[""].version`)3. `plugin/.claude-plugin/plugin.json`4. `packages/mcp/package.json` (self + `~x.y.z` pin on the main package)5. `src/version.ts` (extend the union, assign)6. `src/types.ts` (`ExportData.version` union)7. `src/functions/export-import.ts` (`supportedVersions` Set)8. `test/export-import.test.ts` (assertion)When adding an MCP tool, also update:- The schema list in `GET /agentmemory/mcp/tools` in `src/app.py`- The dispatch handler in `POST /agentmemory/mcp/tools` in `src/app.py`- The tool table in `README.md`- The tool list in `AGENTS.md`
Then: CHANGELOG section, PR, merge, tag, GitHub release. The `Publish to npm` workflow picks up the release trigger and publishes `@agentmemory/agentmemory`, `@agentmemory/mcp`, and `@agentmemory/fs-watcher` to npm with provenance.When adding a new KV scope, also update:- The `KV` class in `src/functions.py`- The scope table in `AGENTS.md`
## Security issues## Good first contributions
Do not open a public issue for a security report. See [SECURITY.md](./SECURITY.md).- Add pytest test coverage for `src/functions.py`- Add a hook script for a new agent (see `INSTALL_FOR_AGENTS.md`)- Add support for an additional embedding provider (OpenAI, Cohere, local)- Improve error messages in the viewer- Add a language-specific README to `READMEs/`
## Questions## Questions?
- Implementation questions: open a GitHub Discussion.- Governance questions: open an issue labeled `governance`. See [GOVERNANCE.md](./GOVERNANCE.md).Open an issue or start a discussion. The project is small enough that a quick question is usually faster than reading all the code.11233456778991011121314151314151617181920211718192420212223272829303124253326272836293031393233413435433637384639404149424351444546474849575051595253546263555657585965606162636465676667686971727374757071777273797475817677787980818283848583868785888987889091929394959697989991100101931021039510410597106107108109110100111112113114115116117103118119105120121107108109110122123112113114124125126127128117129130119131132121133134123124125126127135136137138139140129141142131143144145146133147148149150135136137138139140151152153154155156144145146147148149150151157158159160161162163164165166167168155169170157158159160161171172173174175176163177# Install agentmemory (agent runbook)# Install agentmemory-python (agent runbook)
You are a coding agent. Follow this runbook top to bottom to install agentmemory, wire it into yourself, and verify that persistent memory works. Run each command, check the result against the "Expect" note, then move on. If a step fails, jump to Troubleshooting, and if it still fails, stop and report the step, the exact command, and the error output.You are a coding agent. Follow this runbook top to bottom to install agentmemory-python, wire it into yourself, and verify that persistent memory works. Run each command, check the result against the "Expect" note, then move on.
## What you are installing
agentmemory is a local memory server for coding agents. It runs on your machine, exposes a REST API on port 3111 and an MCP server, and stores memories on disk under `~/.agentmemory`. It is built on the iii engine, which agentmemory downloads and manages for you as a pinned binary under `~/.agentmemory/bin`. You do not install iii separately.agentmemory-python is a local memory server for coding agents. It runs on your machine, exposes a REST API on port 3111 and an MCP endpoint, and stores all memories in a single SQLite file at `~/.agentmemory/agentmemory.db`. It is built with Python and Flask β no Node.js, no external database, no daemon to manage separately.
Default mode needs no API key and no cloud account. Out of the box it runs hybrid retrieval (BM25 keyword search plus local on-device embeddings), so a full install proves real semantic recall with zero credentials. An LLM provider key is optional and only unlocks richer summaries and auto-injection (see "Optional: richer features").Default mode works with no API key. It runs BM25 keyword search out of the box. Set `GEMINI_API_KEY` to also enable vector semantic search.
## Prerequisites
- Node.js >= 20 and npm. Check with `node -v`.- macOS or Linux for the one-command path. On Windows, use WSL2; native Windows engine setup is manual and `agentmemory connect` is not supported there.- Ports 3111 (REST), 3112 (streams), 3113 (viewer), and 49134 (engine) free. Override the whole block with `--port <N>` or `--instance <N>` if any are taken.- Python 3.10 or newer. Check with `python --version` or `python3 --version`.- pip. Check with `pip --version`.- Port 3111 free. If taken, set `III_REST_PORT=<other>` in `~/.agentmemory/.env`.
## Running non-interactively
Several commands prompt on a TTY (for example the first-run "install globally?" question). As an agent you usually want no prompts. Either set `CI=1` in the environment for the commands below, or rely on the fact that agentmemory skips all prompts automatically when stdin/stdout are not a TTY. Prompts are also never-nag: once answered they persist and are not asked again. Re-run onboarding any time with `agentmemory --reset`.
## 1. Install globally## 1. Clone the repo
```bashnpm install -g @agentmemory/agentmemorygit clone https://github.com/Yash030/agentmemory-python.gitcd agentmemory-python```
If you hit `EACCES` on a system Node install (macOS/Linux), retry with `sudo npm install -g @agentmemory/agentmemory`.
No-install alternative: skip this step and run the server with `npx -y @agentmemory/agentmemory@latest` everywhere this runbook says `agentmemory`. The `@latest` and `-y` flags matter because npx caches per version and a bare `npx @agentmemory/agentmemory` can serve a stale release.
Expect: the install completes without errors.Expect: the directory exists with `src/app.py` inside.
## 2. Verify the install## 2. Install dependencies
```bashagentmemory --versionpip install -r requirements.txt```
Expect: a version string is printed. If `command not found`, the global bin is not on `PATH`; use the `npx -y @agentmemory/agentmemory@latest` form instead.This installs: flask, flask-sock, requests, websockets, python-dateutil, huggingface_hub.
## 3. Start the serverExpect: install completes without errors.
The server listens on port 3111 and auto-starts its pinned iii engine on first run (this can take a few seconds the first time while the engine binary is fetched into `~/.agentmemory/bin`). Run it in the background or in a separate terminal so the rest of the runbook can talk to it.## 3. Start the server
```bashagentmemory &python src/app.py &```
Or in a dedicated terminal, run `agentmemory` in the foreground. To run a second isolated instance, use `agentmemory --instance 1` (relocates the whole port block to 3211/3212/3213/49234).Or run in a separate terminal: `python src/app.py`
Wait until it is reachable, then continue:Wait until it is reachable:
```bashcurl -fsS http://localhost:3111/agentmemory/livez```
Expect: a `200` response. Retry for up to ~15 seconds on first run while the engine warms up.Expect: `{"status": "ok"}`. On first run the BM25 index initializes in the background; this takes under a second.
## 4. Prove recall in one command## 4. Prove save and recall works
```bashagentmemory demo --serve```# Save a memorycurl -X POST http://localhost:3111/agentmemory/remember \ -H "Content-Type: application/json" \ -d '{"content":"agentmemory-python install verification probe","concepts":["install-check"]}'
`--serve` boots the server, seeds three realistic sessions (JWT auth, an N+1 query fix, rate limiting), runs semantic searches against them, prints the results, and tears everything down. No second terminal needed.# Recall itcurl -X POST http://localhost:3111/agentmemory/search \ -H "Content-Type: application/json" \ -d '{"query":"install verification probe","limit":5}'```
Expect: the demo finds the "N+1 query fix" memory when it searches for "database performance optimization", which keyword matching alone cannot do. Open `http://localhost:3113` while it runs to watch the memory build live.Expect: first call returns `{"id": "...", "success": true}`, second returns results containing the probe memory.
## 5. Wire MCP into the calling agent
Detect which agent is running this runbook, then wire its MCP config:
```bashagentmemory connect <agent>```Detect which agent is running this runbook, then add agentmemory-python to its MCP config.
`connect` merges agentmemory into that agent's MCP config and preserves any existing servers. Supported agent names:### Standard MCP block (Cursor, Claude Desktop, Cline, Windsurf, Gemini CLI)
`claude-code`, `copilot-cli`, `codex`, `cursor`, `gemini-cli`, `opencode`, `cline`, `continue`, `droid`, `hermes`, `openclaw`, `openhuman`, `pi`, `qwen`, `warp`, `zed`, `antigravity`, `kiro`.Merge this into the agent's `mcpServers` object:
If you cannot tell which agent you are, default to `claude-code`. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server.```json"agentmemory": { "command": "npx", "args": ["-y", "@agentmemory/mcp"], "env": { "AGENTMEMORY_URL": "http://localhost:3111" }}```
Expect: the agent now lists agentmemory's tools. With the server running you should see the full set of 53 tools (for example `memory_save`, `memory_smart_search`, `memory_sessions`). If you see only 7 tools, the MCP shim could not reach a server, see Troubleshooting.### Claude Code
## 6. Install native skillsAdd to `~/.claude.json` under `mcpServers`:
```bashnpx skills add rohitg00/agentmemory -y```json"agentmemory": { "command": "npx", "args": ["-y", "@agentmemory/mcp"], "env": { "AGENTMEMORY_URL": "http://localhost:3111" }}```
This installs the native skills so the agent knows when to call the memory tools, not just that they exist. `connect` makes the tools available; skills teach the agent when to use them.Then reload MCP: run `/mcp` in Claude Code.
Expect: the skills are installed for the detected agent.### Any agent β verify tool count
## 7. Verify a save and recall round-tripAfter wiring, the agent should list agentmemory's tools. With the server running you should see 16 tools (e.g. `memory_save`, `memory_smart_search`, `memory_sessions`).
Confirm health first:If you see 0 tools or an error, check that `python src/app.py` is running and `AGENTMEMORY_URL` points at it.
## 6. Open the viewer (optional)
```bashcurl -fsS http://localhost:3111/agentmemory/healthopen http://localhost:3111/viewer# or on Linux:xdg-open http://localhost:3111/viewer# or on Windows:start http://localhost:3111/viewer```
Expect: a JSON body with an ok status.The viewer shows live sessions, memories, and the knowledge graph.
Now write a memory and read it back. If MCP is wired, call the `memory_save` tool followed by `memory_smart_search`. Otherwise use REST directly (note: these are the REST paths, which differ from the MCP tool names):## Optional: enable vector search
```bashcurl -X POST http://localhost:3111/agentmemory/remember \ -H "Content-Type: application/json" \ -d '{"content":"agentmemory install verification probe","concepts":["install-check"]}'Vector search finds memories semantically, not just by keyword. Enable it with a free Gemini API key:
curl -X POST http://localhost:3111/agentmemory/smart-search \ -H "Content-Type: application/json" \ -d '{"query":"install verification probe","limit":5}'```bashmkdir -p ~/.agentmemoryecho "GEMINI_API_KEY=your-key-here" >> ~/.agentmemory/.env```
Expect: the first call returns `201`, the second returns `200` with results that include the probe memory you just saved.Restart the server after adding the key. The viewer's search bar will now use hybrid BM25 + vector retrieval.
If `AGENTMEMORY_SECRET` is set in the environment, the REST API requires it. Add `-H "Authorization: Bearer $AGENTMEMORY_SECRET"` to both calls. By default no secret is set and localhost is open.## Optional: enable LLM compression
## Optional: richer featuresLLM compression makes each observation richer and more searchable. Requires an LLM API key:
These are off by default because they spend tokens. Enable them only if the user wants them. Put configuration in `~/.agentmemory/.env` (no `export` prefix), then restart the server.
- `AGENTMEMORY_INJECT_CONTEXT=true` makes the SessionStart and PreToolUse hooks inject past memory into the agent's context automatically. Cost: spends session tokens proportional to tool-call frequency.- `AGENTMEMORY_AUTO_COMPRESS=true` sends each observation to your LLM provider for a richer summary. Cost: spends API tokens proportional to tool-use frequency. Requires a provider key.- Provider key: set one of `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, and similar, in the same file. Without a key, agentmemory stays in zero-LLM mode and still indexes and recalls via BM25 plus local embeddings.```bash# Add to ~/.agentmemory/.envANTHROPIC_API_KEY=your-key # or OPENAI_API_KEY or GEMINI_API_KEYAGENTMEMORY_AUTO_COMPRESS=true```
## Tool surface## Lifecycle
The MCP server exposes 53 tools by default (`--tools all`). Use `--tools core` (or `AGENTMEMORY_TOOLS=core`) for a lean 8-tool set on hosts with tight tool limits. The 8 core tools cover save, recall, smart search, sessions, export, audit, and governance delete.```bash# Stop the server (find and kill the process)pkill -f "python src/app.py"
## Lifecycle commands# Check what's storedcurl http://localhost:3111/agentmemory/sessionscurl http://localhost:3111/agentmemory/memories
- `agentmemory status` shows server and engine state.- `agentmemory doctor` runs diagnostics and reports what is misconfigured.- `agentmemory stop` stops the engine this CLI started (`stop --force` bypasses the Docker guard).- `agentmemory upgrade` upgrades agentmemory and the iii runtime, best effort.- `agentmemory --reset` wipes onboarding preferences and re-runs the wizard.- `agentmemory import-jsonl <file>` imports prior Claude Code session logs as memories.# Health checkcurl http://localhost:3111/agentmemory/livez```
## Troubleshooting
- `command not found: agentmemory`: the global bin is not on `PATH`. Use `npx -y @agentmemory/agentmemory@latest`.- `EACCES` during global install: retry with `sudo`, or use the npx form.- Stale npx version: run `npx -y @agentmemory/agentmemory@latest`, or clear the cache with `rm -rf ~/.npm/_npx` (macOS/Linux).- Port already in use: another instance or process holds 3111. Stop it, or relocate with `agentmemory --instance 1`.- Server starts but `livez` never returns 200: re-run with `agentmemory --verbose` to see engine stderr.- Engine version warning on start: harmless. agentmemory uses its own pinned engine in `~/.agentmemory/bin` regardless of any `iii` on `PATH`. Set `AGENTMEMORY_III_VERSION` only to override deliberately.- Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx @agentmemory/agentmemory` and ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP.- Windows: use WSL2 for the path above. Native Windows runs the server but `connect` and the automated engine install are not supported.| Symptom | Fix ||---------|-----|| `ModuleNotFoundError: No module named 'flask'` | Run `pip install -r requirements.txt` || `Address already in use` on port 3111 | Set `III_REST_PORT=3112` in `~/.agentmemory/.env` and restart || `/livez` never returns | Check `python src/app.py` stderr for import errors || 0 tools in agent | Confirm `AGENTMEMORY_URL=http://localhost:3111` and the server is running || `401 Unauthorized` | Set `AGENTMEMORY_SECRET` env var in the MCP config to match `~/.agentmemory/.env` || Vector search not working | Add `GEMINI_API_KEY` to `~/.agentmemory/.env` and restart || Windows Python path issue | Use `python3` instead of `python`, or use WSL2 |
## Report success
Report back to the user:Report back:
- agentmemory installed, version, and the server running on port 3111- which agent was wired via `agentmemory connect`, and the tool count the agent now sees- the save and recall round-trip returned the probe memory- the viewer is available at `http://localhost:3113`- whether any optional features were enabled- agentmemory-python server running on port 3111- MCP wired into the agent, tool count visible- Save and recall round-trip returned the probe memory- Viewer available at http://localhost:3111/viewer- Any optional features enabled (vector search, LLM compression)
If any step failed, report which step, the exact command, and the error output.If any step failed, report the step, exact command, and error output.1233455678971011910111212131414151617181920212223242526271628291819202122232425262728293031323031323536373839404142434445464748495051525354553357343536376061626364653867683940414243447045467273747576474849798081825084515253545556575859868788606190626392646566# Roadmap
This is agentmemory's public 12-month roadmap. It covers Q2 2026 through Q1 2027. The roadmap is the source of truth for where the project is heading; anything significant that lands in main should trace back to an item here or a ratified issue.This is agentmemory-python's public roadmap. Items shift as priorities change.
Items shift as evidence changes. Each quarter we publish a short retrospective on what landed, what slipped, and why β attached to the release notes.- **Shipped** β in main- **Active** β has an open PR- **Planned** β accepted, not started- **Candidate** β under consideration
## How to read this---
- **Shipped** β landed in main and tagged in a release.- **Active** β in-flight, has an open PR or issue owner.- **Planned** β accepted scope for the quarter, not started.- **Candidate** β under consideration, may defer.## Phase 1 β Foundation (done)
Anything not on this list that a contributor wants to pursue is welcome β open an issue labeled `roadmap` and it gets triaged against the quarterly theme.- [x] Python + Flask server replacing Node.js / iii-engine- [x] SQLite WAL backend replacing Dolt SQL- [x] Audit log replacing Dolt git versioning- [x] BM25 search with Porter stemmer- [x] Gemini 768-dim vector search + hybrid RRF fusion- [x] 16-tool MCP endpoint- [x] WebSocket live stream- [x] Built-in HTML viewer (Dashboard, Sessions, Memories, Graph, Timeline, Lessons, Slots, Replay)- [x] Knowledge graph visualization β folder nodes with unique colors, force-directed layout- [x] 4-tier memory consolidation (Working β Episodic β Semantic β Procedural)- [x] Lessons system with confidence decay- [x] HuggingFace Space deployment with sync fingerprinting- [x] Dolt β SQLite one-time migration (7502 rows, 19.6MB)
## Themes---
- **Q2 2026 β Depth.** Multimodal memory, more connectors, close out backlog from the v0.9 cycle.- **Q3 2026 β Breadth.** Hook parity across more agents, community expansion, OpenSSF best-practices alignment.- **Q4 2026 β Trust.** Enterprise features β SSO, audit export, RBAC, long-running deployment story.- **Q1 2027 β v1.0.** Stability, LTS branch, semver freeze on the REST + MCP surface.
## Q2 2026 β Depth (April β June)
### Shipped so far in this quarter- [x] iii console docs in README with vendored screenshots (#157)- [x] Health severity gated on RSS floor (#158 / PR #160)- [x] Standalone MCP proxies to the running server (#159 / PR #161)- [x] Audit coverage for `mem::forget` + audit policy doc (#125 / PR #162)- [x] `@agentmemory/fs-watcher` filesystem connector (#62 / PR #163)- [x] Next.js website on Vercel (PR #164)- [x] CI publishes all three npm packages on release (PR #166)## Phase 2 β Reliability
### Active- [ ] **Multimodal memory** β content-addressed image store, vision-prompt compression, disk quota + refcount on eviction (#64, PR #111)- [ ] **Governance baseline** β this file, plus `GOVERNANCE.md`, `CONTRIBUTING.md`, `MAINTAINERS.md`, `CODE_OF_CONDUCT.md`, `SECURITY.md`
### Planned- [ ] **GitHub connector** (`@agentmemory/github-watcher`) β sync issues, PRs, discussions as observations. Shares the `POST /agentmemory/observe` wire format with the filesystem connector.- [x] **OpenCode hook bus** (#156) β wired 22 hooks covering all 12 Claude Code hook types: session lifecycle (create/idle/status/compacted/update/diff/delete/error), messages & prompts (chat.message, message.updated user+assistant, message.removed), tool capture (before + rich ToolPart lifecycle in message.part.updated), memory injection (context + enrich via system.transform), part tracking (subtask, step-finish, reasoning, file, patch, compaction, agent, retry), file enrichment pipeline (stash via tool.execute.before + file.edited + file parts), permissions (updated + replied), task tracking (todo.updated w/ priority), commands (command.executed), config & model tracking (config + chat.params). Plus 2 slash commands (recall/remember). See `plugin/opencode/`.- [ ] **Session replay UI** in the real-time viewer β scrub the timeline, inspect per-observation payloads.- [ ] **Benchmark harness in CI** β keep the 95.2% R@5 number honest across releases by re-running LongMemEval-S on every minor tag.
## Q3 2026 β Breadth (July β September)
### Planned- [ ] **Additional maintainer onboarding** β at least one Maintainer from a different organization added via the process in `GOVERNANCE.md`. This is a prerequisite for advancing past the foundation's Growth Stage.- [ ] **Slack / Discord connector** β third source in the connector family.- [ ] **OpenSSF Scorecard** β enroll, reach a Silver-equivalent score. Badged in the README.- [ ] **Hermes integration hardening** β reach parity with the OpenClaw plugin surface (session lifecycle + tool-use hooks).- [ ] **Knowledge graph query language** β small DSL on top of `/agentmemory/graph` for multi-hop questions.- [ ] **First conference talk** β submit to KubeCon / LlamaCon / similar.
### Candidate- Cross-agent shared memory namespace. Currently each agent installs its own instance. This would let a Claude Code session and a Cursor session recall each other's observations via a shared mesh node.
## Q4 2026 β Trust (October β December)- [ ] **Pytest test coverage** for `src/functions.py` core operations (observe, remember, search, context)- [ ] **Graph edge label bug** β labels overlap at default zoom on dense graphs
### Planned- [ ] **SSO gateway** β accept OIDC in front of the REST surface for team deployments.- [ ] **Audit log export** β streamable tail to S3 / Loki / stdout for compliance pipelines.- [ ] **RBAC on memory scope** β `project:read`, `project:write`, `governance:delete` role set.- [ ] **Long-running deployment guide** β first-class Docker, systemd unit, and launchd plist.- [ ] **Performance SLO** β publish p50/p95 recall latency targets, enforce via the benchmark harness.- [ ] **Security audit** β external review of the REST surface + mesh-sync path. Fund through LF if foundation acceptance lands before end of quarter.
### Candidate- Agent-to-agent memory handoff protocol β standardize what one agent can inherit from another's memory, complementing MCP.- [ ] **Additional embedding providers** β OpenAI `text-embedding-3-small`, local `sentence-transformers`- [ ] **Hook scripts** β prebuilt bash/PowerShell hook scripts for Claude Code, Cursor, Codex CLI pointing at `http://localhost:3111`- [ ] **Memory export/import** β JSON round-trip so users can migrate between instances- [ ] **Health endpoint** (`/agentmemory/health`) β richer than `/livez`, includes index sizes, sync status, last backup time- [ ] **Graceful shutdown** β flush BM25/vector index to DB before exit on SIGTERM
## Q1 2027 β v1.0 (January β March)---
### Planned- [ ] **REST + MCP surface freeze.** Any break requires a major-version tag per `GOVERNANCE.md`.- [ ] **LTS branch `v1.x`** β 12-month security-fix commitment.- [ ] **v1.0 release** β full documentation pass, all roadmap items from prior quarters either shipped or formally deferred.- [ ] **Foundation membership** β Growth β Impact stage application if adoption + maintainer diversity metrics justify.## Phase 3 β Breadth
### Candidate- Hosted reference instance for the community to benchmark against.- Reference implementation in a second language (Rust or Go) for the MCP server β would expand the set of runtimes that can host agentmemory.
## Out of scope
For transparency, these are deliberately *not* on the roadmap:- **Additional LLM providers** β OpenRouter, Ollama (local), Cohere for compression and consolidation- **MCP tool parity** β expand from 16 to 30+ tools to match the most-used subset of the Node.js 53-tool surface- **GitHub Actions hook** β observe CI runs as memory events- **Slack / Discord connector** β ingest messages as observations- **Multi-agent shared memory** β namespace isolation for team use; agents share a pool with per-agent write attribution- **RBAC** β role-based access control for shared deployments- **Benchmark harness** β reproduce the LongMemEval-S R@5 metric on the Python stack- **pip package** β `pip install agentmemory` with a `agentmemory` CLI entrypoint
- A cloud-hosted agentmemory SaaS.- Billing, subscription tiers, commercial licensing beyond Apache-2.0.- Agent frameworks themselves β agentmemory is a dependency, not a replacement for the agent runtime.---
## Feedback## Non-goals
Anything on this list you disagree with, or think should move up / down β open an issue tagged `roadmap`. Quarterly themes are revisited with every quarterly retrospective.- Full parity with the 128-endpoint / 53-tool Node.js surface β the Python version targets simplicity and HF deployment, not feature count- iii-engine worker model β the Python version intentionally avoids the iii runtime- Dolt git-versioned history β the audit log satisfies the write-tracking requirement without the complexity1226 unmodified lines12271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249861 unmodified lines21112112211320972114211521162117211821192120212121012102212221232124212521042126212721282129198 unmodified lines2328232923302309233123322333233431 unmodified lines23662367236823472369237023712372133 unmodified lines2506250725082487250925102511251227 unmodified lines254025412542252125432544254525467 unmodified lines2554255525562535255725582559256044 unmodified lines2605260626072586260826092610261126121226 unmodified lines decision: '#6B3FA0', pattern: '#2563EB', library: '#C2410C', person: '#111111', folder: '#4F46E5' };
function folderColor(id) { var h = 0; for (var i = 0; i < id.length; i++) { h = (h * 31 + id.charCodeAt(i)) & 0xfffffff; } var hue = (h % 360 + 360) % 360; var sat = 55 + (h % 25); var lig = isDarkMode() ? 52 + (h % 16) : 38 + (h % 14); // Return hex so parseInt(color.slice(1,3),16) works in gradient code var s = sat / 100, l = lig / 100; var a = s * Math.min(l, 1 - l); function f(n) { var k = (n + hue / 30) % 12; var c = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); return Math.round(255 * c).toString(16).padStart(2, '0'); } return '#' + f(0) + f(8) + f(4); } var OP_BADGES = { observe: 'badge-blue', compress: 'badge-cyan', remember: 'badge-green', forget: 'badge-red', evolve: 'badge-purple', consolidate: 'badge-yellow',861 unmodified lines
graphSim.nodes = state.graph.nodes.map(function(n, i) { var angle = (2 * Math.PI * i) / Math.max(state.graph.nodes.length, 1); var radius = Math.min(cw, ch) * 0.3; var radius = Math.min(cw, ch) * 0.38; var deg = edgeMap[n.id] || 0; var activity = ((n.sessions && n.sessions.length) || 0) + ((n.memories && n.memories.length) || 0); var nodeR = n.type === 'folder' ? Math.max(24, Math.min(52, 24 + Math.sqrt(activity + 1) * 3.5)) : Math.max(10, Math.min(26, 10 + deg * 2.5)); return { id: n.id, type: n.type, name: n.name, properties: n.properties, x: Math.cos(angle) * radius + (Math.random() - 0.5) * 50, y: Math.sin(angle) * radius + (Math.random() - 0.5) * 50, sessions: n.sessions, memories: n.memories, x: Math.cos(angle) * radius, y: Math.sin(angle) * radius, vx: 0, vy: 0, r: Math.max(8, Math.min(22, 8 + deg * 2.5)) r: nodeR }; }); graphSim.edges = state.graph.edges.slice();198 unmodified lines graphSim.tickCount = (graphSim.tickCount || 0) + 1; var coolBoost = Math.min(0.4, graphSim.tickCount / 1500); var damping = 0.9 - coolBoost; var repulsion = nodeCount > 1000 ? 3000 : nodeCount > 100 ? 2000 : nodeCount > 50 ? 1200 : 800; var repulsion = nodeCount > 1000 ? 3000 : nodeCount > 100 ? 2000 : nodeCount > 50 ? 1800 : nodeCount > 10 ? 8000 : 18000; var attraction = nodeCount > 100 ? 0.002 : 0.005; var centerGravity = nodeCount > 1000 ? 0.012 : nodeCount > 100 ? 0.005 : 0.01; var velocityCap = nodeCount > 1000 ? 6 : nodeCount > 200 ? 12 : 24;31 unmodified lines var dx = t.x - s.x; var dy = t.y - s.y; var dist = Math.sqrt(dx * dx + dy * dy) || 1; var f = (dist - 100) * attraction; var f = (dist - (s.type === 'folder' || t.type === 'folder' ? 220 : 100)) * attraction; var fx = (dx / dist) * f; var fy = (dy / dist) * f; if (graphSim.dragNode !== s) { s.vx += fx; s.vy += fy; }133 unmodified lines var cpx = (s.x + t.x) / 2 + offsetX; var cpy = (s.y + t.y) / 2 + offsetY;
var edgeColor = NODE_COLORS[s.type] || '#666666'; var edgeColor = s.type === 'folder' ? folderColor(s.id) : (NODE_COLORS[s.type] || '#666666'); var edgeAlpha; if (edgeDimmed) { edgeAlpha = 0.06;27 unmodified lines ctx.fill(); }
var showEdgeLabel = e.type && !edgeDimmed && (isConnectedToFocus ? graphSim.zoom > 0.6 : graphSim.zoom > edgeLabelZoomThreshold); var showEdgeLabel = e.type && !edgeDimmed && isConnectedToFocus && graphSim.zoom > 0.4; if (showEdgeLabel) { var zoomInv = 1 / graphSim.zoom; ctx.save();7 unmodified lines
graphSim.nodes.forEach(function(n) { if (!state.graph.filters[n.type]) return; var color = NODE_COLORS[n.type] || '#666666'; var color = n.type === 'folder' ? folderColor(n.id) : (NODE_COLORS[n.type] || '#666666'); var isSelected = selectedId === n.id; var isHovered = hoverNodeId === n.id; var matchesSearch = !searchActive || n.name.toLowerCase().includes(graphSearchTerm);44 unmodified lines ctx.stroke(); }
var showLabel = matchesSearch && !isFocusFaded && ( var showLabel = !isFocusFaded && ( n.type === 'folder' || isSelected || isHovered || (searchActive && matchesSearch) || (!isDense && graphSim.zoom > labelZoomThreshold) ||AGENTS.md+185-107
CHANGELOG.md
CONTRIBUTING.md+69-87
INSTALL_FOR_AGENTS.md+104-90
README.md
ROADMAP.md+44-70
src/viewer/index.html+33-10