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(decisions): a commit's file list stops answering per-file questions (#2434)
Raghav Chamadiya640a96ac780b
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 5d9d50c62..7af385851 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -1014,10 +1014,24 @@ async def _persist_full_update_async(# The entity split is only coherent once legacy rows are# classified.- from repowise.core.persistence.decision_migration import apply_migration+ from repowise.core.persistence.decision_migration import (+ apply_migration,+ backfill_scope_basis,+ backfill_session_scope_basis,+ prune_unindexed_scope_files,+ )await apply_migration(session, repo_id)+ # Run every index, beside the classification repair and for+ # the same reason: a record written before these rules existed+ # is only reachable from code that runs on an existing store.+ # The prune runs first so the basis repairs judge the file+ # list they will leave behind.+ await prune_unindexed_scope_files(session, repo_id)+ await backfill_scope_basis(session, repo_id)+ await backfill_session_scope_basis(session, repo_id)+if require_decision_persist_success:from repowise.core.persistence.crud import (purge_proposed_decisions_by_source,diff --git a/packages/core/alembic/versions/0070_decision_scope_basis.py b/packages/core/alembic/versions/0070_decision_scope_basis.pynew file mode 100644index 000000000..23b89fe6c--- /dev/null+++ b/packages/core/alembic/versions/0070_decision_scope_basis.py@@ -0,0 +1,52 @@+"""decision_records: record how a decision's file list was arrived at.++``affected_files_json`` was doing two jobs. For a record mined from a commit+it is the provenance of the change, which is worth keeping. It was also the+governance binding every path-scoped surface reads, and there it is mostly+false: the commit-derived miners take the commit's entire file list, so a+decision mined from a large refactor claimed every file the refactor touched.++This column separates the two. ``commit_footprint`` keeps the files and stops+the record answering for each one, ``stated`` marks a scope a person wrote+down, and the empty default binds as before.++Local SQLite stores never run Alembic -- ``init_db``'s reconciler issues+additive DDL for missing columns -- so this migration exists for managed+Postgres. The data repair is deliberately not here: it lives in+``decision_migration.backfill_scope_basis`` and runs on every index, because a+fix in a migration and a fix in the code eventually disagree, and only one of+them runs on an existing store.++Revision ID: 0070+Revises: 0069+Create Date: 2026-09-19+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0070"+down_revision: str | None = "0069"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "decision_records",+ sa.Column(+ "scope_basis",+ sa.String(length=32),+ nullable=False,+ server_default="",+ ),+ )+++def downgrade() -> None:+ op.drop_column("decision_records", "scope_basis")diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.pyindex 7da30471b..2483e7769 100644--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py@@ -53,7 +53,11 @@ from repowise.core.analysis.decisions.policy import (DecisionPolicy,resolve_policy,)-from repowise.core.analysis.decisions.scope import commit_scope_files, resolve_module_nodes+from repowise.core.analysis.decisions.scope import (+ commit_scope_basis,+ commit_scope_files,+ resolve_module_nodes,+)from repowise.core.fs_walk import PRUNED_DIRS, walk_repofrom repowise.core.ingestion.traverser import load_gitignore_spec@@ -146,6 +150,10 @@ class ExtractedDecision:affected_modules: list[str] = field(default_factory=list)tags: list[str] = field(default_factory=list)source: str = "inline_marker"+ #: See :class:`~repowise.core.persistence.models.DecisionRecord.scope_basis`.+ #: Set by the commit-derived miners, which are the only ones that take a+ #: file list they did not choose per file.+ scope_basis: str = ""evidence_commits: list[str] = field(default_factory=list)evidence_file: str | None = Noneevidence_line: int | None = None@@ -728,6 +736,9 @@ class DecisionExtractor:breakif sha:d.evidence_commits = [sha]+ # Basis is judged on the commit's whole list, before the+ # cap: 42 files stored as 20 is still a 42-file footprint.+ d.scope_basis = commit_scope_basis(commit_files.get(sha))d.affected_files = commit_scope_files(commit_files.get(sha))d.source_text = source_by_sha.get(sha, "")d.source = "git_archaeology"@@ -990,6 +1001,7 @@ class DecisionExtractor:breakif sha:d.evidence_commits = [sha]+ d.scope_basis = commit_scope_basis(files_by_sha.get(sha))d.affected_files = commit_scope_files(files_by_sha.get(sha))d.source_text = source_by_sha.get(sha, "")d.source = "pr"diff --git a/packages/core/src/repowise/core/analysis/decisions/scope.py b/packages/core/src/repowise/core/analysis/decisions/scope.pyindex 89b6deb83..31758d06d 100644--- a/packages/core/src/repowise/core/analysis/decisions/scope.py+++ b/packages/core/src/repowise/core/analysis/decisions/scope.py@@ -15,10 +15,19 @@ from repowise.core.support_paths import file_populationfrom repowise.core.test_paths import is_test_related_path__all__ = [+ "MAX_GOVERNING_FILES",+ "NON_BINDING_SCOPE_BASES",+ "SCOPE_BASIS_FOOTPRINT",+ "SCOPE_BASIS_PROXIMITY",+ "SCOPE_BASIS_REPOSITORY",+ "SCOPE_BASIS_STATED","bind_scope_files",+ "binds_to_paths",+ "commit_scope_basis","commit_scope_files","derive_decision_scope","resolve_module_nodes",+ "session_scope_basis",]#: Upper bound on the directories one record may claim. A record naming files@@ -41,6 +50,45 @@ _MAX_MODULES = 12_MAX_FILES = 20+#: The basis value marking a scope that is a commit's footprint rather than a+#: claim about particular files. Stored on the record, read wherever a file is+#: asked what governs it. Any other value (including the empty default) binds.+SCOPE_BASIS_FOOTPRINT = "commit_footprint"++#: The basis value marking files a session merely had open around the moment a+#: decision was stated. A session candidate takes the paths it was near --+#: the last few touched, plus what the next few events touch -- so the list is+#: proximity and not a claim, and a decision that spans unrelated parts of the+#: tree is usually a working rule that the session happened to restate while+#: editing them.+SCOPE_BASIS_PROXIMITY = "session_proximity"++#: The basis value for a record whose scope is the repository itself. A+#: working agreement governs how the work is conducted, so it is true+#: everywhere and specific nowhere; :data:`AGREEMENT_SCOPE` is the same claim+#: on the acceptance row.+SCOPE_BASIS_REPOSITORY = "repository"++#: The basis value marking a scope a person stated: typed at the CLI, written+#: into the manifest, or confirmed on review. It binds, like the empty default+#: does; the difference is that the backfill repairs an empty basis and never+#: touches this one, so a hand-narrowed scope is not re-marked as a footprint+#: on the next index.+SCOPE_BASIS_STATED = "stated"++#: Above this many files, a commit-derived list stops being a claim about+#: files and becomes the footprint of the change it was mined from. The miner+#: reads one decision out of one commit body and has no per-file evidence, so+#: it takes the commit's whole list: true about the commit, false about most+#: of the files in it.+#:+#: A breadth rule rather than a relevance one because relevance was tried and+#: does not work. Overlap between a decision's text and a file's own diff hunk+#: scores the worst answers highest, since lexical similarity tracks the+#: subsystem a file sits in and not whether the decision governs it.+MAX_GOVERNING_FILES = 10++#: Which population a scope entry is ranked under, narrowest claim first. A#: decision is about the system, so production code outranks the test that#: exercises it, which outranks an example, which outranks the docs and@@ -66,6 +114,67 @@ def commit_scope_files(files: Sequence[str] | None) -> list[str]:return sorted(_normalized(files))[:_MAX_FILES]+def commit_scope_basis(files: Sequence[str] | None) -> str:+ """The scope basis for a record mined from one commit's file list.++ Takes the commit's *whole* list, before :func:`commit_scope_files` caps+ it, so that a large commit stored as a capped list is still a footprint.+ """+ return SCOPE_BASIS_FOOTPRINT if len(_normalized(files)) > MAX_GOVERNING_FILES else ""+++#: Every basis that answers "these files are not what this record is about".+#: One set so a new one is added in a single place and every surface honours+#: it at once.+NON_BINDING_SCOPE_BASES: frozenset[str] = frozenset(+ {SCOPE_BASIS_FOOTPRINT, SCOPE_BASIS_PROXIMITY, SCOPE_BASIS_REPOSITORY}+)+++def session_scope_basis(files: Sequence[str] | None, *, is_agreement: bool) -> str:+ """The scope basis for a record mined from a session transcript.++ Session scope is not a footprint -- ``bind_scope_files`` already caps and+ orders it -- so breadth in files is the wrong measure and does not+ separate. What separates is whether the files sit together. Measured over+ 32 labelled file/decision pairs: a record whose files share one directory+ governs them 67% of the time, one spanning two or more governs 19%, and+ one spanning three or more top-level packages governs none of them.++ That is the same distinction :func:`derive_decision_scope` already draws,+ so it is drawn with the same rule rather than a second threshold: a+ session record that is cross-module is a rule the session restated while+ working, not a claim about the files it was working on.+ """+ if is_agreement:+ return SCOPE_BASIS_REPOSITORY+ kept = _normalized(files)+ if len(kept) <= 1:+ return ""+ return (+ SCOPE_BASIS_PROXIMITY+ if len(resolve_module_nodes(kept)) > 1+ else ""+ )+++def binds_to_paths(scope_basis: str | None) -> bool:+ """Whether a record with this basis may answer "what governs this path".++ The one predicate every path-scoped surface asks, so the wiki pages, the+ ``get_why`` lanes, ``get_context``, the decision graph and the health+ findings agree on which records are specific enough to name a path. A+ record that fails it keeps its files and its place in repository-wide+ answers -- search, the overview, a lookup by id.++ Modules are gated with files. A record's module list is+ :func:`resolve_module_nodes` over the same file list, so it is no better+ evidenced, and gating one without the other would leave the surfaces+ reading this column disagreeing with the ones reading the graph.+ """+ return scope_basis not in NON_BINDING_SCOPE_BASES++def bind_scope_files(files: Sequence[str] | None,indexed: Container[str] | None,diff --git a/packages/core/src/repowise/core/analysis/health/governance.py b/packages/core/src/repowise/core/analysis/health/governance.pyindex bc5988c41..8ea77c84f 100644--- a/packages/core/src/repowise/core/analysis/health/governance.py+++ b/packages/core/src/repowise/core/analysis/health/governance.py@@ -137,10 +137,16 @@ def _stale_governance_findings(health_summary: dict[str, Any]) -> list[HealthFin"""import json+ from repowise.core.analysis.decisions.scope import binds_to_paths+# file_path → best (staleness_score, decision) seen so farbest: dict[str, tuple[float, Any]] = {}for decision in health_summary.get("stale_decisions", []):+ # One HIGH finding per file below, so a stale footprint would flag+ # every file its commit touched.+ if not binds_to_paths(getattr(decision, "scope_basis", "")):+ continuetry:affected = json.loads(decision.affected_files_json or "[]")except (ValueError, TypeError):diff --git a/packages/core/src/repowise/core/generation/page_generator/helpers.py b/packages/core/src/repowise/core/generation/page_generator/helpers.pyindex 90597a1df..f40ad912a 100644--- a/packages/core/src/repowise/core/generation/page_generator/helpers.py+++ b/packages/core/src/repowise/core/generation/page_generator/helpers.py@@ -15,6 +15,7 @@ from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any+from repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRYfrom repowise.core.ingestion.models import ParsedFile@@ -331,6 +332,12 @@ def build_decision_maps("status": status,}decisions_all.append(payload)+ # Repo-wide lists keep every record; the per-file index does+ # not. A footprint would otherwise print on every file its commit+ # touched. It still reaches the overview, where a claim about a+ # whole change belongs.+ if not binds_to_paths(getattr(d, "scope_basis", "")):+ continuefor fp in d.affected_files or []:decisions_by_file.setdefault(fp, []).append(payload)return decisions_by_file, decisions_alldiff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex 92e5c789c..3cfd2320c 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -32,6 +32,7 @@ from repowise.core.analysis.decisions.lifecycle import (is_governing,legacy_status_for_currency,)+from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATEDfrom ..decision_graph import upsert_decision_edgefrom ..models import (@@ -616,6 +617,9 @@ async def accept_decision(record.rationale = reasonif scope is not None:record.affected_files_json = json.dumps(scope)+ # The accepter chose these files, so the record binds to them+ # rather than keeping the basis it was mined with.+ record.scope_basis = SCOPE_BASIS_STATEDacceptance = await record_acceptance(session,record,diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.pyindex 1ea108438..5e49918c9 100644--- a/packages/core/src/repowise/core/persistence/crud/decisions.py+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py@@ -30,6 +30,7 @@ from repowise.core.analysis.decisions.provenance import (normalize_text,rank_for_source,)+from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATED, binds_to_pathsfrom ..decision_graph import sync_decision_node_linksfrom ..models import (@@ -325,6 +326,9 @@ async def upsert_decision(rec.alternatives_json = json.dumps(alternatives or [])rec.consequences_json = json.dumps(consequences or [])rec.affected_files_json = json.dumps(affected_files or [])+ # The caller supplied these files, so they are its claim and not+ # any footprint the row carried.+ rec.scope_basis = SCOPE_BASIS_STATED if affected_files else ""rec.affected_modules_json = json.dumps(affected_modules or [])rec.tags_json = json.dumps(tags or [])rec.evidence_commits_json = json.dumps(evidence_commits or [])@@ -581,6 +585,9 @@ async def update_decision_metadata(rec.affected_modules_json = json.dumps(affected_modules)if affected_files is not None:rec.affected_files_json = json.dumps(affected_files)+ # A scope set by hand is stated, whatever the row held before:+ # otherwise the new files are stored and then ignored everywhere.+ rec.scope_basis = SCOPE_BASIS_STATEDrec.updated_at = _now_utc()await session.flush()return rec@@ -672,6 +679,10 @@ async def update_decision_by_id("affected_modules": "affected_modules_json","tags": "tags_json",}+ if "affected_files" in fields:+ # Same rule as every other path that takes a scope from its caller:+ # the basis has to move with the files it describes.+ rec.scope_basis = SCOPE_BASIS_STATED if fields["affected_files"] else ""_scalar_fields = {"title","context",@@ -1344,6 +1355,8 @@ async def bulk_upsert_decisions(alternatives_json=json.dumps(headline.get("alternatives") or []),consequences_json=json.dumps(headline.get("consequences") or []),affected_files_json=json.dumps(headline_files),+ # Rides with the file list it describes.+ scope_basis=headline.get("scope_basis") or "",affected_modules_json=json.dumps(headline.get("affected_modules") or []),tags_json=json.dumps(headline.get("tags") or []),evidence_commits_json=json.dumps(headline.get("evidence_commits") or []),@@ -1378,6 +1391,7 @@ async def bulk_upsert_decisions(rec.alternatives_json = json.dumps(headline.get("alternatives") or [])rec.consequences_json = json.dumps(headline.get("consequences") or [])rec.affected_files_json = json.dumps(headline.get("affected_files") or [])+ rec.scope_basis = headline.get("scope_basis") or ""rec.affected_modules_json = json.dumps(headline.get("affected_modules") or [])rec.tags_json = json.dumps(headline.get("tags") or [])rec.evidence_commits_json = json.dumps(headline.get("evidence_commits") or [])@@ -1432,12 +1446,16 @@ async def bulk_upsert_decisions(# Mirror the JSON file/module arrays into first-class decision→code# links so the graph is traversable both directions (Phase 3A). The# JSON stays the cheap read cache; these rows are the queryable truth.+ # A footprint contributes no links. The graph is what session+ # injection and the ``get_risk`` directives ask "which decisions touch+ # this node", so gating this one write path covers both readers.+ binds = binds_to_paths(rec.scope_basis)await sync_decision_node_links(session,repository_id,rec.id,- files=json.loads(rec.affected_files_json or "[]"),- modules=json.loads(rec.affected_modules_json or "[]"),+ files=json.loads(rec.affected_files_json or "[]") if binds else [],+ modules=json.loads(rec.affected_modules_json or "[]") if binds else [],)# (Re-)embed the record into the shared store so it's matchable by@@ -1901,6 +1919,10 @@ async def get_decision_health_summary(if currency == "uncheckable":counts["unscoped"] += 1unscoped_decisions.append(d)+ # ``governed_files`` is the denominator for "ungoverned hotspots",+ # so a footprint would suppress every file its commit touched.+ if not binds_to_paths(d.scope_basis):+ continuefor fp in json.loads(d.affected_files_json):governed_files.add(fp)diff --git a/packages/core/src/repowise/core/persistence/decision_dedupe.py b/packages/core/src/repowise/core/persistence/decision_dedupe.pyindex fa08d4eea..469c16a94 100644--- a/packages/core/src/repowise/core/persistence/decision_dedupe.py+++ b/packages/core/src/repowise/core/persistence/decision_dedupe.py@@ -60,6 +60,11 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.decisions.lifecycle import ARCHITECTURAL_KINDfrom repowise.core.analysis.decisions.provenance import rank_for_source+from repowise.core.analysis.decisions.scope import (+ SCOPE_BASIS_STATED,+ binds_to_paths,+ commit_scope_basis,+)from repowise.core.analysis.decisions.semantic_match import (DECISION_VECTOR_PREFIX,DEFAULT_DEDUP_TAU,@@ -348,13 +353,23 @@ async def apply_dedupe(for column, name in _UNION_FIELDS:setattr(canonical, column, json.dumps(sorted(union[name])))+ # The union widens the file list, so the basis is recomputed from+ # it rather than inherited: a footprint folding into a narrow+ # canonical would otherwise hand it the wide list under a binding+ # basis, on a record whose source the backfill does not repair.+ canonical.scope_basis = (+ SCOPE_BASIS_STATED+ if canonical.scope_basis == SCOPE_BASIS_STATED+ else commit_scope_basis(sorted(union["files"]))+ )# Sync replaces rather than accretes, so it must see the union.+ binds = binds_to_paths(canonical.scope_basis)await sync_decision_node_links(session,repository_id,canonical.id,- files=sorted(union["files"]),- modules=sorted(union["modules"]),+ files=sorted(union["files"]) if binds else [],+ modules=sorted(union["modules"]) if binds else [],)_rederive_headline(canonical, await list_decision_evidence(session, canonical.id))applied.clusters.append(done)diff --git a/packages/core/src/repowise/core/persistence/decision_manifest.py b/packages/core/src/repowise/core/persistence/decision_manifest.pyindex d61e23437..66fe9f0d7 100644--- a/packages/core/src/repowise/core/persistence/decision_manifest.py+++ b/packages/core/src/repowise/core/persistence/decision_manifest.py@@ -28,6 +28,7 @@ from repowise.core.analysis.decisions.manifest import (write_manifest,)from repowise.core.analysis.decisions.provenance import compute_confidence, rank_for_source+from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATEDfrom .crud.authority import (accepted_decision_ids,@@ -228,6 +229,9 @@ async def _apply_entry(record.confidence = _entry_confidence(entry)record.kind = entry.kind or ARCHITECTURAL_KINDrecord.affected_files_json = json.dumps(sorted(_scope_files(entry.scope)))+ # The file is hand-authored and version controlled, so its scope is+ # stated: a record narrowed here binds to what the file says.+ record.scope_basis = SCOPE_BASIS_STATED# The successor is an id the file wrote down, and the file can be older# than the store it is being read into. Storing it unresolved would put a# retired id back into the column.@@ -307,6 +311,7 @@ async def import_manifest(source=entry.source or "cli",kind=entry.kind or ARCHITECTURAL_KIND,affected_files_json=json.dumps(sorted(_scope_files(entry.scope))),+ scope_basis=SCOPE_BASIS_STATED,evidence_commits_json=json.dumps(sorted(entry.evidence)),superseded_by=entry.superseded_by or None,confidence=_entry_confidence(entry),diff --git a/packages/core/src/repowise/core/persistence/decision_migration.py b/packages/core/src/repowise/core/persistence/decision_migration.pyindex d8dc74adf..f6a44c941 100644--- a/packages/core/src/repowise/core/persistence/decision_migration.py+++ b/packages/core/src/repowise/core/persistence/decision_migration.py@@ -20,7 +20,7 @@ import refrom collections import Counter, defaultdictfrom dataclasses import dataclass, field-from sqlalchemy import select+from sqlalchemy import delete, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.decisions.kinds import classify_kind@@ -28,6 +28,12 @@ from repowise.core.analysis.decisions.lifecycle import (AGREEMENT_KIND,currency_for_legacy_status,)+from repowise.core.analysis.decisions.scope import (+ MAX_GOVERNING_FILES,+ SCOPE_BASIS_FOOTPRINT,+ resolve_module_nodes,+ session_scope_basis,+)from .crud.authority import (AcceptanceRefusedError,@@ -36,14 +42,18 @@ from .crud.authority import (record_acceptance,upsert_candidate_meta,)-from .models import DecisionCandidateMeta, DecisionRecord+from .decision_graph import DecisionNodeLink+from .models import DecisionCandidateMeta, DecisionRecord, GraphNode__all__ = ["MigrationPlan","RowPlan","apply_migration",+ "backfill_scope_basis",+ "backfill_session_scope_basis","plan_json","plan_migration",+ "prune_unindexed_scope_files","render_plan",]@@ -404,6 +414,180 @@ async def apply_migration(return plan+#: Sources whose file list was only ever a commit's whole file list. Neither+#: miner ever chose a file. Every other source names files it saw, so none of+#: them is repaired here.+_COMMIT_FOOTPRINT_SOURCES: frozenset[str] = frozenset({"pr", "git_archaeology"})+++async def backfill_scope_basis(session: AsyncSession, repository_id: str) -> int:+ """Mark legacy commit-derived records whose files are a footprint.++ Returns the number of records changed. A runtime repair for the same+ reason as the rest of this module: the rows predate the column, and only+ code that runs on an existing store can fix them.++ Only rows with an **empty** basis are touched, which makes this idempotent+ and leaves a scope somebody set by hand alone.++ The record keeps its files and loses its decision-graph links. Those are+ dropped here rather than left to the next ``bulk_upsert_decisions``: a+ record nothing re-extracts is never rewritten, and would keep answering+ path questions from the graph forever.+ """+ rows = (+ (+ await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id,+ DecisionRecord.source.in_(tuple(_COMMIT_FOOTPRINT_SOURCES)),+ DecisionRecord.scope_basis == "",+ )+ )+ )+ .scalars()+ .all()+ )+ changed = 0+ for rec in rows:+ try:+ files = json.loads(rec.affected_files_json or "[]")+ except ValueError:+ continue+ if len(files) <= MAX_GOVERNING_FILES:+ continue+ rec.scope_basis = SCOPE_BASIS_FOOTPRINT+ await session.execute(+ delete(DecisionNodeLink).where(DecisionNodeLink.decision_id == rec.id)+ )+ changed += 1+ if changed:+ await session.flush()+ return changed+++async def backfill_session_scope_basis(+ session: AsyncSession, repository_id: str+) -> int:+ """Mark legacy session-mined records whose files are proximity, not scope.++ Returns the number of records changed. The companion to+ :func:`backfill_scope_basis` for the other miner, and empty-basis-only for+ the same reason: it repairs what the old code wrote and leaves a scope+ somebody set by hand alone.++ A session record's files are the paths the transcript was near when the+ decision was stated, so a working rule restated while editing four+ packages claims all four. Measured over 32 labelled pairs, a record whose+ files share one directory governs them 67% of the time and one spanning+ more governs 19%, which is the line :func:`session_scope_basis` draws.+ """+ rows = (+ (+ await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id,+ DecisionRecord.source == "session",+ DecisionRecord.scope_basis == "",+ )+ )+ )+ .scalars()+ .all()+ )+ changed = 0+ for rec in rows:+ try:+ files = json.loads(rec.affected_files_json or "[]")+ except ValueError:+ continue+ basis = session_scope_basis(files, is_agreement=rec.kind == AGREEMENT_KIND)+ if not basis:+ continue+ rec.scope_basis = basis+ await session.execute(+ delete(DecisionNodeLink).where(DecisionNodeLink.decision_id == rec.id)+ )+ changed += 1+ if changed:+ await session.flush()+ return changed+++#: Below this many indexed file nodes, the graph is treated as unbuilt rather+#: than as evidence that a scope is wrong. Pruning against a graph that failed+#: to build would empty every scope in the store, which is the one outcome+#: worse than the stale entries this removes.+_MIN_GRAPH_NODES_TO_PRUNE = 50+++async def prune_unindexed_scope_files(+ session: AsyncSession, repository_id: str+) -> int:+ """Drop scope entries naming a file this repository does not index.++ Returns the number of records changed. Repairs rows written before the+ indexed-set filter reached the session miner: a transcript names plan+ docs, scratch files, sibling checkouts and throwaway worktrees, and every+ one of those resolved on disk and was bound as though it were this+ codebase.++ Validates against the graph's own file nodes, which is the set+ ``decision_node_links`` points into, so an entry this drops could never+ have been a valid link. Skipped entirely when the graph looks unbuilt.++ Rewriting the file list moves the record's identity, which the id+ migration at the head of the next index settles and leaves an alias for,+ exactly as it does for a scope edited through the manifest or an+ acceptance.+ """+ indexed = {+ node_id+ for (node_id,) in await session.execute(+ select(GraphNode.node_id).where(+ GraphNode.repository_id == repository_id,+ GraphNode.node_type == "file",+ )+ )+ }+ if len(indexed) < _MIN_GRAPH_NODES_TO_PRUNE:+ return 0++ rows = (+ (+ await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id+ )+ )+ )+ .scalars()+ .all()+ )+ changed = 0+ for rec in rows:+ try:+ files = json.loads(rec.affected_files_json or "[]")+ except ValueError:+ continue+ kept = [f for f in files if f in indexed]+ if len(kept) == len(files):+ continue+ rec.affected_files_json = json.dumps(kept)+ rec.affected_modules_json = json.dumps(resolve_module_nodes(kept))+ for dropped in set(files) - set(kept):+ await session.execute(+ delete(DecisionNodeLink).where(+ DecisionNodeLink.decision_id == rec.id,+ DecisionNodeLink.node_id == dropped,+ )+ )+ changed += 1+ if changed:+ await session.flush()+ return changed++def render_plan(plan: MigrationPlan, *, limit: int = 10) -> str:"""A human-readable dry-run report."""counts = plan.counts()diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 4e6d06e6e..507683dcb 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -953,6 +953,14 @@ class DecisionRecord(Base):identity_quote: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="")+ #: How ``affected_files_json`` was arrived at, and so whether this record+ #: may answer "what governs this path". ``commit_footprint`` means the+ #: files are the file list of the commit the record was mined from: kept+ #: for provenance and staleness, skipped by every path-scoped surface.+ #: See :func:`~repowise.core.analysis.decisions.scope.binds_to_paths`.+ scope_basis: Mapped[str] = mapped_column(+ String(32), nullable=False, default="", server_default=""+ )confidence: Mapped[float] = mapped_column(Float, nullable=False, default=1.0)# Verification (anti-hallucination gate, Phase 1D). Aggregate over thediff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 5fef4be12..187820373 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -2064,9 +2064,20 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:# with half the surfaces reading each. Idempotent, and it never reopens a# review action somebody already performed.try:- from repowise.core.persistence.decision_migration import apply_migration+ from repowise.core.persistence.decision_migration import (+ apply_migration,+ backfill_scope_basis,+ backfill_session_scope_basis,+ prune_unindexed_scope_files,+ )await apply_migration(session, repo_id)+ # Beside it, and for the same reason: these repair rows written before+ # the rule existed, and nothing re-extracts them. The prune runs first+ # so the two basis repairs judge the file list they will leave behind.+ await prune_unindexed_scope_files(session, repo_id)+ await backfill_scope_basis(session, repo_id)+ await backfill_session_scope_basis(session, repo_id)except Exception as _migrate_err:logger.debug("decision_entity_migration_skipped", error=str(_migrate_err))diff --git a/packages/core/src/repowise/core/pipeline/resume/rehydrate.py b/packages/core/src/repowise/core/pipeline/resume/rehydrate.pyindex 2ce8c7fed..4aff3123a 100644--- a/packages/core/src/repowise/core/pipeline/resume/rehydrate.py+++ b/packages/core/src/repowise/core/pipeline/resume/rehydrate.py@@ -133,6 +133,10 @@ async def rehydrate_decision_report(session: Any, repo_id: str) -> Any:# same way a fresh one does. Without it every rehydrated# record read as a proposal, including the accepted ones.status=r.status,+ # Same reason: the per-file index reads this and fails+ # open without it, so a resumed run would differ from a fresh+ # one.+ scope_basis=r.scope_basis,))return SimpleNamespace(decisions=decisions)diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.pyindex 05fd140d7..0aa0b2e9c 100644--- a/packages/core/src/repowise/core/sessions/miners/decisions.py+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py@@ -59,7 +59,7 @@ import structlogfrom repowise.core.analysis.decisions.discovery.spans import SpanCollectorfrom repowise.core.analysis.decisions.extractor import ExtractedDecisionfrom repowise.core.analysis.decisions.kinds import classify_kind-from repowise.core.analysis.decisions.lifecycle import bundles_decisions+from repowise.core.analysis.decisions.lifecycle import AGREEMENT_KIND, bundles_decisionsfrom repowise.core.analysis.decisions.policy import DEFAULT_HARNESSES, resolve_policyfrom repowise.core.analysis.decisions.provenance import (completeness,@@ -68,7 +68,11 @@ from repowise.core.analysis.decisions.provenance import (verify_quote,)from repowise.core.analysis.decisions.rationale_comments import CAUSAL_MARKERS-from repowise.core.analysis.decisions.scope import bind_scope_files, resolve_module_nodes+from repowise.core.analysis.decisions.scope import (+ bind_scope_files,+ resolve_module_nodes,+ session_scope_basis,+)from repowise.core.distill.corrections import command_anchorfrom repowise.core.precedent.transcript_episodes import (TranscriptEpisodeRecorder,@@ -839,6 +843,9 @@ def promotion_decisions(structured.get("rationale", "") or "",source="session",)+ # The files stay on the record; whether they are a claim about those files+ # is a separate question, and this is where both answers are known.+ scope_basis = session_scope_basis(files, is_agreement=kind == AGREEMENT_KIND)return [ExtractedDecision(title=row["title"],@@ -846,6 +853,7 @@ def promotion_decisions(rationale=structured.get("rationale", ""),affected_files=files,affected_modules=modules,+ scope_basis=scope_basis,source="session",evidence_commits=[sid] if sid else [],confidence=confidence,diff --git a/packages/server/src/repowise/server/mcp_server/_answer_context.py b/packages/server/src/repowise/server/mcp_server/_answer_context.pyindex 233b58fa3..1a4641e2b 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_context.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_context.py@@ -28,6 +28,7 @@ from typing import Anyfrom sqlalchemy import selectfrom repowise.core.analysis.decisions.lifecycle import is_governing+from repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.persistence.crud.authority import decision_currenciesfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import DecisionRecord, GitMetadata@@ -157,6 +158,10 @@ async def fetch_relevant_decisions(scored: list[tuple[int, float, DecisionRecord]] = []for d in all_decisions:+ # Ranked by overlap count, so a footprint would outrank a record+ # naming one file exactly, and this renders into the prompt.+ if not binds_to_paths(d.scope_basis):+ continuetry:affected = set(json.loads(d.affected_files_json or "[]"))except (json.JSONDecodeError, TypeError):diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex e2dcf2d3f..d52bd762d 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -14,6 +14,7 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.decisions.lifecycle import is_governing+from repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRYfrom repowise.core.persistence.models import (Repository,@@ -522,6 +523,10 @@ def _sibling_coverage(for d in all_decisions:if getattr(d, "id", None) not in accepted_ids:continue+ # An accepted footprint would count as a covered sibling in every+ # directory it touched.+ if not binds_to_paths(getattr(d, "scope_basis", "")):+ continueaffected = json.loads(d.affected_files_json)for af in affected:af_dir = "/".join(af.split("/")[:-1])diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.pyindex 8435a5656..dbaa0c287 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py@@ -18,6 +18,7 @@ from sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.decisions.lifecycle import is_governing+from repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.generation.page_selection import STALE_STATUSESfrom repowise.core.ingestion.models import (NON_DEPENDENCY_EDGE_TYPES,@@ -1116,6 +1117,10 @@ async def _resolve_one_target(candidates: list[dict[str, Any]] = []history: list[dict[str, Any]] = []for d in all_decisions:+ # A commit footprint is not a claim about any one of its+ # files.+ if not binds_to_paths(d.scope_basis):+ continueaffected_files = json.loads(d.affected_files_json)affected_modules = json.loads(d.affected_modules_json)if not (diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 455cb6b9f..026652eac 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -13,6 +13,7 @@ from sqlalchemy import selectfrom repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIXfrom repowise.core.analysis.decisions.lifecycle import is_governing, status_rank+from repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.persistence.crud.authority import (accepted_decision_ids,decision_currencies,@@ -1022,11 +1023,17 @@ async def _why_path(query: str, repo: str | None) -> dict:)all_git_meta = all_git_res.scalars().all()+ # A record whose file list is the footprint of the commit it was+ # mined from does not answer "what governs this file". It keeps its+ # files and its place in search; it stops claiming to be specific.matched = [dfor d in all_decisions- if query in json.loads(d.affected_files_json)- or query in json.loads(d.affected_modules_json)+ if binds_to_paths(d.scope_basis)+ and (+ query in json.loads(d.affected_files_json)+ or query in json.loads(d.affected_modules_json)+ )]# The authority split, and the only test that makes it: a record with# no acceptance row is a candidate whatever its status column says.@@ -1604,6 +1611,9 @@ async def _build_target_context(for t in targets:governing_records = []for d in all_decisions:+ # Same gate as ``_why_path``, which one target routes to.+ if not binds_to_paths(d.scope_basis):+ continueaffected = json.loads(d.affected_files_json)affected_mods = json.loads(d.affected_modules_json)if t in affected or any(t.startswith(m + "/") for m in affected_mods):diff --git a/packages/server/src/repowise/server/services/node_signals.py b/packages/server/src/repowise/server/services/node_signals.pyindex d4da1c884..4e156669d 100644--- a/packages/server/src/repowise/server/services/node_signals.py+++ b/packages/server/src/repowise/server/services/node_signals.py@@ -16,6 +16,7 @@ from typing import Any, TypeVarfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.decisions.scope import SCOPE_BASIS_FOOTPRINTfrom repowise.core.persistence.models import (DeadCodeFinding,DecisionRecord,@@ -99,6 +100,9 @@ async def collect_node_signals(dec_q = select(DecisionRecord.affected_files_json).where(DecisionRecord.repository_id == repo_id,DecisionRecord.status.in_(("active", "proposed")),+ # A commit footprint does not make each file it touched a file+ # with a decision.+ DecisionRecord.scope_basis != SCOPE_BASIS_FOOTPRINT,)decision_paths: set[str] = set()for (raw,) in (await session.execute(dec_q)).all():diff --git a/tests/unit/analysis/test_decision_scope.py b/tests/unit/analysis/test_decision_scope.pyindex 191eb7a7d..e275571af 100644--- a/tests/unit/analysis/test_decision_scope.py+++ b/tests/unit/analysis/test_decision_scope.py@@ -3,9 +3,18 @@from __future__ import annotationsfrom repowise.core.analysis.decisions.scope import (+ MAX_GOVERNING_FILES,+ NON_BINDING_SCOPE_BASES,+ SCOPE_BASIS_FOOTPRINT,+ SCOPE_BASIS_PROXIMITY,+ SCOPE_BASIS_REPOSITORY,+ SCOPE_BASIS_STATED,bind_scope_files,+ binds_to_paths,+ commit_scope_basis,commit_scope_files,derive_decision_scope,+ session_scope_basis,)@@ -157,3 +166,86 @@ def test_blanks_and_duplicates_collapse() -> None:def test_the_file_cap_still_applies() -> None:wide = frozenset(f"pkg/m{i:03d}.py" for i in range(40))assert len(bind_scope_files(sorted(wide), wide)) == 20+++# ---------------------------------------------------------------------------+# Scope basis: when a file list is a claim, and when it is a footprint+# ---------------------------------------------------------------------------+++def test_a_narrow_commit_list_is_a_claim() -> None:+ assert commit_scope_basis([f"pkg/m{i}.py" for i in range(MAX_GOVERNING_FILES)]) == ""+++def test_a_wide_commit_list_is_a_footprint() -> None:+ files = [f"pkg/m{i}.py" for i in range(MAX_GOVERNING_FILES + 1)]+ assert commit_scope_basis(files) == SCOPE_BASIS_FOOTPRINT+++def test_the_cap_does_not_launder_a_huge_commit_into_a_claim() -> None:+ """A large commit stored as a capped list is still a footprint.++ Pins the ordering between two independent limits: ``MAX_GOVERNING_FILES``+ must stay below ``commit_scope_files``'s own cap. Raise it to the storage+ cap and every oversized commit comes back a claim of exactly the cap.+ """+ commit = [f"pkg/m{i:03d}.py" for i in range(42)]+ stored = commit_scope_files(commit)+ assert len(stored) < len(commit)+ assert len(stored) > MAX_GOVERNING_FILES+ assert commit_scope_basis(commit) == SCOPE_BASIS_FOOTPRINT+++def test_an_empty_list_is_not_a_footprint() -> None:+ assert commit_scope_basis([]) == ""+ assert commit_scope_basis(None) == ""+++def test_duplicates_do_not_inflate_a_list_into_a_footprint() -> None:+ files = ["pkg/a.py"] * (MAX_GOVERNING_FILES + 5)+ assert commit_scope_basis(files) == ""+++def test_only_the_footprint_basis_stops_a_record_binding_per_file() -> None:+ assert binds_to_paths("") is True+ assert binds_to_paths(None) is True+ assert binds_to_paths("stated") is True+ assert binds_to_paths(SCOPE_BASIS_FOOTPRINT) is False+++# ---------------------------------------------------------------------------+# Session scope: proximity, not a footprint+# ---------------------------------------------------------------------------+++def test_one_file_is_a_claim() -> None:+ assert session_scope_basis(["pkg/a/x.py"], is_agreement=False) == ""+++def test_files_in_one_directory_are_a_claim() -> None:+ assert session_scope_basis(["pkg/a/x.py", "pkg/a/y.py"], is_agreement=False) == ""+++def test_files_across_directories_are_proximity() -> None:+ """A rule restated while editing two areas is not about either of them."""+ basis = session_scope_basis(["pkg/a/x.py", "pkg/b/y.py"], is_agreement=False)+ assert basis == SCOPE_BASIS_PROXIMITY+++def test_an_agreement_is_scoped_to_the_repository_however_narrow() -> None:+ """It governs how the work is conducted, so no file is what it is about."""+ assert (+ session_scope_basis(["pkg/a/x.py"], is_agreement=True)+ == SCOPE_BASIS_REPOSITORY+ )+++def test_no_files_is_not_proximity() -> None:+ assert session_scope_basis([], is_agreement=False) == ""+++def test_every_non_binding_basis_is_refused_by_the_one_predicate() -> None:+ for basis in NON_BINDING_SCOPE_BASES:+ assert binds_to_paths(basis) is False+ assert SCOPE_BASIS_STATED not in NON_BINDING_SCOPE_BASES+ assert binds_to_paths(SCOPE_BASIS_STATED) is Truediff --git a/tests/unit/generation/test_decision_scoping.py b/tests/unit/generation/test_decision_scoping.pyindex e4e62bc4a..267d20c41 100644--- a/tests/unit/generation/test_decision_scoping.py+++ b/tests/unit/generation/test_decision_scoping.py@@ -12,6 +12,7 @@ import refrom pathlib import Pathfrom types import SimpleNamespace+from repowise.core.analysis.decisions.scope import SCOPE_BASIS_FOOTPRINTfrom repowise.core.generation.page_generator.helpers import (build_decision_maps,decisions_for_files,@@ -30,7 +31,14 @@ def _decision(title: str, *, confidence: float | None = 1.0, evidence: str = "e.return payload-def _record(title: str, *, status: str = "proposed", confidence: float = 0.5) -> SimpleNamespace:+def _record(+ title: str,+ *,+ status: str = "proposed",+ confidence: float = 0.5,+ scope_basis: str = "",+ affected_files: list[str] | None = None,+) -> SimpleNamespace:return SimpleNamespace(title=title,decision=f"{title}: do the thing",@@ -38,8 +46,9 @@ def _record(title: str, *, status: str = "proposed", confidence: float = 0.5) ->source="session",confidence=confidence,evidence_file="e.py",- affected_files=["src/app.py"],+ affected_files=affected_files or ["src/app.py"],status=status,+ scope_basis=scope_basis,)@@ -171,3 +180,51 @@ def test_a_record_that_carries_no_status_reads_as_a_proposal():_, all_decisions = build_decision_maps(report)assert all_decisions[0]["status"] == "proposed"+++# ---------------------------------------------------------------------------+# A commit footprint reaches the overview but not a file page+# ---------------------------------------------------------------------------+++def test_a_footprint_is_kept_out_of_the_per_file_index():+ """Its files are the footprint of the commit it was mined from: a true+ statement about the change, a false one about most of the files."""+ report = SimpleNamespace(+ decisions=[+ _record("Narrow rule"),+ _record(+ "Collapse unchanged re-reads",+ scope_basis=SCOPE_BASIS_FOOTPRINT,+ affected_files=["src/app.py", "src/unrelated.py"],+ ),+ ]+ )++ by_file, _ = build_decision_maps(report)++ assert [d["title"] for d in by_file["src/app.py"]] == ["Narrow rule"]+ assert "src/unrelated.py" not in by_file+++def test_a_footprint_still_reaches_the_repository_overview():+ """A claim about a whole change belongs on the page about the whole repo."""+ report = SimpleNamespace(+ decisions=[_record("Wide rule", scope_basis=SCOPE_BASIS_FOOTPRINT)]+ )++ _, all_decisions = build_decision_maps(report)++ assert [d["title"] for d in all_decisions] == ["Wide rule"]+++def test_a_record_with_no_basis_attribute_still_binds():+ """Resume rehydrates records as plain namespaces. That path carries the+ basis, but one built elsewhere must not silently lose its file pages."""+ record = _record("Legacy shape")+ del record.scope_basis+ report = SimpleNamespace(decisions=[record])++ by_file, _ = build_decision_maps(report)++ assert [d["title"] for d in by_file["src/app.py"]] == ["Legacy shape"]diff --git a/tests/unit/persistence/test_decision_dedupe.py b/tests/unit/persistence/test_decision_dedupe.pyindex 54c90dfc4..7f1d45c7e 100644--- a/tests/unit/persistence/test_decision_dedupe.py+++ b/tests/unit/persistence/test_decision_dedupe.py@@ -14,6 +14,11 @@ import mathimport pytestfrom sqlalchemy import select+from repowise.core.analysis.decisions.scope import (+ MAX_GOVERNING_FILES,+ SCOPE_BASIS_FOOTPRINT,+ SCOPE_BASIS_STATED,+)from repowise.core.analysis.decisions.semantic_match import DECISION_VECTOR_PREFIXfrom repowise.core.persistence.crud.authority import (accept_decision,@@ -80,6 +85,7 @@ async def _seed(session, store, repo_id, specs: list[dict]) -> list[DecisionRecokind=spec.get("kind", "architectural"),confidence=spec.get("confidence", 0.5),affected_files_json=json.dumps(spec.get("files", [])),+ scope_basis=spec.get("scope_basis", ""),affected_modules_json=json.dumps([]),evidence_commits_json=json.dumps(spec.get("commits", [])),tags_json=json.dumps([]),@@ -504,3 +510,103 @@ async def test_a_superseded_record_keeps_its_lineage(async_session, repo_id):assert plan.folded_count == 0assert await async_session.get(DecisionRecord, retired.id) is not None+++# ---------------------------------------------------------------------------+# The fold and the scope basis+# ---------------------------------------------------------------------------++_WIDE = [f"pkg/m{i:02d}.py" for i in range(30)]+++async def _links(session, decision_id) -> set[str]:+ rows = (+ (+ await session.execute(+ select(DecisionNodeLink).where(+ DecisionNodeLink.decision_id == decision_id+ )+ )+ )+ .scalars()+ .all()+ )+ return {row.node_id for row in rows}+++async def test_a_footprint_folding_in_does_not_resurrect_its_files(+ async_session, repo_id+):+ """The union widens the canonical past the bar, so the basis is+ recomputed rather than inherited: the canonical's ``source`` is usually+ not one ``backfill_scope_basis`` would repair afterwards."""+ store = _store()+ canonical, _duplicate = await _seed(+ async_session,+ store,+ repo_id,+ [+ {+ "title": "Keep @a",+ "source": "pr",+ "decision": "Body",+ "files": ["kept.py"],+ },+ {+ "title": "Drop @a",+ "source": "comment",+ "files": _WIDE,+ "scope_basis": SCOPE_BASIS_FOOTPRINT,+ },+ ],+ )+ await apply_dedupe(async_session, repo_id, vector_store=store, tau=TAU)++ survivor = await async_session.get(DecisionRecord, canonical.id)+ assert len(json.loads(survivor.affected_files_json)) > MAX_GOVERNING_FILES+ assert survivor.scope_basis == SCOPE_BASIS_FOOTPRINT+ assert await _links(async_session, canonical.id) == set()+++async def test_a_fold_that_stays_narrow_keeps_binding(async_session, repo_id):+ """The recompute must not demote a fold that is still a real claim."""+ store = _store()+ canonical, _duplicate = await _seed(+ async_session,+ store,+ repo_id,+ [+ {"title": "Keep @a", "source": "pr", "decision": "Body", "files": ["a.py"]},+ {"title": "Drop @a", "source": "comment", "files": ["b.py"]},+ ],+ )+ await apply_dedupe(async_session, repo_id, vector_store=store, tau=TAU)++ survivor = await async_session.get(DecisionRecord, canonical.id)+ assert survivor.scope_basis == ""+ assert await _links(async_session, canonical.id) == {"a.py", "b.py"}+++async def test_a_fold_never_overwrites_a_stated_basis(async_session, repo_id):+ """A scope a person accepted survives a later dedupe sweep."""+ store = _store()+ canonical, _duplicate = await _seed(+ async_session,+ store,+ repo_id,+ [+ {+ "title": "Keep @a",+ "source": "pr",+ "decision": "Body",+ "files": ["a.py"],+ "scope_basis": SCOPE_BASIS_STATED,+ },+ {"title": "Drop @a", "source": "comment", "files": _WIDE},+ ],+ )+ await apply_dedupe(async_session, repo_id, vector_store=store, tau=TAU)++ survivor = await async_session.get(DecisionRecord, canonical.id)+ assert survivor.scope_basis == SCOPE_BASIS_STATED+ assert "a.py" in await _links(async_session, canonical.id)diff --git a/tests/unit/persistence/test_decision_scope_basis.py b/tests/unit/persistence/test_decision_scope_basis.pynew file mode 100644index 000000000..ee5260918--- /dev/null+++ b/tests/unit/persistence/test_decision_scope_basis.py@@ -0,0 +1,486 @@+"""A commit footprint keeps its files and stops answering per-file questions.++The defect these pin: the ``pr`` and ``git_archaeology`` miners read one+decision out of one commit body and then take that commit's whole file list,+so a decision mined from a large refactor claims every file it touched, and+``get_why`` on a file answers with decisions about something else.++The case the fixtures are modelled on: ``search_digest.py``, whose whole job+is compacting Grep output, carried five decisions about collapsing repeated+file reads -- a mechanism in a sibling module -- because all five were mined+from one 38-file commit that happened to touch it.+"""++from __future__ import annotations++import json++from sqlalchemy import select++from repowise.core.analysis.decisions.scope import (+ SCOPE_BASIS_FOOTPRINT,+ SCOPE_BASIS_PROXIMITY,+ SCOPE_BASIS_REPOSITORY,+ SCOPE_BASIS_STATED,+)+from repowise.core.persistence.crud import bulk_upsert_decisions, update_decision_metadata+from repowise.core.persistence.decision_graph import (+ get_governed_nodes,+ get_governing_decisions,+)+from repowise.core.persistence.decision_migration import (+ backfill_scope_basis,+ backfill_session_scope_basis,+ prune_unindexed_scope_files,+)+from repowise.core.persistence.models import (+ DecisionNodeLink,+ DecisionRecord,+ GraphNode,+)+from tests.unit.persistence.helpers import insert_repo++#: The mechanism file and the bystander, as in the real commit.+_MECHANISM = "packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py"+_BYSTANDER = "packages/cli/src/repowise/cli/commands/augment_cmd/search_digest.py"+_COMMIT_FILES = [_MECHANISM, _BYSTANDER] + [+ f"packages/core/src/mod{i:02d}.py" for i in range(36)+]+++def _decision(+ title: str, *, files: list[str], scope_basis: str = "", source: str = "pr"+) -> dict:+ return {+ "title": title,+ "decision": f"{title} body",+ "rationale": "measured",+ "source": source,+ "status": "active",+ "affected_files": files,+ "affected_modules": [],+ "scope_basis": scope_basis,+ "evidence_file": None,+ "confidence": 0.8,+ "verification": "exact",+ "source_quote": title,+ }+++async def test_a_footprint_writes_no_file_links(async_session):+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [+ _decision(+ "Collapse unchanged hook re-reads",+ files=_COMMIT_FILES,+ scope_basis=SCOPE_BASIS_FOOTPRINT,+ )+ ],+ )+ did = ids[0]++ # The bystander must not be told this governs it. Nor must the mechanism:+ # the record carries no evidence naming either one.+ assert await get_governing_decisions(async_session, repo.id, _BYSTANDER) == []+ assert await get_governing_decisions(async_session, repo.id, _MECHANISM) == []+ assert [link.link_type for link in await get_governed_nodes(async_session, did)] == []+++async def test_a_footprint_keeps_its_files_on_the_record(async_session):+ """Provenance survives. Staleness and the origin story both read this."""+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_decision("Wide rule", files=_COMMIT_FILES, scope_basis=SCOPE_BASIS_FOOTPRINT)],+ )+ rec = await async_session.get(DecisionRecord, ids[0])+ assert json.loads(rec.affected_files_json) == _COMMIT_FILES+ assert rec.scope_basis == SCOPE_BASIS_FOOTPRINT+++async def test_a_narrow_record_still_binds(async_session):+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_decision("Pin the read state", files=[_MECHANISM], source="inline_marker")],+ )+ governing = await get_governing_decisions(async_session, repo.id, _MECHANISM)+ assert [d.id for d in governing] == ids+++async def test_a_footprint_links_no_modules_either(async_session):+ """Its module list is the directories of the same file list, so no better+ evidenced."""+ repo = await insert_repo(async_session)+ payload = _decision(+ "Wide rule", files=_COMMIT_FILES, scope_basis=SCOPE_BASIS_FOOTPRINT+ )+ payload["affected_modules"] = ["packages/core/src"]+ ids = await bulk_upsert_decisions(async_session, repo.id, [payload])+ assert await get_governed_nodes(async_session, ids[0]) == []+++# ---------------------------------------------------------------------------+# The backfill, for records written before the basis existed+# ---------------------------------------------------------------------------+++async def test_backfill_marks_a_legacy_wide_pr_record_and_drops_its_file_links(+ async_session,+):+ repo = await insert_repo(async_session)+ # Written the way the old code wrote it: no basis, whole commit list.+ ids = await bulk_upsert_decisions(+ async_session, repo.id, [_decision("Legacy wide", files=_COMMIT_FILES)]+ )+ did = ids[0]+ assert await get_governing_decisions(async_session, repo.id, _BYSTANDER) != []++ assert await backfill_scope_basis(async_session, repo.id) == 1++ rec = await async_session.get(DecisionRecord, did)+ assert rec.scope_basis == SCOPE_BASIS_FOOTPRINT+ assert json.loads(rec.affected_files_json) == _COMMIT_FILES+ assert await get_governing_decisions(async_session, repo.id, _BYSTANDER) == []+++async def test_backfill_leaves_a_narrow_commit_record_alone(async_session):+ repo = await insert_repo(async_session)+ files = [f"pkg/m{i}.py" for i in range(4)]+ await bulk_upsert_decisions(+ async_session, repo.id, [_decision("Narrow", files=files)]+ )++ assert await backfill_scope_basis(async_session, repo.id) == 0+ assert await get_governing_decisions(async_session, repo.id, files[0]) != []+++async def test_backfill_leaves_a_wide_record_from_another_source_alone(async_session):+ """Only the two miners that never chose a file are repaired.++ A session-mined record names files the session touched, so a wide one is a+ wide claim rather than a footprint, and demoting it here would be guessing.+ """+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_decision("Wide session rule", files=_COMMIT_FILES, source="session")],+ )+ assert await backfill_scope_basis(async_session, repo.id) == 0+ assert await get_governing_decisions(async_session, repo.id, _BYSTANDER) != []+++async def test_backfill_is_idempotent(async_session):+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(+ async_session, repo.id, [_decision("Legacy wide", files=_COMMIT_FILES)]+ )+ assert await backfill_scope_basis(async_session, repo.id) == 1+ assert await backfill_scope_basis(async_session, repo.id) == 0+++async def test_backfill_does_not_touch_a_basis_somebody_already_set(async_session):+ """``decision confirm --scope`` writes a scope by hand; it stays."""+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_decision("Confirmed wide", files=_COMMIT_FILES, scope_basis="stated")],+ )+ assert await backfill_scope_basis(async_session, repo.id) == 0+ rec = await async_session.get(DecisionRecord, ids[0])+ assert rec.scope_basis == "stated"+++async def test_backfill_drops_every_link_the_record_had(async_session):+ """Matching what the write path would now produce for the same record."""+ repo = await insert_repo(async_session)+ payload = _decision("Legacy wide", files=_COMMIT_FILES)+ payload["affected_modules"] = ["packages/core/src"]+ ids = await bulk_upsert_decisions(async_session, repo.id, [payload])++ await backfill_scope_basis(async_session, repo.id)++ rows = (+ (+ await async_session.execute(+ select(DecisionNodeLink).where(DecisionNodeLink.decision_id == ids[0])+ )+ )+ .scalars()+ .all()+ )+ assert rows == []+++# ---------------------------------------------------------------------------+# A scope a person states outranks a mined one+# ---------------------------------------------------------------------------+++async def test_stating_a_scope_by_hand_makes_a_footprint_bind_again(async_session):+ """Storing the new files and then ignoring them would be the worst of+ both."""+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [+ _decision(+ "Collapse unchanged hook re-reads",+ files=_COMMIT_FILES,+ scope_basis=SCOPE_BASIS_FOOTPRINT,+ )+ ],+ )+ assert await get_governing_decisions(async_session, repo.id, _MECHANISM) == []++ await update_decision_metadata(async_session, ids[0], affected_files=[_MECHANISM])++ rec = await async_session.get(DecisionRecord, ids[0])+ assert rec.scope_basis == SCOPE_BASIS_STATED+ assert json.loads(rec.affected_files_json) == [_MECHANISM]+++async def test_the_backfill_never_re_marks_a_stated_scope(async_session):+ """The row still reads as a wide ``pr`` record to the repair, which looks+ only at source and file count, so the next index would walk it back."""+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session, repo.id, [_decision("Legacy wide", files=_COMMIT_FILES)]+ )+ await update_decision_metadata(async_session, ids[0], affected_files=_COMMIT_FILES)++ assert await backfill_scope_basis(async_session, repo.id) == 0+ rec = await async_session.get(DecisionRecord, ids[0])+ assert rec.scope_basis == SCOPE_BASIS_STATED+++async def test_patching_only_modules_leaves_the_basis_alone(async_session):+ """The basis describes the file list, so a module-only patch says nothing."""+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_decision("Wide", files=_COMMIT_FILES, scope_basis=SCOPE_BASIS_FOOTPRINT)],+ )+ await update_decision_metadata(async_session, ids[0], affected_modules=["pkg"])++ rec = await async_session.get(DecisionRecord, ids[0])+ assert rec.scope_basis == SCOPE_BASIS_FOOTPRINT+++async def test_accepting_with_a_corrected_scope_makes_the_record_bind(async_session):+ """``decision confirm --scope`` runs through ``accept_decision``, not+ through ``update_decision_metadata``."""+ from repowise.core.persistence.crud.authority import accept_decision++ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [+ _decision(+ "Collapse unchanged hook re-reads",+ files=_COMMIT_FILES,+ scope_basis=SCOPE_BASIS_FOOTPRINT,+ )+ ],+ )+ rec = await async_session.get(DecisionRecord, ids[0])+ rec.rationale = "because the reads were measured redundant"++ await accept_decision(+ async_session,+ rec,+ accepter="tester",+ scope=[_MECHANISM],+ evidence=["abc1234"],+ )++ refreshed = await async_session.get(DecisionRecord, ids[0])+ assert refreshed.scope_basis == SCOPE_BASIS_STATED+ assert json.loads(refreshed.affected_files_json) == [_MECHANISM]+++async def test_accepting_without_a_scope_leaves_the_basis_alone(async_session):+ """No scope argument means no claim about files, so nothing changes."""+ from repowise.core.persistence.crud.authority import accept_decision++ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_decision("Narrow", files=[_MECHANISM], source="inline_marker")],+ )+ rec = await async_session.get(DecisionRecord, ids[0])+ rec.rationale = "measured"+ rec.scope_basis = SCOPE_BASIS_FOOTPRINT++ await accept_decision(+ async_session, rec, accepter="tester", evidence=["abc1234"]+ )++ refreshed = await async_session.get(DecisionRecord, ids[0])+ assert refreshed.scope_basis == SCOPE_BASIS_FOOTPRINT+++# ---------------------------------------------------------------------------+# Session scope: proximity is not a claim+# ---------------------------------------------------------------------------++_A1 = "pkg/area_a/one.py"+_A2 = "pkg/area_a/two.py"+_B1 = "pkg/area_b/one.py"+++def _session(title: str, *, files: list[str], kind: str = "architectural") -> dict:+ payload = _decision(title, files=files, source="session")+ payload["kind"] = kind+ return payload+++async def test_backfill_marks_a_session_record_spanning_directories(async_session):+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session, repo.id, [_session("Restated while editing", files=[_A1, _B1])]+ )+ assert await get_governing_decisions(async_session, repo.id, _A1) != []++ assert await backfill_session_scope_basis(async_session, repo.id) == 1++ rec = await async_session.get(DecisionRecord, ids[0])+ assert rec.scope_basis == SCOPE_BASIS_PROXIMITY+ assert json.loads(rec.affected_files_json) == [_A1, _B1]+ assert await get_governing_decisions(async_session, repo.id, _A1) == []+++async def test_backfill_leaves_a_session_record_inside_one_directory(async_session):+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(+ async_session, repo.id, [_session("About this area", files=[_A1, _A2])]+ )+ assert await backfill_session_scope_basis(async_session, repo.id) == 0+ assert await get_governing_decisions(async_session, repo.id, _A1) != []+++async def test_backfill_scopes_an_agreement_to_the_repository(async_session):+ """It governs how the work is conducted, so no file is what it is about."""+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_session("Never attribute the agent", files=[_A1], kind="agreement")],+ )+ assert await backfill_session_scope_basis(async_session, repo.id) == 1+ rec = await async_session.get(DecisionRecord, ids[0])+ assert rec.scope_basis == SCOPE_BASIS_REPOSITORY+ assert await get_governing_decisions(async_session, repo.id, _A1) == []+++async def test_the_session_backfill_leaves_other_sources_alone(async_session):+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_decision("Marker", files=[_A1, _B1], source="inline_marker")],+ )+ assert await backfill_session_scope_basis(async_session, repo.id) == 0+ assert await get_governing_decisions(async_session, repo.id, _A1) != []+++async def test_the_session_backfill_is_idempotent(async_session):+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(+ async_session, repo.id, [_session("Wide", files=[_A1, _B1])]+ )+ assert await backfill_session_scope_basis(async_session, repo.id) == 1+ assert await backfill_session_scope_basis(async_session, repo.id) == 0+++# ---------------------------------------------------------------------------+# Pruning scope entries the index does not hold+# ---------------------------------------------------------------------------+++async def _index_files(session, repo_id, paths: list[str]) -> None:+ """Enough file nodes to clear the unbuilt-graph guard."""+ filler = [f"pkg/filler/f{i:03d}.py" for i in range(60)]+ for node_id in [*paths, *filler]:+ session.add(+ GraphNode(+ repository_id=repo_id,+ node_id=node_id,+ node_type="file",+ name=node_id.rsplit("/", 1)[-1],+ )+ )+ await session.flush()+++async def test_prune_drops_a_path_the_index_does_not_hold(async_session):+ """A transcript names plan docs and sibling checkouts; they resolve on+ disk and are still not this codebase."""+ repo = await insert_repo(async_session)+ await _index_files(async_session, repo.id, [_A1])+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_session("Mixed", files=[_A1, "local-stash/plan/NOTES.md"])],+ )++ assert await prune_unindexed_scope_files(async_session, repo.id) == 1++ rec = await async_session.get(DecisionRecord, ids[0])+ assert json.loads(rec.affected_files_json) == [_A1]+ assert await get_governing_decisions(async_session, repo.id, _A1) != []+ rows = (+ (+ await async_session.execute(+ select(DecisionNodeLink).where(DecisionNodeLink.decision_id == ids[0])+ )+ )+ .scalars()+ .all()+ )+ assert "local-stash/plan/NOTES.md" not in {r.node_id for r in rows}+++async def test_prune_does_nothing_when_the_graph_looks_unbuilt(async_session):+ """Pruning against a failed graph build would empty every scope."""+ repo = await insert_repo(async_session)+ ids = await bulk_upsert_decisions(+ async_session,+ repo.id,+ [_session("Mixed", files=[_A1, "local-stash/plan/NOTES.md"])],+ )+ assert await prune_unindexed_scope_files(async_session, repo.id) == 0+ rec = await async_session.get(DecisionRecord, ids[0])+ assert len(json.loads(rec.affected_files_json)) == 2+++async def test_prune_is_idempotent(async_session):+ repo = await insert_repo(async_session)+ await _index_files(async_session, repo.id, [_A1])+ await bulk_upsert_decisions(+ async_session, repo.id, [_session("Mixed", files=[_A1, "local-stash/x.md"])]+ )+ assert await prune_unindexed_scope_files(async_session, repo.id) == 1+ assert await prune_unindexed_scope_files(async_session, repo.id) == 0+++async def test_prune_rewrites_the_module_list_with_the_files(async_session):+ repo = await insert_repo(async_session)+ await _index_files(async_session, repo.id, [_A1])+ ids = await bulk_upsert_decisions(+ async_session, repo.id, [_session("Mixed", files=[_A1, "outside/gone.py"])]+ )+ await prune_unindexed_scope_files(async_session, repo.id)+ rec = await async_session.get(DecisionRecord, ids[0])+ assert json.loads(rec.affected_modules_json) == ["pkg/area_a"]diff --git a/tests/unit/server/mcp/test_why_scope_basis.py b/tests/unit/server/mcp/test_why_scope_basis.pynew file mode 100644index 000000000..d7a759454--- /dev/null+++ b/tests/unit/server/mcp/test_why_scope_basis.py@@ -0,0 +1,170 @@+"""A commit footprint does not answer "what governs this file".++The record stays in the store, keeps its files and stays findable by text+search. What it loses is the per-file lanes, where a decision mined from one+commit was answering for every file that commit happened to touch.+"""++from __future__ import annotations++import json++import pytest++from repowise.core.analysis.decisions.scope import SCOPE_BASIS_FOOTPRINT+from repowise.core.persistence.models import DecisionRecord++_BYSTANDER = "src/auth/middleware.py"+++async def _add_footprint_record(factory, *, scope_basis: str) -> str:+ """A wide record naming the fixture's files, as the PR miner writes one."""+ from sqlalchemy import select++ from repowise.core.persistence.models import Repository++ async with factory() as session:+ rid = (await session.execute(select(Repository.id))).scalars().first()+ rec = DecisionRecord(+ id="footprint1",+ repository_id=rid,+ title="Collapse unchanged hook re-reads",+ status="active",+ decision="Collapse repeated reads of an unchanged file",+ rationale="mined from one commit body",+ affected_files_json=json.dumps(+ [_BYSTANDER, "src/auth/service.py", "src/db/models.py"]+ ),+ affected_modules_json=json.dumps(["src/auth"]),+ source="pr",+ scope_basis=scope_basis,+ confidence=0.8,+ )+ session.add(rec)+ await session.commit()+ return rid+++async def test_a_footprint_is_absent_from_every_per_file_lane(setup_mcp, factory):+ from repowise.server.mcp_server import get_why++ await _add_footprint_record(factory, scope_basis=SCOPE_BASIS_FOOTPRINT)++ result = await get_why(_BYSTANDER)+ assert result["mode"] == "path"+ titles = [+ d["title"]+ for lane in ("decisions", "candidates", "history")+ for d in result.get(lane) or []+ ]+ assert "Collapse unchanged hook re-reads" not in titles+++async def test_the_same_record_without_the_basis_does_answer(setup_mcp, factory):+ """The gate is the basis, not the title, the source or the file list.++ Without this the test above passes for the wrong reason -- a fixture that+ never matched the path at all.+ """+ from repowise.server.mcp_server import get_why++ await _add_footprint_record(factory, scope_basis="")++ result = await get_why(_BYSTANDER)+ titles = [+ d["title"]+ for lane in ("decisions", "candidates", "history")+ for d in result.get(lane) or []+ ]+ assert "Collapse unchanged hook re-reads" in titles+++async def test_a_footprint_is_still_reachable_by_text_search(setup_mcp, factory):+ """It stops being specific, not stored. A repo-wide question still finds it."""+ from repowise.server.mcp_server import get_why++ await _add_footprint_record(factory, scope_basis=SCOPE_BASIS_FOOTPRINT)++ result = await get_why("why collapse unchanged hook re-reads")+ assert result["mode"] == "search"+ assert any(+ d["title"] == "Collapse unchanged hook re-reads" for d in result["decisions"]+ )+++async def test_two_targets_refuse_what_one_target_refuses(setup_mcp, factory):+ """``get_why`` routes one target to path mode and two to a second selector.++ They read the same column and must agree, or the same file answers+ differently depending on how many were asked about.+ """+ from repowise.server.mcp_server import get_why++ await _add_footprint_record(factory, scope_basis=SCOPE_BASIS_FOOTPRINT)++ # No query: a question would run the relevance pass and suppress the+ # record for a reason that has nothing to do with its scope, so the+ # assertion would hold whether or not the gate existed.+ result = await get_why(targets=[_BYSTANDER, "src/db/models.py"])+ entries = result.get("target_context") or {}+ assert set(entries) == {_BYSTANDER, "src/db/models.py"}+ for entry in entries.values():+ # Both lanes: the record has no acceptance row, so it would land in+ # ``candidate_decisions``, and asserting only on the governing lane+ # would pass without the gate.+ titles = [+ row["title"]+ for lane in ("governing_decisions", "candidate_decisions")+ for row in entry.get(lane) or []+ ]+ assert "Collapse unchanged hook re-reads" not in titles+++async def test_two_targets_do_answer_without_the_basis(setup_mcp, factory):+ """The companion that keeps the test above from passing vacuously."""+ from repowise.server.mcp_server import get_why++ await _add_footprint_record(factory, scope_basis="")++ result = await get_why(targets=[_BYSTANDER, "src/db/models.py"])+ titles = [+ row["title"]+ for entry in (result.get("target_context") or {}).values()+ for lane in ("governing_decisions", "candidate_decisions")+ for row in entry.get(lane) or []+ ]+ assert "Collapse unchanged hook re-reads" in titles+++async def test_get_context_does_not_print_a_footprint_on_a_file_card(+ setup_mcp, factory+):+ """``get_context`` reads the JSON array, not the decision graph, so+ gating the graph at the write path does nothing here."""+ from repowise.server.mcp_server import get_context++ await _add_footprint_record(factory, scope_basis=SCOPE_BASIS_FOOTPRINT)++ result = await get_context(targets=[_BYSTANDER], include=["decisions"])+ blob = json.dumps(result, default=str)+ assert "Collapse unchanged hook re-reads" not in blob+++async def test_get_context_does_print_the_same_record_without_the_basis(+ setup_mcp, factory+):+ """The negative control: the gate is the basis, not the fixture."""+ from repowise.server.mcp_server import get_context++ await _add_footprint_record(factory, scope_basis="")++ result = await get_context(targets=[_BYSTANDER], include=["decisions"])+ blob = json.dumps(result, default=str)+ assert "Collapse unchanged hook re-reads" in blob