Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
Collapse init and generate to a single cost question (#1036)
Raghav Chamadiya7280ed0844d7
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/chooser.py b/packages/cli/src/repowise/cli/commands/generate_cmd/chooser.pyindex 5c09814f6..d22ed0c37 100644--- a/packages/cli/src/repowise/cli/commands/generate_cmd/chooser.py+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/chooser.py@@ -1,16 +1,11 @@-"""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.+"""Interactive helpers for a bare ``repowise generate``.++A bare ``generate`` on a terminal does not silently rewrite the whole wiki. It+shows the wiki's written / unwritten state, defaults to writing the concept+pages that are still stubs, asks about cascade only when it would change which+pages get written, and then puts the single cost question in front of the user.+Piped / ``--yes`` / flagged runs skip straight to that non-interactive default+(``--unwritten``)."""from __future__ import annotations@@ -20,44 +15,43 @@ from dataclasses import dataclassfrom rich.console import Consolefrom rich.prompt import Prompt-from repowise.cli.coverage_select import interactive_coverage_select-from repowise.core.cost_estimator import compute_coverage_optionsfrom repowise.core.generation.cascade import CascadeMode, PageDependencies, expand_cascadefrom 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."""+ """The cascade a bare ``generate`` resolved to through the chooser."""- ranked_seed: set[str]cascade_mode: CascadeMode+def _concept_records(records: list[PageRecord]) -> list[PageRecord]:+ """The pages a model writes. Everything else is structural, and generate+ never touches it, so the wiki-state count and the "nothing unwritten" guard+ both read the concept layer only (a structural page is permanently a+ template, so counting it would always report the wiki as unwritten)."""+ from .engine import _MODEL_WRITTEN_PAGE_TYPES++ return [r for r in records if r.page_type in _MODEL_WRITTEN_PAGE_TYPES]++def print_wiki_state(console: Console, records: list[PageRecord]) -> None:- """Print the written / unwritten / stale breakdown of the current wiki.+ """Print the written / unwritten / stale breakdown of the concept layer.- ``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.+ Scoped to the pages a model writes: ``written`` + ``unwritten`` partition+ those and ``stale`` is a cross-cutting count of ones whose code moved on. The+ total wiki size (structural pages included) is shown for context."""- total = len(records)- template = sum(1 for r in records if r.is_template)+ concept = _concept_records(records)+ total = len(concept)+ template = sum(1 for r in concept if r.is_template)written = total - template- stale = sum(1 for r in records if r.is_stale)+ stale = sum(1 for r in concept if r.is_stale)line = (- f"[bold]Wiki:[/bold] {total} pages — "+ f"[bold]Subsystem pages:[/bold] {total} of {len(records)} wiki pages. "f"[cyan]{written}[/cyan] written, [yellow]{template}[/yellow] unwritten")if stale:@@ -70,15 +64,13 @@ def choose_cascade(seed_ids: set[str],deps: PageDependencies,*,- default: CascadeMode = "none",+ default: CascadeMode = "dependents",) -> 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.+ pages (the "only when it changes the outcome" rule). 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:@@ -88,7 +80,7 @@ def choose_cascade(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",+ "dependents": "also rewrite the layer pages that contain them","full": "also rewrite the repo-wide overview, architecture and onboarding",}choices: list[str] = []@@ -110,61 +102,20 @@ 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.+ """Show the wiki state and resolve a bare ``generate`` to "write the stubs".- Returns ``None`` when there is nothing to write (no unwritten pages, or the- user's coverage pick lands entirely on already-written pages).+ Returns ``None`` when there is nothing to write (every page is already+ written). Otherwise the run writes the unwritten pages (the caller's default+ intent), and this only decides the cascade, asking when it changes the+ outcome."""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."- )+ unwritten = {r.page_id for r in _concept_records(records) if r.is_template}+ if not unwritten:+ console.print("[green]Every subsystem page is already written.[/green] Nothing to upgrade.")return None- cascade_mode = choose_cascade(console, ranked_seed, deps)- return InteractiveChoice(ranked_seed=ranked_seed, cascade_mode=cascade_mode)+ cascade_mode = choose_cascade(console, unwritten, deps)+ return InteractiveChoice(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.pyindex a86f13b61..ae76e442d 100644--- a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py@@ -63,39 +63,30 @@ 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.+# Page types rendered from structure, always. A model never writes one, so+# naming one for `generate` is a mistake worth catching rather than a silent+# no-op: these pages refresh on `repowise update`, not here.+_STRUCTURAL_PAGE_TYPES = frozenset(+ {"file_page", "symbol_spotlight", "api_contract", "infra_page", "scc_page", "layer_page"}+)+++def _reject_structural_page_ids(page_ids: tuple[str, ...]) -> None:+ """Error clearly when an explicit ``--page`` names a structural page.++ A ``file_page`` (or any other structural type) is rendered from the code, so+ there is nothing for a model to write. Naming one is almost always a+ misunderstanding, and a silent no-op would hide it, so it is a clear error+ pointing at the command that does refresh those pages."""- 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:+ bad = [pid for pid in page_ids if pid.split(":", 1)[0] in _STRUCTURAL_PAGE_TYPES]+ if bad:+ joined = ", ".join(bad)raise click.ClickException(- "--coverage / --top rank pages by importance and cannot be combined with "- "--all / --unwritten / --stale / --path / --page."+ f"These pages are rendered from structure, not written by a model, so "+ f"generate has nothing to write for them: {joined}. They refresh on "+ "`repowise update`. generate writes the concept and overview pages.")- 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):@@ -108,11 +99,7 @@ def _make_gate(dry_run: bool):def gate_cost(cost_plans: Any, provider: Any, repo_path: Path, *, yes: bool, dry_run: bool) -> bool:- from repowise.cli.commands.init_cmd.generation import (- COST_GATE_USD,- cost_gate_declined,- format_cost,- )+ from repowise.cli.commands.init_cmd.generation import cost_gate_blocks, format_costfrom repowise.core.cost_estimator import estimate_costest = None@@ -126,22 +113,17 @@ def _make_gate(dry_run: bool):if est is not None:pages = sum(p.count for p in cost_plans)console.print(- f"Estimated: [bold]{pages}[/bold] pages, [bold]{format_cost(est)}[/bold]."+ f"Writing [bold]{pages}[/bold] pages with "+ f"[cyan]{provider.model_name}[/cyan]. Estimated [bold]{format_cost(est)}[/bold].")if dry_run:console.print("[dim]Dry run — nothing generated.[/dim]")return False- if est is not None:- if est.estimated_cost_usd > COST_GATE_USD and not yes and not sys.stdin.isatty():- raise click.ClickException(- f"This would spend about {format_cost(est)} and there is no terminal "- "to confirm on. Re-run with --yes to accept the cost."- )- if cost_gate_declined(est, yes=yes, message=" Generate at this cost?"):- console.print("[yellow]Aborted.[/yellow] Nothing generated.")- return False+ if est is not None and cost_gate_blocks(est, yes=yes, message=" Generate at this cost?"):+ console.print("[yellow]Aborted.[/yellow] Nothing generated.")+ return Falsereturn Truereturn gate_cost@@ -169,31 +151,13 @@ 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=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."+ "What to do with the overview / layer pages that summarize a regenerated "+ "concept page. Default: dependents."),)@click.option("--provider", "provider_name", default=None, help="LLM provider name.")@@ -212,8 +176,6 @@ def generate_command(stale: bool,path_globs: tuple[str, ...],page_ids: tuple[str, ...],- coverage: float | None,- top_n: int | None,cascade: str | None,provider_name: str | None,model: str | None,@@ -223,20 +185,21 @@ def generate_command(yes: bool,verbose: bool,) -> None:- """Write wiki pages with a model. Bare `generate` opens an interactive chooser.+ """Write the concept pages with a model. Bare `generate` writes the stubs.- 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.+ Select with --all (rewrite the prose) / --unwritten (write the concept pages+ still on a stub) / --stale / --path / --page. With no flag on a terminal,+ a bare run shows the wiki's state and writes the unwritten concept pages+ after the single cost question. --page / --path resolve only to pages a model+ writes; naming a structural (file / symbol / api / infra / cycle / layer)+ page is an error, since those refresh on `repowise update`.Examples:- 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+ repowise generate # write the unwritten concept pages+ repowise generate --unwritten # same, explicitly+ repowise generate --all # rewrite the prose on every concept page+ repowise generate --path src/api # just the concept pages under src/api+ repowise generate --page module_page:src/api --cascade none"""configure_cli_logging(verbose=verbose)@@ -248,20 +211,19 @@ def generate_command(cfg = load_config(repo_path)+ # An explicit page id must name a page a model writes. Caught up front so a+ # `--page file_page:...` is a clear error, not a silent no-op deep in resolve.+ _reject_structural_page_ids(page_ids)+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()+ # Bare `generate` on a terminal shows the wiki state and writes the unwritten+ # concept pages. Piped / `--yes` / flagged runs skip straight to that default.+ interactive = not explicit 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")+ # An explicit pick pulls in the pages that summarize it (dependents); the+ # interactive path asks when it would change the outcome.+ cascade_mode = cascade if cascade is not None else "dependents"intent = _build_intent(all_pages=all_pages,@@ -321,8 +283,6 @@ def generate_command(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.pyindex 5f8dfabc4..64d0eb54b 100644--- a/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/engine.py@@ -9,19 +9,40 @@ in core so the OSS server and hosted share it.from __future__ import annotations-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Anyfrom repowise.cli.helpers import console, load_statefrom repowise.core.generation.cascade import CascadeModefrom repowise.core.generation.page_selection import PageSelectionIntent-from repowise.core.generation.scope import ScopePlan, build_ranked_seed, resolve_scope+from repowise.core.generation.scope import ScopePlan, build_cost_plans, resolve_scopefrom repowise.core.pipeline.scoped_generation import (execute_scoped_generation,rehydrate_repo,)+# The page types a model writes. Everything else is structural and refreshes on+# `repowise update`, so `generate` never writes one: it works on the concept+# layer only. Its complement is the structural set in generate_cmd/command.py.+_MODEL_WRITTEN_PAGE_TYPES = frozenset(+ {"module_page", "repo_overview", "architecture_diagram", "onboarding"}+)+++def _narrow_to_model_written(plan: ScopePlan) -> ScopePlan:+ """Drop structural pages from a resolved plan, so generate writes only prose.++ ``--unwritten`` / ``--all`` / ``--path`` resolve against every page type, but+ a structural page has no model to write it: including it would re-render it+ from templates (a no-op that leaves it "unwritten") and inflate the headline+ count. Keep only the model-written pages, in both the generate set and the+ cascade fallout marked stale, and re-price from what remains.+ """+ gen = {pid for pid in plan.generate_ids if pid.split(":", 1)[0] in _MODEL_WRITTEN_PAGE_TYPES}+ stale = {pid for pid in plan.stale_ids if pid.split(":", 1)[0] in _MODEL_WRITTEN_PAGE_TYPES}+ return replace(plan, generate_ids=gen, stale_ids=stale, cost_plans=build_cost_plans(gen))+@dataclassclass GenerateOutcome:@@ -34,18 +55,6 @@ 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,@@ -58,8 +67,6 @@ 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 +117,7 @@ async def run_scoped_generation(if rehydrated is None:console.print("[yellow]This repo has no wiki pages yet.[/yellow] "- "Run `repowise init --docs deterministic` or `repowise update --full` first."+ "Run `repowise init --no-prose` or `repowise update --full` first.")return None@@ -119,55 +126,30 @@ async def run_scoped_generation("(graph + git reused from index).")- # 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+ # A bare interactive run shows the wiki state and writes the unwritten+ # pages (the caller's default intent); it only decides the cascade here.if interactive:from .chooser import run_interactive_chooserchoice = run_interactive_chooser(console,records=rehydrated.records,- parsed_files=rehydrated.parsed_files,- graph_builder=rehydrated.graph_builder,- config=config,- kg_ctx=rehydrated.kg_ctx,- provider=provider,- repo_path=repo_path,- repo_name=rehydrated.repo_name,deps=rehydrated.deps,)if choice is None:return None- ranked_seed = choice.ranked_seedcascade_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(rehydrated.parsed_files))- ranked_seed = build_ranked_seed(- parsed_files=rehydrated.parsed_files,- graph_builder=rehydrated.graph_builder,- config=config,- kg_ctx=rehydrated.kg_ctx,- records=rehydrated.records,- repo_name=rehydrated.repo_name,- coverage_pct=pct,- )- if not ranked_seed:- console.print(- "[yellow]Everything in that coverage is already written.[/yellow] "- "Nothing to generate."- )- return Noneplan = resolve_scope(records=rehydrated.records,intent=intent,cascade_mode=cascade_mode,deps=rehydrated.deps,- ranked_seed=ranked_seed,+ ranked_seed=None,)+ # generate writes the concept layer only; structural pages refresh on+ # `repowise update`, so drop them from whatever the intent resolved to.+ plan = _narrow_to_model_written(plan)if plan.unknown_page_ids:console.print(@@ -245,7 +227,15 @@ async def run_scoped_generation(async def _page_stats(sf: Any, repo_id: str) -> tuple[int, int]:- """Return ``(total_pages, remaining_template_pages)`` from the DB."""+ """Return ``(total_pages, remaining_stub_pages)`` from the DB.++ A "stub" is a page a model was meant to write but has not yet: a+ model-written page type still stamped ``provider_name='template'``.+ Structural pages are permanently ``template`` by design, so counting them+ would mean ``docs_mode`` could never flip to ``llm`` no matter how much+ prose was written. The remaining-stub count is scoped to the concept layer+ for exactly that reason.+ """from sqlalchemy import func as sa_funcfrom sqlalchemy import select as sa_select@@ -262,7 +252,7 @@ async def _page_stats(sf: Any, repo_id: str) -> tuple[int, int]:)).scalar_one())- templates = int(+ stubs = int((await session.execute(sa_select(sa_func.count())@@ -270,11 +260,12 @@ async def _page_stats(sf: Any, repo_id: str) -> tuple[int, int]:.where(Page.repository_id == repo_id,Page.provider_name == "template",+ Page.page_type.in_(list(_MODEL_WRITTEN_PAGE_TYPES)),))).scalar_one())- return total, templates+ return total, stubsdef _report_plan(plan: ScopePlan, cascade_mode: CascadeMode) -> None:diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex d5d5edae0..0e9e61fb2 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -73,7 +73,13 @@ from repowise.core.generation.styles import DEFAULT_STYLE, list_styles, resolve_from repowise.core.reasoning import REASONING_MODESfrom ._interactive import offer_distill_rewrite_hook, offer_hook_install-from .generation import cost_gate_declined, format_cost, run_repo_generation, select_coverage+from .generation import (+ concept_page_count,+ cost_gate_declined,+ estimate_generation,+ format_cost,+ run_repo_generation,+)from .persistence import (build_resume_controller,effective_run_mode_for_resume,@@ -240,7 +246,6 @@ def _run_generation_phase(onboarding: bool,harvest_decisions: bool,wiki_style: str,- coverage_pct: float | None,yes: bool,dry_run: bool,skip_tests: bool,@@ -273,15 +278,13 @@ def _run_generation_phase(harvest_decisions=harvest_decisions,wiki_style=wiki_style,)- chosen_pct, _plans, est, gen_config = select_coverage(+ plans, est = estimate_generation(result=result,gen_config=gen_config,provider=provider,repo_path=repo_path,skip_tests=skip_tests,skip_infra=skip_infra,- coverage_pct=coverage_pct,- yes=yes,)table = Table(title="Generation Plan", border_style=BRAND)@@ -309,11 +312,6 @@ def _run_generation_phase(f"If you see timeout errors, try [bold]--concurrency 1[/bold].")- console.print(- f" Coverage: {int(chosen_pct * 100)}% / "- f"~{est.estimated_input_tokens + est.estimated_output_tokens:,} tokens "- f"({format_cost(est)})"- )if onboarding:console.print(" [cyan]Onboarding collection:[/cyan] "@@ -330,18 +328,29 @@ def _run_generation_phase(console.print("[yellow]Dry run — no pages generated.[/yellow]")return True, False- if cost_gate_declined(est, yes=yes, message=" Write the wiki with the model at this cost?"):+ # The single cost question. Every structural page is free; the spend is the+ # concept tree and the repo-wide synthesis pages, stated as one number.+ #+ # This gate declines rather than raises when it cannot ask (no terminal, over+ # the gate, no --yes): init's index is built but not yet persisted, so+ # raising here would discard the whole run. Declining hands control to the+ # caller's fallback, which renders the free structural wiki and saves the+ # index. `generate` and `update --full` raise instead, because their index+ # already exists and re-running with --yes costs nothing.+ concept_n = concept_page_count(plans)+ console.print(+ f"Writing [bold]{concept_n}[/bold] concept pages with "+ f"[cyan]{provider.model_name}[/cyan]. Estimated [bold]{format_cost(est)}[/bold]."+ )+ if cost_gate_declined(est, yes=yes, message=" Continue?"):console.print("[yellow]Not writing it with the model.[/yellow] "- "[dim]Future `repowise update` runs stay index-only, so the "- "post-commit hook won't start a model run on its own.[/dim]"+ "[dim]Re-run with --yes to accept the cost, or run `repowise generate` "+ "later to write the subsystem pages. Future `repowise update` runs stay "+ "index-only, so the post-commit hook won't start a model run on its own.[/dim]")return False, True- # Persist the tiering knobs so `repowise update` regenerates with the same- # coverage settings (save_config later round-trips and preserves these).- # save_config_partial skips None, so a no-cap tier1 stays unwritten.-run_repo_generation(repo_path=repo_path,result=result,@@ -405,22 +414,31 @@ def _run_generation_phase(default=False,help="Limit generation to top 10 files by PageRank for quick validation.",)+ "--prose/--no-prose",+ "prose",+ default=None,+ help=(+ "Write the subsystem (concept) pages as model prose (needs a key), or "+ "render the whole wiki from structure with no model and no spend. Every "+ "other page is structural either way. Default: prose when a key is "+ "available. Use --mode fast for no wiki at all."+ ),+)@click.option("--index-only",is_flag=True,default=False,- help="Build the wiki from structure instead of writing it with a model. No key, no spend.",+ hidden=True,+ help="Deprecated alias for --no-prose.",)@click.option("--docs","docs_opt",type=click.Choice(["llm", "deterministic"]),default=None,- help=(- "How to produce the wiki: 'llm' writes it with a model (needs a key), "- "'deterministic' renders it from structure for free. Same choice as "- "--index-only, named for what it does. Use --mode fast for no wiki at all."- ),+ hidden=True,+ help="Deprecated: use --prose / --no-prose. 'llm' == --prose, 'deterministic' == --no-prose.",)@click.option("--mode",@@ -516,18 +534,6 @@ def _run_generation_phase("Slots with insufficient signal are skipped automatically."),)- "--coverage",- "coverage_pct",- type=float,- default=None,- metavar="PCT",- help=(- "Documentation coverage as a fraction of repo files (e.g. 0.10, 0.20, "- "0.50). Bypasses the interactive coverage chooser. Default when "- "interactive: prompt; otherwise 0.20."- ),-)@click.option("--coverage-report","coverage_report",@@ -627,6 +633,7 @@ def init_command(concurrency: int,reasoning: str | None,test_run: bool,+ prose: bool | None,index_only: bool,docs_opt: str | None,run_mode: str,@@ -643,7 +650,6 @@ def init_command(no_workspace: bool,init_all: bool,onboarding: bool,- coverage_pct: float | None,coverage_report: tuple[str, ...],harvest_decisions: bool,wiki_style: str | None,@@ -655,18 +661,40 @@ def init_command("""Generate wiki documentation for a codebase.PATH defaults to the current directory.- Use --docs deterministic (or --index-only) to render the wiki from structure- with no model and no key; --docs llm writes it with a model.+ Use --no-prose to render the whole wiki from structure with no model and no+ key; --prose writes the subsystem pages with a model. Every other page is+ structural either way.Use --mode fast for a quick graph + essential-git index of a very large repo."""- # ``--docs`` is the same switch as ``--index-only`` named for what it- # produces rather than what it skips, since an index-only run has rendered- # a full wiki since #975. Kept as two spellings because --index-only is in- # every existing script and doc; they must not disagree.+ # ``--prose / --no-prose`` is the one switch: prose on the concept pages, or+ # the whole wiki from structure. ``--index-only`` and ``--docs`` are the+ # previous spellings, kept working for one release as deprecated aliases so a+ # scripted ``--index-only`` does not break. ``index_only`` stays the internal+ # variable every downstream branch reads.+ if index_only or docs_opt is not None:+ console.print(+ "[dim]--index-only and --docs are deprecated; use --no-prose "+ "(structural, no key) or --prose (model-written). They still work "+ "this release.[/dim]"+ )+ # Each of the three sources votes for "structural" (True) or "prose" (False).+ # --index-only always means structural; --docs maps deterministic->structural,+ # llm->prose; --prose/--no-prose is the direct switch. Two votes that disagree+ # is a contradiction rather than a silent last-one-wins.+ _structural_votes = []+ if index_only:+ _structural_votes.append(True)if docs_opt is not None:- if index_only and docs_opt == "llm":- raise click.UsageError("--docs llm contradicts --index-only. Pass one.")- index_only = docs_opt == "deterministic"+ _structural_votes.append(docs_opt == "deterministic")+ if prose is not None:+ _structural_votes.append(not prose)+ if len(set(_structural_votes)) > 1:+ raise click.UsageError(+ "This mix of --prose / --no-prose, --index-only and --docs contradicts "+ "itself. Pass one."+ )+ if _structural_votes:+ index_only = _structural_votes[0]# --mode fast is a graph + essential-git index with no LLM work, so it# implies index-only on the CLI side; the orchestrator mode below switches# the git tier to ESSENTIAL.@@ -775,7 +803,6 @@ def init_command(resume=resume,force=force,onboarding=onboarding,- coverage_pct=coverage_pct,harvest_decisions=harvest_decisions,# Apply the chosen style uniformly across the workspace's repos# (no per-repo interactive prompt in the multi-repo flow).@@ -1258,7 +1285,6 @@ def init_command(onboarding=onboarding,harvest_decisions=harvest_decisions,wiki_style=wiki_style,- coverage_pct=coverage_pct,yes=yes,dry_run=dry_run,skip_tests=skip_tests,diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.pyindex 0372a8f9a..52ca736f8 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py@@ -13,8 +13,6 @@ returns a "declined" flag; the workspace flow prints a compact line and raisesfrom __future__ import annotationsimport contextlib-import sys-from dataclasses import replace as _replacefrom typing import Anyfrom rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn@@ -26,6 +24,7 @@ from repowise.cli.cost_gate import (COST_GATE_USD,CostGateDeclined,confirm_cost_gate,+ cost_gate_blocks,cost_gate_declined,format_cost,)@@ -41,15 +40,17 @@ from repowise.cli.ui import BRAND_STYLE, OWL_SPINNER, MaybeCountColumn, RichProg__all__ = ["COST_GATE_USD","CostGateDeclined",+ "concept_page_count","confirm_cost_gate",+ "cost_gate_blocks","cost_gate_declined",+ "estimate_generation","format_cost","run_repo_generation",- "select_coverage",]-def select_coverage(+def estimate_generation(*,result: Any,gen_config: Any,@@ -57,70 +58,49 @@ def select_coverage(repo_path: Any,skip_tests: bool,skip_infra: bool,- coverage_pct: float | None,- yes: bool,-) -> tuple[float, list[Any], Any, Any]:- """Pick a coverage level and estimate its cost.+) -> tuple[list[Any], Any]:+ """Build the generation plan and price it. One plan, one estimate.- Renders the interactive coverage chooser when stdin is a TTY and no- explicit ``--coverage`` was passed (and not ``--yes``); otherwise the- configured / default percentage drives a single non-interactive estimate.+ Every structural page type is free, and the concept tree is a total cover of+ the production files, so there is nothing to ration and no coverage level to+ pick. The spend is the concept tree plus the repo-wide synthesis pages, and+ it is a single number.- Returns ``(chosen_pct, plans, estimate, gen_config)`` where ``gen_config``- has the chosen coverage baked in so the page generator honours the pick.+ Returns ``(plans, estimate)``."""- from repowise.cli.cost_estimator import (- build_generation_plan,- compute_coverage_options,- estimate_cost,- )- from repowise.cli.coverage_select import interactive_coverage_select+ from repowise.cli.cost_estimator import build_generation_plan, estimate_cost# 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- if sys.stdin.isatty() and coverage_pct is None and not yes:- options = compute_coverage_options(- parsed_files=result.parsed_files,- graph_builder=result.graph_builder,- base_config=gen_config,- provider_name=provider.provider_name,- model_name=provider.model_name,- repo_path=repo_path,- skip_tests=skip_tests,- skip_infra=skip_infra,- kg_modules=kg_modules,- )- chosen = interactive_coverage_select(console, options, deterministic_tail=True)- chosen_pct = chosen.pct- plans = chosen.plans- est = chosen.estimate- else:- chosen_pct = coverage_pct if coverage_pct is not None else gen_config.coverage_pct- gen_config_for_plan = _replace(- gen_config, coverage_pct=chosen_pct, max_pages_pct=chosen_pct- )- plans = build_generation_plan(- result.parsed_files,- result.graph_builder,- gen_config_for_plan,- skip_tests,- skip_infra,- kg_modules=kg_modules,- )- est = estimate_cost(- plans,- provider.provider_name,- provider.model_name,- repo_path=repo_path,- )+ plans = build_generation_plan(+ result.parsed_files,+ result.graph_builder,+ gen_config,+ skip_tests,+ skip_infra,+ kg_modules=kg_modules,+ )+ est = estimate_cost(+ plans,+ provider.provider_name,+ provider.model_name,+ repo_path=repo_path,+ )+ return plans, est+- # Bake the chosen coverage into the gen_config that runs generation, so the- # page generator's selection layer honours the user's pick.- gen_config = _replace(gen_config, coverage_pct=chosen_pct, max_pages_pct=chosen_pct)- return chosen_pct, plans, est, gen_config+def concept_page_count(plans: list[Any]) -> int:+ """The number of concept pages a model writes, for the cost question.++ ``module_page`` is the concept tree; it dominates the bill and is the count+ the question names. ``repo_overview``, ``architecture_diagram`` and+ ``onboarding`` also cost tokens but are few and fixed, so they ride inside+ the dollar estimate rather than the headline count.+ """+ return next((p.count for p in plans if p.page_type == "module_page"), 0)def _enrich_knowledge_graph(diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex 9ccbbacb1..a918b555e 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -65,10 +65,11 @@ from repowise.core.generation.styles import DEFAULT_STYLEfrom ._interactive import offer_distill_rewrite_hook, offer_hook_installfrom .generation import (CostGateDeclined,+ concept_page_count,cost_gate_declined,+ estimate_generation,format_cost,run_repo_generation,- select_coverage,)from .persistence import persist_resultfrom .reporting import show_workspace_completion@@ -88,7 +89,6 @@ def _run_workspace_generation(test_run: bool,reasoning: str = "auto",onboarding: bool = True,- coverage_pct: float | None = None,harvest_decisions: bool = True,wiki_style: str = DEFAULT_STYLE,language: str = "en",@@ -110,25 +110,26 @@ def _run_workspace_generation(wiki_style=wiki_style,language=language,)- chosen_pct, _plans, est, gen_config = select_coverage(+ plans, est = estimate_generation(result=result,gen_config=gen_config,provider=provider,repo_path=repo_path,skip_tests=skip_tests,skip_infra=skip_infra,- coverage_pct=coverage_pct,- yes=yes,)console.print(- f" Coverage: {int(chosen_pct * 100)}% / "- f"~{est.estimated_input_tokens + est.estimated_output_tokens:,} tokens "- f"({format_cost(est)}, {est.total_pages} pages)"+ f" Writing {concept_page_count(plans)} concept pages with "+ f"{provider.model_name}. {format_cost(est)} ({est.total_pages} pages total).")+ # Declines rather than raises when it cannot ask (see the note in init's+ # _run_generation_phase): a raise would land in the caller's generic error+ # handler and leave this repo with zero pages, instead of the free template+ # wiki the CostGateDeclined sentinel renders.if cost_gate_declined(- est, yes=yes, message=f" Cost for {repo_path.name} exceeds $2.00. Continue?"+ est, yes=yes, message=f" Continue with {repo_path.name} at this cost?"):console.print(" [yellow]Skipped.[/yellow] "@@ -248,7 +249,6 @@ class _WorkspaceCtx:yes: boolresume: boolonboarding: bool- coverage_pct: float | Noneharvest_decisions: boolwiki_style: strlanguage: str@@ -385,7 +385,6 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCttest_run=ctx.test_run,reasoning=ctx.resolved_reasoning,onboarding=ctx.onboarding,- coverage_pct=ctx.coverage_pct,harvest_decisions=ctx.harvest_decisions,wiki_style=ctx.wiki_style,language=ctx.language,@@ -545,7 +544,6 @@ def _workspace_init(resume: bool = False,force: bool = False,onboarding: bool = True,- coverage_pct: float | None = None,harvest_decisions: bool = True,wiki_style: str = DEFAULT_STYLE,language: str | None = None,@@ -733,7 +731,6 @@ def _workspace_init(yes=yes,resume=resume,onboarding=onboarding,- coverage_pct=coverage_pct,harvest_decisions=harvest_decisions,wiki_style=wiki_style,language=language or "en",diff --git a/packages/cli/src/repowise/cli/commands/restyle_cmd.py b/packages/cli/src/repowise/cli/commands/restyle_cmd.pyindex 64d7b2845..d8f9225ed 100644--- a/packages/cli/src/repowise/cli/commands/restyle_cmd.py+++ b/packages/cli/src/repowise/cli/commands/restyle_cmd.py@@ -206,11 +206,12 @@ def restyle_command("Run `repowise update --full` to generate docs first.")if docs_mode == "deterministic":- # A template wiki is a legitimate starting point, not a dead end:- # restyling it is how a user upgrades to model-written pages.+ # A wiki with no written prose is a fine starting point: restyle writes+ # the subsystem pages with a model in the chosen style, the same work+ # `generate --all` does with a style override.console.print(- "[yellow]This repo's wiki was rendered from templates.[/yellow] "- "Restyling rewrites every page with a model, which costs money."+ "[yellow]This repo's wiki has no written prose yet.[/yellow] "+ "Restyling writes the subsystem pages with a model, which costs money.")if style == current:diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.pyindex 8f5af8ebc..6e4a5aacf 100644--- a/packages/cli/src/repowise/cli/commands/status_cmd.py+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py@@ -296,14 +296,14 @@ def _workspace_status(target: CommandTarget) -> None:storage_cell = format_bytes(_index_storage_bytes(repowise_dir))docs_mode = resolve_docs_mode(load_state(abs_path))- # Render the Docs column in plain English so the user instantly knows- # both whether a wiki exists and whether a model wrote it. A template- # wiki is complete but thinner, and `restyle` upgrades it.+ # One axis in the Docs column: every wiki is complete, and the only+ # question is whether the subsystem pages carry written prose or are+ # still stubs. `repowise generate` writes the stubs.if page_count > 0:if docs_mode == "deterministic":- docs_cell = f"[cyan]{page_count} Template[/cyan]"+ docs_cell = f"[cyan]{page_count} · stubs[/cyan]"else:- docs_cell = f"[green]{page_count} LLM[/green]"+ docs_cell = f"[green]{page_count} · prose[/green]"elif docs_mode == "none":docs_cell = "[yellow]None[/yellow]"no_docs.append(entry.alias)diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 810ce8bc6..13d75d928 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -253,9 +253,9 @@ def _surface_release_news(*, written_by: str | None) -> None:default=False,help=("Upgrade an index with a model: backfill the git tier ESSENTIAL -> "- "FULL if it was built with `--mode fast`, and write the pages with a "- "provider, replacing a template wiki from `--index-only`. Incremental: "- "reuses the persisted graph instead of re-parsing and re-resolving it. "+ "FULL if it was built with `--mode fast`, and write the subsystem pages "+ "with a provider on a wiki that has none yet. Incremental: reuses the "+ "persisted graph instead of re-parsing and re-resolving it. ""Single-repo only."),)@@ -1006,23 +1006,19 @@ def run_update(if docs_mode == "deterministic":from .deterministic import (load_prior_page_ids,- partition_regenerate_by_provenance,persist_deterministic_pages,regenerate_deterministic_pages,- regenerate_model_pages,)if emitter is not None:emitter.stage("generate")prior_ids = load_prior_page_ids(repo_path)- # Per-page re-render mode: a page a user upgraded to model prose must- # not silently revert to a template. Template pages re-render for- # free; model-written pages stay model-written.- template_paths, model_paths = partition_regenerate_by_provenance(- repo_path, affected.regenerate- )-+ # Every file page is structural, so the changed files' pages+ # re-render from templates for free. There is no model bucket to+ # keep separate: a file page can no longer be model-written, so a+ # page that predates the single-renderer change re-renders to its+ # structural form here, which is the shape it now has.det_pages = regenerate_deterministic_pages(repo_path=repo_path,parsed_files=parsed_files,@@ -1030,7 +1026,7 @@ def run_update(graph_builder=graph_builder,repo_structure=repo_structure,git_meta_map=git_meta_map,- regenerate_paths=template_paths,+ regenerate_paths=affected.regenerate,cfg=cfg,concurrency=concurrency,degraded=degraded,@@ -1038,92 +1034,21 @@ def run_update(prior_page_ids=prior_ids,)- # Model-written pages: re-render with the model when one resolves- # (D6 wrote the key into .repowise/.env, so an index-only repo whose- # pages were upgraded now has a provider). With no provider, keep the- # existing LLM content and mark it stale — never revert to a template.- model_pages: list = []- stale_model_paths: list[str] = []- if model_paths:- model_provider = None- try:- from repowise.cli.helpers import resolve_provider-- model_provider = resolve_provider(provider_name, model, repo_path=repo_path)- except Exception:- model_provider = None-- if model_provider is not None:- from repowise.cli.providers import build_cost_tracker-- tracker = build_cost_tracker(- repo_path, repo_path.name, no_cost_tracking=no_cost_tracking- )- model_provider._cost_tracker = tracker- model_pages = regenerate_model_pages(- repo_path=repo_path,- parsed_files=parsed_files,- source_map=source_map,- graph_builder=graph_builder,- repo_structure=repo_structure,- git_meta_map=git_meta_map,- regenerate_paths=model_paths,- cfg=cfg,- concurrency=concurrency,- degraded=degraded,- provider=model_provider,- dead_code_report=dead_code_report,- prior_page_ids=prior_ids,- )- index_only_cost = float(getattr(tracker, "session_cost", 0.0) or 0.0)- # Any requested model page the render did not actually- # produce is kept and marked stale. generate_all catches a- # per-page provider error and filters that page out of its- # result, so a partial batch (page A rendered, page B errored)- # must not leave B silently fresh-but-outdated — that is the- # exact revert-in-disguise Task 3 prevents. Full failure- # (empty result) falls out of the same computation.- rendered_paths = {- pg.page_id.split("file_page:", 1)[1]- for pg in model_pages- if getattr(pg, "page_id", "").startswith("file_page:")- }- stale_model_paths = [p for p in model_paths if p not in rendered_paths]- else:- stale_model_paths = list(model_paths)- console.print(- " [yellow]![/yellow] "- f"{len(model_paths)} model-written page(s) changed but no "- "provider is configured; keeping them and marking stale. "- "Add a key, then run [bold]repowise generate[/bold]."- )-- all_pages = det_pages + model_pages- if all_pages or stale_model_paths:+ if det_pages:state["total_pages"] = persist_deterministic_pages(repo_path=repo_path,- generated_pages=all_pages,- # decay_only are cascade-reached templates; the kept model- # pages are stale until a provider re-writes them.- decay_paths=[*affected.decay_only, *stale_model_paths],+ generated_pages=det_pages,+ # decay_only are cascade-reached templates the render did not+ # touch: marked stale so the view stays honest about which+ # pages predate this commit.+ decay_paths=affected.decay_only,degraded=degraded,)- # Advance the docs commit only when something was actually- # re-rendered to HEAD; a run that only kept-and-staled model pages- # has not brought the wiki up to HEAD.- if all_pages:- state["last_docs_commit"] = head- if det_pages:- console.print(- f" [green]✓[/green] Re-rendered [bold]{len(det_pages)}[/bold] "- "wiki pages from structure"- )- if model_pages:- console.print(- f" [green]✓[/green] Re-wrote [bold]{len(model_pages)}[/bold] "- "upgraded page(s) with the model"- )- det_pages = all_pages+ state["last_docs_commit"] = head+ console.print(+ f" [green]✓[/green] Re-rendered [bold]{len(det_pages)}[/bold] "+ "wiki pages from structure"+ )if emitter is not None:emitter.stage("persist")try:diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.pyindex a6191db16..3758d55e7 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py@@ -74,56 +74,6 @@ async def _load_prior_page_ids(repo_path: Path) -> dict:await engine.dispose()-def partition_regenerate_by_provenance(- repo_path: Path, regenerate_paths: list[str]-) -> tuple[list[str], list[str]]:- """Split changed file paths into (template, model_written) by existing page.-- A page a user upgraded to model prose must not silently revert to a template- on the next update. The re-render mode is therefore per-page, read from the- existing ``file_page:<path>`` provenance: ``provider_name == "template"`` (or- no page yet) stays a template; anything else was model-written and is kept so.- Order within each bucket follows ``regenerate_paths``. Never raises — on a- lookup failure every path is treated as model-written, so the free template- render can never overwrite (revert) a page whose provenance we could not read.- A provider then re-renders them; without one the caller keeps and marks them- stale. Erring toward "keep" is the safe direction for the Task 3 guarantee.- """- if not regenerate_paths:- return [], []- try:- model_paths = run_async(_load_model_written_paths(repo_path, regenerate_paths))- except Exception:- return [], list(regenerate_paths)- template = [p for p in regenerate_paths if p not in model_paths]- model = [p for p in regenerate_paths if p in model_paths]- return template, model---async def _load_model_written_paths(repo_path: Path, paths: list[str]) -> set[str]:- from repowise.cli.helpers import get_db_url_for_repo- from repowise.core.persistence import create_engine, create_session_factory, get_session-- engine = create_engine(get_db_url_for_repo(repo_path))- try:- from sqlalchemy import select as sa_select-- from repowise.core.persistence.models import Page-- wanted = {f"file_page:{p}": p for p in paths}- async with get_session(create_session_factory(engine)) as session:- rows = await session.execute(- sa_select(Page.id, Page.provider_name).where(Page.id.in_(list(wanted)))- )- return {- wanted[pid]- for pid, provider_name in rows- if provider_name and provider_name != "template"- }- finally:- await engine.dispose()--def regenerate_deterministic_pages(*,repo_path: Path,@@ -163,54 +113,10 @@ def regenerate_deterministic_pages(degraded=degraded,dead_code_report=dead_code_report,prior_page_ids=prior_page_ids,- provider=None,degrade_label="Template page refresh",)-def regenerate_model_pages(- *,- repo_path: Path,- parsed_files: list,- source_map: dict,- graph_builder: Any,- repo_structure: Any,- git_meta_map: dict,- regenerate_paths: list[str],- cfg: dict,- concurrency: int,- degraded: list[str],- provider: Any,- dead_code_report: Any = None,- prior_page_ids: dict | None = None,-) -> list:- """Re-render *regenerate_paths* with a real model, keeping them model-written.-- The sibling of :func:`regenerate_deterministic_pages` for the pages a user- upgraded away from templates on an otherwise index-only repo. Scoped by- ``only_page_ids`` so the budget can't ration them down: exactly the requested- file pages render, from the same complete view. Never raises — a model- failure degrades the run, and the caller keeps the existing content and marks- those pages stale rather than reverting them.- """- return _render_pages(- repo_path=repo_path,- parsed_files=parsed_files,- source_map=source_map,- graph_builder=graph_builder,- repo_structure=repo_structure,- git_meta_map=git_meta_map,- regenerate_paths=regenerate_paths,- cfg=cfg,- concurrency=concurrency,- degraded=degraded,- dead_code_report=dead_code_report,- prior_page_ids=prior_page_ids,- provider=provider,- degrade_label="Model page refresh",- )--def _render_pages(*,repo_path: Path,@@ -225,14 +131,12 @@ def _render_pages(degraded: list[str],dead_code_report: Any,prior_page_ids: dict | None,- provider: Any,degrade_label: str,) -> list:- """Shared render body for the template and model paths.+ """Render the changed files' pages from structure (free, no LLM).- ``provider=None`` renders from templates (free, no LLM); a provider renders- the file pages with the model, scoped to exactly ``regenerate_paths`` via- ``only_page_ids`` so the coverage budget cannot drop any of them.+ Every file page is structural now, so there is one render mode: the template+ renderer, driven by ``deterministic=True``. There is no model path to choose."""from repowise.core.generation import ContextAssembler, GenerationConfig, PageGeneratorfrom repowise.core.providers.llm.template import TemplateProvider@@ -243,10 +147,9 @@ def _render_pages(if not affected_parsed:return []- is_template = provider is Nonetry:config = GenerationConfig(- deterministic=is_template,+ deterministic=True,file_pages_only=True,max_concurrency=concurrency,language=cfg.get("language", "en"),@@ -272,7 +175,7 @@ def _render_pages(degraded.append(f"Page embedding: {exc}")generator = PageGenerator(- provider if provider is not None else TemplateProvider(),+ TemplateProvider(),ContextAssembler(config),config,vector_store=vector_store,@@ -284,16 +187,9 @@ def _render_pages(prior_pages=prior_page_ids or {},repo_path=repo_path,)- # A model render targets exactly the requested file pages so the coverage- # budget can't ration them; a template render takes every page it is fed- # (deterministic mode bypasses the budget already).- only_page_ids = None if is_template else {f"file_page:{p}" for p in regenerate_paths}- status_msg = (- " Re-rendering wiki pages from structure…"- if is_template- else " Re-writing upgraded pages with the model…"- )- with console.status(status_msg):+ # A template render takes every page it is fed; deterministic mode+ # bypasses the budget already, so no page-id scoping is needed.+ with console.status(" Re-rendering wiki pages from structure…"):return run_async(generator.generate_all(affected_parsed,@@ -304,7 +200,7 @@ def _render_pages(git_meta_map=git_meta_map,repo_path=repo_path,dead_code_report=dead_code_report,- only_page_ids=only_page_ids,+ only_page_ids=None,))except Exception as exc:diff --git a/packages/cli/src/repowise/cli/cost_estimator/__init__.py b/packages/cli/src/repowise/cli/cost_estimator/__init__.pyindex 8d69a28da..e5c49d993 100644--- a/packages/cli/src/repowise/cli/cost_estimator/__init__.py+++ b/packages/cli/src/repowise/cli/cost_estimator/__init__.py@@ -7,27 +7,19 @@ working for existing callers."""from repowise.core.cost_estimator import (- DEFAULT_COVERAGE_OPTIONS,- RECOMMENDED_COVERAGE,CostEstimate,CostRange,- CoverageOption,PageTypePlan,_lookup_cost,build_generation_plan,- compute_coverage_options,estimate_cost,)__all__ = [- "DEFAULT_COVERAGE_OPTIONS",- "RECOMMENDED_COVERAGE","CostEstimate","CostRange",- "CoverageOption","PageTypePlan","_lookup_cost","build_generation_plan",- "compute_coverage_options","estimate_cost",]diff --git a/packages/cli/src/repowise/cli/cost_gate.py b/packages/cli/src/repowise/cli/cost_gate.pyindex de0db226f..a24f9e80a 100644--- a/packages/cli/src/repowise/cli/cost_gate.py+++ b/packages/cli/src/repowise/cli/cost_gate.py@@ -57,22 +57,28 @@ def confirm_cost_gate(message: str, *, estimated_usd: float | None = None) -> boand the expensive one at the same time.Declining is not a dead end and the prompt now says so: the caller- renders the wiki from templates instead, so No costs the user their- model pages, not their wiki.+ renders the wiki from structure instead, so No costs the user the written+ prose on the subsystem pages, not their wiki.Never prompts when stdin is not a terminal. There is nothing to read- there, and ``click.confirm`` would raise ``Abort`` and throw away an- index that is already built — which is the whole run, minutes of it.+ there, and ``click.confirm`` would raise ``Abort``. Callers reach this+ only after :func:`cost_gate_blocks` has already ruled out the no-terminal+ case (it raises an actionable error there instead), so this branch is a+ backstop for a direct caller rather than the main path."""console.line()console.rule(style="yellow")console.print(" [dim]No builds the same wiki from structure instead: no model, "- "no spend. You can upgrade it later with [bold]repowise update "- "--full[/bold].[/dim]"+ "no spend. Add a key and run [bold]repowise generate[/bold] to write "+ "the subsystem pages later.[/dim]")if not sys.stdin.isatty():- console.print(" [dim]Not a terminal, so nothing to ask: building from structure.[/dim]")+ console.print(+ " [dim]Not a terminal, so nothing to ask: building from structure. "+ "Re-run with --yes to accept the cost and write the subsystem pages "+ "with a model.[/dim]"+ )return Falsedefault = Trueif estimated_usd is not None and estimated_usd > COST_GATE_HARD_USD:@@ -88,10 +94,37 @@ 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``.+ was not passed; a declined prompt yields ``True``. Prefer+ :func:`cost_gate_blocks`, which additionally handles the no-terminal case.+ """+ if est.estimated_cost_usd <= COST_GATE_USD or yes:+ return False+ return not confirm_cost_gate(message, estimated_usd=est.estimated_cost_usd)+++def cost_gate_blocks(est: Any, *, yes: bool, message: str) -> bool:+ """Return ``True`` when the run must not spend, ``False`` to proceed.++ The single cost question, shared by ``init``, ``generate`` and+ ``update --full``. Its non-interactive contract is the one an agent depends+ on:++ - ``--yes``, or an estimate at or under :data:`COST_GATE_USD`: never blocks.+ A cheap run the user configured is not worth an interruption.+ - Over the gate with no terminal to confirm on and no ``--yes``: raises an+ actionable error naming ``--yes``, rather than hanging on a prompt nothing+ will answer or silently spending money no one approved.+ - Over the gate on a terminal: asks (default yes, flipping past+ :data:`COST_GATE_HARD_USD`) and blocks when the user declines."""if est.estimated_cost_usd <= COST_GATE_USD or yes:return False+ if not sys.stdin.isatty():+ raise click.ClickException(+ f"This would spend about {format_cost(est)} and there is no terminal "+ "to confirm on. Re-run with --yes to accept the cost, or with "+ "--index-only to build the wiki from structure for free."+ )return not confirm_cost_gate(message, estimated_usd=est.estimated_cost_usd)diff --git a/packages/cli/src/repowise/cli/coverage_select.py b/packages/cli/src/repowise/cli/coverage_select.pydeleted file mode 100644index 21ea63600..000000000--- a/packages/cli/src/repowise/cli/coverage_select.py+++ /dev/null@@ -1,115 +0,0 @@-"""Interactive coverage-level chooser for ``repowise init``.--After ingestion completes but before the LLM run, the user picks how-thoroughly to document the repo. Counts are computed from the actual-ingestion result — not hard-coded heuristics — so the displayed-"pages at this level" always matches what generation will emit.-"""--from __future__ import annotations--from rich.console import Console-from rich.prompt import Prompt-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.-_DISPLAY_COLUMNS: tuple[tuple[str, str], ...] = (- ("file_page", "File"),- ("symbol_spotlight", "Sym"),- ("module_page", "Mod"),- ("api_contract", "API"),- ("infra_page", "Infra"),- ("scc_page", "SCC"),- ("onboarding", "Onb"),-)---def _format_pct(option: CoverageOption) -> str:- # ``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---def _format_cost(option: CoverageOption) -> str:- est = option.estimate- if est.cost_range is None:- return f"${est.estimated_cost_usd:.2f}"- return f"${est.cost_range.low:.2f}-${est.cost_range.high:.2f}"---def render_coverage_table(options: list[CoverageOption]) -> Table:- """Build the Rich table shown to the user."""- table = Table(- title="[bold]Documentation coverage[/bold]",- title_style="",- border_style=BRAND,- padding=(0, 1),- )- table.add_column("#", style=BRAND_STYLE, width=4)- table.add_column("Coverage", style="bold")- table.add_column("Pages", justify="right")- for _, header in _DISPLAY_COLUMNS:- table.add_column(header, justify="right")- table.add_column("Est. cost", justify="right")-- for idx, opt in enumerate(options, start=1):- row = [- f"[{idx}]",- _format_pct(opt),- str(opt.estimate.total_pages),- ]- for page_type, _ in _DISPLAY_COLUMNS:- row.append(str(opt.page_count_for(page_type)))- row.append(_format_cost(opt))- table.add_row(*row)-- return table---def interactive_coverage_select(- console: Console,- options: list[CoverageOption],- *,- deterministic_tail: bool = False,-) -> CoverageOption:- """Render the coverage table and prompt the user for a choice.-- Returns the selected :class:`CoverageOption`. The default is the- one whose ``is_recommended`` flag is set, falling back to the- middle of the list when none is flagged.-- ``deterministic_tail`` notes that files outside the chosen coverage still- get a free, no-LLM page (so the table's counts are not the whole story).- """- if not options:- msg = "No coverage options provided"- raise ValueError(msg)-- console.print(render_coverage_table(options))- if deterministic_tail:- console.print(- " [dim]Every file outside this coverage still gets a free, no-LLM "- "deterministic page, so search can find all of your code.[/dim]"- )-- # Pick the default = recommended option's index, else the median.- default_idx = next(- (i for i, o in enumerate(options, start=1) if o.is_recommended),- len(options) // 2 + 1,- )-- choice = Prompt.ask(- " Select coverage",- choices=[str(i) for i in range(1, len(options) + 1)],- default=str(default_idx),- console=console,- )- return options[int(choice) - 1]diff --git a/packages/cli/src/repowise/cli/ui/mode_selection.py b/packages/cli/src/repowise/cli/ui/mode_selection.pyindex e0742ed61..6a4ff7d64 100644--- a/packages/cli/src/repowise/cli/ui/mode_selection.py+++ b/packages/cli/src/repowise/cli/ui/mode_selection.py@@ -78,11 +78,11 @@ def interactive_mode_select(console: Console) -> str:body.append(" health, decisions + AI-generated wiki, diagrams & API docs.\n\n")body.append(" [2]", style=BRAND_STYLE)- body.append(" Index only ", style="bold")+ body.append(" No prose ", style="bold")body.append("(no key, no spend)\n", style="dim")- body.append(" Same layers, and a complete wiki rendered from the code's\n")- body.append(" structure instead of written by a model. Upgrade it to\n")- body.append(" model-written prose later with update --full.\n\n")+ body.append(" The same complete wiki, rendered from the code's structure.\n")+ body.append(" The subsystem pages read as stubs rather than written prose;\n")+ body.append(" add a key and run repowise generate to write them.\n\n")body.append(" [3]", style=BRAND_STYLE)body.append(" Advanced\n", style="bold")@@ -571,10 +571,10 @@ def print_index_only_intro(console: Console, has_provider: bool = False) -> Nonelines.append("")lines.append(" [dim]No LLM calls. No API key. No cost.[/dim]")lines.append(- " [dim]Every page says it was derived from structure. Run "- "[bold]repowise update --full[/bold][/dim]"+ " [dim]The subsystem pages read as stubs. Add a key and run "+ "[bold]repowise generate[/bold][/dim]")- lines.append(" [dim]later to rewrite the wiki with a model.[/dim]")+ lines.append(" [dim]to write them as prose.[/dim]")console.print(Panel(diff --git a/packages/core/src/repowise/core/cost_estimator/__init__.py b/packages/core/src/repowise/core/cost_estimator/__init__.pyindex f748b5df1..8d4c54359 100644--- a/packages/core/src/repowise/core/cost_estimator/__init__.py+++ b/packages/core/src/repowise/core/cost_estimator/__init__.py@@ -13,12 +13,6 @@ Public API kept stable for existing callers:"""from .approx import approximate_generation_plan-from .coverage import (- DEFAULT_COVERAGE_OPTIONS,- RECOMMENDED_COVERAGE,- CoverageOption,- compute_coverage_options,-)from .estimator import estimate_costfrom .plans import build_generation_planfrom .pricing import _lookup_cost@@ -27,13 +21,9 @@ from .types import CostEstimate, CostRange, PageTypePlan__all__ = ["CostEstimate","CostRange",- "CoverageOption",- "DEFAULT_COVERAGE_OPTIONS","PageTypePlan",- "RECOMMENDED_COVERAGE","_lookup_cost","approximate_generation_plan","build_generation_plan",- "compute_coverage_options","estimate_cost",]diff --git a/packages/core/src/repowise/core/cost_estimator/coverage.py b/packages/core/src/repowise/core/cost_estimator/coverage.pydeleted file mode 100644index a6e503464..000000000--- a/packages/core/src/repowise/core/cost_estimator/coverage.py+++ /dev/null@@ -1,87 +0,0 @@-"""Coverage-option enumeration for the init UI.--The init flow asks the user to pick how thoroughly to document the-repo. This module computes the per-coverage page counts + cost-estimates that the UI renders, by calling :func:`build_generation_plan`-once per offered percentage.--Cheap — no LLM calls, just the deterministic selection function.-"""--from __future__ import annotations--from dataclasses import dataclass-from pathlib import Path-from typing import Any--from .estimator import estimate_cost-from .plans import build_generation_plan-from .types import CostEstimate, PageTypePlan---# Coverage percentages presented in the init UI. The 20% slot is the-# recommended default — fewer than 10% loses key concepts; more than-# 50% starts paying for diminishing-return file pages.-DEFAULT_COVERAGE_OPTIONS: tuple[float, ...] = (0.10, 0.15, 0.20, 0.30, 0.40, 0.50)-RECOMMENDED_COVERAGE: float = 0.20---@dataclass-class CoverageOption:- """One row in the init-flow coverage table."""-- pct: float- plans: list[PageTypePlan]- estimate: CostEstimate- is_recommended: bool-- def page_count_for(self, page_type: str) -> int:- for plan in self.plans:- if plan.page_type == page_type:- return plan.count- return 0---def compute_coverage_options(- *,- parsed_files: list[Any],- graph_builder: Any,- base_config: Any,- provider_name: str,- model_name: str,- repo_path: Path | str | None = None,- skip_tests: bool = False,- skip_infra: bool = False,- kg_modules: list[dict] | None = None,- percentages: tuple[float, ...] = DEFAULT_COVERAGE_OPTIONS,- recommended: float = RECOMMENDED_COVERAGE,-) -> list[CoverageOption]:- """Return one :class:`CoverageOption` per requested percentage.-- ``base_config`` is cloned per percentage so this never mutates the- caller's object.- """- from dataclasses import replace-- options: list[CoverageOption] = []- for pct in percentages:- cfg = replace(base_config, coverage_pct=pct, max_pages_pct=pct)- plans = build_generation_plan(- parsed_files, graph_builder, cfg, skip_tests, skip_infra,- kg_modules=kg_modules,- )- est = estimate_cost(- plans,- provider_name,- model_name,- repo_path=repo_path,- )- options.append(- CoverageOption(- pct=pct,- plans=plans,- estimate=est,- is_recommended=abs(pct - recommended) < 1e-9,- )- )- return optionsdiff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.pyindex 310cb4f34..483e4a83f 100644--- a/tests/integration/test_cli.py+++ b/tests/integration/test_cli.py@@ -667,11 +667,11 @@ class TestInitSeedFrom:monkeypatch.delenv("REPOWISE_DB_URL", raising=False)- # Full doc coverage so the new file is not tier-gated out of a page;- # the copied config carries the setting into the delegated update.+ # Every file gets a structural page now, so no coverage knob is needed+ # to keep the new file from being tier-gated out.r0 = CliRunner().invoke(cli,- ["init", str(git_work_repo), "--provider", "mock", "--coverage", "1.0", "--yes"],+ ["init", str(git_work_repo), "--provider", "mock", "--yes"],catch_exceptions=False,)assert r0.exit_code == 0, r0.outputdiff --git a/tests/integration/test_generation_pipeline.py b/tests/integration/test_generation_pipeline.pyindex 0c7532402..caef021db 100644--- a/tests/integration/test_generation_pipeline.py+++ b/tests/integration/test_generation_pipeline.py@@ -257,8 +257,8 @@ async def test_embedding_latency_does_not_gate_llm_concurrency():embed_concurrency=1,file_page_top_percentile=1.0,top_symbol_percentile=0.01,- # The selection layer drives off coverage_pct; max_pages_pct is- # the deprecated alias kept for backwards compatibility.+ # coverage_pct / max_pages_pct are inert: selection no longer rations by+ # coverage. Set here only to exercise the config round-trip.coverage_pct=1.0,max_pages_pct=1.0,cache_enabled=False,diff --git a/tests/unit/cli/test_generate_chooser.py b/tests/unit/cli/test_generate_chooser.pyindex 7cd1d3ef3..a04af5b31 100644--- a/tests/unit/cli/test_generate_chooser.py+++ b/tests/unit/cli/test_generate_chooser.py@@ -2,16 +2,32 @@from __future__ import annotations-from repowise.cli.commands.generate_cmd import chooser as chooser_mod+import click+import pytest+from repowise.cli.commands.generate_cmd.chooser import (choose_cascade,print_wiki_state,run_interactive_chooser,)+from repowise.cli.commands.generate_cmd.command import _reject_structural_page_idsfrom repowise.core.generation.cascade import build_page_dependenciesfrom repowise.core.generation.page_selection import PageRecord+def test_reject_structural_page_ids_errors_on_file_page():+ # A file page is rendered from structure; naming it for `generate` is a clear+ # error, not a silent no-op.+ with pytest.raises(click.ClickException) as exc:+ _reject_structural_page_ids(("module_page:src/api", "file_page:src/app.py"))+ assert "file_page:src/app.py" in str(exc.value)+++def test_reject_structural_page_ids_allows_concept_pages():+ # Model-written page types pass through untouched.+ _reject_structural_page_ids(("module_page:src/api", "repo_overview:demo"))++class _RecordingConsole:"""Captures print calls; asserts the prompt is never reached."""@@ -57,92 +73,52 @@ def test_choose_cascade_prompts_when_modes_diverge(monkeypatch) -> None:asked["default"] = defaultreturn "2" # pick "dependents"- monkeypatch.setattr(- "repowise.cli.commands.generate_cmd.chooser.Prompt.ask", fake_ask- )+ 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,- )+ return run_interactive_chooser(_RecordingConsole(), records=records, deps=deps)-def test_run_interactive_chooser_returns_scope(monkeypatch) -> None:- records = [PageRecord("file_page:a.py", "file_page", "a.py", is_template=True)]+def test_run_interactive_chooser_returns_cascade_when_unwritten() -> None:+ records = [PageRecord("module_page:src", "module_page", "src", 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+ # No containers/repo-wide, so cascade cannot change the outcome; the default+ # ("dependents") comes back without prompting.+ assert choice.cascade_mode == "dependents"-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)]+def test_run_interactive_chooser_bails_when_nothing_unwritten() -> None:+ records = [PageRecord("module_page:src", "module_page", "src", is_template=False)]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())+ # Guard fires before the cascade step: every page is already written.assert _run(records, deps) is None-def test_print_wiki_state_counts_by_provenance() -> None:+def test_print_wiki_state_counts_concept_layer_only() -> None:+ # Only model-written page types are counted; the file page is structural and+ # is excluded from the written/unwritten split but still counts toward the+ # wiki total.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"),+ PageRecord("a", "module_page", "src/a", is_template=True),+ PageRecord("b", "module_page", "src/b", is_template=False),+ PageRecord("c", "module_page", "src/c", is_template=True, freshness_status="stale"),+ PageRecord("d", "file_page", "d.py", is_template=True),]console = _RecordingConsole()print_wiki_state(console, records)line = console.lines[0]- assert "3 pages" in line+ assert "3 of 4 wiki pages" in lineassert "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 linediff --git a/tests/unit/cli/test_init_noninteractive.py b/tests/unit/cli/test_init_noninteractive.pyindex 0bc687f79..ae04e63be 100644--- a/tests/unit/cli/test_init_noninteractive.py+++ b/tests/unit/cli/test_init_noninteractive.py@@ -83,6 +83,34 @@ class TestCostGate:assert seen["default"] is False+class TestCostGateBlocks:+ """The single cost question shared by init, generate and update --full.++ This is the agent path: a piped run with no --yes must proceed under the+ gate and raise an actionable error over it, never hang.+ """++ def test_under_gate_proceeds(self, monkeypatch):+ monkeypatch.setattr(sys.stdin, "isatty", lambda: False, raising=False)+ assert cost_gate.cost_gate_blocks(_est(0.10), yes=False, message="m") is False++ def test_yes_proceeds_over_gate(self, monkeypatch):+ monkeypatch.setattr(sys.stdin, "isatty", lambda: False, raising=False)+ assert cost_gate.cost_gate_blocks(_est(999.0), yes=True, message="m") is False++ def test_non_tty_over_gate_raises_naming_yes(self, monkeypatch):+ """No terminal + over the gate + no --yes is an actionable error, not a hang."""+ monkeypatch.setattr(sys.stdin, "isatty", lambda: False, raising=False)+ with pytest.raises(click.ClickException) as exc:+ cost_gate.cost_gate_blocks(_est(50.0), yes=False, message="m")+ assert "--yes" in str(exc.value)++ def test_tty_over_gate_asks_and_blocks_on_decline(self, monkeypatch):+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False)+ monkeypatch.setattr(click, "confirm", lambda *_a, **_k: False)+ assert cost_gate.cost_gate_blocks(_est(50.0), yes=False, message="m") is True++class TestHookOfferDegrades:def test_eof_on_hook_offer_does_not_raise(self, monkeypatch, tmp_path):"""A finished run must not fail on an optional trailing question."""@@ -135,3 +163,42 @@ class TestDocsFlag:"""An unknown value is rejected by Click rather than reaching the pipeline."""result = runner.invoke(cli, ["init", str(tmp_path), "--docs", "magic"])assert result.exit_code == 2+++class TestProseFlag:+ @pytest.fixture+ def runner(self) -> CliRunner:+ return CliRunner()++ @pytest.fixture+ def keyless_env(self, monkeypatch):+ for var in (+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY",+ "OPENROUTER_API_KEY",+ "DEEPSEEK_API_KEY",+ "KIMI_API_KEY",+ "GOOGLE_API_KEY",+ "GEMINI_API_KEY",+ "OLLAMA_BASE_URL",+ "LITELLM_API_KEY",+ "REPOWISE_PROVIDER",+ ):+ monkeypatch.delenv(var, raising=False)++ def test_no_prose_needs_no_key(self, runner, tmp_path, keyless_env):+ """`--no-prose` is the current spelling of --index-only: a free wiki."""+ result = runner.invoke(cli, ["init", str(tmp_path), "--no-prose", "--yes"])+ assert result.exit_code == 0, result.output++ def test_index_only_prints_deprecation(self, runner, tmp_path, keyless_env):+ """The deprecated alias still works and says so."""+ result = runner.invoke(cli, ["init", str(tmp_path), "--index-only", "--yes"])+ assert result.exit_code == 0, result.output+ assert "deprecated" in result.output.lower()++ def test_prose_and_no_prose_conflict(self, runner, tmp_path):+ """--prose contradicting the --index-only alias is a usage error."""+ result = runner.invoke(cli, ["init", str(tmp_path), "--prose", "--index-only"])+ assert result.exit_code == 2+ assert "contradicts" in result.outputdiff --git a/tests/unit/cli/test_restyle_cmd.py b/tests/unit/cli/test_restyle_cmd.pyindex a19e85f6c..eeff2a8c2 100644--- a/tests/unit/cli/test_restyle_cmd.py+++ b/tests/unit/cli/test_restyle_cmd.py@@ -99,12 +99,12 @@ def test_restyle_refuses_repo_with_no_pages(tmp_path):assert "no wiki pages to restyle" in result.output-def test_restyle_warns_but_does_not_refuse_on_template_wiki(tmp_path):- # Restyling a template wiki is the supported upgrade to model-written- # pages, so the guard must let it through after saying what it will cost.+def test_restyle_warns_but_does_not_refuse_on_stub_wiki(tmp_path):+ # Restyling a wiki with no written prose writes the subsystem pages in the+ # chosen style, so the guard must let it through after saying what it costs._write_state(tmp_path, {"docs_mode": "deterministic", "last_sync_commit": "abc"})result = CliRunner().invoke(cli, ["restyle", "caveman", str(tmp_path), "--yes"])- assert "rendered from templates" in result.output+ assert "no written prose yet" in result.outputassert "no wiki pages to restyle" not in result.outputdiff --git a/tests/unit/cli/test_update_provenance_partition.py b/tests/unit/cli/test_update_provenance_partition.pydeleted file mode 100644index 344393352..000000000--- a/tests/unit/cli/test_update_provenance_partition.py+++ /dev/null@@ -1,134 +0,0 @@-"""Per-page re-render mode on an index-only update.--A page a user upgraded to model prose must not silently revert to a template on-the next `repowise update`. `partition_regenerate_by_provenance` is the split-that keeps that promise: it reads each changed file's existing page provenance-and routes template pages to the free template render and model-written pages to-the model render.-"""--from __future__ import annotations--from datetime import UTC, datetime--import pytest--from repowise.cli.commands.update_cmd.deterministic import (- partition_regenerate_by_provenance,-)-from repowise.core.generation.models import GeneratedPage-from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,- upsert_pages_from_generated,- upsert_repository,-)---def _page(path: str, provider_name: str) -> GeneratedPage:- now = datetime.now(UTC).isoformat()- return GeneratedPage(- page_id=f"file_page:{path}",- page_type="file_page",- title=path,- content="body",- source_hash=f"hash-{path}",- model_name="template" if provider_name == "template" else "gpt-x",- provider_name=provider_name,- input_tokens=0,- output_tokens=0,- cached_tokens=0,- generation_level=2,- target_path=path,- created_at=now,- updated_at=now,- )---def repo_dir(tmp_path, monkeypatch):- (tmp_path / ".repowise").mkdir(parents=True, exist_ok=True)- db = tmp_path / ".repowise" / "wiki.db"- monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{db.as_posix()}")- return tmp_path---def _seed(repo_dir, pages: list[GeneratedPage]) -> None:- # Seed synchronously (asyncio.run, no running loop): the function under test- # is called from sync CLI code and drives its own loop via ``run_async``, so- # the whole test must stay off the event loop or that call raises.- import asyncio- import os-- async def _do() -> None:- engine = create_engine(os.environ["REPOWISE_DB_URL"])- try:- await init_db(engine)- sf = create_session_factory(engine)- async with get_session(sf) as session:- repo = await upsert_repository(- session, name=repo_dir.name, local_path=str(repo_dir)- )- await upsert_pages_from_generated(session, pages, repo.id)- finally:- await engine.dispose()-- asyncio.run(_do())---def test_splits_template_from_model(repo_dir):- _seed(- repo_dir,- [- _page("a.py", "template"),- _page("b.py", "openai"),- _page("c.py", "template"),- ],- )- template, model = partition_regenerate_by_provenance(- repo_dir, ["a.py", "b.py", "c.py"]- )- assert template == ["a.py", "c.py"]- assert model == ["b.py"]---def test_unknown_path_is_a_template(repo_dir):- # A newly added file has no page yet — it renders as a template (the free,- # safe default), never as a model page we can't afford.- _seed(repo_dir, [_page("a.py", "openai")])- template, model = partition_regenerate_by_provenance(repo_dir, ["a.py", "new.py"])- assert template == ["new.py"]- assert model == ["a.py"]---def test_preserves_input_order(repo_dir):- _seed(repo_dir, [_page("x.py", "openai"), _page("y.py", "template")])- template, model = partition_regenerate_by_provenance(repo_dir, ["y.py", "x.py"])- assert template == ["y.py"]- assert model == ["x.py"]---def test_empty_input_is_two_empty_lists(repo_dir):- assert partition_regenerate_by_provenance(repo_dir, []) == ([], [])---def test_lookup_failure_keeps_pages_never_reverts(tmp_path, monkeypatch):- # When provenance can't be read, every path is treated as model-written so- # the free template render can never overwrite (revert) a page we couldn't- # classify. The caller then re-renders with a provider or keeps + marks stale.- monkeypatch.setenv(- "REPOWISE_DB_URL", f"sqlite+aiosqlite:///{(tmp_path / 'missing.db').as_posix()}"- )-- def _boom(*_a, **_k):- raise RuntimeError("db unavailable")-- monkeypatch.setattr(- "repowise.cli.commands.update_cmd.deterministic._load_model_written_paths",- _boom,- )- template, model = partition_regenerate_by_provenance(tmp_path, ["a.py", "b.py"])- assert template == []- assert model == ["a.py", "b.py"]