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): one finish panel that leads with repowise serve (#4248)

Raghav Chamadiya9c8d83a9ba26
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 1fa450521..a91ea8099 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
@@ -446,6 +446,7 @@ def complete_setup(run: InitRun) -> None:
provider=run.provider,
setup=setup_outcome,
files_written=files_written,
+ verbose=opts.verbose,
)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
index a300b2bc7..4f13bd096 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
@@ -17,6 +17,8 @@ from collections import Counter
from pathlib import Path
from typing import Any
+import structlog
+
# The cost-gate helpers moved to ``repowise.cli.cost_gate`` so ``init`` and
# ``generate`` share one gate. Re-exported here for the callers that still
# import them from this module (init's command + workspace flows).
@@ -48,6 +50,8 @@ from repowise.core.generation.models import (
is_stub_fallback,
)
+logger = structlog.get_logger(__name__)
+
__all__ = [
"COST_GATE_USD",
"CostGateDeclined",
@@ -247,7 +251,12 @@ def _enrich_knowledge_graph(
f"{len(enriched.layers)} layers, {len(enriched.tour)} tour steps"
)
except Exception as exc:
- console.print(f" [{WARN}]KG enrichment skipped: {exc}[/]")
+ # Optional enrichment: the reason goes to the log (shown with -v).
+ logger.warning("kg_enrichment_skipped", error=f"{type(exc).__name__}: {exc}")
+ console.print(
+ " [dim]Knowledge graph layers and tour were skipped; "
+ "run with -v to see why.[/dim]"
+ )
def run_repo_generation(
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 8e0e403a2..ac1292c07 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py
@@ -13,24 +13,38 @@ from typing import Any
from repowise.cli.helpers import console, load_config, load_state
from repowise.cli.ui import (
- ERR,
OK,
WARN,
build_contextual_next_steps,
- build_status_notes,
format_elapsed,
- keyless_upgrade_note,
print_completion_panel,
- print_files_written,
)
-from repowise.cli.ui.mode_names import (
- INDEX_ONLY,
- TITLE_WORKSPACE,
- completion_title,
- pages,
- scope_line,
-)
-from repowise.core.index_scope import FAST_TO_FULL_COMMAND, fast_to_full_command
+from repowise.cli.ui.finish_panel import FinishFacts, print_finish_panel
+from repowise.cli.ui.mode_names import TITLE_WORKSPACE, pages
+from repowise.cli.ui.result_panels import serve_step
+from repowise.core.index_scope import fast_to_full_command
+
+
+def _dead_counts(result: Any) -> tuple[int, int]:
+ findings = result.dead_code_report.findings if result.dead_code_report else []
+ kinds = [f.kind.value for f in findings]
+ return kinds.count("unreachable_file"), kinds.count("unused_export")
+
+
+def _lang_summary(result: Any) -> str:
+ dist = result.repo_structure.root_language_distribution
+ if not dist:
+ return ""
+ top = sorted(dist.items(), key=lambda x: -x[1])[:4]
+ summary = ", ".join(f"{lang} {pct:.0%}" for lang, pct in top)
+ if len(dist) > 4:
+ summary += f" +{len(dist) - 4} more"
+ return summary
+
+
+def _hotspots(result: Any) -> int:
+ summary = result.git_summary
+ return summary.hotspots if summary and hasattr(summary, "hotspots") else 0
def _render_defect_accuracy(result: Any) -> None:
@@ -93,223 +107,64 @@ def show_completion(
provider: Any,
setup: Any = None,
files_written: list[Path] | None = None,
+ verbose: bool = False,
) -> list[tuple[str, str]]:
- """Render the final completion panel (index-only or full mode); returns its next steps.
+ """Render the one finish panel and return its next steps; generation checks only under ``-v``.
*setup* is the :class:`~repowise.cli.editor_setup.EditorSetupOutcome`
- snapshot, so the next-step panel and the MCP status note reflect what setup
- actually did. Passed as ``None`` only by callers with nothing to report.
-
- *files_written* is what editor setup put in the working tree, straight from
- the writers. Printed below the panel and dim: it is a receipt, and the run's
- result is the panel above it.
+ snapshot and *files_written* what editor setup put in the working tree,
+ so the panel reports what setup actually did.
"""
- elapsed = time.monotonic() - start
from repowise.core.index_scope import resolve_index_scope
- _scope = resolve_index_scope(load_state(Path(repo_path)), load_config(Path(repo_path)))
-
- # Unavailable also describes a keyless run; only a failed write earns
- # the failure line.
- _embed_failed = getattr(result, "embed_failed_pages", 0)
- _semantic_on = _scope["search"]["semantic"] == "available"
-
- _graph_final = result.graph_builder.graph()
- _dc_unreachable = sum(
- 1
- for f in (result.dead_code_report.findings if result.dead_code_report else [])
- if f.kind.value == "unreachable_file"
+ scope = resolve_index_scope(load_state(Path(repo_path)), load_config(Path(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 ""
+ documentation, spend = (
+ _template_pages(result) if effective_index_only else _model_pages(result)
)
- _dc_unused = sum(
- 1
- for f in (result.dead_code_report.findings if result.dead_code_report else [])
- if f.kind.value == "unused_export"
+ facts = FinishFacts(
+ scope=scope,
+ files=result.file_count,
+ symbols=result.symbol_count,
+ languages=_lang_summary(result) or str(len(getattr(result, "languages", []))),
+ 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),
)
- _n_decisions = sum(result.decision_report.by_source.values()) if result.decision_report else 0
- _hotspot_count_final = (
- result.git_summary.hotspots
- if result.git_summary and hasattr(result.git_summary, "hotspots")
- else 0
+ 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,
+ top_hotspot=top_hotspot,
+ setup=setup,
)
-
- # Find top hotspot file for contextual next steps
- _top_hotspot = ""
- if result.git_meta_map:
- _by_churn = sorted(
- result.git_meta_map.items(),
- key=lambda x: x[1].get("commit_count", 0),
- reverse=True,
- )
- if _by_churn:
- _top_hotspot = _by_churn[0][0]
- # Shorten to basename for display
- if "/" in _top_hotspot:
- _top_hotspot = _top_hotspot.rsplit("/", 1)[-1]
-
- # Build a compact language summary for the completion panel
- _lang_dist_final = result.repo_structure.root_language_distribution
- if _lang_dist_final:
- _top_final = sorted(_lang_dist_final.items(), key=lambda x: -x[1])[:4]
- _lang_summary_final = ", ".join(f"{lang} {pct:.0%}" for lang, pct in _top_final)
- if len(_lang_dist_final) > 4:
- _lang_summary_final += f" +{len(_lang_dist_final) - 4} more"
- else:
- _lang_summary_final = str(len(result.languages))
-
- # What the run found, in both modes: this panel is the one place a run
- # reports file count, symbols, languages and graph size.
- _index_rows: list[tuple[str, str]] = [
- ("Scope", scope_line(_scope)),
- ("Files indexed", f"{result.file_count:,}"),
- ("Symbols", f"{result.symbol_count:,}"),
- ("Languages", _lang_summary_final),
- ]
- if _scope["file_pages"]["eligible"] is not None:
- _fp = _scope["file_pages"]
- _index_rows.append(
- (
- "File pages",
- f"{_fp['generated']}/{_fp['eligible']} generated · {_fp['omitted']} omitted",
- )
- )
- _structure_rows: list[tuple[str, str]] = [
- (
- "Graph",
- f"{_graph_final.number_of_nodes():,} nodes · {_graph_final.number_of_edges():,} edges",
- ),
- ("Dead code", f"{_dc_unreachable} unreachable · {_dc_unused} unused exports"),
- ("Decisions", str(_n_decisions)),
- ]
- if result.git_summary:
- _structure_rows.append(
- (
- "Git history",
- f"{result.git_summary.files_indexed:,} files · {_hotspot_count_final} hotspots",
- )
- )
-
- if effective_index_only:
- _template_pages = len(result.generated_pages or [])
- metrics: list[tuple[str, str]] = [
- *_index_rows,
- (
- "Documentation",
- f"{pages(_template_pages)} built from code" if _template_pages else "none",
- ),
- ("Elapsed", format_elapsed(elapsed)),
- ("", ""),
- *_structure_rows,
- ]
-
- next_steps = build_contextual_next_steps(
- index_only=True,
- fast_mode=(run_mode == "fast"),
- dead_unreachable=_dc_unreachable,
- dead_unused=_dc_unused,
- hotspot_count=_hotspot_count_final,
- decision_count=_n_decisions,
- top_hotspot=_top_hotspot,
- setup=setup,
- )
- console.print()
- print_completion_panel(console, completion_title(_scope), metrics, next_steps)
- console.print()
- # Fast mode reaches this branch too, and it generates nothing, so the
- # note has to check rather than assume.
- if result.generated_pages:
- # Read from the stamped scope, so the note cannot contradict what
- # status and MCP report for the same run.
- if _embed_failed:
- _search_note = "Full-text\n search works now."
- elif _semantic_on:
- _search_note = "Full-text\n and semantic search work now."
- else:
- _search_note = (
- "Full-text\n search works now; semantic search needs an embedder "
- "(Ollama is the keyless one)."
- )
- console.print(
- " [dim]Every page is built from code and says so in its footer. "
- f"{_search_note}[/dim]"
- )
- # A keyless index is finished, not partial — this just names the
- # two upgrades available from here and the command for each, so
- # the headless path (no editor setup, no `generate` row in
- # build_contextual_next_steps) still learns about them (#3105).
- _note = keyless_upgrade_note(_semantic_on, _scope["search"]["next_command"])
- console.print(f" [dim]{_note}[/dim]")
- _print_embed_failure(_embed_failed)
- else:
- console.print(_fast_to_full_note())
- for _line in build_status_notes(setup):
- console.print(_line)
- console.print()
- _render_defect_accuracy(result)
- else:
- _pages = result.generated_pages or []
- _failed_ids = getattr(result, "failed_page_ids", []) or []
- total_tokens = sum(p.total_tokens for p in _pages)
- # Split model-written from the zero-LLM deterministic coverage tail so
- # broad coverage reads as thoroughness, not padding.
- # A stub standing in for a failed provider call is in ``_pages`` like
- # any other page, so counting the list here reported it as generated
- # while the same run reported it as failed one line down.
- from repowise.core.generation.models import count_stub_fallbacks
-
- _stubs = count_stub_fallbacks(_pages)
- _written = len(_pages) - _stubs
- _det = sum(1 for p in _pages if getattr(p, "provider_name", "") == "template")
- _ai = len(_pages) - _det
- _pages_label = pages(_written)
- if _failed_ids:
- _pages_label += f" ({len(_failed_ids):,} failed)"
- elif _det:
- _pages_label += f" ({_ai:,} written by the model · {_det:,} built from code)"
- # The ledger has the real figure; before this the panel reported
- # millions of tokens and no dollars, on a run the user had just
- # approved a dollar estimate for.
- _cost_usd = getattr(result, "llm_cost_usd", None)
- _spend_row = (
- ("Cost", f"${_cost_usd:.2f} [dim]({total_tokens:,} tokens)[/dim]")
- if _cost_usd is not None
- else ("Total tokens", f"{total_tokens:,}")
- )
- metrics = [
- *_index_rows,
- ("Documentation", _pages_label),
- _spend_row,
- ("Provider", f"{provider.provider_name} / {provider.model_name}"),
- ("Elapsed", format_elapsed(elapsed)),
- ("", ""),
- *_structure_rows,
- ]
-
- next_steps = build_contextual_next_steps(
- index_only=False,
- dead_unreachable=_dc_unreachable,
- dead_unused=_dc_unused,
- hotspot_count=_hotspot_count_final,
- decision_count=_n_decisions,
- top_hotspot=_top_hotspot,
- setup=setup,
- )
-
- console.print()
- print_completion_panel(console, completion_title(_scope), metrics, next_steps)
- console.print()
- _print_embed_failure(_embed_failed)
- if not _semantic_on and not _embed_failed and _scope["search"]["next_command"]:
- console.print(
- " [dim]Semantic search is off. Run "
- f"[bold]{_scope['search']['next_command']}[/bold] to turn it on.[/dim]"
- )
- _render_defect_accuracy(result)
- # A concise, dynamic MCP note (who is connected, how others connect)
- # replaces the old wall of manual per-client config: init already wrote
- # the Claude Code / VS Code registrations and repo `.mcp.json`.
- for _line in build_status_notes(setup):
- console.print(_line)
- console.print()
+ console.print()
+ print_finish_panel(
+ console,
+ facts,
+ steps=steps,
+ setup=setup,
+ repo_path=Path(repo_path),
+ files_written=files_written,
+ )
+ console.print()
+ _render_defect_accuracy(result)
# One quiet stderr line about repowise.dev (see hints.py for when it is
# shown); a big repo hears about staying fresh instead.
@@ -317,48 +172,53 @@ def show_completion(
maybe_hint(completion_hint(run_mode, result.file_count))
- print_files_written(console, Path(repo_path), files_written or [])
+ if verbose:
+ _show_generation_checks(result)
+ return steps
- _show_generation_checks(result)
- return next_steps
+def _top_hotspot(result: Any) -> str:
+ """Basename of the most-committed file, for the risk step and the agent 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]
-def _print_embed_failure(failed: int) -> None:
- if failed:
- console.print(
- f" [{WARN}]Semantic search is unavailable:[/] embedding failed for "
- f"{failed} page(s). See the warning above, then run "
- "[bold]repowise reindex[/bold]."
- )
+def _template_pages(result: Any) -> tuple[str | None, None]:
+ count = len(result.generated_pages or [])
+ return (pages(count) if count else None), None
-def _show_generation_checks(result: Any) -> None:
- """Report the generation quality checks on the pages this run wrote.
- ``init`` built no report at all, so the checks ran on a later ``update``
- and never on the first index — which is the run that creates a repository's
- pages, and so the run where duplication first appears.
+def _model_pages(result: Any) -> tuple[str, str]:
+ """Pages and spend for a model run; a stub left by a failed call counts as failed."""
+ from repowise.core.generation.models import count_stub_fallbacks
- Only the checks are shown, not the statistics table: the completion panel
- above already carries the page count, cost and token totals.
- """
+ generated = result.generated_pages or []
+ failed = getattr(result, "failed_page_ids", []) or []
+ written = len(generated) - count_stub_fallbacks(generated)
+ from_code = sum(1 for p in generated if getattr(p, "provider_name", "") == "template")
+ label = pages(written)
+ if failed:
+ label += f" ({len(failed)} failed)"
+ elif from_code:
+ label += f" ({len(generated) - from_code:,} written by the model · "
+ label += f"{from_code:,} built from code)"
+ tokens = sum(p.total_tokens for p in generated)
+ cost = getattr(result, "llm_cost_usd", None)
+ spend = f"${cost:.2f} ({tokens:,} tokens)" if cost is not None else f"{tokens:,} tokens"
+ return label, spend
+
+
+def _show_generation_checks(result: Any) -> None:
+ """The quality checks on the pages this run wrote (``-v`` only)."""
try:
from repowise.core.generation.report import GenerationReport, render_generation_checks
render_generation_checks(GenerationReport.from_pages(result.generated_pages or []), console)
except Exception as exc:
- # A first index that could not check itself must not read like one that
- # checked itself clean. The run still exits 0; the wiki is written.
- console.print(f"[{ERR}]Generation checks did not run:[/] {type(exc).__name__}: {exc}")
-
-
-def _fast_to_full_note() -> str:
- """The closing note of an Index only run, naming the one fast-to-full command."""
- return (
- f" [dim]{INDEX_ONLY}: fast mode indexes the graph and git history, no "
- f"documentation.\n Run [bold]{FAST_TO_FULL_COMMAND}[/bold] to build it from "
- "code (no key needed).[/dim]"
- )
+ # The run still exits 0 and the documentation is written.
+ console.print(f" [dim]Generation checks were skipped ({type(exc).__name__}: {exc}).[/dim]")
def _workspace_next_steps(run_mode: str, keyless: bool) -> list[tuple[str, str]]:
@@ -373,7 +233,7 @@ def _workspace_next_steps(run_mode: str, keyless: bool) -> list[tuple[str, str]]
else:
upgrade = ("repowise search <query>", "search across all indexed repos")
return [
- ("repowise serve", "open the workspace dashboard at http://localhost:3000"),
+ serve_step("workspace dashboard"),
("repowise status --workspace", "show workspace status"),
upgrade,
]
@@ -434,7 +294,7 @@ def show_workspace_completion(
f" [{WARN}]✗[/] {alias:<20} [{WARN}]skipped[/] [dim]({reason})[/dim]"
)
else:
- console.print(f" [{OK}]✓[/] {alias:<20} [{OK}]{count} pages[/]")
+ console.print(f" [{OK}]✓[/] {alias:<20} [{OK}]{pages(count)}[/]")
if docs_skipped:
first = docs_skipped[0][0]
console.print()
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_frontend.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_frontend.py
index 7a088fc7f..3c37daa98 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd/_frontend.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_frontend.py
@@ -25,8 +25,9 @@ def _node_is_usable(node: str | None) -> bool:
min_major = _web_assets._NODE_MIN_MAJOR
if not node:
console.print(
- f"[yellow]Node.js not found — starting API server only.[/yellow]\n"
- f"[dim]To get the web UI, install Node.js {min_major}+ or use Docker:\n"
+ f"[yellow]Node.js not found, starting the API server only.[/yellow]\n"
+ f"[dim]The web UI needs Node.js {min_major}+. Install it and run "
+ "repowise serve again, or use Docker:\n"
f"{_DOCKER_RUN}"
)
return False
@@ -34,9 +35,9 @@ def _node_is_usable(node: str | None) -> bool:
if node_major is None or node_major >= min_major:
return True
console.print(
- f"[yellow]Node.js {node_major} is too old for the bundled web UI "
- f"(requires {min_major}+) — starting API server only.[/yellow]\n"
- f"[dim]Upgrade Node.js to {min_major}+ or use Docker:\n"
+ f"[yellow]Node.js {node_major} is too old for the web UI "
+ f"(needs {min_major}+), starting the API server only.[/yellow]\n"
+ f"[dim]Upgrade Node.js to {min_major}+ and run repowise serve again, or use Docker:\n"
f"{_DOCKER_RUN}"
)
return False
@@ -47,14 +48,14 @@ def _rebuild_stale_local_web(local_web: Path) -> bool:
npm = _web_assets._npm_available()
if not npm:
console.print(
- "[yellow]Local web bundle is stale and npm not found — "
- "falling back to released tarball.[/yellow]"
+ "[yellow]Local web bundle is stale and npm was not found, "
+ "using the released bundle instead.[/yellow]"
)
return False
- console.print("[dim]Local web bundle is older than source — rebuilding...[/dim]")
+ console.print("[dim]Local web bundle is older than its source, rebuilding...[/dim]")
if _web_assets._build_local_web(local_web, npm):
return True
- console.print("[yellow]Local rebuild failed — falling back to released tarball.[/yellow]")
+ console.print("[yellow]Local rebuild failed, using the released bundle instead.[/yellow]")
return False
@@ -83,12 +84,14 @@ def _launch_web_ui(
ready, local_web = _resolve_web_bundle(refresh_ui)
if not ready:
+ # The download or build error is printed just above this line.
console.print(
- "[yellow]Web UI not available — starting API server only.[/yellow]\n"
- "[dim]The web UI will be available in a future release.\n"
- "For now, use Docker for the full experience:[/dim]\n"
- f"[dim] docker build -t repowise https://github.com/{_web_assets._GITHUB_REPO}.git\n"
- " docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise[/dim]"
+ f"[yellow]Could not get the web UI for v{__version__}, "
+ "starting the API server only.[/yellow]\n"
+ "[dim]Check the network and retry with repowise serve --refresh-ui, "
+ "or use Docker:\n"
+ f" docker build -t repowise https://github.com/{_web_assets._GITHUB_REPO}.git\n"
+ f"{_DOCKER_RUN}"
)
return None
@@ -96,7 +99,10 @@ def _launch_web_ui(
if proc:
console.print(f"[green]Web UI starting on http://localhost:{ui_port}[/green]")
else:
- console.print("[yellow]Could not start web UI — running API only.[/yellow]")
+ console.print(
+ "[yellow]Could not start the web UI, running the API server only.[/yellow]\n"
+ "[dim]Retry with repowise serve --refresh-ui to download it again.[/dim]"
+ )
return proc
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_ports.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_ports.py
index 2e255face..573fb3f52 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd/_ports.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_ports.py
@@ -7,6 +7,9 @@ import socket
from repowise.cli.helpers import console
+#: The port `serve` tries first for the web UI; every surface that names it reads this.
+DEFAULT_UI_PORT = 3000
+
def _is_port_free(host: str, port: int) -> bool:
"""Return True if *port* can be bound on *host* right now."""
@@ -36,7 +39,7 @@ def _find_free_port(host: str, preferred: int, label: str, max_attempts: int = 2
break
if _is_port_free(host, candidate):
console.print(
- f"[yellow]Port {preferred} for {label} is in use — using {candidate} instead.[/yellow]"
+ f"[yellow]Port {preferred} for {label} is in use, using {candidate} instead.[/yellow]"
)
return candidate
@@ -44,6 +47,6 @@ def _find_free_port(host: str, preferred: int, label: str, max_attempts: int = 2
sock.bind((host, 0))
candidate = sock.getsockname()[1]
console.print(
- f"[yellow]Port {preferred} for {label} and nearby ports busy — using {candidate}.[/yellow]"
+ f"[yellow]Port {preferred} for {label} and nearby ports are busy, using {candidate}.[/yellow]"
)
return candidate
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/command.py b/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
index 6791165cd..f41b5666e 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
@@ -96,7 +96,12 @@ def _run_api(
@click.option("--port", default=7337, type=int, help="API server port.", envvar="REPOWISE_PORT")
@click.option("--host", default="127.0.0.1", help="Host to bind to.")
@click.option("--workers", default=1, type=int, help="Number of uvicorn workers.")
[email protected]("--ui-port", default=3000, type=int, help="Web UI port.")
+ "--ui-port",
+ default=_ports.DEFAULT_UI_PORT,
+ type=int,
+ help="Web UI port (the next free one if taken).",
+)
@click.option("--no-ui", is_flag=True, help="Start API server only, skip the web UI.")
@click.option(
"--refresh-ui",
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py
index e5304db00..ade03cbbb 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py
@@ -21,6 +21,7 @@ from repowise.cli.ui import (
format_elapsed,
)
from repowise.cli.ui.mode_names import TITLE_INDEX_UPDATED, TITLE_UPDATED_BUILT_FROM_CODE, pages
+from repowise.cli.ui.result_panels import serve_step
# Status -> display color, shared by the changed-file summary.
_STATUS_COLOR = {"added": "green", "deleted": "red", "modified": "yellow", "renamed": "blue"}
@@ -305,7 +306,7 @@ def show_full_completion(
metrics.append(("Elapsed", format_elapsed(elapsed)))
next_steps = [
- ("repowise serve", "browse the updated documentation at localhost:3000"),
+ serve_step("updated documentation"),
("repowise search <query>", "search the documentation"),
]
console.print()
@@ -351,7 +352,7 @@ def show_index_only_completion(
metrics.append(("Elapsed", format_elapsed(elapsed)))
next_steps = [
- ("repowise serve", "browse the index at localhost:3000"),
+ serve_step(),
]
if template_wiki:
# The scoped, cost-gated upgrade path — a coverage, a directory or one
@@ -404,8 +405,8 @@ def show_workspace_completion(
metrics.append(("Elapsed", format_elapsed(elapsed)))
next_steps = [
+ serve_step("workspace dashboard"),
("repowise status --workspace", "show workspace status"),
- ("repowise serve", "browse a repo's documentation at localhost:3000"),
]
console.print()
console.print(
diff --git a/packages/cli/src/repowise/cli/ui/__init__.py b/packages/cli/src/repowise/cli/ui/__init__.py
index 48184fa0e..cc2de1e69 100644
--- a/packages/cli/src/repowise/cli/ui/__init__.py
+++ b/packages/cli/src/repowise/cli/ui/__init__.py
@@ -41,7 +41,7 @@ _LAZY: dict[str, str] = {
"banner_text": "mascot",
"build_completion_panel": "result_panels",
"build_contextual_next_steps": "result_panels",
- "build_status_notes": "result_panels",
+ "build_finish_panel": "finish_panel",
"keyless_upgrade_note": "result_panels",
"format_bytes": "brand",
"format_elapsed": "brand",
@@ -61,7 +61,6 @@ _LAZY: dict[str, str] = {
"model_call_count": "subscription",
"print_banner": "brand",
"print_completion_panel": "result_panels",
- "print_files_written": "result_panels",
"print_index_only_intro": "mode_selection",
"print_phase_header": "brand",
"print_scan_summary": "repo_scanner",
diff --git a/packages/cli/src/repowise/cli/ui/finish_panel.py b/packages/cli/src/repowise/cli/ui/finish_panel.py
new file mode 100644
index 000000000..12a5eee33
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/finish_panel.py
@@ -0,0 +1,272 @@
+"""The one panel ``repowise init`` ends on.
+
+Read top to bottom it answers, in order: what did I get, can my agent reach it,
+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 pathlib import Path
+from typing import Any
+
+from rich.console import RenderableType
+from rich.markup import escape
+from rich.padding import Padding
+from rich.text import Text
+
+from repowise.cli.ui.brand import BRAND, 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 FinishFacts:
+ """What the run produced, already counted; the panel only formats it."""
+
+ scope: Mapping[str, Any]
+ files: int
+ symbols: int
+ languages: str
+ 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
+
+
+def _n(count: int, noun: str) -> str:
+ return f"{count:,} {noun}" if count == 1 else f"{count:,} {noun}s"
+
+
+def _no_pages(scope: Mapping[str, Any]) -> str:
+ return f"none ({INDEX_ONLY})" if mode_label(scope) == INDEX_ONLY else "none"
+
+
+def _search_label(facts: FinishFacts) -> str:
+ if facts.embed_failed:
+ return f"full-text (embedding failed for {_n(facts.embed_failed, 'page')})"
+ if (facts.scope.get("search") or {}).get("semantic") == "available":
+ return "full-text and semantic"
+ return "full-text only"
+
+
+def _metrics(facts: FinishFacts) -> list[tuple[str, str]]:
+ rows = [
+ ("Scope", escape(scope_line(facts.scope))),
+ (
+ "Indexed",
+ f"{_n(facts.files, 'file')} · {_n(facts.symbols, 'symbol')} · {facts.languages}",
+ ),
+ ("Documentation", facts.pages or _no_pages(facts.scope)),
+ ]
+ if facts.spend:
+ rows.append(("Cost", facts.spend))
+ if facts.pages:
+ 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")),
+ ]
+ 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
+
+
+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))
+
+
+def _dim(markup: str) -> Padding:
+ return _line(f"[dim]{markup}[/dim]")
+
+
+def connected_lines(setup: Any) -> list[RenderableType]:
+ """Which agent can reach the index, and the restart it needs to see it.
+
+ Silent without a setup snapshot. A run with editor setup off gets the
+ ``repowise mcp .`` step row instead of a line here.
+ """
+ if setup is None:
+ return []
+ if getattr(setup, "editor_setup_disabled", False):
+ return [key_value_table([("Connected", "no editor (editor setup was skipped)")])]
+
+ lines: list[RenderableType] = []
+ if getattr(setup, "claude_code_connected", False):
+ lines.append(key_value_table([("Connected", "Claude Code")]))
+ # A first index is the run that wrote the MCP entry, so the client
+ # has not loaded it yet.
+ if getattr(setup, "first_index", True):
+ lines.append(
+ _line(
+ f"[bold {BRAND}]Restart Claude Code[/] [bold](or run /mcp) "
+ "to load the repowise tools.[/bold]"
+ )
+ )
+ else:
+ lines.append(
+ _dim("Claude Code stays connected; restart it only if the tools are not showing.")
+ )
+ lines.append(
+ _dim("Cursor or Codex: run [bold]repowise mcp .[/bold] (config in .repowise/mcp.json).")
+ )
+ # The interactive run offered this hook live; a --yes run skipped the offer.
+ if not getattr(setup, "interactive", False) and not getattr(
+ setup, "rewrite_hook_installed", False
+ ):
+ lines.append(
+ _dim("[bold]repowise hook rewrite install[/bold] compresses noisy command output.")
+ )
+ return lines
+
+
+def agent_questions(top_hotspot: str = "") -> list[str]:
+ """Two questions that show off the index on any repo."""
+ second = (
+ f"Why does {top_hotspot} change so often, and what breaks if I edit it?"
+ if top_hotspot
+ else "Which files are riskiest to change, and why?"
+ )
+ return ["How is this repo organised, and where should I start reading?", second]
+
+
+def _ask_lines(top_hotspot: str) -> list[RenderableType]:
+ lines: list[RenderableType] = [Text(""), _line("[bold]Try asking your agent[/bold]")]
+ lines += [_line(f'[dim]"{escape(q)}"[/dim]', indent=4) for q in agent_questions(top_hotspot)]
+ return lines
+
+
+def _relative(repo_path: Path, paths: list[Path]) -> list[str]:
+ out = []
+ for path in paths:
+ try:
+ out.append(path.relative_to(repo_path).as_posix())
+ except ValueError:
+ out.append(str(path))
+ return out
+
+
+def _search_lines(facts: FinishFacts) -> list[RenderableType]:
+ """The command that turns semantic search on, when documentation exists without it."""
+ search = facts.scope.get("search") or {}
+ if facts.embed_failed:
+ return [
+ _line(
+ f"[{WARN}]Semantic search is unavailable:[/] embedding failed for "
+ f"{facts.embed_failed} page(s). See the warning above, then run "
+ "[bold]repowise reindex[/bold]."
+ )
+ ]
+ if not facts.pages or search.get("semantic") == "available":
+ return []
+ command = search.get("next_command") or "repowise reindex"
+ return [
+ _dim(
+ f"Semantic search is off: [bold]{command}[/bold] turns it on "
+ f"({_embed_cost(command)})."
+ )
+ ]
+
+
+#: Display names for hosted embedders; an unlisted one is shown as written.
+_HOSTED_EMBEDDERS = {"openai": "OpenAI", "gemini": "Gemini", "openrouter": "OpenRouter"}
+
+
+def _embed_cost(command: str) -> str:
+ """Who pays for the embedder the command names; Ollama is the keyless option."""
+ args = command.split()
+ name = args[args.index("--embedder") + 1] if "--embedder" in args[:-1] else None
+ if name is None:
+ return "Ollama needs no key"
+ if name == "ollama":
+ return "runs locally with Ollama, no key"
+ return f"uses your {_HOSTED_EMBEDDERS.get(name, name)} key"
+
+
+def _footer(
+ facts: FinishFacts, setup: Any, repo_path: Path, files_written: list[Path]
+) -> list[RenderableType]:
+ lines = _search_lines(facts)
+ if files_written:
+ lines.append(
+ _dim(
+ "Files added: "
+ + escape(", ".join(_relative(repo_path, files_written)))
+ + " (not gitignored; [bold]--no-editor-setup[/bold] skips them)."
+ )
+ )
+ if setup is not None and not getattr(setup, "editor_setup_disabled", False):
+ if getattr(setup, "autosync_hook_installed", False):
+ lines.append(_dim("Auto-sync: on, the index updates after each commit."))
+ else:
+ lines.append(
+ _dim(
+ "Auto-sync: off. [bold]repowise hook install[/bold] keeps the index "
+ "synced on commit."
+ )
+ )
+ return lines
+
+
+def build_finish_panel(
+ facts: FinishFacts,
+ *,
+ steps: list[tuple[str, str]],
+ setup: Any = None,
+ repo_path: Path | None = None,
+ files_written: list[Path] | None = None,
+) -> Any:
+ """The init completion panel: counts, Connected, questions, steps, receipt."""
+ title, metrics, body, footer = _panel_parts(facts, setup, repo_path, files_written)
+ return build_completion_panel(title, metrics, next_steps=steps, body=body, footer=footer)
+
+
+def print_finish_panel(
+ console: Any,
+ facts: FinishFacts,
+ *,
+ steps: list[tuple[str, str]],
+ setup: Any = None,
+ repo_path: Path | None = None,
+ files_written: list[Path] | None = None,
+) -> None:
+ """The finish panel on a terminal; the same rows as plain lines off one."""
+ title, metrics, body, footer = _panel_parts(facts, setup, repo_path, files_written)
+ print_completion_panel(console, title, metrics, steps, body=body, footer=footer)
+
+
+def _panel_parts(
+ facts: FinishFacts,
+ setup: Any,
+ repo_path: Path | None,
+ files_written: list[Path] | None,
+) -> tuple[str, list[tuple[str, str]], list[RenderableType], list[RenderableType]]:
+ body: list[RenderableType] = []
+ connected = connected_lines(setup)
+ if connected:
+ body.append(Text(""))
+ body += connected
+ body += _ask_lines(facts.top_hotspot)
+ footer = _footer(facts, setup, repo_path or Path("."), files_written or [])
+ return escape(completion_title(facts.scope)), _metrics(facts), body, footer
diff --git a/packages/cli/src/repowise/cli/ui/result_panels.py b/packages/cli/src/repowise/cli/ui/result_panels.py
index f24420b0e..926d7bfcd 100644
--- a/packages/cli/src/repowise/cli/ui/result_panels.py
+++ b/packages/cli/src/repowise/cli/ui/result_panels.py
@@ -6,22 +6,18 @@ working tree — and readouts get a section heading and vertical rhythm rather
than a border, because a border means "a discrete object you act on" and none
of them is.
-The completion panel carries **two** commands. It used to carry up to seven,
-assembled from every signal the run produced: the dashboard, the mode's upgrade
-path, a manual MCP row, two hook installs, dead code, the top hotspot, and the
-decision count. Each was individually justified and the pile was not — a list
-of seven next steps does not tell you what to do next, it tells you the program
-knows seven things. So the panel names the dashboard and the one move that most
-needs making, and the states that are not commands moved out to the dim notes
-below it, where they were always supposed to live.
+The completion panel carries at most three commands: the dashboard, then the
+two moves that most need making. A longer list does not tell you what to do
+next, it tells you the program knows many things. States that are not commands
+(a client to restart, a hook that is off) are lines, not rows.
"""
from __future__ import annotations
-from pathlib import Path
from typing import Any
from rich.console import Console, Group
+from rich.markup import escape
from rich.panel import Panel
from rich.text import Text
@@ -34,16 +30,21 @@ def build_completion_panel(
metrics: list[tuple[str, str]],
*,
next_steps: list[tuple[str, str]] | None = None,
+ body: list[Any] | None = None,
+ footer: list[Any] | None = None,
) -> Panel:
"""Build the run's one bordered panel, titled with the happy owl.
- *metrics* is a list of ``(label, value)`` pairs. *next_steps* is at most two
- ``(command, description)`` pairs — see :func:`build_contextual_next_steps`.
+ *metrics* is a list of ``(label, value)`` pairs. *next_steps* is at most
+ three ``(command, description)`` pairs, see :func:`build_contextual_next_steps`.
+ *body* renders between the metrics and the steps, *footer* after the steps.
Both columns are laid out by Rich rather than padded by hand, so a command
longer than the gutter pushes the gutter instead of running into its own
description.
"""
parts: list[Any] = [key_value_table(metrics)]
+ if body:
+ parts.extend(body)
if next_steps:
parts.append(Text(""))
@@ -59,6 +60,10 @@ def build_completion_panel(
)
)
+ if footer:
+ parts.append(Text(""))
+ parts.extend(footer)
+
return Panel(
Group(*parts),
title=f"[bold]{mini(EYES_HAPPY)} {title}[/bold]",
@@ -72,19 +77,50 @@ def print_completion_panel(
title: str,
metrics: list[tuple[str, str]],
next_steps: list[tuple[str, str]] | None = None,
+ *,
+ body: list[Any] | None = None,
+ footer: list[Any] | None = None,
) -> None:
"""The completion panel on a terminal; off one, the same rows as plain lines.
A border in a log or an agent's transcript is only padding to strip.
"""
if console.is_terminal:
- console.print(build_completion_panel(title, metrics, next_steps=next_steps))
+ console.print(
+ build_completion_panel(
+ title, metrics, next_steps=next_steps, body=body, footer=footer
+ )
+ )
return
console.print(f"{mini(EYES_HAPPY)} {title}", highlight=False)
console.print(key_value_table(metrics))
+ for line in body or []:
+ console.print(line)
if next_steps:
console.print(" What's next:")
console.print(key_value_table(list(next_steps), label_width=24))
+ for line in footer or []:
+ console.print(line)
+
+
+def serve_step(target: str = "dashboard") -> 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.
+ """
+ from repowise.cli.commands.serve_cmd._ports import DEFAULT_UI_PORT
+ from repowise.cli.commands.serve_cmd._web_assets import _NODE_MIN_MAJOR
+
+ 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)",
+ )
+
+
+#: Rows after ``repowise serve``.
+_MAX_FOLLOW_UPS = 2
def build_contextual_next_steps(
@@ -98,66 +134,52 @@ def build_contextual_next_steps(
top_hotspot: str = "",
setup: Any = None,
) -> list[tuple[str, str]]:
- """The dashboard, then the single move that most needs making.
+ """The dashboard, then the two moves that most need making.
``repowise serve`` is the headline in every mode: the dashboard is the one
- place the graph, hotspots, dead code, decisions and wiki are all browsable,
- and it is useful before any upgrade.
+ place the graph, hotspots, dead code, decisions and documentation are all
+ browsable, and it is useful before any upgrade.
- The second row is the first of these that applies, in this order, which is
- "what is stopping this index from being used at all" before "what is
+ The follow-ups are the first two of these that apply, in this order, which
+ is "what is stopping this index from being used at all" before "what is
stopping it from being finished" before "what did it find":
- 1. nothing wired an MCP client, so no agent can reach any of this yet;
- 2. the index is deliberately partial (fast, or index-only), so completing it
- beats exploring it;
- 3. otherwise the largest concrete finding, and only a generic search row
- when the run genuinely found nothing to point at.
-
- The MCP row goes **first**, not after the mode rows. A headless index-only
- run is the single most likely way to reach this function — it is what
- ``--no-editor-setup --index-only`` does, which is the flag pair CI uses —
- and with the mode check first, that run was told to go write prose while
- nothing on the screen said how to connect a client to the index it had just
- built. :func:`build_status_notes` stays silent for a disabled run by design,
- so this row is the only place that information exists.
-
- Everything that is a *state* rather than a command — a client that needs a
- restart, a hook that is not installed — is rendered by
- :func:`build_status_notes` below the panel instead.
+ 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);
+ 3. the largest concrete finding, or a search row when there is none.
"""
- steps: list[tuple[str, str]] = [
- ("repowise serve", "open the dashboard at http://localhost:3000"),
- ]
-
+ candidates: list[tuple[str, str]] = []
if setup is not None and getattr(setup, "editor_setup_disabled", False):
- # Headless / CI / --no-editor-setup: nothing was wired, so the tools are
- # unreachable until someone connects a client by hand.
- steps.append(("repowise mcp .", "connect an MCP client (Cursor, Codex, Claude Code)"))
- elif fast_mode:
- # Fast index: graph + essential git, no docs. Point at the full result.
+ candidates.append(("repowise mcp .", "connect an MCP client (Cursor, Codex, Claude Code)"))
+ if fast_mode:
from repowise.core.index_scope import FAST_TO_FULL_COMMAND
- steps.append(
+ 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 path — a coverage, a
- # directory or one page at a time, each behind an estimate — not the
- # all-or-nothing `update --full` this used to suggest.
- steps.append(("repowise generate", "write the documentation with a model (needs a key)"))
- elif dead_unreachable + dead_unused > 0:
- steps.append(
- ("repowise dead-code", f"explore {dead_unreachable + dead_unused} dead code findings")
+ # `generate` is the scoped, cost-gated upgrade: a coverage, a directory
+ # or one page at a time, each behind an estimate.
+ candidates.append(
+ ("repowise generate", "write the documentation with a model (needs a key)")
)
+ dead = dead_unreachable + dead_unused
+ if dead > 0:
+ noun = "finding" if dead == 1 else "findings"
+ candidates.append(("repowise dead-code", f"explore {dead} dead code {noun}"))
elif hotspot_count > 0 and top_hotspot:
- steps.append((f"repowise risk {top_hotspot}", "assess risk for the top hotspot"))
+ candidates.append(
+ (f"repowise risk {escape(top_hotspot)}", "assess risk for the top hotspot")
+ )
elif decision_count > 0:
- steps.append(("repowise decision list", f"browse {decision_count} architectural decisions"))
- else:
- steps.append(('repowise search "<query>"', "search the documentation"))
+ candidates.append(
+ ("repowise decision list", f"browse {decision_count} architectural decisions")
+ )
+ elif not fast_mode:
+ candidates.append(('repowise search "<query>"', "search the documentation"))
- return steps
+ return [serve_step(), *candidates[:_MAX_FOLLOW_UPS]]
def keyless_upgrade_note(semantic_available: bool, reindex_command: str | None = None) -> str:
@@ -181,86 +203,3 @@ def keyless_upgrade_note(semantic_available: bool, reindex_command: str | None =
return f"{prose}."
command = reindex_command or "repowise reindex"
return f"{prose}; {command} adds semantic search."
-
-
-def build_status_notes(setup: Any) -> list[str]:
- """Rich-markup notes about MCP and hook wiring, shown beside the panel.
-
- Separate from the command rows because "already connected, restart it" is a
- state, not something to run — and because a note can say a thing is missing
- without implying the user must act on it now.
-
- A run that opted out of editor wiring entirely gets nothing: it asked for
- that, and the ``repowise mcp .`` command row already carries the one case
- where it matters.
- """
- if setup is None or getattr(setup, "editor_setup_disabled", False):
- return []
-
- notes: list[str] = []
- if getattr(setup, "claude_code_connected", False):
- if getattr(setup, "first_index", True):
- notes.append(
- " [dim]Claude Code is connected to this repo. Restart it (or run "
- "[bold]/mcp[/bold]) to load the repowise tools.[/dim]"
- )
- else:
- notes.append(
- " [dim]Claude Code stays connected; restart it only if the tools "
- "aren't showing.[/dim]"
- )
- # Cursor and Codex are not auto-wired (init writes the Claude/VS Code configs
- # and repo `.mcp.json`, not `.cursor/mcp.json`), so always point the way.
- notes.append(
- " [dim]Cursor or Codex: run [bold]repowise mcp .[/bold] "
- "(config in [bold].repowise/mcp.json[/bold]).[/dim]"
- )
-
- # Hooks the interactive offers would have covered live. Surfaced only for a
- # non-interactive run, where those offers were skipped in silence. These
- # used to be command rows in the panel, which gave a thing nobody asked for
- # the same weight as the dashboard.
- if not getattr(setup, "interactive", False):
- missing = []
- if not getattr(setup, "autosync_hook_installed", False):
- missing.append("[bold]repowise hook install[/bold] keeps the index synced on commit")
- if not getattr(setup, "rewrite_hook_installed", False):
- missing.append(
- "[bold]repowise hook rewrite install[/bold] compresses noisy command output"
- )
- notes.extend(f" [dim]{line}.[/dim]" for line in missing)
-
- return notes
-
-
-def print_files_written(console: Console, repo_path: Path, paths: list[Path]) -> None:
- """List what init wrote into the working tree, below the panel and dim.
-
- Init writes editor and MCP config outside ``.repowise/`` — ``.mcp.json``,
- ``.claude/CLAUDE.md``, the two ``.vscode`` files — and until this existed it
- named none of them at the end of a run. The only trace was a green tick per
- file, printed minutes earlier and scrolled away, so the first time most
- people saw the list was in ``git status``.
-
- Deliberately the quietest thing on the screen: it is a receipt, not a
- result, and the reader who does not care should be able to skip it in one
- glance. It is also the reason the note names ``--no-editor-setup`` — that
- flag now genuinely writes none of this, so the sentence has somewhere to
- send anyone who does not want the files.
- """
- if not paths:
- return
-
- relative: list[str] = []
- for path in paths:
- try:
- relative.append(path.relative_to(repo_path).as_posix())
- except ValueError:
- relative.append(str(path))
-
- console.print()
- console.print(" [dim]Written to your repo (not gitignored): " + ", ".join(relative) + "[/dim]")
- console.print(
- " [dim]These wire your editor to the index. "
- "[bold]repowise init --no-editor-setup[/bold] skips them.[/dim]"
- )
diff --git a/tests/unit/cli/test_embed_failure_reporting.py b/tests/unit/cli/test_embed_failure_reporting.py
index 9c0bf3de3..d2c1edc07 100644
--- a/tests/unit/cli/test_embed_failure_reporting.py
+++ b/tests/unit/cli/test_embed_failure_reporting.py
@@ -157,10 +157,6 @@ def _closing_card(tmp_path: Path, monkeypatch, *, semantic: str, failed: int) ->
"repowise.cli.commands.init_cmd.reporting.console",
Console(file=buf, width=200, force_terminal=False),
)
- monkeypatch.setattr(
- "repowise.cli.commands.init_cmd.reporting.print_completion_panel",
- lambda console, title, metrics, next_steps=None: console.print("PANEL"),
- )
graph = MagicMock()
graph.number_of_nodes.return_value = 1
graph.number_of_edges.return_value = 0
@@ -195,13 +191,13 @@ def test_card_names_a_failed_embed(tmp_path, monkeypatch):
def test_card_does_not_ask_for_an_embedder_the_run_used(tmp_path, monkeypatch):
out = _closing_card(tmp_path, monkeypatch, semantic="available", failed=0)
- assert "and semantic search work now" in out
- assert "needs an embedder" not in out
+ assert "full-text and semantic" in out
+ assert "Semantic search is off" not in out
def test_card_keeps_the_keyless_note(tmp_path, monkeypatch):
out = _closing_card(tmp_path, monkeypatch, semantic="unavailable", failed=0)
- assert "semantic search needs an embedder" in out
+ assert "Semantic search is off: repowise reindex turns it on" in out
assert "Semantic search is unavailable" not in out
diff --git a/tests/unit/cli/test_fast_mode_offer.py b/tests/unit/cli/test_fast_mode_offer.py
index f7ac50e39..54aa70386 100644
--- a/tests/unit/cli/test_fast_mode_offer.py
+++ b/tests/unit/cli/test_fast_mode_offer.py
@@ -7,10 +7,20 @@ from repowise.cli.ui import (
LARGE_REPO_FILE_THRESHOLD,
RepoScanInfo,
build_contextual_next_steps,
- build_status_notes,
keyless_upgrade_note,
should_offer_fast_mode,
)
+from repowise.cli.ui.finish_panel import connected_lines
+
+
+def build_status_notes(setup) -> list[str]:
+ """The Connected lines as plain text."""
+ from rich.console import Console
+
+ console = Console(width=200, record=True)
+ for line in connected_lines(setup):
+ console.print(line)
+ return [line for line in console.export_text().splitlines() if line.strip()]
def test_should_offer_fast_mode_none():
@@ -64,13 +74,8 @@ def test_next_steps_full_mode():
assert any("search" in c for c in cmds)
-def test_next_steps_are_exactly_two_rows():
- """The panel names the dashboard and one move, never a pile.
-
- It used to assemble up to seven rows from every signal the run produced.
- Each was individually justified and the list was not: seven next steps do
- not tell you what to do next, they tell you the program knows seven things.
- """
+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},
@@ -79,7 +84,9 @@ def test_next_steps_are_exactly_two_rows():
{"index_only": False, "hotspot_count": 4, "top_hotspot": "a.py"},
{"index_only": False, "decision_count": 9},
):
- assert len(build_contextual_next_steps(**kwargs)) == 2
+ steps = build_contextual_next_steps(**kwargs)
+ assert steps[0][0] == "repowise serve"
+ assert 2 <= len(steps) <= 3
def test_next_steps_findings_rank_below_finishing_the_index():
@@ -108,7 +115,7 @@ def test_next_steps_headless_run_gets_manual_mcp_row():
cmds = [c for c, _ in build_contextual_next_steps(index_only=True, setup=setup)]
assert "repowise mcp ." in cmds
# It outranks the index-only upgrade row: `--no-editor-setup --index-only`
- # is the CI shape, and `build_status_notes` is silent for a disabled run,
+ # is the CI shape, and the Connected lines carry no command for a disabled run,
# so this row is the only place the connect instructions exist.
assert cmds[1] == "repowise mcp ."
@@ -138,10 +145,10 @@ def test_next_steps_non_interactive_surfaces_missing_hooks():
claude_code_connected=True,
)
notes = " ".join(build_status_notes(setup))
- assert "repowise hook install" in notes
assert "repowise hook rewrite install" in notes
- # ...and they are notes, not command rows: the panel stays at two.
- assert len(build_contextual_next_steps(index_only=True, setup=setup)) == 2
+ # ...and they are notes, not command rows.
+ cmds = [c for c, _ in build_contextual_next_steps(index_only=True, setup=setup)]
+ assert not any(c.startswith("repowise hook") for c in cmds)
# Already installed → not re-suggested.
setup_installed = EditorSetupOutcome(
@@ -176,9 +183,11 @@ def test_mcp_status_lines_restart_note_only_on_first_index():
assert "stays connected" in rerun_text
-def test_mcp_status_lines_empty_when_headless_or_absent():
+def test_mcp_status_lines_empty_when_absent_and_say_skipped_when_headless():
assert build_status_notes(None) == []
- assert build_status_notes(EditorSetupOutcome(editor_setup_disabled=True)) == []
+ headless = " ".join(build_status_notes(EditorSetupOutcome(editor_setup_disabled=True)))
+ assert "editor setup was skipped" in headless
+ assert "restart" not in headless.lower()
def test_next_steps_render_without_truncation_or_collision():
diff --git a/tests/unit/cli/test_finish_panel.py b/tests/unit/cli/test_finish_panel.py
new file mode 100644
index 000000000..4d44ed1b9
--- /dev/null
+++ b/tests/unit/cli/test_finish_panel.py
@@ -0,0 +1,202 @@
+"""The init finish panel: serve first in every mode, with the real port and Node note."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from rich.console import Console
+
+from repowise.cli.commands.serve_cmd._ports import DEFAULT_UI_PORT
+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.finish_panel import FinishFacts, build_finish_panel
+from repowise.cli.ui.mode_names import completion_title, scope_line
+from repowise.cli.ui.result_panels import serve_step
+
+_SCOPES = {
+ "fast": {"run_mode": "fast", "content_provenance": "none", "git_tier": "essential"},
+ "built_from_code": {"content_provenance": "template", "git_tier": "full"},
+ "written_by_model": {
+ "content_provenance": "model",
+ "git_tier": "full",
+ "git_commit_cap": 500,
+ "provider": {"model": "gemini-2.5-flash"},
+ "search": {"semantic": "available"},
+ },
+}
+
+
+def _render(mode: str, setup=None, files_written=None) -> str:
+ scope = {
+ "search": {"semantic": "unavailable", "next_command": "repowise reindex"},
+ "provider": {},
+ **_SCOPES[mode],
+ }
+ facts = FinishFacts(
+ scope=scope,
+ files=50,
+ symbols=312,
+ languages="Python 100%",
+ 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,
+ top_hotspot="serializer.py",
+ setup=setup,
+ )
+ console = Console(record=True, width=100)
+ console.print(
+ build_finish_panel(
+ facts, steps=steps, setup=setup, repo_path=Path("/r"), files_written=files_written
+ )
+ )
+ return console.export_text()
+
+
+def _step_commands(text: str) -> list[str]:
+ after = text.split("What's next:", 1)[1]
+ rows = [line.strip("│ ").split(" ")[0] for line in after.splitlines()]
+ return [row for row in rows if row.startswith("repowise ")]
+
+
[email protected]("mode", list(_SCOPES))
+ "setup",
+ [
+ None,
+ EditorSetupOutcome(editor_setup_disabled=True),
+ EditorSetupOutcome(claude_code_connected=True, first_index=True),
+ ],
+ ids=["no-setup", "headless", "connected"],
+)
+def test_serve_leads_with_port_and_node_note_then_at_most_two_steps(mode, setup):
+ text = _render(mode, setup)
+ commands = _step_commands(text)
+
+ assert commands[0] == "repowise serve"
+ assert 1 <= len(commands) - 1 <= 2
+ assert f"http://localhost:{DEFAULT_UI_PORT} or the next free port" in text
+ assert f"needs Node {_NODE_MIN_MAJOR}+; the first run downloads the UI" in text
+ assert "—" not in text
+
+
+def test_serve_step_reads_the_port_serve_tries_first():
+ from repowise.cli.commands.serve_cmd.command import serve_command
+
+ ui_port = next(p for p in serve_command.params if p.name == "ui_port")
+ assert ui_port.default == DEFAULT_UI_PORT
+ assert f"localhost:{DEFAULT_UI_PORT}" in serve_step()[1]
+
+
+ ("mode", "title"),
+ [
+ ("fast", "Index only ready"),
+ ("built_from_code", "Index ready, documentation built from code"),
+ ("written_by_model", "Repowise is ready"),
+ ],
+)
+def test_title_and_scope_use_the_design_vocabulary(mode, title):
+ text = _render(mode)
+ assert title in text
+ assert "wiki" not in text.lower()
+
+
+def test_title_and_scope_line_come_from_the_naming_table():
+ text = _render("written_by_model")
+ scope = {**_SCOPES["written_by_model"]}
+ assert scope_line(scope) in text
+ assert completion_title(scope) in text
+ assert "Written by gemini-2.5-flash" in text
+
+
+def test_restart_claude_code_is_inside_the_panel_on_a_first_index():
+ text = _render("built_from_code", EditorSetupOutcome(claude_code_connected=True))
+ panel_lines = [line for line in text.splitlines() if line.startswith("│")]
+ assert any("Restart Claude Code" in line for line in panel_lines)
+ assert any("Claude Code" in line and "Connected" in line for line in panel_lines)
+
+
+def test_rerun_does_not_shout_restart():
+ setup = EditorSetupOutcome(claude_code_connected=True, first_index=False)
+ text = _render("built_from_code", setup)
+ assert "Restart Claude Code" not in text
+ assert "stays connected" in text
+
+
+def test_panel_names_example_questions_files_and_auto_sync():
+ setup = EditorSetupOutcome(claude_code_connected=True, autosync_hook_installed=True)
+ text = _render("built_from_code", setup, [Path("/r/.mcp.json")])
+ assert "Try asking your agent" in text
+ assert "serializer.py" in text
+ assert "Files added: .mcp.json" in text
+ assert "Auto-sync: on" in text
+
+
+def test_semantic_search_line_only_when_off():
+ assert "Semantic search is off: repowise reindex turns it on" in _render("built_from_code")
+ assert "Semantic search is off" not in _render("written_by_model")
+ assert "Semantic search is off" not in _render("fast")
+
+
+
+
+def test_bracketed_file_names_render_literally():
+ setup = EditorSetupOutcome(claude_code_connected=True)
+ 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
+ )
+ console = Console(record=True, width=100)
+ console.print(
+ build_finish_panel(
+ facts, steps=steps, setup=setup, repo_path=Path("/r"),
+ files_written=[Path("/r/app/[slug]/page.md")],
+ )
+ )
+ text = console.export_text()
+ assert 'Why does [id].tsx change' in text
+ assert "repowise risk [id].tsx" in text
+ assert "app/[slug]/page.md" in text
+
+
+ ("command", "tail", "absent"),
+ [
+ ("repowise reindex --embedder openai", "(uses your OpenAI key)", "Ollama"),
+ ("repowise reindex --embedder ollama", "(runs locally with Ollama, no key)", "your"),
+ ("repowise reindex", "(Ollama needs no key)", "your"),
+ ],
+)
+def test_semantic_search_line_names_who_pays_for_the_embedder(command, tail, absent):
+ scope = {
+ "content_provenance": "template",
+ "search": {"semantic": "unavailable", "next_command": command},
+ }
+ facts = FinishFacts(
+ scope=scope, files=1, symbols=1, languages="Python 100%", graph_nodes=1,
+ graph_edges=0, elapsed="1.0s", pages="1 page",
+ )
+ console = Console(record=True, width=120)
+ console.print(build_finish_panel(facts, steps=[serve_step()]))
+ line = next(x for x in console.export_text().splitlines() if "Semantic search is off" in x)
+ assert f"{command} turns it on {tail}" in line
+ assert absent not in line
+
diff --git a/tests/unit/cli/test_init_failure_reporting.py b/tests/unit/cli/test_init_failure_reporting.py
index 730e484bc..4edbb61c2 100644
--- a/tests/unit/cli/test_init_failure_reporting.py
+++ b/tests/unit/cli/test_init_failure_reporting.py
@@ -243,11 +243,11 @@ def test_show_completion_panel_with_failures(monkeypatch):
"""show_completion reflects failed count in metric line when failures exist."""
printed_panels = []
- def mock_completion_panel(console, title, metrics, next_steps=None):
+ def mock_completion_panel(console, title, metrics, next_steps=None, **_kw):
printed_panels.append(metrics)
monkeypatch.setattr(
- "repowise.cli.commands.init_cmd.reporting.print_completion_panel", mock_completion_panel
+ "repowise.cli.ui.finish_panel.print_completion_panel", mock_completion_panel
)
monkeypatch.setattr(
"repowise.cli.commands.init_cmd.reporting.console.print", lambda *a, **kw: None
@@ -309,14 +309,9 @@ _CHECK_ROWS = ("Orientation overlap", "Layer grouping", "Artifact checks", "Over
class TestInitRendersGenerationChecks:
- """`init` writes a repository's first pages, so it must report on them.
+ """The generation checks are a -v readout; the default finish is one panel."""
- It never built a GenerationReport at all: the checks ran only on a later
- `update`. The first index is where duplication is created, and it was the
- one run that said nothing about it.
- """
-
- def _output(self, monkeypatch, *, index_only: bool) -> str:
+ def _output(self, monkeypatch, *, index_only: bool, verbose: bool = True) -> str:
import io
from rich.console import Console
@@ -326,10 +321,6 @@ class TestInitRendersGenerationChecks:
"repowise.cli.commands.init_cmd.reporting.console",
Console(file=buf, width=200, force_terminal=False),
)
- monkeypatch.setattr(
- "repowise.cli.commands.init_cmd.reporting.print_completion_panel",
- lambda console, title, metrics, next_steps=None: console.print("PANEL"),
- )
show_completion(
repo_path="/fake",
result=_completion_result([_page("file_page:a")]),
@@ -337,28 +328,40 @@ class TestInitRendersGenerationChecks:
effective_index_only=index_only,
run_mode="standard",
provider=SimpleNamespace(provider_name="mock", model_name="mock-model"),
+ verbose=verbose,
)
return buf.getvalue()
@pytest.mark.parametrize("index_only", [False, True])
- def test_checks_render_after_completion(self, monkeypatch, index_only):
+ def test_checks_render_under_verbose(self, monkeypatch, index_only):
output = self._output(monkeypatch, index_only=index_only)
for row in _CHECK_ROWS:
- assert row in output, f"{row} missing from init's completion output"
+ assert row in output, f"{row} missing from init -v output"
+
+ @pytest.mark.parametrize("index_only", [False, True])
+ def test_default_finish_has_no_checks_table(self, monkeypatch, index_only):
+ output = self._output(monkeypatch, index_only=index_only, verbose=False)
+
+ assert "Generation Checks" not in output
+ for row in _CHECK_ROWS:
+ assert row not in output
- def test_check_failure_is_loud_and_names_the_cause(self, monkeypatch):
- """A failed check block must not read as a clean first index."""
+ def test_check_failure_is_calm_and_only_under_verbose(self, monkeypatch):
+ """A check that could not run is not an error on an exit-0 run."""
def _boom(*_args, **_kwargs):
raise RuntimeError("overlap exploded")
monkeypatch.setattr("repowise.core.generation.report.GenerationReport.from_pages", _boom)
- output = self._output(monkeypatch, index_only=False)
+ verbose = self._output(monkeypatch, index_only=False)
+ assert "Generation checks were skipped" in verbose
+ assert "overlap exploded" in verbose
+ assert "did not run" not in verbose
- assert "overlap exploded" in output
- assert "RuntimeError" in output
- assert "checks did not run" in output
+ default = self._output(monkeypatch, index_only=False, verbose=False)
+ assert "overlap exploded" not in default
+ assert "Generation checks" not in default
def _stub_page(page_id: str) -> GeneratedPage:
@@ -467,8 +470,8 @@ def test_completion_panel_excludes_placeholders_from_the_page_count(monkeypatch)
"""The panel derives the same split from the same helper, not its own count."""
printed_panels = []
monkeypatch.setattr(
- "repowise.cli.commands.init_cmd.reporting.print_completion_panel",
- lambda console, title, metrics, next_steps=None: printed_panels.append(metrics),
+ "repowise.cli.ui.finish_panel.print_completion_panel",
+ lambda console, title, metrics, next_steps=None, **_kw: printed_panels.append(metrics),
)
monkeypatch.setattr(
"repowise.cli.commands.init_cmd.reporting.console.print", lambda *a, **kw: None
@@ -563,10 +566,6 @@ class TestInitClosingKeylessNote:
"repowise.cli.commands.init_cmd.reporting.console",
Console(file=buf, width=200, force_terminal=False),
)
- monkeypatch.setattr(
- "repowise.cli.commands.init_cmd.reporting.print_completion_panel",
- lambda console, title, metrics, next_steps=None: console.print("PANEL"),
- )
monkeypatch.setattr(
"repowise.cli.commands.init_cmd.reporting.load_state",
lambda _p: state if state is not None else {"docs_mode": "deterministic"},
@@ -601,9 +600,9 @@ class TestInitClosingKeylessNote:
)
def test_note_prints_with_and_without_editor_setup(self, monkeypatch, setup):
out = self._output(monkeypatch, setup=setup, pages=[_page("file_page:a")])
- assert "repowise generate writes the subsystem pages" in out
- assert "--provider ollama" in out
- assert "repowise reindex adds semantic search" in out
+ # Once, as a step row: the duplicate closing sentence is gone.
+ assert out.count("repowise generate") == 1
+ assert "Semantic search is off: repowise reindex turns it on" in out
assert "--embedder ..." not in out
def test_note_drops_the_search_half_when_semantic_search_is_available(self, monkeypatch):
@@ -615,9 +614,10 @@ class TestInitClosingKeylessNote:
},
}
out = self._output(monkeypatch, setup=None, pages=[_page("file_page:a")], state=state)
- assert "repowise generate writes the subsystem pages" in out
+ assert "repowise generate" in out
assert "reindex" not in out
- def test_no_note_when_fast_mode_rendered_no_pages(self, monkeypatch):
+ def test_no_search_line_when_no_documentation_was_built(self, monkeypatch):
out = self._output(monkeypatch, setup=None, pages=[])
- assert "repowise generate" not in out
+ assert "Semantic search" not in out
+ assert "Documentation" in out and "none" in out
diff --git a/tests/unit/cli/test_serve_paths.py b/tests/unit/cli/test_serve_paths.py
index 70d10c08d..80f311773 100644
--- a/tests/unit/cli/test_serve_paths.py
+++ b/tests/unit/cli/test_serve_paths.py
@@ -747,7 +747,9 @@ def test_serve_refresh_ui_skips_local_and_cache(serve) -> None:
def test_serve_no_assets_runs_api_only(serve) -> None:
result = _invoke()
- assert "not available" in result.output
+ assert "Could not get the web UI" in result.output
+ assert "repowise serve --refresh-ui" in result.output
+ assert "future release" not in result.output
names = _names(serve["events"])
assert names[4:] == ["find_local", "cached", "download", "uvicorn"]
assert serve["lock"]["ui_port"] is None
@@ -757,7 +759,7 @@ def test_serve_frontend_that_fails_to_start(serve) -> None:
serve["cached"] = True
serve["proc"] = False
result = _invoke()
- assert "Could not start web UI" in result.output
+ assert "Could not start the web UI" in result.output
assert serve["lock"]["ui_port"] is None
assert "terminate" not in _names(serve["events"])
diff --git a/tests/unit/cli/test_ui_package.py b/tests/unit/cli/test_ui_package.py
index 363e4999a..dd4065c4c 100644
--- a/tests/unit/cli/test_ui_package.py
+++ b/tests/unit/cli/test_ui_package.py
@@ -40,7 +40,6 @@ def test_facade_reexports_public_surface() -> None:
"quick_repo_scan",
"build_completion_panel",
"build_contextual_next_steps",
- "build_status_notes",
"format_bytes",
"format_elapsed",
"LARGE_REPO_FILE_THRESHOLD",