Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(decisions): refuse to accept a mined candidate that has no decision text (#4671)
Raghav Chamadiya3f65e9615b15
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.mdindex 7445ee374..c487ea086 100644--- a/docs/layers/DECISIONS.md+++ b/docs/layers/DECISIONS.md@@ -51,12 +51,13 @@ its source, a confidence, a staleness score, and one or more evidence rowsAcceptance is a recorded event, not a status flag. It carries a reason, ascope, an evidence reference and who signed it, and Repowise refuses to store-an acceptance that is missing any of those:+an acceptance that is missing any of those. A mined candidate with no decision text+is refused too; `confirm --decision` supplies it:```$ repowise decision confirm 4b6ddc58Cannot accept 4b6ddc58: no scope: name the files or modules it governs-Supply the missing parts with --reason, --scope or --evidence.+Supply the missing parts with --decision, --reason, --scope or --evidence.$ repowise decision confirm 4b6ddc58 --scope src/ingestionDecision 4b6ddc58 accepted (governing)diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.mdindex 49856e000..99b542d34 100644--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md@@ -43,8 +43,8 @@ unless the repository turns it on.- **candidates** — `repowise decision candidates --format json` — recordsawaiting review, each with its id and the `blockers` that stop it being accepted.- **confirm** — `repowise decision confirm <id>...` — accept candidates so they- govern. `--reason`, `--scope <path>` and `--evidence <commit|file|link>` fill- the blockers. An agent signs with `--agent <slug>`, which works only where+ govern. `--decision`, `--reason`, `--scope <path>` and+ `--evidence <commit|file|link>` fill the blockers. An agent signs with `--agent <slug>`, which works only wherethe repository has run `repowise decision config agent-acceptance --on`;otherwise leave acceptance to a person.- **deprecate / dismiss** — `repowise decision deprecate <id>` (optionallydiff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.pyindex 527303e77..cdc95f920 100644--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py@@ -842,11 +842,14 @@ def _decision_body_lines(rec) -> list[str]:#: The remedy printed beside a refused acceptance, naming the flags that#: supply what the contract found missing.-_ACCEPT_REMEDY = "Supply the missing parts with --reason, --scope or --evidence."+_ACCEPT_REMEDY = "Supply the missing parts with --decision, --reason, --scope or --evidence."@decision_group.command("confirm")@click.argument("decision_ids", nargs=-1)+ "--decision", "decision_text", default="", help="What was chosen, if the record does not say."+)@click.option("--reason", default="", help="Rationale, or why the constraint needs none.")@click.option("--scope",@@ -866,6 +869,7 @@ _ACCEPT_REMEDY = "Supply the missing parts with --reason, --scope or --evidence.@format_option()def decision_confirm(decision_ids: tuple[str, ...],+ decision_text: str,reason: str,scope: tuple[str, ...],evidence: tuple[str, ...],@@ -880,9 +884,10 @@ def decision_confirm(Takes one id or many, and an optional repository path after them. This isthe acceptance event, and it is the only thing that produces one:extraction, recurrence and confidence all stop at a candidate. Acceptance- is refused rather than stored blank when the candidate carries no reason,- no scope or no evidence; ``--reason``, ``--scope`` and ``--evidence``- supply what is missing, and correcting them here corrects the record too.+ is refused rather than stored blank when the candidate carries no decision+ text, no reason, no scope or no evidence; ``--decision``, ``--reason``,+ ``--scope`` and ``--evidence`` supply what is missing, and correcting them+ here corrects the record too.A refused id does not stop the others, and the run exits non-zero if anywere refused.@@ -911,6 +916,7 @@ def decision_confirm(reason=reason,scope=list(scope) or None,evidence=list(evidence) or None,+ decision=decision_text,)results = run_async(diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.pyindex 29f49f767..f06022bdc 100644--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py@@ -31,6 +31,7 @@ __all__ = ["GRANTING_ACTIONS","HISTORY_CURRENCIES","NEEDS_REVIEW_STALENESS",+ "NO_DECISION_BLOCKER","REVIEW_LANES","SPLIT_MARKERS","STORED_CURRENCIES",@@ -318,21 +319,31 @@ class AcceptanceRequirement:#: inferred. Then the entry itself is the provenance, and demanding a#: separate reference would make manual capture impossible.self_authored: bool = False+ #: What was chosen. ``None`` when the action grants nothing new, so a+ #: record with no text can still be withdrawn or carried over by an import.+ #: A self-authored record is exempt: its author wrote the title as the claim.+ decision: str | None = None#: Named because the review row's ``scope_unresolved`` flag is this exact#: verdict, and re-deriving it would be a second opinion about scope.NO_SCOPE_BLOCKER = "no scope: name the files or modules it governs"+NO_DECISION_BLOCKER = "no decision text: state what was chosen"+def acceptance_blockers(req: AcceptanceRequirement) -> list[str]:"""Return the reasons *req* cannot become an acceptance, empty if it can.- The same four checks the ``decision_acceptances`` CHECK constraints- enforce, stated once in prose so a caller can explain a refusal instead of- surfacing an IntegrityError.+ Reason, scope, evidence and identity are the checks the+ ``decision_acceptances`` CHECK constraints enforce, stated once in prose so+ a caller can explain a refusal instead of surfacing an IntegrityError. The+ decision-text check is enforced here only: a fresh grant of a mined record+ needs it, because one that never says what was chosen binds nobody to it."""blockers: list[str] = []+ if req.decision is not None and not req.self_authored and not req.decision.strip():+ blockers.append(NO_DECISION_BLOCKER)if not req.reason.strip():blockers.append("no rationale or explicit constraint reason")if not [s for s in req.scope if s and s.strip()]:@@ -345,7 +356,7 @@ def acceptance_blockers(req: AcceptanceRequirement) -> list[str]:# The readers below take a mapping keyed ``affected_files``, ``affected_modules``,-# ``kind``, ``rationale``, ``context``, ``source``, ``evidence_commits``,+# ``kind``, ``rationale``, ``context``, ``decision``, ``source``, ``evidence_commits``,# ``evidence_file``; list fields may be stored JSON text. ORM rows go through# ``crud.authority.decision_fields``.@@ -419,8 +430,12 @@ def requirement(evidence: list[str] | None = None,accepter: str = "",artifact: str = "",+ grant: bool = False,) -> AcceptanceRequirement:- """What the acceptance contract would be asked to take for *rec*."""+ """What the acceptance contract would be asked to take for *rec*.++ *grant* asks for the decision text too: it is what a new acceptance binds.+ """# 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.@@ -437,6 +452,7 @@ def requirement(accepter=accepter,artifact=artifact,self_authored=self_authored,+ decision=(rec.get("decision") or "") if grant else None,)@@ -447,7 +463,7 @@ def record_blockers(rec: Mapping[str, Any]) -> list[str]:act, so this asks with an identity in hand: what is left is what a personhas to go and fill in first."""- return acceptance_blockers(requirement(rec, accepter="reviewer"))+ return acceptance_blockers(requirement(rec, accepter="reviewer", grant=True))#: How the pre-split ``decision_records.status`` column maps onto currency, anddiff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex ef515b17b..ab03de1eb 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -480,6 +480,7 @@ def decision_fields(record: DecisionRecord) -> dict[str, Any]:"kind": record.kind,"rationale": record.rationale,"context": record.context,+ "decision": record.decision,"source": record.source,"evidence_commits": record.evidence_commits_json,"evidence_file": record.evidence_file,@@ -561,6 +562,9 @@ async def record_acceptance(evidence=evidence,accepter=accepter,artifact=artifact,+ # An import carries a signature given elsewhere; refusing it here would+ # demote a decision someone already accepted.+ grant=action == "accepted" and kind != "import",)blockers = acceptance_blockers(req)for check in (@@ -672,9 +676,10 @@ async def accept_decision(reason: str = "",scope: list[str] | None = None,evidence: list[str] | None = None,+ decision: str = "",note: str = "",) -> DecisionAcceptance:- """Accept a candidate, optionally editing its reason and scope on the way.+ """Accept a candidate, optionally editing its reason, scope and decision text.The edit is applied to the record too: accepting a claim with a correctedscope must not leave the record describing the uncorrected one. *evidence*@@ -689,6 +694,8 @@ async def accept_decision()if reason:record.rationale = reason+ if decision.strip():+ record.decision = decisionif scope is not None:# The accepter chose these files, so the record binds to them rather# than keeping the basis it was mined with.diff --git a/packages/types/__tests__/decisions-vocabulary.test.ts b/packages/types/__tests__/decisions-vocabulary.test.tsindex 8add07a94..180127ac6 100644--- a/packages/types/__tests__/decisions-vocabulary.test.ts+++ b/packages/types/__tests__/decisions-vocabulary.test.ts@@ -127,6 +127,7 @@ describe("lookup helpers", () => {describe("the acceptance contract, mirrored", () => {const accepted = {+ decision: "Keep sessions in Redis",rationale: "sessions did not survive a restart",affected_files: ["src/auth/service.py"],evidence_commits: ["abc1234"],@@ -151,6 +152,16 @@ describe("the acceptance contract, mirrored", () => {).toContain("no scope: name the files or modules it governs");});+ it("refuses a record that never says what was chosen", () => {+ expect(decisionAcceptanceBlockers({ ...accepted, decision: " " })).toEqual([+ "no decision text: state what was chosen",+ ]);+ // A typed record's title is its claim, as on the engine side.+ expect(+ decisionAcceptanceBlockers({ ...accepted, decision: "", source: "cli" }),+ ).toEqual([]);+ });+it("falls back to the context when there is no rationale", () => {expect(decisionAcceptanceBlockers({@@ -187,7 +198,7 @@ describe("the acceptance contract, mirrored", () => {it("names every gap at once rather than the first", () => {expect(- decisionAcceptanceBlockers({ source: "session" }).length,- ).toBe(3);+ decisionAcceptanceBlockers({ decision: "", source: "session" }).length,+ ).toBe(4);});});diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.tsindex d33f12524..95b9f2ee1 100644--- a/packages/types/src/decisions.ts+++ b/packages/types/src/decisions.ts@@ -495,7 +495,7 @@ export const DECISION_PRESETS = [* What `record_acceptance` would refuse this record for, mirrored so a review* surface can disable a control it knows will be refused instead of finding out* from the error toast. Pinned against the Python contract by the vocabulary- * tests. The fourth check, accepter-or-artifact identity, is not here: the+ * tests. The accepter-or-artifact identity check is not here: the* reviewer supplies that at the moment they act, so it is never something the* record is missing. `record_blockers` on the Python side asks the same way.*@@ -505,9 +505,13 @@ export const DECISION_PRESETS = [** The reason reads `rationale` then `context`, never `decision`: `context` is* what forced the choice, `decision` is the choice itself, and letting the what- * stand in for the why is what marked empty records acceptable.+ * stand in for the why is what marked empty records acceptable. A mined record+ * still needs its `decision`: one that never says what was chosen binds nobody+ * to anything. A typed record's title is its claim.*/export function decisionAcceptanceBlockers(record: {+ // Required so a caller cannot leave it out and have every record refused.+ decision: string;rationale?: string;context?: string;affected_files?: string[];@@ -521,6 +525,10 @@ export function decisionAcceptanceBlockers(record: {const nonBlank = (values: (string | null | undefined)[]) =>values.some((v) => (v ?? "").trim().length > 0);+ const selfAuthored = record.source === "cli";+ if (!selfAuthored && !nonBlank([record.decision])) {+ blockers.push("no decision text: state what was chosen");+ }if (!nonBlank([record.rationale, record.context])) {blockers.push("no rationale or explicit constraint reason");}@@ -534,7 +542,6 @@ export function decisionAcceptanceBlockers(record: {) {blockers.push("no scope: name the files or modules it governs");}- const selfAuthored = record.source === "cli";if (!selfAuthored &&!nonBlank(record.evidence_commits ?? []) &&diff --git a/plugins/claude-code/commands/decision.md b/plugins/claude-code/commands/decision.mdindex 630b30e9a..f3874d082 100644--- a/plugins/claude-code/commands/decision.md+++ b/plugins/claude-code/commands/decision.md@@ -44,8 +44,8 @@ unless the repository turns it on.- **candidates** — `repowise decision candidates --format json` — recordsawaiting review, each with its id and the `blockers` that stop it being accepted.- **confirm** — `repowise decision confirm <id>...` — accept candidates so they- govern. `--reason`, `--scope <path>` and `--evidence <commit|file|link>` fill- the blockers. An agent signs with `--agent <slug>`, which works only where+ govern. `--decision`, `--reason`, `--scope <path>` and+ `--evidence <commit|file|link>` fill the blockers. An agent signs with `--agent <slug>`, which works only wherethe repository has run `repowise decision config agent-acceptance --on`;otherwise leave acceptance to a person.- **deprecate / dismiss** — `repowise decision deprecate <id>` (optionallydiff --git a/plugins/shared/commands/decision.md b/plugins/shared/commands/decision.mdindex 9dc300c2b..7c1ccb115 100644--- a/plugins/shared/commands/decision.md+++ b/plugins/shared/commands/decision.md@@ -45,8 +45,8 @@ unless the repository turns it on.- **candidates** — `repowise decision candidates --format json` — recordsawaiting review, each with its id and the `blockers` that stop it being accepted.- **confirm** — `repowise decision confirm <id>...` — accept candidates so they- govern. `--reason`, `--scope <path>` and `--evidence <commit|file|link>` fill- the blockers. An agent signs with `--agent <slug>`, which works only where+ govern. `--decision`, `--reason`, `--scope <path>` and+ `--evidence <commit|file|link>` fill the blockers. An agent signs with `--agent <slug>`, which works only wherethe repository has run `repowise decision config agent-acceptance --on`;otherwise leave acceptance to a person.- **deprecate / dismiss** — `repowise decision deprecate <id>` (optionallydiff --git a/tests/unit/analysis/test_decision_lifecycle_readers.py b/tests/unit/analysis/test_decision_lifecycle_readers.pyindex 745587e63..7958d8ec1 100644--- a/tests/unit/analysis/test_decision_lifecycle_readers.py+++ b/tests/unit/analysis/test_decision_lifecycle_readers.py@@ -46,7 +46,8 @@ def test_lists_or_their_json_text(files, modules) -> None: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}) == []+ agreement = {"kind": "agreement", "rationale": "r", "decision": "d", **rec}+ assert record_blockers(agreement) == []# A hand-typed record is its own evidence once someone accepts it.assert requirement({"source": "cli"}, accepter="me").evidence == ["accepted by me"]@@ -58,6 +59,7 @@ def test_orm_projection_matches_the_mapping_readers() -> None:kind="architectural",rationale="",context="ctx",+ decision="d",source="inline_marker",evidence_commits_json='["abc"]',evidence_file=None,diff --git a/tests/unit/cli/test_decision_cmd_output.py b/tests/unit/cli/test_decision_cmd_output.pyindex 73a03066e..32d00e90c 100644--- a/tests/unit/cli/test_decision_cmd_output.py+++ b/tests/unit/cli/test_decision_cmd_output.py@@ -262,7 +262,7 @@ def test_batch_table_counts_and_names_each_outcome(seeded: Path) -> None:out = result.outputassert "Accepted 1 of 3" in outassert "Decision not found: 9999" in out- assert "Supply the missing parts with --reason, --scope or --evidence." in out+ assert "Supply the missing parts with --decision, --reason, --scope or --evidence." in outdef test_batch_json_summarises_the_run(seeded: Path) -> None:diff --git a/tests/unit/cli/test_decision_status_cmd.py b/tests/unit/cli/test_decision_status_cmd.pyindex f997c8130..2194b92a7 100644--- a/tests/unit/cli/test_decision_status_cmd.py+++ b/tests/unit/cli/test_decision_status_cmd.py@@ -122,6 +122,29 @@ def test_status_lanes_agree_with_acceptance_not_the_status_column(status_repo: Passert by_key["pr"]["accepted"] == 1+def test_a_candidate_with_no_decision_text_counts_as_blocked(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ (repo / ".repowise").mkdir(parents=True)+ _seed_wiki_db(+ repo,+ [+ {"id": "a" * 32, "title": "Use JWT", "status": "proposed", "source": "pr"},+ {"id": "b" * 32, "title": "Empty", "status": "proposed", "source": "pr", "decision": ""},+ ],+ )++ review = _status(repo)["review"]+ assert (review["acceptable"], review["blocked"]) == (1, 1)++ candidates = CliRunner().invoke(+ cli, ["decision", "candidates", str(repo), "--format", "json"]+ )+ assert candidates.exit_code == 0, candidates.output+ rows = json.loads(candidates.output)["candidates"]+ blockers = {row["title"]: row["blockers"] for row in rows}+ assert blockers == {"Use JWT": [], "Empty": ["no decision text: state what was chosen"]}++def test_status_reports_capture_spend_and_the_last_call(status_repo: Path) -> None:_add_cost_rows(status_repo,diff --git a/tests/unit/persistence/test_decision_authority.py b/tests/unit/persistence/test_decision_authority.pyindex 5e6ddaedd..6ee98b50d 100644--- a/tests/unit/persistence/test_decision_authority.py+++ b/tests/unit/persistence/test_decision_authority.py@@ -14,6 +14,7 @@ from sqlalchemy import selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.decisions.lifecycle import NO_DECISION_BLOCKERfrom repowise.core.persistence.crud import bulk_upsert_decisions, update_decision_statusfrom repowise.core.persistence.crud.authority import (AcceptanceRefusedError,@@ -27,6 +28,8 @@ from repowise.core.persistence.crud.authority import (list_candidates,merge_candidate,reaffirm_decision,+ record_acceptance,+ record_blockers,request_split,resolve_decision_id,return_to_review,@@ -125,7 +128,7 @@ async def test_acceptance_requires_reason_scope_evidence_and_identity(async_sesswith pytest.raises(AcceptanceRefusedError) as refusal:await accept_decision(async_session, rec, accepter="tester")- assert len(refusal.value.blockers) == 3+ assert len(refusal.value.blockers) == 4with pytest.raises(AcceptanceRefusedError):await accept_decision(@@ -139,11 +142,63 @@ async def test_acceptance_requires_reason_scope_evidence_and_identity(async_sessreason="a reason",scope=["src/a.py"],evidence=["deadbeef"],+ decision="do the thing",)assert acceptance.currency == "active"assert rec.status == "active"+async def test_a_mined_candidate_with_no_decision_text_is_refused(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Says nothing")+ rec.decision = " "+ await async_session.flush()++ assert record_blockers(rec) == [NO_DECISION_BLOCKER]+ with pytest.raises(AcceptanceRefusedError) as refusal:+ await accept_decision(async_session, rec, accepter="tester")+ assert refusal.value.blockers == [NO_DECISION_BLOCKER]++ await accept_decision(async_session, rec, accepter="tester", decision="Use Redis")+ assert rec.decision == "Use Redis"+ assert await is_accepted(async_session, rec.id)+++async def test_a_typed_record_needs_no_decision_text(async_session):+ """Its author wrote the title as the claim."""+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Typed")+ rec.source = "cli"+ rec.decision = ""+ await async_session.flush()++ await accept_decision(async_session, rec, accepter="tester")+ assert await is_accepted(async_session, rec.id)+++async def test_a_decision_with_no_text_can_still_be_withdrawn_or_imported(async_session):+ """Only a new grant asks for the text; an accepted record is never stranded."""+ repo = await insert_repo(async_session)+ kept, withdrawn = await _seed(async_session, repo.id, "Imported", "Withdrawn")+ await accept_decision(async_session, withdrawn, accepter="tester")+ for rec in (kept, withdrawn):+ rec.decision = ""+ await async_session.flush()++ await record_acceptance(+ async_session,+ kept,+ action="accepted",+ currency="active",+ artifact="decisions.yaml",+ kind="import",+ )+ await dismiss_candidate(async_session, withdrawn, reason="gone", accepter="tester")++ assert await is_accepted(async_session, kept.id)+ assert (await latest_acceptance(async_session, withdrawn.id)).currency == "dismissed"++async def test_the_database_refuses_an_acceptance_with_no_scope(async_session):"""The contract is a constraint, not only a Python check.diff --git a/tests/unit/persistence/test_decision_head_artifacts.py b/tests/unit/persistence/test_decision_head_artifacts.pyindex 69ae5766c..136b733ca 100644--- a/tests/unit/persistence/test_decision_head_artifacts.py+++ b/tests/unit/persistence/test_decision_head_artifacts.py@@ -165,7 +165,11 @@ async def test_renamed_file_is_not_missing_and_deleted_directory_is(async_sessioasync def test_gone_decision_is_stale_history_never_superseded(async_session, repo_root):repo = await insert_repo(async_session)- why = {"rationale": "Chosen deliberately.", "evidence_commits_json": '["abc1234"]'}+ why = {+ "decision": "Keep it.",+ "rationale": "Chosen deliberately.",+ "evidence_commits_json": '["abc1234"]',+ }gone = await _record(async_session, repo.id, "Legacy layer", ["legacy/a.py"], **why)live = await _record(async_session, repo.id, "Entry point", ["src/old_name.py"], **why)await accept(async_session, gone.id)diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.pyindex 9f238c91b..e885ffef7 100644--- a/tests/unit/server/mcp/test_why.py+++ b/tests/unit/server/mcp/test_why.py@@ -851,6 +851,7 @@ async def test_get_why_targets_do_not_bind_a_record_whose_files_are_gone(sessionid=f"gone{flag}",repository_id=setup_mcp,title=f"Legacy rule {flag}",+ decision="keep the legacy path",rationale="why",affected_files_json=json.dumps([path]),source="pr",diff --git a/tests/unit/server/test_decision_acceptance_contract_wire.py b/tests/unit/server/test_decision_acceptance_contract_wire.pyindex 28765094d..df316774e 100644--- a/tests/unit/server/test_decision_acceptance_contract_wire.py+++ b/tests/unit/server/test_decision_acceptance_contract_wire.py@@ -133,6 +133,7 @@ async def test_blockers_and_review_signals_over_extracted_records(session,repository_id=repo["id"],title="Mined agreement",+ decision="commit on feature branches",kind="agreement",rationale="r",source="inline_marker",