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(cli): give init failures a reason code (#2057)
Raghav Chamadiyac19ce35456ab
diff --git a/packages/cli/src/repowise/cli/_instrumented_group.py b/packages/cli/src/repowise/cli/_instrumented_group.pyindex 84275517f..1b40fb115 100644--- a/packages/cli/src/repowise/cli/_instrumented_group.py+++ b/packages/cli/src/repowise/cli/_instrumented_group.py@@ -179,6 +179,14 @@ class InstrumentedGroup(click.Group):except click.ClickException as exc:status = "error"error_type = type(exc).__name__ # class name only, never the message+ # Only the exception that actually ends the command reports its+ # reason. Recording at the raise site instead attributed a failure+ # to runs that caught it and went on to succeed.+ reason = getattr(exc, "reason", None)+ if isinstance(reason, str) and reason:+ from repowise.cli.platform import telemetry++ telemetry.add_command_outcome(failure_reason=reason)raiseexcept Exception as exc:status = "error"diff --git a/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py b/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.pyindex de7e45c3b..6fd01d5a5 100644--- a/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py+++ b/packages/cli/src/repowise/cli/agent_targets/formats/json_merge.py@@ -29,7 +29,7 @@ import statfrom pathlib import Pathfrom typing import Any-import click+from repowise.cli.errors import reasoned_errorfrom ..types import FileAction@@ -44,19 +44,22 @@ def load_json_object(config_path: Path) -> dict:try:existing = json.loads(config_path.read_text(encoding="utf-8"))except json.JSONDecodeError as exc:- raise click.ClickException(+ raise reasoned_error(f"Cannot update {config_path}: existing file is not valid JSON. "- "Fix or remove it and retry; no changes were written."+ "Fix or remove it and retry; no changes were written.",+ reason="editor_config_malformed",) from excexcept OSError as exc:- raise click.ClickException(+ raise reasoned_error(f"Cannot update {config_path}: existing file could not be read. "- "Fix the file permissions and retry; no changes were written."+ "Fix the file permissions and retry; no changes were written.",+ reason="editor_config_unreadable",) from excif not isinstance(existing, dict):- raise click.ClickException(+ raise reasoned_error(f"Cannot update {config_path}: existing file must contain a JSON object. "- "Fix or remove it and retry; no changes were written."+ "Fix or remove it and retry; no changes were written.",+ reason="editor_config_malformed",)return existingdiff --git a/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py b/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.pyindex 8b010ea0a..e0e6e9be9 100644--- a/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py+++ b/packages/cli/src/repowise/cli/agent_targets/formats/toml_merge.py@@ -28,7 +28,7 @@ import reimport tomllibfrom pathlib import Path-import click+from repowise.cli.errors import reasoned_errorfrom ..types import FileActionfrom .json_merge import json_deep_equal@@ -87,10 +87,11 @@ def ensure_valid_toml(merged_text: str, config_path: Path) -> dict:try:return tomllib.loads(merged_text)except tomllib.TOMLDecodeError as exc:- raise click.ClickException(+ raise reasoned_error(f"Cannot update {config_path}: merging the repowise entry would produce ""invalid TOML (an existing entry may use a different key spelling). "- "No changes were written."+ "No changes were written.",+ reason="editor_config_unmergeable",) from exc@@ -99,9 +100,10 @@ def load_toml_document(config_path: Path, existing_text: str) -> dict:try:return tomllib.loads(existing_text)except tomllib.TOMLDecodeError as exc:- raise click.ClickException(+ raise reasoned_error(f"Cannot update {config_path}: existing file is not valid TOML. "- "Fix or remove it and retry; no changes were written."+ "Fix or remove it and retry; no changes were written.",+ reason="editor_config_malformed",) from exc@@ -111,9 +113,10 @@ def require_table(doc: dict, key: str, config_path: Path, label: str) -> dict |if value is None:return Noneif not isinstance(value, dict):- raise click.ClickException(+ raise reasoned_error(f"Cannot update {config_path}: [{label}] must be a TOML table. "- "Fix or remove it and retry; no changes were written."+ "Fix or remove it and retry; no changes were written.",+ reason="editor_config_malformed",)return valuediff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.pyindex 62a3a571e..6f8e5a8ba 100644--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py@@ -36,6 +36,8 @@ import jsonimport tomllibfrom pathlib import Path+from repowise.cli.errors import reasoned_error+from ..types import (Capability,DoctorReport,@@ -261,7 +263,6 @@ def _migrate_hooks_config(hooks: dict) -> None:def write_server_config(repo_path: Path) -> FileWrite:"""Merge the repowise server table into project-local ``.codex/config.toml``."""- import clickfrom ..formats.toml_merge import (ensure_valid_toml,@@ -305,9 +306,10 @@ def write_server_config(repo_path: Path) -> FileWrite:try:block = table_block("mcp_servers.repowise", merged)except TypeError as exc:- raise click.ClickException(+ raise reasoned_error(f"Cannot update {config_path}: [mcp_servers.repowise] holds a value repowise "- f"cannot rewrite ({exc}). Remove that key and retry; no changes were written."+ f"cannot rewrite ({exc}). Remove that key and retry; no changes were written.",+ reason="editor_config_unmergeable",) from excmerged_text = replace_table(existing_text, "mcp_servers.repowise", block)merged_doc = ensure_valid_toml(merged_text, config_path)@@ -355,8 +357,6 @@ def write_hooks_config(repo_path: Path) -> tuple[FileWrite, FileWrite]:because they are genuinely two files and reporting only the first would hidea run whose sole effect was switching the feature back on."""- import click-from ..formats.json_merge import load_json_object, write_json_confighooks_path = project_hooks_path(repo_path)@@ -370,9 +370,10 @@ def write_hooks_config(repo_path: Path) -> tuple[FileWrite, FileWrite]:hooks = existing.setdefault("hooks", {})if not isinstance(hooks, dict):- raise click.ClickException(+ raise reasoned_error(f"Cannot update {hooks_path}: hooks must contain a JSON object. "- "Fix or remove it and retry; no changes were written."+ "Fix or remove it and retry; no changes were written.",+ reason="editor_config_malformed",)_migrate_hooks_config(hooks)@@ -380,9 +381,10 @@ def write_hooks_config(repo_path: Path) -> tuple[FileWrite, FileWrite]:for event, entries in new_config["hooks"].items():event_hooks = hooks.setdefault(event, [])if not isinstance(event_hooks, list):- raise click.ClickException(+ raise reasoned_error(f"Cannot update {hooks_path}: hooks.{event} must contain a JSON array. "- "Fix or remove it and retry; no changes were written."+ "Fix or remove it and retry; no changes were written.",+ reason="editor_config_malformed",)for entry in entries:if not _has_augment_hook_for_matcher(event_hooks, entry.get("matcher")):diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex 041d94f7b..55b853d81 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -30,6 +30,7 @@ from repowise.cli.editor_setup import (select_agents_interactively,write_editor_project_files,)+from repowise.cli.errors import reasoned_errorfrom repowise.cli.helpers import (config_fingerprint,console,@@ -47,7 +48,6 @@ from repowise.cli.helpers import (save_config_partial,save_state,)-from repowise.cli.platform import telemetryfrom repowise.cli.providers import resolve_embedderfrom repowise.cli.providers.embedders import embedder_was_requested as _embedder_was_requestedfrom repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json@@ -790,8 +790,7 @@ def init_command(repo_path = resolve_repo_path(path)if not repo_path.is_dir():- telemetry.add_command_outcome(failure_reason="invalid_path")- raise click.ClickException(f"Not a directory: {repo_path}")+ raise reasoned_error(f"Not a directory: {repo_path}", reason="invalid_path")# ---- Workspace detection ----# If the path contains multiple git repos (and is not itself a single repo),@@ -816,8 +815,10 @@ def init_command(if seed_from:seed_base = Path(seed_from).resolve()if seed_base == repo_path.resolve():- telemetry.add_command_outcome(failure_reason="seed_from_is_target")- raise click.ClickException("--seed-from cannot be the same as the target directory.")+ raise reasoned_error(+ "--seed-from cannot be the same as the target directory.",+ reason="seed_from_is_target",+ )elif not no_seed and not (repo_path / ".repowise" / "state.json").exists():detected = detect_worktree_base(repo_path)if detected is not None and base_is_seedable(detected):@@ -1148,10 +1149,10 @@ def init_command("written versions stay in page history.")if not sys.stdin.isatty():- telemetry.add_command_outcome(failure_reason="wiki_overwrite_unconfirmed")- raise click.ClickException(+ raise reasoned_error("Refusing to replace a model-written wiki with template pages. "- "Re-run with --yes to confirm, or drop --index-only."+ "Re-run with --yes to confirm, or drop --index-only.",+ reason="wiki_overwrite_unconfirmed",)if not click.confirm(" Replace the written wiki with template pages?", default=False):console.print("[dim]Nothing changed.[/dim]")@@ -1265,8 +1266,10 @@ def init_command())except ProviderError as exc:- telemetry.add_command_outcome(failure_reason="provider_validation_failed")- raise click.ClickException(f"Provider validation failed: {exc}") from exc+ raise reasoned_error(+ f"Provider validation failed: {exc}",+ reason="provider_validation_failed",+ ) from excconsole.print(f" [{OK}]✓[/] Provider connection verified")# ---- Phase 1 & 2: Ingestion + Analysis (always) ----diff --git a/packages/cli/src/repowise/cli/cost_gate.py b/packages/cli/src/repowise/cli/cost_gate.pyindex ae5f2b8b4..e733180b5 100644--- a/packages/cli/src/repowise/cli/cost_gate.py+++ b/packages/cli/src/repowise/cli/cost_gate.py@@ -14,6 +14,7 @@ from typing import Anyimport click+from repowise.cli.errors import reasoned_errorfrom repowise.cli.helpers import console# The LLM-cost confirmation threshold. A run whose estimate exceeds this asks@@ -120,10 +121,11 @@ def cost_gate_blocks(est: Any, *, yes: bool, message: str) -> bool:if est.estimated_cost_usd <= COST_GATE_USD or yes:return Falseif not sys.stdin.isatty():- raise click.ClickException(+ raise reasoned_error(f"This would spend about {format_cost(est)} and there is no terminal ""to confirm on. Re-run with --yes to accept the cost, or with "- "--no-prose to build the wiki from structure for free."+ "--no-prose to build the wiki from structure for free.",+ reason="cost_gate_no_tty",)return not confirm_cost_gate(message, estimated_usd=est.estimated_cost_usd)diff --git a/packages/cli/src/repowise/cli/errors.py b/packages/cli/src/repowise/cli/errors.pynew file mode 100644index 000000000..1c4bd41de--- /dev/null+++ b/packages/cli/src/repowise/cli/errors.py@@ -0,0 +1,39 @@+"""A CLI failure that says why, not just that.++``ClickException`` carries a message and nothing else, so the outcome recorded+for a failed command was the class name alone. 1,612 installs a month die on a+bare ``ClickException`` in ``init`` and the reason is not recoverable after the+fact: a bad path, a cost gate with no terminal to confirm on and a hand-edited+editor config that will not parse are indistinguishable.++Two decisions here, both about not disturbing what is already being measured.++The reason travels *on the exception* rather than being stashed beside it. A+raise site that records into the invocation's outcome and then raises reports a+failure the command may never have: ``init`` catches the no-provider exception+and renders a template wiki instead, so the run succeeds while the outcome still+claims it failed for want of a provider. Attaching it to the exception means only+the one that actually terminates the command is ever recorded, which is what the+root group does with it.++And it is an attribute on a plain ``ClickException``, not a subclass. The outcome+records ``type(exc).__name__``, so a subclass would silently split the very+histogram this exists to make readable - converted sites in one bucket,+unconverted ones in another, with the before-and-after no longer comparable.+"""++from __future__ import annotations++import click+++def reasoned_error(message: str, *, reason: str) -> click.ClickException:+ """A ``ClickException`` that also names a coarse, non-identifying reason.++ ``reason`` is a stable snake_case slug, never a message and never anything+ derived from user input: it lands in anonymous telemetry under the same+ privacy contract as every other outcome field.+ """+ exc = click.ClickException(message)+ exc.reason = reason+ return excdiff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex fa12e6704..29f26133f 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -14,6 +14,7 @@ from typing import Any, Literal, TypeVarimport clickfrom rich.console import Console+from repowise.cli.errors import reasoned_errorfrom repowise.cli.output import resolve_console_widthfrom repowise.core.reasoning import (ReasoningMode,@@ -628,7 +629,7 @@ def resolve_reasoning(try:return resolve_core_reasoning(reasoning, config)except ValueError as exc:- raise click.ClickException(str(exc)) from exc+ raise reasoned_error(str(exc), reason="invalid_reasoning") from excdef resolve_max_file_pages(@@ -957,14 +958,10 @@ def resolve_provider(# as a raw traceback that escaped every caller's handler —# OLLAMA_BASE_URL=http://localhost:abc makes httpx raise# InvalidURL, which killed `init` outright.- # Imported here, not at module scope: the telemetry spool imports- # this module back for the global config dir.- from repowise.cli.platform import telemetry-- telemetry.add_command_outcome(failure_reason="provider_setup_failed")- raise click.ClickException(+ raise reasoned_error(f"Could not set up the {name} provider: {exc}. Check its "- "settings in your environment and .repowise/config.yaml."+ "settings in your environment and .repowise/config.yaml.",+ reason="provider_setup_failed",) from excif provider_name is not None:@@ -986,10 +983,9 @@ def resolve_provider(if provider_credentials_present(candidate):return _build(candidate)- from repowise.cli.platform import telemetry-- telemetry.add_command_outcome(failure_reason="no_provider_configured")- raise click.ClickException(+ # Not fatal on every path: `init` catches this and renders a template wiki+ # instead, so the reason must not be recorded until it ends a command.+ raise reasoned_error("No provider configured. Use --provider, set REPOWISE_PROVIDER, ""or set ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / ""OLLAMA_BASE_URL / GEMINI_API_KEY / GOOGLE_API_KEY / DEEPSEEK_API_KEY / "@@ -997,7 +993,8 @@ def resolve_provider("REPOWISE_PROVIDER=claude_cli to use an ""authenticated Claude Code subscription, REPOWISE_PROVIDER=codex_cli to use ""an authenticated Codex CLI subscription, or REPOWISE_PROVIDER=opencode "- "to use opencode."+ "to use opencode.",+ reason="no_provider_configured",)diff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.pyindex 6cbc67229..d0bed1769 100644--- a/packages/cli/src/repowise/cli/ui/provider_selection.py+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py@@ -15,6 +15,7 @@ from rich.console import Consolefrom rich.prompt import Promptfrom rich.table import Table+from repowise.cli.errors import reasoned_errorfrom repowise.cli.ui.brand import BRAND, BRAND_STYLE, OK, VALUE, WARNfrom repowise.cli.ui.env_persistence import _save_key_to_dotenvfrom repowise.cli.ui.openai_compatible import (@@ -651,12 +652,13 @@ def _select_reasoning_mode(try:requested = normalize_reasoning(reasoning_flag)except ValueError as exc:- raise click.ClickException(str(exc)) from exc+ raise reasoned_error(str(exc), reason="invalid_reasoning") from excif requested not in choices:supported = ", ".join(choices)- raise click.ClickException(+ raise reasoned_error(f"reasoning={requested!r} is not supported by model "- f"{selected.model!r}. Supported reasoning modes: {supported}."+ f"{selected.model!r}. Supported reasoning modes: {supported}.",+ reason="unsupported_reasoning",)return requesteddiff --git a/tests/unit/cli/test_failure_reason_codes.py b/tests/unit/cli/test_failure_reason_codes.pynew file mode 100644index 000000000..028433abe--- /dev/null+++ b/tests/unit/cli/test_failure_reason_codes.py@@ -0,0 +1,228 @@+"""Every failure `init` can die on names a reason, not just a class.++`ClickException` carries a message and nothing else, so a failed `init` recorded+one indistinguishable outcome for a bad path, a cost gate with no terminal to+confirm on, and a hand-edited editor config that will not parse. These pin the+reason on each site.++The reason travels on the exception as an attribute, deliberately not as a+subclass, so `error_type` keeps reporting `ClickException` and the histogram this+feeds stays comparable across the change. The root group is what records it, and+only when the exception actually ends the command - see `test_telemetry.py` for+that half.+"""++from __future__ import annotations++import ast+import json+from pathlib import Path+from types import SimpleNamespace++import click+import pytest+++def _reason(fn, *args, **kwargs) -> str:+ with pytest.raises(click.ClickException) as excinfo:+ fn(*args, **kwargs)+ # Not a subclass: the class name is what telemetry reports, and it must not+ # move just because a site gained a reason.+ assert type(excinfo.value) is click.ClickException+ return excinfo.value.reason+++def test_a_cost_gate_with_no_terminal_says_so(monkeypatch: pytest.MonkeyPatch) -> None:+ """The scripted-agent case: no tty to confirm on and no --yes.++ A coding agent running plain `repowise init` on a repo over the gate hits+ this, and it is indistinguishable from every other init failure today.+ """+ from repowise.cli import cost_gate++ monkeypatch.setattr(cost_gate.sys.stdin, "isatty", lambda: False, raising=False)+ est = SimpleNamespace(estimated_cost_usd=99.0, cost_range=None)++ assert _reason(cost_gate.cost_gate_blocks, est, yes=False, message="?") == "cost_gate_no_tty"+++def test_the_cost_gate_still_lets_a_cheap_or_approved_run_through(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The control: instrumenting the refusal must not create one."""+ from repowise.cli import cost_gate++ monkeypatch.setattr(cost_gate.sys.stdin, "isatty", lambda: False, raising=False)+ cheap = SimpleNamespace(estimated_cost_usd=0.01, cost_range=None)+ dear = SimpleNamespace(estimated_cost_usd=99.0, cost_range=None)++ assert cost_gate.cost_gate_blocks(cheap, yes=False, message="?") is False+ assert cost_gate.cost_gate_blocks(dear, yes=True, message="?") is False+++def test_an_unknown_reasoning_mode_says_so() -> None:+ from repowise.cli.helpers import resolve_reasoning++ assert _reason(resolve_reasoning, "not-a-mode") == "invalid_reasoning"+++def test_a_model_that_does_not_offer_the_mode_says_so_differently() -> None:+ """Distinct from an unparseable mode: this one parsed, the model lacks it.++ Worth its own code because the fix differs - drop the flag, versus pick a+ different model.+ """+ from repowise.cli.ui.provider_selection import _select_reasoning_mode++ selected = SimpleNamespace(model="tiny", reasoning_modes=("auto",))++ assert _reason(_select_reasoning_mode, None, selected, "high") == "unsupported_reasoning"+++def test_an_unparseable_mode_says_so_from_the_selection_path_too() -> None:+ """The same failure as `resolve_reasoning`, so it carries the same code."""+ from repowise.cli.ui.provider_selection import _select_reasoning_mode++ selected = SimpleNamespace(model="tiny", reasoning_modes=("auto", "high"))++ assert _reason(_select_reasoning_mode, None, selected, "not-a-mode") == "invalid_reasoning"+++def test_an_unparseable_editor_config_says_so(tmp_path: Path) -> None:+ """A hand-edited `.mcp.json` that will not parse is a real init failure."""+ from repowise.cli.agent_targets.formats.json_merge import load_json_object++ config = tmp_path / ".mcp.json"+ config.write_text("{not json", encoding="utf-8")++ assert _reason(load_json_object, config) == "editor_config_malformed"+++def test_an_editor_config_of_the_wrong_shape_says_so(tmp_path: Path) -> None:+ from repowise.cli.agent_targets.formats.json_merge import load_json_object++ config = tmp_path / ".mcp.json"+ config.write_text(json.dumps([1, 2, 3]), encoding="utf-8")++ assert _reason(load_json_object, config) == "editor_config_malformed"+++def test_an_unreadable_editor_config_says_so_differently(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Permissions, not content. The user's fix differs, so the code does too."""+ from repowise.cli.agent_targets.formats.json_merge import load_json_object++ config = tmp_path / ".mcp.json"+ config.write_text("{}", encoding="utf-8")++ def denied(*_args, **_kwargs):+ raise PermissionError(13, "Permission denied")++ monkeypatch.setattr(Path, "read_text", denied)++ assert _reason(load_json_object, config) == "editor_config_unreadable"+++def test_an_unparseable_toml_config_says_so(tmp_path: Path) -> None:+ from repowise.cli.agent_targets.formats.toml_merge import load_toml_document++ assert _reason(load_toml_document, tmp_path / "config.toml", "= broken") == (+ "editor_config_malformed"+ )+++def test_a_merge_that_would_corrupt_toml_says_so(tmp_path: Path) -> None:+ """Distinct from a malformed file: theirs parses, ours would not.++ Worth its own code because the fix is different - the user's file is fine+ and repowise is the one that cannot write it.+ """+ from repowise.cli.agent_targets.formats.toml_merge import ensure_valid_toml++ assert _reason(ensure_valid_toml, "= broken", tmp_path / "config.toml") == (+ "editor_config_unmergeable"+ )+++def test_a_config_table_of_the_wrong_type_says_so(tmp_path: Path) -> None:+ from repowise.cli.agent_targets.formats.toml_merge import require_table++ assert (+ _reason(require_table, {"mcp_servers": "not a table"}, "mcp_servers", tmp_path, "mcp")+ == "editor_config_malformed"+ )+++def test_a_hooks_file_of_the_wrong_shape_says_so(tmp_path: Path) -> None:+ """Reached from `init` when the editor is codex and hooks.json is hand-edited."""+ from repowise.cli.agent_targets.targets.codex import project_hooks_path, write_hooks_config++ hooks = project_hooks_path(tmp_path)+ hooks.parent.mkdir(parents=True)+ hooks.write_text(json.dumps({"hooks": "not an object"}), encoding="utf-8")++ assert _reason(write_hooks_config, tmp_path) == "editor_config_malformed"+++def test_a_hooks_event_of_the_wrong_shape_says_so(tmp_path: Path) -> None:+ from repowise.cli.agent_targets.targets.codex import (+ hooks_config,+ project_hooks_path,+ write_hooks_config,+ )++ event = next(iter(hooks_config()["hooks"]))+ hooks = project_hooks_path(tmp_path)+ hooks.parent.mkdir(parents=True)+ hooks.write_text(json.dumps({"hooks": {event: "not a list"}}), encoding="utf-8")++ assert _reason(write_hooks_config, tmp_path) == "editor_config_malformed"+++# --- coverage of the sweep itself -------------------------------------------+++#: Paths the sweep covered end to end. Every `init`-reachable raise in these now+#: names a reason, so a new bare one is a regression rather than an omission.+_SWEPT = (+ "packages/cli/src/repowise/cli/agent_targets",+ "packages/cli/src/repowise/cli/cost_gate.py",+ "packages/cli/src/repowise/cli/ui/provider_selection.py",+)+++def _repo_root() -> Path:+ here = Path(__file__).resolve()+ return next(p for p in here.parents if (p / "packages").is_dir())+++def _bare_click_exception_raises(path: Path) -> list[str]:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ found = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Raise) or not isinstance(node.exc, ast.Call):+ continue+ func = node.exc.func+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None)+ if name == "ClickException":+ found.append(f"{path.name}:{node.lineno}")+ return found+++def test_no_bare_click_exception_is_left_on_the_swept_paths() -> None:+ """The sweep as a property, rather than a list I remembered to update.++ Pinning each site by hand cannot say a NEW raise was added without a reason,+ which is exactly how two sites in `codex.py` went missing the first time+ through. This fails on the next one.+ """+ root = _repo_root()+ offenders: list[str] = []+ for entry in _SWEPT:+ target = root / entry+ files = sorted(target.rglob("*.py")) if target.is_dir() else [target]+ for path in files:+ offenders.extend(_bare_click_exception_raises(path))++ assert offenders == []diff --git a/tests/unit/cli/test_telemetry.py b/tests/unit/cli/test_telemetry.pyindex 1720f0d9e..07f6cd68f 100644--- a/tests/unit/cli/test_telemetry.py+++ b/tests/unit/cli/test_telemetry.py@@ -352,6 +352,62 @@ class TestOutcomeClassification:rec = self._run(monkeypatch, body)assert rec and rec[0]["properties"]["status"] == "error"+ def test_a_reasoned_failure_reports_why(self, monkeypatch: pytest.MonkeyPatch):+ """The gap this exists to close: a bare class name says nothing.++ 1,612 installs a month died on a `ClickException` in `init` and the+ reason was not recoverable after the fact - a bad path, a cost gate with+ no terminal, and an editor config that will not parse all reported the+ same thing.+ """+ from repowise.cli.errors import reasoned_error++ def body() -> None:+ raise reasoned_error("nope", reason="invalid_path")++ rec = self._run(monkeypatch, body)+ assert rec+ props = rec[0]["properties"]+ assert props["status"] == "error"+ assert props["failure_reason"] == "invalid_path"+ # The class is unchanged on purpose. A subclass here would split the+ # error_type histogram this reason code exists to make readable, with+ # converted and unconverted sites landing in different buckets.+ assert props["error_type"] == "ClickException"++ def test_a_plain_failure_reports_no_reason(self, monkeypatch: pytest.MonkeyPatch):+ """Absence stays honest: an uninstrumented raise must not invent a code."""+ import click++ def body() -> None:+ raise click.ClickException("no index found")++ rec = self._run(monkeypatch, body)+ assert rec and "failure_reason" not in rec[0]["properties"]++ def test_a_recovered_failure_reports_nothing(self, monkeypatch: pytest.MonkeyPatch):+ """A caught exception did not fail the command, so it must not say it did.++ `init` catches the no-provider error and renders a template wiki instead.+ Recording at the raise site attributed a failure to a run that went on to+ succeed, which is exactly the histogram this reason code feeds.+ """+ import click++ from repowise.cli.errors import reasoned_error++ def body() -> None:+ try:+ raise reasoned_error("nope", reason="no_provider_configured")+ except click.ClickException:+ pass++ rec = self._run(monkeypatch, body)+ assert rec+ props = rec[0]["properties"]+ assert props["status"] == "ok"+ assert "failure_reason" not in props+def test_command_outcome_rides_the_event(self, monkeypatch: pytest.MonkeyPatch):from repowise.cli.platform import telemetry