Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(decisions): record what signed an acceptance, not only who (#2457)
Raghav Chamadiya43cfe61d5161
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.mdindex 8fada1e81..6bf22bbca 100644--- a/docs/layers/DECISIONS.md+++ b/docs/layers/DECISIONS.md@@ -140,6 +140,7 @@ review as though they were the team's.|---------|-----------------|| `decision confirm ID...` | Accept, optionally editing the reason and scope on the way. Takes many ids. || `decision confirm ID` on a decision | Reaffirm it after review. |+| `decision confirm\|dismiss\|deprecate ID --agent SLUG` | A machine signing as itself. Only `confirm` needs the repository's permission. || `decision merge ID INTO_ID` | Fold a candidate into an existing decision. The old id resolves to the target. || `decision dedupe` | Fold candidates that duplicate another candidate, in one sweep. Dry run until `--apply`. || `decision split ID` | Flag a candidate as bundling two choices. Never splits it for you. |@@ -477,6 +478,39 @@ of the acceptance event, not the authority itself — the acceptance is — buttwo are kept in step, so a reader that only has the status column stays correctrather than merely stale. See [MCP_TOOLS.md](../agent/MCP_TOOLS.md#get_why).+### An agent may withdraw authority; granting it is a switch++An acceptance records what signed it — `person`, `agent` or `import` — beside+who. The two are different questions, and only the first one was ever stored:+`accepter` resolves to `git config user.name`, so an agent confirming a+decision signed the maintainer's name and no surface could tell them apart.++The asymmetry follows. A machine can withdraw authority without asking: the+worst a wrong withdrawal does is stop a rule binding, and re-accepting undoes+it. Granting authority mints a constraint nobody agreed to, under a signature+that reads as an acceptance, so it is refused unless the repository says+otherwise:++```bash+repowise decision config agent-acceptance --on # off by default+repowise decision confirm ID --agent claude_code --session $SESSION_ID+```++`--agent` takes the agent's slug and is accepted by `confirm`, `dismiss` and+`deprecate` alike — withdrawing needs no switch, so it is the action an agent+is likeliest to take, and the one it would otherwise take under your name. On+`confirm` it is refused without the switch. What it+records is visibly an agent's: `decision show --format json` returns+`signature` with the kind and the session, the API carries `accepter_kind`+on every decision row, and the dashboard badges any authority record a person+did not sign. A row written before these columns existed reads as+`unrecorded`, not as a person's — those are the two things the field exists to+keep apart.++The same log records withdrawals, so what is shown is who *signed*, never that+they accepted. A record the evolution stage retired reads "Signed by an agent"+beside a superseded status, not "accepted by" anything.+## Session-mined decisions`repowise update` (docs mode) reads your local coding-agent transcripts and mines@@ -644,7 +678,7 @@ the scope that decision governs.| `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. |+| `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. `--agent SLUG` signs as an agent rather than as you, and needs `decision config agent-acceptance --on`. || `repowise decision dismiss ID...` | Tombstone them. Never re-proposed on reindex. `--preview` writes nothing. || `repowise decision deprecate ID` | Retire it, optionally `--superseded-by <ID>`, which writes the lineage edge. || `repowise decision candidates` | What is awaiting review, and why each was raised. |@@ -656,6 +690,7 @@ the scope that decision governs.| `repowise decision status` | What capture did: policy and preset, per-source state and why, review lanes and backlog age, staging queues, model spend. || `repowise decision config show` | The resolved capture policy: every source, its status, and why. || `repowise decision config preset NAME` | Apply `off`, `local_only`, `balanced`, or `full`. |+| `repowise decision config agent-acceptance --on/--off` | Whether an agent may grant a decision authority. Off by default; no preset changes it. || `repowise decision source list` | The source registry with capabilities and current state. || `repowise decision source set SRC --on/--off` | Switch one source. `--llm/--no-llm` switches only its model stage. || `repowise decision llm --on/--off` | Master switch for decision-extraction model calls. |diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 51cb16995..e6b8950dc 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1011,6 +1011,8 @@ repowise decision add [PATH] # interactive addrepowise decision add --kind agreement # a rule about how the work is donerepowise decision candidates [PATH] # what is awaiting review; these govern nothingrepowise decision confirm ID... [PATH] # accept candidates: this is what makes them govern+repowise decision confirm ID --agent SLUG # an agent signing as itself, not as you+ # (also on dismiss and deprecate)repowise decision dismiss ID... [PATH] # tombstone them (sticky; never re-proposed)repowise decision merge ID INTO_ID # fold a candidate into an existing decisionrepowise decision dedupe [PATH] # fold candidates that duplicate another candidate (dry run by default)@@ -1026,6 +1028,7 @@ repowise decision migrate [PATH] # classify pre-split rows (dry run unlesrepowise decision config show [PATH] # the resolved capture policyrepowise decision config preset NAME [PATH] # default | off | local_only | balanced | fullrepowise decision config discovery [PATH] # budget for the one broad discovery call+repowise decision config agent-acceptance --on|--off # may an agent grant authority? off by defaultrepowise decision source list [PATH] # the source registry and its staterepowise decision source set SRC --on|--off # switch one sourcerepowise decision source set SRC --llm|--no-llm # switch only its model stagediff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex 71a1696a8..5dbd98fb2 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -411,8 +411,15 @@ decisions:max_input_tokens: 30000 # 2000-60000harnesses: # whose transcripts the session lane reads- claude_code # the default; add codex to read that store too+ agent_acceptance: false # may an agent grant a decision authority?```+`agent_acceptance` is the one key here that is not about capture. Off, an agent+can propose candidates and withdraw authority but never grant it; on, it may+accept, and the acceptance is recorded as an agent's — with the session that+signed it — on every surface, never as yours. It ships off and no preset turns+it on.+Every key is optional. **A config with no `decisions:` block behaves exactly asit did before these switches existed**: every source that shipped on is on,model stages on. That resolved policy is named `default`. A source added afterdiff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.pyindex 9b6cb64df..5ea483ac4 100644--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py@@ -20,7 +20,10 @@ from repowise.cli.helpers import (run_async,)from repowise.cli.output import emit_json, emit_refusal, format_option, notice_console+from repowise.core.agents.identity import is_agent_slugfrom repowise.core.analysis.decisions.lifecycle import (+ ACCEPTER_SESSION_MAX,+ AGENT_ACCEPTANCE_REMEDY,AGREEMENT_KIND,ARCHITECTURAL_KIND,DECISION_KINDS,@@ -53,6 +56,68 @@ def _resolve_decision_repo(path: str | None, fmt: str = "table"):return target.repo_path+def _describe_signature(acceptance) -> dict[str, str] | None:+ """Who signed *acceptance*, as a label and its parts. ``None`` for a candidate.++ No stored kind reads as ``unrecorded``, never as a person's. The verb+ comes from the action: the same log records withdrawals.+ """+ if acceptance is None:+ return None+ who = acceptance.accepter or acceptance.artifact+ kind = acceptance.accepter_kind or "unrecorded"+ label = f"{who} ({kind})"+ if acceptance.accepter_session:+ label += f", session {acceptance.accepter_session}"+ return {+ "label": label,+ "verb": acceptance.action.replace("_", " ").capitalize(),+ "accepter": who,+ "kind": kind,+ "session": acceptance.accepter_session,+ "action": acceptance.action,+ }+++def _signer(agent: str, agent_session: str, *, accepter: str = "") -> tuple[str, str]:+ """Validate the signing flags and return ``(kind, accepter_session)``.++ Shared by every verb that appends to the acceptance log, so an agent can+ say it is one wherever it can act.+ """+ if agent and accepter:+ raise click.ClickException("Pass --agent or --as, not both: they name different signers.")+ if agent and not is_agent_slug(agent):+ raise click.ClickException(+ f"{agent!r} is not a well-formed agent slug (lowercase, digits and underscores)."+ )+ if agent_session and not agent:+ raise click.ClickException("--session names the agent signing; pass --agent too.")+ if len(agent_session) > ACCEPTER_SESSION_MAX:+ raise click.ClickException(f"--session is at most {ACCEPTER_SESSION_MAX} characters.")+ return ("agent" if agent else "person"), agent_session+++#: The two flags an agent signs with, on every verb that writes an authority+#: row: withdrawing needs no switch, so it is the likeliest to go unsigned.+def _signing_options(command):+ command = click.option(+ "--session", "agent_session", default="", help="The agent session signing."+ )(command)+ return click.option(+ "--agent",+ default="",+ help="Sign as this agent (e.g. claude_code) rather than as a person.",+ )(command)+++def _load_policy(repo_path: Path):+ """The resolved policy, through the same loader ``decision config`` uses."""+ from repowise.cli.commands.decision_config_cmd import _load++ return _load(repo_path).policy++@click.group("decision")def decision_group() -> None:"""Manage architectural decision records."""@@ -565,6 +630,7 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:get_session,init_db,)+ from repowise.core.persistence.crud.authority import latest_acceptanceurl = get_db_url_for_repo(repo_path)engine = create_engine(url)@@ -574,11 +640,13 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:async with get_session(sf) as session:full_id = await _resolve_decision_id(session, decision_id)rec = await get_decision(session, full_id) if full_id else None+ acceptance = await latest_acceptance(session, rec.id) if rec else None+ signed = _describe_signature(acceptance)await engine.dispose()- return rec+ return rec, signed- rec = run_async(_query())+ rec, signed = run_async(_query())if rec is None:notice_console(fmt).print(f"[red]Decision not found: {decision_id}[/red]")if fmt == "json":@@ -599,6 +667,8 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:"confidence": rec.confidence,"staleness_score": rec.staleness_score,"created_at": rec.created_at.isoformat() if rec.created_at else None,+ # Not "accepted_by": the same log records withdrawals.+ "signature": signed,"currency": describe_decision_currency(repo_path,created_at=rec.created_at,@@ -637,6 +707,9 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:)if currency:lines.append(f"[dim]{currency}[/dim]")+ # A candidate has no line at all; status already says so.+ if signed:+ lines.append(f"{signed['verb']} by: {signed['label']}")lines.append("")if rec.context:lines.append(f"[cyan]Context:[/cyan] {rec.context}")@@ -803,7 +876,9 @@ async def _review_batch(repo_path, tokens, *, action: str, verb: str, preview: breturn results-def _emit_batch(results: list[dict], action: str, verb: str, preview: bool, fmt: str) -> None:+def _emit_batch(+ results: list[dict], action: str, verb: str, preview: bool, fmt: str, remedy: str = ""+) -> None:"""Report a multi-id run, exiting non-zero when any id was refused."""failed = [r for r in results if not r["ok"]]if fmt == "json":@@ -814,6 +889,8 @@ def _emit_batch(results: list[dict], action: str, verb: str, preview: bool, fmt:"results": results,"succeeded": len(results) - len(failed),"failed": len(failed),+ # Once for the run: every refusal here is the same verb.+ **({"remedy": remedy} if failed and remedy else {}),})if failed:@@ -831,6 +908,8 @@ def _emit_batch(results: list[dict], action: str, verb: str, preview: bool, fmt:if preview:console.print("[dim]Nothing was written. Re-run without --preview.[/dim]")if failed:+ if remedy:+ console.print(f"[dim]{remedy}[/dim]")raise click.exceptions.Exit(1)@@ -877,6 +956,7 @@ def _emit_single(result: dict, token: str, verb: str, fmt: str, note: str, remedhelp="Commit, file or link the decision rests on. Repeatable.",)@click.option("--as", "accepter", default="", help="Record a different accepter identity.")+@_signing_options@click.option("--preview", is_flag=True, default=False, help="Report what each id would do, and write nothing.")@@ -887,6 +967,8 @@ def decision_confirm(scope: tuple[str, ...],evidence: tuple[str, ...],accepter: str,+ agent: str,+ agent_session: str,preview: bool,fmt: str,) -> None:@@ -900,10 +982,18 @@ def decision_confirm(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.++ ``--agent`` is how an agent signs as itself. Without it the acceptance is+ recorded as a person's, because without it the identity resolves to the+ repository's git name and a person's is what it would be. It is refused+ unless ``decision config agent-acceptance`` is on for this repository."""ids, path = _split_ids_and_path(decision_ids)repo_path = _resolve_decision_repo(path, fmt)+ kind, signing_session = _signer(agent, agent_session, accepter=accepter)+ granted = _load_policy(repo_path).agent_acceptance if agent else False+async def _accept(session, rec) -> None:from repowise.core.analysis.decisions.accepter import resolve_accepterfrom repowise.core.persistence.crud.authority import accept_decision@@ -911,7 +1001,10 @@ def decision_confirm(await accept_decision(session,rec,- accepter=resolve_accepter(repo_path, override=accepter),+ accepter=agent or resolve_accepter(repo_path, override=accepter),+ kind=kind,+ accepter_session=signing_session,+ agent_acceptance=granted,reason=reason,scope=list(scope) or None,evidence=list(evidence) or None,@@ -922,22 +1015,34 @@ def decision_confirm(repo_path, ids, action="accepted", verb="accept", preview=preview, apply_one=_accept))+ # Both, not either: one run can refuse one id for the policy and another+ # for a missing scope.+ remedy = _ACCEPT_REMEDY+ if agent and not granted:+ remedy = f"{AGENT_ACCEPTANCE_REMEDY} {remedy}"if len(ids) > 1 or preview:- _emit_batch(results, "accepted", "accept", preview, fmt)+ _emit_batch(results, "accepted", "accept", preview, fmt, remedy)return- _emit_single(results[0], ids[0], "accept", fmt, "(governing)", _ACCEPT_REMEDY)+ _emit_single(results[0], ids[0], "accept", fmt, "(governing)", remedy)@decision_group.command("dismiss")@click.argument("decision_ids", nargs=-1, required=True)@click.option("--yes", "-y", is_flag=True, default=False, help="Skip the confirmation prompt.")@click.option("--reason", default="", help="Why it was tombstoned.")+@_signing_options@click.option("--preview", is_flag=True, default=False, help="Report what each id would do, and write nothing.")@format_option()def decision_dismiss(- decision_ids: tuple[str, ...], yes: bool, reason: str, preview: bool, fmt: str+ decision_ids: tuple[str, ...],+ yes: bool,+ reason: str,+ agent: str,+ agent_session: str,+ preview: bool,+ fmt: str,) -> None:"""Dismiss proposed decisions (kept as tombstones; never re-proposed).@@ -945,6 +1050,7 @@ def decision_dismiss("""ids, path = _split_ids_and_path(decision_ids)repo_path = _resolve_decision_repo(path, fmt)+ kind, signing_session = _signer(agent, agent_session)# A machine-readable invocation is non-interactive by construction: the# prompt read EOF and aborted every scripted dismissal.@@ -957,7 +1063,14 @@ def decision_dismiss(from repowise.core.analysis.decisions.accepter import resolve_accepterfrom repowise.core.persistence.crud.authority import dismiss_candidate- await dismiss_candidate(session, rec, reason=reason, accepter=resolve_accepter(repo_path))+ await dismiss_candidate(+ session,+ rec,+ reason=reason,+ accepter=agent or resolve_accepter(repo_path),+ kind=kind,+ accepter_session=signing_session,+ )results = run_async(_review_batch(@@ -986,9 +1099,15 @@ def decision_dismiss(@click.argument("decision_id")@click.argument("path", required=False, default=None)@click.option("--superseded-by", default=None, help="ID of the decision that replaces this one.")+@_signing_options@format_option()def decision_deprecate(- decision_id: str, path: str | None, superseded_by: str | None, fmt: str+ decision_id: str,+ path: str | None,+ superseded_by: str | None,+ agent: str,+ agent_session: str,+ fmt: str,) -> None:"""Retire a decision, optionally naming the one that replaces it.@@ -997,6 +1116,7 @@ def decision_deprecate(exists because somebody named the successor."""repo_path = _resolve_decision_repo(path, fmt)+ kind, signing_session = _signer(agent, agent_session)async def _update():from repowise.core.analysis.decisions.accepter import resolve_accepter@@ -1043,15 +1163,23 @@ def decision_deprecate(session,rec,successor_id=successor,- accepter=resolve_accepter(repo_path),+ accepter=agent or resolve_accepter(repo_path),+ kind=kind,+ accepter_session=signing_session,)except (AcceptanceRefusedError, ValueError) as exc:emit_refusal("supersede_refused", str(exc), fmt, decision_id=rec.id)else:# A candidate has no authority to retire, so this stays the- # plain status change it always was.+ # plain status change it always was. An accepted record+ # reaching it still logs a withdrawal, so the kind travels.await update_decision_status(- session, rec.id, "deprecated", superseded_by=successor+ session,+ rec.id,+ "deprecated",+ superseded_by=successor,+ accepter=agent or resolve_accepter(repo_path),+ kind=kind,)return recfinally:diff --git a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py b/packages/cli/src/repowise/cli/commands/decision_config_cmd.pyindex f7f6f405c..fb4bdbc17 100644--- a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py@@ -110,6 +110,13 @@ def _emit(repo_path: Path, resolution, fmt: str) -> None:# Named even at the default: this is the one setting that widens whose# transcripts are read, and a reader cannot check a line that is absent.console.print(f" [dim]Harnesses read: {', '.join(policy.harnesses)}.[/dim]")+ if policy.agent_acceptance:+ console.print(+ " [yellow]Agent acceptance is ON: an agent may grant a decision "+ "authority. Its acceptances are signed as an agent's, not yours.[/yellow]"+ )+ else:+ console.print(" [dim]Agent acceptance: off. Agents withdraw authority, never grant it.[/dim]")console.print("")for warning in resolution.warnings:@@ -178,6 +185,14 @@ def _diff(before: DecisionPolicy, after: DecisionPolicy) -> list[dict[str, str]]changes.append({"key": f"discovery.{key}", "from": str(old_value), "to": str(new_value)})+ if before.agent_acceptance != after.agent_acceptance:+ changes.append(+ {+ "key": "agent_acceptance",+ "from": str(before.agent_acceptance),+ "to": str(after.agent_acceptance),+ }+ )if before.harnesses != after.harnesses:changes.append({@@ -223,10 +238,19 @@ def config_preset(name: str, path: str | None, dry_run: bool, fmt: str) -> None:from repowise.core.analysis.decisions.policy import preset_policyrepo_path = _resolve_decision_repo(path, fmt)- # A preset names source membership, not which harnesses are read, so the- # harness list the caller did not touch survives applying one.+ # A preset names source membership; the harness list and the agent-grant+ # switch are not, so applying one leaves both as the caller set them.current = _load(repo_path).policy- _apply(repo_path, replace(preset_policy(name), harnesses=current.harnesses), fmt, dry_run)+ _apply(+ repo_path,+ replace(+ preset_policy(name),+ harnesses=current.harnesses,+ agent_acceptance=current.agent_acceptance,+ ),+ fmt,+ dry_run,+ )# ---------------------------------------------------------------------------@@ -279,6 +303,27 @@ def config_discovery(_apply(repo_path, policy, fmt, dry_run)+@config_group.command("agent-acceptance")[email protected]("path", required=False, default=None)[email protected]("--on/--off", "enabled", default=None, required=True, help="Let agents accept.")[email protected]("--dry-run", is_flag=True, default=False, help="Show the change; write nothing.")+@format_option()+def config_agent_acceptance(+ path: str | None, enabled: bool | None, dry_run: bool, fmt: str+) -> None:+ """Allow, or forbid, an agent granting a decision authority.++ Off by default, and off is complete: an agent still withdraws authority,+ proposes candidates and reads what governs. On, its acceptances are+ recorded as an agent's, with the session that signed, on every surface.+ """+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo++ repo_path = _resolve_decision_repo(path, fmt)+ current = _load(repo_path).policy+ _apply(repo_path, current.with_agent_acceptance(bool(enabled)), fmt, dry_run)++@click.group("source")def source_group() -> None:"""List and switch individual capture sources."""diff --git a/packages/core/alembic/versions/0073_decision_acceptance_provenance.py b/packages/core/alembic/versions/0073_decision_acceptance_provenance.pynew file mode 100644index 000000000..8ece0c872--- /dev/null+++ b/packages/core/alembic/versions/0073_decision_acceptance_provenance.py@@ -0,0 +1,55 @@+"""decision_acceptances: record what signed, not only who.++``accepter`` is a free string resolved from ``git config user.name``, so a+machine signing read as a person. ``accepter_kind`` is the distinction;+``accepter_session`` is the transcript behind an agent that signed.++The empty server default is the "written before provenance" value and stays+legible as one; nothing is backfilled to ``person``. Local SQLite stores never+run Alembic -- ``init_db``'s reconciler issues additive DDL -- so this is for+managed Postgres, and the rule itself is enforced in+``crud.authority.record_acceptance``.++Revision ID: 0073+Revises: 0072+Create Date: 2026-09-20+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0073"+down_revision: str | None = "0072"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "decision_acceptances",+ sa.Column("accepter_kind", sa.String(length=16), nullable=False, server_default=""),+ )+ op.add_column(+ "decision_acceptances",+ sa.Column("accepter_session", sa.String(length=64), nullable=False, server_default=""),+ )+ # SQLite cannot ALTER a constraint on, and does not need to: a local store+ # is built from the model, which declares this CHECK at CREATE TABLE.+ if op.get_bind().dialect.name != "sqlite":+ op.create_check_constraint(+ "ck_acceptance_accepter_kind",+ "decision_acceptances",+ "accepter_kind IN ('', 'person', 'agent', 'import')",+ )+++def downgrade() -> None:+ if op.get_bind().dialect.name != "sqlite":+ op.drop_constraint("ck_acceptance_accepter_kind", "decision_acceptances", type_="check")+ op.drop_column("decision_acceptances", "accepter_session")+ op.drop_column("decision_acceptances", "accepter_kind")diff --git a/packages/core/src/repowise/core/analysis/decisions/evolution.py b/packages/core/src/repowise/core/analysis/decisions/evolution.pyindex b3d46f07c..053140853 100644--- a/packages/core/src/repowise/core/analysis/decisions/evolution.py+++ b/packages/core/src/repowise/core/analysis/decisions/evolution.py@@ -771,6 +771,8 @@ async def _retire(session, record, *, successor_id: str | None = None) -> None:action="superseded",currency="superseded",accepter="evolution",+ # This stage retires records and has no path that accepts one.+ kind="agent",note="a later commit reversed this decision",)record.status = "superseded"diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.pyindex dedd75aa5..35f612abf 100644--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py@@ -16,6 +16,9 @@ from dataclasses import dataclass__all__ = ["ACCEPTANCE_ACTIONS",+ "ACCEPTER_KINDS",+ "ACCEPTER_SESSION_MAX",+ "AGENT_ACCEPTANCE_REMEDY","AGREEMENT_KIND","AGREEMENT_SCOPE","ARCHITECTURAL_KIND",@@ -23,17 +26,21 @@ __all__ = ["DECISION_CURRENCIES","DECISION_KINDS","DECISION_STATUS_ORDER",+ "GRANTING_ACTIONS","NEEDS_REVIEW_STALENESS","REVIEW_LANES","SPLIT_MARKERS","STORED_CURRENCIES",+ "UNRECORDED_ACCEPTER_KIND","AcceptanceRequirement","acceptance_blockers",+ "accepter_kind_blocker","bundles_decisions","currency_for_legacy_status","effective_currency","is_governing","legacy_status_for_currency",+ "machine_grant_blocker","status_rank",]@@ -156,6 +163,56 @@ ACCEPTANCE_ACTIONS: tuple[str, ...] = ("returned_to_review",)+#: Actions that create or renew authority, against the three that withdraw it.+GRANTING_ACTIONS: frozenset[str] = frozenset({"accepted", "reaffirmed", "merged"})++#: Who signed an acceptance. ``person`` is a human, ``agent`` a coding agent+#: or a pipeline stage, ``import`` a tracked artifact or manifest speaking for+#: whoever committed it. ``accepter`` alone cannot answer this: it is a free+#: string resolved from the repository's git identity, so a machine signing+#: reads as a person.+#:+#: Stored ``""`` is a row written before this column, never backfilled to+#: ``person``: "unrecorded" and "a human signed" are what this keeps apart.+ACCEPTER_KINDS: tuple[str, ...] = ("person", "agent", "import")+UNRECORDED_ACCEPTER_KIND = ""++#: Width of ``decision_acceptances.accepter_session``, so a caller can refuse+#: a longer id rather than hand Postgres a truncation error.+ACCEPTER_SESSION_MAX = 64++#: What fixes a :func:`machine_grant_blocker` refusal. Addressed to a person,+#: because the party reading it is the agent that was just refused.+AGENT_ACCEPTANCE_REMEDY = (+ "Someone who owns this repository can allow it with "+ "`repowise decision config agent-acceptance --on`, or accept it themselves."+)+++def accepter_kind_blocker(kind: str) -> str | None:+ """Why *kind* cannot be stamped on a new acceptance, or ``None``."""+ if kind in ACCEPTER_KINDS:+ return None+ if kind == UNRECORDED_ACCEPTER_KIND:+ return "no accepter kind: say whether a person, an agent or an import signed this"+ return f"unknown accepter kind {kind!r}: one of {', '.join(ACCEPTER_KINDS)}"+++def machine_grant_blocker(kind: str, action: str, *, granted: bool) -> str | None:+ """Why an agent may not take *action*, or ``None``.++ A machine revokes but does not grant: withdrawing narrows what a record+ claims and re-accepting undoes it, while granting mints a constraint+ nobody agreed to. Stated rather than left true by omission.+ """+ if kind != "agent" or action not in GRANTING_ACTIONS or granted:+ return None+ return (+ f"an agent may not record a {action!r} acceptance: machines withdraw "+ "authority but do not grant it"+ )++#: The fraction of a decision's files that must have moved before the decision#: is worth re-reading. Same 0.5 the staleness surfaces already use; the number#: stays an internal supporting fact and the product word is what is shown.diff --git a/packages/core/src/repowise/core/analysis/decisions/policy.py b/packages/core/src/repowise/core/analysis/decisions/policy.pyindex 599b9d629..57875cfe1 100644--- a/packages/core/src/repowise/core/analysis/decisions/policy.py+++ b/packages/core/src/repowise/core/analysis/decisions/policy.py@@ -344,6 +344,10 @@ class DecisionPolicy:sources: dict[str, SourceSetting]discovery: DiscoveryBudget = _DEFAULT_DISCOVERYharnesses: tuple[str, ...] = DEFAULT_HARNESSES+ #: Whether an agent may grant authority, not merely withdraw it. The only+ #: setting here that lets something other than a person create a+ #: constraint, so it ships off and no preset turns it on.+ agent_acceptance: bool = False# -- queries ---------------------------------------------------------@@ -394,7 +398,12 @@ class DecisionPolicy:# -- projections -----------------------------------------------------def preset_name(self) -> str:- """The preset this policy equals, or ``custom``."""+ """The preset this policy's *capture* equals, or ``custom``.++ ``agent_acceptance`` is not read: it is authority, not membership, and+ counting it would drop the stored ``preset:`` key and with it the+ pinning that keeps a later release's new source switched off.+ """for name, spec in PRESETS.items():if (self.enabled == spec["enabled"]@@ -485,6 +494,8 @@ class DecisionPolicy:block["discovery"] = self.discovery.to_dict()if self.harnesses != DEFAULT_HARNESSES:block["harnesses"] = list(self.harnesses)+ if self.agent_acceptance:+ block["agent_acceptance"] = Truereturn blockdef to_dict(self, *, provider_available: bool = True) -> dict[str, Any]:@@ -495,6 +506,7 @@ class DecisionPolicy:"preset": self.preset_name(),"discovery": self.discovery.to_dict(),"harnesses": list(self.harnesses),+ "agent_acceptance": self.agent_acceptance,"sources": [rt.to_dict() for rt in self.runtime(provider_available=provider_available)],}@@ -529,6 +541,9 @@ class DecisionPolicy:def with_enabled(self, value: bool) -> DecisionPolicy:return replace(self, enabled=value)+ def with_agent_acceptance(self, value: bool) -> DecisionPolicy:+ return replace(self, agent_acceptance=value)+@dataclass(frozen=True, slots=True)class PolicyResolution:@@ -595,6 +610,23 @@ def _resolve_harnesses(raw: Any, warnings: list[str]) -> tuple[str, ...]:return tuple(names)+#: Every key under ``decisions:`` this module owns, live and legacy. A write+#: replaces all of them: ``to_config_block`` omits a setting that equals its+#: default, so merging leaves a stale value and switching one off does nothing.+POLICY_CONFIG_KEYS: frozenset[str] = frozenset(+ {+ "preset",+ "enabled",+ "llm",+ "sources",+ "session_mining",+ "discovery",+ "harnesses",+ "agent_acceptance",+ }+)++def preset_policy(name: str) -> DecisionPolicy:"""The policy a named preset resolves to."""spec = PRESETS.get(name)@@ -740,13 +772,25 @@ def resolve_policy(repo_config: dict[str, Any] | None) -> PolicyResolution:discovery = _resolve_discovery(raw.get("discovery"), warnings)harnesses = _resolve_harnesses(raw.get("harnesses"), warnings)- known = {"preset", "enabled", "llm", "sources", "session_mining", "discovery", "harnesses"}- for field in set(raw) - known:+ # A non-boolean warns rather than grants: the failure this must not have+ # is reading as on.+ agent_acceptance = _as_bool(raw.get("agent_acceptance"))+ if agent_acceptance is None:+ if "agent_acceptance" in raw:+ warnings.append("`decisions.agent_acceptance` is not a boolean; ignoring it.")+ agent_acceptance = False++ for field in set(raw) - POLICY_CONFIG_KEYS:warnings.append(f"Unknown key `decisions.{field}`; ignoring it.")return PolicyResolution(policy=DecisionPolicy(- enabled=enabled, llm=llm, sources=sources, discovery=discovery, harnesses=harnesses+ enabled=enabled,+ llm=llm,+ sources=sources,+ discovery=discovery,+ harnesses=harnesses,+ agent_acceptance=agent_acceptance,),warnings=tuple(warnings),legacy_keys=tuple(legacy),diff --git a/packages/core/src/repowise/core/analysis/decisions/policy_store.py b/packages/core/src/repowise/core/analysis/decisions/policy_store.pyindex b166e149e..40ec90278 100644--- a/packages/core/src/repowise/core/analysis/decisions/policy_store.py+++ b/packages/core/src/repowise/core/analysis/decisions/policy_store.py@@ -13,7 +13,13 @@ from typing import Anyfrom repowise.core.repo_config import load_repo_config, save_repo_config-from .policy import PRESETS, DecisionPolicy, PolicyResolution, resolve_policy+from .policy import (+ POLICY_CONFIG_KEYS,+ PRESETS,+ DecisionPolicy,+ PolicyResolution,+ resolve_policy,+)__all__ = ["PolicyConflictError", "load_policy", "policy_etag", "write_policy"]@@ -67,10 +73,14 @@ def write_policy(merged: dict[str, Any] = dict(config)existing = merged.get("decisions")- decisions = dict(existing) if isinstance(existing, dict) else {}- # `session_mining` is now expressed as `sources.session`; leaving it behind- # would let a stale legacy key contradict the block written above.- decisions.pop("session_mining", None)+ # Every key the policy owns is replaced, not merged over, or a setting+ # `to_config_block` omitted at its default keeps its stored value forever.+ # Unrelated keys under `decisions:` survive, which is what the merge is for.+ decisions = {+ k: v+ for k, v in (existing.items() if isinstance(existing, dict) else ())+ if k not in POLICY_CONFIG_KEYS+ }decisions.update(block)preset = policy.preset_name()if preset in PRESETS:diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex 3cfd2320c..351a6e5ee 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -7,13 +7,20 @@ candidate into a decision, or moves one through review, is here.One rule shapes the module: :func:`record_acceptance` is the only writer of``decision_acceptances``, and it refuses anything the acceptance contract doesnot cover. Every review action goes through it, so no caller can invent a-shortcut past the reason/scope/evidence/identity requirement.+shortcut past the reason/scope/evidence/identity/kind requirement.++The six review verbs below default ``kind`` to ``person`` because that is what+they are: the verbs a human review surface calls. ``record_acceptance`` has no+default, so no caller reaches the log without naming one. The default is a+convention, not a check — what stops an agent signing as a person is that it+says ``--agent``."""from __future__ import annotationsimport jsonfrom collections.abc import Iterable+from dataclasses import dataclassfrom typing import Anyfrom sqlalchemy import func, or_, select@@ -22,15 +29,18 @@ 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,acceptance_blockers,+ accepter_kind_blocker,effective_currency,is_governing,legacy_status_for_currency,+ machine_grant_blocker,)from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATED@@ -46,6 +56,7 @@ from ..models import (__all__ = ["ACCEPTED_SQL_PREDICATE","AcceptanceRefusedError",+ "AcceptanceSignature","accept_decision","accepted_decision_ids","accepted_predicate",@@ -54,11 +65,13 @@ __all__ = ["count_decisions_by_lane","current_currency","decision_currencies",+ "decision_signatures","dismiss_candidate","is_accepted","latest_acceptance","list_candidates","merge_candidate",+ "names_a_scope","reaffirm_decision","record_acceptance","record_blockers",@@ -160,19 +173,8 @@ async def accepted_decision_ids(The subquery picks the highest ``seq`` per decision, which is the append-onlylog's way of saying "current"."""- latest_seq = (- select(- DecisionAcceptance.decision_id.label("did"),- func.max(DecisionAcceptance.seq).label("seq"),- )- .where(DecisionAcceptance.repository_id == repository_id)- .group_by(DecisionAcceptance.decision_id)- .subquery()- )q = select(DecisionAcceptance.decision_id, DecisionAcceptance.currency).join(- latest_seq,- (DecisionAcceptance.decision_id == latest_seq.c.did)- & (DecisionAcceptance.seq == latest_seq.c.seq),+ *_latest_acceptance_join(repository_id))rows = (await session.execute(q)).all()if not governing_only:@@ -198,19 +200,8 @@ async def decision_currencies(different answer: the column is a projection every writer keeps in step, soit agrees right up until something writes it without an acceptance."""- latest_seq = (- select(- DecisionAcceptance.decision_id.label("did"),- func.max(DecisionAcceptance.seq).label("seq"),- )- .where(DecisionAcceptance.repository_id == repository_id)- .group_by(DecisionAcceptance.decision_id)- .subquery()- )q = select(DecisionAcceptance.decision_id, DecisionAcceptance.currency).join(- latest_seq,- (DecisionAcceptance.decision_id == latest_seq.c.did)- & (DecisionAcceptance.seq == latest_seq.c.seq),+ *_latest_acceptance_join(repository_id))stored = {did: currency for did, currency in (await session.execute(q)).all()}@@ -228,6 +219,64 @@ async def decision_currencies(return out+def _latest_acceptance_join(repository_id: str) -> tuple[Any, Any]:+ """Target and ON clause restricting a query to each decision's current row."""+ latest_seq = (+ select(+ DecisionAcceptance.decision_id.label("did"),+ func.max(DecisionAcceptance.seq).label("seq"),+ )+ .where(DecisionAcceptance.repository_id == repository_id)+ .group_by(DecisionAcceptance.decision_id)+ .subquery()+ )+ return latest_seq, (+ (DecisionAcceptance.decision_id == latest_seq.c.did)+ & (DecisionAcceptance.seq == latest_seq.c.seq)+ )+++@dataclass(frozen=True, slots=True)+class AcceptanceSignature:+ """Who signed a decision's current authority record, and what they were.++ Empty ``kind`` means the row predates the columns, which is not a claim+ that a person signed. See :data:`~...decisions.lifecycle.ACCEPTER_KINDS`.+ """++ kind: str+ accepter: str+ artifact: str+ session: str+++async def decision_signatures(+ session: AsyncSession,+ repository_id: str,+ records: Iterable[DecisionRecord],+) -> dict[str, AcceptanceSignature]:+ """Current signature per decision id. A candidate is absent from the map.++ The companion of :func:`decision_currencies`: that says what a decision's+ authority amounts to, this says who signed it. Both read the same+ highest-``seq`` row, so no surface needs a second opinion about which one+ is current. The row may record a withdrawal, so a caller wording this must+ read ``action`` rather than assume an acceptance.+ """+ q = select(+ DecisionAcceptance.decision_id,+ DecisionAcceptance.accepter_kind,+ DecisionAcceptance.accepter,+ DecisionAcceptance.artifact,+ DecisionAcceptance.accepter_session,+ ).join(*_latest_acceptance_join(repository_id))+ rows = {+ did: AcceptanceSignature(kind=kind, accepter=who, artifact=art, session=sess)+ for did, kind, who, art, sess in (await session.execute(q)).all()+ }+ return {r.id: rows[r.id] for r in records if r.id in rows}++async def count_decisions_by_lane(session: AsyncSession, repository_id: str) -> dict[str, int]:@@ -377,6 +426,12 @@ def _non_blank(values: list[str]) -> list[str]:return [v for v in values if v and v.strip()]+def names_a_scope(record: DecisionRecord) -> list[str]:+ """The files or modules *record* names, for a caller asking what a+ re-statement would clear."""+ return _named_scope(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@@ -484,11 +539,14 @@ async def record_acceptance(*,action: str,currency: str,+ kind: str,reason: str = "",scope: list[str] | None = None,evidence: list[str] | None = None,accepter: str = "",artifact: str = "",+ accepter_session: str = "",+ agent_acceptance: bool = False,note: str = "",) -> DecisionAcceptance:"""Append one acceptance row for *record*, or refuse.@@ -498,6 +556,11 @@ async def record_acceptance(well-formed candidate needs no arguments beyond the accepter; a recordmissing any of them is refused with the specific gap named rather thanaccepted with a blank.++ *kind* has no default: the one value nobody should fall into is the one a+ reader takes for a human signature. *agent_acceptance* is the repository's+ policy switch, passed only by a caller that resolved it; without it an+ agent may withdraw authority but not grant it."""if action not in ACCEPTANCE_ACTIONS:raise ValueError(f"Unknown acceptance action {action!r}.")@@ -513,6 +576,17 @@ async def record_acceptance(artifact=artifact,)blockers = acceptance_blockers(req)+ for check in (+ accepter_kind_blocker(kind),+ machine_grant_blocker(kind, action, granted=agent_acceptance),+ # SQLite ignores the column width and Postgres truncates; both are+ # worse than a refusal.+ f"accepter session is longer than {ACCEPTER_SESSION_MAX} characters"+ if len(accepter_session) > ACCEPTER_SESSION_MAX+ else None,+ ):+ if check:+ blockers.append(check)if blockers:raise AcceptanceRefusedError(blockers)@@ -524,6 +598,8 @@ async def record_acceptance(req=req,accepter=accepter,artifact=artifact,+ kind=kind,+ accepter_session=accepter_session,note=note,)@@ -545,6 +621,8 @@ async def _append_acceptance(req: AcceptanceRequirement,accepter: str,artifact: str,+ kind: str,+ accepter_session: str,note: str,) -> DecisionAcceptance:"""Insert the next log row, retrying the sequence on a concurrent append.@@ -573,6 +651,8 @@ async def _append_acceptance(evidence_json=json.dumps(list(req.evidence)),accepter=accepter,artifact=artifact,+ accepter_kind=kind,+ accepter_session=accepter_session,note=note,)try:@@ -595,6 +675,9 @@ async def accept_decision(*,accepter: str = "",artifact: str = "",+ kind: str = "person",+ accepter_session: str = "",+ agent_acceptance: bool = False,reason: str = "",scope: list[str] | None = None,evidence: list[str] | None = None,@@ -630,6 +713,9 @@ async def accept_decision(evidence=evidence,accepter=accepter,artifact=artifact,+ kind=kind,+ accepter_session=accepter_session,+ agent_acceptance=agent_acceptance,note=note,)await _set_review_state(session, record, "accepted")@@ -642,6 +728,9 @@ async def reaffirm_decision(*,accepter: str = "",artifact: str = "",+ kind: str = "person",+ accepter_session: str = "",+ agent_acceptance: bool = False,note: str = "",) -> DecisionAcceptance:"""Re-accept a decision after review, clearing a ``needs_review`` state."""@@ -652,6 +741,9 @@ async def reaffirm_decision(currency="active",accepter=accepter,artifact=artifact,+ kind=kind,+ accepter_session=accepter_session,+ agent_acceptance=agent_acceptance,note=note,)@@ -662,6 +754,8 @@ async def return_to_review(*,accepter: str = "",artifact: str = "",+ kind: str = "person",+ accepter_session: str = "",note: str = "",) -> DecisionAcceptance:"""Send an accepted decision back to review without erasing its history.@@ -677,6 +771,8 @@ async def return_to_review(currency="needs_review",accepter=accepter,artifact=artifact,+ kind=kind,+ accepter_session=accepter_session,note=note,)@@ -688,6 +784,8 @@ async def supersede_decision(successor_id: str,accepter: str = "",artifact: str = "",+ kind: str = "person",+ accepter_session: str = "",note: str = "",) -> DecisionAcceptance:"""Retire *record* in favour of *successor_id*, with an explicit edge.@@ -709,6 +807,8 @@ async def supersede_decision(currency="superseded",accepter=accepter,artifact=artifact,+ kind=kind,+ accepter_session=accepter_session,note=note,)record.superseded_by = successor.id@@ -732,6 +832,9 @@ async def merge_candidate(into_id: str,accepter: str = "",artifact: str = "",+ kind: str = "person",+ accepter_session: str = "",+ agent_acceptance: bool = False,note: str = "",) -> DecisionAcceptance:"""Fold *candidate* into an existing decision instead of accepting it twice.@@ -763,6 +866,9 @@ async def merge_candidate(evidence=_record_evidence(target) + _record_evidence(candidate),accepter=accepter,artifact=artifact,+ kind=kind,+ accepter_session=accepter_session,+ agent_acceptance=agent_acceptance,note=note or f"merged candidate {candidate.id}",)await _set_review_state(session, candidate, "merged", merged_into=target.id)@@ -823,6 +929,8 @@ async def dismiss_candidate(*,reason: str = "",accepter: str = "",+ kind: str = "person",+ accepter_session: str = "",) -> DecisionCandidateMeta:"""Tombstone a candidate so re-extraction never proposes it again.@@ -840,6 +948,8 @@ async def dismiss_candidate(action="dismissed",currency="dismissed",accepter=accepter or "dismissed",+ kind=kind,+ accepter_session=accepter_session,note=reason,)record.status = "dismissed"diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.pyindex 5e49918c9..607882106 100644--- a/packages/core/src/repowise/core/persistence/crud/decisions.py+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py@@ -600,6 +600,7 @@ async def update_decision_status(*,superseded_by: str | None = None,accepter: str = "",+ kind: str = "person",) -> DecisionRecord | None:"""Move a decision record between statuses, recording authority changes.@@ -631,7 +632,9 @@ async def update_decision_status(try:if status == "active":if not accepted:- await accept_decision(session, rec, accepter=accepter or "unrecorded")+ await accept_decision(+ session, rec, accepter=accepter or "unrecorded", kind=kind+ )elif accepted and status in ("dismissed", "deprecated", "superseded"):await record_acceptance(session,@@ -639,6 +642,7 @@ async def update_decision_status(action="superseded" if status == "superseded" else "dismissed",currency="superseded" if status == "superseded" else "dismissed",accepter=accepter or "unrecorded",+ kind=kind,)except AcceptanceRefusedError as exc:raise ValueError(str(exc)) from exc@@ -1128,6 +1132,7 @@ async def _accept_from_tracked_artifact(action="accepted",currency="active",artifact=artifact,+ kind="import",note="accepted by a tracked decision record",)except AcceptanceRefusedError as exc:diff --git a/packages/core/src/repowise/core/persistence/decision_manifest.py b/packages/core/src/repowise/core/persistence/decision_manifest.pyindex 66fe9f0d7..38d2d2fa9 100644--- a/packages/core/src/repowise/core/persistence/decision_manifest.py+++ b/packages/core/src/repowise/core/persistence/decision_manifest.py@@ -334,6 +334,8 @@ async def import_manifest(evidence=sorted(entry.evidence) or [artifact],accepter=entry.accepted_by,artifact=entry.accepted_artifact or artifact,+ # The named accepter signed the manifest, not this store.+ kind="import",note="imported from the tracked manifest",)return outcomediff --git a/packages/core/src/repowise/core/persistence/decision_migration.py b/packages/core/src/repowise/core/persistence/decision_migration.pyindex 7ab7ce793..ab3e46ddb 100644--- a/packages/core/src/repowise/core/persistence/decision_migration.py+++ b/packages/core/src/repowise/core/persistence/decision_migration.py@@ -382,6 +382,7 @@ async def apply_migration(action="accepted",currency="active",accepter=f"migration:{rec.source}",+ kind="import",note="reconstructed from a self-authored legacy record",)except AcceptanceRefusedError as exc:diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 16f80319c..a9fd24991 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -1163,6 +1163,8 @@ class DecisionAcceptance(Base):The CHECK constraints are the acceptance contract, enforced by the databaserather than by whichever caller happens to be writing: a reason, a scope, anevidence reference, and an accepter or artifact identity.++ ``accepter_kind`` is the fifth: the identity says who, this says what."""__tablename__ = "decision_acceptances"@@ -1172,6 +1174,12 @@ class DecisionAcceptance(Base):CheckConstraint("scope_json NOT IN ('', '[]')", name="ck_acceptance_scope"),CheckConstraint("evidence_json NOT IN ('', '[]')", name="ck_acceptance_evidence"),CheckConstraint("accepter <> '' OR artifact <> ''", name="ck_acceptance_identity"),+ # A local store takes its columns from the additive reconciler and+ # never this CHECK, so ``record_acceptance`` is the enforcement.+ CheckConstraint(+ "accepter_kind IN ('', 'person', 'agent', 'import')",+ name="ck_acceptance_accepter_kind",+ ),CheckConstraint("currency IN ('active', 'needs_review', 'uncheckable', 'superseded', 'dismissed')",name="ck_acceptance_currency",@@ -1207,6 +1215,10 @@ class DecisionAcceptance(Base):#: the only accepter that is not a person.accepter: Mapped[str] = mapped_column(Text, nullable=False, default="")artifact: Mapped[str] = mapped_column(Text, nullable=False, default="")+ #: person | agent | import, or '' on a row written before provenance.+ accepter_kind: Mapped[str] = mapped_column(String(16), nullable=False, default="")+ #: The agent session that signed, when one did.+ accepter_session: Mapped[str] = mapped_column(String(64), nullable=False, default="")note: Mapped[str] = mapped_column(Text, nullable=False, default="")created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utcdiff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 026652eac..a2ef987be 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -1128,8 +1128,11 @@ async def _why_path(query: str, repo: str | None) -> dict:result_data["candidates_note"] = (f"{len(candidates)} candidate(s) mention this path and none of them ""govern it. Nobody has accepted them, so they are a review "- "request, not a rule. Accept one with "- "`repowise decision confirm <id> --scope <path>`."+ "request, not a rule. A person accepts one with "+ "`repowise decision confirm <id> --scope <path>`. An agent "+ "cannot, unless this repository has allowed it; where it has, "+ "pass `--agent <your slug>` so the acceptance is not recorded "+ "under a person's name.")if retired:diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.pyindex 09713cbe7..4bbd06166 100644--- a/packages/server/src/repowise/server/routers/decisions.py+++ b/packages/server/src/repowise/server/routers/decisions.py@@ -10,7 +10,11 @@ from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from repowise.core.analysis.decisions.lifecycle import is_governing+from repowise.core.analysis.decisions.lifecycle import (+ AGREEMENT_KIND,+ ARCHITECTURAL_KIND,+ is_governing,+)from repowise.core.persistence import crud, decision_graphfrom repowise.core.persistence.models import DecisionEvidencefrom repowise.server.deps import get_db_session, verify_api_key@@ -42,6 +46,28 @@ router = APIRouter()+def _attach_signature(item: DecisionRecordResponse, signature) -> None:+ """Copy who signed onto a response row. A candidate is left null."""+ if signature is None:+ return+ item.accepter = signature.accepter or signature.artifact+ item.accepter_kind = signature.kind+ item.accepter_session = signature.session+++async def _one_with_signature(session, repo_id: str, rec) -> DecisionRecordResponse:+ """One record, carrying its authority and who signed it.++ Both, never one: a consumer reading a null ``currency`` as "candidate"+ would otherwise call an accepted decision one and find a signature on it.+ """+ item = DecisionRecordResponse.from_orm(rec)+ item.currency = await crud.current_currency(session, rec)+ signatures = await crud.decision_signatures(session, repo_id, [rec])+ _attach_signature(item, signatures.get(rec.id))+ return item++def _in_lane(currency: str | None, lane: str) -> bool:"""Whether a record at *currency* belongs in review lane *lane*.@@ -140,9 +166,11 @@ async def list_decisions(decisions = [d for d in decisions if _in_lane(currencies.get(d.id), lane)]if derived:decisions = decisions[offset : offset + limit]+ signatures = await crud.decision_signatures(session, repo_id, decisions)items = [DecisionRecordResponse.from_orm(d) for d in decisions]for item in items:item.currency = currencies.get(item.id)+ _attach_signature(item, signatures.get(item.id))ids = [d.id for d in decisions]if ids:@@ -337,6 +365,7 @@ def _settings_payload(repo_path: Path, resolution) -> DecisionSettings:enabled=policy.enabled,llm=policy.llm,preset=policy.preset_name(),+ agent_acceptance=policy.agent_acceptance,discovery=DecisionDiscoveryBudget(**policy.discovery.to_dict()),sources=[DecisionSourceState(**rt.to_dict())@@ -414,6 +443,7 @@ async def update_decision_settings(preset_policy(body.preset),discovery=policy.discovery,harnesses=policy.harnesses,+ agent_acceptance=policy.agent_acceptance,)except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc@@ -421,6 +451,8 @@ async def update_decision_settings(policy = policy.with_enabled(body.enabled)if body.llm is not None:policy = policy.with_llm(body.llm)+ if body.agent_acceptance is not None:+ policy = policy.with_agent_acceptance(body.agent_acceptance)for key, patch in (body.sources or {}).items():try:policy = policy.with_source(key, enabled=patch.enabled, llm=patch.llm)@@ -474,7 +506,7 @@ async def get_decision(rec = await crud.get_decision(session, decision_id)if rec is None or rec.repository_id != repo_id:raise HTTPException(status_code=404, detail="Decision not found")- return DecisionRecordResponse.from_orm(rec)+ return await _one_with_signature(session, repo_id, rec)@router.get(@@ -558,9 +590,20 @@ async def create_decision(existing = await crud.find_decision_by_title(session, repo_id, body.title, source="cli")- scoped = bool(body.affected_files or body.affected_modules)- if existing is not None and not scoped and await crud.is_accepted(- session, existing.id+ named = bool(body.affected_files or body.affected_modules)+ # What this body says, or what the record already is: a body naming no+ # kind must not un-agree a stored agreement.+ kind = body.kind or (existing.kind if existing is not None else ARCHITECTURAL_KIND)+ # An agreement names no file because its scope is the repository.+ # Requiring one would leave the noun permanently unacceptable.+ scoped = named or kind == AGREEMENT_KIND+ # What the stored record would lose, not what either side calls it: an+ # agreement can be given a real scope.+ if (+ existing is not None+ and not named+ and crud.names_a_scope(existing)+ and await crud.is_accepted(session, existing.id)):raise HTTPException(status_code=409,@@ -585,6 +628,9 @@ async def create_decision(affected_files=body.affected_files,affected_modules=body.affected_modules,tags=body.tags,+ # None when the body named none: ``upsert_decision`` then leaves an+ # existing record's noun alone.+ kind=body.kind,source="cli",# No confidence: upsert_decision scores a manual entry.)@@ -595,8 +641,8 @@ async def create_decision(# a missing rationale would be the worse answer. The response's# ``status`` reports which of the two happened.with contextlib.suppress(crud.AcceptanceRefusedError):- await crud.accept_decision(session, rec, accepter="web")- return DecisionRecordResponse.from_orm(rec)+ await crud.accept_decision(session, rec, accepter="web", kind="person")+ return await _one_with_signature(session, repo_id, rec)@router.patch(@@ -633,6 +679,7 @@ async def patch_decision(body.status,superseded_by=superseded_by,accepter="web",+ kind="person",)except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc@@ -655,4 +702,4 @@ async def patch_decision(raise HTTPException(status_code=404, detail="Decision not found")assert rec is not None- return DecisionRecordResponse.from_orm(rec)+ return await _one_with_signature(session, repo_id, rec)diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.pyindex 66949d3c8..e0ea9d338 100644--- a/packages/server/src/repowise/server/schemas/decisions.py+++ b/packages/server/src/repowise/server/schemas/decisions.py@@ -4,9 +4,11 @@ from __future__ import annotationsimport jsonfrom datetime import datetime+from typing import Literalfrom pydantic import BaseModel, ConfigDict, Field+from repowise.core.analysis.decisions.lifecycle import DECISION_KINDSfrom repowise.core.analysis.decisions.policy import DISCOVERY_BOUNDSfrom repowise.core.analysis.decisions.scope import derive_decision_scope@@ -63,6 +65,12 @@ class DecisionRecordResponse(BaseModel):# readers that predate the split. A record can be stored ``active`` and# carry no currency at all, which is precisely what a candidate is.currency: str | None = None+ # Who signed the current authority record: person | agent | import, or ""+ # on a row written before provenance. Null on a candidate, with+ # ``currency``.+ accepter: str | None = None+ accepter_kind: str | None = None+ accepter_session: str | None = None@classmethoddef from_orm(cls, obj: object) -> DecisionRecordResponse:@@ -141,6 +149,10 @@ class DecisionLaneCountsResponse(BaseModel):class DecisionCreate(BaseModel):title: str+ # Without this the route could only create the checkable noun, and an+ # agreement names no file. ``None`` states no opinion, so a client that+ # predates the split cannot un-agree a stored agreement.+ kind: Literal[DECISION_KINDS] | None = Nonecontext: str = ""decision: str = ""rationale: str = ""@@ -336,6 +348,10 @@ class DecisionSettings(BaseModel):llm: bool = True#: default | off | local_only | balanced | full | custompreset: str = "default"+ #: Whether an agent may grant a decision authority, as against withdrawing+ #: it. False is the shipped posture, so a settings form that omits this+ #: field is reporting the default rather than hiding a grant.+ agent_acceptance: bool = Falsediscovery: DecisionDiscoveryBudget = DecisionDiscoveryBudget()sources: list[DecisionSourceState] = []provider_available: bool = True@@ -372,6 +388,7 @@ class DecisionSettingsUpdate(BaseModel):llm: bool | None = None#: Applied first, so a preset plus per-source overrides works in one call.preset: str | None = None+ agent_acceptance: bool | None = Nonesources: dict[str, DecisionSourcePatch] | None = None#: Budget for broad session discovery. Omitted fields keep their value.discovery: DecisionDiscoveryPatch | None = Nonediff --git a/packages/types/__tests__/decisions-vocabulary.test.ts b/packages/types/__tests__/decisions-vocabulary.test.tsindex 5acdd85a3..8add07a94 100644--- a/packages/types/__tests__/decisions-vocabulary.test.ts+++ b/packages/types/__tests__/decisions-vocabulary.test.ts@@ -11,6 +11,8 @@*/import { describe, it, expect } from "vitest";import {+ ACCEPTER_KINDS,+ ACCEPTER_KIND_LABELS,CANDIDATE_REVIEW_STATES,DECISION_CURRENCIES,DECISION_SOURCES,@@ -48,6 +50,16 @@ describe("decision vocabulary matches the engine", () => {expect([...DECISION_CURRENCIES]).toEqual(fixture.currencies);});+ it("names the same accepter kinds", () => {+ expect([...ACCEPTER_KINDS]).toEqual(fixture.accepter_kinds);+ });++ it("labels every accepter kind", () => {+ expect(Object.keys(ACCEPTER_KIND_LABELS).sort()).toEqual(+ [...fixture.accepter_kinds].sort(),+ );+ });+it("names the same candidate review states", () => {expect([...CANDIDATE_REVIEW_STATES]).toEqual(fixture.candidate_review_states,diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.tsindex 26a844bf6..e2fd4c5a9 100644--- a/packages/types/src/decisions.ts+++ b/packages/types/src/decisions.ts@@ -196,6 +196,26 @@ export const DECISION_CURRENCY_DESCRIPTIONS: Record<DecisionCurrency, string> =dismissed: "Authority withdrawn. Kept for history.",};+/**+ * What signed an acceptance, as against who. `accepter` is a free string that+ * resolves to the repository's git identity, so a machine signing read as a+ * person. A stored `""` is a row written before the column and is not+ * `person`: "unrecorded" and "a human signed" are what this keeps apart.+ */+export const ACCEPTER_KINDS = ["person", "agent", "import"] as const;++export type AccepterKind = (typeof ACCEPTER_KINDS)[number];++/**+ * Worded for the signature, not the action: the same row records withdrawals,+ * so "accepted" would present a revocation as a grant.+ */+export const ACCEPTER_KIND_LABELS: Record<AccepterKind, string> = {+ person: "Signed by a person",+ agent: "Signed by an agent",+ import: "Signed by a tracked artifact",+};+/** Currencies that still bind future work. A moved decision is one to re-read. */export const GOVERNING_CURRENCIES: readonly DecisionCurrency[] = ["active",@@ -268,6 +288,13 @@ export interface DecisionRecord {* surface that needs the distinction should ask for the lane instead.*/currency?: DecisionCurrency | null;+ /**+ * Who signed the current authority record. Null on a candidate, beside+ * `currency`. `""` means written before provenance, not that a person did.+ */+ accepter?: string | null;+ accepter_kind?: AccepterKind | "" | null;+ accepter_session?: 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. */@@ -285,6 +312,11 @@ export interface EvidencePreview {export interface DecisionCreateInput {title: string;+ /**+ * Omit to state no opinion: the engine then leaves an existing record's+ * noun alone rather than defaulting it back to `architectural`.+ */+ kind?: DecisionKind;context?: string;decision?: string;rationale?: string;@@ -561,6 +593,11 @@ export interface DecisionSettings {enabled: boolean;llm: boolean;preset: DecisionPreset;+ /**+ * Whether an agent may grant a decision authority, as against withdrawing+ * it. False is the shipped posture.+ */+ agent_acceptance: boolean;discovery: DecisionDiscoveryBudget;sources: DecisionSourceState[];provider_available: boolean;@@ -582,6 +619,7 @@ export interface DecisionSettingsUpdate {enabled?: boolean;llm?: boolean;preset?: Exclude<DecisionPreset, "custom">;+ agent_acceptance?: boolean;sources?: Record<string, DecisionSourcePatch>;discovery?: DecisionDiscoveryPatch;etag?: string;diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex bf292065b..9a5a3e88a 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -756,6 +756,7 @@ export interface DecisionCountsResponse {export interface DecisionCreate {title: string;+ kind?: "architectural" | "agreement" | null;context?: string;decision?: string;rationale?: string;@@ -897,6 +898,9 @@ export interface DecisionRecordResponse {evidence_count?: number | null;evidence_preview?: EvidencePreview | null;currency?: string | null;+ accepter?: string | null;+ accepter_kind?: string | null;+ accepter_session?: string | null;}/** The resolved decision capture policy for one repository. */@@ -904,6 +908,7 @@ export interface DecisionSettings {enabled?: boolean;llm?: boolean;preset?: string;+ agent_acceptance?: boolean;discovery?: DecisionDiscoveryBudget;sources?: DecisionSourceState[];provider_available?: boolean;@@ -917,6 +922,7 @@ export interface DecisionSettingsUpdate {enabled?: boolean | null;llm?: boolean | null;preset?: string | null;+ agent_acceptance?: boolean | null;sources?: Record<string, DecisionSourcePatch> | null;discovery?: DecisionDiscoveryPatch | null;etag?: string | null;diff --git a/packages/ui/__tests__/decisions/decision-capture-settings.test.tsx b/packages/ui/__tests__/decisions/decision-capture-settings.test.tsxindex 8dba7cf27..b947be598 100644--- a/packages/ui/__tests__/decisions/decision-capture-settings.test.tsx+++ b/packages/ui/__tests__/decisions/decision-capture-settings.test.tsx@@ -28,6 +28,7 @@ function settings(overrides: Partial<DecisionSettings> = {}): DecisionSettings {enabled: true,llm: true,preset: "default",+ agent_acceptance: false,discovery: { max_sessions: 12, max_input_tokens: 30000 },sources: [source()],provider_available: true,diff --git a/packages/ui/__tests__/decisions/decision-review-lanes.test.tsx b/packages/ui/__tests__/decisions/decision-review-lanes.test.tsxindex 9013a0099..b107382bb 100644--- a/packages/ui/__tests__/decisions/decision-review-lanes.test.tsx+++ b/packages/ui/__tests__/decisions/decision-review-lanes.test.tsx@@ -262,6 +262,75 @@ describe("currency marks the exception, not the default", () => {});});+describe("who signed is marked where it is not a person", () => {+ const rows = () => within(screen.getByRole("list"));++ it("says nothing about the case the surface was built for", () => {+ renderLanes("active", {+ decisions: [+ record({ currency: "active", accepter: "Raghav", accepter_kind: "person" }),+ ],+ });++ expect(rows().queryByText(/Signed by/)).not.toBeInTheDocument();+ });++ it("names an agent, and the session behind it", () => {+ renderLanes("active", {+ decisions: [+ record({+ currency: "active",+ accepter: "claude_code",+ accepter_kind: "agent",+ accepter_session: "sess-42",+ }),+ ],+ });++ const mark = rows().getByText("Signed by an agent");+ expect(mark).toBeInTheDocument();+ expect(mark).toHaveAttribute(+ "title",+ "Signed by an agent: claude_code, session sess-42",+ );+ });++ it("does not call a machine withdrawal an acceptance", () => {+ // The evolution stage retires records as `agent`, so the badge on a+ // history row is over a revocation, not a grant.+ renderLanes("history", {+ decisions: [+ record({+ currency: "superseded",+ accepter: "evolution",+ accepter_kind: "agent",+ }),+ ],+ });++ expect(rows().queryByText(/Accepted by/)).not.toBeInTheDocument();+ expect(rows().getByText("Signed by an agent")).toBeInTheDocument();+ });++ it("marks a row written before the kind was recorded", () => {+ // '' is not `person`: leaving it unmarked would read as one.+ renderLanes("active", {+ decisions: [+ record({ currency: "active", accepter: "Raghav", accepter_kind: "" }),+ ],+ });++ expect(rows().getByText("Signer not recorded")).toBeInTheDocument();+ });++ it("says nothing about a candidate, which nobody signed", () => {+ renderLanes("candidates", { decisions: [record({ currency: null })] });++ expect(rows().queryByText(/Signed by/)).not.toBeInTheDocument();+ expect(rows().queryByText("Signer not recorded")).not.toBeInTheDocument();+ });+});+describe("the source filter is a second axis, not a second lane control", () => {it("offers every live source and no retired one", () => {renderLanes("candidates", { onSourceChange: vi.fn() });diff --git a/packages/ui/src/decisions/decision-capture-settings.tsx b/packages/ui/src/decisions/decision-capture-settings.tsxindex 59fe511ac..4427fa652 100644--- a/packages/ui/src/decisions/decision-capture-settings.tsx+++ b/packages/ui/src/decisions/decision-capture-settings.tsx@@ -179,6 +179,18 @@ export function DecisionCaptureSettings({{...(llmMasterReason ? { reason: llmMasterReason } : {})}onChange={(v) => void write("llm", { llm: v })}/>+ {/* Not a capture switch: capture proposes, this grants. Kept beside+ them because this is the page for what the layer may do alone. */}+ <Toggle+ label="Let agents accept decisions"+ description="Off, an agent can propose and withdraw but never grant authority. On, its acceptances are recorded as an agent's, with the session that signed."+ checked={settings.agent_acceptance}+ disabled={locked || busy("agent_acceptance")}+ {...(readOnlyReason ? { reason: readOnlyReason } : {})}+ onChange={(v) =>+ void write("agent_acceptance", { agent_acceptance: v })+ }+ /></div><section className={SECTION}>diff --git a/packages/ui/src/decisions/decision-review-lanes.tsx b/packages/ui/src/decisions/decision-review-lanes.tsxindex eae3bb73f..89978d3cf 100644--- a/packages/ui/src/decisions/decision-review-lanes.tsx+++ b/packages/ui/src/decisions/decision-review-lanes.tsx@@ -2,6 +2,7 @@import * as React from "react";import {+ ACCEPTER_KIND_LABELS,DECISION_CURRENCY_DESCRIPTIONS,DECISION_CURRENCY_LABELS,DECISION_KIND_LABELS,@@ -12,6 +13,7 @@ import {isRetiredDecisionSource,} from "@repowise-dev/types/decisions";import type {+ AccepterKind,DecisionCurrency,DecisionLane,DecisionRecord,@@ -300,6 +302,7 @@ function DecisionLaneRow({{currency !== null && currency !== "active" && (<CurrencyMark currency={currency as DecisionCurrency} />)}+ <SignatureMark decision={d} />{d.verification && d.verification !== "exact" && (<VerificationBadge verification={d.verification} />)}@@ -406,6 +409,30 @@ function DecisionLaneRow({);}+/**+ * Who signed the row's current authority record, marked only where it is not+ * a person — the case this surface was built for, which carries no badge.+ * `accepter` alone reads as a name, so an agent or an import would be taken+ * for a colleague; an unrecorded kind would be taken for a person.+ */+function SignatureMark({ decision }: { decision: DecisionRecord }) {+ const kind = decision.accepter_kind;+ if (kind === null || kind === undefined || kind === "person") return null;+ const label =+ kind === "" ? "Signer not recorded" : ACCEPTER_KIND_LABELS[kind as AccepterKind];+ const who = [decision.accepter, decision.accepter_session]+ .filter(Boolean)+ .join(", session ");+ return (+ <span+ className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-sm border border-[var(--color-border-default)] px-1.5 text-[11px] text-[var(--color-text-tertiary)]"+ title={who ? `${label}: ${who}` : label}+ >+ {label}+ </span>+ );+}+/*** A currency the reader cannot infer from the row, as a dot plus the word.*diff --git a/tests/fixtures/decision_vocabulary.json b/tests/fixtures/decision_vocabulary.jsonindex c0aac4c99..a4f334d34 100644--- a/tests/fixtures/decision_vocabulary.json+++ b/tests/fixtures/decision_vocabulary.json@@ -52,6 +52,11 @@"dismissed","returned_to_review"],+ "accepter_kinds": [+ "person",+ "agent",+ "import"+ ],"capture_sources": ["inline_marker","git_archaeology",diff --git a/tests/unit/analysis/test_decision_policy.py b/tests/unit/analysis/test_decision_policy.pyindex 0b591ce41..2927fda5c 100644--- a/tests/unit/analysis/test_decision_policy.py+++ b/tests/unit/analysis/test_decision_policy.py@@ -606,3 +606,64 @@ def test_conventions_runs_with_no_model_once_it_is_switched_on():assert policy.source_enabled("conventions") is Trueassert policy.llm_allowed("conventions") is Falseassert "conventions" in policy.enabled_index_sources()+++# ---------------------------------------------------------------------------+# Agent acceptance+# ---------------------------------------------------------------------------+++def test_agent_acceptance_is_off_in_every_preset():+ """The one setting that lets something other than a person grant authority."""+ for name in PRESET_NAMES:+ assert preset_policy(name).agent_acceptance is False+++def test_a_non_boolean_agent_acceptance_does_not_grant():+ resolution = resolve_policy({"decisions": {"agent_acceptance": "yes"}})++ assert resolution.policy.agent_acceptance is False+ assert any("agent_acceptance" in w for w in resolution.warnings)+++def test_turning_agent_acceptance_off_again_actually_writes_it(tmp_path):+ """``to_config_block`` omits a defaulted setting, so a merging write kept+ the stored ``true`` and ``--off`` changed nothing at all."""+ write_policy(tmp_path, preset_policy("default").with_agent_acceptance(True))+ assert load_policy(tmp_path).policy.agent_acceptance is True++ write_policy(tmp_path, load_policy(tmp_path).policy.with_agent_acceptance(False))++ assert load_policy(tmp_path).policy.agent_acceptance is False+++def test_a_policy_write_keeps_unrelated_keys_under_decisions(tmp_path):+ """The replace is scoped to the keys the policy owns, not the whole block."""+ from repowise.core.repo_config import load_repo_config, save_repo_config++ write_policy(tmp_path, preset_policy("default"))+ config = load_repo_config(tmp_path)+ config["decisions"]["something_else"] = 7+ save_repo_config(tmp_path, config)++ write_policy(tmp_path, preset_policy("full"))++ assert load_repo_config(tmp_path)["decisions"]["something_else"] == 7+++def test_the_agent_switch_does_not_rewrite_the_stored_preset(tmp_path):+ """It is authority, not source membership, so it must not read as `custom`.++ Dropping `preset:` also drops the pinning that keeps a source added in a+ later release switched off, which is a capture change from a switch that+ has nothing to do with capture.+ """+ from repowise.core.repo_config import load_repo_config++ write_policy(tmp_path, preset_policy("balanced"))+ write_policy(tmp_path, load_policy(tmp_path).policy.with_agent_acceptance(True))++ resolved = load_policy(tmp_path).policy+ assert resolved.agent_acceptance is True+ assert resolved.preset_name() == "balanced"+ assert load_repo_config(tmp_path)["decisions"]["preset"] == "balanced"diff --git a/tests/unit/analysis/test_decision_vocabulary_contract.py b/tests/unit/analysis/test_decision_vocabulary_contract.pyindex 0a190eb3e..5f98b36ac 100644--- a/tests/unit/analysis/test_decision_vocabulary_contract.py+++ b/tests/unit/analysis/test_decision_vocabulary_contract.py@@ -45,6 +45,15 @@ def test_every_source_has_a_confidence_rank() -> None:assert source in provenance.SOURCE_RANK, source+def test_accepter_kinds_match_the_lifecycle_registry() -> None:+ assert _FIXTURE["accepter_kinds"] == list(lifecycle.ACCEPTER_KINDS)+++def test_unrecorded_accepter_kind_is_not_one_of_them() -> None:+ """The pre-provenance value is not a kind, so no surface may label it one."""+ assert lifecycle.UNRECORDED_ACCEPTER_KIND not in _FIXTURE["accepter_kinds"]++def test_statuses_match_the_one_ladder() -> None:assert _FIXTURE["statuses"] == list(lifecycle.DECISION_STATUS_ORDER)diff --git a/tests/unit/cli/test_decision_agent_acceptance.py b/tests/unit/cli/test_decision_agent_acceptance.pynew file mode 100644index 000000000..964fdbba4--- /dev/null+++ b/tests/unit/cli/test_decision_agent_acceptance.py@@ -0,0 +1,181 @@+"""``decision confirm --agent``: the CLI half of acceptance provenance.++Without ``--agent`` the identity resolves to the repository's git name, so an+agent confirming a decision signed the maintainer's. These hold the flag's+contract: it is refused unless the repository turned agent acceptance on, and+when it is allowed the record says an agent signed it.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.cli.main import cli++from .test_decision_cmd import _seed_wiki_db++_ID = "a" * 32+++def repo(tmp_path: Path) -> Path:+ path = tmp_path / "repo"+ path.mkdir()+ (path / ".repowise").mkdir()+ _seed_wiki_db(+ path,+ [+ {"id": _ID, "title": "Use JWT", "status": "proposed", "source": "pr"},+ {"id": "b" * 32, "title": "Use Postgres", "status": "proposed", "source": "pr"},+ ],+ )+ return path+++def _run(repo: Path, *args: str):+ return CliRunner().invoke(cli, ["decision", *args, str(repo), "--format", "json"])+++def _allow_agents(repo: Path) -> None:+ result = _run(repo, "config", "agent-acceptance", "--on")+ assert result.exit_code == 0, result.output+++def test_an_agent_is_refused_on_a_repository_that_did_not_allow_it(repo: Path) -> None:+ result = _run(repo, "confirm", "aaaa", "--agent", "claude_code")++ assert result.exit_code == 1, result.output+ payload = json.loads(result.output)+ assert "may not record" in payload["message"]+ assert "agent-acceptance --on" in payload["remedy"]+++def test_the_refusal_leads_with_the_switch_it_was_refused_by(repo: Path) -> None:+ """The flags remedy stays, because one run can refuse two ids for two+ reasons, but it must not be the first thing an agent reads: nothing is+ missing from this record."""+ result = _run(repo, "confirm", "aaaa", "--agent", "claude_code")++ remedy = json.loads(result.output)["remedy"]+ assert remedy.startswith("Someone who owns this repository")+++def test_an_allowed_agent_signs_as_itself(repo: Path) -> None:+ _allow_agents(repo)++ result = _run(repo, "confirm", "aaaa", "--agent", "claude_code", "--session", "s-1")+ assert result.exit_code == 0, result.output++ shown = json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"]+ assert (shown["kind"], shown["accepter"], shown["session"]) == (+ "agent",+ "claude_code",+ "s-1",+ )+++def test_confirming_without_the_flag_still_signs_as_a_person(repo: Path) -> None:+ """Turning the switch on must not change what an unflagged confirm records."""+ _allow_agents(repo)++ assert _run(repo, "confirm", "aaaa").exit_code == 0++ shown = json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"]+ assert shown["kind"] == "person"+++def test_a_candidate_reports_no_signer(repo: Path) -> None:+ assert json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"] is None+++def test_a_batch_refusal_still_names_the_switch(repo: Path) -> None:+ """The remedy reached only the one-id path, so a scripted confirm of two+ ids was refused without ever being told which switch to turn on."""+ result = _run(repo, "confirm", "aaaa", "bbbb", "--agent", "claude_code")++ assert result.exit_code == 1, result.output+ assert "agent-acceptance --on" in json.loads(result.output)["remedy"]+++def test_the_remedy_is_addressed_to_a_person(repo: Path) -> None:+ """The party reading it is the one that was just refused. Worded as its+ own next step, it would hand an agent the command that grants it."""+ remedy = json.loads(_run(repo, "confirm", "aaaa", "--agent", "claude_code").output)["remedy"]++ assert "yourself" not in remedy+ assert "owns this repository" in remedy+++def test_a_withdrawal_is_not_reported_as_an_acceptance(repo: Path) -> None:+ """The same log records both, so the verb comes from the action."""+ _allow_agents(repo)+ assert _run(repo, "confirm", "aaaa").exit_code == 0+ assert _run(repo, "dismiss", "aaaa", "--yes").exit_code == 0++ signed = json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"]+ assert signed["verb"] == "Dismissed"+ assert signed["action"] == "dismissed"+++def test_an_agent_signs_its_withdrawals_without_the_switch(repo: Path) -> None:+ """Withdrawing needs no policy, so it is the action an agent is most+ likely to take — and the one it would otherwise take under your name."""+ assert _run(repo, "confirm", "aaaa").exit_code == 0++ result = _run(repo, "dismiss", "aaaa", "--yes", "--agent", "claude_code", "--session", "s-9")+ assert result.exit_code == 0, result.output++ signed = json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"]+ assert (signed["kind"], signed["accepter"], signed["session"]) == (+ "agent",+ "claude_code",+ "s-9",+ )+ assert signed["verb"] == "Dismissed"+++def test_an_agent_signs_a_supersession(repo: Path) -> None:+ assert _run(repo, "confirm", "aaaa").exit_code == 0+ assert _run(repo, "confirm", "bbbb").exit_code == 0++ result = _run(+ repo, "deprecate", "aaaa", "--superseded-by", "bbbb", "--agent", "claude_code"+ )+ assert result.exit_code == 0, result.output++ signed = json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"]+ assert (signed["kind"], signed["verb"]) == ("agent", "Superseded")+++def test_an_agent_signs_a_retirement_with_no_named_successor(repo: Path) -> None:+ """That path goes through ``update_decision_status``, not+ ``supersede_decision``, and it still appends a withdrawal."""+ assert _run(repo, "confirm", "aaaa").exit_code == 0++ assert _run(repo, "deprecate", "aaaa", "--agent", "claude_code").exit_code == 0++ signed = json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"]+ assert signed["kind"] == "agent"+ assert signed["verb"] == "Dismissed"+++ ("args", "expected"),+ [+ (("--agent", "Claude Code"), "not a well-formed agent slug"),+ (("--agent", "claude_code", "--as", "Raghav"), "not both"),+ (("--session", "s-1"), "pass --agent too"),+ ],+)+def test_the_flag_is_checked_before_anything_is_written(+ repo: Path, args: tuple[str, ...], expected: str+) -> None:+ result = _run(repo, "confirm", "aaaa", *args)++ assert result.exit_code != 0+ assert expected in result.output+ assert json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"] is Nonediff --git a/tests/unit/persistence/test_decision_acceptance_provenance.py b/tests/unit/persistence/test_decision_acceptance_provenance.pynew file mode 100644index 000000000..a8f15cf5c--- /dev/null+++ b/tests/unit/persistence/test_decision_acceptance_provenance.py@@ -0,0 +1,288 @@+"""What signed an acceptance, not only who.++``accepter`` resolves to ``git config user.name``, so before these columns an+agent accepting through the CLI signed the maintainer's name and no reader+could tell the two apart. The contract under test is that every new row says+what signed it, and that a machine may withdraw authority but not grant it+unless the repository turned that on.+"""++from __future__ import annotations++import pytest+from sqlalchemy import delete, select++from repowise.core.analysis.decisions.lifecycle import (+ ACCEPTER_KINDS,+ ACCEPTER_SESSION_MAX,+ GRANTING_ACTIONS,+ accepter_kind_blocker,+ machine_grant_blocker,+)+from repowise.core.persistence.crud import bulk_upsert_decisions+from repowise.core.persistence.crud.authority import (+ AcceptanceRefusedError,+ accept_decision,+ decision_signatures,+ dismiss_candidate,+ latest_acceptance,+ reaffirm_decision,+ record_acceptance,+)+from repowise.core.persistence.models import DecisionAcceptance, DecisionRecord+from tests.unit.persistence.helpers import insert_repo+++async def _seed(session, repo_id: str, title: str) -> DecisionRecord:+ await bulk_upsert_decisions(+ session,+ repo_id,+ [+ {+ "title": title,+ "decision": f"{title}: do the thing",+ "rationale": "because the alternative was measured slower",+ "source": "session",+ "status": "proposed",+ "affected_files": ["src/app.py"],+ "evidence_file": "src/app.py",+ "confidence": 0.7,+ "verification": "exact",+ "source_quote": f"{title}: do the thing",+ }+ ],+ )+ return (+ await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repo_id, DecisionRecord.title == title+ )+ )+ ).scalar_one()+++# ---------------------------------------------------------------------------+# The kind is required, and '' is not one+# ---------------------------------------------------------------------------+++async def test_an_acceptance_records_what_signed_it(async_session):+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")++ await accept_decision(async_session, rec, accepter="Raghav", kind="person")++ row = await latest_acceptance(async_session, rec.id)+ assert row is not None+ assert (row.accepter, row.accepter_kind) == ("Raghav", "person")+++async def test_the_accepting_session_is_stored_beside_the_kind(async_session):+ """What turns "an agent" into a transcript somebody can go and read."""+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")++ await accept_decision(+ async_session,+ rec,+ accepter="claude_code",+ kind="agent",+ accepter_session="sess-42",+ agent_acceptance=True,+ )++ row = await latest_acceptance(async_session, rec.id)+ assert (row.accepter_kind, row.accepter_session) == ("agent", "sess-42")+++async def test_the_only_writer_refuses_an_unstated_kind(async_session):+ """'' is the pre-provenance vintage, never a value a new row may claim.++ Without this refusal the column defaults to '' and every surface has to+ decide for itself whether that means "a person" — which is the ambiguity+ the column exists to remove.+ """+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")++ with pytest.raises(AcceptanceRefusedError, match="accepter kind"):+ await record_acceptance(+ async_session, rec, action="accepted", currency="active", accepter="x", kind=""+ )+ assert await latest_acceptance(async_session, rec.id) is None+++async def test_an_unknown_kind_is_refused_by_name(async_session):+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")++ with pytest.raises(AcceptanceRefusedError, match="robot"):+ await record_acceptance(+ async_session, rec, action="accepted", currency="active", accepter="x", kind="robot"+ )+++# ---------------------------------------------------------------------------+# Machines revoke; they do not grant+# ---------------------------------------------------------------------------+++async def test_an_agent_cannot_accept_by_default(async_session):+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")++ with pytest.raises(AcceptanceRefusedError, match="may not record a 'accepted'"):+ await accept_decision(async_session, rec, accepter="claude_code", kind="agent")+ assert await latest_acceptance(async_session, rec.id) is None+++async def test_an_agent_cannot_reaffirm_by_default(async_session):+ """Reaffirming renews authority, so it is a grant and not a read."""+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")+ await accept_decision(async_session, rec, accepter="Raghav", kind="person")++ with pytest.raises(AcceptanceRefusedError, match="may not record a 'reaffirmed'"):+ await reaffirm_decision(async_session, rec, accepter="claude_code", kind="agent")+++async def test_an_agent_may_withdraw_authority_without_the_switch(async_session):+ """The asymmetry, stated: a wrong withdrawal is recoverable, a wrong grant is not."""+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")+ await accept_decision(async_session, rec, accepter="Raghav", kind="person")++ await dismiss_candidate(async_session, rec, reason="reversed", accepter="evolution", kind="agent")++ row = await latest_acceptance(async_session, rec.id)+ assert (row.action, row.accepter_kind) == ("dismissed", "agent")+++async def test_the_policy_switch_is_what_lets_an_agent_accept(async_session):+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")++ await accept_decision(+ async_session, rec, accepter="claude_code", kind="agent", agent_acceptance=True+ )++ row = await latest_acceptance(async_session, rec.id)+ assert (row.action, row.accepter_kind) == ("accepted", "agent")+++async def test_the_switch_does_not_loosen_a_person_or_an_import(async_session):+ """It grants exactly one thing, so turning it on cannot widen anything else."""+ for kind in ACCEPTER_KINDS:+ for action in GRANTING_ACTIONS:+ granted = machine_grant_blocker(kind, action, granted=True)+ ungranted = machine_grant_blocker(kind, action, granted=False)+ assert granted is None+ if kind != "agent":+ assert ungranted is None+++async def test_an_oversized_session_is_refused_not_truncated(async_session):+ """SQLite ignores the width and Postgres raises; both are worse than a refusal."""+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")++ with pytest.raises(AcceptanceRefusedError, match="accepter session is longer"):+ await accept_decision(+ async_session,+ rec,+ accepter="claude_code",+ kind="agent",+ accepter_session="x" * (ACCEPTER_SESSION_MAX + 1),+ agent_acceptance=True,+ )+ assert await latest_acceptance(async_session, rec.id) is None+++def test_the_session_bound_matches_the_column_it_protects():+ from repowise.core.persistence.models import DecisionAcceptance++ width = DecisionAcceptance.__table__.c.accepter_session.type.length+ assert width == ACCEPTER_SESSION_MAX+++def test_every_named_kind_is_storable_and_the_empty_one_is_not():+ assert [k for k in ACCEPTER_KINDS if accepter_kind_blocker(k)] == []+ assert accepter_kind_blocker("") is not None+++# ---------------------------------------------------------------------------+# Reading it back+# ---------------------------------------------------------------------------+++async def test_a_candidate_has_no_signature(async_session):+ """Absent, not blank: a surface must not render an unsigned row as signed."""+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")++ assert await decision_signatures(async_session, repo.id, [rec]) == {}+++async def test_the_signature_read_follows_the_latest_row(async_session):+ """A withdrawal by a machine must not keep showing the person who accepted."""+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")+ await accept_decision(async_session, rec, accepter="Raghav", kind="person")+ assert (await decision_signatures(async_session, repo.id, [rec]))[rec.id].kind == "person"++ await dismiss_candidate(+ async_session, rec, reason="reversed", accepter="evolution", kind="agent"+ )+ signature = (await decision_signatures(async_session, repo.id, [rec]))[rec.id]+ assert (signature.kind, signature.accepter) == ("agent", "evolution")+++async def test_seq_and_not_arrival_order_decides_who_signed(async_session):+ """The log is append-only, so the current row is the highest ``seq``.++ Arrival order agrees with ``seq`` in the ordinary case, which is why a read+ that ignores ``seq`` looks correct: it is the concurrent append — the one+ the ``seq`` retry exists for — that separates them. Written with a lower+ ``seq`` landing last so a read that takes whatever the scan returned picks+ the superseded row.+ """+ repo = await insert_repo(async_session)+ rec = await _seed(async_session, repo.id, "Use Redis")+ await accept_decision(async_session, rec, accepter="Raghav", kind="person")+ await dismiss_candidate(+ async_session, rec, reason="reversed", accepter="evolution", kind="agent"+ )++ # seq 1 again, inserted after seq 2: only the seq restriction rejects it.+ stale = (+ await async_session.execute(+ select(DecisionAcceptance).where(+ DecisionAcceptance.decision_id == rec.id, DecisionAcceptance.seq == 1+ )+ )+ ).scalar_one()+ async_session.expunge(stale)+ await async_session.execute(+ delete(DecisionAcceptance).where(+ DecisionAcceptance.decision_id == rec.id, DecisionAcceptance.seq == 1+ )+ )+ await async_session.flush()+ async_session.add(+ DecisionAcceptance(+ repository_id=repo.id,+ decision_id=rec.id,+ seq=1,+ action="accepted",+ currency="active",+ reason=stale.reason,+ scope_json=stale.scope_json,+ evidence_json=stale.evidence_json,+ accepter="Raghav",+ accepter_kind="person",+ )+ )+ await async_session.flush()++ signature = (await decision_signatures(async_session, repo.id, [rec]))[rec.id]+ assert (signature.kind, signature.accepter) == ("agent", "evolution")diff --git a/tests/unit/server/test_decisions_lanes.py b/tests/unit/server/test_decisions_lanes.pyindex 547f7bf26..a990e91c3 100644--- a/tests/unit/server/test_decisions_lanes.py+++ b/tests/unit/server/test_decisions_lanes.py@@ -227,6 +227,7 @@ async def test_the_governing_lane_pages_over_its_own_rows(action="superseded",currency="superseded",accepter="tester",+ kind="person",evidence=["seed"],)await session.flush()diff --git a/tests/unit/server/test_decisions_provenance_api.py b/tests/unit/server/test_decisions_provenance_api.pynew file mode 100644index 000000000..8f8467f7f--- /dev/null+++ b/tests/unit/server/test_decisions_provenance_api.py@@ -0,0 +1,313 @@+"""The API says who signed, so a dashboard can show it.++A decision list that carries ``currency`` but not the signature can say that+something governs and not whether a person granted it, which is the whole gap+the provenance columns close.+"""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from tests.unit.server.conftest import create_test_repo+++async def _accepted(session_factory, repo_id: str, *, title: str, **accept) -> str:+ async with get_session(session_factory) as session:+ rec = await crud.upsert_decision(+ session,+ repository_id=repo_id,+ title=title,+ status="proposed",+ context="ctx",+ decision=f"dec for {title}",+ rationale="why",+ source="inline_marker",+ affected_files=["src/app.py"],+ evidence_file="src/app.py",+ confidence=0.5,+ )+ await crud.accept_decision(session, rec, evidence=["seed"], **accept)+ await session.flush()+ return rec.id+++async def test_a_list_row_carries_who_signed(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _accepted(+ app.state.session_factory,+ repo["id"],+ title="Signed by an agent",+ accepter="claude_code",+ kind="agent",+ accepter_session="sess-42",+ agent_acceptance=True,+ )++ rows = (await client.get(f"/api/repos/{repo['id']}/decisions")).json()++ assert [r["accepter_kind"] for r in rows] == ["agent"]+ assert rows[0]["accepter"] == "claude_code"+ assert rows[0]["accepter_session"] == "sess-42"+++async def test_a_candidate_carries_no_signature(client: AsyncClient, app) -> None:+ """Null, not blank: an unsigned row must not render as signed."""+ repo = await create_test_repo(client)+ async with get_session(app.state.session_factory) as session:+ await crud.upsert_decision(+ session,+ repository_id=repo["id"],+ title="Nobody accepted this",+ status="proposed",+ context="ctx",+ decision="dec",+ rationale="why",+ source="inline_marker",+ affected_files=["src/app.py"],+ evidence_file="src/app.py",+ confidence=0.5,+ )++ rows = (await client.get(f"/api/repos/{repo['id']}/decisions")).json()++ assert rows[0]["currency"] is None+ assert rows[0]["accepter_kind"] is None+ assert rows[0]["accepter"] is None+++async def test_the_detail_route_says_who_signed_too(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ decision_id = await _accepted(+ app.state.session_factory, repo["id"], title="A rule", accepter="Raghav", kind="person"+ )++ row = (await client.get(f"/api/repos/{repo['id']}/decisions/{decision_id}")).json()++ assert (row["accepter"], row["accepter_kind"]) == ("Raghav", "person")+++async def test_the_web_route_signs_as_a_person(client: AsyncClient) -> None:+ """The person at the keyboard is the signer, and the row says so."""+ repo = await create_test_repo(client)++ created = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Typed by hand",+ "decision": "do the thing",+ "rationale": "because",+ "affected_files": ["src/app.py"],+ },+ )++ assert created.status_code == 201, created.text+ assert created.json()["accepter_kind"] == "person"+++async def test_the_create_route_can_record_an_agreement(client: AsyncClient) -> None:+ """An agreement names no file because it governs the repository.++ Without ``kind`` on the wire this route could only build the checkable+ noun, so an agreement posted here was stored as an unacceptable+ architectural record naming nothing.+ """+ repo = await create_test_repo(client)++ created = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Commit on a branch, never on main",+ "kind": "agreement",+ "decision": "branch first",+ "rationale": "main is protected",+ },+ )++ assert created.status_code == 201, created.text+ body = created.json()+ assert body["kind"] == "agreement"+ assert body["accepter_kind"] == "person", "an agreement must be acceptable"+++async def test_settings_report_the_agent_grant_and_can_change_it(+ client: AsyncClient,+) -> None:+ repo = await create_test_repo(client)++ before = (await client.get(f"/api/repos/{repo['id']}/decisions/settings")).json()+ assert before["agent_acceptance"] is False++ after = await client.put(+ f"/api/repos/{repo['id']}/decisions/settings",+ json={"agent_acceptance": True, "etag": before["etag"]},+ )+ assert after.status_code == 200, after.text+ assert after.json()["agent_acceptance"] is True++ reread = (await client.get(f"/api/repos/{repo['id']}/decisions/settings")).json()+ assert reread["agent_acceptance"] is True+++async def test_a_capture_preset_does_not_revoke_the_agent_grant(+ client: AsyncClient,+) -> None:+ """A preset names source membership. Authority is not membership."""+ repo = await create_test_repo(client)+ first = (await client.get(f"/api/repos/{repo['id']}/decisions/settings")).json()+ on = await client.put(+ f"/api/repos/{repo['id']}/decisions/settings",+ json={"agent_acceptance": True, "etag": first["etag"]},+ )++ after = await client.put(+ f"/api/repos/{repo['id']}/decisions/settings",+ json={"preset": "balanced", "etag": on.json()["etag"]},+ )++ assert after.status_code == 200, after.text+ assert after.json()["agent_acceptance"] is True+++async def test_an_agreement_body_cannot_clear_a_governed_decision(+ client: AsyncClient,+) -> None:+ """The 409 asks what the record would lose, not what the body claims.++ ``kind: agreement`` says "this names no file because it governs the+ repository". Letting that satisfy the guard would let it be said *about a+ record that does govern files*, whose scope the restate then clears while+ its acceptance row survives.+ """+ repo = await create_test_repo(client)+ first = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Use Postgres",+ "decision": "postgres",+ "rationale": "because",+ "affected_files": ["db/engine.py"],+ },+ )+ assert first.json()["accepter_kind"] == "person"++ clash = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={"title": "Use Postgres", "kind": "agreement", "decision": "x", "rationale": "y"},+ )++ assert clash.status_code == 409, clash.text+ still = (+ await client.get(f"/api/repos/{repo['id']}/decisions/{first.json()['id']}")+ ).json()+ assert still["affected_files"] == ["db/engine.py"]+ assert still["kind"] == "architectural"+++async def test_an_agreement_that_names_files_keeps_them(client: AsyncClient) -> None:+ """The noun does not say whether there is a scope to lose.++ An agreement can be given a real one, and then the ordinary rules apply to+ it. Exempting the guard by kind let a re-post silently clear it.+ """+ repo = await create_test_repo(client)+ created = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Release checklist",+ "kind": "agreement",+ "decision": "follow it",+ "rationale": "releases went out unchecked",+ "affected_files": ["docs/RELEASING.md"],+ },+ )+ assert created.status_code == 201, created.text++ clash = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={"title": "Release checklist", "decision": "follow it", "rationale": "typo"},+ )++ assert clash.status_code == 409, clash.text+ still = (+ await client.get(f"/api/repos/{repo['id']}/decisions/{created.json()['id']}")+ ).json()+ assert still["affected_files"] == ["docs/RELEASING.md"]+++async def test_an_agreement_naming_nothing_is_still_restatable(client: AsyncClient) -> None:+ """The guard must not fire where there is genuinely nothing to clear."""+ repo = await create_test_repo(client)+ await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Commit on a branch",+ "kind": "agreement",+ "decision": "branch first",+ "rationale": "main is protected",+ },+ )++ again = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={"title": "Commit on a branch", "decision": "branch first", "rationale": "clearer"},+ )++ assert again.status_code == 201, again.text+ assert again.json()["rationale"] == "clearer"+++async def test_a_body_naming_no_kind_leaves_a_stored_agreement_alone(+ client: AsyncClient,+) -> None:+ """A client that predates the split must not silently un-agree one."""+ repo = await create_test_repo(client)+ created = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Commit on a branch",+ "kind": "agreement",+ "decision": "branch first",+ "rationale": "main is protected",+ },+ )+ assert created.json()["kind"] == "agreement"++ restated = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={"title": "Commit on a branch", "decision": "branch first", "rationale": "fixed typo"},+ )++ assert restated.status_code == 201, restated.text+ assert restated.json()["kind"] == "agreement"+++async def test_a_detail_row_carries_its_currency_beside_its_signature(+ client: AsyncClient, app+) -> None:+ """Both or neither: a consumer reading a null currency as "candidate" would+ otherwise call an accepted decision one and then find a signature on it."""+ repo = await create_test_repo(client)+ decision_id = await _accepted(+ app.state.session_factory, repo["id"], title="A rule", accepter="Raghav", kind="person"+ )++ row = (await client.get(f"/api/repos/{repo['id']}/decisions/{decision_id}")).json()++ assert row["currency"] == "active"+ assert row["accepter_kind"] == "person"diff --git a/tests/unit/server/test_mcp_decision_graph.py b/tests/unit/server/test_mcp_decision_graph.pyindex 3238016c6..eb52254fa 100644--- a/tests/unit/server/test_mcp_decision_graph.py+++ b/tests/unit/server/test_mcp_decision_graph.py@@ -333,6 +333,7 @@ async def decision_db(session: AsyncSession, repo_id: str) -> str:action="superseded",currency="superseded",accepter="test",+ kind="person",evidence=["seed:dec_superseded"],)await session.flush()