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
refactor(cli): move decision id resolution and batch runs into decision_batch (#2581)
Raghav Chamadiya6c6cd98c1964
diff --git a/packages/cli/src/repowise/cli/commands/decision_batch.py b/packages/cli/src/repowise/cli/commands/decision_batch.pynew file mode 100644index 000000000..abe23dd98--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/decision_batch.py@@ -0,0 +1,252 @@+"""Resolve decision ids, and apply one lifecycle verb to many of them.++Shared by the ``decision`` commands in ``decision_cmd``.+"""++from __future__ import annotations++import re+from contextlib import asynccontextmanager+from pathlib import Path++import click+from rich.table import Table++from repowise.cli.helpers import console, get_db_url_for_repo+from repowise.cli.output import emit_json, emit_refusal+++@asynccontextmanager+async def _open_store(repo_path: Path):+ """Yield a session factory on the repo's store; the engine is disposed after.++ A factory, so ``add`` can embed after its session commits.+ """+ from repowise.core.persistence import create_engine, create_session_factory, init_db++ engine = create_engine(get_db_url_for_repo(repo_path))+ try:+ await init_db(engine)+ yield create_session_factory(engine)+ finally:+ await engine.dispose()+++async def _resolve_decision_id(session, decision_id: str) -> str | None:+ """Expand a (possibly truncated) decision id to the full stored id.++ ``decision list`` prints 8-char prefixes, so every id-taking subcommand+ accepts a unique prefix. Returns None when nothing matches; raises on an+ ambiguous prefix.+ """+ from repowise.core.persistence.models import DecisionAlias, DecisionRecord++ full_id = await _match_prefix(session, DecisionRecord.id, DecisionRecord.id, decision_id)+ if full_id is not None:+ return full_id+ # Merging and superseding retire ids that are already written down+ # somewhere. Resolving through the alias keeps those working instead of+ # reporting the decision as gone.+ return await _match_prefix(+ session, DecisionAlias.decision_id, DecisionAlias.alias_id, decision_id+ )+++async def _match_prefix(session, selected, matched, prefix: str) -> str | None:+ """*selected* from the one row whose *matched* column starts with *prefix*."""+ from sqlalchemy import select++ from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like++ result = await session.execute(+ select(selected)+ .where(matched.like(f"{escape_like(prefix)}%", escape=LIKE_ESCAPE))+ .limit(2)+ )+ ids = [row[0] for row in result.all()]+ if len(ids) > 1:+ raise click.ClickException(+ f"Decision id prefix {prefix!r} is ambiguous; use more characters."+ )+ return ids[0] if ids else None+++def _emit_lifecycle(rec, decision_id: str, action: str, fmt: str, note: str = "") -> None:+ """Report one status transition to a person or to a machine.++ Not found exits non-zero: an agent driving the lifecycle could not tell a+ typo'd id from a successful confirm when both returned 0.+ """+ if rec is None:+ if fmt == "json":+ emit_json({"error": "decision_not_found", "decision_id": decision_id})+ else:+ console.print(f"[red]Decision not found: {decision_id}[/red]")+ raise click.exceptions.Exit(1)+ if fmt == "json":+ emit_json({"id": rec.id, "status": rec.status, "action": action})+ return+ console.print(f"[green]Decision {rec.id[:8]} {action}[/green]" + (f" {note}" if note else ""))+++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 len(tokens) > 1 else ""+ # An empty token would otherwise read as the current directory.+ if 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 get_session++ results: list[dict] = []+ async with _open_store(repo_path) as sf, get_session(sf) as session:+ for token in tokens:+ # A token that resolves to nothing already carries its outcome.+ rec, outcome = await _resolve_one(session, token)+ if outcome is None:+ outcome = await _apply_in_savepoint(+ session, rec, token, action=action, verb=verb, preview=preview,+ apply_one=apply_one,+ )+ results.append(outcome)+ if preview:+ await session.rollback()+ return results+++async def _apply_in_savepoint(+ session, rec, token: str, *, action: str, verb: str, preview: bool, apply_one+) -> dict:+ """One id's outcome: applied, would-apply under preview, or refused."""+ from repowise.core.persistence.crud.authority import AcceptanceRefusedError++ 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:+ return {**entry, "ok": True, "action": f"would_{verb}"}+ except AcceptanceRefusedError as exc:+ return {+ **entry,+ "ok": False,+ "error": "acceptance_refused",+ "message": str(exc),+ "blockers": list(exc.blockers),+ }+ return {**entry, "ok": True, "action": action, "status": rec.status}+++def _emit_batch(+ results: list[dict], action: str, verb: str, preview: bool, fmt: str, remedy: str = ""+) -> None:+ """Report a multi-id run, exiting non-zero when any id was refused."""+ 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),+ # Once for the run: every refusal here is the same verb.+ **({"remedy": remedy} if failed and remedy else {}),+ }+ )+ else:+ _print_batch(results, len(failed), action, verb, preview, remedy)+ if failed:+ raise click.exceptions.Exit(1)+++def _print_batch(+ results: list[dict], failed: int, action: str, verb: str, preview: bool, remedy: str+) -> None:+ headline = f"Would {verb}" if preview else action.capitalize()+ table = Table(title=f"{headline} {len(results) - 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 and remedy:+ console.print(f"[dim]{remedy}[/dim]")+++def _emit_single(result: dict, token: str, verb: str, fmt: str, note: str, remedy: str) -> None:+ """Report a one-id run: the transition, or the refusal naming that id."""+ 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 has no record, only 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+ )diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.pyindex 3e71b6ca2..f8e80afbc 100644--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py@@ -3,7 +3,7 @@from __future__ import annotationsimport json-import re+from dataclasses import dataclassfrom pathlib import Pathimport click@@ -12,10 +12,18 @@ from rich.panel import Panelfrom rich.table import Tablefrom repowise.cli.commands import _tool_adapters as _ta+from repowise.cli.commands.decision_batch import (+ _emit_batch,+ _emit_lifecycle,+ _emit_single,+ _open_store,+ _resolve_decision_id,+ _review_batch,+ _split_ids_and_path,+)from repowise.cli.helpers import (console,ensure_repowise_dir,- get_db_url_for_repo,resolve_command_target,run_async,)@@ -31,10 +39,7 @@ from repowise.core.analysis.decisions.lifecycle import (from repowise.core.analysis.decisions.provenance import LISTABLE_SOURCESfrom repowise.core.precedent.currency import describe_decision_currency-#: The ladder's real sources plus the no-filter sentinel. Derived, because the-#: hand-written copy had drifted: it offered ``readme_mining`` (since retired)-#: while omitting ``session``, the source carrying a user's own words and the-#: one you would most want to filter for.+#: Every source a stored record can carry, plus the no-filter sentinel._SOURCE_CHOICES: tuple[str, ...] = (*LISTABLE_SOURCES, "all")@@ -79,23 +84,45 @@ def _describe_signature(acceptance) -> dict[str, str] | None:}-def _signer(agent: str, agent_session: str, *, accepter: str = "") -> tuple[str, str]:- """Validate the signing flags and return ``(kind, accepter_session)``.+@dataclass(frozen=True)+class _Signer:+ """Who signs an acceptance-log row: an agent by slug, or the repository's person."""++ agent: str+ kind: str+ session: str++ def name(self, repo_path: Path, override: str = "") -> str:+ from repowise.core.analysis.decisions.accepter import resolve_accepter++ return self.agent or resolve_accepter(repo_path, override=override)+++def _signer(agent: str, agent_session: str, *, accepter: str = "") -> _Signer:+ """Validate the signing flags and return who they sign as.Shared by every verb that appends to the acceptance log, so an agent cansay it is one wherever it can act."""+ _check_agent_flag(agent, accepter)+ _check_session_flag(agent_session, agent)+ return _Signer(agent=agent, kind="agent" if agent else "person", session=agent_session)+++def _check_agent_flag(agent: str, accepter: str) -> None:if agent and accepter:raise click.ClickException("Pass --agent or --as, not both: they name different signers.")if agent and not is_agent_slug(agent):raise click.ClickException(f"{agent!r} is not a well-formed agent slug (lowercase, digits and underscores).")+++def _check_session_flag(agent_session: str, agent: str) -> None:if agent_session and not agent:raise click.ClickException("--session names the agent signing; pass --agent too.")if len(agent_session) > ACCEPTER_SESSION_MAX:raise click.ClickException(f"--session is at most {ACCEPTER_SESSION_MAX} characters.")- return ("agent" if agent else "person"), agent_session#: The two flags an agent signs with, on every verb that writes an authority@@ -166,54 +193,26 @@ def _register_config_commands() -> None:_register_config_commands()-async def _resolve_decision_id(session, decision_id: str) -> str | None:- """Expand a (possibly truncated) decision id to the full stored id.-- ``decision list`` prints 8-char prefixes, so every id-taking subcommand- accepts a unique prefix. Returns None when nothing matches; raises on an- ambiguous prefix.- """- from sqlalchemy import select-- from repowise.core.persistence.models import DecisionRecord- from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like-- result = await session.execute(- select(DecisionRecord.id)- .where(DecisionRecord.id.like(f"{escape_like(decision_id)}%", escape=LIKE_ESCAPE))- .limit(2)- )- ids = [row[0] for row in result.all()]- if len(ids) > 1:- raise click.ClickException(- f"Decision id prefix {decision_id!r} is ambiguous; use more characters."- )- if ids:- return ids[0]-- # Merging and superseding retire ids that are already written down- # somewhere. Resolving through the alias keeps those working instead of- # reporting the decision as gone.- from repowise.core.persistence.models import DecisionAlias-- alias = await session.execute(- select(DecisionAlias.decision_id)- .where(DecisionAlias.alias_id.like(f"{escape_like(decision_id)}%", escape=LIKE_ESCAPE))- .limit(2)- )- alias_ids = [row[0] for row in alias.all()]- if len(alias_ids) > 1:- raise click.ClickException(- f"Decision id prefix {decision_id!r} is ambiguous; use more characters."- )- return alias_ids[0] if alias_ids else None--# ---------------------------------------------------------------------------# decision add# ---------------------------------------------------------------------------+@dataclass+class _DecisionFields:+ """The answers ``add`` records, whether they came from flags or prompts."""++ kind: str+ title: str | None+ context: str | None+ decision: str | None+ rationale: str | None+ alternatives: list[str]+ consequences: list[str]+ affected_files: list[str]+ tags: list[str]++@decision_group.command("add")@click.argument("path", required=False, default=None)@click.option("--title", default=None, help="Decision title (short).")@@ -271,182 +270,192 @@ def decision_add(inferring one from a diff has not, and the store should be able to tellthem apart. Promote with `repowise decision confirm <id>`."""- # Flags and prompts are the two paths, and a half-filled command line is- # neither: falling through to the prompts would hang a caller that has no- # stdin, which is the failure this command exists to stop having.non_interactive = bool(title and decision_text)if not non_interactive:- flagged = any((title, context, decision_text, rationale)) or any(- (alternatives, consequences, affected, tags, evidence_commits)+ _refuse_partial_flags(+ fmt,+ title, context, decision_text, rationale,+ alternatives, consequences, affected, tags, evidence_commits,)- if flagged or fmt == "json":- _ta.emit_error(- {- "error": "--title and --decision are both required to add a "- "decision without prompting.",- "guidance": "Run `repowise decision add` with no flags to be "- "prompted for each field instead.",- },- fmt,- )repo_path = _resolve_decision_repo(path, fmt)ensure_repowise_dir(repo_path)status = "proposed" if non_interactive else "active"- alternatives_list = list(alternatives)- consequences_list = list(consequences)- affected_files = list(affected)- tags_list = list(tags)+ if non_interactive:+ fields = _DecisionFields(+ kind=kind,+ title=title,+ context=context,+ decision=decision_text,+ rationale=rationale,+ alternatives=list(alternatives),+ consequences=list(consequences),+ affected_files=list(affected),+ tags=list(tags),+ )+ else:+ fields = _prompt_decision_fields(kind)- if not non_interactive:- console.print("[bold]Add Decision[/bold]\n")-- kind = click.prompt(- "Kind (architectural = about the code, agreement = about how we work)",- type=click.Choice(DECISION_KINDS),- # The flag, so `--kind agreement` alone is not silently discarded- # by falling through to the prompts.- default=kind,+ decision_id, stored_status = run_async(+ _persist_decision(repo_path, fields, status, list(evidence_commits))+ )+ if stored_status != "active" and not non_interactive:+ console.print(+ "[yellow]Stored as a candidate: it names no files, so it cannot be "+ "checked against the code.[/yellow]\n"+ f"[dim]repowise decision confirm {decision_id[:8]} --scope <path>[/dim]")- title = click.prompt("Decision title (short)")- context = click.prompt("Context (what forced this decision?)", default="")- decision_text = click.prompt("Decision (what was chosen?)")- rationale = click.prompt("Rationale (why?)", default="")- alternatives_raw = click.prompt(- "Rejected alternatives (comma-separated, optional)", default=""+ if fmt == "json":+ # The full id: a caller passes it back to `confirm` or `show`.+ emit_json(+ {+ "repo": str(repo_path),+ "decision": {+ "id": decision_id,+ "title": fields.title,+ "status": status,+ "kind": fields.kind,+ },+ })- alternatives_list = [a.strip() for a in alternatives_raw.split(",") if a.strip()]+ return+ console.print(+ f"\n[green]Decision recorded[/green] [dim]({status})[/dim] — "+ f"ID: [bold]{decision_id[:8]}[/bold]"+ )+- consequences_raw = click.prompt(- "Tradeoffs/consequences (comma-separated, optional)", default=""+def _refuse_partial_flags(fmt: str, *given) -> None:+ """Stop a half-filled command line before it reaches the prompts.++ Falling through to the prompts would hang a caller that has no stdin.+ """+ if any(given) or fmt == "json":+ _ta.emit_error(+ {+ "error": "--title and --decision are both required to add a "+ "decision without prompting.",+ "guidance": "Run `repowise decision add` with no flags to be "+ "prompted for each field instead.",+ },+ fmt,)- consequences_list = [c.strip() for c in consequences_raw.split(",") if c.strip()]- if kind == ARCHITECTURAL_KIND:- # An agreement names no file by definition, so asking is asking a- # question whose only right answer is blank.- affected_raw = click.prompt(++def _split_csv(raw: str) -> list[str]:+ return [part.strip() for part in raw.split(",") if part.strip()]+++def _prompt_decision_fields(kind: str) -> _DecisionFields:+ """Ask for each field in turn; *kind* is the flag's value, offered as default."""+ console.print("[bold]Add Decision[/bold]\n")++ kind = click.prompt(+ "Kind (architectural = about the code, agreement = about how we work)",+ type=click.Choice(DECISION_KINDS),+ # The flag, so `--kind agreement` alone is not silently discarded+ # by falling through to the prompts.+ default=kind,+ )+ title = click.prompt("Decision title (short)")+ context = click.prompt("Context (what forced this decision?)", default="")+ decision_text = click.prompt("Decision (what was chosen?)")+ rationale = click.prompt("Rationale (why?)", default="")+ alternatives = _split_csv(+ click.prompt("Rejected alternatives (comma-separated, optional)", default="")+ )+ consequences = _split_csv(+ click.prompt("Tradeoffs/consequences (comma-separated, optional)", default="")+ )+ affected_files: list[str] = []+ if kind == ARCHITECTURAL_KIND:+ # An agreement names no file by definition, so asking is asking a+ # question whose only right answer is blank.+ affected_files = _split_csv(+ click.prompt("Affected files/modules (comma-separated; required to make it govern)",default="",)- affected_files = [f.strip() for f in affected_raw.split(",") if f.strip()]-- tags_raw = click.prompt(+ )+ tags = _split_csv(+ click.prompt("Tags (comma-separated: auth, database, api, performance, security, infra, testing)",default="",)- tags_list = [t.strip() for t in tags_raw.split(",") if t.strip()]-- async def _persist() -> str:- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,- upsert_decision,- upsert_repository,- )+ )+ return _DecisionFields(+ kind=kind,+ title=title,+ context=context,+ decision=decision_text,+ rationale=rationale,+ alternatives=alternatives,+ consequences=consequences,+ affected_files=affected_files,+ tags=tags,+ )+- url = get_db_url_for_repo(repo_path)- engine = create_engine(url)- await init_db(engine)- sf = create_session_factory(engine)+async def _persist_decision(+ repo_path: Path, fields: _DecisionFields, status: str, evidence_commits: list[str]+) -> tuple[str, str]:+ """Write the record, accept it when the prompts earned that; return id and status."""+ from repowise.core.persistence import get_session, upsert_decision, upsert_repository+ async with _open_store(repo_path) as sf:async with get_session(sf) as session:repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))rec = await upsert_decision(session,repository_id=repo.id,- title=title,+ title=fields.title,status=status,- context=context or "",- decision=decision_text,- rationale=rationale or "",- alternatives=alternatives_list,- consequences=consequences_list,- affected_files=affected_files,+ context=fields.context or "",+ decision=fields.decision,+ rationale=fields.rationale or "",+ alternatives=fields.alternatives,+ consequences=fields.consequences,+ affected_files=fields.affected_files,# None derives them from the files; [] would clear them.affected_modules=None,- tags=tags_list,+ tags=fields.tags,# What the capture hook suppresses on: without it, the hook# asks again next session for a commit already recorded.- evidence_commits=list(evidence_commits),- kind=kind,+ evidence_commits=evidence_commits,+ kind=fields.kind,source="cli",# No confidence: upsert_decision scores a manual entry.)- decision_id = rec.id- # An architectural decision that names nothing cannot be checked- # against the code and cannot reach the agent editing a governed- # file, so it cannot be accepted. Keeping it as a candidate is- # better than discarding eight answered questions; ``confirm- # --scope`` finishes the job. An agreement is the other noun: it- # names no file *because* it is not about one, its acceptance row- # records the repository as its scope, and SessionStart is how it- # reaches an agent. Refusing it for the files it is defined not to- # have would leave it unacceptable, which is the defect the split- # exists to fix.- if status == "active" and (affected_files or kind == AGREEMENT_KIND):- # Answering the prompts is the acceptance; recording it as one- # is what makes this record indistinguishable from any other- # accepted decision to every reader.- from repowise.core.analysis.decisions.accepter import resolve_accepter- from repowise.core.persistence.crud.authority import (- AcceptanceRefusedError,- accept_decision,- )-- try:- await accept_decision(- session, rec, accepter=resolve_accepter(repo_path)- )- except AcceptanceRefusedError as exc:- raise click.ClickException(- f"Cannot accept this decision: {exc}."- ) from exc+ # An architectural decision needs files to govern, so without them+ # it stays a candidate for ``confirm --scope``. An agreement names no+ # file by definition; its scope is the repository.+ if status == "active" and (fields.affected_files or fields.kind == AGREEMENT_KIND):+ await _accept_answered_prompts(session, rec, repo_path)embed = (rec.id, rec.title, rec.decision or "", rec.evidence_file)stored_status = rec.status- # After the session closes, so a network embed does not hold the write- # transaction open and cannot leave a vector for an uncommitted record.- # ``cli`` is the rank a duplicate should fold into, so a manual entry- # with no vector is the worst one to leave unmatched.+ # After the session commits, so a network embed never holds the write+ # transaction or vectors an uncommitted record.await _embed_decision(repo_path, *embed)+ return embed[0], stored_status- await engine.dispose()- return decision_id, stored_status- decision_id, stored_status = run_async(_persist())- if stored_status != "active" and not non_interactive:- console.print(- "[yellow]Stored as a candidate: it names no files, so it cannot be "- "checked against the code.[/yellow]\n"- f"[dim]repowise decision confirm {decision_id[:8]} --scope <path>[/dim]"- )-- if fmt == "json":- # The full id, not the table's 8-char prefix — a caller that parses- # this is about to pass it back to `confirm` or `show`.- emit_json(- {- "repo": str(repo_path),- "decision": {- "id": decision_id,- "title": title,- "status": status,- "kind": kind,- },- }- )- return- console.print(- f"\n[green]Decision recorded[/green] [dim]({status})[/dim] — "- f"ID: [bold]{decision_id[:8]}[/bold]"+async def _accept_answered_prompts(session, rec, repo_path: Path) -> None:+ """Record the answered prompts as an acceptance, like any other."""+ from repowise.core.analysis.decisions.accepter import resolve_accepter+ from repowise.core.persistence.crud.authority import (+ AcceptanceRefusedError,+ accept_decision,)+ try:+ await accept_decision(session, rec, accepter=resolve_accepter(repo_path))+ except AcceptanceRefusedError as exc:+ raise click.ClickException(f"Cannot accept this decision: {exc}.") from exc+async def _embed_decision(repo_path: Path,@@ -522,70 +531,74 @@ def decision_list() -> None:"""List architectural decision records."""repo_path = _resolve_decision_repo(path, fmt)-- async def _query() -> list:- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,- list_decisions,- upsert_repository,+ decisions = run_async(+ _query_decisions(+ repo_path,+ status=status if status != "all" else ("proposed" if proposed else None),+ source=source if source != "all" else None,)+ )- url = get_db_url_for_repo(repo_path)- engine = create_engine(url)- await init_db(engine)- sf = create_session_factory(engine)+ decisions = _narrow(decisions, proposed=proposed, stale_only=stale_only)- async with get_session(sf) as session:- repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))- decisions = await list_decisions(- session,- repo.id,- status=status if status != "all" else ("proposed" if proposed else None),- source=source if source != "all" else None,- include_proposed=True,- limit=100,- )+ if fmt == "json":+ emit_json({"repo": str(repo_path), "decisions": [_listed_json(d) for d in decisions]})+ return- await engine.dispose()- return decisions+ if not decisions:+ console.print("[dim]No decisions found.[/dim]")+ return+ _print_decision_table(decisions)- decisions = run_async(_query())+def _narrow(decisions: list, *, proposed: bool, stale_only: bool) -> list:+ """Apply ``--proposed`` and ``--stale-only`` to what the query returned."""if proposed:decisions = [d for d in decisions if d.status == "proposed"]if stale_only:decisions = [d for d in decisions if d.staleness_score >= 0.5]+ return decisions- if fmt == "json":- emit_json(- {- "repo": str(repo_path),- "decisions": [- {- # Full id, not the table's 8-char prefix: the prefix- # exists to fit a column, and every id-taking- # subcommand accepts either.- "id": d.id,- "title": d.title,- "status": d.status,- "source": d.source,- "confidence": d.confidence,- "staleness_score": d.staleness_score,- "created_at": d.created_at.isoformat() if d.created_at else None,- }- for d in decisions- ],- }++def _listed_json(d) -> dict:+ return {+ # Full id, not the table's 8-char prefix: the prefix exists to fit a+ # column, and every id-taking subcommand accepts either.+ "id": d.id,+ "title": d.title,+ "status": d.status,+ "source": d.source,+ "confidence": d.confidence,+ "staleness_score": d.staleness_score,+ "created_at": d.created_at.isoformat() if d.created_at else None,+ }+++async def _query_decisions(repo_path: Path, *, status: str | None, source: str | None) -> list:+ from repowise.core.persistence import get_session, list_decisions, upsert_repository++ async with _open_store(repo_path) as sf, get_session(sf) as session:+ repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))+ return await list_decisions(+ session,+ repo.id,+ status=status,+ source=source,+ include_proposed=True,+ limit=100,)- return- if not decisions:- console.print("[dim]No decisions found.[/dim]")- return+_STATUS_COLORS = {+ "active": "green",+ "proposed": "yellow",+ "deprecated": "red",+ "superseded": "dim",+ "dismissed": "dim",+}+++def _print_decision_table(decisions: list) -> None:table = Table(title="Architectural Decisions")table.add_column("ID", style="dim", width=8)table.add_column("Title", max_width=40)@@ -595,16 +608,8 @@ def decision_list(table.add_column("Stale", justify="right")table.add_column("Created", style="dim")- status_colors = {- "active": "green",- "proposed": "yellow",- "deprecated": "red",- "superseded": "dim",- "dismissed": "dim",- }-for d in decisions:- color = status_colors.get(d.status, "white")+ color = _STATUS_COLORS.get(d.status, "white")stale_str = f"{d.staleness_score:.1f}" if d.staleness_score > 0 else "-"created = d.created_at.strftime("%Y-%m-%d") if d.created_at else ""table.add_row(@@ -632,32 +637,7 @@ def decision_list(def decision_show(decision_id: str, path: str | None, fmt: str) -> None:"""Show full details of a decision record."""repo_path = _resolve_decision_repo(path, fmt)-- async def _query():- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_decision,- get_session,- init_db,- )- from repowise.core.persistence.crud.authority import latest_acceptance-- url = get_db_url_for_repo(repo_path)- engine = create_engine(url)- await init_db(engine)- sf = create_session_factory(engine)-- async with get_session(sf) as session:- full_id = await _resolve_decision_id(session, decision_id)- rec = await get_decision(session, full_id) if full_id else None- acceptance = await latest_acceptance(session, rec.id) if rec else None- signed = _describe_signature(acceptance)-- await engine.dispose()- return rec, signed-- rec, signed = run_async(_query())+ rec, signed = run_async(_load_decision(repo_path, decision_id))if rec is None:notice_console(fmt).print(f"[red]Decision not found: {decision_id}[/red]")if fmt == "json":@@ -666,80 +646,90 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:# scripting `show` cannot tell a missing id from an empty record.raise click.exceptions.Exit(1)+ # Asked of git at read time: affordable for one record on demand, never on+ # the hook or update path. None means git could not decide.+ currency = describe_decision_currency(+ repo_path,+ created_at=rec.created_at,+ nodes=json.loads(rec.affected_files_json or "[]"),+ )if fmt == "json":- emit_json(- {- "query": decision_id,- "decision": {- "id": rec.id,- "title": rec.title,- "status": rec.status,- "source": rec.source,- "confidence": rec.confidence,- "staleness_score": rec.staleness_score,- "created_at": rec.created_at.isoformat() if rec.created_at else None,- # Not "accepted_by": the same log records withdrawals.- "signature": signed,- "currency": describe_decision_currency(- repo_path,- created_at=rec.created_at,- nodes=json.loads(rec.affected_files_json or "[]"),- ),- "context": rec.context,- "decision": rec.decision,- "rationale": rec.rationale,- "alternatives": json.loads(rec.alternatives_json),- "consequences": json.loads(rec.consequences_json),- # Not clipped to 10 the way the panel clips it: the panel- # clips to stay readable, and a caller asking for json is- # asking for the record, not a summary of it.- "affected_files": json.loads(rec.affected_files_json),- "tags": json.loads(rec.tags_json),- "evidence_file": rec.evidence_file,- "evidence_line": rec.evidence_line,- },- }- )+ emit_json({"query": decision_id, "decision": _decision_json(rec, signed, currency)})return+ lines = _decision_header_lines(rec, signed, currency) + _decision_body_lines(rec)+ console.print(Panel("\n".join(lines), title=f"Decision {rec.id[:8]}"))+++async def _load_decision(repo_path: Path, decision_id: str):+ """The record *decision_id* names and its signature, or ``(None, None)``."""+ from repowise.core.persistence import get_decision, get_session+ from repowise.core.persistence.crud.authority import latest_acceptance++ async with _open_store(repo_path) as sf, get_session(sf) as session:+ full_id = await _resolve_decision_id(session, decision_id)+ rec = await get_decision(session, full_id) if full_id else None+ acceptance = await latest_acceptance(session, rec.id) if rec else None+ return rec, _describe_signature(acceptance)++def _decision_json(rec, signed, currency) -> dict:+ return {+ "id": rec.id,+ "title": rec.title,+ "status": rec.status,+ "source": rec.source,+ "confidence": rec.confidence,+ "staleness_score": rec.staleness_score,+ "created_at": rec.created_at.isoformat() if rec.created_at else None,+ # Not "accepted_by": the same log records withdrawals.+ "signature": signed,+ "currency": currency,+ "context": rec.context,+ "decision": rec.decision,+ "rationale": rec.rationale,+ "alternatives": json.loads(rec.alternatives_json),+ "consequences": json.loads(rec.consequences_json),+ # Unclipped: json is the record, the panel a summary.+ "affected_files": json.loads(rec.affected_files_json),+ "tags": json.loads(rec.tags_json),+ "evidence_file": rec.evidence_file,+ "evidence_line": rec.evidence_line,+ }+++def _decision_header_lines(rec, signed, currency) -> list[str]:lines = [f"[bold]{rec.title}[/bold]",f"Status: {rec.status} | Source: {rec.source} | Confidence: {rec.confidence:.0%}",f"Staleness: {rec.staleness_score:.2f}",]- # The stored score is a proportion; this is the fact behind it, asked of- # git at read time. `show` is one record on demand, which is exactly where- # a subprocess is affordable — nothing on the hook or update path may do- # this. None means git could not decide, and then we say nothing.- currency = describe_decision_currency(- repo_path,- created_at=rec.created_at,- nodes=json.loads(rec.affected_files_json or "[]"),- )if currency:lines.append(f"[dim]{currency}[/dim]")# A candidate has no line at all; status already says so.if signed:lines.append(f"{signed['verb']} by: {signed['label']}")lines.append("")- if rec.context:- lines.append(f"[cyan]Context:[/cyan] {rec.context}")- if rec.decision:- lines.append(f"[cyan]Decision:[/cyan] {rec.decision}")- if rec.rationale:- lines.append(f"[cyan]Rationale:[/cyan] {rec.rationale}")-- alternatives = json.loads(rec.alternatives_json)- if alternatives:- lines.append("[cyan]Alternatives rejected:[/cyan]")- for a in alternatives:- lines.append(f" - {a}")-- consequences = json.loads(rec.consequences_json)- if consequences:- lines.append("[cyan]Consequences:[/cyan]")- for c in consequences:- lines.append(f" - {c}")+ return lines+++def _decision_body_lines(rec) -> list[str]:+ """The record's prose and lists, each section only when it has content."""+ lines = [+ f"[cyan]{label}:[/cyan] {value}"+ for label, value in (+ ("Context", rec.context),+ ("Decision", rec.decision),+ ("Rationale", rec.rationale),+ )+ if value+ ]+ for heading, items in (+ ("Alternatives rejected", json.loads(rec.alternatives_json)),+ ("Consequences", json.loads(rec.consequences_json)),+ ):+ if items:+ lines.append(f"[cyan]{heading}:[/cyan]")+ lines.extend(f" - {item}" for item in items)affected = json.loads(rec.affected_files_json)if affected:@@ -754,27 +744,7 @@ def decision_show(decision_id: str, path: str | None, fmt: str) -> None:if rec.evidence_line:loc += f":{rec.evidence_line}"lines.append(f"[cyan]Evidence:[/cyan] {loc}")-- console.print(Panel("\n".join(lines), title=f"Decision {rec.id[:8]}"))----def _emit_lifecycle(rec, decision_id: str, action: str, fmt: str, note: str = "") -> None:- """Report one status transition to a person or to a machine.-- Not found exits non-zero: an agent driving the lifecycle could not tell a- typo'd id from a successful confirm when both returned 0.- """- if rec is None:- if fmt == "json":- emit_json({"error": "decision_not_found", "decision_id": decision_id})- else:- console.print(f"[red]Decision not found: {decision_id}[/red]")- raise click.exceptions.Exit(1)- if fmt == "json":- emit_json({"id": rec.id, "status": rec.status, "action": action})- return- console.print(f"[green]Decision {rec.id[:8]} {action}[/green]" + (f" {note}" if note else ""))+ return lines# ---------------------------------------------------------------------------@@ -787,172 +757,6 @@ def _emit_lifecycle(rec, decision_id: str, action: str, fmt: str, note: str = ""_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, remedy: 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),- # Once for the run: every refusal here is the same verb.- **({"remedy": remedy} if failed and remedy else {}),- }- )- 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:- if remedy:- console.print(f"[dim]{remedy}[/dim]")- 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")@click.argument("decision_ids", nargs=-1, required=True)@click.option("--reason", default="", help="Rationale, or why the constraint needs none.")@@ -1002,19 +806,18 @@ def decision_confirm(ids, path = _split_ids_and_path(decision_ids)repo_path = _resolve_decision_repo(path, fmt)- kind, signing_session = _signer(agent, agent_session, accepter=accepter)+ signer = _signer(agent, agent_session, accepter=accepter)granted = _load_policy(repo_path).agent_acceptance if agent else Falseasync def _accept(session, rec) -> None:- from repowise.core.analysis.decisions.accepter import resolve_accepterfrom repowise.core.persistence.crud.authority import accept_decisionawait accept_decision(session,rec,- accepter=agent or resolve_accepter(repo_path, override=accepter),- kind=kind,- accepter_session=signing_session,+ accepter=signer.name(repo_path, override=accepter),+ kind=signer.kind,+ accepter_session=signer.session,agent_acceptance=granted,reason=reason,scope=list(scope) or None,@@ -1061,26 +864,22 @@ def decision_dismiss("""ids, path = _split_ids_and_path(decision_ids)repo_path = _resolve_decision_repo(path, fmt)- kind, signing_session = _signer(agent, agent_session)+ signer = _signer(agent, agent_session)- # A machine-readable invocation is non-interactive by construction: the- # prompt read EOF and aborted every scripted dismissal.- 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}?"):+ if not _dismissal_confirmed(ids, yes=yes, preview=preview, fmt=fmt):console.print("[yellow]Cancelled.[/yellow]")returnasync def _dismiss(session, rec) -> None:- from repowise.core.analysis.decisions.accepter import resolve_accepterfrom repowise.core.persistence.crud.authority import dismiss_candidateawait dismiss_candidate(session,rec,reason=reason,- accepter=agent or resolve_accepter(repo_path),- kind=kind,- accepter_session=signing_session,+ accepter=signer.name(repo_path),+ kind=signer.kind,+ accepter_session=signer.session,)results = run_async(@@ -1101,6 +900,18 @@ def decision_dismiss()+def _dismissal_confirmed(ids: list[str], *, yes: bool, preview: bool, fmt: str) -> bool:+ """Ask before dismissing, unless ``--yes``, ``--preview`` or json skips the prompt.++ A machine-readable invocation is non-interactive by construction, so a+ prompt there would read EOF and abort a scripted dismissal.+ """+ if yes or preview or fmt == "json":+ return True+ subject = ids[0][:8] if len(ids) == 1 else f"{len(ids)} decisions"+ return click.confirm(f"Dismiss {subject}?")++# ---------------------------------------------------------------------------# decision deprecate# ---------------------------------------------------------------------------@@ -1127,78 +938,67 @@ def decision_deprecate(exists because somebody named the successor."""repo_path = _resolve_decision_repo(path, fmt)- kind, signing_session = _signer(agent, agent_session)+ signer = _signer(agent, agent_session)async def _update():- from repowise.core.analysis.decisions.accepter import resolve_accepter- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- init_db,- update_decision_status,- )- from repowise.core.persistence.crud.authority import (- AcceptanceRefusedError,- is_accepted,- supersede_decision,- )+ from repowise.core.persistence import get_sessionfrom 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- successor = (- await _resolve_decision_id(session, superseded_by)- if superseded_by- else None+ async with _open_store(repo_path) as sf, get_session(sf) as session:+ full_id = await _resolve_decision_id(session, decision_id)+ rec = await session.get(DecisionRecord, full_id) if full_id else None+ if rec is None:+ return None+ successor = (+ await _resolve_decision_id(session, superseded_by) if superseded_by else None+ )+ if superseded_by and successor is None:+ emit_refusal(+ "decision_not_found",+ f"Unknown successor: {superseded_by}",+ fmt,+ decision_id=superseded_by,)- if superseded_by and successor is None:- emit_refusal(- "decision_not_found",- f"Unknown successor: {superseded_by}",- fmt,- decision_id=superseded_by,- )- if successor and await is_accepted(session, rec.id):- try:- await supersede_decision(- session,- rec,- successor_id=successor,- accepter=agent or resolve_accepter(repo_path),- kind=kind,- accepter_session=signing_session,- )- except (AcceptanceRefusedError, ValueError) as exc:- emit_refusal("supersede_refused", str(exc), fmt, decision_id=rec.id)- else:- # A candidate has no authority to retire, so this stays the- # plain status change it always was. An accepted record- # reaching it still logs a withdrawal, so the kind travels.- await update_decision_status(- session,- rec.id,- "deprecated",- superseded_by=successor,- accepter=agent or resolve_accepter(repo_path),- kind=kind,- )- return rec- finally:- await engine.dispose()+ await _retire(session, rec, successor, signer=signer, repo_path=repo_path, fmt=fmt)+ return rec_emit_lifecycle(run_async(_update()), decision_id, "deprecated", fmt)+async def _retire(session, rec, successor, *, signer: _Signer, repo_path: Path, fmt: str) -> None:+ """Supersede an accepted record, or mark any other one deprecated."""+ from repowise.core.persistence import update_decision_status+ from repowise.core.persistence.crud.authority import (+ AcceptanceRefusedError,+ is_accepted,+ supersede_decision,+ )++ if successor and await is_accepted(session, rec.id):+ try:+ await supersede_decision(+ session,+ rec,+ successor_id=successor,+ accepter=signer.name(repo_path),+ kind=signer.kind,+ accepter_session=signer.session,+ )+ except (AcceptanceRefusedError, ValueError) as exc:+ emit_refusal("supersede_refused", str(exc), fmt, decision_id=rec.id)+ return+ # A candidate has no authority to retire: a plain status change. An+ # accepted record reaching here still logs a withdrawal, with its kind.+ await update_decision_status(+ session,+ rec.id,+ "deprecated",+ superseded_by=successor,+ accepter=signer.name(repo_path),+ kind=signer.kind,+ )++# ---------------------------------------------------------------------------# decision health# ---------------------------------------------------------------------------@@ -1210,31 +1010,7 @@ def decision_deprecate(def decision_health(path: str | None, fmt: str) -> None:"""Show decision health: stale decisions, proposed, ungoverned hotspots."""repo_path = _resolve_decision_repo(path, fmt)-- async def _query():- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_decision_health_summary,- get_session,- init_db,- upsert_repository,- )-- url = get_db_url_for_repo(repo_path)- engine = create_engine(url)- await init_db(engine)- sf = create_session_factory(engine)-- async with get_session(sf) as session:- repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))- health = await get_decision_health_summary(session, repo.id)-- await engine.dispose()- return health-- health = run_async(_query())- summary = health["summary"]+ health = run_async(_query_health(repo_path))if fmt == "json":# The table caps each list (5 stale, 10 hotspots, 5 proposed) to keep@@ -1242,7 +1018,7 @@ def decision_health(path: str | None, fmt: str) -> None:emit_json({"repo": str(repo_path),- "summary": summary,+ "summary": health["summary"],"stale_decisions": [{"id": d.id, "title": d.title, "staleness_score": d.staleness_score}for d in health["stale_decisions"]@@ -1257,8 +1033,23 @@ def decision_health(path: str | None, fmt: str) -> None:returnconsole.print("[bold]Decision Health[/bold]\n")+ _print_health_summary(health["summary"])+ _print_health_lists(health)+++async def _query_health(repo_path: Path) -> dict:+ from repowise.core.persistence import (+ get_decision_health_summary,+ get_session,+ upsert_repository,+ )++ async with _open_store(repo_path) as sf, get_session(sf) as session:+ repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))+ return await get_decision_health_summary(session, repo.id)- # Summary stats++def _print_health_summary(summary: dict) -> None:stats_table = Table(show_header=False, box=None)stats_table.add_column("Metric", style="cyan")stats_table.add_column("Value", justify="right")@@ -1273,23 +1064,30 @@ def decision_health(path: str | None, fmt: str) -> None:stats_table.add_row("Deprecated", str(summary.get("deprecated", 0)))console.print(stats_table)- # Stale decisions- stale = health["stale_decisions"]- if stale:- console.print(f"\n[red]Stale decisions ({len(stale)}):[/red]")- for d in stale[:5]:- console.print(f" {d.id[:8]} {d.title[:50]} (staleness: {d.staleness_score:.2f})")-- # Ungoverned hotspots- ungoverned = health["ungoverned_hotspots"]- if ungoverned:- console.print(f"\n[yellow]Ungoverned hotspots ({len(ungoverned)}):[/yellow]")- for fp in ungoverned[:10]:- console.print(f" {fp}")-- # Proposed- proposed = health["proposed_awaiting_review"]- if proposed:- console.print(f"\n[yellow]Proposed decisions ({len(proposed)}):[/yellow]")- for d in proposed[:5]:- console.print(f" {d.id[:8]} {d.title[:50]} (source: {d.source})")++def _print_health_lists(health: dict) -> None:+ """Stale, ungoverned and proposed, each capped so the report stays short."""+ _print_capped(+ "red",+ "Stale decisions",+ health["stale_decisions"],+ 5,+ lambda d: f"{d.id[:8]} {d.title[:50]} (staleness: {d.staleness_score:.2f})",+ )+ _print_capped("yellow", "Ungoverned hotspots", health["ungoverned_hotspots"], 10, str)+ _print_capped(+ "yellow",+ "Proposed decisions",+ health["proposed_awaiting_review"],+ 5,+ lambda d: f"{d.id[:8]} {d.title[:50]} (source: {d.source})",+ )+++def _print_capped(color: str, heading: str, items: list, cap: int, line) -> None:+ """A headed list with its full count, showing the first *cap* items."""+ if not items:+ return+ console.print(f"\n[{color}]{heading} ({len(items)}):[/{color}]")+ for item in items[:cap]:+ console.print(f" {line(item)}")diff --git a/tests/unit/cli/test_decision_cmd_output.py b/tests/unit/cli/test_decision_cmd_output.pynew file mode 100644index 000000000..7434d99b0--- /dev/null+++ b/tests/unit/cli/test_decision_cmd_output.py@@ -0,0 +1,300 @@+"""What ``decision add/list/show/health`` and a multi-id run print.++``test_decision_cmd.py`` pins the lifecycle; this file pins each report's+fields, in the table a person reads and the json an agent parses.+"""++from __future__ import annotations++import json+import sqlite3+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++[email protected](autouse=True)+def _no_embedder(monkeypatch):+ """``add`` embeds the new record; a keyless embedder keeps that local."""+ import repowise.cli.providers.embedders as embedders+ from repowise.core.providers.embedding.base import KeylessEmbedder++ monkeypatch.setattr(embedders, "resolve_embedder_for_repo", lambda p: "keyless")+ monkeypatch.setattr(embedders, "build_embedder", lambda name, p: KeylessEmbedder())+++def repo(tmp_path: Path) -> Path:+ root = tmp_path / "repo"+ (root / ".repowise").mkdir(parents=True)+ return root+++_SEED = [+ {"id": "aaaaaaaa11111111", "title": "Active one", "status": "active", "staleness": 0.7},+ {+ "id": "bbbbbbbb22222222",+ "title": "Proposed one",+ "status": "proposed",+ "confidence": 0.4,+ "source": "git_archaeology",+ },+ {"id": "cccccccc33333333", "title": "Deprecated", "status": "deprecated"},+ {+ "id": "dddddddd44444444",+ "title": "Candidate",+ "status": "proposed",+ "affected_files": [],+ "rationale": "",+ },+]+++def seeded(repo: Path) -> Path:+ _seed_wiki_db(repo, _SEED)+ conn = sqlite3.connect(repo / ".repowise" / "wiki.db")+ conn.execute(+ "UPDATE decision_records SET alternatives_json = ?, consequences_json = ?, "+ "tags_json = ?, evidence_line = ?, affected_files_json = ? WHERE id = ?",+ (+ json.dumps(["alt1", "alt2"]),+ json.dumps(["c1"]),+ json.dumps(["t1", "t2"]),+ 42,+ json.dumps([f"f{i}.py" for i in range(12)]),+ "aaaaaaaa11111111",+ ),+ )+ conn.commit()+ conn.close()+ return repo+++def _run(*args: str, input: str | None = None):+ # Keep stderr out of stdout on click 8.1 (8.2 always separates them).+ import inspect++ split = "mix_stderr" in inspect.signature(CliRunner.__init__).parameters+ runner = CliRunner(mix_stderr=False) if split else CliRunner()+ return runner.invoke(cli, ["decision", *args], input=input)+++def _json(*args: str) -> dict:+ result = _run(*args, "--format", "json")+ return json.loads(result.stdout)+++# -- show ---------------------------------------------------------------------+++def test_show_panel_carries_every_filled_field(seeded: Path) -> None:+ result = _run("show", "aaaaaaaa", str(seeded))+ assert result.exit_code == 0, result.output+ out = result.output+ for line in (+ "Active one",+ "Status: active | Source: cli | Confidence: 90%",+ "Staleness: 0.70",+ "Context: forced by Z",+ "Decision: use X",+ "Rationale: because Y",+ "Alternatives rejected:",+ " - alt1",+ "Consequences:",+ " - c1",+ "Tags: t1, t2",+ "Evidence: aaaaaaaa11111111:42",+ ):+ assert line in out, line+ # The panel clips scope to ten entries to stay readable.+ assert "f9.py" in out+ assert "f10.py" not in out+++def test_show_panel_omits_empty_sections(seeded: Path) -> None:+ out = _run("show", "dddddddd", str(seeded)).output+ assert "Rationale:" not in out+ assert "Alternatives rejected:" not in out+ assert "Affected files:" not in out+ assert "Evidence: dddddddd44444444" in out+++def test_show_json_is_the_whole_record(seeded: Path) -> None:+ payload = _json("show", "aaaaaaaa", str(seeded))+ assert payload["query"] == "aaaaaaaa"+ record = payload["decision"]+ assert record["id"] == "aaaaaaaa11111111"+ assert record["alternatives"] == ["alt1", "alt2"]+ assert record["consequences"] == ["c1"]+ assert record["tags"] == ["t1", "t2"]+ assert len(record["affected_files"]) == 12, "json is never clipped"+ assert record["evidence_line"] == 42+ assert record["signature"] is None+++def test_show_unknown_id_exits_nonzero_in_both_formats(seeded: Path) -> None:+ table = _run("show", "9999", str(seeded))+ assert table.exit_code == 1+ assert "Decision not found: 9999" in table.stdout+ as_json = _run("show", "9999", str(seeded), "--format", "json")+ assert as_json.exit_code == 1+ assert json.loads(as_json.stdout) == {"query": "9999", "decision": None}+++# -- list ---------------------------------------------------------------------+++def test_list_json_carries_full_ids(seeded: Path) -> None:+ payload = _json("list", str(seeded))+ assert payload["repo"] == str(seeded)+ by_id = {d["id"]: d for d in payload["decisions"]}+ assert set(by_id) == {d["id"] for d in _SEED}+ assert by_id["bbbbbbbb22222222"]["source"] == "git_archaeology"+ assert by_id["aaaaaaaa11111111"]["staleness_score"] == 0.7+++def test_list_filters(seeded: Path) -> None:+ def ids(*flags: str) -> set[str]:+ return {d["id"][:8] for d in _json("list", str(seeded), *flags)["decisions"]}++ assert ids("--proposed") == {"bbbbbbbb", "dddddddd"}+ assert ids("--stale-only") == {"aaaaaaaa"}+ assert ids("--source", "git_archaeology") == {"bbbbbbbb"}+ assert ids("--status", "deprecated") == {"cccccccc"}+++def test_list_table_rows(seeded: Path) -> None:+ out = _run("list", str(seeded)).output+ assert "Architectural Decisions" in out+ assert "aaaaaaaa" in out and "Active one" in out+ assert "40%" in out+ assert "0.7" in out+++# -- health -------------------------------------------------------------------+++def accepted(seeded: Path) -> Path:+ """Health counts a decision as active only once it has been accepted."""+ assert _run("confirm", "aaaaaaaa", str(seeded)).exit_code == 0+ return seeded+++def test_health_json_carries_whole_lists(accepted: Path) -> None:+ payload = _json("health", str(accepted))+ assert payload["repo"] == str(accepted)+ assert payload["summary"]["active"] == 1+ assert [d["id"] for d in payload["stale_decisions"]] == ["aaaaaaaa11111111"]+ proposed = {d["id"]: d["source"] for d in payload["proposed_awaiting_review"]}+ assert proposed["bbbbbbbb22222222"] == "git_archaeology"+ assert isinstance(payload["ungoverned_hotspots"], list)+++def test_health_table_sections(accepted: Path) -> None:+ out = _run("health", str(accepted)).output+ assert "Decision Health" in out+ assert "Stale decisions (1):" in out+ assert "aaaaaaaa Active one (staleness: 0.70)" in out+ assert "Proposed decisions (2):" in out+ assert "(source: git_archaeology)" in out+++def test_health_on_an_empty_store(repo: Path) -> None:+ result = _run("health", str(repo))+ assert result.exit_code == 0, result.output+ assert "Stale decisions (" not in result.output+ assert "Proposed decisions (" not in result.output+++# -- add ----------------------------------------------------------------------+++def test_add_json_echoes_the_full_id(repo: Path) -> None:+ payload = _json("add", str(repo), "--title", "T", "--decision", "D", "--kind", "agreement")+ assert payload["repo"] == str(repo)+ record = payload["decision"]+ assert len(record["id"]) == 32+ assert record == {**record, "title": "T", "status": "proposed", "kind": "agreement"}+++def test_add_json_without_flags_refuses_rather_than_prompting(repo: Path) -> None:+ result = _run("add", str(repo), "--format", "json")+ assert result.exit_code == 1+ assert "--title and --decision are both required" in json.loads(result.stdout)["error"]+++def test_add_prompts_split_comma_lists(repo: Path) -> None:+ answers = "architectural\nPrompted\nctx\nChose\nwhy\na, b\nc1\nsrc/x.py, src/y.py\nauth, api\n"+ result = _run("add", str(repo), input=answers)+ assert result.exit_code == 0, result.output+ assert "Decision recorded (active)" in result.output+ (decision,) = _json("list", str(repo))["decisions"]+ shown = _json("show", decision["id"], str(repo))["decision"]+ assert shown["alternatives"] == ["a", "b"]+ assert shown["consequences"] == ["c1"]+ assert shown["affected_files"] == ["src/x.py", "src/y.py"]+ assert shown["tags"] == ["auth", "api"]+ assert shown["context"] == "ctx"+++def test_add_prompts_without_files_says_how_to_finish(repo: Path) -> None:+ answers = "architectural\nNo files\n\nChose\n\n\n\n\n\n"+ result = _run("add", str(repo), input=answers)+ assert result.exit_code == 0, result.output+ assert "Stored as a candidate" in result.output+ assert "--scope <path>" in result.output+++# -- multi-id runs and deprecate ------------------------------------------------+++def test_batch_table_counts_and_names_each_outcome(seeded: Path) -> None:+ result = _run("confirm", "bbbbbbbb", "dddddddd", "9999", str(seeded))+ assert result.exit_code == 1+ out = result.output+ assert "Accepted 1 of 3" in out+ assert "Decision not found: 9999" in out+ assert "Supply the missing parts with --reason, --scope or --evidence." in out+++def test_batch_json_summarises_the_run(seeded: Path) -> None:+ result = _run("confirm", "bbbbbbbb", "dddddddd", str(seeded), "--format", "json")+ assert result.exit_code == 1+ payload = json.loads(result.stdout)+ assert payload["action"] == "accepted"+ assert payload["preview"] is False+ assert (payload["succeeded"], payload["failed"]) == (1, 1)+ assert payload["remedy"].startswith("Supply the missing parts")+++def test_a_clean_preview_says_nothing_was_written(seeded: Path) -> None:+ result = _run("dismiss", "bbbbbbbb", str(seeded), "--preview")+ assert result.exit_code == 0, result.output+ assert "Would dismiss 1 of 1" in result.output+ assert "Nothing was written. Re-run without --preview." in result.output+++def test_dismiss_can_be_cancelled_at_the_prompt(seeded: Path) -> None:+ result = _run("dismiss", "dddddddd", str(seeded), input="n\n")+ assert result.exit_code == 0+ assert "Cancelled." in result.output+ assert _json("show", "dddddddd", str(seeded))["decision"]["status"] == "proposed"+++def test_deprecate_refuses_an_unknown_successor(seeded: Path) -> None:+ result = _run("deprecate", "aaaaaaaa", str(seeded), "--superseded-by", "9999", "--format", "json")+ assert result.exit_code == 1+ assert json.loads(result.stdout)["error"] == "decision_not_found"+ assert _json("show", "aaaaaaaa", str(seeded))["decision"]["status"] == "active"+++def test_deprecate_json_reports_the_transition(seeded: Path) -> None:+ payload = _json("deprecate", "bbbbbbbb", str(seeded))+ assert payload == {"id": "bbbbbbbb22222222", "status": "deprecated", "action": "deprecated"}