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.

fix(pages): scope and rank a module page's decision records (#1754)

Ngo Quoc Viet678bbfd232e2
diff --git a/packages/core/src/repowise/core/generation/page_generator/helpers.py b/packages/core/src/repowise/core/generation/page_generator/helpers.py
index eb9aca98b..0c1aa0836 100644
--- a/packages/core/src/repowise/core/generation/page_generator/helpers.py
+++ b/packages/core/src/repowise/core/generation/page_generator/helpers.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import re
from collections import defaultdict
+from collections.abc import Iterable
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -243,6 +244,47 @@ def build_dead_code_map(dead_code_report: Any | None) -> dict[str, list[dict]]:
return dead_code_by_file
+def _decision_confidence(payload: dict) -> float:
+ """A decision's confidence as a float, 0.0 when it is missing or unusable."""
+ try:
+ return float(payload.get("confidence") or 0.0)
+ except (TypeError, ValueError):
+ return 0.0
+
+
+def rank_decisions(decisions: Iterable[dict]) -> list[dict]:
+ """Most confident first, ties in discovery order (the sort is stable).
+
+ A page has room for a handful, so which handful matters -- the list is both
+ rendered and fed to the model as context. Taking a raw slice showed whichever
+ happened to be written first.
+ """
+ ranked = list(decisions)
+ ranked.sort(key=lambda payload: -_decision_confidence(payload))
+ return ranked
+
+
+def decisions_for_files(
+ decisions_by_file: dict[str, list[dict]], paths: Iterable[str]
+) -> list[dict]:
+ """The decisions governing *paths*, de-duplicated and ranked.
+
+ A decision that affects several of a module's files appears once. The key
+ matches the ``decision_records`` uniqueness constraint (title, source,
+ evidence file), so two genuinely distinct records are never collapsed.
+ """
+ seen: set[tuple[Any, Any, Any]] = set()
+ scoped: list[dict] = []
+ for path in paths:
+ for payload in decisions_by_file.get(path) or ():
+ key = (payload.get("title"), payload.get("source"), payload.get("evidence_file"))
+ if key in seen:
+ continue
+ seen.add(key)
+ scoped.append(payload)
+ return rank_decisions(scoped)
+
+
def build_decision_maps(
decision_report: Any | None,
) -> tuple[dict[str, list[dict]], list[dict]]:
diff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.py
index 017334fa4..e48355d60 100644
--- a/packages/core/src/repowise/core/generation/page_generator/levels.py
+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py
@@ -19,7 +19,7 @@ from repowise.core.ids import is_external
from .. import onboarding as _onboarding
from ..context_assembler import FilePageContext
from ..models import compute_page_id
-from .helpers import _is_infra_file
+from .helpers import _is_infra_file, decisions_for_files, rank_decisions
if TYPE_CHECKING:
from ..concept_tree.vocabulary import HouseTerm
@@ -285,7 +285,13 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
run.graph,
git_meta_map=run.git_meta_map,
page_summaries=run.completed_page_summaries,
- decision_records=run.decisions_all,
+ # The module's own decisions, not the repository's. File
+ # pages already scope this way; passing the flat list here
+ # showed the first five written, which on a repo with
+ # decisions concentrated in one area is the same five on
+ # every module page -- and they are prompt context, not
+ # just rendered output.
+ decision_records=decisions_for_files(run.decisions_by_file, material),
dead_code_findings=[
d for fc in fcs for d in run.dead_code_by_file.get(fc.file_path, [])
],
@@ -440,7 +446,9 @@ async def build_level6_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
graph_builder=run.graph_builder,
repo_name=run.repo_name,
external_systems=run.external_systems,
- decision_records=run.decisions_all[:10],
+ # Repo-wide scope is right here; only the choice of ten was
+ # list position.
+ decision_records=rank_decisions(run.decisions_all)[:10],
overview_mermaid=overview_mermaid,
source_map=run.source_map,
# Per-package file counts come from the files this run
diff --git a/tests/unit/generation/test_decision_scoping.py b/tests/unit/generation/test_decision_scoping.py
new file mode 100644
index 000000000..98f1db5aa
--- /dev/null
+++ b/tests/unit/generation/test_decision_scoping.py
@@ -0,0 +1,91 @@
+"""Module pages get their own decisions, ranked (#1587).
+
+Two halves. The behaviour half exercises the helpers directly. The guard half
+is an architecture check in the style of ``test_no_test_path_copies``: a page
+type must not go back to slicing the repo-wide list, because the slice is not
+only rendered, it is prompt context for the page being written.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from repowise.core.generation.page_generator.helpers import (
+ decisions_for_files,
+ rank_decisions,
+)
+
+LEVELS = Path(__file__).resolve().parents[3] / (
+ "packages/core/src/repowise/core/generation/page_generator/levels.py"
+)
+
+
+def _decision(title: str, *, confidence: float | None = 1.0, evidence: str = "e.py") -> dict:
+ payload = {"title": title, "source": "git", "evidence_file": evidence}
+ if confidence is not None:
+ payload["confidence"] = confidence
+ return payload
+
+
+def test_module_decisions_are_scoped_to_the_modules_files():
+ a1 = _decision("a1", confidence=0.4, evidence="a/x.py")
+ a2 = _decision("a2", confidence=0.9, evidence="a/y.py")
+ b1 = _decision("b1", confidence=1.0, evidence="b/z.py")
+ by_file = {"a/x.py": [a1, a2], "a/y.py": [a2], "b/z.py": [b1]}
+
+ module_a = decisions_for_files(by_file, ["a/x.py", "a/y.py"])
+ assert [d["title"] for d in module_a] == ["a2", "a1"], "most confident first"
+
+ module_b = decisions_for_files(by_file, ["b/z.py"])
+ assert [d["title"] for d in module_b] == ["b1"], "another module's decisions do not leak in"
+
+ assert decisions_for_files(by_file, ["unindexed.py"]) == []
+
+
+def test_a_decision_affecting_several_files_appears_once():
+ shared = _decision("shared", evidence="a/x.py")
+ by_file = {"a/x.py": [shared], "a/y.py": [shared], "a/z.py": [shared]}
+
+ assert len(decisions_for_files(by_file, ["a/x.py", "a/y.py", "a/z.py"])) == 1
+
+
+def test_two_records_sharing_a_title_are_not_collapsed():
+ # The dedupe key mirrors the decision_records uniqueness constraint
+ # (title, source, evidence_file), so a repeated title from a different
+ # source or file is a different decision.
+ same_title_other_file = [
+ _decision("Use X", evidence="a/x.py"),
+ _decision("Use X", evidence="b/z.py"),
+ ]
+ by_file = {"a/x.py": same_title_other_file}
+
+ assert len(decisions_for_files(by_file, ["a/x.py"])) == 2
+
+
+def test_ranking_is_stable_and_tolerates_a_missing_confidence():
+ ranked = rank_decisions(
+ [_decision("low", confidence=0.1), _decision("none", confidence=None), _decision("high")]
+ )
+ assert [d["title"] for d in ranked] == ["high", "low", "none"]
+
+ # Equal confidence keeps discovery order rather than reshuffling.
+ tied = rank_decisions([_decision("first"), _decision("second"), _decision("third")])
+ assert [d["title"] for d in tied] == ["first", "second", "third"]
+
+
+def test_no_page_type_slices_the_repo_wide_decision_list_unranked():
+ """A raw ``decisions_all`` slice is the bug this closes.
+
+ Repo-wide scope is correct for the overview; taking its first N is not.
+ Anything reaching for ``decisions_all`` has to say how it ordered them.
+ """
+ source = LEVELS.read_text(encoding="utf-8")
+ offenders = [
+ line.strip()
+ for line in source.splitlines()
+ if re.search(r"decisions_all\s*\[", line) and "rank_decisions" not in line
+ ]
+ assert not offenders, "slice a ranked list, or scope it with decisions_for_files: " + "; ".join(
+ offenders
+ )