Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(init): first-run UX pass over the interactive init flow (#1139)
Raghav Chamadiyaa5bc267bc5cb
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.pyindex c65e9fbe9..8169ef074 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py@@ -72,7 +72,7 @@ def offer_distill_rewrite_hook(returnconsole_obj.print()console_obj.print(- "[bold]Distill:[/bold] rewrite noisy agent commands (tests, builds, "+ "[bold]Distill:[/bold] Rewrite noisy agent commands (tests, builds, ""git, searches) to `repowise distill ...` for compact output?")scope = f"Applies to all {len(repo_paths)} selected repos. " if len(repo_paths) > 1 else ""diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex c6539626a..8234313c5 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -79,6 +79,7 @@ from .generation import (cost_gate_declined,estimate_generation,format_cost,+ page_type_label,run_repo_generation,structural_page_summary,)@@ -265,6 +266,7 @@ def _run_generation_phase(user declined the cost gate (generation skipped, index still saved). Mutates``result`` in place with the generated pages, vector store, and enriched KG."""+ from repowise.core.cost_estimator import STRUCTURAL_PAGE_TYPESfrom repowise.core.generation import GenerationConfigprint_phase_header(@@ -294,14 +296,28 @@ def _run_generation_phase(skip_infra=skip_infra,)+ # "Written by" replaces the old Level column (an internal generation-tier+ # integer nobody could act on) and answers the question the price below+ # raises: most of this total is free.table = Table(title="Generation Plan", border_style=BRAND)- table.add_column("Page Type", style="cyan")+ table.add_column("Pages", style="cyan")table.add_column("Count", justify="right")- table.add_column("Level", justify="right")+ table.add_column("Written by")+ model_pages = 0for plan in est.plans:- table.add_row(plan.page_type, str(plan.count), str(plan.level))+ from_model = plan.page_type not in STRUCTURAL_PAGE_TYPES+ model_pages += plan.count if from_model else 0+ table.add_row(+ page_type_label(plan.page_type),+ f"{plan.count:,}",+ "model" if from_model else "[dim]structure[/dim]",+ )table.add_section()- table.add_row("[bold]Total[/bold]", f"[bold]{est.total_pages}[/bold]", "")+ table.add_row(+ "[bold]Total[/bold]",+ f"[bold]{est.total_pages:,}[/bold]",+ f"[bold]{model_pages:,} by model, {est.total_pages - model_pages:,} from structure[/bold]",+ )console.print(table)# Language breakdown@@ -320,19 +336,18 @@ def _run_generation_phase()if onboarding:+ # Eight proper nouns in a wrapped dim block sat directly above the+ # price and competed with it; none of them is actionable here.console.print(- " [cyan]Onboarding collection:[/cyan] "- "[dim]up to 8 curated pages — Project Overview, Architecture Guide, "- "Getting Started, Codebase Map, Key Concepts, How It Works, "- "Development Guide, Active Landscape "- "(slots without enough signal are skipped).[/dim]"+ " [dim]Plus up to 8 curated onboarding pages (overview, architecture, "+ "getting started, and so on). Slots without enough signal are skipped.[/dim]")else:console.print(" [dim]Onboarding collection: disabled (--no-onboarding).[/dim]")console.print()if dry_run:- console.print("[yellow]Dry run — no pages generated.[/yellow]")+ console.print(" Dry run: no pages generated.")return True, False# The single cost question. Every structural page is free; the spend is the@@ -346,18 +361,19 @@ def _run_generation_phase(# already exists and re-running with --yes costs nothing.concept_n = concept_page_count(plans)console.print(- f"Writing [bold]{concept_n}[/bold] concept pages with "+ f" Writing [bold]{concept_n:,}[/bold] subsystem pages with "f"[cyan]{provider.model_name}[/cyan]. Estimated [bold]{format_cost(est)}[/bold].")structural = structural_page_summary(plans)if structural:- console.print(f"[dim]{structural}[/dim]")+ console.print(f" [dim]{structural}[/dim]")if cost_gate_declined(est, yes=yes, message=" Continue?"):+ console.print(" Skipping the model. [dim]Building the wiki from structure instead.[/dim]")console.print(- "[yellow]Not writing it with the model.[/yellow] "- "[dim]Re-run with --yes to accept the cost, or run `repowise generate` "- "later to write the subsystem pages. Future `repowise update` runs stay "- "index-only, so the post-commit hook won't start a model run on its own.[/dim]"+ " [dim]Run [bold]repowise generate[/bold] any time to write the subsystem "+ "pages, or re-run init with [bold]--yes[/bold] to accept the cost now.\n"+ " Post-commit updates stay index-only, so no hook will start a model run "+ "on its own.[/dim]")return False, True@@ -1121,9 +1137,7 @@ def init_command(print_index_only_intro(console, has_provider=has_provider)else:console.print(f"[bold]repowise index-only[/bold] — {repo_path}")- console.print(- "[yellow]Building the wiki from structure[/yellow] [dim]— no model, no spend.[/dim]"- )+ console.print("Building the wiki from structure [dim]— no model, no spend.[/dim]")if decision_provider:console.print(f"Decision extraction provider: [cyan]{decision_provider.provider_name}[/cyan]"@@ -1139,7 +1153,7 @@ def init_command(# wiki below rather than in a question or a crash.try:provider = resolve_provider(provider_name, model, repo_path)- except click.ClickException:+ except click.ClickException as exc:# Nothing configured anywhere. Workspace init, workspace update# and the OSS server all render a template wiki in this exact# situation rather than refusing to run (#999); single-repo init@@ -1157,6 +1171,12 @@ def init_command("[dim]Set a key (or pass --provider) and run [bold]repowise ""update --full[/bold] to have a model write it.[/dim]")+ # A provider that was configured but could not be built is a+ # different problem from none being configured at all, and the+ # message above would otherwise send the user to set a key they+ # have already set.+ if "Could not set up" in str(exc):+ console.print(f" [dim]{exc}[/dim]")# resolve_provider / interactive provider selection may have just set# the API key in os.environ. Re-resolve the embedder so the# display (and the embed path below) honors the key the user just@@ -1210,16 +1230,22 @@ def init_command(orchestrator_mode = OrchestratorMode.FAST if run_mode == "fast" else OrchestratorMode.STANDARD- with Progress(+ index_columns: list[Any] = [SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),TextColumn("[progress.description]{task.description}"),BarColumn(),MaybeCountColumn(),TimeElapsedColumn(),- TextColumn("[green]${task.fields[cost]:.3f}[/green]"),- console=console,- ) as progress_bar:- rich_callback = RichProgressCallback(progress_bar, console)+ ]+ # Only when a model can actually be called. On a --no-prose run the column+ # would sit at $0.000 for the whole multi-minute index, which reads as an+ # unanswered question rather than an answer (same call generation.py makes+ # for the generation bar).+ if llm_client is not None:+ index_columns.append(TextColumn("[green]${task.fields[cost]:.3f}[/green]"))++ with Progress(*index_columns, console=console) as progress_bar:+ rich_callback = RichProgressCallback(progress_bar, console, total_phases=total_phases)# Wrap the Rich callback so we can record per-phase wall-clock# durations without changing the pipeline API. Timings get# persisted to state.json below.diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.pyindex 48883f4ff..d9a0a1e8f 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py@@ -49,6 +49,7 @@ __all__ = ["cost_gate_declined","estimate_generation","format_cost",+ "page_type_label","run_repo_generation",]@@ -106,18 +107,37 @@ def concept_page_count(plans: list[Any]) -> int:return next((p.count for p in plans if p.page_type == "module_page"), 0)-# Short, plain names for the structural page types, in the order they read best.-# Only the free types are listed: the paid ones are already named by the cost-# question itself.-_STRUCTURAL_LABELS = (- ("file_page", "file"),- ("api_contract", "API"),- ("symbol_spotlight", "symbol"),- ("scc_page", "cycle"),- ("layer_page", "layer"),- ("infra_page", "infra"),+# Every page type, in the order it reads best, with the two plain-English forms+# the init screen needs: a row label for the generation plan table, and a short+# noun for the one-line structural summary under it. One table so the plan, the+# summary and the cost question can never call the same page three things —+# ``module_page`` in the table, "concept pages" in the price, "subsystem pages"+# in the mode panel was the old state.+_PAGE_TYPE_LABELS: tuple[tuple[str, str, str], ...] = (+ ("module_page", "Subsystem pages", "subsystem"),+ ("repo_overview", "Repo overview", "overview"),+ ("architecture_diagram", "Architecture diagram", "diagram"),+ ("onboarding", "Onboarding pages", "onboarding"),+ ("file_page", "File pages", "file"),+ ("api_contract", "API contract pages", "API"),+ ("symbol_spotlight", "Symbol spotlights", "symbol"),+ ("scc_page", "Dependency cycle pages", "cycle"),+ ("layer_page", "Layer pages", "layer"),+ ("infra_page", "Infrastructure pages", "infra"),)+_ROW_LABELS: dict[str, str] = {pt: row for pt, row, _ in _PAGE_TYPE_LABELS}+++def page_type_label(page_type: str) -> str:+ """Plain-English row label for a page type id.++ Falls back to a readable form of the id itself, so a page type added to the+ generator but not to the table above degrades to ``"Scc page"`` rather than+ to a silent hole.+ """+ return _ROW_LABELS.get(page_type) or page_type.replace("_", " ").capitalize()+def structural_page_summary(plans: list[Any]) -> str:"""Return e.g. ``"3622 pages rendered from structure, free: 2947 file, ..."``.@@ -133,7 +153,7 @@ def structural_page_summary(plans: list[Any]) -> str:total = sum(counts.values())if not total:return ""- parts = [f"{counts[t]} {label}" for t, label in _STRUCTURAL_LABELS if counts.get(t)]+ parts = [f"{counts[pt]} {short}" for pt, _, short in _PAGE_TYPE_LABELS if counts.get(pt)]return f"{total} more pages rendered from the code itself, no model, no cost: " + ", ".join(parts)@@ -375,4 +395,13 @@ def run_repo_generation(verbose=verbose,)flush_cost_tracker(cost_tracker)++ # What the run actually spent, for the completion panel. The user was shown+ # an estimate before the run and a live cost column during it; reporting+ # only tokens at the end left the one number they were promised unanswered.+ #+ # Read AFTER enrichment, not before: layer naming and the guided tour are+ # real model calls billed through this same tracker, so capturing it any+ # earlier would print a figure the llm_costs table disagrees with.+ result.llm_cost_usd = cost_tracker.session_cost if cost_tracker is not None else 0.0return generated_pagesdiff --git a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.pyindex b7de11034..76bd5836f 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py@@ -169,29 +169,40 @@ def show_completion(else:_lang_summary_final = str(len(result.languages))+ # What the run found, in both modes. A full run — the recommended path —+ # used to report none of this in its closing panel: file count, symbols,+ # languages and graph size appeared once in the "Analysis Complete"+ # interstitial, minutes and one cost prompt earlier.+ _index_rows: list[tuple[str, str]] = [+ ("Files indexed", f"{result.file_count:,}"),+ ("Symbols", f"{result.symbol_count:,}"),+ ("Languages", _lang_summary_final),+ ]+ _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]] = [- ("Files indexed", str(result.file_count)),- ("Symbols", f"{result.symbol_count:,}"),- ("Languages", _lang_summary_final),- ("Wiki pages", f"{_template_pages} rendered from structure"),+ *_index_rows,+ ("Wiki pages", f"{_template_pages:,} rendered from structure"),("Elapsed", format_elapsed(elapsed)),("", ""),- (- "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)),+ *_structure_rows,]- if result.git_summary:- metrics.append(- (- "Git history",- f"{result.git_summary.files_indexed} files · {_hotspot_count_final} hotspots",- )- )next_steps = build_contextual_next_steps(index_only=True,@@ -239,22 +250,24 @@ def show_completion(_pages_label = f"{len(_pages)} ({len(_failed_ids)} failed)"elif _det:_pages_label = f"{len(_pages)} ({_ai} model-written · {_det} from structure)"+ # 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,("Pages generated", _pages_label),- ("Total tokens", f"{total_tokens:,}"),+ _spend_row,("Provider", f"{provider.provider_name} / {provider.model_name}"),("Elapsed", format_elapsed(elapsed)),("", ""),- ("Dead code", f"{_dc_unreachable} unreachable · {_dc_unused} unused exports"),- ("Decisions", str(_n_decisions)),+ *_structure_rows,]- if result.git_summary:- metrics.append(- (- "Git history",- f"{result.git_summary.files_indexed} files · {_hotspot_count_final} hotspots",- )- )next_steps = build_contextual_next_steps(index_only=False,@@ -296,13 +309,13 @@ def show_workspace_completion("""Render the workspace completion panel + per-repo docs status."""metrics: list[tuple[str, str]] = [("Repositories", f"{len(selected) - len(errors)} indexed"),- ("Total files", str(total_files)),+ ("Total files", f"{total_files:,}"),("Total symbols", f"{total_symbols:,}"),("Primary repo", primary_alias),("Elapsed", format_elapsed(elapsed)),]if not index_only and provider is not None:- metrics.insert(3, ("Pages generated", str(total_pages)))+ metrics.insert(3, ("Pages generated", f"{total_pages:,}"))metrics.insert(4, ("Provider", f"{provider.provider_name} / {provider.model_name}"))if errors:metrics.append(("Errors", f"{len(errors)} repos failed"))diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex 8219e0f09..8a7a707ea 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -49,6 +49,7 @@ from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_from repowise.cli.ui import (BRAND,BRAND_STYLE,+ ERR,OWL_SPINNER,MaybeCountColumn,RichProgressCallback,@@ -125,9 +126,12 @@ def _run_workspace_generation(skip_infra=skip_infra,)+ # Same decision and same stakes as the single-repo flow, so the count and+ # the price carry the same emphasis; in a per-repo loop this line can go by+ # a dozen times, which makes plain text easier to miss, not harder.console.print(- f" Writing {concept_page_count(plans)} concept pages with "- f"{provider.model_name}. {format_cost(est)}."+ f" Writing [bold]{concept_page_count(plans):,}[/bold] subsystem pages with "+ f"[cyan]{provider.model_name}[/cyan]. Estimated [bold]{format_cost(est)}[/bold].")structural = structural_page_summary(plans)if structural:@@ -293,7 +297,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtfrom repowise.core.pipeline.modes import OrchestratorModeconsole.print(- f" [{BRAND}][{idx}/{total}][/] Indexing [bold]{repo.alias}[/bold] ({repo.path.name})..."+ f" [{BRAND}][{idx}/{total}][/] Indexing [bold]{repo.alias}[/bold] ({repo.path.name})…")ensure_repowise_dir(repo.path)@@ -332,10 +336,10 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt)repo_phase_timings: dict[str, float] = callback.timingsconsole.print(- f" [green]✓[/green] {result.file_count} files, {result.symbol_count:,} symbols"+ f" [green]✓[/green] {result.file_count:,} files, {result.symbol_count:,} symbols")except Exception as exc:- console.print(f" [red]✗ Failed: {exc}[/red]\n")+ console.print(f" [{ERR}]✗ Failed: {exc}[/]\n")return _RepoOutcome(error=str(exc))provider = ctx.provider@@ -418,7 +422,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt)_render_from_templates()except Exception as gen_exc:- console.print(f" [yellow]Generation failed: {gen_exc}[/yellow]\n")+ console.print(f" [{ERR}]✗ Generation failed: {gen_exc}[/]\n")skip_reason = f"generation error: {gen_exc}"result.generated_pages = []else:@@ -589,7 +593,9 @@ def _workspace_init(# this way routinely. "Every repo the scan found" is also what --all# means, so the fallback matches the flag a human would have passed.select_all = init_all or yes or not sys.stdin.isatty()- selected = list(scan.repos) if select_all else interactive_repo_select(console, scan.repos)+ selected = (+ list(scan.repos) if select_all else interactive_repo_select(console, scan.repos, root)+ )if not selected:console.print("[yellow]No repositories selected. Aborting.[/yellow]")@@ -621,7 +627,10 @@ def _workspace_init()if is_interactive:- mode = interactive_mode_select(console)+ mode = interactive_mode_select(+ console,+ title=f"How much should repowise write for these {len(selected)} repos?",+ )if mode == "index_only":index_only = Trueelif mode == "advanced":diff --git a/packages/cli/src/repowise/cli/cost_gate.py b/packages/cli/src/repowise/cli/cost_gate.pyindex a24f9e80a..ae5f2b8b4 100644--- a/packages/cli/src/repowise/cli/cost_gate.py+++ b/packages/cli/src/repowise/cli/cost_gate.py@@ -123,7 +123,7 @@ def cost_gate_blocks(est: Any, *, yes: bool, message: str) -> bool:raise click.ClickException(f"This would spend about {format_cost(est)} and there is no terminal ""to confirm on. Re-run with --yes to accept the cost, or with "- "--index-only to build the wiki from structure for free."+ "--no-prose to build the wiki from structure for free.")return not confirm_cost_gate(message, estimated_usd=est.estimated_cost_usd)@@ -136,6 +136,9 @@ def format_cost(est: Any) -> str:f"(median ${est.estimated_cost_usd:.2f})")if est.is_calibrated:- cost_str += " [calibrated]"+ # Not "[calibrated]": the result is interpolated into Rich markup,+ # which parses square brackets as a style tag and renders an+ # unknown one as nothing at all.+ cost_str += " (calibrated on this repo's history)"return cost_strreturn f"${est.estimated_cost_usd:.2f} USD"diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.pyindex 4aa7c4429..2a14c8ce0 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py@@ -124,11 +124,12 @@ def _uses_lean_tool_surface(repo_path: Path) -> bool:def _prompt_claude_md_enabled(console_obj: Any) -> bool:"""Ask whether the Claude project instruction file should be generated."""- from repowise.cli.ui import BRAND-- console_obj.print()- console_obj.print(f" [{BRAND}]Editor Integration[/]")+ # The inline ``Name:`` form its four sibling prompts use. A brand-coloured+ # section header, borrowed from advanced config, oversold a single yes/no.console_obj.print()+ console_obj.print(+ "[bold]Claude Code:[/bold] Write a project instruction file describing this codebase?"+ )return click.confirm(" Generate .claude/CLAUDE.md?",default=True,diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex.py b/packages/cli/src/repowise/cli/editor_integrations/codex.pyindex e8cf602cb..acd585437 100644--- a/packages/cli/src/repowise/cli/editor_integrations/codex.py+++ b/packages/cli/src/repowise/cli/editor_integrations/codex.py@@ -33,6 +33,11 @@ class CodexSetup:console_obj.print()console_obj.print("[bold]Codex:[/bold] Generate project-local .codex config and hooks?")+ # Its two neighbours default to yes; say why this one does not, rather+ # than silently inverting Enter-through in the middle of three prompts.+ console_obj.print(+ " [dim]Off by default: only useful if you drive this repo with the Codex CLI.[/dim]"+ )enabled = click.confirm(" Write .codex/config.toml and .codex/hooks.json?",default=False,@@ -133,7 +138,7 @@ def maybe_generate_agents_md():returntry:- with console_obj.status(" Generating AGENTS.md...", spinner=OWL_SPINNER):+ with console_obj.status(" Generating AGENTS.md…", spinner=OWL_SPINNER):run_async(_write_agents_md_async(repo_path))console_obj.print(" [green]✓[/green] AGENTS.md updated")except Exception as exc:diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex 26c3b9991..671bc4d89 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -698,7 +698,21 @@ def resolve_provider(config_base_url = _config_base_url(name)if config_base_url:kwargs.setdefault("base_url", config_base_url)- return get_provider(name, **kwargs)+ try:+ return get_provider(name, **kwargs)+ except click.ClickException:+ raise+ except Exception as exc:+ # Everything this constructor reads is user input: env vars and+ # .repowise/config.yaml, base_url above all. A typo there is a+ # configuration error, not a repowise bug, but it used to surface+ # as a raw traceback that escaped every caller's handler —+ # OLLAMA_BASE_URL=http://localhost:abc makes httpx raise+ # InvalidURL, which killed `init` outright.+ raise click.ClickException(+ f"Could not set up the {name} provider: {exc}. Check its "+ "settings in your environment and .repowise/config.yaml."+ ) from excif provider_name is not None:# Validate configuration before attempting to create providerdiff --git a/packages/cli/src/repowise/cli/ui/brand.py b/packages/cli/src/repowise/cli/ui/brand.pyindex 08216ada5..03b6436c7 100644--- a/packages/cli/src/repowise/cli/ui/brand.py+++ b/packages/cli/src/repowise/cli/ui/brand.py@@ -46,7 +46,7 @@ def print_banner(console: Console, repo_name: str | None = None) -> None:console.print(f" [dim]codebase intelligence · v{__version__}[/dim]", highlight=False)else:console.print(- f" [dim]codebase intelligence for developers and AI · v{__version__}[/dim]",+ f" [dim]codebase intelligence for developers and AI · v{__version__}[/dim]",highlight=False,)if repo_name:diff --git a/packages/cli/src/repowise/cli/ui/mode_selection.py b/packages/cli/src/repowise/cli/ui/mode_selection.pyindex a581dfc1d..486962d0f 100644--- a/packages/cli/src/repowise/cli/ui/mode_selection.py+++ b/packages/cli/src/repowise/cli/ui/mode_selection.py@@ -14,7 +14,11 @@ from rich.table import Tablefrom rich.text import Textfrom repowise.cli.ui.brand import BRAND, BRAND_STYLE, DIM-from repowise.cli.ui.repo_scanner import RepoScanInfo, estimated_documentable_files+from repowise.cli.ui.repo_scanner import (+ RepoScanInfo,+ estimated_documentable_files,+ estimated_wiki_render_minutes,+)from repowise.core.generation.languages import SUPPORTED_LANGUAGESfrom repowise.core.generation.selection import (FILE_PAGE_AUTO_CEILING,@@ -74,34 +78,45 @@ def interactive_fast_mode_offer(return click.confirm(" Use fast mode?", default=default_fast)-def interactive_mode_select(console: Console) -> str:+def interactive_mode_select(console: Console, *, title: str | None = None) -> str:"""Let the user choose full / index-only / advanced.+ All three options index identically; what differs is how much of the wiki a+ model writes, so the panel asks that rather than "how would you like to+ index". *title* overrides the question for callers indexing more than one+ repo (the workspace flow shows this same panel for a whole workspace).+Returns ``"full"``, ``"index_only"``, or ``"advanced"``."""body = Text()body.append(" [1]", style=BRAND_STYLE)body.append(" Everything ", style="bold")- body.append("(recommended)\n", style="dim")- body.append(" All five layers: dependency graph, git history, code\n")- body.append(" health, decisions + AI-generated wiki, diagrams & API docs.\n\n")+ body.append("(recommended, needs an API key)\n", style="dim")+ body.append(" Everything repowise can build: dependency graph, git history,\n")+ body.append(" code health, architectural decisions, a model-written wiki,\n")+ body.append(" architecture diagrams and API docs.\n")+ body.append(+ " Costs a few cents to a few dollars; you see the estimate\n"+ " before anything runs.\n\n",+ style="dim",+ )body.append(" [2]", style=BRAND_STYLE)body.append(" No prose ", style="bold")body.append("(no key, no spend)\n", style="dim")- body.append(" The same complete wiki, rendered from the code's structure.\n")- body.append(" The subsystem pages read as stubs rather than written prose;\n")- body.append(" add a key and run repowise generate to write them.\n\n")+ body.append(" Every page type still gets built, straight from the code.\n")+ body.append(" Only the subsystem pages come out as outlines instead of prose;\n")+ body.append(" add a key later and run repowise generate to fill them in.\n\n")body.append(" [3]", style=BRAND_STYLE)body.append(" Advanced\n", style="bold")body.append(" Full control — turn AI docs on or off, then tune indexing\n")- body.append(" and generation (commit limit, exclude patterns, concurrency …)")+ body.append(" and generation (commit limit, exclude patterns, concurrency, ...)")console.print(Panel(body,- title="[bold]How would you like to index this repo?[/bold]",+ title=f"[bold]{title or 'How much should repowise write?'}[/bold]",border_style=BRAND,padding=(1, 2),)@@ -185,11 +200,22 @@ def prompt_language(console: Console) -> str:)+def _section(console: Console, title: str, blurb: str) -> None:+ """Open an advanced-config section: blank line, brand heading, dim blurb.++ Every section in this screen opens the same way, so the shape lives here+ rather than in seven near-identical call sites. Titles are sentence case and+ the blurb is required, which is what keeps a section from shipping as a bare+ heading followed by a prompt the user has no context for.+ """+ console.print()+ console.print(f" [{BRAND}]{title}[/]")+ console.print(f" [dim]{blurb}[/dim]")++def _prompt_scope(console: Console, scan: RepoScanInfo | None, result: dict[str, Any]) -> None:"""Scope section: which file classes to include."""- console.print()- console.print(f" [{BRAND}]Scope[/]")- console.print(" [dim]Choose what to include in the analysis[/dim]")+ _section(console, "Scope", "Choose what to include in the analysis")console.print()test_hint = f" ({scan.test_file_count:,} found)" if scan and scan.test_file_count else ""@@ -250,14 +276,14 @@ def prompt_file_page_volume(return Nonewould_be_capped_anyway = estimate > FILE_PAGE_AUTO_CEILING- console.print()- console.print(f" [{BRAND}]Page volume[/]")- console.print(- f" [dim]About [bold]{estimate:,}[/bold] files here would each get a file page "+ _section(+ console,+ "Page volume",+ f"About [bold]{estimate:,}[/bold] files here would each get a file page "f"({_format_mb(estimate)} of wiki).\n"" File pages are rendered from structure, so they cost no model tokens — what\n"" the tail costs is wiki size, one embedding call each, and search results\n"- " that restate what a subsystem page already says.[/dim]"+ " that restate what a subsystem page already says.",)if would_be_capped_anyway:console.print(@@ -269,10 +295,10 @@ def prompt_file_page_volume(f" [{BRAND}][1][/] Top [bold]{recommended:,}[/bold] by importance [dim](recommended) — "f"~{recommended:,} pages, {_format_mb(recommended)}[/dim]")+ render_min, render_max = estimated_wiki_render_minutes(estimate)console.print(f" [{BRAND}][2][/] Every eligible file [dim]— ~{estimate:,} pages, "- f"{_format_mb(estimate)}, roughly "- f"{max(1, round(estimate / 1000)):,}-{max(2, round(2 * estimate / 1000)):,} min "+ f"{_format_mb(estimate)}, roughly {render_min:,}-{render_max:,} min ""longer to render and embed[/dim]")try:@@ -303,10 +329,10 @@ def _prompt_run_mode(# by default on large repos; off otherwise. Only offered for single-repo# init (allow_fast); the workspace path leaves this untouched.if allow_fast:- console.print()- console.print(f" [{BRAND}]Run mode[/]")- console.print(- " [dim]standard = full depth · fast = quick graph + essential git, no LLM docs[/dim]"+ _section(+ console,+ "Run mode",+ "standard = full depth · fast = quick graph + essential git, no LLM docs",)result["run_mode"] = click.prompt(" Run mode",@@ -321,8 +347,12 @@ def _prompt_exclude(console: Console, scan: RepoScanInfo | None, result: dict[str, Any]) -> list[str]:"""Exclude-patterns section. Returns the parsed pattern list."""+ _section(+ console,+ "Exclude patterns",+ "Keep whole directories or globs out of the index entirely",+ )console.print()- console.print(f" [{BRAND}]Exclude Patterns[/]")# Show suggestions from large dirsif scan and scan.large_dirs:@@ -354,12 +384,10 @@ def _prompt_exclude(def _prompt_git(console: Console, scan: RepoScanInfo | None, result: dict[str, Any]) -> None:"""Git-analysis section: commit limit + rename following."""- console.print()- console.print(f" [{BRAND}]Git Analysis[/]")commit_hint = ""if scan and scan.total_commits:- commit_hint = f" [dim](repo has ~{scan.total_commits:,} total commits)[/dim]"- console.print(f" [dim]Controls how deeply git history is analyzed[/dim]{commit_hint}")+ commit_hint = f" (repo has ~{scan.total_commits:,} total commits)"+ _section(console, "Git analysis", f"Controls how deeply git history is analyzed{commit_hint}")console.print()# Smart default based on repo size@@ -402,9 +430,7 @@ def _prompt_generation(prompt is skipped so the flag wins. *language* works the same way for the``--language`` flag."""- console.print()- console.print(f" [{BRAND}]Generation[/]")- console.print(" [dim]LLM page generation settings[/dim]")+ _section(console, "Generation", "LLM page generation settings")console.print()# Smart concurrency default@@ -622,11 +648,11 @@ def _prompt_index_only_search(console: Console, result: dict[str, Any]) -> None:picked up automatically from an API key in the environment, and this modepromises no spend. Choosing one here counts as asking for it."""- console.print()- console.print(f" [{BRAND}]Search[/]")- console.print(- " [dim]Full-text search always works. Semantic search needs an embedder;\n"- " ollama is the keyless one, and the hosted ones charge per page.[/dim]"+ _section(+ console,+ "Search",+ "Full-text search always works. Semantic search needs an embedder;\n"+ " ollama is the keyless one, and the hosted ones charge per page.",)console.print()result["embedder"] = click.prompt(@@ -651,33 +677,34 @@ def _resolve_embedder_from_env() -> str:def print_index_only_intro(console: Console, has_provider: bool = False) -> None:"""Show what index-only mode will do before starting."""+ # Bullets, not checkmarks: every green ✓ elsewhere in a run means "already+ # done", and this panel is a forecast.lines = [- " [green]✓[/] Parse all source files (AST)",- " [green]✓[/] Build dependency graph (PageRank, communities)",- " [green]✓[/] Index git history (hotspots, ownership, co-changes)",- " [green]✓[/] Detect dead code",- " [green]✓[/] Extract architectural decisions",- " [green]✓[/] Render the wiki from structure: file, module, layer and",+ " [dim]•[/dim] Parse all source files (AST)",+ " [dim]•[/dim] Build dependency graph (PageRank, communities)",+ " [dim]•[/dim] Index git history (hotspots, ownership, co-changes)",+ " [dim]•[/dim] Detect dead code",+ " [dim]•[/dim] Extract architectural decisions",+ " [dim]•[/dim] Render the wiki from structure: file, module, layer and"," cycle pages, the architecture diagram, the repo overview, API and"," infra pages, and the onboarding collection",- " [green]✓[/] Set up MCP server for AI assistants",+ " [dim]•[/dim] Set up MCP server for AI assistants",]if has_provider:lines.append(- " [green]✓[/] [dim]Decision extraction enhanced (provider key detected)[/dim]"+ " [dim]•[/dim] [dim]Decision extraction enhanced (provider key detected)[/dim]")lines.append("")lines.append(" [dim]No LLM calls. No API key. No cost.[/dim]")lines.append(" [dim]The subsystem pages read as stubs. Add a key and run "- "[bold]repowise generate[/bold][/dim]"+ "[bold]repowise generate[/bold] to write them as prose.[/dim]")- lines.append(" [dim]to write them as prose.[/dim]")console.print(Panel("\n".join(lines),- title="[bold]Index Only[/bold]",+ title="[bold]Index only: what this will do[/bold]",border_style=BRAND,padding=(1, 1),)diff --git a/packages/cli/src/repowise/cli/ui/progress.py b/packages/cli/src/repowise/cli/ui/progress.pyindex 533a970d7..d52c9503b 100644--- a/packages/cli/src/repowise/cli/ui/progress.py+++ b/packages/cli/src/repowise/cli/ui/progress.py@@ -2,13 +2,33 @@from __future__ import annotations+from collections.abc import Callablefrom typing import Anyfrom rich.console import Consolefrom rich.progress import ProgressColumn, Taskfrom rich.text import Text-from repowise.cli.ui.brand import ERR, OK, WARN+from repowise.cli.ui.brand import ERR, WARN, print_phase_header++# Top-level stage → (phase number, title, subtitle). The pipeline announces the+# stage; how it is numbered and worded is the screen's business, and the screen+# is the only side that knows generation and persistence follow.+#+# The keys are spelled out rather than imported from+# ``repowise.core.pipeline.progress``: that module's package eagerly imports the+# orchestrator, which every other CLI call site is careful to defer into a+# function body, and paying ~170ms of pipeline import on ``repowise --help`` or+# on each post-commit hook run to read two string constants is a bad trade.+# ``test_init_ux`` pins these against the core constants so they cannot drift.+_STAGE_HEADERS: dict[str, tuple[int, str, str]] = {+ "ingestion": (+ 1,+ "Ingestion",+ "Walking the tree, parsing files, building the dependency graph",+ ),+ "analysis": (2, "Analysis", "Dead code, code health, architectural decisions"),+}class MaybeCountColumn(ProgressColumn):@@ -33,25 +53,32 @@ class MaybeCountColumn(ProgressColumn):# Rich progress callback — implements core ProgressCallback protocol# ---------------------------------------------------------------------------+# Every phase the pipeline emits needs an entry here: the fallback prints the+# raw internal id (``knowledge_graph.skeleton...``) beside proper sentences.+# ``…`` throughout, matching the CLI-authored status lines these interleave with._PHASE_LABELS: dict[str, str] = {- "traverse": "Scanning & filtering files...",- "parse": "Parsing files...",- "tsconfig": "Indexing tsconfig path aliases...",- "graph": "Building dependency graph...",+ "traverse": "Scanning & filtering files…",+ "parse": "Parsing files…",+ "tsconfig": "Indexing tsconfig path aliases…",+ "graph": "Building dependency graph…","graph.imports": " ↳ Resolving imports","graph.heritage": " ↳ Resolving inheritance","graph.calls": " ↳ Resolving call edges",+ "graph.type_refs": " ↳ Resolving type references","dynamic_hints": " ↳ Wiring dynamic hints","graph.metrics": " ↳ Computing graph metrics (PageRank, betweenness)","graph.communities": " ↳ Detecting communities","graph.flows": " ↳ Tracing execution flows",- "external_systems": "Parsing external dependency manifests...",- "git": "Indexing file history...",- "co_change": "Analyzing co-changes...",- "dead_code": "Detecting dead code...",- "decisions": "Extracting decisions...",- "generation": "Generating pages...",- "onboarding": "Curating onboarding docs...",+ "external_systems": "Parsing external dependency manifests…",+ "git": "Indexing file history…",+ "co_change": "Analyzing co-changes…",+ "dead_code": "Detecting dead code…",+ "health": "Scoring code health…",+ "decisions": "Extracting decisions…",+ "knowledge_graph.skeleton": "Building the knowledge graph…",+ "knowledge_graph.enrich": " ↳ Naming layers and building the tour",+ "generation": "Generating pages…",+ "onboarding": "Curating onboarding docs…",}@@ -67,13 +94,49 @@ class RichProgressCallback:result = run_async(run_pipeline(..., progress=callback))"""- def __init__(self, progress: Any, console: Console) -> None:+ def __init__(self, progress: Any, console: Console, *, total_phases: int | None = None) -> None:self._progress = progressself._console = consoleself._tasks: dict[str, Any] = {}+ # Set only by the single-repo init flow, which is the one screen that+ # numbers its phases. The workspace flow prints its own per-repo header+ # and would otherwise draw a "Phase 1 of 4" rule for every repo.+ self._total_phases = total_phases++ def _print_above_live(self, emit: Callable[[], None]) -> None:+ """Run *emit* outside the Live region so its output lands cleanly+ above the progress bars instead of interleaving with still-rendering+ spinners (issue: phase summary lines interleaved with bars).+ """+ live = getattr(self._progress, "live", None)+ if live is not None:+ try:+ with live._lock:+ emit()+ self._progress.refresh()+ return+ except Exception:+ pass+ emit()++ def on_stage(self, stage: str) -> None:+ """Render a top-level stage as the same phase rule the CLI uses.++ Phases 1 and 2 used to arrive as small green ``on_message`` lines while+ 3 and 4 got full-width rules, so the first separator a first-time user+ ever saw read "Phase 3 of 4".+ """+ total = self._total_phases+ meta = _STAGE_HEADERS.get(stage)+ if total is None or meta is None:+ return+ num, title, subtitle = meta+ self._print_above_live(+ lambda: print_phase_header(self._progress.console, num, total, title, subtitle)+ )def on_phase_start(self, phase: str, total: int | None) -> None:- label = _PHASE_LABELS.get(phase, f"{phase}...")+ label = _PHASE_LABELS.get(phase, f"{phase}…")# If phase already has a task, update its total and make visibleif phase in self._tasks:self._progress.update(self._tasks[phase], total=total, visible=True)@@ -102,7 +165,11 @@ class RichProgressCallback:passdef on_message(self, level: str, text: str) -> None:- style_map = {"info": OK, "warning": WARN, "error": ERR}+ # ``info`` is deliberately unstyled. It carries neutral facts ("Scanned+ # 12,431 files", "Languages: …"), and rendering those in the same green+ # as "✓ Database updated" made green mean "the pipeline said something"+ # rather than "this succeeded".+ style_map = {"warning": WARN, "error": ERR}style = style_map.get(level, "")# Insight lines (indented with →) get special formattingif text.lstrip().startswith("→"):@@ -112,19 +179,7 @@ class RichProgressCallback:else:line = f" {text}"- # Print under the Live lock so the line lands cleanly above the- # progress region instead of interleaving with still-rendering- # spinners (issue: phase summary lines interleaved with bars).- live = getattr(self._progress, "live", None)- if live is not None:- try:- with live._lock:- self._progress.console.print(line)- self._progress.refresh()- return- except Exception:- pass- self._progress.console.print(line)+ self._print_above_live(lambda: self._progress.console.print(line))def set_cost(self, total_cost: float) -> None:"""Update the live cost display on all active progress tasks."""diff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.pyindex 2121365fc..1b2c8a347 100644--- a/packages/cli/src/repowise/cli/ui/provider_selection.py+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py@@ -4,8 +4,11 @@ from __future__ import annotationsimport osimport re+import socket+from collections.abc import Callablefrom dataclasses import dataclassfrom pathlib import Path+from urllib.parse import urlparseimport clickfrom rich.console import Console@@ -64,6 +67,23 @@ _PROVIDER_SIGNUP: dict[str, str] = {}+# Short dim suffix on the provider name, saying what this provider is or how it+# authenticates. The Status column answers "can I pick this right now"; anything+# provider-specific belongs here so one column keeps one meaning.+_PROVIDER_NOTES: dict[str, str] = {+ "gemini": "recommended",+ "codex_cli": "uses your Codex CLI login",+ "opencode": "uses your opencode CLI setup",+ "ollama": "runs on your machine, no key",+ "litellm": "proxy in front of another provider",+}++_OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434"+# Enough for a loopback connect; the table renders before any prompt, so a slow+# or firewalled endpoint must not hold the whole screen.+_OLLAMA_PROBE_TIMEOUT_S = 0.3++@dataclass(frozen=True)class ProviderSelection:"""Interactive provider/model/reasoning selection result."""@@ -88,8 +108,64 @@ def _detect_opencode_status() -> bool:return shutil.which("opencode") is not None+def ollama_base_url() -> str:+ """Where the picker expects to find Ollama."""+ return os.environ.get("OLLAMA_BASE_URL") or _OLLAMA_DEFAULT_BASE_URL+++def _ollama_endpoint() -> tuple[str, int] | None:+ """``(host, port)`` for the configured Ollama URL, or ``None`` if unusable.++ A bare ``host:port`` is accepted, since that is a natural thing to put in+ ``OLLAMA_BASE_URL`` and urlparse would otherwise read the host as a scheme.+ Anything with no host left after that (``unix://…``, plain junk with a+ scheme) has no TCP endpoint to probe, and must not silently fall back to+ localhost: that reports someone's typo'd remote box as ready and defers the+ failure to the first generation call.+ """+ raw = ollama_base_url().strip()+ if "://" not in raw:+ raw = f"http://{raw}"+ try:+ parsed = urlparse(raw)+ host = parsed.hostname+ # A property, and it raises rather than returning None for a+ # non-numeric or out-of-range port.+ port = parsed.port+ except ValueError:+ return None+ if not host:+ return None+ return host, port or (443 if parsed.scheme == "https" else 11434)+++def _detect_ollama_status() -> bool:+ """Return ``True`` if something is listening at the Ollama endpoint.++ Ollama takes no API key, so "is the env var set" was never the question:+ a user with it running locally and no ``OLLAMA_BASE_URL`` was shown as+ unavailable and then asked to paste a key that does not exist. A TCP+ connect is the cheapest honest answer.+ """+ endpoint = _ollama_endpoint()+ if endpoint is None:+ return False+ try:+ # gaierror and timeout are both OSError subclasses, so a bad host or a+ # black-holed address ends up here rather than escaping.+ with socket.create_connection(endpoint, timeout=_OLLAMA_PROBE_TIMEOUT_S):+ return True+ except OSError:+ return False++def _detect_provider_status() -> dict[str, str]:- """Return {provider: env_var_name} for providers whose key is set."""+ """Return {provider: what makes it ready} for providers that can be used now.++ The value is the env var carrying the key for the hosted providers, and a+ short description of the out-of-band credential for the local ones. Only+ truthiness is load-bearing; the value is for debugging.+ """status: dict[str, str] = {}for prov, env_var in _PROVIDER_ENV.items():if prov == "gemini":@@ -102,11 +178,77 @@ def _detect_provider_status() -> dict[str, str]:elif prov == "opencode":if _detect_opencode_status():status[prov] = "opencode CLI"+ elif prov == "ollama":+ if _detect_ollama_status():+ status[prov] = ollama_base_url()elif os.environ.get(env_var):status[prov] = env_varreturn status+def _codex_cli_setup_lines() -> list[str]:+ installed, _ = _detect_codex_cli_status()+ problem = (+ "Codex CLI is not on PATH." if not installed else "Codex CLI is on PATH but not logged in."+ )+ return [+ " [bold]codex_cli[/bold] uses the Codex CLI's own session. No API key here.",+ f" Install: [{BRAND}]npm install -g @openai/codex[/]",+ f" Log in: [{BRAND}]codex login[/]",+ "",+ f" [{WARN}]{problem}[/] Set it up and retry, or select another provider.",+ ]+++def _opencode_setup_lines() -> list[str]:+ return [+ " [bold]opencode[/bold] is a local AI coding CLI that manages its own "+ "models and authentication. No API key here.",+ f" Install: [{BRAND}]curl -fsSL https://opencode.ai/install | bash[/]",+ f" Set up: [{BRAND}]opencode[/] (first run configures your provider)",+ f" Models: [{BRAND}]opencode models[/]",+ "",+ f" To pick a specific model: [{BRAND}]repowise init --provider opencode "+ "--model opencode/deepseek/deepseek-v4-pro[/]",+ "",+ f" [{WARN}]opencode CLI not found on PATH.[/] Install it and retry, "+ "or select another provider.",+ ]+++def _ollama_setup_lines() -> list[str]:+ base_url = ollama_base_url()+ lines = [" [bold]ollama[/bold] runs models on your machine. No key needed.", ""]+ if _ollama_endpoint() is None:+ # The URL never resolved to a host and port, so "nothing is listening"+ # would name the wrong problem.+ lines.append(+ f" [{WARN}]OLLAMA_BASE_URL is set to {base_url!r}, which is not a "+ f"host repowise can reach.[/] Expected something like "+ f"[{BRAND}]http://localhost:11434[/]."+ )+ return lines+ lines.append(+ f" [{WARN}]Nothing is listening at {base_url}.[/] Start it with "+ f"[{BRAND}]ollama serve[/], pull a model with [{BRAND}]ollama pull qwen3.5:4b[/], "+ "then retry."+ )+ lines.append(" [dim]Set OLLAMA_BASE_URL if it listens somewhere else.[/dim]")+ return lines+++# Providers with no API key to paste: they authenticate out of band or run+# locally, so readiness is a probe and the remedy is a command, never a prompt.+# ``registry.KEYLESS_PROVIDERS`` is the resolution-side version of this idea; it+# also holds litellm and mock, which do take a key here and are not offered+# interactively, so the picker keeps its own narrower list.+_LOCAL_PROVIDER_SETUP: dict[str, Callable[[], list[str]]] = {+ "codex_cli": _codex_cli_setup_lines,+ "opencode": _opencode_setup_lines,+ "ollama": _ollama_setup_lines,+}++def _interactive_provider_name(console: Console,model_flag: str | None,@@ -133,35 +275,21 @@ def _interactive_provider_name(table.add_column("Status", min_width=16)table.add_column("Default Model", style="dim")+ # One axis, two states. The remedy is provider-specific and lives in the+ # dim note beside the name, so the Status column can be read at a glance+ # instead of decoded from three phrasings and two colours.for idx, prov in enumerate(providers, 1):- if prov == "codex_cli":- codex_installed, codex_logged_in = _detect_codex_cli_status()- if codex_logged_in:- status_text = f"[{OK}]✓ codex CLI logged in[/]"- elif codex_installed:- status_text = "[yellow]✗ codex login required[/yellow]"- else:- status_text = "[dim]✗ codex CLI not found[/dim]"- elif prov == "opencode":- if _detect_opencode_status():- status_text = f"[{OK}]✓ opencode CLI available[/]"- else:- status_text = "[dim]✗ opencode CLI not found[/dim]"- else:- status_text = f"[{OK}]✓ API key set[/]" if prov in detected else "[dim]✗ no key[/dim]"- default_model = _PROVIDER_DEFAULTS.get(prov, "")- # Mark gemini as recommended- label = prov- if prov == "gemini":- label = f"{prov} [dim](recommended)[/dim]"- elif prov == "codex_cli":- label = f"{prov} [dim](uses Codex CLI auth)[/dim]"- elif prov == "opencode":- label = f"{prov} [dim](uses opencode CLI auth)[/dim]"- table.add_row(f"[{idx}]", label, status_text, default_model)+ ready = prov in detected+ status_text = f"[{OK}]✓ ready[/]" if ready else "[dim]✗ not set up[/dim]"+ note = _PROVIDER_NOTES.get(prov, "")+ label = f"{prov} [dim]({note})[/dim]" if note else prov+ table.add_row(f"[{idx}]", label, status_text, _PROVIDER_DEFAULTS.get(prov, ""))console.print()console.print(table)+ console.print(+ " [dim]mock is flag-only (writes placeholder pages): repowise init --provider mock[/dim]"+ )console.print()# --- selection ---@@ -183,48 +311,13 @@ def _interactive_provider_name(# --- inline API key entry if missing ---if chosen not in detected:- if chosen == "codex_cli":- codex_installed, codex_logged_in = _detect_codex_cli_status()- console.print()- console.print(- " [bold]codex_cli[/bold] requires the Codex CLI on PATH "- "and an authenticated Codex session."- )- console.print(f" Install CLI: [{BRAND}]npm install -g @openai/codex[/]")- console.print(f" Authenticate: [{BRAND}]codex login[/]")- console.print()- if not codex_installed:- console.print(- f" [{WARN}]Codex CLI not detected. Please install and retry, "- "or select another provider.[/]"- )- elif not codex_logged_in:- console.print(- f" [{WARN}]Codex CLI is not logged in. Run 'codex login' and retry, "- "or select another provider.[/]"- )- return _interactive_provider_name(console, model_flag, repo_path=repo_path)- if chosen == "opencode":- console.print()- console.print(- " [bold]opencode[/bold] is a local AI coding CLI that manages its own "- "models and authentication."- )- console.print()- console.print(f" Install: [{BRAND}]curl -fsSL https://opencode.ai/install | bash[/]")- console.print(f" Setup: [{BRAND}]opencode[/] (first run sets up your provider)")- console.print(f" Models: [{BRAND}]opencode models[/] (list available models)")- console.print(f" More info: [{BRAND}]https://opencode.ai[/]")+ setup_lines = _LOCAL_PROVIDER_SETUP.get(chosen)+ if setup_lines is not None:+ # Nothing to paste: these authenticate out of band or run locally,+ # so the fix is a command, not a key prompt.console.print()- console.print(- f" To use a specific model: [{BRAND}]repowise init --provider opencode "- "--model opencode/deepseek/deepseek-v4-pro[/]"- )- console.print()- console.print(- f" [{WARN}]opencode CLI not detected. Install it and retry, "- "or select another provider.[/]"- )+ for line in setup_lines():+ console.print(line)return _interactive_provider_name(console, model_flag, repo_path=repo_path)env_var = _PROVIDER_ENV[chosen]signup_url = _PROVIDER_SIGNUP.get(chosen, "")@@ -326,9 +419,8 @@ def _select_model_option(repo_path: Path | None,) -> ProviderModelOption:console.print(- " [dim]↳ Smaller is fine — repowise is calibrated for "- "flash-lite / nano / haiku / 8B-class ollama. Bigger models "- "don't improve doc quality.[/]"+ f" [dim]Smaller is fine. repowise is tuned for the {provider_name} budget tier; "+ "bigger models do not produce better docs.[/dim]")display_options = _initial_model_options(options)@@ -352,7 +444,10 @@ def _select_model_option(table.add_column("#", style=BRAND_STYLE, width=4)table.add_column("Model", style="bold", min_width=22)table.add_column("Reasoning", style="dim")- table.add_column("Source", style="dim")+ # No Source column: its values were internal enums (``fallback``,+ # ``manual``) a first-time user cannot act on, and the one case that+ # matters — a built-in list because the provider's list was+ # unreachable — is already stated in full above the table.table.add_column("Notes", style="dim")default_idx = "1"@@ -369,18 +464,11 @@ def _select_model_option(f"[{idx}]",label,_format_reasoning_modes(option.reasoning_modes),- option.source,option.notes,)custom_idx = str(len(display_options) + 1)- table.add_row(- f"[{custom_idx}]",- "Custom model",- "auto",- "manual",- "type an exact model id",- )+ table.add_row(f"[{custom_idx}]", "Custom model", "auto", "type an exact model id")search_idx = Noneif searchable:@@ -389,7 +477,6 @@ def _select_model_option(f"[{search_idx}]",f"Search all {len(options):,} models","",- "","filter the full list by name",)@@ -405,10 +492,11 @@ def _select_model_option(console=console,)if search_idx and choice == search_idx:- query = click.prompt(+ query = Prompt.ask(" Search (e.g. 'mini' or 'nano')",default="",show_default=False,+ console=console,).strip()if not query:continue@@ -427,7 +515,7 @@ def _select_model_option(display_options = matchescontinueif choice == custom_idx:- model = click.prompt(" Model", default=default_model)+ model = Prompt.ask(" Model", default=default_model, console=console)return ProviderModelOption(model=model,label=model,@@ -443,6 +531,7 @@ def _select_model_option(def _select_reasoning_mode(+ console: Console,selected: ProviderModelOption,reasoning_flag: str | None,) -> ReasoningMode:@@ -466,8 +555,14 @@ def _select_reasoning_mode(if choices == ("auto",):return "auto"+ # The one knob on this screen that multiplies token spend, so it gets the+ # same one-line explanation every other prompt in the flow has.+ console.print(+ " [dim]How hard the model thinks per page. Higher costs more tokens; "+ "auto lets repowise pick per page type.[/dim]"+ )return click.prompt(- " Reasoning",+ " Reasoning effort",default="auto",type=click.Choice(choices),)@@ -520,7 +615,7 @@ def interactive_provider_config_select("nano produce equivalent docs at ~10x lower cost on most repos.[/]")- reasoning = _select_reasoning_mode(selected, reasoning_flag)+ reasoning = _select_reasoning_mode(console, selected, reasoning_flag)return ProviderSelection(chosen, selected.model, reasoning)@@ -615,7 +710,8 @@ def _prompt_api_key(# Offer to save for future runsif repo_path is not None:save = click.confirm(- " Save key to .repowise/.env for future runs? (auto-gitignored)",+ " Save this key to .repowise/.env so future runs find it? "+ "(the file is git-ignored, so it will not be committed)",default=True,)if save:diff --git a/packages/cli/src/repowise/cli/ui/repo_scanner.py b/packages/cli/src/repowise/cli/ui/repo_scanner.pyindex 66e3b631b..66cc9b79f 100644--- a/packages/cli/src/repowise/cli/ui/repo_scanner.py+++ b/packages/cli/src/repowise/cli/ui/repo_scanner.py@@ -165,6 +165,16 @@ def estimated_documentable_files(scan: RepoScanInfo | None) -> int:return max(0, src - scan.test_file_count)+def estimated_wiki_render_minutes(documentable: int) -> tuple[int, int]:+ """Rough low/high minutes to render and embed *documentable* file pages.++ Calibrated at roughly 1-2 minutes per thousand pages. Shared by the pre-scan+ summary and the page-volume question so the two screens cannot quote+ different numbers for the same work.+ """+ return max(1, round(documentable / 1000)), max(2, round(2 * documentable / 1000))++def print_scan_summary(console: Console, scan: RepoScanInfo) -> None:"""Print a compact pre-scan summary below the banner."""# File count + language count@@ -194,8 +204,14 @@ def print_scan_summary(console: Console, scan: RepoScanInfo) -> None:src_files = sum(source_langs.values()) or scan.total_filesingest_min = max(1, round(src_files / 500))ingest_max = max(2, round(src_files / 250))+ # Both halves are numbers now. The model step is deliberately absent: its+ # duration follows the concept-page count, which ingestion has not produced+ # yet, and the generation plan states it exactly (with a price) a screen+ # later. A second guess here would only be a worse version of that one.+ render_min, render_max = estimated_wiki_render_minutes(estimated_documentable_files(scan))eta_line = (- f"~{ingest_min}-{ingest_max} min ingestion · LLM generation depends on model + page count"+ f"~{ingest_min}-{ingest_max} min to index · "+ f"~{render_min}-{render_max} min more to render and embed the wiki")body = f" {header_line}\n [dim]{lang_line}[/dim]\n [dim]{eta_line}[/dim]"diff --git a/packages/cli/src/repowise/cli/ui/result_panels.py b/packages/cli/src/repowise/cli/ui/result_panels.pyindex 592d9b588..6be70439e 100644--- a/packages/cli/src/repowise/cli/ui/result_panels.py+++ b/packages/cli/src/repowise/cli/ui/result_panels.py@@ -13,6 +13,22 @@ from repowise.cli.ui.brand import BRANDfrom repowise.cli.ui.mascot import EYES_HAPPY, mini+def build_metrics_table(metrics: list[tuple[str, str]], *, label_width: int = 20) -> Table:+ """Two-column ``label / value`` table, the shape every summary panel uses.++ Rich owns the gutter, which is what the analysis panel's hand-padded row+ labels could not do: ``Decisions`` is one character longer than the 9-column+ gutter ``Graph`` / ``Git`` / ``Dead`` were padded to, so its value started a+ column right of the others.+ """+ table = Table(box=None, padding=(0, 2), show_header=False)+ table.add_column("Metric", style="dim", min_width=label_width)+ table.add_column("Value", style="bold")+ for label, value in metrics:+ table.add_row(label, value)+ return table++def build_analysis_summary_panel(*,file_count: int,@@ -29,34 +45,44 @@ def build_analysis_summary_panel(lang_summary: str = "",) -> Panel:"""Compact analysis-complete interstitial shown before generation."""- lines: list[str] = []- lines.append(+ header = Text.from_markup(f" [bold]{file_count:,}[/bold] files · "f"[bold]{symbol_count:,}[/bold] symbols"+ (f" · [bold]{community_count}[/bold] communities" if community_count else ""))+ parts: list[Any] = [header]if lang_summary:- lines.append(f" [dim]{lang_summary}[/dim]")- lines.append("")- lines.append(- f" Graph [bold]{graph_nodes:,}[/bold] nodes · [bold]{graph_edges:,}[/bold] edges"- )+ parts.append(Text(f" {lang_summary}", style="dim"))+ parts.append(Text(""))++ metrics: list[tuple[str, str]] = [+ ("Graph", f"[bold]{graph_nodes:,}[/bold] nodes · [bold]{graph_edges:,}[/bold] edges")+ ]if git_files:- lines.append(- f" Git [bold]{git_files:,}[/bold] files indexed"- + (f" · [bold]{hotspot_count}[/bold] hotspots" if hotspot_count else "")+ metrics.append(+ (+ "Git",+ f"[bold]{git_files:,}[/bold] files indexed"+ + (f" · [bold]{hotspot_count}[/bold] hotspots" if hotspot_count else ""),+ ))if dead_unreachable or dead_unused:- lines.append(- f" Dead [bold]{dead_unreachable}[/bold] unreachable · "- f"[bold]{dead_unused}[/bold] unused exports"- + (f" · ~{dead_lines:,} lines" if dead_lines else "")+ # "Dead" was an adjective with the noun dropped for column width; the+ # table has no fixed width to protect.+ metrics.append(+ (+ "Dead code",+ f"[bold]{dead_unreachable}[/bold] unreachable · "+ f"[bold]{dead_unused}[/bold] unused exports"+ + (f" · ~{dead_lines:,} lines" if dead_lines else ""),+ ))if decision_count:- lines.append(f" Decisions [bold]{decision_count}[/bold] extracted")+ metrics.append(("Decisions", f"[bold]{decision_count}[/bold] extracted"))+ parts.append(build_metrics_table(metrics, label_width=11))return Panel(- "\n".join(lines),+ Group(*parts),title="[bold]Analysis Complete[/bold]",border_style=BRAND,padding=(1, 1),@@ -87,14 +113,7 @@ def build_completion_panel(The mascot prefix lives here (not at call sites) so every completionpanel gets it consistently."""- table = Table(box=None, padding=(0, 2), show_header=False)- table.add_column("Metric", style="dim", min_width=20)- table.add_column("Value", style="bold")-- for label, value in metrics:- table.add_row(label, value)-- parts: list[Any] = [table]+ parts: list[Any] = [build_metrics_table(metrics)]if next_steps:parts.append(Text(""))diff --git a/packages/cli/src/repowise/cli/ui/workspace_selection.py b/packages/cli/src/repowise/cli/ui/workspace_selection.pyindex c30f7e319..ee5d035cc 100644--- a/packages/cli/src/repowise/cli/ui/workspace_selection.py+++ b/packages/cli/src/repowise/cli/ui/workspace_selection.py@@ -11,13 +11,32 @@ from rich.table import Tablefrom repowise.cli.ui.brand import BRAND_STYLE, OK, WARN+def _display_path(repo: Any, root: Any) -> str:+ """Where this repo sits, relative to the workspace root.++ ``repo.path.name`` is the leaf directory, which for almost every repo is+ the string already in the Repository column — and on a workspace with two+ ``api`` directories under different parents, the one column that would tell+ them apart showed the same text twice.+ """+ if root is None:+ return repo.path.name+ try:+ return repo.path.relative_to(root).as_posix()+ except ValueError:+ # Outside the root (a symlinked or explicitly added repo).+ return str(repo.path)++def interactive_repo_select(console: Console,repos: list[Any],+ root: Any = None,) -> list[Any]:"""Display discovered repos and let the user pick which ones to index.*repos* is a list of :class:`~repowise.core.workspace.scanner.DiscoveredRepo`.+ *root* is the workspace root, used to render each repo's path relative to it.Returns the selected subset in original order."""# Build display table@@ -37,11 +56,14 @@ def interactive_repo_select(status = f"[{OK}]indexed[/]" if repo.has_repowise else "[dim]new[/dim]"if repo.is_submodule:status += " [dim](submodule)[/dim]"- table.add_row(f"[{idx}]", repo.name, str(repo.path.name), status)+ table.add_row(f"[{idx}]", repo.name, _display_path(repo, root), status)console.print()console.print(table)console.print()+ # Ranges and 'none' are supported; they used to be discoverable only by+ # typing something invalid first.+ console.print(" [dim]Numbers (1,2,3), ranges (1-3), 'all' or 'none'.[/dim]")# Selection prompt with retrywhile True:@@ -119,6 +141,12 @@ def interactive_primary_select(if len(repos) == 1:return repos[0].alias+ console.print()+ console.print(" [bold]Primary repository[/bold]")+ console.print(+ " [dim]The primary repo is what MCP tools and the dashboard open by default.\n"+ " You can change it later in repowise.workspace.yaml.[/dim]"+ )console.print()for idx, repo in enumerate(repos, 1):console.print(f" [{BRAND_STYLE}][{idx}][/] {repo.name}")diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 5359550a5..174bf9331 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -24,7 +24,12 @@ from typing import Anyimport structlogfrom repowise.core.pipeline.modes import OrchestratorMode-from repowise.core.pipeline.progress import ProgressCallback+from repowise.core.pipeline.progress import (+ STAGE_ANALYSIS,+ STAGE_INGESTION,+ ProgressCallback,+ emit_stage,+)from repowise.core.registry import HookProgressCallbackfrom .phases._common import _phase_done@@ -272,8 +277,7 @@ async def run_pipeline(llm_client._cost_tracker = cost_tracker# ---- Phase 1: Ingestion ------------------------------------------------- if progress:- progress.on_message("info", "Phase 1: Ingestion")+ emit_stage(progress, STAGE_INGESTION)# Launch git indexing as a background task immediately — it is independent# of parsing and graph-build, so the two stages can run concurrently.@@ -442,8 +446,7 @@ async def run_pipeline(progress.on_message("warning", f"Test run: limiting to {len(parsed_files)} files")# ---- Phase 2: Analysis --------------------------------------------------- if progress:- progress.on_message("info", "Phase 2: Analysis")+ emit_stage(progress, STAGE_ANALYSIS)# Resume fast-path: when a prior run already completed (and persisted) the# ANALYSIS phase, skip recomputing dead code / health / decisions — thediff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.pyindex 15297a623..5aaef3bd3 100644--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py@@ -23,6 +23,19 @@ logger = structlog.get_logger(__name__)# Large repos with tens of thousands of files can take arbitrarily long.DECISION_EXTRACTION_TIMEOUT_SECS = 300+# Where a decision came from, in report order, spelled the way a reader who has+# never seen the extractor would say it ("ADR" alone is unexplained jargon).+_DECISION_SOURCE_LABELS: tuple[tuple[str, str], ...] = (+ ("inline_marker", "from inline markers"),+ ("adr", "from ADR files"),+ ("changelog", "from changelogs"),+ ("pr", "from pull requests"),+ ("git_archaeology", "from git history"),+ ("comment", "from comments"),+ ("readme_mining", "from docs"),+ ("session", "from agent sessions"),+)+async def _run_dead_code_analysis(graph_builder: Any,@@ -313,19 +326,20 @@ async def _run_decision_extraction(progress.on_message("warning", f"Session decision mining skipped: {exc}")if progress:+ # Only the sources that actually found something. On a typical+ # first index most of these are zero, and the line read as+ # "0 ADR · 0 changelog · 0 PR ·" with the real numbers buried.bs = report.by_source- total_decisions = report.total_found+ found = [+ f"{bs[source]} {label}"+ for source, label in _DECISION_SOURCE_LABELS+ if bs.get(source)+ ]+ summary = ", ".join(found) if found else ""progress.on_message("info",- f"→ {total_decisions} decisions: "- f"{bs.get('inline_marker', 0)} inline · "- f"{bs.get('adr', 0)} ADR · "- f"{bs.get('changelog', 0)} changelog · "- f"{bs.get('pr', 0)} PR · "- f"{bs.get('git_archaeology', 0)} git · "- f"{bs.get('comment', 0)} comments · "- f"{bs.get('readme_mining', 0)} docs · "- f"{bs.get('session', 0)} session",+ f"→ {report.total_found} architectural decisions found"+ + (f": {summary}" if summary else ""),)_phase_done(progress, "decisions")diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.pyindex e2d749957..a44cdfb73 100644--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py@@ -57,6 +57,61 @@ async def _timed_step(return result+# Traversal skip counters, in report order: (stat attribute, how to describe it).+# A table rather than eleven near-identical ``if`` blocks, so adding a skip+# reason to the traverser is one line here.+_SKIP_REASONS: tuple[tuple[str, str], ...] = (+ ("skipped_gitignore", "by .gitignore"),+ ("skipped_blocked_extension", "by extension"),+ ("skipped_blocked_pattern", "by filename pattern"),+ ("skipped_oversized", "oversized"),+ ("skipped_binary", "binary"),+ ("skipped_generated", "generated"),+ ("skipped_extra_exclude", "by --exclude"),+ ("skipped_extra_ignore", "by .repowiseIgnore"),+ ("skipped_submodule", "submodule dirs"),+ ("skipped_nested_repo", "nested git repos"),+ ("skipped_unknown_language", "unknown type"),+)++_TOP_LANGUAGES_SHOWN = 6++# Files at or above which the graph build is slow enough to be worth warning+# about. Below it the build finishes in around a second, so the Ctrl-C+# reassurance would be noise on a run that never gets a chance to be+# interrupted. Measured against a 157-file repo (0.8s) and the calibration+# behind the pre-scan estimate, roughly 2 min per 1k source files end to end.+_SLOW_GRAPH_BUILD_FILES = 2000+++def _emit_traversal_summary(+ progress: ProgressCallback | None,+ stats: Any,+ included: int,+) -> None:+ """Report what the walk found and what it left out."""+ if progress is None:+ return++ progress.on_message(+ "info", f"Scanned {stats.total_paths_walked:,} files, {included:,} included"+ )++ skipped = [+ f"{count:,} {label}" for attr, label in _SKIP_REASONS if (count := getattr(stats, attr, 0))+ ]+ if skipped:+ progress.on_message("info", f" Excluded: {', '.join(skipped)}")++ if stats.lang_counts:+ ranked = sorted(stats.lang_counts.items(), key=lambda item: -item[1])+ lang_str = ", ".join(f"{lang} {count:,}" for lang, count in ranked[:_TOP_LANGUAGES_SHOWN])+ rest = sum(count for _, count in ranked[_TOP_LANGUAGES_SHOWN:])+ if rest:+ lang_str += f", other {rest:,}"+ progress.on_message("info", f" Languages: {lang_str}")++# ---------------------------------------------------------------------------# Process-pool worker (module-level — must be picklable)# ---------------------------------------------------------------------------@@ -248,6 +303,12 @@ async def _run_ingestion(if fi.language not in ("dockerfile", "makefile", "terraform", "shell")]+ # Report the traversal here, not at the end of the phase: the graph build,+ # dynamic hints, PageRank and community detection all run below, and on a+ # large repo "Scanned N files" used to land several minutes after the+ # traverse bar had finished and the user had moved on.+ _emit_traversal_summary(progress, traverser.stats, len(file_infos))+# ---- Parse phase: CPU-bound, run in ProcessPoolExecutor ----------------if progress:progress.on_phase_start("parse", len(file_infos))@@ -364,11 +425,16 @@ async def _run_ingestion(# from inside GraphBuilder.build(); the orchestrator drives metrics/# communities/flows below so the longest-running step is no longer an# opaque "graph 0/1" spinner.- if progress:+ if progress and len(file_infos) >= _SLOW_GRAPH_BUILD_FILES:+ # Reassurance before the longest silent stretch of the run, so it is+ # warning-weight rather than another dim stat — which is also why it is+ # gated: on a small repo the build is over in under a second, and a+ # yellow "this may take several minutes" there is a false alarm made+ # louder.progress.on_message(- "info",- " (graph build can take several minutes on first run — safe to "- "Ctrl-C, then run 'repowise init --resume' to continue)",+ "warning",+ "Graph build can take several minutes on a first run. Safe to Ctrl-C — "+ "re-run 'repowise init --resume' to continue where it stopped.",)await asyncio.to_thread(graph_builder.build, progress)@@ -436,53 +502,15 @@ async def _run_ingestion()_phase_done(progress, "graph.communities")- # Emit filtering summary so users can see what was included/excluded- stats = traverser.stats- if progress:- parts: list[str] = []- if stats.skipped_gitignore:- parts.append(f"{stats.skipped_gitignore:,} by .gitignore")- if stats.skipped_blocked_extension:- parts.append(f"{stats.skipped_blocked_extension:,} by extension")- if stats.skipped_blocked_pattern:- parts.append(f"{stats.skipped_blocked_pattern:,} by filename pattern")- if stats.skipped_oversized:- parts.append(f"{stats.skipped_oversized:,} oversized")- if stats.skipped_binary:- parts.append(f"{stats.skipped_binary:,} binary")- if stats.skipped_generated:- parts.append(f"{stats.skipped_generated:,} generated")- if stats.skipped_extra_exclude:- parts.append(f"{stats.skipped_extra_exclude:,} by --exclude")- if stats.skipped_extra_ignore:- parts.append(f"{stats.skipped_extra_ignore:,} by .repowiseIgnore")- if stats.skipped_submodule:- parts.append(f"{stats.skipped_submodule:,} submodule dirs")- if stats.skipped_nested_repo:- parts.append(f"{stats.skipped_nested_repo:,} nested git repos")- if stats.skipped_unknown_language:- parts.append(f"{stats.skipped_unknown_language:,} unknown type")-- excluded_str = ", ".join(parts) if parts else "none"- progress.on_message(- "info",- f"Scanned {stats.total_paths_walked:,} files, {len(file_infos):,} included",- )- if parts:- progress.on_message("info", f" Excluded: {excluded_str}")-- # Language breakdown- if stats.lang_counts:- top_langs = sorted(stats.lang_counts.items(), key=lambda x: -x[1])[:6]- lang_str = ", ".join(f"{lang} {count:,}" for lang, count in top_langs)- rest_count = sum(- c for _, c in sorted(stats.lang_counts.items(), key=lambda x: -x[1])[6:]- )- if rest_count:- lang_str += f", other {rest_count:,}"- progress.on_message("info", f" Languages: {lang_str}")-- return parsed_files, file_infos, repo_structure, source_map, graph_builder, stats, tech_items+ return (+ parsed_files,+ file_infos,+ repo_structure,+ source_map,+ graph_builder,+ traverser.stats,+ tech_items,+ )async def reparse_for_resume(diff --git a/packages/core/src/repowise/core/pipeline/progress.py b/packages/core/src/repowise/core/pipeline/progress.pyindex 7b3e70abd..ca70af783 100644--- a/packages/core/src/repowise/core/pipeline/progress.py+++ b/packages/core/src/repowise/core/pipeline/progress.py@@ -9,12 +9,31 @@ Phase names (stable strings used across all implementations):from __future__ import annotations-from typing import Protocol, runtime_checkable+from typing import Any, Protocol, runtime_checkableimport structloglogger = structlog.get_logger(__name__)+# Top-level stages of a pipeline run, in order. These are the ones a user+# counts ("Phase 2 of 4"); the phase names above are the sub-steps inside them.+STAGE_INGESTION = "ingestion"+STAGE_ANALYSIS = "analysis"+++def emit_stage(progress: Any, stage: str) -> None:+ """Announce a top-level stage, for callbacks that render stage headers.++ Optional, like ``on_phase_done``: the pipeline runs headlessly as well as+ under a CLI, so the header itself belongs to whoever is drawing the screen+ (which is also the only party that knows how many stages follow this one).+ """+ if progress is None:+ return+ fn = getattr(progress, "on_stage", None)+ if fn is not None:+ fn(stage)+@runtime_checkableclass ProgressCallback(Protocol):@@ -40,6 +59,13 @@ class ProgressCallback(Protocol):"""Emit a free-form message. *level* is 'info', 'warning', or 'error'."""...+ def on_stage(self, stage: str) -> None:+ """Called when a top-level stage begins. Optional — reach it via+ :func:`emit_stage`, which no-ops for callbacks that do not render+ stage headers.+ """+ ...+class LoggingProgressCallback:"""Emits progress as structured log messages. Suitable for headless workers (Modal)."""@@ -55,3 +81,6 @@ class LoggingProgressCallback:def on_message(self, level: str, text: str) -> None:getattr(logger, level, logger.info)(text)++ def on_stage(self, stage: str) -> None:+ logger.info("stage_start", stage=stage)diff --git a/tests/unit/cli/test_init_failure_reporting.py b/tests/unit/cli/test_init_failure_reporting.pyindex cc8f7133f..5bc7b9f23 100644--- a/tests/unit/cli/test_init_failure_reporting.py+++ b/tests/unit/cli/test_init_failure_reporting.py@@ -115,6 +115,67 @@ def test_run_repo_generation_reports_failures(tmp_path, monkeypatch):assert "repowise init --resume" in output+def test_recorded_cost_includes_the_knowledge_graph_enrichment(tmp_path, monkeypatch):+ """Layer naming and the guided tour are real model calls billed through the+ same tracker as the pages, so the figure the completion panel prints has to+ be read after enrichment. Capturing it earlier printed a number the+ llm_costs table disagreed with."""+ jobs_dir = tmp_path / ".repowise" / "jobs"+ jobs_dir.mkdir(parents=True, exist_ok=True)+ JobSystem(jobs_dir).create_job(str(tmp_path), SimpleNamespace(max_concurrency=1), "m", "m")++ class _Tracker:+ def __init__(self):+ self.session_cost = 1.00++ tracker = _Tracker()++ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation.console.print", lambda *a, **k: None+ )+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation.run_async",+ lambda coro: [_page("file_page:a")],+ )+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation.build_cost_tracker",+ lambda *a, **k: tracker,+ )+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation.flush_cost_tracker", lambda t: None+ )++ # Enrichment spends another $0.25 through the same tracker.+ def _enrich(**_kwargs):+ tracker.session_cost += 0.25++ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation._enrich_knowledge_graph", _enrich+ )++ result = SimpleNamespace(+ repo_name="test_repo",+ parsed_files=[],+ source_map={},+ graph_builder=MagicMock(),+ repo_structure=MagicMock(),+ git_meta_map={},+ )++ run_repo_generation(+ repo_path=tmp_path,+ result=result,+ provider=SimpleNamespace(provider_name="mock", model_name="mock-model"),+ gen_config=SimpleNamespace(max_concurrency=1, deterministic=False),+ concurrency=1,+ embedder_name_resolved="mock",+ resume=False,+ verbose=False,+ )++ assert result.llm_cost_usd == 1.25++@pytest.mark.parametrize("verbose_flag", [True, False])def test_run_repo_generation_zero_failures(tmp_path, monkeypatch, verbose_flag):"""When no pages fail, run_repo_generation prints success summary only when verbose, stays silent otherwise."""@@ -205,6 +266,9 @@ def test_show_completion_panel_with_failures(monkeypatch):repo_structure=SimpleNamespace(root_language_distribution={"Python": 1.0}),generated_pages=[_page("file_page:a")],failed_page_ids=["file_page:b", "module_page:m1"],+ # The full-mode panel reports the index it built, same as index-only.+ file_count=3,+ symbol_count=42,)provider = SimpleNamespace(provider_name="mock", model_name="mock-model")@@ -236,7 +300,9 @@ def test_run_repo_generation_uses_exact_job_id_when_provided(tmp_path, monkeypattarget_job_id = js.create_job(str(tmp_path), config_mock, "mock", "mock-model")js.fail_page(target_job_id, "file_page:target_failure.ts", "Target error")- monkeypatch.setattr("repowise.cli.commands.init_cmd.generation.console.print", lambda *a, **kw: None)+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation.console.print", lambda *a, **kw: None+ )monkeypatch.setattr("repowise.cli.commands.init_cmd.generation.run_async",lambda coro: [_page("file_page:lib/c.ts")],@@ -274,4 +340,3 @@ def test_run_repo_generation_uses_exact_job_id_when_provided(tmp_path, monkeypat)assert getattr(result, "failed_page_ids", None) == ["file_page:target_failure.ts"]-diff --git a/tests/unit/cli/test_init_ux.py b/tests/unit/cli/test_init_ux.pynew file mode 100644index 000000000..e0d71e16b--- /dev/null+++ b/tests/unit/cli/test_init_ux.py@@ -0,0 +1,260 @@+"""First-run `repowise init` screen behaviour.++Covers the two pieces of the UX pass that are wiring rather than copy: the+stage-header signal the pipeline emits for phases 1 and 2, and the keyless+detection that decides whether picking a provider asks for an API key.+"""++from __future__ import annotations++from io import StringIO+from typing import Any++import pytest+from rich.console import Console+from rich.progress import Progress, TextColumn++from repowise.cli.ui import provider_selection+from repowise.cli.ui.progress import RichProgressCallback+from repowise.core.pipeline.progress import STAGE_ANALYSIS, STAGE_INGESTION, emit_stage+++def _console() -> tuple[Console, StringIO]:+ buf = StringIO()+ return Console(file=buf, force_terminal=False, width=100), buf+++# --- stage headers ---------------------------------------------------------+++def test_stage_renders_the_same_numbered_rule_as_the_later_phases() -> None:+ """Phases 1 and 2 used to be plain green lines while 3 and 4 got rules,+ so the first separator a first-time user saw read "Phase 3 of 4"."""+ console, buf = _console()+ with Progress(TextColumn("{task.description}"), console=console) as bar:+ RichProgressCallback(bar, console, total_phases=4).on_stage(STAGE_INGESTION)++ out = buf.getvalue()+ assert "Phase 1 of 4" in out+ assert "Ingestion" in out+ assert "Walking the tree" in out+++def test_analysis_is_phase_two() -> None:+ console, buf = _console()+ with Progress(TextColumn("{task.description}"), console=console) as bar:+ RichProgressCallback(bar, console, total_phases=4).on_stage(STAGE_ANALYSIS)++ assert "Phase 2 of 4" in buf.getvalue()+++def test_a_callback_without_a_phase_count_draws_no_header() -> None:+ """The workspace flow reuses this callback per repo and prints its own+ per-repo header; a "Phase 1 of 4" rule a dozen times over would be wrong."""+ console, buf = _console()+ with Progress(TextColumn("{task.description}"), console=console) as bar:+ RichProgressCallback(bar, console).on_stage(STAGE_INGESTION)++ assert "Phase" not in buf.getvalue()+++def test_unknown_stage_is_ignored() -> None:+ console, buf = _console()+ with Progress(TextColumn("{task.description}"), console=console) as bar:+ RichProgressCallback(bar, console, total_phases=4).on_stage("not_a_stage")++ assert "Phase" not in buf.getvalue()+++def test_emit_stage_no_ops_for_a_callback_that_does_not_render_headers() -> None:+ """Headless callbacks (Modal, the server job executor) never grew the+ method; the pipeline must not require it of them."""++ class Headless:+ def on_message(self, level: str, text: str) -> None: # pragma: no cover - unused+ raise AssertionError("on_stage must not fall through to on_message")++ emit_stage(Headless(), STAGE_INGESTION)+ emit_stage(None, STAGE_INGESTION)+++def test_emit_stage_reaches_through_a_wrapping_callback() -> None:+ """The real init path wraps the Rich callback in PhaseTimingRecorder and+ HookProgressCallback, both of which forward by ``__getattr__``."""+ from repowise.core.pipeline import PhaseTimingRecorder+ from repowise.core.registry import HookProgressCallback++ seen: list[str] = []++ class Inner:+ def on_stage(self, stage: str) -> None:+ seen.append(stage)++ emit_stage(HookProgressCallback(PhaseTimingRecorder(Inner())), STAGE_ANALYSIS)+ assert seen == [STAGE_ANALYSIS]+++def test_stage_header_keys_match_the_core_stage_constants() -> None:+ """progress.py spells the keys out rather than importing them, to keep the+ pipeline package off the CLI's import path. This is what stops that from+ becoming a silent drift."""+ from repowise.cli.ui.progress import _STAGE_HEADERS++ assert set(_STAGE_HEADERS) == {STAGE_INGESTION, STAGE_ANALYSIS}+++def test_the_progress_module_does_not_drag_in_the_pipeline_package() -> None:+ """``repowise.core.pipeline.__init__`` eagerly imports the orchestrator and+ persist layer. Every CLI call site defers it into a function body; importing+ it at module scope to read two string constants put ~170ms on the front of+ every ``repowise`` invocation, including the post-commit hook."""+ import subprocess+ import sys++ probe = "import repowise.cli.ui.progress, sys; print('repowise.core.pipeline' in sys.modules)"+ out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, check=True)+ assert out.stdout.strip() == "False", (+ "importing repowise.cli.ui.progress pulled in repowise.core.pipeline"+ )+++# --- keyless provider detection --------------------------------------------+++def test_ollama_is_ready_when_the_endpoint_answers(monkeypatch: Any) -> None:+ """It takes no API key, so reachability is the only question worth asking."""+ monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)+ monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: True)+ monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))+ monkeypatch.setattr(provider_selection, "_detect_opencode_status", lambda: False)++ assert provider_selection._detect_provider_status()["ollama"] == "http://localhost:11434"+++def test_ollama_is_not_ready_when_nothing_is_listening(monkeypatch: Any) -> None:+ monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)+ monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))+ monkeypatch.setattr(provider_selection, "_detect_opencode_status", lambda: False)++ assert "ollama" not in provider_selection._detect_provider_status()+++def test_ollama_base_url_honours_the_env_var(monkeypatch: Any) -> None:+ monkeypatch.setenv("OLLAMA_BASE_URL", "http://gpu-box:9999")+ assert provider_selection.ollama_base_url() == "http://gpu-box:9999"+++ ("base_url", "expected"),+ [+ ("http://localhost:11434", ("localhost", 11434)),+ ("http://gpu-box:9999", ("gpu-box", 9999)),+ ("http://gpu-box", ("gpu-box", 11434)),+ ("https://ollama.internal", ("ollama.internal", 443)),+ # A bare host:port is a natural thing to export; urlparse would+ # otherwise read "localhost" as the scheme.+ ("localhost:11434", ("localhost", 11434)),+ ],+)+def test_ollama_endpoint_parses_the_usable_forms(+ monkeypatch: Any, base_url: str, expected: tuple[str, int]+) -> None:+ monkeypatch.setenv("OLLAMA_BASE_URL", base_url)+ assert provider_selection._ollama_endpoint() == expected+++ "base_url",+ [+ "http://localhost:abc", # ValueError from the .port property+ "http://localhost:99999", # port out of range, also ValueError+ "unix:///var/run/ollama.sock", # no TCP host to probe+ "http://", # nothing left after the scheme+ ],+)+def test_an_unusable_ollama_url_is_rejected_rather_than_probing_localhost(+ monkeypatch: Any, base_url: str+) -> None:+ """``parsed.port`` raises rather than returning None, and falling back to+ localhost would report someone's typo'd remote box as ready and defer the+ failure to the first generation call."""+ monkeypatch.setenv("OLLAMA_BASE_URL", base_url)+ assert provider_selection._ollama_endpoint() is None+ # Must not raise, and must not claim the local daemon on this machine.+ assert provider_selection._detect_ollama_status() is False+++def test_a_broken_provider_config_is_a_click_error_not_a_traceback(+ monkeypatch: Any, tmp_path: Any+) -> None:+ """Everything the provider constructor reads is user input. httpx raises+ InvalidURL for a typo'd OLLAMA_BASE_URL, and that escaped every caller's+ handler and killed `repowise init` outright."""+ import click++ from repowise.cli.helpers import resolve_provider++ for var in ("GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"):+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:abc")++ with pytest.raises(click.ClickException) as caught:+ resolve_provider("ollama", None, tmp_path)++ assert "Could not set up the ollama provider" in str(caught.value)+++def test_an_unusable_ollama_url_says_so_instead_of_blaming_the_daemon(+ monkeypatch: Any,+) -> None:+ monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:abc")+ rendered = "\n".join(provider_selection._ollama_setup_lines())+ assert "not a host repowise can reach" in rendered+ assert "Nothing is listening" not in rendered+++def test_the_keyless_providers_get_setup_help_instead_of_a_key_prompt() -> None:+ """Ollama used to be registered like a hosted provider, so selecting it+ asked for an API key it does not have and bounced forever on Enter."""+ assert set(provider_selection._LOCAL_PROVIDER_SETUP) == {"codex_cli", "opencode", "ollama"}+ for name, lines in provider_selection._LOCAL_PROVIDER_SETUP.items():+ rendered = "\n".join(lines()).lower()+ assert rendered.strip(), f"{name} has no setup help"+ assert "no api key here" in rendered or "no key needed" in rendered, (+ f"{name}'s help does not say there is no key to paste"+ )+++def test_selecting_an_unreachable_ollama_never_prompts_for_a_key(monkeypatch: Any) -> None:+ console, buf = _console()+ monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)+ monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))+ monkeypatch.setattr(provider_selection, "_detect_opencode_status", lambda: False)++ def boom(*_args: object, **_kwargs: object) -> str:+ raise AssertionError("ollama has no API key to prompt for")++ monkeypatch.setattr(provider_selection, "_prompt_api_key", boom)++ # Nothing configured on the first render; on the recursive re-render that+ # follows the ollama help, openai is configured so the run can terminate.+ renders: list[int] = []++ def detect() -> dict[str, str]:+ renders.append(1)+ return {} if len(renders) == 1 else {"openai": "OPENAI_API_KEY"}++ monkeypatch.setattr(provider_selection, "_detect_provider_status", detect)++ providers = list(provider_selection._PROVIDER_ENV)+ answers = iter([str(providers.index("ollama") + 1), str(providers.index("openai") + 1)])+ monkeypatch.setattr(provider_selection.Prompt, "ask", lambda *a, **kw: next(answers))++ chosen = provider_selection._interactive_provider_name(console, None)++ assert len(renders) == 2, "picking an unreachable ollama should re-render the table"++ out = buf.getvalue()+ assert chosen == "openai"+ assert "runs on your machine" in out+ assert "ollama serve" in outdiff --git a/tests/unit/cli/test_ui_reasoning.py b/tests/unit/cli/test_ui_reasoning.pyindex 736eca56d..c6bf81c74 100644--- a/tests/unit/cli/test_ui_reasoning.py+++ b/tests/unit/cli/test_ui_reasoning.py@@ -79,7 +79,9 @@ def test_interactive_advanced_config_can_skip_reasoning_prompt(def test_interactive_provider_config_select_uses_model_reasoning_options(monkeypatch: Any,) -> None:- monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda: {"gemini": "GEMINI_API_KEY"})+ monkeypatch.setattr(+ provider_selection, "_detect_provider_status", lambda: {"gemini": "GEMINI_API_KEY"}+ )monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))monkeypatch.setattr(provider_selection,@@ -111,7 +113,7 @@ def test_interactive_provider_config_select_uses_model_reasoning_options(type: Any = None,**_kwargs: object,) -> Any:- if text.strip() == "Reasoning":+ if text.strip() == "Reasoning effort":assert tuple(type.choices) == ("auto", "low", "high")return "high"return default