Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(decisions): mine the decision as a verbatim quote and require its text on every acceptance (#4686)

Raghav Chamadiya2e55e56e1d50
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index c487ea086..53567a75c 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -51,8 +51,8 @@ its source, a confidence, a staleness score, and one or more evidence rows
Acceptance is a recorded event, not a status flag. It carries a reason, a
scope, an evidence reference and who signed it, and Repowise refuses to store
-an acceptance that is missing any of those. A mined candidate with no decision text
-is refused too; `confirm --decision` supplies it:
+an acceptance that is missing any of those. A record with no decision text, mined
+or typed, is refused too; `confirm --decision` supplies it:
```
$ repowise decision confirm 4b6ddc58
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index cdc95f920..e5fb6d547 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -384,6 +384,12 @@ def _split_csv(raw: str) -> list[str]:
return [part.strip() for part in raw.split(",") if part.strip()]
+def _non_blank(value: str) -> str:
+ if not value.strip():
+ raise click.BadParameter("state what was chosen")
+ return value
+
+
def _prompt_decision_fields(kind: str) -> _DecisionFields:
"""Ask for each field in turn; *kind* is the flag's value, offered as default."""
console.print("[bold]Add Decision[/bold]\n")
@@ -397,7 +403,9 @@ def _prompt_decision_fields(kind: str) -> _DecisionFields:
)
title = click.prompt("Decision title (short)")
context = click.prompt("Context (what forced this decision?)", default="")
- decision_text = click.prompt("Decision (what was chosen?)")
+ # Asked again on a blank answer: acceptance refuses a record with no
+ # decision text, and that refusal would discard every answer given here.
+ decision_text = click.prompt("Decision (what was chosen?)", value_proc=_non_blank)
rationale = click.prompt("Rationale (why?)", default="")
alternatives = _split_csv(
click.prompt("Rejected alternatives (comma-separated, optional)", default="")
diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
index f06022bdc..9f4efc9fc 100644
--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
@@ -321,7 +321,8 @@ class AcceptanceRequirement:
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.
+ #: A self-authored record needs it too: a title names the choice, it does
+ #: not state it.
decision: str | None = None
@@ -339,10 +340,11 @@ def acceptance_blockers(req: AcceptanceRequirement) -> list[str]:
``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.
+ needs it, because one that never says what was chosen binds nobody to it,
+ whether it was mined or typed.
"""
blockers: list[str] = []
- if req.decision is not None and not req.self_authored and not req.decision.strip():
+ if req.decision is not None and not req.decision.strip():
blockers.append(NO_DECISION_BLOCKER)
if not req.reason.strip():
blockers.append("no rationale or explicit constraint reason")
diff --git a/packages/core/src/repowise/core/analysis/decisions/prompts.py b/packages/core/src/repowise/core/analysis/decisions/prompts.py
index f46084c8a..5c298d34c 100644
--- a/packages/core/src/repowise/core/analysis/decisions/prompts.py
+++ b/packages/core/src/repowise/core/analysis/decisions/prompts.py
@@ -6,10 +6,14 @@ Extracted from the former decision_extractor.py; imported back into
from __future__ import annotations
+# Every lane behind the substring gate asks for ``decision`` as a verbatim
+# quote: the gate drops any field the source does not contain, so a reworded
+# decision is stored blank.
_SYSTEM_PROMPT = (
"You are an architectural decision extractor. "
"You extract structured decision records from code context. "
- "Return only valid JSON. Never invent rationale not present in the source."
+ "Return only valid JSON. Never invent rationale not present in the source. "
+ "Copy the decision field word for word from the source; never reword it."
)
INLINE_MARKER_PROMPT = """\
@@ -25,7 +29,7 @@ For each marker, return a JSON object:
"marker_line": the line number of the marker this decision came from,
"title": "short title of the decision",
"context": "what situation forced this",
- "decision": "what was chosen",
+ "decision": "the words from the marker that state what was chosen, copied verbatim",
"rationale": "why",
"alternatives": ["rejected alternatives if mentioned"],
"consequences": ["tradeoffs if mentioned"],
@@ -70,7 +74,7 @@ system structure, patterns, migrations, or technology), return a JSON object:
"commit_sha": "the sha",
"title": "short title",
"context": "what situation forced this",
- "decision": "what was chosen or changed",
+ "decision": "the sentence or clause from the commit message that states what was chosen, copied verbatim",
"rationale": "why this approach (infer from message and files only)",
"affected_files": ["which of that commit's files this decision is about"],
"alternatives": [],
@@ -104,7 +108,7 @@ Return a JSON array of decisions:
{{
"title": "short title",
"context": "situation that forced it",
- "decision": "what was chosen",
+ "decision": "the sentence or clause from the document that states what was chosen, copied verbatim",
"rationale": "why",
"alternatives": [],
"consequences": [],
@@ -128,7 +132,7 @@ For each decision return a JSON object:
"commit_sha": "the sha shown",
"title": "short title",
"context": "what situation forced this (only if stated)",
- "decision": "what was chosen or changed",
+ "decision": "the sentence or clause from the body that states what was chosen, copied verbatim",
"rationale": "why (quote/paraphrase the body — never invent)",
"affected_files": ["which of that commit's files this decision is about"],
"alternatives": ["rejected alternatives if mentioned"],
@@ -157,7 +161,7 @@ For each decision return a JSON object:
{{
"title": "short title",
"context": "what situation forced this (only if stated)",
- "decision": "what was chosen",
+ "decision": "the sentence or clause from the comment that states what was chosen, copied verbatim",
"rationale": "why (quote/paraphrase the comment — never invent)",
"alternatives": [],
"consequences": [],
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 28cdb26ec..9e183f078 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -586,8 +586,8 @@ async def create_decision(
be checked against the code or reach an agent editing a governed file, and
a record stating no reason, which has not said why it binds. Discarding the
fields the author did fill in would be worse than keeping the entry
- unaccepted. The response's ``status`` says which of the two happened, and a
- form can predict it from the same one field.
+ unaccepted. The response's ``currency`` says which of the two happened, and
+ a candidate's ``blockers`` name what is missing, such as decision text.
"""
# ``upsert_decision`` dedups on the title and overwrites the scope, so a
# scope-less re-post of an accepted decision would silently withdraw what
@@ -636,7 +636,10 @@ async def create_decision(
# A refused acceptance (e.g. no rationale) keeps the record as a candidate.
with contextlib.suppress(crud.AcceptanceRefusedError):
await crud.accept_decision(session, rec, accepter="web", kind="person")
- return await _one_with_signature(session, repo_id, rec)
+ item = await _one_with_signature(session, repo_id, rec)
+ if item.currency is None:
+ item.blockers = crud.record_blockers(rec)
+ return item
async def _transition_status(
diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.py
index e0ea9d338..e1c66bd08 100644
--- a/packages/server/src/repowise/server/schemas/decisions.py
+++ b/packages/server/src/repowise/server/schemas/decisions.py
@@ -71,6 +71,9 @@ class DecisionRecordResponse(BaseModel):
accepter: str | None = None
accepter_kind: str | None = None
accepter_session: str | None = None
+ # Why a record just created stayed a candidate, in the acceptance
+ # contract's words. Set by the create route only.
+ blockers: list[str] | None = None
@classmethod
def from_orm(cls, obj: object) -> DecisionRecordResponse:
diff --git a/packages/types/__tests__/decisions-vocabulary.test.ts b/packages/types/__tests__/decisions-vocabulary.test.ts
index 180127ac6..8b93b988d 100644
--- a/packages/types/__tests__/decisions-vocabulary.test.ts
+++ b/packages/types/__tests__/decisions-vocabulary.test.ts
@@ -156,10 +156,10 @@ describe("the acceptance contract, mirrored", () => {
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.
+ // A typed record needs it too; only its evidence is exempt.
expect(
decisionAcceptanceBlockers({ ...accepted, decision: "", source: "cli" }),
- ).toEqual([]);
+ ).toEqual(["no decision text: state what was chosen"]);
});
it("falls back to the context when there is no rationale", () => {
diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.ts
index 95b9f2ee1..9af98dc6e 100644
--- a/packages/types/src/decisions.ts
+++ b/packages/types/src/decisions.ts
@@ -300,6 +300,8 @@ export interface DecisionRecord {
accepter?: string | null;
accepter_kind?: AccepterKind | "" | null;
accepter_session?: string | null;
+ /** Why a record just created stayed a candidate. Create endpoint only. */
+ blockers?: string[] | null;
/** Number of evidence rows backing the record. List endpoint only. */
evidence_count?: number | null;
/** Top-ranked evidence row, slimmed for list rows. List endpoint only. */
@@ -501,13 +503,14 @@ export const DECISION_PRESETS = [
*
* `selfAuthored` is the exemption for a record somebody typed: they wrote the
* claim rather than reviewing an inference, so the entry is its own provenance.
- * The engine grants it to `source === "cli"` when an accepter is known.
+ * The engine grants it to `source === "cli"` when an accepter is known. It
+ * covers evidence only.
*
* 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. 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.
+ * stand in for the why is what marked empty records acceptable. Every record
+ * needs its `decision`, typed or mined: one that never says what was chosen
+ * binds nobody to anything.
*/
export function decisionAcceptanceBlockers(record: {
// Required so a caller cannot leave it out and have every record refused.
@@ -526,7 +529,7 @@ export function decisionAcceptanceBlockers(record: {
values.some((v) => (v ?? "").trim().length > 0);
const selfAuthored = record.source === "cli";
- if (!selfAuthored && !nonBlank([record.decision])) {
+ if (!nonBlank([record.decision])) {
blockers.push("no decision text: state what was chosen");
}
if (!nonBlank([record.rationale, record.context])) {
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 47edafa2a..c1683706c 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1614,6 +1614,7 @@ export interface DecisionRecordResponse {
accepter?: string | null;
accepter_kind?: string | null;
accepter_session?: string | null;
+ blockers?: string[] | null;
}
/** The resolved decision capture policy for one repository. */
diff --git a/tests/unit/analysis/test_decision_prompts.py b/tests/unit/analysis/test_decision_prompts.py
new file mode 100644
index 000000000..94d41fe96
--- /dev/null
+++ b/tests/unit/analysis/test_decision_prompts.py
@@ -0,0 +1,32 @@
+"""Every gated extraction prompt asks for ``decision`` as a verbatim quote.
+
+The substring gate blanks any field the source does not contain, so a prompt
+that invites a reworded decision stores the record with no decision text.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.decisions.prompts import (
+ COMMENT_ARCHAEOLOGY_PROMPT,
+ GIT_ARCHAEOLOGY_PROMPT,
+ INLINE_MARKER_PROMPT,
+ PR_BODY_MINING_PROMPT,
+ README_MINING_PROMPT,
+)
+
+
+ "prompt",
+ [
+ INLINE_MARKER_PROMPT,
+ GIT_ARCHAEOLOGY_PROMPT,
+ README_MINING_PROMPT,
+ PR_BODY_MINING_PROMPT,
+ COMMENT_ARCHAEOLOGY_PROMPT,
+ ],
+)
+def test_the_decision_field_is_asked_for_verbatim(prompt: str) -> None:
+ line = next(ln for ln in prompt.splitlines() if ln.strip().startswith('"decision"'))
+ assert "copied verbatim" in line
diff --git a/tests/unit/cli/test_decision_cmd.py b/tests/unit/cli/test_decision_cmd.py
index 9d53f88db..8ebd6e85b 100644
--- a/tests/unit/cli/test_decision_cmd.py
+++ b/tests/unit/cli/test_decision_cmd.py
@@ -225,6 +225,18 @@ def test_decision_add_prompts_record_active(indexed_repo: Path) -> None:
assert [d["status"] for d in records if d["title"] == "Interactive title"] == ["active"]
+def test_decision_add_asks_again_for_a_blank_decision(indexed_repo: Path) -> None:
+ """Acceptance needs the text, so a blank answer is asked again, not stored."""
+ answers = "\nBlank first\ncontext\n \nthe decision\nwhy\n\n\nsrc/app.py\n\n"
+ result = CliRunner().invoke(cli, ["decision", "add", str(indexed_repo)], input=answers)
+
+ assert result.exit_code == 0, result.output
+ assert "state what was chosen" in result.output
+ listed = CliRunner().invoke(cli, ["decision", "list", str(indexed_repo), "--format", "json"])
+ records = json.loads(listed.output)["decisions"]
+ assert [d["status"] for d in records if d["title"] == "Blank first"] == ["active"]
+
+
def test_decision_add_without_a_scope_stays_a_candidate(indexed_repo: Path) -> None:
"""A decision that names no files cannot be checked, so it cannot govern.
@@ -728,6 +740,8 @@ def test_confirm_refuses_a_candidate_with_nothing_to_accept(indexed_repo: Path)
"confirm",
"badbadba",
str(indexed_repo),
+ "--decision",
+ "Keep the measured faster path",
"--reason",
"Because the alternative was measured slower",
"--scope",
diff --git a/tests/unit/persistence/test_decision_authority.py b/tests/unit/persistence/test_decision_authority.py
index 6ee98b50d..82c2037a1 100644
--- a/tests/unit/persistence/test_decision_authority.py
+++ b/tests/unit/persistence/test_decision_authority.py
@@ -164,15 +164,21 @@ async def test_a_mined_candidate_with_no_decision_text_is_refused(async_session)
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."""
+async def test_a_typed_record_needs_decision_text_but_no_evidence(async_session):
+ """A title names the choice without stating it; the entry is still its own evidence."""
repo = await insert_repo(async_session)
(rec,) = await _seed(async_session, repo.id, "Typed")
rec.source = "cli"
rec.decision = ""
+ rec.evidence_commits_json = "[]"
+ rec.evidence_file = None
await async_session.flush()
- await accept_decision(async_session, rec, accepter="tester")
+ 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 await is_accepted(async_session, rec.id)
diff --git a/tests/unit/server/test_decision_acceptance_contract_wire.py b/tests/unit/server/test_decision_acceptance_contract_wire.py
index df316774e..0abd23dfc 100644
--- a/tests/unit/server/test_decision_acceptance_contract_wire.py
+++ b/tests/unit/server/test_decision_acceptance_contract_wire.py
@@ -12,6 +12,7 @@ import pytest
from httpx import AsyncClient
from sqlalchemy import select
+from repowise.core.analysis.decisions.lifecycle import NO_DECISION_BLOCKER, NO_SCOPE_BLOCKER
from repowise.core.persistence import crud
from repowise.core.persistence.crud.authority import candidate_review_signals
from repowise.core.persistence.database import get_session
@@ -62,17 +63,21 @@ async def test_a_file_less_agreement_governs_the_repository(
repo["id"],
title="Commit on feature branches",
kind="agreement",
+ decision="commit on feature branches",
rationale="main is protected",
)
architectural = await _create(
client,
repo["id"],
title="No scope named",
+ decision="d",
rationale="because",
)
assert agreement["status"] == "active"
assert agreement["currency"] == "active"
assert architectural["status"] == "proposed"
+ assert architectural["blockers"] == [NO_SCOPE_BLOCKER]
+ assert agreement["blockers"] is None
async with get_session(app.state.session_factory) as session:
row = (
@@ -97,6 +102,7 @@ async def test_blank_files_fall_through_to_modules(client: AsyncClient) -> None:
client,
repo["id"],
title="Blank file, real module",
+ decision="d",
rationale="why",
affected_files=[" "],
affected_modules=["pkg/core"],
@@ -105,6 +111,23 @@ async def test_blank_files_fall_through_to_modules(client: AsyncClient) -> None:
assert rec["currency"] == "active"
+async def test_a_typed_record_with_no_decision_text_says_why_it_stayed_a_candidate(
+ client: AsyncClient,
+) -> None:
+ repo = await create_test_repo(client)
+ rec = await _create(
+ client,
+ repo["id"],
+ title="Title only",
+ rationale="why",
+ affected_files=["src/a.py"],
+ )
+ assert rec["status"] == "proposed"
+ assert rec["currency"] is None
+ assert rec["blockers"] == [NO_DECISION_BLOCKER]
+
+
@pytest.mark.asyncio
async def test_blockers_and_review_signals_over_extracted_records(
client: AsyncClient, app