: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): add ci:insights adapter (with Mendral concrete class) (#60299)
Raúl Negrón-Oteroa8fe4485bde3
diff --git a/.agents/skills/debugging-ci-failures/SKILL.md b/.agents/skills/debugging-ci-failures/SKILL.mdindex 28266abb209d..f6df9e47c435 100644--- a/.agents/skills/debugging-ci-failures/SKILL.md+++ b/.agents/skills/debugging-ci-failures/SKILL.md@@ -5,9 +5,9 @@ description: >Use when the user asks why CI is red, mentions a failing check, GitHub Actionsrun, Depot runner, workflow, job, shard, flaky test, lint failure, typecheckfailure, snapshot diff, migration check, generated types drift, or skills- build failure. Guides read-only inspection, failure classification, smallest- local reproduction with hogli, and safe reporting without rerunning CI or- posting to GitHub.+ build failure. Guides read-only inspection, failure classification, a check+ for an existing CI-insights hypothesis, smallest local reproduction with+ hogli, and safe reporting without rerunning CI or posting to GitHub.---# Debugging PostHog CI failures@@ -88,6 +88,26 @@ If multiple signals match, choose the most specific class. For example, prefercodegen drift over lint, migration over typecheck, and snapshot / visual over ageneric Playwright test failure.+## Check existing CI insights first++Before reproducing locally, check whether our CI-insights backend already has a+hypothesis for this failure. It aggregates cross-run history — recurring flakes,+occurrence counts, confidence — that a single run can't show, and may already+carry a proposed or merged fix.++```bash+hogli ci:insights # insights for the current repo + branch+hogli ci:insights search "<error or test name>" # match this specific failure+hogli ci:insights view <id> # one insight + its remediation actions+hogli ci:insights plan <id> # print the recommended fix plan (does not apply it)+```++`hogli ci:insights` prints a setup hint if the backend isn't installed or+authenticated — if so, skip this step. When a matching insight exists, weigh its+confidence and occurrence history, and note whether a fix is already merged (the+failure may already be resolved on `master`) or proposed (a plan you can adapt).+Surface what you find per the Safety rules — do not auto-apply a fix.+## Local reproductionRun only the narrowest command that exercises the failure. If the command shapediff --git a/hogli.yaml b/hogli.yamlindex dd4a5b451708..98712846147d 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -906,6 +906,9 @@ tools:bin_script: find-affected-storiesdescription: Compute the set of stories affected by changed files during storybook buildshidden: true+ ci:insights:+ click: hogli_commands.ci_insights:ci_insights+ description: Show CI insights for the current repo + branch (search/view/plan subcommands)utilities:nuke:steps:diff --git a/tools/hogli-commands/hogli_commands/ci_insights.py b/tools/hogli-commands/hogli_commands/ci_insights.pynew file mode 100644index 000000000000..cc8483c75b71--- /dev/null+++ b/tools/hogli-commands/hogli_commands/ci_insights.py@@ -0,0 +1,140 @@+"""CI insights for the current repo + branch.++A vendor-neutral adapter over a CI-insights backend. Every backend-specific+detail lives in one place (``MendralBackend``); swapping providers means+replacing that class, leaving the call sites and the debugging-ci-failures+skill untouched.++ hogli ci:insights # digest for the current repo + branch+ hogli ci:insights search "<error>" # match insights to a failure string+ hogli ci:insights view <id> [--json] # one insight + its remediation actions+ hogli ci:insights plan <id> # print the recommended remediation plan++When stdout is not a terminal the backend emits JSON on its own, so piped/agent+callers get structured output without a flag; ``--json`` forces it in a tty.+"""++from __future__ import annotations++import json+import shutil+import subprocess+from typing import Any++import click++# Actionable statuses, most-preferred first — picks which remediation plan to+# surface when an insight carries several recommended actions.+_ACTIONABLE_STATUSES: tuple[str, ...] = ("proposed", "in_progress", "in_review")+++def _run(*args: str) -> int:+ """Run the backend CLI inheriting stdio; return its exit code."""+ return subprocess.run(args).returncode+++def _capture(*args: str) -> str:+ """Run the backend CLI capturing stdout; raise ClickException on failure."""+ result = subprocess.run(args, capture_output=True, text=True)+ if result.returncode != 0:+ raise click.ClickException((result.stderr or result.stdout).strip() or "backend command failed")+ return result.stdout+++class MendralBackend:+ """The only Mendral-aware code. Swap this class to change providers."""++ name = "Mendral"+ binary = "mendral"+ install_hint = "brew install mendral-ai/tap/mendral"++ def ensure_ready(self) -> None:+ if shutil.which(self.binary) is None:+ raise click.ClickException(+ f"{self.name} CLI not found. Install it with:\n"+ f" {self.install_hint}\n"+ f"Then authenticate: ! {self.binary} auth login"+ )+ # `mendral auth status` exits 0 whether or not you are logged in, so the+ # exit code carries no signal — read the message instead.+ if "Not authenticated" in _capture(self.binary, "auth", "status"):+ raise click.ClickException(f"{self.name} is not authenticated. Run: ! {self.binary} auth login")++ def digest(self) -> int:+ return _run(self.binary, "here")++ def search(self, query: str, *, as_json: bool) -> int:+ return _run(self.binary, "insight", "search", query, *(["--json"] if as_json else []))++ def view(self, insight_id: str, *, as_json: bool) -> int:+ return _run(self.binary, "insight", "view", insight_id, *(["--json"] if as_json else []))++ def plan(self, insight_id: str) -> int:+ raw = _capture(self.binary, "insight", "view", insight_id, "--json")+ try:+ insight = json.loads(raw)+ except json.JSONDecodeError as exc:+ raise click.ClickException(f"Could not parse the {self.name} response for {insight_id}: {exc}")+ actions = [action for action in (insight.get("actions") or []) if isinstance(action, dict)]+ action = _recommended_action(actions)+ if action is None:+ raise click.ClickException(f"No remediation plan available for {insight_id}.")+ click.secho(f"{action.get('title') or 'Remediation plan'} [{action.get('status')}]", bold=True)+ if action.get("status") == "merged":+ click.secho("A fix for this insight has already been merged.", fg="yellow")+ full_plan = action.get("full_plan")+ if not full_plan:+ raise click.ClickException("The recommended action has no plan text.")+ click.echo(full_plan)+ return 0+++def _recommended_action(actions: list[dict[str, Any]]) -> dict[str, Any] | None:+ """Pick the plan worth showing: a recommended, still-actionable action if one+ exists; else any recommended action; else the first action."""+ recommended = [action for action in actions if action.get("recommended")]+ for status in _ACTIONABLE_STATUSES:+ for action in recommended:+ if action.get("status") == status:+ return action+ if recommended:+ return recommended[0]+ return actions[0] if actions else None+++_BACKEND: MendralBackend = MendralBackend()+++# Each entry point calls ensure_ready() in its own body rather than the group+# callback, so `--help` (which short-circuits before the body) works without the+# backend installed. SystemExit is used throughout — the telemetry wrapper+# records its code, unlike click's ctx.exit().[email protected](name="ci:insights", invoke_without_command=True, help="Show CI insights for the current repo + branch.")[email protected]_context+def ci_insights(ctx: click.Context) -> None:+ if ctx.invoked_subcommand is None:+ _BACKEND.ensure_ready()+ raise SystemExit(_BACKEND.digest())+++@ci_insights.command(name="search", help="Search CI insights by keyword or error string.")[email protected]("query")[email protected]("--json", "as_json", is_flag=True, help="Emit raw JSON instead of a table.")+def search(query: str, as_json: bool) -> None:+ _BACKEND.ensure_ready()+ raise SystemExit(_BACKEND.search(query, as_json=as_json))+++@ci_insights.command(name="view", help="View a CI insight and its remediation actions.")[email protected]("insight_id")[email protected]("--json", "as_json", is_flag=True, help="Emit raw JSON instead of a table.")+def view(insight_id: str, as_json: bool) -> None:+ _BACKEND.ensure_ready()+ raise SystemExit(_BACKEND.view(insight_id, as_json=as_json))+++@ci_insights.command(name="plan", help="Print the recommended remediation plan (does not apply changes).")[email protected]("insight_id")+def plan(insight_id: str) -> None:+ _BACKEND.ensure_ready()+ raise SystemExit(_BACKEND.plan(insight_id))diff --git a/tools/hogli-commands/hogli_commands/tests/test_ci_insights.py b/tools/hogli-commands/hogli_commands/tests/test_ci_insights.pynew file mode 100644index 000000000000..8590e2ed8b4c--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_ci_insights.py@@ -0,0 +1,164 @@+from __future__ import annotations++import json+from collections.abc import Iterator++import pytest+from unittest.mock import patch++from click.testing import CliRunner+from hogli_commands import ci_insights+++def runner() -> CliRunner:+ return CliRunner()+++def ready() -> Iterator[None]:+ """Backend binary present and authenticated."""+ with (+ patch.object(ci_insights.shutil, "which", return_value="/usr/bin/mendral"),+ patch.object(ci_insights, "_capture", return_value="Authenticated"),+ ):+ yield+++def test_missing_binary_reports_install_hint(runner: CliRunner) -> None:+ with patch.object(ci_insights.shutil, "which", return_value=None):+ result = runner.invoke(ci_insights.ci_insights, [])+ assert result.exit_code != 0+ assert "brew install mendral-ai/tap/mendral" in result.output+++def test_unauthenticated_reports_login_hint(runner: CliRunner) -> None:+ with (+ patch.object(ci_insights.shutil, "which", return_value="/usr/bin/mendral"),+ patch.object(ci_insights, "_capture", return_value="Not authenticated. Run 'mendral auth login'."),+ ):+ result = runner.invoke(ci_insights.ci_insights, [])+ assert result.exit_code != 0+ assert "auth login" in result.output+++ "argv, expected",+ [+ ([], ("mendral", "here")),+ (["search", "flaky timeout"], ("mendral", "insight", "search", "flaky timeout")),+ (["view", "01ABC"], ("mendral", "insight", "view", "01ABC")),+ (["view", "01ABC", "--json"], ("mendral", "insight", "view", "01ABC", "--json")),+ ],+)+def test_verb_maps_to_backend_call(runner: CliRunner, ready: None, argv: list[str], expected: tuple[str, ...]) -> None:+ with patch.object(ci_insights, "_run", return_value=0) as run:+ result = runner.invoke(ci_insights.ci_insights, argv)+ assert result.exit_code == 0+ run.assert_called_once_with(*expected)++[email protected]("argv", [[], ["search", "x"], ["view", "01ABC"]])+def test_backend_exit_code_propagates(runner: CliRunner, ready: None, argv: list[str]) -> None:+ with patch.object(ci_insights, "_run", return_value=7):+ result = runner.invoke(ci_insights.ci_insights, argv)+ assert result.exit_code == 7++[email protected]("argv", [["--help"], ["search", "--help"], ["view", "--help"], ["plan", "--help"]])+def test_help_works_without_backend(runner: CliRunner, argv: list[str]) -> None:+ with patch.object(ci_insights.shutil, "which", return_value=None):+ result = runner.invoke(ci_insights.ci_insights, argv)+ assert result.exit_code == 0+ assert "Usage:" in result.output+ assert "not found" not in result.output+++_INSIGHT = {+ "actions": [+ {"id": "a1", "recommended": True, "status": "merged", "title": "Old fix", "full_plan": "merged plan"},+ {"id": "a2", "recommended": True, "status": "proposed", "title": "New fix", "full_plan": "do X then Y"},+ ]+}+++def test_plan_prints_actionable_recommended_plan(runner: CliRunner) -> None:+ with (+ patch.object(ci_insights.shutil, "which", return_value="/usr/bin/mendral"),+ patch.object(ci_insights, "_capture", side_effect=["Authenticated", json.dumps(_INSIGHT)]),+ ):+ result = runner.invoke(ci_insights.ci_insights, ["plan", "01XYZ"])+ assert result.exit_code == 0+ assert "New fix" in result.output+ assert "do X then Y" in result.output+++def test_plan_errors_when_no_actions(runner: CliRunner) -> None:+ with (+ patch.object(ci_insights.shutil, "which", return_value="/usr/bin/mendral"),+ patch.object(ci_insights, "_capture", side_effect=["Authenticated", json.dumps({"actions": []})]),+ ):+ result = runner.invoke(ci_insights.ci_insights, ["plan", "01XYZ"])+ assert result.exit_code != 0+ assert "No remediation plan" in result.output++[email protected]("payload", ["", "not json{", '{"actions": [null]}'])+def test_plan_reports_clean_error_on_bad_response(runner: CliRunner, payload: str) -> None:+ with (+ patch.object(ci_insights.shutil, "which", return_value="/usr/bin/mendral"),+ patch.object(ci_insights, "_capture", side_effect=["Authenticated", payload]),+ ):+ result = runner.invoke(ci_insights.ci_insights, ["plan", "01XYZ"])+ assert result.exit_code != 0+ assert "Traceback" not in result.output+++def test_plan_errors_when_recommended_action_has_no_plan_text(runner: CliRunner) -> None:+ insight = {"actions": [{"id": "a", "recommended": True, "status": "proposed", "full_plan": ""}]}+ with (+ patch.object(ci_insights.shutil, "which", return_value="/usr/bin/mendral"),+ patch.object(ci_insights, "_capture", side_effect=["Authenticated", json.dumps(insight)]),+ ):+ result = runner.invoke(ci_insights.ci_insights, ["plan", "01XYZ"])+ assert result.exit_code != 0+ assert "no plan text" in result.output+++def test_plan_warns_when_only_fix_is_merged(runner: CliRunner) -> None:+ insight = {"actions": [{"id": "a", "recommended": True, "status": "merged", "title": "X", "full_plan": "the plan"}]}+ with (+ patch.object(ci_insights.shutil, "which", return_value="/usr/bin/mendral"),+ patch.object(ci_insights, "_capture", side_effect=["Authenticated", json.dumps(insight)]),+ ):+ result = runner.invoke(ci_insights.ci_insights, ["plan", "01XYZ"])+ assert result.exit_code == 0+ assert "already been merged" in result.output+ assert "the plan" in result.output+++ "actions, expected_id",+ [+ ([], None),+ ([{"id": "a", "status": "merged"}], "a"),+ (+ [+ {"id": "a", "recommended": True, "status": "merged"},+ {"id": "b", "recommended": True, "status": "proposed"},+ ],+ "b",+ ),+ ([{"id": "a", "recommended": True, "status": "merged"}], "a"),+ (+ [+ {"id": "a", "recommended": False, "status": "proposed"},+ {"id": "b", "recommended": True, "status": "rejected"},+ ],+ "b",+ ),+ ],+)+def test_recommended_action_selection(actions: list[dict[str, object]], expected_id: str | None) -> None:+ chosen = ci_insights._recommended_action(actions)+ assert (chosen or {}).get("id") == expected_id