Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(decisions): make every review command easy and honest for an agent to drive (#4702)
Raghav Chamadiya5b11931f2cce
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.mdindex 19c585258..d9758129d 100644--- a/docs/layers/DECISIONS.md+++ b/docs/layers/DECISIONS.md@@ -63,9 +63,13 @@ $ repowise decision confirm 4b6ddc58 --scope src/ingestionDecision 4b6ddc58 accepted (governing)```-The acceptance log is append-only. Accepting, re-accepting, withdrawing,-superseding and dismissing each add a row, so the history of who granted and-withdrew authority survives.+The acceptance log is append-only. Accepting, reaffirming, merging,+withdrawing, superseding, deprecating and dismissing each add a row, so the+history of who granted and withdrew authority survives. Only accepted+decisions have rows: dismissing or deprecating a candidate records its signer+(`dismissed_by`, `dismissed_by_kind`, `dismissed_session`) on the candidate's+review row instead. A `deprecated` row withdraws authority like `dismissed`+and is counted as deprecated by `decision health`.## Where decisions come from@@ -99,7 +103,7 @@ currency, which says whether it still describes the code:| Currency | Meaning | Still governs? ||----------|---------|----------------|| `active` | Accepted, and still describes the code | Yes |-| `needs_review` | Accepted, but at least half of the files it names have changed since it was recorded | Yes |+| `needs_review` | Accepted, but at least half of the files it names have changed since it was recorded or last accepted | Yes || `uncheckable` | Accepted, but names no file or module, so it cannot be checked against the code | Agents editing a file are not given it || `stale` | Accepted, but every file it names is gone at HEAD (renames followed) | No || `superseded` | Replaced by a later decision the person named | No |@@ -111,13 +115,16 @@ on every read. `superseded` and `dismissed` are set by a person.- Staleness score: each record carries `staleness_score` between 0 and 1, thefraction of its governed files committed to since the decision was recorded.A record written before its evidence commits landed counts from the commit- (or squash) that landed them. A file the repository does not track counts- as changed. At 0.5 or above a record is stale for `decision list --stale-only`,- the health summary and the `needs_review` currency. A record that names no+ (or squash) that landed them. A later accept, reaffirm or merge by a person+ or agent moves the start to that moment, so reviewing a decision clears+ `needs_review` at once. A file the repository does not track counts as+ changed. At 0.5 or above an accepted decision is `needs_review`, and that is+ what `decision list --stale-only` and the health summary count as stale. A record that names nofile scores 0.0 and is counted separately as unscoped. `repowise decision show` and `get_why` on apath also ask git directly for one record and print what changed.- Sticky review: a dismissed candidate is kept as a tombstone, so re-indexing- never proposes it again. A later extraction never walks an accepted decision+ never proposes it again. Retired candidates (dismissed, deprecated,+ superseded) stay out of the candidate queue and the lane totals. A later extraction never walks an accepted decisionback to `proposed`.- Supersession: `repowise decision deprecate ID --superseded-by ID2` recordsthe successor, and `repowise update` marks a decision that a new commitdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex e6f4ebbb0..d96396fb5 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -954,8 +954,9 @@ repowise decision add --title T --decision D # no prompts, lands proposedrepowise decision add --agent SLUG --title T --decision D --rationale R --affects PATH # an agent's own recordrepowise decision candidates # awaiting review; these govern nothingrepowise decision confirm ID... # accept: this makes them govern+repowise decision reaffirm ID... # renew an accepted decision after re-reading itrepowise decision dismiss ID... # tombstone (sticky; never re-proposed)-repowise decision merge ID INTO_ID # fold into an existing decision (--agent signs)+repowise decision merge ID INTO_ID # fold into an accepted decision (--agent signs)repowise decision dedupe # fold duplicate candidates (dry run unless --apply)repowise decision split ID # flag as bundling two choices; never splits itrepowise decision deprecate ID # optionally naming its successor@@ -1006,19 +1007,24 @@ Every subcommand takes `--format` (`table` default, or `json`) and an optional `| `--lane` | Extraction lane: `pr`, `session`, `session_discovery`, `comment`, `git_archaeology`, `adr`, `inline_marker`, `conventions`, `cli`. Not the Decisions page review lanes. | all lanes || `--limit` | Max listed. | `30` |-**`confirm`, `dismiss`, `deprecate`, `merge`, `split`**+**`confirm`, `reaffirm`, `dismiss`, `deprecate`, `merge`, `split`**| Flag | What it does | Default ||------|--------------|---------|-| `--reason TEXT` | `confirm`: rationale, or why a constraint needs none; corrects the record. `dismiss`: why. `split`: what the two choices are. | |+| `--reason TEXT` | `confirm`: rationale, or why a constraint needs none; corrects the record. `reaffirm`: why it still holds. `dismiss`, `deprecate`: why. `split`: what the two choices are. | || `--scope PATH` | `confirm`: file or module governed. Repeatable; replaces the proposed scope. | proposed scope |-| `--evidence REF` | `confirm`: commit, file or link. Repeatable. | |+| `--evidence REF` | `confirm`, `reaffirm`: commit, file or link. Repeatable. | || `--as NAME` | `confirm`: accepter other than git identity. | git identity || `--superseded-by ID` | `deprecate`: lineage edge to the replacement; deprecated id keeps resolving. | |-| `--agent SLUG` | Not `split`: sign as an agent (e.g. `claude_code`). Granting is refused only under `agent-acceptance --off`. | |-| `--session ID` | Not `split`: signing agent session. | |+| `--agent SLUG` | Sign as an agent (e.g. `claude_code`). Granting is refused only under `agent-acceptance --off`. | |+| `--session ID` | Signing agent session. | || `--yes` / `-y` | `dismiss`: skip the prompt (as does `--format json`). | off |-| `--preview` | `confirm`, `dismiss`: report each id's outcome, write nothing. | off |+| `--preview` | Not `split`: report each id's outcome, write nothing. | off |++- `confirm` accepts candidates; on an already accepted decision it refuses and points at `reaffirm`. `reaffirm` refuses a candidate.+- `merge` needs an accepted target: confirm the target first, or merge the other way.+- A dismissed or deprecated candidate records its signer on its review row.+- With `--format json`, every verb but `split` returns `{action, preview, results, succeeded, failed}`, even for one id.**`dedupe`, `migrate`, `export`, `import`**@@ -1037,7 +1043,7 @@ Every subcommand takes `--format` (`table` default, or `json`) and an optional `| `--status` | `active`, `proposed`, `deprecated`, `superseded`, `dismissed`, `all`. | `all` || `--source` | `adr`, `agent`, `cli`, `comment`, `commit`, `conventions`, `git_archaeology`, `inline_marker`, `llm_inferred`, `pr`, `session`, `all`. | `all` || `--proposed` | `--status proposed`. | off |-| `--stale-only` | Only stale. | off |+| `--stale-only` | Only accepted decisions at `needs_review`, the set `decision health` counts as stale. | off || `--limit` | Max rows listed. | `100` || `--all` | Every matching row; overrides `--limit`. | off |diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.mdindex c26a56d60..fd732f049 100644--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-decision.md@@ -48,12 +48,21 @@ unless the repository turns it on.accept: it signs with `--agent <slug>` (plus `--session <id>` if known), andthe acceptance is recorded as the agent's, not a person's. A repository thatran `repowise decision config agent-acceptance --off` refuses it; then leave- acceptance to a person.+ acceptance to a person. `confirm` refuses a decision that is already+ accepted; renew that one with `reaffirm`.+- **reaffirm** — `repowise decision reaffirm <id>...` — after re-reading a+ `needs_review` decision that still holds, renew it so it counts as current+ from now. Takes `--reason`, `--evidence`, `--agent <slug>` and `--preview`.+ A candidate is refused; accept it with `confirm`.- **merge** — `repowise decision merge <id> <into-id>` — fold a duplicate- candidate into an accepted decision instead of accepting it twice.-- **deprecate / dismiss** — `repowise decision deprecate <id>` (optionally- `--superseded-by <id>`) or `repowise decision dismiss <id> --reason ...`.- An agent passes `--agent <slug>` to merge, deprecate and dismiss too.+ candidate into an accepted decision instead of accepting it twice. The target+ must already be accepted: confirm it first, or merge the other way.+ `--preview` shows the result without writing.+- **deprecate / dismiss** — `repowise decision deprecate <id> --reason ...`+ (optionally `--superseded-by <id>`, `--preview`) or+ `repowise decision dismiss <id> --reason ...`. An agent passes+ `--agent <slug>` to every review command, and the signer is recorded for+ candidates too.## Notes@@ -62,4 +71,7 @@ unless the repository turns it on.alignment score. This command is for *managing* the decision records themselves.- `add` is interactive unless you pass `--title` and `--decision`; the othersubcommands take ids and flags and never prompt, except `dismiss` (pass `--yes`).+- With `--format json`, confirm, reaffirm, merge, deprecate and dismiss always+ return `{action, preview, results, succeeded, failed}`, even for one id. Read+ `results[i].ok`, `.error`, `.message` and `.blockers`.- If unsure of an exact subcommand or flag, run `repowise decision --help`.diff --git a/packages/cli/src/repowise/cli/commands/decision_batch.py b/packages/cli/src/repowise/cli/commands/decision_batch.pyindex 0b921622f..ecd07c2c3 100644--- a/packages/cli/src/repowise/cli/commands/decision_batch.py+++ b/packages/cli/src/repowise/cli/commands/decision_batch.py@@ -5,6 +5,7 @@ Shared by the ``decision`` commands in ``decision_cmd``.from __future__ import annotations+import jsonimport refrom contextlib import asynccontextmanagerfrom dataclasses import dataclass@@ -104,6 +105,31 @@ class _PreviewRollbackError(Exception):"""Signals a preview to roll its savepoint back."""+class _RefusedError(ValueError):+ """A verb's own refusal of one id, carrying the error code to report."""++ def __init__(self, error: str, message: str) -> None:+ super().__init__(message)+ self.error = error+++async def _refuse_if_governing(session, rec) -> None:+ """Refuse to accept a decision that already governs; ``reaffirm`` renews one.++ A withdrawn decision is let through: accepting it again is how it returns.+ """+ from repowise.core.analysis.decisions.lifecycle import HISTORY_CURRENCIES+ from repowise.core.persistence.crud.authority import current_currency++ currency = await current_currency(session, rec)+ if currency is not None and currency not in HISTORY_CURRENCIES:+ raise _RefusedError(+ "already_accepted",+ f"already a decision ({currency}); renew it with "+ f"`repowise decision reaffirm {rec.id[:8]}`",+ )++#: A decision id, or a prefix of one, as ``_resolve_decision_id`` accepts it._ID_SHAPED = re.compile(r"[0-9a-fA-F]{4,64}\Z")@@ -191,11 +217,12 @@ async def _apply_in_savepoint(entry = {"given": token, "id": rec.id, "title": rec.title}try:async with session.begin_nested():- await apply_one(session, rec)+ # A verb may add fields to its outcome, e.g. where a merge went.+ extra = await apply_one(session, rec) or {}if preview:- raise _PreviewRollbackError- except _PreviewRollbackError:- return {**entry, "ok": True, "action": f"would_{verb}"}+ raise _PreviewRollbackError(extra)+ except _PreviewRollbackError as stop:+ return {**entry, "ok": True, "action": f"would_{verb}", **stop.args[0]}except AcceptanceRefusedError as exc:return {**entry,@@ -204,14 +231,28 @@ async def _apply_in_savepoint("message": str(exc),"blockers": list(exc.blockers),}- return {**entry, "ok": True, "action": action, "status": rec.status}+ except ValueError as exc:+ # The verb's own refusal, e.g. a merge target that is not a decision.+ # A corrupt stored JSON column is a fault, not a refusal.+ if isinstance(exc, json.JSONDecodeError):+ raise+ error = exc.error if isinstance(exc, _RefusedError) else f"{verb}_refused"+ return {**entry, "ok": False, "error": error, "message": str(exc)}+ return {**entry, "ok": True, "action": action, "status": rec.status, **extra}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."""+ """Report a run, exiting non-zero when any id was refused.++ Every ``--format json`` review run lands here, one id or many, so an+ agent parses one shape. *remedy* names the contract's flags, so it is+ shown only when the contract refused something.+ """failed = [r for r in results if not r["ok"]]+ if not any("blockers" in r for r in failed):+ remedy = ""if fmt == "json":emit_json({@@ -248,11 +289,11 @@ def _print_batch(def _emit_single(result: dict, token: str, verb: str, fmt: str, note: str, remedy: str) -> None:- """Report a one-id run: the transition, or the refusal naming that id."""+ """Report a one-id run to a person: the transition, or the refusal naming that id.++ ``--format json`` goes through :func:`_emit_batch` instead, for one shape.+ """if result["ok"]:- if fmt == "json":- emit_json({"id": result["id"], "status": result["status"], "action": result["action"]})- returnconsole.print(f"[green]Decision {result['id'][:8]} {result['action']}[/green]"+ (f" {note}" if note else "")@@ -316,6 +357,16 @@ def _check_session_flag(agent_session: str, agent: str) -> None:raise click.ClickException(f"--session is at most {ACCEPTER_SESSION_MAX} characters.")+def _preview_option(command):+ """``--preview``: run the write, report each id's outcome, roll it back."""+ return click.option(+ "--preview",+ is_flag=True,+ default=False,+ help="Report what each id would do, and write nothing.",+ )(command)++#: 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):diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.pyindex 69cf616ec..eec004247 100644--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py@@ -15,7 +15,6 @@ from rich.table import Tablefrom repowise.cli.commands import _tool_adapters as _tafrom repowise.cli.commands.decision_batch import (_emit_batch,- _emit_lifecycle,_emit_single,_open_store,_require_ids,@@ -51,7 +50,9 @@ def _resolve_decision_repo(path: str | None, fmt: str = "table", *, needs_store:"""Resolve the repo path for decision subcommands.Honors workspace auto-detection: in workspace mode without an explicit- path, targets the primary repo and prints a transparency notice.+ path, targets the primary repo and, in human output, prints a one-line+ notice saying so. JSON callers get none: they are agents calling run+ after run, for whom a repeated stderr line is only noise.With ``needs_store`` (the default) the returned path is the checkout whoseindex the command should read and write; see :func:`_checkout_with_index`.@@ -59,7 +60,10 @@ def _resolve_decision_repo(path: str | None, fmt: str = "table", *, needs_store:"""target = resolve_command_target(path=path)- repo_path = target.narrow(notice_console(fmt), command="decision", repo_option=False)+ if fmt == "json":+ repo_path = target.single_repo_path()+ else:+ repo_path = target.narrow(notice_console(fmt), command="decision", repo_option=False)return _checkout_with_index(repo_path, fmt) if needs_store else repo_path@@ -123,6 +127,17 @@ def _load_policy(repo_path: Path):@click.group("decision")def decision_group() -> None:"""Manage architectural decision records."""+ # Unconfigured, structlog prints every level to stdout, so a routine core+ # debug line (a git timeout while dating a record) landed in `decision show`.+ # Scoped to this group: doing it at the CLI root would make light commands+ # like `expand` import structlog. Warnings still print; --format json+ # silences further through format_option.+ import logging++ structlog.configure(+ wrapper_class=structlog.make_filtering_bound_logger(logging.WARNING),+ cache_logger_on_first_use=False,+ )def _register_config_commands() -> None:@@ -148,6 +163,7 @@ def _register_config_commands() -> None:import_command,merge_command,migrate_command,+ reaffirm_command,split_command,status_command,)@@ -155,6 +171,7 @@ def _register_config_commands() -> None:for command in (migrate_command,candidates_command,+ reaffirm_command,merge_command,dedupe_command,split_command,@@ -530,7 +547,12 @@ async def _embed_decision(default="all",)@click.option("--proposed", is_flag=True, default=False, help="Show only proposed decisions.")[email protected]("--stale-only", is_flag=True, default=False, help="Show only stale decisions.")+ "--stale-only",+ is_flag=True,+ default=False,+ help="Show only accepted decisions whose code has moved enough to need review.",+)@click.option("--limit",type=click.IntRange(min=1),@@ -557,12 +579,13 @@ def decision_list(repo_path,status=status if status != "all" else ("proposed" if proposed else None),source=source if source != "all" else None,+ stale_only=stale_only,))# Narrowed before the cut so --stale-only and the total cover every row,# not just the first page.- decisions = _narrow(decisions, proposed=proposed, stale_only=stale_only)+ decisions = _narrow(decisions, proposed=proposed)total = len(decisions)shown = decisions if show_all else decisions[:limit]@@ -590,12 +613,10 @@ def decision_list(console.print(f"[dim]{total} decisions.[/dim]")-def _narrow(decisions: list, *, proposed: bool, stale_only: bool) -> list:- """Apply ``--proposed`` and ``--stale-only`` to what the query returned."""+def _narrow(decisions: list, *, proposed: bool) -> list:+ """Apply ``--proposed`` to what the query returned."""if proposed:decisions = [d for d in decisions if d.status == "proposed"]- if stale_only:- decisions = [d for d in decisions if d.staleness_score >= 0.5]return decisions@@ -613,12 +634,19 @@ def _listed_json(d) -> dict:}-async def _query_decisions(repo_path: Path, *, status: str | None, source: str | None) -> list:- from repowise.core.persistence import get_session, list_decisions, upsert_repository+async def _query_decisions(+ repo_path: Path, *, status: str | None, source: str | None, stale_only: bool = False+) -> list:+ from repowise.core.persistence import (+ get_session,+ get_stale_decisions,+ list_decisions,+ upsert_repository,+ )async with _open_store(repo_path) as sf, get_session(sf) as session:repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))- return await list_decisions(+ rows = await list_decisions(session,repo.id,status=status,@@ -628,6 +656,8 @@ async def _query_decisions(repo_path: Path, *, status: str | None, source: str |# page. Fine at a few thousand records; a COUNT query is the upgrade.limit=None,)+ # Stale means what `decision health` counts, so the two agree.+ return await get_stale_decisions(session, repo.id, rows) if stale_only else rows_STATUS_COLORS = {@@ -679,7 +709,7 @@ def _print_decision_table(decisions: list) -> None:def decision_show(decision_id: str, path: str | None, fmt: str) -> None:"""Show full details of a decision record."""repo_path = _resolve_decision_repo(path, fmt)- rec, signed = run_async(_load_decision(repo_path, decision_id))+ rec, signed, accepted_at = run_async(_load_decision(repo_path, decision_id))if rec is None:notice_console(fmt).print(f"[red]Decision not found: {decision_id}[/red]")if fmt == "json":@@ -695,6 +725,7 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:created_at=rec.created_at,nodes=json.loads(rec.affected_files_json or "[]"),evidence_commits=json.loads(rec.evidence_commits_json or "[]"),+ accepted_at=accepted_at,)if fmt == "json":emit_json({"query": decision_id, "decision": _decision_json(rec, signed, currency)})@@ -704,15 +735,43 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:async def _load_decision(repo_path: Path, decision_id: str):- """The record *decision_id* names and its signature, or ``(None, None)``."""+ """The record *decision_id* names, its signature and its last grant time.++ ``(None, None, None)`` when nothing resolves.+ """from repowise.core.persistence import get_decision, get_sessionfrom repowise.core.persistence.crud.authority import latest_acceptance+ from repowise.core.persistence.crud.decision_staleness import latest_grant_times+ from repowise.core.persistence.models import DecisionCandidateMetaasync with _open_store(repo_path) as sf, 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 Noneacceptance = await latest_acceptance(session, rec.id) if rec else None- return rec, _describe_signature(acceptance)+ signed = _describe_signature(acceptance)+ if rec is not None and signed is None:+ # A candidate's dismissal is signed on its review row, not the log.+ signed = _describe_review(rec, await session.get(DecisionCandidateMeta, rec.id))+ if rec is None:+ return None, None, None+ grants = await latest_grant_times(session, rec.repository_id, [rec.id])+ return rec, signed, grants.get(rec.id)+++def _describe_review(rec, meta) -> dict[str, str] | None:+ """Who dismissed or deprecated a candidate, shaped like :func:`_describe_signature`."""+ if meta is None or not meta.dismissed_by or rec.status not in ("dismissed", "deprecated"):+ return None+ kind = meta.dismissed_by_kind or "unrecorded"+ session_id = meta.dismissed_session or ""+ return {+ "label": f"{meta.dismissed_by} ({kind})" + (f", session {session_id}" if session_id else ""),+ "verb": rec.status.capitalize(),+ "accepter": meta.dismissed_by,+ "kind": kind,+ "session": session_id,+ "action": rec.status,+ }def _decision_json(rec, signed, currency) -> dict:@@ -860,8 +919,10 @@ def decision_confirm(granted = _load_policy(repo_path).agent_acceptance if agent else Falseasync def _accept(session, rec) -> None:+ from repowise.cli.commands.decision_batch import _refuse_if_governingfrom repowise.core.persistence.crud.authority import accept_decision+ await _refuse_if_governing(session, rec)await accept_decision(session,rec,@@ -885,7 +946,7 @@ def decision_confirm(remedy = _ACCEPT_REMEDYif agent and not granted:remedy = f"{AGENT_ACCEPTANCE_REMEDY} {remedy}"- if len(ids) > 1 or preview:+ if len(ids) > 1 or preview or fmt == "json":_emit_batch(results, "accepted", "accept", preview, fmt, remedy)return_emit_single(results[0], ids[0], "accept", fmt, "(governing)", remedy)@@ -939,7 +1000,7 @@ def decision_dismiss(repo_path, ids, action="dismissed", verb="dismiss", preview=preview, apply_one=_dismiss))- if len(ids) > 1 or preview:+ if len(ids) > 1 or preview or fmt == "json":_emit_batch(results, "dismissed", "dismiss", preview, fmt)return_emit_single(@@ -973,14 +1034,20 @@ def _dismissal_confirmed(ids: list[str], *, yes: bool, preview: bool, fmt: str)@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.")[email protected]("--reason", default="", help="Why it was retired.")@_signing_options+ "--preview", is_flag=True, default=False, help="Report what it would do, and write nothing."+)@format_option()def decision_deprecate(decision_id: str,path: str | None,superseded_by: str | None,+ reason: str,agent: str,agent_session: str,+ preview: bool,fmt: str,) -> None:"""Retire a decision, optionally naming the one that replaces it.@@ -989,39 +1056,40 @@ def decision_deprecate(retired id resolving to its successor. Similarity never does either: an edgeexists because somebody named the successor."""+ from repowise.cli.commands.decision_batch import _RefusedError+repo_path = _resolve_decision_repo(path, fmt)signer = _signer(agent, agent_session)- async def _update():- from repowise.core.persistence import get_session- from repowise.core.persistence.models import DecisionRecord-- async with _open_store(repo_path) as sf, get_session(sf) as session:- full_id = await _resolve_decision_id(session, decision_id)- rec = await session.get(DecisionRecord, full_id) if full_id else None- if rec is None:- return None- successor = (- await _resolve_decision_id(session, superseded_by) if superseded_by else None- )- if superseded_by and successor is None:- emit_refusal(- "decision_not_found",- f"Unknown successor: {superseded_by}",- fmt,- decision_id=superseded_by,- )- await _retire(session, rec, successor, signer=signer, repo_path=repo_path, fmt=fmt)- return rec+ async def _deprecate(session, rec) -> None:+ successor = await _resolve_decision_id(session, superseded_by) if superseded_by else None+ if superseded_by and successor is None:+ raise _RefusedError("decision_not_found", f"Unknown successor: {superseded_by}")+ await _retire(session, rec, successor, signer=signer, repo_path=repo_path, reason=reason)- _emit_lifecycle(run_async(_update()), decision_id, "deprecated", fmt)+ results = run_async(+ _review_batch(+ repo_path,+ [decision_id],+ action="deprecated",+ verb="deprecate",+ preview=preview,+ apply_one=_deprecate,+ )+ )+ if preview or fmt == "json":+ _emit_batch(results, "deprecated", "deprecate", preview, fmt)+ return+ _emit_single(results[0], decision_id, "deprecate", fmt, "", "")-async def _retire(session, rec, successor, *, signer: _Signer, repo_path: Path, fmt: str) -> None:+async def _retire(+ session, rec, successor, *, signer: _Signer, repo_path: Path, reason: str+) -> None:"""Supersede an accepted record, or mark any other one deprecated."""- from repowise.core.persistence import update_decision_status+ from repowise.cli.commands.decision_batch import _RefusedErrorfrom repowise.core.persistence.crud.authority import (- AcceptanceRefusedError,+ deprecate_decision,is_accepted,supersede_decision,)@@ -1035,20 +1103,23 @@ async def _retire(session, rec, successor, *, signer: _Signer, repo_path: Path,accepter=signer.name(repo_path),kind=signer.kind,accepter_session=signer.session,+ note=reason,)- except (AcceptanceRefusedError, ValueError) as exc:- emit_refusal("supersede_refused", str(exc), fmt, decision_id=rec.id)+ except ValueError as exc:+ raise _RefusedError("supersede_refused", str(exc)) from excreturn- # A candidate has no authority to retire: a plain status change. An- # accepted record reaching here still logs a withdrawal, with its kind.- await update_decision_status(+ # An accepted record logs the withdrawal as ``deprecated``; a candidate,+ # which has no authority to withdraw, only moves status.+ await deprecate_decision(session,- rec.id,- "deprecated",- superseded_by=successor,+ rec,+ reason=reason,accepter=signer.name(repo_path),kind=signer.kind,+ accepter_session=signer.session,)+ if successor:+ rec.superseded_by = successor# ---------------------------------------------------------------------------diff --git a/packages/cli/src/repowise/cli/commands/decision_review_cmd.py b/packages/cli/src/repowise/cli/commands/decision_review_cmd.pyindex 9c99de038..eb771baa7 100644--- a/packages/cli/src/repowise/cli/commands/decision_review_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_review_cmd.py@@ -10,9 +10,21 @@ from __future__ import annotationsimport clickfrom rich.table import Table-from repowise.cli.commands.decision_batch import _signer, _signing_options+from repowise.cli.commands.decision_batch import (+ _emit_batch,+ _emit_single,+ _preview_option,+ _RefusedError,+ _require_ids,+ _resolve_decision_id,+ _review_batch,+ _signer,+ _signing_options,+ _split_ids_and_path,+)from repowise.cli.helpers import console, get_db_url_for_repo, run_asyncfrom repowise.cli.output import emit_json, emit_refusal, format_option, notice_console+from repowise.core.analysis.decisions.lifecycle import AGENT_ACCEPTANCE_REMEDY__all__ = ["candidates_command",@@ -21,6 +33,7 @@ __all__ = ["import_command","merge_command","migrate_command",+ "reaffirm_command","split_command","status_command",]@@ -162,6 +175,7 @@ def candidates_command("needs_split": bool(meta.needs_split) if meta else False,"lane": meta.lane if meta else "","blockers": record_blockers(rec),+ "reviewed_by": _review_signature(meta),}for rec, meta in rows]@@ -196,8 +210,20 @@ def candidates_command()+def _review_signature(meta) -> dict | None:+ """Who dismissed the candidate or asked for a split, and why. ``None`` if unrecorded."""+ if meta is None or not meta.dismissed_by:+ return None+ return {+ "accepter": meta.dismissed_by,+ "kind": meta.dismissed_by_kind or "unrecorded",+ "session": meta.dismissed_session or "",+ "reason": meta.dismissed_reason,+ }++# ----------------------------------------------------------------------------# decision merge / split+# decision merge / reaffirm / split# ---------------------------------------------------------------------------@@ -206,65 +232,126 @@ def candidates_command(@click.argument("into_id")@click.argument("path", required=False, default=None)@_signing_options+@_preview_option@format_option()def merge_command(- decision_id: str, into_id: str, path: str | None, agent: str, agent_session: str, fmt: str+ decision_id: str,+ into_id: str,+ path: str | None,+ agent: str,+ agent_session: str,+ preview: bool,+ fmt: str,) -> None:"""Fold a candidate into an existing decision instead of accepting a duplicate.- ``--agent`` signs the merge as that agent, like ``decision confirm``.+ INTO_ID must already be an accepted decision: merging into a candidate is+ refused. Accept the target first with ``repowise decision confirm+ INTO_ID``, or merge the other way. ``--agent`` signs the merge as that+ agent, like ``decision confirm``."""- from repowise.cli.commands.decision_cmd import (- _load_policy,- _resolve_decision_id,- _resolve_decision_repo,- )+ from repowise.cli.commands.decision_cmd import _load_policy, _resolve_decision_reposigner = _signer(agent, agent_session)repo_path = _resolve_decision_repo(path, fmt)granted = _load_policy(repo_path).agent_acceptance if agent else False- async def _run():- from repowise.core.persistence import get_session+ async def _merge(session, rec) -> dict:from repowise.core.persistence.crud.authority import merge_candidate- from repowise.core.persistence.models import DecisionRecord- engine, sf = await _open(repo_path)- try:- async with get_session(sf) as session:- src = await _resolve_decision_id(session, decision_id)- dst = await _resolve_decision_id(session, into_id)- if src is None:- emit_refusal("decision_not_found", f"Decision not found: {decision_id}", fmt)- if dst is None:- emit_refusal("decision_not_found", f"Decision not found: {into_id}", fmt)- rec = await session.get(DecisionRecord, src)- try:- await merge_candidate(- session,- rec,- into_id=dst,- accepter=signer.name(repo_path),- kind=signer.kind,- accepter_session=signer.session,- agent_acceptance=granted,- )- except ValueError as exc:- emit_refusal("merge_refused", str(exc), fmt, decision_id=src)- return {"id": src, "merged_into": dst}- finally:- await engine.dispose()+ target = await _resolve_decision_id(session, into_id)+ if target is None:+ raise _RefusedError("decision_not_found", f"Decision not found: {into_id}")+ await merge_candidate(+ session,+ rec,+ into_id=target,+ accepter=signer.name(repo_path),+ kind=signer.kind,+ accepter_session=signer.session,+ agent_acceptance=granted,+ )+ return {"merged_into": target}- result = run_async(_run())- if fmt == "json":- emit_json(result)+ results = run_async(+ _review_batch(+ repo_path, [decision_id], action="merged", verb="merge", preview=preview,+ apply_one=_merge,+ )+ )+ remedy = AGENT_ACCEPTANCE_REMEDY if agent and not granted else ""+ if preview or fmt == "json":+ _emit_batch(results, "merged", "merge", preview, fmt, remedy)return- console.print(- f"[green]Candidate {result['id'][:8]} merged into "- f"{result['merged_into'][:8]}[/green] [dim](the old id still resolves)[/dim]"+ _emit_single(+ results[0], decision_id, "merge", fmt,+ f"into {into_id} [dim](the old id still resolves)[/dim]", remedy,)[email protected]("reaffirm")[email protected]("decision_ids", nargs=-1)[email protected]("--reason", default="", help="Why it still holds. Defaults to its rationale.")+ "--evidence",+ multiple=True,+ help="Commit, file or link the review rests on. Repeatable. Defaults to its evidence.",+)+@_signing_options+@_preview_option+@format_option()+def reaffirm_command(+ decision_ids: tuple[str, ...],+ reason: str,+ evidence: tuple[str, ...],+ agent: str,+ agent_session: str,+ preview: bool,+ fmt: str,+) -> None:+ """Re-accept decisions after review, so they govern as active again.++ For a decision marked needs_review because its code moved: read it, then+ reaffirm it if it still holds. Takes one id or many, and an optional+ repository path after them. A candidate is refused (accept it with+ ``confirm``), and so is a withdrawn decision (accept it again with+ ``confirm``). ``--agent`` signs as that agent, like ``decision confirm``.+ """+ from repowise.cli.commands.decision_cmd import _load_policy, _resolve_decision_repo++ ids, path = _split_ids_and_path(decision_ids)+ _require_ids(ids, "reaffirm", fmt)+ repo_path = _resolve_decision_repo(path, fmt)+ signer = _signer(agent, agent_session)+ granted = _load_policy(repo_path).agent_acceptance if agent else False++ async def _reaffirm(session, rec) -> None:+ from repowise.core.persistence.crud.authority import reaffirm_decision++ await reaffirm_decision(+ session,+ rec,+ accepter=signer.name(repo_path),+ kind=signer.kind,+ accepter_session=signer.session,+ agent_acceptance=granted,+ reason=reason,+ evidence=list(evidence) or None,+ )++ results = run_async(+ _review_batch(+ repo_path, ids, action="reaffirmed", verb="reaffirm", preview=preview,+ apply_one=_reaffirm,+ )+ )+ remedy = AGENT_ACCEPTANCE_REMEDY if agent and not granted else ""+ if len(ids) > 1 or preview or fmt == "json":+ _emit_batch(results, "reaffirmed", "reaffirm", preview, fmt, remedy)+ return+ _emit_single(results[0], ids[0], "reaffirm", fmt, "(governing)", remedy)++# ---------------------------------------------------------------------------# decision dedupe# ---------------------------------------------------------------------------@@ -383,12 +470,16 @@ def dedupe_command(@click.argument("decision_id")@click.argument("path", required=False, default=None)@click.option("--reason", default="", help="What the two choices are.")+@_signing_options@format_option()-def split_command(decision_id: str, path: str | None, reason: str, fmt: str) -> None:+def split_command(+ decision_id: str, path: str | None, reason: str, agent: str, agent_session: str, fmt: str+) -> None:"""Flag a candidate as bundling two choices. Never splits it for you."""- from repowise.cli.commands.decision_cmd import _resolve_decision_id, _resolve_decision_repo+ from repowise.cli.commands.decision_cmd import _resolve_decision_reporepo_path = _resolve_decision_repo(path, fmt)+ signer = _signer(agent, agent_session)async def _run():from repowise.core.persistence import get_session@@ -402,7 +493,14 @@ def split_command(decision_id: str, path: str | None, reason: str, fmt: str) ->if full_id is None:emit_refusal("decision_not_found", f"Decision not found: {decision_id}", fmt)rec = await session.get(DecisionRecord, full_id)- await request_split(session, rec, reason=reason)+ await request_split(+ session,+ rec,+ reason=reason,+ accepter=signer.name(repo_path),+ kind=signer.kind,+ accepter_session=signer.session,+ )return {"id": full_id, "review_state": "needs_split"}finally:await engine.dispose()diff --git a/packages/core/alembic/versions/0118_candidate_meta_dismissed_by.py b/packages/core/alembic/versions/0118_candidate_meta_dismissed_by.pynew file mode 100644index 000000000..f833047e6--- /dev/null+++ b/packages/core/alembic/versions/0118_candidate_meta_dismissed_by.py@@ -0,0 +1,55 @@+"""Record who dismissed a candidate, or asked for it to be split.++``decision_candidate_meta.dismissed_by``, ``dismissed_by_kind`` and+``dismissed_session`` sign ``dismissed_reason`` the way an acceptance row is+signed. On the candidate's review row, because an acceptance row would make a+never-accepted candidate a decision. Nullable: null means "not recorded".++Local SQLite stores never run Alembic -- ``init_db``'s reconciler issues+additive DDL for missing columns -- so this migration exists for managed+Postgres.++Revision ID: 0118+Revises: 0117+Create Date: 2026-10-25+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0118"+down_revision: str | None = "0117"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_TABLE = "decision_candidate_meta"+_COLUMNS = (+ ("dismissed_by", sa.Text()),+ ("dismissed_by_kind", sa.String(16)),+ ("dismissed_session", sa.String(64)),+)+++def _columns() -> set[str]:+ inspector = sa.inspect(op.get_bind())+ return {c["name"] for c in inspector.get_columns(_TABLE)}+++def upgrade() -> None:+ # Guarded: ``init_db``'s reconciler may already have added them on Postgres.+ existing = _columns()+ for name, type_ in _COLUMNS:+ if name not in existing:+ op.add_column(_TABLE, sa.Column(name, type_, nullable=True))+++def downgrade() -> None:+ existing = _columns()+ for name, _type in reversed(_COLUMNS):+ if name in existing:+ op.drop_column(_TABLE, name)diff --git a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.pyindex 4824894d4..176bed53f 100644--- a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py+++ b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py@@ -307,7 +307,7 @@ def stale_decision(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:severity="medium",# The evidence is commits to its files, not a broken rule, so the# row asks for a review and claims nothing more.- title=f"Review the decision “{d.title}”: the files it governs changed since it was recorded",+ title=f"Review the decision “{d.title}”: the files it governs changed since it was recorded or last accepted",impact="Agents and reviewers still follow it, and nobody has checked it against those changes.",why=(WhyFact("status", "Accepted, its files changed since"),),target_kind="decision",diff --git a/packages/core/src/repowise/core/analysis/decisions/landing.py b/packages/core/src/repowise/core/analysis/decisions/landing.pyindex c02a849ef..62f3a6cb1 100644--- a/packages/core/src/repowise/core/analysis/decisions/landing.py+++ b/packages/core/src/repowise/core/analysis/decisions/landing.py@@ -69,8 +69,9 @@ def evidence_landings(try:own = _commits(repo_path, wanted, timeout)line = _first_parent(repo_path, min(c.at for c in own.values()), timeout) if own else {}- except (OSError, subprocess.SubprocessError):- logger.debug("decision_landing_unreadable", exc_info=True)+ except (OSError, subprocess.SubprocessError) as exc:+ # One line: a git timeout here is routine on a large history, not a crash.+ logger.debug("decision_landing_unreadable", error=f"{type(exc).__name__}: {exc}")return {}names = _names(line)out: dict[str, Landing] = {}diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.pyindex 8e7db5aa8..fd791775f 100644--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py@@ -175,9 +175,12 @@ ACCEPTANCE_ACTIONS: tuple[str, ...] = ("superseded","dismissed","returned_to_review",+ # A withdrawal like ``dismissed``, stored at the same currency; the action+ # is what tells a retired decision from a rejected one.+ "deprecated",)-#: Actions that create or renew authority, against the three that withdraw it.+#: Actions that create or renew authority, against the ones that withdraw it.GRANTING_ACTIONS: frozenset[str] = frozenset({"accepted", "reaffirmed", "merged"})#: Who signed an acceptance. ``person`` is a human, ``agent`` a coding agentdiff --git a/packages/core/src/repowise/core/analysis/decisions/prompts.py b/packages/core/src/repowise/core/analysis/decisions/prompts.pyindex 5c298d34c..22b746a4f 100644--- a/packages/core/src/repowise/core/analysis/decisions/prompts.py+++ b/packages/core/src/repowise/core/analysis/decisions/prompts.py@@ -6,14 +6,14 @@ Extracted from the former decision_extractor.py; imported back intofrom __future__ import annotations-# Every lane behind the substring gate asks for ``decision`` as a verbatim-# quote: the gate drops any field the source does not contain, so a reworded-# decision is stored blank.+# Every lane behind the substring gate asks for ``decision`` and ``rationale``+# as verbatim quotes: the gate drops any field the source does not contain, so+# a reworded decision or reason is stored blank._SYSTEM_PROMPT = ("You are an architectural decision extractor. ""You extract structured decision records from code context. ""Return only valid JSON. Never invent rationale not present in the source. "- "Copy the decision field word for word from the source; never reword it."+ "Copy the decision and rationale fields word for word from the source; never reword them.")INLINE_MARKER_PROMPT = """\@@ -30,7 +30,7 @@ For each marker, return a JSON object:"title": "short title of the decision","context": "what situation forced this","decision": "the words from the marker that state what was chosen, copied verbatim",- "rationale": "why",+ "rationale": "the words from the marker that state why, copied verbatim, or empty if none","alternatives": ["rejected alternatives if mentioned"],"consequences": ["tradeoffs if mentioned"],"tags": ["relevant tags from: auth, database, api, performance, security, infra, testing"]@@ -75,7 +75,7 @@ system structure, patterns, migrations, or technology), return a JSON object:"title": "short title","context": "what situation forced this","decision": "the sentence or clause from the commit message that states what was chosen, copied verbatim",- "rationale": "why this approach (infer from message and files only)",+ "rationale": "the sentence or clause from the commit message that states why, copied verbatim, or empty if none","affected_files": ["which of that commit's files this decision is about"],"alternatives": [],"consequences": [],@@ -109,7 +109,7 @@ Return a JSON array of decisions:"title": "short title","context": "situation that forced it","decision": "the sentence or clause from the document that states what was chosen, copied verbatim",- "rationale": "why",+ "rationale": "the sentence or clause from the document that states why, copied verbatim, or empty if none","alternatives": [],"consequences": [],"tags": [],@@ -133,7 +133,7 @@ For each decision return a JSON object:"title": "short title","context": "what situation forced this (only if stated)","decision": "the sentence or clause from the body that states what was chosen, copied verbatim",- "rationale": "why (quote/paraphrase the body — never invent)",+ "rationale": "the sentence or clause from the body that states why, copied verbatim, or empty if none","affected_files": ["which of that commit's files this decision is about"],"alternatives": ["rejected alternatives if mentioned"],"consequences": [],@@ -162,7 +162,7 @@ For each decision return a JSON object:"title": "short title","context": "what situation forced this (only if stated)","decision": "the sentence or clause from the comment that states what was chosen, copied verbatim",- "rationale": "why (quote/paraphrase the comment — never invent)",+ "rationale": "the sentence or clause from the comment that states why, copied verbatim, or empty if none","alternatives": [],"consequences": [],"tags": [],diff --git a/packages/core/src/repowise/core/analysis/decisions/staleness.py b/packages/core/src/repowise/core/analysis/decisions/staleness.pyindex 095779371..a26f931e9 100644--- a/packages/core/src/repowise/core/analysis/decisions/staleness.py+++ b/packages/core/src/repowise/core/analysis/decisions/staleness.py@@ -1,4 +1,4 @@-"""How far the code a decision governs has moved since the decision was recorded."""+"""How far the code a decision governs has moved since the decision was made."""from __future__ import annotations@@ -34,6 +34,7 @@ def compute_staleness(git_meta_map: dict[str, dict],decision_text: str = "",landed_at: datetime | None = None,+ accepted_at: datetime | str | None = None,) -> float:"""Fraction of *affected_files* that have changed since the record's birth.@@ -47,6 +48,10 @@ def compute_staleness(the squash that carries it, so the birth is the later of the two: thelanding commit is the decision, not a change to it.+ *accepted_at* is the latest time a person or agent granted or renewed+ the decision. They read the code as it stood then, so a change before+ that is reviewed, not drift: the birth is the latest of all three.+A file with no git metadata **after** the caller's gap fill counts aschanged: the record names something the repository does not track, soit cannot be shown to still hold.@@ -57,7 +62,7 @@ def compute_staleness(# `decision health` reports it as unscoped rather than fresh.return 0.0- created = _anchor(decision_created_at, landed_at)+ created = _anchor(decision_created_at, landed_at, accepted_at)changed = 0for fp in affected_files:meta = git_meta_map.get(fp)@@ -73,12 +78,17 @@ def compute_staleness(return round(changed / len(affected_files), 3)-def _anchor(created_at: datetime | str | None, landed_at: datetime | None) -> datetime | None:- """The later of a record's birth and its landing, or None with no birth."""+def _anchor(+ created_at: datetime | str | None,+ landed_at: datetime | None,+ accepted_at: datetime | str | None = None,+) -> datetime | None:+ """The latest of a record's birth, landing and acceptance, or None with no birth."""if not created_at:return None- created = _as_aware_utc(_coerce_dt(created_at))- return max(created, _as_aware_utc(landed_at)) if landed_at is not None else created+ return max(+ _as_aware_utc(_coerce_dt(when)) for when in (created_at, landed_at, accepted_at) if when+ )def last_code_change(diff --git a/packages/core/src/repowise/core/analysis/decisions/status.py b/packages/core/src/repowise/core/analysis/decisions/status.pyindex 2e8f0a13c..b2cfc4608 100644--- a/packages/core/src/repowise/core/analysis/decisions/status.py+++ b/packages/core/src/repowise/core/analysis/decisions/status.py@@ -18,6 +18,7 @@ from typing import Anyfrom sqlalchemy import func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.decisions.lifecycle import RETIRED_STATUSESfrom repowise.core.persistence.crud.authority import (accepted_decision_ids,candidate_predicate,@@ -73,7 +74,7 @@ async def _per_source() -> dict[str, dict[str, Any]]:"""Records, accepted count and newest capture per stored source value.- Tombstoned candidates are excluded, because ``count_decisions_by_lane``+ Retired candidates are excluded, because ``count_decisions_by_lane``excludes them: counting them here would make the Sources column sum tomore than the total beside it."""@@ -81,7 +82,10 @@ async def _per_source(await session.execute(select(DecisionRecord.id, DecisionRecord.source, DecisionRecord.created_at).where(DecisionRecord.repository_id == repository_id,- or_(DecisionRecord.status != "dismissed", DecisionRecord.id.in_(accepted)),+ or_(+ DecisionRecord.status.notin_(sorted(RETIRED_STATUSES)),+ DecisionRecord.id.in_(accepted),+ ),))).all()diff --git a/packages/core/src/repowise/core/events/snapshot.py b/packages/core/src/repowise/core/events/snapshot.pyindex 01f86cfc2..50f839296 100644--- a/packages/core/src/repowise/core/events/snapshot.py+++ b/packages/core/src/repowise/core/events/snapshot.py@@ -31,9 +31,6 @@ logger = logging.getLogger(__name__)SNAPSHOT_FACTS_VERSION = 1#: Window for "recent" activity, back from the newest indexed commit.RECENT_DAYS = 90-#: A governing decision at or above this staleness counts as stale-#: (the threshold ``get_stale_decisions`` uses).-STALE_THRESHOLD = 0.5#: Ceiling on ``(file, commit)`` rows read for the recent window, newest first.#: Past it the window is partial and says so (``recent_capped``); the rules#: that read recent activity skip it. Upgrade path: aggregate per component in SQL.@@ -227,22 +224,25 @@ async def _recent_commit_files(session: Any, repository_id: str) -> list[dict[stasync def governing_decisions(session: Any, repository_id: str) -> tuple[dict[str, list[tuple[str, str]]], set[str]]:- """Governing ``(id, title)`` pairs per file, and the ids at or past :data:`STALE_THRESHOLD`."""+ """Governing ``(id, title)`` pairs per file, and the ids of those that are stale.++ Stale is ``get_stale_decisions``' meaning, the one ``decision health`` counts.+ """from repowise.core.persistence.crud.authority import governing_decisions_by_file+ from repowise.core.persistence.crud.decision_staleness import get_stale_decisionsfrom repowise.core.persistence.models import DecisionRecordgoverning = await governing_decisions_by_file(session, repository_id)ids = {d for pairs in governing.values() for d, _ in pairs}if not ids:return governing, set()- stale = await session.scalars(- select(DecisionRecord.id).where(+ records = await session.scalars(+ select(DecisionRecord).where(DecisionRecord.repository_id == repository_id,DecisionRecord.id.in_(sorted(ids)),- DecisionRecord.staleness_score >= STALE_THRESHOLD,))- return governing, set(stale)+ return governing, {d.id for d in await get_stale_decisions(session, repository_id, records)}def provided_contracts(repo_root: Path, head_commit: str | None) -> dict[str, dict[str, int]] | None:diff --git a/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py b/packages/core/src/repowise/core/persistence/_interfaces/_analysis.pyindex 3afefdf65..b65dc85f9 100644--- a/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py+++ b/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py@@ -151,9 +151,7 @@ class AnalysisIndexStore(ABC):) -> int: ...@abstractmethod- async def get_stale_decisions(- self, repository_id: str, threshold: float = 0.5- ) -> list[DecisionRecord]: ...+ async def get_stale_decisions(self, repository_id: str) -> list[DecisionRecord]: ...@abstractmethodasync def get_decision_health_summary(self, repository_id: str) -> dict: ...diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex ab03de1eb..495d5cba9 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -32,6 +32,7 @@ from repowise.core.analysis.decisions.lifecycle import (ACCEPTER_SESSION_MAX,HISTORY_CURRENCIES,NO_SCOPE_BLOCKER,+ RETIRED_STATUSES,STORED_CURRENCIES,AcceptanceRequirement,acceptance_blockers,@@ -78,6 +79,7 @@ __all__ = ["decision_currencies","decision_fields","decision_signatures",+ "deprecate_decision","dismiss_candidate","governing_decisions_by_file","is_accepted",@@ -134,12 +136,17 @@ def accepted_predicate() -> Any:def candidate_predicate() -> Any:"""A ``WHERE`` clause restricting a ``DecisionRecord`` query to candidates.- Never accepted, and not tombstoned. The second half is what keeps a- dismissed candidate out of a review queue while- :func:`count_decisions_by_lane` keeps it out of the totals, so the two- cannot report different backlogs off the same store.+ Never accepted, and not retired. The second half is what keeps a+ dismissed candidate, or one a later commit superseded, out of a review+ queue while :func:`count_decisions_by_lane` keeps it out of the totals, so+ the two cannot report different backlogs off the same store."""- return ~accepted_predicate() & (DecisionRecord.status != "dismissed")+ return ~accepted_predicate() & _not_retired()+++def _not_retired() -> Any:+ """``status`` is not one a retirement wrote (dismissed, deprecated, superseded)."""+ return DecisionRecord.status.notin_(sorted(RETIRED_STATUSES))#: The same predicate for the hook path, which opens the store with stdlib@@ -382,15 +389,11 @@ async def count_decisions_by_lane(await session.execute(select(DecisionRecord.id, *_CURRENCY_COLUMNS).where(DecisionRecord.repository_id == repository_id,- # Tombstoned candidates are excluded; a decision that was+ # Retired candidates are excluded; a decision that was# accepted and then withdrawn is not, because it is history- # the History lane promises. ``dismiss_candidate`` writes the- # same status for both, so the acceptance row is what tells- # them apart, and the loop below does that.- or_(- DecisionRecord.status != "dismissed",- accepted_predicate(),- ),+ # the History lane promises. Both carry the same statuses, so+ # the acceptance row is what tells them apart.+ or_(_not_retired(), accepted_predicate()),))).all()@@ -593,6 +596,14 @@ async def record_acceptance(accepter_session=accepter_session,note=note,)+ # A grant is a review of the code as it stands, so staleness counts from+ # now rather than waiting for the next index.+ from repowise.core.analysis.decisions.lifecycle import GRANTING_ACTIONS++ from .decision_staleness import rescore_decision_staleness++ if action in GRANTING_ACTIONS:+ await rescore_decision_staleness(session, record)# The legacy column is a projection of the acceptance, never its source.# Keeping it in step is what lets readers that predate the split stay@@ -728,14 +739,32 @@ async def reaffirm_decision(kind: str = "person",accepter_session: str = "",agent_acceptance: bool = False,+ reason: str = "",+ evidence: list[str] | None = None,note: str = "",) -> DecisionAcceptance:- """Re-accept a decision after review, clearing a ``needs_review`` state."""+ """Re-accept a decision after review, clearing a ``needs_review`` state.++ Only a governing decision can be reaffirmed. A candidate was never+ accepted, and a withdrawn one needs a fresh acceptance: both are refused,+ naming ``confirm``.+ """+ currency = await current_currency(session, record)+ if currency is None:+ raise AcceptanceRefusedError(+ ["a candidate, never accepted: accept it with `repowise decision confirm`"]+ )+ if currency in HISTORY_CURRENCIES:+ raise AcceptanceRefusedError(+ [f"withdrawn ({currency}): accept it again with `repowise decision confirm`"]+ )return await record_acceptance(session,record,action="reaffirmed",currency="active",+ reason=reason,+ evidence=evidence,accepter=accepter,artifact=artifact,kind=kind,@@ -847,7 +876,8 @@ async def merge_candidate(raise ValueError("A candidate cannot be merged into itself.")if not await is_accepted(session, target.id):raise ValueError(- f"Merge target {into_id!r} is a candidate; accept it before merging into it."+ f"Merge target {into_id[:8]} is a candidate, not a decision. Accept it first "+ f"with `repowise decision confirm {into_id[:8]}`, or merge the other way.")if await is_accepted(session, candidate.id):raise ValueError(@@ -938,6 +968,7 @@ async def dismiss_candidate("""meta = await _set_review_state(session, record, "dismissed")meta.dismissed_reason = reason+ _sign_review(meta, accepter, kind, accepter_session)if await latest_acceptance(session, record.id) is not None:await record_acceptance(session,@@ -961,15 +992,56 @@ async def request_split(record: DecisionRecord,*,reason: str = "",+ accepter: str = "",+ kind: str = "person",+ accepter_session: str = "",) -> DecisionCandidateMeta:"""Flag a candidate as bundling two choices. Never splits it by machine."""meta = await _set_review_state(session, record, "needs_split")meta.needs_split = Truemeta.dismissed_reason = reason+ _sign_review(meta, accepter, kind, accepter_session)await session.flush()return meta+async def deprecate_decision(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ reason: str = "",+ accepter: str = "",+ kind: str = "person",+ accepter_session: str = "",+) -> None:+ """Retire *record* with nothing named in its place.++ On a decision this withdraws authority and logs it as ``deprecated``, so+ the log tells a retirement from a dismissal. A candidate has no authority+ to withdraw: its status moves and its review row is signed.+ """+ if await is_accepted(session, record.id):+ # Sets the status to ``deprecated`` and moves the links.+ await record_acceptance(+ session,+ record,+ action="deprecated",+ currency="dismissed",+ accepter=accepter or "unrecorded",+ kind=kind,+ accepter_session=accepter_session,+ note=reason,+ )+ return+ meta = await _review_meta(session, record)+ meta.dismissed_reason = reason+ _sign_review(meta, accepter, kind, accepter_session)+ record.status = "deprecated"+ record.updated_at = _now_utc()+ await session.flush()+ await sync_links_from_record(session, record)++async def list_candidates(session: AsyncSession,repository_id: str,@@ -1000,11 +1072,13 @@ async def list_candidates()if review_state is not None:# A candidate with no meta row has never been reviewed, which is- # exactly what ``open`` means.+ # exactly what ``open`` means. A retired one is not open, whatever its+ # row says: a later commit can supersede a candidate nobody reviewed.if review_state == "open":q = q.where((DecisionCandidateMeta.review_state == "open")- | (DecisionCandidateMeta.decision_id.is_(None))+ | (DecisionCandidateMeta.decision_id.is_(None)),+ _not_retired(),)else:q = q.where(DecisionCandidateMeta.review_state == review_state)@@ -1032,12 +1106,7 @@ async def _set_review_state(*,merged_into: str | None = None,) -> DecisionCandidateMeta:- meta = await session.get(DecisionCandidateMeta, record.id)- if meta is None:- meta = DecisionCandidateMeta(- decision_id=record.id, repository_id=record.repository_id- )- session.add(meta)+ meta = await _review_meta(session, record)meta.review_state = stateif merged_into is not None:meta.merged_into = merged_into@@ -1046,6 +1115,24 @@ async def _set_review_state(return meta+async def _review_meta(session: AsyncSession, record: DecisionRecord) -> DecisionCandidateMeta:+ """*record*'s review row, created when it has none."""+ meta = await session.get(DecisionCandidateMeta, record.id)+ if meta is None:+ meta = DecisionCandidateMeta(+ decision_id=record.id, repository_id=record.repository_id, review_state="open"+ )+ session.add(meta)+ return meta+++def _sign_review(meta: DecisionCandidateMeta, accepter: str, kind: str, session_id: str) -> None:+ """Stamp who set ``dismissed_reason``, as an acceptance row would be signed."""+ meta.dismissed_by = accepter or None+ meta.dismissed_by_kind = kind or None+ meta.dismissed_session = session_id or None++async def _add_alias(session: AsyncSession, alias_id: str, decision_id: str, *, reason: str) -> None:diff --git a/packages/core/src/repowise/core/persistence/crud/decision_health.py b/packages/core/src/repowise/core/persistence/crud/decision_health.pyindex e2c503bf4..84845a926 100644--- a/packages/core/src/repowise/core/persistence/crud/decision_health.py+++ b/packages/core/src/repowise/core/persistence/crud/decision_health.py@@ -13,6 +13,7 @@ from repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.test_paths import is_test_related_pathfrom ..models import DecisionRecord, GitMetadata+from .decision_staleness import is_staleasync def get_decision_health_summary(@@ -117,12 +118,13 @@ class _Lanes:self.proposed.append(d)returnif currency in HISTORY_CURRENCIES:+ lane = _history_lane(d, currency)# ``stale`` counts apart: that key already means needs_review here.- self.counts["historical" if currency == "stale" else currency] += 1- self.retired.append((currency, d))+ self.counts["historical" if lane == "stale" else lane] += 1+ self.retired.append((lane, d))returnself.counts["active"] += 1- if currency == "needs_review":+ if is_stale(currency):self.counts["stale"] += 1self.stale.append(d)if currency == "uncheckable":@@ -147,6 +149,15 @@ class _Lanes:self.unscoped.sort(key=lambda d: (-(d.confidence or 0.0), d.id))+def _history_lane(d: DecisionRecord, currency: str) -> str:+ """The retired lane for a history *currency*.++ A deprecation and a dismissal share the ``dismissed`` currency; the status+ each one writes is what still tells them apart.+ """+ return "deprecated" if currency == "dismissed" and d.status == "deprecated" else currency++async def _ungoverned_hotspots(session: AsyncSession, repository_id: str, governed_files: set[str]) -> list[str]:diff --git a/packages/core/src/repowise/core/persistence/crud/decision_staleness.py b/packages/core/src/repowise/core/persistence/crud/decision_staleness.pyindex 5174e3483..431dc0ee5 100644--- a/packages/core/src/repowise/core/persistence/crud/decision_staleness.py+++ b/packages/core/src/repowise/core/persistence/crud/decision_staleness.py@@ -3,14 +3,15 @@from __future__ import annotationsimport json+from collections.abc import Iterablefrom datetime import datetimefrom pathlib import Path-from sqlalchemy import select+from sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom ..decision_graph import sync_links_from_record-from ..models import DecisionRecord, GitMetadata, _now_utc+from ..models import DecisionAcceptance, DecisionRecord, GitMetadata, _now_utcasync def _fill_git_meta_gaps(@@ -64,6 +65,8 @@ async def recompute_decision_staleness(With *repo_path*, each record is scored from when its own evidence commitslanded, when that is after its birth; without it, from its birth alone.+ A later reviewed grant (see :func:`latest_grant_times`) moves the anchor+ to it either way.Also fills ``last_code_change`` from the same per-file dates the score iscounted from, and re-derives ``affected_modules_json`` from the files each@@ -109,6 +112,7 @@ async def recompute_decision_staleness()landings = _evidence_landings(repo_path, decisions, affected_by_id)+ grants = await latest_grant_times(session, repository_id)now = _now_utc()updated = 0dated = 0@@ -128,7 +132,7 @@ async def recompute_decision_staleness(if dec.source == "conventions":continue- if _rescore_staleness(dec, affected, git_meta_map, now, landings):+ if _rescore_staleness(dec, affected, git_meta_map, now, landings, grants.get(dec.id)):updated += 1if updated or modules_updated or dated:@@ -185,6 +189,7 @@ def _rescore_staleness(git_meta_map: dict[str, dict],now: datetime,landings: dict,+ accepted_at: datetime | None = None,) -> bool:"""Recompute the git-diff staleness score; True when it moved by more than 0.01."""from repowise.core.analysis.decisions.extractor import DecisionExtractor@@ -198,6 +203,7 @@ def _rescore_staleness(affected,git_meta_map,landed_at=landing.at if landing else None,+ accepted_at=accepted_at,)if abs(new_score - dec.staleness_score) > 0.01:dec.staleness_score = round(new_score, 3)@@ -233,17 +239,87 @@ def _backfill_module_nodes(return moved+#: Signers whose grant means someone read the code as it stood. An ``import``+#: row is stamped when a manifest, migration or tracked ADR is applied on this+#: machine, which says nothing about when the code was last reviewed.+_REVIEWING_KINDS = ("person", "agent")+++async def latest_grant_times(+ session: AsyncSession,+ repository_id: str,+ decision_ids: Iterable[str] | None = None,+) -> dict[str, datetime]:+ """When each decision was last accepted, reaffirmed or merged into, by id.++ Reviewed grants only (see :data:`_REVIEWING_KINDS`). Staleness counts+ from here when it is later than the record's birth and landing.+ """+ from repowise.core.analysis.decisions.lifecycle import GRANTING_ACTIONS++ q = (+ select(DecisionAcceptance.decision_id, func.max(DecisionAcceptance.created_at))+ .where(+ DecisionAcceptance.repository_id == repository_id,+ DecisionAcceptance.action.in_(sorted(GRANTING_ACTIONS)),+ DecisionAcceptance.accepter_kind.in_(_REVIEWING_KINDS),+ )+ .group_by(DecisionAcceptance.decision_id)+ )+ if decision_ids is not None:+ q = q.where(DecisionAcceptance.decision_id.in_(sorted(set(decision_ids))))+ return dict((await session.execute(q)).all())+++async def rescore_decision_staleness(session: AsyncSession, record: DecisionRecord) -> None:+ """Rescore one record from persisted git metadata, anchored at its latest grant.++ Called right after a grant so ``needs_review`` clears without waiting for+ the next index. No evidence landing is read, since a grant just written is+ later than any landing, so a record with no reviewed grant is left to+ :func:`recompute_decision_staleness`, which reads landings.+ """+ affected = json.loads(record.affected_files_json or "[]")+ # Conventions write their own conformance share; see the batch path.+ if not affected or record.source == "conventions":+ return+ grants = await latest_grant_times(session, record.repository_id, [record.id])+ if record.id not in grants:+ return+ from repowise.core.analysis.decisions.staleness import compute_staleness++ git_meta = await _fill_git_meta_gaps(session, record.repository_id, {}, set(affected))+ score = compute_staleness(record.created_at, affected, git_meta, accepted_at=grants[record.id])+ # A later anchor only lowers the score. A rise means a file this store has+ # no metadata for yet, such as one added since the last index, which the+ # next index scores with the full picture.+ if score < (record.staleness_score or 0.0):+ record.staleness_score = score+ record.updated_at = _now_utc()+++def is_stale(currency: str | None) -> bool:+ """The one meaning of a stale decision: accepted, at effective ``needs_review``.++ *currency* is from ``decision_currencies``, where a candidate is ``None``.+ A candidate's staleness score is a fact about its files, not a decision+ going stale, so it never counts.+ """+ return currency == "needs_review"++async def get_stale_decisions(session: AsyncSession,repository_id: str,- threshold: float = 0.5,+ records: Iterable[DecisionRecord] | None = None,) -> list[DecisionRecord]:- """Return active decisions with staleness_score >= threshold."""- result = await session.execute(- select(DecisionRecord).where(- DecisionRecord.repository_id == repository_id,- DecisionRecord.status.in_(["active"]),- DecisionRecord.staleness_score >= threshold,+ """The decisions in *records* (default: the repository's) that :func:`is_stale`."""+ from .authority import decision_currencies++ if records is None:+ records = await session.scalars(+ select(DecisionRecord).where(DecisionRecord.repository_id == repository_id))- )- return list(result.scalars().all())+ records = list(records)+ currencies = await decision_currencies(session, repository_id, records)+ return [r for r in records if is_stale(currencies.get(r.id))]diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.pyindex 6855da02c..c3898dfde 100644--- a/packages/core/src/repowise/core/persistence/crud/decisions.py+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py@@ -337,6 +337,10 @@ async def list_decisions(if accepted is not None:predicate = accepted_predicate()q = q.where(predicate if accepted else ~predicate)+ if accepted is False and status is None and not include_dismissed:+ # Same candidate set ``count_decisions_by_lane`` counts: a retired+ # candidate is history, not something to review.+ q = q.where(DecisionRecord.status.notin_(sorted(RETIRED_STATUSES)))order = decision_priority_order(sort)if accepted is False and sort != "recent":# A candidates page is a review queue, so it leads with the rows the@@ -506,7 +510,9 @@ async def update_decision_status(await record_acceptance(session,rec,- action="superseded" if status == "superseded" else "dismissed",+ # ``deprecated`` and ``dismissed`` share a currency; the action+ # keeps which one happened.+ action=status,currency="superseded" if status == "superseded" else "dismissed",accepter=accepter or "unrecorded",kind=kind,diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex a090471db..49d6db29a 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -1472,6 +1472,7 @@ class DecisionAcceptance(Base):#: actions land in the same transaction, and the tie decides who governs.seq: Mapped[int] = mapped_column(Integer, nullable=False, default=1)#: accepted | reaffirmed | superseded | dismissed | returned_to_review | merged+ #: | deprecatedaction: Mapped[str] = mapped_column(String(24), nullable=False, default="accepted")currency: Mapped[str] = mapped_column(String(16), nullable=False, default="active")#: The rationale, or the explicit reason a constraint has none.@@ -1541,6 +1542,12 @@ class DecisionCandidateMeta(Base):#: Set when review folded this candidate into another record.merged_into: Mapped[str | None] = mapped_column(String(32), nullable=True)dismissed_reason: Mapped[str] = mapped_column(Text, nullable=False, default="")+ #: Who set ``dismissed_reason`` (a dismissal or a split request), signed+ #: like an acceptance row. Here, not in the acceptance log, because a row+ #: there would make the candidate a decision. Null predates the columns.+ dismissed_by: Mapped[str | None] = mapped_column(Text, nullable=True)+ dismissed_by_kind: Mapped[str | None] = mapped_column(String(16), nullable=True)+ dismissed_session: Mapped[str | None] = mapped_column(String(64), nullable=True)first_seen: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)diff --git a/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py b/packages/core/src/repowise/core/persistence/stores/_sql_analysis.pyindex 35adbdfdf..9464ae24d 100644--- a/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py+++ b/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py@@ -175,12 +175,8 @@ class _SqlAnalysisMixin(AnalysisIndexStore):self._session, repository_id, git_meta_map, repo_path)- async def get_stale_decisions(- self, repository_id: str, threshold: float = 0.5- ) -> list[DecisionRecord]:- return await crud.get_stale_decisions(- self._session, repository_id, threshold- )+ async def get_stale_decisions(self, repository_id: str) -> list[DecisionRecord]:+ return await crud.get_stale_decisions(self._session, repository_id)async def get_decision_health_summary(self, repository_id: str) -> dict:return await crud.get_decision_health_summary(self._session, repository_id)diff --git a/packages/core/src/repowise/core/precedent/currency.py b/packages/core/src/repowise/core/precedent/currency.pyindex 2e6baceaf..6f8430b1f 100644--- a/packages/core/src/repowise/core/precedent/currency.py+++ b/packages/core/src/repowise/core/precedent/currency.py@@ -136,6 +136,7 @@ def describe_decision_currency(created_at: datetime | None,nodes: Sequence[str],evidence_commits: Sequence[str] = (),+ accepted_at: datetime | None = None,) -> str | None:"""One sentence on whether a decision's code has moved since it was made.@@ -151,7 +152,8 @@ def describe_decision_currency(A record written before its *evidence_commits* landed counts from afterthe commit that landed them, the same anchor the stored staleness score- uses, so that commit is not reported as a change to it.+ uses, so that commit is not reported as a change to it. A later+ *accepted_at* (the latest reviewed grant) moves the anchor there too."""scope = [n for n in nodes if n]if not scope:@@ -159,10 +161,8 @@ def describe_decision_currency(if created_at is None:return None- since_commit, on = _anchor(root, created_at, evidence_commits)- count = commits_since(- root, since_commit=since_commit, since_date=created_at, nodes=scope- )+ since_commit, since_date, on = _anchor(root, created_at, evidence_commits, accepted_at)+ count = commits_since(root, since_commit=since_commit, since_date=since_date, nodes=scope)if count is None:return None@@ -174,18 +174,26 @@ def describe_decision_currency(def _anchor(- root: Path | str, created_at: datetime, evidence_commits: Sequence[str]-) -> tuple[str | None, str]:- """The commit to count from and how to date it: the landing of a record- written before it, else no commit and the record's own date."""+ root: Path | str,+ created_at: datetime,+ evidence_commits: Sequence[str],+ accepted_at: datetime | None = None,+) -> tuple[str | None, datetime, str]:+ """The commit or date to count from and how to word it: the latest of the+ record's own date, the landing of a record written before it, and its+ latest reviewed acceptance."""# Function-local: this module's import budget is the store and nothing heavier.from repowise.core.analysis.decisions.landing import evidence_landings, record_landing+ from repowise.core.analysis.decisions.staleness import _as_aware_utclandings = evidence_landings(root, evidence_commits, timeout=GIT_TIMEOUT_S)landing = record_landing(evidence_commits, landings, created_at)+ start = _as_aware_utc(landing.at if landing else created_at)+ if accepted_at is not None and _as_aware_utc(accepted_at) > start:+ return None, accepted_at, f"{accepted_at:%Y-%m-%d}, when it was last accepted"if landing is None:- return None, created_at.strftime("%Y-%m-%d")- return landing.sha, f"{landing.at:%Y-%m-%d} (landed in {landing.sha[:9]})"+ return None, created_at, created_at.strftime("%Y-%m-%d")+ return landing.sha, created_at, f"{landing.at:%Y-%m-%d} (landed in {landing.sha[:9]})"def recorded_on(birth_at: float) -> str:diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/sections.py b/packages/server/src/repowise/server/mcp_server/tool_context/sections.pyindex 6f0380e7d..af5b4eadf 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/sections.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/sections.py@@ -17,7 +17,7 @@ from typing import Anyfrom sqlalchemy import func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession-from repowise.core.analysis.decisions.lifecycle import is_governing+from repowise.core.analysis.decisions.lifecycle import RETIRED_STATUSES, is_governingfrom repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.attribution import attribution_enabled, file_sharefrom repowise.core.generation.page_selection import is_stale_status@@ -450,7 +450,7 @@ async def _decisions_section(card: CardState) -> None:``candidates`` never accepted, ``history`` accepted then withdrawn.Ordering is ``decision_priority_order``, shared with the Decisions page.- The dismissed filter is ``count_decisions_by_lane``'s: "dismissed" marks+ The retired filter is ``count_decisions_by_lane``'s: a retired status marksboth a tombstoned candidate and a withdrawn decision, and only theacceptance row tells them apart, so a bare status filter would lose thewithdrawn ones from the history lane.@@ -461,7 +461,7 @@ async def _decisions_section(card: CardState) -> None:select(DecisionRecord).where(DecisionRecord.repository_id == card.repo_id,- or_(DecisionRecord.status != "dismissed", accepted_predicate()),+ or_(DecisionRecord.status.notin_(sorted(RETIRED_STATUSES)), accepted_predicate()),).order_by(*decision_priority_order()))diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.pyindex 43297595b..0747de0e0 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py@@ -12,6 +12,7 @@ from sqlalchemy import selectfrom repowise.core.analysis.decisions.lifecycle import is_governingfrom repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.persistence.crud.authority import decision_currencies+from repowise.core.persistence.crud.decision_staleness import latest_grant_timesfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import DecisionRecordfrom repowise.core.precedent.currency import describe_decision_currency@@ -103,7 +104,7 @@ async def _why_path(query: str, repo: str | None) -> dict:governing, candidates, retired = _split_by_authority(matched, lineage_by_id, currencies, collector)- await _stamp_still_true(governing, matched, ctx.path)+ await _stamp_still_true(governing, matched, ctx.path, session, repository.id)# Every lane: the origin story is evidence, not instruction.origin_story = _origin_for(@@ -234,7 +235,7 @@ def _split_by_authority(async def _stamp_still_true(- governing: list[dict], matched: list, repo_path: str | Path+ governing: list[dict], matched: list, repo_path: str | Path, session: Any, repository_id: str) -> None:"""Ask git whether the top governing record still holds, and say so on it."""# Only the top record: the git query is affordable once per call, and the@@ -242,12 +243,15 @@ async def _stamp_still_true(if not governing:returntop = next(d for d in matched if d.id == governing[0]["id"])+ # Counted from the latest review, as the stored staleness score is.+ grants = await latest_grant_times(session, repository_id, [top.id])sentence = await asyncio.to_thread(describe_decision_currency,repo_path,created_at=top.created_at,nodes=json.loads(top.affected_files_json or "[]"),evidence_commits=json.loads(top.evidence_commits_json or "[]"),+ accepted_at=grants.get(top.id),)if sentence:governing[0]["still_true"] = sentencediff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.pyindex 9e183f078..962eca7d7 100644--- a/packages/server/src/repowise/server/routers/decisions.py+++ b/packages/server/src/repowise/server/routers/decisions.py@@ -719,3 +719,27 @@ async def patch_decision(assert rec is not Nonereturn await _one_with_signature(session, repo_id, rec)+++ "/api/repos/{repo_id}/decisions/{decision_id}/reaffirm",+ response_model=DecisionRecordResponse,+)+async def reaffirm_decision(+ repo_id: str,+ decision_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> DecisionRecordResponse:+ """Re-accept a governing decision after review, as a person on the web.++ What clears ``needs_review`` once someone has re-read the decision. Not a+ status transition: the status stays ``active`` and the acceptance log gains+ a ``reaffirmed`` row. 400 for a candidate or a withdrawn decision, which+ need a fresh acceptance instead.+ """+ rec = await _decision_in_repo(session, repo_id, decision_id)+ try:+ await crud.reaffirm_decision(session, rec, accepter="web", kind="person")+ except crud.AcceptanceRefusedError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ 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 dcb76e5c0..79586ec44 100644--- a/packages/server/src/repowise/server/schemas/decisions.py+++ b/packages/server/src/repowise/server/schemas/decisions.py@@ -74,11 +74,16 @@ class DecisionRecordResponse(BaseModel):# Why a record just created stayed a candidate, in the acceptance# contract's words. Set by the create route only.blockers: list[str] | None = None+ # True when the stored ``decision`` is blank and ``decision`` carries the+ # title fallback. Acceptance reads the stored text, so a review surface+ # needs this to predict the "no decision text" refusal.+ decision_text_missing: bool = False@classmethoddef from_orm(cls, obj: object) -> DecisionRecordResponse:affected_files = json.loads(obj.affected_files_json) # type: ignore[attr-defined]affected_modules = json.loads(obj.affected_modules_json) # type: ignore[attr-defined]+ decision_text = (obj.decision or "").strip() # type: ignore[attr-defined]return cls(id=obj.id, # type: ignore[attr-defined]repository_id=obj.repository_id, # type: ignore[attr-defined]@@ -92,7 +97,8 @@ class DecisionRecordResponse(BaseModel):# (the model's canonical one-line summary, always present) so no read# surface emits a body-less decision. New records get this at write# time in the harvest path; this covers pre-fix stored records.- decision=(obj.decision or "").strip() or obj.title, # type: ignore[attr-defined]+ decision=decision_text or obj.title, # type: ignore[attr-defined]+ decision_text_missing=not decision_text,rationale=obj.rationale, # type: ignore[attr-defined]alternatives=json.loads(obj.alternatives_json), # type: ignore[attr-defined]consequences=json.loads(obj.consequences_json), # type: ignore[attr-defined]diff --git a/packages/types/__tests__/decisions-vocabulary.test.ts b/packages/types/__tests__/decisions-vocabulary.test.tsindex 8b93b988d..a2a0f31ca 100644--- a/packages/types/__tests__/decisions-vocabulary.test.ts+++ b/packages/types/__tests__/decisions-vocabulary.test.ts@@ -162,6 +162,19 @@ describe("the acceptance contract, mirrored", () => {).toEqual(["no decision text: state what was chosen"]);});+ it("reads the server's flag over a decision filled with the title", () => {+ expect(+ decisionAcceptanceBlockers({+ ...accepted,+ decision: "Keep sessions in Redis",+ decision_text_missing: true,+ }),+ ).toEqual(["no decision text: state what was chosen"]);+ expect(+ decisionAcceptanceBlockers({ ...accepted, decision_text_missing: false }),+ ).toEqual([]);+ });+it("falls back to the context when there is no rationale", () => {expect(decisionAcceptanceBlockers({diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.tsindex 9af98dc6e..6183f8007 100644--- a/packages/types/src/decisions.ts+++ b/packages/types/src/decisions.ts@@ -302,6 +302,12 @@ export interface DecisionRecord {accepter_session?: string | null;/** Why a record just created stayed a candidate. Create endpoint only. */blockers?: string[] | null;+ /**+ * True when the stored decision text is blank and `decision` carries the+ * title fallback. Acceptance reads the stored text, so this is what predicts+ * the "no decision text" refusal. Optional for back-compat.+ */+ decision_text_missing?: boolean;/** 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. */@@ -510,11 +516,14 @@ export const DECISION_PRESETS = [* what forced the choice, `decision` is the choice itself, and letting the what* stand in for the why is what marked empty records acceptable. Every record* needs its `decision`, typed or mined: one that never says what was chosen- * binds nobody to anything.+ * binds nobody to anything. A server response fills a blank `decision` with the+ * title for readers, so `decision_text_missing` is what says the stored text is+ * blank.*/export function decisionAcceptanceBlockers(record: {// Required so a caller cannot leave it out and have every record refused.decision: string;+ decision_text_missing?: boolean;rationale?: string;context?: string;affected_files?: string[];@@ -529,7 +538,7 @@ export function decisionAcceptanceBlockers(record: {values.some((v) => (v ?? "").trim().length > 0);const selfAuthored = record.source === "cli";- if (!nonBlank([record.decision])) {+ if (record.decision_text_missing || !nonBlank([record.decision])) {blockers.push("no decision text: state what was chosen");}if (!nonBlank([record.rationale, record.context])) {diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex c1683706c..d99ed2166 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -1615,6 +1615,7 @@ export interface DecisionRecordResponse {accepter_kind?: string | null;accepter_session?: string | null;blockers?: string[] | null;+ decision_text_missing?: boolean;}/** The resolved decision capture policy for one repository. */diff --git a/packages/ui/__tests__/decisions/decision-detail.test.tsx b/packages/ui/__tests__/decisions/decision-detail.test.tsxindex 87fa87ac5..ea46f248b 100644--- a/packages/ui/__tests__/decisions/decision-detail.test.tsx+++ b/packages/ui/__tests__/decisions/decision-detail.test.tsx@@ -214,7 +214,7 @@ describe("DecisionDetail", () => {);expect(screen.getByText(- "All 2 files it names are still tracked and unchanged since it was recorded.",+ "All 2 files it names are still tracked and unchanged since it was recorded or last accepted.",),).toBeInTheDocument();});diff --git a/packages/ui/__tests__/decisions/decision-review-lanes.test.tsx b/packages/ui/__tests__/decisions/decision-review-lanes.test.tsxindex 397143455..29ae30d76 100644--- a/packages/ui/__tests__/decisions/decision-review-lanes.test.tsx+++ b/packages/ui/__tests__/decisions/decision-review-lanes.test.tsx@@ -203,6 +203,19 @@ describe("a candidate is a review request, not an instruction", () => {expect(screen.getByRole("button", { name: "Dismiss" })).toBeEnabled();});+ it("disables Accept when the server filled a blank decision with the title", () => {+ renderLanes("candidates", {+ decisions: [record({ decision: "Use JWTs", decision_text_missing: true })],+ onAccept: vi.fn(),+ onDismiss: vi.fn(),+ });++ // The row reads the title fallback, but acceptance reads the stored text.+ expect(screen.getByRole("button", { name: "Accept" })).toBeDisabled();+ expect(screen.getByText(/no decision text: state what was chosen/))+ .toBeInTheDocument();+ });+it("leaves Accept enabled on a candidate that carries what the contract needs", () => {renderLanes("candidates", {decisions: [diff --git a/packages/ui/__tests__/decisions/decision-staleness.test.ts b/packages/ui/__tests__/decisions/decision-staleness.test.tsindex 362055a4d..f6990bacd 100644--- a/packages/ui/__tests__/decisions/decision-staleness.test.ts+++ b/packages/ui/__tests__/decisions/decision-staleness.test.ts@@ -53,7 +53,7 @@ describe("describeStaleness", () => {it("gives one file its own sentence instead of a plural with the s removed", () => {expect(describeStaleness(["a.ts"], 0).sentence).toBe(- "The one file it names is still tracked and unchanged since it was recorded.",+ "The one file it names is still tracked and unchanged since it was recorded or last accepted.",);expect(describeStaleness(["a.ts"], 1).sentence).toContain("The one file it names has changed",diff --git a/packages/ui/src/decisions/decision-staleness.ts b/packages/ui/src/decisions/decision-staleness.tsindex dd5af61d0..c9a164426 100644--- a/packages/ui/src/decisions/decision-staleness.ts+++ b/packages/ui/src/decisions/decision-staleness.ts@@ -120,8 +120,8 @@ export function describeStaleness(fileCount,changedCount: 0,sentence: one- ? "The one file it names is still tracked and unchanged since it was recorded."- : `All ${fileCount} files it names are still tracked and unchanged since it was recorded.`,+ ? "The one file it names is still tracked and unchanged since it was recorded or last accepted."+ : `All ${fileCount} files it names are still tracked and unchanged since it was recorded or last accepted.`,short: `0 of ${fileCount}`,};}@@ -143,8 +143,8 @@ export function describeStaleness(fileCount,changedCount,sentence: one- ? "The one file it names has changed since it was recorded, or is no longer tracked, so it may no longer describe the code."- : `${changedCount} of its ${fileCount} files ${verb} changed since it was recorded, or ${be} no longer tracked, so parts of it may no longer describe the code.`,+ ? "The one file it names has changed since it was recorded or last accepted, or is no longer tracked, so it may no longer describe the code."+ : `${changedCount} of its ${fileCount} files ${verb} changed since it was recorded or last accepted, or ${be} no longer tracked, so parts of it may no longer describe the code.`,short: `${changedCount} of ${fileCount}`,};}diff --git a/plugins/claude-code/commands/decision.md b/plugins/claude-code/commands/decision.mdindex 54848ada0..80e36192e 100644--- a/plugins/claude-code/commands/decision.md+++ b/plugins/claude-code/commands/decision.md@@ -49,12 +49,21 @@ unless the repository turns it on.accept: it signs with `--agent <slug>` (plus `--session <id>` if known), andthe acceptance is recorded as the agent's, not a person's. A repository thatran `repowise decision config agent-acceptance --off` refuses it; then leave- acceptance to a person.+ acceptance to a person. `confirm` refuses a decision that is already+ accepted; renew that one with `reaffirm`.+- **reaffirm** — `repowise decision reaffirm <id>...` — after re-reading a+ `needs_review` decision that still holds, renew it so it counts as current+ from now. Takes `--reason`, `--evidence`, `--agent <slug>` and `--preview`.+ A candidate is refused; accept it with `confirm`.- **merge** — `repowise decision merge <id> <into-id>` — fold a duplicate- candidate into an accepted decision instead of accepting it twice.-- **deprecate / dismiss** — `repowise decision deprecate <id>` (optionally- `--superseded-by <id>`) or `repowise decision dismiss <id> --reason ...`.- An agent passes `--agent <slug>` to merge, deprecate and dismiss too.+ candidate into an accepted decision instead of accepting it twice. The target+ must already be accepted: confirm it first, or merge the other way.+ `--preview` shows the result without writing.+- **deprecate / dismiss** — `repowise decision deprecate <id> --reason ...`+ (optionally `--superseded-by <id>`, `--preview`) or+ `repowise decision dismiss <id> --reason ...`. An agent passes+ `--agent <slug>` to every review command, and the signer is recorded for+ candidates too.## Notes@@ -63,4 +72,7 @@ unless the repository turns it on.alignment score. This command is for *managing* the decision records themselves.- `add` is interactive unless you pass `--title` and `--decision`; the othersubcommands take ids and flags and never prompt, except `dismiss` (pass `--yes`).+- With `--format json`, confirm, reaffirm, merge, deprecate and dismiss always+ return `{action, preview, results, succeeded, failed}`, even for one id. Read+ `results[i].ok`, `.error`, `.message` and `.blockers`.- If unsure of an exact subcommand or flag, run `repowise decision --help`.diff --git a/plugins/claude-code/skills/architectural-decisions/SKILL.md b/plugins/claude-code/skills/architectural-decisions/SKILL.mdindex 8e7546d8e..94ca6cb76 100644--- a/plugins/claude-code/skills/architectural-decisions/SKILL.md+++ b/plugins/claude-code/skills/architectural-decisions/SKILL.md@@ -65,6 +65,6 @@ Add `--evidence-commit <sha>` once it is committed. The record lands as a candid## Reviewing candidates-You may review and accept candidates yourself. `repowise decision candidates --format json` lists each with its `blockers`. Accept one with `repowise decision confirm <id> --agent <your slug>`, adding `--reason`, `--scope <path>`, `--evidence <commit|file|link>` or `--decision` for whatever a blocker names. Dismiss a wrong one with `repowise decision dismiss <id> --agent <your slug> --reason ... --yes`, fold a duplicate with `repowise decision merge <id> <into-id> --agent <your slug>`, and retire one with `repowise decision deprecate <id> --agent <your slug>`. Your acceptances are recorded as yours, never a person's. If the repository turned agent acceptance off, the confirm is refused; leave it for a person and mention it.+You may review and accept candidates yourself. `repowise decision candidates --format json` lists each with its `blockers`. Accept one with `repowise decision confirm <id> --agent <your slug>`, adding `--reason`, `--scope <path>`, `--evidence <commit|file|link>` or `--decision` for whatever a blocker names. Dismiss a wrong one with `repowise decision dismiss <id> --agent <your slug> --reason ... --yes`, fold a duplicate with `repowise decision merge <id> <into-id> --agent <your slug>` (the target must already be accepted; confirm it first), and retire one with `repowise decision deprecate <id> --agent <your slug> --reason ...`. When an accepted decision is `needs_review` and still holds, renew it with `repowise decision reaffirm <id> --agent <your slug>`; `confirm` is for candidates only. With `--format json` every review command returns `results[]`, even for one id. Your acceptances are recorded as yours, never a person's. If the repository turned agent acceptance off, the confirm is refused; leave it for a person and mention it.If the user states a decision, offer to record it the same way without `--agent`.diff --git a/plugins/codex/skills/architectural-decisions/SKILL.md b/plugins/codex/skills/architectural-decisions/SKILL.mdindex b698788c1..563aed7a3 100644--- a/plugins/codex/skills/architectural-decisions/SKILL.md+++ b/plugins/codex/skills/architectural-decisions/SKILL.md@@ -59,6 +59,6 @@ Add `--evidence-commit <sha>` once it is committed. The record lands as a candid## Reviewing candidates-You may review and accept candidates yourself. `repowise decision candidates --format json` lists each with its `blockers`. Accept one with `repowise decision confirm <id> --agent <your slug>`, adding `--reason`, `--scope <path>`, `--evidence <commit|file|link>` or `--decision` for whatever a blocker names. Dismiss a wrong one with `repowise decision dismiss <id> --agent <your slug> --reason ... --yes`, fold a duplicate with `repowise decision merge <id> <into-id> --agent <your slug>`, and retire one with `repowise decision deprecate <id> --agent <your slug>`. Your acceptances are recorded as yours, never a person's. If the repository turned agent acceptance off, the confirm is refused; leave it for a person and mention it.+You may review and accept candidates yourself. `repowise decision candidates --format json` lists each with its `blockers`. Accept one with `repowise decision confirm <id> --agent <your slug>`, adding `--reason`, `--scope <path>`, `--evidence <commit|file|link>` or `--decision` for whatever a blocker names. Dismiss a wrong one with `repowise decision dismiss <id> --agent <your slug> --reason ... --yes`, fold a duplicate with `repowise decision merge <id> <into-id> --agent <your slug>` (the target must already be accepted; confirm it first), and retire one with `repowise decision deprecate <id> --agent <your slug> --reason ...`. When an accepted decision is `needs_review` and still holds, renew it with `repowise decision reaffirm <id> --agent <your slug>`; `confirm` is for candidates only. With `--format json` every review command returns `results[]`, even for one id. Your acceptances are recorded as yours, never a person's. If the repository turned agent acceptance off, the confirm is refused; leave it for a person and mention it.If the user states a decision, offer to record it the same way without `--agent`.diff --git a/plugins/shared/commands/decision.md b/plugins/shared/commands/decision.mdindex b4fa8d6a2..152f54fa9 100644--- a/plugins/shared/commands/decision.md+++ b/plugins/shared/commands/decision.md@@ -50,12 +50,21 @@ unless the repository turns it on.accept: it signs with `--agent <slug>` (plus `--session <id>` if known), andthe acceptance is recorded as the agent's, not a person's. A repository thatran `repowise decision config agent-acceptance --off` refuses it; then leave- acceptance to a person.+ acceptance to a person. `confirm` refuses a decision that is already+ accepted; renew that one with `reaffirm`.+- **reaffirm** — `repowise decision reaffirm <id>...` — after re-reading a+ `needs_review` decision that still holds, renew it so it counts as current+ from now. Takes `--reason`, `--evidence`, `--agent <slug>` and `--preview`.+ A candidate is refused; accept it with `confirm`.- **merge** — `repowise decision merge <id> <into-id>` — fold a duplicate- candidate into an accepted decision instead of accepting it twice.-- **deprecate / dismiss** — `repowise decision deprecate <id>` (optionally- `--superseded-by <id>`) or `repowise decision dismiss <id> --reason ...`.- An agent passes `--agent <slug>` to merge, deprecate and dismiss too.+ candidate into an accepted decision instead of accepting it twice. The target+ must already be accepted: confirm it first, or merge the other way.+ `--preview` shows the result without writing.+- **deprecate / dismiss** — `repowise decision deprecate <id> --reason ...`+ (optionally `--superseded-by <id>`, `--preview`) or+ `repowise decision dismiss <id> --reason ...`. An agent passes+ `--agent <slug>` to every review command, and the signer is recorded for+ candidates too.## Notes@@ -64,4 +73,7 @@ unless the repository turns it on.alignment score. This command is for *managing* the decision records themselves.- `add` is interactive unless you pass `--title` and `--decision`; the othersubcommands take ids and flags and never prompt, except `dismiss` (pass `--yes`).+- With `--format json`, confirm, reaffirm, merge, deprecate and dismiss always+ return `{action, preview, results, succeeded, failed}`, even for one id. Read+ `results[i].ok`, `.error`, `.message` and `.blockers`.- If unsure of an exact subcommand or flag, run `repowise decision --help`.diff --git a/plugins/shared/skills/architectural-decisions.md b/plugins/shared/skills/architectural-decisions.mdindex 9691db8ab..c748755e2 100644--- a/plugins/shared/skills/architectural-decisions.md+++ b/plugins/shared/skills/architectural-decisions.md@@ -73,6 +73,6 @@ Add `--evidence-commit <sha>` once it is committed. The record lands as a candid## Reviewing candidates-You may review and accept candidates yourself. `repowise decision candidates --format json` lists each with its `blockers`. Accept one with `repowise decision confirm <id> --agent <your slug>`, adding `--reason`, `--scope <path>`, `--evidence <commit|file|link>` or `--decision` for whatever a blocker names. Dismiss a wrong one with `repowise decision dismiss <id> --agent <your slug> --reason ... --yes`, fold a duplicate with `repowise decision merge <id> <into-id> --agent <your slug>`, and retire one with `repowise decision deprecate <id> --agent <your slug>`. Your acceptances are recorded as yours, never a person's. If the repository turned agent acceptance off, the confirm is refused; leave it for a person and mention it.+You may review and accept candidates yourself. `repowise decision candidates --format json` lists each with its `blockers`. Accept one with `repowise decision confirm <id> --agent <your slug>`, adding `--reason`, `--scope <path>`, `--evidence <commit|file|link>` or `--decision` for whatever a blocker names. Dismiss a wrong one with `repowise decision dismiss <id> --agent <your slug> --reason ... --yes`, fold a duplicate with `repowise decision merge <id> <into-id> --agent <your slug>` (the target must already be accepted; confirm it first), and retire one with `repowise decision deprecate <id> --agent <your slug> --reason ...`. When an accepted decision is `needs_review` and still holds, renew it with `repowise decision reaffirm <id> --agent <your slug>`; `confirm` is for candidates only. With `--format json` every review command returns `results[]`, even for one id. Your acceptances are recorded as yours, never a person's. If the repository turned agent acceptance off, the confirm is refused; leave it for a person and mention it.If the user states a decision, offer to record it the same way without `--agent`.diff --git a/tests/fixtures/decision_vocabulary.json b/tests/fixtures/decision_vocabulary.jsonindex 34ed144ab..7bc8bfdb9 100644--- a/tests/fixtures/decision_vocabulary.json+++ b/tests/fixtures/decision_vocabulary.json@@ -52,7 +52,8 @@"merged","superseded","dismissed",- "returned_to_review"+ "returned_to_review",+ "deprecated"],"accepter_kinds": ["person",diff --git a/tests/unit/analysis/test_decision_prompts.py b/tests/unit/analysis/test_decision_prompts.pyindex 94d41fe96..f3a864e9b 100644--- a/tests/unit/analysis/test_decision_prompts.py+++ b/tests/unit/analysis/test_decision_prompts.py@@ -1,7 +1,7 @@-"""Every gated extraction prompt asks for ``decision`` as a verbatim quote.+"""Every gated extraction prompt asks for ``decision`` and ``rationale`` verbatim.The substring gate blanks any field the source does not contain, so a prompt-that invites a reworded decision stores the record with no decision text.+that invites a reworded decision or reason stores the record without it."""from __future__ import annotations@@ -9,6 +9,7 @@ from __future__ import annotationsimport pytestfrom repowise.core.analysis.decisions.prompts import (+ _SYSTEM_PROMPT,COMMENT_ARCHAEOLOGY_PROMPT,GIT_ARCHAEOLOGY_PROMPT,INLINE_MARKER_PROMPT,@@ -16,17 +17,32 @@ from repowise.core.analysis.decisions.prompts import (README_MINING_PROMPT,)+_GATED_PROMPTS = [+ INLINE_MARKER_PROMPT,+ GIT_ARCHAEOLOGY_PROMPT,+ README_MINING_PROMPT,+ PR_BODY_MINING_PROMPT,+ COMMENT_ARCHAEOLOGY_PROMPT,+]- "prompt",- [- INLINE_MARKER_PROMPT,- GIT_ARCHAEOLOGY_PROMPT,- README_MINING_PROMPT,- PR_BODY_MINING_PROMPT,- COMMENT_ARCHAEOLOGY_PROMPT,- ],-)++def _field_line(prompt: str, field: str) -> str:+ return next(ln for ln in prompt.splitlines() if ln.strip().startswith(f'"{field}"'))++[email protected]("prompt", _GATED_PROMPTS)def test_the_decision_field_is_asked_for_verbatim(prompt: str) -> None:- line = next(ln for ln in prompt.splitlines() if ln.strip().startswith('"decision"'))+ assert "copied verbatim" in _field_line(prompt, "decision")++[email protected]("prompt", _GATED_PROMPTS)+def test_the_rationale_field_is_asked_for_verbatim(prompt: str) -> None:+ line = _field_line(prompt, "rationale")assert "copied verbatim" in line+ # An invitation to reword or infer is what the gate blanks.+ assert "paraphrase" not in line+ assert "infer" not in line+++def test_the_system_prompt_forbids_rewording_the_rationale() -> None:+ assert "decision and rationale fields word for word" in _SYSTEM_PROMPTdiff --git a/tests/unit/cli/test_command_target.py b/tests/unit/cli/test_command_target.pyindex 32623ebe1..a999d4d38 100644--- a/tests/unit/cli/test_command_target.py+++ b/tests/unit/cli/test_command_target.py@@ -313,3 +313,14 @@ def test_narrow_is_silent_for_an_explicit_single_repo(fake_workspace):picked, said = _said(resolve_command_target(path=str(fake_workspace / "backend")))assert picked == fake_workspace / "backend" and said == ""+++def test_decision_json_skips_the_workspace_line(fake_workspace, chdir, capsys):+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo++ chdir(fake_workspace)+ picked = _resolve_decision_repo(None, "json", needs_store=False)++ assert picked == fake_workspace / "backend"+ out, err = capsys.readouterr()+ assert "reads one repo" not in out + errdiff --git a/tests/unit/cli/test_decision_agent_acceptance.py b/tests/unit/cli/test_decision_agent_acceptance.pyindex dabe36fa1..7b6e509a4 100644--- a/tests/unit/cli/test_decision_agent_acceptance.py+++ b/tests/unit/cli/test_decision_agent_acceptance.py@@ -59,7 +59,7 @@ def test_an_agent_is_refused_on_a_repository_that_turned_it_off(repo: Path) -> Nassert result.exit_code == 1, result.outputpayload = json.loads(result.output)- assert "may not record" in payload["message"]+ assert "may not record" in payload["results"][0]["message"]assert "agent-acceptance --on" in payload["remedy"]@@ -160,15 +160,16 @@ def test_an_agent_signs_a_supersession(repo: Path) -> None: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."""+ """That path goes through ``deprecate_decision``, not+ ``supersede_decision``, and it still appends a withdrawal, logged as a+ deprecation rather than a dismissal."""assert _run(repo, "confirm", "aaaa").exit_code == 0assert _run(repo, "deprecate", "aaaa", "--agent", "claude_code").exit_code == 0signed = json.loads(_run(repo, "show", "aaaa").output)["decision"]["signature"]assert signed["kind"] == "agent"- assert signed["verb"] == "Dismissed"+ assert (signed["verb"], signed["action"]) == ("Deprecated", "deprecated")@pytest.mark.parametrize(@@ -224,7 +225,9 @@ def test_an_agent_merge_is_refused_where_agent_acceptance_is_off(repo: Path) ->)assert result.exit_code == 1, result.output- assert "agent acceptance is off" in json.loads(result.output)["message"]+ payload = json.loads(result.output)+ assert "agent acceptance is off" in payload["results"][0]["message"]+ assert payload["remedy"].startswith("Agent acceptance is off")def test_a_merge_without_the_flag_signs_as_a_person(repo: Path) -> None:@@ -286,7 +289,8 @@ def test_an_agent_record_gets_no_manual_entry_evidence_exemption(repo: Path) ->refused = _run(repo, "confirm", by_agent)assert refused.exit_code == 1, refused.output- assert any("evidence" in b for b in json.loads(refused.output)["blockers"])+ blockers = json.loads(refused.output)["results"][0]["blockers"]+ assert any("evidence" in b for b in blockers)accepted = _run(repo, "confirm", by_agent, "--evidence", "abc1234")assert accepted.exit_code == 0, accepted.outputdiff --git a/tests/unit/cli/test_decision_batch_review.py b/tests/unit/cli/test_decision_batch_review.pyindex 69e7ca83b..e46ae6bb5 100644--- a/tests/unit/cli/test_decision_batch_review.py+++ b/tests/unit/cli/test_decision_batch_review.py@@ -107,12 +107,15 @@ def test_preview_reports_a_refusal_without_writing(review_repo: Path) -> None:assert _lanes(review_repo)["candidates"] == 3-def test_one_id_keeps_the_transition_document(review_repo: Path) -> None:+def test_one_id_returns_the_batch_document(review_repo: Path) -> None:+ """One shape for one id or many, so an agent parses one document."""result = _run(review_repo, "confirm", "aaaa")assert result.exit_code == 0, result.outputpayload = json.loads(result.output)- assert payload == {"id": _GOOD, "status": "active", "action": "accepted"}+ assert (payload["succeeded"], payload["failed"]) == (1, 0)+ (only,) = payload["results"]+ assert (only["id"], only["status"], only["action"]) == (_GOOD, "active", "accepted")def test_batch_dismiss_reports_an_unknown_id_beside_the_rest(review_repo: Path) -> None:@@ -153,10 +156,10 @@ def test_an_ambiguous_single_id_refuses_instead_of_crashing(tmp_path: Path) -> Nresult = _run(repo, "confirm", "dd")assert result.exit_code == 1, result.output- payload = json.loads(result.output)- assert payload["error"] == "ambiguous_id"- assert "decision_id" not in payload- assert "ambiguous" in payload["message"]+ (only,) = json.loads(result.output)["results"]+ assert only["error"] == "ambiguous_id"+ assert "id" not in only+ assert "ambiguous" in only["message"]def test_an_id_shaped_directory_stays_an_id(review_repo: Path, monkeypatch) -> None:diff --git a/tests/unit/cli/test_decision_cmd.py b/tests/unit/cli/test_decision_cmd.pyindex 8ebd6e85b..b99c5e851 100644--- a/tests/unit/cli/test_decision_cmd.py+++ b/tests/unit/cli/test_decision_cmd.py@@ -455,6 +455,10 @@ def test_stale_only_counts_stale_rows_past_the_first_page(indexed_repo: Path) ->for i in range(100, 104)]_seed_wiki_db(indexed_repo, rows)+ # Stale is a property of accepted decisions only.+ for i in range(100, 104):+ confirmed = CliRunner().invoke(cli, ["decision", "confirm", f"{i:032x}", str(indexed_repo)])+ assert confirmed.exit_code == 0, confirmed.outputdata = _list_json(indexed_repo, "--stale-only")assert (data["total"], data["truncated"], len(data["decisions"])) == (4, False, 4)@@ -632,8 +636,8 @@ class TestTheLifecycleIsDrivableByAnAgent:)assert result.exit_code == 0, result.output- payload = json.loads(result.output)- assert payload == {"id": "c0ffee01", "status": "active", "action": "accepted"}+ (only,) = json.loads(result.output)["results"]+ assert (only["id"], only["status"], only["action"]) == ("c0ffee01", "active", "accepted")def test_dismiss_does_not_prompt_under_json(self, indexed_repo: Path):_seed_wiki_db(indexed_repo, [{"id": "c0ffee02", "title": "T", "status": "proposed"}])@@ -643,7 +647,7 @@ class TestTheLifecycleIsDrivableByAnAgent:)assert result.exit_code == 0, result.output- assert json.loads(result.output)["status"] == "dismissed"+ assert json.loads(result.output)["results"][0]["status"] == "dismissed"def test_dismiss_yes_skips_the_prompt_for_a_person_too(self, indexed_repo: Path):_seed_wiki_db(indexed_repo, [{"id": "c0ffee03", "title": "T", "status": "proposed"}])@@ -675,10 +679,10 @@ class TestTheLifecycleIsDrivableByAnAgent:cli, ["decision", action, "deadbeef", str(indexed_repo), "--format", "json"])- assert json.loads(result.output) == {- "error": "decision_not_found",- "decision_id": "deadbeef",- }+ payload = json.loads(result.output)+ assert (payload["succeeded"], payload["failed"]) == (0, 1)+ (only,) = payload["results"]+ assert (only["given"], only["error"]) == ("deadbeef", "decision_not_found")def test_deprecate_records_the_successor(self, indexed_repo: Path):_seed_wiki_db(@@ -698,7 +702,7 @@ class TestTheLifecycleIsDrivableByAnAgent:)assert result.exit_code == 0, result.output- assert json.loads(result.output)["status"] == "deprecated"+ assert json.loads(result.output)["results"][0]["status"] == "deprecated"def test_confirm_refuses_a_candidate_with_nothing_to_accept(indexed_repo: Path) -> None:@@ -728,9 +732,9 @@ def test_confirm_refuses_a_candidate_with_nothing_to_accept(indexed_repo: Path))assert result.exit_code == 1, result.output- payload = json.loads(result.output)- assert payload["error"] == "acceptance_refused"- assert any("scope" in blocker for blocker in payload["blockers"])+ (refused,) = json.loads(result.output)["results"]+ assert refused["error"] == "acceptance_refused"+ assert any("scope" in blocker for blocker in refused["blockers"])# And it is acceptable once the missing parts are supplied.fixed = CliRunner().invoke(@@ -753,7 +757,7 @@ def test_confirm_refuses_a_candidate_with_nothing_to_accept(indexed_repo: Path)],)assert fixed.exit_code == 0, fixed.output- assert json.loads(fixed.output)["status"] == "active"+ assert json.loads(fixed.output)["results"][0]["status"] == "active"# --- a manual entry is embedded like a mined one ---------------------------diff --git a/tests/unit/cli/test_decision_cmd_output.py b/tests/unit/cli/test_decision_cmd_output.pyindex 32d00e90c..6d02b1dd9 100644--- a/tests/unit/cli/test_decision_cmd_output.py+++ b/tests/unit/cli/test_decision_cmd_output.py@@ -165,7 +165,8 @@ def test_list_filters(seeded: Path) -> None:return {d["id"][:8] for d in _json("list", str(seeded), *flags)["decisions"]}assert ids("--proposed") == {"bbbbbbbb", "dddddddd"}- assert ids("--stale-only") == {"aaaaaaaa"}+ # Nothing is accepted yet, and a candidate's score is not a stale decision.+ assert ids("--stale-only") == set()assert ids("--source", "git_archaeology") == {"bbbbbbbb"}assert ids("--status", "deprecated") == {"cccccccc"}@@ -188,6 +189,14 @@ def accepted(seeded: Path) -> Path:return seeded+def test_stale_only_lists_what_health_counts_as_stale(accepted: Path) -> None:+ listed = _json("list", str(accepted), "--stale-only")+ health = _json("health", str(accepted))+ assert [d["id"] for d in listed["decisions"]] == ["aaaaaaaa11111111"]+ assert [d["id"] for d in health["stale_decisions"]] == ["aaaaaaaa11111111"]+ assert listed["total"] == health["summary"]["stale"] == 1++def test_health_json_carries_whole_lists(accepted: Path) -> None:payload = _json("health", str(accepted))assert payload["repo"] == str(accepted)@@ -292,10 +301,17 @@ def test_dismiss_can_be_cancelled_at_the_prompt(seeded: Path) -> None:def test_deprecate_refuses_an_unknown_successor(seeded: Path) -> None:result = _run("deprecate", "aaaaaaaa", str(seeded), "--superseded-by", "9999", "--format", "json")assert result.exit_code == 1- assert json.loads(result.stdout)["error"] == "decision_not_found"+ (only,) = json.loads(result.stdout)["results"]+ assert only["error"] == "decision_not_found"+ assert "9999" in only["message"]assert _json("show", "aaaaaaaa", str(seeded))["decision"]["status"] == "active"def test_deprecate_json_reports_the_transition(seeded: Path) -> None:payload = _json("deprecate", "bbbbbbbb", str(seeded))- assert payload == {"id": "bbbbbbbb22222222", "status": "deprecated", "action": "deprecated"}+ (only,) = payload["results"]+ assert (only["id"], only["status"], only["action"]) == (+ "bbbbbbbb22222222",+ "deprecated",+ "deprecated",+ )diff --git a/tests/unit/cli/test_decision_review_verbs.py b/tests/unit/cli/test_decision_review_verbs.pynew file mode 100644index 000000000..9d4e3d41b--- /dev/null+++ b/tests/unit/cli/test_decision_review_verbs.py@@ -0,0 +1,145 @@+"""The review verbs an agent drives: reaffirm, deprecate, merge, dismiss, split.++Each must refuse honestly, name the next step, sign as the agent that acted,+and answer ``--format json`` in the one batch shape whatever the id count.+"""++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+++def repo(tmp_path: Path) -> Path:+ path = tmp_path / "repo"+ path.mkdir()+ (path / ".repowise").mkdir()+ _seed_wiki_db(+ path,+ [+ {"id": "a" * 32, "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 _only(result) -> dict:+ (outcome,) = json.loads(result.output)["results"]+ return outcome+++def _signature(repo: Path, decision_id: str) -> dict | None:+ return json.loads(_run(repo, "show", decision_id).output)["decision"]["signature"]+++def test_confirming_a_decision_twice_points_at_reaffirm(repo: Path) -> None:+ assert _run(repo, "confirm", "aaaa").exit_code == 0++ again = _run(repo, "confirm", "aaaa")++ assert again.exit_code == 1, again.output+ outcome = _only(again)+ assert outcome["error"] == "already_accepted"+ assert "decision reaffirm aaaaaaaa" in outcome["message"]+ assert "remedy" not in json.loads(again.output)+ assert _signature(repo, "aaaa")["action"] == "accepted"+++def test_reaffirm_refuses_a_candidate_and_points_at_confirm(repo: Path) -> None:+ result = _run(repo, "reaffirm", "aaaa")++ assert result.exit_code == 1, result.output+ assert "decision confirm" in _only(result)["message"]+ assert _signature(repo, "aaaa") is None+++def test_an_agent_reaffirms_a_decision_signed_as_itself(repo: Path) -> None:+ assert _run(repo, "confirm", "aaaa").exit_code == 0++ result = _run(+ repo, "reaffirm", "aaaa", "--agent", "claude_code", "--reason", "re-read; still holds"+ )++ assert result.exit_code == 0, result.output+ assert _only(result)["action"] == "reaffirmed"+ signed = _signature(repo, "aaaa")+ assert (signed["action"], signed["kind"], signed["accepter"]) == (+ "reaffirmed",+ "agent",+ "claude_code",+ )+++def test_deprecate_preview_writes_nothing(repo: Path) -> None:+ assert _run(repo, "confirm", "aaaa").exit_code == 0++ result = _run(repo, "deprecate", "aaaa", "--preview")++ assert result.exit_code == 0, result.output+ assert _only(result)["action"] == "would_deprecate"+ assert _signature(repo, "aaaa")["action"] == "accepted"+++def test_decision_health_counts_a_deprecation(repo: Path) -> None:+ assert _run(repo, "confirm", "aaaa").exit_code == 0++ assert _run(repo, "deprecate", "aaaa", "--reason", "replaced by sessions").exit_code == 0++ summary = json.loads(_run(repo, "health").output)["summary"]+ assert (summary["deprecated"], summary["dismissed"]) == (1, 0)+++def test_merging_into_a_candidate_names_the_next_step(repo: Path) -> None:+ result = _run(repo, "merge", "aaaa", "bbbb")++ assert result.exit_code == 1, result.output+ outcome = _only(result)+ assert outcome["error"] == "merge_refused"+ assert "repowise decision confirm bbbbbbbb" in outcome["message"]+ assert "merge the other way" in outcome["message"]+++def test_merge_preview_writes_nothing(repo: Path) -> None:+ assert _run(repo, "confirm", "bbbb").exit_code == 0++ result = _run(repo, "merge", "aaaa", "bbbb", "--preview")++ assert result.exit_code == 0, result.output+ outcome = _only(result)+ assert (outcome["action"], outcome["merged_into"]) == ("would_merge", "b" * 32)+ assert _signature(repo, "bbbb")["action"] == "accepted"+++def test_dismissing_a_candidate_records_who_did_it(repo: Path) -> None:+ result = _run(+ repo, "dismiss", "aaaa", "--agent", "claude_code", "--session", "s-1", "--reason", "noise"+ )+ assert result.exit_code == 0, result.output++ listed = json.loads(_run(repo, "candidates", "--state", "dismissed").output)["candidates"]+ assert [c["reviewed_by"] for c in listed] == [+ {"accepter": "claude_code", "kind": "agent", "session": "s-1", "reason": "noise"}+ ]+ signed = _signature(repo, "aaaa")+ assert (signed["verb"], signed["kind"], signed["session"]) == ("Dismissed", "agent", "s-1")+++def test_a_split_request_is_signed(repo: Path) -> None:+ result = _run(repo, "split", "aaaa", "--agent", "claude_code", "--reason", "two choices")+ assert result.exit_code == 0, result.output++ listed = json.loads(_run(repo, "candidates", "--state", "needs_split").output)["candidates"]+ assert listed[0]["reviewed_by"]["accepter"] == "claude_code"diff --git a/tests/unit/persistence/test_decision_authority.py b/tests/unit/persistence/test_decision_authority.pyindex 82c2037a1..188248d63 100644--- a/tests/unit/persistence/test_decision_authority.py+++ b/tests/unit/persistence/test_decision_authority.py@@ -468,3 +468,95 @@ async def test_seq_retry_keeps_earlier_acceptances(async_session, monkeypatch):assert tripped, "the collision never fired, so the retry was not exercised"assert await latest_acceptance(async_session, first.id) is not Noneassert await latest_acceptance(async_session, second.id) is not None+++# ---------------------------------------------------------------------------+# Review verbs an agent drives+# ---------------------------------------------------------------------------+++async def test_a_candidate_cannot_be_reaffirmed(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Never accepted")++ with pytest.raises(AcceptanceRefusedError, match="confirm"):+ await reaffirm_decision(async_session, rec, accepter="tester")+ assert not await is_accepted(async_session, rec.id)+++async def test_a_withdrawn_decision_is_not_reaffirmed_back(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Withdrawn")+ await accept_decision(async_session, rec, accepter="tester")+ await dismiss_candidate(async_session, rec, reason="gone", accepter="tester")++ with pytest.raises(AcceptanceRefusedError, match="confirm"):+ await reaffirm_decision(async_session, rec, accepter="tester")+++async def test_reaffirm_records_the_reason_and_evidence_given(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Re-read")+ await accept_decision(async_session, rec, accepter="tester")++ row = await reaffirm_decision(+ async_session, rec, accepter="tester", reason="still holds", evidence=["abc1234"]+ )++ assert (row.action, row.reason, json.loads(row.evidence_json)) == (+ "reaffirmed",+ "still holds",+ ["abc1234"],+ )+++async def test_dismissing_a_candidate_signs_its_review_row_not_the_log(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Wrong idea")++ meta = await dismiss_candidate(+ async_session, rec, reason="not ours", accepter="claude_code", kind="agent",+ accepter_session="s-1",+ )++ assert (meta.dismissed_by, meta.dismissed_by_kind, meta.dismissed_session) == (+ "claude_code",+ "agent",+ "s-1",+ )+ # An acceptance row would make it a decision.+ assert not await is_accepted(async_session, rec.id)+++async def test_a_deprecation_is_logged_as_one(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Retired")+ await accept_decision(async_session, rec, accepter="tester")++ await update_decision_status(async_session, rec.id, "deprecated", accepter="tester")++ latest = await latest_acceptance(async_session, rec.id)+ assert (latest.action, latest.currency) == ("deprecated", "dismissed")+ assert rec.status == "deprecated"+++async def test_a_superseded_candidate_is_not_open_for_review(async_session):+ """A later commit can retire a candidate nobody reviewed; the queue and+ the lane counts must both drop it."""+ from repowise.core.persistence.crud.authority import count_decisions_by_lane++ repo = await insert_repo(async_session)+ live, retired = await _seed(async_session, repo.id, "Still open", "Reverted")+ retired.status = "superseded"+ await async_session.flush()++ open_ids = {r.id for r, _ in await list_candidates(async_session, repo.id)}+ lanes = await count_decisions_by_lane(async_session, repo.id)++ from repowise.core.persistence.crud import list_decisions++ page = await list_decisions(async_session, repo.id, accepted=False)++ assert open_ids == {live.id}+ assert (lanes["candidates"], lanes["total"]) == (1, 1)+ assert [r.id for r in page] == [live.id]diff --git a/tests/unit/persistence/test_decision_health_named_lanes.py b/tests/unit/persistence/test_decision_health_named_lanes.pyindex 67c625d3c..9b7b52b8b 100644--- a/tests/unit/persistence/test_decision_health_named_lanes.py+++ b/tests/unit/persistence/test_decision_health_named_lanes.py@@ -140,3 +140,38 @@ async def test_a_governing_record_is_in_neither_new_lane(async_session):assert health["summary"]["active"] == 1assert health["retired_decisions"] == []assert health["unscoped_decisions"] == []+++async def test_a_deprecated_decision_counts_as_deprecated_not_dismissed(async_session):+ """Both withdrawals share the ``dismissed`` currency; the status a+ deprecation writes is what keeps it out of the dismissed count."""+ from repowise.core.persistence.crud.authority import (+ accept_decision,+ deprecate_decision,+ dismiss_candidate,+ )++ repo = await insert_repo(async_session)+ retired, rejected = (+ DecisionRecord(+ repository_id=repo.id,+ title=title,+ decision=f"{title}: do it",+ rationale="measured",+ status="proposed",+ source="cli",+ affected_files_json=json.dumps(["src/app.py"]),+ evidence_file="src/app.py",+ )+ for title in ("Retired", "Rejected")+ )+ async_session.add_all([retired, rejected])+ await async_session.flush()+ for rec in (retired, rejected):+ await accept_decision(async_session, rec, accepter="tester")+ await deprecate_decision(async_session, retired, accepter="tester")+ await dismiss_candidate(async_session, rejected, accepter="tester")++ counts = (await get_decision_health_summary(async_session, repo.id))["summary"]++ assert (counts["deprecated"], counts["dismissed"]) == (1, 1)diff --git a/tests/unit/persistence/test_decision_staleness_recompute.py b/tests/unit/persistence/test_decision_staleness_recompute.pyindex fc34fe108..0ba15e47d 100644--- a/tests/unit/persistence/test_decision_staleness_recompute.py+++ b/tests/unit/persistence/test_decision_staleness_recompute.py@@ -260,3 +260,103 @@ async def test_the_commit_that_landed_the_record_is_not_scored_as_drift(session,await recompute_decision_staleness(session, _REPO_ID, {}, "/repo")assert rec.staleness_score == 0.0+++def _grant(rec: DecisionRecord, *, days_ago: int, kind: str = "person", seq: int = 1):+ from repowise.core.persistence.models import DecisionAcceptance++ return DecisionAcceptance(+ repository_id=_REPO_ID,+ decision_id=rec.id,+ seq=seq,+ action="accepted",+ currency="active",+ reason="reviewed",+ scope_json='["src/a.py"]',+ evidence_json='["src/a.py"]',+ accepter="tester",+ accepter_kind=kind,+ created_at=datetime.now(UTC) - timedelta(days=days_ago),+ )+++async def test_a_change_before_acceptance_was_reviewed_and_one_after_is_drift(session):+ rec = await _add_decision(session, files=["src/a.py", "src/b.py"], staleness=0.0)+ await _add_git_metadata(session, "src/a.py", days_ago=10, commits=1)+ await _add_git_metadata(session, "src/b.py", days_ago=1, commits=1)+ session.add(_grant(rec, days_ago=5))+ await session.flush()++ await recompute_decision_staleness(session, _REPO_ID, {})++ assert rec.staleness_score == 0.5+++async def test_an_imported_acceptance_does_not_move_the_anchor(session):+ """An import is stamped when it is applied here, not when anyone read the code."""+ rec = await _add_decision(session, files=["src/a.py"], staleness=0.0)+ await _add_git_metadata(session, "src/a.py", days_ago=10, commits=1)+ session.add(_grant(rec, days_ago=1, kind="import"))+ await session.flush()++ await recompute_decision_staleness(session, _REPO_ID, {})++ assert rec.staleness_score == 1.0+++async def test_reaffirming_clears_needs_review_without_an_index(session):+ from repowise.core.persistence.crud.authority import current_currency, reaffirm_decision++ rec = await _add_decision(session, files=["src/a.py"], staleness=1.0)+ rec.rationale = "because"+ rec.evidence_file = "src/a.py"+ await _add_git_metadata(session, "src/a.py", days_ago=10, commits=1)+ session.add(_grant(rec, days_ago=20))+ await session.flush()+ assert await current_currency(session, rec) == "needs_review"++ await reaffirm_decision(session, rec, accepter="tester")++ assert rec.staleness_score == 0.0+ assert await current_currency(session, rec) == "active"+++async def test_a_grant_never_raises_the_score_from_partial_metadata(session):+ """A file the index has not seen yet is the next index's to score."""+ from repowise.core.persistence.crud.authority import reaffirm_decision++ rec = await _add_decision(session, files=["src/new.py"], staleness=0.0)+ rec.rationale = "because"+ rec.evidence_file = "src/new.py"+ session.add(_grant(rec, days_ago=20))+ await session.flush()++ await reaffirm_decision(session, rec, accepter="tester")++ assert rec.staleness_score == 0.0+++async def test_stale_means_what_decision_health_counts(session):+ """A candidate's score is a fact about its files; only a decision goes stale."""+ from repowise.core.persistence.crud import get_decision_health_summary, get_stale_decisions++ accepted = await _add_decision(session, files=["src/a.py"], staleness=0.9)+ session.add(_grant(accepted, days_ago=40))+ candidate = DecisionRecord(+ id="d2",+ repository_id=_REPO_ID,+ title="Candidate",+ decision="x",+ status="proposed",+ staleness_score=0.9,+ affected_files_json='["src/a.py"]',+ )+ session.add(candidate)+ await session.flush()++ stale = await get_stale_decisions(session, _REPO_ID)+ health = await get_decision_health_summary(session, _REPO_ID)++ assert [d.id for d in stale] == ["d1"]+ assert [d.id for d in health["stale_decisions"]] == ["d1"]+ assert health["summary"]["stale"] == 1diff --git a/tests/unit/persistence/test_decision_sticky_status.py b/tests/unit/persistence/test_decision_sticky_status.pyindex 959c51b24..440c89a14 100644--- a/tests/unit/persistence/test_decision_sticky_status.py+++ b/tests/unit/persistence/test_decision_sticky_status.py@@ -73,6 +73,20 @@ async def test_dismissed_decision_survives_reindex_untouched(async_session):assert len(await list_decision_evidence(async_session, rec.id)) == evidence_before+async def test_deprecated_candidate_survives_reindex_untouched(async_session):+ from repowise.core.persistence.crud.authority import deprecate_decision++ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(async_session, repo.id, [_decision("Use Kafka")])+ rec = await _only_row(async_session, repo.id)+ await deprecate_decision(async_session, rec, reason="replaced", accepter="tester")++ await bulk_upsert_decisions(async_session, repo.id, [_decision("Use Kafka")])++ rec = await _only_row(async_session, repo.id)+ assert rec.status == "deprecated"++async def test_confirmed_decision_not_walked_back_to_proposed(async_session):repo = await insert_repo(async_session)await bulk_upsert_decisions(async_session, repo.id, [_decision("Use Redis")])diff --git a/tests/unit/precedent/test_currency.py b/tests/unit/precedent/test_currency.pyindex 7fdafad93..0cf84e16d 100644--- a/tests/unit/precedent/test_currency.py+++ b/tests/unit/precedent/test_currency.py@@ -118,6 +118,18 @@ def test_changed_scope_says_so_with_a_count(repo: Path) -> None:assert "the 2 files it governs changed in 1 commit since" in sentence+def test_a_change_before_the_latest_acceptance_is_not_reported(repo: Path) -> None:+ _touch_and_commit(repo, "moved.py")++ sentence = describe_decision_currency(+ repo, created_at=_BETWEEN, nodes=["moved.py"], accepted_at=datetime.now(UTC) + timedelta(seconds=2)+ )++ assert sentence is not None+ assert "nothing in the file it governs has changed" in sentence+ assert "when it was last accepted" in sentence++def test_unscoped_record_says_it_cannot_be_checked(repo: Path) -> None:"""The half a 0.0 score cannot express: never checkable, not checked-and-fresh."""sentence = describe_decision_currency(repo, created_at=datetime.now(UTC), nodes=[])diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.pyindex e885ffef7..859e0cfa7 100644--- a/tests/unit/server/mcp/test_why.py+++ b/tests/unit/server/mcp/test_why.py@@ -666,7 +666,7 @@ async def test_get_why_asks_git_about_the_top_record_only(session, setup_mcp, mocalls: list[tuple] = []- def _fake(root, *, created_at, nodes, evidence_commits=()):+ def _fake(root, *, created_at, nodes, evidence_commits=(), accepted_at=None):calls.append((root, tuple(nodes)))return "nothing in the 1 file it governs has changed since 2026-01-01"diff --git a/tests/unit/server/test_decisions_api.py b/tests/unit/server/test_decisions_api.pyindex 598a44662..38beccaef 100644--- a/tests/unit/server/test_decisions_api.py+++ b/tests/unit/server/test_decisions_api.py@@ -6,10 +6,14 @@ Covers:- GET /api/repos/{repo_id}/decisions/graph- 404 behaviour on bad decision_id / wrong repo- verification field on DecisionRecordResponse+- decision_text_missing beside the title fallback"""from __future__ import annotations+from datetime import UTC, datetime+from types import SimpleNamespace+import pytestfrom httpx import AsyncClientfrom sqlalchemy import delete@@ -17,6 +21,7 @@ from sqlalchemy import deletefrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import DecisionEvidence, DecisionNodeLink+from repowise.server.schemas.decisions import DecisionRecordResponsefrom tests.unit.server.conftest import create_test_repo# ---------------------------------------------------------------------------@@ -331,3 +336,53 @@ async def test_decision_record_response_includes_verification(client: AsyncClienassert resp.status_code == 200body = resp.json()assert body["verification"] == "fuzzy"+++# ---------------------------------------------------------------------------+# decision_text_missing beside the title fallback+# ---------------------------------------------------------------------------+++def _orm_row(decision: str | None) -> SimpleNamespace:+ now = datetime.now(UTC)+ return SimpleNamespace(+ id="d1",+ repository_id="r1",+ title="Keep sessions in Redis",+ status="active",+ kind="architectural",+ context="",+ decision=decision,+ rationale="sessions did not survive a restart",+ alternatives_json="[]",+ consequences_json="[]",+ affected_files_json='["src/auth/service.py"]',+ affected_modules_json="[]",+ tags_json="[]",+ source="pr",+ evidence_commits_json='["abc1234"]',+ evidence_file=None,+ evidence_line=None,+ confidence=0.8,+ staleness_score=0.0,+ verification="exact",+ superseded_by=None,+ last_code_change=None,+ created_at=now,+ updated_at=now,+ )++[email protected]("stored", ["", " ", None])+def test_blank_decision_reads_as_title_and_says_text_is_missing(stored) -> None:+ # Readers keep the title fallback; the flag is what lets a review surface+ # predict the acceptance refusal that the stored blank text will draw.+ resp = DecisionRecordResponse.from_orm(_orm_row(stored))+ assert resp.decision == "Keep sessions in Redis"+ assert resp.decision_text_missing is True+++def test_stored_decision_text_is_not_missing() -> None:+ resp = DecisionRecordResponse.from_orm(_orm_row("Keep sessions in Redis."))+ assert resp.decision == "Keep sessions in Redis."+ assert resp.decision_text_missing is Falsediff --git a/tests/unit/server/test_decisions_patch.py b/tests/unit/server/test_decisions_patch.pyindex ece7499bc..992ea4f1c 100644--- a/tests/unit/server/test_decisions_patch.py+++ b/tests/unit/server/test_decisions_patch.py@@ -200,3 +200,38 @@ async def test_patch_decision_not_found(client: AsyncClient) -> None:json={"status": "deprecated"},)assert resp.status_code == 404+++async def test_reaffirm_appends_a_reaffirmed_row(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ decision_id = await _seed_decision(app.state.session_factory, repo["id"])++ resp = await client.post(f"/api/repos/{repo['id']}/decisions/{decision_id}/reaffirm")++ assert resp.status_code == 200, resp.text+ assert resp.json()["status"] == "active"+ async with get_session(app.state.session_factory) as session:+ latest = await crud.latest_acceptance(session, decision_id)+ assert (latest.action, latest.accepter, latest.accepter_kind) == ("reaffirmed", "web", "person")+++async def test_reaffirm_refuses_a_candidate(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ async with get_session(app.state.session_factory) as session:+ rec = await crud.upsert_decision(+ session,+ repository_id=repo["id"],+ title="Never accepted",+ status="proposed",+ decision="Do the thing.",+ affected_files=["src/app.py"],+ source="cli",+ )+ candidate_id = rec.id++ resp = await client.post(f"/api/repos/{repo['id']}/decisions/{candidate_id}/reaffirm")++ assert resp.status_code == 400+ assert "confirm" in resp.json()["detail"]diff --git a/tests/unit/server/test_mcp_decision_graph.py b/tests/unit/server/test_mcp_decision_graph.pyindex ae036452a..7c91b1602 100644--- a/tests/unit/server/test_mcp_decision_graph.py+++ b/tests/unit/server/test_mcp_decision_graph.py@@ -326,7 +326,11 @@ async def decision_db(session: AsyncSession, repo_id: str) -> str:)for d in decisions:+ seeded = d.staleness_scoreawait accept_decision(session, d, accepter="test", evidence=[f"seed:{d.id}"])+ # Accepting rescores from the stored git metadata, which this fixture+ # has none of; the seeded score is the state under test.+ d.staleness_score = seededsuperseded = next(d for d in decisions if d.id == "dec_superseded")await record_acceptance(session,