Skip to content

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

feat(cli): central platform layer + anonymous opt-out telemetry (#555)

Raghav Chamadiyab2ca27f32b2f
diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md
new file mode 100644
index 000000000..3286a6cb2
--- /dev/null
+++ b/docs/TELEMETRY.md
@@ -0,0 +1,118 @@
+# Telemetry
+
+Repowise collects **completely anonymous** usage telemetry to help us decide
+what to build and fix. It is **impossible to tie any event to you, your
+machine, or your code**. There are no usernames, no IP addresses, no file
+paths, and no source content anywhere in what we send.
+
+This page documents exactly what is collected, what is never collected, how to
+verify it yourself, and how to turn it off.
+
+## Why we collect it
+
+A tiny amount of anonymous data answers questions we otherwise have to guess at:
+
+- Which commands do people actually run? (where to invest)
+- Which CLI versions and Python versions are in use? (what we can drop support for)
+- What share of runs fail, and on which command? (where the bugs are)
+- Which OSes matter? (what to test on)
+
+That is the whole purpose. We do not sell it, and we do not use it to identify
+anyone.
+
+## What is collected
+
+One event, `command_run`, is sent once per CLI invocation. Every event carries:
+
+| Field | Example | Purpose |
+|---|---|---|
+| `event` | `command_run` | Event type |
+| `anon_id` | `194639…d48a` | Random per-install id (see below) |
+| `session_id` | `e2ecb2…1158` | Random per-process id, groups one run |
+| `cli_version` | `0.21.0` | Version adoption |
+| `os` | `darwin` / `linux` / `windows` | Platform priorities |
+| `arch` | `arm64` / `x86_64` | Architecture priorities |
+| `python_version` | `3.12` | **major.minor only** |
+| `is_ci` | `true` / `false` | Separate automation from humans |
+| `properties.command` | `init`, `update`, `health` | Which command ran |
+| `properties.subcommand` | `decision.add`, `telemetry.status` | A known subcommand name only |
+| `properties.flags` | `["--resume", "--provider"]` | Option **names only**, never values |
+| `properties.status` | `ok` / `error` | Success rate |
+| `properties.error_type` | `LLMProviderError` | Exception **class name only** |
+| `properties.duration_ms` | `71840` | Performance in the wild |
+
+Example payload:
+
+```json
+{
+ "event": "command_run",
+ "anon_id": "194639251e854669ae2f56081620d48a",
+ "session_id": "e2ecb2aeb4df422883c5af451f2b1158",
+ "cli_version": "0.21.0",
+ "os": "darwin",
+ "arch": "arm64",
+ "python_version": "3.12",
+ "is_ci": false,
+ "properties": {
+ "command": "init",
+ "subcommand": null,
+ "flags": ["--resume"],
+ "status": "ok",
+ "error_type": null,
+ "duration_ms": 71840
+ }
+}
+```
+
+## What is **never** collected
+
+- Source code or file contents
+- File paths or directory names
+- Repository names, package names, symbol/function names
+- Generated documentation text
+- Flag **values** (only the flag name is recorded)
+- Environment variable values
+- API keys or credentials
+- Error messages or stack traces (only the exception class name)
+- IP addresses (the server does not record the request source)
+- Usernames, hostnames, email, or anything personally identifiable
+
+## How the anonymous id works
+
+`anon_id` is a random UUID generated once and stored in
+`~/.repowise/platform.json`. It is **not** derived from your hostname,
+username, or any machine identifier, so it cannot be reversed to a person. It
+only lets us count distinct installs. Delete the file and a new, unrelated id
+is generated; nothing links the two.
+
+## Verify it yourself
+
+Run any command with `REPOWISE_TELEMETRY_DEBUG=1` to print the exact payload to
+stderr **without sending anything**:
+
+```bash
+REPOWISE_TELEMETRY_DEBUG=1 repowise status
+```
+
+## How to opt out
+
+Any one of these disables all telemetry:
+
+```bash
+repowise telemetry disable # persisted to ~/.repowise/platform.json
+export REPOWISE_TELEMETRY_DISABLED=1
+export DO_NOT_TRACK=1 # the cross-tool standard (https://consoledonottrack.com)
+```
+
+Check the current state anytime:
+
+```bash
+repowise telemetry status
+```
+
+Re-enable with `repowise telemetry enable`.
+
+## Data retention
+
+Events are retained for 90 days and then deleted. Only aggregate figures (e.g.
+"X% of runs are on Windows") are ever used or shared.
diff --git a/packages/cli/src/repowise/cli/_instrumented_group.py b/packages/cli/src/repowise/cli/_instrumented_group.py
new file mode 100644
index 000000000..055d377d0
--- /dev/null
+++ b/packages/cli/src/repowise/cli/_instrumented_group.py
@@ -0,0 +1,120 @@
+"""The root Click group, instrumented for anonymous telemetry.
+
+A single seam wraps every CLI invocation: it shows the one-time opt-out notice,
+times the command, classifies the outcome, and records exactly one
+``command_run`` event. Doing it here (rather than in each command) guarantees
+uniform, complete coverage and keeps telemetry out of business logic.
+
+Privacy: only the command name, a known subcommand name, option *names*, the
+outcome, and a duration are captured. Positional arguments (which may be file
+paths) are never recorded — a subcommand is only logged when it matches a real
+registered subcommand of a group.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+import time
+
+import click
+
+#: A well-formed long option name, e.g. ``--provider`` or ``--no-cost-tracking``.
+_LONG_OPT = re.compile(r"--[A-Za-z][\w-]*")
+
+
+def _option_name(token: str) -> str:
+ """Reduce a CLI token to a bare option *name*, never a value.
+
+ Critical for privacy: option *values* (which can be file paths or exclude
+ globs) must never be recorded. This handles every shape Click accepts:
+
+ * ``--name=value`` -> ``--name``
+ * ``--name`` -> ``--name``
+ * ``-xVALUE`` (attached) -> ``-x`` (drops the attached short-option value)
+ * ``-x`` / ``-vv`` -> ``-x`` / ``-v``
+ * anything malformed -> the leading dash run only
+ """
+ if token.startswith("--"):
+ head = token.split("=", 1)[0]
+ m = _LONG_OPT.fullmatch(head)
+ return m.group(0) if m else "--"
+ # Single-dash: keep only the dash and the first option letter, dropping any
+ # attached value (``-p/secret/path`` -> ``-p``) or extra combined letters.
+ return token[:2]
+
+
+class InstrumentedGroup(click.Group):
+ """Root group that emits one telemetry event per invocation."""
+
+ def invoke(self, ctx: click.Context):
+ from repowise.cli.platform import telemetry
+
+ telemetry.maybe_show_notice()
+
+ # The unparsed tail (subcommand + its args) is captured now, before
+ # ``super().invoke`` may consume it.
+ tail = list(ctx.args)
+
+ start = time.monotonic()
+ status = "ok"
+ error_type: str | None = None
+ try:
+ return super().invoke(ctx)
+ except SystemExit as exc:
+ if exc.code not in (0, None):
+ status = "error"
+ raise
+ except (click.ClickException, click.exceptions.Abort) as exc:
+ status = "error"
+ error_type = type(exc).__name__ # class name only, never the message
+ raise
+ except Exception as exc:
+ status = "error"
+ error_type = type(exc).__name__
+ raise
+ finally:
+ # ``invoked_subcommand`` is only populated once ``super().invoke``
+ # has parsed and dispatched, so it is read here, not before. It is
+ # ``None`` for bare ``--help``/``--version`` (nothing to record).
+ command = ctx.invoked_subcommand
+ if command and command != "*":
+ duration_ms = int((time.monotonic() - start) * 1000)
+ subcommand, flags = self._subcommand_and_flags(ctx, command, tail)
+ telemetry.record_command_run(
+ command=command,
+ subcommand=subcommand,
+ flags=flags,
+ status=status,
+ error_type=error_type,
+ duration_ms=duration_ms,
+ )
+
+ def _subcommand_and_flags(
+ self, ctx: click.Context, command: str, tail: list[str]
+ ) -> tuple[str | None, list[str]]:
+ """Extract a safe subcommand name and the option *names* of this run.
+
+ Flags come from ``sys.argv`` reduced to bare option names by
+ :func:`_option_name`, so no value (incl. attached short-option values
+ like ``-p/path``) is ever recorded. The subcommand is taken from the
+ unparsed tail and only returned when it matches a real registered
+ subcommand of a group — so positional arguments (which may be file
+ paths) are never logged.
+ """
+ flags = [_option_name(tok) for tok in sys.argv[1:] if tok.startswith("-")]
+
+ subcommand: str | None = None
+ try:
+ cmd = self.get_command(ctx, command)
+ if isinstance(cmd, click.MultiCommand):
+ known = set(cmd.list_commands(ctx))
+ for tok in tail:
+ if tok.startswith("-"):
+ continue
+ if tok in known:
+ subcommand = tok
+ break
+ except Exception:
+ pass
+ return subcommand, flags
diff --git a/packages/cli/src/repowise/cli/commands/telemetry_cmd.py b/packages/cli/src/repowise/cli/commands/telemetry_cmd.py
new file mode 100644
index 000000000..235364a58
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/telemetry_cmd.py
@@ -0,0 +1,42 @@
+"""``repowise telemetry`` — inspect and control anonymous usage telemetry."""
+
+from __future__ import annotations
+
+import click
+
+from repowise.cli.helpers import console
+
+
[email protected](name="telemetry")
+def telemetry_group() -> None:
+ """Inspect and control anonymous, opt-out usage telemetry."""
+
+
+@telemetry_group.command(name="status")
+def telemetry_status() -> None:
+ """Show whether telemetry is enabled and why."""
+ from repowise.cli.platform import telemetry
+
+ for line in telemetry.status_lines():
+ console.print(line)
+
+
+@telemetry_group.command(name="enable")
+def telemetry_enable() -> None:
+ """Enable anonymous usage telemetry."""
+ from repowise.cli.platform import settings
+
+ settings.set_enabled(True)
+ console.print("[green]✓[/green] Telemetry enabled. Thank you for helping improve Repowise.")
+
+
+@telemetry_group.command(name="disable")
+def telemetry_disable() -> None:
+ """Disable all usage telemetry."""
+ from repowise.cli.platform import settings
+
+ settings.set_enabled(False)
+ console.print("[green]✓[/green] Telemetry disabled. No usage data will be sent.")
+
+
+telemetry_command = telemetry_group
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index d5824216b..736095057 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import click
from repowise.cli import __version__
+from repowise.cli._instrumented_group import InstrumentedGroup
from repowise.cli.commands.augment_cmd import augment_command
from repowise.cli.commands.claude_md_cmd import claude_md_command
from repowise.cli.commands.corrections_cmd import corrections_command
@@ -27,6 +28,7 @@ from repowise.cli.commands.saved_cmd import saved_command
from repowise.cli.commands.search_cmd import search_command
from repowise.cli.commands.serve_cmd import serve_command
from repowise.cli.commands.status_cmd import status_command
+from repowise.cli.commands.telemetry_cmd import telemetry_command
from repowise.cli.commands.update_cmd import update_command
from repowise.cli.commands.watch_cmd import watch_command
from repowise.cli.commands.whats_new_cmd import whats_new_command
@@ -34,7 +36,7 @@ from repowise.cli.commands.workspace_cmd import workspace_group
from repowise.core.registry import cli_registry, register_command
[email protected](cls=InstrumentedGroup)
@click.version_option(version=__version__, prog_name="repowise")
@click.pass_context
def cli(ctx: click.Context) -> None:
@@ -82,6 +84,7 @@ register_command(reindex_command)
register_command(restyle_command)
register_command(wiki_styles_command)
register_command(whats_new_command)
+register_command(telemetry_command)
register_command(workspace_group)
cli_registry.apply(cli)
diff --git a/packages/cli/src/repowise/cli/platform/__init__.py b/packages/cli/src/repowise/cli/platform/__init__.py
new file mode 100644
index 000000000..8fe01b9c8
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/__init__.py
@@ -0,0 +1,25 @@
+"""Central connectivity layer between the OSS CLI and the Repowise hosted platform.
+
+All traffic to ``api.repowise.dev`` flows through here. Today the only consumer
+is anonymous, opt-out :mod:`telemetry`; this package is structured so future
+hosted features (login, account, cross-machine sync) add a client method and a
+sibling module rather than scattering ``httpx`` calls across the CLI.
+
+Layout:
+
+* :mod:`client` — :class:`PlatformClient`, the single HTTP seam (auth-ready).
+* :mod:`store` — ``~/.repowise/platform.json`` read/write.
+* :mod:`identity` — anonymous install id + per-process session id.
+* :mod:`settings` — telemetry consent + env-var precedence.
+* :mod:`telemetry` — the extendable event system.
+"""
+
+from __future__ import annotations
+
+from repowise.cli.platform.client import PLATFORM_BASE_URL, PlatformClient, default_client
+
+__all__ = [
+ "PLATFORM_BASE_URL",
+ "PlatformClient",
+ "default_client",
+]
diff --git a/packages/cli/src/repowise/cli/platform/client.py b/packages/cli/src/repowise/cli/platform/client.py
new file mode 100644
index 000000000..9f8144a26
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/client.py
@@ -0,0 +1,132 @@
+"""Central client for the Repowise hosted platform (``api.repowise.dev``).
+
+This is the single seam between the OSS CLI and the hosted product. Today its
+only consumer is anonymous telemetry; tomorrow it will carry authenticated
+calls (login, account, cross-machine sync). Keeping *all* hosted connectivity
+here means a new hosted feature adds a method, not another ad-hoc ``httpx``
+call scattered across the CLI.
+
+Design rules:
+
+* **Production URL only.** There is no localhost override in the OSS package.
+ Backend development points the private backend repo at a local server; the
+ shipped CLI always talks to ``https://api.repowise.dev``.
+* **Fail-silent.** The OSS CLI must work fully offline, so every method
+ swallows network/parse errors and returns a sentinel instead of raising.
+* **Auth-ready.** :meth:`PlatformClient._auth_headers` is the one place a future
+ bearer token gets attached, so every platform call becomes authenticated at
+ once when login lands.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+#: Production base URL for the hosted platform. Intentionally not configurable
+#: from the OSS package (see module docstring).
+PLATFORM_BASE_URL = "https://api.repowise.dev"
+
+#: Short default timeout — platform calls are best-effort and must never stall
+#: a CLI command waiting on the network.
+DEFAULT_TIMEOUT = 2.0
+
+
+def _user_agent() -> str:
+ try:
+ from repowise.cli import __version__
+
+ return f"repowise-cli/{__version__}"
+ except Exception:
+ return "repowise-cli"
+
+
+class PlatformClient:
+ """Best-effort HTTP client for the hosted platform.
+
+ All methods return a sentinel on failure rather than raising; callers in
+ the OSS CLI treat hosted connectivity as optional.
+ """
+
+ def __init__(
+ self,
+ base_url: str = PLATFORM_BASE_URL,
+ timeout: float = DEFAULT_TIMEOUT,
+ ) -> None:
+ self.base_url = base_url.rstrip("/")
+ self.timeout = timeout
+
+ # -- header assembly ---------------------------------------------------
+
+ def _auth_headers(self) -> dict[str, str]:
+ """Return auth headers for an authenticated platform call.
+
+ Empty today: the OSS CLI makes only anonymous calls. When the pip
+ package gains login this reads the stored bearer token from the
+ credential store, and every platform call is authenticated uniformly
+ without touching individual call sites.
+ """
+ return {}
+
+ def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
+ headers = {
+ "User-Agent": _user_agent(),
+ "Content-Type": "application/json",
+ }
+ headers.update(self._auth_headers())
+ if extra:
+ headers.update(extra)
+ return headers
+
+ # -- verbs -------------------------------------------------------------
+
+ def post(
+ self,
+ path: str,
+ payload: dict[str, Any],
+ *,
+ timeout: float | None = None,
+ ) -> bool:
+ """POST ``payload`` as JSON to ``path``. Returns success, never raises."""
+ url = f"{self.base_url}/{path.lstrip('/')}"
+ try:
+ import httpx
+
+ resp = httpx.post(
+ url,
+ json=payload,
+ headers=self._headers(),
+ timeout=timeout or self.timeout,
+ )
+ resp.raise_for_status()
+ return True
+ except Exception:
+ # Network, JSON, HTTP-status — all advisory. The CLI works offline.
+ return False
+
+ def get(
+ self,
+ path: str,
+ *,
+ params: dict[str, Any] | None = None,
+ timeout: float | None = None,
+ ) -> dict[str, Any] | None:
+ """GET ``path`` and return parsed JSON, or ``None`` on any failure."""
+ url = f"{self.base_url}/{path.lstrip('/')}"
+ try:
+ import httpx
+
+ resp = httpx.get(
+ url,
+ params=params,
+ headers=self._headers(),
+ timeout=timeout or self.timeout,
+ )
+ resp.raise_for_status()
+ return resp.json()
+ except Exception:
+ return None
+
+
+#: Process-wide default client. Callers that don't need a custom base URL or
+#: timeout share this instance.
+default_client = PlatformClient()
diff --git a/packages/cli/src/repowise/cli/platform/identity.py b/packages/cli/src/repowise/cli/platform/identity.py
new file mode 100644
index 000000000..bbcad0b2c
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/identity.py
@@ -0,0 +1,35 @@
+"""Anonymous install identity for the hosted platform.
+
+The anonymous id is a random UUIDv4 generated once and persisted in
+``~/.repowise/platform.json``. It exists only to count distinct installs and
+group a single install's events; it is **not** derived from any machine
+identifier (hostname, username, MAC), which keeps it impossible to reverse to a
+person. A per-process session id groups the commands of one CLI invocation.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+from repowise.cli.platform import store
+
+_ANON_ID_KEY = "anon_id"
+
+#: Generated once per process. Groups the events emitted by a single CLI run.
+_SESSION_ID = uuid.uuid4().hex
+
+
+def get_anonymous_id() -> str:
+ """Return the persistent anonymous install id, creating it on first use."""
+ state = store.load()
+ anon = state.get(_ANON_ID_KEY)
+ if isinstance(anon, str) and anon:
+ return anon
+ anon = uuid.uuid4().hex
+ store.update(**{_ANON_ID_KEY: anon})
+ return anon
+
+
+def get_session_id() -> str:
+ """Return this process's ephemeral session id."""
+ return _SESSION_ID
diff --git a/packages/cli/src/repowise/cli/platform/settings.py b/packages/cli/src/repowise/cli/platform/settings.py
new file mode 100644
index 000000000..070545bb0
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/settings.py
@@ -0,0 +1,82 @@
+"""Telemetry consent resolution and env-var precedence.
+
+Telemetry is **opt-out**: enabled by default, with a one-time loud notice and
+trivially easy disable. This module is the single source of truth for whether
+telemetry may be sent, resolving the stored consent against the environment.
+
+Precedence (highest first):
+
+1. ``DO_NOT_TRACK`` — the cross-tool `console do-not-track` standard. Any
+ truthy value is a hard off and also suppresses the first-run notice.
+2. ``REPOWISE_TELEMETRY_DISABLED`` — tool-specific hard off.
+3. Stored consent (``telemetry_enabled`` in ``platform.json``) when the user
+ has explicitly run ``repowise telemetry disable``/``enable``.
+4. Default: enabled.
+
+``REPOWISE_TELEMETRY_DEBUG`` does not change the enabled state — it makes the
+emitter print the exact payload to stderr instead of sending it, so anyone can
+verify what would leave their machine.
+"""
+
+from __future__ import annotations
+
+import os
+
+from repowise.cli.platform import store
+
+_ENABLED_KEY = "telemetry_enabled"
+_NOTICE_SHOWN_KEY = "telemetry_notice_shown"
+
+_TRUTHY = {"1", "true", "yes", "on"}
+
+
+def _env_truthy(name: str) -> bool:
+ return os.environ.get(name, "").strip().lower() in _TRUTHY
+
+
+def do_not_track() -> bool:
+ """Return whether the cross-tool ``DO_NOT_TRACK`` standard opts out."""
+ return _env_truthy("DO_NOT_TRACK")
+
+
+def debug_mode() -> bool:
+ """Return whether ``REPOWISE_TELEMETRY_DEBUG`` is set (print, don't send)."""
+ return _env_truthy("REPOWISE_TELEMETRY_DEBUG")
+
+
+def is_enabled() -> bool:
+ """Return whether telemetry may currently be sent."""
+ if do_not_track():
+ return False
+ if _env_truthy("REPOWISE_TELEMETRY_DISABLED"):
+ return False
+ # Opt-out default: enabled unless the user explicitly stored a disable.
+ stored = store.load().get(_ENABLED_KEY)
+ return stored is not False
+
+
+def set_enabled(enabled: bool) -> None:
+ """Persist an explicit enable/disable verdict from the user."""
+ store.update(**{_ENABLED_KEY: bool(enabled)})
+
+
+def notice_shown() -> bool:
+ return bool(store.load().get(_NOTICE_SHOWN_KEY))
+
+
+def mark_notice_shown() -> None:
+ store.update(**{_NOTICE_SHOWN_KEY: True})
+
+
+def disabled_reason() -> str | None:
+ """Return a short human reason telemetry is off, or ``None`` if on.
+
+ Used by ``repowise telemetry status`` to explain *why* it is disabled.
+ """
+ if do_not_track():
+ return "DO_NOT_TRACK is set"
+ if _env_truthy("REPOWISE_TELEMETRY_DISABLED"):
+ return "REPOWISE_TELEMETRY_DISABLED is set"
+ if store.load().get(_ENABLED_KEY) is False:
+ return "disabled via 'repowise telemetry disable'"
+ return None
diff --git a/packages/cli/src/repowise/cli/platform/store.py b/packages/cli/src/repowise/cli/platform/store.py
new file mode 100644
index 000000000..0d1c3bee2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/store.py
@@ -0,0 +1,46 @@
+"""Persistence for cross-machine platform state (``~/.repowise/platform.json``).
+
+A single user-global JSON file holds machine-wide, repo-independent platform
+state: the anonymous install id and the telemetry consent/notice flags today;
+account/login tokens later. Reads tolerate a missing or corrupt file (returning
+an empty dict); writes are best-effort and never raise into a CLI command.
+
+Distinct from a repo's local ``.repowise/state.json`` — this is per-user, not
+per-repo.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+from typing import Any
+
+PLATFORM_STATE_FILENAME = "platform.json"
+
+
+def _path():
+ from repowise.cli.helpers import user_global_dir
+
+ return user_global_dir() / PLATFORM_STATE_FILENAME
+
+
+def load() -> dict[str, Any]:
+ """Return the parsed platform state, or an empty dict if absent/corrupt."""
+ try:
+ return json.loads(_path().read_text(encoding="utf-8"))
+ except Exception:
+ return {}
+
+
+def save(state: dict[str, Any]) -> None:
+ """Persist *state*. Best-effort: any I/O error is swallowed."""
+ with contextlib.suppress(Exception):
+ _path().write_text(json.dumps(state, indent=2), encoding="utf-8")
+
+
+def update(**changes: Any) -> dict[str, Any]:
+ """Shallow-merge *changes* into the stored state and persist. Returns it."""
+ state = load()
+ state.update(changes)
+ save(state)
+ return state
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/__init__.py b/packages/cli/src/repowise/cli/platform/telemetry/__init__.py
new file mode 100644
index 000000000..f30a978b3
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/telemetry/__init__.py
@@ -0,0 +1,65 @@
+"""Anonymous, opt-out CLI telemetry.
+
+Public surface used by the rest of the CLI:
+
+* :func:`record_command_run` — central per-invocation event (called once from
+ the root command wrapper in ``main.py``).
+* :func:`maybe_show_notice` — the one-time opt-out notice.
+* :func:`record` — emit any :class:`TelemetryEvent` (extension point for
+ future, richer events).
+
+Everything is fail-silent and respects consent; see :mod:`..settings`.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.cli.platform.telemetry.consent import (
+ TELEMETRY_DOC_URL,
+ maybe_show_notice,
+ status_lines,
+)
+from repowise.cli.platform.telemetry.emitter import record
+from repowise.cli.platform.telemetry.events import (
+ CommandRunEvent,
+ TelemetryEvent,
+ register_event,
+ registered_events,
+)
+
+__all__ = [
+ "TELEMETRY_DOC_URL",
+ "CommandRunEvent",
+ "TelemetryEvent",
+ "maybe_show_notice",
+ "record",
+ "record_command_run",
+ "register_event",
+ "registered_events",
+ "status_lines",
+]
+
+
+def record_command_run(
+ command: str,
+ *,
+ subcommand: str | None = None,
+ flags: list[str] | None = None,
+ status: str = "ok",
+ error_type: str | None = None,
+ duration_ms: int = 0,
+ extra: dict[str, Any] | None = None,
+) -> None:
+ """Record a :class:`CommandRunEvent`. Convenience wrapper over :func:`record`."""
+ record(
+ CommandRunEvent(
+ command=command,
+ subcommand=subcommand,
+ flags=list(flags or []),
+ status=status,
+ error_type=error_type,
+ duration_ms=duration_ms,
+ extra=dict(extra or {}),
+ )
+ )
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/consent.py b/packages/cli/src/repowise/cli/platform/telemetry/consent.py
new file mode 100644
index 000000000..4ac68609e
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/telemetry/consent.py
@@ -0,0 +1,60 @@
+"""The one-time opt-out notice and the user-facing consent controls.
+
+Telemetry is opt-out, so the trust contract is a *loud, once* announcement: the
+first time any command runs after telemetry ships, we print a short notice to
+stderr explaining what is collected and how to turn it off, then never nag
+again. The notice is suppressed when telemetry is already off (incl.
+``DO_NOT_TRACK``), in CI, and when stderr is not a TTY (piped/redirected
+output), so it never corrupts machine-readable streams.
+"""
+
+from __future__ import annotations
+
+import sys
+
+from repowise.cli.platform import settings
+from repowise.cli.platform.telemetry import environment
+
+TELEMETRY_DOC_URL = "https://repowise.dev/telemetry"
+
+_NOTICE = (
+ "Repowise collects completely anonymous usage telemetry (commands run, "
+ "versions, OS, success/duration) to help prioritize what to build.\n"
+ "It never sees your code, file paths, or repo names. Opt out anytime with "
+ "'repowise telemetry disable' or DO_NOT_TRACK=1.\n"
+ f"Details: {TELEMETRY_DOC_URL}"
+)
+
+
+def maybe_show_notice() -> None:
+ """Print the one-time telemetry notice if it is due. Never raises."""
+ try:
+ if not settings.is_enabled():
+ return # already opted out — nothing to announce
+ if settings.notice_shown():
+ return
+ if environment.is_ci():
+ # Mark shown so an interactive run later doesn't re-announce, but
+ # don't spam CI logs.
+ settings.mark_notice_shown()
+ return
+ if not sys.stderr.isatty():
+ return # piped/redirected — don't corrupt the stream; try again later
+
+ print(f"\n{_NOTICE}\n", file=sys.stderr)
+ settings.mark_notice_shown()
+ except Exception:
+ return
+
+
+def status_lines() -> list[str]:
+ """Return human-readable status lines for ``repowise telemetry status``."""
+ enabled = settings.is_enabled()
+ lines = [f"Telemetry: {'enabled' if enabled else 'disabled'}"]
+ reason = settings.disabled_reason()
+ if reason:
+ lines.append(f" reason: {reason}")
+ if settings.debug_mode():
+ lines.append(" debug: REPOWISE_TELEMETRY_DEBUG set (payloads printed, not sent)")
+ lines.append(f" details: {TELEMETRY_DOC_URL}")
+ return lines
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/emitter.py b/packages/cli/src/repowise/cli/platform/telemetry/emitter.py
new file mode 100644
index 000000000..a73b02fef
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/telemetry/emitter.py
@@ -0,0 +1,97 @@
+"""Build the wire envelope for an event and send it, best-effort.
+
+Sending is fire-and-forget on a daemon thread so a slow or unreachable backend
+never delays a CLI command. An ``atexit`` flush briefly joins in-flight sends
+so short-lived invocations still deliver. Everything here is fail-silent: a
+telemetry failure must never surface to the user.
+"""
+
+from __future__ import annotations
+
+import atexit
+import contextlib
+import json
+import sys
+import threading
+
+from repowise.cli.platform import identity, settings
+from repowise.cli.platform.client import default_client
+from repowise.cli.platform.telemetry import environment
+from repowise.cli.platform.telemetry.events import TelemetryEvent
+
+#: Backend ingestion path (joined to the platform base URL by the client).
+_INGEST_PATH = "telemetry/events"
+
+#: In-flight send threads, joined briefly at exit so quick commands deliver.
+_pending: list[threading.Thread] = []
+
+
+def _cli_version() -> str:
+ try:
+ from repowise.cli import __version__
+
+ return __version__
+ except Exception:
+ return "unknown"
+
+
+def build_envelope(event: TelemetryEvent) -> dict[str, object]:
+ """Assemble the anonymous wire envelope for *event*."""
+ envelope: dict[str, object] = {
+ "event": event.name,
+ "anon_id": identity.get_anonymous_id(),
+ "session_id": identity.get_session_id(),
+ "cli_version": _cli_version(),
+ "properties": event.properties(),
+ }
+ envelope.update(environment.base_facts())
+ return envelope
+
+
+def record(event: TelemetryEvent) -> None:
+ """Record *event*: respect consent, then debug-print or send. Never raises."""
+ try:
+ if not settings.is_enabled():
+ return
+ envelope = build_envelope(event)
+
+ if settings.debug_mode():
+ # Verifiability: show exactly what would be sent, send nothing.
+ print(
+ "[repowise telemetry] would send:\n" + json.dumps(envelope, indent=2),
+ file=sys.stderr,
+ )
+ return
+
+ thread = threading.Thread(
+ target=default_client.post,
+ args=(_INGEST_PATH, envelope),
+ daemon=True,
+ )
+ thread.start()
+ # Prune finished sends so a long-lived process (e.g. ``serve``/``watch``)
+ # emitting many events never accumulates dead Thread objects.
+ _pending[:] = [t for t in _pending if t.is_alive()]
+ _pending.append(thread)
+ except Exception:
+ # Telemetry must never break a command.
+ return
+
+
+def _flush() -> None:
+ """Give in-flight sends a brief moment to complete on process exit.
+
+ Bounded to ~2s total across all pending sends so exit is never noticeably
+ delayed even if the backend is hung.
+ """
+ import time
+
+ remaining = 2.0
+ for thread in _pending:
+ if remaining <= 0:
+ break
+ start = time.monotonic()
+ with contextlib.suppress(Exception):
+ thread.join(timeout=remaining)
+ remaining -= time.monotonic() - start
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/environment.py b/packages/cli/src/repowise/cli/platform/telemetry/environment.py
new file mode 100644
index 000000000..18f89725f
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/telemetry/environment.py
@@ -0,0 +1,55 @@
+"""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).
+"""
+
+from __future__ import annotations
+
+import os
+import platform
+
+# Common CI signals across providers. ``CI`` covers GitHub Actions, GitLab,
+# CircleCI, Travis; the rest catch platforms that don't set a generic ``CI``.
+_CI_ENV_VARS = (
+ "CI",
+ "GITHUB_ACTIONS",
+ "GITLAB_CI",
+ "BUILDKITE",
+ "JENKINS_URL",
+ "TEAMCITY_VERSION",
+ "TF_BUILD",
+)
+
+
+def os_family() -> str:
+ """Return a coarse OS family: ``darwin`` / ``linux`` / ``windows``."""
+ return platform.system().lower() or "unknown"
+
+
+def arch() -> str:
+ """Return the CPU architecture (e.g. ``arm64``, ``x86_64``)."""
+ return platform.machine().lower() or "unknown"
+
+
+def python_version() -> str:
+ """Return only ``major.minor`` (e.g. ``3.12``) — never the patch level."""
+ info = platform.python_version_tuple()
+ return f"{info[0]}.{info[1]}"
+
+
+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)
+
+
+def base_facts() -> dict[str, object]:
+ """Return the environment facts common to every telemetry envelope."""
+ return {
+ "os": os_family(),
+ "arch": arch(),
+ "python_version": python_version(),
+ "is_ci": is_ci(),
+ }
diff --git a/packages/cli/src/repowise/cli/platform/telemetry/events.py b/packages/cli/src/repowise/cli/platform/telemetry/events.py
new file mode 100644
index 000000000..4da9ed520
--- /dev/null
+++ b/packages/cli/src/repowise/cli/platform/telemetry/events.py
@@ -0,0 +1,81 @@
+"""Telemetry event types and the registry that makes them extendable.
+
+A telemetry event is a small, declarative object: a stable ``name`` plus a
+``properties()`` dict of anonymous, non-identifying fields. To collect a new
+kind of data later, add a subclass and decorate it with :func:`register_event`
+— the emitter serializes any :class:`TelemetryEvent` uniformly, so no other
+code changes.
+
+Privacy contract for every event (enforced by convention + code review): never
+put source code, file paths, repo/symbol names, flag *values*, env-var values,
+error messages, stack traces, or anything user-identifiable into
+``properties()``. Flag *names* and class names of exceptions are allowed.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, ClassVar
+
+#: name -> event class. Lets the (future) server validate names and lets new
+#: event types self-register without edits elsewhere.
+_REGISTRY: dict[str, type[TelemetryEvent]] = {}
+
+
+def register_event(cls: type[TelemetryEvent]) -> type[TelemetryEvent]:
+ """Class decorator: register an event type under its ``name``."""
+ _REGISTRY[cls.name] = cls
+ return cls
+
+
+def registered_events() -> dict[str, type[TelemetryEvent]]:
+ """Return a copy of the event registry (name -> class)."""
+ return dict(_REGISTRY)
+
+
+class TelemetryEvent:
+ """Base class for all telemetry events.
+
+ Subclasses set the class-level :attr:`name` and implement
+ :meth:`properties`. Keep ``properties`` anonymous (see module docstring).
+ """
+
+ name: ClassVar[str] = "event"
+
+ def properties(self) -> dict[str, Any]:
+ raise NotImplementedError
+
+
+@register_event
+@dataclass
+class CommandRunEvent(TelemetryEvent):
+ """Emitted once per CLI invocation from the central command wrapper.
+
+ Captures *what* ran and *how it went* — never *on what*. ``flags`` holds
+ option names only (``--resume``), never their values.
+ """
+
+ name: ClassVar[str] = "command_run"
+
+ command: str
+ subcommand: str | None = None
+ flags: list[str] = field(default_factory=list)
+ status: str = "ok" # "ok" | "error"
+ error_type: str | None = None # exception class name only, no message
+ duration_ms: int = 0
+ # Open extension point for command-specific anonymous fields (bucketed
+ # counts, coarse enums). Callers must keep these non-identifying.
+ extra: dict[str, Any] = field(default_factory=dict)
+
+ def properties(self) -> dict[str, Any]:
+ props: dict[str, Any] = {
+ "command": self.command,
+ "subcommand": self.subcommand,
+ "flags": self.flags,
+ "status": self.status,
+ "error_type": self.error_type,
+ "duration_ms": self.duration_ms,
+ }
+ if self.extra:
+ props.update(self.extra)
+ return props
diff --git a/tests/unit/cli/test_telemetry.py b/tests/unit/cli/test_telemetry.py
new file mode 100644
index 000000000..5faeb520f
--- /dev/null
+++ b/tests/unit/cli/test_telemetry.py
@@ -0,0 +1,200 @@
+"""Tests for anonymous, opt-out CLI telemetry (the ``platform`` layer).
+
+Covers the three things that protect user trust: consent precedence (env vars
+beat stored state, opt-out default), the privacy shape of the wire envelope
+(only anonymous fields, flag names not values, no patch-version leak), and the
+central command wrapper recording exactly one event without breaking commands.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.platform import identity, settings, store
+from repowise.cli.platform.telemetry import emitter
+from repowise.cli.platform.telemetry.events import CommandRunEvent
+
+
[email protected](autouse=True)
+def isolated_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Point platform.json at a temp dir so tests never touch real ~/.repowise."""
+ monkeypatch.setattr(store, "_path", lambda: tmp_path / "platform.json")
+ # Clear any inherited telemetry env so each test controls precedence.
+ for var in ("DO_NOT_TRACK", "REPOWISE_TELEMETRY_DISABLED", "REPOWISE_TELEMETRY_DEBUG"):
+ monkeypatch.delenv(var, raising=False)
+ # Isolate the module-global pending-send list between tests.
+ emitter._pending.clear()
+ yield
+ emitter._pending.clear()
+
+
+class TestConsentPrecedence:
+ def test_opt_out_default_enabled(self):
+ assert settings.is_enabled() is True
+ assert settings.disabled_reason() is None
+
+ def test_do_not_track_wins(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("DO_NOT_TRACK", "1")
+ assert settings.is_enabled() is False
+ assert settings.disabled_reason() == "DO_NOT_TRACK is set"
+
+ def test_tool_specific_env_disables(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("REPOWISE_TELEMETRY_DISABLED", "true")
+ assert settings.is_enabled() is False
+
+ def test_stored_disable_then_enable(self):
+ settings.set_enabled(False)
+ assert settings.is_enabled() is False
+ assert "disable" in (settings.disabled_reason() or "")
+ settings.set_enabled(True)
+ assert settings.is_enabled() is True
+
+ def test_env_beats_stored_enable(self, monkeypatch: pytest.MonkeyPatch):
+ settings.set_enabled(True)
+ monkeypatch.setenv("DO_NOT_TRACK", "1")
+ assert settings.is_enabled() is False
+
+
+class TestIdentity:
+ def test_anon_id_stable_and_opaque(self):
+ first = identity.get_anonymous_id()
+ assert isinstance(first, str) and len(first) >= 16
+ assert identity.get_anonymous_id() == first # persisted, stable
+
+ def test_anon_id_not_derived_from_machine(self):
+ # Two fresh stores must yield different ids — proof it is random, not a
+ # hash of stable machine identifiers.
+ store.update(anon_id="") # reset
+ a = identity.get_anonymous_id()
+ store.save({}) # wipe
+ b = identity.get_anonymous_id()
+ assert a != b
+
+
+class TestEnvelopePrivacy:
+ def test_envelope_shape(self):
+ ev = CommandRunEvent(
+ command="init",
+ subcommand=None,
+ flags=["--resume", "--provider"],
+ status="ok",
+ duration_ms=1234,
+ )
+ env = emitter.build_envelope(ev)
+ assert env["event"] == "command_run"
+ assert {
+ "anon_id",
+ "session_id",
+ "cli_version",
+ "os",
+ "arch",
+ "python_version",
+ "is_ci",
+ "properties",
+ } <= set(env)
+
+ def test_no_patch_version_leak(self):
+ env = emitter.build_envelope(CommandRunEvent(command="status"))
+ assert env["python_version"].count(".") == 1 # major.minor only
+
+ def test_flags_carry_no_values(self):
+ env = emitter.build_envelope(
+ CommandRunEvent(command="update", flags=["--provider", "--exclude"])
+ )
+ for flag in env["properties"]["flags"]:
+ assert flag.startswith("--")
+ assert "=" not in flag
+
+
+class TestFlagNormalization:
+ """`_option_name` must never let an option value reach an event."""
+
+ def test_long_value_stripped(self):
+ from repowise.cli._instrumented_group import _option_name
+
+ assert _option_name("--provider=openai") == "--provider"
+ assert _option_name("--no-cost-tracking") == "--no-cost-tracking"
+
+ def test_attached_short_value_stripped(self):
+ from repowise.cli._instrumented_group import _option_name
+
+ # The PII leak the review caught: attached short-option values.
+ assert _option_name("-p/home/me/secret-project") == "-p"
+ assert _option_name("-x*internal_codename*") == "-x"
+ assert _option_name("-o/abs/output/path") == "-o"
+
+ def test_plain_short_and_combined(self):
+ from repowise.cli._instrumented_group import _option_name
+
+ assert _option_name("-v") == "-v"
+ assert _option_name("-vv") == "-v"
+
+ def test_extra_extension_point(self):
+ env = emitter.build_envelope(
+ CommandRunEvent(command="init", extra={"file_count_bucket": "500-1k"})
+ )
+ assert env["properties"]["file_count_bucket"] == "500-1k"
+
+
+class TestEmitterRespectsConsent:
+ def test_disabled_sends_nothing(self, monkeypatch: pytest.MonkeyPatch):
+ sent: list = []
+ monkeypatch.setattr(emitter.default_client, "post", lambda *a, **k: sent.append(a) or True)
+ monkeypatch.setenv("DO_NOT_TRACK", "1")
+ emitter.record(CommandRunEvent(command="health"))
+ emitter._flush()
+ assert sent == []
+
+ def test_debug_prints_does_not_send(
+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
+ ):
+ sent: list = []
+ monkeypatch.setattr(emitter.default_client, "post", lambda *a, **k: sent.append(a) or True)
+ monkeypatch.setenv("REPOWISE_TELEMETRY_DEBUG", "1")
+ emitter.record(CommandRunEvent(command="health"))
+ captured = capsys.readouterr()
+ assert "would send" in captured.err
+ assert sent == []
+
+
+class TestCommandWrapper:
+ def test_status_command_records_one_event(self, monkeypatch: pytest.MonkeyPatch):
+ from repowise.cli.main import cli
+
+ recorded: list[dict] = []
+
+ def fake_post(path, payload, **kwargs):
+ recorded.append(payload)
+ return True
+
+ monkeypatch.setattr(emitter.default_client, "post", fake_post)
+ # Force synchronous delivery so we can assert without races.
+ monkeypatch.setattr(
+ emitter.threading,
+ "Thread",
+ lambda target, args, daemon: type(
+ "T", (), {"start": lambda s: target(*args), "join": lambda s, timeout=None: None}
+ )(),
+ )
+
+ res = CliRunner().invoke(cli, ["telemetry", "status"])
+ assert res.exit_code == 0
+ assert len(recorded) == 1
+ assert recorded[0]["event"] == "command_run"
+ assert recorded[0]["properties"]["command"] == "telemetry"
+ assert recorded[0]["properties"]["subcommand"] == "status"
+ assert recorded[0]["properties"]["status"] == "ok"
+
+ def test_help_records_nothing(self, monkeypatch: pytest.MonkeyPatch):
+ from repowise.cli.main import cli
+
+ recorded: list = []
+ monkeypatch.setattr(
+ emitter.default_client, "post", lambda *a, **k: recorded.append(a) or True
+ )
+ res = CliRunner().invoke(cli, ["--help"])
+ assert res.exit_code == 0
+ assert recorded == []