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 `