Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 4 additions & 10 deletions .code-shape/baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
},
Expand Down
10 changes: 5 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand All @@ -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.

Expand Down
6 changes: 4 additions & 2 deletions docs/memory-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**
Expand Down Expand Up @@ -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).

Expand Down Expand Up @@ -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 |
|---|---|
Expand All @@ -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`) |

---

Expand Down
2 changes: 2 additions & 0 deletions docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
95 changes: 31 additions & 64 deletions memclaw/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -33,17 +33,14 @@
)
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
# stays in the session transcript.
_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.
Expand All @@ -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,
Expand All @@ -79,39 +74,29 @@ 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.
self._turn_lock = asyncio.Lock()

# ── 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)

Expand Down Expand Up @@ -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))

Expand All @@ -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()

Expand All @@ -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():
Expand Down
Loading
Loading