diff --git a/src/lib/analytics/AGENTS.md b/src/lib/analytics/AGENTS.md new file mode 100644 index 00000000..7dcc2df0 --- /dev/null +++ b/src/lib/analytics/AGENTS.md @@ -0,0 +1,77 @@ +# AGENTS.md - First-Party Analytics (server side) + +> **Parent**: `../../AGENTS.md` (commands, auth flow, Next.js 16 rules, deployment). + +## Overview + +Phase 1 of the first-party analytics feature (usage data only, replacing +Microsoft Clarity). Plain Postgres tables outside Payload, a beacon collector, +hourly rollups, 90-day raw retention, and a custom admin view at +`/admin/analytics`. The client SDK lives in `src/lib/client-analytics/` (its +README holds the event taxonomy). + +## Structure + +``` +src/lib/analytics/ + schema.ts shared DDL for all six tables (migration + test bootstrap run it) + events.ts pure taxonomy + envelope validation (client-safe, no Payload) + ingest.ts sessionization, attribution, bot filter, rate limit (raw SQL) + rollup.ts daily aggregate recomputation + retention deletes + games.ts /minigames/ -> registry key mapping + queries.ts read-side service for the admin dashboard +src/app/api/collect/route.ts beacon collector (not a Payload operation) +src/scripts/analyticsRollup.ts hourly bin (`payload analytics-rollup`) +src/scripts/analyticsPurge.ts daily bin (`payload analytics-purge`) +src/components/admin/analytics/ the /admin/analytics view (+ recharts islands) +``` + +## Never-miss rules + +- **The tables are plain SQL, not collections.** Write via + `payload.db.drizzle.execute(sql\`...\`)`; never `payload.create`. The single + DDL source is `schema.ts`: the migration `add_analytics_tables` and + `tests/test-db.ts` both execute it. Schema changes mean editing that module + AND creating a new named migration that applies the delta. +- **drizzle push must never see these tables.** The test bootstrap pushes only + the Payload schema; drizzle-kit 0.31.11's introspector breaks on composite + primary keys, so `tests/test-db.ts` drops the analytics tables BEFORE + `pushSchema` and recreates them after. Do not reorder those calls. +- **The collector bypasses Payload on purpose.** No hooks, no access control; + validation is `parseCollectEnvelope` (strict: type whitelist, size caps, + timestamp sanity), bot filtering and per-IP rate limiting are in `ingest.ts`. + It answers 204 and sets the `ptf_analytics_sid` first-party cookie. +- **Sessionization lives server-side**: 30 minutes of inactivity (`SESSION_IDLE_MS`) + closes a session even if the client keeps posting its id; expired sessions get + `ended_at`. Guest sessions link to a user retroactively on first authed flush. +- **Retention**: raw events/sessions older than 90 days are deleted by the + purge bin; the four `analytics_daily_*` aggregate tables are permanent and + must never be purged. Rollups are delete-then-insert per UTC day, so re-runs + (and the hourly cron recomputing today + yesterday) are idempotent. +- **Dashboard gating**: view registered as `admin.components.views.analytics` + in `payload.config.ts`, gated by `admin:analytics:manage` (the Nav entry in + `TechTreeNav.tsx` checks the same permission). The Payload admin panel does + NOT load the frontend shadcn CSS variables: style dashboard panels with + explicit Tailwind palette classes, never `bg-background`/`text-foreground`. + +## Cron (external, single instance) + +``` +0 * * * * payload analytics-rollup # hourly aggregates +30 4 * * * payload analytics-purge # daily retention sweep +``` + +`ANALYTICS_ROLLUP_DAY=YYYY-MM-DD` backfills one specific day. + +## Testing + +Integration tests: `tests/int/analytics.int.spec.ts` (envelope validation, +sessionization, attribution, rollup idempotency, retention). E2E smoke: +`tests/e2e/analytics.e2e.spec.ts` (dev-flag pageview lands, collector accepts +beacons, dashboard renders), enabled by `NEXT_PUBLIC_ANALYTICS_DEV=1` in +playwright.config.ts. + +## Phase 2 (not built yet) + +Heatmaps/rage/dead clicks, scroll maps, JS error + Web Vitals capture, session +timeline reconstruction ("recording" from events), Clarity removal. diff --git a/src/lib/client-analytics/README.md b/src/lib/client-analytics/README.md new file mode 100644 index 00000000..9c213db8 --- /dev/null +++ b/src/lib/client-analytics/README.md @@ -0,0 +1,106 @@ +# Client Analytics SDK (Phase 1) + +First-party, blocker-resistant usage analytics for Polaris Task Force, replacing +Microsoft Clarity (which stays mounted during the transition; removal is a later +release). Usage data only: no rrweb, no recording, no advertising tech. + +- Collector endpoint: `src/app/api/collect/route.ts` +- Server-side ingest + taxonomy validation: `src/lib/analytics/ingest.ts`, + `src/lib/analytics/events.ts` +- Tables and rollups: `src/lib/analytics/` (see its AGENTS.md) +- Admin dashboard: `/admin/analytics` (`src/components/admin/analytics/`) + +## Enablement + +The tracker mounts in exactly two layouts (all user-facing surfaces; the Payload +admin panel is deliberately NOT tracked): + +- `src/app/(frontend)/layout.tsx` (covers guests on the landing page too) +- `src/app/login/layout.tsx` + +It tracks in production builds always, and in development only when +`NEXT_PUBLIC_ANALYTICS_DEV=1` was set at build time. In dev mode every event is +also mirrored to `console.debug("[analytics]", ...)` and rows carry `env='dev'`. + +Exercise it locally: + +```bash +NEXT_PUBLIC_ANALYTICS_DEV=1 bun run dev +# open http://localhost:3000, watch console for [analytics] lines, +# then check rows: SELECT * FROM analytics_events ORDER BY id DESC LIMIT 20; +``` + +Fire-and-forget contract: every SDK entry point swallows errors with a +`console.warn("[analytics] ...")`. Analytics must never break the app. + +## Identity and sessions + +- Session id: issued by the collector as the first-party cookie + `ptf_analytics_sid` (7 days). The client echoes it on every batch; the server + also enforces the boundary itself (30 minutes of inactivity starts a new + session row). +- Anonymous id: random UUID in localStorage (`ptf_analytics_aid`) until login; + the collector attributes batches via the same-origin `payload-token` cookie + and links guest sessions to the user retroactively. +- No consent banner (locked decision: usage data only, unit-internal tool). + doNotTrack/GPC are ignored. No sampling. Full IP + UA stored per session. + +## Flush lifecycle + +Batched `fetch keepalive` POSTs every 10s, on route change, and via +`navigator.sendBeacon` on `pagehide` / tab hidden. Queue is capped at 50 events +(the server's per-batch limit); overflow drops oldest. + +SPA navigation is captured by a `usePathname()` effect plus patched +`history.pushState/replaceState`; duplicate notifications for the same path are +deduped. + +## Event taxonomy + +All rows land in `analytics_events` with `type` one of the seven values below +(the single source of truth is `ANALYTICS_EVENT_TYPES` in +`src/lib/analytics/events.ts`). `path` is the raw pathname as visited; the +dashboard groups by prefix. + +| type | when | `data` | `element` | +| ---------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------- | +| `pageview` | mount + every SPA route change | `referrerPath` / `externalReferrer`; extra keys from `annotatePageview()` (e.g. `wikiSlug`) | - | +| `click` | delegated click on interactive elements | `xPct`, `yPct` (viewport-relative percentages) | selector, visible text, w/h, trackLabel | +| `scroll` | emitted when leaving a page | `maxScrollPct` (0-100), `dwellMs` | - | +| `focus` | focusin/focusout on inputs, selects, buttons, links, editables | `action: "focus" \| "blur"` | element descriptor | +| `visible` | opt-in `data-track="label"` elements, on route change/unload | `trackLabel`, `visibleMs`, `maxRatioPct` | - | +| `heartbeat`| every 15s while `document.visibilityState === "visible"` | `ms` (elapsed visible slice, capped 60s) | - | +| `custom` | `track(name, props)` calls | `name` + flattened props; domain events below | - | + +### Domain custom events (Phase 1) + +| name | fired by | payload | +| --------------------------- | ------------------------------------------ | -------------------------------------------------- | +| `chronicle.read_progress` | first visibility of a beat/journal article | `kind: "beat"\|"journal"`, `ref`, `progressPct` | +| `chronicle.read_completed` | >=90% scrolled AND >=10s visible dwell | `kind`, `ref`, `timeMs` (visible dwell to complete) | +| `wiki.new_clicked` | WikiIndex "New page" links | `source: "toolbar" \| "empty"` | +| `wiki.article_created` | WikiEditor create success | `slug` | + +Minigames need no per-game events: `/minigames/` routes are mapped to +registry keys at rollup time (`src/lib/analytics/games.ts`), and play-session +length is the heartbeat dwell on those routes. + +## Public API + +```ts +import { track, annotatePageview } from "@/lib/client-analytics"; + +track("market.listing_viewed", { listingId: 42 }); // custom event +annotatePageview({ wikiSlug: "radio-procedures" }); // merge into current pageview +``` + +Both are safe to call anywhere in client components; they no-op when tracking +is disabled and never throw. + +## Adding a new event type or domain event + +1. Extend `ANALYTICS_EVENT_TYPES` in `src/lib/analytics/events.ts` (only for a + new structural type, not for custom events). +2. Update this README's taxonomy table. +3. If it should appear in aggregates, extend the rollup SQL in + `src/lib/analytics/rollup.ts`.