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.

feat(decisions): deliver a working agreement to the agent, and let a person type one (#2410)

Raghav Chamadiya4e66d0e384b9
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index 1eb4dcf15..8fada1e81 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -641,7 +641,7 @@ press the button. Re-recording the title of a decision that is already accepted
without naming its scope is refused rather than applied, because it would clear
the scope that decision governs.
-| `repowise decision add` | Guided interactive capture: title, context, decision, rationale, rejected alternatives, tradeoffs, affected files, tags. Answering the prompts is an acceptance, recorded as one. Name no files and it is kept as a candidate instead, because a decision that names nothing cannot be checked against the code. |
+| `repowise decision add` | Guided interactive capture: kind, title, context, decision, rationale, rejected alternatives, tradeoffs, affected files, tags. Answering the prompts is an acceptance, recorded as one. An architectural record that names no files is kept as a candidate instead, because a decision that names nothing cannot be checked against the code. `--kind agreement` records the other noun — a rule about how the work is conducted — which is accepted without naming files, because it governs the repository rather than part of it, and reaches an agent at session start rather than when a file is edited. |
| `repowise decision list` | Table of id, title, status, source, confidence, staleness, created date. |
| `repowise decision show ID` | Full record including alternatives, consequences, affected files, and the evidence file and line. |
| `repowise decision confirm ID...` | Accept candidates. Refuses, naming the gap, when one has no reason, scope or evidence; `--reason`, `--scope` and `--evidence` supply them. A refused id does not stop the others. `--preview` writes nothing. |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 39167e4be..51cb16995 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1008,6 +1008,7 @@ Manage architectural decision records.
repowise decision list [PATH] # list records
repowise decision show ID [PATH] # full details
repowise decision add [PATH] # interactive add
+repowise decision add --kind agreement # a rule about how the work is done
repowise decision candidates [PATH] # what is awaiting review; these govern nothing
repowise decision confirm ID... [PATH] # accept candidates: this is what makes them govern
repowise decision dismiss ID... [PATH] # tombstone them (sticky; never re-proposed)
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.py
index 068ea4bf7..767234ded 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
@@ -13,10 +13,11 @@ target well under 100ms):
decision (via decision_node_links), say so once per session per decision,
under a strict per-session cap.
-Repo-wide session rules (user corrections with no named files, so no node
-links) can only reach the agent here: they carry a flat base relevance at
-SessionStart so a rule like "never use em dashes" is deliverable at all, but
-they still compete under the same floor and cap as everything else.
+Working agreements (records whose ``kind`` says they govern how the work is
+conducted, so they name no file and have no node links) can only reach the
+agent here: they carry a flat base relevance at SessionStart so a rule like
+"never use em dashes" is deliverable at all, but they still compete under the
+same floor and cap as everything else.
Every injected decision id is recorded in the sessions.db sidecar so the
update-time miner can check whether the guidance was followed or contradicted
@@ -56,7 +57,7 @@ _W_HOP_FILE = 0.3
_MODULE_FACTOR = 0.5
#: Score contribution when a branch-name token appears in the decision text.
_W_BRANCH_TOKEN = 0.4
-#: Base relevance for repo-wide session rules (active, session-sourced, no
+#: Base relevance for working agreements (accepted, ``kind = 'agreement'``, no
#: node links). They apply everywhere, so SessionStart is their only path.
_W_GLOBAL_RULE = 0.5
#: At most this many unlinked global rules per block. Working-set-relevant
@@ -305,6 +306,9 @@ _ACCEPTED = "EXISTS (SELECT 1 FROM decision_acceptances a WHERE a.decision_id =
#: is what such a store has, and it is what the split's own migration reads.
_UNMIGRATED = "1 = 1"
+#: ``lifecycle.AGREEMENT_KIND``, spelled out for the same reason as _ACCEPTED.
+_AGREEMENT_KIND = "agreement"
+
def _accepted_clause(conn: sqlite3.Connection, ref: str) -> str:
"""The acceptance filter for *ref*, or a no-op on a pre-split store."""
@@ -318,12 +322,29 @@ def _accepted_clause(conn: sqlite3.Connection, ref: str) -> str:
return _ACCEPTED.format(ref=ref) if found else _UNMIGRATED
+def _kind_column(conn: sqlite3.Connection) -> str:
+ """``kind`` where the store has the column, ``NULL`` where it does not.
+
+ Probed the way :func:`_accepted_clause` probes for the acceptance table,
+ and for the same reason: this path opens the store read-only, never runs
+ the schema reconciler, and so has to read whatever it is given. Selecting
+ a literal NULL keeps one shape of row for both stores, and NULL is what
+ :func:`_is_repo_wide` reads as "this store cannot answer".
+ """
+ try:
+ cols = conn.execute("PRAGMA table_info(decision_records)").fetchall()
+ except sqlite3.Error:
+ return "NULL"
+ return "kind" if any(c[1] == "kind" for c in cols) else "NULL"
+
+
def _load_active_decisions(conn: sqlite3.Connection) -> list[dict]:
"""Accepted, current decisions with their node links, as plain dicts."""
try:
rows = conn.execute(
- "SELECT id, title, decision, rationale, confidence, staleness_score, source "
- "FROM decision_records WHERE status = 'active' AND "
+ "SELECT id, title, decision, rationale, confidence, staleness_score, source, "
+ + _kind_column(conn)
+ + " FROM decision_records WHERE status = 'active' AND "
+ _accepted_clause(conn, "decision_records")
).fetchall()
except sqlite3.Error:
@@ -337,6 +358,7 @@ def _load_active_decisions(conn: sqlite3.Connection) -> list[dict]:
"confidence": r[4] if isinstance(r[4], (int, float)) else 0.5,
"staleness": r[5] if isinstance(r[5], (int, float)) else 0.0,
"source": r[6] or "",
+ "kind": r[7],
"links": [],
}
for r in rows
@@ -355,6 +377,23 @@ def _load_active_decisions(conn: sqlite3.Connection) -> list[dict]:
return decisions
+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:
+ an agreement that names files has been given a real scope by something and
+ the ordinary overlap rules apply to it, so the noun is necessary and not
+ sufficient.
+
+ A store written before the entity split has no noun to read, and refusing
+ to call anything repo-wide there would stop delivering the rules it does
+ hold. That store gets the guess this function replaces.
+ """
+ if decision["kind"] is None:
+ return not decision["links"] and decision["source"] == "session"
+ return decision["kind"] == _AGREEMENT_KIND and not decision["links"]
+
+
def _freshness(staleness: float) -> float:
"""Staleness discounts relevance but never zeroes an otherwise-relevant hit."""
return 1.0 - 0.6 * max(0.0, min(1.0, staleness))
@@ -386,9 +425,9 @@ def _score_decision(
text = f"{decision['title']} {decision['decision']}".lower()
if any(t in text for t in branch_tokens):
relevance = min(1.0, relevance + _W_BRANCH_TOKEN)
- if not decision["links"] and decision["source"] == "session":
- # A repo-wide rule mined from user corrections: applies everywhere,
- # so it gets a base relevance instead of file overlap.
+ if _is_repo_wide(decision):
+ # A working agreement: it applies everywhere, so it gets a base
+ # relevance instead of file overlap.
relevance = max(relevance, _W_GLOBAL_RULE)
return relevance * decision["confidence"] * _freshness(decision["staleness"])
@@ -446,7 +485,7 @@ def _session_decision_block(repo_path: Path, session_id: str) -> str | None:
for decision, _score in scored:
if len(shown) >= _MAX_ITEMS:
break
- is_global = not decision["links"] and decision["source"] == "session"
+ is_global = _is_repo_wide(decision)
if is_global and globals_shown >= _MAX_GLOBAL_RULES:
continue
line = _format_decision_line(decision)
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index 150d338ff..9b6cb64df 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -1,4 +1,4 @@
-"""``repowise decision`` — manage architectural decision records."""
+"""``repowise decision`` — manage decision records."""
from __future__ import annotations
@@ -20,6 +20,11 @@ from repowise.cli.helpers import (
run_async,
)
from repowise.cli.output import emit_json, emit_refusal, format_option, notice_console
+from repowise.core.analysis.decisions.lifecycle import (
+ AGREEMENT_KIND,
+ ARCHITECTURAL_KIND,
+ DECISION_KINDS,
+)
from repowise.core.analysis.decisions.provenance import LISTABLE_SOURCES
from repowise.core.precedent.currency import describe_decision_currency
@@ -160,6 +165,13 @@ async def _resolve_decision_id(session, decision_id: str) -> str | None:
"--affects", "affected", multiple=True, help="A file or module this governs. Repeatable."
)
@click.option("--tag", "tags", multiple=True, help="A tag. Repeatable.")
+ "--kind",
+ type=click.Choice(DECISION_KINDS),
+ default=ARCHITECTURAL_KIND,
+ show_default=True,
+ help="'architectural' governs the code; 'agreement' governs how the work is done.",
+)
@format_option()
def decision_add(
path: str | None,
@@ -171,13 +183,17 @@ def decision_add(
consequences: tuple[str, ...],
affected: tuple[str, ...],
tags: tuple[str, ...],
+ kind: str,
fmt: str,
) -> None:
- """Add an architectural decision, interactively or from flags.
+ """Add a decision, interactively or from flags.
With both --title and --decision, records without prompting and prints the
new id, so a script or an agent can call it. Everything else is optional.
+ `--kind agreement` records a working agreement: a rule about how the work
+ is conducted, which names no file and is not checked against the code.
+
A flag-driven record lands as `proposed`, where the prompts record `active`.
A person answering eight questions has reviewed the decision; a caller
inferring one from a diff has not, and the store should be able to tell
@@ -212,8 +228,15 @@ def decision_add(
tags_list = list(tags)
if not non_interactive:
- console.print("[bold]Add Architectural Decision[/bold]\n")
-
+ console.print("[bold]Add Decision[/bold]\n")
+
+ kind = click.prompt(
+ "Kind (architectural = about the code, agreement = about how we work)",
+ type=click.Choice(DECISION_KINDS),
+ # The flag, so `--kind agreement` alone is not silently discarded
+ # by falling through to the prompts.
+ default=kind,
+ )
title = click.prompt("Decision title (short)")
context = click.prompt("Context (what forced this decision?)", default="")
decision_text = click.prompt("Decision (what was chosen?)")
@@ -229,11 +252,14 @@ def decision_add(
)
consequences_list = [c.strip() for c in consequences_raw.split(",") if c.strip()]
- affected_raw = click.prompt(
- "Affected files/modules (comma-separated; required to make it govern)",
- default="",
- )
- affected_files = [f.strip() for f in affected_raw.split(",") if f.strip()]
+ if kind == ARCHITECTURAL_KIND:
+ # An agreement names no file by definition, so asking is asking a
+ # question whose only right answer is blank.
+ affected_raw = click.prompt(
+ "Affected files/modules (comma-separated; required to make it govern)",
+ default="",
+ )
+ affected_files = [f.strip() for f in affected_raw.split(",") if f.strip()]
tags_raw = click.prompt(
"Tags (comma-separated: auth, database, api, performance, security, infra, testing)",
@@ -271,15 +297,22 @@ def decision_add(
affected_files=affected_files,
affected_modules=[],
tags=tags_list,
+ kind=kind,
source="cli",
# No confidence: upsert_decision scores a manual entry.
)
decision_id = rec.id
- # A decision that names nothing cannot be checked against the code
- # and cannot reach the agent editing a governed file, so it cannot
- # be accepted. Keeping it as a candidate is better than discarding
- # eight answered questions; ``confirm --scope`` finishes the job.
- if status == "active" and affected_files:
+ # An architectural decision that names nothing cannot be checked
+ # against the code and cannot reach the agent editing a governed
+ # file, so it cannot be accepted. Keeping it as a candidate is
+ # better than discarding eight answered questions; ``confirm
+ # --scope`` finishes the job. An agreement is the other noun: it
+ # names no file *because* it is not about one, its acceptance row
+ # records the repository as its scope, and SessionStart is how it
+ # reaches an agent. Refusing it for the files it is defined not to
+ # have would leave it unacceptable, which is the defect the split
+ # exists to fix.
+ if status == "active" and (affected_files or kind == AGREEMENT_KIND):
# Answering the prompts is the acceptance; recording it as one
# is what makes this record indistinguishable from any other
# accepted decision to every reader.
@@ -324,7 +357,12 @@ def decision_add(
emit_json(
{
"repo": str(repo_path),
- "decision": {"id": decision_id, "title": title, "status": status},
+ "decision": {
+ "id": decision_id,
+ "title": title,
+ "status": status,
+ "kind": kind,
+ },
}
)
return
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 434f993cf..76f298b6c 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -207,6 +207,7 @@ async def upsert_decision(
repository_id: str,
title: str,
status: str = "proposed",
+ kind: str | None = None,
context: str = "",
decision: str = "",
rationale: str = "",
@@ -236,6 +237,11 @@ async def upsert_decision(
record and brings evidence with it. ``confidence=None`` therefore scores
it here. Both call sites used to pass a literal ``1.0``, which is above
the formula's own ``0.99`` ceiling and so was never a score at all.
+
+ ``kind`` is written only when it is given. ``None`` leaves an existing
+ record's noun alone rather than defaulting it back to ``architectural``:
+ a caller that does not know about the split must not silently un-agree an
+ accepted agreement by re-stating the record without it.
"""
# Normalise text fields — LLM extractors may return explicit None
rationale = rationale or ""
@@ -264,6 +270,8 @@ async def upsert_decision(
if existing is not None:
existing.status = status
+ if kind is not None:
+ existing.kind = _extraction_kind(kind)
existing.context = context
existing.decision = decision
existing.rationale = rationale
@@ -294,6 +302,7 @@ async def upsert_decision(
repository_id=repository_id,
title=title,
status=status,
+ kind=_extraction_kind(kind),
context=context,
decision=decision,
rationale=rationale,
diff --git a/tests/unit/cli/test_augment_decision_inject.py b/tests/unit/cli/test_augment_decision_inject.py
index ad7785801..09443ff69 100644
--- a/tests/unit/cli/test_augment_decision_inject.py
+++ b/tests/unit/cli/test_augment_decision_inject.py
@@ -16,6 +16,10 @@ from pathlib import Path
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from repowise.cli.commands.augment_cmd import decision_inject
+from repowise.core.analysis.decisions.lifecycle import (
+ AGREEMENT_KIND,
+ ARCHITECTURAL_KIND,
+)
from repowise.core.persistence.database import init_db
from repowise.core.persistence.models import (
DecisionAcceptance,
@@ -48,6 +52,7 @@ async def _build_wiki_db(repo_root: Path, decisions: list[dict], extras=None) ->
decision=spec.get("decision", ""),
rationale=spec.get("rationale", ""),
status=spec.get("status", "active"),
+ kind=spec.get("kind", ARCHITECTURAL_KIND),
source=spec.get("source", "cli"),
confidence=spec.get("confidence", 0.9),
staleness_score=spec.get("staleness", 0.0),
@@ -164,6 +169,7 @@ async def test_global_session_rule_injected_without_file_overlap(tmp_path, monke
"title": "Never use em dashes",
"decision": "never use em dashes in any output",
"source": "session",
+ "kind": AGREEMENT_KIND,
"confidence": 0.8,
"links": [],
},
@@ -187,6 +193,7 @@ async def test_global_rules_are_capped_and_never_crowd_out_linked(tmp_path, monk
"title": f"Global rule {i}",
"decision": f"always follow global rule number {i}",
"source": "session",
+ "kind": AGREEMENT_KIND,
"confidence": 0.8,
"links": [],
}
@@ -201,16 +208,112 @@ async def test_global_rules_are_capped_and_never_crowd_out_linked(tmp_path, monk
assert sum("Global rule" in ln for ln in block.splitlines()) == 2
-async def test_unlinked_non_session_decision_is_not_global(tmp_path, monkeypatch):
- """Only session-mined rules get the repo-wide base relevance."""
+async def test_unlinked_architectural_decision_is_not_global(tmp_path, monkeypatch):
+ """The noun decides, and a record that names no file is not thereby a rule.
+
+ This is the case the ``source == 'session'`` guess got wrong: a session
+ decision accepted through ``confirm --scope`` names files on its acceptance
+ row and none on the record, and the guess read that as a repo-wide rule and
+ injected it into every session.
+ """
+ await _build_wiki_db(
+ tmp_path,
+ [
+ {
+ "id": "d-arch",
+ "title": "Keep why free of LLM calls",
+ "decision": "the why layer stays deterministic",
+ "source": "session",
+ "kind": ARCHITECTURAL_KIND,
+ "confidence": 0.9,
+ "links": [],
+ }
+ ],
+ )
+ _quiet_git(monkeypatch)
+ assert decision_inject._session_decision_block(tmp_path, "sess-1") is None
+
+
+async def test_agreement_is_global_whatever_mined_it(tmp_path, monkeypatch):
+ """An agreement reaches the agent on its noun, not on its source."""
await _build_wiki_db(
tmp_path,
- [{"id": "d-cli", "title": "A CLI note", "decision": "some note", "links": []}],
+ [
+ {
+ "id": "d-cli-rule",
+ "title": "Never use em dashes",
+ "decision": "never use em dashes in any output",
+ "source": "cli",
+ "kind": AGREEMENT_KIND,
+ "confidence": 0.8,
+ "links": [],
+ }
+ ],
)
_quiet_git(monkeypatch)
+ block = decision_inject._session_decision_block(tmp_path, "sess-1")
+ assert block is not None
+ assert "Never use em dashes" in block
+
+
+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
+ misclassified record that does carry links keeps competing on overlap
+ instead of being injected everywhere.
+ """
+ await _build_wiki_db(
+ tmp_path,
+ [
+ {
+ "id": "d-linked-agreement",
+ "title": "Never use em dashes",
+ "decision": "never use em dashes in any output",
+ "source": "session",
+ "kind": AGREEMENT_KIND,
+ "confidence": 0.8,
+ "links": [("src/core/auth.py", "file")],
+ }
+ ],
+ )
+ _quiet_git(monkeypatch) # no seeds, so no overlap to score on
assert decision_inject._session_decision_block(tmp_path, "sess-1") is None
+async def test_pre_split_store_keeps_delivering_its_rules(tmp_path, monkeypatch):
+ """A store written before the ``kind`` column still gets its repo-wide rules.
+
+ The hook opens the store read-only and never runs the schema reconciler, so
+ it cannot add the column and cannot wait for one. Reading a missing column
+ as "no agreements here" would silently stop delivering every rule such a
+ store holds, which is the one thing this phase may not do.
+ """
+ await _build_wiki_db(
+ tmp_path,
+ [
+ {
+ "id": "d-legacy",
+ "title": "Never use em dashes",
+ "decision": "never use em dashes in any output",
+ "source": "session",
+ "kind": AGREEMENT_KIND,
+ "confidence": 0.8,
+ "links": [],
+ }
+ ],
+ )
+ conn = sqlite3.connect(tmp_path / ".repowise" / "wiki.db")
+ conn.execute("ALTER TABLE decision_records DROP COLUMN kind")
+ conn.commit()
+ conn.close()
+ _quiet_git(monkeypatch)
+
+ block = decision_inject._session_decision_block(tmp_path, "sess-1")
+ assert block is not None
+ assert "Never use em dashes" in block
+
+
async def test_one_hop_expansion_via_graph_edge(tmp_path, monkeypatch):
hop_decision = {
"id": "d-hop",
@@ -448,6 +551,30 @@ async def test_edit_notice_respects_session_cap(tmp_path):
assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", state) is None
+async def test_edit_notice_silent_for_an_agreement(tmp_path):
+ """The edit-time notice stays keyed on links, and an agreement has none.
+
+ Deliberate, not incidental: an agreement is a claim about how the work is
+ conducted, so it has nothing to say about the file being edited, and the
+ ``decision_node_links`` join is what keeps it out. Pinned so the delivery
+ split does not later grow a second path here.
+ """
+ await _build_wiki_db(
+ tmp_path,
+ [
+ {
+ "id": "d-agreement",
+ "title": "Never use em dashes",
+ "decision": "never use em dashes in any output",
+ "source": "session",
+ "kind": AGREEMENT_KIND,
+ "links": [],
+ }
+ ],
+ )
+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {}) is None
+
+
async def test_edit_notice_silent_for_ungoverned_file(tmp_path):
await _build_wiki_db(tmp_path, [_AUTH_DECISION])
assert decision_inject._edit_decision_notice(tmp_path, "README.md", "s1", {}) is None
diff --git a/tests/unit/cli/test_decision_cmd.py b/tests/unit/cli/test_decision_cmd.py
index bf38202a9..07bb48128 100644
--- a/tests/unit/cli/test_decision_cmd.py
+++ b/tests/unit/cli/test_decision_cmd.py
@@ -69,6 +69,31 @@ def test_decision_help_lists_subcommands() -> None:
assert name in result.output
+
+def _stored_column(repo_root: Path, decision_id: str, column: str) -> str:
+ """One column of a record as written, for the ones no command prints."""
+ import sqlite3
+
+ conn = sqlite3.connect(repo_root / ".repowise" / "wiki.db")
+ try:
+ row = conn.execute(
+ f"SELECT {column} FROM decision_records WHERE id LIKE ?",
+ (decision_id + "%",),
+ ).fetchone()
+ finally:
+ conn.close()
+ assert row is not None, decision_id
+ return row[0]
+
+
+def _stored_kind(repo_root: Path, decision_id: str) -> str:
+ return _stored_column(repo_root, decision_id, "kind")
+
+
+def _stored_files(repo_root: Path, decision_id: str) -> str:
+ return _stored_column(repo_root, decision_id, "affected_files_json")
+
+
def test_decision_add_records_without_prompting(indexed_repo: Path) -> None:
"""With --title and --decision, nothing is asked and the id comes back.
@@ -134,7 +159,7 @@ def test_a_flag_driven_decision_lands_proposed(indexed_repo: Path) -> None:
def test_decision_add_prompts_record_active(indexed_repo: Path) -> None:
"""Answering the prompts is an acceptance, and a scope is part of it."""
- answers = "Interactive title\ncontext\nthe decision\nwhy\n\n\nsrc/app.py\n\n"
+ answers = "\nInteractive title\ncontext\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
@@ -149,7 +174,7 @@ def test_decision_add_without_a_scope_stays_a_candidate(indexed_repo: Path) -> N
It is kept rather than refused: eight answered questions are worth more
than the round trip, and ``confirm --scope`` finishes the job.
"""
- answers = "Unscoped title\ncontext\nthe decision\nwhy\n\n\n\n\n"
+ answers = "\nUnscoped title\ncontext\nthe decision\nwhy\n\n\n\n\n"
result = CliRunner().invoke(cli, ["decision", "add", str(indexed_repo)], input=answers)
assert result.exit_code == 0, result.output
@@ -159,6 +184,75 @@ def test_decision_add_without_a_scope_stays_a_candidate(indexed_repo: Path) -> N
assert [d["status"] for d in records if d["title"] == "Unscoped title"] == ["proposed"]
+def test_an_agreement_is_accepted_although_it_names_no_files(indexed_repo: Path) -> None:
+ """The asymmetry the split exists for. Its other half is the test above.
+
+ An agreement names no file because it is not about one, and its acceptance
+ row records the repository as its scope, so the contract is satisfied
+ honestly rather than exempted. Refusing it for the files it is defined not
+ to have is what made a working agreement structurally unacceptable before
+ the split. An architectural record with no files is still refused:
+ ``test_decision_add_without_a_scope_stays_a_candidate`` is that half, and
+ the two only mean anything read together.
+ """
+ answers = "agreement\nNever use em dashes\ncontext\nno em dashes anywhere\nwhy\n\n\n\n"
+ result = CliRunner().invoke(cli, ["decision", "add", str(indexed_repo)], input=answers)
+
+ assert result.exit_code == 0, result.output
+ assert "Stored as a candidate" not in result.output
+ listed = CliRunner().invoke(cli, ["decision", "list", str(indexed_repo), "--format", "json"])
+ records = json.loads(listed.output)["decisions"]
+ stored = [d for d in records if d["title"] == "Never use em dashes"]
+ assert [d["status"] for d in stored] == ["active"]
+ # Accepted on the noun, not because it quietly acquired a scope.
+ assert _stored_files(indexed_repo, stored[0]["id"]) == "[]"
+
+
+def test_the_kind_flag_records_the_noun(indexed_repo: Path) -> None:
+ """--kind reaches the column, so a person can type an agreement at all.
+
+ Read off the record rather than the command's own output: what matters is
+ what the store holds, because the column is what the SessionStart injector
+ reads.
+ """
+ result = CliRunner().invoke(
+ cli,
+ [
+ "decision", "add",
+ "--title", "Commit as the user",
+ "--decision", "every commit is authored by the user",
+ "--kind", "agreement",
+ "--format", "json",
+ str(indexed_repo),
+ ],
+ input="",
+ )
+
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.output)["decision"]
+ assert payload["kind"] == "agreement"
+ assert _stored_kind(indexed_repo, payload["id"]) == "agreement"
+
+
+def test_a_decision_added_without_the_flag_is_architectural(indexed_repo: Path) -> None:
+ """The default is the checkable noun, so nothing silently stops being checked."""
+ result = CliRunner().invoke(
+ cli,
+ [
+ "decision", "add",
+ "--title", "Prefer ruff check here",
+ "--decision", "Run ruff check, never ruff format",
+ "--format", "json",
+ str(indexed_repo),
+ ],
+ input="",
+ )
+
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.output)["decision"]
+ assert _stored_kind(indexed_repo, payload["id"]) == "architectural"
+
+
def test_half_a_command_line_is_an_error_not_a_prompt(indexed_repo: Path) -> None:
"""--title alone must not fall through to the prompts.
@@ -189,6 +283,7 @@ def test_decision_add_help_lists_a_flag_per_field() -> None:
"--consequence",
"--affects",
"--tag",
+ "--kind",
"--format",
):
assert flag in result.output
diff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.py
index 994a2862b..88c03eaeb 100644
--- a/tests/unit/generation/test_editor_file_fetcher.py
+++ b/tests/unit/generation/test_editor_file_fetcher.py
@@ -9,6 +9,7 @@ import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import StaticPool
+from repowise.core.analysis.decisions.lifecycle import AGREEMENT_KIND
from repowise.core.generation.editor_files.fetcher import EditorFileDataFetcher
from repowise.core.persistence.crud import upsert_repository
from repowise.core.persistence.database import init_db
@@ -389,6 +390,40 @@ async def test_a_candidate_never_reaches_the_generated_block(session, repo, tmp_
assert [d.title for d in data.decisions] == []
+async def test_an_accepted_agreement_reaches_the_generated_block(session, repo, tmp_path):
+ """A working agreement rides the instructions file unchanged.
+
+ The query filters on ``status = 'active'`` and acceptance and nothing else,
+ and since the entity split an agreement can be both: its acceptance row
+ records the repository as its scope. The exclusion sweep keeps a record
+ with no affected files rather than dropping it, so nothing here has to know
+ about the noun. Pinned because that is a claim about the delivery half, not
+ an accident of this query's current shape.
+ """
+ agreement = DecisionRecord(
+ repository_id=repo.id,
+ title="Never use em dashes",
+ status="active",
+ kind=AGREEMENT_KIND,
+ rationale="they read as machine-written",
+ decision="never use em dashes in any output",
+ source="session",
+ affected_files_json="[]",
+ evidence_file="agreement",
+ staleness_score=0.0,
+ )
+ session.add(agreement)
+ await session.flush()
+ from repowise.core.persistence.crud.authority import accept_decision
+
+ await accept_decision(session, agreement, accepter="tester")
+ await session.commit()
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+
+ assert "Never use em dashes" in [d.title for d in data.decisions]
+
+
async def test_fetch_avg_confidence(session, repo, tmp_path):
await _add_page(session, repo.id, "file_page:src/a.py", "file_page", "src/a.py", "content")
# Update confidence manually