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): collapse search onto search_codebase, and serve get_risk from risk (#1412)

Raghav Chamadiyaec3e34f37707
diff --git a/README.md b/README.md
index 78f321e65..6c988ed2d 100644
--- a/README.md
+++ b/README.md
@@ -728,13 +728,14 @@ repowise generate [PATH] # write wiki pages with a model, on demand (upgrade a
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 search "<q>" # hybrid search (fulltext / semantic / symbol / path)
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 risk -t <file> # what history says about touching a file
repowise impacted-tests # only the tests a diff actually exercises
repowise dead-code # unreachable-code report
repowise decision list # architectural decisions
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 44ba7a634..5124ea512 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -411,27 +411,45 @@ and leaves the prose to a later `repowise update`.
### `repowise search QUERY [PATH]`
-Search wiki pages by keyword, meaning, or symbol name.
+Search wiki pages by keyword, meaning, or symbol name. Runs the same retrieval
+as the `search_codebase` MCP tool: the full-text and vector legs are fused
+rather than chosen between, per-repo excludes and tombstones are honoured, and
+decision / test pages are demoted on queries that did not ask for them.
**Options:**
| Flag | Description |
|------|-------------|
-| `--mode` | `fulltext` (default), `semantic`, `symbol` |
+| `--mode` | `fulltext` (default), `semantic`, `symbol`, plus the tool's own `auto`, `concept`, `path`, `hybrid` |
| `--limit` | Max results (default: 10) |
| `--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` |
+| `--full` | Emit the complete tool payload as JSON (implies `--format json`) |
+
+`fulltext` and `semantic` both run the tool's fused `concept` search, which is
+the successor to picking one leg or the other; on an index built without an
+embedder the vector leg drops out by itself and `--mode semantic` says so.
+`auto` routes on the query's shape — an identifier goes to the symbol index, a
+path resolves files, prose stays conceptual, and a mixed query runs `hybrid`.
```bash
repowise search "rate limiting"
repowise search "how are errors handled" --mode semantic
repowise search "AuthService" --mode symbol
+repowise search "cli/output.py" --mode path
+repowise search "where is resolve_console_width called" --mode auto
repowise search "rate limit" --repo backend # workspace, one repo
repowise search "rate limit" --all # workspace, fan-out
```
+The default payload is a trimmed projection carrying `score`, `title`,
+`page_type`, `path` and `snippet` per hit (symbol hits carry `name`,
+`qualified_name`, `kind`, `path`, `line` and the `symbol_id` you pass to
+`repowise symbol`), plus `candidates` — the distinct openable files the hits
+resolve to. `--full` returns the tool's own dict instead.
+
For a synthesized answer rather than a keyword lookup, use `repowise ask`.
---
@@ -565,9 +583,15 @@ editor's MCP client receives. Measured on this repository:
| `why` (question) | 10.4 KB | 20.9 KB |
| `why` (path) | 10.4 KB | 28.5 KB |
| `symbol` | 0.7 KB | 1.0 KB |
+| `search` (8 hits) | 4.9 KB | 6.8 KB |
+| `search --mode symbol` | 4.2 KB | 5.7 KB |
+| `risk --target` (one file) | 4.5 KB | 5.3 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
+envelope is dropped. `search` and `risk --target` are close for the same
+reason: a ranked hit and a risk card are already mostly the answer, so the trim
+takes ranking internals rather than content. The point of `--full` there is
+exactness, not size. 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`.
@@ -642,7 +666,10 @@ to the model's baseline commit, not this repo.
| `--ext` | Comma-separated file suffixes to count (e.g. `.py` or `.ts,.tsx`) |
| `--exclude` / `-x` | Gitignore-style path pattern to omit. Repeatable; filters both the change and baseline. Root `.riskignore` patterns also apply. |
| `--baseline` | Recent commits to sample for the repo-relative percentile (default 200; `0` shows only the absolute calibrated band) |
+| `--target` / `-t` | Score what history says about these **files** instead of a change. Repeatable; switches the command to the `get_risk` tool |
+| `--changed-file` | With `--target`: PR mode. Leads with a directive naming what will break, which co-changes and tests are missing, and what to run |
| `--format` | Output format: `table` (default) or `json` |
+| `--full` | With `--target`: emit the complete tool payload as JSON (implies `--format json`) |
```bash
repowise risk # score HEAD
@@ -651,6 +678,22 @@ repowise risk --ext .ts,.tsx # restrict to specific suffixes
repowise risk main..HEAD -x 'tests/' -x '*.spec.ts' # omit tests from scoring
```
+**`--target`: what history says about touching some files.** Two questions, one
+command, because they are the same question asked of different subjects. A
+`REVSPEC` scores a *change* from its diff shape; `--target` reports bug-fix
+pressure, churn trend, dependents, co-change partners and ownership for the
+named *files*. That half reads the index, so unlike the REVSPEC path it needs
+`repowise init` to have run. It is the `get_risk` MCP tool.
+
+```bash
+repowise risk --target src/auth.py # one file's history
+repowise risk -t src/auth.py -t src/session.py # several
+repowise risk -t src/auth.py --changed-file src/auth.py # PR mode + directive
+```
+
+Note `--path` on this command already means "the git repository", which is why
+the files are named with `--target`.
+
See [`docs/layers/CHANGE_RISK.md`](../layers/CHANGE_RISK.md) for the scoring model.
---
diff --git a/packages/cli/src/repowise/cli/commands/_tool_adapters.py b/packages/cli/src/repowise/cli/commands/_tool_adapters.py
index d44f279a2..ae444ceaf 100644
--- a/packages/cli/src/repowise/cli/commands/_tool_adapters.py
+++ b/packages/cli/src/repowise/cli/commands/_tool_adapters.py
@@ -196,16 +196,39 @@ def emit_error(payload: dict, fmt: str, *, extra: dict | None = None) -> None:
if fmt == "json":
emit_json({**(extra or {}), "error": error, **companions})
else:
+ # Escaped: a shaped internal error interpolates the exception verbatim,
+ # and exception text routinely carries brackets (``list[str]``, a repr'd
+ # list of aliases). Unescaped, a stray closing tag raises MarkupError
+ # and the command dies with an empty stdout — which is the exact state
+ # this function exists to prevent.
+ from rich.markup import escape
+
notices = _notices(fmt)
- notices.print(f"[red]{as_cli_prose(str(error))}[/red]")
+ notices.print(f"[red]{escape(as_cli_prose(str(error)))}[/red]")
for value in companions.get("suggestions") or []:
- notices.print(f" [cyan]{value}[/cyan]")
+ notices.print(f" [cyan]{escape(str(value))}[/cyan]")
for key in ("remedy", "guidance"):
if companions.get(key):
- notices.print(f"[dim]{as_cli_prose(str(companions[key]))}[/dim]")
+ notices.print(f"[dim]{escape(as_cli_prose(str(companions[key])))}[/dim]")
raise click.exceptions.Exit(1)
+def owner_share(value: object) -> str:
+ """Render an ownership share, 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%". ``why`` reads it as
+ ``author_commit_pct`` and ``risk`` as ``owner_pct``; same column, so one
+ copy of the normalisation.
+ """
+ try:
+ pct = float(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return "?"
+ return f"{pct * 100 if pct <= 1.0 else pct:.0f}%"
+
+
def index_note(payload: dict) -> dict[str, Any]:
"""The freshness bits of a tool's ``_meta``, as the projections carry them.
@@ -241,6 +264,7 @@ __all__ = [
"emit_error",
"emit_full",
"index_note",
+ "owner_share",
"print_index_note",
"resolve_format_for",
"resolve_indexed_repo",
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.py
index 99ea6847f..67542eca8 100644
--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py
@@ -1,14 +1,24 @@
-"""``repowise risk`` — just-in-time change-risk for a commit or diff range.
+"""``repowise risk`` — just-in-time change risk, for a change or for paths.
-Scores a *change* (not a file) from its diff shape — size, diffusion, author
+Two questions, one command, because they are the same question asked of
+different subjects.
+
+A REVSPEC scores a *change* from its diff shape — size, diffusion, author
familiarity — and prints a 0-10 risk with an attributable breakdown. Runs
in-process: pure git + learned constants, no LLM, no network. A natural
pre-merge / PR gate, complementary to ``repowise health`` (which scores files).
+``--target <path>`` instead asks what history says about touching those files:
+bug-fix pressure, churn trend, dependents, co-change partners, ownership. That
+is the ``get_risk`` MCP tool, and this command is a thin adapter over it — the
+same seam ``ask`` / ``context`` / ``symbol`` / ``why`` use. It reads the index
+rather than git, so the repo must be indexed.
+
Examples:
- repowise risk # score HEAD
- repowise risk abc123 # score a single commit
- repowise risk main..HEAD # score a branch / PR range as one change
+ repowise risk # score HEAD
+ repowise risk abc123 # score a single commit
+ repowise risk main..HEAD # score a branch / PR range as one change
+ repowise risk --target a.py -t b.py # what history says about those files
"""
from __future__ import annotations
@@ -18,7 +28,9 @@ import json
import click
from rich.table import Table
+from repowise.cli.commands import _tool_adapters as _ta
from repowise.cli.helpers import console, err_console
+from repowise.cli.output import emit_json, format_option, full_option
from repowise.core.analysis.change_risk import (
change_risk_payload,
review_priority_classification,
@@ -33,6 +45,326 @@ _PRIORITY_LEAD = {
}
+#: Per-target keys the trim drops, and nothing else.
+#:
+#: A denylist, not an allowlist, and deliberately so: the failure mode of a
+#: denylist is a payload slightly larger than intended, while the failure mode
+#: of an allowlist is a silently discarded answer — which is the mistake the
+#: adapter commands' first projections made eight times over. ``get_risk``'s
+#: card is a page of small scalars rather than a block of source, so there is
+#: little to win by trimming harder and a lot to lose.
+#:
+#: ``_base_dep_count`` is bookkeeping the tool uses to rebuild ``risk_summary``
+#: after enrichment. ``impact_surface`` is the transitive dependent set, the one
+#: genuinely unbounded block, and its own summary counts survive in
+#: ``risk_summary`` and ``dependents_count``.
+_DROPPED_TARGET_KEYS = ("_base_dep_count", "impact_surface")
+
+
+def _project_target(card: dict) -> dict:
+ """One ``get_risk`` target card, minus the blocks in ``_DROPPED_TARGET_KEYS``."""
+ return {k: v for k, v in card.items() if k not in _DROPPED_TARGET_KEYS}
+
+
+def project_risk(payload: dict) -> dict:
+ """``get_risk``'s dict, trimmed to what a CLI caller reads.
+
+ Kept whole: ``directive`` (in PR mode this *is* the answer, and the tool's
+ own docstring tells a reader to lead with it), ``pr_blast_radius``,
+ ``global_hotspots``, and the freshness half of ``_meta``. Dropped: the
+ timing half of ``_meta``, and the per-target keys named above.
+
+ ``pr_blast_radius`` survives although ``directive`` summarises much of it,
+ because ``recommended_reviewers`` has no substitute anywhere else in the
+ response, and because the tool has *already* capped its four noisy lists
+ (15/10/10/5) before it gets here — so the block a caller would most want is
+ the one an allowlist would silently discard, at almost no size.
+ """
+ out: dict = {
+ "targets": {
+ name: _project_target(card) for name, card in (payload.get("targets") or {}).items()
+ }
+ }
+ for key in ("directive", "pr_blast_radius", "global_hotspots", "omission_marker"):
+ if payload.get(key):
+ out[key] = payload[key]
+ note = _ta.index_note(payload)
+ if note:
+ out["index"] = note
+ return out
+
+
+def _target_risk(
+ repo_path: str,
+ targets: tuple[str, ...],
+ changed_files: tuple[str, ...],
+ fmt: str,
+ full: bool,
+) -> None:
+ """``--target``: what history says about touching these files."""
+ fmt = _ta.resolve_format_for(fmt, full)
+ repo = _ta.resolve_indexed_repo(
+ path=repo_path,
+ repo_alias=None,
+ no_workspace=False,
+ fmt=fmt,
+ command="risk",
+ )
+
+ def _factory():
+ from repowise.server.mcp_server.tool_risk.get_risk import get_risk
+
+ return get_risk(
+ targets=list(targets),
+ changed_files=list(changed_files) or None,
+ )
+
+ payload = _ta.run(repo, _factory, "get_risk")
+
+ if full:
+ _ta.emit_full(payload)
+ return
+ _ta.emit_error(payload, fmt, extra={"targets": list(targets)})
+ projected = project_risk(payload)
+ if fmt == "json":
+ emit_json(projected)
+ return
+ _render_target_risk(projected, targets)
+ _ta.print_index_note(payload, fmt)
+
+
+def _render_target_risk(projected: dict, requested: tuple[str, ...]) -> None:
+ """The human path for ``--target``: the directive first, then a card each."""
+ from rich.markup import escape
+
+ directive = projected.get("directive")
+ if directive:
+ # PR mode leads with the directive because that is the tool's contract:
+ # what will break, what is missing, what to run.
+ console.print(f"\n[bold]Directive[/bold] {escape(str(directive.get('summary', '')))}")
+ for label, key in (
+ ("Will break", "will_break"),
+ ("Tests likely broken", "will_break_tests"),
+ ("Missing co-changes", "missing_cochanges"),
+ ("Files without tests", "missing_tests"),
+ ("Tests to run", "tests_to_run"),
+ ):
+ _print_list(label, directive.get(key) or [])
+ for label, key in _DIRECTIVE_RECORD_BLOCKS:
+ _print_records(label, directive.get(key) or [], key)
+
+ targets = projected.get("targets") or {}
+ for name in requested:
+ card = targets.get(name)
+ if card is None:
+ # An excluded path is filtered out of the request before the tool
+ # sees it, so a requested target with no card is an answer ("this
+ # is not indexed here"), not a gap to render as an empty section.
+ console.print(f"\n[yellow]{escape(name)} — not indexed (or excluded).[/yellow]")
+ continue
+ _render_card(name, card)
+ # Anything the tool returned that was not asked for by name (it normalises
+ # paths), so a caller never loses a card to a spelling difference.
+ for name, card in targets.items():
+ if name not in requested:
+ _render_card(name, card)
+
+ hotspots = projected.get("global_hotspots") or []
+ if hotspots:
+ table = Table(title="Elsewhere in this repo")
+ table.add_column("File", style="cyan")
+ table.add_column("Hotspot", justify="right")
+ table.add_column("Owner")
+ table.add_column("Fixes", justify="right")
+ for h in hotspots:
+ score = h.get("hotspot_score")
+ fixes = h.get("fix_count")
+ table.add_row(
+ escape(str(h.get("file_path", ""))),
+ "?" if score is None else f"{float(score):.0%}",
+ escape(str(h.get("primary_owner") or "unknown")),
+ "" if fixes is None else str(fixes),
+ )
+ console.print(table)
+
+ if projected.get("omission_marker"):
+ # Printed escaped: it opens with a bracket, which rich would parse as a
+ # style tag and delete outright, taking the expand handle with it.
+ console.print(escape(str(projected["omission_marker"])), style="cyan")
+
+
+def _render_card(name: str, card: dict) -> None:
+ """One target's risk card."""
+ from rich.markup import escape
+
+ console.print(f"\n[bold cyan]{escape(name)}[/bold cyan]")
+ summary = card.get("risk_summary")
+ if summary:
+ console.print(f" {escape(str(summary))}")
+ trend = card.get("trend") or "unknown"
+ console.print(
+ f" [dim]hotspot {float(card.get('hotspot_score') or 0.0):.0%} ({trend}) · "
+ f"{card.get('dependents_count', 0)} dependents · "
+ f"{card.get('risk_type', 'unknown')} · owned "
+ f"{_ta.owner_share(card.get('owner_pct'))} by "
+ f"{escape(str(card.get('primary_owner') or 'unknown'))}[/dim]"
+ )
+ # Kept in the projection, so each owes a line here: a key kept in the
+ # payload that no renderer prints is the second silent failure mode of a
+ # trim, and the one a projection test cannot see.
+ health = card.get("health_score")
+ coverage = card.get("coverage_pct")
+ if health is not None or coverage is not None:
+ parts = []
+ if health is not None:
+ parts.append(f"health {float(health):.1f}/10")
+ if coverage is not None:
+ parts.append(f"coverage {float(coverage):.0f}%")
+ console.print(f" [dim]{escape(' · '.join(parts))}[/dim]")
+ # Keyed ``biomarker_type``, not ``name`` — a generic key guess prints the
+ # whole dict repr, which is how the directive blocks went wrong too.
+ biomarkers = card.get("top_biomarkers") or []
+ if biomarkers:
+ shown = []
+ for b in biomarkers[:3]:
+ if not isinstance(b, dict):
+ shown.append(str(b))
+ continue
+ where = f" in {b['function_name']}" if b.get("function_name") else ""
+ shown.append(f"{b.get('biomarker_type', '?')} ({b.get('severity', '?')}){where}")
+ console.print(f" [dim]{escape(', '.join(shown))}[/dim]")
+ magnitude = card.get("change_magnitude") or {}
+ if magnitude:
+ console.print(
+ f" [dim]+{magnitude.get('lines_added_90d', 0)} / "
+ f"-{magnitude.get('lines_deleted_90d', 0)} lines in 90d · "
+ f"avg commit {magnitude.get('avg_commit_size', 0)} lines · "
+ f"{card.get('contributor_count', 0)} contributor(s), "
+ f"bus factor {card.get('bus_factor', '?')}[/dim]"
+ )
+ if card.get("original_path"):
+ console.print(f" [dim]Renamed from {escape(str(card['original_path']))}.[/dim]")
+ if card.get("recent_owner") and card["recent_owner"] != card.get("primary_owner"):
+ # Ownership has moved: the historical owner is not who to ask now.
+ console.print(
+ f" [dim]Recently owned {_ta.owner_share(card.get('recent_owner_pct'))} by "
+ f"{escape(str(card['recent_owner']))}.[/dim]"
+ )
+ cross = card.get("cross_repo_impact") or {}
+ if cross:
+ repos = cross.get("affected_repos") or []
+ consumers = cross.get("cross_repo_consumers") or []
+ contracts = cross.get("contract_consumers") or []
+ console.print(
+ f" [bold]Crosses repo boundaries[/bold] [dim]{len(consumers)} consumer(s)"
+ + (f", {len(contracts)} contract link(s)" if contracts else "")
+ + (f" in {', '.join(str(r) for r in repos)}" if repos else "")
+ + "[/dim]"
+ )
+ defect = card.get("defect_profile")
+ if defect:
+ magnet = " [magenta](bug magnet)[/magenta]" if defect.get("bug_magnet") else ""
+ console.print(
+ f" [yellow]{defect.get('fix_count', 0)} bug fix(es)[/yellow], last "
+ f"{defect.get('last_fix_days_ago', '?')} day(s) ago{magnet}"
+ )
+ # ``top_symbols`` is a ``{name: fix_count}`` dict, not a list; iterating
+ # it bare prints the names and throws the counts away.
+ top = defect.get("top_symbols") or {}
+ pairs = top.items() if isinstance(top, dict) else [(s, None) for s in top]
+ _print_list(
+ "Mostly in",
+ [f"{name}" + (f" (x{count})" if count is not None else "") for name, count in pairs],
+ indent=" ",
+ )
+ if card.get("test_gap"):
+ console.print(" [yellow]No test file matches this file's name.[/yellow]")
+ for signal in card.get("security_signals") or []:
+ console.print(
+ f" [red]{escape(str(signal.get('severity', '')))}[/red] "
+ f"{escape(str(signal.get('kind', '')))}: {escape(str(signal.get('snippet', '')))}"
+ )
+ partners = card.get("co_change_partners") or []
+ if partners:
+ console.print(" [bold]Co-changes with[/bold]")
+ for p in partners[:8]:
+ link = " [dim](imports)[/dim]" if p.get("has_import_link") else ""
+ # A recency-decayed weight rather than a raw tally, so it is not an
+ # integer; ``:g`` keeps a whole number whole and trims the rest.
+ count = p.get("count", 0)
+ shown = f"{float(count):.1f}".rstrip("0").rstrip(".") if count else "0"
+ console.print(
+ f" {escape(str(p.get('file_path', '')))} [dim]x{shown}[/dim]{link}"
+ )
+ if len(partners) > 8:
+ console.print(f" [dim]… and {len(partners) - 8} more (--format json).[/dim]")
+ episodes = card.get("episodes")
+ if episodes:
+ console.print(f" [dim]{episodes} recorded episode(s) — see 'repowise why'.[/dim]")
+
+
+def _print_list(label: str, values: list[str], *, indent: str = " ") -> None:
+ from rich.markup import escape
+
+ if not values:
+ return
+ console.print(f"{indent}[bold]{label}[/bold] " + ", ".join(escape(str(v)) for v in values))
+
+
+#: The directive blocks whose entries are dicts, with a formatter each.
+#:
+#: One shared "try these keys in order" chain does not work here: the six
+#: blocks are built in ``tool_risk/directives.py`` with six different key sets
+#: and only two of them carry any key a generic chain would guess, so the other
+#: four printed as raw Python dict reprs. Each formatter is written against
+#: that module's construction site.
+_DIRECTIVE_RECORD_BLOCKS = (
+ ("Consumers that may break", "will_break_consumers"),
+ ("Missing cross-repo co-changes", "missing_cross_repo_cochanges"),
+ ("Breaking contract changes", "breaking_changes"),
+ ("Conformance violations", "conformance_violations"),
+ ("Dependency cycles", "dependency_cycles"),
+ ("Governance risk", "governance_risk"),
+)
+
+
+def _record_text(key: str, entry: dict) -> str:
+ """One directive entry as a line, per the shape its block is built with."""
+ if key in ("will_break_consumers", "missing_cross_repo_cochanges"):
+ where = f" [{entry.get('repo')}]" if entry.get("repo") else ""
+ return f"{entry.get('service') or entry.get('repo') or '?'}{where}"
+ if key == "breaking_changes":
+ consumers = entry.get("impacted_consumers") or []
+ who = f" — endangers {len(consumers)} consumer(s)" if consumers else ""
+ return (
+ f"{entry.get('contract_id') or '?'}: {entry.get('kind') or '?'}"
+ f" ({entry.get('severity') or '?'}) {entry.get('detail') or ''}{who}".rstrip()
+ )
+ if key == "conformance_violations":
+ rule = entry.get("rule") or f"{entry.get('source')} -> {entry.get('target')}"
+ return f"{rule}{': ' + entry['description'] if entry.get('description') else ''}"
+ if key == "dependency_cycles":
+ nodes = entry.get("nodes") or []
+ return " -> ".join(str(n) for n in nodes) or f"cycle of {entry.get('length', '?')}"
+ if key == "governance_risk":
+ # ``reason`` alone is a bare enum-ish token; the title is what names
+ # the decision the change runs into.
+ return f"{entry.get('title') or entry.get('decision_id') or '?'} ({entry.get('reason')})"
+ return str(entry)
+
+
+def _print_records(label: str, values: list, key: str) -> None:
+ """A directive block whose entries are dicts, one line each."""
+ from rich.markup import escape
+
+ if not values:
+ return
+ console.print(f" [bold]{label}[/bold]")
+ for entry in values:
+ text = _record_text(key, entry) if isinstance(entry, dict) else str(entry)
+ console.print(f" {escape(str(text))}")
+
+
def _ordinal(n: int) -> str:
"""1 -> '1st', 2 -> '2nd', 93 -> '93rd', 11 -> '11th'."""
suffix = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
@@ -72,21 +404,51 @@ def _ordinal(n: int) -> str:
help="Gitignore-style pattern to exclude. Repeatable; also applies to the baseline.",
)
@click.option(
- "--format",
- "fmt",
- default="table",
- type=click.Choice(["table", "json"]),
- help="Output format.",
+ "--target",
+ "-t",
+ "targets",
+ multiple=True,
+ metavar="PATH",
+ help="Score what history says about these FILES instead of a change. "
+ "Repeatable. Reads the index, so the repo must be indexed.",
+)
+ "--changed-file",
+ "changed_files",
+ multiple=True,
+ metavar="PATH",
+ help="With --target: PR mode. The response leads with a directive naming "
+ "what will break, which co-changes and tests are missing, and what to run.",
)
+@format_option()
+@full_option()
def risk_command(
revspec: str,
repo_path: str,
ext: str | None,
baseline: int,
exclude: tuple[str, ...],
+ targets: tuple[str, ...],
+ changed_files: tuple[str, ...],
fmt: str,
+ full: bool,
) -> None:
- """Score the defect risk of a change (commit or ``base..head`` range)."""
+ """Score the defect risk of a change, or of touching some files.
+
+ With no --target this scores REVSPEC (a commit, or a ``base..head``
+ range) from its diff. With --target it reports what the repo's history
+ says about the named files, the same as the get_risk MCP tool.
+ """
+ if targets:
+ _target_risk(repo_path, targets, changed_files, fmt, full)
+ return
+ if changed_files:
+ raise click.UsageError("--changed-file needs at least one --target.")
+ # ``--full`` means "the complete payload, as JSON" on every command that has
+ # it. The REVSPEC path has no tool to be raw about, but it does have a full
+ # payload, and silently ignoring the flag would hand a script that asked for
+ # JSON a rich table and exit 0.
+ fmt = _ta.resolve_format_for(fmt, full)
extensions = tuple(e.strip() for e in ext.split(",")) if ext else ()
status = err_console if fmt != "table" else console
diff --git a/packages/cli/src/repowise/cli/commands/search_cmd.py b/packages/cli/src/repowise/cli/commands/search_cmd.py
index aa1868b5f..15167007c 100644
--- a/packages/cli/src/repowise/cli/commands/search_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/search_cmd.py
@@ -1,79 +1,166 @@
-"""``repowise search`` — full-text, semantic, and symbol search."""
+"""``repowise search`` — the CLI adapter over the ``search_codebase`` MCP tool.
+
+This command used to carry its own retrieval: an FTS query, a LanceDB query,
+a ``LIKE`` over ``wiki_symbols``, and a workspace fan-out that fused them. All
+of that is what ``search_codebase`` already does, better — it fuses FTS and
+vector legs through RRF rather than picking one, honours per-repo excludes and
+tombstones, demotes decision and test pages on queries that did not ask for
+them, and can route an identifier-shaped query to the symbol index. The command
+is now a thin adapter, so a CLI answer and an MCP answer are the same answer.
+
+Two things are deliberately preserved across the collapse.
+
+**The flag vocabulary.** ``--mode fulltext|semantic|symbol`` still works and is
+still what ``--help`` documents; the tool's own ``auto|concept|path|hybrid``
+are accepted as additional choices. Nobody's script breaks.
+
+**The payload.** The default projection emits the keys this command has always
+emitted (``score/title/page_type/path/snippet``), so the collapse is
+payload-neutral by default; ``--full`` returns the tool's raw dict, the same
+switch the other adapter commands carry.
+"""
from __future__ import annotations
import click
from rich.table import Table
-from repowise.cli.helpers import (
- console,
- ensure_repowise_dir,
- get_db_url_for_repo,
- resolve_command_target,
- run_async,
-)
-from repowise.cli.output import emit_json, format_option
+from repowise.cli.commands import _tool_adapters as _ta
+from repowise.cli.helpers import console
+from repowise.cli.output import emit_json, format_option, full_option
from repowise.cli.output import notice_console as _notices
-# Rank-fusion damping for the workspace fan-out, matching the value the server's
-# retrieval fusion uses. Only reached when repos in one workspace answered on
-# different score scales (some semantic, some full-text), where the raw scores
-# are not comparable and the rank is the only shared quantity.
+# Rank-fusion damping for the workspace fan-out. The tool federates internally
+# through a workspace registry the CLI does not build (see ``tool_bridge``), so
+# ``--all`` calls it once per repo and fuses the ranked lists here. k=60 is the
+# same constant ``_federated_search`` uses, so a fanned-out CLI search ranks the
+# way a fanned-out MCP search does.
_WORKSPACE_RRF_K = 60
+#: CLI mode spelling -> the tool's ``mode=`` argument.
+#:
+#: ``fulltext`` and ``semantic`` both land on ``concept``: the tool's concept
+#: branch fuses the full-text and vector legs through RRF instead of choosing
+#: between them, so it is the successor to both, and it drops the vector leg by
+#: itself on a keyless index (``_safe_vector``) exactly where ``--mode
+#: semantic`` used to fall back to full text by hand.
+_MODE_ALIASES = {"fulltext": "concept", "semantic": "concept", "symbol": "symbol"}
+
+#: What ``--mode`` accepts. The legacy three first, because they are the
+#: documented spelling and one of them is still the default.
+_MODE_CHOICES = ["fulltext", "semantic", "symbol", "auto", "concept", "path", "hybrid"]
+
-def _answered_mode(requested: str, keyless_repos: list[str], mixed_scales: bool) -> str:
- """Which retrieval actually answered, which is not always what was asked.
+def _tool_mode(requested: str) -> str:
+ """The tool's ``mode=`` for a CLI ``--mode``; tool spellings pass through."""
+ return _MODE_ALIASES.get(requested, requested)
- ``--mode semantic`` against a repo with no usable embedder falls through to
- full text. Reporting the request rather than the answer is how someone
- concludes semantic retrieval is bad when what they have is no embedder, and
- for a machine consumer it is worse: FTS returns a negated FTS5 rank and
- LanceDB returns ``1 - cosine``, so ``score`` means two different things
- under one label.
- In a workspace fan-out both can be true at once — some repos answered
- semantically, others fell back — and that is reported as ``mixed`` rather
- than collapsed to either side. It is the same condition the ranking code
- already detects, where it fuses on rank because the scores are not
- comparable.
+def _result_kind(item: dict) -> str:
+ """``symbol`` / ``file`` / ``page`` for one result, whatever mode produced it.
+
+ Symbol and path search tag their results with ``type``; the concept path
+ does not tag its pages at all except inside a hybrid interleave, so an
+ untagged hit is a page.
+ """
+ kind = item.get("type")
+ return kind if kind in ("symbol", "file") else "page"
+
+
+def _project_result(item: dict, *, multi: bool) -> dict:
+ """One tool result, trimmed to the keys this command has always emitted.
+
+ Three result shapes reach here and they do not share a payload, so the
+ projection dispatches on :func:`_result_kind` rather than taking a fixed
+ key list. Each shape keeps the columns its table has always shown, plus
+ the one handle that makes the hit actionable:
+
+ ========== ==============================================================
+ page ``score`` (from ``relevance_score``), ``title``, ``page_type``,
+ ``path`` (from ``target_path``), ``snippet``
+ symbol ``score``, ``name``, ``qualified_name``, ``kind``, ``path``
+ (from ``file``), ``line`` (from ``start_line``), and
+ ``symbol_id`` — the id ``repowise symbol`` takes, without
+ which a symbol hit cannot be followed anywhere
+ file ``score``, ``title``, ``path`` (from ``file``)
+ ========== ==============================================================
+
+ Dropped: ``page_id``, ``sources``, ``confidence_score``, ``end_line``,
+ ``signature``, ``language`` and ``next`` — call envelope and ranking
+ internals, all of them in ``--full``.
+
+ ``type`` is emitted on every row although the old payload had none. It was
+ unambiguous when every row in a response was a page; ``hybrid`` interleaves
+ symbol hits with page hits, so without it a consumer cannot tell which keys
+ a row even has.
"""
- if requested != "semantic" or not keyless_repos:
- return requested
- return "mixed" if mixed_scales else "fulltext"
+ kind = _result_kind(item)
+ score = item.get("relevance_score") if kind == "page" else item.get("score")
+ out: dict = {"type": kind, "score": round(float(score or 0.0), 6)}
+ if kind == "symbol":
+ out.update(
+ {
+ "name": item.get("name") or "",
+ "qualified_name": item.get("qualified_name") or "",
+ "kind": item.get("kind") or "",
+ "path": item.get("file") or "",
+ "line": item.get("start_line"),
+ "symbol_id": item.get("symbol_id") or "",
+ }
+ )
+ elif kind == "file":
+ out.update({"title": item.get("title") or "", "path": item.get("file") or ""})
+ else:
+ out.update(
+ {
+ "title": item.get("title") or "",
+ "page_type": item.get("page_type") or "",
+ "path": item.get("target_path") or "",
+ "snippet": item.get("snippet") or "",
+ }
+ )
+ # ``target_path`` on a symbol_spotlight is a page id (``a.py::Foo``),
+ # not something a reader can open, which is why the tool attaches
+ # ``file`` beside it. ``path`` keeps the tool's own value so the
+ # payload stays what it was; ``file`` carries the openable resolution
+ # and appears only when the two differ.
+ file = item.get("file")
+ if file and file != out["path"]:
+ out["file"] = file
+ if multi:
+ out["repo"] = item.get("repo") or ""
+ return out
-def _page_payload(result, repo_name: str | None = None) -> dict:
- """One wiki-page hit as plain data.
+def project(payload: dict, query: str, *, multi: bool) -> dict:
+ """``search_codebase``'s dict, trimmed to what a CLI caller reads.
- Snippets are not clipped to 50 chars the way the table clips them: the
- table does it to fit a column, and a consumer that asked for JSON has no
- column to fit.
+ Kept beside ``results``: ``candidates`` (the distinct openable files the
+ hits resolve to — some results are pages, and this is what to read),
+ ``exact_match`` and ``note`` (an identifier query that matched no indexed
+ symbol still returns fuzzy neighbours; the note is what stops a caller
+ anchoring on one), ``grep_hint`` (the zero-result recovery path), and the
+ freshness half of ``_meta``. Each of those changes the answer rather than
+ its size, which is the line this trim draws.
+
+ Dropped: the timing and token halves of ``_meta``, and the per-result keys
+ named in :func:`_project_result`.
"""
- payload = {
- "score": round(float(getattr(result, "score", 0.0)), 6),
- "title": result.title or "",
- "page_type": result.page_type or "",
- "path": result.target_path or "",
- "snippet": result.snippet or "",
- }
- if repo_name is not None:
- payload["repo"] = repo_name
- return payload
-
-
-def _symbol_payload(row, repo_name: str | None = None) -> dict:
- """One ``wiki_symbols`` row as plain data, in the SELECT's column order."""
- payload = {
- "name": str(row[0]),
- "qualified_name": str(row[1]),
- "kind": str(row[2]),
- "path": str(row[3]),
- "line": row[4],
+ out: dict = {
+ "query": query,
+ # Only the structured branches report the mode they resolved to. The
+ # concept branch and the federated one are concept by construction and
+ # report nothing, so an absent key is not an unknown.
+ "mode": payload.get("mode") or "concept",
+ "results": [_project_result(r, multi=multi) for r in payload.get("results") or []],
}
- if repo_name is not None:
- payload["repo"] = repo_name
- return payload
+ for key in ("candidates", "exact_match", "note", "grep_hint"):
+ if payload.get(key) is not None:
+ out[key] = payload[key]
+ note = _ta.index_note(payload)
+ if note:
+ out["index"] = note
+ return out
@click.command("search")
@@ -81,9 +168,10 @@ def _symbol_payload(row, repo_name: str | None = None) -> dict:
@click.argument("path", required=False, default=None)
@click.option(
"--mode",
- type=click.Choice(["fulltext", "semantic", "symbol"]),
+ type=click.Choice(_MODE_CHOICES),
default="fulltext",
- help="Search mode.",
+ help="Search mode. fulltext/semantic both run the tool's fused concept "
+ "search; auto routes on the query's shape.",
)
@click.option("--limit", type=int, default=10, help="Max results.")
@click.option(
@@ -106,6 +194,7 @@ def _symbol_payload(row, repo_name: str | None = None) -> dict:
help="Force single-repo mode even when invoked from a workspace.",
)
@format_option()
+@full_option()
def search_command(
query: str,
path: str | None,
@@ -115,14 +204,23 @@ def search_command(
search_all: bool,
no_workspace: bool,
fmt: str,
+ full: bool,
) -> None:
"""Search wiki pages by keyword, meaning, or symbol name.
+ Runs the same hybrid retrieval as the search_codebase MCP tool: the
+ full-text and vector legs are fused rather than chosen between, and
+ --mode symbol/path/hybrid reach the structural indexes.
+
In workspace mode, defaults to the primary repo; pass --repo <alias>
for a specific one or --all to search across every indexed repo.
"""
from pathlib import Path
+ from repowise.cli.helpers import ensure_repowise_dir, resolve_command_target
+
+ fmt = _ta.resolve_format_for(fmt, full)
+ tool_mode = _tool_mode(mode)
target = resolve_command_target(
path=path,
no_workspace_flag=no_workspace,
@@ -153,384 +251,301 @@ def search_command(
repo_paths = [p for p in repo_paths if (p / ".repowise").is_dir()]
if not repo_paths:
notices.print("[yellow]No indexed repos to search. Run 'repowise init' first.[/yellow]")
- # json mode still owes stdout a parseable document, not nothing.
+ # Every early return owes stdout a document: a json caller cannot tell
+ # an empty pipe from a crash.
if fmt == "json":
- emit_json({"query": query, "mode": mode, "results": []})
+ emit_json({"query": query, "mode": tool_mode, "results": []})
return
if len(repo_paths) == 1:
repo_path = repo_paths[0]
ensure_repowise_dir(repo_path)
- if mode == "fulltext":
- _search_fulltext(repo_path, query, limit, fmt)
- elif mode == "semantic":
- _search_semantic(repo_path, query, limit, fmt)
- elif mode == "symbol":
- _search_symbol(repo_path, query, limit, fmt)
- return
-
- # Multi-repo fan-out — gather, rank, render once.
- all_results: list = []
- mixed_scales = False
- keyless_repos: list[str] = []
- for rp in repo_paths:
- try:
- if mode == "fulltext":
- results = _collect_fulltext(rp, query, limit)
- elif mode == "semantic":
- results, served_fulltext = _collect_semantic(rp, query, limit)
- if served_fulltext:
- keyless_repos.append(rp.name)
- else:
- mixed_scales = mixed_scales or bool(results)
- else: # symbol
- results = _collect_symbol(rp, query, limit)
- except Exception as exc:
- notices.print(f"[yellow]search failed for {rp.name}: {exc}[/yellow]")
- continue
- for rank, r in enumerate(results):
- all_results.append((rp.name, r, rank))
-
- if not all_results:
- notices.print("[yellow]No results across the workspace.[/yellow]")
+ payload = _run_search(repo_path, query, limit, tool_mode)
+ if full:
+ _ta.emit_full(payload)
+ return
+ _ta.emit_error(payload, fmt, extra={"query": query, "mode": tool_mode})
+ _warn_if_lexical_only(payload, mode, notices)
+ projected = project(payload, query, multi=False)
if fmt == "json":
- emit_json({"query": query, "mode": mode, "results": []})
+ emit_json(projected)
+ return
+ _render(projected, query, mode, multi=False)
+ _ta.print_index_note(payload, fmt)
return
- if keyless_repos:
- notices.print(
- f"[yellow]No embedder configured for: {', '.join(sorted(keyless_repos))}."
- "[/yellow]\nThose repos contributed full-text results."
- )
+ _fan_out(repo_paths, query, limit, mode, tool_mode, fmt, full, notices)
- if mode == "symbol":
- _render_symbol_rows([(n, r) for n, r, _ in all_results], query, limit, fmt, multi=True)
- else:
- if mode == "semantic" and mixed_scales and keyless_repos:
- # Full-text and vector scores are not the same quantity: FTS returns
- # a negated FTS5 rank (typically >1) and LanceDB returns 1 - cosine
- # distance (roughly 0..1). Sorting them together lets one keyless
- # repo's full-text rows evict every semantic hit in the workspace.
- # Fuse on RANK instead, which is what this codebase already does
- # wherever it combines independently-scored retrievers.
- all_results.sort(key=lambda t: 1.0 / (t[2] + _WORKSPACE_RRF_K), reverse=True)
- else:
- # One scale throughout: the raw score is meaningful, so keep the
- # existing ordering rather than perturbing it with a rank fusion.
- all_results.sort(key=lambda t: getattr(t[1], "score", 0.0), reverse=True)
- all_results = all_results[:limit]
- _display_results_multi(
- [(n, r) for n, r, _ in all_results],
- f"{mode.capitalize()} search: '{query}' (workspace)",
- fmt,
- query=query,
- mode=_answered_mode(mode, keyless_repos, mixed_scales),
- )
+def _run_search(repo_path, query: str, limit: int, tool_mode: str) -> dict:
+ """One ``search_codebase`` call against one repo."""
-def _search_fulltext(repo_path, query: str, limit: int, fmt: str = "table") -> None:
- async def _run():
- from repowise.core.persistence import FullTextSearch, create_engine
-
- url = get_db_url_for_repo(repo_path)
- engine = create_engine(url)
- fts = FullTextSearch(engine)
- results = await fts.search(query, limit=limit)
- await engine.dispose()
- return results
-
- results = run_async(_run())
- _display_results(results, f"Full-text search: '{query}'", fmt, query=query, mode="fulltext")
-
-
-def _search_semantic(repo_path, query: str, limit: int, fmt: str = "table") -> None:
- served_fulltext = False
-
- async def _run():
- nonlocal served_fulltext
- from pathlib import Path
-
- # Try LanceDB first (populated during repowise init)
- lance_dir = Path(repo_path) / ".repowise" / "lancedb"
- if lance_dir.exists():
- try:
- from repowise.cli.providers.embedders import (
- build_embedder,
- resolve_embedder_for_repo,
- )
- from repowise.core.persistence.vector_store import LanceDBVectorStore
- from repowise.core.providers.embedding import store_has_semantic_vectors
-
- embedder = build_embedder(resolve_embedder_for_repo(repo_path))
- store = LanceDBVectorStore(str(lance_dir), embedder=embedder)
- try:
- # A keyless index's own vectors are not discriminative, so
- # ranking on them serves noise as if it were meaning. Fall
- # through to full text instead: `--mode semantic` has to
- # answer with something, and full text is what a keyless
- # index actually offers. Same predicate every other vector
- # read uses; this site was simply never wired to it.
- if store_has_semantic_vectors(store):
- return await store.search(query, limit=limit)
- served_fulltext = True
- finally:
- await store.close()
- except Exception:
- pass
-
- # Fallback to FTS
- from repowise.core.persistence import FullTextSearch, create_engine
-
- url = get_db_url_for_repo(repo_path)
- engine = create_engine(url)
- fts = FullTextSearch(engine)
- results = await fts.search(query, limit=limit)
- await engine.dispose()
- return results
-
- results = run_async(_run())
- if served_fulltext:
- # Say which mode actually answered. Labelling full-text results
- # "Semantic search" is how someone concludes semantic retrieval is bad
- # when what they have is no embedder. This is the common case, not the
- # rare one: a genuinely keyless repo never reaches build_embedder's
- # failure warning, because resolving to the keyless embedder is not a
- # failure.
- #
- # Worded for both states. A repo pinned to a real embedder whose key has
- # since gone away also lands here, having already printed build_embedder's
- # warning; telling that user "no embedder configured" would contradict
- # both their config and the line above it.
- from repowise.cli.providers.embedders import resolve_embedder_for_repo
-
- pinned = resolve_embedder_for_repo(repo_path)
- why = (
- "No embedder configured for this repo"
- if pinned == "mock"
- else f"The '{pinned}' embedder could not be used"
- )
- _notices(fmt).print(
- f"[yellow]{why}, so there is no semantic index to search.[/yellow]\n"
- "Showing full-text results instead. Set an embedder key and run "
- "[cyan]repowise reindex[/cyan] for semantic search."
- )
- _display_results(
- results,
- f"Full-text search: '{query}'" if served_fulltext else f"Semantic search: '{query}'",
- fmt,
- query=query,
- # Say which retrieval actually answered, so a consumer is not told
- # "semantic" when a keyless repo served full text.
- mode="fulltext" if served_fulltext else "semantic",
- )
+ def _factory():
+ from repowise.server.mcp_server.tool_search import search_codebase
+ return search_codebase(query=query, limit=limit, mode=tool_mode)
-def _search_symbol(repo_path, query: str, limit: int, fmt: str = "table") -> None:
- async def _run():
- from sqlalchemy import text as sa_text
+ return _ta.run(repo_path, _factory, "search_codebase")
- from repowise.core.persistence import create_engine, create_session_factory, get_session
- url = get_db_url_for_repo(repo_path)
- engine = create_engine(url)
- sf = create_session_factory(engine)
+def _warn_if_lexical_only(payload: dict, requested: str, notices) -> None:
+ """Say when ``--mode semantic`` was answered lexically, and why.
- async with get_session(sf) as session:
- result = await session.execute(
- sa_text(
- "SELECT name, qualified_name, kind, file_path, start_line "
- "FROM wiki_symbols WHERE name LIKE :pattern LIMIT :limit"
- ),
- {"pattern": f"%{query}%", "limit": limit},
- )
- rows = result.fetchall()
+ ``_meta`` carries ``semantic_search: false`` whenever the vector leg could
+ not be ranked on — a keyless index, or a pinned embedder that would not
+ build — which is the condition this command used to detect for itself
+ before the tool did it. Rendering those rows without saying so is how
+ someone concludes semantic retrieval is bad when what they have is no
+ embedder.
- await engine.dispose()
- return rows
+ Only ``--mode semantic`` is warned about: it is the spelling that promises
+ semantic matching. ``fulltext`` never claimed it, and the tool's own
+ spellings are the tool's contract, where ``_meta`` already says this.
+ """
+ if requested != "semantic":
+ return
+ meta = payload.get("_meta") or {}
+ if meta.get("semantic_search") is not False:
+ return
+ # Worded for both states. A repo pinned to a real embedder whose key has
+ # gone away carries the tool's own reason, which names it; telling that
+ # user "no embedder configured" would contradict their own config.
+ why = meta.get("embedder_warning") or (
+ "No embedder configured for this repo, so there is no semantic index to search."
+ )
+ notices.print(
+ f"[yellow]{why}[/yellow]\nShowing full-text results instead. Set an embedder "
+ "key and run [cyan]repowise reindex[/cyan] for semantic search."
+ )
- rows = run_async(_run())
- # Same renderer as the workspace fan-out — it built an identical table.
- _render_symbol_rows([(None, row) for row in rows], query, limit, fmt, multi=False)
+def _fan_out(
+ repo_paths,
+ query: str,
+ limit: int,
+ mode: str,
+ tool_mode: str,
+ fmt: str,
+ full: bool,
+ notices,
+) -> None:
+ """``--all``: one tool call per repo, fused on rank, rendered once.
-def _display_results(results, title: str, fmt: str = "table", *, query: str, mode: str) -> None:
- if fmt == "json":
- emit_json(
- {
- "query": query,
- "mode": mode,
- "results": [_page_payload(r) for r in results],
- }
+ Rank fusion rather than raw score: each repo scores its own list
+ independently (RRF within a repo for concept mode, a token-overlap score
+ for symbol mode), so the numbers are only comparable within a repo. This is
+ what ``_federated_search`` does with the same constant.
+ """
+ merged: list[tuple[int, dict]] = []
+ payloads: list[dict] = []
+ raw: dict[str, dict] = {}
+ failures: list[str] = []
+ for rp in repo_paths:
+ payload = _run_search(rp, query, limit, tool_mode)
+ raw[rp.name] = payload
+ if payload.get("error"):
+ # One unreadable repo must not take the fan-out down; the others
+ # still have answers. Matches the pre-collapse behaviour.
+ #
+ # Escaped: the shaped error interpolates the exception verbatim and
+ # those routinely carry brackets, so an unescaped ``[/x]`` would
+ # raise MarkupError and take the command down with an empty stdout —
+ # the state every early return in this file exists to avoid.
+ from rich.markup import escape
+
+ failures.append(rp.name)
+ notices.print(
+ f"[yellow]search failed for {rp.name}: {escape(str(payload['error']))}[/yellow]"
+ )
+ continue
+ payloads.append(payload)
+ _warn_if_lexical_only(payload, mode, notices)
+ for rank, item in enumerate(payload.get("results") or []):
+ item["repo"] = rp.name
+ merged.append((rank, item))
+
+ if full:
+ # Every repo's own payload, unmerged and unprojected. There is no single
+ # tool call here to return the payload *of*, and synthesising one would
+ # hand back a dict no tool ever produced while calling it raw.
+ out: dict = {"repos": raw}
+ if not payloads:
+ out["error"] = f"search failed in every repo: {', '.join(failures)}"
+ _ta.emit_full(out)
+ return
+
+ merged.sort(key=lambda pair: 1.0 / (pair[0] + _WORKSPACE_RRF_K), reverse=True)
+ results = [item for _, item in merged[:limit]]
+
+ fused: dict = {"results": results}
+ # Reported from the first repo that answered: the mode is resolved from the
+ # query, which every repo saw, so they all resolved the same one.
+ if payloads and payloads[0].get("mode"):
+ fused["mode"] = payloads[0]["mode"]
+ # Recomputed over the fused window rather than concatenated: the block
+ # promises distinct openable paths, best first, and per-repo lists overlap.
+ from repowise.server.mcp_server._page_paths import file_candidates
+
+ if candidates := file_candidates(results, limit=limit):
+ fused["candidates"] = candidates
+ # A hint or an exact-match verdict is about the query, not the repo, and is
+ # only attached when that repo found nothing — so it is true of the fan-out
+ # only when every repo that answered agrees.
+ for key in ("grep_hint", "note"):
+ values = [p[key] for p in payloads if p.get(key)]
+ if values and len(values) == len(payloads):
+ fused[key] = values[0]
+ if payloads and all("exact_match" in p for p in payloads):
+ fused["exact_match"] = any(p["exact_match"] for p in payloads)
+ fused["_meta"] = _worst_freshness(payloads)
+
+ # "Nothing matched" and "nothing could be searched" are different answers,
+ # and the second one is a failure the exit code has to carry.
+ if not results and not payloads:
+ _ta.emit_error(
+ {"error": f"search failed in every repo: {', '.join(failures)}"},
+ fmt,
+ extra={"query": query, "mode": tool_mode},
)
+ projected = project(fused, query, multi=True)
+ if fmt == "json":
+ emit_json(projected)
return
+ _render(projected, query, mode, multi=True)
+ _ta.print_index_note(fused, fmt)
- table = Table(title=title)
- table.add_column("Score", justify="right", style="green")
- table.add_column("Title", style="cyan")
- table.add_column("Type")
- table.add_column("Path")
- table.add_column("Snippet", max_width=50)
- for r in results:
- table.add_row(
- f"{r.score:.3f}",
- r.title or "",
- r.page_type or "",
- r.target_path or "",
- (r.snippet or "")[:50],
- )
+def _worst_freshness(payloads: list[dict]) -> dict:
+ """The freshness of the fan-out, which is the freshness of its worst repo.
- if not results:
- console.print("[yellow]No results found.[/yellow]")
- else:
- console.print(table)
+ Without this the fan-out reports no ``index`` block and prints no staleness
+ notice, so ``repowise search foo`` would warn that the index is behind while
+ ``repowise search foo --all`` said nothing — and the answer drawn from the
+ most repos is the one most likely to have a stale one among them.
+ """
+ meta: dict = {}
+ for payload in payloads:
+ repo_meta = payload.get("_meta") or {}
+ if repo_meta.get("stale_warning") and not meta.get("stale_warning"):
+ meta["stale_warning"] = repo_meta["stale_warning"]
+ if repo_meta.get("index_behind"):
+ meta["index_behind"] = True
+ # Named so the notice can say which checkout it means; the first
+ # behind repo wins rather than an invented merge of several SHAs.
+ meta.setdefault("indexed_commit", repo_meta.get("indexed_commit", "?"))
+ meta.setdefault("live_head", repo_meta.get("live_head", "?"))
+ age = repo_meta.get("index_age_days")
+ if age is not None:
+ meta["index_age_days"] = max(age, meta.get("index_age_days", age))
+ return meta
# ---------------------------------------------------------------------------
-# Multi-repo (workspace fan-out) helpers
+# Table rendering
# ---------------------------------------------------------------------------
-def _collect_fulltext(repo_path, query: str, limit: int):
- async def _run():
- from repowise.core.persistence import FullTextSearch, create_engine
+def _render(projected: dict, query: str, mode: str, *, multi: bool) -> None:
+ """The human path: one table per result shape, then the tool's own notes.
- url = get_db_url_for_repo(repo_path)
- engine = create_engine(url)
- fts = FullTextSearch(engine)
- results = await fts.search(query, limit=limit)
- await engine.dispose()
- return results
-
- return run_async(_run())
+ A hybrid search interleaves symbol hits and page hits, and the two do not
+ share columns, so they are grouped rather than forced into one table. The
+ groups keep the order they first appear in, which is the tool's ranking.
+ """
+ results = projected.get("results") or []
+ groups: dict[str, list[dict]] = {}
+ for row in results:
+ groups.setdefault(row.get("type") or "page", []).append(row)
+ if not results:
+ from rich.markup import escape
-def _collect_semantic(repo_path, query: str, limit: int):
- """Return ``(results, served_fulltext)`` for one repo in the fan-out.
+ where = " across the workspace" if multi else ""
+ if mode == "symbol":
+ console.print(f"[yellow]No symbols matching '{escape(query)}'{where}[/yellow]")
+ else:
+ console.print(f"[yellow]No results found{where}.[/yellow]")
+ for kind, rows in groups.items():
+ if kind == "symbol":
+ console.print(_symbol_table(rows, query, multi=multi))
+ elif kind == "file":
+ console.print(_file_table(rows, query, multi=multi))
+ else:
+ console.print(_page_table(rows, query, mode, multi=multi))
- The flag is what lets the caller avoid sorting full-text scores against
- vector scores, and what lets it say which repos answered lexically.
- """
- served_fulltext = False
-
- async def _run():
- nonlocal served_fulltext
- from pathlib import Path
-
- from repowise.core.persistence import FullTextSearch, create_engine
-
- lance_dir = Path(repo_path) / ".repowise" / "lancedb"
- if lance_dir.exists():
- try:
- from repowise.cli.providers.embedders import (
- build_embedder,
- resolve_embedder_for_repo,
- )
- from repowise.core.persistence.vector_store import LanceDBVectorStore
- from repowise.core.providers.embedding import store_has_semantic_vectors
-
- embedder = build_embedder(resolve_embedder_for_repo(repo_path))
- store = LanceDBVectorStore(str(lance_dir), embedder=embedder)
- try:
- # See _search_semantic: a keyless store ranks on noise, so
- # this repo falls through to its full-text results rather
- # than contributing a window of them to the workspace fan-out.
- if store_has_semantic_vectors(store):
- return await store.search(query, limit=limit)
- served_fulltext = True
- finally:
- await store.close()
- except Exception:
- pass
-
- url = get_db_url_for_repo(repo_path)
- engine = create_engine(url)
- fts = FullTextSearch(engine)
- results = await fts.search(query, limit=limit)
- await engine.dispose()
- return results
-
- return run_async(_run()), served_fulltext
-
-
-def _collect_symbol(repo_path, query: str, limit: int):
- async def _run():
- from sqlalchemy import text as sa_text
-
- from repowise.core.persistence import create_engine, create_session_factory, get_session
-
- url = get_db_url_for_repo(repo_path)
- engine = create_engine(url)
- sf = create_session_factory(engine)
- async with get_session(sf) as session:
- result = await session.execute(
- sa_text(
- "SELECT name, qualified_name, kind, file_path, start_line "
- "FROM wiki_symbols WHERE name LIKE :pattern LIMIT :limit"
- ),
- {"pattern": f"%{query}%", "limit": limit},
- )
- rows = result.fetchall()
- await engine.dispose()
- return rows
+ _render_notes(projected)
- return run_async(_run())
+def _render_notes(projected: dict) -> None:
+ """``note``, ``grep_hint`` and ``candidates`` — kept keys owe a renderer.
-def _display_results_multi(
- pairs, title: str, fmt: str = "table", *, query: str, mode: str
-) -> None:
- """Render fulltext/semantic results when fanned out across multiple repos."""
- if fmt == "json":
- emit_json(
- {
- "query": query,
- "mode": mode,
- "results": [_page_payload(r, repo_name) for repo_name, r in pairs],
- }
- )
- return
-
- table = Table(title=title)
+ Escaped, because a table cell and ``console.print`` both parse rich markup:
+ a hint quoting ``mode="symbol"`` is harmless but a note quoting a
+ bracketed type would be eaten, and a stray closing tag raises.
+ """
+ from rich.markup import escape
+
+ # ``exact_match: false`` is covered by the note the tool attaches with it;
+ # ``true`` has no note, and silence there leaves a table reader unable to
+ # tell an exact symbol hit from the fuzzy neighbours it ranks beside.
+ if projected.get("exact_match") is True:
+ console.print("[green]Exact symbol match.[/green]")
+ for key in ("note", "grep_hint"):
+ if projected.get(key):
+ console.print(f"[dim]{escape(_ta.as_cli_prose(str(projected[key])))}[/dim]")
+ candidates = projected.get("candidates") or []
+ if candidates:
+ console.print("\n[bold]Files to read[/bold]")
+ for entry in candidates:
+ console.print(f" [cyan]{escape(str(entry.get('path', '')))}[/cyan]")
+
+
+def _titled(query: str, mode: str, *, multi: bool) -> str:
+ # Escaped: a Table title is markup-parsed like any cell, so a query
+ # containing a bracket (`search 'list[str]'`) would lose it, and one
+ # containing a closing tag would raise MarkupError.
+ from rich.markup import escape
+
+ query = escape(query)
+ label = {
+ "fulltext": "Full-text search",
+ "semantic": "Semantic search",
+ "symbol": "Symbol search",
+ "path": "Path search",
+ "hybrid": "Hybrid search",
+ }.get(mode, f"{mode.capitalize()} search")
+ return f"{label}: '{query}' (workspace)" if multi else f"{label}: '{query}'"
+
+
+def _page_table(rows: list[dict], query: str, mode: str, *, multi: bool) -> Table:
+ table = Table(title=_titled(query, mode, multi=multi))
table.add_column("Score", justify="right", style="green")
- table.add_column("Repo", style="magenta")
+ if multi:
+ table.add_column("Repo", style="magenta")
table.add_column("Title", style="cyan")
table.add_column("Type")
table.add_column("Path")
table.add_column("Snippet", max_width=50)
+ from rich.markup import escape
- for repo_name, r in pairs:
- table.add_row(
- f"{r.score:.3f}",
- repo_name,
- r.title or "",
- r.page_type or "",
- r.target_path or "",
- (r.snippet or "")[:50],
- )
- console.print(table)
-
-
-def _render_symbol_rows(pairs, query: str, limit: int, fmt: str = "table", *, multi: bool) -> None:
- """Render symbol rows; ``pairs`` is a list of ``(repo_name, row)`` tuples.
-
- ``repo_name`` is ``None`` in single-repo mode and omitted from the payload.
- """
- if fmt == "json":
- emit_json(
- {
- "query": query,
- "mode": "symbol",
- "results": [
- _symbol_payload(row, repo_name if multi else None)
- for repo_name, row in pairs[:limit]
- ],
- }
- )
- return
-
- title = f"Symbol search: '{query}' (workspace)" if multi else f"Symbol search: '{query}'"
- table = Table(title=title)
+ for row in rows:
+ cells = [f"{float(row.get('score') or 0.0):.3f}"]
+ if multi:
+ cells.append(str(row.get("repo", "")))
+ cells += [
+ str(row.get("title") or ""),
+ str(row.get("page_type") or ""),
+ str(row.get("path") or ""),
+ # The table clips the snippet to fit its column; the JSON payload
+ # does not, because a consumer has no column to fit.
+ str(row.get("snippet") or "")[:50],
+ ]
+ table.add_row(*(escape(c) for c in cells))
+ return table
+
+
+def _symbol_table(rows: list[dict], query: str, *, multi: bool) -> Table:
+ table = Table(title=_titled(query, "symbol", multi=multi))
table.add_column("Name", style="cyan")
if multi:
table.add_column("Repo", style="magenta")
@@ -538,15 +553,35 @@ def _render_symbol_rows(pairs, query: str, limit: int, fmt: str = "table", *, mu
table.add_column("Kind")
table.add_column("File")
table.add_column("Line", justify="right")
+ from rich.markup import escape
- for repo_name, row in pairs[:limit]:
- cells = [str(row[0])]
+ for row in rows:
+ cells = [str(row.get("name") or "")]
if multi:
- cells.append(repo_name)
- cells += [str(row[1]), str(row[2]), str(row[3]), str(row[4])]
- table.add_row(*cells)
+ cells.append(str(row.get("repo", "")))
+ cells += [
+ str(row.get("qualified_name") or ""),
+ str(row.get("kind") or ""),
+ str(row.get("path") or ""),
+ "" if row.get("line") is None else str(row["line"]),
+ ]
+ table.add_row(*(escape(c) for c in cells))
+ return table
- if not pairs:
- console.print(f"[yellow]No symbols matching '{query}'[/yellow]")
- else:
- console.print(table)
+
+def _file_table(rows: list[dict], query: str, *, multi: bool) -> Table:
+ from rich.markup import escape
+
+ table = Table(title=_titled(query, "path", multi=multi))
+ table.add_column("Score", justify="right", style="green")
+ if multi:
+ table.add_column("Repo", style="magenta")
+ table.add_column("Title", style="cyan")
+ table.add_column("Path")
+ for row in rows:
+ cells = [f"{float(row.get('score') or 0.0):.3f}"]
+ if multi:
+ cells.append(str(row.get("repo", "")))
+ cells += [str(row.get("title") or ""), str(row.get("path") or "")]
+ table.add_row(*(escape(c) for c in cells))
+ return table
diff --git a/packages/cli/src/repowise/cli/commands/why_cmd.py b/packages/cli/src/repowise/cli/commands/why_cmd.py
index bc4b2f872..900eff8a9 100644
--- a/packages/cli/src/repowise/cli/commands/why_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/why_cmd.py
@@ -429,18 +429,10 @@ _RENDERABLE_BLOCKS = (
)
-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}%"
+#: Re-exported for the module's own readers; ``risk`` renders the same field
+#: (``owner_pct``) off the same git metadata, so the normalisation lives in
+#: ``_tool_adapters`` and both callers share one copy.
+_owner_share = _ta.owner_share
def _render_archaeology(console, arch: dict, *, indent: str) -> None:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index 9b5b9b6e3..44abe5aaa 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -890,8 +890,14 @@ async def _structured_search(
# hybrid modes the ranked pool leads with symbol hits, and those are the
# entries most likely to collapse onto one another (several symbols of one
# file). Deduping them is the point.
- if candidates := file_candidates(results, limit=limit):
- response["candidates"] = candidates
+ #
+ # Bound to its own name, NOT to ``candidates``: that one holds the query's
+ # identifiers, which the exact-match note below quotes. Rebinding it here
+ # made the note quote file paths as if they were the identifiers asked for,
+ # and — worse — made its gate true for any query with results at all, so a
+ # prose query that names no identifier was told no symbol matched it.
+ if file_cands := file_candidates(results, limit=limit):
+ response["candidates"] = file_cands
# Exact-match honesty: an identifier-shaped query whose target names no
# indexed symbol still returns fuzzy neighbours. Say so, or the agent
# anchors on a wrong hit that looks authoritative (their Alamofire
diff --git a/tests/unit/cli/test_embedder_resolution.py b/tests/unit/cli/test_embedder_resolution.py
index 1f2518ec2..2936b5815 100644
--- a/tests/unit/cli/test_embedder_resolution.py
+++ b/tests/unit/cli/test_embedder_resolution.py
@@ -131,10 +131,14 @@ def test_semantic_search_reads_through_the_repo_resolver(
) -> None:
"""The call site, not just the helper.
- Both ``search`` entry points used to resolve from the environment; a helper
- test alone would keep passing if they were reverted.
+ ``search`` used to resolve from the environment; a helper test alone would
+ keep passing if that were reverted. Since ``search`` collapsed onto the
+ ``search_codebase`` tool, the call site is the bridge that builds the store
+ for every adapter command, so this now covers all of them at once.
"""
- from repowise.cli.commands import search_cmd
+ import asyncio
+
+ from repowise.cli import tool_bridge
_write_config(tmp_path, embedder="mock")
monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
@@ -150,13 +154,10 @@ def test_semantic_search_reads_through_the_repo_resolver(
return MockEmbedder()
monkeypatch.setattr("repowise.cli.providers.embedders.build_embedder", _record)
- monkeypatch.setattr(search_cmd, "_display_results", lambda *a, **k: None)
- monkeypatch.setattr(search_cmd, "get_db_url_for_repo", lambda _p: "sqlite+aiosqlite://")
- search_cmd._search_semantic(tmp_path, "anything", 5)
- search_cmd._collect_semantic(tmp_path, "anything", 5)
+ asyncio.run(tool_bridge._open_vector_store(tmp_path))
- assert seen == ["mock", "mock"], seen
+ assert seen == ["mock"], seen
def test_serve_seeds_a_mock_pin_into_the_environment(
diff --git a/tests/unit/cli/test_output_agent_readiness.py b/tests/unit/cli/test_output_agent_readiness.py
index 57ede617e..83ff92950 100644
--- a/tests/unit/cli/test_output_agent_readiness.py
+++ b/tests/unit/cli/test_output_agent_readiness.py
@@ -23,12 +23,7 @@ import pytest
from rich.console import Console
from rich.table import Table
-from repowise.cli.commands.search_cmd import (
- _answered_mode,
- _display_results,
- _display_results_multi,
- _render_symbol_rows,
-)
+from repowise.cli.commands.search_cmd import project
from repowise.cli.output import NON_TTY_WIDTH, emit_json, resolve_console_width
LONG_PATH = "packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py"
@@ -42,15 +37,23 @@ class _Stream:
return self._tty
-class _Result:
- """Minimal stand-in for a wiki-page search hit."""
+def _page_hit(path: str = LONG_PATH) -> dict:
+ """One page hit shaped the way ``search_codebase`` builds it.
- def __init__(self, path: str = LONG_PATH) -> None:
- self.score = 15.198
- self.title = "Symbol: LanceDBVectorStore"
- self.page_type = "symbol_spotlight"
- self.target_path = path
- self.snippet = "# a snippet that is comfortably longer than fifty characters wide"
+ Built from the tool's response-construction code (``_fused_entry`` plus
+ ``_attach_paths`` and ``_assign_confidence``), not from the projection —
+ a fixture shaped to the projection passes with the projection broken.
+ """
+ return {
+ "page_id": "symbol:lancedb_store.py::LanceDBVectorStore",
+ "title": "Symbol: LanceDBVectorStore",
+ "page_type": "symbol_spotlight",
+ "snippet": "# a snippet that is comfortably longer than fifty characters wide",
+ "relevance_score": 15.198,
+ "sources": ["fts", "vector"],
+ "target_path": path,
+ "confidence_score": 1.0,
+ }
# ---------------------------------------------------------------------------
@@ -126,71 +129,72 @@ def test_emit_json_degrades_unserialisable_values_instead_of_raising(capsys) ->
assert json.loads(capsys.readouterr().out) == {"score": "1.5"}
-def test_search_json_emits_a_document_even_with_no_results(capsys) -> None:
+def test_search_json_emits_a_document_even_with_no_results() -> None:
"""A consumer that gets nothing on stdout cannot tell success from a crash."""
- _display_results([], "ignored", "json", query="nothing", mode="fulltext")
-
- assert json.loads(capsys.readouterr().out) == {
+ assert project({"results": []}, "nothing", multi=False) == {
"query": "nothing",
- "mode": "fulltext",
+ "mode": "concept",
"results": [],
}
-def test_search_json_carries_whole_paths_and_declares_its_mode(capsys) -> None:
- _display_results([_Result()], "ignored", "json", query="lancedb", mode="fulltext")
+def test_search_json_carries_whole_paths_and_declares_its_mode() -> None:
+ payload = project({"results": [_page_hit()]}, "lancedb", multi=False)
- payload = json.loads(capsys.readouterr().out)
assert payload["query"] == "lancedb"
- assert payload["mode"] == "fulltext"
+ # An absent ``mode`` is the concept branch, which is the only one that does
+ # not report one — not an unknown to pass through as "auto".
+ assert payload["mode"] == "concept"
assert payload["results"][0]["path"] == LONG_PATH
-def test_search_json_does_not_clip_the_snippet(capsys) -> None:
+def test_search_json_does_not_clip_the_snippet() -> None:
"""The 50-char clip is there to fit a column; JSON has no column."""
- result = _Result()
- _display_results([result], "ignored", "json", query="q", mode="fulltext")
+ hit = _page_hit()
+ projected = project({"results": [hit]}, "q", multi=False)
- assert json.loads(capsys.readouterr().out)["results"][0]["snippet"] == result.snippet
+ assert projected["results"][0]["snippet"] == hit["snippet"]
-def test_multi_repo_json_labels_each_row_with_its_repo(capsys) -> None:
- _display_results_multi(
- [("api", _Result()), ("web", _Result())],
- "ignored",
- "json",
- query="q",
- mode="fulltext",
- )
+def test_multi_repo_json_labels_each_row_with_its_repo() -> None:
+ hits = [{**_page_hit(), "repo": "api"}, {**_page_hit(), "repo": "web"}]
+ rows = project({"results": hits}, "q", multi=True)["results"]
- rows = json.loads(capsys.readouterr().out)["results"]
assert [r["repo"] for r in rows] == ["api", "web"]
-def test_symbol_json_omits_repo_in_single_repo_mode(capsys) -> None:
- row = ("LanceDBVectorStore", "a.b.LanceDBVectorStore", "class", LONG_PATH, 60)
- _render_symbol_rows([(None, row)], "lancedb", 10, "json", multi=False)
+def test_symbol_json_keeps_the_id_the_next_command_takes() -> None:
+ """``symbol_id`` is the handle ``repowise symbol`` reads; without it a
+ symbol hit cannot be followed anywhere."""
+ hit = {
+ "type": "symbol",
+ "symbol_id": f"{LONG_PATH}::LanceDBVectorStore",
+ "name": "LanceDBVectorStore",
+ "kind": "class",
+ "file": LONG_PATH,
+ "start_line": 60,
+ "end_line": 240,
+ "signature": "class LanceDBVectorStore(VectorStore)",
+ "qualified_name": "a.b.LanceDBVectorStore",
+ "language": "python",
+ "score": 12.5,
+ "next": "get_symbol",
+ }
- payload = json.loads(capsys.readouterr().out)
- assert payload["mode"] == "symbol"
- assert payload["results"] == [
+ assert project({"results": [hit], "mode": "symbol"}, "lancedb", multi=False)["results"] == [
{
+ "type": "symbol",
+ "score": 12.5,
"name": "LanceDBVectorStore",
"qualified_name": "a.b.LanceDBVectorStore",
"kind": "class",
"path": LONG_PATH,
"line": 60,
+ "symbol_id": f"{LONG_PATH}::LanceDBVectorStore",
}
]
-def test_symbol_json_labels_the_repo_in_workspace_mode(capsys) -> None:
- row = ("LanceDBVectorStore", "a.b.LanceDBVectorStore", "class", LONG_PATH, 60)
- _render_symbol_rows([("api", row)], "lancedb", 10, "json", multi=True)
-
- assert json.loads(capsys.readouterr().out)["results"][0]["repo"] == "api"
-
-
def test_shared_console_actually_applies_the_policy() -> None:
"""The seam itself, not just the function that computes the width.
@@ -233,28 +237,22 @@ def test_a_degraded_embedder_warns_on_stderr_so_json_stdout_stays_parseable(
@pytest.mark.parametrize(
- ("requested", "keyless", "mixed", "expected"),
+ ("requested", "expected"),
[
- # Nothing fell back: the request is the answer.
- ("semantic", [], False, "semantic"),
- # Every repo fell back, so these are FTS rows on an FTS score scale.
- ("semantic", ["api"], False, "fulltext"),
- # Some answered semantically and some did not; neither label is true,
- # and this is the case the ranking code fuses on rank for.
- ("semantic", ["api"], True, "mixed"),
- # Non-semantic requests cannot degrade, so they pass through.
- ("fulltext", ["api"], True, "fulltext"),
- ("symbol", ["api"], True, "symbol"),
+ # The legacy spellings both fold onto the tool's fused concept branch,
+ # which is the successor to picking one leg or the other.
+ ("fulltext", "concept"),
+ ("semantic", "concept"),
+ ("symbol", "symbol"),
+ # The tool's own spellings pass through untouched.
+ ("auto", "auto"),
+ ("concept", "concept"),
+ ("path", "path"),
+ ("hybrid", "hybrid"),
],
)
-def test_answered_mode_reports_what_answered_not_what_was_asked(
- requested: str, keyless: list[str], mixed: bool, expected: str
-) -> None:
- assert _answered_mode(requested, keyless, mixed) == expected
-
-
-def test_symbol_json_honours_the_limit(capsys) -> None:
- row = ("N", "q.N", "class", LONG_PATH, 1)
- _render_symbol_rows([(None, row)] * 5, "n", 2, "json", multi=False)
+def test_every_documented_mode_reaches_the_tool(requested: str, expected: str) -> None:
+ from repowise.cli.commands.search_cmd import _MODE_CHOICES, _tool_mode
- assert len(json.loads(capsys.readouterr().out)["results"]) == 2
+ assert requested in _MODE_CHOICES
+ assert _tool_mode(requested) == expected
diff --git a/tests/unit/cli/test_search_collapse.py b/tests/unit/cli/test_search_collapse.py
new file mode 100644
index 000000000..31614deb7
--- /dev/null
+++ b/tests/unit/cli/test_search_collapse.py
@@ -0,0 +1,835 @@
+"""``repowise search`` and ``repowise risk --target`` as MCP-tool adapters.
+
+``search`` used to carry its own FTS query, its own LanceDB query, its own
+``LIKE`` over ``wiki_symbols`` and its own workspace fan-out. It now calls
+``search_codebase``; ``risk`` gained ``--target``, which calls ``get_risk``.
+The same three things have to hold as for the other adapters:
+
+1. **The projection is the contract**, and the fixtures below are built from
+ the tools' response-construction code rather than from the projections. A
+ fixture shaped to the projection omits exactly the keys the projection
+ drops, so every dropped-answer bug passes it.
+2. **A kept key owes a renderer.** A trimmed projection has two silent failure
+ modes — a key dropped from the payload, and a key kept that nothing prints —
+ and only the first is visible to a ``project()`` test. So the renderers are
+ driven through ``CliRunner`` as well.
+3. **Every exit emits a document**, and an error exits non-zero.
+"""
+
+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.risk_cmd import project_risk, risk_command
+from repowise.cli.commands.search_cmd import project, search_command
+
+# --------------------------------------------------------------------------
+# Payloads shaped like the real tools build them
+# --------------------------------------------------------------------------
+
+PAGE_HIT = {
+ "page_id": "file:packages/cli/src/repowise/cli/output.py",
+ "title": "File: packages/cli/src/repowise/cli/output.py",
+ "page_type": "file_page",
+ "snippet": "# " + "s" * 200,
+ "relevance_score": 3.1416,
+ "sources": ["fts", "vector"],
+ "target_path": "packages/cli/src/repowise/cli/output.py",
+ "confidence_score": 1.0,
+}
+
+SYMBOL_HIT = {
+ "type": "symbol",
+ "symbol_id": "packages/cli/src/repowise/cli/output.py::resolve_console_width",
+ "name": "resolve_console_width",
+ "kind": "function",
+ "file": "packages/cli/src/repowise/cli/output.py",
+ "start_line": 44,
+ "end_line": 72,
+ "signature": "def resolve_console_width(stream) -> int | None",
+ "qualified_name": "repowise.cli.output.resolve_console_width",
+ "language": "python",
+ "score": 18.0,
+ "next": "get_symbol",
+}
+
+FILE_HIT = {
+ "type": "file",
+ "page_id": "file:packages/cli/src/repowise/cli/helpers.py",
+ "title": "File: packages/cli/src/repowise/cli/helpers.py",
+ "file": "packages/cli/src/repowise/cli/helpers.py",
+ "score": 140.0,
+ "next": "get_context",
+}
+
+META = {
+ "timing_ms": 12.5,
+ "indexed_commit": "abc123",
+ "live_head": "def456",
+ "index_behind": True,
+ "index_age_days": 2,
+}
+
+CONCEPT_PAYLOAD = {
+ "results": [PAGE_HIT],
+ "candidates": [{"path": "packages/cli/src/repowise/cli/output.py"}],
+ "_meta": META,
+}
+
+SYMBOL_PAYLOAD = {
+ "results": [SYMBOL_HIT],
+ "mode": "symbol",
+ "candidates": [{"path": "packages/cli/src/repowise/cli/output.py"}],
+ "exact_match": True,
+ "_meta": META,
+}
+
+#: The shape a *miss* takes: no exact symbol, so the tool attaches the note
+#: that stops a caller anchoring on a fuzzy neighbour, and a grep hint.
+SYMBOL_MISS_PAYLOAD = {
+ "results": [],
+ "mode": "symbol",
+ "exact_match": False,
+ "note": (
+ "No indexed symbol exactly matches 'reslove_width'. The results are fuzzy "
+ "neighbours ranked by token overlap — confirm a hit names what you meant."
+ ),
+ "grep_hint": (
+ "No indexed match for identifier 'reslove_width'. Retry with mode=\"symbol\"; "
+ "if you need every literal usage, Grep is the right tool for that."
+ ),
+ "_meta": META,
+}
+
+HYBRID_PAYLOAD = {"results": [SYMBOL_HIT, {**PAGE_HIT, "type": "page"}], "mode": "hybrid"}
+
+PATH_PAYLOAD = {"results": [FILE_HIT], "mode": "path"}
+
+RISK_PAYLOAD = {
+ "targets": {
+ "packages/core/src/repowise/core/pipeline/persist.py": {
+ "target": "packages/core/src/repowise/core/pipeline/persist.py",
+ "hotspot_score": 1.0,
+ "dependents_count": 52,
+ "co_change_partners": [
+ {
+ "file_path": "packages/core/src/repowise/core/persistence/models.py",
+ "count": 19.13,
+ "last_co_change": "2026-08-01",
+ "has_import_link": True,
+ }
+ ],
+ "primary_owner": "Raghav Chamadiya",
+ # Stored as a fraction here; the other git-metadata path stores a
+ # percentage, and a raw render shows a sole owner as "0.75%".
+ "owner_pct": 0.75,
+ "recent_owner": "Raghav Chamadiya",
+ "recent_owner_pct": 1.0,
+ "bus_factor": 1,
+ "contributor_count": 2,
+ "trend": "increasing",
+ "risk_type": "bug-prone",
+ "change_pattern": "fix-heavy",
+ "change_magnitude": {"lines_added_90d": 900, "lines_deleted_90d": 400,
+ "avg_commit_size": 61.2},
+ "impact_surface": {"transitive_dependents": ["x.py"] * 200},
+ # A {name: fix_count} dict, not a list — `_top_fix_symbols` builds
+ # it from the persisted counts JSON.
+ "defect_profile": {"fix_count": 22, "last_fix_days_ago": 1, "bug_magnet": True,
+ "top_symbols": {"_prune_stale_file_rows": 9,
+ "mark_tombstone_pages": 4}},
+ "health_score": 3.2,
+ "coverage_pct": 61.0,
+ "top_biomarkers": [
+ {"biomarker_type": "nested_complexity", "severity": "high",
+ "function_name": "persist_analysis", "impact": 0.71},
+ {"biomarker_type": "coverage_gradient", "severity": "low",
+ "function_name": None, "impact": 0.58},
+ ],
+ "test_gap": False,
+ "security_signals": [{"kind": "sql-injection", "severity": "high",
+ "snippet": "sa_text(f'...')"}],
+ "commit_count_capped": False,
+ "episodes": 22,
+ "_base_dep_count": 52,
+ "risk_summary": "persist.py — 22 bug fixes in 6mo, hotspot score 100% (increasing)",
+ }
+ },
+ "global_hotspots": [
+ {"file_path": "packages/core/src/repowise/core/pipeline/incremental.py",
+ "hotspot_score": 0.99, "primary_owner": "Raghav Chamadiya", "fix_count": 17}
+ ],
+ "_meta": META,
+}
+
+PR_RISK_PAYLOAD = {
+ "targets": RISK_PAYLOAD["targets"],
+ "directive": {
+ "will_break": ["packages/core/src/repowise/core/pipeline/orchestrator.py"],
+ "will_break_tests": ["tests/unit/persistence/test_models.py"],
+ "missing_cochanges": ["packages/core/src/repowise/core/persistence/models.py"],
+ "missing_tests": ["packages/core/src/repowise/core/pipeline/persist.py"],
+ "tests_to_run": ["tests/unit/pipeline/test_persist.py::test_tombstone"],
+ # Every dict-valued block below is keyed the way its construction site
+ # in tool_risk/directives.py keys it. Inventing a `summary` key here is
+ # what let four of the six render as raw Python dict reprs: the fixture
+ # was written to match the renderer's fallback chain, not the tool.
+ "will_break_consumers": [
+ {"repo": "backend", "service": "billing-api", "distance": 1, "score": 0.8,
+ "via": "import"}
+ ],
+ "missing_cross_repo_cochanges": [{"repo": "web", "service": "ui", "score": 0.4}],
+ "breaking_changes": [
+ {"contract_id": "api:GET /v1/x", "type": "openapi", "kind": "removed_route",
+ "severity": "high", "detail": "route removed",
+ "impacted_consumers": [{"repo": "web", "service": "ui", "file": "a.ts"}]}
+ ],
+ "conformance_violations": [
+ {"source": "cli", "target": "core", "rule": "cli !-> core",
+ "edge_kind": "import", "description": "layering rule"}
+ ],
+ "dependency_cycles": [{"nodes": ["a.py", "b.py", "a.py"], "length": 2}],
+ "governance_risk": [
+ {"file": "persist.py", "decision_id": "dr-7", "title": "persist tombstones",
+ "status": "accepted", "reason": "stale_governance"}
+ ],
+ "overall_risk_score": 7.4,
+ "summary": "PR touches 1 file(s). ~1 downstream file(s) likely affected.",
+ },
+ "pr_blast_radius": {
+ "transitive_affected": ["packages/core/src/repowise/core/pipeline/orchestrator.py"],
+ "recommended_reviewers": [{"name": "Raghav Chamadiya", "commits": 40}],
+ "test_gaps": ["packages/core/src/repowise/core/pipeline/persist.py"],
+ "overall_risk_score": 7.4,
+ },
+ "_meta": META,
+}
+
+
+# --------------------------------------------------------------------------
+# Helpers, matching test_tool_adapter_commands.py
+# --------------------------------------------------------------------------
+
+
+def _spy_run(payload, calls: list):
+ """Stand in for ``_tool_adapters.run``, but call the factory for real.
+
+ The factory is where the command imports its tool function and binds the
+ arguments, so calling it is what proves the wiring. A typo in the import is
+ otherwise invisible until the command runs against a real repo.
+ """
+
+ def _run(repo_path, factory, tool_name):
+ coro = factory()
+ calls.append((repo_path, coro.cr_code.co_qualname, tool_name))
+ coro.close()
+ return payload(repo_path) if callable(payload) else payload
+
+ return _run
+
+
+def repo(tmp_path):
+ (tmp_path / ".repowise").mkdir()
+ return tmp_path
+
+
+def _invoke(monkeypatch, command, args, repo, payload, calls=None, expect_exit=0):
+ """``risk`` takes its repo as ``--path``; it has no ``--no-workspace``."""
+ 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)])
+ assert result.exit_code == expect_exit, result.output + (result.stderr or "")
+ return result
+
+
+def _search(monkeypatch, args, repo, payload, calls=None, expect_exit=0):
+ """``search`` takes its repo as a trailing positional, not ``--path``."""
+ monkeypatch.setattr(_ta, "run", _spy_run(payload, calls if calls is not None else []))
+ result = CliRunner(mix_stderr=False).invoke(
+ search_command, [*args, str(repo), "--no-workspace"]
+ )
+ assert result.exit_code == expect_exit, result.output + (result.stderr or "")
+ return result
+
+
+# --------------------------------------------------------------------------
+# search — the projection
+# --------------------------------------------------------------------------
+
+
+def test_page_results_keep_exactly_the_payload_this_command_always_emitted():
+ """The collapse is payload-neutral by default, which is the whole point:
+ ``search`` is the command the session-cost eval's CLI arm measured."""
+ out = project(CONCEPT_PAYLOAD, "width", multi=False)
+
+ assert out["results"] == [
+ {
+ "type": "page",
+ "score": 3.1416,
+ "title": PAGE_HIT["title"],
+ "page_type": "file_page",
+ "path": "packages/cli/src/repowise/cli/output.py",
+ "snippet": PAGE_HIT["snippet"],
+ }
+ ]
+ for dropped in ("page_id", "sources", "confidence_score"):
+ assert dropped not in json.dumps(out["results"]), f"{dropped} survived the trim"
+
+
+def test_a_symbol_spotlight_hit_carries_the_openable_file_beside_its_page_id():
+ """``target_path`` on a symbol_spotlight is ``a.py::Foo`` — a page id, not
+ something a reader can open — which is why the tool attaches ``file``."""
+ hit = {**PAGE_HIT, "page_type": "symbol_spotlight",
+ "target_path": "packages/cli/src/repowise/cli/output.py::resolve_console_width",
+ "file": "packages/cli/src/repowise/cli/output.py"}
+ row = project({"results": [hit]}, "q", multi=False)["results"][0]
+
+ assert row["path"].endswith("::resolve_console_width"), "the payload changed shape"
+ assert row["file"] == "packages/cli/src/repowise/cli/output.py"
+
+
+def test_a_plain_file_hit_does_not_carry_a_redundant_file_key():
+ assert "file" not in project(CONCEPT_PAYLOAD, "q", multi=False)["results"][0]
+
+
+def test_a_bracketed_query_does_not_take_the_table_down(monkeypatch, repo):
+ """A Table title is markup-parsed like any cell."""
+ result = _search(monkeypatch, ["list[/bold]"], repo, CONCEPT_PAYLOAD)
+ assert "list[/bold]" in result.output
+
+
+def test_the_snippet_is_not_clipped_in_the_payload():
+ """The 50-char clip fits a table column; a JSON consumer has no column."""
+ out = project(CONCEPT_PAYLOAD, "width", multi=False)
+ assert out["results"][0]["snippet"] == PAGE_HIT["snippet"]
+
+
+def test_a_symbol_hit_keeps_the_id_that_makes_it_followable():
+ out = project(SYMBOL_PAYLOAD, "resolve_console_width", multi=False)
+ assert out["results"][0]["symbol_id"] == SYMBOL_HIT["symbol_id"]
+ assert out["results"][0]["line"] == 44
+ assert out["mode"] == "symbol"
+
+
+def test_hybrid_rows_say_which_shape_they_are():
+ """The old payload needed no ``type``: every row in a response was a page.
+ A hybrid interleave mixes shapes, so without it a consumer cannot tell
+ which keys a row even has."""
+ out = project(HYBRID_PAYLOAD, "where is resolve_console_width", multi=False)
+ assert [r["type"] for r in out["results"]] == ["symbol", "page"]
+
+
+def test_a_path_hit_projects_to_a_path():
+ out = project(PATH_PAYLOAD, "helpers.py", multi=False)
+ assert out["results"] == [
+ {"type": "file", "score": 140.0, "title": FILE_HIT["title"],
+ "path": "packages/cli/src/repowise/cli/helpers.py"}
+ ]
+
+
[email protected]("key", ["candidates", "exact_match", "note", "grep_hint"])
+def test_the_keys_that_change_the_answer_survive_the_trim(key):
+ """Each of these changes what the answer *means*, not how big it is:
+ which files to open, whether a symbol really matched, and the recovery
+ path when nothing did."""
+ payload = {**SYMBOL_MISS_PAYLOAD, "candidates": [{"path": "a.py"}], "exact_match": False}
+ assert key in project(payload, "reslove_width", multi=False)
+
+
+def test_exact_match_false_is_not_mistaken_for_absent():
+ """``if payload.get(key)`` would drop the one value that matters."""
+ out = project(SYMBOL_MISS_PAYLOAD, "reslove_width", multi=False)
+ assert out["exact_match"] is False
+
+
+def test_the_freshness_half_of_meta_survives_and_the_timing_half_does_not():
+ out = project(CONCEPT_PAYLOAD, "width", multi=False)
+ assert out["index"] == {"indexed_commit": "abc123", "live_head": "def456",
+ "index_behind": True, "index_age_days": 2}
+ assert "timing_ms" not in json.dumps(out)
+
+
+def test_an_absent_mode_means_concept_not_unknown():
+ """Only the structured branches report a mode. The concept branch and the
+ federated one are concept by construction and report nothing."""
+ assert project({"results": []}, "q", multi=False)["mode"] == "concept"
+
+
+# --------------------------------------------------------------------------
+# search — the command, through the renderers
+# --------------------------------------------------------------------------
+
+
+ ("requested", "sent"),
+ [("fulltext", "concept"), ("semantic", "concept"), ("symbol", "symbol"),
+ ("auto", "auto"), ("path", "path"), ("hybrid", "hybrid")],
+)
+def test_search_reaches_the_tool_with_the_mapped_mode(monkeypatch, repo, requested, sent):
+ """The argument actually bound, read off the coroutine's own frame.
+
+ Asserting only that ``search_codebase`` was reached would pass with the
+ whole mode mapping deleted, which is the half of this collapse that decides
+ what the command returns.
+ """
+ seen: dict = {}
+
+ def _run(repo_path, factory, tool_name):
+ coro = factory()
+ seen.update(coro.cr_frame.f_locals)
+ coro.close()
+ return CONCEPT_PAYLOAD
+
+ monkeypatch.setattr(_ta, "run", _run)
+ result = CliRunner(mix_stderr=False).invoke(
+ search_command, ["width", "--mode", requested, str(repo), "--no-workspace"]
+ )
+ assert result.exit_code == 0, result.output
+ assert seen["mode"] == sent
+ assert seen["query"] == "width"
+
+
[email protected]("mode", ["fulltext", "semantic", "symbol", "auto", "concept",
+ "path", "hybrid"])
+def test_every_mode_is_accepted_by_the_command(monkeypatch, repo, mode):
+ """The legacy spellings are still the documented ones; nobody's script
+ breaks. The tool's own spellings are accepted alongside them."""
+ _search(monkeypatch, ["width", "--mode", mode], repo, CONCEPT_PAYLOAD)
+
+
+def test_the_table_path_prints_the_note_and_the_grep_hint(monkeypatch, repo):
+ """A kept key that no renderer prints is the second silent failure mode of
+ a trimmed projection, and the one a projection test cannot see."""
+ result = _search(monkeypatch, ["reslove_width", "--mode", "symbol"], repo,
+ SYMBOL_MISS_PAYLOAD)
+ assert "No indexed symbol exactly matches" in result.output
+ assert "Retry with" in result.output
+
+
+def test_the_grep_hint_is_rewritten_into_cli_vocabulary(monkeypatch, repo):
+ """The tools write their hints for an agent holding the MCP surface."""
+ payload = {**SYMBOL_MISS_PAYLOAD,
+ "grep_hint": "Nothing matched; pipe the hit into get_symbol for its body."}
+ result = _search(monkeypatch, ["x", "--mode", "symbol"], repo, payload)
+ assert "repowise symbol" in result.output
+ assert "get_symbol" not in result.output
+
+
+def test_the_table_path_lists_the_files_to_read(monkeypatch, repo):
+ result = _search(monkeypatch, ["width"], repo, CONCEPT_PAYLOAD)
+ assert "Files to read" in result.output
+ assert "packages/cli/src/repowise/cli/output.py" in result.output
+
+
+def test_a_bracketed_snippet_is_not_eaten_by_rich(monkeypatch, repo):
+ """A table cell is markup-parsed, so tool text has to be escaped: a
+ snippet reading ``list[str]`` would otherwise render as ``list``, and a
+ stray closing tag would raise MarkupError and take the command down."""
+ payload = {"results": [{**PAGE_HIT, "snippet": "list[str] not dict[/x]"}]}
+ result = _search(monkeypatch, ["width"], repo, payload)
+ assert "list[str]" in result.output
+
+
+def test_symbol_mode_renders_the_symbol_table_not_the_page_table(monkeypatch, repo):
+ result = _search(monkeypatch, ["resolve_console_width", "--mode", "symbol"], repo,
+ SYMBOL_PAYLOAD)
+ assert "Qualified Name" in result.output
+ assert "repowise.cli.output.resolve_console_width" in result.output
+
+
+def test_hybrid_renders_both_shapes(monkeypatch, repo):
+ result = _search(monkeypatch, ["where is it", "--mode", "hybrid"], repo, HYBRID_PAYLOAD)
+ assert "Qualified Name" in result.output, "the symbol group is missing"
+ assert "Snippet" in result.output, "the page group is missing"
+
+
+def test_json_emits_one_parseable_document(monkeypatch, repo):
+ result = _search(monkeypatch, ["width", "--format", "json"], repo, CONCEPT_PAYLOAD)
+ assert json.loads(result.output)["results"][0]["path"].endswith("output.py")
+
+
+def test_full_emits_the_raw_tool_dict(monkeypatch, repo):
+ result = _search(monkeypatch, ["width", "--full"], repo, CONCEPT_PAYLOAD)
+ payload = json.loads(result.output)
+ assert payload["results"][0]["page_id"] == PAGE_HIT["page_id"]
+ assert payload["_meta"]["timing_ms"] == 12.5
+
+
+def test_an_error_payload_emits_a_document_and_exits_one(monkeypatch, repo):
+ """A json path that exits after only a stderr notice is indistinguishable
+ from a crash to whatever is reading the pipe."""
+ payload = {"error": "no index yet", "remedy": "Run 'repowise init'."}
+ result = _search(monkeypatch, ["width", "--format", "json"], repo, payload,
+ expect_exit=1)
+ assert json.loads(result.output)["error"] == "no index yet"
+
+
+def test_full_also_exits_one_on_an_error(monkeypatch, repo):
+ """``--full`` is exactly the spelling a script reaches for."""
+ result = _search(monkeypatch, ["width", "--full"], repo, {"error": "no index yet"},
+ expect_exit=1)
+ assert json.loads(result.output)["error"] == "no index yet"
+
+
+def test_no_results_still_emits_a_document_and_says_so(monkeypatch, repo):
+ result = _search(monkeypatch, ["zzz", "--format", "json"], repo, {"results": []})
+ assert json.loads(result.output) == {"query": "zzz", "mode": "concept", "results": []}
+
+
+def test_an_unindexed_repo_emits_a_document(monkeypatch, tmp_path):
+ result = CliRunner(mix_stderr=False).invoke(
+ search_command, ["q", str(tmp_path), "--no-workspace", "--format", "json"]
+ )
+ assert result.exit_code == 0
+ assert json.loads(result.output) == {"query": "q", "mode": "concept", "results": []}
+
+
+# --------------------------------------------------------------------------
+# search — the workspace fan-out
+# --------------------------------------------------------------------------
+#
+# The tool federates through a workspace registry the CLI does not build, so
+# ``--all`` calls it once per repo and fuses here. These drive ``_fan_out``
+# directly: a real two-repo fan-out needs two indexed repos.
+
+
+class _Notices:
+ def __init__(self) -> None:
+ self.said: list[str] = []
+
+ def print(self, *args: object) -> None:
+ self.said.append(" ".join(str(a) for a in args))
+
+
+def _fan(monkeypatch, tmp_path, per_repo, *, limit=10, fmt="table", full=False, mode="fulltext"):
+ """Run ``_fan_out`` over fake repos, one canned payload each."""
+ from repowise.cli.commands import search_cmd
+
+ paths = []
+ for name in per_repo:
+ p = tmp_path / name
+ (p / ".repowise").mkdir(parents=True)
+ paths.append(p)
+ monkeypatch.setattr(
+ search_cmd, "_run_search", lambda rp, q, lim, tm: per_repo[rp.name]
+ )
+ notices = _Notices()
+ search_cmd._fan_out(paths, "q", limit, mode, "concept", fmt, full, notices)
+ return notices
+
+
+def _hit(path: str, score: float) -> dict:
+ return {**PAGE_HIT, "target_path": path, "relevance_score": score}
+
+
+def test_the_fan_out_fuses_on_rank_not_on_raw_score(monkeypatch, tmp_path, capsys):
+ """Each repo scores its own list independently, so the numbers are only
+ comparable within a repo. Sorting them together lets one repo's scale
+ evict every hit from the other."""
+ per_repo = {
+ "api": {"results": [_hit("api/a.py", 0.9), _hit("api/b.py", 0.8)]},
+ # Much larger raw scores: a score sort would take both of these first.
+ "web": {"results": [_hit("web/a.py", 90.0), _hit("web/b.py", 80.0)]},
+ }
+ _fan(monkeypatch, tmp_path, per_repo, fmt="json", limit=2)
+
+ rows = json.loads(capsys.readouterr().out)["results"]
+ assert {r["repo"] for r in rows} == {"api", "web"}, "one repo evicted the other"
+
+
+def test_the_fan_out_tags_every_row_with_its_repo(monkeypatch, tmp_path, capsys):
+ per_repo = {"api": {"results": [_hit("a.py", 1.0)]}, "web": {"results": [_hit("b.py", 1.0)]}}
+ _fan(monkeypatch, tmp_path, per_repo, fmt="json")
+
+ assert sorted(r["repo"] for r in json.loads(capsys.readouterr().out)["results"]) == [
+ "api",
+ "web",
+ ]
+
+
+def test_the_fan_out_honours_the_limit_across_repos(monkeypatch, tmp_path, capsys):
+ per_repo = {
+ "api": {"results": [_hit(f"a{i}.py", 1.0) for i in range(5)]},
+ "web": {"results": [_hit(f"w{i}.py", 1.0) for i in range(5)]},
+ }
+ _fan(monkeypatch, tmp_path, per_repo, fmt="json", limit=3)
+
+ assert len(json.loads(capsys.readouterr().out)["results"]) == 3
+
+
+def test_one_failing_repo_does_not_take_the_fan_out_down(monkeypatch, tmp_path, capsys):
+ per_repo = {"api": {"error": "no index yet"}, "web": {"results": [_hit("b.py", 1.0)]}}
+ notices = _fan(monkeypatch, tmp_path, per_repo, fmt="json")
+
+ assert json.loads(capsys.readouterr().out)["results"], "the healthy repo lost its answer"
+ assert any("search failed for api" in s for s in notices.said)
+
+
+def test_every_repo_failing_is_an_error_not_an_empty_result(monkeypatch, tmp_path):
+ """"Nothing matched" and "nothing could be searched" are different answers,
+ and the second one is a failure the exit code has to carry."""
+ import click
+
+ per_repo = {"api": {"error": "no index yet"}, "web": {"error": "no index yet"}}
+ with pytest.raises(click.exceptions.Exit) as excinfo:
+ _fan(monkeypatch, tmp_path, per_repo, fmt="json")
+ assert excinfo.value.exit_code == 1
+
+
+def test_a_hint_survives_only_when_every_repo_agrees(monkeypatch, tmp_path, capsys):
+ """A grep hint is attached only when *that* repo found nothing, so it is
+ true of the fan-out only if no repo found anything."""
+ per_repo = {
+ "api": {"results": [], "grep_hint": "nothing matched"},
+ "web": {"results": [_hit("b.py", 1.0)]},
+ }
+ _fan(monkeypatch, tmp_path, per_repo, fmt="json")
+
+ assert "grep_hint" not in json.loads(capsys.readouterr().out)
+
+
+def test_full_in_the_fan_out_returns_every_repos_own_payload(monkeypatch, tmp_path, capsys):
+ """There is no single tool call here to return the payload *of*, so
+ synthesising one would hand back a dict no tool ever produced."""
+ per_repo = {"api": {"results": [_hit("a.py", 1.0)], "_meta": META}, "web": {"results": []}}
+ _fan(monkeypatch, tmp_path, per_repo, full=True)
+
+ out = json.loads(capsys.readouterr().out)
+ assert set(out["repos"]) == {"api", "web"}
+ assert out["repos"]["api"]["_meta"]["timing_ms"] == 12.5
+
+
+def test_the_fan_out_reports_its_worst_repos_freshness(monkeypatch, tmp_path, capsys):
+ """Without this the answer drawn from the most repos is the one that says
+ nothing about staleness, while the single-repo path warns."""
+ per_repo = {
+ "api": {"results": [_hit("a.py", 1.0)], "_meta": {"index_age_days": 0}},
+ "web": {"results": [], "_meta": {"index_behind": True, "indexed_commit": "aaa",
+ "live_head": "bbb", "index_age_days": 9}},
+ }
+ _fan(monkeypatch, tmp_path, per_repo, fmt="json")
+
+ index = json.loads(capsys.readouterr().out)["index"]
+ assert index["index_behind"] is True
+ assert index["index_age_days"] == 9
+
+
+def test_a_bracketed_error_does_not_take_the_fan_out_down(monkeypatch, tmp_path, capsys):
+ """A shaped error interpolates the exception verbatim, and exception text
+ routinely carries brackets. Unescaped, a stray closing tag raises
+ MarkupError and the command dies with an empty stdout.
+
+ Driven through a *real* rich Console: a fake that just records strings
+ never parses the markup, so it cannot see this bug at all.
+ """
+ import io
+
+ from rich.console import Console
+
+ from repowise.cli.commands import search_cmd
+
+ buf = io.StringIO()
+ real = Console(file=buf, width=200, no_color=True)
+ per_repo = {"api": {"error": "bad type list[/x] here"},
+ "web": {"results": [_hit("b.py", 1.0)]}}
+ paths = []
+ for name in per_repo:
+ p = tmp_path / name
+ (p / ".repowise").mkdir(parents=True)
+ paths.append(p)
+ monkeypatch.setattr(search_cmd, "_run_search", lambda rp, q, lim, tm: per_repo[rp.name])
+
+ search_cmd._fan_out(paths, "q", 10, "fulltext", "concept", "json", False, real)
+
+ assert json.loads(capsys.readouterr().out)["results"], "the healthy repo lost its answer"
+ assert "list[/x]" in buf.getvalue()
+
+
+def test_full_in_the_fan_out_exits_one_when_no_repo_answered(monkeypatch, tmp_path, capsys):
+ import click
+
+ per_repo = {"api": {"error": "no index yet"}}
+ with pytest.raises(click.exceptions.Exit) as excinfo:
+ _fan(monkeypatch, tmp_path, per_repo, full=True)
+ assert excinfo.value.exit_code == 1
+ assert "error" in json.loads(capsys.readouterr().out)
+
+
+# --------------------------------------------------------------------------
+# risk --target
+# --------------------------------------------------------------------------
+
+
+def test_risk_without_a_target_still_scores_a_revspec(monkeypatch, repo):
+ """The collapse must not move the command's default subject."""
+ called: list = []
+ monkeypatch.setattr(
+ "repowise.cli.commands.risk_cmd.score_live_change",
+ lambda *a, **k: called.append(a) or (_ for _ in ()).throw(RuntimeError("boom")),
+ )
+ result = CliRunner(mix_stderr=False).invoke(risk_command, ["HEAD", "--path", str(repo)])
+ assert called, "a bare `repowise risk` must still reach the change scorer"
+ assert result.exit_code != 0 # our own boom
+
+
+def test_risk_target_reaches_get_risk(monkeypatch, repo):
+ calls: list = []
+ _invoke(monkeypatch, risk_command, ["--target", "a.py"], repo, RISK_PAYLOAD, calls)
+ assert calls[0][1] == "get_risk"
+
+
+def test_risk_projection_keeps_the_card_and_drops_only_the_bulk():
+ out = project_risk(RISK_PAYLOAD)
+ card = out["targets"]["packages/core/src/repowise/core/pipeline/persist.py"]
+ # A denylist: the failure mode of an allowlist is a silently discarded
+ # answer, and this card is scalars rather than source.
+ for kept in ("defect_profile", "co_change_partners", "security_signals", "test_gap",
+ "change_magnitude", "bus_factor", "trend", "risk_type", "episodes"):
+ assert kept in card, f"{kept} was discarded"
+ assert "impact_surface" not in card
+ assert "_base_dep_count" not in card
+ assert out["global_hotspots"] == RISK_PAYLOAD["global_hotspots"]
+ assert out["index"]["indexed_commit"] == "abc123"
+
+
+def test_risk_pr_mode_keeps_the_whole_directive():
+ """The tool's own docstring tells a reader to lead with the directive, so
+ every block of it is the answer rather than its size."""
+ out = project_risk(PR_RISK_PAYLOAD)
+ assert out["directive"] == PR_RISK_PAYLOAD["directive"]
+
+
+def test_risk_table_renders_the_directive_first(monkeypatch, repo):
+ result = _invoke(
+ monkeypatch, risk_command,
+ ["--target", "packages/core/src/repowise/core/pipeline/persist.py",
+ "--changed-file", "packages/core/src/repowise/core/pipeline/persist.py"],
+ repo, PR_RISK_PAYLOAD,
+ )
+ out = result.output
+ # Unconditional: a guarded `assert A < B if cond else True` degrades to
+ # `assert True` the moment rich wraps the line the guard looked for.
+ assert out.index("Directive") < out.index("Co-changes with")
+ for expected in ("Will break", "Tests to run", "Missing co-changes",
+ "Conformance violations", "cli !-> core", "layering rule",
+ "persist tombstones", "billing-api", "removed_route",
+ "a.py -> b.py -> a.py"):
+ assert expected in out, f"{expected!r} is in the payload and nothing printed it"
+ # The generic fallback used to print these blocks as Python dict reprs.
+ assert "'contract_id':" not in out
+ assert "'nodes':" not in out
+
+
+def test_risk_table_normalises_the_ownership_share(monkeypatch, repo):
+ """``owner_pct`` is a fraction *or* a percentage depending on which
+ git-metadata path filled it in; printing it raw shows a sole owner
+ as "0.75%"."""
+ result = _invoke(monkeypatch, risk_command, ["--target", "a.py"], repo, RISK_PAYLOAD)
+ assert "75%" in result.output
+ assert "0.75%" not in result.output
+
+
+def test_risk_table_prints_the_security_signal(monkeypatch, repo):
+ result = _invoke(monkeypatch, risk_command, ["--target", "a.py"], repo, RISK_PAYLOAD)
+ assert "sql-injection" in result.output
+
+
+def test_risk_names_a_target_the_tool_returned_no_card_for(monkeypatch, repo):
+ """An excluded path is filtered out before the tool sees it. Rendering
+ nothing reads as "clean"; it is not, it is "not assessed"."""
+ result = _invoke(monkeypatch, risk_command, ["--target", "vendor/x.py"], repo,
+ {"targets": {}, "_meta": META})
+ assert "vendor/x.py" in result.output
+ assert "not indexed" in result.output
+
+
+def test_risk_target_json_is_one_document(monkeypatch, repo):
+ result = _invoke(monkeypatch, risk_command, ["--target", "a.py", "--format", "json"],
+ repo, RISK_PAYLOAD)
+ targets = json.loads(result.output)["targets"]
+ assert list(targets) == ["packages/core/src/repowise/core/pipeline/persist.py"]
+
+
+def test_risk_target_error_exits_one(monkeypatch, repo):
+ result = _invoke(monkeypatch, risk_command, ["--target", "a.py", "--format", "json"],
+ repo, {"error": "no index yet"}, expect_exit=1)
+ assert json.loads(result.output)["error"] == "no index yet"
+
+
+def test_risk_projection_keeps_the_reviewers_nothing_else_names():
+ """``pr_blast_radius`` is the only carrier of ``recommended_reviewers``,
+ and the tool has already capped its noisy lists before the CLI sees it."""
+ out = project_risk(PR_RISK_PAYLOAD)
+ assert out["pr_blast_radius"]["recommended_reviewers"] == [
+ {"name": "Raghav Chamadiya", "commits": 40}
+ ]
+
+
+def test_risk_table_renders_the_health_and_coverage_it_keeps(monkeypatch, repo):
+ result = _invoke(monkeypatch, risk_command, ["--target", "a.py"], repo, RISK_PAYLOAD)
+ assert "health 3.2/10" in result.output
+ assert "coverage 61%" in result.output
+ # Keyed ``biomarker_type``; a generic key guess prints the whole dict repr.
+ assert "nested_complexity (high) in persist_analysis" in result.output
+ assert "'biomarker_type':" not in result.output
+
+
+def test_risk_table_keeps_the_fix_counts_on_top_symbols(monkeypatch, repo):
+ """``top_symbols`` is a {name: count} dict; iterating it bare prints the
+ names and throws the counts away."""
+ result = _invoke(monkeypatch, risk_command, ["--target", "a.py"], repo, RISK_PAYLOAD)
+ assert "_prune_stale_file_rows (x9)" in result.output
+
+
+def test_risk_full_on_a_revspec_is_json_not_a_table(monkeypatch, repo):
+ """``--full`` means "the complete payload, as JSON" on every command that
+ has it; silently ignoring it hands a script asking for JSON a rich table."""
+ from repowise.core.analysis.change_risk import ChangeRiskResult
+
+ monkeypatch.setattr(
+ "repowise.cli.commands.risk_cmd.change_risk_payload", lambda r: {"risk": 4.2}
+ )
+ monkeypatch.setattr(
+ "repowise.cli.commands.risk_cmd.score_live_change",
+ lambda *a, **k: _FakeChangeResult(),
+ )
+ result = CliRunner(mix_stderr=False).invoke(
+ risk_command, ["HEAD", "--path", str(repo), "--full", "--baseline", "0"]
+ )
+ assert result.exit_code == 0, result.output + (result.stderr or "")
+ assert json.loads(result.output) == {"risk": 4.2}
+ assert ChangeRiskResult is not None # import is the contract this leans on
+
+
+class _FakeFeatures:
+ nf = 3
+ ref = "HEAD"
+ subject = "a commit"
+ la = 10
+ ld = 2
+ nd = 1
+ ns = 1
+ entropy = 0.5
+ exp = 40
+ is_fix = False
+
+
+class _FakeChangeResult:
+ features = _FakeFeatures()
+ risk = type("R", (), {"score": 4.2, "level": "moderate", "top_drivers": []})()
+ percentile = None
+ priority = None
+ request_excludes: tuple = ()
+
+
+def test_changed_file_without_a_target_is_a_usage_error(monkeypatch, repo):
+ """It is a modifier on ``--target``, and silently scoring HEAD instead
+ would answer a question nobody asked."""
+ result = CliRunner(mix_stderr=False).invoke(
+ risk_command, ["--changed-file", "a.py", "--path", str(repo)]
+ )
+ assert result.exit_code == 2
diff --git a/tests/unit/server/mcp/test_keyless_vector_leg.py b/tests/unit/server/mcp/test_keyless_vector_leg.py
index de584c5ea..64e1b799d 100644
--- a/tests/unit/server/mcp/test_keyless_vector_leg.py
+++ b/tests/unit/server/mcp/test_keyless_vector_leg.py
@@ -242,170 +242,112 @@ def test_dedup_by_vector_ignores_the_pending_index_too():
# `repowise search --mode semantic` (CLI)
# --------------------------------------------------------------------------
#
-# The two CLI search paths were never wired to the predicate at all. Everything
-# else that reads vectors was swept and guarded; these build their own store
-# inline, so the sweep did not reach them and a keyless user got a window of
-# nearest-neighbour noise rendered as semantic results, with the full-text
-# fallback sitting unused directly below.
+# The CLI used to carry its own retrieval and its own copy of this guard. It is
+# now an adapter over ``search_codebase``, so the guard above is the one that
+# runs. What is left on the CLI side is the *telling*: rendering full-text rows
+# without saying so is how someone concludes semantic retrieval is bad when what
+# they have is no embedder. These pin the chain that carries that signal across
+# the seam — the bridge publishes the embedder status, ``_meta`` turns it into
+# ``semantic_search: false``, and the command warns on it.
-class _Row:
- """The shape the CLI result renderer reads off a hit."""
[email protected](autouse=True)
+def _reset_embedder_status():
+ """``_embedder_status`` is process-global, and these tests set it.
- def __init__(self, tag: str):
- self.tag = tag
- self.score = 0.9
- self.page_id = tag
- self.title = tag
- self.snippet = tag
- self.page_type = "file_page"
- self.target_path = tag
+ Left keyless, it would put ``semantic_search: false`` into the ``_meta`` of
+ every later test in the session that builds one.
+ """
+ from repowise.server.mcp_server import _state
+ before = getattr(_state, "_embedder_status", None)
+ yield
+ _state._embedder_status = before
-class _FakeLanceStore:
- """Stands in for LanceDBVectorStore: records whether it was ranked on."""
- def __init__(self, _path, embedder):
- self._embedder = embedder
- self.searched = False
- self.closed = False
+class _Notices:
+ def __init__(self) -> None:
+ self.said: list[str] = []
- async def search(self, query, limit=10):
- self.searched = True
- return [_Row("vector-noise")]
+ def print(self, *args: object) -> None:
+ self.said.append(" ".join(str(a) for a in args))
- async def close(self):
- self.closed = True
+def _meta_for(embedder, requested: str) -> dict:
+ """``_meta`` as a real call would carry it, via the bridge's own publisher."""
+ from repowise.cli.tool_bridge import _publish_embedder_status
+ from repowise.server.mcp_server._meta import build_meta
-def _patch_cli_search(monkeypatch, tmp_path, embedder):
- """Point both CLI search paths at a fake store and a known FTS result."""
- from repowise.cli.commands import search_cmd
+ _publish_embedder_status(requested, embedder)
+ return build_meta()
- built: dict[str, _FakeLanceStore] = {}
- def _make(path, embedder=None):
- store = _FakeLanceStore(path, embedder)
- built["store"] = store
- return store
+def test_a_keyless_index_reports_no_semantic_search_in_meta() -> None:
+ """The signal the CLI notice reads. Nothing is broken and nothing was
+ misconfigured, so it is not flagged as degraded — but retrieval really is
+ full-text-only and the payload has to say so."""
+ meta = _meta_for(KeylessEmbedder(), "mock")
- (tmp_path / ".repowise" / "lancedb").mkdir(parents=True, exist_ok=True)
- monkeypatch.setattr(
- "repowise.core.persistence.vector_store.LanceDBVectorStore", _make, raising=False
- )
- monkeypatch.setattr(
- "repowise.cli.providers.embedders.build_embedder", lambda _n: embedder
- )
- # "mock" is what a genuinely keyless repo resolves to; individual tests
- # override this to cover the "pinned a real embedder that then failed" case.
- monkeypatch.setattr(
- "repowise.cli.providers.embedders.resolve_embedder_for_repo", lambda _p: "mock"
- )
+ assert meta["semantic_search"] is False
+ assert meta.get("embedder_degraded") is not True
- class _FTS:
- def __init__(self, _engine):
- pass
- async def search(self, query, limit=10):
- return [_Row("fts-result")]
-
- class _Engine:
- async def dispose(self):
- return None
-
- monkeypatch.setattr("repowise.core.persistence.FullTextSearch", _FTS, raising=False)
- monkeypatch.setattr("repowise.core.persistence.create_engine", lambda _u: _Engine(), raising=False)
- monkeypatch.setattr(search_cmd, "get_db_url_for_repo", lambda _p: "sqlite+aiosqlite:///:memory:")
- # _search_semantic renders rather than returns, so capture what it would
- # show AND the title, which is itself part of the contract: full-text rows
- # must not be labelled "Semantic search".
- shown: dict = {"rows": [], "title": None, "notices": []}
- monkeypatch.setattr(
- search_cmd,
- "_display_results",
- # `fmt` and the keyword-only query/mode arrived with `--format json`;
- # this test only exercises the table path.
- lambda results, title, fmt="table", **kw: (
- shown["rows"].extend(r.tag for r in results),
- shown.__setitem__("title", title),
- ),
- )
- monkeypatch.setattr(
- search_cmd.console,
- "print",
- lambda *a, **k: shown["notices"].append(" ".join(str(x) for x in a)),
- )
- return search_cmd, built, shown
+def test_a_failed_pinned_embedder_reports_degraded_and_names_itself() -> None:
+ meta = _meta_for(KeylessEmbedder(), "ollama")
+ assert meta["semantic_search"] is False
+ assert meta["embedder_degraded"] is True
+ assert "ollama" in meta["embedder_warning"]
-def test_cli_semantic_search_does_not_rank_on_a_keyless_store(monkeypatch, tmp_path):
- search_cmd, built, shown = _patch_cli_search(monkeypatch, tmp_path, KeylessEmbedder())
- search_cmd._search_semantic(tmp_path, "how does auth work", 5)
+def test_a_real_embedder_is_not_flagged() -> None:
+ """The guard must not over-fire: a working embedder is not warned about."""
+ meta = _meta_for(_RealisticEmbedder(), "openai")
- assert shown["rows"] == ["fts-result"], "keyless must serve full text, not vector noise"
- assert built["store"].searched is False
- assert built["store"].closed is True, "the store is still closed on the guarded path"
+ assert "semantic_search" not in meta
+ assert "embedder_degraded" not in meta
-def test_cli_semantic_search_says_full_text_answered(monkeypatch, tmp_path):
- """Rendering full-text rows under a "Semantic search" heading is how someone
- concludes semantic retrieval is bad when what they have is no embedder."""
- search_cmd, _built, shown = _patch_cli_search(monkeypatch, tmp_path, KeylessEmbedder())
+def test_cli_semantic_search_says_full_text_answered() -> None:
+ from repowise.cli.commands.search_cmd import _warn_if_lexical_only
- search_cmd._search_semantic(tmp_path, "how does auth work", 5)
+ notices = _Notices()
+ _warn_if_lexical_only({"_meta": _meta_for(KeylessEmbedder(), "mock")}, "semantic", notices)
- assert "Full-text" in shown["title"]
- assert "Semantic" not in shown["title"]
- said = " ".join(shown["notices"]).lower()
+ said = " ".join(notices.said).lower()
assert "no embedder configured" in said
- assert "full-text" in said
+ assert "full-text results instead" in said
-def test_cli_semantic_search_notice_names_a_configured_embedder(monkeypatch, tmp_path):
+def test_cli_semantic_notice_names_a_configured_embedder() -> None:
"""A repo pinned to a real embedder whose key has gone away lands here too.
Telling that user "no embedder configured" contradicts their own config."""
- search_cmd, _built, shown = _patch_cli_search(monkeypatch, tmp_path, KeylessEmbedder())
- monkeypatch.setattr(
- "repowise.cli.providers.embedders.resolve_embedder_for_repo", lambda _p: "ollama"
- )
+ from repowise.cli.commands.search_cmd import _warn_if_lexical_only
- search_cmd._search_semantic(tmp_path, "how does auth work", 5)
+ notices = _Notices()
+ _warn_if_lexical_only({"_meta": _meta_for(KeylessEmbedder(), "ollama")}, "semantic", notices)
- said = " ".join(shown["notices"])
+ said = " ".join(notices.said)
assert "ollama" in said
assert "No embedder configured" not in said
-def test_cli_semantic_search_still_ranks_on_a_real_store(monkeypatch, tmp_path):
- """The guard must not over-fire: a real embedder still gets semantic search."""
- search_cmd, built, shown = _patch_cli_search(monkeypatch, tmp_path, _RealisticEmbedder())
-
- search_cmd._search_semantic(tmp_path, "how does auth work", 5)
-
- assert shown["rows"] == ["vector-noise"]
- assert shown["title"] is not None and "Semantic" in shown["title"]
- assert built["store"].searched is True
- assert shown["notices"] == [], "a working embedder must not be warned about"
-
-
-def test_cli_workspace_semantic_collect_skips_a_keyless_repo(monkeypatch, tmp_path):
- search_cmd, built, _shown = _patch_cli_search(monkeypatch, tmp_path, KeylessEmbedder())
+def test_cli_does_not_warn_when_semantic_search_really_ran() -> None:
+ from repowise.cli.commands.search_cmd import _warn_if_lexical_only
- results, served_fulltext = search_cmd._collect_semantic(tmp_path, "how does auth work", 5)
+ notices = _Notices()
+ _warn_if_lexical_only({"_meta": _meta_for(_RealisticEmbedder(), "openai")}, "semantic", notices)
- assert [r.tag for r in results] == ["fts-result"]
- assert built["store"].searched is False
- # The flag is what stops the fan-out sorting these full-text scores against
- # another repo's cosine scores, which are not the same quantity.
- assert served_fulltext is True
+ assert notices.said == []
-def test_cli_workspace_semantic_collect_reports_a_real_store_as_semantic(monkeypatch, tmp_path):
- search_cmd, built, _shown = _patch_cli_search(monkeypatch, tmp_path, _RealisticEmbedder())
[email protected]("requested", ["fulltext", "concept", "auto", "symbol", "path"])
+def test_only_the_mode_that_promised_semantics_is_warned_about(requested: str) -> None:
+ """``fulltext`` never claimed semantic matching, and the tool's own mode
+ spellings are the tool's contract, where ``_meta`` already says this."""
+ from repowise.cli.commands.search_cmd import _warn_if_lexical_only
- results, served_fulltext = search_cmd._collect_semantic(tmp_path, "how does auth work", 5)
+ notices = _Notices()
+ _warn_if_lexical_only({"_meta": _meta_for(KeylessEmbedder(), "mock")}, requested, notices)
- assert [r.tag for r in results] == ["vector-noise"]
- assert built["store"].searched is True
- assert served_fulltext is False
+ assert notices.said == []
diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.py
index 336dfef49..c4597c229 100644
--- a/tests/unit/server/mcp/test_search.py
+++ b/tests/unit/server/mcp/test_search.py
@@ -921,6 +921,33 @@ class TestExactMatchSignal:
result = await search_codebase("authentication flow for the service")
assert "exact_match" not in result
+ @pytest.mark.asyncio
+ async def test_path_search_gets_no_exact_symbol_signal(self, setup_mcp):
+ """A path query names no identifier, so there is no symbol to be exact
+ about.
+
+ Regression: the response builder computed the query's identifiers into
+ ``candidates`` and then rebound the same name with the *file*
+ candidates, so this signal's gate became "there are results at all" and
+ a path search was told that no symbol matched it.
+ """
+ from repowise.server.mcp_server import search_codebase
+
+ result = await search_codebase("service.py", mode="path")
+ assert result["results"], "the path search should have found something"
+ assert "exact_match" not in result
+ assert "note" not in result
+
+ @pytest.mark.asyncio
+ async def test_the_fuzzy_note_quotes_the_query_not_the_file_list(self, setup_mcp):
+ """Same regression from the other side: the note names what the caller
+ asked after, and the rebind made it name file paths instead."""
+ from repowise.server.mcp_server import search_codebase
+
+ result = await search_codebase("AuthServiceXyz", mode="symbol")
+ assert "'AuthServiceXyz'" in result["note"]
+ assert "'path'" not in result["note"]
+
class TestFusion:
"""search_codebase fuses FTS + vector via RRF, tagging each hit's sources.