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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# From code-shape-kit's templates/CODEOWNERS. With "Require review from Code
# Owners" on in the branch protection rules, a pull request that changes the
# code-shape rules can't be merged without the owner's approval: a red gate
# can't be turned green by loosening them.

# [tool.shape] (limits, banned APIs, output_modules, ...), [tool.importlinter]
# (memclaw's layout rules), [tool.vulture] and the pinned kit version
/pyproject.toml @emanuilo
# the baseline: known violations (memclaw's is empty)
/.code-shape/ @emanuilo
# the hooks that run `code-shape check` before a commit (git and Claude Code)
/.githooks/ @emanuilo
/.claude/settings.json @emanuilo
/.claude/hooks/ @emanuilo
# the CI gate itself (the `shape` job)
/.github/workflows/ci.yml @emanuilo
# this file
/.github/CODEOWNERS @emanuilo
14 changes: 11 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pip install -U pip
pip install -e ".[dev]" --group shape
```

(`--group shape` adds the code-shape checks, see [Code Shape](#code-shape). It needs pip 25.1+ and Python 3.11+. With uv: `uv sync --extra dev --group shape`.)
(`--group shape` adds the code-shape checks, see [Code Shape](#code-shape). It needs pip 25.1+ and Python 3.11.4+. With uv: `uv sync --extra dev --group shape`.)

Copy the environment template and fill in your keys:

Expand Down Expand Up @@ -43,7 +43,9 @@ All tests should pass before submitting a PR. The test suite mocks external API
- **Sizes**: files (500 lines), classes (300), folders (12 modules, 4000 lines), nesting of folders.
- **Functions and classes**: complexity, length, number of arguments, variables, attributes and public methods.
- **Coupling**: environment variables or `.env` files read outside `config.py`, the OpenAI SDK or SQLite used outside their modules, private members (`obj._x`) used from outside, copy-pasted code, import cycles, modules that import too many others (more than 8 memclaw modules).
- **Hygiene**: unused code, dependencies in `pyproject.toml` vs. what the code imports, and type errors (mypy).
- **Hygiene**: unused code, dependencies in `pyproject.toml` vs. what the code imports, and type errors (mypy, also inside functions without type hints).
- **Risky habits**: errors caught too broadly or swallowed (`except Exception`, an `except` that only passes), commented-out code, `print()` (see below), mutable default arguments (`def f(x=[])`), `from x import *`, `shell=True` / SQL built from strings / hard-coded passwords / `eval`, and `True`/`False` arguments passed by position (make them keyword-only: `def f(*, verbose: bool)`).
- **Suppression comments**: every `# noqa`, `# type: ignore`, `# pylint: disable`, `# pragma: no cover` or `# nosec` is a finding. A `# type: ignore` that isn't needed any more is an error too.
- **memclaw's layout rules** (see below).

CI runs it on every PR. Locally:
Expand All @@ -52,7 +54,13 @@ CI runs it on every PR. Locally:
- `code-shape report`: writes `code-shape-report.md` with all the numbers, the worst offenders and git-history trends. It never fails.
- `code-shape tighten`: after a fix, records the improvement in the baseline. Commit the baseline together with the fix.

**The baseline.** `.code-shape/baseline.json` lists the problems memclaw already had when the kit was adopted, so only new ones fail. It may only shrink. Never edit it by hand and don't re-run `code-shape baseline` to accept a new problem: fix the code, then run `code-shape tighten`. `# noqa` comments don't silence these checks, and the limits under `[tool.shape]` in `pyproject.toml` aren't raised to make a change pass. If a rule seems wrong for your case, say so in the PR.
**The baseline.** `.code-shape/baseline.json` lists the problems memclaw already had when the kit was adopted, so only new ones fail. It may only shrink. Never edit it by hand and don't re-run `code-shape baseline` to accept a new problem: fix the code, then run `code-shape tighten`. Suppression comments don't silence these checks (they are findings themselves), and the limits under `[tool.shape]` in `pyproject.toml` aren't raised to make a change pass. If a rule seems wrong for your case, say so in the PR.

**Printing.** Only the entry points (`cli.py`, `__main__.py`) and the Cursor hook script (which answers Cursor on stdout) may call `print()`: they are listed in `output_modules` under `[tool.shape]`. Everywhere else, write to the terminal with rich's `console` and log with loguru's `logger`.

**Catching every error.** `except Exception` must log with `logger.exception(...)` (it keeps the traceback); `logger.error(f"... {e}")` doesn't count. The few functions that deliberately catch everything without a traceback (a loop that must keep running, a health check whose failure is the result) are listed with a reason in `[tool.shape.error_boundaries]` in `pyproject.toml`. That list is under CODEOWNERS review and is never for debt: a new catch-all is fixed in the code.

**Who approves rule changes.** `.github/CODEOWNERS` makes the maintainer (`@emanuilo`) the owner of the files that set the rules: `pyproject.toml`, the baseline, the hooks and the CI workflow.

**Unused code that isn't.** If the unused-code check (vulture) reports a name that a library uses by reflection (e.g. uvicorn reading `Server.should_exit`), add it to `ignore_names` under `[tool.vulture]` in `pyproject.toml`, with a one-line reason. Make sure nothing could call it first: unused code is usually really unused. Agents ask a human before adding a line.

Expand Down
4 changes: 2 additions & 2 deletions memclaw/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ async def start(self, *, include_backend: bool = True):
except Exception as exc:
# E.g. OpenAI unreachable. The bot still works; the background
# sync (or the next start) indexes what's missing.
logger.warning("Index sync at startup failed: {exc}", exc=exc)
logger.exception("Index sync at startup failed: {exc}", exc=exc)
if include_backend:
await self.backend.on_agent_start(self._tools)
self._backend_started = True
Expand Down Expand Up @@ -171,7 +171,7 @@ async def build_context(
except Exception as exc:
# E.g. OpenAI unreachable: answer without memories rather than
# failing the message. memory_search reports its own errors.
logger.warning("Context memory search failed: {exc}", exc=exc)
logger.exception("Context memory search failed: {exc}", exc=exc)
results = []
results = [
r for r in results if Path(r.file_path).name != self.config.memory_file.name
Expand Down
4 changes: 2 additions & 2 deletions memclaw/backends/claude/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ async def _connect(
await client.connect()
return client
except Exception as exc:
logger.warning(
logger.exception(
"Could not resume Claude session {id} ({exc}); starting a fresh one",
id=resume, exc=exc,
)
Expand All @@ -176,7 +176,7 @@ async def _disconnect(session: _Session) -> None:
try:
await client.disconnect()
except Exception as exc:
logger.warning("Error while disconnecting Claude CLI: {exc}", exc=exc)
logger.exception("Error while disconnecting Claude CLI: {exc}", exc=exc)

async def reset(self, session_key: str) -> None:
session = self._sessions.get(session_key)
Expand Down
2 changes: 1 addition & 1 deletion memclaw/backends/cursor/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,4 @@ async def close(self) -> None:
try:
await agent.close()
except Exception as exc:
logger.warning("Error while closing Cursor agent: {exc}", exc=exc)
logger.exception("Error while closing Cursor agent: {exc}", exc=exc)
2 changes: 1 addition & 1 deletion memclaw/backends/cursor/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,4 @@ async def drop(self, client: Any) -> None:
try:
await client.aclose()
except Exception as exc:
logger.warning("Error while closing the Cursor SDK bridge: {exc}", exc=exc)
logger.exception("Error while closing the Cursor SDK bridge: {exc}", exc=exc)
4 changes: 2 additions & 2 deletions memclaw/backends/mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ def build_memclaw_mcp_server(executor: "ToolExecutor") -> Server:
for defn in TOOL_DEFINITIONS
]

@server.list_tools() # type: ignore[untyped-decorator]
@server.list_tools()
async def list_tools() -> list[Tool]:
return cached_tools

@server.call_tool() # type: ignore[untyped-decorator]
@server.call_tool()
async def call_tool(name: str, arguments: dict[str, Any]) -> CallToolResult:
if name not in tool_names:
raise ValueError(f"Tool {name!r} not found")
Expand Down
2 changes: 1 addition & 1 deletion memclaw/backends/model_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async def _model_info(self, model_id: str) -> ModelInfo | None:
try:
await self.list_models()
except Exception as exc:
logger.warning("Could not fetch the {b} model list: {exc}", b=self._label, exc=exc)
logger.exception("Could not fetch the {b} model list: {exc}", b=self._label, exc=exc)
return None
return next((m for m in self._models if m.id == model_id), None)

Expand Down
2 changes: 1 addition & 1 deletion memclaw/bot/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async def load_models(backend: AgentBackend) -> list:
try:
return await backend.list_models()
except Exception as exc:
logger.warning("Could not fetch the model list: {exc}", exc=exc)
logger.exception("Could not fetch the model list: {exc}", exc=exc)
return []


Expand Down
4 changes: 2 additions & 2 deletions memclaw/bot/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def extract_urls(self, text: str) -> list[str]:
if parsed.scheme and parsed.netloc and url not in seen:
seen.add(url)
cleaned.append(url)
except Exception:
except ValueError: # urlparse rejects e.g. a malformed IPv6 host
continue
return cleaned

Expand Down Expand Up @@ -89,7 +89,7 @@ async def summarize(self, content: str, url: str) -> str | None:
{"role": "user", "content": f"Summarize content from {url}:\n\n{content}"},
])
except Exception as exc:
logger.warning("summarize failed for {url}: {exc}", url=url, exc=exc)
logger.exception("summarize failed for {url}: {exc}", url=url, exc=exc)
return None

async def process_links(self, text: str) -> list[dict]:
Expand Down
4 changes: 2 additions & 2 deletions memclaw/bot/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ async def _download_slack_file(self, file_info: dict) -> bytes | None:
resp.raise_for_status()
return resp.content
except Exception as exc:
logger.error("Failed to download Slack file: {exc}", exc=exc)
logger.exception("Failed to download Slack file: {exc}", exc=exc)
return None

async def _upload_and_share_image(self, thread: _Thread, image_path: str, caption: str | None = None):
Expand All @@ -220,7 +220,7 @@ async def _upload_and_share_image(self, thread: _Thread, image_path: str, captio
)
logger.debug("Uploaded image to Slack: {r}", r=result.get("ok"))
except Exception as exc:
logger.error("Failed to upload image to Slack: {exc}", exc=exc)
logger.exception("Failed to upload image to Slack: {exc}", exc=exc)

async def _send_response(self, thread: _Thread, response_text: str, found_images: list[dict]):
"""Send agent response: images first, then text."""
Expand Down
2 changes: 1 addition & 1 deletion memclaw/bot/telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ async def _send_response(
caption=img.get("caption") or None,
)
except Exception as e:
logger.error(f"Failed to send image {img.get('file_id')}: {e}")
logger.exception(f"Failed to send image {img.get('file_id')}: {e}")

if response_text:
try:
Expand Down
8 changes: 4 additions & 4 deletions memclaw/bot/whatsapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ async def _handle_image(self, cli: NewAClient, ev: MessageEv):
try:
image_bytes = await cli.download_any(ev.Message)
except Exception as exc:
logger.error("Failed to download WhatsApp image: {exc}", exc=exc)
logger.exception("Failed to download WhatsApp image: {exc}", exc=exc)
await cli.reply_message("Sorry, I couldn't download that image.", ev)
return

Expand All @@ -154,7 +154,7 @@ async def _handle_audio(self, cli: NewAClient, ev: MessageEv):
try:
audio_bytes = await cli.download_any(ev.Message)
except Exception as exc:
logger.error("Failed to download WhatsApp audio: {exc}", exc=exc)
logger.exception("Failed to download WhatsApp audio: {exc}", exc=exc)
await cli.reply_message("Sorry, I couldn't download that audio message.", ev)
return

Expand Down Expand Up @@ -195,7 +195,7 @@ async def _send_response(
try:
await cli.send_message(chat, response_text)
except Exception as exc:
logger.error("Failed to send WhatsApp message: {exc}", exc=exc)
logger.exception("Failed to send WhatsApp message: {exc}", exc=exc)

@staticmethod
async def _send_image(cli: NewAClient, chat, img: dict) -> str:
Expand All @@ -209,7 +209,7 @@ async def _send_image(cli: NewAClient, chat, img: dict) -> str:
try:
await cli.send_image(chat, media_ref, caption=img.get("caption") or None)
except Exception as exc:
logger.error("Failed to send WhatsApp image: {exc}", exc=exc)
logger.exception("Failed to send WhatsApp image: {exc}", exc=exc)
return ""

# ── Lifecycle ────────────────────────────────────────────────────
Expand Down
2 changes: 1 addition & 1 deletion memclaw/memory/consolidation.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ async def consolidate(self, *, force: bool = False, since: date | None = None) -
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)
logger.exception("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}",
Expand Down
8 changes: 4 additions & 4 deletions memclaw/memory/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ async def get_embeddings(self, texts: list[str]) -> list[np.ndarray]:

# Compute content hashes and check cache
hashes = [hashlib.sha256(t.encode()).hexdigest() for t in texts]
results: list[np.ndarray | None] = [None] * len(texts)
found: dict[int, np.ndarray] = {}
uncached_indices: list[int] = []

for i, h in enumerate(hashes):
Expand All @@ -183,7 +183,7 @@ async def get_embeddings(self, texts: list[str]) -> list[np.ndarray]:
(h, model),
).fetchone()
if row is not None:
results[i] = self.deserialize_embedding(row[0])
found[i] = self.deserialize_embedding(row[0])
else:
uncached_indices.append(i)

Expand All @@ -194,14 +194,14 @@ async def get_embeddings(self, texts: list[str]) -> list[np.ndarray]:
new_embeddings = [np.array(v, dtype=np.float32) for v in vectors]

for idx, emb in zip(uncached_indices, new_embeddings):
results[idx] = emb
found[idx] = emb
self.db.execute(
"INSERT OR REPLACE INTO embedding_cache (content_hash, embedding, model) VALUES (?, ?, ?)",
(hashes[idx], self.serialize_embedding(emb), model),
)
self.db.commit()

return results # type: ignore[return-value]
return [found[i] for i in range(len(texts))]

async def get_embedding(self, text: str) -> np.ndarray:
results = await self.get_embeddings([text])
Expand Down
4 changes: 2 additions & 2 deletions memclaw/memory/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def _combine(
combined: list[tuple[int, float, str]] = []
for cid in set(v_scores) | set(k_scores):
final = vw * v_scores.get(cid, 0.0) + tw * k_scores.get(cid, 0.0)
combined.append((cid, final, _match_type(cid in v_scores, cid in k_scores)))
combined.append((cid, final, _match_type(in_vector=cid in v_scores, in_keyword=cid in k_scores)))
combined.sort(key=lambda x: x[1], reverse=True)
return combined

Expand Down Expand Up @@ -303,7 +303,7 @@ def _normalise(vector_hits: list[tuple[int, float]]) -> dict[int, float]:
}


def _match_type(in_vector: bool, in_keyword: bool) -> str:
def _match_type(*, in_vector: bool, in_keyword: bool) -> str:
if in_vector and in_keyword:
return "hybrid"
return "vector" if in_vector else "keyword"
5 changes: 1 addition & 4 deletions memclaw/reminders.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,7 @@ async def _run(self):
raise
except Exception as exc:
logger.exception("Reminder tick failed: {exc}", exc=exc)
try:
await asyncio.sleep(self.poll_interval)
except asyncio.CancelledError:
raise
await asyncio.sleep(self.poll_interval)

async def _tick(self):
now = datetime.now()
Expand Down
4 changes: 2 additions & 2 deletions memclaw/setup/wizard.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def run_setup(config: MemclawConfig, *, reconfigure: bool = False) -> None:
either way -- it depends only on the chosen platform.
"""
existing = read_env_file()
_print_intro(reconfigure)
_print_intro(reconfigure=reconfigure)

# Start from any previously-saved values so platform-scoped keys we don't
# prompt for this round (because the user picked a different platform) are
Expand All @@ -181,7 +181,7 @@ def run_setup(config: MemclawConfig, *, reconfigure: bool = False) -> None:
check_openai(values.get("OPENAI_API_KEY"), console)


def _print_intro(reconfigure: bool) -> None:
def _print_intro(*, reconfigure: bool) -> None:
if reconfigure:
console.print(
Panel(
Expand Down
2 changes: 1 addition & 1 deletion memclaw/tools/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,6 @@ async def index_written(ctx: ToolContext, path: Path) -> str:
try:
await ctx.index.index_file(path)
except Exception as exc:
logger.warning("Indexing {p} failed, will retry on next sync: {exc}", p=path, exc=exc)
logger.exception("Indexing {p} failed, will retry on next sync: {exc}", p=path, exc=exc)
return " (search indexing is delayed; it will be searchable soon)"
return ""
3 changes: 3 additions & 0 deletions memclaw/tools/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from typing import Any

from loguru import logger

from .catalog import find_tool
from .context import ToolContext

Expand All @@ -26,4 +28,5 @@ async def execute(self, name: str, tool_input: dict[str, Any]) -> str:
try:
return await tool.run(self.context, tool_input)
except Exception as e:
logger.exception("Tool {name} failed: {exc}", name=name, exc=e)
return f"Error executing {name}: {e}"
Loading
Loading