From dcec3bfea52c0fb1d2c64deb727eab3f9f740199 Mon Sep 17 00:00:00 2001 From: Emanuilo Jovanovic Date: Sun, 22 Nov 2026 17:52:10 +0100 Subject: [PATCH 1/6] refactor(search): search reads index.db only through MemoryIndex search.py ran its own SQL on index.db (4 queries, its own sqlite3 import). MemoryIndex now offers what search needs: - embeddings_version(): (count, highest id) of the embedded chunks, the key search caches its embedding matrix on. - chunk_embeddings(): (chunk id, embedding) of every embedded chunk. - keyword_matches(fts_query, limit): the FTS5/BM25 matches; a query SQLite rejects is logged and finds nothing, as before. - get_chunk(id): one stored chunk. search.py keeps the ranking (query words, score weights, decay, MMR) and has no SQL or sqlite3 import left. HybridSearch._merge is split into _normalise, _combine and _load. MemoryIndex is 345 lines (was 419): the table definitions and the telegram_images migration are module functions (_create_schema), with the SQL text unchanged, since SQLite stores it in sqlite_master. Baseline tightened: search.py's sqlite3 use and _merge's complexity and locals are gone, MemoryIndex 419 -> 345 lines. Same results: a fixture vault searched old vs new (300 searches over hybrid, keyword-heavy, no-decay and MMR settings, file filters, the embedding cache, images) gives identical results and scores, and the schema in sqlite_master is identical. --- .code-shape/baseline.json | 9 +- memclaw/index.py | 167 +++++++++++++++++++++++++------------- memclaw/search.py | 125 ++++++++++++---------------- tests/test_index.py | 32 ++++++++ 4 files changed, 195 insertions(+), 138 deletions(-) diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index 249d985..e5013fa 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -6,8 +6,7 @@ "cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend.run_one_shot": 23, "cognitive-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 24, "cognitive-complexity|memclaw/index.py|MemoryIndex.chunk_text": 27, - "cognitive-complexity|memclaw/prompts.py|masked_input": 16, - "cognitive-complexity|memclaw/search.py|HybridSearch._merge": 17 + "cognitive-complexity|memclaw/prompts.py|masked_input": 16 }, "mypy": { "type-errors|memclaw/backends/claude.py|": 1, @@ -22,11 +21,9 @@ "too-many-locals|memclaw/backends/claude.py|ClaudeAgentBackend.wizard_setup": 17, "too-many-locals|memclaw/backends/cursor.py|CursorAgentBackend.run_turn": 20, "too-many-locals|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 19, - "too-many-locals|memclaw/index.py|MemoryIndex.chunk_text": 17, - "too-many-locals|memclaw/search.py|HybridSearch._merge": 22 + "too-many-locals|memclaw/index.py|MemoryIndex.chunk_text": 17 }, "ruff": { - "banned-api|memclaw/search.py|sqlite3 in ": 1, "function-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13, "function-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 11, "function-complexity|memclaw/index.py|MemoryIndex.chunk_text": 12, @@ -40,7 +37,7 @@ "sizes": { "class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 501, "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419, - "class-lines|memclaw/index.py|MemoryIndex": 419, + "class-lines|memclaw/index.py|MemoryIndex": 345, "file-lines|memclaw/backends/claude.py|": 775, "file-lines|memclaw/backends/cursor.py|": 604, "file-lines|memclaw/tools.py|": 577, diff --git a/memclaw/index.py b/memclaw/index.py index f2880e6..85aaf8d 100644 --- a/memclaw/index.py +++ b/memclaw/index.py @@ -6,6 +6,7 @@ from pathlib import Path import numpy as np +from loguru import logger from .config import MemclawConfig from .openai_client import OpenAIClient @@ -20,23 +21,14 @@ class Chunk: embedding: np.ndarray | None = None -class MemoryIndex: - """SQLite-based index with FTS5 keyword search and numpy vector search. +def _create_schema(db: sqlite3.Connection) -> None: + """Create the tables, the FTS5 index and its triggers if missing. - Embeddings are stored as BLOBs in SQLite and cosine similarity is computed - in-memory with numpy — lightweight and dependency-free beyond numpy. + SQLite stores each statement's text, indentation included, in + sqlite_master: keep the text unchanged so every database has the same + schema. """ - - def __init__(self, config: MemclawConfig): - self.config = config - self._openai: OpenAIClient | None = None - self._init_db() - - def _init_db(self): - self.db = sqlite3.connect(str(self.config.db_path)) - self.db.execute("PRAGMA journal_mode=WAL") - - self.db.execute(""" + db.execute(""" CREATE TABLE IF NOT EXISTS chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, file_path TEXT NOT NULL, @@ -49,7 +41,7 @@ def _init_db(self): ) """) - self.db.execute(""" + db.execute(""" CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( content, content='chunks', @@ -58,19 +50,19 @@ def _init_db(self): ) """) - # Triggers keep FTS5 in sync with the chunks table. - self.db.execute(""" + # Triggers keep FTS5 in sync with the chunks table. + db.execute(""" CREATE TRIGGER IF NOT EXISTS chunks_ai AFTER INSERT ON chunks BEGIN INSERT INTO chunks_fts(rowid, content) VALUES (new.id, new.content); END """) - self.db.execute(""" + db.execute(""" CREATE TRIGGER IF NOT EXISTS chunks_ad AFTER DELETE ON chunks BEGIN INSERT INTO chunks_fts(chunks_fts, rowid, content) VALUES ('delete', old.id, old.content); END """) - self.db.execute(""" + db.execute(""" CREATE TRIGGER IF NOT EXISTS chunks_au AFTER UPDATE ON chunks BEGIN INSERT INTO chunks_fts(chunks_fts, rowid, content) VALUES ('delete', old.id, old.content); @@ -78,15 +70,15 @@ def _init_db(self): END """) - self.db.execute(""" + db.execute(""" CREATE TABLE IF NOT EXISTS file_meta ( file_path TEXT PRIMARY KEY, mtime REAL NOT NULL ) """) - # Embedding cache — avoids redundant OpenAI API calls for unchanged content. - self.db.execute(""" + # Embedding cache — avoids redundant OpenAI API calls for unchanged content. + db.execute(""" CREATE TABLE IF NOT EXISTS embedding_cache ( content_hash TEXT PRIMARY KEY, embedding BLOB NOT NULL, @@ -95,8 +87,8 @@ def _init_db(self): ) """) - # Telegram image registry — maps file_ids to descriptions for retrieval. - self.db.execute(""" + # Telegram image registry — maps file_ids to descriptions for retrieval. + db.execute(""" CREATE TABLE IF NOT EXISTS telegram_images ( id INTEGER PRIMARY KEY AUTOINCREMENT, file_id TEXT NOT NULL, @@ -107,8 +99,8 @@ def _init_db(self): ) """) - # Platform-agnostic image registry (Telegram, WhatsApp, Slack, etc.) - self.db.execute(""" + # Platform-agnostic image registry (Telegram, WhatsApp, Slack, etc.) + db.execute(""" CREATE TABLE IF NOT EXISTS platform_images ( id INTEGER PRIMARY KEY AUTOINCREMENT, platform TEXT NOT NULL, @@ -120,25 +112,59 @@ def _init_db(self): ) """) - self._migrate_telegram_images() - self.db.commit() + _migrate_telegram_images(db) - def _migrate_telegram_images(self): - """One-time migration: copy telegram_images rows into platform_images.""" - existing = self.db.execute( - "SELECT COUNT(*) FROM platform_images WHERE platform = 'telegram'" - ).fetchone()[0] - if existing > 0: - return - telegram_count = self.db.execute("SELECT COUNT(*) FROM telegram_images").fetchone()[0] - if telegram_count == 0: - return - self.db.execute(""" + +def _migrate_telegram_images(db: sqlite3.Connection) -> None: + """One-time migration: copy telegram_images rows into platform_images.""" + existing = db.execute( + "SELECT COUNT(*) FROM platform_images WHERE platform = 'telegram'" + ).fetchone()[0] + if existing > 0: + return + telegram_count = db.execute("SELECT COUNT(*) FROM telegram_images").fetchone()[0] + if telegram_count == 0: + return + db.execute(""" INSERT INTO platform_images (platform, media_ref, description, caption, embedding, created_at) SELECT 'telegram', file_id, description, caption, embedding, created_at FROM telegram_images """) + +def _image_dict(row: tuple, score: float | None = None) -> dict: + """(id, platform, media_ref, description, caption, created_at, ...) + as the dict the bots send images from.""" + return { + "id": row[0], + "platform": row[1], + "media_ref": row[2], + "file_id": row[2], # backward compat alias + "description": row[3], + "caption": row[4], + "created_at": row[5], + "score": score, + } + + +class MemoryIndex: + """SQLite-based index with FTS5 keyword search and numpy vector search. + + Embeddings are stored as BLOBs in SQLite and cosine similarity is computed + in-memory with numpy — lightweight and dependency-free beyond numpy. + """ + + def __init__(self, config: MemclawConfig): + self.config = config + self._openai: OpenAIClient | None = None + self._init_db() + + def _init_db(self): + self.db = sqlite3.connect(str(self.config.db_path)) + self.db.execute("PRAGMA journal_mode=WAL") + _create_schema(self.db) + self.db.commit() + @property def openai(self) -> OpenAIClient: if self._openai is None: @@ -344,6 +370,48 @@ async def sync(self) -> bool: self.db.commit() return changed + # ------------------------------------------------------------------ + # Queries for HybridSearch + # ------------------------------------------------------------------ + + def embeddings_version(self) -> tuple[int, int]: + """(count, highest id) of the chunks that have an embedding. It + changes whenever chunks change (re-indexing a file gives its rows + new, higher ids), so a search can cache the embeddings until then.""" + count, max_id = self.db.execute( + "SELECT COUNT(*), COALESCE(MAX(id), 0) FROM chunks WHERE embedding IS NOT NULL" + ).fetchone() + return count, max_id + + def chunk_embeddings(self) -> list[tuple[int, np.ndarray]]: + """(chunk id, embedding) of every chunk that has one.""" + rows = self.db.execute( + "SELECT id, embedding FROM chunks WHERE embedding IS NOT NULL" + ).fetchall() + return [(chunk_id, self.deserialize_embedding(blob)) for chunk_id, blob in rows] + + def keyword_matches(self, fts_query: str, limit: int | None) -> list[tuple[int, float]]: + """(chunk id, FTS5 rank) of the best *limit* matches (all with None) + for an FTS5 query, best first. FTS5's rank is BM25 negated: more + negative is a better match. Empty if the query fails.""" + try: + return self.db.execute( + """SELECT rowid, rank FROM chunks_fts + WHERE chunks_fts MATCH ? ORDER BY rank LIMIT ?""", + (fts_query, -1 if limit is None else limit), + ).fetchall() + except sqlite3.Error as exc: + logger.warning("Keyword search failed for {q!r}: {exc}", q=fts_query, exc=exc) + return [] + + def get_chunk(self, chunk_id: int) -> Chunk | None: + """The stored chunk with this id (without its embedding).""" + row = self.db.execute( + "SELECT file_path, line_start, line_end, content FROM chunks WHERE id = ?", + (chunk_id,), + ).fetchone() + return Chunk(*row) if row else None + # ------------------------------------------------------------------ # Platform-agnostic image registry # ------------------------------------------------------------------ @@ -393,7 +461,7 @@ def search_platform_images( np.dot(query_embedding, stored_emb) / (np.linalg.norm(query_embedding) * np.linalg.norm(stored_emb) + 1e-8) ) - results.append(self._image_dict(row, score=similarity)) + results.append(_image_dict(row, score=similarity)) results.sort(key=lambda x: x["score"], reverse=True) return results[:limit] @@ -409,24 +477,9 @@ def get_platform_images(self, ids: list[int], platform: str | None = None) -> li (image_id, platform, platform), ).fetchone() if row is not None: - found[row[0]] = self._image_dict(row) + found[row[0]] = _image_dict(row) return list(found.values()) - @staticmethod - def _image_dict(row: tuple, score: float | None = None) -> dict: - """(id, platform, media_ref, description, caption, created_at, ...) - as the dict the bots send images from.""" - return { - "id": row[0], - "platform": row[1], - "media_ref": row[2], - "file_id": row[2], # backward compat alias - "description": row[3], - "caption": row[4], - "created_at": row[5], - "score": score, - } - # ------------------------------------------------------------------ # Stats # ------------------------------------------------------------------ diff --git a/memclaw/search.py b/memclaw/search.py index 800e70a..d26a00e 100644 --- a/memclaw/search.py +++ b/memclaw/search.py @@ -2,13 +2,11 @@ import math import re -import sqlite3 from dataclasses import dataclass from datetime import date from pathlib import Path import numpy as np -from loguru import logger from .config import MemclawConfig from .index import MemoryIndex @@ -98,35 +96,18 @@ def _vector_search( ) -> list[tuple[int, float]]: # Spec #8 Phase 1: use the cached embedding matrix while the chunks # haven't changed, avoiding repeated deserialization from SQLite. - current_count, max_id = self.index.db.execute( - "SELECT COUNT(*), COALESCE(MAX(id), 0) FROM chunks WHERE embedding IS NOT NULL" - ).fetchone() - - if current_count == 0: + version = self.index.embeddings_version() + if version[0] == 0: return [] - if ( - self._embedding_cache is not None - and (current_count, max_id) == self._cache_key - ): - matrix, ids = self._embedding_cache - else: - rows = self.index.db.execute( - "SELECT id, embedding FROM chunks WHERE embedding IS NOT NULL" - ).fetchall() - + if self._embedding_cache is None or version != self._cache_key: + rows = self.index.chunk_embeddings() if not rows: return [] - - ids = [] - embeddings = [] - for chunk_id, blob in rows: - ids.append(chunk_id) - embeddings.append(MemoryIndex.deserialize_embedding(blob)) - - matrix = np.stack(embeddings) - self._embedding_cache = (matrix, ids) - self._cache_key = (current_count, max_id) + ids = [chunk_id for chunk_id, _ in rows] + self._embedding_cache = (np.stack([emb for _, emb in rows]), ids) + self._cache_key = version + matrix, ids = self._embedding_cache norms = np.linalg.norm(matrix, axis=1) q_norm = np.linalg.norm(query_embedding) @@ -157,16 +138,7 @@ def _keyword_search(self, query: str, limit: int | None) -> list[tuple[int, floa fts_query = self._fts_query(query) if fts_query is None: return [] - try: - rows = self.index.db.execute( - """SELECT rowid, rank FROM chunks_fts - WHERE chunks_fts MATCH ? ORDER BY rank LIMIT ?""", - (fts_query, -1 if limit is None else limit), - ).fetchall() - except sqlite3.Error as exc: - logger.warning("Keyword search failed for {q!r}: {exc}", q=fts_query, exc=exc) - return [] - + rows = self.index.keyword_matches(fts_query, limit) if not rows: return [] @@ -186,57 +158,41 @@ def _merge( limit: int, file_filter: str | None = None, ) -> list[SearchResult]: + combined = self._combine(_normalise(vector_hits), dict(keyword_hits)) + return self._load(combined, limit, file_filter) + + def _combine( + self, v_scores: dict[int, float], k_scores: dict[int, float], + ) -> list[tuple[int, float, str]]: + """(chunk id, weighted score, match type) for every hit, best first.""" vw = self.config.memory.vector_weight tw = self.config.memory.text_weight - - # Normalise vector scores to 0-1 - if vector_hits: - max_v = max(s for _, s in vector_hits) - min_v = min(s for _, s in vector_hits) - range_v = max_v - min_v - v_scores = { - cid: (s - min_v) / range_v if range_v > 0 else 1.0 - for cid, s in vector_hits - } - else: - v_scores = {} - - k_scores = dict(keyword_hits) - - all_ids = set(v_scores) | set(k_scores) combined: list[tuple[int, float, str]] = [] - for cid in all_ids: - vs = v_scores.get(cid, 0.0) - ks = k_scores.get(cid, 0.0) - final = vw * vs + tw * ks - if cid in v_scores and cid in k_scores: - match_type = "hybrid" - elif cid in v_scores: - match_type = "vector" - else: - match_type = "keyword" - combined.append((cid, final, match_type)) - + for cid in set(v_scores) | set(k_scores): + final = vw * v_scores.get(cid, 0.0) + tw * k_scores.get(cid, 0.0) + combined.append((cid, final, _match_type(cid in v_scores, cid in k_scores))) combined.sort(key=lambda x: x[1], reverse=True) + return combined + def _load( + self, combined: list[tuple[int, float, str]], limit: int, file_filter: str | None, + ) -> list[SearchResult]: + """The first *limit* of *combined* whose file path contains + *file_filter*, as SearchResults.""" results: list[SearchResult] = [] for cid, score, match_type in combined: if len(results) >= limit: break - row = self.index.db.execute( - "SELECT file_path, line_start, line_end, content FROM chunks WHERE id = ?", - (cid,), - ).fetchone() - if row and (file_filter is None or file_filter in row[0]): + chunk = self.index.get_chunk(cid) + if chunk and (file_filter is None or file_filter in chunk.file_path): results.append(SearchResult( - file_path=row[0], - line_start=row[1], - line_end=row[2], - content=row[3], + file_path=chunk.file_path, + line_start=chunk.line_start, + line_end=chunk.line_end, + content=chunk.content, score=score, match_type=match_type, )) - return results # ------------------------------------------------------------------ @@ -332,3 +288,22 @@ def _apply_mmr( selected.append(remaining.pop(best_idx)) return selected + + +def _normalise(vector_hits: list[tuple[int, float]]) -> dict[int, float]: + """Vector scores scaled to 0-1 (all 1.0 when they are equal).""" + if not vector_hits: + return {} + max_v = max(s for _, s in vector_hits) + min_v = min(s for _, s in vector_hits) + range_v = max_v - min_v + return { + cid: (s - min_v) / range_v if range_v > 0 else 1.0 + for cid, s in vector_hits + } + + +def _match_type(in_vector: bool, in_keyword: bool) -> str: + if in_vector and in_keyword: + return "hybrid" + return "vector" if in_vector else "keyword" diff --git a/tests/test_index.py b/tests/test_index.py index 4f108fd..ee8afcb 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -237,3 +237,35 @@ async def test_stats_count_images_from_every_platform(self, idx: MemoryIndex): await idx.store_platform_image("whatsapp", "wa-1", "a cat") await idx.store_platform_image("telegram", "tg-1", "a dog") assert idx.get_stats()["images"] == 2 + + +class TestSearchQueries: + """The queries HybridSearch runs through the index (it has no SQL of its own).""" + + @pytest.mark.asyncio + async def test_chunks_and_their_embeddings(self, cfg: MemclawConfig, idx: MemoryIndex): + assert idx.embeddings_version() == (0, 0) + assert idx.chunk_embeddings() == [] + path = cfg.memory_subdir / "2026-01-01.md" + path.write_text("## 10:00 - Note\n\nmy dog is called Max\n\n---\n") + await idx.index_file(path) + + [(chunk_id, emb)] = idx.chunk_embeddings() + assert idx.embeddings_version() == (1, chunk_id) + assert emb.dtype == np.float32 + chunk = idx.get_chunk(chunk_id) + assert (chunk.file_path, chunk.line_start, chunk.line_end) == (str(path), 0, 4) + assert "my dog is called Max" in chunk.content + assert idx.get_chunk(chunk_id + 1) is None + + @pytest.mark.asyncio + async def test_keyword_matches(self, cfg: MemclawConfig, idx: MemoryIndex): + path = cfg.memory_subdir / "2026-01-01.md" + path.write_text("## 10:00 - Note\n\nmy dog is called Max\n\n---\n") + await idx.index_file(path) + [(chunk_id, rank)] = idx.keyword_matches('"max"', limit=None) + assert idx.get_chunk(chunk_id) is not None and rank < 0 + assert idx.keyword_matches('"nothing"', limit=5) == [] + + def test_a_malformed_keyword_query_finds_nothing(self, idx: MemoryIndex): + assert idx.keyword_matches('"unterminated', limit=5) == [] From 5d3af13370469495fbf09c670688b4aec1702a0d Mon Sep 17 00:00:00 2001 From: Emanuilo Jovanovic Date: Sun, 22 Nov 2026 17:54:16 +0100 Subject: [PATCH 2/6] refactor(memory): the notes and search move into memclaw/memory/ - store.py becomes memory/notes.py (MemoryStore), search.py becomes memory/search.py (HybridSearch, SearchResult). memclaw.memory exports them next to Consolidator; agent, cli, tools and the tests import them from there. Only import paths change. - Tests mirror the move: tests/memory/test_notes.py, test_search.py. Guards: the memory-via-package contract now also covers memory.notes and memory.search, and the core layer loses store and search (they're part of the memory layer). The top-level folder is down to 11 modules (limit 12), so its baseline entry is gone. Library users: `from memclaw.memory import MemoryStore, HybridSearch` (docs/library.md, docs/upgrading.md). --- .code-shape/baseline.json | 3 +-- CONTRIBUTING.md | 4 ++-- docs/library.md | 3 +-- docs/upgrading.md | 2 ++ memclaw/agent.py | 4 +--- memclaw/cli.py | 3 +-- memclaw/memory/__init__.py | 19 ++++++++++++++---- memclaw/memory/consolidation.py | 2 +- memclaw/{store.py => memory/notes.py} | 2 +- memclaw/{ => memory}/search.py | 4 ++-- memclaw/tools.py | 3 +-- pyproject.toml | 20 ++++++++++++------- tests/conftest.py | 3 +-- tests/e2e/test_retrieval_e2e.py | 3 +-- tests/memory/test_consolidation.py | 3 +-- tests/{test_store.py => memory/test_notes.py} | 2 +- tests/{ => memory}/test_search.py | 2 +- tests/test_agent.py | 2 +- tests/test_index.py | 2 +- 19 files changed, 48 insertions(+), 38 deletions(-) rename memclaw/{store.py => memory/notes.py} (98%) rename memclaw/{ => memory}/search.py (99%) rename tests/{test_store.py => memory/test_notes.py} (98%) rename tests/{ => memory}/test_search.py (99%) diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index e5013fa..520bef5 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -40,8 +40,7 @@ "class-lines|memclaw/index.py|MemoryIndex": 345, "file-lines|memclaw/backends/claude.py|": 775, "file-lines|memclaw/backends/cursor.py|": 604, - "file-lines|memclaw/tools.py|": 577, - "package-files|memclaw/|": 13 + "file-lines|memclaw/tools.py|": 576 } }, "version": 1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e53b48b..eba5dc2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,12 +66,12 @@ Claude Code uses `.claude/settings.json` automatically: when Claude runs `git co **memclaw's layout rules** are the import-linter contracts under `[tool.importlinter]` in `pyproject.toml`. `code-shape check` runs them (on their own: `lint-imports`): -- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → `memory` → core modules (`search`, `store`, `reminders`, …) → `index` → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. +- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → `memory` → core modules (`reminders`, `sessions`, …) → `index` → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. - **No cycles inside subpackages** such as `memclaw.backends` and `memclaw.bot`. - **Chat platforms are independent**: `bot/telegram.py`, `bot/slack.py` and `bot/whatsapp.py` never import each other. What they share (voice to text, link summaries, the prompts, the agent call, reminders) is in `bot/inbound.py`. A new platform is one module with a `run(config)` plus one line in `PLATFORMS` (`bot/__init__.py`); the CLI and the setup wizard start and list platforms only through that registry. - **Chat SDKs stay in their platform module**: only those three modules import `telegram`, `slack_bolt` or `neonize`. - **One OpenAI adapter**: only `openai_client.py` imports `openai`; everyone else calls `OpenAIClient`. -- **Memory through its package**: other code uses what `memclaw.memory` exports (`Consolidator`), not the modules inside. `memory/consolidation.py` is the only code that writes MEMORY.md; it reaches the LLM through the backend the agent hands it, so it doesn't import `memclaw.backends`. +- **Memory through its package**: other code uses what `memclaw.memory` exports (`MemoryStore`, `HybridSearch`, `Consolidator`, …), not the modules inside (`notes.py`, `search.py`, `consolidation.py`, …). `memory/consolidation.py` is the only code that writes MEMORY.md; it reaches the LLM through the backend the agent hands it, so it doesn't import `memclaw.backends`. - **Backends are swappable**: only `memclaw.backends` itself imports the concrete backend modules (`claude.py`, `cursor.py`, …). Everyone else goes through `memclaw.backends` / `memclaw.backends.base`. - **`memclaw.defaults` stands alone**: the Cursor hook script there is copied out and run on its own, so it can't import memclaw. diff --git a/docs/library.md b/docs/library.md index 3378998..78eddc9 100644 --- a/docs/library.md +++ b/docs/library.md @@ -5,9 +5,8 @@ The store, index and search work without the agent — only `OPENAI_API_KEY` is ```python import asyncio from memclaw.config import MemclawConfig -from memclaw.store import MemoryStore from memclaw.index import MemoryIndex -from memclaw.search import HybridSearch +from memclaw.memory import HybridSearch, MemoryStore async def main(): config = MemclawConfig() diff --git a/docs/upgrading.md b/docs/upgrading.md index e3611d5..c9318b7 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -4,6 +4,8 @@ Nothing changes for the `memclaw` command or your `.env`. In the library, `MemclawConfig`'s settings moved into groups: `MemclawConfig(openai_api_key="k")` is now `MemclawConfig(openai=OpenAISettings(api_key="k"))`, and `config.slack_bot_token` is `config.slack.bot_token`, `config.mmr_lambda` is `config.memory.mmr_lambda`, and so on. `memory_dir`, `agent_backend` and `platform` stay where they were. See [Using Memclaw as a Library](library.md). +The store and search moved into the `memclaw.memory` package: `from memclaw.store import MemoryStore` is now `from memclaw.memory import MemoryStore`, and `from memclaw.search import HybridSearch, SearchResult` is now `from memclaw.memory import HybridSearch, SearchResult`. They work as before. + ## From 2.x to 3.0 ```bash diff --git a/memclaw/agent.py b/memclaw/agent.py index 6ec5e97..4ede237 100644 --- a/memclaw/agent.py +++ b/memclaw/agent.py @@ -32,11 +32,9 @@ load_agent_instructions, load_permanent_memory, ) -from .memory import Consolidator +from .memory import Consolidator, HybridSearch, MemoryStore from .reminders import ReminderScheduler -from .search import HybridSearch from .sessions import SessionStore -from .store import MemoryStore from .tools import ToolExecutor # Per-turn memory search results. Kept small because every context block diff --git a/memclaw/cli.py b/memclaw/cli.py index e7690e9..87cf65d 100644 --- a/memclaw/cli.py +++ b/memclaw/cli.py @@ -11,9 +11,8 @@ from .bot import PLATFORMS from .config import MemclawConfig, reload_env_file from .index import MemoryIndex -from .search import HybridSearch +from .memory import HybridSearch, MemoryStore from .setup import needs_setup, print_logo, print_probe_report, run_setup -from .store import MemoryStore console = Console() diff --git a/memclaw/memory/__init__.py b/memclaw/memory/__init__.py index db76517..707bb88 100644 --- a/memclaw/memory/__init__.py +++ b/memclaw/memory/__init__.py @@ -1,10 +1,21 @@ -"""Memclaw's memory subsystem. +"""Memclaw's memory subsystem: the notes, how they are searched, and +MEMORY.md. + +Public: + +- `MemoryStore` (notes.py): writes and lists the Markdown notes, the daily + files under memory/ that are the complete record. +- `HybridSearch`, `SearchResult` (search.py): ranks chunks of the notes for + a query (vector + keyword, recency decay, near-duplicates dropped). +- `Consolidator` (consolidation.py): distills the daily notes into + MEMORY.md, and is the only code that writes it. refs.py checks the + references it writes. -Public: `Consolidator`, which distills the daily notes into MEMORY.md (and -is the only code that writes it); `refs.py` checks the references it writes. Other code imports from `memclaw.memory`, not from the modules inside. """ from .consolidation import Consolidator +from .notes import MemoryStore +from .search import HybridSearch, SearchResult -__all__ = ["Consolidator"] +__all__ = ["Consolidator", "HybridSearch", "MemoryStore", "SearchResult"] diff --git a/memclaw/memory/consolidation.py b/memclaw/memory/consolidation.py index 4f5e3d3..7ee30c8 100644 --- a/memclaw/memory/consolidation.py +++ b/memclaw/memory/consolidation.py @@ -24,7 +24,7 @@ from ..config import MemclawConfig from ..index import MemoryIndex -from ..store import MemoryStore +from .notes import MemoryStore from .refs import check_references # After a failed consolidation, wait this long before trying again rather diff --git a/memclaw/store.py b/memclaw/memory/notes.py similarity index 98% rename from memclaw/store.py rename to memclaw/memory/notes.py index 63f92eb..68c32e5 100644 --- a/memclaw/store.py +++ b/memclaw/memory/notes.py @@ -4,7 +4,7 @@ from datetime import date, datetime from pathlib import Path -from .config import MemclawConfig +from ..config import MemclawConfig class MemoryStore: diff --git a/memclaw/search.py b/memclaw/memory/search.py similarity index 99% rename from memclaw/search.py rename to memclaw/memory/search.py index d26a00e..da87807 100644 --- a/memclaw/search.py +++ b/memclaw/memory/search.py @@ -8,8 +8,8 @@ import numpy as np -from .config import MemclawConfig -from .index import MemoryIndex +from ..config import MemclawConfig +from ..index import MemoryIndex # Keyword-query tokenizer: words and numbers (same notion of a token as # FTS5's unicode61 tokenizer). Very common words are dropped — they match diff --git a/memclaw/tools.py b/memclaw/tools.py index ba07744..f26c3c0 100644 --- a/memclaw/tools.py +++ b/memclaw/tools.py @@ -10,9 +10,8 @@ from .config import MemclawConfig from .index import MemoryIndex +from .memory import HybridSearch, MemoryStore, SearchResult from .reminders import ReminderScheduler -from .search import HybridSearch, SearchResult -from .store import MemoryStore # ── Tool definitions (JSON schema) ─────────────────────────────────── diff --git a/pyproject.toml b/pyproject.toml index b2acc07..7419777 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -132,7 +132,7 @@ ignore_names = [ [tool.shape.concepts] # The ideas a change is usually about (tracked in `code-shape report`, never a # gate): words that name each one in code, and the module that should own it. -"memory notes (daily files)" = { terms = ["MemoryStore", "daily_file", "memory_save"], home = "memclaw/store.py" } +"memory notes (daily files)" = { terms = ["MemoryStore", "daily_file", "memory_save"], home = "memclaw/memory/notes.py" } "MEMORY.md + consolidation" = { terms = ["consolidat", "MEMORY\\.md", "permanent_memory"], home = "memclaw/memory/consolidation.py" } "search + index" = { terms = ["HybridSearch", "MemoryIndex", "embedding"], home = "memclaw/index.py" } "reminders" = { terms = ["remind"], home = "memclaw/reminders.py" } @@ -178,12 +178,13 @@ layers = [ "backends", # The memory tools the agent can call. "tools", - # The memory subsystem (memclaw.memory): MEMORY.md consolidation, the only - # writer of MEMORY.md. It builds on the modules below and reaches the LLM - # through the backend the agent hands it, so it doesn't import backends. + # The memory subsystem (memclaw.memory): the notes, search over them, and + # MEMORY.md consolidation (the only writer of MEMORY.md). It builds on the + # modules below and reaches the LLM through the backend the agent hands + # it, so it doesn't import backends. "memory", # Independent building blocks (`|`: they don't import each other). - "search | store | reminders | sessions | prompts | instructions", + "reminders | sessions | prompts | instructions", # SQLite + embeddings index, used by search. "index", # The OpenAI adapter (embeddings, transcription, chat), used by index and bot. @@ -243,9 +244,14 @@ allowed_importers = ["memclaw.openai_client"] [[tool.importlinter.contracts]] id = "memory-via-package" -name = "Only memclaw.memory imports its own modules: everyone else uses what memclaw.memory exports (e.g. Consolidator)" +name = "Only memclaw.memory imports its own modules: everyone else uses what memclaw.memory exports (MemoryStore, HybridSearch, Consolidator, ...)" type = "protected" -protected_modules = ["memclaw.memory.consolidation", "memclaw.memory.refs"] +protected_modules = [ + "memclaw.memory.consolidation", + "memclaw.memory.notes", + "memclaw.memory.refs", + "memclaw.memory.search", +] allowed_importers = ["memclaw.memory"] [[tool.importlinter.contracts]] diff --git a/tests/conftest.py b/tests/conftest.py index 3228419..174ac72 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,8 +12,7 @@ from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings from memclaw.index import MemoryIndex -from memclaw.search import HybridSearch, SearchResult -from memclaw.store import MemoryStore +from memclaw.memory import HybridSearch, MemoryStore, SearchResult class _FakeEmbeddings: diff --git a/tests/e2e/test_retrieval_e2e.py b/tests/e2e/test_retrieval_e2e.py index 21fb288..1187344 100644 --- a/tests/e2e/test_retrieval_e2e.py +++ b/tests/e2e/test_retrieval_e2e.py @@ -7,9 +7,8 @@ from memclaw.agent import MemclawAgent from memclaw.index import MemoryIndex +from memclaw.memory import HybridSearch, MemoryStore from memclaw.openai_client import OpenAIClient -from memclaw.search import HybridSearch -from memclaw.store import MemoryStore from memclaw.tools import ToolExecutor from .conftest import days_ago, write_daily diff --git a/tests/memory/test_consolidation.py b/tests/memory/test_consolidation.py index f306ed7..0ad170b 100644 --- a/tests/memory/test_consolidation.py +++ b/tests/memory/test_consolidation.py @@ -18,9 +18,8 @@ from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings from memclaw.index import MemoryIndex -from memclaw.memory import Consolidator +from memclaw.memory import Consolidator, MemoryStore from memclaw.memory.consolidation import _CONSOLIDATION_BUDGET_CHARS as BUDGET -from memclaw.store import MemoryStore @pytest.fixture diff --git a/tests/test_store.py b/tests/memory/test_notes.py similarity index 98% rename from tests/test_store.py rename to tests/memory/test_notes.py index fbcb6ea..bae6ae2 100644 --- a/tests/test_store.py +++ b/tests/memory/test_notes.py @@ -5,7 +5,7 @@ from pathlib import Path from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings -from memclaw.store import MemoryStore +from memclaw.memory import MemoryStore def _make_store(tmp_path: Path) -> tuple[MemoryStore, MemclawConfig]: diff --git a/tests/test_search.py b/tests/memory/test_search.py similarity index 99% rename from tests/test_search.py rename to tests/memory/test_search.py index eafd541..dcafc4c 100644 --- a/tests/test_search.py +++ b/tests/memory/test_search.py @@ -9,7 +9,7 @@ from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings from memclaw.index import MemoryIndex -from memclaw.search import HybridSearch, SearchResult +from memclaw.memory import HybridSearch, SearchResult # ──────────────────────────────────────────────────────────────────── diff --git a/tests/test_agent.py b/tests/test_agent.py index f68bb15..2763ac8 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -21,7 +21,7 @@ from memclaw.backends.base import TurnResult from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings -from memclaw.search import SearchResult +from memclaw.memory import SearchResult # ──────────────────────────────────────────────────────────────────── diff --git a/tests/test_index.py b/tests/test_index.py index ee8afcb..92d685f 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -158,7 +158,7 @@ def test_empty_text(self, idx: MemoryIndex): class TestEntryChunking: def test_each_entry_is_its_own_chunk(self, cfg: MemclawConfig, idx: MemoryIndex): - from memclaw.store import MemoryStore + from memclaw.memory import MemoryStore store = MemoryStore(cfg) store.save("First entry about apples.") From 5701b945c9c34c24e1dd6ee40f29257fc2ab725f Mon Sep 17 00:00:00 2001 From: Emanuilo Jovanovic Date: Sun, 22 Nov 2026 17:55:45 +0100 Subject: [PATCH 3/6] refactor(index): chunking gets its own module, memclaw/chunking.py MemoryIndex.chunk_text was the most tangled function left in the index (cognitive complexity 27, 17 locals). It is now chunk_text(text, file_path, target_words=, overlap_words=) in chunking.py, with the running state in a small _Chunker (add a line, flush a chunk, keep the overlap after a size split). chunking.py has no I/O and imports nothing from memclaw; Chunk moves there too. MemoryIndex is under the 300-line class limit now, so its baseline entry is gone, with chunk_text's three. Guards: chunking sits in the layer below index, next to openai_client. It joins memclaw/memory/ with the index in the next commit. Same chunks: 300 random notes (headings, `---` lines, blank lines, long lines) indexed with five chunk-size/overlap settings give the same 5,713 chunks, line ranges and text as before. Tests: tests/test_chunking.py (was part of test_index.py), plus two cases for the size split. --- .code-shape/baseline.json | 6 +-- memclaw/chunking.py | 88 +++++++++++++++++++++++++++++++++++++++ memclaw/index.py | 77 +++------------------------------- pyproject.toml | 5 ++- tests/test_chunking.py | 63 ++++++++++++++++++++++++++++ tests/test_index.py | 34 --------------- 6 files changed, 161 insertions(+), 112 deletions(-) create mode 100644 memclaw/chunking.py create mode 100644 tests/test_chunking.py diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index 520bef5..73ebb86 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -5,7 +5,6 @@ "cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 39, "cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend.run_one_shot": 23, "cognitive-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 24, - "cognitive-complexity|memclaw/index.py|MemoryIndex.chunk_text": 27, "cognitive-complexity|memclaw/prompts.py|masked_input": 16 }, "mypy": { @@ -20,13 +19,11 @@ "too-many-locals|memclaw/agent.py|MemclawAgent._handle": 18, "too-many-locals|memclaw/backends/claude.py|ClaudeAgentBackend.wizard_setup": 17, "too-many-locals|memclaw/backends/cursor.py|CursorAgentBackend.run_turn": 20, - "too-many-locals|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 19, - "too-many-locals|memclaw/index.py|MemoryIndex.chunk_text": 17 + "too-many-locals|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 19 }, "ruff": { "function-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13, "function-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 11, - "function-complexity|memclaw/index.py|MemoryIndex.chunk_text": 12, "too-many-args|memclaw/backends/base.py|AgentBackend.run_turn": 10, "too-many-args|memclaw/backends/claude.py|ClaudeAgentBackend.run_turn": 10, "too-many-args|memclaw/backends/cursor.py|CursorAgentBackend.run_turn": 10, @@ -37,7 +34,6 @@ "sizes": { "class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 501, "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419, - "class-lines|memclaw/index.py|MemoryIndex": 345, "file-lines|memclaw/backends/claude.py|": 775, "file-lines|memclaw/backends/cursor.py|": 604, "file-lines|memclaw/tools.py|": 576 diff --git a/memclaw/chunking.py b/memclaw/chunking.py new file mode 100644 index 0000000..d057ee5 --- /dev/null +++ b/memclaw/chunking.py @@ -0,0 +1,88 @@ +"""Splitting a note into the chunks the index embeds and searches.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + + +@dataclass +class Chunk: + file_path: str + line_start: int + line_end: int + content: str + embedding: np.ndarray | None = None + + +def chunk_text(text: str, file_path: str, *, target_words: int, overlap_words: int) -> list[Chunk]: + """Split text into chunks by entries, headings and size. + + A ``---`` line ends an entry (``MemoryStore.save`` writes one after + each), so every entry starts a fresh chunk. A heading starts a new + chunk once the current one is half full. Only an entry too long for + one chunk is split by size, with overlap and its heading repeated. + """ + chunker = _Chunker(file_path, target_words, overlap_words) + lines = text.split("\n") + for i, line in enumerate(lines): + chunker.add(i, line) + if chunker.current: + chunker.flush(len(lines) - 1) + return chunker.chunks + + +class _Chunker: + """The state of one `chunk_text` pass: the lines of the chunk being + built, where it starts, its word count and the heading it is under.""" + + def __init__(self, file_path: str, target_words: int, overlap_words: int): + self.file_path = file_path + self.target = target_words + self.overlap = overlap_words + self.chunks: list[Chunk] = [] + self.current: list[str] = [] + self.start = 0 + self.words = 0 + self.heading = "" + + def add(self, i: int, line: str) -> None: + is_heading = line.startswith("#") + if is_heading and self.words > self.target // 2: + self.flush(i - 1) + self.current, self.start, self.words = [], i, 0 + if is_heading: + self.heading = line + + self.current.append(line) + self.words += len(line.split()) + + if line.strip() == "---": + self.flush(i) + self.current, self.start, self.words, self.heading = [], i + 1, 0, "" + elif self.words >= self.target: + self.flush(i) + self._keep_overlap(i) + + def flush(self, end: int) -> None: + content = "\n".join(self.current).strip() + if content and content != "---": + self.chunks.append(Chunk(file_path=self.file_path, line_start=self.start, + line_end=end, content=content)) + + def _keep_overlap(self, i: int) -> None: + """After a size split at line *i*: keep a tail of the entry for + continuity, under its heading.""" + overlap_words = 0 + keep = len(self.current) + for j in range(len(self.current) - 1, -1, -1): + overlap_words += len(self.current[j].split()) + keep = j + if overlap_words >= self.overlap: + break + self.current = self.current[keep:] if keep > 0 else [] + self.start = i - len(self.current) + 1 + if self.heading and self.current and not any(ln.startswith("#") for ln in self.current): + self.current.insert(0, self.heading) + self.words = sum(len(ln.split()) for ln in self.current) diff --git a/memclaw/index.py b/memclaw/index.py index 85aaf8d..5e13917 100644 --- a/memclaw/index.py +++ b/memclaw/index.py @@ -2,25 +2,16 @@ import hashlib import sqlite3 -from dataclasses import dataclass from pathlib import Path import numpy as np from loguru import logger +from .chunking import Chunk, chunk_text from .config import MemclawConfig from .openai_client import OpenAIClient -@dataclass -class Chunk: - file_path: str - line_start: int - line_end: int - content: str - embedding: np.ndarray | None = None - - def _create_schema(db: sqlite3.Connection) -> None: """Create the tables, the FTS5 index and its triggers if missing. @@ -171,66 +162,6 @@ def openai(self) -> OpenAIClient: self._openai = OpenAIClient(self.config.openai.api_key) return self._openai - # ------------------------------------------------------------------ - # Chunking - # ------------------------------------------------------------------ - - def chunk_text(self, text: str, file_path: str) -> list[Chunk]: - """Split text into chunks by entries, headings and size. - - A ``---`` line ends an entry (``MemoryStore.save`` writes one after - each), so every entry starts a fresh chunk. A heading starts a new - chunk once the current one is half full. Only an entry too long for - one chunk is split by size, with overlap and its heading repeated. - """ - lines = text.split("\n") - chunks: list[Chunk] = [] - current: list[str] = [] - start = 0 - heading = "" - words = 0 - target = self.config.memory.chunk_target_words - - def flush(end: int) -> None: - content = "\n".join(current).strip() - if content and content != "---": - chunks.append(Chunk(file_path=file_path, line_start=start, - line_end=end, content=content)) - - for i, line in enumerate(lines): - is_heading = line.startswith("#") - if is_heading and words > target // 2: - flush(i - 1) - current, start, words = [], i, 0 - if is_heading: - heading = line - - current.append(line) - words += len(line.split()) - - if line.strip() == "---": - flush(i) - current, start, words, heading = [], i + 1, 0, "" - elif words >= target: - flush(i) - # Keep a tail of the entry for continuity, under its heading. - overlap_words = 0 - keep = len(current) - for j in range(len(current) - 1, -1, -1): - overlap_words += len(current[j].split()) - keep = j - if overlap_words >= self.config.memory.chunk_overlap_words: - break - current = current[keep:] if keep > 0 else [] - start = i - len(current) + 1 - if heading and current and not any(ln.startswith("#") for ln in current): - current.insert(0, heading) - words = sum(len(ln.split()) for ln in current) - - if current: - flush(len(lines) - 1) - return chunks - # ------------------------------------------------------------------ # Embeddings # ------------------------------------------------------------------ @@ -316,7 +247,11 @@ async def index_file(self, file_path: Path): mtime = file_path.stat().st_mtime path_str = str(file_path) - chunks = self.chunk_text(content, path_str) if content.strip() else [] + memory = self.config.memory + chunks = chunk_text( + content, path_str, + target_words=memory.chunk_target_words, overlap_words=memory.chunk_overlap_words, + ) if content.strip() else [] embeddings = await self.get_embeddings([c.content for c in chunks]) with self.db: diff --git a/pyproject.toml b/pyproject.toml index 7419777..b735676 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -187,8 +187,9 @@ layers = [ "reminders | sessions | prompts | instructions", # SQLite + embeddings index, used by search. "index", - # The OpenAI adapter (embeddings, transcription, chat), used by index and bot. - "openai_client", + # The OpenAI adapter (embeddings, transcription, chat), used by index and + # bot; splitting notes into chunks, used by index. + "openai_client | chunking", # Settings read from the environment. Imports nothing from memclaw. "config", ] diff --git a/tests/test_chunking.py b/tests/test_chunking.py new file mode 100644 index 0000000..5302e25 --- /dev/null +++ b/tests/test_chunking.py @@ -0,0 +1,63 @@ +"""Tests for chunk_text: how a note is split into the chunks the index stores.""" +from __future__ import annotations + +from pathlib import Path + +from memclaw.chunking import chunk_text +from memclaw.config import MemclawConfig, MemorySettings +from memclaw.memory import MemoryStore + +_DEFAULTS = MemorySettings() + + +def _chunks(text: str, file_path: str): + return chunk_text( + text, file_path, + target_words=_DEFAULTS.chunk_target_words, + overlap_words=_DEFAULTS.chunk_overlap_words, + ) + + +class TestChunking: + def test_basic_chunking(self): + text = "Hello world.\n\n---\n\nSecond paragraph." + chunks = _chunks(text, "test.md") + assert len(chunks) >= 1 + assert all(c.file_path == "test.md" for c in chunks) + + def test_empty_text(self): + chunks = _chunks("", "test.md") + assert chunks == [] + + +class TestEntryChunking: + def test_each_entry_is_its_own_chunk(self, tmp_path: Path): + store = MemoryStore(MemclawConfig(memory_dir=tmp_path / "m")) + store.save("First entry about apples.") + path = store.save("Second entry about bananas.") + chunks = _chunks(path.read_text(), str(path)) + bananas = [c for c in chunks if "bananas" in c.content] + assert len(bananas) == 1 + assert "apples" not in bananas[0].content + assert bananas[0].content.count("## ") == 1 + + def test_long_entry_is_split_with_overlap_under_its_heading(self): + body = "\n".join(f"line {i} " + "word " * 20 for i in range(40)) + chunks = _chunks(f"## 10:00 - Note\n\n{body}\n\n---\n", "f.md") + assert len(chunks) > 1 + assert all(c.content.startswith("## 10:00 - Note") for c in chunks) + # Consecutive chunks share some text. + assert chunks[0].content.splitlines()[-1] in chunks[1].content + + +class TestSizeSplits: + def test_a_heading_starts_a_new_chunk_once_half_full(self): + text = "# A\n" + "word " * 12 + "\n# B\nmore words here" + chunks = chunk_text(text, "f.md", target_words=20, overlap_words=5) + assert [c.content.splitlines()[0] for c in chunks] == ["# A", "# B"] + assert [(c.line_start, c.line_end) for c in chunks] == [(0, 1), (2, 3)] + + def test_an_entry_overlapped_whole_is_not_repeated(self): + # The overlap reaches back to the entry's first line: nothing is kept. + chunks = chunk_text("one two three four", "f.md", target_words=4, overlap_words=50) + assert [c.content for c in chunks] == ["one two three four"] diff --git a/tests/test_index.py b/tests/test_index.py index 92d685f..7a12216 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -144,40 +144,6 @@ async def test_empty_input(self, idx: MemoryIndex): assert result == [] -class TestChunking: - def test_basic_chunking(self, idx: MemoryIndex): - text = "Hello world.\n\n---\n\nSecond paragraph." - chunks = idx.chunk_text(text, "test.md") - assert len(chunks) >= 1 - assert all(c.file_path == "test.md" for c in chunks) - - def test_empty_text(self, idx: MemoryIndex): - chunks = idx.chunk_text("", "test.md") - assert chunks == [] - - -class TestEntryChunking: - def test_each_entry_is_its_own_chunk(self, cfg: MemclawConfig, idx: MemoryIndex): - from memclaw.memory import MemoryStore - - store = MemoryStore(cfg) - store.save("First entry about apples.") - path = store.save("Second entry about bananas.") - chunks = idx.chunk_text(path.read_text(), str(path)) - bananas = [c for c in chunks if "bananas" in c.content] - assert len(bananas) == 1 - assert "apples" not in bananas[0].content - assert bananas[0].content.count("## ") == 1 - - def test_long_entry_is_split_with_overlap_under_its_heading(self, idx: MemoryIndex): - body = "\n".join(f"line {i} " + "word " * 20 for i in range(40)) - chunks = idx.chunk_text(f"## 10:00 - Note\n\n{body}\n\n---\n", "f.md") - assert len(chunks) > 1 - assert all(c.content.startswith("## 10:00 - Note") for c in chunks) - # Consecutive chunks share some text. - assert chunks[0].content.splitlines()[-1] in chunks[1].content - - class TestIndexScope: @pytest.mark.asyncio async def test_agents_md_and_hidden_dirs_are_not_indexed(self, cfg: MemclawConfig, idx: MemoryIndex): From d2641cdb881a9e3e1fb69981a40720675ab58107 Mon Sep 17 00:00:00 2001 From: Emanuilo Jovanovic Date: Sun, 22 Nov 2026 17:58:28 +0100 Subject: [PATCH 4/6] refactor(memory): the index joins memclaw/memory/, sealed behind the package - index.py becomes memory/index.py and chunking.py memory/chunking.py. memclaw.memory exports MemoryIndex; agent, cli, tools and the tests import it from there. Only import paths change. - Tests mirror the move: tests/memory/test_index.py, test_chunking.py. The memory subsystem is now one package: notes, chunking, index, search, consolidation, refs. memclaw/memory/__init__.py lists what it offers; docs/memory-architecture.md has a "Where the Code Lives" table. Guards: - memory-via-package covers every module inside (chunking, index, notes, search, consolidation, refs): other code uses memclaw.memory. - New memory-layers contract: inside the package, consolidation and search sit above notes, index and refs, and chunking below them (exhaustive, so a new module there must be placed). - sqlite3 (kit banned_api) is allowed only in memory/index.py and reminders.py. - The top-level layers lose index and chunking. Library users: `from memclaw.memory import MemoryIndex` (docs/library.md, docs/upgrading.md). --- .code-shape/baseline.json | 2 +- CONTRIBUTING.md | 4 ++-- docs/library.md | 3 +-- docs/memory-architecture.md | 14 ++++++++++++ docs/upgrading.md | 2 +- memclaw/agent.py | 3 +-- memclaw/cli.py | 3 +-- memclaw/memory/__init__.py | 13 +++++++---- memclaw/{ => memory}/chunking.py | 0 memclaw/memory/consolidation.py | 2 +- memclaw/{ => memory}/index.py | 4 ++-- memclaw/memory/search.py | 2 +- memclaw/tools.py | 3 +-- pyproject.toml | 35 +++++++++++++++++++++-------- tests/conftest.py | 3 +-- tests/e2e/test_retrieval_e2e.py | 3 +-- tests/{ => memory}/test_chunking.py | 2 +- tests/memory/test_consolidation.py | 3 +-- tests/{ => memory}/test_index.py | 2 +- tests/memory/test_search.py | 3 +-- 20 files changed, 67 insertions(+), 39 deletions(-) rename memclaw/{ => memory}/chunking.py (100%) rename memclaw/{ => memory}/index.py (99%) rename tests/{ => memory}/test_chunking.py (98%) rename tests/{ => memory}/test_index.py (99%) diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index 73ebb86..20ba0d0 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -36,7 +36,7 @@ "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419, "file-lines|memclaw/backends/claude.py|": 775, "file-lines|memclaw/backends/cursor.py|": 604, - "file-lines|memclaw/tools.py|": 576 + "file-lines|memclaw/tools.py|": 575 } }, "version": 1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eba5dc2..b681729 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,12 +66,12 @@ Claude Code uses `.claude/settings.json` automatically: when Claude runs `git co **memclaw's layout rules** are the import-linter contracts under `[tool.importlinter]` in `pyproject.toml`. `code-shape check` runs them (on their own: `lint-imports`): -- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → `memory` → core modules (`reminders`, `sessions`, …) → `index` → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. +- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → `memory` → core modules (`reminders`, `sessions`, …) → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. - **No cycles inside subpackages** such as `memclaw.backends` and `memclaw.bot`. - **Chat platforms are independent**: `bot/telegram.py`, `bot/slack.py` and `bot/whatsapp.py` never import each other. What they share (voice to text, link summaries, the prompts, the agent call, reminders) is in `bot/inbound.py`. A new platform is one module with a `run(config)` plus one line in `PLATFORMS` (`bot/__init__.py`); the CLI and the setup wizard start and list platforms only through that registry. - **Chat SDKs stay in their platform module**: only those three modules import `telegram`, `slack_bolt` or `neonize`. - **One OpenAI adapter**: only `openai_client.py` imports `openai`; everyone else calls `OpenAIClient`. -- **Memory through its package**: other code uses what `memclaw.memory` exports (`MemoryStore`, `HybridSearch`, `Consolidator`, …), not the modules inside (`notes.py`, `search.py`, `consolidation.py`, …). `memory/consolidation.py` is the only code that writes MEMORY.md; it reaches the LLM through the backend the agent hands it, so it doesn't import `memclaw.backends`. +- **Memory through its package**: other code uses what `memclaw.memory` exports (`MemoryStore`, `MemoryIndex`, `HybridSearch`, `Consolidator`, …), not the modules inside (`notes.py`, `index.py`, `search.py`, …). Inside, `consolidation` and `search` build on `notes` and `index`, never the other way round, and only `index.py` runs SQL on the search index. `memory/consolidation.py` is the only code that writes MEMORY.md; it reaches the LLM through the backend the agent hands it, so it doesn't import `memclaw.backends`. - **Backends are swappable**: only `memclaw.backends` itself imports the concrete backend modules (`claude.py`, `cursor.py`, …). Everyone else goes through `memclaw.backends` / `memclaw.backends.base`. - **`memclaw.defaults` stands alone**: the Cursor hook script there is copied out and run on its own, so it can't import memclaw. diff --git a/docs/library.md b/docs/library.md index 78eddc9..985adba 100644 --- a/docs/library.md +++ b/docs/library.md @@ -5,8 +5,7 @@ The store, index and search work without the agent — only `OPENAI_API_KEY` is ```python import asyncio from memclaw.config import MemclawConfig -from memclaw.index import MemoryIndex -from memclaw.memory import HybridSearch, MemoryStore +from memclaw.memory import HybridSearch, MemoryIndex, MemoryStore async def main(): config = MemclawConfig() diff --git a/docs/memory-architecture.md b/docs/memory-architecture.md index aa98b6b..db29d6f 100644 --- a/docs/memory-architecture.md +++ b/docs/memory-architecture.md @@ -254,6 +254,20 @@ When you ask "show me that photo of the sunset," the agent runs `image_search`: --- +## Where the Code Lives + +All of the above is the `memclaw/memory/` package. Other code imports what its `__init__.py` exports (`MemoryStore`, `MemoryIndex`, `HybridSearch`, `SearchResult`, `Consolidator`), never the modules inside: + +| Module | What it does | +|---|---| +| `notes.py` | `MemoryStore`: appends entries to the daily files, lists the notes | +| `chunking.py` | Splits a note into chunks (per entry, at headings, by size) | +| `index.py` | `MemoryIndex`: the SQLite database (chunks, embeddings and their cache, the FTS5 index, the image registry). The only code here that runs SQL | +| `search.py` | `HybridSearch`: the search pipeline (merge, decay, MMR). It reads the index through `MemoryIndex` methods | +| `consolidation.py`, `refs.py` | `Consolidator`: writes MEMORY.md and checks its references | + +--- + ## Configuration Reference All memory-related settings live in `MemclawConfig` (`memclaw/config.py`), most of them in its `memory` group. Pass them when you build one, e.g. `MemclawConfig(memory=MemorySettings(mmr_lambda=0.5))`, or set them on it (`config.memory.mmr_lambda = 0.5`): diff --git a/docs/upgrading.md b/docs/upgrading.md index c9318b7..6f8450a 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -4,7 +4,7 @@ Nothing changes for the `memclaw` command or your `.env`. In the library, `MemclawConfig`'s settings moved into groups: `MemclawConfig(openai_api_key="k")` is now `MemclawConfig(openai=OpenAISettings(api_key="k"))`, and `config.slack_bot_token` is `config.slack.bot_token`, `config.mmr_lambda` is `config.memory.mmr_lambda`, and so on. `memory_dir`, `agent_backend` and `platform` stay where they were. See [Using Memclaw as a Library](library.md). -The store and search moved into the `memclaw.memory` package: `from memclaw.store import MemoryStore` is now `from memclaw.memory import MemoryStore`, and `from memclaw.search import HybridSearch, SearchResult` is now `from memclaw.memory import HybridSearch, SearchResult`. They work as before. +The store, index and search moved into the `memclaw.memory` package: `from memclaw.store import MemoryStore`, `from memclaw.index import MemoryIndex` and `from memclaw.search import HybridSearch, SearchResult` are now `from memclaw.memory import MemoryStore, MemoryIndex, HybridSearch, SearchResult`. They work as before. ## From 2.x to 3.0 diff --git a/memclaw/agent.py b/memclaw/agent.py index 4ede237..15e5969 100644 --- a/memclaw/agent.py +++ b/memclaw/agent.py @@ -24,7 +24,6 @@ from .backends import AgentBackend, build_backend from .backends.base import ProgressCallback, TurnResult from .config import MemclawConfig -from .index import MemoryIndex from .instructions import ( build_system_prompt, content_hash, @@ -32,7 +31,7 @@ load_agent_instructions, load_permanent_memory, ) -from .memory import Consolidator, HybridSearch, MemoryStore +from .memory import Consolidator, HybridSearch, MemoryIndex, MemoryStore from .reminders import ReminderScheduler from .sessions import SessionStore from .tools import ToolExecutor diff --git a/memclaw/cli.py b/memclaw/cli.py index 87cf65d..b726cfb 100644 --- a/memclaw/cli.py +++ b/memclaw/cli.py @@ -10,8 +10,7 @@ from .bot import PLATFORMS from .config import MemclawConfig, reload_env_file -from .index import MemoryIndex -from .memory import HybridSearch, MemoryStore +from .memory import HybridSearch, MemoryIndex, MemoryStore from .setup import needs_setup, print_logo, print_probe_report, run_setup console = Console() diff --git a/memclaw/memory/__init__.py b/memclaw/memory/__init__.py index 707bb88..6169fab 100644 --- a/memclaw/memory/__init__.py +++ b/memclaw/memory/__init__.py @@ -1,12 +1,16 @@ -"""Memclaw's memory subsystem: the notes, how they are searched, and -MEMORY.md. +"""Memclaw's memory subsystem: the notes, the index and search over them, +and MEMORY.md. Public: - `MemoryStore` (notes.py): writes and lists the Markdown notes, the daily files under memory/ that are the complete record. +- `MemoryIndex` (index.py): the SQLite index of the notes (chunks, + embeddings, FTS5) and of saved images. The only SQLite user here; + chunking.py splits the notes for it. - `HybridSearch`, `SearchResult` (search.py): ranks chunks of the notes for - a query (vector + keyword, recency decay, near-duplicates dropped). + a query (vector + keyword, recency decay, near-duplicates dropped), + reading the index through MemoryIndex's methods. - `Consolidator` (consolidation.py): distills the daily notes into MEMORY.md, and is the only code that writes it. refs.py checks the references it writes. @@ -15,7 +19,8 @@ """ from .consolidation import Consolidator +from .index import MemoryIndex from .notes import MemoryStore from .search import HybridSearch, SearchResult -__all__ = ["Consolidator", "HybridSearch", "MemoryStore", "SearchResult"] +__all__ = ["Consolidator", "HybridSearch", "MemoryIndex", "MemoryStore", "SearchResult"] diff --git a/memclaw/chunking.py b/memclaw/memory/chunking.py similarity index 100% rename from memclaw/chunking.py rename to memclaw/memory/chunking.py diff --git a/memclaw/memory/consolidation.py b/memclaw/memory/consolidation.py index 7ee30c8..77d6790 100644 --- a/memclaw/memory/consolidation.py +++ b/memclaw/memory/consolidation.py @@ -23,7 +23,7 @@ from loguru import logger from ..config import MemclawConfig -from ..index import MemoryIndex +from .index import MemoryIndex from .notes import MemoryStore from .refs import check_references diff --git a/memclaw/index.py b/memclaw/memory/index.py similarity index 99% rename from memclaw/index.py rename to memclaw/memory/index.py index 5e13917..f7e1b9f 100644 --- a/memclaw/index.py +++ b/memclaw/memory/index.py @@ -8,8 +8,8 @@ from loguru import logger from .chunking import Chunk, chunk_text -from .config import MemclawConfig -from .openai_client import OpenAIClient +from ..config import MemclawConfig +from ..openai_client import OpenAIClient def _create_schema(db: sqlite3.Connection) -> None: diff --git a/memclaw/memory/search.py b/memclaw/memory/search.py index da87807..5f2cbda 100644 --- a/memclaw/memory/search.py +++ b/memclaw/memory/search.py @@ -9,7 +9,7 @@ import numpy as np from ..config import MemclawConfig -from ..index import MemoryIndex +from .index import MemoryIndex # Keyword-query tokenizer: words and numbers (same notion of a token as # FTS5's unicode61 tokenizer). Very common words are dropped — they match diff --git a/memclaw/tools.py b/memclaw/tools.py index f26c3c0..07ba3b8 100644 --- a/memclaw/tools.py +++ b/memclaw/tools.py @@ -9,8 +9,7 @@ from loguru import logger from .config import MemclawConfig -from .index import MemoryIndex -from .memory import HybridSearch, MemoryStore, SearchResult +from .memory import HybridSearch, MemoryIndex, MemoryStore, SearchResult from .reminders import ReminderScheduler # ── Tool definitions (JSON schema) ─────────────────────────────────── diff --git a/pyproject.toml b/pyproject.toml index b735676..8b07702 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -106,7 +106,7 @@ baseline = ".code-shape/baseline.json" # Outside systems should be reached through one module each. Existing direct # uses are in the baseline; new ones fail. "openai" = { msg = "Only memclaw/openai_client.py imports the OpenAI SDK. Call OpenAIClient (embed, transcribe, chat), or add the call there.", allowed = ["memclaw/openai_client.py"] } -"sqlite3" = { msg = "Only the storage modules (memclaw/index.py, memclaw/reminders.py) open SQLite; call their methods instead.", allowed = ["memclaw/index.py", "memclaw/reminders.py"] } +"sqlite3" = { msg = "Only the storage modules (memclaw/memory/index.py for the search index, memclaw/reminders.py) open SQLite; call their methods instead, or add the query there.", allowed = ["memclaw/memory/index.py", "memclaw/reminders.py"] } # Settings come from memclaw/config.py only (config_modules above bans os.environ elsewhere); .env files too. "dotenv" = { msg = "Only memclaw/config.py loads .env files. Use its read_env_file / update_env_file / reload_env_file, or add a setting there and read it from MemclawConfig.", allowed = ["memclaw/config.py"] } @@ -134,14 +134,14 @@ ignore_names = [ # gate): words that name each one in code, and the module that should own it. "memory notes (daily files)" = { terms = ["MemoryStore", "daily_file", "memory_save"], home = "memclaw/memory/notes.py" } "MEMORY.md + consolidation" = { terms = ["consolidat", "MEMORY\\.md", "permanent_memory"], home = "memclaw/memory/consolidation.py" } -"search + index" = { terms = ["HybridSearch", "MemoryIndex", "embedding"], home = "memclaw/index.py" } +"search + index" = { terms = ["HybridSearch", "MemoryIndex", "embedding"], home = "memclaw/memory/index.py" } "reminders" = { terms = ["remind"], home = "memclaw/reminders.py" } "settings storage (.env)" = { terms = ["read_env_file", "update_env_file", "write_env_file", "os\\.environ"], home = "memclaw/config.py" } "AI backends" = { terms = ["AgentBackend", "build_backend", "agent_backend", "AGENT_BACKEND"], home = "memclaw/backends/base.py" } "model / effort selection" = { terms = ["set_model", "set_effort", "list_models", "effort_levels"], home = "memclaw/backends/model_selection.py" } "chat platforms" = { terms = ["telegram", "slack", "whatsapp"], home = "memclaw/bot/__init__.py" } "voice transcription" = { terms = ["whisper", "transcri"], home = "memclaw/bot/inbound.py" } -"images" = { terms = ["image_save", "image_search", "platform_image"], home = "memclaw/index.py" } +"images" = { terms = ["image_save", "image_search", "platform_image"], home = "memclaw/memory/index.py" } "agent tools" = { terms = ["TOOL_DEFINITIONS", "ToolExecutor"], home = "memclaw/tools.py" } "conversations / sessions" = { terms = ["SessionStore", "session_key", "reset_session"], home = "memclaw/sessions.py" } "setup wizard" = { terms = ["run_setup", "wizard", "needs_setup"], home = "memclaw/setup.py" } @@ -185,11 +185,9 @@ layers = [ "memory", # Independent building blocks (`|`: they don't import each other). "reminders | sessions | prompts | instructions", - # SQLite + embeddings index, used by search. - "index", - # The OpenAI adapter (embeddings, transcription, chat), used by index and - # bot; splitting notes into chunks, used by index. - "openai_client | chunking", + # The OpenAI adapter (embeddings, transcription, chat), used by the + # memory index and bot. + "openai_client", # Settings read from the environment. Imports nothing from memclaw. "config", ] @@ -245,16 +243,35 @@ allowed_importers = ["memclaw.openai_client"] [[tool.importlinter.contracts]] id = "memory-via-package" -name = "Only memclaw.memory imports its own modules: everyone else uses what memclaw.memory exports (MemoryStore, HybridSearch, Consolidator, ...)" +name = "Only memclaw.memory imports its own modules: everyone else uses what memclaw.memory exports (MemoryStore, MemoryIndex, HybridSearch, Consolidator, ...)" type = "protected" protected_modules = [ + "memclaw.memory.chunking", "memclaw.memory.consolidation", + "memclaw.memory.index", "memclaw.memory.notes", "memclaw.memory.refs", "memclaw.memory.search", ] allowed_importers = ["memclaw.memory"] +[[tool.importlinter.contracts]] +id = "memory-layers" +name = "Inside memclaw.memory: consolidation and search build on the notes and the index, never the other way round" +type = "layers" +containers = ["memclaw.memory"] +layers = [ + # MEMORY.md consolidation; ranking search results. Independent. + "consolidation | search", + # The Markdown notes; the SQLite index of them (the only SQLite user + # here); the reference check consolidation runs. + "notes | index | refs", + # Splitting a note into chunks, used by index. + "chunking", +] +# A new module inside memclaw.memory must be placed in a layer above. +exhaustive = true + [[tool.importlinter.contracts]] id = "defaults-standalone" name = "memclaw.defaults imports nothing from memclaw (its Cursor hook script is copied to ~/.memclaw and run on its own)" diff --git a/tests/conftest.py b/tests/conftest.py index 174ac72..e10349c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,8 +11,7 @@ import pytest from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings -from memclaw.index import MemoryIndex -from memclaw.memory import HybridSearch, MemoryStore, SearchResult +from memclaw.memory import HybridSearch, MemoryIndex, MemoryStore, SearchResult class _FakeEmbeddings: diff --git a/tests/e2e/test_retrieval_e2e.py b/tests/e2e/test_retrieval_e2e.py index 1187344..4c4bcc1 100644 --- a/tests/e2e/test_retrieval_e2e.py +++ b/tests/e2e/test_retrieval_e2e.py @@ -6,8 +6,7 @@ import pytest from memclaw.agent import MemclawAgent -from memclaw.index import MemoryIndex -from memclaw.memory import HybridSearch, MemoryStore +from memclaw.memory import HybridSearch, MemoryIndex, MemoryStore from memclaw.openai_client import OpenAIClient from memclaw.tools import ToolExecutor diff --git a/tests/test_chunking.py b/tests/memory/test_chunking.py similarity index 98% rename from tests/test_chunking.py rename to tests/memory/test_chunking.py index 5302e25..7079bfe 100644 --- a/tests/test_chunking.py +++ b/tests/memory/test_chunking.py @@ -3,9 +3,9 @@ from pathlib import Path -from memclaw.chunking import chunk_text from memclaw.config import MemclawConfig, MemorySettings from memclaw.memory import MemoryStore +from memclaw.memory.chunking import chunk_text _DEFAULTS = MemorySettings() diff --git a/tests/memory/test_consolidation.py b/tests/memory/test_consolidation.py index 0ad170b..0d53a9a 100644 --- a/tests/memory/test_consolidation.py +++ b/tests/memory/test_consolidation.py @@ -17,8 +17,7 @@ import pytest from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings -from memclaw.index import MemoryIndex -from memclaw.memory import Consolidator, MemoryStore +from memclaw.memory import Consolidator, MemoryIndex, MemoryStore from memclaw.memory.consolidation import _CONSOLIDATION_BUDGET_CHARS as BUDGET diff --git a/tests/test_index.py b/tests/memory/test_index.py similarity index 99% rename from tests/test_index.py rename to tests/memory/test_index.py index 7a12216..888c0df 100644 --- a/tests/test_index.py +++ b/tests/memory/test_index.py @@ -9,7 +9,7 @@ import pytest from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings -from memclaw.index import MemoryIndex +from memclaw.memory import MemoryIndex @pytest.fixture diff --git a/tests/memory/test_search.py b/tests/memory/test_search.py index dcafc4c..57c1611 100644 --- a/tests/memory/test_search.py +++ b/tests/memory/test_search.py @@ -8,8 +8,7 @@ import pytest from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings -from memclaw.index import MemoryIndex -from memclaw.memory import HybridSearch, SearchResult +from memclaw.memory import HybridSearch, MemoryIndex, SearchResult # ──────────────────────────────────────────────────────────────────── From 1cd7af81e3b21048b9eaf089bfd362b384f018ae Mon Sep 17 00:00:00 2001 From: Emanuilo Jovanovic Date: Sun, 22 Nov 2026 17:59:49 +0100 Subject: [PATCH 5/6] refactor(setup): backend classes are typed, masked_input's key loop is its own function - The backend registry is typed as type[AgentBackend] (it was plain `type`), so mypy checks what the wizard and cli call on a backend class (name, display_name, wizard_setup, is_configured, ...). That fixes all 5 type errors in setup.py and the 2 in cli.py. - masked_input's terminal key loop (echo, backspace, Ctrl-C) moves to _read_masked, under the complexity limit; masked_input keeps the terminal set-up and restore. New tests drive the key loop. Baseline tightened: those type errors and masked_input's complexity are gone, so setup.py and prompts.py can move into memclaw/setup/ next without carrying old entries. Same wizard: `memclaw configure` (Claude/Cursor, Telegram/Slack/ WhatsApp/terminal, a missing required key), first-run setup, doctor and status print the same text and write the same .env as before. --- .code-shape/baseline.json | 7 ++---- memclaw/backends/__init__.py | 6 ++--- memclaw/prompts.py | 43 +++++++++++++++++++----------------- tests/test_prompts.py | 26 +++++++++++++++++++++- 4 files changed, 53 insertions(+), 29 deletions(-) diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index 20ba0d0..3ef4579 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -4,14 +4,11 @@ "complexipy": { "cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 39, "cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend.run_one_shot": 23, - "cognitive-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 24, - "cognitive-complexity|memclaw/prompts.py|masked_input": 16 + "cognitive-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 24 }, "mypy": { "type-errors|memclaw/backends/claude.py|": 1, - "type-errors|memclaw/backends/mcp_bridge.py|": 1, - "type-errors|memclaw/cli.py|": 2, - "type-errors|memclaw/setup.py|": 5 + "type-errors|memclaw/backends/mcp_bridge.py|": 1 }, "pylint": { "class-attributes|memclaw/agent.py|MemclawAgent": 17, diff --git a/memclaw/backends/__init__.py b/memclaw/backends/__init__.py index e4a8206..eaa5885 100644 --- a/memclaw/backends/__init__.py +++ b/memclaw/backends/__init__.py @@ -21,17 +21,17 @@ DEFAULT_BACKEND = "claude" -REGISTRY: dict[str, type] = { +REGISTRY: dict[str, type[AgentBackend]] = { ClaudeAgentBackend.name: ClaudeAgentBackend, CursorAgentBackend.name: CursorAgentBackend, } -def list_backends() -> list[type]: +def list_backends() -> list[type[AgentBackend]]: return list(REGISTRY.values()) -def get_backend_class(name: str) -> type: +def get_backend_class(name: str) -> type[AgentBackend]: """Look up a backend class by short name. Raises ValueError if unknown.""" cls = REGISTRY.get(name) if cls is None: diff --git a/memclaw/prompts.py b/memclaw/prompts.py index 99f95b6..aa8d5f0 100644 --- a/memclaw/prompts.py +++ b/memclaw/prompts.py @@ -71,30 +71,33 @@ def masked_input(console: "Console", prompt_text: str, *, visible: int = 4) -> s fd = sys.stdin.fileno() old = termios.tcgetattr(fd) - buf: list[str] = [] try: tty.setcbreak(fd) - while True: - ch = sys.stdin.read(1) - if ch in ("\r", "\n"): - break - if ch == "\x03": # Ctrl-C - raise KeyboardInterrupt - if ch in ("\x7f", "\b"): - if buf: - buf.pop() - sys.stdout.write("\b \b") - sys.stdout.flush() - continue - if ord(ch) < 32: - continue - buf.append(ch) - display = ch if len(buf) <= visible else "*" - sys.stdout.write(display) - sys.stdout.flush() + return _read_masked(visible) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) sys.stdout.write("\n") sys.stdout.flush() - return "".join(buf) + +def _read_masked(visible: int) -> str: + """Read keys up to Enter from a terminal in cbreak mode, echoing the + first *visible* characters and '*' for the rest. Backspace deletes.""" + buf: list[str] = [] + while True: + ch = sys.stdin.read(1) + if ch in ("\r", "\n"): + return "".join(buf) + if ch == "\x03": # Ctrl-C + raise KeyboardInterrupt + if ch in ("\x7f", "\b"): + if buf: + buf.pop() + sys.stdout.write("\b \b") + sys.stdout.flush() + continue + if ord(ch) < 32: + continue + buf.append(ch) + sys.stdout.write(ch if len(buf) <= visible else "*") + sys.stdout.flush() diff --git a/tests/test_prompts.py b/tests/test_prompts.py index c804729..ff366b6 100644 --- a/tests/test_prompts.py +++ b/tests/test_prompts.py @@ -1,12 +1,14 @@ """Tests for the shared numbered picker and the setup pickers built on it.""" from __future__ import annotations +import io from unittest.mock import MagicMock, patch +import pytest from rich.panel import Panel from memclaw import setup -from memclaw.prompts import choose +from memclaw.prompts import _read_masked, choose def _choose(answer: str, **kwargs): @@ -40,6 +42,28 @@ def test_footer_goes_under_the_rows(self): assert panel.renderable == "[bold]1)[/bold] a\n\n[dim]note[/dim]" +class TestMaskedKeys: + """The key loop masked_input runs on a real terminal.""" + + def _read(self, keys: str, visible: int = 4) -> tuple[str, str]: + out = io.StringIO() + with patch("sys.stdin", io.StringIO(keys)), patch("sys.stdout", out): + value = _read_masked(visible) + return value, out.getvalue() + + def test_echoes_the_first_chars_then_stars(self): + assert self._read("sk-abcdef\n") == ("sk-abcdef", "sk-a*****") + + def test_backspace_deletes_and_control_keys_are_ignored(self): + value, echo = self._read("ab\x7f\x7f\x7fc\x01d\r") + assert value == "cd" + assert echo == "ab\b \b\b \bcd" + + def test_ctrl_c_interrupts(self): + with pytest.raises(KeyboardInterrupt): + self._read("ab\x03") + + class TestSetupPickers: def test_platform_defaults_to_the_saved_one(self): with patch("memclaw.prompts.Prompt.ask", return_value="3") as ask: From d4ec4913957e317618c028e3c986d2a56b718e27 Mon Sep 17 00:00:00 2001 From: Emanuilo Jovanovic Date: Sun, 22 Nov 2026 18:02:17 +0100 Subject: [PATCH 6/6] refactor(setup): the wizard and the doctor report become memclaw/setup/; prompts.py is terminal_input.py - setup.py becomes setup/wizard.py (the wizard and the logo). The OpenAI model-access check and report move to setup/doctor.py (check_openai, was _check_openai, and print_probe_report), shared by the wizard and `memclaw doctor`. memclaw.setup exports run_setup, needs_setup, print_logo and print_probe_report, what cli uses. - prompts.py becomes terminal_input.py: it is the terminal prompts (numbered choice, masked input), not LLM prompts. It stays at the top level, in the core layer below the backends, because the backends ask their own setup questions (wizard_setup) and setup imports the backend registry: inside memclaw.setup it would make backends import upward. - Tests mirror the move: tests/setup/test_wizard.py (with the platform and backend pickers, from test_prompts.py), tests/setup/test_doctor.py (new), tests/test_terminal_input.py. Guards: a setup-via-package contract (other code uses memclaw.setup, not its modules); terminal_input replaces prompts in the core layer; the "setup wizard" concept's home is setup/wizard.py. Same wizard: first-run setup, `memclaw configure` (several backends and platforms, a missing required key), doctor and status print the same text and write the same .env as before. --- CONTRIBUTING.md | 3 +- memclaw/backends/claude.py | 2 +- memclaw/backends/cursor.py | 2 +- memclaw/setup/__init__.py | 19 ++++++ memclaw/setup/doctor.py | 54 +++++++++++++++++ memclaw/{setup.py => setup/wizard.py} | 58 +++---------------- memclaw/{prompts.py => terminal_input.py} | 9 +-- pyproject.toml | 16 +++-- tests/backends/test_claude.py | 4 +- tests/setup/__init__.py | 0 tests/setup/test_doctor.py | 57 ++++++++++++++++++ tests/{test_setup.py => setup/test_wizard.py} | 21 ++++++- ...test_prompts.py => test_terminal_input.py} | 24 +------- 13 files changed, 182 insertions(+), 87 deletions(-) create mode 100644 memclaw/setup/__init__.py create mode 100644 memclaw/setup/doctor.py rename memclaw/{setup.py => setup/wizard.py} (82%) rename memclaw/{prompts.py => terminal_input.py} (89%) create mode 100644 tests/setup/__init__.py create mode 100644 tests/setup/test_doctor.py rename tests/{test_setup.py => setup/test_wizard.py} (82%) rename tests/{test_prompts.py => test_terminal_input.py} (66%) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b681729..0f9aca2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,12 +66,13 @@ Claude Code uses `.claude/settings.json` automatically: when Claude runs `git co **memclaw's layout rules** are the import-linter contracts under `[tool.importlinter]` in `pyproject.toml`. `code-shape check` runs them (on their own: `lint-imports`): -- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → `memory` → core modules (`reminders`, `sessions`, …) → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. +- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → `memory` → core modules (`reminders`, `sessions`, `terminal_input`, …) → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. (The terminal prompts, `terminal_input.py`, sit below `backends` rather than inside `setup/` because the backends ask their own setup questions.) - **No cycles inside subpackages** such as `memclaw.backends` and `memclaw.bot`. - **Chat platforms are independent**: `bot/telegram.py`, `bot/slack.py` and `bot/whatsapp.py` never import each other. What they share (voice to text, link summaries, the prompts, the agent call, reminders) is in `bot/inbound.py`. A new platform is one module with a `run(config)` plus one line in `PLATFORMS` (`bot/__init__.py`); the CLI and the setup wizard start and list platforms only through that registry. - **Chat SDKs stay in their platform module**: only those three modules import `telegram`, `slack_bolt` or `neonize`. - **One OpenAI adapter**: only `openai_client.py` imports `openai`; everyone else calls `OpenAIClient`. - **Memory through its package**: other code uses what `memclaw.memory` exports (`MemoryStore`, `MemoryIndex`, `HybridSearch`, `Consolidator`, …), not the modules inside (`notes.py`, `index.py`, `search.py`, …). Inside, `consolidation` and `search` build on `notes` and `index`, never the other way round, and only `index.py` runs SQL on the search index. `memory/consolidation.py` is the only code that writes MEMORY.md; it reaches the LLM through the backend the agent hands it, so it doesn't import `memclaw.backends`. +- **Setup through its package**: other code uses what `memclaw.setup` exports (`run_setup`, `needs_setup`, `print_logo`, `print_probe_report`), not `setup/wizard.py` or `setup/doctor.py`. - **Backends are swappable**: only `memclaw.backends` itself imports the concrete backend modules (`claude.py`, `cursor.py`, …). Everyone else goes through `memclaw.backends` / `memclaw.backends.base`. - **`memclaw.defaults` stands alone**: the Cursor hook script there is copied out and run on its own, so it can't import memclaw. diff --git a/memclaw/backends/claude.py b/memclaw/backends/claude.py index f8f986b..202a27f 100644 --- a/memclaw/backends/claude.py +++ b/memclaw/backends/claude.py @@ -29,7 +29,7 @@ ) from loguru import logger from ..config import process_environment -from ..prompts import choose, masked_input +from ..terminal_input import choose, masked_input from ..tools import TOOL_DEFINITIONS from .base import ProgressCallback, TurnResult, report_tool_step from .claude_models import SDK_EFFORT_LEVELS, ModelInfo, fetch_models diff --git a/memclaw/backends/cursor.py b/memclaw/backends/cursor.py index be867c8..ef941a2 100644 --- a/memclaw/backends/cursor.py +++ b/memclaw/backends/cursor.py @@ -19,7 +19,7 @@ from rich.prompt import Prompt from ..config import set_environment -from ..prompts import masked_input +from ..terminal_input import masked_input from .base import ProgressCallback, TurnResult from .claude_models import ModelInfo from .cursor_hooks import cursor_hooks_status, ensure_cursor_hooks diff --git a/memclaw/setup/__init__.py b/memclaw/setup/__init__.py new file mode 100644 index 0000000..05b3ec5 --- /dev/null +++ b/memclaw/setup/__init__.py @@ -0,0 +1,19 @@ +"""Setting Memclaw up from the terminal. + +Public: + +- `run_setup`, `needs_setup`, `print_logo` (wizard.py): the setup wizard, + run on first start and by `memclaw configure`. It asks for the settings + declared with a question in memclaw.config and saves ~/.memclaw/.env. +- `print_probe_report` (doctor.py): the OpenAI model-access report that + `memclaw doctor` prints, and the wizard shows after saving. + +The prompts themselves (numbered choice, masked input) are in +memclaw.terminal_input, below the backends, which ask their own questions. +Other code imports from `memclaw.setup`, not from the modules inside. +""" + +from .doctor import print_probe_report +from .wizard import needs_setup, print_logo, run_setup + +__all__ = ["needs_setup", "print_logo", "print_probe_report", "run_setup"] diff --git a/memclaw/setup/doctor.py b/memclaw/setup/doctor.py new file mode 100644 index 0000000..a8ca3a0 --- /dev/null +++ b/memclaw/setup/doctor.py @@ -0,0 +1,54 @@ +"""OpenAI model access: the check the wizard runs after saving, and the +report `memclaw doctor` prints.""" + +from __future__ import annotations + +import asyncio + +from rich.console import Console +from rich.panel import Panel +from rich.text import Text + +from ..openai_client import ProbeReport, probe_openai + + +def check_openai(api_key: str | None, console: Console) -> None: + """Verify OpenAI model access so the user finds out about disabled models + right now, not when their first voice message silently disappears.""" + if not api_key: + return + console.print("\n[cyan]Checking OpenAI model access...[/cyan]") + try: + report = asyncio.run(probe_openai(api_key)) + print_probe_report(report, console) + except Exception as exc: + console.print(f"[yellow]Skipping model check:[/yellow] {exc}") + + +def print_probe_report(report: ProbeReport, console: Console) -> None: + """Render a probe report (memclaw.openai_client.probe_openai) as a panel.""" + body = Text() + for outcome in report: + marker = "[green]✓[/green]" if outcome.ok else "[red]✗[/red]" + line = f"{marker} {outcome.name} [dim]({outcome.model})[/dim]" + if not outcome.ok and outcome.error: + line += f"\n [red]{outcome.error}[/red]" + body.append_text(Text.from_markup(line)) + body.append("\n") + + if not report.all_ok: + body.append("\n", style="") + body.append_text( + Text.from_markup( + "[yellow]Enable the missing models for your project at[/yellow]\n" + "[bold]https://platform.openai.com/settings/organization/limits[/bold]" + ) + ) + + console.print( + Panel( + body, + title="OpenAI model access", + border_style="green" if report.all_ok else "yellow", + ) + ) diff --git a/memclaw/setup.py b/memclaw/setup/wizard.py similarity index 82% rename from memclaw/setup.py rename to memclaw/setup/wizard.py index f07b7b2..4384394 100644 --- a/memclaw/setup.py +++ b/memclaw/setup/wizard.py @@ -1,15 +1,13 @@ -"""First-run setup wizard and `memclaw configure` handler.""" +"""The setup wizard: first run and `memclaw configure`.""" from __future__ import annotations -import asyncio - from rich.console import Console from rich.panel import Panel from rich.text import Text -from .backends import DEFAULT_BACKEND, get_backend_class, list_backends -from .config import ( +from ..backends import DEFAULT_BACKEND, get_backend_class, list_backends +from ..config import ( ENV_FILE, MemclawConfig, Setting, @@ -18,9 +16,9 @@ set_environment, write_env_file, ) -from .bot import PLATFORMS as CHAT_PLATFORMS -from .openai_client import ProbeReport, probe_openai -from .prompts import choose, masked_input +from ..bot import PLATFORMS as CHAT_PLATFORMS +from ..terminal_input import choose, masked_input +from .doctor import check_openai console = Console() @@ -183,7 +181,7 @@ def run_setup(config: MemclawConfig, *, reconfigure: bool = False) -> None: set_environment(values, drop_keys) console.print(f"\n[green]Config saved to {ENV_FILE}[/green]") - _check_openai(values.get("OPENAI_API_KEY")) + check_openai(values.get("OPENAI_API_KEY"), console) def _print_intro(reconfigure: bool) -> None: @@ -243,45 +241,3 @@ def _require_answers(settings: list[Setting], values: dict[str, str]) -> None: if s.required and s.env and not values.get(s.env): console.print(f"[red]Error:[/red] {s.prompt} is required.") raise SystemExit(1) - - -def _check_openai(api_key: str | None) -> None: - """Verify OpenAI model access so the user finds out about disabled models - right now, not when their first voice message silently disappears.""" - if not api_key: - return - console.print("\n[cyan]Checking OpenAI model access...[/cyan]") - try: - report = asyncio.run(probe_openai(api_key)) - print_probe_report(report, console) - except Exception as exc: - console.print(f"[yellow]Skipping model check:[/yellow] {exc}") - - -def print_probe_report(report: ProbeReport, console: Console) -> None: - """Render a probe report (memclaw.openai_client.probe_openai) as a panel.""" - body = Text() - for outcome in report: - marker = "[green]✓[/green]" if outcome.ok else "[red]✗[/red]" - line = f"{marker} {outcome.name} [dim]({outcome.model})[/dim]" - if not outcome.ok and outcome.error: - line += f"\n [red]{outcome.error}[/red]" - body.append_text(Text.from_markup(line)) - body.append("\n") - - if not report.all_ok: - body.append("\n", style="") - body.append_text( - Text.from_markup( - "[yellow]Enable the missing models for your project at[/yellow]\n" - "[bold]https://platform.openai.com/settings/organization/limits[/bold]" - ) - ) - - console.print( - Panel( - body, - title="OpenAI model access", - border_style="green" if report.all_ok else "yellow", - ) - ) diff --git a/memclaw/prompts.py b/memclaw/terminal_input.py similarity index 89% rename from memclaw/prompts.py rename to memclaw/terminal_input.py index aa8d5f0..9c31cf5 100644 --- a/memclaw/prompts.py +++ b/memclaw/terminal_input.py @@ -1,8 +1,9 @@ -"""Shared interactive prompts for the setup wizard. +"""Asking the user something in the terminal: a numbered choice, masked input. -Lives outside setup.py so backends can import it at module level: setup.py -imports the backend registry, so backends importing setup.py would be -circular. +Used by the setup wizard (memclaw.setup) and by the backends, which ask +their own questions there (`wizard_setup`). It sits in a layer below the +backends, not inside memclaw.setup: setup imports the backend registry, so +backends importing setup would import upward. """ from __future__ import annotations diff --git a/pyproject.toml b/pyproject.toml index 8b07702..ef6fd54 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -144,7 +144,7 @@ ignore_names = [ "images" = { terms = ["image_save", "image_search", "platform_image"], home = "memclaw/memory/index.py" } "agent tools" = { terms = ["TOOL_DEFINITIONS", "ToolExecutor"], home = "memclaw/tools.py" } "conversations / sessions" = { terms = ["SessionStore", "session_key", "reset_session"], home = "memclaw/sessions.py" } -"setup wizard" = { terms = ["run_setup", "wizard", "needs_setup"], home = "memclaw/setup.py" } +"setup wizard" = { terms = ["run_setup", "wizard", "needs_setup"], home = "memclaw/setup/wizard.py" } "links" = { terms = ["LinkProcessor", "process_links"], home = "memclaw/bot/links.py" } # --------------------------------------------------------------------------- @@ -167,8 +167,9 @@ containers = ["memclaw"] layers = [ # Entry point: the `memclaw` command. "cli", - # The interactive setup wizard. It lists the chat platforms from - # memclaw.bot's registry. + # Setting up from the terminal (memclaw.setup): the wizard and the doctor + # report. It lists the chat platforms from memclaw.bot's registry and + # lets the chosen backend ask its own questions. "setup", # The chat bots (memclaw.bot): one module per chat app, plus what they share. "bot", @@ -184,7 +185,7 @@ layers = [ # it, so it doesn't import backends. "memory", # Independent building blocks (`|`: they don't import each other). - "reminders | sessions | prompts | instructions", + "reminders | sessions | terminal_input | instructions", # The OpenAI adapter (embeddings, transcription, chat), used by the # memory index and bot. "openai_client", @@ -272,6 +273,13 @@ layers = [ # A new module inside memclaw.memory must be placed in a layer above. exhaustive = true +[[tool.importlinter.contracts]] +id = "setup-via-package" +name = "Only memclaw.setup imports its own modules: everyone else uses what memclaw.setup exports (run_setup, needs_setup, print_logo, print_probe_report)" +type = "protected" +protected_modules = ["memclaw.setup.doctor", "memclaw.setup.wizard"] +allowed_importers = ["memclaw.setup"] + [[tool.importlinter.contracts]] id = "defaults-standalone" name = "memclaw.defaults imports nothing from memclaw (its Cursor hook script is copied to ~/.memclaw and run on its own)" diff --git a/tests/backends/test_claude.py b/tests/backends/test_claude.py index cdd4e76..945c9fc 100644 --- a/tests/backends/test_claude.py +++ b/tests/backends/test_claude.py @@ -752,7 +752,7 @@ def _prompt(text, **kwargs): return answers[len(prompts) - 1] with patch("memclaw.backends.claude.fetch_models", fetch), \ - patch("memclaw.prompts.Prompt.ask", side_effect=_prompt): + patch("memclaw.terminal_input.Prompt.ask", side_effect=_prompt): values, drops = ClaudeAgentBackend._ask_model_and_effort( console, existing or {}, auth_mode="api_key", credential="sk-ant-test", settings=ClaudeSettings(), # loads CLAUDE_MODEL / CLAUDE_EFFORT from the shell @@ -895,7 +895,7 @@ def _wizard(*, answers, credential="", existing=None, models=None, return_value=models or []) answer_iter = iter(answers) - with patch("memclaw.prompts.Prompt.ask", + with patch("memclaw.terminal_input.Prompt.ask", side_effect=lambda *a, **k: next(answer_iter)), \ patch("memclaw.backends.claude.masked_input", return_value=credential), \ patch("memclaw.backends.claude.fetch_models", fetch): diff --git a/tests/setup/__init__.py b/tests/setup/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/setup/test_doctor.py b/tests/setup/test_doctor.py new file mode 100644 index 0000000..ff0814a --- /dev/null +++ b/tests/setup/test_doctor.py @@ -0,0 +1,57 @@ +"""Tests for the OpenAI model-access report (`memclaw doctor`, and the wizard after saving).""" +from __future__ import annotations + +from unittest.mock import patch + +from rich.console import Console + +from memclaw.openai_client import ProbeOutcome, ProbeReport +from memclaw.setup import doctor, print_probe_report + + +def _report(chat_ok: bool) -> ProbeReport: + return ProbeReport( + ProbeOutcome("Embeddings (search)", "text-embedding-3-small", True), + ProbeOutcome("Chat (link summaries)", "gpt-4o-mini", chat_ok, None if chat_ok else "no access"), + ProbeOutcome("Audio (voice messages)", "whisper-1", True), + ) + + +def _console() -> Console: + return Console(record=True, width=80, color_system=None) + + +class TestProbeReport: + def test_all_models_reachable(self): + console = _console() + print_probe_report(_report(chat_ok=True), console) + text = console.export_text() + assert text.count("✓") == 3 and "✗" not in text + assert "Enable the missing models" not in text + + def test_a_missing_model_shows_its_error_and_where_to_enable_it(self): + console = _console() + print_probe_report(_report(chat_ok=False), console) + text = console.export_text() + assert "✗ Chat (link summaries) (gpt-4o-mini)" in text + assert "no access" in text + assert "platform.openai.com/settings/organization/limits" in text + + +class TestCheckOpenAI: + def test_no_key_checks_nothing(self): + console = _console() + with patch.object(doctor, "probe_openai") as probe: + doctor.check_openai(None, console) + probe.assert_not_called() + assert console.export_text() == "" + + def test_a_failing_probe_is_skipped_not_raised(self): + console = _console() + + async def _fail(_key): + raise RuntimeError("offline") + + with patch.object(doctor, "probe_openai", _fail): + doctor.check_openai("sk-1", console) + assert "Skipping model check: offline" in console.export_text() diff --git a/tests/test_setup.py b/tests/setup/test_wizard.py similarity index 82% rename from tests/test_setup.py rename to tests/setup/test_wizard.py index 5a972f2..c617f65 100644 --- a/tests/test_setup.py +++ b/tests/setup/test_wizard.py @@ -7,8 +7,8 @@ import pytest -from memclaw import setup from memclaw.config import MemclawConfig, all_settings +from memclaw.setup import wizard as setup def _envs(settings) -> list[str]: @@ -64,7 +64,7 @@ def _answer(_console, text): patch("memclaw.backends.ClaudeAgentBackend.wizard_setup", return_value=backend), \ patch.object(setup, "_select_platform", return_value=platform), \ patch.object(setup, "masked_input", side_effect=_answer), \ - patch.object(setup, "_check_openai"): + patch.object(setup, "check_openai"): setup.run_setup(config) return env_file.read_text(), prompts @@ -104,3 +104,20 @@ def test_a_missing_required_answer_stops_before_saving(self, wizard, tmp_path: P with pytest.raises(SystemExit): wizard(["sk-openai-1234", "", ""], "telegram") assert not (tmp_path / ".env").exists() + + +class TestSetupPickers: + def test_platform_defaults_to_the_saved_one(self): + with patch("memclaw.terminal_input.Prompt.ask", return_value="3") as ask: + platform = setup._select_platform({"MEMCLAW_PLATFORM": "whatsapp"}) + expected = [name for name, _ in setup.PLATFORMS].index("whatsapp") + 1 + assert ask.call_args.kwargs["default"] == str(expected) + assert platform == setup.PLATFORMS[2][0] + + def test_backend_defaults_to_the_saved_one(self): + backends = setup.list_backends() + with patch("memclaw.terminal_input.Prompt.ask", return_value="2") as ask: + name = setup._select_backend({"AGENT_BACKEND": "cursor"}) + expected = [cls.name for cls in backends].index("cursor") + 1 + assert ask.call_args.kwargs["default"] == str(expected) + assert name == backends[1].name diff --git a/tests/test_prompts.py b/tests/test_terminal_input.py similarity index 66% rename from tests/test_prompts.py rename to tests/test_terminal_input.py index ff366b6..c97b804 100644 --- a/tests/test_prompts.py +++ b/tests/test_terminal_input.py @@ -1,4 +1,4 @@ -"""Tests for the shared numbered picker and the setup pickers built on it.""" +"""Tests for the terminal prompts: the numbered picker and masked input.""" from __future__ import annotations import io @@ -7,14 +7,13 @@ import pytest from rich.panel import Panel -from memclaw import setup -from memclaw.prompts import _read_masked, choose +from memclaw.terminal_input import _read_masked, choose def _choose(answer: str, **kwargs): """Run `choose` with Prompt.ask mocked. Returns (index, panel, prompt kwargs).""" console = MagicMock() - with patch("memclaw.prompts.Prompt.ask", return_value=answer) as ask: + with patch("memclaw.terminal_input.Prompt.ask", return_value=answer) as ask: index = choose(console, **kwargs) panel = next(c.args[0] for c in console.print.call_args_list if c.args and isinstance(c.args[0], Panel)) @@ -62,20 +61,3 @@ def test_backspace_deletes_and_control_keys_are_ignored(self): def test_ctrl_c_interrupts(self): with pytest.raises(KeyboardInterrupt): self._read("ab\x03") - - -class TestSetupPickers: - def test_platform_defaults_to_the_saved_one(self): - with patch("memclaw.prompts.Prompt.ask", return_value="3") as ask: - platform = setup._select_platform({"MEMCLAW_PLATFORM": "whatsapp"}) - expected = [name for name, _ in setup.PLATFORMS].index("whatsapp") + 1 - assert ask.call_args.kwargs["default"] == str(expected) - assert platform == setup.PLATFORMS[2][0] - - def test_backend_defaults_to_the_saved_one(self): - backends = setup.list_backends() - with patch("memclaw.prompts.Prompt.ask", return_value="2") as ask: - name = setup._select_backend({"AGENT_BACKEND": "cursor"}) - expected = [cls.name for cls in backends].index("cursor") + 1 - assert ask.call_args.kwargs["default"] == str(expected) - assert name == backends[1].name