From 19d4503168ecbe7b77a506374c2f5304fd7ee56a Mon Sep 17 00:00:00 2001 From: Emanuilo Jovanovic Date: Sun, 22 Nov 2026 17:36:23 +0100 Subject: [PATCH 1/2] refactor(memory): MEMORY.md consolidation moves to memclaw/memory/consolidation.py About 245 lines of MemclawAgent were MEMORY.md consolidation. They are now one class, Consolidator, the only code that writes MEMORY.md. It owns the prompt, the daily-text budget, the .history/ copies, the meta.json marker and the background schedule. Its interface: - consolidate(force=False, since=None): run it now. `memclaw consolidate` calls it through agent.consolidator instead of the private agent._maybe_consolidate (`since` was `consolidated_through_override`). - schedule(): run it in the background after a reply (one at a time, an hour's pause after a failure). - aclose() / cancel(): stop a background run at shutdown. It reaches the LLM through the backend the agent hands it (anything with run_one_shot), so it doesn't import memclaw.backends. It lives in a new memclaw/memory/ package because the top-level folder is full; the coming memory/ package move (store, index, search) joins it there. Guards: a `memory` layer between tools and the core modules, and a new contract that other code imports memclaw.memory, not the modules inside. The concept "MEMORY.md + consolidation" now has memory/consolidation.py as its home. Baseline tightened: agent.py is no longer over 500 lines, MemclawAgent is 303 lines (was 482) with 17 attributes (was 18), and the cli -> agent private access is gone. Behaviour is unchanged: same prompt and message text, same files written, same retry, logs and failure handling (a failed one-shot call still leaves MEMORY.md and meta.json alone). The consolidation tests moved to tests/memory/test_consolidation.py and test Consolidator on its own. --- .code-shape/baseline.json | 7 +- CONTRIBUTING.md | 3 +- docs/memory-architecture.md | 2 + memclaw/agent.py | 306 ++------------------- memclaw/cli.py | 4 +- memclaw/memory/__init__.py | 10 + memclaw/memory/consolidation.py | 340 ++++++++++++++++++++++++ pyproject.toml | 15 +- tests/e2e/test_agent_e2e.py | 6 +- tests/memory/__init__.py | 0 tests/memory/test_consolidation.py | 410 +++++++++++++++++++++++++++++ tests/test_agent.py | 358 +------------------------ 12 files changed, 813 insertions(+), 648 deletions(-) create mode 100644 memclaw/memory/__init__.py create mode 100644 memclaw/memory/consolidation.py create mode 100644 tests/memory/__init__.py create mode 100644 tests/memory/test_consolidation.py diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index a223a13..e5b548e 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -10,14 +10,13 @@ "cognitive-complexity|memclaw/search.py|HybridSearch._merge": 17 }, "mypy": { - "type-errors|memclaw/agent.py|": 1, "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 }, "pylint": { - "class-attributes|memclaw/agent.py|MemclawAgent": 18, + "class-attributes|memclaw/agent.py|MemclawAgent": 17, "class-attributes|memclaw/backends/cursor.py|CursorAgentBackend": 13, "too-many-locals|memclaw/agent.py|MemclawAgent._handle": 19, "too-many-locals|memclaw/backends/claude.py|ClaudeAgentBackend.wizard_setup": 17, @@ -31,7 +30,6 @@ "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, - "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, @@ -40,11 +38,10 @@ "too-many-positional|memclaw/tools.py|ToolExecutor.__init__": 7 }, "sizes": { - "class-lines|memclaw/agent.py|MemclawAgent": 482, + "class-lines|memclaw/agent.py|MemclawAgent": 303, "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/agent.py|": 699, "file-lines|memclaw/backends/claude.py|": 775, "file-lines|memclaw/backends/cursor.py|": 604, "file-lines|memclaw/tools.py|": 577, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eddb704..e53b48b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,11 +66,12 @@ 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` → 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 (`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**: `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`. - **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 cfe2b2f..fdf2daa 100644 --- a/docs/memory-architecture.md +++ b/docs/memory-architecture.md @@ -125,6 +125,8 @@ 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=...)`. + The result aims for about 6,000 characters, with absolute dates, in the language MEMORY.md already uses (English when it starts empty). ### Permanent Memory in the Prompt diff --git a/memclaw/agent.py b/memclaw/agent.py index e9756ec..48fa9ae 100644 --- a/memclaw/agent.py +++ b/memclaw/agent.py @@ -1,8 +1,9 @@ """Memclaw agent — backend-agnostic orchestration over a pluggable agent SDK. -The agent owns memory, search, consolidation, the system-prompt shape and -the per-chat session bookkeeping, but delegates every LLM call to an -`AgentBackend` (see `memclaw.backends`). The backend is selected by +The agent handles each turn: the system prompt, the per-message context and +the per-chat session bookkeeping. It wires up memory, search and MEMORY.md +consolidation (`memclaw.memory.Consolidator`), and delegates every LLM call +to an `AgentBackend` (see `memclaw.backends`). The backend is selected by `config.agent_backend` (env var `AGENT_BACKEND`), defaulting to `claude`. Each chat's conversation lives in the backend's own session. The system @@ -14,12 +15,9 @@ from __future__ import annotations import asyncio -import contextlib import hashlib -import json -import re import time -from datetime import date, datetime +from datetime import datetime from pathlib import Path from loguru import logger @@ -28,7 +26,7 @@ from .backends.base import ProgressCallback, TurnResult from .config import MemclawConfig from .index import MemoryIndex -from .memory_refs import check_references +from .memory import Consolidator from .reminders import ReminderScheduler from .search import HybridSearch from .sessions import SessionStore @@ -90,20 +88,6 @@ # Session key for the interactive terminal (no chat id). _CLI_SESSION_KEY = "cli" -# After a failed consolidation, wait this long before trying again rather -# than retrying after every reply. -_CONSOLIDATION_RETRY_S = 3600 - -# Dated copies of MEMORY.md kept from before each consolidation. -_HISTORY_DIR = ".history" -_HISTORY_KEEP = 60 - -# Daily-file text sent to one consolidation call (~20k tokens). -_CONSOLIDATION_BUDGET_CHARS = 80000 - -# A reply wrapped in a ```markdown fence despite the instructions. -_FENCED_RE = re.compile(r"^```[\w-]*\n(.*?)\n?```$", re.DOTALL) - def _load_agent_instructions(config: MemclawConfig) -> str: agent_file = config.agent_file @@ -121,12 +105,6 @@ def _load_permanent_memory(config: MemclawConfig) -> str: return memory -def _strip_fence(text: str) -> str: - text = text.strip() - m = _FENCED_RE.match(text) - return m.group(1).strip() if m else text - - def _hash(text: str) -> str: return hashlib.sha256(text.encode()).hexdigest()[:16] @@ -142,85 +120,12 @@ def instructions_fingerprint(backend_name: str) -> str: return _hash(f"{backend_name}\0{_SYSTEM_PROMPT_TEMPLATE}") -_CONSOLIDATION_PROMPT = """\ -You maintain MEMORY.md, the user's permanent memory. It is loaded into the \ -assistant's system prompt in every conversation, so it is the assistant's \ -overview of the user: a holistic profile plus an index into the detailed \ -notes. The details stay where they are — the daily files \ -(memory/YYYY-MM-DD.md) and the other notes are never deleted — and the \ -assistant opens them when a detail is needed. - -You will receive today's date, the daily files to merge in (each under a \ -"### YYYY-MM-DD" header — that entry lives in memory/YYYY-MM-DD.md), a list \ -of the other notes in the vault, and the current MEMORY.md, which may be \ -empty. Write the complete new MEMORY.md. - -PROFILE — what the assistant should know at a glance, summarized, never \ -transcribed: -- Who the user is (name, age, where they live), their work, and the people \ -and pets in their life and how they relate to them. -- Ongoing projects, plans and goals; health and routines; finances in broad \ -strokes; lasting preferences and habits. -- Open threads worth keeping in mind (a debt, a pending decision, an \ -upcoming plan), each with its date. -- Short bullets, one thing each. Leave the specifics to the notes and add a \ -reference when there's more to read: "- Bekele (dog; also Izi, Beka) → \ -memory/2026-04-18.md". - -INDEX — where the details are, under "## Index" with subheadings such as \ -Credentials, Documents, How-tos, Purchases, Notes: -- One line per thing the user may ask for later — credentials and API keys, \ -document and account numbers, addresses, instructions and recipes, \ -commands, receipts, measurements — naming it and pointing to the note(s) \ -that hold it: "- Lion8 prod login and SSH commands → memory/2026-05-12.md, \ -memory/2026-06-13.md". -- Never copy secrets, document numbers or long instructions into MEMORY.md; \ -reference them. The one exception: a value that is only in the current \ -MEMORY.md, with no note given to you that holds it, is kept as is. -- Reference only files you were given or that the current MEMORY.md \ -already references, and only ones that hold that detail. When a detail was \ -updated, point to the latest entry; when it's spread out, list each file. -- References already in the current MEMORY.md stay unless the detail was \ -superseded. - -Leave out entirely: moments that have passed (one-off verification codes, \ -past events and deadlines, bookings for finished trips, superseded \ -statuses), links and articles saved to read later (they're searchable), \ -behavioural instructions for the assistant (those live in AGENTS.md), and \ -small talk. - -Accuracy: -- Use only what the sources say; never guess or fill gaps. -- Keep every fact with the right person: one person's birthday, document or \ -preference must never end up under someone else. -- When entries conflict, the later one wins, and an explicit correction \ -("ISPRAVKA", "correction", "actually") always overrides what it corrects. -- A fact in the current MEMORY.md stays unless a newer entry updates it or \ -it has clearly expired. - -Format: -- Markdown starting with "# Personal Memory"; profile sections (e.g. About, \ -People, Work & Projects, Health, Home & Pets, Finances, Preferences, Open \ -threads — only those with content), then "## Index". -- References are written exactly as "→ memory/YYYY-MM-DD.md" (several \ -separated by commas) or "→ .md" for the other notes, at the end of \ -the line. -- Absolute dates (YYYY-MM-DD). One language: the one the current MEMORY.md \ -is written in, or English if it is empty; keep names, places and quotes as \ -written. -- Fold any loose "## HH:MM - Note" entries in the current MEMORY.md into \ -the profile or the index. -- Aim for about 6,000 characters in total. -- Output only the MEMORY.md content: no preamble, no code fences. -""" - - class MemclawAgent: """Unified agent for both interactive CLI and messaging bots. - Memory, search, consolidation, and session orchestration live here. - Every LLM call is delegated to a pluggable `AgentBackend` chosen via - `config.agent_backend`. + Turn handling and session orchestration live here; MEMORY.md + consolidation is `self.consolidator`'s. Every LLM call is delegated to + a pluggable `AgentBackend` chosen via `config.agent_backend`. """ def __init__( @@ -256,8 +161,7 @@ def __init__( # Bumped by /new so a turn that was running doesn't re-save the # session it just reset. self._generations: dict[str, int] = {} - self._consolidation_task: asyncio.Task | None = None - self._consolidation_retry_at = 0.0 # monotonic time + 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() @@ -302,11 +206,7 @@ async def start(self, *, include_backend: bool = True): async def aclose(self): """Async shutdown: stop consolidation, release backend resources, then sync cleanup.""" - task = self._consolidation_task - if task is not None and not task.done(): - task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await task + await self.consolidator.aclose() if self._backend_started: await self.backend.on_agent_shutdown() self._backend_started = False @@ -325,181 +225,6 @@ async def _sync_loop(): self._sync_task = asyncio.create_task(_sync_loop()) - # ── Consolidation ──────────────────────────────────────────────── - - async def _maybe_consolidate( - self, - *, - force: bool = False, - consolidated_through_override: date | None = None, - ) -> bool: - """Distill the daily files not in MEMORY.md yet into it. Returns - whether MEMORY.md was rewritten.""" - if consolidated_through_override is not None: - consolidated_through = consolidated_through_override - else: - consolidated_through = self._read_consolidated_through() - - # Today's file is still being written to; it's consolidated once the - # day is over, so nothing saved later today is skipped. - today = date.today() - unconsolidated = [ - path for path in self.store.list_unconsolidated_files(consolidated_through) - if date.fromisoformat(path.stem) < today - ] - if not unconsolidated: - return False - if len(unconsolidated) < self.config.memory.consolidation_threshold and not force: - return False - - daily_text, included = self._daily_text(unconsolidated) - through = date.fromisoformat(included[-1].stem) - if not daily_text.strip(): - self._write_consolidated_through(through) - return False - - existing_memory = self.store.read_file(self.config.memory_file) - result_text = _strip_fence(await self.backend.run_one_shot( - system_prompt=_CONSOLIDATION_PROMPT, - user_message=self._consolidation_message(today, daily_text, existing_memory), - )) - if not result_text: - return False - refs = check_references(result_text, self.config.memory_dir) - for ref in refs.dropped: - logger.warning("Consolidation referenced a missing note, dropped: {r}", r=ref) - for ref in refs.unconfirmed: - logger.warning("Consolidation reference not confirmed by its note: {r}", r=ref) - - if not self._replace_memory(existing_memory, refs.text): - return False - self._write_consolidated_through(through) - try: - await self.index.index_file(self.config.memory_file) - except Exception as exc: - logger.warning("Indexing MEMORY.md after consolidation failed: {exc}", exc=exc) - remaining = len(unconsolidated) - len(included) - logger.info( - "Consolidation complete: {n} files → MEMORY.md (through {d}){more}", - n=len(included), - d=through.isoformat(), - more=f", {remaining} left for the next run" if remaining else "", - ) - return True - - def _daily_text(self, files: list[Path]) -> tuple[str, list[Path]]: - """The daily files to send, and which ones that covers: whole files, - oldest first, up to the budget; the rest wait for the next run. A - single file over the budget is sent truncated, or it would block - consolidation forever.""" - parts: list[str] = [] - included: list[Path] = [] - total = 0 - for path in files: - content = self.store.read_file(path) - part = f"\n### {path.stem}\n\n{content}" if content.strip() else "" - if total + len(part) > _CONSOLIDATION_BUDGET_CHARS: - if not included: - parts.append(part[:_CONSOLIDATION_BUDGET_CHARS]) - included.append(path) - break - if part: - parts.append(part) - total += len(part) - included.append(path) - return "\n".join(parts), included - - def _consolidation_message(self, today: date, daily_text: str, existing_memory: str) -> str: - message = f"Today's date: {today.isoformat()}\n\n## Daily Memory Files\n\n{daily_text}" - other_notes = self._other_notes_overview() - if other_notes: - message += f"\n\n## Other Notes\n\n{other_notes}" - if existing_memory.strip(): - message += f"\n\n## Current MEMORY.md\n\n{existing_memory}" - return message - - def _replace_memory(self, existing_memory: str, new_memory: str) -> bool: - """Write *new_memory* over MEMORY.md, keeping a dated copy of the old - one. Lines someone appended by hand while consolidation was running - are carried over; any other change meanwhile (an edit) means nothing - is written, and consolidation retries later.""" - current = self.store.read_file(self.config.memory_file) - if not current.startswith(existing_memory): - logger.warning("MEMORY.md changed during consolidation; will retry later") - return False - if existing_memory.strip(): - self._save_history(existing_memory) - added_since = current[len(existing_memory):] - self.config.memory_file.write_text(new_memory.rstrip("\n") + "\n" + added_since) - return True - - def _save_history(self, memory: str) -> None: - """Keep a dated copy of MEMORY.md as it was before a consolidation, - in a hidden directory (not indexed, not reachable by the file - tools), pruned to the last `_HISTORY_KEEP`.""" - history = self.config.memory_dir / _HISTORY_DIR - history.mkdir(exist_ok=True) - (history / f"MEMORY-{datetime.now():%Y-%m-%d-%H%M%S}.md").write_text(memory) - for old in sorted(history.glob("MEMORY-*.md"))[:-_HISTORY_KEEP]: - old.unlink() - - def _other_notes_overview(self) -> str: - """The vault's notes besides MEMORY.md and the daily files — name, - size and opening line — so MEMORY.md can reference them.""" - lines = [] - for path in self.index.indexable_files(): - if path.parent == self.config.memory_subdir or path == self.config.memory_file: - continue - text = self.store.read_file(path) - first = next((ln.strip("# ").strip() for ln in text.splitlines() if ln.strip()), "") - rel = path.relative_to(self.config.memory_dir).as_posix() - lines.append(f"- {rel} ({len(text)} chars): {first[:120]}") - return "\n".join(lines) - - @property - def _meta_path(self) -> Path: - return self.config.memory_dir / "meta.json" - - def _read_meta(self) -> dict: - try: - meta = json.loads(self._meta_path.read_text()) - except (OSError, ValueError): # missing or unreadable: start over - return {} - return meta if isinstance(meta, dict) else {} - - def _read_consolidated_through(self) -> date | None: - """The date of the last daily file consolidated, if any.""" - try: - return date.fromisoformat(self._read_meta().get("consolidated_through") or "") - except ValueError: - return None - - def _write_consolidated_through(self, through: date) -> None: - meta = self._read_meta() - meta["consolidated_through"] = through.isoformat() - tmp = self._meta_path.with_suffix(".tmp") - tmp.write_text(json.dumps(meta, indent=2)) - tmp.replace(self._meta_path) - - def _schedule_consolidation(self) -> None: - """Run the consolidation check in the background, after the reply, - so it never delays one. At most one runs at a time.""" - if self._consolidation_task is not None and not self._consolidation_task.done(): - return - if time.monotonic() < self._consolidation_retry_at: - return - self._consolidation_task = asyncio.create_task(self._consolidate_in_background()) - - async def _consolidate_in_background(self) -> None: - try: - await self._maybe_consolidate() - except Exception as exc: - self._consolidation_retry_at = time.monotonic() + _CONSOLIDATION_RETRY_S - logger.exception( - "Background consolidation failed, retrying in {m} min: {exc}", - m=_CONSOLIDATION_RETRY_S // 60, exc=exc, - ) - # ── Context builder ────────────────────────────────────────────── async def build_context( @@ -639,7 +364,7 @@ async def _handle( if result.session_id and self._generations.get(key, 0) == generation: self._save_session(key, result.session_id, agents_hash, memory_hash) - self._schedule_consolidation() + self.consolidator.schedule() response_text = result.text or "I couldn't generate a response." return (response_text, list(self._found_images)) @@ -680,9 +405,10 @@ def _save_session(self, key: str, session_id: str, agents_hash: str, memory_hash }) def _close_sync_only(self) -> None: - for task in (getattr(self, "_sync_task", None), self._consolidation_task): - if task is not None and not task.done(): - task.cancel() + task = getattr(self, "_sync_task", None) + if task is not None and not task.done(): + task.cancel() + self.consolidator.cancel() self.index.close() def close(self): diff --git a/memclaw/cli.py b/memclaw/cli.py index f885649..e7690e9 100644 --- a/memclaw/cli.py +++ b/memclaw/cli.py @@ -233,9 +233,7 @@ async def _run(): with console.status("[cyan]Syncing index...[/cyan]"): await agent.start(include_backend=False) with console.status("[cyan]Running consolidation...[/cyan]"): - result = await agent._maybe_consolidate( - force=True, consolidated_through_override=override - ) + result = await agent.consolidator.consolidate(force=True, since=override) if result: console.print("[green]Consolidation complete.[/green] MEMORY.md has been updated.") else: diff --git a/memclaw/memory/__init__.py b/memclaw/memory/__init__.py new file mode 100644 index 0000000..95e8fca --- /dev/null +++ b/memclaw/memory/__init__.py @@ -0,0 +1,10 @@ +"""Memclaw's memory subsystem. + +Public: `Consolidator`, which distills the daily notes into MEMORY.md (and +is the only code that writes it). Other code imports from `memclaw.memory`, +not from the modules inside. +""" + +from .consolidation import Consolidator + +__all__ = ["Consolidator"] diff --git a/memclaw/memory/consolidation.py b/memclaw/memory/consolidation.py new file mode 100644 index 0000000..45b1509 --- /dev/null +++ b/memclaw/memory/consolidation.py @@ -0,0 +1,340 @@ +"""MEMORY.md consolidation: distill the finished days' notes into MEMORY.md. + +`Consolidator` is the only code that writes MEMORY.md. It owns the prompt, +how much daily text one call gets, the dated copies in `.history/`, the +`meta.json` marker of what's done, and the background schedule (after a +reply, at most one at a time, an hour's pause after a failure). + +The LLM call goes to whatever has a `run_one_shot` (the agent backend), so +this module doesn't depend on the backends. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import re +import time +from datetime import date, datetime +from pathlib import Path +from typing import Protocol + +from loguru import logger + +from ..config import MemclawConfig +from ..index import MemoryIndex +from ..store import MemoryStore +from ..memory_refs import check_references + +# After a failed consolidation, wait this long before trying again rather +# than retrying after every reply. +_CONSOLIDATION_RETRY_S = 3600 + +# Dated copies of MEMORY.md kept from before each consolidation. +_HISTORY_DIR = ".history" +_HISTORY_KEEP = 60 + +# Daily-file text sent to one consolidation call (~20k tokens). +_CONSOLIDATION_BUDGET_CHARS = 80000 + +# A reply wrapped in a ```markdown fence despite the instructions. +_FENCED_RE = re.compile(r"^```[\w-]*\n(.*?)\n?```$", re.DOTALL) + + +_CONSOLIDATION_PROMPT = """\ +You maintain MEMORY.md, the user's permanent memory. It is loaded into the \ +assistant's system prompt in every conversation, so it is the assistant's \ +overview of the user: a holistic profile plus an index into the detailed \ +notes. The details stay where they are — the daily files \ +(memory/YYYY-MM-DD.md) and the other notes are never deleted — and the \ +assistant opens them when a detail is needed. + +You will receive today's date, the daily files to merge in (each under a \ +"### YYYY-MM-DD" header — that entry lives in memory/YYYY-MM-DD.md), a list \ +of the other notes in the vault, and the current MEMORY.md, which may be \ +empty. Write the complete new MEMORY.md. + +PROFILE — what the assistant should know at a glance, summarized, never \ +transcribed: +- Who the user is (name, age, where they live), their work, and the people \ +and pets in their life and how they relate to them. +- Ongoing projects, plans and goals; health and routines; finances in broad \ +strokes; lasting preferences and habits. +- Open threads worth keeping in mind (a debt, a pending decision, an \ +upcoming plan), each with its date. +- Short bullets, one thing each. Leave the specifics to the notes and add a \ +reference when there's more to read: "- Bekele (dog; also Izi, Beka) → \ +memory/2026-04-18.md". + +INDEX — where the details are, under "## Index" with subheadings such as \ +Credentials, Documents, How-tos, Purchases, Notes: +- One line per thing the user may ask for later — credentials and API keys, \ +document and account numbers, addresses, instructions and recipes, \ +commands, receipts, measurements — naming it and pointing to the note(s) \ +that hold it: "- Lion8 prod login and SSH commands → memory/2026-05-12.md, \ +memory/2026-06-13.md". +- Never copy secrets, document numbers or long instructions into MEMORY.md; \ +reference them. The one exception: a value that is only in the current \ +MEMORY.md, with no note given to you that holds it, is kept as is. +- Reference only files you were given or that the current MEMORY.md \ +already references, and only ones that hold that detail. When a detail was \ +updated, point to the latest entry; when it's spread out, list each file. +- References already in the current MEMORY.md stay unless the detail was \ +superseded. + +Leave out entirely: moments that have passed (one-off verification codes, \ +past events and deadlines, bookings for finished trips, superseded \ +statuses), links and articles saved to read later (they're searchable), \ +behavioural instructions for the assistant (those live in AGENTS.md), and \ +small talk. + +Accuracy: +- Use only what the sources say; never guess or fill gaps. +- Keep every fact with the right person: one person's birthday, document or \ +preference must never end up under someone else. +- When entries conflict, the later one wins, and an explicit correction \ +("ISPRAVKA", "correction", "actually") always overrides what it corrects. +- A fact in the current MEMORY.md stays unless a newer entry updates it or \ +it has clearly expired. + +Format: +- Markdown starting with "# Personal Memory"; profile sections (e.g. About, \ +People, Work & Projects, Health, Home & Pets, Finances, Preferences, Open \ +threads — only those with content), then "## Index". +- References are written exactly as "→ memory/YYYY-MM-DD.md" (several \ +separated by commas) or "→ .md" for the other notes, at the end of \ +the line. +- Absolute dates (YYYY-MM-DD). One language: the one the current MEMORY.md \ +is written in, or English if it is empty; keep names, places and quotes as \ +written. +- Fold any loose "## HH:MM - Note" entries in the current MEMORY.md into \ +the profile or the index. +- Aim for about 6,000 characters in total. +- Output only the MEMORY.md content: no preamble, no code fences. +""" + + +class OneShotBackend(Protocol): + """What consolidation needs from the agent backend: one tool-free call + that returns the reply text, or raises if the call failed.""" + + async def run_one_shot(self, *, system_prompt: str, user_message: str) -> str: ... + + +def _strip_fence(text: str) -> str: + text = text.strip() + m = _FENCED_RE.match(text) + return m.group(1).strip() if m else text + + +class Consolidator: + """Distills the daily files not in MEMORY.md yet into it. + + `consolidate()` runs it now (`memclaw consolidate`); `schedule()` runs + it in the background after a reply. `aclose()` / `cancel()` stop a + background run at shutdown. + """ + + def __init__( + self, + config: MemclawConfig, + store: MemoryStore, + index: MemoryIndex, + backend: OneShotBackend, + ): + self.config = config + self._store = store + self._index = index + self._backend = backend + self._task: asyncio.Task | None = None + self._retry_at = 0.0 # monotonic time + + # ── Running ────────────────────────────────────────────────────── + + async def consolidate(self, *, force: bool = False, since: date | None = None) -> bool: + """Distill the daily files not in MEMORY.md yet into it. Returns + whether MEMORY.md was rewritten. + + *force* runs it below `consolidation_threshold`; *since* takes the + daily files after that date instead of after the last one done.""" + consolidated_through = since if since is not None else self._read_consolidated_through() + + # Today's file is still being written to; it's consolidated once the + # day is over, so nothing saved later today is skipped. + today = date.today() + unconsolidated = [ + path for path in self._store.list_unconsolidated_files(consolidated_through) + if date.fromisoformat(path.stem) < today + ] + if not unconsolidated: + return False + if len(unconsolidated) < self.config.memory.consolidation_threshold and not force: + return False + + daily_text, included = self._daily_text(unconsolidated) + through = date.fromisoformat(included[-1].stem) + if not daily_text.strip(): + self._write_consolidated_through(through) + return False + + existing_memory = self._store.read_file(self.config.memory_file) + result_text = _strip_fence(await self._backend.run_one_shot( + system_prompt=_CONSOLIDATION_PROMPT, + user_message=self._message(today, daily_text, existing_memory), + )) + if not result_text: + return False + refs = check_references(result_text, self.config.memory_dir) + for ref in refs.dropped: + logger.warning("Consolidation referenced a missing note, dropped: {r}", r=ref) + for ref in refs.unconfirmed: + logger.warning("Consolidation reference not confirmed by its note: {r}", r=ref) + + if not self._replace_memory(existing_memory, refs.text): + return False + self._write_consolidated_through(through) + try: + await self._index.index_file(self.config.memory_file) + except Exception as exc: + logger.warning("Indexing MEMORY.md after consolidation failed: {exc}", exc=exc) + remaining = len(unconsolidated) - len(included) + logger.info( + "Consolidation complete: {n} files → MEMORY.md (through {d}){more}", + n=len(included), + d=through.isoformat(), + more=f", {remaining} left for the next run" if remaining else "", + ) + return True + + def schedule(self) -> None: + """Run the consolidation check in the background, after the reply, + so it never delays one. At most one runs at a time.""" + if self._task is not None and not self._task.done(): + return + if time.monotonic() < self._retry_at: + return + self._task = asyncio.create_task(self._consolidate_in_background()) + + async def _consolidate_in_background(self) -> None: + try: + await self.consolidate() + except Exception as exc: + self._retry_at = time.monotonic() + _CONSOLIDATION_RETRY_S + logger.exception( + "Background consolidation failed, retrying in {m} min: {exc}", + m=_CONSOLIDATION_RETRY_S // 60, exc=exc, + ) + + def cancel(self) -> None: + """Stop a running background consolidation without waiting for it.""" + if self._task is not None and not self._task.done(): + self._task.cancel() + + async def aclose(self) -> None: + """Stop a running background consolidation and wait until it has.""" + task = self._task + if task is not None and not task.done(): + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + # ── What is sent ───────────────────────────────────────────────── + + def _daily_text(self, files: list[Path]) -> tuple[str, list[Path]]: + """The daily files to send, and which ones that covers: whole files, + oldest first, up to the budget; the rest wait for the next run. A + single file over the budget is sent truncated, or it would block + consolidation forever.""" + parts: list[str] = [] + included: list[Path] = [] + total = 0 + for path in files: + content = self._store.read_file(path) + part = f"\n### {path.stem}\n\n{content}" if content.strip() else "" + if total + len(part) > _CONSOLIDATION_BUDGET_CHARS: + if not included: + parts.append(part[:_CONSOLIDATION_BUDGET_CHARS]) + included.append(path) + break + if part: + parts.append(part) + total += len(part) + included.append(path) + return "\n".join(parts), included + + def _message(self, today: date, daily_text: str, existing_memory: str) -> str: + message = f"Today's date: {today.isoformat()}\n\n## Daily Memory Files\n\n{daily_text}" + other_notes = self._other_notes_overview() + if other_notes: + message += f"\n\n## Other Notes\n\n{other_notes}" + if existing_memory.strip(): + message += f"\n\n## Current MEMORY.md\n\n{existing_memory}" + return message + + def _other_notes_overview(self) -> str: + """The vault's notes besides MEMORY.md and the daily files — name, + size and opening line — so MEMORY.md can reference them.""" + lines = [] + for path in self._index.indexable_files(): + if path.parent == self.config.memory_subdir or path == self.config.memory_file: + continue + text = self._store.read_file(path) + first = next((ln.strip("# ").strip() for ln in text.splitlines() if ln.strip()), "") + rel = path.relative_to(self.config.memory_dir).as_posix() + lines.append(f"- {rel} ({len(text)} chars): {first[:120]}") + return "\n".join(lines) + + # ── Writing MEMORY.md ──────────────────────────────────────────── + + def _replace_memory(self, existing_memory: str, new_memory: str) -> bool: + """Write *new_memory* over MEMORY.md, keeping a dated copy of the old + one. Lines someone appended by hand while consolidation was running + are carried over; any other change meanwhile (an edit) means nothing + is written, and consolidation retries later.""" + current = self._store.read_file(self.config.memory_file) + if not current.startswith(existing_memory): + logger.warning("MEMORY.md changed during consolidation; will retry later") + return False + if existing_memory.strip(): + self._save_history(existing_memory) + added_since = current[len(existing_memory):] + self.config.memory_file.write_text(new_memory.rstrip("\n") + "\n" + added_since) + return True + + def _save_history(self, memory: str) -> None: + """Keep a dated copy of MEMORY.md as it was before a consolidation, + in a hidden directory (not indexed, not reachable by the file + tools), pruned to the last `_HISTORY_KEEP`.""" + history = self.config.memory_dir / _HISTORY_DIR + history.mkdir(exist_ok=True) + (history / f"MEMORY-{datetime.now():%Y-%m-%d-%H%M%S}.md").write_text(memory) + for old in sorted(history.glob("MEMORY-*.md"))[:-_HISTORY_KEEP]: + old.unlink() + + # ── The marker (meta.json) ─────────────────────────────────────── + + @property + def _meta_path(self) -> Path: + return self.config.memory_dir / "meta.json" + + def _read_meta(self) -> dict: + try: + meta = json.loads(self._meta_path.read_text()) + except (OSError, ValueError): # missing or unreadable: start over + return {} + return meta if isinstance(meta, dict) else {} + + def _read_consolidated_through(self) -> date | None: + """The date of the last daily file consolidated, if any.""" + try: + return date.fromisoformat(self._read_meta().get("consolidated_through") or "") + except ValueError: + return None + + def _write_consolidated_through(self, through: date) -> None: + meta = self._read_meta() + meta["consolidated_through"] = through.isoformat() + tmp = self._meta_path.with_suffix(".tmp") + tmp.write_text(json.dumps(meta, indent=2)) + tmp.replace(self._meta_path) diff --git a/pyproject.toml b/pyproject.toml index c1bc94b..6124a6b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -133,7 +133,7 @@ ignore_names = [ # The ideas a change is usually about (tracked in `code-shape report`, never a # gate): words that name each one in code, and the module that should own it. "memory notes (daily files)" = { terms = ["MemoryStore", "daily_file", "memory_save"], home = "memclaw/store.py" } -"MEMORY.md + consolidation" = { terms = ["consolidat", "MEMORY\\.md", "permanent_memory"], home = "memclaw/agent.py" } +"MEMORY.md + consolidation" = { terms = ["consolidat", "MEMORY\\.md", "permanent_memory"], home = "memclaw/memory/consolidation.py" } "search + index" = { terms = ["HybridSearch", "MemoryIndex", "embedding"], home = "memclaw/index.py" } "reminders" = { terms = ["remind"], home = "memclaw/reminders.py" } "settings storage (.env)" = { terms = ["read_env_file", "update_env_file", "write_env_file", "os\\.environ"], home = "memclaw/config.py" } @@ -161,7 +161,7 @@ include_external_packages = true [[tool.importlinter.contracts]] id = "layers" -name = "Layers: a module may only import modules in layers BELOW it (entry points -> agent -> backends -> tools -> core -> config)" +name = "Layers: a module may only import modules in layers BELOW it (entry points -> agent -> backends -> tools -> memory -> core -> config)" type = "layers" containers = ["memclaw"] layers = [ @@ -178,6 +178,10 @@ layers = [ "backends", # The memory tools the agent can call. "tools", + # The memory subsystem (memclaw.memory): MEMORY.md consolidation, the only + # writer of MEMORY.md. It builds on the modules below and reaches the LLM + # through the backend the agent hands it, so it doesn't import backends. + "memory", # Independent building blocks (`|`: they don't import each other). "search | store | reminders | sessions | memory_refs | prompts", # SQLite + embeddings index, used by search. @@ -237,6 +241,13 @@ type = "protected" protected_modules = ["openai"] allowed_importers = ["memclaw.openai_client"] +[[tool.importlinter.contracts]] +id = "memory-via-package" +name = "Only memclaw.memory imports its own modules: everyone else uses what memclaw.memory exports (e.g. Consolidator)" +type = "protected" +protected_modules = ["memclaw.memory.consolidation"] +allowed_importers = ["memclaw.memory"] + [[tool.importlinter.contracts]] id = "defaults-standalone" name = "memclaw.defaults imports nothing from memclaw (its Cursor hook script is copied to ~/.memclaw and run on its own)" diff --git a/tests/e2e/test_agent_e2e.py b/tests/e2e/test_agent_e2e.py index 80007fd..fabe90f 100644 --- a/tests/e2e/test_agent_e2e.py +++ b/tests/e2e/test_agent_e2e.py @@ -62,7 +62,7 @@ async def test_durable_fact_reaches_memory_md_after_the_day(agent_vault): # The day is over. agent_vault.daily_file().rename(agent_vault.daily_file(days_ago(1))) - assert await agent._maybe_consolidate() + assert await agent.consolidator.consolidate() assert "penicillin" in agent_vault.memory_file.read_text().lower() finally: await agent.aclose() @@ -141,7 +141,7 @@ async def run_one_shot_with_concurrent_save(**kwargs): agent.backend.run_one_shot = run_one_shot_with_concurrent_save try: await agent.start(include_backend=False) - assert await agent._maybe_consolidate(force=True) + assert await agent.consolidator.consolidate(force=True) finally: await agent.aclose() @@ -183,7 +183,7 @@ async def test_consolidation_prompt_quality(agent_vault): agent = MemclawAgent(agent_vault) try: - assert await agent._maybe_consolidate(force=True) + assert await agent.consolidator.consolidate(force=True) finally: await agent.aclose() diff --git a/tests/memory/__init__.py b/tests/memory/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/memory/test_consolidation.py b/tests/memory/test_consolidation.py new file mode 100644 index 0000000..f306ed7 --- /dev/null +++ b/tests/memory/test_consolidation.py @@ -0,0 +1,410 @@ +"""Tests for Consolidator — distilling the daily notes into MEMORY.md. + +They run against a fake one-shot backend, so they pin what is sent, what is +written (MEMORY.md, .history/, meta.json) and when it runs, without an SDK. +""" +from __future__ import annotations + +import asyncio +import json +import time +from dataclasses import dataclass, field +from datetime import date, timedelta +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings +from memclaw.index import MemoryIndex +from memclaw.memory import Consolidator +from memclaw.memory.consolidation import _CONSOLIDATION_BUDGET_CHARS as BUDGET +from memclaw.store import MemoryStore + + +@pytest.fixture +def cfg(tmp_path: Path) -> MemclawConfig: + return MemclawConfig( + memory_dir=tmp_path / "m", + openai=OpenAISettings(api_key="test-openai-key"), + claude=ClaudeSettings(api_key="test-anthropic-key"), + ) + + +@dataclass +class FakeBackend: + """One-shot stub that records calls and returns a canned reply.""" + + one_shot_response: str = "" + one_shot_calls: list[dict[str, Any]] = field(default_factory=list) + + 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 + + +@pytest.fixture +def fake_backend() -> FakeBackend: + return FakeBackend() + + +@pytest.fixture +def index(cfg: MemclawConfig): + idx = MemoryIndex(cfg) + yield idx + idx.close() + + +@pytest.fixture +def consolidator(cfg: MemclawConfig, index: MemoryIndex, fake_backend: FakeBackend) -> Consolidator: + return Consolidator(cfg, MemoryStore(cfg), index, fake_backend) + + +def _daily(cfg: MemclawConfig, d: date, text: str) -> Path: + path = cfg.daily_file(d) + path.write_text(text) + return path + + +def _consolidated_through(cfg: MemclawConfig) -> str: + return json.loads((cfg.memory_dir / "meta.json").read_text())["consolidated_through"] + + +# ──────────────────────────────────────────────────────────────────── +# When it runs +# ──────────────────────────────────────────────────────────────────── + +class TestThreshold: + @pytest.mark.asyncio + async def test_skips_when_below_threshold(self, cfg, fake_backend, consolidator): + """Consolidation should not run when file count < threshold.""" + cfg.memory.consolidation_threshold = 7 + for i in range(3): + _daily(cfg, date(2025, 3, i + 1), f"# Day {i}\nSome content") + + assert await consolidator.consolidate() is False + assert fake_backend.one_shot_calls == [] + + @pytest.mark.asyncio + async def test_runs_when_above_threshold(self, cfg, fake_backend, consolidator, index): + """Consolidation should run when file count >= threshold.""" + cfg.memory.consolidation_threshold = 3 + fake_backend.one_shot_response = "## Key Facts\n\n- Fact 0\n- Fact 1\n" + for i in range(5): + _daily(cfg, date(2025, 3, i + 1), f"# Day {i}\nImportant fact {i}") + index.index_file = AsyncMock() + + assert await consolidator.consolidate() is True + assert "Key Facts" in cfg.memory_file.read_text() + assert _consolidated_through(cfg) == "2025-03-05" + index.index_file.assert_awaited_once_with(cfg.memory_file) + + @pytest.mark.asyncio + async def test_force_ignores_threshold(self, cfg, fake_backend, consolidator, index): + """force=True should run consolidation even with 1 file.""" + cfg.memory.consolidation_threshold = 100 + fake_backend.one_shot_response = "## Notes\n- One note" + _daily(cfg, date(2025, 3, 1), "# Single day\nJust one note") + index.index_file = AsyncMock() + + assert await consolidator.consolidate(force=True) is True + + @pytest.mark.asyncio + async def test_since_overrides_meta(self, cfg, fake_backend, consolidator, index): + """since= takes the files after that date, whatever meta.json says.""" + fake_backend.one_shot_response = "## Consolidated" + for i in range(1, 11): + _daily(cfg, date(2025, 3, i), f"Content for day {i}") + (cfg.memory_dir / "meta.json").write_text(json.dumps({"consolidated_through": "2025-03-01"})) + index.index_file = AsyncMock() + + assert await consolidator.consolidate(force=True, since=date(2025, 3, 8)) is True + user_msg = fake_backend.one_shot_calls[-1]["user"] + assert "2025-03-09" in user_msg + assert "2025-03-10" in user_msg + assert "2025-03-05" not in user_msg + + @pytest.mark.asyncio + async def test_no_files_returns_false(self, fake_backend, consolidator): + assert await consolidator.consolidate(force=True) is False + assert fake_backend.one_shot_calls == [] + + @pytest.mark.asyncio + async def test_by_default_it_runs_once_a_day_has_passed(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = "# Personal Memory\n- x" + _daily(cfg, date.today(), "today") + assert await consolidator.consolidate() is False # today isn't over + _daily(cfg, date.today() - timedelta(days=1), "yesterday") + assert await consolidator.consolidate() is True + + @pytest.mark.asyncio + async def test_todays_file_is_left_for_later(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = "## Facts\n- x" + _daily(cfg, date.today() - timedelta(days=1), "yesterday's note") + _daily(cfg, date.today(), "today's note") + + assert await consolidator.consolidate(force=True) + assert "today's note" not in fake_backend.one_shot_calls[0]["user"] + assert _consolidated_through(cfg) == (date.today() - timedelta(days=1)).isoformat() + + @pytest.mark.asyncio + async def test_only_today_means_nothing_to_do(self, cfg, fake_backend, consolidator): + _daily(cfg, date.today(), "today's note") + assert await consolidator.consolidate(force=True) is False + assert fake_backend.one_shot_calls == [] + + @pytest.mark.asyncio + async def test_empty_daily_files_are_marked_done_without_a_call(self, cfg, fake_backend, consolidator): + _daily(cfg, date(2025, 3, 1), " ") + _daily(cfg, date(2025, 3, 2), "") + assert await consolidator.consolidate(force=True) is False + assert fake_backend.one_shot_calls == [] + assert _consolidated_through(cfg) == "2025-03-02" + + +# ──────────────────────────────────────────────────────────────────── +# What is sent +# ──────────────────────────────────────────────────────────────────── + +class TestMessage: + @pytest.mark.asyncio + async def test_content_limit(self, cfg, fake_backend, consolidator): + """Content gathering should stop at the consolidation budget.""" + fake_backend.one_shot_response = "## Consolidated" + for i in range(1, 6): + _daily(cfg, date(2025, 3, i), "x" * (BUDGET // 3)) + + await consolidator.consolidate(force=True) + assert len(fake_backend.one_shot_calls[-1]["user"]) < BUDGET + 5000 + + @pytest.mark.asyncio + async def test_files_past_the_budget_stay_unconsolidated(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = "## Facts\n- x" + for day in range(1, 6): + _daily(cfg, date(2025, 3, day), f"day {day} " + "x" * (BUDGET // 3)) + + assert await consolidator.consolidate(force=True) + user_msg = fake_backend.one_shot_calls[0]["user"] + assert "day 2 " in user_msg and "day 3 " not in user_msg + assert _consolidated_through(cfg) == "2025-03-02" + + # The next run picks up where this one stopped. + assert await consolidator.consolidate(force=True) + assert "day 3 " in fake_backend.one_shot_calls[1]["user"] + + @pytest.mark.asyncio + async def test_single_oversized_file_is_truncated_not_stuck(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = "## Facts\n- x" + _daily(cfg, date(2025, 3, 1), "y" * (BUDGET + 20000)) + assert await consolidator.consolidate(force=True) + assert _consolidated_through(cfg) == "2025-03-01" + + @pytest.mark.asyncio + async def test_consolidation_is_told_todays_date(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = "# Personal Memory" + _daily(cfg, date(2025, 3, 1), "note") + await consolidator.consolidate(force=True) + assert f"Today's date: {date.today().isoformat()}" in fake_backend.one_shot_calls[0]["user"] + + @pytest.mark.asyncio + async def test_prompt_and_message_layout(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = "# Personal Memory" + cfg.memory_file.write_text("# Personal Memory\n- old fact\n") + _daily(cfg, date(2025, 3, 1), "note one") + await consolidator.consolidate(force=True) + call = fake_backend.one_shot_calls[0] + assert call["system"].startswith("You maintain MEMORY.md, the user's permanent memory.") + assert call["user"] == ( + f"Today's date: {date.today().isoformat()}\n\n## Daily Memory Files\n\n" + "\n### 2025-03-01\n\nnote one" + "\n\n## Current MEMORY.md\n\n# Personal Memory\n- old fact\n" + ) + + @pytest.mark.asyncio + async def test_other_notes_are_listed_for_the_index(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = "# Personal Memory" + (cfg.memory_dir / "todos.md").write_text("# Todos\n- renew passport") + _daily(cfg, date(2025, 3, 1), "note") + await consolidator.consolidate(force=True) + user_msg = fake_backend.one_shot_calls[0]["user"] + assert "## Other Notes" in user_msg + assert "- todos.md (" in user_msg and "Todos" in user_msg + assert "AGENTS.md" not in user_msg.split("## Other Notes")[1] + + +# ──────────────────────────────────────────────────────────────────── +# Writing MEMORY.md +# ──────────────────────────────────────────────────────────────────── + +class TestWriting: + @pytest.mark.asyncio + async def test_save_during_consolidation_is_kept(self, cfg, fake_backend, consolidator): + _daily(cfg, date(2025, 3, 1), "note") + + async def one_shot(**kwargs): + with open(cfg.memory_file, "a") as f: # appended by hand meanwhile + f.write("- Blood type 0 negative\n") + return "## Facts\n- consolidated" + + fake_backend.run_one_shot = one_shot + assert await consolidator.consolidate(force=True) + memory = cfg.memory_file.read_text() + assert memory.startswith("## Facts\n- consolidated") + assert "Blood type 0 negative" in memory + history = list((cfg.memory_dir / ".history").glob("MEMORY-*.md")) + assert [h.read_text() for h in history] == ["# Personal Memory\n"] + + @pytest.mark.asyncio + async def test_manual_edit_during_consolidation_aborts(self, cfg, fake_backend, consolidator): + _daily(cfg, date(2025, 3, 1), "note") + + async def one_shot(**kwargs): + cfg.memory_file.write_text("# Edited by hand\n") + return "## Facts\n- consolidated" + + fake_backend.run_one_shot = one_shot + assert await consolidator.consolidate(force=True) is False + assert cfg.memory_file.read_text() == "# Edited by hand\n" + assert not (cfg.memory_dir / "meta.json").exists() + + @pytest.mark.asyncio + async def test_failed_backend_call_leaves_memory_untouched(self, cfg, fake_backend, consolidator): + _daily(cfg, date(2025, 3, 1), "note") + before = cfg.memory_file.read_text() + + async def one_shot(**kwargs): + raise RuntimeError("Claude one-shot failed (unknown): API Error: Connection refused") + + fake_backend.run_one_shot = one_shot + with pytest.raises(RuntimeError): + await consolidator.consolidate(force=True) + assert cfg.memory_file.read_text() == before + assert not (cfg.memory_dir / "meta.json").exists() + assert not (cfg.memory_dir / ".history").exists() + + @pytest.mark.asyncio + async def test_empty_reply_leaves_memory_untouched(self, cfg, fake_backend, consolidator): + _daily(cfg, date(2025, 3, 1), "note") + before = cfg.memory_file.read_text() + fake_backend.one_shot_response = " \n" + assert await consolidator.consolidate(force=True) is False + assert cfg.memory_file.read_text() == before + assert not (cfg.memory_dir / "meta.json").exists() + + @pytest.mark.asyncio + async def test_code_fence_is_stripped(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = "```markdown\n## Facts\n- x\n```" + _daily(cfg, date(2025, 3, 1), "note") + assert await consolidator.consolidate(force=True) + assert cfg.memory_file.read_text() == "## Facts\n- x\n" + + @pytest.mark.asyncio + async def test_references_to_missing_notes_are_dropped(self, cfg, fake_backend, consolidator): + fake_backend.one_shot_response = ( + "# Personal Memory\n\n## Index\n" + "- Lion8 login → memory/2025-03-01.md, memory/2024-01-01.md\n" + ) + _daily(cfg, date(2025, 3, 1), "Lion8 login: admin") + await consolidator.consolidate(force=True) + assert "- Lion8 login → memory/2025-03-01.md\n" in cfg.memory_file.read_text() + + @pytest.mark.asyncio + async def test_history_keeps_the_last_60(self, cfg, fake_backend, consolidator): + history = cfg.memory_dir / ".history" + history.mkdir() + for i in range(65): + (history / f"MEMORY-2025-01-01-{i:06d}.md").write_text(str(i)) + cfg.memory_file.write_text("latest") + fake_backend.one_shot_response = "# Personal Memory\n- next" + _daily(cfg, date(2025, 3, 1), "note") + assert await consolidator.consolidate(force=True) + kept = sorted(history.glob("MEMORY-*.md")) + assert len(kept) == 60 + assert kept[-1].read_text() == "latest" + assert not (history / "MEMORY-2025-01-01-000000.md").exists() + + @pytest.mark.asyncio + async def test_indexing_failure_still_counts_as_done(self, cfg, fake_backend, consolidator, index): + fake_backend.one_shot_response = "# Personal Memory\n- x" + _daily(cfg, date(2025, 3, 1), "note") + index.index_file = AsyncMock(side_effect=RuntimeError("OpenAI down")) + assert await consolidator.consolidate(force=True) + assert cfg.memory_file.read_text() == "# Personal Memory\n- x\n" + assert _consolidated_through(cfg) == "2025-03-01" + + @pytest.mark.asyncio + async def test_unreadable_meta_starts_over(self, cfg, fake_backend, consolidator): + (cfg.memory_dir / "meta.json").write_text("[1, 2]") + fake_backend.one_shot_response = "# Personal Memory\n- x" + _daily(cfg, date(2025, 3, 1), "note") + assert await consolidator.consolidate() + assert json.loads((cfg.memory_dir / "meta.json").read_text()) == {"consolidated_through": "2025-03-01"} + + +# ──────────────────────────────────────────────────────────────────── +# Background schedule +# ──────────────────────────────────────────────────────────────────── + +class TestSchedule: + @pytest.mark.asyncio + async def test_at_most_one_runs_at_a_time(self, consolidator): + release = asyncio.Event() + + async def slow(**kwargs): + await release.wait() + return True + + consolidator.consolidate = AsyncMock(side_effect=slow) + consolidator.schedule() + await asyncio.sleep(0) + consolidator.schedule() # one already running: no second one + release.set() + await consolidator._task + assert consolidator.consolidate.await_count == 1 + + @pytest.mark.asyncio + async def test_failure_is_logged_and_not_retried_for_an_hour(self, consolidator): + consolidator.consolidate = AsyncMock(side_effect=RuntimeError("bad model")) + consolidator.schedule() + await consolidator._task # does not raise + consolidator.schedule() + await consolidator._task + assert consolidator.consolidate.await_count == 1 + assert 3590 < consolidator._retry_at - time.monotonic() <= 3600 + + consolidator._retry_at = time.monotonic() - 1 # the hour has passed + consolidator.schedule() + await consolidator._task + assert consolidator.consolidate.await_count == 2 + + @pytest.mark.asyncio + async def test_aclose_cancels_a_running_consolidation(self, consolidator): + async def forever(**kwargs): + await asyncio.sleep(60) + + consolidator.consolidate = AsyncMock(side_effect=forever) + consolidator.schedule() + await asyncio.sleep(0) + task = consolidator._task + await consolidator.aclose() + assert task.cancelled() + + @pytest.mark.asyncio + async def test_cancel_stops_without_waiting(self, consolidator): + async def forever(**kwargs): + await asyncio.sleep(60) + + consolidator.consolidate = AsyncMock(side_effect=forever) + consolidator.schedule() + await asyncio.sleep(0) + task = consolidator._task + consolidator.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert task.cancelled() + + @pytest.mark.asyncio + async def test_aclose_without_a_run_is_a_no_op(self, consolidator): + await consolidator.aclose() + consolidator.cancel() diff --git a/tests/test_agent.py b/tests/test_agent.py index e887189..0b376f4 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -1,4 +1,7 @@ -"""Tests for MemclawAgent — sessions, consolidation, context, sync, fs guardrail. +"""Tests for MemclawAgent — sessions, context, sync, fs guardrail. + +MEMORY.md consolidation itself is tested in tests/memory/test_consolidation.py; +here only that the agent schedules and stops it. These tests run against a backend-agnostic `FakeBackend` so they exercise the orchestration in `MemclawAgent` without depending on any SDK. Per-backend @@ -9,7 +12,6 @@ import asyncio import json -from datetime import date from pathlib import Path from typing import Any from unittest.mock import AsyncMock @@ -91,7 +93,7 @@ def _chat_agent(cfg: MemclawConfig, backend: FakeBackend, platform: str | None = """An agent ready for handle(): no search, no consolidation.""" agent = _make_agent(cfg, backend, platform) agent.search.search = AsyncMock(return_value=[]) - agent._maybe_consolidate = AsyncMock(return_value=False) + agent.consolidator.consolidate = AsyncMock(return_value=False) return agent @@ -368,22 +370,22 @@ async def slow_consolidate(**kwargs): await release.wait() return True - agent._maybe_consolidate = AsyncMock(side_effect=slow_consolidate) + agent.consolidator.consolidate = AsyncMock(side_effect=slow_consolidate) await agent.handle("hi") # returns while consolidation is still pending await asyncio.wait_for(started.wait(), 1) await agent.handle("again") # one already running: no second one release.set() - await agent._consolidation_task - assert agent._maybe_consolidate.await_count == 1 + await agent.consolidator._task + assert agent.consolidator.consolidate.await_count == 1 agent.close() @pytest.mark.asyncio async def test_failure_is_logged_not_raised(self, cfg: MemclawConfig, fake_backend: FakeBackend): agent = _chat_agent(cfg, fake_backend) - agent._maybe_consolidate = AsyncMock(side_effect=RuntimeError("API down")) + agent.consolidator.consolidate = AsyncMock(side_effect=RuntimeError("API down")) reply, _ = await agent.handle("hi") - await agent._consolidation_task # does not raise + await agent.consolidator._task # does not raise assert reply agent.close() @@ -395,143 +397,14 @@ async def test_aclose_cancels_a_running_consolidation( async def forever(**kwargs): await asyncio.sleep(60) - agent._maybe_consolidate = AsyncMock(side_effect=forever) + agent.consolidator.consolidate = AsyncMock(side_effect=forever) await agent.handle("hi") await asyncio.sleep(0) - task = agent._consolidation_task + task = agent.consolidator._task await agent.aclose() assert task.cancelled() -# ──────────────────────────────────────────────────────────────────── -# Spec #2: Memory Consolidation -# ──────────────────────────────────────────────────────────────────── - -class TestConsolidation: - @pytest.mark.asyncio - async def test_skips_when_below_threshold(self, cfg: MemclawConfig, fake_backend: FakeBackend): - """Consolidation should not run when file count < threshold.""" - cfg.memory.consolidation_threshold = 7 - agent = _make_agent(cfg, fake_backend) - - # Create 3 daily files (below threshold of 7) - for i in range(3): - d = date(2025, 3, i + 1) - path = cfg.memory_subdir / f"{d.isoformat()}.md" - path.write_text(f"# Day {i}\nSome content") - - result = await agent._maybe_consolidate() - assert result is False - assert fake_backend.one_shot_calls == [] - agent.close() - - @pytest.mark.asyncio - async def test_runs_when_above_threshold(self, cfg: MemclawConfig, fake_backend: FakeBackend): - """Consolidation should run when file count >= threshold.""" - cfg.memory.consolidation_threshold = 3 - fake_backend.one_shot_response = "## Key Facts\n\n- Fact 0\n- Fact 1\n" - agent = _make_agent(cfg, fake_backend) - - # Create 5 daily files (above threshold of 3) - for i in range(5): - d = date(2025, 3, i + 1) - path = cfg.memory_subdir / f"{d.isoformat()}.md" - path.write_text(f"# Day {i}\nImportant fact {i}") - - agent.index.index_file = AsyncMock() - - result = await agent._maybe_consolidate() - - assert result is True - assert cfg.memory_file.exists() - assert "Key Facts" in cfg.memory_file.read_text() - - meta_path = cfg.memory_dir / "meta.json" - assert meta_path.exists() - meta = json.loads(meta_path.read_text()) - assert meta["consolidated_through"] == "2025-03-05" - - agent.close() - - @pytest.mark.asyncio - async def test_force_ignores_threshold(self, cfg: MemclawConfig, fake_backend: FakeBackend): - """force=True should run consolidation even with 1 file.""" - cfg.memory.consolidation_threshold = 100 - fake_backend.one_shot_response = "## Notes\n- One note" - agent = _make_agent(cfg, fake_backend) - - path = cfg.memory_subdir / "2025-03-01.md" - path.write_text("# Single day\nJust one note") - - agent.index.index_file = AsyncMock() - - result = await agent._maybe_consolidate(force=True) - - assert result is True - agent.close() - - @pytest.mark.asyncio - async def test_consolidated_through_override(self, cfg: MemclawConfig, fake_backend: FakeBackend): - """consolidated_through_override should override meta.json.""" - fake_backend.one_shot_response = "## Consolidated" - agent = _make_agent(cfg, fake_backend) - - for i in range(1, 11): - d = date(2025, 3, i) - path = cfg.memory_subdir / f"{d.isoformat()}.md" - path.write_text(f"Content for day {i}") - - meta_path = cfg.memory_dir / "meta.json" - meta_path.write_text(json.dumps({"consolidated_through": "2025-03-01"})) - - agent.index.index_file = AsyncMock() - - result = await agent._maybe_consolidate( - force=True, - consolidated_through_override=date(2025, 3, 8), - ) - - assert result is True - # The user message passed to the backend should cover days > 2025-03-08. - user_msg = fake_backend.one_shot_calls[-1]["user"] - assert "2025-03-09" in user_msg - assert "2025-03-10" in user_msg - assert "2025-03-05" not in user_msg - - agent.close() - - @pytest.mark.asyncio - async def test_no_files_returns_false(self, cfg: MemclawConfig, fake_backend: FakeBackend): - """If there are no daily files at all, return False.""" - agent = _make_agent(cfg, fake_backend) - result = await agent._maybe_consolidate(force=True) - assert result is False - assert fake_backend.one_shot_calls == [] - agent.close() - - @pytest.mark.asyncio - async def test_content_limit(self, cfg: MemclawConfig, fake_backend: FakeBackend): - """Content gathering should stop at the consolidation budget.""" - from memclaw.agent import _CONSOLIDATION_BUDGET_CHARS as budget - - fake_backend.one_shot_response = "## Consolidated" - agent = _make_agent(cfg, fake_backend) - - for i in range(1, 6): - d = date(2025, 3, i) - path = cfg.memory_subdir / f"{d.isoformat()}.md" - path.write_text("x" * (budget // 3)) - - agent.index.index_file = AsyncMock() - - await agent._maybe_consolidate(force=True) - - user_msg = fake_backend.one_shot_calls[-1]["user"] - assert len(user_msg) < budget + 5000 - - agent.close() - - # ──────────────────────────────────────────────────────────────────── # Spec #3: MEMORY.md in the system prompt # ──────────────────────────────────────────────────────────────────── @@ -725,135 +598,6 @@ def test_tool_definitions_contain_all_tools(self): assert len(names) == len(expected) -# ──────────────────────────────────────────────────────────────────── -# Consolidation edge cases -# ──────────────────────────────────────────────────────────────────── - -def _daily(cfg: MemclawConfig, d: date, text: str) -> Path: - path = cfg.daily_file(d) - path.write_text(text) - return path - - -def _consolidated_through(cfg: MemclawConfig) -> str: - return json.loads((cfg.memory_dir / "meta.json").read_text())["consolidated_through"] - - -class TestConsolidationSafety: - @pytest.mark.asyncio - async def test_todays_file_is_left_for_later(self, cfg: MemclawConfig, fake_backend: FakeBackend): - from datetime import timedelta - - fake_backend.one_shot_response = "## Facts\n- x" - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date.today() - timedelta(days=1), "yesterday's note") - _daily(cfg, date.today(), "today's note") - - assert await agent._maybe_consolidate(force=True) - assert "today's note" not in fake_backend.one_shot_calls[0]["user"] - assert _consolidated_through(cfg) == (date.today() - timedelta(days=1)).isoformat() - agent.close() - - @pytest.mark.asyncio - async def test_only_today_means_nothing_to_do(self, cfg: MemclawConfig, fake_backend: FakeBackend): - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date.today(), "today's note") - assert await agent._maybe_consolidate(force=True) is False - assert fake_backend.one_shot_calls == [] - agent.close() - - @pytest.mark.asyncio - async def test_files_past_the_budget_stay_unconsolidated(self, cfg: MemclawConfig, fake_backend: FakeBackend): - fake_backend.one_shot_response = "## Facts\n- x" - agent = _make_agent(cfg, fake_backend) - from memclaw.agent import _CONSOLIDATION_BUDGET_CHARS as budget - - for day in range(1, 6): - _daily(cfg, date(2025, 3, day), f"day {day} " + "x" * (budget // 3)) - - assert await agent._maybe_consolidate(force=True) - user_msg = fake_backend.one_shot_calls[0]["user"] - assert "day 2 " in user_msg and "day 3 " not in user_msg - assert _consolidated_through(cfg) == "2025-03-02" - - # The next run picks up where this one stopped. - assert await agent._maybe_consolidate(force=True) - assert "day 3 " in fake_backend.one_shot_calls[1]["user"] - agent.close() - - @pytest.mark.asyncio - async def test_single_oversized_file_is_truncated_not_stuck(self, cfg: MemclawConfig, fake_backend: FakeBackend): - from memclaw.agent import _CONSOLIDATION_BUDGET_CHARS as budget - - fake_backend.one_shot_response = "## Facts\n- x" - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date(2025, 3, 1), "y" * (budget + 20000)) - assert await agent._maybe_consolidate(force=True) - assert _consolidated_through(cfg) == "2025-03-01" - agent.close() - - @pytest.mark.asyncio - async def test_save_during_consolidation_is_kept(self, cfg: MemclawConfig, fake_backend: FakeBackend): - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date(2025, 3, 1), "note") - - async def one_shot(**kwargs): - with open(cfg.memory_file, "a") as f: # appended by hand meanwhile - f.write("- Blood type 0 negative\n") - return "## Facts\n- consolidated" - - fake_backend.run_one_shot = one_shot - assert await agent._maybe_consolidate(force=True) - memory = cfg.memory_file.read_text() - assert memory.startswith("## Facts\n- consolidated") - assert "Blood type 0 negative" in memory - history = list((cfg.memory_dir / ".history").glob("MEMORY-*.md")) - assert [h.read_text() for h in history] == ["# Personal Memory\n"] - agent.close() - - @pytest.mark.asyncio - async def test_manual_edit_during_consolidation_aborts(self, cfg: MemclawConfig, fake_backend: FakeBackend): - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date(2025, 3, 1), "note") - - async def one_shot(**kwargs): - cfg.memory_file.write_text("# Edited by hand\n") - return "## Facts\n- consolidated" - - fake_backend.run_one_shot = one_shot - assert await agent._maybe_consolidate(force=True) is False - assert cfg.memory_file.read_text() == "# Edited by hand\n" - assert not (cfg.memory_dir / "meta.json").exists() - agent.close() - - @pytest.mark.asyncio - async def test_failed_backend_call_leaves_memory_untouched( - self, cfg: MemclawConfig, fake_backend: FakeBackend, - ): - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date(2025, 3, 1), "note") - before = cfg.memory_file.read_text() - - async def one_shot(**kwargs): - raise RuntimeError("Claude one-shot failed (unknown): API Error: Connection refused") - - fake_backend.run_one_shot = one_shot - with pytest.raises(RuntimeError): - await agent._maybe_consolidate(force=True) - assert cfg.memory_file.read_text() == before - assert not (cfg.memory_dir / "meta.json").exists() - agent.close() - - @pytest.mark.asyncio - async def test_code_fence_is_stripped(self, cfg: MemclawConfig, fake_backend: FakeBackend): - fake_backend.one_shot_response = "```markdown\n## Facts\n- x\n```" - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date(2025, 3, 1), "note") - assert await agent._maybe_consolidate(force=True) - assert cfg.memory_file.read_text() == "## Facts\n- x\n" - agent.close() - - # ──────────────────────────────────────────────────────────────────── # Resilience and concurrency # ──────────────────────────────────────────────────────────────────── @@ -865,7 +609,7 @@ async def test_context_search_failure_does_not_fail_the_turn( ): fake_backend.turn_response = TurnResult(text="hi") agent = _make_agent(cfg, fake_backend) - agent._maybe_consolidate = AsyncMock(return_value=False) + agent.consolidator.consolidate = AsyncMock(return_value=False) agent.search.search = AsyncMock(side_effect=RuntimeError("OpenAI down")) reply, _ = await agent.handle("hello") assert reply == "hi" @@ -990,68 +734,7 @@ async def test_a_permanent_flag_from_an_old_session_is_ignored(self, cfg: Memcla assert "Daisy Disk serial ABC-123" in cfg.daily_file().read_text() agent.close() - @pytest.mark.asyncio - async def test_by_default_consolidation_runs_once_a_day_has_passed(self, cfg: MemclawConfig, fake_backend: FakeBackend): - from datetime import timedelta - - fake_backend.one_shot_response = "# Personal Memory\n- x" - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date.today(), "today") - assert await agent._maybe_consolidate() is False # today isn't over - _daily(cfg, date.today() - timedelta(days=1), "yesterday") - assert await agent._maybe_consolidate() is True - agent.close() - - @pytest.mark.asyncio - async def test_history_keeps_the_last_60(self, cfg: MemclawConfig, fake_backend: FakeBackend): - history = cfg.memory_dir / ".history" - history.mkdir() - for i in range(65): - (history / f"MEMORY-2025-01-01-{i:06d}.md").write_text(str(i)) - agent = _make_agent(cfg, fake_backend) - agent._save_history("latest") - kept = sorted(history.glob("MEMORY-*.md")) - assert len(kept) == 60 - assert kept[-1].read_text() == "latest" - assert not (history / "MEMORY-2025-01-01-000000.md").exists() - agent.close() - - @pytest.mark.asyncio - async def test_consolidation_is_told_todays_date(self, cfg: MemclawConfig, fake_backend: FakeBackend): - fake_backend.one_shot_response = "# Personal Memory" - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date(2025, 3, 1), "note") - await agent._maybe_consolidate(force=True) - assert f"Today's date: {date.today().isoformat()}" in fake_backend.one_shot_calls[0]["user"] - agent.close() - - -class TestConsolidationReferences: - @pytest.mark.asyncio - async def test_other_notes_are_listed_for_the_index(self, cfg: MemclawConfig, fake_backend: FakeBackend): - fake_backend.one_shot_response = "# Personal Memory" - agent = _make_agent(cfg, fake_backend) - (cfg.memory_dir / "todos.md").write_text("# Todos\n- renew passport") - _daily(cfg, date(2025, 3, 1), "note") - await agent._maybe_consolidate(force=True) - user_msg = fake_backend.one_shot_calls[0]["user"] - assert "## Other Notes" in user_msg - assert "- todos.md (" in user_msg and "Todos" in user_msg - assert "AGENTS.md" not in user_msg.split("## Other Notes")[1] - agent.close() - - @pytest.mark.asyncio - async def test_references_to_missing_notes_are_dropped(self, cfg: MemclawConfig, fake_backend: FakeBackend): - fake_backend.one_shot_response = ( - "# Personal Memory\n\n## Index\n" - "- Lion8 login → memory/2025-03-01.md, memory/2024-01-01.md\n" - ) - agent = _make_agent(cfg, fake_backend) - _daily(cfg, date(2025, 3, 1), "Lion8 login: admin") - await agent._maybe_consolidate(force=True) - assert "- Lion8 login → memory/2025-03-01.md\n" in cfg.memory_file.read_text() - agent.close() - +class TestSystemPromptReferences: def test_system_prompt_explains_references(self): from memclaw.agent import _SYSTEM_PROMPT_TEMPLATE @@ -1074,19 +757,6 @@ async def test_file_write_cannot_replace_memory_or_daily_notes( assert read == before agent.close() - @pytest.mark.asyncio - async def test_failed_consolidation_is_not_retried_after_every_reply( - self, cfg: MemclawConfig, fake_backend: FakeBackend, - ): - agent = _chat_agent(cfg, fake_backend) - agent._maybe_consolidate = AsyncMock(side_effect=RuntimeError("bad model")) - await agent.handle("one") - await agent._consolidation_task - await agent.handle("two") - await agent._consolidation_task - assert agent._maybe_consolidate.await_count == 1 - agent.close() - @pytest.mark.asyncio async def test_image_save_writes_nothing_when_the_embedding_fails( self, cfg: MemclawConfig, fake_backend: FakeBackend, From 4756094eb5a046ef78ad90b414106b32092b2443 Mon Sep 17 00:00:00 2001 From: Emanuilo Jovanovic Date: Sun, 22 Nov 2026 17:38:46 +0100 Subject: [PATCH 2/2] refactor(agent): the system prompt moves to memclaw/instructions.py - instructions.py holds what a session is started with: the system-prompt template, loading AGENTS.md and MEMORY.md for it (with the 20,000-char cap), the content hash and instructions_fingerprint. agent.py keeps turn handling: the context block, handle() and the session bookkeeping (348 lines, was 699 before the consolidation move; MemclawAgent is under the 300-line class limit). - memory_refs.py becomes memclaw/memory/refs.py, next to consolidation, its only user. That keeps the top-level folder at 13 modules while instructions.py is added. Guards: instructions joins the core layer; memory.refs joins the modules only memclaw.memory may import. Baseline tightened (MemclawAgent class length, _handle's locals 19 -> 18). Same template text, fingerprint, truncation and session hashes, so saved sessions resume as before. Tests: tests/test_instructions.py (was part of test_agent.py), tests/memory/test_refs.py (was test_memory_refs.py). --- .code-shape/baseline.json | 3 +- docs/memory-architecture.md | 4 +- memclaw/agent.py | 105 +++--------------- memclaw/instructions.py | 102 +++++++++++++++++ memclaw/memory/__init__.py | 4 +- memclaw/memory/consolidation.py | 2 +- memclaw/{memory_refs.py => memory/refs.py} | 0 pyproject.toml | 4 +- tests/e2e/test_agent_e2e.py | 2 +- .../test_refs.py} | 2 +- tests/test_agent.py | 33 ------ tests/test_instructions.py | 66 +++++++++++ 12 files changed, 193 insertions(+), 134 deletions(-) create mode 100644 memclaw/instructions.py rename memclaw/{memory_refs.py => memory/refs.py} (100%) rename tests/{test_memory_refs.py => memory/test_refs.py} (97%) create mode 100644 tests/test_instructions.py diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index e5b548e..249d985 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -18,7 +18,7 @@ "pylint": { "class-attributes|memclaw/agent.py|MemclawAgent": 17, "class-attributes|memclaw/backends/cursor.py|CursorAgentBackend": 13, - "too-many-locals|memclaw/agent.py|MemclawAgent._handle": 19, + "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, @@ -38,7 +38,6 @@ "too-many-positional|memclaw/tools.py|ToolExecutor.__init__": 7 }, "sizes": { - "class-lines|memclaw/agent.py|MemclawAgent": 303, "class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 501, "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419, "class-lines|memclaw/index.py|MemoryIndex": 419, diff --git a/docs/memory-architecture.md b/docs/memory-architecture.md index fdf2daa..aa98b6b 100644 --- a/docs/memory-architecture.md +++ b/docs/memory-architecture.md @@ -42,6 +42,8 @@ The system prompt is **static for a session**, so the backend can prompt-cache i 2. Reply-formatting rules and a description of the per-message context block. 3. **MEMORY.md** — your permanent memory (see Permanent Memory in the Prompt below). +The template, and the fingerprint described above, are in `memclaw/instructions.py`. + Everything that changes per turn goes at the **top of the user message**, in a compact `` block: - The current local date and time (used for dates and reminders). @@ -121,7 +123,7 @@ Today's file is never consolidated: it is still being written to, and marking it - existing facts and references stay unless updated or expired; - left out entirely: expired one-offs (verification codes, past events, finished trips' bookings), links saved to read later (they stay searchable), instructions for the assistant (they belong in AGENTS.md), small talk. - A wrapping ```` ``` ```` fence in the reply is stripped, and every reference is checked: one to a note that doesn't exist is dropped, one whose note shares no word with the line is logged as unconfirmed. + A wrapping ```` ``` ```` fence in the reply is stripped, and every reference is checked: one to a note that doesn't exist is dropped, one whose note shares no word with the line is logged as unconfirmed (`memclaw/memory/refs.py`). 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. diff --git a/memclaw/agent.py b/memclaw/agent.py index 48fa9ae..6ec5e97 100644 --- a/memclaw/agent.py +++ b/memclaw/agent.py @@ -15,7 +15,6 @@ from __future__ import annotations import asyncio -import hashlib import time from datetime import datetime from pathlib import Path @@ -26,6 +25,13 @@ 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 .reminders import ReminderScheduler from .search import HybridSearch @@ -33,53 +39,6 @@ from .store import MemoryStore from .tools import ToolExecutor -# ── Prompts ────────────────────────────────────────────────────────── - -# Static for the whole session. Changing this template changes the session -# fingerprint, so existing sessions start fresh instead of being resumed. -_SYSTEM_PROMPT_TEMPLATE = """\ -{agent_instructions} - -=== REPLY FORMATTING === -Replies are delivered to messaging apps with limited markdown support. Use \ -ONLY this minimal syntax — anything else leaks as literal characters: -- Bold: `*bold*` (single asterisk). NEVER use `**double asterisks**`. -- Italic: `_italic_`. -- Bullet lists: plain `- item` on its own line. -- Paragraphs: separate with a blank line. -- Headings (`#`, `##`, ...) are NOT supported — use a bold line on its own \ -(e.g. `*Section name*`) followed by a blank line instead. -- No backticks or fenced code blocks. -- No `[label](url)` links — write the bare URL. - -=== PER-MESSAGE CONTEXT === -Each user message starts with a block added by Memclaw, not typed \ -by the user. It holds the current local time (use it for dates and \ -reminders), memories that may be relevant to that message, reminders that \ -were delivered to the user since their last message, and the new content of \ -AGENTS.md or MEMORY.md when either file changes — such an update supersedes \ -the version in this system prompt and any earlier update. Don't mention the \ -block itself to the user. - -=== PERMANENT MEMORY (MEMORY.md) === -An overview of the user. Lines ending in "→ memory/2026-04-18.md" (or \ -another file) point to the notes holding the details: when the user needs \ -a detail — an exact value, a number, instructions — open the note with \ -file_read and answer from it, rather than from the summary. memory_search \ -finds anything else. - -{permanent_memory} - -IMPORTANT: When the user gives you a behavioural instruction (e.g. "always respond \ -in Spanish", "be more formal", "never use emojis"), you MUST call the \ -update_instructions tool to save it. These are rules you should follow in every \ -future conversation. -""" - -# Consolidation aims for ~6,000 characters of MEMORY.md; -# this cap only guards against a runaway file. -_MEMORY_PROMPT_CHARS = 20000 - # Per-turn memory search results. Kept small because every context block # stays in the session transcript. _CONTEXT_RESULTS = 5 @@ -89,37 +48,6 @@ _CLI_SESSION_KEY = "cli" -def _load_agent_instructions(config: MemclawConfig) -> str: - agent_file = config.agent_file - if agent_file.exists(): - return agent_file.read_text().strip() - return "You are Memclaw, a personal memory assistant." - - -def _load_permanent_memory(config: MemclawConfig) -> str: - memory = config.memory_file.read_text().strip() if config.memory_file.exists() else "" - if not memory: - return "(empty)" - if len(memory) > _MEMORY_PROMPT_CHARS: - return memory[:_MEMORY_PROMPT_CHARS] + "\n\n[... truncated; use memory_search for more]" - return memory - - -def _hash(text: str) -> str: - return hashlib.sha256(text.encode()).hexdigest()[:16] - - -def instructions_fingerprint(backend_name: str) -> str: - """Hash of the code-level instructions a session is started with. - - Claude Code keeps a session's original system prompt when it is resumed, - so a session started under a different template (or backend) must not be - resumed. AGENTS.md / MEMORY.md are tracked separately per session and - sent as updates instead, so editing them doesn't reset conversations. - """ - return _hash(f"{backend_name}\0{_SYSTEM_PROMPT_TEMPLATE}") - - class MemclawAgent: """Unified agent for both interactive CLI and messaging bots. @@ -311,10 +239,10 @@ async def _handle( key = self._session_key(chat_id) generation = self._generations.get(key, 0) - agent_instructions = _load_agent_instructions(self.config) - permanent_memory = _load_permanent_memory(self.config) - agents_hash = _hash(agent_instructions) - memory_hash = _hash(permanent_memory) + 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. @@ -333,15 +261,10 @@ async def _handle( ), ) - # Only used when the backend starts a new session. - system_prompt = _SYSTEM_PROMPT_TEMPLATE.format( - agent_instructions=agent_instructions, - permanent_memory=permanent_memory, - ) - t0 = time.perf_counter() result = await self.backend.run_turn( - system_prompt=system_prompt, + # 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, @@ -359,7 +282,7 @@ 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 = _hash(_load_agent_instructions(self.config)) + 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) diff --git a/memclaw/instructions.py b/memclaw/instructions.py new file mode 100644 index 0000000..e9bb655 --- /dev/null +++ b/memclaw/instructions.py @@ -0,0 +1,102 @@ +"""What a chat session is started with: the system prompt, and the +fingerprint that tells whether a saved session may be resumed. + +The system prompt is AGENTS.md, Memclaw's fixed rules (reply formatting, the +per-message context block, how to read MEMORY.md's references) and +MEMORY.md. It is static for a session, so the backend can prompt-cache it; +when AGENTS.md or MEMORY.md change later, the agent sends the new content in +the next message's context block instead (see `memclaw.agent`). +""" + +from __future__ import annotations + +import hashlib + +from .config import MemclawConfig + +# Static for the whole session. Changing this template changes the session +# fingerprint, so existing sessions start fresh instead of being resumed. +_SYSTEM_PROMPT_TEMPLATE = """\ +{agent_instructions} + +=== REPLY FORMATTING === +Replies are delivered to messaging apps with limited markdown support. Use \ +ONLY this minimal syntax — anything else leaks as literal characters: +- Bold: `*bold*` (single asterisk). NEVER use `**double asterisks**`. +- Italic: `_italic_`. +- Bullet lists: plain `- item` on its own line. +- Paragraphs: separate with a blank line. +- Headings (`#`, `##`, ...) are NOT supported — use a bold line on its own \ +(e.g. `*Section name*`) followed by a blank line instead. +- No backticks or fenced code blocks. +- No `[label](url)` links — write the bare URL. + +=== PER-MESSAGE CONTEXT === +Each user message starts with a block added by Memclaw, not typed \ +by the user. It holds the current local time (use it for dates and \ +reminders), memories that may be relevant to that message, reminders that \ +were delivered to the user since their last message, and the new content of \ +AGENTS.md or MEMORY.md when either file changes — such an update supersedes \ +the version in this system prompt and any earlier update. Don't mention the \ +block itself to the user. + +=== PERMANENT MEMORY (MEMORY.md) === +An overview of the user. Lines ending in "→ memory/2026-04-18.md" (or \ +another file) point to the notes holding the details: when the user needs \ +a detail — an exact value, a number, instructions — open the note with \ +file_read and answer from it, rather than from the summary. memory_search \ +finds anything else. + +{permanent_memory} + +IMPORTANT: When the user gives you a behavioural instruction (e.g. "always respond \ +in Spanish", "be more formal", "never use emojis"), you MUST call the \ +update_instructions tool to save it. These are rules you should follow in every \ +future conversation. +""" + +# Consolidation aims for ~6,000 characters of MEMORY.md; +# this cap only guards against a runaway file. +_MEMORY_PROMPT_CHARS = 20000 + + +def load_agent_instructions(config: MemclawConfig) -> str: + """AGENTS.md, the user's behavioural instructions (or a default).""" + agent_file = config.agent_file + if agent_file.exists(): + return agent_file.read_text().strip() + return "You are Memclaw, a personal memory assistant." + + +def load_permanent_memory(config: MemclawConfig) -> str: + """MEMORY.md as it goes into the prompt: "(empty)" when there is none, + cut at `_MEMORY_PROMPT_CHARS`.""" + memory = config.memory_file.read_text().strip() if config.memory_file.exists() else "" + if not memory: + return "(empty)" + if len(memory) > _MEMORY_PROMPT_CHARS: + return memory[:_MEMORY_PROMPT_CHARS] + "\n\n[... truncated; use memory_search for more]" + return memory + + +def build_system_prompt(agent_instructions: str, permanent_memory: str) -> str: + return _SYSTEM_PROMPT_TEMPLATE.format( + agent_instructions=agent_instructions, + permanent_memory=permanent_memory, + ) + + +def content_hash(text: str) -> str: + """Short hash of a file's content, to tell whether a session has seen it.""" + return hashlib.sha256(text.encode()).hexdigest()[:16] + + +def instructions_fingerprint(backend_name: str) -> str: + """Hash of the code-level instructions a session is started with. + + Claude Code keeps a session's original system prompt when it is resumed, + so a session started under a different template (or backend) must not be + resumed. AGENTS.md / MEMORY.md are tracked separately per session and + sent as updates instead, so editing them doesn't reset conversations. + """ + return content_hash(f"{backend_name}\0{_SYSTEM_PROMPT_TEMPLATE}") diff --git a/memclaw/memory/__init__.py b/memclaw/memory/__init__.py index 95e8fca..db76517 100644 --- a/memclaw/memory/__init__.py +++ b/memclaw/memory/__init__.py @@ -1,8 +1,8 @@ """Memclaw's memory subsystem. Public: `Consolidator`, which distills the daily notes into MEMORY.md (and -is the only code that writes it). Other code imports from `memclaw.memory`, -not from the modules inside. +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 diff --git a/memclaw/memory/consolidation.py b/memclaw/memory/consolidation.py index 45b1509..4f5e3d3 100644 --- a/memclaw/memory/consolidation.py +++ b/memclaw/memory/consolidation.py @@ -25,7 +25,7 @@ from ..config import MemclawConfig from ..index import MemoryIndex from ..store import MemoryStore -from ..memory_refs import check_references +from .refs import check_references # After a failed consolidation, wait this long before trying again rather # than retrying after every reply. diff --git a/memclaw/memory_refs.py b/memclaw/memory/refs.py similarity index 100% rename from memclaw/memory_refs.py rename to memclaw/memory/refs.py diff --git a/pyproject.toml b/pyproject.toml index 6124a6b..b2acc07 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -183,7 +183,7 @@ layers = [ # through the backend the agent hands it, so it doesn't import backends. "memory", # Independent building blocks (`|`: they don't import each other). - "search | store | reminders | sessions | memory_refs | prompts", + "search | store | reminders | sessions | prompts | instructions", # SQLite + embeddings index, used by search. "index", # The OpenAI adapter (embeddings, transcription, chat), used by index and bot. @@ -245,7 +245,7 @@ allowed_importers = ["memclaw.openai_client"] id = "memory-via-package" name = "Only memclaw.memory imports its own modules: everyone else uses what memclaw.memory exports (e.g. Consolidator)" type = "protected" -protected_modules = ["memclaw.memory.consolidation"] +protected_modules = ["memclaw.memory.consolidation", "memclaw.memory.refs"] allowed_importers = ["memclaw.memory"] [[tool.importlinter.contracts]] diff --git a/tests/e2e/test_agent_e2e.py b/tests/e2e/test_agent_e2e.py index fabe90f..eebe36c 100644 --- a/tests/e2e/test_agent_e2e.py +++ b/tests/e2e/test_agent_e2e.py @@ -10,7 +10,7 @@ import pytest from memclaw.agent import MemclawAgent -from memclaw.memory_refs import check_references +from memclaw.memory.refs import check_references from memclaw.openai_client import OpenAIClient from .conftest import days_ago, write_daily diff --git a/tests/test_memory_refs.py b/tests/memory/test_refs.py similarity index 97% rename from tests/test_memory_refs.py rename to tests/memory/test_refs.py index f0e0b1d..8fe97a3 100644 --- a/tests/test_memory_refs.py +++ b/tests/memory/test_refs.py @@ -3,7 +3,7 @@ from pathlib import Path -from memclaw.memory_refs import check_references +from memclaw.memory.refs import check_references def _vault(tmp_path: Path) -> Path: diff --git a/tests/test_agent.py b/tests/test_agent.py index 0b376f4..f68bb15 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -405,32 +405,6 @@ async def forever(**kwargs): assert task.cancelled() -# ──────────────────────────────────────────────────────────────────── -# Spec #3: MEMORY.md in the system prompt -# ──────────────────────────────────────────────────────────────────── - -class TestPermanentMemoryPrompt: - def test_small_memory_included_in_full(self, cfg: MemclawConfig): - from memclaw.agent import _load_permanent_memory - - cfg.memory_file.write_text("## Key Facts\n\n- I like Python") - assert _load_permanent_memory(cfg) == "## Key Facts\n\n- I like Python" - - def test_runaway_memory_is_truncated(self, cfg: MemclawConfig): - from memclaw.agent import _MEMORY_PROMPT_CHARS, _load_permanent_memory - - cfg.memory_file.write_text("x" * (_MEMORY_PROMPT_CHARS + 100)) - text = _load_permanent_memory(cfg) - assert len(text) < _MEMORY_PROMPT_CHARS + 100 - assert "truncated" in text - - def test_empty_memory(self, cfg: MemclawConfig): - from memclaw.agent import _load_permanent_memory - - cfg.memory_file.write_text("") - assert _load_permanent_memory(cfg) == "(empty)" - - # ──────────────────────────────────────────────────────────────────── # Spec #9: Startup and Background Sync # ──────────────────────────────────────────────────────────────────── @@ -734,13 +708,6 @@ async def test_a_permanent_flag_from_an_old_session_is_ignored(self, cfg: Memcla assert "Daisy Disk serial ABC-123" in cfg.daily_file().read_text() agent.close() -class TestSystemPromptReferences: - def test_system_prompt_explains_references(self): - from memclaw.agent import _SYSTEM_PROMPT_TEMPLATE - - assert "file_read" in _SYSTEM_PROMPT_TEMPLATE and "→ memory/" in _SYSTEM_PROMPT_TEMPLATE - - class TestReviewFixes: @pytest.mark.asyncio @pytest.mark.parametrize("target", ["MEMORY.md", "memory/2026-10-15.md"]) diff --git a/tests/test_instructions.py b/tests/test_instructions.py new file mode 100644 index 0000000..5e685bd --- /dev/null +++ b/tests/test_instructions.py @@ -0,0 +1,66 @@ +"""Tests for the system prompt a session starts with, and its fingerprint.""" +from __future__ import annotations + +from pathlib import Path + +import pytest + +from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings +from memclaw.instructions import ( + _MEMORY_PROMPT_CHARS, + _SYSTEM_PROMPT_TEMPLATE, + build_system_prompt, + instructions_fingerprint, + load_agent_instructions, + load_permanent_memory, +) + + +@pytest.fixture +def cfg(tmp_path: Path) -> MemclawConfig: + return MemclawConfig( + memory_dir=tmp_path / "m", + openai=OpenAISettings(api_key="test-openai-key"), + claude=ClaudeSettings(api_key="test-anthropic-key"), + ) + + +class TestPermanentMemoryPrompt: + def test_small_memory_included_in_full(self, cfg: MemclawConfig): + cfg.memory_file.write_text("## Key Facts\n\n- I like Python") + assert load_permanent_memory(cfg) == "## Key Facts\n\n- I like Python" + + def test_runaway_memory_is_truncated(self, cfg: MemclawConfig): + cfg.memory_file.write_text("x" * (_MEMORY_PROMPT_CHARS + 100)) + text = load_permanent_memory(cfg) + assert len(text) < _MEMORY_PROMPT_CHARS + 100 + assert "truncated" in text + + def test_empty_memory(self, cfg: MemclawConfig): + cfg.memory_file.write_text("") + assert load_permanent_memory(cfg) == "(empty)" + + +class TestAgentInstructions: + def test_agents_md_is_used(self, cfg: MemclawConfig): + cfg.agent_file.write_text(" You are Test.\n") + assert load_agent_instructions(cfg) == "You are Test." + + def test_default_without_agents_md(self, cfg: MemclawConfig): + cfg.agent_file.unlink(missing_ok=True) + assert load_agent_instructions(cfg) == "You are Memclaw, a personal memory assistant." + + +class TestSystemPrompt: + def test_holds_instructions_then_memory(self): + prompt = build_system_prompt("You are Test.", "- likes tea") + assert prompt.startswith("You are Test.\n\n=== REPLY FORMATTING ===") + assert prompt.index("=== PERMANENT MEMORY (MEMORY.md) ===") < prompt.index("- likes tea") + + def test_explains_references(self): + assert "file_read" in _SYSTEM_PROMPT_TEMPLATE and "→ memory/" in _SYSTEM_PROMPT_TEMPLATE + + def test_fingerprint_is_per_backend_and_stable(self): + assert instructions_fingerprint("claude") == instructions_fingerprint("claude") + assert instructions_fingerprint("claude") != instructions_fingerprint("cursor") + assert len(instructions_fingerprint("claude")) == 16