Skip to content

: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.

feat(ci): point hogli ci:insights at engineering analytics (#77581)

Raúl Negrón-Otero0f8afb660c60
diff --git a/.agents/skills/debugging-ci-failures/SKILL.md b/.agents/skills/debugging-ci-failures/SKILL.md
index 225b603a7766..2554698d194c 100644
--- a/.agents/skills/debugging-ci-failures/SKILL.md
+++ b/.agents/skills/debugging-ci-failures/SKILL.md
@@ -7,10 +7,10 @@ description: >
current CI or master status, or mentions a failing check, GitHub Actions run,
Depot runner, workflow, job, shard, flaky test, lint failure, typecheck
failure, snapshot diff, migration check, generated types drift, or skills
- build failure. Start with the `hogli ci:insights` digest (aggregated cross-run
- CI intelligence), then guides read-only inspection, failure classification,
- smallest local reproduction with hogli, and safe reporting without rerunning CI
- or posting to GitHub.
+ build failure. Start with the `hogli ci:insights` digest (cross-run CI history
+ from engineering analytics), then guides read-only inspection, failure
+ classification, smallest local reproduction with hogli, and safe reporting
+ without rerunning CI or posting to GitHub.
---
# Debugging PostHog CI failures
@@ -19,13 +19,18 @@ Find the first meaningful failure, classify it, reproduce the smallest useful
case locally when appropriate, and report the result. Avoid public-visible or
irreversible actions unless the user explicitly asks.
-Always start with the `hogli ci:insights` digest. It is the institutional,
-cross-run source of truth, and it is fresher and more reliable than scraping
-`gh run list` / the GitHub Actions API, which can lag or rate-limit.
+Always start with the `hogli ci:insights` digest. It aggregates across runs and
+branches, which `gh` cannot do cheaply, and tells you whether a failure is
+likely trunk-borne, gate-only, or isolated to a small set of branches. `gh` is
+authoritative for one run's current state and attribution. Use the digest to
+decide _what_ to inspect; use `gh` to confirm _whose_ failure it is and exactly
+what failed in a given run.
This skill triages and classifies. Once a failure is confirmed flaky, hand off
to the `fixing-flaky-tests` skill, which owns local reproduction, root-cause
-fixing, and N-run validation.
+fixing, and N-run validation. For "who broke master" — the culprit commit and
+the commit that fixed it — hand off to the `investigating-ci-failures` skill,
+which owns the green/red boundary analysis.
## Safety rules
@@ -47,31 +52,62 @@ overwrite unrelated work.
### 1. Start with CI insights (always first)
-`hogli ci:insights` is the institutional CI-intelligence backend. It aggregates
-cross-run history — recurring flakes, occurrence counts, confidence, and any
-proposed or merged fix — that a single run can't show. Consult it before any raw
-`gh` log archaeology; the raw GitHub Actions API can lag or rate-limit, while the
-insights digest is the freshest aggregated view.
+`hogli ci:insights` reads PostHog's own engineering analytics — the cross-run
+failure history a single run can't show. Consult it before any raw `gh` log
+archaeology.
```bash
hogli ci:insights # digest for the current repo + branch
hogli ci:insights search "<error or test name>" # match a 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 view <ref> # one failure in full
+hogli ci:insights view <ref> --logs # ...plus the failing log lines
```
- Broad question ("is CI red?", "is master green today?", "what's broken right
- now?"): the no-arg digest answers directly — it lists open / in-progress /
- resolved counts and the most recent insights with severity and confidence. You
- often do not need a target PR or run at all; report from the digest.
-- Specific failure: run `search "<error>"` to match it before reading logs. 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).
-
-`hogli ci:insights` prints a setup hint if the backend isn't installed or
-authenticated — if so, fall back to the `gh`-based inspection below. Surface what
-you find per the Safety rules — do not auto-apply a fix.
+ now?"): the no-arg digest answers directly. It gives the default-branch verdict
+ (how many workflows are failing on their latest run, and which), the live
+ failures grouped by state, the jobs red on trunk right now, a grouped feed of
+ default-branch failures, and the PR your branch belongs to. You often do not
+ need a target PR or run at all; report from the digest.
+- Specific failure: run `search "<error>"` to match it before reading logs, then
+ `view <ref>` on a row the digest or search printed. `--logs` prints the thinned
+ failing lines from that failure's latest run, which is usually enough to
+ classify without touching `gh`.
+
+Read each row's `state` as a triage ranking:
+
+| State | Means |
+| ---------------------- | ---------------------------------------------------------------------------- |
+| `breaking_master` | failing on the default branch and that job's latest run is still red |
+| `blocking_merge_queue` | failed only on merge-queue gate branches in the window |
+| `novel_burst` | new within a day, already spreading across branches, not on trunk yet |
+| `potentially_resolved` | hit trunk but that job's latest run is green again |
+| `flaky` | sporadic across two or more branches over more than a day |
+| `pr_only` | limited branch spread; job status may be missing or behind the failure lines |
+
+`potentially_resolved` is a hint, not a conclusion: confirm from run data before
+reporting a failure as already fixed.
+
+`blocking_merge_queue` proves a gate failure happened in the window, not that it
+still blocks landings. Check the current queue run with `gh` before reporting it
+as active. Likewise, confirm `pr_only` from the current run before assigning the
+failure to a PR; it is also the fallback when job status is missing or stale.
+
+Caveats to carry into whatever you report:
+
+- Failure grouping is pytest-only. Jest, Playwright, and cargo failures appear
+ only in the digest's grouped master-failures section, never as a row with a ref.
+- Every count is absolute, never a rate. Passing runs are not in this data, so
+ there is no denominator and no failure rate to quote.
+- A run's conclusion can lag until GitHub's `workflow_run` webhook settles it, so
+ during a live incident confirm a specific run against `gh`.
+
+If nobody has signed in on this machine, `hogli ci:insights` exits `78`. Treat
+exit `78` as "no CI insights available" and fall back to the `gh`-based
+inspection below — then tell the user they can run `hogli posthog:login`
+once, which opens a browser and needs no API key. Do not run it yourself: it
+waits on a consent screen you cannot see. Surface what you find per the Safety
+rules — do not auto-apply a fix.
### 2. Find the failing run (for a specific failure)
diff --git a/.agents/skills/fixing-flaky-tests/SKILL.md b/.agents/skills/fixing-flaky-tests/SKILL.md
index 18ac7402b537..e12c1bce5a25 100644
--- a/.agents/skills/fixing-flaky-tests/SKILL.md
+++ b/.agents/skills/fixing-flaky-tests/SKILL.md
@@ -28,7 +28,7 @@ For writing new Playwright tests that aren't flaky, use the `playwright-test` sk
## 1. Measure the failure rate — from GitHub, not from a digest
-The GitHub Actions API (or GitHub MCP) is the source of truth. `hogli ci:insights` is a digest, not an oracle — it can mislabel flaky-vs-deterministic, misstate the rate, and lag the API. Use it to _validate_ a hypothesis or pull historical context, never as the first move or the classification authority.
+The GitHub Actions API (or GitHub MCP) is the source of truth. `hogli ci:insights` is a digest, not an oracle — it can mislabel flaky-vs-deterministic, it lags the API until GitHub's webhook settles, and it cannot give you a rate at all: it reports absolute counts, because CI emits failures but omits ordinary passing runs, so there is no denominator. Use it to _validate_ a hypothesis or pull historical context, never as the first move or the classification authority.
Establish the timeline yourself from raw run data:
@@ -49,7 +49,7 @@ Read the timeline before you classify:
- **Interleaved pass/fail on adjacent commits** — the same unchanged test verified passing in some runs, failing in others → genuinely **flaky**; continue here.
- **A long unbroken failure streak** (say 30+ consecutive) is statistically incompatible with a flake — at any per-run rate below ~95%, `p^30 ≈ 0`. That is a **deterministic regression**: go to `debugging-ci-failures` and find the introducing commit (step 4).
-- **Both at once** is common: a latent flake whose rate jumped to ~100%. Find the transition (last green → first red); that boundary, not the digest's one-line guess, is what tells you what tipped it.
+- **Both at once** is common: a latent flake whose rate jumped to ~100%. Find the transition (last green → first red); that boundary, not the digest's one-line verdict, is what tells you what tipped it. The `investigating-ci-failures` skill has the boundary query if the failure reached master.
If a failure is reported as (or you suspect it is) **consistent**, don't serialize — measure the rate and attempt a repro **in parallel**.
@@ -59,10 +59,13 @@ Then confirm it is not already handled:
```bash
git log --oneline -10 -- <test_file_path> # recently fixed already?
-hogli ci:insights search "<test name or error>" # historical context / existing fix — corroborate against the run data, do not trust blindly
+hogli ci:insights search "<test name or error>" # cross-run history — corroborate against the run data, do not trust blindly
```
-An insight with a **merged fix** means the flake may already be resolved — read the fix, confirm _against the run data_ that it covers this failure, and report instead of re-fixing.
+`search` reports two surfaces; read each for what it actually claims:
+
+- **broken tests** (recent failure fingerprints, last 2 days). A `potentially_resolved` state means that job's latest default-branch run is green again — weak evidence a fix landed, not proof. Confirm _against the run data_ that it covers this failure before reporting instead of re-fixing.
+- **test health** (ranked by blast radius). `confirmed_flake` is the only classification backed by proof: one commit both failed and passed the test, via a re-run attempt going green or an in-job retry. `suspected_regression` means no recovery was recorded — absence of proof, not proof of a regression, so treat it as real until your own run data says otherwise.
### Corroborate with Trunk Flaky Tests
@@ -272,7 +275,7 @@ Run the surrounding file/suite once to confirm nothing depended on it, and carry
```text
Test: <file path>::<test name>
-Observed in CI: <measured rate from run data, e.g. 8/45 runs over 3h (gh run list); ci:insights corroborates>
+Observed in CI: <measured rate from run data, e.g. 8/45 runs over 3h (gh run list); ci:insights state corroborates>
Local repro: <command + conditions, e.g. 3/20 failures with neighbor X, maxWorkers=2 | not reproducible locally>
Root cause: <one or two sentences>
Outcome: fixed | re-leveled (<from> → <to>) | deleted
diff --git a/hogli.yaml b/hogli.yaml
index f4403ebe9028..3a44087f9038 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -1033,7 +1033,7 @@ tools:
hidden: true
ci:insights:
click: hogli_commands.ci_insights:ci_insights
- description: Show CI insights for the current repo + branch (search/view/plan subcommands)
+ description: What's broken in CI right now, from engineering analytics (search/view subcommands)
ci:preflight:
click: hogli_commands.ci_preflight:ci_preflight
description: Catch deterministic CI failures reachable from your diff before you push (advisory; --fix, --strict)
diff --git a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
index fa5502180e0f..a605ab558f07 100644
--- a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
+++ b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md
@@ -121,6 +121,7 @@ threshold aren't recorded, so there is no honest denominator.
| Question | Use |
| -------------------------------------- | ---------------------------------------------------------------------- |
| "What's broken across CI right now?" | `engineering-analytics-broken-tests` MCP tool (triaged, classified) |
+| Same, but from a terminal | `hogli ci:insights` — these endpoints, scoped to the checkout's repo |
| "Why did MY PR's CI fail?" | `engineering-analytics-ci-failure-logs` MCP tool (PR-scoped, grouped) |
| "Who broke master / when did X start?" | The two views, workflow above |
| "Is X flaky?" | Shape from `ci_failures` + the flaky-tests tool |
diff --git a/tools/hogli-commands/hogli_commands/ci_insights.py b/tools/hogli-commands/hogli_commands/ci_insights.py
index cc8483c75b71..cd6fff8f5ae9 100644
--- a/tools/hogli-commands/hogli_commands/ci_insights.py
+++ b/tools/hogli-commands/hogli_commands/ci_insights.py
@@ -1,140 +1,1161 @@
-"""CI insights for the current repo + branch.
+"""CI insights for the current repo + branch, read from PostHog's engineering analytics.
-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 a failure by test name or error text
+ hogli ci:insights view <ref> [--logs] # one failure, with its failing log lines
- 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
+A REST client over the named ``engineering_analytics`` endpoints, the same ones the in-app UI
+and the MCP tools read, so the domain rules are not copied here. This module only picks
+endpoints, summarizes, and renders.
-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.
+Missing or rejected credentials exit ``78`` (sysexits ``EX_CONFIG``) so the
+debugging-ci-failures skill can branch to its read-only ``gh`` fallback on the exit code
+rather than on message text. Diagnostics go to stderr, keeping stdout parseable.
+
+Output is JSON when stdout is not a terminal, so piped and agent callers get structure without
+passing a flag, and ``--json`` forces it in a tty. That JSON is this command's own summarized
+shape rather than an endpoint passthrough, because ``broken_tests`` alone returns 200 rows whose
+bytes are mostly hourly sparklines.
"""
from __future__ import annotations
+import os
+import sys
import json
import shutil
+import hashlib
import subprocess
-from typing import Any
+import unicodedata
+from collections.abc import Callable
+from concurrent.futures import Future, ThreadPoolExecutor
+from dataclasses import dataclass, replace
+from datetime import UTC, datetime
+from types import NoneType, UnionType
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ NoReturn,
+ NotRequired,
+ TypedDict,
+ TypeVar,
+ Union,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+ is_typeddict,
+)
+from urllib.parse import ParseResult, urlparse
import click
+import requests
+from click.core import ParameterSource
+
+from hogli_commands import posthog_auth
+
+_DEFAULT_HOST = "https://us.posthog.com"
+# The project holding the synced PostHog/posthog GitHub source. Committed rather than configured
+# because a project id is not a secret, the same reason hogli.yaml commits the telemetry write key.
+_DEFAULT_PROJECT_ID = "2"
+
+# The one scope these endpoints require, so a CI-triage credential cannot write anywhere.
+_SCOPES = ("engineering_analytics:read",)
+
+_EXIT_NOT_CONFIGURED = posthog_auth.EXIT_NOT_CONFIGURED
+
+_DIGEST_ROWS = 8
+_MAX_LISTED_CANDIDATES = 10
+_SEARCH_DEFAULT_DAYS = 7
+# Mirrors MAX_FLAKY_WINDOW_DAYS in products/engineering_analytics/backend/logic/suite_health.py.
+_MAX_FLAKY_DAYS = 30
+_FLAKY_SCAN_LIMIT = 200
+# Below this, a ref prefix matches too much to be a useful handle.
+_MIN_REF_PREFIX = 4
+
+# BrokenTestState, most urgent first. The endpoint already returns rows in this order, so this
+# drives the count summary only, never a client-side re-sort of the rows, which would put the
+# classifier's judgement in a second place.
+_STATE_MEANINGS: dict[str, str] = {
+ "breaking_master": "failing on the default branch, and that job's latest run is still red",
+ "blocking_merge_queue": "failed only on merge-queue gate branches on a commit the PR's own CI passed",
+ "novel_burst": "first seen within a day and already spreading across branches, not on trunk yet",
+ "potentially_resolved": "hit the default branch but that job is green again",
+ "flaky": "sporadic across two or more branches over more than a day",
+ "pr_only": "limited branch spread; confirm the current run before assigning it to a PR",
+}
+
+_SPARK_LEVELS = " ▁▂▃▄▅▆▇█"
+
+_SECTION_LABELS = {
+ "master": "default branch",
+ "broken": "broken tests",
+ "master_failures": "master failures",
+ "branch": "your branch",
+}
+
+# The JSON payload key each internal section name lands under, so `_unavailable` can name what a
+# consumer actually reads.
+_SECTION_KEYS = {
+ "master": "master",
+ "broken": "broken_tests",
+ "master_failures": "master_failures",
+ "branch": "branch_pull_requests",
+}
+
+# `search` reads a different pair of sections than the digest.
+_SEARCH_SECTION_KEYS = {"broken": "broken_tests", "flaky": "flaky_tests"}
+
+_CAVEATS = (
+ "Fingerprints are pytest-only, so jest/playwright/cargo breakage shows up under master failures, not above.\n"
+ "Counts are absolute, never rates, because passing runs are not in this data.\n"
+ "A run's conclusion can lag until GitHub's webhook settles it; confirm a specific run with `gh`."
+)
+
+
+_BrokenTestState = Literal[
+ "breaking_master",
+ "blocking_merge_queue",
+ "novel_burst",
+ "potentially_resolved",
+ "flaky",
+ "pr_only",
+]
+_FlakyTestClassification = Literal["confirmed_flake", "suspected_regression", "quarantined"]
+
+
+class _GitHubSource(TypedDict):
+ id: str
+ repo: str
+ prefix: str
+ synced: bool
+
+
+class _CurrentBranchHealth(TypedDict):
+ default_branch: str
+ settled_workflows: int
+ failing_workflows: int
+ failing_workflow_names: list[str]
+
+
+class _RepoRef(TypedDict):
+ provider: str
+ owner: str
+ name: str
+
+
+class _MasterFailureGroup(TypedDict):
+ repo: _RepoRef
+ workflow_name: str
+ failed_job: str
+ run_count: int
+ first_seen: str
+ last_seen: str
+ latest_run_id: int
+
+
+class _BrokenTestRow(TypedDict):
+ fingerprint: str
+ test_id: str
+ error_signature: str
+ job_name: str
+ repo: str
+ state: _BrokenTestState
+ first_seen: str
+ last_seen: str
+ occurrences: int
+ branches: int
+ master_hits: int
+ latest_run_id: int
+ latest_branch: str
+ trend_24h: list[int]
+
+
+class _BrokenTestSummary(TypedDict):
+ ref: str
+ fingerprint: str
+ test_id: str
+ error_signature: str
+ job_name: str
+ repo: str
+ state: _BrokenTestState
+ first_seen: str
+ last_seen: str
+ occurrences: int
+ branches: int
+ master_hits: int
+ latest_run_id: int
+ latest_branch: str
+
+
+class _BrokenTests(TypedDict):
+ rows: list[_BrokenTestRow]
+ breaking_master_jobs: list[str]
+ window_days: int
+ truncated: bool
+ limit: int
+
+
+class _FlakyTestItem(TypedDict):
+ runner: str
+ nodeid: str
+ selector: str
+ classification: _FlakyTestClassification
+ same_commit_recovery_run_count: int
+ failed_run_count: int
+ failed_pr_count: int
+ master_failed_run_count: int
+ quarantined_failed_run_count: int
+ last_signal_at: str
+
+
+class _FlakyTests(TypedDict):
+ items: list[_FlakyTestItem]
+ truncated: bool
+ limit: int
+
+
+class _BranchPRMatch(TypedDict):
+ repo: str
+ number: int
+ title: str | None
+ state: str | None
+
+
+class _FailureLogLine(TypedDict):
+ original_line: int | None
+ text: str
+
+
+class _FailureLogJob(TypedDict):
+ job_id: int
+ run_id: int
+ conclusion: str
+ branch: str
+ original_total_lines: int
+ line_count: int
+ lines: list[_FailureLogLine]
+ truncated: bool
+
+
+class _RunFailureLogs(TypedDict):
+ run_id: int
+ logs_available: bool
+ jobs: list[_FailureLogJob]
+ truncated: bool
+
-# 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 _invalid_payload(action: str, path: str, expected: str) -> NoReturn:
+ raise _ApiError(f"{action} returned an invalid payload: {path} must be {expected}.")
-def _run(*args: str) -> int:
- """Run the backend CLI inheriting stdio; return its exit code."""
- return subprocess.run(args).returncode
+def _validate_payload(value: object, expected: object, action: str, path: str = "response") -> None:
+ origin = get_origin(expected)
+ if is_typeddict(expected):
+ if not isinstance(value, dict) or not all(isinstance(key, str) for key in value):
+ _invalid_payload(action, path, "an object")
+ payload = cast(dict[str, object], value)
+ fields: dict[str, object] = get_type_hints(expected)
+ required = cast(frozenset[str], expected.__required_keys__)
+ for key in required:
+ if key not in payload:
+ _invalid_payload(action, f"{path}.{key}", "present")
+ for key, field_type in fields.items():
+ if key in payload:
+ _validate_payload(payload[key], field_type, action, f"{path}.{key}")
+ return
+ if origin is list:
+ if not isinstance(value, list):
+ _invalid_payload(action, path, "an array")
+ item_type = get_args(expected)[0]
+ for index, item in enumerate(value):
+ _validate_payload(item, item_type, action, f"{path}[{index}]")
+ return
+ if origin in {Union, UnionType}:
+ choices = get_args(expected)
+ if value is None and NoneType in choices:
+ return
+ remaining = tuple(choice for choice in choices if choice is not NoneType)
+ if len(remaining) == 1:
+ _validate_payload(value, remaining[0], action, path)
+ return
+ if origin is Literal:
+ if value not in get_args(expected):
+ _invalid_payload(action, path, f"one of {get_args(expected)!r}")
+ return
+ if expected is int:
+ if type(value) is not int:
+ _invalid_payload(action, path, "an integer")
+ return
+ if expected is bool:
+ if type(value) is not bool:
+ _invalid_payload(action, path, "a boolean")
+ return
+ if expected is str:
+ if not isinstance(value, str):
+ _invalid_payload(action, path, "a string")
+ return
+ raise TypeError(f"Unsupported API payload annotation: {expected!r}")
-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
+def _parse_sources(value: object, action: str) -> list[_GitHubSource]:
+ expected = list[_GitHubSource]
+ _validate_payload(value, expected, action)
+ return cast(list[_GitHubSource], value)
-class MendralBackend:
- """The only Mendral-aware code. Swap this class to change providers."""
+def _parse_current_branch_health(value: object, action: str) -> _CurrentBranchHealth:
+ _validate_payload(value, _CurrentBranchHealth, action)
+ return cast(_CurrentBranchHealth, value)
- 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"
+def _parse_master_failures(value: object, action: str) -> list[_MasterFailureGroup]:
+ expected = list[_MasterFailureGroup]
+ _validate_payload(value, expected, action)
+ return cast(list[_MasterFailureGroup], value)
+
+
+def _parse_broken_tests(value: object, action: str) -> _BrokenTests:
+ _validate_payload(value, _BrokenTests, action)
+ return cast(_BrokenTests, value)
+
+
+def _parse_flaky_tests(value: object, action: str) -> _FlakyTests:
+ _validate_payload(value, _FlakyTests, action)
+ return cast(_FlakyTests, value)
+
+
+def _parse_branch_matches(value: object, action: str) -> list[_BranchPRMatch]:
+ expected = list[_BranchPRMatch]
+ _validate_payload(value, expected, action)
+ return cast(list[_BranchPRMatch], value)
+
+
+def _parse_run_failure_logs(value: object, action: str) -> _RunFailureLogs:
+ _validate_payload(value, _RunFailureLogs, action)
+ return cast(_RunFailureLogs, value)
+
+
+def _terminal_text(value: object) -> str:
+ return "".join(character for character in str(value) if unicodedata.category(character) not in {"Cc", "Cf"})
+
+
+def _parse_http_origin(host: str) -> ParseResult | None:
+ try:
+ parsed = urlparse(host)
+ hostname = parsed.hostname
+ except ValueError:
+ return None
+ if (
+ parsed.scheme not in {"http", "https"}
+ or not hostname
+ or parsed.username
+ or parsed.password
+ or parsed.path
+ or parsed.params
+ or parsed.query
+ or parsed.fragment
+ ):
+ return None
+ return parsed
+
+
+class _ApiError(Exception):
+ def __init__(self, message: str, *, exit_code: int = 1) -> None:
+ safe_message = "\n".join(_terminal_text(line) for line in message.splitlines())
+ super().__init__(safe_message)
+ self.message = safe_message
+ self.exit_code = exit_code
+
+
+def _fail(error: _ApiError) -> NoReturn:
+ click.secho(error.message, fg="red", err=True)
+ raise SystemExit(error.exit_code)
+
+
+def _request(url: str, *, token: str, params: dict[str, str | int], timeout: float) -> requests.Response:
+ """One authenticated GET, and the only HTTP call in the module, so tests replace it wholesale."""
+ return requests.get(
+ url,
+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
+ params=params,
+ timeout=timeout,
+ )
+
+
+def _parse(response: requests.Response, action: str) -> object:
+ try:
+ payload: object = response.json()
+ return payload
+ except ValueError as exc:
+ raise _ApiError(f"{action} returned a non-JSON body: {exc}") from exc
+
+
+def _detail(response: requests.Response) -> str:
+ """The API's own explanation, user-safe on every status mapped in ``_explain``."""
+ try:
+ body = response.json()
+ except ValueError:
+ return response.text.strip()[:200]
+ if isinstance(body, dict):
+ return str(body.get("detail") or body)[:400]
+ return str(body)[:400]
+
+
+def _explain(response: requests.Response, action: str, *, host: str, project_id: str) -> _ApiError:
+ """An HTTP failure, restated as the next thing the reader should do about it."""
+ detail = _detail(response)
+ status = response.status_code
+ if status == 401:
+ return _ApiError(
+ f"{host} rejected the credential. It may be revoked, or issued for a different region.\n"
+ " Run `hogli posthog:logout` then `hogli posthog:login` to re-authorize.",
+ exit_code=_EXIT_NOT_CONFIGURED,
+ )
+ if status == 403 and "scope" in detail:
+ return _ApiError(
+ "The credential lacks 'engineering_analytics:read'.\n Run `hogli posthog:login` to authorize it.",
+ exit_code=_EXIT_NOT_CONFIGURED,
+ )
+ if status == 403:
+ return _ApiError(
+ f"{detail}\n Engineering analytics is flag-gated. Ask #team-devex to enable it for your account.",
+ exit_code=_EXIT_NOT_CONFIGURED,
+ )
+ if status == 400 and "source" in detail:
+ return _ApiError(
+ f"{detail}\n No GitHub source readable in project {project_id}. Check the project id, and that "
+ "your user has warehouse access to the source."
+ )
+ if status == 404:
+ return _ApiError(f"No {action} endpoint at {host} for project {project_id}. The project id may be wrong.")
+ return _ApiError(f"{action} failed ({status}): {detail}")
+
+
+@dataclass(frozen=True, kw_only=True)
+class _Api:
+ """A reader bound to one project, and after ``bound()`` to one repository."""
+
+ host: str
+ project_id: str
+ token: str
+ timeout: float
+ source_id: str | None = None
+ repo: str | None = None
+
+ def bound(self, *, source_id: str, repo: str) -> _Api:
+ return replace(self, source_id=source_id, repo=repo)
+
+ def _get(self, action: str, **params: str | int) -> object:
+ url = f"{self.host}/api/projects/{self.project_id}/engineering_analytics/{action}/"
+ query = {"source_id": self.source_id, "repo": self.repo, **params}
+ try:
+ response = _request(
+ url,
+ token=self.token,
+ params={key: value for key, value in query.items() if value},
+ timeout=self.timeout,
)
- # `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")
+ except requests.RequestException as exc:
+ raise _ApiError(f"Could not reach {self.host}: {exc}") from exc
+ if response.status_code == 200:
+ return _parse(response, action)
+ raise _explain(response, action, host=self.host, project_id=self.project_id)
+
+ def sources(self) -> list[_GitHubSource]:
+ action = "sources"
+ return _parse_sources(self._get(action), action)
+
+ def current_branch_health(self) -> _CurrentBranchHealth:
+ action = "current_branch_health"
+ return _parse_current_branch_health(self._get(action), action)
+
+ def broken_tests(self) -> _BrokenTests:
+ action = "broken_tests"
+ return _parse_broken_tests(self._get(action), action)
+
+ def master_failures(self) -> list[_MasterFailureGroup]:
+ action = "master_failures"
+ return _parse_master_failures(self._get(action, date_from="-24h"), action)
+
+ def flaky_tests(self, *, days: int) -> _FlakyTests:
+ action = "flaky_tests"
+ return _parse_flaky_tests(self._get(action, date_from=f"-{days}d", limit=_FLAKY_SCAN_LIMIT), action)
+
+ def resolve_branch(self, *, branch: str) -> list[_BranchPRMatch]:
+ action = "resolve_branch"
+ return _parse_branch_matches(self._get(action, branch=branch), action)
+
+ def run_failure_logs(self, *, run_id: int) -> _RunFailureLogs:
+ action = "run_failure_logs"
+ return _parse_run_failure_logs(self._get(action, run_id=run_id), action)
+
+
+def _git(*args: str) -> str | None:
+ """Trimmed stdout of a git command, None on any failure."""
+ try:
+ result = subprocess.run(["git", *args], capture_output=True, text=True, timeout=5.0)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ return result.stdout.strip() if result.returncode == 0 else None
+
+
+def _origin_repo() -> str | None:
+ """'owner/name' from the origin remote, for either URL form GitHub hands out."""
+ url = _git("remote", "get-url", "origin")
+ if not url:
+ return None
+ slug = url.removesuffix("/").removesuffix(".git")
+ slug = slug.partition(":")[2] if slug.startswith("git@") else "/".join(slug.split("/")[-2:])
+ return slug if slug.count("/") == 1 and all(slug.split("/")) else None
- 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 _current_branch() -> str | None:
+ """The checked-out branch, None on a detached HEAD."""
+ branch = _git("rev-parse", "--abbrev-ref", "HEAD")
+ return branch if branch and branch != "HEAD" else None
- 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")
+def _resolve_source(api: _Api, repo: str | None) -> _Api:
+ """Bind to the synced source for ``repo``, so a fork or unrelated checkout cannot
+ silently report another repository's CI as if it were yours."""
+ entries = api.sources()
+ wanted = (repo or _origin_repo() or "").lower()
+ if not wanted:
+ raise _ApiError("Could not read an 'owner/name' repo from the origin remote. Pass --repo.")
+ for entry in entries:
+ if entry["repo"].lower() == wanted and entry["synced"]:
+ return api.bound(source_id=entry["id"], repo=entry["repo"])
+ readable = ", ".join(sorted(entry["repo"] for entry in entries if entry["synced"])) or "none"
+ raise _ApiError(f"No synced GitHub source for {wanted} in project {api.project_id}. Readable repos: {readable}.")
+
+
+def _ref(fingerprint: str) -> str:
+ """An 8-hex handle for a failure fingerprint, usable as an argv token.
+
+ The fingerprint is ``test_id | error_signature``, so it carries spaces and a pipe. Hashing its
+ content keeps the handle stable across invocations with no cached state, and changes it exactly
+ when the fingerprint does (the fingerprint recipe is pytest-only v1 and evolves).
+ """
+ return hashlib.blake2s(fingerprint.encode(), digest_size=4).hexdigest()
+
+
+def _resolve_ref(rows: list[_BrokenTestRow], ref: str) -> _BrokenTestRow:
+ """The one row ``ref`` names, from a handle, handle prefix, full fingerprint, or test-id
+ substring. Matching several rows is an error, never a guess at which one was meant."""
+ lowered = ref.lower()
+ candidates = [row for row in rows if _ref(row["fingerprint"]) == lowered or row["fingerprint"] == ref]
+ if not candidates and len(ref) >= _MIN_REF_PREFIX:
+ candidates = [row for row in rows if _ref(row["fingerprint"]).startswith(lowered)]
+ if not candidates:
+ candidates = [row for row in rows if lowered in row["test_id"].lower()]
+ if len(candidates) == 1:
+ return candidates[0]
+ if not candidates:
+ raise _ApiError(f"No current failure matches {ref!r}. Refs come from `hogli ci:insights` or `search`.")
+ listed = "\n".join(f" {_ref(row['fingerprint'])} {row['test_id']}" for row in candidates[:_MAX_LISTED_CANDIDATES])
+ raise _ApiError(f"{ref!r} matches {len(candidates)} failures:\n{listed}")
+
+
+def _spark(counts: list[int]) -> str:
+ """A one-cell-per-hour histogram, scaled to its own peak.
+
+ An hour with no failures is blank rather than the shortest bar, because a row of shortest bars
+ reads as "it failed a little, constantly".
+ """
+ peak = max(counts, default=0)
+ top = len(_SPARK_LEVELS) - 1
+ return "".join(
+ _SPARK_LEVELS[0] if not count else _SPARK_LEVELS[min(top, max(1, round(count / peak * top)))]
+ for count in counts
+ )
+
+
+def _short(text: str, width: int) -> str:
+ text = _terminal_text(text)
+ return text if len(text) <= width else f"{text[: width - 1]}…"
+
+
+def _ago(timestamp: str | None) -> str:
+ """How long ago an ISO8601 stamp was, at the coarsest unit that still reads usefully."""
+ if not timestamp:
+ return "-"
+ try:
+ seen = datetime.fromisoformat(str(timestamp).replace("Z", "+00:00"))
+ except ValueError:
+ return "-"
+ seconds = (datetime.now(UTC) - seen).total_seconds()
+ for unit, size in (("d", 86400), ("h", 3600), ("m", 60)):
+ if seconds >= size:
+ return f"{int(seconds // size)}{unit}"
+ return "now"
+
+
+def _term_width() -> int:
+ return max(80, min(shutil.get_terminal_size((100, 24)).columns, 140))
+
+
+def _summarize_row(row: _BrokenTestRow) -> _BrokenTestSummary:
+ """A row as this command reports it: with its ref, and without the hourly sparkline that
+ dominates the endpoint's bytes."""
+ return _BrokenTestSummary(
+ ref=_ref(row["fingerprint"]),
+ fingerprint=row["fingerprint"],
+ test_id=row["test_id"],
+ error_signature=row["error_signature"],
+ job_name=row["job_name"],
+ repo=row["repo"],
+ state=row["state"],
+ first_seen=row["first_seen"],
+ last_seen=row["last_seen"],
+ occurrences=row["occurrences"],
+ branches=row["branches"],
+ master_hits=row["master_hits"],
+ latest_run_id=row["latest_run_id"],
+ latest_branch=row["latest_branch"],
+ )
+
+
+_ItemT = TypeVar("_ItemT")
+
+
+def _capped(rows: list[_ItemT], limit: int) -> list[_ItemT]:
+ """`--limit 0` asks for every row."""
+ return rows if limit == 0 else rows[:limit]
+
+
+def _render_rows(rows: list[_BrokenTestRow]) -> None:
+ """The failure table shared by the digest and search."""
+ test_width = max(24, _term_width() - 74)
+ click.echo(f" {'REF':<10}{'STATE':<22}{'OCC':>4}{'BR':>4}{'MSTR':>6}{'LAST':>7} {'24H':<24} TEST")
+ for row in rows:
+ state = _terminal_text(row["state"])
+ click.echo(
+ f" {_ref(row['fingerprint']):<10}{state:<22}"
+ f"{row['occurrences']:>4}{row['branches']:>4}{row['master_hits']:>6}"
+ f"{_ago(row['last_seen']):>7} {_spark(row['trend_24h']):<24} "
+ f"{_short(row['test_id'], test_width)}"
+ )
+
+
+def _render_master(health: _CurrentBranchHealth) -> None:
+ failing = health["failing_workflows"]
+ settled = health["settled_workflows"]
+ branch = _terminal_text(health["default_branch"])
+ label = f"{branch:<20}"
+ # A read that succeeded with nothing behind it is not a green default branch. Rendering it as
+ # OK claims every workflow passed, when the truth is that none has settled to be counted.
+ if not settled:
+ click.echo(f"{label}{click.style('NO DATA', fg='yellow', bold=True)} no workflow run has settled yet")
+ return
+ verdict = click.style("RED", fg="red", bold=True) if failing else click.style("OK", fg="green", bold=True)
+ click.echo(f"{label}{verdict} {failing} of {settled} workflows failing on their latest run")
+ for name in health["failing_workflow_names"]:
+ click.echo(f"{'':<20} {_terminal_text(name)}")
+
+
+def _render_broken(broken: _BrokenTests, *, limit: int) -> None:
+ rows = broken["rows"]
+ click.echo(f"{'broken tests':<20}{len(rows)} distinct failures over {broken['window_days']}d")
+ for state, count in _state_counts(rows).items():
+ if count:
+ click.echo(f"{'':<20}{state:<22}{count:>4}")
+ shown = _capped(rows, limit)
+ if shown:
+ click.echo("")
+ _render_rows(shown)
+ if len(shown) < len(rows) or broken["truncated"]:
+ cap = " (endpoint cap reached)" if broken["truncated"] else ""
+ click.echo(f"\n Showing {len(shown)} of {len(rows)}{cap}. `hogli ci:insights view <REF>` shows one failure.")
+ jobs = broken["breaking_master_jobs"]
+ if jobs:
+ click.echo(f"\n Jobs red on the default branch now: {', '.join(_terminal_text(job) for job in jobs[:4])}")
+
+
+def _render_master_failures(groups: list[_MasterFailureGroup]) -> None:
+ click.echo(f"{'master failures':<20}grouped over 24h, including runners without fingerprinting")
+ if not groups:
+ click.echo(f"{'':<20}none")
+ return
+ for group in groups[:_DIGEST_ROWS]:
+ click.echo(
+ f" {group['run_count']:>4} {_short(group['workflow_name'], 22):<24}"
+ f"{_short(group['failed_job'] or '(workflow level)', 34):<36}"
+ f"{_ago(group['last_seen']):>7} {group['latest_run_id']}"
+ )
+
+
+def _render_branch(branch: str, matches: list[_BranchPRMatch]) -> None:
+ click.echo(f"{'your branch':<20}{_terminal_text(branch)}")
+ if not matches:
+ click.echo(f"{'':<20}no open PR found: not pushed yet, no open PR, or a fork")
+ return
+ for match in matches[:3]:
+ number = _terminal_text(match["number"])
+ state = _terminal_text(match["state"] or "unknown")
+ title = _terminal_text(match["title"] or "")
+ click.echo(f"{'':<20}PR #{number} ({state}) {title}")
+
+
+def _state_counts(rows: list[_BrokenTestRow]) -> dict[str, int]:
+ return {state: sum(1 for row in rows if row["state"] == state) for state in _STATE_MEANINGS}
+
+
+_PayloadT_co = TypeVar("_PayloadT_co", covariant=True)
+
+
+@dataclass(frozen=True, kw_only=True)
+class _Section(Generic[_PayloadT_co]):
+ """One endpoint read: its payload, or the error standing in for it."""
+
+ data: _PayloadT_co | None = None
+ error: _ApiError | None = None
+
+
+class _DigestSections(TypedDict):
+ master: _Section[_CurrentBranchHealth]
+ broken: _Section[_BrokenTests]
+ master_failures: _Section[list[_MasterFailureGroup]]
+ branch: NotRequired[_Section[list[_BranchPRMatch]]]
+
+
+class _SearchSections(TypedDict):
+ broken: _Section[_BrokenTests]
+ flaky: _Section[_FlakyTests]
+
+
+_PayloadT = TypeVar("_PayloadT")
+
+
+def _settle(future: Future[_PayloadT]) -> _Section[_PayloadT]:
+ """Keep a section's error beside its slot so one failed read does not discard the rest."""
+ try:
+ return _Section(data=future.result())
+ except _ApiError as exc:
+ return _Section(error=exc)
+
+
+def _unavailable(sections: dict[str, _Section[object]], keys: dict[str, str]) -> dict[str, str]:
+ """The sections that failed, keyed by the payload key each lands under, so a consumer can join
+ the failure to the section it is missing. The internal names would not do: `broken` names
+ nothing in the payload, and `branch` collides with the branch name."""
+ return {keys[name]: section.error.message for name, section in sections.items() if section.error is not None}
+
+
+def _gather(api: _Api, branch: str | None) -> _DigestSections:
+ """Read every digest section concurrently, so the whole read costs the slowest call."""
+ with ThreadPoolExecutor(max_workers=4 if branch else 3) as pool:
+ master_future = pool.submit(api.current_branch_health)
+ broken_future = pool.submit(api.broken_tests)
+ master_failures_future = pool.submit(api.master_failures)
+ branch_future = pool.submit(api.resolve_branch, branch=branch) if branch else None
+ sections = _DigestSections(
+ master=_settle(master_future),
+ broken=_settle(broken_future),
+ master_failures=_settle(master_failures_future),
+ )
+ if branch_future is not None:
+ sections["branch"] = _settle(branch_future)
+ all_sections: list[_Section[object]] = [
+ sections["master"],
+ sections["broken"],
+ sections["master_failures"],
+ ]
+ if "branch" in sections:
+ all_sections.append(sections["branch"])
+ errors = [section.error for section in all_sections if section.error is not None]
+ # A credential or flag problem is global rather than one section's bad luck, so surface it whole.
+ fatal = next((error for error in errors if error.exit_code == _EXIT_NOT_CONFIGURED), None)
+ # Degradation is for a partial outage. When nothing came back there is no digest to render, and
+ # exiting 0 over a page of "unavailable" would read as "CI is fine".
+ if fatal is not None:
+ raise fatal
+ if len(errors) == len(all_sections):
+ raise errors[0]
+ return sections
+
+
+def _emit_json(payload: object) -> NoReturn:
+ click.echo(json.dumps(payload, indent=2, default=str))
+ raise SystemExit(0)
+
+
+@dataclass(frozen=True, kw_only=True)
+class _Options:
+ """The options every subcommand shares, declared once by ``_common_options``."""
+
+ repo: str | None
+ project: str
+ host: str
+ timeout: float
+ output_format: str
+ limit: int
+
+ def api(self) -> _Api:
+ host = self.host.rstrip("/")
+ parsed_host = _parse_http_origin(host)
+ if parsed_host is None:
+ raise _ApiError("--host must be an HTTP(S) origin without credentials, a path, a query, or a fragment.")
+ hostname = parsed_host.hostname or ""
+ is_posthog_cloud = parsed_host.scheme == "https" and (
+ hostname == "posthog.com" or hostname.endswith(".posthog.com")
+ )
+ if (environment_key := posthog_auth.key_in_env()) and not is_posthog_cloud:
+ raise _ApiError(
+ f"Refusing to send {environment_key.variable} to {host}.\n"
+ f" Unset it, then run `hogli posthog:login --host {host}` to use a host-bound credential.",
+ exit_code=_EXIT_NOT_CONFIGURED,
+ )
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.")
+ token = posthog_auth.token(scopes=_SCOPES, host=host)
+ except posthog_auth.AuthError as exc:
+ # Re-raised as this module's error so every failure exits through `_fail`, keeping the
+ # exit code and the stderr-only rule in one place.
+ raise _ApiError(exc.message, exit_code=exc.exit_code) from exc
+ return _Api(host=host, project_id=self.project, token=token, timeout=self.timeout)
+
+ def emits_json(self) -> bool:
+ if self.output_format == "json":
+ return True
+ return self.output_format == "auto" and not sys.stdout.isatty()
+
+
+def _options(ctx: click.Context, kwargs: dict[str, Any]) -> _Options:
+ """The shared options, merged across both places click can put them.
+
+ They are declared on the group and on every subcommand, so ``ci:insights --json view x`` parses
+ into the group while ``ci:insights view x --json`` parses into the subcommand. Reading either
+ set alone drops the other half and answers about the wrong repo or host, so precedence runs
+ subcommand-explicit, then group-explicit, then default.
+ """
+ given = {
+ name: value for name, value in kwargs.items() if ctx.get_parameter_source(name) is not ParameterSource.DEFAULT
+ }
+ # `--json` is documented as shorthand for `--format json`, so collapse it into that one field
+ # before merging. Kept separate, the two could disagree across the group/subcommand boundary and
+ # `--json view x --format text` would silently print JSON.
+ if given.pop("as_json", False):
+ given["output_format"] = "json"
+ inherited = ctx.parent.obj if ctx.parent is not None and isinstance(ctx.parent.obj, dict) else {}
+ ctx.obj = given
+ merged = {**kwargs, **inherited, **given}
+ merged.pop("as_json", None)
+ return _Options(**merged)
+
+
+def _common_options(func: Callable[..., None]) -> Callable[..., None]:
+ """Stack the shared options onto a command, so they parse either before or after the
+ subcommand. `_options` merges the two sides."""
+ options = [
+ click.option("--repo", help="'owner/name' to read; defaults to the origin remote."),
+ click.option(
+ "--project",
+ default=lambda: os.environ.get("POSTHOG_CI_INSIGHTS_PROJECT_ID") or _DEFAULT_PROJECT_ID,
+ help="PostHog project id holding the GitHub source.",
+ ),
+ click.option(
+ "--host",
+ default=lambda: os.environ.get("POSTHOG_CI_INSIGHTS_HOST") or _DEFAULT_HOST,
+ help="PostHog host to read from.",
+ ),
+ click.option(
+ "--timeout",
+ type=click.FloatRange(min=0, min_open=True),
+ default=30.0,
+ show_default=True,
+ help="Per-request timeout in seconds.",
+ ),
+ click.option("--json", "as_json", is_flag=True, help="Shorthand for --format json."),
+ click.option(
+ "--format",
+ "output_format",
+ type=click.Choice(["auto", "text", "json"]),
+ default="auto",
+ show_default=True,
+ help="'auto' emits JSON when stdout is not a terminal.",
+ ),
+ click.option(
+ "--limit",
+ type=click.IntRange(min=0),
+ default=_DIGEST_ROWS,
+ show_default=True,
+ help="Failures to show; 0 for every row.",
+ ),
+ ]
+ for option in reversed(options):
+ func = option(func)
+ return func
+
+
+# Each entry point resolves credentials in its own body rather than the group callback, so `--help`
+# (which short-circuits before the body) works with nothing configured. Every exit raises SystemExit
+# because the telemetry wrapper records its code, which click's ctx.exit() does not reach.
+ name="ci:insights",
+ invoke_without_command=True,
+ help="What's broken in CI right now, from engineering analytics.",
+)
+@_common_options
@click.pass_context
-def ci_insights(ctx: click.Context) -> None:
+def ci_insights(ctx: click.Context, **kwargs: Any) -> None:
+ options = _options(ctx, kwargs)
if ctx.invoked_subcommand is None:
- _BACKEND.ensure_ready()
- raise SystemExit(_BACKEND.digest())
+ _digest(options)
+
+
+def _digest_payload(api: _Api, branch: str | None, sections: _DigestSections, limit: int) -> dict[str, object]:
+ """The digest as `--json` reports it, summarized rather than passed through."""
+ broken = sections["broken"].data
+ rows = broken["rows"] if broken is not None else []
+ shown = _capped(rows, limit)
+ unavailable_sections: dict[str, _Section[object]] = {
+ "master": sections["master"],
+ "broken": sections["broken"],
+ "master_failures": sections["master_failures"],
+ }
+ if "branch" in sections:
+ unavailable_sections["branch"] = sections["branch"]
+ return {
+ "repo": api.repo,
+ "source_id": api.source_id,
+ "branch": branch,
+ "unavailable": _unavailable(unavailable_sections, _SECTION_KEYS),
+ "master": sections["master"].data,
+ # None, never a zero-filled section: a failed read rendered as `total: 0` is a complete,
+ # well-formed claim that nothing is broken, and JSON is the default for every non-tty caller.
+ "broken_tests": None
+ if sections["broken"].error is not None
+ else {
+ "window_days": broken["window_days"] if broken is not None else None,
+ "total": len(rows),
+ "shown": len(shown),
+ "truncated": broken["truncated"] if broken is not None else False,
+ "state_counts": _state_counts(rows),
+ "breaking_master_jobs": broken["breaking_master_jobs"] if broken is not None else [],
+ "rows": [_summarize_row(row) for row in shown],
+ },
+ "master_failures": sections["master_failures"].data,
+ "branch_pull_requests": sections["branch"].data if "branch" in sections else None,
+ }
+
+
+def _render_section(label: str, section: _Section[_PayloadT], render: Callable[[_PayloadT], None]) -> None:
+ click.echo("")
+ if section.error is not None:
+ click.secho(f"{label:<20}(unavailable: {section.error.message})", fg="yellow")
+ elif section.data is not None:
+ render(section.data)
+
+
+def _digest(options: _Options) -> NoReturn:
+ try:
+ api = _resolve_source(options.api(), options.repo)
+ branch = _current_branch()
+ sections = _gather(api, branch)
+ except _ApiError as exc:
+ _fail(exc)
+
+ if options.emits_json():
+ _emit_json(_digest_payload(api, branch, sections, options.limit))
+ click.secho(f"{api.repo} · CI insights · {options.host}", bold=True)
+ _render_section(_SECTION_LABELS["master"], sections["master"], _render_master)
+ _render_section(
+ _SECTION_LABELS["broken"], sections["broken"], lambda data: _render_broken(data, limit=options.limit)
+ )
+ _render_section(_SECTION_LABELS["master_failures"], sections["master_failures"], _render_master_failures)
+ if branch and "branch" in sections:
+ _render_section(_SECTION_LABELS["branch"], sections["branch"], lambda data: _render_branch(branch, data))
+ click.echo(f"\n{_CAVEATS}")
+ raise SystemExit(0)
-@ci_insights.command(name="search", help="Search CI insights by keyword or error string.")
+
+@ci_insights.command(name="search", help="Match a failure by test name or stable error text.")
@click.argument("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))
+ "--days",
+ # Ranged rather than clamped: the backend rejects a wider window, and silently narrowing the
+ # window someone asked for would answer a different question than the one they posed.
+ type=click.IntRange(1, _MAX_FLAKY_DAYS),
+ default=_SEARCH_DEFAULT_DAYS,
+ show_default=True,
+ help=f"Window for the test-health queue (max {_MAX_FLAKY_DAYS}). "
+ "Error text is only searchable over the last 2 days.",
+)
+@_common_options
+def search(ctx: click.Context, query: str, days: int, **kwargs: Any) -> NoReturn:
+ options = _options(ctx, kwargs)
+ needle = query.lower()
+ try:
+ api = _resolve_source(options.api(), options.repo)
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ broken_future = pool.submit(api.broken_tests)
+ flaky_future = pool.submit(api.flaky_tests, days=days)
+ sections = _SearchSections(broken=_settle(broken_future), flaky=_settle(flaky_future))
+ errors = [error for error in (sections["broken"].error, sections["flaky"].error) if error is not None]
+ # One section failing must not discard the other: they are independent reads, and the digest
+ # already degrades this way. Both failing means there is nothing to show.
+ if len(errors) == len(sections):
+ raise errors[0]
+ except _ApiError as exc:
+ _fail(exc)
+
+ broken_payload = sections["broken"].data
+ flaky_payload = sections["flaky"].data
+ broken = [
+ row
+ for row in (broken_payload["rows"] if broken_payload is not None else [])
+ if any(needle in value.lower() for value in (row["test_id"], row["error_signature"], row["job_name"]))
+ ]
+ flaky = [
+ item
+ for item in (flaky_payload["items"] if flaky_payload is not None else [])
+ if any(needle in value.lower() for value in (item["nodeid"], item["selector"]))
+ ]
+ shown_broken, shown_flaky = _capped(broken, options.limit), _capped(flaky, options.limit)
+ source_truncated = {
+ "broken_tests": broken_payload["truncated"] if broken_payload is not None else False,
+ "flaky_tests": flaky_payload["truncated"] if flaky_payload is not None else False,
+ }
+ truncated_sections = [
+ name
+ for name, truncated in source_truncated.items()
+ if truncated
+ or (name == "broken_tests" and len(shown_broken) < len(broken))
+ or (name == "flaky_tests" and len(shown_flaky) < len(flaky))
+ ]
+ if options.emits_json():
+ _emit_json(
+ {
+ "query": query,
+ "unavailable": _unavailable(
+ {"broken": sections["broken"], "flaky": sections["flaky"]}, _SEARCH_SECTION_KEYS
+ ),
+ "broken_tests": None
+ if sections["broken"].error is not None
+ else [_summarize_row(row) for row in shown_broken],
+ "flaky_tests": None if sections["flaky"].error is not None else shown_flaky,
+ "truncated": bool(truncated_sections),
+ "truncated_sections": truncated_sections,
+ }
+ )
+
+ # Two sections, never one merged ranking: these are different grains (failure lines from Logs
+ # versus CI runs from Traces) over different windows, so fusing them would invent a
+ # flaky-versus-broken verdict neither endpoint made.
+ click.secho("broken tests recent failure fingerprints, last 2 days", bold=True)
+ if sections["broken"].error is not None:
+ click.secho(f"{'':<20}unavailable: {sections['broken'].error.message}", fg="yellow")
+ elif broken:
+ _render_rows(shown_broken)
+ _note_truncation(len(shown_broken), len(broken), source_truncated=source_truncated["broken_tests"])
+ else:
+ suffix = " in returned rows" if source_truncated["broken_tests"] else ""
+ click.echo(f"{'':<20}no match{suffix}")
+ _note_truncation(0, 0, source_truncated=source_truncated["broken_tests"])
+ click.echo("")
+ click.secho(f"test health ranked by blast radius, last {days} days", bold=True)
+ if sections["flaky"].error is not None:
+ click.secho(f"{'':<20}unavailable: {sections['flaky'].error.message}", fg="yellow")
+ elif flaky:
+ _render_flaky(shown_flaky)
+ _note_truncation(len(shown_flaky), len(flaky), source_truncated=source_truncated["flaky_tests"])
+ else:
+ suffix = " in returned rows" if source_truncated["flaky_tests"] else ""
+ click.echo(f"{'':<20}no match{suffix}")
+ _note_truncation(0, 0, source_truncated=source_truncated["flaky_tests"])
+ if not broken and not flaky and not errors:
+ click.echo(
+ "\nError signatures normalize volatile numbers and hashes. Search stable text or a test name.\n"
+ "Only pytest error text from the last 2 days is searchable here; for older or non-pytest text, use\n"
+ "the investigating-ci-failures skill's SQL over engineering_analytics_ci_failures."
+ )
+ raise SystemExit(0)
+
+def _note_truncation(shown: int, total: int, *, source_truncated: bool) -> None:
+ if shown < total:
+ click.echo(f"{'':<20}Showing {shown} of {total}. Raise --limit, or 0 for every row.")
+ if source_truncated:
+ click.echo(f"{'':<20}Endpoint cap reached; more matches may exist.")
+
+
+def _render_flaky(items: list[_FlakyTestItem]) -> None:
+ click.echo(f" {'CLASSIFICATION':<24}{'RUNS':>5}{'PRS':>5}{'MSTR':>6} TEST")
+ for item in items:
+ click.echo(
+ f" {item['classification']:<24}{item['failed_run_count']:>5}"
+ f"{item['failed_pr_count']:>5}{item['master_failed_run_count']:>6} "
+ f"{_short(item['selector'] or item['nodeid'], max(24, _term_width() - 46))}"
+ )
+
+
+@ci_insights.command(name="view", help="Show one failure, optionally with its failing log lines.")
[email protected]("--logs", "with_logs", is_flag=True, help="Include the thinned failing log lines from its latest run.")
+@_common_options
+def view(ctx: click.Context, ref: str, with_logs: bool, **kwargs: Any) -> NoReturn:
+ options = _options(ctx, kwargs)
+ try:
+ api = _resolve_source(options.api(), options.repo)
+ row = _resolve_ref(api.broken_tests()["rows"], ref)
+ # The endpoint writes `latest_run_id or 0`, so 0 is "no run id recorded" rather than a run.
+ run_id = row["latest_run_id"]
+ logs = api.run_failure_logs(run_id=run_id) if with_logs and run_id else None
+ except _ApiError as exc:
+ _fail(exc)
+ if options.emits_json():
+ _emit_json({**_summarize_row(row), "logs": logs})
-@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))
+ state = _terminal_text(row["state"])
+ click.secho(f"{_ref(row['fingerprint'])} {_terminal_text(row['test_id'])}", bold=True)
+ click.echo(f"\n {'state':<18}{state}: {_STATE_MEANINGS.get(state, 'unclassified')}")
+ for label, value in (
+ ("error", row["error_signature"]),
+ ("job", row["job_name"]),
+ ("repo", row["repo"]),
+ ("occurrences", row["occurrences"]),
+ ("branches", row["branches"]),
+ ("master hits", row["master_hits"]),
+ ("first seen", row["first_seen"]),
+ ("last seen", row["last_seen"]),
+ ("latest run", row["latest_run_id"]),
+ ("latest branch", row["latest_branch"]),
+ ):
+ click.echo(f" {label:<18}{_terminal_text(value)}")
+ trend = row["trend_24h"]
+ click.echo(f" {'last 24h':<18}{_spark(trend)} ({sum(trend)} failures, oldest hour first)")
+ if with_logs:
+ if not run_id:
+ click.echo("\n No failure logs: this failure has no run id recorded, so there is nothing to fetch.")
+ else:
+ if logs is not None:
+ _render_logs(logs)
+ click.echo(f"\n{_CAVEATS}")
+ raise SystemExit(0)
-@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))
+def _render_logs(logs: _RunFailureLogs) -> None:
+ """The thinned failure region per failed job. Jobs carry an id but no name, so the run
+ id and branch are the only anchors back to GitHub."""
+ if not logs["logs_available"]:
+ click.echo("\n No failure logs: the run did not fail, or its logs aged out of the short Logs retention.")
+ return
+ for job in logs["jobs"]:
+ job_id = _terminal_text(job["job_id"])
+ run_id = _terminal_text(job["run_id"])
+ conclusion = _terminal_text(job["conclusion"])
+ branch = _terminal_text(job["branch"])
+ click.echo(f"\n job {job_id} · run {run_id} · {conclusion} · {branch}")
+ for line in job["lines"]:
+ number = line["original_line"]
+ text = _terminal_text(line["text"])
+ click.echo(f" {str(number) if number else '·':>7} {text}")
+ if job["truncated"]:
+ # A run-level cap also sets this flag on the last job, so the exact cap is unknown.
+ click.echo(" (job log output truncated)")
+ if logs["truncated"]:
+ click.echo("\n Run log cap reached; later lines or jobs may be missing.")
diff --git a/tools/hogli-commands/hogli_commands/tests/test_ci_insights.py b/tools/hogli-commands/hogli_commands/tests/test_ci_insights.py
index 8590e2ed8b4c..50728e8fb0a8 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_ci_insights.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_ci_insights.py
@@ -2,12 +2,165 @@ from __future__ import annotations
import json
from collections.abc import Iterator
+from typing import Any
import pytest
from unittest.mock import patch
from click.testing import CliRunner
-from hogli_commands import ci_insights
+from hogli_commands import ci_insights, posthog_auth
+
+_TOKEN = "phx_test_key_do_not_leak"
+
+_SOURCES = [
+ {"id": "src-other", "repo": "PostHog/posthog.com", "prefix": "website", "synced": True},
+ {"id": "src-unsynced", "repo": "PostHog/posthog", "prefix": "", "synced": False},
+ {"id": "src-good", "repo": "PostHog/posthog", "prefix": "eng_analytics", "synced": True},
+]
+
+_MASTER = {
+ "default_branch": "master",
+ "settled_workflows": 61,
+ "failing_workflows": 2,
+ "failing_workflow_names": ["ci-backend", "ci-frontend"],
+}
+
+
+def _row(test_id: str, *, state: str = "flaky", signature: str = "AssertionError", **overrides: Any) -> dict[str, Any]:
+ return {
+ "fingerprint": f"{test_id} | {signature}",
+ "test_id": test_id,
+ "error_signature": signature,
+ "job_name": "Django tests (1/19)",
+ "repo": "PostHog/posthog",
+ "state": state,
+ "first_seen": "2026-08-04T10:00:00Z",
+ "last_seen": "2026-08-04T13:00:00Z",
+ "occurrences": 4,
+ "branches": 2,
+ "master_hits": 0,
+ "latest_run_id": 30912586404,
+ "latest_branch": "feat/thing",
+ "trend_24h": [0] * 22 + [4, 0],
+ **overrides,
+ }
+
+
+_ROWS = [
+ _row("posthog/api/test/test_capture.py::test_event", state="breaking_master", master_hits=9),
+ # A third of this repo's PR rows are merge-queue gate attempts, so this state is common here.
+ _row("posthog/test/test_migrations.py::test_forward", state="blocking_merge_queue"),
+ _row("posthog/hogql/test/test_resolver.py::test_join", state="novel_burst"),
+ _row("products/logs/test_query.py::test_severity", state="pr_only"),
+]
+
+_BROKEN = {
+ "rows": _ROWS,
+ "breaking_master_jobs": ["ci-backend / Django tests"],
+ "window_days": 2,
+ "truncated": False,
+ "limit": 200,
+}
+
+_MASTER_FAILURES = [
+ {
+ "repo": {"provider": "github", "owner": "PostHog", "name": "posthog"},
+ "workflow_name": "ci-frontend",
+ "failed_job": "Jest tests",
+ "run_count": 18,
+ "first_seen": "2026-08-04T09:00:00Z",
+ "last_seen": "2026-08-04T13:00:00Z",
+ "latest_run_id": 30912401882,
+ }
+]
+
+_FLAKY = {
+ "items": [
+ {
+ "runner": "pytest",
+ "nodeid": "posthog/api/test/test_capture.py::test_event",
+ "selector": "posthog/api/test/test_capture.py::TestCapture::test_event",
+ "classification": "confirmed_flake",
+ "same_commit_recovery_run_count": 2,
+ "failed_run_count": 12,
+ "failed_pr_count": 5,
+ "master_failed_run_count": 1,
+ "quarantined_failed_run_count": 0,
+ "last_signal_at": "2026-08-04T13:00:00Z",
+ }
+ ],
+ "truncated": False,
+ "limit": 200,
+}
+
+_PAYLOADS: dict[str, Any] = {
+ "sources": _SOURCES,
+ "current_branch_health": _MASTER,
+ "broken_tests": _BROKEN,
+ "master_failures": _MASTER_FAILURES,
+ "flaky_tests": _FLAKY,
+ "resolve_branch": [{"repo": "PostHog/posthog", "number": 77271, "title": "Do a thing", "state": "open"}],
+ "run_failure_logs": {
+ "run_id": 30912586404,
+ "logs_available": True,
+ "truncated": False,
+ "jobs": [
+ {
+ "job_id": 1,
+ "run_id": 30912586404,
+ "conclusion": "failure",
+ "branch": "feat/thing",
+ "original_total_lines": 900,
+ "line_count": 2,
+ "truncated": False,
+ "lines": [{"original_line": 42, "text": "FAILED x::y"}, {"original_line": None, "text": "... 3 lines"}],
+ }
+ ],
+ },
+}
+
+
+class _Response:
+ def __init__(self, status_code: int, payload: Any) -> None:
+ self.status_code = status_code
+ self._payload = payload
+ self.text = json.dumps(payload) if payload is not None else ""
+
+ def json(self) -> Any:
+ if self._payload is None:
+ raise ValueError("no body")
+ return self._payload
+
+
+class _Recorder:
+ def __init__(
+ self,
+ *,
+ status: int = 200,
+ payload: Any = None,
+ fail: str | None = None,
+ overrides: dict[str, Any] | None = None,
+ ) -> None:
+ self.calls: list[dict[str, Any]] = []
+ self._status = status
+ self._payload = payload
+ self._fail = fail
+ self._overrides = overrides or {}
+
+ def __call__(self, url: str, *, token: str, params: dict[str, Any], timeout: float) -> _Response:
+ self.calls.append({"url": url, "token": token, "params": params, "timeout": timeout})
+ action = url.rstrip("/").rsplit("/", 1)[-1]
+ if self._status != 200 and action != "sources":
+ return _Response(self._status, self._payload)
+ if self._fail == action:
+ return _Response(500, {"detail": "upstream exploded"})
+ return _Response(200, self._overrides.get(action, _PAYLOADS[action]))
+
+ def actions(self) -> set[str]:
+ return {call["url"].rstrip("/").rsplit("/", 1)[-1] for call in self.calls}
+
+ def params_for(self, action: str) -> dict[str, Any]:
+ return next(call["params"] for call in self.calls if call["url"].rstrip("/").endswith(action))
@pytest.fixture
@@ -15,150 +168,435 @@ 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"),
[email protected](autouse=True)
+def repo_checkout() -> Iterator[None]:
+ # Stand in a PostHog/posthog checkout on a feature branch.
+ with patch.object(
+ ci_insights,
+ "_git",
+ side_effect=lambda *args: "[email protected]:PostHog/posthog.git" if args[0] == "remote" else "feat/thing",
):
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
+# A signed-in caller. How a token is obtained is posthog_auth's contract, tested there; this suite
+# is about what ci:insights does once it has one.
[email protected](autouse=True)
+def token(monkeypatch: pytest.MonkeyPatch) -> None:
+ for var in posthog_auth.KEY_ENV_VARS:
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("POSTHOG_PERSONAL_API_KEY", _TOKEN)
-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
+def _invoke(runner: CliRunner, argv: list[str], recorder: _Recorder) -> Any:
+ with patch.object(ci_insights, "_request", recorder):
+ return runner.invoke(ci_insights.ci_insights, argv)
+
+
+# `hogli ci:insights --help` is exercised for every manifest `click:` entry by
+# tools/hogli/tests/test_cli.py, so it has to work with nothing configured, which is why credentials
+# are resolved inside each command body rather than the group callback.
[email protected]("argv", [["--help"], ["search", "--help"], ["view", "--help"]])
+def test_help_works_without_a_configured_key(
+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch, argv: list[str]
+) -> None:
+ monkeypatch.delenv("POSTHOG_PERSONAL_API_KEY", raising=False)
+ result = runner.invoke(ci_insights.ci_insights, argv)
+ assert result.exit_code == 0
+ assert "Usage:" in result.output
+ assert "personal API key" not in result.output
+
+
+# The debugging-ci-failures skill branches to `gh` on exit 78, so the code is contract, including
+# when the failure comes from the shared auth module rather than from this one.
+def test_an_unauthenticated_caller_exits_not_configured_with_the_hint_on_stderr(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ for var in posthog_auth.KEY_ENV_VARS:
+ monkeypatch.delenv(var, raising=False)
+ with patch.object(posthog_auth, "load", return_value=None):
+ result = CliRunner(mix_stderr=False).invoke(ci_insights.ci_insights, [])
+ assert result.exit_code == posthog_auth.EXIT_NOT_CONFIGURED
+ assert "posthog:login" in result.stderr
+ # Diagnostics stay off stdout so `--format json` consumers never parse them.
+ assert result.stdout == ""
+
+
+# A page of "unavailable" sections exiting 0 would read as "CI is fine".
+def test_digest_fails_when_no_section_came_back(runner: CliRunner) -> None:
+ result = _invoke(runner, ["--format", "text"], _Recorder(status=503, payload={"detail": "down"}))
+ assert result.exit_code == 1
+ assert "unavailable" not in result.output
+
+
+def test_request_shape_and_no_key_in_output(runner: CliRunner) -> None:
+ recorder = _Recorder()
+ result = _invoke(runner, ["--format", "text"], recorder)
+ assert result.exit_code == 0
+ broken = next(call for call in recorder.calls if call["url"].endswith("broken_tests/"))
+ assert broken["url"] == "https://us.posthog.com/api/projects/2/engineering_analytics/broken_tests/"
+ assert broken["token"] == _TOKEN
+ assert broken["params"] == {"source_id": "src-good", "repo": "PostHog/posthog"}
+ assert recorder.params_for("master_failures")["date_from"] == "-24h"
+ # A leaked key would land in every agent transcript that ran this command.
+ assert _TOKEN not in result.output
+
+
+def test_environment_key_is_not_sent_to_a_non_posthog_host(runner: CliRunner, monkeypatch: pytest.MonkeyPatch) -> None:
+ recorder = _Recorder()
+ monkeypatch.setenv("POSTHOG_CI_INSIGHTS_HOST", "https://attacker.example")
+ result = _invoke(runner, ["--format", "text"], recorder)
+ assert result.exit_code == posthog_auth.EXIT_NOT_CONFIGURED
+ assert recorder.calls == []
+ assert "Refusing to send POSTHOG_PERSONAL_API_KEY" in result.output
+ assert "hogli posthog:login --host https://attacker.example" in result.output
+
+
+def test_host_must_be_an_origin(runner: CliRunner) -> None:
+ recorder = _Recorder()
+ result = _invoke(runner, ["--host", "https://us.posthog.com/api", "--format", "text"], recorder)
+ assert result.exit_code == 1
+ assert recorder.calls == []
+ assert "must be an HTTP(S) origin" in result.output
@pytest.mark.parametrize(
- "argv, expected",
+ "status, detail, expected_exit, expected_text",
[
- ([], ("mendral", "here")),
- (["search", "flaky timeout"], ("mendral", "insight", "search", "flaky timeout")),
- (["view", "01ABC"], ("mendral", "insight", "view", "01ABC")),
- (["view", "01ABC", "--json"], ("mendral", "insight", "view", "01ABC", "--json")),
+ (401, "Invalid token", 78, "rejected the credential"),
+ (403, "API key missing required scope 'engineering_analytics:read'", 78, "engineering_analytics:read"),
+ (403, "This action requires feature flag 'engineering-analytics'", 78, "flag-gated"),
+ (400, "Connect a GitHub data warehouse source to use engineering analytics.", 1, "warehouse access"),
+ (404, "Not found.", 1, "project id may be wrong"),
+ (500, "boom", 1, "failed (500)"),
],
)
-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)
+def test_http_failures_become_actionable_messages(
+ runner: CliRunner, status: int, detail: str, expected_exit: int, expected_text: str
+) -> None:
+ recorder = _Recorder(status=status, payload={"detail": detail})
+ result = _invoke(runner, [], recorder)
+ assert result.exit_code == expected_exit
+ assert expected_text in result.output
+ assert "Traceback" not in result.output
+
+
+def test_api_payload_schema_drift_is_reported_before_rendering(runner: CliRunner) -> None:
+ broken = {**_BROKEN, "rows": [{**_ROWS[0], "occurrences": "four"}]}
+ result = _invoke(
+ runner,
+ ["view", "test_capture", "--format", "text"],
+ _Recorder(overrides={"broken_tests": broken}),
+ )
+ assert result.exit_code == 1
+ assert "broken_tests returned an invalid payload" in result.output
+ assert "response.rows[0].occurrences must be an integer" in result.output
+
+
+# Reading an unsynced or unrelated source would report another repo's CI as yours.
+ "repo, expected",
+ [
+ ("PostHog/posthog", "src-good"),
+ ("posthog/POSTHOG", "src-good"),
+ ("PostHog/posthog.com", "src-other"),
+ ],
+)
+def test_source_binding_prefers_the_synced_entry(runner: CliRunner, repo: str, expected: str) -> None:
+ recorder = _Recorder()
+ result = _invoke(runner, ["--repo", repo, "--format", "text"], recorder)
assert result.exit_code == 0
- run.assert_called_once_with(*expected)
+ assert recorder.params_for("broken_tests")["source_id"] == 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
+def test_unknown_repo_names_what_the_caller_can_read(runner: CliRunner) -> None:
+ result = _invoke(runner, ["--repo", "PostHog/nope"], _Recorder())
+ assert result.exit_code == 1
+ assert "PostHog/posthog" in result.output
[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)
+def test_digest_reports_every_row_state_and_discloses_the_cap(runner: CliRunner) -> None:
+ recorder = _Recorder()
+ result = _invoke(runner, ["--format", "text", "--limit", "2"], recorder)
assert result.exit_code == 0
- assert "Usage:" in result.output
- assert "not found" not in result.output
+ assert "master" in result.output and "2 of 61 workflows failing" in result.output
+ assert "4 distinct failures over 2d" in result.output
+ assert "Showing 2 of 4" in result.output
+ assert "PR #77271" in result.output
+ # Every state present in the rows is named, so a class of failure can't go unmentioned.
+ for state in ("breaking_master", "blocking_merge_queue", "novel_burst", "pr_only"):
+ assert state 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"},
- ]
-}
+# A read that succeeds with no workflow behind it says nothing about the default branch. Rendering
+# it as OK claims every workflow passed, which is the "CI is fine" misreport this digest exists to
+# avoid, and the skills tell agents to report master health from here.
+def test_digest_does_not_call_the_default_branch_green_without_data(runner: CliRunner) -> None:
+ empty = {
+ "default_branch": "master",
+ "settled_workflows": 0,
+ "failing_workflows": 0,
+ "failing_workflow_names": [],
+ }
+ recorder = _Recorder(overrides={"current_branch_health": empty})
+ result = _invoke(runner, ["--format", "text"], recorder)
+ assert result.exit_code == 0
+ assert "NO DATA" in result.output
+ assert "0 of 0 workflows failing" not in result.output
-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"])
+# A partial outage is when this read is worth most, so it must not be all-or-nothing.
+def test_digest_degrades_one_section_without_losing_the_rest(runner: CliRunner) -> None:
+ result = _invoke(runner, ["--format", "text"], _Recorder(fail="master_failures"))
assert result.exit_code == 0
- assert "New fix" in result.output
- assert "do X then Y" in result.output
+ assert "unavailable" in result.output
+ assert "4 distinct failures" 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
+# A zero-filled section is a complete, well-formed claim that nothing is broken. JSON is the default
+# for every non-tty caller, and the skills tell agents to report from the digest.
+def test_digest_json_reports_a_failed_section_as_null_not_as_zero(runner: CliRunner) -> None:
+ result = _invoke(runner, ["--json"], _Recorder(fail="broken_tests"))
+ assert result.exit_code == 0
+ payload = json.loads(result.output)
+ assert payload["broken_tests"] is None
+ assert "broken_tests" in payload["unavailable"]
[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
+# Keyed by the internal section name, `broken` and `branch` name nothing in the payload, so a
+# consumer cannot join the failure to the section, and `branch` collides with the branch name.
+ "failed, key",
+ [
+ ("broken_tests", "broken_tests"),
+ ("resolve_branch", "branch_pull_requests"),
+ ("master_failures", "master_failures"),
+ ],
+)
+def test_digest_json_keys_unavailable_by_the_section_it_describes(runner: CliRunner, failed: str, key: str) -> None:
+ result = _invoke(runner, ["--json"], _Recorder(fail=failed))
+ payload = json.loads(result.output)
+ assert list(payload["unavailable"]) == [key]
+ assert key in payload
-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
+# `--limit` is accepted on every subcommand, so text and --json must agree on how many matches
+# exist: capping text silently while --json returns everything hides matches from one of them.
+def test_search_honors_limit_and_discloses_what_it_dropped(runner: CliRunner) -> None:
+ rows = [_row(f"posthog/test_{index}.py::test_it") for index in range(25)]
+ broken = {**_BROKEN, "rows": rows}
+ text = _invoke(
+ runner,
+ ["search", "test_it", "--format", "text", "--limit", "3"],
+ _Recorder(overrides={"broken_tests": broken}),
+ )
+ assert text.exit_code == 0
+ assert text.output.count("posthog/test_") == 3
+ assert "Showing 3 of 25" in text.output
+ every = _invoke(
+ runner, ["search", "test_it", "--json", "--limit", "0"], _Recorder(overrides={"broken_tests": broken})
+ )
+ assert len(json.loads(every.output)["broken_tests"]) == 25
-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"])
+# The backend caps the flaky window at 30 days and 400s past it, which would discard the healthy
+# broken-tests half of the search too.
+def test_search_rejects_a_window_the_backend_will_not_serve(runner: CliRunner) -> None:
+ result = _invoke(runner, ["search", "x", "--days", "45"], _Recorder())
+ assert result.exit_code == 2
+ assert "30" in result.output
+
+
+# Independent reads: raising the first error would throw away results that came back fine.
+def test_search_keeps_one_section_when_the_other_fails(runner: CliRunner) -> None:
+ result = _invoke(runner, ["search", "test_event", "--format", "text"], _Recorder(fail="flaky_tests"))
+ assert result.exit_code == 0
+ # The ref, not the test id: the id is truncated to the terminal width when rendered.
+ assert ci_insights._ref(_ROWS[0]["fingerprint"]) in result.output
+ assert "test health" in result.output
+ assert "unavailable: flaky_tests failed" in result.output
+
+
+def test_search_json_marks_a_failed_section_as_unavailable(runner: CliRunner) -> None:
+ result = _invoke(runner, ["search", "test_event", "--json"], _Recorder(fail="flaky_tests"))
assert result.exit_code == 0
- assert "already been merged" in result.output
- assert "the plan" in result.output
+ payload = json.loads(result.output)
+ assert payload["broken_tests"]
+ assert payload["flaky_tests"] is None
+ assert "flaky_tests" in payload["unavailable"]
+def test_search_discloses_when_the_endpoint_could_have_omitted_matches(runner: CliRunner) -> None:
+ broken = {**_BROKEN, "rows": [], "truncated": True}
+ recorder = _Recorder(overrides={"broken_tests": broken})
+ text_result = _invoke(runner, ["search", "not_returned", "--format", "text"], recorder)
+ assert text_result.exit_code == 0
+ assert "no match in returned rows" in text_result.output
+ assert "Endpoint cap reached; more matches may exist" in text_result.output
+
+ json_result = _invoke(runner, ["search", "not_returned", "--json"], _Recorder(overrides={"broken_tests": broken}))
+ payload = json.loads(json_result.output)
+ assert payload["truncated"] is True
+ assert payload["truncated_sections"] == ["broken_tests"]
+
+
+# The endpoint writes `latest_run_id or 0`, so 0 means no run id was recorded. Treating it as absent
+# blames log retention, which has nothing to do with the real cause.
+def test_view_logs_explains_a_missing_run_id_rather_than_blaming_retention(runner: CliRunner) -> None:
+ broken = {**_BROKEN, "rows": [_row("posthog/test_norun.py::test_it", latest_run_id=0)]}
+ recorder = _Recorder(overrides={"broken_tests": broken})
+ result = _invoke(runner, ["view", "test_norun", "--logs", "--format", "text"], recorder)
+ assert result.exit_code == 0
+ assert "no run id recorded" in result.output
+ assert "run_failure_logs" not in recorder.actions()
+
+
+# Auto-JSON plus an endpoint passthrough would dump the full payload into transcripts.
+def test_digest_json_carries_only_the_shown_rows_and_no_sparklines(runner: CliRunner) -> None:
+ result = _invoke(runner, ["--json", "--limit", "1"], _Recorder())
+ assert result.exit_code == 0
+ payload = json.loads(result.output)
+ assert payload["broken_tests"]["total"] == 4
+ assert len(payload["broken_tests"]["rows"]) == 1
+ assert payload["broken_tests"]["state_counts"]["breaking_master"] == 1
+ assert "trend_24h" not in payload["broken_tests"]["rows"][0]
+ assert payload["broken_tests"]["rows"][0]["ref"] == ci_insights._ref(_ROWS[0]["fingerprint"])
+
+
+# CliRunner's stdout is not a tty, so "auto" must resolve to JSON there.
@pytest.mark.parametrize(
- "actions, expected_id",
+ "argv, expect_json",
[
- ([], 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",
- ),
+ ([], True),
+ (["--format", "text"], False),
+ (["--json"], True),
+ # These options are declared on the group AND on every subcommand, so a value given
+ # on one side must not be lost to the other side's default, and `--json` must not
+ # outrank an explicit `--format` across that boundary.
+ (["--json", "search", "test_capture"], True),
+ (["search", "test_capture", "--json"], True),
+ (["--json", "search", "test_capture", "--format", "text"], False),
+ (["--format", "text", "search", "test_capture", "--json"], True),
+ (["--format", "text", "search", "test_capture"], False),
],
)
-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
+def test_format_resolution(runner: CliRunner, argv: list[str], expect_json: bool) -> None:
+ result = _invoke(runner, argv, _Recorder())
+ assert result.exit_code == 0
+ assert result.output.lstrip().startswith("{") is expect_json
+
+
+# Dropping a group-level --repo/--host would silently answer about a different repo.
[email protected]("argv", [["--repo", "PostHog/posthog.com", "view", "test_capture"], ["view", "test_capture"]])
+def test_subcommands_inherit_group_level_options(runner: CliRunner, argv: list[str]) -> None:
+ recorder = _Recorder()
+ result = _invoke(runner, [*argv, "--format", "text"], recorder)
+ assert result.exit_code == 0
+ expected = "src-other" if "--repo" in argv else "src-good"
+ assert recorder.params_for("broken_tests")["source_id"] == expected
+
+
+def test_ref_is_stable_and_short() -> None:
+ ref = ci_insights._ref(_ROWS[0]["fingerprint"])
+ assert ref == ci_insights._ref(_ROWS[0]["fingerprint"])
+ assert len(ref) == 8
+ assert ref != ci_insights._ref(_ROWS[1]["fingerprint"])
+
+
+# A ref printed by the digest has to be usable by view, so the two must not drift.
[email protected]("ref_of", ["full_ref", "prefix", "fingerprint", "test_id_substring"])
+def test_view_resolves_every_accepted_ref_form(runner: CliRunner, ref_of: str) -> None:
+ row = _ROWS[0]
+ ref = {
+ "full_ref": ci_insights._ref(row["fingerprint"]),
+ "prefix": ci_insights._ref(row["fingerprint"])[:4],
+ "fingerprint": row["fingerprint"],
+ "test_id_substring": "test_capture",
+ }[ref_of]
+ result = _invoke(runner, ["view", ref, "--format", "text"], _Recorder())
+ assert result.exit_code == 0
+ assert row["test_id"] in result.output
+ assert "breaking_master: failing on the default branch" in result.output
+
+
+def test_view_lists_candidates_when_a_ref_is_ambiguous(runner: CliRunner) -> None:
+ result = _invoke(runner, ["view", "test_", "--format", "text"], _Recorder())
+ assert result.exit_code == 1
+ assert "matches 4 failures" in result.output
+
+
+def test_view_points_at_the_digest_for_an_unknown_ref(runner: CliRunner) -> None:
+ result = _invoke(runner, ["view", "deadbeef", "--format", "text"], _Recorder())
+ assert result.exit_code == 1
+ assert "hogli ci:insights" in result.output
+
+
+def test_view_logs_reads_the_rows_latest_run(runner: CliRunner) -> None:
+ recorder = _Recorder()
+ result = _invoke(runner, ["view", "test_capture", "--logs", "--format", "text"], recorder)
+ assert result.exit_code == 0
+ assert recorder.params_for("run_failure_logs")["run_id"] == _ROWS[0]["latest_run_id"]
+ assert "FAILED x::y" in result.output
+
+
+def test_view_logs_discloses_the_run_level_cap_without_mislabeling_the_job(runner: CliRunner) -> None:
+ logs = {
+ **_PAYLOADS["run_failure_logs"],
+ "truncated": True,
+ "jobs": [{**_PAYLOADS["run_failure_logs"]["jobs"][0], "truncated": True}],
+ }
+ result = _invoke(
+ runner,
+ ["view", "test_capture", "--logs", "--format", "text"],
+ _Recorder(overrides={"run_failure_logs": logs}),
+ )
+ assert result.exit_code == 0
+ assert "Run log cap reached; later lines or jobs may be missing." in result.output
+ assert "(job log output truncated)" in result.output
+ assert "per-job line cap" not in result.output
+
+
+def test_view_logs_strips_terminal_control_characters(runner: CliRunner) -> None:
+ logs = {
+ **_PAYLOADS["run_failure_logs"],
+ "jobs": [
+ {
+ **_PAYLOADS["run_failure_logs"]["jobs"][0],
+ "lines": [{"original_line": 42, "text": "\x1b]52;c;payload\x07\nFAILED x::y"}],
+ }
+ ],
+ }
+ result = _invoke(
+ runner,
+ ["view", "test_capture", "--logs", "--format", "text"],
+ _Recorder(overrides={"run_failure_logs": logs}),
+ )
+ assert result.exit_code == 0
+ assert "\x1b" not in result.output
+ assert "\x07" not in result.output
+ assert "]52;c;payloadFAILED x::y" in result.output
+
+
+# Merging failure lines with the test-health queue would invent a verdict neither made.
+def test_search_keeps_the_two_grains_in_separate_sections(runner: CliRunner) -> None:
+ recorder = _Recorder()
+ result = _invoke(runner, ["search", "test_capture", "--format", "text"], recorder)
+ assert result.exit_code == 0
+ assert "broken tests" in result.output and "test health" in result.output
+ assert "confirmed_flake" in result.output
+ assert recorder.params_for("flaky_tests")["date_from"] == "-7d"
+
+
+def test_search_with_no_match_states_what_it_cannot_see(runner: CliRunner) -> None:
+ result = _invoke(runner, ["search", "nothing_matches_this", "--format", "text"], _Recorder())
+ assert result.exit_code == 0
+ assert result.output.count("no match") == 2
+ assert "non-pytest" in result.output
+
+
+def test_search_json_reports_both_surfaces(runner: CliRunner) -> None:
+ result = _invoke(runner, ["search", "test_capture", "--json"], _Recorder())
+ assert result.exit_code == 0
+ payload = json.loads(result.output)
+ assert [row["test_id"] for row in payload["broken_tests"]] == [_ROWS[0]["test_id"]]
+ assert len(payload["flaky_tests"]) == 1