: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(devex): add devex:feedback command for dev experience feedback (#68000)
Julian Beza260725409d8
diff --git a/AGENTS.md b/AGENTS.mdindex fcb4f681e6f5..d807ad5547d1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -28,6 +28,8 @@- OpenAPI/types: `hogli build:openapi` (regenerate after changing serializers/viewsets)- New product: `bin/hogli product:bootstrap <name>`- LSP: Pyright is configured against the flox venv. Prefer LSP (`goToDefinition`, `findReferences`, `hover`) over grep when navigating or refactoring Python code.+- Dev experience feedback: `hogli devex:feedback "<message>"` sends feedback about repo tooling — hogli, the dev stack, tests, CI, migrations, this setup — straight to the devex team as a `hogli_feedback` event (add `-c bug|idea|praise|question`).+ **Agents must use it too**: when a hogli command or dev workflow is broken, slow, or confusing, run it — e.g. `hogli devex:feedback -c bug "migrations:run failed with <error>"`. Agent-sent feedback is tagged as such, and it's the fastest signal the devex team gets, so use it liberally rather than suffering friction silently.## Commits and Pull Requestsdiff --git a/devenv/news.txt b/devenv/news.txtindex ef0bd9ea0c9f..90a52bd50fd8 100644--- a/devenv/news.txt+++ b/devenv/news.txt@@ -1,3 +1,6 @@+2026-07-02+send feedback to the devex team (humans and agents): hogli devex:feedback "..."+2026-06-08objectstorage swapped minio -> seaweedfs; old local files stay on the old volume, run hogli deploy:upgrade-objectstorage to copy them overdiff --git a/hogli.yaml b/hogli.yamlindex fc4c42436ee4..acf8c9bc8a5d 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -62,6 +62,8 @@ metadata:title: Authenticate to internal services- key: toolstitle: Developer tools and utilities+ - key: devex+ title: Developer experience feedback- key: utilitiestitle: Git worktrees and admin- key: devbox@@ -991,6 +993,10 @@ tools:ci:preflight:click: hogli_commands.ci_preflight:ci_preflightdescription: Catch deterministic CI failures reachable from your diff before you push (advisory; --fix, --strict)+devex:+ devex:feedback:+ click: hogli_commands.feedback:devex_feedback+ description: Send feedback about the dev experience to the devex team (humans and agents)utilities:nuke:steps:diff --git a/tools/hogli-commands/hogli_commands/feedback.py b/tools/hogli-commands/hogli_commands/feedback.pynew file mode 100644index 000000000000..9808fd37ec27--- /dev/null+++ b/tools/hogli-commands/hogli_commands/feedback.py@@ -0,0 +1,183 @@+"""hogli devex:feedback — send feedback about the dev experience to the devex team.++Feedback lands as a ``hogli_feedback`` event in PostHog's internal hogli project,+carrying the same environment context that hogli telemetry attaches (environment,+agent, git branch, repo vintage) so the devex team can triage it.++Unlike passive telemetry, feedback is an explicit, user-initiated action: the+command name states exactly what it does, so it is sent even when passive+telemetry is opted out — though it then uses a throwaway distinct id rather than+minting a persistent one. It still needs a configured telemetry API key as a+destination.+"""++from __future__ import annotations++import os+import sys+import uuid+import platform+from datetime import UTC, datetime+from typing import Any++import click+import requests+from hogli import telemetry+from hogli.hooks import telemetry_property_hooks+from hogli.manifest import get_manifest++_EVENT = "hogli_feedback"+_DEFAULT_HOST = "https://us.i.posthog.com"+_CATEGORIES = ("bug", "idea", "praise", "question", "other")+++def _endpoint() -> tuple[str, str]:+ """(host, api_key) for the feedback event, env override then manifest config."""+ cfg = get_manifest().config.get("telemetry", {}) or {}+ host = os.environ.get("POSTHOG_TELEMETRY_HOST") or cfg.get("host", _DEFAULT_HOST)+ api_key = os.environ.get("POSTHOG_TELEMETRY_API_KEY") or cfg.get("api_key", "")+ return host, api_key+++def _distinct_id() -> str:+ """Distinct id for the feedback event.++ Reuse the persisted anonymous telemetry id when telemetry is enabled, so+ feedback correlates with the sender's other hogli events. Under opt-out+ (DO_NOT_TRACK, POSTHOG_TELEMETRY_OPT_OUT, disabled config, CI), don't mint or+ persist a durable id just to send an explicit one-off — use a throwaway.+ """+ if telemetry.is_enabled():+ return telemetry.get_anonymous_id()+ return str(uuid.uuid4())+++def _stdin_is_tty() -> bool:+ """True when stdin is an interactive terminal — False, not a crash, when stdin+ is closed or absent (daemon / sandbox / agent contexts)."""+ try:+ return sys.stdin.isatty()+ except (ValueError, AttributeError):+ return False+++def _read_piped_stdin() -> str:+ """Read all of piped stdin, blocking until EOF (standard pipeline semantics).++ Returns "" when stdin is closed or absent (daemon / sandbox contexts) rather+ than raising. A caller that holds an empty pipe open with no writer blocks+ here, same as any Unix filter — pass the message as an argument to avoid that.+ """+ try:+ return sys.stdin.read()+ except (ValueError, AttributeError):+ return ""+++def _context_properties() -> dict[str, Any]:+ """Environment context attached to the feedback event.++ Reuses the registered telemetry property hooks (environment, agent,+ git_branch, repo_sha, …) so feedback carries the same triage context as+ hogli's regular events, plus a few static platform props.+ """+ props: dict[str, Any] = {+ "os": platform.system(),+ "arch": platform.machine(),+ "python_version": platform.python_version(),+ }+ for hook in telemetry_property_hooks:+ try:+ props.update(hook("devex:feedback"))+ except Exception:+ pass+ return props+++def _send(message: str, category: str | None, context: dict[str, Any]) -> tuple[bool, str]:+ """POST the feedback event synchronously. Returns (ok, error_message)."""+ host, api_key = _endpoint()+ if not api_key:+ return False, "no telemetry API key configured, so there is nowhere to send feedback"++ # context first, then the command's invariants, so no context key can override+ # the anonymity flag or the message.+ props: dict[str, Any] = {**context, "$process_person_profile": False, "message": message}+ if category:+ props["category"] = category++ entry = {+ "event": _EVENT,+ "distinct_id": _distinct_id(),+ "properties": props,+ "timestamp": datetime.now(UTC).isoformat(),+ }+ try:+ resp = requests.post(f"{host}/batch/", json={"api_key": api_key, "batch": [entry]}, timeout=10)+ resp.raise_for_status()+ return True, ""+ except Exception as exc:+ return False, str(exc)++[email protected](name="devex:feedback")[email protected]("message", nargs=-1)[email protected]("-c", "--category", type=click.Choice(_CATEGORIES), help="Optional feedback category.")[email protected]("-y", "--yes", is_flag=True, help="Send without the confirmation preview (implied when non-interactive).")+def devex_feedback(message: tuple[str, ...], category: str | None, yes: bool) -> None:+ """Send feedback about the dev experience to the PostHog devex team.++ Humans and agents alike: when a hogli command, the dev stack, or any repo+ tooling is slow, broken, confusing, or delightful, say so here. It lands as+ a `hogli_feedback` event the devex team triages, tagged with your+ environment, branch, and whether an agent sent it.++ \b+ hogli devex:feedback "dev:reset took 20 min and the schema restore silently failed"+ hogli devex:feedback -c idea "add a hogli db:snapshot to save/restore local state"+ echo "long note" | hogli devex:feedback++ The message is the only free-form content sent; everything else is the same+ environment context hogli telemetry already attaches. Run interactively to+ confirm before sending.+ """+ interactive = _stdin_is_tty()+ text = " ".join(message).strip()++ # No inline message: prompt an interactive human, or read piped stdin (blocking,+ # like any Unix filter) so delayed producers such as `… | hogli devex:feedback` work.+ if not text and interactive:+ text = click.prompt("Your feedback for the devex team", default="", show_default=False).strip()+ elif not text:+ text = _read_piped_stdin().strip()++ if not text:+ raise click.ClickException('nothing to send — provide a message: hogli devex:feedback "..."')++ # Preview + confirm for interactive humans; agents and pipes send straight through.+ if interactive and not yes:+ click.echo()+ click.secho("Sending to the devex team:", bold=True)+ click.echo(f" {text}")+ if category:+ click.echo(f" category: {category}")+ click.secho(+ "\nTagged with the same environment context hogli telemetry attaches (environment, agent, branch, repo).\n",+ dim=True,+ )+ if not click.confirm("Send?", default=True):+ click.secho("Not sent.", fg="yellow")+ return++ # Collect context only once we're committed to sending — the telemetry hooks can+ # shell out (gh api) and persist cache, so a declined preview stays side-effect-free.+ context = _context_properties()++ ok, err = _send(text, category, context)+ if ok:+ click.secho("✓ Sent to the devex team. Thank you!", fg="green")+ return++ click.secho(f"✗ Could not send feedback: {err}", fg="red", err=True)+ click.echo("Check your connection and retry, or share it with the devex team directly.", err=True)+ raise SystemExit(1)diff --git a/tools/hogli-commands/hogli_commands/tests/test_feedback.py b/tools/hogli-commands/hogli_commands/tests/test_feedback.pynew file mode 100644index 000000000000..764bf4a56e33--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_feedback.py@@ -0,0 +1,128 @@+"""Tests for hogli devex:feedback.++The framework's parametrized ``--help`` test already covers command wellformedness;+these guard the one thing it can't see — that a feedback submission still lands as a+well-formed ``hogli_feedback`` event, so the feature can't silently stop reaching the+devex project on a refactor.+"""++from __future__ import annotations++from pathlib import Path++import pytest+from unittest.mock import patch++from click.testing import CliRunner+from hogli_commands import feedback+++def isolated_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # Keep get_anonymous_id() off the real ~/.config and pin a deterministic key.+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("POSTHOG_TELEMETRY_API_KEY", "phc_test")+ monkeypatch.delenv("POSTHOG_TELEMETRY_HOST", raising=False)+++def test_send_posts_wellformed_feedback_event(isolated_config: None) -> None:+ with patch.object(feedback.requests, "post") as post:+ post.return_value.raise_for_status.return_value = None+ ok, err = feedback._send("reset was slow", "bug", {"environment": "local", "is_agent": True})++ assert ok and err == ""+ url = post.call_args.args[0]+ body = post.call_args.kwargs["json"]+ assert url.endswith("/batch/")+ assert body["api_key"] == "phc_test"++ (event,) = body["batch"]+ assert event["event"] == "hogli_feedback"+ assert event["distinct_id"]+ props = event["properties"]+ assert props["message"] == "reset was slow"+ assert props["category"] == "bug"+ assert props["environment"] == "local" and props["is_agent"] is True+ # Feedback is anonymous — it must not create a person profile.+ assert props["$process_person_profile"] is False+++def test_opt_out_uses_ephemeral_distinct_id(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # Feedback still sends under DO_NOT_TRACK (explicit action), but must not mint or+ # persist a durable anonymous id on disk just to do it.+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("DO_NOT_TRACK", "1")+ monkeypatch.setenv("POSTHOG_TELEMETRY_API_KEY", "phc_test")+ with patch.object(feedback.requests, "post") as post:+ post.return_value.raise_for_status.return_value = None+ ok, _ = feedback._send("hi", None, {})++ assert ok+ assert post.call_args.kwargs["json"]["batch"][0]["distinct_id"] # a throwaway id is still sent+ assert not feedback.telemetry.get_config_path().exists() # nothing persisted+++def test_send_without_api_key_never_posts(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(feedback, "_endpoint", lambda: ("https://us.i.posthog.com", ""))+ with patch.object(feedback.requests, "post") as post:+ ok, err = feedback._send("hi", None, {})+ assert ok is False+ assert "no telemetry API key" in err+ post.assert_not_called()+++def test_send_returns_error_on_network_failure(isolated_config: None) -> None:+ # A failed POST must surface as (False, msg) so the CLI exits non-zero, not crash.+ with patch.object(feedback.requests, "post", side_effect=feedback.requests.exceptions.Timeout("boom")):+ ok, err = feedback._send("hi", None, {})+ assert ok is False+ assert err+++ ("answer", "should_send"),+ [("y\n", True), ("n\n", False)],+ ids=["confirm_sends", "decline_aborts"],+)+def test_interactive_confirm_gate(monkeypatch: pytest.MonkeyPatch, answer: str, should_send: bool) -> None:+ # On a TTY, the preview's "Send?" prompt gates the send: 'n' must not transmit.+ monkeypatch.setattr(feedback, "_stdin_is_tty", lambda: True)+ ctx_calls: list[int] = []+ monkeypatch.setattr(feedback, "_context_properties", lambda: (ctx_calls.append(1), {})[1])+ sent: list[str] = []+ monkeypatch.setattr(feedback, "_send", lambda msg, cat, ctx: (sent.append(msg), (True, ""))[1])++ result = CliRunner().invoke(feedback.devex_feedback, ["the message"], input=answer)++ assert result.exit_code == 0+ assert bool(sent) is should_send+ # Context collection can shell out / persist cache — it must only run when sending.+ assert bool(ctx_calls) is should_send+++ ("env_host", "manifest_host", "expected"),+ [+ ("http://env.example", "http://manifest.example", "http://env.example"),+ (None, "http://manifest.example", "http://manifest.example"),+ (None, None, feedback._DEFAULT_HOST),+ ],+ ids=["env_override_wins", "manifest_fallback", "default_host_fallback"],+)+def test_endpoint_host_precedence(+ monkeypatch: pytest.MonkeyPatch, env_host: str | None, manifest_host: str | None, expected: str+) -> None:+ if env_host is None:+ monkeypatch.delenv("POSTHOG_TELEMETRY_HOST", raising=False)+ else:+ monkeypatch.setenv("POSTHOG_TELEMETRY_HOST", env_host)+ monkeypatch.setenv("POSTHOG_TELEMETRY_API_KEY", "phc_test")+ # Omit the host key entirely when manifest_host is None so the `.get(..., default)`+ # fallback is exercised, rather than storing an explicit None that shadows it.+ telemetry_cfg: dict[str, str] = {"api_key": "phc_manifest"}+ if manifest_host is not None:+ telemetry_cfg["host"] = manifest_host+ with patch.object(feedback, "get_manifest") as gm:+ gm.return_value.config = {"telemetry": telemetry_cfg}+ host, _ = feedback._endpoint()+ assert host == expected