Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(init): short lines when piped, and --progress json for agents (#4254)
Raghav Chamadiyac18680f1cdb9
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex c64dad933..5327e831d 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -192,6 +192,7 @@ All three reach the indexing knobs; the LLM-only knobs appear only when model-wr| `--test-run` | Write docs with the model for only the top 10 files (by PageRank). Not with `--no-prose` or `--mode fast` || `--all` | In multi-repo mode, index every detected repo without prompting || `--no-workspace` | Force single-repo mode even when invoked from a workspace root (indexes only the target PATH instead of fanning out across workspace repos) |+| `--progress` | `rich` (default): a live checklist in a terminal, one short line per step (at most 100 columns) anywhere else. `json`: one JSON event per line on stdout, ending with a summary line; see below. |**Examples:**@@ -223,6 +224,16 @@ there was no terminal, so re-run with `--yes`). `130` interrupted: run`repowise init --resume` to continue. Any other non-zero code is a failure; ausage error (a bad flag) also exits `2`, before anything runs.+**Driving init from an agent or script.** `repowise init --yes --no-prose --progress json`+writes only JSON lines to stdout; human text goes to stderr. Every line has `v`+(schema version, `1`) and `event`: `stage`, `phase` (`state` is `start`, `done`+or `failed`, with `completed`, `total`, `unit` and `elapsed_s`), `warning`, and+last `summary`. The summary's `status` is `ready`, `degraded`, `interrupted` or+`failed`, matching exit `0`, `2`, `130` or any other code, and it carries+`mode` (`key` from the index scope, `label`, `run_mode`), `restart_required`+(the editor needs a restart or `/mcp` to load the tools), `spend` (`tokens`,+`usd`), `warnings`, `files_written` and `next` (commands, `repowise serve` first).+With a real embedder (anything but `mock`), a run whose page vectors fail towrite, for example because the LanceDB install is broken, keeps its pages andfull-text index, records `search.semantic: unavailable` in the index scope, anddiff --git a/packages/cli/src/repowise/cli/agent_events.py b/packages/cli/src/repowise/cli/agent_events.pynew file mode 100644index 000000000..6611a3e68--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_events.py@@ -0,0 +1,120 @@+"""The NDJSON stream ``--progress json`` writes on stdout, for agents and scripts.++One JSON object per line. Every object carries ``v`` (:data:`SCHEMA_VERSION`)+and ``event``:++- ``stage``: a top-level stage opened. ``stage``, ``title``.+- ``phase``: a step started, finished or failed. ``phase`` (stable id),+ ``label``, ``state`` (``start`` / ``done`` / ``failed``), ``completed``,+ ``total`` (null when unknown), ``unit``, ``elapsed_s`` (null on ``start``).+- ``warning``: something the run skipped or degraded. ``level``, ``text``.+- ``summary``: always the last line. ``status`` is ``ready`` (exit 0),+ ``degraded`` (exit 2), ``interrupted`` (exit 130) or ``failed`` (any other+ exit, with ``error``); then ``mode``, ``restart_required``, ``spend``,+ ``warnings``, ``files_written`` and ``next`` (commands, first one first).++While the stream is open, human text goes to stderr, so stdout is only these lines.+"""++from __future__ import annotations++import contextlib+import json+import sys+from collections.abc import Iterator+from typing import IO, Any++from repowise.cli.exit_codes import EXIT_DEGRADED, EXIT_INTERRUPTED++#: Bumped on any change a consumer would have to handle: a renamed or removed+#: field, or a changed meaning. New fields do not bump it.+SCHEMA_VERSION = 1++STATUS_READY = "ready"+STATUS_DEGRADED = "degraded"+STATUS_INTERRUPTED = "interrupted"+STATUS_FAILED = "failed"++_STATUS_BY_EXIT = {0: STATUS_READY, EXIT_DEGRADED: STATUS_DEGRADED, EXIT_INTERRUPTED: STATUS_INTERRUPTED}+++def status_for_exit(code: Any) -> str:+ """The summary status for a process exit code (``None`` is 0, as for ``SystemExit``)."""+ return _STATUS_BY_EXIT.get(0 if code is None else code, STATUS_FAILED)+++def summary_fields(+ status: str,+ *,+ mode: dict[str, Any] | None = None,+ restart_required: bool = False,+ spend: dict[str, Any] | None = None,+ warnings: list[str] | None = None,+ files_written: list[str] | None = None,+ next_commands: list[str] | None = None,+ error: str | None = None,+) -> dict[str, Any]:+ """Every summary key, always present, so a consumer never probes for one."""+ fields: dict[str, Any] = {+ "status": status,+ "mode": mode,+ "restart_required": restart_required,+ "spend": spend or {"tokens": 0, "usd": 0.0},+ "warnings": list(warnings or []),+ "files_written": list(files_written or []),+ "next": list(next_commands or []),+ }+ if error is not None:+ fields["error"] = error+ return fields+++class EventStream:+ """Writes one event per line and flushes, so a reader sees each as it happens."""++ def __init__(self, stream: IO[str]) -> None:+ self._stream = stream+ self.summary_sent = False++ def emit(self, event: str, **fields: Any) -> None:+ line = json.dumps({"v": SCHEMA_VERSION, "event": event, **fields}, default=str)+ self._stream.write(line + "\n")+ self._stream.flush()++ def summary(self, fields: dict[str, Any]) -> None:+ """The last line. Only the first call writes: the most specific caller wins."""+ if self.summary_sent:+ return+ self.summary_sent = True+ self.emit("summary", **fields)+++_active: EventStream | None = None+++def active() -> EventStream | None:+ """The open stream, or None when output is for a person."""+ return _active+++def open_stream(console: Any) -> Iterator[EventStream]:+ """Point stdout at the event stream and *console* at stderr until the block ends."""+ from repowise.cli.helpers import silence_logs_for_machine_output+ from repowise.cli.output import line_output_width, resolve_console_width++ global _active+ # ``_file`` is None for a console that follows sys.stdout, and ``_width``+ # None for one that measures its terminal; restore exactly those.+ previous_file, previous_width = console._file, console._width+ stream = EventStream(sys.stdout)+ console.file = sys.stderr+ console._width = resolve_console_width(sys.stderr)+ _active = stream+ try:+ with silence_logs_for_machine_output(), line_output_width(console, sys.stderr):+ yield stream+ finally:+ _active = None+ console.file = previous_file+ console._width = previous_widthdiff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_agent_summary.py b/packages/cli/src/repowise/cli/commands/init_cmd/_agent_summary.pynew file mode 100644index 000000000..bd29249ea--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_agent_summary.py@@ -0,0 +1,142 @@+"""How ``repowise init`` writes for a reader that is not a person.++Off a terminal, lines stay within :data:`~repowise.cli.output.LINE_OUTPUT_WIDTH`.+Under ``--progress json``, stdout is the :mod:`repowise.cli.agent_events`+stream, and every exit ends it with a ``summary`` line.+"""++from __future__ import annotations++import contextlib+import sys+from collections.abc import Iterator, Mapping+from pathlib import Path+from typing import Any++import click++from repowise.cli import agent_events+from repowise.cli.helpers import console, load_config, load_state+from repowise.cli.output import line_output_width++from ._ingest import RESUME_COMMAND+from ._options import InitRun++SERVE_COMMAND = "repowise serve"+++def mode_of(scope: Mapping[str, Any]) -> dict[str, Any]:+ """``{"key", "label", "run_mode"}`` for a resolved index scope.++ ``key`` is ``index_scope.content_provenance``: ``model``, ``template``,+ ``none`` (fast, no documentation), ``mixed`` or ``unknown``.+ """+ key = scope.get("content_provenance") or "unknown"+ if key == "unknown" and scope.get("run_mode") == "fast":+ key = "none"+ from repowise.cli.ui.mode_names import mode_label++ return {"key": key, "label": mode_label(scope), "run_mode": scope.get("run_mode")}+++def _stored_mode(repo_path: Path) -> dict[str, Any] | None:+ """The mode state.json records, or None when this repo has no index yet."""+ from repowise.core.index_scope import resolve_index_scope++ # Runs inside the exit handlers: an unreadable state.json must not cost the+ # summary. load_config already degrades a broken config to {}.+ try:+ state = load_state(repo_path)+ except (OSError, ValueError):+ return None+ if not isinstance(state, dict) or not state.get("index_scope"):+ return None+ return mode_of(resolve_index_scope(state, load_config(repo_path)))+++def _relative(repo_path: Path, paths: list[Path]) -> list[str]:+ out = []+ for path in paths:+ try:+ out.append(path.relative_to(repo_path).as_posix())+ except ValueError:+ out.append(str(path))+ return out+++def _restart_required(run: InitRun) -> bool:+ """Whether the editor must restart (or run /mcp) to load the tools, as the panel says."""+ setup = run.setup_outcome+ if setup is None or setup.editor_setup_disabled or not setup.claude_code_connected:+ return False+ return bool(setup.first_index or run.mcp_repointed)+++def _spend(result: Any) -> dict[str, Any]:+ pages = getattr(result, "generated_pages", None) or []+ cost = getattr(result, "llm_cost_usd", None)+ return {+ "tokens": sum(getattr(p, "total_tokens", 0) or 0 for p in pages),+ "usd": round(cost or 0.0, 4),+ }+++def _next_commands(run: InitRun) -> list[str]:+ """The panel's next steps, ``repowise serve`` first."""+ commands = [command for command, _gloss in run.next_steps]+ if SERVE_COMMAND not in commands:+ commands.insert(0, SERVE_COMMAND)+ return commands+++def run_summary(run: InitRun, gaps: list[str]) -> dict[str, Any]:+ """The summary of a run that finished: ready, or degraded by *gaps*."""+ return agent_events.summary_fields(+ agent_events.STATUS_DEGRADED if gaps else agent_events.STATUS_READY,+ mode=_stored_mode(run.repo_path),+ restart_required=_restart_required(run),+ spend=_spend(run.result),+ warnings=[*run.run_warnings, *gaps],+ files_written=_relative(run.repo_path, run.files_written),+ next_commands=_next_commands(run),+ )+++def _exit_summary(status: str, repo_path: Path | None) -> dict[str, Any]:+ """The summary when the run ended before :func:`run_summary` could be built."""+ if status == agent_events.STATUS_INTERRUPTED:+ return agent_events.summary_fields(status, next_commands=[RESUME_COMMAND])+ mode = _stored_mode(repo_path) if repo_path is not None else None+ next_commands = [SERVE_COMMAND] if mode is not None and status != agent_events.STATUS_FAILED else []+ return agent_events.summary_fields(status, mode=mode, next_commands=next_commands)+++def init_output(progress: str, repo_path: Path | None) -> Iterator[None]:+ """Cap line width off a terminal; under ``--progress json``, own stdout until exit."""+ if progress != "json":+ with line_output_width(console, sys.stdout):+ yield+ return+ with agent_events.open_stream(console) as events:+ try:+ yield+ except SystemExit as exc:+ events.summary(_exit_summary(agent_events.status_for_exit(exc.code), repo_path))+ raise+ except click.exceptions.Exit as exc:+ events.summary(_exit_summary(agent_events.status_for_exit(exc.exit_code), repo_path))+ raise+ except click.ClickException as exc:+ events.summary(+ agent_events.summary_fields(agent_events.STATUS_FAILED, error=exc.format_message())+ )+ raise+ except BaseException as exc:+ events.summary(+ agent_events.summary_fields(+ agent_events.STATUS_FAILED, error=str(exc) or type(exc).__name__+ )+ )+ raise+ events.summary(_exit_summary(agent_events.STATUS_READY, repo_path))diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.pyindex d78728990..1fa450521 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_finish.py@@ -20,7 +20,7 @@ from repowise.cli.helpers import (save_state,)from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json-from repowise.cli.ui import OK, RichProgressCallback, make_progress, print_stage+from repowise.cli.ui import OK, print_stage, progress_stepsfrom repowise.core.analysis.health import HEALTH_ANALYZER_VERSIONfrom repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSIONfrom repowise.core.decision_lanes import record_decision_lanes@@ -46,8 +46,7 @@ def persist_index(run: InitRun) -> None:print_stage(console, "persistence", run.total_phases)recorder = run.recorder- with make_progress(console) as persist_bar:- steps = RichProgressCallback(persist_bar, console)+ with progress_steps(console, stage="persistence") as steps:persist_callback = recorder.rebind(steps)# Indeterminate, announced so the stage is never silent.persist_callback.on_phase_start("persist", None)@@ -109,13 +108,15 @@ def register_clients(run: InitRun) -> None:"""Global client registration, then the workspace's distill verdict."""from repowise.cli.editor_integrations.global_mcp import confirm_global_mcp+ no_editor_setup = not run.opts.editor_setupif confirm_global_mcp(console,run.repo_path,yes=run.opts.yes,- no_editor_setup=not run.opts.editor_setup,+ no_editor_setup=no_editor_setup,):- register_editor_clients(console, run.repo_path)+ run.mcp_repointed = _mcp_entry_moves(run.repo_path)+ register_editor_clients(console, run.repo_path, no_editor_setup=no_editor_setup)# Before the config fingerprint: left unwritten, the first update writes it,# sees a fingerprint change and re-scores every file.@@ -124,6 +125,18 @@ def register_clients(run: InitRun) -> None:inherit_workspace_distill_verdict(run.repo_path)+def _mcp_entry_moves(repo_path: Path) -> bool:+ """Whether registering writes a new or moved global repowise MCP entry. Read-only.++ The consent gate's own probe, so the two cannot disagree; an unreadable+ config reads as no move, as it does there.+ """+ from repowise.cli.editor_integrations.global_mcp import _probe++ target = _probe(repo_path)+ return target is not None and (target.repoints or target.command_changes)++def _docs_mode(run: InitRun) -> str:"""``llm``, ``deterministic`` (templates) or ``none`` (fast mode)."""if run.opts.run_mode == "fast":@@ -359,7 +372,7 @@ def _record_init_outcome(run: InitRun) -> None:)-def _write_editor_files(run: InitRun, steps: RichProgressCallback) -> list[Path]:+def _write_editor_files(run: InitRun, steps: Any) -> list[Path]:"""Read views, project editor files and the coverage hook; returns the files written.Runs after state is saved so the guidance reads the final index_scope.@@ -391,8 +404,7 @@ def complete_setup(run: InitRun) -> None:opts = run.optsrepo_path = run.repo_path# The prompts below cannot run under a live display, so it closes first.- with make_progress(console) as tail_bar:- steps = RichProgressCallback(tail_bar, console)+ with progress_steps(console) as steps:with steps.step("state"):write_run_state(run)files_written = _write_editor_files(run, steps)@@ -418,13 +430,14 @@ def complete_setup(run: InitRun) -> None:# offers' gate: when they were skipped the panel names their hooks.from repowise.cli.editor_setup import detect_editor_setup_outcome- setup_outcome = detect_editor_setup_outcome(+ run.files_written = files_written+ run.setup_outcome = setup_outcome = detect_editor_setup_outcome(repo_path,interactive=(sys.stdin.isatty() and not opts.yes),first_index=run.first_index,no_editor_setup=not opts.editor_setup,)- show_completion(+ run.next_steps = show_completion(repo_path=repo_path,result=run.result,start=run.start,@@ -438,17 +451,20 @@ def complete_setup(run: InitRun) -> None:def exit_with_gaps(run: InitRun) -> None:"""Exit degraded when the run left a gap; last, so everything else is kept."""+ from repowise.cli.agent_events import activefrom repowise.cli.providers import embed_failure_message+ from ._agent_summary import run_summaryfrom ._exit import exit_on_gaps, run_gapsresult = run.result- exit_on_gaps(- run.gaps- + run_gaps(- failed_pages=len(getattr(result, "failed_page_ids", None) or []),- embed_error=embed_failure_message(- run.scope_embedder, getattr(result, "embed_failed_pages", 0)- ),- )+ gaps = run.gaps + run_gaps(+ failed_pages=len(getattr(result, "failed_page_ids", None) or []),+ embed_error=embed_failure_message(+ run.scope_embedder, getattr(result, "embed_failed_pages", 0)+ ),)+ events = active()+ if events is not None:+ events.summary(run_summary(run, gaps))+ exit_on_gaps(gaps)diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py b/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.pyindex 952058ff5..2d601ef65 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_ingest.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom typing import Anyfrom repowise.cli.helpers import console, load_state, run_async-from repowise.cli.ui import RichProgressCallback, make_progress+from repowise.cli.ui import progress_stepsfrom ._options import InitRunfrom .persistence import build_resume_controller@@ -126,11 +126,13 @@ def index_repository(run: InitRun) -> None:index_vector_store = _index_vector_store(run)# Cost column only when a model can be called.- with make_progress(- console, cost=llm_client is not None, resume_command=RESUME_COMMAND- ) as progress_bar:- rich_callback = RichProgressCallback(progress_bar, console, total_phases=run.total_phases)- callback = PhaseTimingRecorder(rich_callback)+ with progress_steps(+ console,+ cost=llm_client is not None,+ resume_command=RESUME_COMMAND,+ total_phases=run.total_phases,+ ) as steps:+ callback = PhaseTimingRecorder(steps)# Whole-run total: phases nest and overlap, so their sum can exceed it.callback.table.start("run")@@ -162,4 +164,4 @@ def index_repository(run: InitRun) -> None:run.result = resultrun.recorder = callback- run.run_warnings = list(rich_callback.warnings)+ run.run_warnings = list(steps.warnings)diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py b/packages/cli/src/repowise/cli/commands/init_cmd/_options.pyindex 3ddd1e626..48a8c5f23 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_options.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_options.py@@ -109,6 +109,11 @@ class InitRun:effective_index_only: bool = Falsephase_timings: dict[str, float] = field(default_factory=dict)scope_embedder: str | None = None+ # What the finish reported, kept for the --progress json summary.+ mcp_repointed: bool = False+ setup_outcome: Any = None+ files_written: list[Path] = field(default_factory=list)+ next_steps: list[tuple[str, str]] = field(default_factory=list)def resolve_structural_flags(opts: InitOptions) -> InitOptions:diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex 2fd5cb3a3..3f9f3ae80 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -25,6 +25,7 @@ from repowise.core.generation.styles import list_styles, resolve_stylefrom repowise.core.reasoning import REASONING_MODESfrom repowise.core.update_lock import init_in_progress+from ._agent_summary import init_outputfrom ._exit import exit_interruptedfrom ._finish import (complete_setup,@@ -447,7 +448,13 @@ def _run_workspace_init(opts: InitOptions, scan: Any) -> None:"--progress",type=click.Choice(["rich", "json"]),default="rich",- help="Progress output style.",+ help=(+ "Progress output. 'rich' (default) draws a live checklist in a terminal "+ "and one short line per step anywhere else. 'json' writes one JSON event "+ "per line to stdout (stages, steps, warnings) and ends with a summary "+ "line: status, mode, restart_required, spend, warnings, files_written "+ "and next commands. Human text goes to stderr."+ ),)def init_command(**params: Any) -> None:"""Index a codebase and build its documentation.@@ -460,10 +467,11 @@ def init_command(**params: Any) -> None:"""from repowise.core.cancellation import PipelineCancelled- try:- _run_init(resolve_structural_flags(InitOptions(**params)))- except (PipelineCancelled, KeyboardInterrupt):- exit_interrupted()+ with init_output(params.get("progress", "rich"), resolve_repo_path(params.get("path"))):+ try:+ _run_init(resolve_structural_flags(InitOptions(**params)))+ except (PipelineCancelled, KeyboardInterrupt):+ exit_interrupted()def _run_init(opts: InitOptions) -> None:diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.pyindex 05a03f45a..a300b2bc7 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py@@ -40,8 +40,7 @@ from repowise.cli.ui import (OK,OWL_SPINNER,WARN,- RichProgressCallback,- make_progress,+ progress_steps,)from repowise.core.generation.models import (STUB_FALLBACK_ERROR,@@ -301,10 +300,8 @@ def run_repo_generation(vector_store: Any = getattr(result, "vector_store", None)if vector_store is None and verbose:# Opening the store can take seconds on a large index; say so.- with make_progress(console) as store_bar:- steps = RichProgressCallback(store_bar, console)- with steps.step("vector_store"):- vector_store = build_vector_store(repo_path, embedder_impl)+ with progress_steps(console) as steps, steps.step("vector_store"):+ vector_store = build_vector_store(repo_path, embedder_impl)elif vector_store is None:vector_store = build_vector_store(repo_path, embedder_impl)result.vector_store = vector_store@@ -345,14 +342,13 @@ def run_repo_generation(# ``total_phases`` comes only from single-repo init, whose resume this is.from ._ingest import RESUME_COMMAND- with make_progress(+ with progress_steps(console,cost=not deterministic,resume_command=RESUME_COMMAND if total_phases is not None else None,- ) as gen_progress:- gen_callback: Any = RichProgressCallback(- gen_progress, console, total_phases=total_phases, stage="generation"- )+ total_phases=total_phases,+ stage="generation",+ ) as gen_callback:if timings is not None:gen_callback = PhaseTimingRecorder(gen_callback, timings)generated_pages = run_async(diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.pyindex cf3462ed5..8e0e403a2 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py@@ -16,11 +16,11 @@ from repowise.cli.ui import (ERR,OK,WARN,- build_completion_panel,build_contextual_next_steps,build_status_notes,format_elapsed,keyless_upgrade_note,+ print_completion_panel,print_files_written,)from repowise.cli.ui.mode_names import (@@ -93,8 +93,8 @@ def show_completion(provider: Any,setup: Any = None,files_written: list[Path] | None = None,-) -> None:- """Render the final completion panel (index-only or full mode).+) -> list[tuple[str, str]]:+ """Render the final completion panel (index-only or full mode); returns its next steps.*setup* is the :class:`~repowise.cli.editor_setup.EditorSetupOutcome`snapshot, so the next-step panel and the MCP status note reflect what setup@@ -212,9 +212,7 @@ def show_completion(setup=setup,)console.print()- console.print(- build_completion_panel(completion_title(_scope), metrics, next_steps=next_steps)- )+ print_completion_panel(console, completion_title(_scope), metrics, next_steps)console.print()# Fast mode reaches this branch too, and it generates nothing, so the# note has to check rather than assume.@@ -297,9 +295,7 @@ def show_completion()console.print()- console.print(- build_completion_panel(completion_title(_scope), metrics, next_steps=next_steps)- )+ print_completion_panel(console, completion_title(_scope), metrics, next_steps)console.print()_print_embed_failure(_embed_failed)if not _semantic_on and not _embed_failed and _scope["search"]["next_command"]:@@ -324,6 +320,7 @@ def show_completion(print_files_written(console, Path(repo_path), files_written or [])_show_generation_checks(result)+ return next_stepsdef _print_embed_failure(failed: int) -> None:@@ -422,9 +419,7 @@ def show_workspace_completion(next_steps = _workspace_next_steps(run_mode, index_only or provider is None)console.print()- console.print(- build_completion_panel(TITLE_WORKSPACE, metrics, next_steps=next_steps)- )+ print_completion_panel(console, TITLE_WORKSPACE, metrics, next_steps)console.print()# Honest docs status — print a per-repo summary listing exactly whichdiff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex 186146969..fbbe5579f 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -56,15 +56,14 @@ from repowise.cli.ui import (OK,VALUE,WARN,- RichProgressCallback,interactive_advanced_config,interactive_mode_select,interactive_primary_select,interactive_provider_config_select,interactive_repo_select,load_dotenv,- make_progress,print_banner,+ progress_steps,)from repowise.cli.ui.mode_names import pagesfrom repowise.core.ci.markdown import plural@@ -425,8 +424,8 @@ def _index_repo(repo: Any, ctx: _WorkspaceCtx, repo_provider: Any) -> _RepoIndexfrom repowise.core.pipeline import PhaseTimingRecorder, run_pipelinefrom repowise.core.pipeline.modes import OrchestratorMode- with make_progress(console) as progress_bar:- callback = PhaseTimingRecorder(RichProgressCallback(progress_bar, console))+ with progress_steps(console) as steps:+ callback = PhaseTimingRecorder(steps)_prev_state = load_state(repo.path)_prev_kg_fp = (@@ -557,8 +556,8 @@ def _persist_repo_index(repo_path: Path, index: _RepoIndex) -> list[str]:"""Persist to the repo-local DB; returns the persist phase's warnings."""persist_warnings: list[str] = []callback = index.callback- with make_progress(console, transient=True) as persist_bar:- persist_callback = callback.rebind(RichProgressCallback(persist_bar, console))+ with progress_steps(console, transient=True) as persist_steps:+ persist_callback = callback.rebind(persist_steps)persist_callback.on_phase_start("persist", None)try:run_async(persist_result(index.result, repo_path, persist_callback, callback.table))diff --git a/packages/cli/src/repowise/cli/output.py b/packages/cli/src/repowise/cli/output.pyindex be357e199..683187d03 100644--- a/packages/cli/src/repowise/cli/output.py+++ b/packages/cli/src/repowise/cli/output.py@@ -22,8 +22,10 @@ consumers (agents, pipes, CI):from __future__ import annotations+import contextlibimport jsonimport os+from collections.abc import Iteratorfrom typing import IO, Anyimport click@@ -74,6 +76,28 @@ def resolve_console_width(stream: IO[str]) -> int | None:return NON_TTY_WIDTH+#: Width of a pipeline command's progress lines when no person is watching.+#: Its lines are prose, not tables, so the table headroom above only pads+#: rules and panels; ~100 columns reads in any log viewer.+LINE_OUTPUT_WIDTH = 100+++def line_output_width(console: Any, stream: IO[str]) -> Iterator[None]:+ """Hold *console* at :data:`LINE_OUTPUT_WIDTH` while *stream* is not a terminal.++ Rich keeps the width a console was built with in ``_width``; restoring that+ rather than the measured width keeps a terminal console measuring itself.+ """+ previous = console._width+ if resolve_console_width(stream) is not None:+ console.width = LINE_OUTPUT_WIDTH+ try:+ yield+ finally:+ console._width = previous++def _silence_when_machine_readable(ctx: Any, param: Any, value: str) -> str:"""Turn log output off the moment a machine-readable format is selected.@@ -213,11 +237,13 @@ def emit_json(payload: Any) -> None:__all__ = [+ "LINE_OUTPUT_WIDTH","NON_TTY_WIDTH","emit_json","format_option","full_option","json_option",+ "line_output_width","notice_console","resolve_console_width","resolve_format",diff --git a/packages/cli/src/repowise/cli/ui/__init__.py b/packages/cli/src/repowise/cli/ui/__init__.pyindex e709918e1..48184fa0e 100644--- a/packages/cli/src/repowise/cli/ui/__init__.py+++ b/packages/cli/src/repowise/cli/ui/__init__.py@@ -60,12 +60,14 @@ _LAZY: dict[str, str] = {"mini": "mascot","model_call_count": "subscription","print_banner": "brand",+ "print_completion_panel": "result_panels","print_files_written": "result_panels","print_index_only_intro": "mode_selection","print_phase_header": "brand","print_scan_summary": "repo_scanner","print_section": "brand","print_stage": "progress",+ "progress_steps": "progress","prompt_file_page_volume": "mode_selection","prompt_wiki_style": "mode_selection","quick_repo_scan": "repo_scanner",diff --git a/packages/cli/src/repowise/cli/ui/progress.py b/packages/cli/src/repowise/cli/ui/progress.pyindex 27688a9c2..3171362e7 100644--- a/packages/cli/src/repowise/cli/ui/progress.py+++ b/packages/cli/src/repowise/cli/ui/progress.py@@ -351,3 +351,35 @@ class RichProgressCallback:for task_id in self._tasks.values():with contextlib.suppress(Exception):self._progress.update(task_id, cost=total_cost)+++def progress_steps(+ console: Console,+ *,+ cost: bool = False,+ transient: bool = False,+ resume_command: str | None = None,+ total_phases: int | None = None,+ stage: str | None = None,+) -> Iterator[Any]:+ """The step callback a pipeline command drives: the live display, or the+ ``--progress json`` event stream when one is open. Arguments as for+ :func:`~repowise.cli.ui.progress_display.make_progress` and+ :class:`RichProgressCallback`; the stream ignores the display-only ones.+ """+ from repowise.cli.agent_events import active++ events = active()+ if events is not None:+ from repowise.cli.ui.progress_json import JsonProgressCallback++ yield JsonProgressCallback(events, stage=stage)+ return++ from repowise.cli.ui.progress_display import make_progress++ with make_progress(+ console, cost=cost, transient=transient, resume_command=resume_command+ ) as bar:+ yield RichProgressCallback(bar, console, total_phases=total_phases, stage=stage)diff --git a/packages/cli/src/repowise/cli/ui/progress_json.py b/packages/cli/src/repowise/cli/ui/progress_json.pynew file mode 100644index 000000000..cd0717213--- /dev/null+++ b/packages/cli/src/repowise/cli/ui/progress_json.py@@ -0,0 +1,101 @@+"""The ``--progress json`` twin of :class:`~repowise.cli.ui.progress.RichProgressCallback`.++Same interface, same phase labels and units; it writes ``stage``, ``phase`` and+``warning`` events (see :mod:`repowise.cli.agent_events`) instead of drawing.+"""++from __future__ import annotations++import contextlib+import time+from collections.abc import Iterator++from repowise.cli.agent_events import EventStream+from repowise.cli.ui import checklist+from repowise.cli.ui.progress import _DEGRADING_LEVELS, _PHASE_LABELS, _PHASE_UNITS, _STAGES+from repowise.core.redaction import redact_secrets+++class JsonProgressCallback:+ """Implements ``repowise.core.pipeline.ProgressCallback`` as NDJSON events."""++ def __init__(self, events: EventStream, *, stage: str | None = None) -> None:+ self._events = events+ # phase -> [completed, total, started_at]+ self._steps: dict[str, list[float | None]] = {}+ self._done: set[str] = set()+ #: Every warning emitted, in order, as RichProgressCallback keeps them.+ self.warnings: list[str] = []+ if stage is not None:+ self.on_stage(stage)++ def on_stage(self, stage: str) -> None:+ if stage in _STAGES:+ self._events.emit("stage", stage=stage, title=_STAGES[stage][0])++ def _phase(self, phase: str, state: str, elapsed: float | None) -> None:+ completed, total, _ = self._steps[phase]+ label, _depth = checklist.split_label(_PHASE_LABELS.get(phase, phase))+ self._events.emit(+ "phase",+ phase=phase,+ label=label,+ state=state,+ completed=int(completed or 0),+ total=None if total is None else int(total),+ unit=_PHASE_UNITS.get(phase, ""),+ elapsed_s=None if elapsed is None else round(elapsed, 3),+ )++ def on_phase_start(self, phase: str, total: int | None) -> None:+ self._done.discard(phase)+ step = self._steps.get(phase)+ if step is not None:+ # A phase restarted with a new total keeps its count and clock.+ step[1] = total+ return+ self._steps[phase] = [0, total, time.monotonic()]+ self._phase(phase, "start", None)++ def on_item_done(self, phase: str) -> None:+ step = self._steps.get(phase)+ if step is not None:+ step[0] = (step[0] or 0) + 1++ def on_item_label(self, phase: str, label: str) -> None:+ """Per-item labels are for a live display; a stream would drown in them."""++ def _finish(self, phase: str, state: str) -> None:+ step = self._steps.get(phase)+ if step is None or phase in self._done:+ return+ self._done.add(phase)+ if state == "done" and step[1] is not None:+ step[0] = step[1]+ self._phase(phase, state, time.monotonic() - (step[2] or 0.0))++ def on_phase_done(self, phase: str) -> None:+ self._finish(phase, "done")++ def on_phase_failed(self, phase: str) -> None:+ self._finish(phase, "failed")++ @contextlib.contextmanager+ def step(self, phase: str) -> Iterator[None]:+ self.on_phase_start(phase, None)+ try:+ yield+ except BaseException:+ self.on_phase_failed(phase)+ raise+ self.on_phase_done(phase)++ def on_message(self, level: str, text: str) -> None:+ if level not in _DEGRADING_LEVELS:+ return+ text = redact_secrets(text)+ self.warnings.append(text)+ self._events.emit("warning", level=level, text=text.strip())++ def set_cost(self, total_cost: float) -> None:+ """Spend is reported once, in the summary."""diff --git a/packages/cli/src/repowise/cli/ui/result_panels.py b/packages/cli/src/repowise/cli/ui/result_panels.pyindex 5985a2b32..f24420b0e 100644--- a/packages/cli/src/repowise/cli/ui/result_panels.py+++ b/packages/cli/src/repowise/cli/ui/result_panels.py@@ -67,6 +67,26 @@ def build_completion_panel()+def print_completion_panel(+ console: Console,+ title: str,+ metrics: list[tuple[str, str]],+ next_steps: list[tuple[str, str]] | None = None,+) -> None:+ """The completion panel on a terminal; off one, the same rows as plain lines.++ A border in a log or an agent's transcript is only padding to strip.+ """+ if console.is_terminal:+ console.print(build_completion_panel(title, metrics, next_steps=next_steps))+ return+ console.print(f"{mini(EYES_HAPPY)} {title}", highlight=False)+ console.print(key_value_table(metrics))+ if next_steps:+ console.print(" What's next:")+ console.print(key_value_table(list(next_steps), label_width=24))++def build_contextual_next_steps(*,index_only: bool,diff --git a/tests/unit/cli/test_embed_failure_reporting.py b/tests/unit/cli/test_embed_failure_reporting.pyindex 2204f07f1..9c0bf3de3 100644--- a/tests/unit/cli/test_embed_failure_reporting.py+++ b/tests/unit/cli/test_embed_failure_reporting.py@@ -158,8 +158,8 @@ def _closing_card(tmp_path: Path, monkeypatch, *, semantic: str, failed: int) ->Console(file=buf, width=200, force_terminal=False),)monkeypatch.setattr(- "repowise.cli.commands.init_cmd.reporting.build_completion_panel",- lambda title, metrics, next_steps=None: "PANEL",+ "repowise.cli.commands.init_cmd.reporting.print_completion_panel",+ lambda console, title, metrics, next_steps=None: console.print("PANEL"),)graph = MagicMock()graph.number_of_nodes.return_value = 1diff --git a/tests/unit/cli/test_init_agent_mode.py b/tests/unit/cli/test_init_agent_mode.pynew file mode 100644index 000000000..b5cd49d51--- /dev/null+++ b/tests/unit/cli/test_init_agent_mode.py@@ -0,0 +1,235 @@+"""`repowise init` for agents: short lines off a terminal, NDJSON under --progress json."""++from __future__ import annotations++import contextlib+import io+import json++import click+import pytest+from click.testing import CliRunner+from rich.console import Console++from repowise.cli import agent_events+from repowise.cli.commands.init_cmd import _ingest+from repowise.cli.commands.init_cmd._agent_summary import init_output+from repowise.cli.main import cli+from repowise.cli.output import LINE_OUTPUT_WIDTH, line_output_width+from repowise.cli.ui.brand import print_phase_header+from repowise.cli.ui.mode_names import TITLE_BUILT_FROM_CODE+from repowise.cli.ui.progress_json import JsonProgressCallback+from repowise.cli.ui.result_panels import print_completion_panel++_SUMMARY_KEYS = {+ "v",+ "event",+ "status",+ "mode",+ "restart_required",+ "spend",+ "warnings",+ "files_written",+ "next",+}++_KEYS = (+ "ANTHROPIC_API_KEY",+ "OPENAI_API_KEY",+ "OPENROUTER_API_KEY",+ "DEEPSEEK_API_KEY",+ "KIMI_API_KEY",+ "GOOGLE_API_KEY",+ "GEMINI_API_KEY",+ "OLLAMA_BASE_URL",+ "LITELLM_API_KEY",+ "REPOWISE_PROVIDER",+ "REPOWISE_EMBEDDER",+)+++def _lines(text: str) -> list[dict]:+ return [json.loads(line) for line in text.splitlines() if line.strip()]+++def repo(tmp_path, monkeypatch):+ for var in _KEYS:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.delenv("COLUMNS", raising=False)+ (tmp_path / "app.py").write_text("def main():\n return 1\n", encoding="utf-8")+ return tmp_path+++def _init(repo, *flags):+ return CliRunner(mix_stderr=False).invoke(+ cli, ["init", str(repo), "--no-workspace", "--yes", "--no-prose", *flags]+ )+++def test_every_event_is_one_versioned_json_line():+ buf = io.StringIO()+ events = agent_events.EventStream(buf)+ callback = JsonProgressCallback(events, stage="persistence")+ callback.on_phase_start("parse", 2)+ callback.on_item_done("parse")+ callback.on_item_label("parse", "app.py")+ callback.on_phase_done("parse")+ callback.on_phase_done("parse")+ with pytest.raises(RuntimeError), callback.step("state"):+ raise RuntimeError("disk full")+ callback.on_message("info", "Scanned 2 files")+ callback.on_message("warning", "Git history skipped")++ lines = _lines(buf.getvalue())+ assert all(line["v"] == agent_events.SCHEMA_VERSION for line in lines)+ assert [(line["event"], line.get("state")) for line in lines] == [+ ("stage", None),+ ("phase", "start"),+ ("phase", "done"),+ ("phase", "start"),+ ("phase", "failed"),+ ("warning", None),+ ]+ done = lines[2]+ assert done["phase"] == "parse"+ assert done["label"] == "Parsing files"+ assert (done["completed"], done["total"], done["unit"]) == (2, 2, "files")+ assert isinstance(done["elapsed_s"], float)+ assert lines[1]["elapsed_s"] is None+ assert lines[5] == {"v": 1, "event": "warning", "level": "warning", "text": "Git history skipped"}+ assert callback.warnings == ["Git history skipped"]+++ ("raised", "status", "next_commands"),+ [+ (None, "ready", []),+ (SystemExit(0), "ready", []),+ (SystemExit(2), "degraded", []),+ (SystemExit(130), "interrupted", ["repowise init --resume"]),+ (click.ClickException("Not a directory"), "failed", []),+ (SystemExit(1), "failed", []),+ ],+)+def test_every_exit_ends_with_a_summary(tmp_path, capsys, raised, status, next_commands):+ expect = pytest.raises(type(raised)) if raised else contextlib.nullcontext()+ with expect, init_output("json", tmp_path):+ if raised:+ raise raised++ lines = _lines(capsys.readouterr().out)+ assert len(lines) == 1+ summary = lines[0]+ assert summary["event"] == "summary"+ assert summary["status"] == status+ assert set(summary) >= _SUMMARY_KEYS+ assert summary["next"] == next_commands+ assert summary["spend"] == {"tokens": 0, "usd": 0.0}+ if status == "failed" and isinstance(raised, click.ClickException):+ assert summary["error"] == "Not a directory"+++def test_only_the_first_summary_is_written():+ buf = io.StringIO()+ events = agent_events.EventStream(buf)+ events.summary(agent_events.summary_fields("degraded", warnings=["x"]))+ events.summary(agent_events.summary_fields("ready"))+ assert [line["status"] for line in _lines(buf.getvalue())] == ["degraded"]+++def test_status_follows_the_exit_code():+ assert agent_events.status_for_exit(None) == "ready"+ assert agent_events.status_for_exit(0) == "ready"+ assert agent_events.status_for_exit(2) == "degraded"+ assert agent_events.status_for_exit(130) == "interrupted"+ assert agent_events.status_for_exit(1) == "failed"+++def test_off_a_terminal_lines_are_capped_and_panels_are_plain(monkeypatch):+ monkeypatch.delenv("COLUMNS", raising=False)+ buf = io.StringIO()+ console = Console(file=buf, width=400)+ with line_output_width(console, buf):+ assert console.width == LINE_OUTPUT_WIDTH+ print_phase_header(console, 1, 4, "Ingestion", "Walking the tree")+ print_completion_panel(+ console,+ "repowise index complete",+ [("Files indexed", "1")],+ [("repowise serve", "open the dashboard")],+ )+ assert console.width == 400+ out = buf.getvalue()+ assert max(len(line) for line in out.splitlines()) <= LINE_OUTPUT_WIDTH+ assert "╭" not in out and "│" not in out+ assert "repowise serve" in out+++def test_a_terminal_keeps_its_width(monkeypatch):+ monkeypatch.delenv("COLUMNS", raising=False)+ console = Console(file=io.StringIO(), width=180, force_terminal=True)+ stream = io.StringIO()+ stream.isatty = lambda: True # type: ignore[method-assign]+ with line_output_width(console, stream):+ assert console.width == 180+++def test_a_piped_init_stays_within_the_line_width(repo):+ result = _init(repo, "--no-editor-setup")++ assert result.exit_code == 0, result.output+ assert max(len(line) for line in result.stdout.splitlines()) <= LINE_OUTPUT_WIDTH+ assert "╭" not in result.stdout+++def test_json_init_writes_only_events_and_ends_with_a_ready_summary(repo):+ result = _init(repo, "--no-editor-setup", "--progress", "json")++ assert result.exit_code == 0, result.stderr+ lines = _lines(result.stdout)+ assert {line["event"] for line in lines} >= {"stage", "phase", "summary"}+ summary = lines[-1]+ assert summary["event"] == "summary"+ assert summary["status"] == "ready"+ assert summary["mode"] == {"key": "template", "label": "Built from code", "run_mode": "standard"}+ assert summary["restart_required"] is False+ assert summary["spend"] == {"tokens": 0, "usd": 0.0}+ assert summary["next"][0] == "repowise serve"+ # The human screen still happens, on stderr.+ assert TITLE_BUILT_FROM_CODE in result.stderr+++def test_json_init_degraded_summary_names_the_gap(repo, monkeypatch):+ from repowise.cli.commands.init_cmd import command++ real = _ingest.index_repository++ def _with_warning(run):+ real(run)+ run.run_warnings.append("Git history skipped: repository is shallow")++ monkeypatch.setattr(command, "index_repository", _with_warning)++ result = _init(repo, "--no-editor-setup", "--progress", "json")++ assert result.exit_code == 2, result.stderr+ summary = _lines(result.stdout)[-1]+ assert summary["status"] == "degraded"+ assert "Git history skipped: repository is shallow" in summary["warnings"]+ assert summary["mode"]["key"] == "template"+++def test_json_init_interrupted_summary(repo, monkeypatch):+ async def _stop(*_a, **_k):+ raise KeyboardInterrupt++ monkeypatch.setattr(_ingest, "_index_with_resume", _stop)++ result = _init(repo, "--progress", "json")++ assert result.exit_code == 130, result.stderr+ summary = _lines(result.stdout)[-1]+ assert summary["status"] == "interrupted"+ assert summary["next"] == ["repowise init --resume"]+ assert "Interrupted." in result.stderrdiff --git a/tests/unit/cli/test_init_failure_reporting.py b/tests/unit/cli/test_init_failure_reporting.pyindex b56434bd0..730e484bc 100644--- a/tests/unit/cli/test_init_failure_reporting.py+++ b/tests/unit/cli/test_init_failure_reporting.py@@ -243,12 +243,11 @@ def test_show_completion_panel_with_failures(monkeypatch):"""show_completion reflects failed count in metric line when failures exist."""printed_panels = []- def mock_completion_panel(title, metrics, next_steps=None):+ def mock_completion_panel(console, title, metrics, next_steps=None):printed_panels.append(metrics)- return "PANEL"monkeypatch.setattr(- "repowise.cli.commands.init_cmd.reporting.build_completion_panel", mock_completion_panel+ "repowise.cli.commands.init_cmd.reporting.print_completion_panel", mock_completion_panel)monkeypatch.setattr("repowise.cli.commands.init_cmd.reporting.console.print", lambda *a, **kw: None@@ -328,8 +327,8 @@ class TestInitRendersGenerationChecks:Console(file=buf, width=200, force_terminal=False),)monkeypatch.setattr(- "repowise.cli.commands.init_cmd.reporting.build_completion_panel",- lambda title, metrics, next_steps=None: "PANEL",+ "repowise.cli.commands.init_cmd.reporting.print_completion_panel",+ lambda console, title, metrics, next_steps=None: console.print("PANEL"),)show_completion(repo_path="/fake",@@ -468,8 +467,8 @@ def test_completion_panel_excludes_placeholders_from_the_page_count(monkeypatch)"""The panel derives the same split from the same helper, not its own count."""printed_panels = []monkeypatch.setattr(- "repowise.cli.commands.init_cmd.reporting.build_completion_panel",- lambda title, metrics, next_steps=None: printed_panels.append(metrics) or "PANEL",+ "repowise.cli.commands.init_cmd.reporting.print_completion_panel",+ lambda console, title, metrics, next_steps=None: printed_panels.append(metrics),)monkeypatch.setattr("repowise.cli.commands.init_cmd.reporting.console.print", lambda *a, **kw: None@@ -565,8 +564,8 @@ class TestInitClosingKeylessNote:Console(file=buf, width=200, force_terminal=False),)monkeypatch.setattr(- "repowise.cli.commands.init_cmd.reporting.build_completion_panel",- lambda title, metrics, next_steps=None: "PANEL",+ "repowise.cli.commands.init_cmd.reporting.print_completion_panel",+ lambda console, title, metrics, next_steps=None: console.print("PANEL"),)monkeypatch.setattr("repowise.cli.commands.init_cmd.reporting.load_state",