Skip to content

refactor(cli): cli.py only parses and dispatches (code-shape 5/5) - #22

Merged
emanuilo merged 8 commits into
mainfrom
refactor/5-thin-cli
Nov 22, 2026
Merged

emanuilo merged 8 commits into
mainfrom
refactor/5-thin-cli

Conversation

@emanuilo

Copy link
Copy Markdown
Owner

Summary

Stack 5/5 of the code-shape restructuring (base: #21). cli.py only reads arguments and dispatches; each command's logic lives with its feature.

 memclaw/cli.py              316 → 182 lines, imports 7 → 5 (backends, bot, config, memory, setup)
-  terminal chat loop, save/search/index/consolidate/status logic, builds MemclawAgent for consolidate
+  parse args → one feature call per command → print
+memclaw/bot/terminal.py     terminal chat, registered in PLATFORMS ("terminal"); wizard reads it from the registry
+memclaw/memory/vault.py     MemoryVault: notes + index together, one method per command (save, search, index, consolidate)
 memclaw/sessions.py
+  ChatSessions: session key, saved session, queued reminders, /new   (out of MemclawAgent)
 memclaw/backends/
-  run_turn(10 arguments)
+  run_turn(request: TurnRequest, tool_executor)
+  status_rows(config), configuration_problem(config)
-  claude_models.ModelInfo  → model_selection.ModelInfo
memclaw status
  cli.status
    MemoryStore.status_rows()
    MemoryIndex.status_rows()
    bot.status_rows(config)
    backends.status_rows(config)

memclaw consolidate
  cli.consolidate
    MemoryVault.consolidate(...)     Consolidator(store, index, backends.build_backend())   (no MemclawAgent)

Config: kit fan-out limit lowered 12 → 8 ([tool.shape.limits], own commit).

Evidence

  • 44 scenarios, old (2d87ba3) vs new, fake HOME/backend/embeddings: every --help, status (empty, filled, Cursor), save, search, index, consolidate (nothing to do, bad --since, real run, rerun, failing sync), backend/credential errors, terminal chat over piped stdin (/new, failing turn, exit, Ctrl-D), Telegram/Slack without tokens. Compared stdout, stderr, exit codes and vault files.
    Only differences:
    • Before: memclaw save|search|index without an OpenAI key → openai.AuthenticationError traceback (and save wrote the note first).
      After: Error: OPENAI_API_KEY is not set. / Run memclaw configure to set it.; nothing written.
    • Log source of the failed-index-sync warning: memclaw.memory.vault instead of memclaw.agent.
  • code-shape: MemclawAgent attributes 17 → 12, _handle locals 18 → 14, largest fan-out 9 → 8, baseline 24 → 18 (79 at the start of the stack).
  • pytest: 567 passed, 20 skipped (was 526). ruff, lint-imports (11 contracts), code-shape check clean.

Merge Danger

Door: two-way

Blast Radius: CLI + custom backends

  • One intended visible change: the missing-OpenAI-key error for save/search/index.
  • Custom backends implement run_turn(request, tool_executor); ModelInfo moved to memclaw.backends.model_selection. Both in docs/upgrading.md.
  • WhatsApp start-up wasn't run end to end (it pairs over the network without credentials); only its dispatch moved, covered by tests.
  • Remaining debt (18 baseline entries) is mostly in backends/claude.py, backends/cursor.py, cursor_sdk_adapter.collect_run_result and tools.py.
  • Stacked on refactor: memory/ and setup/ packages (code-shape 4/5) #21; merge bottom-up.

🤖 Generated with Claude Code

…rminal.py

The chat loop that `memclaw` runs when no chat app is chosen lived in
cli.py (_interactive). It is now memclaw/bot/terminal.py with a
run(config) like the other platforms, registered in PLATFORMS as
"terminal" ("Terminal chat"):

- cli starts every platform the same way: bot.chosen_platform(config)
  picks the one MEMCLAW_PLATFORM names, and the terminal when it is empty
  or unknown (as before; DEFAULT_PLATFORM).
- The setup wizard lists the platforms straight from the registry; the
  hand-added ("terminal", "Terminal chat") entry is gone. Same list, same
  order, same default.
- bot.log_to() without a file logs to the terminal only, which is what
  the chat loop set up by hand.

Guards: the platforms-via-registry and chat-platforms-independent
contracts now cover memclaw.bot.terminal too.

Same chat: banner, "Syncing index..." / "Thinking..." spinners, /new,
/quit, exit, Ctrl-D, the error line on a failed turn and the goodbye are
unchanged. Tests: tests/bot/test_terminal.py drives the loop with a fake
agent, and checks the registry and the fallback to the terminal.
…lives with its feature

cli.py was 316 lines holding the terminal chat (moved out in the previous
commit) and the save/search/index/consolidate/status logic. Now each
command is a few lines that call the owning code:

- save, search, index, consolidate: memclaw.memory.MemoryVault
  (memory/vault.py), the notes and the index opened together, one method
  per command (save, search, reindex, sync_or_warn, consolidate). It sits
  on top of the memory package's layers.
- consolidate no longer builds a whole MemclawAgent (tools, sessions,
  reminders) to reach agent.consolidator: MemoryVault.consolidate makes a
  Consolidator from the store, the index and backends.build_backend().
- status: each part reports its own rows. MemoryStore.status_rows() and
  MemoryIndex.status_rows() join the backends' status_rows(); bot and
  backends offer status_rows(config) for the platform and the chosen
  backend. cli prints them in the same order.
- The "is the backend usable" check is backends.configuration_problem()
  (the message, or None); cli prints it.
- doctor: setup.run_doctor() probes and prints the report; memclaw.setup
  exports it instead of print_probe_report.

cli.py: 179 lines (was 316), imports 5 memclaw modules (was 7; no more
agent or openai_client).

Guards: memory.vault joins the memory-via-package contract and the
memory-layers contract (its own top layer).

Same output: --help and every subcommand's --help, status (Claude,
Cursor, a platform set), save, search, index, consolidate (nothing to
do, a bad --since, a run, a failing index sync), the backend and OpenAI
key errors, the terminal chat and the Telegram/Slack start-up errors
print the same text and leave the same files as before, run old vs new
with a fake backend in a fake HOME. The one difference is where a log
line comes from: the failed index sync before consolidating is logged
by memclaw.memory.vault instead of memclaw.agent, with the same text.

Tests: tests/test_cli.py (was test_cli_status.py) runs the commands,
tests/memory/test_vault.py covers MemoryVault and the status rows.
…d of a traceback

Without an OpenAI key the three commands reached the OpenAI API with an
empty key and died with an openai.AuthenticationError traceback; `save`
had already written the note by then, so running it again after setting
the key saved it twice.

Now they check the key first and stop with the message `consolidate`,
`doctor` and the bare `memclaw` already print:

    Error: OPENAI_API_KEY is not set.
    Run memclaw configure to set it.

Nothing is written (no note, no index). Tests: tests/test_cli.py.
…e model switching

ModelInfo (a model a credential can use, as /model lists it) is shared by
both backends, but lived in claude_models.py, the Claude model discovery
call. So the Cursor backend imported a Claude module just for the type,
which made it the module with the most memclaw imports (9).

It now sits in model_selection.py with the /model and /effort state that
uses it; claude_models.py, claude.py, cursor.py and base.py import it from
there. The Cursor backend is down to 8 memclaw imports. Library code that
imported memclaw.backends.claude_models.ModelInfo still finds it there
(claude_models imports it), but the home is model_selection.

Baseline tightened (cursor.py 604 -> 603 lines). Tests import ModelInfo
from model_selection.
The kit's default lets a module import up to 12 others. memclaw's most
connected modules now import 8 (agent, the Cursor backend) and cli 5
(it was 12 when the kit was adopted), so [tool.shape.limits] holds
fan_out at 8, as the code-shape review suggested once cli was thin.

A deliberate config change, and a stricter one: nothing is over it, so
the baseline gains no entry. CONTRIBUTING.md says what the limit is.
…ments

AgentBackend.run_turn took system_prompt, context, user_message,
tool_executor, session_key, resume_session_id, image_b64,
image_media_type, max_turns and on_tool, repeated in the protocol and in
both backends, so adding a field meant editing every signature.

The message and how to run it are now one dataclass, TurnRequest
(backends/base.py, exported by memclaw.backends next to TurnResult), with
each field's meaning written on it once. run_turn(request, tool_executor)
keeps the tool executor apart: it answers the tool calls, it isn't part
of the message. The agent builds the request; the Claude and Cursor
backends read it. Same values, same defaults.

Baseline tightened: the three run_turn too-many-args entries and the
Cursor run_turn's too-many-locals are gone; claude.py 775 -> 762 lines,
cursor.py 603 -> 590, their classes 13 lines shorter.

Tests: the backends' tests build a TurnRequest; the agent tests' fake
backend records the same fields as before.
…s in sessions.py

MemclawAgent kept five things about each chat's conversation next to the
memory, tools and backend wiring: the saved sessions, the instructions
fingerprint, the reminders a chat hasn't seen, the /new counters and the
session-key rule. That made it 17 attributes (limit 12) and _handle 18
local variables (limit 15).

They are now ChatSessions (memclaw/sessions.py, next to SessionStore,
which it uses for sessions.json):

- key(chat_id): `<platform>:<chat id>`, or "cli" for the terminal.
- add_note / reset: a delivered reminder; /new.
- begin(chat_id) -> TurnStart: the saved session to resume, the queued
  notes and the /new count as a turn starts; saw_other() says whether the
  session saw another AGENTS.md / MEMORY.md.
- finish(turn, session_id, agents_hash=, memory_hash=): drop the notes
  the turn carried, save the session unless a /new overtook the turn.

agent.sessions is the ChatSessions now (saved(key) replaces
sessions.get(key, agent._fingerprint)). The platform and scheduler the
agent only passed on to the tool executor are no longer kept on it.

Baseline tightened: MemclawAgent's attributes (now 12) and _handle's
locals (now 14) are within the limits, so both entries are gone.

Same behaviour: same session keys, the same sessions.json, the same
notes kept or dropped, /new during a turn still wins; test_agent.py
passes unchanged and the terminal chat prints the same as before.
Tests: tests/test_sessions.py covers ChatSessions on its own.
docs/memory-architecture.md says where the bookkeeping lives.
@emanuilo
emanuilo force-pushed the refactor/5-thin-cli branch from d87a5c5 to 9404950 Compare November 22, 2026 19:34
@emanuilo
emanuilo changed the base branch from refactor/4-packages to main November 22, 2026 19:34
@emanuilo emanuilo closed this Nov 22, 2026
@emanuilo emanuilo reopened this Nov 22, 2026
@emanuilo
emanuilo merged commit 89f6ca8 into main Nov 22, 2026
10 checks passed
@emanuilo
emanuilo deleted the refactor/5-thin-cli branch November 22, 2026 20:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant