diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index 3ef4579..b7ad607 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -11,28 +11,22 @@ "type-errors|memclaw/backends/mcp_bridge.py|": 1 }, "pylint": { - "class-attributes|memclaw/agent.py|MemclawAgent": 17, "class-attributes|memclaw/backends/cursor.py|CursorAgentBackend": 13, - "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 }, "ruff": { "function-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13, "function-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 11, - "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, "too-many-args|memclaw/tools.py|ToolExecutor.__init__": 7, "too-many-branches|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13, "too-many-positional|memclaw/tools.py|ToolExecutor.__init__": 7 }, "sizes": { - "class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 501, - "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419, - "file-lines|memclaw/backends/claude.py|": 775, - "file-lines|memclaw/backends/cursor.py|": 604, + "class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 488, + "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 406, + "file-lines|memclaw/backends/claude.py|": 762, + "file-lines|memclaw/backends/cursor.py|": 590, "file-lines|memclaw/tools.py|": 575 } }, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0f9aca2..41f1cfa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -42,7 +42,7 @@ All tests should pass before submitting a PR. The test suite mocks external API - **Sizes**: files (500 lines), classes (300), folders (12 modules, 4000 lines), nesting of folders. - **Functions and classes**: complexity, length, number of arguments, variables, attributes and public methods. -- **Coupling**: environment variables or `.env` files read outside `config.py`, the OpenAI SDK or SQLite used outside their modules, private members (`obj._x`) used from outside, copy-pasted code, import cycles, modules that import too many others. +- **Coupling**: environment variables or `.env` files read outside `config.py`, the OpenAI SDK or SQLite used outside their modules, private members (`obj._x`) used from outside, copy-pasted code, import cycles, modules that import too many others (more than 8 memclaw modules). - **Hygiene**: unused code, dependencies in `pyproject.toml` vs. what the code imports, and type errors (mypy). - **memclaw's layout rules** (see below). @@ -68,11 +68,11 @@ Claude Code uses `.claude/settings.json` automatically: when Claude runs `git co - **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`. +- **Chat platforms are independent**: `bot/telegram.py`, `bot/slack.py`, `bot/whatsapp.py` and `bot/terminal.py` (the terminal chat) never import each other. What the chat apps 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 the three chat-app 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`. +- **Memory through its package**: other code uses what `memclaw.memory` exports (`MemoryStore`, `MemoryIndex`, `HybridSearch`, `Consolidator`, `MemoryVault`, …), not the modules inside (`notes.py`, `index.py`, `search.py`, …). Inside, `vault` (what the one-off `memclaw` commands call) sits on top, `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`, `run_doctor`), 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/memory-architecture.md b/docs/memory-architecture.md index db29d6f..7ab6266 100644 --- a/docs/memory-architecture.md +++ b/docs/memory-architecture.md @@ -21,6 +21,7 @@ Each chat's conversation lives in the agent backend's own session (for Claude, a - If a session can't be resumed (deleted, created on another machine, ...), a warning is logged and a fresh session starts. - Each saved session records a **fingerprint** of the code-level instructions (the system-prompt template and the backend). A resumed session keeps its original system prompt, so a session created under different instructions (e.g. after an upgrade that changed the template) is not resumed; the chat starts fresh. - `/new` (Telegram command; a message of exactly `/new` in Slack, WhatsApp and the terminal) closes that chat's session and forgets its id. Your memories are untouched. +- The agent keeps this bookkeeping (session keys, the saved sessions, the reminders a chat hasn't seen yet, `/new`) in `ChatSessions`, `memclaw/sessions.py`. - `/model` and `/effort` (Telegram) switch the model or effort level, and the conversation is kept. Claude sessions reconnect on their next message, resuming the same session with the new settings; Cursor passes the model with every message, so its agents just use it. For Cursor, `/effort` is available only on models that expose a reasoning/effort parameter. **What this means in practice:** @@ -127,7 +128,7 @@ Today's file is never consolidated: it is still being written to, and marking it 4. Saves a dated copy of the previous MEMORY.md in `.history/` (the last 60 are kept; the hidden directory isn't indexed or reachable by the file tools), then overwrites MEMORY.md with the result. Lines appended by hand while the backend was working are carried over below the result; if MEMORY.md was otherwise edited meanwhile, nothing is written and consolidation retries later. 5. Records the date of the last file it included in `meta.json` so those files aren't processed again. -All of this is `Consolidator` in `memclaw/memory/consolidation.py`, the only code that writes MEMORY.md. The agent creates it and calls `schedule()` after each reply; `memclaw consolidate` calls `consolidate(force=True, since=...)`. +All of this is `Consolidator` in `memclaw/memory/consolidation.py`, the only code that writes MEMORY.md. The agent creates it and calls `schedule()` after each reply; `memclaw consolidate` creates one through `MemoryVault` with the configured backend, without starting the agent, and calls `consolidate(force=True, since=...)`. The result aims for about 6,000 characters, with absolute dates, in the language MEMORY.md already uses (English when it starts empty). @@ -256,7 +257,7 @@ 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: +All of the above is the `memclaw/memory/` package. Other code imports what its `__init__.py` exports (`MemoryStore`, `MemoryIndex`, `HybridSearch`, `SearchResult`, `Consolidator`, `MemoryVault`), never the modules inside: | Module | What it does | |---|---| @@ -265,6 +266,7 @@ All of the above is the `memclaw/memory/` package. Other code imports what its ` | `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 | +| `vault.py` | `MemoryVault`: the notes and the index opened together, one method per one-off command (`memclaw save`, `search`, `index`, `consolidate`, `status`) | --- diff --git a/docs/upgrading.md b/docs/upgrading.md index 6f8450a..fdb6e23 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -6,6 +6,8 @@ Nothing changes for the `memclaw` command or your `.env`. In the library, `Memcl 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. +A custom agent backend's `run_turn` now takes `run_turn(request, tool_executor)`, where `request` is a `memclaw.backends.TurnRequest` holding the fields that used to be keyword arguments (`system_prompt`, `context`, `user_message`, `session_key`, `resume_session_id`, ...). `ModelInfo` lives in `memclaw.backends.model_selection`. + ## From 2.x to 3.0 ```bash diff --git a/memclaw/agent.py b/memclaw/agent.py index 15e5969..127278e 100644 --- a/memclaw/agent.py +++ b/memclaw/agent.py @@ -22,7 +22,7 @@ from loguru import logger from .backends import AgentBackend, build_backend -from .backends.base import ProgressCallback, TurnResult +from .backends.base import ProgressCallback, TurnRequest, TurnResult from .config import MemclawConfig from .instructions import ( build_system_prompt, @@ -33,7 +33,7 @@ ) from .memory import Consolidator, HybridSearch, MemoryIndex, MemoryStore from .reminders import ReminderScheduler -from .sessions import SessionStore +from .sessions import ChatSessions from .tools import ToolExecutor # Per-turn memory search results. Kept small because every context block @@ -41,9 +41,6 @@ _CONTEXT_RESULTS = 5 _CONTEXT_SNIPPET_CHARS = 500 -# Session key for the interactive terminal (no chat id). -_CLI_SESSION_KEY = "cli" - class MemclawAgent: """Unified agent for both interactive CLI and messaging bots. @@ -62,11 +59,9 @@ def __init__( backend: AgentBackend | None = None, ): self.config = config - self.platform = platform self.store = MemoryStore(config) self.index = MemoryIndex(config) self.search = HybridSearch(config, self.index) - self.scheduler = scheduler self._found_images: list[dict] = [] self._tools = ToolExecutor( config=config, @@ -79,13 +74,11 @@ def __init__( ) self.backend: AgentBackend = backend or build_backend(config) self._backend_started = False - self.sessions = SessionStore(config.memory_dir / "sessions.json") - self._fingerprint = instructions_fingerprint(self.backend.name) - # Delivered reminders not yet seen by the chat's session. - self._pending_notes: dict[str, list[str]] = {} - # Bumped by /new so a turn that was running doesn't re-save the - # session it just reset. - self._generations: dict[str, int] = {} + self.sessions = ChatSessions( + config.memory_dir / "sessions.json", + instructions_fingerprint(self.backend.name), + platform, + ) self.consolidator = Consolidator(config, self.store, self.index, self.backend) # The tool executor holds per-turn state (chat id, found images), so # turns run one at a time, even across chats. @@ -93,25 +86,17 @@ def __init__( # ── Sessions ───────────────────────────────────────────────────── - def _session_key(self, chat_id: str | None) -> str: - if chat_id is None: - return _CLI_SESSION_KEY - return f"{self.platform}:{chat_id}" if self.platform else str(chat_id) - def record_reminder_fired(self, text: str, chat_id: str | None = None): """Remember a delivered reminder so the chat's next message carries it, giving the agent context if the user replies to it.""" - self._pending_notes.setdefault(self._session_key(chat_id), []).append(text) + self.sessions.add_note(chat_id, text) async def reset_conversation(self, chat_id: str | None = None) -> None: """Start a fresh conversation for *chat_id* (the `/new` command).""" - key = self._session_key(chat_id) - self._generations[key] = self._generations.get(key, 0) + 1 # Forget the session before awaiting the backend: a message sent # right after /new may run while the reset is still disconnecting, # and must not resume the old session. - self.sessions.drop(key) - self._pending_notes.pop(key, None) + key = self.sessions.reset(chat_id) await self.backend.reset_session(key) logger.info("Started a new conversation for {k}", k=key) @@ -233,44 +218,41 @@ async def _handle( ) -> tuple[str, list[dict]]: self._found_images.clear() self._tools.chat_id = chat_id - key = self._session_key(chat_id) - generation = self._generations.get(key, 0) + turn = self.sessions.begin(chat_id) agent_instructions = load_agent_instructions(self.config) permanent_memory = load_permanent_memory(self.config) - agents_hash = content_hash(agent_instructions) memory_hash = content_hash(permanent_memory) # A resumed (or live) session has the AGENTS.md / MEMORY.md it last # saw; send whichever changed since, once. - entry = self.sessions.get(key, self._fingerprint) - notes = list(self._pending_notes.get(key, ())) context = await self.build_context( message, - notes=notes, + notes=turn.notes, agents_update=( agent_instructions - if entry and entry.get("agents_hash") != agents_hash else None + if turn.saw_other("agents_hash", content_hash(agent_instructions)) else None ), memory_update=( - permanent_memory - if entry and entry.get("memory_hash") != memory_hash else None + permanent_memory if turn.saw_other("memory_hash", memory_hash) else None ), ) t0 = time.perf_counter() result = await self.backend.run_turn( - # Only used when the backend starts a new session. - system_prompt=build_system_prompt(agent_instructions, permanent_memory), - context=context, - user_message=message, - tool_executor=self._tools, - session_key=key, - resume_session_id=entry["session_id"] if entry else None, - image_b64=image_b64, - image_media_type=image_media_type, - max_turns=10, - on_tool=on_tool, + TurnRequest( + # Only used when the backend starts a new session. + system_prompt=build_system_prompt(agent_instructions, permanent_memory), + context=context, + user_message=message, + session_key=turn.key, + resume_session_id=turn.resume_session_id, + image_b64=image_b64, + image_media_type=image_media_type, + max_turns=10, + on_tool=on_tool, + ), + self._tools, ) self._log_turn(result, int((time.perf_counter() - t0) * 1000)) @@ -279,10 +261,11 @@ async def _handle( # seen too, so they aren't sent back next turn. It never writes # MEMORY.md, so a change to it during the turn (a consolidation) is # still unseen and goes into the next message. - agents_hash = content_hash(load_agent_instructions(self.config)) - self._ack_notes(key, len(notes)) - if result.session_id and self._generations.get(key, 0) == generation: - self._save_session(key, result.session_id, agents_hash, memory_hash) + self.sessions.finish( + turn, result.session_id, + agents_hash=content_hash(load_agent_instructions(self.config)), + memory_hash=memory_hash, + ) self.consolidator.schedule() @@ -308,22 +291,6 @@ def _log_turn(self, result: TurnResult, elapsed_ms: int) -> None: turns=turns, ms=elapsed_ms, tokens=tokens, ) - def _ack_notes(self, key: str, seen: int) -> None: - """Drop the first *seen* pending notes, the ones this turn carried. - Only after the turn succeeded, and only those: a reminder delivered - during the turn stays queued for the next message.""" - pending = self._pending_notes.get(key) - if pending: - del pending[:seen] - - def _save_session(self, key: str, session_id: str, agents_hash: str, memory_hash: str) -> None: - self.sessions.set(key, { - "session_id": session_id, - "fingerprint": self._fingerprint, - "agents_hash": agents_hash, - "memory_hash": memory_hash, - }) - def _close_sync_only(self) -> None: task = getattr(self, "_sync_task", None) if task is not None and not task.done(): diff --git a/memclaw/backends/__init__.py b/memclaw/backends/__init__.py index eaa5885..2c05fca 100644 --- a/memclaw/backends/__init__.py +++ b/memclaw/backends/__init__.py @@ -11,7 +11,7 @@ from typing import TYPE_CHECKING -from .base import AgentBackend, TurnResult +from .base import AgentBackend, TurnRequest, TurnResult from .claude import ClaudeAgentBackend from .cursor import CursorAgentBackend @@ -50,15 +50,40 @@ def build_backend(config: "MemclawConfig") -> AgentBackend: return get_backend_class(resolve_backend_name(config))(config) +def configuration_problem(config: "MemclawConfig") -> str | None: + """Why the backend *config* chooses can't run (an unknown name, missing + credentials), as a message for the user with Rich markup; None if it can.""" + name = resolve_backend_name(config) + backend_cls = REGISTRY.get(name) + if backend_cls is None: + known = ", ".join(REGISTRY) or "(none)" + return ( + f"unknown agent backend [bold]{name}[/bold] " + f"(set via AGENT_BACKEND). Available: {known}.\n" + "Run [bold]memclaw configure[/bold] to pick a valid backend." + ) + if backend_cls.is_configured(config): + return None + return f"{backend_cls.configuration_help()}\nRun [bold]memclaw configure[/bold] to set it." + + +def status_rows(config: "MemclawConfig") -> list[tuple[str, str]]: + """``(label, value)`` pairs `memclaw status` shows for the chosen backend.""" + return get_backend_class(resolve_backend_name(config)).status_rows(config) + + __all__ = [ "AgentBackend", "ClaudeAgentBackend", "CursorAgentBackend", "DEFAULT_BACKEND", "REGISTRY", + "TurnRequest", "TurnResult", "build_backend", + "configuration_problem", "get_backend_class", "list_backends", "resolve_backend_name", + "status_rows", ] diff --git a/memclaw/backends/base.py b/memclaw/backends/base.py index 3180ab9..7c0b54d 100644 --- a/memclaw/backends/base.py +++ b/memclaw/backends/base.py @@ -31,7 +31,7 @@ class in `memclaw.backends.__init__.REGISTRY`. Nothing else in the project from ..config import MemclawConfig from ..tools import ToolExecutor - from .claude_models import ModelInfo + from .model_selection import ModelInfo @dataclass @@ -68,6 +68,31 @@ class ToolStep: ProgressCallback = Callable[[ToolStep], Awaitable[None]] +@dataclass +class TurnRequest: + """One user message for `AgentBackend.run_turn`, in the conversation + identified by ``session_key``.""" + + # Static per session: only used when the backend starts a new session. + system_prompt: str + # The per-turn context block (time, relevant memories, ...) that must + # reach the model with this message, ahead of ``user_message``. + context: str + user_message: str + session_key: str + # The session to resume if the backend has to (re)connect; if it can't + # be resumed the backend starts a fresh one. + resume_session_id: str | None = None + image_b64: str | None = None + image_media_type: str = "image/jpeg" + # Passed to SDKs that support it (e.g. Claude). Backends without a + # native cap should log when reported turns exceed it after the run. + max_turns: int = 10 + # Called (via `report_tool_step`) for every tool call the agent makes, + # for progress messages. + on_tool: ProgressCallback | None = None + + async def report_tool_step( on_tool: ProgressCallback | None, index: int, name: str, args: Any, ) -> None: @@ -172,40 +197,13 @@ async def run_one_shot( if the call failed, rather than returning an error message as text.""" ... - async def run_turn( - self, - *, - system_prompt: str, - context: str, - user_message: str, - tool_executor: "ToolExecutor", - session_key: str, - resume_session_id: str | None = None, - image_b64: str | None = None, - image_media_type: str = "image/jpeg", - max_turns: int = 10, - on_tool: ProgressCallback | None = None, - ) -> TurnResult: - """Run one full agentic turn with tool access, in the conversation - identified by *session_key*. - - ``system_prompt`` is static per session: it is only used when the - backend starts a new session. ``context`` is the per-turn context - block (time, relevant memories, ...) that must reach the model with - this message, ahead of ``user_message``. ``resume_session_id`` is - the session to resume if the backend has to (re)connect; if it can't - be resumed the backend starts a fresh one. - - ``on_tool`` is called (via `report_tool_step`) for every tool call - the agent makes, for progress messages. + async def run_turn(self, request: TurnRequest, tool_executor: "ToolExecutor") -> TurnResult: + """Run one full agentic turn with tool access for *request* (see + `TurnRequest`), in the conversation identified by its session_key. The backend is responsible for translating ``TOOL_DEFINITIONS`` into its SDK's tool format and routing tool calls back through ``tool_executor.execute(name, args)``. - - ``max_turns`` is passed to SDKs that support it (e.g. Claude). - Backends without a native cap should log when reported turns exceed - this limit after the run completes. """ ... @@ -245,4 +243,4 @@ async def set_effort(self, level: str) -> None: # Subclasses register themselves through this attribute name; see # memclaw/backends/__init__.py. -__all__ = ["AgentBackend", "TurnResult"] +__all__ = ["AgentBackend", "TurnRequest", "TurnResult"] diff --git a/memclaw/backends/claude.py b/memclaw/backends/claude.py index 202a27f..450204d 100644 --- a/memclaw/backends/claude.py +++ b/memclaw/backends/claude.py @@ -31,10 +31,10 @@ from ..config import process_environment 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 +from .base import ProgressCallback, TurnRequest, TurnResult, report_tool_step +from .claude_models import SDK_EFFORT_LEVELS, fetch_models from .mcp_tools import MCP_SERVER_NAME -from .model_selection import ModelSelectionMixin +from .model_selection import ModelInfo, ModelSelectionMixin if TYPE_CHECKING: from rich.console import Console @@ -657,49 +657,36 @@ async def run_one_shot( raise RuntimeError(f"Claude one-shot failed ({error}): {result_text[:200]}") return result_text - async def run_turn( - self, - *, - system_prompt: str, - context: str, - user_message: str, - tool_executor: "ToolExecutor", - session_key: str, - resume_session_id: str | None = None, - image_b64: str | None = None, - image_media_type: str = "image/jpeg", - max_turns: int = 10, - on_tool: ProgressCallback | None = None, - ) -> TurnResult: + async def run_turn(self, request: TurnRequest, tool_executor: "ToolExecutor") -> TurnResult: if self._mcp_server is None: self._mcp_server = _build_mcp_server(tool_executor) - session = self._sessions.setdefault(session_key, _Session()) + session = self._sessions.setdefault(request.session_key, _Session()) async with session.lock: options_key = (self._model, self._effort) if session.client is not None and session.options_key != options_key: await self._disconnect(session) if session.client is None: session.client = await self._connect( - system_prompt=system_prompt, - resume=resume_session_id, - max_turns=max_turns, + system_prompt=request.system_prompt, + resume=request.resume_session_id, + max_turns=request.max_turns, ) session.options_key = options_key try: result = await self._query( session.client, - _compose_prompt(context, user_message), - image_b64=image_b64, - image_media_type=image_media_type, - on_tool=on_tool, + _compose_prompt(request.context, request.user_message), + image_b64=request.image_b64, + image_media_type=request.image_media_type, + on_tool=request.on_tool, ) except BaseException: # The CLI may be dead or mid-turn; reconnect (resuming) next time. await self._disconnect(session) raise - result.cost_usd = self._turn_cost(result, resume_session_id) + result.cost_usd = self._turn_cost(result, request.resume_session_id) return result def _turn_cost(self, result: TurnResult, resume_session_id: str | None) -> float | None: diff --git a/memclaw/backends/claude_models.py b/memclaw/backends/claude_models.py index 7e1ba69..7413103 100644 --- a/memclaw/backends/claude_models.py +++ b/memclaw/backends/claude_models.py @@ -12,12 +12,13 @@ from __future__ import annotations -from dataclasses import dataclass from datetime import datetime, timezone from typing import Any import httpx +from .model_selection import ModelInfo + MODELS_URL = "https://api.anthropic.com/v1/models" API_VERSION = "2023-06-01" @@ -34,14 +35,6 @@ SDK_EFFORT_LEVELS = ("low", "medium", "high", "xhigh", "max") -@dataclass -class ModelInfo: - id: str - display_name: str - created_at: str - effort_levels: list[str] # empty when the model has no effort support - - # ── Request building ──────────────────────────────────────────────── def _build_headers(auth_mode: str, credential: str) -> dict[str, str]: diff --git a/memclaw/backends/cursor.py b/memclaw/backends/cursor.py index ef941a2..48b8c6c 100644 --- a/memclaw/backends/cursor.py +++ b/memclaw/backends/cursor.py @@ -20,12 +20,11 @@ from ..config import set_environment from ..terminal_input import masked_input -from .base import ProgressCallback, TurnResult -from .claude_models import ModelInfo +from .base import ProgressCallback, TurnRequest, TurnResult from .cursor_hooks import cursor_hooks_status, ensure_cursor_hooks from .cursor_sdk_adapter import RunUsageTracker, collect_run_result, extract_run_text from .mcp_bridge import HttpMcpServer, mcp_servers_for -from .model_selection import ModelSelectionMixin +from .model_selection import ModelInfo, ModelSelectionMixin if TYPE_CHECKING: from rich.console import Console @@ -540,20 +539,7 @@ async def run_one_shot(self, *, system_prompt: str, user_message: str) -> str: raise RuntimeError("Cursor SDK one-shot returned no text") return text - async def run_turn( - self, - *, - system_prompt: str, - context: str, - user_message: str, - tool_executor: "ToolExecutor", - session_key: str, - resume_session_id: str | None = None, - image_b64: str | None = None, - image_media_type: str = "image/jpeg", - max_turns: int = 10, - on_tool: ProgressCallback | None = None, - ) -> TurnResult: + async def run_turn(self, request: TurnRequest, tool_executor: "ToolExecutor") -> TurnResult: from cursor_sdk import CursorAgentError # optional dependency (cursor-sdk) if not self._api_key: @@ -565,28 +551,28 @@ async def run_turn( raise RuntimeError("MCP server failed to start") mcp_servers = mcp_servers_for(mcp_config) - session = self._sessions.setdefault(session_key, _Session()) + session = self._sessions.setdefault(request.session_key, _Session()) async with session.lock: client = await self._get_client() try: agent = await self._ensure_agent( - session, client, resume=resume_session_id, mcp_servers=mcp_servers, + session, client, resume=request.resume_session_id, mcp_servers=mcp_servers, ) message = _build_user_message( # A Cursor agent has no system-prompt field; a new one # gets it at the top of its first message. - system_prompt=system_prompt if agent == "created" else "", - context=context, - user_message=user_message, - image_b64=image_b64, - image_media_type=image_media_type, + system_prompt=request.system_prompt if agent == "created" else "", + context=request.context, + user_message=request.user_message, + image_b64=request.image_b64, + image_media_type=request.image_media_type, ) result = await self._send( session.agent, message, mcp_servers=mcp_servers, # A resumed agent may still show a run that died with # the previous process; take it over. force=agent == "resumed", - max_turns=max_turns, on_tool=on_tool, + max_turns=request.max_turns, on_tool=request.on_tool, ) except BaseException as exc: # The agent may be mid-run or gone; reopen (resuming) next time. diff --git a/memclaw/backends/model_selection.py b/memclaw/backends/model_selection.py index b6a0793..34db382 100644 --- a/memclaw/backends/model_selection.py +++ b/memclaw/backends/model_selection.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import dataclass from typing import TYPE_CHECKING, ClassVar from loguru import logger @@ -10,7 +11,16 @@ if TYPE_CHECKING: from ..config import ClaudeSettings, CursorSettings, MemclawConfig - from .claude_models import ModelInfo + + +@dataclass +class ModelInfo: + """A model a backend's credential can use, as /model lists it.""" + + id: str + display_name: str + created_at: str + effort_levels: list[str] # empty when the model has no effort support class ModelSelectionMixin: @@ -30,9 +40,9 @@ class ModelSelectionMixin: config: "MemclawConfig" _model: str _effort: str | None - _models: list["ModelInfo"] + _models: list[ModelInfo] - async def list_models(self) -> list["ModelInfo"]: + async def list_models(self) -> list[ModelInfo]: raise NotImplementedError @property @@ -43,7 +53,7 @@ def model(self) -> str: def effort(self) -> str | None: return self._effort - async def _model_info(self, model_id: str) -> "ModelInfo | None": + async def _model_info(self, model_id: str) -> ModelInfo | None: """*model_id*'s entry in the model list, or None if it isn't listed or the list can't be fetched.""" if not self._models: @@ -54,7 +64,7 @@ async def _model_info(self, model_id: str) -> "ModelInfo | None": return None return next((m for m in self._models if m.id == model_id), None) - async def _known_model(self, model_id: str) -> "ModelInfo": + async def _known_model(self, model_id: str) -> ModelInfo: """*model_id*'s entry, or ValueError. An id that can't be checked (the list didn't load) is refused too: a typo would break every turn until ~/.memclaw/.env is fixed by hand.""" diff --git a/memclaw/bot/__init__.py b/memclaw/bot/__init__.py index aa1439b..9a8d2c7 100644 --- a/memclaw/bot/__init__.py +++ b/memclaw/bot/__init__.py @@ -1,9 +1,10 @@ -"""The chat apps Memclaw runs on. +"""The places Memclaw chats in: the chat apps and the terminal. -Each platform is one module here (`telegram.py`, `slack.py`, `whatsapp.py`) -that only does that app's I/O: receive a message, download its media, send -the reply. What happens in between (voice to text, link summaries, the -prompt, the agent call, reminders) is shared, in `inbound.py`. +Each platform is one module here. The chat apps' (`telegram.py`, +`slack.py`, `whatsapp.py`) only do that app's I/O: receive a message, +download its media, send the reply. What happens in between (voice to text, +link summaries, the prompt, the agent call, reminders) is shared, in +`inbound.py`. `terminal.py` is the chat in the shell that runs `memclaw`. Each platform module has a `run(config)` that starts it. The bare `memclaw` command and the setup wizard find the platforms in `PLATFORMS` below, so @@ -30,7 +31,7 @@ @dataclass(frozen=True) class Platform: - """A chat app; its code is the module `memclaw/bot/.py`.""" + """A place to chat in; its code is the module `memclaw/bot/.py`.""" name: str label: str # shown by the setup wizard @@ -47,9 +48,23 @@ def run(self, config: MemclawConfig) -> None: Platform("telegram", "Telegram"), Platform("whatsapp", "WhatsApp"), Platform("slack", "Slack"), + Platform("terminal", "Terminal chat"), ) } +# What the bare `memclaw` starts when MEMCLAW_PLATFORM is empty or unknown. +DEFAULT_PLATFORM = "terminal" + + +def chosen_platform(config: MemclawConfig) -> Platform: + """The platform *config* names (MEMCLAW_PLATFORM), else the terminal.""" + return PLATFORMS.get(config.platform) or PLATFORMS[DEFAULT_PLATFORM] + + +def status_rows(config: MemclawConfig) -> list[tuple[str, object]]: + """``(label, value)`` pairs `memclaw status` shows for the platform.""" + return [("Platform", config.platform or DEFAULT_PLATFORM)] + def mask_user_id(user_id: str | int) -> str: """Mask the middle of a user identifier for log safety. @@ -71,12 +86,13 @@ def require_setting(value: str, env_var: str) -> None: raise SystemExit(1) -def log_to(log_file: Path) -> None: - """Log INFO to the terminal and DEBUG to *log_file* (rotated).""" +def log_to(log_file: Path | None = None) -> None: + """Log INFO to the terminal and, with a *log_file*, DEBUG to it (rotated).""" logger.remove() logger.add( sys.stderr, level="INFO", format="{time:HH:mm:ss} | {level:<8} | {message}", ) - logger.add(str(log_file), rotation="10 MB", retention="7 days", level="DEBUG") + if log_file is not None: + logger.add(str(log_file), rotation="10 MB", retention="7 days", level="DEBUG") diff --git a/memclaw/bot/terminal.py b/memclaw/bot/terminal.py new file mode 100644 index 0000000..b8040b5 --- /dev/null +++ b/memclaw/bot/terminal.py @@ -0,0 +1,83 @@ +"""The terminal: chat with Memclaw in the shell that runs `memclaw`. + +Unlike the chat apps there's nothing to download or transcribe: a line +typed at the prompt goes straight to the agent, and its reply is printed +as Markdown. +""" + +from __future__ import annotations + +import asyncio + +from rich.markdown import Markdown +from rich.panel import Panel + +from ..agent import MemclawAgent +from ..config import MemclawConfig +from . import console, log_to + +_QUIT = ("/quit", "/exit", "quit", "exit") + + +async def chat(agent: MemclawAgent) -> None: + """Read messages from the terminal and print the agent's replies, until + the user quits (`/quit`, Ctrl-D or Ctrl-C). `/new` starts a fresh + conversation.""" + while True: + try: + user_input = console.input("[bold green]> [/bold green]") + except (EOFError, KeyboardInterrupt): + return + + stripped = user_input.strip() + if stripped.lower() in _QUIT: + return + if not stripped: + continue + if stripped.lower() == "/new": + await agent.reset_conversation() + console.print("[cyan]Started a new conversation.[/cyan]\n") + continue + + try: + with console.status("[cyan]Thinking...[/cyan]"): + response, _images = await agent.handle(stripped) + except Exception as e: + console.print(f"\n[red]Error:[/red] {e}\n") + continue + + if response: + console.print() + console.print(Markdown(response)) + console.print() + + +async def _run(config: MemclawConfig) -> None: + console.print( + Panel( + "[bold]Memclaw[/bold] — Your Personal Memory Vault\n\n" + "Type your thoughts, questions, or commands.\n" + "Type [bold]/new[/bold] to start a fresh conversation, " + "[bold]/quit[/bold] to exit.", + title="memclaw", + border_style="bright_cyan", + ) + ) + + agent = MemclawAgent(config) + + # Spec #9: run a full index sync once at startup + with console.status("[cyan]Syncing index...[/cyan]"): + await agent.start() + + try: + await chat(agent) + finally: + await agent.aclose() + console.print("\nGoodbye! Your memories are safe.") + + +def run(config: MemclawConfig) -> None: + """Chat in the terminal and block until the user quits.""" + log_to() + asyncio.run(_run(config)) diff --git a/memclaw/cli.py b/memclaw/cli.py index b726cfb..e1e73a7 100644 --- a/memclaw/cli.py +++ b/memclaw/cli.py @@ -1,61 +1,39 @@ +"""The `memclaw` command: reads the arguments and hands each command to the +code that does it (memclaw.bot, memclaw.memory, memclaw.setup).""" + from __future__ import annotations import asyncio +from datetime import date from pathlib import Path import click from rich.console import Console -from rich.markdown import Markdown from rich.panel import Panel -from .bot import PLATFORMS +from . import backends, bot from .config import MemclawConfig, reload_env_file -from .memory import HybridSearch, MemoryIndex, MemoryStore -from .setup import needs_setup, print_logo, print_probe_report, run_setup +from .memory import MemoryVault +from .setup import needs_setup, print_logo, run_doctor, run_setup console = Console() -def _require_backend_auth(config: MemclawConfig) -> None: - """Exit with a helpful message unless the chosen backend is configured.""" - from .backends import REGISTRY, get_backend_class, resolve_backend_name - - name = resolve_backend_name(config) - try: - backend_cls = get_backend_class(name) - except ValueError: - known = ", ".join(REGISTRY) or "(none)" - console.print( - f"[red]Error:[/red] unknown agent backend [bold]{name}[/bold] " - f"(set via AGENT_BACKEND). Available: {known}.\n" - "Run [bold]memclaw configure[/bold] to pick a valid backend." - ) +def _require_backend(config: MemclawConfig) -> None: + """Exit with a helpful message unless the chosen backend can run.""" + problem = backends.configuration_problem(config) + if problem: + console.print(f"[red]Error:[/red] {problem}") raise SystemExit(1) - if backend_cls.is_configured(config): - return - console.print( - f"[red]Error:[/red] {backend_cls.configuration_help()}\n" - "Run [bold]memclaw configure[/bold] to set it." - ) - raise SystemExit(1) def _require_openai(config: MemclawConfig) -> None: - if not config.openai.api_key: - console.print("[red]Error:[/red] OPENAI_API_KEY is not set.") - console.print("Run [bold]memclaw configure[/bold] to set it.") - raise SystemExit(1) + bot.require_setting(config.openai.api_key, "OPENAI_API_KEY") -def _ensure_setup(ctx): - """Run first-time setup if ~/.memclaw/.env doesn't exist, then reload config.""" - if needs_setup(): - run_setup(ctx.obj["config"]) - # Reload .env so newly saved keys are picked up - reload_env_file() - memory_dir = ctx.obj.get("memory_dir") - config = MemclawConfig(memory_dir=memory_dir) if memory_dir else MemclawConfig() - ctx.obj["config"] = config +def _config(ctx: click.Context) -> MemclawConfig: + memory_dir = ctx.obj["memory_dir"] + return MemclawConfig(memory_dir=memory_dir) if memory_dir else MemclawConfig() @click.group(invoke_without_command=True) @@ -70,94 +48,20 @@ def cli(ctx, memory_dir): """Memclaw -- your personal memory vault, powered by AI.""" ctx.ensure_object(dict) ctx.obj["memory_dir"] = memory_dir - config = MemclawConfig(memory_dir=memory_dir) if memory_dir else MemclawConfig() - ctx.obj["config"] = config + ctx.obj["config"] = _config(ctx) if ctx.invoked_subcommand is None: print_logo() - _ensure_setup(ctx) + if needs_setup(): + # First run: the wizard writes ~/.memclaw/.env; read it back in. + run_setup(ctx.obj["config"]) + reload_env_file() + ctx.obj["config"] = _config(ctx) config = ctx.obj["config"] - _require_backend_auth(config) + _require_backend(config) _require_openai(config) + bot.chosen_platform(config).run(config) - platform = PLATFORMS.get(config.platform) - if platform is not None: - platform.run(config) - else: - asyncio.run(_interactive(config)) - - -# ------------------------------------------------------------------ -# Interactive (terminal) mode -# ------------------------------------------------------------------ - -async def _interactive(config: MemclawConfig): - import sys - - from loguru import logger - - from .agent import MemclawAgent - - logger.remove() - logger.add( - sys.stderr, - level="INFO", - format="{time:HH:mm:ss} | {level:<8} | {message}", - ) - - console.print( - Panel( - "[bold]Memclaw[/bold] — Your Personal Memory Vault\n\n" - "Type your thoughts, questions, or commands.\n" - "Type [bold]/new[/bold] to start a fresh conversation, " - "[bold]/quit[/bold] to exit.", - title="memclaw", - border_style="bright_cyan", - ) - ) - - agent = MemclawAgent(config) - - # Spec #9: run a full index sync once at startup - with console.status("[cyan]Syncing index...[/cyan]"): - await agent.start() - - try: - while True: - try: - user_input = console.input("[bold green]> [/bold green]") - except (EOFError, KeyboardInterrupt): - break - - stripped = user_input.strip() - if stripped.lower() in ("/quit", "/exit", "quit", "exit"): - break - if not stripped: - continue - if stripped.lower() == "/new": - await agent.reset_conversation() - console.print("[cyan]Started a new conversation.[/cyan]\n") - continue - - try: - with console.status("[cyan]Thinking...[/cyan]"): - response, _images = await agent.handle(stripped) - except Exception as e: - console.print(f"\n[red]Error:[/red] {e}\n") - continue - - if response: - console.print() - console.print(Markdown(response)) - console.print() - finally: - await agent.aclose() - console.print("\nGoodbye! Your memories are safe.") - - -# ------------------------------------------------------------------ -# Direct commands (work without the Claude agent / Anthropic key) -# ------------------------------------------------------------------ @cli.command() @click.argument("content") @@ -165,13 +69,9 @@ async def _interactive(config: MemclawConfig): def save(ctx, content): """Save a memory directly (no agent needed).""" config: MemclawConfig = ctx.obj["config"] - store = MemoryStore(config) - index = MemoryIndex(config) - - file_path = store.save(content) - asyncio.run(index.index_file(file_path)) - index.close() - + _require_openai(config) + with MemoryVault(config) as vault: + file_path = asyncio.run(vault.save(content)) console.print(f"[green]✓[/green] Memory saved to [bold]{file_path.name}[/bold]") @@ -182,22 +82,18 @@ def save(ctx, content): def search(ctx, query_text, limit): """Search your memories (no agent needed).""" config: MemclawConfig = ctx.obj["config"] - index = MemoryIndex(config) - engine = HybridSearch(config, index) - - results = asyncio.run(engine.search(query_text, limit=limit)) - index.close() + _require_openai(config) + with MemoryVault(config) as vault: + results = asyncio.run(vault.search(query_text, limit=limit)) if not results: console.print("[yellow]No matching memories found.[/yellow]") return - for i, r in enumerate(results, 1): - source = Path(r.file_path).stem console.print( Panel( r.content.strip(), - title=f"[{i}] {source} (score: {r.score:.2f}, {r.match_type})", + title=f"[{i}] {Path(r.file_path).stem} (score: {r.score:.2f}, {r.match_type})", border_style="blue", ) ) @@ -208,38 +104,30 @@ def search(ctx, query_text, limit): @click.pass_context def consolidate(ctx, since_date): """Consolidate daily memory files into MEMORY.md.""" - from datetime import date as date_type - - from .agent import MemclawAgent - config: MemclawConfig = ctx.obj["config"] - - _require_backend_auth(config) + _require_backend(config) _require_openai(config) - override = None + since = None if since_date: try: - override = date_type.fromisoformat(since_date) + since = date.fromisoformat(since_date) except ValueError: console.print(f"[red]Error:[/red] Invalid date format: {since_date}. Use YYYY-MM-DD.") raise SystemExit(1) - async def _run(): - agent = MemclawAgent(config) - try: - with console.status("[cyan]Syncing index...[/cyan]"): - await agent.start(include_backend=False) - with console.status("[cyan]Running consolidation...[/cyan]"): - result = await agent.consolidator.consolidate(force=True, since=override) - if result: - console.print("[green]Consolidation complete.[/green] MEMORY.md has been updated.") - else: - console.print("[yellow]No daily files to consolidate.[/yellow]") - finally: - await agent.aclose() + async def _run(vault: MemoryVault) -> bool: + backend = backends.build_backend(config) + with console.status("[cyan]Syncing index...[/cyan]"): + await vault.sync_or_warn() + with console.status("[cyan]Running consolidation...[/cyan]"): + return await vault.consolidate(backend, since=since) - asyncio.run(_run()) + with MemoryVault(config) as vault: + if asyncio.run(_run(vault)): + console.print("[green]Consolidation complete.[/green] MEMORY.md has been updated.") + else: + console.print("[yellow]No daily files to consolidate.[/yellow]") @cli.command(name="index") @@ -247,14 +135,11 @@ async def _run(): def rebuild_index(ctx): """Rebuild the search index from all memory files.""" config: MemclawConfig = ctx.obj["config"] - index = MemoryIndex(config) - - changed = asyncio.run(index.sync()) - stats = index.get_stats() - index.close() + _require_openai(config) + with MemoryVault(config) as vault: + changed, stats = asyncio.run(vault.reindex()) - label = "updated" if changed else "already up to date" - console.print(f"[green]✓[/green] Index {label}") + console.print(f"[green]✓[/green] Index {'updated' if changed else 'already up to date'}") console.print(f" Chunks: {stats['chunks']} Files: {stats['files']}") @@ -262,27 +147,14 @@ def rebuild_index(ctx): @click.pass_context def status(ctx): """Show memory vault status.""" - from .backends import get_backend_class, resolve_backend_name - config: MemclawConfig = ctx.obj["config"] - store = MemoryStore(config) - index = MemoryIndex(config) - - files = store.list_files() - stats = index.get_stats() - index.close() - - backend_cls = get_backend_class(resolve_backend_name(config)) - rows = [ - ("Memory directory", config.memory_dir), - ("Memory files", len(files)), - ("Platform", config.platform or "terminal"), - *backend_cls.status_rows(config), - ("Indexed chunks", stats["chunks"]), - ("Stored images", stats["images"]), - ("Database", config.db_path), - ] - + with MemoryVault(config) as vault: + rows = [ + *vault.store.status_rows(), + *bot.status_rows(config), + *backends.status_rows(config), + *vault.index.status_rows(), + ] console.print( Panel( "\n".join(f"{label:<16} : {value}" for label, value in rows), @@ -304,13 +176,7 @@ def configure(ctx): @click.pass_context def doctor(ctx): """Check that your OpenAI key can reach every model Memclaw uses.""" - from .openai_client import probe_openai - config: MemclawConfig = ctx.obj["config"] _require_openai(config) - - with console.status("[cyan]Probing OpenAI...[/cyan]"): - report = asyncio.run(probe_openai(config.openai.api_key)) - print_probe_report(report, console) - if not report.all_ok: + if not run_doctor(config.openai.api_key, console): raise SystemExit(1) diff --git a/memclaw/memory/__init__.py b/memclaw/memory/__init__.py index 6169fab..3aa2ef5 100644 --- a/memclaw/memory/__init__.py +++ b/memclaw/memory/__init__.py @@ -14,6 +14,8 @@ - `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. +- `MemoryVault` (vault.py): the notes and the index opened together, one + method per one-off `memclaw` command (save, search, index, consolidate). Other code imports from `memclaw.memory`, not from the modules inside. """ @@ -22,5 +24,13 @@ from .index import MemoryIndex from .notes import MemoryStore from .search import HybridSearch, SearchResult +from .vault import MemoryVault -__all__ = ["Consolidator", "HybridSearch", "MemoryIndex", "MemoryStore", "SearchResult"] +__all__ = [ + "Consolidator", + "HybridSearch", + "MemoryIndex", + "MemoryStore", + "MemoryVault", + "SearchResult", +] diff --git a/memclaw/memory/index.py b/memclaw/memory/index.py index f7e1b9f..1a10154 100644 --- a/memclaw/memory/index.py +++ b/memclaw/memory/index.py @@ -425,5 +425,14 @@ def get_stats(self) -> dict: images = self.db.execute("SELECT COUNT(*) FROM platform_images").fetchone()[0] return {"chunks": chunks, "files": files, "images": images} + def status_rows(self) -> list[tuple[str, object]]: + """``(label, value)`` pairs `memclaw status` shows for the index.""" + stats = self.get_stats() + return [ + ("Indexed chunks", stats["chunks"]), + ("Stored images", stats["images"]), + ("Database", self.config.db_path), + ] + def close(self): self.db.close() diff --git a/memclaw/memory/notes.py b/memclaw/memory/notes.py index 68c32e5..a51fb48 100644 --- a/memclaw/memory/notes.py +++ b/memclaw/memory/notes.py @@ -66,6 +66,13 @@ def list_files(self) -> list[Path]: files.extend(sorted(self.config.memory_subdir.glob("*.md"))) return files + def status_rows(self) -> list[tuple[str, object]]: + """``(label, value)`` pairs `memclaw status` shows for the notes.""" + return [ + ("Memory directory", self.config.memory_dir), + ("Memory files", len(self.list_files())), + ] + _DAILY_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})\.md$") def list_unconsolidated_files(self, consolidated_through: date | None = None) -> list[Path]: diff --git a/memclaw/memory/vault.py b/memclaw/memory/vault.py new file mode 100644 index 0000000..bc2e761 --- /dev/null +++ b/memclaw/memory/vault.py @@ -0,0 +1,70 @@ +"""The notes and their index together, for the one-off `memclaw` commands. + +`memclaw save`, `search`, `index`, `consolidate` and `status` each open the +notes and the index, do one thing and close them again: one `MemoryVault` +method per command. (The agent keeps its own store and index open for as +long as it runs.) +""" + +from __future__ import annotations + +from datetime import date +from pathlib import Path + +from loguru import logger + +from ..config import MemclawConfig +from .consolidation import Consolidator, OneShotBackend +from .index import MemoryIndex +from .notes import MemoryStore +from .search import HybridSearch, SearchResult + + +class MemoryVault: + """The notes (`store`) and their search index (`index`); use it as a + context manager, which closes the index.""" + + def __init__(self, config: MemclawConfig): + self.config = config + self.store = MemoryStore(config) + self.index = MemoryIndex(config) + + def __enter__(self) -> MemoryVault: + return self + + def __exit__(self, *_exc_info: object) -> None: + self.index.close() + + async def save(self, content: str) -> Path: + """Add *content* to today's daily note and index it. Returns the + daily file.""" + file_path = self.store.save(content) + await self.index.index_file(file_path) + return file_path + + async def search(self, query: str, *, limit: int) -> list[SearchResult]: + """The notes' chunks that best match *query* (see HybridSearch).""" + return await HybridSearch(self.config, self.index).search(query, limit=limit) + + async def reindex(self) -> tuple[bool, dict[str, int]]: + """Re-index the notes that changed. Returns whether anything did, and + the index's counts (chunks, files, images).""" + changed = await self.index.sync() + return changed, self.index.get_stats() + + async def sync_or_warn(self) -> None: + """Re-index the notes that changed; a failure (e.g. OpenAI + unreachable) is logged, not raised.""" + try: + await self.index.sync() + except Exception as exc: + logger.warning("Index sync at startup failed: {exc}", exc=exc) + + async def consolidate(self, backend: OneShotBackend, *, since: date | None = None) -> bool: + """Distill the daily notes into MEMORY.md now, with *backend*'s LLM. + Returns False if there was nothing to consolidate.""" + consolidator = Consolidator(self.config, self.store, self.index, backend) + try: + return await consolidator.consolidate(force=True, since=since) + finally: + await consolidator.aclose() diff --git a/memclaw/sessions.py b/memclaw/sessions.py index a5f0f1f..4a26f31 100644 --- a/memclaw/sessions.py +++ b/memclaw/sessions.py @@ -1,7 +1,10 @@ -"""Persisted per-chat conversation sessions. +"""Per-chat conversation sessions. -Maps a chat's session key to the backend session id the conversation lives -in, so a restarted Memclaw resumes it. Each entry also records: +`ChatSessions` is the agent's bookkeeping for each chat: which conversation +it is in, the reminders it hasn't seen yet, and `/new`. `SessionStore` is +the saved part (sessions.json): it maps a chat's session key to the +backend session id the conversation lives in, so a restarted Memclaw +resumes it. Each entry also records: - ``fingerprint`` — hash of the code-level instructions (system-prompt template + backend) the session started with. Claude Code keeps a @@ -14,10 +17,14 @@ from __future__ import annotations import json +from dataclasses import dataclass from pathlib import Path from loguru import logger +# Session key for the interactive terminal (no chat id). +_CLI_SESSION_KEY = "cli" + class SessionStore: """``{session_key: {session_id, fingerprint, agents_hash, memory_hash}}`` @@ -63,3 +70,93 @@ def _save(self) -> None: tmp = self.path.with_suffix(".tmp") tmp.write_text(json.dumps(self._data, indent=2)) tmp.replace(self.path) + + +@dataclass +class TurnStart: + """A chat's session as a turn begins (`ChatSessions.begin`).""" + + key: str + # /new count when the turn began; a turn that a /new overtook doesn't + # save its session. + generation: int + # The saved session to resume, or None. + entry: dict[str, str] | None + # Reminders delivered since the chat's last message. + notes: list[str] + + @property + def resume_session_id(self) -> str | None: + return self.entry["session_id"] if self.entry else None + + def saw_other(self, field: str, content_hash: str) -> bool: + """Whether the resumed session saw another version of a file than + *content_hash* (*field*: "agents_hash" or "memory_hash").""" + return self.entry is not None and self.entry.get(field) != content_hash + + +class ChatSessions: + """Each chat's conversation: its saved backend session (resumed unless + the instructions changed, see *fingerprint*), the reminders delivered + since its last message, and `/new`.""" + + def __init__(self, path: Path, fingerprint: str, platform: str | None = None) -> None: + self._store = SessionStore(path) + self.fingerprint = fingerprint + self._platform = platform + self._pending_notes: dict[str, list[str]] = {} + # Bumped by /new so a turn that was running doesn't re-save the + # session it just reset. + self._generations: dict[str, int] = {} + + def key(self, chat_id: str | None) -> str: + """The session key of *chat_id*: `:`, or "cli" + for the terminal (no chat id).""" + if chat_id is None: + return _CLI_SESSION_KEY + return f"{self._platform}:{chat_id}" if self._platform else str(chat_id) + + def saved(self, key: str) -> dict[str, str] | None: + """The saved session of *key* that would be resumed, or None.""" + return self._store.get(key, self.fingerprint) + + def add_note(self, chat_id: str | None, text: str) -> None: + """Queue a delivered reminder for the chat's next message.""" + self._pending_notes.setdefault(self.key(chat_id), []).append(text) + + def reset(self, chat_id: str | None) -> str: + """Forget the chat's session and queued reminders (`/new`). Returns + its session key.""" + key = self.key(chat_id) + self._generations[key] = self._generations.get(key, 0) + 1 + self._store.drop(key) + self._pending_notes.pop(key, None) + return key + + def begin(self, chat_id: str | None) -> TurnStart: + """What the chat's session has seen, as a turn begins.""" + key = self.key(chat_id) + return TurnStart( + key=key, + generation=self._generations.get(key, 0), + entry=self.saved(key), + notes=list(self._pending_notes.get(key, ())), + ) + + def finish( + self, turn: TurnStart, session_id: str | None, *, agents_hash: str, memory_hash: str, + ) -> None: + """After a successful turn: the session has seen *turn*'s notes and + these file versions. Only those notes are dropped (a reminder + delivered during the turn stays queued), and the session is saved + unless a /new came in meanwhile.""" + pending = self._pending_notes.get(turn.key) + if pending: + del pending[:len(turn.notes)] + if session_id and self._generations.get(turn.key, 0) == turn.generation: + self._store.set(turn.key, { + "session_id": session_id, + "fingerprint": self.fingerprint, + "agents_hash": agents_hash, + "memory_hash": memory_hash, + }) diff --git a/memclaw/setup/__init__.py b/memclaw/setup/__init__.py index 05b3ec5..d0cb92a 100644 --- a/memclaw/setup/__init__.py +++ b/memclaw/setup/__init__.py @@ -5,15 +5,15 @@ - `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. +- `run_doctor` (doctor.py): `memclaw doctor`, the OpenAI model-access + check (the wizard shows the same report 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 .doctor import run_doctor from .wizard import needs_setup, print_logo, run_setup -__all__ = ["needs_setup", "print_logo", "print_probe_report", "run_setup"] +__all__ = ["needs_setup", "print_logo", "run_doctor", "run_setup"] diff --git a/memclaw/setup/doctor.py b/memclaw/setup/doctor.py index a8ca3a0..8942eb6 100644 --- a/memclaw/setup/doctor.py +++ b/memclaw/setup/doctor.py @@ -1,5 +1,5 @@ -"""OpenAI model access: the check the wizard runs after saving, and the -report `memclaw doctor` prints.""" +"""OpenAI model access: the check the wizard runs after saving, and +`memclaw doctor`.""" from __future__ import annotations @@ -25,6 +25,15 @@ def check_openai(api_key: str | None, console: Console) -> None: console.print(f"[yellow]Skipping model check:[/yellow] {exc}") +def run_doctor(api_key: str, console: Console) -> bool: + """`memclaw doctor`: try every model Memclaw uses with *api_key* and + print the report. Returns True if all of them work.""" + with console.status("[cyan]Probing OpenAI...[/cyan]"): + report = asyncio.run(probe_openai(api_key)) + print_probe_report(report, console) + return report.all_ok + + def print_probe_report(report: ProbeReport, console: Console) -> None: """Render a probe report (memclaw.openai_client.probe_openai) as a panel.""" body = Text() diff --git a/memclaw/setup/wizard.py b/memclaw/setup/wizard.py index 4384394..1e25fdd 100644 --- a/memclaw/setup/wizard.py +++ b/memclaw/setup/wizard.py @@ -65,13 +65,10 @@ def print_logo() -> None: console.print() -# Supported front-end platforms (name, label) in display order: the chat -# apps of memclaw.bot, then the terminal. The first one is also the default -# when nothing has been configured yet. -PLATFORMS: list[tuple[str, str]] = [ - *((p.name, p.label) for p in CHAT_PLATFORMS.values()), - ("terminal", "Terminal chat"), -] +# Supported front-end platforms (name, label) in display order, from +# memclaw.bot's registry. The first one is also the default when nothing has +# been configured yet. +PLATFORMS: list[tuple[str, str]] = [(p.name, p.label) for p in CHAT_PLATFORMS.values()] def questions(platform: str | None = None) -> list[Setting]: diff --git a/pyproject.toml b/pyproject.toml index ef6fd54..4b8a677 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -90,7 +90,8 @@ select = ["E4", "E7", "E9", "F"] # hooks. Known violations are listed in .code-shape/baseline.json: only new or # worse ones fail. Never edit the baseline by hand; fix the code, then run # `code-shape tighten`. The kit's default limits apply (see its -# templates/shape.toml); don't raise one to make a change pass. +# templates/shape.toml) unless [tool.shape.limits] below sets a stricter +# one; don't raise one to make a change pass. # --------------------------------------------------------------------------- [tool.shape] packages = ["memclaw"] @@ -102,6 +103,11 @@ tests = "tests" config_modules = ["memclaw/config.py", "memclaw/defaults/cursor_hooks/*"] baseline = ".code-shape/baseline.json" +[tool.shape.limits] +# Lower than the kit's 12: no module imports more than 8 memclaw modules +# (the agent and the Cursor backend are at 8, cli at 5), so hold it there. +fan_out = 8 + [tool.shape.banned_api] # Outside systems should be reached through one module each. Existing direct # uses are in the baseline; new ones fail. @@ -171,7 +177,8 @@ layers = [ # 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. + # Where Memclaw chats (memclaw.bot): one module per chat app and one for + # the terminal, plus what they share. "bot", # Platform-agnostic assistant: wires backends, tools and storage together. "agent", @@ -209,12 +216,13 @@ ancestors = ["memclaw.*"] [[tool.importlinter.contracts]] id = "chat-platforms-independent" -name = "Chat platforms are independent: the Telegram, Slack and WhatsApp modules never import each other (share code via memclaw.bot.inbound or lower layers)" +name = "Chat platforms are independent: the Telegram, Slack, WhatsApp and terminal modules never import each other (share code via memclaw.bot.inbound or lower layers)" type = "independence" modules = [ "memclaw.bot.telegram", "memclaw.bot.slack", "memclaw.bot.whatsapp", + "memclaw.bot.terminal", ] [[tool.importlinter.contracts]] @@ -225,6 +233,7 @@ protected_modules = [ "memclaw.bot.telegram", "memclaw.bot.slack", "memclaw.bot.whatsapp", + "memclaw.bot.terminal", ] allowed_importers = ["memclaw.bot"] @@ -244,7 +253,7 @@ 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, MemoryIndex, HybridSearch, Consolidator, ...)" +name = "Only memclaw.memory imports its own modules: everyone else uses what memclaw.memory exports (MemoryStore, MemoryIndex, HybridSearch, Consolidator, MemoryVault, ...)" type = "protected" protected_modules = [ "memclaw.memory.chunking", @@ -253,6 +262,7 @@ protected_modules = [ "memclaw.memory.notes", "memclaw.memory.refs", "memclaw.memory.search", + "memclaw.memory.vault", ] allowed_importers = ["memclaw.memory"] @@ -262,6 +272,8 @@ name = "Inside memclaw.memory: consolidation and search build on the notes and t type = "layers" containers = ["memclaw.memory"] layers = [ + # The notes and the index opened together for the one-off commands. + "vault", # MEMORY.md consolidation; ranking search results. Independent. "consolidation | search", # The Markdown notes; the SQLite index of them (the only SQLite user @@ -275,7 +287,7 @@ 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)" +name = "Only memclaw.setup imports its own modules: everyone else uses what memclaw.setup exports (run_setup, needs_setup, print_logo, run_doctor)" type = "protected" protected_modules = ["memclaw.setup.doctor", "memclaw.setup.wizard"] allowed_importers = ["memclaw.setup"] diff --git a/tests/backends/test_claude.py b/tests/backends/test_claude.py index 945c9fc..bc033b4 100644 --- a/tests/backends/test_claude.py +++ b/tests/backends/test_claude.py @@ -8,8 +8,9 @@ import pytest from memclaw.backends import claude as claude_backend +from memclaw.backends.base import TurnRequest from memclaw.backends.claude import ClaudeAgentBackend -from memclaw.backends.claude_models import ModelInfo +from memclaw.backends.model_selection import ModelInfo from memclaw.config import ClaudeSettings @@ -235,9 +236,11 @@ def __call__(self, options=None, *args, **kwargs): async def _turn(backend, executor, *, key="telegram:1", resume=None, context="now", message="hello", **kwargs): return await backend.run_turn( - system_prompt="sys", context=context, user_message=message, - tool_executor=executor, session_key=key, resume_session_id=resume, - **kwargs, + TurnRequest( + system_prompt="sys", context=context, user_message=message, + session_key=key, resume_session_id=resume, **kwargs, + ), + executor, ) diff --git a/tests/backends/test_cursor.py b/tests/backends/test_cursor.py index 74729d8..69644c4 100644 --- a/tests/backends/test_cursor.py +++ b/tests/backends/test_cursor.py @@ -18,7 +18,7 @@ SDKModel, ) -from memclaw.backends.base import TurnResult +from memclaw.backends.base import TurnRequest, TurnResult from memclaw.backends import REGISTRY, get_backend_class from memclaw.backends.cursor import ( CursorAgentBackend, @@ -367,8 +367,11 @@ def _patched(backend, *clients): async def _turn(backend, text="User", *, key="cli", resume=None, context="ctx"): return await backend.run_turn( - system_prompt="System", context=context, user_message=text, - tool_executor=MagicMock(), session_key=key, resume_session_id=resume, + TurnRequest( + system_prompt="System", context=context, user_message=text, + session_key=key, resume_session_id=resume, + ), + MagicMock(), ) diff --git a/tests/bot/test_telegram.py b/tests/bot/test_telegram.py index 0ef1d07..150fa87 100644 --- a/tests/bot/test_telegram.py +++ b/tests/bot/test_telegram.py @@ -90,7 +90,7 @@ class _SelectableBackend: supports_model_selection = True def __init__(self): - from memclaw.backends.claude_models import ModelInfo + from memclaw.backends.model_selection import ModelInfo self.models = [ ModelInfo("claude-opus-5", "Claude Opus 5", "", ["low", "medium", "high"]), diff --git a/tests/bot/test_terminal.py b/tests/bot/test_terminal.py new file mode 100644 index 0000000..6ad68ea --- /dev/null +++ b/tests/bot/test_terminal.py @@ -0,0 +1,102 @@ +"""The terminal chat: typed lines go to the agent, its replies are printed, +`/new` resets, `/quit` (or Ctrl-D) ends it.""" +from __future__ import annotations + +from unittest.mock import AsyncMock, MagicMock + +import pytest +from rich.console import Console + +from memclaw.bot import DEFAULT_PLATFORM, PLATFORMS, chosen_platform, status_rows +from memclaw.bot import terminal + + +@pytest.fixture +def screen(monkeypatch): + """The terminal's console, recording what is printed.""" + console = Console(record=True, width=80, color_system=None) + monkeypatch.setattr(terminal, "console", console) + return console + + +def _typed(monkeypatch, screen: Console, *lines: str) -> None: + """Make the prompt return *lines* in turn, then Ctrl-D.""" + queue = list(lines) + + def _input(_prompt): + if not queue: + raise EOFError + return queue.pop(0) + + monkeypatch.setattr(screen, "input", _input) + + +def _agent(reply: str = "Noted.") -> MagicMock: + agent = MagicMock() + agent.handle = AsyncMock(return_value=(reply, [])) + agent.reset_conversation = AsyncMock() + return agent + + +@pytest.mark.asyncio +async def test_a_message_goes_to_the_agent_and_its_reply_is_printed(monkeypatch, screen): + _typed(monkeypatch, screen, " remember the milk ", "", "/quit", "never read") + agent = _agent("**Saved** the milk.") + + await terminal.chat(agent) + + agent.handle.assert_awaited_once_with("remember the milk") + assert "Saved the milk." in screen.export_text() + + +@pytest.mark.asyncio +async def test_new_starts_a_fresh_conversation(monkeypatch, screen): + _typed(monkeypatch, screen, "/NEW") + agent = _agent() + + await terminal.chat(agent) + + agent.reset_conversation.assert_awaited_once_with() + agent.handle.assert_not_awaited() + assert "Started a new conversation." in screen.export_text() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("word", ["/quit", "/exit", "quit", "EXIT"]) +async def test_quit_words_end_the_chat(monkeypatch, screen, word): + _typed(monkeypatch, screen, word, "not sent") + agent = _agent() + + await terminal.chat(agent) + + agent.handle.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_a_failed_turn_is_shown_and_the_chat_goes_on(monkeypatch, screen): + _typed(monkeypatch, screen, "first", "second") + agent = _agent() + agent.handle.side_effect = [RuntimeError("backend down"), ("ok", [])] + + await terminal.chat(agent) + + assert agent.handle.await_count == 2 + assert "Error: backend down" in screen.export_text() + + +def test_the_terminal_is_a_registered_platform(): + assert PLATFORMS["terminal"].label == "Terminal chat" + assert DEFAULT_PLATFORM == "terminal" + + +@pytest.mark.parametrize("configured, started", [ + ("", "terminal"), ("terminal", "terminal"), ("slack", "slack"), ("nonsense", "terminal"), +]) +def test_chosen_platform_falls_back_to_the_terminal(configured, started): + config = MagicMock(platform=configured) + assert chosen_platform(config).name == started + + +def test_status_shows_the_terminal_when_no_platform_is_set(): + assert status_rows(MagicMock(platform="")) == [("Platform", "terminal")] + assert status_rows(MagicMock(platform="slack")) == [("Platform", "slack")] diff --git a/tests/e2e/test_agent_e2e.py b/tests/e2e/test_agent_e2e.py index eebe36c..d3e4bd4 100644 --- a/tests/e2e/test_agent_e2e.py +++ b/tests/e2e/test_agent_e2e.py @@ -76,7 +76,7 @@ async def test_conversation_resumes_after_restart(agent_vault): "to memory, just keep it in this conversation. Reply 'ok'.", chat_id="7", ) - first = agent.sessions.get("e2e:7", agent._fingerprint) + first = agent.sessions.saved("e2e:7") finally: await agent.aclose() assert first is not None @@ -85,7 +85,7 @@ async def test_conversation_resumes_after_restart(agent_vault): try: reply, _ = await agent.handle("What was the secret word?", chat_id="7") assert "tangerine" in reply.lower() - assert agent.sessions.get("e2e:7", agent._fingerprint)["session_id"] == first["session_id"] + assert agent.sessions.saved("e2e:7")["session_id"] == first["session_id"] finally: await agent.aclose() diff --git a/tests/memory/test_vault.py b/tests/memory/test_vault.py new file mode 100644 index 0000000..e9d30b0 --- /dev/null +++ b/tests/memory/test_vault.py @@ -0,0 +1,101 @@ +"""Tests for MemoryVault — the notes and the index opened together for the +one-off `memclaw` commands (save, search, index, consolidate, status).""" +from __future__ import annotations + +from datetime import date, timedelta +from unittest.mock import AsyncMock, patch + +import pytest + +from memclaw.config import MemclawConfig +from memclaw.memory import MemoryVault + + +class _OneShot: + def __init__(self, reply: str): + self.reply = reply + self.calls = 0 + + async def run_one_shot(self, *, system_prompt: str, user_message: str) -> str: + self.calls += 1 + return self.reply + + +@pytest.mark.asyncio +async def test_save_writes_the_daily_note_and_indexes_it(tmp_config: MemclawConfig): + with MemoryVault(tmp_config) as vault: + path = await vault.save("Alex's birthday is March 3") + + assert path == tmp_config.daily_file() + assert "Alex's birthday is March 3" in path.read_text() + assert vault.index.get_stats()["files"] == 1 + + +@pytest.mark.asyncio +async def test_search_finds_a_saved_note(tmp_config: MemclawConfig): + with MemoryVault(tmp_config) as vault: + await vault.save("The spare key is under the blue flowerpot") + results = await vault.search("spare key flowerpot", limit=3) + + assert results + assert "blue flowerpot" in results[0].content + + +@pytest.mark.asyncio +async def test_reindex_reports_whether_anything_changed(tmp_config: MemclawConfig): + with MemoryVault(tmp_config) as vault: + vault.store.save("A note") + changed, stats = await vault.reindex() + assert changed is True + assert stats["files"] >= 1 and stats["chunks"] >= 1 + + changed, again = await vault.reindex() + assert changed is False + assert again == stats + + +@pytest.mark.asyncio +async def test_sync_or_warn_swallows_a_failing_sync(tmp_config: MemclawConfig): + with MemoryVault(tmp_config) as vault: + with patch.object(vault.index, "sync", AsyncMock(side_effect=RuntimeError("offline"))): + await vault.sync_or_warn() + + +@pytest.mark.asyncio +async def test_consolidate_writes_memory_md_with_the_backend_given(tmp_config: MemclawConfig): + backend = _OneShot("## Key Facts\n- Alex's birthday is March 3") + yesterday = date.today() - timedelta(days=1) + with MemoryVault(tmp_config) as vault: + # Today's note is still being written; consolidation takes the days before. + tmp_config.daily_file(yesterday).write_text("# Yesterday\n\nAlex's birthday is March 3\n") + + assert await vault.consolidate(backend) is True + + assert backend.calls == 1 + assert "Alex's birthday is March 3" in tmp_config.memory_file.read_text() + + +@pytest.mark.asyncio +async def test_consolidate_with_no_daily_notes_does_nothing(tmp_config: MemclawConfig): + backend = _OneShot("unused") + with MemoryVault(tmp_config) as vault: + assert await vault.consolidate(backend) is False + assert backend.calls == 0 + + +def test_status_rows(tmp_config: MemclawConfig): + with MemoryVault(tmp_config) as vault: + vault.store.save("A note") + store_rows = dict(vault.store.status_rows()) + index_rows = dict(vault.index.status_rows()) + + assert store_rows["Memory directory"] == tmp_config.memory_dir + assert store_rows["Memory files"] == 2 # MEMORY.md and today's note + assert index_rows == {"Indexed chunks": 0, "Stored images": 0, "Database": tmp_config.db_path} + + +def test_closing_the_vault_closes_the_index(tmp_config: MemclawConfig): + with MemoryVault(tmp_config) as vault: + pass + with pytest.raises(Exception, match="closed"): + vault.index.get_stats() diff --git a/tests/setup/test_doctor.py b/tests/setup/test_doctor.py index ff0814a..8b001cd 100644 --- a/tests/setup/test_doctor.py +++ b/tests/setup/test_doctor.py @@ -6,7 +6,8 @@ from rich.console import Console from memclaw.openai_client import ProbeOutcome, ProbeReport -from memclaw.setup import doctor, print_probe_report +from memclaw.setup import doctor +from memclaw.setup.doctor import print_probe_report def _report(chat_ok: bool) -> ProbeReport: @@ -55,3 +56,16 @@ async def _fail(_key): with patch.object(doctor, "probe_openai", _fail): doctor.check_openai("sk-1", console) assert "Skipping model check: offline" in console.export_text() + + +class TestRunDoctor: + def test_prints_the_report_and_says_whether_all_models_work(self): + for chat_ok in (True, False): + console = _console() + + async def _probe(_key, chat_ok=chat_ok): + return _report(chat_ok) + + with patch.object(doctor, "probe_openai", _probe): + assert doctor.run_doctor("sk-1", console) is chat_ok + assert "OpenAI model access" in console.export_text() diff --git a/tests/test_agent.py b/tests/test_agent.py index 2763ac8..55b69ec 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -19,7 +19,7 @@ import pytest -from memclaw.backends.base import TurnResult +from memclaw.backends.base import TurnRequest, TurnResult from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings from memclaw.memory import SearchResult @@ -67,8 +67,8 @@ async def run_one_shot(self, *, system_prompt: str, user_message: str) -> str: self.one_shot_calls.append({"system": system_prompt, "user": user_message}) return self.one_shot_response - async def run_turn(self, **kwargs) -> TurnResult: - self.turn_calls.append(kwargs) + async def run_turn(self, request: TurnRequest, tool_executor) -> TurnResult: + self.turn_calls.append({**vars(request), "tool_executor": tool_executor}) if self.turn_error is not None: raise self.turn_error result = TurnResult(**vars(self.turn_response)) @@ -289,7 +289,7 @@ async def test_own_writes_during_a_turn_are_not_sent_back( cfg.memory_file.write_text("## Key Facts\n- Old fact") agent = _chat_agent(cfg, fake_backend) - async def turn_that_saves(**kwargs): + async def turn_that_saves(request, tool_executor): # update_instructions mid-turn. cfg.agent_file.write_text("Be terse.") return TurnResult(text="saved", session_id="sess-1") @@ -310,7 +310,7 @@ async def test_consolidation_during_a_turn_is_still_sent( cfg.memory_file.write_text("## Key Facts\n- Old fact") agent = _chat_agent(cfg, fake_backend) - async def turn_racing_consolidation(**kwargs): + async def turn_racing_consolidation(request, tool_executor): cfg.memory_file.write_text("## Key Facts\n- Consolidated") return TurnResult(text="ok", session_id="sess-1") @@ -616,10 +616,10 @@ async def test_tool_calls_see_their_own_chat(self, cfg: MemclawConfig, fake_back seen: dict[str, str | None] = {} agent = _chat_agent(cfg, fake_backend, platform="slack") - async def run_turn(**kwargs): - key = kwargs["session_key"] + async def run_turn(request, tool_executor): + key = request.session_key await asyncio.sleep(0.05) # the other chat's message arrives meanwhile - seen[key] = kwargs["tool_executor"].chat_id + seen[key] = tool_executor.chat_id return TurnResult(text="ok", session_id=f"s-{key}") fake_backend.run_turn = run_turn diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..abec2be --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,173 @@ +"""Tests for the `memclaw` command: each command reaches the code that does +it, and stops with a clear message when a setting it needs is missing.""" +from __future__ import annotations + +from datetime import date, timedelta +from pathlib import Path + +import pytest +from click.testing import CliRunner + +from memclaw import backends +from memclaw.bot import Platform +from memclaw.cli import cli + + +@pytest.fixture(autouse=True) +def _isolate_env(monkeypatch, isolate_claude_env): + """Keep the developer's own settings out of the commands.""" + for name in ("AGENT_BACKEND", "CURSOR_MODEL", "CURSOR_API_KEY", "MEMCLAW_PLATFORM"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("OPENAI_API_KEY", "test-openai-key") + + +def _run(tmp_path: Path, *args: str, exit_code: int = 0) -> str: + result = CliRunner().invoke(cli, ["--memory-dir", str(tmp_path / "m"), *args], obj={}) + assert result.exit_code == exit_code, result.output + return result.output + + +class _OneShotBackend: + """A registered backend that only answers consolidation's one-shot call.""" + + name = "fake" + + def __init__(self, config): + pass + + @classmethod + def is_configured(cls, config): + return True + + async def run_one_shot(self, *, system_prompt: str, user_message: str) -> str: + return "## Key Facts\n- Consolidated" + + +@pytest.fixture +def fake_backend(monkeypatch): + monkeypatch.setitem(backends.REGISTRY, "fake", _OneShotBackend) + monkeypatch.setenv("AGENT_BACKEND", "fake") + + +# ── status ────────────────────────────────────────────────────────── + + +def test_claude_backend_shows_its_model_and_effort(tmp_path: Path, monkeypatch): + monkeypatch.setenv("CLAUDE_MODEL", "claude-opus-5") + monkeypatch.setenv("CLAUDE_EFFORT", "high") + + output = _run(tmp_path, "status") + + assert "Model : claude-opus-5" in output + assert "Effort : high" in output + + +def test_cursor_backend_shows_only_its_own_model(tmp_path: Path, monkeypatch): + monkeypatch.setenv("AGENT_BACKEND", "cursor") + monkeypatch.setenv("CURSOR_MODEL", "composer-3") + monkeypatch.delenv("CURSOR_EFFORT", raising=False) + monkeypatch.setenv("CLAUDE_MODEL", "claude-opus-5") + monkeypatch.setenv("CLAUDE_EFFORT", "high") + + output = _run(tmp_path, "status") + + assert "Model : composer-3" in output + assert "Effort : default" in output + assert "claude-opus-5" not in output + + +def test_general_rows_are_still_shown(tmp_path: Path): + output = _run(tmp_path, "status") + + labels = ["Memory directory", "Memory files", "Platform", "Model", + "Indexed chunks", "Stored images", "Database"] + positions = [output.index(label) for label in labels] + assert positions == sorted(positions) + assert "Platform : terminal" in output + + +# ── save, search, index ───────────────────────────────────────────── + + +def test_save_then_search_then_index(tmp_path: Path): + assert "Memory saved to" in _run(tmp_path, "save", "The spare key is under the blue flowerpot") + + output = _run(tmp_path, "search", "spare key flowerpot", "--limit", "1") + assert "[1]" in output and "blue flowerpot" in output + + assert "Index updated" in _run(tmp_path, "index") # AGENTS.md, MEMORY.md + output = _run(tmp_path, "index") + assert "Index already up to date" in output + assert "Chunks: 2 Files: 2" in output + + +def test_search_with_nothing_saved(tmp_path: Path): + assert "No matching memories found." in _run(tmp_path, "search", "anything") + + +@pytest.mark.parametrize("args", [["save", "a note"], ["search", "a query"], ["index"]]) +def test_commands_that_embed_need_the_openai_key(tmp_path: Path, monkeypatch, args): + monkeypatch.setenv("OPENAI_API_KEY", "") + + output = _run(tmp_path, *args, exit_code=1) + + assert "Error: OPENAI_API_KEY is not set." in output + assert "Run memclaw configure to set it." in output + assert not list((tmp_path / "m" / "memory").glob("*.md")) + + +# ── consolidate ───────────────────────────────────────────────────── + + +def test_consolidate_runs_with_the_chosen_backend(tmp_path: Path, fake_backend): + memory = tmp_path / "m" + (memory / "memory").mkdir(parents=True) + yesterday = date.today() - timedelta(days=1) + (memory / "memory" / f"{yesterday.isoformat()}.md").write_text("# Yesterday\n\nA fact\n") + + output = _run(tmp_path, "consolidate") + + assert "Consolidation complete." in output + assert "- Consolidated" in (memory / "MEMORY.md").read_text() + + +def test_consolidate_with_nothing_to_do(tmp_path: Path, fake_backend): + assert "No daily files to consolidate." in _run(tmp_path, "consolidate") + + +def test_consolidate_rejects_a_bad_date(tmp_path: Path, fake_backend): + output = _run(tmp_path, "consolidate", "--since", "yesterday", exit_code=1) + assert "Invalid date format: yesterday. Use YYYY-MM-DD." in output + + +def test_an_unknown_backend_is_named(tmp_path: Path, monkeypatch): + monkeypatch.setenv("AGENT_BACKEND", "nope") + + output = _run(tmp_path, "consolidate", exit_code=1) + + assert "Error: unknown agent backend nope (set via AGENT_BACKEND)." in output + assert "Available: claude, cursor." in " ".join(output.split()) + + +def test_a_backend_without_credentials_says_what_to_set(tmp_path: Path): + output = _run(tmp_path, "consolidate", exit_code=1) + + assert "Error: no Claude credential is configured." in output + assert "Run memclaw configure to set it." in output + + +# ── bare `memclaw` ────────────────────────────────────────────────── + + +@pytest.mark.parametrize("configured, started", [("", "terminal"), ("slack", "slack")]) +def test_bare_memclaw_starts_the_chosen_platform( + tmp_path: Path, monkeypatch, fake_backend, configured, started, +): + monkeypatch.setenv("MEMCLAW_PLATFORM", configured) + monkeypatch.setattr("memclaw.cli.needs_setup", lambda: False) + ran: list[str] = [] + monkeypatch.setattr(Platform, "run", lambda self, config: ran.append(self.name)) + + _run(tmp_path) + + assert ran == [started] diff --git a/tests/test_cli_status.py b/tests/test_cli_status.py deleted file mode 100644 index 5936ab4..0000000 --- a/tests/test_cli_status.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Tests for `memclaw status`.""" -from __future__ import annotations - -from pathlib import Path - -import pytest -from click.testing import CliRunner - -from memclaw.cli import cli - - -@pytest.fixture(autouse=True) -def _isolate_env(monkeypatch, isolate_claude_env): - """Keep the developer's own backend settings out of the status output.""" - for name in ("AGENT_BACKEND", "CURSOR_MODEL", "MEMCLAW_PLATFORM"): - monkeypatch.delenv(name, raising=False) - - -def _status(tmp_path: Path) -> str: - result = CliRunner().invoke( - cli, ["--memory-dir", str(tmp_path / "m"), "status"], obj={}, - ) - assert result.exit_code == 0, result.output - return result.output - - -def test_claude_backend_shows_its_model_and_effort(tmp_path: Path, monkeypatch): - monkeypatch.setenv("CLAUDE_MODEL", "claude-opus-5") - monkeypatch.setenv("CLAUDE_EFFORT", "high") - - output = _status(tmp_path) - - assert "Model : claude-opus-5" in output - assert "Effort : high" in output - - -def test_cursor_backend_shows_only_its_own_model(tmp_path: Path, monkeypatch): - monkeypatch.setenv("AGENT_BACKEND", "cursor") - monkeypatch.setenv("CURSOR_MODEL", "composer-3") - monkeypatch.delenv("CURSOR_EFFORT", raising=False) - monkeypatch.setenv("CLAUDE_MODEL", "claude-opus-5") - monkeypatch.setenv("CLAUDE_EFFORT", "high") - - output = _status(tmp_path) - - assert "Model : composer-3" in output - assert "Effort : default" in output - assert "claude-opus-5" not in output - - -def test_general_rows_are_still_shown(tmp_path: Path): - output = _status(tmp_path) - - for label in ("Memory directory", "Memory files", "Platform", - "Indexed chunks", "Stored images", "Database"): - assert label in output diff --git a/tests/test_sessions.py b/tests/test_sessions.py new file mode 100644 index 0000000..0566c66 --- /dev/null +++ b/tests/test_sessions.py @@ -0,0 +1,87 @@ +"""Tests for ChatSessions — each chat's session, queued reminders and /new +(the agent's turn-level behaviour is in test_agent.py).""" +from __future__ import annotations + +import json +from pathlib import Path + +from memclaw.sessions import ChatSessions + + +def _chats(tmp_path: Path, *, platform: str | None = "telegram", fingerprint: str = "fp1") -> ChatSessions: + return ChatSessions(tmp_path / "sessions.json", fingerprint, platform) + + +def _saved(tmp_path: Path) -> dict: + return json.loads((tmp_path / "sessions.json").read_text()) + + +def test_session_keys(): + chats = ChatSessions(Path("unused.json"), "fp", "slack") + assert chats.key("C1") == "slack:C1" + assert chats.key(None) == "cli" + assert ChatSessions(Path("unused.json"), "fp").key("42") == "42" + + +def test_a_finished_turn_is_saved_and_resumed(tmp_path: Path): + chats = _chats(tmp_path) + turn = chats.begin("42") + assert turn.entry is None and turn.resume_session_id is None + + chats.finish(turn, "sess-1", agents_hash="a1", memory_hash="m1") + + assert _saved(tmp_path) == {"telegram:42": { + "session_id": "sess-1", "fingerprint": "fp1", "agents_hash": "a1", "memory_hash": "m1", + }} + again = _chats(tmp_path).begin("42") + assert again.resume_session_id == "sess-1" + assert again.saw_other("agents_hash", "a2") and not again.saw_other("memory_hash", "m1") + + +def test_a_session_from_other_instructions_is_not_resumed(tmp_path: Path): + chats = _chats(tmp_path) + chats.finish(chats.begin("42"), "sess-1", agents_hash="a", memory_hash="m") + + assert _chats(tmp_path, fingerprint="fp2").begin("42").entry is None + + +def test_a_turn_without_a_session_id_saves_nothing(tmp_path: Path): + chats = _chats(tmp_path) + chats.finish(chats.begin("42"), None, agents_hash="a", memory_hash="m") + assert not (tmp_path / "sessions.json").exists() + + +def test_only_the_notes_a_turn_carried_are_dropped(tmp_path: Path): + chats = _chats(tmp_path) + chats.add_note("42", "first") + turn = chats.begin("42") + chats.add_note("42", "during the turn") + chats.add_note("7", "other chat") + + chats.finish(turn, "s", agents_hash="a", memory_hash="m") + + assert turn.notes == ["first"] + assert chats.begin("42").notes == ["during the turn"] + assert chats.begin("7").notes == ["other chat"] + + +def test_new_forgets_the_session_and_notes(tmp_path: Path): + chats = _chats(tmp_path) + chats.finish(chats.begin("42"), "sess-1", agents_hash="a", memory_hash="m") + chats.add_note("42", "a reminder") + + assert chats.reset("42") == "telegram:42" + + turn = chats.begin("42") + assert turn.entry is None and turn.notes == [] + assert _saved(tmp_path) == {} + + +def test_a_turn_overtaken_by_new_does_not_save_its_session(tmp_path: Path): + chats = _chats(tmp_path) + turn = chats.begin("42") + chats.reset("42") + + chats.finish(turn, "old-session", agents_hash="a", memory_hash="m") + + assert chats.begin("42").entry is None