Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat: coverage picker for web bulk documentation generation (#994)
Raghav Chamadiyabec96da30702
diff --git a/README.md b/README.mdindex b19d15988..bffddbb96 100644--- a/README.md+++ b/README.md@@ -110,10 +110,14 @@ queryable from the CLI, the MCP tools, and the local dashboard.| **◈ Decisions** | Architectural decisions mined from eight sources, evidence-backed, linked to the graph nodes they govern, connected by supersedes / refines / conflicts_with, tracked for staleness | **★ Captured nowhere else** || **★ Code health** | **25 deterministic markers**, 1 to 10 per file · three signals: defect risk · maintainability · performance · coverage ingestion · concrete refactoring plans (Extract Class / Helper, Move Method, Break Cycle, Split File) · **zero LLM, under 30s** | **★ Defect-validated, with the fix attached** |-Only model-written prose needs an LLM. `repowise init --index-only` builds the-graph, git, decision, and health layers with no API key and no spend, and renders-the whole wiki from the code's structure (seven of the eight decision sources are-deterministic; only the one harvested during doc generation needs a provider).+**The whole wiki is generated with no LLM, then upgraded to model-written prose on+demand.** `repowise init --index-only` builds the graph, git, decision and health+layers and renders every wiki page from your code's structure, with no API key and+no spend. Convert any part of it to LLM-written prose whenever you want, one page,+one directory, or a ranked coverage slice at a time, and pay only for what you pick,+from the CLI or right in the dashboard with the cost shown before you confirm.+(Seven of the eight decision sources are deterministic too; only the one harvested+during doc generation needs a provider.)Full detail on every layer: **[docs/layers/INTELLIGENCE_LAYERS.md →](docs/layers/INTELLIGENCE_LAYERS.md)**diff --git a/packages/api-client/src/types/misc.ts b/packages/api-client/src/types/misc.tsindex bee03a308..afe4f92f6 100644--- a/packages/api-client/src/types/misc.ts+++ b/packages/api-client/src/types/misc.ts@@ -53,15 +53,25 @@ export interface ProviderValidation {export type GenerateCascade = "none" | "dependents" | "full";/** Which pages a generate/estimate call targets. Mirrors the server's- * `GenerateSelectionBody`. */+ * `GenerateSelectionBody`. Two philosophies, kept distinct: explicit (`all` /+ * `unwritten` / `stale` / `page_ids` / `path_prefix`) names the pages; `ranked`+ * writes the most important slice sized by `coverage_pct` (a fraction, 0.2 ==+ * the top 20%, 1.0 == all) or `top_n` (a target page count). The two cannot be+ * combined, and `coverage_pct` / `top_n` are only valid with `kind: "ranked"`. */export interface GenerateSelection {- kind: "all" | "unwritten" | "stale" | "page_ids" | "path_prefix";+ kind: "all" | "unwritten" | "stale" | "page_ids" | "path_prefix" | "ranked";page_ids?: string[];path_prefix?: string;+ /** Ranked only: fraction of importance to cover (0.2 == top 20%, 1.0 == all). */+ coverage_pct?: number;+ /** Ranked only: target number of top pages (mapped to a coverage fraction). */+ top_n?: number;}export interface GenerateRequest {selection?: GenerateSelection;+ /** Omit to take the server default: `none` for a ranked selection,+ * `dependents` for an explicit one. */cascade?: GenerateCascade;style?: string;}diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex b98017603..14b27f661 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -783,9 +783,78 @@ def _build_generate_intent(config: dict) -> Any:if kind == "path_prefix":prefix = sel.get("path_prefix")return PageSelectionIntent(path_globs=(prefix,) if prefix else ())+ if kind == "ranked":+ # The seed comes from build_ranked_seed and short-circuits resolve_scope,+ # so the intent is unused; return an empty one rather than picking a kind.+ return PageSelectionIntent()return PageSelectionIntent(unwritten=True)+def _effective_cascade(config: dict) -> str:+ """Resolve the cascade mode, honoring the same defaults the CLI uses.++ An explicit ``cascade`` in the config always wins. Left unset, a ranked+ coverage selection defaults to ``none`` (the ranked set is already a coherent+ slice) and the legacy single-page alias to ``none``; everything else defaults+ to ``dependents`` (an explicit selection pulls in its container pages).+ """+ explicit = config.get("cascade")+ if explicit:+ return explicit+ sel = config.get("selection") or {}+ if sel.get("kind") == "ranked" or config.get("mode") == "single_page":+ return "none"+ return "dependents"+++def _ranked_coverage_pct(selection: dict, n_files: int) -> float:+ """The coverage fraction a ranked selection resolves to.++ ``coverage_pct`` is used verbatim (a fraction in ``(0, 1]``); ``top_n`` maps+ to ``n / n_files`` so the budget picks about N pages. ``top_n`` is a target,+ not an exact count — per-type floors and always-emitted repo-wide/onboarding+ pages nudge the real number, which the estimate and job report faithfully.+ """+ pct = selection.get("coverage_pct")+ if pct is not None:+ return float(pct)+ top_n = int(selection.get("top_n") or 0)+ return min(1.0, max(0.0, top_n / max(1, n_files)))+++def _resolve_generate_scope(config: dict, rehydrated: Any, gen_config: Any) -> Any:+ """Resolve a generate config + rehydrated repo into a :class:`ScopePlan`.++ The one place a ranked coverage seed is built, so the estimate endpoint and+ the launched job resolve the *identical* page set — the estimate cannot+ under-quote. A ranked selection runs the core ``build_ranked_seed`` (the same+ importance model ``repowise init`` uses at that coverage); everything else+ resolves its intent normally.+ """+ from repowise.core.generation.scope import build_ranked_seed, resolve_scope++ selection = config.get("selection") or {}+ ranked_seed: set[str] | None = None+ if selection.get("kind") == "ranked":+ pct = _ranked_coverage_pct(selection, len(rehydrated.parsed_files))+ ranked_seed = build_ranked_seed(+ parsed_files=rehydrated.parsed_files,+ graph_builder=rehydrated.graph_builder,+ config=gen_config,+ kg_ctx=rehydrated.kg_ctx,+ records=rehydrated.records,+ repo_name=rehydrated.repo_name,+ coverage_pct=pct,+ )+ return resolve_scope(+ records=rehydrated.records,+ intent=_build_generate_intent(config),+ cascade_mode=_effective_cascade(config),+ deps=rehydrated.deps,+ ranked_seed=ranked_seed,+ )++def _build_generation_config(repo_path: Path, config: dict, wiki_style: str) -> Any:"""Build the ``GenerationConfig`` a generate job (or its estimate) runs with.@@ -832,7 +901,6 @@ async def _run_generate_job(generate/persist/heal half is the same code the CLI ``repowise generate``runs, so behaviour matches across the two surfaces."""- from repowise.core.generation.scope import resolve_scopefrom repowise.core.pipeline.scoped_generation import (execute_scoped_generation,rehydrate_repo,@@ -853,18 +921,9 @@ async def _run_generate_job(if rehydrated is None:raise RuntimeError("Repository has no wiki pages yet; run an index first.")- intent = _build_generate_intent(config)- # Explicit selections pull in their container pages by default; the legacy- # single-page alias keeps its historical "just this page" behaviour.- cascade_mode = config.get("cascade") or (- "none" if config.get("mode") == "single_page" else "dependents"- )- plan = resolve_scope(- records=rehydrated.records,- intent=intent,- cascade_mode=cascade_mode,- deps=rehydrated.deps,- )+ # Resolve the scope (ranked seed included) through the shared helper so the+ # job writes exactly what its estimate priced.+ plan = _resolve_generate_scope(config, rehydrated, gen_config)generated_pages: list = []marked_stale = 0diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.pyindex a521f859c..9caea0d5f 100644--- a/packages/server/src/repowise/server/routers/repos.py+++ b/packages/server/src/repowise/server/routers/repos.py@@ -547,23 +547,82 @@ async def full_resync(class GenerateSelectionBody(BaseModel):"""Which pages a generate request targets.- Mirrors the CLI's explicit selection: ``all`` / ``unwritten`` / ``stale``,- an explicit ``page_ids`` list, or every page under a ``path_prefix``.+ Two selection philosophies, kept distinct exactly as the CLI keeps them:++ - **Explicit**: ``all`` / ``unwritten`` / ``stale``, an explicit ``page_ids``+ list, or every page under a ``path_prefix`` — the caller names the pages.+ - **Ranked** (``kind="ranked"``): write the most important slice by the same+ importance model ``repowise init`` uses, sized by ``coverage_pct`` (a+ fraction in ``(0, 1]``; ``1.0`` == everything) or ``top_n`` (a target page+ count, not exact). The two are mutually exclusive.++ The two philosophies cannot be combined; :func:`_validate_generate_selection`+ enforces it with an actionable 400."""- kind: Literal["all", "unwritten", "stale", "page_ids", "path_prefix"] = "unwritten"+ kind: Literal["all", "unwritten", "stale", "page_ids", "path_prefix", "ranked"] = "unwritten"page_ids: list[str] | None = Nonepath_prefix: str | None = None+ # Ranked selection only. ``coverage_pct`` is a fraction (0.2 == the top 20%);+ # ``top_n`` targets ~N pages (mapped to a coverage fraction downstream).+ coverage_pct: float | None = None+ top_n: int | None = Noneclass GenerateRequestBody(BaseModel):- """Body for the generate + estimate endpoints."""+ """Body for the generate + estimate endpoints.++ ``cascade`` is optional: left unset it resolves to ``none`` for a ranked+ selection (the ranked set is already a coherent slice) and ``dependents`` for+ an explicit one, matching the CLI ``generate`` defaults.+ """selection: GenerateSelectionBody = Field(default_factory=GenerateSelectionBody)- cascade: Literal["none", "dependents", "full"] = "dependents"+ cascade: Literal["none", "dependents", "full"] | None = Nonestyle: str | None = None+def _validate_generate_selection(sel: GenerateSelectionBody) -> None:+ """Reject an incoherent selection with an actionable 400.++ Ranked and explicit selection are distinct philosophies (see+ :class:`GenerateSelectionBody`) and may not be mixed; ``coverage_pct`` and+ ``top_n`` are mutually exclusive and belong only to a ranked selection.+ """+ is_ranked = sel.kind == "ranked"+ has_coverage = sel.coverage_pct is not None+ has_top_n = sel.top_n is not None++ if is_ranked:+ if has_coverage == has_top_n:+ raise HTTPException(+ status_code=400,+ detail="A ranked selection needs exactly one of coverage_pct or top_n.",+ )+ if has_coverage and not 0.0 < sel.coverage_pct <= 1.0:+ raise HTTPException(+ status_code=400,+ detail="coverage_pct must be a fraction in (0, 1] (0.2 == the top 20%, 1.0 == all).",+ )+ if has_top_n and sel.top_n <= 0:+ raise HTTPException(+ status_code=400, detail="top_n must be a positive number of pages."+ )+ if sel.page_ids is not None or sel.path_prefix is not None:+ raise HTTPException(+ status_code=400,+ detail="A ranked selection cannot also carry page_ids or path_prefix.",+ )+ elif has_coverage or has_top_n:+ raise HTTPException(+ status_code=400,+ detail=(+ "coverage_pct / top_n rank pages by importance and require "+ 'selection kind "ranked", not "' + sel.kind + '".'+ ),+ )++def _validate_generate_style(style: str | None) -> None:"""Reject an unknown wiki style with a 400 listing the valid ones."""if style is None:@@ -582,6 +641,11 @@ def _generate_job_config(body: GenerateRequestBody) -> dict:selection["page_ids"] = body.selection.page_ids or []elif body.selection.kind == "path_prefix":selection["path_prefix"] = body.selection.path_prefix+ elif body.selection.kind == "ranked":+ if body.selection.coverage_pct is not None:+ selection["coverage_pct"] = body.selection.coverage_pct+ if body.selection.top_n is not None:+ selection["top_n"] = body.selection.top_nconfig: dict = {"mode": "generate", "selection": selection, "cascade": body.cascade}if body.style is not None:config["style"] = body.style@@ -605,6 +669,7 @@ async def generate_pages(if repo is None:raise HTTPException(status_code=404, detail="Repository not found")+ _validate_generate_selection(body.selection)_validate_generate_style(body.style)await _ensure_no_active_job(session, repo_id)@@ -639,17 +704,17 @@ async def generate_estimate(if repo is None:raise HTTPException(status_code=404, detail="Repository not found")+ _validate_generate_selection(body.selection)_validate_generate_style(body.style)repo_path = Path(repo.local_path)- from repowise.core.generation.scope import resolve_scopefrom repowise.core.pipeline.scoped_generation import rehydrate_repofrom repowise.server.job_executor import (- _build_generate_intent,_build_generation_config,_load_state,_repo_exclude_patterns,_repo_wiki_style,+ _resolve_generate_scope,)exclude_patterns = _repo_exclude_patterns(repo, str(repo_path))@@ -701,12 +766,9 @@ async def generate_estimate("note": note,}- plan = resolve_scope(- records=rehydrated.records,- intent=_build_generate_intent(job_config),- cascade_mode=body.cascade,- deps=rehydrated.deps,- )+ # Resolve the exact same scope a launched job would, including a ranked+ # coverage seed, so the estimate's page count and cost never under-quote.+ plan = _resolve_generate_scope(job_config, rehydrated, gen_config)pages_by_type = {p.page_type: p.count for p in plan.cost_plans}total_pages = sum(pages_by_type.values())diff --git a/packages/ui/__tests__/wiki/regenerate-button.test.tsx b/packages/ui/__tests__/wiki/regenerate-button.test.tsxindex 6b93fa38e..24e2d1785 100644--- a/packages/ui/__tests__/wiki/regenerate-button.test.tsx+++ b/packages/ui/__tests__/wiki/regenerate-button.test.tsx@@ -76,4 +76,31 @@ describe("GenerateConfirmDialog (bulk overrides)", () => {const link = screen.getByRole("link", { name: /Add a provider key/ });expect(link).toHaveAttribute("href", "/repos/r1/settings#provider");});++ it("renders a coverage bucket picker (100% as 'All') and fires onCoverageChange", () => {+ const onCoverageChange = vi.fn();+ render(+ <GenerateConfirmDialog+ {...base}+ cascadeScope="selection"+ coverageOptions={[0.1, 0.2, 0.3, 0.5, 1]}+ coveragePct={0.2}+ onCoverageChange={onCoverageChange}+ recommendedCoverage={0.2}+ />,+ );+ // Buckets render, with 1.0 shown as "All".+ expect(screen.getByRole("button", { name: "20%", pressed: true })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "All" })).toBeInTheDocument();+ // The recommended hint mentions the recommended percent.+ expect(screen.getByText(/20% covers the most important pages/)).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "All" }));+ expect(onCoverageChange).toHaveBeenCalledWith(1);+ });++ it("omits the coverage picker for an explicit selection", () => {+ render(<GenerateConfirmDialog {...base} cascadeScope="selection" />);+ expect(screen.queryByText("How much to write")).not.toBeInTheDocument();+ });});diff --git a/packages/ui/src/wiki/regenerate-button.tsx b/packages/ui/src/wiki/regenerate-button.tsxindex 9a0dee2b1..d2ce2ab11 100644--- a/packages/ui/src/wiki/regenerate-button.tsx+++ b/packages/ui/src/wiki/regenerate-button.tsx@@ -159,6 +159,15 @@ export interface GenerateConfirmDialogProps {/** Phrasing of the cascade options: "page" (single-page reader upgrade) or* "selection" (bulk generation). Defaults to "page". */cascadeScope?: "page" | "selection";+ /** Ranked coverage buckets (fractions, e.g. `[0.1, 0.2, 0.3, 0.5, 1]`). When+ * set with `onCoverageChange`, a bucket picker renders above the cascade+ * choice and `1` shows as "All". Omit for an explicit selection. */+ coverageOptions?: number[];+ /** The currently-selected coverage bucket (a fraction). */+ coveragePct?: number;+ onCoverageChange?: (pct: number) => void;+ /** The bucket to flag as recommended (e.g. `0.2`). */+ recommendedCoverage?: number;cascade: RegenerateCascade;onCascadeChange: (next: RegenerateCascade) => void;/** Lazily-fetched estimate for the current cascade. `null` while unknown. */@@ -190,6 +199,10 @@ export function GenerateConfirmDialog({description,confirmLabel,cascadeScope = "page",+ coverageOptions,+ coveragePct,+ onCoverageChange,+ recommendedCoverage,cascade,onCascadeChange,estimate,@@ -205,6 +218,8 @@ export function GenerateConfirmDialog({cascadeScope === "selection" ? CASCADE_OPTIONS_SELECTION : CASCADE_OPTIONS_PAGE;const heading =title ?? (isWrite ? "Write this page with AI" : "Regenerate this page");+ const showCoverage =+ !!coverageOptions && coverageOptions.length > 0 && !!onCoverageChange;return (<Dialog open={open} onOpenChange={onOpenChange}>@@ -253,6 +268,44 @@ export function GenerateConfirmDialog({))}+ {showCoverage && (+ <fieldset className="space-y-1.5">+ <legend className="text-xs font-medium text-[var(--color-text-secondary)]">+ How much to write+ </legend>+ <div className="flex flex-wrap gap-1.5">+ {coverageOptions!.map((pct) => {+ const active =+ coveragePct != null && Math.abs(pct - coveragePct) < 1e-9;+ const isAll = pct >= 1;+ return (+ <button+ key={pct}+ type="button"+ aria-pressed={active}+ onClick={() => onCoverageChange!(pct)}+ className={cn(+ "rounded-full border px-3 py-1 text-xs font-medium transition-colors",+ active+ ? "border-[var(--color-border-active)] bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-inset)]",+ )}+ >+ {isAll ? "All" : `${Math.round(pct * 100)}%`}+ </button>+ );+ })}+ </div>+ {recommendedCoverage != null && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {Math.round(recommendedCoverage * 100)}% covers the most+ important pages, a good place to start. Pick All to write+ every page.+ </p>+ )}+ </fieldset>+ )}+<fieldset className="space-y-1.5"><legend className="text-xs font-medium text-[var(--color-text-secondary)]">What else to updatediff --git a/packages/web/src/components/coverage/freshness-table-wrapper.tsx b/packages/web/src/components/coverage/freshness-table-wrapper.tsxindex 78e427062..8ee1bfa3c 100644--- a/packages/web/src/components/coverage/freshness-table-wrapper.tsx+++ b/packages/web/src/components/coverage/freshness-table-wrapper.tsx@@ -88,13 +88,12 @@ export function FreshnessTableWithRegenerate({function writeAllTemplates() {if (busy || templateCount === 0) return;- bulk.begin(- { kind: "unwritten" },- {- label: "every page still generated from structure",- defaultCascade: "none",- },- );+ // The banner's "Write with AI" opens the coverage picker at the recommended+ // percent rather than committing to every template page; "All" is one click.+ bulk.beginCoverage({+ label: "the most important pages by coverage",+ defaultCascade: "none",+ });}const toolbar =diff --git a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx b/packages/web/src/components/dashboard/quick-actions-wrapper.tsxindex e985f0bff..d54664b1e 100644--- a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx+++ b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx@@ -104,10 +104,13 @@ export function QuickActionsWrapper({async function handleAction(key: QuickActionKey) {if (key === "generate-docs") {- bulk.begin(- { kind: "unwritten" },- { label: "every page still generated from structure", defaultCascade: "none" },- );+ // Open in coverage mode at the recommended percent, not silently+ // targeting every unwritten page: a large repo is never one click from+ // writing all N. "All" is the 100% bucket, one click away.+ bulk.beginCoverage({+ label: "the most important pages by coverage",+ defaultCascade: "none",+ });return;}try {diff --git a/packages/web/src/components/docs/bulk-generate-confirm.tsx b/packages/web/src/components/docs/bulk-generate-confirm.tsxindex bad817883..8f9237757 100644--- a/packages/web/src/components/docs/bulk-generate-confirm.tsx+++ b/packages/web/src/components/docs/bulk-generate-confirm.tsx@@ -2,7 +2,11 @@import { GenerateConfirmDialog } from "@repowise-dev/ui/wiki/regenerate-button";import { formatEstimateCost } from "@/lib/generate-format";-import type { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";+import {+ COVERAGE_OPTIONS,+ RECOMMENDED_COVERAGE,+ type useBulkGenerate,+} from "@/lib/hooks/use-bulk-generate";/*** Maps a `useBulkGenerate` flow onto the shared, presentational@@ -19,8 +23,9 @@ export function BulkGenerateConfirm({/** Dialog title, e.g. "Write documentation with AI". */title?: string;}) {- const { estimate, noProvider, label } = flow;+ const { estimate, noProvider, label, coveragePct } = flow;const pages = estimate?.total_pages ?? 0;+ const isCoverage = coveragePct != null;return (<GenerateConfirmDialog@@ -29,6 +34,10 @@ export function BulkGenerateConfirm({mode="write"title={title ?? "Write documentation with AI"}cascadeScope="selection"+ coverageOptions={isCoverage ? [...COVERAGE_OPTIONS] : undefined}+ coveragePct={coveragePct ?? undefined}+ onCoverageChange={isCoverage ? flow.changeCoverage : undefined}+ recommendedCoverage={isCoverage ? RECOMMENDED_COVERAGE : undefined}description={<>Write{" "}diff --git a/packages/web/src/lib/hooks/use-bulk-generate.ts b/packages/web/src/lib/hooks/use-bulk-generate.tsindex 309aa9b96..040e8294d 100644--- a/packages/web/src/lib/hooks/use-bulk-generate.ts+++ b/packages/web/src/lib/hooks/use-bulk-generate.ts@@ -7,57 +7,88 @@ import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";import { generateEstimate, generatePages } from "@/lib/api/repos";import type { GenerateEstimate, GenerateSelection } from "@/lib/api/types";+/** Ranked coverage buckets offered in the bulk confirm, mirroring init's+ * chooser: 10 / 20 / 30 / 50 / All, recommended 20%. `1` is "everything". */+export const COVERAGE_OPTIONS = [0.1, 0.2, 0.3, 0.5, 1] as const;+export const RECOMMENDED_COVERAGE = 0.2;+/*** The bulk "Write with AI" flow, shared by the dashboard quick action, the* auto-docs banner, and the coverage "Write selected" action. Owns the- * lazily-fetched, per-cascade cached `/generate/estimate` (heavy, so never per- * render), the launch, and the active job id. The shared `GenerateConfirmDialog`- * and `GenerationProgressWrapper` stay presentational; the caller maps this- * state onto them and renders progress wherever it fits.+ * lazily-fetched estimate (heavy, so never per render) cached per coverage+ * bucket and cascade, the launch, and the active job id. The shared+ * `GenerateConfirmDialog` and `GenerationProgressWrapper` stay presentational;+ * the caller maps this state onto them and renders progress wherever it fits.+ *+ * A selection is either explicit (a fixed `GenerateSelection`) or a ranked+ * coverage pick. Begin a coverage-mode flow with `beginCoverage` — the dialog+ * then shows the bucket picker and the estimate re-prices the real page count+ * for each bucket the user tries.*/export function useBulkGenerate(repoId: string) {const [selection, setSelection] = useState<GenerateSelection | null>(null);const [label, setLabel] = useState<string | undefined>(undefined);const [confirmOpen, setConfirmOpen] = useState(false);const [cascade, setCascade] = useState<RegenerateCascade>("none");+ // null when the flow is an explicit selection; a fraction when it is a ranked+ // coverage pick (which reveals the bucket picker in the dialog).+ const [coveragePct, setCoveragePct] = useState<number | null>(null);const [estimate, setEstimate] = useState<GenerateEstimate | null>(null);const [estimateLoading, setEstimateLoading] = useState(false);const [estimateError, setEstimateError] = useState<string | null>(null);const [launching, setLaunching] = useState(false);const [jobId, setJobId] = useState<string | null>(null);- // Estimate cache keyed by cascade so toggling the choice back doesn't refetch- // the heavy endpoint. Cleared on each new `begin`, since the selection (and- // thus the estimate) changes.- const cacheRef = useRef<Map<RegenerateCascade, GenerateEstimate>>(new Map());- const wantedCascadeRef = useRef<RegenerateCascade>("none");- const selectionRef = useRef<GenerateSelection | null>(null);- // A monotonic token bumped on each `begin`. Latest-wins keys on BOTH the- // token and the cascade, so a late estimate for a since-abandoned selection- // (not just a since-abandoned cascade) can never write into the current+ // Estimate cache keyed by (coverage bucket, cascade) so toggling either back+ // to a value already priced doesn't refetch the heavy endpoint. Cleared on+ // each new `begin`, since the base selection (and thus the estimate) changes.+ const cacheRef = useRef<Map<string, GenerateEstimate>>(new Map());+ // The (bucket, cascade) the UI currently wants shown, so a late response for a+ // since-abandoned bucket or cascade never writes into the dialog.+ const wantedKeyRef = useRef("");+ const explicitSelectionRef = useRef<GenerateSelection | null>(null);+ // A monotonic token bumped on each `begin`. Latest-wins keys on BOTH the token+ // and the wanted key, so a late estimate for a since-abandoned selection (not+ // just a since-abandoned bucket/cascade) can never write into the current// dialog or its freshly-cleared cache.const requestRef = useRef(0);+ const keyFor = (pct: number | null, which: RegenerateCascade) =>+ `${pct ?? "x"}|${which}`;++ // The selection sent to the estimate/launch endpoints for a given bucket:+ // ranked when in coverage mode, the fixed explicit selection otherwise.+ const selectionFor = useCallback(+ (pct: number | null): GenerateSelection | null =>+ pct != null ? { kind: "ranked", coverage_pct: pct } : explicitSelectionRef.current,+ [],+ );+const fetchEstimate = useCallback(- async (which: RegenerateCascade) => {- const sel = selectionRef.current;+ async (pct: number | null, which: RegenerateCascade) => {+ const sel = selectionFor(pct);if (!sel) return;const token = requestRef.current;- wantedCascadeRef.current = which;- const cached = cacheRef.current.get(which);+ const key = keyFor(pct, which);+ wantedKeyRef.current = key;+ const cached = cacheRef.current.get(key);if (cached) {setEstimate(cached);setEstimateError(null);+ // Clear any spinner left set by a still-in-flight fetch for a bucket the+ // user has since switched away from: that fetch's `finally` no-ops now+ // (current() is false), so this cache hit owns resetting the flag.+ setEstimateLoading(false);return;}setEstimateLoading(true);setEstimateError(null);const current = () =>- requestRef.current === token && wantedCascadeRef.current === which;+ requestRef.current === token && wantedKeyRef.current === key;try {const res = await generateEstimate(repoId, { selection: sel, cascade: which });if (requestRef.current !== token) return;- cacheRef.current.set(which, res);+ cacheRef.current.set(key, res);if (current()) setEstimate(res);} catch (e) {if (current()) {@@ -68,45 +99,73 @@ export function useBulkGenerate(repoId: string) {if (current()) setEstimateLoading(false);}},- [repoId],+ [repoId, selectionFor],);- /** Open the confirm dialog for a selection. The estimate is fetched lazily- * here (once, on open) and re-priced per cascade choice — never live as a- * selection is built, since the endpoint is heavy. */- const begin = useCallback(+ const openFor = useCallback((- sel: GenerateSelection,+ pct: number | null,+ explicit: GenerateSelection | null,opts?: { label?: string; defaultCascade?: RegenerateCascade },) => {const startCascade = opts?.defaultCascade ?? "none";requestRef.current += 1;cacheRef.current.clear();- selectionRef.current = sel;- setSelection(sel);+ explicitSelectionRef.current = explicit;+ setSelection(explicit ?? (pct != null ? { kind: "ranked", coverage_pct: pct } : null));+ setCoveragePct(pct);setLabel(opts?.label);setCascade(startCascade);setEstimateError(null);setEstimate(null);- void fetchEstimate(startCascade);+ void fetchEstimate(pct, startCascade);setConfirmOpen(true);},[fetchEstimate],);+ /** Open the confirm dialog for a fixed, explicit selection (no coverage+ * picker). The estimate is fetched lazily here and re-priced per cascade. */+ const begin = useCallback(+ (+ sel: GenerateSelection,+ opts?: { label?: string; defaultCascade?: RegenerateCascade },+ ) => openFor(null, sel, opts),+ [openFor],+ );++ /** Open the confirm dialog in ranked coverage mode, starting at+ * `startPct` (default the recommended bucket). The dialog shows the bucket+ * picker and re-prices the real page count for each bucket tried. */+ const beginCoverage = useCallback(+ (opts?: { label?: string; startPct?: number; defaultCascade?: RegenerateCascade }) =>+ openFor(opts?.startPct ?? RECOMMENDED_COVERAGE, null, opts),+ [openFor],+ );+const changeCascade = useCallback((next: RegenerateCascade) => {setCascade(next);- void fetchEstimate(next);+ void fetchEstimate(coveragePct, next);},- [fetchEstimate],+ [fetchEstimate, coveragePct],+ );++ const changeCoverage = useCallback(+ (pct: number) => {+ setCoveragePct(pct);+ setSelection({ kind: "ranked", coverage_pct: pct });+ void fetchEstimate(pct, cascade);+ },+ [fetchEstimate, cascade],);const confirm = useCallback(async () => {- if (!selection) return;+ const sel = selectionFor(coveragePct);+ if (!sel) return;setLaunching(true);try {- const res = await generatePages(repoId, { selection, cascade });+ const res = await generatePages(repoId, { selection: sel, cascade });setJobId(res.job_id);setConfirmOpen(false);} catch (e) {@@ -114,7 +173,7 @@ export function useBulkGenerate(repoId: string) {} finally {setLaunching(false);}- }, [repoId, selection, cascade]);+ }, [repoId, selectionFor, coveragePct, cascade]);const clearJob = useCallback(() => setJobId(null), []);@@ -127,6 +186,8 @@ export function useBulkGenerate(repoId: string) {setConfirmOpen,cascade,changeCascade,+ coveragePct,+ changeCoverage,estimate,estimateLoading,estimateError,@@ -134,6 +195,7 @@ export function useBulkGenerate(repoId: string) {launching,jobId,begin,+ beginCoverage,confirm,clearJob,};diff --git a/tests/unit/server/test_generate.py b/tests/unit/server/test_generate.pyindex f1ecd1964..81f7da4e5 100644--- a/tests/unit/server/test_generate.py+++ b/tests/unit/server/test_generate.py@@ -47,12 +47,52 @@ from tests.unit.server.conftest import create_test_repo{"mode": "single_page", "page_id": "file_page:a.py"},PageSelectionIntent(page_ids=("file_page:a.py",)),),+ # Ranked short-circuits resolve_scope via the seed, so the intent is empty.+ ({"selection": {"kind": "ranked", "coverage_pct": 0.2}}, PageSelectionIntent()),],)def test_build_generate_intent(config: dict, expected: PageSelectionIntent) -> None:assert _build_generate_intent(config) == expected+# ---------------------------------------------------------------------------+# cascade + ranked-coverage helpers+# ---------------------------------------------------------------------------+++ ("config", "expected"),+ [+ ({"cascade": "full"}, "full"), # explicit always wins+ ({"selection": {"kind": "ranked", "coverage_pct": 0.2}}, "none"),+ ({"mode": "single_page"}, "none"),+ ({"selection": {"kind": "unwritten"}}, "dependents"),+ ({}, "dependents"),+ # Explicit cascade wins even for a ranked selection.+ ({"selection": {"kind": "ranked", "top_n": 5}, "cascade": "dependents"}, "dependents"),+ ],+)+def test_effective_cascade(config: dict, expected: str) -> None:+ from repowise.server.job_executor import _effective_cascade++ assert _effective_cascade(config) == expected+++ ("selection", "n_files", "expected"),+ [+ ({"coverage_pct": 0.3}, 100, 0.3), # coverage_pct passes through+ ({"top_n": 5}, 100, 0.05), # top_n maps to n / n_files+ ({"top_n": 500}, 100, 1.0), # clamped to 1.0+ ({}, 100, 0.0), # neither set (guarded upstream) is a no-op fraction+ ],+)+def test_ranked_coverage_pct(selection: dict, n_files: int, expected: float) -> None:+ from repowise.server.job_executor import _ranked_coverage_pct++ assert _ranked_coverage_pct(selection, n_files) == pytest.approx(expected)++# ---------------------------------------------------------------------------# POST /generate + /generate/estimate endpoints# ---------------------------------------------------------------------------@@ -100,6 +140,50 @@ async def test_generate_endpoint_page_ids_selection(client: AsyncClient, app) ->assert cfg["style"] == "caveman"+async def test_generate_endpoint_ranked_selection(client: AsyncClient, app) -> None:+ """A ranked coverage selection is carried into the job config."""+ repo = await create_test_repo(client)+ with patch("repowise.server.routers.repos._launch_job_task"):+ resp = await client.post(+ f"/api/repos/{repo['id']}/generate",+ json={"selection": {"kind": "ranked", "coverage_pct": 0.2}, "cascade": "none"},+ )+ assert resp.status_code == 202+ cfg = await _job_config(app.state.session_factory, resp.json()["job_id"])+ assert cfg["selection"] == {"kind": "ranked", "coverage_pct": 0.2}+ assert cfg["cascade"] == "none"+++ ("selection", "needle"),+ [+ # Ranked needs exactly one sizing knob.+ ({"kind": "ranked"}, "exactly one"),+ ({"kind": "ranked", "coverage_pct": 0.2, "top_n": 5}, "exactly one"),+ # Out-of-range coverage / non-positive top_n.+ ({"kind": "ranked", "coverage_pct": 1.5}, "fraction"),+ ({"kind": "ranked", "coverage_pct": 0}, "fraction"),+ ({"kind": "ranked", "top_n": 0}, "positive"),+ # Ranked cannot also carry explicit page selectors.+ ({"kind": "ranked", "coverage_pct": 0.2, "page_ids": ["file_page:a.py"]}, "page_ids"),+ # coverage_pct / top_n only belong to a ranked selection.+ ({"kind": "unwritten", "coverage_pct": 0.2}, "ranked"),+ ({"kind": "all", "top_n": 5}, "ranked"),+ ],+)+async def test_generate_endpoint_rejects_bad_ranked(+ client: AsyncClient, selection: dict, needle: str+) -> None:+ repo = await create_test_repo(client)+ resp = await client.post(+ f"/api/repos/{repo['id']}/generate", json={"selection": selection}+ )+ assert resp.status_code == 400, resp.text+ assert needle in resp.json()["detail"].lower()++@pytest.mark.asyncioasync def test_generate_endpoint_rejects_unknown_style(client: AsyncClient) -> None:repo = await create_test_repo(client)@@ -243,6 +327,46 @@ async def test_generate_job_runs_scoped_engine(session_factory, tmp_path) -> Nonassert cfg["pages_generated"] == 1+def test_resolve_generate_scope_ranked_uses_build_ranked_seed() -> None:+ """A ranked config resolves through build_ranked_seed, so the estimate and+ the job (both callers of this one helper) plan the identical page set."""+ from repowise.server.job_executor import _resolve_generate_scope++ template_ids = ["file_page:a.py", "file_page:b.py", "file_page:c.py"]+ rehydrated = _fake_rehydrated(template_ids)+ # A non-empty parsed_files so top_n mapping (if used) has a denominator.+ rehydrated.parsed_files = [SimpleNamespace(path=f"{p}.py") for p in "abc"]+ seed = {"file_page:a.py"}++ config = {"selection": {"kind": "ranked", "coverage_pct": 0.2}, "cascade": "none"}+ gen_config = SimpleNamespace(coverage_pct=0.2, max_pages_pct=0.2, deterministic=False)+ with patch(+ "repowise.core.generation.scope.build_ranked_seed", return_value=seed+ ) as ranked:+ plan = _resolve_generate_scope(config, rehydrated, gen_config)++ ranked.assert_called_once()+ assert ranked.call_args.kwargs["coverage_pct"] == pytest.approx(0.2)+ assert ranked.call_args.kwargs["repo_name"] == "test-repo"+ # Cascade none + empty deps: the plan is exactly the ranked seed, nothing+ # invented and nothing dropped (the estimate's page count == the job's).+ assert plan.generate_ids == seed+++def test_resolve_generate_scope_explicit_skips_ranked_seed() -> None:+ """An explicit selection never builds a ranked seed."""+ from repowise.server.job_executor import _resolve_generate_scope++ rehydrated = _fake_rehydrated(["file_page:a.py", "file_page:b.py"])+ config = {"selection": {"kind": "unwritten"}, "cascade": "none"}+ gen_config = SimpleNamespace(coverage_pct=0.2, max_pages_pct=0.2, deterministic=False)+ with patch("repowise.core.generation.scope.build_ranked_seed") as ranked:+ plan = _resolve_generate_scope(config, rehydrated, gen_config)++ ranked.assert_not_called()+ assert plan.generate_ids == {"file_page:a.py", "file_page:b.py"}++@pytest.mark.asyncioasync def test_generate_job_fails_without_provider(session_factory, tmp_path) -> None:from repowise.server.job_executor import execute_job