Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(docs): surface and down-rank the deterministic coverage tail (#819)

Raghav Chamadiya7404b2592095
diff --git a/packages/api-client/src/hosted.ts b/packages/api-client/src/hosted.ts
index c939f5809..a95341e5a 100644
--- a/packages/api-client/src/hosted.ts
+++ b/packages/api-client/src/hosted.ts
@@ -309,6 +309,7 @@ export function mapHostedSearchResult(raw: Record<string, unknown>): SearchResul
score: 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/search.ts b/packages/api-client/src/types/search.ts
index 4ae516e9b..abb42ede4 100644
--- a/packages/api-client/src/types/search.ts
+++ b/packages/api-client/src/types/search.ts
@@ -16,4 +16,9 @@ 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/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
index bbf65ee15..e2da95729 100644
--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
@@ -193,7 +193,12 @@ async def hydrate_hits(hits: list[dict], ctx: Any, *, scope: str | None = None)
async with get_session(ctx.session_factory) as session:
res = await session.execute(
select(
- Page.id, Page.target_path, Page.summary, Page.page_type, Page.freshness_status
+ Page.id,
+ Page.target_path,
+ Page.summary,
+ Page.page_type,
+ Page.freshness_status,
+ Page.provider_name,
).where(Page.id.in_(page_ids))
)
meta_by_id = {
@@ -202,6 +207,7 @@ 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()
}
@@ -221,6 +227,9 @@ 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 out
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
index faae8780e..f2b0f614c 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
@@ -109,6 +109,7 @@ 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,
_intersection_boost,
_rerank_by_coverage,
)
@@ -557,6 +558,11 @@ 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 a
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
index d5647336f..12dd0401f 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
@@ -238,6 +238,13 @@ _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 on
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
index ff59b628d..b54d77ae8 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,6 +19,7 @@ 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,
@@ -221,6 +222,24 @@ 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.py
index 9e9af7596..5af3e273c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -141,6 +141,14 @@ 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",
@@ -162,6 +170,23 @@ 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-backed
page on non-why queries.
@@ -310,20 +335,25 @@ 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]:
- """Batch-load target paths, tombstones, and optionally git metadata.
-
- 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``).
+) -> 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"``).
"""
page_ids = [item["page_id"] for item in output]
res = await session.execute(
- select(Page.id, Page.target_path, Page.freshness_status).where(Page.id.in_(page_ids))
+ select(Page.id, Page.target_path, Page.freshness_status, Page.provider_name).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:
@@ -333,7 +363,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
+ return page_info, tombstoned, git_map, det_ids
def _apply_freshness_boost(item: dict, gm: GitMetadata | None) -> None:
@@ -439,19 +469,24 @@ async def _search_single_repo(
_downweight_decisions(output, query)
output = await _rescue_all_decision_window(ctx, output, query, fetch_limit)
- _sort_demoting_decisions(output, query)
- # Attach target_path and drop excluded hits per repo (so federated search
- # honours each repo's own exclude_patterns) before aggregation. Runs on
- # the over-fetched list so the kind filter below has real headroom.
+ # 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()
if output:
async with get_session(ctx.session_factory) as session:
- page_info, tombstoned, _ = await _load_page_info(session, output)
+ page_info, tombstoned, _, det_ids = 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)
return output[:limit], method
@@ -731,7 +766,9 @@ async def search_codebase(
# Batch-lookup page target paths for the kind filter + git freshness boost
if output:
async with get_session(ctx.session_factory) as session:
- page_info, tombstoned, git_map = await _load_page_info(session, output, with_git=True)
+ page_info, tombstoned, git_map, det_ids = 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]
@@ -748,7 +785,10 @@ async def search_codebase(
gm = git_map.get(target_path) if target_path else None
_apply_freshness_boost(item, gm)
- # Re-sort by boosted relevance, decisions hard-demoted on non-why queries
+ # 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)
_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.py
index eee24e5bb..73718f07b 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -217,6 +217,11 @@ 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_row
else None
diff --git a/packages/server/src/repowise/server/routers/search.py b/packages/server/src/repowise/server/routers/search.py
index cb25ea4b5..0d1113594 100644
--- a/packages/server/src/repowise/server/routers/search.py
+++ b/packages/server/src/repowise/server/routers/search.py
@@ -8,7 +8,16 @@ and vector store so a single query covers the whole workspace. Pass
from __future__ import annotations
from fastapi import APIRouter, Depends, Query, Request
-from repowise.server.deps import get_fts, get_vector_store, verify_api_key
+from sqlalchemy import select
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import Page
+from repowise.server.deps import (
+ get_fts,
+ get_vector_store,
+ resolve_session_factory,
+ verify_api_key,
+)
from repowise.server.schemas import SearchResultResponse
router = APIRouter(
@@ -18,7 +27,7 @@ router = APIRouter(
)
-def _to_response(r) -> SearchResultResponse:
+def _to_response(r, det_ids: set[str]) -> SearchResultResponse:
"""Convert a SearchResult dataclass into the API schema."""
return SearchResultResponse(
page_id=r.page_id,
@@ -28,9 +37,33 @@ def _to_response(r) -> 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,
@@ -64,7 +97,8 @@ async def search(
request, query, limit, repo_id=repo_id, primary_vs=vector_store
)
- return [_to_response(r) for r in results]
+ 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]
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/pages.py b/packages/server/src/repowise/server/schemas/pages.py
index 9e9f5217f..d239ae0da 100644
--- a/packages/server/src/repowise/server/schemas/pages.py
+++ b/packages/server/src/repowise/server/schemas/pages.py
@@ -26,12 +26,20 @@ class PageResponse(BaseModel):
confidence: float
freshness_status: str
metadata: 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 = None
human_notes: str | None = None
created_at: datetime
updated_at: datetime
@classmethod
def from_orm(cls, obj: object) -> PageResponse:
+ metadata = json.loads(obj.metadata_json) # type: ignore[attr-defined]
return cls(
id=obj.id, # type: ignore[attr-defined]
repository_id=obj.repository_id, # type: ignore[attr-defined]
@@ -49,7 +57,9 @@ class PageResponse(BaseModel):
version=obj.version, # type: ignore[attr-defined]
confidence=obj.confidence, # type: ignore[attr-defined]
freshness_status=obj.freshness_status, # type: ignore[attr-defined]
- metadata=json.loads(obj.metadata_json), # 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]
created_at=obj.created_at, # type: ignore[attr-defined]
updated_at=obj.updated_at, # type: ignore[attr-defined]
diff --git a/packages/server/src/repowise/server/schemas/search.py b/packages/server/src/repowise/server/schemas/search.py
index 29c67306f..4d9abb61b 100644
--- a/packages/server/src/repowise/server/schemas/search.py
+++ b/packages/server/src/repowise/server/schemas/search.py
@@ -19,3 +19,7 @@ class SearchResultResponse(BaseModel):
score: float
snippet: str
search_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 = False
diff --git a/packages/types/src/docs.ts b/packages/types/src/docs.ts
index 6e0f1a48f..8721d6338 100644
--- a/packages/types/src/docs.ts
+++ b/packages/types/src/docs.ts
@@ -27,6 +27,14 @@ 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;
created_at: string;
updated_at: string;
diff --git a/packages/types/src/files.ts b/packages/types/src/files.ts
index 4ba9a37ad..38c1944f6 100644
--- a/packages/types/src/files.ts
+++ b/packages/types/src/files.ts
@@ -16,6 +16,14 @@ 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/ui/src/docs/docs-reader.tsx b/packages/ui/src/docs/docs-reader.tsx
index 0b6223a20..d856f6873 100644
--- a/packages/ui/src/docs/docs-reader.tsx
+++ b/packages/ui/src/docs/docs-reader.tsx
@@ -14,7 +14,12 @@ import {
import type { DocPage } from "@repowise-dev/types/docs";
import { cn } from "../lib/cn";
import { formatRelativeTime, formatTokens } from "../lib/format";
-import { getPageTypeLabel } from "../lib/page-types";
+import {
+ getPageTypeLabel,
+ isDeterministicPage,
+ DETERMINISTIC_BADGE_LABEL,
+ DETERMINISTIC_BADGE_TITLE,
+} from "../lib/page-types";
import { computeDocNav } from "./doc-nav";
import { filterMarkdownByPersona, type ReaderPersona } from "./reader-persona";
import { WikiMarkdown } from "../wiki/wiki-markdown";
@@ -296,6 +301,14 @@ 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="rounded-full border border-[var(--color-border-default)] px-2 py-0.5 uppercase tracking-wider text-[var(--color-text-tertiary)]"
+ title={DETERMINISTIC_BADGE_TITLE}
+ >
+ {DETERMINISTIC_BADGE_LABEL}
+ </span>
+ )}
{moduleSeg && (
<button
onClick={() => goToPageId(moduleSeg.pageId!)}
diff --git a/packages/ui/src/docs/docs-tree.tsx b/packages/ui/src/docs/docs-tree.tsx
index 5afd2412c..a63aa4c77 100644
--- a/packages/ui/src/docs/docs-tree.tsx
+++ b/packages/ui/src/docs/docs-tree.tsx
@@ -22,6 +22,7 @@ import {
getOnboardingSlot,
getPageTypeIcon,
getPageTypeLabel,
+ isDeterministicPage,
type OnboardingSlot,
} from "../lib/page-types";
import { cn } from "../lib/cn";
@@ -32,6 +33,12 @@ 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";
@@ -247,6 +254,98 @@ 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.
+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);
+ }
+ }
+ return { regular, deterministic };
+}
+
// ---------------------------------------------------------------------------
// Domain (semantic) tree
// ---------------------------------------------------------------------------
@@ -824,11 +923,25 @@ 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);
-
- const tree = useMemo(
- () => (viewMode === "domain" ? buildDomainTree(pages) : buildTree(pages)),
- [pages, viewMode],
+ // 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 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" ? buildDomainTree(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],
@@ -848,7 +961,11 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc
const freshCount = pages.filter((p) => p.freshness_status === "fresh").length;
const needAttention = totalPages - freshCount;
const activeFilterCount =
- (typeFilter !== "all" ? 1 : 0) + (freshnessFilter !== "all" ? 1 : 0);
+ (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);
return (
<div className={cn("flex flex-col h-full", className)}>
@@ -953,6 +1070,17 @@ 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.tsx
index 9f1af0e42..8bbbc9fbf 100644
--- a/packages/ui/src/files/file-doc-tab.tsx
+++ b/packages/ui/src/files/file-doc-tab.tsx
@@ -2,6 +2,11 @@ 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";
@@ -39,6 +44,11 @@ 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 && (
<span
className="text-xs text-[var(--color-text-tertiary)]"
diff --git a/packages/ui/src/lib/page-types.ts b/packages/ui/src/lib/page-types.ts
index 59b3cb421..0a9d22c3e 100644
--- a/packages/ui/src/lib/page-types.ts
+++ b/packages/ui/src/lib/page-types.ts
@@ -41,6 +41,39 @@ export function getPageTypeLabel(pageType: string): string {
return PAGE_TYPE_CONFIG[pageType]?.label ?? pageType.replace(/_/g, " ");
}
+// ---------------------------------------------------------------------------
+// Deterministic ("auto") 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.
+
+/** 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;
+}
+
+/**
+ * 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;
+ 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.";
+
// ---------------------------------------------------------------------------
// Onboarding collection
// ---------------------------------------------------------------------------
diff --git a/packages/web/src/components/search/search-result-card.tsx b/packages/web/src/components/search/search-result-card.tsx
index 68c074bdc..a75e7b04c 100644
--- a/packages/web/src/components/search/search-result-card.tsx
+++ b/packages/web/src/components/search/search-result-card.tsx
@@ -1,7 +1,12 @@
import Link from "next/link";
import { Badge } from "@repowise-dev/ui/ui/badge";
import { truncatePath } from "@repowise-dev/ui/lib/format";
-import { getPageTypeLabel } from "@repowise-dev/ui/lib/page-types";
+import {
+ getPageTypeLabel,
+ isDeterministicPage,
+ DETERMINISTIC_BADGE_LABEL,
+ DETERMINISTIC_BADGE_TITLE,
+} 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";
@@ -43,6 +48,11 @@ 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>
<span
className={cn(