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
26 changes: 1 addition & 25 deletions .code-shape/baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
"cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 39,
"cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend.run_one_shot": 23,
"cognitive-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 24,
"cognitive-complexity|memclaw/bot/whatsapp_handlers.py|WhatsAppBot._send_response": 16,
"cognitive-complexity|memclaw/index.py|MemoryIndex.chunk_text": 27,
"cognitive-complexity|memclaw/prompts.py|masked_input": 16,
"cognitive-complexity|memclaw/search.py|HybridSearch._merge": 17
Expand All @@ -14,63 +13,40 @@
"type-errors|memclaw/agent.py|": 1,
"type-errors|memclaw/backends/claude.py|": 1,
"type-errors|memclaw/backends/mcp_bridge.py|": 1,
"type-errors|memclaw/bot/handlers.py|": 30,
"type-errors|memclaw/bot/whatsapp_handlers.py|": 3,
"type-errors|memclaw/cli.py|": 2,
"type-errors|memclaw/setup.py|": 5
},
"pylint": {
"class-attributes|memclaw/agent.py|MemclawAgent": 18,
"class-attributes|memclaw/backends/cursor.py|CursorAgentBackend": 13,
"duplicate-code|memclaw/bot/handlers.py|same code as memclaw/bot/slack_handlers.py": 15,
"duplicate-code|memclaw/bot/slack_handlers.py|same code as memclaw/bot/whatsapp_handlers.py": 16,
"too-many-locals|memclaw/agent.py|MemclawAgent._handle": 19,
"too-many-locals|memclaw/backends/claude.py|ClaudeAgentBackend.wizard_setup": 17,
"too-many-locals|memclaw/backends/cursor.py|CursorAgentBackend.run_turn": 20,
"too-many-locals|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 19,
"too-many-locals|memclaw/bot/slack_handlers.py|SlackHandlers._handle_audio": 21,
"too-many-locals|memclaw/bot/slack_handlers.py|SlackHandlers._handle_image": 21,
"too-many-locals|memclaw/bot/whatsapp_handlers.py|WhatsAppBot._handle_audio": 17,
"too-many-locals|memclaw/bot/whatsapp_handlers.py|WhatsAppBot._handle_image": 19,
"too-many-locals|memclaw/index.py|MemoryIndex.chunk_text": 17,
"too-many-locals|memclaw/search.py|HybridSearch._merge": 22
},
"ruff": {
"banned-api|memclaw/bot/handlers.py|openai in <module>": 1,
"banned-api|memclaw/bot/link_processor.py|openai in <module>": 1,
"banned-api|memclaw/bot/slack_handlers.py|openai in <module>": 1,
"banned-api|memclaw/bot/whatsapp_handlers.py|openai in <module>": 1,
"banned-api|memclaw/cli.py|openai in _run_slack": 1,
"banned-api|memclaw/cli.py|openai in _run_whatsapp": 1,
"banned-api|memclaw/openai_health.py|openai in <module>": 1,
"banned-api|memclaw/search.py|sqlite3 in <module>": 1,
"function-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13,
"function-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 11,
"function-complexity|memclaw/bot/handlers.py|build_application": 15,
"function-complexity|memclaw/index.py|MemoryIndex.chunk_text": 12,
"private-access|memclaw/cli.py|_maybe_consolidate in consolidate._run": 1,
"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/bot/slack_handlers.py|SlackHandlers._handle_audio": 7,
"too-many-args|memclaw/bot/slack_handlers.py|SlackHandlers._handle_image": 7,
"too-many-args|memclaw/tools.py|ToolExecutor.__init__": 7,
"too-many-branches|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13,
"too-many-positional|memclaw/bot/slack_handlers.py|SlackHandlers._handle_audio": 7,
"too-many-positional|memclaw/bot/slack_handlers.py|SlackHandlers._handle_image": 7,
"too-many-positional|memclaw/tools.py|ToolExecutor.__init__": 7
},
"sizes": {
"class-lines|memclaw/agent.py|MemclawAgent": 482,
"class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 501,
"class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419,
"class-lines|memclaw/bot/handlers.py|MessageHandlers": 309,
"class-lines|memclaw/bot/slack_handlers.py|SlackHandlers": 306,
"class-lines|memclaw/index.py|MemoryIndex": 422,
"class-lines|memclaw/index.py|MemoryIndex": 419,
"file-lines|memclaw/agent.py|": 699,
"file-lines|memclaw/backends/claude.py|": 775,
"file-lines|memclaw/backends/cursor.py|": 604,
"file-lines|memclaw/bot/handlers.py|": 570,
"file-lines|memclaw/tools.py|": 577,
"package-files|memclaw/|": 13
}
Expand Down
7 changes: 4 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,11 @@ Claude Code uses `.claude/settings.json` automatically: when Claude runs `git co

**memclaw's layout rules** are the import-linter contracts under `[tool.importlinter]` in `pyproject.toml`. `code-shape check` runs them (on their own: `lint-imports`):

- **Layers**: `cli` → `bot` / `setup` → `agent` → `backends` → `tools` → core modules (`search`, `store`, `reminders`, …) → `index` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer.
- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → core modules (`search`, `store`, `reminders`, …) → `index` → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer.
- **No cycles inside subpackages** such as `memclaw.backends` and `memclaw.bot`.
- **Chat platforms are independent**: the Telegram (`bot/handlers.py`), Slack and WhatsApp handlers never import each other. Put shared code in `memclaw/bot/` or a lower layer.
- **Chat SDKs stay in `memclaw.bot`**: only `memclaw.bot` imports `telegram`, `slack_bolt` or `neonize`.
- **Chat platforms are independent**: `bot/telegram.py`, `bot/slack.py` and `bot/whatsapp.py` never import each other. What they share (voice to text, link summaries, the prompts, the agent call, reminders) is in `bot/inbound.py`. A new platform is one module with a `run(config)` plus one line in `PLATFORMS` (`bot/__init__.py`); the CLI and the setup wizard start and list platforms only through that registry.
- **Chat SDKs stay in their platform module**: only those three modules import `telegram`, `slack_bolt` or `neonize`.
- **One OpenAI adapter**: only `openai_client.py` imports `openai`; everyone else calls `OpenAIClient`.
- **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
2 changes: 1 addition & 1 deletion docs/memory-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ Details — credentials, document numbers, instructions, receipts — stay in th

### How Memories Get Saved

The agent — not the handler, not a pre-processing step — decides what to save. When you send a text message, voice note, photo, or link, the raw content is passed to the agent with a note saying it hasn't been saved yet. The agent reads it and decides:
The agent — not the chat platform's code, not a pre-processing step — decides what to save. When you send a text message, voice note, photo, or link, the raw content is passed to the agent with a note saying it hasn't been saved yet (the same prompt on every platform: `memclaw/bot/inbound.py`). The agent reads it and decides:

- **Save it** if the content is useful (a fact, a note, a decision).
- **Rephrase it** if the verbatim text is messy but the information matters.
Expand Down
72 changes: 72 additions & 0 deletions memclaw/bot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,56 @@
"""The chat apps Memclaw runs on.

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 module has a `run(config)` that starts it. The bare `memclaw`
command and the setup wizard find the platforms in `PLATFORMS` below, so
adding one is a new module plus one line there. A platform module (and its
chat SDK) is only imported when that platform is started.
"""

from __future__ import annotations

import sys
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
from typing import TYPE_CHECKING

from loguru import logger
from rich.console import Console

if TYPE_CHECKING:
from ..config import MemclawConfig

console = Console()


@dataclass(frozen=True)
class Platform:
"""A chat app; its code is the module `memclaw/bot/<name>.py`."""

name: str
label: str # shown by the setup wizard

def run(self, config: MemclawConfig) -> None:
"""Start the bot and block until it stops."""
import_module(f"{__name__}.{self.name}").run(config)


# In the order the setup wizard lists them.
PLATFORMS: dict[str, Platform] = {
p.name: p
for p in (
Platform("telegram", "Telegram"),
Platform("whatsapp", "WhatsApp"),
Platform("slack", "Slack"),
)
}


def mask_user_id(user_id: str | int) -> str:
"""Mask the middle of a user identifier for log safety.

Expand All @@ -8,3 +61,22 @@ def mask_user_id(user_id: str | int) -> str:
if len(s) <= 5:
return "*" * len(s)
return f"{s[:3]}{'*' * (len(s) - 5)}{s[-2:]}"


def require_setting(value: str, env_var: str) -> None:
"""Exit with a hint unless *value* (the setting *env_var*) is set."""
if not value:
console.print(f"[red]Error:[/red] {env_var} is not set.")
console.print("Run [bold]memclaw configure[/bold] to set it.")
raise SystemExit(1)


def log_to(log_file: Path) -> None:
"""Log INFO to the terminal and DEBUG to *log_file* (rotated)."""
logger.remove()
logger.add(
sys.stderr,
level="INFO",
format="<green>{time:HH:mm:ss}</green> | <level>{level:<8}</level> | <level>{message}</level>",
)
logger.add(str(log_file), rotation="10 MB", retention="7 days", level="DEBUG")
58 changes: 58 additions & 0 deletions memclaw/bot/commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""What the /model and /effort chat commands say and do, apart from the
chat app's I/O (Telegram adds its buttons, in telegram.py)."""

from __future__ import annotations

from loguru import logger

from ..backends import AgentBackend

_APPLIES = "Applies from your next message; the conversation is kept."


def unsupported(backend: AgentBackend, what: str) -> str:
return f"{what} isn't supported for the {backend.display_name} backend yet."


async def load_models(backend: AgentBackend) -> list:
try:
return await backend.list_models()
except Exception as exc:
logger.warning("Could not fetch the model list: {exc}", exc=exc)
return []


def status_lines(backend: AgentBackend, models: list, levels: list[str] | None) -> list[str]:
info = next((m for m in models if m.id == backend.model), None)
model = f"{info.display_name} ({info.id})" if info else backend.model
if levels == []:
effort = "not supported by this model"
else:
effort = backend.effort or "model default"
return [f"Model: {model}", f"Effort: {effort}"]


async def select_model(backend: AgentBackend, model_id: str) -> str:
"""Switch to *model_id*. Returns a note for the user; raises ValueError
for an unknown model."""
if model_id == backend.model:
return f"Already using {model_id}."
note = await backend.set_model(model_id)
return " ".join(p for p in (f"Switched to {backend.model}.", note, _APPLIES) if p)


async def select_effort(backend: AgentBackend, level: str) -> str:
"""Set the effort level. Returns a note; raises ValueError if rejected."""
await backend.set_effort(level)
return f"Effort set to {backend.effort}. {_APPLIES}"


async def resolve_model_arg(backend: AgentBackend, arg: str) -> str:
"""`/model <number or id>` → model id. Raises ValueError."""
if not arg.isdigit():
return arg
models = await load_models(backend)
n = int(arg)
if not 1 <= n <= len(models):
raise ValueError(f"There's no model number {n}.")
return models[n - 1].id
Loading
Loading