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(init): end on what stood out, and name the model command for this machine (#4677)

Raghav Chamadiya4da7df563970
diff --git a/packages/cli/src/repowise/cli/agent_events.py b/packages/cli/src/repowise/cli/agent_events.py
index 6611a3e68..2e62000cd 100644
--- a/packages/cli/src/repowise/cli/agent_events.py
+++ b/packages/cli/src/repowise/cli/agent_events.py
@@ -53,6 +53,7 @@ def summary_fields(
files_written: list[str] | None = None,
next_commands: list[str] | None = None,
error: str | None = None,
+ findings: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Every summary key, always present, so a consumer never probes for one."""
fields: dict[str, Any] = {
@@ -63,6 +64,8 @@ def summary_fields(
"warnings": list(warnings or []),
"files_written": list(files_written or []),
"next": list(next_commands or []),
+ # What the finish panel's "What stood out" showed; null before it rendered.
+ "findings": findings,
}
if error is not None:
fields["error"] = error
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_agent_summary.py b/packages/cli/src/repowise/cli/commands/init_cmd/_agent_summary.py
index bd29249ea..c793efd3c 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_agent_summary.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_agent_summary.py
@@ -82,10 +82,12 @@ def _spend(result: Any) -> dict[str, Any]:
def _next_commands(run: InitRun) -> list[str]:
- """The panel's next steps, ``repowise serve`` first."""
+ """The panel's next steps, ``repowise serve`` first, then its model command if any."""
commands = [command for command, _gloss in run.next_steps]
if SERVE_COMMAND not in commands:
commands.insert(0, SERVE_COMMAND)
+ if run.model_upgrade is not None:
+ commands.insert(1, run.model_upgrade.command)
return commands
@@ -99,6 +101,7 @@ def run_summary(run: InitRun, gaps: list[str]) -> dict[str, Any]:
warnings=[*run.run_warnings, *gaps],
files_written=_relative(run.repo_path, run.files_written),
next_commands=_next_commands(run),
+ findings=run.stood_out.as_summary() if run.stood_out is not None else None,
)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
index 8509f96f3..0b15c3eec 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
@@ -442,7 +442,7 @@ def complete_setup(run: InitRun) -> None:
first_index=run.first_index,
no_editor_setup=not opts.editor_setup,
)
- run.next_steps = show_completion(
+ completion = show_completion(
repo_path=repo_path,
result=run.result,
start=run.start,
@@ -454,6 +454,9 @@ def complete_setup(run: InitRun) -> None:
verbose=opts.verbose,
owl=_finish_owl(run),
)
+ run.next_steps = completion.steps
+ run.stood_out = completion.stood_out
+ run.model_upgrade = completion.model_upgrade
def _gaps(run: InitRun) -> list[str]:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
index 6ea31b833..6608b3141 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
@@ -119,6 +119,9 @@ class InitRun:
setup_outcome: Any = None
files_written: list[Path] = field(default_factory=list)
next_steps: list[tuple[str, str]] = field(default_factory=list)
+ #: The finish panel's findings (StoodOut) and model block (ModelUpgrade).
+ stood_out: Any = None
+ model_upgrade: Any = None
def resolve_structural_flags(opts: InitOptions) -> InitOptions:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py
index dba7ed7e4..ec073d7c2 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py
@@ -9,7 +9,9 @@ from __future__ import annotations
import time
from pathlib import Path
-from typing import Any
+from typing import Any, NamedTuple
+
+import structlog
from repowise.cli.helpers import console, load_config, load_state
from repowise.cli.ui import (
@@ -17,7 +19,12 @@ from repowise.cli.ui import (
format_elapsed,
mascot,
)
-from repowise.cli.ui.finish_panel import FinishFacts, print_finish_panel
+from repowise.cli.ui.finish_panel import (
+ FinishFacts,
+ ModelUpgrade,
+ StoodOut,
+ print_finish_panel,
+)
from repowise.cli.ui.mode_names import pages, provider_model
from repowise.cli.ui.workspace_finish import (
RepoOutcome,
@@ -25,6 +32,8 @@ from repowise.cli.ui.workspace_finish import (
print_workspace_finish_panel,
)
+logger = structlog.get_logger(__name__)
+
def _dead_counts(result: Any) -> tuple[int, int]:
findings = result.dead_code_report.findings if result.dead_code_report else []
@@ -93,9 +102,23 @@ def _render_defect_accuracy(result: Any) -> None:
_LARGE_REPO_FILES = 1000
-def completion_hint(run_mode: str, file_count: int) -> str:
- """Which hint a finished init earns: big repos hear about freshness."""
- return "large_repo" if run_mode == "fast" or file_count >= _LARGE_REPO_FILES else "init_success"
+def completion_hint(run_mode: str, file_count: int, first_index: bool = False) -> str | None:
+ """Which hint a finished init earns: big repos hear about freshness.
+
+ A first index ends on its own findings and tour, so it earns no
+ ``init_success`` hint.
+ """
+ if run_mode == "fast" or file_count >= _LARGE_REPO_FILES:
+ return "large_repo"
+ return None if first_index else "init_success"
+
+
+class Completion(NamedTuple):
+ """What the finish panel showed, for the ``--progress json`` summary."""
+
+ steps: list[tuple[str, str]]
+ stood_out: StoodOut
+ model_upgrade: ModelUpgrade | None
def show_completion(
@@ -110,23 +133,28 @@ def show_completion(
files_written: list[Path] | None = None,
verbose: bool = False,
owl: str = mascot.DONE,
-) -> list[tuple[str, str]]:
- """Render the one finish panel and return its next steps; generation checks only under ``-v``.
+) -> Completion:
+ """Render the one finish panel and return what it showed; generation checks only under ``-v``.
*owl* is the mini owl state on the panel title: how the run finished.
*setup* is the :class:`~repowise.cli.editor_setup.EditorSetupOutcome`
snapshot and *files_written* what editor setup put in the working tree,
- so the panel reports what setup actually did.
+ so the panel reports what setup actually did. Its ``first_index`` also
+ keeps the ``init_success`` hint off a first index.
"""
from repowise.core.index_scope import resolve_index_scope
- scope = resolve_index_scope(load_state(Path(repo_path)), load_config(Path(repo_path)))
+ repo_path = Path(repo_path)
+ scope = resolve_index_scope(load_state(repo_path), load_config(repo_path))
graph = result.graph_builder.graph()
dead_unreachable, dead_unused = _dead_counts(result)
- decisions = sum(result.decision_report.by_source.values()) if result.decision_report else 0
# A most-committed file is only worth naming when git analysis calls it a hotspot.
- top_hotspot = _top_hotspot(result) if _hotspots(result) else ""
+ hotspot = _top_hotspot(result) if _hotspots(result) else None
+ top_hotspot = hotspot[0].rsplit("/", 1)[-1] if hotspot else ""
+ stood_out = _stood_out(result, repo_path, hotspot)
+ # Fast mode has its own keyless next step: the full index, before any model.
+ keyless_docs = effective_index_only and run_mode != "fast"
documentation, spend = (
_template_pages(result) if effective_index_only else _model_pages(result)
)
@@ -138,23 +166,19 @@ def show_completion(
graph_nodes=graph.number_of_nodes(),
graph_edges=graph.number_of_edges(),
elapsed=format_elapsed(time.monotonic() - start),
- dead_unreachable=dead_unreachable,
- dead_unused=dead_unused,
- decisions=decisions,
- git_files=result.git_summary.files_indexed if result.git_summary else None,
- hotspots=_hotspots(result),
top_hotspot=top_hotspot,
pages=documentation,
spend=spend,
embed_failed=getattr(result, "embed_failed_pages", 0),
+ stood_out=stood_out,
+ model_upgrade=_model_upgrade(repo_path) if keyless_docs else None,
)
steps = build_contextual_next_steps(
- index_only=effective_index_only,
fast_mode=(run_mode == "fast"),
dead_unreachable=dead_unreachable,
dead_unused=dead_unused,
- hotspot_count=facts.hotspots,
- decision_count=decisions,
+ hotspot_count=_hotspots(result),
+ decision_count=stood_out.decision_candidates or 0,
top_hotspot=top_hotspot,
setup=setup,
)
@@ -164,7 +188,7 @@ def show_completion(
facts,
steps=steps,
setup=setup,
- repo_path=Path(repo_path),
+ repo_path=repo_path,
files_written=files_written,
owl=owl,
)
@@ -175,19 +199,156 @@ def show_completion(
# shown); a big repo hears about staying fresh instead.
from repowise.cli.hints import maybe_hint
- maybe_hint(completion_hint(run_mode, result.file_count))
+ hint = completion_hint(run_mode, result.file_count, bool(getattr(setup, "first_index", False)))
+ if hint:
+ maybe_hint(hint)
if verbose:
_show_generation_checks(result)
- return steps
+ return Completion(steps, stood_out, facts.model_upgrade)
-def _top_hotspot(result: Any) -> str:
- """Basename of the most-committed file, for the risk step and the agent question."""
+def _top_hotspot(result: Any) -> tuple[str, int] | None:
+ """The most-committed file and its commit count, for the findings, risk step and question."""
if not result.git_meta_map:
- return ""
- path = max(result.git_meta_map.items(), key=lambda x: x[1].get("commit_count", 0))[0]
- return path.rsplit("/", 1)[-1]
+ return None
+ path, meta = max(result.git_meta_map.items(), key=lambda x: x[1].get("commit_count", 0))
+ return path, int(meta.get("commit_count", 0) or 0)
+
+
+def _stood_out(result: Any, repo_path: Path, hotspot: tuple[str, int] | None) -> StoodOut:
+ """The finish panel's findings, each from data this run already has."""
+ path, commits = hotspot or (None, None)
+ return StoodOut(
+ **_health_finding(result),
+ **_dead_finding(result),
+ hotspot_file=path,
+ hotspot_commits=commits,
+ decision_candidates=_decision_candidates(repo_path),
+ )
+
+
+def _health_finding(result: Any) -> dict[str, Any]:
+ """Repo score, its mark (withheld when too little was analysed), and the lowest file."""
+ report = getattr(result, "health_report", None)
+ kpis = getattr(report, "kpis", None) or {}
+ score = kpis.get("average_health")
+ if not isinstance(score, (int, float)):
+ return {}
+ from repowise.core.analysis.health.grading import headline_band, mark_for
+
+ graded = headline_band(float(score), kpis.get("analysed_share")) is not None
+ return {
+ "health_score": float(score),
+ "health_mark": mark_for(float(score)) if graded else None,
+ "lowest_file": kpis.get("worst_performer_path"),
+ "lowest_score": kpis.get("worst_performer_score"),
+ }
+
+
+def _dead_finding(result: Any) -> dict[str, Any]:
+ """Unreachable files, and the findings that pass the deletion gate.
+
+ A whole unreachable file is review-only and never passes the gate, so the
+ safe count is over every finding, not over those files.
+ """
+ report = getattr(result, "dead_code_report", None)
+ if report is None:
+ return {}
+ from repowise.core.analysis.dead_code.serving import is_safe
+
+ findings = report.findings
+ return {
+ "dead_unreachable": sum(1 for f in findings if f.kind.value == "unreachable_file"),
+ "dead_safe": sum(1 for f in findings if is_safe(f)),
+ }
+
+
+def _decision_candidates(repo_path: Path) -> int | None:
+ """The decision layer's own candidate count from the store; None when it cannot be read."""
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.cli.helpers import run_async
+
+ try:
+ return run_async(_count_candidates(repo_path))
+ except (SQLAlchemyError, OSError):
+ # A missing or unreadable store: the row is left out, never shown as 0.
+ return None
+ except Exception:
+ # Anything else is a bug in the count. Logged, and the row is still
+ # left out so the finish panel never fails on it.
+ logger.exception("decision_candidate_count_failed", repo=str(repo_path))
+ return None
+
+
+async def _count_candidates(repo_path: Path) -> int | None:
+ from sqlalchemy import select
+
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.crud.authority import count_decisions_by_lane
+ from repowise.core.persistence.models import Repository
+
+ engine = create_engine(get_db_url_for_repo(repo_path))
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ repo_id = (
+ await session.execute(
+ select(Repository.id).where(Repository.local_path == str(repo_path))
+ )
+ ).scalar_one_or_none()
+ if repo_id is None:
+ return None
+ return (await count_decisions_by_lane(session, repo_id))["candidates"]
+ finally:
+ await engine.dispose()
+
+
+def _model_upgrade(repo_path: Path) -> ModelUpgrade:
+ """The command that adds a model, for the source this machine already has.
+
+ A signed-in agent CLI first, then a key, else the bare command. A sign-in
+ is never called free: it does not prove a plan.
+ """
+ from repowise.core.index_scope import MODEL_COMMAND
+
+ source = _signed_in_agent() or _keyed_provider(repo_path)
+ if source is None:
+ return ModelUpgrade(MODEL_COMMAND)
+ name, line = source
+ return ModelUpgrade(f"{MODEL_COMMAND} --provider {name}", line)
+
+
+def _signed_in_agent() -> tuple[str, str] | None:
+ """``(provider id, source line)`` for the first signed-in agent CLI worth offering."""
+ from repowise.core.platform.telemetry import network_disabled
+
+ if network_disabled(): # the probe spawns third-party CLIs that phone home
+ return None
+ from repowise.cli.ui.subscription import logged_in_agent_providers
+ from repowise.core.agents.identity import identity_for_provider
+
+ for name, auth in logged_in_agent_providers().items():
+ agent = identity_for_provider(name)
+ if auth.offer and agent is not None:
+ return name, f"Uses your {agent.display_name} sign-in"
+ return None
+
+
+def _keyed_provider(repo_path: Path) -> tuple[str, str] | None:
+ """``(provider id, source line)`` for the first provider a key or local model is set for."""
+ from repowise.core.providers.llm.resolve import credentialed_providers
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+ for name in credentialed_providers(repo_path):
+ spec = PROVIDER_SPECS.get(name)
+ if spec is None or spec.agent or name == "mock":
+ continue
+ if spec.local:
+ return name, f"Uses {spec.label.removesuffix(' (Local)')} on this machine"
+ return name, f"Uses your {spec.label} key"
+ return None
def _template_pages(result: Any) -> tuple[str | None, None]:
diff --git a/packages/cli/src/repowise/cli/hints.py b/packages/cli/src/repowise/cli/hints.py
index ee228fe56..a0c2fa092 100644
--- a/packages/cli/src/repowise/cli/hints.py
+++ b/packages/cli/src/repowise/cli/hints.py
@@ -5,6 +5,8 @@ Rules that keep it from being a nag:
* stderr only, one dim line plus its link, never in ``--format json`` runs;
* at most one hint per command run, and each hint at most once every 7 days;
* never from ``mcp``, ``serve``, ``watch``, hooks, or anything an agent reads;
+* never ``init_success`` on a first index, which ends on its own findings
+ (``init_cmd.reporting.completion_hint``);
* off in CI and tests, when stderr is not a terminal, for signed-in users,
with ``REPOWISE_NO_HINTS=1``, ``repowise config hints off`` or ``DO_NOT_TRACK``.
diff --git a/packages/cli/src/repowise/cli/ui/finish_panel.py b/packages/cli/src/repowise/cli/ui/finish_panel.py
index 47ecfb6af..df7ad2423 100644
--- a/packages/cli/src/repowise/cli/ui/finish_panel.py
+++ b/packages/cli/src/repowise/cli/ui/finish_panel.py
@@ -7,7 +7,7 @@ what do I ask it, what do I run next, and what did init leave in my repo.
from __future__ import annotations
from collections.abc import Mapping
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -17,11 +17,63 @@ from rich.padding import Padding
from rich.text import Text
from repowise.cli.ui import mascot
-from repowise.cli.ui.brand import BRAND, WARN, key_value_table
+from repowise.cli.ui.brand import BRAND, ERR, INFO, MODEL, OK, WARN, key_value_table
from repowise.cli.ui.mode_names import INDEX_ONLY, completion_title, mode_label, scope_line
from repowise.cli.ui.result_panels import build_completion_panel, print_completion_panel
+@dataclass(frozen=True)
+class StoodOut:
+ """What the run measured that is worth a look; ``None`` means not measured."""
+
+ health_score: float | None = None
+ #: ``grading.mark_for`` of the score; None when too little was analysed to grade.
+ health_mark: str | None = None
+ lowest_file: str | None = None
+ lowest_score: float | None = None
+ dead_unreachable: int | None = None
+ #: Findings of any kind that pass the deletion gate (a whole file never does).
+ dead_safe: int | None = None
+ hotspot_file: str | None = None
+ hotspot_commits: int | None = None
+ decision_candidates: int | None = None
+
+ def as_summary(self) -> dict[str, Any]:
+ """The same findings for ``--progress json``, one key each, null when not measured."""
+ health = None
+ if self.health_score is not None:
+ health = {
+ "score": self.health_score,
+ "band": self.health_mark,
+ "lowest_file": self.lowest_file,
+ "lowest_score": self.lowest_score,
+ }
+ dead = None
+ if self.dead_unreachable is not None:
+ dead = {
+ "unreachable_files": self.dead_unreachable,
+ "findings_safe_to_delete": self.dead_safe,
+ }
+ hotspot = None
+ if self.hotspot_file:
+ hotspot = {"file": self.hotspot_file, "commits": self.hotspot_commits}
+ return {
+ "health": health,
+ "dead_code": dead,
+ "hotspot": hotspot,
+ "decision_candidates": self.decision_candidates,
+ }
+
+
+@dataclass(frozen=True)
+class ModelUpgrade:
+ """The command that adds a model, and the source on this machine it uses."""
+
+ command: str
+ #: e.g. "Uses your Claude Code sign-in"; None when nothing was detected.
+ source: str | None = None
+
+
@dataclass(frozen=True)
class FinishFacts:
"""What the run produced, already counted; the panel only formats it."""
@@ -33,18 +85,15 @@ class FinishFacts:
graph_nodes: int
graph_edges: int
elapsed: str
- dead_unreachable: int = 0
- dead_unused: int = 0
- decisions: int = 0
- #: None when the run read no git history.
- git_files: int | None = None
- hotspots: int = 0
top_hotspot: str = ""
#: The documentation count, e.g. "42 pages"; None when none was built.
pages: str | None = None
#: Model spend, e.g. "$0.12 (40,000 tokens)"; None for a keyless run.
spend: str | None = None
embed_failed: int = 0
+ stood_out: StoodOut = field(default_factory=StoodOut)
+ #: The "add a model" block of a run whose documentation was built from the index.
+ model_upgrade: ModelUpgrade | None = None
def _n(count: int, noun: str) -> str:
@@ -78,21 +127,86 @@ def _metrics(facts: FinishFacts) -> list[tuple[str, str]]:
rows.append(("Search", _search_label(facts)))
rows += [
("Graph", f"{_n(facts.graph_nodes, 'node')} · {_n(facts.graph_edges, 'edge')}"),
- (
- "Dead code",
- f"{_n(facts.dead_unreachable, 'unreachable file')} · "
- f"{_n(facts.dead_unused, 'unused export')}",
- ),
- ("Decisions", _n(facts.decisions, "decision")),
+ ("Elapsed", facts.elapsed),
]
- if facts.git_files is not None:
- rows.append(
- ("Git history", f"{_n(facts.git_files, 'file')} · {_n(facts.hotspots, 'hotspot')}")
- )
- rows.append(("Elapsed", facts.elapsed))
return rows
+_MARK_STYLE = {"healthy": OK, "warning": WARN, "alert": ERR}
+
+
+def _health_value(s: StoodOut) -> str:
+ from repowise.core.analysis.health.grading import MARK_LABEL, format_score
+
+ figure = f"{format_score(s.health_score)}/10"
+ if s.health_mark:
+ figure = f"[{_MARK_STYLE[s.health_mark]}]{figure} {MARK_LABEL[s.health_mark]}[/]"
+ if s.lowest_file and s.lowest_score is not None:
+ figure += f" {escape(s.lowest_file)} is lowest at {format_score(s.lowest_score)}"
+ return figure
+
+
+def _dead_value(s: StoodOut) -> str:
+ if s.dead_unreachable:
+ noun = "file" if s.dead_unreachable == 1 else "files"
+ value = f"{s.dead_unreachable:,} {noun} nothing reaches"
+ else:
+ value = "no unreachable files"
+ if s.dead_safe:
+ value += f", {_n(s.dead_safe, 'finding')} safe to delete"
+ return value
+
+
+def _hotspot_value(s: StoodOut) -> str:
+ value = escape(s.hotspot_file or "")
+ if s.hotspot_commits:
+ value += f", changed in {_n(s.hotspot_commits, 'commit')}"
+ return value
+
+
+def _decisions_value(s: StoodOut) -> str:
+ count = s.decision_candidates or 0
+ noun = "candidate" if count == 1 else "candidates"
+ return f"{count:,} {noun} to review"
+
+
+def stood_out_lines(s: StoodOut) -> list[RenderableType]:
+ """Up to four findings from data the run already has; an unmeasured one is left out."""
+ rows: list[tuple[str, str]] = []
+ if s.health_score is not None:
+ rows.append(("Health", _health_value(s)))
+ if s.dead_unreachable is not None:
+ rows.append(("Dead code", _dead_value(s)))
+ if s.hotspot_file:
+ rows.append(("Hotspot", _hotspot_value(s)))
+ if s.decision_candidates is not None:
+ rows.append(("Decisions", _decisions_value(s)))
+ if not rows:
+ return []
+ return [Text(""), line("[bold]What stood out[/bold]"), key_value_table(rows, label_width=10, value_style=INFO)]
+
+
+def model_upgrade_lines(upgrade: ModelUpgrade | None) -> list[RenderableType]:
+ """What a model adds and the exact command for the source this machine has."""
+ if upgrade is None:
+ return []
+ command = f"[{MODEL}]{escape(upgrade.command)}[/]"
+ if upgrade.source:
+ how = f"{escape(upgrade.source)}: {command}"
+ else:
+ how = f"{command} needs a key, or [{MODEL}]--provider ollama[/] for a local model."
+ return [
+ Text(""),
+ line(f"[bold {MODEL}]Add a model when you want more[/]"),
+ line(
+ "Docs that explain how and why, chat in the dashboard, "
+ "written answers for your agent."
+ ),
+ line(how),
+ dim_line("Or press m next time on the plan screen."),
+ ]
+
+
def line(markup: str, indent: int = 2) -> Padding:
"""One wrapped line; wrapped text keeps the indent."""
return Padding(Text.from_markup(markup), (0, 0, 0, indent))
@@ -274,7 +388,10 @@ def _panel_parts(
repo_path: Path | None,
files_written: list[Path] | None,
) -> tuple[str, list[tuple[str, str]], list[RenderableType], list[RenderableType]]:
- body: list[RenderableType] = []
+ body: list[RenderableType] = [
+ *stood_out_lines(facts.stood_out),
+ *model_upgrade_lines(facts.model_upgrade),
+ ]
connected = connected_lines(setup)
if connected:
body.append(Text(""))
diff --git a/packages/cli/src/repowise/cli/ui/result_panels.py b/packages/cli/src/repowise/cli/ui/result_panels.py
index 8202e596f..3e10f97e9 100644
--- a/packages/cli/src/repowise/cli/ui/result_panels.py
+++ b/packages/cli/src/repowise/cli/ui/result_panels.py
@@ -108,29 +108,34 @@ def print_completion_panel(
console.print(line)
-def serve_step(target: str = "dashboard") -> tuple[str, str]:
+def serve_step(target: str = "dashboard", gloss: str | None = None) -> tuple[str, str]:
"""The ``repowise serve`` row every completion panel leads with.
The port is the one serve tries first; serve moves to the next free port
- when it is taken, so the row says so rather than promising an exact URL.
+ when it is taken, so the row says so instead of promising an exact URL.
+ *gloss* is a first line saying what serve is for, above the address.
"""
from repowise.cli.commands.serve_cmd._ports import DEFAULT_UI_PORT
from repowise.cli.commands.serve_cmd._web_assets import _NODE_MIN_MAJOR
+ where = f"http://localhost:{DEFAULT_UI_PORT} or the next free port"
+ where = f"{gloss}\n{where}" if gloss else f"{target} at {where}"
return (
"repowise serve",
- f"{target} at http://localhost:{DEFAULT_UI_PORT} or the next free port\n"
- f"(needs Node {_NODE_MIN_MAJOR}+; the first run downloads the UI)",
+ f"{where}\n(needs Node {_NODE_MIN_MAJOR}+; the first run downloads the UI)",
)
+#: What ``repowise serve`` is for at the end of ``init``.
+TOUR_GLOSS = "a guided tour of all this in your browser"
+
+
#: Rows after ``repowise serve``.
_MAX_FOLLOW_UPS = 2
def build_contextual_next_steps(
*,
- index_only: bool,
fast_mode: bool = False,
dead_unreachable: int = 0,
dead_unused: int = 0,
@@ -151,24 +156,20 @@ def build_contextual_next_steps(
1. nothing wired an MCP client, so no agent can reach any of this yet
(``--no-editor-setup``, the CI shape, has no Connected line to say so);
- 2. the index is deliberately partial (fast, or index-only);
+ 2. the index is deliberately partial (fast);
3. the largest concrete finding, or a search row when there is none.
"""
candidates: list[tuple[str, str]] = []
if setup is not None and getattr(setup, "editor_setup_disabled", False):
candidates.append(("repowise mcp .", "connect an MCP client (Cursor, Codex, Claude Code)"))
- from repowise.core.index_scope import FAST_TO_FULL_COMMAND, MODEL_COMMAND
+ from repowise.core.index_scope import FAST_TO_FULL_COMMAND
+ # Documentation built from the index gets the panel's "add a model" block
+ # instead of a step, so the model command is not named twice.
if fast_mode:
candidates.append(
(FAST_TO_FULL_COMMAND, "build documentation from code and the full git history (no key)")
)
- elif index_only:
- # `generate` is the scoped, cost-gated upgrade: a coverage, a directory
- # or one page at a time, each behind an estimate.
- candidates.append(
- (MODEL_COMMAND, "write the documentation with a model (needs a key)")
- )
dead = dead_unreachable + dead_unused
if dead > 0:
noun = "finding" if dead == 1 else "findings"
@@ -178,13 +179,14 @@ def build_contextual_next_steps(
(f"repowise risk {escape(top_hotspot)}", "assess risk for the top hotspot")
)
elif decision_count > 0:
+ noun = "candidate" if decision_count == 1 else "candidates"
candidates.append(
- ("repowise decision list", f"browse {decision_count} architectural decisions")
+ ("repowise decision candidates", f"review {decision_count} decision {noun}")
)
elif not fast_mode:
candidates.append(('repowise search "<query>"', "search the documentation"))
- return [serve_step(), *candidates[:_MAX_FOLLOW_UPS]]
+ return [serve_step(gloss=TOUR_GLOSS), *candidates[:_MAX_FOLLOW_UPS]]
def keyless_upgrade_note(semantic_available: bool, reindex_command: str | None = None) -> str:
diff --git a/packages/core/src/repowise/core/analysis/health/grading.py b/packages/core/src/repowise/core/analysis/health/grading.py
index 85454d75d..ce94b5c43 100644
--- a/packages/core/src/repowise/core/analysis/health/grading.py
+++ b/packages/core/src/repowise/core/analysis/health/grading.py
@@ -100,6 +100,26 @@ def band_for(score: float) -> HealthBand:
return "at_risk"
+# The canonical three-band reading beside a health mark, for a figure and a word
+# printed together. Mirror of ``HEALTHY_MIN`` and ``healthMark`` in the TS packages.
+HEALTHY_MIN = 8.0
+
+HealthMark = Literal["healthy", "warning", "alert"]
+
+MARK_LABEL: dict[HealthMark, str] = {
+ "healthy": "Healthy",
+ "warning": "Warning",
+ "alert": "Alert",
+}
+
+
+def mark_for(score: float) -> HealthMark:
+ """Healthy from 8, Warning from 4, Alert below."""
+ if score >= HEALTHY_MIN:
+ return "healthy"
+ return "warning" if score >= NEEDS_WORK_MIN else "alert"
+
+
# Below this share of code files scored, the repo average describes a sample,
# not the repo, so no band is put on it. Presentation only, like the cutoffs.
HEADLINE_MIN_ANALYSED_SHARE = 0.5
diff --git a/tests/unit/cli/test_fast_mode_offer.py b/tests/unit/cli/test_fast_mode_offer.py
index 498c03039..612ed789d 100644
--- a/tests/unit/cli/test_fast_mode_offer.py
+++ b/tests/unit/cli/test_fast_mode_offer.py
@@ -42,19 +42,15 @@ def test_should_offer_fast_mode_large_repo():
def test_next_steps_serve_is_the_headline_in_every_mode():
- """`repowise serve` (the dashboard) leads in fast, index-only and full — the
- one place the graph, hotspots, dead code, decisions and wiki all live."""
- for kwargs in (
- {"index_only": True, "fast_mode": True},
- {"index_only": True, "fast_mode": False},
- {"index_only": False},
- ):
+ """`repowise serve` leads in fast and full, glossed as the guided tour."""
+ for kwargs in ({"fast_mode": True}, {}):
steps = build_contextual_next_steps(**kwargs)
assert steps[0][0] == "repowise serve"
+ assert steps[0][1].startswith("a guided tour of all this in your browser\n")
def test_next_steps_fast_mode_second_row_is_full_upgrade():
- steps = build_contextual_next_steps(index_only=True, fast_mode=True)
+ steps = build_contextual_next_steps(fast_mode=True)
cmds = [c for c, _ in steps]
descs = " ".join(d for _, d in steps).lower()
# After serve, fast mode points at the one fast-to-full command, keyless.
@@ -62,15 +58,14 @@ def test_next_steps_fast_mode_second_row_is_full_upgrade():
assert "documentation" in descs and "no key" in descs
-def test_next_steps_index_only_upgrades_via_generate_not_update_full():
- steps = build_contextual_next_steps(index_only=True, fast_mode=False)
- cmds = [c for c, _ in steps]
- assert any(c == "repowise generate" for c in cmds) # the scoped upgrade path
- assert not any("update --full" in c for c in cmds) # never the all-or-nothing path
+def test_next_steps_leave_the_model_command_to_the_model_block():
+ cmds = [c for c, _ in build_contextual_next_steps()]
+ assert not any(c.startswith("repowise generate") for c in cmds)
+ assert not any("update --full" in c for c in cmds)
def test_next_steps_full_mode():
- steps = build_contextual_next_steps(index_only=False)
+ steps = build_contextual_next_steps()
cmds = [c for c, _ in steps]
assert any("search" in c for c in cmds)
@@ -78,12 +73,11 @@ def test_next_steps_full_mode():
def test_next_steps_are_serve_and_at_most_two_more():
"""The panel names the dashboard and at most two moves, never a pile."""
for kwargs in (
- {"index_only": True, "fast_mode": True},
- {"index_only": True, "fast_mode": False},
- {"index_only": False},
- {"index_only": False, "dead_unreachable": 12, "dead_unused": 30},
- {"index_only": False, "hotspot_count": 4, "top_hotspot": "a.py"},
- {"index_only": False, "decision_count": 9},
+ {"fast_mode": True},
+ {},
+ {"dead_unreachable": 12, "dead_unused": 30},
+ {"hotspot_count": 4, "top_hotspot": "a.py"},
+ {"decision_count": 9},
):
steps = build_contextual_next_steps(**kwargs)
assert steps[0][0] == "repowise serve"
@@ -92,20 +86,18 @@ def test_next_steps_are_serve_and_at_most_two_more():
def test_next_steps_findings_rank_below_finishing_the_index():
"""A partial index is a worse problem than an unexplored finding."""
- steps = build_contextual_next_steps(
- index_only=True, fast_mode=False, dead_unreachable=40, decision_count=9
- )
- assert steps[1][0] == "repowise generate"
+ steps = build_contextual_next_steps(fast_mode=True, dead_unreachable=40, decision_count=9)
+ assert steps[1][0] == "repowise update --full"
# With the index complete, the largest finding gets the row.
found = build_contextual_next_steps(
- index_only=False, dead_unreachable=12, dead_unused=30, decision_count=9
+ dead_unreachable=12, dead_unused=30, decision_count=9
)
assert found[1][0] == "repowise dead-code"
def test_next_steps_fall_back_to_search_when_nothing_was_found():
- steps = build_contextual_next_steps(index_only=False)
+ steps = build_contextual_next_steps()
assert steps[1][0].startswith("repowise search")
@@ -113,7 +105,7 @@ def test_next_steps_headless_run_gets_manual_mcp_row():
"""A skipped-setup run (CI/headless) can't auto-wire a client, so the panel
offers the manual connect command naming the real clients."""
setup = EditorSetupOutcome(editor_setup_disabled=True, claude_code_connected=False)
- cmds = [c for c, _ in build_contextual_next_steps(index_only=True, setup=setup)]
+ cmds = [c for c, _ in build_contextual_next_steps(setup=setup)]
assert "repowise mcp ." in cmds
# It outranks the index-only upgrade row: `--no-editor-setup --index-only`
# is the CI shape, and the Connected lines carry no command for a disabled run,
@@ -123,7 +115,7 @@ def test_next_steps_headless_run_gets_manual_mcp_row():
# Fast mode too, for the same reason.
fast = [
c
- for c, _ in build_contextual_next_steps(index_only=True, fast_mode=True, setup=setup)
+ for c, _ in build_contextual_next_steps(fast_mode=True, setup=setup)
]
assert fast[1] == "repowise mcp ."
# A skip-setup run opted out of all wiring, so it is never nagged to install
@@ -132,7 +124,7 @@ def test_next_steps_headless_run_gets_manual_mcp_row():
# A normally-wired run never shows the manual MCP command row.
wired = EditorSetupOutcome(claude_code_connected=True, interactive=True)
- cmds_wired = [c for c, _ in build_contextual_next_steps(index_only=True, setup=wired)]
+ cmds_wired = [c for c, _ in build_contextual_next_steps(setup=wired)]
assert "repowise mcp ." not in cmds_wired
@@ -148,7 +140,7 @@ def test_next_steps_non_interactive_surfaces_missing_hooks():
notes = " ".join(build_status_notes(setup))
assert "repowise hook rewrite install" in notes
# ...and they are notes, not command rows.
- cmds = [c for c, _ in build_contextual_next_steps(index_only=True, setup=setup)]
+ cmds = [c for c, _ in build_contextual_next_steps(setup=setup)]
assert not any(c.startswith("repowise hook") for c in cmds)
# Already installed → not re-suggested.
diff --git a/tests/unit/cli/test_finish_panel.py b/tests/unit/cli/test_finish_panel.py
index dc58e835f..b0bd130a0 100644
--- a/tests/unit/cli/test_finish_panel.py
+++ b/tests/unit/cli/test_finish_panel.py
@@ -12,7 +12,7 @@ from repowise.cli.commands.serve_cmd._web_assets import _NODE_MIN_MAJOR
from repowise.cli.editor_setup import EditorSetupOutcome
from repowise.cli.ui import build_contextual_next_steps
from repowise.cli.ui.brand import THEME
-from repowise.cli.ui.finish_panel import FinishFacts, build_finish_panel
+from repowise.cli.ui.finish_panel import FinishFacts, ModelUpgrade, StoodOut, build_finish_panel
from repowise.cli.ui.mode_names import completion_title, scope_line
from repowise.cli.ui.result_panels import serve_step
@@ -43,15 +43,11 @@ def _render(mode: str, setup=None, files_written=None) -> str:
graph_nodes=400,
graph_edges=900,
elapsed="12.3s",
- dead_unused=4,
- git_files=50,
- hotspots=3,
top_hotspot="serializer.py",
pages=None if mode == "fast" else "42 pages",
spend="$0.12 (40,000 tokens)" if mode == "written_by_model" else None,
)
steps = build_contextual_next_steps(
- index_only=mode != "written_by_model",
fast_mode=mode == "fast",
dead_unused=4,
hotspot_count=3,
@@ -160,11 +156,9 @@ def test_bracketed_file_names_render_literally():
scope = {"content_provenance": "template", "search": {"semantic": "available"}}
facts = FinishFacts(
scope=scope, files=1, symbols=1, languages="TypeScript 100%", graph_nodes=1,
- graph_edges=0, elapsed="1.0s", hotspots=1, top_hotspot="[id].tsx", pages="1 page",
- )
- steps = build_contextual_next_steps(
- index_only=False, hotspot_count=1, top_hotspot="[id].tsx", setup=setup
+ graph_edges=0, elapsed="1.0s", top_hotspot="[id].tsx", pages="1 page",
)
+ steps = build_contextual_next_steps(hotspot_count=1, top_hotspot="[id].tsx", setup=setup)
console = Console(record=True, width=100, theme=THEME)
console.print(
build_finish_panel(
@@ -201,3 +195,122 @@ def test_semantic_search_line_names_who_pays_for_the_embedder(command, tail, abs
assert f"{command} turns it on {tail}" in line
assert absent not in line
+
+
+# -- What stood out and the model block ------------------------------------------
+
+_FOUND = StoodOut(
+ health_score=7.43,
+ health_mark="warning",
+ lowest_file="scheduler/planner.py",
+ lowest_score=3.12,
+ dead_unreachable=38,
+ dead_safe=12,
+ hotspot_file="auth/session.py",
+ hotspot_commits=48,
+ decision_candidates=14,
+)
+
+
+def _panel(stood_out: StoodOut | None = None, model_upgrade=None, mode="built_from_code") -> str:
+ scope = {"search": {"semantic": "available"}, **_SCOPES[mode]}
+ facts = FinishFacts(
+ scope=scope, files=1284, symbols=9812, languages="Python 70%, TypeScript 30%",
+ graph_nodes=1, graph_edges=0, elapsed="1.0s", pages="412 pages",
+ stood_out=stood_out or StoodOut(), model_upgrade=model_upgrade,
+ )
+ console = Console(record=True, width=100, theme=THEME)
+ console.print(build_finish_panel(facts, steps=build_contextual_next_steps()))
+ return console.export_text()
+
+
+def test_stood_out_names_the_four_findings():
+ text = _panel(_FOUND)
+ assert "What stood out" in text
+ assert "7.4/10 Warning scheduler/planner.py is lowest at 3.1" in text
+ assert "38 files nothing reaches, 12 findings safe to delete" in text
+ assert "Hotspot auth/session.py, changed in 48 commits" in text
+ assert "14 candidates to review" in text
+ assert "confirmed" not in text and "decisions found" not in text
+ # The count rows they replace are gone; the rest stay.
+ assert "Git history" not in text and "unused export" not in text
+ assert text.count("Dead code") == 1 and text.count("Decisions") == 1
+ assert "Indexed" in text and "Documentation" in text and "Elapsed" in text
+
+
+ ("score", "word", "style"),
+ [(8.0, "Healthy", "green"), (7.99, "Warning", "yellow"), (3.99, "Alert", "red")],
+)
+def test_health_word_and_colour_follow_the_three_bands(score, word, style):
+ from repowise.core.analysis.health.grading import mark_for
+
+ stood = StoodOut(health_score=score, health_mark=mark_for(score))
+ console = Console(record=True, width=100, theme=THEME, color_system="truecolor")
+ facts = FinishFacts(
+ scope={}, files=1, symbols=1, languages="Python", graph_nodes=1, graph_edges=0,
+ elapsed="1s", stood_out=stood,
+ )
+ console.print(build_finish_panel(facts, steps=[serve_step()]))
+ assert f"/10 {word}" in console.export_text(clear=False)
+ from rich.color import Color
+
+ html = console.export_html(inline_styles=True)
+ assert f"color: {Color.parse(style).get_truecolor().hex}" in html
+
+
+def test_unmeasured_findings_are_left_out():
+ text = _panel(StoodOut(dead_unreachable=0, decision_candidates=1))
+ assert "Health" not in text and "Hotspot" not in text
+ assert "no unreachable files" in text
+ assert "1 candidate to review" in text
+ assert "What stood out" not in _panel(StoodOut())
+
+
+def test_ungraded_health_shows_the_score_without_a_word():
+ text = _panel(StoodOut(health_score=9.0))
+ assert "9.0/10" in text
+ assert "Healthy" not in text
+
+
+ ("upgrade", "line"),
+ [
+ (
+ ModelUpgrade("repowise generate --provider claude_cli", "Uses your Claude Code sign-in"),
+ "Uses your Claude Code sign-in: repowise generate --provider claude_cli",
+ ),
+ (
+ ModelUpgrade("repowise generate --provider openai", "Uses your OpenAI key"),
+ "Uses your OpenAI key: repowise generate --provider openai",
+ ),
+ (
+ ModelUpgrade("repowise generate"),
+ "repowise generate needs a key, or --provider ollama for a local model.",
+ ),
+ ],
+)
+def test_keyless_run_names_what_a_model_adds_and_the_detected_source(upgrade, line):
+ text = _panel(model_upgrade=upgrade)
+ assert "Add a model when you want more" in text
+ assert "Docs that explain how and why, chat in the dashboard," in text
+ assert line in text
+ assert "Or press m next time on the plan screen." in text
+ block = text[text.index("Add a model") : text.index("Try asking")]
+ assert "free" not in block.lower()
+
+
+def test_a_model_run_has_no_model_block():
+ assert "Add a model" not in _panel(_FOUND, mode="written_by_model")
+
+
+def test_new_lines_stay_ascii_for_a_cp1252_console(monkeypatch):
+ from repowise.cli import _stdio
+
+ monkeypatch.setattr(_stdio, "original_stdout_encoding", lambda: "cp1252")
+ text = _panel(_FOUND, ModelUpgrade("repowise generate"))
+ start = text.index("What stood out")
+ block = text[start : text.index("What's next:")]
+ body = "\n".join(line.strip("│ ") for line in block.splitlines())
+ body.encode("ascii")
+ assert "Index ready" in text and "a guided tour of all this in your browser" in text
diff --git a/tests/unit/cli/test_init_agent_mode.py b/tests/unit/cli/test_init_agent_mode.py
index 7b9605d2e..16a529d70 100644
--- a/tests/unit/cli/test_init_agent_mode.py
+++ b/tests/unit/cli/test_init_agent_mode.py
@@ -31,6 +31,7 @@ _SUMMARY_KEYS = {
"warnings",
"files_written",
"next",
+ "findings",
}
_KEYS = (
@@ -183,7 +184,9 @@ def test_a_piped_init_stays_within_the_line_width(repo):
assert "╭" not in result.stdout
-def test_json_init_writes_only_events_and_ends_with_a_ready_summary(repo):
+def test_json_init_writes_only_events_and_ends_with_a_ready_summary(repo, monkeypatch):
+ # No agent CLI probe: the model command is then the same on every machine.
+ monkeypatch.setenv("REPOWISE_OFFLINE", "1")
result = _init(repo, "--no-editor-setup", "--progress", "json")
assert result.exit_code == 0, result.stderr
@@ -195,7 +198,11 @@ def test_json_init_writes_only_events_and_ends_with_a_ready_summary(repo):
assert summary["mode"] == {"key": "template", "label": "Built from code", "run_mode": "standard"}
assert summary["restart_required"] is False
assert summary["spend"] == {"tokens": 0, "usd": 0.0}
- assert summary["next"][0] == "repowise serve"
+ assert summary["next"][:2] == ["repowise serve", "repowise generate"]
+ findings = summary["findings"]
+ assert set(findings) == {"health", "dead_code", "hotspot", "decision_candidates"}
+ assert isinstance(findings["decision_candidates"], int)
+ assert findings["dead_code"]["unreachable_files"] >= 0
# The human screen still happens, on stderr.
assert TITLE_BUILT_FROM_CODE in result.stderr
diff --git a/tests/unit/cli/test_init_finish_findings.py b/tests/unit/cli/test_init_finish_findings.py
new file mode 100644
index 000000000..f1a12f1e2
--- /dev/null
+++ b/tests/unit/cli/test_init_finish_findings.py
@@ -0,0 +1,288 @@
+"""What the init finish panel measured, the model command it names, and the JSON summary."""
+
+from __future__ import annotations
+
+import io
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from rich.console import Console
+from sqlalchemy.exc import OperationalError
+
+from repowise.cli.commands.init_cmd import reporting
+from repowise.cli.commands.init_cmd._agent_summary import run_summary
+from repowise.cli.editor_setup import EditorSetupOutcome
+from repowise.cli.ui.brand import THEME
+from repowise.cli.ui.finish_panel import ModelUpgrade, StoodOut
+from repowise.cli.ui.subscription import CliAuth
+from repowise.core.analysis.dead_code.models import DeadCodeKind
+
+
+def _dead(path: str, safe: bool, kind: DeadCodeKind = DeadCodeKind.UNREACHABLE_FILE):
+ return SimpleNamespace(kind=kind, file_path=path, confidence=0.99, safe_to_delete=safe)
+
+
+def _result(**overrides) -> SimpleNamespace:
+ graph = MagicMock()
+ graph.number_of_nodes.return_value = 10
+ graph.number_of_edges.return_value = 5
+ fields = dict(
+ graph_builder=MagicMock(graph=lambda: graph),
+ dead_code_report=SimpleNamespace(
+ findings=[
+ _dead("src/legacy/old_report.py", True),
+ _dead("src/legacy/old_export.py", False),
+ _dead("src/api.py", True, DeadCodeKind.UNUSED_EXPORT),
+ ]
+ ),
+ decision_report=None,
+ git_summary=SimpleNamespace(files_indexed=3, hotspots=1),
+ git_meta_map={"auth/session.py": {"commit_count": 48}, "a.py": {"commit_count": 2}},
+ health_report=SimpleNamespace(
+ kpis={
+ "average_health": 7.43,
+ "analysed_share": 1.0,
+ "worst_performer_path": "scheduler/planner.py",
+ "worst_performer_score": 3.12,
+ },
+ metrics=[],
+ findings=[],
+ ),
+ repo_structure=SimpleNamespace(root_language_distribution={"Python": 1.0}),
+ generated_pages=[],
+ failed_page_ids=[],
+ file_count=3,
+ symbol_count=42,
+ )
+ return SimpleNamespace(**{**fields, **overrides})
+
+
+def no_probe(monkeypatch):
+ """No agent CLI, no key, and a store that reports 14 candidates."""
+ monkeypatch.setattr(reporting, "_signed_in_agent", lambda: None)
+ monkeypatch.setattr(reporting, "_keyed_provider", lambda _repo: None)
+ monkeypatch.setattr(reporting, "_decision_candidates", lambda _repo: 14)
+
+
+# -- the findings ------------------------------------------------------------------
+
+
+def test_findings_come_from_the_run(no_probe):
+ from repowise.core.analysis.dead_code.serving import is_safe
+
+ result = _result()
+ stood = reporting._stood_out(result, Path("/r"), reporting._top_hotspot(result))
+
+ assert stood.health_score == 7.43
+ assert stood.health_mark == "warning"
+ assert (stood.lowest_file, stood.lowest_score) == ("scheduler/planner.py", 3.12)
+ assert stood.dead_unreachable == 2
+ # A whole file is review-only; the safe count is over every finding.
+ assert stood.dead_safe == sum(1 for f in result.dead_code_report.findings if is_safe(f)) == 1
+ assert (stood.hotspot_file, stood.hotspot_commits) == ("auth/session.py", 48)
+ assert stood.decision_candidates == 14
+
+
+def test_unmeasured_findings_stay_none(no_probe):
+ result = _result(health_report=None, dead_code_report=None, git_meta_map={})
+ stood = reporting._stood_out(result, Path("/r"), reporting._top_hotspot(result))
+ assert stood.health_score is None and stood.dead_unreachable is None
+ assert stood.hotspot_file is None
+
+
+def test_too_little_analysed_keeps_the_score_and_drops_the_word():
+ result = _result(
+ health_report=SimpleNamespace(kpis={"average_health": 9.1, "analysed_share": 0.2})
+ )
+ finding = reporting._health_finding(result)
+ assert finding["health_score"] == 9.1
+ assert finding["health_mark"] is None
+
+
+def test_candidates_are_none_without_a_store(tmp_path):
+ assert reporting._decision_candidates(tmp_path) is None
+
+
+# -- the model command -----------------------------------------------------------
+
+
+def test_a_signed_in_cli_comes_first(monkeypatch, tmp_path):
+ monkeypatch.setattr(
+ "repowise.cli.ui.subscription.logged_in_agent_providers",
+ lambda: {
+ "codex_cli": CliAuth("signed in with ChatGPT", offer=False),
+ "claude_cli": CliAuth("Claude max plan: uses your plan quota"),
+ },
+ )
+ monkeypatch.setattr(reporting, "_keyed_provider", lambda _repo: ("openai", "x"))
+ upgrade = reporting._model_upgrade(tmp_path)
+ assert upgrade == ModelUpgrade(
+ "repowise generate --provider claude_cli", "Uses your Claude Code sign-in"
+ )
+
+
[email protected]("var", ["REPOWISE_OFFLINE", "DO_NOT_TRACK"])
+def test_no_cli_is_probed_with_the_network_off(monkeypatch, tmp_path, var):
+ monkeypatch.setenv(var, "1")
+ monkeypatch.setattr(
+ "repowise.cli.ui.subscription.logged_in_agent_providers",
+ lambda: pytest.fail("probed an agent CLI"),
+ )
+ monkeypatch.setattr(reporting, "_keyed_provider", lambda _repo: None)
+ assert reporting._model_upgrade(tmp_path) == ModelUpgrade("repowise generate")
+
+
+def test_a_key_in_the_repo_env_is_named(monkeypatch, tmp_path):
+ monkeypatch.setattr(reporting, "_signed_in_agent", lambda: None)
+ monkeypatch.setattr(
+ "repowise.core.providers.llm.resolve.credentialed_providers", lambda _repo: ("anthropic",)
+ )
+ upgrade = reporting._model_upgrade(tmp_path)
+ assert upgrade == ModelUpgrade("repowise generate --provider anthropic", "Uses your Anthropic key")
+
+
+def test_nothing_detected_names_the_bare_command(monkeypatch, tmp_path):
+ monkeypatch.setattr(reporting, "_signed_in_agent", lambda: None)
+ monkeypatch.setattr(
+ "repowise.core.providers.llm.resolve.credentialed_providers", lambda _repo: ()
+ )
+ assert reporting._model_upgrade(tmp_path) == ModelUpgrade("repowise generate")
+
+
+# -- show_completion: the panel, the steps and the hint ----------------------------
+
+
+def _complete(monkeypatch, tmp_path, *, index_only: bool, first_index: bool = False):
+ buf = io.StringIO()
+ monkeypatch.setattr(
+ reporting, "console", Console(file=buf, width=120, force_terminal=False, theme=THEME)
+ )
+ hints: list[str] = []
+ monkeypatch.setattr("repowise.cli.hints.maybe_hint", lambda h, **_kw: hints.append(h))
+ completion = reporting.show_completion(
+ repo_path=tmp_path,
+ result=_result(),
+ start=0.0,
+ effective_index_only=index_only,
+ run_mode="standard",
+ provider=None,
+ setup=EditorSetupOutcome(first_index=first_index),
+ )
+ return completion, buf.getvalue(), hints
+
+
+def test_keyless_completion_shows_findings_model_block_and_tour(monkeypatch, tmp_path, no_probe):
+ completion, out, _ = _complete(monkeypatch, tmp_path, index_only=True)
+ assert "What stood out" in out
+ assert "7.4/10 Warning" in out and "14 candidates to review" in out
+ assert "Add a model when you want more" in out
+ assert completion.model_upgrade == ModelUpgrade("repowise generate")
+ assert completion.steps[0][0] == "repowise serve"
+ assert completion.steps[0][1].startswith("a guided tour of all this in your browser")
+ assert not any(c.startswith("repowise generate") for c, _ in completion.steps)
+
+
+def test_model_completion_has_no_model_block(monkeypatch, tmp_path, no_probe):
+ completion, out, _ = _complete(monkeypatch, tmp_path, index_only=False)
+ assert "What stood out" in out
+ assert "Add a model" not in out
+ assert completion.model_upgrade is None
+
+
+def test_first_index_never_shows_the_init_success_hint(monkeypatch, tmp_path, no_probe):
+ assert _complete(monkeypatch, tmp_path, index_only=True, first_index=True)[2] == []
+ assert _complete(monkeypatch, tmp_path, index_only=True)[2] == ["init_success"]
+
+
+def test_completion_hint_rule():
+ assert reporting.completion_hint("standard", 10, first_index=True) is None
+ assert reporting.completion_hint("standard", 10) == "init_success"
+ # Big repos keep their freshness hint either way.
+ assert reporting.completion_hint("standard", 5000, first_index=True) == "large_repo"
+ assert reporting.completion_hint("fast", 10, first_index=True) == "large_repo"
+
+
+# -- --progress json -------------------------------------------------------------------
+
+
+def test_summary_carries_the_findings_and_the_model_command(tmp_path):
+ run = SimpleNamespace(
+ repo_path=tmp_path,
+ setup_outcome=None,
+ mcp_repointed=False,
+ result=_result(),
+ run_warnings=[],
+ files_written=[],
+ next_steps=[("repowise serve", "tour"), ("repowise dead-code", "x")],
+ stood_out=StoodOut(
+ health_score=7.43,
+ health_mark="warning",
+ lowest_file="scheduler/planner.py",
+ lowest_score=3.12,
+ dead_unreachable=38,
+ dead_safe=12,
+ hotspot_file="auth/session.py",
+ hotspot_commits=48,
+ decision_candidates=14,
+ ),
+ model_upgrade=ModelUpgrade("repowise generate --provider claude_cli", "x"),
+ )
+ summary = run_summary(run, [])
+ assert summary["findings"] == {
+ "health": {
+ "score": 7.43,
+ "band": "warning",
+ "lowest_file": "scheduler/planner.py",
+ "lowest_score": 3.12,
+ },
+ "dead_code": {"unreachable_files": 38, "findings_safe_to_delete": 12},
+ "hotspot": {"file": "auth/session.py", "commits": 48},
+ "decision_candidates": 14,
+ }
+ assert summary["next"] == [
+ "repowise serve",
+ "repowise generate --provider claude_cli",
+ "repowise dead-code",
+ ]
+
+
+def test_summary_findings_are_null_when_nothing_was_measured(tmp_path):
+ run = SimpleNamespace(
+ repo_path=tmp_path, setup_outcome=None, mcp_repointed=False, result=_result(),
+ run_warnings=[], files_written=[], next_steps=[], stood_out=StoodOut(), model_upgrade=None,
+ )
+ assert run_summary(run, [])["findings"] == {
+ "health": None, "dead_code": None, "hotspot": None, "decision_candidates": None,
+ }
+
+
+ ("error", "logged_as_bug"),
+ [
+ (OperationalError("SELECT", {}, Exception("no such table")), False),
+ (RuntimeError("a bug in the count"), True),
+ ],
+ ids=["unreadable-store", "unexpected"],
+)
+def test_a_failed_candidate_count_drops_the_row_and_is_null(
+ monkeypatch, tmp_path, error, logged_as_bug
+):
+ async def _raise(_repo):
+ raise error
+
+ monkeypatch.setattr(reporting, "_count_candidates", _raise)
+ monkeypatch.setattr(reporting, "_signed_in_agent", lambda: None)
+ monkeypatch.setattr(reporting, "_keyed_provider", lambda _repo: None)
+ logged: list[str] = []
+ monkeypatch.setattr(reporting.logger, "exception", lambda event, **_kw: logged.append(event))
+
+ completion, out, _ = _complete(monkeypatch, tmp_path, index_only=True)
+
+ assert completion.stood_out.decision_candidates is None
+ assert "candidates to review" not in out and "Decisions" not in out
+ assert completion.stood_out.as_summary()["decision_candidates"] is None
+ # Only an error a store cannot explain is logged as a bug.
+ assert logged == (["decision_candidate_count_failed"] if logged_as_bug else [])
diff --git a/tests/unit/health/test_grading.py b/tests/unit/health/test_grading.py
index 4b2db34e5..d1f1ac78c 100644
--- a/tests/unit/health/test_grading.py
+++ b/tests/unit/health/test_grading.py
@@ -25,6 +25,7 @@ from repowise.core.analysis.health.grading import (
format_score,
headline_band,
headline_scope,
+ mark_for,
)
@@ -195,3 +196,11 @@ def test_headline_scope_only_when_a_minority_was_analysed() -> None:
assert headline_scope(60, 40) is None
assert headline_scope(115, 0) is None
assert headline_scope(0, 0) is None
+
+
+def test_mark_reads_the_canonical_three_bands() -> None:
+ # Mirror of ``healthMark`` in packages/ui: Healthy from 8, Warning from 4.
+ assert mark_for(8.0) == "healthy"
+ assert mark_for(7.99) == "warning"
+ assert mark_for(NEEDS_WORK_MIN) == "warning"
+ assert mark_for(3.99) == "alert"