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
19 changes: 4 additions & 15 deletions .code-shape/baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,23 @@
"complexipy": {
"cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 39,
"cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend.run_one_shot": 23,
"cognitive-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 24,
"cognitive-complexity|memclaw/index.py|MemoryIndex.chunk_text": 27,
"cognitive-complexity|memclaw/prompts.py|masked_input": 16,
"cognitive-complexity|memclaw/search.py|HybridSearch._merge": 17
"cognitive-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 24
},
"mypy": {
"type-errors|memclaw/backends/claude.py|": 1,
"type-errors|memclaw/backends/mcp_bridge.py|": 1,
"type-errors|memclaw/cli.py|": 2,
"type-errors|memclaw/setup.py|": 5
"type-errors|memclaw/backends/mcp_bridge.py|": 1
},
"pylint": {
"class-attributes|memclaw/agent.py|MemclawAgent": 17,
"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,
"too-many-locals|memclaw/index.py|MemoryIndex.chunk_text": 17,
"too-many-locals|memclaw/search.py|HybridSearch._merge": 22
"too-many-locals|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 19
},
"ruff": {
"banned-api|memclaw/search.py|sqlite3 in <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/index.py|MemoryIndex.chunk_text": 12,
"too-many-args|memclaw/backends/base.py|AgentBackend.run_turn": 10,
"too-many-args|memclaw/backends/claude.py|ClaudeAgentBackend.run_turn": 10,
"too-many-args|memclaw/backends/cursor.py|CursorAgentBackend.run_turn": 10,
Expand All @@ -40,11 +31,9 @@
"sizes": {
"class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 501,
"class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419,
"class-lines|memclaw/index.py|MemoryIndex": 419,
"file-lines|memclaw/backends/claude.py|": 775,
"file-lines|memclaw/backends/cursor.py|": 604,
"file-lines|memclaw/tools.py|": 577,
"package-files|memclaw/|": 13
"file-lines|memclaw/tools.py|": 575
}
},
"version": 1
Expand Down
5 changes: 3 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,13 @@ Claude Code uses `.claude/settings.json` automatically: when Claude runs `git co

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

- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → `memory` → core modules (`search`, `store`, `reminders`, …) → `index` → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer.
- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → `memory` → core modules (`reminders`, `sessions`, `terminal_input`, …) → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. (The terminal prompts, `terminal_input.py`, sit below `backends` rather than inside `setup/` because the backends ask their own setup questions.)
- **No cycles inside subpackages** such as `memclaw.backends` and `memclaw.bot`.
- **Chat platforms are independent**: `bot/telegram.py`, `bot/slack.py` and `bot/whatsapp.py` never import each other. What they share (voice to text, link summaries, the prompts, the agent call, reminders) is in `bot/inbound.py`. A new platform is one module with a `run(config)` plus one line in `PLATFORMS` (`bot/__init__.py`); the CLI and the setup wizard start and list platforms only through that registry.
- **Chat SDKs stay in their platform module**: only those three modules import `telegram`, `slack_bolt` or `neonize`.
- **One OpenAI adapter**: only `openai_client.py` imports `openai`; everyone else calls `OpenAIClient`.
- **Memory through its package**: other code uses what `memclaw.memory` exports (`Consolidator`), not the modules inside. `memory/consolidation.py` is the only code that writes MEMORY.md; it reaches the LLM through the backend the agent hands it, so it doesn't import `memclaw.backends`.
- **Memory through its package**: other code uses what `memclaw.memory` exports (`MemoryStore`, `MemoryIndex`, `HybridSearch`, `Consolidator`, …), not the modules inside (`notes.py`, `index.py`, `search.py`, …). Inside, `consolidation` and `search` build on `notes` and `index`, never the other way round, and only `index.py` runs SQL on the search index. `memory/consolidation.py` is the only code that writes MEMORY.md; it reaches the LLM through the backend the agent hands it, so it doesn't import `memclaw.backends`.
- **Setup through its package**: other code uses what `memclaw.setup` exports (`run_setup`, `needs_setup`, `print_logo`, `print_probe_report`), not `setup/wizard.py` or `setup/doctor.py`.
- **Backends are swappable**: only `memclaw.backends` itself imports the concrete backend modules (`claude.py`, `cursor.py`, …). Everyone else goes through `memclaw.backends` / `memclaw.backends.base`.
- **`memclaw.defaults` stands alone**: the Cursor hook script there is copied out and run on its own, so it can't import memclaw.

Expand Down
4 changes: 1 addition & 3 deletions docs/library.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ The store, index and search work without the agent — only `OPENAI_API_KEY` is
```python
import asyncio
from memclaw.config import MemclawConfig
from memclaw.store import MemoryStore
from memclaw.index import MemoryIndex
from memclaw.search import HybridSearch
from memclaw.memory import HybridSearch, MemoryIndex, MemoryStore

async def main():
config = MemclawConfig()
Expand Down
14 changes: 14 additions & 0 deletions docs/memory-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,20 @@ When you ask "show me that photo of the sunset," the agent runs `image_search`:

---

## Where the Code Lives

All of the above is the `memclaw/memory/` package. Other code imports what its `__init__.py` exports (`MemoryStore`, `MemoryIndex`, `HybridSearch`, `SearchResult`, `Consolidator`), never the modules inside:

| Module | What it does |
|---|---|
| `notes.py` | `MemoryStore`: appends entries to the daily files, lists the notes |
| `chunking.py` | Splits a note into chunks (per entry, at headings, by size) |
| `index.py` | `MemoryIndex`: the SQLite database (chunks, embeddings and their cache, the FTS5 index, the image registry). The only code here that runs SQL |
| `search.py` | `HybridSearch`: the search pipeline (merge, decay, MMR). It reads the index through `MemoryIndex` methods |
| `consolidation.py`, `refs.py` | `Consolidator`: writes MEMORY.md and checks its references |

---

## Configuration Reference

All memory-related settings live in `MemclawConfig` (`memclaw/config.py`), most of them in its `memory` group. Pass them when you build one, e.g. `MemclawConfig(memory=MemorySettings(mmr_lambda=0.5))`, or set them on it (`config.memory.mmr_lambda = 0.5`):
Expand Down
2 changes: 2 additions & 0 deletions docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

Nothing changes for the `memclaw` command or your `.env`. In the library, `MemclawConfig`'s settings moved into groups: `MemclawConfig(openai_api_key="k")` is now `MemclawConfig(openai=OpenAISettings(api_key="k"))`, and `config.slack_bot_token` is `config.slack.bot_token`, `config.mmr_lambda` is `config.memory.mmr_lambda`, and so on. `memory_dir`, `agent_backend` and `platform` stay where they were. See [Using Memclaw as a Library](library.md).

The store, index and search moved into the `memclaw.memory` package: `from memclaw.store import MemoryStore`, `from memclaw.index import MemoryIndex` and `from memclaw.search import HybridSearch, SearchResult` are now `from memclaw.memory import MemoryStore, MemoryIndex, HybridSearch, SearchResult`. They work as before.

## From 2.x to 3.0

```bash
Expand Down
5 changes: 1 addition & 4 deletions memclaw/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,16 @@
from .backends import AgentBackend, build_backend
from .backends.base import ProgressCallback, TurnResult
from .config import MemclawConfig
from .index import MemoryIndex
from .instructions import (
build_system_prompt,
content_hash,
instructions_fingerprint,
load_agent_instructions,
load_permanent_memory,
)
from .memory import Consolidator
from .memory import Consolidator, HybridSearch, MemoryIndex, MemoryStore
from .reminders import ReminderScheduler
from .search import HybridSearch
from .sessions import SessionStore
from .store import MemoryStore
from .tools import ToolExecutor

# Per-turn memory search results. Kept small because every context block
Expand Down
6 changes: 3 additions & 3 deletions memclaw/backends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@

DEFAULT_BACKEND = "claude"

REGISTRY: dict[str, type] = {
REGISTRY: dict[str, type[AgentBackend]] = {
ClaudeAgentBackend.name: ClaudeAgentBackend,
CursorAgentBackend.name: CursorAgentBackend,
}


def list_backends() -> list[type]:
def list_backends() -> list[type[AgentBackend]]:
return list(REGISTRY.values())


def get_backend_class(name: str) -> type:
def get_backend_class(name: str) -> type[AgentBackend]:
"""Look up a backend class by short name. Raises ValueError if unknown."""
cls = REGISTRY.get(name)
if cls is None:
Expand Down
2 changes: 1 addition & 1 deletion memclaw/backends/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
)
from loguru import logger
from ..config import process_environment
from ..prompts import choose, masked_input
from ..terminal_input import choose, masked_input
from ..tools import TOOL_DEFINITIONS
from .base import ProgressCallback, TurnResult, report_tool_step
from .claude_models import SDK_EFFORT_LEVELS, ModelInfo, fetch_models
Expand Down
2 changes: 1 addition & 1 deletion memclaw/backends/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from rich.prompt import Prompt

from ..config import set_environment
from ..prompts import masked_input
from ..terminal_input import masked_input
from .base import ProgressCallback, TurnResult
from .claude_models import ModelInfo
from .cursor_hooks import cursor_hooks_status, ensure_cursor_hooks
Expand Down
4 changes: 1 addition & 3 deletions memclaw/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@

from .bot import PLATFORMS
from .config import MemclawConfig, reload_env_file
from .index import MemoryIndex
from .search import HybridSearch
from .memory import HybridSearch, MemoryIndex, MemoryStore
from .setup import needs_setup, print_logo, print_probe_report, run_setup
from .store import MemoryStore

console = Console()

Expand Down
24 changes: 20 additions & 4 deletions memclaw/memory/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
"""Memclaw's memory subsystem.
"""Memclaw's memory subsystem: the notes, the index and search over them,
and MEMORY.md.

Public:

- `MemoryStore` (notes.py): writes and lists the Markdown notes, the daily
files under memory/ that are the complete record.
- `MemoryIndex` (index.py): the SQLite index of the notes (chunks,
embeddings, FTS5) and of saved images. The only SQLite user here;
chunking.py splits the notes for it.
- `HybridSearch`, `SearchResult` (search.py): ranks chunks of the notes for
a query (vector + keyword, recency decay, near-duplicates dropped),
reading the index through MemoryIndex's methods.
- `Consolidator` (consolidation.py): distills the daily notes into
MEMORY.md, and is the only code that writes it. refs.py checks the
references it writes.

Public: `Consolidator`, which distills the daily notes into MEMORY.md (and
is the only code that writes it); `refs.py` checks the references it writes.
Other code imports from `memclaw.memory`, not from the modules inside.
"""

from .consolidation import Consolidator
from .index import MemoryIndex
from .notes import MemoryStore
from .search import HybridSearch, SearchResult

__all__ = ["Consolidator"]
__all__ = ["Consolidator", "HybridSearch", "MemoryIndex", "MemoryStore", "SearchResult"]
88 changes: 88 additions & 0 deletions memclaw/memory/chunking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""Splitting a note into the chunks the index embeds and searches."""

from __future__ import annotations

from dataclasses import dataclass

import numpy as np


@dataclass
class Chunk:
file_path: str
line_start: int
line_end: int
content: str
embedding: np.ndarray | None = None


def chunk_text(text: str, file_path: str, *, target_words: int, overlap_words: int) -> list[Chunk]:
"""Split text into chunks by entries, headings and size.

A ``---`` line ends an entry (``MemoryStore.save`` writes one after
each), so every entry starts a fresh chunk. A heading starts a new
chunk once the current one is half full. Only an entry too long for
one chunk is split by size, with overlap and its heading repeated.
"""
chunker = _Chunker(file_path, target_words, overlap_words)
lines = text.split("\n")
for i, line in enumerate(lines):
chunker.add(i, line)
if chunker.current:
chunker.flush(len(lines) - 1)
return chunker.chunks


class _Chunker:
"""The state of one `chunk_text` pass: the lines of the chunk being
built, where it starts, its word count and the heading it is under."""

def __init__(self, file_path: str, target_words: int, overlap_words: int):
self.file_path = file_path
self.target = target_words
self.overlap = overlap_words
self.chunks: list[Chunk] = []
self.current: list[str] = []
self.start = 0
self.words = 0
self.heading = ""

def add(self, i: int, line: str) -> None:
is_heading = line.startswith("#")
if is_heading and self.words > self.target // 2:
self.flush(i - 1)
self.current, self.start, self.words = [], i, 0
if is_heading:
self.heading = line

self.current.append(line)
self.words += len(line.split())

if line.strip() == "---":
self.flush(i)
self.current, self.start, self.words, self.heading = [], i + 1, 0, ""
elif self.words >= self.target:
self.flush(i)
self._keep_overlap(i)

def flush(self, end: int) -> None:
content = "\n".join(self.current).strip()
if content and content != "---":
self.chunks.append(Chunk(file_path=self.file_path, line_start=self.start,
line_end=end, content=content))

def _keep_overlap(self, i: int) -> None:
"""After a size split at line *i*: keep a tail of the entry for
continuity, under its heading."""
overlap_words = 0
keep = len(self.current)
for j in range(len(self.current) - 1, -1, -1):
overlap_words += len(self.current[j].split())
keep = j
if overlap_words >= self.overlap:
break
self.current = self.current[keep:] if keep > 0 else []
self.start = i - len(self.current) + 1
if self.heading and self.current and not any(ln.startswith("#") for ln in self.current):
self.current.insert(0, self.heading)
self.words = sum(len(ln.split()) for ln in self.current)
4 changes: 2 additions & 2 deletions memclaw/memory/consolidation.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
from loguru import logger

from ..config import MemclawConfig
from ..index import MemoryIndex
from ..store import MemoryStore
from .index import MemoryIndex
from .notes import MemoryStore
from .refs import check_references

# After a failed consolidation, wait this long before trying again rather
Expand Down
Loading
Loading