Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(decisions): a review queue that leads with work you can finish (#2073)

Raghav Chamadiya801d55e7c48a
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index cb9c0080f..a2542a318 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -162,7 +162,7 @@ partition the repository, so the counts add up and no record is in two of them:
| Lane | What is in it |
|------|---------------|
| Active | Accepted, and still describes the code it names. These are the rules. |
-| Candidates | Never accepted. Governs nothing, reaches no agent. Carries the evidence quote it was drawn from, so it can be accepted or dismissed from the row. |
+| Candidates | Never accepted. Governs nothing, reaches no agent. Carries the evidence quote it was drawn from, so it can be accepted or dismissed from the row. Ordered so the ones the acceptance contract would take come first. |
| Needs review | Accepted, but the files it names have moved. Still binds. |
| Uncheckable | Accepted, but names no file or module, so nothing can check it against the code and no agent editing a file will be given it. |
| History | Accepted and then withdrawn, superseded or dismissed. |
@@ -175,6 +175,22 @@ also carries a `currency` field; a record with no `currency` is a candidate.
The lane is applied before the page is cut, so a page of a lane is a page of
that lane.
+A candidate carries a review row, written where it is captured and refreshed
+for every open candidate on each index. It records which lane raised it, the
+version that extracted it, whether the lane saw the candidate bundling more
+than one choice, and whether the record names any scope at all. It also carries
+the review priority the Candidates lane and `repowise decision candidates`
+order on, which is the acceptance contract's verdict as of the last index and
+nothing else: a reviewer meets the candidates they can finish first, and
+confidence and recency break the ties. Re-extraction refreshes those signals
+but never the review state, so a dismissal or a split request survives the next
+index.
+
+A store indexed before the row existed has candidates without one. Until the
+next index writes them a row they rank as unjudged, alongside the ones the
+contract refused, and `repowise decision status` counts them so the gap is
+visible rather than silent.
+
Accepting from the UI goes through the same acceptance contract as
`repowise decision confirm`, so a candidate missing a reason, a scope or an
evidence reference has its Accept disabled with the gap named beside it rather
@@ -201,8 +217,9 @@ repowise decision health
`repowise decision health` scores governance. `repowise decision status` reports
capture: the effective policy and preset, every source with the reason it made
-no call, what each has captured and when, the review lanes and the age of the
-unreviewed backlog, the staging queues, and the model spend booked to decision
+no call, what each has captured and when, the review lanes, how much of the
+unreviewed backlog is ready to accept against how much is blocked, the age of
+that backlog, the staging queues, and the model spend booked to decision
extraction.
Nothing records a capture run. The extraction report and the broad lane's
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 8b85d5124..c2e949ee1 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -948,10 +948,17 @@ repowise decision llm --on|--off [PATH] # all decision-extraction mode
| `--reason TEXT` | On `dismiss`: why it was tombstoned. |
| `--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. |
+| `--lane NAME` | On `candidates`: only candidates raised by that extraction lane (`pr`, `session`, `session_discovery`, `comment`, `git_archaeology`, `adr`, `inline_marker`, `cli`). Unrelated to the review lanes the Decisions page splits on. |
| `--apply` | On `migrate`: write the plan. Without it the command reports and writes nothing. |
| `--dry-run` | On `import`: report and write nothing. |
+`candidates` is a review queue, so it leads with the candidates the acceptance
+contract would take, as judged at the last index, and puts the rest below them.
+Its `Acceptable` column is either `yes` or the same blockers `confirm` would
+refuse with, so the work you can finish and the work waiting on somebody is
+separated before you start. Under `--format json` each row carries a `blockers`
+array.
+
`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
@@ -1008,7 +1015,8 @@ into five lanes over the acceptance join.
**Reporting on capture:** `repowise decision status` answers what the sources
actually did, in one screen: the effective policy and preset, every source with
its state and the reason it made no call, what each one has captured and when,
-the five review lanes, the age of the unreviewed backlog, the staging queues,
+the five review lanes, how much of the unreviewed backlog a reviewer can accept
+today against how much is blocked, the age of that backlog, the staging queues,
and the model spend booked to decision extraction.
Nothing records a capture run, so every figure is derived from a durable trace
diff --git a/packages/cli/src/repowise/cli/commands/decision_review_cmd.py b/packages/cli/src/repowise/cli/commands/decision_review_cmd.py
index 1bccfa3aa..11fd9b493 100644
--- a/packages/cli/src/repowise/cli/commands/decision_review_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_review_cmd.py
@@ -114,20 +114,30 @@ def migrate_command(path: str | None, apply_: bool, limit: int, fmt: str) -> Non
default="open",
show_default=True,
)
[email protected]("--lane", default=None, help="Only candidates raised by this lane.")
+ "--lane", default=None, help="Only candidates raised by this extraction lane."
+)
@click.option("--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."""
+ """List records awaiting review. These do not govern anything.
+
+ Acceptable candidates come first, so the top of the list is work a reviewer
+ can finish. The rest name what has to be filled in before `confirm` will
+ take them.
+ """
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
+ from repowise.core.persistence.crud.authority import (
+ list_candidates,
+ record_blockers,
+ )
engine, sf = await _open(repo_path)
try:
@@ -149,6 +159,7 @@ def candidates_command(
"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 "",
+ "blockers": record_blockers(rec),
}
for rec, meta in rows
]
@@ -163,16 +174,18 @@ def candidates_command(
console.print("[dim]No candidates in this state.[/dim]")
return
table = Table(title=f"Candidates ({state})")
- for column in ("ID", "Title", "Source", "Conf", "State"):
+ for column in ("ID", "Title", "Source", "Conf", "State", "Acceptable"):
table.add_column(column)
for row in rows:
title = row["title"] + (" [yellow](split?)[/yellow]" if row["needs_split"] else "")
+ blockers = row["blockers"]
table.add_row(
row["id"][:8],
title,
row["source"],
f"{row['confidence']:.2f}",
row["review_state"],
+ ("[red]" + "; ".join(blockers) + "[/red]") if blockers else "[green]yes[/green]",
)
console.print(table)
console.print(
@@ -443,6 +456,15 @@ def _render_status(report: dict) -> None:
f" [dim]{review['unreviewed']} awaiting review · oldest "
f"{review['oldest_age_days']:.0f}d · median {review['median_age_days']:.0f}d[/dim]"
)
+ console.print(
+ f" [dim]{review['acceptable']} ready to accept · {review['blocked']} blocked; "
+ "`repowise decision candidates` names why[/dim]"
+ )
+ if review["no_review_row"]:
+ console.print(
+ f" [dim]{review['no_review_row']} candidates carry no review row yet, "
+ "so they rank as unjudged until the next index.[/dim]"
+ )
backlog = report["backlog"]
if backlog["available"]:
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index 701685264..d6731193f 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -158,6 +158,10 @@ class ExtractedDecision:
# each extractor, consumed by the substring gate, then cleared before
# persistence (the persistence layer ignores unknown dict keys anyway).
source_text: str = ""
+ # ``source`` alone cannot separate the two session lanes. Blank and False
+ # mean the lane said nothing, not that it said no.
+ lane: str = ""
+ needs_split: bool = False
class DecisionSourceError(RuntimeError):
diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
index 1a123a130..9a70868e5 100644
--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
@@ -160,6 +160,11 @@ class AcceptanceRequirement:
self_authored: bool = False
+#: Named because the review row's ``scope_unresolved`` flag is this exact
+#: verdict, and re-deriving it would be a second opinion about scope.
+NO_SCOPE_BLOCKER = "no scope: name the files or modules it governs"
+
+
def acceptance_blockers(req: AcceptanceRequirement) -> list[str]:
"""Return the reasons *req* cannot become an acceptance, empty if it can.
@@ -171,7 +176,7 @@ def acceptance_blockers(req: AcceptanceRequirement) -> 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")
+ blockers.append(NO_SCOPE_BLOCKER)
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():
diff --git a/packages/core/src/repowise/core/analysis/decisions/status.py b/packages/core/src/repowise/core/analysis/decisions/status.py
index 4f8ccc0e1..2e8f0a13c 100644
--- a/packages/core/src/repowise/core/analysis/decisions/status.py
+++ b/packages/core/src/repowise/core/analysis/decisions/status.py
@@ -22,6 +22,7 @@ from repowise.core.persistence.crud.authority import (
accepted_decision_ids,
candidate_predicate,
count_decisions_by_lane,
+ record_blockers,
)
from repowise.core.persistence.models import (
DecisionCandidateMeta,
@@ -109,27 +110,34 @@ async def _review(session: AsyncSession, repository_id: str) -> dict[str, Any]:
)
).all()
)
- # A candidate raised before the review table existed has no meta row, so
- # the record's own created_at is the only age it has.
- ages = (
- (
- await session.execute(
- select(DecisionRecord.created_at).where(
- DecisionRecord.repository_id == repository_id,
- candidate_predicate(),
- )
+ # Asked of the record rather than read off the stored review priority, so
+ # this and `decision candidates` cannot report different backlogs for one
+ # store. Having no review row at all is a separate count, not a blocker.
+ open_rows = (
+ await session.execute(
+ select(DecisionRecord, DecisionCandidateMeta.decision_id)
+ .outerjoin(
+ DecisionCandidateMeta,
+ DecisionCandidateMeta.decision_id == DecisionRecord.id,
+ )
+ .where(
+ DecisionRecord.repository_id == repository_id,
+ candidate_predicate(),
)
)
- .scalars()
- .all()
- )
+ ).all()
now = _now_utc()
- days = sorted(_age_days(value, now) for value in ages)
+ days = sorted(_age_days(record.created_at, now) for record, _ in open_rows)
+ acceptable = sum(1 for record, _ in open_rows if not record_blockers(record))
+ no_review_row = sum(1 for _, meta_id in open_rows if meta_id is None)
middle = len(days) // 2
return {
"states": {state: int(states.get(state, 0)) for state in CANDIDATE_REVIEW_STATES},
"unreviewed": len(days),
+ "acceptable": acceptable,
+ "blocked": len(days) - acceptable,
+ "no_review_row": no_review_row,
"oldest_age_days": days[-1] if days else 0.0,
"median_age_days": (
0.0
diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.py
index 6f28fff93..a35f702ed 100644
--- a/packages/core/src/repowise/core/persistence/crud/authority.py
+++ b/packages/core/src/repowise/core/persistence/crud/authority.py
@@ -22,6 +22,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.decisions.lifecycle import (
ACCEPTANCE_ACTIONS,
+ NO_SCOPE_BLOCKER,
STORED_CURRENCIES,
AcceptanceRequirement,
acceptance_blockers,
@@ -46,6 +47,7 @@ __all__ = [
"accepted_decision_ids",
"accepted_predicate",
"candidate_predicate",
+ "candidate_review_signals",
"count_decisions_by_lane",
"current_currency",
"decision_currencies",
@@ -56,6 +58,7 @@ __all__ = [
"merge_candidate",
"reaffirm_decision",
"record_acceptance",
+ "record_blockers",
"request_split",
"resolve_decision_id",
"return_to_review",
@@ -358,9 +361,15 @@ def _json_list(value: Any) -> list[str]:
return [str(v) for v in (value or [])]
+def _non_blank(values: list[str]) -> list[str]:
+ return [v for v in values if v and v.strip()]
+
+
def _record_scope(record: DecisionRecord) -> list[str]:
- return _json_list(record.affected_files_json) or _json_list(
- record.affected_modules_json
+ # Blank entries fall through to the modules rather than short-circuiting on
+ # them, so this agrees with the TypeScript mirror about a whitespace path.
+ return _non_blank(_json_list(record.affected_files_json)) or _non_blank(
+ _json_list(record.affected_modules_json)
)
@@ -371,6 +380,58 @@ def _record_evidence(record: DecisionRecord) -> list[str]:
return evidence
+def _first_non_blank(*values: str) -> str:
+ return next((v for v in values if v and v.strip()), "")
+
+
+def _requirement(
+ record: DecisionRecord,
+ *,
+ reason: str = "",
+ scope: list[str] | None = None,
+ evidence: list[str] | None = None,
+ accepter: str = "",
+ artifact: str = "",
+) -> AcceptanceRequirement:
+ """What the acceptance contract would be asked to take for *record*."""
+ # 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}"]
+ return AcceptanceRequirement(
+ reason=_first_non_blank(reason, record.rationale, record.decision),
+ scope=scope if scope is not None else _record_scope(record),
+ evidence=resolved_evidence,
+ accepter=accepter,
+ artifact=artifact,
+ self_authored=self_authored,
+ )
+
+
+def record_blockers(record: DecisionRecord) -> list[str]:
+ """Why the contract would refuse *record* as it stands, empty if it would not.
+
+ The accepter and artifact are what a reviewer supplies at the moment they
+ act, so this asks with an identity in hand: what is left is what a person
+ has to go and fill in first.
+ """
+ return acceptance_blockers(_requirement(record, accepter="reviewer"))
+
+
+def candidate_review_signals(record: DecisionRecord) -> tuple[float, bool]:
+ """Review ordering and the scope flag for *record*, both from the contract.
+
+ Priority is the contract's verdict and nothing else, so the queue leads
+ with candidates a reviewer can act on and leaves confidence and recency to
+ break ties.
+ """
+ blockers = acceptance_blockers(_requirement(record, accepter="reviewer"))
+ return (0.0 if blockers else 1.0), NO_SCOPE_BLOCKER in blockers
+
+
async def record_acceptance(
session: AsyncSession,
record: DecisionRecord,
@@ -397,21 +458,13 @@ async def record_acceptance(
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,
+ req = _requirement(
+ record,
+ reason=reason,
+ scope=scope,
+ evidence=evidence,
accepter=accepter,
artifact=artifact,
- self_authored=self_authored,
)
blockers = acceptance_blockers(req)
if blockers:
@@ -476,13 +529,15 @@ async def _append_acceptance(
artifact=artifact,
note=note,
)
- session.add(acceptance)
try:
- await session.flush()
+ # Savepoint-scoped: a root rollback would discard every earlier
+ # acceptance in the session, not just this attempt.
+ async with session.begin_nested():
+ session.add(acceptance)
+ await session.flush()
except IntegrityError:
if attempt == _SEQ_RETRIES - 1:
raise
- await session.rollback()
continue
return acceptance
raise RuntimeError("unreachable") # pragma: no cover
@@ -799,7 +854,9 @@ async def list_candidates(
if lane is not None:
q = q.where(DecisionCandidateMeta.lane == lane)
q = q.order_by(
- DecisionCandidateMeta.review_priority.desc().nullslast(),
+ # A candidate with no review row yet is unjudged, not lowest: it ranks
+ # with the ones the contract refused and confidence orders within.
+ func.coalesce(DecisionCandidateMeta.review_priority, 0.0).desc(),
DecisionRecord.confidence.desc(),
DecisionRecord.created_at.desc(),
).limit(limit).offset(offset)
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index bc071eb81..ced22f30d 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -15,6 +15,7 @@ import structlog
from sqlalchemy import case, delete, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core import __version__
from repowise.core.analysis.decisions.lifecycle import DECISION_STATUS_ORDER
from repowise.core.analysis.decisions.provenance import (
SOURCE_RANK,
@@ -24,6 +25,7 @@ from repowise.core.analysis.decisions.provenance import (
from ..decision_graph import sync_decision_node_links
from ..models import (
+ DecisionCandidateMeta,
DecisionEdge,
DecisionEvidence,
DecisionNodeLink,
@@ -31,6 +33,12 @@ from ..models import (
GitMetadata,
_now_utc,
)
+from .authority import (
+ accepted_predicate,
+ candidate_predicate,
+ candidate_review_signals,
+ upsert_candidate_meta,
+)
# ---------------------------------------------------------------------------
# DecisionRecord CRUD
@@ -241,6 +249,7 @@ async def upsert_decision(
existing.superseded_by = superseded_by
existing.updated_at = _now_utc()
await session.flush()
+ await _write_candidate_meta(session, repository_id, {}, only={existing.id})
return existing
rec = DecisionRecord(
@@ -273,6 +282,7 @@ async def upsert_decision(
)
session.add(rec)
await session.flush()
+ await _write_candidate_meta(session, repository_id, {}, only={rec.id})
return rec
@@ -340,11 +350,22 @@ async def list_decisions(
# Match exact module path in JSON array
q = q.where(DecisionRecord.affected_modules_json.contains(f'"{module}"'))
if accepted is not None:
- from .authority import accepted_predicate
-
predicate = accepted_predicate()
q = q.where(predicate if accepted else ~predicate)
- q = q.order_by(*_decision_order(sort)).limit(limit).offset(offset)
+ order = _decision_order(sort)
+ if accepted is False and sort != "recent":
+ # A candidates page is a review queue, so it leads with the rows the
+ # acceptance contract would take rather than the highest-confidence
+ # ones a reviewer cannot act on.
+ q = q.outerjoin(
+ DecisionCandidateMeta,
+ DecisionCandidateMeta.decision_id == DecisionRecord.id,
+ )
+ order = (
+ func.coalesce(DecisionCandidateMeta.review_priority, 0.0).desc(),
+ *order,
+ )
+ q = q.order_by(*order).limit(limit).offset(offset)
result = await session.execute(q)
return list(result.scalars().all())
@@ -1045,6 +1066,7 @@ async def bulk_upsert_decisions(
pending = PendingDecisionIndex() if batch_mode else None
touched_ids: list[str] = []
+ captured: dict[str, tuple[str, bool]] = {}
for norm, members in groups.items():
headline = headline_by_norm[norm]
@@ -1151,6 +1173,13 @@ async def bulk_upsert_decisions(
_rederive_headline(rec, await list_decision_evidence(session, rec.id))
rec.updated_at = _now_utc()
touched_ids.append(rec.id)
+ # Two title groups can fold onto one record, so this accumulates:
+ # the later group must not drop what the earlier one raised.
+ prior_lane, prior_split = captured.get(rec.id, ("", False))
+ captured[rec.id] = (
+ prior_lane or headline.get("lane") or "",
+ prior_split or bool(headline.get("needs_split")),
+ )
# Mirror the JSON file/module arrays into first-class decision→code
# links so the graph is traversable both directions (Phase 3A). The
@@ -1214,10 +1243,78 @@ async def bulk_upsert_decisions(
}
await upsert_decision_vectors(vector_store, items, vectors_by_text=vectors_by_text)
+ await _write_candidate_meta(session, repository_id, captured)
+
await session.flush()
return touched_ids
+async def _write_candidate_meta(
+ session: AsyncSession,
+ repository_id: str,
+ captured: dict[str, tuple[str, bool]],
+ *,
+ only: set[str] | None = None,
+) -> None:
+ """Refresh the review row every open candidate in the repository is owed.
+
+ Not only the ones this run touched: the staging store does not re-emit an
+ already-promoted decision, so a backlog would otherwise stay unjudged until
+ something happened to re-extract each record individually. The signals come
+ from the record, so an unchanged candidate costs a comparison and no write.
+ """
+ rows = (
+ await session.execute(
+ select(DecisionRecord, DecisionCandidateMeta)
+ .outerjoin(
+ DecisionCandidateMeta,
+ DecisionCandidateMeta.decision_id == DecisionRecord.id,
+ )
+ .where(
+ DecisionRecord.repository_id == repository_id,
+ candidate_predicate(),
+ *([DecisionRecord.id.in_(only)] if only is not None else []),
+ )
+ )
+ ).all()
+
+ for rec, meta in rows:
+ priority, scope_unresolved = candidate_review_signals(rec)
+ capture = captured.get(rec.id)
+ if capture is None:
+ # Not extracted this run, so the provenance is not ours to write:
+ # only the contract-derived signals are refreshed, and a row with
+ # no lane yet takes the record's own source.
+ if (
+ meta is not None
+ and meta.lane
+ and meta.review_priority == priority
+ and meta.scope_unresolved == scope_unresolved
+ ):
+ continue
+ await upsert_candidate_meta(
+ session,
+ rec,
+ lane=meta.lane if meta is not None and meta.lane else rec.source,
+ review_priority=priority,
+ scope_unresolved=scope_unresolved,
+ )
+ continue
+
+ lane, needs_split = capture
+ await upsert_candidate_meta(
+ session,
+ rec,
+ lane=lane or rec.source,
+ extractor_version=__version__,
+ review_priority=priority,
+ # Raised, never cleared: a re-extraction must not walk back a split
+ # somebody asked for.
+ needs_split=True if needs_split else None,
+ scope_unresolved=scope_unresolved,
+ )
+
+
async def purge_proposed_decisions_by_source(
session: AsyncSession,
repository_id: str,
diff --git a/packages/core/src/repowise/core/persistence/decision_migration.py b/packages/core/src/repowise/core/persistence/decision_migration.py
index 61b99f6b4..4203f4f45 100644
--- a/packages/core/src/repowise/core/persistence/decision_migration.py
+++ b/packages/core/src/repowise/core/persistence/decision_migration.py
@@ -28,6 +28,7 @@ from repowise.core.analysis.decisions.lifecycle import currency_for_legacy_statu
from .crud.authority import (
AcceptanceRefusedError,
accepted_decision_ids,
+ candidate_review_signals,
record_acceptance,
upsert_candidate_meta,
)
@@ -114,10 +115,10 @@ def _normalize_title(title: str) -> str:
def _has_scope(rec: DecisionRecord) -> bool:
- return rec.affected_files_json not in ("", "[]") or rec.affected_modules_json not in (
- "",
- "[]",
- )
+ # The acceptance contract's own answer, so the gap this plan reports and
+ # the flag the review row carries cannot disagree about one record.
+ _, scope_unresolved = candidate_review_signals(rec)
+ return not scope_unresolved
async def plan_migration(
@@ -348,14 +349,19 @@ async def apply_migration(
continue
existed = await session.get(DecisionCandidateMeta, rec.id) is not None
- await upsert_candidate_meta(session, rec, lane=rec.source)
+ priority, scope_unresolved = candidate_review_signals(rec)
+ await upsert_candidate_meta(
+ session,
+ rec,
+ lane=rec.source,
+ review_priority=priority,
+ scope_unresolved=scope_unresolved,
+ )
+ # Only a row this run created gets its review state set. Rerunning must
+ # not walk a split or a dismissal back to unreviewed.
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)
+ if meta is not None and not existed:
+ meta.review_state = row.review_state
# 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.
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 2f7c8849e..5797c7886 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -614,6 +614,9 @@ def promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[ExtractedD
recurring candidate accretes evidence without re-proposing itself.
"""
structured = row["structured"]
+ # Both session lanes store source="session"; the staging kind is what tells
+ # a reviewer which one raised the candidate.
+ lane = DISCOVERY_KIND if row.get("kind") == DISCOVERY_KIND else "session"
files = relative_files(structured.get("affected_files") or row["files"], repo_root)
modules = resolve_module_nodes(files)
confidence = compute_confidence(
@@ -635,6 +638,8 @@ def promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[ExtractedD
status="proposed",
source_quote=structured.get("source_quote", ""),
verification=structured.get("verification", "unverified"),
+ lane=lane,
+ needs_split=bool(structured.get("needs_split")),
)
for sid in sessions
]
diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.ts
index af339e40d..879c744b3 100644
--- a/packages/types/src/decisions.ts
+++ b/packages/types/src/decisions.ts
@@ -431,9 +431,12 @@ export const DECISION_PRESETS = [
] as const;
/**
- * The four checks `record_acceptance` refuses on, mirrored so a review surface
- * can disable a control it knows will be refused instead of finding out from
- * the error toast. Pinned against the Python contract by the vocabulary tests.
+ * What `record_acceptance` would refuse this record for, mirrored so a review
+ * surface can disable a control it knows will be refused instead of finding out
+ * from the error toast. Pinned against the Python contract by the vocabulary
+ * tests. The fourth check, accepter-or-artifact identity, is not here: the
+ * reviewer supplies that at the moment they act, so it is never something the
+ * record is missing. `record_blockers` on the Python side asks the same way.
*
* `selfAuthored` is the exemption for a record somebody typed: they wrote the
* claim rather than reviewing an inference, so the entry is its own provenance.
diff --git a/tests/unit/analysis/test_decision_authority_containment.py b/tests/unit/analysis/test_decision_authority_containment.py
index 70495833e..166a755b5 100644
--- a/tests/unit/analysis/test_decision_authority_containment.py
+++ b/tests/unit/analysis/test_decision_authority_containment.py
@@ -238,3 +238,23 @@ class TestSiblingCoverageCountsAcceptedRecordsOnly:
assert result["sibling_coverage"] == 0.5
assert result["score"] == "high"
+
+
+class TestPromotionCarriesTheReviewLane:
+ """``source`` is ``session`` for both lanes, so ``lane`` is what tells them apart."""
+
+ def test_the_broad_lane_names_itself(self):
+ out = promotion_decisions(_row(kind="session_discovery"), Path("."))
+
+ assert {d.lane for d in out} == {"session_discovery"}
+
+ def test_the_deterministic_lane_is_plain_session(self):
+ out = promotion_decisions(_row(kind="user_correction"), Path("."))
+
+ assert {d.lane for d in out} == {"session"}
+
+ def test_a_bundled_candidate_carries_its_split_flag(self):
+ row = _row(kind="session_discovery")
+ row["structured"]["needs_split"] = True
+
+ assert all(d.needs_split for d in promotion_decisions(row, Path(".")))
diff --git a/tests/unit/cli/test_decision_candidates_review.py b/tests/unit/cli/test_decision_candidates_review.py
new file mode 100644
index 000000000..c87f279ff
--- /dev/null
+++ b/tests/unit/cli/test_decision_candidates_review.py
@@ -0,0 +1,115 @@
+"""``repowise decision candidates`` is a queue, so it has to lead with work.
+
+Ordering by confidence put the candidates nobody could accept at the top, which
+is the opposite of what a reviewer opening the list needs.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from repowise.cli.main import cli
+from repowise.core.persistence.models import DecisionCandidateMeta
+
+from .test_decision_cmd import _REPO_ID, _seed_wiki_db
+
+
+def _add_meta(repo: Path, rows: list[dict]) -> None:
+ async def _build() -> None:
+ db_path = repo / ".repowise" / "wiki.db"
+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ for row in rows:
+ session.add(DecisionCandidateMeta(repository_id=_REPO_ID, **row))
+ await session.commit()
+ await engine.dispose()
+
+ asyncio.run(_build())
+
+
+def review_repo(tmp_path: Path) -> Path:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".repowise").mkdir()
+ _seed_wiki_db(
+ repo,
+ [
+ # High confidence, but names no scope: `confirm` will refuse it.
+ {
+ "id": "a" * 32,
+ "title": "Unscoped",
+ "status": "proposed",
+ "source": "session",
+ "confidence": 0.99,
+ "affected_files": [],
+ },
+ {
+ "id": "b" * 32,
+ "title": "Acceptable",
+ "status": "proposed",
+ "source": "session",
+ "confidence": 0.20,
+ },
+ ],
+ )
+ # The priorities capture writes for these two records: the contract refuses
+ # the unscoped one and would take the other.
+ _add_meta(
+ repo,
+ [
+ {"decision_id": "a" * 32, "review_priority": 0.0, "lane": "session_discovery"},
+ {"decision_id": "b" * 32, "review_priority": 1.0, "lane": "session"},
+ ],
+ )
+ return repo
+
+
+def _candidates(repo: Path, *args: str) -> dict:
+ result = CliRunner().invoke(
+ cli, ["decision", "candidates", str(repo), *args, "--format", "json"]
+ )
+ assert result.exit_code == 0, result.output
+ return json.loads(result.output)
+
+
+def test_acceptable_candidates_come_first(review_repo: Path) -> None:
+ """Ahead of the higher-confidence row, which is the point of the change."""
+ rows = _candidates(review_repo)["candidates"]
+
+ assert [row["title"] for row in rows] == ["Acceptable", "Unscoped"]
+ assert rows[0]["confidence"] < rows[1]["confidence"]
+ assert rows[0]["blockers"] == [] and rows[1]["blockers"]
+
+
+def test_each_row_names_what_would_refuse_it(review_repo: Path) -> None:
+ by_title = {row["title"]: row for row in _candidates(review_repo)["candidates"]}
+
+ assert by_title["Acceptable"]["blockers"] == []
+ assert by_title["Unscoped"]["blockers"] == [
+ "no scope: name the files or modules it governs"
+ ]
+
+
+def test_lane_filters_to_the_lane_that_raised_it(review_repo: Path) -> None:
+ rows = _candidates(review_repo, "--lane", "session_discovery")["candidates"]
+
+ assert [row["title"] for row in rows] == ["Unscoped"]
+
+
+def test_the_table_says_which_rows_are_acceptable(review_repo: Path) -> None:
+ result = CliRunner().invoke(cli, ["decision", "candidates", str(review_repo)])
+
+ assert result.exit_code == 0, result.output
+ lines = result.output.splitlines()
+ acceptable = next(line for line in lines if "bbbbbbbb" in line)
+ unscoped = next(line for line in lines if "aaaaaaaa" in line)
+ assert "yes" in acceptable and "no scope" not in acceptable
+ assert "no scope" in unscoped and "yes" not in unscoped
diff --git a/tests/unit/cli/test_decision_status_cmd.py b/tests/unit/cli/test_decision_status_cmd.py
index 5e5985066..f997c8130 100644
--- a/tests/unit/cli/test_decision_status_cmd.py
+++ b/tests/unit/cli/test_decision_status_cmd.py
@@ -223,3 +223,42 @@ def test_the_source_census_counts_the_same_records_the_lanes_do(status_repo: Pat
assert counted == report["lanes"]["total"] == 2
assert report["review"]["unreviewed"] == report["lanes"]["candidates"] == 2
+
+
+def test_status_separates_acceptable_from_blocked_backlog(status_repo: Path) -> None:
+ """A backlog size means little without saying how much of it is workable."""
+ review = _status(status_repo)["review"]
+
+ # All three name a scope, a rationale and an evidence file, so `confirm`
+ # would take them and `decision candidates` renders them acceptable. The
+ # two commands have to agree about that.
+ assert review["unreviewed"] == 3
+ assert review["acceptable"] == 3
+ assert review["blocked"] == 0
+ assert review["acceptable"] + review["blocked"] == review["unreviewed"]
+ # Seeded straight into the store, so no capture has written them a row.
+ assert review["no_review_row"] == 3
+
+
+def test_status_counts_a_blocked_candidate_as_blocked(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".repowise").mkdir()
+ _seed_wiki_db(
+ repo,
+ [
+ {"id": "d" * 32, "title": "Scoped", "status": "proposed", "source": "pr"},
+ {
+ "id": "e" * 32,
+ "title": "Unscoped",
+ "status": "proposed",
+ "source": "pr",
+ "affected_files": [],
+ },
+ ],
+ )
+
+ review = _status(repo)["review"]
+
+ assert review["acceptable"] == 1
+ assert review["blocked"] == 1
diff --git a/tests/unit/persistence/test_decision_authority.py b/tests/unit/persistence/test_decision_authority.py
index e420b391f..5e6ddaedd 100644
--- a/tests/unit/persistence/test_decision_authority.py
+++ b/tests/unit/persistence/test_decision_authority.py
@@ -12,6 +12,7 @@ import json
import pytest
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.persistence.crud import bulk_upsert_decisions, update_decision_status
from repowise.core.persistence.crud.authority import (
@@ -373,3 +374,36 @@ async def test_effective_currency_reads_the_code_not_only_the_log(async_session)
rec.affected_modules_json = json.dumps([])
await async_session.flush()
assert await current_currency(async_session, rec) == "uncheckable"
+
+
+async def test_seq_retry_keeps_earlier_acceptances(async_session, monkeypatch):
+ """The retry rolls back its own attempt, not the whole session.
+
+ ``decision confirm`` writes many acceptances per session, so a root-scoped
+ rollback here would discard every id reviewed before the collision.
+ """
+ repo = await insert_repo(async_session)
+ first, second = await _seed(async_session, repo.id, "First", "Second")
+ await accept_decision(async_session, first, accepter="tester")
+
+ real_flush = AsyncSession.flush
+ tripped: list[bool] = []
+
+ async def flaky(self, *args, **kwargs):
+ pending = [
+ obj
+ for obj in self.new
+ if isinstance(obj, DecisionAcceptance) and obj.decision_id == second.id
+ ]
+ if pending and not tripped:
+ tripped.append(True)
+ raise IntegrityError("seq collision", None, Exception("unique"))
+ return await real_flush(self, *args, **kwargs)
+
+ monkeypatch.setattr(AsyncSession, "flush", flaky)
+ await accept_decision(async_session, second, accepter="tester")
+ monkeypatch.undo()
+
+ assert tripped, "the collision never fired, so the retry was not exercised"
+ assert await latest_acceptance(async_session, first.id) is not None
+ assert await latest_acceptance(async_session, second.id) is not None
diff --git a/tests/unit/persistence/test_decision_candidate_meta_capture.py b/tests/unit/persistence/test_decision_candidate_meta_capture.py
new file mode 100644
index 000000000..de1ff83af
--- /dev/null
+++ b/tests/unit/persistence/test_decision_candidate_meta_capture.py
@@ -0,0 +1,281 @@
+"""Capture writes the review row, and the queue leads with acceptable work.
+
+Before this, ``decision_candidate_meta`` existed only for records the one-time
+migration walked, so everything captured since had no lane to filter on and no
+ordering signal for the review queue.
+"""
+
+from __future__ import annotations
+
+import json
+
+from sqlalchemy import select
+
+from repowise.core import __version__
+from repowise.core.persistence.crud import bulk_upsert_decisions, list_decisions
+from repowise.core.persistence.crud.authority import (
+ accept_decision,
+ list_candidates,
+ record_blockers,
+)
+from repowise.core.persistence.models import DecisionCandidateMeta, DecisionRecord
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _decision(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 _record(session, title: str) -> DecisionRecord:
+ return (
+ await session.execute(select(DecisionRecord).where(DecisionRecord.title == title))
+ ).scalar_one()
+
+
+async def test_capture_writes_a_review_row(async_session):
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session, repo.id, [_decision("Adopt the queue", lane="session_discovery")]
+ )
+
+ rec = await _record(async_session, "Adopt the queue")
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None
+ assert meta.lane == "session_discovery"
+ assert meta.extractor_version == __version__
+ assert meta.review_state == "open"
+ assert meta.scope_unresolved is False
+ assert meta.review_priority == 1.0
+
+
+async def test_lane_falls_back_to_the_source(async_session):
+ """Only the session lanes need a discriminator; the rest are their source."""
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(async_session, repo.id, [_decision("From a PR", source="pr")])
+
+ rec = await _record(async_session, "From a PR")
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None and meta.lane == "pr"
+
+
+async def test_lane_filter_matches_a_freshly_captured_candidate(async_session):
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session,
+ repo.id,
+ [
+ _decision("Broad lane", lane="session_discovery"),
+ _decision("Deterministic lane", lane="session"),
+ ],
+ )
+
+ rows = await list_candidates(async_session, repo.id, lane="session_discovery")
+ assert [rec.title for rec, _ in rows] == ["Broad lane"]
+
+
+async def test_an_unscoped_candidate_is_flagged_and_sorts_last(async_session):
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session,
+ repo.id,
+ [
+ # Higher confidence, but a reviewer cannot accept it: no scope.
+ _decision("No scope", affected_files=[], evidence_file=None, confidence=0.95),
+ _decision("Ready to accept", confidence=0.4),
+ ],
+ )
+
+ unscoped = await _record(async_session, "No scope")
+ meta = await async_session.get(DecisionCandidateMeta, unscoped.id)
+ assert meta is not None
+ assert meta.scope_unresolved is True
+ assert meta.review_priority == 0.0
+ assert record_blockers(unscoped) == [
+ "no scope: name the files or modules it governs",
+ "no evidence reference",
+ ]
+
+ rows = await list_candidates(async_session, repo.id)
+ assert [rec.title for rec, _ in rows] == ["Ready to accept", "No scope"]
+
+ page = await list_decisions(async_session, repo.id, accepted=False)
+ assert [rec.title for rec in page] == ["Ready to accept", "No scope"]
+
+
+async def test_re_extraction_refreshes_priority_without_reopening_review(async_session):
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session, repo.id, [_decision("Grew scope", affected_files=[], evidence_file=None)]
+ )
+ rec = await _record(async_session, "Grew scope")
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None and meta.review_priority == 0.0
+ meta.review_state = "needs_split"
+ meta.needs_split = True
+ await async_session.flush()
+
+ await bulk_upsert_decisions(async_session, repo.id, [_decision("Grew scope")])
+
+ await async_session.refresh(meta)
+ assert meta.review_priority == 1.0
+ assert meta.scope_unresolved is False
+ # A re-extraction must not walk back what review said about the candidate.
+ assert meta.review_state == "needs_split"
+ assert meta.needs_split is True
+
+
+async def test_capture_leaves_an_accepted_record_alone(async_session):
+ """Review is over for an accepted record; capture has nothing to say about it."""
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(async_session, repo.id, [_decision("Already governing")])
+ rec = await _record(async_session, "Already governing")
+ await accept_decision(async_session, rec, accepter="tester")
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None and meta.review_state == "accepted"
+ meta.review_priority = 0.0
+ meta.extractor_version = "0.0.0"
+ await async_session.flush()
+
+ await bulk_upsert_decisions(async_session, repo.id, [_decision("Already governing")])
+
+ await async_session.refresh(meta)
+ assert meta.review_state == "accepted"
+ assert meta.review_priority == 0.0
+ assert meta.extractor_version == "0.0.0"
+
+
+async def test_needs_split_survives_a_capture_that_does_not_claim_it(async_session):
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session, repo.id, [_decision("Two choices", needs_split=True)]
+ )
+ rec = await _record(async_session, "Two choices")
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None and meta.needs_split is True
+
+ await bulk_upsert_decisions(async_session, repo.id, [_decision("Two choices")])
+ await async_session.refresh(meta)
+ assert meta.needs_split is True
+
+
+async def test_the_scope_flag_agrees_with_the_contract_on_blank_entries(async_session):
+ """A scope list of one empty string is no scope, and both readers say so."""
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session, repo.id, [_decision("Blank scope", affected_files=[" "])]
+ )
+
+ rec = await _record(async_session, "Blank scope")
+ assert json.loads(rec.affected_files_json) == [" "]
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None and meta.scope_unresolved is True
+ assert "no scope: name the files or modules it governs" in record_blockers(rec)
+
+
+async def test_scope_flag_reads_modules_when_no_files_are_named(async_session):
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session,
+ repo.id,
+ [_decision("Module scoped", affected_files=[], affected_modules=["src"])],
+ )
+
+ rec = await _record(async_session, "Module scoped")
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None and meta.scope_unresolved is False
+ assert json.loads(rec.affected_modules_json) == ["src"]
+
+
+async def test_an_untouched_candidate_still_gets_its_review_row(async_session):
+ """A backlog that predates the review row must not wait to be re-extracted."""
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(async_session, repo.id, [_decision("Older")])
+ older = await _record(async_session, "Older")
+ meta = await async_session.get(DecisionCandidateMeta, older.id)
+ assert meta is not None
+ await async_session.delete(meta)
+ await async_session.flush()
+
+ # A later run that captures something else entirely.
+ await bulk_upsert_decisions(async_session, repo.id, [_decision("Newer")])
+
+ refreshed = await async_session.get(DecisionCandidateMeta, older.id)
+ assert refreshed is not None
+ assert refreshed.review_priority == 1.0
+ assert refreshed.lane == "session"
+ # Not extracted by this run, so its provenance is not claimed.
+ assert refreshed.extractor_version == ""
+
+
+async def test_a_single_record_add_gets_a_review_row(async_session):
+ """`decision add` goes through upsert_decision, not the accretion path."""
+ from repowise.core.persistence.crud import upsert_decision
+
+ repo = await insert_repo(async_session)
+ rec = await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="Typed by hand",
+ decision="use one queue",
+ rationale="because two drifted",
+ affected_files=["src/app.py"],
+ source="cli",
+ )
+
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None
+ assert meta.lane == "cli"
+ assert meta.review_priority == 1.0
+
+
+async def test_a_fold_keeps_the_split_flag_the_first_group_raised(async_session):
+ """Two titles can land on one record; the later must not drop the flag."""
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session,
+ repo.id,
+ [
+ _decision("Cache the parse tree", needs_split=True, lane="session_discovery"),
+ _decision("cache the parse tree"),
+ ],
+ )
+
+ rec = await _record(async_session, "Cache the parse tree")
+ meta = await async_session.get(DecisionCandidateMeta, rec.id)
+ assert meta is not None
+ assert meta.needs_split is True
+ assert meta.lane == "session_discovery"
+
+
+async def test_a_candidate_with_no_review_row_ranks_as_unjudged(async_session):
+ """Not last: it ranks with the refused ones, and confidence orders within."""
+ repo = await insert_repo(async_session)
+ await bulk_upsert_decisions(
+ async_session,
+ repo.id,
+ [
+ _decision("Ready", confidence=0.9),
+ _decision("Refused", affected_files=[], evidence_file=None, confidence=0.5),
+ _decision("Unjudged", confidence=0.7),
+ ],
+ )
+ unjudged = await _record(async_session, "Unjudged")
+ await async_session.delete(await async_session.get(DecisionCandidateMeta, unjudged.id))
+ await async_session.flush()
+
+ rows = await list_candidates(async_session, repo.id)
+
+ assert [rec.title for rec, _ in rows] == ["Ready", "Unjudged", "Refused"]