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 plan screen replaces the run of start questions (#4253)

Raghav Chamadiya3dd6bd875ccf
diff --git a/docs/scale/WORKTREES.md b/docs/scale/WORKTREES.md
index 1bb0182c8..770ac641e 100644
--- a/docs/scale/WORKTREES.md
+++ b/docs/scale/WORKTREES.md
@@ -11,10 +11,12 @@ repowise init # seeds from the base checkout, then runs an incremental up
repowise update # same: an unindexed worktree seeds itself first, then updates
```
-repowise detects that the directory is a linked worktree, derives the base checkout from git's own metadata (no path needed from you), copies the base's `.repowise/` index, and delegates to the incremental update so only the files that differ on your branch are re-processed. You'll see a one-line notice:
+repowise detects that the directory is a linked worktree, derives the base checkout from git's own metadata (no path needed from you), copies the base's `.repowise/` index, and delegates to the incremental update so only the files that differ on your branch are re-processed. init says so before it hands over:
```
-[worktree] Linked worktree of /path/to/base detected; seeding its index.
+This is a linked worktree of /path/to/base, which is already indexed. init copies that index
+and catches it up with repowise update instead of indexing from scratch.
+Pass --no-seed for a full init here.
```
Agents and git hooks benefit without any setup: a post-commit hook or a coding agent running `repowise update` inside an unindexed worktree gets the seed-then-update path instead of an error.
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 a91ea8099..95ad8435d 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py
@@ -106,13 +106,22 @@ def save_run_config(run: InitRun) -> None:
def register_clients(run: InitRun) -> None:
"""Global client registration, then the workspace's distill verdict."""
- from repowise.cli.editor_integrations.global_mcp import confirm_global_mcp
+ from repowise.cli.editor_integrations.global_mcp import (
+ REGISTER_LATER_COMMAND,
+ confirm_global_mcp,
+ )
no_editor_setup = not run.opts.editor_setup
- if confirm_global_mcp(
+ if run.global_mcp_consent is False:
+ console.print(
+ " [dim]Global Claude config left as is (this repo only). Run "
+ f"'{REGISTER_LATER_COMMAND}' to point it here later.[/dim]"
+ )
+ elif confirm_global_mcp(
console,
run.repo_path,
- yes=run.opts.yes,
+ # Answered on the plan screen: print old and new, do not ask again.
+ yes=run.opts.yes or run.global_mcp_consent is True,
no_editor_setup=no_editor_setup,
):
run.mcp_repointed = _mcp_entry_moves(run.repo_path)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
index 49655ed34..5c5aa5a47 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py
@@ -70,15 +70,17 @@ class InitRun:
repo_path: Path
start: float
is_interactive: bool = False
- # The two axes the interactive menu resolves: docs on or off, and whether
- # the advanced prompts ran. They gate the editor-files question.
+ #: This run made ``.repowise/``, so quitting before indexing removes it again.
+ repowise_dir_created: bool = False
+ # Whether a model writes the documentation (the plan screen's answer).
generate_docs: bool = True
- customize: bool = False
# Advanced-mode answers, None until chosen. Each loses to its flag and
# wins over config.yaml.
language_choice: str | None = None
max_file_pages_choice: int | None = None
editor_options: Any = None
+ #: The plan screen's answer to repointing the global MCP entry; None = not asked.
+ global_mcp_consent: bool | None = None
config: dict[str, Any] = field(default_factory=dict)
language: str = "en"
max_file_pages: int | None = None
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_plan.py b/packages/cli/src/repowise/cli/commands/init_cmd/_plan.py
new file mode 100644
index 000000000..6c5a6c378
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_plan.py
@@ -0,0 +1,269 @@
+"""The plan screen of an interactive single-repo init: what each key changes."""
+
+from __future__ import annotations
+
+import contextlib
+from dataclasses import dataclass, replace
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import console, load_config
+from repowise.cli.ui import (
+ WARN,
+ agent_providers_set_up,
+ interactive_advanced_config,
+ interactive_provider_config_select,
+ should_offer_fast_mode,
+)
+from repowise.cli.ui.plan_screen import (
+ EDIT,
+ MODEL,
+ QUIT,
+ THIS_REPO,
+ ModelPrice,
+ PlanState,
+ RunShape,
+ build_offer,
+ end_of_input_is_eof,
+ model_calls_for,
+ price_model,
+ read_plan_key,
+ render_plan,
+)
+from repowise.cli.ui.subscription import SubscriptionContext
+
+from ._options import InitRun
+
+
+@dataclass
+class _Answers:
+ """What the keys have changed so far."""
+
+ chosen: ModelPrice | None = None
+ selection: Any = None
+ sync: bool = True
+ this_repo_only: bool = False
+
+
+def _outside_lines(run: InitRun) -> tuple[str, ...]:
+ """Old and new target of the global MCP entry, empty when it would not move."""
+ from repowise.cli.editor_integrations.global_mcp import read_global_mcp_target
+
+ try:
+ target = read_global_mcp_target(run.repo_path)
+ # A probe failure never blocks the screen; JSONDecodeError is a ValueError.
+ except (OSError, ValueError, KeyError, TypeError):
+ return ()
+ return tuple(target.summary_lines()) if target.repoints else ()
+
+
+def _embedders(run: InitRun) -> tuple[str, str]:
+ """``(free run embedder, model run embedder)``, as the run would resolve them."""
+ from repowise.cli.providers import resolve_embedder, template_run_embedder
+ from repowise.cli.providers.embedders import embedder_was_requested
+
+ resolved = resolve_embedder(run.opts.embedder_name)
+ requested = embedder_was_requested(
+ run.opts.embedder_name, load_config(run.repo_path).get("embedder")
+ )
+ return template_run_embedder(resolved, requested), resolved
+
+
+def _state(run: InitRun, base: PlanState, answers: _Answers) -> PlanState:
+ """The screen for the run as it stands."""
+ from repowise.cli.editor_setup import planned_agents
+
+ from ._prepare import _editor_options
+
+ free_embedder, model_embedder = _embedders(run)
+ agents = planned_agents(run.repo_path, _editor_options(run)) if base.editor_setup else ()
+ return replace(
+ base,
+ run_mode=run.opts.run_mode,
+ chosen=answers.chosen,
+ free_embedder=free_embedder,
+ model_embedder=model_embedder,
+ agents=agents,
+ sync=answers.sync,
+ this_repo_only=answers.this_repo_only,
+ commit_limit=_commit_limit(run),
+ )
+
+
+def _commit_limit(run: InitRun) -> int:
+ """The commit cap the run will use: flag, then config.yaml, then the default."""
+ from repowise.core.ingestion.git_indexer._constants import _DEFAULT_COMMIT_LIMIT
+
+ limit = (
+ run.opts.commit_limit
+ or load_config(run.repo_path).get("commit_limit")
+ or _DEFAULT_COMMIT_LIMIT
+ )
+ return max(1, min(int(limit), 10000))
+
+
+def _shape(run: InitRun, scan: Any) -> RunShape:
+ return RunShape(scan, onboarding=run.opts.onboarding, concurrency=run.opts.concurrency)
+
+
+def _base_state(run: InitRun, scan: Any, prefer: tuple[str, ...]) -> PlanState:
+ """The parts that do not change while the screen is up (detection, the probe)."""
+ from repowise.cli.editor_setup import is_editor_setup_disabled
+ from repowise.cli.ui.provider_selection import _detect_provider_status
+
+ opts = run.opts
+ editor_setup = not is_editor_setup_disabled(not opts.editor_setup)
+ with console.status(" Checking for a model…"):
+ offer = build_offer(_detect_provider_status(run.repo_path), prefer, _shape(run, scan))
+ return PlanState(
+ repo_name=run.repo_path.name or str(run.repo_path),
+ scan=scan,
+ offer=offer,
+ editor_setup=editor_setup,
+ outside=_outside_lines(run) if editor_setup else (),
+ large_repo=should_offer_fast_mode(scan),
+ )
+
+
+def _pick_model(run: InitRun, scan: Any, prefer: tuple[str, ...], answers: _Answers) -> None:
+ """``m``: the picker, or back to built from code when a model is already picked."""
+ if answers.chosen is not None:
+ answers.chosen = answers.selection = None
+ return
+ opts = run.opts
+ if opts.run_mode == "fast":
+ # A model writes documentation, which an index-only run skips.
+ run.opts = replace(opts, run_mode="standard")
+ console.print(" [dim]Run mode back to standard: fast mode writes no documentation.[/dim]")
+ selection = interactive_provider_config_select(
+ console,
+ opts.model,
+ opts.reasoning,
+ repo_path=run.repo_path,
+ save_key=opts.save_key,
+ subscription=SubscriptionContext(
+ prefer=prefer,
+ model_calls=model_calls_for(_shape(run, scan)),
+ concurrency=opts.concurrency,
+ allow_skip=True,
+ ),
+ )
+ if selection is None:
+ return
+ answers.selection = selection
+ answers.chosen = price_model(selection.provider_name, selection.model, _shape(run, scan))
+
+
+def _edit_plan(run: InitRun, scan: Any, editor_setup: bool, answers: _Answers) -> None:
+ """``e``: the advanced options, the agent checklist and the sync hook."""
+ from repowise.cli.editor_setup import select_agents_interactively
+
+ from ._prepare import _editor_options
+ from ._questions import _apply_advanced_answers
+
+ run.generate_docs = answers.chosen is not None
+ adv = interactive_advanced_config(
+ console,
+ scan=scan,
+ allow_fast=True,
+ prompt_reasoning=False,
+ generate_docs=run.generate_docs,
+ wiki_style=run.opts.wiki_style,
+ language=run.opts.language_opt,
+ commit_limit=run.opts.commit_limit,
+ )
+ _apply_advanced_answers(run, adv)
+ if run.opts.run_mode == "fast":
+ answers.chosen = answers.selection = None
+ if editor_setup:
+ run.editor_options = select_agents_interactively(
+ console, run.repo_path, _editor_options(run)
+ )
+ answers.sync = click.confirm(
+ " Keep the index in sync after each commit (post-commit hook)?",
+ default=answers.sync,
+ )
+
+
+def _apply(run: InitRun, base: PlanState, answers: _Answers) -> None:
+ """Enter: fold the plan into the run, so nothing later asks again."""
+ opts = run.opts
+ selection = answers.selection
+ run.generate_docs = selection is not None
+ if selection is not None:
+ opts = replace(
+ opts,
+ index_only=False,
+ provider_name=selection.provider_name,
+ model=selection.model,
+ reasoning=selection.reasoning,
+ )
+ else:
+ opts = replace(opts, index_only=True)
+ if base.editor_setup and opts.hook is None:
+ opts = replace(opts, hook=answers.sync)
+ run.opts = opts
+ if base.can_keep_global:
+ run.global_mcp_consent = not answers.this_repo_only
+
+
+def _leave_repo_as_it_was(run: InitRun) -> None:
+ """Remove the ``.repowise/`` this run made, when nothing has been put in it."""
+ if not run.repowise_dir_created:
+ return
+ # Not empty means the picker saved a key there, and that stays.
+ with contextlib.suppress(OSError):
+ (run.repo_path / ".repowise").rmdir()
+
+
+def _until_enter(
+ run: InitRun, scan: Any, prefer: tuple[str, ...], base: PlanState, answers: _Answers
+) -> None:
+ """Render, read a key, act on it; return on Enter."""
+ while True:
+ state = _state(run, base, answers)
+ console.print()
+ render_plan(console, state)
+ action = read_plan_key(console, state)
+ if action == QUIT:
+ _leave_repo_as_it_was(run)
+ console.print(" [dim]Nothing indexed.[/dim]")
+ raise click.exceptions.Exit(0)
+ if action == MODEL:
+ _pick_model(run, scan, prefer, answers)
+ elif action == EDIT:
+ _edit_plan(run, scan, base.editor_setup, answers)
+ elif action == THIS_REPO:
+ answers.this_repo_only = not answers.this_repo_only
+ else:
+ return
+
+
+def run_plan_screen(run: InitRun, scan: Any) -> None:
+ """Show the plan, act on keys until Enter, then fold the answers into *run*.
+
+ The first read is the probe for a terminal that cannot answer (Windows
+ Git Bash ``< /dev/null``, pty wrappers, ``docker run -t`` without -i):
+ EOF drops to the non-interactive path instead of dying on a question
+ nobody can hear. Only EOFError is caught; Ctrl-C still stops the run.
+ """
+ prefer = agent_providers_set_up(run.repo_path)
+ base = _base_state(run, scan, prefer)
+ answers = _Answers(sync=run.opts.hook if run.opts.hook is not None else True)
+ # Restored on EOF, so the defaults path never runs half an answer.
+ before = (run.opts, run.generate_docs, run.editor_options)
+ try:
+ # The questions behind m and e end the same way as the key read.
+ with end_of_input_is_eof():
+ _until_enter(run, scan, prefer, base, answers)
+ except EOFError:
+ run.opts, run.generate_docs, run.editor_options = before
+ run.is_interactive = False
+ console.print(
+ f"\n[{WARN}]No answer available on stdin[/] "
+ "[dim]- continuing with defaults. Pass --yes to skip the "
+ "questions, or --prose / --no-prose to choose directly.[/dim]"
+ )
+ return
+ _apply(run, base, answers)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py b/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
index 12b546342..19bd2c066 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
@@ -15,10 +15,7 @@ from repowise.cli.editor_integrations.defaults import (
get_default_integration_overrides,
get_default_project_file_overrides,
)
-from repowise.cli.editor_setup import (
- resolve_editor_setup_options,
- select_agents_interactively,
-)
+from repowise.cli.editor_setup import resolve_editor_setup_options
from repowise.cli.errors import reasoned_error
from repowise.cli.helpers import (
console,
@@ -65,6 +62,7 @@ def _interactive_gate(
def _start_run(opts: InitOptions, repo_path: Path, start: float) -> InitRun:
"""Prepare ``.repowise/``, logging and the resume mode, then open the run."""
+ dir_created = not (repo_path / ".repowise").exists()
ensure_repowise_dir(repo_path)
load_dotenv(repo_path)
@@ -98,13 +96,20 @@ def _start_run(opts: InitOptions, repo_path: Path, start: float) -> InitRun:
start=start,
is_interactive=is_interactive,
generate_docs=not opts.index_only,
+ repowise_dir_created=dir_created,
)
def _editor_options(run: InitRun) -> Any:
- """Which editor files and integrations this run writes."""
+ """Which editor files and integrations this run writes.
+
+ The agent checklist on the plan screen's ``e`` sets ``run.editor_options``;
+ otherwise the flags and detection decide, with no question.
+ """
+ if run.editor_options is not None:
+ return run.editor_options
opts = run.opts
- editor_options = resolve_editor_setup_options(
+ return resolve_editor_setup_options(
disabled_project_files=get_default_disabled_project_files(
no_claude_md=opts.no_claude_md,
),
@@ -115,13 +120,6 @@ def _editor_options(run: InitRun) -> Any:
codex_setup=opts.codex_setup,
),
)
- # Ask which agents to wire up whenever the user is engaging interactively:
- # either generating docs or customizing an index-only run. Not asked when
- # editor setup is off: every answer would be discarded by
- # `write_editor_project_files`.
- if opts.editor_setup and run.is_interactive and (run.generate_docs or run.customize):
- editor_options = select_agents_interactively(console, run.repo_path, editor_options)
- return editor_options
def _resolve_settings(run: InitRun) -> None:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_provider.py b/packages/cli/src/repowise/cli/commands/init_cmd/_provider.py
index f1af1926a..7b0492f87 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_provider.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_provider.py
@@ -10,24 +10,28 @@ import click
from repowise.cli.errors import reasoned_error
from repowise.cli.helpers import console, resolve_explicit_provider_or_prompt, run_async
from repowise.cli.providers import resolve_embedder_choice, template_run_embedder
-from repowise.cli.ui import OK, OWL_SPINNER, VALUE, WARN, print_index_only_intro
+from repowise.cli.ui import OK, OWL_SPINNER, VALUE, WARN
from repowise.cli.ui.mode_names import BUILT_FROM_CODE, INDEX_ONLY, written_by
from ._options import InitRun
def announce_index_only(run: InitRun) -> None:
- """Tell the user what a run without a model builds."""
+ """Tell the user what a run without a model builds.
+
+ An interactive run already showed it on the plan screen, so nothing is
+ printed after it.
+ """
fast = run.opts.run_mode == "fast"
- if run.is_interactive:
- print_index_only_intro(console, fast=fast)
- return
- mode = INDEX_ONLY if fast else BUILT_FROM_CODE
- console.print(f"[bold]repowise init[/bold] · {mode} · {run.repo_path}")
- if fast:
- console.print("Indexing the graph and git history [dim](no documentation, no spend).[/dim]")
- else:
- console.print("Building documentation from code [dim](no model, no spend).[/dim]")
+ if not run.is_interactive:
+ mode = INDEX_ONLY if fast else BUILT_FROM_CODE
+ console.print(f"[bold]repowise init[/bold] · {mode} · {run.repo_path}")
+ if fast:
+ console.print(
+ "Indexing the graph and git history [dim](no documentation, no spend).[/dim]"
+ )
+ else:
+ console.print("Building documentation from code [dim](no model, no spend).[/dim]")
def _resolve_or_fall_back(run: InitRun) -> None:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_questions.py b/packages/cli/src/repowise/cli/commands/init_cmd/_questions.py
index 25a7e0f91..5b6848150 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_questions.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_questions.py
@@ -1,4 +1,4 @@
-"""The interactive questionnaire of a single-repo init."""
+"""The interactive part of a single-repo init: the plan screen and its answers."""
from __future__ import annotations
@@ -6,98 +6,11 @@ from dataclasses import replace
from typing import Any
from repowise.cli.helpers import console
-from repowise.cli.ui import (
- OWL_SPINNER,
- WARN,
- agent_providers_set_up,
- interactive_advanced_config,
- interactive_customize_offer,
- interactive_fast_mode_offer,
- interactive_generate_docs_toggle,
- interactive_mode_select,
- interactive_provider_config_select,
- model_call_count,
- print_banner,
- print_scan_summary,
- prompt_wiki_style,
- quick_repo_scan,
- should_offer_fast_mode,
-)
-from repowise.cli.ui.subscription import SubscriptionContext
+from repowise.cli.ui import OWL_SPINNER, print_banner, quick_repo_scan
from ._options import InitRun
-def _ask_mode(run: InitRun) -> None:
- """The mode menu, mapped onto the two axes (docs on/off, customize yes/no).
-
- ``sys.stdin.isatty()`` is not a reliable answer to "can I read from
- stdin". On Windows under Git Bash, ``repowise init < /dev/null`` reports a
- TTY and then reads EOF on the first question; the same goes for some pty
- wrappers and ``docker run -t`` without -i. Agents drive init through
- exactly those shapes, so the first prompt is the probe: if it cannot be
- answered, drop to the non-interactive path rather than dying on a question
- nobody can hear. Only EOFError is caught. A real Ctrl-C raises
- KeyboardInterrupt/Abort and must still stop the run.
- """
- try:
- mode = interactive_mode_select(console)
- except EOFError:
- run.is_interactive = False
- console.print(
- f"\n[{WARN}]No answer available on stdin[/] "
- "[dim]- continuing with defaults. Pass --yes to skip the "
- "questions, or --prose / --no-prose to choose directly.[/dim]"
- )
- return
-
- # full -> docs on, optional customize
- # index_only -> docs off, optional customize
- # advanced -> docs toggle, always customize
- if mode == "index_only":
- run.generate_docs = False
- run.customize = interactive_customize_offer(console, generate_docs=False)
- elif mode == "advanced":
- run.generate_docs = interactive_generate_docs_toggle(console)
- run.customize = True
- elif mode is not None: # full
- run.generate_docs = True
- run.customize = interactive_customize_offer(console, generate_docs=True)
- if mode is not None:
- run.opts = replace(run.opts, index_only=not run.generate_docs)
-
-
-def _ask_provider(run: InitRun, scan_info: Any = None) -> None:
- """Provider selection, only when docs will be generated.
-
- The scan's file count sizes the estimate shown beside a subscription CLI,
- from the same pre-index plan the server quotes.
- """
- from repowise.core.cost_estimator import approximate_generation_plan
-
- opts = run.opts
- files = getattr(scan_info, "total_files", 0)
- plans = approximate_generation_plan(files, onboarding=opts.onboarding) if files else []
- selection = interactive_provider_config_select(
- console,
- opts.model,
- opts.reasoning,
- repo_path=run.repo_path,
- save_key=opts.save_key,
- subscription=SubscriptionContext(
- prefer=agent_providers_set_up(run.repo_path),
- model_calls=model_call_count(plans),
- concurrency=opts.concurrency,
- ),
- )
- run.opts = replace(
- opts,
- provider_name=selection.provider_name,
- model=selection.model,
- reasoning=selection.reasoning,
- )
-
-
def _apply_advanced_answers(run: InitRun, adv: dict[str, Any]) -> None:
"""Fold the advanced-config answers into the run."""
opts = run.opts
@@ -137,55 +50,11 @@ def _apply_advanced_answers(run: InitRun, adv: dict[str, Any]) -> None:
run.opts = replace(opts, **changes)
-def _offer_fast_mode(run: InitRun, scan_info: Any) -> None:
- """No customization: still offer the fast first-index on large repos.
-
- Default yes for an index-only run (docs already opted out), no for a full
- run (the user explicitly asked for docs).
- """
- if (
- run.opts.run_mode != "fast"
- and should_offer_fast_mode(scan_info)
- and interactive_fast_mode_offer(console, scan_info, default_fast=not run.generate_docs)
- ):
- run.opts = replace(run.opts, run_mode="fast", index_only=True)
- run.generate_docs = False
-
-
def _ask_questions(run: InitRun) -> None:
- """The interactive questionnaire (TTY, no explicit flags)."""
- print_banner(console, repo_name=run.repo_path.name)
+ """The plan screen (TTY, no explicit flags), then the follow-ups its keys open."""
+ from ._plan import run_plan_screen
+
+ print_banner(console)
with console.status(" Scanning repository…", spinner=OWL_SPINNER):
scan_info = quick_repo_scan(run.repo_path)
- print_scan_summary(console, scan_info)
-
- _ask_mode(run)
- # ``is_interactive`` can have been cleared by an unanswerable menu, in
- # which case every remaining question here is unanswerable too.
- if run.generate_docs and run.is_interactive:
- _ask_provider(run, scan_info)
-
- if run.customize:
- adv = interactive_advanced_config(
- console,
- scan=scan_info,
- allow_fast=True,
- prompt_reasoning=False,
- generate_docs=run.generate_docs,
- wiki_style=run.opts.wiki_style,
- language=run.opts.language_opt,
- )
- _apply_advanced_answers(run, adv)
- elif run.is_interactive:
- _offer_fast_mode(run, scan_info)
-
- # Wiki style: prompt for a docs run when not already chosen (via the
- # --wiki-style flag or the advanced generation section). Index-only runs
- # generate no pages, so the question is skipped. --yes uses the default.
- if (
- run.generate_docs
- and run.opts.wiki_style is None
- and not run.opts.yes
- and run.is_interactive
- ):
- run.opts = replace(run.opts, wiki_style=prompt_wiki_style(console))
+ run_plan_screen(run, scan_info)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_seed.py b/packages/cli/src/repowise/cli/commands/init_cmd/_seed.py
index 6b93dbbf8..d871fc75c 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_seed.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_seed.py
@@ -36,8 +36,10 @@ def _seed_base(opts: InitOptions, repo_path: Path) -> Path | None:
seed_base = detected
if not opts.force:
console.print(
- f"[dim]\\[worktree][/dim] Linked worktree of {detected} detected; "
- f"seeding its index."
+ f"This is a linked worktree of {detected}, which is already "
+ "indexed. init copies that index and catches it up with "
+ "[bold]repowise update[/bold] instead of indexing from scratch.\n"
+ "[dim]Pass --no-seed for a full init here.[/dim]"
)
# ``--force`` asks for the re-index seeding exists to avoid, so the two do
@@ -120,6 +122,9 @@ def delegate_to_seeded_update(opts: InitOptions, repo_path: Path, scan: Any) ->
if opts.dry_run:
console.print("[dim]Dry run: Would seed worktree index and delegate to update.[/dim]")
return True
- console.print(f"[{OK}]Worktree index seeded successfully. Delegating to update...[/]")
+ console.print(
+ f"[{OK}]Index copied from {seed_base}.[/] Running [bold]repowise update[/bold] "
+ "to catch it up."
+ )
_run_seeded_update(opts, repo_path, scan)
return True
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index e5a9ee43f..18797c4b8 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -52,28 +52,19 @@ from ._prepare import (
_resolve_settings,
_start_run,
)
-from ._questions import (
- _apply_advanced_answers,
- _ask_mode,
- _ask_provider,
- _ask_questions,
- _offer_fast_mode,
-)
+from ._questions import _apply_advanced_answers, _ask_questions
from ._seed import delegate_to_seeded_update
from ._workspace_repos import check_repos_flag, split_repo_names
from .workspace import _workspace_init
__all__ = [
"_apply_advanced_answers",
- "_ask_mode",
- "_ask_provider",
"_ask_questions",
"_confirm_wiki_overwrite",
"_editor_options",
"_generate",
"_generate_with_model",
"_interactive_gate",
- "_offer_fast_mode",
"_prepare_single_repo",
"_print_structural_plan",
"_render_template_wiki",
@@ -161,7 +152,25 @@ def _run_workspace_init(opts: InitOptions, scan: Any) -> None:
# duplication caches, which are derived data.
help="Show the generation plan and cost estimate. Writes no documentation.",
)
[email protected]("--yes", "-y", is_flag=True, default=False, help="Skip cost confirmation prompt.")
+ "--yes",
+ "-y",
+ is_flag=True,
+ default=False,
+ help=(
+ "Start at once with every answer at its default. Skips the plan screen "
+ "and every question after it: documentation is written by a model only "
+ "when a provider is configured (an API key in the environment or "
+ ".repowise/.env), else built from code; a logged-in Claude Code, Codex "
+ "or OpenCode is used only with --provider; the cost confirmation is "
+ "accepted; advanced options keep their defaults (standard run mode at "
+ "any size, comprehensive style); the detected agents "
+ "are connected; the global repowise MCP entry is pointed here, with the "
+ "old and new target printed; the post-commit hook is installed and the "
+ "distill rewrite hook is not; and with --no-prose, documentation a "
+ "model wrote is replaced without asking."
+ ),
+)
@click.option(
"--resume",
is_flag=True,
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index ad265f126..5c51604e3 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -64,6 +64,7 @@ from repowise.cli.ui import (
progress_steps,
)
from repowise.cli.ui.mode_names import pages
+from repowise.cli.ui.subscription import SubscriptionContext
from repowise.core.ci.markdown import plural
from repowise.core.decision_lanes import record_decision_lanes
from repowise.core.docs_mode import docs_mode_state_fields
@@ -969,6 +970,7 @@ def _ask_workspace_mode(
adv = interactive_advanced_config(
console,
prompt_reasoning=False,
+ generate_docs=not answers.index_only,
wiki_style=answers.wiki_style,
language=answers.language,
)
@@ -986,7 +988,11 @@ def _ask_workspace_provider(
answers.reasoning,
repo_path=primary_repo.path,
save_key=save_key,
+ subscription=SubscriptionContext(allow_skip=True),
)
+ if selection is None:
+ answers.index_only = True
+ return
answers.provider_name = selection.provider_name
answers.model = selection.model
answers.reasoning = selection.reasoning
diff --git a/packages/cli/src/repowise/cli/editor_setup.py b/packages/cli/src/repowise/cli/editor_setup.py
index 1a8c118e4..c3d98d9c7 100644
--- a/packages/cli/src/repowise/cli/editor_setup.py
+++ b/packages/cli/src/repowise/cli/editor_setup.py
@@ -238,6 +238,36 @@ def _resolve_configured_project_file_optouts(
)
+def _installable_rows(rows: list[dict]) -> tuple[list[dict], list[dict]]:
+ """Split agent rows into those init can write and those it cannot."""
+ installable = {integration.integration_id for integration in _resolve_integrations(None)}
+ return (
+ [row for row in rows if row["id"] in installable],
+ [row for row in rows if row["id"] not in installable],
+ )
+
+
+def _ticked(rows: list[dict], options: EditorSetupOptions) -> set[str]:
+ """Detection's default selection, with each flag override applied."""
+ from repowise.cli.agent_targets.registry import default_selection
+
+ ticked = default_selection(rows)
+ for row in rows:
+ flagged = options.integration_overrides.get(row["id"])
+ if flagged is not None:
+ ticked = (ticked | {row["id"]}) if flagged else (ticked - {row["id"]})
+ return ticked
+
+
+def planned_agents(repo_path: Path, options: EditorSetupOptions) -> tuple[str, ...]:
+ """Display names of the agents init connects with *options*, without asking."""
+ from repowise.cli.agent_targets.registry import describe_agents
+
+ rows, _ = _installable_rows(describe_agents(repo_path))
+ ticked = _ticked(rows, options)
+ return tuple(row["display_name"] for row in rows if row["id"] in ticked)
+
+
def select_agents_interactively(
console_obj: Any,
repo_path: Path,
@@ -264,7 +294,7 @@ def select_agents_interactively(
as ``--codex``) is shown pre-ticked to match the flag, so accepting the
checklist re-applies what the flag already said.
"""
- from repowise.cli.agent_targets.registry import default_selection, describe_agents
+ from repowise.cli.agent_targets.registry import describe_agents
from repowise.cli.ui.agent_selection import AgentChoice, interactive_agent_select
# Offer only what this command can act on. The checklist is built from the
@@ -276,10 +306,7 @@ def select_agents_interactively(
#
# ``repowise agents add --target=<id>`` is the command for those, and the
# line below names it rather than leaving them invisible.
- rows = describe_agents(repo_path)
- installable = {integration.integration_id for integration in _resolve_integrations(None)}
- deferred = [row for row in rows if row["id"] not in installable]
- rows = [row for row in rows if row["id"] in installable]
+ rows, deferred = _installable_rows(describe_agents(repo_path))
for row in deferred:
if row["present"] or row["registrations"]:
console_obj.print(
@@ -287,11 +314,7 @@ def select_agents_interactively(
f"[bold]repowise agents add --target={row['id']}[/bold][/dim]"
)
- ticked = default_selection(rows)
- for row in rows:
- flagged = options.integration_overrides.get(row["id"])
- if flagged is not None:
- ticked = (ticked | {row["id"]}) if flagged else (ticked - {row["id"]})
+ ticked = _ticked(rows, options)
chosen = interactive_agent_select(
console_obj,
diff --git a/packages/cli/src/repowise/cli/ui/__init__.py b/packages/cli/src/repowise/cli/ui/__init__.py
index cc2de1e69..7e361b152 100644
--- a/packages/cli/src/repowise/cli/ui/__init__.py
+++ b/packages/cli/src/repowise/cli/ui/__init__.py
@@ -46,9 +46,6 @@ _LAZY: dict[str, str] = {
"format_bytes": "brand",
"format_elapsed": "brand",
"interactive_advanced_config": "mode_selection",
- "interactive_customize_offer": "mode_selection",
- "interactive_fast_mode_offer": "mode_selection",
- "interactive_generate_docs_toggle": "mode_selection",
"interactive_mode_select": "mode_selection",
"interactive_primary_select": "workspace_selection",
"interactive_provider_config_select": "provider_selection",
@@ -61,9 +58,7 @@ _LAZY: dict[str, str] = {
"model_call_count": "subscription",
"print_banner": "brand",
"print_completion_panel": "result_panels",
- "print_index_only_intro": "mode_selection",
"print_phase_header": "brand",
- "print_scan_summary": "repo_scanner",
"print_section": "brand",
"print_stage": "progress",
"progress_steps": "progress",
diff --git a/packages/cli/src/repowise/cli/ui/mode_selection.py b/packages/cli/src/repowise/cli/ui/mode_selection.py
index 074016366..354bfd892 100644
--- a/packages/cli/src/repowise/cli/ui/mode_selection.py
+++ b/packages/cli/src/repowise/cli/ui/mode_selection.py
@@ -1,4 +1,4 @@
-"""Interactive mode selection, fast-mode offer, and advanced configuration."""
+"""Interactive mode selection and advanced configuration."""
from __future__ import annotations
@@ -53,38 +53,6 @@ def should_offer_fast_mode(scan: RepoScanInfo | None) -> bool:
return scan is not None and scan.total_files > LARGE_REPO_FILE_THRESHOLD
-def interactive_fast_mode_offer(
- console: Console,
- scan: RepoScanInfo | None,
- *,
- default_fast: bool,
-) -> bool:
- """Offer fast mode after a large repo is detected. Returns True to use it.
-
- Shown only when :func:`should_offer_fast_mode` is true. Fast mode is a quick
- first index (dependency graph + essential git history, metrics in SQL) with
- no per-file blame, no co-change walk, and no LLM docs — backfillable later.
- """
- n = scan.total_files if scan else 0
- body = Text()
- body.append(" Large repository detected: ", style="bold")
- body.append(f"{n:,} files.\n\n", style=BRAND_STYLE)
- body.append(f" Fast mode runs a quick first index ({INDEX_ONLY.lower()}):\n", style="bold")
- body.append(" • dependency graph + essential git history\n")
- body.append(" • graph metrics materialized to SQL\n")
- body.append(" • no per-file blame, no co-change walk, no documentation\n\n")
- body.append(" You can add full git history and documentation later.\n", style="dim")
- console.print(
- Panel(
- body,
- title="[bold]Fast first index?[/bold]",
- border_style=BRAND,
- padding=(1, 2),
- )
- )
- return click.confirm(" Use fast mode?", default=default_fast)
-
-
def interactive_mode_select(console: Console, *, title: str | None = None) -> str:
"""Let the user choose full / index-only / advanced.
@@ -138,32 +106,6 @@ def interactive_mode_select(console: Console, *, title: str | None = None) -> st
return {"1": "full", "2": "index_only", "3": "advanced"}[choice]
-def interactive_generate_docs_toggle(console: Console) -> bool:
- """Advanced-mode entry: ask whether to generate AI wiki docs.
-
- Returns True for a full doc-generating run, False for an index-only run that
- still flows through the indexing-configuration prompts. Indexing (graph, git,
- code health, dead code) is free; only doc generation calls the LLM.
- """
- console.print()
- console.print(
- " [dim]Documentation written by a model calls the LLM (has a cost). Say no and "
- "you still\n get documentation, built from code, for free.[/dim]"
- )
- return click.confirm(" Have a model write the documentation?", default=True)
-
-
-def interactive_customize_offer(console: Console, *, generate_docs: bool) -> bool:
- """Offer to drop into advanced configuration from full / index-only modes.
-
- Returns True when the user wants to tune the defaults rather than accept
- them. The label tracks whether generation knobs are in scope.
- """
- what = "indexing & generation" if generate_docs else "indexing"
- console.print()
- return click.confirm(f" Customize {what} options?", default=False)
-
-
def prompt_wiki_style(console: Console) -> str:
"""Interactive picker for the wiki documentation style.
@@ -323,11 +265,13 @@ 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:
- print_section(
- console,
- "Run mode",
- f"standard = full depth · fast = {INDEX_ONLY.lower()}, quick graph + essential git",
- )
+ blurb = f"standard = full depth · fast = {INDEX_ONLY.lower()}, quick graph + essential git"
+ if is_large:
+ blurb += (
+ f"\n fast is the default here: it is recommended above "
+ f"{LARGE_REPO_FILE_THRESHOLD:,} files"
+ )
+ print_section(console, "Run mode", blurb)
result["run_mode"] = click.prompt(
" Run mode",
default="fast" if is_large else "standard",
@@ -376,8 +320,17 @@ def _prompt_exclude(
return patterns
-def _prompt_git(console: Console, scan: RepoScanInfo | None, result: dict[str, Any]) -> None:
- """Git-analysis section: commit limit + rename following."""
+def _prompt_git(
+ console: Console,
+ scan: RepoScanInfo | None,
+ result: dict[str, Any],
+ commit_limit: int | None = None,
+) -> None:
+ """Git-analysis section: commit limit + rename following.
+
+ *commit_limit* is the ``--commit-limit`` flag, offered as the default so
+ Enter keeps it.
+ """
commit_hint = ""
if scan and scan.total_commits:
commit_hint = f" (repo has ~{scan.total_commits:,} total commits)"
@@ -389,7 +342,7 @@ def _prompt_git(console: Console, scan: RepoScanInfo | None, result: dict[str, A
val = click.prompt(
" Max commits per file",
- default=_DEFAULT_COMMIT_LIMIT,
+ default=commit_limit or _DEFAULT_COMMIT_LIMIT,
type=int,
)
val = max(1, min(val, 10000))
@@ -547,6 +500,7 @@ def interactive_advanced_config(
generate_docs: bool = True,
wiki_style: str | None = None,
language: str | None = None,
+ commit_limit: int | None = None,
) -> dict[str, Any]:
"""Prompt for advanced init options, grouped into logical sections.
@@ -584,7 +538,7 @@ def interactive_advanced_config(
_prompt_scope(console, scan, result)
_prompt_run_mode(console, result, allow_fast=allow_fast, is_large=is_large)
patterns = _prompt_exclude(console, scan, result)
- _prompt_git(console, scan, result)
+ _prompt_git(console, scan, result, commit_limit)
# Asked in both branches: an index-only run renders file pages too (they need
# no model), so page volume is a real question either way. Fast mode renders
# no wiki at all, so there is nothing to bound.
@@ -664,40 +618,3 @@ def _resolve_embedder_from_env() -> str:
from repowise.cli.providers.keys import global_config_embedder
return global_config_embedder() or "mock"
-
-
-def print_index_only_intro(console: Console, *, fast: bool = False) -> None:
- """Show what index-only mode will do before starting.
-
- A forecast, so no border — nothing here is a thing to act on, and it used to
- carry the same box as the question two screens earlier.
- """
- title = INDEX_ONLY if fast else BUILT_FROM_CODE
- print_section(console, title, "No LLM calls. No API key. No cost.")
- console.print()
- # Bullets, not checkmarks: every green ✓ elsewhere in a run means "already
- # done", and this is a forecast.
- lines = [
- " [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 without a model",
- " [dim]•[/dim] Set up MCP server for AI assistants",
- ]
- if not fast:
- lines[5:5] = [
- " [dim]•[/dim] Build documentation from code: file, module, layer and",
- " cycle pages, the architecture diagram, the repo overview, API and",
- " infra pages, and the onboarding collection",
- ]
- for line in lines:
- console.print(line)
- console.print()
- if not fast:
- console.print(
- " [dim]The subsystem pages read as outlines, and decisions from PRs, commit "
- "history and comments wait for a model. Add a key and run "
- "[bold]repowise generate[/bold] to add both.[/dim]"
- )
- console.print()
diff --git a/packages/cli/src/repowise/cli/ui/plan_screen/__init__.py b/packages/cli/src/repowise/cli/ui/plan_screen/__init__.py
new file mode 100644
index 000000000..a5877a068
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/__init__.py
@@ -0,0 +1,43 @@
+"""The single start screen of an interactive ``repowise init``.
+
+``state`` gathers the facts, ``render`` prints them and ``keys`` reads the
+answer. The command layer owns what each key changes.
+"""
+
+from repowise.cli.ui.plan_screen.keys import (
+ EDIT,
+ MODEL,
+ QUIT,
+ START,
+ THIS_REPO,
+ end_of_input_is_eof,
+ read_plan_key,
+)
+from repowise.cli.ui.plan_screen.render import render_plan
+from repowise.cli.ui.plan_screen.state import (
+ ModelOffer,
+ ModelPrice,
+ PlanState,
+ RunShape,
+ build_offer,
+ model_calls_for,
+ price_model,
+)
+
+__all__ = [
+ "EDIT",
+ "MODEL",
+ "QUIT",
+ "START",
+ "THIS_REPO",
+ "ModelOffer",
+ "ModelPrice",
+ "PlanState",
+ "RunShape",
+ "build_offer",
+ "end_of_input_is_eof",
+ "model_calls_for",
+ "price_model",
+ "read_plan_key",
+ "render_plan",
+]
diff --git a/packages/cli/src/repowise/cli/ui/plan_screen/keys.py b/packages/cli/src/repowise/cli/ui/plan_screen/keys.py
new file mode 100644
index 000000000..559ff3db2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/keys.py
@@ -0,0 +1,76 @@
+"""Reading one key from the plan screen."""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+
+import click.termui
+from rich.console import Console
+from rich.prompt import Prompt
+
+from repowise.cli.ui.plan_screen.state import PlanState
+
+START, MODEL, EDIT, THIS_REPO, QUIT = "start", "model", "edit", "this_repo", "quit"
+
+_KEYS = {"": START, "m": MODEL, "e": EDIT, "s": THIS_REPO, "q": QUIT}
+
+
+class _InputEndedError(Exception):
+ """End of input inside a click prompt; click lets anything but EOF and ^C through."""
+
+
+@contextmanager
+def end_of_input_is_eof() -> Iterator[None]:
+ """Inside, end of input in a click prompt raises EOFError, the way Rich's does.
+
+ Click turns EOF into Abort, the same exception as Ctrl-C, so the
+ questions behind ``m`` and ``e`` would end the run where the key read
+ falls back to defaults. Ctrl-C is untouched and still aborts.
+ """
+ saved = click.termui.visible_prompt_func, click.termui.hidden_prompt_func
+
+ def ending(read: Callable[[str], str]) -> Callable[[str], str]:
+ def guarded(prompt: str) -> str:
+ try:
+ return read(prompt)
+ except EOFError:
+ raise _InputEndedError from None
+
+ return guarded
+
+ click.termui.visible_prompt_func = ending(saved[0])
+ click.termui.hidden_prompt_func = ending(saved[1])
+ try:
+ yield
+ except _InputEndedError:
+ raise EOFError from None
+ finally:
+ click.termui.visible_prompt_func, click.termui.hidden_prompt_func = saved
+
+
+def read_plan_key(
+ console: Console, state: PlanState, ask: Callable[[], str] | None = None
+) -> str:
+ """The action for the next key: start, model, edit, this_repo or quit.
+
+ Line-based on purpose: a single-keypress read goes to the console device
+ on Windows, so it would block an agent whose stdin is a pipe or
+ ``/dev/null``. Rich's prompt, not click's: click turns EOF into Abort,
+ which is also Ctrl-C. EOFError propagates; the caller treats it as
+ "nobody can answer".
+ """
+ if ask is None:
+
+ def ask() -> str:
+ return Prompt.ask(" Choice", default="", show_default=False, console=console)
+
+ while True:
+ raw = ask().strip().lower()
+ action = _KEYS.get(raw)
+ if action == THIS_REPO and not state.can_keep_global:
+ action = None
+ if action is not None:
+ return action
+ offered = "m, e, s or q" if state.can_keep_global else "m, e or q"
+ console.print(f" [dim]Press Enter to start, or {offered}.[/dim]")
diff --git a/packages/cli/src/repowise/cli/ui/plan_screen/render.py b/packages/cli/src/repowise/cli/ui/plan_screen/render.py
new file mode 100644
index 000000000..7b45fe04c
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/render.py
@@ -0,0 +1,194 @@
+"""The init plan screen: one readout of what Enter runs, and the keys that change it."""
+
+from __future__ import annotations
+
+from rich.console import Console
+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 BUILT_FROM_CODE, INDEX_ONLY, written_by
+from repowise.cli.ui.mode_selection import LARGE_REPO_FILE_THRESHOLD
+from repowise.cli.ui.plan_screen.state import (
+ PlanState,
+ eta_phrase,
+ eta_seconds,
+ source_and_languages,
+)
+from repowise.core.index_scope import FAST_TO_FULL_COMMAND
+
+#: What ``e`` opens, named so the key is not a blind door.
+EDIT_PREVIEW = (
+ "scope, run mode, excludes, commit limit, file pages, embedder, agents and "
+ "sync, plus concurrency, style and language with a model"
+)
+
+
+def _say(console: Console, markup: str, indent: int = 4) -> None:
+ """One line, wrapped under its own indent rather than at column 0."""
+ console.print(Padding(Text.from_markup(markup), (0, 0, 0, indent)))
+
+
+def _model_adds(state: PlanState) -> str:
+ search = (
+ f"semantic search with the {escape(state.model_embedder)} embedder"
+ if state.model_embedder != "mock"
+ else "semantic search once an embedder is set up"
+ )
+ return (
+ "Adds written subsystem documentation, decisions from PRs, git history "
+ f"and comments, and {search}."
+ )
+
+
+def _scan_line(state: PlanState) -> str:
+ scan = state.scan
+ source, languages = source_and_languages(scan)
+ parts = [f"[bold]{escape(state.repo_name)}[/bold]", f"{scan.total_files:,} files scanned"]
+ if source:
+ parts.append(f"{source:,} source")
+ if languages:
+ parts.append(f"{languages} language" + ("" if languages == 1 else "s"))
+ if scan.total_commits:
+ parts.append(f"{scan.total_commits:,} commits")
+ return " " + " · ".join(parts)
+
+
+def _eta_line(state: PlanState) -> str:
+ what = "to index" if state.run_mode == "fast" else "to index and build the documentation"
+ if state.chosen is not None:
+ what = "to index and write the documentation"
+ phrase = eta_phrase(*eta_seconds(state))
+ return f" {phrase[0].upper()}{phrase[1:]} {what}."
+
+
+def _documentation_rows(state: PlanState) -> list[tuple[str, str]]:
+ if state.run_mode == "fast":
+ return [
+ ("Documentation", f"{INDEX_ONLY}: none this run"),
+ ("", f"[dim]{FAST_TO_FULL_COMMAND} adds it later[/dim]"),
+ ]
+ if state.chosen is not None:
+ return [("Documentation", written_by(escape(state.chosen.model_label)))]
+ return [
+ ("Documentation", BUILT_FROM_CODE),
+ ("", "[dim]a model can write it later: repowise generate[/dim]"),
+ ]
+
+
+def _search_row(state: PlanState) -> str:
+ if state.run_mode == "fast":
+ return "no documentation to search this run"
+ embedder = state.model_embedder if state.chosen is not None else state.free_embedder
+ if embedder == "mock":
+ return "full-text · semantic search needs an embedder (choose one under e)"
+ return f"full-text and semantic search ({escape(embedder)} embedder)"
+
+
+def _decisions_row(state: PlanState) -> str:
+ if state.chosen is not None:
+ return "from code markers, ADR files, PRs, git history and comments"
+ return "from code markers and ADR files"
+
+
+def _connect_rows(state: PlanState) -> list[tuple[str, str]]:
+ if not state.editor_setup:
+ off = "off (--no-editor-setup)"
+ return [("Connect", off), ("Keep in sync", off)]
+ agents = ", ".join(escape(a) for a in state.agents) or "no agents"
+ sync = (
+ "repowise update after each commit (post-commit hook)"
+ if state.sync
+ else "off: run repowise update yourself"
+ )
+ return [("Connect", agents), ("Keep in sync", sync)]
+
+
+def _plan_heading(state: PlanState) -> str:
+ if state.chosen is None:
+ return f" [{BRAND}]The plan[/] [dim]free, runs on this machine[/dim]"
+ chosen = state.chosen
+ return (
+ f" [{BRAND}]The plan[/] [dim]uses {escape(chosen.provider)} / "
+ f"{escape(chosen.model_label)}: {escape(chosen.cost)}, about {chosen.minutes:,} min more[/dim]"
+ )
+
+
+def _print_model_offer(console: Console, state: PlanState) -> None:
+ """The opt-in line: what a model adds, what it costs, and that it waits for ``m``."""
+ if state.chosen is not None or state.run_mode == "fast":
+ return
+ console.print()
+ console.print(f" [{BRAND}]Optional[/] {written_by()}, used only if you press m")
+ price = state.offer.price
+ if price is None:
+ _say(
+ console,
+ "No key found. m sets up an API key or a logged-in Claude Code, Codex or OpenCode.",
+ )
+ else:
+ _say(
+ console,
+ f"{escape(state.offer.found)}: {escape(price.provider)} / {escape(price.model_label)}",
+ )
+ _say(console, f"[dim]{escape(price.cost)}, about {price.minutes:,} min more[/dim]")
+ _say(console, f"[dim]{_model_adds(state)}[/dim]")
+
+
+def _print_outside(console: Console, state: PlanState) -> None:
+ """D2: where the one global MCP entry points now, and where it will point."""
+ if not state.editor_setup:
+ return
+ if not state.outside:
+ return
+ console.print()
+ console.print(f" [{WARN}]![/] [bold]Outside this repo[/bold]")
+ if state.this_repo_only:
+ _say(
+ console,
+ "Global repowise MCP entry left as is. Agents opened in this repo "
+ "still connect through its project files.",
+ )
+ _say(console, "[dim]Press s to point it here after all.[/dim]")
+ return
+ for line in state.outside:
+ _say(console, escape(line.strip()))
+ _say(console, "[dim]Press s to leave it as is and connect this repo only.[/dim]")
+
+
+def _key_line(state: PlanState) -> str:
+ model_key = "back to built from code" if state.chosen is not None else "add a model"
+ keys = [("Enter", "start"), ("m", model_key), ("e", "edit plan")]
+ if state.can_keep_global:
+ keys.append(("s", "point it here" if state.this_repo_only else "this repo only"))
+ keys.append(("q", "quit"))
+ return " " + " ".join(f"[bold {BRAND}]{k}[/] {label}" for k, label in keys)
+
+
+def render_plan(console: Console, state: PlanState) -> None:
+ """Print the plan screen for *state*."""
+ _say(console, _scan_line(state).strip(), indent=2)
+ _say(console, _eta_line(state).strip(), indent=2)
+ if state.large_repo and state.run_mode != "fast":
+ _say(
+ console,
+ f"[dim]Above {LARGE_REPO_FILE_THRESHOLD:,} files a fast first index "
+ f"({INDEX_ONLY.lower()}) is recommended: choose run mode fast under e.[/dim]",
+ indent=2,
+ )
+ console.print()
+ console.print(_plan_heading(state))
+ rows = [
+ ("Index", "code graph, git history, health, dead code"),
+ ("Decisions", _decisions_row(state)),
+ *_documentation_rows(state),
+ ("Search", _search_row(state)),
+ *_connect_rows(state),
+ ]
+ console.print(key_value_table(rows, label_width=14, value_style=""), highlight=False)
+ _print_model_offer(console, state)
+ _print_outside(console, state)
+ console.print()
+ _say(console, _key_line(state).strip(), indent=2)
+ _say(console, f"[dim]e covers {EDIT_PREVIEW}.[/dim]", indent=2)
diff --git a/packages/cli/src/repowise/cli/ui/plan_screen/state.py b/packages/cli/src/repowise/cli/ui/plan_screen/state.py
new file mode 100644
index 000000000..c381dfaab
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/state.py
@@ -0,0 +1,173 @@
+"""What the init plan screen shows: the facts, gathered before it renders."""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+
+from repowise.cli.ui.repo_scanner import (
+ RepoScanInfo,
+ estimated_model_minutes,
+ estimated_run_seconds,
+ source_file_counts,
+)
+
+
+@dataclass(frozen=True)
+class ModelPrice:
+ """A model and what a written run with it costs: money or quota, and time."""
+
+ provider: str
+ model: str
+ #: ``about $0.04-$0.07, about 14 model calls``, or a subscription's quota line.
+ cost: str
+ minutes: int
+
+ @property
+ def model_label(self) -> str:
+ """The model id without a repeated ``<provider>/`` prefix."""
+ return self.model.removeprefix(f"{self.provider}/")
+
+
+@dataclass(frozen=True)
+class ModelOffer:
+ """The model ``m`` defaults to. ``price`` is ``None`` when nothing is set up."""
+
+ price: ModelPrice | None = None
+ #: How it was found: ``OPENAI_API_KEY found``, ``Claude Code is logged in``.
+ found: str = ""
+
+
+@dataclass
+class PlanState:
+ """Everything one render of the plan screen needs."""
+
+ repo_name: str
+ scan: RepoScanInfo
+ #: ``standard`` or ``fast`` (index only, no documentation).
+ run_mode: str = "standard"
+ #: The model picked with ``m``; Enter then runs it.
+ chosen: ModelPrice | None = None
+ offer: ModelOffer = field(default_factory=ModelOffer)
+ #: Embedder each path would use; ``mock`` means full-text search only.
+ free_embedder: str = "mock"
+ model_embedder: str = "mock"
+ #: Display names of the agents the run connects.
+ agents: tuple[str, ...] = ()
+ editor_setup: bool = True
+ sync: bool = True
+ #: Old and new target of the global MCP entry; empty when it does not move.
+ outside: tuple[str, ...] = ()
+ this_repo_only: bool = False
+ large_repo: bool = False
+ #: Commits git history walks at most (``--commit-limit`` or config.yaml).
+ commit_limit: int = 5000
+
+ @property
+ def can_keep_global(self) -> bool:
+ """Whether ``s`` means anything: the global entry would move."""
+ return self.editor_setup and bool(self.outside)
+
+
+@dataclass(frozen=True)
+class RunShape:
+ """What sizes a written run before indexing: the scan and two run options."""
+
+ scan: RepoScanInfo
+ onboarding: bool = True
+ concurrency: int = 10
+
+
+def _plans(shape: RunShape) -> list:
+ from repowise.core.cost_estimator import approximate_generation_plan
+
+ return approximate_generation_plan(shape.scan.total_files, onboarding=shape.onboarding)
+
+
+def model_calls_for(shape: RunShape) -> int:
+ """Model calls a written run makes, from the plan the server quotes before indexing."""
+ from repowise.cli.ui.subscription import model_call_count
+
+ return model_call_count(_plans(shape)) if shape.scan.total_files else 0
+
+
+def price_model(provider: str, model: str, shape: RunShape) -> ModelPrice:
+ """What a written run with *provider* / *model* costs, before indexing."""
+ from repowise.cli.ui.subscription import subscription_minutes, subscription_quota
+ from repowise.core.cost_estimator import estimate_cost
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+ calls = model_calls_for(shape)
+ spec = PROVIDER_SPECS.get(provider)
+ if spec is not None and spec.agent:
+ return ModelPrice(
+ provider,
+ model,
+ subscription_quota(provider, calls, shape.concurrency),
+ subscription_minutes(provider, calls, shape.concurrency),
+ )
+ est = estimate_cost(_plans(shape), provider, model)
+ rng = est.cost_range
+ price = f"about ${rng.low:.2f}-${rng.high:.2f}" if rng else f"about ${est.estimated_cost_usd:.2f}"
+ calls_word = "call" if calls == 1 else "calls"
+ return ModelPrice(
+ provider,
+ model,
+ f"{price}, about {calls:,} model {calls_word}",
+ estimated_model_minutes(calls),
+ )
+
+
+def _found_phrase(provider: str, how: str) -> str:
+ from repowise.core.agents.identity import identity_for_provider
+
+ agent = identity_for_provider(provider)
+ if agent is not None:
+ label = agent.display_name.removesuffix(" CLI")
+ return f"{label} is logged in" if agent.login_check else f"{label} is installed"
+ if provider == "ollama":
+ return f"Ollama is running at {how}"
+ return f"{how} found" if how else f"{provider} is set up"
+
+
+def build_offer(detected: dict[str, str], prefer: tuple[str, ...], shape: RunShape) -> ModelOffer:
+ """The provider ``m`` defaults to: an agent CLI set up here, else the first detected.
+
+ *detected* is the picker's own detection (``provider -> how``) and
+ *prefer* its preference, so this line and the picker default agree.
+ """
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+ if not detected:
+ return ModelOffer()
+ name = next((p for p in prefer if p in detected), next(iter(detected)))
+ runtime = "openai" if name == "openai_compatible" else name
+ spec = PROVIDER_SPECS.get(runtime)
+ model = spec.default_model if spec is not None else ""
+ return ModelOffer(
+ price=price_model(runtime, model, shape),
+ found=_found_phrase(runtime, detected[name]),
+ )
+
+
+def eta_seconds(state: PlanState) -> tuple[float, float]:
+ """Low and high seconds for the run as planned."""
+ low, high = estimated_run_seconds(state.scan, state.commit_limit)
+ if state.chosen is not None:
+ low, high = low + state.chosen.minutes * 60, high + state.chosen.minutes * 60
+ return low, high
+
+
+def eta_phrase(low: float, high: float) -> str:
+ """``under a minute``, ``about 1-2 min`` or ``about 3-6 min``."""
+ if high < 60:
+ return "under a minute"
+ lo = max(1, math.floor(low / 60))
+ hi = max(lo + 1, math.ceil(high / 60))
+ return f"about {lo:,}-{hi:,} min"
+
+
+def source_and_languages(scan: RepoScanInfo) -> tuple[int, int]:
+ """``(source files, source languages)`` from the pre-scan."""
+ counts = {lang: n for lang, n in source_file_counts(scan).items() if n > 0}
+ return sum(counts.values()), len(counts)
diff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.py
index 7a9123736..210dcc058 100644
--- a/packages/cli/src/repowise/cli/ui/provider_selection.py
+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py
@@ -268,13 +268,15 @@ def _interactive_provider_name(
repo_path: Path | None = None,
save_key: bool = True,
subscription: SubscriptionContext = _NO_SUBSCRIPTION,
-) -> str:
+) -> str | None:
"""Show provider table, handle selection + inline key entry + save.
The first ready provider in *prefer* (see :func:`agent_providers_set_up`)
becomes the default, else the one auto-detection would pick. With
*model_calls*, a ready agent CLI is shown with its quota and time
- estimate. Returns the chosen provider name.
+ estimate. Returns the chosen provider name, or ``None`` when
+ ``subscription.allow_skip`` is set and the user chose to go on without a
+ model.
"""
providers = list(_PROVIDER_CHOICES) # gemini first
detected = _detect_provider_status(repo_path)
@@ -365,50 +367,63 @@ def _interactive_provider_name(
has_official_openai_key = chosen == "openai" and bool(
(os.environ.get("OPENAI_API_KEY") or "").strip()
)
- if chosen not in detected and not has_official_openai_key:
- 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()
- for line in setup_lines():
- console.print(line)
- return _interactive_provider_name(
- console,
- model_flag,
- repo_path=repo_path,
- save_key=save_key,
- subscription=subscription,
- )
- env_var = _PROVIDER_ENV[chosen]
- signup_url = _PICKER_SPECS[chosen].signup_url
- console.print()
- console.print(f" [bold]{chosen}[/bold] requires [{VALUE}]{env_var}[/].")
- if signup_url:
- console.print(f" Get your API key here: [{BRAND}]{signup_url}[/]")
- console.print()
- key = _prompt_api_key(
+ if (
+ chosen not in detected
+ and not has_official_openai_key
+ and not _set_up_inline(console, chosen, repo_path, save_key)
+ ):
+ if _go_without_model(console, subscription.allow_skip, keyed=chosen in _PROVIDER_ENV):
+ return None
+ return _interactive_provider_name(
console,
- chosen,
- env_var,
+ model_flag,
repo_path=repo_path,
save_key=save_key,
+ subscription=subscription,
)
- if not key:
- console.print(f" [{WARN}]Skipped. Please select another provider.[/]")
- return _interactive_provider_name(
- console,
- model_flag,
- repo_path=repo_path,
- save_key=save_key,
- subscription=subscription,
- )
if chosen == "openai" and repo_path is not None:
_save_key_to_dotenv(repo_path, "OPENAI_BASE_URL", _OPENAI_DEFAULT_BASE_URL)
return chosen
+def _set_up_inline(console: Console, chosen: str, repo_path: Path | None, save_key: bool) -> bool:
+ """Set up a provider that is not ready. True when a key was entered.
+
+ Local and agent-CLI providers have nothing to paste: they authenticate out
+ of band or run locally, so the remedy is a command and this is False.
+ """
+ setup_lines = _LOCAL_PROVIDER_SETUP.get(chosen)
+ console.print()
+ if setup_lines is not None:
+ for line in setup_lines():
+ console.print(line)
+ return False
+ env_var = _PROVIDER_ENV[chosen]
+ signup_url = _PICKER_SPECS[chosen].signup_url
+ console.print(f" [bold]{chosen}[/bold] requires [{VALUE}]{env_var}[/].")
+ if signup_url:
+ console.print(f" Get your API key here: [{BRAND}]{signup_url}[/]")
+ console.print()
+ key = _prompt_api_key(console, chosen, env_var, repo_path=repo_path, save_key=save_key)
+ return bool(key)
+
+
+def _go_without_model(console: Console, allow_skip: bool, *, keyed: bool) -> bool:
+ """After a provider that is still not set up: True to go on without a model."""
+ if not allow_skip:
+ if keyed:
+ console.print(f" [{WARN}]Skipped. Please select another provider.[/]")
+ return False
+ if keyed:
+ console.print(f" [{WARN}]No key entered.[/]")
+ console.print(
+ f" [{BRAND}][1][/] Continue without a model [dim](documentation built from code)[/dim]"
+ )
+ console.print(f" [{BRAND}][2][/] Pick another provider")
+ return Prompt.ask(" Choose", choices=["1", "2"], default="1", console=console) == "1"
+
+
def _fallback_model_option(provider_name: str) -> ProviderModelOption:
default_model = _PROVIDER_DEFAULTS.get(provider_name, "")
return ProviderModelOption(
@@ -652,11 +667,13 @@ def interactive_provider_config_select(
repo_path: Path | None = None,
save_key: bool = True,
subscription: SubscriptionContext = _NO_SUBSCRIPTION,
-) -> ProviderSelection:
+) -> ProviderSelection | None:
"""Show provider/model/reasoning selection for interactive init.
Returns a :class:`ProviderSelection` carrying the chosen provider name,
- model, and reasoning mode.
+ model, and reasoning mode. With ``subscription.allow_skip``, a provider
+ that is not set up offers to go on without a model, and that answer
+ returns ``None``.
"""
chosen = _interactive_provider_name(
console,
@@ -665,13 +682,22 @@ def interactive_provider_config_select(
save_key=save_key,
subscription=subscription,
)
+ if chosen is None:
+ return None
if chosen == _OPENAI_COMPATIBLE_CHOICE:
- return _interactive_openai_compatible_select(
+ gateway = _interactive_openai_compatible_select(
+ console, model_flag, reasoning_flag, repo_path=repo_path, save_key=save_key
+ )
+ if gateway is not None:
+ return gateway
+ # The user asked to go back to provider selection.
+ return interactive_provider_config_select(
console,
model_flag,
reasoning_flag,
repo_path=repo_path,
save_key=save_key,
+ subscription=subscription,
)
default_model = _PROVIDER_DEFAULTS.get(chosen, "")
@@ -727,6 +753,7 @@ def interactive_provider_select(
reasoning_flag="auto",
repo_path=repo_path,
)
+ assert selection is not None # allow_skip is off, so a provider was chosen
return selection.provider_name, selection.model
@@ -844,8 +871,11 @@ def _interactive_openai_compatible_select(
*,
repo_path: Path | None,
save_key: bool,
-) -> ProviderSelection:
- """Configure, verify, and select a model from a custom OpenAI gateway."""
+) -> ProviderSelection | None:
+ """Configure, verify, and select a model from a custom OpenAI gateway.
+
+ ``None`` means the user asked to go back to provider selection.
+ """
console.print()
console.print(" [bold]OpenAI-compatible custom gateway[/bold]")
console.print(" [dim]Works with 9router, vLLM, SGLang, and compatible /v1 APIs.[/dim]")
@@ -882,13 +912,7 @@ def _interactive_openai_compatible_select(
if action == "1":
continue
if action == "3":
- return interactive_provider_config_select(
- console,
- model_flag,
- reasoning_flag,
- repo_path=repo_path,
- save_key=save_key,
- )
+ return None
selected = _prompt_exact_model(console)
break
diff --git a/packages/cli/src/repowise/cli/ui/repo_scanner.py b/packages/cli/src/repowise/cli/ui/repo_scanner.py
index afbdd5e4a..9038bf53b 100644
--- a/packages/cli/src/repowise/cli/ui/repo_scanner.py
+++ b/packages/cli/src/repowise/cli/ui/repo_scanner.py
@@ -1,4 +1,4 @@
-"""Quick repo pre-scan (fast, no AST) and its summary panel."""
+"""Quick repo pre-scan (fast, no AST) and the estimates read from it."""
from __future__ import annotations
@@ -7,8 +7,6 @@ import subprocess
from dataclasses import dataclass, field
from pathlib import Path
-from rich.console import Console
-
from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
from repowise.core.test_paths import is_test_related_path
@@ -164,58 +162,35 @@ def estimated_documentable_files(scan: RepoScanInfo | None) -> int:
return max(0, src - scan.test_file_count)
+def estimated_wiki_render_seconds(documentable: int) -> tuple[float, float]:
+ """Rough low/high seconds to render and embed *documentable* file pages.
+
+ Calibrated at roughly 1-2 minutes per thousand pages.
+ """
+ return documentable * 0.06, documentable * 0.12
+
+
def estimated_wiki_render_minutes(documentable: int) -> tuple[int, int]:
- """Rough low/high minutes to render and embed *documentable* file pages.
+ """The same estimate in whole minutes, for the page-volume question."""
+ low, high = estimated_wiki_render_seconds(documentable)
+ return max(1, round(low / 60)), max(2, round(high / 60))
- 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.
+
+def estimated_run_seconds(scan: RepoScanInfo, commit_limit: int) -> tuple[float, float]:
+ """Rough low/high seconds for a run without a model, start to finish.
+
+ Git history dominates: file history and co-changes walk every commit up
+ to *commit_limit*. A fixed tail covers the save and persist steps.
+ Calibrated on measured runs: 16 source files and 677 commits in about
+ 10 s, 90 source files and 5,555 commits in 1m 51s, 1,186 source files
+ and 7,860 commits in 1m 24s to 1m 44s. Coarse on purpose.
"""
- 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
- source_langs = {lang: c for lang, c in source_file_counts(scan).items() if c > 0}
- lang_count = len(source_langs)
-
- parts = [f"[bold]{scan.total_files:,}[/bold] files"]
- if lang_count:
- parts.append(f"[bold]{lang_count}[/bold] languages")
- if scan.total_commits:
- parts.append(f"[bold]{scan.total_commits:,}[/bold] commits")
-
- header_line = " · ".join(parts)
-
- # Top languages (source code only, top 4)
- total_source = sum(source_langs.values()) or 1
- top_langs = sorted(source_langs.items(), key=lambda x: -x[1])[:4]
- lang_parts = [f"{lang} {count / total_source:.0%}" for lang, count in top_langs]
- if len(source_langs) > 4:
- lang_parts.append(f"+{len(source_langs) - 4} more")
- lang_line = ", ".join(lang_parts) if lang_parts else "no source files detected"
-
- # Rough wall-time estimate so users know what they're committing to.
- # Calibrated against ~700-file Python+TS repos: traverse+parse+graph
- # comes in around 2 min/1k source files, plus ~1 min/100 LLM pages.
- # We surface a range, not a point, to set honest expectations.
- src_files = sum(source_langs.values()) or scan.total_files
- ingest_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 to index · "
- f"~{render_min}-{render_max} min more to render and embed the wiki"
- )
+ src_files = sum(source_file_counts(scan).values()) or scan.total_files
+ commits = min(scan.total_commits, commit_limit)
+ low = 5 + 0.02 * commits + 0.01 * src_files
+ return low, 1.5 * low
+
- # A readout, so no border. It sits directly under the banner and used to be
- # the first of five boxes a user crossed before anything was asked of them.
- console.print(f" {header_line}")
- console.print(f" [dim]{lang_line}[/dim]")
- console.print(f" [dim]{eta_line}[/dim]")
- console.print()
+def estimated_model_minutes(model_calls: int) -> int:
+ """Rough minutes an API model takes for *model_calls* pages, about 1 min per 100."""
+ return max(1, round(model_calls / 100))
diff --git a/packages/cli/src/repowise/cli/ui/subscription.py b/packages/cli/src/repowise/cli/ui/subscription.py
index e44d15553..6d85a855e 100644
--- a/packages/cli/src/repowise/cli/ui/subscription.py
+++ b/packages/cli/src/repowise/cli/ui/subscription.py
@@ -35,16 +35,19 @@ SECONDS_PER_CALL = 60
@dataclass(frozen=True)
class SubscriptionContext:
- """What the picker needs to offer an agent CLI.
+ """What the picker knows about the run that opened it.
*prefer*: agent CLIs set up in this repo, the first ready one becomes the
default (see ``agent_providers_set_up``). *model_calls* and *concurrency*
size the quota and time estimate; no estimate is shown without calls.
+ *allow_skip*: a provider that is not set up offers to go on without a
+ model, and the picker returns ``None`` for that answer.
"""
prefer: tuple[str, ...] = ()
model_calls: int | None = None
concurrency: int = 10
+ allow_skip: bool = False
@dataclass(frozen=True)
@@ -204,6 +207,34 @@ def model_call_count(plans: Iterable[object]) -> int:
)
+def _parallel(provider_name: str, concurrency: int | None) -> int:
+ limit = process_limit(provider_name)
+ return max(1, min(concurrency, limit) if concurrency else limit)
+
+
+def subscription_minutes(
+ provider_name: str, model_calls: int, concurrency: int | None = None
+) -> int:
+ """Minutes a subscription run of *model_calls* takes, at least one."""
+ parallel = _parallel(provider_name, concurrency)
+ return max(1, math.ceil(math.ceil(model_calls / parallel) * SECONDS_PER_CALL / 60))
+
+
+def subscription_quota(
+ provider_name: str,
+ model_calls: int,
+ concurrency: int | None = None,
+ billing: str | None = None,
+) -> str:
+ """``uses your Claude Code login, about 14 model calls, 4 at a time``."""
+ parallel = _parallel(provider_name, concurrency)
+ calls = "call" if model_calls == 1 else "calls"
+ return (
+ f"{billing or PROVIDER_SPECS[provider_name].note}, about {model_calls:,} model {calls}, "
+ f"{parallel} at a time"
+ )
+
+
def subscription_estimate(
provider_name: str,
model_calls: int,
@@ -217,15 +248,9 @@ def subscription_estimate(
run's ``--concurrency``; the CLI's own process limit caps it. *billing*
(from :func:`agent_cli_auth`) replaces the generic login note.
"""
- limit = process_limit(provider_name)
- parallel = max(1, min(concurrency, limit) if concurrency else limit)
- minutes = max(1, math.ceil(math.ceil(model_calls / parallel) * SECONDS_PER_CALL / 60))
- calls = "call" if model_calls == 1 else "calls"
- return (
- f"{billing or PROVIDER_SPECS[provider_name].note}, "
- f"about {model_calls:,} model {calls}, "
- f"{parallel} at a time, about {minutes:,} min"
- )
+ minutes = subscription_minutes(provider_name, model_calls, concurrency)
+ quota = subscription_quota(provider_name, model_calls, concurrency, billing)
+ return f"{quota}, about {minutes:,} min"
def subscription_note(ready: tuple[str, ...], auth: CliAuth | None = None) -> str | None:
@@ -261,5 +286,7 @@ __all__ = [
"process_limit",
"ready_agent_providers",
"subscription_estimate",
+ "subscription_minutes",
"subscription_note",
+ "subscription_quota",
]
diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py
index d30df479e..fcc6a1031 100644
--- a/tests/integration/test_cli.py
+++ b/tests/integration/test_cli.py
@@ -1352,8 +1352,8 @@ class TestInitSeedFrom:
catch_exceptions=False,
)
assert r1.exit_code == 0, r1.output
- assert "Worktree index seeded successfully" in r1.output
- assert "Delegating to update..." in r1.output
+ assert "Index copied from" in r1.output
+ assert "to catch it up" in r1.output
assert (worktree_dir / ".repowise" / "state.json").exists()
assert (worktree_dir / ".repowise" / "wiki.db").exists()
@@ -1487,7 +1487,7 @@ class TestInitSeedFrom:
catch_exceptions=False,
)
assert r1.exit_code == 0, r1.output
- assert "Delegating to update" in r1.output
+ assert "to catch it up" in r1.output
# Copied config.yaml and the vector db directory (lancedb).
assert (worktree_dir / ".repowise" / "config.yaml").exists()
@@ -1539,8 +1539,8 @@ class TestWorktreeAutoSeed:
cli, ["init", str(worktree_dir), "--index-only"], catch_exceptions=False
)
assert r1.exit_code == 0, r1.output
- assert "[worktree]" in r1.output
- assert "Worktree index seeded successfully" in r1.output
+ assert "This is a linked worktree of" in r1.output
+ assert "Index copied from" in r1.output
assert (worktree_dir / ".repowise" / "state.json").exists()
assert (worktree_dir / ".repowise" / "wiki.db").exists()
finally:
@@ -1565,7 +1565,7 @@ class TestWorktreeAutoSeed:
catch_exceptions=False,
)
assert r1.exit_code == 0, r1.output
- assert "[worktree]" not in r1.output
+ assert "linked worktree of" not in r1.output
# Cold init still produces a working index.
assert (worktree_dir / ".repowise" / "state.json").exists()
finally:
@@ -1617,7 +1617,7 @@ class TestWorktreeAutoSeed:
cli, ["init", str(worktree_dir), "--index-only"], catch_exceptions=False
)
assert r1.exit_code == 0, r1.output
- assert "[worktree]" not in r1.output
+ assert "linked worktree of" not in r1.output
assert (worktree_dir / ".repowise" / "state.json").exists()
finally:
_remove_worktree(git_work_repo, worktree_dir)
@@ -1702,7 +1702,7 @@ class TestWorktreeInitForce:
assert upgrade_calls == [], "init --force must not enter the paid upgrade path"
# The seed is deliberately skipped: --force asks for the re-index
# seeding exists to avoid, so no delegation line and no seeded index.
- assert "Delegating to update" not in flat
+ assert "to catch it up" not in flat
assert "--force re-indexes this checkout from scratch" in flat
state = json.loads(
@@ -1833,8 +1833,8 @@ class TestWorktreeInitForce:
)
assert r1.exit_code == 0, r1.output
flat = " ".join(r1.output.split())
- assert "Worktree index seeded successfully" in flat
- assert "Delegating to update" in flat
+ assert "Index copied from" in flat
+ assert "to catch it up" in flat
assert seen, "the seed path should still delegate to update"
assert all(call["full"] is False for call in seen), seen
finally:
diff --git a/tests/unit/cli/test_commands.py b/tests/unit/cli/test_commands.py
index 80a4e8bf5..8ab9f80d3 100644
--- a/tests/unit/cli/test_commands.py
+++ b/tests/unit/cli/test_commands.py
@@ -305,7 +305,7 @@ class TestInitYesFlag:
return_value=fake_scan,
),
patch(
- "repowise.cli.commands.init_cmd._questions.prompt_wiki_style",
+ "repowise.cli.ui.mode_selection.prompt_wiki_style",
side_effect=_fake_prompt_wiki_style,
),
patch(
@@ -316,12 +316,12 @@ class TestInitYesFlag:
runner.invoke(cli, ["init", "-y", "--index-only", str(tmp_path)])
assert not prompt_called, "-y should bypass the wiki-style interactive prompt"
- def test_yes_skips_mode_select_on_tty(self, runner, tmp_path):
- """With -y on a TTY, the interactive mode-selection menu is never shown.
+ def test_yes_skips_plan_screen_on_tty(self, runner, tmp_path):
+ """With -y on a TTY, the plan screen is never shown.
Without the ``and not yes`` guard on ``is_interactive`` a scripted
- ``init -y`` would still block on ``interactive_mode_select`` whenever
- stdin happens to be a TTY.
+ ``init -y`` would still block on the plan screen whenever stdin
+ happens to be a TTY.
"""
from unittest.mock import MagicMock, patch
@@ -339,7 +339,7 @@ class TestInitYesFlag:
),
patch("sys.stdin.isatty", return_value=True),
patch(
- "repowise.cli.commands.init_cmd._questions.interactive_mode_select",
+ "repowise.cli.commands.init_cmd._plan.run_plan_screen",
side_effect=lambda *_a, **_kw: mode_select_called.append(True),
),
# Stop before the real pipeline runs.
@@ -350,7 +350,7 @@ class TestInitYesFlag:
):
runner.invoke(cli, ["init", "-y", str(tmp_path)])
assert not mode_select_called, (
- "-y must bypass the interactive mode-selection menu even on a TTY"
+ "-y must bypass the plan screen even on a TTY"
)
diff --git a/tests/unit/cli/test_global_mcp_consent.py b/tests/unit/cli/test_global_mcp_consent.py
index 4e151662c..610d6cd92 100644
--- a/tests/unit/cli/test_global_mcp_consent.py
+++ b/tests/unit/cli/test_global_mcp_consent.py
@@ -198,8 +198,12 @@ def test_no_editor_setup_asks_and_prints_nothing(home: Path, repo: Path, monkeyp
assert buf.getvalue() == ""
-def _run(repo: Path, *, yes: bool) -> SimpleNamespace:
- return SimpleNamespace(repo_path=repo, opts=SimpleNamespace(yes=yes, editor_setup=True))
+def _run(repo: Path, *, yes: bool, consent: bool | None = None) -> SimpleNamespace:
+ return SimpleNamespace(
+ repo_path=repo,
+ opts=SimpleNamespace(yes=yes, editor_setup=True),
+ global_mcp_consent=consent,
+ )
def test_decline_leaves_global_configs_byte_identical(
@@ -246,3 +250,39 @@ def test_probe_failure_never_blocks_registration(home: Path, repo: Path, monkeyp
console, buf = _console()
assert global_mcp.confirm_global_mcp(console, repo) is True
assert buf.getvalue() == ""
+
+
+def test_plan_screen_this_repo_only_writes_nothing_and_asks_nothing(
+ home: Path, repo: Path, monkeypatch
+) -> None:
+ from repowise.cli.commands.init_cmd import _finish
+
+ _write(_settings(home), _entry("C:/elsewhere"))
+ before = _settings(home).read_bytes()
+ monkeypatch.setattr("sys.stdin", _Tty())
+ monkeypatch.setattr(click, "confirm", _no_prompt)
+ console, buf = _console()
+ monkeypatch.setattr(_finish, "console", console)
+
+ _finish.register_clients(_run(repo, yes=False, consent=False))
+
+ assert _settings(home).read_bytes() == before
+ assert "this repo only" in buf.getvalue()
+
+
+def test_plan_screen_yes_repoints_without_asking_again(
+ home: Path, repo: Path, monkeypatch
+) -> None:
+ from repowise.cli.commands.init_cmd import _finish
+
+ _write(_settings(home), _entry("C:/elsewhere"))
+ monkeypatch.setattr("sys.stdin", _Tty())
+ monkeypatch.setattr(click, "confirm", _no_prompt)
+ console, buf = _console()
+ monkeypatch.setattr(_finish, "console", console)
+
+ _finish.register_clients(_run(repo, yes=False, consent=True))
+
+ stored = json.loads(_settings(home).read_text(encoding="utf-8"))["mcpServers"]["repowise"]
+ assert stored["args"][1] == _arg(repo)
+ assert "now points at" in buf.getvalue()
diff --git a/tests/unit/cli/test_init_noninteractive.py b/tests/unit/cli/test_init_noninteractive.py
index 90fc17df4..c81f2a0c0 100644
--- a/tests/unit/cli/test_init_noninteractive.py
+++ b/tests/unit/cli/test_init_noninteractive.py
@@ -381,7 +381,8 @@ class TestAdvancedExcludeMergesWithFlag:
import subprocess
from unittest import mock
- from repowise.cli.commands.init_cmd import _prepare, _questions
+ from repowise.cli.commands.init_cmd import _plan, _prepare
+ from repowise.cli.ui.plan_screen import ModelOffer
repo = tmp_path / "repo"
(repo / "vendor").mkdir(parents=True)
@@ -406,10 +407,15 @@ class TestAdvancedExcludeMergesWithFlag:
with (
mock.patch.object(_prepare, "_interactive_gate", lambda **_: True),
- mock.patch.object(_questions, "interactive_mode_select", lambda _c: "advanced"),
- mock.patch.object(_questions, "interactive_generate_docs_toggle", lambda _c: False),
+ # e (edit plan), then Enter.
+ mock.patch.object(_plan, "read_plan_key", mock.Mock(side_effect=["edit", "start"])),
+ mock.patch.object(_plan, "build_offer", lambda *a, **k: ModelOffer()),
+ mock.patch.object(_plan, "agent_providers_set_up", lambda _r: ()),
+ mock.patch(
+ "repowise.cli.ui.provider_selection._detect_provider_status", lambda _r: {}
+ ),
mock.patch.object(
- _questions, "interactive_advanced_config", lambda *a, **k: dict(answers)
+ _plan, "interactive_advanced_config", lambda *a, **k: dict(answers)
),
mock.patch.object(_prepare, "_confirm_wiki_overwrite", _stop_after_settings),
):
diff --git a/tests/unit/cli/test_init_plan_screen.py b/tests/unit/cli/test_init_plan_screen.py
new file mode 100644
index 000000000..70cd2f2a8
--- /dev/null
+++ b/tests/unit/cli/test_init_plan_screen.py
@@ -0,0 +1,516 @@
+"""The init plan screen: what it shows, what each key does, and the -y help."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import click
+import pytest
+from click.testing import CliRunner
+from rich.console import Console
+
+from repowise.cli.main import cli
+from repowise.cli.ui import provider_selection
+from repowise.cli.ui.plan_screen import (
+ EDIT,
+ MODEL,
+ QUIT,
+ START,
+ THIS_REPO,
+ ModelOffer,
+ PlanState,
+ RunShape,
+ build_offer,
+ read_plan_key,
+ render_plan,
+)
+from repowise.cli.ui.repo_scanner import RepoScanInfo
+from repowise.cli.ui.subscription import SubscriptionContext
+
+_SCAN = RepoScanInfo(total_files=50, language_counts={"Python": 30}, total_commits=400)
+_OUTSIDE = ("Global repowise MCP entry (Claude Code) now points at /old, will point here: /new",)
+
+
+def _render(state: PlanState) -> str:
+ console = Console(record=True, width=100, color_system=None)
+ render_plan(console, state)
+ # Flattened: where the console wraps at 100 columns is not the copy's business.
+ return " ".join(console.export_text().split())
+
+
+def _state(**kwargs: Any) -> PlanState:
+ return PlanState(repo_name="demo", scan=_SCAN, **kwargs)
+
+
+# -- render -------------------------------------------------------------------
+
+
+def test_keyless_plan_is_the_free_run_with_a_visible_model_opt_in() -> None:
+ out = _render(_state(agents=("Claude Code",)))
+ assert "demo · 50 files scanned · 30 source · 1 language · 400 commits" in out
+ assert "Under a minute to index and build the documentation." in out
+ assert "free, runs on this machine" in out
+ assert "Built from code" in out
+ assert "No key found" in out
+ assert "Claude Code, Codex or OpenCode" in out
+ assert "decisions from PRs, git history" in out
+ assert "Enter start" in out and "m add a model" in out and "q quit" in out
+ # s only exists when the global entry would move.
+ assert "this repo only" not in out
+ assert "e covers scope, run mode" in out
+ assert "\N{EM DASH}" not in out
+
+
+def test_a_detected_key_is_named_with_cost_and_time_and_never_used_unasked() -> None:
+ offer = build_offer({"openai": "OPENAI_API_KEY"}, (), RunShape(_SCAN))
+ out = _render(_state(offer=offer, model_embedder="openai"))
+ assert "OPENAI_API_KEY found: openai /" in out
+ assert "$" in out and "model calls" in out and "min more" in out
+ assert "used only if you press m" in out
+ assert "semantic search with the openai embedder" in out
+ # The plan itself stays free.
+ assert "Built from code" in out
+
+
+def test_a_logged_in_claude_code_is_offered_with_quota_and_time(monkeypatch: Any) -> None:
+ offer = build_offer({"claude_cli": "agent CLI"}, (), RunShape(_SCAN))
+ out = _render(_state(offer=offer))
+ assert "Claude Code is logged in: claude_cli /" in out
+ assert "uses your Claude Code login" in out
+ assert "at a time" in out
+ assert "$0.00" not in out
+
+
+def test_a_chosen_model_changes_the_plan_and_the_m_key() -> None:
+ offer = build_offer({"openai": "OPENAI_API_KEY"}, (), RunShape(_SCAN))
+ assert offer.price is not None
+ out = _render(_state(offer=offer, chosen=offer.price, model_embedder="openai"))
+ assert f"Written by {offer.price.model}" in out
+ assert "uses openai /" in out
+ assert "m back to built from code" in out
+ assert "Optional" not in out
+ assert "full-text and semantic search (openai embedder)" in out
+
+
+def test_outside_this_repo_shows_old_and_new_and_offers_s() -> None:
+ out = _render(_state(outside=_OUTSIDE))
+ assert "! Outside this repo" in out
+ assert "now points at /old, will point here: /new" in out
+ assert "s this repo only" in out
+ kept = _render(_state(outside=_OUTSIDE, this_repo_only=True))
+ assert "left as is" in kept
+ assert "s point it here" in kept
+
+
+def test_editor_setup_off_writes_nothing_outside() -> None:
+ out = _render(_state(outside=_OUTSIDE, editor_setup=False))
+ assert "Outside this repo" not in out
+ assert "off (--no-editor-setup)" in out
+ assert "this repo only" not in out
+
+
+def test_fast_mode_and_the_large_repo_hint() -> None:
+ assert "Index only: none this run" in _render(_state(run_mode="fast"))
+ big = _render(_state(large_repo=True))
+ assert "Above 5,000 files a fast first index (index only) is recommended" in big
+
+
+# -- keys ---------------------------------------------------------------------
+
+
+def _keys(*answers: str):
+ it = iter(answers)
+ return lambda: next(it)
+
+
+ ("typed", "action"),
+ [("", START), ("m", MODEL), ("E", EDIT), (" q ", QUIT)],
+)
+def test_each_key_maps_to_its_action(typed: str, action: str) -> None:
+ assert read_plan_key(Console(width=100), _state(), _keys(typed)) == action
+
+
+def test_s_needs_a_global_entry_that_would_move() -> None:
+ console = Console(record=True, width=100)
+ assert read_plan_key(console, _state(), _keys("s", "x", "")) == START
+ assert "Press Enter to start, or m, e or q." in console.export_text()
+ assert read_plan_key(console, _state(outside=_OUTSIDE), _keys("s")) == THIS_REPO
+
+
+def test_eof_propagates_to_the_caller() -> None:
+ def eof() -> str:
+ raise EOFError
+
+ with pytest.raises(EOFError):
+ read_plan_key(Console(width=100), _state(), eof)
+
+
+# -- the no-key path ----------------------------------------------------------
+
+
+def test_no_key_offers_to_continue_without_a_model(monkeypatch: Any) -> None:
+ monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda *_a: {})
+ monkeypatch.setattr(provider_selection, "_prompt_api_key", lambda *a, **k: None)
+ gemini = str(list(provider_selection._PROVIDER_CHOICES).index("gemini") + 1)
+ answers = iter([gemini, "1"])
+ monkeypatch.setattr(provider_selection.Prompt, "ask", lambda *a, **k: next(answers))
+ console = Console(record=True, width=100)
+
+ selection = provider_selection.interactive_provider_config_select(
+ console, None, subscription=SubscriptionContext(allow_skip=True)
+ )
+
+ assert selection is None
+ out = console.export_text()
+ assert "Continue without a model" in out
+ assert "Please select another provider" not in out
+
+
+def test_no_key_can_still_pick_another_provider(monkeypatch: Any) -> None:
+ renders: list[int] = []
+
+ def detect(*_a: object) -> dict[str, str]:
+ renders.append(1)
+ return {} if len(renders) == 1 else {"openai": "OPENAI_API_KEY"}
+
+ monkeypatch.setattr(provider_selection, "_detect_provider_status", detect)
+ monkeypatch.setattr(provider_selection, "_prompt_api_key", lambda *a, **k: None)
+ choices = list(provider_selection._PROVIDER_CHOICES)
+ answers = iter([str(choices.index("gemini") + 1), "2", str(choices.index("openai") + 1)])
+ monkeypatch.setattr(provider_selection.Prompt, "ask", lambda *a, **k: next(answers))
+
+ chosen = provider_selection._interactive_provider_name(
+ Console(width=100), None, subscription=SubscriptionContext(allow_skip=True)
+ )
+
+ assert chosen == "openai"
+
+
+# -- the screen loop ----------------------------------------------------------
+
+
+def _run(tmp_path: Path, **opts: Any) -> Any:
+ from repowise.cli.commands.init_cmd._options import InitOptions, InitRun
+
+ fields = {name: None for name in InitOptions.__dataclass_fields__}
+ fields.update(
+ exclude=(), coverage_report=(), run_mode="standard", concurrency=10,
+ onboarding=True, editor_setup=True, save_key=True, yes=False, index_only=False,
+ follow_renames=False, skip_tests=False, skip_infra=False,
+ )
+ fields.update(opts)
+ return InitRun(
+ opts=InitOptions(**fields), repo_path=tmp_path, start=0.0, is_interactive=True
+ )
+
+
+def plan(monkeypatch: Any):
+ from repowise.cli.commands.init_cmd import _plan
+
+ monkeypatch.setattr(_plan, "agent_providers_set_up", lambda _r: ())
+ monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda _r: {})
+ monkeypatch.setattr(_plan, "_outside_lines", lambda _run: _OUTSIDE)
+ monkeypatch.setattr(
+ "repowise.cli.editor_setup.is_editor_setup_disabled", lambda _flag=False: False
+ )
+ monkeypatch.setattr("repowise.cli.editor_setup.planned_agents", lambda *_a: ("Claude Code",))
+
+ def drive(run: Any, *keys: str) -> None:
+ it = iter(keys)
+ monkeypatch.setattr(_plan, "read_plan_key", lambda *_a: next(it))
+ _plan.run_plan_screen(run, _SCAN)
+
+ return SimpleNamespace(module=_plan, drive=drive)
+
+
+def test_enter_runs_the_free_run_and_records_every_answer(plan: Any, tmp_path: Path) -> None:
+ run = _run(tmp_path)
+ plan.drive(run, START)
+ assert run.generate_docs is False
+ assert run.opts.index_only is True
+ assert run.opts.provider_name is None
+ assert run.opts.hook is True
+ assert run.global_mcp_consent is True
+
+
+def test_s_then_enter_keeps_the_global_entry(plan: Any, tmp_path: Path) -> None:
+ run = _run(tmp_path)
+ plan.drive(run, THIS_REPO, START)
+ assert run.global_mcp_consent is False
+
+
+def test_m_picks_a_model_and_enter_runs_it(
+ plan: Any, tmp_path: Path, monkeypatch: Any
+) -> None:
+ picked = provider_selection.ProviderSelection("openai", "gpt-test", "auto")
+ seen: dict[str, Any] = {}
+
+ def picker(*_a: Any, **kwargs: Any) -> Any:
+ seen.update(kwargs)
+ return picked
+
+ monkeypatch.setattr(plan.module, "interactive_provider_config_select", picker)
+ run = _run(tmp_path)
+ plan.drive(run, MODEL, START)
+ assert seen["subscription"].allow_skip is True
+ assert seen["subscription"].model_calls > 0
+ assert run.generate_docs is True
+ assert run.opts.index_only is False
+ assert (run.opts.provider_name, run.opts.model) == ("openai", "gpt-test")
+
+
+def test_m_with_no_key_goes_back_to_the_plan(
+ plan: Any, tmp_path: Path, monkeypatch: Any
+) -> None:
+ monkeypatch.setattr(plan.module, "interactive_provider_config_select", lambda *a, **k: None)
+ run = _run(tmp_path)
+ plan.drive(run, MODEL, START)
+ assert run.generate_docs is False
+ assert run.opts.index_only is True
+
+
+def test_q_quits_without_indexing(plan: Any, tmp_path: Path) -> None:
+ with pytest.raises(click.exceptions.Exit):
+ plan.drive(_run(tmp_path), QUIT)
+
+
+def test_eof_falls_back_to_the_non_interactive_path(
+ plan: Any, tmp_path: Path, monkeypatch: Any
+) -> None:
+ def eof(*_a: Any) -> str:
+ raise EOFError
+
+ monkeypatch.setattr(plan.module, "read_plan_key", eof)
+ run = _run(tmp_path)
+ plan.module.run_plan_screen(run, _SCAN)
+ assert run.is_interactive is False
+
+
+def test_explicit_no_hook_stays_off(plan: Any, tmp_path: Path) -> None:
+ run = _run(tmp_path, hook=False)
+ plan.drive(run, START)
+ assert run.opts.hook is False
+
+
+def test_offer_prefers_the_agent_set_up_here() -> None:
+ offer = build_offer(
+ {"openai": "OPENAI_API_KEY", "claude_cli": "agent CLI"},
+ ("claude_cli",),
+ RunShape(_SCAN),
+ )
+ assert offer.price is not None and offer.price.provider == "claude_cli"
+ assert build_offer({}, (), RunShape(_SCAN)) == ModelOffer()
+
+
+# -- -y help ------------------------------------------------------------------
+
+
+def test_yes_help_says_everything_it_skips() -> None:
+ result = CliRunner().invoke(cli, ["init", "--help"], terminal_width=200)
+ flat = " ".join(result.output.split())
+ for phrase in (
+ "Skips the plan screen",
+ "written by a model only when a provider is configured",
+ "used only with --provider",
+ "cost confirmation is accepted",
+ "advanced options keep their defaults",
+ "detected agents are connected",
+ "old and new target printed",
+ "post-commit hook is installed",
+ "distill rewrite hook is not",
+ ):
+ assert phrase in flat, phrase
+
+
+def test_eof_after_a_key_restores_the_run(plan: Any, tmp_path: Path, monkeypatch: Any) -> None:
+ def picker(*_a: Any, **_k: Any) -> Any:
+ raise EOFError
+
+ monkeypatch.setattr(plan.module, "interactive_provider_config_select", picker)
+ run = _run(tmp_path, run_mode="fast")
+ opts = run.opts
+ plan.drive(run, MODEL)
+ assert run.opts is opts
+ assert run.is_interactive is False
+
+
+def test_q_removes_the_repowise_dir_this_run_made(plan: Any, tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ run = _run(tmp_path)
+ run.repowise_dir_created = True
+ with pytest.raises(click.exceptions.Exit):
+ plan.drive(run, QUIT)
+ assert not (tmp_path / ".repowise").exists()
+
+
+def test_q_keeps_a_repowise_dir_that_was_there_or_holds_a_key(
+ plan: Any, tmp_path: Path
+) -> None:
+ (tmp_path / ".repowise").mkdir()
+ with pytest.raises(click.exceptions.Exit):
+ plan.drive(_run(tmp_path), QUIT)
+ assert (tmp_path / ".repowise").is_dir()
+
+ (tmp_path / ".repowise" / ".env").write_text("GEMINI_API_KEY=x\n")
+ run = _run(tmp_path)
+ run.repowise_dir_created = True
+ with pytest.raises(click.exceptions.Exit):
+ plan.drive(run, QUIT)
+ assert (tmp_path / ".repowise" / ".env").exists()
+
+
+# -- ETA ----------------------------------------------------------------------
+
+
+def _scan(source: int, commits: int) -> RepoScanInfo:
+ return RepoScanInfo(
+ total_files=source, language_counts={"Python": source}, total_commits=commits
+ )
+
+
+_BUILD = "to index and build the documentation."
+
+
+ ("source", "commits", "run_mode", "expected"),
+ [
+ # itsdangerous: about 10 s for the whole free run.
+ (16, 677, "standard", f"Under a minute {_BUILD}"),
+ # flask: 1m 51s, nearly all of it file history and co-changes.
+ (90, 5555, "standard", f"About 1-3 min {_BUILD}"),
+ # fastapi: 1m 41s as a fast index, 1m 24s to 1m 44s as a full free run.
+ (1186, 7860, "fast", "About 1-3 min to index."),
+ (1186, 7860, "standard", f"About 1-3 min {_BUILD}"),
+ ],
+)
+def test_eta_matches_measured_runs(
+ source: int, commits: int, run_mode: str, expected: str
+) -> None:
+ state = PlanState(repo_name="r", scan=_scan(source, commits), run_mode=run_mode)
+ assert expected in _render(state)
+
+
+def test_eta_counts_only_the_commits_the_limit_lets_git_walk() -> None:
+ state = PlanState(repo_name="r", scan=_scan(90, 5555), commit_limit=500)
+ assert f"Under a minute {_BUILD}" in _render(state)
+
+
+def test_eta_never_reads_zero_minutes() -> None:
+ from repowise.cli.ui.plan_screen.state import eta_phrase
+
+ assert eta_phrase(5, 59) == "under a minute"
+ assert eta_phrase(30, 61) == "about 1-2 min"
+ assert eta_phrase(200, 400) == "about 3-7 min"
+
+
+# -- model id -----------------------------------------------------------------
+
+
+def test_a_subscription_model_is_named_once() -> None:
+ offer = build_offer({"claude_cli": "agent CLI"}, (), RunShape(_SCAN))
+ assert offer.price is not None
+ out = _render(_state(offer=offer))
+ assert "claude_cli / claude_cli/" not in out
+ assert f"claude_cli / {offer.price.model_label}" in out
+ chosen = _render(_state(offer=offer, chosen=offer.price))
+ assert f"Written by {offer.price.model_label}" in chosen
+ assert "claude_cli/" not in chosen
+
+
+def test_back_from_the_gateway_keeps_the_picker_context(monkeypatch: Any) -> None:
+ seen: list[Any] = []
+ names = iter([provider_selection._OPENAI_COMPATIBLE_CHOICE, None])
+
+ def name(*_a: Any, subscription: Any, **_k: Any) -> Any:
+ seen.append(subscription)
+ return next(names)
+
+ monkeypatch.setattr(provider_selection, "_interactive_provider_name", name)
+ monkeypatch.setattr(
+ provider_selection, "_interactive_openai_compatible_select", lambda *a, **k: None
+ )
+ context = SubscriptionContext(allow_skip=True)
+
+ selection = provider_selection.interactive_provider_config_select(
+ Console(width=100), None, subscription=context
+ )
+
+ assert selection is None
+ assert seen == [context, context]
+
+
+# -- end of input inside the questions behind e and m -------------------------
+
+
+def _raise(exc: type[BaseException]):
+ def read(_prompt: str) -> str:
+ raise exc
+
+ return read
+
+
+def test_eof_inside_edit_falls_back_like_the_key_read(
+ plan: Any, tmp_path: Path, monkeypatch: Any
+) -> None:
+ monkeypatch.setattr(click.termui, "visible_prompt_func", _raise(EOFError))
+ run = _run(tmp_path)
+ opts = run.opts
+ plan.drive(run, EDIT)
+ assert run.is_interactive is False
+ assert run.opts is opts
+
+
+def test_eof_at_the_key_prompt_behind_m_falls_back_too(
+ plan: Any, tmp_path: Path, monkeypatch: Any
+) -> None:
+ monkeypatch.setattr(click.termui, "hidden_prompt_func", _raise(EOFError))
+ monkeypatch.setattr(provider_selection.Prompt, "ask", lambda *a, **k: "1")
+ run = _run(tmp_path)
+ plan.drive(run, MODEL)
+ assert run.is_interactive is False
+
+
+def test_ctrl_c_inside_edit_still_aborts(plan: Any, tmp_path: Path, monkeypatch: Any) -> None:
+ monkeypatch.setattr(click.termui, "visible_prompt_func", _raise(KeyboardInterrupt))
+ with pytest.raises(click.Abort):
+ plan.drive(_run(tmp_path), EDIT)
+
+
+def test_click_prompts_are_restored_after_the_screen(plan: Any, tmp_path: Path) -> None:
+ before = (click.termui.visible_prompt_func, click.termui.hidden_prompt_func)
+ plan.drive(_run(tmp_path), START)
+ assert (click.termui.visible_prompt_func, click.termui.hidden_prompt_func) == before
+
+
+# -- after Enter: the plan is not repeated -------------------------------------
+
+
+def _announce(run: Any, monkeypatch: Any) -> str:
+ from repowise.cli.commands.init_cmd import _provider
+
+ console = Console(record=True, width=100, color_system=None)
+ monkeypatch.setattr(_provider, "console", console)
+ _provider.announce_index_only(run)
+ return " ".join(console.export_text().split())
+
+
+def test_after_the_plan_screen_the_forecast_is_not_repeated(
+ tmp_path: Path, monkeypatch: Any
+) -> None:
+ run = _run(tmp_path, index_only=True, editor_setup=False)
+ assert _announce(run, monkeypatch) == ""
+ assert "MCP" not in _announce(run, monkeypatch)
+
+
+def test_a_run_without_the_screen_still_says_what_it_builds(
+ tmp_path: Path, monkeypatch: Any
+) -> None:
+ run = _run(tmp_path, index_only=True)
+ run.is_interactive = False
+ out = _announce(run, monkeypatch)
+ assert "Built from code" in out
+ assert "no model, no spend" in out
diff --git a/tests/unit/cli/test_ui_package.py b/tests/unit/cli/test_ui_package.py
index dd4065c4c..39b004145 100644
--- a/tests/unit/cli/test_ui_package.py
+++ b/tests/unit/cli/test_ui_package.py
@@ -29,14 +29,11 @@ def test_facade_reexports_public_surface() -> None:
"interactive_provider_select",
"interactive_advanced_config",
"interactive_mode_select",
- "interactive_fast_mode_offer",
"interactive_repo_select",
"interactive_primary_select",
"should_offer_fast_mode",
"print_banner",
"print_phase_header",
- "print_scan_summary",
- "print_index_only_intro",
"quick_repo_scan",
"build_completion_panel",
"build_contextual_next_steps",