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.

fix(cli): stop non-TTY output truncating result paths, and add search --format json (#1402)

Raghav Chamadiyae611057f0fbe
diff --git a/packages/cli/src/repowise/cli/commands/search_cmd.py b/packages/cli/src/repowise/cli/commands/search_cmd.py
index 9d3280087..eb6c1f7ab 100644
--- a/packages/cli/src/repowise/cli/commands/search_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/search_cmd.py
@@ -8,10 +8,12 @@ from rich.table import Table
from repowise.cli.helpers import (
console,
ensure_repowise_dir,
+ err_console,
get_db_url_for_repo,
resolve_command_target,
run_async,
)
+from repowise.cli.output import emit_json, format_option
# 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
@@ -20,6 +22,70 @@ from repowise.cli.helpers import (
_WORKSPACE_RRF_K = 60
+def _notices(fmt: str):
+ """Console for human asides — stderr under ``--format json``.
+
+ Progress notices, keyless-embedder warnings and "no results" lines are all
+ written for a person. On stdout they would sit in front of the JSON
+ document and break every parser reading it, so json mode diverts them.
+ """
+ return err_console if fmt == "json" else console
+
+
+def _answered_mode(requested: str, keyless_repos: list[str], mixed_scales: bool) -> str:
+ """Which retrieval actually answered, which is not always what was asked.
+
+ ``--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.
+ """
+ if requested != "semantic" or not keyless_repos:
+ return requested
+ return "mixed" if mixed_scales else "fulltext"
+
+
+def _page_payload(result, repo_name: str | None = None) -> dict:
+ """One wiki-page hit as plain data.
+
+ 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.
+ """
+ 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],
+ }
+ if repo_name is not None:
+ payload["repo"] = repo_name
+ return payload
+
+
@click.command("search")
@click.argument("query")
@click.argument("path", required=False, default=None)
@@ -49,6 +115,7 @@ _WORKSPACE_RRF_K = 60
default=False,
help="Force single-repo mode even when invoked from a workspace.",
)
+@format_option()
def search_command(
query: str,
path: str | None,
@@ -57,6 +124,7 @@ def search_command(
repo_alias: str | None,
search_all: bool,
no_workspace: bool,
+ fmt: str,
) -> None:
"""Search wiki pages by keyword, meaning, or symbol name.
@@ -70,7 +138,8 @@ def search_command(
no_workspace_flag=no_workspace,
repo_alias=repo_alias,
)
- target.notice(console, command=f"search ({mode})")
+ notices = _notices(fmt)
+ target.notice(notices, command=f"search ({mode})")
repo_paths: list[Path] = []
if target.is_workspace:
@@ -93,18 +162,21 @@ def search_command(
repo_paths = [p for p in repo_paths if (p / ".repowise").is_dir()]
if not repo_paths:
- console.print("[yellow]No indexed repos to search. Run 'repowise init' first.[/yellow]")
+ notices.print("[yellow]No indexed repos to search. Run 'repowise init' first.[/yellow]")
+ # json mode still owes stdout a parseable document, not nothing.
+ if fmt == "json":
+ emit_json({"query": query, "mode": 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)
+ _search_fulltext(repo_path, query, limit, fmt)
elif mode == "semantic":
- _search_semantic(repo_path, query, limit)
+ _search_semantic(repo_path, query, limit, fmt)
elif mode == "symbol":
- _search_symbol(repo_path, query, limit)
+ _search_symbol(repo_path, query, limit, fmt)
return
# Multi-repo fan-out — gather, rank, render once.
@@ -124,23 +196,25 @@ def search_command(
else: # symbol
results = _collect_symbol(rp, query, limit)
except Exception as exc:
- console.print(f"[yellow]search failed for {rp.name}: {exc}[/yellow]")
+ 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:
- console.print("[yellow]No results across the workspace.[/yellow]")
+ notices.print("[yellow]No results across the workspace.[/yellow]")
+ if fmt == "json":
+ emit_json({"query": query, "mode": mode, "results": []})
return
if keyless_repos:
- console.print(
+ notices.print(
f"[yellow]No embedder configured for: {', '.join(sorted(keyless_repos))}."
"[/yellow]\nThose repos contributed full-text results."
)
if mode == "symbol":
- _render_symbol_rows([(n, r) for n, r, _ in all_results], query, limit, multi=True)
+ _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
@@ -158,10 +232,13 @@ def search_command(
_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 _search_fulltext(repo_path, query: str, limit: int) -> None:
+def _search_fulltext(repo_path, query: str, limit: int, fmt: str = "table") -> None:
async def _run():
from repowise.core.persistence import FullTextSearch, create_engine
@@ -173,10 +250,10 @@ def _search_fulltext(repo_path, query: str, limit: int) -> None:
return results
results = run_async(_run())
- _display_results(results, f"Full-text search: '{query}'")
+ _display_results(results, f"Full-text search: '{query}'", fmt, query=query, mode="fulltext")
-def _search_semantic(repo_path, query: str, limit: int) -> None:
+def _search_semantic(repo_path, query: str, limit: int, fmt: str = "table") -> None:
served_fulltext = False
async def _run():
@@ -242,7 +319,7 @@ def _search_semantic(repo_path, query: str, limit: int) -> None:
if pinned == "mock"
else f"The '{pinned}' embedder could not be used"
)
- console.print(
+ _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."
@@ -250,10 +327,15 @@ def _search_semantic(repo_path, query: str, limit: int) -> None:
_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 _search_symbol(repo_path, query: str, limit: int) -> None:
+def _search_symbol(repo_path, query: str, limit: int, fmt: str = "table") -> None:
async def _run():
from sqlalchemy import text as sa_text
@@ -277,24 +359,21 @@ def _search_symbol(repo_path, query: str, limit: int) -> None:
return rows
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 _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],
+ }
+ )
+ return
- table = Table(title=f"Symbol search: '{query}'")
- table.add_column("Name", style="cyan")
- table.add_column("Qualified Name")
- table.add_column("Kind")
- table.add_column("File")
- table.add_column("Line", justify="right")
-
- for row in rows:
- table.add_row(str(row[0]), str(row[1]), str(row[2]), str(row[3]), str(row[4]))
-
- if not rows:
- console.print(f"[yellow]No symbols matching '{query}'[/yellow]")
- else:
- console.print(table)
-
-
-def _display_results(results, title: str) -> None:
table = Table(title=title)
table.add_column("Score", justify="right", style="green")
table.add_column("Title", style="cyan")
@@ -408,8 +487,20 @@ def _collect_symbol(repo_path, query: str, limit: int):
return run_async(_run())
-def _display_results_multi(pairs, title: str) -> None:
+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)
table.add_column("Score", justify="right", style="green")
table.add_column("Repo", style="magenta")
@@ -430,8 +521,24 @@ def _display_results_multi(pairs, title: str) -> None:
console.print(table)
-def _render_symbol_rows(pairs, query: str, limit: int, *, multi: bool) -> None:
- """Render symbol rows; ``pairs`` is a list of ``(repo_name, row)`` tuples."""
+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)
table.add_column("Name", style="cyan")
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 0b6cfadc3..9a207c048 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -6,6 +6,7 @@ import asyncio
import contextlib
import json
import os
+import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal, TypeVar
@@ -13,6 +14,7 @@ from typing import Any, Literal, TypeVar
import click
from rich.console import Console
+from repowise.cli.output import resolve_console_width
from repowise.core.reasoning import (
ReasoningMode,
)
@@ -43,8 +45,11 @@ from repowise.core.update_lock import (
T = TypeVar("T")
-console = Console()
-err_console = Console(stderr=True)
+# Width is pinned only when the stream is not a terminal — see
+# `output.resolve_console_width`. Without it rich renders a pipe at 80 columns
+# and ellipsises the very paths an agent needs to act on.
+console = Console(width=resolve_console_width(sys.stdout))
+err_console = Console(stderr=True, width=resolve_console_width(sys.stderr))
STATE_FILENAME = "state.json"
REPOWISE_DIR = ".repowise"
diff --git a/packages/cli/src/repowise/cli/output.py b/packages/cli/src/repowise/cli/output.py
new file mode 100644
index 000000000..370340010
--- /dev/null
+++ b/packages/cli/src/repowise/cli/output.py
@@ -0,0 +1,108 @@
+"""The CLI's single output seam: console width policy and machine-readable output.
+
+Two problems this module owns, both of which only bite non-interactive
+consumers (agents, pipes, CI):
+
+1. **Width.** Rich sizes a non-terminal ``Console`` at 80 columns — *narrower*
+ than any real terminal. So the consumer that cannot ask for the rest is the
+ one whose output gets truncated hardest: at 80 columns ``repowise search``
+ renders every path as ``packages/core…``, which cannot be opened, grepped,
+ or even recognised as truncated without counting characters.
+ :func:`resolve_console_width` is the fix, applied once where the shared
+ consoles are built (``helpers.py``) rather than at each of the ~36 table
+ call sites.
+
+2. **Format.** A rich table is not a machine format at any width: widening it
+ stops the ellipsis, but folding a long path across three lines inside box
+ drawing is no more parseable. Structured output is the real answer, and
+ :func:`format_option` / :func:`emit_json` are the one spelling of it, so the
+ CLI stops growing a new flag name per command (it already has four:
+ ``--format``, ``--json``, ``--output``, ``--progress``).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from typing import IO, Any
+
+import click
+
+#: Width used for a non-interactive stream. Rich sizes tables to their content,
+#: so a generous value costs nothing when rows are short — measured on this
+#: repo, ``repowise search`` emits 4,318 chars with 14 ellipses at 200 columns
+#: and 3,620 chars with none at 400, i.e. the wider rendering is both complete
+#: *and* smaller. 400 carries enough headroom for a deep monorepo path in a
+#: multi-column table.
+#:
+#: Ceiling: ``Panel`` expands to the full width, so a panel printed to a pipe
+#: costs ~1.2K chars here against ~240 at 80 columns. That is affordable today
+#: because only ``decision`` prints a panel on a result path; the rest live in
+#: the interactive ``ui/`` flows, which only render to a real terminal. If a
+#: future command prints panels to a pipe, give it ``expand=False`` rather than
+#: narrowing this constant and reintroducing truncation everywhere.
+NON_TTY_WIDTH = 400
+
+
+def resolve_console_width(stream: IO[str]) -> int | None:
+ """Width for a shared :class:`~rich.console.Console` writing to *stream*.
+
+ ``None`` means "let rich decide" — it reads ``COLUMNS`` and then the real
+ terminal size. An explicit width is returned only for the non-interactive
+ case rich would otherwise render at 80 columns.
+
+ ``COLUMNS`` still wins when set, so an operator (or a benchmark harness
+ pinning a width deliberately) keeps full control.
+
+ Known limitation: this cannot tell a deliberate ``COLUMNS`` from an
+ inherited one. Some shells and CI runners export ``COLUMNS=80``, and in
+ that environment the truncation fix silently does not apply. Honouring the
+ variable is the standard contract and a benchmark pinning a narrow width
+ depends on it, so it is honoured unconditionally rather than second-guessed
+ by comparing against a threshold — but it does mean "a non-TTY never
+ truncates" holds only when ``COLUMNS`` is unset.
+ """
+ if os.environ.get("COLUMNS"):
+ return None
+ try:
+ if stream.isatty():
+ return None
+ except Exception:
+ # A stream that cannot answer isatty() (a captured buffer, a closed
+ # handle) is not a terminal for our purposes.
+ pass
+ return NON_TTY_WIDTH
+
+
+def format_option(
+ *,
+ choices: tuple[str, ...] = ("table", "json"),
+ default: str = "table",
+ help: str = "Output format.",
+) -> Any:
+ """The CLI's one ``--format`` option, bound to the ``fmt`` parameter.
+
+ Matches the spelling the commands that already have a machine-readable
+ mode use (``dead-code``, ``doctor``, ``health``, ``impacted-tests``,
+ ``risk``), so adopting it elsewhere adds no new convention.
+ """
+ return click.option(
+ "--format",
+ "fmt",
+ type=click.Choice(list(choices)),
+ default=default,
+ help=help,
+ )
+
+
+def emit_json(payload: Any) -> None:
+ """Write *payload* to stdout as JSON, the way the existing commands do.
+
+ ``default=str`` keeps a stray non-serialisable value (a ``Decimal`` or
+ ``datetime`` off a database row) from turning a working command into a
+ traceback; the field degrades to its string form instead.
+ """
+ click.echo(json.dumps(payload, indent=2, default=str))
+
+
+__all__ = ["NON_TTY_WIDTH", "emit_json", "format_option", "resolve_console_width"]
diff --git a/packages/cli/src/repowise/cli/providers/embedders.py b/packages/cli/src/repowise/cli/providers/embedders.py
index 644c02a08..7d96b0479 100644
--- a/packages/cli/src/repowise/cli/providers/embedders.py
+++ b/packages/cli/src/repowise/cli/providers/embedders.py
@@ -155,9 +155,15 @@ def build_embedder(embedder_name_resolved: str) -> Any:
# Said here, once, rather than in each of the thirteen call sites, for
# the same reason build_vector_store says its own refusal here: a
# caller that forgets is exactly how this became invisible.
- from repowise.cli.helpers import console
-
- console.print(
+ # stderr, not stdout: this is a diagnostic about a degraded run, and
+ # every caller's stdout may be a machine-readable document. `repowise
+ # search --mode semantic --format json` against a repo whose key has
+ # gone away otherwise prints this warning in front of the JSON and
+ # breaks every parser reading it — and that is the common case for a
+ # keyless repo, not an exotic one.
+ from repowise.cli.helpers import err_console
+
+ err_console.print(
f"[yellow]Embedder '{embedder_name_resolved}' could not be built:[/yellow] "
f"{type(exc).__name__}: {exc}\n"
"Falling back to keyless embeddings, which means [bold]no semantic search[/bold] "
diff --git a/tests/unit/cli/test_embedder_resolution.py b/tests/unit/cli/test_embedder_resolution.py
index 30611696f..1f2518ec2 100644
--- a/tests/unit/cli/test_embedder_resolution.py
+++ b/tests/unit/cli/test_embedder_resolution.py
@@ -607,12 +607,17 @@ def test_duplicate_reembed_actions_run_once() -> None:
def _capture_console(monkeypatch) -> list[str]:
- """Collect what build_embedder prints, without a real terminal."""
+ """Collect what build_embedder prints, without a real terminal.
+
+ It warns on **stderr**: the caller's stdout may be a JSON document (see
+ ``test_output_agent_readiness.py``), and a warning printed in front of it
+ breaks every parser reading it.
+ """
from repowise.cli import helpers
printed: list[str] = []
monkeypatch.setattr(
- helpers.console, "print", lambda *a, **k: printed.append(" ".join(str(x) for x in a))
+ helpers.err_console, "print", lambda *a, **k: printed.append(" ".join(str(x) for x in a))
)
return printed
diff --git a/tests/unit/cli/test_output_agent_readiness.py b/tests/unit/cli/test_output_agent_readiness.py
new file mode 100644
index 000000000..57ede617e
--- /dev/null
+++ b/tests/unit/cli/test_output_agent_readiness.py
@@ -0,0 +1,260 @@
+"""Non-interactive output must not lose information, and must be parseable.
+
+Rich sizes a non-terminal ``Console`` at 80 columns, which is *narrower* than
+any real terminal. So the consumer that cannot ask for the rest — an agent, a
+pipe, CI — was the one getting truncated hardest: ``repowise search`` rendered
+every result path as ``packages/core…``, which cannot be opened or grepped and
+cannot even be recognised as truncated without counting characters. Measured on
+this repo before the fix: 28 ellipses at the non-TTY default, and still 14 at
+``COLUMNS=200`` (the width the session-cost eval pinned as its mitigation).
+
+Widening stops the ellipsis, but a rich table is still not a machine format, so
+``search`` also grew ``--format json``. These tests pin both halves.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import sys
+
+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.output import NON_TTY_WIDTH, emit_json, resolve_console_width
+
+LONG_PATH = "packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py"
+
+
+class _Stream:
+ def __init__(self, tty: bool) -> None:
+ self._tty = tty
+
+ def isatty(self) -> bool:
+ return self._tty
+
+
+class _Result:
+ """Minimal stand-in for a wiki-page search hit."""
+
+ 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"
+
+
+# ---------------------------------------------------------------------------
+# Width policy
+# ---------------------------------------------------------------------------
+
+
+def test_non_tty_gets_an_explicit_wide_width() -> None:
+ assert resolve_console_width(_Stream(tty=False)) == NON_TTY_WIDTH
+
+
+def test_terminal_is_left_to_rich() -> None:
+ assert resolve_console_width(_Stream(tty=True)) is None
+
+
+def test_explicit_columns_wins_over_the_policy(monkeypatch) -> None:
+ """An operator (or a benchmark pinning a width) keeps control."""
+ monkeypatch.setenv("COLUMNS", "120")
+ assert resolve_console_width(_Stream(tty=False)) is None
+
+
+def test_stream_that_cannot_answer_isatty_is_treated_as_non_tty() -> None:
+ class Broken:
+ def isatty(self):
+ raise ValueError("detached")
+
+ assert resolve_console_width(Broken()) == NON_TTY_WIDTH
+
+
+# ---------------------------------------------------------------------------
+# The regression itself: a piped table must keep its paths whole
+# ---------------------------------------------------------------------------
+
+
+def _render_table(width: int | None) -> str:
+ buf = io.StringIO()
+ table = Table(title="Full-text search")
+ for column in ("Score", "Title", "Type", "Path", "Snippet"):
+ table.add_column(column)
+ for _ in range(3):
+ table.add_row("15.198", "Symbol: LanceDBVectorStore", "symbol_spotlight", LONG_PATH, "#")
+ Console(file=buf, width=width, no_color=True).print(table)
+ return buf.getvalue()
+
+
+def test_piped_table_keeps_every_path_intact() -> None:
+ rendered = _render_table(NON_TTY_WIDTH)
+ assert LONG_PATH in rendered
+ assert "…" not in rendered
+
+
+def test_the_old_default_width_is_what_destroyed_the_paths() -> None:
+ """Guards the premise: at rich's non-TTY default the path is unusable."""
+ rendered = _render_table(80)
+ assert LONG_PATH not in rendered
+ assert "…" in rendered
+
+
+# ---------------------------------------------------------------------------
+# Machine-readable output
+# ---------------------------------------------------------------------------
+
+
+def test_emit_json_round_trips(capsys) -> None:
+ emit_json({"a": 1, "nested": [{"b": 2}]})
+ assert json.loads(capsys.readouterr().out) == {"a": 1, "nested": [{"b": 2}]}
+
+
+def test_emit_json_degrades_unserialisable_values_instead_of_raising(capsys) -> None:
+ from decimal import Decimal
+
+ emit_json({"score": Decimal("1.5")})
+ assert json.loads(capsys.readouterr().out) == {"score": "1.5"}
+
+
+def test_search_json_emits_a_document_even_with_no_results(capsys) -> 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) == {
+ "query": "nothing",
+ "mode": "fulltext",
+ "results": [],
+ }
+
+
+def test_search_json_carries_whole_paths_and_declares_its_mode(capsys) -> None:
+ _display_results([_Result()], "ignored", "json", query="lancedb", mode="fulltext")
+
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["query"] == "lancedb"
+ assert payload["mode"] == "fulltext"
+ assert payload["results"][0]["path"] == LONG_PATH
+
+
+def test_search_json_does_not_clip_the_snippet(capsys) -> 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")
+
+ assert json.loads(capsys.readouterr().out)["results"][0]["snippet"] == result.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",
+ )
+
+ 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)
+
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["mode"] == "symbol"
+ assert payload["results"] == [
+ {
+ "name": "LanceDBVectorStore",
+ "qualified_name": "a.b.LanceDBVectorStore",
+ "kind": "class",
+ "path": LONG_PATH,
+ "line": 60,
+ }
+ ]
+
+
+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.
+
+ ``output.py`` can be perfectly correct while ``helpers.py`` forgets to use
+ it, which would leave every table truncated exactly as before.
+ """
+ if os.environ.get("COLUMNS"):
+ pytest.skip("COLUMNS is pinned here, and the policy defers to it by design")
+
+ from repowise.cli import helpers
+
+ assert not sys.stdout.isatty(), "pytest captures stdout; this test assumes a non-TTY"
+ assert helpers.console.width == NON_TTY_WIDTH
+
+
+def test_a_degraded_embedder_warns_on_stderr_so_json_stdout_stays_parseable(
+ capsys, monkeypatch
+) -> None:
+ """Regression: this warning used to print to stdout, in front of the JSON.
+
+ ``build_embedder`` is two modules below ``search``, so the command-level
+ stderr diversion cannot reach it — the warning has to be on stderr at its
+ source. A repo whose embedder key has gone away is the common case for
+ ``--mode semantic``, not an exotic one, so this corrupted the payload for
+ exactly the users most likely to hit it.
+ """
+ from repowise.cli import providers
+
+ def _boom(name: str, **kwargs: object):
+ raise RuntimeError("no key configured")
+
+ monkeypatch.setattr("repowise.core.providers.embedding.registry.get_embedder", _boom)
+
+ providers.build_embedder("openai")
+ emit_json({"query": "auth", "mode": "fulltext", "results": []})
+
+ captured = capsys.readouterr()
+ assert json.loads(captured.out) == {"query": "auth", "mode": "fulltext", "results": []}
+ assert "openai" in captured.err
+
+
+ ("requested", "keyless", "mixed", "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"),
+ ],
+)
+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)
+
+ assert len(json.loads(capsys.readouterr().out)["results"]) == 2
diff --git a/tests/unit/server/mcp/test_keyless_vector_leg.py b/tests/unit/server/mcp/test_keyless_vector_leg.py
index 2096ff61f..de584c5ea 100644
--- a/tests/unit/server/mcp/test_keyless_vector_leg.py
+++ b/tests/unit/server/mcp/test_keyless_vector_leg.py
@@ -323,7 +323,9 @@ def _patch_cli_search(monkeypatch, tmp_path, embedder):
monkeypatch.setattr(
search_cmd,
"_display_results",
- lambda results, title: (
+ # `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),
),