Skip to content

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

feat(cli): roll --format json across the agent-facing commands (#1407)

Raghav Chamadiyadf58714bd823
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 32a9a82ab..4a714361f 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -445,6 +445,7 @@ Show wiki sync state, page statistics, and coverage.
repowise status # auto-detects mode
repowise status --workspace # all workspace repos
repowise status --no-workspace # force single-repo even in a workspace
+repowise status --format json # machine-readable
```
In workspace mode, the table includes a **Docs** column with each repo's page count and a per-repo **Docs status** block listing skip reasons (e.g. `cost gate declined`) and the exact remediation command.
@@ -542,12 +543,12 @@ not re-run the working-tree scan.
| `--to <rev>` | Upper git revision bound (inclusive). Defaults to HEAD / all history |
| `--path <dir>` | Repo path (defaults to cwd / workspace primary) |
| `--all-patterns` | History mode: also report code-smell patterns (`eval`, `os.system`, weak hashes, …). Default history mode reports only leaked-secret patterns (`hardcoded_password` / `hardcoded_secret`) to avoid noise |
-| `--output` | `table` (default) or `json` |
+| `--format` | `table` (default) or `json`. `--output` is a deprecated alias, still accepted; when both are given `--output` wins |
```bash
repowise security scan --history
repowise security scan --history --since v1.0.0 --to HEAD
-repowise security scan --history --all-patterns --output json
+repowise security scan --history --all-patterns --format json
```
Findings are written to the `security_findings` table (idempotent on re-run)
@@ -656,6 +657,9 @@ repowise decision health [PATH] # health dashboard
| `--source` | `adr`, `cli`, `comment`, `commit`, `git_archaeology`, `inline_marker`, `llm_inferred`, `pr`, `session`, `all` |
| `--proposed` | Shortcut for `--status proposed` |
| `--stale-only` | Only stale decisions |
+| `--format` | `table` (default) or `json` |
+
+`--format json` is also available on `decision show` and `decision health`. In JSON, `decision list` emits full ids rather than the table's 8-character prefixes, and `show` / `health` skip the caps the human output applies to keep a panel readable.
---
@@ -699,6 +703,7 @@ repowise coverage add --verbose # show ingestion debug logs
coverage run --contexts=test -m pytest # produce .coverage with contexts
repowise coverage add .coverage # per-file coverage + per-test map
repowise coverage status # coverage summary + "Test-to-code map" counts
+repowise coverage status --format json # machine-readable (note: the --format on `coverage add` names the input parser instead)
```
> The per-test map is a separate dimension from the per-file aggregate that
@@ -759,6 +764,9 @@ distill filters.
| `--model` | Pricing model for the dollar estimate (input-token rate). Defaults to the model detected from this repo's most recent agent session, falling back to `claude-sonnet-4-6` |
| `--missed` | Report commands that looked distillable but weren't rewritten |
| `--missed-days` | Window in days for `--missed` (default 7.0) |
+| `--format` | `table` (default) or `json` |
+
+JSON folds the table, the net, and every trailing advisory line into one document.
```bash
repowise saved # per-filter rollup + totals
@@ -781,6 +789,7 @@ default; entirely local. See [DISTILL.md](../agent/DISTILL.md#repowise-correctio
| `--days` | Transcript window for the scan (default 30) |
| `--write` | Maintain the "Known command corrections" managed block in `.claude/CLAUDE.md` / `AGENTS.md` (opt-in) |
| `--min-count` | Occurrences a rule needs before `--write` includes it (default 2) |
+| `--format` | `table` (default) or `json` |
```bash
repowise corrections # report recurring fumbles
@@ -800,6 +809,7 @@ Show LLM spend tracking.
| `--repo` | Scope to a specific workspace repo |
| `--all` | Aggregate across every workspace repo |
| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
+| `--format` | `table` (default) or `json` |
```bash
repowise costs # auto-detects mode
@@ -898,11 +908,11 @@ Explain the cross-repo contract link count: per-repo provider/consumer counts, u
| Flag | Description |
|------|-------------|
| `--repo` | Limit the report to one repo alias |
-| `--json` | Emit raw diagnostics JSON |
+| `--format` | `table` (default) or `json`. `--json` is a deprecated alias, still accepted |
```bash
repowise workspace diagnostics # human-readable report
-repowise workspace diagnostics --json # raw JSON
+repowise workspace diagnostics --format json # raw JSON
repowise workspace diagnostics --repo api # limit to one repo alias
```
@@ -912,11 +922,11 @@ Architecture lint: check the declared `conformance:` rules against the system gr
| Flag | Description |
|------|-------------|
-| `--json` | Emit the raw conformance report as JSON |
+| `--format` | `table` (default) or `json`. `--json` is a deprecated alias, still accepted |
```bash
repowise workspace check # human-readable report; exit 1 on findings
-repowise workspace check --json # raw report JSON
+repowise workspace check --format json # raw report JSON
```
### `repowise workspace metrics [PATH]`
@@ -925,11 +935,11 @@ Architecture-complexity metrics over the system graph built by `repowise update
| Flag | Description |
|------|-------------|
-| `--json` | Emit the raw metrics as JSON |
+| `--format` | `table` (default) or `json`. `--json` is a deprecated alias, still accepted |
```bash
repowise workspace metrics
-repowise workspace metrics --json
+repowise workspace metrics --format json
```
See [Workspaces](../scale/WORKSPACES.md) for the full multi-repo guide.
@@ -975,7 +985,7 @@ in `.repowise/sessions/sessions.db`.
```bash
repowise hook stats
-repowise hook stats --json # raw per-surface rows
+repowise hook stats --format json # raw per-surface rows
```
Notices that ask for nothing (stale-read, the silent read-after-served
@@ -1163,6 +1173,9 @@ version as seen. Works offline from the changelog bundled with the install.
|------|-------------|
| `--version X.Y.Z` | Show notes for a single release |
| `--all` | Show the full changelog history |
+| `--format` | `table` (default) or `json` |
+
+JSON carries every selected release; the panel caps at 5 releases and 8 bullets each.
```bash
repowise whats-new # what changed since you last looked
diff --git a/packages/cli/src/repowise/cli/commands/corrections_cmd.py b/packages/cli/src/repowise/cli/commands/corrections_cmd.py
index ee36b7ea7..0e442cb3f 100644
--- a/packages/cli/src/repowise/cli/commands/corrections_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/corrections_cmd.py
@@ -17,6 +17,7 @@ import click
from rich.table import Table
from repowise.cli.helpers import console
+from repowise.cli.output import emit_json, format_option, notice_console
_KIND_LABELS = {
"wrong_tool": "wrong tool",
@@ -52,7 +53,10 @@ _KIND_LABELS = {
show_default=True,
help="Occurrences a rule needs before --write includes it.",
)
-def corrections_command(path: str | None, days: float, write_block: bool, min_count: int) -> None:
+@format_option()
+def corrections_command(
+ path: str | None, days: float, write_block: bool, min_count: int, fmt: str
+) -> None:
"""Show recurring command fumbles mined from local agent transcripts.
PATH defaults to the current directory's enclosing repowise repo. The
@@ -62,10 +66,32 @@ def corrections_command(path: str | None, days: float, write_block: bool, min_co
from repowise.cli.helpers import find_repowise_repo_root
from repowise.core.distill.corrections import scan_corrections
+ notices = notice_console(fmt)
start = Path(path).resolve() if path else Path.cwd()
repo_root = find_repowise_repo_root(start) or start
report = scan_corrections(repo_root, days=days)
+ if fmt == "json":
+ emit_json(
+ {
+ "repo": str(repo_root),
+ "days": days,
+ "min_count": min_count,
+ "rules": report["rules"],
+ }
+ )
+ # --write is a filesystem effect, not a rendering one, so json mode
+ # still performs it; only its confirmations move to stderr.
+ #
+ # Gated on there being rules, matching the table path, which returns
+ # before it can write. Without the guard, a scan that found nothing
+ # would *prune* the managed block in json mode and leave it alone in
+ # table mode — a destructive difference between two spellings of the
+ # same command, on a file the user maintains.
+ if write_block and report["rules"]:
+ _write_managed_blocks(repo_root, report["rules"], min_count, out=notices)
+ return
+
if not report["rules"]:
console.print(
f"[yellow]No command corrections found in the last {days:g} days.[/yellow] "
@@ -115,13 +141,20 @@ def corrections_command(path: str | None, days: float, write_block: bool, min_co
console.print()
-def _write_managed_blocks(repo_root: Path, rules: list[dict], min_count: int) -> None:
- """Upsert the managed block into CLAUDE.md/AGENTS.md (or prune it)."""
+def _write_managed_blocks(
+ repo_root: Path, rules: list[dict], min_count: int, out=None
+) -> None:
+ """Upsert the managed block into CLAUDE.md/AGENTS.md (or prune it).
+
+ *out* is where the confirmations go; it is stderr under ``--format json``
+ so the write still reports itself without landing in the payload.
+ """
from repowise.core.distill.corrections import (
render_corrections_block,
update_corrections_block,
)
+ out = out or console
block = render_corrections_block(rules, min_count=min_count)
claude_md = repo_root / ".claude" / "CLAUDE.md"
agents_md = repo_root / "AGENTS.md"
@@ -130,7 +163,7 @@ def _write_managed_blocks(repo_root: Path, rules: list[dict], min_count: int) ->
# is only updated when the user already maintains one.
targets = [claude_md] + ([agents_md] if agents_md.exists() else [])
if block is None:
- console.print(
+ out.print(
f" [yellow]No rule seen {min_count}+ times - managed block "
"removed where present.[/yellow]"
)
@@ -138,8 +171,8 @@ def _write_managed_blocks(repo_root: Path, rules: list[dict], min_count: int) ->
try:
changed = update_corrections_block(target, block)
except OSError:
- console.print(f" [yellow]Could not update {target}[/yellow]")
+ out.print(f" [yellow]Could not update {target}[/yellow]")
continue
if changed:
verb = "updated" if block is not None else "removed"
- console.print(f" [green]✓[/green] Known-corrections block {verb} ({target})")
+ out.print(f" [green]✓[/green] Known-corrections block {verb} ({target})")
diff --git a/packages/cli/src/repowise/cli/commands/costs_cmd.py b/packages/cli/src/repowise/cli/commands/costs_cmd.py
index 1d503c6c3..4be3a6d72 100644
--- a/packages/cli/src/repowise/cli/commands/costs_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/costs_cmd.py
@@ -15,6 +15,7 @@ from repowise.cli.helpers import (
resolve_command_target,
run_async,
)
+from repowise.cli.output import emit_json, format_option, notice_console
def _parse_date(value: str | None) -> datetime | None:
@@ -74,6 +75,7 @@ def _parse_date(value: str | None) -> datetime | None:
default=False,
help="Force single-repo mode even when invoked from a workspace.",
)
+@format_option()
def costs_command(
path: str | None,
since: str | None,
@@ -82,6 +84,7 @@ def costs_command(
repo_alias: str | None,
show_all: bool,
no_workspace: bool,
+ fmt: str,
) -> None:
"""Show LLM cost history for a repository.
@@ -90,6 +93,8 @@ def costs_command(
In workspace mode, defaults to the primary repo; pass --repo <alias>
for a specific one or --all to sum across every repo.
"""
+ notices = notice_console(fmt)
+
# Support both positional PATH and --repo-path flag
raw_path = path or repo_path_flag
@@ -98,7 +103,12 @@ def costs_command(
no_workspace_flag=no_workspace,
repo_alias=repo_alias,
)
- target.notice(console, command="costs")
+ target.notice(notices, command="costs")
+
+ # Parsed before the early returns below so ``since`` has one type in every
+ # json payload: an ISO string normalised by the parser, never the raw
+ # argument on one path and the normalised form on another.
+ since_dt = _parse_date(since)
# Resolve which repo paths to query
repo_paths: list[Path] = []
@@ -126,15 +136,22 @@ def costs_command(
# would just return an empty result and confuse the user.
valid_paths = [p for p in repo_paths if (p / ".repowise").is_dir()]
if not valid_paths:
- console.print("[yellow]No indexed .repowise/ directory found. Run 'repowise init' first.[/yellow]")
+ notices.print(
+ "[yellow]No indexed .repowise/ directory found. Run 'repowise init' first.[/yellow]"
+ )
+ if fmt == "json":
+ emit_json(
+ {
+ "group_by": group_by,
+ "since": since_dt.isoformat() if since_dt else None,
+ "repos": [],
+ "rows": [],
+ }
+ )
return
if len(valid_paths) < len(repo_paths):
missing = [p.name for p in repo_paths if p not in valid_paths]
- console.print(
- f"[yellow]Skipping unindexed repos: {', '.join(missing)}[/yellow]"
- )
-
- since_dt = _parse_date(since)
+ notices.print(f"[yellow]Skipping unindexed repos: {', '.join(missing)}[/yellow]")
# Aggregate cost rows across every selected repo. For single-repo this
# is the original behavior; for --all it sums per group across repos.
@@ -166,6 +183,23 @@ def costs_command(
m["cost_usd"] += row.get("cost_usd", 0.0)
rows = sorted(merged.values(), key=lambda r: r["cost_usd"], reverse=True)
+ if fmt == "json":
+ emit_json(
+ {
+ "group_by": group_by,
+ "since": since_dt.isoformat() if since_dt else None,
+ "repos": [str(p) for p in valid_paths],
+ "rows": rows,
+ "totals": {
+ "calls": sum(r["calls"] for r in rows),
+ "input_tokens": sum(r["input_tokens"] for r in rows),
+ "output_tokens": sum(r["output_tokens"] for r in rows),
+ "cost_usd": sum(r["cost_usd"] for r in rows),
+ },
+ }
+ )
+ return
+
if not rows:
msg = "No cost records found"
if since_dt:
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
index 7e5710472..52a677849 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -22,12 +22,13 @@ from repowise.cli.helpers import (
resolve_command_target,
run_async,
)
+from repowise.cli.output import emit_json, format_option, notice_console
-def _resolve_coverage_repo(path: str | None) -> Path:
+def _resolve_coverage_repo(path: str | None, fmt: str = "table") -> Path:
"""Resolve the repo path for coverage subcommands (workspace-aware)."""
target = resolve_command_target(path=path)
- target.notice(console, command="coverage")
+ target.notice(notice_console(fmt), command="coverage")
if target.is_workspace:
primary = target.primary_path()
if primary is None:
@@ -286,9 +287,14 @@ def _discover_context_reports(repo_path: Path) -> list[Path]:
@click.option(
"--path", "repo", default=None, help="Repo path (defaults to cwd / workspace primary)."
)
-def coverage_status(repo: str | None) -> None:
+# Safe to spell this ``--format`` here: the ``--format`` that names an *input*
+# parser (lcov / cobertura / clover) lives on ``coverage add``, not on the
+# group, so the two never meet on one command line.
+@format_option()
+def coverage_status(repo: str | None, fmt: str) -> None:
"""Show the coverage currently ingested for this repo."""
- repo_path = _resolve_coverage_repo(repo)
+ repo_path = _resolve_coverage_repo(repo, fmt)
+ notices = notice_console(fmt)
async def _do() -> None:
from repowise.core.persistence import (
@@ -307,11 +313,24 @@ def coverage_status(repo: str | None) -> None:
async with get_session(sf) as session:
repo_row = await get_repository_by_path(session, str(repo_path))
if repo_row is None:
- console.print("[yellow]No index yet — run `repowise init`.[/yellow]")
+ notices.print("[yellow]No index yet — run `repowise init`.[/yellow]")
+ if fmt == "json":
+ emit_json({"repo": str(repo_path), "indexed": False})
return
summary = await get_coverage_summary(session, repo_row.id)
map_summary = await get_test_coverage_summary(session, repo_row.id)
+ if fmt == "json":
+ emit_json(
+ {
+ "repo": str(repo_path),
+ "indexed": True,
+ "coverage": summary if summary.get("file_count") else None,
+ "test_map": map_summary if map_summary.get("pair_count") else None,
+ }
+ )
+ return
+
if not summary.get("file_count") and not map_summary.get("pair_count"):
console.print(
"[yellow]No coverage ingested.[/yellow] Run "
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index d4cd6fdb0..f169ebbfa 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -15,6 +15,7 @@ from repowise.cli.helpers import (
resolve_command_target,
run_async,
)
+from repowise.cli.output import emit_json, format_option, notice_console
from repowise.core.analysis.decisions.provenance import LISTABLE_SOURCES
from repowise.core.precedent.currency import describe_decision_currency
@@ -25,7 +26,7 @@ from repowise.core.precedent.currency import describe_decision_currency
_SOURCE_CHOICES: tuple[str, ...] = (*LISTABLE_SOURCES, "all")
-def _resolve_decision_repo(path: str | None):
+def _resolve_decision_repo(path: str | None, fmt: str = "table"):
"""Resolve the repo path for decision subcommands.
Honors workspace auto-detection: in workspace mode without an explicit
@@ -33,7 +34,7 @@ def _resolve_decision_repo(path: str | None):
"""
target = resolve_command_target(path=path)
- target.notice(console, command="decision")
+ target.notice(notice_console(fmt), command="decision")
if target.is_workspace:
primary = target.primary_path()
if primary is None:
@@ -170,15 +171,17 @@ def decision_add(path: str | None) -> None:
)
@click.option("--proposed", is_flag=True, default=False, help="Show only proposed decisions.")
@click.option("--stale-only", is_flag=True, default=False, help="Show only stale decisions.")
+@format_option()
def decision_list(
path: str | None,
status: str,
source: str,
proposed: bool,
stale_only: bool,
+ fmt: str,
) -> None:
"""List architectural decision records."""
- repo_path = _resolve_decision_repo(path)
+ repo_path = _resolve_decision_repo(path, fmt)
async def _query() -> list:
from repowise.core.persistence import (
@@ -216,6 +219,29 @@ def decision_list(
if stale_only:
decisions = [d for d in decisions if d.staleness_score >= 0.5]
+ 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
+ ],
+ }
+ )
+ return
+
if not decisions:
console.print("[dim]No decisions found.[/dim]")
return
@@ -262,9 +288,10 @@ def decision_list(
@decision_group.command("show")
@click.argument("decision_id")
@click.argument("path", required=False, default=None)
-def decision_show(decision_id: str, path: str | None) -> None:
+@format_option()
+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)
+ repo_path = _resolve_decision_repo(path, fmt)
async def _query():
from repowise.core.persistence import (
@@ -289,7 +316,43 @@ def decision_show(decision_id: str, path: str | None) -> None:
rec = run_async(_query())
if rec is None:
- console.print(f"[red]Decision not found: {decision_id}[/red]")
+ notice_console(fmt).print(f"[red]Decision not found: {decision_id}[/red]")
+ if fmt == "json":
+ emit_json({"query": decision_id, "decision": None})
+ return
+
+ 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,
+ "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,
+ },
+ }
+ )
return
lines = [
@@ -486,9 +549,10 @@ def decision_deprecate(decision_id: str, path: str | None, superseded_by: str |
@decision_group.command("health")
@click.argument("path", required=False, default=None)
-def decision_health(path: str | None) -> None:
+@format_option()
+def decision_health(path: str | None, fmt: str) -> None:
"""Show decision health: stale decisions, proposed, ungoverned hotspots."""
- repo_path = _resolve_decision_repo(path)
+ repo_path = _resolve_decision_repo(path, fmt)
async def _query():
from repowise.core.persistence import (
@@ -515,6 +579,26 @@ def decision_health(path: str | None) -> None:
health = run_async(_query())
summary = health["summary"]
+ if fmt == "json":
+ # The table caps each list (5 stale, 10 hotspots, 5 proposed) to keep
+ # the report short; json carries them whole.
+ emit_json(
+ {
+ "repo": str(repo_path),
+ "summary": summary,
+ "stale_decisions": [
+ {"id": d.id, "title": d.title, "staleness_score": d.staleness_score}
+ for d in health["stale_decisions"]
+ ],
+ "ungoverned_hotspots": list(health["ungoverned_hotspots"]),
+ "proposed_awaiting_review": [
+ {"id": d.id, "title": d.title, "source": d.source}
+ for d in health["proposed_awaiting_review"]
+ ],
+ }
+ )
+ return
+
console.print("[bold]Decision Health[/bold]\n")
# Summary stats
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index fba5f5c1b..36084ad9a 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -8,6 +8,25 @@ from repowise.cli.helpers import (
console,
resolve_command_target,
)
+from repowise.cli.output import (
+ emit_json,
+ format_option,
+ json_option,
+ notice_console,
+ resolve_format,
+)
+
+#: Every ``hook stats --format json`` payload carries these five keys, whether
+#: or not there is a ledger to fill them from. A consumer that has to check
+#: which keys exist before reading them is not much better off than one parsing
+#: a table, so the empty case is the full shape rather than a shorter one.
+_EMPTY_STATS: dict = {
+ "surfaces": [],
+ "runs": [], # hook_run_by_tool
+ "decision_feedback": {}, # decision_feedback_totals
+ "builds": [], # injection_builds
+ "rewrite": [], # rewrite_run_totals
+}
@click.group("hook")
@@ -685,14 +704,9 @@ def _print_builds(builds: list[dict]) -> None:
@hook_group.command("stats")
@click.argument("path", required=False, default=None)
- "--json",
- "as_json",
- is_flag=True,
- default=False,
- help="Emit the raw per-surface rows as JSON instead of a table.",
-)
-def hook_stats(path: str | None, as_json: bool) -> None:
+@format_option(help="Output format. ``json`` emits the raw per-surface rows.")
+@json_option()
+def hook_stats(path: str | None, fmt: str, as_json: bool) -> None:
"""Show what the agent hooks fired and whether the agent acted on it.
Reads the efficacy ledger in .repowise/sessions/sessions.db. The live
@@ -701,8 +715,6 @@ def hook_stats(path: str | None, as_json: bool) -> None:
acted on. A surface showing firings but no verdicts has not been
classified yet — run the backfill.
"""
- import json as json_mod
-
from repowise.core.sessions.efficacy import (
CLASSIFIED_SURFACES,
NO_ACTION_EXPECTED,
@@ -710,10 +722,15 @@ def hook_stats(path: str | None, as_json: bool) -> None:
)
from repowise.core.sessions.staging import SessionStagingStore, default_store_path
+ fmt = resolve_format(fmt, as_json)
+ notices = notice_console(fmt)
+
target = resolve_command_target(path=path, workspace_flag=False, no_workspace_flag=True)
assert target.repo_path is not None
if not default_store_path(target.repo_path).exists():
- console.print("[yellow]No hook ledger yet.[/yellow] Run `repowise hook backfill`.")
+ notices.print("[yellow]No hook ledger yet.[/yellow] Run `repowise hook backfill`.")
+ if fmt == "json":
+ emit_json(_EMPTY_STATS)
return
store = SessionStagingStore.open_default(target.repo_path)
@@ -728,24 +745,32 @@ def hook_stats(path: str | None, as_json: bool) -> None:
finally:
store.close()
if not rows:
- console.print("[yellow]Hook ledger is empty.[/yellow] Run `repowise hook backfill`.")
- return
-
- if as_json:
- # The machine-readable twin carries the same lie the table did, so it
- # gets the same label rather than a footer nothing can parse.
- for row in rows:
- row["retired"] = (row["surface"], row["category"]) in RETIRED_CATEGORIES
- console.print_json(
- json_mod.dumps(
+ notices.print("[yellow]Hook ledger is empty.[/yellow] Run `repowise hook backfill`.")
+ if fmt == "json":
+ emit_json(
{
- "surfaces": rows,
+ **_EMPTY_STATS,
"runs": by_tool,
"decision_feedback": feedback,
"builds": builds,
"rewrite": rewrites,
}
)
+ return
+
+ if fmt == "json":
+ # The machine-readable twin carries the same lie the table did, so it
+ # gets the same label rather than a footer nothing can parse.
+ for row in rows:
+ row["retired"] = (row["surface"], row["category"]) in RETIRED_CATEGORIES
+ emit_json(
+ {
+ "surfaces": rows,
+ "runs": by_tool,
+ "decision_feedback": feedback,
+ "builds": builds,
+ "rewrite": rewrites,
+ }
)
return
diff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.py
index 4e1657c83..a90fdab7e 100644
--- a/packages/cli/src/repowise/cli/commands/saved_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py
@@ -22,6 +22,7 @@ import click
from rich.table import Table
from repowise.cli.helpers import console
+from repowise.cli.output import emit_json, format_option, notice_console
#: Fallback pricing model for the dollar estimate. Saved tokens are input-side
#: tokens the coding agent never had to read, so the input rate applies. Used
@@ -70,6 +71,7 @@ DEFAULT_PRICING_MODEL = "claude-sonnet-4-6"
metavar="DAYS",
help="Transcript window for the missed-savings scan.",
)
+@format_option()
def saved_command(
path: str | None,
group_by: str,
@@ -77,6 +79,7 @@ def saved_command(
pricing_model: str | None,
show_missed: bool,
missed_days: float,
+ fmt: str,
) -> None:
"""Show tokens (and estimated dollars) saved by ``repowise distill``.
@@ -87,22 +90,35 @@ def saved_command(
"""
from repowise.core.distill.store import OmissionStore, default_store_path
+ notices = notice_console(fmt)
since_ts = _parse_since(since)
start = Path(path).resolve() if path else Path.cwd()
pricing_model, pricing_note = _resolve_pricing(start, pricing_model)
if show_missed:
+ if fmt == "json":
+ emit_json(
+ {
+ "days": missed_days,
+ "pricing_model": pricing_model,
+ "missed_distill": _missed_report(start, missed_days),
+ "missed_mcp_rereads": _reread_report(start, missed_days),
+ }
+ )
+ return
_print_missed_report(start, missed_days, pricing_model)
return
db_path = default_store_path(start)
if not db_path.exists():
- console.print(
+ notices.print(
"[yellow]No savings recorded yet.[/yellow] Run commands through "
"'repowise distill <cmd>' (or install the rewrite hook with "
"'repowise hook rewrite install') to start saving tokens."
)
+ if fmt == "json":
+ emit_json({"ledger": str(db_path), "events": 0, "rows": []})
return
store = OmissionStore(db_path)
@@ -112,6 +128,28 @@ def saved_command(
finally:
store.close()
+ if fmt == "json":
+ saved_tokens = summary["saved_tokens"]
+ usd, rate = _estimate_usd(saved_tokens, pricing_model)
+ emit_json(
+ {
+ "ledger": str(db_path),
+ "group_by": group_by,
+ "since": since,
+ "pricing_model": pricing_model,
+ "pricing_source": pricing_note,
+ "input_rate_usd_per_mtok": rate,
+ "summary": {**summary, "estimated_usd": usd},
+ "rows": rows,
+ "mcp_truncation": _mcp_truncation_rows(db_path, since_ts),
+ "net": _net_data(start, saved_tokens, since_ts),
+ "missed_distill": _missed_report(start, missed_days),
+ "missed_mcp_rereads": _reread_report(start, missed_days),
+ "forgone": _forgone_rows(start, db_path, since_ts),
+ }
+ )
+ return
+
if summary["events"] == 0:
msg = "No distillation events recorded"
if since_ts is not None:
@@ -177,6 +215,65 @@ def saved_command(
console.print()
+def _net_data(start: Path, saved_tokens: int, since_ts: float | None) -> dict | None:
+ """The net figures behind :func:`_print_net`, or ``None`` when there is no net.
+
+ Split out so ``--format json`` reports the same numbers the table path
+ prints rather than a second, drifting computation of them. The three
+ honesty rules documented on :func:`_print_net` all live here, since they
+ decide whether a net exists at all: a windowed ``--since`` has no
+ comparable debit side, and neither does a repo with no debit rows.
+ """
+ if since_ts is not None:
+ return None
+ try:
+ from repowise.cli.helpers import find_repowise_repo_root
+ from repowise.core.sessions.efficacy import advisory_cost
+ from repowise.core.sessions.footprint import measure
+ from repowise.core.sessions.staging import SessionStagingStore, default_store_path
+
+ repo_root = find_repowise_repo_root(start) or start
+ advisory_chars = advisory_firings = 0
+ if default_store_path(repo_root).exists():
+ store = SessionStagingStore.open_default(repo_root)
+ try:
+ advisory_chars, advisory_firings = advisory_cost(store.efficacy_rows())
+ finally:
+ store.close()
+ footprint = measure(
+ repo_root,
+ advisory_chars=advisory_chars,
+ advisory_firings=advisory_firings,
+ )
+ except Exception:
+ return None
+ if not footprint.debits:
+ return None
+
+ amp = footprint.amplification
+ billed_saved = int(saved_tokens * (amp.ratio if amp.known else 1.0))
+ return {
+ "billed_saved": billed_saved,
+ "billed_spent": footprint.billed_total,
+ "net": billed_saved - footprint.billed_total,
+ "amplification": (
+ {"known": True, "ratio": amp.ratio, "sessions": amp.sessions, "calls": amp.calls}
+ if amp.known
+ else {"known": False}
+ ),
+ "debits": [
+ {
+ "label": d.label,
+ "billed_tokens": d.billed_tokens,
+ "raw_tokens": d.raw_tokens,
+ "detail": d.detail,
+ }
+ for d in footprint.debits
+ ],
+ "unmeasured": list(footprint.unmeasured),
+ }
+
+
def _print_net(start: Path, saved_tokens: int, since_ts: float | None = None) -> None:
"""Gross saved, gross spent, net — and the net may be negative.
@@ -206,50 +303,28 @@ def _print_net(start: Path, saved_tokens: int, since_ts: float | None = None) ->
"describe the same period. Run without --since for the net.[/dim]"
)
return
- try:
- from repowise.cli.helpers import find_repowise_repo_root
- from repowise.core.sessions.efficacy import advisory_cost
- from repowise.core.sessions.footprint import measure
- from repowise.core.sessions.staging import SessionStagingStore, default_store_path
-
- repo_root = find_repowise_repo_root(start) or start
- advisory_chars = advisory_firings = 0
- if default_store_path(repo_root).exists():
- store = SessionStagingStore.open_default(repo_root)
- try:
- advisory_chars, advisory_firings = advisory_cost(store.efficacy_rows())
- finally:
- store.close()
- footprint = measure(
- repo_root,
- advisory_chars=advisory_chars,
- advisory_firings=advisory_firings,
- )
- except Exception:
- return
- if not footprint.debits:
+ data = _net_data(start, saved_tokens, since_ts)
+ if data is None:
return
- amp = footprint.amplification
- multiplier = amp.ratio if amp.known else 1.0
- billed_saved = int(saved_tokens * multiplier)
- net = billed_saved - footprint.billed_total
+ net = data["net"]
colour = "green" if net > 0 else "red"
+ amp = data["amplification"]
console.print()
console.print(" [bold]Net[/bold] [dim](billed tokens, after amplification)[/dim]")
- console.print(f" gross saved [green]{billed_saved:>12,}[/green]")
- console.print(f" gross spent [yellow]{footprint.billed_total:>12,}[/yellow]")
+ console.print(f" gross saved [green]{data['billed_saved']:>12,}[/green]")
+ console.print(f" gross spent [yellow]{data['billed_spent']:>12,}[/yellow]")
console.print(f" net [{colour}]{net:>12,}[/{colour}]")
- for debit in footprint.debits:
+ for debit in data["debits"]:
console.print(
- f" [dim]{debit.label}: {debit.billed_tokens:,} "
- f"({debit.raw_tokens:,} raw — {debit.detail})[/dim]"
+ f" [dim]{debit['label']}: {debit['billed_tokens']:,} "
+ f"({debit['raw_tokens']:,} raw — {debit['detail']})[/dim]"
)
- if amp.known:
+ if amp["known"]:
console.print(
- f" [dim]amplification {amp.ratio:.1f}x, measured over {amp.sessions} "
- f"sessions at a median {amp.calls} API calls each. It is a function of "
+ f" [dim]amplification {amp['ratio']:.1f}x, measured over {amp['sessions']} "
+ f"sessions at a median {amp['calls']} API calls each. It is a function of "
"session length, not a constant.[/dim]"
)
else:
@@ -257,7 +332,7 @@ def _print_net(start: Path, saved_tokens: int, since_ts: float | None = None) ->
" [dim]no cache figures on disk, so nothing was amplified and "
"both sides are raw tokens.[/dim]"
)
- for missing in footprint.unmeasured:
+ for missing in data["unmeasured"]:
console.print(f" [dim]not counted as a cost: {missing}.[/dim]")
console.print(
" [dim]Savings recorded before the cost side existed have no debit "
@@ -296,6 +371,23 @@ _FORGONE_SURFACES = (
)
+def _mcp_truncation_rows(db_path: Path, since_ts: float | None) -> list[dict]:
+ """Per-tool truncation drops, or ``[]`` when this repo has never served MCP."""
+ import sqlite3
+
+ from repowise.core.distill import tracking
+
+ try:
+ con = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=2)
+ try:
+ summary = tracking.mcp_savings_summary(con, since=since_ts)
+ finally:
+ con.close()
+ except sqlite3.Error:
+ return [] # no such table: this repo has never served MCP, not an error
+ return [r for r in summary["per_tool"] if r["kind"] == "truncation"]
+
+
def _print_mcp_truncation_line(db_path: Path, since_ts: float | None) -> None:
"""MCP savings the table above structurally cannot show.
@@ -311,20 +403,7 @@ def _print_mcp_truncation_line(db_path: Path, since_ts: float | None) -> None:
put in them. ``mcp_savings_summary`` merges with counterfactual
precedence, so taking only the ``truncation`` rows adds each tool once.
"""
- import sqlite3
-
- from repowise.core.distill import tracking
-
- try:
- con = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=2)
- try:
- summary = tracking.mcp_savings_summary(con, since=since_ts)
- finally:
- con.close()
- except sqlite3.Error:
- return # no such table: this repo has never served MCP, not an error
-
- rows = [r for r in summary["per_tool"] if r["kind"] == "truncation"]
+ rows = _mcp_truncation_rows(db_path, since_ts)
if not rows:
return
tokens = sum(r["tokens"] for r in rows)
@@ -339,24 +418,20 @@ def _print_mcp_truncation_line(db_path: Path, since_ts: float | None) -> None:
)
-def _print_forgone_read_skeleton_line(start: Path, db_path: Path, since_ts: float | None) -> None:
- """What each replacing surface would have saved, for repos that have it off.
-
- Read out of its own table rather than the savings ledger, and printed
- below the total rather than inside it, because none of it happened.
+def _forgone_rows(start: Path, db_path: Path, since_ts: float | None) -> list[dict]:
+ """One row per replacing surface that has measured rows, else ``[]``.
- The caveat is not decoration. This number is exactly half the question:
- it says what the replacement would have taken off the bill, and it cannot
- say what the agent would then have had to read back, because nothing was
- replaced and so nothing was recovered. A repo can show a large figure here
- and still be one where serving skeletons is a bad trade.
+ A surface with no rows is omitted rather than reported as zero: nothing
+ was measured there, which is a different claim from "would have saved
+ nothing".
"""
import sqlite3
+ from repowise.cli.commands.augment_cmd._shared import hook_flag_enabled
from repowise.cli.helpers import find_repowise_repo_root
repo_root = find_repowise_repo_root(start) or start
- printed = False
+ rows: list[dict] = []
for source, flag, label, noun, install_cmd in _FORGONE_SURFACES:
try:
con = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=2)
@@ -380,33 +455,66 @@ def _print_forgone_read_skeleton_line(start: Path, db_path: Path, since_ts: floa
finally:
con.close()
except sqlite3.Error:
- return # no such table: this repo never measured, which is not an error
+ # ``break``, not ``return []``: the surfaces already read are real
+ # measurements and the printer used to keep them, because it
+ # printed as it went. The common error (no such table) still fails
+ # on the first surface and yields nothing either way; a locked
+ # database part-way through must not retract what was gathered.
+ break
if not items:
continue
+ rows.append(
+ {
+ "filter": flag,
+ "source": source,
+ "label": label,
+ "noun": noun,
+ "install_cmd": install_cmd,
+ # Rows outlive the setting that produced them, and nothing
+ # prunes them, so the state has to be read rather than inferred
+ # from their presence, or a repo that measured for a week and
+ # then turned the feature on gets told forever that it is off.
+ "enabled": hook_flag_enabled(repo_root, flag),
+ "items": items,
+ "raw_tokens": raw,
+ "distilled_tokens": distilled,
+ "forgone_tokens": raw - distilled,
+ }
+ )
+ return rows
- # Rows outlive the setting that produced them, and nothing prunes them,
- # so the state has to be read rather than inferred from their presence,
- # or a repo that measured for a week and then turned the feature on gets
- # told forever that it is off and should turn it on.
- from repowise.cli.commands.augment_cmd._shared import hook_flag_enabled
- printed = True
+def _print_forgone_read_skeleton_line(start: Path, db_path: Path, since_ts: float | None) -> None:
+ """What each replacing surface would have saved, for repos that have it off.
+
+ Read out of its own table rather than the savings ledger, and printed
+ below the total rather than inside it, because none of it happened.
+
+ The caveat is not decoration. This number is exactly half the question:
+ it says what the replacement would have taken off the bill, and it cannot
+ say what the agent would then have had to read back, because nothing was
+ replaced and so nothing was recovered. A repo can show a large figure here
+ and still be one where serving skeletons is a bad trade.
+ """
+ rows = _forgone_rows(start, db_path, since_ts)
+ for row in rows:
+ items, raw, distilled = row["items"], row["raw_tokens"], row["distilled_tokens"]
plural = "" if items == 1 else "s"
- if not hook_flag_enabled(repo_root, flag):
+ if not row["enabled"]:
console.print(
- f" [dim]Not saved:[/dim] {label} are [yellow]off[/yellow] here: "
- f"{items:,} {noun}{plural} would have cost "
+ f" [dim]Not saved:[/dim] {row['label']} are [yellow]off[/yellow] here: "
+ f"{items:,} {row['noun']}{plural} would have cost "
f"[bold]{raw - distilled:,}[/bold] fewer tokens ({raw:,} → {distilled:,}). "
- f"[dim]Turn on with `{install_cmd}`.[/dim]"
+ f"[dim]Turn on with `{row['install_cmd']}`.[/dim]"
)
else:
console.print(
- f" [dim]Measured before {label} was turned on:[/dim] {items:,} "
- f"{noun}{plural} would have cost "
+ f" [dim]Measured before {row['label']} was turned on:[/dim] {items:,} "
+ f"{row['noun']}{plural} would have cost "
f"[bold]{raw - distilled:,}[/bold] fewer tokens ({raw:,} → {distilled:,}). "
"[dim]Savings since then are in the table above.[/dim]"
)
- if printed:
+ if rows:
console.print(
" [dim]This is what the replacement would have taken off the bill, and only "
"that: nothing was replaced, so nothing was read back, so it says nothing "
diff --git a/packages/cli/src/repowise/cli/commands/search_cmd.py b/packages/cli/src/repowise/cli/commands/search_cmd.py
index eb6c1f7ab..aa1868b5f 100644
--- a/packages/cli/src/repowise/cli/commands/search_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/search_cmd.py
@@ -8,12 +8,12 @@ from rich.table import Table
from repowise.cli.helpers import (
console,
ensure_repowise_dir,
- err_console,
get_db_url_for_repo,
resolve_command_target,
run_async,
)
from repowise.cli.output import emit_json, format_option
+from repowise.cli.output import notice_console as _notices
# Rank-fusion damping for the workspace fan-out, matching the value the server's
# retrieval fusion uses. Only reached when repos in one workspace answered on
@@ -22,16 +22,6 @@ from repowise.cli.output import emit_json, format_option
_WORKSPACE_RRF_K = 60
-def _notices(fmt: str):
- """Console for human asides — stderr under ``--format json``.
-
- Progress notices, keyless-embedder warnings and "no results" lines are all
- written for a person. On stdout they would sit in front of the JSON
- document and break every parser reading it, so json mode diverts them.
- """
- return err_console if fmt == "json" else console
-
-
def _answered_mode(requested: str, keyless_repos: list[str], mixed_scales: bool) -> str:
"""Which retrieval actually answered, which is not always what was asked.
diff --git a/packages/cli/src/repowise/cli/commands/security_cmd.py b/packages/cli/src/repowise/cli/commands/security_cmd.py
index e857bb576..83a919584 100644
--- a/packages/cli/src/repowise/cli/commands/security_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/security_cmd.py
@@ -1,7 +1,7 @@
"""``repowise security scan`` — security signal scanning.
Subcommands:
- scan --history [--since <rev>] [--to <rev>] [--output json]
+ scan --history [--since <rev>] [--to <rev>] [--format json]
Walk the entire git history of the repo (not just the working tree) with
the same pattern registry the indexer uses, and persist any secrets or
risky patterns into the shared ``security_findings`` table — tagged with
@@ -10,8 +10,6 @@ Subcommands:
from __future__ import annotations
-import json
-
import click
from repowise.cli.helpers import (
@@ -22,6 +20,7 @@ from repowise.cli.helpers import (
run_async,
silence_logs_for_machine_output,
)
+from repowise.cli.output import emit_json, format_option, notice_console
@click.group("security")
@@ -60,12 +59,14 @@ def security_command() -> None:
"weak hashes, ...). By default history mode reports only leaked-secret "
"patterns (hardcoded_password / hardcoded_secret) to avoid noise.",
)
+@format_option(help="Output format. ``json`` is the machine-readable summary.")
@click.option(
"--output",
- "output_format",
- default="table",
+ "legacy_output",
+ default=None,
type=click.Choice(["table", "json"]),
- help="Output format. ``json`` is the machine-readable summary.",
+ hidden=True,
+ help="Deprecated alias for --format.",
)
def security_scan(
history: bool,
@@ -73,7 +74,8 @@ def security_scan(
to: str | None,
all_patterns: bool,
repo: str | None,
- output_format: str,
+ fmt: str,
+ legacy_output: str | None,
) -> None:
"""Scan for security signals and persist findings to the local store.
@@ -83,13 +85,23 @@ def security_scan(
patterns that were later removed — something the working-tree scan cannot
see.
"""
+ # ``--output`` shipped before ``--format`` was the convention. An explicit
+ # ``--output`` still wins so existing scripts keep their behaviour; with it
+ # unset (the default) ``--format`` decides.
+ output_format = legacy_output or fmt
+
if not history:
- console.print(
+ # Notice on stderr and a payload on stdout, rather than a rich notice
+ # and nothing: json mode has to leave stdout parseable even on the
+ # path where the command declines to do any work.
+ notice_console(output_format).print(
"[yellow]Working-tree scanning runs automatically during "
"`repowise init`/`repowise update`.[/yellow]\n"
"Pass [cyan]--history[/cyan] to scan the full git history for secrets "
"and risky patterns (including ones deleted in later commits)."
)
+ if output_format == "json":
+ emit_json({"scanned": False, "reason": "history-mode-not-requested"})
return
if output_format == "json":
@@ -109,7 +121,7 @@ def security_scan(
)
target = resolve_command_target(path=repo)
- target.notice(console, command="security scan --history")
+ target.notice(notice_console(output_format), command="security scan --history")
if target.is_workspace:
primary = target.primary_path()
@@ -156,7 +168,7 @@ def security_scan(
result = run_async(_do())
if output_format == "json":
- click.echo(json.dumps(result, indent=2))
+ emit_json(result)
return
console.print(f"[bold]repowise security scan --history[/bold] — {repo_path}")
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index 85bd8dcc4..18909b241 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -19,6 +19,7 @@ from repowise.cli.helpers import (
resolve_command_target,
run_async,
)
+from repowise.cli.output import emit_json, format_option, notice_console
from repowise.cli.ui.brand import format_bytes
from repowise.core.docs_mode import resolve_docs_mode
@@ -142,13 +143,40 @@ def _query_page_count(repo_path: Path) -> int:
return 0
-def _query_health_line(repo_path: Path) -> str | None:
- """One-line health summary for ``repowise status``.
+async def _query_pages(repo_path: Path) -> tuple[dict[str, int], int]:
+ """Page counts per type and total page tokens for *repo_path*."""
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_repository_by_path,
+ get_session,
+ list_pages,
+ )
- Returns ``None`` when no health data exists yet so the caller can
- skip the line silently. Format matches plan §4 P4.10:
+ engine = create_engine(get_db_url_for_repo(repo_path))
+ sf = create_session_factory(engine)
- Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts)
+ counts: dict[str, int] = {}
+ total_tokens = 0
+ try:
+ async with get_session(sf) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is None:
+ return counts, total_tokens
+ pages = await list_pages(session, repo.id, include_tombstones=False, limit=10000)
+ for p in pages:
+ counts[p.page_type] = counts.get(p.page_type, 0) + 1
+ total_tokens += (p.input_tokens or 0) + (p.output_tokens or 0)
+ finally:
+ await engine.dispose()
+ return counts, total_tokens
+
+
+def _query_health(repo_path: Path) -> dict | None:
+ """Health figures for ``repowise status``, or ``None`` when there are none.
+
+ Split from :func:`_query_health_line` so the json mode reports the numbers
+ rather than a string with rich markup in it.
"""
db_path = get_repowise_dir(repo_path) / "wiki.db"
if not db_path.exists() and not db_configured():
@@ -195,9 +223,20 @@ def _query_health_line(repo_path: Path) -> str | None:
await engine.dispose()
try:
- data = run_async(_q())
+ return run_async(_q()) or None
except Exception:
return None
+
+
+def _query_health_line(repo_path: Path) -> str | None:
+ """One-line health summary for ``repowise status``.
+
+ Returns ``None`` when no health data exists yet so the caller can
+ skip the line silently. Format matches plan §4 P4.10:
+
+ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts)
+ """
+ data = _query_health(repo_path)
if not data:
return None
worst_path = data["worst_performer_path"] or "n/a"
@@ -254,17 +293,94 @@ def _format_relative_time(iso_timestamp: str | None) -> str:
return iso_timestamp[:10] if len(iso_timestamp) >= 10 else iso_timestamp
-def _workspace_status(target: CommandTarget) -> None:
- """Show status for all repos in a workspace."""
+def _workspace_rows(target: CommandTarget) -> list[dict]:
+ """One plain-data row per workspace repo, before any rendering.
+
+ Split out so json mode reports the underlying values (a byte count, a
+ boolean, a commit) rather than the table's cells, which carry rich markup
+ and pre-formatted strings like ``3d ago``.
+
+ Every row carries every key. An unindexed repo has nothing to report and
+ leaves the measured fields ``None``, rather than omitting them and making
+ each consumer branch on ``indexed`` before it may read a field.
+ """
from repowise.core.workspace import check_repo_staleness
+ ws_root = target.ws_root
+ ws_config = target.ws_config
+ assert ws_root is not None and ws_config is not None
+
+ rows: list[dict] = []
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ repowise_dir = abs_path / ".repowise"
+ row: dict = {
+ "alias": entry.alias,
+ "path": str(abs_path),
+ "primary": entry.alias == ws_config.default_repo,
+ "indexed": repowise_dir.exists(),
+ "indexed_at": entry.indexed_at,
+ "files": None,
+ "symbols": None,
+ "pages": None,
+ "docs_mode": None,
+ "storage_bytes": None,
+ "head": None,
+ "stale": None,
+ "commits_behind": None,
+ }
+ if not row["indexed"]:
+ rows.append(row)
+ continue
+
+ file_count, symbol_count = _query_repo_counts(abs_path)
+ page_count = _query_page_count(abs_path)
+ is_stale, current_head, behind = check_repo_staleness(
+ abs_path, entry.last_commit_at_index
+ )
+ row.update(
+ files=file_count,
+ symbols=symbol_count,
+ pages=page_count,
+ docs_mode=resolve_docs_mode(load_state(abs_path)),
+ storage_bytes=_index_storage_bytes(repowise_dir),
+ head=current_head,
+ stale=is_stale,
+ commits_behind=behind,
+ )
+ rows.append(row)
+ return rows
+
+
+def _workspace_status(target: CommandTarget, fmt: str = "table") -> None:
+ """Show status for all repos in a workspace."""
ws_root = target.ws_root
ws_config = target.ws_config
if ws_root is None or ws_config is None:
- console.print(
+ notice_console(fmt).print(
"[yellow]No .repowise-workspace.yaml found. "
"Run 'repowise init <workspace-dir>' first.[/yellow]"
)
+ if fmt == "json":
+ emit_json({"workspace": None, "repos": []})
+ return
+
+ rows = _workspace_rows(target)
+
+ if fmt == "json":
+ emit_json(
+ {
+ "workspace": {
+ "name": ws_root.name,
+ "path": str(ws_root),
+ "default_repo": ws_config.default_repo,
+ "repo_count": len(rows),
+ "indexed_count": sum(1 for r in rows if r["indexed"]),
+ "stale_count": sum(1 for r in rows if r["stale"]),
+ },
+ "repos": rows,
+ }
+ )
return
table = Table(title=f"Workspace: {ws_root.name}")
@@ -280,22 +396,17 @@ def _workspace_status(target: CommandTarget) -> None:
total_stale = 0
no_docs: list[str] = [] # aliases with index but no generated pages
- for entry in ws_config.repos:
- abs_path = (ws_root / entry.path).resolve()
- repowise_dir = abs_path / ".repowise"
- label = entry.alias
- if entry.alias == ws_config.default_repo:
+ for row in rows:
+ label = row["alias"]
+ if row["primary"]:
label += " [bold](primary)[/bold]"
- if not repowise_dir.exists():
+ if not row["indexed"]:
table.add_row(label, "-", "-", "-", "-", "-", "-", "[yellow]not indexed[/yellow]")
continue
- file_count, symbol_count = _query_repo_counts(abs_path)
- indexed_ago = _format_relative_time(entry.indexed_at)
- page_count = _query_page_count(abs_path)
- storage_cell = format_bytes(_index_storage_bytes(repowise_dir))
- docs_mode = resolve_docs_mode(load_state(abs_path))
+ page_count = row["pages"]
+ docs_mode = row["docs_mode"]
# One axis in the Docs column: every wiki is complete, and the only
# question is whether the subsystem pages carry written prose or are
@@ -307,44 +418,39 @@ def _workspace_status(target: CommandTarget) -> None:
docs_cell = f"[green]{page_count} · prose[/green]"
elif docs_mode == "none":
docs_cell = "[yellow]None[/yellow]"
- no_docs.append(entry.alias)
+ no_docs.append(row["alias"])
else:
docs_cell = "[yellow]0[/yellow]"
- no_docs.append(entry.alias)
+ no_docs.append(row["alias"])
- # Check staleness by comparing stored commit to current HEAD
- stored_commit = entry.last_commit_at_index
- is_stale, current_head, behind = check_repo_staleness(abs_path, stored_commit)
- head_short = (current_head or "-")[:7]
-
- if is_stale and behind > 0:
+ behind = row["commits_behind"]
+ if row["stale"] and behind > 0:
status = f"[yellow]{behind} new commit(s)[/yellow]"
total_stale += 1
- elif is_stale:
+ elif row["stale"]:
status = "[yellow]stale[/yellow]"
total_stale += 1
- elif file_count > 0:
+ elif row["files"] > 0:
status = "[green]up to date[/green]"
else:
status = "[yellow]empty[/yellow]"
table.add_row(
label,
- str(file_count),
- f"{symbol_count:,}",
+ str(row["files"]),
+ f"{row['symbols']:,}",
docs_cell,
- storage_cell,
- indexed_ago,
- head_short,
+ format_bytes(row["storage_bytes"]),
+ _format_relative_time(row["indexed_at"]),
+ (row["head"] or "-")[:7],
status,
)
console.print(table)
# Summary line
- total_repos = len(ws_config.repos)
- indexed = sum(1 for e in ws_config.repos if (ws_root / e.path / ".repowise").exists())
- summary = f"\n {indexed}/{total_repos} repos indexed. Default: {ws_config.default_repo}"
+ indexed = sum(1 for r in rows if r["indexed"])
+ summary = f"\n {indexed}/{len(rows)} repos indexed. Default: {ws_config.default_repo}"
if total_stale:
summary += f". [yellow]{total_stale} stale[/yellow]"
console.print(summary)
@@ -384,20 +490,23 @@ def _workspace_status(target: CommandTarget) -> None:
default=False,
help="Force single-repo mode even when invoked from a workspace.",
)
-def status_command(path: str | None, workspace: bool, no_workspace: bool) -> None:
+@format_option()
+def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: str) -> None:
"""Show wiki sync state and page statistics.
Auto-detects workspace mode when invoked from a workspace root.
"""
+ notices = notice_console(fmt)
+
target = resolve_command_target(
path=path,
workspace_flag=workspace,
no_workspace_flag=no_workspace,
)
- target.notice(console, command="status")
+ target.notice(notices, command="status")
if target.is_workspace:
- _workspace_status(target)
+ _workspace_status(target, fmt)
return
repo_path = target.repo_path
@@ -405,12 +514,47 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool) -> Non
repowise_dir = get_repowise_dir(repo_path)
if not repowise_dir.exists():
- console.print("[yellow]No .repowise/ directory found. Run 'repowise init' first.[/yellow]")
+ notices.print(
+ "[yellow]No .repowise/ directory found. Run 'repowise init' first.[/yellow]"
+ )
+ if fmt == "json":
+ emit_json({"repo": str(repo_path), "indexed": False})
return
state = load_state(repo_path)
+ storage_bytes = _index_storage_bytes(repowise_dir)
+ db_path = repowise_dir / "wiki.db"
+ has_db = db_path.exists() or db_configured()
- # State table
+ if fmt == "json":
+ counts, total_db_tokens = (
+ run_async(_query_pages(repo_path)) if has_db else ({}, 0)
+ )
+ emit_json(
+ {
+ "repo": str(repo_path),
+ "indexed": True,
+ "state": {
+ "last_sync_commit": state.get("last_sync_commit"),
+ "total_pages": state.get("total_pages", 0),
+ "provider": state.get("provider"),
+ "model": state.get("model"),
+ "total_tokens": state.get("total_tokens", 0),
+ "storage_bytes": storage_bytes,
+ },
+ "database_found": has_db,
+ "pages_by_type": counts,
+ "page_total": sum(counts.values()),
+ "page_tokens": total_db_tokens,
+ "health": _query_health(repo_path),
+ }
+ )
+ return
+
+ # State table. Printed before the page query runs, not after: the query is
+ # unguarded, and on a wiki.db whose schema predates the current models it
+ # raises. Ordering it first means a reader still gets the sync state that
+ # tells them the index is old.
state_table = Table(title="Sync State")
state_table.add_column("Key", style="cyan")
state_table.add_column("Value")
@@ -419,48 +563,14 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool) -> Non
state_table.add_row("Provider", state.get("provider", "—") or "—")
state_table.add_row("Model", state.get("model", "—") or "—")
state_table.add_row("Total tokens", f"{state.get('total_tokens', 0):,}")
- state_table.add_row("Index storage", format_bytes(_index_storage_bytes(repowise_dir)))
+ state_table.add_row("Index storage", format_bytes(storage_bytes))
console.print(state_table)
- # Page counts from DB
- db_path = repowise_dir / "wiki.db"
- if not db_path.exists() and not db_configured():
+ if not has_db:
console.print(f"[yellow]Database not found at {db_path}.[/yellow]")
return
- async def _query_pages():
- from repowise.core.persistence import (
- create_engine,
- create_session_factory,
- get_repository_by_path,
- get_session,
- list_pages,
- )
-
- url = get_db_url_for_repo(repo_path)
- engine = create_engine(url)
- sf = create_session_factory(engine)
-
- counts: dict[str, int] = {}
- total_tokens = 0
-
- async with get_session(sf) as session:
- repo = await get_repository_by_path(session, str(repo_path))
- if repo is None:
- await engine.dispose()
- return counts, total_tokens
- pages = await list_pages(
- session, repo.id, include_tombstones=False, limit=10000
- )
- for p in pages:
- counts[p.page_type] = counts.get(p.page_type, 0) + 1
- total_tokens += (p.input_tokens or 0) + (p.output_tokens or 0)
-
- await engine.dispose()
- return counts, total_tokens
-
- counts, total_db_tokens = run_async(_query_pages())
-
+ counts, total_db_tokens = run_async(_query_pages(repo_path))
if counts:
pages_table = Table(title="Pages by Type")
pages_table.add_column("Page Type", style="cyan")
diff --git a/packages/cli/src/repowise/cli/commands/whats_new_cmd.py b/packages/cli/src/repowise/cli/commands/whats_new_cmd.py
index 0816ae82f..8ed8b0886 100644
--- a/packages/cli/src/repowise/cli/commands/whats_new_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/whats_new_cmd.py
@@ -6,6 +6,7 @@ import click
from repowise.cli import __version__
from repowise.cli.helpers import console
+from repowise.cli.output import emit_json, format_option, notice_console
from repowise.cli.whats_new import (
load_changelog_entries,
read_last_seen_version,
@@ -14,40 +15,95 @@ from repowise.cli.whats_new import (
)
+def _entry_dict(entry) -> dict:
+ """One changelog release as plain data.
+
+ The table path renders through ``render_whats_new``, which caps at 5
+ releases and 8 bullets each to keep a panel readable. json applies no such
+ cap: the selection is already the caller's (``--version`` / ``--all`` /
+ the last-seen watermark), and silently dropping the rest of what was asked
+ for is exactly the truncation this phase exists to remove.
+ """
+ return {
+ "version": entry.version,
+ "label": entry.label,
+ "sections": [{"name": s.name, "items": list(s.items)} for s in entry.sections],
+ }
+
+
@click.command("whats-new")
@click.option(
"--version", "version", default=None, help="Show notes for a single version (e.g. 0.21.0)."
)
@click.option("--all", "show_all", is_flag=True, help="Show the full changelog history.")
-def whats_new_command(version: str | None, show_all: bool) -> None:
+@format_option()
+def whats_new_command(version: str | None, show_all: bool, fmt: str) -> None:
"""Show what changed in recent repowise releases.
By default shows releases newer than the last one you viewed, then records
the current version as seen. ``--all`` shows everything; ``--version`` shows
one specific release.
"""
+ notices = notice_console(fmt)
entries = load_changelog_entries()
if not entries:
from repowise.cli.whats_new import RELEASES_URL
- console.print(f"[yellow]No changelog found.[/yellow] Release notes: {RELEASES_URL}")
+ notices.print(f"[yellow]No changelog found.[/yellow] Release notes: {RELEASES_URL}")
+ if fmt == "json":
+ emit_json({"current_version": __version__, "releases": []})
return
if version:
match = [e for e in entries if e.version == version]
if not match:
- console.print(f"[yellow]No changelog entry for v{version}.[/yellow]")
+ notices.print(f"[yellow]No changelog entry for v{version}.[/yellow]")
+ if fmt == "json":
+ emit_json({"current_version": __version__, "releases": []})
+ return
+ if fmt == "json":
+ emit_json(
+ {
+ "current_version": __version__,
+ "releases": [_entry_dict(e) for e in match],
+ }
+ )
return
render_whats_new(console, match, since_version=None, title=f"repowise v{version}")
return
if show_all:
+ if fmt == "json":
+ emit_json(
+ {
+ "current_version": __version__,
+ "releases": [_entry_dict(e) for e in entries],
+ }
+ )
+ return
render_whats_new(
console, entries, since_version=None, max_versions=len(entries), title="Changelog"
)
return
since = read_last_seen_version()
+ if fmt == "json":
+ from repowise.core.upgrade.changelog import entries_between
+
+ selected = entries_between(entries, newer_than=since, up_to=__version__)
+ emit_json(
+ {
+ "current_version": __version__,
+ "last_seen_version": since,
+ "releases": [_entry_dict(e) for e in selected],
+ }
+ )
+ # Same watermark write as the table path: json mode is still "I have
+ # seen these", and skipping it would re-report the same releases every
+ # run to the one consumer least able to notice the repetition.
+ write_last_seen_version(__version__)
+ return
+
rendered = render_whats_new(
console, entries, since_version=since, up_to_version=__version__, title="What's new"
)
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index 2ce5096f1..16a88c312 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -18,6 +18,7 @@ from repowise.cli.helpers import (
resolve_repo_path,
run_async,
)
+from repowise.cli.output import emit_json, format_option, json_option, resolve_format
from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
if TYPE_CHECKING:
@@ -910,8 +911,11 @@ def workspace_set_default(alias: str) -> None:
@workspace_group.command("diagnostics")
@click.argument("path", required=False, default=None)
@click.option("--repo", "repo_alias", default=None, help="Limit the report to one repo alias.")
[email protected]("--json", "as_json", is_flag=True, help="Emit raw diagnostics JSON.")
-def workspace_diagnostics(path: str | None, repo_alias: str | None, as_json: bool) -> None:
+@format_option(help="Output format. ``json`` emits the raw diagnostics.")
+@json_option()
+def workspace_diagnostics(
+ path: str | None, repo_alias: str | None, fmt: str, as_json: bool
+) -> None:
"""Explain the cross-repo contract link count.
Reports, per repo, how many providers and consumers were found, which
@@ -919,10 +923,9 @@ def workspace_diagnostics(path: str | None, repo_alias: str | None, as_json: boo
the answer to "why are there so few links?". Reads the system graph built
during 'repowise update --workspace'.
"""
- import json as _json
-
from repowise.core.workspace.system_graph import load_system_graph
+ fmt = resolve_format(fmt, as_json)
start = resolve_repo_path(path)
ws_root, _ws_config = _require_workspace(start)
@@ -942,18 +945,19 @@ def workspace_diagnostics(path: str | None, repo_alias: str | None, as_json: boo
unmatched = [u for u in unmatched if u.repo == repo_alias]
orphans = [o for o in orphans if o.repo == repo_alias]
- if as_json:
- payload = {
- "total_providers": diag.total_providers,
- "total_consumers": diag.total_consumers,
- "total_links": diag.total_links,
- "weak_link_count": diag.weak_link_count,
- "repo_breakdown": [r.to_dict() for r in breakdown],
- "unmatched_consumers": [u.to_dict() for u in unmatched],
- "unmatched_by_reason": diag.unmatched_by_reason,
- "orphan_providers": [o.to_dict() for o in orphans],
- }
- console.print_json(_json.dumps(payload))
+ if fmt == "json":
+ emit_json(
+ {
+ "total_providers": diag.total_providers,
+ "total_consumers": diag.total_consumers,
+ "total_links": diag.total_links,
+ "weak_link_count": diag.weak_link_count,
+ "repo_breakdown": [r.to_dict() for r in breakdown],
+ "unmatched_consumers": [u.to_dict() for u in unmatched],
+ "unmatched_by_reason": diag.unmatched_by_reason,
+ "orphan_providers": [o.to_dict() for o in orphans],
+ }
+ )
return
# Per-repo provider/consumer breakdown
@@ -1012,8 +1016,9 @@ def workspace_diagnostics(path: str | None, repo_alias: str | None, as_json: boo
@workspace_group.command("check")
@click.argument("path", required=False, default=None)
[email protected]("--json", "as_json", is_flag=True, help="Emit the raw conformance report as JSON.")
-def workspace_check(path: str | None, as_json: bool) -> None:
+@format_option(help="Output format. ``json`` emits the raw conformance report.")
+@json_option()
+def workspace_check(path: str | None, fmt: str, as_json: bool) -> None:
"""Architecture lint — fail on dependency-rule violations or cycles.
Checks the declared ``conformance`` rules in ``.repowise-workspace.yaml``
@@ -1022,7 +1027,6 @@ def workspace_check(path: str | None, as_json: bool) -> None:
recomputes from) the system graph built by 'repowise update --workspace', so
editing rules and re-running picks them up without a full re-index.
"""
- import json as _json
import sys
from repowise.core.workspace.conformance import (
@@ -1031,6 +1035,7 @@ def workspace_check(path: str | None, as_json: bool) -> None:
)
from repowise.core.workspace.system_graph import load_system_graph
+ fmt = resolve_format(fmt, as_json)
start = resolve_repo_path(path)
ws_root, ws_config = _require_workspace(start)
@@ -1047,8 +1052,8 @@ def workspace_check(path: str | None, as_json: bool) -> None:
tags_by_repo_from_config(ws_config),
)
- if as_json:
- console.print_json(_json.dumps(report.to_dict()))
+ if fmt == "json":
+ emit_json(report.to_dict())
if report.has_findings:
sys.exit(1)
return
@@ -1102,8 +1107,9 @@ def workspace_check(path: str | None, as_json: bool) -> None:
@workspace_group.command("metrics")
@click.argument("path", required=False, default=None)
[email protected]("--json", "as_json", is_flag=True, help="Emit the raw metrics as JSON.")
-def workspace_metrics(path: str | None, as_json: bool) -> None:
+@format_option(help="Output format. ``json`` emits the raw metrics.")
+@json_option()
+def workspace_metrics(path: str | None, fmt: str, as_json: bool) -> None:
"""Architecture metrics — propagation cost, core, and a 1-10 score.
Computes the standard architecture-complexity metrics over the system graph
@@ -1113,8 +1119,6 @@ def workspace_metrics(path: str | None, as_json: bool) -> None:
Declared-rule violations, if any, are folded into the score. CI-friendly
plain output.
"""
- import json as _json
-
from repowise.core.workspace.architecture_metrics import compute_architecture_metrics
from repowise.core.workspace.conformance import (
check_conformance,
@@ -1122,6 +1126,7 @@ def workspace_metrics(path: str | None, as_json: bool) -> None:
)
from repowise.core.workspace.system_graph import load_system_graph
+ fmt = resolve_format(fmt, as_json)
start = resolve_repo_path(path)
ws_root, ws_config = _require_workspace(start)
@@ -1141,8 +1146,8 @@ def workspace_metrics(path: str | None, as_json: bool) -> None:
generated_at=graph.generated_at,
)
- if as_json:
- console.print_json(_json.dumps(metrics.to_dict()))
+ if fmt == "json":
+ emit_json(metrics.to_dict())
return
if metrics.node_count == 0:
diff --git a/packages/cli/src/repowise/cli/output.py b/packages/cli/src/repowise/cli/output.py
index 370340010..56e3ccf3f 100644
--- a/packages/cli/src/repowise/cli/output.py
+++ b/packages/cli/src/repowise/cli/output.py
@@ -74,6 +74,23 @@ def resolve_console_width(stream: IO[str]) -> int | None:
return NON_TTY_WIDTH
+def _silence_when_machine_readable(ctx: Any, param: Any, value: str) -> str:
+ """Turn log output off the moment a machine-readable format is selected.
+
+ Structlog's unconfigured default writes to **stdout**, so one ``info()``
+ call anywhere below a command lands inside its JSON document. Doing this in
+ the option's callback rather than in each command body means it holds for
+ every consumer of :func:`format_option`, including ones added later, and
+ it runs at parse time — before any command body has had a chance to import
+ a module that logs on import.
+ """
+ if value != "table":
+ from repowise.cli.helpers import silence_logs_for_machine_output
+
+ silence_logs_for_machine_output()
+ return value
+
+
def format_option(
*,
choices: tuple[str, ...] = ("table", "json"),
@@ -91,10 +108,75 @@ def format_option(
"fmt",
type=click.Choice(list(choices)),
default=default,
+ callback=_silence_when_machine_readable,
help=help,
)
+def _silence_when_alias_selects_json(ctx: Any, param: Any, value: bool) -> bool:
+ """:func:`_silence_when_machine_readable` for the boolean ``--json`` alias.
+
+ The alias selects json while ``--format`` never leaves ``table``, so it has
+ to silence logs itself or the one payload that can still be corrupted is
+ the one a legacy caller asked for.
+ """
+ if value:
+ from repowise.cli.helpers import silence_logs_for_machine_output
+
+ silence_logs_for_machine_output()
+ return value
+
+
+def json_option(*, help: str = "Deprecated alias for --format json.") -> Any:
+ """A hidden ``--json`` flag, for commands that shipped that spelling first.
+
+ ``hook stats``, ``workspace check/diagnostics/metrics`` and (as
+ ``--output``) ``security scan`` were machine-readable before ``--format``
+ was the convention. Removing their flag would break every script and CI
+ job already calling them, so it stays and stays working — just hidden from
+ ``--help``, so the documented surface is one flag rather than four.
+
+ Bound to ``as_json``; combine with :func:`format_option` and resolve the
+ pair through :func:`resolve_format`.
+ """
+ return click.option(
+ "--json",
+ "as_json",
+ is_flag=True,
+ default=False,
+ hidden=True,
+ callback=_silence_when_alias_selects_json,
+ help=help,
+ )
+
+
+def resolve_format(fmt: str, as_json: bool) -> str:
+ """Fold a legacy boolean alias into the ``--format`` value.
+
+ The alias can only ever *select* json, never deselect it, so
+ ``--format json`` and ``--json`` agree and passing both is not an error.
+ """
+ return "json" if as_json else fmt
+
+
+def notice_console(fmt: str) -> Any:
+ """The console a command's human-facing asides should print to.
+
+ Under ``--format json`` stdout has to be one parseable document, so every
+ notice, warning and tip moves to stderr rather than being suppressed — an
+ agent's ``jq`` still works and a human running the command still sees why
+ the payload looks the way it does. Under any other format this is the
+ ordinary stdout console and nothing moves.
+
+ Only covers prints the command itself makes. A print in a module it calls
+ is invisible from here and has to be fixed at its own source (see
+ ``providers/vector_store.py``).
+ """
+ from repowise.cli.helpers import console, err_console
+
+ return err_console if fmt == "json" else console
+
+
def emit_json(payload: Any) -> None:
"""Write *payload* to stdout as JSON, the way the existing commands do.
@@ -105,4 +187,12 @@ def emit_json(payload: Any) -> None:
click.echo(json.dumps(payload, indent=2, default=str))
-__all__ = ["NON_TTY_WIDTH", "emit_json", "format_option", "resolve_console_width"]
+__all__ = [
+ "NON_TTY_WIDTH",
+ "emit_json",
+ "format_option",
+ "json_option",
+ "notice_console",
+ "resolve_console_width",
+ "resolve_format",
+]
diff --git a/packages/cli/src/repowise/cli/providers/vector_store.py b/packages/cli/src/repowise/cli/providers/vector_store.py
index 63be0f443..f7eeb1fb0 100644
--- a/packages/cli/src/repowise/cli/providers/vector_store.py
+++ b/packages/cli/src/repowise/cli/providers/vector_store.py
@@ -72,9 +72,15 @@ def build_vector_store(repo_path: Path, embedder: Any) -> Any | None:
# "not updating" rather than "skipped" because the generation phase
# substitutes a throwaway in-memory store for a None one, so this run
# does still embed — it just does not persist anywhere.
- from repowise.cli.helpers import console
-
- console.print(
+ #
+ # stderr, not stdout: this fires two modules below whichever command
+ # asked for a store, so a command-level "divert notices in --format
+ # json" cannot reach it, and on stdout it would land inside the JSON
+ # document. Same defect that corrupted ``search --format json`` from
+ # ``build_embedder``; fixed at the source for the same reason.
+ from repowise.cli.helpers import err_console
+
+ err_console.print(
"[yellow]Search index left unchanged:[/yellow] this run has no real embedder, "
"and the\nexisting index was built with one. Kept it rather than overwrite it. "
"Set an\nembedder key and run [cyan]repowise reindex[/cyan] to refresh it."
diff --git a/tests/unit/cli/test_format_json_rollout.py b/tests/unit/cli/test_format_json_rollout.py
new file mode 100644
index 000000000..e97808e0f
--- /dev/null
+++ b/tests/unit/cli/test_format_json_rollout.py
@@ -0,0 +1,407 @@
+"""Every command with a machine-readable mode spells it ``--format``.
+
+Phase 1 built the seam (``output.py``) and gave ``search`` the first
+``--format json``. This pins the rollout across the rest of the agent-facing
+surface, plus the three legacy spellings (``--json`` on ``hook stats`` and the
+``workspace`` reports, ``--output`` on ``security scan``) that now resolve onto
+``--format`` while continuing to work.
+
+Two properties matter more than any individual payload and are tested as
+properties rather than per-command:
+
+1. **``--format`` is the only documented spelling.** A command that grows a
+ fourth flag name for the same axis is the problem this phase exists to fix,
+ so the alias flags must be hidden.
+2. **stdout under json is one parseable document.** Notices, warnings and tips
+ go to stderr. A print in a *called* module cannot be diverted by the
+ command, which is why ``providers/vector_store.py`` is pinned here too.
+"""
+
+from __future__ import annotations
+
+import json
+
+import click
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.output import (
+ emit_json,
+ format_option,
+ json_option,
+ notice_console,
+ resolve_format,
+)
+
+# (import path, attribute) for every command that gained --format in phase 2,
+# plus the three that had a legacy spelling folded onto it.
+_FORMAT_COMMANDS = [
+ ("repowise.cli.commands.status_cmd", "status_command"),
+ ("repowise.cli.commands.costs_cmd", "costs_command"),
+ ("repowise.cli.commands.saved_cmd", "saved_command"),
+ ("repowise.cli.commands.corrections_cmd", "corrections_command"),
+ ("repowise.cli.commands.whats_new_cmd", "whats_new_command"),
+ ("repowise.cli.commands.decision_cmd", "decision_list"),
+ ("repowise.cli.commands.decision_cmd", "decision_show"),
+ ("repowise.cli.commands.decision_cmd", "decision_health"),
+ ("repowise.cli.commands.coverage_cmd", "coverage_status"),
+ ("repowise.cli.commands.security_cmd", "security_scan"),
+ ("repowise.cli.commands.hook_cmd", "hook_stats"),
+ ("repowise.cli.commands.workspace_cmd", "workspace_check"),
+ ("repowise.cli.commands.workspace_cmd", "workspace_diagnostics"),
+ ("repowise.cli.commands.workspace_cmd", "workspace_metrics"),
+]
+
+# Commands that shipped a machine mode under a different name. The old flag
+# keeps working (scripts and CI jobs already call it) but is hidden, so
+# ``--help`` documents exactly one spelling.
+_LEGACY_ALIASES = [
+ ("repowise.cli.commands.hook_cmd", "hook_stats", "--json"),
+ ("repowise.cli.commands.workspace_cmd", "workspace_check", "--json"),
+ ("repowise.cli.commands.workspace_cmd", "workspace_diagnostics", "--json"),
+ ("repowise.cli.commands.workspace_cmd", "workspace_metrics", "--json"),
+ ("repowise.cli.commands.security_cmd", "security_scan", "--output"),
+]
+
+
+def _load(module: str, attr: str):
+ import importlib
+
+ return getattr(importlib.import_module(module), attr)
+
+
+def _params(cmd) -> dict[str, click.Parameter]:
+ return {opt: p for p in cmd.params for opt in p.opts}
+
+
+def _split_runner() -> CliRunner:
+ """A runner that keeps stderr out of ``result.stdout``.
+
+ The whole point of the notice diversion is that the two streams are
+ separate, so a runner that merges them cannot see whether it worked.
+ ``mix_stderr`` exists on click 8.1 and was removed in 8.2, where the
+ streams are already separate — hence the signature check rather than a
+ version comparison.
+ """
+ import inspect
+
+ if "mix_stderr" in inspect.signature(CliRunner.__init__).parameters:
+ return CliRunner(mix_stderr=False)
+ return CliRunner()
+
+
+# ---------------------------------------------------------------------------
+# One convention
+# ---------------------------------------------------------------------------
+
+
[email protected](("module", "attr"), _FORMAT_COMMANDS)
+def test_command_offers_format_json(module: str, attr: str) -> None:
+ param = _params(_load(module, attr)).get("--format")
+ assert param is not None, f"{attr} has no --format"
+ assert "json" in param.type.choices
+ assert param.default == "table", "table stays the default; agents opt in"
+
+
[email protected](("module", "attr", "flag"), _LEGACY_ALIASES)
+def test_legacy_alias_still_accepted_but_hidden(module: str, attr: str, flag: str) -> None:
+ param = _params(_load(module, attr))[flag]
+ assert param.hidden, f"{attr} {flag} should be hidden, not documented"
+
+
[email protected](("module", "attr", "flag"), _LEGACY_ALIASES)
+def test_legacy_alias_absent_from_help(module: str, attr: str, flag: str) -> None:
+ result = CliRunner().invoke(_load(module, attr), ["--help"])
+ assert result.exit_code == 0
+ assert "--format" in result.output
+ assert flag not in result.output
+
+
+ ("module", "attr", "args"),
+ [
+ ("repowise.cli.commands.workspace_cmd", "workspace_check", ["--json"]),
+ ("repowise.cli.commands.workspace_cmd", "workspace_diagnostics", ["--json"]),
+ ("repowise.cli.commands.workspace_cmd", "workspace_metrics", ["--json"]),
+ ("repowise.cli.commands.hook_cmd", "hook_stats", ["--json"]),
+ ("repowise.cli.commands.security_cmd", "security_scan", ["--output", "json"]),
+ ],
+)
+def test_legacy_alias_actually_selects_json(module: str, attr: str, args, tmp_path) -> None:
+ """Hidden is not enough — the alias has to still *work*.
+
+ Checking ``param.hidden`` passes even if the ``resolve_format`` call that
+ folds the alias into ``fmt`` were deleted from the body, which is exactly
+ the regression the aliasing introduces. So each one is invoked and its
+ stdout parsed. The workspace commands abort without a workspace and
+ ``hook stats`` without a ledger; both are run from a bare ``tmp_path``, so
+ what is pinned is the *no-crash, stdout-is-json-or-the-abort-path*
+ contract rather than a populated payload.
+ """
+ cmd = _load(module, attr)
+ runner = _split_runner()
+ with runner.isolated_filesystem(temp_dir=tmp_path):
+ result = runner.invoke(cmd, args)
+ if result.exit_code == 0 and result.stdout.strip():
+ json.loads(result.stdout) # must be one parseable document
+ else:
+ # A ClickException abort is fine; an unhandled traceback is not.
+ assert not isinstance(result.exception, (TypeError, KeyError, NameError)), (
+ result.exception
+ )
+
+
+def test_resolve_format_lets_the_alias_only_select_json() -> None:
+ assert resolve_format("table", True) == "json"
+ assert resolve_format("json", True) == "json"
+ assert resolve_format("json", False) == "json"
+ # The alias is a flag, so its unset state must not veto --format json.
+ assert resolve_format("table", False) == "table"
+
+
+# ---------------------------------------------------------------------------
+# stdout stays parseable
+# ---------------------------------------------------------------------------
+
+
+def test_notice_console_is_stderr_under_json() -> None:
+ from repowise.cli.helpers import console, err_console
+
+ assert notice_console("json") is err_console
+ assert notice_console("table") is console
+
+
+def test_vector_store_refusal_prints_to_stderr(monkeypatch, tmp_path, capsys) -> None:
+ """A print two modules down cannot be diverted by the command.
+
+ ``build_vector_store`` refuses to overwrite a real index with mock vectors
+ and says so. On the shared stdout console that sentence lands inside the
+ JSON document of whichever command asked for a store, and the keyless repo
+ that triggers it is the common case, not an edge one.
+ """
+ from repowise.cli import providers
+ from repowise.core.providers.embedding.base import MockEmbedder
+
+ monkeypatch.setattr(
+ "repowise.cli.providers.vector_store.existing_vector_dim", lambda _d: 1536
+ )
+ assert providers.build_vector_store(tmp_path, MockEmbedder()) is None
+
+ captured = capsys.readouterr()
+ assert "Search index left unchanged" in captured.err
+ assert captured.out == ""
+
+
+def test_emit_json_writes_one_parseable_document(capsys) -> None:
+ emit_json({"a": 1, "nested": {"b": [1, 2]}})
+ assert json.loads(capsys.readouterr().out) == {"a": 1, "nested": {"b": [1, 2]}}
+
+
+# ---------------------------------------------------------------------------
+# The seam's own options
+# ---------------------------------------------------------------------------
+
+
+def test_format_option_binds_to_fmt() -> None:
+ @click.command()
+ @format_option()
+ def cmd(fmt: str) -> None:
+ click.echo(fmt)
+
+ assert CliRunner().invoke(cmd, ["--format", "json"]).output.strip() == "json"
+ assert CliRunner().invoke(cmd, []).output.strip() == "table"
+
+
+def test_json_option_binds_to_as_json_and_is_hidden() -> None:
+ @click.command()
+ @format_option()
+ @json_option()
+ def cmd(fmt: str, as_json: bool) -> None:
+ click.echo(resolve_format(fmt, as_json))
+
+ assert CliRunner().invoke(cmd, ["--json"]).output.strip() == "json"
+ assert "--json" not in CliRunner().invoke(cmd, ["--help"]).output
+
+
+def test_format_option_rejects_an_unknown_format() -> None:
+ @click.command()
+ @format_option()
+ def cmd(fmt: str) -> None: # pragma: no cover - never reached
+ click.echo(fmt)
+
+ result = CliRunner().invoke(cmd, ["--format", "yaml"])
+ assert result.exit_code != 0
+
+
+# ---------------------------------------------------------------------------
+# Payload shape where a caller would depend on it
+# ---------------------------------------------------------------------------
+
+
+def test_whats_new_json_carries_every_selected_release() -> None:
+ """json applies none of the table path's 5-release / 8-bullet caps.
+
+ The caps exist to keep a panel readable. Applying them to json would be
+ the same silent truncation this phase removed from the table path, one
+ layer down.
+ """
+ from repowise.cli.commands.whats_new_cmd import whats_new_command
+
+ result = CliRunner().invoke(whats_new_command, ["--all", "--format", "json"])
+ assert result.exit_code == 0
+ payload = json.loads(result.output)
+ assert len(payload["releases"]) > 5
+ assert all("version" in r and "sections" in r for r in payload["releases"])
+ # The cap that matters is the 8-bullet one, so at least one release has to
+ # carry more than 8 bullets. Asserting only that the keys exist would pass
+ # against a payload whose sections are all empty.
+ assert max(
+ sum(len(s["items"]) for s in r["sections"]) for r in payload["releases"]
+ ) > 8
+
+
+def test_status_json_reports_absence_rather_than_only_a_notice(tmp_path) -> None:
+ """An unindexed repo still owes stdout a document.
+
+ A command that prints a human notice and nothing else leaves the agent
+ parsing an empty string, which is indistinguishable from a crash.
+ """
+ from repowise.cli.commands.status_cmd import status_command
+
+ result = _split_runner().invoke(
+ status_command, [str(tmp_path), "--no-workspace", "--format", "json"]
+ )
+ assert result.exit_code == 0
+ assert json.loads(result.stdout)["indexed"] is False
+
+
+def test_corrections_json_write_does_not_prune_when_the_scan_found_nothing(
+ monkeypatch, tmp_path
+) -> None:
+ """``--write`` must do the same thing in both formats.
+
+ The table path returns before it can write when no rules were found. json
+ emits its document first, so without an explicit guard the same invocation
+ would fall through and *remove* the managed block from a file the user
+ maintains — a destructive difference between two spellings of one command.
+ """
+ from repowise.cli.commands import corrections_cmd
+
+ monkeypatch.setattr(
+ "repowise.core.distill.corrections.scan_corrections",
+ lambda *_a, **_k: {"rules": []},
+ )
+ wrote: list = []
+ monkeypatch.setattr(
+ corrections_cmd, "_write_managed_blocks", lambda *a, **k: wrote.append(a)
+ )
+
+ result = _split_runner().invoke(
+ corrections_cmd.corrections_command,
+ [str(tmp_path), "--write", "--format", "json"],
+ )
+ assert result.exit_code == 0
+ assert json.loads(result.stdout)["rules"] == []
+ assert wrote == [], "an empty scan must not touch the managed block"
+
+
+def test_workspace_rows_give_every_repo_the_same_keys(tmp_path) -> None:
+ """An unindexed repo reports ``None``, not a missing key.
+
+ ``status --format json`` fans out over a workspace, and a consumer that
+ has to branch on ``indexed`` before it may read ``stale`` is barely better
+ off than one parsing the table. Pins the row contract and the table path's
+ "not indexed" branch at the same time.
+ """
+ from types import SimpleNamespace
+
+ from repowise.cli.commands.status_cmd import _workspace_rows
+
+ indexed = tmp_path / "api"
+ (indexed / ".repowise").mkdir(parents=True)
+ (tmp_path / "web").mkdir()
+
+ target = SimpleNamespace(
+ ws_root=tmp_path,
+ ws_config=SimpleNamespace(
+ default_repo="api",
+ repos=[
+ SimpleNamespace(alias="api", path="api", indexed_at=None,
+ last_commit_at_index=None),
+ SimpleNamespace(alias="web", path="web", indexed_at=None,
+ last_commit_at_index=None),
+ ],
+ ),
+ )
+ rows = _workspace_rows(target)
+
+ assert [r["alias"] for r in rows] == ["api", "web"]
+ assert [r["indexed"] for r in rows] == [True, False]
+ assert [r["primary"] for r in rows] == [True, False]
+ assert set(rows[0]) == set(rows[1]), "row shape must not depend on indexed"
+ unindexed = rows[1]
+ assert all(
+ unindexed[k] is None
+ for k in ("files", "symbols", "pages", "docs_mode", "storage_bytes", "head", "stale")
+ )
+ # The whole payload has to survive json.dumps; a Path or a rich string here
+ # would only show up at emit time.
+ assert json.loads(json.dumps(rows, default=str))
+
+
+def test_forgone_rows_keeps_what_it_read_when_a_later_surface_errors(
+ monkeypatch, tmp_path
+) -> None:
+ """A mid-loop sqlite error must not retract earlier surfaces.
+
+ The printer this was split out of printed each surface as it went, so a
+ failure on surface 2 left surface 1's line on screen. Accumulating into a
+ list makes ``return []`` silently lose it, which is a reporting regression
+ no test would otherwise catch.
+ """
+ import sqlite3
+
+ from repowise.cli.commands import saved_cmd
+
+ class _Row:
+ def __init__(self, row):
+ self._row = row
+
+ def fetchone(self):
+ return self._row
+
+ calls = {"n": 0}
+
+ class _Con:
+ def execute(self, *_a, **_k):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return _Row((3, 900, 100))
+ raise sqlite3.OperationalError("database is locked")
+
+ def close(self) -> None:
+ pass
+
+ # ``_forgone_rows`` imports sqlite3 inside the function, so the module
+ # attribute is what it resolves at call time.
+ monkeypatch.setattr(sqlite3, "connect", lambda *a, **k: _Con())
+ monkeypatch.setattr(
+ "repowise.cli.commands.augment_cmd._shared.hook_flag_enabled", lambda *_a: False
+ )
+
+ rows = saved_cmd._forgone_rows(tmp_path, tmp_path / "omissions.db", None)
+ assert len(rows) == 1, "the surface read before the error must survive"
+ assert rows[0]["forgone_tokens"] == 800
+
+
+def test_security_scan_json_without_history_still_emits_a_document() -> None:
+ """And the human notice that accompanies it is on stderr, not in the payload."""
+ from repowise.cli.commands.security_cmd import security_scan
+
+ result = _split_runner().invoke(security_scan, ["--format", "json"])
+ assert result.exit_code == 0
+ assert json.loads(result.stdout) == {
+ "scanned": False,
+ "reason": "history-mode-not-requested",
+ }
+ assert "Working-tree scanning" in result.stderr
diff --git a/tests/unit/cli/test_security_cmd.py b/tests/unit/cli/test_security_cmd.py
index 7c4df11cc..007ea6678 100644
--- a/tests/unit/cli/test_security_cmd.py
+++ b/tests/unit/cli/test_security_cmd.py
@@ -31,7 +31,10 @@ def test_security_scan_help_lists_history_flags() -> None:
assert "--since" in result.output
assert "--to" in result.output
assert "--all-patterns" in result.output
- assert "--output" in result.output
+ # ``--output`` still works but is hidden: the machine-readable axis is
+ # spelled ``--format`` everywhere now, and --help documents one name.
+ assert "--format" in result.output
+ assert "--output" not in result.output
@dataclass
diff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.py
index a618e55c8..78dc49ced 100644
--- a/tests/unit/cli/test_workspace_cmd.py
+++ b/tests/unit/cli/test_workspace_cmd.py
@@ -521,7 +521,10 @@ class TestWorkspaceDiagnostics:
def test_diagnostics_help(self, runner):
result = runner.invoke(cli, ["workspace", "diagnostics", "--help"])
assert result.exit_code == 0
- assert "--json" in result.output
+ # ``--json`` still works but is hidden; ``--format`` is the one
+ # documented spelling. See tests/unit/cli/test_format_json_rollout.py.
+ assert "--format" in result.output
+ assert "--json" not in result.output
# ---------------------------------------------------------------------------