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
refactor(decisions): read acceptance requirements from plain records in lifecycle (#2510)
Raghav Chamadiyaeee0561eb074
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.pyindex a0019ee05..d75d45216 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py@@ -507,7 +507,7 @@ def _load_decisions(conn: sqlite3.Connection, where: str) -> list[dict]:def _is_repo_wide(decision: dict) -> bool:"""Whether *decision* governs the repository rather than particular files.- Mirrors ``crud.authority._is_repo_wide``, which this path cannot import:+ Mirrors ``decisions.lifecycle.is_repo_wide``:an agreement that names files has been given a real scope by something andthe ordinary overlap rules apply to it, so the noun is necessary and notsufficient.diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.pyindex 46bd8fb3e..c48bff253 100644--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py@@ -11,8 +11,10 @@ cannot mean one thing in the database and another on the wire.from __future__ import annotations-from collections.abc import Sequence+import json+from collections.abc import Mapping, Sequencefrom dataclasses import dataclass+from typing import Any__all__ = ["ACCEPTANCE_ACTIONS",@@ -39,8 +41,14 @@ __all__ = ["currency_for_legacy_status","effective_currency","is_governing",+ "is_repo_wide","legacy_status_for_currency","machine_grant_blocker",+ "named_scope",+ "record_blockers",+ "record_evidence",+ "record_scope",+ "requirement","status_rank",]@@ -324,6 +332,112 @@ def acceptance_blockers(req: AcceptanceRequirement) -> list[str]:return blockers+# The readers below take a mapping keyed ``affected_files``, ``affected_modules``,+# ``kind``, ``rationale``, ``context``, ``source``, ``evidence_commits``,+# ``evidence_file``; list fields may be stored JSON text. ORM rows go through+# ``crud.authority.decision_fields``.+++def _str_list(value: Any) -> list[str]:+ if isinstance(value, str):+ try:+ parsed = json.loads(value or "[]")+ except (TypeError, ValueError):+ return []+ return [str(v) for v in parsed] if isinstance(parsed, list) else []+ return [str(v) for v in (value or [])]+++def _non_blank(values: list[str]) -> list[str]:+ return [v for v in values if v and v.strip()]+++def _first_non_blank(*values: str | None) -> str:+ return next((v for v in values if v and v.strip()), "")+++def named_scope(rec: Mapping[str, Any]) -> list[str]:+ """The files or modules *rec* actually names, blanks dropped."""+ # Blank entries fall through to the modules rather than short-circuiting on+ # them, so this agrees with the TypeScript mirror about a whitespace path.+ return _non_blank(_str_list(rec.get("affected_files"))) or _non_blank(+ _str_list(rec.get("affected_modules"))+ )+++def is_repo_wide(rec: Mapping[str, Any]) -> bool:+ """Whether *rec* governs the repository as a whole rather than part of it.++ Both halves are needed. An agreement that names files has been given a real+ scope by something, and the ordinary rules apply to it: the noun says the+ record is *allowed* to name nothing, not that anything it does name should+ be ignored. Keying this off the kind alone would take a record with real+ files out of staleness checking for good, and the classifier is a regex+ with a measured false-positive rate.+ """+ return rec.get("kind") == AGREEMENT_KIND and not named_scope(rec)+++def record_scope(rec: Mapping[str, Any]) -> list[str]:+ """What *rec* claims to govern, for every reader of the contract.++ An agreement naming no file governs the repository rather than part of it,+ so it reports that scope instead of an empty one. The acceptance contract,+ the review flag and the currency all read this, and those three disagreeing+ about what an agreement governs is the failure this exists to prevent.+ """+ return named_scope(rec) or (+ [AGREEMENT_SCOPE] if rec.get("kind") == AGREEMENT_KIND else []+ )+++def record_evidence(rec: Mapping[str, Any]) -> list[str]:+ """The evidence references *rec* already carries."""+ evidence = _str_list(rec.get("evidence_commits"))+ if rec.get("evidence_file"):+ evidence.append(rec["evidence_file"])+ return evidence+++def requirement(+ rec: Mapping[str, Any],+ *,+ reason: str = "",+ scope: list[str] | None = None,+ evidence: list[str] | None = None,+ accepter: str = "",+ artifact: str = "",+) -> AcceptanceRequirement:+ """What the acceptance contract would be asked to take for *rec*."""+ # A record somebody typed is its own provenance: the accepter did not read+ # an inference, they wrote the claim. Everything mined from a transcript, a+ # commit or a document still has to say what it rests on.+ self_authored = rec.get("source") == "cli" and bool(accepter.strip())+ resolved_evidence = evidence if evidence is not None else record_evidence(rec)+ if not resolved_evidence and self_authored:+ resolved_evidence = [f"accepted by {accepter}"]+ # The why comes from `rationale` or `context` ("what forced this decision?"),+ # never from `decision`, which is the what.+ return AcceptanceRequirement(+ reason=_first_non_blank(reason, rec.get("rationale"), rec.get("context")),+ scope=scope if scope is not None else record_scope(rec),+ evidence=resolved_evidence,+ accepter=accepter,+ artifact=artifact,+ self_authored=self_authored,+ )+++def record_blockers(rec: Mapping[str, Any]) -> list[str]:+ """Why the contract would refuse *rec* as it stands, empty if it would not.++ The accepter and artifact are what a reviewer supplies at the moment they+ act, so this asks with an identity in hand: what is left is what a person+ has to go and fill in first.+ """+ return acceptance_blockers(requirement(rec, accepter="reviewer"))++#: How the pre-split ``decision_records.status`` column maps onto currency, and#: back. The column survives as a denormalized projection so unmigrated readers#: keep working; the acceptance row is the authority.diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex 2fae07756..b078ea7ae 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -30,8 +30,6 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.decisions.lifecycle import (ACCEPTANCE_ACTIONS,ACCEPTER_SESSION_MAX,- AGREEMENT_KIND,- AGREEMENT_SCOPE,NO_SCOPE_BLOCKER,STORED_CURRENCIES,AcceptanceRequirement,@@ -39,8 +37,16 @@ from repowise.core.analysis.decisions.lifecycle import (accepter_kind_blocker,effective_currency,is_governing,+ is_repo_wide,legacy_status_for_currency,machine_grant_blocker,+ named_scope,+ record_evidence,+ record_scope,+ requirement,+)+from repowise.core.analysis.decisions.lifecycle import (+ record_blockers as _record_blockers,)from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATED@@ -69,6 +75,7 @@ __all__ = ["count_decisions_by_lane","current_currency","decision_currencies",+ "decision_fields","decision_signatures","dismiss_candidate","is_accepted",@@ -359,17 +366,16 @@ async def count_decisions_by_lane(if acceptance is None:counts["candidates"] += 1continue- # The same blank handling as _named_scope: a whitespace-only path is- # not a scope, and these two computations of one partition must not- # disagree about that.- named = _non_blank(_json_list(files_json)) or _non_blank(- _json_list(modules_json)- )+ fields = {+ "affected_files": files_json,+ "affected_modules": modules_json,+ "kind": kind,+ }currency = effective_currency(acceptance,- has_scope=bool(named) or kind == AGREEMENT_KIND,+ has_scope=bool(record_scope(fields)),staleness=staleness or 0.0,- repo_wide=kind == AGREEMENT_KIND and not named,+ repo_wide=is_repo_wide(fields),)counts["history" if currency in ("superseded", "dismissed") else currency] += 1if is_governing(currency):@@ -416,114 +422,41 @@ async def resolve_decision_id(session: AsyncSession, decision_id: str) -> str |# ----------------------------------------------------------------------------def _json_list(value: Any) -> list[str]:- if isinstance(value, str):- try:- parsed = json.loads(value or "[]")- except (TypeError, ValueError):- return []- return [str(v) for v in parsed] if isinstance(parsed, list) else []- return [str(v) for v in (value or [])]---def _non_blank(values: list[str]) -> list[str]:- return [v for v in values if v and v.strip()]+def decision_fields(record: DecisionRecord) -> dict[str, Any]:+ """*record* as the plain mapping the lifecycle readers take."""+ return {+ "affected_files": record.affected_files_json,+ "affected_modules": record.affected_modules_json,+ "kind": record.kind,+ "rationale": record.rationale,+ "context": record.context,+ "source": record.source,+ "evidence_commits": record.evidence_commits_json,+ "evidence_file": record.evidence_file,+ }def names_a_scope(record: DecisionRecord) -> list[str]:"""The files or modules *record* names, for a caller asking what are-statement would clear."""- return _named_scope(record)+ return named_scope(decision_fields(record))-def _named_scope(record: DecisionRecord) -> list[str]:- """The files or modules *record* actually names, blanks dropped."""- # Blank entries fall through to the modules rather than short-circuiting on- # them, so this agrees with the TypeScript mirror about a whitespace path.- return _non_blank(_json_list(record.affected_files_json)) or _non_blank(- _json_list(record.affected_modules_json)- )+def _record_scope(record: DecisionRecord) -> list[str]:+ return record_scope(decision_fields(record))def _is_repo_wide(record: DecisionRecord) -> bool:- """Whether *record* governs the repository as a whole rather than part of it.-- Both halves are needed. An agreement that names files has been given a real- scope by something, and the ordinary rules apply to it: the noun says the- record is *allowed* to name nothing, not that anything it does name should- be ignored. Keying this off the kind alone would take a record with real- files out of staleness checking for good, and the classifier is a regex- with a measured false-positive rate.- """- return record.kind == AGREEMENT_KIND and not _named_scope(record)---def _record_scope(record: DecisionRecord) -> list[str]:- """What *record* claims to govern, for every reader of the contract.-- An agreement naming no file governs the repository rather than part of it,- so it reports that scope instead of an empty one. Written here rather than- at the three call sites because they are the acceptance contract, the review- flag and the currency, and those three disagreeing about what an agreement- governs is the failure :func:`accepted_predicate` exists to describe.- """- return _named_scope(record) or (- [AGREEMENT_SCOPE] if record.kind == AGREEMENT_KIND else []- )+ return is_repo_wide(decision_fields(record))def _record_evidence(record: DecisionRecord) -> list[str]:- evidence = _json_list(record.evidence_commits_json)- if record.evidence_file:- evidence.append(record.evidence_file)- return evidence---def _first_non_blank(*values: str) -> str:- return next((v for v in values if v and v.strip()), "")---def _requirement(- record: DecisionRecord,- *,- reason: str = "",- scope: list[str] | None = None,- evidence: list[str] | None = None,- accepter: str = "",- artifact: str = "",-) -> AcceptanceRequirement:- """What the acceptance contract would be asked to take for *record*."""- # A record somebody typed is its own provenance: the accepter did not read- # an inference, they wrote the claim. Everything mined from a transcript, a- # commit or a document still has to say what it rests on.- self_authored = record.source == "cli" and bool(accepter.strip())- resolved_evidence = evidence if evidence is not None else _record_evidence(record)- if not resolved_evidence and self_authored:- resolved_evidence = [f"accepted by {accepter}"]- # The why may come from `rationale` or from `context` ("what forced this- # decision?"), never from `decision`, which is the what. Measured over the- # dev store's 513 acceptable records: 199 have a blank rationale, but 145- # of those give their reason in `context`, so stopping at `rationale` would- # block 145 records a hand-read sample of 20 judged worth keeping. Stopping- # at `context` blocks the other 54, each blank in both fields.- return AcceptanceRequirement(- reason=_first_non_blank(reason, record.rationale, record.context),- scope=scope if scope is not None else _record_scope(record),- evidence=resolved_evidence,- accepter=accepter,- artifact=artifact,- self_authored=self_authored,- )+ return record_evidence(decision_fields(record))def record_blockers(record: DecisionRecord) -> list[str]:- """Why the contract would refuse *record* as it stands, empty if it would not.-- The accepter and artifact are what a reviewer supplies at the moment they- act, so this asks with an identity in hand: what is left is what a person- has to go and fill in first.- """- return acceptance_blockers(_requirement(record, accepter="reviewer"))+ """Why the contract would refuse *record* as it stands, empty if it would not."""+ return _record_blockers(decision_fields(record))def candidate_review_signals(record: DecisionRecord) -> tuple[float, bool]:@@ -533,7 +466,7 @@ def candidate_review_signals(record: DecisionRecord) -> tuple[float, bool]:with candidates a reviewer can act on and leaves confidence and recency tobreak ties."""- blockers = acceptance_blockers(_requirement(record, accepter="reviewer"))+ blockers = record_blockers(record)return (0.0 if blockers else 1.0), NO_SCOPE_BLOCKER in blockers@@ -571,8 +504,8 @@ async def record_acceptance(if currency not in STORED_CURRENCIES:raise ValueError(f"Unknown stored currency {currency!r}.")- req = _requirement(- record,+ req = requirement(+ decision_fields(record),reason=reason,scope=scope,evidence=evidence,diff --git a/tests/unit/analysis/test_decision_lifecycle_readers.py b/tests/unit/analysis/test_decision_lifecycle_readers.pynew file mode 100644index 000000000..745587e63--- /dev/null+++ b/tests/unit/analysis/test_decision_lifecycle_readers.py@@ -0,0 +1,67 @@+"""The acceptance contract's record readers, over plain mappings."""++from __future__ import annotations++import pytest++from repowise.core.analysis.decisions.lifecycle import (+ AGREEMENT_SCOPE,+ is_repo_wide,+ record_blockers,+ record_evidence,+ record_scope,+ requirement,+)+from repowise.core.persistence.crud.authority import decision_fields+from repowise.core.persistence.models import DecisionRecord+++def test_reason_falls_back_to_context_then_stops() -> None:+ assert requirement({"rationale": " ", "context": "forced by X"}).reason == "forced by X"+ assert requirement({"rationale": "why", "context": "ctx"}).reason == "why"+ # `decision` is the what, never the why.+ assert requirement({"rationale": "", "context": "", "decision": "use Y"}).reason == ""+ assert requirement({"rationale": "why"}, reason="stated").reason == "stated"+++def test_file_less_agreement_governs_the_repository() -> None:+ agreement = {"kind": "agreement", "affected_files": [], "affected_modules": []}+ assert record_scope(agreement) == [AGREEMENT_SCOPE]+ assert is_repo_wide(agreement)+ scoped = {**agreement, "affected_files": ["src/a.py"]}+ assert record_scope(scoped) == ["src/a.py"]+ assert not is_repo_wide(scoped)+ assert record_scope({"kind": "architectural"}) == []+++ "files, modules",+ [([" "], ["pkg"]), ('[" "]', '["pkg"]')],+)+def test_lists_or_their_json_text(files, modules) -> None:+ rec = {"affected_files": files, "affected_modules": modules}+ assert record_scope(rec) == ["pkg"]+++def test_evidence_and_blockers() -> None:+ rec = {"evidence_commits": '["abc"]', "evidence_file": "AGENTS.md"}+ assert record_evidence(rec) == ["abc", "AGENTS.md"]+ assert record_blockers({"kind": "agreement", "rationale": "r", **rec}) == []+ # A hand-typed record is its own evidence once someone accepts it.+ assert requirement({"source": "cli"}, accepter="me").evidence == ["accepted by me"]+++def test_orm_projection_matches_the_mapping_readers() -> None:+ rec = DecisionRecord(+ affected_files_json="[]",+ affected_modules_json='["pkg"]',+ kind="architectural",+ rationale="",+ context="ctx",+ source="inline_marker",+ evidence_commits_json='["abc"]',+ evidence_file=None,+ )+ fields = decision_fields(rec)+ assert record_scope(fields) == ["pkg"]+ assert record_blockers(fields) == []diff --git a/tests/unit/cli/test_augment_decision_inject.py b/tests/unit/cli/test_augment_decision_inject.pyindex d27a045ef..4e380bec1 100644--- a/tests/unit/cli/test_augment_decision_inject.py+++ b/tests/unit/cli/test_augment_decision_inject.py@@ -278,7 +278,7 @@ async def test_agreement_is_global_whatever_mined_it(tmp_path, monkeypatch):async def test_agreement_that_names_files_is_scored_on_them(tmp_path, monkeypatch):"""The noun says a record may name nothing, not that its files are noise.- Mirrors ``crud.authority._is_repo_wide``: both halves are required, so a+ Mirrors ``decisions.lifecycle.is_repo_wide``: both halves are required, so amisclassified record that does carry links keeps competing on overlapinstead of being injected everywhere."""diff --git a/tests/unit/server/test_decision_acceptance_contract_wire.py b/tests/unit/server/test_decision_acceptance_contract_wire.pynew file mode 100644index 000000000..28765094d--- /dev/null+++ b/tests/unit/server/test_decision_acceptance_contract_wire.py@@ -0,0 +1,153 @@+"""The acceptance contract's reads of a record, pinned at the server.++The reason falls back from ``rationale`` to ``context`` and never to+``decision``, and an agreement naming no file governs the repository.+"""++from __future__ import annotations++import json++import pytest+from httpx import AsyncClient+from sqlalchemy import select++from repowise.core.persistence import crud+from repowise.core.persistence.crud.authority import candidate_review_signals+from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import DecisionAcceptance+from tests.unit.server.conftest import create_test_repo+++async def _create(client: AsyncClient, repo_id: str, **body) -> dict:+ res = await client.post(f"/api/repos/{repo_id}/decisions", json=body)+ assert res.status_code == 201, res.text+ return res.json()+++async def test_reason_falls_back_to_context_and_never_to_decision(+ client: AsyncClient,+) -> None:+ repo = await create_test_repo(client)+ from_context = await _create(+ client,+ repo["id"],+ title="Context gives the why",+ context="the cache thrashed",+ decision="use an LRU",+ rationale="",+ affected_files=["src/cache.py"],+ )+ from_decision = await _create(+ client,+ repo["id"],+ title="Only the what is stated",+ context="",+ decision="use an LRU",+ rationale="",+ affected_files=["src/cache.py"],+ )+ assert from_context["status"] == "active"+ assert from_decision["status"] == "proposed"+++async def test_a_file_less_agreement_governs_the_repository(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ agreement = await _create(+ client,+ repo["id"],+ title="Commit on feature branches",+ kind="agreement",+ rationale="main is protected",+ )+ architectural = await _create(+ client,+ repo["id"],+ title="No scope named",+ rationale="because",+ )+ assert agreement["status"] == "active"+ assert agreement["currency"] == "active"+ assert architectural["status"] == "proposed"++ async with get_session(app.state.session_factory) as session:+ row = (+ await session.execute(+ select(DecisionAcceptance).where(+ DecisionAcceptance.decision_id == agreement["id"]+ )+ )+ ).scalar_one()+ assert json.loads(row.scope_json) == ["<repository>"]++ res = await client.get(f"/api/repos/{repo['id']}/decisions/lane-counts")+ assert res.status_code == 200, res.text+ counts = res.json()+ assert (counts["active"], counts["candidates"], counts["uncheckable"]) == (1, 1, 0)+++async def test_blank_files_fall_through_to_modules(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ rec = await _create(+ client,+ repo["id"],+ title="Blank file, real module",+ rationale="why",+ affected_files=[" "],+ affected_modules=["pkg/core"],+ )+ assert rec["status"] == "active"+ assert rec["currency"] == "active"+++async def test_blockers_and_review_signals_over_extracted_records(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ async with get_session(app.state.session_factory) as session:+ mined = await crud.upsert_decision(+ session,+ repository_id=repo["id"],+ title="Mined with evidence",+ context="",+ decision="d",+ rationale="",+ source="inline_marker",+ affected_files=["src/a.py"],+ evidence_commits=["abc123"],+ )+ bare = await crud.upsert_decision(+ session,+ repository_id=repo["id"],+ title="Mined with nothing",+ decision="d2",+ source="inline_marker",+ )+ agreement = await crud.upsert_decision(+ session,+ repository_id=repo["id"],+ title="Mined agreement",+ kind="agreement",+ rationale="r",+ source="inline_marker",+ evidence_file="AGENTS.md",+ )+ assert crud.record_blockers(mined) == [+ "no rationale or explicit constraint reason"+ ]+ assert candidate_review_signals(mined) == (0.0, False)+ assert crud.record_blockers(bare) == [+ "no rationale or explicit constraint reason",+ "no scope: name the files or modules it governs",+ "no evidence reference",+ ]+ assert candidate_review_signals(bare) == (0.0, True)+ assert crud.record_blockers(agreement) == []+ assert candidate_review_signals(agreement) == (1.0, False)+ assert crud.names_a_scope(agreement) == []