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(telemetry): reason codes on failures, a host label, no sending under test (#4687)

Raghav Chamadiya9c7032d4bef0
diff --git a/docs/architecture/savings-accounting.md b/docs/architecture/savings-accounting.md
index 091c6b502..7c4e545e4 100644
--- a/docs/architecture/savings-accounting.md
+++ b/docs/architecture/savings-accounting.md
@@ -96,7 +96,7 @@ counterfactual estimation, dead-end handling, and the final writer.
FastMCP exposes a request ID across stdio, SSE, and streamable HTTP. On normal
stateful sessions it also exposes initialize-time `clientInfo`, which is
-client-declared rather than authenticated. Mapping version `mcp_client_info_v1`
+client-declared rather than authenticated. Mapping version `mcp_client_info_v2`
lowercases the name and removes non-alphanumerics, then looks the result up in
the agent registry (`repowise.core.agents.identity`), where every agent answers
to its own slug and its own display name, plus any extra name its host is known
diff --git a/docs/reference/TELEMETRY.md b/docs/reference/TELEMETRY.md
index f7a0bd011..26ced12c1 100644
--- a/docs/reference/TELEMETRY.md
+++ b/docs/reference/TELEMETRY.md
@@ -37,6 +37,13 @@ Every event, whatever its type, carries the same anonymous envelope:
| `python_version` | `3.12` | **major.minor only** |
| `is_ci` | `true` / `false` | Separate automation from humans |
+Every event's `properties.client` names the host that ran repowise, as one
+fixed label: `claude_code`, `codex`, `cursor`, `vscode`, `ci` or `terminal`.
+It comes from which host-specific environment variables are set (never their
+values), from a hook's `--client` flag, or for an MCP tool call from the name
+the client announces when it connects, which can also name another supported
+agent such as `opencode` (`unknown` when nothing matches).
+
### `command_run` — once per CLI invocation
| Field | Example | Purpose |
@@ -47,6 +54,13 @@ Every event, whatever its type, carries the same anonymous envelope:
| `properties.status` | `ok` / `error` / `usage_error` / `interrupted` | Success, failure, a mis-invocation (bad/unknown flag), or user-cancelled (Ctrl-C) |
| `properties.error_type` | `LLMProviderError` | Exception **class name only** |
| `properties.duration_ms` | `71840` | Performance in the wild |
+| `properties.failure_reason` | `no_sync_base` | A fixed reason code for a known failure, never the message |
+
+`failure_reason` codes include `store_open_failed`, `db_url_unreachable` and
+`workspace_default_failed` for `mcp`, and `no_index`, `no_sync_base`,
+`no_provider_configured` and `embed_failed` for `update`. An `mcp` run also
+reports `served_no_index` (`true` when it serves a directory with no index),
+and an `update` that defers to one already running reports `outcome: deferred`.
For `init` and `update`, a few coarse **buckets and enums** describe the shape
of the run so we can see the size of repos people index and whether docs
@@ -72,6 +86,7 @@ response, **never the question, query, results, paths, or repo/symbol names**:
|---|---|---|
| `properties.tool` | `get_answer`, `search_codebase` | Which tool was called |
| `properties.status` | `ok` / `error` | Tool error rate |
+| `properties.error_reason` | `not_found` / `invalid_args` / `no_index` / `index_behind` / `server_stale` / `internal` / `other` | Why an `error` call failed, a fixed code |
| `properties.duration_ms` | `820` | Tool latency in the wild |
| `properties.confidence` | `high` / `medium` / `low` | Answer confidence distribution |
| `properties.retrieval_quality` | `high` / `partial` / `weak` | Retrieval quality distribution; sent only when the call asked for `include=["diagnostics"]` |
@@ -136,6 +151,9 @@ detached process that sends what is queued and removes the file. So the send
costs you nothing in command time, and you can read the queued file to see
exactly what is about to leave your machine.
+Nothing is queued or sent while a test runner is driving repowise
+(`PYTEST_CURRENT_TEST` or `PYTEST_VERSION` is set, or pytest is loaded).
+
If the send fails the queued events are discarded, not retried. Disabling
telemetry also discards anything still queued, so a disable is never followed
by one last batch.
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
index 6cb64f9b1..411e20ed9 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
@@ -177,6 +177,11 @@ def augment_command(
) -> None:
"""Enrich AI agent tool calls with codebase graph context (hook mode)."""
configure_cli_logging(verbose=verbose)
+ if client:
+ from repowise.cli.platform import telemetry
+
+ # The hook names its host; that beats reading the environment.
+ telemetry.add_command_outcome(client=client)
# stdout carries the hook response; logs go to stderr.
with contextlib.suppress(ImportError):
import structlog
diff --git a/packages/cli/src/repowise/cli/commands/mcp_cmd.py b/packages/cli/src/repowise/cli/commands/mcp_cmd.py
index 5972c7286..1fcacb6d5 100644
--- a/packages/cli/src/repowise/cli/commands/mcp_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/mcp_cmd.py
@@ -7,6 +7,7 @@ from pathlib import Path
import click
+from repowise.cli.errors import reasoned_error
from repowise.cli.helpers import console, find_repowise_repo_root, resolve_repo_path, warn
from repowise.cli.ui import load_dotenv
@@ -209,8 +210,14 @@ def mcp_command(
)
except StoreUnavailableError as exc:
# One line on stderr and exit 1, not a traceback the host respawns on.
- raise click.ClickException(str(exc)) from exc
+ # The reason slug becomes the event's failure_reason.
+ raise reasoned_error(str(exc), reason=exc.reason) from exc
finally:
from repowise.cli.platform import telemetry
+ from repowise.server.mcp_server import _state
- telemetry.add_command_outcome(transport=transport, transport_outcome=outcome)
+ telemetry.add_command_outcome(
+ transport=transport,
+ transport_outcome=outcome,
+ served_no_index=bool(_state._serving_no_index),
+ )
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 58a47ddaa..0e077dbf5 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -22,6 +22,7 @@ import structlog
from repowise.cli._setup import configure_cli_logging
from repowise.cli.commands._index_outcome import record_index_outcome, refresh_read_snapshots
+from repowise.cli.errors import reasoned_error
from repowise.cli.helpers import (
clear_update_queued,
console,
@@ -121,7 +122,7 @@ def _fail_on_embed_failure(
save_state(repo_path, state)
if emitter is not None:
emitter.error(message)
- raise click.ClickException(message)
+ raise reasoned_error(message, reason="embed_failed")
def _docs_provider_prompt_allowed(emitter: Any) -> bool:
@@ -697,9 +698,10 @@ def _update_workspace_target(opts: UpdateOptions, run: UpdateRun, target) -> Upd
run.repo_path = (target.ws_root / entry.path).resolve()
return _full_upgrade(opts, run)
if opts.full:
- raise click.ClickException(
+ raise reasoned_error(
"--full upgrades one repo at a time. Run it inside that repo, or pass "
- "--repo <alias>."
+ "--repo <alias>.",
+ reason="full_needs_one_repo",
)
with _errors_reported(run):
_workspace_update(
@@ -820,7 +822,9 @@ def _raise_no_sync_base(run: UpdateRun) -> None:
)
if run.emitter is not None:
run.emitter.error(message)
- raise click.ClickException(message)
+ # An empty state means the repo was never indexed; a state without a sync
+ # commit means it was, but no sync completed.
+ raise reasoned_error(message, reason="no_sync_base" if run.state else "no_index")
def _widen_to_pending_repair(run: UpdateRun) -> None:
@@ -1079,6 +1083,10 @@ def _acquire_update_lock(run: UpdateRun) -> UpdateOutcome | None:
existing_lock = try_acquire_update_lock(repo_path, head)
if existing_lock is not None:
_report_lock_held(run, existing_lock)
+ from repowise.cli.platform import telemetry
+
+ # Not a failure: another update holds the lock and this run defers to it.
+ telemetry.add_command_outcome(outcome="deferred")
return _emit_done(run, UpdateOutcome.DEFERRED)
import atexit
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/emitter.py b/packages/cli/src/repowise/cli/platform/telemetry/emitter.py
index d17c04183..6f0f1b002 100644
--- a/packages/cli/src/repowise/cli/platform/telemetry/emitter.py
+++ b/packages/cli/src/repowise/cli/platform/telemetry/emitter.py
@@ -48,19 +48,18 @@ def _cli_version() -> str:
def _under_test() -> bool:
- """Return whether we are running inside a pytest session.
+ """Return whether a test runner is driving this process.
The suite drives real CLI commands, and its fixtures relocate the home
- directory that holds ``anon_id``, so without this every test run delivers
- 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.
+ directory that holds ``anon_id``, so without this every test run would
+ queue events under a freshly minted install. Only delivery is suppressed:
+ consent resolution and the debug print stay real, so their tests still
+ exercise them. Shared with the core emitter, which also honours the
+ ``REPOWISE_TELEMETRY_IN_TESTS`` opt-in telemetry's own tests use.
"""
- return environment.under_pytest() or "pytest" in sys.modules
+ from repowise.core.platform.telemetry import under_test
+
+ return under_test()
def build_envelope(event: TelemetryEvent) -> dict[str, object]:
@@ -70,7 +69,7 @@ def build_envelope(event: TelemetryEvent) -> dict[str, object]:
"anon_id": identity.get_anonymous_id(),
"session_id": identity.get_session_id(),
"cli_version": _cli_version(),
- "properties": event.properties(),
+ "properties": {"client": environment.client(), **event.properties()},
}
envelope.update(environment.base_facts())
return envelope
@@ -90,6 +89,8 @@ def record(event: TelemetryEvent) -> None:
file=sys.stderr,
)
return
+ if _under_test():
+ return
spool.append(envelope)
except Exception:
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/environment.py b/packages/cli/src/repowise/cli/platform/telemetry/environment.py
index 02124742e..53a204c37 100644
--- a/packages/cli/src/repowise/cli/platform/telemetry/environment.py
+++ b/packages/cli/src/repowise/cli/platform/telemetry/environment.py
@@ -12,6 +12,7 @@ import os
import platform
from repowise.core.ci.base import CI_ENV_VARS as _CI_ENV_VARS
+from repowise.core.platform.telemetry import pytest_in_env
def os_family() -> str:
@@ -34,13 +35,9 @@ 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.
+ a subprocess boundary. Shared with the core emitter so the two cannot drift.
"""
- return bool(os.environ.get("PYTEST_CURRENT_TEST") or os.environ.get("PYTEST_VERSION"))
+ return pytest_in_env()
def is_ci() -> bool:
@@ -62,3 +59,15 @@ def base_facts() -> dict[str, object]:
"python_version": python_version(),
"is_ci": is_ci(),
}
+
+
+def client() -> str:
+ """Return the host that launched this process, as one fixed label.
+
+ See :func:`repowise.core.platform.telemetry.detect_client` for the labels.
+ A command that knows better (a hook handed ``--client``) overrides it
+ through :func:`..add_command_outcome`.
+ """
+ from repowise.core.platform.telemetry import detect_client
+
+ return detect_client()
diff --git a/packages/core/src/repowise/core/agents/identity.py b/packages/core/src/repowise/core/agents/identity.py
index ace59327d..706dc5fd0 100644
--- a/packages/core/src/repowise/core/agents/identity.py
+++ b/packages/core/src/repowise/core/agents/identity.py
@@ -51,7 +51,7 @@ UNKNOWN_AGENT = "unknown"
#: Version of the announced-name mapping, recorded on events that used it so a
#: later change to the alias rules is legible in stored data.
-CLIENT_IDENTITY_MAPPING_VERSION = "mcp_client_info_v1"
+CLIENT_IDENTITY_MAPPING_VERSION = "mcp_client_info_v2"
#: Storage rule for an agent slug. Syntactic on purpose — see the module
#: docstring. Bounded so a column value cannot be a payload.
@@ -193,6 +193,8 @@ CLAUDE_CODE = AgentIdentity(
CODEX = AgentIdentity(
slug="codex",
display_name="Codex CLI",
+ #: Codex announces its MCP client (`codex-mcp-client`), not the product.
+ announced_as=frozenset({"codexmcpclient"}),
hook_adapter="codex",
session_adapter="codex",
capture_adapter="codex",
@@ -202,10 +204,16 @@ CODEX = AgentIdentity(
login_hint="codex login",
indexing_provider="codex_cli",
)
-VSCODE = AgentIdentity(slug="vscode", display_name="VS Code", executable="code")
+VSCODE = AgentIdentity(
+ slug="vscode",
+ display_name="VS Code",
+ announced_as=frozenset({"visualstudiocode", "visualstudiocodeinsiders"}),
+ executable="code",
+)
CURSOR = AgentIdentity(
slug="cursor",
display_name="Cursor",
+ announced_as=frozenset({"cursorvscode"}),
hook_adapter="cursor",
capture_adapter="cursor",
executable="cursor",
diff --git a/packages/core/src/repowise/core/platform/telemetry.py b/packages/core/src/repowise/core/platform/telemetry.py
index ebb7fd70f..8639a2312 100644
--- a/packages/core/src/repowise/core/platform/telemetry.py
+++ b/packages/core/src/repowise/core/platform/telemetry.py
@@ -115,6 +115,70 @@ def _is_ci() -> bool:
return any(os.environ.get(var) for var in CI_ENV_VARS)
+#: Opt back in to delivery under a test runner. Only telemetry's own tests set it.
+TESTS_OPT_IN_ENV = "REPOWISE_TELEMETRY_IN_TESTS"
+
+
+def pytest_in_env() -> bool:
+ """Whether a pytest session is in progress, judged from the environment.
+
+ The env survives a subprocess boundary, so a real ``repowise`` command a
+ test spawns sees it too. ``PYTEST_CURRENT_TEST`` covers a running test;
+ ``PYTEST_VERSION`` (pytest 8.1+) also covers collection and teardown.
+ """
+ return bool(os.environ.get("PYTEST_CURRENT_TEST") or os.environ.get("PYTEST_VERSION"))
+
+
+def under_test() -> bool:
+ """Whether delivery is suppressed because a test runner is driving this process.
+
+ Test fixtures relocate the home that holds ``anon_id``, so every test that
+ reaches the emitter would otherwise register a brand new install. Applies to
+ any project's suite that exercises repowise, not only this one.
+ """
+ if _env_truthy(TESTS_OPT_IN_ENV):
+ return False
+ import sys
+
+ return pytest_in_env() or "pytest" in sys.modules
+
+
+#: Host labels, checked in order. Agents come before editors because an agent
+#: running inside an editor terminal sees both; Cursor before VS Code because
+#: Cursor's terminal also sets ``TERM_PROGRAM=vscode``.
+_HOST_ENV_VARS: tuple[tuple[str, tuple[str, ...]], ...] = (
+ ("claude_code", ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")),
+ (
+ "codex",
+ (
+ "CODEX_SANDBOX",
+ "CODEX_SANDBOX_NETWORK_DISABLED",
+ "CODEX_MANAGED_BY_NPM",
+ "CODEX_MANAGED_BY_BUN",
+ ),
+ ),
+ ("cursor", ("CURSOR_TRACE_ID", "CURSOR_AGENT")),
+ ("vscode", ("VSCODE_PID", "VSCODE_IPC_HOOK_CLI")),
+)
+
+#: Every value :func:`detect_client` can return.
+CLIENT_LABELS = frozenset({label for label, _ in _HOST_ENV_VARS} | {"ci", "terminal"})
+
+
+def detect_client() -> str:
+ """Name the host that launched this process, from its environment alone.
+
+ One fixed label, never an env value: ``claude_code``, ``codex``,
+ ``cursor``, ``vscode``, ``ci``, else ``terminal``.
+ """
+ for label, names in _HOST_ENV_VARS:
+ if any(os.environ.get(name) for name in names):
+ return label
+ if os.environ.get("TERM_PROGRAM", "").lower() == "vscode":
+ return "vscode"
+ return "ci" if _is_ci() else "terminal"
+
+
def _version() -> str:
try:
from repowise.core import __version__
@@ -141,7 +205,7 @@ def build_envelope(event: str, properties: dict[str, Any]) -> dict[str, object]:
"anon_id": get_anonymous_id(),
"session_id": _SESSION_ID,
"cli_version": _version(),
- "properties": properties,
+ "properties": {"client": detect_client(), **properties},
}
envelope.update(_base_facts())
return envelope
@@ -189,6 +253,9 @@ def record_event(event: str, properties: dict[str, Any] | None = None) -> None:
file=sys.stderr,
)
return
+ if under_test():
+ # After the debug print, so a test can still see what would leave.
+ return
thread = threading.Thread(target=_deliver, args=(event, props), daemon=True)
thread.start()
diff --git a/packages/server/src/repowise/server/mcp_server/_failure_shield.py b/packages/server/src/repowise/server/mcp_server/_failure_shield.py
index 34005cb88..61b2c1e47 100644
--- a/packages/server/src/repowise/server/mcp_server/_failure_shield.py
+++ b/packages/server/src/repowise/server/mcp_server/_failure_shield.py
@@ -195,21 +195,43 @@ def _shape_internal_error(tool: str, exc: Exception) -> dict[str, Any]:
}
-def _shape_exception(tool: str, exc: Exception, *, long_running: bool = True) -> dict[str, Any]:
- """*long_running* is False for a process that imports fresh on every run (the CLI)."""
+def _exception_reason(exc: Exception) -> str:
+ """The coarse telemetry reason for a shielded exception: a fixed slug."""
if isinstance(exc, LookupError):
- if _NOT_INDEXED_MARKER in str(exc):
- return _shape_not_indexed()
- return _shape_unknown_repo(exc)
+ return "no_index" if _NOT_INDEXED_MARKER in str(exc) else "not_found"
# Workspace mode raises ValueError("Unknown repo '<alias>'. Available:
# [...]") from the registry — same expected condition, different type.
if isinstance(exc, ValueError) and str(exc).startswith("Unknown repo"):
- return _shape_unknown_repo(exc)
+ return "not_found"
if _is_stale_index_error(exc):
- return _shape_stale_index(exc)
+ return "index_behind"
if is_stale_server_import(exc):
- return _shape_stale_server(exc) if long_running else _shape_broken_install(exc)
- return _shape_internal_error(tool, exc)
+ return "server_stale"
+ return "internal"
+
+
+_SHAPES: dict[str, Callable[[str, Exception, bool], dict[str, Any]]] = {
+ "no_index": lambda tool, exc, long_running: _shape_not_indexed(),
+ "not_found": lambda tool, exc, long_running: _shape_unknown_repo(exc),
+ "index_behind": lambda tool, exc, long_running: _shape_stale_index(exc),
+ "server_stale": lambda tool, exc, long_running: (
+ _shape_stale_server(exc) if long_running else _shape_broken_install(exc)
+ ),
+ "internal": lambda tool, exc, long_running: _shape_internal_error(tool, exc),
+}
+
+
+def _shape_exception(tool: str, exc: Exception, *, long_running: bool = True) -> dict[str, Any]:
+ """*long_running* is False for a process that imports fresh on every run (the CLI).
+
+ Also notes the reason on the call in flight, so the ``mcp_tool_call`` event
+ can say why the call failed without reading the message.
+ """
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ reason = _exception_reason(exc)
+ note_error_reason(reason)
+ return _SHAPES[reason](tool, exc, long_running)
async def _await_import_warmup(tool: str) -> None:
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 410b61b91..9ed3dafb7 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -223,6 +223,9 @@ async def _resolve_repo_context(repo: str | None = None) -> Any:
def _unsupported_repo_all(tool_name: str) -> dict:
"""Return an error dict for tools that don't support ``repo='all'``."""
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("invalid_args")
registry = _state._registry
available = registry.get_all_aliases() if registry is not None else []
return {
diff --git a/packages/server/src/repowise/server/mcp_server/_savings/interaction.py b/packages/server/src/repowise/server/mcp_server/_savings/interaction.py
index 87c4c29f7..4c041fa82 100644
--- a/packages/server/src/repowise/server/mcp_server/_savings/interaction.py
+++ b/packages/server/src/repowise/server/mcp_server/_savings/interaction.py
@@ -54,6 +54,9 @@ class Interaction:
baseline_input_tokens: int | None = None
#: Raw tool output, before any budget shed anything.
pre_budget_input_tokens: int | None = None
+ #: Why an in-band ``{"error": ...}`` reply failed, as a fixed slug for
+ #: telemetry. Set where the error payload is built; see :data:`ERROR_REASONS`.
+ error_reason: str | None = None
def observe_pre_budget(self, tokens: int | None) -> None:
"""Record the raw size, first positive writer only.
@@ -87,6 +90,23 @@ def current() -> Interaction | None:
return _CURRENT.get()
+#: Every ``error_reason`` a tool call can report. Fixed slugs, never message text.
+ERROR_REASONS = frozenset(
+ {"not_found", "invalid_args", "no_index", "index_behind", "server_stale", "internal"}
+)
+
+
+def note_error_reason(reason: str) -> None:
+ """Record why the call in flight is answering with an error. Never raises.
+
+ The first note wins: the site that built the payload knows best, and an
+ outer layer that sees the same failure must not overwrite it.
+ """
+ live = _CURRENT.get()
+ if live is not None and live.error_reason is None and reason in ERROR_REASONS:
+ live.error_reason = reason
+
+
@contextmanager
def begin(tool: str) -> Iterator[Interaction]:
"""Open an invocation, mint its id, and attribute it. Never raises."""
diff --git a/packages/server/src/repowise/server/mcp_server/_savings/wrapper.py b/packages/server/src/repowise/server/mcp_server/_savings/wrapper.py
index 72731ab29..9c276a518 100644
--- a/packages/server/src/repowise/server/mcp_server/_savings/wrapper.py
+++ b/packages/server/src/repowise/server/mcp_server/_savings/wrapper.py
@@ -102,6 +102,48 @@ def _results_count_bucket(result: Any) -> str | None:
return "10+"
+def _client_label() -> str:
+ """The host making this call, as one fixed label.
+
+ The MCP ``clientInfo`` name, resolved through the agent registry, is the
+ best evidence. Without it, the server's own environment is the fallback,
+ and a stdio server is never a plain terminal, so that answer becomes
+ ``unknown``.
+ """
+ from repowise.core.agents.identity import UNKNOWN_AGENT
+ from repowise.core.platform.telemetry import detect_client
+
+ live = interaction.current()
+ if live is not None and live.agent != UNKNOWN_AGENT:
+ return live.agent
+ label = detect_client()
+ return UNKNOWN_AGENT if label == "terminal" else label
+
+
+def _error_reason() -> str:
+ """Why the call in flight failed, from the note its error payload left.
+
+ ``other`` for an in-band error whose site does not note a reason yet.
+ """
+ live = interaction.current()
+ return (live.error_reason if live is not None else None) or "other"
+
+
+def _result_flags(result: dict[str, Any]) -> dict[str, Any]:
+ """The coarse enums a reply carries at the top level and booleans in its ``_meta``."""
+ flags: dict[str, Any] = {}
+ for key in _RESULT_ENUMS:
+ value = result.get(key)
+ if isinstance(value, str) and value:
+ flags[key] = value
+ meta = result.get("_meta")
+ if isinstance(meta, dict):
+ for key in _META_FLAGS:
+ if isinstance(meta.get(key), bool):
+ flags[key] = meta[key]
+ return flags
+
+
def _telemetry_properties(tool: str, result: Any, duration_ms: int) -> dict[str, Any]:
"""Build the anonymous ``mcp_tool_call`` properties for *result*.
@@ -112,17 +154,12 @@ def _telemetry_properties(tool: str, result: Any, duration_ms: int) -> dict[str,
"tool": tool,
"status": "error" if is_error else "ok",
"duration_ms": duration_ms,
+ "client": _client_label(),
}
+ if is_error:
+ props["error_reason"] = _error_reason()
if isinstance(result, dict):
- for key in _RESULT_ENUMS:
- value = result.get(key)
- if isinstance(value, str) and value:
- props[key] = value
- meta = result.get("_meta")
- if isinstance(meta, dict):
- for key in _META_FLAGS:
- if isinstance(meta.get(key), bool):
- props[key] = meta[key]
+ props.update(_result_flags(result))
bucket = _results_count_bucket(result)
if bucket is not None:
props["results_bucket"] = bucket
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index 0ebbba27b..bbb0e5a72 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -49,8 +49,16 @@ class StoreUnavailableError(RuntimeError):
one to respawn, so an unwritable .repowise became a crash loop. Click-free
because the server does not depend on the CLI; the mcp command turns it
into a clean non-zero exit.
+
+ ``reason`` is a fixed slug for anonymous telemetry, never message text:
+ ``store_open_failed``, ``db_url_unreachable`` or
+ ``workspace_default_failed``.
"""
+ def __init__(self, message: str, *, reason: str = "store_open_failed") -> None:
+ super().__init__(message)
+ self.reason = reason
+
#: Store served for a directory with no ``.repowise/``: empty, so tools report
#: "not indexed", and never written to disk.
@@ -58,20 +66,26 @@ _NO_INDEX_DB_URL = "sqlite+aiosqlite:///:memory:"
def _store_unavailable(
- where: str | None, repo_path: str | None, exc: BaseException
+ where: str | None,
+ repo_path: str | None,
+ exc: BaseException,
+ *,
+ reason: str = "store_open_failed",
) -> StoreUnavailableError:
"""``where`` is the repo-local directory, or None when an env URL is in use;
a configured database gets its own remedy, not the directory one."""
if where is None:
return StoreUnavailableError(
f"repowise MCP: cannot open the configured database: {exc}. "
- "Check REPOWISE_DB_URL and that the database server is reachable."
+ "Check REPOWISE_DB_URL and that the database server is reachable.",
+ reason="db_url_unreachable",
)
repo = repo_path or "the repository"
return StoreUnavailableError(
f"repowise MCP: cannot open the index store at {where}: {exc}. "
f"Run 'repowise init' in {repo} to create it, or fix the permissions "
- "on that directory."
+ "on that directory.",
+ reason=reason,
)
@@ -530,7 +544,9 @@ async def _lifespan(server: FastMCP):
default_ctx = await registry.get_default()
except (OSError, OperationalError) as exc:
await _abort_startup(_release_task, _warm_task)
- raise _store_unavailable(str(ws_root), str(ws_root), exc) from exc
+ raise _store_unavailable(
+ str(ws_root), str(ws_root), exc, reason="workspace_default_failed"
+ ) from exc
except BaseException:
await _abort_startup(_release_task, _warm_task)
raise
@@ -588,6 +604,7 @@ async def _lifespan(server: FastMCP):
# When repo path is set and no env override, prefer repo-local DB.
store_location: str | None = None
db_url: str | None = None
+ _state._serving_no_index = False
try:
if _state._repo_path and configured_db_url is None:
db_path = get_repo_db_path(_state._repo_path)
@@ -604,6 +621,7 @@ async def _lifespan(server: FastMCP):
"No %s in %s; run 'repowise init'", repowise_dir.name, repowise_dir.parent
)
db_url = _NO_INDEX_DB_URL
+ _state._serving_no_index = True
elif not db_path.exists():
_log.warning(
"No wiki.db in %s — run 'repowise init' to generate the wiki",
diff --git a/packages/server/src/repowise/server/mcp_server/_state.py b/packages/server/src/repowise/server/mcp_server/_state.py
index 6d0b2e902..fc8686af2 100644
--- a/packages/server/src/repowise/server/mcp_server/_state.py
+++ b/packages/server/src/repowise/server/mcp_server/_state.py
@@ -25,6 +25,9 @@ _served_repo_id: str | None = None
# When set, the server skips workspace auto-detection even if the path is
# inside a workspace root. This backs the CLI's `--no-workspace` escape hatch.
_force_single_repo: bool = False
+# Set by _lifespan when the directory has no .repowise/ and the server is
+# serving the empty in-memory store. Read by the mcp command for telemetry.
+_serving_no_index: bool = False
# Set to an asyncio.Event by _lifespan; signals that vector stores are loaded.
# tool_search awaits this before searching to avoid racing a background load.
_vector_store_ready: asyncio.Event | None = None
diff --git a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
index a0abad0d9..954b034a6 100644
--- a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
+++ b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
@@ -130,6 +130,9 @@ def one_repo_refusal(tool: str, routes: list[Route]) -> dict[str, Any]:
for alias, rs in groups.items()
)
error = f"The targets span several workspace repos; {tool} reads one per call: {calls}."
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("not_found" if unresolved else "invalid_args")
return {
"error": error,
"routes": {
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
index 8f046032f..2873c64e6 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
@@ -391,6 +391,9 @@ class _Ask:
def _empty_question_payload(t0: float) -> dict:
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("invalid_args")
return {
"answer": "",
"citations": [],
diff --git a/packages/server/src/repowise/server/mcp_server/tool_flows.py b/packages/server/src/repowise/server/mcp_server/tool_flows.py
index 518f2e835..57bb73a42 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_flows.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py
@@ -126,6 +126,9 @@ async def get_execution_flows(
# Trace from a specific symbol
node = await _entry_node(session, repo_id, entry_point, exclude_spec)
if node is None:
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("not_found")
return {
"entry_point": entry_point,
"error": f"Symbol not found: {entry_point!r}",
diff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
index c33b1175c..5139cfd14 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
@@ -80,6 +80,9 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)
None,
)
if row is None:
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("not_found")
return {
"error": "not_found",
"detail": f"No refactoring plan with id {suggestion_id!r} in this repo.",
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
index 2cb957be6..7ef328de7 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py
@@ -486,6 +486,9 @@ async def get_risk(
if repo == "all":
return _unsupported_repo_all("get_risk")
if not targets and not changed_files:
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("invalid_args")
return {"error": "targets or changed_files is required", "_meta": _build_meta()}
routes = (
await route_targets([*(targets or []), *(changed_files or [])], paths_only=True)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search/tool.py b/packages/server/src/repowise/server/mcp_server/tool_search/tool.py
index 2843b758e..09edff9b6 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search/tool.py
@@ -241,6 +241,9 @@ async def search_codebase(
ignored: list[dict[str, Any]] = []
query = _query_from_pattern(query, pattern, ignored)
if not query.strip():
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("invalid_args")
return {
"results": [],
"error": "search_codebase requires `query` (or its alias `pattern`).",
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/body.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/body.py
index 51234477c..d982d7177 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol/body.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/body.py
@@ -113,6 +113,9 @@ async def _container_outline(
def _unreadable_source_response(row: Any, symbol_id: str, repository: Any, t0: float) -> dict:
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("index_behind")
return {
"symbol_id": symbol_id,
"file": row.file_path,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/misses.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/misses.py
index b6c5080de..9d30ba9c7 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol/misses.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/misses.py
@@ -106,6 +106,10 @@ async def _not_found_response(
return live
async with get_session(ctx.session_factory) as session:
suggestions = await _symbol_suggestions(session, repository.id, symbol_id, exclude_spec)
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ # Both replies below are a miss, with or without suggestions.
+ note_error_reason("not_found")
if suggestions:
return {
"symbol_id": symbol_id,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/omission.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/omission.py
index 01e94b9c8..075883adb 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol/omission.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/omission.py
@@ -69,6 +69,9 @@ def _resolve_omission_ref(
break
if record is None:
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("not_found")
return {
"symbol_id": symbol_id,
"ref": canonical_ref,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/tool.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/tool.py
index 72f277801..398d289c3 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/tool.py
@@ -161,6 +161,9 @@ async def get_symbol(
t0 = time.perf_counter()
symbol_id, query = _requested_id(symbol_id, id, query)
if not symbol_id or not symbol_id.strip():
+ from repowise.server.mcp_server._savings.interaction import note_error_reason
+
+ note_error_reason("invalid_args")
return {
"symbol_id": symbol_id,
"error": 'get_symbol requires `symbol_id`, e.g. "path/to/file.py::Name".',
diff --git a/tests/unit/cli/test_agent_identity.py b/tests/unit/cli/test_agent_identity.py
index f0c1c4796..bf42ad1b1 100644
--- a/tests/unit/cli/test_agent_identity.py
+++ b/tests/unit/cli/test_agent_identity.py
@@ -359,3 +359,17 @@ def test_an_unannounced_client_is_stored_as_unknown_not_as_the_fallback() -> Non
resolved, _ = normalize_mcp_identity(None)
assert resolved == UNKNOWN_AGENT
assert resolved != identity_for_target_id("claude-code").slug # type: ignore[union-attr]
+
+
+ ("announced", "slug"),
+ [
+ ("codex-mcp-client", "codex"),
+ ("cursor-vscode", "cursor"),
+ ("Visual Studio Code", "vscode"),
+ ("Visual Studio Code - Insiders", "vscode"),
+ ("claude-code", "claude_code"),
+ ],
+)
+def test_hosts_resolve_from_the_name_they_announce(announced, slug):
+ assert resolve_client_identity(announced) == slug
diff --git a/tests/unit/cli/test_mcp_transport.py b/tests/unit/cli/test_mcp_transport.py
index baa2207d3..e0ce14ec8 100644
--- a/tests/unit/cli/test_mcp_transport.py
+++ b/tests/unit/cli/test_mcp_transport.py
@@ -503,6 +503,28 @@ def test_the_way_a_session_ended_reaches_the_invocation_outcome(
assert result.exit_code == 0
assert recorded["transport_outcome"] == "client_closed"
assert recorded["transport"] == "stdio"
+ assert recorded["served_no_index"] is False
+
+
+def test_a_store_failure_reports_its_reason_code(monkeypatch, tmp_path: Path) -> None:
+ """A startup exit says which store failed, not only that the server faulted."""
+ from repowise.cli.platform import telemetry
+ from repowise.server.mcp_server._server import StoreUnavailableError
+
+ (tmp_path / ".repowise").mkdir()
+ recorded: dict[str, object] = {}
+ monkeypatch.setattr(telemetry, "add_command_outcome", recorded.update)
+
+ def refuse(**_kw):
+ raise StoreUnavailableError("cannot open", reason="db_url_unreachable")
+
+ monkeypatch.setattr("repowise.server.mcp_server.run_mcp", refuse)
+
+ result = CliRunner().invoke(cli, ["mcp", str(tmp_path)])
+
+ assert result.exit_code == 1
+ assert recorded["transport_outcome"] == "server_fault"
+ assert recorded["failure_reason"] == "db_url_unreachable"
def test_a_client_hanging_up_is_not_an_error_exit(monkeypatch, tmp_path: Path) -> None:
diff --git a/tests/unit/cli/test_telemetry.py b/tests/unit/cli/test_telemetry.py
index 682d646c7..c30209841 100644
--- a/tests/unit/cli/test_telemetry.py
+++ b/tests/unit/cli/test_telemetry.py
@@ -16,7 +16,7 @@ import pytest
from click.testing import CliRunner
from repowise.cli.platform import identity, settings, store
-from repowise.cli.platform.telemetry import emitter, spool
+from repowise.cli.platform.telemetry import emitter, environment, spool
from repowise.cli.platform.telemetry.events import CommandRunEvent
@@ -38,6 +38,8 @@ def isolated_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
):
monkeypatch.delenv(var, raising=False)
monkeypatch.setattr(emitter, "_flush_thread", None, raising=False)
+ # These tests exercise delivery itself, so they opt back in to it.
+ monkeypatch.setenv("REPOWISE_TELEMETRY_IN_TESTS", "1")
class TestConsentPrecedence:
@@ -224,15 +226,36 @@ class TestSpooledDelivery:
emitter._flush()
assert spawned == [True]
- def test_exit_spawns_nothing_under_pytest(self, monkeypatch: pytest.MonkeyPatch):
+ def test_nothing_is_queued_or_spawned_under_pytest(self, monkeypatch: pytest.MonkeyPatch):
spawned: list = []
monkeypatch.setattr(emitter, "_spawn_flusher", lambda: spawned.append(True) or True)
+ monkeypatch.delenv("REPOWISE_TELEMETRY_IN_TESTS")
emitter.record(CommandRunEvent(command="health"))
emitter._flush()
+ assert spool.claim() == []
assert spawned == []
+ def test_debug_still_prints_under_pytest(
+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
+ ):
+ monkeypatch.delenv("REPOWISE_TELEMETRY_IN_TESTS")
+ monkeypatch.setenv("REPOWISE_TELEMETRY_DEBUG", "1")
+ emitter.record(CommandRunEvent(command="health"))
+ assert "would send" in capsys.readouterr().err
+
+ def test_envelope_carries_a_client_label(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(environment, "client", lambda: "codex")
+ envelope = emitter.build_envelope(CommandRunEvent(command="health"))
+ assert envelope["properties"]["client"] == "codex"
+ assert "client" not in envelope # a property, not a top-level field
+
+ def test_a_command_outcome_client_wins(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(environment, "client", lambda: "terminal")
+ event = CommandRunEvent(command="augment", extra={"client": "cursor"})
+ assert emitter.build_envelope(event)["properties"]["client"] == "cursor"
+
def test_flusher_posts_and_drains(self, monkeypatch: pytest.MonkeyPatch):
from repowise.cli.platform import client
from repowise.cli.platform.telemetry import flusher
diff --git a/tests/unit/cli/test_update_progress_json.py b/tests/unit/cli/test_update_progress_json.py
index 68ef1d04e..43afbdab7 100644
--- a/tests/unit/cli/test_update_progress_json.py
+++ b/tests/unit/cli/test_update_progress_json.py
@@ -147,6 +147,25 @@ class TestUpdateProgressJsonCli:
for line in lines:
json.loads(line) # would raise if any non-JSON line leaked through
+ @pytest.mark.parametrize(
+ ("state", "reason"),
+ [(None, "no_index"), ('{"total_pages": 3}', "no_sync_base")],
+ )
+ def test_no_prior_sync_reports_a_reason_code(self, monkeypatch, state, reason):
+ from repowise.cli.platform import telemetry
+
+ recorded: dict = {}
+ monkeypatch.setattr(telemetry, "add_command_outcome", recorded.update)
+ with tempfile.TemporaryDirectory() as td:
+ os.makedirs(os.path.join(td, ".repowise"))
+ if state is not None:
+ with open(os.path.join(td, ".repowise", "state.json"), "w") as fh:
+ fh.write(state)
+ result = _split_output_runner().invoke(cli, ["update", td])
+
+ assert result.exit_code != 0
+ assert recorded["failure_reason"] == reason
+
def test_up_to_date_emits_start_stage_done(self):
runner = _split_output_runner()
with tempfile.TemporaryDirectory() as td:
diff --git a/tests/unit/server/mcp/test_failure_shield.py b/tests/unit/server/mcp/test_failure_shield.py
index 269af1964..740cc4c17 100644
--- a/tests/unit/server/mcp/test_failure_shield.py
+++ b/tests/unit/server/mcp/test_failure_shield.py
@@ -335,3 +335,26 @@ async def test_gate_is_bounded(monkeypatch):
return {"ok": True}
assert await shield(tool)() == {"ok": True}
+
+
+ ("exc", "reason"),
+ [
+ (LookupError("No repositories found. Run repowise init."), "no_index"),
+ (LookupError("Repository 'x' not found"), "not_found"),
+ (ValueError("Unknown repo 'x'. Available: []"), "not_found"),
+ (RuntimeError("boom"), "internal"),
+ ],
+)
+async def test_a_shielded_failure_notes_its_reason_code(exc, reason):
+ """The mcp_tool_call event says why, from a fixed code, never the message."""
+ from repowise.server.mcp_server._savings import interaction
+
+ async def get_answer() -> dict:
+ raise exc
+
+ with interaction.begin("get_answer") as live:
+ result = await shield(get_answer)()
+ assert result["error"]
+ assert live.error_reason == reason
diff --git a/tests/unit/server/mcp/test_startup_guards.py b/tests/unit/server/mcp/test_startup_guards.py
index b9faca786..37b3b49e4 100644
--- a/tests/unit/server/mcp/test_startup_guards.py
+++ b/tests/unit/server/mcp/test_startup_guards.py
@@ -44,6 +44,7 @@ async def test_lifespan_names_the_path_when_the_store_cannot_be_opened(
message = str(raised.value)
assert str(tmp_path / ".repowise") in message
assert "repowise init" in message
+ assert raised.value.reason == "store_open_failed"
# The failure path never reaches the teardown, so it has to leave the
# warmup event cleared itself. A leaked event stays bound to this test's
# loop and makes every later tool call raise inside the failure shield.
@@ -78,6 +79,7 @@ async def test_unindexed_directory_starts_and_reports_no_index(
assert "no repowise index" in result["error"].lower()
assert "repowise init" in result["remedy"]
+ assert _state._serving_no_index is True
assert not (tmp_path / ".repowise").exists()
assert _state._lancedb_ready is None
@@ -128,6 +130,7 @@ async def test_configured_database_failure_names_the_url_not_the_directory(
message = str(raised.value)
assert "REPOWISE_DB_URL" in message
assert "repowise init" not in message
+ assert raised.value.reason == "db_url_unreachable"
@pytest.mark.asyncio
diff --git a/tests/unit/server/mcp/test_tool_telemetry.py b/tests/unit/server/mcp/test_tool_telemetry.py
index 0626e8e0f..0d73f443a 100644
--- a/tests/unit/server/mcp/test_tool_telemetry.py
+++ b/tests/unit/server/mcp/test_tool_telemetry.py
@@ -30,6 +30,8 @@ class TestTelemetryProperties:
key here and the equality assertions would fail for the wrong reason.
"""
monkeypatch.setattr(wrapper, "_semantic_search_state", lambda: None)
+ # Likewise the host label, which reads the process environment.
+ monkeypatch.setattr(wrapper, "_client_label", lambda: "claude_code")
def test_answer_shape_extracts_enums_and_flags(self):
result = {
@@ -45,6 +47,7 @@ class TestTelemetryProperties:
"tool": "get_answer",
"status": "ok",
"duration_ms": 42,
+ "client": "claude_code",
"confidence": "high",
"retrieval_quality": "strong",
"grounding": "exact_symbol",
@@ -100,6 +103,28 @@ class TestTelemetryProperties:
def test_error_result_is_status_error(self):
props = wrapper._telemetry_properties("get_symbol", {"error": "boom"}, 3)
assert props["status"] == "error"
+ # No site noted a reason, so it says so rather than guessing.
+ assert props["error_reason"] == "other"
+
+ def test_error_reason_comes_from_the_note_not_the_message(self):
+ from repowise.server.mcp_server._savings import interaction
+
+ with interaction.begin("get_symbol"):
+ interaction.note_error_reason("not_found")
+ interaction.note_error_reason("internal") # the first note wins
+ props = wrapper._telemetry_properties("get_symbol", {"error": "Symbol x"}, 3)
+ assert props["error_reason"] == "not_found"
+
+ def test_an_unknown_reason_is_never_recorded(self):
+ from repowise.server.mcp_server._savings import interaction
+
+ with interaction.begin("get_symbol"):
+ interaction.note_error_reason("Symbol not found: 'secret'")
+ props = wrapper._telemetry_properties("get_symbol", {"error": "x"}, 3)
+ assert props["error_reason"] == "other"
+
+ def test_ok_result_has_no_error_reason(self):
+ assert "error_reason" not in wrapper._telemetry_properties("get_answer", {}, 1)
def test_search_result_reports_count_bucket_not_content(self):
result = {"results": [{"path": "secret/a.py"}, {"path": "secret/b.py"}]}
@@ -110,6 +135,7 @@ class TestTelemetryProperties:
"tool",
"status",
"duration_ms",
+ "client",
"results_bucket",
"response_chars",
"response_tokens",
@@ -118,7 +144,12 @@ class TestTelemetryProperties:
def test_non_dict_result_is_safe(self):
props = wrapper._telemetry_properties("get_overview", "unexpected", 1)
- assert props == {"tool": "get_overview", "status": "ok", "duration_ms": 1}
+ assert props == {
+ "tool": "get_overview",
+ "status": "ok",
+ "duration_ms": 1,
+ "client": "claude_code",
+ }
def test_response_size_is_the_serialised_payload(self):
"""Size is a number about the payload, not any of its content."""
@@ -142,6 +173,7 @@ class TestTelemetryProperties:
"tool": "get_answer",
"status": "ok",
"duration_ms": 1,
+ "client": "claude_code",
"confidence": "high",
}
@@ -190,3 +222,25 @@ def test_response_size_prefers_the_budget_stamp(monkeypatch: pytest.MonkeyPatch)
props = wrapper._telemetry_properties("get_answer", result, 1)
assert props["response_chars"] == 4000
assert props["response_tokens"] == 1000
+
+
+class TestClientLabel:
+ def test_announced_client_wins(self, monkeypatch: pytest.MonkeyPatch):
+ from repowise.server.mcp_server._savings import interaction
+
+ monkeypatch.setattr(interaction, "_attribution", lambda: ("codex", {}, None))
+ monkeypatch.setenv("CLAUDECODE", "1")
+ with interaction.begin("get_answer"):
+ assert wrapper._client_label() == "codex"
+
+ def test_falls_back_to_the_environment(self, monkeypatch: pytest.MonkeyPatch):
+ from repowise.core.platform import telemetry
+
+ monkeypatch.setattr(telemetry, "detect_client", lambda: "cursor")
+ assert wrapper._client_label() == "cursor"
+
+ def test_a_server_is_never_a_terminal(self, monkeypatch: pytest.MonkeyPatch):
+ from repowise.core.platform import telemetry
+
+ monkeypatch.setattr(telemetry, "detect_client", lambda: "terminal")
+ assert wrapper._client_label() == "unknown"
diff --git a/tests/unit/test_platform_telemetry.py b/tests/unit/test_platform_telemetry.py
index ca3ea75fa..babefe5f1 100644
--- a/tests/unit/test_platform_telemetry.py
+++ b/tests/unit/test_platform_telemetry.py
@@ -8,6 +8,7 @@ envelope shape, and never touch disk or the network on the caller's hot path.
from __future__ import annotations
import json
+import sys
from pathlib import Path
import pytest
@@ -23,6 +24,8 @@ def isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(telemetry, "_state_cache", None, raising=False)
for var in ("DO_NOT_TRACK", "REPOWISE_TELEMETRY_DISABLED", "REPOWISE_TELEMETRY_DEBUG"):
monkeypatch.delenv(var, raising=False)
+ # These tests exercise delivery itself, so they opt back in to it.
+ monkeypatch.setenv(telemetry.TESTS_OPT_IN_ENV, "1")
telemetry._pending.clear()
yield telemetry, state_path
telemetry._pending.clear()
@@ -103,3 +106,89 @@ class TestDebug:
telemetry.record_event("mcp_tool_call", {"tool": "get_answer"})
assert "would send" in capsys.readouterr().err
assert sent == []
+
+
+class TestUnderTest:
+ def test_pytest_suppresses_delivery(self, isolated, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.delenv(telemetry.TESTS_OPT_IN_ENV)
+ sent = _capture(monkeypatch)
+ telemetry.record_event("mcp_tool_call", {"tool": "get_answer"})
+ assert sent == []
+
+ def test_env_alone_is_enough(self, isolated, monkeypatch: pytest.MonkeyPatch):
+ """A subprocess a test spawns has no pytest import, only the env."""
+ monkeypatch.delenv(telemetry.TESTS_OPT_IN_ENV)
+ monkeypatch.delitem(sys.modules, "pytest")
+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
+ monkeypatch.setenv("PYTEST_VERSION", "8.4.2")
+ assert telemetry.under_test() is True
+
+ def test_debug_still_prints(
+ self, isolated, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
+ ):
+ monkeypatch.delenv(telemetry.TESTS_OPT_IN_ENV)
+ monkeypatch.setenv("REPOWISE_TELEMETRY_DEBUG", "1")
+ telemetry.record_event("mcp_tool_call", {"tool": "get_answer"})
+ assert "would send" in capsys.readouterr().err
+
+
+_HOST_VARS = (
+ "CLAUDECODE",
+ "CLAUDE_CODE_ENTRYPOINT",
+ "CODEX_SANDBOX",
+ "CODEX_SANDBOX_NETWORK_DISABLED",
+ "CODEX_MANAGED_BY_NPM",
+ "CODEX_MANAGED_BY_BUN",
+ "CURSOR_TRACE_ID",
+ "CURSOR_AGENT",
+ "VSCODE_PID",
+ "VSCODE_IPC_HOOK_CLI",
+ "TERM_PROGRAM",
+)
+
+
+class TestDetectClient:
+ @pytest.fixture(autouse=True)
+ def _clean_env(self, monkeypatch: pytest.MonkeyPatch):
+ from repowise.core.ci.base import CI_ENV_VARS
+
+ for var in (*_HOST_VARS, *CI_ENV_VARS):
+ monkeypatch.delenv(var, raising=False)
+
+ @pytest.mark.parametrize(
+ ("var", "value", "label"),
+ [
+ ("CLAUDECODE", "1", "claude_code"),
+ ("CODEX_MANAGED_BY_NPM", "1", "codex"),
+ ("CURSOR_TRACE_ID", "abc", "cursor"),
+ ("TERM_PROGRAM", "vscode", "vscode"),
+ ("VSCODE_PID", "123", "vscode"),
+ ("CI", "true", "ci"),
+ ],
+ )
+ def test_each_host(self, monkeypatch: pytest.MonkeyPatch, var, value, label):
+ monkeypatch.setenv(var, value)
+ assert telemetry.detect_client() == label
+ assert label in telemetry.CLIENT_LABELS
+
+ def test_plain_terminal(self):
+ assert telemetry.detect_client() == "terminal"
+
+ def test_agent_in_an_editor_terminal_is_the_agent(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("TERM_PROGRAM", "vscode")
+ monkeypatch.setenv("CLAUDECODE", "1")
+ assert telemetry.detect_client() == "claude_code"
+
+ def test_cursor_terminal_is_cursor_not_vscode(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("TERM_PROGRAM", "vscode")
+ monkeypatch.setenv("CURSOR_TRACE_ID", "abc")
+ assert telemetry.detect_client() == "cursor"
+
+ def test_envelope_carries_it_as_a_property(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("CLAUDECODE", "1")
+ envelope = telemetry.build_envelope("mcp_tool_call", {"tool": "x"})
+ assert envelope["properties"]["client"] == "claude_code"
+ assert "client" not in envelope
+ # A caller that knows better (the MCP clientInfo) overrides it.
+ envelope = telemetry.build_envelope("mcp_tool_call", {"client": "codex"})
+ assert envelope["properties"]["client"] == "codex"