diff --git a/docs/configuration.md b/docs/configuration.md index 45005ad..27a7a92 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2,7 +2,13 @@ On first run, `memclaw` launches a setup wizard: it asks which front-end you want (Telegram, WhatsApp, Slack or Terminal) and which agent backend, prompts only for the keys those need, and saves them to `~/.memclaw/.env`. Run `memclaw configure` anytime to switch platform or backend, or to update keys. -You can also set keys via environment variables or a `.env` in the current directory — these take the usual precedence over the saved config. +You can also set any of them as environment variables. Where a value comes from, highest first: + +1. The environment of the shell that runs `memclaw`. +2. A `.env` in the folder Memclaw is installed in or any folder above it (python-dotenv searches upward from the installed `memclaw` package, not from the folder you run `memclaw` in). In practice this only matters for a development install from a clone, where the clone's `.env` is picked up. +3. `~/.memclaw/.env`, written by the wizard. + +A `.env` in the current folder is not read; to use one, export its variables into your shell first (e.g. `set -a; . ./.env; set +a`). ```bash memclaw --memory-dir ~/my-vault # override storage location @@ -53,11 +59,11 @@ Via [`cursor-sdk`](https://pypi.org/project/cursor-sdk/). Install with `pip inst | `CURSOR_EFFORT` | Optional | Cursor reasoning level, for models that have one (set by `/effort`) | | `MEMCLAW_MCP_PORT` | For Cursor backend | Local MCP HTTP port (defaults to `17373`) | | `TELEGRAM_BOT_TOKEN` | For Telegram bot | Your Telegram bot token | -| `ALLOWED_USER_IDS` | For Telegram bot | Comma-separated Telegram user IDs | +| `ALLOWED_USER_IDS` | For Telegram bot | Comma-separated Telegram user IDs allowed to use the bot (empty = nobody) | | `SLACK_BOT_TOKEN` | For Slack bot | Slack bot token (`xoxb-...`) | | `SLACK_APP_TOKEN` | For Slack bot | Slack app-level token for Socket Mode (`xapp-...`) | -| `SLACK_ALLOWED_CHANNELS` | For Slack bot | Comma-separated Slack channel IDs (optional) | -| `SLACK_ALLOWED_USERS` | For Slack bot | Comma-separated Slack user IDs (optional — restricts who can DM/mention the bot) | +| `SLACK_ALLOWED_CHANNELS` | Optional | Comma-separated Slack channel IDs the bot answers in (empty = any channel the allowed users write in, DMs included) | +| `SLACK_ALLOWED_USERS` | For Slack bot | Comma-separated Slack user IDs who can DM/mention the bot (empty = nobody) | Search and memory tuning (weights, decay, chunk sizes) is listed in the [Memory Architecture](memory-architecture.md#configuration-reference) doc. diff --git a/docs/memory-architecture.md b/docs/memory-architecture.md index 7ab6266..c8eb9b4 100644 --- a/docs/memory-architecture.md +++ b/docs/memory-architecture.md @@ -108,7 +108,7 @@ Daily files accumulate over time. Consolidation is a periodic process that disti **When it runs:** -- Automatically, in the background after a reply, once a past day has notes that aren't consolidated yet — in practice after your first message of the next day you wrote in (days without notes cost nothing; after a few quiet days it catches up in one call). `consolidation_threshold` (default 1) raises the number of pending days to wait for. At most one consolidation runs at a time; a failure is logged and retried after a reply an hour or more later. A failed backend call (network down, auth, rate limit) is a failure, not a reply: the error text the CLI returns is never written to MEMORY.md, and the consolidation marker doesn't move. +- Automatically, in the background after a reply, once a past day has notes that aren't consolidated yet — in practice after your first message of the next day you wrote in (days without notes cost nothing; after a few quiet days it catches up in one call). `consolidation_threshold` (default 1) raises the number of pending days to wait for. At most one consolidation runs at a time; a failure is logged and retried after a reply an hour or more later. A failed backend call (network down, auth, rate limit) is a failure, not a reply: the error text the CLI returns is never written to MEMORY.md, and the consolidation marker doesn't move. The same goes for a reply that isn't a MEMORY.md (see step 4). - Manually, via the `memclaw consolidate` CLI command (which forces it regardless of count). Today's file is never consolidated: it is still being written to, and marking it done would skip everything saved later that day. It is picked up once the day is over. @@ -125,8 +125,9 @@ Today's file is never consolidated: it is still being written to, and marking it - 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 (`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. +4. Checks the reply is a MEMORY.md: it must start with `# Personal Memory` and have a `## Index` heading, as the prompt requires (it asks for the index even when there's nothing to index yet). Anything else (error text a backend returned instead of failing, such as "API Error: Connection refused" or Cursor's "I couldn't generate a response.", an empty or cut-off reply) is logged with a short preview and treated as a failed call: nothing is written, and the background run waits an hour. +5. 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. +6. 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` creates one through `MemoryVault` with the configured backend, without starting the agent, and calls `consolidate(force=True, since=...)`. diff --git a/docs/platforms.md b/docs/platforms.md index 8e7f548..207007f 100644 --- a/docs/platforms.md +++ b/docs/platforms.md @@ -26,7 +26,7 @@ Commands: `/new` starts a fresh conversation, `/model` shows the available model 1. Create a bot via [@BotFather](https://t.me/BotFather) and copy the token. 2. Get your Telegram user ID (e.g. via [@userinfobot](https://t.me/userinfobot)). -3. Run `memclaw`, pick **Telegram**, and enter the token and your user ID when asked. +3. Run `memclaw`, pick **Telegram**, and enter the token and your user ID when asked. Only the IDs in `ALLOWED_USER_IDS` can use the bot; if it's empty, nobody can (the bot warns about it at start). ## WhatsApp @@ -92,9 +92,9 @@ Connects via **Socket Mode** (WebSocket) — no public URL or webhook server nee 2. **Install to Workspace** and copy the **Bot Token** (`xoxb-...`). 3. Under **Basic Information → App-Level Tokens**, generate a token with `connections:write` scope and copy it (`xapp-...`). -4. Run `memclaw`, pick **Slack**, and enter both tokens. +4. Run `memclaw`, pick **Slack**, and enter both tokens and the users who may use it (`SLACK_ALLOWED_USERS`; find your Slack ID via **Profile → ••• → Copy member ID**). -DM the bot directly or mention it in channels (`@Memclaw save this...`). Optionally restrict it to specific channels with `SLACK_ALLOWED_CHANNELS`, or to specific users with `SLACK_ALLOWED_USERS` (find your Slack ID via **Profile → ••• → Copy member ID**). +DM the bot directly or mention it in channels (`@Memclaw save this...`). Only the users in `SLACK_ALLOWED_USERS` get an answer; if it's empty, nobody does (the bot warns about it at start). Optionally restrict it to specific channels with `SLACK_ALLOWED_CHANNELS`; left empty, the allowed users can use it in any channel and in DMs. ## Terminal @@ -126,4 +126,4 @@ memclaw status # vault overview memclaw doctor # check your OpenAI key can reach every model Memclaw uses ``` -If voice messages aren't transcribed or link summaries come back empty, run `memclaw doctor`. It probes `text-embedding-3-small` (search), `gpt-5-mini` (link summaries) and `whisper-1` (voice) and tells you which ones your OpenAI project can use. The same check runs at the end of the setup wizard. +If voice messages aren't transcribed or links arrive without a summary, run `memclaw doctor`. It probes `text-embedding-3-small` (search), `gpt-5-mini` (link summaries) and `whisper-1` (voice) and tells you which ones your OpenAI project can use. The same check runs at the end of the setup wizard. diff --git a/memclaw/bot/__init__.py b/memclaw/bot/__init__.py index 9a8d2c7..de1223a 100644 --- a/memclaw/bot/__init__.py +++ b/memclaw/bot/__init__.py @@ -14,7 +14,9 @@ from __future__ import annotations +import asyncio import sys +from collections.abc import Awaitable, Callable from dataclasses import dataclass from importlib import import_module from pathlib import Path @@ -86,6 +88,36 @@ def require_setting(value: str, env_var: str) -> None: raise SystemExit(1) +def allowlist_label(allowlist: list, env_var: str) -> str: + """How the start banner shows an allowlist. An empty one lets nobody in, + so it also prints a warning naming the setting to fill in.""" + if allowlist: + return ", ".join(str(who) for who in allowlist) + console.print( + f"[yellow]Warning:[/yellow] {env_var} is empty, so nobody can use the bot. " + f"Set it to a comma-separated list of IDs with [bold]memclaw configure[/bold] " + f"(or in ~/.memclaw/.env) and restart." + ) + return "nobody" + + +def run_until_stopped(start: Callable[[], Awaitable[object]], aclose: Callable[[], Awaitable[object]], + name: str) -> None: + """Run *start* until it returns or Ctrl+C, then always await *aclose* + (the bot's async shutdown: consolidation, the AI backend, reminders).""" + async def main() -> None: + try: + await start() + finally: + await aclose() + + try: + asyncio.run(main()) + except KeyboardInterrupt: + pass + console.print(f"\nMemclaw {name} bot shut down.") + + def log_to(log_file: Path | None = None) -> None: """Log INFO to the terminal and, with a *log_file*, DEBUG to it (rotated).""" logger.remove() diff --git a/memclaw/bot/inbound.py b/memclaw/bot/inbound.py index c7f5d11..7801e5e 100644 --- a/memclaw/bot/inbound.py +++ b/memclaw/bot/inbound.py @@ -35,11 +35,9 @@ SendText = Callable[[str, str], Awaitable[None]] # (chat id, text) -def is_allowed(who: object, allowlist: Collection, *, empty_allows_all: bool) -> bool: - """Whether *who* may use the bot. The platforms disagree on what an - empty allowlist means, so each one says (see their access checks).""" - if not allowlist: - return empty_allows_all +def is_allowed(who: object, allowlist: Collection) -> bool: + """Whether *who* may use the bot: only those on the allowlist, so an + empty allowlist lets nobody in (on every platform that has one).""" return who in allowlist @@ -150,7 +148,3 @@ async def start(self) -> None: async def aclose(self) -> None: await self.agent.aclose() self.scheduler.close() - - def close(self) -> None: - self.scheduler.close() - self.agent.close() diff --git a/memclaw/bot/links.py b/memclaw/bot/links.py index 23307a2..c6026ca 100644 --- a/memclaw/bot/links.py +++ b/memclaw/bot/links.py @@ -73,7 +73,10 @@ def _extract_text(html: str, max_chars: int = 5000) -> str: text = re.sub(r"\s+", " ", text).strip() return text[:max_chars] - async def summarize(self, content: str, url: str) -> str: + async def summarize(self, content: str, url: str) -> str | None: + """The page's summary, or None if the summary call failed (logged), + the same as for a page that couldn't be fetched: the agent gets no + summary rather than the error text presented as one.""" try: return await self.openai.chat([ { @@ -85,11 +88,13 @@ async def summarize(self, content: str, url: str) -> str: }, {"role": "user", "content": f"Summarize content from {url}:\n\n{content}"}, ]) - except Exception as e: - return f"Could not summarize: {e}" + except Exception as exc: + logger.warning("summarize failed for {url}: {exc}", url=url, exc=exc) + return None async def process_links(self, text: str) -> list[dict]: - """Extract URLs, fetch content, summarize. Returns [{url, summary}].""" + """Extract URLs, fetch content, summarize. Returns [{url, summary}]; + the summary is None when the page couldn't be fetched or summarized.""" urls = self.extract_urls(text) results: list[dict] = [] diff --git a/memclaw/bot/slack.py b/memclaw/bot/slack.py index f761911..a277110 100644 --- a/memclaw/bot/slack.py +++ b/memclaw/bot/slack.py @@ -6,7 +6,6 @@ from __future__ import annotations -import asyncio import re from dataclasses import dataclass from pathlib import Path @@ -18,7 +17,7 @@ from slack_bolt.async_app import AsyncApp from ..config import MemclawConfig -from . import console, log_to, mask_user_id, require_setting +from . import allowlist_label, console, log_to, mask_user_id, require_setting, run_until_stopped from .inbound import TRANSCRIPTION_FAILED, Inbound, is_allowed, save_media # Image MIME types we handle @@ -78,13 +77,15 @@ async def handle_mention(event, say, client): await self._route_event(event, say) # ── Access control ─────────────────────────────────────────────── - # An empty SLACK_ALLOWED_CHANNELS / SLACK_ALLOWED_USERS lets everyone in. + # Only the users in SLACK_ALLOWED_USERS (empty lets nobody in), in the + # channels in SLACK_ALLOWED_CHANNELS (empty = any channel, DMs included). def _check_channel(self, channel: str) -> bool: - return is_allowed(channel, self.config.slack.allowed_channels_list, empty_allows_all=True) + channels = self.config.slack.allowed_channels_list + return not channels or is_allowed(channel, channels) def _check_user(self, user: str) -> bool: - return is_allowed(user, self.config.slack.allowed_users_list, empty_allows_all=True) + return is_allowed(user, self.config.slack.allowed_users_list) # ── Event routing ──────────────────────────────────────────────── @@ -95,6 +96,7 @@ async def _route_event(self, event: dict, say): channel = event.get("channel", "") if not self._check_channel(channel): + logger.info("Ignoring Slack message in channel {c} (not in SLACK_ALLOWED_CHANNELS)", c=channel) return user = event.get("user", "unknown") @@ -262,18 +264,10 @@ def run(config: MemclawConfig) -> None: bot = SlackBot(config) + users = allowlist_label([mask_user_id(u) for u in config.slack.allowed_users_list], "SLACK_ALLOWED_USERS") + channels = ", ".join(config.slack.allowed_channels_list) or "any" console.print( f"[green]Starting Memclaw Slack bot (Socket Mode)...[/green] " - f"(allowed channels: {config.slack.allowed_channels_list or 'all'})" + f"(allowed users: {users}; allowed channels: {channels})" ) - - async def _run(): - try: - await bot.start() - except KeyboardInterrupt: - pass - finally: - await bot.aclose() - console.print("\nMemclaw Slack bot shut down.") - - asyncio.run(_run()) + run_until_stopped(bot.start, bot.aclose, "Slack") diff --git a/memclaw/bot/telegram.py b/memclaw/bot/telegram.py index 800ad41..903ca89 100644 --- a/memclaw/bot/telegram.py +++ b/memclaw/bot/telegram.py @@ -29,7 +29,7 @@ from ..backends import AgentBackend from ..backends.base import ToolStep from ..config import MemclawConfig -from . import console, log_to, mask_user_id, require_setting +from . import allowlist_label, console, log_to, mask_user_id, require_setting from .commands import ( load_models, resolve_model_arg, @@ -160,9 +160,7 @@ async def send(chat_id: str, text: str) -> None: def _allowed(self, update: Update) -> bool: """Only the users in ALLOWED_USER_IDS; an empty list lets nobody in.""" user = update.effective_user - return user is not None and is_allowed( - user.id, self.config.telegram.allowed_user_ids_list, empty_allows_all=False, - ) + return user is not None and is_allowed(user.id, self.config.telegram.allowed_user_ids_list) def _message(self, update: Update) -> Message | None: """The update's message, if it comes from an allowed user.""" @@ -377,9 +375,6 @@ async def handle_voice(self, update: Update, context: ContextTypes.DEFAULT_TYPE) async def aclose(self): await self.inbound.aclose() - def close(self): - self.inbound.close() - Handler = Callable[[TelegramBot, Update, ContextTypes.DEFAULT_TYPE], Awaitable[None]] @@ -458,10 +453,7 @@ def run(config: MemclawConfig) -> None: app = build_application(config) - allowed = config.telegram.allowed_user_ids_list - masked = [mask_user_id(u) for u in allowed] if allowed else "all" - console.print( - f"[green]Starting Memclaw Telegram bot...[/green] " - f"(allowed users: {masked})" - ) + masked = [mask_user_id(u) for u in config.telegram.allowed_user_ids_list] + users = allowlist_label(masked, "ALLOWED_USER_IDS") + console.print(f"[green]Starting Memclaw Telegram bot...[/green] (allowed users: {users})") app.run_polling(allowed_updates=["message", "callback_query"]) diff --git a/memclaw/bot/whatsapp.py b/memclaw/bot/whatsapp.py index f8c7490..6698e14 100644 --- a/memclaw/bot/whatsapp.py +++ b/memclaw/bot/whatsapp.py @@ -10,7 +10,6 @@ from __future__ import annotations -import asyncio from pathlib import Path from loguru import logger @@ -19,7 +18,7 @@ from neonize.utils.jid import build_jid from ..config import MemclawConfig -from . import console, log_to, mask_user_id +from . import console, log_to, mask_user_id, run_until_stopped from .inbound import TRANSCRIPTION_FAILED, Inbound, save_media _MIME_TO_EXT = { @@ -221,8 +220,8 @@ async def start(self): await self.client.connect() await self.client.idle() - def close(self): - self.inbound.close() + async def aclose(self): + await self.inbound.aclose() def run(config: MemclawConfig) -> None: @@ -238,9 +237,4 @@ def run(config: MemclawConfig) -> None: "Open WhatsApp → Settings → Linked Devices → Link a Device, and scan it." ) - try: - asyncio.run(bot.start()) - except KeyboardInterrupt: - pass - finally: - bot.close() + run_until_stopped(bot.start, bot.aclose, "WhatsApp") diff --git a/memclaw/config.py b/memclaw/config.py index d1596c0..f986e54 100644 --- a/memclaw/config.py +++ b/memclaw/config.py @@ -166,10 +166,12 @@ class SlackSettings(Settings): app_token: str = setting( "SLACK_APP_TOKEN", secret=True, required=True, prompt="Slack app-level token for Socket Mode (xapp-...)") + # Empty = any channel (DMs included) the allowed users write in. allowed_channels: str = setting( "SLACK_ALLOWED_CHANNELS", prompt="Allowed Slack channel IDs (comma-separated)") + # Like ALLOWED_USER_IDS, an empty list lets nobody in. allowed_users: str = setting( - "SLACK_ALLOWED_USERS", prompt="Allowed Slack user IDs (comma-separated)") + "SLACK_ALLOWED_USERS", required=True, prompt="Allowed Slack user IDs (comma-separated)") @property def allowed_channels_list(self) -> list[str]: diff --git a/memclaw/memory/consolidation.py b/memclaw/memory/consolidation.py index 77d6790..62c3fa4 100644 --- a/memclaw/memory/consolidation.py +++ b/memclaw/memory/consolidation.py @@ -41,6 +41,11 @@ # A reply wrapped in a ```markdown fence despite the instructions. _FENCED_RE = re.compile(r"^```[\w-]*\n(.*?)\n?```$", re.DOTALL) +# What the prompt's Format section requires of every MEMORY.md: it starts +# with this title and has the index heading. +_MEMORY_TITLE = "# Personal Memory" +_INDEX_RE = re.compile(r"^## Index[ \t]*$", re.MULTILINE) + _CONSOLIDATION_PROMPT = """\ You maintain MEMORY.md, the user's permanent memory. It is loaded into the \ @@ -101,7 +106,8 @@ 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". +threads — only those with content), then "## Index" (always, even when \ +there is nothing to index yet). - 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. @@ -128,6 +134,27 @@ def _strip_fence(text: str) -> str: return m.group(1).strip() if m else text +def _check_memory_text(text: str) -> None: + """Raise unless *text* has what the prompt requires of a MEMORY.md: it + starts with the title and has the index heading. + + A backend can return error text instead of raising ("API Error: ...", + Cursor's "I couldn't generate a response."), or a reply can come back + empty or cut off; written over MEMORY.md, it would replace the user's + whole profile. Raising treats it as the failed call it is: nothing is + written and the background run waits an hour, rather than paying for a + new call after every reply.""" + if text.startswith(_MEMORY_TITLE) and _INDEX_RE.search(text): + return + preview = text.strip()[:80] + logger.warning( + "Consolidation reply is not a MEMORY.md (no \"{t}\" title or \"## Index\"), " + "MEMORY.md left as it was: {p!r}", + t=_MEMORY_TITLE, p=preview, + ) + raise RuntimeError(f"Consolidation reply is not a MEMORY.md: {preview!r}") + + class Consolidator: """Distills the daily files not in MEMORY.md yet into it. @@ -183,8 +210,6 @@ async def consolidate(self, *, force: bool = False, since: date | None = None) - 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) @@ -291,7 +316,11 @@ 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.""" + is written, and consolidation retries later. + + Raises if *new_memory* isn't a MEMORY.md (an error message, a + placeholder, an empty or cut-off reply), like a failed backend call.""" + _check_memory_text(new_memory) 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") diff --git a/tests/bot/test_inbound.py b/tests/bot/test_inbound.py index 7a8fe4f..026ee68 100644 --- a/tests/bot/test_inbound.py +++ b/tests/bot/test_inbound.py @@ -17,10 +17,9 @@ def test_pipeline_never_saves_on_its_own(): def test_is_allowed(): - assert is_allowed("a", ["a", "b"], empty_allows_all=False) - assert not is_allowed("c", ["a", "b"], empty_allows_all=True) - assert is_allowed("c", [], empty_allows_all=True) - assert not is_allowed("c", [], empty_allows_all=False) + assert is_allowed("a", ["a", "b"]) + assert not is_allowed("c", ["a", "b"]) + assert not is_allowed("c", []) # an empty allowlist lets nobody in class TestAgentsFile: diff --git a/tests/bot/test_links.py b/tests/bot/test_links.py index f9e106e..42064b6 100644 --- a/tests/bot/test_links.py +++ b/tests/bot/test_links.py @@ -1,4 +1,4 @@ -"""memclaw.bot.links: URLs in a message, and what a failed summary says.""" +"""memclaw.bot.links: URLs in a message, and what a failed summary gives.""" from __future__ import annotations import pytest @@ -18,7 +18,7 @@ def test_extract_urls(): @pytest.mark.asyncio -async def test_failed_summary_is_reported_as_the_summary(): - """The error text becomes the summary the agent sees (as before).""" +async def test_failed_summary_is_no_summary(): + """None, as for a page that couldn't be fetched, so no link note is added.""" links = LinkProcessor(_FailingOpenAI()) - assert await links.summarize("page", "https://a.com") == "Could not summarize: quota" + assert await links.summarize("page", "https://a.com") is None diff --git a/tests/bot/test_parity.py b/tests/bot/test_parity.py index 0526fc9..5fbd27b 100644 --- a/tests/bot/test_parity.py +++ b/tests/bot/test_parity.py @@ -125,6 +125,7 @@ def __init__(self, *args, **kwargs): self.transcriptions: list[tuple] = [] self.chats: list[dict] = [] self.fail_transcription = False + self.fail_chat = False self.audio = SimpleNamespace(transcriptions=SimpleNamespace(create=self._transcribe)) self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._chat)) @@ -136,6 +137,8 @@ async def _transcribe(self, *, model, file): async def _chat(self, **kwargs): self.chats.append(kwargs) + if self.fail_chat: + raise RuntimeError("quota exceeded") return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=SUMMARY))]) async def close(self): @@ -158,7 +161,9 @@ def env(tmp_path, monkeypatch): memory_dir=tmp_path / "m", openai=OpenAISettings(api_key="sk-test"), telegram=TelegramSettings(bot_token="123:abc", allowed_user_ids="1"), - slack=SlackSettings(bot_token="xoxb-1", app_token="xapp-1", allowed_users="U1"), + slack=SlackSettings( + bot_token="xoxb-1", app_token="xapp-1", allowed_users="U1", allowed_channels="C1", + ), ) return SimpleNamespace(config=config, openai=openai, monkeypatch=monkeypatch) @@ -324,8 +329,8 @@ async def say(**kw): self.said.append(kw) await self.app.events[kind](event=event, say=say, client=None) - async def text(self, text, *, stranger=False, user=None): - user = user or ("U9" if stranger else "U1") + async def text(self, text, *, stranger=False): + user = "U9" if stranger else "U1" await self._event({"channel": "C1", "user": user, "text": text, "ts": "1.0"}) async def photo(self, caption): @@ -515,6 +520,16 @@ async def test_link_that_cannot_be_fetched_adds_nothing(chat): assert chat.env.openai.chats == [] +async def test_link_that_cannot_be_summarized_adds_nothing(chat): + """A failed summary is no summary, like a page that can't be fetched: + the error text never reaches the agent as if it were the page's summary.""" + chat.env.openai.fail_chat = True + await chat.text(LINK_TEXT) + assert [c["prompt"] for c in chat.agent.calls] == [LINK_TEXT] + assert len(chat.env.openai.chats) == 1 + assert chat.replies == ["Got it."] + + async def test_photo_with_a_link_in_the_caption(chat): await chat.photo(LINK_TEXT) [call] = chat.agent.calls @@ -654,19 +669,30 @@ async def test_telegram_quotes_the_replied_message(env): async def test_telegram_empty_allowlist_blocks_everyone(env): - """Quirk: on Telegram an empty ALLOWED_USER_IDS lets nobody in...""" + """An empty ALLOWED_USER_IDS lets nobody in...""" env.config.telegram.allowed_user_ids = "" chat = TelegramDriver(env) await chat.text("hello") assert chat.agent.calls == [] and chat.replies == [] -async def test_slack_empty_allowlist_lets_everyone_in(env): - """...while on Slack an empty SLACK_ALLOWED_USERS lets everyone in.""" +async def test_slack_empty_allowlist_blocks_everyone(env): + """...and so does an empty SLACK_ALLOWED_USERS (WhatsApp has no + allowlist: only your own self-chat gets in).""" env.config.slack.allowed_users = "" chat = SlackDriver(env) - await chat.text("hello", user="U-anyone") - assert [c["prompt"] for c in chat.agent.calls] == ["hello"] + await chat.text("hello") + assert chat.agent.calls == [] and chat.replies == [] + + +async def test_slack_empty_channel_list_means_any_channel(env): + """An empty SLACK_ALLOWED_CHANNELS lets the allowed users in anywhere + (a DM included); strangers are still ignored.""" + env.config.slack.allowed_channels = "" + chat = SlackDriver(env) + await chat._event({"channel": "D1", "user": "U1", "text": "in a DM", "ts": "1.0"}) + await chat._event({"channel": "D9", "user": "U9", "text": "stranger", "ts": "1.0"}) + assert [c["prompt"] for c in chat.agent.calls] == ["in a DM"] async def test_slack_allowlists(env): diff --git a/tests/bot/test_slack.py b/tests/bot/test_slack.py index 7032f68..8cdf6a7 100644 --- a/tests/bot/test_slack.py +++ b/tests/bot/test_slack.py @@ -14,8 +14,8 @@ async def test_new_message_resets_the_channel(): handlers = SlackBot.__new__(SlackBot) handlers.config = MagicMock() - handlers.config.slack.allowed_channels_list = [] - handlers.config.slack.allowed_users_list = [] + handlers.config.slack.allowed_channels_list = ["C1"] + handlers.config.slack.allowed_users_list = ["U1"] handlers.inbound = Inbound.__new__(Inbound) handlers.inbound.agent = agent = MagicMock() agent.reset_conversation = AsyncMock() @@ -29,3 +29,29 @@ async def test_new_message_resets_the_channel(): agent.reset_conversation.assert_awaited_once_with("C1") agent.handle.assert_not_awaited() say.assert_awaited_once_with(text="Started a new conversation.", thread_ts="1.0") + + +@pytest.mark.parametrize(("users", "channels", "warned", "shown"), [ + ("", "C1", True, "allowed users: nobody; allowed channels: C1"), + ("U1", "", False, "allowed users: **; allowed channels: any"), + ("", "", True, "allowed users: nobody; allowed channels: any"), + ("U1", "C1", False, "allowed users: **; allowed channels: C1"), +]) +def test_start_warns_only_about_an_empty_user_list(monkeypatch, tmp_path, users, channels, warned, shown): + from memclaw.bot import console, slack + from memclaw.config import MemclawConfig, SlackSettings + + monkeypatch.setattr(slack, "log_to", lambda *a: None) + bot = MagicMock(start=AsyncMock(), aclose=AsyncMock()) + monkeypatch.setattr(slack, "SlackBot", lambda config: bot) + config = MemclawConfig(memory_dir=tmp_path, slack=SlackSettings(bot_token="xoxb-1", app_token="xapp-1")) + # Set after construction: an empty value there would be read from the environment. + config.slack.allowed_users, config.slack.allowed_channels = users, channels + with console.capture() as captured: + slack.run(config) + out = " ".join(captured.get().split()) + + assert ("SLACK_ALLOWED_USERS is empty, so nobody can use the bot" in out) == warned + assert "SLACK_ALLOWED_CHANNELS" not in out + assert shown in out + bot.aclose.assert_awaited_once() # the async shutdown ran diff --git a/tests/bot/test_telegram.py b/tests/bot/test_telegram.py index 150fa87..aaacca9 100644 --- a/tests/bot/test_telegram.py +++ b/tests/bot/test_telegram.py @@ -366,3 +366,28 @@ def test_labels_and_truncation(self): assert describe_tool_call("unknown_tool", {"x": 1}) == "unknown_tool" long = describe_tool_call("file_read", {"file_path": "a" * 200}) assert long.endswith("…") and len(long) <= len("Reading: ") + 80 + + +class TestStartBanner: + def _start(self, monkeypatch, tmp_path, allowed: str) -> str: + from memclaw.bot import console, telegram + from memclaw.config import MemclawConfig, TelegramSettings + + monkeypatch.setattr(telegram, "log_to", lambda *a: None) + monkeypatch.setattr(telegram, "build_application", lambda config: MagicMock()) + config = MemclawConfig(memory_dir=tmp_path, telegram=TelegramSettings(bot_token="1:a")) + config.telegram.allowed_user_ids = allowed # after: an empty value would read the env + with console.capture() as captured: + telegram.run(config) + return " ".join(captured.get().split()) + + def test_empty_allowlist_warns_and_says_nobody(self, monkeypatch, tmp_path): + out = self._start(monkeypatch, tmp_path, "") + assert "allowed users: nobody" in out + assert "users: all" not in out + assert "ALLOWED_USER_IDS is empty, so nobody can use the bot" in out + + def test_allowlist_is_shown_masked(self, monkeypatch, tmp_path): + out = self._start(monkeypatch, tmp_path, "100951236") + assert "allowed users: 100****36" in out + assert "Warning" not in out diff --git a/tests/bot/test_whatsapp.py b/tests/bot/test_whatsapp.py index 3e68c83..de8ac5b 100644 --- a/tests/bot/test_whatsapp.py +++ b/tests/bot/test_whatsapp.py @@ -65,3 +65,68 @@ def ev(*, is_group: bool, is_from_me: bool, chat_user: str, sender_user: str): assert check(None, out_to_friend) is False, "outgoing DM to friend must be ignored" assert check(None, in_from_friend) is False assert check(None, group) is False + + +# ──────────────────────────────────────────────────────────────────── +# Shutdown: Ctrl+C runs the async shutdown (the AI backend's aclose) +# ──────────────────────────────────────────────────────────────────── + +class TestShutdown: + def _run(self, monkeypatch, tmp_path, idle) -> list[str]: + import tests.bot.test_parity # noqa: F401 (stands in for neonize without libmagic) + import memclaw.bot.whatsapp as whatsapp + from memclaw.config import MemclawConfig + + events: list[str] = [] + + class FakeInbound: + def __init__(self, config, platform): + pass + + def deliver_reminders(self, send): + pass + + async def start(self): + events.append("start") + + async def aclose(self): + events.append("aclose") + + def close(self): + events.append("close") + + class FakeClient: + def __init__(self, path): + pass + + def event(self, ev_type): + return lambda fn: fn + + async def connect(self): + pass + + async def idle(self): + await idle() + + monkeypatch.setattr(whatsapp, "Inbound", FakeInbound) + monkeypatch.setattr(whatsapp, "NewAClient", FakeClient) + monkeypatch.setattr(whatsapp, "log_to", lambda *a: None) + whatsapp.run(MemclawConfig(memory_dir=tmp_path)) + return events + + def test_ctrl_c_shuts_the_backend_down(self, monkeypatch, tmp_path): + import asyncio + import os + import signal + + async def ctrl_c(): + os.kill(os.getpid(), signal.SIGINT) + await asyncio.sleep(5) + + assert self._run(monkeypatch, tmp_path, ctrl_c) == ["start", "aclose"] + + def test_disconnect_shuts_the_backend_down(self, monkeypatch, tmp_path): + async def disconnected(): + pass + + assert self._run(monkeypatch, tmp_path, disconnected) == ["start", "aclose"] diff --git a/tests/memory/test_consolidation.py b/tests/memory/test_consolidation.py index 0d53a9a..746e3df 100644 --- a/tests/memory/test_consolidation.py +++ b/tests/memory/test_consolidation.py @@ -15,11 +15,15 @@ from unittest.mock import AsyncMock import pytest +from loguru import logger from memclaw.config import ClaudeSettings, MemclawConfig, OpenAISettings from memclaw.memory import Consolidator, MemoryIndex, MemoryStore from memclaw.memory.consolidation import _CONSOLIDATION_BUDGET_CHARS as BUDGET +# The smallest reply that is a MEMORY.md (the prompt's required headings). +VALID = "# Personal Memory\n\n## Index\n" + @pytest.fixture def cfg(tmp_path: Path) -> MemclawConfig: @@ -59,6 +63,15 @@ def consolidator(cfg: MemclawConfig, index: MemoryIndex, fake_backend: FakeBacke return Consolidator(cfg, MemoryStore(cfg), index, fake_backend) +@pytest.fixture +def warnings_logged(): + """The messages logged at WARNING or above while the test runs.""" + messages: list[str] = [] + sink = logger.add(lambda m: messages.append(m.record["message"]), level="WARNING") + yield messages + logger.remove(sink) + + def _daily(cfg: MemclawConfig, d: date, text: str) -> Path: path = cfg.daily_file(d) path.write_text(text) @@ -88,7 +101,7 @@ async def test_skips_when_below_threshold(self, cfg, fake_backend, consolidator) 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" + fake_backend.one_shot_response = "# Personal Memory\n\n## Key Facts\n\n- Fact 0\n- Fact 1\n\n## Index\n" for i in range(5): _daily(cfg, date(2025, 3, i + 1), f"# Day {i}\nImportant fact {i}") index.index_file = AsyncMock() @@ -102,7 +115,7 @@ async def test_runs_when_above_threshold(self, cfg, fake_backend, consolidator, 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" + fake_backend.one_shot_response = "# Personal Memory\n\n## Notes\n- One note\n\n## Index" _daily(cfg, date(2025, 3, 1), "# Single day\nJust one note") index.index_file = AsyncMock() @@ -111,7 +124,7 @@ async def test_force_ignores_threshold(self, cfg, fake_backend, consolidator, in @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" + fake_backend.one_shot_response = VALID 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"})) @@ -130,7 +143,7 @@ async def test_no_files_returns_false(self, fake_backend, consolidator): @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" + fake_backend.one_shot_response = "# Personal Memory\n- x\n## Index" _daily(cfg, date.today(), "today") assert await consolidator.consolidate() is False # today isn't over _daily(cfg, date.today() - timedelta(days=1), "yesterday") @@ -138,7 +151,7 @@ async def test_by_default_it_runs_once_a_day_has_passed(self, cfg, fake_backend, @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" + fake_backend.one_shot_response = "# Personal Memory\n## Facts\n- x\n## Index" _daily(cfg, date.today() - timedelta(days=1), "yesterday's note") _daily(cfg, date.today(), "today's note") @@ -169,7 +182,7 @@ 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" + fake_backend.one_shot_response = VALID for i in range(1, 6): _daily(cfg, date(2025, 3, i), "x" * (BUDGET // 3)) @@ -178,7 +191,7 @@ async def test_content_limit(self, cfg, fake_backend, consolidator): @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" + fake_backend.one_shot_response = "# Personal Memory\n## Facts\n- x\n## Index" for day in range(1, 6): _daily(cfg, date(2025, 3, day), f"day {day} " + "x" * (BUDGET // 3)) @@ -193,21 +206,21 @@ async def test_files_past_the_budget_stay_unconsolidated(self, cfg, fake_backend @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" + fake_backend.one_shot_response = "# Personal Memory\n## Facts\n- x\n## Index" _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" + fake_backend.one_shot_response = VALID _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" + fake_backend.one_shot_response = VALID cfg.memory_file.write_text("# Personal Memory\n- old fact\n") _daily(cfg, date(2025, 3, 1), "note one") await consolidator.consolidate(force=True) @@ -221,7 +234,7 @@ async def test_prompt_and_message_layout(self, cfg, fake_backend, consolidator): @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" + fake_backend.one_shot_response = VALID (cfg.memory_dir / "todos.md").write_text("# Todos\n- renew passport") _daily(cfg, date(2025, 3, 1), "note") await consolidator.consolidate(force=True) @@ -243,12 +256,12 @@ async def test_save_during_consolidation_is_kept(self, cfg, fake_backend, consol 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" + return "# Personal Memory\n- consolidated\n## Index" 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 memory.startswith("# Personal Memory\n- consolidated\n## Index\n") 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"] @@ -259,7 +272,7 @@ async def test_manual_edit_during_consolidation_aborts(self, cfg, fake_backend, async def one_shot(**kwargs): cfg.memory_file.write_text("# Edited by hand\n") - return "## Facts\n- consolidated" + return "# Personal Memory\n- consolidated\n## Index" fake_backend.run_one_shot = one_shot assert await consolidator.consolidate(force=True) is False @@ -281,21 +294,45 @@ async def one_shot(**kwargs): assert not (cfg.memory_dir / "meta.json").exists() assert not (cfg.memory_dir / ".history").exists() + @pytest.mark.parametrize("reply", [ + "API Error: Connection refused", # a backend's error text, returned instead of raised + "I couldn't generate a response.", # Cursor's placeholder for an empty result + " \n", # empty + "# Personal Memory\n\n## About\n- Ana, lives in", # cut off before the index + "Here is the updated MEMORY.md:\n\n# Personal Memory\n\n## Index\n", # preamble + ], ids=["error", "placeholder", "empty", "cut-off", "preamble"]) @pytest.mark.asyncio - async def test_empty_reply_leaves_memory_untouched(self, cfg, fake_backend, consolidator): + async def test_a_reply_that_is_not_a_memory_file_is_rejected( + self, cfg, fake_backend, consolidator, reply, warnings_logged, + ): + """Raised like a failed backend call (so the background run waits an + hour), with MEMORY.md, .history/ and meta.json untouched.""" _daily(cfg, date(2025, 3, 1), "note") + cfg.memory_file.write_text("# Personal Memory\n- old fact\n\n## Index\n") before = cfg.memory_file.read_text() - fake_backend.one_shot_response = " \n" - assert await consolidator.consolidate(force=True) is False + fake_backend.one_shot_response = reply + with pytest.raises(RuntimeError, match="not a MEMORY.md"): + 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() + [warning] = [m for m in warnings_logged if "not a MEMORY.md" in m] + assert repr(reply.strip()[:80]) in warning + + @pytest.mark.asyncio + async def test_a_valid_reply_is_written(self, cfg, fake_backend, consolidator): + _daily(cfg, date(2025, 3, 1), "note") + fake_backend.one_shot_response = "\n# Personal Memory\n\n## About\n- Ana\n\n## Index\n### Notes\n" + assert await consolidator.consolidate(force=True) + assert cfg.memory_file.read_text() == "# Personal Memory\n\n## About\n- Ana\n\n## Index\n### Notes\n" + assert _consolidated_through(cfg) == "2025-03-01" @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```" + fake_backend.one_shot_response = "```markdown\n# Personal Memory\n- x\n## Index\n```" _daily(cfg, date(2025, 3, 1), "note") assert await consolidator.consolidate(force=True) - assert cfg.memory_file.read_text() == "## Facts\n- x\n" + assert cfg.memory_file.read_text() == "# Personal Memory\n- x\n## Index\n" @pytest.mark.asyncio async def test_references_to_missing_notes_are_dropped(self, cfg, fake_backend, consolidator): @@ -314,7 +351,7 @@ async def test_history_keeps_the_last_60(self, cfg, fake_backend, consolidator): 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" + fake_backend.one_shot_response = "# Personal Memory\n- next\n## Index" _daily(cfg, date(2025, 3, 1), "note") assert await consolidator.consolidate(force=True) kept = sorted(history.glob("MEMORY-*.md")) @@ -324,17 +361,17 @@ async def test_history_keeps_the_last_60(self, cfg, fake_backend, consolidator): @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" + fake_backend.one_shot_response = "# Personal Memory\n- x\n## Index" _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 cfg.memory_file.read_text() == "# Personal Memory\n- x\n## Index\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" + fake_backend.one_shot_response = "# Personal Memory\n- x\n## Index" _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"} diff --git a/tests/memory/test_vault.py b/tests/memory/test_vault.py index e9d30b0..d716c27 100644 --- a/tests/memory/test_vault.py +++ b/tests/memory/test_vault.py @@ -63,7 +63,7 @@ async def test_sync_or_warn_swallows_a_failing_sync(tmp_config: MemclawConfig): @pytest.mark.asyncio async def test_consolidate_writes_memory_md_with_the_backend_given(tmp_config: MemclawConfig): - backend = _OneShot("## Key Facts\n- Alex's birthday is March 3") + backend = _OneShot("# Personal Memory\n\n- Alex's birthday is March 3\n\n## Index\n") yesterday = date.today() - timedelta(days=1) with MemoryVault(tmp_config) as vault: # Today's note is still being written; consolidation takes the days before. diff --git a/tests/setup/test_wizard.py b/tests/setup/test_wizard.py index c617f65..d40bf52 100644 --- a/tests/setup/test_wizard.py +++ b/tests/setup/test_wizard.py @@ -80,7 +80,7 @@ def test_first_run_writes_the_answers(self, wizard): "Slack bot token (xoxb-...) (required)", "Slack app-level token for Socket Mode (xapp-...) (required)", "Allowed Slack channel IDs (comma-separated) (optional)", - "Allowed Slack user IDs (comma-separated) (optional)", + "Allowed Slack user IDs (comma-separated) (required)", ] assert text == ( "AGENT_BACKEND=claude\nCLAUDE_CODE_OAUTH_TOKEN=oat-token\n" diff --git a/tests/test_cli.py b/tests/test_cli.py index abec2be..a17eea9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -40,7 +40,7 @@ def is_configured(cls, config): return True async def run_one_shot(self, *, system_prompt: str, user_message: str) -> str: - return "## Key Facts\n- Consolidated" + return "# Personal Memory\n\n## Key Facts\n- Consolidated\n\n## Index\n" @pytest.fixture