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): a folder of repos gets the same plan screen, with the repo list and r to choose (#4262)

Raghav Chamadiyad4f7c79fe5c4
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_plan.py b/packages/cli/src/repowise/cli/commands/init_cmd/_plan.py
index a38341df4..243491e86 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_plan.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_plan.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import contextlib
from dataclasses import dataclass, replace
+from pathlib import Path
from typing import Any
import click
@@ -47,12 +48,12 @@ class _Answers:
git_exclude: bool = False
-def _outside_lines(run: InitRun) -> tuple[str, ...]:
+def outside_lines(repo_path: Path) -> 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)
+ target = read_global_mcp_target(repo_path)
# A probe failure never blocks the screen; JSONDecodeError is a ValueError.
except (OSError, ValueError, KeyError, TypeError):
return ()
@@ -136,7 +137,7 @@ def _base_state(run: InitRun, scan: Any, prefer: tuple[str, ...]) -> PlanState:
scan=scan,
offer=offer,
editor_setup=editor_setup,
- outside=_outside_lines(run) if editor_setup else (),
+ outside=outside_lines(run.repo_path) if editor_setup else (),
large_repo=should_offer_fast_mode(scan),
)
@@ -264,6 +265,15 @@ def _until_enter(
return
+def say_no_answer() -> None:
+ """The line a plan screen prints when stdin ends before Enter."""
+ 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]"
+ )
+
+
def run_plan_screen(run: InitRun, scan: Any) -> None:
"""Show the plan, act on keys until Enter, then fold the answers into *run*.
@@ -284,10 +294,6 @@ def run_plan_screen(run: InitRun, scan: Any) -> None:
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]"
- )
+ say_no_answer()
return
_apply(run, base, answers)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_plan.py b/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_plan.py
new file mode 100644
index 000000000..7eae26d3d
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_workspace_plan.py
@@ -0,0 +1,274 @@
+"""The plan screen of an interactive workspace init: what each key changes."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import console, load_config
+from repowise.cli.providers import resolve_embedder
+from repowise.cli.ui import (
+ OWL_SPINNER,
+ agent_providers_set_up,
+ interactive_advanced_config,
+ interactive_provider_config_select,
+ quick_repo_scan,
+)
+from repowise.cli.ui.plan_screen import (
+ EDIT,
+ MODEL,
+ QUIT,
+ REPOS,
+ THIS_REPO,
+ PlanState,
+ build_offer,
+ end_of_input_is_eof,
+ model_calls_for,
+ price_model,
+ read_plan_key,
+)
+from repowise.cli.ui.plan_screen.workspace import (
+ WorkspacePlanState,
+ WorkspaceRepo,
+ choose_repos,
+ render_workspace_plan,
+)
+from repowise.cli.ui.subscription import SubscriptionContext
+
+from ._plan import outside_lines, say_no_answer
+
+
+@dataclass
+class WorkspaceAnswers:
+ """The run settings the plan screen (or the flags alone) settle for every repo."""
+
+ index_only: bool
+ provider_name: str | None
+ model: str | None
+ reasoning: str | None
+ commit_limit: int | None
+ follow_renames: bool
+ skip_tests: bool
+ skip_infra: bool
+ concurrency: int
+ exclude_patterns: list[str]
+ test_run: bool
+ onboarding: bool
+ wiki_style: str
+ language: str | None
+ #: ``--embedder`` or the one chosen under ``e``; resolved once keys are loaded.
+ embedder_name: str | None = None
+ embedder_name_resolved: str = "mock"
+
+
+def apply_workspace_advanced(answers: WorkspaceAnswers, adv: dict[str, Any]) -> None:
+ """Fold the advanced-config answers into the workspace run."""
+ answers.commit_limit = adv.get("commit_limit") or answers.commit_limit
+ answers.follow_renames = adv.get("follow_renames", answers.follow_renames)
+ answers.skip_tests = adv.get("skip_tests", answers.skip_tests)
+ answers.skip_infra = adv.get("skip_infra", answers.skip_infra)
+ answers.concurrency = adv.get("concurrency", answers.concurrency)
+ if adv.get("exclude"):
+ answers.exclude_patterns = list(answers.exclude_patterns) + list(adv["exclude"])
+ answers.test_run = adv.get("test_run", answers.test_run)
+ answers.reasoning = adv.get("reasoning") or answers.reasoning
+ answers.embedder_name = adv.get("embedder") or answers.embedder_name
+ answers.embedder_name_resolved = resolve_embedder(answers.embedder_name)
+ answers.onboarding = adv.get("onboarding", answers.onboarding)
+ if adv.get("wiki_style"):
+ answers.wiki_style = adv["wiki_style"]
+ if adv.get("language"):
+ answers.language = adv["language"]
+
+
+@dataclass
+class WorkspacePlan:
+ """What Enter on the workspace screen settled."""
+
+ selected: list[Any]
+ primary_alias: str
+ answers: WorkspaceAnswers
+ #: The post-commit hook answer; ``None`` leaves it to the flags.
+ sync: bool | None = None
+ #: ``True`` / ``False`` answered the global MCP question; ``None`` never asked it.
+ global_consent: bool | None = None
+
+
+@dataclass
+class _Screen:
+ """What stays put while the screen is up, and what the keys change."""
+
+ state: WorkspacePlanState
+ detected: dict[str, str]
+ prefer: tuple[str, ...]
+ editor_options: Any
+ selection: Any = None
+ sync: bool = True
+
+
+def _primary_path(screen: _Screen) -> Any:
+ return next(r.repo.path for r in screen.state.repos if r.repo.alias == screen.state.primary)
+
+
+def _refresh(screen: _Screen, answers: WorkspaceAnswers) -> None:
+ """Re-plan for the current pick: prices, agents and the outside line follow it."""
+ from repowise.cli.editor_setup import planned_agents
+ from repowise.cli.providers import template_run_embedder
+ from repowise.cli.providers.embedders import embedder_was_requested
+
+ state = screen.state
+ state.onboarding = answers.onboarding
+ primary = _primary_path(screen)
+ shape = state.shape(answers.onboarding, answers.concurrency)
+ chosen = (
+ price_model(screen.selection.provider_name, screen.selection.model, shape)
+ if screen.selection is not None
+ else None
+ )
+ resolved = resolve_embedder(answers.embedder_name)
+ requested = embedder_was_requested(
+ answers.embedder_name, load_config(primary).get("embedder")
+ )
+ plan = state.plan
+ state.plan = replace(
+ plan,
+ repo_name=primary.name,
+ scan=next(r.scan for r in state.repos if r.repo.alias == state.primary),
+ chosen=chosen,
+ offer=build_offer(screen.detected, screen.prefer, shape),
+ free_embedder=template_run_embedder(resolved, requested),
+ model_embedder=resolved,
+ agents=planned_agents(primary, screen.editor_options) if plan.editor_setup else (),
+ sync=screen.sync,
+ outside=outside_lines(primary) if plan.editor_setup else (),
+ )
+
+
+def _pick_model(screen: _Screen, answers: WorkspaceAnswers, save_key: bool) -> None:
+ """``m``: the picker, or back to built from code when a model is already picked."""
+ if screen.selection is not None:
+ screen.selection = None
+ return
+ screen.selection = interactive_provider_config_select(
+ console,
+ answers.model,
+ answers.reasoning,
+ repo_path=_primary_path(screen),
+ save_key=save_key,
+ subscription=SubscriptionContext(
+ prefer=screen.prefer,
+ model_calls=model_calls_for(
+ screen.state.shape(answers.onboarding, answers.concurrency)
+ ),
+ concurrency=answers.concurrency,
+ allow_skip=True,
+ ),
+ )
+
+
+def _edit_plan(screen: _Screen, answers: WorkspaceAnswers) -> None:
+ """``e``: the advanced options, then the sync hook. One answer for every repo."""
+ adv = interactive_advanced_config(
+ console,
+ prompt_reasoning=False,
+ generate_docs=screen.selection is not None,
+ wiki_style=answers.wiki_style,
+ language=answers.language,
+ commit_limit=answers.commit_limit,
+ ask_file_pages=False,
+ )
+ apply_workspace_advanced(answers, adv)
+ if screen.state.plan.editor_setup:
+ screen.sync = click.confirm(
+ " Keep each index in sync after each commit (post-commit hook)?",
+ default=screen.sync,
+ )
+
+
+def _until_enter(screen: _Screen, answers: WorkspaceAnswers, save_key: bool) -> None:
+ """Render, read a key, act on it; return on Enter."""
+ while True:
+ _refresh(screen, answers)
+ console.print()
+ render_workspace_plan(console, screen.state)
+ action = read_plan_key(console, screen.state.plan, extra={"r": REPOS})
+ if action == QUIT:
+ console.print(" [dim]Nothing indexed.[/dim]")
+ raise click.exceptions.Exit(0)
+ if action == MODEL:
+ _pick_model(screen, answers, save_key)
+ elif action == EDIT:
+ _edit_plan(screen, answers)
+ elif action == REPOS:
+ choose_repos(console, screen.state)
+ elif action == THIS_REPO:
+ plan = screen.state.plan
+ screen.state.plan = replace(plan, this_repo_only=not plan.this_repo_only)
+ else:
+ return
+
+
+def run_workspace_plan_screen(
+ scan: Any,
+ answers: WorkspaceAnswers,
+ *,
+ editor_options: Any,
+ editor_setup: bool,
+ save_key: bool,
+ hook: bool | None,
+) -> WorkspacePlan | None:
+ """Show the workspace plan, act on keys until Enter, and return what it settled.
+
+ ``None`` when nobody can answer (EOF on the first read or inside a
+ question): the caller runs the non-interactive defaults, every repo
+ with the first as primary. Ctrl-C still stops the run.
+ """
+ from repowise.cli.editor_setup import is_editor_setup_disabled
+ from repowise.cli.ui.provider_selection import _detect_provider_status
+
+ repos = list(scan.repos)
+ with console.status(" Scanning repositories…", spinner=OWL_SPINNER):
+ rows = [WorkspaceRepo(repo, quick_repo_scan(repo.path)) for repo in repos]
+ with console.status(" Checking for a model…"):
+ detected = _detect_provider_status(repos[0].path)
+ work = replace(answers, exclude_patterns=list(answers.exclude_patterns))
+ screen = _Screen(
+ state=WorkspacePlanState(
+ root=scan.root,
+ repos=rows,
+ selected=list(range(len(rows))),
+ primary=repos[0].alias,
+ plan=PlanState(
+ repo_name=repos[0].name,
+ scan=rows[0].scan,
+ editor_setup=not is_editor_setup_disabled(not editor_setup),
+ ),
+ ),
+ detected=detected,
+ prefer=agent_providers_set_up(repos[0].path),
+ editor_options=editor_options,
+ sync=hook if hook is not None else True,
+ )
+ try:
+ # The questions behind m, e and r end the same way as the key read.
+ with end_of_input_is_eof():
+ _until_enter(screen, work, save_key)
+ except EOFError:
+ say_no_answer()
+ return None
+ selection = screen.selection
+ work.index_only = selection is None
+ if selection is not None:
+ work.provider_name = selection.provider_name
+ work.model = selection.model
+ work.reasoning = selection.reasoning
+ plan = screen.state.plan
+ return WorkspacePlan(
+ selected=[r.repo for r in screen.state.picked],
+ primary_alias=screen.state.primary,
+ answers=work,
+ sync=screen.sync if plan.editor_setup and hook is None else None,
+ global_consent=(not plan.this_repo_only) if plan.can_keep_global else None,
+ )
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 5c51604e3..4bb7b7866 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import os
import sys
import time
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -56,16 +56,11 @@ from repowise.cli.ui import (
OK,
VALUE,
WARN,
- interactive_advanced_config,
- interactive_mode_select,
- interactive_provider_config_select,
load_dotenv,
print_banner,
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
from repowise.core.generation.styles import DEFAULT_STYLE
@@ -75,6 +70,7 @@ from ._exit import COST_UNCONFIRMED_BUILT, exit_on_gaps
from ._ingest import structural_generation_config
from ._interactive import offer_distill_rewrite_hook, offer_hook_install
from ._workspace_config import WorkspacePick, build_workspace_config
+from ._workspace_plan import WorkspaceAnswers, WorkspacePlan, run_workspace_plan_screen
from ._workspace_repos import repos_primary_line, select_workspace_repos
from .generation import (
CostGateDeclined,
@@ -739,27 +735,6 @@ def _run_cross_repo_analysis(ws_config: Any, root: Any, selected: list[Any], err
console.print(f" [{WARN}]⚠ Cross-repo analysis failed: {exc}[/]")
-@dataclass
-class _WorkspaceAnswers:
- """The run settings the mode menu, advanced config and provider setup may change."""
-
- index_only: bool
- provider_name: str | None
- model: str | None
- reasoning: str | None
- commit_limit: int | None
- follow_renames: bool
- skip_tests: bool
- skip_infra: bool
- concurrency: int
- exclude_patterns: list[str]
- test_run: bool
- onboarding: bool
- wiki_style: str
- language: str | None
- embedder_name_resolved: str
-
-
@dataclass
class _WorkspaceTotals:
"""What the per-repo loop indexed, and what failed."""
@@ -822,17 +797,8 @@ def _workspace_init(
root = scan.root
print_banner(console, repo_name=f"Workspace: {root.name}")
- console.print(f" Detected [bold]{len(scan.repos)}[/bold] repositories in {root}\n")
-
- pick = select_workspace_repos(scan, repo_names=repo_names, select_all=init_all or yes)
- if pick is None:
- return
- selected, primary_alias, primary_repo = pick.selected, pick.primary_alias, pick.primary_repo
- load_dotenv(primary_repo.path)
- # --yes suppresses every prompt, so it means non-interactive.
- is_interactive = sys.stdin.isatty() and provider_name is None and not index_only and not yes
- answers = _WorkspaceAnswers(
+ answers = WorkspaceAnswers(
index_only=index_only,
provider_name=provider_name,
model=model,
@@ -847,18 +813,38 @@ def _workspace_init(
onboarding=onboarding,
wiki_style=wiki_style,
language=language,
- embedder_name_resolved=resolve_embedder(embedder_name),
+ embedder_name=embedder_name,
)
+ editor_options = _workspace_editor_options(no_claude_md, agents_md, codex_setup)
+ picked = _settle_repos(
+ scan,
+ answers,
+ repo_names=repo_names,
+ interactive=sys.stdin.isatty() and provider_name is None and not index_only and not yes,
+ select_all=init_all or yes or not sys.stdin.isatty(),
+ editor_options=editor_options,
+ editor_setup=editor_setup,
+ save_key=save_key,
+ hook=hook,
+ )
+ if picked is None:
+ return
+ pick, plan = picked
+ selected, primary_alias = pick.selected, pick.primary_alias
+ if plan is not None:
+ answers = plan.answers
+ hook = plan.sync if plan.sync is not None else hook
+ primary_repo = pick.primary_repo
+ load_dotenv(primary_repo.path)
+ answers.embedder_name_resolved = resolve_embedder(answers.embedder_name)
# Whether the user named this embedder, rather than resolve_embedder
# inferring one from an LLM key: the free template path will not put a
# hosted embedder on the user's bill unless they named it.
- embedder_was_requested = bool(embedder_name) or bool(
+ embedder_was_requested = bool(answers.embedder_name) or bool(
os.environ.get("REPOWISE_EMBEDDER", "").strip()
)
- if is_interactive:
- _ask_workspace_mode(answers, selected, primary_repo, embedder_name, save_key=save_key)
provider, resolved_reasoning = _resolve_workspace_provider(
- answers, primary_repo, embedder_name, yes=yes, save_key=save_key
+ answers, primary_repo, yes=yes, save_key=save_key
)
ws_config = _workspace_config(pick, ask=sys.stdin.isatty() and not yes, dry_run=dry_run)
if repo_names:
@@ -869,7 +855,7 @@ def _workspace_init(
ctx = _WorkspaceCtx(
provider=provider,
ws_config=ws_config,
- editor_options=_workspace_editor_options(no_claude_md, agents_md, codex_setup),
+ editor_options=editor_options,
editor_setup=editor_setup,
save_key=save_key,
index_only=answers.index_only,
@@ -898,7 +884,13 @@ def _workspace_init(
# A dry run writes nothing for any repo, so nothing at the workspace level.
if not dry_run:
_save_workspace(
- ws_config, root, selected, totals.errors, editor_setup=editor_setup, yes=yes
+ ws_config,
+ root,
+ selected,
+ totals.errors,
+ editor_setup=editor_setup,
+ yes=yes,
+ global_consent=plan.global_consent if plan is not None else None,
)
show_workspace_completion(
@@ -927,6 +919,57 @@ def _workspace_init(
exit_on_gaps(_workspace_gaps(ctx, totals))
+def _settle_repos(
+ scan: Any,
+ answers: WorkspaceAnswers,
+ *,
+ repo_names: list[str],
+ interactive: bool,
+ select_all: bool,
+ editor_options: Any,
+ editor_setup: bool,
+ save_key: bool,
+ hook: bool | None,
+) -> tuple[WorkspacePick, WorkspacePlan | None] | None:
+ """The picked repos and primary, and the plan screen's answers; None to stop.
+
+ ``--repos`` is matched first (an unknown name stops the run); the plan
+ screen then shows only those repos. *interactive* shows the plan screen (a
+ terminal, no --yes, --provider or --no-prose); *select_all* takes every
+ repo without asking.
+ """
+ named = None
+ if repo_names:
+ named = select_workspace_repos(scan, repo_names=repo_names, select_all=True)
+ if named is None:
+ return None
+ scan = replace(scan, repos=list(named.selected))
+ if interactive:
+ plan = run_workspace_plan_screen(
+ scan,
+ answers,
+ editor_options=editor_options,
+ editor_setup=editor_setup,
+ save_key=save_key,
+ hook=hook,
+ )
+ if plan is not None:
+ primary_repo = next(r for r in plan.selected if r.alias == plan.primary_alias)
+ # The screen defaults to the first repo; only a changed primary replaces
+ # the one an existing workspace config names.
+ primary_picked = plan.primary_alias != plan.selected[0].alias
+ pick = WorkspacePick(
+ plan.selected, scan.root, plan.primary_alias, primary_repo, primary_picked
+ )
+ return pick, plan
+ # Stdin ended, so nobody is there to pick repos either.
+ select_all = True
+ if named is not None:
+ return named, None
+ pick = select_workspace_repos(scan, repo_names=[], select_all=select_all)
+ return None if pick is None else (pick, None)
+
+
def _save_workspace(
ws_config: Any,
root: Path,
@@ -935,94 +978,42 @@ def _save_workspace(
*,
editor_setup: bool,
yes: bool,
+ global_consent: bool | None = None,
) -> None:
- """Save the indexed timestamps, run cross-repo analysis, register the primary."""
+ """Save the indexed timestamps, run cross-repo analysis, register the primary.
+
+ *global_consent* is the plan screen's answer for the global MCP entry;
+ ``None`` when the screen did not ask.
+ """
ws_config.save(root)
_run_cross_repo_analysis(ws_config, root, selected, errors)
primary_entry = ws_config.get_primary()
- if primary_entry:
- primary_path = (root / primary_entry.path).resolve()
- from repowise.cli.editor_integrations.global_mcp import confirm_global_mcp
-
- if confirm_global_mcp(console, primary_path, yes=yes, no_editor_setup=not editor_setup):
- register_editor_clients(console, primary_path)
-
-
-def _ask_workspace_mode(
- answers: _WorkspaceAnswers,
- selected: list[Any],
- primary_repo: Any,
- embedder_name: str | None,
- *,
- save_key: bool,
-) -> None:
- """The mode menu, then the provider (and advanced config) it calls for."""
- mode = interactive_mode_select(
- console,
- title=f"How much should repowise write for {plural(len(selected), 'repo')}?",
+ if not primary_entry:
+ return
+ from repowise.cli.editor_integrations.global_mcp import (
+ REGISTER_LATER_COMMAND,
+ confirm_global_mcp,
)
- if mode == "index_only":
- answers.index_only = True
- elif mode == "advanced":
- _ask_workspace_provider(answers, primary_repo, save_key=save_key)
- # The resolved style keeps the advanced section from asking per
- # workspace: one style applies to every repo.
- adv = interactive_advanced_config(
- console,
- prompt_reasoning=False,
- generate_docs=not answers.index_only,
- wiki_style=answers.wiki_style,
- language=answers.language,
- )
- _apply_workspace_advanced(answers, adv, embedder_name)
- elif not answers.index_only:
- _ask_workspace_provider(answers, primary_repo, save_key=save_key)
-
-def _ask_workspace_provider(
- answers: _WorkspaceAnswers, primary_repo: Any, *, save_key: bool
-) -> None:
- selection = interactive_provider_config_select(
+ primary_path = (root / primary_entry.path).resolve()
+ if global_consent is False:
+ console.print(
+ " [dim]Global Claude config left as is (this workspace only). Run "
+ f"'{REGISTER_LATER_COMMAND}' in the primary repo to point it here later.[/dim]"
+ )
+ elif confirm_global_mcp(
console,
- answers.model,
- 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
-
-
-def _apply_workspace_advanced(
- answers: _WorkspaceAnswers, adv: dict[str, Any], embedder_name: str | None
-) -> None:
- """Fold the advanced-config answers into the workspace run."""
- answers.commit_limit = adv.get("commit_limit") or answers.commit_limit
- answers.follow_renames = adv.get("follow_renames", answers.follow_renames)
- answers.skip_tests = adv.get("skip_tests", answers.skip_tests)
- answers.skip_infra = adv.get("skip_infra", answers.skip_infra)
- answers.concurrency = adv.get("concurrency", answers.concurrency)
- if adv.get("exclude"):
- answers.exclude_patterns = list(answers.exclude_patterns) + list(adv["exclude"])
- answers.test_run = adv.get("test_run", answers.test_run)
- answers.reasoning = adv.get("reasoning") or answers.reasoning
- answers.embedder_name_resolved = resolve_embedder(adv.get("embedder") or embedder_name)
- answers.onboarding = adv.get("onboarding", answers.onboarding)
- if adv.get("wiki_style"):
- answers.wiki_style = adv["wiki_style"]
- if adv.get("language"):
- answers.language = adv["language"]
+ primary_path,
+ # Answered on the plan screen: print old and new, do not ask again.
+ yes=yes or global_consent is True,
+ no_editor_setup=not editor_setup,
+ ):
+ register_editor_clients(console, primary_path)
def _resolve_workspace_provider(
- answers: _WorkspaceAnswers,
+ answers: WorkspaceAnswers,
primary_repo: Any,
- embedder_name: str | None,
*,
yes: bool,
save_key: bool,
@@ -1042,7 +1033,7 @@ def _resolve_workspace_provider(
)
# Re-resolve: interactive provider selection may just have set the
# provider's API key in os.environ.
- answers.embedder_name_resolved = resolve_embedder(embedder_name)
+ answers.embedder_name_resolved = resolve_embedder(answers.embedder_name)
console.print(
f" Provider: [{VALUE}]{provider.provider_name}[/] / "
f"Model: [{VALUE}]{provider.model_name}[/]"
diff --git a/packages/cli/src/repowise/cli/ui/__init__.py b/packages/cli/src/repowise/cli/ui/__init__.py
index 7e361b152..a2909d724 100644
--- a/packages/cli/src/repowise/cli/ui/__init__.py
+++ b/packages/cli/src/repowise/cli/ui/__init__.py
@@ -46,7 +46,6 @@ _LAZY: dict[str, str] = {
"format_bytes": "brand",
"format_elapsed": "brand",
"interactive_advanced_config": "mode_selection",
- "interactive_mode_select": "mode_selection",
"interactive_primary_select": "workspace_selection",
"interactive_provider_config_select": "provider_selection",
"interactive_provider_select": "provider_selection",
diff --git a/packages/cli/src/repowise/cli/ui/mode_selection.py b/packages/cli/src/repowise/cli/ui/mode_selection.py
index 354bfd892..735ab5cfa 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 and advanced configuration."""
+"""Interactive advanced configuration and the questions it shares."""
from __future__ import annotations
@@ -7,14 +7,11 @@ from typing import Any
import click
from rich.console import Console
-from rich.panel import Panel
from rich.prompt import Prompt
from rich.rule import Rule
-from rich.text import Text
from repowise.cli.ui.brand import (
BRAND,
- BRAND_STYLE,
DIM,
VALUE,
key_value_table,
@@ -53,59 +50,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_mode_select(console: Console, *, title: str | None = None) -> str:
- """Let the user choose full / index-only / advanced.
-
- All three options index identically; what differs is how much of the wiki a
- model writes, so the panel asks that rather than "how would you like to
- index". *title* overrides the question for callers indexing more than one
- repo (the workspace flow shows this same panel for a whole workspace).
-
- Returns ``"full"``, ``"index_only"``, or ``"advanced"``.
- """
- body = Text()
- body.append(" [1]", style=BRAND_STYLE)
- body.append(f" {written_by()} ", style="bold")
- body.append("(recommended, needs an API key)\n", style="dim")
- body.append(" Dependency graph, git history, code health, architectural\n")
- body.append(" decisions, and documentation a model writes, with\n")
- body.append(" architecture diagrams and API docs.\n")
- body.append(
- " Costs a few cents to a few dollars; you see the estimate\n"
- " before anything runs.\n\n",
- style="dim",
- )
-
- body.append(" [2]", style=BRAND_STYLE)
- body.append(f" {BUILT_FROM_CODE} ", style="bold")
- body.append("(no key, no spend)\n", style="dim")
- body.append(" The same index, with every documentation page built from the code.\n")
- body.append(" Subsystem pages come out as outlines; add a key later and run\n")
- body.append(" repowise generate to have a model write them.\n\n")
-
- body.append(" [3]", style=BRAND_STYLE)
- body.append(" Advanced\n", style="bold")
- body.append(" Full control: choose who writes the documentation, then tune indexing\n")
- body.append(" and generation (commit limit, exclude patterns, concurrency, ...)")
-
- console.print(
- Panel(
- body,
- title=f"[bold]{title or 'How much should repowise write?'}[/bold]",
- border_style=BRAND,
- padding=(1, 2),
- )
- )
-
- choice = Prompt.ask(
- " Select mode",
- choices=["1", "2", "3"],
- default="1",
- console=console,
- )
- return {"1": "full", "2": "index_only", "3": "advanced"}[choice]
-
-
def prompt_wiki_style(console: Console) -> str:
"""Interactive picker for the wiki documentation style.
@@ -501,9 +445,13 @@ def interactive_advanced_config(
wiki_style: str | None = None,
language: str | None = None,
commit_limit: int | None = None,
+ ask_file_pages: bool = True,
) -> dict[str, Any]:
"""Prompt for advanced init options, grouped into logical sections.
+ *ask_file_pages* is off for a workspace: each repo keeps the file-page
+ cap in its own config.yaml, so one answer would apply nowhere.
+
When *scan* is provided, uses it for smart defaults and contextual hints
(file counts, suggested exclude patterns, etc.).
@@ -542,7 +490,7 @@ def interactive_advanced_config(
# 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.
- if result.get("run_mode") != "fast":
+ if ask_file_pages and result.get("run_mode") != "fast":
result["max_file_pages"] = prompt_file_page_volume(console, scan)
if generate_docs:
_prompt_generation(
diff --git a/packages/cli/src/repowise/cli/ui/plan_screen/__init__.py b/packages/cli/src/repowise/cli/ui/plan_screen/__init__.py
index a5877a068..b74eaf843 100644
--- a/packages/cli/src/repowise/cli/ui/plan_screen/__init__.py
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/__init__.py
@@ -8,12 +8,13 @@ from repowise.cli.ui.plan_screen.keys import (
EDIT,
MODEL,
QUIT,
+ REPOS,
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.render import render_plan, render_plan_body
from repowise.cli.ui.plan_screen.state import (
ModelOffer,
ModelPrice,
@@ -28,6 +29,7 @@ __all__ = [
"EDIT",
"MODEL",
"QUIT",
+ "REPOS",
"START",
"THIS_REPO",
"ModelOffer",
@@ -40,4 +42,5 @@ __all__ = [
"price_model",
"read_plan_key",
"render_plan",
+ "render_plan_body",
]
diff --git a/packages/cli/src/repowise/cli/ui/plan_screen/keys.py b/packages/cli/src/repowise/cli/ui/plan_screen/keys.py
index 559ff3db2..e2ebdad4c 100644
--- a/packages/cli/src/repowise/cli/ui/plan_screen/keys.py
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/keys.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
import click.termui
@@ -12,8 +12,9 @@ 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"
+#: Workspace only: choose the repos and the primary.
+REPOS = "repos"
-_KEYS = {"": START, "m": MODEL, "e": EDIT, "s": THIS_REPO, "q": QUIT}
class _InputEndedError(Exception):
@@ -50,10 +51,15 @@ def end_of_input_is_eof() -> Iterator[None]:
def read_plan_key(
- console: Console, state: PlanState, ask: Callable[[], str] | None = None
+ console: Console,
+ state: PlanState,
+ ask: Callable[[], str] | None = None,
+ extra: Mapping[str, str] | None = None,
) -> str:
"""The action for the next key: start, model, edit, this_repo or quit.
+ *extra* maps further keys to actions, offered on this screen only.
+
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,
@@ -65,12 +71,14 @@ def read_plan_key(
def ask() -> str:
return Prompt.ask(" Choice", default="", show_default=False, console=console)
+ keys = {"": START, "m": MODEL, "e": EDIT, **(extra or {})}
+ if state.can_keep_global:
+ keys["s"] = THIS_REPO
+ keys["q"] = QUIT
+ offered = [k for k in keys if k]
+ hint = ", ".join(offered[:-1]) + f" or {offered[-1]}"
while True:
- raw = ask().strip().lower()
- action = _KEYS.get(raw)
- if action == THIS_REPO and not state.can_keep_global:
- action = None
+ action = keys.get(ask().strip().lower())
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]")
+ console.print(f" [dim]Press Enter to start, or {hint}.[/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
index 11a73827b..16de2a0e7 100644
--- a/packages/cli/src/repowise/cli/ui/plan_screen/render.py
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/render.py
@@ -166,9 +166,9 @@ def _print_outside(console: Console, state: PlanState) -> None:
_say(console, "[dim]Press s to leave it as is and connect this repo only.[/dim]")
-def _key_line(state: PlanState) -> str:
+def _key_line(state: PlanState, extra_keys: tuple[tuple[str, str], ...]) -> 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")]
+ keys = [("Enter", "start"), ("m", model_key), ("e", "edit plan"), *extra_keys]
if state.can_keep_global:
keys.append(("s", "point it here" if state.this_repo_only else "this repo only"))
keys.append(("q", "quit"))
@@ -186,6 +186,21 @@ def render_plan(console: Console, state: PlanState) -> None:
f"({INDEX_ONLY.lower()}) is recommended: choose run mode fast under e.[/dim]",
indent=2,
)
+ render_plan_body(console, state)
+
+
+def render_plan_body(
+ console: Console,
+ state: PlanState,
+ *,
+ extra_keys: tuple[tuple[str, str], ...] = (),
+ edit_preview: str = EDIT_PREVIEW,
+) -> None:
+ """The plan rows, the model opt-in, the outside line and the keys.
+
+ Shared by the single-repo and the workspace screen; each prints its own
+ header above it and may offer *extra_keys* before ``s`` and ``q``.
+ """
console.print()
console.print(_plan_heading(state))
rows = [
@@ -201,5 +216,5 @@ def render_plan(console: Console, state: PlanState) -> None:
_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)
+ _say(console, _key_line(state, extra_keys).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
index b67e0881f..907282194 100644
--- a/packages/cli/src/repowise/cli/ui/plan_screen/state.py
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/state.py
@@ -79,19 +79,26 @@ class RunShape:
scan: RepoScanInfo
onboarding: bool = True
concurrency: int = 10
+ #: The other repos of a workspace run, each planned as its own repo.
+ also: tuple[RepoScanInfo, ...] = ()
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)
+ return [
+ plan
+ for scan in (shape.scan, *shape.also)
+ if scan.total_files
+ for plan in approximate_generation_plan(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
+ return model_call_count(_plans(shape))
def price_model(provider: str, model: str, shape: RunShape) -> ModelPrice:
diff --git a/packages/cli/src/repowise/cli/ui/plan_screen/workspace.py b/packages/cli/src/repowise/cli/ui/plan_screen/workspace.py
new file mode 100644
index 000000000..bf24dc570
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/plan_screen/workspace.py
@@ -0,0 +1,218 @@
+"""The workspace plan screen: the repos found, which ones run, and the shared plan."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import dataclass, replace
+from pathlib import Path
+from typing import Any
+
+from rich.console import Console
+from rich.markup import escape
+from rich.padding import Padding
+from rich.prompt import Prompt
+from rich.table import Table
+from rich.text import Text
+
+from repowise.cli.ui.brand import BRAND_STYLE, OK, WARN
+from repowise.cli.ui.plan_screen.render import render_plan_body
+from repowise.cli.ui.plan_screen.state import (
+ PlanState,
+ RunShape,
+ eta_phrase,
+ eta_seconds,
+ model_calls_for,
+)
+from repowise.cli.ui.repo_scanner import RepoScanInfo
+from repowise.cli.ui.workspace_selection import (
+ display_path,
+ interactive_primary_select,
+ parse_selection,
+)
+
+#: Rows the screen lists before it summarises the rest; ``r`` lists them all.
+ROWS_SHOWN = 12
+
+#: What ``e`` opens on a workspace: one set of answers for every repo.
+WORKSPACE_EDIT_PREVIEW = (
+ "scope, excludes, commit limit, embedder and sync for every repo, plus "
+ "concurrency, style and language with a model"
+)
+
+REPOS_KEY = ("r", "choose repos")
+
+
+@dataclass(frozen=True)
+class WorkspaceRepo:
+ """One repo the workspace scan found, with its pre-scan."""
+
+ repo: Any
+ scan: RepoScanInfo
+
+
+@dataclass
+class WorkspacePlanState:
+ """One render of the workspace screen: the repos, the pick and the plan."""
+
+ root: Path
+ repos: list[WorkspaceRepo]
+ #: Zero-based indices into *repos*, in workspace order.
+ selected: list[int]
+ primary: str
+ plan: PlanState
+ #: Sizes each repo's model calls, as the combined price does.
+ onboarding: bool = True
+
+ @property
+ def picked(self) -> list[WorkspaceRepo]:
+ return [self.repos[i] for i in self.selected]
+
+ def shape(self, onboarding: bool = True, concurrency: int = 10) -> RunShape:
+ """The selected repos, priced together and each planned as its own repo."""
+ scans = [r.scan for r in self.picked] or [RepoScanInfo()]
+ return RunShape(scans[0], onboarding, concurrency, also=tuple(scans[1:]))
+
+
+def _plural(n: int, word: str) -> str:
+ return f"{n:,} {word}" + ("" if n == 1 else "s")
+
+
+def _eta_line(state: WorkspacePlanState) -> str:
+ low = high = 0.0
+ for repo in state.picked:
+ lo, hi = eta_seconds(replace(state.plan, scan=repo.scan, chosen=None))
+ low, high = low + lo, high + hi
+ what = "to index and build the documentation"
+ chosen = state.plan.chosen
+ if chosen is not None:
+ low, high = low + chosen.minutes * 60, high + chosen.minutes * 60
+ what = "to index and write the documentation"
+ phrase = eta_phrase(low, high)
+ return f"{phrase[0].upper()}{phrase[1:]} {what} for {_plural(len(state.picked), 'repo')}."
+
+
+def _shows_calls(state: WorkspacePlanState) -> bool:
+ plan = state.plan
+ return plan.run_mode != "fast" and (plan.chosen is not None or plan.offer.price is not None)
+
+
+def _status(repo: Any, primary: bool) -> Text:
+ """``new`` / ``indexed``, with submodule and primary said in words."""
+ status = Text("indexed", style=OK) if repo.has_repowise else Text("new", style="dim")
+ if repo.is_submodule:
+ status.append(" (submodule)", style="dim")
+ if primary:
+ status.append(" · primary", style="bold")
+ return status
+
+
+def _row(state: WorkspacePlanState, idx: int, calls: bool) -> list[Any]:
+ """One repo's cells; the model-calls cell only when that column is shown."""
+ row = state.repos[idx]
+ picked = idx in state.selected
+ cells: list[Any] = [
+ Text("[x]" if picked else "[ ]"),
+ str(idx + 1),
+ Text(row.repo.name),
+ Text(display_path(row.repo, state.root)),
+ f"{row.scan.total_files:,}",
+ _status(row.repo, picked and row.repo.alias == state.primary),
+ ]
+ if calls:
+ n = model_calls_for(RunShape(row.scan, state.onboarding)) if picked else 0
+ cells.append(f"about {n:,}" if picked else "")
+ return cells
+
+
+def repo_table(state: WorkspacePlanState, limit: int | None = ROWS_SHOWN) -> Table:
+ """The repo list: pick mark, number, name, path, files, status."""
+ table = Table(box=None, padding=(0, 1), pad_edge=False, show_header=True, header_style="dim")
+ table.add_column("", no_wrap=True)
+ table.add_column("#", style=BRAND_STYLE, justify="right", no_wrap=True)
+ table.add_column("Repository", style="bold", max_width=24, overflow="ellipsis", no_wrap=True)
+ table.add_column("Path", style="dim", max_width=30, overflow="ellipsis", no_wrap=True)
+ table.add_column("Files", justify="right", no_wrap=True)
+ table.add_column("Status", no_wrap=True)
+ calls = _shows_calls(state)
+ if calls:
+ table.add_column("Model calls", justify="right", no_wrap=True)
+ count = len(state.repos) if limit is None else min(limit, len(state.repos))
+ for idx in range(count):
+ table.add_row(*_row(state, idx, calls))
+ return table
+
+
+def _hidden_line(state: WorkspacePlanState) -> str | None:
+ hidden = len(state.repos) - ROWS_SHOWN
+ if hidden <= 0:
+ return None
+ return (
+ f"[dim]{_plural(hidden, 'more repo')} not shown; "
+ f"{len(state.selected):,} of {len(state.repos):,} selected in all. "
+ "r lists every repo.[/dim]"
+ )
+
+
+def render_workspace_plan(console: Console, state: WorkspacePlanState) -> None:
+ """Print the workspace plan screen for *state*."""
+ files = sum(r.scan.total_files for r in state.picked)
+ console.print(
+ f" [bold]{escape(state.root.name or str(state.root))}[/bold] · "
+ f"{_plural(len(state.repos), 'repo')} found · {len(state.selected):,} selected "
+ f"({_plural(files, 'file')})",
+ highlight=False,
+ )
+ console.print(f" [dim]{escape(str(state.root))}[/dim]", highlight=False)
+ console.print(f" {_eta_line(state)}", highlight=False)
+ console.print()
+ console.print(Padding(repo_table(state), (0, 0, 0, 2)), highlight=False)
+ hidden = _hidden_line(state)
+ if hidden:
+ console.print(f" {hidden}", highlight=False)
+ render_plan_body(
+ console,
+ state.plan,
+ extra_keys=(REPOS_KEY,),
+ edit_preview=WORKSPACE_EDIT_PREVIEW,
+ )
+
+
+def _ask_selection(console: Console, ask: Callable[[], str], count: int) -> list[int] | None:
+ """Zero-based indices typed in the selection grammar; None when Enter keeps it."""
+ while True:
+ raw = ask().strip().lower()
+ if not raw:
+ return None
+ picked = list(range(count)) if raw == "all" else parse_selection(raw, count)
+ if picked:
+ return sorted(picked)
+ if raw == "none":
+ console.print(f" [{WARN}]Choose at least one repo, or press q on the plan to quit.[/]")
+ else:
+ console.print(f" [{WARN}]Invalid selection. Use numbers (1,3), ranges (2-5) or all.[/]")
+
+
+def choose_repos(
+ console: Console, state: WorkspacePlanState, ask: Callable[[], str] | None = None
+) -> None:
+ """``r``: every repo listed, then which to index and which is the primary.
+
+ Enter keeps the current pick. EOFError propagates, as on the key read.
+ """
+ if ask is None:
+
+ def ask() -> str:
+ return Prompt.ask(" Repos to index", default="", show_default=False, console=console)
+
+ console.print()
+ console.print(Padding(repo_table(state, limit=None), (0, 0, 0, 2)), highlight=False)
+ console.print(
+ " [dim]Numbers (1,3), ranges (2-5) or all. Enter keeps the current choice.[/dim]"
+ )
+ state.selected = _ask_selection(console, ask, len(state.repos)) or state.selected
+ repos = [r.repo for r in state.picked]
+ state.primary = (
+ interactive_primary_select(console, repos, current=state.primary)
+ if len(repos) > 1
+ else repos[0].alias
+ )
diff --git a/packages/cli/src/repowise/cli/ui/workspace_selection.py b/packages/cli/src/repowise/cli/ui/workspace_selection.py
index c6794339d..78eb1ae81 100644
--- a/packages/cli/src/repowise/cli/ui/workspace_selection.py
+++ b/packages/cli/src/repowise/cli/ui/workspace_selection.py
@@ -11,7 +11,7 @@ from rich.table import Table
from repowise.cli.ui.brand import BRAND_STYLE, OK, WARN
-def _display_path(repo: Any, root: Any) -> str:
+def display_path(repo: Any, root: Any) -> str:
"""Where this repo sits, relative to the workspace root.
``repo.path.name`` is the leaf directory, which for almost every repo is
@@ -57,7 +57,7 @@ def interactive_repo_select(
status = f"[{OK}]indexed[/]" if repo.has_repowise else "[dim]new[/dim]"
if repo.is_submodule:
status += " [dim](submodule)[/dim]"
- table.add_row(f"[{idx}]", repo.name, _display_path(repo, root), status)
+ table.add_row(f"[{idx}]", repo.name, display_path(repo, root), status)
console.print()
console.print(table)
@@ -151,18 +151,18 @@ def match_repo_names(repos: list[Any], names: list[str], root: Any = None) -> li
hits = [
r
for r in repos
- if name in (r.alias.casefold(), r.name.casefold(), _display_path(r, root).casefold())
+ if name in (r.alias.casefold(), r.name.casefold(), display_path(r, root).casefold())
]
if not hits:
unknown.append(raw)
elif len(hits) > 1:
- paths = ", ".join(_display_path(r, root) for r in hits)
+ paths = ", ".join(display_path(r, root) for r in hits)
raise ValueError(f"'{raw}' matches {len(hits)} repos ({paths}). Name one by its path.")
elif hits[0].alias not in seen:
seen.add(hits[0].alias)
picked.append(hits[0])
if unknown:
- available = ", ".join(_display_path(r, root) for r in repos)
+ available = ", ".join(display_path(r, root) for r in repos)
raise ValueError(f"Unknown repo: {', '.join(unknown)}. Available: {available}.")
return picked
@@ -170,10 +170,12 @@ def match_repo_names(repos: list[Any], names: list[str], root: Any = None) -> li
def interactive_primary_select(
console: Console,
repos: list[Any],
+ current: str | None = None,
) -> str:
"""Ask which repo is the primary/default. Returns the alias.
- *repos* is the list of selected :class:`DiscoveredRepo` objects.
+ *repos* is the list of selected :class:`DiscoveredRepo` objects;
+ *current* is the alias Enter keeps, when it is among them.
"""
if len(repos) == 1:
return repos[0].alias
@@ -190,10 +192,12 @@ def interactive_primary_select(
console.print()
choices = [str(i) for i in range(1, len(repos) + 1)]
+ aliases = [repo.alias for repo in repos]
+ default = aliases.index(current) + 1 if current in aliases else 1
chosen = Prompt.ask(
" Which is your primary repo?",
choices=choices,
- default="1",
+ default=str(default),
console=console,
)
return repos[int(chosen) - 1].alias
diff --git a/tests/unit/cli/test_init_plan_screen.py b/tests/unit/cli/test_init_plan_screen.py
index 70cd2f2a8..7149658e6 100644
--- a/tests/unit/cli/test_init_plan_screen.py
+++ b/tests/unit/cli/test_init_plan_screen.py
@@ -213,7 +213,7 @@ def plan(monkeypatch: Any):
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(_plan, "outside_lines", lambda _path: _OUTSIDE)
monkeypatch.setattr(
"repowise.cli.editor_setup.is_editor_setup_disabled", lambda _flag=False: False
)
diff --git a/tests/unit/cli/test_init_workspace_plan_screen.py b/tests/unit/cli/test_init_workspace_plan_screen.py
new file mode 100644
index 000000000..5107627b2
--- /dev/null
+++ b/tests/unit/cli/test_init_workspace_plan_screen.py
@@ -0,0 +1,293 @@
+"""The workspace plan screen: the repo list, choosing repos and the primary, EOF."""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import click
+import pytest
+from rich.console import Console
+
+from repowise.cli.ui import workspace_selection
+from repowise.cli.ui.plan_screen import (
+ EDIT,
+ MODEL,
+ QUIT,
+ REPOS,
+ START,
+ PlanState,
+ build_offer,
+ read_plan_key,
+)
+from repowise.cli.ui.plan_screen.workspace import (
+ ROWS_SHOWN,
+ WorkspacePlanState,
+ WorkspaceRepo,
+ choose_repos,
+ render_workspace_plan,
+)
+from repowise.cli.ui.repo_scanner import RepoScanInfo
+
+_ROOT = Path("/work/platform")
+
+
+def _repo(i: int) -> WorkspaceRepo:
+ name = f"service-{i}"
+ return WorkspaceRepo(
+ SimpleNamespace(
+ name=name,
+ alias=name,
+ path=_ROOT / "services" / name,
+ has_repowise=i == 2,
+ is_submodule=False,
+ ),
+ RepoScanInfo(total_files=50 * i, language_counts={"Python": 30}, total_commits=100),
+ )
+
+
+def _state(n: int, **plan: Any) -> WorkspacePlanState:
+ repos = [_repo(i) for i in range(1, n + 1)]
+ return WorkspacePlanState(
+ root=_ROOT,
+ repos=repos,
+ selected=list(range(n)),
+ primary="service-1",
+ plan=PlanState(repo_name="service-1", scan=repos[0].scan, **plan),
+ )
+
+
+def _lines(state: WorkspacePlanState) -> list[str]:
+ console = Console(record=True, width=100, color_system=None)
+ render_workspace_plan(console, state)
+ return console.export_text().splitlines()
+
+
+def _flat(state: WorkspacePlanState) -> str:
+ return " ".join(" ".join(_lines(state)).split())
+
+
+def _answers() -> Any:
+ from repowise.cli.commands.init_cmd._workspace_plan import WorkspaceAnswers
+
+ return WorkspaceAnswers(
+ index_only=False, provider_name=None, model=None, reasoning=None,
+ commit_limit=None, follow_renames=False, skip_tests=False, skip_infra=False,
+ concurrency=10, exclude_patterns=[], test_run=False, onboarding=True,
+ wiki_style="comprehensive", language=None,
+ )
+
+
+def _keys(*answers: str):
+ it = iter(answers)
+ return lambda: next(it)
+
+
+# -- render -------------------------------------------------------------------
+
+
+def test_three_repos_show_the_list_the_plan_and_the_repos_key() -> None:
+ state = _state(3)
+ out = _flat(state)
+ assert "platform · 3 repos found · 3 selected (300 files)" in out
+ assert "to index and build the documentation for 3 repos" in out
+ assert "[x] 1 service-1 services/service-1 50 new · primary" in out
+ assert "[x] 2 service-2 services/service-2 100 indexed" in out
+ # The same plan rows as one repo.
+ for row in ("Index", "Decisions", "Documentation", "Built from code", "Search", "Connect"):
+ assert row in out
+ assert "Keep in sync" in out
+ assert "r choose repos" in out and "Enter start" in out and "q quit" in out
+ assert "\N{EM DASH}" not in out
+ assert all(len(line) <= 100 for line in _lines(state))
+
+
+def test_twenty_five_repos_list_the_first_rows_and_count_the_rest() -> None:
+ state = _state(25)
+ state.selected = [0, 2, 24]
+ out = _flat(state)
+ assert f"service-{ROWS_SHOWN}" in out
+ assert f"service-{ROWS_SHOWN + 1} " not in out
+ assert "13 more repos not shown; 3 of 25 selected in all. r lists every repo." in out
+ assert "[ ] 2 service-2" in out
+ assert "25 repos found · 3 selected" in out
+ assert all(len(line) <= 100 for line in _lines(state))
+
+
+def test_the_model_line_prices_the_selected_repos_together() -> None:
+ one = _state(3)
+ one.selected = [0]
+ three = _state(3)
+ one.plan = replace(one.plan, offer=build_offer({"openai": "K"}, (), one.shape()))
+ three.plan = replace(three.plan, offer=build_offer({"openai": "K"}, (), three.shape()))
+ assert one.plan.offer.price and three.plan.offer.price
+ assert one.plan.offer.price.cost != three.plan.offer.price.cost
+ out = _flat(three)
+ assert "K found: openai /" in out and "model calls" in out
+ # Per repo, the compact column: a model's calls for each selected repo.
+ assert "Model calls" in out and "about " in out
+
+
+def test_a_long_path_is_cut_to_fit_100_columns() -> None:
+ state = _state(3)
+ state.repos[0].repo.path = _ROOT / ("deep-" * 30) / "service-1"
+ state.repos[0].repo.name = "a-repository-name-" * 4
+ assert all(len(line) <= 100 for line in _lines(state))
+
+
+# -- keys ---------------------------------------------------------------------
+
+
+def test_r_is_offered_on_the_workspace_screen_only() -> None:
+ console = Console(record=True, width=100)
+ plan = _state(3).plan
+ assert read_plan_key(console, plan, _keys("r"), extra={"r": REPOS}) == REPOS
+ assert read_plan_key(console, plan, _keys("r", ""), extra=None) == START
+ assert "Press Enter to start, or m, e or q." in console.export_text()
+ console = Console(record=True, width=100)
+ read_plan_key(console, plan, _keys("x", ""), extra={"r": REPOS})
+ assert "Press Enter to start, or m, e, r or q." in console.export_text()
+
+
+def test_choose_repos_takes_numbers_and_ranges_then_the_primary(monkeypatch: Any) -> None:
+ monkeypatch.setattr(workspace_selection.Prompt, "ask", lambda *a, **k: "2")
+ state = _state(5)
+ choose_repos(Console(width=100), state, _keys("1,3-4"))
+ assert state.selected == [0, 2, 3]
+ assert state.primary == "service-3"
+
+
+def test_choose_repos_keeps_the_primary_when_it_stays_picked(monkeypatch: Any) -> None:
+ defaults: list[str] = []
+
+ def ask(*_a: Any, **kwargs: Any) -> str:
+ defaults.append(kwargs["default"])
+ return kwargs["default"]
+
+ monkeypatch.setattr(workspace_selection.Prompt, "ask", ask)
+ state = _state(4)
+ state.primary = "service-3"
+ choose_repos(Console(width=100), state, _keys("2-3"))
+ assert state.selected == [1, 2]
+ assert defaults == ["2"]
+ assert state.primary == "service-3"
+
+
+def test_choose_repos_rejects_none_and_nonsense_and_enter_keeps(monkeypatch: Any) -> None:
+ console = Console(record=True, width=100)
+ state = _state(3)
+ choose_repos(console, state, _keys("none", "9", "x", "3"))
+ out = console.export_text()
+ assert "Choose at least one repo" in out
+ assert "Invalid selection" in out
+ assert state.selected == [2] and state.primary == "service-3"
+ choose_repos(console, state, _keys(""))
+ assert state.selected == [2]
+
+
+# -- the screen loop ----------------------------------------------------------
+
+
+def screen(monkeypatch: Any):
+ from repowise.cli.commands.init_cmd import _workspace_plan as module
+ from repowise.cli.ui import provider_selection
+
+ monkeypatch.setattr(module, "quick_repo_scan", lambda p: RepoScanInfo(total_files=50))
+ monkeypatch.setattr(module, "agent_providers_set_up", lambda _r: ())
+ monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda _r: {})
+ monkeypatch.setattr(module, "outside_lines", lambda _p: ())
+ monkeypatch.setattr("repowise.cli.editor_setup.planned_agents", lambda *_a: ("Claude Code",))
+ monkeypatch.setattr(
+ "repowise.cli.editor_setup.is_editor_setup_disabled", lambda _flag=False: False
+ )
+ scan = SimpleNamespace(root=_ROOT, repos=[_repo(i).repo for i in (1, 2, 3)])
+
+ def drive(*keys: str, hook: bool | None = None) -> Any:
+ it = iter(keys)
+ monkeypatch.setattr(module, "read_plan_key", lambda *_a, **_k: next(it))
+ return module.run_workspace_plan_screen(
+ scan, _answers(), editor_options=None, editor_setup=True, save_key=False, hook=hook
+ )
+
+ return SimpleNamespace(module=module, drive=drive)
+
+
+def test_enter_runs_every_repo_built_from_code(screen: Any) -> None:
+ plan = screen.drive(START)
+ assert [r.alias for r in plan.selected] == ["service-1", "service-2", "service-3"]
+ assert plan.primary_alias == "service-1"
+ assert plan.answers.index_only is True
+ assert plan.answers.provider_name is None
+ assert plan.sync is True
+
+
+def test_r_then_enter_runs_the_chosen_repos(screen: Any, monkeypatch: Any) -> None:
+ # Rich's prompt reads both: the repos, then the primary.
+ typed = iter(["1,3", "2"])
+ monkeypatch.setattr(workspace_selection.Prompt, "ask", lambda *a, **k: next(typed))
+ plan = screen.drive(REPOS, START)
+ assert [r.alias for r in plan.selected] == ["service-1", "service-3"]
+ assert plan.primary_alias == "service-3"
+
+
+def test_m_picks_a_model_for_every_repo(screen: Any, monkeypatch: Any) -> None:
+ from repowise.cli.ui.provider_selection import ProviderSelection
+
+ seen: dict[str, Any] = {}
+
+ def picker(*_a: Any, **kwargs: Any) -> Any:
+ seen.update(kwargs)
+ return ProviderSelection("openai", "gpt-test", "auto")
+
+ monkeypatch.setattr(screen.module, "interactive_provider_config_select", picker)
+ plan = screen.drive(MODEL, START)
+ assert seen["subscription"].model_calls > 0
+ assert seen["repo_path"] == _ROOT / "services" / "service-1"
+ assert plan.answers.index_only is False
+ assert (plan.answers.provider_name, plan.answers.model) == ("openai", "gpt-test")
+
+
+def test_q_quits_without_indexing(screen: Any) -> None:
+ with pytest.raises(click.exceptions.Exit):
+ screen.drive(QUIT)
+
+
+def test_eof_falls_back_to_the_defaults(screen: Any, monkeypatch: Any) -> None:
+ def eof(*_a: Any, **_k: Any) -> str:
+ raise EOFError
+
+ monkeypatch.setattr(screen.module, "read_plan_key", eof)
+ scan = SimpleNamespace(root=_ROOT, repos=[_repo(1).repo, _repo(2).repo])
+ plan = screen.module.run_workspace_plan_screen(
+ scan, _answers(), editor_options=None, editor_setup=True, save_key=False, hook=None
+ )
+ assert plan is None
+
+
+def test_eof_inside_the_repo_question_falls_back_too(screen: Any, monkeypatch: Any) -> None:
+ def eof(*_a: Any, **_k: Any) -> str:
+ raise EOFError
+
+ monkeypatch.setattr(workspace_selection.Prompt, "ask", eof)
+ assert screen.drive(REPOS) is None
+
+
+
+def test_e_does_not_ask_file_pages_a_workspace_would_ignore(screen: Any, monkeypatch: Any) -> None:
+ from repowise.cli.ui import mode_selection
+
+ def no_file_pages(*_a: Any, **_k: Any) -> Any:
+ raise AssertionError("file pages asked on a workspace")
+
+ monkeypatch.setattr(mode_selection, "prompt_file_page_volume", no_file_pages)
+ monkeypatch.setattr(mode_selection.click, "confirm", lambda *_a, **k: k.get("default", False))
+ monkeypatch.setattr(mode_selection.click, "prompt", lambda *_a, **k: k.get("default"))
+ monkeypatch.setattr(screen.module.click, "confirm", lambda *_a, **k: False)
+ monkeypatch.setattr(mode_selection, "_prompt_exclude", lambda *_a, **_k: [])
+ monkeypatch.setattr(mode_selection, "_prompt_index_only_search", lambda *_a, **_k: None)
+ plan = screen.drive(EDIT, START)
+ assert plan.sync is False
+ assert plan.answers.index_only is True
diff --git a/tests/unit/cli/test_ui_package.py b/tests/unit/cli/test_ui_package.py
index 39b004145..47bc3f95e 100644
--- a/tests/unit/cli/test_ui_package.py
+++ b/tests/unit/cli/test_ui_package.py
@@ -28,7 +28,6 @@ def test_facade_reexports_public_surface() -> None:
"load_dotenv",
"interactive_provider_select",
"interactive_advanced_config",
- "interactive_mode_select",
"interactive_repo_select",
"interactive_primary_select",
"should_offer_fast_mode",
diff --git a/tests/unit/cli/test_workspace_init_config.py b/tests/unit/cli/test_workspace_init_config.py
index f3091fe1f..ff09dc24e 100644
--- a/tests/unit/cli/test_workspace_init_config.py
+++ b/tests/unit/cli/test_workspace_init_config.py
@@ -14,7 +14,6 @@ import yaml
from rich.console import Console
from repowise.cli.commands.init_cmd import _workspace_repos
-from repowise.cli.commands.init_cmd import workspace as ws_mod
from repowise.cli.commands.init_cmd._workspace_config import (
WorkspacePick,
build_workspace_config,
@@ -140,23 +139,6 @@ def test_picker_number_column_fits_three_digits() -> None:
assert "[226]" in text and "…" not in text
-def test_mode_question_pluralizes_repo_count() -> None:
- titles: list[str] = []
-
- def _mode(_console: object, *, title: str) -> str:
- titles.append(title)
- return "index_only"
-
- answers = SimpleNamespace(index_only=False)
- with patch.object(ws_mod, "interactive_mode_select", side_effect=_mode):
- ws_mod._ask_workspace_mode(answers, [object()], None, None, save_key=False)
- ws_mod._ask_workspace_mode(answers, [object(), object()], None, None, save_key=False)
- assert titles == [
- "How much should repowise write for 1 repo?",
- "How much should repowise write for 2 repos?",
- ]
-
-
def test_primary_moves_when_its_alias_was_taken(tmp_path: Path) -> None:
(tmp_path / "old").mkdir()
(tmp_path / "b").mkdir()