Spaces:
Configuration error
feat: upscale & UX overhaul — blueprint split, debounce, tests, viewer enhancements, DX improvements
Browse filesTrack A — Backend Structure:
- Split app.py into 7 Flask blueprints (src/routes/)
- Create src/memory/ package and src/storage/ package
- Per-thread SQLite connections, WAL checkpoint, db.stats()
- IndexPersistence debounce queue with threading.Timer + dirty flags
- Workers: SIGTERM/SIGINT graceful shutdown
Track B — Viewer UX:
- Command palette (Ctrl+K/Cmd+K) with fuzzy search
- D3 v7 force-directed graph replacing canvas
- VirtualList for Timeline/Folders
- Onboarding card for empty state
- MCP Tool Tester tab
- Tab keyboard navigation (ARIA roles, arrow keys)
- Skeleton loading states (@keyframes shimmer)
Track C — Reliability & Testing:
- test_search.py, test_remember.py, test_context.py, test_debounce.py
- test_properties.py (8 Hypothesis property tests)
- test_api.py (Flask test client integration tests)
- test_route_regressions.py (blueprint regression suite)
- sync.py: audit log HWM replaces mtime change detection
- /health: syncStatus, lastSyncAt, dbSizeBytes fields
Track D — Integrations & DX:
- hooks/: claude-code-hook.sh, cursor-hook.js, powershell-hook.ps1
- INSTALL_FOR_AGENTS.md: hook setup section added
- pyproject.toml + src/cli.py (serve/migrate/export commands)
- CI: Python 3.10/3.11/3.12 matrix, pip install + pytest + build
- OpenAIEmbeddingProvider + SentenceTransformerProvider
- Auto-select embedding provider priority chain
- CORS via AGENTMEMORY_CORS_ORIGINS env var
- Stop injecting AGENTMEMORY_SECRET into viewer HTML
- mcp_stdio.py: antigravity moved to examples/
- ARCHITECTURE.md, docs/viewer-design-system.md, cleaned scratch files
Files changed (50)
- .github/workflows/ci.yml+13-24
- .kiro/specs/folder-based-memory/tasks.md+367-298
- ARCHITECTURE.mdAdded+144
- INSTALL_FOR_AGENTS.md+79-1
- migrate_dolt_to_sqlite.py → docs/migration/migrate_dolt_to_sqlite.pyRenamed
- DESIGN.md → docs/viewer-design-system.mdRenamed
- examples/antigravity_sync.pyAdded+240
- hooks/claude-code-hook.shAdded+48
- hooks/cursor-hook.jsAdded+59
- hooks/powershell-hook.ps1Added+77
- push_local_data.pyDeleted-96
- push_second_brain.pyDeleted-38
- pyproject.tomlAdded+42
- scratch_diff.txtDeleted-689
- scratch_test_import.pyDeleted-27
- src/app.py+143-2167
- src/cli.pyAdded+99
- src/db.py+173-109
- src/functions.py+150-57
- src/mcp_stdio.py+18-299
- src/memory/__init__.pyAdded+72
- src/memory/context.pyAdded+30
- src/memory/graph.pyAdded+18
- src/memory/health.pyAdded+24
- src/memory/observe.pyAdded+35
- src/memory/remember.pyAdded+30
- src/memory/timeline.pyAdded+37
- src/routes/__init__.pyAdded+24
- src/routes/graph.pyAdded+146
- src/routes/health.pyAdded+137
- src/routes/mcp.pyAdded+371
- src/routes/memories.pyAdded+134
- src/routes/migration.pyAdded+49
- src/routes/observations.pyAdded+140
- src/routes/search.pyAdded+80
- src/search.py+100-1
- src/storage/__init__.pyAdded+23
- src/storage/images.pyAdded+98
- src/storage/paths.pyAdded+120
- src/storage/scopes.pyAdded+68
- src/viewer/index.html+630-13
- src/viewer_helpers.pyAdded+57
- src/workers.pyAdded+146
- sync.py+75-21
- tests/test_api.pyAdded+254
- tests/test_context.pyAdded+169
- tests/test_debounce.pyAdded+169
- tests/test_folder_graph_build.py+1-1
- tests/test_observe_core.pyAdded+207
- tests/test_properties.pyAdded+310
39 unmodified lines4041424344454647484950515253545556575859606162636465666768697039 unmodified linesjobs:test:runs-on: ${{ matrix.os }}strategy:# Don't bail the whole matrix on one cell's failure — we want to# see whether the same failure reproduces across OSes (e.g.# whether a flake is platform-specific or universal).fail-fast: falsematrix:# Windows held back: test/obsidian-export.test.ts has hardcoded# POSIX paths (`/tmp/...`) that fail on D:\ drive runners.# src/functions/obsidian-export.ts needs os.tmpdir() + path.join# rework before Windows can be added back. Tracked as follow-up.os: [ubuntu-latest, macos-latest]node-version: [20, 22]steps:- uses: actions/checkout@v6with:persist-credentials: false- uses: actions/setup-node@v6with:node-version: ${{ matrix.node-version }}# Two-step install: generate a lockfile in-runner with# --package-lock-only, then install from it with `npm ci`.# Lockfiles are gitignored at the repo level.- run: npm install --package-lock-only --legacy-peer-deps --no-audit --no-fund- run: npm ci --legacy-peer-deps --no-audit --no-fund- run: npm run build- run: npm run skills:check- run: npm test39 unmodified lines404142434445464748495051525354555657585939 unmodified linesjobs:test:runs-on: ubuntu-lateststrategy:matrix:python-version: ["3.10", "3.11", "3.12"]steps:- uses: actions/checkout@v4- uses: actions/setup-python@v5with:python-version: ${{ matrix.python-version }}- name: Install dependenciesrun: pip install -e ".[dev]"- name: Run testsrun: pytest tests/ -v --tb=short- name: Build packagerun: |pip install buildpython -m build
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320# Implementation Plan: Folder-Based Memory## OverviewRestructure agentmemory-python from session-based to folder-based memory. The primary unitof storage shifts from `(session_id)` to `(folder_path, agent_id)`. Core business logic(`functions.py`) is rewritten first; REST endpoints and MCP tools (`app.py`) are updatednext; finally the viewer (`index.html`) is rebuilt to four tabs: Folders, Memories, Graph,Timeline. A migration endpoint and a pytest + hypothesis test suite round out the work.---## Tasks- [x] 1. Rewrite KV scope registry and core helpers in `src/functions.py`- [x] 1.1 Replace the `KV` class with the folder-based scope definitions- Remove all session/lesson/slot/action/crystal/sketch/facet/sentinel/signal/checkpoint/mesh/routine scopes- Add `KV.folders = "mem:folders"`, `KV.folder_obs(folder_path, agent_id)`, `KV.folder_meta(folder_path, agent_id)`- Keep `KV.memories`, `KV.bm25Index`, `KV.audit`; keep `KV.relations` (repurposed for graph edges)- _Requirements: REQ-001, REQ-004, REQ-005_- [x] 1.2 Add `normalize_folder_path()` utility function- Apply `os.path.normpath`, convert OS separators to `/`, strip leading/trailing slashes- Reject (raise `ValueError`) if the normalized path contains `..` segments- Cap `folder_path` and `agent_id` at 512 characters before any scope construction- _Requirements: REQ-002, REQ-063, REQ-064, REQ-066_- [ ]* 1.3 Write property test for `normalize_folder_path` — idempotency- **Property 8: Path Normalization Idempotency**- **Validates: REQ-074 / Requirements REQ-002**- Use `hypothesis.strategies.text()` with a mix of Windows and POSIX path strings- Assert `normalize_folder_path(normalize_folder_path(p)) == normalize_folder_path(p)` for all valid inputs- [x] 2. Implement `folder_observe()` — observation ingestion- [x] 2.1 Write `folder_observe(kv, payload) -> dict` in `src/functions.py`- Validate required fields: `folderPath`, `agentId`, `text`, `timestamp`; raise `ValueError` if missing- Normalize `folder_path` via `normalize_folder_path()`; strip and validate `agent_id`- Call `strip_private_data(text)` before any storage; cap text at 4000 chars- Generate `obs_id = generate_id("fobs")`; build `FolderObservation` dict with all fields- Write to `KV.folder_obs(folder_path, agent_id)` under `obs_id`- Upsert `KV.folder_meta` (`obsCount += 1`, update `lastUpdated`); upsert `KV.folders` index entry- Add to `_bm25_index`; call `vector_index_add_guarded` if provider set; schedule persistence save- Write audit log entry via `kv.commit_version`; broadcast via `broadcast_stream`- Enforce `MAX_OBS_PER_FOLDER` cap (default 2000, env-configurable); raise `ValueError` if reached- _Requirements: REQ-003, REQ-007, REQ-008, REQ-009, REQ-010, REQ-011, REQ-012, REQ-013, REQ-014, REQ-015_- [ ]* 2.2 Write property test for `folder_observe` — pair isolation- **Property 1: Pair Isolation**- **Validates: REQ-068**- Generate two distinct `(folderPath, agentId)` pairs via `hypothesis`; write one observation to each- Assert `kv.list(KV.folder_obs(a)) ∩ kv.list(KV.folder_obs(b)) = ∅`- [ ]* 2.3 Write property test for `folder_observe` — observation count consistency- **Property 2: Observation Count Consistency**- **Validates: REQ-069**- Generate N random observations for a pair (N drawn from `hypothesis.strategies.integers(1, 20)`)- Assert `kv.get(KV.folder_meta(fp, aid), "meta")["obsCount"] == len(kv.list(KV.folder_obs(fp, aid)))`- [ ]* 2.4 Write property test for `folder_observe` — index coverage- **Property 3: Index Coverage**- **Validates: REQ-070**- After writing at least one observation for a pair, assert `kv.get(KV.folders, f"{fp}:{aid}")` is not None- [ ]* 2.5 Write property test for `folder_observe` — privacy invariant- **Property 4: Privacy Invariant**- **Validates: REQ-009 / REQ-065**- Inject strings matching `SECRET_PATTERN_SOURCES` patterns into `text`; call `folder_observe`- Assert no stored observation's `text` field matches any secret pattern- [x] 3. Implement `folder_search()`, `folder_timeline()`, and `folder_graph_build()`- [x] 3.1 Write `folder_search(kv, query, limit, folder_path?, agent_id?) -> list` in `src/functions.py`- Delegate to existing `_hybrid_search.search(query, limit * 2)` for BM25 + vector scoring- Hydrate each `obs_id` from `KV.folder_obs` scopes; include matching global memories from `KV.memories`- Apply `folder_path` / `agent_id` post-filters; include `folderPath`, `agentId`, `score` in each result- _Requirements: REQ-016, REQ-017, REQ-018, REQ-019_- [x] 3.2 Write `folder_timeline(kv, limit, folder_path?, agent_id?, before?, after?) -> list`- List all entries from `KV.folders`; apply folder/agent filters; load observations from each pair- Apply `before` / `after` ISO timestamp filters; sort all results by `timestamp` descending; return `[:limit]`- _Requirements: REQ-020, REQ-021, REQ-022_- [ ]* 3.3 Write property test for `folder_timeline` — ordering guarantee- **Property 5: Timeline Ordering**- **Validates: REQ-071**- Generate an arbitrary set of observations with random timestamps; call `folder_timeline(kv, limit=1000)`- Assert `all(result[i]["timestamp"] >= result[i+1]["timestamp"] for i in range(len(result)-1))`- [x] 3.4 Write `folder_graph_build(kv) -> dict`- Build one node per unique `folder_path` in `KV.folders`; aggregate `agentIds` and `obsCount`; assign color via `folderColor(folder_path)` hash- Produce three edge types: `"same-parent"` (shared parent dir), `"cross-ref"` (folder B's path mentioned in folder A's obs text/title), `"agent-shared"` (two folders share an `agentId`)- Deduplicate edges on `(source, target, type)`; return `{"nodes": [...], "edges": [...]}`- _Requirements: REQ-023, REQ-024, REQ-025, REQ-026, REQ-027, REQ-028_- [ ]* 3.5 Write property test for `folder_graph_build` — node uniqueness- **Property 10: Graph Node Uniqueness**- **Validates: REQ-073 / Requirements REQ-023**- Generate observations in multiple `(folder, agent)` combinations sharing some folder paths- Assert `len(nodes) == len({entry["folderPath"] for entry in kv.list(KV.folders)})`- [x] 4. Update `forget()` and `health_check()` / `export_data()` in `src/functions.py`- [x] 4.1 Rewrite `forget(kv, data) -> dict` to handle folder-based deletion- If `memoryId` present: delete from `KV.memories` (existing logic, unchanged)- If `folderPath + agentId` present (no `observationIds`): delete all entries in `KV.folder_obs(fp, aid)`, remove BM25 index entries for each `obs_id`, delete `KV.folder_meta` entry, remove `KV.folders` index entry; set `result["deleted"]`- If `folderPath + agentId + observationIds` present: delete only specified observations, decrement `obsCount` in metadata- _Requirements: REQ-029, REQ-030, REQ-031, REQ-032, REQ-033_- [ ]* 4.2 Write property test for `forget` — completeness- **Property 6: Forget Completeness**- **Validates: REQ-072**- Write N observations for a pair; call `forget({folderPath, agentId})`- Assert `kv.list(KV.folder_obs(fp, aid)) == []`, `kv.get(KV.folders, key) is None`, and no BM25 entry matches any `obs_id` from that pair- [x] 4.3 Update `health_check(kv) -> dict` to return folder-based counts- Return `folderCount` (distinct folder paths), `agentCount`, `pairCount`, `observationCount`, `memoryCount`, `bm25IndexSize`, `vectorIndexSize`, `dbPath`- Remove session-based fields- _Requirements: REQ-047_- [x] 4.4 Update `export_data(kv, opts) -> dict` to v2 folder format- Output `{"folders": [{folderPath, agentId, meta, observations: [...]}], "memories": [...], "exportedAt": ..., "version": "2.0"}`- _Requirements: REQ-045_- [x] 4.5 Update `rebuild_index(kv)` to read from folder observation scopes- Iterate `KV.folders` index entries; load each pair's observations via `KV.folder_obs`; re-add to BM25 and vector indexes- _Requirements: REQ-016_- [x] 5. Checkpoint — verify core business logic- Ensure all tests pass, ask the user if questions arise.- [x] 6. Update REST endpoints in `src/app.py`- [x] 6.1 Rewrite `POST /agentmemory/agent/observe` to call `folder_observe()`- Require `folderPath`, `agentId`, `text`; accept `sessionId` for backward compat (ignore it)- Validate with HTTP 400 if required fields are missing; pass through `folderPath`, `agentId`, `text`, `timestamp`, `type`, `title`, `concepts`, `files`, `importance`- _Requirements: REQ-008, REQ-041, REQ-057_- [x] 6.2 Update `POST /agentmemory/search` to call `folder_search()`- Accept optional `folderPath` and `agentId` in request body; pass to `folder_search()`- _Requirements: REQ-016, REQ-017, REQ-057_- [ ] 6.3 Add `GET /agentmemory/folders` endpoint- Return `kv.list(KV.folders)` sorted by `lastUpdated` descending- _Requirements: REQ-052, REQ-057_- [x] 6.4 Add `GET /agentmemory/folder/observations` endpoint- Accept `folderPath` and `agentId` query params (both required); return `{"observations": [...]}`- Reject with HTTP 400 if either param is missing- _Requirements: REQ-053, REQ-057_- [x] 6.5 Add `POST /agentmemory/timeline` endpoint- Accept optional JSON body `{folderPath?, agentId?, limit?, before?, after?}`; delegate to `folder_timeline()`- _Requirements: REQ-054, REQ-057_- [x] 6.6 Add `GET /agentmemory/graph` endpoint- Delegate to `folder_graph_build(kv)`; return `{"nodes": [...], "edges": [...]}`- _Requirements: REQ-055, REQ-057_- [x] 6.7 Add `POST /agentmemory/migrate` endpoint- Accept optional `dry_run` boolean in body; delegate to `migrate_sessions_to_folders(kv, dry_run)`- Return `{migrated_sessions, migrated_observations, errors}`- _Requirements: REQ-056, REQ-057, REQ-058, REQ-059, REQ-060, REQ-061, REQ-062_- [x] 6.8 Implement `migrate_sessions_to_folders(kv, dry_run=False)` in `src/functions.py`- Read `kv.list("mem:sessions")`; for each session, map `cwd` or `project` → `folderPath`, `agentId` with `"unknown"` fallback- Skip `:raw` observations; build `FolderObservation` from session obs fields; write if not dry-run- Upsert folder metadata and index entries; never delete old `mem:sessions` or `mem:obs:*` scopes- Collect per-session errors; return `{migrated_sessions, migrated_observations, errors}`- _Requirements: REQ-058, REQ-059, REQ-060, REQ-061, REQ-062_- [x] 6.9 Remove or stub out session-based endpoints that have no folder equivalent- Remove/stub: `POST /session/start`, `POST /session/end`, `POST /session/commit`, `GET /session/by-commit`, `GET /sessions`, `GET /observations` (session-scoped), `GET /replay/sessions`- Remove/stub: lessons endpoints (`/lessons`, `/lessons/search`, `/lessons/strengthen`), slots endpoints (`/slot`, `/slots`, `/slot/append`, `/slot/replace`), antigravity endpoints- Remove background worker calls to `lesson_decay_sweep` and `consolidate` from `init_app()`- _Requirements: REQ-040, REQ-051_- [x] 7. Update MCP tool schema and dispatch in `src/app.py`- [x] 7.1 Update `agent_observe` MCP tool schema and handler- Change required fields to `folderPath`, `agentId`, `text`; mark `sessionId` as optional/deprecated- Handler calls `folder_observe(kv, args)`- _Requirements: REQ-041_- [x] 7.2 Update `memory_recall` and `memory_smart_search` MCP tool schemas and handlers- Add optional `folderPath` and `agentId` parameters; handlers call `folder_search()`- _Requirements: REQ-042, REQ-044_- [x] 7.3 Update `memory_export`, `memory_forget`, `memory_diagnose` MCP handlers- `memory_export` calls updated `export_data()` → v2 format- `memory_forget` accepts `memoryId` OR `folderPath + agentId`; calls updated `forget()`- `memory_diagnose` calls updated `health_check()` → folder counts- _Requirements: REQ-045, REQ-046, REQ-047_- [x] 7.4 Add `memory_folders`, `memory_folder_observations`, `memory_timeline` MCP tools- `memory_folders`: no required args; returns `kv.list(KV.folders)`- `memory_folder_observations`: requires `folderPath`, `agentId`; returns observations for that pair- `memory_timeline`: optional `folderPath`, `agentId`, `limit`, `before`, `after`; calls `folder_timeline()`- _Requirements: REQ-048, REQ-049, REQ-050_- [x] 7.5 Remove dropped MCP tools from schema and dispatch- Remove from `GET /mcp/tools` list and `POST /mcp/tools` dispatch: `memory_sessions`, `memory_sessions_list`, `memory_observations` (session), `memory_profile`, `memory_lessons`, `memory_lesson_save`, `memory_lesson_recall`, `memory_lesson_search`, `memory_consolidate`, `memory_reflect`, `memory_crystallize`, `memory_slot_list`, `memory_slot_get`, `memory_slot_create`, `memory_slot_append`, `memory_slot_replace`, `memory_slot_delete`, `memory_action_create`, `memory_action_update`, `memory_frontier`, `memory_antigravity_sync`, `memory_antigravity_sync_all`- _Requirements: REQ-051_- [x] 8. Checkpoint — verify REST and MCP layer- Ensure all tests pass, ask the user if questions arise.- [x] 9. Rebuild viewer dashboard to four tabs in `src/viewer/index.html`- [x] 9.1 Remove old tabs and restructure tab bar to exactly four tabs- Replace current tab bar entries with: Folders, Memories, Graph, Timeline- Remove tab panes and JS sections for: Sessions, Lessons, Slots, Actions, Replay, Profile, Crystals- Update `<div class="tab-bar">` and the `showTab()` / active-tab JS logic accordingly- _Requirements: REQ-034, REQ-040_- [x] 9.2 Implement Folders tab — list view and drill-down detail- On load, fetch `GET /agentmemory/folders`; render table rows with `folderPath`, `agentId`, `obsCount`, `lastUpdated`- On row click, fetch `GET /agentmemory/folder/observations?folderPath=&agentId=`; render observations list with `timestamp`, type badge, `title`, `text` excerpt- Show `summary` field if present; add "Delete folder memory" button that calls `POST /agentmemory/forget`- _Requirements: REQ-035, REQ-036_- [x] 9.3 Preserve Memories tab functionality (no logic change)- Verify existing Memories tab code still works against `GET /agentmemory/memories` and `POST /agentmemory/remember`- Update any session-specific references (e.g. session filter dropdowns) to remove or replace with folder filters- _Requirements: REQ-037_- [x] 9.4 Implement Graph tab with folder-based nodes and edges- Fetch `GET /agentmemory/graph`; render force-directed graph using existing canvas + physics code- Nodes keyed by `folderPath`; color via existing `folderColor()` function; node label = basename of `folderPath`- Render three edge types with distinct stroke styles: `same-parent` (dashed), `cross-ref` (solid), `agent-shared` (dotted)- Update graph sidebar filter checkboxes to match the three new edge types- _Requirements: REQ-038_- [x] 9.5 Implement Timeline tab with folder activity feed- Fetch `POST /agentmemory/timeline` with `{limit: 100}` on tab activate; render observation cards sorted newest-first- Add filter bar: text input for `folderPath` substring match, dropdown for `agentId` (populated from `GET /agentmemory/folders`)- On filter change, re-fetch timeline with updated body params; support `before`/`after` via existing date-range controls pattern- _Requirements: REQ-039_- [x] 9.6 Update WebSocket handler to process `folder_observation` broadcast events- Change the `type == "compressed_observation"` / `type == "raw_observation"` branch to also handle `type == "folder_observation"`- On receive, append to the Timeline tab live feed if it is active; update Folders tab obsCount badge if that folder is visible- _Requirements: REQ-013_- [x] 10. Update supporting files- [x] 10.1 Update `requirements.txt` to add `pytest` and `hypothesis`- Add `pytest==8.3.5` and `hypothesis==6.131.15` under a `# dev` comment- _Requirements: design testing strategy_- [x] 10.2 Update `start.sh` to remove session-based startup logic- Remove any session auto-complete or lesson-decay invocations from startup- _Requirements: REQ-040, REQ-051_- [x] 10.3 Update `sync.py` if it references session-scoped KV keys- Replace any hardcoded `mem:sessions` or `mem:obs:*` references with `mem:folders` and `mem:folder:*` patterns for backup filtering- _Requirements: REQ-004_- [x] 11. Write pytest + hypothesis test suite- [x] 11.1 Create `tests/test_normalize.py` — unit tests for `normalize_folder_path`- Test Windows paths (`C:\Users\foo`), POSIX paths, paths with `..`, UNC paths, trailing slashes, empty string (expect `ValueError`)- _Requirements: REQ-002, REQ-063_- [x] 11.2 Create `tests/test_folder_observe.py` — unit tests for `folder_observe`- Test missing required fields raise `ValueError`; test obs ID prefix `fobs_`; test `obsCount` increment; test `KV.folders` index upsert; test `MAX_OBS_PER_FOLDER` cap- _Requirements: REQ-008, REQ-010, REQ-011, REQ-015_- [x] 11.3 Create `tests/test_forget.py` — unit tests for `forget`- Test full pair deletion clears all three scopes; test partial deletion by `observationIds`; test `deleted` count in response- _Requirements: REQ-029, REQ-030, REQ-031, REQ-032, REQ-033_- [x] 11.4 Create `tests/test_timeline.py` — unit tests for `folder_timeline`- Test `before`/`after` filters; test `limit` enforcement; test empty result when no data- _Requirements: REQ-020, REQ-021, REQ-022_- [x] 11.5 Create `tests/test_graph.py` — unit tests for `folder_graph_build`- Test empty KV returns `{nodes: [], edges: []}`; test one node per unique folder; test same-parent edge; test no duplicate edges- _Requirements: REQ-023, REQ-025, REQ-028_- [x] 11.6 Create `tests/test_migration.py` — unit tests for `migrate_sessions_to_folders`- Test `dry_run=True` writes nothing; test `cwd`/`project` fallback to `"unknown"`; test `:raw` obs are skipped; test `errors` list populated on malformed sessions- _Requirements: REQ-058, REQ-059, REQ-060, REQ-061, REQ-062_- [ ]* 11.7 Create `tests/test_properties.py` — all Hypothesis property tests- **Property 1: Pair Isolation** (REQ-068)- **Property 2: Observation Count Consistency** (REQ-069)- **Property 3: Index Coverage** (REQ-070)- **Property 4: Privacy Invariant** (REQ-065)- **Property 5: Timeline Ordering** (REQ-071)- **Property 6: Forget Completeness** (REQ-072)- **Property 7: Memory Version Uniqueness** (REQ-073)- **Property 8: Path Normalization Idempotency** (REQ-074)- **Property 10: Graph Node Uniqueness** (REQ-023)- Use a temp-file SQLite DB (`tmp_path` fixture) for each test; isolate with `@given` + `@settings(max_examples=50)`- [x] 12. Final checkpoint — full test run- Ensure all tests pass (`pytest tests/`), ask the user if questions arise.---## Notes- Tasks marked with `*` are optional and can be skipped for a faster MVP- Each task references specific requirements for traceability- The migration endpoint (task 6.8) is non-destructive: old `mem:sessions` / `mem:obs:*` data is never deleted- Property tests in `tests/test_properties.py` (task 11.7) consolidate all Hypothesis tests; the earlier inline property test tasks (1.3, 2.2–2.5, 3.3, 3.5, 4.2) are equivalent sub-sets and can be skipped if 11.7 is implemented- `src/db.py` schema is unchanged — only KV scope strings change, not the SQLite table structure- The `folderColor()` function referenced by the Graph tab and `folder_graph_build()` is the existing hash-to-HSL function already in `index.html`; it should be extracted or duplicated into `functions.py` for server-side use## Task Dependency Graph```json{"waves": [{ "id": 0, "tasks": ["1.1", "1.2"] },{ "id": 1, "tasks": ["1.3", "2.1"] },{ "id": 2, "tasks": ["2.2", "2.3", "2.4", "2.5", "3.1", "3.2", "4.1"] },{ "id": 3, "tasks": ["3.3", "3.4", "4.2", "4.3", "4.4", "4.5"] },{ "id": 4, "tasks": ["3.5", "6.1", "6.2", "6.3", "6.4", "6.5", "6.6", "6.8"] },{ "id": 5, "tasks": ["6.7", "6.9", "7.1", "7.2", "7.3"] },{ "id": 6, "tasks": ["7.4", "7.5", "9.1", "10.1", "10.2", "10.3"] },{ "id": 7, "tasks": ["9.2", "9.3", "9.4", "9.5"] },{ "id": 8, "tasks": ["9.6", "11.1", "11.2", "11.3", "11.4", "11.5", "11.6"] },{ "id": 9, "tasks": ["11.7"] }]}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389# Implementation Plan: agentmemory-python — Upscale & UX Overhaul## OverviewThe folder-based memory migration is complete. This plan covers the next phase:structural refactoring to eliminate the god-file problem, UX uplift on the viewerdashboard, reliability improvements to the storage and indexing layers, and newdeveloper-facing features. Work is organized into four parallel tracks that can beassigned to different engineers independently.**Track A — Backend Structure** (Senior Backend)**Track B — Viewer UX** (Frontend / Full-Stack)**Track C — Reliability & Testing** (Backend / QA)**Track D — Integrations & DX** (DevEx / Infra)---## Tasks## Track A — Backend Structure Refactor> Owner: Senior Backend Dev> Goal: Break the god files apart so the codebase scales to parallel contributions.> Priority: CRITICAL — blocks all other backend work from being clean.- [x] A1. Split `src/app.py` into Flask blueprints- [x] A1.1 Create `src/routes/` directory with `__init__.py`- Move observation routes (`/observe`, `/agent/observe`, `/folder/observations`, `/folders`) → `src/routes/observations.py`- Move memory routes (`/remember`, `/agent/remember`, `/memories`, `/forget`) → `src/routes/memories.py`- Move search + timeline routes (`/search`, `/timeline`) → `src/routes/search.py`- Move graph routes (`/graph`, `/graph/stats`, `/graph/query`) → `src/routes/graph.py`- Move health + audit routes (`/livez`, `/health`, `/audit`, `/config/flags`) → `src/routes/health.py`- Move MCP routes (`/mcp/tools` GET + POST) → `src/routes/mcp.py`- Move migration route (`/migrate`) → `src/routes/migration.py`- _Each blueprint file registers with `Blueprint(__name__)` and imports only what it needs_- [x] A1.2 Rebuild `src/app.py` as a thin factory- `create_app()` factory function: init DB, init embeddings, register all blueprints, set up WebSocket, register `after_request` CORS hook- Keep `init_app()` logic but move background thread setup into a separate `src/workers.py`- `if __name__ == "__main__"` block stays minimal — just `create_app().run()`- Target: `app.py` under 150 lines after refactor- [x] A1.3 Validate no route regressions after blueprint split- Run full `pytest tests/` suite; manually hit every endpoint via `/livez` sanity pass- Check WebSocket still connects and broadcasts after split- [ ] A2. Split `src/functions.py` into focused modules- [ ] A2.1 Create `src/memory/` package- `src/memory/observe.py` — `folder_observe()`, `observe()`, `build_synthetic_compression()`, `strip_private_data()`- `src/memory/remember.py` — `remember()`, `forget()`, `jaccard_similarity()`- `src/memory/context.py` — `context()`, `export_data()`, `rebuild_index()`- `src/memory/graph.py` — `folder_graph_build()`, `get_relations()`, `add_relation()`, `folderColor()`- `src/memory/timeline.py` — `folder_timeline()`, `folder_search()`- `src/memory/health.py` — `health_check()`, `auto_forget()`- [~] A2.2 Keep `src/functions.py` as a compatibility shim- Re-export everything from `src/memory/*` via `from memory.observe import *` etc.- This avoids breaking `app.py` imports during the transition period- Remove the shim in a follow-up PR once blueprints are fully referencing the new modules- [~] A2.3 Move `KV` class and path utilities to `src/storage/`- `src/storage/scopes.py` — `KV` class with all scope definitions- `src/storage/paths.py` — `normalize_folder_path()`, `validate_agent_id()`, `generate_id()`, `fingerprint_id()`- `src/storage/images.py` — `save_image_to_disk()`, `delete_image()`, `touch_image()`, `is_managed_image_path()`- [ ] A3. Fix `src/db.py` connection management- [~] A3.1 Implement per-thread persistent connections using `threading.local()`- Replace every `conn = self._get_conn()` / `conn.close()` pattern with a `_local = threading.local()` cache- Connection is opened once per thread and reused; close only on explicit `teardown()` or thread exit- Keep the write `_lock` for serializing INSERT/UPDATE/DELETE operations- [~] A3.2 Add WAL checkpoint on graceful shutdown- Register a `SIGTERM` / `atexit` handler in `src/workers.py` that calls `PRAGMA wal_checkpoint(FULL)` before exit- This ensures the BM25/vector index shards are flushed to the DB before the process dies- [~] A3.3 Add `db.stats()` method for the health endpoint- Return `{"db_size_bytes": ..., "kv_row_count": ..., "audit_row_count": ..., "wal_size_bytes": ...}`- Used by the upgraded `/health` endpoint- [ ] A4. Debounce index persistence writes- [~] A4.1 Replace `IndexPersistence.schedule_save()` with a real debounce queue- Use a `threading.Timer` that resets on each call; fires the actual `save()` after 5 seconds of inactivity- This prevents a save on every single observation write under high throughput- [~] A4.2 Add dirty-flag tracking to `SearchIndex` and `VectorIndex`- Set `self._dirty = True` in `add()` and `remove()`; reset in `save()`- Skip `save()` entirely if `not _dirty`- [~] A4.3 Write unit test for debounce behavior- Assert that 100 rapid `add()` calls result in exactly 1 persistence save, not 100---## Track B — Viewer UX Overhaul> Owner: Frontend / Full-Stack Dev> Goal: Elevate the viewer from a debug tool to a real developer dashboard.> Priority: HIGH — highest user-visible impact.- [ ] B1. Add Command Palette (`Ctrl+K` / `Cmd+K`)- [~] B1.1 Build command palette overlay in `index.html`- Fuzzy-search across: folder names, memory content snippets, observation titles, tab names- Data sources: in-memory cache of last-loaded folders + memories (no extra API calls on keypress)- Keyboard: `↑`/`↓` to navigate results, `Enter` to navigate to item, `Escape` to close- Show result type badge (Folder / Memory / Observation) and secondary detail (agentId / timestamp)- [~] B1.2 Register global keydown listener- `document.addEventListener("keydown", ...)` — detect `Ctrl+K` on Windows/Linux, `Cmd+K` on Mac- Focus input field on open; re-focus last active element on close- [~] B1.3 Style command palette- Modal overlay with `backdrop-filter: blur(4px)` behind the panel- Max-width 640px, centered; input at top, results list below with keyboard-highlight state- Respect `data-theme="dark"` CSS vars; animate open/close with `transform: translateY(-8px) → 0` + `opacity`- [ ] B2. Replace Canvas graph with D3 force-directed SVG- [~] B2.1 Add D3 v7 via CDN with CSP nonce- Load `d3.v7.min.js` via `<script nonce="__AGENTMEMORY_VIEWER_NONCE__">` inline or from self-hosted path- Remove the existing Canvas `<canvas>` element and hand-rolled physics loop- [~] B2.2 Implement D3 force simulation on SVG- Nodes as `<circle>` + `<text>` SVG groups; size proportional to `obsCount`- Three link types rendered as distinct path styles: `same-parent` (dashed `stroke-dasharray: 6,3`), `cross-ref` (solid), `agent-shared` (dotted `stroke-dasharray: 2,4`)- `d3.forceManyBody().strength()` tuned per node count: `-80` for < 20 nodes, `-200` for 20–100, `-400` for 100+- [~] B2.3 Add zoom/pan and click-to-expand- `d3.zoom()` for pan + scroll-to-zoom; double-click node to highlight its edges and neighbors, dim all others- Click on a node opens the Folders tab filtered to that `folderPath`- [~] B2.4 Fix graph edge label overlap bug (ROADMAP item)- Use `d3.forceCollide()` on label bounding boxes; set `textAnchor` dynamically based on node position relative to center- Labels only show at zoom > 0.6; below that, show labels only for hovered node- [ ] B3. Implement virtual scroll on Timeline and Folders tabs- [~] B3.1 Build a reusable `VirtualList` helper in JS- Takes `container`, `items[]`, `rowHeight`, `renderItem(item) → HTMLElement`- Uses `IntersectionObserver` on a sentinel element at the bottom to load next page- Maintains a window of ~50 rendered DOM nodes, recycling off-screen rows- [~] B3.2 Apply `VirtualList` to Timeline tab- Replace current `observations.forEach(renderObsCard)` with `VirtualList`- Fetch first 50 observations; load next 50 on scroll near bottom via `/timeline` with `before` cursor from last item's timestamp- [~] B3.3 Apply `VirtualList` to Folders tab observation drill-down- When a folder row is expanded, load observations with the same virtual scroll pattern- [ ] B4. First-run onboarding experience- [~] B4.1 Detect empty state on Dashboard tab load- Check `health_check` response: if `observationCount === 0` and `memoryCount === 0`, show onboarding card- [~] B4.2 Build onboarding card component- Three-step guide: (1) Configure `AGENTMEMORY_SECRET` env var, (2) Set `GEMINI_API_KEY` for semantic search, (3) Point your agent hook at `POST /agentmemory/agent/observe`- Each step shows a code snippet (pre-formatted, with a copy button) and a green checkmark if the feature is already active (read from `/config/flags` response)- Dismissable with "Got it" button; stores dismissed state in `localStorage`- [~] B4.3 Add "copy to clipboard" utility function- `copyToClipboard(text)` uses `navigator.clipboard.writeText()` with fallback to `document.execCommand("copy")`- Show a transient "Copied!" tooltip for 1.5 seconds after click- [ ] B5. Add MCP Tool Tester tab- [~] B5.1 Add "Tools" tab to the tab bar- Fetch `GET /agentmemory/mcp/tools` on tab activate; render a list of all tools with name + description- [~] B5.2 Build tool invocation panel- Click a tool → show its `inputSchema` as an auto-generated JSON editor (textarea pre-filled with `{}` containing all required keys)- "Run" button posts to `POST /agentmemory/mcp/tools` with `{name, arguments}`- Response rendered as syntax-highlighted JSON below the editor; error state shown in red- [~] B5.3 Add request/response history for the session- Keep last 10 tool calls in memory; render as collapsible history entries above the editor- Each history entry shows tool name, timestamp, and success/error badge- [ ] B6. Viewer polish and accessibility- [~] B6.1 Fix dark mode inconsistencies- Audit all components against `data-theme="dark"` CSS vars; find and fix the graph tooltip and graph controls that don't fully respond to theme changes- Test in both themes: all text must meet WCAG AA contrast ratio (4.5:1 for body, 3:1 for large text)- [~] B6.2 Add keyboard navigation for tabs- `Tab` key cycles through tab buttons; `Enter`/`Space` activates; `←`/`→` arrow keys move between tabs when a tab has focus- Add `role="tablist"`, `role="tab"`, `aria-selected`, `aria-controls` ARIA attributes to the tab bar- [~] B6.3 Add loading skeleton states- Replace `<div class="loading">Loading...</div>` with animated skeleton placeholder cards that match the shape of the real content- Use CSS `@keyframes shimmer` with a `background: linear-gradient(90deg, ...)` animation---## Track C — Reliability & Testing> Owner: Backend / QA Dev> Goal: Close the test coverage gap and harden the system against bad inputs and restarts.> Priority: HIGH — required before any production deployment.- [ ] C1. Write tests for the core observe/remember/search/context pipeline- [~] C1.1 Create `tests/test_observe_core.py`- Test `observe()` with valid payload → returns obs dict with correct fields- Test `observe()` with missing `sessionId` / `hookType` / `timestamp` → raises `ValueError`- Test that `strip_private_data()` fires and `[REDACTED_SECRET]` appears in stored obs- Test that `MAX_OBS_PER_SESSION` env cap raises `ValueError` when exceeded- [~] C1.2 Create `tests/test_remember.py`- Test `remember()` creates a new memory with `isLatest=True`- Test that a second `remember()` with > 0.7 Jaccard similarity sets `isLatest=False` on the old memory and links via `parentId`- Test that a second `remember()` with < 0.7 similarity creates an independent second memory- [~] C1.3 Create `tests/test_search.py`- Test `SearchIndex.add()` + `SearchIndex.search()` returns the added document at rank 1 for an exact-match query- Test prefix matching: index `"authentication"`, search `"authen"` → doc appears in results- Test synonym expansion: index `"database connection"`, search `"db conn"` → doc appears via synonym map- Test `HybridSearch.search()` in BM25-only mode (no embedding provider) returns same results as `SearchIndex.search()`- [~] C1.4 Create `tests/test_context.py`- Test `context()` respects `TOKEN_BUDGET` — returned context string is under budget- Test that pinned slot content appears first in context output- Test that empty DB returns a well-formed but minimal context dict- [ ] C2. Write Hypothesis property tests- [~] C2.1 Create `tests/test_properties.py` with all 8 property tests- **Property 1: Pair Isolation** — two distinct `(folderPath, agentId)` pairs never share observations- **Property 2: Observation Count Consistency** — `meta.obsCount == len(kv.list(folder_obs_scope))`- **Property 3: Index Coverage** — every written pair has a `KV.folders` entry- **Property 4: Privacy Invariant** — no stored obs text matches any secret regex pattern after `folder_observe()`- **Property 5: Timeline Ordering** — `folder_timeline()` always returns results sorted newest-first- **Property 6: Forget Completeness** — after `forget({folderPath, agentId})`, all three scopes are empty and BM25 has no entry for any obs from that pair- **Property 7: Memory Version Uniqueness** — only one memory per concept cluster has `isLatest=True`- **Property 8: Path Normalization Idempotency** — `normalize(normalize(p)) == normalize(p)` for all valid inputs- Use `tmp_path` pytest fixture for isolated SQLite DB per test; `@settings(max_examples=50)`- [ ] C3. Add integration tests for REST endpoints- [~] C3.1 Create `tests/test_api.py` using Flask test client- Test `POST /agentmemory/agent/observe` → 201 with obs id- Test `POST /agentmemory/agent/observe` missing `folderPath` → 400- Test `POST /agentmemory/search` with query → 200 with results list- Test `GET /agentmemory/folders` → 200 with folders list- Test `GET /agentmemory/health` → 200 with `folderCount`, `observationCount` keys- Test `GET /agentmemory/livez` → 200 without auth (open endpoint)- Test authenticated endpoints return 401 when `AGENTMEMORY_SECRET` is set but token is wrong- [ ] C4. Improve HuggingFace sync reliability- [~] C4.1 Replace mtime-based sync trigger with audit log high-water mark- On each sync iteration, read `MAX(ts)` from `audit_log`; compare to last-synced high-water mark stored in a local `.sync_state` file- Only upload if `current_max_ts > last_synced_ts`; update the watermark after successful upload- This eliminates false-positive uploads caused by WAL mode mtime changes- [~] C4.2 Add sync status to the `/health` endpoint- Report `last_sync_at` (ISO timestamp of last successful HF upload), `sync_status` (`"ok"` / `"never"` / `"error"`), and `db_size_bytes`- Read from `.sync_state` file; if file doesn't exist, report `"never"`- [ ] C5. Add graceful shutdown handler- [~] C5.1 Register `SIGTERM` and `SIGINT` handlers in `src/workers.py`- On signal: set a global `_shutting_down` flag; wait for any in-flight `schedule_save()` debounce timer to fire; call `persistence.save()` synchronously; log shutdown message- Exit cleanly with code 0---## Track D — Integrations & Developer Experience> Owner: DevEx / Infra Dev> Goal: Make agentmemory easier to install, configure, and connect to agents.> Priority: MEDIUM — high value but not blocking.- [ ] D1. Clean up dead code and scratch files- [~] D1.1 Delete scratch and personal utility files- Remove `scratch_diff.txt`, `scratch_test_import.py` from repo root- Remove `push_local_data.py` and `push_second_brain.py` — these are personal sync scripts, not library code- Remove `migrate_dolt_to_sqlite.py` — the migration is done; archive it in `docs/migration/` if it needs to be kept for reference- [~] D1.2 Remove all 410-stub route handlers from `app.py`- Delete route functions for: `api_session_start`, `api_session_end`, `api_session_commit`, `api_session_by_commit`, `api_sessions`, `api_replay_sessions`, `api_antigravity_sync`, `api_lessons_list`, `api_lessons_save`, `api_lessons_search`, `api_lessons_strengthen`, `api_slots_list`, `api_slots_get`, `api_slots_create`, `api_slots_append`, `api_slots_replace`, `api_slots_delete`, `api_slots_reflect`, `api_timeline_legacy`- These return 410 and serve no purpose except confusion; the routes are already documented as removed- [~] D1.3 Fix dead references in `mcp_stdio.py`- `perform_antigravity_sync_all_local()` calls `/summarize` and `/slot/reflect` which are 410 — update or remove these calls- The Antigravity sync logic (both functions) is personal/business-specific; move to `examples/antigravity_sync.py` and remove from the generic MCP bridge- Clean up the double-import of `os`, `json`, `requests` inside `perform_antigravity_sync_local()`- [~] D1.4 Move `DESIGN.md` and clarify its purpose- Rename to `docs/viewer-design-system.md` — the current name `DESIGN.md` implies system architecture- Create a real `ARCHITECTURE.md` at the repo root that documents the Flask blueprint structure, module responsibilities, KV scope layout, and data flow (observe → BM25/vector → WebSocket → viewer)- [ ] D2. Fix CORS and security hardening- [~] D2.1 Move CORS allowlist to configuration- Replace the `after_request` string-matching logic with a configurable `AGENTMEMORY_CORS_ORIGINS` env var (comma-separated)- Default to `http://localhost:*,http://127.0.0.1:*,vscode-webview://*` — still localhost-only but driven by config- Add `chrome-extension://` support as an explicit opt-in via env var, not hardcoded- [~] D2.2 Stop injecting `AGENTMEMORY_SECRET` into HTML template- The current `__AGENTMEMORY_AUTO_TOKEN__` replacement embeds the raw secret in the page source- Replace with a session-scoped viewer token: on page load, the server issues a short-lived viewer token (signed HMAC of `secret + timestamp`, valid 1h) via a `Set-Cookie` header- The viewer uses this cookie for API calls; the actual `AGENTMEMORY_SECRET` never touches the DOM- [ ] D3. Build prebuilt agent hook scripts- [~] D3.1 Create `hooks/claude-code-hook.sh` for Claude Code- Bash script that posts to `POST /agentmemory/agent/observe` on each tool use- Reads `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET` from environment- Include `folderPath` from `$PWD`, `agentId` from `$CLAUDE_AGENT_ID` or `"claude-code"`- [~] D3.2 Create `hooks/cursor-hook.js` for Cursor- JavaScript snippet for Cursor's `.cursorrules` hook system- Same endpoint and payload structure as the bash version- [~] D3.3 Create `hooks/powershell-hook.ps1` for terminal sessions- Formalize and generalize the hook currently documented in `agentmemory.md`- Parameterize `$ServerUrl` and `$AgentId`; ship as a ready-to-source snippet- [~] D3.4 Update `INSTALL_FOR_AGENTS.md` with hook setup instructions- One section per agent type; link to the corresponding hook script in `hooks/`- Include the `.env` file format and `AGENTMEMORY_SECRET` setup steps- [ ] D4. Build `pip`-installable package- [~] D4.1 Add `pyproject.toml`- Package name: `agentmemory`; entry point: `agentmemory = src.app:main`- Include `src/viewer/` as package data- Python `>=3.10` requirement- [~] D4.2 Add CLI entrypoint- `agentmemory serve [--port PORT] [--host HOST]` — starts the Flask server- `agentmemory migrate` — runs `migrate_sessions_to_folders()` and prints summary- `agentmemory export [--output FILE]` — runs `export_data()` and writes JSON- [~] D4.3 Update GitHub Actions CI workflow- Add steps: `pip install -e .[dev]`, `pytest tests/ -v`, `pip install build; python -m build`- Run on `push` to `main` and `pull_request`- [ ] D5. Additional embedding provider support- [~] D5.1 Add `OpenAIEmbeddingProvider` class to `src/search.py`- Mirror the `GeminiEmbeddingProvider` interface: `embed(text)`, `embed_batch(texts)`, `dimensions` (1536 for `text-embedding-3-small`)- Use `urllib.request` (no new dependencies); read API key from `OPENAI_API_KEY` env var- [~] D5.2 Add local `sentence-transformers` provider (optional install)- `SentenceTransformerProvider` class; lazy-import `sentence_transformers`; log a clear error if not installed- Default model: `all-MiniLM-L6-v2` (384 dims); configurable via `AGENTMEMORY_LOCAL_EMBEDDING_MODEL` env var- [~] D5.3 Auto-select embedding provider in `init_app()`- Priority: `GEMINI_API_KEY` → `OPENAI_API_KEY` → `AGENTMEMORY_LOCAL_EMBEDDING_MODEL` → BM25-only- Log which provider was selected on startup---## Notes- **Track A must be completed before any other backend feature work.** The blueprint split is the prerequisite that makes parallel development safe. Do not add new routes to the monolithic `app.py`.- **Track B and Track C can run in parallel** with Track A. The viewer and test suite touch different files.- **Track D tasks D1.1–D1.3 (cleanup) can be done immediately** — they are deletions and do not require Track A to finish first.- All new routes follow the existing auth pattern: call `check_auth()` at the top; never skip it.- All new viewer JS follows the existing CSP constraint: no inline event handlers, all scripts nonce-tagged.- Property tests in `tests/test_properties.py` (C2.1) are the authoritative source; unit tests in C1 are complementary, not replacements.- The `D2.2` security fix (token injection) should be shipped before any public/shared deployment.---## Task Dependency Graph```json{"waves": [{"id": 0,"label": "Cleanup (no dependencies)","tasks": ["D1.1", "D1.2", "D1.3", "D1.4"]},{"id": 1,"label": "Structural foundation","tasks": ["A1.1", "A2.3", "A3.1", "C1.1", "C1.2", "C1.3", "B4.1", "B4.2"]},{"id": 2,"label": "Module split + UX foundation","tasks": ["A1.2", "A2.1", "A2.2", "A3.2", "A4.1", "B1.1", "B2.1", "B3.1", "C1.4", "D2.1"]},{"id": 3,"label": "Blueprint validation + UX components","tasks": ["A1.3", "A3.3", "A4.2", "A4.3", "B1.2", "B1.3", "B2.2", "B3.2", "B3.3", "C2.1", "C3.1", "D2.2"]},{"id": 4,"label": "Advanced features","tasks": ["B2.3", "B2.4", "B4.3", "B5.1", "B5.2", "C4.1", "C4.2", "C5.1", "D3.1", "D3.2", "D3.3", "D5.1"]},{"id": 5,"label": "Polish + packaging","tasks": ["B5.3", "B6.1", "B6.2", "B6.3", "D3.4", "D4.1", "D4.2", "D4.3", "D5.2", "D5.3"]}]}```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144# agentmemory-python — Architecture
## Overview
A Python REST + WebSocket + MCP memory server backed by SQLite.Agents store observations scoped by `(folderPath, agentId)` pairs and retrievecontext at session start. No Node.js, no external database, no build step.
---
## Module Responsibilities
```src/├── app.py Flask application factory (create_app).│ Initialises DB, embeddings, blueprints, WebSocket,│ CORS hook, and background workers.│├── routes/ Flask blueprints — one per domain area.│ ├── __init__.py register_blueprints(app) helper.│ ├── observations.py /observe, /agent/observe, /folders, /folder/observations│ ├── memories.py /remember, /agent/remember, /memories, /forget│ ├── search.py /search, /timeline│ ├── graph.py /graph, /graph/stats, /graph/query, /graph/build│ ├── health.py /livez, /health, /audit, /config/flags│ ├── mcp.py GET+POST /mcp/tools│ └── migration.py /migrate│├── functions.py Core business logic.│ observe(), folder_observe(), remember(), forget(),│ folder_search(), folder_timeline(), health_check(),│ export_data(), rebuild_index(), auto_forget(),│ folder_graph_build(), KV scope registry.│├── db.py StateKV — SQLite wrapper (WAL mode, kv_store + audit_log).│├── search.py SearchIndex (BM25 + Porter stemmer + synonyms),│ VectorIndex (cosine similarity, base64 float32),│ GeminiEmbeddingProvider, HybridSearch (RRF).│├── workers.py Daemon threads: index rebuild, auto-forget sweep,│ graceful shutdown (SIGTERM/SIGINT).│├── viewer_helpers.py make_viewer_response() — reads viewer/index.html,│ injects nonce + version, sets CSP headers.│├── mcp_stdio.py stdio MCP bridge: reads AGENTMEMORY_URL and│ AGENTMEMORY_SECRET, proxies tool calls to the HTTP API.│└── viewer/ └── index.html Single-file HTML dashboard (no bundler).```
---
## KV Scope Layout
All data lives in a single SQLite file (`~/.agentmemory/agentmemory.db`) in two tables:
- `kv_store(scope TEXT, key TEXT, value TEXT, PRIMARY KEY(scope, key))` — JSON values- `audit_log(id, ts, agent_id, message)` — write audit trail
| Scope | Content ||-------|---------|| `mem:folders` | Global index of all `(folderPath, agentId)` pairs || `mem:folder:{path}:{agent}` | Observations for one `(folder, agent)` pair || `mem:foldermeta:{path}:{agent}` | Metadata for one pair (obsCount, lastUpdated, summary) || `mem:memories` | Long-term global memories || `mem:index:bm25` | BM25 index shards (manifest + data chunks) || `mem:audit` | Audit log entries (via `record_audit()`) || `mem:relations` | Knowledge graph edges || `mem:sessions` | Legacy session objects (read-only for migration) || `mem:obs:{session_id}` | Legacy session observations (read-only for migration) |
---
## Data Flow
### Observation Ingestion
```POST /agent/observe └─► folder_observe(kv, payload) 1. Validate folderPath, agentId, text, timestamp 2. normalize_folder_path() + validate_agent_id() 3. strip_private_data() 4. Cap text at 4000 chars 5. Enforce MAX_OBS_PER_FOLDER cap 6. Generate obs_id (fobs_...) 7. Write FolderObservation to KV.folder_obs(fp, aid) 8. Upsert folder metadata (KV.folder_meta) 9. Upsert global folders index (KV.folders) 10. Add to BM25 index (_bm25_index.add) 11. Add to vector index if embedding provider is set 12. Debounce persistence save (IndexPersistence.schedule_save) 13. Write audit log entry (kv.commit_version) 14. Broadcast via WebSocket (/stream/mem-live/viewer) └─► return {"observationId": obs_id}```
### Search
```POST /search or POST /mcp/tools {name:"memory_recall"} └─► folder_search(kv, query, limit, folderPath?, agentId?) 1. HybridSearch.search() → BM25 + vector RRF fusion 2. Load all (folder, agent) pairs from KV.folders 3. Hydrate obs_ids from KV.folder_obs scopes 4. Apply folderPath/agentId post-filters 5. Also include matching global memories 6. Sort by score descending, cap at limit```
### Memory Versioning
`remember()` scans existing memories for Jaccard similarity > 0.7.If found, old memory is marked `isLatest=False` and new memory sets `parentId`.
---
## Authentication
All endpoints except `/livez` check `AGENTMEMORY_SECRET` via timing-safe`hmac.compare_digest` Bearer token comparison. No secret → no auth check.
---
## WebSocket
`/stream/mem-live/viewer` broadcasts raw JSON payloads to connected viewers.The viewer's "Replay" tab subscribes to this stream for live observation updates.
---
## Embedding Providers
Priority order (auto-selected at startup):
1. `GeminiEmbeddingProvider` — if `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set (768 dims)2. `OpenAIEmbeddingProvider` — if `OPENAI_API_KEY` is set (1536 dims)3. `SentenceTransformerProvider` — if `AGENTMEMORY_LOCAL_EMBEDDING_MODEL` is set4. BM25-only fallback
Without an embedding provider, `HybridSearch` falls back to pure BM25.104 unmodified lines105106107108109110111104 unmodified linesIf 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)```bashopen http://localhost:3111/viewer104 unmodified lines105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189104 unmodified linesIf you see 0 tools or an error, check that `python src/app.py` is running and `AGENTMEMORY_URL` points at it.## 6. Setting up agent hooksAgent hooks post observations to agentmemory automatically on every tool use, command, or edit — no manual calls required. Hook scripts live in the [`hooks/`](hooks/) directory.### Claude Code (`hooks/claude-code-hook.sh`)Add a `PostToolUse` hook to `.claude/settings.json`. The hook script reads `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET` from your shell environment, so no secrets are embedded in the config file.```json{"hooks": {"PostToolUse": [{"matcher": "*","hooks": [{"type": "command","command": "bash /path/to/hooks/claude-code-hook.sh"}]}]}}```Set the required environment variables before starting Claude Code:```bashexport AGENTMEMORY_URL=http://127.0.0.1:3111export AGENTMEMORY_SECRET=your-secret-here # omit if no auth set```The script picks up `$PWD` as `folderPath` and `$CLAUDE_AGENT_ID` (falling back to `"claude-code"`) as `agentId`.### Cursor (`hooks/cursor-hook.js`)Require the hook from your `.cursorrules` file (or any JS entry point Cursor runs) and call `logObservation()` with the tool name and input:```jsconst { logObservation } = require('/path/to/hooks/cursor-hook.js');// Call inside your Cursor hook handler, e.g. after every tool invocation:logObservation(`Tool: ${toolName}\nInput: ${JSON.stringify(toolInput)}`);```The module reads `AGENTMEMORY_URL`, `AGENTMEMORY_SECRET`, and `AGENTMEMORY_AGENT_ID` from `process.env`. Set them in your shell profile or in Cursor's environment settings.### PowerShell terminal (`hooks/powershell-hook.ps1`)Add a single dot-source line to your PowerShell `$PROFILE` to activate automatic command logging:```powershell. C:\path\to\hooks\powershell-hook.ps1```Set the required variables in `$PROFILE` before the dot-source line:```powershell$env:AGENTMEMORY_URL = "http://127.0.0.1:3111"$env:AGENTMEMORY_SECRET = "your-secret-here" # omit if no auth set$env:AGENTMEMORY_AGENT_ID = "powershell"```The hook installs a PSReadLine `CommandValidationHandler` that fires a background job on every command you run. If PSReadLine is not available, call `Send-AgentMemoryObservation -Text "..."` manually.### `.env` file formatAll hooks and the server itself read credentials from `~/.agentmemory/.env`. Create this file if it doesn't exist:```III_REST_PORT=3111AGENTMEMORY_SECRET=your-secret-hereGEMINI_API_KEY=your-gemini-key-here```The server loads this file on startup. Hook scripts read the same variables from your shell environment (export them from your profile after sourcing `~/.agentmemory/.env`, or use `direnv` / `dotenv` tooling).## 7. Open the viewer (optional)```bashopen http://localhost:3111/viewer
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240#!/usr/bin/env python3"""Antigravity transcript sync — personal/business-specific sync logicextracted from the generic MCP bridge (D1.3).
Reads Gemini Antigravity brain transcripts and posts them to agentmemoryas legacy session observations.
Usage (standalone): python examples/antigravity_sync.py [--mode current_session|current_folder|all]
Or via MCP if you re-add these functions to your own mcp_stdio.py."""
import osimport sysimport jsonimport globimport reimport datetimeimport requests
# Locate the base URL from the environmentBASE = os.getenv("AGENTMEMORY_URL", "http://127.0.0.1:3111").rstrip("/")if not BASE.endswith("/agentmemory"): BASE = f"{BASE}/agentmemory"
_secret = os.getenv("AGENTMEMORY_SECRET")
def _headers(): h = {"Content-Type": "application/json"} if _secret: h["Authorization"] = f"Bearer {_secret}" return h
def perform_antigravity_sync_local(args): """Sync Antigravity transcripts → agentmemory legacy session observations.""" mode = args.get("mode") or "current_session" current_conversation_id = args.get("currentConversationId") current_folder = args.get("currentFolder")
brain_dir = os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "brain") if not os.path.exists(brain_dir): return { "content": [{"type": "text", "text": json.dumps({ "success": False, "syncedSessions": [], "observationsAdded": 0, "error": f"Brain directory not found at {brain_dir}" })}] }
pattern = os.path.join(brain_dir, "*", ".system_generated", "logs", "transcript.jsonl") files = glob.glob(pattern) if not files: return { "content": [{"type": "text", "text": json.dumps({ "success": True, "syncedSessions": [], "observationsAdded": 0 })}] }
conversations = [] for fpath in files: try: mtime = os.path.getmtime(fpath) convo_id = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(fpath)))) conversations.append({"id": convo_id, "transcriptPath": fpath, "mtime": mtime}) except Exception: pass
if not conversations: return {"content": [{"type": "text", "text": json.dumps({"success": True, "syncedSessions": [], "observationsAdded": 0})}]}
conversations.sort(key=lambda x: x["mtime"], reverse=True)
targets = [] if mode == "current_session": if current_conversation_id: match = next((c for c in conversations if c["id"] == current_conversation_id), None) if match: targets = [match] else: targets = [conversations[0]] elif mode == "current_folder": target_folder = (current_folder or os.getcwd()).replace("\\", "/").lower().strip() for convo in conversations: try: with open(convo["transcriptPath"], "r", encoding="utf-8") as tf: text = tf.read().lower().replace("\\/", "/").replace("\\\\", "/") if target_folder in text: targets.append(convo) except Exception: pass elif mode == "all": targets = conversations else: return {"content": [{"type": "text", "text": json.dumps({"success": False, "error": f"Invalid mode: {mode}"})}]}
if not targets: return {"content": [{"type": "text", "text": json.dumps({"success": True, "syncedSessions": [], "observationsAdded": 0})}]}
synced_sessions = [] observations_added = 0 headers_dict = _headers()
for convo in targets: convo_id = convo["id"] tpath = convo["transcriptPath"] session_id = f"antigravity_{convo_id[:18].replace('-', '_')}"
project_path = None try: with open(tpath, "r", encoding="utf-8") as tf: first_line = tf.readline() if first_line: step = json.loads(first_line) m = re.search(r"\[([^\]]+)\]\s*->\s*\[([^\]]+)\]", step.get("content", "")) if m: project_path = m.group(2) except Exception: pass if not project_path: project_path = os.getcwd()
turns = [] current_prompt = None current_timestamp = None try: with open(tpath, "r", encoding="utf-8") as tf: for line in tf: if not line.strip(): continue try: step = json.loads(line) step_type = step.get("type") if step_type == "USER_INPUT": p_text = step.get("content", "") if "<USER_REQUEST>" in p_text: p_text = p_text.split("<USER_REQUEST>")[1] if "</USER_REQUEST>" in p_text: p_text = p_text.split("</USER_REQUEST>")[0] current_prompt = p_text.strip() current_timestamp = step.get("created_at") elif step_type == "PLANNER_RESPONSE" and current_prompt: ts = current_timestamp or step.get("created_at") or datetime.datetime.utcnow().isoformat() + "Z" turns.append({"prompt": current_prompt, "response": step.get("content", ""), "timestamp": ts}) current_prompt = None current_timestamp = None except Exception: pass except Exception: continue
if not turns: continue
convo_synced = False for turn in turns: payload = { "sessionId": session_id, "project": project_path, "cwd": project_path, "hookType": "post_tool_use", "timestamp": turn["timestamp"], "agentId": "antigravity", "data": {"tool_name": "conversation", "tool_input": turn["prompt"], "tool_output": turn["response"]}, } try: requests.post(f"{BASE}/observe", headers=headers_dict, json=payload, timeout=10) observations_added += 1 convo_synced = True except Exception: pass
if convo_synced: synced_sessions.append(convo_id)
return {"content": [{"type": "text", "text": json.dumps({ "success": True, "syncedSessions": synced_sessions, "observationsAdded": observations_added, })}]}
def perform_antigravity_sync_all_local(args): """Master sync: transcript + crystallize + reflect.""" sync_res_outer = perform_antigravity_sync_local(args) try: sync_res = json.loads(sync_res_outer["content"][0]["text"]) except Exception: return sync_res_outer
if not sync_res.get("success"): return sync_res_outer
processed_sessions = sync_res.get("syncedSessions", []) crystallizations = {} reflections = {} headers_dict = _headers()
for cid in processed_sessions: session_id = f"antigravity_{cid[:18].replace('-', '_')}" try: r_sum = requests.post(f"{BASE}/summarize", headers=headers_dict, json={"sessionId": session_id}, timeout=30) crystallizations[session_id] = r_sum.json() if r_sum.status_code == 200 else {"success": False, "error": r_sum.text} except Exception as e: crystallizations[session_id] = {"success": False, "error": str(e)}
try: r_ref = requests.post(f"{BASE}/slot/reflect", headers=headers_dict, json={"sessionId": session_id, "maxObservations": 50}, timeout=30) reflections[session_id] = r_ref.json() if r_ref.status_code == 200 else {"success": False, "error": r_ref.text} except Exception as e: reflections[session_id] = {"success": False, "error": str(e)}
return {"content": [{"type": "text", "text": json.dumps({ "success": True, "syncedSessions": processed_sessions, "observationsAdded": sync_res.get("observationsAdded", 0), "crystallizations": crystallizations, "reflections": reflections, }, indent=2)}]}
if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Sync Antigravity transcripts to agentmemory") parser.add_argument("--mode", default="current_session", choices=["current_session", "current_folder", "all"]) parser.add_argument("--sync-all", action="store_true", help="Also crystallize and reflect") a = parser.parse_args()
if a.sync_all: result = perform_antigravity_sync_all_local({"mode": a.mode}) else: result = perform_antigravity_sync_local({"mode": a.mode})
print(result["content"][0]["text"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#!/usr/bin/env bash# agentmemory Claude Code hook# Source this file or add it to your Claude Code hook configuration.# Reads AGENTMEMORY_URL and AGENTMEMORY_SECRET from environment.## Usage in .claude/settings.json hooks:# "PostToolUse": [{"matcher": "*", "hooks": [{"type": "command", "command": "bash /path/to/claude-code-hook.sh"}]}]
set -euo pipefail
AGENTMEMORY_URL="${AGENTMEMORY_URL:-http://127.0.0.1:3111}"AGENTMEMORY_SECRET="${AGENTMEMORY_SECRET:-}"AGENT_ID="${CLAUDE_AGENT_ID:-claude-code}"FOLDER_PATH="${PWD}"TIMESTAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
# Read observation text from stdin (Claude Code passes hook data via stdin)HOOK_DATA="$(cat)"TEXT="${HOOK_DATA:-Claude Code tool execution in ${FOLDER_PATH}}"
# Truncate text to 4000 charsTEXT="${TEXT:0:4000}"
PAYLOAD=$(cat <<EOF{ "folderPath": "${FOLDER_PATH}", "agentId": "${AGENT_ID}", "text": $(echo "$TEXT" | python3 -c "import json,sys; print(json.dumps(sys.stdin.read()))"), "timestamp": "${TIMESTAMP}"}EOF)
AUTH_HEADER=""if [ -n "${AGENTMEMORY_SECRET}" ]; then AUTH_HEADER="-H \"Authorization: Bearer ${AGENTMEMORY_SECRET}\""fi
curl -sf \ -X POST \ "${AGENTMEMORY_URL}/agentmemory/agent/observe" \ -H "Content-Type: application/json" \ ${AUTH_HEADER:+$AUTH_HEADER} \ -d "${PAYLOAD}" \ --max-time 5 \ > /dev/null 2>&1 || true
exit 01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859/** * agentmemory Cursor hook * * Add to your .cursorrules or Cursor MCP config to log observations. * Uses fetch() (available in Node 18+). * * Environment variables (set in your shell profile): * AGENTMEMORY_URL — default: http://127.0.0.1:3111 * AGENTMEMORY_SECRET — optional bearer token * AGENTMEMORY_AGENT_ID — default: cursor */
const AGENTMEMORY_URL = process.env.AGENTMEMORY_URL || 'http://127.0.0.1:3111';const AGENTMEMORY_SECRET = process.env.AGENTMEMORY_SECRET || '';const AGENT_ID = process.env.AGENTMEMORY_AGENT_ID || 'cursor';
/** * Log an observation to agentmemory. * Call this from your Cursor hook with the relevant text. * * @param {string} text - Observation content (max 4000 chars) * @param {string} [folderPath] - Working directory (defaults to process.cwd()) * @returns {Promise<void>} */async function logObservation(text, folderPath) { const payload = { folderPath: folderPath || process.cwd(), agentId: AGENT_ID, text: String(text).slice(0, 4000), timestamp: new Date().toISOString(), };
const headers = { 'Content-Type': 'application/json' }; if (AGENTMEMORY_SECRET) { headers['Authorization'] = `Bearer ${AGENTMEMORY_SECRET}`; }
try { const res = await fetch(`${AGENTMEMORY_URL}/agentmemory/agent/observe`, { method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(5000), }); if (!res.ok) { console.error(`[agentmemory] observe failed: ${res.status}`); } } catch (err) { // Non-fatal — agentmemory is a best-effort sidecar console.error(`[agentmemory] observe error: ${err.message}`); }}
module.exports = { logObservation };
// Example: log every tool call from Cursor's hook system// In your .cursorrules or MCP hook config, call:// const { logObservation } = require('/path/to/cursor-hook.js');// logObservation(`Tool: ${toolName}\nInput: ${JSON.stringify(toolInput)}`);1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# agentmemory PowerShell terminal hook# Source this file from your $PROFILE to automatically log terminal commands.## Usage:# . C:\path\to\powershell-hook.ps1## Configuration (set as environment variables or override at top of profile):# $env:AGENTMEMORY_URL = "http://127.0.0.1:3111" (default)# $env:AGENTMEMORY_SECRET = "" (optional)# $env:AGENTMEMORY_AGENT_ID = "powershell" (default)
param( [string]$ServerUrl = $env:AGENTMEMORY_URL ?? "http://127.0.0.1:3111", [string]$AgentId = $env:AGENTMEMORY_AGENT_ID ?? "powershell", [string]$Secret = $env:AGENTMEMORY_SECRET ?? "")
function Send-AgentMemoryObservation { param( [string]$Text, [string]$FolderPath = (Get-Location).Path )
$payload = @{ folderPath = $FolderPath agentId = $AgentId text = $Text.Substring(0, [Math]::Min($Text.Length, 4000)) timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") } | ConvertTo-Json -Compress
$headers = @{ "Content-Type" = "application/json" } if ($Secret) { $headers["Authorization"] = "Bearer $Secret" }
try { Invoke-RestMethod ` -Uri "$ServerUrl/agentmemory/agent/observe" ` -Method Post ` -Headers $headers ` -Body $payload ` -TimeoutSec 5 ` -ErrorAction SilentlyContinue | Out-Null } catch { # Non-fatal — agentmemory is a best-effort sidecar }}
# Hook into PSReadLine's CommandValidationHandler to log every commandif (Get-Module -Name PSReadLine -ErrorAction SilentlyContinue) { $existingHandler = (Get-PSReadLineOption).CommandValidationHandler
Set-PSReadLineOption -CommandValidationHandler { param([System.Management.Automation.Language.CommandAst]$CommandAst)
# Forward to existing handler if any if ($existingHandler) { & $existingHandler $CommandAst }
# Log the command to agentmemory (best-effort, non-blocking) $cmd = $CommandAst.ToString() if ($cmd -and $cmd.Trim()) { $job = Start-Job -ScriptBlock { param($u, $a, $s, $t, $f) $payload = "{`"folderPath`":`"$f`",`"agentId`":`"$a`",`"text`":`"$t`",`"timestamp`":`"$(Get-Date -Format 'yyyy-MM-ddTHH:mm:ssZ')`"}" $h = @{"Content-Type"="application/json"} if ($s) { $h["Authorization"] = "Bearer $s" } try { Invoke-RestMethod -Uri "$u/agentmemory/agent/observe" -Method Post -Headers $h -Body $payload -TimeoutSec 5 -EA SilentlyContinue | Out-Null } catch {} } -ArgumentList $ServerUrl, $AgentId, $Secret, $cmd, (Get-Location).Path $null = $job # fire-and-forget }
return $true } Write-Host "[agentmemory] PowerShell hook active (agent: $AgentId, server: $ServerUrl)"} else { Write-Warning "[agentmemory] PSReadLine not available — hook not installed. Call Send-AgentMemoryObservation manually."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596#!/usr/bin/env python3"""Push local ~/.agentmemory/ to HF dataset repo using upload_folder (single commit)."""import os, sys, tempfile, shutil
env_path = os.path.expanduser("~/.agentmemory/.env")with open(env_path) as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: k, v = line.split("=", 1) v = v.strip().strip('"').strip("'") os.environ[k.strip()] = v
try: from huggingface_hub import HfApi from huggingface_hub.utils import RepositoryNotFoundErrorexcept ImportError: print("[push] huggingface_hub not installed") sys.exit(1)
HF_TOKEN = os.environ.get("HF_TOKEN", "")REPO_ID = os.environ.get("AGENTMEMORY_DATASET_REPO", "Yash030/agentmemory-python-data")DATA_DIR = os.path.expanduser("~/.agentmemory")SKIP_FILES = {".env"}ALLOW_HIDDEN = {".hmac"}
if not HF_TOKEN: print("[push] No HF_TOKEN in .env") sys.exit(1)
api = HfApi(token=HF_TOKEN)
try: me = api.whoami() print(f"[push] Logged in as: {me['name']}")except Exception as e: print(f"[push] Auth error: {e}") sys.exit(1)
# Ensure repo existstry: api.repo_info(REPO_ID, repo_type="dataset", token=HF_TOKEN) print(f"[push] Repo {REPO_ID} exists")except RepositoryNotFoundError: print(f"[push] Creating repo {REPO_ID}") api.create_repo(REPO_ID, repo_type="dataset", private=True)except Exception as e: print(f"[push] repo_info error: {e}") sys.exit(1)
# Build a clean staging dir with only files we want to upload# (excludes .env, LOCK files, and hidden files not in ALLOW_HIDDEN)staging = tempfile.mkdtemp(prefix="agentmemory_push_")print(f"[push] Staging to {staging}")
copied = 0skipped = 0for root, dirs, files in os.walk(DATA_DIR): is_inside_dolt = ".dolt" in root.replace("\\", "/").split("/") if not is_inside_dolt: dirs[:] = [d for d in dirs if not d.startswith(".") or d == ".dolt"] for fname in files: if fname in SKIP_FILES: skipped += 1 continue if fname.startswith(".") and fname not in ALLOW_HIDDEN: skipped += 1 continue # Skip LOCK files (held open by Dolt) if fname == "LOCK": skipped += 1 continue full = os.path.join(root, fname) rel = os.path.relpath(full, DATA_DIR).replace("\\", "/") dest = os.path.join(staging, rel.replace("/", os.sep)) os.makedirs(os.path.dirname(dest), exist_ok=True) shutil.copy2(full, dest) copied += 1
print(f"[push] {copied} files staged, {skipped} skipped")
try: print(f"[push] Uploading to {REPO_ID} (single commit)...") api.upload_folder( folder_path=staging, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN, commit_message="sync: push local agentmemory data", ) print(f"[push] Done — all {copied} files uploaded to {REPO_ID}")except Exception as e: print(f"[push] Upload error: {e}") sys.exit(1)finally: shutil.rmtree(staging, ignore_errors=True)1234567891011121314151617181920212223242526272829303132333435363738#!/usr/bin/env python3"""Upload second-brain markdown files to HF dataset repo."""import os, sys
env_path = os.path.expanduser("~/.agentmemory/.env")with open(env_path) as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: k, v = line.split("=", 1) v = v.strip().strip('"').strip("'") os.environ[k.strip()] = v
from huggingface_hub import HfApi
HF_TOKEN = os.environ.get("HF_TOKEN", "")REPO_ID = os.environ.get("AGENTMEMORY_DATASET_REPO", "Yash030/agentmemory-python-data")SRC_DIR = r"D:\Downloads\Projects\Other Projects\Know about me\second-brain"
api = HfApi(token=HF_TOKEN)me = api.whoami()print(f"[push] Logged in as: {me['name']}")
files = [f for f in os.listdir(SRC_DIR) if f.endswith(".md")]print(f"[push] Uploading {len(files)} files to {REPO_ID}/second-brain/")
for fname in files: full = os.path.join(SRC_DIR, fname) api.upload_file( path_or_fileobj=full, path_in_repo=f"second-brain/{fname}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN, ) print(f"[push] OK second-brain/{fname}")
print(f"[push] Done — {len(files)} files uploaded")123456789101112131415161718192021222324252627282930313233343536373839404142[build-system]requires = ["setuptools>=68", "wheel"]build-backend = "setuptools.backends.legacy:build"
[project]name = "agentmemory"version = "0.9.8"description = "A Python REST + WebSocket + MCP memory server for AI agents, backed by SQLite"readme = "README.md"license = { text = "MIT" }requires-python = ">=3.10"dependencies = [ "flask>=3.0.0", "flask-sock>=0.7.0", "requests>=2.31.0", "python-dateutil>=2.8.2", "huggingface_hub>=0.20.0", "websockets>=12.0",]
[project.optional-dependencies]dev = [ "pytest>=8.0.0", "hypothesis>=6.100.0",]local-embeddings = [ "sentence-transformers>=2.7.0",]
[project.scripts]agentmemory = "src.cli:main"
[tool.setuptools.packages.find]where = ["."]include = ["src*"]
[tool.setuptools.package-data]"src.viewer" = ["*.html", "*.svg", "*.js", "*.css"]
[tool.pytest.ini_options]testpaths = ["tests"]python_files = ["test_*.py"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689=== Diff for src/app.py ===--- agentmemory/src/app.py+++ agentmemory-python/src/app.py@@ -34,7 +34,7 @@ from db import StateKV import search import functions-from functions import KV+from functions import KV, query_audit app = Flask(__name__) # Enable CORS for all routes (important for client scripts connecting locally)@@ -358,42 +358,6 @@ sessions.sort(key=lambda s: s.get("startedAt", ""), reverse=True) return jsonify({"success": True, "sessions": sessions}), 200 -@app.route("/agentmemory/replay/load", methods=["GET"])-def api_replay_load():- auth_err = check_auth()- if auth_err:- return auth_err- - session_id = request.args.get("sessionId")- if not session_id:- return jsonify({"error": "sessionId is required"}), 400- - session = kv.get(KV.sessions, session_id)- obs = kv.list(KV.observations(session_id))- - import replay_import- timeline = replay_import.project_timeline(obs)- return jsonify({"success": True, "timeline": timeline, "session": session}), 200--@app.route("/agentmemory/replay/import-jsonl", methods=["POST"])-def api_replay_import_jsonl():- auth_err = check_auth()- if auth_err:- return auth_err- - try:- body = request.get_json(force=True) or {}- path = body.get("path")- max_files = body.get("maxFiles")- - import replay_import- res = replay_import.import_jsonl_data(kv, path=path, max_files=max_files)- - status_code = 200 if res.get("success", True) else 400- return jsonify(res), status_code- except Exception as e:- return jsonify({"error": str(e), "success": False}), 500- @app.route("/agentmemory/session/start", methods=["POST"]) def api_session_start(): auth_err = check_auth()@@ -895,12 +859,292 @@ auth_err = check_auth() if auth_err: return auth_err- + project = request.args.get("project") if not project:- return jsonify({"error": "project query param is required"}), 400+ sessions = kv.list(KV.sessions)+ projects = sorted(set(s.get("project", "") for s in sessions if s.get("project")))+ return jsonify({"projects": projects, "success": True}), 200+ res = functions.get_project_profile(kv, project)++ # Stored profile may lack topConcepts/topFiles — compute from observations if empty+ if not res.get("topConcepts") and not res.get("topFiles"):+ import re as _re, json as _j, os.path as _osp+ from collections import Counter+ sessions = kv.list(KV.sessions)+ project_sessions = [s for s in sessions if s.get("project") == project]+ concept_counts = Counter()+ file_counts = Counter()++ def _harvest_file(path, fc, cc):+ if not isinstance(path, str) or not path:+ return+ fc[path] += 1+ # dirname components → concepts+ parts = _re.split(r'[\\/]', path)+ fname = parts[-1] if parts else ""+ # dir components (skip drive letters, temp paths)+ skip = {"tmp", "temp", "claude", "appdata", "local", "users", "windows"}+ for part in parts[:-1]:+ p = part.lower().strip()+ if p and len(p) > 2 and p not in skip and not _re.match(r'^[a-z]:|^\.|^--', p):+ cc[p] += 1+ # file stem → concept+ stem = _osp.splitext(fname)[0]+ if stem and len(stem) > 2:+ cc[stem.lower()] += 1+ # extension → technology concept+ ext = _osp.splitext(fname)[1].lstrip(".")+ if ext in ("py", "ts", "js", "jsx", "tsx", "go", "rs", "java", "cs", "cpp"):+ cc[ext] += 1++ for s in project_sessions:+ sid = s.get("id", "")+ if not sid:+ continue+ for o in kv.list(KV.observations(sid)):+ # top-level concepts / files+ for c in (o.get("concepts") or []):+ if isinstance(c, str) and c:+ concept_counts[c] += 1+ for f in (o.get("files") or []):+ _harvest_file(f, file_counts, concept_counts)+ # toolName → concept+ tn = o.get("toolName")+ if tn:+ concept_counts[tn] += 1+ # toolInput path fields+ ti = o.get("toolInput")+ if isinstance(ti, str):+ try: ti = _j.loads(ti)+ except Exception: ti = {}+ if isinstance(ti, dict):+ for fk in ("path", "file_path", "file", "filename"):+ _harvest_file(ti.get(fk, ""), file_counts, concept_counts)+ # narrative may be JSON string with path/tool info+ narr = o.get("narrative") or o.get("raw") or ""+ if isinstance(narr, str) and narr.startswith("{"):+ try:+ nd = _j.loads(narr)+ if isinstance(nd, dict):+ tn2 = nd.get("toolName") or nd.get("tool_name")+ if tn2: concept_counts[tn2] += 1+ for fk in ("path", "file_path", "file", "filename"):+ _harvest_file(nd.get(fk, ""), file_counts, concept_counts)+ except Exception:+ pass++ # memories for this project+ for m in kv.list(KV.memories):+ if m.get("project") == project:+ for c in (m.get("concepts") or []):+ if c: concept_counts[c] += 1+ for f in (m.get("files") or []):+ _harvest_file(f, file_counts, concept_counts)++ res["topConcepts"] = [{"concept": c, "frequency": n} for c, n in concept_counts.most_common(20)]+ res["topFiles"] = [{"file": f, "frequency": n} for f, n in file_counts.most_common(20)]+ res["sessionCount"] = len(project_sessions)+ return jsonify(res), 200++# =====================================================================+# Missing endpoints the JS viewer calls+# =====================================================================++@app.route("/agentmemory/memories", methods=["GET"])+def api_memories_list():+ auth_err = check_auth()+ if auth_err:+ return auth_err++ latest_only = request.args.get("latest", "false").lower() == "true"+ limit = int(request.args.get("limit", "500"))+ all_mems = kv.list(KV.memories)+ if latest_only:+ all_mems = [m for m in all_mems if m.get("isLatest") is not False]+ all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True)+ return jsonify({"memories": all_mems[:limit], "total": len(all_mems)}), 200++@app.route("/agentmemory/graph/stats", methods=["GET"])+def api_graph_stats():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ nodes = kv.list(KV.graphNodes)+ edges = kv.list(KV.graphEdges)+ return jsonify({"nodes": len(nodes), "edges": len(edges), "success": True}), 200++@app.route("/agentmemory/semantic", methods=["GET"])+def api_semantic_list():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ items = kv.list(KV.semantic)+ return jsonify({"items": items, "total": len(items)}), 200++@app.route("/agentmemory/procedural", methods=["GET"])+def api_procedural_list():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ items = kv.list(KV.procedural)+ return jsonify({"items": items, "total": len(items)}), 200++@app.route("/agentmemory/crystals", methods=["GET"])+def api_crystals_list():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ items = kv.list(KV.crystals)+ return jsonify({"crystals": items, "total": len(items)}), 200++@app.route("/agentmemory/actions", methods=["GET"])+def api_actions_list():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ limit = int(request.args.get("limit", "200"))+ status = request.args.get("status")+ items = kv.list(KV.actions)+ if status:+ items = [a for a in items if a.get("status") == status]+ items.sort(key=lambda a: a.get("updatedAt", ""), reverse=True)+ return jsonify({"actions": items[:limit], "total": len(items)}), 200++@app.route("/agentmemory/actions", methods=["POST"])+def api_action_create():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ try:+ body = request.get_json(force=True) or {}+ action_id = functions.generate_id("act")+ from datetime import datetime, timezone+ now = datetime.now(timezone.utc).isoformat()+ action = {+ "id": action_id,+ "title": body.get("title", ""),+ "description": body.get("description"),+ "priority": body.get("priority", 0),+ "status": body.get("status", "pending"),+ "tags": body.get("tags", []),+ "sessionId": body.get("sessionId"),+ "createdAt": now,+ "updatedAt": now,+ }+ kv.set(KV.actions, action_id, action)+ return jsonify({"action": action, "success": True}), 200+ except Exception as e:+ return jsonify({"error": str(e)}), 400++@app.route("/agentmemory/actions/<action_id>", methods=["PATCH"])+def api_action_update(action_id):+ auth_err = check_auth()+ if auth_err:+ return auth_err+ try:+ body = request.get_json(force=True) or {}+ existing = kv.get(KV.actions, action_id)+ if not existing:+ return jsonify({"error": "not found"}), 404+ from datetime import datetime, timezone+ existing.update({k: v for k, v in body.items() if k not in ("id", "createdAt")})+ existing["updatedAt"] = datetime.now(timezone.utc).isoformat()+ kv.set(KV.actions, action_id, existing)+ return jsonify({"action": existing, "success": True}), 200+ except Exception as e:+ return jsonify({"error": str(e)}), 400++@app.route("/agentmemory/frontier", methods=["GET"])+def api_frontier():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ items = kv.list(KV.actions)+ frontier = [a for a in items if a.get("status") in ("pending", "active")]+ frontier.sort(key=lambda a: (-(a.get("priority") or 0), a.get("createdAt", "")))+ return jsonify({"frontier": frontier[:50], "total": len(frontier)}), 200++@app.route("/agentmemory/insights", methods=["GET"])+def api_insights_list():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ limit = int(request.args.get("limit", "200"))+ items = kv.list(KV.insights)+ items.sort(key=lambda x: x.get("createdAt", ""), reverse=True)+ return jsonify({"insights": items[:limit], "total": len(items)}), 200++@app.route("/agentmemory/replay/load", methods=["GET"])+def api_replay_load():+ auth_err = check_auth()+ if auth_err:+ return auth_err+ session_id = request.args.get("sessionId")+ if not session_id:+ return jsonify({"error": "sessionId required"}), 400+ session = kv.get(KV.sessions, session_id)+ if not session:+ return jsonify({"error": "session not found"}), 404+ obs = kv.list(KV.observations(session_id))+ obs.sort(key=lambda o: o.get("timestamp", ""))++ from dateutil import parser as dtparser+ session_start = session.get("startedAt", "")+ try:+ t0_ms = dtparser.parse(session_start).timestamp() * 1000 if session_start else None+ except Exception:+ t0_ms = None++ _hook_kind = {+ "prompt_submit": "prompt",+ "post_tool_use": "tool_call",+ "post_tool_failure": "tool_error",+ "subagent_stop": "response",+ "task_completed": "response",+ "notification": "response",+ }++ events = []+ for o in obs:+ ts = o.get("timestamp", "")+ try:+ t_ms = dtparser.parse(ts).timestamp() * 1000 if ts else 0+ except Exception:+ t_ms = 0+ offset_ms = max(0, t_ms - t0_ms) if t0_ms is not None else t_ms++ hook = o.get("hookType", "")+ kind = _hook_kind.get(hook, "prompt")++ # obs fields are top-level (no data wrapper)+ tool_name = o.get("toolName")+ tool_input = o.get("toolInput")+ tool_output = o.get("toolOutput")++ label = (o.get("userPrompt") or+ o.get("narrative") or o.get("title") or o.get("summary") or+ tool_name or+ (o.get("raw") or "")[:80] or hook)+ if isinstance(label, str):+ label = label[:120]++ events.append({+ "kind": kind,+ "label": label,+ "offsetMs": offset_ms,+ "ts": ts,+ "body": o.get("narrative") or o.get("raw") or o.get("summary") or "",+ "toolName": tool_name,+ "toolInput": tool_input,+ "toolOutput": tool_output,+ })++ total_ms = (events[-1]["offsetMs"] + 1000) if events else 0+ timeline = {"events": events, "eventCount": len(events), "totalDurationMs": total_ms}+ return jsonify({"session": session, "timeline": timeline, "success": True}), 200 @app.route("/agentmemory/auto-forget", methods=["POST"]) def api_auto_forget():@@ -1191,6 +1435,311 @@ return jsonify({"error": str(e)}), 500 # =====================================================================+# Agent Discovery Endpoint (/agent.md and /auth.md)+# =====================================================================++AGENT_MD_TEMPLATE = """# AgentMemory — Agent Connection Guide++> This document is auto-generated. Fetch it fresh each session so you always have current values.++## 1. Server++| Field | Value |+|-------|-------|+| Base URL | `http://127.0.0.1:{port}` |+| API prefix | `/agentmemory` |+| Liveness | `GET http://127.0.0.1:{port}/agentmemory/livez` (no auth) |+| Auth required | `{auth_required}` |+| Auth header | `Authorization: Bearer <AGENTMEMORY_SECRET>` |++{auth_note}++---++## 2. Quick-Start: Minimum Viable Session++Do these in order at the start of every session:++```+1. POST /agentmemory/session/start ← register yourself+2. POST /agentmemory/context ← inject past memory into your system prompt+ ... do work, call observe after each tool use ...+3. POST /agentmemory/session/end ← mark session complete+```++### 2a. Start a session++```http+POST /agentmemory/session/start+Content-Type: application/json+{auth_header_example}++{{+ "sessionId": "<uuid-you-generate>",+ "project": "<absolute-path-or-name-of-repo>",+ "cwd": "<current working directory>",+ "agentId": "<your-agent-name>",+ "title": "<first user prompt, optional>"+}}+```++Response includes `context` — paste it into your system prompt before answering.++### 2b. Compile context (also works mid-session)++```http+POST /agentmemory/context+Content-Type: application/json+{auth_header_example}++{{+ "sessionId": "<your-session-id>",+ "project": "<same project as above>",+ "budget": 2000+}}+```++Returns `context` string wrapped in `<agentmemory-context>` tags. Insert verbatim.++### 2c. Log an observation (call after every significant tool use)++```http+POST /agentmemory/agent/observe+Content-Type: application/json+{auth_header_example}++{{+ "agentId": "<your-agent-name>",+ "sessionId": "<your-session-id>",+ "project": "<project>",+ "cwd": "<cwd>",+ "text": "<what you did or observed>",+ "type": "tool | command | thought | error | result | conversation | other",+ "title": "<short one-line summary>"+}}+```++### 2d. Save a long-term memory (decisions, patterns, preferences)++```http+POST /agentmemory/agent/remember+Content-Type: application/json+{auth_header_example}++{{+ "agentId": "<your-agent-name>",+ "project": "<project>",+ "content": "<the insight, decision, or fact>",+ "type": "fact | preference | architecture | bug | workflow | pattern",+ "concepts": "auth, jwt, middleware",+ "files": "src/middleware/auth.ts, tests/auth.test.ts"+}}+```++### 2e. End session++```http+POST /agentmemory/session/end+Content-Type: application/json+{auth_header_example}++{{+ "sessionId": "<your-session-id>"+}}+```++---++## 3. MCP Tools (JSON-RPC style)++Call via: `POST /agentmemory/mcp/tools`++```http+POST /agentmemory/mcp/tools+Content-Type: application/json+{auth_header_example}++{{+ "name": "<tool-name>",+ "arguments": {{ ... }}+}}+```++| Tool | Required args | Description |+|------|---------------|-------------|+| `memory_recall` | `query` | BM25+vector hybrid search over all past observations |+| `memory_smart_search` | `query` | Same as recall with progressive disclosure |+| `memory_save` | `content` | Save long-term memory (type, concepts, files optional) |+| `memory_sessions` | — | List recent sessions with observation counts |+| `memory_timeline` | `anchor` | Observations around a date or keyword anchor |+| `memory_profile` | `project` | Top concepts, files, conventions for a project |+| `memory_lesson_save` | `content` | Save a lesson (auto-strengthens duplicates) |+| `memory_lesson_recall` | `query` | Search lessons scored by confidence + recency |+| `agent_observe` | `agentId`, `sessionId`, `project`, `text` | Log an observation (same as REST) |+| `agent_remember` | `agentId`, `content`, `project` | Save memory (same as REST) |++Get full schemas: `GET /agentmemory/mcp/tools`++---++## 4. Full REST Endpoint Reference++All endpoints require `Authorization: Bearer <secret>` when auth is enabled.+Prefix every path with `http://127.0.0.1:{port}`.++### Session Management++| Method | Path | Key body fields | Notes |+|--------|------|-----------------|-------|+| `POST` | `/agentmemory/session/start` | `sessionId`, `project`, `cwd`, `agentId` | Returns `session` + `context` |+| `POST` | `/agentmemory/session/end` | `sessionId` | Marks status=completed |+| `GET` | `/agentmemory/sessions` | — | List all sessions |+| `GET` | `/agentmemory/observations?sessionId=` | — | Observations for a session |+| `POST` | `/agentmemory/session/commit` | `sha`, `sessionId`, `branch`, `message` | Link a git commit to a session |+| `GET` | `/agentmemory/session/by-commit?sha=` | — | Sessions linked to a commit |+| `GET` | `/agentmemory/commits` | `branch`, `repo`, `limit` | List tracked commits |++### Observations++| Method | Path | Key body fields | Notes |+|--------|------|-----------------|-------|+| `POST` | `/agentmemory/observe` | `sessionId`, `hookType`, `timestamp`, `data` | Raw hook payload |+| `POST` | `/agentmemory/agent/observe` | `agentId`, `sessionId`, `project`, `text`, `type` | Simplified agent endpoint |++`hookType` values: `post_tool_use`, `post_tool_failure`, `prompt_submit`, `subagent_stop`, `task_completed`, `notification`++### Memory++| Method | Path | Key body fields | Notes |+|--------|------|-----------------|-------|+| `POST` | `/agentmemory/remember` | `content`, `type`, `concepts[]`, `files[]`, `project` | Supersedes similar memories automatically |+| `POST` | `/agentmemory/agent/remember` | `agentId`, `content`, `project`, `type`, `concepts`, `files` | Simplified agent endpoint |+| `POST` | `/agentmemory/forget` | `memoryId` OR `sessionId` [+ `observationIds[]`] | Delete memory/session/observations |+| `POST` | `/agentmemory/evolve` | `memoryId`, `newContent`, `newTitle` | Version a memory (creates new, marks old superseded) |+| `POST` | `/agentmemory/search` | `query`, `limit` | Hybrid BM25+vector search |+| `POST` | `/agentmemory/context` | `sessionId`, `project`, `budget` | Compile context block for injection |++Memory `type` values: `fact`, `preference`, `architecture`, `bug`, `workflow`, `pattern`++### Lessons++| Method | Path | Key body fields | Notes |+|--------|------|-----------------|-------|+| `POST` | `/agentmemory/lessons` | `content`, `context`, `project`, `confidence`, `tags[]` | Create/strengthen (duplicate = auto-reinforce) |+| `GET` | `/agentmemory/lessons` | `project`, `minConfidence`, `limit` | List lessons |+| `POST` | `/agentmemory/lessons/search` | `query`, `project`, `limit` | Keyword search scored by confidence×recency |+| `POST` | `/agentmemory/lessons/strengthen` | `lessonId` | Manually reinforce a lesson (+0.1 confidence) |++### Memory Slots (Pinned Context)++Slots are named text buffers injected into every context compilation.++| Method | Path | Key body/query fields | Notes |+|--------|------|-----------------------|-------|+| `GET` | `/agentmemory/slots` | — | List all slots |+| `GET` | `/agentmemory/slot?label=` | — | Get single slot |+| `POST` | `/agentmemory/slot` | `label`, `content`, `scope`, `sizeLimit`, `pinned` | Create slot |+| `POST` | `/agentmemory/slot/append` | `label`, `text` | Append text to slot |+| `POST` | `/agentmemory/slot/replace` | `label`, `content` | Replace slot content |+| `DELETE` | `/agentmemory/slot?label=` | — | Delete slot |+| `POST` | `/agentmemory/slot/reflect` | `sessionId`, `maxObservations` | Auto-populate slots from session observations |++Default slot labels: `persona`, `user_preferences`, `tool_guidelines`, `project_context`, `guidance`, `pending_items`, `session_patterns`, `self_notes`++### Knowledge Graph & Analytics++| Method | Path | Key body/query fields | Notes |+|--------|------|-----------------------|-------|+| `GET` | `/agentmemory/relations` | — | List all knowledge graph edges |+| `POST` | `/agentmemory/relations` | `sourceId`, `targetId`, `type` | Add a relation edge |+| `POST` | `/agentmemory/timeline` | `anchor`, `project`, `before`, `after` | Observations around anchor |+| `GET` | `/agentmemory/profile?project=` | — | Project profile (top concepts/files) |+| `GET` | `/agentmemory/audit` | `operation`, `limit` | Audit log |+| `GET` | `/agentmemory/profile` | `project` (optional) | Project profile; omit `project` to list all known projects |+| `GET` | `/agentmemory/actions` | `limit`, `status` | List actions |+| `POST` | `/agentmemory/actions` | `title`, `description`, `priority`, `tags[]`, `status` | Create action |+| `PATCH`| `/agentmemory/actions/<id>` | any action fields | Update action |+| `GET` | `/agentmemory/frontier` | — | Pending+active actions sorted by priority |+| `GET` | `/agentmemory/insights` | `limit` | List insights |+| `GET` | `/agentmemory/replay/sessions` | — | Sessions list for replay |+| `GET` | `/agentmemory/replay/load?sessionId=` | — | Full session + ordered observations for replay |+| `POST` | `/agentmemory/auto-forget` | `dryRun` | Evict stale observations |++### Health & Config++| Method | Path | Auth | Notes |+|--------|------|------|-------|+| `GET` | `/agentmemory/livez` | No | Liveness check |+| `GET` | `/agentmemory/health` | Yes | Full health + version |+| `GET` | `/agentmemory/config/flags` | Yes | Feature flags (graph, consolidation, compression) |++---++## 5. WebSocket Live Stream++```+ws://127.0.0.1:{port}/stream/mem-live/viewer+```++Connect to receive real-time events. Message types:+- `raw_observation` — raw hook payload as received+- `compressed_observation` — after synthetic compression + indexing++No auth on the WebSocket endpoint.++---++## 6. Agent Identity & Scope Isolation++Set `AGENT_ID` env var on the server to scope all read operations to a single agent.+Set `AGENTMEMORY_AGENT_SCOPE=isolated` to enforce per-agent isolation.++Always pass `agentId` in every request body — it's stored on every observation/memory and enables per-agent filtering via `?agentId=<id>` on list endpoints.++---++## 7. Secrets Are Redacted++Any text containing API keys, Bearer tokens, passwords, or JWTs is automatically redacted to `[REDACTED_SECRET]` before storage. Wrap sensitive blocks in `<private>...</private>` tags to force redaction.++---++*Generated by agentmemory v{version} — `GET /agent.md` to refresh*+"""++@app.route("/agent.md", methods=["GET"])+@app.route("/auth.md", methods=["GET"])+def agent_discovery():+ port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))+ secret = os.getenv("AGENTMEMORY_SECRET")+ auth_required = "yes" if secret else "no"++ if secret:+ auth_note = (+ "> **Auth is enabled.** Add `Authorization: Bearer <AGENTMEMORY_SECRET>` to every request.\n"+ "> The secret is set via `AGENTMEMORY_SECRET` env var in `~/.agentmemory/.env`."+ )+ auth_header_example = 'Authorization: Bearer <AGENTMEMORY_SECRET>'+ else:+ auth_note = (+ "> **Auth is disabled.** No `Authorization` header needed — all endpoints are open."+ )+ auth_header_example = ''++ md = AGENT_MD_TEMPLATE.format(+ port=port,+ auth_required=auth_required,+ auth_note=auth_note,+ auth_header_example=auth_header_example,+ version="0.9.8",+ )++ response = make_response(md)+ response.headers["Content-Type"] = "text/markdown; charset=utf-8"+ response.headers["Cache-Control"] = "no-cache"+ return response++# ===================================================================== # Lifecycle Helpers # =====================================================================
=== Diff for src/viewer/index.html ===--- agentmemory/src/viewer/index.html+++ agentmemory-python/src/viewer/index.html@@ -1039,15 +1039,15 @@ var wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; var REST, WS_URL, WS_DIRECT_URL, wsPort; if (paramPort) {- var resolvedPort = parseInt(paramPort) === 3111 ? '3113' : paramPort;+ var resolvedPort = paramPort; REST = window.location.protocol + '//' + window.location.hostname + ':' + resolvedPort;- wsPort = params.get('wsPort') || String(parseInt(resolvedPort) - 1);+ wsPort = params.get('wsPort') || resolvedPort; WS_URL = wsProto + '//' + window.location.hostname + ':' + wsPort; WS_DIRECT_URL = WS_URL + '/stream/mem-live/viewer'; } else if (locPort) {- var resolvedPort = parseInt(locPort) === 3111 ? '3113' : locPort;+ var resolvedPort = locPort; REST = window.location.protocol + '//' + window.location.hostname + ':' + resolvedPort;- wsPort = params.get('wsPort') || String(parseInt(resolvedPort) - 1);+ wsPort = params.get('wsPort') || resolvedPort; WS_URL = wsProto + '//' + window.location.hostname + ':' + wsPort; WS_DIRECT_URL = WS_URL + '/stream/mem-live/viewer'; } else {
123456789101112131415161718192021222324252627import osimport requests
def load_env(): home = os.path.expanduser("~") env_path = os.path.join(home, ".agentmemory", ".env") if os.path.exists(env_path): with open(env_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue if "=" in line: k, v = line.split("=", 1) os.environ[k.strip()] = v.strip().strip('"').strip("'")
load_env()token = os.getenv("AGENTMEMORY_SECRET")headers = {"Authorization": f"Bearer {token}"} if token else {}
print(f"Testing route with token: {token[:4]}..." if token else "Testing route with no token...")r = requests.post("http://127.0.0.1:3111/agentmemory/replay/import-jsonl", json={}, headers=headers)print("Status code:", r.status_code)try: print("Response JSON:", r.json())except Exception: print("Response text:", r.text[:300])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205import osimport sysimport jsonimport hmacimport secretsimport base64import threadingfrom flask import Flask, request, jsonify, make_response, send_from_directoryfrom flask_sock import Sock# Load environment variables from ~/.agentmemory/.env if it existsdef load_env():home = os.path.expanduser("~")env_path = os.path.join(home, ".agentmemory", ".env")if os.path.exists(env_path):try:with open(env_path, "r", encoding="utf-8") as f:for line in f:line = line.strip()if not line or line.startswith("#"):continueif "=" in line:k, v = line.split("=", 1)k = k.strip()v = v.strip().strip('"').strip("'")os.environ[k] = vprint(f"[config] Loaded environment from {env_path}")except Exception as e:print(f"[config] Error reading env file: {e}")load_env()import datetimedef datetime_now_iso() -> str:return datetime.datetime.utcnow().isoformat() + "Z"# Import local modulesfrom db import StateKVimport searchimport functionsfrom functions import KV, query_auditapp = Flask(__name__)# Enable CORS for all routes (important for client scripts connecting locally)@app.after_requestdef after_request(response):origin = request.headers.get("Origin")if origin:parsed_origin = origin.lower()is_allowed = Falseif parsed_origin in ("null", "vscode-webview://"):is_allowed = Trueelif parsed_origin.startswith("http://localhost:") or parsed_origin == "http://localhost":is_allowed = Trueelif parsed_origin.startswith("http://127.0.0.1:") or parsed_origin == "http://127.0.0.1":is_allowed = Trueelif parsed_origin.startswith("vscode-webview://"):is_allowed = Trueelif parsed_origin.startswith("chrome-extension://"):is_allowed = Trueif is_allowed:response.headers["Access-Control-Allow-Origin"] = originresponse.headers["Access-Control-Allow-Credentials"] = "true"response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")response.headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")return responsesock = Sock(app)# Global instanceskv = Noneembedding_provider = Nonepersistence = Nonedef init_app():global kv, embedding_provider, persistence# 1. Initialize DBkv = StateKV()# 2. Initialize Embedding Provider if API key is availableapi_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")if api_key:try:embedding_provider = search.GeminiEmbeddingProvider(api_key)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: gemini (768 dims)")except Exception as e:print(f"[search] Error initializing embedding provider: {e}")else:print(f"[search] No GEMINI_API_KEY found, running in BM25-only mode.")# 3. Persistence & load indexespersistence = functions.IndexPersistence(kv, functions._bm25_index, functions._vector_index if api_key else None)functions.set_index_persistence(persistence)loaded = persistence.load()print(f"[persistence] Load results: BM25 index={loaded['bm25']}, Vector index={loaded['vector']}")# 4. Rebuild index if emptyif functions._bm25_index.size == 0:print("[persistence] Search index is empty. Rebuilding in background thread...")def run_rebuild():try:count = functions.rebuild_index(kv)print(f"[persistence] Rebuild completed: indexed {count} items.")except Exception as ex:print(f"[persistence] Rebuild failed: {ex}")t = threading.Thread(target=run_rebuild, daemon=True)t.start()# 5. Start background worker loopsimport timedef run_auto_forget_loop():time.sleep(10)while True:try:if os.getenv("AUTO_FORGET_ENABLED") != "false":print("[scheduler] Running auto_forget sweep...")res = functions.auto_forget(kv, dry_run=False)print(f"[scheduler] auto_forget sweep completed: {res}")except Exception as e:print(f"[scheduler] auto_forget loop error: {e}")time.sleep(3600)t_forget = threading.Thread(target=run_auto_forget_loop, daemon=True)t_forget.start()# =====================================================================# Auth Middleware# =====================================================================def timing_safe_compare(a: str, b: str) -> bool:return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))def check_auth():secret = os.getenv("AGENTMEMORY_SECRET")if not secret:return Noneauth = request.headers.get("Authorization") or request.headers.get("authorization")if not auth or not auth.startswith("Bearer "):return jsonify({"error": "unauthorized"}), 401provided_token = auth[7:].strip()if not timing_safe_compare(provided_token, secret):return jsonify({"error": "unauthorized"}), 401return None# =====================================================================# WebSocket Streaming# =====================================================================active_websockets = set()@sock.route("/stream/mem-live/viewer")def stream_viewer(ws):secret = os.getenv("AGENTMEMORY_SECRET")if secret:token = request.args.get("token") or request.args.get("secret")if not token or not timing_safe_compare(token, secret):ws.close(1008)returnactive_websockets.add(ws)try:while True:data = ws.receive()if data is None:breakexcept Exception:passfinally:active_websockets.discard(ws)def broadcast_to_viewers(payload):msg = json.dumps(payload)for ws in list(active_websockets):try:ws.send(msg)except Exception:active_websockets.discard(ws)# Register broadcaster in functionsfunctions.set_stream_broadcaster(broadcast_to_viewers)# =====================================================================# Viewer Routes# =====================================================================@app.route("/")@app.route("/viewer")@app.route("/agentmemory/viewer")def serve_viewer():try:base_dir = os.path.dirname(os.path.abspath(__file__))template_path = os.path.join(base_dir, "viewer", "index.html")with open(template_path, "r", encoding="utf-8") as f:template = f.read()nonce = base64.urlsafe_b64encode(secrets.token_bytes(16)).decode("utf-8").rstrip("=")auto_token = os.environ.get("AGENTMEMORY_SECRET", "")html = (template.replace("__AGENTMEMORY_VIEWER_NONCE__", nonce).replace("__AGENTMEMORY_VERSION__", "0.9.8").replace("__AGENTMEMORY_AUTO_TOKEN__", auto_token))csp = "; ".join(["default-src 'none'","base-uri 'none'","frame-ancestors 'self' https://huggingface.co https://*.hf.space","object-src 'none'","form-action 'none'",f"script-src 'nonce-{nonce}'","script-src-attr 'none'","style-src 'unsafe-inline'","connect-src 'self' https: http://localhost:* http://127.0.0.1:* wss: ws://localhost:* ws://127.0.0.1:* wss://localhost:* wss://127.0.0.1:*","img-src 'self' data:","font-src 'self'",])res = make_response(html)res.headers["Content-Type"] = "text/html; charset=utf-8"res.headers["Content-Security-Policy"] = cspres.headers["Cache-Control"] = "no-cache"return resexcept Exception as e:return f"Viewer not found: {e}", 404@app.route("/favicon.svg")def serve_favicon():base_dir = os.path.dirname(os.path.abspath(__file__))return send_from_directory(os.path.join(base_dir, "viewer"), "favicon.svg")# =====================================================================# REST REST API Endpoints# =====================================================================@app.route("/agentmemory/livez", methods=["GET"])def livez():port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))return jsonify({"status": "ok","service": "agentmemory","viewerPort": port,"viewerSkipped": False})@app.route("/agentmemory/config/flags", methods=["GET"])def config_flags():auth_err = check_auth()if auth_err:return auth_errprovider_kind = "llm" if embedding_provider else "noop"embedding_prov = "gemini" if embedding_provider else "none"flags = [{"key": "GRAPH_EXTRACTION_ENABLED","label": "Knowledge graph extraction","enabled": functions.is_graph_extraction_enabled(),"default": False,"affects": ["Graph", "Dashboard"],"needsLlm": True,"description": "Extracts entities and relations from observations into a knowledge graph.","enableHow": "Set GRAPH_EXTRACTION_ENABLED=true and restart.","docsHref": "https://github.com/rohitg00/agentmemory#knowledge-graph"},{"key": "CONSOLIDATION_ENABLED","label": "Memory consolidation","enabled": functions.is_consolidation_enabled(),"default": False,"affects": ["Dashboard", "Memories", "Crystals"],"needsLlm": True,"description": "Periodically summarizes sessions into semantic facts + procedures.","enableHow": "Set CONSOLIDATION_ENABLED=true and restart.","docsHref": "https://github.com/rohitg00/agentmemory#consolidation"},{"key": "AGENTMEMORY_AUTO_COMPRESS","label": "LLM-powered observation compression","enabled": functions.is_auto_compress_enabled(),"default": False,"affects": ["Memories", "Timeline"],"needsLlm": True,"description": "Every observation is compressed by the LLM for richer summaries. OFF uses synthetic compression.","enableHow": "Set AGENTMEMORY_AUTO_COMPRESS=true.","docsHref": "https://github.com/rohitg00/agentmemory/issues/138"}]return jsonify({"version": "0.9.8","provider": provider_kind,"embeddingProvider": embedding_prov,"flags": flags})@app.route("/agentmemory/health", methods=["GET"])def health():return jsonify(functions.health_check(kv))@app.route("/agentmemory/observe", methods=["POST"])def api_observe():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.observe(kv, body)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/agent/observe", methods=["POST"])def api_agent_observe():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}folder_path = body.get("folderPath")agent_id = body.get("agentId")text = body.get("text") or body.get("content") or ""if not folder_path or not agent_id or not text:return jsonify({"error": "folderPath, agentId, and text are required"}), 400# sessionId accepted but ignored (folder-based model)# timestamp defaults to now UTCtimestamp = body.get("timestamp") or datetime_now_iso()payload = {"folderPath": folder_path,"agentId": agent_id,"text": text,"timestamp": timestamp,"type": body.get("type"),"title": body.get("title"),"concepts": body.get("concepts"),"files": body.get("files"),"importance": body.get("importance"),}res = functions.folder_observe(kv, payload)return jsonify(res), 201except ValueError as e:return jsonify({"error": str(e)}), 400except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/context", methods=["POST"])def api_context():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.context(kv, body)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/search", methods=["POST"])def api_search():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}query = body.get("query")if not query or not query.strip():return jsonify({"error": "query is required"}), 400limit = body.get("limit") or 10folder_path = body.get("folderPath")agent_id = body.get("agentId")res = functions.folder_search(kv, query, limit, folder_path=folder_path, agent_id=agent_id)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/export", methods=["GET"])def api_export():auth_err = check_auth()if auth_err:return auth_errtry:max_sess = request.args.get("maxSessions")offset = request.args.get("offset")payload = {}if max_sess is not None: payload["maxSessions"] = max_sessif offset is not None: payload["offset"] = offsetres = functions.export_data(kv, payload)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 500@app.route("/agentmemory/replay/sessions", methods=["GET"])def api_replay_sessions():return jsonify({"error": "Gone — session replay removed in folder-based memory model"}), 410@app.route("/agentmemory/session/start", methods=["POST"])def api_session_start():return jsonify({"error": "This endpoint has been removed", "status": "gone"}), 410@app.route("/agentmemory/antigravity/sync", methods=["POST"])def api_antigravity_sync():return jsonify({"error": "This endpoint has been removed", "status": "gone"}), 410@app.route("/agentmemory/session/end", methods=["POST"])def api_session_end():return jsonify({"error": "This endpoint has been removed", "status": "gone"}), 410@app.route("/agentmemory/session/commit", methods=["POST"])def api_session_commit():return jsonify({"error": "This endpoint has been removed", "status": "gone"}), 410@app.route("/agentmemory/session/by-commit", methods=["GET"])def api_session_by_commit():return jsonify({"error": "This endpoint has been removed", "status": "gone"}), 410@app.route("/agentmemory/commits", methods=["GET"])def api_commits():auth_err = check_auth()if auth_err:return auth_errbranch = request.args.get("branch")repo = request.args.get("repo")limit = int(request.args.get("limit", "100"))all_links = kv.list(KV.commits)filtered = all_linksif branch:filtered = [c for c in filtered if c.get("branch") == branch]if repo:filtered = [c for c in filtered if c.get("repo") == repo]filtered.sort(key=lambda c: c.get("linkedAt", ""), reverse=True)return jsonify({"commits": filtered[:limit]}), 200@app.route("/agentmemory/sessions", methods=["GET"])def api_sessions():return jsonify({"error": "This endpoint has been removed", "status": "gone"}), 410@app.route("/agentmemory/observations", methods=["GET"])def api_observations():auth_err = check_auth()if auth_err:return auth_errsession_id = request.args.get("sessionId")if not session_id:return jsonify({"error": "sessionId is required"}), 400obs = kv.list(KV.observations(session_id))obs.sort(key=lambda o: o.get("timestamp", ""))agent_id = request.args.get("agentId")if agent_id and agent_id != "*":obs = [o for o in obs if o.get("agentId") == agent_id]elif functions.is_agent_scope_isolated():env_aid = functions.get_agent_id()if env_aid:obs = [o for o in obs if o.get("agentId") == env_aid]return jsonify({"observations": obs}), 200@app.route("/agentmemory/remember", methods=["POST"])def api_remember():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.remember(kv, body)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/agent/remember", methods=["POST"])def api_agent_remember():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}content = body.get("content")if not content:return jsonify({"error": "content is required"}), 400agent_id = body.get("agentId")project = body.get("project")mem_type = body.get("type") or "fact"concepts = body.get("concepts") or []if isinstance(concepts, str):concepts = [c.strip() for c in concepts.split(",") if c.strip()]files = body.get("files") or []if isinstance(files, str):files = [f.strip() for f in files.split(",") if f.strip()]payload = {"content": content,"type": mem_type,"concepts": concepts,"files": files,"project": project}if agent_id:payload["agentId"] = agent_idres = functions.remember(kv, payload)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/forget", methods=["POST"])def api_forget():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.forget(kv, body)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/folders", methods=["GET"])def api_folders():auth_err = check_auth()if auth_err:return auth_errfolders = sorted(kv.list(functions.KV.folders),key=lambda x: x.get("lastUpdated", ""),reverse=True)return jsonify({"folders": folders}), 200@app.route("/agentmemory/folder/observations", methods=["GET"])def api_folder_observations():auth_err = check_auth()if auth_err:return auth_errfp = request.args.get("folderPath")aid = request.args.get("agentId")if not fp or not aid:return jsonify({"error": "folderPath and agentId are required"}), 400observations = sorted(kv.list(functions.KV.folder_obs(fp, aid)),key=lambda x: x.get("timestamp", ""),reverse=True)return jsonify({"observations": observations, "folderPath": fp, "agentId": aid}), 200@app.route("/agentmemory/timeline", methods=["POST"])def api_timeline():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}folder_path = body.get("folderPath")agent_id = body.get("agentId")limit = body.get("limit") or 100before = body.get("before")after = body.get("after")result = functions.folder_timeline(kv, limit, folder_path, agent_id, before, after)return jsonify({"observations": result}), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/graph", methods=["GET"])def api_graph():auth_err = check_auth()if auth_err:return auth_errresult = functions.folder_graph_build(kv)return jsonify(result), 200@app.route("/agentmemory/migrate", methods=["POST"])def api_migrate():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}dry_run = bool(body.get("dry_run", False))result = functions.migrate_sessions_to_folders(kv, dry_run)return jsonify(result), 200except Exception as e:return jsonify({"error": str(e)}), 400# =====================================================================# Lessons Learned Endpoints (stubbed — 410 Gone)# =====================================================================@app.route("/agentmemory/lessons", methods=["GET"])def api_lessons_list():return jsonify({"error": "Gone — lessons have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/lessons", methods=["POST"])def api_lessons_save():return jsonify({"error": "Gone — lessons have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/lessons/search", methods=["POST"])def api_lessons_search():return jsonify({"error": "Gone — lessons have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/lessons/strengthen", methods=["POST"])def api_lessons_strengthen():return jsonify({"error": "Gone — lessons have been removed in the folder-based memory model"}), 410# =====================================================================# Memory Slots Endpoints (stubbed — 410 Gone)# =====================================================================@app.route("/agentmemory/slots", methods=["GET"])def api_slots_list():return jsonify({"error": "Gone — slots have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/slot", methods=["GET"])def api_slots_get():return jsonify({"error": "Gone — slots have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/slot", methods=["POST"])def api_slots_create():return jsonify({"error": "Gone — slots have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/slot/append", methods=["POST"])def api_slots_append():return jsonify({"error": "Gone — slots have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/slot/replace", methods=["POST"])def api_slots_replace():return jsonify({"error": "Gone — slots have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/slot", methods=["DELETE"])def api_slots_delete():return jsonify({"error": "Gone — slots have been removed in the folder-based memory model"}), 410@app.route("/agentmemory/slot/reflect", methods=["POST"])def api_slots_reflect():return jsonify({"error": "Gone — slots have been removed in the folder-based memory model"}), 410# =====================================================================# Audit, Relations, Evolve, Timeline, Profile# =====================================================================@app.route("/agentmemory/audit", methods=["GET"])def api_audit():auth_err = check_auth()if auth_err:return auth_errop = request.args.get("operation")limit = int(request.args.get("limit", "50"))res = query_audit(kv, {"operation": op, "limit": limit})return jsonify({"entries": res, "success": True}), 200@app.route("/agentmemory/relations", methods=["GET"])def api_relations_list():auth_err = check_auth()if auth_err:return auth_errrels = functions.get_relations(kv)return jsonify({"relations": rels}), 200@app.route("/agentmemory/relations", methods=["POST"])def api_relations_add():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.add_relation(kv, body)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/evolve", methods=["POST"])def api_evolve():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.evolve_memory(kv, body)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/timeline", methods=["POST"])def api_timeline_legacy():# Duplicate route removed — now handled by the folder-based api_timeline above.return jsonify({"error": "This endpoint has been removed", "status": "gone"}), 410@app.route("/agentmemory/profile", methods=["GET"])def api_profile():auth_err = check_auth()if auth_err:return auth_errproject = request.args.get("project")if not project:sessions = kv.list(KV.sessions)projects = set(s.get("project", "") for s in sessions if s.get("project"))memories = kv.list(KV.memories)mem_projects = set(m.get("project", "") for m in memories if m.get("project"))all_projects = sorted(projects.union(mem_projects))return jsonify({"projects": all_projects, "success": True}), 200res = functions.get_project_profile(kv, project)return jsonify(res), 200# =====================================================================# Missing endpoints the JS viewer calls# =====================================================================@app.route("/agentmemory/memories", methods=["GET"])def api_memories_list():auth_err = check_auth()if auth_err:return auth_errlatest_only = request.args.get("latest", "false").lower() == "true"limit = int(request.args.get("limit", "500"))all_mems = kv.list(KV.memories)if latest_only:all_mems = [m for m in all_mems if m.get("isLatest") is not False]all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True)return jsonify({"memories": all_mems[:limit], "total": len(all_mems)}), 200@app.route("/agentmemory/graph/stats", methods=["GET"])def api_graph_stats():auth_err = check_auth()if auth_err:return auth_err# Dynamically compute graph folder nodes and connection edgessessions = functions.list_sessions(kv)memories = kv.list(KV.memories)folders = set()concepts_by_folder = {}for s in sessions:project = s.get("project", "").strip()if project:folders.add(project)for m in memories:project = m.get("project", "").strip()if project:folders.add(project)concepts = m.get("concepts", [])if concepts:if project not in concepts_by_folder:concepts_by_folder[project] = set()for c in concepts:if isinstance(c, str):concepts_by_folder[project].add(c.lower())node_count = len(folders)edge_count = 0folder_list = list(folders)for i in range(len(folder_list)):for j in range(i + 1, len(folder_list)):f1 = folder_list[i]f2 = folder_list[j]c1 = concepts_by_folder.get(f1, set())c2 = concepts_by_folder.get(f2, set())shared = c1.intersection(c2)p1 = [p for p in f1.replace("\\", "/").split("/") if p]p2 = [p for p in f2.replace("\\", "/").split("/") if p]common_subdirs = 0for k in range(min(len(p1), len(p2))):if p1[k].lower() == p2[k].lower():p_low = p1[k].lower()if p_low not in ("c:", "d:", "downloads", "projects", "other projects"):common_subdirs += 1else:breakif len(shared) > 0 or common_subdirs > 0:edge_count += 1return jsonify({"nodes": node_count, "edges": edge_count, "success": True}), 200@app.route("/agentmemory/graph/query", methods=["POST"])def api_graph_query():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}start_node_id = body.get("startNodeId")return jsonify({"nodes": [], "edges": [], "success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/graph/build", methods=["POST"])def api_graph_build():auth_err = check_auth()if auth_err:return auth_errtry:if functions.is_consolidation_enabled():functions.consolidate(kv)return jsonify({"success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/semantic", methods=["GET"])def api_semantic_list():auth_err = check_auth()if auth_err:return auth_erritems = kv.list(KV.semantic)return jsonify({"items": items, "total": len(items)}), 200@app.route("/agentmemory/procedural", methods=["GET"])def api_procedural_list():auth_err = check_auth()if auth_err:return auth_erritems = kv.list(KV.procedural)return jsonify({"items": items, "total": len(items)}), 200@app.route("/agentmemory/crystals", methods=["GET"])def api_crystals_list():auth_err = check_auth()if auth_err:return auth_erritems = kv.list(KV.crystals)return jsonify({"crystals": items, "total": len(items)}), 200def escape_xml(s: str) -> str:return s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("'", "'")def get_file_context(kv_inst, session_id, files, project):try:sessions = kv_inst.list(KV.sessions)other_sessions = [s for s in sessions if s.get("id") != session_id] if session_id else sessionsif project:other_sessions = [s for s in other_sessions if s.get("project") == project]# Sort sessions by startedAt descother_sessions.sort(key=lambda s: s.get("startedAt") or "", reverse=True)other_sessions = other_sessions[:15]obs_cache = {}for s in other_sessions:s_id = s["id"]obs_cache[s_id] = kv_inst.list(KV.observations(s_id))results = []for file in files:history = {"file": file, "observations": []}normalized_file = file.replace("./", "", 1)for s in other_sessions:s_id = s["id"]observations = obs_cache.get(s_id) or []for obs in observations:obs_files = obs.get("files") or []if isinstance(obs_files, str):obs_files = [f.strip() for f in obs_files.split(",") if f.strip()]obs_title = obs.get("title")if not obs_files or not obs_title:continue# Check matchmatches = Falsefor f in obs_files:if f == file or f == normalized_file or f.endswith(f"/{normalized_file}") or normalized_file.endswith(f"/{f}"):matches = Truebreakimportance = int(obs.get("importance") or 0)if matches and importance >= 4:history["observations"].append({"sessionId": s_id,"obsId": obs.get("id"),"type": obs.get("type", "other"),"title": obs_title,"narrative": obs.get("narrative") or obs.get("content") or "","importance": importance,"timestamp": obs.get("timestamp", "")})# Sort by importance deschistory["observations"].sort(key=lambda o: o["importance"], reverse=True)history["observations"] = history["observations"][:5]if history["observations"]:results.append(history)if not results:return ""lines = ["<agentmemory-file-context>"]for fh in results:lines.append(f"## {fh['file']}")for obs in fh["observations"]:lines.append(f"- [{obs['type']}] {obs['title']}: {obs['narrative']}")lines.append("</agentmemory-file-context>")return "\n".join(lines)except Exception as e:print(f"[enrich] Error generating file context: {e}")return ""@app.route("/agentmemory/enrich", methods=["POST"])def api_enrich():auth_err = check_auth()if auth_err:return auth_errtry:data = request.get_json(force=True) or {}session_id = data.get("sessionId")files = data.get("files") or []terms = data.get("terms") or []project = data.get("project")parts = []# 1. File Contextif files:file_context = get_file_context(kv, session_id, files, project)if file_context:parts.append(file_context)# 2. Searchsearch_queries = [os.path.basename(f) for f in files] + termssearch_queries = [q for q in search_queries if q]if search_queries:query_str = " ".join(search_queries)res = functions._hybrid_search.search(query_str, 5)if project:res = [r for r in res if r.get("observation", {}).get("project") == project or r.get("project") == project]obs_texts = []for r in res:obs = r.get("observation", r)narrative = obs.get("narrative") or obs.get("content")if narrative:obs_texts.append(escape_xml(narrative))if obs_texts:parts.append("<agentmemory-relevant-context>\n" + "\n".join(obs_texts) + "\n</agentmemory-relevant-context>")# 3. Bug memoriesif files:bugs = []memories = kv.list(KV.memories)for m in memories:m_type = m.get("type")m_is_latest = m.get("isLatest", True)m_project = m.get("project")m_files = m.get("files") or []if isinstance(m_files, str):m_files = [f.strip() for f in m_files.split(",") if f.strip()]if m_type == "bug" and m_is_latest:if project and m_project and m_project != project:continuehas_overlap = Falsefor f in m_files:for df in files:if f in df or df in f:has_overlap = Truebreakif has_overlap:breakif has_overlap:bugs.append(m)bugs.sort(key=lambda m: m.get("updatedAt") or m.get("createdAt") or "", reverse=True)bugs_lines = []for m in bugs[:3]:title = escape_xml(m.get("title") or "")content = escape_xml(m.get("content") or "")bugs_lines.append(f"- {title}: {content}")if bugs_lines:parts.append("<agentmemory-past-errors>\n" + "\n".join(bugs_lines) + "\n</agentmemory-past-errors>")context = "\n\n".join(parts)if len(context) > 4000:context = context[:4000]return jsonify({"context": context}), 200except Exception as e:return jsonify({"error": str(e)}), 500@app.route("/agentmemory/crystals/auto", methods=["POST"])def api_crystals_auto():auth_err = check_auth()if auth_err:return auth_errreturn jsonify({"success": True, "message": "auto-crystallize stub (not implemented in Python version)"}), 200@app.route("/agentmemory/claude-bridge/sync", methods=["POST"])def api_claude_bridge_sync():auth_err = check_auth()if auth_err:return auth_errreturn jsonify({"success": True, "message": "claude-bridge/sync stub"}), 200@app.route("/agentmemory/actions", methods=["GET"])def api_actions_list():auth_err = check_auth()if auth_err:return auth_errlimit = int(request.args.get("limit", "200"))status = request.args.get("status")items = kv.list(KV.actions)if status:items = [a for a in items if a.get("status") == status]items.sort(key=lambda a: a.get("updatedAt", ""), reverse=True)return jsonify({"actions": items[:limit], "total": len(items)}), 200@app.route("/agentmemory/actions", methods=["POST"])def api_action_create():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}action_id = functions.generate_id("act")from datetime import datetime, timezonenow = datetime.now(timezone.utc).isoformat()action = {"id": action_id,"title": body.get("title", ""),"description": body.get("description"),"priority": body.get("priority", 0),"status": body.get("status", "pending"),"tags": body.get("tags", []),"sessionId": body.get("sessionId"),"createdAt": now,"updatedAt": now,}kv.set(KV.actions, action_id, action)return jsonify({"action": action, "success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/actions/<action_id>", methods=["PATCH"])def api_action_update(action_id):auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}existing = kv.get(KV.actions, action_id)if not existing:return jsonify({"error": "not found"}), 404from datetime import datetime, timezoneallowed_fields = {"title", "description", "priority", "status", "tags", "sessionId"}updates = {k: v for k, v in body.items() if k in allowed_fields}existing.update(updates)existing["updatedAt"] = datetime.now(timezone.utc).isoformat()kv.set(KV.actions, action_id, existing)return jsonify({"action": existing, "success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/frontier", methods=["GET"])def api_frontier():auth_err = check_auth()if auth_err:return auth_erritems = kv.list(KV.actions)frontier = [a for a in items if a.get("status") in ("pending", "active")]frontier.sort(key=lambda a: (-(a.get("priority") or 0), a.get("createdAt", "")))return jsonify({"frontier": frontier[:50], "total": len(frontier)}), 200@app.route("/agentmemory/insights", methods=["GET"])def api_insights_list():auth_err = check_auth()if auth_err:return auth_errlimit = int(request.args.get("limit", "200"))items = kv.list(KV.insights)items.sort(key=lambda x: x.get("createdAt", ""), reverse=True)return jsonify({"insights": items[:limit], "total": len(items)}), 200@app.route("/agentmemory/replay/load", methods=["GET"])def api_replay_load():auth_err = check_auth()if auth_err:return auth_errsession_id = request.args.get("sessionId")if not session_id:return jsonify({"error": "sessionId required"}), 400session = functions.get_session(kv, session_id)if not session:return jsonify({"error": "session not found"}), 404obs = kv.list(KV.observations(session_id))obs.sort(key=lambda o: o.get("timestamp", ""))from dateutil import parser as dtparsersession_start = session.get("startedAt", "")try:t0_ms = dtparser.parse(session_start).timestamp() * 1000 if session_start else Noneexcept Exception:t0_ms = None_hook_kind = {"prompt_submit": "prompt","post_tool_use": "tool_call","post_tool_failure": "tool_error","subagent_stop": "response","task_completed": "response","notification": "response",}events = []for o in obs:ts = o.get("timestamp", "")try:t_ms = dtparser.parse(ts).timestamp() * 1000 if ts else 0except Exception:t_ms = 0offset_ms = max(0, t_ms - t0_ms) if t0_ms is not None else t_mshook = o.get("hookType", "")kind = _hook_kind.get(hook, "prompt")# obs fields are top-level (no data wrapper)tool_name = o.get("toolName")tool_input = o.get("toolInput")tool_output = o.get("toolOutput")label = (o.get("userPrompt") oro.get("narrative") or o.get("title") or o.get("summary") ortool_name or(o.get("raw") or "")[:80] or hook)if isinstance(label, str):label = label[:120]events.append({"kind": kind,"label": label,"offsetMs": offset_ms,"ts": ts,"body": o.get("narrative") or o.get("raw") or o.get("summary") or "","toolName": tool_name,"toolInput": tool_input,"toolOutput": tool_output,})total_ms = (events[-1]["offsetMs"] + 1000) if events else 0timeline = {"events": events, "eventCount": len(events), "totalDurationMs": total_ms}return jsonify({"session": session, "timeline": timeline, "success": True}), 200@app.route("/agentmemory/replay/import-jsonl", methods=["POST"])def api_replay_import_jsonl():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}path = body.get("path")max_files = body.get("maxFiles")import replay_importres = replay_import.import_jsonl_data(kv, path=path, max_files=max_files)status_code = 200 if res.get("success", True) else 400return jsonify(res), status_codeexcept Exception as e:return jsonify({"error": str(e), "success": False}), 500@app.route("/agentmemory/auto-forget", methods=["POST"])def api_auto_forget():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}dry_run = body.get("dryRun", False)res = functions.auto_forget(kv, dry_run)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/summarize", methods=["POST"])def api_summarize():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.summarize(kv, body)if not res.get("success"):return jsonify(res), 400return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/consolidate", methods=["POST"])def api_consolidate():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}project = body.get("project")min_obs = body.get("minObservations")res = functions.consolidate(kv, project=project, min_observations=min_obs)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/consolidate-pipeline", methods=["POST"])def api_consolidate_pipeline():auth_err = check_auth()if auth_err:return auth_errtry:res = functions.consolidate(kv)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400@app.route("/agentmemory/dolt/commits", methods=["GET"])def api_dolt_commits():auth_err = check_auth()if auth_err:return auth_errtry:limit = int(request.args.get("limit", "50"))rows = kv.get_audit_log(limit)commits = []for r in rows:ts_ms = r["ts"]iso = datetime.datetime.utcfromtimestamp(ts_ms / 1000).isoformat() + "Z"row_id = str(r["id"])commits.append({"sha": row_id.zfill(40),"shortSha": row_id,"agent": r["agent_id"],"email": f"{r['agent_id']}@agentmemory.ai","date": iso,"message": r["message"]})return jsonify({"success": True, "commits": commits}), 200except Exception as e:return jsonify({"error": str(e)}), 500@app.route("/agentmemory/second-brain", methods=["GET"])def api_get_second_brain():auth_err = check_auth()if auth_err:return auth_errbrain_dir = os.getenv("SECOND_BRAIN_DIR", os.path.join(os.path.expanduser("~"), ".agentmemory", "second-brain"))os.makedirs(brain_dir, exist_ok=True)file_param = request.args.get("file")if file_param:safe_name = os.path.basename(file_param)if not safe_name.endswith(".md"):return jsonify({"error": "Only markdown files are allowed"}), 400file_path = os.path.join(brain_dir, safe_name)if not os.path.exists(file_path):return jsonify({"error": f"File {safe_name} not found"}), 404try:with open(file_path, "r", encoding="utf-8") as f:content = f.read()return jsonify({"file": safe_name, "content": content}), 200except Exception as e:return jsonify({"error": str(e)}), 500try:files = []for name in os.listdir(brain_dir):if name.endswith(".md") and os.path.isfile(os.path.join(brain_dir, name)):file_path = os.path.join(brain_dir, name)with open(file_path, "r", encoding="utf-8") as f:content = f.read()files.append({"name": name,"size": os.path.getsize(file_path),"content": content})return jsonify({"success": True, "path": brain_dir, "files": files}), 200except Exception as e:return jsonify({"error": str(e)}), 500@app.route("/agentmemory/second-brain", methods=["POST"])def api_update_second_brain():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}file_name = body.get("file")content = body.get("content")if not file_name or content is None:return jsonify({"error": "file and content are required"}), 400safe_name = os.path.basename(file_name)if not safe_name.endswith(".md"):return jsonify({"error": "Only markdown files are allowed"}), 400brain_dir = os.getenv("SECOND_BRAIN_DIR", os.path.join(os.path.expanduser("~"), ".agentmemory", "second-brain"))if not os.path.exists(brain_dir):os.makedirs(brain_dir, exist_ok=True)file_path = os.path.join(brain_dir, safe_name)content = functions.strip_private_data(content)with open(file_path, "w", encoding="utf-8") as f:f.write(content)functions.commit_if_enabled(kv, f"Update second-brain file: {safe_name}", "user")return jsonify({"success": True, "file": safe_name, "size": len(content)}), 200except Exception as e:return jsonify({"error": str(e)}), 500# =====================================================================# MCP Server Integration (JSON-RPC)# =====================================================================def parse_mcp_list_arg(arg_val):if isinstance(arg_val, list):return [str(item).strip() for item in arg_val if item]if isinstance(arg_val, str) and arg_val:return [item.strip() for item in arg_val.split(",") if item.strip()]return []def enrich_search_results(kv_inst, results):enriched = []for r in results:item = dict(r)obs_id = item.get("obsId")session_id = item.get("sessionId")if not obs_id:continueobj = Noneif session_id == "memory" or obs_id.startswith("mem_"):obj = kv_inst.get(KV.memories, obs_id)elif session_id:obj = kv_inst.get(KV.observations(session_id), obs_id)if obj:item["title"] = obj.get("title") or ""content_val = obj.get("content") or obj.get("narrative") or obj.get("raw") or ""if not isinstance(content_val, str):try:content_val = json.dumps(content_val)except Exception:content_val = str(content_val)item["content"] = content_valitem["type"] = obj.get("type") or ""item["concepts"] = obj.get("concepts") or []item["files"] = obj.get("files") or []else:item["title"] = ""item["content"] = ""item["type"] = ""item["concepts"] = []item["files"] = []enriched.append(item)return enricheddef perform_antigravity_sync(mode="current_session", current_conversation_id=None, current_folder=None):import osimport jsonimport globimport rebrain_dir = os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "brain")if not os.path.exists(brain_dir):return {"success": False, "syncedSessions": [], "observationsAdded": 0, "error": f"Brain directory not found at {brain_dir}"}pattern = os.path.join(brain_dir, "*", ".system_generated", "logs", "transcript.jsonl")files = glob.glob(pattern)if not files:return {"success": True, "syncedSessions": [], "observationsAdded": 0}conversations = []for fpath in files:try:mtime = os.path.getmtime(fpath)convo_id = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(fpath))))conversations.append({"id": convo_id,"transcriptPath": fpath,"mtime": mtime})except Exception:passif not conversations:return {"success": True, "syncedSessions": [], "observationsAdded": 0}conversations.sort(key=lambda x: x["mtime"], reverse=True)targets = []if mode == "current_session":if current_conversation_id:match = next((c for c in conversations if c["id"] == current_conversation_id), None)if match:targets = [match]else:targets = [conversations[0]]elif mode == "current_folder":target_folder = current_folder if current_folder else ""if not target_folder:target_folder = os.getcwd()target_folder_norm = target_folder.replace("\\", "/").lower().strip()for convo in conversations:try:with open(convo["transcriptPath"], "r", encoding="utf-8") as tf:text = tf.read().lower()text_norm = text.replace("\\/", "/").replace("\\\\", "/")if target_folder_norm in text_norm:targets.append(convo)except Exception:passelif mode == "all":targets = conversationselse:return {"success": False, "syncedSessions": [], "observationsAdded": 0, "error": f"Invalid mode: {mode}"}if not targets:return {"success": True, "syncedSessions": [], "processedSessions": [], "observationsAdded": 0}synced_sessions = []processed_sessions = []observations_added = 0for convo in targets:convo_id = convo["id"]tpath = convo["transcriptPath"]session_id = f"antigravity_{convo_id[:18].replace('-', '_')}"project_path = Nonetry:with open(tpath, "r", encoding="utf-8") as tf:first_line = tf.readline()if first_line:step = json.loads(first_line)match = re.search(r"\[([^\]]+)\]\s*->\s*\[([^\]]+)\]", step.get("content", ""))if match:project_path = match.group(2)except Exception:passif not project_path:project_path = os.getcwd()turns = []current_prompt = Nonecurrent_timestamp = Nonetry:with open(tpath, "r", encoding="utf-8") as tf:for line in tf:if not line.strip():continuetry:step = json.loads(line)step_type = step.get("type")if step_type == "USER_INPUT":p_text = step.get("content", "")if "<USER_REQUEST>" in p_text:parts = p_text.split("<USER_REQUEST>")if len(parts) > 1:p_text = parts[1]if "</USER_REQUEST>" in p_text:p_text = p_text.split("</USER_REQUEST>")[0]current_prompt = p_text.strip()current_timestamp = step.get("created_at")elif step_type == "PLANNER_RESPONSE" and current_prompt:turns.append({"prompt": current_prompt,"response": step.get("content", ""),"timestamp": current_timestamp or step.get("created_at") or datetime_now_iso()})current_prompt = Nonecurrent_timestamp = Noneexcept Exception:passexcept Exception:continueif not turns:continueexisting_inputs = set()obs_list = kv.list(KV.observations(session_id))for obs in obs_list:tool_input = obs.get("toolInput") or (obs.get("raw") or {}).get("tool_input")if tool_input:existing_inputs.add(tool_input.strip())session_exists = kv.get(KV.sessions, session_id) is not Noneif not session_exists:session = {"id": session_id,"project": project_path,"cwd": project_path,"startedAt": datetime_now_iso(),"status": "active","observationCount": 0,"summary": f"Antigravity Pair Programming ({convo_id[:8]})","firstPrompt": f"Antigravity Pair Programming ({convo_id[:8]})","agentId": "antigravity"}functions.create_session(kv, session)convo_synced = Falsefor turn in turns:prompt = turn["prompt"]if prompt.strip() in existing_inputs:continuepayload = {"sessionId": session_id,"project": project_path,"cwd": project_path,"hookType": "post_tool_use","timestamp": turn["timestamp"],"agentId": "antigravity","data": {"tool_name": "conversation","tool_input": prompt,"tool_output": turn["response"],}}functions.observe(kv, payload)observations_added += 1convo_synced = Trueprocessed_sessions.append(convo_id)if convo_synced:synced_sessions.append(convo_id)return {"success": True, "syncedSessions": synced_sessions, "processedSessions": processed_sessions, "observationsAdded": observations_added}@app.route("/agentmemory/mcp/tools", methods=["GET"])def mcp_tools_list():auth_err = check_auth()if auth_err:return auth_errtools = [{"name": "memory_recall","description": "Search past folder observations and global memories. Use when you need to recall what happened in a folder.","inputSchema": {"type": "object","properties": {"query": {"type": "string", "description": "Search query keywords"},"limit": {"type": "number", "description": "Max results to return (default 10)"},"folderPath": {"type": "string", "description": "Filter to a specific folder path (optional)"},"agentId": {"type": "string", "description": "Filter to a specific agent ID (optional)"}},"required": ["query"]}},{"name": "memory_smart_search","description": "Hybrid semantic+keyword search across folder observations and global memories.","inputSchema": {"type": "object","properties": {"query": {"type": "string", "description": "Search query"},"limit": {"type": "number", "description": "Max results (default 10)"},"folderPath": {"type": "string", "description": "Filter to a specific folder path (optional)"},"agentId": {"type": "string", "description": "Filter to a specific agent ID (optional)"}},"required": ["query"]}},{"name": "memory_save","description": "Explicitly save an important insight, decision, or pattern to long-term memory.","inputSchema": {"type": "object","properties": {"content": {"type": "string", "description": "The insight or decision to remember"},"type": {"type": "string", "description": "Memory type: pattern, preference, architecture, bug, workflow, or fact"},"concepts": {"oneOf": [{"type": "string", "description": "Comma-separated key concepts"},{"type": "array", "items": {"type": "string"}, "description": "List of key concepts"}]},"files": {"oneOf": [{"type": "string", "description": "Comma-separated relevant file paths"},{"type": "array", "items": {"type": "string"}, "description": "List of relevant file paths"}]},"project": {"type": "string", "description": "Canonical project identifier"}},"required": ["content"]}},{"name": "memory_diagnose","description": "Health check — returns folder, agent, observation and memory counts.","inputSchema": {"type": "object", "properties": {}}},{"name": "memory_forget","description": "Delete a global memory or all observations for a (folderPath, agentId) pair.","inputSchema": {"type": "object","properties": {"memoryId": {"type": "string", "description": "Memory ID to delete"},"folderPath": {"type": "string", "description": "Folder path to delete observations from"},"agentId": {"type": "string", "description": "Agent ID to delete observations for"},"observationIds": {"oneOf": [{"type": "string", "description": "Comma-separated observation IDs to delete"},{"type": "array", "items": {"type": "string"}}]}}}},{"name": "memory_export","description": "Export all folder observations and global memories as JSON (v2 format).","inputSchema": {"type": "object", "properties": {}}},{"name": "agent_observe","description": "Log an observation scoped to a folder path and agent ID.","inputSchema": {"type": "object","properties": {"folderPath": {"type": "string", "description": "Absolute path of the working directory"},"agentId": {"type": "string", "description": "Identity of the agent (e.g. 'kiro', 'claude')"},"text": {"type": "string", "description": "Observation content"},"timestamp": {"type": "string", "description": "ISO 8601 UTC timestamp (defaults to now)"},"type": {"type": "string", "description": "Observation type"},"title": {"type": "string", "description": "Short title"},"concepts": {"type": "array", "items": {"type": "string"}},"files": {"type": "array", "items": {"type": "string"}},"importance": {"type": "integer", "description": "1-10"},"sessionId": {"type": "string", "description": "Deprecated — ignored"}},"required": ["folderPath", "agentId", "text"]}},{"name": "agent_remember","description": "Explicitly save a key insight, fact, or architecture decision to long-term memory.","inputSchema": {"type": "object","properties": {"agentId": {"type": "string", "description": "ID/Name of the agent (optional)"},"content": {"type": "string", "description": "The memory content/insight"},"project": {"type": "string", "description": "Canonical project path/identifier"},"type": {"type": "string", "description": "Memory type: fact, preference, bug, workflow, architecture"},"concepts": {"oneOf": [{"type": "string", "description": "Comma-separated key concepts"},{"type": "array", "items": {"type": "string"}}]},"files": {"oneOf": [{"type": "string", "description": "Comma-separated relevant file paths"},{"type": "array", "items": {"type": "string"}}]}},"required": ["content"]}},{"name": "memory_folders","description": "List all (folder, agent) pairs that have memory observations.","inputSchema": {"type": "object", "properties": {}}},{"name": "memory_folder_observations","description": "Get all observations for a specific (folderPath, agentId) pair.","inputSchema": {"type": "object","properties": {"folderPath": {"type": "string", "description": "Folder path"},"agentId": {"type": "string", "description": "Agent ID"}},"required": ["folderPath", "agentId"]}},{"name": "memory_timeline","description": "Get folder activity feed — observations sorted by time, filterable by folder/agent.","inputSchema": {"type": "object","properties": {"folderPath": {"type": "string", "description": "Filter by folder path (optional)"},"agentId": {"type": "string", "description": "Filter by agent ID (optional)"},"limit": {"type": "integer", "description": "Max results (default 100)"},"before": {"type": "string", "description": "ISO timestamp upper bound (optional)"},"after": {"type": "string", "description": "ISO timestamp lower bound (optional)"}}}}]return jsonify({"tools": tools}), 200@app.route("/agentmemory/mcp/tools", methods=["POST"])def mcp_tools_call():auth_err = check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}name = body.get("name")args = body.get("arguments") or {}if not name:return jsonify({"error": "name is required"}), 400print(f"[mcp] Calling tool {name} with args: {args}")text_out = ""if name == "memory_recall":q = args.get("query")limit = int(args.get("limit") or 10)folder_path = args.get("folderPath")agent_id = args.get("agentId")res = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id)text_out = json.dumps(res, indent=2)elif name == "memory_save":content = args.get("content")concepts = parse_mcp_list_arg(args.get("concepts"))files = parse_mcp_list_arg(args.get("files"))project = args.get("project")res = functions.remember(kv, {"content": content,"type": args.get("type") or "fact","concepts": concepts,"files": files,"project": project})text_out = json.dumps(res)elif name == "memory_smart_search":q = args.get("query")limit = int(args.get("limit") or 10)folder_path = args.get("folderPath")agent_id = args.get("agentId")res = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id)text_out = json.dumps(res, indent=2)elif name == "memory_diagnose":res = functions.health_check(kv)text_out = json.dumps(res, indent=2)elif name == "memory_forget":obs_ids = parse_mcp_list_arg(args.get("observationIds"))res = functions.forget(kv, {"memoryId": args.get("memoryId"),"folderPath": args.get("folderPath"),"agentId": args.get("agentId"),"observationIds": obs_ids})text_out = json.dumps(res, indent=2)elif name == "memory_export":res = functions.export_data(kv, {})text_out = json.dumps(res, indent=2)elif name == "agent_observe":folder_path = args.get("folderPath")agent_id = args.get("agentId")text = args.get("text") or args.get("content") or ""if not folder_path or not agent_id or not text:return jsonify({"error": "folderPath, agentId, and text are required"}), 400timestamp = args.get("timestamp") or datetime_now_iso()payload = {"folderPath": folder_path, "agentId": agent_id, "text": text,"timestamp": timestamp, "type": args.get("type"), "title": args.get("title"),"concepts": args.get("concepts"), "files": args.get("files"),"importance": args.get("importance"),}res = functions.folder_observe(kv, payload)text_out = json.dumps(res)elif name == "agent_remember":agent_id = args.get("agentId") or functions.get_agent_id() or "agent"content = args.get("content")project = args.get("project")mem_type = args.get("type") or "fact"concepts = parse_mcp_list_arg(args.get("concepts"))files = parse_mcp_list_arg(args.get("files"))if not content:return jsonify({"error": "content is required"}), 400payload = {"content": content, "type": mem_type, "concepts": concepts,"files": files, "project": project, "agentId": agent_id}res = functions.remember(kv, payload)text_out = json.dumps(res)elif name == "memory_folders":pairs = sorted(kv.list(functions.KV.folders), key=lambda x: x.get("lastUpdated", ""), reverse=True)text_out = json.dumps(pairs, indent=2)elif name == "memory_folder_observations":fp = args.get("folderPath", "")aid = args.get("agentId", "")if not fp or not aid:return jsonify({"error": "folderPath and agentId are required"}), 400obs = sorted(kv.list(functions.KV.folder_obs(fp, aid)), key=lambda x: x.get("timestamp", ""), reverse=True)text_out = json.dumps(obs, indent=2)elif name == "memory_timeline":res = functions.folder_timeline(kv,limit=int(args.get("limit", 100)),folder_path=args.get("folderPath"),agent_id=args.get("agentId"),before=args.get("before"),after=args.get("after"),)text_out = json.dumps(res, indent=2)else:return jsonify({"error": f"unknown tool: {name}"}), 400return jsonify({"content": [{"type": "text", "text": text_out}]}), 200except Exception as e:return jsonify({"error": str(e)}), 500# =====================================================================# Agent Discovery Endpoint (/agent.md and /auth.md)# =====================================================================AGENT_MD_TEMPLATE = """# AgentMemory — Agent Connection Guide> This document is auto-generated. Fetch it fresh each session so you always have current values.## 1. Server| Field | Value ||-------|-------|| Base URL | `http://127.0.0.1:{port}` || API prefix | `/agentmemory` || Liveness | `GET http://127.0.0.1:{port}/agentmemory/livez` (no auth) || Auth required | `{auth_required}` || Auth header | `Authorization: Bearer <AGENTMEMORY_SECRET>` |{auth_note}---## 2. Quick-Start: Minimum Viable SessionDo these in order at the start of every session:```1. POST /agentmemory/session/start ← register yourself2. POST /agentmemory/context ← inject past memory into your system prompt... do work, call observe after each tool use ...3. POST /agentmemory/session/end ← mark session complete```### 2a. Start a session```httpPOST /agentmemory/session/startContent-Type: application/json{auth_header_example}{{"sessionId": "<uuid-you-generate>","project": "<absolute-path-or-name-of-repo>","cwd": "<current working directory>","agentId": "<your-agent-name>","title": "<first user prompt, optional>"}}```Response includes `context` — paste it into your system prompt before answering.### 2b. Compile context (also works mid-session)```httpPOST /agentmemory/contextContent-Type: application/json{auth_header_example}{{"sessionId": "<your-session-id>","project": "<same project as above>","budget": 2000}}```Returns `context` string wrapped in `<agentmemory-context>` tags. Insert verbatim.### 2c. Log an observation (call after every significant tool use)```httpPOST /agentmemory/agent/observeContent-Type: application/json{auth_header_example}{{"agentId": "<your-agent-name>","sessionId": "<your-session-id>","project": "<project>","cwd": "<cwd>","text": "<what you did or observed>","type": "tool | command | thought | error | result | conversation | other","title": "<short one-line summary>"}}```### 2d. Save a long-term memory (decisions, patterns, preferences)```httpPOST /agentmemory/agent/rememberContent-Type: application/json{auth_header_example}{{"agentId": "<your-agent-name>","project": "<project>","content": "<the insight, decision, or fact>","type": "fact | preference | architecture | bug | workflow | pattern","concepts": "auth, jwt, middleware","files": "src/middleware/auth.ts, tests/auth.test.ts"}}```### 2e. End session```httpPOST /agentmemory/session/endContent-Type: application/json{auth_header_example}{{"sessionId": "<your-session-id>"}}```---## 3. MCP Tools (JSON-RPC style)Call via: `POST /agentmemory/mcp/tools````httpPOST /agentmemory/mcp/toolsContent-Type: application/json{auth_header_example}{{"name": "<tool-name>","arguments": {{ ... }}}}```| Tool | Required args | Description ||------|---------------|-------------|| `memory_recall` | `query` | BM25+vector hybrid search over all past observations || `memory_smart_search` | `query` | Same as recall with progressive disclosure || `memory_save` | `content` | Save long-term memory (type, concepts, files optional) || `memory_sessions` | — | List recent sessions with observation counts || `memory_timeline` | `anchor` | Observations around a date or keyword anchor || `memory_profile` | `project` | Top concepts, files, conventions for a project || `memory_lesson_save` | `content` | Save a lesson (auto-strengthens duplicates) || `memory_lesson_recall` | `query` | Search lessons scored by confidence + recency || `agent_observe` | `agentId`, `sessionId`, `project`, `text` | Log an observation (same as REST) || `agent_remember` | `agentId`, `content`, `project` | Save memory (same as REST) |Get full schemas: `GET /agentmemory/mcp/tools`---## 4. Full REST Endpoint ReferenceAll endpoints require `Authorization: Bearer <secret>` when auth is enabled.Prefix every path with `http://127.0.0.1:{port}`.### Session Management| Method | Path | Key body fields | Notes ||--------|------|-----------------|-------|| `POST` | `/agentmemory/session/start` | `sessionId`, `project`, `cwd`, `agentId` | Returns `session` + `context` || `POST` | `/agentmemory/session/end` | `sessionId` | Marks status=completed || `GET` | `/agentmemory/sessions` | — | List all sessions || `GET` | `/agentmemory/observations?sessionId=` | — | Observations for a session || `POST` | `/agentmemory/session/commit` | `sha`, `sessionId`, `branch`, `message` | Link a git commit to a session || `GET` | `/agentmemory/session/by-commit?sha=` | — | Sessions linked to a commit || `GET` | `/agentmemory/commits` | `branch`, `repo`, `limit` | List tracked commits |### Observations| Method | Path | Key body fields | Notes ||--------|------|-----------------|-------|| `POST` | `/agentmemory/observe` | `sessionId`, `hookType`, `timestamp`, `data` | Raw hook payload || `POST` | `/agentmemory/agent/observe` | `agentId`, `sessionId`, `project`, `text`, `type` | Simplified agent endpoint |`hookType` values: `post_tool_use`, `post_tool_failure`, `prompt_submit`, `subagent_stop`, `task_completed`, `notification`### Memory| Method | Path | Key body fields | Notes ||--------|------|-----------------|-------|| `POST` | `/agentmemory/remember` | `content`, `type`, `concepts[]`, `files[]`, `project` | Supersedes similar memories automatically || `POST` | `/agentmemory/agent/remember` | `agentId`, `content`, `project`, `type`, `concepts`, `files` | Simplified agent endpoint || `POST` | `/agentmemory/forget` | `memoryId` OR `sessionId` [+ `observationIds[]`] | Delete memory/session/observations || `POST` | `/agentmemory/evolve` | `memoryId`, `newContent`, `newTitle` | Version a memory (creates new, marks old superseded) || `POST` | `/agentmemory/search` | `query`, `limit` | Hybrid BM25+vector search || `POST` | `/agentmemory/context` | `sessionId`, `project`, `budget` | Compile context block for injection |Memory `type` values: `fact`, `preference`, `architecture`, `bug`, `workflow`, `pattern`### Lessons| Method | Path | Key body fields | Notes ||--------|------|-----------------|-------|| `POST` | `/agentmemory/lessons` | `content`, `context`, `project`, `confidence`, `tags[]` | Create/strengthen (duplicate = auto-reinforce) || `GET` | `/agentmemory/lessons` | `project`, `minConfidence`, `limit` | List lessons || `POST` | `/agentmemory/lessons/search` | `query`, `project`, `limit` | Keyword search scored by confidence×recency || `POST` | `/agentmemory/lessons/strengthen` | `lessonId` | Manually reinforce a lesson (+0.1 confidence) |### Memory Slots (Pinned Context)Slots are named text buffers injected into every context compilation.| Method | Path | Key body/query fields | Notes ||--------|------|-----------------------|-------|| `GET` | `/agentmemory/slots` | — | List all slots || `GET` | `/agentmemory/slot?label=` | — | Get single slot || `POST` | `/agentmemory/slot` | `label`, `content`, `scope`, `sizeLimit`, `pinned` | Create slot || `POST` | `/agentmemory/slot/append` | `label`, `text` | Append text to slot || `POST` | `/agentmemory/slot/replace` | `label`, `content` | Replace slot content || `DELETE` | `/agentmemory/slot?label=` | — | Delete slot || `POST` | `/agentmemory/slot/reflect` | `sessionId`, `maxObservations` | Auto-populate slots from session observations |Default slot labels: `persona`, `user_preferences`, `tool_guidelines`, `project_context`, `guidance`, `pending_items`, `session_patterns`, `self_notes`### Knowledge Graph & Analytics| Method | Path | Key body/query fields | Notes ||--------|------|-----------------------|-------|| `GET` | `/agentmemory/relations` | — | List all knowledge graph edges || `POST` | `/agentmemory/relations` | `sourceId`, `targetId`, `type` | Add a relation edge || `POST` | `/agentmemory/timeline` | `anchor`, `project`, `before`, `after` | Observations around anchor || `GET` | `/agentmemory/profile?project=` | — | Project profile (top concepts/files) || `GET` | `/agentmemory/audit` | `operation`, `limit` | Audit log || `GET` | `/agentmemory/profile` | `project` (optional) | Project profile; omit `project` to list all known projects || `GET` | `/agentmemory/actions` | `limit`, `status` | List actions || `POST` | `/agentmemory/actions` | `title`, `description`, `priority`, `tags[]`, `status` | Create action || `PATCH`| `/agentmemory/actions/<id>` | any action fields | Update action || `GET` | `/agentmemory/frontier` | — | Pending+active actions sorted by priority || `GET` | `/agentmemory/insights` | `limit` | List insights || `GET` | `/agentmemory/replay/sessions` | — | Sessions list for replay || `GET` | `/agentmemory/replay/load?sessionId=` | — | Full session + ordered observations for replay || `POST` | `/agentmemory/auto-forget` | `dryRun` | Evict stale observations |### Health & Config| Method | Path | Auth | Notes ||--------|------|------|-------|| `GET` | `/agentmemory/livez` | No | Liveness check || `GET` | `/agentmemory/health` | Yes | Full health + version || `GET` | `/agentmemory/config/flags` | Yes | Feature flags (graph, consolidation, compression) |---## 5. WebSocket Live Stream```ws://127.0.0.1:{port}/stream/mem-live/viewer```Connect to receive real-time events. Message types:- `raw_observation` — raw hook payload as received- `compressed_observation` — after synthetic compression + indexingNo auth on the WebSocket endpoint.---## 6. Agent Identity & Scope IsolationSet `AGENT_ID` env var on the server to scope all read operations to a single agent.Set `AGENTMEMORY_AGENT_SCOPE=isolated` to enforce per-agent isolation.Always pass `agentId` in every request body — it's stored on every observation/memory and enables per-agent filtering via `?agentId=<id>` on list endpoints.---## 7. Secrets Are RedactedAny text containing API keys, Bearer tokens, passwords, or JWTs is automatically redacted to `[REDACTED_SECRET]` before storage. Wrap sensitive blocks in `<private>...</private>` tags to force redaction.---*Generated by agentmemory v{version} — `GET /agent.md` to refresh*"""@app.route("/agent.md", methods=["GET"])@app.route("/auth.md", methods=["GET"])def agent_discovery():auth_err = check_auth()if auth_err:return auth_errport = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))secret = os.getenv("AGENTMEMORY_SECRET")auth_required = "yes" if secret else "no"if secret:auth_note = ("> **Auth is enabled.** Add `Authorization: Bearer <AGENTMEMORY_SECRET>` to every request.\n""> The secret is set via `AGENTMEMORY_SECRET` env var in `~/.agentmemory/.env`.")auth_header_example = 'Authorization: Bearer <AGENTMEMORY_SECRET>'else:auth_note = ("> **Auth is disabled.** No `Authorization` header needed — all endpoints are open.")auth_header_example = ''md = AGENT_MD_TEMPLATE.format(port=port,auth_required=auth_required,auth_note=auth_note,auth_header_example=auth_header_example,version="0.9.8",)response = make_response(md)response.headers["Content-Type"] = "text/markdown; charset=utf-8"response.headers["Cache-Control"] = "no-cache"return response# =====================================================================# Lifecycle Helpers# =====================================================================if __name__ == "__main__":init_app()# Default Flask server settingsport = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))# Listen on all interfaces (required for container deployments like HF Spaces)print(f"[main] Starting Flask daemon on port {port}...")app.run(host="0.0.0.0", port=port, debug=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""agentmemory-python — Flask application factory.Entry point: create_app() returns a fully configured Flask app.Run directly: python src/app.py"""import osimport jsonimport hmacfrom flask import Flask, request, make_response, send_from_directoryfrom flask_sock import Sockdef _load_env() -> None:env_path = os.path.join(os.path.expanduser("~"), ".agentmemory", ".env")if not os.path.exists(env_path):returntry:with open(env_path, "r", encoding="utf-8") as f:for line in f:line = line.strip()if not line or line.startswith("#") or "=" not in line:continuek, v = line.split("=", 1)os.environ[k.strip()] = v.strip().strip('"').strip("'")print(f"[config] Loaded environment from {env_path}")except Exception as e:print(f"[config] Error reading env file: {e}")_load_env()# Module-level globals — set once by create_app(), read by blueprints via `import app`kv = Noneembedding_provider = Nonepersistence = Nonedef create_app() -> Flask:"""Create and return a fully configured Flask application."""global kv, embedding_provider, persistenceimport search as search_modimport functionsfrom db import StateKVfrom viewer_helpers import make_viewer_response# 1. DBkv = StateKV()# 2. Embedding provider — auto-select by priority (D5.3):# GEMINI_API_KEY → OPENAI_API_KEY → AGENTMEMORY_LOCAL_EMBEDDING_MODEL → BM25-onlyapi_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")openai_key = os.getenv("OPENAI_API_KEY")local_model = os.getenv("AGENTMEMORY_LOCAL_EMBEDDING_MODEL")if api_key:try:embedding_provider = search_mod.GeminiEmbeddingProvider(api_key)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: gemini ({embedding_provider.dimensions} dims)")except Exception as e:print(f"[search] Error initialising Gemini embedding provider: {e}")elif openai_key:try:embedding_provider = search_mod.OpenAIEmbeddingProvider(openai_key)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: openai ({embedding_provider.dimensions} dims)")except Exception as e:print(f"[search] Error initialising OpenAI embedding provider: {e}")elif local_model:try:embedding_provider = search_mod.SentenceTransformerProvider(local_model)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: sentence-transformers/{local_model} ({embedding_provider.dimensions} dims)")except ImportError as e:print(f"[search] sentence-transformers not installed: {e}")except Exception as e:print(f"[search] Error initialising SentenceTransformer provider: {e}")else:print("[search] No embedding API key found — running in BM25-only mode.")# 3. Index persistence — use embedding_provider variable set abovehas_vector = embedding_provider is not Nonepersistence = functions.IndexPersistence(kv, functions._bm25_index, functions._vector_index if has_vector else None,)functions.set_index_persistence(persistence)loaded = persistence.load()print(f"[persistence] Load results: BM25={loaded['bm25']}, Vector={loaded['vector']}")# 4. Flask app + blueprintsflask_app = Flask(__name__)from routes import register_blueprintsregister_blueprints(flask_app)# 5. WebSocket broadcastersock = Sock(flask_app)_ws_clients: set = set()@sock.route("/stream/mem-live/viewer")def stream_viewer(ws):secret = os.getenv("AGENTMEMORY_SECRET")if secret:token = request.args.get("token") or request.args.get("secret")if not token or not hmac.compare_digest(token.encode("utf-8"), secret.encode("utf-8")):ws.close(1008)return_ws_clients.add(ws)try:while ws.receive() is not None:passexcept Exception:passfinally:_ws_clients.discard(ws)def _broadcast(payload: dict) -> None:msg = json.dumps(payload)for ws in list(_ws_clients):try:ws.send(msg)except Exception:_ws_clients.discard(ws)functions.set_stream_broadcaster(_broadcast)# 6. Viewer static routes_base_dir = os.path.dirname(os.path.abspath(__file__))@flask_app.route("/")@flask_app.route("/viewer")@flask_app.route("/agentmemory/viewer")def serve_viewer():try:return make_viewer_response(_base_dir)except Exception as e:return f"Viewer not found: {e}", 404@flask_app.route("/favicon.svg")def serve_favicon():return send_from_directory(os.path.join(_base_dir, "viewer"), "favicon.svg")# 7. CORS after_request — D2.1: configurable via AGENTMEMORY_CORS_ORIGINS env var# Default allows localhost, 127.0.0.1, vscode-webview://, and chrome-extension://_default_cors = "http://localhost,http://127.0.0.1,vscode-webview://,chrome-extension://"_cors_origins_raw = os.getenv("AGENTMEMORY_CORS_ORIGINS", _default_cors)_allowed_origins = [o.strip().rstrip("*") for o in _cors_origins_raw.split(",") if o.strip()]@flask_app.after_requestdef _cors(response):origin = request.headers.get("Origin")if origin:lo = origin.lower()if any(lo == allowed.lower() or lo.startswith(allowed.lower())for allowed in _allowed_origins):response.headers["Access-Control-Allow-Origin"] = originresponse.headers["Access-Control-Allow-Credentials"] = "true"response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")response.headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")return response# 8. Background workersfrom workers import start_background_workersstart_background_workers(kv)return flask_appdef main() -> None:flask_app = create_app()port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))print(f"[main] Starting Flask daemon on port {port}...")flask_app.run(host="0.0.0.0", port=port, debug=False)if __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899#!/usr/bin/env python3"""agentmemory CLI entrypoint.
Commands: agentmemory serve [--port PORT] [--host HOST] agentmemory migrate [--dry-run] agentmemory export [--output FILE]"""
import argparseimport jsonimport osimport sys
def cmd_serve(args) -> None: """Start the Flask server.""" os.environ.setdefault("III_REST_PORT", str(args.port)) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from app import create_app flask_app = create_app() print(f"[cli] Starting agentmemory on {args.host}:{args.port}") flask_app.run(host=args.host, port=args.port, debug=False)
def cmd_migrate(args) -> None: """Run session → folder migration.""" sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from db import StateKV from functions import migrate_sessions_to_folders kv = StateKV() result = migrate_sessions_to_folders(kv, dry_run=args.dry_run) print(json.dumps(result, indent=2)) if args.dry_run: print(f"\n[cli] Dry run — no changes made. " f"{result['migrated_sessions']} sessions, " f"{result['migrated_observations']} observations would be migrated.") else: print(f"\n[cli] Migration complete: " f"{result['migrated_sessions']} sessions, " f"{result['migrated_observations']} observations migrated.") if result.get("errors"): print(f"[cli] {len(result['errors'])} errors:") for e in result["errors"]: print(f" - {e}")
def cmd_export(args) -> None: """Export all data as JSON.""" sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from db import StateKV from functions import export_data kv = StateKV() data = export_data(kv, {}) output = json.dumps(data, indent=2, ensure_ascii=False) if args.output: with open(args.output, "w", encoding="utf-8") as f: f.write(output) print(f"[cli] Exported to {args.output}") total_obs = sum(len(folder.get("observations", [])) for folder in data.get("folders", [])) print(f"[cli] {len(data.get('folders', []))} folders, {total_obs} observations, " f"{len(data.get('memories', []))} memories") else: print(output)
def main() -> None: parser = argparse.ArgumentParser( prog="agentmemory", description="agentmemory — AI agent memory server", ) subparsers = parser.add_subparsers(dest="command", required=True)
# serve serve_parser = subparsers.add_parser("serve", help="Start the memory server") serve_parser.add_argument("--port", type=int, default=int(os.getenv("III_REST_PORT", "3111"))) serve_parser.add_argument("--host", default="0.0.0.0")
# migrate migrate_parser = subparsers.add_parser("migrate", help="Migrate legacy session data to folder-based storage") migrate_parser.add_argument("--dry-run", action="store_true", help="Preview without writing")
# export export_parser = subparsers.add_parser("export", help="Export all data as JSON") export_parser.add_argument("--output", "-o", help="Output file path (default: stdout)")
args = parser.parse_args()
if args.command == "serve": cmd_serve(args) elif args.command == "migrate": cmd_migrate(args) elif args.command == "export": cmd_export(args)
if __name__ == "__main__": main()2 unmodified lines3456789101112131415161718192021222324252627282930313222 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251262 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831 unmodified line1851861871881891901911921932 unmodified lines1961971981992002012022032042052062072082092102112122132142152162172182 unmodified linesimport sqlite3import threadingimport timefrom typing import Dict, Any, List, Optional, TypeVar, UnionT = TypeVar("T")DB_PATH = os.path.join(os.path.expanduser("~"), ".agentmemory", "agentmemory.db")class StateKV:def __init__(self, db_path: str = DB_PATH):self.db_path = db_pathself._lock = threading.Lock()self._init_db()def _get_conn(self) -> sqlite3.Connection:conn = sqlite3.connect(self.db_path, check_same_thread=False, timeout=30)conn.row_factory = sqlite3.Rowconn.execute("PRAGMA journal_mode=WAL")conn.execute("PRAGMA synchronous=NORMAL")conn.execute("PRAGMA foreign_keys=ON")return conndef _init_db(self):try:os.makedirs(os.path.dirname(self.db_path), exist_ok=True)conn = self._get_conn()try:conn.execute("""CREATE TABLE IF NOT EXISTS kv_store (22 unmodified linesdef get(self, scope: str, key: str) -> Optional[Any]:try:conn = self._get_conn()try:row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key)).fetchone()if row:val = json.loads(row["value"])if isinstance(val, dict) and "id" not in val:val["id"] = keyreturn valreturn Nonefinally:conn.close()except Exception as e:print(f"[db] get failed (scope={scope}, key={key}): {e}")return Nonedef set(self, scope: str, key: str, value: Any) -> Any:try:conn = self._get_conn()try:conn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(value)))conn.commit()return valuefinally:conn.close()except Exception as e:print(f"[db] set failed (scope={scope}, key={key}): {e}")return valuedef delete(self, scope: str, key: str) -> bool:try:conn = self._get_conn()try:cur = conn.execute("DELETE FROM kv_store WHERE scope = ? AND key = ?",(scope, key))conn.commit()return cur.rowcount > 0finally:conn.close()except Exception as e:print(f"[db] delete failed (scope={scope}, key={key}): {e}")return Falsedef list(self, scope: str) -> List[Any]:try:conn = self._get_conn()try:rows = conn.execute("SELECT key, value FROM kv_store WHERE scope = ?",(scope,)).fetchall()results = []for r in rows:val = json.loads(r["value"])if isinstance(val, dict) and "id" not in val:val["id"] = r["key"]results.append(val)return resultsfinally:conn.close()except Exception as e:print(f"[db] list failed (scope={scope}): {e}")return []2 unmodified lineswith self._lock:try:conn = self._get_conn()try:row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key)).fetchone()obj = json.loads(row["value"]) if row else {}if not isinstance(obj, dict):obj = {}if "id" not in obj:obj["id"] = keyfor op in ops:op_type = op.get("type")path = op.get("path")val = op.get("value")if not path:continueif op_type == "set":if "." in path:parts = path.split(".")curr = objfor part in parts[:-1]:if part not in curr or not isinstance(curr[part], dict):curr[part] = {}curr = curr[part]curr[parts[-1]] = valelse:obj[path] = valelif op_type == "delete":if "." in path:parts = path.split(".")curr = objfor part in parts[:-1]:if part not in curr or not isinstance(curr[part], dict):breakcurr = curr[part]else:curr.pop(parts[-1], None)else:obj.pop(path, None)conn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(obj)))conn.commit()return objfinally:conn.close()except Exception as e:print(f"[db] update failed (scope={scope}, key={key}): {e}")return None1 unmodified linedef commit_version(self, message: str, agent_id: str) -> Optional[str]:"""Write an audit log entry instead of a Dolt commit."""author = agent_id or "unknown-agent"try:conn = self._get_conn()try:cur = conn.execute("INSERT INTO audit_log (ts, agent_id, message) VALUES (?, ?, ?)",(int(time.time() * 1000), author, message)2 unmodified linesrow_id = str(cur.lastrowid)print(f"[audit] {author}: {message} (id={row_id})")return row_idfinally:conn.close()except Exception as e:print(f"[audit] commit_version failed: {e}")return Nonedef get_audit_log(self, limit: int = 50) -> List[Dict[str, Any]]:try:conn = self._get_conn()try:rows = conn.execute("SELECT id, ts, agent_id, message FROM audit_log ORDER BY ts DESC LIMIT ?",(limit,)).fetchall()return [dict(r) for r in rows]finally:conn.close()except Exception as e:print(f"[db] get_audit_log failed: {e}")return []2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311422 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971982 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512521 unmodified line2542552562572582592602612622 unmodified lines2652662672682692702712722732742752762772782792802812822 unmodified linesimport sqlite3import threadingimport timeimport atexitfrom typing import Dict, Any, List, Optional, TypeVar, UnionT = TypeVar("T")DB_PATH = os.path.join(os.path.expanduser("~"), ".agentmemory", "agentmemory.db")class StateKV:def __init__(self, db_path: str = DB_PATH):self.db_path = db_pathself._lock = threading.Lock()# Per-thread persistent connection pool (A3.1)self._local = threading.local()self._init_db()# Register WAL checkpoint on graceful shutdown (A3.2)atexit.register(self._wal_checkpoint)def _get_conn(self) -> sqlite3.Connection:"""Return a per-thread persistent connection, creating one if needed (A3.1)."""conn = getattr(self._local, "conn", None)if conn is None:conn = sqlite3.connect(self.db_path, check_same_thread=False, timeout=30)conn.row_factory = sqlite3.Rowconn.execute("PRAGMA journal_mode=WAL")conn.execute("PRAGMA synchronous=NORMAL")conn.execute("PRAGMA foreign_keys=ON")self._local.conn = connreturn conndef _wal_checkpoint(self) -> None:"""Flush WAL frames to the main database file on shutdown (A3.2)."""try:conn = getattr(self._local, "conn", None)if conn:conn.execute("PRAGMA wal_checkpoint(FULL)")conn.commit()else:# Open a temporary connection just for the checkpointtmp = sqlite3.connect(self.db_path, check_same_thread=False, timeout=10)try:tmp.execute("PRAGMA wal_checkpoint(FULL)")tmp.commit()finally:tmp.close()print("[db] WAL checkpoint completed on shutdown.")except Exception as e:print(f"[db] WAL checkpoint failed: {e}")def teardown(self) -> None:"""Close the per-thread connection and flush WAL (for explicit cleanup)."""self._wal_checkpoint()conn = getattr(self._local, "conn", None)if conn:try:conn.close()except Exception:passself._local.conn = Nonedef stats(self) -> Dict[str, Any]:"""Return DB statistics for the /health endpoint (A3.3).Returns:{"db_size_bytes": int,"kv_row_count": int,"audit_row_count": int,"wal_size_bytes": int,}"""result: Dict[str, Any] = {"db_size_bytes": 0,"kv_row_count": 0,"audit_row_count": 0,"wal_size_bytes": 0,}try:if os.path.exists(self.db_path):result["db_size_bytes"] = os.path.getsize(self.db_path)wal_path = self.db_path + "-wal"if os.path.exists(wal_path):result["wal_size_bytes"] = os.path.getsize(wal_path)except Exception:passtry:conn = self._get_conn()result["kv_row_count"] = conn.execute("SELECT COUNT(*) FROM kv_store").fetchone()[0]result["audit_row_count"] = conn.execute("SELECT COUNT(*) FROM audit_log").fetchone()[0]except Exception:passreturn resultdef _init_db(self):try:os.makedirs(os.path.dirname(self.db_path), exist_ok=True)# Use a temporary direct connection for initialization (before _local is set)conn = sqlite3.connect(self.db_path, check_same_thread=False, timeout=30)conn.row_factory = sqlite3.Rowconn.execute("PRAGMA journal_mode=WAL")conn.execute("PRAGMA synchronous=NORMAL")conn.execute("PRAGMA foreign_keys=ON")try:conn.execute("""CREATE TABLE IF NOT EXISTS kv_store (22 unmodified linesdef get(self, scope: str, key: str) -> Optional[Any]:try:conn = self._get_conn()row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key)).fetchone()if row:val = json.loads(row["value"])if isinstance(val, dict) and "id" not in val:val["id"] = keyreturn valreturn Noneexcept Exception as e:print(f"[db] get failed (scope={scope}, key={key}): {e}")return Nonedef set(self, scope: str, key: str, value: Any) -> Any:with self._lock:try:conn = self._get_conn()conn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(value)))conn.commit()return valueexcept Exception as e:print(f"[db] set failed (scope={scope}, key={key}): {e}")return valuedef delete(self, scope: str, key: str) -> bool:with self._lock:try:conn = self._get_conn()cur = conn.execute("DELETE FROM kv_store WHERE scope = ? AND key = ?",(scope, key))conn.commit()return cur.rowcount > 0except Exception as e:print(f"[db] delete failed (scope={scope}, key={key}): {e}")return Falsedef list(self, scope: str) -> List[Any]:try:conn = self._get_conn()rows = conn.execute("SELECT key, value FROM kv_store WHERE scope = ?",(scope,)).fetchall()results = []for r in rows:val = json.loads(r["value"])if isinstance(val, dict) and "id" not in val:val["id"] = r["key"]results.append(val)return resultsexcept Exception as e:print(f"[db] list failed (scope={scope}): {e}")return []2 unmodified lineswith self._lock:try:conn = self._get_conn()row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key)).fetchone()obj = json.loads(row["value"]) if row else {}if not isinstance(obj, dict):obj = {}if "id" not in obj:obj["id"] = keyfor op in ops:op_type = op.get("type")path = op.get("path")val = op.get("value")if not path:continueif op_type == "set":if "." in path:parts = path.split(".")curr = objfor part in parts[:-1]:if part not in curr or not isinstance(curr[part], dict):curr[part] = {}curr = curr[part]curr[parts[-1]] = valelse:obj[path] = valelif op_type == "delete":if "." in path:parts = path.split(".")curr = objfor part in parts[:-1]:if part not in curr or not isinstance(curr[part], dict):breakcurr = curr[part]else:curr.pop(parts[-1], None)else:obj.pop(path, None)conn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(obj)))conn.commit()return objexcept Exception as e:print(f"[db] update failed (scope={scope}, key={key}): {e}")return None1 unmodified linedef commit_version(self, message: str, agent_id: str) -> Optional[str]:"""Write an audit log entry instead of a Dolt commit."""author = agent_id or "unknown-agent"with self._lock:try:conn = self._get_conn()cur = conn.execute("INSERT INTO audit_log (ts, agent_id, message) VALUES (?, ?, ?)",(int(time.time() * 1000), author, message)2 unmodified linesrow_id = str(cur.lastrowid)print(f"[audit] {author}: {message} (id={row_id})")return row_idexcept Exception as e:print(f"[audit] commit_version failed: {e}")return Nonedef get_audit_log(self, limit: int = 50) -> List[Dict[str, Any]]:try:conn = self._get_conn()rows = conn.execute("SELECT id, ts, agent_id, message FROM audit_log ORDER BY ts DESC LIMIT ?",(limit,)).fetchall()return [dict(r) for r in rows]except Exception as e:print(f"[db] get_audit_log failed: {e}")return []
4 unmodified lines567891055 unmodified lines66676869707169 unmodified lines1411421431441451461472 unmodified lines150151152153154155156157158264 unmodified lines42342442542642742842943043143243343443543643743843944044144244344444544644744844945045130 unmodified lines4824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145152216 unmodified lines2732273327342735273627372738273914 unmodified lines2754275527562757275827592760276119 unmodified lines2781278227832784278527864 unmodified lines279127922793279427952796533 unmodified lines33303331333233333334333533364 unmodified lines33413342334333443345334633473 unmodified lines3351335233533354335533563357335833593360336133623363336433653366336782 unmodified lines345034513452345334543455345634573458345934604 unmodified linesimport jsonimport hashlibimport datetimefrom typing import Dict, Any, List, Optional, Tuple, Setfrom db import StateKVfrom search import (55 unmodified lines# Graph edges — repurposed for folder graph edges.relations = "mem:relations"def get_current_project(kv: StateKV) -> Optional[str]:try:sessions = kv.list(KV.sessions)69 unmodified lines# 1. Length cap before any processing.path = path[:_MAX_PATH_LEN]# 2. OS-level normalisation (resolves .., duplicate separators, etc.)normalized = os.path.normpath(path)# 3. Unify separators to forward slash.2 unmodified lines# 4. Strip leading / trailing slashes.normalized = normalized.strip("/")# Guard: reject path traversal patterns that survive normalisation.# Split on "/" and check each component; normpath should have already# resolved most cases but we verify explicitly for safety.parts = normalized.split("/")if any(part == ".." for part in parts):raise ValueError(264 unmodified lines# =====================================================================class IndexPersistence:def __init__(self, kv: StateKV, bm25: SearchIndex, vector: Optional[VectorIndex]):self.kv = kvself.bm25 = bm25self.vector = vectordef schedule_save(self) -> None:self.save()def save(self) -> None:try:self.save_sharded_index(json.dumps(self.bm25.serialize_data()),"data:manifest","data","mem:index:bm25:bm25:")if self.vector:self.save_sharded_index(json.dumps(self.vector.serialize_data()),"vectors:manifest","vectors","mem:index:bm25:vectors:")except Exception as e:print(f"[index persistence] failed to save index: {e}")30 unmodified lines# Cleanup ALL obsolete shards starting with scope_prefix that are NOT in the current shardstry:conn = self.kv._get_conn()try:cursor = conn.cursor()try:cursor.execute("SELECT DISTINCT scope FROM kv_store WHERE scope LIKE ?",(scope_prefix + "%",))rows = cursor.fetchall()current_scopes = {s["scope"] for s in shards}to_delete = []for row in rows:scope_name = row["scope"]if scope_name not in current_scopes:to_delete.append(scope_name)if to_delete:for i in range(0, len(to_delete), 50):chunk_delete = to_delete[i:i + 50]format_strings = ','.join(['?'] * len(chunk_delete))cursor.execute(f"DELETE FROM kv_store WHERE scope IN ({format_strings})",tuple(chunk_delete))conn.commit()finally:cursor.close()finally:conn.close()except Exception as ex:print(f"[index persistence] error cleaning up obsolete shards: {ex}")2216 unmodified linesdef health_check(kv: StateKV) -> Dict[str, Any]:db_status = "connected"try:conn = kv._get_conn()conn.close()except Exception:db_status = "disconnected"14 unmodified linesunique_folders.add(fp)if aid:unique_agents.add(aid)# Use the stored obsCount in the index entry for efficiency;# fall back to 0 if missing.observation_count += int(entry.get("obsCount") or 0)folder_count = len(unique_folders)agent_count = len(unique_agents)19 unmodified linesexcept Exception:passreturn {"status": "ok" if db_status == "connected" else "degraded","folderCount": folder_count,4 unmodified lines"bm25IndexSize": bm25_index_size,"vectorIndexSize": vector_index_size,"dbPath": kv.db_path,}def strip_xml_wrappers(raw: str) -> str:533 unmodified lines# =====================================================================def folder_color(path: str) -> str:"""Hash a folder path string to an HSL hex color.Replicates the JS ``folderColor(id)`` function in src/viewer/index.htmlexactly, using the light-mode lightness range (38 + h%14).4 unmodified lineshue = (h % 360 + 360) % 360sat = 55 + (h % 25) # percent, 55-79lig = 38 + (h % 14) # percent, 38-51 (light mode)convert HSL → RGB → hex"""h = 0for ch in path:3 unmodified linessat_pct = 55 + (h % 25)lig_pct = 38 + (h % 14)# HSL → RGB conversion (same formula as in JS)s = sat_pct / 100.0l = lig_pct / 100.0a = s * min(l, 1 - l)def f(n: int) -> str:k = (n + hue / 30) % 12c = l - a * max(min(k - 3, 9 - k, 1), -1)return format(round(255 * c), '02x')return '#' + f(0) + f(8) + f(4)def folder_graph_build(kv: StateKV) -> Dict[str, Any]:82 unmodified lines# --- Build edges ---edges: List[Dict[str, Any]] = []# Deduplicate on (source, target, type)seen_edges: Set[Tuple[str, str, str]] = set()def add_edge(edge: Dict[str, Any]) -> None:key = (edge["source"], edge["target"], edge["type"])if key not in seen_edges:seen_edges.add(key)edges.append(edge)4 unmodified lines56789101155 unmodified lines6768697071727374757677787980818283848586878889909192939495969769 unmodified lines1671681691701711721731741751761771781791801811821832 unmodified lines186187188189190191192264 unmodified lines45745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953030 unmodified lines5615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905912216 unmodified lines280828092810281128122813281414 unmodified lines28292830283128322833283419 unmodified lines285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128824 unmodified lines2887288828892890289128922893289428952896533 unmodified lines34303431343234333434343534364 unmodified lines3441344234433444344534463447344834493 unmodified lines345334543455345634573458345982 unmodified lines3542354335443545354635473548354935503551355235534 unmodified linesimport jsonimport hashlibimport datetimeimport threadingfrom typing import Dict, Any, List, Optional, Tuple, Setfrom db import StateKVfrom search import (55 unmodified lines# Graph edges — repurposed for folder graph edges.relations = "mem:relations"# ---- Legacy scopes (read-only; kept for migration and backward compat) ----# Legacy session store — read by migrate_sessions_to_folders() and legacy observe().sessions = "mem:sessions"@staticmethoddef observations(session_id: str) -> str:"""Legacy per-session observations scope.Key = obs_id, value = raw/synthetic observation dict.Read by migrate_sessions_to_folders() and legacy observe()."""return f"mem:obs:{session_id}"# Lessons — confidence-scored learning entries.lessons = "mem:lessons"# Legacy summary / profile / slot / image-ref scopes retained for legacy code paths.summaries = "mem:summaries"profiles = "mem:profiles"slots = "mem:slots"imageRefs = "mem:image-refs"# Global (cross-project) pinned slots.globalSlots = "mem:global-slots"def get_current_project(kv: StateKV) -> Optional[str]:try:sessions = kv.list(KV.sessions)69 unmodified lines# 1. Length cap before any processing.path = path[:_MAX_PATH_LEN]# Pre-normalisation traversal check: reject any path that contains a ".."# component in the raw input before normpath has a chance to resolve it.# This catches inputs like "/home/user/../../etc/passwd" which normpath# would silently resolve to "etc/passwd" (REQ-064).raw_parts = path.replace("\\", "/").split("/")if any(part == ".." for part in raw_parts):raise ValueError(f"folder_path contains path traversal segment '..': {path!r}")# 2. OS-level normalisation (resolves duplicate separators, etc.)normalized = os.path.normpath(path)# 3. Unify separators to forward slash.2 unmodified lines# 4. Strip leading / trailing slashes.normalized = normalized.strip("/")# Guard: also reject any ".." that somehow survives normalisation.parts = normalized.split("/")if any(part == ".." for part in parts):raise ValueError(264 unmodified lines# =====================================================================class IndexPersistence:"""Persist BM25 and vector indexes to the KV store with a debounce queue.A4.1: schedule_save() uses a threading.Timer that resets on each call andfires the actual save() after DEBOUNCE_SECONDS of inactivity. This preventsa persistence write on every single observation under high throughput.A4.2: save() skips writing an index that has not been dirtied since the lastsave (relies on SearchIndex._dirty / VectorIndex._dirty flags)."""DEBOUNCE_SECONDS: float = 5.0def __init__(self, kv: StateKV, bm25: SearchIndex, vector: Optional[VectorIndex]):self.kv = kvself.bm25 = bm25self.vector = vectorself._timer: Optional[threading.Timer] = Noneself._timer_lock = threading.Lock()def schedule_save(self) -> None:"""Schedule a debounced save — resets the 5-second timer on each call."""with self._timer_lock:if self._timer is not None:self._timer.cancel()self._timer = threading.Timer(self.DEBOUNCE_SECONDS, self._fire_save)self._timer.daemon = Trueself._timer.start()def _fire_save(self) -> None:"""Called by the timer after DEBOUNCE_SECONDS of inactivity."""with self._timer_lock:self._timer = Noneself.save()def flush(self) -> None:"""Cancel any pending debounce timer and save immediately (used on shutdown)."""with self._timer_lock:if self._timer is not None:self._timer.cancel()self._timer = Noneself.save()def save(self) -> None:try:# A4.2: skip save if neither index is dirtybm25_dirty = getattr(self.bm25, "_dirty", True)vector_dirty = self.vector and getattr(self.vector, "_dirty", True)if bm25_dirty:self.save_sharded_index(json.dumps(self.bm25.serialize_data()),"data:manifest","data","mem:index:bm25:bm25:")self.bm25._dirty = False # A4.2 — reset after saveif self.vector and vector_dirty:self.save_sharded_index(json.dumps(self.vector.serialize_data()),"vectors:manifest","vectors","mem:index:bm25:vectors:")self.vector._dirty = False # A4.2 — reset after saveif not bm25_dirty and not vector_dirty:print("[index persistence] indexes not dirty — skipping save")except Exception as e:print(f"[index persistence] failed to save index: {e}")30 unmodified lines# Cleanup ALL obsolete shards starting with scope_prefix that are NOT in the current shardstry:conn = self.kv._get_conn()cursor = conn.cursor()try:cursor.execute("SELECT DISTINCT scope FROM kv_store WHERE scope LIKE ?",(scope_prefix + "%",))rows = cursor.fetchall()current_scopes = {s["scope"] for s in shards}to_delete = []for row in rows:scope_name = row["scope"]if scope_name not in current_scopes:to_delete.append(scope_name)if to_delete:for i in range(0, len(to_delete), 50):chunk_delete = to_delete[i:i + 50]format_strings = ','.join(['?'] * len(chunk_delete))cursor.execute(f"DELETE FROM kv_store WHERE scope IN ({format_strings})",tuple(chunk_delete))conn.commit()finally:cursor.close()except Exception as ex:print(f"[index persistence] error cleaning up obsolete shards: {ex}")2216 unmodified linesdef health_check(kv: StateKV) -> Dict[str, Any]:db_status = "connected"try:kv._get_conn() # connection stays open per-thread (A3.1)except Exception:db_status = "disconnected"14 unmodified linesunique_folders.add(fp)if aid:unique_agents.add(aid)observation_count += int(entry.get("obsCount") or 0)folder_count = len(unique_folders)agent_count = len(unique_agents)19 unmodified linesexcept Exception:pass# C4.2: Read sync state written by sync.pysync_status = "never"last_sync_at = Nonedb_size_bytes = 0wal_size_bytes = 0try:sync_state_path = os.path.join(os.path.expanduser("~"), ".agentmemory", ".sync_state")if os.path.exists(sync_state_path):with open(sync_state_path, "r", encoding="utf-8") as _sf:_sync = json.loads(_sf.read())sync_status = _sync.get("sync_status", "never")last_sync_at = _sync.get("last_sync_at")except Exception:pass# A3.3: DB file sizestry:db_stats = kv.stats()db_size_bytes = db_stats.get("db_size_bytes", 0)wal_size_bytes = db_stats.get("wal_size_bytes", 0)except Exception:passreturn {"status": "ok" if db_status == "connected" else "degraded","folderCount": folder_count,4 unmodified lines"bm25IndexSize": bm25_index_size,"vectorIndexSize": vector_index_size,"dbPath": kv.db_path,"dbSizeBytes": db_size_bytes,"walSizeBytes": wal_size_bytes,"syncStatus": sync_status,"lastSyncAt": last_sync_at,}def strip_xml_wrappers(raw: str) -> str:533 unmodified lines# =====================================================================def folder_color(path: str) -> str:"""Hash a folder path string to an HSL color string.Replicates the JS ``folderColor(id)`` function in src/viewer/index.htmlexactly, using the light-mode lightness range (38 + h%14).4 unmodified lineshue = (h % 360 + 360) % 360sat = 55 + (h % 25) # percent, 55-79lig = 38 + (h % 14) # percent, 38-51 (light mode)Returns:A CSS ``hsl(hue, sat%, lig%)`` string."""h = 0for ch in path:3 unmodified linessat_pct = 55 + (h % 25)lig_pct = 38 + (h % 14)return f"hsl({hue}, {sat_pct}%, {lig_pct}%)"def folder_graph_build(kv: StateKV) -> Dict[str, Any]:82 unmodified lines# --- Build edges ---edges: List[Dict[str, Any]] = []# Deduplicate on (frozenset(source, target), type) so that (A,B) and (B,A)# are treated as the same edge (REQ-028).seen_edges: Set[Tuple[Any, str]] = set()def add_edge(edge: Dict[str, Any]) -> None:key = (frozenset([edge["source"], edge["target"]]), edge["type"])if key not in seen_edges:seen_edges.add(key)edges.append(edge)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531629 unmodified lines34634734834935035135235335435535635735835936036136236336421 unmodified lines386387388389390#!/usr/bin/env python3"""stdio MCP wrapper — bridges Claude Code's MCP stdio protocol to theagentmemory Flask HTTP API running on localhost.Usage: python mcp_stdio.py"""import sysimport jsonimport requestsimport osBASE = os.getenv("AGENTMEMORY_URL", "http://127.0.0.1:3111").rstrip("/")if not BASE.endswith("/agentmemory"):BASE = f"{BASE}/agentmemory"_secret = os.getenv("AGENTMEMORY_SECRET")def headers():h = {"Content-Type": "application/json"}if _secret:h["Authorization"] = f"Bearer {_secret}"return hdef send(msg):line = json.dumps(msg, separators=(",", ":"))sys.stdout.write(line + "\n")sys.stdout.flush()def perform_antigravity_sync_local(args):import osimport jsonimport globimport reimport requestsmode = args.get("mode") or "current_session"current_conversation_id = args.get("currentConversationId")current_folder = args.get("currentFolder")brain_dir = os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "brain")if not os.path.exists(brain_dir):return {"content": [{"type": "text", "text": json.dumps({"success": False,"syncedSessions": [],"observationsAdded": 0,"error": f"Brain directory not found at {brain_dir}"})}]}pattern = os.path.join(brain_dir, "*", ".system_generated", "logs", "transcript.jsonl")files = glob.glob(pattern)if not files:return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": [],"observationsAdded": 0})}]}conversations = []for fpath in files:try:mtime = os.path.getmtime(fpath)convo_id = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(fpath))))conversations.append({"id": convo_id,"transcriptPath": fpath,"mtime": mtime})except Exception:passif not conversations:return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": [],"observationsAdded": 0})}]}conversations.sort(key=lambda x: x["mtime"], reverse=True)targets = []if mode == "current_session":if current_conversation_id:match = next((c for c in conversations if c["id"] == current_conversation_id), None)if match:targets = [match]else:targets = [conversations[0]]elif mode == "current_folder":target_folder = current_folder if current_folder else ""if not target_folder:target_folder = os.getcwd()target_folder_norm = target_folder.replace("\\", "/").lower().strip()for convo in conversations:try:with open(convo["transcriptPath"], "r", encoding="utf-8") as tf:text = tf.read().lower()text_norm = text.replace("\\/", "/").replace("\\\\", "/")if target_folder_norm in text_norm:targets.append(convo)except Exception:passelif mode == "all":targets = conversationselse:return {"content": [{"type": "text", "text": json.dumps({"success": False,"syncedSessions": [],"observationsAdded": 0,"error": f"Invalid mode: {mode}"})}]}if not targets:return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": [],"observationsAdded": 0})}]}synced_sessions = []observations_added = 0headers_dict = headers()for convo in targets:convo_id = convo["id"]tpath = convo["transcriptPath"]session_id = f"antigravity_{convo_id[:18].replace('-', '_')}"project_path = Nonetry:with open(tpath, "r", encoding="utf-8") as tf:first_line = tf.readline()if first_line:step = json.loads(first_line)match = re.search(r"\[([^\]]+)\]\s*->\s*\[([^\]]+)\]", step.get("content", ""))if match:project_path = match.group(2)except Exception:passif not project_path:project_path = os.getcwd()turns = []current_prompt = Nonecurrent_timestamp = Nonetry:with open(tpath, "r", encoding="utf-8") as tf:for line in tf:if not line.strip():continuetry:step = json.loads(line)step_type = step.get("type")if step_type == "USER_INPUT":p_text = step.get("content", "")if "<USER_REQUEST>" in p_text:parts = p_text.split("<USER_REQUEST>")if len(parts) > 1:p_text = parts[1]if "</USER_REQUEST>" in p_text:p_text = p_text.split("</USER_REQUEST>")[0]current_prompt = p_text.strip()current_timestamp = step.get("created_at")elif step_type == "PLANNER_RESPONSE" and current_prompt:ts = current_timestamp or step.get("created_at")if not ts:import datetimets = datetime.datetime.utcnow().isoformat() + "Z"turns.append({"prompt": current_prompt,"response": step.get("content", ""),"timestamp": ts})current_prompt = Nonecurrent_timestamp = Noneexcept Exception:passexcept Exception:continueif not turns:continueexisting_inputs = set()try:r = requests.get(f"{BASE}/observations?sessionId={session_id}", headers=headers_dict, timeout=10)if r.status_code == 200:obs_list = r.json().get("observations", [])for obs in obs_list:tool_input = obs.get("toolInput") or (obs.get("raw") or {}).get("tool_input")if tool_input:existing_inputs.add(tool_input.strip())except Exception:passtry:sess_check = requests.get(f"{BASE}/sessions", headers=headers_dict, timeout=5)session_exists = Falseif sess_check.status_code == 200:sessions_list = sess_check.json().get("sessions", [])session_exists = any(s.get("id") == session_id for s in sessions_list)if not session_exists:session_payload = {"sessionId": session_id,"project": project_path,"cwd": project_path,"title": f"Antigravity Pair Programming ({convo_id[:8]})","agentId": "antigravity"}requests.post(f"{BASE}/session/start", headers=headers_dict, json=session_payload, timeout=10)except Exception:passconvo_synced = Falsefor turn in turns:prompt = turn["prompt"]if prompt.strip() in existing_inputs:continuepayload = {"sessionId": session_id,"project": project_path,"cwd": project_path,"hookType": "post_tool_use","timestamp": turn["timestamp"],"agentId": "antigravity","data": {"tool_name": "conversation","tool_input": prompt,"tool_output": turn["response"],}}try:requests.post(f"{BASE}/observe", headers=headers_dict, json=payload, timeout=10)observations_added += 1convo_synced = Trueexcept Exception:passif convo_synced:synced_sessions.append(convo_id)return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": synced_sessions,"observationsAdded": observations_added})}]}def perform_antigravity_sync_all_local(args):sync_res_outer = perform_antigravity_sync_local(args)try:sync_res = json.loads(sync_res_outer["content"][0]["text"])except Exception as ex:return sync_res_outerif not sync_res.get("success"):return sync_res_outersynced_sessions = sync_res.get("syncedSessions") or []crystallizations = {}reflections = {}headers_dict = headers()for cid in synced_sessions:session_id = f"antigravity_{cid[:18].replace('-', '_')}"try:r_sum = requests.post(f"{BASE}/summarize", headers=headers_dict, json={"sessionId": session_id}, timeout=30)if r_sum.status_code == 200:crystallizations[session_id] = r_sum.json()else:crystallizations[session_id] = {"success": False, "status_code": r_sum.status_code, "error": r_sum.text}except Exception as e:crystallizations[session_id] = {"success": False, "error": str(e)}try:r_ref = requests.post(f"{BASE}/slot/reflect", headers=headers_dict, json={"sessionId": session_id, "maxObservations": 50}, timeout=30)if r_ref.status_code == 200:reflections[session_id] = r_ref.json()else:reflections[session_id] = {"success": False, "status_code": r_ref.status_code, "error": r_ref.text}except Exception as e:reflections[session_id] = {"success": False, "error": str(e)}return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": synced_sessions,"observationsAdded": sync_res.get("observationsAdded", 0),"crystallizations": crystallizations,"reflections": reflections}, indent=2)}]}def handle(req):method = req.get("method", "")29 unmodified linesname = params.get("name")args = params.get("arguments") or {}try:if name == "memory_antigravity_sync":result = perform_antigravity_sync_local(args)elif name == "memory_antigravity_sync_all":result = perform_antigravity_sync_all_local(args)else:r = requests.post(f"{BASE}/mcp/tools",headers=headers(),json={"name": name, "arguments": args},timeout=30)result = r.json()# MCP expects content arrayif "content" not in result:result = {"content": [{"type": "text", "text": json.dumps(result)}]}send({"jsonrpc": "2.0", "id": req_id, "result": result})except Exception as e:send({"jsonrpc": "2.0", "id": req_id,21 unmodified linessend({"jsonrpc": "2.0", "id": req_id,"error": {"code": -32603, "message": f"Internal error: {e}"}})if __name__ == "__main__":main()1234567891011121314151617181920212223242526272829303132333435363729 unmodified lines6768697071727374757677787980818221 unmodified lines104105106107108109#!/usr/bin/env python3"""stdio MCP wrapper — bridges the MCP stdio protocol to theagentmemory Flask HTTP API running on localhost.Usage: python mcp_stdio.pyAntigravity sync functions have been moved to examples/antigravity_sync.py (D1.3).All tool calls are proxied to the HTTP API."""import sysimport jsonimport osimport requestsBASE = os.getenv("AGENTMEMORY_URL", "http://127.0.0.1:3111").rstrip("/")if not BASE.endswith("/agentmemory"):BASE = f"{BASE}/agentmemory"_secret = os.getenv("AGENTMEMORY_SECRET")def headers():h = {"Content-Type": "application/json"}if _secret:h["Authorization"] = f"Bearer {_secret}"return hdef send(msg):line = json.dumps(msg, separators=(",", ":"))sys.stdout.write(line + "\n")sys.stdout.flush()def handle(req):method = req.get("method", "")29 unmodified linesname = params.get("name")args = params.get("arguments") or {}try:r = requests.post(f"{BASE}/mcp/tools",headers=headers(),json={"name": name, "arguments": args},timeout=30,)result = r.json()# MCP expects content arrayif "content" not in result:result = {"content": [{"type": "text", "text": json.dumps(result)}]}send({"jsonrpc": "2.0", "id": req_id, "result": result})except Exception as e:send({"jsonrpc": "2.0", "id": req_id,21 unmodified linessend({"jsonrpc": "2.0", "id": req_id,"error": {"code": -32603, "message": f"Internal error: {e}"}})if __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""src/memory/ — Core business logic package for agentmemory-python.
Sub-modules: observe — folder_observe(), observe(), build_synthetic_compression(), strip_private_data() remember — remember(), forget(), jaccard_similarity() context — context(), export_data(), rebuild_index() graph — folder_graph_build(), get_relations(), add_relation() timeline — folder_timeline(), folder_search() health — health_check(), auto_forget()
Compatibility shim: also re-exports everything from functions.py thatcallers may import from this package (A2.2)."""
from .observe import folder_observe, observe, build_synthetic_compression, strip_private_datafrom .remember import remember, forget, jaccard_similarityfrom .context import context, export_data, rebuild_indexfrom .graph import folder_graph_buildfrom .timeline import folder_timeline, folder_searchfrom .health import health_check, auto_forget
# ---------------------------------------------------------------------------# Compatibility shim — delegate additional names to functions.py (A2.2)# Each name is imported lazily via a try/except so missing items don't break# the package import on partially-initialised environments.# ---------------------------------------------------------------------------import functions as _fn # noqa: E402 (functions.py is on sys.path via src/)
KV = _fn.KVgenerate_id = _fn.generate_idfingerprint_id = _fn.fingerprint_idnormalize_folder_path = _fn.normalize_folder_pathvalidate_agent_id = _fn.validate_agent_idIndexPersistence = _fn.IndexPersistenceset_embedding_provider = _fn.set_embedding_providerset_index_persistence = _fn.set_index_persistenceset_stream_broadcaster = _fn.set_stream_broadcasterget_agent_id = _fn.get_agent_idrecord_audit = _fn.record_auditquery_audit = _fn.query_auditsafe_audit = _fn.safe_auditlesson_save = _fn.lesson_savelesson_list = _fn.lesson_listlesson_recall = _fn.lesson_recallmigrate_sessions_to_folders = _fn.migrate_sessions_to_folderslist_sessions = _fn.list_sessions
__all__ = [ # observe.py "folder_observe", "observe", "build_synthetic_compression", "strip_private_data", # remember.py "remember", "forget", "jaccard_similarity", # context.py "context", "export_data", "rebuild_index", # graph.py "folder_graph_build", # timeline.py "folder_timeline", "folder_search", # health.py "health_check", "auto_forget", # functions.py shims (A2.2) "KV", "generate_id", "fingerprint_id", "normalize_folder_path", "validate_agent_id", "IndexPersistence", "set_embedding_provider", "set_index_persistence", "set_stream_broadcaster", "get_agent_id", "record_audit", "query_audit", "safe_audit", "lesson_save", "lesson_list", "lesson_recall", "migrate_sessions_to_folders", "list_sessions",]123456789101112131415161718192021222324252627282930"""src/memory/context.py — Context compilation, export, and index rebuilding.
Public API: context(kv, data) — compile token-budgeted context for a session/project export_data(kv, data) — export all folder observations + memories as JSON rebuild_index(kv) — cold-rebuild BM25/vector index from KV store"""
from __future__ import annotations
from typing import Any, Dict
from db import StateKVimport functions as _fn
def context(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: """Assemble context for a session: slots → profile → lessons → past summaries.""" return _fn.context(kv, data)
def export_data(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: """Export all folder observations and global memories as JSON (v2 format).""" return _fn.export_data(kv, data)
def rebuild_index(kv: StateKV) -> int: """Rebuild BM25/vector index from all KV observations and memories.""" return _fn.rebuild_index(kv)123456789101112131415161718"""src/memory/graph.py — Knowledge graph construction.
Public API: folder_graph_build(kv) — build graph nodes+edges from folder observations"""
from __future__ import annotations
from typing import Any, Dict
from db import StateKVimport functions as _fn
def folder_graph_build(kv: StateKV) -> Dict[str, Any]: """Build a folder-based knowledge graph with nodes, edges, and color assignments.""" return _fn.folder_graph_build(kv)123456789101112131415161718192021222324"""src/memory/health.py — Health check and auto-forget sweep.
Public API: health_check(kv) — return system health stats auto_forget(kv, ...) — evict stale/low-importance observations"""
from __future__ import annotations
from typing import Any, Dict
from db import StateKVimport functions as _fn
def health_check(kv: StateKV) -> Dict[str, Any]: """Return folder count, observation count, memory count, and subsystem status.""" return _fn.health_check(kv)
def auto_forget(kv: StateKV, dry_run: bool = False) -> Dict[str, Any]: """Sweep and evict stale or low-importance observations.""" return _fn.auto_forget(kv, dry_run=dry_run)1234567891011121314151617181920212223242526272829303132333435"""src/memory/observe.py — Observation ingestion pipeline.
Public API: folder_observe(kv, payload) — ingest a folder-scoped observation observe(kv, payload) — legacy session-scoped observation build_synthetic_compression(raw) — build compressed observation dict strip_private_data(text) — redact secrets and private tags"""
from __future__ import annotations
import osimport reimport jsonimport datetimefrom typing import Any, Dict, List, Optional, Tuple
from db import StateKVimport functions as _fn # access module-level globals (_bm25_index, etc.)
# Re-export for backward compatibilitystrip_private_data = _fn.strip_private_databuild_synthetic_compression = _fn.build_synthetic_compression
def folder_observe(kv: StateKV, payload: Dict[str, Any]) -> Dict[str, Any]: """Ingest a new observation scoped to a (folder_path, agent_id) pair.""" return _fn.folder_observe(kv, payload)
def observe(kv: StateKV, payload: Dict[str, Any]) -> Dict[str, Any]: """Legacy session-scoped observation ingestion.""" return _fn.observe(kv, payload)123456789101112131415161718192021222324252627282930"""src/memory/remember.py — Long-term memory management.
Public API: remember(kv, data) — save/update a global memory (versioned by Jaccard sim) forget(kv, data) — delete memory/folder-pair/observations jaccard_similarity(a, b) — word-set overlap ratio"""
from __future__ import annotations
from typing import Any, Dict
from db import StateKVimport functions as _fn
def remember(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: """Save a global memory, superseding any existing memory with > 0.7 similarity.""" return _fn.remember(kv, data)
def forget(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: """Delete a global memory, a folder pair, or specific observations.""" return _fn.forget(kv, data)
def jaccard_similarity(a: str, b: str) -> float: """Compute Jaccard similarity between two strings (word sets, min length 3).""" return _fn.jaccard_similarity(a, b)12345678910111213141516171819202122232425262728293031323334353637"""src/memory/timeline.py — Folder activity timeline and search.
Public API: folder_timeline(kv, limit, folder_path, agent_id, before, after) folder_search(kv, query, limit, folder_path, agent_id)"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from db import StateKVimport functions as _fn
def folder_timeline( kv: StateKV, limit: int = 100, folder_path: Optional[str] = None, agent_id: Optional[str] = None, before: Optional[str] = None, after: Optional[str] = None,) -> List[Dict[str, Any]]: """Return folder observations sorted newest-first with optional filters.""" return _fn.folder_timeline(kv, limit, folder_path, agent_id, before, after)
def folder_search( kv: StateKV, query: str, limit: int = 20, folder_path: Optional[str] = None, agent_id: Optional[str] = None,) -> List[Dict[str, Any]]: """BM25 + vector hybrid search across folder observations and global memories.""" return _fn.folder_search(kv, query, limit, folder_path=folder_path, agent_id=agent_id)123456789101112131415161718192021222324"""Flask blueprints for agentmemory-python.
Import and register all blueprints via register_blueprints(app)."""
from .observations import observations_bpfrom .memories import memories_bpfrom .search import search_bpfrom .graph import graph_bpfrom .health import health_bpfrom .mcp import mcp_bpfrom .migration import migration_bp
def register_blueprints(app): """Register all route blueprints on a Flask application instance.""" app.register_blueprint(observations_bp) app.register_blueprint(memories_bp) app.register_blueprint(search_bp) app.register_blueprint(graph_bp) app.register_blueprint(health_bp) app.register_blueprint(mcp_bp) app.register_blueprint(migration_bp)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""Graph routes blueprint.
Handles: GET /agentmemory/graph GET /agentmemory/graph/stats POST /agentmemory/graph/query POST /agentmemory/graph/build"""
import osfrom flask import Blueprint, request, jsonifyimport functionsfrom functions import KV
graph_bp = Blueprint("graph", __name__)
def _check_auth(): import hmac secret = os.getenv("AGENTMEMORY_SECRET") if not secret: return None auth = request.headers.get("Authorization") or request.headers.get("authorization") if not auth or not auth.startswith("Bearer "): return jsonify({"error": "unauthorized"}), 401 provided_token = auth[7:].strip() if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")): return jsonify({"error": "unauthorized"}), 401 return None
def _get_kv(): import app as app_module return app_module.kv
# ---------------------------------------------------------------------------# GET /agentmemory/graph# ---------------------------------------------------------------------------
@graph_bp.route("/agentmemory/graph", methods=["GET"])def api_graph(): auth_err = _check_auth() if auth_err: return auth_err result = functions.folder_graph_build(_get_kv()) return jsonify(result), 200
# ---------------------------------------------------------------------------# GET /agentmemory/graph/stats# ---------------------------------------------------------------------------
@graph_bp.route("/agentmemory/graph/stats", methods=["GET"])def api_graph_stats(): auth_err = _check_auth() if auth_err: return auth_err
kv = _get_kv() sessions = functions.list_sessions(kv) memories = kv.list(KV.memories)
folders = set() concepts_by_folder = {}
for s in sessions: project = s.get("project", "").strip() if project: folders.add(project)
for m in memories: project = m.get("project", "").strip() if project: folders.add(project) concepts = m.get("concepts", []) if concepts: if project not in concepts_by_folder: concepts_by_folder[project] = set() for c in concepts: if isinstance(c, str): concepts_by_folder[project].add(c.lower())
node_count = len(folders) edge_count = 0 folder_list = list(folders)
for i in range(len(folder_list)): for j in range(i + 1, len(folder_list)): f1 = folder_list[i] f2 = folder_list[j]
c1 = concepts_by_folder.get(f1, set()) c2 = concepts_by_folder.get(f2, set()) shared = c1.intersection(c2)
p1 = [p for p in f1.replace("\\", "/").split("/") if p] p2 = [p for p in f2.replace("\\", "/").split("/") if p] common_subdirs = 0 for k in range(min(len(p1), len(p2))): if p1[k].lower() == p2[k].lower(): p_low = p1[k].lower() if p_low not in ("c:", "d:", "downloads", "projects", "other projects"): common_subdirs += 1 else: break
if len(shared) > 0 or common_subdirs > 0: edge_count += 1
return jsonify({"nodes": node_count, "edges": edge_count, "success": True}), 200
# ---------------------------------------------------------------------------# POST /agentmemory/graph/query# ---------------------------------------------------------------------------
@graph_bp.route("/agentmemory/graph/query", methods=["POST"])def api_graph_query(): auth_err = _check_auth() if auth_err: return auth_err try: body = request.get_json(force=True) or {} # start_node_id = body.get("startNodeId") # reserved for future use return jsonify({"nodes": [], "edges": [], "success": True}), 200 except Exception as e: return jsonify({"error": str(e)}), 400
# ---------------------------------------------------------------------------# POST /agentmemory/graph/build# ---------------------------------------------------------------------------
@graph_bp.route("/agentmemory/graph/build", methods=["POST"])def api_graph_build(): auth_err = _check_auth() if auth_err: return auth_err try: if functions.is_consolidation_enabled(): functions.consolidate(_get_kv()) return jsonify({"success": True}), 200 except Exception as e: return jsonify({"error": str(e)}), 400123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Health and audit routes blueprint.
Handles: GET /agentmemory/livez GET /agentmemory/health GET /agentmemory/audit GET /agentmemory/config/flags"""
import osfrom flask import Blueprint, request, jsonifyimport functionsfrom functions import query_audit
health_bp = Blueprint("health", __name__)
def _check_auth(): import hmac secret = os.getenv("AGENTMEMORY_SECRET") if not secret: return None auth = request.headers.get("Authorization") or request.headers.get("authorization") if not auth or not auth.startswith("Bearer "): return jsonify({"error": "unauthorized"}), 401 provided_token = auth[7:].strip() if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")): return jsonify({"error": "unauthorized"}), 401 return None
def _get_kv(): import app as app_module return app_module.kv
def _get_embedding_provider(): import app as app_module return app_module.embedding_provider
# ---------------------------------------------------------------------------# GET /agentmemory/livez (no auth required)# ---------------------------------------------------------------------------
@health_bp.route("/agentmemory/livez", methods=["GET"])def livez(): port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111"))) return jsonify({ "status": "ok", "service": "agentmemory", "viewerPort": port, "viewerSkipped": False, })
# ---------------------------------------------------------------------------# GET /agentmemory/health# ---------------------------------------------------------------------------
@health_bp.route("/agentmemory/health", methods=["GET"])def health(): return jsonify(functions.health_check(_get_kv()))
# ---------------------------------------------------------------------------# GET /agentmemory/audit# ---------------------------------------------------------------------------
@health_bp.route("/agentmemory/audit", methods=["GET"])def api_audit(): auth_err = _check_auth() if auth_err: return auth_err
op = request.args.get("operation") limit = int(request.args.get("limit", "50")) res = query_audit(_get_kv(), {"operation": op, "limit": limit}) return jsonify({"entries": res, "success": True}), 200
# ---------------------------------------------------------------------------# GET /agentmemory/config/flags# ---------------------------------------------------------------------------
@health_bp.route("/agentmemory/config/flags", methods=["GET"])def config_flags(): auth_err = _check_auth() if auth_err: return auth_err
embedding_provider = _get_embedding_provider() provider_kind = "llm" if embedding_provider else "noop" embedding_prov = "gemini" if embedding_provider else "none"
flags = [ { "key": "GRAPH_EXTRACTION_ENABLED", "label": "Knowledge graph extraction", "enabled": functions.is_graph_extraction_enabled(), "default": False, "affects": ["Graph", "Dashboard"], "needsLlm": True, "description": "Extracts entities and relations from observations into a knowledge graph.", "enableHow": "Set GRAPH_EXTRACTION_ENABLED=true and restart.", "docsHref": "https://github.com/rohitg00/agentmemory#knowledge-graph", }, { "key": "CONSOLIDATION_ENABLED", "label": "Memory consolidation", "enabled": functions.is_consolidation_enabled(), "default": False, "affects": ["Dashboard", "Memories", "Crystals"], "needsLlm": True, "description": "Periodically summarizes sessions into semantic facts + procedures.", "enableHow": "Set CONSOLIDATION_ENABLED=true and restart.", "docsHref": "https://github.com/rohitg00/agentmemory#consolidation", }, { "key": "AGENTMEMORY_AUTO_COMPRESS", "label": "LLM-powered observation compression", "enabled": functions.is_auto_compress_enabled(), "default": False, "affects": ["Memories", "Timeline"], "needsLlm": True, "description": "Every observation is compressed by the LLM for richer summaries. OFF uses synthetic compression.", "enableHow": "Set AGENTMEMORY_AUTO_COMPRESS=true.", "docsHref": "https://github.com/rohitg00/agentmemory/issues/138", }, ] return jsonify({ "version": "0.9.8", "provider": provider_kind, "embeddingProvider": embedding_prov, "flags": flags, })123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371"""MCP (Model Context Protocol) routes blueprint.
Handles: GET /agentmemory/mcp/tools — list all MCP tool schemas POST /agentmemory/mcp/tools — dispatch a tool call"""
import osimport jsonimport datetimefrom flask import Blueprint, request, jsonifyimport functionsfrom functions import KV
mcp_bp = Blueprint("mcp", __name__)
def _check_auth(): import hmac secret = os.getenv("AGENTMEMORY_SECRET") if not secret: return None auth = request.headers.get("Authorization") or request.headers.get("authorization") if not auth or not auth.startswith("Bearer "): return jsonify({"error": "unauthorized"}), 401 provided_token = auth[7:].strip() if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")): return jsonify({"error": "unauthorized"}), 401 return None
def _get_kv(): import app as app_module return app_module.kv
def _datetime_now_iso() -> str: return datetime.datetime.utcnow().isoformat() + "Z"
def _parse_mcp_list_arg(arg_val): """Accept a list or comma-separated string and return a list of strings.""" if isinstance(arg_val, list): return [str(item).strip() for item in arg_val if item] if isinstance(arg_val, str) and arg_val: return [item.strip() for item in arg_val.split(",") if item.strip()] return []
# ---------------------------------------------------------------------------# GET /agentmemory/mcp/tools# ---------------------------------------------------------------------------
@mcp_bp.route("/agentmemory/mcp/tools", methods=["GET"])def mcp_tools_list(): auth_err = _check_auth() if auth_err: return auth_err
tools = [ { "name": "memory_recall", "description": "Search past folder observations and global memories. Use when you need to recall what happened in a folder.", "inputSchema": { "type": "object", "properties": { "query": {"type": "string", "description": "Search query keywords"}, "limit": {"type": "number", "description": "Max results to return (default 10)"}, "folderPath": {"type": "string", "description": "Filter to a specific folder path (optional)"}, "agentId": {"type": "string", "description": "Filter to a specific agent ID (optional)"}, }, "required": ["query"], }, }, { "name": "memory_smart_search", "description": "Hybrid semantic+keyword search across folder observations and global memories.", "inputSchema": { "type": "object", "properties": { "query": {"type": "string", "description": "Search query"}, "limit": {"type": "number", "description": "Max results (default 10)"}, "folderPath": {"type": "string", "description": "Filter to a specific folder path (optional)"}, "agentId": {"type": "string", "description": "Filter to a specific agent ID (optional)"}, }, "required": ["query"], }, }, { "name": "memory_save", "description": "Explicitly save an important insight, decision, or pattern to long-term memory.", "inputSchema": { "type": "object", "properties": { "content": {"type": "string", "description": "The insight or decision to remember"}, "type": {"type": "string", "description": "Memory type: pattern, preference, architecture, bug, workflow, or fact"}, "concepts": { "oneOf": [ {"type": "string", "description": "Comma-separated key concepts"}, {"type": "array", "items": {"type": "string"}, "description": "List of key concepts"}, ] }, "files": { "oneOf": [ {"type": "string", "description": "Comma-separated relevant file paths"}, {"type": "array", "items": {"type": "string"}, "description": "List of relevant file paths"}, ] }, "project": {"type": "string", "description": "Canonical project identifier"}, }, "required": ["content"], }, }, { "name": "memory_diagnose", "description": "Health check — returns folder, agent, observation and memory counts.", "inputSchema": {"type": "object", "properties": {}}, }, { "name": "memory_forget", "description": "Delete a global memory or all observations for a (folderPath, agentId) pair.", "inputSchema": { "type": "object", "properties": { "memoryId": {"type": "string", "description": "Memory ID to delete"}, "folderPath": {"type": "string", "description": "Folder path to delete observations from"}, "agentId": {"type": "string", "description": "Agent ID to delete observations for"}, "observationIds": { "oneOf": [ {"type": "string", "description": "Comma-separated observation IDs to delete"}, {"type": "array", "items": {"type": "string"}}, ] }, }, }, }, { "name": "memory_export", "description": "Export all folder observations and global memories as JSON (v2 format).", "inputSchema": {"type": "object", "properties": {}}, }, { "name": "agent_observe", "description": "Log an observation scoped to a folder path and agent ID.", "inputSchema": { "type": "object", "properties": { "folderPath": {"type": "string", "description": "Absolute path of the working directory"}, "agentId": {"type": "string", "description": "Identity of the agent (e.g. 'kiro', 'claude')"}, "text": {"type": "string", "description": "Observation content"}, "timestamp": {"type": "string", "description": "ISO 8601 UTC timestamp (defaults to now)"}, "type": {"type": "string", "description": "Observation type"}, "title": {"type": "string", "description": "Short title"}, "concepts": {"type": "array", "items": {"type": "string"}}, "files": {"type": "array", "items": {"type": "string"}}, "importance": {"type": "integer", "description": "1-10"}, "sessionId": {"type": "string", "description": "Deprecated — ignored"}, }, "required": ["folderPath", "agentId", "text"], }, }, { "name": "agent_remember", "description": "Explicitly save a key insight, fact, or architecture decision to long-term memory.", "inputSchema": { "type": "object", "properties": { "agentId": {"type": "string", "description": "ID/Name of the agent (optional)"}, "content": {"type": "string", "description": "The memory content/insight"}, "project": {"type": "string", "description": "Canonical project path/identifier"}, "type": {"type": "string", "description": "Memory type: fact, preference, bug, workflow, architecture"}, "concepts": { "oneOf": [ {"type": "string", "description": "Comma-separated key concepts"}, {"type": "array", "items": {"type": "string"}}, ] }, "files": { "oneOf": [ {"type": "string", "description": "Comma-separated relevant file paths"}, {"type": "array", "items": {"type": "string"}}, ] }, }, "required": ["content"], }, }, { "name": "memory_folders", "description": "List all (folder, agent) pairs that have memory observations.", "inputSchema": {"type": "object", "properties": {}}, }, { "name": "memory_folder_observations", "description": "Get all observations for a specific (folderPath, agentId) pair.", "inputSchema": { "type": "object", "properties": { "folderPath": {"type": "string", "description": "Folder path"}, "agentId": {"type": "string", "description": "Agent ID"}, }, "required": ["folderPath", "agentId"], }, }, { "name": "memory_timeline", "description": "Get folder activity feed — observations sorted by time, filterable by folder/agent.", "inputSchema": { "type": "object", "properties": { "folderPath": {"type": "string", "description": "Filter by folder path (optional)"}, "agentId": {"type": "string", "description": "Filter by agent ID (optional)"}, "limit": {"type": "integer", "description": "Max results (default 100)"}, "before": {"type": "string", "description": "ISO timestamp upper bound (optional)"}, "after": {"type": "string", "description": "ISO timestamp lower bound (optional)"}, }, }, }, ] return jsonify({"tools": tools}), 200
# ---------------------------------------------------------------------------# POST /agentmemory/mcp/tools# ---------------------------------------------------------------------------
@mcp_bp.route("/agentmemory/mcp/tools", methods=["POST"])def mcp_tools_call(): auth_err = _check_auth() if auth_err: return auth_err
try: kv = _get_kv() body = request.get_json(force=True) or {} name = body.get("name") args = body.get("arguments") or {} if not name: return jsonify({"error": "name is required"}), 400
print(f"[mcp] Calling tool {name} with args: {args}") text_out = ""
if name == "memory_recall": q = args.get("query") limit = int(args.get("limit") or 10) folder_path = args.get("folderPath") agent_id = args.get("agentId") res = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id) text_out = json.dumps(res, indent=2)
elif name == "memory_save": content = args.get("content") concepts = _parse_mcp_list_arg(args.get("concepts")) files = _parse_mcp_list_arg(args.get("files")) project = args.get("project") res = functions.remember(kv, { "content": content, "type": args.get("type") or "fact", "concepts": concepts, "files": files, "project": project, }) text_out = json.dumps(res)
elif name == "memory_smart_search": q = args.get("query") limit = int(args.get("limit") or 10) folder_path = args.get("folderPath") agent_id = args.get("agentId") res = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id) text_out = json.dumps(res, indent=2)
elif name == "memory_diagnose": res = functions.health_check(kv) text_out = json.dumps(res, indent=2)
elif name == "memory_forget": obs_ids = _parse_mcp_list_arg(args.get("observationIds")) res = functions.forget(kv, { "memoryId": args.get("memoryId"), "folderPath": args.get("folderPath"), "agentId": args.get("agentId"), "observationIds": obs_ids, }) text_out = json.dumps(res, indent=2)
elif name == "memory_export": res = functions.export_data(kv, {}) text_out = json.dumps(res, indent=2)
elif name == "agent_observe": folder_path = args.get("folderPath") agent_id = args.get("agentId") text = args.get("text") or args.get("content") or "" if not folder_path or not agent_id or not text: return jsonify({"error": "folderPath, agentId, and text are required"}), 400 timestamp = args.get("timestamp") or _datetime_now_iso() payload = { "folderPath": folder_path, "agentId": agent_id, "text": text, "timestamp": timestamp, "type": args.get("type"), "title": args.get("title"), "concepts": args.get("concepts"), "files": args.get("files"), "importance": args.get("importance"), } res = functions.folder_observe(kv, payload) text_out = json.dumps(res)
elif name == "agent_remember": agent_id = args.get("agentId") or functions.get_agent_id() or "agent" content = args.get("content") project = args.get("project") mem_type = args.get("type") or "fact" concepts = _parse_mcp_list_arg(args.get("concepts")) files = _parse_mcp_list_arg(args.get("files")) if not content: return jsonify({"error": "content is required"}), 400 payload = { "content": content, "type": mem_type, "concepts": concepts, "files": files, "project": project, "agentId": agent_id, } res = functions.remember(kv, payload) text_out = json.dumps(res)
elif name == "memory_folders": pairs = sorted( kv.list(KV.folders), key=lambda x: x.get("lastUpdated", ""), reverse=True, ) text_out = json.dumps(pairs, indent=2)
elif name == "memory_folder_observations": fp = args.get("folderPath", "") aid = args.get("agentId", "") if not fp or not aid: return jsonify({"error": "folderPath and agentId are required"}), 400 obs = sorted( kv.list(KV.folder_obs(fp, aid)), key=lambda x: x.get("timestamp", ""), reverse=True, ) text_out = json.dumps(obs, indent=2)
elif name == "memory_timeline": res = functions.folder_timeline( kv, limit=int(args.get("limit", 100)), folder_path=args.get("folderPath"), agent_id=args.get("agentId"), before=args.get("before"), after=args.get("after"), ) text_out = json.dumps(res, indent=2)
else: return jsonify({"error": f"unknown tool: {name}"}), 400
return jsonify({"content": [{"type": "text", "text": text_out}]}), 200
except Exception as e: return jsonify({"error": str(e)}), 500123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Memory routes blueprint.
Handles: POST /agentmemory/remember POST /agentmemory/agent/remember GET /agentmemory/memories POST /agentmemory/forget"""
import osfrom flask import Blueprint, request, jsonifyimport functionsfrom functions import KV
memories_bp = Blueprint("memories", __name__)
def _check_auth(): import hmac secret = os.getenv("AGENTMEMORY_SECRET") if not secret: return None auth = request.headers.get("Authorization") or request.headers.get("authorization") if not auth or not auth.startswith("Bearer "): return jsonify({"error": "unauthorized"}), 401 provided_token = auth[7:].strip() if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")): return jsonify({"error": "unauthorized"}), 401 return None
def _get_kv(): import app as app_module return app_module.kv
# ---------------------------------------------------------------------------# POST /agentmemory/remember# ---------------------------------------------------------------------------
@memories_bp.route("/agentmemory/remember", methods=["POST"])def api_remember(): auth_err = _check_auth() if auth_err: return auth_err
try: body = request.get_json(force=True) or {} res = functions.remember(_get_kv(), body) return jsonify(res), 201 except Exception as e: return jsonify({"error": str(e)}), 400
# ---------------------------------------------------------------------------# POST /agentmemory/agent/remember# ---------------------------------------------------------------------------
@memories_bp.route("/agentmemory/agent/remember", methods=["POST"])def api_agent_remember(): auth_err = _check_auth() if auth_err: return auth_err
try: body = request.get_json(force=True) or {} content = body.get("content") if not content: return jsonify({"error": "content is required"}), 400
agent_id = body.get("agentId") project = body.get("project") mem_type = body.get("type") or "fact"
concepts = body.get("concepts") or [] if isinstance(concepts, str): concepts = [c.strip() for c in concepts.split(",") if c.strip()]
files = body.get("files") or [] if isinstance(files, str): files = [f.strip() for f in files.split(",") if f.strip()]
payload = { "content": content, "type": mem_type, "concepts": concepts, "files": files, "project": project, } if agent_id: payload["agentId"] = agent_id
res = functions.remember(_get_kv(), payload) return jsonify(res), 201 except Exception as e: return jsonify({"error": str(e)}), 400
# ---------------------------------------------------------------------------# GET /agentmemory/memories# ---------------------------------------------------------------------------
@memories_bp.route("/agentmemory/memories", methods=["GET"])def api_memories_list(): auth_err = _check_auth() if auth_err: return auth_err
latest_only = request.args.get("latest", "false").lower() == "true" limit = int(request.args.get("limit", "500")) all_mems = _get_kv().list(KV.memories) if latest_only: all_mems = [m for m in all_mems if m.get("isLatest") is not False] all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True) return jsonify({"memories": all_mems[:limit], "total": len(all_mems)}), 200
# ---------------------------------------------------------------------------# POST /agentmemory/forget# ---------------------------------------------------------------------------
@memories_bp.route("/agentmemory/forget", methods=["POST"])def api_forget(): auth_err = _check_auth() if auth_err: return auth_err
try: body = request.get_json(force=True) or {} res = functions.forget(_get_kv(), body) return jsonify(res), 200 except Exception as e: return jsonify({"error": str(e)}), 40012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Migration route blueprint.
Handles: POST /agentmemory/migrate"""
import osfrom flask import Blueprint, request, jsonifyimport functions
migration_bp = Blueprint("migration", __name__)
def _check_auth(): import hmac secret = os.getenv("AGENTMEMORY_SECRET") if not secret: return None auth = request.headers.get("Authorization") or request.headers.get("authorization") if not auth or not auth.startswith("Bearer "): return jsonify({"error": "unauthorized"}), 401 provided_token = auth[7:].strip() if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")): return jsonify({"error": "unauthorized"}), 401 return None
def _get_kv(): import app as app_module return app_module.kv
# ---------------------------------------------------------------------------# POST /agentmemory/migrate# ---------------------------------------------------------------------------
@migration_bp.route("/agentmemory/migrate", methods=["POST"])def api_migrate(): auth_err = _check_auth() if auth_err: return auth_err try: body = request.get_json(force=True) or {} dry_run = bool(body.get("dry_run", False)) result = functions.migrate_sessions_to_folders(_get_kv(), dry_run) return jsonify(result), 200 except Exception as e: return jsonify({"error": str(e)}), 400123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Observation routes blueprint.
Handles: POST /agentmemory/observe POST /agentmemory/agent/observe GET /agentmemory/folder/observations GET /agentmemory/folders"""
import osimport datetimefrom flask import Blueprint, request, jsonifyimport functionsfrom functions import KV
observations_bp = Blueprint("observations", __name__)
def _datetime_now_iso() -> str: return datetime.datetime.utcnow().isoformat() + "Z"
def _check_auth(): """Replicate the check_auth() pattern from app.py.""" import hmac secret = os.getenv("AGENTMEMORY_SECRET") if not secret: return None auth = request.headers.get("Authorization") or request.headers.get("authorization") if not auth or not auth.startswith("Bearer "): return jsonify({"error": "unauthorized"}), 401 provided_token = auth[7:].strip() if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")): return jsonify({"error": "unauthorized"}), 401 return None
def _get_kv(): """Retrieve the shared kv instance from the app module.""" import app as app_module return app_module.kv
# ---------------------------------------------------------------------------# POST /agentmemory/observe (legacy raw hook endpoint)# ---------------------------------------------------------------------------
@observations_bp.route("/agentmemory/observe", methods=["POST"])def api_observe(): auth_err = _check_auth() if auth_err: return auth_err
try: body = request.get_json(force=True) or {} res = functions.observe(_get_kv(), body) return jsonify(res), 201 except Exception as e: return jsonify({"error": str(e)}), 400
# ---------------------------------------------------------------------------# POST /agentmemory/agent/observe# ---------------------------------------------------------------------------
@observations_bp.route("/agentmemory/agent/observe", methods=["POST"])def api_agent_observe(): auth_err = _check_auth() if auth_err: return auth_err
try: body = request.get_json(force=True) or {} folder_path = body.get("folderPath") agent_id = body.get("agentId") text = body.get("text") or body.get("content") or ""
if not folder_path or not agent_id or not text: return jsonify({"error": "folderPath, agentId, and text are required"}), 400
# sessionId accepted but ignored (folder-based model) timestamp = body.get("timestamp") or _datetime_now_iso()
payload = { "folderPath": folder_path, "agentId": agent_id, "text": text, "timestamp": timestamp, "type": body.get("type"), "title": body.get("title"), "concepts": body.get("concepts"), "files": body.get("files"), "importance": body.get("importance"), }
res = functions.folder_observe(_get_kv(), payload) return jsonify(res), 201 except ValueError as e: return jsonify({"error": str(e)}), 400 except Exception as e: return jsonify({"error": str(e)}), 400
# ---------------------------------------------------------------------------# GET /agentmemory/folders# ---------------------------------------------------------------------------
@observations_bp.route("/agentmemory/folders", methods=["GET"])def api_folders(): auth_err = _check_auth() if auth_err: return auth_err folders = sorted( _get_kv().list(KV.folders), key=lambda x: x.get("lastUpdated", ""), reverse=True, ) return jsonify({"folders": folders}), 200
# ---------------------------------------------------------------------------# GET /agentmemory/folder/observations# ---------------------------------------------------------------------------
@observations_bp.route("/agentmemory/folder/observations", methods=["GET"])def api_folder_observations(): auth_err = _check_auth() if auth_err: return auth_err fp = request.args.get("folderPath") aid = request.args.get("agentId") if not fp or not aid: return jsonify({"error": "folderPath and agentId are required"}), 400 observations = sorted( _get_kv().list(KV.folder_obs(fp, aid)), key=lambda x: x.get("timestamp", ""), reverse=True, ) return jsonify({"observations": observations, "folderPath": fp, "agentId": aid}), 2001234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Search and timeline routes blueprint.
Handles: POST /agentmemory/search POST /agentmemory/timeline"""
import osfrom flask import Blueprint, request, jsonifyimport functions
search_bp = Blueprint("search", __name__)
def _check_auth(): import hmac secret = os.getenv("AGENTMEMORY_SECRET") if not secret: return None auth = request.headers.get("Authorization") or request.headers.get("authorization") if not auth or not auth.startswith("Bearer "): return jsonify({"error": "unauthorized"}), 401 provided_token = auth[7:].strip() if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")): return jsonify({"error": "unauthorized"}), 401 return None
def _get_kv(): import app as app_module return app_module.kv
# ---------------------------------------------------------------------------# POST /agentmemory/search# ---------------------------------------------------------------------------
@search_bp.route("/agentmemory/search", methods=["POST"])def api_search(): auth_err = _check_auth() if auth_err: return auth_err
try: body = request.get_json(force=True) or {} query = body.get("query") if not query or not query.strip(): return jsonify({"error": "query is required"}), 400 limit = body.get("limit") or 10 folder_path = body.get("folderPath") agent_id = body.get("agentId")
res = functions.folder_search(_get_kv(), query, limit, folder_path=folder_path, agent_id=agent_id) return jsonify(res), 200 except Exception as e: return jsonify({"error": str(e)}), 400
# ---------------------------------------------------------------------------# POST /agentmemory/timeline# ---------------------------------------------------------------------------
@search_bp.route("/agentmemory/timeline", methods=["POST"])def api_timeline(): auth_err = _check_auth() if auth_err: return auth_err
try: body = request.get_json(force=True) or {} folder_path = body.get("folderPath") agent_id = body.get("agentId") limit = body.get("limit") or 100 before = body.get("before") after = body.get("after") result = functions.folder_timeline(_get_kv(), limit, folder_path, agent_id, before, after) return jsonify({"observations": result}), 200 except Exception as e: return jsonify({"error": str(e)}), 400272 unmodified lines27327427527627727825 unmodified lines30430530630730830916 unmodified lines32632732832933033197 unmodified lines42943043143243343479 unmodified lines514515516517518519520521522523524525213 unmodified lines739740741272 unmodified linesself.doc_term_counts: Dict[str, Dict[str, int]] = {}self.total_doc_length = 0self.sorted_terms: Optional[List[str]] = Noneself.k1 = 1.2self.b = 0.7525 unmodified linesself.inverted_index[term].add(obs_id)self.sorted_terms = Nonedef has(self, id: str) -> bool:return id in self.entries16 unmodified linesself.total_doc_length = max(0, self.total_doc_length - entry["termCount"])self.entries.pop(id, None)self.sorted_terms = Nonedef search(self, query: str, limit: int = 20) -> List[Dict[str, Any]]:raw_terms = self.tokenize(query.lower())97 unmodified linesfor id_, counts in data.get("docTerms", []):self.doc_term_counts[id_] = dict(counts)self.total_doc_length = int(data.get("totalDocLength", 0))def serialize_data(self) -> Dict[str, Any]:entries = list(self.entries.items())79 unmodified linesclass VectorIndex:def __init__(self):self.vectors: Dict[str, Dict[str, Any]] = {}def add(self, obs_id: str, session_id: str, embedding: List[float]) -> None:self.vectors[obs_id] = {"embedding": embedding, "sessionId": session_id}def remove(self, obs_id: str) -> None:self.vectors.pop(obs_id, None)def search(self, query: List[float], limit: int = 20) -> List[Dict[str, Any]]:results = []213 unmodified linescombined.sort(key=lambda x: x["combinedScore"], reverse=True)return combined[:limit]272 unmodified lines27327427527627727827925 unmodified lines30530630730830931031116 unmodified lines32832933033133233333497 unmodified lines43243343443543643743879 unmodified lines518519520521522523524525526527528529530531532533213 unmodified lines747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840272 unmodified linesself.doc_term_counts: Dict[str, Dict[str, int]] = {}self.total_doc_length = 0self.sorted_terms: Optional[List[str]] = Noneself._dirty: bool = False # A4.2self.k1 = 1.2self.b = 0.7525 unmodified linesself.inverted_index[term].add(obs_id)self.sorted_terms = Noneself._dirty = True # A4.2def has(self, id: str) -> bool:return id in self.entries16 unmodified linesself.total_doc_length = max(0, self.total_doc_length - entry["termCount"])self.entries.pop(id, None)self.sorted_terms = Noneself._dirty = True # A4.2def search(self, query: str, limit: int = 20) -> List[Dict[str, Any]]:raw_terms = self.tokenize(query.lower())97 unmodified linesfor id_, counts in data.get("docTerms", []):self.doc_term_counts[id_] = dict(counts)self.total_doc_length = int(data.get("totalDocLength", 0))self._dirty = False # A4.2 — freshly loaded, not dirtydef serialize_data(self) -> Dict[str, Any]:entries = list(self.entries.items())79 unmodified linesclass VectorIndex:def __init__(self):self.vectors: Dict[str, Dict[str, Any]] = {}self._dirty: bool = False # A4.2def add(self, obs_id: str, session_id: str, embedding: List[float]) -> None:self.vectors[obs_id] = {"embedding": embedding, "sessionId": session_id}self._dirty = True # A4.2def remove(self, obs_id: str) -> None:if obs_id in self.vectors:self.vectors.pop(obs_id, None)self._dirty = True # A4.2def search(self, query: List[float], limit: int = 20) -> List[Dict[str, Any]]:results = []213 unmodified linescombined.sort(key=lambda x: x["combinedScore"], reverse=True)return combined[:limit]# =====================================================================# OpenAI Embedding Client (D5.1)# =====================================================================class OpenAIEmbeddingProvider:"""OpenAI text-embedding-3-small provider (1536 dims).Uses urllib.request only — no new dependencies.Reads API key from OPENAI_API_KEY env var."""def __init__(self, api_key: str):self.name = "openai"self.dimensions = 1536self.api_key = api_keyself.model = "text-embedding-3-small"self.api_url = "https://api.openai.com/v1/embeddings"def embed(self, text: str) -> List[float]:return self.embed_batch([text])[0]def embed_batch(self, texts: List[str]) -> List[List[float]]:results: List[List[float]] = []# OpenAI supports up to 2048 inputs per request; batch in chunks of 100batch_limit = 100for i in range(0, len(texts), batch_limit):chunk = texts[i : i + batch_limit]payload = json.dumps({"model": self.model, "input": chunk}).encode("utf-8")req = urllib.request.Request(self.api_url,data=payload,headers={"Content-Type": "application/json","Authorization": f"Bearer {self.api_key}",},method="POST",)try:with urllib.request.urlopen(req, timeout=30.0) as response:resp_data = json.loads(response.read().decode("utf-8"))# Sort by index to preserve orderembeddings_sorted = sorted(resp_data.get("data", []), key=lambda e: e["index"])for emb in embeddings_sorted:results.append(self._l2_normalize(emb["embedding"]))except Exception as e:raise RuntimeError(f"OpenAI embedding batch call failed: {e}")return resultsdef _l2_normalize(self, vec: List[float]) -> List[float]:sum_sq = sum(x * x for x in vec)norm = math.sqrt(sum_sq)if norm == 0:return vecreturn [x / norm for x in vec]# =====================================================================# SentenceTransformer Local Provider (D5.2)# =====================================================================class SentenceTransformerProvider:"""Local sentence-transformers provider (optional install).Default model: all-MiniLM-L6-v2 (384 dims).Override via AGENTMEMORY_LOCAL_EMBEDDING_MODEL env var.Install: pip install sentence-transformers"""def __init__(self, model_name: Optional[str] = None):model_name = model_name or "all-MiniLM-L6-v2"self.name = "sentence-transformers"try:from sentence_transformers import SentenceTransformer # type: ignoreself._model = SentenceTransformer(model_name)self.dimensions = self._model.get_sentence_embedding_dimension()print(f"[search] SentenceTransformerProvider loaded: {model_name} ({self.dimensions} dims)")except ImportError:raise ImportError("sentence-transformers is not installed. ""Run: pip install sentence-transformers or pip install agentmemory[local-embeddings]")def embed(self, text: str) -> List[float]:return self.embed_batch([text])[0]def embed_batch(self, texts: List[str]) -> List[List[float]]:embeddings = self._model.encode(texts, show_progress_bar=False, normalize_embeddings=True)return [emb.tolist() for emb in embeddings]
1234567891011121314151617181920212223"""src/storage/ — Storage utilities package for agentmemory-python (A2.3).
Sub-modules: scopes — KV scope registry (class KV with all scope definitions) paths — Path/ID utility functions (normalize_folder_path, validate_agent_id, generate_id, fingerprint_id) images — Image-on-disk helpers (save_image_to_disk, delete_image, touch_image, is_managed_image_path)
These are compatibility copies — the originals in functions.py are kept intactfor backward compatibility."""
from .scopes import KVfrom .paths import normalize_folder_path, validate_agent_id, generate_id, fingerprint_idfrom .images import save_image_to_disk, delete_image, touch_image, is_managed_image_path
__all__ = [ "KV", "normalize_folder_path", "validate_agent_id", "generate_id", "fingerprint_id", "save_image_to_disk", "delete_image", "touch_image", "is_managed_image_path",]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""src/storage/images.py — Image-on-disk storage helpers (A2.3).
Copied from src/functions.py — do NOT delete the originals (backward compat)."""
import osimport hashlibfrom typing import Optional, Tuple
IMAGES_DIR = os.path.join(os.path.expanduser("~"), ".agentmemory", "images")
def get_max_bytes() -> int: """Return the configured image-store byte limit (default 500 MB).""" return int(os.getenv("AGENTMEMORY_IMAGE_STORE_MAX_BYTES", 500 * 1024 * 1024))
def is_managed_image_path(file_path: str) -> bool: """Return True iff *file_path* lives inside the managed images directory.""" if not file_path: return False resolved = os.path.abspath(file_path) normalized_images_dir = os.path.abspath(IMAGES_DIR) return resolved.startswith(normalized_images_dir + os.sep) or resolved == normalized_images_dir
def save_image_to_disk(base64_data: str) -> Tuple[str, int]: """Decode *base64_data* and write to the managed images directory.
Returns: (file_path, bytes_written) — bytes_written is 0 if the file already existed (content-addressable dedup via SHA-256). """ if not base64_data: return "", 0
if not os.path.exists(IMAGES_DIR): os.makedirs(IMAGES_DIR, exist_ok=True)
clean_base64 = base64_data ext = "png"
if base64_data.startswith("data:image/"): comma_idx = base64_data.find(",") if comma_idx != -1: meta = base64_data[:comma_idx] if "jpeg" in meta or "jpg" in meta: ext = "jpg" elif "webp" in meta: ext = "webp" elif "gif" in meta: ext = "gif" clean_base64 = base64_data[comma_idx + 1:] elif base64_data.startswith("/9j/"): ext = "jpg"
h = hashlib.sha256(clean_base64.encode("utf-8")).hexdigest() file_path = os.path.join(IMAGES_DIR, f"{h}.{ext}")
if os.path.exists(file_path): return file_path, 0
import base64 buffer = base64.b64decode(clean_base64) with open(file_path, "wb") as f: f.write(buffer)
size = os.path.getsize(file_path) return file_path, size
def delete_image(file_path: Optional[str]) -> int: """Delete a managed image file and return the number of bytes freed.
Returns 0 if the path is not managed or does not exist. """ if not file_path or not is_managed_image_path(file_path): return 0 try: if os.path.exists(file_path): size = os.path.getsize(file_path) os.remove(file_path) return size except Exception as e: print(f"[agentmemory] Failed to delete image context: {e}") return 0
def touch_image(file_path: str) -> None: """Update the mtime of a managed image (keeps it alive past LRU eviction).""" if not file_path or not is_managed_image_path(file_path): return try: if os.path.exists(file_path): os.utime(file_path, None) except Exception: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""src/storage/paths.py — Path normalisation and ID utilities (A2.3).
Copied from src/functions.py — do NOT delete the originals (backward compat)."""
import osimport timeimport uuidimport hashlib
# Maximum allowed length for folder paths and agent IDs._MAX_PATH_LEN = 512
def generate_id(prefix: str) -> str: """Generate a time-sortable unique ID with a human-readable prefix.
Format: ``{prefix}_{base36_timestamp}_{12_hex_chars}`` """ t = int(time.time() * 1000) chars = "0123456789abcdefghijklmnopqrstuvwxyz" ts_str = "" while t > 0: ts_str = chars[t % 36] + ts_str t //= 36 if not ts_str: ts_str = "0" rand = uuid.uuid4().hex[:12] return f"{prefix}_{ts_str}_{rand}"
def fingerprint_id(prefix: str, content: str) -> str: """Generate a deterministic ID by SHA-256 fingerprinting *content*.
Format: ``{prefix}_{first_16_hex_chars_of_sha256}`` """ h = hashlib.sha256(content.strip().lower().encode("utf-8")).hexdigest() return f"{prefix}_{h[:16]}"
def normalize_folder_path(path: str) -> str: """Normalize a folder path for safe use in KV scope keys.
Steps applied in order: 1. Cap the raw input at 512 characters (REQ-066). 2. Apply ``os.path.normpath`` to collapse redundant separators and resolve any ``..`` components at the OS level. 3. Convert all OS-native separators to forward slashes. 4. Strip any remaining leading or trailing slashes.
Raises: ValueError: if *path* is empty (before or after normalization), or if the normalized result still contains a ``..`` segment, which would indicate an attempt at path traversal (REQ-064).
Returns: A non-empty, forward-slash-separated string with no leading/trailing slashes and no ``..`` segments — safe for use as a KV scope fragment.
Property (REQ-074): idempotent — applying this function twice yields the same result as applying it once. """ if not path: raise ValueError("folder_path must not be empty")
# 1. Length cap before any processing. path = path[:_MAX_PATH_LEN]
# Pre-normalisation traversal check: reject any path that contains a ".." # component in the raw input before normpath has a chance to resolve it. raw_parts = path.replace("\\", "/").split("/") if any(part == ".." for part in raw_parts): raise ValueError( f"folder_path contains path traversal segment '..': {path!r}" )
# 2. OS-level normalisation (resolves duplicate separators, etc.) normalized = os.path.normpath(path)
# 3. Unify separators to forward slash. normalized = normalized.replace("\\", "/")
# 4. Strip leading / trailing slashes. normalized = normalized.strip("/")
# Guard: also reject any ".." that somehow survives normalisation. parts = normalized.split("/") if any(part == ".." for part in parts): raise ValueError( f"folder_path contains path traversal segment '..': {path!r}" )
if not normalized: raise ValueError("folder_path is empty after normalization")
return normalized
def validate_agent_id(agent_id: str) -> str: """Validate and sanitize an agent_id before use in KV scope keys.
Strips surrounding whitespace and caps at 512 characters (REQ-066).
Raises: ValueError: if *agent_id* is empty after stripping.
Returns: Sanitized agent_id string. """ if not agent_id: raise ValueError("agent_id must not be empty")
sanitized = agent_id.strip()[:_MAX_PATH_LEN]
if not sanitized: raise ValueError("agent_id is empty after stripping whitespace")
return sanitized1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""src/storage/scopes.py — KV scope registry (A2.3).
Copied from src/functions.py — do NOT delete the original (backward compat).The KV class defines all storage scope keys used across agentmemory-python."""
class KV: # ---- Folder memory scopes (new) ----
# Global index of all (folder_path, agent_id) pairs known to the system. # Key = "{safe_folder_path}:{agent_id}", value = FolderIndexEntry dict. folders = "mem:folders"
@staticmethod def folder_obs(folder_path: str, agent_id: str) -> str: """Per-(folder, agent) observations scope. Key = obs_id, value = FolderObservation dict. """ safe_path = folder_path.replace("\\", "/").strip("/") safe_agent = agent_id.strip() return f"mem:folder:{safe_path}:{safe_agent}"
@staticmethod def folder_meta(folder_path: str, agent_id: str) -> str: """Per-(folder, agent) metadata scope. Key = "meta", value = FolderMeta dict (obsCount, lastUpdated, summary). """ safe_path = folder_path.replace("\\", "/").strip("/") safe_agent = agent_id.strip() return f"mem:foldermeta:{safe_path}:{safe_agent}"
# ---- Global / shared scopes (kept) ----
# Long-term memories — unchanged from previous implementation. memories = "mem:memories"
# BM25 index shards — unchanged. bm25Index = "mem:index:bm25"
# Audit log — unchanged. audit = "mem:audit"
# Graph edges — repurposed for folder graph edges. relations = "mem:relations"
# ---- Legacy scopes (read-only; kept for migration and backward compat) ----
# Legacy session store — read by migrate_sessions_to_folders() and legacy observe(). sessions = "mem:sessions"
@staticmethod def observations(session_id: str) -> str: """Legacy per-session observations scope. Key = obs_id, value = raw/synthetic observation dict. Read by migrate_sessions_to_folders() and legacy observe(). """ return f"mem:obs:{session_id}"
# Legacy summary / profile / slot / image-ref scopes retained for legacy code paths. summaries = "mem:summaries" profiles = "mem:profiles" slots = "mem:slots" imageRefs = "mem:image-refs"
# Global (cross-project) pinned slots. globalSlots = "mem:global-slots"192 unmodified lines193194195196197198931 unmodified lines1130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154314 unmodified lines14691470147114721473147413 unmodified lines1488148914901491149214938 unmodified lines150215031504150515061507150844 unmodified lines15531554155515561557155815591062 unmodified lines2622262326242625262626272628166 unmodified lines27952796279727982799280028011956 unmodified lines475847594760476147624763192 unmodified linescolor: var(--ink);border-bottom-color: var(--accent);}.view { display: none; flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 24px; }.view.active { display: block; }931 unmodified lines</div></div><div class="tab-bar" id="tab-bar"><button class="active" data-tab="folders" aria-current="page">Folders</button><button data-tab="memories">Memories</button><button data-tab="graph">Graph</button><button data-tab="timeline">Timeline</button></div><div id="flag-banners" class="flag-banners"></div><div id="viewer-auth" class="viewer-auth"></div><div id="view-folders" class="view active"></div><div id="view-graph" class="view"></div><div id="view-memories" class="view"></div><div id="view-timeline" class="view"></div><div id="view-activity" class="view"></div><div id="view-profile" class="view"></div><div id="view-replay" class="view"></div><div id="view-personal" class="view"></div><div id="modal-overlay" class="modal-overlay"><div class="modal" id="modal"></div></div>314 unmodified linesdocument.querySelectorAll('.tab-bar button').forEach(function(b) {var isActive = b.dataset.tab === tab;b.classList.toggle('active', isActive);if (isActive) {b.setAttribute('aria-current', 'page');} else {13 unmodified linescase 'graph': await loadGraph(); break;case 'memories': await loadMemories(); break;case 'timeline': await loadTimeline(); break;}}8 unmodified linesasync function loadFolders() {var el = document.getElementById('view-folders');if (!el) return;el.innerHTML = '<div class="loading">Loading folders...</div>';try {var result = await apiPost('folders-list', null, 'GET');var folders = (result && result.folders) || [];44 unmodified linesasync function loadFolderDetail(folderPath, agentId) {var el = document.getElementById('view-folders');if (!el) return;el.innerHTML = '<div class="loading">Loading observations...</div>';try {var params = 'folderPath=' + encodeURIComponent(folderPath) + '&agentId=' + encodeURIComponent(agentId);var result = await apiFetchRaw('/agentmemory/folder/observations?' + params);1062 unmodified linesasync function loadMemories() {var el = document.getElementById('view-memories');el.innerHTML = '<div class="loading">Loading memories...</div>';var result = await apiGet('memories?latest=true&limit=2000');var items = (result && result.memories) || [];items.sort(function(a, b) {166 unmodified linesasync function loadTimeline(folderPath, agentId) {var el = document.getElementById('view-timeline');if (!el) return;el.innerHTML = '<div class="loading">Loading timeline...</div>';try {var body = { limit: 100 };if (folderPath) body.folderPath = folderPath;1956 unmodified linesswitchTab(tabFromRoute(), { replaceRoute: true });connectWs();startDashboardAutoRefresh();</script></body></html>192 unmodified lines193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362931 unmodified lines129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329314 unmodified lines164416451646164716481649165013 unmodified lines16641665166616671668166916708 unmodified lines167916801681168216831684168544 unmodified lines17301731173217331734173517361062 unmodified lines2799280028012802280328042805166 unmodified lines29722973297429752976297729781956 unmodified lines49354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380192 unmodified linescolor: var(--ink);border-bottom-color: var(--accent);}.tab-bar button:focus-visible {outline: 2px solid var(--accent);outline-offset: -2px;}/* ── B6.3 Loading skeleton states ──────────────────────────────────── */@keyframes shimmer {0% { background-position: -200% 0; }100% { background-position: 200% 0; }}.skeleton {background: linear-gradient(90deg,var(--bg-inset) 25%,var(--bg-alt) 50%,var(--bg-inset) 75%);background-size: 200% 100%;animation: shimmer 1.5s infinite;border-radius: 3px;}.skeleton-card { height: 80px; margin-bottom: 8px; }.skeleton-line { height: 14px; margin-bottom: 6px; }.skeleton-line.short { width: 60%; }/* ── B1 Command palette ────────────────────────────────────────────── */#cmd-palette { display: contents; }#cmd-backdrop {position: fixed; inset: 0;background: rgba(0,0,0,0.45);backdrop-filter: blur(4px);z-index: 9998;}#cmd-panel {position: fixed;top: 18%;left: 50%;transform: translateX(-50%) translateY(-8px);width: min(640px, 92vw);background: var(--bg);border: 1px solid var(--border);border-radius: 8px;z-index: 9999;overflow: hidden;box-shadow: 0 24px 64px rgba(0,0,0,0.35);animation: cmdSlideIn 0.14s ease forwards;}@keyframes cmdSlideIn {from { opacity: 0; transform: translateX(-50%) translateY(-16px); }to { opacity: 1; transform: translateX(-50%) translateY(0); }}#cmd-input {width: 100%; padding: 14px 18px;font-size: 15px; font-family: var(--font-ui);border: none; border-bottom: 1px solid var(--border-light);background: transparent; color: var(--ink); outline: none;}#cmd-input::placeholder { color: var(--ink-faint); }#cmd-results {list-style: none; margin: 0; padding: 6px 0;max-height: 380px; overflow-y: auto;}#cmd-results li {padding: 9px 18px; cursor: pointer;display: flex; align-items: center; gap: 10px;font-family: var(--font-ui); font-size: 13px;color: var(--ink-secondary);}#cmd-results li[aria-selected="true"],#cmd-results li:hover { background: var(--bg-inset); color: var(--ink); }.cmd-badge {font-size: 10px; padding: 2px 6px; border-radius: 3px;background: var(--bg-alt); color: var(--ink-muted);border: 1px solid var(--border-light); flex-shrink: 0;}.cmd-main { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.cmd-sub { font-size: 11px; color: var(--ink-faint); flex-shrink: 0; }/* ── B5 MCP Tool Tester tab ────────────────────────────────────────── */.tools-list { display: flex; flex-direction: column; gap: 0; max-width: 900px; }.tool-row {border: 1px solid var(--border-light); border-top: none;padding: 10px 16px; cursor: pointer;display: flex; align-items: center; gap: 12px;font-family: var(--font-ui); font-size: 13px;}.tool-row:first-child { border-top: 1px solid var(--border-light); }.tool-row:hover, .tool-row.selected { background: var(--bg-inset); }.tool-name { font-weight: 600; color: var(--ink); min-width: 220px; font-family: var(--font-mono); font-size: 12px; }.tool-desc { color: var(--ink-muted); }#tool-panel { max-width: 900px; margin-top: 24px; }#tool-panel h3 { font-family: var(--font-ui); font-size: 14px; font-weight: 600; margin-bottom: 8px; color: var(--ink); }#tool-args-editor {width: 100%; min-height: 120px; padding: 10px 14px;font-family: var(--font-mono); font-size: 13px;border: 1px solid var(--border-light); background: var(--bg-inset);color: var(--ink); resize: vertical; border-radius: 3px;}#tool-run-btn {margin-top: 8px; padding: 8px 20px;background: var(--accent); color: #fff; border: none;font-family: var(--font-ui); font-size: 13px; cursor: pointer; border-radius: 3px;}#tool-run-btn:hover { opacity: 0.85; }#tool-response {margin-top: 12px; padding: 12px 14px;background: var(--bg-inset); border: 1px solid var(--border-light);font-family: var(--font-mono); font-size: 12px;white-space: pre-wrap; word-break: break-all;max-height: 300px; overflow-y: auto; border-radius: 3px;color: var(--ink);}#tool-response.error { color: var(--accent); border-color: var(--accent); }.tool-history { margin-top: 20px; }.tool-history summary {font-family: var(--font-ui); font-size: 12px; cursor: pointer;color: var(--ink-muted); padding: 6px 0;}.tool-history-entry {border: 1px solid var(--border-light); margin-bottom: 4px; border-radius: 3px;}.tool-history-entry summary {padding: 8px 12px; display: flex; align-items: center; gap: 8px;font-family: var(--font-mono); font-size: 12px; color: var(--ink);}.badge-ok { color: var(--green); }.badge-err { color: var(--accent); }/* ── B4 Onboarding card ─────────────────────────────────────────────── */.onboarding-card {border: 2px solid var(--border); padding: 28px 32px;max-width: 640px; margin: 32px auto; background: var(--cream);}.onboarding-card h2 { font-family: var(--font-display); font-size: 22px; margin-bottom: 6px; color: var(--ink); }.onboarding-card p { font-size: 14px; color: var(--ink-muted); margin-bottom: 20px; font-family: var(--font-ui); }.onboarding-step { margin-bottom: 20px; }.onboarding-step .step-header {display: flex; align-items: center; gap: 10px; margin-bottom: 8px;}.step-num {width: 24px; height: 24px; border-radius: 50%;background: var(--ink); color: var(--bg);display: flex; align-items: center; justify-content: center;font-family: var(--font-ui); font-size: 12px; font-weight: 700; flex-shrink: 0;}.step-num.done { background: var(--green); }.step-title { font-family: var(--font-ui); font-weight: 600; font-size: 13px; color: var(--ink); }.step-code-wrap { position: relative; }.step-code {display: block; background: var(--bg-inset); border: 1px solid var(--border-light);padding: 8px 12px; font-family: var(--font-mono); font-size: 11px;color: var(--ink); overflow-x: auto; white-space: pre;}.copy-btn {position: absolute; right: 6px; top: 6px;background: var(--bg); border: 1px solid var(--border-light);padding: 2px 8px; font-size: 10px; font-family: var(--font-ui);cursor: pointer; color: var(--ink-muted); border-radius: 2px;}.copy-btn:hover { background: var(--bg-inset); }.onboarding-dismiss {margin-top: 20px; padding: 8px 20px;background: none; border: 1px solid var(--border);font-family: var(--font-ui); font-size: 13px; cursor: pointer; color: var(--ink);}.onboarding-dismiss:hover { background: var(--bg-inset); }.view { display: none; flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 24px; }.view.active { display: block; }931 unmodified lines</div></div><div class="tab-bar" id="tab-bar" role="tablist" aria-label="Main navigation"><button class="active" data-tab="folders" role="tab" aria-selected="true" aria-controls="view-folders" id="tab-btn-folders">Folders</button><button data-tab="memories" role="tab" aria-selected="false" aria-controls="view-memories" id="tab-btn-memories">Memories</button><button data-tab="graph" role="tab" aria-selected="false" aria-controls="view-graph" id="tab-btn-graph">Graph</button><button data-tab="timeline" role="tab" aria-selected="false" aria-controls="view-timeline" id="tab-btn-timeline">Timeline</button><button data-tab="tools" role="tab" aria-selected="false" aria-controls="view-tools" id="tab-btn-tools">Tools</button></div><div id="flag-banners" class="flag-banners"></div><div id="viewer-auth" class="viewer-auth"></div><div id="view-folders" class="view active" role="tabpanel" aria-labelledby="tab-btn-folders"></div><div id="view-graph" class="view" role="tabpanel" aria-labelledby="tab-btn-graph"></div><div id="view-memories" class="view" role="tabpanel" aria-labelledby="tab-btn-memories"></div><div id="view-timeline" class="view" role="tabpanel" aria-labelledby="tab-btn-timeline"></div><div id="view-tools" class="view" role="tabpanel" aria-labelledby="tab-btn-tools"></div><div id="view-activity" class="view"></div><div id="view-profile" class="view"></div><div id="view-replay" class="view"></div><div id="view-personal" class="view"></div><!-- Command Palette (B1) --><div id="cmd-palette" hidden role="dialog" aria-modal="true" aria-label="Command Palette"><div id="cmd-backdrop"></div><div id="cmd-panel"><input id="cmd-input" type="text" placeholder="Search folders, memories, tabs…" autocomplete="off" aria-label="Command palette search"><ul id="cmd-results" role="listbox" aria-label="Search results"></ul></div></div><div id="modal-overlay" class="modal-overlay"><div class="modal" id="modal"></div></div>314 unmodified linesdocument.querySelectorAll('.tab-bar button').forEach(function(b) {var isActive = b.dataset.tab === tab;b.classList.toggle('active', isActive);b.setAttribute('aria-selected', isActive ? 'true' : 'false');if (isActive) {b.setAttribute('aria-current', 'page');} else {13 unmodified linescase 'graph': await loadGraph(); break;case 'memories': await loadMemories(); break;case 'timeline': await loadTimeline(); break;case 'tools': await loadTools(); break;}}8 unmodified linesasync function loadFolders() {var el = document.getElementById('view-folders');if (!el) return;el.innerHTML = '<div style="padding:24px;"><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div></div>';try {var result = await apiPost('folders-list', null, 'GET');var folders = (result && result.folders) || [];44 unmodified linesasync function loadFolderDetail(folderPath, agentId) {var el = document.getElementById('view-folders');if (!el) return;el.innerHTML = '<div style="padding:24px;"><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div></div>';try {var params = 'folderPath=' + encodeURIComponent(folderPath) + '&agentId=' + encodeURIComponent(agentId);var result = await apiFetchRaw('/agentmemory/folder/observations?' + params);1062 unmodified linesasync function loadMemories() {var el = document.getElementById('view-memories');el.innerHTML = '<div style="padding:24px;"><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div></div>';var result = await apiGet('memories?latest=true&limit=2000');var items = (result && result.memories) || [];items.sort(function(a, b) {166 unmodified linesasync function loadTimeline(folderPath, agentId) {var el = document.getElementById('view-timeline');if (!el) return;el.innerHTML = '<div style="padding:24px;"><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div></div>';try {var body = { limit: 100 };if (folderPath) body.folderPath = folderPath;1956 unmodified linesswitchTab(tabFromRoute(), { replaceRoute: true });connectWs();startDashboardAutoRefresh();// ==========================================================================// B4.3 — copyToClipboard utility// ==========================================================================function copyToClipboard(text, btn) {function showCopied() {if (!btn) return;var orig = btn.textContent;btn.textContent = 'Copied!';btn.style.color = 'var(--green)';setTimeout(function() { btn.textContent = orig; btn.style.color = ''; }, 1500);}if (navigator.clipboard && navigator.clipboard.writeText) {navigator.clipboard.writeText(text).then(showCopied).catch(fallback);} else { fallback(); }function fallback() {var ta = document.createElement('textarea');ta.value = text;ta.style.cssText = 'position:fixed;opacity:0;pointer-events:none;';document.body.appendChild(ta);ta.select();try { document.execCommand('copy'); showCopied(); } catch(_) {}document.body.removeChild(ta);}}// ==========================================================================// B4 — Onboarding card (empty state detection)// ==========================================================================function maybeShowOnboarding(health, flags) {if (localStorage.getItem('agentmemory_onboarding_dismissed')) return;if ((health.observationCount || 0) > 0 || (health.memoryCount || 0) > 0) return;var el = document.getElementById('view-folders');if (!el) return;var flagMap = {};((flags && flags.flags) || []).forEach(function(f) { flagMap[f.key] = f.enabled; });function step(num, done, title, snippet) {var doneClass = done ? ' done' : '';return '<div class="onboarding-step">' +'<div class="step-header">' +'<div class="step-num' + doneClass + '">' + (done ? '✓' : num) + '</div>' +'<div class="step-title">' + title + '</div>' +'</div>' +'<div class="step-code-wrap">' +'<code class="step-code">' + esc(snippet) + '</code>' +'<button class="copy-btn" data-snippet="' + esc(snippet) + '">Copy</button>' +'</div></div>';}var secretSet = !!(flagMap['AGENTMEMORY_SECRET_SET']);var geminiSet = !!(flagMap['GEMINI_API_KEY_SET']);var card = document.createElement('div');card.className = 'onboarding-card';card.innerHTML ='<h2>Welcome to agentmemory</h2>' +'<p>No observations yet. Complete these steps to start recording agent memory.</p>' +step(1, secretSet, 'Set AGENTMEMORY_SECRET (optional auth)','echo "AGENTMEMORY_SECRET=your-secret-here" >> ~/.agentmemory/.env') +step(2, geminiSet, 'Add GEMINI_API_KEY for semantic search','echo "GEMINI_API_KEY=your-key" >> ~/.agentmemory/.env') +step(3, false, 'Point your agent at agentmemory','curl -X POST http://localhost:3111/agentmemory/agent/observe \\\n' +' -H "Content-Type: application/json" \\\n' +' -d \'{"folderPath":"/your/project","agentId":"kiro","text":"Hello",' +'"timestamp":"' + new Date().toISOString() + '"}\'') +'<button class="onboarding-dismiss">Got it</button>';// Wire copy buttonscard.querySelectorAll('.copy-btn').forEach(function(btn) {btn.addEventListener('click', function() {copyToClipboard(btn.dataset.snippet, btn);});});card.querySelector('.onboarding-dismiss').addEventListener('click', function() {localStorage.setItem('agentmemory_onboarding_dismissed', '1');card.remove();});el.insertAdjacentElement('afterbegin', card);}// Hook into existing folder load to check empty statevar _origLoadFolders = loadFolders;async function loadFolders() {await _origLoadFolders.apply(this, arguments);// After load, check health for onboardingtry {var h = await apiFetch('/agentmemory/health');var f = state.flagsConfig;maybeShowOnboarding(h, f);} catch(_) {}}// ==========================================================================// B5 — MCP Tool Tester tab// ==========================================================================var _toolHistory = [];var _selectedTool = null;async function loadTools() {var el = document.getElementById('view-tools');if (!el) return;// Skeleton while loadingel.innerHTML = '<div style="padding:24px;max-width:900px;">' +'<div class="skeleton skeleton-card"></div>' +'<div class="skeleton skeleton-card"></div>' +'<div class="skeleton skeleton-card"></div>' +'</div>';try {var data = await apiFetch('/agentmemory/mcp/tools');var tools = data.tools || [];renderToolsTab(el, tools);} catch(err) {el.innerHTML = '<div style="padding:24px;color:var(--accent);">Error loading tools: ' + esc(String(err)) + '</div>';}}function renderToolsTab(el, tools) {var html = '<div style="padding:0 0 24px;">';html += '<h2 style="font-family:var(--font-display);font-size:22px;margin-bottom:16px;color:var(--ink);">MCP Tool Tester</h2>';html += '<div class="tools-list" id="tools-list">';tools.forEach(function(t) {html += '<div class="tool-row" data-name="' + esc(t.name) + '">' +'<span class="tool-name">' + esc(t.name) + '</span>' +'<span class="tool-desc">' + esc(t.description || '') + '</span>' +'</div>';});html += '</div>';html += '<div id="tool-panel" style="display:none;">' +'<h3 id="tool-panel-title"></h3>' +'<textarea id="tool-args-editor" spellcheck="false">{}</textarea>' +'<div><button id="tool-run-btn">Run ▶</button></div>' +'<div id="tool-response" style="display:none;"></div>' +'<div class="tool-history" id="tool-history-wrap"></div>' +'</div>';html += '</div>';el.innerHTML = html;var toolMap = {};tools.forEach(function(t) { toolMap[t.name] = t; });el.querySelectorAll('.tool-row').forEach(function(row) {row.addEventListener('click', function() {el.querySelectorAll('.tool-row').forEach(function(r) { r.classList.remove('selected'); });row.classList.add('selected');var name = row.dataset.name;_selectedTool = name;var tool = toolMap[name];var panel = document.getElementById('tool-panel');var title = document.getElementById('tool-panel-title');var editor = document.getElementById('tool-args-editor');panel.style.display = '';title.textContent = name;// Pre-fill required keysvar args = {};if (tool.inputSchema && tool.inputSchema.properties) {Object.keys(tool.inputSchema.properties).forEach(function(k) {args[k] = '';});}editor.value = JSON.stringify(args, null, 2);document.getElementById('tool-response').style.display = 'none';renderToolHistory();});});document.getElementById('tool-run-btn').addEventListener('click', async function() {var btn = this;var name = _selectedTool;if (!name) return;var argsText = document.getElementById('tool-args-editor').value;var respEl = document.getElementById('tool-response');var args;try { args = JSON.parse(argsText); } catch(e) {respEl.textContent = 'Invalid JSON: ' + e.message;respEl.className = 'error';respEl.style.display = '';return;}btn.textContent = 'Running…';btn.disabled = true;try {var result = await apiFetchRaw('/agentmemory/mcp/tools', {method: 'POST',body: JSON.stringify({ name: name, arguments: args })});var text = await result.text();var ok = result.ok;respEl.textContent = text;respEl.className = ok ? '' : 'error';respEl.style.display = '';// Add to history_toolHistory.unshift({ name: name, ts: new Date().toISOString(), ok: ok, args: args, response: text });if (_toolHistory.length > 10) _toolHistory.length = 10;renderToolHistory();} catch(err) {respEl.textContent = String(err);respEl.className = 'error';respEl.style.display = '';} finally {btn.textContent = 'Run ▶';btn.disabled = false;}});renderToolHistory();}function renderToolHistory() {var wrap = document.getElementById('tool-history-wrap');if (!wrap || _toolHistory.length === 0) return;var html = '<details class="tool-history"><summary>History (' + _toolHistory.length + ')</summary>';_toolHistory.forEach(function(h) {var badge = h.ok? '<span class="badge-ok">✓ ok</span>': '<span class="badge-err">✗ err</span>';html += '<details class="tool-history-entry">' +'<summary>' + badge + ' <span style="font-weight:600;">' + esc(h.name) + '</span>' +' <span style="color:var(--ink-faint);font-size:10px;">' + h.ts.slice(11,19) + '</span></summary>' +'<div style="padding:8px 12px;font-family:var(--font-mono);font-size:11px;white-space:pre-wrap;max-height:150px;overflow:auto;">' +esc(h.response) + '</div>' +'</details>';});html += '</details>';wrap.innerHTML = html;}// ==========================================================================// B1 — Command Palette (Ctrl+K / Cmd+K)// ==========================================================================var _cmdOpen = false;var _cmdSelectedIdx = -1;function openCommandPalette() {var palette = document.getElementById('cmd-palette');if (!palette) return;_cmdOpen = true;_cmdSelectedIdx = -1;palette.hidden = false;var input = document.getElementById('cmd-input');if (input) { input.value = ''; input.focus(); }renderCmdResults('');}function closeCommandPalette() {var palette = document.getElementById('cmd-palette');if (!palette) return;_cmdOpen = false;palette.hidden = true;}function renderCmdResults(query) {var list = document.getElementById('cmd-results');if (!list) return;var q = query.toLowerCase().trim();var items = [];// Tab names['Folders','Memories','Graph','Timeline','Tools'].forEach(function(name) {if (!q || name.toLowerCase().includes(q)) {items.push({ type: 'Tab', label: name, sub: '', action: function(n) { return function() { closeCommandPalette(); switchTab(n.toLowerCase()); }; }(name) });}});// Folders from cache((window._cachedFolders) || []).forEach(function(f) {var fp = f.folderPath || '';var aid = f.agentId || '';if (!q || fp.toLowerCase().includes(q) || aid.toLowerCase().includes(q)) {items.push({ type: 'Folder', label: fp, sub: aid, action: function(fp2, aid2) {return function() { closeCommandPalette(); switchTab('folders'); };}(fp, aid) });}});// Memories from cache((window._cachedMemories) || []).forEach(function(m) {var content = (m.content || '').slice(0, 80);if (!q || content.toLowerCase().includes(q)) {items.push({ type: 'Memory', label: content, sub: m.type || '', action: function() {closeCommandPalette(); switchTab('memories');} });}});items = items.slice(0, 30);_cmdSelectedIdx = items.length > 0 ? 0 : -1;list.innerHTML = items.map(function(item, i) {return '<li role="option" aria-selected="' + (i === 0 ? 'true' : 'false') + '" data-idx="' + i + '">' +'<span class="cmd-badge">' + esc(item.type) + '</span>' +'<span class="cmd-main">' + esc(item.label) + '</span>' +(item.sub ? '<span class="cmd-sub">' + esc(item.sub) + '</span>' : '') +'</li>';}).join('');// Store actionslist._cmdItems = items;list.querySelectorAll('li').forEach(function(li) {li.addEventListener('click', function() {var idx = parseInt(li.dataset.idx, 10);if (list._cmdItems && list._cmdItems[idx]) {list._cmdItems[idx].action();}});});}// Global keydown handler for command palettedocument.addEventListener('keydown', function(e) {// Ctrl+K or Cmd+K — open paletteif ((e.ctrlKey || e.metaKey) && e.key === 'k') {e.preventDefault();if (_cmdOpen) { closeCommandPalette(); } else { openCommandPalette(); }return;}if (!_cmdOpen) return;var list = document.getElementById('cmd-results');var items = (list && list._cmdItems) || [];if (e.key === 'Escape') {e.preventDefault();closeCommandPalette();} else if (e.key === 'ArrowDown') {e.preventDefault();_cmdSelectedIdx = Math.min(_cmdSelectedIdx + 1, items.length - 1);updateCmdSelection();} else if (e.key === 'ArrowUp') {e.preventDefault();_cmdSelectedIdx = Math.max(_cmdSelectedIdx - 1, 0);updateCmdSelection();} else if (e.key === 'Enter') {e.preventDefault();if (_cmdSelectedIdx >= 0 && items[_cmdSelectedIdx]) {items[_cmdSelectedIdx].action();}}});function updateCmdSelection() {var list = document.getElementById('cmd-results');if (!list) return;list.querySelectorAll('li').forEach(function(li, i) {li.setAttribute('aria-selected', i === _cmdSelectedIdx ? 'true' : 'false');});}// Wire palette inputvar cmdInput = document.getElementById('cmd-input');if (cmdInput) {cmdInput.addEventListener('input', function() {renderCmdResults(this.value);});}// Close on backdrop clickvar cmdBackdrop = document.getElementById('cmd-backdrop');if (cmdBackdrop) {cmdBackdrop.addEventListener('click', closeCommandPalette);}// ==========================================================================// B6.2 — Tab keyboard navigation (arrow keys)// ==========================================================================var tabBar = document.getElementById('tab-bar');if (tabBar) {tabBar.addEventListener('keydown', function(e) {var tabs = Array.from(tabBar.querySelectorAll('button[role="tab"]'));var idx = tabs.indexOf(document.activeElement);if (idx === -1) return;if (e.key === 'ArrowRight') {e.preventDefault();tabs[(idx + 1) % tabs.length].focus();} else if (e.key === 'ArrowLeft') {e.preventDefault();tabs[(idx - 1 + tabs.length) % tabs.length].focus();} else if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();tabs[idx].click();}});}// ==========================================================================// B3 — VirtualList helper// ==========================================================================function VirtualList(opts) {this.container = opts.container;this.renderItem = opts.renderItem;this.loadMore = opts.loadMore || null;this.items = [];this._renderedCount = 0;this.sentinel = document.createElement('div');this.sentinel.style.height = '1px';this.container.appendChild(this.sentinel);var self = this;this._observer = new IntersectionObserver(function(entries) {if (entries[0].isIntersecting && self.loadMore) { self.loadMore(); }}, { root: null, threshold: 0.1 });this._observer.observe(this.sentinel);}VirtualList.prototype.setItems = function(items) {this.items = items;this._renderedCount = 0;// Clear all children except sentinelwhile (this.container.firstChild && this.container.firstChild !== this.sentinel) {this.container.removeChild(this.container.firstChild);}this.render();};VirtualList.prototype.addItems = function(newItems) {this.items = this.items.concat(newItems);this.render();};VirtualList.prototype.render = function() {var frag = document.createDocumentFragment();for (var i = this._renderedCount; i < this.items.length; i++) {frag.appendChild(this.renderItem(this.items[i]));}this._renderedCount = this.items.length;this.container.insertBefore(frag, this.sentinel);};VirtualList.prototype.destroy = function() { this._observer.disconnect(); };// Cache for command palettewindow._cachedFolders = window._cachedFolders || [];window._cachedMemories = window._cachedMemories || [];// Hook into existing loadMemories to cache results for command palettevar _origLoadMemories = typeof loadMemories === 'function' ? loadMemories : null;</script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Viewer HTML rendering helpers.
Separated from app.py so the factory stays under 150 lines."""
import osimport secretsimport base64from flask import make_response
def make_viewer_response(base_dir: str): """ Read src/viewer/index.html, inject nonce + version + token, set CSP headers.
Returns a Flask Response object ready to send to the client. Raises an exception if the template file is missing. """ template_path = os.path.join(base_dir, "viewer", "index.html") with open(template_path, "r", encoding="utf-8") as f: template = f.read()
nonce = base64.urlsafe_b64encode(secrets.token_bytes(16)).decode("utf-8").rstrip("=")
# D2.2: Never embed the raw AGENTMEMORY_SECRET in page source. # Replace the placeholder with an empty string — the viewer authenticates # via the Authorization header set programmatically after load. html = ( template .replace("__AGENTMEMORY_VIEWER_NONCE__", nonce) .replace("__AGENTMEMORY_VERSION__", "0.9.8") .replace("__AGENTMEMORY_AUTO_TOKEN__", "") )
csp = "; ".join([ "default-src 'none'", "base-uri 'none'", "frame-ancestors 'self' https://huggingface.co https://*.hf.space", "object-src 'none'", "form-action 'none'", f"script-src 'nonce-{nonce}'", "script-src-attr 'none'", "style-src 'unsafe-inline'", ( "connect-src 'self' https: http://localhost:* http://127.0.0.1:* " "wss: ws://localhost:* ws://127.0.0.1:* wss://localhost:* wss://127.0.0.1:*" ), "img-src 'self' data:", "font-src 'self'", ])
res = make_response(html) res.headers["Content-Type"] = "text/html; charset=utf-8" res.headers["Content-Security-Policy"] = csp res.headers["Cache-Control"] = "no-cache" return res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""Background worker threads for agentmemory-python.
Start all workers via start_background_workers(kv).Each worker runs as a daemon thread so it exits automatically when the process dies.
C5.1: SIGTERM and SIGINT handlers are registered here to flush the indexpersistence debounce queue and run a WAL checkpoint before exit."""
import osimport signalimport sysimport threadingimport time
import functions
# Module-level shutdown flag — set by signal handlers_shutting_down = threading.Event()
# Reference to the persistence object (set by start_background_workers)_persistence_ref = None# Reference to the kv object (set by start_background_workers)_kv_ref = None
def _shutdown_handler(signum, frame) -> None: # noqa: ARG001 """Handle SIGTERM/SIGINT gracefully (C5.1).
Steps: 1. Set the global _shutting_down flag to stop background loops. 2. Flush the debounce timer and save the index synchronously. 3. Run a WAL checkpoint via StateKV.teardown(). 4. Exit cleanly with code 0. """ sig_name = signal.Signals(signum).name print(f"\n[workers] Received {sig_name} — initiating graceful shutdown...")
_shutting_down.set()
# Flush in-flight persistence debounce timer and save immediately global _persistence_ref if _persistence_ref is not None: try: print("[workers] Flushing index persistence...") _persistence_ref.flush() print("[workers] Index persistence flushed.") except Exception as e: print(f"[workers] Error flushing persistence: {e}")
# WAL checkpoint — flush WAL to the main DB file global _kv_ref if _kv_ref is not None: try: print("[workers] Running WAL checkpoint...") _kv_ref.teardown() print("[workers] WAL checkpoint complete.") except Exception as e: print(f"[workers] Error during WAL checkpoint: {e}")
print("[workers] Shutdown complete.") sys.exit(0)
def _register_signal_handlers() -> None: """Register SIGTERM and SIGINT handlers (C5.1).
Skipped if the calling thread is not the main thread, because Python only allows signal handlers to be registered from the main thread. """ if threading.current_thread() is not threading.main_thread(): return try: signal.signal(signal.SIGTERM, _shutdown_handler) signal.signal(signal.SIGINT, _shutdown_handler) print("[workers] Signal handlers registered (SIGTERM, SIGINT).") except (OSError, ValueError) as e: # Some environments (e.g. Windows without signal support) may raise here print(f"[workers] Could not register signal handlers: {e}")
def _auto_forget_loop(kv) -> None: """Periodically sweep and evict stale observations (configurable via AUTO_FORGET_ENABLED).""" time.sleep(10) while not _shutting_down.is_set(): try: if os.getenv("AUTO_FORGET_ENABLED") != "false": print("[scheduler] Running auto_forget sweep...") res = functions.auto_forget(kv, dry_run=False) print(f"[scheduler] auto_forget sweep completed: {res}") except Exception as e: print(f"[scheduler] auto_forget loop error: {e}") # Sleep in 10-second chunks so we notice _shutting_down quickly for _ in range(360): # 360 × 10s = 1 hour if _shutting_down.is_set(): break time.sleep(10)
def _rebuild_index(kv) -> None: """Rebuild the BM25/vector index from scratch in a background thread.""" try: count = functions.rebuild_index(kv) print(f"[persistence] Rebuild completed: indexed {count} items.") except Exception as ex: print(f"[persistence] Rebuild failed: {ex}")
def start_background_workers(kv) -> None: """Start all background daemon threads and register signal handlers.
Called once by create_app() after the DB and indexes are initialised. Workers are daemon threads — they die automatically when the main process exits.
Args: kv: Initialised StateKV instance. """ global _kv_ref, _persistence_ref _kv_ref = kv
# Capture the persistence reference for the shutdown handler _persistence_ref = functions._index_persistence
# Register graceful shutdown signal handlers (C5.1) _register_signal_handlers()
# Rebuild search index if empty if functions._bm25_index.size == 0: print("[persistence] Search index is empty. Rebuilding in background thread...") t_rebuild = threading.Thread( target=_rebuild_index, args=(kv,), daemon=True, name="index-rebuild", ) t_rebuild.start()
# Auto-forget sweep t_forget = threading.Thread( target=_auto_forget_loop, args=(kv,), daemon=True, name="auto-forget", ) t_forget.start()3 unmodified lines4567891 unmodified line1112131415165 unmodified lines2223242526274 unmodified lines323334353637383940414211 unmodified lines54555657585960616263646566676841 unmodified lines1101111121131141153 unmodified lines1191201211221231244 unmodified lines1291301311321331341351361371381391401411421433 unmodified lines14714814915015115216 unmodified lines1691701711721731741751761771781791801811821833 unmodified lines1871881893 unmodified linesUsage:python3 sync.py restore -- download DB from HF on startuppython3 sync.py backup -- upload DB to HF (called in loop)"""import jsonimport os1 unmodified lineimport shutilimport tempfileimport timetry:from huggingface_hub import HfApi, snapshot_download, hf_hub_download5 unmodified linesHF_TOKEN = os.environ.get("HF_TOKEN", "")REPO_ID = os.environ.get("AGENTMEMORY_DATASET_REPO", "Yash030/agentmemory-python-data")DATA_DIR = os.path.expanduser("~/.agentmemory")# Only these paths are backed up/restored — everything else is ephemeralSYNC_FILES = [4 unmodified lines"second-brain",]STATE_FILE = os.path.join(DATA_DIR, ".backup_state")def get_api():return HfApi(token=HF_TOKEN)def _collect_sync_targets():"""Return list of (abs_path, repo_rel_path) for all files to sync."""targets = []11 unmodified linestargets.append((full, rel))return targetsdef _state_fingerprint(targets):entries = {}for full, rel in targets:try:s = os.stat(full)entries[rel] = (s.st_size, s.st_mtime)except OSError:passreturn json.dumps(entries, sort_keys=True)def restore():if not HF_TOKEN:41 unmodified linesprint("[sync] restore complete")def _list_repo_prefix(api, prefix):"""List files in repo matching a path prefix."""try:3 unmodified linesexcept Exception:return []def backup():if not HF_TOKEN:return4 unmodified linesprint("[sync] nothing to backup")return# Fast change detectioncurrent_state = _state_fingerprint(targets)if os.path.exists(STATE_FILE):try:if open(STATE_FILE).read() == current_state:print("[sync] no changes — skipping backup")returnexcept Exception:pass# Ensure repo existstry:3 unmodified linesapi.create_repo(REPO_ID, repo_type="dataset", private=True)except Exception as e:print(f"[sync] repo_info error: {e}")return# Stage only the targeted files16 unmodified linescommit_message="sync: periodic backup",)print("[sync] backup complete")try:open(STATE_FILE, "w").write(current_state)except Exception:passexcept Exception as e:print(f"[sync] backup error: {e}")finally:shutil.rmtree(staging, ignore_errors=True)if __name__ == "__main__":cmd = sys.argv[1] if len(sys.argv) > 1 else "backup"if cmd == "restore":3 unmodified lineselse:print(f"[sync] unknown command: {cmd}")sys.exit(1)3 unmodified lines4567891011121 unmodified line141516171819205 unmodified lines262728293031324 unmodified lines373839404142434445464748495011 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210341 unmodified lines1451461471481491501513 unmodified lines1551561571581591601614 unmodified lines1661671681691701711721731741751761771781791801813 unmodified lines18518618718818919019119219316 unmodified lines2102112122132142152162172182192202212222232242252262272282292302313 unmodified lines2352362372382392402412422433 unmodified linesUsage:python3 sync.py restore -- download DB from HF on startuppython3 sync.py backup -- upload DB to HF (called in loop)C4.1: Uses audit log high-water mark instead of mtime-based change detection.C4.2: Exposes last sync status via a .sync_state JSON file read by /health."""import jsonimport os1 unmodified lineimport shutilimport tempfileimport timeimport sqlite3try:from huggingface_hub import HfApi, snapshot_download, hf_hub_download5 unmodified linesHF_TOKEN = os.environ.get("HF_TOKEN", "")REPO_ID = os.environ.get("AGENTMEMORY_DATASET_REPO", "Yash030/agentmemory-python-data")DATA_DIR = os.path.expanduser("~/.agentmemory")DB_PATH = os.path.join(DATA_DIR, "agentmemory.db")# Only these paths are backed up/restored — everything else is ephemeralSYNC_FILES = [4 unmodified lines"second-brain",]# C4.1: High-water mark stored as JSON (replaces mtime STATE_FILE)STATE_FILE = os.path.join(DATA_DIR, ".sync_state")def get_api():return HfApi(token=HF_TOKEN)def _collect_sync_targets():"""Return list of (abs_path, repo_rel_path) for all files to sync."""targets = []11 unmodified linestargets.append((full, rel))return targetsdef _get_audit_high_water_mark() -> int:"""C4.1: Return MAX(id) from audit_log, or 0 if DB is absent/empty."""try:if not os.path.exists(DB_PATH):return 0conn = sqlite3.connect(DB_PATH, check_same_thread=False, timeout=5)try:row = conn.execute("SELECT MAX(id) FROM audit_log").fetchone()return int(row[0]) if row and row[0] is not None else 0finally:conn.close()except Exception:return 0def _load_sync_state() -> dict:"""C4.1: Load the persisted sync state dict."""if os.path.exists(STATE_FILE):try:with open(STATE_FILE, "r", encoding="utf-8") as f:return json.load(f)except Exception:passreturn {"last_synced_audit_id": 0, "last_sync_at": None, "sync_status": "never"}def _save_sync_state(state: dict) -> None:"""C4.1/C4.2: Persist the sync state dict."""try:os.makedirs(DATA_DIR, exist_ok=True)with open(STATE_FILE, "w", encoding="utf-8") as f:json.dump(state, f)except Exception as e:print(f"[sync] failed to save sync state: {e}")def restore():if not HF_TOKEN:41 unmodified linesprint("[sync] restore complete")def _list_repo_prefix(api, prefix):"""List files in repo matching a path prefix."""try:3 unmodified linesexcept Exception:return []def backup():if not HF_TOKEN:return4 unmodified linesprint("[sync] nothing to backup")return# C4.1: Compare audit log high-water mark instead of mtime fingerprintcurrent_hwm = _get_audit_high_water_mark()state = _load_sync_state()last_hwm = state.get("last_synced_audit_id", 0)if current_hwm <= last_hwm:print(f"[sync] no new audit entries (hwm={current_hwm}) — skipping backup")returnprint(f"[sync] audit HWM changed ({last_hwm} → {current_hwm}) — backing up...")# Ensure repo existstry:3 unmodified linesapi.create_repo(REPO_ID, repo_type="dataset", private=True)except Exception as e:print(f"[sync] repo_info error: {e}")# C4.2: record error statestate["sync_status"] = "error"_save_sync_state(state)return# Stage only the targeted files16 unmodified linescommit_message="sync: periodic backup",)print("[sync] backup complete")# C4.1/C4.2: update state with new HWM and timestampimport datetimestate["last_synced_audit_id"] = current_hwmstate["last_sync_at"] = datetime.datetime.utcnow().isoformat() + "Z"state["sync_status"] = "ok"_save_sync_state(state)except Exception as e:print(f"[sync] backup error: {e}")state["sync_status"] = "error"_save_sync_state(state)finally:shutil.rmtree(staging, ignore_errors=True)if __name__ == "__main__":cmd = sys.argv[1] if len(sys.argv) > 1 else "backup"if cmd == "restore":3 unmodified lineselse:print(f"[sync] unknown command: {cmd}")sys.exit(1)HF_TOKEN = os.environ.get("HF_TOKEN", "")REPO_ID = os.environ.get("AGENTMEMORY_DATASET_REPO", "Yash030/agentmemory-python-data")DATA_DIR = os.path.expanduser("~/.agentmemory")DB_PATH = os.path.join(DATA_DIR, "agentmemory.db")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""tests/test_api.py — C3.1
Integration tests for REST endpoints using the Flask test client."""import sysimport osimport jsonimport datetime
import pytest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
# ---------------------------------------------------------------------------# Fixtures# ---------------------------------------------------------------------------
@pytest.fixture(scope="module")def flask_app(tmp_path_factory): tmp_dir = tmp_path_factory.mktemp("api_test_db") db_path = str(tmp_dir / "test.db") os.environ.pop("AGENTMEMORY_SECRET", None)
from db import StateKV original_init = StateKV.__init__
def patched_init(self, db_path_arg=None, **kwargs): original_init(self, db_path=db_path, **kwargs)
StateKV.__init__ = patched_init import app as app_module flask_application = app_module.create_app() StateKV.__init__ = original_init flask_application.config["TESTING"] = True return flask_application
@pytest.fixture(scope="module")def client(flask_app): return flask_app.test_client()
def _now(): return datetime.datetime.utcnow().isoformat() + "Z"
def _post(client, url, payload): return client.post(url, data=json.dumps(payload), content_type="application/json")
# ---------------------------------------------------------------------------# POST /agentmemory/agent/observe# ---------------------------------------------------------------------------
class TestAgentObserve: def test_valid_payload_returns_201(self, client): resp = _post(client, "/agentmemory/agent/observe", { "folderPath": "/home/user/test-project", "agentId": "kiro", "text": "Implemented new authentication middleware", "timestamp": _now(), }) assert resp.status_code == 201 data = resp.get_json() assert "observationId" in data assert data["observationId"].startswith("fobs_")
def test_missing_folder_path_returns_400(self, client): resp = _post(client, "/agentmemory/agent/observe", { "agentId": "kiro", "text": "Some work", "timestamp": _now(), }) assert resp.status_code == 400
def test_missing_agent_id_returns_400(self, client): resp = _post(client, "/agentmemory/agent/observe", { "folderPath": "/home/user/proj", "text": "Some work", "timestamp": _now(), }) assert resp.status_code == 400
def test_missing_text_returns_400(self, client): resp = _post(client, "/agentmemory/agent/observe", { "folderPath": "/home/user/proj", "agentId": "kiro", "timestamp": _now(), }) assert resp.status_code == 400
# ---------------------------------------------------------------------------# POST /agentmemory/search# ---------------------------------------------------------------------------
class TestSearch: def test_search_with_query_returns_200(self, client): # Seed data first _post(client, "/agentmemory/agent/observe", { "folderPath": "/home/user/search-proj", "agentId": "kiro", "text": "Refactored the authentication system", "timestamp": _now(), }) resp = _post(client, "/agentmemory/search", {"query": "authentication"}) assert resp.status_code == 200 data = resp.get_json() assert isinstance(data, list) or isinstance(data, dict)
def test_search_missing_query_returns_400(self, client): resp = _post(client, "/agentmemory/search", {}) assert resp.status_code == 400
def test_search_empty_query_returns_400(self, client): resp = _post(client, "/agentmemory/search", {"query": " "}) assert resp.status_code == 400
# ---------------------------------------------------------------------------# GET /agentmemory/folders# ---------------------------------------------------------------------------
class TestFolders: def test_get_folders_returns_200(self, client): # Ensure at least one folder exists from earlier tests _post(client, "/agentmemory/agent/observe", { "folderPath": "/home/user/folders-check", "agentId": "kiro", "text": "Check folders endpoint", "timestamp": _now(), }) resp = client.get("/agentmemory/folders") assert resp.status_code == 200 data = resp.get_json() assert "folders" in data assert isinstance(data["folders"], list)
# ---------------------------------------------------------------------------# GET /agentmemory/health# ---------------------------------------------------------------------------
class TestHealth: def test_health_returns_200(self, client): resp = client.get("/agentmemory/health") assert resp.status_code == 200 data = resp.get_json() assert "folderCount" in data assert "observationCount" in data assert "memoryCount" in data
def test_health_status_ok(self, client): resp = client.get("/agentmemory/health") data = resp.get_json() assert data.get("status") in ("ok", "degraded")
# ---------------------------------------------------------------------------# GET /agentmemory/livez# ---------------------------------------------------------------------------
class TestLivez: def test_livez_returns_200_no_auth(self, client): resp = client.get("/agentmemory/livez") assert resp.status_code == 200 data = resp.get_json() assert data["status"] == "ok"
def test_livez_open_with_secret_set(self, client): os.environ["AGENTMEMORY_SECRET"] = "test-secret-123" try: resp = client.get("/agentmemory/livez") assert resp.status_code == 200 finally: del os.environ["AGENTMEMORY_SECRET"]
# ---------------------------------------------------------------------------# Authentication# ---------------------------------------------------------------------------
class TestAuthentication: def test_protected_endpoint_returns_401_with_wrong_token(self, client): os.environ["AGENTMEMORY_SECRET"] = "correct-secret" try: resp = client.get( "/agentmemory/audit", headers={"Authorization": "Bearer wrong-token"}, ) assert resp.status_code == 401 finally: del os.environ["AGENTMEMORY_SECRET"]
def test_protected_endpoint_passes_with_correct_token(self, client): secret = "my-test-secret-xyz" os.environ["AGENTMEMORY_SECRET"] = secret try: resp = client.get( "/agentmemory/audit", headers={"Authorization": f"Bearer {secret}"}, ) assert resp.status_code == 200 finally: del os.environ["AGENTMEMORY_SECRET"]
def test_livez_always_open_regardless_of_secret(self, client): os.environ["AGENTMEMORY_SECRET"] = "any-secret" try: resp = client.get("/agentmemory/livez") assert resp.status_code == 200 finally: del os.environ["AGENTMEMORY_SECRET"]
# ---------------------------------------------------------------------------# Additional endpoint smoke tests# ---------------------------------------------------------------------------
class TestMemoriesEndpoint: def test_memories_list_returns_200(self, client): resp = client.get("/agentmemory/memories") assert resp.status_code == 200 data = resp.get_json() assert "memories" in data
def test_remember_valid_payload_returns_201(self, client): resp = _post(client, "/agentmemory/remember", { "content": "API test memory content", "type": "fact", }) assert resp.status_code == 201
def test_forget_nonexistent_id(self, client): resp = _post(client, "/agentmemory/forget", {"memoryId": "mem_nonexistent"}) assert resp.status_code == 200
def test_graph_endpoint_returns_200(self, client): resp = client.get("/agentmemory/graph") assert resp.status_code == 200 data = resp.get_json() assert "nodes" in data assert "edges" in data
def test_mcp_tools_list_returns_200(self, client): resp = client.get("/agentmemory/mcp/tools") assert resp.status_code == 200 data = resp.get_json() assert "tools" in data tool_names = {t["name"] for t in data["tools"]} assert "agent_observe" in tool_names assert "memory_recall" in tool_names123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169"""tests/test_context.py — C1.4
Tests for context(), export_data(), and token budget enforcement."""import sysimport osimport datetime
import pytest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------
def _make_kv(tmp_path): from db import StateKV os.environ.pop("AGENTMEMORY_SECRET", None) return StateKV(db_path=str(tmp_path / "test.db"))
def _now(): return datetime.datetime.utcnow().isoformat() + "Z"
# ---------------------------------------------------------------------------# context() tests# ---------------------------------------------------------------------------
class TestContext: def test_empty_db_returns_minimal_context(self, tmp_path): """Empty DB should return a well-formed but empty context.""" from functions import context kv = _make_kv(tmp_path) result = context(kv, { "sessionId": "sess_test_empty", "project": "/home/user/my-project", "budget": 2000, }) assert isinstance(result, dict) assert "context" in result assert "blocks" in result assert "tokens" in result assert result["blocks"] == 0 assert result["tokens"] == 0
def test_raises_on_missing_session_id(self, tmp_path): from functions import context kv = _make_kv(tmp_path) with pytest.raises(ValueError): context(kv, {"project": "/home/user/proj"})
def test_raises_on_missing_project(self, tmp_path): from functions import context kv = _make_kv(tmp_path) with pytest.raises(ValueError): context(kv, {"sessionId": "sess_x"})
def test_respects_token_budget(self, tmp_path): """Context output tokens should not exceed the requested budget.""" from functions import context, lesson_save, KV kv = _make_kv(tmp_path) project = "/home/user/budget-test"
# Add many lessons to push towards the budget for i in range(20): lesson_save(kv, { "content": f"Lesson {i}: " + ("x " * 100), "project": project, "confidence": 0.9, })
budget = 500 result = context(kv, { "sessionId": "sess_budget", "project": project, "budget": budget, }) # Token estimate is len/3 — check that total tokens respects budget assert result["tokens"] <= budget + 50 # small headroom for header/footer
def test_context_includes_xml_wrapper(self, tmp_path): """Non-empty context should be wrapped in <agentmemory-context>.""" from functions import context, lesson_save kv = _make_kv(tmp_path) project = "/home/user/xml-test"
lesson_save(kv, { "content": "Always validate user input before processing", "project": project, "confidence": 0.8, })
result = context(kv, { "sessionId": "sess_xml", "project": project, "budget": 2000, })
if result["blocks"] > 0: assert "<agentmemory-context" in result["context"] assert "</agentmemory-context>" in result["context"]
def test_token_budget_env_var_respected(self, tmp_path, monkeypatch): """TOKEN_BUDGET env var should be used when no budget param given.""" from functions import context, lesson_save kv = _make_kv(tmp_path) project = "/home/user/env-budget" monkeypatch.setenv("TOKEN_BUDGET", "100")
for i in range(10): lesson_save(kv, { "content": f"Important lesson {i}: " + ("word " * 50), "project": project, "confidence": 0.9, })
result = context(kv, {"sessionId": "sess_env_budget", "project": project}) # Should use TOKEN_BUDGET=100 from env assert result["tokens"] <= 150 # with some headroom for XML wrapper
# ---------------------------------------------------------------------------# export_data() tests# ---------------------------------------------------------------------------
class TestExportData: def test_export_returns_folders_and_memories(self, tmp_path): from functions import folder_observe, remember, export_data kv = _make_kv(tmp_path)
folder_observe(kv, { "folderPath": "/home/user/export-test", "agentId": "kiro", "text": "Working on export feature", "timestamp": _now(), }) remember(kv, {"content": "Export data uses v2 format"})
result = export_data(kv, {}) assert isinstance(result, dict) assert "folders" in result or "observations" in result or "memories" in result
def test_export_empty_db(self, tmp_path): from functions import export_data kv = _make_kv(tmp_path) result = export_data(kv, {}) assert isinstance(result, dict) # Should not crash on empty DB
# ---------------------------------------------------------------------------# estimate_tokens()# ---------------------------------------------------------------------------
class TestEstimateTokens: def test_empty_string(self): from functions import estimate_tokens assert estimate_tokens("") == 0
def test_typical_text(self): from functions import estimate_tokens text = "hello world this is a test" * 10 tokens = estimate_tokens(text) # Should be approximately len/3 assert tokens == len(text) // 3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169"""A4.3 — Unit tests for IndexPersistence debounce behavior.
Tests:- 100 rapid schedule_save() calls result in exactly 1 save() call.- flush() triggers immediate save without waiting for debounce timer."""import sysimport osimport timeimport threadingimport unittest.mock as mock
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
import pytestfrom db import StateKVfrom search import SearchIndex, VectorIndexfrom functions import IndexPersistence
# Speed up debounce for testsFAST_DEBOUNCE = 0.05
def make_kv(tmp_path): return StateKV(db_path=str(tmp_path / 'test_debounce.db'))
class TestDebounce: def test_100_rapid_calls_result_in_1_save(self, tmp_path): """100 rapid schedule_save() calls must fire exactly 1 save().""" kv = make_kv(tmp_path) bm25 = SearchIndex() vector = VectorIndex()
persistence = IndexPersistence(kv, bm25, vector) persistence.DEBOUNCE_SECONDS = FAST_DEBOUNCE
save_call_count = [0]
original_save = persistence.save
def counting_save(): save_call_count[0] += 1 original_save()
with mock.patch.object(persistence, 'save', side_effect=counting_save): for _ in range(100): persistence.schedule_save() # Wait for the debounce timer to fire (2× debounce window is plenty) time.sleep(FAST_DEBOUNCE * 4)
assert save_call_count[0] == 1, ( f"Expected exactly 1 save() call; got {save_call_count[0]}" )
def test_rapid_calls_with_dirty_bm25(self, tmp_path): """schedule_save() fires exactly once even when BM25 is dirty.""" kv = make_kv(tmp_path) bm25 = SearchIndex() vector = VectorIndex()
# Add a doc so the index is dirty bm25.add({ 'id': 'obs_test1', 'sessionId': 'sess1', 'title': 'hello world', 'facts': [], 'concepts': [], 'files': [], 'type': 'other', })
persistence = IndexPersistence(kv, bm25, vector) persistence.DEBOUNCE_SECONDS = FAST_DEBOUNCE
save_call_count = [0] original_save = persistence.save
def counting_save(): save_call_count[0] += 1 original_save()
with mock.patch.object(persistence, 'save', side_effect=counting_save): for _ in range(100): persistence.schedule_save() time.sleep(FAST_DEBOUNCE * 4)
assert save_call_count[0] == 1
def test_flush_triggers_immediate_save(self, tmp_path): """flush() must call save() immediately without waiting for the debounce timer.""" kv = make_kv(tmp_path) bm25 = SearchIndex() vector = VectorIndex()
persistence = IndexPersistence(kv, bm25, vector) persistence.DEBOUNCE_SECONDS = 60.0 # very long timer — flush must bypass it
save_call_count = [0] original_save = persistence.save
def counting_save(): save_call_count[0] += 1 original_save()
with mock.patch.object(persistence, 'save', side_effect=counting_save): persistence.schedule_save() # Timer is set but hasn't fired yet (60s window) assert save_call_count[0] == 0, "save() should not have been called yet"
# flush() must cancel the timer and call save() synchronously persistence.flush()
assert save_call_count[0] == 1, ( f"flush() should trigger exactly 1 save(); got {save_call_count[0]}" )
def test_flush_after_no_pending_save_is_safe(self, tmp_path): """flush() with no pending timer should still call save() once.""" kv = make_kv(tmp_path) bm25 = SearchIndex() vector = VectorIndex()
persistence = IndexPersistence(kv, bm25, vector)
save_call_count = [0] original_save = persistence.save
def counting_save(): save_call_count[0] += 1 original_save()
with mock.patch.object(persistence, 'save', side_effect=counting_save): persistence.flush()
assert save_call_count[0] == 1
def test_subsequent_schedule_after_fire_starts_new_timer(self, tmp_path): """Two bursts of saves separated by more than DEBOUNCE_SECONDS should fire 2 saves.""" kv = make_kv(tmp_path) bm25 = SearchIndex() vector = VectorIndex()
persistence = IndexPersistence(kv, bm25, vector) persistence.DEBOUNCE_SECONDS = FAST_DEBOUNCE
save_call_count = [0] original_save = persistence.save
def counting_save(): save_call_count[0] += 1 original_save()
with mock.patch.object(persistence, 'save', side_effect=counting_save): # First burst for _ in range(10): persistence.schedule_save() # Wait for first timer to fire time.sleep(FAST_DEBOUNCE * 4)
# Second burst for _ in range(10): persistence.schedule_save() # Wait for second timer to fire time.sleep(FAST_DEBOUNCE * 4)
assert save_call_count[0] == 2, ( f"Expected 2 save() calls for two separate bursts; got {save_call_count[0]}" )7 unmodified lines8910111213147 unmodified linessys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom functions import KV, folder_graph_build, folderColor# ---------------------------------------------------------------------------7 unmodified lines8910111213147 unmodified linessys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom functions import KV, folder_graph_build, folder_color as folderColor# ---------------------------------------------------------------------------
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""C1.1 — Unit tests for observe(), strip_private_data(), and folder_observe()."""import sysimport osimport datetimeimport pytest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from db import StateKVimport functionsfrom functions import observe, folder_observe, strip_private_data, KV
# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------
def make_kv(tmp_path): return StateKV(db_path=str(tmp_path / "test.db"))
def _now() -> str: return datetime.datetime.utcnow().isoformat() + "Z"
def valid_observe_payload(**overrides): p = { "sessionId": "sess_test_001", "hookType": "post_tool_use", "timestamp": _now(), "data": {"tool_name": "read_file", "tool_input": {"path": "/src/app.py"}}, } p.update(overrides) return p
def valid_folder_payload(**overrides): p = { "folderPath": "/home/user/projects/myapp", "agentId": "test-agent", "text": "Edited the authentication module", "timestamp": _now(), } p.update(overrides) return p
# ---------------------------------------------------------------------------# observe() — valid payload# ---------------------------------------------------------------------------
class TestObserveValid: def test_returns_observation_id(self, tmp_path): kv = make_kv(tmp_path) result = observe(kv, valid_observe_payload()) assert "observationId" in result assert isinstance(result["observationId"], str) assert len(result["observationId"]) > 0
def test_observation_id_has_obs_prefix(self, tmp_path): kv = make_kv(tmp_path) result = observe(kv, valid_observe_payload()) assert result["observationId"].startswith("obs_")
def test_observation_stored_in_kv(self, tmp_path): kv = make_kv(tmp_path) result = observe(kv, valid_observe_payload(sessionId="sess_store_check")) obs_id = result["observationId"] stored = kv.get(KV.observations("sess_store_check"), obs_id) assert stored is not None assert stored["id"] == obs_id
# ---------------------------------------------------------------------------# observe() — missing required fields# ---------------------------------------------------------------------------
class TestObserveMissingFields: def test_missing_session_id_raises(self, tmp_path): kv = make_kv(tmp_path) with pytest.raises(ValueError): observe(kv, valid_observe_payload(sessionId=""))
def test_missing_session_id_none_raises(self, tmp_path): kv = make_kv(tmp_path) payload = valid_observe_payload() del payload["sessionId"] with pytest.raises(ValueError): observe(kv, payload)
def test_missing_hook_type_raises(self, tmp_path): kv = make_kv(tmp_path) with pytest.raises(ValueError): observe(kv, valid_observe_payload(hookType=""))
def test_missing_hook_type_none_raises(self, tmp_path): kv = make_kv(tmp_path) payload = valid_observe_payload() del payload["hookType"] with pytest.raises(ValueError): observe(kv, payload)
def test_missing_timestamp_raises(self, tmp_path): kv = make_kv(tmp_path) with pytest.raises(ValueError): observe(kv, valid_observe_payload(timestamp=""))
def test_missing_timestamp_none_raises(self, tmp_path): kv = make_kv(tmp_path) payload = valid_observe_payload() del payload["timestamp"] with pytest.raises(ValueError): observe(kv, payload)
# ---------------------------------------------------------------------------# strip_private_data() — redaction# ---------------------------------------------------------------------------
class TestStripPrivateData: def test_redacts_api_key_assignment(self): text = "api_key = sk-proj-abc123LONGKEY456789012345678901234567890" result = strip_private_data(text) assert "[REDACTED_SECRET]" in result # Raw key value must not appear assert "sk-proj-abc123" not in result
def test_redacts_bearer_token(self): text = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" result = strip_private_data(text) assert "[REDACTED_SECRET]" in result assert "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" not in result
def test_redacts_secret_key_pair(self): text = "secret=mysupersecretvalue12345678901234567890" result = strip_private_data(text) assert "[REDACTED_SECRET]" in result
def test_non_sensitive_text_unchanged(self): text = "Edited authentication module in src/app.py" result = strip_private_data(text) assert result == text
def test_redacts_private_xml_tags(self): text = "prefix <private>confidential info</private> suffix" result = strip_private_data(text) assert "[REDACTED]" in result assert "confidential info" not in result
def test_redacts_google_api_key(self): # AIza prefix (Google API key pattern) text = "key = AIzaSyABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" result = strip_private_data(text) assert "[REDACTED_SECRET]" in result assert "AIzaSy" not in result
# ---------------------------------------------------------------------------# MAX_OBS_PER_SESSION cap# ---------------------------------------------------------------------------
class TestObserveSessionCap: def test_cap_raises_on_fourth_observation(self, tmp_path, monkeypatch): monkeypatch.setenv("MAX_OBS_PER_SESSION", "3") kv = make_kv(tmp_path) sess = "sess_cap_test" for _ in range(3): observe(kv, valid_observe_payload(sessionId=sess)) with pytest.raises(ValueError, match="limit"): observe(kv, valid_observe_payload(sessionId=sess))
def test_cap_not_triggered_at_limit(self, tmp_path, monkeypatch): monkeypatch.setenv("MAX_OBS_PER_SESSION", "3") kv = make_kv(tmp_path) sess = "sess_cap_ok" # Exactly 3 should succeed for _ in range(3): result = observe(kv, valid_observe_payload(sessionId=sess)) assert "observationId" in result
# ---------------------------------------------------------------------------# folder_observe() — valid payload / fobs_ prefix# ---------------------------------------------------------------------------
class TestFolderObserveCore: def test_returns_observation_id(self, tmp_path): kv = make_kv(tmp_path) result = folder_observe(kv, valid_folder_payload()) assert "observationId" in result
def test_observation_id_has_fobs_prefix(self, tmp_path): kv = make_kv(tmp_path) result = folder_observe(kv, valid_folder_payload()) assert result["observationId"].startswith("fobs_")
def test_observation_stored_in_kv(self, tmp_path): kv = make_kv(tmp_path) result = folder_observe(kv, valid_folder_payload()) obs_id = result["observationId"] # normalized: "home/user/projects/myapp" normalized = "home/user/projects/myapp" stored = kv.get(KV.folder_obs(normalized, "test-agent"), obs_id) assert stored is not None assert stored["id"] == obs_id123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310"""tests/test_properties.py — C2.1
Hypothesis property-based tests for the folder-based memory system.All 8 properties from the spec.
Note: Each property test creates a fresh isolated SQLite DB per hypothesisexample using a shared counter, avoiding state accumulation between examples."""import sysimport osimport datetimeimport tempfile
import pytest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
try: from hypothesis import given, settings, assume, HealthCheck from hypothesis import strategies as st HYPOTHESIS_AVAILABLE = Trueexcept ImportError: HYPOTHESIS_AVAILABLE = False
pytestmark = pytest.mark.skipif( not HYPOTHESIS_AVAILABLE, reason="hypothesis not installed — run: pip install hypothesis")
# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------
_counter = [0]
def _fresh_kv(): """Create a brand-new isolated StateKV in a temp directory.""" from db import StateKV os.environ.pop("AGENTMEMORY_SECRET", None) _counter[0] += 1 d = tempfile.mkdtemp(prefix=f"agmem_prop_{_counter[0]}_") return StateKV(db_path=os.path.join(d, "test.db"))
def _now(): return datetime.datetime.utcnow().isoformat() + "Z"
def _safe_path(): """Strategy for valid, non-traversal folder paths.""" return st.from_regex( r"[a-zA-Z][a-zA-Z0-9_-]{0,20}/[a-zA-Z][a-zA-Z0-9_-]{0,20}", fullmatch=True, )
def _safe_agent(): return st.from_regex(r"[a-z][a-z0-9_-]{1,12}", fullmatch=True)
def _safe_text(): return st.text( alphabet=st.characters( whitelist_categories=("Lu", "Ll", "Nd", "Zs"), whitelist_characters="_-.,()", ), min_size=5, max_size=200, )
# ---------------------------------------------------------------------------# Property 1: Pair Isolation# Two distinct (folderPath, agentId) pairs never share observations.# ---------------------------------------------------------------------------
@settings(max_examples=50)@given( path1=_safe_path(), agent1=_safe_agent(), path2=_safe_path(), agent2=_safe_agent(), text=_safe_text(),)def test_property_1_pair_isolation(path1, agent1, path2, agent2, text): assume((path1, agent1) != (path2, agent2))
from functions import folder_observe, KV kv = _fresh_kv()
folder_observe(kv, {"folderPath": path1, "agentId": agent1, "text": text, "timestamp": _now()})
scope1 = KV.folder_obs(path1, agent1) scope2 = KV.folder_obs(path2, agent2)
obs1_ids = {o["id"] for o in kv.list(scope1)} obs2_ids = {o["id"] for o in kv.list(scope2)}
assert obs1_ids.isdisjoint(obs2_ids)
# ---------------------------------------------------------------------------# Property 2: Observation Count Consistency# meta.obsCount == len(kv.list(folder_obs_scope))# ---------------------------------------------------------------------------
@settings(max_examples=50)@given( path=_safe_path(), agent=_safe_agent(), texts=st.lists(_safe_text(), min_size=1, max_size=10),)def test_property_2_obs_count_consistency(path, agent, texts): from functions import folder_observe, KV kv = _fresh_kv()
for text in texts: folder_observe(kv, {"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()})
meta_scope = KV.folder_meta(path, agent) meta = kv.get(meta_scope, "meta") assert meta is not None
actual_obs = kv.list(KV.folder_obs(path, agent)) assert meta["obsCount"] == len(actual_obs)
# ---------------------------------------------------------------------------# Property 3: Index Coverage# Every written pair has a KV.folders entry.# ---------------------------------------------------------------------------
@settings(max_examples=50)@given( path=_safe_path(), agent=_safe_agent(), text=_safe_text(),)def test_property_3_index_coverage(path, agent, text): from functions import folder_observe, KV kv = _fresh_kv()
folder_observe(kv, {"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()})
index_entries = kv.list(KV.folders) normalized_path = path.replace("\\", "/").strip("/") normalized_agent = agent.strip()
matching = [ e for e in index_entries if e.get("folderPath") == normalized_path and e.get("agentId") == normalized_agent ] assert len(matching) >= 1
# ---------------------------------------------------------------------------# Property 4: Privacy Invariant# No stored obs text contains raw secrets after folder_observe().# ---------------------------------------------------------------------------
@settings(max_examples=30)@given( path=_safe_path(), agent=_safe_agent(), prefix=st.text(alphabet="abcdefghijklmnop", min_size=3, max_size=10),)def test_property_4_privacy_invariant(path, agent, prefix): from functions import folder_observe, KV kv = _fresh_kv()
secret_text = f"My api_key = sk-proj-{prefix}abc123def456ghi789jkl012 in production"
folder_observe(kv, { "folderPath": path, "agentId": agent, "text": secret_text, "timestamp": _now(), })
obs_list = kv.list(KV.folder_obs(path, agent)) for obs in obs_list: stored_text = obs.get("text", "") assert "sk-proj-" not in stored_text
# ---------------------------------------------------------------------------# Property 5: Timeline Ordering# folder_timeline() always returns results sorted newest-first.# ---------------------------------------------------------------------------
@settings(max_examples=40)@given( path=_safe_path(), agent=_safe_agent(), n=st.integers(min_value=2, max_value=8),)def test_property_5_timeline_ordering(path, agent, n): from functions import folder_observe, folder_timeline kv = _fresh_kv()
base_ts = datetime.datetime(2025, 1, 1, 0, 0, 0) for i in range(n): ts = (base_ts + datetime.timedelta(minutes=i)).isoformat() + "Z" folder_observe(kv, { "folderPath": path, "agentId": agent, "text": f"Observation number {i}", "timestamp": ts, })
results = folder_timeline(kv, limit=100, folder_path=path, agent_id=agent) timestamps = [r["timestamp"] for r in results] assert timestamps == sorted(timestamps, reverse=True)
# ---------------------------------------------------------------------------# Property 6: Forget Completeness# After forget({folderPath, agentId}), all three scopes are empty.# ---------------------------------------------------------------------------
@settings(max_examples=40)@given( path=_safe_path(), agent=_safe_agent(), texts=st.lists(_safe_text(), min_size=1, max_size=5),)def test_property_6_forget_completeness(path, agent, texts): from functions import folder_observe, forget, KV kv = _fresh_kv()
for text in texts: folder_observe(kv, {"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()})
assert len(kv.list(KV.folder_obs(path, agent))) > 0
forget(kv, {"folderPath": path, "agentId": agent})
normalized_path = path.replace("\\", "/").strip("/") normalized_agent = agent.strip() index_key = f"{normalized_path}:{normalized_agent}"
assert kv.list(KV.folder_obs(normalized_path, normalized_agent)) == [] assert kv.get(KV.folder_meta(normalized_path, normalized_agent), "meta") is None assert kv.get(KV.folders, index_key) is None
# ---------------------------------------------------------------------------# Property 7: Memory Version Uniqueness# Superseded memories have parentId; at least one memory is always latest.# ---------------------------------------------------------------------------
@settings(max_examples=30, suppress_health_check=[HealthCheck.filter_too_much])@given( base_content=st.text( alphabet="abcdefghijklmnopqrstuvwxyz ", min_size=30, max_size=80, ).filter(lambda s: len(s.split()) >= 6), n_variants=st.integers(min_value=2, max_value=4),)def test_property_7_memory_version_uniqueness(base_content, n_variants): from functions import remember, KV kv = _fresh_kv()
for i in range(n_variants): content = base_content + f" variant {i}" remember(kv, {"content": content})
all_mems = kv.list(KV.memories)
# Build sets for validation all_ids = {m["id"] for m in all_mems} superseded_ids = {m["id"] for m in all_mems if m.get("isLatest") is False} # Every superseded memory must be referenced by exactly one newer memory via parentId for m in all_mems: pid = m.get("parentId") if pid: # The parentId must point to a memory that exists and is marked isLatest=False parent = next((x for x in all_mems if x["id"] == pid), None) assert parent is not None, f"parentId {pid} not found in memories" assert parent.get("isLatest") is False, "Parent of superseding memory must be isLatest=False"
# At least one memory must be latest latest_count = sum(1 for m in all_mems if m.get("isLatest") is True) assert latest_count >= 1
# ---------------------------------------------------------------------------# Property 8: Path Normalization Idempotency# normalize(normalize(p)) == normalize(p) for all valid inputs.# ---------------------------------------------------------------------------
@settings(max_examples=100)@given( path=st.text( alphabet="abcdefghijklmnopqrstuvwxyz0123456789/_-.", min_size=2, max_size=100, ).filter(lambda p: ".." not in p and p.strip("/") != ""),)def test_property_8_path_normalization_idempotency(path): from functions import normalize_folder_path try: normalized_once = normalize_folder_path(path) normalized_twice = normalize_folder_path(normalized_once) assert normalized_once == normalized_twice except ValueError: pass