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(cli): rank generate coverage and add an interactive chooser (#979)

Raghav Chamadiya3a46ecfb73b5
diff --git a/README.md b/README.md
index 9f5082522..b19d15988 100644
--- a/README.md
+++ b/README.md
@@ -355,11 +355,15 @@ or the whole thing at a time, each behind a cost estimate:
```bash
export ANTHROPIC_API_KEY="sk-ant-..." # or OPENAI_API_KEY / GEMINI_API_KEY
-repowise generate --dry-run # preview the plan and the cost
-repowise generate # write every unwritten page
+repowise generate # interactive chooser: pick a coverage, see the cost
+repowise generate --coverage 20 # or write the most important 20%, leave the rest as templates
repowise generate --path src/api # or just one area first
```
+Bare `repowise generate` opens a chooser (wiki state, a coverage menu with cost
+per tier, then the confirm), so a big repo is never one keystroke from writing
+every page.
+
Or write the whole wiki as part of the first index with `repowise init --provider
gemini|anthropic|openai`.
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 018327938..05c8f0cc2 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -193,25 +193,46 @@ repowise update --full --provider anthropic # upgrade a fast index to full
Write wiki pages with a model, on demand. This is the upgrade path for an
`--index-only` repo: it turns the template (structure-rendered) pages into
-model-written prose, one page, one directory, or the whole wiki at a time,
-each behind a cost estimate. It also fills in the template tail a budgeted full
-`init` leaves behind, and rewrites already-written pages.
+model-written prose, one page, one directory, a ranked slice, or the whole wiki
+at a time, each behind a cost estimate. It also fills in the template tail a
+budgeted full `init` leaves behind, and rewrites already-written pages.
Like `update --full` and `restyle`, it reuses the persisted index: the graph and
git metadata are rehydrated from SQL, only the per-file parse and the LLM
generation for the pages you selected run. A provider is required; a missing one
is an actionable error naming the key-setup path.
-**Selection** (the default is `--unwritten`; combine freely, the result is their
-union):
+**Interactive chooser.** Run `repowise generate` with no selection flag on a
+terminal and it opens a chooser instead of writing everything: it prints the
+wiki's state (written / unwritten / stale), then the same coverage menu `init`
+uses (page counts and cost per tier, 20% recommended), asks about cascade only
+when the choice would change which pages get written, and ends at the normal cost
+confirm. A large repo is never one keystroke away from writing every page. Piped,
+`--yes`, or flagged runs stay non-interactive (the old `--unwritten` default).
+
+**Selection.** Two philosophies, and they do not mix. *Explicit* names exactly
+which pages (`--unwritten` / `--all` / `--stale` / `--path` / `--page`, combined
+as a union). *Ranked* writes the most important pages by the same importance
+ranking `init` uses (`--coverage` / `--top`).
| Flag | Selects |
|------|---------|
-| `--unwritten` | Every template (unwritten) page. The default. This is "finish writing the wiki". |
+| `--unwritten` | Every template (unwritten) page. The default for a non-interactive run. This is "finish writing the wiki". |
| `--all` | Every page, template or already written. A full rewrite. |
| `--stale` | Every page marked stale (its code changed since it was written). |
| `--path <glob>` | Every page under a path prefix or glob, e.g. `--path src/api` (repeatable). |
| `--page <id>` | One explicit page id, e.g. `--page file_page:src/app.py` (repeatable). |
+| `--coverage <pct>` | The most important unwritten pages up to this coverage, ranked the way `init` ranks coverage. `--coverage 20` writes the top 20% and leaves the rest as templates. Accepts a percent from 1 to 100 (`20`), or a fraction below 1 (`0.2`); use `100` for everything. |
+| `--top <n>` | About the `n` most important unwritten pages (a target, not an exact count: per-type floors and the always-included repo-wide/onboarding pages nudge it, and the real number shows before the gate). |
+
+`--coverage` / `--top` rank the file / module / cycle / symbol content pages; the
+repo-wide and structural pages (overview, architecture, layer, onboarding) are
+always included when unwritten, exactly as `init` emits them at every coverage.
+They cannot be combined with an explicit selector or with each other, and they
+default to `--cascade none` (the ranked set is already a coherent slice). On a
+small repo (20 files or fewer) the coverage budget floors to the whole repo, so
+any tier writes essentially every unwritten page, same as `init`; the plan report
+shows the real count before the gate.
**Cascade.** Regenerating a file page makes the pages that summarize it drift:
its module, cycle (SCC) and layer pages, and the repo overview, architecture and
@@ -229,19 +250,23 @@ The cost estimate includes the cascade fallout, so it does not under-quote.
| Flag | Description |
|------|-------------|
-| `--unwritten` / `--all` / `--stale` | Selection (see above). Default: `--unwritten`. |
+| `--unwritten` / `--all` / `--stale` | Explicit selection (see above). Default for a non-interactive run: `--unwritten`. |
| `--path <glob>` | Restrict to a path prefix or glob (repeatable). |
| `--page <id>` | An explicit page id (repeatable). |
-| `--cascade none\|dependents\|full` | Dependent-page policy (default: `dependents`). |
+| `--coverage <pct>` | Ranked: the most important unwritten pages up to this coverage. |
+| `--top <n>` | Ranked: about the `n` most important unwritten pages. |
+| `--cascade none\|dependents\|full` | Dependent-page policy. Default: `dependents` for an explicit selection, `none` for `--coverage`/`--top`. |
| `--provider` / `--model` / `--reasoning` | LLM overrides for this run. |
| `--concurrency` | Max concurrent LLM calls (default: 12). |
| `--dry-run` | Print the plan and the cost estimate; generate nothing. |
-| `--yes` / `-y` | Skip the cost confirmation. |
+| `--yes` / `-y` | Skip the cost confirmation (and the interactive chooser). |
| `--verbose` / `-v` | Show pipeline debug logs. |
```bash
-repowise generate --dry-run # what would it write, and cost?
-repowise generate # write every unwritten page
+repowise generate # interactive chooser (coverage menu)
+repowise generate --coverage 20 # write the most important 20% of templates
+repowise generate --coverage 20 --dry-run # what would that write, and cost?
+repowise generate --unwritten # write every unwritten page
repowise generate --all # rewrite the whole wiki
repowise generate --path src/api # just the pages under src/api
repowise generate --page file_page:src/app.py --cascade none # one page, nothing else
diff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.md
index cbda02243..f500035db 100644
--- a/docs/start/QUICKSTART.md
+++ b/docs/start/QUICKSTART.md
@@ -151,16 +151,18 @@ Set a key, preview the cost, then write:
```bash
export ANTHROPIC_API_KEY="sk-ant-..." # or OPENAI_API_KEY / GEMINI_API_KEY
-repowise generate --dry-run # what would it write, and what does it cost?
-repowise generate # write every unwritten page
+repowise generate # interactive: pick a coverage, see the cost, confirm
```
-On Windows PowerShell: `$env:ANTHROPIC_API_KEY = "sk-ant-..."`
+Bare `generate` shows the wiki's state and a coverage menu (page counts and cost
+per tier, 20% recommended), so you choose how much to write rather than getting
+the whole repo by default. On Windows PowerShell: `$env:ANTHROPIC_API_KEY = "sk-ant-..."`
-You do not have to write the whole wiki at once. Start with the part you care
-about and grow from there, each run behind its own cost estimate:
+You do not have to write the whole wiki at once. Pick a ranked slice, an area, or
+a single page, each run behind its own cost estimate:
```bash
+repowise generate --coverage 20 # the most important 20%, ranked like init
repowise generate --path src/api # just one area
repowise generate --page file_page:src/app.py # or a single page
repowise generate --all # or rewrite everything
diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.md
index b1fef0ca7..fcaf709e9 100644
--- a/docs/start/USER_GUIDE.md
+++ b/docs/start/USER_GUIDE.md
@@ -93,11 +93,13 @@ You do not have to choose up front. Start index-only, then upgrade the wiki with
at a time, each behind a cost estimate:
```bash
-repowise generate --dry-run # what it would write, and what it costs
-repowise generate # write every unwritten page
+repowise generate # interactive chooser: wiki state, coverage menu, cost
+repowise generate --coverage 20 # or the most important 20%, ranked like init
repowise generate --path src/api # or just the part you care about
```
+Bare `generate` opens a chooser (a coverage menu with page counts and cost per
+tier) rather than writing everything, so a large repo never spends by accident.
`generate` reuses the persisted graph instead of re-parsing it, so the upgrade is
cheap. (`repowise update --full` still does the whole wiki in one shot if you
prefer.) Semantic search is separate: it needs an embedder, and `repowise
@@ -316,8 +318,8 @@ time, each behind a cost estimate:
```bash
export ANTHROPIC_API_KEY="sk-ant-..."
-repowise generate --dry-run # preview the plan and the cost
-repowise generate # write every unwritten page
+repowise generate # interactive chooser: pick a coverage, see the cost
+repowise generate --coverage 20 # or the most important 20%, ranked like init
repowise generate --path src/api # or just one area first
```
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/chooser.py b/packages/cli/src/repowise/cli/commands/generate_cmd/chooser.py
new file mode 100644
index 000000000..5c09814f6
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/chooser.py
@@ -0,0 +1,170 @@
+"""Interactive scope chooser for a bare ``repowise generate``.
+
+When a user runs ``generate`` with no selection flag on a terminal, we do not
+default to writing every unwritten page — on a 3,000-file index-only repo that
+is one Enter from a very large bill. Instead we show the wiki's current state,
+offer the same coverage menu ``repowise init`` uses (page counts + cost per
+tier, recommended default 20%), then ask about cascade only when it would change
+which pages get written, and finally the normal cost gate.
+
+The coverage table and its prompt are the exact ones ``init`` renders
+(:mod:`repowise.cli.coverage_select`); the per-tier counts and costs come from
+the shared :func:`compute_coverage_options`. So init and generate present one
+chooser, not two look-alikes.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from rich.console import Console
+from rich.prompt import Prompt
+
+from repowise.cli.coverage_select import interactive_coverage_select
+from repowise.core.cost_estimator import compute_coverage_options
+from repowise.core.generation.cascade import CascadeMode, PageDependencies, expand_cascade
+from repowise.core.generation.page_selection import PageRecord
+
+from .scope import build_ranked_seed
+
+# Coverage tiers offered by the generate chooser. Wider at the top than init's
+# ladder because a generate run is an explicit upgrade step, and it ends in an
+# ``All`` (100%) row so "write everything unwritten" is a deliberate pick, never
+# the Enter-through default. 20% stays the recommended default.
+GENERATE_COVERAGE_PCTS: tuple[float, ...] = (0.10, 0.20, 0.30, 0.50, 1.00)
+RECOMMENDED_PCT: float = 0.20
+
+_CASCADE_MODES: tuple[CascadeMode, ...] = ("none", "dependents", "full")
+
+
+@dataclass(frozen=True)
+class InteractiveChoice:
+ """The scope a bare ``generate`` resolved to through the chooser."""
+
+ ranked_seed: set[str]
+ cascade_mode: CascadeMode
+
+
+def print_wiki_state(console: Console, records: list[PageRecord]) -> None:
+ """Print the written / unwritten / stale breakdown of the current wiki.
+
+ ``written`` + ``unwritten`` partition the wiki and sum to the total; ``stale``
+ is a cross-cutting count (a page of either kind whose code moved on), shown
+ after a separator so it does not read as a third slice of the total.
+ """
+ total = len(records)
+ template = sum(1 for r in records if r.is_template)
+ written = total - template
+ stale = sum(1 for r in records if r.is_stale)
+ line = (
+ f"[bold]Wiki:[/bold] {total} pages — "
+ f"[cyan]{written}[/cyan] written, [yellow]{template}[/yellow] unwritten"
+ )
+ if stale:
+ line += f" · [red]{stale}[/red] stale (code changed since written)"
+ console.print(line + ".")
+
+
+def choose_cascade(
+ console: Console,
+ seed_ids: set[str],
+ deps: PageDependencies,
+ *,
+ default: CascadeMode = "none",
+) -> CascadeMode:
+ """Ask how to treat the pages that summarize the chosen set.
+
+ Returns *default* without prompting when every cascade mode writes the same
+ pages (the "only when it changes the outcome" rule) — which is the common
+ case for a coverage pick, whose set already includes the module and
+ repo-wide pages. When the modes diverge, the extra page counts are shown so
+ the choice is concrete.
+ """
+ generated = {m: expand_cascade(seed_ids, m, deps).generate_ids for m in _CASCADE_MODES}
+ if len({frozenset(ids) for ids in generated.values()}) == 1:
+ return default
+
+ base = len(generated["none"])
+ console.print("\n[bold]Cascade[/bold] — the pages that summarize the ones you are writing:")
+ labels = {
+ "none": "write exactly these pages; mark the rest stale",
+ "dependents": "also rewrite the module / cycle / layer pages that contain them",
+ "full": "also rewrite the repo-wide overview, architecture and onboarding",
+ }
+ choices: list[str] = []
+ default_choice = "1"
+ for idx, mode in enumerate(_CASCADE_MODES, start=1):
+ extra = len(generated[mode]) - base
+ suffix = f" [dim](+{extra} pages)[/dim]" if extra > 0 else ""
+ rec = " [dim](default)[/dim]" if mode == default else ""
+ console.print(f" [{idx}] [bold]{mode}[/bold] — {labels[mode]}{suffix}{rec}")
+ choices.append(str(idx))
+ if mode == default:
+ default_choice = str(idx)
+
+ picked = Prompt.ask(" Cascade", choices=choices, default=default_choice, console=console)
+ return _CASCADE_MODES[int(picked) - 1]
+
+
+def run_interactive_chooser(
+ console: Console,
+ *,
+ records: list[PageRecord],
+ parsed_files: list,
+ graph_builder: object,
+ config: object,
+ kg_ctx: object,
+ provider: object,
+ repo_path: object,
+ repo_name: str,
+ deps: PageDependencies,
+) -> InteractiveChoice | None:
+ """Drive the full bare-``generate`` chooser and return the resolved scope.
+
+ Returns ``None`` when there is nothing to write (no unwritten pages, or the
+ user's coverage pick lands entirely on already-written pages).
+ """
+ print_wiki_state(console, records)
+ if not any(r.is_template for r in records):
+ console.print("[green]Every page is already written.[/green] Nothing to upgrade.")
+ return None
+
+ options = compute_coverage_options(
+ parsed_files=parsed_files,
+ graph_builder=graph_builder,
+ base_config=config,
+ provider_name=provider.provider_name, # type: ignore[attr-defined]
+ model_name=provider.model_name, # type: ignore[attr-defined]
+ repo_path=repo_path,
+ percentages=GENERATE_COVERAGE_PCTS,
+ recommended=RECOMMENDED_PCT,
+ )
+ # The menu sizes each tier for a full wiki (it is blind to what is already
+ # written). When some pages are written, the run skips those, so the real
+ # count and cost (shown in the plan + at the confirm) are lower. Say so, so
+ # the table's numbers do not read as a contradiction of the final estimate.
+ if any(not r.is_template for r in records):
+ console.print(
+ " [dim]Counts below size each tier for a full wiki; already-written "
+ "pages are skipped, so the final estimate (shown before you confirm) "
+ "is lower.[/dim]"
+ )
+ chosen = interactive_coverage_select(console, options, deterministic_tail=True)
+
+ ranked_seed = build_ranked_seed(
+ parsed_files=parsed_files,
+ graph_builder=graph_builder,
+ config=config,
+ kg_ctx=kg_ctx,
+ records=records,
+ repo_name=repo_name,
+ coverage_pct=chosen.pct,
+ )
+ if not ranked_seed:
+ console.print(
+ "[yellow]Everything in that coverage is already written.[/yellow] Nothing to generate."
+ )
+ return None
+
+ cascade_mode = choose_cascade(console, ranked_seed, deps)
+ return InteractiveChoice(ranked_seed=ranked_seed, cascade_mode=cascade_mode)
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
index fc24eafd7..60062310c 100644
--- a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
@@ -1,9 +1,12 @@
"""``repowise generate`` — write any subset of the wiki with a model.
The single, cost-gated entry point for turning template (unwritten) pages into
-LLM prose, or regenerating written ones. Selection is explicit (all / unwritten
-/ stale / path / page) and defaults to ``--unwritten``; the cascade mode decides
-what happens to the pages that summarize a regenerated file.
+LLM prose, or regenerating written ones. Selection comes in two shapes: explicit
+(all / unwritten / stale / path / page, unioned) and ranked by importance
+(coverage / top). A bare ``generate`` on a terminal opens an interactive chooser
+(wiki state + coverage menu) instead of writing everything; piped / ``--yes`` /
+flagged runs default to ``--unwritten``. The cascade mode decides what happens to
+the pages that summarize a regenerated file.
"""
from __future__ import annotations
@@ -60,6 +63,41 @@ def _build_intent(
return intent
+def _resolve_ranked_flags(
+ *, coverage: float | None, top_n: int | None, explicit: bool
+) -> float | None:
+ """Validate --coverage / --top and return the coverage fraction (or None).
+
+ ``--coverage`` accepts a percent from 1 to 100 (``20`` -> 0.20, ``100`` ->
+ everything) or a fraction below 1 (``0.2`` -> 0.20). The boundary is ``>= 1``
+ so ``--coverage 1`` reads as 1 percent (the smallest slice), never as 100
+ percent; use ``100`` or ``--all`` for everything. Ranked selection is its own
+ philosophy, so it may not be combined with an explicit selector or with the
+ other ranked flag. ``--top`` is handled downstream (it needs the file count),
+ so this only validates it here and returns None for the coverage fraction.
+ """
+ if coverage is not None and top_n is not None:
+ raise click.ClickException("Use either --coverage or --top, not both.")
+ if (coverage is not None or top_n is not None) and explicit:
+ raise click.ClickException(
+ "--coverage / --top rank pages by importance and cannot be combined with "
+ "--all / --unwritten / --stale / --path / --page."
+ )
+ if top_n is not None and top_n <= 0:
+ raise click.ClickException("--top must be a positive number of pages.")
+ if coverage is None:
+ return None
+ if coverage <= 0:
+ raise click.ClickException(
+ "--coverage must be positive: a percent from 1 to 100, or a fraction below 1."
+ )
+ # A value of 1 or more is a percent (1 -> 1%, 100 -> everything); below 1 it
+ # is a fraction (0.2 -> 20%). This keeps `--coverage 1` a tiny slice, not the
+ # whole wiki.
+ pct = coverage / 100 if coverage >= 1 else coverage
+ return min(pct, 1.0)
+
+
def _make_gate(dry_run: bool):
"""Return the ``gate_cost`` callback the engine invokes before generating.
@@ -131,11 +169,32 @@ def _make_gate(dry_run: bool):
multiple=True,
help="An explicit page id to generate (repeatable).",
)
+ "--coverage",
+ "coverage",
+ type=float,
+ default=None,
+ help=(
+ "Write the most important unwritten pages up to this coverage, ranked the "
+ "way `init` ranks coverage. A percent from 1 to 100 (--coverage 20) or a "
+ "fraction below 1 (0.2); use 100 for everything. Leaves the rest as templates."
+ ),
+)
+ "--top",
+ "top_n",
+ type=int,
+ default=None,
+ help="Write about the N most important unwritten pages (a target, not exact).",
+)
@click.option(
"--cascade",
type=click.Choice(["none", "dependents", "full"]),
- default="dependents",
- help="What to do with the module/overview pages that summarize a regenerated file.",
+ default=None,
+ help=(
+ "What to do with the module/overview pages that summarize a regenerated "
+ "file. Default: dependents for an explicit selection, none for --coverage/--top."
+ ),
)
@click.option("--provider", "provider_name", default=None, help="LLM provider name.")
@click.option("--model", default=None, help="Model identifier override.")
@@ -153,7 +212,9 @@ def generate_command(
stale: bool,
path_globs: tuple[str, ...],
page_ids: tuple[str, ...],
- cascade: str,
+ coverage: float | None,
+ top_n: int | None,
+ cascade: str | None,
provider_name: str | None,
model: str | None,
reasoning: str | None,
@@ -162,10 +223,17 @@ def generate_command(
yes: bool,
verbose: bool,
) -> None:
- """Write wiki pages with a model. Defaults to every unwritten page.
+ """Write wiki pages with a model. Bare `generate` opens an interactive chooser.
+
+ Two ways to select: explicit (--all / --unwritten / --stale / --path / --page)
+ or ranked by importance (--coverage / --top). With no flag on a terminal, a
+ chooser shows the wiki's state and a coverage menu, so a big repo is never one
+ keystroke from writing everything.
Examples:
- repowise generate # write every template page
+ repowise generate # interactive chooser (coverage menu)
+ repowise generate --coverage 20 # write the most important 20% of templates
+ repowise generate --unwritten # write every template page
repowise generate --all # rewrite the whole wiki
repowise generate --path src/api # just the pages under src/api
repowise generate --page file_page:src/app.py --cascade none
@@ -179,6 +247,22 @@ def generate_command(
raise click.ClickException(f"No index found at {repo_path}. Run `repowise init` first.")
cfg = load_config(repo_path)
+
+ explicit = bool(all_pages or unwritten or stale or path_globs or page_ids)
+ coverage_pct = _resolve_ranked_flags(coverage=coverage, top_n=top_n, explicit=explicit)
+ ranked = coverage_pct is not None or top_n is not None
+
+ # Bare `generate` on a terminal opens the chooser rather than defaulting to
+ # writing every unwritten page. Piped / `--yes` / flagged runs keep the old
+ # non-interactive behaviour.
+ interactive = not explicit and not ranked and not yes and sys.stdin.isatty()
+
+ # Cascade default depends on the selection kind: an explicit pick pulls in
+ # its container pages (dependents); a ranked coverage set is already a
+ # curated, coherent slice, so it defaults to none (the interactive chooser
+ # asks when it would change the outcome).
+ cascade_mode = cascade if cascade is not None else ("none" if ranked else "dependents")
+
intent = _build_intent(
all_pages=all_pages,
unwritten=unwritten,
@@ -219,12 +303,15 @@ def generate_command(
provider,
config,
intent=intent,
- cascade_mode=cascade, # type: ignore[arg-type]
+ cascade_mode=cascade_mode, # type: ignore[arg-type]
exclude_patterns=exclude_patterns,
embedder_name=embedder_name,
yes=yes,
dry_run=dry_run,
gate_cost=_make_gate(dry_run),
+ coverage_pct=coverage_pct,
+ top_n=top_n,
+ interactive=interactive,
)
)
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py b/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py
index 1e39088fc..34258df77 100644
--- a/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py
+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py
@@ -16,7 +16,13 @@ from repowise.cli.helpers import console
from repowise.core.generation.cascade import CascadeMode
from repowise.core.generation.page_selection import PageSelectionIntent
-from .scope import ScopePlan, build_dependencies, load_page_records, resolve_scope
+from .scope import (
+ ScopePlan,
+ build_dependencies,
+ build_ranked_seed,
+ load_page_records,
+ resolve_scope,
+)
@dataclass
@@ -30,6 +36,18 @@ class GenerateOutcome:
plan: ScopePlan
+def _coverage_from_top(top_n: int, n_files: int) -> float:
+ """Map ``--top N`` to the coverage fraction that budgets ~N pages.
+
+ ``compute_budget`` uses ``int(n_files * pct)`` for a large repo, so
+ ``pct = N / n_files`` yields a budget of about ``N``. Per-bucket floors and
+ the always-emitted repo-wide/onboarding pages nudge the actual count, which
+ is why the plan report (and the cost gate) show the real number before any
+ spend — ``--top`` is a target, not an exact count.
+ """
+ return min(1.0, max(0.0, top_n / max(1, n_files)))
+
+
async def run_scoped_generation(
repo_path: Path,
provider: Any,
@@ -42,6 +60,9 @@ async def run_scoped_generation(
yes: bool,
dry_run: bool,
gate_cost: Any,
+ coverage_pct: float | None = None,
+ top_n: int | None = None,
+ interactive: bool = False,
) -> GenerateOutcome | None:
"""Resolve the scope, gate on cost, generate, persist, and heal.
@@ -110,7 +131,55 @@ async def run_scoped_generation(
records=records,
repo_name=repo_name,
)
- plan = resolve_scope(records=records, intent=intent, cascade_mode=cascade_mode, deps=deps)
+ # Ranked (coverage/top) and interactive runs replace the intent seed
+ # with an importance-ranked page-id set; explicit runs leave it None.
+ ranked_seed: set[str] | None = None
+ if interactive:
+ from .chooser import run_interactive_chooser
+
+ choice = run_interactive_chooser(
+ console,
+ records=records,
+ parsed_files=parsed_files,
+ graph_builder=graph_builder,
+ config=config,
+ kg_ctx=kg_ctx,
+ provider=provider,
+ repo_path=repo_path,
+ repo_name=repo_name,
+ deps=deps,
+ )
+ if choice is None:
+ return None
+ ranked_seed = choice.ranked_seed
+ cascade_mode = choice.cascade_mode
+ elif coverage_pct is not None or top_n is not None:
+ pct = coverage_pct
+ if pct is None:
+ pct = _coverage_from_top(top_n or 0, len(parsed_files))
+ ranked_seed = build_ranked_seed(
+ parsed_files=parsed_files,
+ graph_builder=graph_builder,
+ config=config,
+ kg_ctx=kg_ctx,
+ records=records,
+ repo_name=repo_name,
+ coverage_pct=pct,
+ )
+ if not ranked_seed:
+ console.print(
+ "[yellow]Everything in that coverage is already written.[/yellow] "
+ "Nothing to generate."
+ )
+ return None
+
+ plan = resolve_scope(
+ records=records,
+ intent=intent,
+ cascade_mode=cascade_mode,
+ deps=deps,
+ ranked_seed=ranked_seed,
+ )
if plan.unknown_page_ids:
console.print(
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/scope.py b/packages/cli/src/repowise/cli/commands/generate_cmd/scope.py
index e5e283bb3..14c3ed984 100644
--- a/packages/cli/src/repowise/cli/commands/generate_cmd/scope.py
+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/scope.py
@@ -10,7 +10,7 @@ fallout, so the estimate does not under-quote).
from __future__ import annotations
import json
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Any
from repowise.core.cost_estimator.types import PageTypePlan
@@ -28,11 +28,17 @@ from repowise.core.generation.page_selection import (
PageSelectionIntent,
resolve_page_selection,
)
-from repowise.core.generation.selection import SelectionInputs, select_pages
+from repowise.core.generation.selection import Selection, SelectionInputs, select_pages
# Page types that describe the whole repository (as opposed to one file/module).
_REPO_WIDE_TYPES = frozenset({"repo_overview", "architecture_diagram", "onboarding"})
+# Structural pages the coverage budget does not rank: layer pages come from KG
+# membership and onboarding is curated, so init emits every one of them at every
+# coverage. A ranked run includes the unwritten ones rather than leaving holes in
+# the navigation. (repo_overview / architecture come from the Selection itself.)
+_STRUCTURAL_PAGE_TYPES = frozenset({"layer_page", "onboarding"})
+
@dataclass(frozen=True)
class ScopePlan:
@@ -89,21 +95,19 @@ def _layer_membership(kg_ctx: Any) -> dict[str, str]:
return out
-def build_dependencies(
+def _selection_inputs(
*,
parsed_files: list[Any],
graph_builder: Any,
config: Any,
kg_ctx: Any,
- records: list[PageRecord],
- repo_name: str,
-) -> PageDependencies:
- """Compute the structural file -> container-page map for cascade.
+ select_all: bool,
+) -> SelectionInputs:
+ """Bundle the inputs :func:`select_pages` needs from the rehydrated graph.
- Uses the same full-coverage selection the engine will use
- (``select_all=True``), so the module/SCC page ids it derives match the ones
- generation emits. Repo-wide ids are the overview + architecture pages
- (keyed by repo name) plus every persisted onboarding page.
+ Shared by the cascade-dependency selection (``select_all=True``) and the
+ ranked coverage selection (``select_all=False`` + a coverage-scoped config),
+ so both derive their page ids from the same graph metrics and KG modules.
"""
try:
community_info_map = graph_builder.community_info() or {}
@@ -114,17 +118,42 @@ def build_dependencies(
if kg_ctx and getattr(kg_ctx, "available", False):
kg_modules = kg_ctx.get_modules() or None
+ return SelectionInputs(
+ parsed_files=parsed_files,
+ pagerank=graph_builder.pagerank(),
+ betweenness=graph_builder.betweenness_centrality(),
+ community=graph_builder.community_detection(),
+ community_info=community_info_map,
+ sccs=list(graph_builder.strongly_connected_components()),
+ git_meta_map=None,
+ config=config,
+ kg_modules=kg_modules,
+ select_all=select_all,
+ )
+
+
+def build_dependencies(
+ *,
+ parsed_files: list[Any],
+ graph_builder: Any,
+ config: Any,
+ kg_ctx: Any,
+ records: list[PageRecord],
+ repo_name: str,
+) -> PageDependencies:
+ """Compute the structural file -> container-page map for cascade.
+
+ Uses the same full-coverage selection the engine will use
+ (``select_all=True``), so the module/SCC page ids it derives match the ones
+ generation emits. Repo-wide ids are the overview + architecture pages
+ (keyed by repo name) plus every persisted onboarding page.
+ """
selection = select_pages(
- SelectionInputs(
+ _selection_inputs(
parsed_files=parsed_files,
- pagerank=graph_builder.pagerank(),
- betweenness=graph_builder.betweenness_centrality(),
- community=graph_builder.community_detection(),
- community_info=community_info_map,
- sccs=list(graph_builder.strongly_connected_components()),
- git_meta_map=None,
+ graph_builder=graph_builder,
config=config,
- kg_modules=kg_modules,
+ kg_ctx=kg_ctx,
select_all=True,
)
)
@@ -143,6 +172,89 @@ def build_dependencies(
)
+def selection_page_ids(sel: Selection, repo_name: str) -> set[str]:
+ """Turn a budgeted :class:`Selection` into the page ids generation emits.
+
+ Mirrors the id assignment in the page generator's level builders exactly
+ (``levels.py``), so a ranked coverage pick names the same pages a full run
+ at that coverage would write. Repo-wide overview/architecture pages are
+ keyed by the repo name; onboarding is not budgeted here (the caller adds it).
+ """
+ ids: set[str] = set()
+ ids.update(compute_page_id("file_page", p) for p in sel.file_page_paths)
+ ids.update(compute_page_id("module_page", mg.key) for mg in sel.module_groups)
+ ids.update(compute_page_id("scc_page", scc_id) for scc_id, _ in sel.scc_groups)
+ ids.update(compute_page_id("api_contract", p) for p in sel.api_contract_paths)
+ ids.update(compute_page_id("infra_page", p) for p in sel.infra_paths)
+ ids.update(
+ compute_page_id("symbol_spotlight", f"{path}::{name}")
+ for path, name in sel.symbol_spotlights
+ )
+ if sel.emit_repo_overview:
+ ids.add(compute_page_id("repo_overview", repo_name))
+ if sel.emit_arch_diagram:
+ ids.add(compute_page_id("architecture_diagram", repo_name))
+ return ids
+
+
+def build_ranked_seed(
+ *,
+ parsed_files: list[Any],
+ graph_builder: Any,
+ config: Any,
+ kg_ctx: Any,
+ records: list[PageRecord],
+ repo_name: str,
+ coverage_pct: float,
+) -> set[str]:
+ """The unwritten pages inside the top ``coverage_pct`` by importance.
+
+ Runs the *budgeted* selection at ``coverage_pct`` (the same importance model
+ ``repowise init`` uses at that coverage) and maps it to page ids. The
+ file / module / cycle / symbol content pages are what coverage rations;
+ the repo-wide and structural pages (overview, architecture, layers,
+ onboarding) are always included when unwritten, as init emits them at every
+ coverage. Only ids that exist as template pages survive: a written page is
+ not re-billed, and a selected id with no page yet (a file added since
+ indexing) is dropped, since ``generate`` only rewrites existing pages.
+
+ One deliberate simplification: the selection here is demand-free
+ (``demand=None``), whereas a full init pass tilts its file-page picks by
+ mined session demand. On a fresh install the two are identical; where session
+ history exists they can pick the same *count* of files but a slightly
+ different set. Not worth reading every transcript on each generate run.
+ """
+ coverage_cfg = replace(
+ config, coverage_pct=coverage_pct, max_pages_pct=coverage_pct, deterministic=False
+ )
+ selection = select_pages(
+ _selection_inputs(
+ parsed_files=parsed_files,
+ graph_builder=graph_builder,
+ config=coverage_cfg,
+ kg_ctx=kg_ctx,
+ select_all=False,
+ )
+ )
+ return _ranked_ids_to_seed(selection_page_ids(selection, repo_name), records)
+
+
+def _ranked_ids_to_seed(ranked_ids: set[str], records: list[PageRecord]) -> set[str]:
+ """Restrict ranked ids to the unwritten pages, adding structural pages.
+
+ Layer + onboarding pages are structural: the budgeted selection does not
+ rank them (layers come from KG membership, onboarding is curated), and init
+ writes every one of them regardless of coverage. Add the unwritten ones so a
+ coverage upgrade produces the same navigable wiki init would, then keep only
+ ids that exist as template pages today.
+ """
+ structural_ids = {
+ r.page_id for r in records if r.page_type in _STRUCTURAL_PAGE_TYPES and r.is_template
+ }
+ template_ids = {r.page_id for r in records if r.is_template}
+ return (ranked_ids | structural_ids) & template_ids
+
+
def build_cost_plans(generate_ids: set[str]) -> list[PageTypePlan]:
"""Group the id set by page type into cost-estimator plans.
@@ -165,14 +277,31 @@ def resolve_scope(
intent: PageSelectionIntent,
cascade_mode: CascadeMode,
deps: PageDependencies,
+ ranked_seed: set[str] | None = None,
) -> ScopePlan:
- """Resolve intent -> seeds -> cascade -> the full scope plan."""
- seeds = resolve_page_selection(records, intent)
- cascade: CascadeResult = expand_cascade(set(seeds.page_ids), cascade_mode, deps)
+ """Resolve seeds -> cascade -> the full scope plan.
+
+ ``ranked_seed`` short-circuits the intent selectors: a ``--coverage`` /
+ ``--top`` run has already picked the exact page-id set by importance (see
+ :func:`build_ranked_seed`), so it is used verbatim as the seed. Otherwise
+ the intent (all / unwritten / stale / paths / ids) is resolved against the
+ existing records.
+ """
+ if ranked_seed is not None:
+ seed_ids = set(ranked_seed)
+ unknown: tuple[str, ...] = ()
+ seed_count = len(seed_ids)
+ else:
+ seeds = resolve_page_selection(records, intent)
+ seed_ids = set(seeds.page_ids)
+ unknown = seeds.unknown_page_ids
+ seed_count = len(seeds)
+
+ cascade: CascadeResult = expand_cascade(seed_ids, cascade_mode, deps)
return ScopePlan(
generate_ids=cascade.generate_ids,
stale_ids=cascade.stale_ids,
cost_plans=build_cost_plans(cascade.generate_ids),
- unknown_page_ids=seeds.unknown_page_ids,
- seed_count=len(seeds),
+ unknown_page_ids=unknown,
+ seed_count=seed_count,
)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
index 998693e66..2db39c840 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
@@ -17,9 +17,18 @@ import sys
from dataclasses import replace as _replace
from typing import Any
-import click
from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
+# The cost-gate helpers moved to ``repowise.cli.cost_gate`` so ``init`` and
+# ``generate`` share one gate. Re-exported here for the callers that still
+# import them from this module (init's command + workspace flows).
+from repowise.cli.cost_gate import (
+ COST_GATE_USD,
+ CostGateDeclined,
+ confirm_cost_gate,
+ cost_gate_declined,
+ format_cost,
+)
from repowise.cli.helpers import console, run_async
from repowise.cli.providers import (
build_cost_tracker,
@@ -29,62 +38,15 @@ from repowise.cli.providers import (
)
from repowise.cli.ui import BRAND_STYLE, OWL_SPINNER, MaybeCountColumn, RichProgressCallback
-# The LLM-cost confirmation threshold. A run whose estimate exceeds this asks
-# for confirmation (unless ``--yes``); below it generation proceeds silently.
-COST_GATE_USD = 2.00
-
-
-class CostGateDeclined(Exception): # noqa: N818 — a control-flow signal, not an error
- """Raised when the user answers No at the LLM-cost confirmation prompt.
-
- Carries no payload — the caller just needs to know that generation was
- declined so it can persist state in index-only shape (no docs) and
- return cleanly. Using an exception (vs. a sentinel return value) lets
- us bail out of nested generation flows without rethreading return
- types through every helper.
- """
-
-
-def confirm_cost_gate(message: str) -> bool:
- """Render the cost-gate ``[Y/n]`` prompt with visual padding.
-
- Click's plain ``confirm`` interleaves with the trailing line of any
- prior Rich output (progress-bar frames, status spinners), making the
- confirm glyphs hard to spot — users have walked past it and approved
- a $14 bill thinking they were still in cost-estimate territory. A
- blank line + horizontal rule cleanly separates the prompt from
- whatever was printed above it.
-
- Default is Yes: the user just picked a coverage tier with the cost
- range printed next to it, so Enter-through should continue the run
- they configured — the gate exists to make the spend visible, not to
- interrupt it.
- """
- console.line()
- console.rule(style="yellow")
- return click.confirm(message, default=True)
-
-
-def cost_gate_declined(est: Any, *, yes: bool, message: str) -> bool:
- """Return ``True`` when the run should skip generation on cost grounds.
-
- Only prompts when the estimate clears :data:`COST_GATE_USD` and ``--yes``
- was not passed; a declined prompt yields ``True``.
- """
- return est.estimated_cost_usd > COST_GATE_USD and not yes and not confirm_cost_gate(message)
-
-
-def format_cost(est: Any) -> str:
- """Render an estimate as a human-readable USD string (range when known)."""
- if est.cost_range is not None:
- cost_str = (
- f"${est.cost_range.low:.2f} - ${est.cost_range.high:.2f} USD "
- f"(median ${est.estimated_cost_usd:.2f})"
- )
- if est.is_calibrated:
- cost_str += " [calibrated]"
- return cost_str
- return f"${est.estimated_cost_usd:.2f} USD"
+__all__ = [
+ "COST_GATE_USD",
+ "CostGateDeclined",
+ "confirm_cost_gate",
+ "cost_gate_declined",
+ "format_cost",
+ "run_repo_generation",
+ "select_coverage",
+]
def select_coverage(
@@ -117,9 +79,7 @@ def select_coverage(
# Curated modules from the in-memory index result, so the plan/cost
# estimate selects the same module set generation will (the artifact
# file is not on disk yet during a fresh init).
- kg_modules = (
- getattr(getattr(result, "knowledge_graph_result", None), "modules", None) or None
- )
+ kg_modules = getattr(getattr(result, "knowledge_graph_result", None), "modules", None) or None
if sys.stdin.isatty() and coverage_pct is None and not yes:
options = compute_coverage_options(
@@ -298,9 +258,7 @@ def run_repo_generation(
# kg_ctx file fallback is empty and module selection silently
# degrades to community grouping.
kg_modules=(
- getattr(
- getattr(result, "knowledge_graph_result", None), "modules", None
- )
+ getattr(getattr(result, "knowledge_graph_result", None), "modules", None)
or None
),
kg_data=(
diff --git a/packages/cli/src/repowise/cli/cost_gate.py b/packages/cli/src/repowise/cli/cost_gate.py
new file mode 100644
index 000000000..578788d62
--- /dev/null
+++ b/packages/cli/src/repowise/cli/cost_gate.py
@@ -0,0 +1,73 @@
+"""Shared LLM-cost confirmation gate.
+
+Both ``repowise init`` and ``repowise generate`` put a spend estimate in front
+of the user and ask before running a model. The gate constant, the declined
+signal, and the confirm/format helpers used to live in ``init_cmd/generation``;
+they now live here so the two commands share one gate rather than one importing
+the other's internals.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import console
+
+# The LLM-cost confirmation threshold. A run whose estimate exceeds this asks
+# for confirmation (unless ``--yes``); below it generation proceeds silently.
+COST_GATE_USD = 2.00
+
+
+class CostGateDeclined(Exception): # noqa: N818 — a control-flow signal, not an error
+ """Raised when the user answers No at the LLM-cost confirmation prompt.
+
+ Carries no payload — the caller just needs to know that generation was
+ declined so it can persist state in index-only shape (no docs) and
+ return cleanly. Using an exception (vs. a sentinel return value) lets
+ us bail out of nested generation flows without rethreading return
+ types through every helper.
+ """
+
+
+def confirm_cost_gate(message: str) -> bool:
+ """Render the cost-gate ``[Y/n]`` prompt with visual padding.
+
+ Click's plain ``confirm`` interleaves with the trailing line of any
+ prior Rich output (progress-bar frames, status spinners), making the
+ confirm glyphs hard to spot — users have walked past it and approved
+ a $14 bill thinking they were still in cost-estimate territory. A
+ blank line + horizontal rule cleanly separates the prompt from
+ whatever was printed above it.
+
+ Default is Yes: the user just picked a coverage tier with the cost
+ range printed next to it, so Enter-through should continue the run
+ they configured — the gate exists to make the spend visible, not to
+ interrupt it.
+ """
+ console.line()
+ console.rule(style="yellow")
+ return click.confirm(message, default=True)
+
+
+def cost_gate_declined(est: Any, *, yes: bool, message: str) -> bool:
+ """Return ``True`` when the run should skip generation on cost grounds.
+
+ Only prompts when the estimate clears :data:`COST_GATE_USD` and ``--yes``
+ was not passed; a declined prompt yields ``True``.
+ """
+ return est.estimated_cost_usd > COST_GATE_USD and not yes and not confirm_cost_gate(message)
+
+
+def format_cost(est: Any) -> str:
+ """Render an estimate as a human-readable USD string (range when known)."""
+ if est.cost_range is not None:
+ cost_str = (
+ f"${est.cost_range.low:.2f} - ${est.cost_range.high:.2f} USD "
+ f"(median ${est.estimated_cost_usd:.2f})"
+ )
+ if est.is_calibrated:
+ cost_str += " [calibrated]"
+ return cost_str
+ return f"${est.estimated_cost_usd:.2f} USD"
diff --git a/packages/cli/src/repowise/cli/coverage_select.py b/packages/cli/src/repowise/cli/coverage_select.py
index e6c519819..21ea63600 100644
--- a/packages/cli/src/repowise/cli/coverage_select.py
+++ b/packages/cli/src/repowise/cli/coverage_select.py
@@ -15,7 +15,6 @@ from rich.table import Table
from repowise.cli.cost_estimator import CoverageOption
from repowise.cli.ui import BRAND, BRAND_STYLE
-
# Columns shown in the coverage table. ``onboarding`` is constant
# across percentages (curated slots) but we include it so the user
# sees the full picture.
@@ -31,7 +30,9 @@ _DISPLAY_COLUMNS: tuple[tuple[str, str], ...] = (
def _format_pct(option: CoverageOption) -> str:
- label = f"{int(option.pct * 100)}%"
+ # ``repowise generate`` offers a 100% row meaning "every unwritten page";
+ # "All" reads better than "100%" for it. init never passes >= 1.0.
+ label = "All" if option.pct >= 1.0 else f"{int(option.pct * 100)}%"
if option.is_recommended:
label += " (rec)"
return label
diff --git a/tests/unit/cli/test_generate_chooser.py b/tests/unit/cli/test_generate_chooser.py
new file mode 100644
index 000000000..7cd1d3ef3
--- /dev/null
+++ b/tests/unit/cli/test_generate_chooser.py
@@ -0,0 +1,150 @@
+"""Unit tests for the ``repowise generate`` interactive chooser helpers."""
+
+from __future__ import annotations
+
+from repowise.cli.commands.generate_cmd import chooser as chooser_mod
+from repowise.cli.commands.generate_cmd.chooser import (
+ choose_cascade,
+ print_wiki_state,
+ run_interactive_chooser,
+)
+from repowise.core.generation.cascade import build_page_dependencies
+from repowise.core.generation.page_selection import PageRecord
+
+
+class _RecordingConsole:
+ """Captures print calls; asserts the prompt is never reached."""
+
+ def __init__(self) -> None:
+ self.lines: list[str] = []
+
+ def print(self, *args: object, **_: object) -> None:
+ self.lines.append(" ".join(str(a) for a in args))
+
+
+class _MG:
+ def __init__(self, key: str, file_paths: tuple[str, ...]) -> None:
+ self.key = key
+ self.file_paths = file_paths
+
+
+def test_choose_cascade_skips_prompt_when_outcome_is_identical() -> None:
+ # No containers and no repo-wide pages: every cascade mode generates exactly
+ # the seed, so the choice cannot change the outcome and must not prompt.
+ deps = build_page_dependencies(
+ module_groups=[], scc_groups=[], layer_page_of={}, repo_wide_ids=()
+ )
+ console = _RecordingConsole()
+ mode = choose_cascade(console, {"file_page:a.py"}, deps, default="none")
+ assert mode == "none"
+ # Nothing printed because the modes did not diverge (no prompt shown).
+ assert console.lines == []
+
+
+def test_choose_cascade_prompts_when_modes_diverge(monkeypatch) -> None:
+ # a.py rolls up into a module page and there is a repo-wide overview, so the
+ # three modes generate different sets and the chooser must prompt.
+ deps = build_page_dependencies(
+ module_groups=[_MG("src", ("a.py",))],
+ scc_groups=[],
+ layer_page_of={},
+ repo_wide_ids=("repo_overview:demo",),
+ )
+ asked: dict[str, object] = {}
+
+ def fake_ask(prompt, choices, default, console):
+ asked["choices"] = choices
+ asked["default"] = default
+ return "2" # pick "dependents"
+
+ monkeypatch.setattr(
+ "repowise.cli.commands.generate_cmd.chooser.Prompt.ask", fake_ask
+ )
+ mode = choose_cascade(_RecordingConsole(), {"file_page:a.py"}, deps, default="none")
+ assert mode == "dependents"
+ assert asked["choices"] == ["1", "2", "3"]
+ assert asked["default"] == "1" # default maps to "none"
+
+
+class _Provider:
+ provider_name = "openai"
+ model_name = "gpt-x"
+
+
+class _Option:
+ def __init__(self, pct: float) -> None:
+ self.pct = pct
+
+
+def _patch_chooser(monkeypatch, *, chosen_pct: float, seed: set[str]) -> None:
+ monkeypatch.setattr(chooser_mod, "compute_coverage_options", lambda **_: [_Option(0.2)])
+ monkeypatch.setattr(
+ chooser_mod, "interactive_coverage_select", lambda *a, **k: _Option(chosen_pct)
+ )
+ monkeypatch.setattr(chooser_mod, "build_ranked_seed", lambda **_: set(seed))
+
+
+def _run(records, deps):
+ return run_interactive_chooser(
+ _RecordingConsole(),
+ records=records,
+ parsed_files=[],
+ graph_builder=object(),
+ config=object(),
+ kg_ctx=object(),
+ provider=_Provider(),
+ repo_path=object(),
+ repo_name="demo",
+ deps=deps,
+ )
+
+
+def test_run_interactive_chooser_returns_scope(monkeypatch) -> None:
+ records = [PageRecord("file_page:a.py", "file_page", "a.py", is_template=True)]
+ deps = build_page_dependencies(
+ module_groups=[], scc_groups=[], layer_page_of={}, repo_wide_ids=()
+ )
+ _patch_chooser(monkeypatch, chosen_pct=0.2, seed={"file_page:a.py"})
+ choice = _run(records, deps)
+ assert choice is not None
+ assert choice.ranked_seed == {"file_page:a.py"}
+ # No containers/repo-wide, so cascade cannot change the outcome -> none.
+ assert choice.cascade_mode == "none"
+
+
+def test_run_interactive_chooser_bails_when_nothing_unwritten(monkeypatch) -> None:
+ records = [PageRecord("file_page:a.py", "file_page", "a.py", is_template=False)]
+ deps = build_page_dependencies(
+ module_groups=[], scc_groups=[], layer_page_of={}, repo_wide_ids=()
+ )
+ _patch_chooser(monkeypatch, chosen_pct=0.2, seed=set())
+ # Guard fires before the menu: every page is already written.
+ assert _run(records, deps) is None
+
+
+def test_run_interactive_chooser_bails_when_pick_is_all_written(monkeypatch) -> None:
+ records = [PageRecord("file_page:a.py", "file_page", "a.py", is_template=True)]
+ deps = build_page_dependencies(
+ module_groups=[], scc_groups=[], layer_page_of={}, repo_wide_ids=()
+ )
+ # There are unwritten pages, but the chosen coverage resolves to an empty
+ # seed (e.g. a tiny pct on a repo whose important pages are all written).
+ _patch_chooser(monkeypatch, chosen_pct=0.1, seed=set())
+ assert _run(records, deps) is None
+
+
+def test_print_wiki_state_counts_by_provenance() -> None:
+ records = [
+ PageRecord("a", "file_page", "a.py", is_template=True),
+ PageRecord("b", "file_page", "b.py", is_template=False),
+ PageRecord("c", "file_page", "c.py", is_template=True, freshness_status="stale"),
+ ]
+ console = _RecordingConsole()
+ print_wiki_state(console, records)
+ line = console.lines[0]
+ assert "3 pages" in line
+ assert "written" in line and "unwritten" in line and "stale" in line
+ # Numbers are wrapped in rich color markup, so match the wrapped forms.
+ assert "1[/cyan] written" in line
+ assert "2[/yellow] unwritten" in line
+ assert "1[/red] stale" in line
diff --git a/tests/unit/cli/test_generate_scope.py b/tests/unit/cli/test_generate_scope.py
index 39b5272b5..28913012a 100644
--- a/tests/unit/cli/test_generate_scope.py
+++ b/tests/unit/cli/test_generate_scope.py
@@ -5,12 +5,15 @@ from __future__ import annotations
from dataclasses import dataclass
from repowise.cli.commands.generate_cmd.scope import (
+ _ranked_ids_to_seed,
build_cost_plans,
load_page_records,
resolve_scope,
+ selection_page_ids,
)
from repowise.core.generation.cascade import build_page_dependencies
-from repowise.core.generation.page_selection import PageSelectionIntent
+from repowise.core.generation.models import compute_page_id
+from repowise.core.generation.page_selection import PageRecord, PageSelectionIntent
@dataclass
@@ -96,3 +99,92 @@ def test_resolve_scope_unwritten_with_cascade_none() -> None:
# not stale. No repo-wide left (overview is regenerated).
assert plan.stale_ids == set()
assert plan.seed_count == 3
+
+
+class _FakeGroup:
+ """Duck-typed selection ``ModuleGroup``."""
+
+ def __init__(self, key: str) -> None:
+ self.key = key
+
+
+class _FakeSelection:
+ """Minimal duck-typed :class:`Selection` for ``selection_page_ids``."""
+
+ def __init__(self) -> None:
+ self.file_page_paths = ["src/a.py", "src/b.py"]
+ self.module_groups = [_FakeGroup("src")]
+ self.scc_groups = [("cycle-1", ["src/a.py", "src/b.py"])]
+ self.api_contract_paths = ["openapi.yaml"]
+ self.infra_paths = ["Dockerfile"]
+ self.symbol_spotlights = [("src/a.py", "Widget")]
+ self.emit_repo_overview = True
+ self.emit_arch_diagram = True
+
+
+def test_selection_page_ids_mirrors_generation_id_assignment() -> None:
+ ids = selection_page_ids(_FakeSelection(), "demo")
+ assert ids == {
+ compute_page_id("file_page", "src/a.py"),
+ compute_page_id("file_page", "src/b.py"),
+ compute_page_id("module_page", "src"),
+ compute_page_id("scc_page", "cycle-1"),
+ compute_page_id("api_contract", "openapi.yaml"),
+ compute_page_id("infra_page", "Dockerfile"),
+ compute_page_id("symbol_spotlight", "src/a.py::Widget"),
+ compute_page_id("repo_overview", "demo"),
+ compute_page_id("architecture_diagram", "demo"),
+ }
+
+
+def test_selection_page_ids_honors_emit_flags() -> None:
+ sel = _FakeSelection()
+ sel.emit_repo_overview = False
+ sel.emit_arch_diagram = False
+ ids = selection_page_ids(sel, "demo")
+ assert compute_page_id("repo_overview", "demo") not in ids
+ assert compute_page_id("architecture_diagram", "demo") not in ids
+
+
+def test_ranked_ids_to_seed_keeps_unwritten_and_adds_structural() -> None:
+ records = [
+ PageRecord("file_page:a.py", "file_page", "a.py", is_template=True),
+ PageRecord("file_page:b.py", "file_page", "b.py", is_template=False),
+ PageRecord("layer_page:core", "layer_page", "core", is_template=True),
+ PageRecord("onboarding:tour", "onboarding", "tour", is_template=True),
+ PageRecord("onboarding:map", "onboarding", "map", is_template=False),
+ ]
+ # Ranked picks both file pages; the written one (b.py) must drop, and the
+ # unwritten structural pages (layer + one onboarding) must be pulled in even
+ # though the ranked set never named them.
+ seed = _ranked_ids_to_seed({"file_page:a.py", "file_page:b.py"}, records)
+ assert seed == {"file_page:a.py", "layer_page:core", "onboarding:tour"}
+
+
+def test_ranked_ids_to_seed_drops_ids_with_no_page() -> None:
+ # A ranked id for a file added since indexing has no page row; it is dropped
+ # rather than fabricated (generate only rewrites existing pages).
+ records = [PageRecord("file_page:a.py", "file_page", "a.py", is_template=True)]
+ seed = _ranked_ids_to_seed({"file_page:a.py", "file_page:new.py"}, records)
+ assert seed == {"file_page:a.py"}
+
+
+def test_resolve_scope_uses_ranked_seed_verbatim() -> None:
+ records = [
+ PageRecord("file_page:a.py", "file_page", "a.py", is_template=True),
+ PageRecord("file_page:b.py", "file_page", "b.py", is_template=True),
+ ]
+ deps = build_page_dependencies(
+ module_groups=[], scc_groups=[], layer_page_of={}, repo_wide_ids=()
+ )
+ # An all-selecting intent would pick both; the ranked seed overrides it.
+ plan = resolve_scope(
+ records=records,
+ intent=PageSelectionIntent(all_pages=True),
+ cascade_mode="none",
+ deps=deps,
+ ranked_seed={"file_page:a.py"},
+ )
+ assert plan.generate_ids == {"file_page:a.py"}
+ assert plan.seed_count == 1
+ assert plan.unknown_page_ids == ()