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
fix(generation): reject pages that talk to the prompter, and cap the overview's prose (#1172)
Swati Ahuja01364b748baa
diff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.pyindex 06f04c90b..ca813e50f 100644--- a/packages/core/src/repowise/core/generation/page_generator/core.py+++ b/packages/core/src/repowise/core/generation/page_generator/core.py@@ -42,7 +42,7 @@ from .structural import (oneline,signature,)-from .validation import validate_generated_response+from .validation import reset_artifact_check_counts, validate_generated_responseif TYPE_CHECKING:from pathlib import Path as _Path # noqa: F401@@ -244,6 +244,11 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):"""from .orchestrate import run_generate_all+ # The artifact-check tallies are per run, and a long-lived process+ # generates more than once. Reset so the report's denominator counts+ # this run's responses rather than every response since start-up.+ reset_artifact_check_counts()+return await run_generate_all(self,parsed_files=parsed_files,diff --git a/packages/core/src/repowise/core/generation/page_generator/prompts.py b/packages/core/src/repowise/core/generation/page_generator/prompts.pyindex 6cf114c09..f5bdab52b 100644--- a/packages/core/src/repowise/core/generation/page_generator/prompts.py+++ b/packages/core/src/repowise/core/generation/page_generator/prompts.py@@ -69,7 +69,11 @@ SYSTEM_PROMPTS: dict[str, str] = {"Good: 'Repowise is a codebase documentation engine: it indexes a repository ""by traversing files, parsing code into ASTs, analyzing dependencies, and ""generating LLM-synthesised wiki pages served via MCP and a web UI.' "- "Required sections: ## Project Summary, ## Technology Stack, ## Entry Points, ## Architecture."+ "Required sections: ## Project Summary, ## Technology Stack, ## Entry Points, ## Architecture. "+ "\n"+ "The page is a short orientation, not a manual: keep the prose within the "+ "word budget the user prompt states, and reach for a table or a list "+ "wherever the material is a set of facts rather than an argument."),"architecture_diagram": ("You are repowise, an expert technical documentation generator. "diff --git a/packages/core/src/repowise/core/generation/page_generator/validation.py b/packages/core/src/repowise/core/generation/page_generator/validation.pyindex 93c7e0445..af9467751 100644--- a/packages/core/src/repowise/core/generation/page_generator/validation.py+++ b/packages/core/src/repowise/core/generation/page_generator/validation.py@@ -9,7 +9,9 @@ from __future__ import annotationsimport refrom collections import Counter+from dataclasses import dataclass+from repowise.core.generation.prose import prose_textfrom repowise.core.ingestion.models import ParsedFilefrom repowise.core.providers.llm.base import GeneratedResponse@@ -24,6 +26,121 @@ class InvalidGeneratedContentError(ValueError):"""Raised when a fresh LLM response cannot be persisted as documentation."""+# ---------------------------------------------------------------------------+# Generation artifacts+#+# Phrasings in which the model addresses whoever prompted it instead of the+# reader of the page. Each rule is checked against the page's prose only —+# fenced blocks and inline code are stripped first — because quoted source+# legitimately contains any word at all.+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class ArtifactRule:+ """One phrasing that must never reach a reader, and why."""++ name: str+ pattern: re.Pattern[str]+ explanation: str+++GENERATION_ARTIFACT_RULES: tuple[ArtifactRule, ...] = (+ ArtifactRule(+ name="trailing_offer",+ # An offer of further work, which only makes sense to whoever is+ # holding the conversation. The offer verb is required: "let me know"+ # alone would be a bare idiom, and every phrasing here needs the model+ # to be proposing that *it* do something next.+ pattern=re.compile(+ r"\b(?:"+ r"I(?:'d| would)? (?:can|could|am happy to|would be happy to)"+ r"(?: also)? (?:produce|generate|provide|create|write|add|draw|"+ r"expand|prepare|put together|do)"+ r"|let me know if"+ r"|would you like me to"+ r"|do you want me to"+ r"|if you(?:'d| would)? (?:want|like), I"+ r"|just say the word"+ r")\b",+ re.IGNORECASE,+ ),+ explanation="offers the reader further work, which no page can deliver",+ ),+ ArtifactRule(+ name="first_person",+ # First-person singular in the *author's* voice. Three deliberate+ # narrowings, each measured against this repo's own documentation:+ #+ # * A bare ``\bI\b`` is unusable. It matches the ``I`` of ``I/O`` on+ # every performance page, and it matches the reader-voice questions+ # documentation is written in — "How do I update a workspace?",+ # "should I worry about this file?". So ``I`` must be followed by+ # a verb that only the writer of the page would use of themselves.+ # * The verb list excludes the ones that read naturally after a+ # question word ("how do I read", "where do I find", "how do I+ # choose"), keeping only their past tense, which cannot.+ # * "we" is left alone entirely: plenty of projects write house+ # documentation in the first-person plural on purpose.+ pattern=re.compile(+ r"\bI(?:'m|'ll|'ve|'d)\b"+ r"|\bI (?:do|did|have|had|am|was|would|could) not\b"+ r"|\bI (?:can|can't|cannot|could|couldn't|will|would|should|must|am|was|"+ r"haven't|hadn't|didn't|don't|note|noted|notice|noticed|assume|assumed|"+ r"inferred|chose|omitted|recommend|suggest|think|believe|focused|"+ r"included|excluded|generated|wrote|found)\b"+ r"|\bmyself\b"+ ),+ explanation="speaks as the generator rather than describing the code",+ ),+ ArtifactRule(+ name="supplied_context",+ # The model narrating the shape of its own prompt. The reader has no+ # idea what was "provided" and cannot go and look at it.+ pattern=re.compile(+ r"\bthe (?:provided|supplied|given|attached|above) "+ r"(?:information|context|data|input|material|details|excerpt|"+ r"snippet|list|files?|documents?)\b"+ r"|\byou (?:provided|supplied|gave|listed)\b",+ re.IGNORECASE,+ ),+ explanation="refers to the prompt, which the reader cannot see",+ ),+)++# How many responses each rule has seen and rejected, for the whole process.+# A rule that matches nothing is indistinguishable from a rule that never ran+# unless the run count is recorded, and a check nobody can see the denominator+# for reads as a pass whether or not it happened.+_artifact_check_counts: Counter[str] = Counter()+++def artifact_check_counts() -> dict[str, int]:+ """Snapshot of the artifact-check tallies since the last reset.++ ``responses_checked`` is the denominator: zero means the checks never ran,+ which is not the same fact as ``rejected`` being zero.+ """+ return dict(_artifact_check_counts)+++def reset_artifact_check_counts() -> None:+ """Clear the tallies. Used between runs and between tests."""+ _artifact_check_counts.clear()+++def _artifact_detail(content: str) -> str | None:+ """Describe the first generation artifact in ``content``, if any."""+ prose = prose_text(content)+ for rule in GENERATION_ARTIFACT_RULES:+ match = rule.pattern.search(prose)+ if match is not None:+ _artifact_check_counts["rejected"] += 1+ _artifact_check_counts[f"rejected:{rule.name}"] += 1+ return f"{rule.name}: {rule.explanation} ({match.group(0).strip()!r})"+ return None++def _pathological_repetition_detail(content: str) -> str | None:"""Describe gross repetition, using deliberately conservative thresholds.@@ -57,6 +174,7 @@ def _pathological_repetition_detail(content: str) -> str | None:def validate_generated_response(response: GeneratedResponse) -> None:"""Reject fresh provider output that is unsafe to persist as a wiki page."""+ _artifact_check_counts["responses_checked"] += 1if response.stop_reason == "max_tokens":detail = (f" (provider reason: {response.provider_stop_reason})"@@ -75,6 +193,12 @@ def validate_generated_response(response: GeneratedResponse) -> None:f"provider returned pathologically repetitive documentation: {repetition_detail}")+ artifact_detail = _artifact_detail(response.content)+ if artifact_detail is not None:+ raise InvalidGeneratedContentError(+ f"provider returned text addressed to the prompter, not the reader — {artifact_detail}"+ )+# Common words that appear in backticks but are not code symbols._BACKTICK_SKIP = frozenset(diff --git a/packages/core/src/repowise/core/generation/prose.py b/packages/core/src/repowise/core/generation/prose.pynew file mode 100644index 000000000..46871823b--- /dev/null+++ b/packages/core/src/repowise/core/generation/prose.py@@ -0,0 +1,62 @@+"""Prose extraction for generated markdown pages.++Several checks care about what a page *says* rather than what it *quotes*: a+loop counter named ``I`` inside a C snippet is not the model addressing the+reader, and a JSON payload is not prose the reader has to wade through. This+module isolates that distinction in one place so every check draws the line+the same way.++Fenced blocks are tracked line by line rather than matched with a regex so an+unterminated fence — a truncated response — still removes everything after it+instead of leaking the whole tail back into the prose.+"""++from __future__ import annotations++import re++# Single-backtick spans: inline code, symbol names, paths.+_INLINE_CODE_RE = re.compile(r"`+[^`\n]*`+")++_FENCE_PREFIXES = ("```", "~~~")++# A token counts as a word only if it carries a letter or a digit, so bullet+# dashes, em dashes and stray pipes do not inflate the count.+_WORDISH = re.compile(r"[^\W_]")+++def prose_text(content: str) -> str:+ """``content`` with fenced code blocks and inline code spans removed.++ Everything else is kept verbatim, including headings, list markers and+ table pipes, so line structure survives for callers that need it.+ """+ kept: list[str] = []+ fence: str | None = None+ for line in content.splitlines():+ stripped = line.lstrip()+ if fence is None:+ opener = next((f for f in _FENCE_PREFIXES if stripped.startswith(f)), None)+ if opener is not None:+ fence = opener+ continue+ kept.append(line)+ elif stripped.startswith(fence):+ fence = None+ return _INLINE_CODE_RE.sub(" ", "\n".join(kept))+++def prose_word_count(content: str) -> int:+ """How many words of prose a page asks the reader to read.++ Code, inline code and table rows are excluded: they are looked up rather+ than read, and counting them would let a page of tables look as expensive+ as a page of argument. Headings and list text are counted, because the+ reader does read those.+ """+ total = 0+ for line in prose_text(content).splitlines():+ if line.lstrip().startswith("|"):+ continue+ total += sum(1 for token in line.split() if _WORDISH.search(token))+ return totaldiff --git a/packages/core/src/repowise/core/generation/report.py b/packages/core/src/repowise/core/generation/report.pyindex 0f636cf2a..c77b81228 100644--- a/packages/core/src/repowise/core/generation/report.py+++ b/packages/core/src/repowise/core/generation/report.py@@ -11,6 +11,14 @@ from dataclasses import dataclass, fieldfrom .models import GeneratedPagefrom .page_overlap import OverlapReport, measure_orientation_overlapfrom .page_tree import LayerGroupingReport, measure_layer_grouping+from .prose import prose_word_count++# How much prose the repository overview may ask a reader to get through.+# The page is the first thing anyone reads and it had grown past nine hundred+# words while saying what four hundred and fifty say. The prompt asks for the+# same number; the check below reports whether the run honoured it. Warn-only+# on purpose — a long overview is worth seeing, never worth failing a run over.+ORIENTATION_PROSE_WORD_BUDGET = 450@dataclass@@ -37,6 +45,14 @@ class GenerationReport:# raises when it is missing — the wiki just comes out flat. Read# ``measured`` before reading the counts.layer_grouping: LayerGroupingReport = field(default_factory=LayerGroupingReport)+ # Tally of the generation-artifact checks run over provider responses this+ # process. Carries its own denominator so "checked nothing" and "found+ # nothing" stay separate facts.+ artifact_checks: dict[str, int] = field(default_factory=dict)+ # Prose length of the repository overview this run produced, or ``None``+ # when the run produced no overview. ``None`` and ``0`` are different+ # facts: nothing was measured, versus an overview with nothing in it.+ overview_prose_words: int | None = None@classmethoddef from_pages(@@ -48,6 +64,10 @@ class GenerationReport:decisions_count: int = 0,elapsed: float = 0.0,) -> GenerationReport:+ # Deferred: the page generator pulls in the provider stack, and the+ # report is importable on its own (the CLI renders it lazily).+ from .page_generator.validation import artifact_check_counts+by_type = dict(Counter(p.page_type for p in pages))hal_count = sum(1 for p in pages if p.metadata.get("hallucination_warnings"))repair_count = sum(1 for p in pages if p.metadata.get("self_repair"))@@ -64,12 +84,42 @@ class GenerationReport:self_repaired_page_count=repair_count,orientation_overlap=measure_orientation_overlap(pages),layer_grouping=measure_layer_grouping(pages),+ artifact_checks=artifact_check_counts(),+ overview_prose_words=next(+ (+ prose_word_count(p.content or "")+ for p in pages+ if p.page_type == "repo_overview"+ ),+ None,+ ),)@propertydef total_pages(self) -> int:return sum(self.pages_by_type.values())+ @property+ def overview_over_budget(self) -> bool:+ """Whether the overview asks for more prose than the budget allows."""+ if self.overview_prose_words is None:+ return False+ return self.overview_prose_words > ORIENTATION_PROSE_WORD_BUDGET++ def overview_length_summary(self) -> str:+ """One line naming the overview's length against its budget."""+ if self.overview_prose_words is None:+ return "no overview in this run"+ line = f"{self.overview_prose_words} / {ORIENTATION_PROSE_WORD_BUDGET} words"+ return f"{line} — over budget" if self.overview_over_budget else line++ def artifact_check_summary(self) -> str:+ """One line saying whether the artifact checks ran, and what they found."""+ checked = self.artifact_checks.get("responses_checked", 0)+ if not checked:+ return "not run (0 responses checked)"+ return f"{checked} checked, {self.artifact_checks.get('rejected', 0)} rejected"+def estimated_cost_usd(self,input_rate: float = 3.0,@@ -128,6 +178,20 @@ def render_report(report: GenerationReport, console: object) -> None:grouping_text = f"[yellow]{grouping_text}[/yellow]"table.add_row("Layer grouping", grouping_text)+ # Same reasoning as the overlap row: shown even at zero, because a check+ # that never ran must not look like a check that passed.+ artifact_text = report.artifact_check_summary()+ if report.artifact_checks.get("rejected"):+ artifact_text = f"[yellow]{artifact_text}[/yellow]"+ table.add_row("Artifact checks", artifact_text)++ # Always shown for the same reason as the two rows above: a budget nobody+ # sees the reading of is a budget nobody keeps.+ length_text = report.overview_length_summary()+ if report.overview_over_budget:+ length_text = f"[yellow]{length_text}[/yellow]"+ table.add_row("Overview length", length_text)+console.print(table) # type: ignore[union-attr]for pair in overlap.flagged:diff --git a/packages/core/src/repowise/core/generation/templates/repo_overview.j2 b/packages/core/src/repowise/core/generation/templates/repo_overview.j2index ea98b76c4..81f820fb5 100644--- a/packages/core/src/repowise/core/generation/templates/repo_overview.j2+++ b/packages/core/src/repowise/core/generation/templates/repo_overview.j2@@ -71,3 +71,10 @@ Key entry points and their execution paths:{% endif %}Generate a complete wiki page following the sections above.++LENGTH: at most 450 words of prose across the whole page. Tables, lists and+code do not count against that, so put enumerable facts — packages, entry+points, languages — in a table or a list rather than describing them in+sentences. Say each thing once: the reader has the architecture page and the+per-module pages for depth, and a sentence that restates a heading is a+sentence they read twice.diff --git a/tests/unit/generation/test_output_validation.py b/tests/unit/generation/test_output_validation.pyindex b6a581d49..39be19daf 100644--- a/tests/unit/generation/test_output_validation.py+++ b/tests/unit/generation/test_output_validation.py@@ -4,6 +4,8 @@ import pytestfrom repowise.core.generation.page_generator.validation import (InvalidGeneratedContentError,+ artifact_check_counts,+ reset_artifact_check_counts,validate_generated_response,)from repowise.core.providers.llm.base import GeneratedResponse@@ -86,3 +88,121 @@ The response includes the distinct operation code `operation_{index}`.)validate_generated_response(_response("\n".join(sections)))+++# ---------------------------------------------------------------------------+# Generation-artifact rules+#+# These three phrasings are how the model talks to *us* rather than to the+# reader. All three reached live public pages, so the exact leaked strings are+# used as fixtures below.+# ---------------------------------------------------------------------------+++def test_rejects_trailing_offer_of_more_work() -> None:+ """The exact trailing offer that shipped on a public architecture page."""+ content = (+ "# Architecture\n\n"+ "The pipeline ingests a repository and writes wiki pages.\n\n"+ "If you want, I can also produce: (1) a 'sequence diagram' for a full "+ "pipeline run, or (2) a package-by-package dependency matrix focusing "+ "strictly on the 43 top files you provided."+ )+ with pytest.raises(InvalidGeneratedContentError, match="trailing_offer"):+ validate_generated_response(_response(content))+++def test_rejects_reference_to_the_provided_information() -> None:+ """The exact phrasing that shipped on a public Key Concepts page."""+ content = (+ "# Key Concepts\n\n"+ "These concepts recur across the codebase, but the provided information "+ "only anchors them by layer/cluster."+ )+ with pytest.raises(InvalidGeneratedContentError, match="supplied_context"):+ validate_generated_response(_response(content))+++def test_rejects_first_person_prose() -> None:+ content = "# Overview\n\nI could not find a test suite, so I assumed the module is untested."+ with pytest.raises(InvalidGeneratedContentError, match="first_person"):+ validate_generated_response(_response(content))+++def test_accepts_first_person_inside_a_code_block() -> None:+ """A loop counter named ``I`` is not the model addressing the reader.++ This is the case that decides whether the rule is shippable at all: a+ first-person check that fires on quoted source would reject correct pages.+ """+ content = '''# Overview++The scanner walks the buffer once.++```c+for (int I = 0; I < n; I++) {+ consume(buffer[I]);+}+```++```python+def scan(buffer):+ """I is the cursor; my own index is kept separately."""+ return len(buffer)+```++Inline, the counter `I` is never reused.+'''+ validate_generated_response(_response(content))+++def test_accepts_prose_that_merely_mentions_provided_files() -> None:+ """Only the model's own hedging phrasings are rejected, not the words."""+ content = (+ "# Overview\n\n"+ "The loader reads the configuration files provided by the workspace "+ "root and merges them in order."+ )+ validate_generated_response(_response(content))+++def test_artifact_checks_are_counted_so_a_clean_run_is_not_silence() -> None:+ """A run that checked nothing must not read like a run that found nothing."""+ reset_artifact_check_counts()+ assert artifact_check_counts() == {}++ validate_generated_response(_response("# Overview\n\nThe loader reads files.\n"))+ counts = artifact_check_counts()+ assert counts["responses_checked"] == 1+ assert counts.get("rejected", 0) == 0++ with pytest.raises(InvalidGeneratedContentError):+ validate_generated_response(+ _response("# Overview\n\nLet me know if you want a deeper diagram.")+ )+ counts = artifact_check_counts()+ assert counts["responses_checked"] == 2+ assert counts["rejected"] == 1+ assert counts["rejected:trailing_offer"] == 1+++def test_report_shows_the_artifact_check_denominator() -> None:+ """The generation report prints unconditionally; the log level does not.++ A reader of the report must be able to tell "checked 2, rejected 0" from+ "never checked anything", so the row is rendered either way.+ """+ from repowise.core.generation.report import GenerationReport++ reset_artifact_check_counts()+ report = GenerationReport.from_pages([])+ assert report.artifact_check_summary() == "not run (0 responses checked)"++ validate_generated_response(_response("# Overview\n\nThe loader reads files.\n"))+ report = GenerationReport.from_pages([])+ assert report.artifact_check_summary() == "1 checked, 0 rejected"++ with pytest.raises(InvalidGeneratedContentError):+ validate_generated_response(_response("# Overview\n\nWould you like me to add a diagram?"))+ report = GenerationReport.from_pages([])+ assert report.artifact_check_summary() == "2 checked, 1 rejected"diff --git a/tests/unit/generation/test_prose_budget.py b/tests/unit/generation/test_prose_budget.pynew file mode 100644index 000000000..e7d27d643--- /dev/null+++ b/tests/unit/generation/test_prose_budget.py@@ -0,0 +1,119 @@+"""The repository overview's prose budget, and the report row that checks it.++The overview is the page every reader meets first, and it had grown to roughly+a thousand words of prose saying what four hundred said. The budget is asked+for in the prompt; this is the check that says whether the run honoured it.+"""++from __future__ import annotations++from repowise.core.generation.models import GeneratedPage+from repowise.core.generation.prose import prose_word_count+from repowise.core.generation.report import (+ ORIENTATION_PROSE_WORD_BUDGET,+ GenerationReport,+)++BUDGET = ORIENTATION_PROSE_WORD_BUDGET+++def _page(content: str, page_type: str = "repo_overview") -> GeneratedPage:+ return GeneratedPage(+ page_id=f"{page_type}:.",+ page_type=page_type,+ title="Repository Overview",+ content=content,+ source_hash="",+ model_name="mock",+ provider_name="mock",+ input_tokens=0,+ output_tokens=0,+ cached_tokens=0,+ generation_level=6,+ target_path="",+ created_at="2026-07-29T00:00:00Z",+ updated_at="2026-07-29T00:00:00Z",+ )+++def _overview_of(word_count: int) -> GeneratedPage:+ body = " ".join(f"word{index}" for index in range(word_count - 1))+ return _page(f"# Overview\n\n{body}\n")+++# ---------------------------------------------------------------------------+# Counting+# ---------------------------------------------------------------------------+++def test_prose_word_count_ignores_code_blocks_and_tables() -> None:+ content = """# Overview++The loader reads three files.++```python+these words are quoted source and are not prose the reader wades through+```++| Field | Type |+| --- | --- |+| path | string |+"""+ # "Overview" plus "The loader reads three files."+ assert prose_word_count(content) == 6+++def test_prose_word_count_ignores_bare_punctuation() -> None:+ assert prose_word_count("- one — two\n\n* three\n") == 3+++# ---------------------------------------------------------------------------+# The budget+# ---------------------------------------------------------------------------+++def test_overview_at_the_cap_is_within_budget() -> None:+ report = GenerationReport.from_pages([_overview_of(BUDGET)])++ assert report.overview_prose_words == BUDGET+ assert not report.overview_over_budget+ assert report.overview_length_summary() == f"{BUDGET} / {BUDGET} words"+++def test_overview_just_under_the_cap_is_within_budget() -> None:+ report = GenerationReport.from_pages([_overview_of(BUDGET - 1)])++ assert report.overview_prose_words == BUDGET - 1+ assert not report.overview_over_budget+++def test_overview_just_over_the_cap_is_flagged() -> None:+ report = GenerationReport.from_pages([_overview_of(BUDGET + 1)])++ assert report.overview_prose_words == BUDGET + 1+ assert report.overview_over_budget+ assert "over budget" in report.overview_length_summary()+++def test_a_run_without_an_overview_says_so_rather_than_reading_as_a_pass() -> None:+ report = GenerationReport.from_pages([_page("# Layer\n\nwords.", page_type="layer_page")])++ assert report.overview_prose_words is None+ assert not report.overview_over_budget+ assert report.overview_length_summary() == "no overview in this run"+++# ---------------------------------------------------------------------------+# Prompt and check must agree+# ---------------------------------------------------------------------------+++def test_the_prompt_states_the_same_cap_the_report_checks() -> None:+ """A budget the prompt never mentions would only ever be reported, never met."""+ from pathlib import Path++ template = (+ Path(__file__).parents[3]+ / "packages/core/src/repowise/core/generation/templates/repo_overview.j2"+ )+ assert str(ORIENTATION_PROSE_WORD_BUDGET) in template.read_text()