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): report what capture did, and review a backlog in one command (#2072)
Raghav Chamadiya577196f49c4b
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.mdindex 6ffa174a7..cb9c0080f 100644--- a/docs/layers/DECISIONS.md+++ b/docs/layers/DECISIONS.md@@ -138,13 +138,20 @@ review as though they were the team's.| Command | What it records ||---------|-----------------|-| `decision confirm ID` | Accept, optionally editing the reason and scope on the way. |+| `decision confirm ID...` | Accept, optionally editing the reason and scope on the way. Takes many ids. || `decision confirm ID` on a decision | Reaffirm it after review. || `decision 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 dismiss ID...` | Tombstone it. On an accepted decision this also withdraws its authority. Takes many ids. || `decision deprecate ID --superseded-by ID2` | Retire it with an explicit lineage edge. |+`confirm` and `dismiss` take a list because a repository accumulates candidates+faster than anyone reviews them one command at a time. Every id in a batch goes+through the same acceptance contract as a single one, and each is applied on its+own, so one refusal commits the rest and reports itself instead of ending the+run. `--preview` runs the batch through that contract and rolls it back, so the+report is what the write would have said rather than a second opinion about it.+Similarity never supersedes anything: an edge exists because somebody named thesuccessor. Merging and superseding retire ids that may already be written downsomewhere, so both leave an alias and the retired id keeps resolving.@@ -192,6 +199,21 @@ repowise decision healthpayments/processor.ts```+`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+extraction.++Nothing records a capture run. The extraction report and the broad lane's+discovery report are rendered to the progress line and discarded, and+`.repowise/state.json` carries nothing per source, so `status` derives every+figure from a durable trace instead: the records and their review rows, the+staging queues, and the `decision_extraction` cost rows. Two things follow, and+the command says both rather than papering over them. Spend is all-time with+the last call named, because no stored boundary says which call belonged to+which run. And a queue that a store predates is reported absent, not as zero.+From an agent:```python@@ -565,8 +587,8 @@ the scope that decision governs.| `repowise decision add` | Guided interactive capture: title, context, decision, rationale, rejected alternatives, tradeoffs, affected files, tags. Answering the prompts is an acceptance, recorded as one. Name no files and it is kept as a candidate instead, because a decision that names nothing cannot be checked against the code. || `repowise decision list` | Table of id, title, status, source, confidence, staleness, created date. || `repowise decision show ID` | Full record including alternatives, consequences, affected files, and the evidence file and line. |-| `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 confirm ID...` | Accept candidates. Refuses, naming the gap, when one has no reason, scope or evidence; `--reason`, `--scope` and `--evidence` supply them. A refused id does not stop the others. `--preview` writes nothing. |+| `repowise decision dismiss ID...` | Tombstone them. Never re-proposed on reindex. `--preview` writes nothing. || `repowise decision deprecate ID` | Retire it, optionally `--superseded-by <ID>`, which writes the lineage edge. || `repowise decision candidates` | What is awaiting review, and why each was raised. || `repowise decision merge ID INTO_ID` | Fold a candidate into an existing decision. |@@ -574,6 +596,7 @@ the scope that decision governs.| `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 status` | What capture did: policy and preset, per-source state and why, review lanes and backlog age, staging queues, model spend. || `repowise decision config show` | The resolved capture policy: every source, its status, and why. || `repowise decision config preset NAME` | Apply `off`, `local_only`, `balanced`, or `full`. || `repowise decision source list` | The source registry with capabilities and current state. |diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex a70d07360..8b85d5124 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -915,12 +915,13 @@ repowise decision list [PATH] # list recordsrepowise decision show ID [PATH] # full detailsrepowise decision add [PATH] # interactive addrepowise 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 confirm ID... [PATH] # accept candidates: this is what makes them govern+repowise decision dismiss ID... [PATH] # tombstone them (sticky; never re-proposed)repowise decision merge ID INTO_ID # fold a candidate into an existing decisionrepowise decision split ID [PATH] # flag a candidate as bundling two choicesrepowise decision deprecate ID [PATH] # retire a decision, optionally naming its successorrepowise decision health [PATH] # health dashboard+repowise decision status [PATH] # what capture did, and what it costrepowise decision export [PATH] # write accepted decisions to .repowise/decisions.yamlrepowise decision import [PATH] # reconcile the store to that file@@ -943,6 +944,8 @@ repowise decision llm --on|--off [PATH] # all decision-extraction mode| `--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. |+| `--preview` | On `confirm` and `dismiss`: report what each id would do, and write nothing. |+| `--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. |@@ -955,6 +958,30 @@ 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.+`confirm` and `dismiss` take one id or many, with the optional repository path+still last. A refused id does not stop the others, and each id is applied+independently, so a batch that refuses one commits the rest and exits 1.+`--preview` puts every id through the same acceptance contract and then rolls+the whole run back, so what it reports is what the write would have said.++One id keeps the transition document those verbs already emitted+(`{"id", "status", "action"}`). Two or more, or `--preview`, emit a results+document instead:++```json+{+ "action": "accepted",+ "preview": false,+ "results": [+ {"given": "9f3c", "id": "...", "title": "...", "ok": true, "action": "accepted", "status": "active"},+ {"given": "2b70", "id": "...", "title": "...", "ok": false,+ "error": "acceptance_refused", "blockers": ["no scope: name the files or modules it governs"]}+ ],+ "succeeded": 1,+ "failed": 1+}+```+**Capture-control options:**| Flag | Description |@@ -978,6 +1005,31 @@ as "what governs". `repowise decision candidates` is the authoritative list ofwhat nobody has accepted, and the Decisions page splits the same repositoryinto 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,+and the model spend booked to decision extraction.++Nothing records a capture run, so every figure is derived from a durable trace+rather than a run ledger. That has two consequences the command states rather+than papering over: spend is all-time with the last call named, because no+stored boundary says which call belonged to which run; and a queue that a+store predates is reported absent rather than as zero.++```+repowise decision status++ Decision capture++ Capture on · LLM extraction on · preset default++ Source Status Records Accepted Last seen Why+ inline_marker enabled 4 2 2026-08-31 Runs with model structuring.+ pr skipped_no_provider 213 0 2026-08-31 No LLM provider is configured.+ session_discovery disabled 0 0 - This source is switched off.+```+**Scripting these:** every subcommand takes `--format json`, and `confirm`,`dismiss`, `deprecate`, and `show` exit non-zero on an unknown id with`{"error": "decision_not_found", "decision_id": "..."}` so a caller can tell adiff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.pyindex 4e99b2e71..59838e849 100644--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py@@ -3,6 +3,8 @@from __future__ import annotationsimport json+import re+from pathlib import Pathimport clickfrom rich.panel import Panel@@ -73,6 +75,7 @@ def _register_config_commands() -> None:merge_command,migrate_command,split_command,+ status_command,)for command in (@@ -82,6 +85,7 @@ def _register_config_commands() -> None:split_command,export_command,import_command,+ status_command,):decision_group.add_command(command)@@ -596,13 +600,177 @@ def _emit_lifecycle(rec, decision_id: str, action: str, fmt: str, note: str = ""# ----------------------------------------------------------------------------# decision confirm+# decision confirm / dismiss# ---------------------------------------------------------------------------+#: The remedy printed beside a refused acceptance, naming the flags that+#: supply what the contract found missing.+_ACCEPT_REMEDY = "Supply the missing parts with --reason, --scope or --evidence."+++class _PreviewRollbackError(Exception):+ """Signals a preview to roll its savepoint back."""+++#: A decision id, or a prefix of one, as ``_resolve_decision_id`` accepts it.+_ID_SHAPED = re.compile(r"[0-9a-fA-F]{4,64}\Z")+++def _split_ids_and_path(tokens: tuple[str, ...]) -> tuple[list[str], str | None]:+ """Separate decision ids from the optional trailing repo path.++ ``confirm ID [PATH]`` shipped before batch arity, so the path is still a+ positional. An id-shaped last token stays an id even when a directory of+ that name happens to exist, because reading one as a path would drop it+ from the batch and still exit 0.+ """+ last = tokens[-1] if tokens else ""+ if len(tokens) > 1 and last and not _ID_SHAPED.match(last) and Path(last).is_dir():+ return list(tokens[:-1]), last+ return list(tokens), None+++async def _resolve_one(session, token: str):+ """The record *token* names, or the failure to report for it."""+ from repowise.core.persistence.models import DecisionRecord++ try:+ full_id = await _resolve_decision_id(session, token)+ except click.ClickException as exc:+ return None, {"given": token, "ok": False, "error": "ambiguous_id", "message": str(exc)}+ rec = await session.get(DecisionRecord, full_id) if full_id else None+ if rec is None:+ return None, {+ "given": token,+ "ok": False,+ "error": "decision_not_found",+ "message": f"Decision not found: {token}",+ }+ return rec, None+++async def _review_batch(repo_path, tokens, *, action: str, verb: str, preview: bool, apply_one):+ """Apply *apply_one* to every id, keeping one refusal from ending the run.++ Each id runs inside its own savepoint. ``accept_decision`` edits the+ record's rationale and scope before the contract can refuse it, so without+ one a refused id would leave that edit in the transaction the accepted ids+ commit. A preview runs the real write and then rolls the whole session+ back, so what it reports is what the contract actually said; the schema+ reconcile every subcommand opens the store with still runs.+ """+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ )+ from repowise.core.persistence.crud.authority import AcceptanceRefusedError++ engine = create_engine(get_db_url_for_repo(repo_path))+ try:+ await init_db(engine)+ except BaseException:+ await engine.dispose()+ raise+ results: list[dict] = []+ try:+ async with get_session(create_session_factory(engine)) as session:+ for token in tokens:+ rec, failure = await _resolve_one(session, token)+ if failure is not None:+ results.append(failure)+ continue+ entry = {"given": token, "id": rec.id, "title": rec.title}+ try:+ async with session.begin_nested():+ await apply_one(session, rec)+ if preview:+ raise _PreviewRollbackError+ except _PreviewRollbackError:+ results.append({**entry, "ok": True, "action": f"would_{verb}"})+ except AcceptanceRefusedError as exc:+ results.append(+ {+ **entry,+ "ok": False,+ "error": "acceptance_refused",+ "message": str(exc),+ "blockers": list(exc.blockers),+ }+ )+ else:+ results.append({**entry, "ok": True, "action": action, "status": rec.status})+ if preview:+ await session.rollback()+ finally:+ await engine.dispose()+ return results+++def _emit_batch(results: list[dict], action: str, verb: str, preview: bool, fmt: str) -> None:+ """Report a multi-id run, exiting non-zero when any id was refused."""+ failed = [r for r in results if not r["ok"]]+ if fmt == "json":+ emit_json(+ {+ "action": action,+ "preview": preview,+ "results": results,+ "succeeded": len(results) - len(failed),+ "failed": len(failed),+ }+ )+ if failed:+ raise click.exceptions.Exit(1)+ return++ headline = f"Would {verb}" if preview else action.capitalize()+ table = Table(title=f"{headline} {len(results) - len(failed)} of {len(results)}")+ for column in ("ID", "Title", "Outcome"):+ table.add_column(column)+ for result in results:+ outcome = "[green]ok[/green]" if result["ok"] else f"[red]{result['message']}[/red]"+ table.add_row(result.get("id", result["given"])[:8], result.get("title", "")[:50], outcome)+ console.print(table)+ if preview:+ console.print("[dim]Nothing was written. Re-run without --preview.[/dim]")+ if failed:+ raise click.exceptions.Exit(1)+++def _emit_single(result: dict, token: str, verb: str, fmt: str, note: str, remedy: str) -> None:+ """The one-id document, unchanged from before these verbs took many."""+ if result["ok"]:+ if fmt == "json":+ emit_json({"id": result["id"], "status": result["status"], "action": result["action"]})+ return+ console.print(+ f"[green]Decision {result['id'][:8]} {result['action']}[/green]"+ + (f" {note}" if note else "")+ )+ return+ if result["error"] == "decision_not_found":+ _emit_lifecycle(None, token, "", fmt)+ return+ if "id" not in result:+ # An ambiguous prefix never resolved to a record, so there is nothing+ # to name but the token the caller gave.+ emit_refusal(result["error"], result["message"], fmt)+ return+ extra: dict = {"decision_id": result["id"]}+ if "blockers" in result:+ extra["blockers"] = result["blockers"]+ if remedy:+ extra["remedy"] = remedy+ emit_refusal(+ result["error"], f"Cannot {verb} {result['id'][:8]}: {result['message']}", fmt, **extra+ )++@decision_group.command("confirm")[email protected]("decision_id")[email protected]("path", required=False, default=None)[email protected]("decision_ids", nargs=-1, required=True)@click.option("--reason", default="", help="Rationale, or why the constraint needs none.")@click.option("--scope",@@ -615,131 +783,103 @@ def _emit_lifecycle(rec, decision_id: str, action: str, fmt: str, note: str = ""help="Commit, file or link the decision rests on. Repeatable.",)@click.option("--as", "accepter", default="", help="Record a different accepter identity.")+ "--preview", is_flag=True, default=False, help="Report what each id would do, and write nothing."+)@format_option()def decision_confirm(- decision_id: str,- path: str | None,+ decision_ids: tuple[str, ...],reason: str,scope: tuple[str, ...],evidence: tuple[str, ...],accepter: str,+ preview: bool,fmt: str,) -> None:- """Accept a candidate, making it a decision that governs.+ """Accept candidates, making them decisions that govern.- This is the acceptance event, and it is the only thing that produces one:+ Takes one id or many, and an optional repository path after them. This is+ the acceptance event, and it is the only thing that produces one:extraction, recurrence and confidence all stop at a candidate. Acceptanceis 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.+ A refused id does not stop the others, and the run exits non-zero if any+ were refused."""+ ids, path = _split_ids_and_path(decision_ids)repo_path = _resolve_decision_repo(path, fmt)- async def _update():+ async def _accept(session, rec) -> None:from repowise.core.analysis.decisions.accepter import resolve_accepter- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,+ from repowise.core.persistence.crud.authority import accept_decision++ await accept_decision(+ session,+ rec,+ accepter=resolve_accepter(repo_path, override=accepter),+ reason=reason,+ scope=list(scope) or None,+ evidence=list(evidence) or None,)- from repowise.core.persistence.crud.authority import (- AcceptanceRefusedError,- accept_decision,- )- from repowise.core.persistence.models import DecisionRecord-- url = get_db_url_for_repo(repo_path)- engine = create_engine(url)- await init_db(engine)- sf = create_session_factory(engine)- 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)")---# ----------------------------------------------------------------------------# decision dismiss-# ---------------------------------------------------------------------------+ results = run_async(+ _review_batch(+ repo_path, ids, action="accepted", verb="accept", preview=preview, apply_one=_accept+ )+ )+ if len(ids) > 1 or preview:+ _emit_batch(results, "accepted", "accept", preview, fmt)+ return+ _emit_single(results[0], ids[0], "accept", fmt, "(governing)", _ACCEPT_REMEDY)@decision_group.command("dismiss")[email protected]("decision_id")[email protected]("path", required=False, default=None)[email protected]("decision_ids", nargs=-1, required=True)@click.option("--yes", "-y", is_flag=True, default=False, help="Skip the confirmation prompt.")[email protected]("--reason", default="", help="Why it was tombstoned.")+ "--preview", is_flag=True, default=False, help="Report what each id would do, and write nothing."+)@format_option()-def decision_dismiss(decision_id: str, path: str | None, yes: bool, fmt: str) -> None:- """Dismiss a proposed decision (kept as a tombstone; never re-proposed)."""+def decision_dismiss(+ decision_ids: tuple[str, ...], yes: bool, reason: str, preview: bool, fmt: str+) -> None:+ """Dismiss proposed decisions (kept as tombstones; never re-proposed).++ Takes one id or many, and an optional repository path after them.+ """+ ids, path = _split_ids_and_path(decision_ids)repo_path = _resolve_decision_repo(path, fmt)# A machine-readable invocation is non-interactive by construction: the# prompt read EOF and aborted every scripted dismissal.- if not yes and fmt != "json" and not click.confirm(f"Dismiss decision {decision_id[:8]}?"):+ subject = ids[0][:8] if len(ids) == 1 else f"{len(ids)} decisions"+ if not yes and not preview and fmt != "json" and not click.confirm(f"Dismiss {subject}?"):console.print("[yellow]Cancelled.[/yellow]")return- async def _dismiss():- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,- )+ async def _dismiss(session, rec) -> None:+ from repowise.core.analysis.decisions.accepter import resolve_accepterfrom repowise.core.persistence.crud.authority import dismiss_candidate- from repowise.core.persistence.models import DecisionRecord-- url = get_db_url_for_repo(repo_path)- engine = create_engine(url)- await init_db(engine)- sf = create_session_factory(engine)- 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 dismiss_candidate(session, rec, reason=reason, accepter=resolve_accepter(repo_path))- await dismiss_candidate(- session, rec, accepter=resolve_accepter(repo_path)- )- return rec- finally:- await engine.dispose()-- _emit_lifecycle(- run_async(_dismiss()),- decision_id,- "dismissed",+ results = run_async(+ _review_batch(+ repo_path, ids, action="dismissed", verb="dismiss", preview=preview, apply_one=_dismiss+ )+ )+ if len(ids) > 1 or preview:+ _emit_batch(results, "dismissed", "dismiss", preview, fmt)+ return+ _emit_single(+ results[0],+ ids[0],+ "dismiss",fmt,"[dim](kept as a tombstone; reindexing will not re-propose it)[/dim]",+ "",)diff --git a/packages/cli/src/repowise/cli/commands/decision_review_cmd.py b/packages/cli/src/repowise/cli/commands/decision_review_cmd.pyindex 409ab93f4..1bccfa3aa 100644--- a/packages/cli/src/repowise/cli/commands/decision_review_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_review_cmd.py@@ -20,6 +20,7 @@ __all__ = ["merge_command","migrate_command","split_command",+ "status_command",]@@ -379,3 +380,132 @@ def import_command(path: str | None, dry_run: bool, fmt: str) -> None:console.print(f" [yellow]skipped[/yellow] {skipped['id'][:8]}: {skipped['reason']}")if dry_run:console.print("[dim]Nothing was written.[/dim]")+++# ---------------------------------------------------------------------------+# decision status+# ---------------------------------------------------------------------------+++_STATUS_STYLE = {+ "enabled": "green",+ "always_on": "green",+ "deterministic_only": "yellow",+ "skipped_no_provider": "yellow",+ "disabled": "dim",+}+++def _render_status(report: dict) -> None:+ """Render the capture report for a person."""+ policy = report["policy"]+ console.print("[bold]Decision capture[/bold]\n")+ console.print(+ f" Capture [bold]{'on' if policy['enabled'] else 'off'}[/bold] · "+ f"LLM extraction [bold]{'on' if policy['llm'] else 'off'}[/bold] · "+ f"preset [bold]{policy['preset']}[/bold]"+ )+ if not policy["provider_available"]:+ console.print(" [dim]No LLM provider configured; model stages are skipped.[/dim]")+ for warning in policy["warnings"]:+ console.print(f" [yellow]{warning}[/yellow]")++ sources = Table(title="\nSources", box=None, pad_edge=False, show_edge=False)+ for column in ("Source", "Status", "Records", "Accepted", "Last seen", "Why"):+ sources.add_column(column)+ for source in report["sources"]:+ style = _STATUS_STYLE.get(source["status"], "")+ last = source.get("last_captured")+ sources.add_row(+ source["key"],+ f"[{style}]{source['status']}[/{style}]" if style else source["status"],+ str(source["records"]),+ str(source["accepted"]),+ str(last)[:10] if last else "-",+ f"[dim]{source['reason']}[/dim]",+ )+ console.print(sources)++ lanes = report["lanes"]+ review = report["review"]+ counts = Table(title="\nRecords", show_header=False, box=None, pad_edge=False, show_edge=False)+ counts.add_column("Metric", style="cyan")+ counts.add_column("Value", justify="right")+ counts.add_row("Governing", str(lanes["governing"]))+ counts.add_row("Active", str(lanes["active"]))+ counts.add_row("Needs review", str(lanes["needs_review"]))+ counts.add_row("Uncheckable", str(lanes["uncheckable"]))+ counts.add_row("History", str(lanes["history"]))+ counts.add_row("Candidates", f"[yellow]{lanes['candidates']}[/yellow]")+ counts.add_row("Total", str(lanes["total"]))+ console.print(counts)+ console.print(+ f" [dim]{review['unreviewed']} awaiting review · oldest "+ f"{review['oldest_age_days']:.0f}d · median {review['median_age_days']:.0f}d[/dim]"+ )++ backlog = report["backlog"]+ if backlog["available"]:+ console.print(+ "\n Backlog: "+ + " ".join(f"{k} {v}" for k, v in backlog.items() if k != "available")+ )+ else:+ console.print(f"\n [dim]Backlog: {backlog.get('reason', 'unavailable')}[/dim]")++ cost = report["cost"]+ if cost["calls"]:+ last = cost["last_call"]+ console.print(+ f"\n Model spend: {cost['calls']} calls "+ f"{cost['input_tokens'] + cost['output_tokens']} tokens "+ f"${cost['cost_usd']:.4f}"+ )+ console.print(f" [dim]Last call {str(last['at'])[:19]} on {last['model']}[/dim]")+ else:+ console.print("\n [dim]No decision-extraction model calls recorded.[/dim]")+ console.print(+ "\n[dim]Totals are all-time: capture records no per-run ledger, so a single "+ "run cannot be costed on its own.[/dim]"+ )++[email protected]("status")[email protected]("path", required=False, default=None)+@format_option()+def status_command(path: str | None, fmt: str) -> None:+ """Report what decision capture did, and what it cost."""+ 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.status import capture_status+ from repowise.core.persistence import get_session+ from repowise.core.providers.llm.registry import provider_available_for_repo++ engine, sf = await _open(repo_path)+ try:+ async with get_session(sf) as session:+ repo_id = await _repository_id(session, repo_path)+ return await capture_status(+ session,+ repo_id,+ repo_path,+ provider_available=provider_available_for_repo(repo_path),+ )+ finally:+ await engine.dispose()++ from repowise.core.repo_config import RepoConfigError++ try:+ report = run_async(_run())+ except RepoConfigError as exc:+ emit_refusal("config_unreadable", str(exc), fmt)+ return++ if fmt == "json":+ emit_json({"repo": str(repo_path), **report})+ return+ _render_status(report)diff --git a/packages/core/src/repowise/core/analysis/decisions/status.py b/packages/core/src/repowise/core/analysis/decisions/status.pynew file mode 100644index 000000000..4f8ccc0e1--- /dev/null+++ b/packages/core/src/repowise/core/analysis/decisions/status.py@@ -0,0 +1,316 @@+"""What decision capture did, assembled from what capture actually persisted.++There is no capture-run ledger, so every figure here is derived from a durable+trace capture left behind, and the report omits what it cannot attribute rather+than guessing at it.++Lives in core rather than in the CLI so the API can answer the same question.+"""++from __future__ import annotations++import sqlite3+from dataclasses import dataclass+from datetime import datetime+from pathlib import Path+from typing import Any++from sqlalchemy import func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.persistence.crud.authority import (+ accepted_decision_ids,+ candidate_predicate,+ count_decisions_by_lane,+)+from repowise.core.persistence.models import (+ DecisionCandidateMeta,+ DecisionRecord,+ LlmCost,+ _now_utc,+)+from repowise.core.sessions.staging import default_store_path++from .lifecycle import CANDIDATE_REVIEW_STATES+from .policy import SOURCE_SPECS, SourceRuntime+from .policy_store import load_policy+from .provenance import RETIRED_SOURCES++#: The ``LlmCost.operation`` every decision-extraction call is booked under.+#: One label covers the index sources and the broad session lane alike, so+#: spend cannot be split between them here.+CAPTURE_COST_OPERATION = "decision_extraction"++_SECONDS_PER_DAY = 86_400.0+++@dataclass(frozen=True, slots=True)+class _Backlog:+ """Queue depth from the session staging store, or why it could not be read."""++ available: bool+ reason: str = ""+ values: dict[str, int] | None = None++ def to_dict(self) -> dict[str, Any]:+ payload: dict[str, Any] = {"available": self.available}+ if self.reason:+ payload["reason"] = self.reason+ payload.update(self.values or {})+ return payload+++def _age_days(then: datetime, now: datetime) -> float:+ """Age in days. SQLite hands back naive datetimes, and they are UTC."""+ if then.tzinfo is None:+ then = then.replace(tzinfo=now.tzinfo)+ return round(max(0.0, (now - then).total_seconds()) / _SECONDS_PER_DAY, 2)+++async def _per_source(+ session: AsyncSession, repository_id: str, accepted: set[str]+) -> dict[str, dict[str, Any]]:+ """Records, accepted count and newest capture per stored source value.++ Tombstoned candidates are excluded, because ``count_decisions_by_lane``+ excludes them: counting them here would make the Sources column sum to+ more than the total beside it.+ """+ rows = (+ await session.execute(+ select(DecisionRecord.id, DecisionRecord.source, DecisionRecord.created_at).where(+ DecisionRecord.repository_id == repository_id,+ or_(DecisionRecord.status != "dismissed", DecisionRecord.id.in_(accepted)),+ )+ )+ ).all()+ out: dict[str, dict[str, Any]] = {}+ for did, source, created_at in rows:+ bucket = out.setdefault(+ source, {"records": 0, "accepted": 0, "candidates": 0, "last_captured": None}+ )+ bucket["records"] += 1+ bucket["accepted" if did in accepted else "candidates"] += 1+ if created_at is not None and (+ bucket["last_captured"] is None or created_at > bucket["last_captured"]+ ):+ bucket["last_captured"] = created_at+ return out+++async def _review(session: AsyncSession, repository_id: str) -> dict[str, Any]:+ """Review-state counts and the age of the unreviewed backlog."""+ states = dict(+ (+ await session.execute(+ select(DecisionCandidateMeta.review_state, func.count())+ .where(DecisionCandidateMeta.repository_id == repository_id)+ .group_by(DecisionCandidateMeta.review_state)+ )+ ).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(),+ )+ )+ )+ .scalars()+ .all()+ )++ now = _now_utc()+ days = sorted(_age_days(value, now) for value in ages)+ middle = len(days) // 2+ return {+ "states": {state: int(states.get(state, 0)) for state in CANDIDATE_REVIEW_STATES},+ "unreviewed": len(days),+ "oldest_age_days": days[-1] if days else 0.0,+ "median_age_days": (+ 0.0+ if not days+ else days[middle]+ if len(days) % 2+ else round((days[middle - 1] + days[middle]) / 2, 2)+ ),+ }+++def _backlog(repo_path: Path) -> _Backlog:+ """Staging-queue depth, read without creating or migrating the store.++ Opened read-only on purpose: ``SessionStagingStore`` reconciles its schema+ on construction, and a report has no business writing a queue table into a+ store that predates it.+ """+ db_path = default_store_path(repo_path)+ if not db_path.exists():+ return _Backlog(False, "No session staging store yet.")++ queries = {+ "discovery_spans_pending": "SELECT COUNT(*) FROM discovery_spans WHERE consumed_at IS NULL",+ "discovery_spans_retrying": (+ "SELECT COUNT(*) FROM discovery_spans WHERE consumed_at IS NULL AND attempts > 0"+ ),+ "raw_candidates_pending": (+ "SELECT COUNT(*) FROM raw_candidates WHERE structured_key IS NULL"+ ),+ "session_decisions_unpromoted": "SELECT COUNT(*) FROM decisions WHERE promoted_at IS NULL",+ }+ values: dict[str, int] = {}+ try:+ conn = sqlite3.connect(f"{db_path.as_uri()}?mode=ro", uri=True)+ except sqlite3.Error as exc:+ return _Backlog(False, f"Session staging store unreadable: {exc}")+ try:+ for key, sql in queries.items():+ try:+ values[key] = int(conn.execute(sql).fetchone()[0])+ except sqlite3.Error as exc:+ # A store written before this queue existed has no such table,+ # and absent is not zero, so the key is left out rather than+ # faked. Anything else is this store being unreadable — a WAL+ # database with no companion file cannot be opened read-only —+ # and reporting that as an empty queue would be a lie.+ if "no such table" not in str(exc):+ return _Backlog(False, f"Session staging store unreadable: {exc}")+ continue+ finally:+ conn.close()+ if not values:+ return _Backlog(False, "Session staging store has no queue tables yet.")+ return _Backlog(True, values=values)+++async def _cost(session: AsyncSession, repository_id: str) -> dict[str, Any]:+ """Model spend booked to decision extraction.++ Totals are all-time and ``last_call`` is one row, because nothing records+ which call belonged to which run: a per-run figure would be a guess at a+ boundary the store does not have.+ """+ totals = (+ await session.execute(+ select(+ func.count(),+ func.coalesce(func.sum(LlmCost.input_tokens), 0),+ func.coalesce(func.sum(LlmCost.output_tokens), 0),+ func.coalesce(func.sum(LlmCost.cost_usd), 0.0),+ ).where(+ LlmCost.repository_id == repository_id,+ LlmCost.operation == CAPTURE_COST_OPERATION,+ )+ )+ ).one()+ last = (+ await session.execute(+ select(LlmCost.ts, LlmCost.model, LlmCost.input_tokens, LlmCost.output_tokens)+ .where(+ LlmCost.repository_id == repository_id,+ LlmCost.operation == CAPTURE_COST_OPERATION,+ )+ .order_by(LlmCost.ts.desc(), LlmCost.id.desc())+ .limit(1)+ )+ ).first()+ return {+ "operation": CAPTURE_COST_OPERATION,+ "calls": int(totals[0]),+ "input_tokens": int(totals[1]),+ "output_tokens": int(totals[2]),+ "cost_usd": round(float(totals[3]), 6),+ "last_call": (+ None+ if last is None+ else {+ "at": last[0],+ "model": last[1],+ "input_tokens": int(last[2]),+ "output_tokens": int(last[3]),+ }+ ),+ }+++async def capture_status(+ session: AsyncSession,+ repository_id: str,+ repo_path: Path,+ *,+ provider_available: bool,+) -> dict[str, Any]:+ """The one capture report, shared by every surface that asks for it."""+ resolution = load_policy(repo_path)+ policy = resolution.policy++ accepted = await accepted_decision_ids(session, repository_id)+ by_source = await _per_source(session, repository_id, accepted)++ sources: list[dict[str, Any]] = []+ for runtime in policy.runtime(provider_available=provider_available):+ captured = by_source.get(runtime.key, {})+ sources.append(+ {+ **runtime.to_dict(),+ "records": captured.get("records", 0),+ "accepted": captured.get("accepted", 0),+ "candidates": captured.get("candidates", 0),+ "last_captured": captured.get("last_captured"),+ }+ )+ # A retired source keeps its stored rows, and a row whose source has no+ # spec would otherwise vanish from a report that claims to be a census.+ # Built through SourceRuntime so it is the same row shape as the rest:+ # the API's source model requires every field a spec-backed row carries.+ known = {spec.key for spec in SOURCE_SPECS}+ for key in sorted(set(by_source) - known):+ retired = key in RETIRED_SOURCES+ sources.append(+ {+ **SourceRuntime(+ key=key,+ label=key,+ description=(+ "Retired source; stored rows only."+ if retired+ else "Unknown source; stored rows only."+ ),+ authority="machine",+ deterministic=False,+ supports_llm=False,+ togglable=False,+ enabled=False,+ llm_enabled=False,+ status="disabled",+ reason=(+ "This source no longer runs."+ if retired+ else "This source is not in the registry."+ ),+ ).to_dict(),+ **by_source[key],+ }+ )++ # The policy's own source list is dropped: ``sources`` below is the same+ # runtime rows with the capture counts joined on, and two lists that can+ # disagree is the drift this layer exists to stop having.+ resolved = policy.to_dict(provider_available=provider_available)+ resolved.pop("sources", None)+ return {+ "policy": {+ **resolved,+ "provider_available": provider_available,+ "warnings": list(resolution.warnings),+ },+ "sources": sources,+ "lanes": await count_decisions_by_lane(session, repository_id),+ "review": await _review(session, repository_id),+ "backlog": _backlog(repo_path).to_dict(),+ "cost": await _cost(session, repository_id),+ }diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex 31116106c..6f28fff93 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -45,6 +45,7 @@ __all__ = ["accept_decision","accepted_decision_ids","accepted_predicate",+ "candidate_predicate","count_decisions_by_lane","current_currency","decision_currencies",@@ -98,6 +99,17 @@ def accepted_predicate() -> Any:).exists()+def candidate_predicate() -> Any:+ """A ``WHERE`` clause restricting a ``DecisionRecord`` query to candidates.++ Never accepted, and not tombstoned. The second half is what keeps a+ dismissed candidate out of a review queue while+ :func:`count_decisions_by_lane` keeps it out of the totals, so the two+ cannot report different backlogs off the same store.+ """+ return ~accepted_predicate() & (DecisionRecord.status != "dismissed")++#: 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.diff --git a/tests/unit/cli/test_decision_batch_review.py b/tests/unit/cli/test_decision_batch_review.pynew file mode 100644index 000000000..7c1d2db15--- /dev/null+++ b/tests/unit/cli/test_decision_batch_review.py@@ -0,0 +1,170 @@+"""Batch arity and preview on ``repowise decision confirm`` / ``dismiss``.++The dev store holds hundreds of candidates, so the properties that matter here+are that one refusal does not end the run, that a preview writes nothing, and+that the single-id document these verbs already emitted is unchanged.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.cli.main import cli++from .test_decision_cmd import _seed_wiki_db++_GOOD = "a" * 32+_ALSO_GOOD = "b" * 32+#: No rationale and no scope, so the acceptance contract refuses it.+_BARE = "c" * 32+++def review_repo(tmp_path: Path) -> Path:+ repo = tmp_path / "repo"+ repo.mkdir()+ (repo / ".repowise").mkdir()+ _seed_wiki_db(+ repo,+ [+ {"id": _GOOD, "title": "Use JWT", "status": "proposed", "source": "pr"},+ {"id": _ALSO_GOOD, "title": "Use Postgres", "status": "proposed", "source": "pr"},+ {+ "id": _BARE,+ "title": "Bare",+ "status": "proposed",+ "source": "pr",+ "rationale": "",+ "decision": "",+ "affected_files": [],+ },+ ],+ )+ return repo+++def _run(repo: Path, *args: str):+ return CliRunner().invoke(cli, ["decision", *args, str(repo), "--format", "json"])+++def _lanes(repo: Path) -> dict:+ result = _run(repo, "status")+ assert result.exit_code == 0, result.output+ return json.loads(result.output)["lanes"]+++def test_batch_confirm_applies_the_rest_after_a_refusal(review_repo: Path) -> None:+ result = _run(review_repo, "confirm", "aaaa", "cccc", "bbbb")++ assert result.exit_code == 1, result.output+ payload = json.loads(result.output)+ assert payload["succeeded"] == 2+ assert payload["failed"] == 1+ by_id = {r["given"]: r for r in payload["results"]}+ assert by_id["aaaa"]["action"] == "accepted"+ assert by_id["bbbb"]["action"] == "accepted"+ assert by_id["cccc"]["error"] == "acceptance_refused"+ assert any("scope" in blocker for blocker in by_id["cccc"]["blockers"])+ # The refused id is the middle one: the two either side still landed.+ assert _lanes(review_repo)["governing"] == 2+++def test_a_refused_id_leaves_no_edit_behind(review_repo: Path) -> None:+ """``accept_decision`` edits scope before the contract can refuse.++ Without a savepoint per id the refused record would keep the edit that+ the accepted ids commit alongside them.+ """+ result = _run(review_repo, "confirm", "aaaa", "cccc", "--scope", "src/edited.py")++ assert result.exit_code == 1, result.output+ shown = CliRunner().invoke(cli, ["decision", "show", "cccc", str(review_repo), "--format", "json"])+ assert "src/edited.py" not in shown.output+++def test_preview_writes_nothing(review_repo: Path) -> None:+ result = _run(review_repo, "confirm", "aaaa", "bbbb", "--preview")++ assert result.exit_code == 0, result.output+ payload = json.loads(result.output)+ assert payload["preview"] is True+ assert [r["action"] for r in payload["results"]] == ["would_accept", "would_accept"]+ assert _lanes(review_repo)["governing"] == 0+++def test_preview_reports_a_refusal_without_writing(review_repo: Path) -> None:+ result = _run(review_repo, "confirm", "cccc", "--preview")++ assert result.exit_code == 1, result.output+ payload = json.loads(result.output)+ assert payload["results"][0]["error"] == "acceptance_refused"+ assert _lanes(review_repo)["candidates"] == 3+++def test_one_id_keeps_the_transition_document(review_repo: Path) -> None:+ result = _run(review_repo, "confirm", "aaaa")++ assert result.exit_code == 0, result.output+ payload = json.loads(result.output)+ assert payload == {"id": _GOOD, "status": "active", "action": "accepted"}+++def test_batch_dismiss_reports_an_unknown_id_beside_the_rest(review_repo: Path) -> None:+ result = _run(review_repo, "dismiss", "cccc", "zzzz", "--yes")++ assert result.exit_code == 1, result.output+ payload = json.loads(result.output)+ assert payload["succeeded"] == 1+ by_id = {r["given"]: r for r in payload["results"]}+ assert by_id["cccc"]["action"] == "dismissed"+ assert by_id["zzzz"]["error"] == "decision_not_found"+++def test_the_trailing_path_still_resolves_with_many_ids(review_repo: Path, tmp_path: Path) -> None:+ """A path is a positional after the ids, and only a real directory is one."""+ runner = CliRunner()+ result = runner.invoke(+ cli, ["decision", "confirm", "aaaa", "bbbb", str(review_repo), "--format", "json"]+ )++ assert result.exit_code == 0, result.output+ assert json.loads(result.output)["succeeded"] == 2+++def test_an_ambiguous_single_id_refuses_instead_of_crashing(tmp_path: Path) -> None:+ """An ambiguous prefix resolves to no record, so there is no id to name."""+ repo = tmp_path / "ambiguous"+ repo.mkdir()+ (repo / ".repowise").mkdir()+ _seed_wiki_db(+ repo,+ [+ {"id": "dd" + "1" * 30, "title": "One", "status": "proposed"},+ {"id": "dd" + "2" * 30, "title": "Two", "status": "proposed"},+ ],+ )++ result = _run(repo, "confirm", "dd")++ assert result.exit_code == 1, result.output+ payload = json.loads(result.output)+ assert payload["error"] == "ambiguous_id"+ assert "decision_id" not in payload+ assert "ambiguous" in payload["message"]+++def test_an_id_shaped_directory_stays_an_id(review_repo: Path, monkeypatch) -> None:+ """Reading a hex token as a path would drop it from the batch and exit 0."""+ monkeypatch.chdir(review_repo.parent)+ (review_repo.parent / "cccc").mkdir()++ result = CliRunner().invoke(+ cli, ["decision", "confirm", "aaaa", "cccc", "--preview", "--format", "json"]+ )++ payload = json.loads(result.output)+ assert [r["given"] for r in payload["results"]] == ["aaaa", "cccc"]diff --git a/tests/unit/cli/test_decision_status_cmd.py b/tests/unit/cli/test_decision_status_cmd.pynew file mode 100644index 000000000..5e5985066--- /dev/null+++ b/tests/unit/cli/test_decision_status_cmd.py@@ -0,0 +1,225 @@+"""``repowise decision status`` — what capture did, and what it cost.++Nothing records a capture run, so every figure the command reports has to come+off a durable trace: the records, the review rows, the staging queues and the+``decision_extraction`` cost rows. These tests pin it to those, and pin the+absent ones to being absent rather than reported as zero.+"""++from __future__ import annotations++import asyncio+import json+import sqlite3+from pathlib import Path++import pytest+import yaml+from click.testing import CliRunner+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from repowise.cli.main import cli+from repowise.core.analysis.decisions.status import CAPTURE_COST_OPERATION+from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import LlmCost++from .test_decision_cmd import _REPO_ID, _seed_wiki_db+++def _add_cost_rows(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()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ for row in rows:+ session.add(LlmCost(repository_id=_REPO_ID, **row))+ await session.commit()+ await engine.dispose()++ asyncio.run(_build())+++def status_repo(tmp_path: Path) -> Path:+ repo = tmp_path / "repo"+ repo.mkdir()+ (repo / ".repowise").mkdir()+ _seed_wiki_db(+ repo,+ [+ {"id": "a" * 32, "title": "Use JWT", "status": "proposed", "source": "pr"},+ {"id": "b" * 32, "title": "Use Postgres", "status": "proposed", "source": "pr"},+ {"id": "c" * 32, "title": "Typed", "status": "proposed", "source": "git_archaeology"},+ ],+ )+ return repo+++def _status(repo: Path) -> dict:+ result = CliRunner().invoke(cli, ["decision", "status", str(repo), "--format", "json"])+ assert result.exit_code == 0, result.output+ return json.loads(result.output)+++def test_status_reports_the_effective_policy_and_preset(status_repo: Path) -> None:+ policy = _status(status_repo)["policy"]++ assert policy["preset"] == "default"+ assert policy["enabled"] is True+ # The per-source rows live under `sources`, not here: one list, so the two+ # cannot drift apart.+ assert "sources" not in policy+++def test_status_names_why_a_source_made_no_call(status_repo: Path) -> None:+ (status_repo / ".repowise" / "config.yaml").write_text(+ yaml.safe_dump({"decisions": {"preset": "off"}}), encoding="utf-8"+ )++ report = _status(status_repo)++ assert report["policy"]["preset"] == "off"+ by_key = {source["key"]: source for source in report["sources"]}+ assert by_key["pr"]["status"] == "disabled"+ assert by_key["pr"]["reason"] == "Decision capture is off for this repository."+ # Manual entry is an authority route, not capture, so it has nothing to+ # switch off and says so rather than reading as collateral damage.+ assert by_key["cli"]["status"] == "always_on"+++def test_status_counts_what_each_source_captured(status_repo: Path) -> None:+ by_key = {source["key"]: source for source in _status(status_repo)["sources"]}++ assert by_key["pr"]["records"] == 2+ assert by_key["pr"]["candidates"] == 2+ assert by_key["pr"]["accepted"] == 0+ assert by_key["pr"]["last_captured"] is not None+ assert by_key["git_archaeology"]["records"] == 1+ assert by_key["adr"]["records"] == 0+ assert by_key["adr"]["last_captured"] is None+++def test_status_lanes_agree_with_acceptance_not_the_status_column(status_repo: Path) -> None:+ report = _status(status_repo)++ assert report["lanes"]["candidates"] == 3+ assert report["lanes"]["governing"] == 0+ assert report["review"]["unreviewed"] == 3++ accepted = CliRunner().invoke(+ cli, ["decision", "confirm", "aaaa", str(status_repo), "--format", "json"]+ )+ assert accepted.exit_code == 0, accepted.output++ after = _status(status_repo)+ assert after["lanes"]["governing"] == 1+ assert after["lanes"]["candidates"] == 2+ assert after["review"]["unreviewed"] == 2+ assert after["review"]["states"]["accepted"] == 1+ by_key = {source["key"]: source for source in after["sources"]}+ assert by_key["pr"]["accepted"] == 1+++def test_status_reports_capture_spend_and_the_last_call(status_repo: Path) -> None:+ _add_cost_rows(+ status_repo,+ [+ {+ "model": "gpt-5.6-luna",+ "operation": CAPTURE_COST_OPERATION,+ "input_tokens": 1000,+ "output_tokens": 200,+ "cost_usd": 0.01,+ },+ {+ "model": "gpt-5.6-luna",+ "operation": CAPTURE_COST_OPERATION,+ "input_tokens": 500,+ "output_tokens": 100,+ "cost_usd": 0.005,+ },+ # Another operation's spend is not decision capture's.+ {+ "model": "gpt-5.6-luna",+ "operation": "doc_generation",+ "input_tokens": 9_999,+ "output_tokens": 9_999,+ "cost_usd": 5.0,+ },+ ],+ )++ cost = _status(status_repo)["cost"]++ assert cost["calls"] == 2+ assert cost["input_tokens"] == 1500+ assert cost["output_tokens"] == 300+ assert cost["cost_usd"] == pytest.approx(0.015)+ assert cost["last_call"]["model"] == "gpt-5.6-luna"+++def test_status_says_the_backlog_is_absent_rather_than_empty(status_repo: Path) -> None:+ backlog = _status(status_repo)["backlog"]++ assert backlog["available"] is False+ assert "reason" in backlog+ assert "discovery_spans_pending" not in backlog+++def test_status_reads_the_backlog_without_migrating_it(status_repo: Path) -> None:+ """A store predating a queue reports the queues it has, and gains no table."""+ sessions_db = status_repo / ".repowise" / "sessions" / "sessions.db"+ sessions_db.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(sessions_db)+ conn.execute("CREATE TABLE decisions (key TEXT PRIMARY KEY, promoted_at REAL)")+ conn.execute("INSERT INTO decisions VALUES ('one', NULL), ('two', 1.0)")+ conn.commit()+ conn.close()++ backlog = _status(status_repo)["backlog"]++ assert backlog["available"] is True+ assert backlog["session_decisions_unpromoted"] == 1+ assert "discovery_spans_pending" not in backlog++ conn = sqlite3.connect(sessions_db)+ tables = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}+ conn.close()+ assert tables == {"decisions"}+++def test_a_retired_source_keeps_the_row_shape_every_source_has(tmp_path: Path) -> None:+ """The API's source model requires every field a registry-backed row carries."""+ repo = tmp_path / "retired"+ repo.mkdir()+ (repo / ".repowise").mkdir()+ _seed_wiki_db(+ repo,+ [{"id": "d" * 32, "title": "Old", "status": "proposed", "source": "code_comment"}],+ )++ sources = _status(repo)["sources"]+ registry = {source["key"] for source in sources if source["key"] != "code_comment"}+ retired = next(source for source in sources if source["key"] == "code_comment")+ reference = next(source for source in sources if source["key"] == "pr")++ assert registry, "the registry rows must still be present"+ assert set(retired) == set(reference)+ assert retired["records"] == 1+ assert retired["status"] == "disabled"+++def test_the_source_census_counts_the_same_records_the_lanes_do(status_repo: Path) -> None:+ """Otherwise the Sources column sums to more than the total beside it."""+ dismissed = CliRunner().invoke(+ cli, ["decision", "dismiss", "aaaa", str(status_repo), "--yes", "--format", "json"]+ )+ assert dismissed.exit_code == 0, dismissed.output++ report = _status(status_repo)+ counted = sum(source["records"] for source in report["sources"])++ assert counted == report["lanes"]["total"] == 2+ assert report["review"]["unreviewed"] == report["lanes"]["candidates"] == 2