Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(cli): add ask, context, symbol and why as adapters over the MCP tools (#1411)

Raghav Chamadiya686bc1346a4b
diff --git a/README.md b/README.md
index 1cc491070..78f321e65 100644
--- a/README.md
+++ b/README.md
@@ -729,6 +729,10 @@ repowise serve [PATH] # MCP server + local dashboard
repowise update [PATH] # incremental update (seconds; --workspace for every repo)
repowise watch # auto-sync daemon, re-index on file change
repowise search "<q>" # search the wiki (fulltext / semantic / symbol)
+repowise ask "<q>" # a synthesized answer with citations
+repowise context <files> # triage card: layer, hotspot, fix history, freshness
+repowise symbol <id> # one symbol's body, with verified line bounds
+repowise why <q|path> # decisions, rationale, git archaeology
repowise health # code-health KPIs and lowest-scoring files
repowise risk main..HEAD # score a branch or PR range for defect risk
repowise impacted-tests # only the tests a diff actually exercises
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 4a714361f..44ba7a634 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -422,6 +422,7 @@ Search wiki pages by keyword, meaning, or symbol name.
| `--repo` | Scope to a specific workspace repo by alias |
| `--all` | Fan out across every workspace repo and merge results |
| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
+| `--format` | `table` (default) or `json` |
```bash
repowise search "rate limiting"
@@ -431,9 +432,145 @@ repowise search "rate limit" --repo backend # workspace, one repo
repowise search "rate limit" --all # workspace, fan-out
```
-For question answering and synthesized explanations (not keyword lookup), use
-the MCP `get_answer` tool from your editor, or the **Chat** tab in the web UI
-(`repowise serve`), there is no dedicated CLI command for this.
+For a synthesized answer rather than a keyword lookup, use `repowise ask`.
+
+---
+
+### `repowise ask QUESTION`
+
+Answer a question about the codebase, with citations. The same synthesis the
+`get_answer` MCP tool performs: hybrid retrieval followed by an LLM answer over
+what it found, so this command costs an LLM call where the other query commands
+do not.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--scope` | Restrict retrieval to a path prefix (e.g. `packages/cli/`) |
+
+```bash
+repowise ask "how does the retry backoff work?"
+repowise ask "where is the session cookie set?" --format json
+repowise ask "how is width resolved?" --scope packages/cli/
+repowise ask "why is auth split across two modules?" --full
+```
+
+`confidence: high` is content-grounded, so it can be cited directly. A
+low-confidence answer returns `best_guesses` (a file plus why it is in the
+running) instead of an empty one.
+
+---
+
+### `repowise context TARGETS...`
+
+Triage card for files, modules or symbols: title, summary, architectural layer,
+hotspot and bug-fix history, doc freshness, and the shape of the verified
+skeleton. Relationships and risk signals, not source bytes. Batch targets in one
+call.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--include` | Opt-in block, repeatable: `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `skeleton` |
+| `--no-compact` | Add structure, imports and docstrings to each card |
+
+```bash
+repowise context src/api/routes.py src/api/auth.py
+repowise context src/api/routes.py::login --include callers --include metrics
+repowise context src/api/routes.py --full # includes the skeleton source
+```
+
+The skeleton's *text* is the bulk of the underlying payload, so the default
+reports its size and coverage and `--full` carries the source.
+
+---
+
+### `repowise symbol SYMBOL_ID`
+
+Read one function, class or constant with live-verified line bounds. `source`
+arrives in the same line-numbered format a file read produces; `verified: true`
+means the bounds were checked against the live file.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--context-lines` | Extra lines before and after the body (0-50) |
+| `--query` | Omission refs only: regex or substring filter on the restored lines |
+
+```bash
+repowise symbol "src/api/routes.py::login"
+repowise symbol "src/api/routes.py:140-180" # live range read
+repowise symbol "repowise#a1b2c3d4e5f6" # a distill omission ref
+```
+
+An ambiguous id (overloads, re-exports) returns every matching body rather than
+silently picking one. A truncated body carries a `continuation` you can pass
+straight back to `repowise symbol`.
+
+---
+
+### `repowise why [QUERY]`
+
+Why the code is shaped this way: decision records, rationale and git
+archaeology. Worth running before a refactor or a deliberate divergence from a
+pattern.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--target` | File path to anchor the search to. Repeatable |
+
+```bash
+repowise why "why is auth using JWT?" # question
+repowise why src/api/auth.py # governing decisions + origin story
+repowise why "why the retry cap?" --target src/api/client.py
+repowise why # decision health dashboard
+```
+
+Falls back to git archaeology when a path has no decisions, so it is never
+empty.
+
+---
+
+### Shared options: `ask`, `context`, `symbol`, `why`
+
+These four are thin adapters over the MCP tools of the same name, so they share
+one option block.
+
+| Flag | Description |
+|------|-------------|
+| `--path` | Repo (or workspace) root. Defaults to the current directory |
+| `--repo` | Workspace repo alias to query |
+| `--no-workspace` | Force single-repo mode even inside a workspace |
+| `--format` | `table` (default) or `json` |
+| `--full` | Emit the complete tool payload as JSON (implies `--format json`) |
+
+The repo is `--path` here rather than the trailing positional `[PATH]` the older
+commands take: `context` accepts a variadic list of targets, which would swallow
+a trailing path.
+
+`--format json` emits a **trimmed CLI projection**, not the tool's whole
+response. What each one keeps and drops is documented on the `project()`
+function in its command module. `--full` returns the raw dict, which is what an
+editor's MCP client receives. Measured on this repository:
+
+| Command | trimmed | `--full` |
+|---------|--------:|---------:|
+| `ask` | 3.4 KB | 19.5 KB |
+| `context` (one file) | 0.9 KB | 12.4 KB |
+| `why` (question) | 10.4 KB | 20.9 KB |
+| `why` (path) | 10.4 KB | 28.5 KB |
+| `symbol` | 0.7 KB | 1.0 KB |
+
+`symbol` barely moves because its payload *is* its answer — only the call
+envelope is dropped. Nothing that changes the *answer* is ever trimmed: an
+error, a not-found, a did-you-mean list, a truncation marker, a continuation
+token, and the ambiguity signals all survive at every format. `ask` reports the
+names of the heavy blocks it left out in `dropped_blocks`.
---
diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.md
index e908bbb7c..c8a225639 100644
--- a/docs/start/USER_GUIDE.md
+++ b/docs/start/USER_GUIDE.md
@@ -152,6 +152,10 @@ Grouped by what you are trying to do. Every flag for every command lives in the
| Command | What it is for |
|---|---|
| `repowise search "<q>"` | Search the wiki. `--mode fulltext\|semantic\|symbol`. |
+| `repowise ask "<q>"` | A synthesized answer with citations and a confidence rating. Costs an LLM call. |
+| `repowise context <files>` | Triage card per file: layer, hotspot, bug-fix history, doc freshness. |
+| `repowise symbol "<file>::<Name>"` | One symbol's body with live-verified line bounds. |
+| `repowise why "<q>"` | Decisions and rationale behind the shape of the code. A path gets its origin story; no argument gets the decision health dashboard. |
| `repowise health` | Lowest-scoring files and why. `--trend` for direction, `--refactoring-targets` for concrete plans. |
| `repowise risk main..HEAD` | Defect risk for a commit or range, scored 0-10. |
| `repowise dead-code` | What nothing references any more, by confidence tier. |
diff --git a/packages/cli/src/repowise/cli/commands/_tool_adapters.py b/packages/cli/src/repowise/cli/commands/_tool_adapters.py
new file mode 100644
index 000000000..d44f279a2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/_tool_adapters.py
@@ -0,0 +1,249 @@
+"""Shared plumbing for the four MCP-tool adapter commands.
+
+``ask``, ``context``, ``symbol`` and ``why`` all do the same three things
+before they differ: resolve one indexed repo, decide whether the caller wants
+the CLI projection or the raw tool dict, and emit a document even when there is
+nothing to say. This module owns those three so the four commands stay thin.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli.output import emit_json, format_option, full_option
+from repowise.cli.output import notice_console as _notices
+
+
+def target_options(fn: Callable) -> Callable:
+ """The ``--path --repo --no-workspace --format --full`` option block.
+
+ The repo is an option here rather than the trailing positional ``PATH``
+ the older commands take. ``context`` accepts a variadic list of targets,
+ which would swallow a trailing path, and on the other three a bare second
+ positional would be ambiguous with the query. One spelling across the four
+ adapters beats matching a convention only three of them could keep.
+
+ Applied bottom-up the way Click stacks decorators, so the resulting
+ ``--help`` lists them in the order written here.
+ """
+ for decorate in reversed(
+ (
+ click.option(
+ "--path",
+ "path",
+ default=None,
+ type=click.Path(exists=True, file_okay=False),
+ help="Repo (or workspace) root. Defaults to the current directory.",
+ ),
+ click.option(
+ "--repo",
+ "repo_alias",
+ default=None,
+ help="Workspace repo alias to query (implies workspace mode).",
+ ),
+ click.option(
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+ ),
+ format_option(),
+ full_option(),
+ )
+ ):
+ fn = decorate(fn)
+ return fn
+
+
+def resolve_format_for(fmt: str, full: bool) -> str:
+ """``--full`` implies json: the raw tool dict has no table rendering."""
+ return "json" if full else fmt
+
+
+def resolve_indexed_repo(
+ *,
+ path: str | None,
+ repo_alias: str | None,
+ no_workspace: bool,
+ fmt: str,
+ command: str,
+) -> Path:
+ """The one repo these commands run against, or a ``ClickException``.
+
+ Workspace mode picks a single repo rather than fanning out: the tools are
+ single-repo by construction (see ``tool_bridge``), so ``--repo <alias>``
+ selects whose resources get wired and the primary repo is the default.
+ """
+ from repowise.cli.helpers import resolve_command_target
+
+ target = resolve_command_target(
+ path=path,
+ no_workspace_flag=no_workspace,
+ repo_alias=repo_alias,
+ )
+ target.notice(_notices(fmt), command=command)
+
+ if target.is_workspace:
+ if target.repo_filter is not None:
+ picked = target.resolve_repo_alias(target.repo_filter)
+ if picked is None:
+ raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")
+ repo_path = picked
+ else:
+ primary = target.primary_path()
+ if primary is None:
+ raise click.ClickException("Workspace has no primary repo configured.")
+ repo_path = primary
+ else:
+ assert target.repo_path is not None
+ repo_path = target.repo_path
+
+ from repowise.cli.helpers import REPOWISE_DIR
+
+ if not (repo_path / REPOWISE_DIR).is_dir():
+ raise click.ClickException(
+ f"{repo_path} is not indexed. Run 'repowise init' there first."
+ )
+ return repo_path
+
+
+def emit_full(payload: dict) -> None:
+ """``--full``: the raw tool dict, and a non-zero exit if it is an error.
+
+ Same rule as :func:`emit_error` — the document is always emitted, and the
+ status still tells the truth. ``--full`` is exactly the spelling a script
+ reaches for, so this is the path where a failed lookup exiting 0 would do
+ the most damage.
+ """
+ emit_json(payload)
+ if payload.get("error"):
+ raise click.exceptions.Exit(1)
+
+
+def run(repo_path: Path, factory: Callable[[], Awaitable[dict]], tool_name: str) -> dict:
+ """Await one tool coroutine with this repo's resources published.
+
+ Logs are silenced here rather than on the format option, because these
+ four commands need it at *every* format. ``format_option``'s callback only
+ fires for a machine-readable format, and ``ask`` synthesises through an LLM
+ provider that emits three structlog debug lines per call — on stdout, where
+ structlog's unconfigured default writes. That corrupts the JSON document,
+ but it also lands three timestamped lines in the middle of the human answer
+ and inside anything reading it through ``repowise distill``. A tool call's
+ own logs are never any of these commands' output.
+ """
+ from repowise.cli.helpers import silence_logs_for_machine_output
+ from repowise.cli.tool_bridge import call_tool
+
+ silence_logs_for_machine_output()
+ return call_tool(repo_path, factory, tool_name)
+
+
+#: MCP tool name -> the CLI command that now does the same thing.
+#:
+#: The tools write their hints for an agent holding the MCP surface, so a
+#: not-found from ``get_symbol`` reads "Use get_context to list available
+#: symbols" — advice naming something a CLI user cannot run. Rewriting the
+#: names is cheaper and more honest than forking the messages.
+_TOOL_TO_COMMAND = {
+ "get_answer": "repowise ask",
+ "get_context": "repowise context",
+ "get_symbol": "repowise symbol",
+ "get_why": "repowise why",
+ "search_codebase": "repowise search",
+}
+
+
+def as_cli_prose(text: str) -> str:
+ """Rewrite MCP tool names in a message meant for a human at a terminal.
+
+ Applied only on the table path. A JSON consumer is reading the tool's own
+ projection and is better served by the tool's own vocabulary, so the
+ payload keeps the names it was given.
+ """
+ for tool, command in _TOOL_TO_COMMAND.items():
+ text = text.replace(tool, command)
+ return text
+
+
+#: Keys the tools attach *beside* ``error`` to make it recoverable.
+#:
+#: ``suggestions`` is ``get_symbol``'s did-you-mean list, and its error message
+#: literally ends "retry with one of these exact symbol_ids" — dropping the
+#: list leaves a message pointing at nothing. ``remedy`` and ``guidance`` come
+#: from the failure shield's shaped responses (an unindexed repo, an unknown
+#: alias) and are the only part of those that says what to do.
+_ERROR_COMPANIONS = ("suggestions", "remedy", "guidance")
+
+
+def emit_error(payload: dict, fmt: str, *, extra: dict | None = None) -> None:
+ """Render a tool's ``error`` key, if it has one, and exit non-zero.
+
+ Every early return owes stdout a document — a json path that exits with
+ only a stderr notice is indistinguishable from a crash to whatever is
+ reading the pipe. Having emitted it, the command still exits non-zero:
+ ``symbol`` on a name that does not exist is a failed lookup, and a script
+ that only checks the exit code must not read it as a hit.
+ """
+ error = payload.get("error")
+ if not error:
+ return
+ companions = {key: payload[key] for key in _ERROR_COMPANIONS if payload.get(key)}
+ if fmt == "json":
+ emit_json({**(extra or {}), "error": error, **companions})
+ else:
+ notices = _notices(fmt)
+ notices.print(f"[red]{as_cli_prose(str(error))}[/red]")
+ for value in companions.get("suggestions") or []:
+ notices.print(f" [cyan]{value}[/cyan]")
+ for key in ("remedy", "guidance"):
+ if companions.get(key):
+ notices.print(f"[dim]{as_cli_prose(str(companions[key]))}[/dim]")
+ raise click.exceptions.Exit(1)
+
+
+def index_note(payload: dict) -> dict[str, Any]:
+ """The freshness bits of a tool's ``_meta``, as the projections carry them.
+
+ ``_meta`` is otherwise dropped from a projection: ``timing_ms`` and the
+ token accounting describe the call, not the answer. What survives is the
+ part that tells a caller whether to trust it.
+ """
+ meta = payload.get("_meta") or {}
+ note: dict[str, Any] = {}
+ for key in ("indexed_commit", "live_head", "index_behind", "index_age_days"):
+ if key in meta:
+ note[key] = meta[key]
+ if meta.get("stale_warning"):
+ note["stale_warning"] = meta["stale_warning"]
+ return note
+
+
+def print_index_note(payload: dict, fmt: str) -> None:
+ """Say so on the human path when the index is behind or stale."""
+ meta = payload.get("_meta") or {}
+ notices = _notices(fmt)
+ if meta.get("stale_warning"):
+ notices.print(f"[yellow]{meta['stale_warning']}[/yellow]")
+ elif meta.get("index_behind"):
+ notices.print(
+ f"[dim]Index is behind HEAD: indexed {meta.get('indexed_commit', '?')}, "
+ f"now {meta.get('live_head', '?')}. Run 'repowise update' to resync.[/dim]"
+ )
+
+
+__all__ = [
+ "as_cli_prose",
+ "emit_error",
+ "emit_full",
+ "index_note",
+ "print_index_note",
+ "resolve_format_for",
+ "resolve_indexed_repo",
+ "run",
+ "target_options",
+]
diff --git a/packages/cli/src/repowise/cli/commands/ask_cmd.py b/packages/cli/src/repowise/cli/commands/ask_cmd.py
new file mode 100644
index 000000000..9fa9c54ee
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/ask_cmd.py
@@ -0,0 +1,241 @@
+"""``repowise ask`` — the CLI adapter over the ``get_answer`` MCP tool."""
+
+from __future__ import annotations
+
+import click
+
+from repowise.cli.commands import _tool_adapters as _ta
+from repowise.cli.output import emit_json
+
+#: The heavy blocks the trim drops, reported by name in ``dropped_blocks``.
+#:
+#: Each is answer-adjacent material the tool has already consumed into the
+#: answer — a 1,500-char excerpt per retrieval hit, full symbol bodies, mined
+#: rationale comments — and together they are most of the payload. Naming them
+#: rather than silently removing them is what keeps ``note``'s references
+#: meaningful and tells a caller that ``--full`` has more.
+_DROPPED_BLOCKS = (
+ "retrieval",
+ "candidates",
+ "symbol_bodies",
+ "code_rationale",
+ "more_definitions",
+ "flow_path",
+)
+
+
+def project(payload: dict, question: str) -> dict:
+ """``get_answer``'s dict, trimmed to what a CLI caller reads.
+
+ Field mapping, kept explicit because the session-cost bake-off cites it:
+
+ ================== ===========================================
+ kept answer, confidence, grounding,
+ retrieval_quality, citations, quotes,
+ fallback_targets, best_guesses (without their
+ excerpts), next_action_hint, note,
+ omission_marker, episodes (subject / recorded
+ / still_true), error, index (from ``_meta``)
+ dropped every block in ``_DROPPED_BLOCKS`` — but
+ their names are reported in
+ ``dropped_blocks``, so nothing is silent —
+ and the timing half of ``_meta``
+ ================== ===========================================
+
+ ``quotes`` survives the trim although ``retrieval`` does not: it is the
+ literal source line behind a claim at ~120 chars a row, which is what makes
+ the answer checkable, while ``retrieval`` is the material synthesis already
+ consumed. ``--full`` returns everything.
+ """
+ out: dict = {
+ "question": question,
+ "answer": payload.get("answer", ""),
+ "confidence": payload.get("confidence", ""),
+ "retrieval_quality": payload.get("retrieval_quality", ""),
+ "citations": list(payload.get("citations") or []),
+ }
+ quotes = payload.get("quotes") or []
+ if quotes:
+ out["quotes"] = [
+ {
+ "path": q.get("path", ""),
+ "lines": q.get("lines"),
+ "quote": q.get("quote", ""),
+ }
+ for q in quotes
+ ]
+ # Present when confidence is low: one-line guesses instead of an empty
+ # answer, and the files to read if none of them lands. Each guess carries
+ # the candidate page's whole ``excerpt`` — the same 1,500-char blocks
+ # dropped from ``retrieval``, and on a low-confidence answer there are
+ # several of them, so the abstain path would otherwise be the *largest*
+ # payload this command emits. The justification and the score are what
+ # make the guess actionable; the excerpt is one `context` call away.
+ if payload.get("best_guesses"):
+ out["best_guesses"] = [
+ {
+ "file": g.get("file", ""),
+ "why_relevant": g.get("why_relevant", ""),
+ "score": g.get("score"),
+ }
+ for g in payload["best_guesses"]
+ ]
+ # ``note`` and ``next_action_hint`` say what to do next, and ``grounding``
+ # is a trust axis in its own right ("extracted" is content-grounded, so it
+ # can be cited without a verifying read).
+ for key in ("grounding", "next_action_hint", "note", "omission_marker"):
+ if payload.get(key):
+ out[key] = payload[key]
+ # ``note`` names the blocks it wants read — "symbol_bodies carries the full
+ # live body", "code_rationale may already answer the question". Keeping the
+ # note while dropping what it points at leaves a dangling instruction, so
+ # say which of them the tool returned and where to get them.
+ dropped = [key for key in _DROPPED_BLOCKS if payload.get(key)]
+ if dropped:
+ out["dropped_blocks"] = dropped
+ if payload.get("fallback_targets"):
+ out["fallback_targets"] = list(payload["fallback_targets"])
+ episodes = payload.get("episodes") or []
+ if episodes:
+ out["episodes"] = [
+ {
+ "subject": e.get("subject", ""),
+ "recorded": e.get("recorded", ""),
+ "still_true": e.get("still_true", ""),
+ }
+ for e in episodes
+ ]
+ note = _ta.index_note(payload)
+ if note:
+ out["index"] = note
+ return out
+
+
[email protected]("question")
+ "--scope",
+ default=None,
+ help='Restrict retrieval to a path prefix (e.g. "packages/cli/").',
+)
+@_ta.target_options
+def ask_command(
+ question: str,
+ scope: str | None,
+ path: str | None,
+ repo_alias: str | None,
+ no_workspace: bool,
+ fmt: str,
+ full: bool,
+) -> None:
+ """Answer a question about this codebase, with citations.
+
+ The same synthesis the get_answer MCP tool performs: hybrid retrieval
+ followed by an LLM answer over what it found, so this command costs an
+ LLM call where the other read-only commands do not.
+ """
+ fmt = _ta.resolve_format_for(fmt, full)
+ repo_path = _ta.resolve_indexed_repo(
+ path=path,
+ repo_alias=repo_alias,
+ no_workspace=no_workspace,
+ fmt=fmt,
+ command="ask",
+ )
+
+ def _factory():
+ from repowise.server.mcp_server.tool_answer import get_answer
+
+ return get_answer(question=question, scope=scope)
+
+ payload = _ta.run(repo_path, _factory, "get_answer")
+
+ if full:
+ _ta.emit_full(payload)
+ return
+ _ta.emit_error(payload, fmt, extra={"question": question})
+ projected = project(payload, question)
+ if fmt == "json":
+ emit_json(projected)
+ return
+ _render(projected)
+ _ta.print_index_note(payload, fmt)
+
+
+def _render(projected: dict) -> None:
+ from repowise.cli.helpers import console
+
+ answer = projected.get("answer") or ""
+ if answer:
+ # click.echo, not rich Markdown. The answer is already markdown, and
+ # rendering it centres and pads every heading to the console width —
+ # which phase 1 deliberately set to 400 for a non-TTY, so a piped
+ # answer would carry hundreds of chars of padding per heading and lose
+ # the markdown a caller may want to keep. Echoing the source is the
+ # exact bytes, greppable, and reads fine in a terminal.
+ click.echo(answer)
+ else:
+ console.print("[yellow]No answer synthesised for that question.[/yellow]")
+
+ confidence = projected.get("confidence") or "?"
+ quality = projected.get("retrieval_quality") or "?"
+ colour = {"high": "green", "medium": "yellow"}.get(confidence, "red")
+ grounding = projected.get("grounding")
+ console.print(
+ f"\n[{colour}]confidence: {confidence}[/{colour}] [dim]retrieval: {quality}"
+ + (f" grounding: {grounding}" if grounding else "")
+ + "[/dim]"
+ )
+ if projected.get("note"):
+ # The value-grounding gate ("the numbers may be synthesised, read X
+ # before citing one") and the degraded-retrieval reason live only
+ # here, so a table path that skips it drops the caveat on the answer.
+ console.print(f"[dim]{_ta.as_cli_prose(str(projected['note']))}[/dim]")
+ if projected.get("dropped_blocks"):
+ console.print(
+ f"[dim]Not shown: {', '.join(projected['dropped_blocks'])}. "
+ "Pass --full for them.[/dim]"
+ )
+ if projected.get("omission_marker"):
+ # Printed as-is and escaped: the marker carries its own "restore:
+ # repowise expand <ref>" instruction, and it opens with a bracket,
+ # which rich would parse as a style tag and delete outright.
+ from rich.markup import escape
+
+ console.print(escape(str(projected["omission_marker"])), style="cyan")
+
+ guesses = projected.get("best_guesses") or []
+ if guesses:
+ console.print("\n[bold]Best guesses[/bold]")
+ for g in guesses:
+ console.print(
+ f" [cyan]{g.get('file', '')}[/cyan] [dim]({g.get('score', '?')})[/dim] "
+ f"{g.get('why_relevant', '')}"
+ )
+ if projected.get("next_action_hint"):
+ # The tools write their hints for an agent holding the MCP surface, so
+ # names like get_context land in front of someone who cannot run one.
+ console.print(f"\n[bold]Next[/bold] {_ta.as_cli_prose(projected['next_action_hint'])}")
+
+ for label, key in (("Citations", "citations"), ("Read next", "fallback_targets")):
+ values = projected.get(key) or []
+ if values:
+ console.print(f"\n[bold]{label}[/bold]")
+ for value in values:
+ console.print(f" {value}")
+
+ quotes = projected.get("quotes") or []
+ if quotes:
+ console.print("\n[bold]Evidence[/bold]")
+ for q in quotes:
+ lines = q.get("lines") or []
+ where = f":{lines[0]}" if lines else ""
+ console.print(f" [cyan]{q.get('path', '')}{where}[/cyan] {q.get('quote', '')}")
+
+ episodes = projected.get("episodes") or []
+ if episodes:
+ console.print("\n[bold]Recorded about this checkout[/bold]")
+ for e in episodes:
+ console.print(f" {e.get('subject', '')}: {e.get('recorded', '')}")
+ if e.get("still_true"):
+ console.print(f" [dim]{e['still_true']}[/dim]")
diff --git a/packages/cli/src/repowise/cli/commands/context_cmd.py b/packages/cli/src/repowise/cli/commands/context_cmd.py
new file mode 100644
index 000000000..4fda37ee0
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/context_cmd.py
@@ -0,0 +1,351 @@
+"""``repowise context`` — the CLI adapter over the ``get_context`` MCP tool."""
+
+from __future__ import annotations
+
+import click
+
+from repowise.cli.commands import _tool_adapters as _ta
+from repowise.cli.output import emit_json
+
+#: ``include`` blocks the tool accepts, as ``--include`` choices.
+_INCLUDE_BLOCKS = (
+ "full_doc",
+ "ownership",
+ "last_change",
+ "callers",
+ "callees",
+ "metrics",
+ "community",
+ "decisions",
+ "health",
+ "skeleton",
+)
+
+#: Card keys the projection replaces or drops. Everything else passes through.
+#:
+#: A denylist, not an allowlist. Most of what a card carries is opt-in: nine
+#: ``--include`` blocks, each landing under its own key, and an allowlist that
+#: misses one turns ``--include ownership`` into a flag that changes nothing
+#: the caller can see. The failure mode of a denylist is a payload slightly
+#: larger than intended; the failure mode of an allowlist is a silently
+#: discarded answer, and that is the whole risk this trim carries.
+_REPLACED_KEYS = frozenset(
+ {
+ # Placed by hand above the sweep.
+ "target",
+ "type",
+ "docs",
+ "hotspot",
+ "fix_history",
+ "episodes",
+ # Folded into flatter keys.
+ "architectural_layer",
+ "freshness",
+ # Replaced by its shape, without its ~10K-char text.
+ "skeleton",
+ # A breadcrumb to the wiki page the card came from, not a signal.
+ "parent_page",
+ }
+)
+
+#: The two ``docs`` keys the card lifts to the top level. Everything else under
+#: ``docs`` stays: for a **symbol** target the whole card lives there
+#: (``signature``, ``docstring``, ``used_by``, ``candidates``), and for a file
+#: target it holds ``symbols`` — the list a caller pipes into ``repowise
+#: symbol`` — plus ``content_md``/``documentation`` when ``--include full_doc``
+#: asked for them. Denylisting ``docs`` wholesale projected a symbol target to
+#: an empty card and made ``--include full_doc`` an inert flag.
+_LIFTED_DOC_KEYS = ("title", "summary")
+
+
+def _project_one(card: dict) -> dict:
+ """One target's triage card, trimmed."""
+ out: dict = {"target": card.get("target", "")}
+ if card.get("type"):
+ out["type"] = card["type"]
+ if card.get("error"):
+ # A target the tool could not resolve gets a card carrying only this.
+ # Trimming it away leaves an empty card, which reads as "indexed, but
+ # nothing to say" rather than "that path does not exist". A tombstone
+ # (a page deleted or renamed after indexing) carries the redirect
+ # beside the error, which is the whole point of the tombstone.
+ out["error"] = card["error"]
+ for key in ("successor_paths", "hint"):
+ if card.get(key):
+ out[key] = card[key]
+ return out
+ docs = card.get("docs") or {}
+ for key in _LIFTED_DOC_KEYS:
+ if docs.get(key):
+ out[key] = docs[key]
+ rest = {k: v for k, v in docs.items() if k not in _LIFTED_DOC_KEYS and v not in (None, [], {}, "")}
+ if rest:
+ out["docs"] = rest
+ layer = card.get("architectural_layer") or {}
+ if layer.get("name"):
+ out["layer"] = layer["name"]
+ if card.get("hotspot"):
+ out["hotspot"] = True
+ if card.get("fix_history"):
+ out["fix_history"] = card["fix_history"]
+ freshness = card.get("freshness") or {}
+ # ``is_stale`` is None when the tool could not judge; reporting that as
+ # False would say "these docs are current" on no evidence.
+ if freshness.get("is_stale") is not None:
+ out["stale"] = bool(freshness["is_stale"])
+ if card.get("episodes"):
+ out["episodes"] = card["episodes"]
+ # Everything else the card carries, including every --include block. A
+ # block the caller asked for by name is never trimmed: they paid a flag
+ # for it.
+ for key, value in card.items():
+ if key not in _REPLACED_KEYS and key not in out and value not in (None, [], {}, ""):
+ out[key] = value
+ skeleton = card.get("skeleton") or {}
+ if skeleton:
+ # The skeleton *text* is the bulk of get_context's payload — 10K chars
+ # for one file — and it is source a caller can also get from `symbol`
+ # or a plain Read. The card keeps its shape and size so a caller can
+ # decide whether to pay for it; --full carries the text.
+ out["skeleton"] = {
+ "mode": skeleton.get("mode", ""),
+ "tokens": skeleton.get("tokens"),
+ "full_tokens": skeleton.get("full_tokens"),
+ "pct_of_full": skeleton.get("pct_of_full"),
+ "verified": skeleton.get("verified"),
+ "bodies_kept": skeleton.get("bodies_kept") or [],
+ }
+ return out
+
+
+def project(payload: dict, targets: tuple[str, ...]) -> dict:
+ """``get_context``'s dict, trimmed to the triage card itself.
+
+ Field mapping, per target:
+
+ ================== ===========================================
+ kept target, type, docs.title -> title,
+ docs.summary -> summary,
+ architectural_layer.name -> layer,
+ freshness.is_stale -> stale, the skeleton's
+ shape without its ``text``, and **every other
+ key the card carries** — hotspot, fix_history,
+ episodes, and each ``--include`` block under
+ its own name
+ dropped skeleton.text (~10K chars per file, the bulk
+ of the payload), skeleton.opt_out_hint /
+ auto, parent_page,
+ freshness.confidence_score, ``_meta`` minus
+ its freshness keys
+ ================== ===========================================
+
+ A target the tool could not resolve gets a card carrying only ``error``,
+ and that key survives the trim. Top-level ``truncated`` /
+ ``dropped_targets`` / ``dropped_symbols`` are kept whenever they say
+ something — a silently dropped target is exactly the thing a caller must
+ not have to diff two payloads to notice.
+ """
+ cards = payload.get("targets") or {}
+ out: dict = {
+ "targets": {key: _project_one(card) for key, card in cards.items()},
+ }
+ if payload.get("truncated"):
+ out["truncated"] = True
+ for key in ("dropped_targets", "dropped_symbols", "omission_marker"):
+ # omission_marker is the only handle on what truncation banked, so a
+ # `truncated: true` without it says content went missing and offers no
+ # way to get it back.
+ if payload.get(key):
+ out[key] = payload[key]
+ # Requested but absent from the response at all: neither a card nor a
+ # recorded drop. Without this a typo'd path is indistinguishable from a
+ # path the index simply has nothing to say about.
+ missing = [t for t in targets if t not in cards and t not in (payload.get("dropped_targets") or [])]
+ if missing:
+ out["not_found"] = missing
+ note = _ta.index_note(payload)
+ if note:
+ out["index"] = note
+ return out
+
+
[email protected]("targets", nargs=-1, required=True)
+ "--include",
+ "include",
+ multiple=True,
+ type=click.Choice(_INCLUDE_BLOCKS),
+ help="Opt-in blocks to add. Repeatable.",
+)
+ "--no-compact",
+ is_flag=True,
+ default=False,
+ help="Add structure, imports and docstrings to each card.",
+)
+@_ta.target_options
+def context_command(
+ targets: tuple[str, ...],
+ include: tuple[str, ...],
+ no_compact: bool,
+ path: str | None,
+ repo_alias: str | None,
+ no_workspace: bool,
+ fmt: str,
+ full: bool,
+) -> None:
+ """Triage card for files, modules or symbols.
+
+ TARGETS are file paths, module paths, or "path/to/file.py::Symbol" ids.
+ Batch them in one call. Relationships and risk signals, not source bytes:
+ pass --full for the verified skeleton, or use 'repowise symbol' for one
+ body.
+ """
+ fmt = _ta.resolve_format_for(fmt, full)
+ repo_path = _ta.resolve_indexed_repo(
+ path=path,
+ repo_alias=repo_alias,
+ no_workspace=no_workspace,
+ fmt=fmt,
+ command="context",
+ )
+
+ def _factory():
+ from repowise.server.mcp_server.tool_context import get_context
+
+ return get_context(
+ targets=list(targets),
+ include=list(include) or None,
+ compact=not no_compact,
+ )
+
+ payload = _ta.run(repo_path, _factory, "get_context")
+
+ if full:
+ _ta.emit_full(payload)
+ return
+ _ta.emit_error(payload, fmt, extra={"targets": list(targets)})
+ projected = project(payload, targets)
+ if fmt == "json":
+ emit_json(projected)
+ return
+ _render(projected)
+ _ta.print_index_note(payload, fmt)
+
+
+def _render(projected: dict) -> None:
+ from rich.markup import escape
+ from rich.table import Table
+
+ from repowise.cli.helpers import console
+
+ cards = projected.get("targets") or {}
+ if not cards:
+ console.print("[yellow]No context for those targets.[/yellow]")
+
+ for card in cards.values():
+ if card.get("error"):
+ console.print(
+ f"[yellow]{escape(str(card.get('target', '')))}: "
+ f"{escape(_ta.as_cli_prose(str(card['error'])))}[/yellow]"
+ )
+ if card.get("hint"):
+ console.print(f" [dim]{escape(_ta.as_cli_prose(str(card['hint'])))}[/dim]")
+ for successor in card.get("successor_paths") or []:
+ console.print(f" [cyan]{successor}[/cyan]")
+ continue
+ table = Table(title=card.get("target", ""), show_header=False)
+ table.add_column("Field", style="cyan")
+ table.add_column("Value")
+ for label, key in (
+ ("Type", "type"),
+ ("Title", "title"),
+ ("Summary", "summary"),
+ ("Layer", "layer"),
+ ):
+ if card.get(key):
+ # Every cell here is tool text. Rich markup-parses a cell, so a
+ # summary containing `list[str]` renders as `list` and a stray
+ # `[/x]` raises MarkupError and takes the command down.
+ table.add_row(label, escape(str(card[key])))
+ signals = []
+ if card.get("hotspot"):
+ signals.append("hotspot")
+ fix = card.get("fix_history") or {}
+ if fix.get("fix_count"):
+ magnet = " (bug magnet)" if fix.get("bug_magnet") else ""
+ signals.append(
+ f"{fix['fix_count']} bug fixes, last {fix.get('last_fix_days_ago', '?')}d ago{magnet}"
+ )
+ if card.get("stale"):
+ signals.append("docs stale")
+ if card.get("episodes"):
+ signals.append(f"{card['episodes']} episodes")
+ if signals:
+ table.add_row("Signals", ", ".join(signals))
+ skeleton = card.get("skeleton") or {}
+ if skeleton:
+ table.add_row(
+ "Skeleton",
+ f"{skeleton.get('mode', '?')}, {skeleton.get('tokens', '?')} of "
+ f"{skeleton.get('full_tokens', '?')} tokens "
+ f"({skeleton.get('pct_of_full', '?')}% of full) — pass --full for the text",
+ )
+ if card.get("decision_records"):
+ table.add_row(
+ "Decision records",
+ escape(", ".join(str(v) for v in card["decision_records"])),
+ )
+ # Every remaining block, including each --include the caller asked
+ # for by name. Rendering only the ones this function happens to know
+ # about is how `--include ownership` ends up printing nothing at all.
+ for key, value in card.items():
+ if key in _RENDERED_KEYS:
+ continue
+ table.add_row(key.replace("_", " ").title(), escape(_flatten(value)))
+ console.print(table)
+
+ for label, key in (
+ ("Not found", "not_found"),
+ ("Dropped", "dropped_targets"),
+ ):
+ if projected.get(key):
+ console.print(f"[yellow]{label}: {escape(', '.join(projected[key]))}[/yellow]")
+ if projected.get("truncated"):
+ console.print("[yellow]Response was truncated to fit the tool's budget.[/yellow]")
+ marker = projected.get("omission_marker")
+ if marker:
+ # Printed as-is: the marker already reads
+ # "[repowise#<ref>: N lines omitted; restore: repowise expand <ref>]",
+ # so it carries its own instruction — and it opens with a bracket,
+ # which rich would parse as a style tag and delete outright.
+ console.print(escape(str(marker)), style="cyan")
+
+
+#: Card keys ``_render`` has already placed by hand, by the time it sweeps the
+#: rest. Everything not listed here is rendered generically rather than dropped.
+_RENDERED_KEYS = frozenset(
+ {
+ "target",
+ "type",
+ "title",
+ "summary",
+ "layer",
+ "hotspot",
+ "fix_history",
+ "stale",
+ "episodes",
+ "skeleton",
+ "decision_records",
+ }
+)
+
+
+def _flatten(value: object) -> str:
+ """One cell for an arbitrary block a caller opted into with ``--include``."""
+ if isinstance(value, dict):
+ return ", ".join(f"{k}: {_flatten(v)}" for k, v in value.items())
+ if isinstance(value, list):
+ return ", ".join(_flatten(v) for v in value)
+ return str(value)
diff --git a/packages/cli/src/repowise/cli/commands/symbol_cmd.py b/packages/cli/src/repowise/cli/commands/symbol_cmd.py
new file mode 100644
index 000000000..778ff2c1b
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/symbol_cmd.py
@@ -0,0 +1,204 @@
+"""``repowise symbol`` — the CLI adapter over the ``get_symbol`` MCP tool."""
+
+from __future__ import annotations
+
+import click
+
+from repowise.cli.commands import _tool_adapters as _ta
+from repowise.cli.output import emit_json
+
+#: Everything the tool returns except ``_meta``, in the order it returns it.
+#: ``get_symbol`` is the one tool whose payload is already its answer — the
+#: source body — so the projection is the whole dict minus the call envelope,
+#: not a selection from it. Keys absent from a given response are skipped.
+_KEPT = (
+ "symbol_id",
+ "file",
+ "name",
+ "kind",
+ "qualified_name",
+ "signature",
+ "language",
+ "start_line",
+ "end_line",
+ "symbol_start_line",
+ "symbol_end_line",
+ "total_lines",
+ "bounds",
+ "verified",
+ "source",
+ "truncated",
+ "continuation",
+ "candidates",
+ "ambiguous",
+ "match_count",
+ "resolution",
+ "suggestions",
+ "fallback_lines",
+ "note",
+ # Omission-ref reads ("repowise#<hex>") return a different shape entirely:
+ # ``content`` is the banked text and ``source`` is the *command* it came
+ # from, not a body. Keeping ``source`` without ``content`` would print the
+ # provenance label where the content should be.
+ "ref",
+ "content",
+ "original_tokens",
+ "created_at",
+ "query",
+)
+
+
+def project(payload: dict) -> dict:
+ """``get_symbol``'s dict, minus ``_meta``.
+
+ Field mapping:
+
+ ================== ===========================================
+ kept every key in ``_KEPT`` that is present,
+ across all three response shapes this tool
+ has — a symbol body, an omission-ref read,
+ and an ambiguous or not-found card — plus
+ ``index`` from the freshness half of ``_meta``
+ dropped ``_meta``'s timing and token accounting
+ ================== ===========================================
+
+ Nothing else is trimmed on purpose. Dropping ``candidates`` would silently
+ pick one of an ambiguous id's bodies, ``continuation`` would make a
+ truncated body un-continuable, ``suggestions`` would leave a did-you-mean
+ error pointing at nothing, and ``content`` would make an omission-ref read
+ return its provenance label instead of the text it banked. All four change
+ the answer rather than its size.
+ """
+ out = {key: payload[key] for key in _KEPT if key in payload}
+ note = _ta.index_note(payload)
+ if note:
+ out["index"] = note
+ return out
+
+
[email protected]("symbol_id")
+ "--context-lines",
+ type=click.IntRange(0, 50),
+ default=0,
+ help="Extra lines before and after the body.",
+)
+ "--query",
+ default=None,
+ help="Omission refs only: regex or substring filter on the restored lines.",
+)
+@_ta.target_options
+def symbol_command(
+ symbol_id: str,
+ context_lines: int,
+ query: str | None,
+ path: str | None,
+ repo_alias: str | None,
+ no_workspace: bool,
+ fmt: str,
+ full: bool,
+) -> None:
+ """Read one symbol's body with live-verified line bounds.
+
+ SYMBOL_ID is "path/to/file.py::Name" (as 'repowise context' reports it),
+ "path/to/file.py:140-180" for a live range read, or a "repowise#<hex>"
+ omission ref from a distilled command.
+ """
+ fmt = _ta.resolve_format_for(fmt, full)
+ repo_path = _ta.resolve_indexed_repo(
+ path=path,
+ repo_alias=repo_alias,
+ no_workspace=no_workspace,
+ fmt=fmt,
+ command="symbol",
+ )
+
+ def _factory():
+ from repowise.server.mcp_server.tool_symbol import get_symbol
+
+ return get_symbol(
+ symbol_id=symbol_id,
+ context_lines=context_lines,
+ query=query,
+ )
+
+ payload = _ta.run(repo_path, _factory, "get_symbol")
+
+ if full:
+ _ta.emit_full(payload)
+ return
+ _ta.emit_error(payload, fmt, extra={"symbol_id": symbol_id})
+ projected = project(payload)
+ if fmt == "json":
+ emit_json(projected)
+ return
+ _render(projected)
+ _ta.print_index_note(payload, fmt)
+
+
+def _render(projected: dict) -> None:
+ from repowise.cli.helpers import console
+
+ if projected.get("kind") == "omission":
+ # A "repowise#<hex>" read: ``content`` is the banked text and ``source``
+ # is the command it came from. Nothing here is a symbol body.
+ console.print(
+ f"[cyan]{projected.get('ref', '')}[/cyan] [dim]banked from "
+ f"{projected.get('source') or '?'}"
+ + (f", {projected['original_tokens']} tokens" if projected.get("original_tokens") else "")
+ + (f", {projected['created_at']}" if projected.get("created_at") else "")
+ + "[/dim]"
+ )
+ _echo_lines(projected.get("content") or "")
+ if projected.get("note"):
+ console.print(f"[dim]{_ta.as_cli_prose(str(projected['note']))}[/dim]")
+ return
+
+ candidates = projected.get("candidates") or []
+ if candidates:
+ console.print(
+ f"[yellow]{len(candidates)} symbols match that id — showing all.[/yellow]"
+ )
+ for candidate in candidates:
+ _render_body(console, candidate)
+ return
+ _render_body(console, projected)
+
+
+def _echo_lines(text: str) -> None:
+ """Print source verbatim: no markup, no highlighting, and no wrapping.
+
+ ``console.print`` word-wraps to the console width even with
+ ``markup=False``, and the width is 400 for a non-TTY. A source line longer
+ than that comes back split across rows with its `` 1 `` prefix stranded
+ on the first one, which is not the file. ``click.echo`` is the exact bytes;
+ ``expand`` prints its restored content the same way.
+ """
+ if text:
+ click.echo(text)
+
+
+def _render_body(console, body: dict) -> None:
+ where = body.get("file", "")
+ start, end = body.get("start_line"), body.get("end_line")
+ if start is not None:
+ where = f"{where}:{start}-{end}"
+ verified = "verified" if body.get("verified") else body.get("bounds") or "unverified"
+ console.print(f"[cyan]{body.get('qualified_name') or body.get('name') or ''}[/cyan] "
+ f"[dim]{body.get('kind', '')} · {where} · {verified}[/dim]")
+ _echo_lines(body.get("source") or "")
+ for line in body.get("fallback_lines") or []:
+ _echo_lines(str(line))
+ if body.get("note"):
+ console.print(f"[dim]{_ta.as_cli_prose(str(body['note']))}[/dim]")
+ if body.get("truncated"):
+ continuation = body.get("continuation")
+ if continuation:
+ console.print(
+ "[yellow]Body truncated.[/yellow] Continue with: "
+ f"[cyan]repowise symbol {continuation}[/cyan]"
+ )
+ else:
+ console.print("[yellow]Body truncated.[/yellow]")
diff --git a/packages/cli/src/repowise/cli/commands/why_cmd.py b/packages/cli/src/repowise/cli/commands/why_cmd.py
new file mode 100644
index 000000000..bc4b2f872
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/why_cmd.py
@@ -0,0 +1,472 @@
+"""``repowise why`` — the CLI adapter over the ``get_why`` MCP tool."""
+
+from __future__ import annotations
+
+import click
+
+from repowise.cli.commands import _tool_adapters as _ta
+from repowise.cli.output import emit_json
+
+#: How many entries of a long list survive the trim. The tool already ranks
+#: them, so a head is the cheapest honest cut — and the count it was cut from
+#: travels beside it so a caller knows there is more.
+_LIST_CAP = 5
+
+
+def _capped(values: list, cap: int = _LIST_CAP) -> list:
+ return list(values or [])[:cap]
+
+
+def _project_decision(decision: dict) -> dict:
+ """One decision record, trimmed to the decision and why it was taken."""
+ out = {
+ "id": decision.get("id", ""),
+ "title": decision.get("title", ""),
+ "status": decision.get("status", ""),
+ "decision": decision.get("decision", ""),
+ "rationale": decision.get("rationale", ""),
+ }
+ files = decision.get("affected_files") or []
+ if files:
+ out["affected_files"] = _capped(files)
+ total = decision.get("affected_files_total", len(files))
+ if total > len(out["affected_files"]):
+ out["affected_files_total"] = total
+ if decision.get("still_true"):
+ out["still_true"] = decision["still_true"]
+ return out
+
+
+def _project_episode(episode: dict) -> dict:
+ return {
+ "kind": episode.get("kind", ""),
+ "subject": episode.get("subject", ""),
+ "recorded": episode.get("recorded", ""),
+ "evidence": episode.get("evidence", ""),
+ "still_true": episode.get("still_true", ""),
+ }
+
+
+_ARCH_LAYERS = (
+ ("file_commits", ("sha", "date", "author", "message")),
+ ("git_log", ("sha", "date", "author", "message")),
+ ("cross_references", ("source_file", "sha", "date", "message")),
+)
+
+
+def _project_archaeology(arch: dict) -> dict:
+ """The git-history fallback, capped per layer, each with its total.
+
+ Three layers: the file's own significant commits and the cross-references
+ (10 each from the tool), and a live ``git log`` (20). The summary line
+ survives whole — it is the one sentence that says a file is ungoverned and
+ what was recovered instead. Every cap reports what it cut, the way every
+ other capped list in this module does; a head with no total is how "5 of
+ 18" reads as "18".
+ """
+ out: dict = {}
+ if arch.get("summary"):
+ out["summary"] = arch["summary"]
+ for key, fields in _ARCH_LAYERS:
+ rows = arch.get(key) or []
+ if not rows:
+ continue
+ out[key] = [{f: c.get(f, "") for f in fields} for c in _capped(rows)]
+ if len(rows) > len(out[key]):
+ out[f"{key}_total"] = len(rows)
+ return out
+
+
+def _project_target_entry(entry: dict) -> dict:
+ """One ``--target``'s card: its governing decisions, origin and fallback.
+
+ Recursively the same trim as the top level — the per-target ``origin``
+ carries the same ~2K-char prose ``summary`` and the per-target
+ ``git_archaeology`` the same three capped layers.
+ """
+ out: dict = {"governing_decisions": entry.get("governing_decisions") or []}
+ origin = entry.get("origin") or {}
+ if origin:
+ out["origin"] = {
+ key: origin[key]
+ for key in ("available", "primary_author", "total_commits", "age_days", "summary")
+ if key in origin and (key != "summary" or not origin.get("available"))
+ }
+ if entry.get("git_archaeology"):
+ out["git_archaeology"] = _project_archaeology(entry["git_archaeology"])
+ return out
+
+
+def project(payload: dict) -> dict:
+ """``get_why``'s dict, trimmed. The tool has three modes and so has this.
+
+ Common to every mode: ``mode`` survives, ``_meta`` collapses to ``index``.
+
+ ================== ===========================================
+ search mode kept query, decisions (id / title / status /
+ decision / rationale / affected_files head
+ / still_true), related_documentation
+ (title / page_type / snippet), episodes
+ (kind / subject / recorded / evidence /
+ still_true)
+ path mode kept path, alignment, decisions as above,
+ origin_story minus ``summary`` and minus
+ each key commit's ``body``, episodes,
+ truncated / omission_marker /
+ dropped_decisions, and the three blocks the
+ tool substitutes when nothing governs the
+ path: git_archaeology (summary plus the head
+ of each of its three layers), code_rationale
+ and target_context
+ dashboard kept summary, counts, and the head of each of
+ stale_decisions / proposed_awaiting_review /
+ ungoverned_hotspots / conflicts, with the
+ full count beside it
+ ================== ===========================================
+
+ Dropped throughout: a decision's ``context``, ``consequences``,
+ ``alternatives``, ``lineage``, ``confidence`` and ``staleness_score``; the
+ tail of every capped list; ``origin_story.summary`` (a ~2K-char prose
+ retelling of the key commits printed beside it) and each key commit's
+ ``body``. ``--full`` returns all of it.
+ """
+ mode = payload.get("mode", "")
+ out: dict = {"mode": mode}
+
+ if payload.get("query"):
+ out["query"] = payload["query"]
+ if payload.get("path"):
+ out["path"] = payload["path"]
+ if payload.get("summary"):
+ out["summary"] = payload["summary"]
+ if payload.get("counts"):
+ out["counts"] = payload["counts"]
+ if payload.get("alignment"):
+ out["alignment"] = payload["alignment"]
+
+ decisions = payload.get("decisions")
+ if decisions is not None:
+ out["decisions"] = [_project_decision(d) for d in _capped(decisions)]
+ total = payload.get("decisions_total", len(decisions))
+ if total > len(out["decisions"]):
+ out["decisions_total"] = total
+
+ origin = payload.get("origin_story") or {}
+ if origin:
+ out["origin_story"] = {
+ key: origin[key]
+ for key in (
+ "available",
+ "primary_author",
+ "author_commit_pct",
+ "total_commits",
+ "first_commit",
+ "last_commit",
+ "age_days",
+ )
+ if key in origin
+ }
+ commits = origin.get("key_commits") or []
+ if commits:
+ out["origin_story"]["key_commits"] = [
+ {
+ "sha": c.get("sha", ""),
+ "date": c.get("date", ""),
+ "author": c.get("author", ""),
+ "message": c.get("message", ""),
+ }
+ for c in _capped(commits)
+ ]
+
+ docs = payload.get("related_documentation")
+ if docs:
+ out["related_documentation"] = [
+ {
+ "title": d.get("title", ""),
+ "page_type": d.get("page_type", ""),
+ "snippet": d.get("snippet", ""),
+ }
+ for d in _capped(docs)
+ ]
+
+ episodes = payload.get("episodes")
+ if episodes:
+ out["episodes"] = [_project_episode(e) for e in _capped(episodes)]
+
+ # The three blocks the tool substitutes when decisions are silent. Losing
+ # them empties exactly the mode this tool exists to never leave empty:
+ # `get_why` sets git_archaeology and code_rationale *because* nothing
+ # governs the path, and target_context is the entire product of --target.
+ if payload.get("git_archaeology"):
+ out["git_archaeology"] = _project_archaeology(payload["git_archaeology"])
+ if payload.get("code_rationale"):
+ out["code_rationale"] = [
+ {k: entry.get(k) for k in ("path", "lines", "comment")}
+ for entry in _capped(payload["code_rationale"])
+ ]
+ if payload.get("target_context"):
+ out["target_context"] = {
+ target: _project_target_entry(entry)
+ for target, entry in payload["target_context"].items()
+ }
+
+ for key in ("stale_decisions", "proposed_awaiting_review", "ungoverned_hotspots", "conflicts"):
+ values = payload.get(key)
+ if values:
+ out[key] = _capped(values)
+ if len(values) > len(out[key]):
+ out[f"{key}_total"] = len(values)
+
+ if payload.get("truncated"):
+ out["truncated"] = True
+ for key in ("omission_marker", "dropped_decisions"):
+ if payload.get(key):
+ out[key] = payload[key]
+
+ note = _ta.index_note(payload)
+ if note:
+ out["index"] = note
+ return out
+
+
[email protected]("query", required=False, default=None)
+ "--target",
+ "targets",
+ multiple=True,
+ help="File path to anchor the search to. Repeatable.",
+)
+@_ta.target_options
+def why_command(
+ query: str | None,
+ targets: tuple[str, ...],
+ path: str | None,
+ repo_alias: str | None,
+ no_workspace: bool,
+ fmt: str,
+ full: bool,
+) -> None:
+ """Why the code is shaped this way: decisions, rationale, git archaeology.
+
+ QUERY is a question ("why is auth using JWT?"), a file path (its governing
+ decisions, origin story and alignment score), or omitted for the decision
+ health dashboard. Falls back to git archaeology when a path has no
+ decisions, so it is never empty.
+ """
+ fmt = _ta.resolve_format_for(fmt, full)
+ repo_path = _ta.resolve_indexed_repo(
+ path=path,
+ repo_alias=repo_alias,
+ no_workspace=no_workspace,
+ fmt=fmt,
+ command="why",
+ )
+
+ def _factory():
+ from repowise.server.mcp_server.tool_why import get_why
+
+ return get_why(query=query, targets=list(targets) or None)
+
+ payload = _ta.run(repo_path, _factory, "get_why")
+
+ if full:
+ _ta.emit_full(payload)
+ return
+ _ta.emit_error(payload, fmt, extra={"query": query})
+ projected = project(payload)
+ if fmt == "json":
+ emit_json(projected)
+ return
+ _render(projected)
+ _ta.print_index_note(payload, fmt)
+
+
+def _render(projected: dict) -> None:
+ from rich.table import Table
+
+ from repowise.cli.helpers import console
+
+ if projected.get("summary"):
+ console.print(f"[bold]{projected['summary']}[/bold]")
+ counts = projected.get("counts") or {}
+ if counts:
+ table = Table(title="Decision health")
+ for key in counts:
+ table.add_column(key.replace("_", " ").title(), justify="right")
+ table.add_row(*[str(v) for v in counts.values()])
+ console.print(table)
+
+ alignment = projected.get("alignment") or {}
+ if alignment:
+ console.print(
+ f"\n[bold]Alignment[/bold] {alignment.get('score', '?')} — "
+ f"{alignment.get('explanation', '')}"
+ )
+
+ decisions = projected.get("decisions") or []
+ if decisions:
+ console.print("\n[bold]Decisions[/bold]")
+ for d in decisions:
+ console.print(f" [cyan]{d.get('title', '')}[/cyan] [dim]({d.get('status', '')})[/dim]")
+ if d.get("decision"):
+ console.print(f" {d['decision']}")
+ if d.get("rationale"):
+ console.print(f" [dim]why: {d['rationale']}[/dim]")
+ if d.get("still_true"):
+ console.print(f" [dim]{d['still_true']}[/dim]")
+ if projected.get("decisions_total"):
+ console.print(
+ f" [dim]{len(decisions)} of {projected['decisions_total']} shown; "
+ f"pass --full for the rest.[/dim]"
+ )
+
+ origin = projected.get("origin_story") or {}
+ if origin.get("available"):
+ console.print(
+ f"\n[bold]Origin[/bold] {origin.get('total_commits', '?')} commits over "
+ f"{origin.get('age_days', '?')} days, mostly "
+ f"{origin.get('primary_author', '?')} "
+ f"({_owner_share(origin.get('author_commit_pct'))})"
+ )
+ for c in origin.get("key_commits") or []:
+ console.print(
+ f" [dim]{c.get('sha', '')} {str(c.get('date', ''))[:10]}[/dim] "
+ f"{c.get('message', '')}"
+ )
+
+ if projected.get("git_archaeology"):
+ console.print("")
+ _render_archaeology(console, projected["git_archaeology"], indent="")
+
+ rationale = projected.get("code_rationale") or []
+ if rationale:
+ console.print("\n[bold]Rationale comments in the code[/bold]")
+ for entry in rationale:
+ lines = entry.get("lines") or []
+ where = f":{lines[0]}" if lines else ""
+ console.print(f" [cyan]{entry.get('path', '')}{where}[/cyan]")
+ console.print(f" [dim]{entry.get('comment', '')}[/dim]")
+
+ for target, entry in (projected.get("target_context") or {}).items():
+ console.print(f"\n[bold]Target[/bold] [cyan]{target}[/cyan]")
+ for governing in entry.get("governing_decisions") or []:
+ console.print(
+ f" {governing.get('title', '')} [dim]({governing.get('status', '')})[/dim]"
+ )
+ origin = entry.get("origin") or {}
+ if origin.get("summary"):
+ # Only set when there is no git history — the short "No git history
+ # for X." line, not the long prose the projection drops.
+ console.print(f" [dim]{origin['summary']}[/dim]")
+ elif origin.get("available"):
+ console.print(
+ f" [dim]{origin.get('total_commits', '?')} commits over "
+ f"{origin.get('age_days', '?')} days, mostly "
+ f"{origin.get('primary_author', '?')}[/dim]"
+ )
+ if entry.get("git_archaeology"):
+ _render_archaeology(console, entry["git_archaeology"], indent=" ")
+
+ for label, key in (
+ ("Stale decisions", "stale_decisions"),
+ ("Proposed, awaiting review", "proposed_awaiting_review"),
+ ("Conflicts", "conflicts"),
+ ):
+ rows = projected.get(key) or []
+ if rows:
+ console.print(f"\n[bold]{label}[/bold]")
+ for row in rows:
+ console.print(f" {row.get('title', row) if isinstance(row, dict) else row}")
+ _print_more(console, projected, key, len(rows))
+
+ hotspots = projected.get("ungoverned_hotspots") or []
+ if hotspots:
+ console.print("\n[bold]Ungoverned hotspots[/bold]")
+ for hotspot in hotspots:
+ console.print(f" {hotspot}")
+ _print_more(console, projected, "ungoverned_hotspots", len(hotspots))
+
+ docs = projected.get("related_documentation") or []
+ if docs:
+ console.print("\n[bold]Related documentation[/bold]")
+ for d in docs:
+ console.print(f" [cyan]{d.get('title', '')}[/cyan] [dim]{d.get('page_type', '')}[/dim]")
+
+ episodes = projected.get("episodes") or []
+ if episodes:
+ console.print("\n[bold]Recorded about this checkout[/bold]")
+ for e in episodes:
+ console.print(f" [dim]{e.get('evidence', '')}[/dim] {e.get('subject', '')}")
+ if e.get("still_true"):
+ console.print(f" [dim]{e['still_true']}[/dim]")
+
+ # Every block this function can render. Search mode with --target sets
+ # target_context and code_rationale and none of the others, so a guard
+ # listing only the path-mode blocks printed "Nothing recorded" underneath
+ # the things it had just recorded.
+ if not any(projected.get(key) for key in _RENDERABLE_BLOCKS):
+ console.print("[yellow]Nothing recorded for that query.[/yellow]")
+
+
+#: Every key ``_render`` can put on the screen. Keeping the emptiness guard
+#: derived from one list is what stops it drifting behind a new block.
+_RENDERABLE_BLOCKS = (
+ "summary",
+ "counts",
+ "alignment",
+ "decisions",
+ "origin_story",
+ "git_archaeology",
+ "code_rationale",
+ "target_context",
+ "stale_decisions",
+ "proposed_awaiting_review",
+ "conflicts",
+ "ungoverned_hotspots",
+ "related_documentation",
+ "episodes",
+)
+
+
+def _owner_share(value: object) -> str:
+ """Render ``author_commit_pct``, which is a fraction *or* a percentage.
+
+ Its source stores either, depending on which git-metadata path filled it in
+ — ``developer_congestion`` already normalises the same field the same way.
+ Printing it raw shows a dominant author as "0.99%".
+ """
+ try:
+ pct = float(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return "?"
+ return f"{pct * 100 if pct <= 1.0 else pct:.0f}%"
+
+
+def _render_archaeology(console, arch: dict, *, indent: str) -> None:
+ """The archaeology block, at the top level or nested under one ``--target``."""
+ console.print(f"{indent}[bold]Git archaeology[/bold] {arch.get('summary', '')}")
+ for label, key in (
+ ("this file", "file_commits"),
+ ("git log", "git_log"),
+ ("mentioned by", "cross_references"),
+ ):
+ rows = arch.get(key) or []
+ for c in rows:
+ where = f" [dim]({c['source_file']})[/dim]" if c.get("source_file") else ""
+ console.print(
+ f"{indent} [dim]{label}: {str(c.get('sha', ''))[:8]} "
+ f"{str(c.get('date', ''))[:10]}[/dim] {c.get('message', '')}{where}"
+ )
+ total = arch.get(f"{key}_total")
+ if total:
+ console.print(
+ f"{indent} [dim]{len(rows)} of {total} {label} shown; "
+ f"pass --full for the rest.[/dim]"
+ )
+
+
+def _print_more(console, projected: dict, key: str, shown: int) -> None:
+ total = projected.get(f"{key}_total")
+ if total:
+ console.print(f" [dim]{shown} of {total} shown; pass --full for the rest.[/dim]")
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 549a34946..372498468 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -65,6 +65,10 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("coverage", "coverage_cmd:coverage_group"),
("impacted-tests", "impacted_tests_cmd:impacted_tests_command"),
("search", "search_cmd:search_command"),
+ ("ask", "ask_cmd:ask_command"),
+ ("context", "context_cmd:context_command"),
+ ("symbol", "symbol_cmd:symbol_command"),
+ ("why", "why_cmd:why_command"),
("distill", "distill_cmd:distill_command"),
("expand", "expand_cmd:expand_command"),
("saved", "saved_cmd:saved_command"),
diff --git a/packages/cli/src/repowise/cli/output.py b/packages/cli/src/repowise/cli/output.py
index 56e3ccf3f..07bd9d817 100644
--- a/packages/cli/src/repowise/cli/output.py
+++ b/packages/cli/src/repowise/cli/output.py
@@ -150,6 +150,31 @@ def json_option(*, help: str = "Deprecated alias for --format json.") -> Any:
)
+def full_option(*, help: str | None = None) -> Any:
+ """``--full``: emit the underlying tool payload instead of the CLI projection.
+
+ ``ask``, ``context``, ``symbol`` and ``why`` are adapters over the MCP tool
+ functions, and those return considerably more than a command needs to show
+ — ``get_context`` on two files is ~20K chars, most of it skeleton source.
+ The default is therefore a trimmed projection and the raw dict is opt-in,
+ so payload size is a switch a caller (or a benchmark) can measure both
+ sides of rather than a choice baked into the command.
+
+ A raw tool dict has no table rendering, so this implies ``--format json``.
+ It carries the same log-silencing callback as :func:`json_option` for that
+ reason: ``--full`` alone leaves ``--format`` on ``table``, so without it the
+ one payload that stays corruptible is the one asked for by name.
+ """
+ return click.option(
+ "--full",
+ "full",
+ is_flag=True,
+ default=False,
+ callback=_silence_when_alias_selects_json,
+ help=help or "Emit the complete tool payload as JSON (implies --format json).",
+ )
+
+
def resolve_format(fmt: str, as_json: bool) -> str:
"""Fold a legacy boolean alias into the ``--format`` value.
@@ -191,6 +216,7 @@ __all__ = [
"NON_TTY_WIDTH",
"emit_json",
"format_option",
+ "full_option",
"json_option",
"notice_console",
"resolve_console_width",
diff --git a/packages/cli/src/repowise/cli/tool_bridge.py b/packages/cli/src/repowise/cli/tool_bridge.py
new file mode 100644
index 000000000..ad04cd1cf
--- /dev/null
+++ b/packages/cli/src/repowise/cli/tool_bridge.py
@@ -0,0 +1,166 @@
+"""Run an MCP tool function from a CLI command, against a local repo.
+
+``mcp_tool_registry.register`` returns the decorated function unchanged — it
+only records it, and the FastMCP binding happens later at ``apply()``. So every
+tool is a plain ``async def f(...) -> dict`` that a command can await directly,
+and ``ask`` / ``context`` / ``symbol`` / ``why`` need no second implementation
+of anything the MCP server already does.
+
+The one thing a tool cannot supply itself is its resources: it reads a session
+factory, a full-text index and a vector store out of ``mcp_server._state``,
+which the MCP server's lifespan normally publishes.
+:func:`repowise.server.chat_tools.init_tool_state` is the existing publisher for
+exactly that, and this module is the CLI's caller of it — the same wiring the
+HTTP server's chat router already does, built from the same pieces
+``search_cmd`` builds its own store from.
+
+Deliberately *not* set: ``_vector_store_ready`` and ``_lancedb_ready``. Those
+are the MCP server's signals that a background load has finished, and a command
+here loads synchronously before it calls anything, so there is nothing to wait
+for. ``tool_search._wait_for_vector_state`` skips the wait when they are
+``None``, which is the state a fresh process is already in.
+
+Ceiling: single-repo only. The tools take a ``repo=`` alias resolved through a
+workspace registry the CLI does not build; ``--repo`` on these commands picks
+*which repo's* resources get wired instead, which answers the same question
+without a registry. A tool that needs cross-repo fan-out (``repo="all"``) is
+still MCP-only.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from collections.abc import Awaitable, Callable
+from pathlib import Path
+from typing import Any
+
+from repowise.cli.helpers import run_async
+
+
+async def _acall_tool(
+ repo_path: Path, factory: Callable[[], Awaitable[dict]], tool_name: str
+) -> dict:
+ """Wire tool state for *repo_path*, await ``factory()``, then tear down."""
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import FullTextSearch, create_engine
+ from repowise.server.chat_tools import init_tool_state
+ from repowise.server.mcp_server._failure_shield import _shape_exception
+
+ engine = None
+ store = None
+ # The MCP surface composes every tool as
+ # ``_savings_instrument(_failure_shield(fn))`` at ``apply()`` time, so an
+ # MCP client never sees a raw exception: a repo with a ``.repowise/``
+ # directory but no built database comes back as a shaped "no index yet,
+ # run repowise init" dict. A CLI command awaiting the tool function
+ # directly gets the undecorated one, and would print a traceback with an
+ # **empty stdout** — the state a caller cannot distinguish from a crash,
+ # which is what every early return in these commands exists to avoid.
+ #
+ # The shield covers the setup as well as the call. Resolving the DB URL,
+ # opening the store and building the embedder all touch config and disk,
+ # and a failure there is the same condition from the caller's side.
+ try:
+ engine = create_engine(get_db_url_for_repo(repo_path))
+ session_factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ store = await _open_vector_store(repo_path)
+ init_tool_state(
+ session_factory,
+ FullTextSearch(engine),
+ store,
+ # The server points both at one store: decisions live in the same
+ # table under a "decision:" namespace rather than a separate one.
+ decision_store=store,
+ repo_path=str(repo_path),
+ )
+ return await factory()
+ except Exception as exc:
+ return _shape_exception(tool_name, exc)
+ finally:
+ close = getattr(store, "close", None)
+ if close is not None:
+ # Teardown of a store the tool already answered from must not turn
+ # a good result into a traceback.
+ with contextlib.suppress(Exception):
+ await close()
+ if engine is not None:
+ with contextlib.suppress(Exception):
+ await engine.dispose()
+
+
+async def _open_vector_store(repo_path: Path) -> Any:
+ """The repo's LanceDB store, or an in-memory one when there is none.
+
+ Mirrors the MCP server's ``_load_vector_stores`` rather than
+ ``search_cmd._search_semantic``: the difference is that ``search`` decides
+ for itself whether a keyless store is worth ranking on, while the tools
+ make that judgement internally. Building the store the way the server does
+ is what keeps a CLI answer and an MCP answer the same answer.
+ """
+ from repowise.cli.helpers import REPOWISE_DIR
+ from repowise.cli.providers.embedders import build_embedder, resolve_embedder_for_repo
+ from repowise.core.persistence.vector_store import InMemoryVectorStore
+
+ requested = resolve_embedder_for_repo(repo_path)
+ embedder = build_embedder(requested)
+ _publish_embedder_status(requested, embedder)
+ lance_dir = repo_path / REPOWISE_DIR / "lancedb"
+ if lance_dir.is_dir():
+ try:
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+
+ return LanceDBVectorStore(str(lance_dir), embedder=embedder)
+ except Exception:
+ # No lancedb wheel, or an unreadable table. The tools that do not
+ # need vector search still work off the session factory and FTS,
+ # so degrade rather than refuse to run.
+ pass
+ return InMemoryVectorStore(embedder=embedder)
+
+
+def _publish_embedder_status(requested: str, embedder: Any) -> None:
+ """Record whether the embedder we got is the one the repo asked for.
+
+ ``build_meta`` reads ``_state._embedder_status`` to put ``embedder_degraded``
+ into every tool's ``_meta``, and only the MCP server's own
+ ``_resolve_embedder`` ever set it. Without this, a repo pinned to an
+ embedder whose key has gone away answers off keyless vectors and the
+ payload looks identical to a healthy one — the exact condition #306 added
+ the field for, and (per the keyless-embedder work) the common case rather
+ than the rare one.
+ """
+ from repowise.core.providers.embedding import KeylessEmbedder
+ from repowise.server.mcp_server import _state
+
+ wanted_mock = not requested or requested == "mock"
+ degraded = not wanted_mock and isinstance(embedder, KeylessEmbedder)
+ status: dict[str, Any] = {
+ "active": "mock" if isinstance(embedder, KeylessEmbedder) else requested,
+ "requested": requested or None,
+ "degraded": degraded,
+ }
+ if degraded:
+ status["reason"] = (
+ f"Configured embedder {requested!r} could not be built, so this "
+ "answer used keyless vectors and no semantic retrieval."
+ )
+ _state._embedder_status = status
+
+
+def call_tool(repo_path: Path, factory: Callable[[], Awaitable[dict]], tool_name: str) -> dict:
+ """Run one MCP tool coroutine against *repo_path* and return its dict.
+
+ *factory* is called (not awaited) inside the event loop after the tool
+ state is published, so it must be a zero-argument callable returning the
+ coroutine — building the coroutine eagerly at the call site would be
+ harmless today but would run any future eager work before the wiring.
+
+ *tool_name* names the tool in a shaped internal-error response, matching
+ what the MCP failure shield would have said.
+ """
+ return run_async(_acall_tool(repo_path, factory, tool_name))
+
+
+__all__ = ["call_tool"]
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index 5f4e6d72c..8793394a8 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -33,12 +33,13 @@ from repowise.core.registry import CLIRegistry, LazyCommand
#: command is meant to require editing it.
_EXPECTED_NAMES = frozenset(
{
- "augment", "corrections", "costs", "coverage", "dead-code", "decision",
- "delete", "distill", "doctor", "expand", "export", "generate",
- "generate-claude-md", "health", "hook", "impacted-tests", "init", "login",
- "logout", "mcp", "reindex", "restyle", "risk", "saved", "search",
- "security", "serve", "status", "telemetry", "update", "watch",
- "whats-new", "whoami", "wiki-styles", "workspace",
+ "ask", "augment", "context", "corrections", "costs", "coverage",
+ "dead-code", "decision", "delete", "distill", "doctor", "expand",
+ "export", "generate", "generate-claude-md", "health", "hook",
+ "impacted-tests", "init", "login", "logout", "mcp", "reindex", "restyle",
+ "risk", "saved", "search", "security", "serve", "status", "symbol",
+ "telemetry", "update", "watch", "whats-new", "whoami", "why",
+ "wiki-styles", "workspace",
}
) # fmt: skip
diff --git a/tests/unit/cli/test_tool_adapter_commands.py b/tests/unit/cli/test_tool_adapter_commands.py
new file mode 100644
index 000000000..5b375e6a8
--- /dev/null
+++ b/tests/unit/cli/test_tool_adapter_commands.py
@@ -0,0 +1,874 @@
+"""``ask`` / ``context`` / ``symbol`` / ``why`` — the four MCP-tool adapters.
+
+Three things have to hold and each has tests below.
+
+1. **The projection is the contract.** These commands emit a trimmed CLI
+ projection by default and the raw tool dict under ``--full``, and the
+ session-cost bake-off cites the difference. So the field mapping is pinned
+ against realistic payloads rather than described: a test that only checked
+ "some keys survived" would pass with the trim silently disabled, which is
+ the exact regression that matters.
+2. **Every exit emits a document.** A json path that returns after a stderr
+ notice leaves stdout empty, and a caller cannot tell that from a crash.
+3. **The tool is really reached.** The tool functions are imported inside each
+ command's factory, so a typo there is invisible until the command is run
+ against a real repo. ``_spy_run`` calls the factory for real and only then
+ substitutes a canned payload.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands import _tool_adapters as _ta
+from repowise.cli.commands.ask_cmd import ask_command
+from repowise.cli.commands.ask_cmd import project as project_ask
+from repowise.cli.commands.context_cmd import context_command
+from repowise.cli.commands.context_cmd import project as project_context
+from repowise.cli.commands.symbol_cmd import project as project_symbol
+from repowise.cli.commands.symbol_cmd import symbol_command
+from repowise.cli.commands.why_cmd import project as project_why
+from repowise.cli.commands.why_cmd import why_command
+
+# --------------------------------------------------------------------------
+# Payloads shaped like the real tools' responses, trimmed in breadth but not
+# in kind — every key the projections branch on is present.
+# --------------------------------------------------------------------------
+
+ANSWER_PAYLOAD = {
+ "answer": "The width is resolved once, in helpers.py.",
+ "citations": ["packages/cli/src/repowise/cli/output.py"],
+ "confidence": "high",
+ "retrieval_quality": "strong",
+ "fallback_targets": ["packages/cli/src/repowise/cli/helpers.py"],
+ "retrieval": [
+ {
+ "path": "packages/cli/src/repowise/cli/output.py",
+ "excerpt": "x" * 1500,
+ "key_symbols": [{"name": "resolve_console_width"}],
+ }
+ ],
+ "quotes": [
+ {"path": "packages/cli/src/repowise/cli/output.py", "lines": [44, 44],
+ "quote": "NON_TTY_WIDTH = 400"}
+ ],
+ "candidates": [{"path": "a.py", "lines": "1-20", "defines": "f:1"}],
+ "symbol_bodies": {"a.py::f": "def f(): ..."},
+ "best_guesses": [
+ {"file": "a.py", "why_relevant": "names the constant", "score": 2.1,
+ "domain_penalty": None, "excerpt": "y" * 1500}
+ ],
+ "next_action_hint": "Read a.py first.",
+ "grounding": "extracted",
+ "note": "symbol_bodies carries the full live body — cite that directly.",
+ "code_rationale": [{"path": "a.py", "lines": [1, 2], "comment": "c" * 400}],
+ "more_definitions": ["a.py::g"],
+ "omission_marker": "[repowise#ask1]",
+ "_meta": {"timing_ms": 12.5, "indexed_commit": "abc123", "live_head": "def456",
+ "index_behind": True, "index_age_days": 2},
+}
+
+CONTEXT_PAYLOAD = {
+ "targets": {
+ "a.py": {
+ "target": "a.py",
+ "type": "file",
+ "parent_page": {"title": "CLI", "target_path": "packages/cli"},
+ "docs": {"title": "File: a.py", "summary": "Does a thing."},
+ "hotspot": True,
+ "fix_history": {"fix_count": 3, "last_fix_days_ago": 1, "bug_magnet": True},
+ "freshness": {"confidence_score": 0.9, "is_stale": False},
+ "architectural_layer": {"name": "CLI", "description": "d" * 150},
+ # Blocks only an --include can produce. They must survive the trim:
+ # a flag that changes nothing the caller can see is not a flag.
+ "ownership": {"primary_owner": "Raghav", "bus_factor": 1},
+ "last_change": {"date": "2026-08-01", "author": "Raghav"},
+ "decisions": [{"id": "d1", "title": "Decision 1", "rationale": "because"}],
+ "community": {"id": 3, "neighbors": ["b.py"]},
+ "callers": ["b.py::g"],
+ "metrics": {"pagerank": 0.4},
+ "skeleton": {
+ "mode": "smart", "tokens": 100, "full_tokens": 400,
+ "pct_of_full": 25.0, "bodies_kept": ["f"], "text": "z" * 10000,
+ "verified": True, "auto": True, "opt_out_hint": "h" * 100,
+ },
+ "episodes": 4,
+ }
+ },
+ "truncated": False,
+ "dropped_targets": ["b.py"],
+ "dropped_symbols": {},
+ "_meta": {"timing_ms": 3.0, "indexed_commit": "abc123", "live_head": "abc123",
+ "index_behind": False, "index_age_days": 0},
+}
+
+SYMBOL_PAYLOAD = {
+ "symbol_id": "a.py::f",
+ "file": "a.py",
+ "name": "f",
+ "kind": "function",
+ "qualified_name": "a.f",
+ "signature": "def f() -> None",
+ "language": "python",
+ "start_line": 1,
+ "end_line": 3,
+ "symbol_start_line": 1,
+ "symbol_end_line": 3,
+ "source": " 1 def f() -> None:\n 2 return None",
+ "truncated": True,
+ "continuation": "a.py:4-40",
+ "verified": True,
+ "_meta": {"timing_ms": 1.0, "replaced_tokens": 9, "indexed_commit": "abc123",
+ "live_head": "abc123", "index_behind": False},
+}
+
+#: The tool's *other* two response shapes. ``get_symbol`` serves three, and a
+#: projection tested only against the first is a projection tested against the
+#: implementation rather than the contract.
+OMISSION_PAYLOAD = {
+ "symbol_id": "repowise#a1b2c3d4e5f6",
+ "ref": "a1b2c3d4e5f6",
+ "kind": "omission",
+ # ``source`` here is the *command* the content was banked from, not a body.
+ "source": "git log --stat",
+ "original_tokens": 4200,
+ "content": "THE ACTUAL OMITTED TEXT",
+ "created_at": "2026-08-10T00:00:00+00:00",
+ "_meta": {"timing_ms": 1.0},
+}
+
+SUGGESTION_PAYLOAD = {
+ "symbol_id": "x.py::login",
+ "error": (
+ "Symbol not found: 'x.py::login'. A symbol with this name exists at "
+ "the path(s) below — retry with one of these exact symbol_ids."
+ ),
+ "suggestions": ["a/b.py::login", "c/d.py::login"],
+ "_meta": {"timing_ms": 1.0},
+}
+
+
+def _decision(n: int) -> dict:
+ return {
+ "id": f"id{n}", "title": f"Decision {n}", "status": "active",
+ "decision": "do the thing", "rationale": "because",
+ "context": "c" * 300, "consequences": ["x", "y"], "alternatives": [],
+ "lineage": [], "confidence": 0.9, "staleness_score": 0.1,
+ "affected_files": [f"f{i}.py" for i in range(20)],
+ "affected_files_total": 20,
+ }
+
+
+WHY_PATH_PAYLOAD = {
+ "mode": "path",
+ "path": "a.py",
+ "decisions": [_decision(n) for n in range(8)],
+ "decisions_total": 8,
+ "alignment": {"score": "B", "explanation": "mostly governed"},
+ "origin_story": {
+ "available": True, "primary_author": "Raghav", "author_commit_pct": 80.0,
+ "total_commits": 12, "first_commit": "2026-01-01", "last_commit": "2026-08-01",
+ "age_days": 200, "summary": "s" * 2000,
+ "contributors": [{"name": "Raghav", "email": "r@e", "commit_count": 10}],
+ "key_commits": [
+ {"sha": f"sha{i}", "date": "2026-01-01", "message": f"m{i}",
+ "author": "Raghav", "body": "b" * 300}
+ for i in range(7)
+ ],
+ },
+ "episodes": [{"tier": "git", "kind": "code_fix", "subject": "s", "recorded": "r",
+ "evidence": "e", "scope": ["a.py"], "still_true": "yes"}],
+ "truncated": True,
+ "omission_marker": "[repowise#abc]",
+ "dropped_decisions": ["id7"],
+ "_meta": {"indexed_commit": "abc123", "live_head": "def456",
+ "stale_warning": "index is behind"},
+}
+
+#: The path mode as it actually arrives for an *ungoverned* file: no decisions,
+#: and the three fallback blocks the tool substitutes instead. This is the shape
+#: behind "falls back to git archaeology, so it is never empty", and a
+#: projection that only ever sees the governed shape cannot test it.
+WHY_UNGOVERNED_PAYLOAD = {
+ "mode": "path",
+ "path": "a.py",
+ "decisions": [],
+ "alignment": {"score": "none", "explanation": "This file is ungoverned."},
+ "origin_story": {"available": False},
+ "git_archaeology": {
+ "triggered": True,
+ "summary": "No architectural decisions found for a.py, but git archaeology recovered 7.",
+ "file_commits": [
+ {"sha": f"sha{i}", "message": f"m{i}", "author": "Raghav", "date": "2026-01-01"}
+ for i in range(7)
+ ],
+ "cross_references": [
+ {"source_file": "b.py", "sha": "shax", "message": "mentions a.py",
+ "author": "Raghav", "date": "2026-02-01", "matched_terms": ["a"]}
+ ],
+ "git_log": [{"sha": "shay", "message": "live", "author": "Raghav", "date": "2026-03-01"}],
+ },
+ "code_rationale": [{"path": "a.py", "lines": [10, 12], "comment": "why it is this way",
+ "matched_terms": ["why"]}],
+ "target_context": {
+ "b.py": {
+ "governing_decisions": [{"title": "Decision 1", "status": "active"}],
+ "origin": {"available": True, "primary_author": "Raghav", "total_commits": 3,
+ "age_days": 40, "summary": "s" * 2000},
+ }
+ },
+ "_meta": {"indexed_commit": "abc123", "live_head": "abc123"},
+}
+
+WHY_DASHBOARD_PAYLOAD = {
+ "mode": "health",
+ "summary": "37 active",
+ "counts": {"active": 37, "stale": 14},
+ "stale_decisions": [{"id": f"s{i}", "title": f"Stale {i}"} for i in range(10)],
+ "proposed_awaiting_review": [],
+ "ungoverned_hotspots": [f"h{i}.md" for i in range(15)],
+ "conflicts": [],
+ "_meta": {"indexed_commit": "abc123", "live_head": "abc123"},
+}
+
+
+# --------------------------------------------------------------------------
+# Harness
+# --------------------------------------------------------------------------
+
+
+def repo(tmp_path):
+ """An indexed-looking repo the commands will accept."""
+ (tmp_path / ".repowise").mkdir()
+ return tmp_path
+
+
+def _spy_run(payload: dict, calls: list):
+ """Stand in for ``_tool_adapters.run``, but call the factory for real.
+
+ The factory is where each command imports its tool function and binds the
+ arguments, so calling it is what proves the wiring. Its coroutine is closed
+ rather than awaited — running it would need a database.
+ """
+
+ def _run(repo_path, factory, tool_name):
+ coro = factory()
+ calls.append((repo_path, coro.cr_code.co_qualname, tool_name))
+ coro.close()
+ return payload
+
+ return _run
+
+
+def _invoke(monkeypatch, command, args, repo, payload, calls=None, expect_exit=0):
+ monkeypatch.setattr(_ta, "run", _spy_run(payload, calls if calls is not None else []))
+ result = CliRunner(mix_stderr=False).invoke(
+ command, [*args, "--path", str(repo), "--no-workspace"]
+ )
+ assert result.exit_code == expect_exit, result.output + (result.stderr or "")
+ return result
+
+
+# --------------------------------------------------------------------------
+# The projections — the field mapping, pinned
+# --------------------------------------------------------------------------
+
+
+def test_ask_projection_drops_the_bulk_and_keeps_the_evidence():
+ out = project_ask(ANSWER_PAYLOAD, "q?")
+ assert out["answer"] == ANSWER_PAYLOAD["answer"]
+ assert out["citations"] == ANSWER_PAYLOAD["citations"]
+ assert out["quotes"][0]["quote"] == "NON_TTY_WIDTH = 400"
+ for dropped in ("retrieval", "candidates", "symbol_bodies", "_meta"):
+ assert dropped not in out, f"{dropped} survived the trim"
+ # The freshness half of _meta survives; the timing half does not.
+ assert out["index"] == {"indexed_commit": "abc123", "live_head": "def456",
+ "index_behind": True, "index_age_days": 2}
+
+
+def test_ask_projection_strips_the_excerpt_from_every_best_guess():
+ """The abstain path carries a 1,500-char excerpt per guess.
+
+ Dropping ``retrieval`` but keeping ``best_guesses`` whole would make the
+ low-confidence answer the *largest* thing this command emits.
+ """
+ out = project_ask(ANSWER_PAYLOAD, "q?")
+ assert out["best_guesses"] == [
+ {"file": "a.py", "why_relevant": "names the constant", "score": 2.1}
+ ]
+ assert "excerpt" not in json.dumps(out)
+ assert out["next_action_hint"] == "Read a.py first."
+
+
+def test_ask_projection_names_the_blocks_it_dropped():
+ """``note`` points at blocks by name ("symbol_bodies carries the body").
+
+ Keeping the note while silently removing what it names leaves a dangling
+ instruction, so the trim reports which of them the tool actually returned.
+ """
+ out = project_ask(ANSWER_PAYLOAD, "q?")
+ assert out["note"].startswith("symbol_bodies")
+ assert set(out["dropped_blocks"]) == {
+ "retrieval", "candidates", "symbol_bodies", "code_rationale", "more_definitions",
+ }
+ assert out["grounding"] == "extracted"
+ assert out["omission_marker"] == "[repowise#ask1]"
+
+
+def test_ask_projection_is_a_fraction_of_the_payload():
+ trimmed = len(json.dumps(project_ask(ANSWER_PAYLOAD, "q?")))
+ full = len(json.dumps(ANSWER_PAYLOAD))
+ assert trimmed * 3 < full, f"trim saved too little: {trimmed} of {full}"
+
+
+def test_context_projection_keeps_the_skeleton_shape_without_its_text():
+ out = project_context(CONTEXT_PAYLOAD, ("a.py",))
+ card = out["targets"]["a.py"]
+ assert card["title"] == "File: a.py"
+ assert card["summary"] == "Does a thing."
+ assert card["layer"] == "CLI"
+ assert card["hotspot"] is True
+ assert card["fix_history"]["bug_magnet"] is True
+ assert card["stale"] is False
+ # ``is_stale: null`` means the tool could not judge, not "current".
+ unknown = {"target": "a.py", "freshness": {"is_stale": None}}
+ assert "stale" not in project_context({"targets": {"a.py": unknown}}, ("a.py",))["targets"]["a.py"]
+ assert card["episodes"] == 4
+ assert card["skeleton"] == {
+ "mode": "smart", "tokens": 100, "full_tokens": 400,
+ "pct_of_full": 25.0, "verified": True, "bodies_kept": ["f"],
+ }
+ assert "z" * 100 not in json.dumps(out), "skeleton text survived the trim"
+ assert "parent_page" not in card
+
+
+def test_context_projection_keeps_every_include_block():
+ """A flag that changes nothing the caller can see is not a flag.
+
+ Each ``--include`` lands under its own key, so an allowlist that misses
+ one makes ``repowise context f.py --include ownership`` print exactly what
+ a bare call prints.
+ """
+ card = project_context(CONTEXT_PAYLOAD, ("a.py",))["targets"]["a.py"]
+ assert card["ownership"] == {"primary_owner": "Raghav", "bus_factor": 1}
+ assert card["last_change"] == {"date": "2026-08-01", "author": "Raghav"}
+ assert card["decisions"][0]["rationale"] == "because"
+ assert card["community"] == {"id": 3, "neighbors": ["b.py"]}
+ assert card["callers"] == ["b.py::g"]
+ assert card["metrics"] == {"pagerank": 0.4}
+
+
+def test_context_projection_keeps_a_tombstones_redirect():
+ """The successor path is the whole point of a tombstone card."""
+ payload = {
+ "targets": {
+ "old.py": {
+ "target": "old.py",
+ "error": "'old.py' was deleted or renamed after indexing",
+ "successor_paths": ["new.py"],
+ "hint": "Content moved; call get_context on 'new.py' instead.",
+ }
+ },
+ "_meta": {},
+ }
+ card = project_context(payload, ("old.py",))["targets"]["old.py"]
+ assert card["successor_paths"] == ["new.py"]
+ assert "new.py" in card["hint"]
+
+
+def test_context_projection_keeps_a_targets_own_error():
+ """A card carrying only ``error`` must not trim down to an empty card.
+
+ An empty card reads as "indexed, nothing to say"; the error says the path
+ does not exist. Found by running the command against a typo.
+ """
+ payload = {
+ "targets": {"nope.py": {"target": "nope.py", "error": "Target not found: 'nope.py'"}},
+ "_meta": {},
+ }
+ card = project_context(payload, ("nope.py",))["targets"]["nope.py"]
+ assert card == {"target": "nope.py", "error": "Target not found: 'nope.py'"}
+
+
+def test_context_projection_reports_a_target_the_tool_never_mentioned():
+ """A typo'd path must not look like a path with nothing to say."""
+ out = project_context(CONTEXT_PAYLOAD, ("a.py", "b.py", "typo.py"))
+ # b.py is in dropped_targets, so it is accounted for; typo.py is not.
+ assert out["dropped_targets"] == ["b.py"]
+ assert out["not_found"] == ["typo.py"]
+
+
+def test_symbol_projection_keeps_the_body_and_the_continuation():
+ """``symbol``'s payload *is* its answer, so only the envelope is dropped."""
+ out = project_symbol(SYMBOL_PAYLOAD)
+ assert out["source"] == SYMBOL_PAYLOAD["source"]
+ assert out["continuation"] == "a.py:4-40"
+ assert out["truncated"] is True
+ assert "_meta" not in out
+ assert out["index"]["indexed_commit"] == "abc123"
+
+
+def test_symbol_projection_keeps_an_omission_refs_content():
+ """``source`` on this shape is the command, not a body — ``content`` is.
+
+ Keeping ``source`` and dropping ``content`` makes ``repowise symbol
+ repowise#<ref>`` print the provenance label where the text should be, and
+ the renderer prints it through the body branch, so it looks like one.
+ """
+ out = project_symbol(OMISSION_PAYLOAD)
+ assert out["content"] == "THE ACTUAL OMITTED TEXT"
+ assert out["ref"] == "a1b2c3d4e5f6"
+ assert out["kind"] == "omission"
+ assert out["original_tokens"] == 4200
+
+
+def test_symbol_projection_keeps_the_did_you_mean_list():
+ """The error ends 'retry with one of these exact symbol_ids'."""
+ out = project_symbol(SUGGESTION_PAYLOAD)
+ assert out["suggestions"] == ["a/b.py::login", "c/d.py::login"]
+
+
+def test_why_path_projection_caps_lists_and_says_what_it_capped():
+ out = project_why(WHY_PATH_PAYLOAD)
+ assert len(out["decisions"]) == 5
+ assert out["decisions_total"] == 8
+ decision = out["decisions"][0]
+ assert decision["rationale"] == "because"
+ assert len(decision["affected_files"]) == 5
+ assert decision["affected_files_total"] == 20
+ for dropped in ("context", "consequences", "alternatives", "lineage",
+ "confidence", "staleness_score"):
+ assert dropped not in decision
+
+
+def test_why_path_projection_drops_the_prose_retelling_and_commit_bodies():
+ out = project_why(WHY_PATH_PAYLOAD)
+ origin = out["origin_story"]
+ assert origin["primary_author"] == "Raghav"
+ assert "summary" not in origin, "the 2K-char origin prose survived"
+ assert "contributors" not in origin
+ assert len(origin["key_commits"]) == 5
+ assert all("body" not in c for c in origin["key_commits"])
+ assert out["truncated"] is True
+ assert out["omission_marker"] == "[repowise#abc]"
+ assert out["index"]["stale_warning"] == "index is behind"
+
+
+def test_why_projection_keeps_the_blocks_that_answer_an_ungoverned_path():
+ """`get_why` is documented as never empty; the fallbacks are why.
+
+ It sets git_archaeology and code_rationale *because* nothing governs the
+ path. Dropping them leaves `repowise why <ungoverned file>` printing one
+ alignment line and nothing else.
+ """
+ out = project_why(WHY_UNGOVERNED_PAYLOAD)
+ arch = out["git_archaeology"]
+ assert arch["summary"].startswith("No architectural decisions found")
+ assert len(arch["file_commits"]) == 5, "the per-layer cap did not apply"
+ assert arch["cross_references"][0]["source_file"] == "b.py"
+ assert arch["git_log"][0]["sha"] == "shay"
+ assert out["code_rationale"][0]["comment"] == "why it is this way"
+
+
+def test_why_projection_keeps_target_context_and_trims_it_the_same_way():
+ """--target's entire product is target_context. Dropping it inerts the flag."""
+ out = project_why(WHY_UNGOVERNED_PAYLOAD)
+ entry = out["target_context"]["b.py"]
+ assert entry["governing_decisions"] == [{"title": "Decision 1", "status": "active"}]
+ # The per-target origin carries the same ~2K-char prose as the top level.
+ assert "summary" not in entry["origin"]
+ assert entry["origin"]["primary_author"] == "Raghav"
+
+
+def test_why_projection_keeps_the_handles_on_what_truncation_removed():
+ out = project_why(WHY_PATH_PAYLOAD)
+ assert out["omission_marker"] == "[repowise#abc]"
+ assert out["dropped_decisions"] == ["id7"]
+
+
+def test_why_dashboard_projection_caps_each_list_with_its_total():
+ out = project_why(WHY_DASHBOARD_PAYLOAD)
+ assert out["counts"] == {"active": 37, "stale": 14}
+ assert len(out["stale_decisions"]) == 5
+ assert out["stale_decisions_total"] == 10
+ assert len(out["ungoverned_hotspots"]) == 5
+ assert out["ungoverned_hotspots_total"] == 15
+ # Empty lists are not reported as capped-to-zero.
+ assert "conflicts" not in out
+ assert "proposed_awaiting_review" not in out
+
+
+# --------------------------------------------------------------------------
+# --full, and the commands end to end
+# --------------------------------------------------------------------------
+
+
+ ("command", "args", "payload"),
+ [
+ (ask_command, ["q?"], ANSWER_PAYLOAD),
+ (context_command, ["a.py"], CONTEXT_PAYLOAD),
+ (symbol_command, ["a.py::f"], SYMBOL_PAYLOAD),
+ (why_command, ["a.py"], WHY_PATH_PAYLOAD),
+ ],
+)
+def test_full_emits_the_raw_tool_dict_without_asking_for_json(
+ monkeypatch, repo, command, args, payload
+):
+ """``--full`` implies json — a raw tool dict has no table rendering."""
+ result = _invoke(monkeypatch, command, [*args, "--full"], repo, payload)
+ assert json.loads(result.stdout) == payload
+
+
+ ("command", "args"),
+ [
+ (ask_command, ["q?"]),
+ (context_command, ["a.py"]),
+ (symbol_command, ["a.py::f"]),
+ (why_command, ["a.py"]),
+ ],
+)
+def test_full_exits_non_zero_on_an_error_too(monkeypatch, repo, command, args):
+ """``--full`` is exactly the spelling a script reaches for."""
+ result = _invoke(
+ monkeypatch, command, [*args, "--full"], repo, {"error": "nope"}, expect_exit=1
+ )
+ assert json.loads(result.stdout) == {"error": "nope"}
+
+
+ ("command", "args", "payload"),
+ [
+ (ask_command, ["q?"], ANSWER_PAYLOAD),
+ (context_command, ["a.py"], CONTEXT_PAYLOAD),
+ (symbol_command, ["a.py::f"], SYMBOL_PAYLOAD),
+ (why_command, ["a.py"], WHY_PATH_PAYLOAD),
+ ],
+)
+def test_json_is_the_projection_and_stdout_is_one_document(
+ monkeypatch, repo, command, args, payload
+):
+ result = _invoke(monkeypatch, command, [*args, "--format", "json"], repo, payload)
+ parsed = json.loads(result.stdout)
+ assert parsed != payload, "--format json emitted the raw dict, not the projection"
+ assert len(result.stdout) < len(json.dumps(payload, indent=2))
+
+
+ ("command", "args"),
+ [
+ (ask_command, ["q?"]),
+ (context_command, ["a.py"]),
+ (symbol_command, ["a.py::f"]),
+ (why_command, ["a.py"]),
+ ],
+)
+def test_a_tool_error_still_leaves_a_document_on_stdout(monkeypatch, repo, command, args):
+ """An empty stdout is indistinguishable from a crash to whatever reads it.
+
+ The document is emitted *and* the exit code is non-zero: a failed lookup
+ that exits 0 reads as a hit to any script checking only the status.
+ """
+ result = _invoke(
+ monkeypatch,
+ command,
+ [*args, "--format", "json"],
+ repo,
+ {"error": "no such repo"},
+ expect_exit=1,
+ )
+ assert json.loads(result.stdout)["error"] == "no such repo"
+
+
+def test_a_tool_error_is_rewritten_into_commands_a_cli_user_can_run(monkeypatch, repo):
+ """``get_symbol``'s not-found hint names get_context, which is not a command."""
+ result = _invoke(
+ monkeypatch,
+ symbol_command,
+ ["a.py::Nope"],
+ repo,
+ {"error": "Symbol not found. Use get_context to list available symbols."},
+ expect_exit=1,
+ )
+ printed = result.stdout + (result.stderr or "")
+ assert "repowise context" in printed
+ assert "get_context" not in printed
+
+
+def test_the_json_error_payload_keeps_the_tools_own_vocabulary(monkeypatch, repo):
+ """A json consumer is reading the tool's projection, tool names and all."""
+ result = _invoke(
+ monkeypatch,
+ symbol_command,
+ ["a.py::Nope", "--format", "json"],
+ repo,
+ {"error": "Use get_context to list available symbols."},
+ expect_exit=1,
+ )
+ assert "get_context" in json.loads(result.stdout)["error"]
+
+
+ ("command", "args"),
+ [
+ (ask_command, ["q?"]),
+ (context_command, ["a.py"]),
+ (symbol_command, ["a.py::f"]),
+ (why_command, ["a.py"]),
+ ],
+)
+def test_an_empty_result_still_renders_on_the_table_path(monkeypatch, repo, command, args):
+ result = _invoke(monkeypatch, command, args, repo, {"_meta": {}})
+ assert result.stdout.strip(), "table path printed nothing at all"
+
+
+ ("command", "args", "tool"),
+ [
+ (ask_command, ["q?"], "get_answer"),
+ (context_command, ["a.py"], "get_context"),
+ (symbol_command, ["a.py::f"], "get_symbol"),
+ (why_command, ["a.py"], "get_why"),
+ ],
+)
+def test_the_command_builds_the_coroutine_of_the_tool_it_names(
+ monkeypatch, repo, command, args, tool
+):
+ """The tool import lives inside the factory, so only calling it proves it.
+
+ A wrong module or attribute name there raises nothing until the command
+ runs against a real repo — the same class of defect the lazy command table
+ has its own test for. Asserting the coroutine's own qualname rather than
+ "the module is in sys.modules" is what makes this order-independent: by
+ the fourth parametrized case all four tool modules are imported, so a
+ presence check would pass for a command wired to the wrong tool.
+ """
+ calls: list = []
+ _invoke(monkeypatch, command, args, repo, {"_meta": {}}, calls=calls)
+ assert len(calls) == 1
+ repo_path, qualname, tool_name = calls[0]
+ assert repo_path == repo
+ assert qualname == tool
+ # The same name reaches the bridge, which uses it to shape an internal
+ # error the way the MCP failure shield would have.
+ assert tool_name == tool
+
+
+def test_an_unindexed_repo_is_refused_before_any_tool_runs(monkeypatch, tmp_path):
+ calls: list = []
+ monkeypatch.setattr(_ta, "run", _spy_run({}, calls))
+ result = CliRunner(mix_stderr=False).invoke(
+ ask_command, ["q?", "--path", str(tmp_path), "--no-workspace"]
+ )
+ assert result.exit_code != 0
+ assert "not indexed" in (result.stderr or result.output)
+ assert calls == []
+
+
[email protected]("args", [[], ["--format", "json"], ["--full"]])
+def test_logs_are_silenced_at_every_format_not_only_the_machine_ones(
+ monkeypatch, repo, args
+):
+ """``ask`` synthesises through a provider that logs to *stdout*.
+
+ ``format_option``'s callback only fires for a machine-readable format, so
+ it would leave three timestamped structlog lines in the middle of the human
+ answer — and inside anything reading it through ``repowise distill``.
+ """
+ silenced: list = []
+ monkeypatch.setattr(
+ "repowise.cli.helpers.silence_logs_for_machine_output",
+ lambda: silenced.append(True),
+ )
+ monkeypatch.setattr("repowise.cli.tool_bridge.call_tool", lambda p, f, t: {"_meta": {}})
+ result = CliRunner(mix_stderr=False).invoke(
+ ask_command, ["q?", *args, "--path", str(repo), "--no-workspace"]
+ )
+ assert result.exit_code == 0, result.output
+ assert silenced, "the tool call ran with logging still pointed at stdout"
+
+
+def test_ask_echoes_the_answer_verbatim_rather_than_rendering_markdown(monkeypatch, repo):
+ """Rich would centre and pad every heading to the 400-column non-TTY width.
+
+ Echoing the source keeps the bytes, the markdown, and the grep.
+ """
+ payload = {**ANSWER_PAYLOAD, "answer": "## A heading\n\nA [bracketed] body."}
+ result = _invoke(monkeypatch, ask_command, ["q?"], repo, payload)
+ assert "## A heading" in result.stdout
+ assert "[bracketed]" in result.stdout
+
+
+# --------------------------------------------------------------------------
+# The renderers. A projection test cannot see a block that survives the trim
+# and is then never printed, and "kept but never rendered" is a defect this
+# file has already had to fix once.
+# --------------------------------------------------------------------------
+
+
+def test_context_renders_every_include_block_it_kept(monkeypatch, repo):
+ result = _invoke(monkeypatch, context_command, ["a.py"], repo, CONTEXT_PAYLOAD)
+ for expected in ("Ownership", "Last Change", "Community", "Metrics", "Raghav"):
+ assert expected in result.stdout, f"{expected} survived the trim but was not rendered"
+
+
+def test_context_renders_a_symbol_target(monkeypatch, repo):
+ """A symbol target's whole card lives under ``docs``.
+
+ Dropping ``docs`` wholesale projected it to ``{target, type}`` and printed
+ a one-row table, on the id spelling ``repowise symbol``'s help points at.
+ """
+ payload = {
+ "targets": {
+ "a.py::Login": {
+ "target": "a.py::Login",
+ "type": "symbol",
+ "docs": {
+ "name": "Login",
+ "signature": "class Login(Base)",
+ "docstring": "Session start.",
+ "file_path": "a.py",
+ "used_by": ["b.py"],
+ },
+ }
+ },
+ "_meta": {},
+ }
+ result = _invoke(monkeypatch, context_command, ["a.py::Login"], repo, payload)
+ assert "class Login(Base)" in result.stdout
+ assert "Session start." in result.stdout
+
+
+def test_context_does_not_let_rich_eat_a_bracket_in_tool_text(monkeypatch, repo):
+ """Rich markup-parses a table cell, so `list[str]` renders as `list`."""
+ payload = {
+ "targets": {
+ "a.py": {
+ "target": "a.py",
+ "type": "file",
+ "docs": {"summary": "Returns list[str], not dict[str, int]."},
+ }
+ },
+ "_meta": {},
+ }
+ result = _invoke(monkeypatch, context_command, ["a.py"], repo, payload)
+ assert "list[str]" in result.stdout
+ assert "dict[str, int]" in result.stdout
+
+
+def test_context_prints_the_marker_that_recovers_truncated_content(monkeypatch, repo):
+ """The marker opens with a bracket, which rich deletes as a style tag."""
+ marker = "[repowise#abc123: 120 lines omitted; restore: repowise expand abc123]"
+ payload = {"targets": {}, "truncated": True, "omission_marker": marker, "_meta": {}}
+ result = _invoke(monkeypatch, context_command, ["a.py"], repo, payload)
+ assert "repowise#abc123" in result.stdout
+ assert "repowise expand abc123" in result.stdout
+
+
+def test_why_renders_the_archaeology_it_falls_back_to(monkeypatch, repo):
+ result = _invoke(monkeypatch, why_command, ["a.py"], repo, WHY_UNGOVERNED_PAYLOAD)
+ assert "Git archaeology" in result.stdout
+ assert "mentions a.py" in result.stdout
+ assert "5 of 7" in result.stdout, "the cap was applied but never disclosed"
+
+
+def test_why_renders_a_targets_own_history(monkeypatch, repo):
+ """``origin.summary`` exists only when there is *no* history.
+
+ Rendering only that line left a target with real history showing its name
+ and nothing else.
+ """
+ payload = {
+ **WHY_UNGOVERNED_PAYLOAD,
+ "target_context": {
+ "b.py": {
+ "governing_decisions": [],
+ "origin": {"available": True, "primary_author": "Raghav",
+ "total_commits": 9, "age_days": 40, "summary": "s" * 2000},
+ }
+ },
+ }
+ result = _invoke(monkeypatch, why_command, ["a.py"], repo, payload)
+ assert "9 commits over 40 days" in result.stdout
+ assert "s" * 100 not in result.stdout, "the 2K-char prose reached the screen"
+
+
+def test_why_does_not_say_nothing_recorded_under_what_it_just_recorded(monkeypatch, repo):
+ """Search mode with --target sets none of the path-mode blocks."""
+ payload = {
+ "mode": "search",
+ "query": "q",
+ "code_rationale": [{"path": "b.py", "lines": [1, 2], "comment": "because"}],
+ "target_context": {"b.py": {"governing_decisions": [], "origin": {"available": False}}},
+ "_meta": {},
+ }
+ result = _invoke(monkeypatch, why_command, ["q", "--target", "b.py"], repo, payload)
+ assert "because" in result.stdout
+ assert "Nothing recorded" not in result.stdout
+
+
+def test_symbol_renders_an_omission_refs_banked_content(monkeypatch, repo):
+ result = _invoke(
+ monkeypatch, symbol_command, ["repowise#a1b2c3d4e5f6"], repo, OMISSION_PAYLOAD
+ )
+ assert "THE ACTUAL OMITTED TEXT" in result.stdout
+ assert "git log --stat" in result.stdout
+
+
+def test_symbol_does_not_wrap_a_long_source_line(monkeypatch, repo):
+ """``console.print`` wraps at the console width even with markup off.
+
+ A wrapped body strands the `` 1 `` prefix on its own row, which is not
+ the file.
+ """
+ long_line = " 1 " + "x" * 600
+ payload = {**SYMBOL_PAYLOAD, "source": long_line, "truncated": False}
+ result = _invoke(monkeypatch, symbol_command, ["a.py::f"], repo, payload)
+ assert long_line in result.stdout
+
+
+def test_a_did_you_mean_error_prints_its_suggestions(monkeypatch, repo):
+ """The error's last words are 'retry with one of these exact symbol_ids'."""
+ result = _invoke(
+ monkeypatch, symbol_command, ["x.py::login"], repo, SUGGESTION_PAYLOAD, expect_exit=1
+ )
+ printed = result.stdout + (result.stderr or "")
+ assert "a/b.py::login" in printed and "c/d.py::login" in printed
+
+
+def test_an_unindexed_repos_shaped_error_prints_its_remedy(monkeypatch, repo):
+ """The shield's ``remedy`` is the only part that says what to do."""
+ payload = {
+ "error": "This repository has no repowise index yet.",
+ "remedy": "The user can build one by running 'repowise init --yes'.",
+ "guidance": "Until an index exists, every repowise tool returns this.",
+ }
+ result = _invoke(monkeypatch, ask_command, ["q?"], repo, payload, expect_exit=1)
+ printed = result.stdout + (result.stderr or "")
+ assert "repowise init --yes" in printed
+ assert "Until an index exists" in printed
+
+
+def test_ask_renders_the_note_and_names_what_it_left_out(monkeypatch, repo):
+ result = _invoke(monkeypatch, ask_command, ["q?"], repo, ANSWER_PAYLOAD)
+ assert "symbol_bodies carries the full live body" in result.stdout
+ assert "Not shown:" in result.stdout and "retrieval" in result.stdout
+ assert "repowise#ask1" in result.stdout
+
+
+def test_why_renders_a_dominant_author_as_a_percentage_not_a_fraction():
+ """``author_commit_pct`` is a 0-1 fraction or a 0-100 percentage.
+
+ Its source stores either, so printing it raw shows a sole author as
+ "0.99%".
+ """
+ from repowise.cli.commands.why_cmd import _owner_share
+
+ assert _owner_share(0.9956) == "100%"
+ assert _owner_share(80.0) == "80%"
+ assert _owner_share(None) == "?"
diff --git a/tests/unit/cli/test_tool_bridge.py b/tests/unit/cli/test_tool_bridge.py
new file mode 100644
index 000000000..d97007da3
--- /dev/null
+++ b/tests/unit/cli/test_tool_bridge.py
@@ -0,0 +1,237 @@
+"""The CLI's wiring of MCP tool state.
+
+The tools read their session factory, full-text index and vector store out of
+``mcp_server._state``, which the MCP server's lifespan normally publishes.
+This bridge is the CLI's caller of the same publisher, and the two things that
+can go wrong are silent: publishing the wrong objects (the tool answers from
+another repo's database) and not tearing down (a leaked engine per invocation,
+invisible in a one-shot process and fatal in a test suite).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.cli import tool_bridge
+
+
+class _FakeEngine:
+ def __init__(self) -> None:
+ self.disposed = False
+
+ async def dispose(self) -> None:
+ self.disposed = True
+
+
+class _FakeStore:
+ def __init__(self) -> None:
+ self.closed = False
+
+ async def close(self) -> None:
+ self.closed = True
+
+
+def wired(monkeypatch, tmp_path):
+ """Patch the bridge's collaborators and record what it published."""
+ engine = _FakeEngine()
+ store = _FakeStore()
+ published: dict = {}
+
+ monkeypatch.setattr(
+ "repowise.core.persistence.create_engine", lambda url: engine, raising=False
+ )
+ monkeypatch.setattr(
+ "repowise.core.persistence.FullTextSearch", lambda eng: ("fts", eng), raising=False
+ )
+ monkeypatch.setattr(
+ "repowise.cli.helpers.get_db_url_for_repo", lambda p: f"sqlite+aiosqlite:///{p}"
+ )
+
+ async def _fake_open(repo_path):
+ return store
+
+ monkeypatch.setattr(tool_bridge, "_open_vector_store", _fake_open)
+
+ def _fake_init(session_factory, fts, vector_store, decision_store=None, repo_path=None):
+ published.update(
+ session_factory=session_factory,
+ fts=fts,
+ vector_store=vector_store,
+ decision_store=decision_store,
+ repo_path=repo_path,
+ )
+
+ monkeypatch.setattr("repowise.server.chat_tools.init_tool_state", _fake_init)
+ return engine, store, published, tmp_path
+
+
+def test_it_publishes_this_repos_resources_and_tears_them_down(wired):
+ engine, store, published, repo = wired
+
+ async def _tool():
+ return {"ok": True}
+
+ assert tool_bridge.call_tool(repo, _tool, "get_symbol") == {"ok": True}
+ # The session factory is the object that decides *which repo's database*
+ # answers, so it is the one most worth pinning.
+ assert published["session_factory"].kw["bind"] is engine
+ assert published["vector_store"] is store
+ # The server points both at one store: decisions share the page table under
+ # a "decision:" namespace rather than living in a separate one.
+ assert published["decision_store"] is store
+ assert published["repo_path"] == str(repo)
+ assert published["fts"] == ("fts", engine)
+ assert engine.disposed and store.closed
+
+
+def test_a_failing_tool_becomes_a_shaped_error_not_a_traceback(wired):
+ """The MCP surface composes every tool inside ``_failure_shield``.
+
+ A CLI command awaits the undecorated function, so without this a repo with
+ a ``.repowise/`` directory but no built database prints a sqlalchemy
+ traceback with an **empty stdout** — the state a caller cannot tell from a
+ crash, which is what every early return here exists to avoid.
+ """
+ engine, store, _published, repo = wired
+
+ async def _tool():
+ raise RuntimeError("boom")
+
+ result = tool_bridge.call_tool(repo, _tool, "get_symbol")
+ assert "get_symbol" in result["error"] and "boom" in result["error"]
+ assert engine.disposed and store.closed
+
+
+def test_an_unindexed_repo_gets_the_shields_run_init_advice(wired):
+ """``_get_repo`` raises this exact LookupError; the shield shapes it."""
+ _engine, _store, _published, repo = wired
+
+ async def _tool():
+ raise LookupError("No repositories found in the database")
+
+ result = tool_bridge.call_tool(repo, _tool, "get_context")
+ assert "no repowise index yet" in result["error"].lower()
+ assert "repowise init" in result["remedy"]
+
+
+def test_a_store_that_fails_to_open_still_disposes_the_engine(wired, monkeypatch):
+ """Building the embedder happens before the tool call and can raise."""
+ engine, _store, _published, repo = wired
+
+ async def _explode(repo_path):
+ raise RuntimeError("no embedder")
+
+ monkeypatch.setattr(tool_bridge, "_open_vector_store", _explode)
+
+ async def _tool():
+ return {}
+
+ result = tool_bridge.call_tool(repo, _tool, "get_why")
+ assert "no embedder" in result["error"]
+ assert engine.disposed
+
+
+def test_a_store_that_fails_to_close_does_not_lose_the_answer(wired, monkeypatch):
+ """Teardown of a store the tool already answered from is not the answer."""
+ engine, store, _published, repo = wired
+
+ async def _explode():
+ raise OSError("lancedb handle already gone")
+
+ monkeypatch.setattr(store, "close", _explode)
+
+ async def _tool():
+ return {"ok": True}
+
+ assert tool_bridge.call_tool(repo, _tool, "get_symbol") == {"ok": True}
+ assert engine.disposed
+
+
+def test_the_factory_runs_inside_the_loop_after_the_state_is_published(wired):
+ """A coroutine built before the wiring would see the previous repo's state."""
+ _engine, _store, published, repo = wired
+ seen: list = []
+
+ async def _tool():
+ seen.append(dict(published))
+ return {}
+
+ tool_bridge.call_tool(repo, _tool, "get_symbol")
+ assert seen and seen[0]["repo_path"] == str(repo)
+
+
+def restore_embedder_status(monkeypatch):
+ """``_open_vector_store`` writes a module global that outlives the test.
+
+ ``_state._embedder_status`` feeds ``build_meta``, so leaking a "mock"
+ status here would make any later test that builds a ``_meta`` envelope see
+ a degraded embedder that no test set.
+ """
+ from repowise.server.mcp_server import _state
+
+ monkeypatch.setattr(_state, "_embedder_status", None, raising=False)
+ return _state
+
+
+def test_it_falls_back_to_an_in_memory_store_when_the_repo_has_no_lancedb(
+ monkeypatch, tmp_path, restore_embedder_status
+):
+ from repowise.core.persistence.vector_store import InMemoryVectorStore
+
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.resolve_embedder_for_repo", lambda p: "mock"
+ )
+ monkeypatch.setattr("repowise.cli.providers.embedders.build_embedder", lambda name: object())
+
+ import asyncio
+
+ store = asyncio.run(tool_bridge._open_vector_store(tmp_path))
+ assert isinstance(store, InMemoryVectorStore)
+
+
+def test_a_repo_whose_embedder_key_went_away_is_recorded_as_degraded(
+ monkeypatch, tmp_path, restore_embedder_status
+):
+ """``build_meta`` reads this global to set ``embedder_degraded``.
+
+ Only the MCP server's own ``_resolve_embedder`` ever wrote it, so a CLI
+ answer produced with no semantic retrieval looked identical to a healthy
+ one — the exact condition the field was added for.
+ """
+ import asyncio
+
+ from repowise.core.providers.embedding import KeylessEmbedder
+
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.resolve_embedder_for_repo", lambda p: "openai"
+ )
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.build_embedder", lambda name: KeylessEmbedder()
+ )
+ asyncio.run(tool_bridge._open_vector_store(tmp_path))
+
+ status = restore_embedder_status._embedder_status
+ assert status["degraded"] is True
+ assert status["requested"] == "openai" and status["active"] == "mock"
+ assert "openai" in status["reason"]
+
+
+def test_a_repo_that_asked_for_keyless_is_not_reported_as_degraded(
+ monkeypatch, tmp_path, restore_embedder_status
+):
+ """Resolving to the keyless embedder is a configuration, not a failure."""
+ import asyncio
+
+ from repowise.core.providers.embedding import KeylessEmbedder
+
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.resolve_embedder_for_repo", lambda p: "mock"
+ )
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.build_embedder", lambda name: KeylessEmbedder()
+ )
+ asyncio.run(tool_bridge._open_vector_store(tmp_path))
+
+ assert restore_embedder_status._embedder_status["degraded"] is False