Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(agents): add web analytics support triage skill (#69796)

Lucas Ricoydb4f2c0cc0a5
diff --git a/.agents/skills/triaging-web-analytics-support/SKILL.md b/.agents/skills/triaging-web-analytics-support/SKILL.md
new file mode 100644
index 000000000000..d423db64d7d6
--- /dev/null
+++ b/.agents/skills/triaging-web-analytics-support/SKILL.md
@@ -0,0 +1,59 @@
+---
+name: triaging-web-analytics-support
+description: >
+ Triage web analytics support tickets end to end: enumerate open tickets from
+ the in-app conversations product and their Zendesk mirrors, classify each
+ into a diagnostic shape (frontend crash, "two numbers don't match", traffic
+ count drop, tracker not loading / undercounting vs a competitor, ad-platform
+ integration error, channel type misclassification), run the matching
+ playbook, and produce reply drafts plus fix PRs where warranted. Use when
+ asked to triage the web analytics support channel, investigate a web
+ analytics Zendesk or conversations ticket, or explain metric discrepancies a
+ customer reported. Internal-only: queries cross-customer support and usage
+ data; never copy customer names or their traffic numbers into public
+ artifacts (PRs, issues, commits).
+---
+
+# Triaging web analytics support tickets
+
+The job: turn a pile of open support tickets into (a) reply drafts grounded in code or data, and (b) draft PRs for real bugs.
+Most reported "bugs" are explainable semantics; most real bugs show up in error tracking or raw data before they show up in the code.
+Diagnose before writing code, and always determine which layer a symptom lives in before proposing a fix.
+
+## 1. Enumerate the queue
+
+Tickets live in the conversations product and are queryable via the PostHog MCP `execute-sql` tool against `system.support_tickets` (project 2, US).
+Zendesk mirrors carry full comment history in the data warehouse.
+See [references/ticket-queries.md](references/ticket-queries.md) for ready-to-run SQL: open-ticket scans, keyword filters, full Zendesk comment extraction (the `child_events` JSON pattern), and resolving a requester email to an org/team across US and EU regions.
+
+Slack channel `#support-web-analytics` mirrors new Zendesk tickets; the in-app ticket link in each message carries the conversations UUID.
+
+## 2. Classify the shape, then run its playbook
+
+Detailed walk-throughs with worked examples are in [references/diagnostic-playbooks.md](references/diagnostic-playbooks.md). The shapes:
+
+| Shape | Trigger phrases | First move |
+| -------------------------------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Frontend crash | "everything crashes", exception ID, stack trace | Error tracking lookup; sourcemapped frames name the file. Check both US and EU projects |
+| Two numbers don't match | "two different bounce rates", "insight X disagrees with tile Y" | Semantics first, not code: event-level vs session-entry scoping, "landing vs containing", any-event vs entry-event filters explain most of these |
+| Count drop over time | "pageviews declined", "tracking loss" | Layer split: raw stored counts vs query-side exclusion. `$pageview` vs `$pageleave` ratio, UA segmentation, SDK version pin. Bot-shaped traffic disappearing is common and is not a PostHog bug |
+| Tracker not loading / undercounts competitor | "numbers lower than <other tool>", GTM, consent, ad blockers | Runtime loading audit with Playwright against their live site: load method, first-request timing, blocklist simulation. See [references/loading-audit.md](references/loading-audit.md) |
+| Ad-platform integration error | "can't re-add source", OAuth errors, "no conversions" | Source re-creation paths, OAuth failure modes (for example Microsoft AADSTS650052), attribution join keys (exact campaign name + normalized source, both UTMs required for the fallback) |
+| Channel type misclassification | "shows as Direct", "wrong channel" | `posthog/models/channel_type/channel_definitions.json` + the decision tree in `posthog/hogql/database/schema/channel_type.py`; unknown source + stripped referrer falls through to Direct |
+
+Two cross-cutting rules:
+
+- **Determine the layer before the fix.** Capture → ingestion → stored events → query-time classification → UI. A drop in raw `count()` can't be caused by query-time bot exclusion; a classification change can't alter stored counts. State which layer the evidence points at.
+- **Check for prior art before building.** Search open issues/PRs and the channel history; several recurring asks (self-referral exclusion, AI channel type, OAuth error surfacing) have open issues with context that changes the right response.
+
+## 3. Produce artifacts
+
+- **Reply drafts**: ground every claim in a file:line, a query result, or a doc link. Offer the customer the aligned filter/property instead of only explaining why they're "wrong" (for example: session `$entry_utm_campaign` instead of event `utm_campaign`).
+- **Fix PRs**: one worktree + branch per fix, conventional commit, draft PR using the repo template. Public-repo safety: describe bugs generically; never include customer names, Zendesk numbers, or customer traffic volumes. Slack/ticket links behind auth are acceptable as origin context.
+- **Session note**: keep a running triage note (`.notes/`) with one section per ticket and an explicit "action left" marker per ticket, so a human can pick up the queue.
+
+## 4. Verification tools
+
+- Runtime loading audits and traffic simulation: [references/loading-audit.md](references/loading-audit.md).
+- Production query-side checks (per-team event series, UA splits, ingestion warnings): the `query-clickhouse-via-metabase` skill covers prod-us and prod-eu access.
+- Error tracking: MCP `query-error-tracking-issues-list` / `query-error-tracking-issue-events` with `verbosity: stack` gives sourcemapped frames.
diff --git a/.agents/skills/triaging-web-analytics-support/references/diagnostic-playbooks.md b/.agents/skills/triaging-web-analytics-support/references/diagnostic-playbooks.md
new file mode 100644
index 000000000000..41ac4a82be86
--- /dev/null
+++ b/.agents/skills/triaging-web-analytics-support/references/diagnostic-playbooks.md
@@ -0,0 +1,55 @@
+# Diagnostic playbooks by ticket shape
+
+Worked patterns from real triage sessions, anonymized. Each playbook states the evidence chain that settles the diagnosis.
+
+## Frontend crash
+
+1. Get the exception: ticket usually has an exception ID or a minified stack (`chunk-XXXX.js` frames).
+2. Search error tracking in the internal project (`query-error-tracking-issues-list` with `searchQuery` + a `/web` URL filter). The issue's `source` field gives the sourcemapped file; events with `verbosity: stack` give resolved function names.
+3. Read the named code path. Common web analytics crash class: **kea-router JSON-parses query params**, so `?someParam=123` arrives as a number and `?p=a&p=b` as an array; any persisted reducer fed from `searchParams` can hold a non-string forever and crash every selector recompute (date change, filter change) — including on scenes that only _connect_ the logic.
+4. Fix at both ends: coerce at the router boundary AND at the read path (persisted bad values outlive a boundary-only fix). Add a cheap pure-function regression test asserting non-string inputs don't throw.
+5. CI gate jobs ("X Tests Pass") fail when a dependent job is cancelled by a superseded duplicate run — read the gate log before chasing phantom test failures; a runner that failed with zero executed steps is infra, rerun it.
+
+## Two numbers don't match
+
+Almost always scoping semantics, in one of three flavors:
+
+- **Landing vs containing**: overview tiles scope sessions by "any event matches the filters"; per-path bounce/breakdown rows scope by session _entry_ value. Same filters, different denominators, both correct.
+- **Event-level filter vs session-entry breakdown**: filtering by event `utm_campaign` selects sessions containing any matching event; the UTM breakdown tile groups by session `$entry_utm_campaign`. A session that picked up the UTM mid-session matches the filter but shows "(not set)".
+- **Operator drift**: `contains` vs `equals` on URLs, path cleaning on vs off, event vs session property of the same name.
+
+Resolution: name the two definitions precisely, then hand the customer the aligned pair (filter by the session entry property when comparing against a session-scoped breakdown). Only escalate to "bug" if the two surfaces claim the _same_ definition and still disagree.
+
+Key code: `products/web_analytics/backend/hogql_queries/` (overview vs stats_table query builders), `posthog/hogql/database/schema/sessions_v2.py` (entry property aggregation).
+
+## Count drop over time
+
+The decisive question: **which layer dropped?**
+
+1. Pull the raw daily series (`count()` on events by day for their team, via `query-clickhouse-via-metabase`). If raw counts dropped, no query-time change (bot classification, exclusions, materialization) can be the cause — those never alter stored counts.
+2. Sanity checks that kill false leads fast: `$lib` + SDK version split (pinned version = no SDK regression), duplicate-UUID counts (dedup), day-of-week matched comparison (seasonality), hour-of-day spread (region/outage).
+3. The bot fingerprint: only `$pageview` drops while `$pageleave` stays flat, loss concentrated in a few UA strings collapsing 10-50x week over week, ~2 pageviews/session with no pageleave. That is non-human traffic that stopped executing the JS SDK — typically the customer's edge (WAF, bot-fight mode, JS challenge) changed, or the scraper stopped. Their server logs still count those requests, which is why "our logs look unchanged".
+4. Reply framing: PostHog stored what it received; identify the segment that vanished; ask what changed at their edge on the exact step dates; note the new lower level is closer to true human traffic.
+
+## Tracker not loading / undercounting vs a competitor
+
+Run a runtime loading audit (see [loading-audit.md](loading-audit.md)) against their live pages. Findings that recur:
+
+- **Delivery chain beats endpoint proxying**: a reverse-proxied `api_host` is unblockable, but if the SDK loads _through GTM_, blocking `googletagmanager.com` kills it anyway. First-party script + first-party endpoint or it doesn't count.
+- **Consent latency loses quick bounces**: even in banner-less regions, tag managers + consent platforms resolve asynchronously; every visitor who leaves before that window sends nothing. Measure first-request timing vs the competitor script.
+- **Compare like with like**: competitor tools differ on visit definitions, bot filtering, and cookieless counting; quantify the load-chain gap before litigating definitional gaps.
+
+## Ad-platform integration errors
+
+- Soft-deleted sources do not block re-adding (prefix checks exclude deleted rows) — "Prefix already exists" means the old source is still live.
+- OAuth reconnect failures are the top re-add blocker; Microsoft AADSTS650052 (missing tenant admin consent / service principal) surfaces as a bare `invalid_client` toast. Ask for the exact error text and _where_ it appears (sign-in popup vs field vs create toast) — each maps to a different code path.
+- Account pickers may be project-admin-gated; a member sees a permission error where an admin sees accounts.
+- Marketing analytics attribution: conversion events attribute via their own UTMs, else fall back to the last prior pageview carrying **both** `utm_campaign` and `utm_source` in the window, then LEFT JOIN on **exact case-sensitive campaign name** plus normalized source. Any miss lands in "organic". Zero paid conversions with a fat organic row means the join keys or the both-UTMs requirement failed, not the goals.
+- Native ad sources need only their stats tables synced for spend metrics; PostHog events matter only for conversion goals.
+
+## Channel type misclassification
+
+- Classification is query-time (HogQL), driven by `posthog/models/channel_type/channel_definitions.json` through the `channel_definition_dict` ClickHouse dictionary; changes reclassify history automatically.
+- The default decision tree ends in a fallback that maps _unknown_ source + `$direct` referring domain to Direct — an unrecognized `utm_source` on referrer-stripped traffic therefore reads as Direct. Fix by adding definition rows, not by changing the fallback (its behavior is pinned by tests as intentional for garbage UTMs).
+- Definition changes need a ClickHouse migration: `add_missing_channel_types` only INSERTs missing pairs; type _changes_ need a rebuild (truncate → re-insert → `SYSTEM RELOAD DICTIONARY`). Update `create_channel_definitions_file.py` too, or the next regeneration reverts the JSON.
+- Same-origin interstitials (bot challenges) destroy `document.referrer` while preserving query strings — self-referrals with intact UTMs are the signature. Mitigations: `before_send` rewrite of self-referrals, a custom channel rule on the customer's own domain, scoping the challenge down.
diff --git a/.agents/skills/triaging-web-analytics-support/references/loading-audit.md b/.agents/skills/triaging-web-analytics-support/references/loading-audit.md
new file mode 100644
index 000000000000..75eac9eaf00c
--- /dev/null
+++ b/.agents/skills/triaging-web-analytics-support/references/loading-audit.md
@@ -0,0 +1,28 @@
+# Runtime loading audit
+
+Verifies what actually happens when a browser loads the customer's site: which trackers load, via what delivery chain, how late, and what an ad blocker changes.
+This is the check the wizard's audit mode does NOT do (it is a static code review of the customer's repo) — a live-site audit is the only way to see GTM, consent, and blocker effects.
+
+## Pattern
+
+Playwright (Chromium), two passes over 2-4 representative URLs (landing page, one deep page, one with UTM params):
+
+1. **Normal pass**: real-user UA, US locale/timezone. Record every request to tracker domains with a timestamp relative to navigation start. After load + ~10s, evaluate in-page state: `window.posthog` (`__loaded`, `config.api_host`, `config.token` prefix, `person_profiles`), tag-manager containers and `dataLayer` length, consent platform object and its resolved state, competitor tracker globals and script tags.
+2. **Blocklist pass**: same, but abort requests matching an EasyPrivacy-style domain list (`googletagmanager.com`, `google-analytics.com`, analytics vendor domains). Compare which trackers survive.
+
+What to read from the results:
+
+- **Load method**: `<head>` snippet vs tag manager vs bundled. A proxied `api_host` with GTM delivery still dies when GTM is blocked — the delivery chain is the weakest link.
+- **First-request delta**: tracker's first network activity in ms after navigation, vs the competitor's. The gap is the quick-bounce blind window.
+- **Consent geo-gating**: consent platforms often don't load at all outside GDPR regions; delay in those regions is tag-manager boot, not the banner.
+
+## Caveats
+
+- **Both major SDKs suppress automation**: posthog-js and most competitors detect `navigator.webdriver` and do not send events from headless browsers. Zero capture requests in the audit is expected and says nothing about real users. Assert on script/runtime presence and timing, not on event POSTs.
+- A visit with `?utm_...` test params is harmless; never inject fabricated conversion events into a customer's project.
+- Numeric hostnames parse as IPv4 in `new URL()` — don't assert exact parsed hosts on synthetic inputs.
+
+## Prior art
+
+- Session-scoped audit script: written fresh per audit (~120 lines); an earlier full-featured CLI (`check-loading`, `new-user`, `returning-user` scenarios) lives in an internal sandbox repo with an open plan to publish as `tools/traffic-sim/`.
+- A per-page comparison table (load method, snippet location, config key/host, match vs baseline) makes partial-migration states obvious — pages missing the tracker entirely show up immediately.
diff --git a/.agents/skills/triaging-web-analytics-support/references/ticket-queries.md b/.agents/skills/triaging-web-analytics-support/references/ticket-queries.md
new file mode 100644
index 000000000000..b792ea17544e
--- /dev/null
+++ b/.agents/skills/triaging-web-analytics-support/references/ticket-queries.md
@@ -0,0 +1,61 @@
+# Ticket queries
+
+All queries run through the PostHog MCP `execute-sql` tool in the internal project (US, project 2).
+Always confirm table columns via `system.information_schema.columns` before querying a `system.*` table.
+
+## Open web analytics tickets from the conversations product
+
+```sql
+SELECT ticket_number, id, status, priority, channel_source,
+ substring(last_message_text, 1, 400) AS last_msg, created_at, message_count
+FROM system.support_tickets
+WHERE status IN ('new', 'open', 'pending')
+ AND created_at >= now() - INTERVAL 21 DAY
+ AND (last_message_text ILIKE '%web analytics%'
+ OR last_message_text ILIKE '%bounce%'
+ OR last_message_text ILIKE '%utm%'
+ OR last_message_text ILIKE '%pageview%'
+ OR email_subject ILIKE '%web analytics%')
+ORDER BY created_at DESC
+```
+
+Caveats: `last_message_text` is only the latest message and may be truncated; `message_count > 1` means there is history you have not seen.
+The keyword filter misses tickets phrased differently — also read the `#support-web-analytics` Slack channel for the Zendesk-mirrored stream.
+
+## Full comment history via the Zendesk warehouse mirror
+
+`system.support_tickets` has no messages table. The Zendesk mirror does, inside a JSON array column:
+
+```sql
+SELECT created_at, body FROM (
+ SELECT created_at,
+ JSONExtractString(
+ arrayJoin(JSONExtractArrayRaw(assumeNotNull(toString(child_events)))),
+ 'body') AS body
+ FROM zendesk.ticket_events
+ WHERE ticket_id = {zendesk_ticket_id}
+) WHERE body != ''
+ORDER BY created_at ASC
+```
+
+Notes: `assumeNotNull` is required (arrayJoin cannot sit inside Nullable); apply `LIMIT` after the subquery or arrayJoin eats it; MCP display truncates long cells, so extract fields instead of dumping raw JSON.
+
+## Resolve a requester to an org/team (US and EU)
+
+```sql
+SELECT 'us' AS region, u.email, u.current_team_id
+FROM postgres.posthog_user u WHERE u.email = '{email}'
+UNION ALL
+SELECT 'eu', u.email, u.current_team_id
+FROM eu_postgres_posthog_user u WHERE u.email = '{email}'
+```
+
+Also useful: `postgres.posthog_organizationdomain` (verified domains only — often empty for smaller orgs), `postgres.posthog_organization` by name, `all_posthog_team`.
+
+EU customer data is not queryable from the US MCP project.
+For per-team event data on either region, use the `query-clickhouse-via-metabase` skill.
+
+## Error tracking cross-reference
+
+Frontend crashes reported by EU customers usually have US occurrences too (PostHog staff and US users hit the same code).
+Search the internal project's error tracking with the MCP tools; `source` on the issue row names the sourcemapped file, and `verbosity: stack` on events gives resolved frame names, so you can go from a minified customer stack to `file:line` without a local repro.