diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ed53c6da9470b353258f94db3d7d9e5d7141730a..f32608dfc0d7b19c00cb7ba4fcfeed4bd07ce7df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,31 +40,20 @@ concurrency: jobs: test: - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest 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: false matrix: - # 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] + python-version: ["3.10", "3.11", "3.12"] steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 with: - persist-credentials: false - - uses: actions/setup-node@v6 - with: - 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 test + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: pip install -e ".[dev]" + - name: Run tests + run: pytest tests/ -v --tb=short + - name: Build package + run: | + pip install build + python -m build diff --git a/.kiro/specs/folder-based-memory/tasks.md b/.kiro/specs/folder-based-memory/tasks.md index 32d0f87d24b9b3f27a3614a172c055118c20b519..58f4116ce9a08e2f6bbd83902616eefa75e84b1b 100644 --- a/.kiro/specs/folder-based-memory/tasks.md +++ b/.kiro/specs/folder-based-memory/tasks.md @@ -1,320 +1,389 @@ -# Implementation Plan: Folder-Based Memory +# Implementation Plan: agentmemory-python — Upscale & UX Overhaul ## Overview -Restructure agentmemory-python from session-based to folder-based memory. The primary unit -of 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 updated -next; 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. +The folder-based memory migration is complete. This plan covers the next phase: +structural refactoring to eliminate the god-file problem, UX uplift on the viewer +dashboard, reliability improvements to the storage and indexing layers, and new +developer-facing features. Work is organized into four parallel tracks that can be +assigned 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 -- [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 `
` 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. +## 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 ` + + diff --git a/src/viewer_helpers.py b/src/viewer_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7f51e1c14a18c0921854d8fb0ca30a7338b75b --- /dev/null +++ b/src/viewer_helpers.py @@ -0,0 +1,57 @@ +""" +Viewer HTML rendering helpers. + +Separated from app.py so the factory stays under 150 lines. +""" + +import os +import secrets +import base64 +from 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 res diff --git a/src/workers.py b/src/workers.py new file mode 100644 index 0000000000000000000000000000000000000000..26f876557c30a59c1b2750c86130ff8b03022903 --- /dev/null +++ b/src/workers.py @@ -0,0 +1,146 @@ +""" +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 index +persistence debounce queue and run a WAL checkpoint before exit. +""" + +import os +import signal +import sys +import threading +import 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() diff --git a/sync.py b/sync.py index dc3f4a9f47a209b55849fa91ef4a6ad95ceef45e..1612d201abcfa717fc9fa8456237a090defa8743 100644 --- a/sync.py +++ b/sync.py @@ -4,6 +4,9 @@ Sync agentmemory data to/from a private HF Dataset repo. Usage: python3 sync.py restore -- download DB from HF on startup python3 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 json import os @@ -11,6 +14,7 @@ import sys import shutil import tempfile import time +import sqlite3 try: from huggingface_hub import HfApi, snapshot_download, hf_hub_download @@ -22,6 +26,7 @@ except ImportError: 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") # Only these paths are backed up/restored — everything else is ephemeral SYNC_FILES = [ @@ -32,11 +37,14 @@ SYNC_DIRS = [ "second-brain", ] -STATE_FILE = os.path.join(DATA_DIR, ".backup_state") +# 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 = [] @@ -54,15 +62,42 @@ def _collect_sync_targets(): targets.append((full, rel)) return targets -def _state_fingerprint(targets): - entries = {} - for full, rel in targets: + +def _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 0 + conn = 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 0 + finally: + conn.close() + except Exception: + return 0 + + +def _load_sync_state() -> dict: + """C4.1: Load the persisted sync state dict.""" + if os.path.exists(STATE_FILE): try: - s = os.stat(full) - entries[rel] = (s.st_size, s.st_mtime) - except OSError: + with open(STATE_FILE, "r", encoding="utf-8") as f: + return json.load(f) + except Exception: pass - return json.dumps(entries, sort_keys=True) + return {"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: @@ -110,6 +145,7 @@ def restore(): print("[sync] restore complete") + def _list_repo_prefix(api, prefix): """List files in repo matching a path prefix.""" try: @@ -119,6 +155,7 @@ def _list_repo_prefix(api, prefix): except Exception: return [] + def backup(): if not HF_TOKEN: return @@ -129,15 +166,16 @@ def backup(): print("[sync] nothing to backup") return - # Fast change detection - current_state = _state_fingerprint(targets) - if os.path.exists(STATE_FILE): - try: - if open(STATE_FILE).read() == current_state: - print("[sync] no changes — skipping backup") - return - except Exception: - pass + # C4.1: Compare audit log high-water mark instead of mtime fingerprint + current_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") + return + + print(f"[sync] audit HWM changed ({last_hwm} → {current_hwm}) — backing up...") # Ensure repo exists try: @@ -147,6 +185,9 @@ def backup(): api.create_repo(REPO_ID, repo_type="dataset", private=True) except Exception as e: print(f"[sync] repo_info error: {e}") + # C4.2: record error state + state["sync_status"] = "error" + _save_sync_state(state) return # Stage only the targeted files @@ -169,15 +210,22 @@ def backup(): commit_message="sync: periodic backup", ) print("[sync] backup complete") - try: - open(STATE_FILE, "w").write(current_state) - except Exception: - pass + + # C4.1/C4.2: update state with new HWM and timestamp + import datetime + state["last_synced_audit_id"] = current_hwm + state["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": @@ -187,3 +235,9 @@ if __name__ == "__main__": else: 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") diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..41d2f84f63af4792662987f6b13957b88db659f3 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,254 @@ +""" +tests/test_api.py — C3.1 + +Integration tests for REST endpoints using the Flask test client. +""" +import sys +import os +import json +import 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_names diff --git a/tests/test_context.py b/tests/test_context.py new file mode 100644 index 0000000000000000000000000000000000000000..17d8d7a7a7b345c1af737cd9dbe10615b34078f7 --- /dev/null +++ b/tests/test_context.py @@ -0,0 +1,169 @@ +""" +tests/test_context.py — C1.4 + +Tests for context(), export_data(), and token budget enforcement. +""" +import sys +import os +import 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 .""" + 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 "" 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) // 3 diff --git a/tests/test_debounce.py b/tests/test_debounce.py new file mode 100644 index 0000000000000000000000000000000000000000..9a9dcdd679e3f07204260b3e7d7e5ae7f695e538 --- /dev/null +++ b/tests/test_debounce.py @@ -0,0 +1,169 @@ +"""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 sys +import os +import time +import threading +import unittest.mock as mock + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src')) + +import pytest +from db import StateKV +from search import SearchIndex, VectorIndex +from functions import IndexPersistence + +# Speed up debounce for tests +FAST_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]}" + ) diff --git a/tests/test_folder_graph_build.py b/tests/test_folder_graph_build.py index de8be46950fd88c9de0cb77b67373945e7c91270..3c776de3553e8424b4391fc9cf70ecc9cf55c633 100644 --- a/tests/test_folder_graph_build.py +++ b/tests/test_folder_graph_build.py @@ -8,7 +8,7 @@ import pytest sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) from db import StateKV -from functions import KV, folder_graph_build, folderColor +from functions import KV, folder_graph_build, folder_color as folderColor # --------------------------------------------------------------------------- diff --git a/tests/test_observe_core.py b/tests/test_observe_core.py new file mode 100644 index 0000000000000000000000000000000000000000..1241a6802793f8b88e2453124214b88e51bb0af2 --- /dev/null +++ b/tests/test_observe_core.py @@ -0,0 +1,207 @@ +""" +C1.1 — Unit tests for observe(), strip_private_data(), and folder_observe(). +""" +import sys +import os +import datetime +import pytest + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) + +from db import StateKV +import functions +from 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 confidential info 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_id diff --git a/tests/test_properties.py b/tests/test_properties.py new file mode 100644 index 0000000000000000000000000000000000000000..c01d6fec578eb5fad8009a1e93fb9b8d37ae7c51 --- /dev/null +++ b/tests/test_properties.py @@ -0,0 +1,310 @@ +""" +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 hypothesis +example using a shared counter, avoiding state accumulation between examples. +""" +import sys +import os +import datetime +import 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 = True +except 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 diff --git a/tests/test_remember.py b/tests/test_remember.py new file mode 100644 index 0000000000000000000000000000000000000000..05fd2f5ba0c432a84e431d9b7ad59d02c6feddf7 --- /dev/null +++ b/tests/test_remember.py @@ -0,0 +1,192 @@ +""" +tests/test_remember.py — C1.2 + +Tests for remember(), forget(), and jaccard_similarity(). +""" +import sys +import os +import 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" + + +# --------------------------------------------------------------------------- +# jaccard_similarity +# --------------------------------------------------------------------------- + +class TestJaccardSimilarity: + def test_identical_strings(self): + from functions import jaccard_similarity + assert jaccard_similarity("hello world foo", "hello world foo") == 1.0 + + def test_completely_different(self): + from functions import jaccard_similarity + score = jaccard_similarity("apple banana cherry", "xyz uvw qrs") + assert score == 0.0 + + def test_partial_overlap(self): + from functions import jaccard_similarity + score = jaccard_similarity("authentication security token", "authentication bearer token") + assert 0.0 < score < 1.0 + + def test_empty_strings(self): + from functions import jaccard_similarity + assert jaccard_similarity("", "") == 1.0 + + def test_high_similarity_above_threshold(self): + from functions import jaccard_similarity + # These two should meet or exceed the 0.7 threshold used in remember() + a = "Use parameterised queries to prevent SQL injection in all database calls" + b = "Use parameterised queries to prevent SQL injection in database operations" + assert jaccard_similarity(a, b) >= 0.7 + + def test_low_similarity_below_threshold(self): + from functions import jaccard_similarity + a = "Configure Redis as the session cache backend" + b = "Deploy the React frontend to Vercel using GitHub Actions CI" + assert jaccard_similarity(a, b) < 0.7 + + +# --------------------------------------------------------------------------- +# remember() +# --------------------------------------------------------------------------- + +class TestRemember: + def test_creates_memory_with_is_latest_true(self, tmp_path): + from functions import remember + kv = _make_kv(tmp_path) + result = remember(kv, {"content": "Always use type hints in Python functions"}) + assert result["success"] is True + mem = result["memory"] + assert mem["isLatest"] is True + assert mem["id"].startswith("mem_") + assert "Always use type hints" in mem["content"] + + def test_memory_has_required_fields(self, tmp_path): + from functions import remember + kv = _make_kv(tmp_path) + result = remember(kv, { + "content": "Prefer composition over inheritance", + "type": "architecture", + "concepts": ["design", "patterns"], + }) + mem = result["memory"] + assert "id" in mem + assert "content" in mem + assert "createdAt" in mem + assert mem["type"] == "architecture" + assert "design" in mem["concepts"] + + def test_supersedes_memory_with_high_jaccard_similarity(self, tmp_path): + from functions import remember, KV + kv = _make_kv(tmp_path) + + first = remember(kv, {"content": "Always use parameterised SQL queries to prevent injection attacks in every database call"}) + first_id = first["memory"]["id"] + + # Highly similar content — should supersede the first + second = remember(kv, {"content": "Always use parameterised SQL queries to prevent injection attacks in every database operation"}) + second_mem = second["memory"] + + # Old memory should be marked as not latest + old_mem = kv.get(KV.memories, first_id) + assert old_mem is not None + assert old_mem.get("isLatest") is False + + # New memory should be latest and point to old via parentId + assert second_mem["isLatest"] is True + assert second_mem.get("parentId") == first_id + + def test_independent_memory_with_low_jaccard_similarity(self, tmp_path): + from functions import remember, KV + kv = _make_kv(tmp_path) + + first = remember(kv, {"content": "Configure Redis as the session cache backend for high throughput"}) + first_id = first["memory"]["id"] + + # Very different content — should be independent + second = remember(kv, {"content": "Deploy the React frontend to Vercel using GitHub Actions continuous deployment"}) + second_mem = second["memory"] + + # Old memory should remain latest + old_mem = kv.get(KV.memories, first_id) + assert old_mem is not None + assert old_mem.get("isLatest") is True + + # New memory has no parentId + assert second_mem["isLatest"] is True + assert second_mem.get("parentId") is None + + # Both exist independently + all_mems = kv.list(KV.memories) + assert len(all_mems) == 2 + + def test_remember_raises_on_empty_content(self, tmp_path): + from functions import remember + kv = _make_kv(tmp_path) + with pytest.raises(ValueError, match="content is required"): + remember(kv, {"content": ""}) + + def test_remember_strips_private_data(self, tmp_path): + from functions import remember + kv = _make_kv(tmp_path) + result = remember(kv, { + "content": "API key is sk-proj-abc123def456ghi789jkl012mno345pqr678 for production" + }) + assert "sk-proj-" not in result["memory"]["content"] + assert "[REDACTED" in result["memory"]["content"] + + def test_remember_with_project_scoping(self, tmp_path): + from functions import remember + kv = _make_kv(tmp_path) + # Two very similar memories for different projects should not supersede each other + first = remember(kv, { + "content": "Always use parameterised queries in all database operations", + "project": "project-alpha", + }) + second = remember(kv, { + "content": "Always use parameterised queries in all database operations", + "project": "project-beta", + }) + # Both should remain independent (different projects) + assert first["memory"]["isLatest"] is True + assert second["memory"]["isLatest"] is True + + +# --------------------------------------------------------------------------- +# forget() +# --------------------------------------------------------------------------- + +class TestForget: + def test_forget_memory_by_id(self, tmp_path): + from functions import remember, forget, KV + kv = _make_kv(tmp_path) + result = remember(kv, {"content": "This memory will be forgotten"}) + mem_id = result["memory"]["id"] + + forget_result = forget(kv, {"memoryId": mem_id}) + assert forget_result["deleted"] >= 1 + assert kv.get(KV.memories, mem_id) is None + + def test_forget_returns_zero_for_nonexistent_memory(self, tmp_path): + from functions import forget + kv = _make_kv(tmp_path) + result = forget(kv, {"memoryId": "mem_nonexistent_id"}) + # Should still succeed (memory was already gone) — deleted may be 0 or 1 + assert "deleted" in result diff --git a/tests/test_route_regressions.py b/tests/test_route_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..bfa95c3c83d415f9af2f0bcb8ff647a2b61d4163 --- /dev/null +++ b/tests/test_route_regressions.py @@ -0,0 +1,648 @@ +""" +Route regression tests for the blueprint split (Task A1.3). + +Validates that every endpoint from all 7 blueprints is reachable and returns +the expected HTTP status codes after the monolithic app.py was split into +src/routes/{observations, memories, search, graph, health, mcp, migration}.py. + +Tests use the Flask test client — no running server required. +The AGENTMEMORY_SECRET env var is NOT set so all auth checks pass through. +""" +import sys +import os +import json +import datetime + +import pytest + +# Ensure src/ is on the path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- + +@pytest.fixture(scope="module") +def flask_app(tmp_path_factory): + """ + Create a fully-configured Flask application using create_app(). + + Uses a temp SQLite database so the test suite never touches the real DB. + Background workers are started but are daemon threads — they exit when + the process exits; this does not affect test correctness. + """ + tmp_dir = tmp_path_factory.mktemp("route_regression_db") + db_path = str(tmp_dir / "test.db") + + # Point the server at an isolated DB + os.environ["AGENTMEMORY_DB_PATH"] = db_path + # Ensure no auth requirement during tests + os.environ.pop("AGENTMEMORY_SECRET", None) + + import app as app_module + from db import StateKV + + # Patch StateKV to use tmp db before create_app() initialises it + original_init = StateKV.__init__ + + def patched_init(self, db_path=None, **kwargs): + original_init(self, db_path=str(tmp_dir / "test.db"), **kwargs) + + StateKV.__init__ = patched_init + 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 a Flask test client bound to the module-scoped app.""" + return flask_app.test_client() + + +# --------------------------------------------------------------------------- +# Helper +# --------------------------------------------------------------------------- + +def _now_iso() -> str: + return datetime.datetime.utcnow().isoformat() + "Z" + + +def _post_json(client, url, payload): + return client.post( + url, + data=json.dumps(payload), + content_type="application/json", + ) + + +# =========================================================================== +# Blueprint 1: health.py +# GET /agentmemory/livez +# GET /agentmemory/health +# GET /agentmemory/audit +# GET /agentmemory/config/flags +# =========================================================================== + +class TestHealthBlueprint: + def test_livez_no_auth_required(self, client): + """GET /livez must respond 200 without any auth token (always open).""" + resp = client.get("/agentmemory/livez") + assert resp.status_code == 200 + data = resp.get_json() + assert data["status"] == "ok" + assert "service" in data + + def test_livez_returns_service_name(self, client): + resp = client.get("/agentmemory/livez") + data = resp.get_json() + assert data["service"] == "agentmemory" + + def test_health_returns_200(self, client): + resp = client.get("/agentmemory/health") + assert resp.status_code == 200 + data = resp.get_json() + # Folder-based health check fields (REQ-047) + assert "folderCount" in data + assert "observationCount" in data + assert "memoryCount" in data + + def test_audit_returns_200(self, client): + resp = client.get("/agentmemory/audit") + assert resp.status_code == 200 + data = resp.get_json() + assert "entries" in data + + def test_config_flags_returns_200(self, client): + resp = client.get("/agentmemory/config/flags") + assert resp.status_code == 200 + data = resp.get_json() + assert "flags" in data + assert "version" in data + + +# =========================================================================== +# Blueprint 2: observations.py +# POST /agentmemory/observe +# POST /agentmemory/agent/observe +# GET /agentmemory/folders +# GET /agentmemory/folder/observations +# =========================================================================== + +class TestObservationsBlueprint: + def test_agent_observe_valid_payload(self, client): + """POST /agent/observe with valid payload returns 201 with observationId.""" + payload = { + "folderPath": "/home/user/proj-test", + "agentId": "kiro", + "text": "Added a new feature to the app", + "timestamp": _now_iso(), + } + resp = _post_json(client, "/agentmemory/agent/observe", payload) + assert resp.status_code == 201 + data = resp.get_json() + assert "observationId" in data + assert data["observationId"].startswith("fobs_") + + def test_agent_observe_missing_folder_path_returns_400(self, client): + """POST /agent/observe missing folderPath returns 400.""" + payload = {"agentId": "kiro", "text": "some work", "timestamp": _now_iso()} + resp = _post_json(client, "/agentmemory/agent/observe", payload) + assert resp.status_code == 400 + + def test_agent_observe_missing_agent_id_returns_400(self, client): + """POST /agent/observe missing agentId returns 400.""" + payload = {"folderPath": "/home/user/proj", "text": "some work", "timestamp": _now_iso()} + resp = _post_json(client, "/agentmemory/agent/observe", payload) + assert resp.status_code == 400 + + def test_agent_observe_missing_text_returns_400(self, client): + """POST /agent/observe missing text returns 400.""" + payload = {"folderPath": "/home/user/proj", "agentId": "kiro", "timestamp": _now_iso()} + resp = _post_json(client, "/agentmemory/agent/observe", payload) + assert resp.status_code == 400 + + def test_folders_list_returns_200(self, client): + """GET /folders returns 200 with a folders list.""" + # Seed at least one observation first + _post_json(client, "/agentmemory/agent/observe", { + "folderPath": "/home/user/proj-folders-test", + "agentId": "kiro", + "text": "Folders test observation", + "timestamp": _now_iso(), + }) + resp = client.get("/agentmemory/folders") + assert resp.status_code == 200 + data = resp.get_json() + assert "folders" in data + assert isinstance(data["folders"], list) + + def test_folder_observations_returns_200(self, client): + """GET /folder/observations with valid params returns 200.""" + # Seed an observation first + fp = "/home/user/proj-obs-test" + _post_json(client, "/agentmemory/agent/observe", { + "folderPath": fp, + "agentId": "kiro", + "text": "Obs for folder/observations test", + "timestamp": _now_iso(), + }) + resp = client.get("/agentmemory/folder/observations?folderPath=home/user/proj-obs-test&agentId=kiro") + assert resp.status_code == 200 + data = resp.get_json() + assert "observations" in data + + def test_folder_observations_missing_params_returns_400(self, client): + """GET /folder/observations without required params returns 400.""" + resp = client.get("/agentmemory/folder/observations") + assert resp.status_code == 400 + + def test_legacy_observe_endpoint_returns_400_or_201(self, client): + """POST /observe endpoint exists (legacy hook) — doesn't 404.""" + payload = { + "folderPath": "/home/user/proj", + "agentId": "kiro", + "text": "legacy observe call", + "timestamp": _now_iso(), + } + resp = _post_json(client, "/agentmemory/observe", payload) + # The legacy endpoint exists — expect either success or a controlled error, never 404 + assert resp.status_code != 404 + + +# =========================================================================== +# Blueprint 3: memories.py +# POST /agentmemory/remember +# POST /agentmemory/agent/remember +# GET /agentmemory/memories +# POST /agentmemory/forget +# =========================================================================== + +class TestMemoriesBlueprint: + def test_remember_valid_payload(self, client): + """POST /remember with valid payload returns 201.""" + payload = { + "content": "Always use parameterised queries for SQL", + "type": "fact", + "concepts": ["sql", "security"], + } + resp = _post_json(client, "/agentmemory/remember", payload) + assert resp.status_code == 201 + data = resp.get_json() + assert "memory" in data + + def test_agent_remember_valid_payload(self, client): + """POST /agent/remember with content returns 201.""" + payload = { + "content": "The project uses SQLite with WAL mode", + "agentId": "kiro", + "type": "architecture", + "concepts": ["sqlite", "wal"], + } + resp = _post_json(client, "/agentmemory/agent/remember", payload) + assert resp.status_code == 201 + + def test_agent_remember_missing_content_returns_400(self, client): + """POST /agent/remember without content returns 400.""" + resp = _post_json(client, "/agentmemory/agent/remember", {"agentId": "kiro"}) + assert resp.status_code == 400 + + def test_memories_list_returns_200(self, client): + """GET /memories returns 200 with memories list.""" + resp = client.get("/agentmemory/memories") + assert resp.status_code == 200 + data = resp.get_json() + assert "memories" in data + assert isinstance(data["memories"], list) + + def test_memories_list_latest_only(self, client): + """GET /memories?latest=true filters to only latest memories.""" + resp = client.get("/agentmemory/memories?latest=true") + assert resp.status_code == 200 + data = resp.get_json() + # All returned memories should be latest=True or isLatest not False + for mem in data["memories"]: + assert mem.get("isLatest") is not False + + def test_forget_memory_by_id(self, client): + """POST /forget with memoryId deletes a global memory.""" + # Create a memory first + create_resp = _post_json(client, "/agentmemory/remember", { + "content": "This memory will be forgotten", + "type": "fact", + }) + mem_id = create_resp.get_json()["memory"]["id"] + # Forget it + resp = _post_json(client, "/agentmemory/forget", {"memoryId": mem_id}) + assert resp.status_code == 200 + data = resp.get_json() + assert data["deleted"] >= 1 + + def test_forget_folder_pair(self, client): + """POST /forget with folderPath+agentId clears folder observations.""" + # Seed an observation + fp = "/home/user/proj-to-forget" + _post_json(client, "/agentmemory/agent/observe", { + "folderPath": fp, + "agentId": "kiro", + "text": "Some work that will be forgotten", + "timestamp": _now_iso(), + }) + resp = _post_json(client, "/agentmemory/forget", { + "folderPath": fp, + "agentId": "kiro", + }) + assert resp.status_code == 200 + data = resp.get_json() + assert "deleted" in data + assert data["deleted"] >= 1 + + +# =========================================================================== +# Blueprint 4: search.py +# POST /agentmemory/search +# POST /agentmemory/timeline +# =========================================================================== + +class TestSearchBlueprint: + def test_search_with_query_returns_200(self, client): + """POST /search with a query returns 200.""" + # Seed something searchable first + _post_json(client, "/agentmemory/agent/observe", { + "folderPath": "/home/user/proj-search-test", + "agentId": "kiro", + "text": "Implemented authentication middleware for the app", + "timestamp": _now_iso(), + }) + resp = _post_json(client, "/agentmemory/search", {"query": "authentication"}) + assert resp.status_code == 200 + + def test_search_missing_query_returns_400(self, client): + """POST /search without query returns 400.""" + resp = _post_json(client, "/agentmemory/search", {}) + assert resp.status_code == 400 + + def test_search_with_folder_filter(self, client): + """POST /search with folderPath filter returns 200.""" + resp = _post_json(client, "/agentmemory/search", { + "query": "test", + "folderPath": "/home/user/proj-search-test", + "agentId": "kiro", + }) + assert resp.status_code == 200 + + def test_timeline_returns_200(self, client): + """POST /timeline returns 200 with observations list.""" + resp = _post_json(client, "/agentmemory/timeline", {}) + assert resp.status_code == 200 + data = resp.get_json() + assert "observations" in data + assert isinstance(data["observations"], list) + + def test_timeline_with_filters_returns_200(self, client): + """POST /timeline with folder/agent filters returns 200.""" + resp = _post_json(client, "/agentmemory/timeline", { + "folderPath": "/home/user/proj-search-test", + "agentId": "kiro", + "limit": 10, + }) + assert resp.status_code == 200 + + def test_timeline_results_sorted_descending(self, client): + """Timeline results are sorted newest-first (REQ-071).""" + fp = "/home/user/proj-timeline-order" + # Seed observations with distinct timestamps + for i in range(3): + ts = datetime.datetime(2025, 6, 1, 10, i, 0).isoformat() + "Z" + _post_json(client, "/agentmemory/agent/observe", { + "folderPath": fp, "agentId": "kiro", + "text": f"Observation {i}", "timestamp": ts, + }) + resp = _post_json(client, "/agentmemory/timeline", { + "folderPath": fp, "agentId": "kiro", + }) + assert resp.status_code == 200 + data = resp.get_json() + timestamps = [o["timestamp"] for o in data["observations"]] + assert timestamps == sorted(timestamps, reverse=True) + + +# =========================================================================== +# Blueprint 5: graph.py +# GET /agentmemory/graph +# GET /agentmemory/graph/stats +# POST /agentmemory/graph/query +# POST /agentmemory/graph/build +# =========================================================================== + +class TestGraphBlueprint: + def test_graph_returns_200(self, client): + """GET /graph returns 200 with nodes and edges.""" + resp = client.get("/agentmemory/graph") + assert resp.status_code == 200 + data = resp.get_json() + assert "nodes" in data + assert "edges" in data + + def test_graph_stats_returns_200(self, client): + """GET /graph/stats returns 200.""" + resp = client.get("/agentmemory/graph/stats") + assert resp.status_code == 200 + data = resp.get_json() + assert "nodes" in data + assert "edges" in data + + def test_graph_query_returns_200(self, client): + """POST /graph/query returns 200.""" + resp = _post_json(client, "/agentmemory/graph/query", {}) + assert resp.status_code == 200 + + def test_graph_build_returns_200(self, client): + """POST /graph/build returns 200.""" + resp = _post_json(client, "/agentmemory/graph/build", {}) + assert resp.status_code == 200 + + def test_graph_nodes_have_required_fields(self, client): + """Graph nodes contain id, label, folderPath, agentIds, obsCount, color (REQ-024).""" + # Seed some data + _post_json(client, "/agentmemory/agent/observe", { + "folderPath": "/home/user/proj-graph-check", + "agentId": "kiro", + "text": "Graph node field check", + "timestamp": _now_iso(), + }) + resp = client.get("/agentmemory/graph") + data = resp.get_json() + if data["nodes"]: + node = data["nodes"][0] + for field in ("id", "label", "folderPath", "agentIds", "obsCount", "color"): + assert field in node, f"Missing field '{field}' on graph node" + + +# =========================================================================== +# Blueprint 6: mcp.py +# GET /agentmemory/mcp/tools +# POST /agentmemory/mcp/tools +# =========================================================================== + +class TestMcpBlueprint: + def test_mcp_tools_list_returns_200(self, client): + """GET /mcp/tools returns 200 with a tools list.""" + resp = client.get("/agentmemory/mcp/tools") + assert resp.status_code == 200 + data = resp.get_json() + assert "tools" in data + assert isinstance(data["tools"], list) + assert len(data["tools"]) > 0 + + def test_mcp_tools_contains_required_tools(self, client): + """The expected MCP tools are all present in the schema.""" + resp = client.get("/agentmemory/mcp/tools") + tool_names = {t["name"] for t in resp.get_json()["tools"]} + required_tools = { + "agent_observe", + "memory_recall", + "memory_save", + "agent_remember", + "memory_diagnose", + "memory_forget", + "memory_export", + "memory_smart_search", + "memory_folders", + "memory_folder_observations", + "memory_timeline", + } + assert required_tools.issubset(tool_names), \ + f"Missing tools: {required_tools - tool_names}" + + def test_mcp_tool_call_agent_observe(self, client): + """POST /mcp/tools agent_observe returns 200.""" + payload = { + "name": "agent_observe", + "arguments": { + "folderPath": "/home/user/proj-mcp-test", + "agentId": "kiro", + "text": "MCP observe test", + "timestamp": _now_iso(), + }, + } + resp = _post_json(client, "/agentmemory/mcp/tools", payload) + assert resp.status_code == 200 + data = resp.get_json() + assert "content" in data + + def test_mcp_tool_call_memory_recall(self, client): + """POST /mcp/tools memory_recall returns 200.""" + resp = _post_json(client, "/agentmemory/mcp/tools", { + "name": "memory_recall", + "arguments": {"query": "authentication"}, + }) + assert resp.status_code == 200 + + def test_mcp_tool_call_memory_diagnose(self, client): + """POST /mcp/tools memory_diagnose returns folderCount etc.""" + resp = _post_json(client, "/agentmemory/mcp/tools", { + "name": "memory_diagnose", + "arguments": {}, + }) + assert resp.status_code == 200 + data = resp.get_json() + result = json.loads(data["content"][0]["text"]) + assert "folderCount" in result + assert "observationCount" in result + + def test_mcp_tool_call_memory_folders(self, client): + """POST /mcp/tools memory_folders returns list.""" + resp = _post_json(client, "/agentmemory/mcp/tools", { + "name": "memory_folders", + "arguments": {}, + }) + assert resp.status_code == 200 + + def test_mcp_tool_call_memory_timeline(self, client): + """POST /mcp/tools memory_timeline returns list.""" + resp = _post_json(client, "/agentmemory/mcp/tools", { + "name": "memory_timeline", + "arguments": {"limit": 10}, + }) + assert resp.status_code == 200 + + def test_mcp_tool_unknown_name_returns_400(self, client): + """POST /mcp/tools with unknown tool name returns 400.""" + resp = _post_json(client, "/agentmemory/mcp/tools", { + "name": "nonexistent_tool_xyz", + "arguments": {}, + }) + assert resp.status_code == 400 + + def test_mcp_tool_missing_name_returns_400(self, client): + """POST /mcp/tools without name returns 400.""" + resp = _post_json(client, "/agentmemory/mcp/tools", {"arguments": {}}) + assert resp.status_code == 400 + + +# =========================================================================== +# Blueprint 7: migration.py +# POST /agentmemory/migrate +# =========================================================================== + +class TestMigrationBlueprint: + def test_migrate_dry_run_returns_200(self, client): + """POST /migrate with dry_run=true returns 200 with counts.""" + resp = _post_json(client, "/agentmemory/migrate", {"dry_run": True}) + assert resp.status_code == 200 + data = resp.get_json() + assert "migrated_sessions" in data + assert "migrated_observations" in data + assert "errors" in data + + def test_migrate_without_body_defaults_to_no_dry_run(self, client): + """POST /migrate with empty body returns 200.""" + resp = _post_json(client, "/agentmemory/migrate", {}) + assert resp.status_code == 200 + + +# =========================================================================== +# Blueprint registration completeness +# =========================================================================== + +class TestBlueprintRegistration: + def test_all_expected_endpoints_registered(self, flask_app): + """All 7 blueprints contribute at least one route each.""" + registered_rules = {rule.rule for rule in flask_app.url_map.iter_rules()} + + # observations.py + assert "/agentmemory/agent/observe" in registered_rules + assert "/agentmemory/folders" in registered_rules + assert "/agentmemory/folder/observations" in registered_rules + + # memories.py + assert "/agentmemory/remember" in registered_rules + assert "/agentmemory/memories" in registered_rules + assert "/agentmemory/forget" in registered_rules + + # search.py + assert "/agentmemory/search" in registered_rules + assert "/agentmemory/timeline" in registered_rules + + # graph.py + assert "/agentmemory/graph" in registered_rules + assert "/agentmemory/graph/stats" in registered_rules + assert "/agentmemory/graph/query" in registered_rules + + # health.py + assert "/agentmemory/livez" in registered_rules + assert "/agentmemory/health" in registered_rules + assert "/agentmemory/audit" in registered_rules + assert "/agentmemory/config/flags" in registered_rules + + # mcp.py + assert "/agentmemory/mcp/tools" in registered_rules + + # migration.py + assert "/agentmemory/migrate" in registered_rules + + def test_no_routes_return_404_from_blueprints(self, client): + """None of the expected blueprint routes return 404.""" + get_routes = [ + "/agentmemory/livez", + "/agentmemory/health", + "/agentmemory/folders", + "/agentmemory/memories", + "/agentmemory/graph", + "/agentmemory/graph/stats", + "/agentmemory/audit", + "/agentmemory/config/flags", + "/agentmemory/mcp/tools", + ] + for route in get_routes: + resp = client.get(route) + assert resp.status_code != 404, f"Route {route} returned 404" + + def test_cors_headers_present_on_responses(self, client): + """CORS after_request hook adds the expected headers.""" + resp = client.get( + "/agentmemory/livez", + headers={"Origin": "http://localhost:3000"}, + ) + assert resp.status_code == 200 + # The CORS hook in create_app() should have added these headers + assert "Access-Control-Allow-Headers" in resp.headers + assert "Access-Control-Allow-Methods" in resp.headers + + def test_auth_returns_401_when_secret_set(self, client, flask_app): + """When AGENTMEMORY_SECRET is configured, missing token returns 401 on protected routes. + + /agentmemory/audit requires auth; /agentmemory/livez and /agentmemory/health are open. + """ + os.environ["AGENTMEMORY_SECRET"] = "test-secret-token" + try: + resp = client.get("/agentmemory/audit") + assert resp.status_code == 401 + finally: + del os.environ["AGENTMEMORY_SECRET"] + + def test_auth_passes_with_correct_bearer_token(self, client, flask_app): + """Correct Bearer token passes auth on protected endpoints.""" + secret = "test-secret-token-correct" + 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): + """GET /livez is always unauthenticated, even when secret is set (REQ-057).""" + os.environ["AGENTMEMORY_SECRET"] = "some-secret" + try: + resp = client.get("/agentmemory/livez") + assert resp.status_code == 200 + finally: + del os.environ["AGENTMEMORY_SECRET"] diff --git a/tests/test_search.py b/tests/test_search.py new file mode 100644 index 0000000000000000000000000000000000000000..e52e2119c2225bbe2909838aa0c8b2ad363c1c43 --- /dev/null +++ b/tests/test_search.py @@ -0,0 +1,235 @@ +""" +tests/test_search.py — C1.3 + +Tests for SearchIndex, HybridSearch, and synonym expansion. +""" +import sys +import os + +import pytest + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) + + +# --------------------------------------------------------------------------- +# SearchIndex unit tests +# --------------------------------------------------------------------------- + +class TestSearchIndex: + def _make_obs(self, obs_id, title, narrative="", concepts=None, obs_type="other"): + return { + "id": obs_id, + "sessionId": "sess_test", + "title": title, + "narrative": narrative, + "concepts": concepts or [], + "files": [], + "type": obs_type, + } + + def test_add_and_exact_match_returns_rank_one(self): + from search import SearchIndex + idx = SearchIndex() + obs = self._make_obs("obs_001", "authentication middleware refactor") + idx.add(obs) + results = idx.search("authentication middleware") + assert len(results) > 0 + assert results[0]["obsId"] == "obs_001" + + def test_prefix_matching(self): + from search import SearchIndex + idx = SearchIndex() + obs = self._make_obs("obs_002", "authentication token validation") + idx.add(obs) + results = idx.search("authen") + assert any(r["obsId"] == "obs_002" for r in results) + + def test_synonym_expansion_db_conn(self): + """'db conn' should find document indexed with 'database connection'.""" + from search import SearchIndex + idx = SearchIndex() + obs = self._make_obs("obs_003", "database connection pooling setup", "configure database connection pool") + idx.add(obs) + results = idx.search("db conn") + assert any(r["obsId"] == "obs_003" for r in results) + + def test_remove_document(self): + from search import SearchIndex + idx = SearchIndex() + obs = self._make_obs("obs_004", "deploy kubernetes service mesh") + idx.add(obs) + idx.remove("obs_004") + results = idx.search("kubernetes") + assert not any(r["obsId"] == "obs_004" for r in results) + + def test_empty_index_returns_empty(self): + from search import SearchIndex + idx = SearchIndex() + results = idx.search("anything") + assert results == [] + + def test_multiple_docs_rank_order(self): + from search import SearchIndex + idx = SearchIndex() + idx.add(self._make_obs("obs_a", "authentication login system", "user authentication flow")) + idx.add(self._make_obs("obs_b", "database migration script", "run database migration")) + idx.add(self._make_obs("obs_c", "deployment pipeline CI", "CI CD pipeline deployment")) + + results = idx.search("authentication") + assert results[0]["obsId"] == "obs_a" + + def test_size_property(self): + from search import SearchIndex + idx = SearchIndex() + assert idx.size == 0 + idx.add(self._make_obs("x1", "title one")) + idx.add(self._make_obs("x2", "title two")) + assert idx.size == 2 + idx.remove("x1") + assert idx.size == 1 + + def test_clear(self): + from search import SearchIndex + idx = SearchIndex() + idx.add(self._make_obs("x1", "something")) + idx.clear() + assert idx.size == 0 + assert idx.search("something") == [] + + def test_dirty_flag_set_on_add(self): + from search import SearchIndex + idx = SearchIndex() + assert idx._dirty is False + idx.add(self._make_obs("x1", "test dirty flag")) + assert idx._dirty is True + + def test_dirty_flag_set_on_remove(self): + from search import SearchIndex + idx = SearchIndex() + idx.add(self._make_obs("x1", "test remove dirty")) + idx._dirty = False # reset manually + idx.remove("x1") + assert idx._dirty is True + + def test_dirty_flag_reset_after_restore(self): + from search import SearchIndex + idx = SearchIndex() + idx.add(self._make_obs("x1", "test restore")) + data = idx.serialize_data() + idx2 = SearchIndex() + idx2.restore_from_data(data) + assert idx2._dirty is False + + def test_has_method(self): + from search import SearchIndex + idx = SearchIndex() + obs = self._make_obs("obs_has", "has method test") + assert not idx.has("obs_has") + idx.add(obs) + assert idx.has("obs_has") + idx.remove("obs_has") + assert not idx.has("obs_has") + + +# --------------------------------------------------------------------------- +# VectorIndex unit tests +# --------------------------------------------------------------------------- + +class TestVectorIndex: + def test_dirty_flag_on_add(self): + from search import VectorIndex + vi = VectorIndex() + assert vi._dirty is False + vi.add("v1", "sess", [0.1, 0.2, 0.3]) + assert vi._dirty is True + + def test_dirty_flag_on_remove(self): + from search import VectorIndex + vi = VectorIndex() + vi.add("v1", "sess", [0.1, 0.2, 0.3]) + vi._dirty = False + vi.remove("v1") + assert vi._dirty is True + + def test_dirty_flag_reset_after_restore(self): + from search import VectorIndex + vi = VectorIndex() + vi.add("v1", "sess", [0.1, 0.2, 0.3]) + data = vi.serialize_data() + vi2 = VectorIndex() + vi2.restore_from_data(data) + assert vi2._dirty is False + + +# --------------------------------------------------------------------------- +# HybridSearch in BM25-only mode +# --------------------------------------------------------------------------- + +class TestHybridSearchBM25Only: + def _make_obs(self, obs_id, title, narrative=""): + return { + "id": obs_id, + "sessionId": "sess_hybrid", + "title": title, + "narrative": narrative, + "concepts": [], + "files": [], + "type": "other", + } + + def test_hybrid_bm25_only_returns_same_results_as_search_index(self): + from search import SearchIndex, VectorIndex, HybridSearch + + bm25 = SearchIndex() + vector = VectorIndex() + + docs = [ + self._make_obs("h1", "authentication middleware implementation"), + self._make_obs("h2", "database migration scripts"), + self._make_obs("h3", "deployment kubernetes configuration"), + ] + for d in docs: + bm25.add(d) + + # HybridSearch with no embedding provider — BM25 only + hybrid = HybridSearch(bm25, vector, None, None) + bm25_direct = bm25.search("authentication", 10) + hybrid_results = hybrid.search("authentication", 10) + + bm25_ids = [r["obsId"] for r in bm25_direct] + hybrid_ids = [r["obsId"] for r in hybrid_results] + + # The same document should appear at the top in both + assert bm25_ids[0] == hybrid_ids[0] + + def test_hybrid_returns_empty_for_no_matches(self): + from search import SearchIndex, VectorIndex, HybridSearch + bm25 = SearchIndex() + hybrid = HybridSearch(bm25, VectorIndex(), None, None) + assert hybrid.search("zzznomatch", 10) == [] + + +# --------------------------------------------------------------------------- +# Serialization round-trip +# --------------------------------------------------------------------------- + +class TestSearchIndexSerialization: + def test_roundtrip_preserves_search_results(self): + from search import SearchIndex + idx = SearchIndex() + idx.add({ + "id": "rt_001", + "sessionId": "sess_rt", + "title": "serialization round trip test", + "narrative": "verify that index survives serialize/restore", + "concepts": ["test"], + "files": [], + "type": "other", + }) + + data = idx.serialize_data() + idx2 = SearchIndex() + idx2.restore_from_data(data) + + results = idx2.search("serialization round trip") + assert any(r["obsId"] == "rt_001" for r in results)