:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogli): trustworthy telemetry dimensions and eager started flush (#63096)
Raúl Negrón-Oteroa0a9365db3f3
diff --git a/hogli.yaml b/hogli.yamlindex a19c05dd7275..5942690bb901 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -159,15 +159,21 @@ devbox:devbox:ssh:click: hogli_commands.devbox.cli:devbox_sshdescription: SSH into your devbox+ # exec-replaces the process (os.execvp): completed events can't fire+ untracked: truedevbox:exec:click: hogli_commands.devbox.cli:devbox_remote_execdescription: Run a command inside your devbox (non-interactive)+ untracked: truedevbox:open:click: hogli_commands.devbox.cli:devbox_opendescription: Open devbox in browser, VS Code, or Cursor+ untracked: truedevbox:logs:click: hogli_commands.devbox.cli:devbox_logsdescription: Tail devbox build and agent logs+ # exec-replaces the process (os.execvp): completed events can't fire+ untracked: truedevbox:destroy:click: hogli_commands.devbox.cli:devbox_destroydescription: Destroy your devbox and its data@@ -177,6 +183,8 @@ devbox:devbox:forward:click: hogli_commands.devbox.cli:devbox_forwarddescription: Forward PostHog UI to localhost+ # exec-replaces the process (os.execvp): completed events can't fire+ untracked: truedevbox:users:click: hogli_commands.devbox.cli:devbox_usersdescription: List Coder users (for devbox sharing)@@ -195,6 +203,8 @@ devbox:devbox:task:click: hogli_commands.devbox.cli:devbox_taskdescription: Run a background agent task on a fresh devbox+ # exec-replaces the process (os.execvp): completed events can't fire+ untracked: truedevbox:secret:list:click: hogli_commands.devbox.cli:devbox_secret_listdescription: List your Coder user secrets@@ -790,13 +800,13 @@ auth:metabase:cookie:click: hogli_commands.metabase:metabase_cookiedescription: Print the cached Metabase cookie header+tools:metabase:databases:click: hogli_commands.metabase:metabase_databasesdescription: List Metabase databases (id, name, engine) for a regionmetabase:query:click: hogli_commands.metabase:metabase_querydescription: Run a SQL query against Metabase /api/dataset; results to stdout-tools:doctor:click: hogli_commands.doctor:doctordescription: Quick health check for your dev environment@@ -986,15 +996,6 @@ environment:setup:python:cmd: uv sync --activedescription: Install Python dependencies to active virtual environment- telemetry:on:- click: hogli_commands.telemetry_commands:telemetry_on- description: Enable anonymous usage telemetry- telemetry:off:- click: hogli_commands.telemetry_commands:telemetry_off- description: Disable anonymous usage telemetry- telemetry:status:- click: hogli_commands.telemetry_commands:telemetry_status- description: Show current telemetry settingssandbox:bin_script: sandboxdescription: Manage isolated dev sandboxesdiff --git a/tools/hogli-commands/README.md b/tools/hogli-commands/README.mdindex f262624c2430..e1251854e92b 100644--- a/tools/hogli-commands/README.md+++ b/tools/hogli-commands/README.md@@ -50,7 +50,7 @@ That's it. No side-effect imports, no central registration list to maintain.`config.boot_modules` in `hogli.yaml` lists modules imported once at startup. They register hooks via `hogli.hooks`:- `hogli_commands.prechecks` — declares the `migrations` precheck (used by `dev:start`).-- `hogli_commands.telemetry_props` — adds PostHog environment props (`in_flox`, `is_worktree`, `is_posthog_dev`, `process_manager`, `has_devenv_config`) to every `command_completed` event.+- `hogli_commands.telemetry_props` — adds PostHog environment props (`environment`, `agent`, `is_agent`, `in_flox`, `is_worktree`, `is_posthog_dev`, `process_manager`, `has_devenv_config`, `repo_sha`, `repo_commit_date`) to every `command_started` / `command_completed` event.- `hogli_commands.hint_hook` — shows a contextual hint after successful commands.Add a new boot module by creating a file that calls one of the `register_*` helpers from `hogli.hooks` at import time, then list it under `config.boot_modules:`. Keep these modules import-light: the precheck handler in `prechecks.py` is the canonical example of deferring its heavy import until the handler actually fires.diff --git a/tools/hogli-commands/hogli_commands/telemetry_commands.py b/tools/hogli-commands/hogli_commands/telemetry_commands.pydeleted file mode 100644index 49a9e04f1ba0..000000000000--- a/tools/hogli-commands/hogli_commands/telemetry_commands.py+++ /dev/null@@ -1,44 +0,0 @@-"""CLI commands for managing hogli telemetry settings."""--from __future__ import annotations--import os--import click-from hogli import telemetry--[email protected](name="telemetry:on", help="Enable anonymous usage telemetry")-def telemetry_on() -> None:- telemetry.set_enabled(True)- click.echo("Telemetry enabled. Thank you for helping improve hogli!")--[email protected](name="telemetry:off", help="Disable anonymous usage telemetry")-def telemetry_off() -> None:- telemetry.set_enabled(False)- click.echo("Telemetry disabled.")--[email protected](name="telemetry:status", help="Show current telemetry settings")-def telemetry_status() -> None:- enabled = telemetry.is_enabled()- config_path = telemetry.get_config_path()-- click.echo(f"Telemetry: {'enabled' if enabled else 'disabled'}")-- # Show which mechanism controls the state- if telemetry.is_ci():- click.echo("Controlled by: CI environment detected")- elif os.environ.get("POSTHOG_TELEMETRY_OPT_OUT") == "1":- click.echo("Controlled by: POSTHOG_TELEMETRY_OPT_OUT=1")- elif os.environ.get("DO_NOT_TRACK") == "1":- click.echo("Controlled by: DO_NOT_TRACK=1")- else:- click.echo("Controlled by: config file")-- if enabled:- click.echo(f"Anonymous ID: {telemetry.get_anonymous_id()}")- else:- click.echo("Anonymous ID: (not generated -- telemetry disabled)")- click.echo(f"Config path: {config_path}")diff --git a/tools/hogli-commands/hogli_commands/telemetry_props.py b/tools/hogli-commands/hogli_commands/telemetry_props.pyindex 3d02b3f0a7d4..715129d48ab0 100644--- a/tools/hogli-commands/hogli_commands/telemetry_props.py+++ b/tools/hogli-commands/hogli_commands/telemetry_props.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport osimport sysimport time+import functoolsimport subprocessimport configparserfrom pathlib import Path@@ -18,11 +19,100 @@ from typing import Anyfrom hogli.hooks import register_telemetry_propertiesfrom hogli.manifest import REPO_ROOT-from hogli.telemetry import _load_config, _save_config+from hogli.telemetry import _load_config, _save_config, is_ci_POSTHOG_DEV_CACHE_TTL_SECONDS = 30 * 86400 # 30 days+# Created by hogland's guest overlay (hog-env-materialise) on every hogbox+# boot; the guest exposes no ambient env var, so this path is the marker.+# Prefer baking HOGLI_ENVIRONMENT=hogland into the guest image -- this is the+# fallback until that ships.+_HOGLAND_MARKER = Path("/var/lib/hog")++# Coder sets these inside every workspace, which is what our devboxes run on.+_DEVBOX_ENV_MARKERS = ("CODER", "CODER_WORKSPACE_NAME")++# Ambient markers set by agent harnesses in the shells they spawn. Ordered+# most-specific first: posthog-code drives claude/codex under the hood, so its+# marker must win over theirs. Harnesses without an ambient marker (e.g.+# non-sandboxed codex) can self-declare via HOGLI_AGENT instead.+_AGENT_ENV_MARKERS = (+ ("POSTHOG_CODE_VERSION", "posthog-code"),+ ("CLAUDECODE", "claude-code"),+ ("CODEX_SANDBOX", "codex"),+)+++def _declared(var: str) -> str:+ """Self-declared label from *var*, normalized so a sloppy export ('Sandbox ')+ can't fragment the telemetry dimension."""+ return os.environ.get(var, "").strip().lower()[:64]+++def _detect_environment() -> str:+ """Classify where hogli is running: ci, devbox, hogland, local, or a self-declared value.++ Environments without an ambient marker (e.g. agent sandboxes) should export+ ``HOGLI_ENVIRONMENT`` in their bootstrap to self-declare.+ """+ declared = _declared("HOGLI_ENVIRONMENT")+ if declared:+ return declared+ # Unreachable while the CI gate disables telemetry entirely; kept so the+ # label can never diverge from the gate (same rationale as the is_ci prop).+ if is_ci():+ return "ci"+ # Checked before the hogland marker so Coder-on-hogland reads as a devbox.+ if any(os.environ.get(var) for var in _DEVBOX_ENV_MARKERS):+ return "devbox"+ if _HOGLAND_MARKER.exists():+ return "hogland"+ return "local"+++def _detect_agent() -> str | None:+ """Name of the agent harness driving this invocation, or None for a human."""+ declared = _declared("HOGLI_AGENT")+ if declared:+ return declared+ for var, agent in _AGENT_ENV_MARKERS:+ if os.environ.get(var):+ return agent+ return None+++def _repo_commit() -> tuple[str, str] | None:+ """Short SHA and committer date of HEAD, identifying the checkout's vintage.++ --no-show-signature keeps gpg verification lines (log.showSignature=true)+ out of stdout, which would otherwise corrupt the parse.+ """+ try:+ result = subprocess.run(+ ["git", "-C", str(REPO_ROOT), "log", "-1", "--no-show-signature", "--format=%h %cI"],+ capture_output=True,+ text=True,+ timeout=2,+ )+ if result.returncode != 0:+ return None+ sha, _, commit_date = result.stdout.strip().partition(" ")+ if not sha or not commit_date:+ return None+ return sha, commit_date+ except Exception:+ return None+++def _repo_commit_properties() -> dict[str, str]:+ commit = _repo_commit()+ if commit is None:+ return {}+ return {"repo_sha": commit[0], "repo_commit_date": commit[1]}++def _infer_process_manager(command: str | None) -> str | None:pm = os.environ.get("HOGLI_PROCESS_MANAGER")if pm:@@ -80,12 +170,19 @@ def _is_posthog_dev() -> bool:def _posthog_telemetry_properties(command: str | None = None) -> dict[str, Any]:+ # Agent-driven traffic (e.g. skills running metabase:query) otherwise+ # swamps human usage stats.+ agent = _detect_agent()return {+ "agent": agent,+ "environment": _detect_environment(),"has_devenv_config": (REPO_ROOT / ".posthog" / ".generated" / "mprocs.yaml").exists(),"in_flox": os.environ.get("FLOX_ENV") is not None,+ "is_agent": agent is not None,"is_worktree": (REPO_ROOT / ".git").is_file(),"is_posthog_dev": _is_posthog_dev(),"process_manager": _infer_process_manager(command),+ **_repo_commit_properties(),}diff --git a/tools/hogli-commands/hogli_commands/tests/test_commands.py b/tools/hogli-commands/hogli_commands/tests/test_commands.pyindex 0c2303ebc50c..47007a5473c8 100644--- a/tools/hogli-commands/hogli_commands/tests/test_commands.py+++ b/tools/hogli-commands/hogli_commands/tests/test_commands.py@@ -8,7 +8,16 @@ import timeimport pytestfrom unittest.mock import patch-from hogli_commands.telemetry_props import _infer_process_manager, _is_posthog_dev+from hogli_commands.telemetry_props import (+ _AGENT_ENV_MARKERS,+ _DEVBOX_ENV_MARKERS,+ _detect_agent,+ _detect_environment,+ _infer_process_manager,+ _is_posthog_dev,+ _repo_commit,+ _repo_commit_properties,+)class TestProcessManagerInference:@@ -31,6 +40,107 @@ class TestProcessManagerInference:assert _infer_process_manager("start") == expected+class TestDetectEnvironment:+ @pytest.fixture(autouse=True)+ def _neutral_environment(self, monkeypatch, tmp_path):+ # is_ci is the seam the code consults -- mock it instead of coupling+ # to the framework's internal list of CI env vars.+ monkeypatch.setattr("hogli_commands.telemetry_props.is_ci", lambda: False)+ monkeypatch.setattr("hogli_commands.telemetry_props._HOGLAND_MARKER", tmp_path / "absent")+ for var in ("HOGLI_ENVIRONMENT", *_DEVBOX_ENV_MARKERS):+ monkeypatch.delenv(var, raising=False)++ @pytest.mark.parametrize(+ ("env_vars", "ci", "hogland", "expected"),+ [+ ({}, False, False, "local"),+ ({}, True, False, "ci"),+ ({"CODER": "true"}, False, False, "devbox"),+ ({"CODER_WORKSPACE_NAME": "raul-devbox"}, False, False, "devbox"),+ ({}, False, True, "hogland"),+ ({"CODER": "true"}, False, True, "devbox"),+ ({"HOGLI_ENVIRONMENT": "sandbox"}, False, False, "sandbox"),+ ({"HOGLI_ENVIRONMENT": " Sandbox "}, False, False, "sandbox"),+ ({"HOGLI_ENVIRONMENT": "sandbox"}, True, False, "sandbox"),+ ({"CODER": "true"}, True, False, "ci"),+ ],+ ids=[+ "local",+ "ci",+ "coder",+ "coder_workspace",+ "hogland",+ "devbox_beats_hogland",+ "declared",+ "declared_normalized",+ "declared_beats_ci",+ "ci_beats_devbox",+ ],+ )+ def test_classification(self, monkeypatch, tmp_path, env_vars, ci, hogland, expected) -> None:+ if ci:+ monkeypatch.setattr("hogli_commands.telemetry_props.is_ci", lambda: True)+ if hogland:+ monkeypatch.setattr("hogli_commands.telemetry_props._HOGLAND_MARKER", tmp_path)+ for key, value in env_vars.items():+ monkeypatch.setenv(key, value)+ assert _detect_environment() == expected+++class TestDetectAgent:+ @pytest.fixture(autouse=True)+ def _no_ambient_agent(self, monkeypatch):+ monkeypatch.delenv("HOGLI_AGENT", raising=False)+ for var, _ in _AGENT_ENV_MARKERS:+ monkeypatch.delenv(var, raising=False)++ @pytest.mark.parametrize(+ ("env_vars", "expected"),+ [+ ({}, None),+ ({"CLAUDECODE": "1"}, "claude-code"),+ ({"CODEX_SANDBOX": "seatbelt"}, "codex"),+ ({"POSTHOG_CODE_VERSION": "1.2.3"}, "posthog-code"),+ ({"POSTHOG_CODE_VERSION": "1.2.3", "CLAUDECODE": "1"}, "posthog-code"),+ ({"HOGLI_AGENT": " Goose "}, "goose"),+ ({"HOGLI_AGENT": "goose", "CLAUDECODE": "1"}, "goose"),+ ],+ ids=[+ "human",+ "claude_code",+ "codex",+ "posthog_code",+ "posthog_code_beats_claude",+ "declared_normalized",+ "declared_beats_sniffed",+ ],+ )+ def test_detection(self, monkeypatch, env_vars, expected) -> None:+ for key, value in env_vars.items():+ monkeypatch.setenv(key, value)+ assert _detect_agent() == expected+++class TestRepoCommitProperties:+ @pytest.fixture(autouse=True)+ def _fresh_cache(self):+ _repo_commit.cache_clear()+ yield+ _repo_commit.cache_clear()++ def test_returns_sha_and_date_in_a_git_checkout(self) -> None:+ props = _repo_commit_properties()+ assert set(props) == {"repo_sha", "repo_commit_date"}+ # %h honors core.abbrev, which git permits down to 4+ assert len(props["repo_sha"]) >= 4+ assert props["repo_commit_date"][:2] == "20" # ISO date++ def test_returns_empty_when_git_fails(self) -> None:+ with patch("hogli_commands.telemetry_props.subprocess.run") as mock_run:+ mock_run.return_value.returncode = 128+ assert _repo_commit_properties() == {}++class TestIsPosthogDev:@pytest.fixture()def _config_dir(self, tmp_path, monkeypatch):diff --git a/tools/hogli/AGENTS.md b/tools/hogli/AGENTS.mdindex 39bc5632d766..6df51666f94a 100644--- a/tools/hogli/AGENTS.md+++ b/tools/hogli/AGENTS.md@@ -85,3 +85,13 @@ Anti-patterns flagged during PR review (don't re-introduce):## When in doubtIf you're about to add code to `tools/hogli/` and you're not sure whether it's generic enough: it probably isn't. Ask first, or write it in `tools/hogli-commands/` and we can promote it later if multiple consumers want it.++## HOGLI\_\* environment variable namespace++Core and consumers share the `HOGLI_` env prefix; check both lists before minting a new name.++Core-reserved (defined in `tools/hogli/src/hogli/`): `HOGLI_DEBUG`, `HOGLI_MANIFEST`, `HOGLI_SECRETS_WRAPPED`, `HOGLI_NESTED_INVOCATION`.++Consumer-owned (defined in `tools/hogli-commands/`): `HOGLI_ENVIRONMENT`, `HOGLI_AGENT`, `HOGLI_PROCESS_MANAGER` (telemetry self-declaration), `HOGLI_NO_HINTS`, `HOGLI_MPROCS_PATH`, `HOGLI_DEVBOX_CODER_URL`, `HOGLI_DEVBOX_CODER_VERSION`.++If core needs a name a consumer already uses (or vice versa), rename rather than overload — bootstraps in other repos export these and silently changing semantics breaks them.diff --git a/tools/hogli/README.md b/tools/hogli/README.mdindex 20f939ab1dfc..ce2d97fb79fd 100644--- a/tools/hogli/README.md+++ b/tools/hogli/README.md@@ -112,6 +112,7 @@ my:command:destructive: true # Prompts for confirmation before runninghidden: true # Hides from --help (still runnable)needs_secrets: true # Triggers the configured `env.secrets.wrap` (see below)+ untracked: true # Skips command_started/command_completed telemetry (use for exec-style commands that replace the process, so a completed event could never fire)```## Python Commands@@ -227,7 +228,7 @@ dev:start:### Telemetry properties-Inject extra key/value pairs into the `command_completed` telemetry event. Receives the invoked command name.+Inject extra key/value pairs into the `command_started` / `command_completed` telemetry events. Receives the invoked command name.```pythonfrom hogli.hooks import register_telemetry_propertiesdiff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.pyindex 2a4ce1e219f1..0fe1c7aa74b9 100644--- a/tools/hogli/src/hogli/cli.py+++ b/tools/hogli/src/hogli/cli.py@@ -11,7 +11,9 @@ import sysimport time as _timeimport shutilimport platform+import functoolsimport importlib+import importlib.metadatafrom collections import defaultdictfrom pathlib import Pathfrom typing import Any@@ -34,6 +36,15 @@ from hogli.validate import auto_update_manifest, find_missing_manifest_entries,_DEFAULT_HELP = "Developer CLI framework with YAML-based command definitions."+# Sentinel inherited by subprocesses so nested hogli invocations (composite+# steps, prechecks, process managers re-running hogli) can be told apart in+# telemetry. is_nested means "descends from a hogli process tree" -- a human+# typing hogli inside a shell that hogli spawned (flox:activate, sandbox)+# counts as nested too. Captured at import, before this process sets the+# sentinel for its own children.+_NESTED_INVOCATION_VAR = "HOGLI_NESTED_INVOCATION"+_IS_NESTED = _NESTED_INVOCATION_VAR in os.environ+class CategorizedGroup(click.Group):"""Custom Click group that formats help output like git help with categories.@@ -80,7 +91,10 @@ class CategorizedGroup(click.Group):raisefinally:_fire_telemetry(ctx, exit_code)- telemetry.flush()+ try:+ telemetry.flush()+ except Exception:+ pass_fire_post_command_hooks(ctx.invoked_subcommand, exit_code)def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:@@ -179,8 +193,9 @@ def _auto_update_manifest() -> None:@click.pass_contextdef cli(ctx: click.Context) -> None:"""hogli - YAML-driven developer CLI."""- # Skip env loading during shell completion — completion fires this- # callback for every Tab press and doesn't need the env populated.+ # Defensive: skip env loading in resilient-parsing (completion) contexts.+ # click builds those contexts without invoking callbacks, so this guard is+ # belt-and-braces, not load-bearing.if not ctx.resilient_parsing:_apply_env_config(ctx.invoked_subcommand)# Auto-update manifest on every invocation (but skip for meta:check and git hooks)@@ -189,18 +204,69 @@ def cli(ctx: click.Context) -> None:if ctx.invoked_subcommand not in {"meta:check", "help"} and not in_git_hook:_auto_update_manifest()# telemetry:on still shows the notice (it arms tracking by setting- # first_run_notice_shown); only off/status suppress it. This set is- # intentionally narrower than _TELEMETRY_META_COMMANDS below.+ # first_run_notice_shown); only off/status suppress it.if ctx.invoked_subcommand not in {"telemetry:off", "telemetry:status"}:telemetry.show_first_run_notice_if_needed()- # Fire early so long-running commands (e.g. hogli start) are always counted- # even if the process is killed without a clean exit. Gated identically to- # command_completed so the two events form matched pairs.- if _should_track(ctx.invoked_subcommand):- telemetry.track(- "command_started", {"command": ctx.invoked_subcommand, **_env_properties(ctx.invoked_subcommand)}- )+ # Set before the send thread spawns below: mutating the environment while+ # another thread sits in C-level getenv (resolver, OpenSSL) is undefined+ # behavior on POSIX.+ os.environ[_NESTED_INVOCATION_VAR] = "1"++ # Fire early so long-running commands (e.g. hogli start) are counted even+ # on a hard kill (see flush_async). The gate decision is stashed so+ # command_completed reuses it: evaluating it again at command end could+ # disagree (config flipped mid-run) and unpair the events.+ ctx.meta["hogli.telemetry_active"] = _telemetry_active(ctx.invoked_subcommand)+ if ctx.meta["hogli.telemetry_active"]:+ try:+ telemetry.track(+ "command_started", {"command": ctx.invoked_subcommand, **_env_properties(ctx.invoked_subcommand)}+ )+ telemetry.flush_async()+ except Exception:+ pass++[email protected](name="telemetry:on", help="Enable anonymous usage telemetry")+def telemetry_on() -> None:+ telemetry.set_enabled(True)+ click.echo("Telemetry enabled. Thank you for helping improve hogli!")++[email protected](name="telemetry:off", help="Disable anonymous usage telemetry")+def telemetry_off() -> None:+ telemetry.set_enabled(False)+ click.echo("Telemetry disabled.")++[email protected](name="telemetry:status", help="Show current telemetry settings")+def telemetry_status() -> None:+ enabled = telemetry.is_enabled()+ config_path = telemetry.get_config_path()++ if enabled and not telemetry.is_active():+ # Enabled but the first-run notice flag never persisted (fresh or+ # read-only HOME): nothing sends until the notice is shown.+ click.echo("Telemetry: enabled (pending first-run notice -- shown on your next tracked command)")+ else:+ click.echo(f"Telemetry: {'enabled' if enabled else 'disabled'}")++ # Show which mechanism controls the state+ if telemetry.is_ci():+ click.echo("Controlled by: CI environment detected")+ elif os.environ.get("POSTHOG_TELEMETRY_OPT_OUT") == "1":+ click.echo("Controlled by: POSTHOG_TELEMETRY_OPT_OUT=1")+ elif os.environ.get("DO_NOT_TRACK") == "1":+ click.echo("Controlled by: DO_NOT_TRACK=1")+ else:+ click.echo("Controlled by: config file")++ if enabled:+ click.echo(f"Anonymous ID: {telemetry.get_anonymous_id()}")+ else:+ click.echo("Anonymous ID: (not generated -- telemetry disabled)")+ click.echo(f"Config path: {config_path}")@cli.command(name="meta:check", help="Validate manifest against bin scripts (for CI)")@@ -372,8 +438,7 @@ def _command_needs_secrets(invoked_subcommand: str | None, manifest: Manifest) -return Falseif invoked_subcommand in _BUILTIN_COMMANDS_NEEDING_SECRETS:return True- cmd_config = manifest.get_command_config(invoked_subcommand) or {}- return bool(cmd_config.get("needs_secrets"))+ return manifest.command_flag(invoked_subcommand, "needs_secrets")def _maybe_reexec_via_wrap(secrets: dict[str, Any], env_files: list[Path]) -> None:@@ -514,6 +579,14 @@ _register_script_commands()_load_boot_modules()+def _hogli_version() -> str | None:+ try:+ return importlib.metadata.version("hogli")+ except importlib.metadata.PackageNotFoundError:+ return None++def _env_properties(command: str | None = None) -> dict[str, Any]:"""Static environment properties shared across telemetry events."""props: dict[str, Any] = {@@ -521,7 +594,9 @@ def _env_properties(command: str | None = None) -> dict[str, Any]:"os": platform.system(),"arch": platform.machine(),"python_version": platform.python_version(),+ "hogli_version": _hogli_version(),"is_ci": telemetry.is_ci(),+ "is_nested": _IS_NESTED,}for hook in telemetry_property_hooks:try:@@ -531,19 +606,39 @@ def _env_properties(command: str | None = None) -> dict[str, Any]:return props-# Telemetry commands manage telemetry itself; tracking them would pollute the-# dataset with self-referential noise, so they emit no command events.-_TELEMETRY_META_COMMANDS = frozenset({"telemetry:on", "telemetry:off", "telemetry:status"})+# Core builtins exempt from telemetry: the telemetry:* management commands+# would pollute the dataset with self-referential noise, and `run`+# exec-replaces the process (os.execvp), so its started/completed events could+# never pair. Mirrors _BUILTIN_COMMANDS_NEEDING_SECRETS -- manifest-declared+# commands opt out the same way via `untracked: true` (e.g. exec-style devbox+# commands), so consumer command names stay out of core.+_UNTRACKED_BUILTINS = frozenset({"telemetry:on", "telemetry:off", "telemetry:status", "run"})def _should_track(command: str | None) -> bool:"""Whether a subcommand should emit command_started / command_completed.Requires a real subcommand (so bare ``hogli`` / ``--help`` don't fire a- completed event with no matching started event) and excludes the telemetry- management commands.+ completed event with no matching started event), excludes the untracked+ core builtins, and honors a manifest-level ``untracked: true``."""- return bool(command) and command not in _TELEMETRY_META_COMMANDS+ if not command or command in _UNTRACKED_BUILTINS:+ return False+ return not get_manifest().command_flag(command, "untracked")+++def _telemetry_active(command: str | None) -> bool:+ """Gate for command_started / command_completed -- identical for both so+ the events pair under stable config.++ Checked before property computation: the property hooks fork subprocesses,+ which inactive paths (CI, opt-outs, unconfigured HOMEs) shouldn't pay for.+ Never raises -- telemetry must not break commands.+ """+ try:+ return _should_track(command) and telemetry.is_active()+ except Exception:+ return Falsedef _outcome(exit_code: int) -> str:@@ -561,7 +656,9 @@ def _outcome(exit_code: int) -> str:def _fire_telemetry(ctx: click.Context, exit_code: int) -> None:"""Send a command_completed telemetry event. Never raises."""command = ctx.invoked_subcommand- if not _should_track(command):+ # Reuse the gate decision made at command start (fail closed if the group+ # callback never ran) so started/completed pair even if config flips mid-run.+ if not ctx.meta.get("hogli.telemetry_active", False):returntry:start_time: float = ctx.meta.get("hogli.start_time", 0.0)diff --git a/tools/hogli/src/hogli/manifest.py b/tools/hogli/src/hogli/manifest.pyindex f418dd2efac1..769ab221af1c 100644--- a/tools/hogli/src/hogli/manifest.py+++ b/tools/hogli/src/hogli/manifest.py@@ -322,13 +322,21 @@ class Manifest:return category[command_name]return None+ def command_flag(self, command_name: str, key: str) -> bool:+ """Read a boolean flag from a command's manifest entry.++ Single home for the per-command flag lookup (``hidden``,+ ``needs_secrets``, ``untracked``). Missing command or key -> False.+ """+ config = self.get_command_config(command_name) or {}+ return bool(config.get(key, False))+def is_command_hidden(self, command_name: str) -> bool:"""Whether a command should be hidden from help. Manifest is the only source of truth.Set ``hidden: true`` on the manifest entry; do not use ``@click.command(hidden=True)``."""- config = self.get_command_config(command_name) or {}- return bool(config.get("hidden", False))+ return self.command_flag(command_name, "hidden")def get_children_for_command(self, command_name: str) -> list[str]:"""Get child commands that extend this command."""diff --git a/tools/hogli/src/hogli/telemetry.py b/tools/hogli/src/hogli/telemetry.pyindex 8ac6a98992bb..427a1eb3bd13 100644--- a/tools/hogli/src/hogli/telemetry.py+++ b/tools/hogli/src/hogli/telemetry.py@@ -1,7 +1,8 @@"""Anonymous opt-out telemetry for hogli CLI.-Events are queued in-process and flushed as a single batch POST to a-PostHog-compatible ``/batch/`` endpoint.+Events are queued in-process and sent as batch POSTs to a PostHog-compatible+``/batch/`` endpoint -- eagerly via :func:`flush_async`, or blocking via+:func:`flush` (registered atexit, which also joins in-flight sends).Telemetry is **disabled** unless an API key is configured via the``telemetry.api_key`` section of ``hogli.yaml`` (or the@@ -19,6 +20,7 @@ from __future__ import annotationsimport osimport sysimport json+import timeimport uuidimport atexitimport threading@@ -87,11 +89,12 @@ def _save_config(config: TelemetryConfig) -> None:class TelemetryClient:- """Queue-based telemetry client that batches events into a single POST."""+ """Queue-based telemetry client that sends events as batch POSTs."""def __init__(self) -> None:self._queue: list[dict[str, Any]] = []self._lock = threading.Lock()+ self._inflight: list[threading.Thread] = []# -- config-backed helpers --@@ -125,6 +128,19 @@ class TelemetryClient:return Falsereturn _load_config().get("enabled", True)+ def is_active(self) -> bool:+ """The single emission predicate: a track() call right now would queue and send.++ Stricter than :meth:`is_enabled`: also requires the first-run notice+ flag to have been persisted, which never happens on read-only or+ ephemeral HOMEs. Never raises -- telemetry must not break its host.+ """+ try:+ return self.is_enabled() and bool(_load_config().get("first_run_notice_shown"))+ except Exception as exc:+ _debug(f"is_active check failed (treating as inactive): {exc}")+ return False+def get_anonymous_id(self) -> str:config = _load_config()anon_id = config.get("anonymous_id")@@ -153,7 +169,8 @@ class TelemetryClient:click.echo("\n""hogli collects anonymous usage data to help improve the developer experience.\n"- "No personal information is collected -- only command names and timing.\n"+ "No personal information is collected -- only command names, timing, and\n"+ "environment context (OS, tool versions, dev-environment type).\n""\n""You can opt out at any time:\n"" hogli telemetry:off (persistent)\n"@@ -173,16 +190,12 @@ class TelemetryClient:# -- event tracking --def track(self, event: str, properties: dict[str, Any] | None = None) -> None:- """Queue a single event. No-ops if telemetry is disabled."""- if not self.is_enabled():- return- config = _load_config()- if not config.get("first_run_notice_shown"):+ """Queue a single event. No-ops unless telemetry is active."""+ if not self.is_active():returnprops: dict[str, Any] = {"$process_person_profile": False,- "$groups": {"project": "hogli"},}if properties:props.update(properties)@@ -199,16 +212,40 @@ class TelemetryClient:self._queue.append(entry)def flush(self, timeout: float = 2.0) -> None:- """Send queued events as a single batch POST, blocking up to *timeout*."""+ """Send queued events and wait for in-flight sends, up to *timeout* total.++ Each send thread is joined at most once across flush calls; a thread+ still alive after its window is abandoned to its daemon fate, so a+ hung send can't stall both the post-command flush and the atexit one.+ """+ self._start_send()+ with self._lock:+ pending, self._inflight = self._inflight, []+ deadline = time.monotonic() + timeout+ for thread in pending:+ thread.join(timeout=max(0.0, deadline - time.monotonic()))++ def flush_async(self) -> None:+ """Send queued events in the background without blocking (joined later+ by :meth:`flush`). On a hard kill the POST is already in flight, so+ eagerly-flushed events usually survive where queued ones never do.+ """+ self._start_send()++ def _start_send(self) -> None:+ # Drain, start, and register in one critical section so a concurrent+ # flush() can never swap _inflight between them: appending first would+ # let it join an unstarted thread (RuntimeError), appending after+ # start outside the lock would let the thread escape the join. The+ # send thread never touches _lock, so starting it here can't deadlock.with self._lock:if not self._queue:returnbatch = self._queue[:]self._queue.clear()-- thread = threading.Thread(target=self._send_batch, args=(batch,), daemon=True)- thread.start()- thread.join(timeout=timeout)+ thread = threading.Thread(target=self._send_batch, args=(batch,), daemon=True)+ thread.start()+ self._inflight.append(thread)def _send_batch(self, batch: list[dict[str, Any]]) -> None:host = self._host@@ -230,13 +267,28 @@ class TelemetryClient:# ---------------------------------------------------------------------------_client = TelemetryClient()-atexit.register(_client.flush)+++def _flush_at_exit() -> None:+ # Never let telemetry teardown print a traceback at process exit (e.g.+ # thread creation failing under resource exhaustion).+ try:+ _client.flush()+ except Exception:+ pass+++atexit.register(_flush_at_exit)def is_enabled() -> bool:return _client.is_enabled()+def is_active() -> bool:+ return _client.is_active()++def get_anonymous_id() -> str:return _client.get_anonymous_id()@@ -257,6 +309,10 @@ def flush(timeout: float = 2.0) -> None:_client.flush(timeout)+def flush_async() -> None:+ _client.flush_async()++# ---------------------------------------------------------------------------# Debug logging# ---------------------------------------------------------------------------diff --git a/tools/hogli/tests/conftest.py b/tools/hogli/tests/conftest.pyindex 3bf3a4e91446..d8142ff576b2 100644--- a/tools/hogli/tests/conftest.py+++ b/tools/hogli/tests/conftest.py@@ -6,9 +6,20 @@ from hogli import telemetry@pytest.fixture(autouse=True)-def _clear_telemetry_queue():+def _opt_out_of_real_telemetry(monkeypatch):+ # CliRunner tests otherwise run the live path against the developer's real+ # ~/.config/posthog config and POST real events with the committed api_key.+ # Suites that exercise telemetry itself (test_telemetry.py) delete this var+ # in their own fixture and substitute an isolated tmp config.+ monkeypatch.setenv("POSTHOG_TELEMETRY_OPT_OUT", "1")++[email protected](autouse=True)+def _clear_telemetry_state():with telemetry._client._lock:telemetry._client._queue.clear()+ telemetry._client._inflight.clear()yieldwith telemetry._client._lock:telemetry._client._queue.clear()+ telemetry._client._inflight.clear()diff --git a/tools/hogli/tests/test_cli.py b/tools/hogli/tests/test_cli.pyindex c8d1cd2648df..a75a12b8a4d3 100644--- a/tools/hogli/tests/test_cli.py+++ b/tools/hogli/tests/test_cli.py@@ -310,6 +310,7 @@ class TestApplyEnvConfig:return {"needs_secrets": True} if name in opted_in else {}m.get_command_config.side_effect = get_command_config+ m.command_flag.side_effect = lambda name, key: bool(get_command_config(name).get(key, False))return mdef test_no_env_config_is_noop(self, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tools/hogli/tests/test_telemetry.py b/tools/hogli/tests/test_telemetry.pyindex 7008296d430f..4a5413097ad7 100644--- a/tools/hogli/tests/test_telemetry.py+++ b/tools/hogli/tests/test_telemetry.py@@ -129,6 +129,19 @@ class TestTrack:telemetry.flush(timeout=1.0)mock_send.assert_not_called()+ def test_flush_async_drains_queue_without_blocking(self, telemetry_config: Path):+ telemetry_config.write_text(+ json.dumps({"enabled": True, "anonymous_id": "test-id", "first_run_notice_shown": True})+ )+ with patch.object(telemetry._client, "_send_batch") as mock_send:+ telemetry.track("command_started", {"command": "test"})+ telemetry.flush_async()+ # The later blocking flush only joins the in-flight send; the queue+ # was already drained, so exactly one batch goes out.+ telemetry.flush(timeout=2.0)+ mock_send.assert_called_once()+ assert mock_send.call_args[0][0][0]["event"] == "command_started"+class TestFirstRunNotice:def test_creates_config(self, telemetry_config: Path):@@ -193,14 +206,18 @@ class TestInvokeTelemetry:)monkeypatch.setenv("POSTHOG_TELEMETRY_HOST", "http://localhost")monkeypatch.setenv("POSTHOG_TELEMETRY_API_KEY", "test-key")+ # The suite itself may run under `hogli test`, which marks its whole+ # process tree nested; pin the import-time capture for a stable assert.+ monkeypatch.setattr("hogli.cli._IS_NESTED", False)with patch.object(telemetry._client, "_send_batch") as mock_send:runner = CliRunner()result = runner.invoke(cli, ["quickstart"])assert result.exit_code == 0- # Single batch call containing both events- mock_send.assert_called_once()- batch = mock_send.call_args[0][0]+ # started is flushed eagerly in its own batch; completed flushes at+ # command end -- two sends, so a hard kill can't lose the started event.+ assert mock_send.call_count == 2+ batch = [event for call in mock_send.call_args_list for event in call.args[0]]events = {e["event"] for e in batch}assert "command_started" in eventsassert "command_completed" in events@@ -208,6 +225,8 @@ class TestInvokeTelemetry:started = next(e for e in batch if e["event"] == "command_started")assert started["properties"]["command"] == "quickstart"assert "is_ci" in started["properties"]+ assert "hogli_version" in started["properties"]+ assert started["properties"]["is_nested"] is Falsecompleted = next(e for e in batch if e["event"] == "command_completed")assert completed["properties"]["command"] == "quickstart"@@ -216,6 +235,20 @@ class TestInvokeTelemetry:assert "duration_s" in completed["properties"]assert "is_ci" in completed["properties"]+ def test_first_run_shows_notice_and_emits_events(self, monkeypatch: pytest.MonkeyPatch, telemetry_config: Path):+ """A brand-new install (no config file) must arm itself and emit events+ in the same invocation -- the notice block must run before the gate."""+ assert not telemetry_config.exists()+ monkeypatch.setenv("POSTHOG_TELEMETRY_HOST", "http://localhost")+ monkeypatch.setenv("POSTHOG_TELEMETRY_API_KEY", "test-key")+ monkeypatch.setattr("hogli.cli._IS_NESTED", False)+ with patch.object(telemetry._client, "_send_batch") as mock_send:+ result = CliRunner().invoke(cli, ["quickstart"])+ assert result.exit_code == 0+ events = {e["event"] for call in mock_send.call_args_list for e in call.args[0]}+ assert events == {"command_started", "command_completed"}+ assert "hogli collects anonymous usage data" in result.output+@pytest.mark.parametrize("command", ["telemetry:on", "telemetry:off", "telemetry:status"])def test_management_commands_emit_no_events(self, monkeypatch: pytest.MonkeyPatch, telemetry_config: Path, command: str@@ -231,7 +264,27 @@ class TestInvokeTelemetry:mock_send.assert_not_called()+def _patch_cli_manifest(monkeypatch: pytest.MonkeyPatch, command_config: dict | None) -> None:+ """Point hogli.cli at a fake manifest whose every command has *command_config*.++ Keeps core tests off PostHog's hogli.yaml per the framework boundary.+ """++ class _FakeManifest:+ def command_flag(self, command, key):+ return bool((command_config or {}).get(key, False))++ def get_command_config(self, command):+ return command_config++ monkeypatch.setattr("hogli.cli.get_manifest", lambda: _FakeManifest())++class TestShouldTrack:+ @pytest.fixture(autouse=True)+ def _no_untracked_manifest(self, monkeypatch: pytest.MonkeyPatch):+ _patch_cli_manifest(monkeypatch, None)+@pytest.mark.parametrize("command, expected",[@@ -241,11 +294,16 @@ class TestShouldTrack:("telemetry:on", False),("telemetry:off", False),("telemetry:status", False),+ ("run", False), # exec-replaces the process; events could never pair],)def test_should_track(self, command, expected):assert _should_track(command) is expected+ def test_manifest_untracked_key_suppresses_tracking(self, monkeypatch: pytest.MonkeyPatch):+ _patch_cli_manifest(monkeypatch, {"untracked": True})+ assert _should_track("devbox:ssh") is False+class TestOutcome:@pytest.mark.parametrize(