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.

fix(cli): name the real error when a command fails, and flag pytest runs (#1447)

Raghav Chamadiyaf6b74539cb54
diff --git a/packages/cli/src/repowise/cli/_instrumented_group.py b/packages/cli/src/repowise/cli/_instrumented_group.py
index 775c34e51..cc956c845 100644
--- a/packages/cli/src/repowise/cli/_instrumented_group.py
+++ b/packages/cli/src/repowise/cli/_instrumented_group.py
@@ -132,6 +132,19 @@ class InstrumentedGroup(click.Group):
status = "interrupted"
else:
status = "error"
+ # Mirror the ``Exit`` branch above and name the class, or this
+ # bucket records a failure with no error type at all. Commands
+ # that raise ``SystemExit`` directly rather than via
+ # ``ctx.exit()`` all land here, so leaving it unset loses the
+ # only diagnostic the event carries. Prefer the chained cause
+ # when there is one: a bare ``SystemExit(1)`` says nothing on
+ # its own, whereas the exception that forced the exit does.
+ # ``from None`` is honoured — a suppressed context is the
+ # author saying it is not the explanation.
+ cause = exc.__cause__
+ if cause is None and not exc.__suppress_context__:
+ cause = exc.__context__
+ error_type = type(cause).__name__ if cause else "SystemExit"
raise
except (KeyboardInterrupt, click.exceptions.Abort):
# User cancelled (Ctrl-C / declined a prompt). Not a failure — long-
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index c393d14b1..ecf5902a4 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -46,6 +46,7 @@ from repowise.cli.helpers import (
save_config_partial,
save_state,
)
+from repowise.cli.platform import telemetry
from repowise.cli.providers import resolve_embedder
from repowise.cli.providers.embedders import embedder_was_requested as _embedder_was_requested
from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json
@@ -770,6 +771,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}")
# ---- Workspace detection ----
@@ -795,6 +797,7 @@ 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.")
elif not no_seed and not (repo_path / ".repowise" / "state.json").exists():
detected = detect_worktree_base(repo_path)
@@ -1107,6 +1110,7 @@ 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(
"Refusing to replace a model-written wiki with template pages. "
"Re-run with --yes to confirm, or drop --index-only."
@@ -1220,6 +1224,7 @@ 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
console.print(" [green]✓[/green] Provider connection verified")
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 9a207c048..cf004f264 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -798,6 +798,11 @@ 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(
f"Could not set up the {name} provider: {exc}. Check its "
"settings in your environment and .repowise/config.yaml."
@@ -822,6 +827,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(
"No provider configured. Use --provider, set REPOWISE_PROVIDER, "
"or set ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / "
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/emitter.py b/packages/cli/src/repowise/cli/platform/telemetry/emitter.py
index c6dcdddd2..601b5d8f1 100644
--- a/packages/cli/src/repowise/cli/platform/telemetry/emitter.py
+++ b/packages/cli/src/repowise/cli/platform/telemetry/emitter.py
@@ -55,8 +55,12 @@ def _under_test() -> bool:
events under a freshly minted install. Only delivery is suppressed:
consent resolution stays real, so its own tests still exercise the actual
precedence rules.
+
+ Shares the env-var check with :func:`environment.under_pytest` so the two
+ cannot drift. The ``sys.modules`` fallback is kept because this guard is
+ only consulted in-process, where an import is evidence enough.
"""
- return "PYTEST_CURRENT_TEST" in os.environ or "pytest" in sys.modules
+ return environment.under_pytest() or "pytest" in sys.modules
def build_envelope(event: TelemetryEvent) -> dict[str, object]:
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/environment.py b/packages/cli/src/repowise/cli/platform/telemetry/environment.py
index 18f89725f..05f6cd508 100644
--- a/packages/cli/src/repowise/cli/platform/telemetry/environment.py
+++ b/packages/cli/src/repowise/cli/platform/telemetry/environment.py
@@ -1,9 +1,9 @@
"""Coarse, non-identifying environment facts attached to every event.
Deliberately low-resolution: OS family, CPU architecture, a major.minor Python
-version, and a CI boolean. Nothing here can identify a machine or a person — no
-hostname, no username, no full version string, no IP (the server never records
-the source address).
+version, and an automated-run boolean. Nothing here can identify a machine or a
+person — no hostname, no username, no full version string, no IP (the server
+never records the source address).
"""
from __future__ import annotations
@@ -40,9 +40,28 @@ def python_version() -> str:
return f"{info[0]}.{info[1]}"
+def under_pytest() -> bool:
+ """Return whether a pytest session is in progress, judged from the env.
+
+ Read from the environment rather than ``sys.modules`` so the answer survives
+ a subprocess boundary: the suite drives real ``repowise`` commands, and a
+ child interpreter sees the inherited env vars but has its own module table.
+ ``PYTEST_CURRENT_TEST`` covers the window while a test runs;
+ ``PYTEST_VERSION`` (pytest 8.1+) also covers collection and teardown, when
+ no test is current but an atexit flush can still fire.
+ """
+ return bool(os.environ.get("PYTEST_CURRENT_TEST") or os.environ.get("PYTEST_VERSION"))
+
+
def is_ci() -> bool:
- """Return whether we appear to be running in a CI environment."""
- return any(os.environ.get(var) for var in _CI_ENV_VARS)
+ """Return whether this looks like an automated rather than a human run.
+
+ Counts a pytest session as automated. Test fixtures relocate the home
+ directory that holds ``anon_id``, so every run would otherwise register as
+ a brand new install whose usage is not a user's, which is the same reason
+ CI is flagged.
+ """
+ return under_pytest() or any(os.environ.get(var) for var in _CI_ENV_VARS)
def base_facts() -> dict[str, object]:
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index c22553996..923b19c52 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -558,6 +558,37 @@ def create_mcp_server(
return mcp
+#: Depth bound when unwrapping nested task-group failures. Groups nest one or
+#: two deep in practice; the cap only stops a pathological cycle from hanging.
+_MAX_GROUP_DEPTH = 10
+
+
+def _run_transport(transport: str) -> None:
+ """Run the server, raising the cause of a task-group failure rather than the group.
+
+ ``mcp.run`` drives an anyio event loop, and anyio reports a child task's
+ failure as an ``ExceptionGroup`` wrapping the real exception. Anything that
+ reads the outermost class then learns only that *a* task failed: the CLI
+ records the wrapper's name as the error type, so a missing dependency, a
+ permission problem and a closed pipe are indistinguishable after the fact.
+ Unwrap to the first leaf and raise that, so the layers above name the real
+ error. A group holding several distinct failures loses the siblings, which
+ is worth it to stop losing the cause entirely.
+ """
+ try:
+ mcp.run(transport=transport)
+ except BaseExceptionGroup as group:
+ leaf: BaseException = group
+ for _ in range(_MAX_GROUP_DEPTH):
+ if not isinstance(leaf, BaseExceptionGroup) or not leaf.exceptions:
+ break
+ leaf = leaf.exceptions[0]
+ # A cancelled run is how a client-initiated shutdown looks, not a fault.
+ if isinstance(leaf, Exception):
+ _log.error("MCP server (%s) stopped: %r", transport, leaf, exc_info=leaf)
+ raise leaf from group
+
+
def run_mcp(
transport: str = "stdio",
repo_path: str | None = None,
@@ -588,7 +619,7 @@ def run_mcp(
"network-accessible. Set REPOWISE_API_KEY or bind to 127.0.0.1.",
host,
)
- mcp.run(transport="sse")
+ _run_transport("sse")
elif transport == "streamable-http":
mcp.settings.host = host
mcp.settings.port = port
@@ -599,7 +630,7 @@ def run_mcp(
"network-accessible. Set REPOWISE_API_KEY or bind to 127.0.0.1.",
host,
)
- mcp.run(transport="streamable-http")
+ _run_transport("streamable-http")
else:
# stdout is the JSON-RPC channel on stdio, so every log line written
# there arrives at the client as a malformed protocol frame. Move the
@@ -614,4 +645,4 @@ def run_mcp(
from repowise.server.mcp_server._watchdog import start_parent_watchdog
start_parent_watchdog()
- mcp.run(transport="stdio")
+ _run_transport("stdio")
diff --git a/tests/unit/cli/test_mcp_transport.py b/tests/unit/cli/test_mcp_transport.py
index 1ce7e01f5..71664d141 100644
--- a/tests/unit/cli/test_mcp_transport.py
+++ b/tests/unit/cli/test_mcp_transport.py
@@ -287,3 +287,53 @@ def test_run_mcp_sets_host_on_settings(monkeypatch) -> None:
assert _server.mcp.settings.host == "0.0.0.0"
assert _server.mcp.settings.port == 7343
assert calls == [{"transport": "streamable-http"}]
+
+
+def test_task_group_failure_surfaces_the_real_error(monkeypatch) -> None:
+ """anyio wraps a child task's error; the wrapper must not be what escapes.
+
+ The event loop reports a failed task as an ExceptionGroup, so callers that
+ read the outermost class learn only that something failed. Every start-up
+ failure then looks identical from the outside.
+ """
+ import pytest
+
+ from repowise.server.mcp_server import _server
+
+ def boom(**_kw):
+ raise ExceptionGroup("task failed", [PermissionError("wiki.db is locked")])
+
+ monkeypatch.setattr(_server.mcp, "run", boom)
+
+ with pytest.raises(PermissionError):
+ _server.run_mcp(transport="stdio")
+
+
+def test_nested_task_groups_unwrap_to_the_leaf(monkeypatch) -> None:
+ import pytest
+
+ from repowise.server.mcp_server import _server
+
+ def boom(**_kw):
+ inner = ExceptionGroup("inner", [ModuleNotFoundError("no mcp")])
+ raise ExceptionGroup("outer", [inner])
+
+ monkeypatch.setattr(_server.mcp, "run", boom)
+
+ with pytest.raises(ModuleNotFoundError):
+ _server.run_mcp(transport="stdio")
+
+
+def test_a_plain_error_is_left_alone(monkeypatch) -> None:
+ """Only grouped failures are unwrapped; an ungrouped one already names itself."""
+ import pytest
+
+ from repowise.server.mcp_server import _server
+
+ def boom(**_kw):
+ raise OSError("address in use")
+
+ monkeypatch.setattr(_server.mcp, "run", boom)
+
+ with pytest.raises(OSError):
+ _server.run_mcp(transport="stdio")
diff --git a/tests/unit/cli/test_telemetry.py b/tests/unit/cli/test_telemetry.py
index 3912bd565..1720f0d9e 100644
--- a/tests/unit/cli/test_telemetry.py
+++ b/tests/unit/cli/test_telemetry.py
@@ -102,6 +102,31 @@ class TestEnvelopePrivacy:
env = emitter.build_envelope(CommandRunEvent(command="status"))
assert env["python_version"].count(".") == 1 # major.minor only
+ def test_a_pytest_run_is_flagged_automated(self):
+ # This assertion runs under pytest, so it is its own fixture: the
+ # suite's fixtures relocate the home holding anon_id, and every run
+ # would otherwise arrive as a brand new install.
+ env = emitter.build_envelope(CommandRunEvent(command="status"))
+ assert env["is_ci"] is True
+
+ def test_automated_detection_reads_the_env_not_sys_modules(
+ self, monkeypatch: pytest.MonkeyPatch
+ ):
+ # A test may shell out to a real repowise process: the child inherits
+ # the env but builds its own module table, so the env is what travels.
+ from repowise.cli.platform.telemetry import environment
+
+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
+ monkeypatch.delenv("PYTEST_VERSION", raising=False)
+ for var in environment._CI_ENV_VARS:
+ monkeypatch.delenv(var, raising=False)
+ assert environment.under_pytest() is False
+ assert environment.is_ci() is False
+
+ monkeypatch.setenv("PYTEST_VERSION", "8.4.1")
+ assert environment.under_pytest() is True
+ assert environment.is_ci() is True
+
def test_flags_carry_no_values(self):
env = emitter.build_envelope(
CommandRunEvent(command="update", flags=["--provider", "--exclude"])
@@ -339,6 +364,52 @@ class TestOutcomeClassification:
assert props["file_count_bucket"] == "500-999"
assert props["docs_mode"] is False
+ def test_bare_system_exit_still_names_a_class(self, monkeypatch: pytest.MonkeyPatch):
+ # Commands that exit via ``SystemExit`` rather than ``ctx.exit()`` used
+ # to record an error with no class at all, which left the whole bucket
+ # undiagnosable.
+ def body() -> None:
+ raise SystemExit(1)
+
+ rec = self._run(monkeypatch, body)
+ assert rec and rec[0]["properties"]["status"] == "error"
+ assert rec[0]["properties"]["error_type"] == "SystemExit"
+
+ def test_system_exit_reports_the_cause_it_was_raised_from(
+ self, monkeypatch: pytest.MonkeyPatch
+ ):
+ # ``raise SystemExit(1) from exc`` carries the real reason; report that
+ # rather than the exit wrapper.
+ def body() -> None:
+ try:
+ raise ModuleNotFoundError("no uvicorn")
+ except ModuleNotFoundError as exc:
+ raise SystemExit(1) from exc
+
+ rec = self._run(monkeypatch, body)
+ assert rec and rec[0]["properties"]["error_type"] == "ModuleNotFoundError"
+
+ def test_suppressed_context_is_not_reported(self, monkeypatch: pytest.MonkeyPatch):
+ # ``from None`` is the author saying the in-flight exception is not the
+ # explanation, so it must not be mined for an error class.
+ def body() -> None:
+ try:
+ raise ModuleNotFoundError("no uvicorn")
+ except ModuleNotFoundError:
+ raise SystemExit(1) from None
+
+ rec = self._run(monkeypatch, body)
+ assert rec and rec[0]["properties"]["error_type"] == "SystemExit"
+
+ def test_clean_system_exit_records_no_error_class(self, monkeypatch: pytest.MonkeyPatch):
+ # Exit code 0 is a success: naming a class here would invent a failure.
+ def body() -> None:
+ raise SystemExit(0)
+
+ rec = self._run(monkeypatch, body)
+ assert rec and rec[0]["properties"]["status"] == "ok"
+ assert rec[0]["properties"].get("error_type") is None
+
class TestBucketCount:
def test_buckets_are_coarse_ranges(self):