Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(decisions): review lanes, one vocabulary, and authority on every read (#2070)
Raghav Chamadiyafd6f639ee2d3
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 032acdb4f..2b9ae8b4a 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -656,7 +656,7 @@ Architectural decision intelligence. Falls back to git archaeology when no decis**Modes:**1. **NL search**: pass a question, optionally anchored to `targets`: `get_why(query="why JWT over sessions?")` -> searches decision records.-2. **Path-based**: pass a file path as `query`: `get_why(query="src/auth/service.ts")` -> returns decisions governing that file plus its origin story.+2. **Path-based**: pass a file path as `query`: `get_why(query="src/auth/service.ts")` -> returns three lanes, `decisions` (accepted, governing), `candidates` (nobody accepted them) and `history` (accepted and since replaced), plus the file's origin story.3. **Health dashboard**: no `query`: `get_why()` -> stale decisions, conflicts, ungoverned hotspots.4. **Reference lookup**: pass `id`: `get_why(id="ev_...")` -> the exact evidence and supporting decision in one call.@@ -664,9 +664,13 @@ Architectural decision intelligence. Falls back to git archaeology when no decis`answer_basis` names the strongest lane the response rests on: `decision`, `episode`, `rationale`, `archaeology`, or `documentation`. Only `decision` is a ruling; the rest are evidence to weigh. Absent when no lane was served, and on the health dashboard.-**A record's `status` decides whether it binds you.** `active` means somebody accepted it, in a recorded event that names the reason, the scope, the evidence and the accepter: treat it as a constraint. Anything else is a candidate — something was inferred and nobody has agreed to it — so read it as a hint and never as a rule. Nothing produces an acceptance except an explicit `repowise decision confirm` or a committed ADR that says it is accepted, so a candidate that has recurred across fifty sessions is still a candidate.+**The lane a record is in decides whether it binds you, and path mode puts it in one.** `decisions` holds accepted records: somebody accepted each in a recorded event naming the reason, the scope, the evidence and the accepter, so treat them as constraints. `candidates` holds records something inferred and nobody has agreed to; read them as hints and never as rules, and note the `candidates_note` beside them says so too. Nothing produces an acceptance except an explicit `repowise decision confirm` or a committed ADR that says it is accepted, so a candidate that has recurred across fifty sessions is still a candidate.-Path mode's `alignment` counts the two separately: `active_count` is what governs the file, `candidate_count` is what is merely awaiting review, and `score` is derived from the accepted records alone. A file with `active_count: 0` is ungoverned however many candidates name it.+Do not read the lane off `status`. That column is a projection kept in step for readers that predate the split, and a record can carry `status: "active"` with no acceptance behind it at all. An accepted record instead carries a `currency`: `active` (still describes its code), `needs_review` (its files have moved, and it still binds), `uncheckable` (it names nothing, so nothing can check it), `superseded` or `dismissed`. A candidate carries `review_state: "open"` and no `currency`.++Path mode's `alignment` counts the lanes separately and they sum to `governing_count`, which is every record naming the file: `active_count` is what governs it, `deprecated_count` what was accepted and withdrawn, `uncheckable_count` what was accepted but names nothing, `candidate_count` what is merely awaiting review. `score` is derived from `active_count` alone, so a file with `active_count: 0` is ungoverned however many candidates name it.++The `candidates` and `history` lanes are capped at three rows each and shed first under response-budget pressure, so an absent lane means the budget was tight, not that it was empty. `get_overview`, `get_risk` directives and `get_answer` serve accepted records only; a candidate reaches none of them as an instruction.**When to use:** Before architectural changes, understand existing intent and constraints. After changes, record new decisions.diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.mdindex 3a3dd797a..6ffa174a7 100644--- a/docs/layers/DECISIONS.md+++ b/docs/layers/DECISIONS.md@@ -149,6 +149,31 @@ Similarity never supersedes anything: an edge exists because somebody named thesuccessor. Merging and superseding retire ids that may already be written downsomewhere, so both leave an alias and the retired id keeps resolving.+The same actions are on the Decisions page, split into five review lanes that+partition the repository, so the counts add up and no record is in two of them:++| Lane | What is in it |+|------|---------------|+| Active | Accepted, and still describes the code it names. These are the rules. |+| Candidates | Never accepted. Governs nothing, reaches no agent. Carries the evidence quote it was drawn from, so it can be accepted or dismissed from the row. |+| Needs review | Accepted, but the files it names have moved. Still binds. |+| Uncheckable | Accepted, but names no file or module, so nothing can check it against the code and no agent editing a file will be given it. |+| History | Accepted and then withdrawn, superseded or dismissed. |++The lane is a join onto the acceptance, not a filter on the status column, so+`GET /api/repos/{id}/decisions?lane=candidates` and+`GET /api/repos/{id}/decisions/lane-counts` are different questions from+`/decisions/counts`, which groups the status projection. Every listed record+also carries a `currency` field; a record with no `currency` is a candidate.+The lane is applied before the page is cut, so a page of a lane is a page of+that lane.++Accepting from the UI goes through the same acceptance contract as+`repowise decision confirm`, so a candidate missing a reason, a scope or an+evidence reference has its Accept disabled with the gap named beside it rather+than failing after the click. Dismissing stays available: a candidate that+cannot be accepted is the one most worth tombstoning.+```repowise decision health@@ -512,10 +537,17 @@ record's staleness: whether you overrode a decision is a judgement about therecord, staleness is a measurement of the code, and one of those is per-machinewhile the other travels with the repository.-Decisions also land in the generated `CLAUDE.md` (active records, freshest+Decisions also land in the generated `CLAUDE.md` (accepted records, freshestfirst) and in `get_overview()`, `get_context()`, and the `governance_risk` flagin `get_risk()` PR review.+Every one of those reads is the acceptance join, not the status column. A+candidate does not appear in `get_overview()`'s key decisions, cannot raise a+`governance_risk` directive against a pull request, and reaches `get_answer`'s+prompt labelled `candidate` rather than `active`. That labelling matters: the+row is rendered verbatim into a model prompt, and a candidate named `active`+reads to the model as something the repository has settled on.+## CLI referenceEvery subcommand takes an optional trailing `PATH`; in workspace mode it targets@@ -523,6 +555,13 @@ the primary repo. Decision ids accept an 8-character prefix.| Command | What it does ||---------|--------------|+Recording a decision from the UI follows the same rule as `repowise decision+add`: name the files or modules it governs and the write records an acceptance,+name none and it is stored as a candidate, and the form says which before you+press the button. Re-recording the title of a decision that is already accepted+without naming its scope is refused rather than applied, because it would clear+the scope that decision governs.+| `repowise decision add` | Guided interactive capture: title, context, decision, rationale, rejected alternatives, tradeoffs, affected files, tags. Answering the prompts is an acceptance, recorded as one. Name no files and it is kept as a candidate instead, because a decision that names nothing cannot be checked against the code. || `repowise decision list` | Table of id, title, status, source, confidence, staleness, created date. || `repowise decision show ID` | Full record including alternatives, consequences, affected files, and the evidence file and line. |@@ -559,12 +598,27 @@ Full flag reference: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-d| Call shape | Mode | Returns ||------------|------|---------|| No `query` | health | `counts`, `stale_decisions`, `proposed_awaiting_review`, `ungoverned_hotspots`, `conflicts` |-| `query` is a path | path | The decisions governing that file (with `lineage` when the chain is longer than one), an `origin_story` from git, and an `alignment` read scored on accepted decisions only |+| `query` is a path | path | Three lanes: `decisions`, the accepted decisions governing that file (with `lineage` when the chain is longer than one); `candidates`, records naming it that nobody has accepted; and `history`, records accepted and since superseded or withdrawn. Plus an `origin_story` from git and an `alignment` read scored on the first lane only || `query` is a question | search | Ranked decision records plus `related_documentation`, optionally anchored with `targets` || `repo="all"` | workspace search | The same records across every workspace repo, each tagged with its alias |-It is designed never to come back empty-handed. If no decision record covers a-path, it falls back to git archaeology on that file. If git history is silent+The lanes never mix. `decisions` is what governs, and it is the only lane an+agent should read as a rule. `candidates` carries a `candidates_note` saying in+as many words that nobody has accepted them and how to accept one, and+`history` carries a `history_note` saying its records were accepted and have+since been replaced. When only candidates name a path, `alignment.score` is+`none` and its explanation says there is no accepted decision, rather than+reporting the file as governed. `alignment` also splits its counts four ways,+and they sum to `governing_count`: `active_count`, `deprecated_count`,+`uncheckable_count`, `candidate_count`.++Both non-governing lanes are capped at three rows and are the first things shed+under budget pressure: they are context, and a response that cannot afford the+rules must not spend on the queue. A note is dropped with its lane, so a+sentence never counts rows that are no longer in the payload.++It is designed never to come back empty-handed. If no accepted decision covers+a path, it falls back to git archaeology on that file. If git history is silenttoo, it mines a rationale comment live from the source and returns it as`code_rationale`. Semantic decision search falls back to full-text search whenthe vector store is unavailable.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 8bc274c4d..a70d07360 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -972,6 +972,12 @@ Broad discovery itself is a source, so it is switched with`confirm` is the acceptance event. Nothing else promotes a record to `active`:extraction, recurrence across sessions, and confidence all stop at `proposed`.+`--status` filters the status column, which is a projection of the acceptance+kept in step for readers that predate the split, so it is not the same question+as "what governs". `repowise decision candidates` is the authoritative list of+what nobody has accepted, and the Decisions page splits the same repository+into five lanes over the acceptance join.+**Scripting these:** every subcommand takes `--format json`, and `confirm`,`dismiss`, `deprecate`, and `show` exit non-zero on an unknown id with`{"error": "decision_not_found", "decision_id": "..."}` so a caller can tell a@@ -982,7 +988,7 @@ typo from a successful transition. `dismiss` skips its confirmation prompt under| Flag | Description ||------|-------------|-| `--status` | `active`, `proposed`, `deprecated`, `superseded`, `all` |+| `--status` | `active`, `proposed`, `deprecated`, `superseded`, `dismissed`, `all` || `--source` | `adr`, `cli`, `comment`, `commit`, `git_archaeology`, `inline_marker`, `llm_inferred`, `pr`, `session`, `all` || `--proposed` | Shortcut for `--status proposed` || `--stale-only` | Only stale decisions |diff --git a/packages/api-client/src/decisions.ts b/packages/api-client/src/decisions.tsindex 3679ccb56..8036ef6ad 100644--- a/packages/api-client/src/decisions.ts+++ b/packages/api-client/src/decisions.ts@@ -5,6 +5,8 @@ import type {DecisionEvidenceResponse,DecisionCounts,DecisionGraph,+ DecisionLaneCounts,+ DecisionLaneFilter,DecisionLineageEntry,DecisionLineageResponse,DecisionRecordResponse,@@ -21,6 +23,12 @@ export async function listDecisions(tag?: string;module?: string;include_proposed?: boolean;+ /**+ * Review lane. `candidates` are records nobody has accepted; `governing`+ * is what still binds. Applied after the page is fetched on the server,+ * because a lane is a join and not a column.+ */+ lane?: DecisionLaneFilter;limit?: number;offset?: number;/**@@ -49,6 +57,22 @@ export async function getDecisionCounts(return apiGet<DecisionCounts>(`/api/repos/${repoId}/decisions/counts`, opts);}+/**+ * Counts per review lane, from a scan of the acceptance join.+ *+ * Not interchangeable with {@link getDecisionCounts}, which groups the status+ * column. That column is the projection kept in step for readers that predate+ * the acceptance split, so its `active` and this one's `active` answer+ * different questions.+ */+export async function getDecisionLaneCounts(+ repoId: string,+): Promise<DecisionLaneCounts> {+ return apiGet<DecisionLaneCounts>(+ `/api/repos/${repoId}/decisions/lane-counts`,+ );+}+export async function getDecision(repoId: string,decisionId: string,diff --git a/packages/api-client/src/types/decisions.ts b/packages/api-client/src/types/decisions.tsindex b38b70f60..7be4e8d5b 100644--- a/packages/api-client/src/types/decisions.ts+++ b/packages/api-client/src/types/decisions.ts@@ -2,150 +2,52 @@// Decisions// ----------------------------------------------------------------------------// One vocabulary, imported rather than re-typed. Three copies of the union-// lived here and none of them listed `dismissed`, which the engine has always-// accepted — so the UI had no way to say it and sent `deprecated` instead.-import type { DecisionStatus } from "@repowise-dev/types/decisions";--// Re-exported rather than re-declared: the capture policy has one shape and-// the server generates it from the same registry.+// One vocabulary, imported rather than re-typed. Ten shapes were re-declared+// here and had drifted from the canonical ones: `source` still named a retired+// `readme_mining` and omitted five live values, `DecisionStatusUpdate.status`+// had widened to a bare string, and `DecisionCounts` was a byte-identical+// duplicate. A client that re-types its own wire contract is a second contract.export type {+ CandidateReviewState,+ DecisionCodeEdge,+ DecisionCounts,+ DecisionCurrency,+ DecisionEvidence,+ DecisionGraph,+ DecisionGraphEdge,+ DecisionGraphNode,+ DecisionLaneCounts,+ DecisionLaneFilter,+ DecisionLineageEntry,DecisionPreset,+ DecisionScope,DecisionSettings,DecisionSettingsUpdate,+ DecisionSource,DecisionSourcePatch,DecisionSourceState,+ DecisionStatus,+ DecisionStatusUpdate,+ DecisionVerification,+ EvidencePreview,} from "@repowise-dev/types/decisions";-export interface DecisionRecordResponse {- id: string;- repository_id: string;- title: string;- status: DecisionStatus;- context: string;- decision: string;- rationale: string;- alternatives: string[];- consequences: string[];- affected_files: string[];- affected_modules: string[];- tags: string[];- source: "git_archaeology" | "inline_marker" | "readme_mining" | "cli";- evidence_commits: string[];- evidence_file: string | null;- evidence_line: number | null;- confidence: number;- staleness_score: number;- superseded_by: string | null;- last_code_change: string | null;- /** Trust tier of the decision's primary supporting evidence. */- verification?: DecisionVerification;- /**- * Derived granularity of the decision's blast area. Absent on older- * backends; null when the record has no code linkage at all.- */- scope?: "file" | "module" | "cross-module" | null;- created_at: string;- updated_at: string;- /** Evidence rows backing the record. Populated by the list endpoint only. */- evidence_count?: number | null;- /** Top-ranked evidence row, slimmed. Populated by the list endpoint only. */- evidence_preview?: EvidencePreview | null;-}--export type DecisionVerification = "exact" | "fuzzy" | "unverified";+// The record under the name this client has always used for it. `Response` is+// the transport-layer name; the shape is the canonical one.+export type { DecisionRecord as DecisionRecordResponse } from "@repowise-dev/types/decisions";+export type { DecisionCreateInput as DecisionCreate } from "@repowise-dev/types/decisions";-export interface EvidencePreview {- source: string;- source_quote: string;- verification: DecisionVerification;- evidence_file?: string | null;- evidence_line?: number | null;-}--export interface DecisionEvidence {- id: string;- source: string;- source_rank: number;- evidence_file: string | null;- evidence_line: number | null;- evidence_commit: string | null;- source_quote: string;- confidence: number;- verification: DecisionVerification;- created_at: string;-}+import type {+ DecisionEvidence,+ DecisionLineageEntry,+} from "@repowise-dev/types/decisions";+// Envelope shapes, which exist only on the wire and have no canonical+// counterpart: the endpoints wrap their lists in a single-key object.export interface DecisionEvidenceResponse {evidence: DecisionEvidence[];}-export interface DecisionLineageEntry {- id: string;- title: string;- status: DecisionStatus;- source: string;- relation: string | null;-}-export interface DecisionLineageResponse {lineage: DecisionLineageEntry[];}--export interface DecisionGraphNode {- id: string;- title: string;- status: DecisionStatus;- source: string;- confidence: number;- staleness_score: number;- verification: DecisionVerification;-}--export interface DecisionGraphEdge {- src: string;- dst: string;- kind: "supersedes" | "refines" | "relates_to" | "conflicts_with";- confidence: number;- evidence: string;-}--export interface DecisionCodeEdge {- decision_id: string;- node_id: string;- link_type: "file" | "module";-}--export interface DecisionGraph {- nodes: DecisionGraphNode[];- decision_edges: DecisionGraphEdge[];- code_edges: DecisionCodeEdge[];-}--export interface DecisionCreate {- title: string;- context?: string;- decision?: string;- rationale?: string;- alternatives?: string[];- consequences?: string[];- affected_files?: string[];- affected_modules?: string[];- tags?: string[];-}--export interface DecisionStatusUpdate {- status?: string;- superseded_by?: string;- affected_modules?: string[];- affected_files?: string[];-}--/** Counts by status, from a grouped COUNT on the server. */-export interface DecisionCounts {- total: number;- active: number;- proposed: number;- superseded: number;- deprecated: number;-}diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.pyindex 3caabf649..1a123a130 100644--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py@@ -18,7 +18,9 @@ __all__ = ["ACCEPTANCE_ACTIONS","CANDIDATE_REVIEW_STATES","DECISION_CURRENCIES",+ "DECISION_STATUS_ORDER","NEEDS_REVIEW_STALENESS",+ "REVIEW_LANES","STORED_CURRENCIES","AcceptanceRequirement","acceptance_blockers",@@ -26,6 +28,7 @@ __all__ = ["effective_currency","is_governing","legacy_status_for_currency",+ "status_rank",]#: What a decision's authority currently amounts to. Replaces the numeric@@ -59,6 +62,42 @@ STORED_CURRENCIES: tuple[str, ...] = ("dismissed",)+#: The one ranking of ``decision_records.status``, best first. A rule the team+#: stands behind, then a candidate, then history, then a tombstone. Four+#: independent copies of this ordering existed and two of them disagreed about+#: where ``superseded`` sat, so a list and the tool describing it ranked the+#: same rows differently.+DECISION_STATUS_ORDER: tuple[str, ...] = (+ "active",+ "proposed",+ "superseded",+ "deprecated",+ "dismissed",+)++_STATUS_RANK: dict[str, int] = {s: i for i, s in enumerate(DECISION_STATUS_ORDER)}+++def status_rank(status: str) -> int:+ """Sort key for *status*. An unknown status sorts after every known one."""+ return _STATUS_RANK.get(status, len(DECISION_STATUS_ORDER))+++#: The review lanes, which partition a repository: every record is in exactly+#: one, and the five sum to the total. ``candidates`` is the absence of an+#: acceptance; the other four are the currencies, with ``superseded`` and+#: ``dismissed`` folded into ``history`` because a reader working a queue does+#: not need those apart. ``governing`` is deliberately not here: it is the+#: roll-up of ``active`` and ``needs_review``, so it overlaps two lanes and+#: belongs in a filter rather than in a tab row.+REVIEW_LANES: tuple[str, ...] = (+ "active",+ "candidates",+ "needs_review",+ "uncheckable",+ "history",+)+#: What an acceptance row records having happened.ACCEPTANCE_ACTIONS: tuple[str, ...] = ("accepted",diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex d917b248f..31116106c 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -13,9 +13,10 @@ shortcut past the reason/scope/evidence/identity requirement.from __future__ import annotationsimport json+from collections.abc import Iterablefrom typing import Any-from sqlalchemy import func, select+from sqlalchemy import func, or_, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession@@ -25,6 +26,7 @@ from repowise.core.analysis.decisions.lifecycle import (AcceptanceRequirement,acceptance_blockers,effective_currency,+ is_governing,legacy_status_for_currency,)@@ -43,7 +45,9 @@ __all__ = ["accept_decision","accepted_decision_ids","accepted_predicate",+ "count_decisions_by_lane","current_currency",+ "decision_currencies","dismiss_candidate","is_accepted","latest_acceptance",@@ -158,6 +162,142 @@ async def accepted_decision_ids(return {did for did, currency in rows if currency not in ("superseded", "dismissed")}+async def decision_currencies(+ session: AsyncSession,+ repository_id: str,+ records: Iterable[DecisionRecord],+) -> dict[str, str]:+ """Effective currency per decision id. A candidate is absent from the map.++ The batched form of :func:`current_currency`, and the primitive every read+ surface splits its lanes with. One query for the repository's current+ acceptances, then :func:`effective_currency` per record, because the+ ``needs_review`` and ``uncheckable`` derivations need the record's scope and+ staleness and the acceptance row does not carry them.++ Absent means candidate, which is the only test that separates the two+ entities. Reading ``status == "active"`` instead is the same question with a+ different answer: the column is a projection every writer keeps in step, so+ it agrees right up until something writes it without an acceptance.+ """+ latest_seq = (+ select(+ DecisionAcceptance.decision_id.label("did"),+ func.max(DecisionAcceptance.seq).label("seq"),+ )+ .where(DecisionAcceptance.repository_id == repository_id)+ .group_by(DecisionAcceptance.decision_id)+ .subquery()+ )+ q = select(DecisionAcceptance.decision_id, DecisionAcceptance.currency).join(+ latest_seq,+ (DecisionAcceptance.decision_id == latest_seq.c.did)+ & (DecisionAcceptance.seq == latest_seq.c.seq),+ )+ stored = {did: currency for did, currency in (await session.execute(q)).all()}++ out: dict[str, str] = {}+ for record in records:+ currency = stored.get(record.id)+ if currency is None:+ continue+ out[record.id] = effective_currency(+ currency,+ has_scope=bool(_record_scope(record)),+ staleness=record.staleness_score,+ )+ return out+++async def count_decisions_by_lane(+ session: AsyncSession, repository_id: str+) -> dict[str, int]:+ """Records per review lane, as counts a surface can put on a tab.++ ``candidates`` plus the four currencies (``active``, ``needs_review``,+ ``uncheckable``, ``history``) partition the repository, so the five sum to+ ``total`` and no record is counted twice. ``governing`` is the roll-up of+ the two currencies that still bind, reported alongside rather than as a+ peer lane: a tab row of overlapping datasets is a tab row a reader cannot+ add up.++ Loads the id, scope and staleness of every record rather than grouping in+ SQL: two of the currencies are derived from the record's scope and+ staleness by :func:`effective_currency`, so no ``GROUP BY`` over the+ acceptance table can produce them. Three columns per row, which is less+ than ``get_decision_health_summary`` already pays for whole rows.+ """+ rows = (+ await session.execute(+ select(+ DecisionRecord.id,+ DecisionRecord.affected_files_json,+ DecisionRecord.affected_modules_json,+ DecisionRecord.staleness_score,+ ).where(+ DecisionRecord.repository_id == repository_id,+ # Tombstoned 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(),+ ),+ )+ )+ ).all()++ latest_seq = (+ select(+ DecisionAcceptance.decision_id.label("did"),+ func.max(DecisionAcceptance.seq).label("seq"),+ )+ .where(DecisionAcceptance.repository_id == repository_id)+ .group_by(DecisionAcceptance.decision_id)+ .subquery()+ )+ stored = dict(+ (+ await session.execute(+ select(+ DecisionAcceptance.decision_id, DecisionAcceptance.currency+ ).join(+ latest_seq,+ (DecisionAcceptance.decision_id == latest_seq.c.did)+ & (DecisionAcceptance.seq == latest_seq.c.seq),+ )+ )+ ).all()+ )++ counts = {+ "candidates": 0,+ "active": 0,+ "needs_review": 0,+ "uncheckable": 0,+ "history": 0,+ "governing": 0,+ "total": len(rows),+ }+ for did, files_json, modules_json, staleness in rows:+ acceptance = stored.get(did)+ if acceptance is None:+ counts["candidates"] += 1+ continue+ has_scope = bool(json.loads(files_json or "[]")) or bool(+ json.loads(modules_json or "[]")+ )+ currency = effective_currency(+ acceptance, has_scope=has_scope, staleness=staleness or 0.0+ )+ counts["history" if currency in ("superseded", "dismissed") else currency] += 1+ if is_governing(currency):+ counts["governing"] += 1+ return counts++async def current_currency(session: AsyncSession, record: DecisionRecord) -> str | None:"""Effective currency for *record*, or ``None`` if it is a candidate."""acceptance = await latest_acceptance(session, record.id)diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.pyindex 6d571da5b..9df673568 100644--- a/packages/core/src/repowise/core/persistence/crud/decisions.py+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py@@ -14,6 +14,7 @@ import structlogfrom sqlalchemy import case, delete, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.decisions.lifecycle import DECISION_STATUS_ORDERfrom repowise.core.analysis.decisions.provenance import (SOURCE_RANK,compute_confidence,@@ -73,6 +74,50 @@ def _merge_status(existing: str, incoming: str) -> str:return incoming+def _dedup_query(+ repository_id: str,+ title: str,+ *,+ source: str,+ evidence_file: str | None,+) -> Any:+ """The identity :func:`upsert_decision` deduplicates on.++ ``evidence_file`` may be NULL, which no equality test matches, so the two+ cases are separate clauses. Shared with :func:`find_decision_by_title` so a+ caller can ask what an upsert would land on before it lands on it.+ """+ q = select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id,+ DecisionRecord.title == title,+ DecisionRecord.source == source,+ )+ if evidence_file is not None:+ return q.where(DecisionRecord.evidence_file == evidence_file)+ return q.where(DecisionRecord.evidence_file.is_(None))+++async def find_decision_by_title(+ session: AsyncSession,+ repository_id: str,+ title: str,+ *,+ source: str = "cli",+ evidence_file: str | None = None,+) -> DecisionRecord | None:+ """The record an :func:`upsert_decision` with these arguments would update.++ Exists so a caller can tell "this creates a record" from "this overwrites+ one" before writing. The create endpoint needs the difference: overwriting+ an accepted decision with a scopeless body would clear the scope it governs+ and leave its acceptance row behind.+ """+ result = await session.execute(+ _dedup_query(repository_id, title, source=source, evidence_file=evidence_file)+ )+ return result.scalar_one_or_none()++async def upsert_decision(session: AsyncSession,*,@@ -107,16 +152,9 @@ async def upsert_decision(context = context or ""decision = decision or ""- # Build the WHERE clause — evidence_file may be NULL- q = select(DecisionRecord).where(- DecisionRecord.repository_id == repository_id,- DecisionRecord.title == title,- DecisionRecord.source == source,+ q = _dedup_query(+ repository_id, title, source=source, evidence_file=evidence_file)- if evidence_file is not None:- q = q.where(DecisionRecord.evidence_file == evidence_file)- else:- q = q.where(DecisionRecord.evidence_file.is_(None))# No write path creates authority. ``active`` here would be a status a# caller asserted rather than an acceptance anyone performed; the caller@@ -189,6 +227,8 @@ async def list_decisions(tag: str | None = None,module: str | None = None,include_proposed: bool = True,+ accepted: bool | None = None,+ include_dismissed: bool = False,limit: int = 100,offset: int = 0,sort: str = "priority",@@ -198,6 +238,17 @@ async def list_decisions(Dismissed records are tombstones and only show up when explicitly askedfor via ``status="dismissed"``.+ ``accepted`` filters on the acceptance join rather than the status column:+ ``False`` is every candidate, ``True`` every decision. It is applied in SQL,+ before the page is cut, because a caller paging a lane needs the page to be+ of that lane. Filtering after the cut returned an empty Candidates page on a+ store whose first fifty rows by priority were all statused ``active``.++ ``include_dismissed`` keeps the tombstones in without narrowing to them.+ A candidate that was dismissed should stay hidden, but a *decision* that was+ accepted and then withdrawn is history somebody needs to be able to read,+ and ``dismiss_candidate`` writes ``status="dismissed"`` for both.+``sort`` controls ordering:* ``"priority"`` (default) — what a reader needs first. Confirmed rules@@ -212,7 +263,8 @@ async def list_decisions(if status is not None:q = q.where(DecisionRecord.status == status)else:- q = q.where(DecisionRecord.status != "dismissed")+ if not include_dismissed:+ q = q.where(DecisionRecord.status != "dismissed")if not include_proposed:q = q.where(DecisionRecord.status != "proposed")if source is not None:@@ -224,21 +276,32 @@ async def list_decisions(if module is not None:# Match exact module path in JSON arrayq = q.where(DecisionRecord.affected_modules_json.contains(f'"{module}"'))+ if accepted is not None:+ from .authority import accepted_predicate++ predicate = accepted_predicate()+ q = q.where(predicate if accepted else ~predicate)q = q.order_by(*_decision_order(sort)).limit(limit).offset(offset)result = await session.execute(q)return list(result.scalars().all())-# Lower sorts first. Active is a rule the team stands behind; proposed is a-# candidate; superseded and deprecated are history.-_STATUS_RANK = {"active": 0, "proposed": 1, "superseded": 2, "deprecated": 3}+# Lower sorts first, from the one ladder in lifecycle. ``dismissed`` is in the+# ladder but not here: this rank also zero-fills ``count_decisions_by_status``,+# which excludes dismissed rows, so a key for it would report a count of zero+# for rows the query never looked at.+_STATUS_RANK = {+ status: rank+ for rank, status in enumerate(DECISION_STATUS_ORDER)+ if status != "dismissed"+}def _decision_order(sort: str) -> tuple[Any, ...]:"""ORDER BY terms for :func:`list_decisions`."""if sort == "recent":return (DecisionRecord.created_at.desc(),)- rank = case(_STATUS_RANK, value=DecisionRecord.status, else_=4)+ rank = case(_STATUS_RANK, value=DecisionRecord.status, else_=len(DECISION_STATUS_ORDER))return (rank,DecisionRecord.confidence.desc(),@@ -1277,12 +1340,21 @@ async def get_decision_health_summary(session: AsyncSession,repository_id: str,) -> dict:- """Return decision health: counts by status, stale decisions, ungoverned hotspots.+ """Return decision health: counts by lane, stale decisions, ungoverned hotspots.The three list fields are returned ranked worst-first: stale by staleness,proposed by confidence, ungoverned hotspots by temporal hotspot score. Acaller that shows only the first few shows the few that matter.Callers may truncate; they must not re-order.++ Counts the acceptance, not the status column. The key names are the ones+ every caller already renders, and they keep their product meaning:+ ``active`` is what governs, ``proposed`` is what nobody has accepted. What+ changed is that a record reaches ``active`` here by having an acceptance,+ the same way it does on every other governance read. Counting the column+ made this the one surface still reporting a hundred governing decisions on+ a store whose acceptances were empty, and it fed ``ungoverned_hotspots``,+ so unaccepted records were also suppressing the files nothing governs."""result = await session.execute(select(DecisionRecord).where(@@ -1290,6 +1362,9 @@ async def get_decision_health_summary())all_decisions = list(result.scalars().all())+ from .authority import decision_currencies++ currencies = await decision_currencies(session, repository_id, all_decisions)counts = {"active": 0,@@ -1298,7 +1373,7 @@ async def get_decision_health_summary("superseded": 0,"dismissed": 0,"stale": 0,- # Active records naming no file. They score 0.0 because the staleness+ # Accepted records naming no file. They score 0.0 because the staleness# question cannot be asked of them, which renders identically to a# record whose code genuinely has not moved — so they are counted# separately rather than banked as fresh.@@ -1307,21 +1382,38 @@ async def get_decision_health_summary(stale_decisions: list[DecisionRecord] = []proposed_decisions: list[DecisionRecord] = []- # Collect all governed files from active decisions+ # Files an *accepted* decision names. A candidate naming a hotspot does not+ # make it governed, and counting one did: it removed the file from+ # ``ungoverned_hotspots``, which is the list whose whole job is to say+ # where nobody has decided anything.governed_files: set[str] = set()for d in all_decisions:- counts[d.status] = counts.get(d.status, 0) + 1- if d.status == "active":- if d.staleness_score >= 0.5:- counts["stale"] += 1- stale_decisions.append(d)- affected_files = json.loads(d.affected_files_json)- if not affected_files:- counts["unscoped"] += 1- for fp in affected_files:- governed_files.add(fp)- elif d.status == "proposed":- proposed_decisions.append(d)+ currency = currencies.get(d.id)+ if currency is None:+ # No acceptance, so it does not govern. A retired one is not+ # awaiting review either: it keeps the status that retired it and+ # stays out of the queue, which is the one thing a tombstone must+ # never be counted as.+ if d.status in ("dismissed", "deprecated", "superseded"):+ counts[d.status] = counts.get(d.status, 0) + 1+ else:+ counts["proposed"] += 1+ proposed_decisions.append(d)+ continue+ if currency == "superseded":+ counts["superseded"] += 1+ continue+ if currency == "dismissed":+ counts["dismissed"] += 1+ continue+ counts["active"] += 1+ if currency == "needs_review":+ counts["stale"] += 1+ stale_decisions.append(d)+ if currency == "uncheckable":+ counts["unscoped"] += 1+ for fp in json.loads(d.affected_files_json):+ governed_files.add(fp)# Find ungoverned hotspots, hottest first. Sorting these by path put the file# most in need of a decision behind whatever sorts alphabetically first,diff --git a/packages/server/src/repowise/server/mcp_server/_answer_context.py b/packages/server/src/repowise/server/mcp_server/_answer_context.pyindex 7af1323d3..233b58fa3 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_context.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_context.py@@ -27,6 +27,8 @@ from typing import Anyfrom sqlalchemy import select+from repowise.core.analysis.decisions.lifecycle import is_governing+from repowise.core.persistence.crud.authority import decision_currenciesfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import DecisionRecord, GitMetadata@@ -132,8 +134,13 @@ async def fetch_relevant_decisions(Scans active+proposed decisions (skips deprecated/superseded — those arehistorical and shouldn't drive a current answer). Ranks by overlap withtarget_paths: a decision touching three of the top hits is more relevant- than one touching only the fifth. Ties broken by status preference- (active > proposed) and confidence.+ than one touching only the fifth. Ties broken by lane (an accepted decision+ over a candidate) and confidence.++ Each row carries the lane, not the status column, because these rows are+ rendered into a model prompt. A candidate labelled ``active`` reads to the+ model as something the repository has settled on, which is exactly the+ claim nobody has made about it."""if not target_paths:return []@@ -146,6 +153,7 @@ async def fetch_relevant_decisions())all_decisions = list(res.scalars().all())+ currencies = await decision_currencies(session, repo_id, all_decisions)scored: list[tuple[int, float, DecisionRecord]] = []for d in all_decisions:@@ -156,25 +164,30 @@ async def fetch_relevant_decisions(overlap = len(affected & targets_set)if overlap == 0:continue- # Active outranks proposed at the same overlap; confidence breaks- # ties within a status. Negative tuple element so higher = better- # after ascending sort.- status_rank = 0 if d.status == "active" else 1- scored.append((-overlap, status_rank, d))+ # An accepted decision outranks a candidate at the same overlap;+ # confidence breaks ties within a lane. Negative tuple element so+ # higher = better after ascending sort.+ lane_rank = 0 if is_governing(currencies.get(d.id, "")) else 1+ scored.append((-overlap, lane_rank, d))scored.sort(key=lambda t: (t[0], t[1], -(t[2].confidence or 0.0)))selected = [d for _, _, d in scored[:limit]]- return [_decision_to_dict(d) for d in selected]+ return [_decision_to_dict(d, currencies.get(d.id)) for d in selected]++def _decision_to_dict(d: DecisionRecord, currency: str | None) -> dict:+ """Compact projection — only fields the LLM needs to ground rationale.-def _decision_to_dict(d: DecisionRecord) -> dict:- """Compact projection — only fields the LLM needs to ground rationale."""+ ``lane`` is ``accepted`` or ``candidate``, and it replaces the status+ column because this string is rendered verbatim into a model prompt.+ """rationale = (d.rationale or "").strip()if len(rationale) > _DECISION_RATIONALE_CHARS:rationale = rationale[:_DECISION_RATIONALE_CHARS].rstrip() + "…"return {"title": d.title,- "status": d.status,+ "lane": "accepted" if currency is not None else "candidate",+ "currency": currency,"decision": (d.decision or "").strip(),"rationale": rationale,}@@ -215,7 +228,7 @@ async def build_structured_prelude(sections.append(f"Recent significant commits: {commits_line}")if decisions:- titles = "; ".join(f"{d['title']} ({d['status']})" for d in decisions)+ titles = "; ".join(f"{d['title']} ({d['lane']})" for d in decisions)sections.append(f"Decision records touching these files: {titles}")if not sections:@@ -332,7 +345,7 @@ def _format_decisions_block(decisions: list[dict]) -> str:"""Pull the ADRs to the front of the prompt where the LLM grounds intent."""lines = ["## Architectural decisions touching these files"]for i, d in enumerate(decisions, start=1):- lines.append(f"[D{i}] {d['title']} ({d['status']})")+ lines.append(f"[D{i}] {d['title']} ({d['lane']})")if d.get("decision"):lines.append(f" decision: {d['decision']}")if d.get("rationale"):diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex b77ac832d..0b3255b9d 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -123,6 +123,11 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {# Every tail trimmed before any lane is dropped, cheapest loss# first. Episodes last here; the path fitter sheds them first for a# different reason, documented on _fit_path_response.+ # Candidates before accepted decisions: a candidate is a review+ # request, so losing one to the budget costs the reader nothing+ # they were meant to act on now.+ "history[]",+ "candidates[]","decisions[]","git_archaeology.file_commits[]","git_archaeology.cross_references[]",@@ -136,6 +141,8 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"git_archaeology.git_log","related_documentation","code_rationale",+ "history",+ "candidates","origin_story",),expansion_argument=None,diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex 909966747..1ee8c5044 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -13,6 +13,7 @@ from typing import Anyfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.decisions.lifecycle import is_governingfrom repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRYfrom repowise.core.persistence.models import (Repository,@@ -462,7 +463,12 @@ def _build_origin_story(}-def _sibling_coverage(file_path: str, governing: list[dict], all_decisions: list) -> float | None:+def _sibling_coverage(+ file_path: str,+ governing: list[dict],+ all_decisions: list,+ accepted_ids: set[str],+) -> float | None:"""Fraction of sibling-file decisions that also cover *file_path* (None if no siblings).Both sides count accepted records only. Filtering the numerator alone read@@ -474,7 +480,7 @@ def _sibling_coverage(file_path: str, governing: list[dict], all_decisions: listfile_decision_titles = {d["title"] for d in governing}for d in all_decisions:- if getattr(d, "status", None) != "active":+ if getattr(d, "id", None) not in accepted_ids:continueaffected = json.loads(d.affected_files_json)for af in affected:@@ -513,8 +519,9 @@ def _alignment_score() -> tuple:"""Derive the (score, explanation) tuple from accepted decisions.- Only accepted (``active``) records score. A proposed record is a candidate- awaiting review: counting one as governance let a machine-inferred record+ Only accepted records score, and accepted means an acceptance row exists,+ not that the status column reads ``active``. A candidate awaiting review+ scores nothing: counting one as governance let a machine-inferred recordreport a file as aligned with a decision nobody had agreed to."""if stale and len(stale) >= len(accepted) / 2:@@ -546,8 +553,19 @@ def _compute_alignment(file_path: str,governing: list[dict],all_decisions: list,+ currencies: dict[str, str],) -> dict:- """Compute how well a file aligns with established architectural decisions."""+ """Compute how well a file aligns with established architectural decisions.++ *currencies* maps decision id to effective currency for every **accepted**+ record in the repository; a record absent from it is a candidate. That map+ is the authority test, and it is a required argument rather than an+ optional one on purpose. This function previously read+ ``status == "active"`` and called the result ``accepted``, so a record+ written straight to the column with no acceptance behind it made a file+ report as governed. Defaulting the argument would have left that path+ reachable from any caller that forgot it.+ """if not governing:return {"score": "none",@@ -563,15 +581,37 @@ def _compute_alignment("sibling_coverage": None,}- accepted = [d for d in governing if d["status"] == "active"]- deprecated = [d for d in governing if d["status"] in ("deprecated", "superseded")]- stale = [d for d in accepted if d.get("staleness_score", 0) > 0.5]- candidates = [d for d in governing if d["status"] == "proposed"]+ # Three lanes, split by the acceptance rather than by the column: what a+ # person accepted and still binds, what they accepted and then withdrew,+ # and what nobody has reviewed.+ accepted = [d for d in governing if is_governing(currencies.get(d["id"], ""))]+ deprecated = [+ d+ for d in governing+ if currencies.get(d["id"]) in ("superseded", "dismissed")+ ]+ # Repository-wide, not scoped to the matched records: the sibling+ # denominator is drawn from decisions naming *other* files in the same+ # directory, none of which appear in ``governing``.+ accepted_ids = {+ did for did, currency in currencies.items() if is_governing(currency)+ }+ # ``needs_review`` is the derived answer to "have the files it names+ # moved", which is the same 0.5 threshold this used to apply by hand.+ stale = [d for d in accepted if currencies.get(d["id"]) == "needs_review"]+ candidates = [d for d in governing if d["id"] not in currencies]+ # Accepted, and neither binding nor withdrawn: it names nothing the+ # repository can be asked about. Counted on its own so the four lanes add+ # up to ``governing_count``; without it a reader could subtract them and+ # find records unaccounted for with nothing saying where they went.+ uncheckable = [d for d in governing if currencies.get(d["id"]) == "uncheckable"]dir_path = "/".join(file_path.split("/")[:-1])# Scoped to accepted records for the same reason the score is: a sibling- # pattern established only by proposals is not an established pattern.- sibling_coverage = _sibling_coverage(file_path, accepted, all_decisions)+ # pattern established only by candidates is not an established pattern.+ sibling_coverage = _sibling_coverage(+ file_path, accepted, all_decisions, accepted_ids+ )score, explanation = _alignment_score(accepted, deprecated, stale, candidates, dir_path, sibling_coverage@@ -580,13 +620,16 @@ def _compute_alignment(return {"score": score,"explanation": explanation,- # Unchanged meaning: how many records name this file at all. The- # authority split is carried by active_count / candidate_count, which- # is what the score reads.+ # Unchanged meaning, and deliberately not renamed: how many records+ # name this file at all, which is what every existing consumer reads+ # it as. The authority split is carried by the four counts below, and+ # they sum to it: accepted + withdrawn + uncheckable + candidate."governing_count": len(governing),"active_count": len(accepted),"candidate_count": len(candidates),+ # Accepted once and withdrawn since, whether superseded or dismissed."deprecated_count": len(deprecated),+ "uncheckable_count": len(uncheckable),"stale_count": len(stale),"sibling_coverage": round(sibling_coverage, 2) if sibling_coverage is not None else None,}diff --git a/packages/server/src/repowise/server/mcp_server/_why_evidence.py b/packages/server/src/repowise/server/mcp_server/_why_evidence.pyindex 458b9ee8a..c8fc2a037 100644--- a/packages/server/src/repowise/server/mcp_server/_why_evidence.py+++ b/packages/server/src/repowise/server/mcp_server/_why_evidence.py@@ -533,7 +533,16 @@ def annotate_response_evidence(lineage_record, repository, resolved_commits=resolved_commits)- for key in ("decisions", "stale_decisions", "proposed_awaiting_review"):+ # ``candidates`` is annotated like every other lane. A candidate is the row+ # a reader is most likely to want the provenance of, because deciding+ # whether to accept it is the whole reason it is on the page.+ for key in (+ "decisions",+ "candidates",+ "history",+ "stale_decisions",+ "proposed_awaiting_review",+ ):for row in result.get(key) or []:if isinstance(row, dict):annotate_decision(row)diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex 9e23f43e0..36cbf89f3 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -22,13 +22,14 @@ from repowise.core.generation.onboarding.slots import (PROMOTED_SLOTS,)from repowise.core.persistence.crud import (- get_health_metrics as _get_health_metrics,+ accepted_predicate,+ get_hotspot_file_paths,)from repowise.core.persistence.crud import (- get_health_summary as _get_health_summary,+ get_health_metrics as _get_health_metrics,)from repowise.core.persistence.crud import (- get_hotspot_file_paths,+ get_health_summary as _get_health_summary,)from repowise.core.persistence.crud import (get_kg_layers as _get_kg_layers,@@ -836,7 +837,13 @@ async def _build_recent_reversals(session: Any, repository: Any) -> list[dict[stasync def _build_key_decisions(session: Any, repository: Any, exclude_spec: Any = None) -> dict[str, Any]:- """Top active decisions + recent reversals (Phase 4A)."""+ """The repository's accepted decisions, and its recent reversals.++ ``accepted_predicate()`` rather than the status column: this block is the+ first thing an agent reads about a repository, so a machine-inferred+ record nobody agreed to must not appear under a heading that presents it+ as what the repository has settled on.+ """try:# Over-fetch, then drop records anchored entirely in excluded paths# (vendored venvs, local-only scratch dirs mined before the exclude@@ -846,6 +853,7 @@ async def _build_key_decisions(.where(DecisionRecord.repository_id == repository.id,DecisionRecord.status == "active",+ accepted_predicate(),).order_by(DecisionRecord.confidence.desc()).limit(25)diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.pyindex e723612a8..1c0b87b55 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py@@ -7,6 +7,7 @@ from typing import Anyfrom sqlalchemy import selectfrom repowise.core.analysis.risk_semantics import structural_impact_contract+from repowise.core.persistence.crud.authority import decision_currenciesfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.decision_graph import list_conflict_edgesfrom repowise.core.persistence.models import DecisionNodeLink, DecisionRecord@@ -388,13 +389,23 @@ async def _governance_directive(ctx: Any, changed_files: list[str]) -> list[dictby_file: dict[str, list[Any]] = {}for record, node_id in linked_rows:by_file.setdefault(node_id, []).append(record)+ # A directive tells a reviewer their change is constrained, so only+ # an accepted decision may raise one. Without the join a candidate+ # nobody had reviewed produced a stale-governance warning against a+ # pull request.+ currencies = await decision_currencies(+ _gr_session, _gr_repo_id, [r for r, _ in linked_rows]+ )seen_dr_ids: set[str] = set()for cf in changed_files:for dr in by_file.get(cf, []):if dr.id in seen_dr_ids:continueseen_dr_ids.add(dr.id)- reason = _governance_reason(dr, conflict_decision_ids)+ currency = currencies.get(dr.id)+ if currency is None:+ continue+ reason = _governance_reason(dr, currency, conflict_decision_ids)if reason is None:continuegovernance_risk.append(@@ -403,6 +414,7 @@ async def _governance_directive(ctx: Any, changed_files: list[str]) -> list[dict"decision_id": dr.id,"title": dr.title,"status": dr.status,+ "currency": currency,"reason": reason,})@@ -411,12 +423,19 @@ async def _governance_directive(ctx: Any, changed_files: list[str]) -> list[dictreturn governance_risk-def _governance_reason(dr: Any, conflict_decision_ids: set[str]) -> str | None:- """Map a governing decision to a directive reason, or None when clean."""- staleness = dr.staleness_score or 0.0- if dr.status == "active" and staleness >= 0.5:+def _governance_reason(+ dr: Any, currency: str, conflict_decision_ids: set[str]+) -> str | None:+ """Map an accepted decision to a directive reason, or None when clean.++ *currency* is the effective currency from the acceptance, so the caller has+ already established the record is a decision rather than a candidate.+ ``needs_review`` is the derived answer to "have the files it names moved",+ which is the staleness test this used to apply to the column by hand.+ """+ if currency == "needs_review":return "stale_governance"- if dr.status == "superseded":+ if currency == "superseded":return "superseded_decision"if dr.id in conflict_decision_ids:return "contradicted_decision"diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex e69ee2380..9ce58c5e1 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -12,6 +12,8 @@ from typing import Anyfrom sqlalchemy import selectfrom repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIX+from repowise.core.analysis.decisions.lifecycle import is_governing, status_rank+from repowise.core.persistence.crud.authority import decision_currenciesfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (DecisionEdge,@@ -516,6 +518,12 @@ async def _why_health_dashboard(repo: str | None) -> dict:#: Governing records kept, best-first. Past ~8 the tail is review-queue noise._MAX_PATH_DECISIONS = 8+#: Candidates inlined beside a path's decisions. Deliberately far below the+#: decisions cap: this lane exists so a reader knows a queue is there and can+#: go and work it, not so they can work it from inside a get_why response. A+#: live index carries 380 candidates, and a hot path can be named by dozens.+_MAX_PATH_CANDIDATES = 3+#: Paths kept per record. The array answers "how wide is this decision", which#: a head plus a total answers as well as 241 paths do._MAX_AFFECTED_FILES = 10@@ -531,9 +539,10 @@ _MAX_COMMIT_TEXT_CHARS = 320#: ``omission_marker`` + ``_meta.omitted`` *after* the last size check._COLLECTOR_HEADROOM_CHARS = 600-#: Sort order for governing records: what governs beats what was proposed-#: beats what is retired; then confidence; then freshness.-_PATH_STATUS_ORDER = {"active": 0, "proposed": 1, "deprecated": 2, "superseded": 3}+# Ranking uses ``status_rank`` from lifecycle. The local table this file kept+# had drifted from it: it ranked ``deprecated`` ahead of ``superseded`` while+# the list endpoint ranked them the other way, so a record moved position+# depending on which surface was asked.# --- Search-mode caps -------------------------------------------------------@@ -594,7 +603,7 @@ _MAX_HEALTH_UNGOVERNED = 8def _path_decision_sort_key(d: Any) -> tuple[int, float, float]:return (- _PATH_STATUS_ORDER.get(d.status, 4),+ status_rank(d.status),-(d.confidence or 0.0),d.staleness_score or 0.0,)@@ -783,10 +792,12 @@ def _fit_path_response(1. Drop ``origin_story.linked_decisions``, which re-inlines each record'stitle, rationale and matched commits — all of it already in``decisions``.- 2. Drop governing records from the tail, all the way to none if it comes+ 2. Drop the candidate lane whole. A candidate is a review request, and a+ response that cannot afford the rules it must not spend on the queue.+ 3. Drop governing records from the tail, all the way to none if it comesto that. They are sorted best-first, so the tail is review-queue noise,and an empty list plus a marker beats a rejected response.- 3. Trim the fallback blocks the ungoverned branch adds (``code_rationale``,+ 4. Trim the fallback blocks the ungoverned branch adds (``code_rationale``,then ``git_archaeology``) to a tail, dropping them whole only if that isnot enough, then ``origin_story``. What survives — mode, path,alignment, ``_meta`` — is bounded.@@ -832,7 +843,23 @@ def _fit_path_response(# ``episodes[]`` floors at one row, so the whole-block entry behind it is# what still empties the lane before the decisions loop below. Trimming# first is why mild pressure costs rows: this served 0 of 20.- _shed("origin_story.linked_decisions", "episodes[]", "episodes")+ # Candidates first of everything: they are the one lane whose whole+ # purpose is to be reviewed later, so under pressure they are the cheapest+ # thing in the response to lose. Their note goes with them, because a+ # sentence counting candidates that are no longer in the payload is worse+ # than no sentence.+ _shed(+ "origin_story.linked_decisions",+ "history[]",+ "history",+ "candidates[]",+ "candidates",+ )+ for lane_key in ("candidates", "history"):+ if not result_data.get(lane_key):+ result_data.pop(f"{lane_key}_note", None)++ _shed("episodes[]", "episodes")decisions: list = result_data.get("decisions") or []while decisions and _over():@@ -908,35 +935,68 @@ async def _why_path(query: str, repo: str | None) -> dict:if query in json.loads(d.affected_files_json)or query in json.loads(d.affected_modules_json)]+ # The authority split, and the only test that makes it: a record with+ # no acceptance row is a candidate whatever its status column says.+ # Computed over every record in the repository, because the sibling+ # coverage inside alignment reads records this path did not match.+ currencies = await decision_currencies(session, repository.id, all_decisions)+# Rank before capping, so the 8 that survive are the 8 that govern —# not whichever 8 the table scan happened to yield first.matched.sort(key=_path_decision_sort_key)lineage_by_id = await _lineage_for_records(session, matched, all_decisions)- governing = []- for rank, d in enumerate(matched):+ governing: list[dict] = []+ candidates: list[dict] = []+ retired: list[dict] = []+ for d in matched:# Walk supersedes/refines back to roots so the answer is a# lineage chain (sessions → JWT → OAuth2), not a flat list.lineage = lineage_by_id.get(d.id, [])entry = _governing_decision_entry(d, json.loads(d.affected_files_json), lineage, collector)- # Ask git whether the top record still holds — and only the top- # one. The query is ~60 ms, which is affordable once inside an MCP- # call and is not affordable eight times; the record ranked first- # is the one a reader acts on. Everything below it keeps the- # stored proportion, which needed no subprocess to compute.- if rank == 0:- sentence = await asyncio.to_thread(- describe_decision_currency,- ctx.path,- created_at=d.created_at,- nodes=json.loads(d.affected_files_json or "[]"),- )- if sentence:- entry["still_true"] = sentence- governing.append(entry)-- origin_story = _build_origin_story(query, git_meta, governing)+ currency = currencies.get(d.id)+ if currency is None:+ # Never accepted. It goes in its own lane, labelled, rather+ # than into the list an agent reads as the rules for this file.+ entry["review_state"] = "open"+ candidates.append(entry)+ continue+ entry["currency"] = currency+ if is_governing(currency):+ governing.append(entry)+ else:+ # Accepted once and withdrawn since. Not a rule and not a+ # review request, so it gets a third lane rather than being+ # dropped: on a file whose only record was superseded, dropping+ # it left the answer with nothing to say about the one thing+ # anybody had ever decided there.+ retired.append(entry)++ # Ask git whether the top governing record still holds — and only the+ # top one. The query is ~60 ms, which is affordable once inside an MCP+ # call and is not affordable eight times; the record ranked first is+ # the one a reader acts on. Everything below it keeps the stored+ # proportion, which needed no subprocess to compute. A candidate never+ # gets the check: it is not something anyone should be acting on.+ if governing:+ top = next(d for d in matched if d.id == governing[0]["id"])+ sentence = await asyncio.to_thread(+ describe_decision_currency,+ ctx.path,+ created_at=top.created_at,+ nodes=json.loads(top.affected_files_json or "[]"),+ )+ if sentence:+ governing[0]["still_true"] = sentence++ # Every lane: the origin story is history, and a commit that matches a+ # candidate's or a retired record's title is still the commit that+ # explains the file. It is evidence, not instruction, so nothing here+ # needs the authority test.+ origin_story = _build_origin_story(+ query, git_meta, governing + candidates + retired+ )result_data: dict[str, Any] = {"mode": "path",@@ -946,22 +1006,39 @@ async def _why_path(query: str, repo: str | None) -> dict:# Alignment is scored over every matching record, not just the# ones that survived the cap — it is a coverage number, and# capping its input would make a well-governed hotspot look thin.- # It reads only status/staleness/title, so the cheap projection is- # the whole of what it needs.+ # It reads the id, the title and the acceptance map, so the cheap+ # projection is the whole of what it needs."alignment": _compute_alignment(query,- [- {- "title": d.title,- "status": d.status,- "staleness_score": d.staleness_score,- }- for d in matched- ],+ [{"id": d.id, "title": d.title} for d in matched],all_decisions,+ currencies,),}- # --- Fallback: git archaeology when no decisions found ---+ if candidates:+ # Named, counted and separated from the rules. An agent reading+ # this must be able to tell a request to review something from an+ # instruction to follow it, without parsing a status string.+ result_data["candidates"] = candidates+ result_data["candidates_note"] = (+ f"{len(candidates)} candidate(s) mention this path and none of them "+ "govern it. Nobody has accepted them, so they are a review "+ "request, not a rule. Accept one with "+ "`repowise decision confirm <id> --scope <path>`."+ )++ if retired:+ # Named as history, never as a rule. A reader asking why a file+ # looks the way it does is owed "this was decided and then+ # replaced", which is the sentence a dropped record cannot say.+ result_data["history"] = retired+ result_data["history_note"] = (+ f"{len(retired)} decision(s) governing this path were accepted "+ "and have since been superseded or withdrawn. They are history, "+ "not rules."+ )++ # --- Fallback: git archaeology when no accepted decision governs ---if not governing:result_data["git_archaeology"] = await _git_archaeology_fallback(query,@@ -1018,6 +1095,16 @@ async def _why_path(query: str, repo: str | None) -> dict:collector,label=f"path decisions beyond cap={_MAX_PATH_DECISIONS}",)+ for lane_key in ("candidates", "history"):+ if result_data.get(lane_key):+ cap_collection(+ result_data,+ lane_key,+ result_data[lane_key],+ _MAX_PATH_CANDIDATES,+ collector,+ label=f"path {lane_key} beyond cap={_MAX_PATH_CANDIDATES}",+ )return _fit_path_response(result_data, ctx.path, collector=collector)@@ -1081,7 +1168,7 @@ def _score_keyword_matches((-score,-_score_decision(d, set(terms), target_set),- _PATH_STATUS_ORDER.get(d.status, 4),+ status_rank(d.status),d,))diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.pyindex 17a1cccc5..6b1672ad6 100644--- a/packages/server/src/repowise/server/routers/decisions.py+++ b/packages/server/src/repowise/server/routers/decisions.py@@ -9,6 +9,7 @@ from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.decisions.lifecycle import is_governingfrom repowise.core.persistence import crud, decision_graphfrom repowise.core.persistence.models import DecisionEvidencefrom repowise.server.deps import get_db_session, verify_api_key@@ -23,6 +24,7 @@ from repowise.server.schemas import (DecisionGraphNode,DecisionGraphResponse,DecisionHealthResponse,+ DecisionLaneCountsResponse,DecisionLineageEntry,DecisionLineageResponse,DecisionRecordResponse,@@ -39,6 +41,30 @@ router = APIRouter()+def _in_lane(currency: str | None, lane: str) -> bool:+ """Whether a record at *currency* belongs in review lane *lane*.++ ``None`` means no acceptance row, which is the whole definition of a+ candidate. The accept/candidate half of this is pushed into SQL by+ ``list_decisions(accepted=...)``; only the currency, which comes from the+ record's scope and staleness rather than from the acceptance row, is+ resolved here.+ """+ if lane == "candidates":+ return currency is None+ if lane == "governing":+ return currency is not None and is_governing(currency)+ if lane == "history":+ return currency in ("superseded", "dismissed")+ return currency == lane+++#: How many accepted records a currency-derived lane scans before paging in+#: Python. Matches the endpoint's own ``limit`` ceiling: past it the lane would+#: need the currency in SQL, which the derivation cannot give it.+_LANE_SCAN_CAP = 500++@router.get("/api/repos/{repo_id}/decisions",response_model=list[DecisionRecordResponse],@@ -50,6 +76,15 @@ async def list_decisions(tag: str | None = Query(None, description="Filter by tag"),module: str | None = Query(None, description="Filter by module path"),include_proposed: bool = Query(True),+ lane: str | None = Query(+ None,+ pattern="^(candidates|governing|active|needs_review|uncheckable|history)$",+ description=(+ "Review lane. candidates: never accepted. governing: accepted and "+ "still binding. history: accepted and withdrawn. Applied after the "+ "page is fetched, because the lane is a join and not a column."+ ),+ ),limit: int = Query(100, ge=1, le=500),offset: int = Query(0, ge=0),sort: str = Query(@@ -63,12 +98,26 @@ async def list_decisions(Each row carries an ``evidence_preview`` (the top-ranked evidence row'sverbatim quote) plus the total ``evidence_count``, so the table can show- provenance without N+1 calls to the per-decision /evidence endpoint.+ provenance without N+1 calls to the per-decision /evidence endpoint, and a+ ``currency`` naming what its acceptance currently amounts to. A row with no+ ``currency`` is a candidate: nobody has accepted it.Defaults to ``sort=priority``. Newest-first buried every confirmeddecision under the unreviewed proposals the indexer had just mined, sopage one was entirely machine guesses."""+ # The acceptance half of the lane is a SQL predicate, so a page of a lane+ # is a page of that lane. The currency half cannot be: ``needs_review`` and+ # ``uncheckable`` are derived from the record's scope and staleness. Those+ # lanes therefore over-fetch the accepted set and cut the page afterwards,+ # which is affordable because an accepted decision requires a human action+ # and the set stays small by construction.+ # Every lane but ``candidates`` filters the accepted set by currency, and a+ # currency is derived from the record rather than stored, so the page has+ # to be cut after the derivation. ``governing`` is in here for the same+ # reason as the rest: cutting first returned an empty tab on a repository+ # whose newest accepted records had all been superseded.+ derived = lane is not None and lane != "candidates"decisions = await crud.list_decisions(session,repo_id,@@ -77,11 +126,22 @@ async def list_decisions(tag=tag,module=module,include_proposed=include_proposed,- limit=limit,- offset=offset,+ accepted=None if lane is None else lane != "candidates",+ # History has to reach a decision that was accepted and then dismissed,+ # which carries a tombstone status the default listing hides.+ include_dismissed=lane == "history",+ limit=max(_LANE_SCAN_CAP, offset + limit) if derived else limit,+ offset=0 if derived else offset,sort=sort,)+ currencies = await crud.decision_currencies(session, repo_id, decisions)+ if lane is not None:+ decisions = [d for d in decisions if _in_lane(currencies.get(d.id), lane)]+ if derived:+ decisions = decisions[offset : offset + limit]items = [DecisionRecordResponse.from_orm(d) for d in decisions]+ for item in items:+ item.currency = currencies.get(item.id)ids = [d.id for d in decisions]if ids:@@ -170,6 +230,30 @@ async def decision_counts()+ "/api/repos/{repo_id}/decisions/lane-counts",+ response_model=DecisionLaneCountsResponse,+)+async def decision_lane_counts(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> DecisionLaneCountsResponse:+ """Counts per review lane.++ Separate from ``/counts``, which groups the ``status`` column. That column+ is the projection kept in step for readers that predate the acceptance+ split, so its ``active`` and this endpoint's ``active`` are different+ questions: a record can be stored active and have no acceptance at all.+ A tab row must not be labelled from the other one's answer.++ Declared above ``/{decision_id}`` for the same reason ``/counts`` is:+ FastAPI matches in declaration order.+ """+ return DecisionLaneCountsResponse(+ **await crud.count_decisions_by_lane(session, repo_id)+ )++@router.get("/api/repos/{repo_id}/decisions/graph",response_model=DecisionGraphResponse,@@ -421,7 +505,42 @@ async def create_decision(body: DecisionCreate,session: AsyncSession = Depends(get_db_session),) -> DecisionRecordResponse:- """Create a new decision record (e.g. from CLI capture via API)."""+ """Create a decision record, accepting it when it names a scope.++ Typing a decision by hand is an acceptance, but it is recorded as one+ rather than written straight into the status column, so this surface and+ the CLI agree about what made the record govern.++ A record naming no file or module is stored as a candidate instead of+ being refused, which is what ``repowise decision add`` does with the same+ input. It cannot be checked against the code and cannot reach an agent+ editing a governed file, so it cannot govern; discarding the fields the+ author did fill in would be worse. The response's ``status`` says which of+ the two happened, and a form can predict it from the same one field.+ """+ # ``upsert_decision`` dedups on the title and overwrites the scope with+ # whatever the body carries, so a second post of an accepted decision's+ # title with no files would clear the scope it governs and leave its+ # acceptance row pointing at a record that no longer binds. Refuse, and+ # name the record, rather than quietly retiring somebody's decision from a+ # call that says "create".+ existing = await crud.find_decision_by_title(+ session, repo_id, body.title, source="cli"+ )+ scoped = bool(body.affected_files or body.affected_modules)+ if existing is not None and not scoped and await crud.is_accepted(+ session, existing.id+ ):+ raise HTTPException(+ status_code=409,+ detail=(+ f"{existing.title!r} is already an accepted decision "+ f"({existing.id}). Recording it again without the files it "+ "governs would withdraw its scope. Edit it instead, or post it "+ "with affected_files."+ ),+ )+rec = await crud.upsert_decision(session,repository_id=repo_id,@@ -438,13 +557,11 @@ async def create_decision(source="cli",confidence=1.0,)- # Typing a decision by hand is an acceptance, but it is still recorded as- # one rather than written straight into the status column, so this surface- # and the CLI agree about what made the record govern.- try:- await crud.accept_decision(session, rec, accepter="web")- except crud.AcceptanceRefusedError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc+ if scoped:+ try:+ await crud.accept_decision(session, rec, accepter="web")+ except crud.AcceptanceRefusedError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from excreturn DecisionRecordResponse.from_orm(rec)diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex e716f4ab0..5ce6352f7 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -86,6 +86,7 @@ from .decisions import (DecisionGraphNode,DecisionGraphResponse,DecisionHealthResponse,+ DecisionLaneCountsResponse,DecisionLineageEntry,DecisionLineageResponse,DecisionRecordResponse,@@ -353,6 +354,7 @@ __all__ = ["DecisionGraphNode","DecisionGraphResponse","DecisionHealthResponse",+ "DecisionLaneCountsResponse","DecisionLineageEntry","DecisionLineageResponse","DecisionRecordResponse",diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.pyindex 32eba9f90..2b5871640 100644--- a/packages/server/src/repowise/server/schemas/decisions.py+++ b/packages/server/src/repowise/server/schemas/decisions.py@@ -55,6 +55,11 @@ class DecisionRecordResponse(BaseModel):# /evidence endpoint instead).evidence_count: int | None = Noneevidence_preview: EvidencePreview | None = None+ # Effective currency from the acceptance, or None for a candidate. This is+ # the authority answer; ``status`` is the projection kept in step for+ # readers that predate the split. A record can be stored ``active`` and+ # carry no currency at all, which is precisely what a candidate is.+ currency: str | None = None@classmethoddef from_orm(cls, obj: object) -> DecisionRecordResponse:@@ -113,6 +118,23 @@ class DecisionCountsResponse(BaseModel):deprecated: int+class DecisionLaneCountsResponse(BaseModel):+ """Records per review lane, from a scan of the acceptance join.++ ``candidates`` and the four currency lanes partition the repository and sum+ to ``total``; ``governing`` is the roll-up of the two that still bind, so a+ caller can state "N rules" without adding two tabs together.+ """++ candidates: int+ active: int+ needs_review: int+ uncheckable: int+ history: int+ governing: int+ total: int++class DecisionCreate(BaseModel):title: strcontext: str = ""diff --git a/packages/types/__tests__/decisions-vocabulary.test.ts b/packages/types/__tests__/decisions-vocabulary.test.tsnew file mode 100644index 000000000..478658b4d--- /dev/null+++ b/packages/types/__tests__/decisions-vocabulary.test.ts@@ -0,0 +1,168 @@+/**+ * The TypeScript half of the decision-vocabulary contract.+ *+ * `tests/fixtures/decision_vocabulary.json` is generated from the Python+ * registry and checked against it by+ * `tests/unit/analysis/test_decision_vocabulary_contract.py`. This file checks the+ * TypeScript consts against the same fixture, so a source, status, currency or+ * review state added on one side fails on the other instead of drifting.+ *+ * Order is asserted, not just membership: `DECISION_STATUSES` is a ranking.+ */+import { describe, it, expect } from "vitest";+import {+ CANDIDATE_REVIEW_STATES,+ DECISION_CURRENCIES,+ DECISION_SOURCES,+ DECISION_CURRENCY_DESCRIPTIONS,+ DECISION_CURRENCY_LABELS,+ DECISION_LANES,+ DECISION_PRESETS,+ DECISION_SOURCE_LABELS,+ DECISION_STATUSES,+ DECISION_STATUS_LABELS,+ GOVERNING_CURRENCIES,+ RETIRED_DECISION_SOURCES,+ decisionAcceptanceBlockers,+ decisionSourceLabel,+ decisionStatusRank,+ isRetiredDecisionSource,+} from "../src/decisions";+import fixture from "../../../tests/fixtures/decision_vocabulary.json";++describe("decision vocabulary matches the engine", () => {+ it("names the same sources", () => {+ expect([...DECISION_SOURCES]).toEqual(fixture.sources);+ });++ it("names the same retired sources", () => {+ expect([...RETIRED_DECISION_SOURCES]).toEqual(fixture.retired_sources);+ });++ it("ranks statuses in the same order", () => {+ expect([...DECISION_STATUSES]).toEqual(fixture.statuses);+ });++ it("names the same currencies", () => {+ expect([...DECISION_CURRENCIES]).toEqual(fixture.currencies);+ });++ it("names the same candidate review states", () => {+ expect([...CANDIDATE_REVIEW_STATES]).toEqual(+ fixture.candidate_review_states,+ );+ });++ it("labels every source a row can carry", () => {+ const labelled = Object.keys(DECISION_SOURCE_LABELS).sort();+ const expected = [...fixture.sources, ...fixture.retired_sources].sort();+ expect(labelled).toEqual(expected);+ });++ it("names the same review lanes, in the same order", () => {+ expect([...DECISION_LANES]).toEqual(fixture.review_lanes);+ });++ it("names the same capture presets", () => {+ expect([...DECISION_PRESETS]).toEqual(fixture.presets);+ });++ it("labels every status", () => {+ expect(Object.keys(DECISION_STATUS_LABELS).sort()).toEqual(+ [...fixture.statuses].sort(),+ );+ });++ it("labels and explains every currency", () => {+ const expected = [...fixture.currencies].sort();+ expect(Object.keys(DECISION_CURRENCY_LABELS).sort()).toEqual(expected);+ expect(Object.keys(DECISION_CURRENCY_DESCRIPTIONS).sort()).toEqual(expected);+ });++ it("keeps every governing currency in the vocabulary", () => {+ for (const currency of GOVERNING_CURRENCIES) {+ expect(fixture.currencies).toContain(currency);+ }+ });+});++describe("lookup helpers", () => {+ it("ranks a known status by position and an unknown one last", () => {+ expect(decisionStatusRank("active")).toBe(0);+ expect(decisionStatusRank("dismissed")).toBe(DECISION_STATUSES.length - 1);+ expect(decisionStatusRank("not_a_status")).toBe(DECISION_STATUSES.length);+ });++ it("does not reach Object.prototype for an unmapped source", () => {+ expect(decisionSourceLabel("toString")).toBe("toString");+ expect(decisionSourceLabel("constructor")).toBe("constructor");+ });++ it("returns an unmapped source verbatim rather than blank", () => {+ expect(decisionSourceLabel("something_new")).toBe("something_new");+ });++ it("recognises a retired source and not a live one", () => {+ expect(isRetiredDecisionSource("readme_mining")).toBe(true);+ expect(isRetiredDecisionSource("comment")).toBe(false);+ });+});++describe("the acceptance contract, mirrored", () => {+ const accepted = {+ rationale: "sessions did not survive a restart",+ affected_files: ["src/auth/service.py"],+ evidence_commits: ["abc1234"],+ source: "pr",+ };++ it("passes a candidate carrying reason, scope and evidence", () => {+ expect(decisionAcceptanceBlockers(accepted)).toEqual([]);+ });++ it("names the missing scope in the engine's own words", () => {+ // The exact sentence the API returns, so a surface can show one string+ // whether it predicted the refusal or received it.+ expect(+ decisionAcceptanceBlockers({ ...accepted, affected_files: [] }),+ ).toEqual(["no scope: name the files or modules it governs"]);+ });++ it("treats a blank-only scope as no scope, as the engine does", () => {+ expect(+ decisionAcceptanceBlockers({ ...accepted, affected_files: [" ", ""] }),+ ).toContain("no scope: name the files or modules it governs");+ });++ it("falls back to the decision body when there is no rationale", () => {+ expect(+ decisionAcceptanceBlockers({+ ...accepted,+ rationale: "",+ decision: "Issue signed JWTs",+ }),+ ).toEqual([]);+ });++ it("requires evidence from a mined record and not from a typed one", () => {+ const bare = { ...accepted, evidence_commits: [], evidence_file: null };+ expect(decisionAcceptanceBlockers(bare)).toEqual(["no evidence reference"]);+ expect(decisionAcceptanceBlockers({ ...bare, source: "cli" })).toEqual([]);+ });++ it("accepts an evidence file in place of a commit", () => {+ expect(+ decisionAcceptanceBlockers({+ ...accepted,+ evidence_commits: [],+ evidence_file: "docs/auth.md",+ }),+ ).toEqual([]);+ });++ it("names every gap at once rather than the first", () => {+ expect(+ decisionAcceptanceBlockers({ source: "session" }).length,+ ).toBe(3);+ });+});diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.tsindex 9e24a4f26..af339e40d 100644--- a/packages/types/src/decisions.ts+++ b/packages/types/src/decisions.ts@@ -7,25 +7,193 @@* adapters fill defaults before passing data to components.*/+// ---------------------------------------------------------------------------+// Shared vocabulary+//+// The engine owns these words. Every one below is pinned against+// `tests/fixtures/decision_vocabulary.json`, which the Python registry+// generates, by `__tests__/decisions-vocabulary.test.ts` and by+// `tests/unit/analysis/test_decision_vocabulary_contract.py`. Adding a source or a+// currency on either side without the other fails a build.+//+// Four surfaces used to keep their own copies, and they had already drifted:+// this union named a retired `readme_mining` and omitted five live sources,+// two status ladders disagreed about where `superseded` sat, and the retired+// set was hand-mirrored with nothing tying it to its source.+// ---------------------------------------------------------------------------+/**+ * `decision_records.status`, best first: a rule the team stands behind, then a+ * candidate, then history, then a tombstone. This is the sort order, not just+ * a set.+ ** `dismissed` is a tombstone and `deprecated` is a retirement, and the* difference is load-bearing: the engine skips a dismissed record on every* re-extraction and hides it from listings, where a deprecated one keeps being- * re-derived and keeps its row. The union omitted `dismissed` while the engine- * had always accepted it, which left the UI no way to say it.+ * re-derived and keeps its row.*/-export type DecisionStatus =- | "proposed"- | "active"- | "deprecated"- | "dismissed"- | "superseded";--export type DecisionSource =- | "git_archaeology"- | "inline_marker"- | "readme_mining"- | "cli";+export const DECISION_STATUSES = [+ "active",+ "proposed",+ "superseded",+ "deprecated",+ "dismissed",+] as const;++export type DecisionStatus = (typeof DECISION_STATUSES)[number];++/** The word for a status. Presentation, so the fixture pins coverage only. */+export const DECISION_STATUS_LABELS: Record<DecisionStatus, string> = {+ active: "Active",+ proposed: "Proposed",+ superseded: "Superseded",+ deprecated: "Deprecated",+ dismissed: "Dismissed",+};++/** Sort key for a status. An unknown status sorts after every known one. */+export function decisionStatusRank(status: string): number {+ const i = (DECISION_STATUSES as readonly string[]).indexOf(status);+ return i === -1 ? DECISION_STATUSES.length : i;+}++/**+ * The values `DecisionRecord.source` can carry on a live index.+ *+ * Wider than the capture-source registry the settings panel switches on and+ * off: `commit` and `llm_inferred` are stored provenance with no toggle, and+ * broad session discovery stores `session` rather than a value of its own.+ */+export const DECISION_SOURCES = [+ "adr",+ "cli",+ "comment",+ "commit",+ "git_archaeology",+ "inline_marker",+ "llm_inferred",+ "pr",+ "session",+] as const;++export type DecisionSource = (typeof DECISION_SOURCES)[number];++/**+ * Sources the engine no longer emits and whose rows were purged with them. A+ * record carrying one cannot exist, so offering it as a filter is a control+ * that cannot act. `code_comment` is retired and `comment` is not: they are+ * different values and a live index still carries the second.+ */+export const RETIRED_DECISION_SOURCES = [+ "code_comment",+ "readme_mining",+ "changelog",+] as const;++export type RetiredDecisionSource = (typeof RETIRED_DECISION_SOURCES)[number];++/**+ * Column labels for every source a row can carry, retired ones included so an+ * old record still renders a word rather than a raw key.+ *+ * Presentation, so it is not in the fixture. The test asserts it covers every+ * live and retired source, which is the drift that actually happened: one+ * column mixed "Docs" with a bare `pr`.+ */+export const DECISION_SOURCE_LABELS: Record<+ DecisionSource | RetiredDecisionSource,+ string+> = {+ adr: "ADR",+ cli: "Manual",+ comment: "Comment",+ commit: "Commit",+ git_archaeology: "Git history",+ inline_marker: "Marker",+ llm_inferred: "Model",+ pr: "Pull request",+ session: "Session",+ changelog: "Changelog",+ code_comment: "Comment",+ readme_mining: "Docs",+};++/**+ * `source` is an unconstrained string on the wire, so a plain index into the+ * label map reaches `Object.prototype`: a row sourced `toString` would hand a+ * function to `localeCompare` and throw inside a sort comparator.+ */+export function decisionSourceLabel(source: string): string {+ return Object.hasOwn(DECISION_SOURCE_LABELS, source)+ ? DECISION_SOURCE_LABELS[source as DecisionSource]+ : source;+}++/** Whether a source string names a retired source. */+export function isRetiredDecisionSource(source: string): boolean {+ return (RETIRED_DECISION_SOURCES as readonly string[]).includes(source);+}++/**+ * What an accepted decision's authority currently amounts to.+ *+ * Not the same axis as `DecisionStatus`, which is the legacy projection kept+ * in step for readers that predate the acceptance split. `needs_review` and+ * `uncheckable` are derived from the code rather than set by a person, which+ * is why a record can be stored `active` and shown `uncheckable`.+ */+export const DECISION_CURRENCIES = [+ "active",+ "needs_review",+ "uncheckable",+ "superseded",+ "dismissed",+] as const;++export type DecisionCurrency = (typeof DECISION_CURRENCIES)[number];++/**+ * The word for a currency, and the sentence that says why it reads that way.+ *+ * `uncheckable` and `needs_review` are the two a reader cannot guess: the+ * first means the decision names nothing the repository can be asked about,+ * the second that the files it names have moved. Neither is an error, and+ * neither is quiet.+ */+export const DECISION_CURRENCY_LABELS: Record<DecisionCurrency, string> = {+ active: "Active",+ needs_review: "Needs review",+ uncheckable: "Uncheckable",+ superseded: "Superseded",+ dismissed: "Dismissed",+};++export const DECISION_CURRENCY_DESCRIPTIONS: Record<DecisionCurrency, string> =+ {+ active: "Accepted, and still describes the code it names.",+ needs_review: "Accepted, but the code it names has moved since.",+ uncheckable:+ "Accepted, but it names no file or module, so nothing checks it against the code.",+ superseded: "Replaced by a later decision.",+ dismissed: "Authority withdrawn. Kept for history.",+ };++/** Currencies that still bind future work. A moved decision is one to re-read. */+export const GOVERNING_CURRENCIES: readonly DecisionCurrency[] = [+ "active",+ "needs_review",+];++/** Where a candidate is in review. `dismissed` is a durable tombstone. */+export const CANDIDATE_REVIEW_STATES = [+ "open",+ "accepted",+ "merged",+ "needs_split",+ "dismissed",+] as const;++export type CandidateReviewState = (typeof CANDIDATE_REVIEW_STATES)[number];/** Derived granularity of a decision's blast area, narrowest first. */export type DecisionScope = "file" | "module" | "cross-module";@@ -43,7 +211,12 @@ export interface DecisionRecord {affected_files: string[];affected_modules: string[];tags: string[];- source: DecisionSource;+ /**+ * Where the record came from. Includes the retired values, because a row+ * written before a source was retired still carries its name and still has+ * to render; only the *filter* vocabulary is narrowed to the live set.+ */+ source: DecisionSource | RetiredDecisionSource;evidence_commits: string[];evidence_file: string | null;evidence_line: number | null;@@ -60,6 +233,17 @@ export interface DecisionRecord {scope?: DecisionScope | null;created_at: string;updated_at: string;+ /**+ * Effective currency from the acceptance, or null for a candidate.+ *+ * This is the authority answer. `status` is the projection kept in step for+ * readers that predate the acceptance split, so the two are different+ * questions: a record can be stored `active` and carry no currency at all,+ * which is exactly what a candidate is. Optional for back-compat with+ * backends that predate the field; absent and null both mean unknown, so a+ * surface that needs the distinction should ask for the lane instead.+ */+ currency?: DecisionCurrency | null;/** Number of evidence rows backing the record. List endpoint only. */evidence_count?: number | null;/** Top-ranked evidence row, slimmed for list rows. List endpoint only. */@@ -185,6 +369,109 @@ export interface DecisionGraph {code_edges: DecisionCodeEdge[];}+/**+ * Review lanes, as the list endpoint's `lane` parameter accepts them.+ *+ * `governing` is the roll-up of `active` and `needs_review`, so it overlaps+ * the two and is meant for a caller asking "what binds", not for a tab row.+ */+export const DECISION_LANE_FILTERS = [+ "candidates",+ "governing",+ "active",+ "needs_review",+ "uncheckable",+ "history",+] as const;++export type DecisionLaneFilter = (typeof DECISION_LANE_FILTERS)[number];++/**+ * Records per review lane.+ *+ * `candidates` and the four currency lanes partition the repository and sum to+ * `total`; `governing` is the roll-up of the two that still bind.+ */+export interface DecisionLaneCounts {+ candidates: number;+ active: number;+ needs_review: number;+ uncheckable: number;+ history: number;+ governing: number;+ total: number;+}++/**+ * The review lanes, in tab order. They partition a repository: every record is+ * in exactly one, and the five counts sum to the total.+ *+ * `governing` is deliberately absent. It is the roll-up of `active` and+ * `needs_review`, so it overlaps two lanes; it lives in `DECISION_LANE_FILTERS`+ * for a caller asking "what binds" and never in a tab row, because a tab row of+ * overlapping datasets is one a reader cannot add up.+ */+export const DECISION_LANES = [+ "active",+ "candidates",+ "needs_review",+ "uncheckable",+ "history",+] as const;++export type DecisionLane = (typeof DECISION_LANES)[number];++/** The capture presets a caller may set. `custom` is a reading, not a choice. */+export const DECISION_PRESETS = [+ "default",+ "off",+ "local_only",+ "balanced",+ "full",+] as const;++/**+ * The four checks `record_acceptance` refuses on, mirrored so a review surface+ * can disable a control it knows will be refused instead of finding out from+ * the error toast. Pinned against the Python contract by the vocabulary tests.+ *+ * `selfAuthored` is the exemption for a record somebody typed: they wrote the+ * claim rather than reviewing an inference, so the entry is its own provenance.+ * The engine grants it to `source === "cli"` when an accepter is known.+ */+export function decisionAcceptanceBlockers(record: {+ rationale?: string;+ decision?: string;+ affected_files?: string[];+ affected_modules?: string[];+ evidence_commits?: string[];+ evidence_file?: string | null;+ source?: string;+}): string[] {+ const blockers: string[] = [];+ const nonBlank = (values: (string | null | undefined)[]) =>+ values.some((v) => (v ?? "").trim().length > 0);++ if (!nonBlank([record.rationale, record.decision])) {+ blockers.push("no rationale or explicit constraint reason");+ }+ if (+ !nonBlank(record.affected_files ?? []) &&+ !nonBlank(record.affected_modules ?? [])+ ) {+ blockers.push("no scope: name the files or modules it governs");+ }+ const selfAuthored = record.source === "cli";+ if (+ !selfAuthored &&+ !nonBlank(record.evidence_commits ?? []) &&+ !nonBlank([record.evidence_file])+ ) {+ blockers.push("no evidence reference");+ }+ return blockers;+}+/** Counts by status, from a grouped COUNT on the server. */export interface DecisionCounts {total: number;diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 7bd0392b5..2eb01d823 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -801,6 +801,23 @@ export interface DecisionHealthResponse {ungoverned_hotspots?: string[];}+/**+ * Records per review lane, from a scan of the acceptance join.+ *+ * ``candidates`` and the four currency lanes partition the repository and sum+ * to ``total``; ``governing`` is the roll-up of the two that still bind, so a+ * caller can state "N rules" without adding two tabs together.+ */+export interface DecisionLaneCountsResponse {+ candidates: number;+ active: number;+ needs_review: number;+ uncheckable: number;+ history: number;+ governing: number;+ total: number;+}+/** One node in a decision lineage chain (root → … → current). */export interface DecisionLineageEntry {id: string;@@ -842,6 +859,7 @@ export interface DecisionRecordResponse {updated_at: string;evidence_count?: number | null;evidence_preview?: EvidencePreview | null;+ currency?: string | null;}/** The resolved decision capture policy for one repository. */diff --git a/packages/ui/__tests__/decisions/decision-capture-settings.test.tsx b/packages/ui/__tests__/decisions/decision-capture-settings.test.tsxnew file mode 100644index 000000000..8dba7cf27--- /dev/null+++ b/packages/ui/__tests__/decisions/decision-capture-settings.test.tsx@@ -0,0 +1,281 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { DecisionCaptureSettings } from "../../src/decisions/decision-capture-settings";+import type {+ DecisionSettings,+ DecisionSourceState,+} from "@repowise-dev/types/decisions";++function source(overrides: Partial<DecisionSourceState> = {}): DecisionSourceState {+ return {+ key: "pr",+ label: "Pull request bodies",+ description: "Squash-merge and PR bodies that read as a description.",+ authority: "machine",+ deterministic: false,+ supports_llm: true,+ togglable: true,+ enabled: true,+ llm_enabled: true,+ status: "enabled",+ reason: "",+ ...overrides,+ };+}++function settings(overrides: Partial<DecisionSettings> = {}): DecisionSettings {+ return {+ enabled: true,+ llm: true,+ preset: "default",+ discovery: { max_sessions: 12, max_input_tokens: 30000 },+ sources: [source()],+ provider_available: true,+ warnings: [],+ legacy_keys: [],+ etag: "etag-1",+ ...overrides,+ };+}++function renderPanel(+ props: Partial<React.ComponentProps<typeof DecisionCaptureSettings>> = {},+) {+ const onChange = vi.fn(async () => undefined);+ render(+ <DecisionCaptureSettings+ settings={settings()}+ onChange={onChange}+ {...props}+ />,+ );+ return onChange;+}++describe("the panel is the registry, not a copy of it", () => {+ it("renders a row per source the payload carries, whatever it names", () => {+ renderPanel({+ settings: settings({+ sources: [+ source({ key: "adr", label: "ADR files" }),+ source({ key: "brand_new", label: "Something added later" }),+ ],+ }),+ });++ expect(screen.getByText("ADR files")).toBeInTheDocument();+ expect(screen.getByText("Something added later")).toBeInTheDocument();+ expect(screen.getByText("brand_new")).toBeInTheDocument();+ });++ it("shows the engine's own effective status and reason", () => {+ renderPanel({+ settings: settings({+ sources: [+ source({+ status: "skipped_no_provider",+ reason: "no model key is configured",+ }),+ ],+ }),+ });++ expect(+ screen.getByText(/skipped no provider · no model key is configured/),+ ).toBeInTheDocument();+ });+});++describe("writes carry the etag", () => {+ it("sends the etag with every switch, not only the risky ones", async () => {+ const onChange = renderPanel();++ fireEvent.click(screen.getByLabelText("Capture decisions"));++ await waitFor(() =>+ expect(onChange).toHaveBeenCalledWith({ enabled: false, etag: "etag-1" }),+ );+ });++ it("patches one source rather than the whole list", async () => {+ const onChange = renderPanel();+ const row = screen.getByText("Pull request bodies").closest("li");++ fireEvent.click(within(row as HTMLElement).getByLabelText("Model"));++ await waitFor(() =>+ expect(onChange).toHaveBeenCalledWith({+ sources: { pr: { llm: false } },+ etag: "etag-1",+ }),+ );+ });++ it("says a concurrent edit was refused rather than overwritten", async () => {+ const onChange = vi.fn(async () => {+ throw new Error("409: the policy changed");+ });+ render(<DecisionCaptureSettings settings={settings()} onChange={onChange} />);++ fireEvent.click(screen.getByLabelText("Capture decisions"));++ await waitFor(() =>+ expect(screen.getByText(/changed somewhere else/)).toBeInTheDocument(),+ );+ });+});++describe("a control that cannot act says why before it is pressed", () => {+ it("disables the model switch on a source that has no model stage", () => {+ renderPanel({+ settings: settings({ sources: [source({ supports_llm: false })] }),+ });+ const row = screen.getByText("Pull request bodies").closest("li");+ const toggle = within(row as HTMLElement).getByLabelText("Model");++ expect(toggle).toBeDisabled();+ expect(toggle).toHaveAttribute("title", "This source has no model stage.");+ });++ it("disables the capture switch on the authority route", () => {+ renderPanel({+ settings: settings({+ sources: [+ source({+ key: "cli",+ label: "Manual entry",+ authority: "human",+ togglable: false,+ supports_llm: false,+ status: "always_on",+ }),+ ],+ }),+ });+ const row = screen.getByText("Manual entry").closest("li");+ const toggle = within(row as HTMLElement).getByLabelText("Capture");++ expect(toggle).toBeDisabled();+ expect(toggle.getAttribute("title")).toMatch(/Always available/);+ });++ it("disables every source switch while capture is off, and says so", () => {+ renderPanel({ settings: settings({ enabled: false }) });+ const row = screen.getByText("Pull request bodies").closest("li");++ for (const name of ["Capture", "Model"]) {+ const toggle = within(row as HTMLElement).getByLabelText(name);+ expect(toggle).toBeDisabled();+ expect(toggle).toHaveAttribute("title", "Capture is switched off.");+ }+ });++ it("disables a source's model switch while the master model switch is off", () => {+ renderPanel({ settings: settings({ llm: false }) });+ const row = screen.getByText("Pull request bodies").closest("li");++ expect(within(row as HTMLElement).getByLabelText("Model")).toHaveAttribute(+ "title",+ "Model calls are switched off.",+ );+ // Capture is a different axis and stays usable.+ expect(within(row as HTMLElement).getByLabelText("Capture")).toBeEnabled();+ });+});++describe("a surface that cannot write says so and points at the CLI", () => {+ it("locks every control and names the route", () => {+ const onChange = renderPanel({ readOnlyReason: "Read-only snapshot." });++ expect(screen.getByLabelText("Capture decisions")).toBeDisabled();+ expect(screen.getByText(/repowise decision config show/)).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "balanced" }));+ expect(onChange).not.toHaveBeenCalled();+ });+});++describe("state the payload reports", () => {+ it("says the provider is absent rather than painting it a warning", () => {+ renderPanel({ settings: settings({ provider_available: false }) });++ expect(screen.getByText(/No provider is configured/)).toBeInTheDocument();+ });++ it("surfaces resolver warnings verbatim", () => {+ renderPanel({+ settings: settings({ warnings: ["unknown source 'readme_mining' ignored"] }),+ });++ expect(+ screen.getByText("unknown source 'readme_mining' ignored"),+ ).toBeInTheDocument();+ });++ it("warns that saving replaces a legacy key", () => {+ renderPanel({ settings: settings({ legacy_keys: ["decisions.mine"] }) });++ expect(screen.getByText("decisions.mine")).toBeInTheDocument();+ expect(screen.getByText(/replaces it/)).toBeInTheDocument();+ });++ it("shows custom as a reading and never as a preset to pick", () => {+ renderPanel({ settings: settings({ preset: "custom" }) });++ // `custom` is a description of where the policy is, so it renders as a+ // word beside the presets and never as a sixth one to press. The section's+ // own prose names it too, hence the getAll.+ expect(+ screen.queryByRole("button", { name: "custom" }),+ ).not.toBeInTheDocument();+ expect(screen.getAllByText("custom").length).toBeGreaterThan(0);+ });++ it("marks the active preset for assistive technology, not only in colour", () => {+ renderPanel({ settings: settings({ preset: "balanced" }) });++ expect(screen.getByRole("button", { name: "balanced" })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ expect(screen.getByRole("button", { name: "full" })).toHaveAttribute(+ "aria-pressed",+ "false",+ );+ });++ it("states the discovery budget with its units", () => {+ renderPanel();++ expect(screen.getByText("Sessions per update")).toBeInTheDocument();+ expect(screen.getByText("12")).toBeInTheDocument();+ expect(screen.getByText("30,000")).toBeInTheDocument();+ });+});++describe("loading and failure", () => {+ it("renders nothing while the first fetch is in flight", () => {+ const { container } = render(+ <DecisionCaptureSettings+ settings={undefined}+ onChange={vi.fn(async () => undefined)}+ isLoading+ />,+ );++ expect(container).toBeEmptyDOMElement();+ });++ it("offers a retry when the fetch failed", () => {+ render(+ <DecisionCaptureSettings+ settings={undefined}+ onChange={vi.fn(async () => undefined)}+ error={new Error("boom")}+ onRetry={vi.fn()}+ />,+ );++ expect(screen.getByText(/Couldn't load capture settings/)).toBeInTheDocument();+ });+});diff --git a/packages/ui/__tests__/decisions/decision-create-form.test.tsx b/packages/ui/__tests__/decisions/decision-create-form.test.tsxindex 8333c5247..b68694ca9 100644--- a/packages/ui/__tests__/decisions/decision-create-form.test.tsx+++ b/packages/ui/__tests__/decisions/decision-create-form.test.tsx@@ -61,7 +61,7 @@ describe("DecisionCreateForm", () => {fill("Title", "Prefer ruff check");fill("Decision", "never ruff format");- fireEvent.click(screen.getByRole("button", { name: "Record decision" }));+ fireEvent.click(screen.getByRole("button", { name: "Save as candidate" }));await waitFor(() =>expect(onSubmit).toHaveBeenCalledWith(@@ -78,7 +78,7 @@ describe("DecisionCreateForm", () => {it("cannot be submitted without a title and a decision", () => {render(<DecisionCreateForm onSubmit={vi.fn(async () => undefined)} />);- const submit = screen.getByRole("button", { name: "Record decision" });+ const submit = screen.getByRole("button", { name: "Save as candidate" });expect(submit).toBeDisabled();fill("Title", "Half a record");@@ -88,6 +88,67 @@ describe("DecisionCreateForm", () => {expect(submit).toBeEnabled();});+ // The form and the acceptance contract have to agree before the write, not+ // after it. `record_acceptance` refuses an acceptance that names no scope,+ // so a form offering "Record decision" on an empty Affected files sent a+ // request that came back as "no scope: name the files or modules it+ // governs" in a failure toast, with the eight answered fields still on+ // screen and nothing saying which field was the problem.+ describe("says which outcome the write will have", () => {+ function fillRequired() {+ fill("Title", "Use JWT for authentication");+ fill("Decision", "Issue signed JWTs");+ }++ it("offers to record a decision once it names a scope", () => {+ render(<DecisionCreateForm onSubmit={vi.fn(async () => undefined)} />);+ fillRequired();+ fill("Affected files", "src/auth/service.py");++ expect(+ screen.getByRole("button", { name: "Record decision" }),+ ).toBeEnabled();+ expect(screen.getByText(/Recorded as confirmed/)).toBeInTheDocument();+ });++ it("offers to save a candidate while it names nothing", () => {+ render(<DecisionCreateForm onSubmit={vi.fn(async () => undefined)} />);+ fillRequired();++ expect(+ screen.getByRole("button", { name: "Save as candidate" }),+ ).toBeEnabled();+ expect(+ screen.getByText(/Name the files it governs to confirm it/),+ ).toBeInTheDocument();+ });++ it("switches the verb as the scope field is filled and cleared", () => {+ render(<DecisionCreateForm onSubmit={vi.fn(async () => undefined)} />);+ fillRequired();++ fill("Affected files", "src/auth/service.py");+ expect(screen.getByRole("button", { name: "Record decision" })).toBeTruthy();++ // A field holding only separators names nothing, the same way the+ // server reads it: splitList drops the blanks on both sides.+ fill("Affected files", " , ");+ expect(+ screen.getByRole("button", { name: "Save as candidate" }),+ ).toBeTruthy();+ });++ it("names the outcome in the success toast too", async () => {+ const onSubmit = vi.fn(async () => undefined);+ render(<DecisionCreateForm onSubmit={onSubmit} />);+ fillRequired();+ fireEvent.click(screen.getByRole("button", { name: "Save as candidate" }));++ await waitFor(() => expect(toastSuccess).toHaveBeenCalled());+ expect(toastSuccess.mock.calls[0]?.[0]).toMatch(/candidate/i);+ });+ });+it("keeps the form open and says so when the write fails", async () => {const onSubmit = vi.fn(async () => {throw new Error("repo is read-only");@@ -97,7 +158,7 @@ describe("DecisionCreateForm", () => {fill("Title", "Use JWT");fill("Decision", "sign them");- fireEvent.click(screen.getByRole("button", { name: "Record decision" }));+ fireEvent.click(screen.getByRole("button", { name: "Save as candidate" }));await waitFor(() => expect(toastError).toHaveBeenCalled());expect(onCreated).not.toHaveBeenCalled();diff --git a/packages/ui/__tests__/decisions/decision-review-lanes.test.tsx b/packages/ui/__tests__/decisions/decision-review-lanes.test.tsxnew file mode 100644index 000000000..9013a0099--- /dev/null+++ b/packages/ui/__tests__/decisions/decision-review-lanes.test.tsx@@ -0,0 +1,332 @@+import { beforeAll, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, within } from "@testing-library/react";+import {+ DECISION_LANES,+ DecisionReviewLanes,+ type DecisionLane,+} from "../../src/decisions/decision-review-lanes";+import type { DecisionRecord } from "@repowise-dev/types/decisions";++// jsdom has no scrollIntoView; `ViewTabs` keeps the active tab in view on mount.+beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn();+});++function record(overrides: Partial<DecisionRecord> = {}): DecisionRecord {+ return {+ id: "d1",+ repository_id: "r1",+ title: "Use JWT for authentication",+ status: "proposed",+ context: "",+ decision: "Issue signed JWTs",+ // Carries what the acceptance contract needs, because that is the ordinary+ // candidate: reason, scope and an evidence reference. The cases that are+ // missing one say so explicitly.+ rationale: "sessions did not survive a restart",+ alternatives: [],+ consequences: [],+ affected_files: ["src/auth/service.py"],+ affected_modules: [],+ tags: [],+ source: "pr",+ evidence_commits: ["abc1234"],+ evidence_file: null,+ evidence_line: null,+ confidence: 0.6,+ staleness_score: 0,+ superseded_by: null,+ last_code_change: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++function renderLanes(+ lane: DecisionLane,+ props: Partial<React.ComponentProps<typeof DecisionReviewLanes>> = {},+) {+ return render(+ <DecisionReviewLanes+ lane={lane}+ onLaneChange={vi.fn()}+ decisions={[record()]}+ repoId="r1"+ {...props}+ />,+ );+}++describe("lane structure", () => {+ it("partitions the repository: five lanes, no overlap", () => {+ expect([...DECISION_LANES]).toEqual([+ "active",+ "candidates",+ "needs_review",+ "uncheckable",+ "history",+ ]);+ expect(new Set(DECISION_LANES).size).toBe(DECISION_LANES.length);+ });++ it("renders one tab per lane, with the measured counts", () => {+ renderLanes("active", {+ counts: {+ active: 122,+ candidates: 381,+ needs_review: 4,+ uncheckable: 57,+ history: 2,+ },+ });++ const tablist = screen.getByRole("tablist");+ expect(within(tablist).getAllByRole("tab")).toHaveLength(5);+ expect(within(tablist).getByText("381")).toBeInTheDocument();+ expect(within(tablist).getByText("57")).toBeInTheDocument();+ });++ it("omits a badge for a lane nobody counted", () => {+ renderLanes("active", { counts: { active: 3 } });++ const tablist = screen.getByRole("tablist");+ // One badge rendered, not five zeroes: a number nobody measured is worse+ // than no number.+ expect(within(tablist).queryByText("0")).not.toBeInTheDocument();+ expect(within(tablist).getByText("3")).toBeInTheDocument();+ });++ it("reports the lane change rather than switching itself", () => {+ const onLaneChange = vi.fn();+ renderLanes("active", { onLaneChange });++ fireEvent.click(screen.getByRole("tab", { name: /Candidates/ }));++ expect(onLaneChange).toHaveBeenCalledWith("candidates");+ });+});++describe("a candidate is a review request, not an instruction", () => {+ it("carries the evidence it was drawn from", () => {+ renderLanes("candidates", {+ decisions: [+ record({+ evidence_count: 3,+ evidence_preview: {+ source: "pr",+ source_quote: "we settled on JWT because sessions did not survive",+ verification: "exact",+ evidence_file: "docs/auth.md",+ evidence_line: 12,+ },+ }),+ ],+ });++ expect(+ screen.getByText(/we settled on JWT because sessions did not survive/),+ ).toBeInTheDocument();+ expect(screen.getByText(/docs\/auth\.md:12/)).toBeInTheDocument();+ expect(screen.getByText(/2 more/)).toBeInTheDocument();+ });++ it("says it governs nothing and nobody has accepted it", () => {+ renderLanes("candidates");++ expect(screen.getByText(/nobody has accepted/i)).toBeInTheDocument();+ expect(screen.getByText(/govern nothing and reach no agent/i)).toBeInTheDocument();+ });++ it("offers the review verbs only in the candidates lane", () => {+ const onAccept = vi.fn();+ renderLanes("active", { onAccept, decisions: [record({ currency: "active" })] });+ expect(screen.queryByRole("button", { name: "Accept" })).not.toBeInTheDocument();++ renderLanes("candidates", { onAccept });+ expect(screen.getByRole("button", { name: "Accept" })).toBeInTheDocument();+ });++ it("hands the record back rather than writing", () => {+ const onAccept = vi.fn();+ const onDismiss = vi.fn();+ renderLanes("candidates", { onAccept, onDismiss });++ fireEvent.click(screen.getByRole("button", { name: "Accept" }));+ expect(onAccept).toHaveBeenCalledWith(expect.objectContaining({ id: "d1" }));++ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ expect(onDismiss).toHaveBeenCalledWith(expect.objectContaining({ id: "d1" }));+ });++ it("disables the verbs while that row's write is in flight, and only that row", () => {+ renderLanes("candidates", {+ onAccept: vi.fn(),+ onDismiss: vi.fn(),+ pendingIds: new Set(["d1"]),+ });++ expect(screen.getByRole("button", { name: "Accepting…" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Dismiss" })).toBeDisabled();+ });++ it("leaves a second row usable while the first is in flight", () => {+ renderLanes("candidates", {+ decisions: [record({ id: "d1" }), record({ id: "d2", title: "Other" })],+ onAccept: vi.fn(),+ pendingIds: new Set(["d1"]),+ });++ // One write in flight must not freeze the queue: a single pending id used+ // to disable every row, and re-enable them all when the first resolved.+ expect(screen.getByRole("button", { name: "Accepting…" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Accept" })).toBeEnabled();+ });++ it("disables Accept, with the reason, on a candidate the engine would refuse", () => {+ renderLanes("candidates", {+ decisions: [+ record({+ affected_files: [],+ affected_modules: [],+ rationale: "",+ decision: "",+ }),+ ],+ onAccept: vi.fn(),+ onDismiss: vi.fn(),+ });++ // The engine refuses an acceptance with no scope, reason or evidence. The+ // row already knows all three, so the button says so before it is pressed+ // rather than reporting it in an error toast afterwards.+ expect(screen.getByRole("button", { name: "Accept" })).toBeDisabled();+ expect(screen.getByText(/no scope: name the files or modules it governs/))+ .toBeInTheDocument();+ // Dismissing stays available: an unacceptable candidate is exactly the one+ // worth tombstoning.+ expect(screen.getByRole("button", { name: "Dismiss" })).toBeEnabled();+ });++ it("leaves Accept enabled on a candidate that carries what the contract needs", () => {+ renderLanes("candidates", {+ decisions: [+ record({+ rationale: "sessions did not survive a restart",+ affected_files: ["src/auth/service.py"],+ evidence_commits: ["abc1234"],+ }),+ ],+ onAccept: vi.fn(),+ });++ expect(screen.getByRole("button", { name: "Accept" })).toBeEnabled();+ expect(screen.queryByText(/Cannot accept/)).not.toBeInTheDocument();+ });++ it("explains itself instead of rendering a control it cannot use", () => {+ renderLanes("candidates", {+ onAccept: vi.fn(),+ readOnlyReason: "Read-only snapshot",+ });++ expect(screen.queryByRole("button", { name: "Accept" })).not.toBeInTheDocument();+ expect(screen.getByText("Read-only snapshot")).toBeInTheDocument();+ });+});++describe("currency marks the exception, not the default", () => {+ // Scoped to the row list: every lane name is also a tab label, so an+ // unscoped query would find the tab and pass whatever the row rendered.+ const rows = () => within(screen.getByRole("list"));++ it("says nothing extra about a decision that still describes its code", () => {+ renderLanes("active", { decisions: [record({ currency: "active" })] });++ expect(rows().queryByText("Needs review")).not.toBeInTheDocument();+ expect(rows().queryByText("Uncheckable")).not.toBeInTheDocument();+ expect(rows().queryByText("Active")).not.toBeInTheDocument();+ });++ it("names a currency the reader cannot guess", () => {+ renderLanes("uncheckable", {+ decisions: [+ record({ currency: "uncheckable", affected_files: [], affected_modules: [] }),+ ],+ });++ expect(rows().getByText("Uncheckable")).toBeInTheDocument();+ // And the row says the same thing in its own words rather than only in a+ // colour: this record names nothing at all.+ expect(rows().getByText("names nothing")).toBeInTheDocument();+ });+});++describe("the source filter is a second axis, not a second lane control", () => {+ it("offers every live source and no retired one", () => {+ renderLanes("candidates", { onSourceChange: vi.fn() });+ const select = screen.getByLabelText("Filter by source");++ // Built from the shared list, so a source absent from this page's fifty+ // rows is still selectable.+ expect(within(select).getByRole("option", { name: "Commit" })).toBeTruthy();+ expect(within(select).getByRole("option", { name: "Model" })).toBeTruthy();+ expect(within(select).queryByRole("option", { name: "Docs" })).toBeNull();+ });++ it("reports the change rather than filtering itself", () => {+ const onSourceChange = vi.fn();+ renderLanes("candidates", { onSourceChange });++ fireEvent.change(screen.getByLabelText("Filter by source"), {+ target: { value: "pr" },+ });++ expect(onSourceChange).toHaveBeenCalledWith("pr");+ });++ it("renders no control when the host cannot act on it", () => {+ renderLanes("candidates");++ expect(screen.queryByLabelText("Filter by source")).not.toBeInTheDocument();+ });++ it("says an empty result may be the filter rather than the lane", () => {+ renderLanes("candidates", {+ decisions: [],+ source: "pr",+ onSourceChange: vi.fn(),+ });++ expect(screen.getByText(/clear the source filter/)).toBeInTheDocument();+ expect(screen.queryByText(/No candidates are waiting/)).not.toBeInTheDocument();+ });+});++describe("empty and failed lanes", () => {+ it("says what will fill the lane", () => {+ renderLanes("candidates", { decisions: [] });++ expect(screen.getByText(/No candidates are waiting/)).toBeInTheDocument();+ });++ it("says nothing while the first page is still loading", () => {+ renderLanes("candidates", { decisions: undefined, isLoading: true });++ expect(screen.queryByText(/No candidates are waiting/)).not.toBeInTheDocument();+ });++ it("offers a retry when the fetch failed", () => {+ const onRetry = vi.fn();+ renderLanes("candidates", {+ decisions: [],+ error: new Error("boom"),+ onRetry,+ });++ // The error replaces the lane rather than sitting beside an empty state+ // that would read as "there is nothing here".+ expect(screen.queryByText(/No candidates are waiting/)).not.toBeInTheDocument();+ expect(screen.getByText(/Couldn't load this lane/)).toBeInTheDocument();+ });+});diff --git a/packages/ui/src/decisions/decision-capture-settings.tsx b/packages/ui/src/decisions/decision-capture-settings.tsxnew file mode 100644index 000000000..0347733e4--- /dev/null+++ b/packages/ui/src/decisions/decision-capture-settings.tsx@@ -0,0 +1,468 @@+"use client";++import * as React from "react";+import { DECISION_PRESETS } from "@repowise-dev/types/decisions";+import type {+ DecisionSettings,+ DecisionSettingsUpdate,+ DecisionSourceState,+} from "@repowise-dev/types/decisions";+import { ApiError } from "../shared/api-error";++/**+ * What captures decisions, and whether any of it may call a model.+ *+ * Every row here comes from the source registry the engine resolves, delivered+ * whole by `GET /decisions/settings`. Nothing in this file lists a source, a+ * preset or a status word: a second list would be a second registry, and the+ * one drift this layer has already suffered was exactly that.+ *+ * Autosave, per the form archetype: a switch is one whole-object write and+ * there is nothing to batch. The write is optimistic and rolls back on+ * failure, and the etag the payload carries is passed straight back, so a+ * change made in `.repowise/config.yaml` or by `repowise decision source set`+ * while this page was open is reported as a conflict rather than overwritten.+ *+ * Presentation and pending state only. The host owns the fetch and the write.+ */++export interface DecisionCaptureSettingsProps {+ settings: DecisionSettings | undefined;+ /**+ * Applies a partial policy change. Rejecting rolls the control back; a+ * rejection carrying a 409 should be reported through `conflict`.+ */+ onChange: (update: DecisionSettingsUpdate) => Promise<void>;+ /**+ * Why this surface cannot write, e.g. a read-only snapshot or a repository+ * whose config it does not own. Set it and every control is disabled with+ * the reason beside it, and the CLI route to make the change is shown.+ * Never leave a live-looking switch that explains itself after it is+ * pressed.+ */+ readOnlyReason?: string;+ error?: unknown;+ isLoading?: boolean;+ onRetry?: () => void;+}++const SECTION = "space-y-3 border-t border-[var(--color-border-subtle)] pt-5";+const MICRO_LABEL =+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";++/**+ * What each preset is for. The names come from the shared vocabulary; only+ * these sentences are local, and a preset with no sentence still renders as a+ * button rather than disappearing.+ */+const PRESET_BLURB: Record<string, string> = {+ default: "The deterministic sources, and no broad model pass.",+ off: "Capture nothing. Decisions you record by hand still work.",+ local_only: "Only what this checkout can see, with no model call at all.",+ balanced: "The deterministic sources plus one broad pass over new sessions.",+ full: "Every source, model stages included.",+};++export function DecisionCaptureSettings({+ settings,+ onChange,+ readOnlyReason,+ error,+ isLoading,+ onRetry,+}: DecisionCaptureSettingsProps) {+ const [pending, setPending] = React.useState<string | null>(null);+ const [conflict, setConflict] = React.useState(false);++ const write = React.useCallback(+ async (key: string, update: DecisionSettingsUpdate) => {+ if (!settings) return;+ setPending(key);+ setConflict(false);+ try {+ // The etag goes with every write, not only the risky-looking ones:+ // this config is also edited by the CLI and by hand, so any write can+ // be the one that lands on top of somebody else's.+ await onChange({ ...update, etag: settings.etag });+ } catch (err) {+ // Handled, not re-thrown. These calls are made from click handlers,+ // which have nowhere to return a promise to, so re-throwing produced+ // an unhandled rejection on every failed write. A conflict gets the+ // sentence below; the host reports everything else, having already+ // rolled the control back.+ setConflict(err instanceof Error && /409|conflict/i.test(err.message));+ } finally {+ setPending(null);+ }+ },+ [onChange, settings],+ );++ if (error) {+ return (+ <ApiError+ title="Couldn't load capture settings"+ message="An error occurred while reading the decision policy."+ {...(onRetry ? { onRetry } : {})}+ />+ );+ }+ if (!settings) {+ return isLoading ? null : (+ <p className="text-xs text-[var(--color-text-secondary)]">+ No capture policy is available for this repository.+ </p>+ );+ }++ const locked = Boolean(readOnlyReason);+ const busy = (key: string) => pending === key;+ const llmMasterReason =+ readOnlyReason ?? (settings.enabled ? "" : "Capture is switched off.");++ return (+ <div className="space-y-5">+ {readOnlyReason && (+ <p className="text-xs text-[var(--color-text-secondary)]">+ {readOnlyReason} Change it from the checkout with{" "}+ <code className="font-mono text-[11px]">+ repowise decision config show+ </code>+ .+ </p>+ )}++ {conflict && (+ <p className="text-xs text-[var(--color-text-secondary)]">+ The policy changed somewhere else while this page was open, so the+ write was refused rather than applied on top of it. Reload to see the+ current state.+ </p>+ )}++ {settings.warnings.map((warning) => (+ <p key={warning} className="text-xs text-[var(--color-text-secondary)]">+ {warning}+ </p>+ ))}++ {settings.legacy_keys.length > 0 && (+ <p className="text-xs text-[var(--color-text-secondary)]">+ Still reading{" "}+ <span className="font-mono">{settings.legacy_keys.join(", ")}</span>{" "}+ from an older config. Saving anything here replaces{" "}+ {settings.legacy_keys.length === 1 ? "it" : "them"}.+ </p>+ )}++ {/* The two master switches. Separate rows because they are separate+ questions: capture can run with no model at all, and turning the+ model off must not read as turning capture off. */}+ <div className="space-y-3">+ <Toggle+ label="Capture decisions"+ description="Mine decisions from this repository during indexing and updates."+ checked={settings.enabled}+ disabled={locked || busy("enabled")}+ {...(readOnlyReason ? { reason: readOnlyReason } : {})}+ onChange={(v) => void write("enabled", { enabled: v })}+ />+ <Toggle+ label="Allow model calls"+ description={+ settings.provider_available+ ? "Lets the sources that have a model stage use it. Their prose is sent to the configured provider."+ : "No provider is configured, so the sources that have a model stage run their deterministic half only."+ }+ checked={settings.llm}+ disabled={locked || !settings.enabled || busy("llm")}+ {...(llmMasterReason ? { reason: llmMasterReason } : {})}+ onChange={(v) => void write("llm", { llm: v })}+ />+ </div>++ <section className={SECTION}>+ <div>+ <h3 className="text-sm font-medium text-[var(--color-text-primary)]">+ Preset+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)]">+ A named set of sources. Changing one source afterwards leaves the+ preset reading <span className="font-mono">custom</span>, which is+ a description of where you are and not a preset you can pick.+ </p>+ </div>+ <div className="flex flex-wrap gap-2">+ {DECISION_PRESETS.map((preset) => {+ const active = settings.preset === preset;+ return (+ <button+ key={preset}+ type="button"+ aria-pressed={active}+ disabled={locked || busy("preset")}+ title={locked ? readOnlyReason : PRESET_BLURB[preset]}+ onClick={() => void write("preset", { preset })}+ className={+ "rounded-md border px-2.5 py-1 text-xs transition-colors disabled:opacity-40 " ++ (active+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)]")+ }+ >+ {preset}+ </button>+ );+ })}+ {/* Whatever the payload says, when it is not one of the buttons.+ `custom` is the resolver's word for "somebody changed a source+ after picking a preset"; anything else is a preset this build+ predates. Either way the reader must be able to see what is+ actually set rather than five unpressed buttons. */}+ {!(DECISION_PRESETS as readonly string[]).includes(settings.preset) && (+ <span className="self-center text-xs text-[var(--color-text-tertiary)]">+ {settings.preset}+ </span>+ )}+ </div>+ </section>++ <section className={SECTION}>+ <div>+ <h3 className="text-sm font-medium text-[var(--color-text-primary)]">+ Sources+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)]">+ Each source's effective state and why it reads that way. A source+ with a model stage sends the prose it reads to the configured+ provider only while both its own switch and the master model switch+ are on.+ </p>+ </div>+ <ul className="divide-y divide-[var(--color-border-subtle)] border-t border-[var(--color-border-subtle)]">+ {settings.sources.map((source) => (+ <SourceRow+ key={source.key}+ source={source}+ masterOff={!settings.enabled}+ llmOff={!settings.llm}+ locked={locked}+ {...(readOnlyReason ? { readOnlyReason } : {})}+ busy={busy(source.key)}+ onChange={(patch) =>+ void write(source.key, { sources: { [source.key]: patch } })+ }+ />+ ))}+ </ul>+ </section>++ <section className={SECTION}>+ <div>+ <h3 className="text-sm font-medium text-[var(--color-text-primary)]">+ Broad discovery budget+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)]">+ The ceiling on the one broad model pass each update. It is one call,+ not one per session, and these are its bounds.+ </p>+ </div>+ <dl className="flex flex-wrap gap-x-8 gap-y-1">+ <Figure+ label="Sessions per update"+ value={settings.discovery.max_sessions}+ />+ <Figure+ label="Input tokens"+ value={settings.discovery.max_input_tokens}+ />+ </dl>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Change them with{" "}+ <code className="font-mono text-[11px]">+ repowise decision config discovery --max-sessions N+ </code>+ .+ </p>+ </section>+ </div>+ );+}++function Figure({ label, value }: { label: string; value: number }) {+ return (+ <div className="space-y-0.5">+ <dt className={MICRO_LABEL}>{label}</dt>+ <dd className="font-mono text-sm tabular-nums text-[var(--color-text-primary)]">+ {value.toLocaleString()}+ </dd>+ </div>+ );+}++function SourceRow({+ source,+ masterOff,+ llmOff,+ locked,+ readOnlyReason,+ busy,+ onChange,+}: {+ source: DecisionSourceState;+ masterOff: boolean;+ llmOff: boolean;+ locked: boolean;+ readOnlyReason?: string;+ busy: boolean;+ onChange: (patch: { enabled?: boolean; llm?: boolean }) => void;+}) {+ // `togglable: false` is the authority route: manual entry has no capture to+ // switch off, so it gets a sentence rather than a control that cannot act.+ const captureReason = locked+ ? readOnlyReason+ : !source.togglable+ ? "Always available. Recording a decision yourself is not a capture pass."+ : masterOff+ ? "Capture is switched off."+ : undefined;+ const llmReason = locked+ ? readOnlyReason+ : !source.supports_llm+ ? "This source has no model stage."+ : masterOff+ ? "Capture is switched off."+ : llmOff+ ? "Model calls are switched off."+ : !source.enabled+ ? "This source is switched off."+ : undefined;++ return (+ <li className="flex flex-col gap-2 py-3 sm:flex-row sm:items-start sm:justify-between sm:gap-6">+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex flex-wrap items-baseline gap-x-2">+ <span className="text-sm text-[var(--color-text-primary)]">+ {source.label}+ </span>+ <span className={MICRO_LABEL}>{source.key}</span>+ {source.authority === "human" && (+ <span className={MICRO_LABEL}>human</span>+ )}+ </div>+ <p className="text-xs text-[var(--color-text-secondary)]">+ {source.description}+ </p>+ {/* The effective state, in the engine's own words. Shown on every row+ rather than only the surprising ones: this is a settings surface,+ and "why is this off" is the question it exists to answer. */}+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {source.status.replace(/_/g, " ")}+ {source.reason ? ` · ${source.reason}` : ""}+ </p>+ </div>+ <div className="flex shrink-0 flex-col gap-1.5">+ <Toggle+ compact+ label="Capture"+ checked={source.enabled}+ disabled={locked || !source.togglable || masterOff || busy}+ {...(captureReason ? { reason: captureReason } : {})}+ onChange={(v) => onChange({ enabled: v })}+ />+ <Toggle+ compact+ label="Model"+ checked={source.llm_enabled}+ disabled={+ locked ||+ !source.supports_llm ||+ masterOff ||+ llmOff ||+ !source.enabled ||+ busy+ }+ {...(llmReason ? { reason: llmReason } : {})}+ onChange={(v) => onChange({ llm: v })}+ />+ </div>+ </li>+ );+}++/**+ * A labelled checkbox with its reason attached.+ *+ * A native `input type="checkbox"` rather than a bespoke switch: it is+ * keyboard reachable, announces its own state, and needs no roving-focus+ * contract explained. `title` carries the reason so a disabled control can be+ * asked why before it is pressed, which is the rule a live-looking button that+ * explains itself afterwards breaks.+ */+function Toggle({+ label,+ description,+ checked,+ disabled,+ reason,+ compact,+ onChange,+}: {+ label: string;+ description?: string;+ checked: boolean;+ disabled?: boolean;+ reason?: string;+ compact?: boolean;+ onChange: (value: boolean) => void;+}) {+ const id = React.useId();+ const reasonId = `${id}-reason`;+ const describedBy = disabled && reason ? reasonId : undefined;+ return (+ <div className={compact ? "" : "space-y-0.5"}>+ <div className="flex items-center gap-2">+ <input+ id={id}+ type="checkbox"+ checked={checked}+ disabled={disabled}+ title={disabled ? reason : undefined}+ {...(describedBy ? { "aria-describedby": describedBy } : {})}+ onChange={(e) => onChange(e.target.checked)}+ className="h-3.5 w-3.5 shrink-0 accent-[var(--color-accent-primary)] disabled:opacity-40"+ />+ <label+ htmlFor={id}+ className={+ compact+ ? "text-xs text-[var(--color-text-secondary)]"+ : "text-sm text-[var(--color-text-primary)]"+ }+ >+ {label}+ </label>+ </div>+ {description && (+ <p className="pl-[1.375rem] text-xs text-[var(--color-text-secondary)]">+ {description}+ </p>+ )}+ {disabled && reason && (+ <p+ id={reasonId}+ className={+ compact+ ? "sr-only"+ : "pl-[1.375rem] text-xs text-[var(--color-text-tertiary)]"+ }+ >+ {reason}+ </p>+ )}+ </div>+ );+}++/** Exported for a host that wants to render its own preset chooser. */+export { PRESET_BLURB };diff --git a/packages/ui/src/decisions/decision-create-form.tsx b/packages/ui/src/decisions/decision-create-form.tsxindex a5c3e7f3e..62c9f8761 100644--- a/packages/ui/src/decisions/decision-create-form.tsx+++ b/packages/ui/src/decisions/decision-create-form.tsx@@ -21,6 +21,12 @@ import { Label } from "../ui/label";* The comma-separated list fields mirror the CLI's prompts rather than* inventing a chip editor. They are the fields people leave blank most often,* and a text input that accepts "a, b" needs no keyboard contract explained.+ *+ * Affected files is the one field that changes what the write produces. An+ * acceptance has to name what it governs, so an entry naming nothing is stored+ * as a candidate instead. That is the same outcome `repowise decision add`+ * gives the same input, and the form says which one is coming before the+ * button is pressed rather than reporting it in a failure toast afterwards.*/const FIELD = "space-y-1.5";@@ -68,6 +74,9 @@ export function DecisionCreateForm({// as it is at the prompts.const canSubmit = title.trim().length > 0 && decision.trim().length > 0 && !saving;+ // Mirrors the server: scope present means the write records an acceptance.+ const governs = splitList(affectedFiles).length > 0;+async function handleSubmit(event: React.FormEvent) {event.preventDefault();if (!canSubmit) return;@@ -83,7 +92,11 @@ export function DecisionCreateForm({affected_files: splitList(affectedFiles),tags: splitList(tags),});- toast.success("Decision recorded");+ toast.success(+ governs+ ? "Decision recorded and confirmed"+ : "Saved as a candidate. Add the files it governs to confirm it.",+ );onCreated?.();} catch (err) {toast.error(@@ -171,16 +184,6 @@ export function DecisionCreateForm({disabled={saving}/></div>- <div className={FIELD}>- <Label htmlFor="decision-files">Affected files</Label>- <Input- id="decision-files"- value={affectedFiles}- onChange={(e) => setAffectedFiles(e.target.value)}- placeholder="src/auth/service.py, src/auth/middleware.py"- disabled={saving}- />- </div><div className={FIELD}><Label htmlFor="decision-tags">Tags</Label><Input@@ -193,14 +196,39 @@ export function DecisionCreateForm({</div></div>- <div className="flex justify-end gap-2 pt-1">+ <div className={FIELD}>+ <Label htmlFor="decision-files">Affected files</Label>+ <Input+ id="decision-files"+ value={affectedFiles}+ onChange={(e) => setAffectedFiles(e.target.value)}+ placeholder="src/auth/service.py, src/auth/middleware.py"+ disabled={saving}+ aria-describedby="decision-outcome"+ />+ </div>++ <div className="flex flex-wrap items-center justify-end gap-x-4 gap-y-2 pt-1">+ <p+ id="decision-outcome"+ aria-live="polite"+ className="min-w-0 flex-1 text-xs text-[var(--color-text-secondary)]"+ >+ {governs+ ? "Recorded as confirmed, because you are the person confirming it. It will govern the files above."+ : "Name the files it governs to confirm it. Without them it is saved as a candidate: nothing checks it against the code, and it does not reach an agent."}+ </p>{onCancel && (<Button type="button" variant="ghost" onClick={onCancel} disabled={saving}>Cancel</Button>)}<Button type="submit" disabled={!canSubmit}>- {saving ? "Recording…" : "Record decision"}+ {saving+ ? "Recording…"+ : governs+ ? "Record decision"+ : "Save as candidate"}</Button></div></form>diff --git a/packages/ui/src/decisions/decision-review-lanes.tsx b/packages/ui/src/decisions/decision-review-lanes.tsxnew file mode 100644index 000000000..c68a01858--- /dev/null+++ b/packages/ui/src/decisions/decision-review-lanes.tsx@@ -0,0 +1,424 @@+"use client";++import * as React from "react";+import {+ DECISION_CURRENCY_DESCRIPTIONS,+ DECISION_CURRENCY_LABELS,+ DECISION_LANES,+ DECISION_SOURCES,+ decisionAcceptanceBlockers,+ decisionSourceLabel,+ isRetiredDecisionSource,+} from "@repowise-dev/types/decisions";+import type {+ DecisionCurrency,+ DecisionLane,+ DecisionRecord,+} from "@repowise-dev/types/decisions";+import { ApiError } from "../shared/api-error";+import { EmptyState } from "../shared/empty-state";+import { ViewTabs, type ViewTab } from "../shared/view-tabs";+import { Button } from "../ui/button";+import { VerificationBadge } from "./verification-badge";+import { describeRecordStaleness } from "./decision-staleness";+import { stripMarkdown } from "../lib/format";++/**+ * The review lanes: what governs, what is waiting to be reviewed, and what has+ * been retired.+ *+ * The decisions page had one table sorted by a status column, which is the+ * wrong axis now that authority is an acceptance rather than a status. On a+ * live index that table opens on 505 rows of which 381 are candidates nobody+ * has looked at, mixed in with the 122 that govern and separated only by a+ * word in a column. A reader could not tell a rule from a guess without+ * reading every row, and an agent quoting the page could not either.+ *+ * The lanes are that separation, and they are semantic before they are+ * visual: a candidate is a request to review something, never an instruction.+ * It gets its own lane, its own verb, and the evidence it was drawn from, so+ * the decision to accept it can be made from the row.+ *+ * Presentation and lane state only. The host fetches, pages and writes, per+ * the convention the rest of this directory follows, so one implementation+ * serves the OSS app and hosted.+ */++/**+ * The lane vocabulary is shared and pinned against the engine's, so this file+ * declares neither the lanes nor their words. A second list here would be the+ * second registry this whole change exists to remove.+ */+export type { DecisionLane };+export { DECISION_LANES };++const LANE_LABEL: Record<DecisionLane, string> = {+ active: DECISION_CURRENCY_LABELS.active,+ candidates: "Candidates",+ needs_review: DECISION_CURRENCY_LABELS.needs_review,+ uncheckable: DECISION_CURRENCY_LABELS.uncheckable,+ history: "History",+};++/**+ * What the lane holds, and what the reader is being asked to do with it. Shown+ * under the tab row, because a lane whose name is a noun still owes the reader+ * a sentence about why its rows are in it.+ */+const LANE_DESCRIPTION: Record<DecisionLane, string> = {+ active:+ "Accepted decisions that still describe the code they name. These are the rules, and they are what an agent is given when it edits a governed file.",+ candidates:+ "Records the indexer inferred and nobody has accepted. They govern nothing and reach no agent. Read the evidence, then accept the ones that are real.",+ needs_review:+ "Accepted decisions whose files have moved since. They still bind, and they are worth re-reading before you rely on one.",+ uncheckable:+ "Accepted decisions that name no file or module. Nothing can check them against the code and no agent editing a file will be given one. Add the paths they govern and they move to Active.",+ history:+ "Decisions that were accepted and then withdrawn, superseded or dismissed. Kept so the record of what changed survives.",+};++/** An empty lane says what will fill it and what the reader can do next. */+const LANE_EMPTY: Record<DecisionLane, string> = {+ active:+ "Nothing here governs yet. Accept a candidate, or record a decision yourself, and it will appear here.",+ candidates:+ "No candidates are waiting. The indexer raises them from pull requests, commits, comments and your own sessions.",+ needs_review: "No accepted decision has drifted from the code it names.",+ uncheckable: "Every accepted decision names the code it governs.",+ history: "Nothing has been retired yet.",+};++export interface DecisionReviewLanesProps {+ lane: DecisionLane;+ onLaneChange: (lane: DecisionLane) => void;+ /**+ * Rows for the current lane. The caller filters, because the lane is a+ * server query parameter and this shows one page of it.+ */+ decisions: DecisionRecord[] | undefined;+ /**+ * Per-lane totals for the tab badges. A lane whose count is unknown renders+ * without one rather than with a number nobody measured.+ */+ counts?: Partial<Record<DecisionLane, number>>;+ /**+ * Narrow the lane to one capture source, or `"all"`. A separate axis from+ * the lane: the lane asks who accepted a record, this asks where it came+ * from, and the two never select the same thing.+ */+ source?: string;+ onSourceChange?: (source: string) => void;+ /** Accepts the candidate. Omit where the surface cannot write. */+ onAccept?: (decision: DecisionRecord) => void;+ /** Dismisses the candidate as a tombstone. Omit where the surface cannot write. */+ onDismiss?: (decision: DecisionRecord) => void;+ /**+ * Why writes are unavailable, shown in place of the verbs. A control that+ * cannot act has to expose its reason, and a review surface that silently+ * renders no actions reads as one with nothing to do.+ */+ readOnlyReason?: string;+ /**+ * Ids whose review write is in flight; their verbs are disabled. A set+ * rather than one id, because two reviews can overlap and a single value+ * re-enabled the second row the moment the first resolved.+ */+ pendingIds?: ReadonlySet<string>;+ repoId: string;+ linkPrefix?: string;+ LinkComponent?: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;+ error?: unknown;+ isLoading?: boolean;+ onRetry?: () => void;+}++export function DecisionReviewLanes({+ lane,+ onLaneChange,+ decisions,+ counts,+ source = "all",+ onSourceChange,+ onAccept,+ onDismiss,+ readOnlyReason,+ pendingIds,+ repoId,+ linkPrefix,+ LinkComponent = "a",+ error,+ isLoading,+ onRetry,+}: DecisionReviewLanesProps) {+ const prefix = linkPrefix ?? `/repos/${repoId}`;+ const Link = LinkComponent;++ const tabs: ViewTab[] = DECISION_LANES.map((id) => {+ const badge = counts?.[id];+ return badge === undefined+ ? { id, label: LANE_LABEL[id] }+ : { id, label: LANE_LABEL[id], badge };+ });++ const rows = decisions ?? [];++ return (+ <ViewTabs+ tabs={tabs}+ value={lane}+ onValueChange={(id) => onLaneChange(id as DecisionLane)}+ >+ <div className="flex flex-wrap items-start justify-between gap-3">+ <p className="min-w-0 max-w-[68ch] flex-1 text-xs text-[var(--color-text-secondary)]">+ {LANE_DESCRIPTION[lane]}+ </p>+ {/* Built from the shared source list rather than from the loaded rows:+ a lane page is one window, so a source absent from it would become+ unselectable, which is the same defect wearing a dynamic coat. */}+ {onSourceChange && (+ <select+ value={source}+ onChange={(e) => onSourceChange(e.target.value)}+ aria-label="Filter by source"+ className="shrink-0 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)]"+ >+ <option value="all">All sources</option>+ {DECISION_SOURCES.filter((s) => !isRetiredDecisionSource(s)).map(+ (s) => (+ <option key={s} value={s}>+ {decisionSourceLabel(s)}+ </option>+ ),+ )}+ </select>+ )}+ </div>++ {error ? (+ <ApiError+ title="Couldn't load this lane"+ message="An error occurred while fetching decisions."+ {...(onRetry ? { onRetry } : {})}+ />+ ) : rows.length === 0 ? (+ isLoading ? null : (+ <EmptyState+ title={`Nothing in ${LANE_LABEL[lane].toLowerCase()}`}+ description={+ source === "all"+ ? LANE_EMPTY[lane]+ : `No ${decisionSourceLabel(source)} record is in this lane. The lane itself may not be empty; clear the source filter to see it.`+ }+ />+ )+ ) : (+ // Hairline-separated rows rather than a table or a grid of cards: the+ // rows are unequal in height because a candidate carries its evidence,+ // and repeating a bordered container at one weight per record turns+ // the lane into box soup.+ <ul className="divide-y divide-[var(--color-border-subtle)] border-t border-[var(--color-border-subtle)]">+ {rows.map((d) => (+ <DecisionLaneRow+ key={d.id}+ decision={d}+ lane={lane}+ href={`${prefix}/decisions/${d.id}`}+ Link={Link}+ {...(onAccept ? { onAccept } : {})}+ {...(onDismiss ? { onDismiss } : {})}+ {...(readOnlyReason ? { readOnlyReason } : {})}+ pending={pendingIds?.has(d.id) ?? false}+ />+ ))}+ </ul>+ )}+ </ViewTabs>+ );+}++interface RowProps {+ decision: DecisionRecord;+ lane: DecisionLane;+ href: string;+ Link: React.ElementType<{+ href: string;+ className?: string;+ children: React.ReactNode;+ }>;+ onAccept?: (decision: DecisionRecord) => void;+ onDismiss?: (decision: DecisionRecord) => void;+ readOnlyReason?: string;+ pending?: boolean;+}++const MICRO_LABEL =+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";++function DecisionLaneRow({+ decision: d,+ lane,+ href,+ Link,+ onAccept,+ onDismiss,+ readOnlyReason,+ pending,+}: RowProps) {+ const staleness = describeRecordStaleness(d);+ const currency = d.currency ?? null;+ const evidence = d.evidence_preview;+ const scope = [...d.affected_files, ...d.affected_modules];+ // The same four checks the engine refuses on, asked before the button is+ // drawn. A candidate that names nothing already renders "names nothing"+ // beside an Accept that could only fail; predicting the refusal is what+ // turns that into a control the reader can understand.+ const blockers = decisionAcceptanceBlockers(d);++ return (+ <li className="flex flex-col gap-2 py-3 sm:flex-row sm:items-start sm:justify-between sm:gap-6">+ <div className="min-w-0 flex-1 space-y-1.5">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <Link+ href={href}+ className="text-sm font-medium text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)]"+ >+ {stripMarkdown(d.title)}+ </Link>+ {/* Marked only where it is an exception. An accepted decision that+ still describes its code is the quiet default and carries no+ badge; a currency the reader cannot guess does. */}+ {currency !== null && currency !== "active" && (+ <CurrencyMark currency={currency as DecisionCurrency} />+ )}+ {d.verification && d.verification !== "exact" && (+ <VerificationBadge verification={d.verification} />+ )}+ </div>++ <p className="text-xs text-[var(--color-text-secondary)]">+ {stripMarkdown(d.decision || d.title)}+ </p>++ {/* Candidates carry the quote they were drawn from. It is the whole+ basis for accepting or dismissing one, and sending the reader to a+ detail page to find it is what leaves a review queue unworked. */}+ {lane === "candidates" && evidence?.source_quote && (+ <figure className="space-y-1 border-l-2 border-[var(--color-border-default)] bg-[var(--color-bg-inset)] px-3 py-2">+ <blockquote className="text-xs italic text-[var(--color-text-secondary)]">+ “{stripMarkdown(evidence.source_quote)}”+ </blockquote>+ <figcaption className={MICRO_LABEL}>+ {decisionSourceLabel(evidence.source)}+ {evidence.evidence_file ? ` · ${evidence.evidence_file}` : ""}+ {evidence.evidence_line != null+ ? `:${evidence.evidence_line}`+ : ""}+ {(d.evidence_count ?? 0) > 1+ ? ` · ${(d.evidence_count ?? 0) - 1} more`+ : ""}+ </figcaption>+ </figure>+ )}++ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span className={MICRO_LABEL}>{decisionSourceLabel(d.source)}</span>+ {/* One path reads as the path. Several read as a count, with the+ list on the title, because the alternative is a row whose+ primary label is crowded off by its own metadata. */}+ <span className={MICRO_LABEL} title={scope.join(", ")}>+ {scope.length === 0+ ? "names nothing"+ : scope.length === 1+ ? scope[0]+ : `${scope.length} paths`}+ </span>+ {staleness.kind === "moved" && (+ <span className={MICRO_LABEL} title={staleness.sentence}>+ {staleness.short} changed+ </span>+ )}+ </div>+ </div>++ {/* One primary verb per row, and only in the lane where it means+ something. Accepting is the review action; everything else on the+ record lives on its detail page. */}+ {lane === "candidates" && (+ <div className="flex shrink-0 flex-col items-start gap-1 sm:items-end">+ {readOnlyReason ? (+ <span className="text-xs text-[var(--color-text-tertiary)]">+ {readOnlyReason}+ </span>+ ) : (+ <>+ <div className="flex items-center gap-2">+ {onDismiss && (+ <Button+ variant="ghost"+ size="sm"+ disabled={pending}+ onClick={() => onDismiss(d)}+ >+ Dismiss+ </Button>+ )}+ {onAccept && (+ <Button+ size="sm"+ disabled={pending || blockers.length > 0}+ title={blockers.length ? blockers.join("; ") : undefined}+ onClick={() => onAccept(d)}+ >+ {pending ? "Accepting…" : "Accept"}+ </Button>+ )}+ </div>+ {/* Dismissing is always available: a candidate that cannot be+ accepted is exactly the one worth tombstoning. The sentence+ is text rather than only a tooltip, because a disabled+ button takes no focus and a tooltip on it is mouse-only. */}+ {onAccept && blockers.length > 0 && (+ <p className="max-w-[28ch] text-right text-xs text-[var(--color-text-tertiary)]">+ Cannot accept: {blockers.join("; ")}. Fill it in with{" "}+ <code className="font-mono text-[11px]">+ repowise decision confirm {d.id.slice(0, 8)}+ </code>+ .+ </p>+ )}+ </>+ )}+ </div>+ )}+ </li>+ );+}++/**+ * A currency the reader cannot infer from the row, as a dot plus the word.+ *+ * Deliberately not semantic colour. `needs_review` is not a warning and+ * `uncheckable` is not an error: both describe decisions somebody accepted,+ * and painting them amber would put them on the health scale, where amber+ * means the code is in trouble. The word carries the meaning, the title+ * carries the sentence.+ */+function CurrencyMark({ currency }: { currency: DecisionCurrency }) {+ return (+ <span+ className="inline-flex items-center gap-1.5 whitespace-nowrap text-[11px] text-[var(--color-text-tertiary)]"+ title={DECISION_CURRENCY_DESCRIPTIONS[currency]}+ >+ <span+ aria-hidden+ className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-text-tertiary)]"+ />+ {DECISION_CURRENCY_LABELS[currency]}+ </span>+ );+}diff --git a/packages/ui/src/decisions/decision-status-mark.tsx b/packages/ui/src/decisions/decision-status-mark.tsxindex 05c3e9aee..648707dd1 100644--- a/packages/ui/src/decisions/decision-status-mark.tsx+++ b/packages/ui/src/decisions/decision-status-mark.tsx@@ -2,7 +2,9 @@ import * as React from "react";import { cn } from "../lib/cn";import type { DecisionStatus } from "@repowise-dev/types/decisions";-const STATUS_COLOR: Record<string, string> = {+// Keyed on the shared ladder rather than on `string`, so a status added to the+// vocabulary fails a typecheck here instead of silently rendering grey.+const STATUS_COLOR: Record<DecisionStatus, string> = {active: "var(--color-success)",proposed: "var(--color-accent-primary)",deprecated: "var(--color-error)",@@ -21,7 +23,11 @@ const STATUS_COLOR: Record<string, string> = {* colours depending on where you were looking.*/export function decisionStatusColor(status: DecisionStatus | string): string {- return STATUS_COLOR[status] ?? "var(--color-text-tertiary)";+ // `status` is an unconstrained string on the wire, so index safely: a row+ // sourced `toString` would otherwise hand a function to a style attribute.+ return Object.hasOwn(STATUS_COLOR, status)+ ? STATUS_COLOR[status as DecisionStatus]+ : "var(--color-text-tertiary)";}export interface DecisionStatusMarkProps {diff --git a/packages/ui/src/decisions/decisions-table.tsx b/packages/ui/src/decisions/decisions-table.tsxindex 2f77d3e26..55696dc21 100644--- a/packages/ui/src/decisions/decisions-table.tsx+++ b/packages/ui/src/decisions/decisions-table.tsx@@ -11,6 +11,13 @@ import { VerificationBadge } from "./verification-badge";import { DecisionStatusMark } from "./decision-status-mark";import { describeRecordStaleness } from "./decision-staleness";import { stripMarkdown } from "../lib/format";+import {+ DECISION_SOURCES,+ DECISION_STATUSES,+ DECISION_STATUS_LABELS,+ decisionSourceLabel,+ isRetiredDecisionSource,+} from "@repowise-dev/types/decisions";import type {DecisionRecord,DecisionStatus,@@ -18,41 +25,6 @@ import type {DecisionScope,} from "@repowise-dev/types/decisions";-// The engine emits more sources than the four the type union names: a live-// index carries comment / pr / adr / session as well. Unmapped values used-// to fall through raw, so one column mixed "Docs" with "pr". The retired-// entries below stay in the map so an old row still renders a label; see-// RETIRED_SOURCES for why they are not offered as filters.-const SOURCE_LABEL: Record<string, string> = {- inline_marker: "Marker",- git_archaeology: "Git history",- readme_mining: "Docs",- cli: "Manual",- comment: "Comment",- pr: "Pull request",- adr: "ADR",- changelog: "Changelog",- session: "Session",-};--// Sources the engine no longer emits and whose rows were purged with them.-// Mirrors `RETIRED_SOURCES` in `analysis/decisions/provenance.py`; a record-// carrying one of these cannot exist, so offering it as a filter is a control-// that cannot act. Note `code_comment` is retired and `comment` is not: they-// are different values and a live index still carries the second.-const RETIRED_SOURCES = new Set(["code_comment", "readme_mining", "changelog"]);--/**- * `source` is an unconstrained string on the wire, so a plain index into the- * map reaches `Object.prototype`: a row sourced `toString` would hand a- * function to `localeCompare` and throw inside the sort comparator.- */-function sourceLabel(source: string): string {- return Object.hasOwn(SOURCE_LABEL, source)- ? (SOURCE_LABEL[source] as string)- : source;-}-export type DecisionStatusFilter = DecisionStatus | "all";export type DecisionSourceFilter = DecisionSource | "all";export type DecisionScopeFilter = DecisionScope | "all";@@ -116,19 +88,21 @@ export function DecisionsTable({// server round trip on the whole store, so the two live sources could not// be reached at all and the retired one could only empty the table.//- // Built from the label map rather than from the loaded rows on purpose: the- // rows are one page of fifty, so a source that happens not to appear on- // page one would become unselectable, which is the same defect wearing a- // dynamic coat. Anything present but unmapped is unioned in so a source the- // engine adds is reachable before this map learns its name.+ // Built from the shared source list rather than from the loaded rows on+ // purpose: the rows are one page of fifty, so a source that happens not to+ // appear on page one would become unselectable, which is the same defect+ // wearing a dynamic coat. Anything present but unlisted is unioned in so a+ // source the engine adds is reachable before this build learns its name.const sourceOptions = [...new Set([- ...Object.keys(SOURCE_LABEL).filter((s) => !RETIRED_SOURCES.has(s)),+ ...DECISION_SOURCES,...(decisions ?? []).map((d) => d.source).filter(Boolean),]),]- .filter((s) => !RETIRED_SOURCES.has(s))- .sort((a, b) => sourceLabel(a).localeCompare(sourceLabel(b)));+ .filter((s) => !isRetiredDecisionSource(s))+ .sort((a, b) =>+ decisionSourceLabel(a).localeCompare(decisionSourceLabel(b)),+ );const columns: ResponsiveColumn<DecisionRecord>[] = [{@@ -185,7 +159,7 @@ export function DecisionsTable({header: "Source",priority: 3,cellClassName: "text-[var(--color-text-secondary)]",- render: (d) => sourceLabel(d.source),+ render: (d) => decisionSourceLabel(d.source),},// Scope, Confidence and Trust all left this row. Scope is `cross-module`// on three quarters of a live index and confidence is source rank times@@ -288,14 +262,16 @@ export function DecisionsTable({className="w-full sm:w-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)]"><option value="all">All statuses</option>- <option value="active">Active</option>- <option value="proposed">Proposed</option>- <option value="deprecated">Deprecated</option>- {/* Dismissed records are excluded from every default listing, so- without this option a dismissal is a one-way door: nothing in the- UI could show what had been dismissed, or undo one. */}- <option value="dismissed">Dismissed</option>- <option value="superseded">Superseded</option>+ {/* From the shared ladder, so a status the engine adds is reachable+ without editing this list. Dismissed is in it: dismissed records+ are excluded from every default listing, so without the option a+ dismissal would be a one-way door with nothing in the UI able to+ show what had been dismissed, or undo one. */}+ {DECISION_STATUSES.map((s) => (+ <option key={s} value={s}>+ {DECISION_STATUS_LABELS[s]}+ </option>+ ))}</select><selectvalue={filters.source}@@ -308,7 +284,7 @@ export function DecisionsTable({<option value="all">All sources</option>{sourceOptions.map((s) => (<option key={s} value={s}>- {sourceLabel(s)}+ {decisionSourceLabel(s)}</option>))}</select>diff --git a/packages/ui/src/decisions/index.ts b/packages/ui/src/decisions/index.tsindex 8be936d70..44136f355 100644--- a/packages/ui/src/decisions/index.ts+++ b/packages/ui/src/decisions/index.ts@@ -1,4 +1,6 @@export * from "./decisions-table";+export * from "./decision-review-lanes";+export * from "./decision-capture-settings";export * from "./module-link-editor";export * from "./verification-badge";export * from "./decision-status-mark";diff --git a/packages/vscode/webview/src/views/decisions/App.tsx b/packages/vscode/webview/src/views/decisions/App.tsxindex ab57903e7..c02e1ac21 100644--- a/packages/vscode/webview/src/views/decisions/App.tsx+++ b/packages/vscode/webview/src/views/decisions/App.tsx@@ -8,15 +8,25 @@ import {} from "@repowise-dev/ui/decisions/decision-status-mark";import { WikiMarkdown } from "@repowise-dev/ui/wiki/wiki-markdown";import { formatRelativeTime, stripMarkdown } from "@repowise-dev/ui/lib/format";+import {+ DECISION_STATUSES,+ DECISION_STATUS_LABELS,+} from "@repowise-dev/types/decisions";import type { DecisionRecordResponse } from "@repowise-dev/api-client/types";import type { ViewProps } from "../../runtime/mount";type Status = DecisionRecordResponse["status"];-const STATUS_ORDER: readonly Status[] = ["active", "proposed", "deprecated", "superseded"];+// The shared ladder, not a local copy. The copy that was here ordered+// deprecated ahead of superseded while the list endpoint ordered them the+// other way, so the same rows ranked differently depending on the surface.+const STATUS_ORDER: readonly Status[] = DECISION_STATUSES;function statusLabel(status: Status): string {- return status.charAt(0).toUpperCase() + status.slice(1);+ // `status` is a strict union here but an unconstrained string on the wire,+ // so fall back to the raw value: a chip carrying a count needs a word beside+ // it, and a blank label is worse than an unfamiliar one.+ return DECISION_STATUS_LABELS[status] ?? status;}/** Record section labels. Uppercase micro-labels are mono: it separates adiff --git a/packages/web/src/app/repos/[id]/decisions/page.tsx b/packages/web/src/app/repos/[id]/decisions/page.tsxindex 74dd97557..85f65d897 100644--- a/packages/web/src/app/repos/[id]/decisions/page.tsx+++ b/packages/web/src/app/repos/[id]/decisions/page.tsx@@ -4,11 +4,15 @@ import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { OverviewSection } from "@repowise-dev/ui/overview";import { PageLede } from "@repowise-dev/ui/shared/page-lede";import { CheckoutFacts } from "@repowise-dev/ui/decisions";-import { getDecisionCounts, listDecisions } from "@/lib/api/decisions";+import {+ getDecisionCounts,+ getDecisionLaneCounts,+ listDecisions,+} from "@/lib/api/decisions";import { listEpisodes } from "@/lib/api/episodes";import { ApiClientError } from "@/lib/api/client";-import { DecisionsTableWrapper } from "@/components/decisions/decisions-table-wrapper";import { AddDecisionButton } from "@/components/decisions/add-decision-button";+import { DecisionReviewWrapper } from "@/components/decisions/decision-review-wrapper";export const revalidate = 30;export const metadata: Metadata = { title: "Decisions" };@@ -84,6 +88,14 @@ export default async function DecisionsPage({ params }: Props) {include_proposed: true,}).catch(() => undefined);+ // The lede's figure. `/decisions/counts` groups the status column, which is+ // the projection kept in step for readers that predate the acceptance split,+ // so its `active` counts records nobody accepted. The number this page leads+ // with is what the repository actually stands behind, which is the lane+ // count. Degrades the same way: a frontend ahead of its backend 404s here+ // and falls back to the projection rather than losing the page.+ const lanes = await getDecisionLaneCounts(repoId).catch(() => undefined);+// Facts about the checkout, which is the structural tier of the episode// store. Five rows on this repository and none of them need history, a key// or a transcript, so this is the one section that says something on a@@ -103,11 +115,22 @@ export default async function DecisionsPage({ params }: Props) {// With counts we can state a measured total; without them we report only// what this page actually loaded, and say so. Never a number nobody counted.- const total = counts?.total;+ const total = lanes?.total ?? counts?.total;const proposed =- counts?.proposed ?? decisions.filter((d) => d.status === "proposed").length;- const active =- counts?.active ?? decisions.filter((d) => d.status === "active").length;+ lanes?.candidates ??+ counts?.proposed ??+ decisions.filter((d) => d.status === "proposed").length;+ // Everything with an acceptance row, which is what "accepted" means. Not+ // `governing`: that is `active + needs_review` and leaves the accepted but+ // unscoped records out, so the lede and the Uncheckable tab under it would+ // not add up. The status fallback counts the projection instead, and it can+ // include records nobody accepted, so it is labelled differently below.+ const accepted =+ lanes !== undefined+ ? lanes.active + lanes.needs_review + lanes.uncheckable+ : (counts?.active ??+ decisions.filter((d) => d.status === "active").length);+ const measuredByLane = lanes !== undefined;const empty = total === 0;const denominator =total !== undefined@@ -121,60 +144,78 @@ export default async function DecisionsPage({ params }: Props) {>{/* The headline used to be the size of the review queue, so the largestnumber on the page pointed at the work nobody had done rather than at- what the repository actually stands behind. The confirmed count leads- now; the queue keeps its sentence, because 87 unconfirmed proposals- are worth knowing about, just not worth 52px.-- The count is the measured `active` total and is not de-duplicated. A- live index carries near-identical pairs, two spellings of one fix- landing as two confirmed records, and collapsing them here would need- a title-similarity threshold tuned on one repository sitting in a- page component, where a wrong merge hides a record a human confirmed.- That belongs to supersession, which is structural and not yet built.- Until then the number is honest about what it counts and the pairs- stay visible in the table, where they can be deprecated. */}+ what the repository actually stands behind. The accepted count leads+ now; the queue keeps its sentence, because a few hundred unreviewed+ candidates are worth knowing about, just not worth 52px.++ It counts acceptance rows, not the status column, so it is every+ record somebody accepted: the ones that govern plus the ones that+ were accepted and then drifted or turned out to name nothing. Those+ are separate lanes below and the four numbers add up.++ The count is not de-duplicated. A live index carries near-identical+ pairs, two spellings of one fix landing as two accepted records, and+ collapsing them here would need a title-similarity threshold tuned on+ one repository sitting in a page component, where a wrong merge hides+ a record a human accepted. That belongs to supersession, which is+ structural and not yet built. Until then the number is honest about+ what it counts and the pairs stay visible in their lane, where they+ can be superseded. */}<PageLede- label="Confirmed"- value={active.toLocaleString()}+ label={measuredByLane ? "Accepted" : "Confirmed"}+ value={accepted.toLocaleString()}unit={denominator}layout="beside">- {empty || active === 0 ? (+ {empty ? (+ <p>+ Decisions land here as the indexer mines them from pull requests,+ commit messages, code comments and your own sessions, and as you+ record them yourself — below, or with{" "}+ <code>repowise decision add</code>. Each one keeps the quote it was+ drawn from and the files it governs.+ </p>+ ) : accepted === 0 ? (+ // A repository with records and no accepted one is not an empty+ // repository, and it used to get the copy for one: "decisions land+ // here as the indexer mines them" on a store already holding five+ // hundred of them. It is also what a store looks like the first time+ // it is read after the acceptance split, when everything the status+ // column called active turns out to be something nobody accepted, so+ // this is the state most likely to be read by somebody surprised.<><p>- Decisions land here as the indexer mines them from pull requests,- commit messages, code comments and your own sessions, and as you- record them yourself — below, or with{" "}- <code>repowise decision add</code>. Each one keeps the quote it- was drawn from and the files it governs.+ Nothing here governs yet. A record governs only once somebody+ accepts it, naming the files it covers and why — mining it,+ seeing it recur, and scoring it confident all stop short of that.+ </p>+ <p>+ {proposed.toLocaleString()} candidate+ {proposed === 1 ? " is" : "s are"} waiting below, and{" "}+ {proposed === 1 ? "it is" : "they are"} all still here: nothing+ was deleted and every id still resolves. If this page used to+ show confirmed decisions, those are the records now in+ Candidates. Accepting one takes a click and changes no code.</p>- {proposed > 0 && (- <p>- {proposed.toLocaleString()} proposal- {proposed === 1 ? " is" : "s are"} waiting below. Confirming one- takes a click and changes no code; it marks the record as- something the team stands behind, which is what makes it worth- quoting back to an agent later.- </p>- )}</>) : (<><p>- {active.toLocaleString()} record- {active === 1 ? " is" : "s are"} confirmed: somebody read{" "}- {active === 1 ? "it" : "them"} and marked{" "}- {active === 1 ? "it" : "them"} as something the team stands- behind, which is what makes {active === 1 ? "it" : "them"} worth+ {accepted.toLocaleString()} record+ {accepted === 1 ? " is" : "s are"} accepted: somebody read{" "}+ {accepted === 1 ? "it" : "them"} and marked{" "}+ {accepted === 1 ? "it" : "them"} as something the team stands+ behind, which is what makes {accepted === 1 ? "it" : "them"} worthquoting back to an agent later.</p>{proposed > 0 && (<p>- {proposed.toLocaleString()} more are proposals the indexer mined- and nobody has confirmed yet. Until one is confirmed it is a- guess about your codebase rather than a rule for it. Filter by- status below to work through them; confirming or dismissing one- takes a click and changes no code.+ {proposed.toLocaleString()} more are candidates the indexer+ mined and nobody has accepted. Until one is accepted it is a+ guess about your codebase rather than a rule for it, and no+ agent is ever given one. Open the Candidates lane below to work+ through them; accepting or dismissing one takes a click and+ changes no code.</p>)}</>@@ -203,17 +244,14 @@ export default async function DecisionsPage({ params }: Props) {{!empty && (<OverviewSection- title="All decisions"- description="Confirmed records first, then the proposals most likely to be real. Filter by status to work the queue, or by source to see where a record came from. The last column is a count, not a score: how many of the files a record names have been committed to since it was recorded, or are no longer tracked."+ title="Review"+ description="Split by what each record's acceptance amounts to, not by a status word. Every record is in exactly one lane and the counts add up: what governs, what nobody has reviewed, what has drifted from the code it names, what names nothing at all, and what has been retired.">- <DecisionsTableWrapper- repoId={repoId}- initialData={decisions}- {...(total !== undefined ? { initialTotal: total } : {})}- pageSize={PAGE_SIZE}- />+ <DecisionReviewWrapper repoId={repoId} pageSize={PAGE_SIZE} /></OverviewSection>)}++</PageShell>);}diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsxindex e27f9a64c..462e0164b 100644--- a/packages/web/src/app/repos/[id]/settings/page.tsx+++ b/packages/web/src/app/repos/[id]/settings/page.tsx@@ -3,6 +3,7 @@ import Link from "next/link";import { notFound } from "next/navigation";import { OverviewSection } from "@repowise-dev/ui/overview";import { PageShell } from "@repowise-dev/ui/shared/page-shell";+import { DecisionCaptureSettingsWrapper } from "@/components/decisions/decision-capture-settings-wrapper";import { RefactoringSettingsSection } from "@/components/repos/refactoring-settings-section";import { ProviderSettingsPanel } from "@/components/settings/provider-settings-panel";import { getRepo } from "@/lib/api/repos";@@ -79,6 +80,13 @@ export default async function RepoSettingsPage({ params }: Props) {<ProviderSettingsPanel repoId={id} /></OverviewSection>+ <OverviewSection+ title="Decision capture"+ description="What mines architectural decisions from this repository, and whether any of it may send prose to your configured model. Capture only ever produces candidates: nothing here can accept a decision on your behalf."+ >+ <DecisionCaptureSettingsWrapper repoId={id} />+ </OverviewSection>+<OverviewSectiontitle="Refactoring code generation"description="Opt in to turning refactoring plans into reviewable diffs with your configured model."diff --git a/packages/web/src/components/decisions/add-decision-button.tsx b/packages/web/src/components/decisions/add-decision-button.tsxindex c53645adb..e79a16f5d 100644--- a/packages/web/src/components/decisions/add-decision-button.tsx+++ b/packages/web/src/components/decisions/add-decision-button.tsx@@ -42,8 +42,9 @@ export function AddDecisionButton({ repoId }: { repoId: string }) {<DialogHeader><DialogTitle>Record a decision</DialogTitle><DialogDescription>- Something the team has settled on. It is recorded as confirmed,- because you are the person confirming it.+ Something the team has settled on. Name the files it governs and+ it is recorded as confirmed, because you are the person+ confirming it.</DialogDescription></DialogHeader><DecisionCreateFormdiff --git a/packages/web/src/components/decisions/decision-capture-settings-wrapper.tsx b/packages/web/src/components/decisions/decision-capture-settings-wrapper.tsxnew file mode 100644index 000000000..ef8abcda0--- /dev/null+++ b/packages/web/src/components/decisions/decision-capture-settings-wrapper.tsx@@ -0,0 +1,66 @@+"use client";++import * as React from "react";+import useSWR from "swr";+import { toast } from "sonner";+import { DecisionCaptureSettings } from "@repowise-dev/ui/decisions/decision-capture-settings";+import type { DecisionSettingsUpdate } from "@repowise-dev/types/decisions";+import {+ getDecisionSettings,+ updateDecisionSettings,+} from "@/lib/api/decisions";++/**+ * The host half of the capture settings: the fetch, the write, and the+ * optimistic rollback.+ *+ * The panel writes through `mutate` with the server's response rather than the+ * value it sent, because the resolver answers a wider question than the switch+ * asked: turning one source off can move the preset to `custom`, and turning+ * the master model switch off changes every source's effective status. Echoing+ * back what was sent would leave those reading stale until the next fetch.+ */+export function DecisionCaptureSettingsWrapper({ repoId }: { repoId: string }) {+ const { data, error, mutate, isLoading } = useSWR(+ [`/api/repos/${repoId}/decisions/settings`],+ () => getDecisionSettings(repoId),+ );++ const onChange = React.useCallback(+ async (update: DecisionSettingsUpdate) => {+ try {+ await mutate(+ () => updateDecisionSettings(repoId, update),+ // No optimistic payload: the resolved policy is not derivable from+ // the patch, so guessing it would flicker a wrong effective status.+ // The controls disable themselves for the duration instead.+ { revalidate: false, rollbackOnError: true },+ );+ } catch (err) {+ // A 409 is the panel's own case and it renders its own sentence for+ // it; anything else is worth a toast, because the control has already+ // rolled back and would otherwise fail silently.+ const message = err instanceof Error ? err.message : "";+ if (!/409|conflict/i.test(message)) {+ toast.error(+ message+ ? `Couldn't save capture settings: ${message}`+ : "Couldn't save capture settings.",+ );+ }+ throw err;+ }+ },+ [repoId, mutate],+ );++ return (+ <DecisionCaptureSettings+ settings={data}+ onChange={onChange}+ error={error}+ isLoading={isLoading}+ onRetry={() => void mutate()}+ />+ );+}diff --git a/packages/web/src/components/decisions/decision-review-wrapper.tsx b/packages/web/src/components/decisions/decision-review-wrapper.tsxnew file mode 100644index 000000000..dad86d8e7--- /dev/null+++ b/packages/web/src/components/decisions/decision-review-wrapper.tsx@@ -0,0 +1,190 @@+"use client";++import * as React from "react";+import useSWR from "swr";+import Link from "next/link";+import { toast } from "sonner";+import {+ DecisionReviewLanes,+ type DecisionLane,+} from "@repowise-dev/ui/decisions/decision-review-lanes";+import type { DecisionRecord } from "@repowise-dev/types/decisions";+import {+ getDecisionLaneCounts,+ listDecisions,+ patchDecision,+} from "@/lib/api/decisions";++interface Props {+ repoId: string;+ pageSize?: number;+}++/**+ * The host half of the review lanes: the per-lane fetch, the review writes,+ * and the refresh.+ *+ * The lane is a server query parameter rather than a client-side filter of a+ * loaded page. A live index carries 381 candidates against 122 accepted+ * records, so filtering a fifty-row window would show an empty Active lane on+ * a repository with a hundred rules in it.+ */+export function DecisionReviewWrapper({ repoId, pageSize = 50 }: Props) {+ const [lane, setLane] = React.useState<DecisionLane>("active");+ // A set, not one id: two accepts can be in flight, and a single value let+ // the first to resolve re-enable the second row's buttons while its own+ // write was still running, so a second click double-wrote.+ const [pending, setPending] = React.useState<ReadonlySet<string>>(new Set());+ const [page, setPage] = React.useState(0);+ const [source, setSource] = React.useState("all");++ const { data, error, mutate, isLoading } = useSWR(+ [`/api/repos/${repoId}/decisions`, "lane", lane, source, page, pageSize],+ () =>+ listDecisions(repoId, {+ lane,+ ...(source !== "all" ? { source } : {}),+ include_proposed: true,+ limit: pageSize,+ offset: page * pageSize,+ }),+ );++ // One aggregate over the acceptance join, not four page fetches. The badges+ // and the rows they label therefore come from the same question, and a lane+ // holding more rows than a page can carry still reports a measured total.+ //+ // Deliberately not /decisions/counts: that endpoint groups the status+ // column, which is the projection rather than the authority, so its+ // "active" would contradict the lane a reader then opened.+ const { data: counts, mutate: mutateCounts } = useSWR(+ [`/api/repos/${repoId}/decisions/lane-counts`],+ () => getDecisionLaneCounts(repoId),+ );++ // A lane change invalidates the offset: page 3 of Candidates is not page 3+ // of Active, and leaving it put lands the reader on an empty lane.+ // Either control invalidates the offset: page 3 of Candidates is not page 3+ // of Active, and leaving it put lands the reader on an empty lane.+ const changeLane = React.useCallback((next: DecisionLane) => {+ setLane(next);+ setPage(0);+ }, []);++ const changeSource = React.useCallback((next: string) => {+ setSource(next);+ setPage(0);+ }, []);++ const review = React.useCallback(+ async (d: DecisionRecord, status: "active" | "dismissed") => {+ setPending((prev) => new Set(prev).add(d.id));+ try {+ await patchDecision(repoId, d.id, { status });+ toast.success(+ status === "active"+ ? "Accepted. It governs the files it names."+ : "Dismissed. Reindexing will not propose it again.",+ );+ // Both, and in parallel: a review action moves a record between lanes,+ // so refreshing the rows without the badges leaves every tab count+ // contradicting the list under it.+ await Promise.all([mutate(), mutateCounts()]);+ } catch (err) {+ // The acceptance contract refuses a record with no reason, scope or+ // evidence, and it names which. Surface that sentence rather than a+ // generic failure: it is the whole instruction for what to do next.+ toast.error(+ err instanceof Error+ ? `Couldn't ${status === "active" ? "accept" : "dismiss"}: ${err.message}`+ : "The review action failed.",+ );+ } finally {+ setPending((prev) => {+ const next = new Set(prev);+ next.delete(d.id);+ return next;+ });+ }+ },+ [repoId, mutate, mutateCounts],+ );++ const rows = data ?? [];+ // Only when the rows and the badge count the same set. Under a source filter+ // the lane count is the wrong denominator, so the range says what it loaded+ // and nothing more rather than "1-12 of 381".+ const total = source === "all" ? counts?.[lane] : undefined;+ const first = page * pageSize + 1;+ const last = page * pageSize + rows.length;+ const hasNext =+ total !== undefined ? last < total : rows.length === pageSize;++ return (+ <div className="space-y-4">+ <DecisionReviewLanes+ lane={lane}+ onLaneChange={changeLane}+ decisions={data}+ {...(counts ? { counts } : {})}+ source={source}+ onSourceChange={changeSource}+ onAccept={(d) => void review(d, "active")}+ onDismiss={(d) => void review(d, "dismissed")}+ pendingIds={pending}+ repoId={repoId}+ LinkComponent={Link}+ error={error}+ isLoading={isLoading}+ onRetry={() => void mutate()}+ />++ {/* Paged, because a live index carries 381 candidates against a 50-row+ window. The denominator is the lane's own measured count, so the+ range and the badge above it come from one number. */}+ {(page > 0 || hasNext) && (+ <div className="flex items-center justify-between gap-4 border-t border-[var(--color-border-default)] pt-3">+ <p className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">+ {rows.length > 0 ? `${first}–${last}` : "0"}+ {total !== undefined ? ` of ${total.toLocaleString()}` : ""}+ </p>+ <div className="flex items-center gap-2">+ <PageButton+ onClick={() => setPage((p) => Math.max(0, p - 1))}+ disabled={page === 0 || isLoading}+ >+ Previous+ </PageButton>+ <PageButton+ onClick={() => setPage((p) => p + 1)}+ disabled={!hasNext || isLoading}+ >+ Next+ </PageButton>+ </div>+ </div>+ )}+ </div>+ );+}++function PageButton({+ onClick,+ disabled,+ children,+}: {+ onClick: () => void;+ disabled: boolean;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ className="rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:opacity-40 disabled:hover:border-[var(--color-border-default)] disabled:hover:text-[var(--color-text-secondary)]"+ >+ {children}+ </button>+ );+}diff --git a/packages/web/src/components/decisions/decisions-table-wrapper.tsx b/packages/web/src/components/decisions/decisions-table-wrapper.tsxdeleted file mode 100644index d03e40b2a..000000000--- a/packages/web/src/components/decisions/decisions-table-wrapper.tsx+++ /dev/null@@ -1,178 +0,0 @@-"use client";--import * as React from "react";-import useSWR from "swr";-import Link from "next/link";-import {- DecisionsTable,- type DecisionsTableFilters,-} from "@repowise-dev/ui/decisions/decisions-table";-import { getDecisionCounts, listDecisions } from "@/lib/api/decisions";-import type { DecisionRecord } from "@repowise-dev/types/decisions";-import type { DecisionCounts } from "@repowise-dev/api-client/types";--interface DecisionsTableWrapperProps {- repoId: string;- initialData?: DecisionRecord[];- /** Measured total for the unfiltered set, from the server's COUNT. */- initialTotal?: number;- pageSize?: number;-}--/**- * Data wrapper for the decisions table.- *- * Pages on the server. It used to pull `limit: 100` in one shot and render- * every row: on a repository with several hundred records that is ~920KB of- * JSON for a table nobody scrolls past the top of, and it still could not show- * the rest. The window is now `pageSize` rows and the count beside it comes- * from the aggregate endpoint, so "51–100 of 500" is measured on both sides.- */-export function DecisionsTableWrapper({- repoId,- initialData,- initialTotal,- pageSize = 50,-}: DecisionsTableWrapperProps) {- const [filters, setFilters] = React.useState<DecisionsTableFilters>({- status: "all",- source: "all",- });- const [page, setPage] = React.useState(0);-- const status = filters.status !== "all" ? filters.status : undefined;- const source = filters.source !== "all" ? filters.source : undefined;-- // A filter change invalidates the offset — page 3 of "all" is not page 3 of- // "active", and leaving it put lands the reader on an empty table.- const handleFiltersChange = React.useCallback((next: DecisionsTableFilters) => {- setFilters(next);- setPage(0);- }, []);-- const { data, error, mutate, isLoading } = useSWR(- [`/api/repos/${repoId}/decisions`, status, source, page, pageSize],- () =>- listDecisions(repoId, {- ...(status ? { status } : {}),- ...(source ? { source } : {}),- include_proposed: true,- limit: pageSize,- offset: page * pageSize,- }),- { fallbackData: page === 0 && !status && !source ? initialData : undefined },- );-- // Counts follow the filters, because "of 500" beside a filtered table is the- // wrong denominator. Source is a server filter so it goes in the key; status- // is read off the returned per-status counts.- const { data: counts } = useSWR(- [`/api/repos/${repoId}/decisions/counts`, source],- () =>- getDecisionCounts(repoId, {- ...(source ? { source } : {}),- include_proposed: true,- }),- );-- const total = counts- ? countFor(counts, filters.status)- : !source && filters.status === "all"- ? initialTotal- : undefined;-- const rows = data ?? [];- const first = page * pageSize + 1;- const last = page * pageSize + rows.length;- const hasNext =- total !== undefined ? last < total : rows.length === pageSize;-- return (- <div className="space-y-4">- <DecisionsTable- decisions={data}- filters={filters}- onFiltersChange={handleFiltersChange}- repoId={repoId}- LinkComponent={Link}- error={error}- isLoading={isLoading}- onRetry={() => mutate()}- />-- {(page > 0 || hasNext) && (- <div className="flex items-center justify-between gap-4 border-t border-[var(--color-border-default)] pt-3">- <p className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">- {rows.length > 0 ? `${first}–${last}` : "0"}- {total !== undefined ? ` of ${total.toLocaleString()}` : ""}- </p>- <div className="flex items-center gap-2">- <PageButton- onClick={() => setPage((p) => Math.max(0, p - 1))}- disabled={page === 0 || isLoading}- >- Previous- </PageButton>- <PageButton- onClick={() => setPage((p) => p + 1)}- disabled={!hasNext || isLoading}- >- Next- </PageButton>- </div>- </div>- )}- </div>- );-}--/**- * The measured total behind one status filter, or undefined when nobody- * counted it.- *- * Not every status has a count: dismissed records are tombstones and the- * counts endpoint excludes them by design, so that filter reports the window- * it loaded rather than an "of 0" beside a table with rows in it. A switch- * rather than an index, so a status added later fails the build here instead- * of quietly reading undefined.- */-function countFor(- counts: DecisionCounts,- status: DecisionsTableFilters["status"],-): number | undefined {- switch (status) {- case "all":- return counts.total;- case "active":- return counts.active;- case "proposed":- return counts.proposed;- case "deprecated":- return counts.deprecated;- case "superseded":- return counts.superseded;- case "dismissed":- return undefined;- }-}--function PageButton({- onClick,- disabled,- children,-}: {- onClick: () => void;- disabled: boolean;- children: React.ReactNode;-}) {- return (- <button- type="button"- onClick={onClick}- disabled={disabled}- className="rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:opacity-40 disabled:hover:border-[var(--color-border-default)] disabled:hover:text-[var(--color-text-secondary)]"- >- {children}- </button>- );-}diff --git a/tests/fixtures/decision_vocabulary.json b/tests/fixtures/decision_vocabulary.jsonnew file mode 100644index 000000000..6e8a88508--- /dev/null+++ b/tests/fixtures/decision_vocabulary.json@@ -0,0 +1,77 @@+{+ "_comment": "Generated from the Python decision vocabulary. Checked by tests/unit/analysis/test_decision_vocabulary_contract.py and by packages/types/__tests__/decisions-vocabulary.test.ts, so a source, status, currency, lane or preset added on one side fails on the other.",+ "sources": [+ "adr",+ "cli",+ "comment",+ "commit",+ "git_archaeology",+ "inline_marker",+ "llm_inferred",+ "pr",+ "session"+ ],+ "retired_sources": [+ "code_comment",+ "readme_mining",+ "changelog"+ ],+ "statuses": [+ "active",+ "proposed",+ "superseded",+ "deprecated",+ "dismissed"+ ],+ "currencies": [+ "active",+ "needs_review",+ "uncheckable",+ "superseded",+ "dismissed"+ ],+ "stored_currencies": [+ "active",+ "needs_review",+ "superseded",+ "dismissed"+ ],+ "candidate_review_states": [+ "open",+ "accepted",+ "merged",+ "needs_split",+ "dismissed"+ ],+ "acceptance_actions": [+ "accepted",+ "reaffirmed",+ "merged",+ "superseded",+ "dismissed",+ "returned_to_review"+ ],+ "capture_sources": [+ "inline_marker",+ "git_archaeology",+ "adr",+ "pr",+ "comment",+ "session",+ "session_discovery"+ ],+ "presets": [+ "default",+ "off",+ "local_only",+ "balanced",+ "full"+ ],+ "review_lanes": [+ "active",+ "candidates",+ "needs_review",+ "uncheckable",+ "history"+ ]+}diff --git a/tests/unit/analysis/test_decision_authority_containment.py b/tests/unit/analysis/test_decision_authority_containment.pyindex b9acd961b..70495833e 100644--- a/tests/unit/analysis/test_decision_authority_containment.py+++ b/tests/unit/analysis/test_decision_authority_containment.py@@ -7,6 +7,7 @@ read that counted proposals as things governing a file.from __future__ import annotations+import jsonfrom pathlib import Pathfrom repowise.core.sessions.miners.decisions import promotion_decisions@@ -52,12 +53,22 @@ class TestRecurrenceIsNotAcceptance:class TestOnlyAcceptedDecisionsGovern:- def _decision(self, status: str, title: str = "d", staleness: float = 0.0) -> dict:- return {"status": status, "title": title, "staleness_score": staleness}+ """Authority is the acceptance join, not the status column.- def test_proposals_alone_govern_nothing(self):+ Every case here passes a currency map instead of a status string, because+ that map is the whole test: a record absent from it has no acceptance row+ and is a candidate regardless of what ``decision_records.status`` says.+ """++ def _decision(self, did: str = "d1", title: str = "d") -> dict:+ return {"id": did, "title": title}++ def test_candidates_alone_govern_nothing(self):result = _compute_alignment(- "src/a.py", [self._decision("proposed"), self._decision("proposed", "d2")], []+ "src/a.py",+ [self._decision("d1"), self._decision("d2", "d2")],+ [],+ {},)assert result["score"] == "none"@@ -66,64 +77,164 @@ class TestOnlyAcceptedDecisionsGovern:# governing_count keeps its old meaning: records naming this file.assert result["governing_count"] == 2- def test_proposals_are_named_as_awaiting_review(self):- result = _compute_alignment("src/a.py", [self._decision("proposed")], [])+ def test_a_record_absent_from_the_currency_map_is_a_candidate(self):+ """Absence from the map is the whole test, whatever the column says.++ The end-to-end half of this, with a record actually stored active+ and carrying no acceptance row, is+ test_decisions_lanes.test_an_active_status_without_an_acceptance_is_a_candidate.+ This function never sees a status, which is the point: it cannot be+ fooled by one.+ """+ result = _compute_alignment("src/a.py", [self._decision()], [], {})++ assert result["score"] == "none"+ assert result["active_count"] == 0+ assert result["candidate_count"] == 1++ def test_candidates_are_named_as_awaiting_review(self):+ result = _compute_alignment("src/a.py", [self._decision()], [], {})assert "awaiting review" in result["explanation"]assert "No accepted decision" in result["explanation"]- def test_accepted_decisions_still_govern(self):- result = _compute_alignment("src/a.py", [self._decision("active")], [])+ def test_accepted_decisions_govern(self):+ result = _compute_alignment(+ "src/a.py", [self._decision()], [], {"d1": "active"}+ )assert result["score"] == "high"assert result["active_count"] == 1assert result["candidate_count"] == 0- def test_proposals_do_not_inflate_the_accepted_count(self):+ def test_a_decision_whose_code_moved_still_governs(self):+ """``needs_review`` binds: it is a decision to re-read, not to ignore."""+ result = _compute_alignment(+ "src/a.py", [self._decision()], [], {"d1": "needs_review"}+ )++ assert result["active_count"] == 1+ assert result["stale_count"] == 1+ assert result["score"] == "low"++ def test_candidates_do_not_inflate_the_accepted_count(self):governing = [- self._decision("active"),- self._decision("proposed", "d2"),- self._decision("proposed", "d3"),+ self._decision("d1"),+ self._decision("d2", "d2"),+ self._decision("d3", "d3"),]- result = _compute_alignment("src/a.py", governing, [])+ result = _compute_alignment("src/a.py", governing, [], {"d1": "active"})assert result["active_count"] == 1assert result["candidate_count"] == 2assert result["governing_count"] == 3- def test_proposals_cannot_rescue_an_all_deprecated_file(self):- governing = [self._decision("deprecated"), self._decision("proposed", "d2")]+ def test_candidates_cannot_rescue_a_withdrawn_file(self):+ governing = [self._decision("d1"), self._decision("d2", "d2")]- result = _compute_alignment("src/a.py", governing, [])+ result = _compute_alignment(+ "src/a.py", governing, [], {"d1": "superseded"}+ )assert result["score"] == "low"- assert "deprecated" in result["explanation"]+ assert result["deprecated_count"] == 1+ assert result["candidate_count"] == 1def test_staleness_is_measured_over_accepted_records_only(self):- governing = [- self._decision("active", "d1", staleness=0.0),- self._decision("proposed", "d2", staleness=1.0),- ]+ governing = [self._decision("d1"), self._decision("d2", "d2")]- result = _compute_alignment("src/a.py", governing, [])+ result = _compute_alignment("src/a.py", governing, [], {"d1": "active"})assert result["stale_count"] == 0assert result["score"] == "high"def test_a_majority_stale_accepted_set_still_scores_low(self):- governing = [- self._decision("active", "d1", staleness=0.9),- self._decision("active", "d2", staleness=0.0),- ]+ governing = [self._decision("d1"), self._decision("d2", "d2")]- result = _compute_alignment("src/a.py", governing, [])+ result = _compute_alignment(+ "src/a.py", governing, [], {"d1": "needs_review", "d2": "active"}+ )assert result["score"] == "low"+ def test_the_four_lane_counts_add_up_to_the_records_naming_the_file(self):+ """No record naming the file may fall out of every count."""+ governing = [self._decision(f"d{i}", f"d{i}") for i in range(4)]++ result = _compute_alignment(+ "src/a.py",+ governing,+ [],+ {"d0": "active", "d1": "superseded", "d2": "uncheckable"},+ )++ assert result["active_count"] == 1+ assert result["deprecated_count"] == 1+ assert result["uncheckable_count"] == 1+ assert result["candidate_count"] == 1+ assert (+ result["active_count"]+ + result["deprecated_count"]+ + result["uncheckable_count"]+ + result["candidate_count"]+ == result["governing_count"]+ )++ def test_an_uncheckable_decision_governs_nothing(self):+ """Accepted, but it names nothing, so nothing can check it."""+ result = _compute_alignment(+ "src/a.py", [self._decision()], [], {"d1": "uncheckable"}+ )++ assert result["score"] == "none"+ assert result["active_count"] == 0+ assert result["uncheckable_count"] == 1+def test_ungoverned_shape_carries_the_candidate_count(self):- result = _compute_alignment("src/a.py", [], [])+ result = _compute_alignment("src/a.py", [], [], {})assert result["candidate_count"] == 0assert result["active_count"] == 0assert result["governing_count"] == 0+++class TestSiblingCoverageCountsAcceptedRecordsOnly:+ """A pattern established only by candidates is not an established pattern."""++ class _Row:+ def __init__(self, did: str, title: str, files: list[str]):+ self.id = did+ self.title = title+ self.affected_files_json = json.dumps(files)++ def test_a_candidate_sibling_is_not_a_pattern(self):+ siblings = [self._Row("s1", "shared rule", ["src/b.py"])]++ result = _compute_alignment(+ "src/a.py",+ [{"id": "d1", "title": "shared rule"}],+ siblings,+ {"d1": "active"},+ )++ # No accepted sibling, so there is nothing to compare against and the+ # score falls back to "governed by one accepted decision".+ assert result["sibling_coverage"] is None+ assert result["score"] == "high"++ def test_an_accepted_sibling_sets_the_denominator(self):+ siblings = [+ self._Row("s1", "shared rule", ["src/b.py"]),+ self._Row("s2", "other rule", ["src/c.py"]),+ ]++ result = _compute_alignment(+ "src/a.py",+ [{"id": "d1", "title": "shared rule"}],+ siblings,+ {"d1": "active", "s1": "active", "s2": "active"},+ )++ assert result["sibling_coverage"] == 0.5+ assert result["score"] == "high"diff --git a/tests/unit/analysis/test_decision_vocabulary_contract.py b/tests/unit/analysis/test_decision_vocabulary_contract.pynew file mode 100644index 000000000..1c5e286d2--- /dev/null+++ b/tests/unit/analysis/test_decision_vocabulary_contract.py@@ -0,0 +1,140 @@+"""The Python half of the decision-vocabulary contract.++``tests/fixtures/decision_vocabulary.json`` is the one list every surface+derives from. This file checks it against the registry it was generated from;+``packages/types/__tests__/decisions-vocabulary.test.ts`` checks the same file+against the TypeScript consts. A source, status, currency or review state added+to one side without the other fails here or there rather than drifting.++The drift is not hypothetical. Before this test the TypeScript union named a+retired ``readme_mining`` and omitted five live sources, the retired set was+hand-mirrored in ``packages/ui`` with a comment saying so, and two of the four+status ladders disagreed about where ``superseded`` sat.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++from repowise.core.analysis.decisions import lifecycle, policy, provenance+from repowise.core.persistence.crud import decisions as crud_decisions++_ROOT = Path(__file__).resolve().parents[3]+_FIXTURE = json.loads(+ (_ROOT / "tests/fixtures/decision_vocabulary.json").read_text(encoding="utf-8")+)+++def test_sources_match_the_listable_registry() -> None:+ assert _FIXTURE["sources"] == list(provenance.LISTABLE_SOURCES)+++def test_retired_sources_match_provenance() -> None:+ assert _FIXTURE["retired_sources"] == list(provenance.RETIRED_SOURCES)+++def test_no_source_is_both_live_and_retired() -> None:+ assert not set(_FIXTURE["sources"]) & set(_FIXTURE["retired_sources"])+++def test_every_source_has_a_confidence_rank() -> None:+ """A source the ranker has never heard of floors to 1 and sorts last."""+ for source in _FIXTURE["sources"] + _FIXTURE["retired_sources"]:+ assert source in provenance.SOURCE_RANK, source+++def test_statuses_match_the_one_ladder() -> None:+ assert _FIXTURE["statuses"] == list(lifecycle.DECISION_STATUS_ORDER)+++def test_status_ladder_covers_every_storable_status() -> None:+ assert set(_FIXTURE["statuses"]) == set(crud_decisions._VALID_DECISION_STATUSES)+++def test_list_ordering_derives_from_the_ladder() -> None:+ """The ORDER BY rank is the ladder minus the status the query excludes."""+ expected = {+ status: rank+ for rank, status in enumerate(_FIXTURE["statuses"])+ if status != "dismissed"+ }+ assert expected == crud_decisions._STATUS_RANK+++def test_currencies_match_lifecycle() -> None:+ assert _FIXTURE["currencies"] == list(lifecycle.DECISION_CURRENCIES)+ assert _FIXTURE["stored_currencies"] == list(lifecycle.STORED_CURRENCIES)+++def test_stored_currencies_are_a_subset_of_the_vocabulary() -> None:+ assert set(_FIXTURE["stored_currencies"]) <= set(_FIXTURE["currencies"])+++def test_review_states_and_actions_match_lifecycle() -> None:+ assert _FIXTURE["candidate_review_states"] == list(lifecycle.CANDIDATE_REVIEW_STATES)+ assert _FIXTURE["acceptance_actions"] == list(lifecycle.ACCEPTANCE_ACTIONS)+++def test_review_lanes_match_lifecycle() -> None:+ assert _FIXTURE["review_lanes"] == list(lifecycle.REVIEW_LANES)+++def test_review_lanes_are_the_currencies_plus_candidates() -> None:+ """The five partition a repository, so they must cover the vocabulary."""+ lanes = set(_FIXTURE["review_lanes"])+ assert lanes == (set(_FIXTURE["currencies"]) | {"candidates"}) - {+ "superseded",+ "dismissed",+ } | {"history"}+++def test_the_acceptance_blocker_sentences_are_stable() -> None:+ """The TypeScript mirror copies these strings; a reword must break it.++ A review surface predicts a refusal with the mirror and reports a real one+ from the API, and the two have to read identically or the same problem gets+ two names.+ """+ blockers = lifecycle.acceptance_blockers(+ lifecycle.AcceptanceRequirement(reason="", scope=[], evidence=[])+ )+ assert blockers == [+ "no rationale or explicit constraint reason",+ "no scope: name the files or modules it governs",+ "no evidence reference",+ "no accepter or tracked-artifact identity",+ ]+++def test_capture_sources_and_presets_match_policy() -> None:+ assert _FIXTURE["capture_sources"] == list(policy.CAPTURE_SOURCE_KEYS)+ assert _FIXTURE["presets"] == list(policy.PRESET_NAMES)+++def test_every_capture_source_is_declared_in_the_registry() -> None:+ declared = {spec.key for spec in policy.SOURCE_SPECS}+ assert set(_FIXTURE["capture_sources"]) <= declared+++def test_typescript_declares_the_same_words() -> None:+ """Guards the TypeScript half for a checkout with no node toolchain.++ The vitest suite is the real assertion; this one keeps a Python-only CI+ lane from passing a fixture the TypeScript side has not adopted.+ """+ ts = (_ROOT / "packages/types/src/decisions.ts").read_text(encoding="utf-8")+ for const, key in (+ ("DECISION_SOURCES", "sources"),+ ("RETIRED_DECISION_SOURCES", "retired_sources"),+ ("DECISION_STATUSES", "statuses"),+ ("DECISION_CURRENCIES", "currencies"),+ ("CANDIDATE_REVIEW_STATES", "candidate_review_states"),+ ("DECISION_LANES", "review_lanes"),+ ("DECISION_PRESETS", "presets"),+ ):+ match = re.search(rf"export const {const} = \[(.*?)\] as const;", ts, re.S)+ assert match is not None, f"{const} is not declared in decisions.ts"+ members = re.findall(r'"([^"]+)"', match.group(1))+ assert members == _FIXTURE[key], constdiff --git a/tests/unit/persistence/test_decision_health_ranking.py b/tests/unit/persistence/test_decision_health_ranking.pyindex ff4c04c0a..76cce4ec9 100644--- a/tests/unit/persistence/test_decision_health_ranking.py+++ b/tests/unit/persistence/test_decision_health_ranking.py@@ -39,20 +39,44 @@ async def _add_decision(confidence: float = 1.0,files: list[str] | None = None,) -> None:- session.add(- DecisionRecord(- id=rec_id,- repository_id=repo_id,- title=title,- decision=f"{title} because reasons",- status=status,- staleness_score=staleness,- confidence=confidence,- affected_files_json=json.dumps(files or []),- source="changelog",- )+ """Add a record, and accept it when the caller asked for a governing one.++ ``status="active"`` alone no longer makes a record govern: the summary+ counts the acceptance, so a fixture that only set the column would seed+ candidates and prove nothing about the lists this file is about.+ """+ record = DecisionRecord(+ id=rec_id,+ repository_id=repo_id,+ title=title,+ decision=f"{title} because reasons",+ status=status,+ staleness_score=staleness,+ confidence=confidence,+ affected_files_json=json.dumps(files or []),+ source="changelog",)+ session.add(record)await session.flush()+ if status == "active":+ from repowise.core.persistence.crud.authority import accept_decision++ # An acceptance has to name what it governs, so a fixture that gave no+ # files gets one. Without it the record accepts as ``uncheckable``,+ # which is not the currency any of these tests is about.+ await accept_decision(+ session,+ record,+ accepter="test",+ evidence=[f"seed:{rec_id}"],+ scope=files or [f"src/{rec_id}.py"],+ )+ # The scope ``accept_decision`` wrote stands: it is what makes the+ # record checkable, and wiping it back to empty would derive+ # ``uncheckable`` instead of the currency each test is about. Staleness+ # is restored because the acceptance does not carry it.+ record.staleness_score = staleness+ await session.flush()async def _add_hotspot(session, repo_id: str, path: str, score: float | None) -> None:diff --git a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.pyindex d801ca379..373d58a9b 100644--- a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py+++ b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py@@ -598,7 +598,10 @@ async def test_why_real_minimum_and_typical_wire_shapes(typical = await wrapped("src/auth/service.py")_assert_wire(typical, "mode", DEFAULT_RESPONSE_CHARS)- assert typical["decisions"]+ # The fixture's records name this path and nobody has accepted them, so+ # the typical response carries a candidate lane and no rules.+ assert typical["decisions"] == []+ assert typical["candidates"]@pytest.mark.asynciodiff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.pyindex a92ef9d62..782195361 100644--- a/tests/unit/server/mcp/test_why.py+++ b/tests/unit/server/mcp/test_why.py@@ -27,8 +27,11 @@ async def test_get_why_file_path(setup_mcp):result = await get_why("src/auth/service.py")assert result["mode"] == "path"assert result["path"] == "src/auth/service.py"- assert len(result["decisions"]) >= 1- assert any(d["title"] == "Use JWT for authentication" for d in result["decisions"])+ # The JWT record has never been accepted, so it is a review request rather+ # than a rule, and it is in the lane that says so.+ assert result["decisions"] == []+ assert any(d["title"] == "Use JWT for authentication" for d in result["candidates"])+ assert "not a rule" in result["candidates_note"]# Origin storyorigin = result["origin_story"]@@ -39,10 +42,13 @@ async def test_get_why_file_path(setup_mcp):assert len(origin["contributors"]) >= 1assert "Alice" in origin["summary"]- # Alignment — dec1 is "proposed", both service.py and middleware.py share it+ # Alignment — dec1 names this file but nobody accepted it, so it counts as+ # a candidate and the file scores as ungoverned.alignment = result["alignment"]- assert alignment["score"] in ("high", "medium", "low", "none")+ assert alignment["score"] == "none"assert alignment["governing_count"] >= 1+ assert alignment["active_count"] == 0+ assert alignment["candidate_count"] >= 1assert "explanation" in alignment@@ -108,10 +114,12 @@ async def test_get_why_file_no_git_metadata(setup_mcp):assert origin["available"] is Falseassert "No git history" in origin["summary"]- # But it still has decisions (dec1 affects middleware.py)- assert len(result["decisions"]) >= 1+ # But it still has a record naming it (dec1 affects middleware.py), in the+ # candidate lane because nobody has accepted it.+ assert len(result["candidates"]) >= 1alignment = result["alignment"]assert alignment["governing_count"] >= 1+ assert alignment["candidate_count"] >= 1@pytest.mark.asyncio@@ -196,7 +204,7 @@ async def test_one_target_and_no_query_answers_about_that_target(setup_mcp):assert result["mode"] == "path"assert result["path"] == "src/auth/service.py"- assert result["decisions"]+ assert result["candidates"]@pytest.mark.asyncio@@ -233,8 +241,8 @@ async def test_get_why_module_path(setup_mcp):result = await get_why("src/db")assert result["mode"] == "path"- assert len(result["decisions"]) >= 1- assert any(d["title"] == "SQLAlchemy as ORM" for d in result["decisions"])+ assert len(result["candidates"]) >= 1+ assert any(d["title"] == "SQLAlchemy as ORM" for d in result["candidates"])@pytest.mark.asyncio@@ -372,27 +380,41 @@ async def test_get_why_semantic_decision_namespace_filtering(session, setup_mcp)async def _seed_bulky_decisions(session, rid: str, path: str, count: int) -> None:- """``count`` records governing *path*, each as heavy as a real one gets."""+ """``count`` records governing *path*, each as heavy as a real one gets.++ Every one is accepted, because these fixtures exist to press the transport+ budget with the lane an agent actually reads. Seeding them as candidates+ would test the budget against a lane the fitter sheds first.+ """import json+ from repowise.core.persistence.crud.authority import accept_decisionfrom repowise.core.persistence.models import DecisionRecord+ records = []for i in range(count):- session.add(- DecisionRecord(- id=f"bulk{i}",- repository_id=rid,- title=f"Bulky decision {i}",- status="superseded" if i else "active",- context="ctx " * 200,- decision="dec " * 200,- rationale="why " * 200,- affected_files_json=json.dumps([path] + [f"src/f{i}/{n}.py" for n in range(60)]),- affected_modules_json=json.dumps([]),- source="pr",- confidence=0.5,- staleness_score=0.0,- )+ record = DecisionRecord(+ id=f"bulk{i}",+ repository_id=rid,+ title=f"Bulky decision {i}",+ status="active",+ context="ctx " * 200,+ decision="dec " * 200,+ rationale="why " * 200,+ affected_files_json=json.dumps([path] + [f"src/f{i}/{n}.py" for n in range(60)]),+ affected_modules_json=json.dumps([]),+ source="pr",+ confidence=0.5,+ staleness_score=0.0,+ )+ session.add(record)+ records.append(record)+ await session.flush()+ for i, record in enumerate(records):+ # Mined from a pull request, so the acceptance has to cite what the+ # accepter went on; only a hand-typed record is its own provenance.+ await accept_decision(+ session, record, accepter="test", evidence=[f"pr#{i}"])await session.flush()@@ -491,14 +513,17 @@ async def test_get_why_path_caps_records_and_keeps_the_active_one_first(result = await get_why("src/auth/service.py")assert len(result["decisions"]) <= _MAX_PATH_DECISIONS- # Ranked, not table-scan order: the one active record leads.+ # Ranked, not table-scan order, and every row is an accepted decision.assert result["decisions"][0]["status"] == "active"+ assert all(d["currency"] == "active" for d in result["decisions"])# And the count that was capped is still reported honestly.- assert result["decisions_total"] == 31+ assert result["decisions_total"] == 30assert result["decisions_emitted"] == _MAX_PATH_DECISIONSassert result["decisions_reduced_reason"] == "construction_cap_and_response_budget"assert result["_meta"]["omitted"]["refs"]+ # The fixture's unaccepted JWT record is counted, and it is not a decision.assert result["alignment"]["governing_count"] == 31+ assert result["alignment"]["candidate_count"] == 1@pytest.mark.asyncio@@ -563,7 +588,7 @@ async def test_get_why_path_leaves_a_small_response_untouched(session, setup_mcpassert "truncated" not in resultassert "decisions_total" not in result- jwt = next(d for d in result["decisions"] if d["title"] == "Use JWT for authentication")+ jwt = next(d for d in result["candidates"] if d["title"] == "Use JWT for authentication")assert jwt["affected_files"] == ["src/auth/service.py", "src/auth/middleware.py"]assert "affected_files_total" not in jwtdiff --git a/tests/unit/server/mcp/test_why_evidence_contract.py b/tests/unit/server/mcp/test_why_evidence_contract.pyindex 291e8f1a7..d595b5809 100644--- a/tests/unit/server/mcp/test_why_evidence_contract.py+++ b/tests/unit/server/mcp/test_why_evidence_contract.py@@ -16,6 +16,21 @@ from repowise.server.mcp_server._why_evidence import ()from repowise.server.mcp_server.tool_why import _rank_keyword_matches++def _row_by_id(result: dict, decision_id: str) -> dict:+ """The row for *decision_id*, from whichever lane the response put it in.++ Path mode splits accepted decisions from candidates, so a record's lane+ depends on whether anybody has accepted it. Its public reference must not:+ that is the contract these tests exist to hold.+ """+ for lane in ("decisions", "candidates"):+ for row in result.get(lane) or []:+ if row["id"] == decision_id:+ return row+ raise AssertionError(f"{decision_id} is in no lane of {sorted(result)}")++_A = "a" * 40_B = "b" * 40_C = "c" * 40@@ -393,8 +408,8 @@ async def test_persisted_evidence_rows_accrete_into_the_public_decision(result = await get_why("why is JWT used for authentication")path_result = await get_why("src/auth/service.py")- decision = next(row for row in result["decisions"] if row["id"] == "dec1")- path_decision = next(row for row in path_result["decisions"] if row["id"] == "dec1")+ decision = _row_by_id(result, "dec1")+ path_decision = _row_by_id(path_result, "dec1")assert {ref["provenance"] for ref in decision["evidence_refs"]} == {"human_decision",@@ -471,7 +486,7 @@ async def test_every_single_repository_query_mode_keeps_the_exact_public_referenawait get_why(targets=["src/auth/service.py"]),]for result in calls:- decision = next(row for row in result["decisions"] if row["id"] == "dec1")+ decision = _row_by_id(result, "dec1")assert decision["source"] == "readme_mining"assert decision["provenance"] == "historical"assert decision["evidence_refs"] == [expected]diff --git a/tests/unit/server/test_decisions_lanes.py b/tests/unit/server/test_decisions_lanes.pynew file mode 100644index 000000000..cb1d20f38--- /dev/null+++ b/tests/unit/server/test_decisions_lanes.py@@ -0,0 +1,619 @@+"""Review lanes over the acceptance join.++The lane a record is in answers "who accepted this and does it still bind",+which the ``status`` column cannot: it is a projection every writer keeps in+step, so it agrees right up until something writes it without an acceptance.+These tests hold the two apart, including on a record stored ``active`` that+nobody ever accepted.+"""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from tests.unit.server.conftest import create_test_repo+++async def _seed(+ session_factory,+ repo_id: str,+ *,+ title: str,+ status: str = "proposed",+ accept: bool = False,+ scope: list[str] | None = None,+ staleness: float = 0.0,+) -> str:+ """One record, accepted or not, independently of its status column."""+ async with get_session(session_factory) as session:+ rec = await crud.upsert_decision(+ session,+ repository_id=repo_id,+ title=title,+ status=status,+ context="ctx",+ decision="dec",+ rationale="why",+ source="inline_marker",+ affected_files=["src/app.py"] if scope is None else scope,+ evidence_file="src/app.py",+ confidence=0.5,+ )+ rec.staleness_score = staleness+ # ``upsert_decision`` refuses to write ``active``: extraction cannot+ # confer authority. A record stored active with no acceptance behind it+ # therefore only arises from a pre-split store, which is exactly the+ # seam under test, so write the column directly to reproduce one.+ if status == "active" and not accept:+ rec.status = "active"+ if accept:+ await crud.accept_decision(+ session, rec, accepter="tester", evidence=["seed"]+ )+ # accept_decision projects the column back to ``active``; restore+ # the staleness the seed asked for, which the projection does not+ # touch and ``effective_currency`` reads.+ rec.staleness_score = staleness+ await session.flush()+ return rec.id+++async def _lane(client: AsyncClient, repo_id: str, lane: str) -> list[dict]:+ res = await client.get(+ f"/api/repos/{repo_id}/decisions", params={"lane": lane, "limit": 500}+ )+ assert res.status_code == 200, res.text+ return res.json()+++async def test_an_active_status_without_an_acceptance_is_a_candidate(+ client: AsyncClient, app+) -> None:+ """The seam, at the wire. The column says active; nobody accepted it."""+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ await _seed(sf, repo["id"], title="Never accepted", status="active")++ candidates = await _lane(client, repo["id"], "candidates")+ governing = await _lane(client, repo["id"], "governing")++ assert [d["title"] for d in candidates] == ["Never accepted"]+ assert candidates[0]["status"] == "active"+ assert candidates[0]["currency"] is None+ assert governing == []+++async def test_an_accepted_record_governs_and_carries_its_currency(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ await _seed(sf, repo["id"], title="A rule", accept=True)++ governing = await _lane(client, repo["id"], "governing")++ assert [d["title"] for d in governing] == ["A rule"]+ assert governing[0]["currency"] == "active"+++async def test_a_decision_whose_files_moved_lands_in_needs_review(+ client: AsyncClient, app+) -> None:+ """It still governs. ``needs_review`` is a decision to re-read, not to drop."""+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ await _seed(sf, repo["id"], title="Drifted", accept=True, staleness=0.9)++ assert [d["title"] for d in await _lane(client, repo["id"], "needs_review")] == [+ "Drifted"+ ]+ assert [d["title"] for d in await _lane(client, repo["id"], "governing")] == [+ "Drifted"+ ]+ assert await _lane(client, repo["id"], "active") == []+++async def test_a_scopeless_acceptance_is_uncheckable_and_does_not_govern(+ client: AsyncClient, app+) -> None:+ """Only reachable through the manifest, which accepts with an artifact.++ The acceptance contract refuses a scopeless acceptance at the API, so this+ seeds one directly to prove the read side classifies it rather than+ reporting it as a rule.+ """+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ did = await _seed(sf, repo["id"], title="Names nothing", accept=True)+ async with get_session(sf) as session:+ rec = await crud.get_decision(session, did)+ rec.affected_files_json = "[]"+ rec.affected_modules_json = "[]"+ await session.flush()++ assert [d["title"] for d in await _lane(client, repo["id"], "uncheckable")] == [+ "Names nothing"+ ]+ assert await _lane(client, repo["id"], "governing") == []+++async def test_withdrawing_authority_moves_a_record_to_history(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ did = await _seed(sf, repo["id"], title="Retired", accept=True)++ res = await client.patch(+ f"/api/repos/{repo['id']}/decisions/{did}", json={"status": "deprecated"}+ )+ assert res.status_code == 200, res.text++ assert [d["title"] for d in await _lane(client, repo["id"], "history")] == [+ "Retired"+ ]+ assert await _lane(client, repo["id"], "governing") == []+++async def test_a_dismissed_decision_stays_in_history(client: AsyncClient, app) -> None:+ """A withdrawn decision is history; a dismissed candidate is a tombstone.++ ``dismiss_candidate`` writes ``status="dismissed"`` for both, and the+ default listing hides that status, so the accepted one used to fall out of+ every lane and every badge while the History copy promised it was kept.+ """+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ did = await _seed(sf, repo["id"], title="Withdrawn rule", accept=True)+ await _seed(sf, repo["id"], title="Rejected guess")+ async with get_session(sf) as session:+ from repowise.core.persistence.crud.authority import dismiss_candidate++ for title in ("Withdrawn rule", "Rejected guess"):+ rec = await crud.find_decision_by_title(+ session,+ repo["id"],+ title,+ source="inline_marker",+ evidence_file="src/app.py",+ )+ await dismiss_candidate(session, rec, accepter="tester")+ await session.flush()++ assert [d["title"] for d in await _lane(client, repo["id"], "history")] == [+ "Withdrawn rule"+ ]+ assert await _lane(client, repo["id"], "candidates") == []+ counts = (+ await client.get(f"/api/repos/{repo['id']}/decisions/lane-counts")+ ).json()+ assert counts["history"] == 1+ assert counts["candidates"] == 0+ assert counts["total"] == 1+ assert did+++async def test_the_governing_lane_pages_over_its_own_rows(+ client: AsyncClient, app+) -> None:+ """It filters accepted rows by currency, so its page is cut after that.++ Cutting first returned an empty tab on a repository whose newest accepted+ records had all been superseded.+ """+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ from repowise.core.persistence.crud.authority import record_acceptance++ for i in range(4):+ did = await _seed(sf, repo["id"], title=f"Retired {i}", accept=True)+ async with get_session(sf) as session:+ rec = await crud.get_decision(session, did)+ await record_acceptance(+ session,+ rec,+ action="superseded",+ currency="superseded",+ accepter="tester",+ evidence=["seed"],+ )+ await session.flush()+ await _seed(sf, repo["id"], title="The only rule", accept=True)++ res = await client.get(+ f"/api/repos/{repo['id']}/decisions",+ params={"lane": "governing", "limit": 2},+ )++ assert res.status_code == 200, res.text+ assert [d["title"] for d in res.json()] == ["The only rule"]+++async def test_lane_counts_partition_the_repository(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ await _seed(sf, repo["id"], title="Rule", accept=True)+ await _seed(sf, repo["id"], title="Drifted", accept=True, staleness=0.9)+ await _seed(sf, repo["id"], title="Candidate one")+ await _seed(sf, repo["id"], title="Candidate two", status="active")++ res = await client.get(f"/api/repos/{repo['id']}/decisions/lane-counts")+ assert res.status_code == 200, res.text+ counts = res.json()++ assert counts["active"] == 1+ assert counts["needs_review"] == 1+ assert counts["uncheckable"] == 0+ assert counts["history"] == 0+ assert counts["candidates"] == 2+ # The five exclusive lanes add up, and governing rolls up the two that bind.+ assert (+ counts["active"]+ + counts["needs_review"]+ + counts["uncheckable"]+ + counts["history"]+ + counts["candidates"]+ == counts["total"]+ )+ assert counts["governing"] == 2+++async def test_lane_counts_and_status_counts_are_different_questions(+ client: AsyncClient, app+) -> None:+ """A record written straight to the column is counted by one and not the other."""+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ await _seed(sf, repo["id"], title="Never accepted", status="active")++ status_counts = (+ await client.get(f"/api/repos/{repo['id']}/decisions/counts")+ ).json()+ lane_counts = (+ await client.get(f"/api/repos/{repo['id']}/decisions/lane-counts")+ ).json()++ assert status_counts["active"] == 1+ assert lane_counts["active"] == 0+ assert lane_counts["candidates"] == 1+++async def test_a_lane_page_is_a_page_of_that_lane(client: AsyncClient, app) -> None:+ """The filter runs before the page is cut, not after it.++ Priority sort leads with accepted records, so a lane filtered after the cut+ returned an empty Candidates page on a store holding hundreds of them. This+ seeds more accepted records than the page holds and asks for the lane+ behind them.+ """+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ for i in range(6):+ await _seed(sf, repo["id"], title=f"Rule {i}", accept=True)+ await _seed(sf, repo["id"], title="The only candidate")++ res = await client.get(+ f"/api/repos/{repo['id']}/decisions",+ params={"lane": "candidates", "limit": 3},+ )++ assert res.status_code == 200, res.text+ assert [d["title"] for d in res.json()] == ["The only candidate"]+++async def test_a_derived_lane_pages_over_its_own_rows(+ client: AsyncClient, app+) -> None:+ """``needs_review`` is derived, so its page is cut after the derivation."""+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ for i in range(4):+ await _seed(sf, repo["id"], title=f"Fresh {i}", accept=True)+ for i in range(3):+ await _seed(+ sf, repo["id"], title=f"Drifted {i}", accept=True, staleness=0.9+ )++ first = await client.get(+ f"/api/repos/{repo['id']}/decisions",+ params={"lane": "needs_review", "limit": 2, "offset": 0},+ )+ second = await client.get(+ f"/api/repos/{repo['id']}/decisions",+ params={"lane": "needs_review", "limit": 2, "offset": 2},+ )++ titles = [d["title"] for d in first.json()] + [+ d["title"] for d in second.json()+ ]+ assert len(first.json()) == 2+ assert len(second.json()) == 1+ assert sorted(titles) == ["Drifted 0", "Drifted 1", "Drifted 2"]+++async def test_an_unknown_lane_is_rejected_rather_than_ignored(+ client: AsyncClient, app+) -> None:+ """A misspelt lane must not return an unfiltered page that reads as the lane."""+ repo = await create_test_repo(client)++ res = await client.get(+ f"/api/repos/{repo['id']}/decisions", params={"lane": "governng"}+ )++ assert res.status_code == 422+++async def test_the_lane_parameter_is_optional(client: AsyncClient, app) -> None:+ """Omitting it lists everything, so an older client keeps working."""+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ await _seed(sf, repo["id"], title="Rule", accept=True)+ await _seed(sf, repo["id"], title="Candidate")++ res = await client.get(f"/api/repos/{repo['id']}/decisions")++ assert res.status_code == 200+ assert len(res.json()) == 2+++# ---------------------------------------------------------------------------+# Creating a record by hand+# ---------------------------------------------------------------------------+++async def test_creating_with_a_scope_records_an_acceptance(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)++ res = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Use JWT",+ "decision": "Issue signed JWTs",+ "affected_files": ["src/auth/service.py"],+ },+ )++ assert res.status_code == 201, res.text+ assert res.json()["status"] == "active"+ assert [d["title"] for d in await _lane(client, repo["id"], "governing")] == [+ "Use JWT"+ ]+++async def test_creating_without_a_scope_lands_a_candidate_rather_than_failing(+ client: AsyncClient, app+) -> None:+ """The form and the acceptance contract have to agree.++ An acceptance names what it governs, so a scopeless entry cannot be one.+ Refusing the write instead would throw away every field the author did+ fill in, and reported the gap in a failure toast after the fact; the+ record is kept as a candidate, which is what ``repowise decision add``+ does with the same input.+ """+ repo = await create_test_repo(client)++ res = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={"title": "Use JWT", "decision": "Issue signed JWTs"},+ )++ assert res.status_code == 201, res.text+ assert res.json()["status"] == "proposed"+ assert [d["title"] for d in await _lane(client, repo["id"], "candidates")] == [+ "Use JWT"+ ]+ assert await _lane(client, repo["id"], "governing") == []+++async def test_a_module_only_scope_is_enough_to_accept(+ client: AsyncClient, app+) -> None:+ """The scope is files *or* modules, the same pair the contract checks."""+ repo = await create_test_repo(client)++ res = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={+ "title": "Keep the resolver pure",+ "decision": "No I/O in resolvers",+ "affected_modules": ["src/resolvers"],+ },+ )++ assert res.status_code == 201, res.text+ assert res.json()["status"] == "active"+++async def test_recording_a_title_again_cannot_withdraw_its_scope(+ client: AsyncClient, app+) -> None:+ """The create endpoint upserts on the title, so it can hit a live decision.++ ``upsert_decision`` overwrites the scope with whatever the body carries. A+ second post of an accepted decision's title with no files therefore cleared+ the files it governed and left its acceptance row pointing at a record that+ no longer binds, from a call that says "create". Refuse instead.+ """+ repo = await create_test_repo(client)+ body = {+ "title": "Use JWT",+ "decision": "Issue signed JWTs",+ "affected_files": ["src/auth/service.py"],+ }+ first = await client.post(f"/api/repos/{repo['id']}/decisions", json=body)+ assert first.status_code == 201, first.text++ again = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={"title": "Use JWT", "decision": "Issue signed JWTs"},+ )++ assert again.status_code == 409+ assert "already an accepted decision" in again.json()["detail"]+ governing = await _lane(client, repo["id"], "governing")+ assert [d["title"] for d in governing] == ["Use JWT"]+ assert governing[0]["affected_files"] == ["src/auth/service.py"]+++async def test_recording_a_title_again_with_a_scope_still_works(+ client: AsyncClient, app+) -> None:+ """Only the withdrawal is refused, not an ordinary re-record."""+ repo = await create_test_repo(client)+ body = {+ "title": "Use JWT",+ "decision": "Issue signed JWTs",+ "affected_files": ["src/auth/service.py"],+ }+ await client.post(f"/api/repos/{repo['id']}/decisions", json=body)++ again = await client.post(+ f"/api/repos/{repo['id']}/decisions",+ json={**body, "affected_files": ["src/auth/service.py", "src/auth/mw.py"]},+ )++ assert again.status_code == 201, again.text+ assert again.json()["affected_files"] == [+ "src/auth/service.py",+ "src/auth/mw.py",+ ]+++async def test_a_scopeless_re_record_of_a_candidate_is_fine(+ client: AsyncClient, app+) -> None:+ """Nothing is withdrawn, because nothing was accepted."""+ repo = await create_test_repo(client)+ body = {"title": "Maybe JWT", "decision": "Consider signed JWTs"}+ await client.post(f"/api/repos/{repo['id']}/decisions", json=body)++ again = await client.post(f"/api/repos/{repo['id']}/decisions", json=body)++ assert again.status_code == 201, again.text+ assert again.json()["status"] == "proposed"+++# ---------------------------------------------------------------------------+# The health rollup+# ---------------------------------------------------------------------------+++async def test_health_counts_the_acceptance_not_the_status_column(+ client: AsyncClient, app+) -> None:+ """The fifth governance reader, and the one a migrated store meets first.++ Between the acceptance tables appearing and the classifier running, the+ status column still says ``active`` for records nobody accepted. Counting+ it made ``repowise decision health`` and ``get_why()`` report a hundred+ governing decisions on a store whose acceptance log was empty, while every+ other surface reported none.+ """+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ await _seed(sf, repo["id"], title="Never accepted", status="active")+ await _seed(sf, repo["id"], title="A real rule", accept=True)++ res = await client.get(f"/api/repos/{repo['id']}/decisions/health")++ assert res.status_code == 200, res.text+ summary = res.json()["summary"]+ assert summary["active"] == 1+ assert summary["proposed"] == 1+ titles = [d["title"] for d in res.json()["proposed_awaiting_review"]]+ assert "Never accepted" in titles+++async def test_a_candidate_does_not_make_a_hotspot_governed(+ client: AsyncClient, app+) -> None:+ """``ungoverned_hotspots`` exists to say where nobody has decided anything.++ A candidate naming a hotspot used to remove it from that list, which is+ the one answer the list must not give.+ """+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ async with get_session(sf) as session:+ from repowise.core.persistence.models import GitMetadata++ session.add(+ GitMetadata(+ repository_id=repo["id"],+ file_path="src/app.py",+ is_hotspot=True,+ temporal_hotspot_score=0.9,+ )+ )+ await session.flush()+ await _seed(sf, repo["id"], title="Names the hotspot", status="active")++ res = await client.get(f"/api/repos/{repo['id']}/decisions/health")++ assert res.status_code == 200, res.text+ assert "src/app.py" in res.json()["ungoverned_hotspots"]++ # Accepting it is what makes the file governed, and only then.+ async with get_session(sf) as session:+ rec = await crud.find_decision_by_title(+ session,+ repo["id"],+ "Names the hotspot",+ source="inline_marker",+ evidence_file="src/app.py",+ )+ await crud.accept_decision(session, rec, accepter="tester", evidence=["x"])+ await session.flush()++ after = await client.get(f"/api/repos/{repo['id']}/decisions/health")+ assert "src/app.py" not in after.json()["ungoverned_hotspots"]+++async def test_health_and_lane_counts_agree(client: AsyncClient, app) -> None:+ """Two rollups, one question. They disagreed before, and loudly."""+ repo = await create_test_repo(client)+ sf = app.state.session_factory+ await _seed(sf, repo["id"], title="Rule", accept=True)+ await _seed(sf, repo["id"], title="Drifted", accept=True, staleness=0.9)+ await _seed(sf, repo["id"], title="Candidate", status="active")++ health = (await client.get(f"/api/repos/{repo['id']}/decisions/health")).json()+ lanes = (+ await client.get(f"/api/repos/{repo['id']}/decisions/lane-counts")+ ).json()++ assert health["summary"]["active"] == lanes["governing"]+ assert health["summary"]["proposed"] == lanes["candidates"]+ assert health["summary"]["stale"] == lanes["needs_review"]+ assert health["summary"]["unscoped"] == lanes["uncheckable"]diff --git a/tests/unit/server/test_mcp_decision_graph.py b/tests/unit/server/test_mcp_decision_graph.pyindex 346966c82..f83f21cd7 100644--- a/tests/unit/server/test_mcp_decision_graph.py+++ b/tests/unit/server/test_mcp_decision_graph.py@@ -315,6 +315,28 @@ async def decision_db(session: AsyncSession, repo_id: str) -> str:await session.flush()+ # Every one of these is accepted. The status column alone no longer makes a+ # record govern: the surfaces under test join the acceptance, so a fixture+ # that only sets the column would exercise the candidate path throughout+ # and prove nothing about governance.+ from repowise.core.persistence.crud.authority import (+ accept_decision,+ record_acceptance,+ )++ for d in decisions:+ await accept_decision(session, d, accepter="test", evidence=[f"seed:{d.id}"])+ superseded = next(d for d in decisions if d.id == "dec_superseded")+ await record_acceptance(+ session,+ superseded,+ action="superseded",+ currency="superseded",+ accepter="test",+ evidence=["seed:dec_superseded"],+ )+ await session.flush()+# DecisionNodeLink rows — the graph truth used by get_governing_decisionslinks = [DecisionNodeLink(