: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(engineering_analytics): private read layer + typed endpoints (#60317)
Raúl Negrón-Otero72886962c139
diff --git a/posthog/scopes.py b/posthog/scopes.pyindex b1ee4053622a..f2b76d7235dd 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -39,6 +39,7 @@ APIScopeObject = Literal["desktop_recording","early_access_feature","endpoint",+ "engineering_analytics","error_tracking","evaluation","element",diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 5278cd4b0547..34e1bf320907 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -448,6 +448,7 @@ SPECTACULAR_SETTINGS = {# path (drf-spectacular generates the x-spec-enum-id from the same tuples).# --- Model class paths (ChoiceField x-spec-enum-id hashes) ---"RestrictionLevelEnum": "products.dashboards.backend.models.dashboard.Dashboard.RestrictionLevel",+ "EngineeringAnalyticsPRStateEnum": "products.engineering_analytics.backend.facade.contracts.PRState","OrganizationMembershipLevelEnum": "posthog.models.organization.OrganizationMembership.Level","SetupTaskId": "posthog.models.team.setup_tasks.SetupTaskId","SurveyType": "products.surveys.backend.models.Survey.SurveyType",diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex fedc31b15c48..0f8aa7aaf6dc 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -67,7 +67,7 @@ PostHog Code engineering_analytics PostHog product analy(generates code, → (CI / review / merge / deploy) → (events, errors, flags,opens PRs) surveys, replays)↑ │- └─────────── signals feed back to PostHog Code ───────────┘+ └─────────── Signals feed back to PostHog Code ───────────┘```The middle — what happens to code between "PR opened" and "running in production" — is invisible to both ends today. Engineering analytics fills it, serving two consumers with the same tools:@@ -75,7 +75,27 @@ The middle — what happens to code between "PR opened" and "running in producti- **Engineers** driving an agent (Claude Code, Cursor, PostHog AI) asking about their monorepo. We dogfood on `PostHog/posthog` from day one.- **PostHog Code** itself, autonomously, calling the same tools on its own PRs — to diagnose why a PR is stuck, decide whether to retry, and eventually see how a merged change behaved in production.-Tool return shapes must be legible to an autonomous agent, not just renderable in chat: typed contracts with explicit `metric_quality` markers, never prose an LLM might paraphrase wrong.+Tool return shapes must be legible to an autonomous agent, not just renderable in chat: typed contracts whose caveats ride in honest field names and a `metric_quality` marker where load-bearing, never free-form prose an LLM might paraphrase wrong.++## Goal: surface CI Signals for PostHog Code++The product drives toward one outcome: turn the curated CI/PR read layer into+**Signals** — emitted into PostHog's [Signals](../signals) product, grouped and+researched against the repository, and, when a finding is actionable, handed to+PostHog Code for autonomous remediation. "CI slowed down on workflow X", "this PR is+wedged on a failing required check", "this check is flaky" become first-class Signals+an agent acts on — not dashboards a human has to watch.++The two read surfaces exist to serve that goal, in priority order:++1. **MCP tools — the official surface.** Engineers query the monorepo through PostHog+ MCP, and agents (including PostHog Code) call the same tools. Detection of what+ counts as a valuable CI Signal lives in `logic/` over the read layer, so the same+ definitions back the MCP tools and the Signal emitter.+2. **Read-only UI — a showcase** over the same endpoints. Useful, but secondary.++Shortening ready-for-review-to-merge is the headline _metric_ this serves; emitting+actionable CI Signals to PostHog Code is the _goal_ that metric ladders up to.## v1 vs the destination@@ -94,35 +114,35 @@ Change one only in a separate PR with a written reason. Engineering-level decisi- Two consumer classes: human-driven agents (primary) and agent-driven agents like PostHog Code (secondary, designed-for-now).- Unit of value = the open PR.- Phase model: draft (experimentation, low rigor) vs ready-for-review (high stakes).-- North star: shorten ready-for-review-to-merge without removing useful friction.+- North star: surface actionable CI Signals for PostHog Code, emitted into the Signals product. Shortening ready-for-review-to-merge is the headline metric it serves, not the end in itself.- Wedge = end-to-end code visibility, served as MCP tools to PostHog Code (autonomous) and engineers using PostHog MCP (human-driven).-- Tool return shapes = typed Python (pydantic / dataclasses) with explicit `metric_quality` markers (`precise | coarse | partial`). Not free-form prose.-- Validation UI = demo surface. Read-only. Capped at the design-system showcase. No saved views — saved state lives in agent memory, not Postgres.+- Surface = MCP is the official surface, delivered as named typed endpoints that run the curated read layer privately (no global HogQL view; off the per-query hot path; core imports only the viewset). `metric_quality` is a typed field on `pr_lifecycle`; aggregate endpoints carry caveats in honest field names + tool docs — never free-form prose an LLM might paraphrase wrong. See [SPEC.md](./SPEC.md) §3 / §7.+- UI = read-only analytics surface on the **same** endpoints (PR list, CI health, workflow health) — a real read surface, not only a design-system showcase. No saved views or stateful filters in this phase; persisted/stateful surfaces are a later, separate decision.- v1 data path = HogQL on warehouse. Event ingestion deferred. Product Postgres DB stays empty.- Author identity = `Author{handle, display_name, avatar_url, is_bot}`. No PostHog-user mapping in v1.- Bots and drafts excluded by default in throughput / cycle-time tools; bots are first-class in bot-impact analysis (don't strip them everywhere).- Bot detection = `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist for v1.-- `time_to_merge` v1 = `merged_at - created_at` (draft + ready-for-review combined), marked coarse on the return shape.+- Time to merge v1 = the read layer's `open_to_merge_seconds` column = `merged_at - created_at` (draft + ready-for-review combined). Coarse — encoded in the column name, never named cycle/review time.- CI granularity = workflow level (`github_workflow_runs`). Job-level is a later add.- `pull_request_reviews` warehouse source deferred until the wedge tool is built.- No privacy guardrails in v1; revisit if scope widens beyond the team-devex maintainer.## Glossary-| Term | Definition |-| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |-| **PR (unit of value)** | An open GitHub pull request, draft or ready-for-review — the atomic thing this product measures |-| **Draft phase** | Experimentation. Low-rigor measurement. Selective tests + advisory bots are OK |-| **Ready-for-review phase** | High-stakes. Where DevEx measures aggressively |-| **Good friction** | Tests / bots / checks that catch real problems. Kept and optimized |-| **Bad friction** | Tests / bots / checks that engineers ignore or that fail for unrelated reasons. Removed |-| **Wedge** | End-to-end code visibility: code tracked from written → CI / review → live, served via MCP to PostHog Code and engineers using PostHog MCP |-| **MCP tool** | A function the agent calls. Its description is a production prompt |-| **Surface** | Primary = MCP tools; secondary = read-only demo UI |-| **Human-driven agent** | Claude Code / Cursor / PostHog AI invoked by an engineer typing |-| **Agent-driven agent** | An autonomous agent (e.g. PostHog Code) invoking MCP tools without a human in the loop |-| **The AI-to-prod loop** | PostHog Code → engineering_analytics → PostHog product analytics → feedback to PostHog Code. The full lifecycle of agent-generated code, instrumented |-| **The dark middle** | The CI / review / merge / deploy steps between PostHog Code and PostHog product analytics, currently invisible to both |-| **`time_to_merge` (v1)** | `merged_at - created_at`. PR open to merge — combines draft + ready-for-review until state-transition data lands. Marked coarse on the return shape |-| **Workflow** | A GitHub Actions workflow run on a PR's head commit. One row in `github_workflow_runs`. v1 CI granularity; job-level is a later add |-| **Bot** | An `Author` with `is_bot = True`. Detection: `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES` |+| Term | Definition |+| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **PR (unit of value)** | An open GitHub pull request, draft or ready-for-review — the atomic thing this product measures |+| **Draft phase** | Experimentation. Low-rigor measurement. Selective tests + advisory bots are OK |+| **Ready-for-review phase** | High-stakes. Where DevEx measures aggressively |+| **Good friction** | Tests / bots / checks that catch real problems. Kept and optimized |+| **Bad friction** | Tests / bots / checks that engineers ignore or that fail for unrelated reasons. Removed |+| **Wedge** | End-to-end code visibility: code tracked from written → CI / review → live, served via MCP to PostHog Code and engineers using PostHog MCP |+| **MCP tool** | A function the agent calls. Its description is a production prompt |+| **Surface** | Primary = MCP tools; secondary = read-only demo UI |+| **Human-driven agent** | Claude Code / Cursor / PostHog AI invoked by an engineer typing |+| **Agent-driven agent** | An autonomous agent (e.g. PostHog Code) invoking MCP tools without a human in the loop |+| **The AI-to-prod loop** | PostHog Code → engineering_analytics → PostHog product analytics → feedback to PostHog Code. The full lifecycle of agent-generated code, instrumented |+| **The dark middle** | The CI / review / merge / deploy steps between PostHog Code and PostHog product analytics, currently invisible to both |+| **`open_to_merge_seconds` (v1)** | The read layer's coarse time-to-merge column: `merged_at - created_at`. PR open to merge — combines draft + ready-for-review until state-transition data lands. The name encodes the caveat |+| **Workflow** | A GitHub Actions workflow run on a PR's head commit. One row in `github_workflow_runs`. v1 CI granularity; job-level is a later add |+| **Bot** | An `Author` with `is_bot = True`. Detection: `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES` |diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 07effb64c6d1..102c30ca5336 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -5,7 +5,9 @@ Sibling doc: [README.md](./README.md) — read that first for the product pictur## 1. Purpose-Engineering contract for the `products/engineering_analytics/` product. The product surfaces PR + CI lifecycle data from the warehouse (`github_pull_requests`, `github_workflow_runs`) as MCP tools and DRF endpoints. Consumers and motivations are in the README.+Engineering contract for the `products/engineering_analytics/` product. The product surfaces PR + CI lifecycle data from the warehouse (`github_pull_requests`, `github_workflow_runs`) through **named, typed read endpoints** that run curated HogQL privately. **MCP is the official surface** (the endpoints are exposed as MCP tools); a read-only UI consumes the same endpoints. Nothing is registered as a global HogQL view, so the product stays isolated and off the per-query catalog hot path — core imports only the viewset, exactly like `visual_review`. Consumers and motivations are in the README.++The **goal** is to surface these as **Signals** for PostHog Code: valuable CI conditions are emitted into PostHog's [Signals](../signals) product, grouped and researched against the repository, and acted on autonomously when a finding is actionable. The read substrate + MCP serve that goal directly — what counts as a valuable CI Signal is defined once in `logic/` over the read layer, reused by both the surface and the emitter — and the UI is a showcase over the same layer.## 2. Non-goals@@ -16,51 +18,50 @@ Engineering contract for the `products/engineering_analytics/` product. The prod## 3. Architecture+One general **curated read layer** that every surface composes. The curated query builders are the deep, reusable layer where all domain knowledge lives once; the named endpoints, MCP, and the UI are thin consumers above it. Crucially the product runs this layer **privately** — it is never registered as a global HogQL view, so core's HogQL layer never imports it and no per-team query pays for it. The only core→product edge is the viewset registration in `posthog/api/`, the standard product edge that every viewset has. (APOSD: general-purpose lower layer, thin surfaces, domain rules defined once.)+```mermaidgraph TBsubgraph Consumers- MCP[MCP clients - Claude Code / Cursor / PostHog AI]- UI[Read-only demo UI - React + kea]- Other[PostHog Code and other agent-driven callers]+ MCP[MCP clients — Claude Code / Cursor / PostHog AI]+ UI[Read-only UI — React + kea]+ Other[PostHog Code & other agent-driven callers]end- subgraph "Surface (autogen)"- Tools["MCP tools<br/>(tools.yaml -> codegen)"]- DRF["DRF viewsets<br/>(@extend_schema)"]+ subgraph "Surface (thin)"+ Endpoints["named typed DRF endpoints<br/>ci_cards / pull_requests / workflow_health / pr_lifecycle<br/>@extend_schema → OpenAPI → MCP tools + UI client"]end- subgraph Domain- Facade["facade/api.py<br/>(public interface, canonical types)"]- Logic["logic/<br/>(metric definitions)"]- Queries["logic/queries/<br/>(HogQL queries, GitHub-shaped)"]+ subgraph "Curated read layer (domain rules defined ONCE)"+ Sys["curated query builders — build_query()<br/>embedded as subqueries, run via execute_hogql_query<br/>NOT registered as global views"]endsubgraph StorageWH[(warehouse<br/>github_pull_requests<br/>github_workflow_runs)]+ EV[(events — PR as group type<br/>destination, deferred)]end- MCP --> Tools- UI --> DRF- Other --> Tools- Tools --> DRF- DRF --> Facade- Facade --> Logic- Logic --> Queries- Queries --> WH+ MCP --> Endpoints+ UI --> Endpoints+ Other --> Endpoints+ Endpoints --> Sys+ Sys --> WH+ Sys -. future .-> EV```Rules:-- HogQL via `execute_hogql_query()` is the only data access pattern. No raw ClickHouse `sync_execute()`.-- Django ORM is not used by this product. There is no product Postgres DB in v1 — see README → Locked decisions.-- `logic/queries/` is the only module that names warehouse tables (`github_pull_requests`, `github_workflow_runs`). Logic and facade work with canonical types only.-- One contract feeds both surfaces: DRF viewsets with `@extend_schema` produce OpenAPI → TypeScript types AND MCP tool descriptions. Logic functions are called by both.-- Every MCP-tools PR ships with a matching in-product skill at `skills/<name>/SKILL.md` so the dogfooder has an installed playbook for chaining tool calls — same pattern as `products/visual_review/skills/triaging-visual-review-runs/`.-- Provider abstraction (`CodeHostProvider` Protocol) is **deferred**. GitHub-specific HogQL lives in `logic/queries/` directly; when a second provider lands, the Protocol is extracted then. See §7.+- **Curated read layer = curated query builders** over the warehouse tables: `backend/logic/views/{pull_requests,workflow_runs}.py` each expose `build_query()` returning a curated `SELECT` over the raw `github_*` table. Query modules (`backend/logic/queries/`) embed those as parenthesised subqueries (via `_curated`) and run them with `execute_hogql_query`. Repo identity (`base.repo.full_name`), labels, `is_bot`, and the PR↔CI head-SHA join are mapped here **from the JSON the source already lands — no new ingestion**. Domain rules (bot detection, default exclusions, the join, honest metric naming) are defined exactly **once**, here. **Nothing is registered in `Database.create_for`** — the product is not a global-catalog citizen, which keeps it off the per-query hot path and means `posthog/hogql` never imports it (the viewset registration in `posthog/api/` is the normal product edge, loaded once at URL-conf time).+- **MCP is the official surface, via named typed endpoints.** Each capability is a DRF action with `@extend_schema` that flows to an MCP tool through OpenAPI codegen (`ci_cards`, `pull_requests`, `workflow_health`, `pr_lifecycle`). This is the `visual_review` shape: core imports only the viewset; everything else stays in the product.+- **The UI reads the same endpoints** via the generated typed API client (kea loaders) — not client-side HogQL, and not bespoke report endpoints distinct from the MCP ones. One endpoint set, two consumers.+- HogQL only, via `execute_hogql_query`. No raw ClickHouse `sync_execute()`. No product Postgres DB.+- The curated builders (and `logic/queries/`) are the only place that names warehouse tables or GitHub-shaped columns. Canonical types stay above them.+- Every named-tool PR ships a matching `skills/<name>/SKILL.md` teaching tool selection and carrying the metric caveats — same pattern as `products/visual_review/skills/triaging-visual-review-runs/`.+- Provider abstraction (`CodeHostProvider` Protocol) is **deferred**. GitHub-specific HogQL lives in the curated builders; when a second provider lands, the Protocol is extracted then. See §7.## 4. Canonical types-Defined in `backend/facade/contracts.py` as `pydantic.dataclasses.dataclass(frozen=True)` — same `is_dataclass()` semantics as the stdlib variant (so `DataclassSerializer` works) but with runtime validation at construction. No Django imports.+Defined in `backend/facade/contracts.py` as `pydantic.dataclasses.dataclass(frozen=True)` — same `is_dataclass()` semantics as the stdlib variant (so `DataclassSerializer` works) but with runtime validation at construction. No Django imports. These back **every endpoint** and any cross-product use — the named endpoints return these typed contracts (objects or lists), so there is no untyped row surface.```mermaidclassDiagram@@ -117,44 +118,66 @@ classDiagramWorkflowRun --> WorkflowConclusion```-`is_bot` on `Author` is set inside the query / mapping layer:-`is_bot = handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`.+`is_bot` on `Author` is set inside the read layer: `is_bot = handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`.++`pr_lifecycle` returns a `metric_quality` field where the caveat is load-bearing (`partial`). The aggregate endpoints carry their caveats in **honest field names** (`open_to_merge_seconds`) plus serializer/tool docs (see §7).++Types named in the README but not yet modeled (reviewers, deploys, file paths) wait until the corresponding data lands.++## 5. Curated read layer & surface++### Curated read layer-Tool-specific return types (`WorkflowReport`, `TimeToMerge`, `PRLifecycle`) live in `facade/contracts.py` alongside the canonical types. They wrap rows + a `metric_quality` field per README → Locked decisions.+Two curated `build_query()` SELECTs over the existing warehouse data — columns mapped from JSON we already store, **no new ingestion, no global view registration**. Column names encode caveats so a misread is defined out of existence (`open_to_merge_seconds`, never `cycle_time`).-Types named in the README but not in v1 contracts (reviewers, deploys, file paths) wait until the corresponding warehouse data lands.+- pull-requests builder — `number`, `title`, `author_handle`, `is_bot`, `repo_owner` / `repo_name` (from `base.repo.full_name`), `labels`, `state`, `is_draft`, `created_at`, `merged_at`, `closed_at`, `head_sha`, `open_to_merge_seconds` (coarse — see §7).+- workflow-runs builder — `workflow_name`, `head_sha`, `conclusion`, `status`, `run_started_at`, `updated_at`, `duration_seconds`, `repo_owner` / `repo_name`.-## 5. v1 tool catalog+A PR's current CI status is the head-SHA join between the two (the `ci_rollup` CTE in `_curated`); defined once.-Tools live in `products/engineering_analytics/mcp/tools.yaml`. Each tool description is prompt-engineered — it explains to the calling LLM **when** and **why** to call it, not just the parameter list. Tool return shapes are typed contracts, not free-form prose (README → Locked decisions).+### Surface-| Tool | Source data | Returns | Quality |-| ----------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |-| `workflow_report` | `github_workflow_runs` | `list[WorkflowReportRow]` — workflow name, total runs, success rate, median + p95 duration, last failed at | precise |-| `time_to_merge` | `github_pull_requests` | `list[TimeToMergeRow]` — `bucket` (overall or per author), pr_count, median + p95 seconds | coarse (combines draft + ready-for-review time) |-| `pr_lifecycle` | both | `PRLifecycle` — PR header + timeline of CI run events | partial (no reviews/comments until reviews data lands) |+**MCP (official):** named typed tools, each a DRF endpoint returning a typed contract:-All tools accept `date_from` / `date_to` per PostHog convention (relative `-7d` or ISO8601). Optional `repo` filter on the first two.+- `ci_cards` — open-PR backlog counts (open / repos / stuck >7d / failing CI).+- `pull_requests` — PR list with head-SHA CI rollup; `date_from` recency window. Capped (newest first) and returned as `{items, truncated, limit}` so the page never silently under-counts against `ci_cards`.+- `workflow_health` — per-workflow run count, success rate, p50/p95 duration, last failure over a `date_from`/`date_to` window.+- `pr_lifecycle` — PR header + ordered CI-run timeline (a genuine assembly; `metric_quality = "partial"` until reviews/deploys land).-UI: one read-only scene rendering `workflow_report` as a horizontal bar chart of slowest workflows. Design system showcase only. No filters, no kea forms, no saved views.+**UI:** a read-only scene on the same endpoints via the generated API client — a PR list (CI status, CI duration, age), the count cards (open / stuck >7d / failing CI), and a workflow-health view. Read-only; **no saved views or stateful filters in this phase** (persisted/stateful surfaces are a later, separate decision). Columns that need deferred data — time-in-review, reviewers/approvals, per-check counts, DORA — are out until the event substrate lands (§9).++All time-windowed access uses `date_from` / `date_to` per PostHog convention (relative `-30d` or ISO8601).## 6. Delivery shape-Vertical slices, each independently mergeable — a feature PR delivers a complete read path (HogQL → logic → facade → DRF → MCP), not a horizontal layer. The near-term path: this scaffold, then the `github_workflow_runs` source, then the first MCP tools (`workflow_report` + `time_to_merge` + `pr_lifecycle`) with a matching `skills/<name>/SKILL.md`, then the read-only UI scene. Beyond that, sequencing follows the data — see §9.+Vertical slices, each independently mergeable. The near-term path:++1. scaffold — **done**.+2. `github_workflow_runs` warehouse source — **done**.+3. **curated read layer + named endpoints** (`ci_cards` / `pull_requests` / `workflow_health` / `pr_lifecycle`), run privately — no global registration — plus the in-product skill.+4. read-only UI scene on those endpoints (PR list + cards + workflow health).+5. destination: GitHub webhooks → events (PR as group type) — unlocks the deferred columns (§9).++The earlier explorations — three bespoke `*_report` RPC tools, then a generic `query` / `execute_sql` surface over globally-registered views — are **superseded** by named typed endpoints that run the curated builders privately. The named endpoints serve both MCP and the UI, keep domain rules defined once, and (unlike registered views) leave the product isolated and off the per-query hot path. See §7 for why.++The goal these slices build toward: emit valuable CI Signals from the curated read layer into the Signals product for PostHog Code. That emission rides on the curated builders — it does not wait on the events destination — and reuses the `logic/` detection that backs the MCP surface.## 7. Locked decisionsEngineering-specific decisions. Product-level decisions live in README → Locked decisions. If you want to change one, do it in a separate PR with a written reason.+- **Signals emission for PostHog Code is the goal; the substrate is shaped for it.** Valuable CI conditions are surfaced as Signals via the Signals product's `emit_signal()` for PostHog Code to act on. Detection of what counts as a valuable Signal is defined once in `logic/` over the read layer, so the emitter and the MCP/SQL surface share one definition — never re-derived in the UI. The emission contract (source taxonomy, thresholds, autonomy priority) is owned by the Signals product; nothing in the read substrate or surfaces may foreclose it.+- **Curated read layer, run privately; MCP is the official surface via named typed endpoints.** _(Changed — reason:)_ registering the curated views in the global HogQL catalog (`Database.create_for`, the `revenue_analytics` precedent) inverts the dependency — core imports the product — and runs on the per-query hot path for **every** team. Running the curated `build_query()` as subqueries from the product's own DRF endpoints keeps domain rules defined once while leaving the product isolated and off the hot path: core imports only the viewset, exactly like `visual_review`. The endpoints back both the MCP tools and the UI, so there is no parallel read path. (This restructure is the written reason for changing the prior "registered substrate + generic SQL surface" decision.)+- **`metric_quality` is a typed field on `pr_lifecycle`; aggregate endpoints carry caveats in field names + docs.** _(Changed — reason:)_ the aggregate endpoints return typed lists, so the coarse/staleness caveats ride in honest field names (`open_to_merge_seconds`) and serializer/tool descriptions — structurally hard to misread. `pr_lifecycle` keeps the typed `metric_quality` field (`partial`) where the assembly's incompleteness is load-bearing.+- **No new ingestion to support v1 UI.** Repo identity, labels, and `is_bot` are mapped from the warehouse JSON already landed; the PR↔CI status is a head-SHA join. All in the read layer.- **HogQL only for analytics data.** No raw ClickHouse.-- **No product Postgres DB.** Saved state lives in the agent's memory; tool calls are stateless. No `db_routing.yaml` entry — analytics data is in the warehouse / ClickHouse (shared infra, nothing to provision). If a product-config model is ever needed, it goes on the **main** DB as a team-scoped model (`TeamScopedRootMixin`), not a separate DB.-- **Provider abstraction deferred.** No `CodeHostProvider` Protocol in v1. GitHub-shaped HogQL lives in `logic/queries/`. The boundary between `logic/queries/` and `logic/` is the future Protocol seam — keep canonical types above it, GitHub-isms below.-- **Canonical types live in `facade/contracts.py`** as frozen dataclasses. No Django imports, no provider-specific fields.-- **CI granularity = workflow level** (`github_workflow_runs`). Job-level breakdown requires a new warehouse endpoint and is deferred.-- **Bot detection** lives in the query / mapping layer: `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist for v1; per-team config deferred.-- **Bots and drafts excluded by default** in PR-listing / cycle-time tools. They are first-class in any future bot-impact analysis (don't strip them everywhere).-- **`time_to_merge` v1** = `merged_at - created_at`. Marked `metric_quality = "coarse"`. Precise companion lands when state-transition data exists.-- **Tool return shapes** = typed pydantic / dataclasses with explicit `metric_quality` marker (`"precise" | "coarse" | "partial"`). Repo convention.+- **No product Postgres DB.** Tool calls are stateless; saved/stateful state is a later, separate decision. No `db_routing.yaml` entry — analytics data lives in the warehouse / ClickHouse. If a product-config model is ever needed, it goes on the **main** DB as a team-scoped model (`TeamScopedRootMixin`), not a separate DB.+- **Provider abstraction deferred.** No `CodeHostProvider` Protocol in v1. GitHub-shaped HogQL lives in the read layer; that boundary is the future Protocol seam — keep canonical types above it, GitHub-isms below.+- **Canonical types live in `facade/contracts.py`** as frozen dataclasses (for the named deep tools). No Django imports, no provider-specific fields.+- **CI granularity = workflow level** (`github_workflow_runs`). Per-check/job breakdown requires a new warehouse endpoint and is deferred.+- **Bot detection** defined once in the read layer: `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist for v1; per-team config deferred.+- **Bots and drafts excluded by default** in throughput / cycle-time recipes (an explicit column flag + a default filter the skill applies). First-class in any future bot-impact analysis — don't strip them at the substrate.+- **Time to merge v1** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (combines draft + ready-for-review time). The precise companion lands with state-transition data.## 8. Deferred (engineering) decisions@@ -165,22 +188,27 @@ Use the current default; revisit when the relevant data lands (§9).- Deploy definition (deployment events vs named workflow vs tag push) — decide when deploy data lands.- Path-based filtering (which files a PR touched) — not in the current snapshot; comes with the lifecycle-event data.- Commits-till-merged — same; comes with the lifecycle-event data.-- Provider Protocol — wait for a second provider. The query-layer boundary is already drawn to make extraction mechanical.+- Provider Protocol — wait for a second provider. The read-layer boundary is already drawn to make extraction mechanical.+- Stateful / persisted UI (saved views, persisted filters) — a separate decision once the read-only scene proves out.## 9. Data sources-Available now (warehouse snapshots, queried via HogQL):+Available now (warehouse snapshots, read via the curated query builders):-- `github_pull_requests` — PR snapshot: number, title, author, state, created_at, merged_at, closed_at, draft flag, base/head refs. Current state only — transitions are overwritten on update.+- `github_pull_requests` — PR snapshot: number, title, author, state, created_at, merged_at, closed_at, draft flag, base/head refs, **labels and `base.repo.full_name` in the raw JSON** (mapped in the read layer, not new ingestion). Current state only — transitions are overwritten on update.- `github_workflow_runs` — CI runs: workflow name, status, conclusion, run_started_at, updated_at, head SHA. Each run is immutable, so durations and their trends are precise.These bound v1 to coarse PR timing (no transition history) and workflow-level CI (no per-check detail).-Beyond v1 the product needs lifecycle data the snapshots can't hold: PR state transitions (draft↔ready), reviews and approvals, per-check/job CI, and deploys. The likely path is **GitHub webhooks → PostHog events, with the PR as a group type** — one mechanism that delivers all of these as immutable timestamped events, while the warehouse snapshots stay as the current-state/backfill layer. PostHog already runs a GitHub App webhook receiver, so this is an analytics handler on existing infra, not new infra. A per-primitive warehouse-source poll is the heavier alternative and still can't recover transition timing, so it's not the plan. See README → "v1 vs the destination".+**Freshness caveat:** `github_workflow_runs` syncs on a `created_at` watermark and does not refresh the conclusion of a run that completes after newer runs land — so a PR's "failing / running" CI status can be stale until the `workflow_run` webhook ships. The read layer should surface the run's `status` honestly rather than imply a settled conclusion.++Beyond v1 the product needs lifecycle data the snapshots can't hold: PR state transitions (draft↔ready), reviews and approvals, per-check/job CI, and deploys. The likely path is **GitHub webhooks → PostHog events, with the PR as a group type** — one mechanism that delivers all of these as immutable timestamped events, while the warehouse snapshots stay as the current-state/backfill layer. PostHog already runs a GitHub App webhook receiver, so this is an analytics handler on existing infra, not new infra. When it lands, the deferred UI columns (time-in-review, reviewers/approvals, per-check, DORA) become available on the same read layer. A per-primitive warehouse-source poll is the heavier alternative and still can't recover transition timing, so it's not the plan. See README → "v1 vs the destination".## 10. Reference reading- [README.md](./README.md) — product picture, motivations, locked decisions, glossary (read this first)+- `docs/published/handbook/engineering/ai/implementing-mcp-tools.md` — MCP tool design (DRF endpoint → OpenAPI → MCP tool)+- `products/visual_review/backend/presentation/` — the precedent for a facade product whose DRF endpoints back both MCP tools and the UI, with core importing only the viewset (no global-catalog registration)+- `posthog/hogql/query.py` (`execute_hogql_query`) — how the product runs its curated HogQL privately, without a `Database.create_for` registration- `products/architecture.md` — folder structure, isolation rules, tach + import-linter-- `products/README.md` — how to scaffold a product- `posthog/models/scoping/README.md` — `TeamScopedRootMixin` contract (main-DB team-scoped model, for whenever the first config model lands)diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 151275377b1d..23bc0f934e9e 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -1 +1,50 @@-"""Facade for engineering_analytics — the only module other products may import."""+"""Facade for engineering_analytics.++The ONLY module other products (and the DRF presentation layer) import for+runtime PR/CI analytics. Public functions take a team plus PostHog-convention+parameters and return canonical contract types.++``repo`` is an optional ``owner/name`` filter, applied against the curated repo+identity (mapped from ``base.repo.full_name``). ``date_from`` / ``date_to`` accept+relative strings (``-30d``) or ISO8601 and are resolved against the team timezone.+"""++from posthog.models.team import Team++from products.engineering_analytics.backend import logic+from products.engineering_analytics.backend.facade.contracts import (+ CICardSummary,+ PRLifecycle,+ PullRequestList,+ WorkflowHealthItem,+)+++def get_pr_lifecycle(+ *,+ team: Team,+ pr_number: int,+ repo: str | None = None,+) -> PRLifecycle | None:+ return logic.build_pr_lifecycle(team=team, pr_number=pr_number, repo=repo)+++def get_ci_cards(*, team: Team) -> CICardSummary:+ return logic.build_ci_cards(team=team)+++def list_pull_requests(+ *,+ team: Team,+ date_from: str | None = None,+) -> PullRequestList:+ return logic.build_pull_request_list(team=team, date_from=date_from)+++def list_workflow_health(+ *,+ team: Team,+ date_from: str | None = None,+ date_to: str | None = None,+) -> list[WorkflowHealthItem]:+ return logic.build_workflow_health(team=team, date_from=date_from, date_to=date_to)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 0299fcdea35b..5ee27e97a847 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -1 +1,213 @@-"""Contract types for engineering_analytics — frozen pydantic dataclasses, no Django imports."""+"""Contract types for engineering_analytics.++Framework-free frozen dataclasses that define the canonical data model this+product exposes — Author, RepoRef, PullRequest, WorkflowRun — plus the+``pr_lifecycle`` deep-tool return types. No Django imports.++Every surface — the named MCP tools, the DRF read endpoints, and the UI — returns+these typed contracts. The product runs its curated HogQL privately behind them;+nothing is registered as a global view. Where a caveat is load-bearing on a deep+tool it rides as a ``metric_quality`` field (``pr_lifecycle``); the aggregate+endpoints carry their caveats in honest field names (``open_to_merge_seconds``)+and serializer/tool docs.++These use ``pydantic.dataclasses.dataclass`` rather than the stdlib variant: same+``is_dataclass()`` compatibility (so ``DataclassSerializer`` keeps working) but+with runtime validation on construction, so a mapper that hands back the wrong+shape fails at the facade boundary instead of producing malformed JSON later.++Provider-specific shapes (GitHub column names, nesting) never reach here — the+read layer maps them into these types. Reviewers, deploys, and file paths are+intentionally absent until the warehouse data that backs them lands.+"""++from datetime import datetime+from enum import StrEnum++from pydantic.dataclasses import dataclass+++class GitHubSourceNotConnectedError(Exception):+ """Raised when a team has no GitHub warehouse source — the curated queries+ reference ``github_*`` tables that aren't in the catalog. Surfaces as a clear+ 4xx so the UI prompts to connect a source and an agent gets an actionable+ error instead of a misleading empty result. Framework-free; the presentation+ layer translates it to an HTTP response.+ """++ DEFAULT_MESSAGE = "Connect a GitHub data warehouse source to use engineering analytics."++ def __init__(self, message: str = DEFAULT_MESSAGE) -> None:+ super().__init__(message)+++class PRState(StrEnum):+ OPEN = "open"+ CLOSED = "closed"+ MERGED = "merged"+++class WorkflowConclusion(StrEnum):+ SUCCESS = "success"+ FAILURE = "failure"+ CANCELLED = "cancelled"+ SKIPPED = "skipped"+ TIMED_OUT = "timed_out"+ NEUTRAL = "neutral"+++class MetricQuality(StrEnum):+ """How much to trust a metric, surfaced on a deep-tool return so an+ autonomous caller can act on the result without paraphrasing a caveat.++ - ``precise``: computed directly from the data, no known approximation.+ - ``coarse``: a usable approximation with a known systematic gap (e.g. the+ read layer's ``open_to_merge_seconds`` combines draft and ready-for-review+ time).+ - ``partial``: real but incomplete, because backing data hasn't landed yet+ (e.g. ``pr_lifecycle`` has no review/comment events).+ """++ PRECISE = "precise"+ COARSE = "coarse"+ PARTIAL = "partial"+++class PRLifecycleEventKind(StrEnum):+ OPENED = "opened"+ CI_STARTED = "ci_started"+ CI_FINISHED = "ci_finished"+ MERGED = "merged"+ CLOSED = "closed"+++@dataclass(frozen=True)+class RepoRef:+ provider: str+ owner: str+ name: str+++@dataclass(frozen=True)+class Author:+ handle: str+ display_name: str+ avatar_url: str+ is_bot: bool+++@dataclass(frozen=True)+class PullRequest:+ id: int+ number: int+ title: str+ author: Author+ repo: RepoRef+ state: PRState+ is_draft: bool+ created_at: datetime+ merged_at: datetime | None+ closed_at: datetime | None+++@dataclass(frozen=True)+class WorkflowRun:+ id: int+ workflow_name: str+ head_sha: str+ # None while a run is still in progress — it has no conclusion yet.+ conclusion: WorkflowConclusion | None+ run_started_at: datetime+ updated_at: datetime+ # None until the run completes — the curated builder only computes a duration+ # for completed runs (see workflow_runs.build_query).+ duration_seconds: int | None+++@dataclass(frozen=True)+class PRLifecycleEvent:+ kind: PRLifecycleEventKind+ at: datetime+ detail: str | None = None+++@dataclass(frozen=True)+class PRLifecycle:+ pull_request: PullRequest+ events: list[PRLifecycleEvent]+ metric_quality: MetricQuality = MetricQuality.PARTIAL+++@dataclass(frozen=True)+class CIStatusRollup:+ """A PR's CI, collapsed from the latest workflow run per workflow on its head+ SHA. Counts can lag until the ``workflow_run`` webhook settles a run that+ completes after newer runs land (SPEC §9) — treat ``pending`` as unsettled.+ """++ runs: int+ passing: int+ failing: int+ pending: int+++@dataclass(frozen=True)+class PullRequestListItem:+ """One row of the PR list: the PR plus its head-SHA CI rollup. No ``id`` or+ ``head_sha`` — this is a display/triage row, not the full ``PullRequest``.+ """++ number: int+ title: str+ author: Author+ repo: RepoRef+ state: PRState+ is_draft: bool+ created_at: datetime+ merged_at: datetime | None+ # merged_at - created_at; coarse (fuses draft + ready-for-review time). None until merged.+ open_to_merge_seconds: int | None+ labels: list[str]+ ci: CIStatusRollup+++@dataclass(frozen=True)+class PullRequestList:+ """A page of the PR list plus an explicit truncation signal. ``items`` is capped+ at ``limit`` (newest first); ``truncated`` is True when more pull requests match+ than the cap. Surfaced so a consumer never mistakes a capped page for the whole+ set — the aggregate counts in ``CICardSummary`` can legitimately exceed+ ``len(items)`` when ``truncated`` is True.+ """++ items: list[PullRequestListItem]+ truncated: bool+ limit: int+++@dataclass(frozen=True)+class CICardSummary:+ """Headline counts for the open-PR backlog. ``failing_ci`` rests on the+ head-SHA CI join and can lag (see ``CIStatusRollup``).+ """++ open_prs: int+ repos: int+ # Open, non-draft, non-bot PRs older than 7 days.+ stuck: int+ # Open PRs with at least one failing latest CI run.+ failing_ci: int+++@dataclass(frozen=True)+class WorkflowHealthItem:+ """Per-workflow CI health over a window. Rates and percentiles are over+ completed runs only, so they are ``None`` when the window has none.+ """++ workflow_name: str+ run_count: int+ success_rate: float | None+ p50_seconds: float | None+ p95_seconds: float | None+ last_failure_at: datetime | Nonediff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 93ed15dd23ce..b757c63144d2 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -1 +1,68 @@-"""Business logic for engineering_analytics — metric definitions over canonical types."""+"""Orchestration for engineering_analytics.++Resolves caller inputs (PostHog-convention date strings, ``owner/name`` repo) into+the values the query layer needs and returns canonical contract types. The curated+query builders (``backend/logic/views``) own all GitHub-shaped mapping and domain+rules; this layer deals only in canonical types.+"""++from datetime import datetime++from posthog.models.team import Team+from posthog.utils import relative_date_parse++from products.engineering_analytics.backend.facade.contracts import (+ CICardSummary,+ PRLifecycle,+ PullRequestList,+ WorkflowHealthItem,+)+from products.engineering_analytics.backend.logic.queries.ci_cards import query_ci_cards+from products.engineering_analytics.backend.logic.queries.pr_lifecycle import query_pr_lifecycle+from products.engineering_analytics.backend.logic.queries.pull_request_list import query_pull_request_list+from products.engineering_analytics.backend.logic.queries.workflow_health import query_workflow_health++# Default recency window when a caller omits date_from. Relative strings (-30d) and+# ISO8601 are both accepted and resolved against the team's timezone.+_DEFAULT_WINDOW = "-30d"+++def build_pr_lifecycle(*, team: Team, pr_number: int, repo: str | None) -> PRLifecycle | None:+ owner, name = _split_repo(repo)+ return query_pr_lifecycle(team=team, pr_number=pr_number, repo_owner=owner, repo_name=name)+++def build_ci_cards(*, team: Team) -> CICardSummary:+ return query_ci_cards(team=team)+++def build_pull_request_list(*, team: Team, date_from: str | None = None) -> PullRequestList:+ return query_pull_request_list(team=team, date_from=_parse_date(team, date_from or _DEFAULT_WINDOW))+++def build_workflow_health(+ *,+ team: Team,+ date_from: str | None = None,+ date_to: str | None = None,+) -> list[WorkflowHealthItem]:+ return query_workflow_health(+ team=team,+ date_from=_parse_date(team, date_from or _DEFAULT_WINDOW),+ date_to=_parse_date(team, date_to) if date_to else None,+ )+++def _parse_date(team: Team, value: str) -> datetime:+ return relative_date_parse(value, team.timezone_info)+++def _split_repo(repo: str | None) -> tuple[str | None, str | None]:+ if not repo:+ return None, None+ owner, _, name = repo.partition("/")+ # A half-specified repo (bare org, trailing/leading slash) would otherwise drop+ # the filter silently and return a PR from the wrong repo — fail loudly instead.+ if not (owner and name):+ raise ValueError(f"repo must be in 'owner/name' format, got: {repo!r}")+ return owner, namediff --git a/products/engineering_analytics/backend/logic/queries/__init__.py b/products/engineering_analytics/backend/logic/queries/__init__.pyindex 20a841e9c20e..9a1a9ba33459 100644--- a/products/engineering_analytics/backend/logic/queries/__init__.py+++ b/products/engineering_analytics/backend/logic/queries/__init__.py@@ -1,6 +1,8 @@"""HogQL queries for engineering_analytics.-The only module allowed to name warehouse tables (`github_pull_requests`,-`github_workflow_runs`); logic and facade work with canonical types only.-This boundary is the future code-host-provider seam.+Each module embeds the curated query builders (``backend/logic/views``) as+subqueries via ``_curated`` and runs them with ``execute_hogql_query`` — the+product reads its data privately, never registering a global HogQL view. The raw+``github_*`` warehouse tables are named only inside those curated builders;+everything returned here is shaped into canonical contract types."""diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pynew file mode 100644index 000000000000..a108650ec65f--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -0,0 +1,99 @@+"""Shared helpers for the curated query modules.++The ``pull_requests`` / ``workflow_runs`` builders return a curated ``SELECT``+over the raw ``github_*`` warehouse tables. Query modules embed those as+parenthesised subqueries (``FROM {pr_source()} AS pr``) and run them with+``run_query`` — the product reads its data privately rather than registering a+global HogQL view, keeping it off the per-query catalog hot path.++Every fragment here is built from trusted constants. User-supplied values must+always flow through ``ast.Constant`` placeholders in the calling query, never be+string-substituted into these fragments.+"""++from posthog.schema import HogQLQueryResponse++from posthog.hogql import ast+from posthog.hogql.errors import QueryError+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.models.team import Team++from products.engineering_analytics.backend.facade.contracts import GitHubSourceNotConnectedError+from products.engineering_analytics.backend.logic.views import pull_requests, workflow_runs++# The curated builders are the only place a warehouse table is named; reuse their+# constants so "which tables mean a GitHub source is connected" is defined once.+_SOURCE_TABLES = (pull_requests.SOURCE_TABLE, workflow_runs.SOURCE_TABLE)+++def pr_source() -> str:+ """Curated pull-requests ``SELECT``, parenthesised for use as a subquery."""+ return f"({pull_requests.build_query()})"+++def run_source() -> str:+ """Curated workflow-runs ``SELECT``, parenthesised for use as a subquery."""+ return f"({workflow_runs.build_query()})"+++def ci_rollup_cte() -> str:+ """CTE collapsing each head SHA's workflow runs into pass/fail/pending counts.++ Takes the latest run per ``(head_sha, workflow_name)`` via ``argMax`` (a PR's+ CI status is its newest run per workflow), then aggregates per SHA. The join+ target for the cards and pull-request-list queries; ``head_sha`` is the only+ link between a PR and its CI.+ """+ return f"""+ ci_rollup AS (+ SELECT+ head_sha,+ count() AS runs,+ countIf(s = 'completed' AND c = 'success') AS passing,+ countIf(s = 'completed' AND c IN ('failure', 'timed_out')) AS failing,+ countIf(s != 'completed') AS pending+ FROM (+ SELECT+ head_sha,+ workflow_name,+ argMax(status, run_started_at) AS s,+ argMax(conclusion, run_started_at) AS c+ FROM {run_source()} AS r+ GROUP BY head_sha, workflow_name+ )+ GROUP BY head_sha+ )+ """+++def run_query(+ sql: str,+ *,+ team: Team,+ query_type: str,+ placeholders: dict[str, ast.Expr] | None = None,+) -> HogQLQueryResponse:+ """Parse + execute a curated HogQL query.++ Raises ``GitHubSourceNotConnectedError`` when the team has no GitHub warehouse+ source: the curated subqueries reference the ``github_*`` tables, which aren't in+ the catalog, so the resolver raises ``Unknown table``. The presentation layer+ turns that into a clear 4xx. Any other query error is a real bug and propagates.+ """+ try:+ return execute_hogql_query(+ query=parse_select(sql, placeholders=placeholders),+ team=team,+ query_type=query_type,+ )+ except QueryError as err:+ message = str(err)+ # HogQL raises ``Unknown table `<name>`.`` for any table missing from the+ # catalog. Only the absence of OUR source tables means "no GitHub source";+ # any other unknown table is a real bug (e.g. a typo in a curated builder)+ # and must surface unchanged rather than masquerade as a missing-source 4xx.+ if any(f"Unknown table `{table}`" in message for table in _SOURCE_TABLES):+ raise GitHubSourceNotConnectedError() from err+ raisediff --git a/products/engineering_analytics/backend/logic/queries/ci_cards.py b/products/engineering_analytics/backend/logic/queries/ci_cards.pynew file mode 100644index 000000000000..909fee94615e--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/ci_cards.py@@ -0,0 +1,34 @@+"""Curated query: headline counts for the open-PR backlog.++Open PRs joined to their head-SHA CI rollup, collapsed into four counts. ``stuck``+is a fixed rule (open, non-draft, non-bot, older than 7 days), so there is no+window parameter.+"""++from posthog.models.team import Team++from products.engineering_analytics.backend.facade.contracts import CICardSummary+from products.engineering_analytics.backend.logic.queries import _curated++_EMPTY = CICardSummary(open_prs=0, repos=0, stuck=0, failing_ci=0)++_SELECT = """+ SELECT+ countIf(pr.state = 'open') AS open_prs,+ count(DISTINCT if(pr.state = 'open', concat(pr.repo_owner, '/', pr.repo_name), NULL)) AS repos,+ countIf(+ pr.state = 'open' AND NOT pr.is_draft AND NOT pr.is_bot AND pr.created_at < now() - INTERVAL 7 DAY+ ) AS stuck,+ countIf(pr.state = 'open' AND coalesce(ci.failing, 0) > 0) AS failing_ci+ FROM __PR_SOURCE__ AS pr+ LEFT JOIN ci_rollup AS ci ON ci.head_sha = pr.head_sha+"""+++def query_ci_cards(*, team: Team) -> CICardSummary:+ sql = f"WITH {_curated.ci_rollup_cte()} {_SELECT}".replace("__PR_SOURCE__", _curated.pr_source())+ response = _curated.run_query(sql, team=team, query_type="engineering_analytics.ci_cards")+ if not response.results:+ return _EMPTY+ open_prs, repos, stuck, failing_ci = response.results[0]+ return CICardSummary(open_prs=open_prs, repos=repos, stuck=stuck, failing_ci=failing_ci)diff --git a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.pynew file mode 100644index 000000000000..10f989a48a2e--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py@@ -0,0 +1,133 @@+"""HogQL assembly of a single PR's lifecycle over the curated query builders.++Embeds the curated ``github_pull_requests`` / ``github_workflow_runs`` builders+as subqueries (via ``_curated``) — the product runs this privately rather than+registering a global view. The curated SELECTs already carry the derived columns+(canonical ``state``, ``is_bot``, repo identity, ``head_sha``), so this layer only+shapes the rows into the ``PRLifecycle`` contract; no GitHub-isms or domain rules+live here.+"""++from posthog.hogql import ast++from posthog.models.team import Team++from products.engineering_analytics.backend.facade.contracts import (+ Author,+ PRLifecycle,+ PRLifecycleEvent,+ PRLifecycleEventKind,+ PRState,+ PullRequest,+ RepoRef,+)+from products.engineering_analytics.backend.logic.queries import _curated++# The curated subqueries and the repo filter are filled with str.replace (trusted+# constants), leaving the HogQL {value} placeholders untouched for parse_select.+_HEADER = """+ SELECT+ id, number, title, state, is_draft,+ created_at, merged_at, closed_at,+ author_handle, author_avatar_url, is_bot,+ repo_owner, repo_name, head_sha+ FROM __PR_SOURCE__ AS pr+ WHERE number = {pr_number} __REPO_FILTER__+ ORDER BY created_at DESC+ LIMIT 1+"""++_RUNS = """+ SELECT workflow_name, status, conclusion, run_started_at, updated_at+ FROM __RUNS_SOURCE__ AS r+ WHERE head_sha = {head_sha}+ ORDER BY run_started_at ASC+"""+++def query_pr_lifecycle(+ *,+ team: Team,+ pr_number: int,+ repo_owner: str | None,+ repo_name: str | None,+) -> PRLifecycle | None:+ placeholders: dict[str, ast.Expr] = {"pr_number": ast.Constant(value=pr_number)}+ repo_filter = ""+ if repo_owner and repo_name:+ repo_filter = "AND repo_owner = {repo_owner} AND repo_name = {repo_name}"+ placeholders["repo_owner"] = ast.Constant(value=repo_owner)+ placeholders["repo_name"] = ast.Constant(value=repo_name)++ header_sql = _HEADER.replace("__PR_SOURCE__", _curated.pr_source()).replace("__REPO_FILTER__", repo_filter)+ header = _curated.run_query(+ header_sql,+ team=team,+ query_type="engineering_analytics.pr_lifecycle.header",+ placeholders=placeholders,+ )+ if not header.results:+ return None++ (+ pr_id,+ number,+ title,+ state,+ is_draft,+ created_at,+ merged_at,+ closed_at,+ author_handle,+ author_avatar_url,+ is_bot,+ owner,+ name,+ head_sha,+ ) = header.results[0]++ pull_request = PullRequest(+ id=pr_id,+ number=number,+ title=title,+ author=Author(+ handle=author_handle,+ display_name=author_handle,+ avatar_url=author_avatar_url,+ is_bot=bool(is_bot),+ ),+ repo=RepoRef(provider="github", owner=owner, name=name),+ state=PRState(state),+ is_draft=bool(is_draft),+ created_at=created_at,+ merged_at=merged_at,+ closed_at=closed_at,+ )++ events = [PRLifecycleEvent(kind=PRLifecycleEventKind.OPENED, at=created_at)]+ runs = (+ _curated.run_query(+ _RUNS.replace("__RUNS_SOURCE__", _curated.run_source()),+ team=team,+ query_type="engineering_analytics.pr_lifecycle.runs",+ placeholders={"head_sha": ast.Constant(value=head_sha)},+ )+ if head_sha+ else None+ )+ if runs is not None:+ for workflow_name, status, conclusion, run_started_at, updated_at in runs.results:+ events.append(+ PRLifecycleEvent(kind=PRLifecycleEventKind.CI_STARTED, at=run_started_at, detail=workflow_name)+ )+ if status == "completed":+ detail = f"{workflow_name}: {conclusion}" if conclusion else workflow_name+ events.append(PRLifecycleEvent(kind=PRLifecycleEventKind.CI_FINISHED, at=updated_at, detail=detail))++ if merged_at is not None:+ events.append(PRLifecycleEvent(kind=PRLifecycleEventKind.MERGED, at=merged_at))+ elif closed_at is not None:+ events.append(PRLifecycleEvent(kind=PRLifecycleEventKind.CLOSED, at=closed_at))++ events.sort(key=lambda event: event.at)+ return PRLifecycle(pull_request=pull_request, events=events)diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.pynew file mode 100644index 000000000000..d2dc4982edd8--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py@@ -0,0 +1,99 @@+"""Curated query: PR list with head-SHA CI rollup.++All open PRs plus any merged or closed since ``date_from`` (the recency floor for+finished work; open PRs are always included regardless of age). Ordered newest+first, capped at ``_LIMIT``. The query fetches ``_LIMIT + 1`` rows so an overflow is+detectable, and the result reports ``truncated`` rather than silently dropping the+tail (the aggregate counts in ``ci_cards`` can then legitimately exceed the list).+"""++from datetime import datetime++from posthog.hogql import ast++from posthog.models.team import Team++from products.engineering_analytics.backend.facade.contracts import (+ Author,+ CIStatusRollup,+ PRState,+ PullRequestList,+ PullRequestListItem,+ RepoRef,+)+from products.engineering_analytics.backend.logic.queries import _curated++_LIMIT = 1000++_SELECT = f"""+ SELECT+ pr.number, pr.title, pr.repo_owner, pr.repo_name,+ pr.author_handle, pr.author_avatar_url, pr.is_bot,+ pr.state, pr.is_draft, pr.created_at, pr.merged_at,+ pr.open_to_merge_seconds, pr.labels,+ coalesce(ci.runs, 0) AS runs,+ coalesce(ci.passing, 0) AS passing,+ coalesce(ci.failing, 0) AS failing,+ coalesce(ci.pending, 0) AS pending+ FROM __PR_SOURCE__ AS pr+ LEFT JOIN ci_rollup AS ci ON ci.head_sha = pr.head_sha+ WHERE pr.state = 'open'+ OR pr.merged_at >= {{date_from}}+ OR pr.closed_at >= {{date_from}}+ ORDER BY pr.created_at DESC+ LIMIT {_LIMIT + 1}+"""+++def query_pull_request_list(*, team: Team, date_from: datetime) -> PullRequestList:+ sql = f"WITH {_curated.ci_rollup_cte()} {_SELECT}".replace("__PR_SOURCE__", _curated.pr_source())+ response = _curated.run_query(+ sql,+ team=team,+ query_type="engineering_analytics.pull_request_list",+ placeholders={"date_from": ast.Constant(value=date_from)},+ )+ rows = response.results or []+ truncated = len(rows) > _LIMIT+ items = [_map_row(row) for row in rows[:_LIMIT]]+ return PullRequestList(items=items, truncated=truncated, limit=_LIMIT)+++def _map_row(row: tuple) -> PullRequestListItem:+ (+ number,+ title,+ repo_owner,+ repo_name,+ author_handle,+ author_avatar_url,+ is_bot,+ state,+ is_draft,+ created_at,+ merged_at,+ open_to_merge_seconds,+ labels,+ runs,+ passing,+ failing,+ pending,+ ) = row+ return PullRequestListItem(+ number=number,+ title=title,+ author=Author(+ handle=author_handle,+ display_name=author_handle,+ avatar_url=author_avatar_url,+ is_bot=bool(is_bot),+ ),+ repo=RepoRef(provider="github", owner=repo_owner, name=repo_name),+ state=PRState(state),+ is_draft=bool(is_draft),+ created_at=created_at,+ merged_at=merged_at,+ open_to_merge_seconds=open_to_merge_seconds,+ labels=list(labels),+ ci=CIStatusRollup(runs=runs, passing=passing, failing=failing, pending=pending),+ )diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.pynew file mode 100644index 000000000000..b6fa88480fed--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py@@ -0,0 +1,73 @@+"""Curated query: per-workflow CI health over a window.++Run counts, success rate, and duration percentiles per ``workflow_name`` for runs+started within ``[date_from, date_to]`` (``date_to`` optional). Rates and+percentiles are over completed runs only, so they are ``None`` for a window with+no completed runs.+"""++import math+from datetime import datetime++from posthog.hogql import ast++from posthog.models.team import Team++from products.engineering_analytics.backend.facade.contracts import WorkflowHealthItem+from products.engineering_analytics.backend.logic.queries import _curated++_LIMIT = 100++_SELECT = f"""+ SELECT+ workflow_name,+ count() AS run_count,+ countIf(status = 'completed' AND conclusion = 'success') / nullIf(countIf(status = 'completed'), 0) AS success_rate,+ quantileIf(0.5)(duration_seconds, status = 'completed') AS p50_seconds,+ quantileIf(0.95)(duration_seconds, status = 'completed') AS p95_seconds,+ max(if(conclusion = 'failure', run_started_at, NULL)) AS last_failure_at+ FROM __RUNS_SOURCE__ AS r+ WHERE run_started_at >= {{date_from}} __DATE_TO__+ GROUP BY workflow_name+ ORDER BY run_count DESC+ LIMIT {_LIMIT}+"""+++def query_workflow_health(+ *,+ team: Team,+ date_from: datetime,+ date_to: datetime | None,+) -> list[WorkflowHealthItem]:+ date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""+ sql = _SELECT.replace("__RUNS_SOURCE__", _curated.run_source()).replace("__DATE_TO__", date_to_clause)++ placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}+ if date_to is not None:+ placeholders["date_to"] = ast.Constant(value=date_to)++ response = _curated.run_query(+ sql,+ team=team,+ query_type="engineering_analytics.workflow_health",+ placeholders=placeholders,+ )+ return [+ WorkflowHealthItem(+ workflow_name=workflow_name,+ run_count=run_count,+ success_rate=_to_opt_float(success_rate),+ p50_seconds=_to_opt_float(p50_seconds),+ p95_seconds=_to_opt_float(p95_seconds),+ last_failure_at=last_failure_at,+ )+ for workflow_name, run_count, success_rate, p50_seconds, p95_seconds, last_failure_at in response.results+ ]+++def _to_opt_float(value: float | None) -> float | None:+ # quantileIf over an empty window returns NaN; nullIf division returns None.+ if value is None or (isinstance(value, float) and math.isnan(value)):+ return None+ return float(value)diff --git a/products/engineering_analytics/backend/logic/views/__init__.py b/products/engineering_analytics/backend/logic/views/__init__.pynew file mode 100644index 000000000000..ba535bf7bfd3--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/__init__.py@@ -0,0 +1,8 @@+"""Curated query builders over the GitHub warehouse snapshots.++``pull_requests`` and ``workflow_runs`` each expose a ``build_query()`` returning+the curated ``SELECT`` over the raw ``github_*`` table. All PR/CI domain rules+(bot detection, repo identity, label extraction, honest metric naming) are+defined here exactly once. Query modules embed these as subqueries via+``logic.queries._curated`` — nothing is registered as a global HogQL view.+"""diff --git a/products/engineering_analytics/backend/logic/views/pull_requests.py b/products/engineering_analytics/backend/logic/views/pull_requests.pynew file mode 100644index 000000000000..5582d8c7599e--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/pull_requests.py@@ -0,0 +1,53 @@+"""Curated ``github_pull_requests`` query builder.++Maps the raw ``github_pull_requests`` warehouse snapshot (GitHub's PR JSON,+landed verbatim) into honest, query-able columns. This is the ONLY place PR+domain rules live — bot detection, repo identity from ``base.repo.full_name``,+label extraction, the canonical PR state, and the coarse open-to-merge duration.+Every query module embeds this ``SELECT`` as a subquery (see ``_curated``) rather+than re-deriving the columns from JSON; nothing registers it as a global HogQL+view, so the product stays off the per-query catalog hot path.+"""++SOURCE_TABLE = "github_pull_requests"++# Bots whose handle does not carry GitHub's automatic ``[bot]`` suffix. Kept+# deliberately small; per-team configuration is deferred.+KNOWN_BOT_HANDLES: frozenset[str] = frozenset(+ {+ "posthog-bot",+ "dependabot",+ "renovate",+ "github-actions",+ }+)+++def _bot_handle_in_list() -> str:+ # Hardcoded allowlist, never user input — safe to inline as SQL literals.+ return ", ".join(f"'{handle}'" for handle in sorted(KNOWN_BOT_HANDLES))+++def build_query() -> str:+ handle = "JSONExtractString(user, 'login')"+ repo_full_name = "JSONExtractString(base, 'repo', 'full_name')"+ return f"""+ SELECT+ id,+ number,+ title,+ {handle} AS author_handle,+ JSONExtractString(user, 'avatar_url') AS author_avatar_url,+ ({handle} LIKE '%[bot]' OR {handle} IN ({_bot_handle_in_list()})) AS is_bot,+ arrayElement(splitByChar('/', {repo_full_name}), 1) AS repo_owner,+ arrayElement(splitByChar('/', {repo_full_name}), 2) AS repo_name,+ arrayMap(label -> JSONExtractString(label, 'name'), JSONExtractArrayRaw(labels)) AS labels,+ if(merged_at IS NOT NULL, 'merged', state) AS state,+ coalesce(draft, false) AS is_draft,+ created_at,+ merged_at,+ closed_at,+ JSONExtractString(head, 'sha') AS head_sha,+ if(merged_at IS NOT NULL, dateDiff('second', created_at, merged_at), NULL) AS open_to_merge_seconds+ FROM {SOURCE_TABLE}+ """diff --git a/products/engineering_analytics/backend/logic/views/workflow_runs.py b/products/engineering_analytics/backend/logic/views/workflow_runs.pynew file mode 100644index 000000000000..a98ba945466f--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/workflow_runs.py@@ -0,0 +1,32 @@+"""Curated ``github_workflow_runs`` query builder.++Maps the raw ``github_workflow_runs`` warehouse snapshot into honest CI columns:+``status`` and ``conclusion`` are passed through unchanged (a conclusion can be+stale until the ``workflow_run`` webhook settles it — see SPEC §9), and+``duration_seconds`` is only computed for completed runs. ``head_sha`` is the+canonical join key back to the pull-requests builder for a PR's CI status.++Every query module embeds this ``SELECT`` as a subquery (see ``_curated``);+nothing registers it as a global HogQL view.+"""++SOURCE_TABLE = "github_workflow_runs"+++def build_query() -> str:+ repo_full_name = "JSONExtractString(repository, 'full_name')"+ return f"""+ SELECT+ id,+ name AS workflow_name,+ head_sha,+ status,+ conclusion,+ run_started_at,+ updated_at,+ created_at,+ if(status = 'completed', dateDiff('second', run_started_at, updated_at), NULL) AS duration_seconds,+ arrayElement(splitByChar('/', {repo_full_name}), 1) AS repo_owner,+ arrayElement(splitByChar('/', {repo_full_name}), 2) AS repo_name+ FROM {SOURCE_TABLE}+ """diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.pyindex e6137b96b4c3..5dc9b7ee19de 100644--- a/products/engineering_analytics/backend/presentation/serializers.py+++ b/products/engineering_analytics/backend/presentation/serializers.py@@ -1 +1,175 @@-"""DRF serializers for engineering_analytics."""+"""DRF serializers for engineering_analytics.++Output-only serializers that turn the facade's frozen dataclasses into JSON via+``DataclassSerializer``. Field types are auto-derived from the contract types;+``help_text`` is added through ``Meta.extra_kwargs`` so it flows downstream into+the OpenAPI spec, generated TypeScript types, and the ``pr_lifecycle`` MCP tool+schema.+"""++from rest_framework_dataclasses.serializers import DataclassSerializer++from products.engineering_analytics.backend.facade.contracts import (+ Author,+ CICardSummary,+ CIStatusRollup,+ PRLifecycle,+ PRLifecycleEvent,+ PullRequest,+ PullRequestList,+ PullRequestListItem,+ RepoRef,+ WorkflowHealthItem,+)+++class RepoRefSerializer(DataclassSerializer):+ class Meta:+ dataclass = RepoRef+ extra_kwargs = {+ "provider": {"help_text": "Code host provider, e.g. 'github'."},+ "owner": {"help_text": "Repository owner or organization."},+ "name": {"help_text": "Repository name."},+ }+++class AuthorSerializer(DataclassSerializer):+ class Meta:+ dataclass = Author+ extra_kwargs = {+ "handle": {"help_text": "Login handle of the pull request author."},+ "display_name": {"help_text": "Human-readable name; equals the handle in v1."},+ "avatar_url": {"help_text": "URL of the author's avatar image."},+ "is_bot": {"help_text": "True if the author is a bot (handle ends in [bot] or is a known bot)."},+ }+++class PullRequestSerializer(DataclassSerializer):+ author = AuthorSerializer(help_text="The pull request author.")+ repo = RepoRefSerializer(help_text="Repository the pull request belongs to.")++ class Meta:+ dataclass = PullRequest+ extra_kwargs = {+ "id": {"help_text": "GitHub pull request id."},+ "number": {"help_text": "Pull request number within the repository."},+ "title": {"help_text": "Pull request title."},+ "state": {"help_text": "Derived state: 'open', 'closed', or 'merged'."},+ "is_draft": {"help_text": "True if the pull request is a draft."},+ "created_at": {"help_text": "When the pull request was opened."},+ "merged_at": {"help_text": "When the pull request was merged, or null.", "allow_null": True},+ "closed_at": {"help_text": "When the pull request was closed, or null.", "allow_null": True},+ }+++class PRLifecycleEventSerializer(DataclassSerializer):+ class Meta:+ dataclass = PRLifecycleEvent+ extra_kwargs = {+ "kind": {"help_text": "Event kind: opened, ci_started, ci_finished, merged, or closed."},+ "at": {"help_text": "When the event occurred."},+ "detail": {+ "help_text": "Optional detail, e.g. workflow name and conclusion for CI events.",+ "allow_null": True,+ },+ }+++class PRLifecycleSerializer(DataclassSerializer):+ pull_request = PullRequestSerializer(help_text="The pull request header.")+ events = PRLifecycleEventSerializer(many=True, help_text="Lifecycle events ordered by time.")++ class Meta:+ dataclass = PRLifecycle+ extra_kwargs = {+ "metric_quality": {+ "help_text": "Always 'partial' — CI events only; reviews and comments are not yet available.",+ },+ }+++class CIStatusRollupSerializer(DataclassSerializer):+ class Meta:+ dataclass = CIStatusRollup+ extra_kwargs = {+ "runs": {"help_text": "Distinct workflows run on the PR's head SHA."},+ "passing": {"help_text": "Latest runs that completed with conclusion 'success'."},+ "failing": {"help_text": "Latest runs that completed with conclusion 'failure' or 'timed_out'."},+ "pending": {"help_text": "Latest runs not yet completed (queued or in progress)."},+ }+++class PullRequestListItemSerializer(DataclassSerializer):+ author = AuthorSerializer(help_text="The pull request author.")+ repo = RepoRefSerializer(help_text="Repository the pull request belongs to.")+ ci = CIStatusRollupSerializer(help_text="CI status from the latest workflow runs on the head SHA.")++ class Meta:+ dataclass = PullRequestListItem+ extra_kwargs = {+ "number": {"help_text": "Pull request number within the repository."},+ "title": {"help_text": "Pull request title."},+ "state": {"help_text": "Derived state: 'open', 'closed', or 'merged'."},+ "is_draft": {"help_text": "True if the pull request is a draft."},+ "created_at": {"help_text": "When the pull request was opened."},+ "merged_at": {"help_text": "When the pull request was merged, or null.", "allow_null": True},+ "open_to_merge_seconds": {+ "help_text": "Coarse open-to-merge time in seconds (merged_at - created_at; fuses draft and "+ "ready-for-review time). Null until merged.",+ "allow_null": True,+ },+ "labels": {"help_text": "GitHub label names on the pull request."},+ }+++class PullRequestListSerializer(DataclassSerializer):+ items = PullRequestListItemSerializer(many=True, help_text="Pull requests, newest first, capped at `limit`.")++ class Meta:+ dataclass = PullRequestList+ extra_kwargs = {+ "truncated": {+ "help_text": "True when more pull requests match than the cap; `items` is the newest `limit` rows "+ "and the aggregate counts in ci_cards can exceed it.",+ },+ "limit": {"help_text": "Maximum number of pull requests returned in `items`."},+ }+++class CICardSummarySerializer(DataclassSerializer):+ class Meta:+ dataclass = CICardSummary+ extra_kwargs = {+ "open_prs": {"help_text": "Count of open pull requests."},+ "repos": {"help_text": "Distinct repositories with at least one open pull request."},+ "stuck": {"help_text": "Open, non-draft, non-bot pull requests older than 7 days."},+ "failing_ci": {+ "help_text": "Open pull requests with at least one failing latest CI run. May lag until the "+ "workflow_run webhook settles late completions.",+ },+ }+++class WorkflowHealthItemSerializer(DataclassSerializer):+ class Meta:+ dataclass = WorkflowHealthItem+ extra_kwargs = {+ "workflow_name": {"help_text": "GitHub Actions workflow name."},+ "run_count": {"help_text": "Total runs started in the window."},+ "success_rate": {+ "help_text": "Fraction of completed runs that succeeded (0-1). Null if no completed runs.",+ "allow_null": True,+ },+ "p50_seconds": {+ "help_text": "Median duration of completed runs, in seconds. Null if none completed.",+ "allow_null": True,+ },+ "p95_seconds": {+ "help_text": "95th-percentile duration of completed runs, in seconds. Null if none completed.",+ "allow_null": True,+ },+ "last_failure_at": {+ "help_text": "When the most recent run with conclusion 'failure' started, or null.",+ "allow_null": True,+ },+ }diff --git a/products/engineering_analytics/backend/presentation/urls.py b/products/engineering_analytics/backend/presentation/urls.pyindex e4aaa402f6ae..538718524214 100644--- a/products/engineering_analytics/backend/presentation/urls.py+++ b/products/engineering_analytics/backend/presentation/urls.py@@ -1,3 +1,15 @@-"""URL routes for engineering_analytics."""+"""URL routes for engineering_analytics.-urlpatterns: list = []+Reference router for documentation. The real wiring lives in+``products/engineering_analytics/backend/routes.py`` (``register_routes``), which+nests the viewset onto the shared project router via auto-discovery.+"""++from rest_framework.routers import DefaultRouter++from products.engineering_analytics.backend.presentation.views import EngineeringAnalyticsViewSet++router = DefaultRouter()+router.register(r"engineering_analytics", EngineeringAnalyticsViewSet, basename="engineering_analytics")++urlpatterns = router.urlsdiff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.pyindex 59fa4a5e88ac..f56be987b194 100644--- a/products/engineering_analytics/backend/presentation/views.py+++ b/products/engineering_analytics/backend/presentation/views.py@@ -1 +1,181 @@-"""DRF views for engineering_analytics."""+"""DRF views for engineering_analytics.++Named, typed read endpoints over the curated PR/CI query builders. Each action+runs curated HogQL privately (no global view registration) and returns a typed+contract. These same endpoints back both the MCP tools and the UI:++- ``ci_cards`` — backlog headline counts.+- ``pull_requests`` — PR list with head-SHA CI rollup.+- ``workflow_health`` — per-workflow CI health over a window.+- ``pr_lifecycle`` — a single PR's header plus its ordered CI timeline.+"""++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema+from rest_framework import status, viewsets+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin++from products.engineering_analytics.backend.facade import api+from products.engineering_analytics.backend.facade.contracts import GitHubSourceNotConnectedError+from products.engineering_analytics.backend.presentation.serializers import (+ CICardSummarySerializer,+ PRLifecycleSerializer,+ PullRequestListSerializer,+ WorkflowHealthItemSerializer,+)++ENGINEERING_ANALYTICS_TAG = "engineering_analytics"++_REPO = OpenApiParameter(+ name="repo",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Optional 'owner/name' repository to disambiguate when the PR number exists in more than one "+ "connected repo.",+)++_DATE_FROM = OpenApiParameter(+ name="date_from",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.",+)++_DATE_TO = OpenApiParameter(+ name="date_to",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Window end: relative or ISO8601. Defaults to now.",+)+++def _invalid_date() -> Response:+ return Response({"detail": "Invalid date_from or date_to"}, status=status.HTTP_400_BAD_REQUEST)+++@extend_schema(tags=[ENGINEERING_ANALYTICS_TAG])+class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """PR and CI lifecycle analytics over the GitHub warehouse data."""++ scope_object = "engineering_analytics"+ scope_object_read_actions = ["ci_cards", "pull_requests", "workflow_health", "pr_lifecycle"]+ scope_object_write_actions: list[str] = []++ def handle_exception(self, exc: Exception) -> Response:+ # No GitHub warehouse source connected — every action degrades the same way.+ if isinstance(exc, GitHubSourceNotConnectedError):+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)+ return super().handle_exception(exc)++ @extend_schema(+ operation_id="engineering_analytics_ci_cards",+ responses={200: CICardSummarySerializer},+ description=(+ "Headline counts for the open-PR backlog: open PRs, distinct repos, stuck PRs (open, non-draft, "+ "non-bot, older than 7 days), and PRs with failing CI. The failing-CI count rests on the head-SHA "+ "join and can lag until late CI completions settle."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def ci_cards(self, request: Request, **kwargs) -> Response:+ result = api.get_ci_cards(team=self.team)+ return Response(CICardSummarySerializer(instance=result).data)++ @extend_schema(+ operation_id="engineering_analytics_pull_requests",+ parameters=[_DATE_FROM],+ responses={+ 200: PullRequestListSerializer,+ 400: OpenApiResponse(description="Invalid date_from."),+ },+ description=(+ "Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with "+ "its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards "+ "counts can exceed it. open_to_merge_seconds is coarse — it fuses draft and ready-for-review time; "+ "CI counts can lag until late completions settle."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def pull_requests(self, request: Request, **kwargs) -> Response:+ try:+ result = api.list_pull_requests(team=self.team, date_from=request.query_params.get("date_from") or None)+ except ValueError:+ return _invalid_date()+ return Response(PullRequestListSerializer(instance=result).data)++ @extend_schema(+ operation_id="engineering_analytics_workflow_health",+ parameters=[_DATE_FROM, _DATE_TO],+ responses={+ 200: WorkflowHealthItemSerializer(many=True),+ 400: OpenApiResponse(description="Invalid date_from or date_to."),+ },+ description=(+ "Per-workflow CI health over a window (default last 30 days): run count, success rate, p50/p95 "+ "duration over completed runs, and last failure time. Use this for 'is CI getting slower' and 'which "+ "workflow is the long pole'; compare two windows to get a trend."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def workflow_health(self, request: Request, **kwargs) -> Response:+ try:+ result = api.list_workflow_health(+ team=self.team,+ date_from=request.query_params.get("date_from") or None,+ date_to=request.query_params.get("date_to") or None,+ )+ except ValueError:+ return _invalid_date()+ return Response(WorkflowHealthItemSerializer(instance=result, many=True).data)++ @extend_schema(+ operation_id="engineering_analytics_pr_lifecycle",+ parameters=[+ OpenApiParameter(+ name="pr_number",+ type=OpenApiTypes.INT,+ location=OpenApiParameter.QUERY,+ required=True,+ description="Pull request number to inspect.",+ ),+ _REPO,+ ],+ responses={+ 200: PRLifecycleSerializer,+ 400: OpenApiResponse(description="Missing or non-integer pr_number."),+ 404: OpenApiResponse(description="No pull request with that number in the warehouse."),+ },+ description=(+ "The timeline of a single pull request: header plus ordered events (opened, CI started/finished, "+ "merged or closed). Use this to answer 'where is this PR stuck and what happened to it'. This is a "+ "partial view: review and comment events are not yet available."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def pr_lifecycle(self, request: Request, **kwargs) -> Response:+ raw_pr_number = request.query_params.get("pr_number")+ if raw_pr_number is None:+ return Response({"detail": "pr_number must be an integer"}, status=status.HTTP_400_BAD_REQUEST)+ try:+ pr_number = int(raw_pr_number)+ except ValueError:+ return Response({"detail": "pr_number must be an integer"}, status=status.HTTP_400_BAD_REQUEST)++ try:+ result = api.get_pr_lifecycle(+ team=self.team,+ pr_number=pr_number,+ repo=request.query_params.get("repo") or None,+ )+ except ValueError as err:+ return Response({"detail": str(err)}, status=status.HTTP_400_BAD_REQUEST)+ if result is None:+ return Response({"detail": "Pull request not found"}, status=status.HTTP_404_NOT_FOUND)+ return Response(PRLifecycleSerializer(instance=result).data)diff --git a/products/engineering_analytics/backend/routes.py b/products/engineering_analytics/backend/routes.pynew file mode 100644index 000000000000..09bdc120dce8--- /dev/null+++ b/products/engineering_analytics/backend/routes.py@@ -0,0 +1,12 @@+from posthog.api.routing import RouterRegistry++from products.engineering_analytics.backend.presentation.views import EngineeringAnalyticsViewSet+++def register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(+ r"engineering_analytics",+ EngineeringAnalyticsViewSet,+ "project_engineering_analytics",+ ["project_id"],+ )diff --git a/products/engineering_analytics/backend/tests/test_facade.py b/products/engineering_analytics/backend/tests/test_facade.pynew file mode 100644index 000000000000..3ea7562012fe--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_facade.py@@ -0,0 +1,39 @@+from posthog.test.base import BaseTest+from unittest import mock++from products.engineering_analytics.backend.facade import api++_LOGIC = "products.engineering_analytics.backend.facade.api.logic"+++class TestEngineeringAnalyticsFacade(BaseTest):+ def test_get_pr_lifecycle_delegates_with_defaults(self) -> None:+ with mock.patch(f"{_LOGIC}.build_pr_lifecycle", return_value=None) as build:+ assert api.get_pr_lifecycle(team=self.team, pr_number=10) is None++ build.assert_called_once_with(team=self.team, pr_number=10, repo=None)++ def test_get_pr_lifecycle_forwards_repo(self) -> None:+ with mock.patch(f"{_LOGIC}.build_pr_lifecycle", return_value=mock.sentinel.result) as build:+ result = api.get_pr_lifecycle(team=self.team, pr_number=42, repo="PostHog/posthog")++ assert result is mock.sentinel.result+ build.assert_called_once_with(team=self.team, pr_number=42, repo="PostHog/posthog")++ def test_get_ci_cards_delegates(self) -> None:+ with mock.patch(f"{_LOGIC}.build_ci_cards", return_value=mock.sentinel.result) as build:+ assert api.get_ci_cards(team=self.team) is mock.sentinel.result++ build.assert_called_once_with(team=self.team)++ def test_list_pull_requests_forwards_date_from(self) -> None:+ with mock.patch(f"{_LOGIC}.build_pull_request_list", return_value=[]) as build:+ api.list_pull_requests(team=self.team, date_from="-7d")++ build.assert_called_once_with(team=self.team, date_from="-7d")++ def test_list_workflow_health_forwards_window(self) -> None:+ with mock.patch(f"{_LOGIC}.build_workflow_health", return_value=[]) as build:+ api.list_workflow_health(team=self.team, date_from="-7d", date_to="-1d")++ build.assert_called_once_with(team=self.team, date_from="-7d", date_to="-1d")diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.pyindex e69de29bb2d1..1675a14c0765 100644--- a/products/engineering_analytics/backend/tests/test_logic.py+++ b/products/engineering_analytics/backend/tests/test_logic.py@@ -0,0 +1,375 @@+import tempfile+from datetime import UTC, datetime, timedelta+from pathlib import Path+from types import SimpleNamespace+from typing import Any++from freezegun import freeze_time+from posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest import mock++from django.utils import timezone++import pandas as pd+from parameterized import parameterized++from posthog.hogql.errors import QueryError++from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv+from products.engineering_analytics.backend.facade import api+from products.engineering_analytics.backend.facade.contracts import (+ GitHubSourceNotConnectedError,+ MetricQuality,+ PRLifecycleEventKind,+ PRState,+)+from products.engineering_analytics.backend.logic import (+ build_ci_cards,+ build_pr_lifecycle,+ build_pull_request_list,+ build_workflow_health,+)+from products.engineering_analytics.backend.logic.queries import _curated+from products.engineering_analytics.backend.tests.test_views import (+ _PULL_REQUESTS_COLUMNS,+ _WORKFLOW_RUNS_COLUMNS,+ _pr_row,+ _run_row,+)++# All query modules run through this helper; patch it to test row mapping without a warehouse.+_RUN_QUERY = "products.engineering_analytics.backend.logic.queries._curated.run_query"+_PR_LIST = "products.engineering_analytics.backend.logic.queries.pull_request_list"++TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.logic"+++def _resp(results: list[tuple]) -> SimpleNamespace:+ return SimpleNamespace(results=results)+++def _dt(value: str) -> datetime:+ return datetime.fromisoformat(value).replace(tzinfo=UTC)+++def _ago(days: int) -> str:+ # Seed dates relative to real time: HogQL now() runs server-side and ignores+ # freezegun, so window/age assertions must share the clock the query uses.+ return (timezone.now() - timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")+++def _header(+ state: str,+ *,+ merged_at: datetime | None,+ closed_at: datetime | None = None,+ is_bot: bool = False,+ head_sha: str = "sha10",+) -> tuple:+ # Mirrors the SELECT column order in query_pr_lifecycle's header query.+ return (+ 1010,+ 10,+ "PR 10",+ state,+ False,+ _dt("2026-01-10T09:00:00"),+ merged_at,+ closed_at if closed_at is not None else merged_at,+ "alice",+ "https://avatars/alice",+ is_bot,+ "PostHog",+ "posthog",+ head_sha,+ )+++class _WarehouseMixin(ClickhouseTestMixin, BaseTest):+ """Creates warehouse tables from in-memory rows; skips when object storage is+ unreachable so the suite still runs without the dev stack."""++ def _create_table(self, name: str, columns: dict, rows: list[dict[str, Any]]) -> None:+ df = pd.DataFrame(rows, columns=list(columns.keys()))+ tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False)+ df.to_csv(tmp.name, index=False)+ tmp.close()+ self.addCleanup(Path(tmp.name).unlink, missing_ok=True)+ try:+ _table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(+ csv_path=Path(tmp.name),+ table_name=name,+ table_columns=columns,+ test_bucket=TEST_BUCKET,+ team=self.team,+ source_prefix="",+ )+ except PermissionError as err:+ self.skipTest(f"object storage unavailable: {err}")+ self.addCleanup(cleanup)+++class TestPRLifecycleMapping(BaseTest):+ """HogQL parsing (parse_select runs for real) plus row mapping and event+ assembly, without touching object storage."""++ def test_assembles_ordered_events_and_marks_partial(self) -> None:+ header = _header("merged", merged_at=_dt("2026-01-12T15:00:00"))+ runs = [("CI", "completed", "success", _dt("2026-01-11T09:00:00"), _dt("2026-01-11T12:00:00"))]+ with mock.patch(_RUN_QUERY, side_effect=[_resp([header]), _resp(runs)]):+ lifecycle = build_pr_lifecycle(team=self.team, pr_number=10, repo="PostHog/posthog")++ assert lifecycle is not None+ assert lifecycle.metric_quality == MetricQuality.PARTIAL+ assert lifecycle.pull_request.state == PRState.MERGED+ assert lifecycle.pull_request.author.handle == "alice"+ assert lifecycle.pull_request.author.is_bot is False+ assert lifecycle.pull_request.repo.owner == "PostHog" and lifecycle.pull_request.repo.name == "posthog"+ assert [e.kind for e in lifecycle.events] == [+ PRLifecycleEventKind.OPENED,+ PRLifecycleEventKind.CI_STARTED,+ PRLifecycleEventKind.CI_FINISHED,+ PRLifecycleEventKind.MERGED,+ ]++ def test_returns_none_when_not_found(self) -> None:+ with mock.patch(_RUN_QUERY, return_value=_resp([])):+ assert build_pr_lifecycle(team=self.team, pr_number=999, repo=None) is None++ @parameterized.expand(["PostHog", "PostHog/", "/posthog", "/"])+ def test_malformed_repo_raises_before_querying(self, repo: str) -> None:+ # A half-specified repo must fail loudly, not silently drop the filter and+ # return a PR from the wrong repo. Raises in _split_repo before any query.+ with self.assertRaises(ValueError):+ build_pr_lifecycle(team=self.team, pr_number=10, repo=repo)++ def test_passes_through_view_derived_fields(self) -> None:+ # is_bot and state come from the curated query as columns; the logic layer does not re-derive them.+ header = _header("closed", merged_at=None, closed_at=_dt("2026-01-12T15:00:00"), is_bot=True, head_sha="")+ with mock.patch(_RUN_QUERY, return_value=_resp([header])):+ lifecycle = build_pr_lifecycle(team=self.team, pr_number=10, repo=None)++ assert lifecycle is not None+ assert lifecycle.pull_request.state == PRState.CLOSED+ assert lifecycle.pull_request.author.is_bot is True+ assert [e.kind for e in lifecycle.events] == [PRLifecycleEventKind.OPENED, PRLifecycleEventKind.CLOSED]++ @parameterized.expand(+ [+ ("open", PRState.OPEN),+ ("closed", PRState.CLOSED),+ ("merged", PRState.MERGED),+ ]+ )+ def test_state_passthrough(self, state: str, expected: PRState) -> None:+ merged_at = _dt("2026-01-12T15:00:00") if state == "merged" else None+ with mock.patch(_RUN_QUERY, return_value=_resp([_header(state, merged_at=merged_at, head_sha="")])):+ lifecycle = build_pr_lifecycle(team=self.team, pr_number=10, repo=None)++ assert lifecycle is not None+ assert lifecycle.pull_request.state == expected+++class TestEndpointMapping(BaseTest):+ """Row mapping for the aggregate endpoints (query helper mocked, no warehouse),+ plus the no-source error path."""++ def test_ci_cards_maps_counts(self) -> None:+ with mock.patch(_RUN_QUERY, return_value=_resp([(5, 2, 1, 1)])):+ cards = build_ci_cards(team=self.team)+ assert (cards.open_prs, cards.repos, cards.stuck, cards.failing_ci) == (5, 2, 1, 1)++ def test_pull_request_list_maps_row(self) -> None:+ row = (+ 10,+ "PR 10",+ "PostHog",+ "posthog",+ "alice",+ "https://avatars/alice",+ False,+ "open",+ False,+ _dt("2026-01-10T09:00:00"),+ None,+ None,+ ["bug", "p1"],+ 3,+ 2,+ 1,+ 0,+ )+ with mock.patch(_RUN_QUERY, return_value=_resp([row])):+ result = build_pull_request_list(team=self.team, date_from="-30d")++ assert result.truncated is False+ assert len(result.items) == 1+ item = result.items[0]+ assert item.number == 10+ assert item.author.handle == "alice" and item.author.is_bot is False+ assert item.repo.owner == "PostHog" and item.repo.name == "posthog"+ assert item.state == PRState.OPEN+ assert item.labels == ["bug", "p1"]+ assert item.open_to_merge_seconds is None+ assert (item.ci.runs, item.ci.passing, item.ci.failing, item.ci.pending) == (3, 2, 1, 0)++ def test_pull_request_list_flags_truncation(self) -> None:+ # Cap patched low; return more rows than the cap to exercise the N+1 overflow+ # detection — the list reports truncated instead of silently dropping the tail.+ row = (+ 10,+ "PR 10",+ "PostHog",+ "posthog",+ "alice",+ "https://avatars/alice",+ False,+ "open",+ False,+ _dt("2026-01-10T09:00:00"),+ None,+ None,+ ["bug"],+ 0,+ 0,+ 0,+ 0,+ )+ with mock.patch(f"{_PR_LIST}._LIMIT", 2), mock.patch(_RUN_QUERY, return_value=_resp([row, row, row])):+ result = build_pull_request_list(team=self.team, date_from="-30d")++ assert result.truncated is True+ assert result.limit == 2+ assert len(result.items) == 2++ def test_workflow_health_maps_and_nulls_empty_window(self) -> None:+ rows = [+ ("CI", 10, 0.9, 120.0, 600.0, _dt("2026-01-20T00:00:00")),+ # No completed runs: success_rate is NULL and quantileIf returns NaN — both map to None.+ ("Deploy", 2, None, float("nan"), float("nan"), None),+ ]+ with mock.patch(_RUN_QUERY, return_value=_resp(rows)):+ items = build_workflow_health(team=self.team, date_from="-30d", date_to=None)++ assert items[0].workflow_name == "CI" and items[0].success_rate == 0.9+ assert items[0].p50_seconds == 120.0 and items[0].p95_seconds == 600.0+ assert items[1].success_rate is None+ assert items[1].p50_seconds is None and items[1].p95_seconds is None+ assert items[1].last_failure_at is None++ @parameterized.expand(+ [+ ("github_pull_requests", GitHubSourceNotConnectedError),+ ("github_workflow_runs", GitHubSourceNotConnectedError),+ # An unrelated missing table is a real bug, not "no GitHub source" — it must+ # surface as the original QueryError rather than masquerade as a 4xx.+ ("some_typo", QueryError),+ ]+ )+ def test_unknown_table_only_translates_for_source_tables(self, table: str, expected: type[Exception]) -> None:+ with mock.patch(+ "products.engineering_analytics.backend.logic.queries._curated.execute_hogql_query",+ side_effect=QueryError(f"Unknown table `{table}`."),+ ):+ with self.assertRaises(expected):+ _curated.run_query("SELECT 1", team=self.team, query_type="engineering_analytics.test")++ def test_build_propagates_source_error(self) -> None:+ with mock.patch(_RUN_QUERY, side_effect=GitHubSourceNotConnectedError()):+ with self.assertRaises(GitHubSourceNotConnectedError):+ build_pull_request_list(team=self.team)+++class TestPRLifecycleWarehouse(_WarehouseMixin, BaseTest):+ """End-to-end through the curated builders over real warehouse tables.+ Skips when object storage is unreachable."""++ @freeze_time("2026-02-01")+ def test_pr_lifecycle_end_to_end(self) -> None:+ self._create_table(+ "github_pull_requests",+ _PULL_REQUESTS_COLUMNS,+ [+ _pr_row(+ 10, "alice", "closed", 0, "2026-01-10 09:00:00", merged_at="2026-01-12 15:00:00", head_sha="sha10"+ )+ ],+ )+ self._create_table(+ "github_workflow_runs",+ _WORKFLOW_RUNS_COLUMNS,+ [_run_row(2001, "CI", "sha10", "completed", "success", "2026-01-11 09:00:00", "2026-01-11 12:00:00")],+ )++ lifecycle = build_pr_lifecycle(team=self.team, pr_number=10, repo="PostHog/posthog")++ assert lifecycle is not None+ assert lifecycle.pull_request.state == PRState.MERGED+ assert lifecycle.pull_request.author.handle == "alice"+ assert lifecycle.pull_request.repo.name == "posthog"+ assert [e.kind for e in lifecycle.events] == [+ PRLifecycleEventKind.OPENED,+ PRLifecycleEventKind.CI_STARTED,+ PRLifecycleEventKind.CI_FINISHED,+ PRLifecycleEventKind.MERGED,+ ]+++class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):+ """End-to-end aggregates over real warehouse tables. Seeds dates relative to+ real time (HogQL now() is server-side). Skips when object storage is+ unreachable."""++ def _seed(self) -> None:+ self._create_table(+ "github_pull_requests",+ _PULL_REQUESTS_COLUMNS,+ [+ # open, recent (<7d), human, failing CI on sha10+ _pr_row(10, "alice", "open", 0, _ago(1), head_sha="sha10", labels=("bug",)),+ # open, old (>7d), human -> stuck; passing CI on sha11+ _pr_row(11, "bob", "open", 0, _ago(30), head_sha="sha11"),+ # open draft -> not stuck+ _pr_row(12, "carol", "open", 1, _ago(30), head_sha="sha12"),+ # open bot -> not stuck+ _pr_row(13, "dependabot[bot]", "open", 0, _ago(30), head_sha="sha13"),+ # merged within the default 30d window -> in the list, not open+ _pr_row(14, "alice", "closed", 0, _ago(40), merged_at=_ago(5), head_sha="sha14"),+ # merged long ago -> outside the window, excluded from the list+ _pr_row(15, "alice", "closed", 0, _ago(120), merged_at=_ago(60), head_sha="sha15"),+ ],+ )+ self._create_table(+ "github_workflow_runs",+ _WORKFLOW_RUNS_COLUMNS,+ [+ _run_row(2001, "CI", "sha10", "completed", "failure", _ago(1), _ago(1)),+ _run_row(2002, "CI", "sha11", "completed", "success", _ago(2), _ago(2)),+ ],+ )++ def test_ci_cards_counts(self) -> None:+ self._seed()+ cards = api.get_ci_cards(team=self.team)+ assert cards.open_prs == 4 # 10, 11, 12, 13+ assert cards.repos == 1 # all PostHog/posthog+ assert cards.stuck == 1 # only 11 (10 recent, 12 draft, 13 bot)+ assert cards.failing_ci == 1 # only 10 has a failing latest run++ def test_pull_request_list_window_and_rollup(self) -> None:+ self._seed()+ result = api.list_pull_requests(team=self.team)+ assert result.truncated is False+ by_number = {item.number: item for item in result.items}+ assert set(by_number) == {10, 11, 12, 13, 14} # 15 merged before the window+ assert by_number[10].ci.failing == 1+ assert by_number[11].ci.passing == 1+ assert by_number[13].author.is_bot is True++ def test_workflow_health_aggregates(self) -> None:+ self._seed()+ items = api.list_workflow_health(team=self.team)+ ci = next(item for item in items if item.workflow_name == "CI")+ assert ci.run_count == 2+ assert ci.success_rate == 0.5 # 1 success of 2 completed+ assert ci.last_failure_at is not Nonediff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex e69de29bb2d1..29b0dcb1e561 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -0,0 +1,141 @@+from datetime import UTC, datetime++from posthog.test.base import APIBaseTest+from unittest import mock++from rest_framework import status++from products.engineering_analytics.backend.facade import contracts++_VIEWS = "products.engineering_analytics.backend.presentation.views.api"+++def _pr_lifecycle() -> contracts.PRLifecycle:+ return contracts.PRLifecycle(+ pull_request=contracts.PullRequest(+ id=1010,+ number=10,+ title="PR 10",+ author=contracts.Author(handle="alice", display_name="alice", avatar_url="https://x", is_bot=False),+ repo=contracts.RepoRef(provider="github", owner="PostHog", name="posthog"),+ state=contracts.PRState.MERGED,+ is_draft=False,+ created_at=datetime(2026, 1, 10, tzinfo=UTC),+ merged_at=datetime(2026, 1, 12, tzinfo=UTC),+ closed_at=datetime(2026, 1, 12, tzinfo=UTC),+ ),+ events=[+ contracts.PRLifecycleEvent(kind=contracts.PRLifecycleEventKind.OPENED, at=datetime(2026, 1, 10, tzinfo=UTC))+ ],+ )+++def _cards() -> contracts.CICardSummary:+ return contracts.CICardSummary(open_prs=5, repos=2, stuck=1, failing_ci=1)+++def _pr_list_item() -> contracts.PullRequestListItem:+ return contracts.PullRequestListItem(+ number=10,+ title="PR 10",+ author=contracts.Author(handle="alice", display_name="alice", avatar_url="https://x", is_bot=False),+ repo=contracts.RepoRef(provider="github", owner="PostHog", name="posthog"),+ state=contracts.PRState.OPEN,+ is_draft=False,+ created_at=datetime(2026, 1, 10, tzinfo=UTC),+ merged_at=None,+ open_to_merge_seconds=None,+ labels=["bug"],+ ci=contracts.CIStatusRollup(runs=3, passing=2, failing=1, pending=0),+ )+++def _workflow_health() -> contracts.WorkflowHealthItem:+ return contracts.WorkflowHealthItem(+ workflow_name="CI",+ run_count=10,+ success_rate=0.9,+ p50_seconds=120.0,+ p95_seconds=600.0,+ last_failure_at=datetime(2026, 1, 20, tzinfo=UTC),+ )+++class TestEngineeringAnalyticsAPI(APIBaseTest):+ def _url(self, action: str) -> str:+ return f"/api/projects/{self.team.id}/engineering_analytics/{action}/"++ def test_ci_cards_serializes(self) -> None:+ with mock.patch(f"{_VIEWS}.get_ci_cards", return_value=_cards()):+ response = self.client.get(self._url("ci_cards"))++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["open_prs"] == 5++ def test_no_github_source_returns_400(self) -> None:+ with mock.patch(f"{_VIEWS}.get_ci_cards", side_effect=contracts.GitHubSourceNotConnectedError()):+ response = self.client.get(self._url("ci_cards"))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "GitHub" in response.json()["detail"]++ def test_pull_requests_serializes(self) -> None:+ result = contracts.PullRequestList(items=[_pr_list_item()], truncated=False, limit=1000)+ with mock.patch(f"{_VIEWS}.list_pull_requests", return_value=result) as listing:+ response = self.client.get(self._url("pull_requests"), {"date_from": "-7d"})++ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["truncated"] is False+ assert body["limit"] == 1000+ assert body["items"][0]["number"] == 10+ assert body["items"][0]["ci"]["failing"] == 1+ assert listing.call_args.kwargs["date_from"] == "-7d"++ def test_pull_requests_400_on_bad_date(self) -> None:+ with mock.patch(f"{_VIEWS}.list_pull_requests", side_effect=ValueError("bad date")):+ response = self.client.get(self._url("pull_requests"), {"date_from": "garbage"})++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_workflow_health_serializes(self) -> None:+ with mock.patch(f"{_VIEWS}.list_workflow_health", return_value=[_workflow_health()]):+ response = self.client.get(self._url("workflow_health"))++ assert response.status_code == status.HTTP_200_OK+ assert response.json()[0]["workflow_name"] == "CI"++ def test_pr_lifecycle_serializes(self) -> None:+ with mock.patch(f"{_VIEWS}.get_pr_lifecycle", return_value=_pr_lifecycle()) as get:+ response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "10", "repo": "PostHog/posthog"})++ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["metric_quality"] == "partial"+ assert body["pull_request"]["state"] == "merged"+ assert body["events"][0]["kind"] == "opened"+ assert get.call_args.kwargs["pr_number"] == 10+ assert get.call_args.kwargs["repo"] == "PostHog/posthog"++ def test_pr_lifecycle_404_when_not_found(self) -> None:+ with mock.patch(f"{_VIEWS}.get_pr_lifecycle", return_value=None):+ response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "999"})++ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_pr_lifecycle_400_when_pr_number_invalid(self) -> None:+ response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "not-a-number"})++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_pr_lifecycle_400_on_malformed_repo(self) -> None:+ # Bare org (no '/name') would otherwise silently match the wrong repo.+ response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "10", "repo": "PostHog"})++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_requires_authentication(self) -> None:+ self.client.logout()+ response = self.client.get(self._url("pr_lifecycle"))++ assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.pynew file mode 100644index 000000000000..59849d07cb76--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_views.py@@ -0,0 +1,202 @@+import tempfile+from pathlib import Path+from typing import Any++from posthog.test.base import BaseTest, ClickhouseTestMixin++import pandas as pd++from posthog.hogql.query import execute_hogql_query++from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv+from products.engineering_analytics.backend.logic.views import pull_requests, workflow_runs++TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.views"++_PULL_REQUESTS_COLUMNS = {+ "id": {"clickhouse": "Int64", "hogql": "IntegerDatabaseField"},+ "number": {"clickhouse": "Int64", "hogql": "IntegerDatabaseField"},+ "title": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "state": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "draft": {"clickhouse": "Bool", "hogql": "BooleanDatabaseField"},+ "created_at": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "updated_at": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "merged_at": {"clickhouse": "Nullable(DateTime64(3, 'UTC'))", "hogql": "DateTimeDatabaseField"},+ "closed_at": {"clickhouse": "Nullable(DateTime64(3, 'UTC'))", "hogql": "DateTimeDatabaseField"},+ "user": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "head": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "base": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "labels": {"clickhouse": "String", "hogql": "StringDatabaseField"},+}++_WORKFLOW_RUNS_COLUMNS = {+ "id": {"clickhouse": "Int64", "hogql": "IntegerDatabaseField"},+ "name": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "head_sha": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "status": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "conclusion": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "created_at": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "run_started_at": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "updated_at": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "repository": {"clickhouse": "String", "hogql": "StringDatabaseField"},+}+++def _user(login: str) -> str:+ return f'{{"login": "{login}", "avatar_url": "https://avatars/{login}"}}'+++def _base(full_name: str) -> str:+ return f'{{"repo": {{"full_name": "{full_name}"}}}}'+++def _labels(*names: str) -> str:+ return "[" + ", ".join(f'{{"name": "{name}"}}' for name in names) + "]"+++def _pr_row(+ number: int,+ login: str,+ state: str,+ draft: int,+ created_at: str,+ *,+ merged_at: str | None = None,+ head_sha: str = "",+ full_name: str = "PostHog/posthog",+ labels: tuple[str, ...] = (),+) -> dict[str, Any]:+ return {+ "id": 1000 + number,+ "number": number,+ "title": f"PR {number}",+ "state": state,+ "draft": draft,+ "created_at": created_at,+ "updated_at": merged_at or created_at,+ "merged_at": merged_at,+ "closed_at": merged_at,+ "user": _user(login),+ "head": f'{{"sha": "{head_sha}"}}',+ "base": _base(full_name),+ "labels": _labels(*labels),+ }+++def _run_row(+ run_id: int,+ name: str,+ head_sha: str,+ status: str,+ conclusion: str | None,+ run_started_at: str,+ updated_at: str,+ *,+ full_name: str = "PostHog/posthog",+) -> dict[str, Any]:+ return {+ "id": run_id,+ "name": name,+ "head_sha": head_sha,+ "status": status,+ "conclusion": conclusion,+ "created_at": run_started_at,+ "run_started_at": run_started_at,+ "updated_at": updated_at,+ "repository": f'{{"full_name": "{full_name}"}}',+ }+++class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):+ """The curated query builders, exercised as inline subqueries over real+ warehouse tables. Skips when object storage is unreachable so the suite still+ runs without the dev stack."""++ def _create_table(self, name: str, columns: dict, rows: list[dict[str, Any]]) -> None:+ df = pd.DataFrame(rows, columns=list(columns.keys()))+ tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False)+ df.to_csv(tmp.name, index=False)+ tmp.close()+ self.addCleanup(Path(tmp.name).unlink, missing_ok=True)+ try:+ _table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(+ csv_path=Path(tmp.name),+ table_name=name,+ table_columns=columns,+ test_bucket=TEST_BUCKET,+ team=self.team,+ source_prefix="",+ )+ except PermissionError as err:+ self.skipTest(f"object storage unavailable: {err}")+ self.addCleanup(cleanup)++ def _select(self, sql: str) -> list[tuple]:+ return execute_hogql_query(query=sql, team=self.team, query_type="engineering_analytics.test").results++ def test_pull_requests_view_maps_columns(self) -> None:+ self._create_table(+ "github_pull_requests",+ _PULL_REQUESTS_COLUMNS,+ [+ _pr_row(+ 10,+ "alice",+ "closed",+ 0,+ "2026-01-10 10:00:00",+ merged_at="2026-01-12 10:00:00",+ head_sha="sha10",+ labels=("bug", "p1"),+ ),+ _pr_row(11, "dependabot[bot]", "closed", 0, "2026-01-11 10:00:00", merged_at="2026-01-11 12:00:00"),+ _pr_row(12, "charlie", "open", 1, "2026-01-08 10:00:00"),+ ],+ )++ rows = self._select(+ "SELECT number, author_handle, is_bot, repo_owner, repo_name, labels, state, is_draft, "+ "head_sha, open_to_merge_seconds "+ f"FROM ({pull_requests.build_query()}) AS pr ORDER BY number"+ )++ by_number = {row[0]: row for row in rows}+ # merged human PR with labels and a head sha+ assert by_number[10][1:] == (+ "alice",+ False,+ "PostHog",+ "posthog",+ ["bug", "p1"],+ "merged",+ False,+ "sha10",+ 172800,+ )+ # bot detection from the [bot] suffix (ClickHouse Bool comes back as 1/0)+ assert by_number[11][2] == 1+ # open PR: state passthrough, draft flag, null duration+ assert by_number[12][6] == "open"+ assert by_number[12][7] == 1+ assert by_number[12][9] is None++ def test_workflow_runs_view_maps_columns(self) -> None:+ self._create_table(+ "github_workflow_runs",+ _WORKFLOW_RUNS_COLUMNS,+ [+ _run_row(2001, "CI", "sha1", "completed", "success", "2026-01-20 10:00:00", "2026-01-20 10:30:00"),+ _run_row(2002, "CI", "sha2", "completed", "failure", "2026-01-22 10:00:00", "2026-01-22 10:45:00"),+ _run_row(2003, "Deploy", "sha3", "in_progress", None, "2026-01-25 10:00:00", "2026-01-25 10:05:00"),+ ],+ )++ rows = self._select(+ "SELECT workflow_name, status, conclusion, duration_seconds, repo_owner, repo_name "+ f"FROM ({workflow_runs.build_query()}) AS r ORDER BY id"+ )++ # completed runs carry a duration; in-progress run has null duration and null conclusion+ assert rows[0] == ("CI", "completed", "success", 1800, "PostHog", "posthog")+ assert rows[1][3] == 2700+ assert rows[2] == ("Deploy", "in_progress", None, None, "PostHog", "posthog")diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..1238b5de5903--- /dev/null+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -0,0 +1,258 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+export interface CICardSummaryApi {+ /** Count of open pull requests. */+ open_prs: number+ /** Distinct repositories with at least one open pull request. */+ repos: number+ /** Open, non-draft, non-bot pull requests older than 7 days. */+ stuck: number+ /** Open pull requests with at least one failing latest CI run. May lag until the workflow_run webhook settles late completions. */+ failing_ci: number+}++export interface AuthorApi {+ /** Login handle of the pull request author. */+ handle: string+ /** Human-readable name; equals the handle in v1. */+ display_name: string+ /** URL of the author's avatar image. */+ avatar_url: string+ /** True if the author is a bot (handle ends in [bot] or is a known bot). */+ is_bot: boolean+}++export interface RepoRefApi {+ /** Code host provider, e.g. 'github'. */+ provider: string+ /** Repository owner or organization. */+ owner: string+ /** Repository name. */+ name: string+}++/**+ * * `open` - OPEN+ * `closed` - CLOSED+ * `merged` - MERGED+ */+export type EngineeringAnalyticsPRStateEnumApi =+ (typeof EngineeringAnalyticsPRStateEnumApi)[keyof typeof EngineeringAnalyticsPRStateEnumApi]++export const EngineeringAnalyticsPRStateEnumApi = {+ Open: 'open',+ Closed: 'closed',+ Merged: 'merged',+} as const++export interface PullRequestApi {+ /** The pull request author. */+ author: AuthorApi+ /** Repository the pull request belongs to. */+ repo: RepoRefApi+ /** GitHub pull request id. */+ id: number+ /** Pull request number within the repository. */+ number: number+ /** Pull request title. */+ title: string+ /** Derived state: 'open', 'closed', or 'merged'.++ * `open` - OPEN+ * `closed` - CLOSED+ * `merged` - MERGED */+ state: EngineeringAnalyticsPRStateEnumApi+ /** True if the pull request is a draft. */+ is_draft: boolean+ /** When the pull request was opened. */+ created_at: string+ /**+ * When the pull request was merged, or null.+ * @nullable+ */+ merged_at: string | null+ /**+ * When the pull request was closed, or null.+ * @nullable+ */+ closed_at: string | null+}++/**+ * * `opened` - OPENED+ * `ci_started` - CI_STARTED+ * `ci_finished` - CI_FINISHED+ * `merged` - MERGED+ * `closed` - CLOSED+ */+export type PRLifecycleEventKindEnumApi = (typeof PRLifecycleEventKindEnumApi)[keyof typeof PRLifecycleEventKindEnumApi]++export const PRLifecycleEventKindEnumApi = {+ Opened: 'opened',+ CiStarted: 'ci_started',+ CiFinished: 'ci_finished',+ Merged: 'merged',+ Closed: 'closed',+} as const++export interface PRLifecycleEventApi {+ /** Event kind: opened, ci_started, ci_finished, merged, or closed.++ * `opened` - OPENED+ * `ci_started` - CI_STARTED+ * `ci_finished` - CI_FINISHED+ * `merged` - MERGED+ * `closed` - CLOSED */+ kind: PRLifecycleEventKindEnumApi+ /** When the event occurred. */+ at: string+ /**+ * Optional detail, e.g. workflow name and conclusion for CI events.+ * @nullable+ */+ detail?: string | null+}++/**+ * * `precise` - PRECISE+ * `coarse` - COARSE+ * `partial` - PARTIAL+ */+export type MetricQualityEnumApi = (typeof MetricQualityEnumApi)[keyof typeof MetricQualityEnumApi]++export const MetricQualityEnumApi = {+ Precise: 'precise',+ Coarse: 'coarse',+ Partial: 'partial',+} as const++export interface PRLifecycleApi {+ /** The pull request header. */+ pull_request: PullRequestApi+ /** Lifecycle events ordered by time. */+ events: PRLifecycleEventApi[]+ /** Always 'partial' — CI events only; reviews and comments are not yet available.++ * `precise` - PRECISE+ * `coarse` - COARSE+ * `partial` - PARTIAL */+ metric_quality?: MetricQualityEnumApi+}++export interface CIStatusRollupApi {+ /** Distinct workflows run on the PR's head SHA. */+ runs: number+ /** Latest runs that completed with conclusion 'success'. */+ passing: number+ /** Latest runs that completed with conclusion 'failure' or 'timed_out'. */+ failing: number+ /** Latest runs not yet completed (queued or in progress). */+ pending: number+}++export interface PullRequestListItemApi {+ /** The pull request author. */+ author: AuthorApi+ /** Repository the pull request belongs to. */+ repo: RepoRefApi+ /** CI status from the latest workflow runs on the head SHA. */+ ci: CIStatusRollupApi+ /** Pull request number within the repository. */+ number: number+ /** Pull request title. */+ title: string+ /** Derived state: 'open', 'closed', or 'merged'.++ * `open` - OPEN+ * `closed` - CLOSED+ * `merged` - MERGED */+ state: EngineeringAnalyticsPRStateEnumApi+ /** True if the pull request is a draft. */+ is_draft: boolean+ /** When the pull request was opened. */+ created_at: string+ /**+ * When the pull request was merged, or null.+ * @nullable+ */+ merged_at: string | null+ /**+ * Coarse open-to-merge time in seconds (merged_at - created_at; fuses draft and ready-for-review time). Null until merged.+ * @nullable+ */+ open_to_merge_seconds: number | null+ /** GitHub label names on the pull request. */+ labels: string[]+}++export interface PullRequestListApi {+ /** Pull requests, newest first, capped at `limit`. */+ items: PullRequestListItemApi[]+ /** True when more pull requests match than the cap; `items` is the newest `limit` rows and the aggregate counts in ci_cards can exceed it. */+ truncated: boolean+ /** Maximum number of pull requests returned in `items`. */+ limit: number+}++export interface WorkflowHealthItemApi {+ /** GitHub Actions workflow name. */+ workflow_name: string+ /** Total runs started in the window. */+ run_count: number+ /**+ * Fraction of completed runs that succeeded (0-1). Null if no completed runs.+ * @nullable+ */+ success_rate: number | null+ /**+ * Median duration of completed runs, in seconds. Null if none completed.+ * @nullable+ */+ p50_seconds: number | null+ /**+ * 95th-percentile duration of completed runs, in seconds. Null if none completed.+ * @nullable+ */+ p95_seconds: number | null+ /**+ * When the most recent run with conclusion 'failure' started, or null.+ * @nullable+ */+ last_failure_at: string | null+}++export type EngineeringAnalyticsPrLifecycleParams = {+ /**+ * Pull request number to inspect.+ */+ pr_number: number+ /**+ * Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.+ */+ repo?: string+}++export type EngineeringAnalyticsPullRequestsParams = {+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string+}++export type EngineeringAnalyticsWorkflowHealthParams = {+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string+ /**+ * Window end: relative or ISO8601. Defaults to now.+ */+ date_to?: string+}diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsnew file mode 100644index 000000000000..cbc71d2bafc1--- /dev/null+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -0,0 +1,135 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ CICardSummaryApi,+ EngineeringAnalyticsPrLifecycleParams,+ EngineeringAnalyticsPullRequestsParams,+ EngineeringAnalyticsWorkflowHealthParams,+ PRLifecycleApi,+ PullRequestListApi,+ WorkflowHealthItemApi,+} from './api.schemas'++export const getEngineeringAnalyticsCiCardsUrl = (projectId: string) => {+ return `/api/projects/${projectId}/engineering_analytics/ci_cards/`+}++/**+ * Headline counts for the open-PR backlog: open PRs, distinct repos, stuck PRs (open, non-draft, non-bot, older than 7 days), and PRs with failing CI. The failing-CI count rests on the head-SHA join and can lag until late CI completions settle.+ */+export const engineeringAnalyticsCiCards = async (+ projectId: string,+ options?: RequestInit+): Promise<CICardSummaryApi> => {+ return apiMutator<CICardSummaryApi>(getEngineeringAnalyticsCiCardsUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getEngineeringAnalyticsPrLifecycleUrl = (+ projectId: string,+ params: EngineeringAnalyticsPrLifecycleParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/pr_lifecycle/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/pr_lifecycle/`+}++/**+ * The timeline of a single pull request: header plus ordered events (opened, CI started/finished, merged or closed). Use this to answer 'where is this PR stuck and what happened to it'. This is a partial view: review and comment events are not yet available.+ */+export const engineeringAnalyticsPrLifecycle = async (+ projectId: string,+ params: EngineeringAnalyticsPrLifecycleParams,+ options?: RequestInit+): Promise<PRLifecycleApi> => {+ return apiMutator<PRLifecycleApi>(getEngineeringAnalyticsPrLifecycleUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getEngineeringAnalyticsPullRequestsUrl = (+ projectId: string,+ params?: EngineeringAnalyticsPullRequestsParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/pull_requests/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/pull_requests/`+}++/**+ * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse — it fuses draft and ready-for-review time; CI counts can lag until late completions settle.+ */+export const engineeringAnalyticsPullRequests = async (+ projectId: string,+ params?: EngineeringAnalyticsPullRequestsParams,+ options?: RequestInit+): Promise<PullRequestListApi> => {+ return apiMutator<PullRequestListApi>(getEngineeringAnalyticsPullRequestsUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getEngineeringAnalyticsWorkflowHealthUrl = (+ projectId: string,+ params?: EngineeringAnalyticsWorkflowHealthParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/workflow_health/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/workflow_health/`+}++/**+ * Per-workflow CI health over a window (default last 30 days): run count, success rate, p50/p95 duration over completed runs, and last failure time. Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.+ */+export const engineeringAnalyticsWorkflowHealth = async (+ projectId: string,+ params?: EngineeringAnalyticsWorkflowHealthParams,+ options?: RequestInit+): Promise<WorkflowHealthItemApi[]> => {+ return apiMutator<WorkflowHealthItemApi[]>(getEngineeringAnalyticsWorkflowHealthUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/engineering_analytics/frontend/generated/api.zod.schemas.ts b/products/engineering_analytics/frontend/generated/api.zod.schemas.tsnew file mode 100644index 000000000000..2a1914108305--- /dev/null+++ b/products/engineering_analytics/frontend/generated/api.zod.schemas.ts@@ -0,0 +1,335 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import { z as zod } from 'zod'++export const CICardSummaryApi = zod.object({+ open_prs: zod.number().describe('Count of open pull requests.'),+ repos: zod.number().describe('Distinct repositories with at least one open pull request.'),+ stuck: zod.number().describe('Open, non-draft, non-bot pull requests older than 7 days.'),+ failing_ci: zod+ .number()+ .describe(+ 'Open pull requests with at least one failing latest CI run. May lag until the workflow_run webhook settles late completions.'+ ),+})++export type CICardSummaryApi = zod.input<typeof CICardSummaryApi>+export type CICardSummaryApiOutput = zod.output<typeof CICardSummaryApi>++export const AuthorApi = zod.object({+ handle: zod.string().describe('Login handle of the pull request author.'),+ display_name: zod.string().describe('Human-readable name; equals the handle in v1.'),+ avatar_url: zod.string().describe("URL of the author's avatar image."),+ is_bot: zod.boolean().describe('True if the author is a bot (handle ends in [bot] or is a known bot).'),+})++export type AuthorApi = zod.input<typeof AuthorApi>+export type AuthorApiOutput = zod.output<typeof AuthorApi>++export const RepoRefApi = zod.object({+ provider: zod.string().describe("Code host provider, e.g. 'github'."),+ owner: zod.string().describe('Repository owner or organization.'),+ name: zod.string().describe('Repository name.'),+})++export type RepoRefApi = zod.input<typeof RepoRefApi>+export type RepoRefApiOutput = zod.output<typeof RepoRefApi>++export const EngineeringAnalyticsPRStateEnumApi = zod+ .enum(['open', 'closed', 'merged'])+ .describe('\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED')++export type EngineeringAnalyticsPRStateEnumApi = zod.input<typeof EngineeringAnalyticsPRStateEnumApi>+export type EngineeringAnalyticsPRStateEnumApiOutput = zod.output<typeof EngineeringAnalyticsPRStateEnumApi>++export const PullRequestApi = zod.object({+ author: zod+ .object({+ handle: zod.string().describe('Login handle of the pull request author.'),+ display_name: zod.string().describe('Human-readable name; equals the handle in v1.'),+ avatar_url: zod.string().describe("URL of the author's avatar image."),+ is_bot: zod.boolean().describe('True if the author is a bot (handle ends in [bot] or is a known bot).'),+ })+ .describe('The pull request author.'),+ repo: zod+ .object({+ provider: zod.string().describe("Code host provider, e.g. 'github'."),+ owner: zod.string().describe('Repository owner or organization.'),+ name: zod.string().describe('Repository name.'),+ })+ .describe('Repository the pull request belongs to.'),+ id: zod.number().describe('GitHub pull request id.'),+ number: zod.number().describe('Pull request number within the repository.'),+ title: zod.string().describe('Pull request title.'),+ state: zod+ .enum(['open', 'closed', 'merged'])+ .describe('\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED')+ .describe(+ "Derived state: 'open', 'closed', or 'merged'.\n\n\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED"+ ),+ is_draft: zod.boolean().describe('True if the pull request is a draft.'),+ created_at: zod.iso.datetime({ offset: true }).describe('When the pull request was opened.'),+ merged_at: zod.iso.datetime({ offset: true }).nullable().describe('When the pull request was merged, or null.'),+ closed_at: zod.iso.datetime({ offset: true }).nullable().describe('When the pull request was closed, or null.'),+})++export type PullRequestApi = zod.input<typeof PullRequestApi>+export type PullRequestApiOutput = zod.output<typeof PullRequestApi>++export const PRLifecycleEventKindEnumApi = zod+ .enum(['opened', 'ci_started', 'ci_finished', 'merged', 'closed'])+ .describe(+ '\* `opened` - OPENED\n\* `ci_started` - CI_STARTED\n\* `ci_finished` - CI_FINISHED\n\* `merged` - MERGED\n\* `closed` - CLOSED'+ )++export type PRLifecycleEventKindEnumApi = zod.input<typeof PRLifecycleEventKindEnumApi>+export type PRLifecycleEventKindEnumApiOutput = zod.output<typeof PRLifecycleEventKindEnumApi>++export const PRLifecycleEventApi = zod.object({+ kind: zod+ .enum(['opened', 'ci_started', 'ci_finished', 'merged', 'closed'])+ .describe(+ '\* `opened` - OPENED\n\* `ci_started` - CI_STARTED\n\* `ci_finished` - CI_FINISHED\n\* `merged` - MERGED\n\* `closed` - CLOSED'+ )+ .describe(+ 'Event kind: opened, ci_started, ci_finished, merged, or closed.\n\n\* `opened` - OPENED\n\* `ci_started` - CI_STARTED\n\* `ci_finished` - CI_FINISHED\n\* `merged` - MERGED\n\* `closed` - CLOSED'+ ),+ at: zod.iso.datetime({ offset: true }).describe('When the event occurred.'),+ detail: zod.string().nullish().describe('Optional detail, e.g. workflow name and conclusion for CI events.'),+})++export type PRLifecycleEventApi = zod.input<typeof PRLifecycleEventApi>+export type PRLifecycleEventApiOutput = zod.output<typeof PRLifecycleEventApi>++export const MetricQualityEnumApi = zod+ .enum(['precise', 'coarse', 'partial'])+ .describe('\* `precise` - PRECISE\n\* `coarse` - COARSE\n\* `partial` - PARTIAL')++export type MetricQualityEnumApi = zod.input<typeof MetricQualityEnumApi>+export type MetricQualityEnumApiOutput = zod.output<typeof MetricQualityEnumApi>++export const PRLifecycleApi = zod.object({+ pull_request: zod+ .object({+ author: zod+ .object({+ handle: zod.string().describe('Login handle of the pull request author.'),+ display_name: zod.string().describe('Human-readable name; equals the handle in v1.'),+ avatar_url: zod.string().describe("URL of the author's avatar image."),+ is_bot: zod+ .boolean()+ .describe('True if the author is a bot (handle ends in [bot] or is a known bot).'),+ })+ .describe('The pull request author.'),+ repo: zod+ .object({+ provider: zod.string().describe("Code host provider, e.g. 'github'."),+ owner: zod.string().describe('Repository owner or organization.'),+ name: zod.string().describe('Repository name.'),+ })+ .describe('Repository the pull request belongs to.'),+ id: zod.number().describe('GitHub pull request id.'),+ number: zod.number().describe('Pull request number within the repository.'),+ title: zod.string().describe('Pull request title.'),+ state: zod+ .enum(['open', 'closed', 'merged'])+ .describe('\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED')+ .describe(+ "Derived state: 'open', 'closed', or 'merged'.\n\n\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED"+ ),+ is_draft: zod.boolean().describe('True if the pull request is a draft.'),+ created_at: zod.iso.datetime({ offset: true }).describe('When the pull request was opened.'),+ merged_at: zod.iso+ .datetime({ offset: true })+ .nullable()+ .describe('When the pull request was merged, or null.'),+ closed_at: zod.iso+ .datetime({ offset: true })+ .nullable()+ .describe('When the pull request was closed, or null.'),+ })+ .describe('The pull request header.'),+ events: zod+ .array(+ zod.object({+ kind: zod+ .enum(['opened', 'ci_started', 'ci_finished', 'merged', 'closed'])+ .describe(+ '\* `opened` - OPENED\n\* `ci_started` - CI_STARTED\n\* `ci_finished` - CI_FINISHED\n\* `merged` - MERGED\n\* `closed` - CLOSED'+ )+ .describe(+ 'Event kind: opened, ci_started, ci_finished, merged, or closed.\n\n\* `opened` - OPENED\n\* `ci_started` - CI_STARTED\n\* `ci_finished` - CI_FINISHED\n\* `merged` - MERGED\n\* `closed` - CLOSED'+ ),+ at: zod.iso.datetime({ offset: true }).describe('When the event occurred.'),+ detail: zod+ .string()+ .nullish()+ .describe('Optional detail, e.g. workflow name and conclusion for CI events.'),+ })+ )+ .describe('Lifecycle events ordered by time.'),+ metric_quality: zod+ .enum(['precise', 'coarse', 'partial'])+ .describe('\* `precise` - PRECISE\n\* `coarse` - COARSE\n\* `partial` - PARTIAL')+ .optional()+ .describe(+ "Always 'partial' — CI events only; reviews and comments are not yet available.\n\n\* `precise` - PRECISE\n\* `coarse` - COARSE\n\* `partial` - PARTIAL"+ ),+})++export type PRLifecycleApi = zod.input<typeof PRLifecycleApi>+export type PRLifecycleApiOutput = zod.output<typeof PRLifecycleApi>++export const CIStatusRollupApi = zod.object({+ runs: zod.number().describe("Distinct workflows run on the PR's head SHA."),+ passing: zod.number().describe("Latest runs that completed with conclusion 'success'."),+ failing: zod.number().describe("Latest runs that completed with conclusion 'failure' or 'timed_out'."),+ pending: zod.number().describe('Latest runs not yet completed (queued or in progress).'),+})++export type CIStatusRollupApi = zod.input<typeof CIStatusRollupApi>+export type CIStatusRollupApiOutput = zod.output<typeof CIStatusRollupApi>++export const PullRequestListItemApi = zod.object({+ author: zod+ .object({+ handle: zod.string().describe('Login handle of the pull request author.'),+ display_name: zod.string().describe('Human-readable name; equals the handle in v1.'),+ avatar_url: zod.string().describe("URL of the author's avatar image."),+ is_bot: zod.boolean().describe('True if the author is a bot (handle ends in [bot] or is a known bot).'),+ })+ .describe('The pull request author.'),+ repo: zod+ .object({+ provider: zod.string().describe("Code host provider, e.g. 'github'."),+ owner: zod.string().describe('Repository owner or organization.'),+ name: zod.string().describe('Repository name.'),+ })+ .describe('Repository the pull request belongs to.'),+ ci: zod+ .object({+ runs: zod.number().describe("Distinct workflows run on the PR's head SHA."),+ passing: zod.number().describe("Latest runs that completed with conclusion 'success'."),+ failing: zod.number().describe("Latest runs that completed with conclusion 'failure' or 'timed_out'."),+ pending: zod.number().describe('Latest runs not yet completed (queued or in progress).'),+ })+ .describe('CI status from the latest workflow runs on the head SHA.'),+ number: zod.number().describe('Pull request number within the repository.'),+ title: zod.string().describe('Pull request title.'),+ state: zod+ .enum(['open', 'closed', 'merged'])+ .describe('\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED')+ .describe(+ "Derived state: 'open', 'closed', or 'merged'.\n\n\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED"+ ),+ is_draft: zod.boolean().describe('True if the pull request is a draft.'),+ created_at: zod.iso.datetime({ offset: true }).describe('When the pull request was opened.'),+ merged_at: zod.iso.datetime({ offset: true }).nullable().describe('When the pull request was merged, or null.'),+ open_to_merge_seconds: zod+ .number()+ .nullable()+ .describe(+ 'Coarse open-to-merge time in seconds (merged_at - created_at; fuses draft and ready-for-review time). Null until merged.'+ ),+ labels: zod.array(zod.string()).describe('GitHub label names on the pull request.'),+})++export type PullRequestListItemApi = zod.input<typeof PullRequestListItemApi>+export type PullRequestListItemApiOutput = zod.output<typeof PullRequestListItemApi>++export const PullRequestListApi = zod.object({+ items: zod+ .array(+ zod.object({+ author: zod+ .object({+ handle: zod.string().describe('Login handle of the pull request author.'),+ display_name: zod.string().describe('Human-readable name; equals the handle in v1.'),+ avatar_url: zod.string().describe("URL of the author's avatar image."),+ is_bot: zod+ .boolean()+ .describe('True if the author is a bot (handle ends in [bot] or is a known bot).'),+ })+ .describe('The pull request author.'),+ repo: zod+ .object({+ provider: zod.string().describe("Code host provider, e.g. 'github'."),+ owner: zod.string().describe('Repository owner or organization.'),+ name: zod.string().describe('Repository name.'),+ })+ .describe('Repository the pull request belongs to.'),+ ci: zod+ .object({+ runs: zod.number().describe("Distinct workflows run on the PR's head SHA."),+ passing: zod.number().describe("Latest runs that completed with conclusion 'success'."),+ failing: zod+ .number()+ .describe("Latest runs that completed with conclusion 'failure' or 'timed_out'."),+ pending: zod.number().describe('Latest runs not yet completed (queued or in progress).'),+ })+ .describe('CI status from the latest workflow runs on the head SHA.'),+ number: zod.number().describe('Pull request number within the repository.'),+ title: zod.string().describe('Pull request title.'),+ state: zod+ .enum(['open', 'closed', 'merged'])+ .describe('\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED')+ .describe(+ "Derived state: 'open', 'closed', or 'merged'.\n\n\* `open` - OPEN\n\* `closed` - CLOSED\n\* `merged` - MERGED"+ ),+ is_draft: zod.boolean().describe('True if the pull request is a draft.'),+ created_at: zod.iso.datetime({ offset: true }).describe('When the pull request was opened.'),+ merged_at: zod.iso+ .datetime({ offset: true })+ .nullable()+ .describe('When the pull request was merged, or null.'),+ open_to_merge_seconds: zod+ .number()+ .nullable()+ .describe(+ 'Coarse open-to-merge time in seconds (merged_at - created_at; fuses draft and ready-for-review time). Null until merged.'+ ),+ labels: zod.array(zod.string()).describe('GitHub label names on the pull request.'),+ })+ )+ .describe('Pull requests, newest first, capped at `limit`.'),+ truncated: zod+ .boolean()+ .describe(+ 'True when more pull requests match than the cap; `items` is the newest `limit` rows and the aggregate counts in ci_cards can exceed it.'+ ),+ limit: zod.number().describe('Maximum number of pull requests returned in `items`.'),+})++export type PullRequestListApi = zod.input<typeof PullRequestListApi>+export type PullRequestListApiOutput = zod.output<typeof PullRequestListApi>++export const WorkflowHealthItemApi = zod.object({+ workflow_name: zod.string().describe('GitHub Actions workflow name.'),+ run_count: zod.number().describe('Total runs started in the window.'),+ success_rate: zod+ .number()+ .nullable()+ .describe('Fraction of completed runs that succeeded (0-1). Null if no completed runs.'),+ p50_seconds: zod+ .number()+ .nullable()+ .describe('Median duration of completed runs, in seconds. Null if none completed.'),+ p95_seconds: zod+ .number()+ .nullable()+ .describe('95th-percentile duration of completed runs, in seconds. Null if none completed.'),+ last_failure_at: zod.iso+ .datetime({ offset: true })+ .nullable()+ .describe("When the most recent run with conclusion 'failure' started, or null."),+})++export type WorkflowHealthItemApi = zod.input<typeof WorkflowHealthItemApi>+export type WorkflowHealthItemApiOutput = zod.output<typeof WorkflowHealthItemApi>diff --git a/products/engineering_analytics/frontend/generated/api.zod.ts b/products/engineering_analytics/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..e8a15d4e1b52--- /dev/null+++ b/products/engineering_analytics/frontend/generated/api.zod.ts@@ -0,0 +1,9 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */diff --git a/products/engineering_analytics/package.json b/products/engineering_analytics/package.jsonindex b8bd7bdb10e4..6789d340a448 100644--- a/products/engineering_analytics/package.json+++ b/products/engineering_analytics/package.json@@ -1,6 +1,7 @@{"name": "@posthog/products-engineering-analytics","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",+ "backend:contract-check": "echo 'Contract files unchanged'"}}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f552cf2aff76..289a9804600e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7870,6 +7870,17 @@ export namespace Schemas {PositionBased: 'position_based',} as const;+ export interface Author {+ /** Login handle of the pull request author. */+ handle: string;+ /** Human-readable name; equals the handle in v1. */+ display_name: string;+ /** URL of the author's avatar image. */+ avatar_url: string;+ /** True if the author is a bot (handle ends in [bot] or is a known bot). */+ is_bot: boolean;+ }+export type AutocompleteCompletionItemKind = typeof AutocompleteCompletionItemKind[keyof typeof AutocompleteCompletionItemKind];@@ -10194,6 +10205,17 @@ export namespace Schemas {Other: 'other',} as const;+ export interface CICardSummary {+ /** Count of open pull requests. */+ open_prs: number;+ /** Distinct repositories with at least one open pull request. */+ repos: number;+ /** Open, non-draft, non-bot pull requests older than 7 days. */+ stuck: number;+ /** Open pull requests with at least one failing latest CI run. May lag until the workflow_run webhook settles late completions. */+ failing_ci: number;+ }+export interface CIMDVerificationToken {readonly id: string;/** @maxLength 40 */@@ -10226,6 +10248,17 @@ export namespace Schemas {readonly value: string;}+ export interface CIStatusRollup {+ /** Distinct workflows run on the PR's head SHA. */+ runs: number;+ /** Latest runs that completed with conclusion 'success'. */+ passing: number;+ /** Latest runs that completed with conclusion 'failure' or 'timed_out'. */+ failing: number;+ /** Latest runs not yet completed (queued or in progress). */+ pending: number;+ }+export interface EventsHeatMapColumnAggregationResult {column: number;value: number;@@ -14627,6 +14660,20 @@ export namespace Schemas {Postgres: 'postgres',} as const;+ /**+ * * `open` - OPEN+ * `closed` - CLOSED+ * `merged` - MERGED+ */+ export type EngineeringAnalyticsPRStateEnum = typeof EngineeringAnalyticsPRStateEnum[keyof typeof EngineeringAnalyticsPRStateEnum];+++ export const EngineeringAnalyticsPRStateEnum = {+ Open: 'open',+ Closed: 'closed',+ Merged: 'merged',+ } as const;+/*** Serializer mixin that handles tags for objects.*/@@ -22355,6 +22402,20 @@ export namespace Schemas {SetConfigOption: 'set_config_option',} as const;+ /**+ * * `precise` - PRECISE+ * `coarse` - COARSE+ * `partial` - PARTIAL+ */+ export type MetricQualityEnum = typeof MetricQualityEnum[keyof typeof MetricQualityEnum];+++ export const MetricQualityEnum = {+ Precise: 'precise',+ Coarse: 'coarse',+ Partial: 'partial',+ } as const;+export interface MinimalPerson {/** Numeric person ID. */readonly id: number;@@ -23184,6 +23245,97 @@ export namespace Schemas {NeedsAttention: 'needs_attention',} as const;+ export interface RepoRef {+ /** Code host provider, e.g. 'github'. */+ provider: string;+ /** Repository owner or organization. */+ owner: string;+ /** Repository name. */+ name: string;+ }++ export interface PullRequest {+ /** The pull request author. */+ author: Author;+ /** Repository the pull request belongs to. */+ repo: RepoRef;+ /** GitHub pull request id. */+ id: number;+ /** Pull request number within the repository. */+ number: number;+ /** Pull request title. */+ title: string;+ /** Derived state: 'open', 'closed', or 'merged'.++ * `open` - OPEN+ * `closed` - CLOSED+ * `merged` - MERGED */+ state: EngineeringAnalyticsPRStateEnum;+ /** True if the pull request is a draft. */+ is_draft: boolean;+ /** When the pull request was opened. */+ created_at: string;+ /**+ * When the pull request was merged, or null.+ * @nullable+ */+ merged_at: string | null;+ /**+ * When the pull request was closed, or null.+ * @nullable+ */+ closed_at: string | null;+ }++ /**+ * * `opened` - OPENED+ * `ci_started` - CI_STARTED+ * `ci_finished` - CI_FINISHED+ * `merged` - MERGED+ * `closed` - CLOSED+ */+ export type PRLifecycleEventKindEnum = typeof PRLifecycleEventKindEnum[keyof typeof PRLifecycleEventKindEnum];+++ export const PRLifecycleEventKindEnum = {+ Opened: 'opened',+ CiStarted: 'ci_started',+ CiFinished: 'ci_finished',+ Merged: 'merged',+ Closed: 'closed',+ } as const;++ export interface PRLifecycleEvent {+ /** Event kind: opened, ci_started, ci_finished, merged, or closed.++ * `opened` - OPENED+ * `ci_started` - CI_STARTED+ * `ci_finished` - CI_FINISHED+ * `merged` - MERGED+ * `closed` - CLOSED */+ kind: PRLifecycleEventKindEnum;+ /** When the event occurred. */+ at: string;+ /**+ * Optional detail, e.g. workflow name and conclusion for CI events.+ * @nullable+ */+ detail?: string | null;+ }++ export interface PRLifecycle {+ /** The pull request header. */+ pull_request: PullRequest;+ /** Lifecycle events ordered by time. */+ events: PRLifecycleEvent[];+ /** Always 'partial' — CI events only; reviews and comments are not yet available.++ * `precise` - PRECISE+ * `coarse` - COARSE+ * `partial` - PARTIAL */+ metric_quality?: MetricQualityEnum;+ }+export interface PaginatedAccountList {count: number;/** @nullable */@@ -34898,6 +35050,50 @@ export namespace Schemas {max_proxy_records: number;}+ export interface PullRequestListItem {+ /** The pull request author. */+ author: Author;+ /** Repository the pull request belongs to. */+ repo: RepoRef;+ /** CI status from the latest workflow runs on the head SHA. */+ ci: CIStatusRollup;+ /** Pull request number within the repository. */+ number: number;+ /** Pull request title. */+ title: string;+ /** Derived state: 'open', 'closed', or 'merged'.++ * `open` - OPEN+ * `closed` - CLOSED+ * `merged` - MERGED */+ state: EngineeringAnalyticsPRStateEnum;+ /** True if the pull request is a draft. */+ is_draft: boolean;+ /** When the pull request was opened. */+ created_at: string;+ /**+ * When the pull request was merged, or null.+ * @nullable+ */+ merged_at: string | null;+ /**+ * Coarse open-to-merge time in seconds (merged_at - created_at; fuses draft and ready-for-review time). Null until merged.+ * @nullable+ */+ open_to_merge_seconds: number | null;+ /** GitHub label names on the pull request. */+ labels: string[];+ }++ export interface PullRequestList {+ /** Pull requests, newest first, capped at `limit`. */+ items: PullRequestListItem[];+ /** True when more pull requests match than the cap; `items` is the newest `limit` rows and the aggregate counts in ci_cards can exceed it. */+ truncated: boolean;+ /** Maximum number of pull requests returned in `items`. */+ limit: number;+ }+/*** * `ios` - iOS* `android` - Android@@ -40393,6 +40589,33 @@ export namespace Schemas {results: WidgetCatalogEntry[];}+ export interface WorkflowHealthItem {+ /** GitHub Actions workflow name. */+ workflow_name: string;+ /** Total runs started in the window. */+ run_count: number;+ /**+ * Fraction of completed runs that succeeded (0-1). Null if no completed runs.+ * @nullable+ */+ success_rate: number | null;+ /**+ * Median duration of completed runs, in seconds. Null if none completed.+ * @nullable+ */+ p50_seconds: number | null;+ /**+ * 95th-percentile duration of completed runs, in seconds. Null if none completed.+ * @nullable+ */+ p95_seconds: number | null;+ /**+ * When the most recent run with conclusion 'failure' started, or null.+ * @nullable+ */+ last_failure_at: string | null;+ }+export interface _CompareFilter {/** When true, also fetch results for a comparison window and return them under `compare`. */compare?: boolean;@@ -47058,6 +47281,35 @@ export namespace Schemas {offset?: number;};+ export type EngineeringAnalyticsPrLifecycleParams = {+ /**+ * Pull request number to inspect.+ */+ pr_number: number;+ /**+ * Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.+ */+ repo?: string;+ };++ export type EngineeringAnalyticsPullRequestsParams = {+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string;+ };++ export type EngineeringAnalyticsWorkflowHealthParams = {+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string;+ /**+ * Window end: relative or ISO8601. Defaults to now.+ */+ date_to?: string;+ };+export type EnvironmentsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex e7b9312975db..c2b6754e8324 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -57,6 +57,8 @@ export const OAUTH_SCOPES_SUPPORTED = ['early_access_feature:write','endpoint:read','endpoint:write',+ 'engineering_analytics:read',+ 'engineering_analytics:write','error_tracking:read','error_tracking:write','evaluation:read',diff --git a/tach.toml b/tach.tomlindex a0d4b7b414a7..be1b8e48e549 100644--- a/tach.toml+++ b/tach.toml@@ -77,6 +77,7 @@ depends_on = ["products.desktop_recordings","products.early_access_features","products.endpoints",+ "products.engineering_analytics","products.error_tracking","products.event_definitions","products.experiments",