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: drop the template-vs-AI provenance axis from the API and UI (#1037)
Raghav Chamadiya34a534f65bc1
diff --git a/packages/api-client/src/hosted.ts b/packages/api-client/src/hosted.tsindex c51ad663f..c939f5809 100644--- a/packages/api-client/src/hosted.ts+++ b/packages/api-client/src/hosted.ts@@ -270,11 +270,6 @@ export function mapHostedPage(raw: Record<string, unknown>, repoId: string): Paghuman_notes: null,created_at: str("created_at"),updated_at: str("updated_at") || str("created_at"),- is_deterministic:- typeof raw.is_deterministic === "boolean"- ? (raw.is_deterministic as boolean)- : str("provider_name") === "template",- doc_tier: typeof raw.doc_tier === "number" ? (raw.doc_tier as number) : null,};}@@ -314,7 +309,6 @@ export function mapHostedSearchResult(raw: Record<string, unknown>): SearchResulscore: partial.score ?? 0,snippet: partial.snippet ?? "",search_type: partial.search_type ?? "keyword",- is_deterministic: partial.is_deterministic ?? false,};}diff --git a/packages/api-client/src/types/pages.ts b/packages/api-client/src/types/pages.tsindex 75823a25d..9bcbace60 100644--- a/packages/api-client/src/types/pages.ts+++ b/packages/api-client/src/types/pages.ts@@ -23,13 +23,6 @@ export interface PageResponse {human_notes: string | null;created_at: string;updated_at: string;- /** True when the page was rendered from structure (a template) rather than- * written by a model — the flat marker the server projects from- * `provider_name === "template"`. Drives the "Write with AI" vs- * "Regenerate" affordance. */- is_deterministic: boolean;- /** 2 = in-budget template, 3 = coverage tail; null on model-written pages. */- doc_tier: number | null;/** Position in the wiki outline, computed once at generation time so every* reader navigates the same tree. Optional: pages written before the wiki* carried a tree have no placement, which reads as flat. */diff --git a/packages/api-client/src/types/search.ts b/packages/api-client/src/types/search.tsindex abb42ede4..4ae516e9b 100644--- a/packages/api-client/src/types/search.ts+++ b/packages/api-client/src/types/search.ts@@ -16,9 +16,4 @@ export interface SearchResultResponse {score: number;snippet: string;search_type: string;- /**- * True for deterministic template pages (the coverage tail) — drives the- * "Auto" badge on the result card. Optional so older payloads type-check.- */- is_deterministic?: boolean;}diff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.pyindex 89c50872e..500ce1db3 100644--- a/packages/core/src/repowise/core/generation/models.py+++ b/packages/core/src/repowise/core/generation/models.py@@ -293,6 +293,15 @@ def compute_page_id(page_type: str, target_path: str) -> str:# next index. A new page type of this shape belongs here and nowhere else.STRUCTURALLY_KEYED_PAGE_TYPES: tuple[str, ...] = ("module_page", "layer_page", "scc_page")+# The page types a model writes as prose. Every other type renders from+# structure and is permanently ``provider_name='template'``, so "does this page+# have prose yet" is only a meaningful question for these four. A stub is one of+# these still stamped ``template``; a written one carries a real provider. The+# CLI keeps its own mirror in ``generate_cmd/engine.py``.+MODEL_WRITTEN_PAGE_TYPES: frozenset[str] = frozenset(+ {"module_page", "repo_overview", "architecture_diagram", "onboarding"}+)+def member_structural_key(members: Iterable[str], *, prefix: str) -> str:"""Return a stable identity for a page defined by the files it covers.diff --git a/packages/core/src/repowise/core/persistence/crud/pages.py b/packages/core/src/repowise/core/persistence/crud/pages.pyindex ee61a31ee..d6f33d770 100644--- a/packages/core/src/repowise/core/persistence/crud/pages.py+++ b/packages/core/src/repowise/core/persistence/crud/pages.py@@ -483,7 +483,7 @@ async def list_pages(repository_id: str,*,page_type: str | None = None,- deterministic: bool | None = None,+ has_prose: bool | None = None,limit: int = 100,offset: int = 0,sort_by: str = "updated_at",@@ -491,17 +491,25 @@ async def list_pages() -> list[Page]:"""Return pages for a repository, optionally filtered by page_type.- ``deterministic=True`` returns only unwritten (template) pages;- ``deterministic=False`` returns only model-written ones. ``None`` (default)- returns both. A template page is stamped ``provider_name='template'``.+ ``has_prose`` filters on whether a model has written a page's prose, which is+ only a meaningful question for the model-written page types (the concept tree+ and onboarding); every other type renders from structure and never has prose.+ So the filter is scoped to those types: ``has_prose=True`` returns the ones a+ model has written, ``has_prose=False`` the ones still stubs, and ``None``+ (default) returns every page of every type. A stub is a model-written type+ still stamped ``provider_name='template'``."""q = select(Page).where(Page.repository_id == repository_id)if page_type is not None:q = q.where(Page.page_type == page_type)- if deterministic is True:- q = q.where(Page.provider_name == "template")- elif deterministic is False:- q = q.where(Page.provider_name != "template")+ if has_prose is not None:+ from repowise.core.generation.models import MODEL_WRITTEN_PAGE_TYPES++ q = q.where(Page.page_type.in_(sorted(MODEL_WRITTEN_PAGE_TYPES)))+ if has_prose:+ q = q.where(Page.provider_name != "template")+ else:+ q = q.where(Page.provider_name == "template")_sort_cols = {"updated_at": Page.updated_at,"confidence": Page.confidence,diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex 2ecaac4dc..41c753698 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -852,6 +852,25 @@ def _ranked_coverage_pct(selection: dict, n_files: int) -> float:return min(1.0, max(0.0, top_n / max(1, n_files)))+def _narrow_plan_to_model_written(plan: Any) -> Any:+ """Drop structural pages from a resolved plan so generate writes only prose.++ A generate request resolves against every page type, but a structural page+ has no model to write it: including it would re-render a template (a no-op+ that leaves it "unwritten") and inflate the count. Keep only the+ model-written pages in both the generate set and the cascade fallout, and+ re-price from what remains. Mirrors the CLI's ``_narrow_to_model_written``.+ """+ from dataclasses import replace++ from repowise.core.generation.models import MODEL_WRITTEN_PAGE_TYPES+ from repowise.core.generation.scope import build_cost_plans++ 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))++def _resolve_generate_scope(config: dict, rehydrated: Any, gen_config: Any) -> Any:"""Resolve a generate config + rehydrated repo into a :class:`ScopePlan`.@@ -859,7 +878,8 @@ def _resolve_generate_scope(config: dict, rehydrated: Any, gen_config: Any) -> Athe launched job resolve the *identical* page set — the estimate cannotunder-quote. A ranked selection runs the core ``build_ranked_seed`` (the sameimportance model ``repowise init`` uses at that coverage); everything else- resolves its intent normally.+ resolves its intent normally. The plan is then narrowed to the model-written+ types, so generate works on the concept layer only, mirroring the CLI."""from repowise.core.generation.scope import build_ranked_seed, resolve_scope@@ -876,13 +896,14 @@ def _resolve_generate_scope(config: dict, rehydrated: Any, gen_config: Any) -> Arepo_name=rehydrated.repo_name,coverage_pct=pct,)- return resolve_scope(+ plan = resolve_scope(records=rehydrated.records,intent=_build_generate_intent(config),cascade_mode=_effective_cascade(config),deps=rehydrated.deps,ranked_seed=ranked_seed,)+ return _narrow_plan_to_model_written(plan)def _build_generation_config(repo_path: Path, config: dict, wiki_style: str) -> Any:@@ -1045,31 +1066,40 @@ async def _run_generate_job(async def _repo_page_counts(session: Any, repo_id: str) -> tuple[int, int]:- """Return ``(total_pages, remaining_template_pages)`` for a repo."""+ """Return ``(total_pages, remaining_stub_pages)`` for a repo.++ The stub count is scoped to the model-written page types: a structural page+ is stamped ``template`` forever, so counting every template page would keep+ the ``docs_mode -> llm`` flip below from ever firing once file pages exist.+ A remaining stub is a concept/onboarding page a model has not written yet.+ """from sqlalchemy import func as sa_funcfrom sqlalchemy import select as sa_select+ from repowise.core.generation.models import MODEL_WRITTEN_PAGE_TYPESfrom repowise.core.persistence.models import Pagetotal = int((await session.execute(- sa_select(sa_func.count())- .select_from(Page)- .where(Page.repository_id == repo_id)+ sa_select(sa_func.count()).select_from(Page).where(Page.repository_id == repo_id))).scalar_one())- templates = int(+ stubs = int((await session.execute(sa_select(sa_func.count()).select_from(Page)- .where(Page.repository_id == repo_id, Page.provider_name == "template")+ .where(+ Page.repository_id == repo_id,+ Page.page_type.in_(sorted(MODEL_WRITTEN_PAGE_TYPES)),+ Page.provider_name == "template",+ ))).scalar_one())- return total, templates+ return total, stubsasync def _incremental_page_regen(diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pyindex 62e11b9f9..b90c7a42a 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -205,7 +205,6 @@ async def hydrate_hits(hits: list[dict], ctx: Any, *, scope: str | None = None)Page.summary,Page.page_type,Page.freshness_status,- Page.provider_name,).where(Page.id.in_(page_ids)))meta_by_id = {@@ -214,7 +213,6 @@ async def hydrate_hits(hits: list[dict], ctx: Any, *, scope: str | None = None)"summary": row[2] or "","page_type": row[3] or "","freshness": row[4] or "",- "provider_name": row[5] or "",}for row in res.all()}@@ -234,9 +232,6 @@ async def hydrate_hits(hits: list[dict], ctx: Any, *, scope: str | None = None)# Prefer the Page table's page_type when present — it's the source# of truth; retrievers sometimes carry stale or empty types.h["page_type"] = meta.get("page_type") or h.get("page_type", "")- # Deterministic template pages (the coverage tail) are down-weighted- # downstream so a thin projection can't displace a rich LLM page.- h["_deterministic"] = meta.get("provider_name") == "template"out.append(h)return outdiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.pyindex c2cdccdbe..6e4bfa872 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py@@ -118,7 +118,6 @@ from repowise.server.mcp_server.tool_answer.data_shape import (from repowise.server.mcp_server.tool_answer.retrieval import (_apply_domain_penalty,_candidate_justification,- _downweight_deterministic,_enrich_gated_excerpts,_intersection_boost,_rerank_by_coverage,@@ -746,11 +745,6 @@ async def get_answer(# candidate set so it's a tie-breaker, not a wholesale reordering.with contextlib.suppress(Exception):await _apply_pagerank_bias(hits, ctx)- # Deterministic coverage-tail pages are factual but thin — down-weight them- # so a projection can't displace a rich LLM page when both match. A tie-- # breaker, applied after the score biases and before symbol/flow anchoring- # (which can still promote a deterministic page the question names directly).- _downweight_deterministic(hits)# Graph expansion: 1-hop walk from the top hits to rescue near-misses# where retrieval landed in the right module but on the wrong file# (consumer instead of orchestrator). Adds up to 3 neighbors with adiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py b/packages/server/src/repowise/server/mcp_server/tool_answer/config.pyindex 464af10d9..3fa351249 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py@@ -273,13 +273,6 @@ _BACKEND_QUESTION_TOKENS = frozenset(# domain hit (real top score outlier) still survives._DOMAIN_PENALTY = 0.5-# Deterministic template pages (the Phase G coverage tail) are factual but-# thin — they exist so every source file is retrievable, not to out-argue a-# rich LLM page. Multiplicative, not absolute: a deterministic page that is-# genuinely the best hit (its file has no LLM page) still surfaces, preserving-# the coverage the tail adds; the factor only breaks ties toward the LLM page.-_DETERMINISTIC_DOWNWEIGHT = 0.9-# Floor on raw top-hit score for "high" confidence. Below this the answer# may be technically dominant but built on weak retrieval — downgrade to# "medium" so the agent verifies. Tuned against observed BM25 ranges ondiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.pyindex 592ad6a61..75aa3b3f3 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py@@ -19,7 +19,6 @@ from repowise.server.mcp_server.tool_answer.config import (_BACKEND_PATH_PREFIXES,_BACKEND_QUESTION_TOKENS,_COVERAGE_FLOOR,- _DETERMINISTIC_DOWNWEIGHT,_DOMAIN_PENALTY,_GATED_EXCERPT_CHARS,_GATED_RETURN_HITS,@@ -164,9 +163,7 @@ async def _enrich_gated_excerpts(hits: list[dict], ctx: Any = None) -> None:returntry:async with get_session(ctx.session_factory) as session:- res = await session.execute(- select(Page.id, Page.content).where(Page.id.in_(page_ids))- )+ res = await session.execute(select(Page.id, Page.content).where(Page.id.in_(page_ids)))content_by_id = {row[0]: (row[1] or "") for row in res.all()}except Exception:return@@ -222,24 +219,6 @@ def _apply_domain_penalty(hits: list[dict], question: str) -> None:hits.sort(key=lambda h: h["score"], reverse=True)-def _downweight_deterministic(hits: list[dict]) -> None:- """Down-weight deterministic-template hits in place, then re-sort by score.-- The ``_deterministic`` marker is attached during hydration- (``provider_name == "template"``). A thin coverage-tail page should not- displace a rich LLM page when both match a conceptual question; the- multiplicative factor only breaks ties, so a deterministic page that is- clearly the best hit (its file has no LLM page) still ranks first.- """- touched = False- for h in hits:- if h.get("_deterministic") and h.get("score"):- h["score"] = h["score"] * _DETERMINISTIC_DOWNWEIGHT- touched = True- if touched:- hits.sort(key=lambda h: h["score"], reverse=True)--def _candidate_justification(h: dict) -> str:"""One-line reason this hit might answer the question.diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex a6125aefa..426a10b56 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -110,8 +110,9 @@ def _prose_dominates(query: str, identifiers: list[str]) -> bool:return (total - ident_count) > ident_count-def _interleave_hybrid(query: str, symbols: list[dict], concepts: list[dict],- limit: int, exact: bool) -> list[dict]:+def _interleave_hybrid(+ query: str, symbols: list[dict], concepts: list[dict], limit: int, exact: bool+) -> list[dict]:"""Order one hybrid result window from the two incomparable score scales.Symbol SQL scores (~43, +100 on an exact-name hit) and concept relevance@@ -141,14 +142,6 @@ def _interleave_hybrid(query: str, symbols: list[dict], concepts: list[dict],# who phrases one here clearly wants the decision pages ranked honestly._DECISION_DOWNWEIGHT = 0.6-# Deterministic template pages (the Phase G coverage tail) are factual but-# thin — they exist so every source file is retrievable, not to out-argue a-# rich LLM page. A mild multiplicative down-weight breaks ties toward the LLM-# page when both match a conceptual query, without burying a deterministic-# page that is genuinely the best hit (its file has no LLM page). A stronger-# demotion would re-bury the coverage the tail pages add.-_DETERMINISTIC_DOWNWEIGHT = 0.9-_WHY_SHAPED_RE = re.compile(r"^\s*(why|when\s+did|when\s+was|who\s+decided|who\s+chose|what\s+was\s+the\s+(reason|rationale))\b"r"|\b(decision|decided|rationale|adr)\b",@@ -170,23 +163,6 @@ def _downweight_decisions(output: list[dict], query: str) -> None:item["relevance_score"] = round(item["relevance_score"] * _DECISION_DOWNWEIGHT, 4)-def _downweight_deterministic(output: list[dict], det_ids: set) -> None:- """Scale down deterministic-template pages' relevance in place.-- A thin projection page should not displace a rich LLM page when both- match a conceptual query. The multiplicative factor only breaks ties —- a deterministic page that is clearly the best hit (its file has no LLM- page) still surfaces, preserving the coverage the tail adds.- """- if not det_ids:- return- for item in output:- if item.get("page_id") in det_ids and item.get("relevance_score"):- item["relevance_score"] = round(- item["relevance_score"] * _DETERMINISTIC_DOWNWEIGHT, 4- )--def _sort_demoting_decisions(output: list[dict], query: str) -> None:"""Sort by relevance, ranking decision records below every file-backedpage on non-why queries.@@ -335,25 +311,20 @@ def _filter_by_kind(output: list[dict], kind: str | None) -> list[dict]:async def _load_page_info(session, output: list[dict], *, with_git: bool = False-) -> tuple[dict, set, dict, set]:- """Batch-load target paths, tombstones, deterministic markers, and git.-- Returns ``(page_info, tombstoned, git_map, det_ids)`` where ``page_info``- maps page_id -> target_path, ``tombstoned`` is the set of tombstoned- page_ids, ``git_map`` maps file_path -> GitMetadata (empty unless- ``with_git``), and ``det_ids`` is the set of page_ids for deterministic- template pages (the coverage tail — ``provider_name == "template"``).+) -> tuple[dict, set, dict]:+ """Batch-load target paths, tombstones, and git.++ Returns ``(page_info, tombstoned, git_map)`` where ``page_info`` maps+ page_id -> target_path, ``tombstoned`` is the set of tombstoned page_ids,+ and ``git_map`` maps file_path -> GitMetadata (empty unless ``with_git``)."""page_ids = [item["page_id"] for item in output]res = await session.execute(- select(Page.id, Page.target_path, Page.freshness_status, Page.provider_name).where(- Page.id.in_(page_ids)- )+ select(Page.id, Page.target_path, Page.freshness_status).where(Page.id.in_(page_ids)))rows = res.all()page_info = {row[0]: row[1] for row in rows}tombstoned = {row[0] for row in rows if row[2] == "tombstone"}- det_ids = {row[0] for row in rows if row[3] == "template"}git_map: dict[str, GitMetadata] = {}if with_git:@@ -363,7 +334,7 @@ async def _load_page_info(select(GitMetadata).where(GitMetadata.file_path.in_(target_paths)))git_map = {g.file_path: g for g in git_res.scalars().all()}- return page_info, tombstoned, git_map, det_ids+ return page_info, tombstoned, git_mapdef _apply_freshness_boost(item: dict, gm: GitMetadata | None) -> None:@@ -473,18 +444,16 @@ async def _search_single_repo(# Attach target_path + deterministic markers and drop excluded hits per# repo (so federated search honours each repo's own exclude_patterns)# before ranking. Runs on the over-fetched list so the kind filter below- # has real headroom. Load precedes the sort so both the decision demotion- # and the deterministic down-weight see the page metadata they key on.- det_ids: set = set()+ # has real headroom. Load precedes the sort so the decision demotion sees+ # the page metadata it keys on.if output:async with get_session(ctx.session_factory) as session:- page_info, tombstoned, _, det_ids = await _load_page_info(session, output)+ page_info, tombstoned, _ = await _load_page_info(session, output)output = [item for item in output if item["page_id"] not in tombstoned]for item in output:item["target_path"] = page_info.get(item["page_id"], "")output = filter_dicts_by_key(output, "target_path", _get_exclude_spec(ctx.path))- _downweight_deterministic(output, det_ids)_sort_demoting_decisions(output, query)output = _filter_by_kind(output, kind)@@ -787,9 +756,7 @@ async def search_codebase(# Batch-lookup page target paths for the kind filter + git freshness boostif output:async with get_session(ctx.session_factory) as session:- page_info, tombstoned, git_map, det_ids = await _load_page_info(- session, output, with_git=True- )+ page_info, tombstoned, git_map = await _load_page_info(session, output, with_git=True)# Tombstoned pages document deleted/renamed files — never results.output = [item for item in output if item["page_id"] not in tombstoned]@@ -806,10 +773,8 @@ async def search_codebase(gm = git_map.get(target_path) if target_path else None_apply_freshness_boost(item, gm)- # Down-weight thin deterministic pages so they don't displace a rich- # LLM page, then re-sort by adjusted relevance with decisions hard-- # demoted on non-why queries.- _downweight_deterministic(output, det_ids)+ # Re-sort by adjusted relevance with decisions hard-demoted on non-why+ # queries._sort_demoting_decisions(output, query)output = _filter_by_kind(output, kind)diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.pyindex e3193a1ae..64edd174c 100644--- a/packages/server/src/repowise/server/routers/files.py+++ b/packages/server/src/repowise/server/routers/files.py@@ -217,11 +217,6 @@ async def file_detail("confidence": page_row.confidence,"human_notes": page_row.human_notes,"updated_at": page_row.updated_at.isoformat() if page_row.updated_at else None,- # Deterministic template pages (the coverage tail) are badged in- # the file docs tab. provider_name is the marker; doc_tier (2/3)- # mirrors metadata.doc_tier for the reader that wants the tier.- "is_deterministic": page_row.provider_name == "template",- "doc_tier": json.loads(page_row.metadata_json or "{}").get("doc_tier"),}if page_rowelse Nonediff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.pyindex 9111c9222..1b92592b7 100644--- a/packages/server/src/repowise/server/routers/overview.py+++ b/packages/server/src/repowise/server/routers/overview.py@@ -214,17 +214,6 @@ async def overview_summary(total_pages = (await session.scalar(select(func.count(Page.id)).where(Page.repository_id == repo_id)) or 0)- # Template-provider pages are the deterministic coverage tail (zero LLM);- # everything else came out of a model. Same discriminator the page schema- # uses for the "Auto" badge.- auto_pages = (- await session.scalar(- select(func.count(Page.id)).where(- Page.repository_id == repo_id, Page.provider_name == "template"- )- )- or 0- )fresh_pages = (await session.scalar(select(func.count(Page.id)).where(@@ -427,7 +416,6 @@ async def overview_summary("symbol_count": symbol_count,"entry_point_count": entry_point_count,"doc_page_count": total_pages,- "doc_auto_page_count": auto_pages,"doc_coverage_pct": doc_coverage_pct,"freshness_score": freshness_score,"dead_export_count": dead_export_count,diff --git a/packages/server/src/repowise/server/routers/pages.py b/packages/server/src/repowise/server/routers/pages.pyindex cb7564691..cc52e3901 100644--- a/packages/server/src/repowise/server/routers/pages.py+++ b/packages/server/src/repowise/server/routers/pages.py@@ -27,10 +27,11 @@ router = APIRouter(async def list_pages(repo_id: str = Query(..., description="Repository ID"),page_type: str | None = Query(None, description="Filter by page type"),- deterministic: bool | None = Query(+ has_prose: bool | None = Query(None,- description="true = only unwritten (template) pages; false = only "- "model-written pages; omit for both.",+ description="Scoped to the model-written page types (the concept tree and "+ "onboarding): true = only the ones a model has written, false = only the "+ "ones still stubs; omit for every page of every type.",),sort_by: str = Query("updated_at", description="Sort field: updated_at, confidence, created_at"@@ -45,7 +46,7 @@ async def list_pages(session,repo_id,page_type=page_type,- deterministic=deterministic,+ has_prose=has_prose,limit=limit,offset=offset,sort_by=sort_by,@@ -115,8 +116,7 @@ async def regenerate_page_by_query(),cascade: str = Query("none",- description="What to do with the pages that summarize this one: "- "none / dependents / full.",+ description="What to do with the pages that summarize this one: none / dependents / full.",),session: AsyncSession = Depends(get_db_session), # noqa: B008) -> dict:diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.pyindex 9caea0d5f..0355e35eb 100644--- a/packages/server/src/repowise/server/routers/repos.py+++ b/packages/server/src/repowise/server/routers/repos.py@@ -244,9 +244,7 @@ async def list_repos(# docs_enabled=True by default. Deriving the flag from the# resolved mode alone would flip those old indexes to False,# so keep the legacy default when nothing at all is recorded.- if not any(- k in state for k in ("docs_mode", "docs_enabled", "provider", "model")- ):+ if not any(k in state for k in ("docs_mode", "docs_enabled", "provider", "model")):resp.docs_enabled = Trueelse:resp.docs_enabled = resp.docs_mode != "none"@@ -589,6 +587,23 @@ def _validate_generate_selection(sel: GenerateSelectionBody) -> None::class:`GenerateSelectionBody`) and may not be mixed; ``coverage_pct`` and``top_n`` are mutually exclusive and belong only to a ranked selection."""+ if sel.kind == "page_ids":+ from repowise.core.generation.models import MODEL_WRITTEN_PAGE_TYPES++ structural = [+ pid+ for pid in (sel.page_ids or [])+ if pid.split(":", 1)[0] not in MODEL_WRITTEN_PAGE_TYPES+ ]+ if structural:+ raise HTTPException(+ status_code=400,+ detail=(+ "generate writes the concept layer only; these pages render "+ "from structure and refresh on update, not generate: " + ", ".join(structural)+ ),+ )+is_ranked = sel.kind == "ranked"has_coverage = sel.coverage_pct is not Nonehas_top_n = sel.top_n is not None@@ -605,9 +620,7 @@ def _validate_generate_selection(sel: GenerateSelectionBody) -> None: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."- )+ 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,@@ -631,7 +644,9 @@ def _validate_generate_style(style: str | None) -> None:if not is_known_style(style):valid = ", ".join(s.name for s in list_styles())- raise HTTPException(status_code=400, detail=f"Unknown style '{style}'. Valid styles: {valid}.")+ raise HTTPException(+ status_code=400, detail=f"Unknown style '{style}'. Valid styles: {valid}."+ )def _generate_job_config(body: GenerateRequestBody) -> dict:diff --git a/packages/server/src/repowise/server/routers/search.py b/packages/server/src/repowise/server/routers/search.pyindex 271291b40..09fbf4ce3 100644--- a/packages/server/src/repowise/server/routers/search.py+++ b/packages/server/src/repowise/server/routers/search.py@@ -10,14 +10,10 @@ from __future__ import annotationsfrom pathlib import Pathfrom fastapi import APIRouter, Depends, Query, Request-from sqlalchemy import select-from repowise.core.persistence.database import get_session-from repowise.core.persistence.models import Pagefrom repowise.server.deps import (get_fts,get_vector_store,- resolve_session_factory,verify_api_key,)from repowise.server.schemas import SearchResultResponse@@ -29,7 +25,7 @@ router = APIRouter()-def _to_response(r, det_ids: set[str]) -> SearchResultResponse:+def _to_response(r) -> SearchResultResponse:"""Convert a SearchResult dataclass into the API schema."""return SearchResultResponse(page_id=r.page_id,@@ -39,33 +35,9 @@ def _to_response(r, det_ids: set[str]) -> SearchResultResponse:score=r.score,snippet=r.snippet,search_type=r.search_type,- is_deterministic=r.page_id in det_ids,)-async def _deterministic_page_ids(- request: Request, repo_id: str | None, page_ids: list[str]-) -> set[str]:- """Page ids among ``page_ids`` that are deterministic template pages.-- One batch lookup against the resolved repo's DB. Best-effort: workspace- fan-out results whose page lives in another repo's DB simply aren't- flagged (the badge is a hint, not load-bearing), so a lookup miss or- error yields an empty set rather than failing the search.- """- if not page_ids:- return set()- try:- factory = resolve_session_factory(request.app.state, repo_id)- async with get_session(factory) as session:- rows = await session.execute(- select(Page.id).where(Page.id.in_(page_ids), Page.provider_name == "template")- )- return {row[0] for row in rows.all()}- except Exception:- return set()--@router.get("", response_model=list[SearchResultResponse])async def search(request: Request,@@ -97,8 +69,7 @@ async def search(else:results = await _semantic(request, query, limit, repo_id=repo_id, primary_vs=vector_store)- det_ids = await _deterministic_page_ids(request, repo_id, [r.page_id for r in results])- return [_to_response(r, det_ids) for r in results]+ return [_to_response(r) for r in results]# ---------------------------------------------------------------------------diff --git a/packages/server/src/repowise/server/schemas/pages.py b/packages/server/src/repowise/server/schemas/pages.pyindex 494d72f7b..b7c1cc0f6 100644--- a/packages/server/src/repowise/server/schemas/pages.py+++ b/packages/server/src/repowise/server/schemas/pages.py@@ -26,13 +26,6 @@ class PageResponse(BaseModel):confidence: floatfreshness_status: strmetadata: dict- # Deterministic coverage-tail pages are template-generated (zero LLM).- # ``is_deterministic`` is the flat marker for UI badging / ranking;- # ``doc_tier`` (2 = in-budget template, 3 = coverage tail) mirrors- # ``metadata.doc_tier`` at the top level so consumers don't dig into the- # metadata blob. Both default to the LLM-page values for older rows.- is_deterministic: bool = False- doc_tier: int | None = Nonehuman_notes: str | None = None# Position in the wiki outline. Older rows carry no placement, which reads# as a flat wiki and is what those rows actually describe.@@ -64,8 +57,6 @@ class PageResponse(BaseModel):confidence=obj.confidence, # type: ignore[attr-defined]freshness_status=obj.freshness_status, # type: ignore[attr-defined]metadata=metadata,- is_deterministic=obj.provider_name == "template", # type: ignore[attr-defined]- doc_tier=metadata.get("doc_tier"),human_notes=obj.human_notes, # type: ignore[attr-defined]parent_page_id=obj.parent_page_id, # type: ignore[attr-defined]display_order=obj.display_order, # type: ignore[attr-defined]diff --git a/packages/server/src/repowise/server/schemas/search.py b/packages/server/src/repowise/server/schemas/search.pyindex 4d9abb61b..29c67306f 100644--- a/packages/server/src/repowise/server/schemas/search.py+++ b/packages/server/src/repowise/server/schemas/search.py@@ -19,7 +19,3 @@ class SearchResultResponse(BaseModel):score: floatsnippet: strsearch_type: str- # True for deterministic template pages (the coverage tail) — drives the- # "Auto" badge on the search result card. Defaults False so older callers- # and unresolved pages read as regular LLM pages.- is_deterministic: bool = Falsediff --git a/packages/types/src/docs.ts b/packages/types/src/docs.tsindex a32c35eef..31433c267 100644--- a/packages/types/src/docs.ts+++ b/packages/types/src/docs.ts@@ -27,14 +27,6 @@ export interface DocPage {confidence: number;freshness_status: FreshnessStatus;metadata: Record<string, unknown>;- /**- * Deterministic coverage-tail pages are template-generated (zero LLM).- * `is_deterministic` is the flat marker for badging / ranking; `doc_tier`- * (2 = in-budget template, 3 = coverage tail) mirrors `metadata.doc_tier`.- * Optional so older payloads without the fields still type-check.- */- is_deterministic?: boolean;- doc_tier?: number | null;human_notes: string | null;/*** Position in the wiki outline, computed once at generation time so everydiff --git a/packages/types/src/files.ts b/packages/types/src/files.tsindex 1fb6b711b..b83e729bf 100644--- a/packages/types/src/files.ts+++ b/packages/types/src/files.ts@@ -16,14 +16,6 @@ export interface FileWikiPageRef {confidence: number;human_notes: string | null;updated_at: string | null;- /**- * Deterministic coverage-tail pages are template-generated (zero LLM).- * `is_deterministic` drives the "Auto" badge in the file docs tab;- * `doc_tier` (2/3) mirrors `metadata.doc_tier`. Optional so payloads that- * predate the fields still type-check.- */- is_deterministic?: boolean;- doc_tier?: number | null;}export interface FileHealthFinding {diff --git a/packages/types/src/overview.ts b/packages/types/src/overview.tsindex cd56e3982..1c7c37e97 100644--- a/packages/types/src/overview.ts+++ b/packages/types/src/overview.ts@@ -39,13 +39,6 @@ export interface OverviewStats {* backend deploy — treat absent as unknown rather than rendering NaN.*/doc_page_count?: number;- /**- * Of `doc_page_count`, the deterministic template-generated ("Auto") pages —- * the zero-LLM coverage tail. AI-written pages are the remainder. Both sides- * derive this from the page's `provider_name === "template"`, the same- * discriminator behind the "Auto" badge.- */- doc_auto_page_count?: number;doc_coverage_pct: number;freshness_score: number;dead_export_count: number;diff --git a/packages/ui/__tests__/coverage/freshness-table.test.tsx b/packages/ui/__tests__/coverage/freshness-table.test.tsxindex 1e088bd63..2e485ecf5 100644--- a/packages/ui/__tests__/coverage/freshness-table.test.tsx+++ b/packages/ui/__tests__/coverage/freshness-table.test.tsx@@ -57,6 +57,11 @@ describe("FreshnessTable", () => {expect(screen.getByText("stale.ts")).toBeInTheDocument();});+ it("offers only freshness tabs, no provenance filter", () => {+ render(<FreshnessTable pages={[makePage()]} />);+ expect(screen.queryByRole("tab", { name: /Auto/ })).not.toBeInTheDocument();+ });+it("invokes onRegenerate with the page id when the button is clicked", async () => {const onRegenerate = vi.fn().mockResolvedValue(undefined);render(@@ -76,69 +81,9 @@ describe("FreshnessTable", () => {).not.toBeInTheDocument();});- it("filters to auto (template) pages via the Auto tab", () => {- render(- <FreshnessTable- pages={[- makePage({ id: "1", target_path: "written.ts", provider_name: "openai" }),- makePage({ id: "2", target_path: "auto.ts", is_deterministic: true }),- ]}- />,- );- fireEvent.click(screen.getByRole("tab", { name: /Auto/ }));- expect(screen.getByText("auto.ts")).toBeInTheDocument();- expect(screen.queryByText("written.ts")).not.toBeInTheDocument();- });-- describe("selection", () => {- it("renders a checkbox per row and toggles onToggleSelect", () => {- const onToggleSelect = vi.fn();- render(- <FreshnessTable- pages={[makePage({ id: "p1", target_path: "x.ts" })]}- selectable- selectedIds={new Set()}- onToggleSelect={onToggleSelect}- />,- );- fireEvent.click(screen.getByRole("checkbox", { name: /Select x\.ts/ }));- expect(onToggleSelect).toHaveBeenCalledWith("p1");- });-- it("selects all template pages, not AI-written ones", () => {- const onSelectTemplates = vi.fn();- render(- <FreshnessTable- pages={[- makePage({ id: "t1", target_path: "a.ts", is_deterministic: true }),- makePage({ id: "t2", target_path: "b.ts", is_deterministic: true }),- makePage({ id: "w1", target_path: "c.ts", provider_name: "openai" }),- ]}- selectable- selectedIds={new Set()}- onSelectTemplates={onSelectTemplates}- />,- );- fireEvent.click(screen.getByText(/Select all 2 template pages/));- expect(onSelectTemplates).toHaveBeenCalledWith(["t1", "t2"]);- });-- it("renders the caller-provided toolbar", () => {- render(- <FreshnessTable- pages={[makePage({ is_deterministic: true })]}- selectable- selectedIds={new Set(["p1"])}- toolbar={<div data-testid="sel-toolbar">1 selected</div>}- />,- );- expect(screen.getByTestId("sel-toolbar")).toBeInTheDocument();- });-- it("does not render checkboxes or the select-all affordance when not selectable", () => {- render(<FreshnessTable pages={[makePage({ is_deterministic: true })]} />);- expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();- expect(screen.queryByText(/template pages/)).not.toBeInTheDocument();- });+ it("never renders selection checkboxes or a select-all affordance", () => {+ render(<FreshnessTable pages={[makePage()]} />);+ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();+ expect(screen.queryByText(/template pages/)).not.toBeInTheDocument();});});diff --git a/packages/ui/__tests__/docs/auto-docs-banner.test.tsx b/packages/ui/__tests__/docs/auto-docs-banner.test.tsxdeleted file mode 100644index c7cb7ce1b..000000000--- a/packages/ui/__tests__/docs/auto-docs-banner.test.tsx+++ /dev/null@@ -1,48 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import { render, screen, fireEvent } from "@testing-library/react";-import { AutoDocsBanner } from "../../src/docs/auto-docs-banner.js";--describe("AutoDocsBanner", () => {- it("renders nothing when no template pages remain", () => {- const { container } = render(- <AutoDocsBanner templateCount={0} writtenCount={12} onWriteAll={vi.fn()} />,- );- expect(container).toBeEmptyDOMElement();- });-- it("shows the count (formatted) and offers the bulk write", () => {- const onWriteAll = vi.fn();- render(- <AutoDocsBanner templateCount={1238} writtenCount={0} onWriteAll={onWriteAll} />,- );- expect(screen.getByText("1,238")).toBeInTheDocument();- expect(screen.getByText(/auto-documented from your code/i)).toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: /Write with AI/ }));- expect(onWriteAll).toHaveBeenCalledTimes(1);- });-- it("words a mixed repo honestly (pages still generated from structure)", () => {- render(- <AutoDocsBanner templateCount={5} writtenCount={40} onWriteAll={vi.fn()} />,- );- expect(screen.getByText(/still/i)).toBeInTheDocument();- });-- it("shows a dismiss control only when the host owns dismissal", () => {- const onDismiss = vi.fn();- const { rerender } = render(- <AutoDocsBanner templateCount={3} writtenCount={0} onWriteAll={vi.fn()} />,- );- expect(screen.queryByRole("button", { name: /Dismiss/ })).not.toBeInTheDocument();- rerender(- <AutoDocsBanner- templateCount={3}- writtenCount={0}- onWriteAll={vi.fn()}- onDismiss={onDismiss}- />,- );- fireEvent.click(screen.getByRole("button", { name: /Dismiss/ }));- expect(onDismiss).toHaveBeenCalledTimes(1);- });-});diff --git a/packages/ui/__tests__/docs/docs-mode-badge.test.tsx b/packages/ui/__tests__/docs/docs-mode-badge.test.tsxindex cddc42aa1..e9fcebe9f 100644--- a/packages/ui/__tests__/docs/docs-mode-badge.test.tsx+++ b/packages/ui/__tests__/docs/docs-mode-badge.test.tsx@@ -8,18 +8,13 @@ describe("DocsModeBadge", () => {expect(container).toBeEmptyDOMElement();});- it("labels a template repo as Auto docs, never fully written", () => {+ it("flags a repo whose subsystem pages are still stubs", () => {render(<DocsModeBadge mode="deterministic" />);- expect(screen.getByText("Auto docs")).toBeInTheDocument();+ expect(screen.getByText("Subsystem pages unwritten")).toBeInTheDocument();});- it("labels a partly-upgraded repo as Mixed docs", () => {- render(<DocsModeBadge mode="mixed" />);- expect(screen.getByText("Mixed docs")).toBeInTheDocument();- });-- it("labels a fully model-written repo as AI docs", () => {- render(<DocsModeBadge mode="llm" />);- expect(screen.getByText("AI docs")).toBeInTheDocument();+ it("renders nothing on a fully written wiki", () => {+ const { container } = render(<DocsModeBadge mode="llm" />);+ expect(container).toBeEmptyDOMElement();});});diff --git a/packages/ui/__tests__/docs/docs-tree.test.tsx b/packages/ui/__tests__/docs/docs-tree.test.tsxindex 929de027a..ccb1b2fc2 100644--- a/packages/ui/__tests__/docs/docs-tree.test.tsx+++ b/packages/ui/__tests__/docs/docs-tree.test.tsx@@ -290,22 +290,20 @@ describe("DocsTree", () => {expect(screen.getByText("infra-0.yml")).toBeInTheDocument();});- it("does not bucket the whole file layer on a deterministic-mode wiki", () => {- // Every file page is template-generated. The "Auto-documented" group- // exists to keep that tail from drowning AI-written pages; with no- // AI-written file pages to protect it would swallow the entire leaf level.- const auto = (id: string, path: string) =>+ it("places file pages under their module, never in a provenance bucket", () => {+ // Every page renders from one place now: file pages sit under their module+ // in the tree, with no separate "Auto-documented" group to partition into.+ const file = (id: string, path: string) =>makePage({id,target_path: path,title: path,parent_page_id: MODULE.id,display_order: 1,- is_deterministic: true,});render(<DocsTree- pages={[ROOT, LAYER_RUNTIME, MODULE, auto("f1", "runtime/engine/a.py"), auto("f2", "runtime/engine/b.py")]}+ pages={[ROOT, LAYER_RUNTIME, MODULE, file("f1", "runtime/engine/a.py"), file("f2", "runtime/engine/b.py")]}selectedPageId={null}onSelectPage={() => {}}/>,@@ -315,24 +313,4 @@ describe("DocsTree", () => {fireEvent.click(screen.getByText("runtime/engine"));expect(screen.getByText("a.py")).toBeInTheDocument();});-- it("still groups the coverage tail when AI-written file pages exist", () => {- render(- <DocsTree- pages={[- ...SPINE,- makePage({- id: "auto1",- target_path: "runtime/engine/generated.py",- title: "generated.py",- parent_page_id: MODULE.id,- is_deterministic: true,- }),- ]}- selectedPageId={null}- onSelectPage={() => {}}- />,- );- expect(screen.getByText(/Auto-documented \(1\)/)).toBeInTheDocument();- });});diff --git a/packages/ui/__tests__/lib/page-types.test.ts b/packages/ui/__tests__/lib/page-types.test.tsnew file mode 100644index 000000000..6bbc91066--- /dev/null+++ b/packages/ui/__tests__/lib/page-types.test.ts@@ -0,0 +1,60 @@+import { describe, it, expect } from "vitest";+import {+ isModelWrittenType,+ isStubPage,+ MODEL_WRITTEN_PAGE_TYPES,+} from "../../src/lib/page-types.js";++// The regenerate / write affordance is gated on `isModelWrittenType`: it renders+// on a concept-tree or onboarding page and on nothing else. These assert that+// gate by page type, so a structural page can never grow the button.++const STRUCTURAL_TYPES = [+ "file_page",+ "symbol_spotlight",+ "api_contract",+ "infra_page",+ "scc_page",+ "layer_page",+];++describe("isModelWrittenType", () => {+ it("is true for exactly the four model-written types", () => {+ for (const t of ["module_page", "repo_overview", "architecture_diagram", "onboarding"]) {+ expect(isModelWrittenType(t)).toBe(true);+ }+ expect([...MODEL_WRITTEN_PAGE_TYPES].sort()).toEqual(+ ["architecture_diagram", "module_page", "onboarding", "repo_overview"],+ );+ });++ it("is false for every structural type", () => {+ for (const t of STRUCTURAL_TYPES) expect(isModelWrittenType(t)).toBe(false);+ });++ it("is false for null / undefined / unknown", () => {+ expect(isModelWrittenType(null)).toBe(false);+ expect(isModelWrittenType(undefined)).toBe(false);+ expect(isModelWrittenType("nonsense")).toBe(false);+ });+});++describe("isStubPage", () => {+ it("is true for a model-written type still stamped template", () => {+ expect(isStubPage({ page_type: "module_page", provider_name: "template" })).toBe(true);+ });++ it("is false for a written model page (real provider)", () => {+ expect(isStubPage({ page_type: "module_page", provider_name: "openai" })).toBe(false);+ });++ it("is false for a structural page even when it is a template", () => {+ // A file page is template forever; it is never a stub awaiting prose.+ expect(isStubPage({ page_type: "file_page", provider_name: "template" })).toBe(false);+ });++ it("is false for null / undefined", () => {+ expect(isStubPage(null)).toBe(false);+ expect(isStubPage(undefined)).toBe(false);+ });+});diff --git a/packages/ui/__tests__/wiki/regenerate-button.test.tsx b/packages/ui/__tests__/wiki/regenerate-button.test.tsxindex 24e2d1785..af5469c1f 100644--- a/packages/ui/__tests__/wiki/regenerate-button.test.tsx+++ b/packages/ui/__tests__/wiki/regenerate-button.test.tsx@@ -77,30 +77,11 @@ describe("GenerateConfirmDialog (bulk overrides)", () => {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", () => {+ it("never renders a coverage bucket picker", () => {+ // Bulk generation writes every unwritten concept page as one action; a free+ // file layer has nothing to ration, so the picker is gone.render(<GenerateConfirmDialog {...base} cascadeScope="selection" />);expect(screen.queryByText("How much to write")).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "All" })).not.toBeInTheDocument();});});diff --git a/packages/ui/src/coverage/freshness-table.tsx b/packages/ui/src/coverage/freshness-table.tsxindex b0d317169..30adee15e 100644--- a/packages/ui/src/coverage/freshness-table.tsx+++ b/packages/ui/src/coverage/freshness-table.tsx@@ -1,6 +1,6 @@"use client";-import { useMemo, useState, type ReactNode } from "react";+import { useMemo, useState } from "react";import { Button } from "../ui/button";import { EmptyState } from "../shared/empty-state";import { VirtualizedTable } from "../shared/virtualized-table";@@ -14,16 +14,10 @@ import {formatConfidence,formatRelativeTime,} from "../lib/format";-import {- getPageTypeIcon,- getPageTypeLabel,- isDeterministicPage,-} from "../lib/page-types";+import { getPageTypeIcon, getPageTypeLabel } from "../lib/page-types";import type { DocPage } from "@repowise-dev/types/docs";-// "auto" is a provenance filter (template pages), orthogonal to freshness — it-// lets a user jump to the pages worth upgrading and select them in one place.-type Filter = "all" | "fresh" | "stale" | "outdated" | "auto";+type Filter = "all" | "fresh" | "stale" | "outdated";export interface FreshnessTableProps {/** Pages to render. Caller is responsible for fetching. */@@ -34,68 +28,34 @@ export interface FreshnessTableProps {* per-row pending UI state. Omit to hide the regenerate button.*/onRegenerate?: (pageId: string) => Promise<void>;- /**- * When true, each row gets a checkbox and a "select all template pages"- * affordance is shown, for launching a bulk generate. Selection state is- * owned by the caller (so the cost estimate lives with the data wiring).- */- selectable?: boolean;- selectedIds?: Set<string>;- onToggleSelect?: (pageId: string) => void;- /** Called with every template (auto) page id — powers "select all template- * pages". */- onSelectTemplates?: (templateIds: string[]) => void;- onClearSelection?: () => void;- /** Rendered above the table — typically the running count + cost + a- * "Write selected" action the caller builds from the selection. */- toolbar?: ReactNode;}export function FreshnessTable({pages,onRegenerate,- selectable = false,- selectedIds,- onToggleSelect,- onSelectTemplates,- onClearSelection,- toolbar,}: FreshnessTableProps) {const [filter, setFilter] = useState<Filter>("all");const [regenerating, setRegenerating] = useState<Set<string>>(new Set());- // Template (auto) page ids power the "select all template pages" affordance.- const templateIds = useMemo(- () => pages.filter((p) => isDeterministicPage(p)).map((p) => p.id),- [pages],- );- const selectedCount = selectedIds?.size ?? 0;- const allTemplatesSelected =- templateIds.length > 0 && templateIds.every((id) => selectedIds?.has(id));-// The filter is a set of discrete status toggle buttons, not a free-text// search input, so there are no rapid keystroke updates to debounce — each// click is a single discrete state change. We only need to memoize the- // derived data so the four count scans and the filter scan don't re-run on+ // derived data so the count scans and the filter scan don't re-run on// unrelated re-renders (e.g. per-row regenerate state changes).const counts = useMemo<Record<Filter, number>>(() => {let fresh = 0;let stale = 0;let outdated = 0;- let auto = 0;for (const p of pages) {if (p.freshness_status === "fresh") fresh += 1;else if (p.freshness_status === "stale") stale += 1;else if (p.freshness_status === "outdated") outdated += 1;- // Provenance is independent of freshness, so count it separately.- if (isDeterministicPage(p)) auto += 1;}- return { all: pages.length, fresh, stale, outdated, auto };+ return { all: pages.length, fresh, stale, outdated };}, [pages]);const filtered = useMemo(() => {if (filter === "all") return pages;- if (filter === "auto") return pages.filter((p) => isDeterministicPage(p));return pages.filter((p) => p.freshness_status === filter);}, [pages, filter]);@@ -117,21 +77,15 @@ export function FreshnessTable({<div className="space-y-4"><div className="flex flex-wrap items-center justify-between gap-2"><div role="tablist" aria-label="Filter pages" className="flex flex-wrap items-center gap-1">- {(["all", "fresh", "stale", "outdated", "auto"] as Filter[]).map((f) => {+ {(["all", "fresh", "stale", "outdated"] as Filter[]).map((f) => {const count = counts[f];- const label =- f === "all" ? "All" : f === "auto" ? "Auto" : statusLabel(f as FreshnessStatus);+ const label = f === "all" ? "All" : statusLabel(f as FreshnessStatus);return (<buttonkey={f}role="tab"aria-selected={filter === f}onClick={() => setFilter(f)}- title={- f === "auto"- ? "Pages generated from code structure (upgrade candidates)"- : undefined- }className={cn("rounded-md px-3 py-1.5 text-xs font-medium transition-colors",filter === f@@ -145,37 +99,8 @@ export function FreshnessTable({);})}</div>-- {selectable && templateIds.length > 0 && (- <div className="flex items-center gap-3 text-xs">- <button- type="button"- onClick={() =>- allTemplatesSelected- ? onClearSelection?.()- : onSelectTemplates?.(templateIds)- }- className="font-medium text-[var(--color-accent-primary)] hover:text-[var(--color-accent-hover)]"- >- {allTemplatesSelected- ? "Clear selection"- : `Select all ${templateIds.length} template pages`}- </button>- {selectedCount > 0 && !allTemplatesSelected && onClearSelection && (- <button- type="button"- onClick={() => onClearSelection()}- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]"- >- Clear- </button>- )}- </div>- )}</div>- {selectable && toolbar}-{filtered.length === 0 ? (<EmptyState title="No pages" description="No pages match this filter." />) : (@@ -189,11 +114,6 @@ export function FreshnessTable({headerClassName="bg-[var(--color-bg-surface)]"header={<tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">- {selectable && (- <th scope="col" className="w-10 px-4 py-2.5">- <span className="sr-only">Select</span>- </th>- )}<th scope="col" className="px-4 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">Page</th>@@ -217,23 +137,7 @@ export function FreshnessTable({renderRow={(page) => {const status = page.freshness_status as FreshnessStatus;return (- <tr- className={cn(- "group border-b border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0",- selectable && selectedIds?.has(page.id) && "bg-[var(--color-accent-muted)]",- )}- >- {selectable && (- <td className="px-4 py-2.5">- <input- type="checkbox"- checked={selectedIds?.has(page.id) ?? false}- onChange={() => onToggleSelect?.(page.id)}- className="accent-[var(--color-accent-fill)]"- aria-label={`Select ${page.target_path}`}- />- </td>- )}+ <tr className="group border-b border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0"><td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[220px] max-w-[480px]"><div className="truncate group-hover:underline underline-offset-2" title={page.target_path}>{page.target_path}</div>{(() => { const TypeIcon = getPageTypeIcon(page.page_type); return (diff --git a/packages/ui/src/dashboard/quick-actions.tsx b/packages/ui/src/dashboard/quick-actions.tsxindex 57d6bcd3b..bf320d92f 100644--- a/packages/ui/src/dashboard/quick-actions.tsx+++ b/packages/ui/src/dashboard/quick-actions.tsx@@ -1,7 +1,7 @@"use client";import { useMemo, useState, type ReactNode, type ComponentType } from "react";-import { RefreshCw, Trash2, AlertTriangle, Zap, Sparkles } from "lucide-react";+import { RefreshCw, Trash2, AlertTriangle, Zap } from "lucide-react";import { Button } from "../ui/button";import {Dialog,@@ -67,7 +67,7 @@ function estimateCost(pageCount: number, modelName: string) {return { inputTokens, outputTokens, cost };}-export type QuickActionKey = "sync" | "resync" | "dead-code" | "generate-docs";+export type QuickActionKey = "sync" | "resync" | "dead-code";export interface QuickActionDef {key: QuickActionKey;@@ -80,20 +80,6 @@ export interface QuickActionDef {confirmDescription: string;}-/** Bulk "Write with AI" entry point. `needsConfirm` is false because the- * wrapper opens its own cost-aware confirm dialog (real `/generate/estimate` +- * cascade + no-provider routing), not the heuristic panel below. */-export const GENERATE_DOCS_ACTION: QuickActionDef = {- key: "generate-docs",- label: "Write with AI",- description: "Upgrade pages generated from structure to model-written prose",- icon: Sparkles,- destructive: false,- needsConfirm: false,- confirmTitle: "",- confirmDescription: "",-};-export const DEFAULT_QUICK_ACTIONS: QuickActionDef[] = [{key: "sync",diff --git a/packages/ui/src/docs/auto-docs-banner.tsx b/packages/ui/src/docs/auto-docs-banner.tsxdeleted file mode 100644index a587013bd..000000000--- a/packages/ui/src/docs/auto-docs-banner.tsx+++ /dev/null@@ -1,72 +0,0 @@-"use client";--import { Sparkles, X } from "lucide-react";-import { formatNumber } from "../lib/format";-import { cn } from "../lib/cn";--/**- * A thin, one-line strip shown above the docs reader when a repo still has- * pages generated from structure (templates). It reframes an index-only wiki as- * "auto-documented, upgrade me" rather than empty, and offers the bulk write,- * without stealing vertical space from the reader.- *- * Presentational only: the caller counts template vs written pages, owns the- * launch (`onWriteAll`), and owns dismissal (`onDismiss`) so it can persist- * "don't show this again" per repo instead of nagging on every visit.- */-export function AutoDocsBanner({- templateCount,- writtenCount,- onWriteAll,- onDismiss,- className,-}: {- /** Number of pages still rendered from templates (the upgrade target). */- templateCount: number;- /** Number of AI-written pages, used to word the "mixed" case honestly. */- writtenCount: number;- onWriteAll: () => void;- /** Omit to hide the dismiss control (host owns whether it persists). */- onDismiss?: () => void;- className?: string;-}) {- if (templateCount <= 0) return null;-- const mixed = writtenCount > 0;- const pageWord = templateCount === 1 ? "page" : "pages";-- return (- <div- className={cn(- "flex items-center gap-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-1.5 text-xs sm:px-6",- className,- )}- >- <Sparkles className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)]" />- <span className="min-w-0 flex-1 truncate text-[var(--color-text-secondary)]">- <span className="font-medium text-[var(--color-text-primary)]">- {formatNumber(templateCount)}- </span>{" "}- {mixed ? `${pageWord} still` : pageWord} auto-documented from your code.- Upgrade to AI-written prose for the how and why.- </span>- <button- type="button"- onClick={onWriteAll}- className="shrink-0 font-medium text-[var(--color-accent-primary)] hover:text-[var(--color-accent-hover)]"- >- Write with AI- </button>- {onDismiss && (- <button- type="button"- onClick={onDismiss}- aria-label="Dismiss"- className="shrink-0 rounded p-0.5 text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-inset)] hover:text-[var(--color-text-secondary)]"- >- <X className="h-3.5 w-3.5" />- </button>- )}- </div>- );-}diff --git a/packages/ui/src/docs/docs-mode-badge.tsx b/packages/ui/src/docs/docs-mode-badge.tsxindex 287048ef5..d8e34b3ee 100644--- a/packages/ui/src/docs/docs-mode-badge.tsx+++ b/packages/ui/src/docs/docs-mode-badge.tsx@@ -1,45 +1,17 @@"use client";-import { Cog, Sparkles, Blend } from "lucide-react";+import { Cog } from "lucide-react";import { cn } from "../lib/cn";-/** How a repo's wiki was written. `deterministic` and `mixed` both come from- * the repos API `docs_mode: "deterministic"` (which only flips to `llm` once- * no template page remains); a caller that can count provenance passes- * `mixed` so a partly-upgraded repo never reads as fully written. */-export type DocsMode = "none" | "deterministic" | "mixed" | "llm";+/** How a repo's wiki stands, from the repos API `docs_mode`. `deterministic`+ * means the subsystem pages are still structural stubs; it flips to `llm` once+ * a model has written every one of them. */+export type DocsMode = "none" | "deterministic" | "llm";-const CONFIG: Record<- Exclude<DocsMode, "none">,- { label: string; title: string; icon: typeof Cog; className: string }-> = {- deterministic: {- label: "Auto docs",- title:- "Generated from code structure (no AI). Upgrade individual pages, or write them all, with a model.",- icon: Cog,- className:- "border-[var(--color-info)]/35 bg-[var(--color-info)]/10 text-[var(--color-info)]",- },- mixed: {- label: "Mixed docs",- title:- "Some pages are AI-written, the rest are generated from code structure. Write the remaining ones with a model.",- icon: Blend,- className:- "border-[var(--color-accent-primary)]/35 bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]",- },- llm: {- label: "AI docs",- title: "Written by AI from the code and its context.",- icon: Sparkles,- className:- "border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]",- },-};--/** A small provenance chip for a repo header. Renders nothing when there are- * no docs yet (`none`), so the header stays quiet until a repo is documented. */+/** A small chip for a repo header, shown only while the subsystem pages are+ * unwritten. A fully written wiki (`llm`) and an undocumented repo (`none`)+ * both render nothing: a badge every repo carries says nothing, so the header+ * stays quiet unless there is prose still to write. */export function DocsModeBadge({mode,className,@@ -47,19 +19,18 @@ export function DocsModeBadge({mode: DocsMode;className?: string;}) {- if (mode === "none") return null;- const { label, title, icon: Icon, className: tone } = CONFIG[mode];+ if (mode !== "deterministic") return null;return (<span- title={title}+ title="The subsystem pages are still generated from code structure. Write them with a model for the how and why."className={cn("inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider",- tone,+ "border-[var(--color-info)]/35 bg-[var(--color-info)]/10 text-[var(--color-info)]",className,)}>- <Icon className="h-2.5 w-2.5" />- {label}+ <Cog className="h-2.5 w-2.5" />+ Subsystem pages unwritten</span>);}diff --git a/packages/ui/src/docs/docs-reader.tsx b/packages/ui/src/docs/docs-reader.tsxindex 461eb60b0..25920b176 100644--- a/packages/ui/src/docs/docs-reader.tsx+++ b/packages/ui/src/docs/docs-reader.tsx@@ -10,20 +10,11 @@ import {Loader2,Layers,FileInput,- Sparkles,- Cog,} from "lucide-react";import type { DocPage } from "@repowise-dev/types/docs";import { cn } from "../lib/cn";import { formatRelativeTime, formatTokens } from "../lib/format";-import {- getPageTypeLabel,- isDeterministicPage,- DETERMINISTIC_BADGE_LABEL,- DETERMINISTIC_BADGE_TITLE,- AI_WRITTEN_BADGE_LABEL,- AI_WRITTEN_BADGE_TITLE,-} from "../lib/page-types";+import { getPageTypeLabel } from "../lib/page-types";import { computeDocNav } from "./doc-nav";import { filterMarkdownByPersona, type ReaderPersona } from "./reader-persona";import { WikiMarkdown } from "../wiki/wiki-markdown";@@ -335,26 +326,7 @@ function DocsReaderBody({<span className="rounded-full bg-[var(--color-bg-elevated)] px-2 py-0.5 uppercase tracking-wider">{getPageTypeLabel(page.page_type)}</span>- {isDeterministicPage(page) ? (- <>- <span- className="inline-flex items-center gap-1 rounded-full border border-[var(--color-info)]/35 bg-[var(--color-info)]/10 px-2 py-0.5 uppercase tracking-wider text-[var(--color-info)]"- title={DETERMINISTIC_BADGE_TITLE}- >- <Cog className="h-2.5 w-2.5" />- {DETERMINISTIC_BADGE_LABEL}- </span>- {upgradeSlot}- </>- ) : (- <span- className="inline-flex items-center gap-1 rounded-full border border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] px-2 py-0.5 uppercase tracking-wider text-[var(--color-accent-primary)]"- title={AI_WRITTEN_BADGE_TITLE}- >- <Sparkles className="h-2.5 w-2.5" />- {AI_WRITTEN_BADGE_LABEL}- </span>- )}+ {upgradeSlot}{moduleSeg && (<buttononClick={() => goToPageId(moduleSeg.pageId!)}diff --git a/packages/ui/src/docs/docs-tree.tsx b/packages/ui/src/docs/docs-tree.tsxindex 365d4ce07..5c65dddb0 100644--- a/packages/ui/src/docs/docs-tree.tsx+++ b/packages/ui/src/docs/docs-tree.tsx@@ -18,7 +18,6 @@ import {getOnboardingSlot,getPageTypeIcon,getPageTypeLabel,- isDeterministicPage,type OnboardingSlot,} from "../lib/page-types";import { RAW_GRAPH_ID, displayLabel, treeLabel } from "./page-labels";@@ -30,12 +29,6 @@ import type { DocPage } from "@repowise-dev/types/docs";// real target_path (which never starts with "@") so directory lookups don't// collide with module paths.const ONBOARDING_DIR_KEY = "@onboarding";-// Synthetic key for the collapsed "Auto-documented" group that collects the-// deterministic coverage-tail file pages (~1,400 on a large repo). Namespaced-// with "@group:" so its dir keys never collide with real target_paths and it-// is NOT auto-expanded — the tail stays out of the way while browsing the-// AI-written pages, and default-hidden behind the filter toggle.-const AUTO_GROUP_KEY = "@group:auto";// Tree expansion survives reloads (per-browser, not per-repo — paths rarely// collide across repos and the fallback is just the default expansion).const EXPANDED_DIRS_KEY = "repowise:docs-tree-expanded";@@ -255,111 +248,6 @@ function buildTree(pages: DocPage[]): TreeNode[] {return root;}-// ----------------------------------------------------------------------------// Auto-documented (deterministic coverage tail) group-// ----------------------------------------------------------------------------//-// The tail can be ~1,400 file pages. Scattering them through the module /-// folder tree drowns the AI-written pages, so they are pulled out of the main-// tree (see `partitionDeterministic`) and nested by directory under one-// collapsed group. The group is only shown when the reader opts in via the-// filter toggle.--function buildAutoGroup(deterministicPages: DocPage[]): TreeNode | null {- const filePages = deterministicPages.filter((p) => p.target_path);- if (filePages.length === 0) return null;-- const dirMap = new Map<string, TreeNode>();- const roots: TreeNode[] = [];-- function ensureDir(dirPath: string): TreeNode {- const existing = dirMap.get(dirPath);- if (existing) return existing;- const parts = dirPath.split("/");- const node: TreeNode = {- name: parts[parts.length - 1] ?? dirPath,- // Prefix so these dir keys never collide with the main tree's dir nodes- // (which key on the raw target_path) or with real page ids.- path: `${AUTO_GROUP_KEY}:${dirPath}`,- isDir: true,- children: [],- };- dirMap.set(dirPath, node);- if (parts.length > 1) {- ensureDir(parts.slice(0, -1).join("/")).children.push(node);- } else {- roots.push(node);- }- return node;- }-- for (const page of filePages) {- const parts = page.target_path.split("/");- const fileName = parts[parts.length - 1] ?? page.target_path;- const leaf: TreeNode = {- name: fileName,- path: page.id,- isDir: false,- page,- children: [],- };- if (parts.length > 1) {- ensureDir(parts.slice(0, -1).join("/")).children.push(leaf);- } else {- roots.push(leaf);- }- }-- function sortRec(nodes: TreeNode[]) {- nodes.sort((a, b) => {- if (a.isDir && !b.isDir) return -1;- if (!a.isDir && b.isDir) return 1;- return a.name.localeCompare(b.name);- });- for (const n of nodes) if (n.children.length > 0) sortRec(n.children);- }- sortRec(roots);-- return {- name: `Auto-documented (${filePages.length})`,- path: AUTO_GROUP_KEY,- isDir: true,- children: roots,- };-}--// Split off the deterministic coverage-tail file pages so the main tree is-// built only from the human/AI-written pages. Deterministic pages are always-// file_pages, so nothing else is affected.-//-// The split only makes sense when there ARE written file pages to protect. On-// a deterministic-mode wiki (`repowise init --index-only`) every file page is-// template-generated, and a per-page predicate with no repo-level guard swept-// the entire file layer into one collapsed "Auto-documented" bucket — the-// tree's whole leaf level, hidden behind one toggle. That condition is read-// off the pages here rather than threaded in as repo `docs_mode`, because the-// pages already answer the question and both host apps would otherwise have to-// fetch and forward a field they have no other use for.-function partitionDeterministic(pages: DocPage[]): {- regular: DocPage[];- deterministic: DocPage[];-} {- const regular: DocPage[] = [];- const deterministic: DocPage[] = [];- for (const page of pages) {- if (page.page_type === "file_page" && isDeterministicPage(page)) {- deterministic.push(page);- } else {- regular.push(page);- }- }- const anyWrittenFilePage = regular.some((p) => p.page_type === "file_page");- if (deterministic.length > 0 && !anyWrittenFilePage) {- return { regular: pages, deterministic: [] };- }- return { regular, deterministic };-}-// ---------------------------------------------------------------------------// Domain (semantic) tree — read from the store, not derived here// ---------------------------------------------------------------------------@@ -814,25 +702,11 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc// Per-row freshness dots are opt-in noise — off by default. Turning this on// (or filtering by status) is how a reader audits staleness across the tree.const [showFreshness, setShowFreshness] = useState(false);- // The deterministic coverage tail (~1,400 auto pages on a large repo) lives- // in its own collapsed "Auto-documented" group, so it's shown by default- // (discoverable without hunting through the filter) while staying out of the- // way; the reader can hide it entirely via this toggle.- const [showDeterministic, setShowDeterministic] = useState(true);-- const { regular, deterministic } = useMemo(- () => partitionDeterministic(pages),- [pages],++ const tree = useMemo(+ () => (viewMode === "domain" ? buildStoredTree(pages) : buildTree(pages)),+ [pages, viewMode],);- const autoGroup = useMemo(() => buildAutoGroup(deterministic), [deterministic]);-- const tree = useMemo(() => {- // Build the main tree from the human/AI-written pages only, then append the- // collapsed auto group when the reader has opted in.- const base = viewMode === "domain" ? buildStoredTree(regular) : buildTree(regular);- if (showDeterministic && autoGroup) base.push(autoGroup);- return base;- }, [regular, viewMode, showDeterministic, autoGroup]);const filteredTree = useMemo(() => filterTree(tree, search, typeFilter, freshnessFilter),[tree, search, typeFilter, freshnessFilter],@@ -852,11 +726,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Docconst freshCount = pages.filter((p) => p.freshness_status === "fresh").length;const needAttention = totalPages - freshCount;const activeFilterCount =- (typeFilter !== "all" ? 1 : 0) +- (freshnessFilter !== "all" ? 1 : 0) +- // Auto-documented pages show by default; hiding them is the non-default- // (restricting) state, so count that as an active filter.- (showDeterministic ? 0 : 1);+ (typeFilter !== "all" ? 1 : 0) + (freshnessFilter !== "all" ? 1 : 0);return (<div className={cn("flex flex-col h-full", className)}>@@ -961,17 +831,6 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc/>Show freshness dots on every row</label>- {deterministic.length > 0 && (- <label className="flex items-center gap-1.5 text-[10px] text-[var(--color-text-tertiary)] cursor-pointer select-none">- <input- type="checkbox"- checked={showDeterministic}- onChange={(e) => setShowDeterministic(e.target.checked)}- className="h-3 w-3 accent-[var(--color-accent-primary)]"- />- Show {deterministic.length} auto-documented pages- </label>- )}</div>)}diff --git a/packages/ui/src/files/file-doc-tab.tsx b/packages/ui/src/files/file-doc-tab.tsxindex b86833024..51b2bfaf2 100644--- a/packages/ui/src/files/file-doc-tab.tsx+++ b/packages/ui/src/files/file-doc-tab.tsx@@ -2,11 +2,6 @@ import type { ReactNode } from "react";import { BookOpen } from "lucide-react";import { EmptyState } from "../shared/empty-state";import { Badge } from "../ui/badge";-import {- isDeterministicPage,- DETERMINISTIC_BADGE_LABEL,- DETERMINISTIC_BADGE_TITLE,-} from "../lib/page-types";import { formatRelativeTime } from "../lib/format";import type { FileWikiPageRef } from "@repowise-dev/types/files";@@ -44,11 +39,6 @@ export function FileDocTab({ wikiPage, docSlot, wikiHref }: FileDocTabProps) {>{wikiPage.freshness_status}</Badge>- {isDeterministicPage(wikiPage) && (- <Badge variant="outline" className="text-[10px] h-5" title={DETERMINISTIC_BADGE_TITLE}>- {DETERMINISTIC_BADGE_LABEL}- </Badge>- )}{wikiPage.updated_at && (<spanclassName="text-xs text-[var(--color-text-tertiary)]"diff --git a/packages/ui/src/lib/page-types.ts b/packages/ui/src/lib/page-types.tsindex aba29d421..c6917aea2 100644--- a/packages/ui/src/lib/page-types.ts+++ b/packages/ui/src/lib/page-types.ts@@ -42,42 +42,39 @@ export function getPageTypeLabel(pageType: string): string {}// ----------------------------------------------------------------------------// Deterministic ("auto") pages+// Model-written pages// ---------------------------------------------------------------------------//-// The Phase G coverage tail gives every parsed source file a template-generated-// page (zero LLM) so the whole tree is browsable and retrievable. These are-// factual but terse; the UI badges them "Auto" and the docs tree groups them so-// human browsing of the AI-written pages stays clean.+// Every file / symbol / api / infra / scc / layer page renders from structure+// and is a template forever. Only the concept tree and onboarding are written+// by a model, so "does this page have prose yet" is a question that only makes+// sense for these four types. This mirrors core's MODEL_WRITTEN_PAGE_TYPES.-/** Fields any surface needs to recognise a deterministic page. All optional so- * older payloads (DocPage / FileWikiPageRef / SearchResultResponse) type-check. */-export interface DeterministicMarker {- is_deterministic?: boolean;- doc_tier?: number | null;- provider_name?: string;+export const MODEL_WRITTEN_PAGE_TYPES = new Set([+ "module_page",+ "repo_overview",+ "architecture_diagram",+ "onboarding",+]);++/** True for the page types a model writes (the concept tree and onboarding).+ * The regenerate affordance renders only on these; every other type is+ * structural and has nothing to write into. */+export function isModelWrittenType(pageType: string | null | undefined): boolean {+ return !!pageType && MODEL_WRITTEN_PAGE_TYPES.has(pageType);}-/**- * True when a page is a deterministic (auto, no-LLM) page. Prefers the flat- * `is_deterministic` flag; falls back to `doc_tier >= 2` or the `template`- * provider for rows/payloads that only carry those.- */-export function isDeterministicPage(page: DeterministicMarker | null | undefined): boolean {- if (!page) return false;- if (page.is_deterministic) return true;- if (typeof page.doc_tier === "number" && page.doc_tier >= 2) return true;+/** True when a model-written page is still a structural stub (no prose yet).+ * Scoped to the model-written types: a stub carries `provider_name ===+ * "template"`, a written page a real provider. Returns false for every+ * structural page type, which is never a stub in this sense. */+export function isStubPage(+ page: { page_type?: string; provider_name?: string } | null | undefined,+): boolean {+ if (!page || !isModelWrittenType(page.page_type)) return false;return page.provider_name === "template";}-export const DETERMINISTIC_BADGE_LABEL = "Auto";-export const DETERMINISTIC_BADGE_TITLE =- "Auto-documented from code structure (no AI). Factual but terse.";--export const AI_WRITTEN_BADGE_LABEL = "AI";-export const AI_WRITTEN_BADGE_TITLE =- "Written by AI from the code and its context.";-// ---------------------------------------------------------------------------// Onboarding collection// ---------------------------------------------------------------------------diff --git a/packages/ui/src/wiki/regenerate-button.tsx b/packages/ui/src/wiki/regenerate-button.tsxindex d2ce2ab11..9a0dee2b1 100644--- a/packages/ui/src/wiki/regenerate-button.tsx+++ b/packages/ui/src/wiki/regenerate-button.tsx@@ -159,15 +159,6 @@ 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. */@@ -199,10 +190,6 @@ export function GenerateConfirmDialog({description,confirmLabel,cascadeScope = "page",- coverageOptions,- coveragePct,- onCoverageChange,- recommendedCoverage,cascade,onCascadeChange,estimate,@@ -218,8 +205,6 @@ 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}>@@ -268,44 +253,6 @@ 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/app/repos/[id]/docs/coverage/page.tsx b/packages/web/src/app/repos/[id]/docs/coverage/page.tsxindex 0bdde7ba9..ed3590097 100644--- a/packages/web/src/app/repos/[id]/docs/coverage/page.tsx+++ b/packages/web/src/app/repos/[id]/docs/coverage/page.tsx@@ -22,8 +22,7 @@ export default async function CoveragePage({try {// Auto-paginate past the 500-item API cap so the counts, donut, and the- // "select all template pages" affordance see every page, not just the first- // page of results.+ // freshness table see every page, not just the first page of results.pages = await listAllPages(id);} catch {// API unavailablediff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex 1bb75ba16..c535f8625 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -54,10 +54,8 @@ export default async function OverviewPage({ params }: Props) {const isFresh = stats.file_count === 0;// Fall back to the sync page count so the tile still reads on a server that- // predates the AI/auto split; the split line just hides.+ // predates the doc page count.const docPages = stats.doc_page_count ?? sync.page_count ?? 0;- const autoPages = stats.doc_auto_page_count;- const aiPages = autoPages != null ? Math.max(0, docPages - autoPages) : null;const kpis: KpiItem[] = [{@@ -76,12 +74,6 @@ export default async function OverviewPage({ params }: Props) {label: "Docs",value: formatNumber(docPages),href: `/repos/${id}/docs`,- // The AI/auto split is the interesting part of a page count: it says how- // much of the wiki a model wrote vs what was templated from structure.- description:- docPages > 0 && aiPages != null && autoPages != null- ? `${formatNumber(aiPages)} AI · ${formatNumber(autoPages)} auto`- : undefined,},{label: "Dead Exports",@@ -143,9 +135,6 @@ export default async function OverviewPage({ params }: Props) {modelName={providers?.active.model ?? sync.last_sync_model ?? ""}lastSyncAt={sync.last_sync_at}lastResyncAt={sync.last_resync_at}- // Offer the bulk "Write with AI" action only when template (auto)- // pages actually exist to upgrade.- docsMode={autoPages != null && autoPages > 0 ? "deterministic" : undefined}/>)}diff --git a/packages/web/src/components/coverage/freshness-table-wrapper.tsx b/packages/web/src/components/coverage/freshness-table-wrapper.tsxindex 8ee1bfa3c..e29cc2346 100644--- a/packages/web/src/components/coverage/freshness-table-wrapper.tsx+++ b/packages/web/src/components/coverage/freshness-table-wrapper.tsx@@ -1,20 +1,14 @@"use client";-import { useCallback, useMemo, useState } from "react";+import { useCallback, useState } from "react";import { useRouter } from "next/navigation";import { toast } from "sonner";-import { Sparkles } from "lucide-react";import {FreshnessTable,type FreshnessTableProps,} from "@repowise-dev/ui/coverage/freshness-table";-import { AutoDocsBanner } from "@repowise-dev/ui/docs/auto-docs-banner";-import { isDeterministicPage } from "@repowise-dev/ui/lib/page-types";-import { Button } from "@repowise-dev/ui/ui/button";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";-import { BulkGenerateConfirm } from "@/components/docs/bulk-generate-confirm";-import { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";import { regeneratePage } from "@/lib/api/pages";export function FreshnessTableWithRegenerate({@@ -22,40 +16,12 @@ export function FreshnessTableWithRegenerate({repoId,}: Pick<FreshnessTableProps, "pages"> & { repoId: string }) {const router = useRouter();- const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());- // A single active job — a per-row regenerate or a bulk write — shown above- // the table. On completion we revalidate the (server-rendered) page list.+ // A single active job (a per-row regenerate) shown above the table. On+ // completion we revalidate the (server-rendered) page list.const [activeJobId, setActiveJobId] = useState<string | null>(null);- const bulk = useBulkGenerate(repoId);+ const busy = activeJobId != null;- const templateCount = useMemo(- () => pages.filter((p) => isDeterministicPage(p)).length,- [pages],- );- const writtenCount = pages.length - templateCount;-- const jobId = activeJobId ?? bulk.jobId;- // Only one job runs at a time (the server 409s a second), so refuse to launch- // another while one is in flight rather than orphaning its progress slot.- const busy = jobId != null;-- const toggleSelect = useCallback((pageId: string) => {- setSelectedIds((prev) => {- const next = new Set(prev);- if (next.has(pageId)) next.delete(pageId);- else next.add(pageId);- return next;- });- }, []);-- const selectTemplates = useCallback((ids: string[]) => {- setSelectedIds(new Set(ids));- }, []);-- const clearSelection = useCallback(() => setSelectedIds(new Set()), []);-- // Task 1.3: per-row regenerate now launches a tracked job with a toast and- // error handling, instead of firing and forgetting.+ // Per-row regenerate launches a tracked job with a toast and error handling.const handleRegenerate = useCallback(async (pageId: string) => {if (busy) {@@ -73,83 +39,19 @@ export function FreshnessTableWithRegenerate({[busy],);- const selectedList = useMemo(() => [...selectedIds], [selectedIds]);-- function writeSelected() {- if (busy || selectedList.length === 0) return;- const n = selectedList.length;- // Price on open (the confirm dialog), not live per checkbox — the estimate- // endpoint is heavy. The toolbar shows the count only.- bulk.begin(- { kind: "page_ids", page_ids: selectedList },- { label: `${n} selected ${n === 1 ? "page" : "pages"}`, defaultCascade: "none" },- );- }-- function writeAllTemplates() {- if (busy || templateCount === 0) return;- // 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 =- selectedIds.size > 0 ? (- <div className="flex flex-wrap items-center justify-between gap-3 rounded-md border border-[var(--color-border-active)] bg-[var(--color-accent-muted)] px-3 py-2">- <span className="text-sm text-[var(--color-text-primary)]">- <span className="font-medium">{selectedIds.size}</span>{" "}- {selectedIds.size === 1 ? "page" : "pages"} selected- </span>- <Button- size="sm"- onClick={writeSelected}- disabled={busy}- className="h-7 gap-1.5 text-xs"- >- <Sparkles className="h-3.5 w-3.5" />- Write selected- </Button>- </div>- ) : null;-return (<div className="space-y-3">- {templateCount > 0 && (- <AutoDocsBanner- templateCount={templateCount}- writtenCount={writtenCount}- onWriteAll={writeAllTemplates}- className="rounded-md border"- />- )}-- {jobId && (+ {activeJobId && (<GenerationProgressWrapper- jobId={jobId}+ jobId={activeJobId}onDone={() => {setActiveJobId(null);- bulk.clearJob();- clearSelection();router.refresh();}}/>)}- <FreshnessTable- pages={pages}- onRegenerate={handleRegenerate}- selectable- selectedIds={selectedIds}- onToggleSelect={toggleSelect}- onSelectTemplates={selectTemplates}- onClearSelection={clearSelection}- toolbar={toolbar}- />-- <BulkGenerateConfirm flow={bulk} repoId={repoId} title="Write selected pages with AI" />+ <FreshnessTable pages={pages} onRegenerate={handleRegenerate} /></div>);}diff --git a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx b/packages/web/src/components/dashboard/quick-actions-wrapper.tsxindex d54664b1e..91905d384 100644--- a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx+++ b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx@@ -1,22 +1,18 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useState } from "react";import { useRouter } from "next/navigation";import { toast } from "sonner";import {QuickActions as QuickActionsShell,DEFAULT_QUICK_ACTIONS,- GENERATE_DOCS_ACTION,type QuickActionKey,} from "@repowise-dev/ui/dashboard/quick-actions";import { syncRepo, fullResyncRepo } from "@/lib/api/repos";import { listJobs } from "@/lib/api/jobs";import { analyzeDeadCode } from "@/lib/api/dead-code";import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";-import { BulkGenerateConfirm } from "@/components/docs/bulk-generate-confirm";-import { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";-import type { RepoResponse } from "@/lib/api/types";interface Props {repoId: string;@@ -25,16 +21,11 @@ interface Props {modelName?: string;lastSyncAt?: string | null;lastResyncAt?: string | null;- /** When "deterministic" the repo still has template pages, so the "Write with- * AI" bulk action is offered. */- docsMode?: RepoResponse["docs_mode"];}/** Human label for an action key, for toast copy. */function labelFor(key: QuickActionKey): string {- return (- [GENERATE_DOCS_ACTION, ...DEFAULT_QUICK_ACTIONS].find((a) => a.key === key)?.label ?? key- );+ return DEFAULT_QUICK_ACTIONS.find((a) => a.key === key)?.label ?? key;}export function QuickActionsWrapper({@@ -44,14 +35,12 @@ export function QuickActionsWrapper({modelName = "",lastSyncAt,lastResyncAt,- docsMode,}: Props) {const router = useRouter();const [activeJobId, setActiveJobId] = useState<string | null>(null);// Which action started the job on screen, so its completion can be reported// and refreshed in its own terms rather than as a generic doc generation.const [activeKey, setActiveKey] = useState<QuickActionKey | null>(null);- const bulk = useBulkGenerate(repoId);// Hydrate from any in-flight job so refreshes don't lose progress visibility.useEffect(() => {@@ -74,14 +63,6 @@ export function QuickActionsWrapper({};}, [repoId]);- const actions = useMemo(- () =>- docsMode === "deterministic"- ? [GENERATE_DOCS_ACTION, ...DEFAULT_QUICK_ACTIONS]- : DEFAULT_QUICK_ACTIONS,- [docsMode],- );-function startWatching(jobId: string, key: QuickActionKey | null) {setActiveJobId(jobId);setActiveKey(key);@@ -91,7 +72,6 @@ export function QuickActionsWrapper({const key = activeKey;setActiveJobId(null);setActiveKey(null);- bulk.clearJob();if (key === "dead-code") {if (status === "completed") toast.success("Dead code scan finished");else if (status === "failed") toast.error("Dead code scan failed");@@ -103,16 +83,6 @@ export function QuickActionsWrapper({}async function handleAction(key: QuickActionKey) {- if (key === "generate-docs") {- // 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 {if (key === "sync") {const job = await syncRepo(repoId);@@ -152,11 +122,9 @@ export function QuickActionsWrapper({}}- // A bulk generate job shares the same progress slot as sync/resync.- const jobId = activeJobId ?? bulk.jobId;- const activeSlot = jobId ? (+ const activeSlot = activeJobId ? (<GenerationProgressWrapper- jobId={jobId}+ jobId={activeJobId}repoName={repoName}// A dead-code scan runs the index-only pipeline, so the generic// "Documentation updated - 0 pages generated" toast would describe it@@ -167,17 +135,14 @@ export function QuickActionsWrapper({) : null;return (- <>- <QuickActionsShell- actions={actions}- onAction={handleAction}- lastSyncAt={lastSyncAt}- lastResyncAt={lastResyncAt}- pageCount={pageCount}- modelName={modelName}- activeJobSlot={activeSlot}- />- <BulkGenerateConfirm flow={bulk} repoId={repoId} />- </>+ <QuickActionsShell+ actions={DEFAULT_QUICK_ACTIONS}+ onAction={handleAction}+ lastSyncAt={lastSyncAt}+ lastResyncAt={lastResyncAt}+ pageCount={pageCount}+ modelName={modelName}+ activeJobSlot={activeSlot}+ />);}diff --git a/packages/web/src/components/docs/bulk-generate-button.tsx b/packages/web/src/components/docs/bulk-generate-button.tsxnew file mode 100644index 000000000..8b3c09ea8--- /dev/null+++ b/packages/web/src/components/docs/bulk-generate-button.tsx@@ -0,0 +1,66 @@+"use client";++import { Sparkles } from "lucide-react";+import { Button } from "@repowise-dev/ui/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@repowise-dev/ui/ui/dialog";+import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";+import { BulkGenerateConfirm } from "./bulk-generate-confirm";+import { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";++/**+ * The one bulk generation action, mounted in the docs header. Writes every+ * subsystem page still rendered from structure, with a single cost estimate.+ * Shown by the header only while stubs remain, so it retires itself once the+ * wiki is fully written.+ */+export function BulkGenerateButton({+ repoId,+ onGenerated,+}: {+ repoId: string;+ /** Called once a run completes so the host can refresh the page list. */+ onGenerated?: () => void;+}) {+ const bulk = useBulkGenerate(repoId);++ return (+ <>+ <Button+ variant="outline"+ size="sm"+ onClick={bulk.open}+ disabled={bulk.jobId != null}+ className="h-7 gap-1.5 border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] text-xs text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-muted)] hover:text-[var(--color-accent-hover)]"+ >+ <Sparkles className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">Write subsystem pages</span>+ </Button>++ <BulkGenerateConfirm flow={bulk} repoId={repoId} title="Write the subsystem pages" />++ <Dialog+ open={bulk.jobId != null}+ onOpenChange={(v) => {+ if (!v) bulk.clearJob();+ }}+ >+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Writing the subsystem pages</DialogTitle>+ </DialogHeader>+ {bulk.jobId != null && (+ <GenerationProgressWrapper+ jobId={bulk.jobId}+ onDone={() => onGenerated?.()}+ />+ )}+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/packages/web/src/components/docs/bulk-generate-confirm.tsx b/packages/web/src/components/docs/bulk-generate-confirm.tsxindex 8f9237757..19e0f37e8 100644--- a/packages/web/src/components/docs/bulk-generate-confirm.tsx+++ b/packages/web/src/components/docs/bulk-generate-confirm.tsx@@ -2,16 +2,12 @@import { GenerateConfirmDialog } from "@repowise-dev/ui/wiki/regenerate-button";import { formatEstimateCost } from "@/lib/generate-format";-import {- COVERAGE_OPTIONS,- RECOMMENDED_COVERAGE,- type useBulkGenerate,-} from "@/lib/hooks/use-bulk-generate";+import { type useBulkGenerate } from "@/lib/hooks/use-bulk-generate";/*** Maps a `useBulkGenerate` flow onto the shared, presentational- * `GenerateConfirmDialog` (selection-scoped cascade wording). Kept tiny so the- * quick action, banner, and coverage toolbar reuse one mapping.+ * `GenerateConfirmDialog` (selection-scoped cascade wording). One estimate, one+ * confirm: no coverage picker, since a free file layer has nothing to ration.*/export function BulkGenerateConfirm({flow,@@ -20,33 +16,20 @@ export function BulkGenerateConfirm({}: {flow: ReturnType<typeof useBulkGenerate>;repoId: string;- /** Dialog title, e.g. "Write documentation with AI". */+ /** Dialog title, e.g. "Write the subsystem pages". */title?: string;}) {- const { estimate, noProvider, label, coveragePct } = flow;+ const { estimate, noProvider } = flow;const pages = estimate?.total_pages ?? 0;- const isCoverage = coveragePct != null;return (<GenerateConfirmDialogopen={flow.confirmOpen}onOpenChange={flow.setConfirmOpen}mode="write"- title={title ?? "Write documentation with AI"}+ title={title ?? "Write the subsystem pages"}cascadeScope="selection"- coverageOptions={isCoverage ? [...COVERAGE_OPTIONS] : undefined}- coveragePct={coveragePct ?? undefined}- onCoverageChange={isCoverage ? flow.changeCoverage : undefined}- recommendedCoverage={isCoverage ? RECOMMENDED_COVERAGE : undefined}- description={- <>- Write{" "}- <span className="font-medium text-[var(--color-text-primary)]">- {label ?? "the selected pages"}- </span>{" "}- with your configured model.- </>- }+ description="Write every subsystem page still generated from structure, with your configured model."confirmLabel={pages > 0 ? `Write ${pages} ${pages === 1 ? "page" : "pages"}` : "Write with AI"}cascade={flow.cascade}onCascadeChange={flow.changeCascade}diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsxindex 30fca7bd3..ad2f0943e 100644--- a/packages/web/src/components/docs/docs-explorer.tsx+++ b/packages/web/src/components/docs/docs-explorer.tsx@@ -28,6 +28,8 @@ import {SidebarToggle,} from "./docs-page-actions";import { PageGenerateButton } from "./page-generate-button";+import { BulkGenerateButton } from "./bulk-generate-button";+import { isModelWrittenType, isStubPage } from "@repowise-dev/ui/lib/page-types";import { search as searchPages } from "@/lib/api/search";import { downloadTextFile } from "@/lib/utils/download";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";@@ -73,6 +75,13 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {[selectedPage],);+ // The docs header offers one bulk "write the subsystem pages" action, shown+ // only while concept pages are still stubs. A structural page is never a stub.+ const hasStubs = useMemo(+ () => (pages as DocPage[]).some((p) => isStubPage(p)),+ [pages],+ );+// Keep the selected page in sync with the ?page= URL param. This fires on// mount and whenever the param changes — including when an in-content wiki// link or breadcrumb navigates via <Link href="?page=...">.@@ -276,13 +285,14 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {personaHasEffect={personaHasEffect}/>)}- {selectedPage && (+ {selectedPage && isModelWrittenType(selectedPage.page_type) && (<PageGenerateButtonpage={selectedPage}repoId={repoId}onGenerated={handleGenerated}/>)}+ {hasStubs && <BulkGenerateButton repoId={repoId} onGenerated={handleGenerated} />}<buttononClick={() => setSearchOpen(true)}className="flex items-center gap-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 text-xs text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-secondary)]"diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxindex 317a32186..55aed1507 100644--- a/packages/web/src/components/docs/docs-viewer.tsx+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -15,7 +15,7 @@ import { cn } from "@/lib/utils/cn";import { getGitMetadata } from "@/lib/api/git";import { summarizeFixHistory } from "@repowise-dev/ui/lib/fix-history";import { DocsReader } from "@repowise-dev/ui/docs/docs-reader";-import { isDeterministicPage } from "@repowise-dev/ui/lib/page-types";+import { isModelWrittenType } from "@repowise-dev/ui/lib/page-types";import { PageGenerateButton } from "./page-generate-button";import { Badge } from "@repowise-dev/ui/ui/badge";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";@@ -332,7 +332,7 @@ export function DocsViewer({buildPageHref={buildPageHref}LinkComponent={Link}upgradeSlot={- page && isDeterministicPage(page) ? (+ page && isModelWrittenType(page.page_type) ? (<PageGenerateButtonpage={page}repoId={repoId}diff --git a/packages/web/src/components/docs/page-generate-button.tsx b/packages/web/src/components/docs/page-generate-button.tsxindex 31459905e..aa9ae938a 100644--- a/packages/web/src/components/docs/page-generate-button.tsx+++ b/packages/web/src/components/docs/page-generate-button.tsx@@ -8,6 +8,7 @@ import {type RegenerateCascade,} from "@repowise-dev/ui/wiki/regenerate-button";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";+import { isStubPage } from "@repowise-dev/ui/lib/page-types";import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";import { regeneratePage } from "@/lib/api/pages";import { generateEstimate } from "@/lib/api/repos";@@ -33,7 +34,10 @@ export function PageGenerateButton({* link-like entry point rendered beside the provenance pill in the reader. */variant?: "button" | "inline";}) {- const mode = page.is_deterministic ? "write" : "regenerate";+ // "Write" on a stub concept page, "Regenerate" on a written one. Callers only+ // mount this on the model-written page types, so a stub here is genuinely a+ // page awaiting its first prose, never a structural file page.+ const mode = isStubPage(page) ? "write" : "regenerate";const settingsHref = `/repos/${repoId}/settings#provider`;const [confirmOpen, setConfirmOpen] = useState(false);diff --git a/packages/web/src/components/search/search-result-card.tsx b/packages/web/src/components/search/search-result-card.tsxindex a75e7b04c..68c074bdc 100644--- a/packages/web/src/components/search/search-result-card.tsx+++ b/packages/web/src/components/search/search-result-card.tsx@@ -1,12 +1,7 @@import Link from "next/link";import { Badge } from "@repowise-dev/ui/ui/badge";import { truncatePath } from "@repowise-dev/ui/lib/format";-import {- getPageTypeLabel,- isDeterministicPage,- DETERMINISTIC_BADGE_LABEL,- DETERMINISTIC_BADGE_TITLE,-} from "@repowise-dev/ui/lib/page-types";+import { getPageTypeLabel } from "@repowise-dev/ui/lib/page-types";import { cn } from "@/lib/utils/cn";import { pageHref } from "@/lib/utils/page-href";import type { SearchResultResponse } from "@/lib/api/types";@@ -48,11 +43,6 @@ export function SearchResultCard({ result, query, repoId }: SearchResultCardProp{result.title}</h3><div className="flex items-center gap-1.5 shrink-0">- {isDeterministicPage(result) && (- <Badge variant="outline" title={DETERMINISTIC_BADGE_TITLE}>- {DETERMINISTIC_BADGE_LABEL}- </Badge>- )}<Badge variant="default">{getPageTypeLabel(result.page_type)}</Badge><spanclassName={cn(diff --git a/packages/web/src/lib/hooks/use-bulk-generate.ts b/packages/web/src/lib/hooks/use-bulk-generate.tsindex 040e8294d..75981ffc2 100644--- a/packages/web/src/lib/hooks/use-bulk-generate.ts+++ b/packages/web/src/lib/hooks/use-bulk-generate.ts@@ -7,165 +7,82 @@ 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;+// One bulk action: write every subsystem page a model has not written yet.+// The server resolves "unwritten" to the concept layer only (structural pages+// have no model path), so this is always the stubs and never the file layer.+const SELECTION: GenerateSelection = { kind: "unwritten" };/**- * 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 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.+ * The bulk "write the subsystem pages" flow behind the docs-header action. Owns+ * the lazily-fetched estimate (heavy, so cached per cascade and never fetched+ * per render), the cascade choice, the launch, and the active job id. The+ * shared `GenerateConfirmDialog` and `GenerationProgressWrapper` stay+ * presentational; the caller maps this state onto them.*/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 (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,- [],- );+ // Estimate cache keyed by cascade so toggling the choice back to a value+ // already priced doesn't refetch the heavy endpoint. The cascade the UI wants+ // shown, so a late response for a since-abandoned cascade never overwrites it.+ const cacheRef = useRef<Map<RegenerateCascade, GenerateEstimate>>(new Map());+ const wantedCascadeRef = useRef<RegenerateCascade>("none");const fetchEstimate = useCallback(- async (pct: number | null, which: RegenerateCascade) => {- const sel = selectionFor(pct);- if (!sel) return;- const token = requestRef.current;- const key = keyFor(pct, which);- wantedKeyRef.current = key;- const cached = cacheRef.current.get(key);+ async (which: RegenerateCascade) => {+ wantedCascadeRef.current = which;+ const cached = cacheRef.current.get(which);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 && wantedKeyRef.current === key;try {- const res = await generateEstimate(repoId, { selection: sel, cascade: which });- if (requestRef.current !== token) return;- cacheRef.current.set(key, res);- if (current()) setEstimate(res);+ const res = await generateEstimate(repoId, { selection: SELECTION, cascade: which });+ cacheRef.current.set(which, res);+ if (wantedCascadeRef.current === which) setEstimate(res);} catch (e) {- if (current()) {+ if (wantedCascadeRef.current === which) {setEstimateError(toFriendlyMessage(e));setEstimate(null);}} finally {- if (current()) setEstimateLoading(false);+ if (wantedCascadeRef.current === which) setEstimateLoading(false);}},- [repoId, selectionFor],+ [repoId],);- const openFor = useCallback(- (- pct: number | null,- explicit: GenerateSelection | null,- opts?: { label?: string; defaultCascade?: RegenerateCascade },- ) => {- const startCascade = opts?.defaultCascade ?? "none";- requestRef.current += 1;- cacheRef.current.clear();- 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(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 open = useCallback(() => {+ cacheRef.current.clear();+ setCascade("none");+ setEstimate(null);+ setEstimateError(null);+ void fetchEstimate("none");+ setConfirmOpen(true);+ }, [fetchEstimate]);const changeCascade = useCallback((next: RegenerateCascade) => {setCascade(next);- void fetchEstimate(coveragePct, next);+ void fetchEstimate(next);},- [fetchEstimate, coveragePct],- );-- const changeCoverage = useCallback(- (pct: number) => {- setCoveragePct(pct);- setSelection({ kind: "ranked", coverage_pct: pct });- void fetchEstimate(pct, cascade);- },- [fetchEstimate, cascade],+ [fetchEstimate],);const confirm = useCallback(async () => {- const sel = selectionFor(coveragePct);- if (!sel) return;setLaunching(true);try {- const res = await generatePages(repoId, { selection: sel, cascade });+ const res = await generatePages(repoId, { selection: SELECTION, cascade });setJobId(res.job_id);setConfirmOpen(false);} catch (e) {@@ -173,29 +90,24 @@ export function useBulkGenerate(repoId: string) {} finally {setLaunching(false);}- }, [repoId, selectionFor, coveragePct, cascade]);+ }, [repoId, cascade]);const clearJob = useCallback(() => setJobId(null), []);const noProvider = !!estimate && estimate.provider.name == null;return {- selection,- label,confirmOpen,setConfirmOpen,cascade,changeCascade,- coveragePct,- changeCoverage,estimate,estimateLoading,estimateError,noProvider,launching,jobId,- begin,- beginCoverage,+ open,confirm,clearJob,};diff --git a/tests/unit/server/test_generate.py b/tests/unit/server/test_generate.pyindex 81f7da4e5..09bfb07a0 100644--- a/tests/unit/server/test_generate.py+++ b/tests/unit/server/test_generate.py@@ -129,17 +129,30 @@ async def test_generate_endpoint_page_ids_selection(client: AsyncClient, app) ->resp = await client.post(f"/api/repos/{repo['id']}/generate",json={- "selection": {"kind": "page_ids", "page_ids": ["file_page:a.py"]},+ "selection": {"kind": "page_ids", "page_ids": ["module_page:src/foo"]},"cascade": "none","style": "caveman",},)assert resp.status_code == 202cfg = await _job_config(app.state.session_factory, resp.json()["job_id"])- assert cfg["selection"] == {"kind": "page_ids", "page_ids": ["file_page:a.py"]}+ assert cfg["selection"] == {"kind": "page_ids", "page_ids": ["module_page:src/foo"]}assert cfg["style"] == "caveman"+async def test_generate_endpoint_rejects_structural_page_id(client: AsyncClient) -> None:+ """generate writes the concept layer only, so a structural page id is a clear+ error rather than a silent no-op re-render of a template."""+ repo = await create_test_repo(client)+ resp = await client.post(+ f"/api/repos/{repo['id']}/generate",+ json={"selection": {"kind": "page_ids", "page_ids": ["file_page:a.py"]}},+ )+ assert resp.status_code == 400+ assert "file_page:a.py" in resp.json()["detail"]++@pytest.mark.asyncioasync def test_generate_endpoint_ranked_selection(client: AsyncClient, app) -> None:"""A ranked coverage selection is carried into the job config."""@@ -177,9 +190,7 @@ 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}- )+ resp = await client.post(f"/api/repos/{repo['id']}/generate", json={"selection": selection})assert resp.status_code == 400, resp.textassert needle in resp.json()["detail"].lower()@@ -266,12 +277,8 @@ def _fake_rehydrated(template_ids: list[str]) -> RehydratedRepo:async def _seed_generate_job(session_factory, repo_path: Path, config: dict) -> str:async with session_factory() as session:- repo = await crud.upsert_repository(- session, name="test-repo", local_path=str(repo_path)- )- job = await crud.upsert_generation_job(- session, repository_id=repo.id, config=config- )+ repo = await crud.upsert_repository(session, name="test-repo", local_path=str(repo_path))+ job = await crud.upsert_generation_job(session, repository_id=repo.id, config=config)await session.commit()return job.id@@ -289,9 +296,11 @@ async def test_generate_job_runs_scoped_engine(session_factory, tmp_path) -> Non)app_state = SimpleNamespace(session_factory=session_factory, fts=None, vector_store=None)- template_ids = ["file_page:a.py", "file_page:b.py"]+ # generate writes the concept layer, so the resolved plan is model-written+ # ids; the scope helper narrows structural ids out.+ template_ids = ["module_page:a", "module_page:b"]written = SimpleNamespace(- page_id="file_page:a.py", title="a", content="x", input_tokens=10, output_tokens=20+ page_id="module_page:a", title="a", content="x", input_tokens=10, output_tokens=20)execute_mock = AsyncMock(return_value=ScopedGenerationResult(generated_pages=[written], marked_stale=0)@@ -332,17 +341,15 @@ def test_resolve_generate_scope_ranked_uses_build_ranked_seed() -> None: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"]+ template_ids = ["module_page:a", "module_page:b", "module_page:c"]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"}+ seed = {"module_page:a"}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:+ 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()@@ -357,14 +364,14 @@ 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"])+ rehydrated = _fake_rehydrated(["module_page:a", "module_page:b"])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"}+ assert plan.generate_ids == {"module_page:a", "module_page:b"}@pytest.mark.asyncio@@ -407,9 +414,7 @@ async def test_sync_regen_receives_vector_store_and_prior_pages(session_factory,job_id = await _seed_generate_job(session_factory, tmp_path, {"mode": "sync"})app_state = SimpleNamespace(session_factory=session_factory, fts=None, vector_store=None)- fake_result = SimpleNamespace(- generated_pages=[], parsed_files=[], file_count=1, symbol_count=1- )+ fake_result = SimpleNamespace(generated_pages=[], parsed_files=[], file_count=1, symbol_count=1)regen_mock = AsyncMock(return_value=[])with (patch("repowise.server.job_executor.run_pipeline", AsyncMock(return_value=fake_result)),diff --git a/tests/unit/server/test_overview_docs_split.py b/tests/unit/server/test_overview_docs_split.pyindex c0cdd8261..9ef54d8de 100644--- a/tests/unit/server/test_overview_docs_split.py+++ b/tests/unit/server/test_overview_docs_split.py@@ -1,9 +1,9 @@-"""Tests for the docs counts in /api/repos/{id}/overview-summary.+"""Tests for the docs count in /api/repos/{id}/overview-summary.-The Overview's Docs tile reports total generated pages plus how many of them-are the deterministic template ("Auto") coverage tail, so a reader can tell-model-written docs from structure-derived ones. ``provider_name == "template"``-is the discriminator, matching the page schema's ``is_deterministic``.+The Overview's Docs tile reports the total generated page count. The+template-vs-AI split it used to carry was retired with the provenance axis: the+file layer is structural for every repo, so a per-page "who wrote this" count+said nothing."""from __future__ import annotations@@ -42,8 +42,8 @@ def _page(repo_id: str, path: str, provider: str) -> Page:@pytest.mark.asyncio-async def test_docs_counts_split_ai_from_template_pages(client: AsyncClient, app) -> None:- """Total counts every page; auto counts only the template-provider ones."""+async def test_docs_count_totals_every_page(client: AsyncClient, app) -> None:+ """The Docs tile counts every generated page, of every provenance."""repo = await create_test_repo(client)async with get_session(app.state.session_factory) as session:@@ -56,12 +56,12 @@ async def test_docs_counts_split_ai_from_template_pages(client: AsyncClient, appstats = resp.json()["stats"]assert stats["doc_page_count"] == 3- assert stats["doc_auto_page_count"] == 1+ assert "doc_auto_page_count" not in stats@pytest.mark.asyncio-async def test_docs_counts_are_zero_without_pages(client: AsyncClient) -> None:- """An index-only repo has no wiki: both counts read zero, not null."""+async def test_docs_count_is_zero_without_pages(client: AsyncClient) -> None:+ """An index-only repo has no wiki: the count reads zero, not null."""repo = await create_test_repo(client)resp = await client.get(f"/api/repos/{repo['id']}/overview-summary")@@ -69,4 +69,3 @@ async def test_docs_counts_are_zero_without_pages(client: AsyncClient) -> None:stats = resp.json()["stats"]assert stats["doc_page_count"] == 0- assert stats["doc_auto_page_count"] == 0diff --git a/tests/unit/server/test_pages.py b/tests/unit/server/test_pages.pyindex 7972d819d..8d76d4677 100644--- a/tests/unit/server/test_pages.py+++ b/tests/unit/server/test_pages.py@@ -118,48 +118,61 @@ async def test_update_page_notes_not_found(client: AsyncClient) -> None:@pytest.mark.asyncio-async def test_list_pages_deterministic_filter(client: AsyncClient, app) -> None:- """?deterministic splits template (unwritten) pages from model-written ones."""+async def test_list_pages_has_prose_filter(client: AsyncClient, app) -> None:+ """?has_prose splits written concept pages from stubs, scoped to the+ model-written types. A structural file page (never has prose) is in neither+ filtered view but present when the filter is omitted."""repo = await create_test_repo(client)repo_id = repo["id"]async with get_session(app.state.session_factory) as session:+ # A concept-tree stub: a model-written type still rendered as a template.await crud.upsert_page(session,- page_id="file_page:tmpl.py",+ page_id="module_page:stub",repository_id=repo_id,- page_type="file_page",- title="tmpl",- content="template page",- target_path="tmpl.py",+ page_type="module_page",+ title="stub",+ content="stub page",+ target_path="src/stub",source_hash="",model_name="template",provider_name="template",)+ # A written concept page.await crud.upsert_page(session,- page_id="file_page:written.py",+ page_id="module_page:written",repository_id=repo_id,- page_type="file_page",+ page_type="module_page",title="written",content="model page",- target_path="written.py",+ target_path="src/written",source_hash="h",model_name="gpt",provider_name="openai",)+ # A structural file page: template forever, outside the has_prose axis.+ await crud.upsert_page(+ session,+ page_id="file_page:f.py",+ repository_id=repo_id,+ page_type="file_page",+ title="f",+ content="file page",+ target_path="f.py",+ source_hash="",+ model_name="template",+ provider_name="template",+ )- unwritten = await client.get(- "/api/pages", params={"repo_id": repo_id, "deterministic": "true"}- )- assert {p["id"] for p in unwritten.json()} == {"file_page:tmpl.py"}+ stubs = await client.get("/api/pages", params={"repo_id": repo_id, "has_prose": "false"})+ assert {p["id"] for p in stubs.json()} == {"module_page:stub"}- written = await client.get(- "/api/pages", params={"repo_id": repo_id, "deterministic": "false"}- )- assert {p["id"] for p in written.json()} == {"file_page:written.py"}+ written = await client.get("/api/pages", params={"repo_id": repo_id, "has_prose": "true"})+ assert {p["id"] for p in written.json()} == {"module_page:written"}both = await client.get("/api/pages", params={"repo_id": repo_id})- assert len(both.json()) == 2+ assert len(both.json()) == 3@pytest.mark.asyncio