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): acceptance as a recorded event, and a tracked manifest (#2069)
Raghav Chamadiyaec92fe15e5e4
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 7dc9e3cd8..032acdb4f 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -664,7 +664,7 @@ 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 a person accepted it: treat it as a constraint. `proposed` means something was inferred and nobody has confirmed it: read it as a hint and never as a rule. Nothing promotes a record to `active` except an explicit `repowise decision confirm`, so a proposal that has recurred across fifty sessions is still a proposal.+**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.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.diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.mdindex 5ee4215d0..3a3dd797a 100644--- a/docs/layers/DECISIONS.md+++ b/docs/layers/DECISIONS.md@@ -10,13 +10,145 @@ and pushed back at your agent at the moment it is about to violate or honor it.```bashrepowise init # extraction runs as part of indexing-repowise decision list # what has been captured-repowise decision list --proposed # auto-proposed, awaiting your review-repowise decision confirm a1b2c3d4 # promote a proposal to active+repowise decision candidates # what is awaiting review; none of it governs+repowise decision confirm a1b2c3d4 # accept one: this is what makes it govern+repowise decision export # write the accepted ones to a tracked file+repowise decision list # everything, decisions and candidates alikerepowise decision health # stale, conflicting, ungoverned hotspotsrepowise decision add # guided interactive capture```+## Three things, not one++Repowise distinguishes what it observed, what it inferred, and what you agreed+to, because conflating them is how a machine ends up writing your team's rules.++| | What it is | Can a machine create it? | Does it govern? |+|---|---|---|---|+| **Episode** | An evidenced event: a transcript span, a commit, a structural change | Yes | No |+| **Candidate** | A durable choice inferred from that evidence | Yes | No |+| **Decision** | A constraint you accepted | No, except a committed ADR | Yes |++Only the third reaches your agent, scores path alignment, or lands in the+generated `CLAUDE.md`. Recurrence, confidence, a model's verdict and a+successful implementation are all evidence that a candidate is worth reading;+none of them is an acceptance.++**Acceptance is a recorded event**, not a status somebody set. It carries a+reason, a scope, an evidence reference, and who accepted it, and repowise+refuses to store one missing any of those rather than filling in a blank:++```+$ repowise decision confirm 4b6ddc58+Cannot accept 4b6ddc58: no scope: name the files or modules it governs+Supply the missing parts with --reason, --scope or --evidence.++$ repowise decision confirm 4b6ddc58 --scope packages/core/src/repowise/core/ingestion+Decision 4b6ddc58 accepted (governing)+```++The log is append-only. Re-accepting after review, sending a decision back to+review, superseding it and withdrawing it each add a row, so the history of who+granted and withdrew authority survives every later action.++### Upgrading from before the split++Before this, a record reached `active` by appearing in two coding-agent+sessions, with nobody involved. `repowise decision migrate` classifies those:++```+$ repowise decision migrate++Decision migration (dry run)++ Total legacy records 504+ Kept as decisions 0+ Reclassified as candidates 502+ Dismissed tombstones 2+ Already migrated 0++ Why records became candidates:+ 381 never accepted: it was awaiting review+ 121 active by recurrence, not by a person: a session row carries no acceptance event+```++**Expect your standing decisions to shrink**, and on many repositories to+empty. That is the correction, not a regression: those records were never+accepted, and everything is still there under `repowise decision candidates`,+ready to be accepted deliberately. Nothing is deleted, every id keeps+resolving, retirements you performed are preserved, and re-running changes+nothing. `repowise init` and `repowise update` run the same classification, so+a store cannot sit half-migrated with the status column and the acceptance log+disagreeing.++## The tracked manifest++Accepted decisions are the one part of this layer that belongs to the+repository rather than to your machine, so they live in a file you commit:++```bash+repowise decision export # store -> .repowise/decisions.yaml+repowise decision import # .repowise/decisions.yaml -> store+```++```yaml+# Accepted architectural decisions for this repository.+version: 1+decisions:+- id: 228ddce7b28c4f93a8f1e8976dd1ba4c+ title: Avoid feature gating+ decision: Do not add feature gating.+ reason: Feature flags outlived their purpose here+ scope:+ - packages/core+ currency: active+ source: session+ accepted_at: '2026-09-01T13:04:22+00:00'+ accepted_by: Raghav+```++Ordered by id and rendered from a fixed field order, so two machines holding+the same decisions produce the same bytes and a one-line change is a one-line+diff. Written atomically and fsynced; an unchanged render is not rewritten at+all. Comments are not preserved — it is generated, and says so in its own+header.++`export` un-ignores the file in your `.gitignore` if a `.repowise/` rule was+hiding it, leaving everything else under `.repowise/` ignored, including nested+ones elsewhere in the tree.++On import the file wins: it is what a colleague's commit changed and the store+is the copy. A decision the file has and the store does not is created and+accepted with the file itself as the accepter — the only non-human accepter+there is, and only because it is version controlled and reviewable. An entry+that differs is re-accepted from the file. An entry missing a reason or a scope+is skipped rather than guessed at, and an entry the file no longer holds is+left alone: a missing line is as likely a bad merge as a deliberate removal.++Two guards on the write. A store with no acceptances refuses to overwrite a+non-empty committed file, because deleting the index is a documented recovery+step and it must not delete your decisions with it. And a file written by a+newer repowise is refused rather than silently downgraded.++Episodes and candidates stay out of it. They are evidence and inference, they+turn over constantly, and committing them would put a machine's opinions under+review as though they were the team's.++## Review actions++| Command | What it records |+|---------|-----------------|+| `decision confirm ID` | Accept, optionally editing the reason and scope on the way. |+| `decision confirm ID` on a decision | Reaffirm it after review. |+| `decision merge ID INTO_ID` | Fold a candidate into an existing decision. The old id resolves to the target. |+| `decision split ID` | Flag a candidate as bundling two choices. Never splits it for you. |+| `decision dismiss ID` | Tombstone it. On an accepted decision this also withdraws its authority. |+| `decision deprecate ID --superseded-by ID2` | Retire it with an explicit lineage edge. |++Similarity never supersedes anything: an edge exists because somebody named the+successor. Merging and superseding retire ids that may already be written down+somewhere, so both leave an alias and the retired id keeps resolving.+```repowise decision health@@ -51,7 +183,7 @@ history.| Source | Key | Reads | Notes ||--------|-----|-------|-------|-| ADR files | `adr` | `adr/`, `adrs/`, `docs/adr/`, `docs/adrs/`, `docs/decisions/`, `decisions/`, `architecture/`, `doc/adr/` | Nygard and MADR headings plus YAML frontmatter, parsed without an LLM. Up to 60 files. `accepted`/`approved` map to `active`, `draft` to `proposed`, `rejected` to `deprecated`. |+| ADR files | `adr` | `adr/`, `adrs/`, `docs/adr/`, `docs/adrs/`, `docs/decisions/`, `decisions/`, `architecture/`, `doc/adr/` | Nygard and MADR headings plus YAML frontmatter, parsed without an LLM. Up to 60 files. A document that explicitly says `accepted`/`approved`, is committed, and names what it governs accepts its own decision, with the file recorded as the accepter; it is the only non-human acceptance there is. A draft, an uncommitted file, or one with no Status section lands as a candidate. || Inline markers | `inline_marker` | `# WHY:` / `# DECISION:` / `# TRADEOFF:` / `# ADR:` / `# RATIONALE:` / `# REJECTED:` | Any comment syntax (`#`, `//`, `--`, `/*`, `*`). The keyword is case-sensitive and must be capitalised, like `TODO:` and `FIXME:` — otherwise ordinary prose ("# Rejected: nothing to extract.") becomes an architectural decision. Up to 5 continuation lines, plus 20 lines of surrounding context. Fenced code blocks in Markdown are skipped. || Git archaeology | `git_archaeology` | Commit messages | Gated on 19 decision verbs (migrate, switch to, replace, adopt, deprecate, drop, rewrite, split, revert, and the rest). || PR bodies | `pr` | Squash-merge and PR commit bodies | A body only qualifies when it looks like a PR description (`## Why`, `## Motivation`, `## Context`, `Closes #`, `Before:` / `After:`). Up to 25 bodies. |@@ -224,6 +356,20 @@ affected files that have been committed to since the decision was recorded.**`>= 0.5` is stale everywhere: `repowise decision list --stale-only`, the healthsummary, and the staleness column in the CLI table.+The number is a supporting fact; what an accepted decision *is* gets a word:++| Currency | Meaning |+|----------|---------|+| `active` | Accepted, and still describes the code. |+| `needs_review` | Accepted, but the files it names have moved. Still governs — a decision whose code moved is one to re-read, not one to ignore. |+| `uncheckable` | Accepted, but names nothing the repository can be asked about. |+| `superseded` | Replaced by a later decision, through an explicit lineage edge. |+| `dismissed` | Authority withdrawn, kept for history. |++The first three are derived from the code on every read, so a decision moves+between them without anybody touching it. The last two are states a person set,+and the repository does not get to argue with them.+There is deliberately no constant in that definition. An earlier version grewthe score with 90-day commit volume and record age, and added a boost when alater commit *message* contained words like "migrate away"; both were fitted to@@ -249,9 +395,11 @@ cannot be mistaken for a successful one; `dismiss` skips its prompt underthe whole source registry with a `status` and a `reason` per source, which isthe machine-readable answer to "will this source run, and if not why not".-Reading decisions back, the `status` field is what decides whether a record-binds: `active` was accepted by a person, `proposed` was inferred and is a hint.-See [MCP_TOOLS.md](../agent/MCP_TOOLS.md#get_why).+Reading decisions back, `active` means somebody accepted it and it binds;+anything else is a candidate and is a hint. The stored status is a projection+of the acceptance event, not the authority itself — the acceptance is — but the+two are kept in step, so a reader that only has the status column stays correct+rather than merely stale. See [MCP_TOOLS.md](../agent/MCP_TOOLS.md#get_why).## Session-mined decisions@@ -271,12 +419,12 @@ Three stages, in order:2. **One batched LLM structuring call per update**, capped at 60 candidates.Every produced field must quote the transcript verbatim or it is dropped;an ungrounded `source_quote` rejects the candidate.-3. **Promotion to a proposal.** A decision seen in two or more distinct+3. **Promotion to a candidate.** A decision seen in two or more distinctsessions, or one direct user correction, is written with `source: session`- and status `proposed`. Recurrence is evidence that a candidate is worth- reading, not an acceptance event: `repowise decision confirm` is what makes- it govern. Repeated observations accrete evidence rows and raise confidence- without ever changing status.+ as a candidate. Recurrence is evidence that a candidate is worth reading,+ not an acceptance event: `repowise decision confirm` is what makes it+ govern. Repeated observations accrete evidence rows and raise confidence+ without ever creating authority.Everything stays on your machine. Transcripts are read locally, staging lives in`.repowise/sessions/sessions.db`, and only the distilled decision text about the@@ -375,12 +523,17 @@ the primary repo. Decision ids accept an 8-character prefix.| Command | What it does ||---------|--------------|-| `repowise decision add` | Guided interactive capture: title, context, decision, rationale, rejected alternatives, tradeoffs, affected files, tags. Stored `active` at confidence 1.0. |+| `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. |-| `repowise decision confirm ID` | Promote a proposal to `active`. |+| `repowise decision confirm ID` | Accept a candidate. Refuses, naming the gap, when it has no reason, scope or evidence; `--reason`, `--scope` and `--evidence` supply them. || `repowise decision dismiss ID` | Tombstone it. Never re-proposed on reindex. |-| `repowise decision deprecate ID` | Mark deprecated, optionally `--superseded-by <ID>`. |+| `repowise decision deprecate ID` | Retire it, optionally `--superseded-by <ID>`, which writes the lineage edge. |+| `repowise decision candidates` | What is awaiting review, and why each was raised. |+| `repowise decision merge ID INTO_ID` | Fold a candidate into an existing decision. |+| `repowise decision split ID` | Flag a candidate as bundling two choices. |+| `repowise decision export` / `import` | Round-trip accepted decisions through `.repowise/decisions.yaml`. |+| `repowise decision migrate` | Classify pre-split records. Dry run unless `--apply`. || `repowise decision health` | Counts, stale decisions, ungoverned hotspots, proposals awaiting review. || `repowise decision config show` | The resolved capture policy: every source, its status, and why. || `repowise decision config preset NAME` | Apply `off`, `local_only`, `balanced`, or `full`. |diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 69d27ef3b..8bc274c4d 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -911,14 +911,21 @@ Manage architectural decision records.**Subcommands:**```bash-repowise decision list [PATH] # list decisions+repowise decision list [PATH] # list recordsrepowise decision show ID [PATH] # full detailsrepowise decision add [PATH] # interactive add-repowise decision confirm ID [PATH] # confirm a proposal-repowise decision dismiss ID [PATH] # dismiss a proposal (sticky; never re-proposed)-repowise decision deprecate ID [PATH] # mark deprecated+repowise decision candidates [PATH] # what is awaiting review; these govern nothing+repowise decision confirm ID [PATH] # accept a candidate: this is what makes it govern+repowise decision dismiss ID [PATH] # tombstone it (sticky; never re-proposed)+repowise decision merge ID INTO_ID # fold a candidate into an existing decision+repowise decision split ID [PATH] # flag a candidate as bundling two choices+repowise decision deprecate ID [PATH] # retire a decision, optionally naming its successorrepowise decision health [PATH] # health dashboard+repowise decision export [PATH] # write accepted decisions to .repowise/decisions.yaml+repowise decision import [PATH] # reconcile the store to that file+repowise decision migrate [PATH] # classify pre-split rows (dry run unless --apply)+repowise decision config show [PATH] # the resolved capture policyrepowise decision config preset NAME [PATH] # default | off | local_only | balanced | fullrepowise decision config discovery [PATH] # budget for the one broad discovery call@@ -928,6 +935,26 @@ repowise decision source set SRC --llm|--no-llm # switch only its model stagerepowise decision llm --on|--off [PATH] # all decision-extraction model calls```+**Review options:**++| Flag | Description |+|------|-------------|+| `--reason TEXT` | On `confirm`: the rationale, or why a constraint needs none. Also corrects the record. |+| `--scope PATH` | On `confirm`: a file or module this governs. Repeatable, and replaces the proposed scope. |+| `--evidence REF` | On `confirm`: a commit, file or link it rests on. Repeatable. |+| `--as NAME` | On `confirm`: record a different accepter than the repo's git identity. |+| `--superseded-by ID` | On `deprecate`: writes an explicit lineage edge and keeps the retired id resolving. |+| `--state STATE` | On `candidates`: `open` (default), `accepted`, `merged`, `needs_split`, `dismissed`, `all`. |+| `--lane NAME` | On `candidates`: only candidates raised by that extraction lane. |+| `--apply` | On `migrate`: write the plan. Without it the command reports and writes nothing. |+| `--dry-run` | On `import`: report and write nothing. |++`confirm` refuses rather than storing a blank acceptance: a candidate needs a+reason, a scope and an evidence reference, and the flags above supply whatever+is missing. Under `--format json` the refusal is a document+(`{"error": "acceptance_refused", "blockers": [...]}`) and the exit code is 1,+so a scripted review can tell it apart from a crash.+**Capture-control options:**| Flag | Description |diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex 91d11b678..d09616ac1 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -466,13 +466,23 @@ The legacy `decisions.session_mining: true|false` key is still honoured andresolves to the `session` source. The first write through the CLI or the APIreplaces it with `sources.session`.+### `.repowise/decisions.yaml`++Everything else under `.repowise/` is a local index you can delete and rebuild.+This one file is not: it holds the decisions you accepted, and it is meant to be+committed. `repowise decision export` writes it and un-ignores it in your+`.gitignore` if a `.repowise/` rule was hiding it; `repowise decision import`+reconciles the store to it, with the file as the authority. Its format carries+its own `version`, and a file written by a newer repowise is refused rather than+downgraded. See [DECISIONS.md](../layers/DECISIONS.md) for the round trip.+`session` mining lets `repowise update` read coding-agent session transcripts(Claude Code's `~/.claude/projects/`) for durable decisions: user corrections,explicit choices with a stated reason, and failed approaches replaced by workingones. Candidates pass deterministic gates first, then one batched LLMstructuring call per update, and every produced field must quote the transcript-verbatim or it is dropped. **Mined decisions are stored as `proposed`**, however-many sessions they recur across; confirming one with `repowise decision confirm`+verbatim or it is dropped. **Mined decisions are stored as candidates**, however+many sessions they recur across; accepting one with `repowise decision confirm`is what makes it govern. Everything stays local: transcripts are read from yourmachine, staging lives in `.repowise/sessions/sessions.db`, and only thedistilled decision text about the codebase is stored.diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.pyindex a03822154..c6ee28d27 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py@@ -290,12 +290,39 @@ def _expand_one_hop(conn: sqlite3.Connection, seeds: list[str]) -> set[str]:# ---------------------------------------------------------------------------+#: Governance is acceptance, not a status string. Spelled out here rather than+#: imported because this path opens the store with stdlib sqlite3 and never+#: imports ``repowise.core``; it mirrors ``crud.authority.ACCEPTED_SQL_PREDICATE``.+_ACCEPTED = "EXISTS (SELECT 1 FROM decision_acceptances a WHERE a.decision_id = {ref}.id)"++#: What to add to a governance query on a store that predates the entity split.+#: Nothing, deliberately. This path opens the store read-only and never runs the+#: schema reconciler, so it cannot create the table and cannot wait for one: an+#: acceptance filter there would silently strip every standing decision from the+#: agent, with no error and no way for this process to fix it. The status column+#: is what such a store has, and it is what the split's own migration reads.+_UNMIGRATED = "1 = 1"+++def _accepted_clause(conn: sqlite3.Connection, ref: str) -> str:+ """The acceptance filter for *ref*, or a no-op on a pre-split store."""+ try:+ found = conn.execute(+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",+ ("decision_acceptances",),+ ).fetchone()+ except sqlite3.Error:+ return _UNMIGRATED+ return _ACCEPTED.format(ref=ref) if found else _UNMIGRATED++def _load_active_decisions(conn: sqlite3.Connection) -> list[dict]:- """Active decisions with their node links, as plain dicts."""+ """Accepted, current decisions with their node links, as plain dicts."""try:rows = conn.execute("SELECT id, title, decision, rationale, confidence, staleness_score, source "- "FROM decision_records WHERE status = 'active'"+ "FROM decision_records WHERE status = 'active' AND "+ + _accepted_clause(conn, "decision_records")).fetchall()except sqlite3.Error:return []@@ -459,7 +486,8 @@ def _governing_decisions(conn: sqlite3.Connection, rel: str) -> list[dict]:for row in conn.execute("SELECT d.id, d.title, d.decision, d.rationale ""FROM decision_node_links l JOIN decision_records d ON d.id = l.decision_id "- "WHERE l.node_id IN (?, ?) AND l.link_type = 'file' AND d.status = 'active'",+ "WHERE l.node_id IN (?, ?) AND l.link_type = 'file' AND d.status = 'active' "+ "AND " + _accepted_clause(conn, "d"),(rel, native),):if row[0] not in seen:@@ -469,7 +497,8 @@ def _governing_decisions(conn: sqlite3.Connection, rel: str) -> list[dict]:for row in conn.execute("SELECT d.id, d.title, d.decision, d.rationale, l.node_id ""FROM decision_node_links l JOIN decision_records d ON d.id = l.decision_id "- "WHERE l.link_type = 'module' AND d.status = 'active'"+ "WHERE l.link_type = 'module' AND d.status = 'active' "+ "AND " + _accepted_clause(conn, "d")):if (row[0] not in seendiff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.pyindex 63eba9f4f..4e99b2e71 100644--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py@@ -16,7 +16,7 @@ from repowise.cli.helpers import (resolve_command_target,run_async,)-from repowise.cli.output import emit_json, format_option, notice_console+from repowise.cli.output import emit_json, emit_refusal, format_option, notice_consolefrom repowise.core.analysis.decisions.provenance import LISTABLE_SOURCESfrom repowise.core.precedent.currency import describe_decision_currency@@ -66,6 +66,25 @@ def _register_config_commands() -> None:decision_group.add_command(source_group)decision_group.add_command(llm_command)+ from repowise.cli.commands.decision_review_cmd import (+ candidates_command,+ export_command,+ import_command,+ merge_command,+ migrate_command,+ split_command,+ )++ for command in (+ migrate_command,+ candidates_command,+ merge_command,+ split_command,+ export_command,+ import_command,+ ):+ decision_group.add_command(command)+_register_config_commands()@@ -92,7 +111,25 @@ async def _resolve_decision_id(session, decision_id: str) -> str | None:raise click.ClickException(f"Decision id prefix {decision_id!r} is ambiguous; use more characters.")- return ids[0] if ids else None+ if ids:+ return ids[0]++ # Merging and superseding retire ids that are already written down+ # somewhere. Resolving through the alias keeps those working instead of+ # reporting the decision as gone.+ from repowise.core.persistence.models import DecisionAlias++ alias = await session.execute(+ select(DecisionAlias.decision_id)+ .where(DecisionAlias.alias_id.like(f"{escape_like(decision_id)}%", escape=LIKE_ESCAPE))+ .limit(2)+ )+ alias_ids = [row[0] for row in alias.all()]+ if len(alias_ids) > 1:+ raise click.ClickException(+ f"Decision id prefix {decision_id!r} is ambiguous; use more characters."+ )+ return alias_ids[0] if alias_ids else None# ---------------------------------------------------------------------------@@ -186,7 +223,8 @@ def decision_add(consequences_list = [c.strip() for c in consequences_raw.split(",") if c.strip()]affected_raw = click.prompt(- "Affected files/modules (comma-separated, optional)", default=""+ "Affected files/modules (comma-separated; required to make it govern)",+ default="",)affected_files = [f.strip() for f in affected_raw.split(",") if f.strip()]@@ -230,11 +268,39 @@ def decision_add(confidence=1.0,)decision_id = rec.id+ # A decision that names nothing cannot be checked against the code+ # and cannot reach the agent editing a governed file, so it cannot+ # be accepted. Keeping it as a candidate is better than discarding+ # eight answered questions; ``confirm --scope`` finishes the job.+ if status == "active" and affected_files:+ # Answering the prompts is the acceptance; recording it as one+ # is what makes this record indistinguishable from any other+ # accepted decision to every reader.+ from repowise.core.analysis.decisions.accepter import resolve_accepter+ from repowise.core.persistence.crud.authority import (+ AcceptanceRefusedError,+ accept_decision,+ )- await engine.dispose()- return decision_id+ try:+ await accept_decision(+ session, rec, accepter=resolve_accepter(repo_path)+ )+ except AcceptanceRefusedError as exc:+ raise click.ClickException(+ f"Cannot accept this decision: {exc}."+ ) from exc- decision_id = run_async(_persist())+ await engine.dispose()+ return decision_id, rec.status++ decision_id, stored_status = run_async(_persist())+ if stored_status != "active" and not non_interactive:+ console.print(+ "[yellow]Stored as a candidate: it names no files, so it cannot be "+ "checked against the code.[/yellow]\n"+ f"[dim]repowise decision confirm {decision_id[:8]} --scope <path>[/dim]"+ )if fmt == "json":# The full id, not the table's 8-char prefix — a caller that parses@@ -537,37 +603,86 @@ def _emit_lifecycle(rec, decision_id: str, action: str, fmt: str, note: str = ""@decision_group.command("confirm")@click.argument("decision_id")@click.argument("path", required=False, default=None)[email protected]("--reason", default="", help="Rationale, or why the constraint needs none.")+ "--scope",+ multiple=True,+ help="File or module this governs. Repeatable; replaces the proposed scope.",+)+ "--evidence",+ multiple=True,+ help="Commit, file or link the decision rests on. Repeatable.",+)[email protected]("--as", "accepter", default="", help="Record a different accepter identity.")@format_option()-def decision_confirm(decision_id: str, path: str | None, fmt: str) -> None:- """Confirm a proposed decision (set status to active).+def decision_confirm(+ decision_id: str,+ path: str | None,+ reason: str,+ scope: tuple[str, ...],+ evidence: tuple[str, ...],+ accepter: str,+ fmt: str,+) -> None:+ """Accept a candidate, making it a decision that governs.- This is the acceptance event. Nothing else promotes a record to ``active``:- extraction, recurrence and confidence all stop at ``proposed``.+ This is the acceptance event, and it is the only thing that produces one:+ extraction, recurrence and confidence all stop at a candidate. Acceptance+ is refused rather than stored blank when the candidate carries no reason,+ no scope or no evidence; ``--reason``, ``--scope`` and ``--evidence``+ supply what is missing, and correcting them here corrects the record too."""repo_path = _resolve_decision_repo(path, fmt)async def _update():+ from repowise.core.analysis.decisions.accepter import resolve_accepterfrom repowise.core.persistence import (create_engine,create_session_factory,get_session,init_db,- update_decision_status,)+ from repowise.core.persistence.crud.authority import (+ AcceptanceRefusedError,+ accept_decision,+ )+ from repowise.core.persistence.models import DecisionRecordurl = get_db_url_for_repo(repo_path)engine = create_engine(url)await init_db(engine)sf = create_session_factory(engine)- async with get_session(sf) as session:- full_id = await _resolve_decision_id(session, decision_id)- rec = await update_decision_status(session, full_id, "active") if full_id else None-- await engine.dispose()- return rec-- _emit_lifecycle(run_async(_update()), decision_id, "confirmed", fmt, "(active)")+ try:+ async with get_session(sf) as session:+ full_id = await _resolve_decision_id(session, decision_id)+ rec = await session.get(DecisionRecord, full_id) if full_id else None+ if rec is None:+ return None+ try:+ await accept_decision(+ session,+ rec,+ accepter=resolve_accepter(repo_path, override=accepter),+ reason=reason,+ scope=list(scope) or None,+ evidence=list(evidence) or None,+ )+ except AcceptanceRefusedError as exc:+ emit_refusal(+ "acceptance_refused",+ f"Cannot accept {rec.id[:8]}: {exc}",+ fmt,+ decision_id=rec.id,+ blockers=list(exc.blockers),+ remedy="Supply the missing parts with --reason, --scope or --evidence.",+ )+ return rec+ finally:+ await engine.dispose()++ _emit_lifecycle(run_async(_update()), decision_id, "accepted", fmt, "(governing)")# ---------------------------------------------------------------------------@@ -596,20 +711,28 @@ def decision_dismiss(decision_id: str, path: str | None, yes: bool, fmt: str) ->create_session_factory,get_session,init_db,- update_decision_status,)+ from repowise.core.persistence.crud.authority import dismiss_candidate+ from repowise.core.persistence.models import DecisionRecordurl = get_db_url_for_repo(repo_path)engine = create_engine(url)await init_db(engine)sf = create_session_factory(engine)- async with get_session(sf) as session:- full_id = await _resolve_decision_id(session, decision_id)- rec = await update_decision_status(session, full_id, "dismissed") if full_id else None+ try:+ async with get_session(sf) as session:+ full_id = await _resolve_decision_id(session, decision_id)+ rec = await session.get(DecisionRecord, full_id) if full_id else None+ if rec is not None:+ from repowise.core.analysis.decisions.accepter import resolve_accepter- await engine.dispose()- return rec+ await dismiss_candidate(+ session, rec, accepter=resolve_accepter(repo_path)+ )+ return rec+ finally:+ await engine.dispose()_emit_lifecycle(run_async(_dismiss()),@@ -633,10 +756,16 @@ def decision_dismiss(decision_id: str, path: str | None, yes: bool, fmt: str) ->def decision_deprecate(decision_id: str, path: str | None, superseded_by: str | None, fmt: str) -> None:- """Deprecate an active decision."""+ """Retire a decision, optionally naming the one that replaces it.++ With ``--superseded-by`` this writes an explicit lineage edge and keeps the+ retired id resolving to its successor. Similarity never does either: an edge+ exists because somebody named the successor.+ """repo_path = _resolve_decision_repo(path, fmt)async def _update():+ from repowise.core.analysis.decisions.accepter import resolve_accepterfrom repowise.core.persistence import (create_engine,create_session_factory,@@ -644,24 +773,55 @@ def decision_deprecate(init_db,update_decision_status,)+ from repowise.core.persistence.crud.authority import (+ AcceptanceRefusedError,+ is_accepted,+ supersede_decision,+ )+ from repowise.core.persistence.models import DecisionRecordurl = get_db_url_for_repo(repo_path)engine = create_engine(url)await init_db(engine)sf = create_session_factory(engine)- async with get_session(sf) as session:- full_id = await _resolve_decision_id(session, decision_id)- rec = (- await update_decision_status(- session, full_id, "deprecated", superseded_by=superseded_by+ try:+ async with get_session(sf) as session:+ full_id = await _resolve_decision_id(session, decision_id)+ rec = await session.get(DecisionRecord, full_id) if full_id else None+ if rec is None:+ return None+ successor = (+ await _resolve_decision_id(session, superseded_by)+ if superseded_by+ else None)- if full_id- else None- )-- await engine.dispose()- return rec+ if superseded_by and successor is None:+ emit_refusal(+ "decision_not_found",+ f"Unknown successor: {superseded_by}",+ fmt,+ decision_id=superseded_by,+ )+ if successor and await is_accepted(session, rec.id):+ try:+ await supersede_decision(+ session,+ rec,+ successor_id=successor,+ accepter=resolve_accepter(repo_path),+ )+ except (AcceptanceRefusedError, ValueError) as exc:+ emit_refusal("supersede_refused", str(exc), fmt, decision_id=rec.id)+ else:+ # A candidate has no authority to retire, so this stays the+ # plain status change it always was.+ await update_decision_status(+ session, rec.id, "deprecated", superseded_by=successor+ )+ return rec+ finally:+ await engine.dispose()_emit_lifecycle(run_async(_update()), decision_id, "deprecated", fmt)diff --git a/packages/cli/src/repowise/cli/commands/decision_review_cmd.py b/packages/cli/src/repowise/cli/commands/decision_review_cmd.pynew file mode 100644index 000000000..409ab93f4--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/decision_review_cmd.py@@ -0,0 +1,381 @@+"""``repowise decision`` subcommands for review, the manifest, and migration.++Attached to the same group as the lifecycle commands. Separate module because+those own one record at a time, while these own the corpus: what is waiting for+review, what the tracked file says, and how legacy rows were classified.+"""++from __future__ import annotations++import click+from rich.table import Table++from repowise.cli.helpers import console, get_db_url_for_repo, run_async+from repowise.cli.output import emit_json, emit_refusal, format_option++__all__ = [+ "candidates_command",+ "export_command",+ "import_command",+ "merge_command",+ "migrate_command",+ "split_command",+]+++async def _open(repo_path):+ """Open the store for one repository, returning engine and session factory."""+ from repowise.core.persistence import create_engine, create_session_factory, init_db++ engine = create_engine(get_db_url_for_repo(repo_path))+ try:+ await init_db(engine)+ except BaseException:+ # Otherwise a failed schema reconcile strands the engine's pool outside+ # the caller's try/finally, and the process hangs on exit.+ await engine.dispose()+ raise+ return engine, create_session_factory(engine)+++async def _repository_id(session, repo_path) -> str:+ """The repository row for *repo_path*, resolved the way every other+ ``decision`` subcommand resolves it, so a store that answers ``list``+ answers these too."""+ from repowise.core.persistence import upsert_repository++ repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))+ return repo.id+++# ---------------------------------------------------------------------------+# decision migrate+# ---------------------------------------------------------------------------++[email protected]("migrate")[email protected]("path", required=False, default=None)[email protected]("--apply", "apply_", is_flag=True, default=False, help="Write the plan.")[email protected]("--limit", default=10, show_default=True, help="Reasons to list in the report.")+@format_option()+def migrate_command(path: str | None, apply_: bool, limit: int, fmt: str) -> None:+ """Classify legacy decision rows as candidates or accepted decisions.++ Dry run by default. Records promoted by recurrence rather than by a person+ become candidates, which is a visible loss of standing decisions and the+ intended one: they were never accepted. Nothing is deleted, every id keeps+ resolving, and re-running changes nothing.+ """+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo++ repo_path = _resolve_decision_repo(path, fmt)++ async def _run():+ from repowise.core.persistence import get_session+ from repowise.core.persistence.decision_migration import (+ apply_migration,+ plan_migration,+ render_plan,+ )++ engine, sf = await _open(repo_path)+ try:+ async with get_session(sf) as session:+ repo_id = await _repository_id(session, repo_path)+ plan = await plan_migration(session, repo_id)+ if apply_:+ plan = await apply_migration(session, repo_id, plan=plan)+ return plan, render_plan(plan, limit=limit)+ finally:+ await engine.dispose()++ plan, report = run_async(_run())+ if fmt == "json":+ payload = plan.as_dict()+ payload["applied"] = apply_+ emit_json(payload)+ return+ console.print(report.replace("(dry run)", "(applied)" if apply_ else "(dry run)"))+ if not apply_:+ console.print("\n[dim]Nothing was written. Re-run with --apply.[/dim]")+++# ---------------------------------------------------------------------------+# decision candidates+# ---------------------------------------------------------------------------++[email protected]("candidates")[email protected]("path", required=False, default=None)+ "--state",+ type=click.Choice(["open", "accepted", "merged", "needs_split", "dismissed", "all"]),+ default="open",+ show_default=True,+)[email protected]("--lane", default=None, help="Only candidates raised by this lane.")[email protected]("--limit", default=30, show_default=True)+@format_option()+def candidates_command(+ path: str | None, state: str, lane: str | None, limit: int, fmt: str+) -> None:+ """List records awaiting review. These do not govern anything."""+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo++ repo_path = _resolve_decision_repo(path, fmt)++ async def _run():+ from repowise.core.persistence import get_session+ from repowise.core.persistence.crud.authority import list_candidates++ engine, sf = await _open(repo_path)+ try:+ async with get_session(sf) as session:+ repo_id = await _repository_id(session, repo_path)+ rows = await list_candidates(+ session,+ repo_id,+ review_state=None if state == "all" else state,+ lane=lane,+ limit=limit,+ )+ return [+ {+ "id": rec.id,+ "title": rec.title,+ "source": rec.source,+ "confidence": round(rec.confidence, 3),+ "review_state": meta.review_state if meta else "open",+ "needs_split": bool(meta.needs_split) if meta else False,+ "lane": meta.lane if meta else "",+ }+ for rec, meta in rows+ ]+ finally:+ await engine.dispose()++ rows = run_async(_run())+ if fmt == "json":+ emit_json({"candidates": rows, "count": len(rows)})+ return+ if not rows:+ console.print("[dim]No candidates in this state.[/dim]")+ return+ table = Table(title=f"Candidates ({state})")+ for column in ("ID", "Title", "Source", "Conf", "State"):+ table.add_column(column)+ for row in rows:+ title = row["title"] + (" [yellow](split?)[/yellow]" if row["needs_split"] else "")+ table.add_row(+ row["id"][:8],+ title,+ row["source"],+ f"{row['confidence']:.2f}",+ row["review_state"],+ )+ console.print(table)+ console.print(+ "[dim]Candidates are review material, not guidance. "+ "`repowise decision confirm ID` is what makes one govern.[/dim]"+ )+++# ---------------------------------------------------------------------------+# decision merge / split+# ---------------------------------------------------------------------------++[email protected]("merge")[email protected]("decision_id")[email protected]("into_id")[email protected]("path", required=False, default=None)+@format_option()+def merge_command(decision_id: str, into_id: str, path: str | None, fmt: str) -> None:+ """Fold a candidate into an existing decision instead of accepting a duplicate."""+ from repowise.cli.commands.decision_cmd import _resolve_decision_id, _resolve_decision_repo++ repo_path = _resolve_decision_repo(path, fmt)++ async def _run():+ from repowise.core.analysis.decisions.accepter import resolve_accepter+ from repowise.core.persistence import get_session+ from repowise.core.persistence.crud.authority import merge_candidate+ from repowise.core.persistence.models import DecisionRecord++ engine, sf = await _open(repo_path)+ try:+ async with get_session(sf) as session:+ src = await _resolve_decision_id(session, decision_id)+ dst = await _resolve_decision_id(session, into_id)+ if src is None:+ emit_refusal("decision_not_found", f"Decision not found: {decision_id}", fmt)+ if dst is None:+ emit_refusal("decision_not_found", f"Decision not found: {into_id}", fmt)+ rec = await session.get(DecisionRecord, src)+ try:+ await merge_candidate(+ session, rec, into_id=dst, accepter=resolve_accepter(repo_path)+ )+ except ValueError as exc:+ emit_refusal("merge_refused", str(exc), fmt, decision_id=src)+ return {"id": src, "merged_into": dst}+ finally:+ await engine.dispose()++ result = run_async(_run())+ if fmt == "json":+ emit_json(result)+ return+ console.print(+ f"[green]Candidate {result['id'][:8]} merged into "+ f"{result['merged_into'][:8]}[/green] [dim](the old id still resolves)[/dim]"+ )++[email protected]("split")[email protected]("decision_id")[email protected]("path", required=False, default=None)[email protected]("--reason", default="", help="What the two choices are.")+@format_option()+def split_command(decision_id: str, path: str | None, reason: str, fmt: str) -> None:+ """Flag a candidate as bundling two choices. Never splits it for you."""+ from repowise.cli.commands.decision_cmd import _resolve_decision_id, _resolve_decision_repo++ repo_path = _resolve_decision_repo(path, fmt)++ async def _run():+ from repowise.core.persistence import get_session+ from repowise.core.persistence.crud.authority import request_split+ from repowise.core.persistence.models import DecisionRecord++ engine, sf = await _open(repo_path)+ try:+ async with get_session(sf) as session:+ full_id = await _resolve_decision_id(session, decision_id)+ if full_id is None:+ emit_refusal("decision_not_found", f"Decision not found: {decision_id}", fmt)+ rec = await session.get(DecisionRecord, full_id)+ await request_split(session, rec, reason=reason)+ return {"id": full_id, "review_state": "needs_split"}+ finally:+ await engine.dispose()++ result = run_async(_run())+ if fmt == "json":+ emit_json(result)+ return+ console.print(f"[yellow]Candidate {result['id'][:8]} flagged for splitting[/yellow]")+++# ---------------------------------------------------------------------------+# decision export / import+# ---------------------------------------------------------------------------++[email protected]("export")[email protected]("path", required=False, default=None)+ "--force",+ is_flag=True,+ default=False,+ help="Overwrite a committed manifest from a store that has accepted nothing.",+)+@format_option()+def export_command(path: str | None, force: bool, fmt: str) -> None:+ """Write accepted decisions to the tracked ``.repowise/decisions.yaml``.++ Refuses to write an empty file over a committed non-empty one: deleting the+ index is a documented recovery step, and it must not delete the decisions+ along with the cache. Import them first, or pass ``--force``.+ """+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo++ repo_path = _resolve_decision_repo(path, fmt)++ async def _run():+ from repowise.core.analysis.decisions.manifest import ManifestConflictError+ from repowise.core.persistence import get_session+ from repowise.core.persistence.decision_manifest import export_manifest++ engine, sf = await _open(repo_path)+ try:+ async with get_session(sf) as session:+ repo_id = await _repository_id(session, repo_path)+ try:+ count, changed = await export_manifest(+ session, repo_id, repo_path, allow_empty=force+ )+ except ManifestConflictError as exc:+ emit_refusal(+ "manifest_conflict",+ str(exc),+ fmt,+ remedy="Run `repowise decision import` first, or pass --force.",+ )+ return {"exported": count, "changed": changed}+ finally:+ await engine.dispose()++ result = run_async(_run())+ from repowise.core.repo_config import ensure_manifest_tracked++ tracked = ensure_manifest_tracked(repo_path) if result["exported"] else False+ result["gitignore_updated"] = tracked+ if fmt == "json":+ emit_json(result)+ return+ where = ".repowise/decisions.yaml"+ if not result["changed"]:+ console.print(f"[dim]{where} already matches the store ({result['exported']}).[/dim]")+ else:+ console.print(f"[green]Wrote {result['exported']} decision(s) to {where}[/green]")+ if tracked:+ console.print("[dim]Un-ignored it in .gitignore so it can be committed.[/dim]")++[email protected]("import")[email protected]("path", required=False, default=None)[email protected]("--dry-run", is_flag=True, default=False, help="Report without writing.")+@format_option()+def import_command(path: str | None, dry_run: bool, fmt: str) -> None:+ """Reconcile the store to ``.repowise/decisions.yaml``.++ The file wins: it is what a colleague's commit changes, and the store is the+ copy. Entries missing a reason or a scope are skipped rather than guessed at.+ """+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo++ repo_path = _resolve_decision_repo(path, fmt)++ async def _run():+ from repowise.core.analysis.decisions.manifest import ManifestConflictError+ from repowise.core.persistence import get_session+ from repowise.core.persistence.decision_manifest import import_manifest++ engine, sf = await _open(repo_path)+ try:+ async with get_session(sf) as session:+ repo_id = await _repository_id(session, repo_path)+ try:+ outcome = await import_manifest(+ session, repo_id, repo_path, dry_run=dry_run+ )+ except ManifestConflictError as exc:+ emit_refusal("manifest_unreadable", str(exc), fmt)+ return outcome.as_dict()+ finally:+ await engine.dispose()++ result = run_async(_run())+ if fmt == "json":+ result["dry_run"] = dry_run+ emit_json(result)+ return+ console.print(+ f"created {len(result['created'])} accepted {len(result['accepted'])} "+ f"unchanged {len(result['unchanged'])} skipped {len(result['skipped'])}"+ )+ for skipped in result["skipped"]:+ console.print(f" [yellow]skipped[/yellow] {skipped['id'][:8]}: {skipped['reason']}")+ if dry_run:+ console.print("[dim]Nothing was written.[/dim]")diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex aa7dcb905..4d6437929 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -811,6 +811,12 @@ async def _persist_full_update_async(await purge_proposed_decisions_by_source(session, repo_id, _retired)await reconcile_source_ranks(session)+ # Same repair on the path a ``repowise update`` user takes: the+ # entity split is only coherent once legacy rows are classified.+ from repowise.core.persistence.decision_migration import apply_migration++ await apply_migration(session, repo_id)+decision_dicts: list[dict] = []if new_decision_markers:import dataclasses as _dcdiff --git a/packages/cli/src/repowise/cli/output.py b/packages/cli/src/repowise/cli/output.pyindex 07bd9d817..3d0e628c7 100644--- a/packages/cli/src/repowise/cli/output.py+++ b/packages/cli/src/repowise/cli/output.py@@ -222,3 +222,24 @@ __all__ = ["resolve_console_width","resolve_format",]+++def emit_refusal(code: str, message: str, fmt: str, **extra: Any) -> None:+ """Report a refused operation and exit non-zero.++ A ``--format json`` caller is owed a document on every exit, including this+ one: raising a ``ClickException`` prints prose on the channel the caller is+ parsing, and the difference between a refusal and a crash disappears.+ """+ import click++ if fmt == "json":+ emit_json({"error": code, "message": message, **extra})+ else:+ from rich.markup import escape++ notices = notice_console(fmt)+ notices.print(f"[red]{escape(message)}[/red]")+ if extra.get("remedy"):+ notices.print(f"[dim]{escape(str(extra['remedy']))}[/dim]")+ raise click.exceptions.Exit(1)diff --git a/packages/core/alembic/versions/0063_decision_entity_split.py b/packages/core/alembic/versions/0063_decision_entity_split.pynew file mode 100644index 000000000..c67f9161d--- /dev/null+++ b/packages/core/alembic/versions/0063_decision_entity_split.py@@ -0,0 +1,156 @@+"""Separate decision candidates from accepted decisions.++Before this, a record reached ``active`` by being seen in two coding-agent+sessions, and an agent read it as a standing instruction. Recurrence is evidence+that a candidate is worth reviewing, not an acceptance event, so authority moves+out of the status column and into a row somebody has to write.++``decision_acceptances`` is that row, and it is append-only: reaffirming,+superseding and dismissing add to the log rather than editing it, so the history+of who granted authority survives every later action. Its CHECK constraints are+the acceptance contract — a reason, a scope, an evidence reference, and an+accepter or a tracked-artifact identity — enforced by the database rather than by+whichever caller is writing. A record with no acceptance row is a candidate, and+because a governance read is a join onto this table, a candidate cannot be+reached through one.++``decision_candidate_meta`` holds what review needs and a decision does not, so+the two entities do not share a column set. ``decision_aliases`` keeps ids that+merge and supersede retire from failing to resolve.++Legacy rows are classified by ``repowise decision migrate``, not here: a data+repair that lives in a migration and one that lives in the code eventually+disagree, and only one of them runs on an existing store.++Local SQLite stores get these tables from the models via ``init_db``'s schema+reconciler; this migration covers the managed Postgres ones.++Revision ID: 0063+Revises: 0062+Create Date: 2026-09-01+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0063"+down_revision: str | None = "0062"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.create_table(+ "decision_acceptances",+ sa.Column("id", sa.String(length=32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(length=32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column(+ "decision_id",+ sa.String(length=32),+ sa.ForeignKey("decision_records.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("seq", sa.Integer(), nullable=False, server_default="1"),+ sa.Column("action", sa.String(length=24), nullable=False, server_default="accepted"),+ sa.Column("currency", sa.String(length=16), nullable=False, server_default="active"),+ sa.Column("reason", sa.Text(), nullable=False),+ sa.Column("scope_json", sa.Text(), nullable=False, server_default="[]"),+ sa.Column("evidence_json", sa.Text(), nullable=False, server_default="[]"),+ sa.Column("accepter", sa.Text(), nullable=False, server_default=""),+ sa.Column("artifact", sa.Text(), nullable=False, server_default=""),+ sa.Column("note", sa.Text(), nullable=False, server_default=""),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.UniqueConstraint("decision_id", "seq", name="uq_decision_acceptance_seq"),+ sa.CheckConstraint("reason <> ''", name="ck_acceptance_reason"),+ sa.CheckConstraint("scope_json NOT IN ('', '[]')", name="ck_acceptance_scope"),+ sa.CheckConstraint("evidence_json NOT IN ('', '[]')", name="ck_acceptance_evidence"),+ sa.CheckConstraint("accepter <> '' OR artifact <> ''", name="ck_acceptance_identity"),+ sa.CheckConstraint(+ "currency IN ('active', 'needs_review', 'uncheckable', 'superseded', 'dismissed')",+ name="ck_acceptance_currency",+ ),+ )+ op.create_index(+ "ix_decision_acceptances_repository_id", "decision_acceptances", ["repository_id"]+ )+ op.create_index(+ "ix_decision_acceptances_decision_id", "decision_acceptances", ["decision_id"]+ )++ op.create_table(+ "decision_candidate_meta",+ sa.Column(+ "decision_id",+ sa.String(length=32),+ sa.ForeignKey("decision_records.id", ondelete="CASCADE"),+ primary_key=True,+ ),+ sa.Column(+ "repository_id",+ sa.String(length=32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("review_state", sa.String(length=16), nullable=False, server_default="open"),+ sa.Column("review_priority", sa.Float(), nullable=False, server_default="0"),+ sa.Column("grounding_json", sa.Text(), nullable=False, server_default="{}"),+ sa.Column("extractor_version", sa.String(length=64), nullable=False, server_default=""),+ sa.Column("lane", sa.String(length=32), nullable=False, server_default=""),+ sa.Column("needs_split", sa.Boolean(), nullable=False, server_default=sa.false()),+ sa.Column("scope_unresolved", sa.Boolean(), nullable=False, server_default=sa.false()),+ sa.Column("merged_into", sa.String(length=32), nullable=True),+ sa.Column("dismissed_reason", sa.Text(), nullable=False, server_default=""),+ sa.Column("first_seen", sa.DateTime(timezone=True), nullable=False),+ sa.Column("last_seen", sa.DateTime(timezone=True), nullable=False),+ sa.CheckConstraint(+ "review_state IN ('open', 'accepted', 'merged', 'needs_split', 'dismissed')",+ name="ck_candidate_review_state",+ ),+ )+ op.create_index(+ "ix_decision_candidate_meta_repository_id",+ "decision_candidate_meta",+ ["repository_id"],+ )+ op.create_index(+ "ix_candidate_meta_repo_state",+ "decision_candidate_meta",+ ["repository_id", "review_state"],+ )++ op.create_table(+ "decision_aliases",+ sa.Column("alias_id", sa.String(length=32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(length=32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column(+ "decision_id",+ sa.String(length=32),+ sa.ForeignKey("decision_records.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("reason", sa.String(length=32), nullable=False, server_default="merged"),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ )+ op.create_index("ix_decision_aliases_repository_id", "decision_aliases", ["repository_id"])+ op.create_index("ix_decision_aliases_decision_id", "decision_aliases", ["decision_id"])+++def downgrade() -> None:+ op.drop_table("decision_aliases")+ op.drop_table("decision_candidate_meta")+ op.drop_table("decision_acceptances")diff --git a/packages/core/src/repowise/core/analysis/decisions/accepter.py b/packages/core/src/repowise/core/analysis/decisions/accepter.pynew file mode 100644index 000000000..2e7f436d5--- /dev/null+++ b/packages/core/src/repowise/core/analysis/decisions/accepter.py@@ -0,0 +1,75 @@+"""Who is accepting a decision, when a command line is the surface.++An acceptance without an identity is not auditable, and asking for one on every+confirm would make the common case worse than the current unattributed promote.+So it is resolved: the repository's own git identity first, because that is the+name the decision's commits will carry, then the OS user, then a last-resort+constant that at least says the acceptance was local and manual.+"""++from __future__ import annotations++import getpass+import subprocess+from pathlib import Path++__all__ = ["is_tracked", "resolve_accepter"]++_FALLBACK = "local"+++def _git_identity(repo_path: Path) -> str:+ try:+ proc = subprocess.run(+ ["git", "config", "user.name"],+ cwd=repo_path,+ capture_output=True,+ text=True,+ timeout=5,+ check=False,+ )+ except (OSError, subprocess.SubprocessError):+ return ""+ return proc.stdout.strip() if proc.returncode == 0 else ""+++def resolve_accepter(repo_path: Path | str, *, override: str = "") -> str:+ """The identity to stamp on an acceptance, never empty."""+ if override.strip():+ return override.strip()+ name = _git_identity(Path(repo_path))+ if name:+ return name+ try:+ return getpass.getuser() or _FALLBACK+ except Exception:+ return _FALLBACK+++def is_tracked(repo_path: Path | str, rel_path: str) -> bool:+ """Whether *rel_path* is committed, so somebody other than this machine saw it.++ The tracked-artifact acceptance rests entirely on this: an ADR a coding+ agent wrote and never committed is a file on one machine, not a statement+ the team reviewed.++ Only an actual "git tracks this repository and not this file" is a refusal.+ Where there is no git to ask — an unversioned directory, no git binary —+ there is no commit gate to fail, and the document is exactly as+ authoritative as anything else the user put on disk.+ """+ if not rel_path:+ return False+ try:+ proc = subprocess.run(+ ["git", "ls-files", "--error-unmatch", "--", rel_path],+ cwd=Path(repo_path),+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ except (OSError, subprocess.SubprocessError):+ return True+ # 0 tracked, 1 untracked, 128 not a repository.+ return proc.returncode != 1diff --git a/packages/core/src/repowise/core/analysis/decisions/evolution.py b/packages/core/src/repowise/core/analysis/decisions/evolution.pyindex db3a182ed..19678f265 100644--- a/packages/core/src/repowise/core/analysis/decisions/evolution.py+++ b/packages/core/src/repowise/core/analysis/decisions/evolution.py@@ -347,8 +347,6 @@ async def detect_supersessions_and_conflicts(if not touched_ids or vector_store is None:return summary- from datetime import UTC, datetime-from repowise.core.persistence.decision_graph import upsert_decision_edgefrom repowise.core.persistence.models import DecisionRecord@@ -426,9 +424,7 @@ async def detect_supersessions_and_conflicts(if edge is not None:summary["supersedes"] += 1if conf >= autoflip_confidence and older.status in ("active", "proposed"):- older.status = "superseded"- older.superseded_by = newer.id- older.updated_at = datetime.now(UTC)+ await _retire(session, older, successor_id=newer.id)summary["flipped"] += 1else:# Two active decisions contradict, neither clearly reverses the@@ -447,8 +443,6 @@ async def detect_supersessions_and_conflicts(await session.flush()return summary--_CONTRADICTION_SYSTEM = ("You judge whether two architectural decisions contradict each other. ""Answer with a single word: CONTRADICT or COMPATIBLE."@@ -705,8 +699,7 @@ async def run_update_evolution(kind = verdict["verdict"]if kind == "superseded":if dec.status in ("active", "proposed"):- dec.status = "superseded"- dec.updated_at = now+ await _retire(session, dec)regen.update(governed)result["superseded"] += 1elif kind == "amended":@@ -726,3 +719,38 @@ async def run_update_evolution(await session.flush()return result+++async def _retire(session, record, *, successor_id: str | None = None) -> None:+ """Mark a record superseded, recording the withdrawal if it was accepted.++ An accepted decision's authority lives in the acceptance log, so retiring it+ by writing the status column alone would leave the log still saying it+ governs — and the tracked manifest would keep exporting it as current.+ A candidate has no authority to withdraw, so it only moves status.+ """+ import contextlib+ from datetime import UTC, datetime++ from repowise.core.persistence.crud.authority import (+ AcceptanceRefusedError,+ is_accepted,+ record_acceptance,+ )++ if await is_accepted(session, record.id):+ # A record that lost the evidence its acceptance rested on cannot log+ # the withdrawal; the retirement itself still applies.+ with contextlib.suppress(AcceptanceRefusedError):+ await record_acceptance(+ session,+ record,+ action="superseded",+ currency="superseded",+ accepter="evolution",+ note="a later commit reversed this decision",+ )+ record.status = "superseded"+ if successor_id is not None:+ record.superseded_by = successor_id+ record.updated_at = datetime.now(UTC)diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.pyindex be08df2fa..701685264 100644--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py@@ -883,8 +883,12 @@ class DecisionExtractor:if not (decision_txt or context):return None+ # A document with no Status section has not said it is accepted, and a+ # committed ADR is the one artifact allowed to accept its own decision.+ # Defaulting to ``active`` therefore let any draft under docs/adr/ grant+ # itself authority.status_key = status.strip().lower().split()[0] if status.strip() else ""- mapped_status = _ADR_STATUS_MAP.get(status_key, "active")+ mapped_status = _ADR_STATUS_MAP.get(status_key, "proposed")return ExtractedDecision(title=_truncate_title(title or rel_path, 200),diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.pynew file mode 100644index 000000000..3caabf649--- /dev/null+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py@@ -0,0 +1,169 @@+"""The three-entity vocabulary: episode, candidate, decision.++An *episode* is an evidenced event. A *candidate* is a possible durable choice+inferred from evidence. A *decision* is a constraint a person accepted. Only the+third governs, and nothing but an explicit acceptance produces one.++Pure: no I/O, no ORM, no provider. The persistence layer, the CLI, the manifest+writer and the migration all resolve the same words here so a review action+cannot mean one thing in the database and another on the wire.+"""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass++__all__ = [+ "ACCEPTANCE_ACTIONS",+ "CANDIDATE_REVIEW_STATES",+ "DECISION_CURRENCIES",+ "NEEDS_REVIEW_STALENESS",+ "STORED_CURRENCIES",+ "AcceptanceRequirement",+ "acceptance_blockers",+ "currency_for_legacy_status",+ "effective_currency",+ "is_governing",+ "legacy_status_for_currency",+]++#: What a decision's authority currently amounts to. Replaces the numeric+#: staleness threshold as the *product* answer; the score stays an internal+#: supporting fact that feeds ``needs_review``.+DECISION_CURRENCIES: tuple[str, ...] = (+ "active", # accepted and still describes the code+ "needs_review", # accepted, but the code it names has moved+ "uncheckable", # accepted, but names nothing the repository can be asked about+ "superseded", # replaced by a later decision, via an explicit lineage edge+ "dismissed", # authority withdrawn; kept for history+)++#: Where a candidate is in review. ``dismissed`` is a durable tombstone: it is+#: what stops re-extraction from re-proposing something already rejected.+CANDIDATE_REVIEW_STATES: tuple[str, ...] = (+ "open",+ "accepted",+ "merged",+ "needs_split",+ "dismissed",+)++#: The currencies a person or artifact can *set*. ``needs_review`` and+#: ``uncheckable`` are also derived from the code by :func:`effective_currency`,+#: which is why the stored set is smaller than the vocabulary.+STORED_CURRENCIES: tuple[str, ...] = (+ "active",+ "needs_review",+ "superseded",+ "dismissed",+)++#: What an acceptance row records having happened.+ACCEPTANCE_ACTIONS: tuple[str, ...] = (+ "accepted",+ "reaffirmed",+ "merged",+ "superseded",+ "dismissed",+ "returned_to_review",+)++#: The fraction of a decision's files that must have moved before the decision+#: is worth re-reading. Same 0.5 the staleness surfaces already use; the number+#: stays an internal supporting fact and the product word is what is shown.+NEEDS_REVIEW_STALENESS: float = 0.5++#: Currencies that still bind future work. ``needs_review`` deliberately does:+#: a decision whose code moved is a decision to re-read, not one to ignore.+_GOVERNING: frozenset[str] = frozenset({"active", "needs_review"})+++def is_governing(currency: str) -> bool:+ """Whether a decision at *currency* still constrains new work."""+ return currency in _GOVERNING+++def effective_currency(+ stored: str,+ *,+ has_scope: bool,+ staleness: float,+) -> str:+ """The currency to show for a decision stored at *stored*.++ ``superseded``, ``dismissed`` and an explicit ``needs_review`` are authority+ states a person set, and the code cannot argue with them. An ``active``+ decision is re-read against the repository: one that names nothing cannot be+ checked at all, and one whose files have moved is worth looking at again.+ """+ if stored != "active":+ return stored if stored in DECISION_CURRENCIES else "active"+ if not has_scope:+ return "uncheckable"+ if staleness >= NEEDS_REVIEW_STALENESS:+ return "needs_review"+ return "active"+++@dataclass(frozen=True, slots=True)+class AcceptanceRequirement:+ """The evidence an acceptance has to carry to be storable."""++ reason: str+ scope: Sequence[str]+ evidence: Sequence[str]+ accepter: str = ""+ artifact: str = ""+ #: The accepter wrote the record rather than reviewing something a machine+ #: inferred. Then the entry itself is the provenance, and demanding a+ #: separate reference would make manual capture impossible.+ self_authored: bool = False+++def acceptance_blockers(req: AcceptanceRequirement) -> list[str]:+ """Return the reasons *req* cannot become an acceptance, empty if it can.++ The same four checks the ``decision_acceptances`` CHECK constraints+ enforce, stated once in prose so a caller can explain a refusal instead of+ surfacing an IntegrityError.+ """+ blockers: list[str] = []+ if not req.reason.strip():+ blockers.append("no rationale or explicit constraint reason")+ if not [s for s in req.scope if s and s.strip()]:+ blockers.append("no scope: name the files or modules it governs")+ if not req.self_authored and not [e for e in req.evidence if e and e.strip()]:+ blockers.append("no evidence reference")+ if not req.accepter.strip() and not req.artifact.strip():+ blockers.append("no accepter or tracked-artifact identity")+ return blockers+++#: How the pre-split ``decision_records.status`` column maps onto currency, and+#: back. The column survives as a denormalized projection so unmigrated readers+#: keep working; the acceptance row is the authority.+_LEGACY_TO_CURRENCY: dict[str, str] = {+ "active": "active",+ "deprecated": "dismissed",+ "superseded": "superseded",+ "dismissed": "dismissed",+}++_CURRENCY_TO_LEGACY: dict[str, str] = {+ "active": "active",+ "needs_review": "active",+ "uncheckable": "active",+ "superseded": "superseded",+ "dismissed": "deprecated",+}+++def currency_for_legacy_status(status: str) -> str | None:+ """Currency for a legacy status, or ``None`` if it is not a decision at all."""+ return _LEGACY_TO_CURRENCY.get(status)+++def legacy_status_for_currency(currency: str) -> str:+ """The ``decision_records.status`` value that projects *currency*."""+ return _CURRENCY_TO_LEGACY.get(currency, "active")diff --git a/packages/core/src/repowise/core/analysis/decisions/manifest.py b/packages/core/src/repowise/core/analysis/decisions/manifest.pynew file mode 100644index 000000000..499bf3dc7--- /dev/null+++ b/packages/core/src/repowise/core/analysis/decisions/manifest.py@@ -0,0 +1,252 @@+"""``.repowise/decisions.yaml`` — the tracked source of truth for accepted decisions.++Accepted decisions are the one part of the decision layer that belongs to the+repository rather than to a machine. A candidate is a local inference; a+decision is a constraint the team agreed to, and it should travel in the same+commit as the code it governs, be reviewable in a diff, and survive a deleted+index. The database keeps the same rows as an indexed projection.++The format is generated, not hand-authored prose: reading it back and writing it+again produces the same bytes, which is what makes it diffable. Comments are not+preserved, and the file says so in its own header.++Episodes and candidates deliberately stay out. They are evidence and inference,+they turn over constantly, and committing them would put a machine's opinions+under review as though they were the team's.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import yaml++from repowise.core.fsutils import atomic_write_text++__all__ = [+ "MANIFEST_FILENAME",+ "MANIFEST_VERSION",+ "ManifestConflictError",+ "ManifestDecision",+ "load_manifest",+ "manifest_path",+ "render_manifest",+ "write_manifest",+]++MANIFEST_FILENAME = "decisions.yaml"++#: Bumped only for a change a previous reader could misread. Additive optional+#: keys do not bump it: an older repowise ignoring a key it does not know is+#: better than refusing to read the file at all.+MANIFEST_VERSION = 1++_HEADER = (+ "# Accepted architectural decisions for this repository.\n"+ "#\n"+ "# Generated and rewritten by repowise; edits survive, comments do not.\n"+ "# Commit this file: it is the source of truth, and the index is a copy.\n"+ "# Candidates and evidence stay out of it on purpose.\n"+)+++@dataclass(frozen=True, slots=True)+class ManifestDecision:+ """One accepted decision, as the file represents it."""++ id: str+ title: str+ decision: str+ reason: str+ scope: list[str]+ accepted_at: str+ accepted_by: str = ""+ accepted_artifact: str = ""+ currency: str = "active"+ source: str = "cli"+ evidence: list[str] = field(default_factory=list)+ superseded_by: str = ""+ aliases: list[str] = field(default_factory=list)++ def to_mapping(self) -> dict[str, Any]:+ """The ordered projection written to disk.++ Field order is fixed here rather than left to the dataclass, and empty+ optionals are dropped, so two stores holding the same decisions render+ byte-identical files.+ """+ out: dict[str, Any] = {+ "id": self.id,+ "title": self.title,+ "decision": self.decision,+ "reason": self.reason,+ "scope": sorted(self.scope),+ "currency": self.currency,+ "source": self.source,+ "accepted_at": self.accepted_at,+ }+ if self.accepted_by:+ out["accepted_by"] = self.accepted_by+ if self.accepted_artifact:+ out["accepted_artifact"] = self.accepted_artifact+ if self.evidence:+ out["evidence"] = sorted(self.evidence)+ if self.superseded_by:+ out["superseded_by"] = self.superseded_by+ if self.aliases:+ out["aliases"] = sorted(self.aliases)+ return out++ @classmethod+ def from_mapping(cls, data: dict[str, Any]) -> ManifestDecision:+ def _text(key: str) -> str:+ value = data.get(key)+ return "" if value is None else str(value)++ def _list(key: str) -> list[str]:+ value = data.get(key) or []+ return [str(v) for v in value] if isinstance(value, list) else []++ return cls(+ id=_text("id"),+ title=_text("title"),+ decision=_text("decision"),+ reason=_text("reason"),+ scope=_list("scope"),+ accepted_at=_text("accepted_at"),+ accepted_by=_text("accepted_by"),+ accepted_artifact=_text("accepted_artifact"),+ currency=_text("currency") or "active",+ source=_text("source") or "cli",+ evidence=_list("evidence"),+ superseded_by=_text("superseded_by"),+ aliases=_list("aliases"),+ )+++class ManifestConflictError(Exception):+ """The file on disk is not the one the caller read.++ Raised instead of overwriting: a manifest is a tracked artifact, and the+ change the caller would clobber may be a colleague's commit rather than a+ stale copy.+ """+++def _check_version(path: Path, version: object) -> None:+ """Refuse a file this build would silently downgrade.++ A malformed version is refused for the same reason a newer one is: the file+ is tracked, and rewriting one this build does not understand loses whatever+ the newer writer put in it.+ """+ if version is None:+ return+ try:+ found = int(version)+ except (TypeError, ValueError) as exc:+ raise ManifestConflictError(+ f"{path} has a non-numeric format version {version!r}."+ ) from exc+ if found > MANIFEST_VERSION:+ raise ManifestConflictError(+ f"{path} was written by a newer repowise (format {found}, this build "+ f"reads {MANIFEST_VERSION}). Upgrade rather than rewriting it."+ )+++def manifest_path(repo_path: Path | str) -> Path:+ return Path(repo_path) / ".repowise" / MANIFEST_FILENAME+++def render_manifest(decisions: list[ManifestDecision]) -> str:+ """Serialize *decisions* deterministically.++ Ordered by id, not by acceptance time: an id is stable and a timestamp is+ not, so ordering by id keeps a re-accepted decision from moving and turning+ a one-line change into a whole-file diff.+ """+ payload = {+ "version": MANIFEST_VERSION,+ "decisions": [d.to_mapping() for d in sorted(decisions, key=lambda d: d.id)],+ }+ body = yaml.dump(+ payload,+ default_flow_style=False,+ sort_keys=False,+ allow_unicode=True,+ width=100,+ )+ return _HEADER + body+++def load_manifest(repo_path: Path | str) -> tuple[list[ManifestDecision], str]:+ """Read the manifest, returning its decisions and its raw bytes.++ The raw text is what :func:`write_manifest` compares against to detect a+ concurrent change; an absent file reads as no decisions and an empty string,+ which is a legitimate starting state rather than an error.+ """+ path = manifest_path(repo_path)+ if not path.exists():+ return [], ""+ raw = path.read_text(encoding="utf-8")+ try:+ data = yaml.safe_load(raw)+ except yaml.YAMLError as exc:+ raise ManifestConflictError(f"{path} is not valid YAML: {exc}") from exc+ if data is None:+ return [], raw+ if not isinstance(data, dict):+ raise ManifestConflictError(f"{path} must hold a mapping, not {type(data).__name__}.")+ _check_version(path, data.get("version"))+ entries = data.get("decisions") or []+ if not isinstance(entries, list):+ raise ManifestConflictError(f"{path}: 'decisions' must be a list.")+ return [+ ManifestDecision.from_mapping(e) for e in entries if isinstance(e, dict)+ ], raw+++def write_manifest(+ repo_path: Path | str,+ decisions: list[ManifestDecision],+ *,+ expected_raw: str | None = None,+ allow_empty: bool = False,+) -> bool:+ """Write the manifest atomically. Returns whether the bytes changed.++ With *expected_raw*, a file that no longer matches what the caller read+ raises :class:`ManifestConflictError` and nothing is written. An unchanged render+ is not rewritten at all, so a no-op update leaves the mtime — and any watcher+ keyed on it — alone.+ """+ path = manifest_path(repo_path)+ rendered = render_manifest(decisions)+ current = path.read_text(encoding="utf-8") if path.exists() else ""+ if expected_raw is not None and current != expected_raw:+ raise ManifestConflictError(+ f"{path} changed since it was read. Reconcile the two versions and retry."+ )+ if current:+ existing, _ = load_manifest(repo_path)+ # A store rebuilt from scratch has no acceptances yet, and writing its+ # empty projection over the committed file would delete the team's+ # decisions with no way back. The file is the source of truth; an empty+ # store is a store that has not imported it.+ if existing and not decisions and not allow_empty:+ raise ManifestConflictError(+ f"{path} holds {len(existing)} decision(s) and the store holds none. "+ "Import it first, or pass allow_empty to overwrite it deliberately."+ )+ if current == rendered:+ return False+ path.parent.mkdir(parents=True, exist_ok=True)+ # Newline-normalized so the file does not churn between contributors on+ # different platforms, and fsynced because losing it loses the authority+ # itself rather than a cache.+ atomic_write_text(path, rendered, newline="\n", fsync=True)+ return Truediff --git a/packages/core/src/repowise/core/fsutils.py b/packages/core/src/repowise/core/fsutils.pyindex 328e690b3..97fe72a35 100644--- a/packages/core/src/repowise/core/fsutils.py+++ b/packages/core/src/repowise/core/fsutils.py@@ -2,22 +2,37 @@from __future__ import annotations+import osimport tempfilefrom pathlib import Path-def atomic_write_text(path: Path, content: str, *, newline: str | None = None) -> None:+def atomic_write_text(+ path: Path,+ content: str,+ *,+ newline: str | None = None,+ fsync: bool = False,+) -> None:"""Write *content* to *path* atomically via a temp file + rename.Readers never observe a truncated or half-written file: the temp file iscreated in the destination directory (same filesystem, so the rename isatomic) and either replaces *path* wholesale or is cleaned up on failure.++ With *fsync*, the bytes are on the platter before the rename, so the file+ also survives a power loss rather than only a concurrent read. Off by+ default: it costs a disk round-trip, and most callers here are rewriting+ something they can regenerate."""parent = path.parentfd, tmp = tempfile.mkstemp(dir=parent, suffix=".tmp")try:with open(fd, "w", encoding="utf-8", newline=newline) as f:f.write(content)+ if fsync:+ f.flush()+ os.fsync(f.fileno())Path(tmp).replace(path)except Exception:Path(tmp).unlink(missing_ok=True)diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.pyindex 8f9f1e711..cf806158b 100644--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py@@ -261,14 +261,21 @@ class EditorFileDataFetcher:return hotspotsasync def _get_decisions(self) -> list[DecisionSummary]:- """Active decision records, least-stale first."""+ """Accepted decision records, least-stale first.++ An agent reads this block as instructions, so it is the surface where+ the candidate/decision distinction matters most: acceptance, not a+ status string a recurrence check wrote, is what earns a line here.+ """from repowise.core.exclusion import build_exclude_spec, decision_is_excluded+ from repowise.core.persistence.crud.authority import accepted_predicateresult = await self._session.execute(select(DecisionRecord).where(DecisionRecord.repository_id == self._repo_id,DecisionRecord.status == "active",+ accepted_predicate(),).order_by(DecisionRecord.staleness_score.asc())# Over-fetch: records anchored entirely in excluded paths (vendoreddiff --git a/packages/core/src/repowise/core/persistence/crud/__init__.py b/packages/core/src/repowise/core/persistence/crud/__init__.pyindex 950535cf0..a68e0fbe4 100644--- a/packages/core/src/repowise/core/persistence/crud/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/__init__.py@@ -19,6 +19,7 @@ knowledge_graph). Import names from here — sub-module layout may change.from __future__ import annotationsfrom .analysis import * # noqa: F403+from .authority import * # noqa: F403from .chat import * # noqa: F403from .decisions import * # noqa: F403from .external_systems import * # noqa: F403diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pynew file mode 100644index 000000000..d917b248f--- /dev/null+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -0,0 +1,717 @@+"""Acceptance, candidate review, and id continuity.++The write side of the three-entity contract. ``decisions.py`` owns extraction's+accretion path and knows nothing about authority; everything that turns a+candidate into a decision, or moves one through review, is here.++One rule shapes the module: :func:`record_acceptance` is the only writer of+``decision_acceptances``, and it refuses anything the acceptance contract does+not cover. Every review action goes through it, so no caller can invent a+shortcut past the reason/scope/evidence/identity requirement.+"""++from __future__ import annotations++import json+from typing import Any++from sqlalchemy import func, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.decisions.lifecycle import (+ ACCEPTANCE_ACTIONS,+ STORED_CURRENCIES,+ AcceptanceRequirement,+ acceptance_blockers,+ effective_currency,+ legacy_status_for_currency,+)++from ..decision_graph import upsert_decision_edge+from ..models import (+ DecisionAcceptance,+ DecisionAlias,+ DecisionCandidateMeta,+ DecisionRecord,+ _now_utc,+)++__all__ = [+ "ACCEPTED_SQL_PREDICATE",+ "AcceptanceRefusedError",+ "accept_decision",+ "accepted_decision_ids",+ "accepted_predicate",+ "current_currency",+ "dismiss_candidate",+ "is_accepted",+ "latest_acceptance",+ "list_candidates",+ "merge_candidate",+ "reaffirm_decision",+ "record_acceptance",+ "request_split",+ "resolve_decision_id",+ "return_to_review",+ "supersede_decision",+ "upsert_candidate_meta",+]+++#: Retries for the read-then-write ``seq`` allocation. Two is enough for the+#: only contention this has: two acceptances of one decision landing together.+_SEQ_RETRIES = 3+++class AcceptanceRefusedError(ValueError):+ """An acceptance was attempted without what acceptance requires.++ Carries the individual blockers so a caller can tell the user which of the+ four is missing rather than restating the whole contract.+ """++ def __init__(self, blockers: list[str]) -> None:+ self.blockers = blockers+ super().__init__("; ".join(blockers))+++# ---------------------------------------------------------------------------+# Reading authority+# ---------------------------------------------------------------------------+++def accepted_predicate() -> Any:+ """A ``WHERE`` clause restricting a ``DecisionRecord`` query to decisions.++ Every governance read adds this. Written once rather than per caller+ because the previous arrangement — each surface spelling out its own+ ``status == "active"`` — is how the same question came to have four+ different answers across the CLI, the MCP tools and two web surfaces.+ """+ return select(DecisionAcceptance.id).where(+ DecisionAcceptance.decision_id == DecisionRecord.id+ ).exists()+++#: The same predicate for the hook path, which opens the store with stdlib+#: sqlite3 and cannot import the ORM. Correlated on ``decision_records.id``, so+#: it drops into an existing ``WHERE`` unchanged.+ACCEPTED_SQL_PREDICATE = (+ "EXISTS (SELECT 1 FROM decision_acceptances a "+ "WHERE a.decision_id = decision_records.id)"+)+++async def latest_acceptance(+ session: AsyncSession, decision_id: str+) -> DecisionAcceptance | None:+ """The acceptance row that currently governs *decision_id*, if any.++ ``None`` means the record is a candidate. This is the one predicate that+ separates the two entities; every governance read is a join onto it.+ """+ result = await session.execute(+ select(DecisionAcceptance)+ .where(DecisionAcceptance.decision_id == decision_id)+ .order_by(DecisionAcceptance.seq.desc())+ .limit(1)+ )+ return result.scalar_one_or_none()+++async def is_accepted(session: AsyncSession, decision_id: str) -> bool:+ """Whether *decision_id* has ever been accepted."""+ return await latest_acceptance(session, decision_id) is not None+++async def accepted_decision_ids(+ session: AsyncSession,+ repository_id: str,+ *,+ governing_only: bool = False,+) -> set[str]:+ """Ids of every accepted decision in *repository_id*.++ With *governing_only*, drops the ones whose authority has been withdrawn+ (``superseded``, ``dismissed``) so the caller is left with what still binds.+ The subquery picks the highest ``seq`` per decision, which is the append-only+ log's way of saying "current".+ """+ latest_seq = (+ select(+ DecisionAcceptance.decision_id.label("did"),+ func.max(DecisionAcceptance.seq).label("seq"),+ )+ .where(DecisionAcceptance.repository_id == repository_id)+ .group_by(DecisionAcceptance.decision_id)+ .subquery()+ )+ q = select(DecisionAcceptance.decision_id, DecisionAcceptance.currency).join(+ latest_seq,+ (DecisionAcceptance.decision_id == latest_seq.c.did)+ & (DecisionAcceptance.seq == latest_seq.c.seq),+ )+ rows = (await session.execute(q)).all()+ if not governing_only:+ return {did for did, _ in rows}+ return {did for did, currency in rows if currency not in ("superseded", "dismissed")}+++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)+ if acceptance is None:+ return None+ has_scope = bool(_record_scope(record))+ return effective_currency(+ acceptance.currency,+ has_scope=has_scope,+ staleness=record.staleness_score,+ )+++async def resolve_decision_id(session: AsyncSession, decision_id: str) -> str | None:+ """Resolve an id that may be a retired alias to the live record's id.++ Merging and superseding retire ids that are already in circulation — in a+ committed manifest, in an agent's notes. Every id-taking entry point routes+ through here so those keep resolving instead of reading as deleted.+ """+ alias = await session.get(DecisionAlias, decision_id)+ if alias is not None and alias.reason == "merged":+ # A merged candidate's row survives, because its evidence is worth+ # keeping, so the record still resolves by id. Following the alias is+ # what stops the same constraint being accepted a second time under the+ # id that was folded away. A superseded decision keeps resolving to+ # itself: it is still a decision, and its history is what you asked for.+ return alias.decision_id+ if await session.get(DecisionRecord, decision_id) is not None:+ return decision_id+ return alias.decision_id if alias is not None else None+++# ---------------------------------------------------------------------------+# Writing authority+# ---------------------------------------------------------------------------+++def _json_list(value: Any) -> list[str]:+ if isinstance(value, str):+ try:+ parsed = json.loads(value or "[]")+ except (TypeError, ValueError):+ return []+ return [str(v) for v in parsed] if isinstance(parsed, list) else []+ return [str(v) for v in (value or [])]+++def _record_scope(record: DecisionRecord) -> list[str]:+ return _json_list(record.affected_files_json) or _json_list(+ record.affected_modules_json+ )+++def _record_evidence(record: DecisionRecord) -> list[str]:+ evidence = _json_list(record.evidence_commits_json)+ if record.evidence_file:+ evidence.append(record.evidence_file)+ return evidence+++async def record_acceptance(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ action: str,+ currency: str,+ reason: str = "",+ scope: list[str] | None = None,+ evidence: list[str] | None = None,+ accepter: str = "",+ artifact: str = "",+ note: str = "",+) -> DecisionAcceptance:+ """Append one acceptance row for *record*, or refuse.++ The only writer of ``decision_acceptances``. *reason*, *scope* and+ *evidence* default to what the record already carries, so an accept of a+ well-formed candidate needs no arguments beyond the accepter; a record+ missing any of them is refused with the specific gap named rather than+ accepted with a blank.+ """+ if action not in ACCEPTANCE_ACTIONS:+ raise ValueError(f"Unknown acceptance action {action!r}.")+ if currency not in STORED_CURRENCIES:+ raise ValueError(f"Unknown stored currency {currency!r}.")++ # A record somebody typed is its own provenance: the accepter did not read+ # an inference, they wrote the claim. Everything mined from a transcript, a+ # commit or a document still has to say what it rests on.+ self_authored = record.source == "cli" and bool(accepter.strip())+ resolved_evidence = evidence if evidence is not None else _record_evidence(record)+ if not resolved_evidence and self_authored:+ resolved_evidence = [f"accepted by {accepter}"]++ req = AcceptanceRequirement(+ reason=reason or record.rationale or record.decision,+ scope=scope if scope is not None else _record_scope(record),+ evidence=resolved_evidence,+ accepter=accepter,+ artifact=artifact,+ self_authored=self_authored,+ )+ blockers = acceptance_blockers(req)+ if blockers:+ raise AcceptanceRefusedError(blockers)++ acceptance = await _append_acceptance(+ session,+ record,+ action=action,+ currency=currency,+ req=req,+ accepter=accepter,+ artifact=artifact,+ note=note,+ )++ # The legacy column is a projection of the acceptance, never its source.+ # Keeping it in step is what lets readers that predate the split stay+ # correct instead of merely stale.+ record.status = legacy_status_for_currency(currency)+ record.updated_at = _now_utc()+ await session.flush()+ return acceptance+++async def _append_acceptance(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ action: str,+ currency: str,+ req: AcceptanceRequirement,+ accepter: str,+ artifact: str,+ note: str,+) -> DecisionAcceptance:+ """Insert the next log row, retrying the sequence on a concurrent append.++ ``seq`` is allocated read-then-write, so two acceptances of one decision+ landing together both read the same maximum and one loses the unique+ constraint. Retrying is the whole fix: the loser re-reads and takes the+ next number, which is what serializing them would have produced anyway.+ """+ for attempt in range(_SEQ_RETRIES):+ next_seq = (+ await session.execute(+ select(func.coalesce(func.max(DecisionAcceptance.seq), 0)).where(+ DecisionAcceptance.decision_id == record.id+ )+ )+ ).scalar_one() + 1+ acceptance = DecisionAcceptance(+ repository_id=record.repository_id,+ decision_id=record.id,+ seq=next_seq,+ action=action,+ currency=currency,+ reason=req.reason,+ scope_json=json.dumps(list(req.scope)),+ evidence_json=json.dumps(list(req.evidence)),+ accepter=accepter,+ artifact=artifact,+ note=note,+ )+ session.add(acceptance)+ try:+ await session.flush()+ except IntegrityError:+ if attempt == _SEQ_RETRIES - 1:+ raise+ await session.rollback()+ continue+ return acceptance+ raise RuntimeError("unreachable") # pragma: no cover+++async def accept_decision(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ accepter: str = "",+ artifact: str = "",+ reason: str = "",+ scope: list[str] | None = None,+ evidence: list[str] | None = None,+ note: str = "",+) -> DecisionAcceptance:+ """Accept a candidate, optionally editing its reason and scope on the way.++ The edit is applied to the record too: accepting a claim with a corrected+ scope must not leave the record describing the uncorrected one. *evidence*+ supplies what a candidate that cites nothing is missing, and is recorded on+ the acceptance rather than rewritten onto the record: it is what the+ accepter went on, not something extraction found.+ """+ meta = await session.get(DecisionCandidateMeta, record.id)+ if meta is not None and meta.review_state == "merged":+ raise AcceptanceRefusedError(+ [f"already merged into {meta.merged_into or 'another decision'}"]+ )+ if reason:+ record.rationale = reason+ if scope is not None:+ record.affected_files_json = json.dumps(scope)+ acceptance = await record_acceptance(+ session,+ record,+ action="accepted",+ currency="active",+ reason=reason,+ scope=scope,+ evidence=evidence,+ accepter=accepter,+ artifact=artifact,+ note=note,+ )+ await _set_review_state(session, record, "accepted")+ return acceptance+++async def reaffirm_decision(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ accepter: str = "",+ artifact: str = "",+ note: str = "",+) -> DecisionAcceptance:+ """Re-accept a decision after review, clearing a ``needs_review`` state."""+ return await record_acceptance(+ session,+ record,+ action="reaffirmed",+ currency="active",+ accepter=accepter,+ artifact=artifact,+ note=note,+ )+++async def return_to_review(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ accepter: str = "",+ artifact: str = "",+ note: str = "",+) -> DecisionAcceptance:+ """Send an accepted decision back to review without erasing its history.++ Appends rather than deletes, so the record keeps the acceptance that made it+ govern in the first place. It remains a decision, not a candidate: it was+ accepted once, and pretending otherwise would lose that.+ """+ return await record_acceptance(+ session,+ record,+ action="returned_to_review",+ currency="needs_review",+ accepter=accepter,+ artifact=artifact,+ note=note,+ )+++async def supersede_decision(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ successor_id: str,+ accepter: str = "",+ artifact: str = "",+ note: str = "",+) -> DecisionAcceptance:+ """Retire *record* in favour of *successor_id*, with an explicit edge.++ Similarity never reaches here: an edge is written because someone named the+ successor. The retired id becomes an alias of the successor so references to+ it keep resolving to the decision that now governs.+ """+ successor = await session.get(DecisionRecord, successor_id)+ if successor is None:+ raise ValueError(f"Unknown successor decision {successor_id!r}.")+ if successor.id == record.id:+ raise ValueError("A decision cannot supersede itself.")++ acceptance = await record_acceptance(+ session,+ record,+ action="superseded",+ currency="superseded",+ accepter=accepter,+ artifact=artifact,+ note=note,+ )+ record.superseded_by = successor.id+ await upsert_decision_edge(+ session,+ repository_id=record.repository_id,+ src_decision_id=successor.id,+ dst_decision_id=record.id,+ kind="supersedes",+ confidence=1.0,+ evidence=f"superseded by {accepter or artifact}",+ )+ await _add_alias(session, record.id, successor.id, reason="superseded")+ return acceptance+++async def merge_candidate(+ session: AsyncSession,+ candidate: DecisionRecord,+ *,+ into_id: str,+ accepter: str = "",+ artifact: str = "",+ note: str = "",+) -> DecisionAcceptance:+ """Fold *candidate* into an existing decision instead of accepting it twice.++ The target must already be a decision: merging into a candidate would create+ authority out of two things that have none. The candidate's evidence stays+ on its own row and its id becomes an alias of the target.+ """+ target = await session.get(DecisionRecord, into_id)+ if target is None:+ raise ValueError(f"Unknown merge target {into_id!r}.")+ if target.id == candidate.id:+ raise ValueError("A candidate cannot be merged into itself.")+ if not await is_accepted(session, target.id):+ raise ValueError(+ f"Merge target {into_id!r} is a candidate; accept it before merging into it."+ )+ if await is_accepted(session, candidate.id):+ raise ValueError(+ f"{candidate.id} is an accepted decision, not a candidate. "+ "Supersede it instead, so the retirement is recorded."+ )++ acceptance = await record_acceptance(+ session,+ target,+ action="merged",+ currency="active",+ evidence=_record_evidence(target) + _record_evidence(candidate),+ accepter=accepter,+ artifact=artifact,+ note=note or f"merged candidate {candidate.id}",+ )+ await _set_review_state(session, candidate, "merged", merged_into=target.id)+ await _add_alias(session, candidate.id, target.id, reason="merged")+ return acceptance+++# ---------------------------------------------------------------------------+# Candidate review+# ---------------------------------------------------------------------------+++async def upsert_candidate_meta(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ lane: str = "",+ grounding: dict[str, Any] | None = None,+ extractor_version: str = "",+ review_priority: float | None = None,+ needs_split: bool | None = None,+ scope_unresolved: bool | None = None,+) -> DecisionCandidateMeta:+ """Create or refresh the review row for a candidate.++ Never touches ``review_state``: a re-extraction refreshing grounding must+ not resurrect a dismissed candidate, which is the whole point of the+ tombstone. State moves only through the review actions below.+ """+ meta = await session.get(DecisionCandidateMeta, record.id)+ if meta is None:+ meta = DecisionCandidateMeta(+ decision_id=record.id,+ repository_id=record.repository_id,+ review_state="open",+ )+ session.add(meta)+ if lane:+ meta.lane = lane+ if grounding is not None:+ meta.grounding_json = json.dumps(grounding, sort_keys=True)+ if extractor_version:+ meta.extractor_version = extractor_version+ if review_priority is not None:+ meta.review_priority = review_priority+ if needs_split is not None:+ meta.needs_split = needs_split+ if scope_unresolved is not None:+ meta.scope_unresolved = scope_unresolved+ meta.last_seen = _now_utc()+ await session.flush()+ return meta+++async def dismiss_candidate(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ reason: str = "",+ accepter: str = "",+) -> DecisionCandidateMeta:+ """Tombstone a candidate so re-extraction never proposes it again.++ On a record that *was* accepted this is a withdrawal, and a withdrawal is an+ authority change: it appends to the acceptance log rather than only flipping+ the status column. Without that row the manifest would keep exporting the+ decision as governing, and a colleague's import would undo the dismissal.+ """+ meta = await _set_review_state(session, record, "dismissed")+ meta.dismissed_reason = reason+ if await latest_acceptance(session, record.id) is not None:+ await record_acceptance(+ session,+ record,+ action="dismissed",+ currency="dismissed",+ accepter=accepter or "dismissed",+ note=reason,+ )+ record.status = "dismissed"+ record.updated_at = _now_utc()+ await session.flush()+ return meta+++async def request_split(+ session: AsyncSession,+ record: DecisionRecord,+ *,+ reason: str = "",+) -> DecisionCandidateMeta:+ """Flag a candidate as bundling two choices. Never splits it by machine."""+ meta = await _set_review_state(session, record, "needs_split")+ meta.needs_split = True+ meta.dismissed_reason = reason+ await session.flush()+ return meta+++async def list_candidates(+ session: AsyncSession,+ repository_id: str,+ *,+ review_state: str | None = "open",+ lane: str | None = None,+ limit: int = 100,+ offset: int = 0,+) -> list[tuple[DecisionRecord, DecisionCandidateMeta | None]]:+ """Records with no acceptance, newest and highest-priority first.++ The left join keeps candidates that predate the review table visible; the+ ``NOT IN`` is what makes this a candidate read rather than a status read.+ """+ accepted = select(DecisionAcceptance.decision_id).where(+ DecisionAcceptance.repository_id == repository_id+ )+ q = (+ select(DecisionRecord, DecisionCandidateMeta)+ .outerjoin(+ DecisionCandidateMeta,+ DecisionCandidateMeta.decision_id == DecisionRecord.id,+ )+ .where(+ DecisionRecord.repository_id == repository_id,+ DecisionRecord.id.notin_(accepted),+ )+ )+ if review_state is not None:+ # A candidate with no meta row has never been reviewed, which is+ # exactly what ``open`` means.+ if review_state == "open":+ q = q.where(+ (DecisionCandidateMeta.review_state == "open")+ | (DecisionCandidateMeta.decision_id.is_(None))+ )+ else:+ q = q.where(DecisionCandidateMeta.review_state == review_state)+ if lane is not None:+ q = q.where(DecisionCandidateMeta.lane == lane)+ q = q.order_by(+ DecisionCandidateMeta.review_priority.desc().nullslast(),+ DecisionRecord.confidence.desc(),+ DecisionRecord.created_at.desc(),+ ).limit(limit).offset(offset)+ return [(rec, meta) for rec, meta in (await session.execute(q)).all()]+++# ---------------------------------------------------------------------------+# Internals+# ---------------------------------------------------------------------------+++async def _set_review_state(+ session: AsyncSession,+ record: DecisionRecord,+ state: str,+ *,+ merged_into: str | None = None,+) -> DecisionCandidateMeta:+ meta = await session.get(DecisionCandidateMeta, record.id)+ if meta is None:+ meta = DecisionCandidateMeta(+ decision_id=record.id, repository_id=record.repository_id+ )+ session.add(meta)+ meta.review_state = state+ if merged_into is not None:+ meta.merged_into = merged_into+ meta.last_seen = _now_utc()+ await session.flush()+ return meta+++async def _add_alias(+ session: AsyncSession, alias_id: str, decision_id: str, *, reason: str+) -> None:+ # An alias chain would leave a two-hop lookup nobody performs, so anything+ # already pointing at the retired id is repointed at its successor first —+ # for the update branch as much as the insert one, or A -> B followed by+ # B -> C strands A at an id that no longer resolves.+ stale = (+ (+ await session.execute(+ select(DecisionAlias).where(DecisionAlias.decision_id == alias_id)+ )+ )+ .scalars()+ .all()+ )+ for row in stale:+ row.decision_id = decision_id++ existing = await session.get(DecisionAlias, alias_id)+ if existing is not None:+ existing.decision_id = decision_id+ existing.reason = reason+ await session.flush()+ return+ record = await session.get(DecisionRecord, decision_id)+ session.add(+ DecisionAlias(+ alias_id=alias_id,+ repository_id=record.repository_id if record else "",+ decision_id=decision_id,+ reason=reason,+ )+ )+ await session.flush()diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.pyindex c220a72dc..6d571da5b 100644--- a/packages/core/src/repowise/core/persistence/crud/decisions.py+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py@@ -48,13 +48,26 @@ _VALID_DECISION_STATUSES = frozenset(_PROTECTED_STATUSES = frozenset({"active", "deprecated", "superseded", "dismissed"})+def _extraction_status(incoming: str) -> str:+ """The status extraction is allowed to write.++ Extraction proposes; acceptance promotes. An incoming ``active`` is a+ parsed ADR heading or an old code path's optimism, and neither is an+ acceptance event, so it lands as a proposal. A tracked ADR still reaches+ ``active`` — via :func:`_accept_from_tracked_artifact` below, which records+ the document as the accepter instead of leaving the promotion anonymous.+ """+ return "proposed" if incoming == "active" else incoming++def _merge_status(existing: str, incoming: str) -> str:"""Resolve a re-extracted status against the stored one.- Extraction only ever emits ``proposed`` or ``active`` (ADR files can also- carry ``deprecated``/``superseded``). A protected stored status wins over- an incoming ``proposed``; anything else follows the incoming value.+ A protected stored status wins over an incoming ``proposed``; anything else+ follows the incoming value, after :func:`_extraction_status` has taken+ authority out of extraction's hands."""+ incoming = _extraction_status(incoming)if incoming == "proposed" and existing in _PROTECTED_STATUSES:return existingreturn incoming@@ -105,6 +118,11 @@ async def upsert_decision(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+ # accepts explicitly afterwards if it means to.+ status = _extraction_status(status)+result = await session.execute(q)existing = result.scalar_one_or_none()@@ -300,10 +318,18 @@ async def update_decision_status(status: str,*,superseded_by: str | None = None,+ accepter: str = "",) -> DecisionRecord | None:- """Update the status of a decision record.+ """Move a decision record between statuses, recording authority changes.- Raises ValueError for invalid statuses. Returns None if not found.+ The status column is a projection, so a caller asking for ``active`` is+ asking for an acceptance and gets one, stamped with *accepter*; a caller+ retiring an accepted decision gets a withdrawal appended to the same log.+ Writing the column alone would leave the two disagreeing, which is how a+ dismissal survives in one surface and not another.++ Raises ValueError for an invalid status, and for an acceptance the record+ cannot support. Returns None if not found."""if status not in _VALID_DECISION_STATUSES:raise ValueError(@@ -312,6 +338,30 @@ async def update_decision_status(rec = await session.get(DecisionRecord, decision_id)if rec is None:return None++ from .authority import (+ AcceptanceRefusedError,+ accept_decision,+ is_accepted,+ record_acceptance,+ )++ accepted = await is_accepted(session, rec.id)+ try:+ if status == "active":+ if not accepted:+ await accept_decision(session, rec, accepter=accepter or "unrecorded")+ elif accepted and status in ("dismissed", "deprecated", "superseded"):+ await record_acceptance(+ session,+ rec,+ action="superseded" if status == "superseded" else "dismissed",+ currency="superseded" if status == "superseded" else "dismissed",+ accepter=accepter or "unrecorded",+ )+ except AcceptanceRefusedError as exc:+ raise ValueError(str(exc)) from exc+rec.status = statusif superseded_by is not None:rec.superseded_by = superseded_by@@ -679,6 +729,56 @@ def _first_commit(d: dict) -> str | None:return commits[0] if commits else None+#: Sources whose evidence file is itself a reviewable, version-controlled+#: statement of the decision. Only these can accept without a person present.+_TRACKED_ARTIFACT_SOURCES: frozenset[str] = frozenset({"adr"})+++async def _accept_from_tracked_artifact(+ session: AsyncSession, rec: DecisionRecord, headline: dict+) -> None:+ """Grant acceptance to an ADR the repository has committed as accepted.++ Silent on anything that is not one: a missing rationale or scope means the+ document did not say enough to bind future work, and a refusal there is+ correct rather than an error to report. Re-running is a no-op because the+ acceptance already exists.+ """+ if headline.get("status") != "active":+ return+ if headline.get("source") not in _TRACKED_ARTIFACT_SOURCES:+ return+ artifact = headline.get("evidence_file") or ""+ if not artifact:+ return++ from repowise.core.analysis.decisions.accepter import is_tracked++ from ..models import Repository+ from .authority import AcceptanceRefusedError, is_accepted, record_acceptance++ if await is_accepted(session, rec.id):+ return+ repo = await session.get(Repository, rec.repository_id)+ if repo is None or not is_tracked(repo.local_path, artifact):+ # An uncommitted document is one machine's file. Letting it accept would+ # replace the human acceptance event with a file an agent can write.+ return+ try:+ await record_acceptance(+ session,+ rec,+ action="accepted",+ currency="active",+ artifact=artifact,+ note="accepted by a tracked decision record",+ )+ except AcceptanceRefusedError as exc:+ structlog.get_logger(__name__).debug(+ "adr_acceptance_refused", decision_id=rec.id, reason=str(exc)+ )++async def bulk_upsert_decisions(session: AsyncSession,repository_id: str,@@ -854,7 +954,7 @@ async def bulk_upsert_decisions(id=_new_uuid(),repository_id=repository_id,title=headline.get("title", ""),- status=headline.get("status", "proposed"),+ status=_extraction_status(headline.get("status", "proposed")),context=headline.get("context") or "",decision=headline.get("decision") or "",rationale=headline.get("rationale") or "",@@ -907,6 +1007,11 @@ async def bulk_upsert_decisions(verification=d.get("verification", "unverified"),)+ # A committed ADR that says "accepted" is the one non-human acceptance+ # the contract allows, because the document is version controlled and+ # reviewable. Recorded here, where the parsed heading is still in hand.+ await _accept_from_tracked_artifact(session, rec, headline)+# Re-derive headline confidence + verification from the FULL evidence# set (existing + just-added), so corroboration accrues across runs._rederive_headline(rec, await list_decision_evidence(session, rec.id))diff --git a/packages/core/src/repowise/core/persistence/decision_manifest.py b/packages/core/src/repowise/core/persistence/decision_manifest.pynew file mode 100644index 000000000..89e578c47--- /dev/null+++ b/packages/core/src/repowise/core/persistence/decision_manifest.py@@ -0,0 +1,266 @@+"""Round-tripping accepted decisions between the store and ``decisions.yaml``.++Export projects the accepted rows onto the tracked file. Import reads that file+back and reconciles the store to it, because the file is what a colleague's+commit changes and the store is the copy. Neither side invents authority: an+import only recognizes decisions the file already presents as accepted, and it+records the file itself as the acceptance artifact.+"""++from __future__ import annotations++import json+from pathlib import Path++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.decisions.lifecycle import STORED_CURRENCIES+from repowise.core.analysis.decisions.manifest import (+ MANIFEST_FILENAME,+ ManifestDecision,+ load_manifest,+ write_manifest,+)++from .crud.authority import (+ accepted_decision_ids,+ latest_acceptance,+ record_acceptance,+ resolve_decision_id,+)+from .models import DecisionAlias, DecisionRecord++__all__ = ["ImportOutcome", "export_manifest", "import_manifest"]+++def _stored_currency(value: str) -> str:+ """Map a manifest currency onto one an acceptance row may hold.++ ``uncheckable`` is derived from the code rather than declared, so a file+ carrying it is read as the ``active`` it was derived from.+ """+ return value if value in STORED_CURRENCIES else "active"+++def _json_list(raw: str) -> list[str]:+ try:+ parsed = json.loads(raw or "[]")+ except (TypeError, ValueError):+ return []+ return [str(v) for v in parsed] if isinstance(parsed, list) else []+++async def _aliases_for(session: AsyncSession, decision_id: str) -> list[str]:+ rows = await session.execute(+ select(DecisionAlias.alias_id).where(DecisionAlias.decision_id == decision_id)+ )+ return [r[0] for r in rows.all()]+++async def export_manifest(+ session: AsyncSession,+ repository_id: str,+ repo_path: Path | str,+ *,+ expected_raw: str | None = None,+ allow_empty: bool = False,+) -> tuple[int, bool]:+ """Write every accepted decision to ``decisions.yaml``.++ Returns the number exported and whether the file's bytes changed. Dismissed+ decisions are exported too: a withdrawn constraint is part of the record a+ reviewer needs, and dropping it would make the file re-import as though the+ withdrawal never happened.+ """+ # Read before writing: the version gate and the empty-overwrite guard both+ # live on what is already committed, and a blind write is how a rebuilt+ # store erases a colleague's file.+ if expected_raw is None:+ _, expected_raw = load_manifest(repo_path)++ accepted = await accepted_decision_ids(session, repository_id)+ if not accepted:+ return 0, write_manifest(+ repo_path, [], expected_raw=expected_raw, allow_empty=allow_empty+ )++ records = (+ (+ await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id,+ DecisionRecord.id.in_(accepted),+ )+ )+ )+ .scalars()+ .all()+ )++ entries: list[ManifestDecision] = []+ for rec in records:+ acceptance = await latest_acceptance(session, rec.id)+ if acceptance is None: # pragma: no cover - accepted set says otherwise+ continue+ entries.append(+ ManifestDecision(+ id=rec.id,+ title=rec.title,+ decision=rec.decision,+ reason=acceptance.reason,+ scope=_json_list(acceptance.scope_json),+ accepted_at=acceptance.created_at.isoformat(),+ accepted_by=acceptance.accepter,+ accepted_artifact=acceptance.artifact,+ currency=acceptance.currency,+ source=rec.source,+ evidence=_json_list(acceptance.evidence_json),+ superseded_by=rec.superseded_by or "",+ aliases=await _aliases_for(session, rec.id),+ )+ )+ changed = write_manifest(+ repo_path, entries, expected_raw=expected_raw, allow_empty=allow_empty+ )+ return len(entries), changed+++class ImportOutcome:+ """What reconciling the store against the manifest did."""++ __slots__ = ("accepted", "created", "reaffirmed", "skipped", "unchanged")++ def __init__(self) -> None:+ self.created: list[str] = []+ self.accepted: list[str] = []+ self.reaffirmed: list[str] = []+ self.unchanged: list[str] = []+ self.skipped: list[tuple[str, str]] = []++ def as_dict(self) -> dict[str, object]:+ return {+ "created": self.created,+ "accepted": self.accepted,+ "reaffirmed": self.reaffirmed,+ "unchanged": self.unchanged,+ "skipped": [{"id": i, "reason": r} for i, r in self.skipped],+ }+++def _differs(+ entry: ManifestDecision, record: DecisionRecord, acceptance: object+) -> bool:+ """Whether the file says something the store's acceptance does not."""+ return (+ entry.reason.strip() != (acceptance.reason or "").strip()+ or sorted(entry.scope) != sorted(_json_list(acceptance.scope_json))+ or _stored_currency(entry.currency) != acceptance.currency+ or entry.title != record.title+ or entry.decision != record.decision+ )+++def _apply_entry(entry: ManifestDecision, record: DecisionRecord) -> None:+ """Copy the file's version of a decision onto the stored record."""+ record.title = entry.title+ record.decision = entry.decision+ record.rationale = entry.reason+ record.affected_files_json = json.dumps(sorted(entry.scope))+ record.superseded_by = entry.superseded_by or None+++async def import_manifest(+ session: AsyncSession,+ repository_id: str,+ repo_path: Path | str,+ *,+ dry_run: bool = False,+) -> ImportOutcome:+ """Reconcile the store to ``decisions.yaml``.++ The file is the authority, so a decision present there and absent here is+ created and accepted, with the file as the acceptance artifact: it is+ version controlled and reviewable, which is the only reason a non-human+ accepter is allowed at all, and an entry the file does not present as+ accepted is skipped rather than guessed at. An entry that differs from the+ store is re-accepted from the file, because the difference is somebody's+ commit; an entry the file no longer holds is left alone, since a missing+ line is as likely a bad merge as a deliberate removal.+ """+ outcome = ImportOutcome()+ entries, _ = load_manifest(repo_path)+ artifact = f".repowise/{MANIFEST_FILENAME}"++ for entry in entries:+ if not entry.id or not entry.title:+ outcome.skipped.append((entry.id or "<no id>", "missing id or title"))+ continue+ if not entry.reason.strip():+ outcome.skipped.append((entry.id, "no reason recorded"))+ continue+ if not [s for s in entry.scope if s.strip()]:+ outcome.skipped.append((entry.id, "no scope recorded"))+ continue++ resolved = await resolve_decision_id(session, entry.id)+ record = await session.get(DecisionRecord, resolved) if resolved else None+ if record is not None and record.repository_id != repository_id:+ # One store can hold several repositories. An id that resolves into+ # a different one is not this file's decision.+ outcome.skipped.append((entry.id, "belongs to another repository"))+ continue++ if record is not None:+ acceptance = await latest_acceptance(session, record.id)+ if acceptance is not None:+ if not _differs(entry, record, acceptance):+ outcome.unchanged.append(entry.id)+ continue+ # The file changed: a colleague edited the reason, corrected+ # the scope, or withdrew the decision. Their edit is the+ # authority, so it is re-accepted rather than left disagreeing+ # with the store — appended to the log, so the history of both+ # acceptances survives.+ outcome.reaffirmed.append(entry.id)+ if dry_run:+ continue+ _apply_entry(entry, record)++ if record is None:+ outcome.created.append(entry.id)+ if dry_run:+ continue+ record = DecisionRecord(+ id=entry.id,+ repository_id=repository_id,+ title=entry.title,+ decision=entry.decision,+ rationale=entry.reason,+ source=entry.source or "cli",+ affected_files_json=json.dumps(sorted(entry.scope)),+ evidence_commits_json=json.dumps(sorted(entry.evidence)),+ superseded_by=entry.superseded_by or None,+ confidence=1.0,+ verification="unverified",+ )+ session.add(record)+ await session.flush()+ elif entry.id not in outcome.reaffirmed:+ outcome.accepted.append(entry.id)+ if dry_run:+ continue++ await record_acceptance(+ session,+ record,+ action="accepted",+ currency=_stored_currency(entry.currency),+ reason=entry.reason,+ scope=sorted(entry.scope),+ evidence=sorted(entry.evidence) or [artifact],+ accepter=entry.accepted_by,+ artifact=entry.accepted_artifact or artifact,+ note="imported from the tracked manifest",+ )+ return outcomediff --git a/packages/core/src/repowise/core/persistence/decision_migration.py b/packages/core/src/repowise/core/persistence/decision_migration.pynew file mode 100644index 000000000..61b99f6b4--- /dev/null+++ b/packages/core/src/repowise/core/persistence/decision_migration.py@@ -0,0 +1,396 @@+"""Classifying legacy decision rows as candidates or decisions.++A runtime repair rather than an Alembic step, following the rule this repository+already learned: a data fix that lives in a migration and a data fix that lives+in the code eventually disagree, and only one of them runs on an existing store.++The classification is deliberately conservative. Before the entity split a row+could reach ``active`` by being seen in two sessions, with no person involved.+Those rows govern today, they are in the agent's standing-decisions block, and+almost none of them can show an acceptance event. Demoting them is the point:+authority the user did not grant should never have been authority. What the+migration owes them is an exact account of what it did and why, which is what+:func:`plan_migration` produces before anything is written.+"""++from __future__ import annotations++import json+import re+from collections import Counter, defaultdict+from dataclasses import dataclass, field++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.decisions.lifecycle import currency_for_legacy_status++from .crud.authority import (+ AcceptanceRefusedError,+ accepted_decision_ids,+ record_acceptance,+ upsert_candidate_meta,+)+from .models import DecisionCandidateMeta, DecisionRecord++__all__ = [+ "MigrationPlan",+ "RowPlan",+ "apply_migration",+ "plan_json",+ "plan_migration",+ "render_plan",+]++#: Sources whose rows a person authored directly. A ``cli`` row exists because+#: somebody typed it, and an ``adr`` row because somebody committed the document+#: it was parsed from, so both carry their own acceptance evidence. Nothing else+#: does: every other source is an inference over text written for another+#: purpose.+_SELF_ACCEPTING_SOURCES: frozenset[str] = frozenset({"cli", "adr"})++#: Statuses that record a retirement somebody performed. The migration keeps+#: them: reclassifying one as an open candidate would undo the retirement.+_RETIRED_STATUSES: frozenset[str] = frozenset({"dismissed", "deprecated", "superseded"})+++@dataclass(slots=True)+class RowPlan:+ """What the migration will do with one legacy row, and why."""++ decision_id: str+ title: str+ status: str+ source: str+ outcome: str # decision | candidate | tombstone | already_migrated+ reason: str+ review_state: str = "open"+ duplicate_of: str | None = None+++@dataclass(slots=True)+class MigrationPlan:+ """The full account of a store's legacy rows."""++ rows: list[RowPlan] = field(default_factory=list)+ duplicate_clusters: dict[str, list[str]] = field(default_factory=dict)++ def counts(self) -> dict[str, int]:+ return dict(Counter(r.outcome for r in self.rows))++ def by_outcome(self, outcome: str) -> list[RowPlan]:+ return [r for r in self.rows if r.outcome == outcome]++ def as_dict(self) -> dict[str, object]:+ return {+ "total": len(self.rows),+ "counts": self.counts(),+ "duplicate_clusters": self.duplicate_clusters,+ "rows": [+ {+ "id": r.decision_id,+ "title": r.title,+ "status": r.status,+ "source": r.source,+ "outcome": r.outcome,+ "reason": r.reason,+ "review_state": r.review_state,+ "duplicate_of": r.duplicate_of,+ }+ for r in self.rows+ ],+ }+++def _normalize_title(title: str) -> str:+ """The staging store's normalization, so clusters agree with promotion.++ Exact and re-extraction duplicates only. Two rows whose titles differ by+ punctuation are the same extraction seen twice; two rows that merely mean+ something similar are not, and merging those is a judgement no migration+ gets to make.+ """+ return re.sub(r"\s+", " ", re.sub(r"[^a-z0-9 ]", "", title.lower())).strip()+++def _has_scope(rec: DecisionRecord) -> bool:+ return rec.affected_files_json not in ("", "[]") or rec.affected_modules_json not in (+ "",+ "[]",+ )+++async def plan_migration(+ session: AsyncSession, repository_id: str+) -> MigrationPlan:+ """Classify every legacy row without writing anything.++ Four outcomes, and every row gets exactly one:++ - ``already_migrated``: an acceptance row exists, so nothing to decide.+ - ``tombstone``: dismissed, deprecated or superseded. Keeps that status.+ - ``decision``: a person or a tracked document authored it *and* it carries+ the reason, scope and evidence acceptance requires.+ - ``candidate``: everything else, including every automatically promoted+ ``active`` row.+ """+ plan = MigrationPlan()+ records = (+ (+ await session.execute(+ select(DecisionRecord)+ .where(DecisionRecord.repository_id == repository_id)+ .order_by(DecisionRecord.created_at)+ )+ )+ .scalars()+ .all()+ )+ already = await accepted_decision_ids(session, repository_id)+ reviewed = set(+ (+ await session.execute(+ select(DecisionCandidateMeta.decision_id).where(+ DecisionCandidateMeta.repository_id == repository_id,+ DecisionCandidateMeta.review_state != "open",+ )+ )+ )+ .scalars()+ .all()+ )++ by_title: dict[str, list[DecisionRecord]] = defaultdict(list)+ for rec in records:+ by_title[_normalize_title(rec.title)].append(rec)+ canonical = {+ norm: group[0].id for norm, group in by_title.items() if len(group) > 1+ }+ plan.duplicate_clusters = {+ canonical[norm]: [r.id for r in group[1:]]+ for norm, group in by_title.items()+ if len(group) > 1+ }++ for rec in records:+ norm = _normalize_title(rec.title)+ dup_of = canonical.get(norm)+ dup_of = dup_of if dup_of and dup_of != rec.id else None++ if rec.id in already:+ plan.rows.append(+ RowPlan(+ rec.id,+ rec.title,+ rec.status,+ rec.source,+ "already_migrated",+ "an acceptance event is already recorded",+ duplicate_of=dup_of,+ )+ )+ continue++ # A retirement is a review action somebody already performed. Reopening+ # it as an unreviewed candidate would put a decision the user retired+ # back in front of them asking to be accepted, so all three retired+ # statuses keep their status and carry a tombstone.+ if rec.status in _RETIRED_STATUSES:+ plan.rows.append(+ RowPlan(+ rec.id,+ rec.title,+ rec.status,+ rec.source,+ "tombstone",+ f"{rec.status} before the split; the retirement is preserved",+ review_state="dismissed",+ duplicate_of=dup_of,+ )+ )+ continue++ if rec.id in reviewed:+ plan.rows.append(+ RowPlan(+ rec.id,+ rec.title,+ rec.status,+ rec.source,+ "already_migrated",+ "already reviewed; its review state is left alone",+ duplicate_of=dup_of,+ )+ )+ continue++ currency = currency_for_legacy_status(rec.status)+ if currency is None:+ plan.rows.append(+ RowPlan(+ rec.id,+ rec.title,+ rec.status,+ rec.source,+ "candidate",+ "never accepted: it was awaiting review",+ duplicate_of=dup_of,+ )+ )+ continue++ if rec.source not in _SELF_ACCEPTING_SOURCES:+ plan.rows.append(+ RowPlan(+ rec.id,+ rec.title,+ rec.status,+ rec.source,+ "candidate",+ f"{rec.status} by recurrence, not by a person: "+ f"a {rec.source} row carries no acceptance event",+ duplicate_of=dup_of,+ )+ )+ continue++ gaps: list[str] = []+ if not (rec.rationale.strip() or rec.decision.strip()):+ gaps.append("no rationale")+ if not _has_scope(rec):+ gaps.append("no scope")+ if gaps:+ plan.rows.append(+ RowPlan(+ rec.id,+ rec.title,+ rec.status,+ rec.source,+ "candidate",+ f"authored via {rec.source} but {' and '.join(gaps)}",+ duplicate_of=dup_of,+ )+ )+ continue++ plan.rows.append(+ RowPlan(+ rec.id,+ rec.title,+ rec.status,+ rec.source,+ "decision",+ f"authored via {rec.source}, with a reason and a scope",+ duplicate_of=dup_of,+ )+ )+ return plan+++async def apply_migration(+ session: AsyncSession, repository_id: str, *, plan: MigrationPlan | None = None+) -> MigrationPlan:+ """Write the plan. Idempotent: a second run reclassifies nothing.++ Idempotence falls out of the classification rather than being bolted on: a+ row the first run accepted lands in ``already_migrated`` on the second,+ and a candidate row already carrying its review state is rewritten to the+ same values.+ """+ plan = plan or await plan_migration(session, repository_id)+ records = {+ rec.id: rec+ for rec in (+ (+ await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id+ )+ )+ )+ .scalars()+ .all()+ )+ }++ for row in plan.rows:+ rec = records.get(row.decision_id)+ if rec is None or row.outcome == "already_migrated":+ continue+ if rec.status in _RETIRED_STATUSES and row.outcome != "decision":+ # Record the tombstone without touching the status that carries the+ # retirement.+ existed = await session.get(DecisionCandidateMeta, rec.id) is not None+ await upsert_candidate_meta(session, rec, lane=rec.source)+ meta = await session.get(DecisionCandidateMeta, rec.id)+ if meta is not None and not existed:+ meta.review_state = "dismissed"+ continue++ if row.outcome == "decision":+ try:+ await record_acceptance(+ session,+ rec,+ action="accepted",+ currency="active",+ accepter=f"migration:{rec.source}",+ note="reconstructed from a self-authored legacy record",+ )+ except AcceptanceRefusedError as exc:+ # The gap checks above and the CHECK constraints agree on all+ # four requirements, so this is a row whose evidence went+ # missing rather than one the plan misjudged. Demote it and say+ # so, instead of failing the whole migration over one record.+ row.outcome = "candidate"+ row.reason = f"acceptance refused: {exc}"+ else:+ continue++ existed = await session.get(DecisionCandidateMeta, rec.id) is not None+ await upsert_candidate_meta(session, rec, lane=rec.source)+ meta = await session.get(DecisionCandidateMeta, rec.id)+ if meta is not None:+ # Only a row this run created gets its review state set. Rerunning+ # must not walk a split or a dismissal back to unreviewed.+ if not existed:+ meta.review_state = row.review_state+ meta.scope_unresolved = not _has_scope(rec)+ # The legacy column is a projection: a candidate is not ``active``, and+ # leaving it so would keep every unmigrated reader treating it as one.+ # A tombstone keeps the status that records its retirement.+ if row.outcome == "candidate" and rec.status != "proposed":+ rec.status = "proposed"++ await session.flush()+ return plan+++def render_plan(plan: MigrationPlan, *, limit: int = 10) -> str:+ """A human-readable dry-run report."""+ counts = plan.counts()+ lines = [+ "Decision migration (dry run)",+ "",+ f" Total legacy records {len(plan.rows):>5}",+ f" Kept as decisions {counts.get('decision', 0):>5}",+ f" Reclassified as candidates {counts.get('candidate', 0):>5}",+ f" Dismissed tombstones {counts.get('tombstone', 0):>5}",+ f" Already migrated {counts.get('already_migrated', 0):>5}",+ ]+ if plan.duplicate_clusters:+ clustered = sum(len(v) for v in plan.duplicate_clusters.values())+ lines += [+ "",+ f" Duplicate clusters {len(plan.duplicate_clusters)} "+ f"covering {clustered} repeat rows (flagged, not merged)",+ ]+ reasons = Counter(r.reason for r in plan.rows if r.outcome == "candidate")+ if reasons:+ lines += ["", " Why records became candidates:"]+ lines += [f" {n:>4} {reason}" for reason, n in reasons.most_common(limit)]+ return "\n".join(lines)+++def plan_json(plan: MigrationPlan) -> str:+ return json.dumps(plan.as_dict(), indent=2)diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 16a3ba458..47dde91e4 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -16,6 +16,7 @@ from uuid import uuid4from sqlalchemy import (Boolean,+ CheckConstraint,DateTime,Float,ForeignKey,@@ -849,9 +850,12 @@ class DecisionRecord(Base):# Core contenttitle: Mapped[str] = mapped_column(Text, nullable=False)+ # Legacy currency projection, kept so readers that predate the entity split+ # keep working. Authority itself lives in ``DecisionAcceptance``: a record+ # with no acceptance row is a candidate whatever this column says.status: Mapped[str] = mapped_column(String(32), nullable=False, default="proposed"- ) # proposed | active | deprecated | superseded+ ) # proposed | active | deprecated | superseded | dismissedcontext: Mapped[str] = mapped_column(Text, nullable=False, default="")decision: Mapped[str] = mapped_column(Text, nullable=False, default="")rationale: Mapped[str] = mapped_column(Text, nullable=False, default="")@@ -1037,6 +1041,160 @@ class DecisionNodeLink(Base):)+class DecisionAcceptance(Base):+ """The event that turned a candidate into a governing decision.++ A ``DecisionRecord`` row is a *candidate* until it has one of these. That is+ the structural separation between the two entities: nothing in the record+ itself says "accepted", so a decision read is a join onto this table and a+ candidate cannot be reached through it. Recurrence, confidence and model+ verdicts write records; only an explicit action or a tracked authoritative+ artifact writes acceptances.++ Append-only. Reaffirming, superseding, dismissing and returning a decision+ to review each add a row rather than editing one, so the authority history+ survives every later action. The highest ``seq`` for a decision is its+ current authority; ``currency`` on that row is its product state.++ The CHECK constraints are the acceptance contract, enforced by the database+ rather than by whichever caller happens to be writing: a reason, a scope, an+ evidence reference, and an accepter or artifact identity.+ """++ __tablename__ = "decision_acceptances"+ __table_args__ = (+ UniqueConstraint("decision_id", "seq", name="uq_decision_acceptance_seq"),+ CheckConstraint("reason <> ''", name="ck_acceptance_reason"),+ CheckConstraint("scope_json NOT IN ('', '[]')", name="ck_acceptance_scope"),+ CheckConstraint("evidence_json NOT IN ('', '[]')", name="ck_acceptance_evidence"),+ CheckConstraint("accepter <> '' OR artifact <> ''", name="ck_acceptance_identity"),+ CheckConstraint(+ "currency IN ('active', 'needs_review', 'uncheckable', 'superseded', 'dismissed')",+ name="ck_acceptance_currency",+ ),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32),+ ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ decision_id: Mapped[str] = mapped_column(+ String(32),+ ForeignKey("decision_records.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ #: Per-decision monotone counter. Ordering by timestamp alone ties when two+ #: actions land in the same transaction, and the tie decides who governs.+ seq: Mapped[int] = mapped_column(Integer, nullable=False, default=1)+ #: accepted | reaffirmed | superseded | dismissed | returned_to_review | merged+ action: Mapped[str] = mapped_column(String(24), nullable=False, default="accepted")+ currency: Mapped[str] = mapped_column(String(16), nullable=False, default="active")+ #: The rationale, or the explicit reason a constraint has none.+ reason: Mapped[str] = mapped_column(Text, nullable=False)+ #: Scope and evidence snapshotted at acceptance time: what the accepter+ #: actually agreed to, not what a later re-extraction rewrote it into.+ scope_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ evidence_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ #: Exactly one is set. ``artifact`` is a tracked, version-controlled path,+ #: the only accepter that is not a person.+ accepter: Mapped[str] = mapped_column(Text, nullable=False, default="")+ artifact: Mapped[str] = mapped_column(Text, nullable=False, default="")+ note: Mapped[str] = mapped_column(Text, nullable=False, default="")+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+++class DecisionCandidateMeta(Base):+ """Review state for a ``DecisionRecord`` that has not been accepted.++ One row per candidate, holding what review needs and a decision does not:+ where the claim came from, how well it was grounded, whether it bundles two+ choices, and whether it has already been rejected. Split out rather than+ widened onto ``decision_records`` so the two entities do not share a column+ set, and so ``review_state`` is never confused with a decision's currency.++ ``dismissed`` here is the tombstone that survives re-extraction.+ """++ __tablename__ = "decision_candidate_meta"+ __table_args__ = (+ CheckConstraint(+ "review_state IN ('open', 'accepted', 'merged', 'needs_split', 'dismissed')",+ name="ck_candidate_review_state",+ ),+ Index("ix_candidate_meta_repo_state", "repository_id", "review_state"),+ )++ decision_id: Mapped[str] = mapped_column(+ String(32),+ ForeignKey("decision_records.id", ondelete="CASCADE"),+ primary_key=True,+ )+ repository_id: Mapped[str] = mapped_column(+ String(32),+ ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ review_state: Mapped[str] = mapped_column(String(16), nullable=False, default="open")+ #: Review ordering hint, highest first. Derived, never a promotion gate.+ review_priority: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ #: The grounding verdict the extraction lane recorded, as JSON.+ grounding_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ #: Which extraction produced it, so a bad vintage can be found later.+ extractor_version: Mapped[str] = mapped_column(String(64), nullable=False, default="")+ #: The lane that raised it (``session_discovery`` and the deterministic+ #: miner both store ``source="session"``; this is what tells them apart).+ lane: Mapped[str] = mapped_column(String(32), nullable=False, default="")+ needs_split: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ scope_unresolved: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ #: Set when review folded this candidate into another record.+ merged_into: Mapped[str | None] = mapped_column(String(32), nullable=True)+ dismissed_reason: Mapped[str] = mapped_column(Text, nullable=False, default="")+ first_seen: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ last_seen: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+++class DecisionAlias(Base):+ """A retired decision id that still resolves to a live record.++ Merging a candidate into a decision, and superseding one decision with+ another, both leave an id in circulation: in a manifest someone committed,+ in an agent's notes, in a link. The alias keeps it resolving instead of+ failing to find anything, which is what makes merge and supersede safe to+ perform.+ """++ __tablename__ = "decision_aliases"++ alias_id: Mapped[str] = mapped_column(String(32), primary_key=True)+ repository_id: Mapped[str] = mapped_column(+ String(32),+ ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ decision_id: Mapped[str] = mapped_column(+ String(32),+ ForeignKey("decision_records.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ reason: Mapped[str] = mapped_column(String(32), nullable=False, default="merged")+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )++class Conversation(Base):"""A chat conversation for a repository."""diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 4cfcb552e..ef2534224 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -1739,6 +1739,19 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:except Exception as _rank_err:logger.debug("decision_rank_reconcile_skipped", error=str(_rank_err))+ # Classify legacy rows against the entity split. A record promoted by+ # recurrence rather than by a person becomes a candidate, which visibly+ # shrinks what governs; leaving it to an explicit command would instead+ # leave the status column and the acceptance log permanently disagreeing,+ # with half the surfaces reading each. Idempotent, and it never reopens a+ # review action somebody already performed.+ try:+ from repowise.core.persistence.decision_migration import apply_migration++ await apply_migration(session, repo_id)+ except Exception as _migrate_err:+ logger.debug("decision_entity_migration_skipped", error=str(_migrate_err))+if decision_dicts:# Reuse the run's shared vector store for semantic (paraphrase) dedup# and to make decisions searchable; title dedup still runs when None.diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.pyindex c700ae91b..bf8003f14 100644--- a/packages/core/src/repowise/core/repo_config.py+++ b/packages/core/src/repowise/core/repo_config.py@@ -8,6 +8,10 @@ from typing import AnyCONFIG_FILENAME = "config.yaml"+#: Named here rather than imported from the manifest module, which imports yaml+#: and the analysis package; this file is on the cheap config path.+MANIFEST_BASENAME = "decisions.yaml"+class RepoConfigError(ValueError):"""A repo-local ``.repowise/config.yaml`` or ``.env`` could not be parsed.@@ -256,6 +260,50 @@ def save_repo_env_key(pass+def ensure_manifest_tracked(repo_path: Path | str) -> bool:+ """Let ``.repowise/decisions.yaml`` be committed. Returns whether it changed.++ The manifest is the only thing under ``.repowise/`` meant to travel with the+ repository, and a ``.repowise/`` rule blocks it: git does not descend into an+ excluded directory, so a negation for a file inside one never fires.++ The existing rule is left in place and three anchored lines are appended+ after it. Rewriting ``.repowise/`` to ``.repowise/*`` would look equivalent+ and is not: the first has no internal slash and so matches a ``.repowise``+ directory at *any* depth, while the second is anchored to this file's own+ directory. That rewrite would un-ignore every nested ``.repowise/`` in the+ tree, which is how a fixture's session database gets committed.+ """+ from repowise.core.fsutils import atomic_write_text++ gitignore = Path(repo_path) / ".gitignore"+ if not gitignore.exists():+ return False++ # Read as bytes: text mode translates CRLF away, and the line ending is+ # exactly what has to survive here. Rewriting a CRLF .gitignore as LF turns+ # one appended rule into a whole-file diff for every contributor on the+ # platform this project mostly runs on.+ raw = gitignore.read_bytes()+ content = raw.decode("utf-8", errors="replace")+ lines = content.splitlines()+ if f"!/.repowise/{MANIFEST_BASENAME}" in {line.strip() for line in lines}:+ return False++ newline = "\r\n" if b"\r\n" in raw else "\n"+ addition = [+ "",+ "# repowise: the decisions manifest is meant to be committed",+ "!/.repowise/",+ "/.repowise/*",+ f"!/.repowise/{MANIFEST_BASENAME}",+ ]+ atomic_write_text(+ gitignore, newline.join([*lines, *addition]) + newline, newline=""+ )+ return True++def _ensure_env_gitignored(repo_path: Path | str) -> None:"""Add ``.repowise/.env`` to the repo's ``.gitignore`` if not already listed."""gitignore = Path(repo_path) / ".gitignore"diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.pyindex 5a0b3dddb..17a1cccc5 100644--- a/packages/server/src/repowise/server/routers/decisions.py+++ b/packages/server/src/repowise/server/routers/decisions.py@@ -426,7 +426,7 @@ async def create_decision(session,repository_id=repo_id,title=body.title,- status="active",+ status="proposed",context=body.context,decision=body.decision,rationale=body.rationale,@@ -438,6 +438,13 @@ 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 excreturn DecisionRecordResponse.from_orm(rec)@@ -468,6 +475,7 @@ async def patch_decision(decision_id,body.status,superseded_by=body.superseded_by,+ accepter="web",)except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from excdiff --git a/tests/unit/cli/test_augment_decision_inject.py b/tests/unit/cli/test_augment_decision_inject.pyindex d4214d030..ad7785801 100644--- a/tests/unit/cli/test_augment_decision_inject.py+++ b/tests/unit/cli/test_augment_decision_inject.py@@ -18,6 +18,7 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_enginefrom repowise.cli.commands.augment_cmd import decision_injectfrom repowise.core.persistence.database import init_dbfrom repowise.core.persistence.models import (+ DecisionAcceptance,DecisionEvidence,DecisionNodeLink,DecisionRecord,@@ -53,6 +54,23 @@ async def _build_wiki_db(repo_root: Path, decisions: list[dict], extras=None) ->evidence_file=spec["id"], # keeps the unique constraint happy))+ # Injection serves accepted decisions. A spec is accepted unless it+ # says otherwise, so an ``accepted: False`` spec is a candidate and+ # proves the hook leaves candidates out.+ if spec.get("accepted", True):+ session.add(+ DecisionAcceptance(+ repository_id=_REPO_ID,+ decision_id=spec["id"],+ seq=1,+ action="accepted",+ currency="active",+ reason=spec.get("rationale") or spec["title"],+ scope_json=json.dumps([spec["id"]]),+ evidence_json=json.dumps([spec["id"]]),+ accepter="tester",+ )+ )for node_id, link_type in spec.get("links", []):session.add(DecisionNodeLink(@@ -482,3 +500,25 @@ def test_detached_head_yields_no_branch(tmp_path, monkeypatch):files, branch = decision_inject._dirty_files_and_branch(tmp_path)assert files == ["a.py"]assert branch == ""+++async def test_a_candidate_is_never_injected(tmp_path):+ """A record with no acceptance is review material, not guidance.++ The whole point of the entity split lands here: before it, two sightings in+ two transcripts were enough to put a line in front of the agent as though a+ person had agreed to it.+ """+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "cand0001",+ "title": "Never accepted by anybody",+ "decision": "do the thing",+ "accepted": False,+ "links": [("src/app.py", "file")],+ }+ ],+ )+ assert decision_inject._edit_decision_notice(tmp_path, "src/app.py", "s1", {}) is Nonediff --git a/tests/unit/cli/test_decision_cmd.py b/tests/unit/cli/test_decision_cmd.pyindex 3c9ded505..89778b111 100644--- a/tests/unit/cli/test_decision_cmd.py+++ b/tests/unit/cli/test_decision_cmd.py@@ -41,6 +41,9 @@ def _seed_wiki_db(repo_root: Path, decisions: list[dict]) -> None:source=spec.get("source", "cli"),confidence=spec.get("confidence", 0.9),staleness_score=spec.get("staleness", 0.0),+ affected_files_json=json.dumps(+ spec.get("affected_files", ["src/app.py"])+ ),evidence_file=spec["id"],))@@ -130,20 +133,32 @@ def test_a_flag_driven_decision_lands_proposed(indexed_repo: Path) -> None:def test_decision_add_prompts_record_active(indexed_repo: Path) -> None:- """The interactive path is unchanged, including the status it writes."""- answers = "Interactive title\ncontext\nthe decision\nwhy\n\n\n\n\n"- result = CliRunner().invoke(- cli, ["decision", "add", str(indexed_repo)], input=answers- )+ """Answering the prompts is an acceptance, and a scope is part of it."""+ answers = "Interactive title\ncontext\nthe decision\nwhy\n\n\nsrc/app.py\n\n"+ result = CliRunner().invoke(cli, ["decision", "add", str(indexed_repo)], input=answers)assert result.exit_code == 0, result.output- listed = CliRunner().invoke(- cli, ["decision", "list", str(indexed_repo), "--format", "json"]- )+ listed = CliRunner().invoke(cli, ["decision", "list", str(indexed_repo), "--format", "json"])records = json.loads(listed.output)["decisions"]assert [d["status"] for d in records if d["title"] == "Interactive title"] == ["active"]+def test_decision_add_without_a_scope_stays_a_candidate(indexed_repo: Path) -> None:+ """A decision that names no files cannot be checked, so it cannot govern.++ It is kept rather than refused: eight answered questions are worth more+ than the round trip, and ``confirm --scope`` finishes the job.+ """+ answers = "Unscoped title\ncontext\nthe decision\nwhy\n\n\n\n\n"+ result = CliRunner().invoke(cli, ["decision", "add", str(indexed_repo)], input=answers)++ assert result.exit_code == 0, result.output+ assert "Stored as a candidate" in result.output+ listed = CliRunner().invoke(cli, ["decision", "list", str(indexed_repo), "--format", "json"])+ records = json.loads(listed.output)["decisions"]+ assert [d["status"] for d in records if d["title"] == "Unscoped title"] == ["proposed"]++def test_half_a_command_line_is_an_error_not_a_prompt(indexed_repo: Path) -> None:"""--title alone must not fall through to the prompts.@@ -252,7 +267,7 @@ def test_decision_confirm_promotes_proposed(indexed_repo: Path) -> None:result = CliRunner().invoke(cli, ["decision", "confirm", "cccccccc", str(indexed_repo)])assert result.exit_code == 0, result.output- assert "confirmed (active)" in result.output+ assert "accepted (governing)" in result.outputshown = CliRunner().invoke(cli, ["decision", "show", "cccccccc", str(indexed_repo)])assert shown.exit_code == 0, shown.output@@ -347,7 +362,7 @@ class TestTheLifecycleIsDrivableByAnAgent:assert result.exit_code == 0, result.outputpayload = json.loads(result.output)- assert payload == {"id": "c0ffee01", "status": "active", "action": "confirmed"}+ assert payload == {"id": "c0ffee01", "status": "active", "action": "accepted"}def test_dismiss_does_not_prompt_under_json(self, indexed_repo: Path):_seed_wiki_db(indexed_repo, [{"id": "c0ffee02", "title": "T", "status": "proposed"}])@@ -413,3 +428,56 @@ class TestTheLifecycleIsDrivableByAnAgent:assert result.exit_code == 0, result.outputassert json.loads(result.output)["status"] == "deprecated"+++def test_confirm_refuses_a_candidate_with_nothing_to_accept(indexed_repo: Path) -> None:+ """Acceptance needs a reason, a scope and an evidence reference.++ Storing a blank one would make the acceptance log say a person agreed to+ something it cannot state, which is the pre-split promotion under a new+ name. The refusal is machine-readable, because a scripted review has to be+ able to tell it apart from a crash.+ """+ _seed_wiki_db(+ indexed_repo,+ [+ {+ "id": "badbadbadbadbadbadbadbadbadbadba",+ "title": "Nothing to go on",+ "status": "proposed",+ "rationale": "",+ "decision": "",+ "affected_files": [],+ }+ ],+ )++ result = CliRunner().invoke(+ cli, ["decision", "confirm", "badbadba", str(indexed_repo), "--format", "json"]+ )++ assert result.exit_code == 1, result.output+ payload = json.loads(result.output)+ assert payload["error"] == "acceptance_refused"+ assert any("scope" in blocker for blocker in payload["blockers"])++ # And it is acceptable once the missing parts are supplied.+ fixed = CliRunner().invoke(+ cli,+ [+ "decision",+ "confirm",+ "badbadba",+ str(indexed_repo),+ "--reason",+ "Because the alternative was measured slower",+ "--scope",+ "src/app.py",+ "--evidence",+ "docs/notes.md",+ "--format",+ "json",+ ],+ )+ assert fixed.exit_code == 0, fixed.output+ assert json.loads(fixed.output)["status"] == "active"diff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.pyindex 3b2629112..a97a39d91 100644--- a/tests/unit/generation/test_editor_file_fetcher.py+++ b/tests/unit/generation/test_editor_file_fetcher.py@@ -130,6 +130,11 @@ async def _add_git_meta(async def _add_decision(session, repo_id, title, status="active", rationale="Some reason"):+ """Add a record, accepting it when the caller wants one that governs.++ The generated block serves accepted decisions, so a fixture that only sets+ ``status`` would be seeding candidates and asserting on decisions.+ """dr = DecisionRecord(repository_id=repo_id,title=title,@@ -138,10 +143,16 @@ async def _add_decision(session, repo_id, title, status="active", rationale="Somdecision="Decided to use X",context="Context here",source="inline_marker",+ affected_files_json='["src/app.py"]',+ evidence_file="src/app.py",staleness_score=0.0,)session.add(dr)await session.flush()+ if status == "active":+ from repowise.core.persistence.crud.authority import accept_decision++ await accept_decision(session, dr, accepter="tester")return dr@@ -349,6 +360,23 @@ async def test_fetch_active_decisions_only(session, repo, tmp_path):assert "Old choice" not in titles+async def test_a_candidate_never_reaches_the_generated_block(session, repo, tmp_path):+ """An agent reads that block as instructions, so acceptance is the gate.++ A record whose status column says ``active`` but which nobody accepted is+ still a candidate, and the block is where treating one as guidance does the+ most damage.+ """+ await _add_decision(session, repo.id, "Never accepted", status="proposed")+ unaccepted = await _add_decision(session, repo.id, "Looks active", status="proposed")+ unaccepted.status = "active"+ await session.commit()++ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()++ assert [d.title for d in data.decisions] == []++async def test_fetch_avg_confidence(session, repo, tmp_path):await _add_page(session, repo.id, "file_page:src/a.py", "file_page", "src/a.py", "content")# Update confidence manuallydiff --git a/tests/unit/persistence/helpers.py b/tests/unit/persistence/helpers.pyindex 255ca7304..12515f6bc 100644--- a/tests/unit/persistence/helpers.py+++ b/tests/unit/persistence/helpers.py@@ -41,3 +41,19 @@ async def insert_repo(session, **overrides) -> Repository:repo = await upsert_repository(session, **make_repo_kwargs(**overrides))await session.commit()return repo+++async def accept(session, decision_id: str, *, accepter: str = "tester"):+ """Accept a stored record, the way the product does.++ Tests that need a *governing* decision must go through this rather than+ handing ``status="active"`` to ``bulk_upsert_decisions``: extraction cannot+ create authority, so a setup that fabricates one is testing a state the+ product can no longer reach.+ """+ from repowise.core.persistence.crud.authority import accept_decision+ from repowise.core.persistence.models import DecisionRecord++ record = await session.get(DecisionRecord, decision_id)+ await accept_decision(session, record, accepter=accepter)+ return recorddiff --git a/tests/unit/persistence/test_decision_authority.py b/tests/unit/persistence/test_decision_authority.pynew file mode 100644index 000000000..e420b391f--- /dev/null+++ b/tests/unit/persistence/test_decision_authority.py@@ -0,0 +1,375 @@+"""Acceptance is the only thing that makes a record govern.++The contract under test is the entity split itself: a ``DecisionRecord`` with no+row in ``decision_acceptances`` is a candidate, no matter what its status column+says, and nothing but an explicit action or a tracked artifact writes one.+"""++from __future__ import annotations++import json++import pytest+from sqlalchemy import select+from sqlalchemy.exc import IntegrityError++from repowise.core.persistence.crud import bulk_upsert_decisions, update_decision_status+from repowise.core.persistence.crud.authority import (+ AcceptanceRefusedError,+ accept_decision,+ accepted_decision_ids,+ accepted_predicate,+ current_currency,+ dismiss_candidate,+ is_accepted,+ latest_acceptance,+ list_candidates,+ merge_candidate,+ reaffirm_decision,+ request_split,+ resolve_decision_id,+ return_to_review,+ supersede_decision,+)+from repowise.core.persistence.decision_graph import get_decision_edges+from repowise.core.persistence.models import DecisionAcceptance, DecisionRecord+from tests.unit.persistence.helpers import insert_repo+++def _dict(title: str, **overrides) -> dict:+ base = {+ "title": title,+ "decision": f"{title}: do the thing",+ "rationale": "because the alternative was measured slower",+ "source": "session",+ "status": "proposed",+ "affected_files": ["src/app.py"],+ "evidence_file": "src/app.py",+ "confidence": 0.7,+ "verification": "exact",+ "source_quote": f"{title}: do the thing",+ }+ base.update(overrides)+ return base+++async def _seed(session, repo_id: str, *titles: str) -> list[DecisionRecord]:+ await bulk_upsert_decisions(session, repo_id, [_dict(t) for t in titles])+ rows = (+ (+ await session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo_id)+ )+ )+ .scalars()+ .all()+ )+ by_title = {r.title: r for r in rows}+ return [by_title[t] for t in titles]+++# ---------------------------------------------------------------------------+# The separation itself+# ---------------------------------------------------------------------------+++async def test_extraction_produces_candidates_not_decisions(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Use Redis")++ assert not await is_accepted(async_session, rec.id)+ assert await accepted_decision_ids(async_session, repo.id) == set()+ assert await current_currency(async_session, rec) is None+++async def test_a_governance_read_cannot_reach_a_candidate(async_session):+ """The predicate every governing surface adds is a join, not a status test."""+ repo = await insert_repo(async_session)+ candidate, decision = await _seed(async_session, repo.id, "Candidate", "Decision")+ await accept_decision(async_session, decision, accepter="tester")++ # A candidate forced to look accepted by the legacy column is still a+ # candidate, because the column is a projection and not the authority.+ candidate.status = "active"+ await async_session.flush()++ governing = (+ (+ await async_session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repo.id, accepted_predicate()+ )+ )+ )+ .scalars()+ .all()+ )+ assert [r.id for r in governing] == [decision.id]+++async def test_acceptance_requires_reason_scope_evidence_and_identity(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(+ async_session,+ repo.id,+ "Bare",+ )+ rec.rationale = ""+ rec.decision = ""+ rec.affected_files_json = "[]"+ rec.affected_modules_json = "[]"+ rec.evidence_commits_json = "[]"+ rec.evidence_file = None+ await async_session.flush()++ with pytest.raises(AcceptanceRefusedError) as refusal:+ await accept_decision(async_session, rec, accepter="tester")+ assert len(refusal.value.blockers) == 3++ with pytest.raises(AcceptanceRefusedError):+ await accept_decision(+ async_session, rec, reason="r", scope=["src/a.py"], evidence=["c"]+ ) # no accepter and no artifact++ acceptance = await accept_decision(+ async_session,+ rec,+ accepter="tester",+ reason="a reason",+ scope=["src/a.py"],+ evidence=["deadbeef"],+ )+ assert acceptance.currency == "active"+ assert rec.status == "active"+++async def test_the_database_refuses_an_acceptance_with_no_scope(async_session):+ """The contract is a constraint, not only a Python check.++ A caller reaching past the domain function still cannot store an acceptance+ that says nothing about what it governs.+ """+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Constrained")++ async_session.add(+ DecisionAcceptance(+ repository_id=repo.id,+ decision_id=rec.id,+ seq=1,+ action="accepted",+ currency="active",+ reason="a reason",+ scope_json="[]",+ evidence_json='["c"]',+ accepter="tester",+ )+ )+ with pytest.raises(IntegrityError):+ await async_session.flush()+ await async_session.rollback()+++async def test_the_database_refuses_an_anonymous_acceptance(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Anonymous")++ async_session.add(+ DecisionAcceptance(+ repository_id=repo.id,+ decision_id=rec.id,+ seq=1,+ action="accepted",+ currency="active",+ reason="a reason",+ scope_json='["src/a.py"]',+ evidence_json='["c"]',+ accepter="",+ artifact="",+ )+ )+ with pytest.raises(IntegrityError):+ await async_session.flush()+ await async_session.rollback()+++# ---------------------------------------------------------------------------+# The review actions+# ---------------------------------------------------------------------------+++async def test_the_acceptance_log_appends_rather_than_overwrites(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Reviewed twice")++ await accept_decision(async_session, rec, accepter="tester")+ await return_to_review(async_session, rec, accepter="tester")+ await reaffirm_decision(async_session, rec, accepter="tester")++ rows = (+ (+ await async_session.execute(+ select(DecisionAcceptance)+ .where(DecisionAcceptance.decision_id == rec.id)+ .order_by(DecisionAcceptance.seq)+ )+ )+ .scalars()+ .all()+ )+ assert [(r.seq, r.action) for r in rows] == [+ (1, "accepted"),+ (2, "returned_to_review"),+ (3, "reaffirmed"),+ ]+ assert (await latest_acceptance(async_session, rec.id)).currency == "active"+++async def test_returning_to_review_keeps_the_record_a_decision(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Sent back")+ await accept_decision(async_session, rec, accepter="tester")++ await return_to_review(async_session, rec, accepter="tester")++ assert await is_accepted(async_session, rec.id)+ assert await current_currency(async_session, rec) == "needs_review"+++async def test_dismissing_an_accepted_decision_withdraws_its_authority(async_session):+ """Otherwise the manifest keeps exporting it as governing."""+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Withdrawn")+ await accept_decision(async_session, rec, accepter="tester")++ await dismiss_candidate(async_session, rec, reason="no longer true", accepter="tester")++ assert (await latest_acceptance(async_session, rec.id)).currency == "dismissed"+ assert await accepted_decision_ids(+ async_session, repo.id, governing_only=True+ ) == set()+++async def test_superseding_writes_an_explicit_edge_and_keeps_the_id_resolving(+ async_session,+):+ repo = await insert_repo(async_session)+ old, new = await _seed(async_session, repo.id, "Old way", "New way")+ await accept_decision(async_session, old, accepter="tester")+ await accept_decision(async_session, new, accepter="tester")++ await supersede_decision(async_session, old, successor_id=new.id, accepter="tester")++ edges = await get_decision_edges(async_session, new.id)+ assert [(e.kind, e.dst_decision_id) for e in edges] == [("supersedes", old.id)]+ assert old.superseded_by == new.id+ assert (await latest_acceptance(async_session, old.id)).currency == "superseded"+ # A superseded decision still resolves to itself: its history is what you+ # asked for when you named it.+ assert await resolve_decision_id(async_session, old.id) == old.id+++async def test_merging_folds_a_candidate_and_redirects_its_id(async_session):+ repo = await insert_repo(async_session)+ candidate, target = await _seed(async_session, repo.id, "Duplicate", "Canonical")+ await accept_decision(async_session, target, accepter="tester")++ await merge_candidate(async_session, candidate, into_id=target.id, accepter="tester")++ assert await resolve_decision_id(async_session, candidate.id) == target.id+ # And the folded id cannot be accepted a second time under its own name.+ with pytest.raises(AcceptanceRefusedError):+ await accept_decision(async_session, candidate, accepter="tester")+++async def test_merging_refuses_a_candidate_target_and_an_accepted_source(async_session):+ repo = await insert_repo(async_session)+ a, b = await _seed(async_session, repo.id, "A", "B")++ with pytest.raises(ValueError, match="candidate"):+ await merge_candidate(async_session, a, into_id=b.id, accepter="tester")++ await accept_decision(async_session, a, accepter="tester")+ await accept_decision(async_session, b, accepter="tester")+ with pytest.raises(ValueError, match="Supersede"):+ await merge_candidate(async_session, a, into_id=b.id, accepter="tester")+++async def test_a_dismissed_candidate_survives_re_extraction(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Rejected idea")+ await dismiss_candidate(async_session, rec, reason="not a real decision")++ await bulk_upsert_decisions(async_session, repo.id, [_dict("Rejected idea")])++ refreshed = await async_session.get(DecisionRecord, rec.id)+ assert refreshed.status == "dismissed"+ assert not await is_accepted(async_session, rec.id)+ open_candidates = await list_candidates(async_session, repo.id, review_state="open")+ assert rec.id not in {r.id for r, _ in open_candidates}+++async def test_a_split_request_never_splits_anything(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Two choices in one")++ await request_split(async_session, rec, reason="bundles caching and auth")++ rows = await list_candidates(async_session, repo.id, review_state="needs_split")+ assert [r.id for r, _ in rows] == [rec.id]+ assert rows[0][1].needs_split is True+ # Still exactly one record: machines flag, people split.+ all_rows = (+ (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ )+ .scalars()+ .all()+ )+ assert len(all_rows) == 1+++# ---------------------------------------------------------------------------+# The status column stays a projection+# ---------------------------------------------------------------------------+++async def test_update_decision_status_to_active_records_an_acceptance(async_session):+ """The web surface and the CLI must agree about what made a record govern."""+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Via the API")++ await update_decision_status(async_session, rec.id, "active", accepter="web")++ acceptance = await latest_acceptance(async_session, rec.id)+ assert acceptance is not None and acceptance.accepter == "web"+++async def test_update_decision_status_refuses_what_acceptance_refuses(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Unscoped")+ rec.affected_files_json = "[]"+ rec.affected_modules_json = "[]"+ await async_session.flush()++ with pytest.raises(ValueError, match="scope"):+ await update_decision_status(async_session, rec.id, "active", accepter="web")+++async def test_effective_currency_reads_the_code_not_only_the_log(async_session):+ repo = await insert_repo(async_session)+ (rec,) = await _seed(async_session, repo.id, "Moved on")+ await accept_decision(async_session, rec, accepter="tester")++ assert await current_currency(async_session, rec) == "active"++ rec.staleness_score = 0.9+ await async_session.flush()+ assert await current_currency(async_session, rec) == "needs_review"++ rec.affected_files_json = json.dumps([])+ rec.affected_modules_json = json.dumps([])+ await async_session.flush()+ assert await current_currency(async_session, rec) == "uncheckable"diff --git a/tests/unit/persistence/test_decision_evidence.py b/tests/unit/persistence/test_decision_evidence.pyindex 2a04df131..4a7dad7d5 100644--- a/tests/unit/persistence/test_decision_evidence.py+++ b/tests/unit/persistence/test_decision_evidence.py@@ -6,6 +6,7 @@ from sqlalchemy import selectfrom repowise.core.analysis.decision_provenance import compute_confidence, rank_for_sourcefrom repowise.core.persistence.crud import bulk_upsert_decisions, list_decision_evidence+from repowise.core.persistence.crud.authority import latest_acceptancefrom repowise.core.persistence.models import DecisionRecordfrom tests.unit.persistence.helpers import insert_repo@@ -18,6 +19,9 @@ def _adr_dict(title="Use PostgreSQL for storage"):"source": "adr","status": "active","evidence_file": "docs/adr/0001-postgres.md",+ # A committed ADR is a tracked authoritative artifact, so it can accept+ # its own decision — but only if it says what the decision governs.+ "affected_files": ["src/storage/db.py"],"confidence": 0.9,"verification": "exact","source_quote": "Use PostgreSQL as the primary datastore",@@ -66,6 +70,13 @@ async def test_two_sources_merge_into_one_record_with_two_evidence_rows(async_seassert rec.decision == "Use PostgreSQL as the primary datastore"assert rec.status == "active"+ # ``active`` is a projection of an acceptance, never a status extraction+ # wrote on its own: the ADR file is recorded as the accepter.+ acceptance = await latest_acceptance(async_session, rec.id)+ assert acceptance is not None+ assert acceptance.artifact == "docs/adr/0001-postgres.md"+ assert acceptance.accepter == ""+# Strongest evidence verification wins; confidence reflects corroboration.assert rec.verification == "exact"# Two corroborating sources score strictly above the same decision backed@@ -120,3 +131,23 @@ async def test_distinct_decisions_stay_separate(async_session):)rows = await _decision_rows(async_session, repo.id)assert len(rows) == 2+++async def test_scopeless_adr_stays_a_candidate(async_session):+ """An ADR that names no code cannot be accepted, so it does not govern.++ Acceptance requires a scope, and the ADR is the accepter here; a document+ that says what to do but not where it applies has not said enough to bind+ future work, and reading it as ``active`` would put it in front of an agent+ as an instruction nobody can check.+ """+ repo = await insert_repo(async_session)+ scopeless = _adr_dict()+ scopeless.pop("affected_files")++ await bulk_upsert_decisions(async_session, repo.id, [scopeless])++ rows = await _decision_rows(async_session, repo.id)+ assert len(rows) == 1+ assert rows[0].status == "proposed"+ assert await latest_acceptance(async_session, rows[0].id) is Nonediff --git a/tests/unit/persistence/test_decision_evolution_update.py b/tests/unit/persistence/test_decision_evolution_update.pyindex df0ba3287..8230d523c 100644--- a/tests/unit/persistence/test_decision_evolution_update.py+++ b/tests/unit/persistence/test_decision_evolution_update.py@@ -20,7 +20,7 @@ from repowise.core.analysis.decision_evolution import (supersession_confidence,)from repowise.core.persistence.crud import bulk_upsert_decisions, get_decision-from tests.unit.persistence.helpers import insert_repo+from tests.unit.persistence.helpers import accept, insert_repo# ---------------------------------------------------------------------------# Pure heuristics@@ -102,7 +102,7 @@ async def _seed_decision(session, repo_id: str) -> str:"decision": "use MySQL as the primary datastore","rationale": "","source": "inline_marker",- "status": "active",+ "status": "proposed","affected_files": ["src/db.py"],"evidence_file": "src/db.py","confidence": 0.6,@@ -111,6 +111,7 @@ async def _seed_decision(session, repo_id: str) -> str:}],)+ await accept(session, ids[0])return ids[0]diff --git a/tests/unit/persistence/test_decision_manifest.py b/tests/unit/persistence/test_decision_manifest.pynew file mode 100644index 000000000..2ff62dced--- /dev/null+++ b/tests/unit/persistence/test_decision_manifest.py@@ -0,0 +1,290 @@+"""``.repowise/decisions.yaml`` is the tracked source of truth for decisions.++What matters here is that the file and the store cannot drift silently: the+render is deterministic, the round trip is lossless, an empty store does not+overwrite a committed file, and a colleague's edit wins on import.+"""++from __future__ import annotations++from dataclasses import replace++import pytest+from sqlalchemy import select++from repowise.core.analysis.decisions.manifest import (+ MANIFEST_VERSION,+ ManifestConflictError,+ ManifestDecision,+ load_manifest,+ manifest_path,+ render_manifest,+ write_manifest,+)+from repowise.core.persistence.crud import bulk_upsert_decisions+from repowise.core.persistence.crud.authority import (+ accept_decision,+ dismiss_candidate,+ latest_acceptance,+)+from repowise.core.persistence.decision_manifest import export_manifest, import_manifest+from repowise.core.persistence.models import DecisionRecord+from tests.unit.persistence.helpers import insert_repo+++def _entry(decision_id: str, **overrides) -> ManifestDecision:+ fields = {+ "id": decision_id,+ "title": f"Decision {decision_id}",+ "decision": "do the thing",+ "reason": "because the alternative was slower",+ "scope": ["src/b.py", "src/a.py"],+ "accepted_at": "2026-09-01T00:00:00+00:00",+ "accepted_by": "tester",+ "evidence": ["deadbeef"],+ }+ fields.update(overrides)+ return ManifestDecision(**fields)+++def _dict(title: str, **overrides) -> dict:+ base = {+ "title": title,+ "decision": f"{title}: do the thing",+ "rationale": "because the alternative was measured slower",+ "source": "session",+ "status": "proposed",+ "affected_files": ["src/app.py"],+ "evidence_file": "src/app.py",+ "confidence": 0.7,+ "verification": "exact",+ "source_quote": f"{title}: do the thing",+ }+ base.update(overrides)+ return base+++# ---------------------------------------------------------------------------+# Rendering+# ---------------------------------------------------------------------------+++def test_the_render_does_not_depend_on_input_order(tmp_path):+ """Two stores holding the same decisions produce the same bytes.++ Ordering by id rather than by acceptance time is what keeps a re-accepted+ decision from moving and turning a one-line change into a whole-file diff.+ """+ a, b, c = _entry("aaa"), _entry("bbb"), _entry("ccc")+ assert render_manifest([c, a, b]) == render_manifest([a, b, c])+++def test_the_round_trip_is_lossless(tmp_path):+ entries = [_entry("aaa", superseded_by="bbb", aliases=["zzz"]), _entry("bbb")]+ write_manifest(tmp_path, entries)++ parsed, _ = load_manifest(tmp_path)++ assert render_manifest(parsed) == render_manifest(entries)+ assert parsed[0].scope == sorted(entries[0].scope)+ assert parsed[0].aliases == ["zzz"]+++def test_an_unchanged_render_is_not_rewritten(tmp_path):+ entries = [_entry("aaa")]+ assert write_manifest(tmp_path, entries) is True+ assert write_manifest(tmp_path, entries) is False+++def test_a_concurrent_change_is_refused_rather_than_clobbered(tmp_path):+ write_manifest(tmp_path, [_entry("aaa")])+ _, raw = load_manifest(tmp_path)++ manifest_path(tmp_path).write_text(+ render_manifest([_entry("aaa"), _entry("bbb")]), encoding="utf-8"+ )++ with pytest.raises(ManifestConflictError, match="changed since"):+ write_manifest(tmp_path, [_entry("aaa", reason="mine")], expected_raw=raw)+++def test_an_empty_store_does_not_erase_a_committed_file(tmp_path):+ """The recovery path is deleting the index; it must not delete the file."""+ write_manifest(tmp_path, [_entry("aaa")])++ with pytest.raises(ManifestConflictError, match="Import it first"):+ write_manifest(tmp_path, [])++ assert load_manifest(tmp_path)[0]+ assert write_manifest(tmp_path, [], allow_empty=True) is True+++def test_a_newer_format_is_refused_rather_than_downgraded(tmp_path):+ path = manifest_path(tmp_path)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f"version: {MANIFEST_VERSION + 1}\ndecisions: []\n", encoding="utf-8")++ with pytest.raises(ManifestConflictError, match="newer repowise"):+ load_manifest(tmp_path)+++def test_a_malformed_version_is_a_conflict_not_a_traceback(tmp_path):+ path = manifest_path(tmp_path)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("version: one\ndecisions: []\n", encoding="utf-8")++ with pytest.raises(ManifestConflictError, match="non-numeric"):+ load_manifest(tmp_path)+++# ---------------------------------------------------------------------------+# Store <-> file+# ---------------------------------------------------------------------------+++async def test_only_accepted_decisions_are_exported(async_session, tmp_path):+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(+ async_session, repo.id, [_dict("Accepted"), _dict("Candidate")]+ )+ rows = {+ r.title: r+ for r in (+ (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ )+ .scalars()+ .all()+ )+ }+ await accept_decision(async_session, rows["Accepted"], accepter="tester")++ count, changed = await export_manifest(async_session, repo.id, tmp_path)++ assert (count, changed) == (1, True)+ entries, _ = load_manifest(tmp_path)+ assert [e.title for e in entries] == ["Accepted"]+ assert entries[0].accepted_by == "tester"+++async def test_export_import_export_is_a_fixed_point(async_session, tmp_path):+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(async_session, repo.id, [_dict("Round trip")])+ rec = (+ (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ )+ .scalars()+ .one()+ )+ await accept_decision(async_session, rec, accepter="tester")++ await export_manifest(async_session, repo.id, tmp_path)+ first = manifest_path(tmp_path).read_text(encoding="utf-8")++ outcome = await import_manifest(async_session, repo.id, tmp_path)+ assert outcome.unchanged == [rec.id]++ await export_manifest(async_session, repo.id, tmp_path)+ assert manifest_path(tmp_path).read_text(encoding="utf-8") == first+++async def test_the_file_creates_and_accepts_a_decision_the_store_lacks(+ async_session, tmp_path+):+ """A colleague's commit is the authority; the store is the copy."""+ repo = await insert_repo(async_session)+ write_manifest(tmp_path, [_entry("f" * 32)])++ outcome = await import_manifest(async_session, repo.id, tmp_path)++ assert outcome.created == ["f" * 32]+ rec = await async_session.get(DecisionRecord, "f" * 32)+ assert rec is not None and rec.status == "active"+ acceptance = await latest_acceptance(async_session, rec.id)+ assert acceptance.artifact == ".repowise/decisions.yaml"+++async def test_a_dry_run_import_writes_nothing(async_session, tmp_path):+ repo = await insert_repo(async_session)+ write_manifest(tmp_path, [_entry("f" * 32)])++ outcome = await import_manifest(async_session, repo.id, tmp_path, dry_run=True)++ assert outcome.created == ["f" * 32]+ assert await async_session.get(DecisionRecord, "f" * 32) is None+++async def test_an_edited_entry_is_reconciled_rather_than_reported_unchanged(+ async_session, tmp_path+):+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(async_session, repo.id, [_dict("Edited elsewhere")])+ rec = (+ (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ )+ .scalars()+ .one()+ )+ await accept_decision(async_session, rec, accepter="tester")+ await export_manifest(async_session, repo.id, tmp_path)++ entries, _ = load_manifest(tmp_path)+ write_manifest(+ tmp_path,+ [+ replace(+ entries[0],+ reason="a colleague corrected this",+ scope=["src/corrected.py"],+ )+ ],+ )++ outcome = await import_manifest(async_session, repo.id, tmp_path)++ assert outcome.reaffirmed == [rec.id]+ acceptance = await latest_acceptance(async_session, rec.id)+ assert acceptance.reason == "a colleague corrected this"+ assert acceptance.scope_json == '["src/corrected.py"]'+++async def test_an_entry_missing_a_reason_is_skipped_not_guessed_at(+ async_session, tmp_path+):+ repo = await insert_repo(async_session)+ write_manifest(tmp_path, [_entry("f" * 32, reason="")])++ outcome = await import_manifest(async_session, repo.id, tmp_path)++ assert outcome.skipped == [("f" * 32, "no reason recorded")]+ assert await async_session.get(DecisionRecord, "f" * 32) is None+++async def test_a_withdrawn_decision_exports_as_withdrawn(async_session, tmp_path):+ """Otherwise a colleague's import would undo the dismissal."""+ repo = await insert_repo(async_session)+ await bulk_upsert_decisions(async_session, repo.id, [_dict("Withdrawn")])+ rec = (+ (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ )+ .scalars()+ .one()+ )+ await accept_decision(async_session, rec, accepter="tester")+ await dismiss_candidate(async_session, rec, accepter="tester")++ await export_manifest(async_session, repo.id, tmp_path)++ entries, _ = load_manifest(tmp_path)+ assert [e.currency for e in entries] == ["dismissed"]diff --git a/tests/unit/persistence/test_decision_migration.py b/tests/unit/persistence/test_decision_migration.pynew file mode 100644index 000000000..51e0d1d86--- /dev/null+++ b/tests/unit/persistence/test_decision_migration.py@@ -0,0 +1,212 @@+"""Classifying pre-split decision rows.++The store this migrates from could not tell a decision from a candidate, so the+question every test here asks is the same one: does this row carry an acceptance+event somebody performed, or does it only carry a status a machine wrote?+"""++from __future__ import annotations++from sqlalchemy import select++from repowise.core.persistence.crud.authority import (+ accept_decision,+ is_accepted,+ request_split,+)+from repowise.core.persistence.decision_migration import (+ apply_migration,+ plan_migration,+ render_plan,+)+from repowise.core.persistence.models import DecisionCandidateMeta, DecisionRecord+from tests.unit.persistence.helpers import insert_repo+++async def _legacy(+ session,+ repo_id: str,+ title: str,+ *,+ status: str = "active",+ source: str = "session",+ rationale: str = "because it was measured faster",+ files: list[str] | None = None,+) -> DecisionRecord:+ """Insert a row shaped the way the pre-split store held them.++ Deliberately built by hand rather than through the write path: the point is+ a store nothing in this build could produce any more.+ """+ rec = DecisionRecord(+ repository_id=repo_id,+ title=title,+ decision=f"{title}: do the thing",+ rationale=rationale,+ status=status,+ source=source,+ affected_files_json='["src/app.py"]' if files is None else f"{files!r}".replace("'", '"'),+ evidence_file="src/app.py",+ confidence=0.84,+ )+ session.add(rec)+ await session.flush()+ return rec+++async def _plan_for(session, repo_id, decision_id):+ plan = await plan_migration(session, repo_id)+ return next(r for r in plan.rows if r.decision_id == decision_id)+++async def test_an_automatically_promoted_row_becomes_a_candidate(async_session):+ """Recurrence promoted these; nobody accepted them."""+ repo = await insert_repo(async_session)+ rec = await _legacy(async_session, repo.id, "Promoted by recurrence")++ row = await _plan_for(async_session, repo.id, rec.id)++ assert row.outcome == "candidate"+ assert "not by a person" in row.reason+++async def test_a_proposal_becomes_a_candidate(async_session):+ repo = await insert_repo(async_session)+ rec = await _legacy(async_session, repo.id, "Awaiting review", status="proposed")++ row = await _plan_for(async_session, repo.id, rec.id)++ assert row.outcome == "candidate"+ assert row.reason == "never accepted: it was awaiting review"+++async def test_a_self_authored_row_keeps_its_authority(async_session):+ """A ``cli`` row exists because somebody typed it."""+ repo = await insert_repo(async_session)+ rec = await _legacy(async_session, repo.id, "Typed by hand", source="cli")++ row = await _plan_for(async_session, repo.id, rec.id)+ assert row.outcome == "decision"++ await apply_migration(async_session, repo.id)+ assert await is_accepted(async_session, rec.id)+++async def test_a_self_authored_row_missing_its_parts_is_still_demoted(async_session):+ repo = await insert_repo(async_session)+ rec = await _legacy(+ async_session, repo.id, "Typed but empty", source="cli", rationale="", files=[]+ )+ rec.decision = ""+ await async_session.flush()++ row = await _plan_for(async_session, repo.id, rec.id)++ assert row.outcome == "candidate"+ assert "no rationale" in row.reason and "no scope" in row.reason+++async def test_a_retirement_is_preserved_rather_than_reopened(async_session):+ """Reopening one would put a decision the user retired back in the queue."""+ repo = await insert_repo(async_session)+ dismissed = await _legacy(async_session, repo.id, "Rejected", status="dismissed")+ deprecated = await _legacy(async_session, repo.id, "Retired", status="deprecated")+ superseded = await _legacy(async_session, repo.id, "Replaced", status="superseded")++ await apply_migration(async_session, repo.id)++ for rec, status in (+ (dismissed, "dismissed"),+ (deprecated, "deprecated"),+ (superseded, "superseded"),+ ):+ refreshed = await async_session.get(DecisionRecord, rec.id)+ assert refreshed.status == status+ meta = await async_session.get(DecisionCandidateMeta, rec.id)+ assert meta.review_state == "dismissed"+++async def test_apply_is_idempotent(async_session):+ repo = await insert_repo(async_session)+ await _legacy(async_session, repo.id, "One")+ await _legacy(async_session, repo.id, "Two", source="cli")+ await _legacy(async_session, repo.id, "Three", status="dismissed")++ first = await apply_migration(async_session, repo.id)+ second = await apply_migration(async_session, repo.id)++ assert first.counts() == {"candidate": 1, "decision": 1, "tombstone": 1}+ assert second.counts() == {"candidate": 1, "already_migrated": 1, "tombstone": 1}+ rows = (+ (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ )+ .scalars()+ .all()+ )+ assert sorted(r.status for r in rows) == ["active", "dismissed", "proposed"]+++async def test_rerunning_does_not_reopen_a_review_action(async_session):+ """A split request survives the next index run."""+ repo = await insert_repo(async_session)+ rec = await _legacy(async_session, repo.id, "Bundles two choices")+ await apply_migration(async_session, repo.id)+ await request_split(async_session, rec, reason="two choices")++ await apply_migration(async_session, repo.id)++ meta = await async_session.get(DecisionCandidateMeta, rec.id)+ assert meta.review_state == "needs_split"+++async def test_an_accepted_record_is_left_alone(async_session):+ repo = await insert_repo(async_session)+ rec = await _legacy(async_session, repo.id, "Already accepted", status="proposed")+ await accept_decision(async_session, rec, accepter="tester")++ row = await _plan_for(async_session, repo.id, rec.id)++ assert row.outcome == "already_migrated"+ await apply_migration(async_session, repo.id)+ assert (await async_session.get(DecisionRecord, rec.id)).status == "active"+++async def test_duplicates_are_clustered_but_never_merged(async_session):+ """Exact re-extractions only, and flagged rather than folded together."""+ repo = await insert_repo(async_session)+ first = await _legacy(async_session, repo.id, "Use Redis")+ second = await _legacy(async_session, repo.id, "use redis!")+ unrelated = await _legacy(async_session, repo.id, "Cache with Redis")++ plan = await plan_migration(async_session, repo.id)++ assert plan.duplicate_clusters == {first.id: [second.id]}+ assert unrelated.id not in plan.duplicate_clusters+ await apply_migration(async_session, repo.id, plan=plan)+ remaining = (+ (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ )+ .scalars()+ .all()+ )+ assert len(remaining) == 3+++async def test_the_report_accounts_for_every_row(async_session):+ repo = await insert_repo(async_session)+ await _legacy(async_session, repo.id, "One")+ await _legacy(async_session, repo.id, "Two", status="proposed")+ await _legacy(async_session, repo.id, "Three", source="cli")++ plan = await plan_migration(async_session, repo.id)+ report = render_plan(plan)++ assert sum(plan.counts().values()) == len(plan.rows) == 3+ assert "Total legacy records" in report+ assert all(row.reason for row in plan.rows)diff --git a/tests/unit/persistence/test_decision_source_rank_backfill.py b/tests/unit/persistence/test_decision_source_rank_backfill.pyindex 971c81b25..5e99b7c0a 100644--- a/tests/unit/persistence/test_decision_source_rank_backfill.py+++ b/tests/unit/persistence/test_decision_source_rank_backfill.py@@ -21,7 +21,7 @@ from repowise.core.persistence.crud import (reconcile_source_ranks,)from repowise.core.persistence.models import DecisionEvidence, DecisionRecord-from tests.unit.persistence.helpers import insert_repo+from tests.unit.persistence.helpers import accept, insert_repo_TITLE = "Use PostgreSQL for storage"@@ -205,9 +205,9 @@ def test_persist_wires_both_repairs():async def test_purge_keeps_what_a_human_confirmed(async_session):- """Only ``proposed`` rows drain. An active record survives its source's removal."""+ """Only ``proposed`` rows drain. An accepted record survives its source's removal."""repo = await insert_repo(async_session)- await bulk_upsert_decisions(+ ids = await bulk_upsert_decisions(async_session,repo.id,[@@ -215,13 +215,18 @@ async def test_purge_keeps_what_a_human_confirmed(async_session):"title": "Kept because someone confirmed it","decision": "mined from a changelog, then confirmed by a human","source": "changelog",- "status": "active",+ "status": "proposed",+ "affected_files": ["src/changelog.py"],+ "evidence_file": "CHANGELOG.md","confidence": 0.6,"verification": "exact","source_quote": "mined from a changelog, then confirmed by a human",}],)+ # Accepting is what makes it survive; the row lands ``proposed`` whatever+ # the extraction dict claimed.+ await accept(async_session, ids[0])assert await purge_proposed_decisions_by_source(async_session, repo.id, "changelog") == 0rec = await _record(async_session, repo.id)diff --git a/tests/unit/persistence/test_decision_sticky_status.py b/tests/unit/persistence/test_decision_sticky_status.pyindex 1a3c41554..a5fda8f34 100644--- a/tests/unit/persistence/test_decision_sticky_status.py+++ b/tests/unit/persistence/test_decision_sticky_status.py@@ -21,6 +21,7 @@ from repowise.core.persistence.crud import (purge_proposed_decisions_by_source,update_decision_status,)+from repowise.core.persistence.crud.authority import latest_acceptancefrom repowise.core.persistence.models import DecisionEvidence, DecisionRecordfrom tests.unit.persistence.helpers import insert_repo@@ -32,6 +33,9 @@ def _decision(title: str, *, source: str = "changelog", status: str = "proposed""rationale": "","source": source,"status": status,+ # A scope, so these records can be accepted: acceptance is what the+ # sticky-status guard has to protect, and a record with none cannot be.+ "affected_files": [f"{title.lower().replace(' ', '_')}.py"],"evidence_file": f"{title.lower().replace(' ', '_')}.py","confidence": 0.6,"verification": "exact",@@ -80,17 +84,38 @@ async def test_confirmed_decision_not_walked_back_to_proposed(async_session):assert rec.status == "active"-async def test_proposed_still_upgrades_to_active(async_session):+async def test_accepted_adr_promotes_a_proposal(async_session):+ """A committed ADR is the one artifact that can accept without a person.++ It still has to meet the acceptance contract, so the ADR must say what the+ decision governs; the resulting ``active`` is a projection of the recorded+ acceptance rather than a status extraction wrote for itself.+ """repo = await insert_repo(async_session)await bulk_upsert_decisions(async_session, repo.id, [_decision("Use Redis")])- # An ADR marked accepted arrives for the same decision.- await bulk_upsert_decisions(- async_session, repo.id, [_decision("Use Redis", source="adr", status="active")]- )+ adr = _decision("Use Redis", source="adr", status="active")+ adr["affected_files"] = ["src/cache.py"]+ adr["evidence_file"] = "docs/adr/0002-redis.md"+ await bulk_upsert_decisions(async_session, repo.id, [adr])rec = await _only_row(async_session, repo.id)assert rec.status == "active"+ acceptance = await latest_acceptance(async_session, rec.id)+ assert acceptance is not None and acceptance.artifact == "docs/adr/0002-redis.md"+++async def test_extraction_alone_never_reaches_active(async_session):+ """The same ADR without a scope stays a candidate."""+ repo = await insert_repo(async_session)+ adr = _decision("Use Redis", source="adr", status="active")+ adr["evidence_file"] = "docs/adr/0002-redis.md"+ adr.pop("affected_files")+ await bulk_upsert_decisions(async_session, repo.id, [adr])++ rec = await _only_row(async_session, repo.id)+ assert rec.status == "proposed"+ assert await latest_acceptance(async_session, rec.id) is Noneasync def test_update_decision_status_accepts_dismissed(async_session):diff --git a/tests/unit/persistence/test_decision_supersession.py b/tests/unit/persistence/test_decision_supersession.pyindex c1ca7a94f..8bb2f3944 100644--- a/tests/unit/persistence/test_decision_supersession.py+++ b/tests/unit/persistence/test_decision_supersession.py@@ -23,7 +23,7 @@ from repowise.core.analysis.decisions import evolutionfrom repowise.core.persistence.crud import bulk_upsert_decisions, get_decisionfrom repowise.core.persistence.decision_graph import get_decision_edgesfrom repowise.core.persistence.vector_store import InMemoryVectorStore-from tests.unit.persistence.helpers import insert_repo+from tests.unit.persistence.helpers import accept, insert_repo@pytest.fixture@@ -65,13 +65,27 @@ class _TopicEmbedder:return out+async def _seed_active(session, repo_id, decisions, **kwargs):+ """Upsert decisions and accept each one.++ The detector only considers accepted decisions, and extraction can no+ longer produce one: a dict carrying ``status: "active"`` lands as a+ proposal, so a setup that relied on it was seeding candidates and asserting+ on decisions.+ """+ ids = await bulk_upsert_decisions(session, repo_id, decisions, **kwargs)+ for decision_id in ids:+ await accept(session, decision_id)+ return ids++def _dec(title: str, decision: str, *, files: list[str]) -> dict:return {"title": title,"decision": decision,"rationale": "","source": "inline_marker",- "status": "active",+ "status": "proposed","affected_files": files,"evidence_file": files[0],"confidence": 0.6,@@ -90,7 +104,7 @@ async def test_reversal_creates_supersedes_edge_and_autoflips(async_session, enarepo = await insert_repo(async_session)store = InMemoryVectorStore(_TopicEmbedder())- old_ids = await bulk_upsert_decisions(+ old_ids = await _seed_active(async_session,repo.id,[@@ -102,7 +116,7 @@ async def test_reversal_creates_supersedes_edge_and_autoflips(async_session, ena],vector_store=store,)- new_ids = await bulk_upsert_decisions(+ new_ids = await _seed_active(async_session,repo.id,[@@ -142,7 +156,7 @@ async def test_two_active_conflicts_without_reversal(async_session, enable_3b):repo = await insert_repo(async_session)store = InMemoryVectorStore(_TopicEmbedder())- ids_a = await bulk_upsert_decisions(+ ids_a = await _seed_active(async_session,repo.id,[@@ -154,7 +168,7 @@ async def test_two_active_conflicts_without_reversal(async_session, enable_3b):],vector_store=store,)- ids_b = await bulk_upsert_decisions(+ ids_b = await _seed_active(async_session,repo.id,[@@ -184,7 +198,7 @@ async def test_related_but_compatible_pair_gets_no_edge(async_session, enable_3brepo = await insert_repo(async_session)store = InMemoryVectorStore(_TopicEmbedder())- ids_a = await bulk_upsert_decisions(+ ids_a = await _seed_active(async_session,repo.id,[@@ -198,7 +212,7 @@ async def test_related_but_compatible_pair_gets_no_edge(async_session, enable_3b)# Same related band (jwt/session axes), but no opposing verb / reversal and# too few shared content tokens → not a contradiction.- ids_b = await bulk_upsert_decisions(+ ids_b = await _seed_active(async_session,repo.id,[@@ -233,13 +247,13 @@ async def test_disabled_detector_writes_nothing(async_session):repo = await insert_repo(async_session)store = InMemoryVectorStore(_TopicEmbedder())- old_ids = await bulk_upsert_decisions(+ old_ids = await _seed_active(async_session,repo.id,[_dec("Use sessions for authentication", "use server-side sessions", files=["a.py"])],vector_store=store,)- new_ids = await bulk_upsert_decisions(+ new_ids = await _seed_active(async_session,repo.id,[_dec("Adopt JWT authentication", "replace sessions with JWT tokens", files=["a.py"])],@@ -261,7 +275,7 @@ async def test_disabled_detector_writes_nothing(async_session):async def test_no_store_is_a_noop(async_session, enable_3b):repo = await insert_repo(async_session)- ids = await bulk_upsert_decisions(+ ids = await _seed_active(async_session,repo.id,[_dec("Use sessions", "use sessions", files=["a.py"])],diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex 458075f2b..fbcd4fe54 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -308,6 +308,9 @@ def test_base_includes_all_models():"decision_records","decision_evidence","decision_edges",+ "decision_acceptances",+ "decision_candidate_meta",+ "decision_aliases","decision_node_links","conversations","chat_messages",diff --git a/tests/unit/server/test_decisions_counts.py b/tests/unit/server/test_decisions_counts.pyindex f4cde5787..7a0595469 100644--- a/tests/unit/server/test_decisions_counts.py+++ b/tests/unit/server/test_decisions_counts.py@@ -34,8 +34,15 @@ async def _seed(decision="dec",rationale="why",source=source,+ affected_files=["src/app.py"],+ evidence_file="src/app.py",confidence=confidence,)+ # ``active`` is a projection of an acceptance, so a seed that wants a+ # governing decision has to perform one; a bare upsert lands a+ # candidate however the status argument reads.+ if status == "active":+ await crud.accept_decision(session, rec, accepter="tester")return rec.iddiff --git a/tests/unit/server/test_decisions_patch.py b/tests/unit/server/test_decisions_patch.pyindex a09bdca7d..cd709765e 100644--- a/tests/unit/server/test_decisions_patch.py+++ b/tests/unit/server/test_decisions_patch.py@@ -28,6 +28,9 @@ async def _seed_decision(session_factory, repo_id: str) -> str:affected_files=["packages/core/src/repowise/core/persistence/database.py"],source="cli",)+ # ``active`` is a projection of an acceptance, so the seed has to+ # perform one; extraction and a bare upsert both land a candidate.+ await crud.accept_decision(session, rec, accepter="tester")return rec.iddiff --git a/tests/unit/test_manifest_gitignore.py b/tests/unit/test_manifest_gitignore.pynew file mode 100644index 000000000..c48369c36--- /dev/null+++ b/tests/unit/test_manifest_gitignore.py@@ -0,0 +1,91 @@+"""Making ``.repowise/decisions.yaml`` committable without un-ignoring the rest.++``.repowise/`` and ``.repowise/*`` look interchangeable and are not: the first+has no internal slash, so git matches it at any depth, while the second is+anchored to the ``.gitignore``'s own directory. Rewriting one into the other+would un-ignore every nested ``.repowise/`` in the tree, which in this+repository means committing a fixture's session database.+"""++from __future__ import annotations++import subprocess++import pytest++from repowise.core.repo_config import ensure_manifest_tracked+++def _git(repo, *args) -> subprocess.CompletedProcess:+ return subprocess.run(+ ["git", *args], cwd=repo, capture_output=True, text=True, check=False+ )+++def repo(tmp_path):+ _git(tmp_path, "init", "-q")+ for rel in (".repowise", "pkg/.repowise"):+ (tmp_path / rel).mkdir(parents=True)+ (tmp_path / rel / "wiki.db").write_text("x", encoding="utf-8")+ (tmp_path / ".repowise" / "decisions.yaml").write_text("version: 1\n", encoding="utf-8")+ return tmp_path+++def _ignored(repo, rel: str) -> bool:+ return _git(repo, "check-ignore", "-q", rel).returncode == 0+++def test_the_manifest_becomes_committable(repo):+ (repo / ".gitignore").write_text(".repowise/\n", encoding="utf-8")++ assert ensure_manifest_tracked(repo) is True++ assert not _ignored(repo, ".repowise/decisions.yaml")+ assert _ignored(repo, ".repowise/wiki.db")+++def test_a_nested_repowise_directory_stays_ignored(repo):+ (repo / ".gitignore").write_text(".repowise/\n", encoding="utf-8")++ ensure_manifest_tracked(repo)++ assert _ignored(repo, "pkg/.repowise/wiki.db")+++def test_it_is_idempotent(repo):+ (repo / ".gitignore").write_text(".repowise/\n", encoding="utf-8")++ assert ensure_manifest_tracked(repo) is True+ after_first = (repo / ".gitignore").read_text(encoding="utf-8")+ assert ensure_manifest_tracked(repo) is False+ assert (repo / ".gitignore").read_text(encoding="utf-8") == after_first+++def test_unrelated_rules_survive(repo):+ (repo / ".gitignore").write_text(+ "# build output\nnode_modules/\n.repowise/\n*.log\n", encoding="utf-8"+ )++ ensure_manifest_tracked(repo)++ content = (repo / ".gitignore").read_text(encoding="utf-8")+ for line in ("# build output", "node_modules/", ".repowise/", "*.log"):+ assert line in content.splitlines()+++def test_a_crlf_gitignore_is_not_rewritten_as_lf(repo):+ """One appended rule must not become a whole-file diff on Windows."""+ (repo / ".gitignore").write_bytes(b"node_modules/\r\n.repowise/\r\n")++ ensure_manifest_tracked(repo)++ raw = (repo / ".gitignore").read_bytes()+ assert b"\r\n" in raw+ assert b"\n" not in raw.replace(b"\r\n", b"")+++def test_a_repo_without_a_gitignore_is_left_alone(tmp_path):+ """Creating one would take over ignoring decisions this tool does not own."""+ assert ensure_manifest_tracked(tmp_path) is False+ assert not (tmp_path / ".gitignore").exists()