diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index 249d985..3ef4579 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -4,16 +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/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/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, @@ -21,15 +16,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/search.py|HybridSearch._merge": 22 + "too-many-locals|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 19 }, "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, "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, @@ -40,11 +31,9 @@ "sizes": { "class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 501, "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419, - "class-lines|memclaw/index.py|MemoryIndex": 419, "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|": 575 } }, "version": 1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e53b48b..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 (`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`, `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 (`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`, `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/docs/library.md b/docs/library.md index 3378998..985adba 100644 --- a/docs/library.md +++ b/docs/library.md @@ -5,9 +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.store import MemoryStore -from memclaw.index import MemoryIndex -from memclaw.search import HybridSearch +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 e3611d5..6f8450a 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, 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 ```bash diff --git a/memclaw/agent.py b/memclaw/agent.py index 6ec5e97..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,11 +31,9 @@ load_agent_instructions, load_permanent_memory, ) -from .memory import Consolidator +from .memory import Consolidator, HybridSearch, MemoryIndex, 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/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/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/cli.py b/memclaw/cli.py index e7690e9..b726cfb 100644 --- a/memclaw/cli.py +++ b/memclaw/cli.py @@ -10,10 +10,8 @@ from .bot import PLATFORMS from .config import MemclawConfig, reload_env_file -from .index import MemoryIndex -from .search import HybridSearch +from .memory import HybridSearch, MemoryIndex, 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..6169fab 100644 --- a/memclaw/memory/__init__.py +++ b/memclaw/memory/__init__.py @@ -1,10 +1,26 @@ -"""Memclaw's memory subsystem. +"""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), + 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. -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 .index import MemoryIndex +from .notes import MemoryStore +from .search import HybridSearch, SearchResult -__all__ = ["Consolidator"] +__all__ = ["Consolidator", "HybridSearch", "MemoryIndex", "MemoryStore", "SearchResult"] diff --git a/memclaw/memory/chunking.py b/memclaw/memory/chunking.py new file mode 100644 index 0000000..d057ee5 --- /dev/null +++ b/memclaw/memory/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/memory/consolidation.py b/memclaw/memory/consolidation.py index 4f5e3d3..77d6790 100644 --- a/memclaw/memory/consolidation.py +++ b/memclaw/memory/consolidation.py @@ -23,8 +23,8 @@ from loguru import logger from ..config import MemclawConfig -from ..index import MemoryIndex -from ..store import MemoryStore +from .index import MemoryIndex +from .notes import MemoryStore from .refs import check_references # After a failed consolidation, wait this long before trying again rather diff --git a/memclaw/index.py b/memclaw/memory/index.py similarity index 74% rename from memclaw/index.py rename to memclaw/memory/index.py index f2880e6..f7e1b9f 100644 --- a/memclaw/index.py +++ b/memclaw/memory/index.py @@ -2,41 +2,24 @@ import hashlib import sqlite3 -from dataclasses import dataclass from pathlib import Path import numpy as np +from loguru import logger -from .config import MemclawConfig -from .openai_client import OpenAIClient +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. - -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. + 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 +32,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 +41,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 +61,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 +78,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 +90,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,91 +103,65 @@ 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: 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 # ------------------------------------------------------------------ @@ -290,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: @@ -344,6 +305,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 +396,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 +412,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/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 78% rename from memclaw/search.py rename to memclaw/memory/search.py index 800e70a..5f2cbda 100644 --- a/memclaw/search.py +++ b/memclaw/memory/search.py @@ -2,15 +2,13 @@ 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 ..config import MemclawConfig from .index import MemoryIndex # Keyword-query tokenizer: words and numbers (same notion of a token as @@ -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/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 65% rename from memclaw/prompts.py rename to memclaw/terminal_input.py index 99f95b6..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 @@ -71,30 +72,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/memclaw/tools.py b/memclaw/tools.py index ba07744..07ba3b8 100644 --- a/memclaw/tools.py +++ b/memclaw/tools.py @@ -9,10 +9,8 @@ from loguru import logger from .config import MemclawConfig -from .index import MemoryIndex +from .memory import HybridSearch, MemoryIndex, 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..ef6fd54 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"] } @@ -132,19 +132,19 @@ 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" } +"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" } +"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", @@ -178,15 +179,15 @@ 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", - # SQLite + embeddings index, used by search. - "index", - # The OpenAI adapter (embeddings, transcription, chat), used by index and bot. + "reminders | sessions | terminal_input | instructions", + # 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", @@ -243,11 +244,42 @@ 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, MemoryIndex, HybridSearch, Consolidator, ...)" type = "protected" -protected_modules = ["memclaw.memory.consolidation", "memclaw.memory.refs"] +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 = "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/conftest.py b/tests/conftest.py index 3228419..e10349c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,9 +11,7 @@ import pytest 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, MemoryIndex, MemoryStore, SearchResult class _FakeEmbeddings: diff --git a/tests/e2e/test_retrieval_e2e.py b/tests/e2e/test_retrieval_e2e.py index 21fb288..4c4bcc1 100644 --- a/tests/e2e/test_retrieval_e2e.py +++ b/tests/e2e/test_retrieval_e2e.py @@ -6,10 +6,8 @@ import pytest from memclaw.agent import MemclawAgent -from memclaw.index import MemoryIndex +from memclaw.memory import HybridSearch, MemoryIndex, 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_chunking.py b/tests/memory/test_chunking.py new file mode 100644 index 0000000..7079bfe --- /dev/null +++ b/tests/memory/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.config import MemclawConfig, MemorySettings +from memclaw.memory import MemoryStore +from memclaw.memory.chunking import chunk_text + +_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/memory/test_consolidation.py b/tests/memory/test_consolidation.py index f306ed7..0d53a9a 100644 --- a/tests/memory/test_consolidation.py +++ b/tests/memory/test_consolidation.py @@ -17,10 +17,8 @@ import pytest from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings -from memclaw.index import MemoryIndex -from memclaw.memory import Consolidator +from memclaw.memory import Consolidator, MemoryIndex, MemoryStore from memclaw.memory.consolidation import _CONSOLIDATION_BUDGET_CHARS as BUDGET -from memclaw.store import MemoryStore @pytest.fixture diff --git a/tests/test_index.py b/tests/memory/test_index.py similarity index 84% rename from tests/test_index.py rename to tests/memory/test_index.py index 4f108fd..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 @@ -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.store 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): @@ -237,3 +203,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) == [] 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..57c1611 100644 --- a/tests/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.search import HybridSearch, SearchResult +from memclaw.memory import HybridSearch, MemoryIndex, SearchResult # ──────────────────────────────────────────────────────────────────── 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_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_prompts.py b/tests/test_terminal_input.py similarity index 56% rename from tests/test_prompts.py rename to tests/test_terminal_input.py index c804729..c97b804 100644 --- a/tests/test_prompts.py +++ b/tests/test_terminal_input.py @@ -1,18 +1,19 @@ -"""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 from unittest.mock import MagicMock, patch +import pytest from rich.panel import Panel -from memclaw import setup -from memclaw.prompts import 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)) @@ -40,18 +41,23 @@ def test_footer_goes_under_the_rows(self): assert panel.renderable == "[bold]1)[/bold] a\n\n[dim]note[/dim]" -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 +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")