git:20261114.b353ad0 to git:20261114.1296d8c

57 added, 184 removed. Audit A to A.

What this update changes in the checks

No check changed: every fixed check gives the same answer before and after this update.

A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.

---
name: gameplay-analytics
description: >-
- Use when tracking player events, implementing retention analytics, building engagement funnels, measuring D1/D7/D30 retention, or setting up gameplay telemetry. Triggers: analytics, telemetry, events, retention, D1 D7 D30, funnel, engagement, session tracking, player behavior.
+ Covers player event tracking, session tracking, cohort retention (D1, D7, D30), ordered funnels and retention targets for a game backend on PostgreSQL with a Redis buffer. Use when instrumenting what players do in a game, measuring whether players come back, finding where new players drop out of the tutorial or first match, or setting retention targets.
---
# Gameplay Analytics
- ## Purpose
-
- Genre-agnostic gameplay analytics for tracking player events, measuring retention (D1/D7/D30), building engagement funnels, session analysis, and A/B testing hooks. Uses Drizzle ORM + PostgreSQL for storage and Redis for high-throughput event buffering.
-
- ## When to Use
-
- Trigger: analytics, telemetry, player events, retention, D1/D7/D30, funnel analysis, engagement metrics, session tracking, player behavior, DAU, MAU, cohort analysis, A/B testing, event tracking
-
- ## Prerequisites
-
- - `postgres-game-schema` for base database schema and Drizzle configuration
- - `redis-game-patterns` for Redis connection and buffering infrastructure
-
- ## Core Principles
-
- > Will Wright: "I'm a big believer in metrics. You can have the best intuition in the world, but if you're not measuring what players actually do, you're designing blind."
- > Raph Koster: "The game is not what the designer thinks it is. The game is what the player does."
- > Amy Jo Kim: "Retention is not a metric to optimize. It's a signal that players are finding sustained meaning in your system."
-
- 1. **Use `noun_verb` naming for all events** — `level_completed`, `item_purchased`, `match_ended`. Consistent naming makes querying, filtering, and building dashboards trivial. Never use camelCase or free-form strings.
-
- 2. **Every event carries required context** — `userId`, `sessionId`, `timestamp`, `version`, `platform`. Without these five fields, an event is unanalyzable. Enforce this at the client level, not as a DB constraint, so malformed events are logged rather than dropped.
-
- 3. **Buffer events in Redis before writing to PostgreSQL** — game clients produce high-frequency events; writing each one directly to the database creates unsustainable write pressure. LPUSH events to a Redis list, then drain the buffer in batches via a worker. See `boilerplate/analytics-client.ts`.
-
- 4. **Track sessions explicitly: start, heartbeat, end** — don't infer sessions from event gaps. Send a `session_started` event on connect, `session_heartbeat` every 30-60 seconds, and `session_ended` on disconnect. Use a server-side idle timeout (5 minutes) to close orphaned sessions.
-
- 5. **Compute retention as cohort analysis, not rolling windows** — D1/D7/D30 retention groups players by their registration date (cohort) and measures what fraction returned on day 1, 7, and 30. Rolling "how many players were active yesterday" is DAU, not retention. See `templates/retention-dashboard.md`.
-
- 6. **Define funnels as ordered step sequences with drop-off per step** — a funnel is a list of event names in order. For each step, count how many users from the previous step completed this step. Report both absolute counts and percentage drop-off. Never hard-code funnels; make them configurable.
-
- 7. **Never block gameplay for analytics** — `track()` must be fire-and-forget. If Redis is down, log to a local buffer or drop the event. Never await a database write in the game loop. Analytics is observability, not game logic.
-
- 8. **Separate analytics tables from gameplay tables** — analytics data is append-only, high-volume, and queried differently. Keep `analytics_events`, `analytics_sessions`, and `analytics_retention_cohorts` in their own schema namespace. Don't pollute gameplay tables with telemetry columns.
-
- 9. **Plan for event volume from day one** — a game with 10K DAU generating 50 events/session produces 500K events/day. Add `createdAt` partitioning for time-range queries, archive events older than 90 days, and use materialized views or pre-aggregated tables for dashboards.
-
- 10. **A/B test by tagging events, not by forking code paths** — add an `experimentId` and `variant` to event properties. Query analytics by grouping on variant. This keeps game code clean and lets you analyze experiments retroactively from the event stream.
-
- ## Step-by-Step Instructions
-
- ### 1. Install Dependencies
-
- ```bash
- bun add drizzle-orm @neondatabase/serverless ioredis
- bun add -d drizzle-kit
- ```
-
- ### 2. Set Up the Analytics Schema
-
- Copy `boilerplate/analytics-schema.ts` into your project's schema directory. This provides three tables:
-
- - `analyticsEvents` — append-only event log with JSONB properties
- - `analyticsSessions` — session lifecycle tracking with heartbeat
- - `analyticsRetentionCohorts` — pre-computed cohort retention data
-
- Generate and run migrations:
-
- ```bash
- bunx drizzle-kit generate
- bunx drizzle-kit migrate
- ```
-
- ### 3. Initialize the Analytics Client
-
- Copy `boilerplate/analytics-client.ts` and configure it with your Redis and Drizzle instances:
-
- ```typescript
- import { AnalyticsClient } from './analytics-client';
- import { redis } from './redis-client';
- import { db } from './db';
-
- const analytics = new AnalyticsClient({ redis, db });
- ```
-
- ### 4. Instrument Events in Game Code
-
- ```typescript
- // Fire-and-forget — never await in game loop
- analytics.track('level_completed', {
- levelId: 'level_12',
- score: 4500,
- timeSeconds: 127,
- deaths: 3,
- });
-
- analytics.track('item_purchased', {
- itemId: 'sword_rare_01',
- currency: 'gold',
- amount: 500,
- });
- ```
-
- ### 5. Track Sessions
-
- ```typescript
- // On player connect
- analytics.trackSession('start');
-
- // Every 30-60 seconds while connected
- analytics.trackSession('heartbeat');
-
- // On player disconnect
- analytics.trackSession('end');
- ```
-
- ### 6. Set Up the Buffer Worker
-
- The analytics client pushes events to a Redis list. Set up a worker (via `bullmq-game-queues` or a simple interval) to drain the buffer:
-
- ```typescript
- // Run on a worker process, not the game server
- setInterval(async () => {
- await analytics.flush();
- }, 5000);
- ```
-
- ### 7. Run Retention Queries
-
- See `templates/retention-dashboard.md` for pre-built Drizzle ORM queries for D1/D7/D30 retention, DAU/MAU, session duration distribution, top events, and funnel analysis.
-
- ### 8. Build Your Event Catalog
-
- Use `templates/event-catalog.md` as a starting point to document all events in your game. Share this with your entire team so designers, producers, and engineers agree on event names and properties.
+ Events go from the game server into a Redis list, a single worker drains the list into PostgreSQL in batches, and retention and funnels run as SQL over the stored tables.
- ## Code Examples
+ Files:
- ### Tracking with A/B test variant
+ - `boilerplate/analytics-schema.ts`: copy when adding the three analytics tables (events, sessions, stored retention cohorts) to a Drizzle schema.
+ - `boilerplate/analytics-client.ts`: copy when wiring `track()`, session tracking, the buffer flush and the idle-session closer. It takes the Drizzle database and the ioredis client as parameters, so it works with any Drizzle Postgres driver.
+ - `templates/retention-dashboard.md`: read when writing retention, funnel, session-length or DAU/MAU queries. Every query in it was run on PostgreSQL 16.
+ - `templates/event-catalog.md`: copy when starting the list of events the team agrees to track.
+ - `references/sources.md`: read when you need the doc pages behind the Redis and PostgreSQL behaviour this skill relies on.
- ```typescript
- analytics.track('tutorial_step_completed', {
- step: 3,
- experimentId: 'onboarding_v2',
- variant: 'shortened',
- });
- ```
+ Related skills: `postgres-game-schema` (base schema, players table, Drizzle setup), `redis-game-patterns` (Redis connection), `bullmq-game-queues` (scheduled flush and nightly cohort jobs).
- ### Querying events by player
+ ## Rules
- ```typescript
- import { eq, and, gte } from 'drizzle-orm';
- import { analyticsEvents } from './analytics-schema';
+ 1. **Name events `noun_verb`, snake_case, past tense for finished actions**: `level_completed`, `item_purchased`, `match_ended`. Keep a finite catalog in `templates/event-catalog.md`; an event not in the catalog does not ship.
+ 2. **Every event carries `userId`, `sessionId`, `createdAt`, `version`, `platform`.** The client fills them. It drops events tracked before a session starts instead of filing them under a fake session id.
+ 3. **Never block gameplay on analytics.** `track()` returns at once and never throws. A Redis outage loses events, not frames.
+ 4. **Buffer in Redis, insert in batches.** `track()` does LPUSH. One worker per Redis key runs `flush()`, which reads the oldest batch from the list tail, inserts it, then trims it. The insert skips ids that already exist, so a crash between insert and trim replays safely. Two flushers on one key insert the same batch twice and trim twice, losing events.
+ 5. **Track sessions explicitly: start, heartbeat, end.** Do not infer sessions from gaps between events. Players crash and lose network without sending `end`, so run `closeIdleSessions(db, idleMs)` on a schedule with `idleMs` set to a few heartbeat intervals.
+ 6. **Retention is cohort-based.** A cohort is the UTC day of a player's first session. D<N> is the share of a cohort with a session on exactly cohort day + N. Report a cohort only after its day N has ended. "Players active yesterday" is DAU, not retention.
+ 7. **Funnels are ordered.** A player counts at step K only after doing step K-1. Choose the key on purpose: `session_id` for flows that must finish in one sitting (tutorial, first match), `user_id` for flows across sessions (install to first purchase). The query is in `templates/retention-dashboard.md`.
+ 8. **Store UTC, compute days in UTC.** Use `(now() AT TIME ZONE 'UTC')::date` for today. `CURRENT_DATE` follows the connection's time zone.
+ 9. **Keep analytics tables apart from gameplay tables.** They are append-only, large and read by different queries.
+ 10. **Tag experiments on the event, do not fork code paths for analytics.** Put `experimentId` and `variant` in `properties` and group by them in SQL.
- const recentEvents = await db
- .select()
- .from(analyticsEvents)
- .where(
- and(
- eq(analyticsEvents.userId, 'player_123'),
- gte(analyticsEvents.createdAt, new Date(Date.now() - 86400000)),
- ),
- )
- .orderBy(analyticsEvents.createdAt);
- ```
+ ## Setup
- ### Batch insert from Redis buffer
+ 1. Install the packages (versions this skill was checked against: `drizzle-orm` 0.45.4, `ioredis` 6.0.0). Install your Postgres driver as `postgres-game-schema` describes.
- ```typescript
- import { analyticsEvents } from './analytics-schema';
+ ```bash
+ bun add drizzle-orm ioredis
+ bun add -d drizzle-kit
+ ```
- const batch = await redis.lrange('analytics:events', 0, 499);
- if (batch.length > 0) {
- const rows = batch.map((raw) => JSON.parse(raw));
- await db.insert(analyticsEvents).values(rows);
- await redis.ltrim('analytics:events', batch.length, -1);
- }
- ```
+ 2. Copy `boilerplate/analytics-schema.ts` into your schema directory, then generate and run the migration with `bunx drizzle-kit generate` and `bunx drizzle-kit migrate`.
- See `boilerplate/analytics-client.ts` for the full implementation and `boilerplate/analytics-schema.ts` for table definitions.
+ 3. Create one client per connected player. The caller owns both connections:
- ## Cross-References
+ ```typescript
+ import { AnalyticsClient, type AnalyticsDb } from './analytics-client';
+ import type Redis from 'ioredis';
- - `postgres-game-schema` for base database schema, Drizzle config, and players table
- - `redis-game-patterns` for Redis connection, buffering, and pub/sub infrastructure
- - `bullmq-game-queues` for reliable async event processing and scheduled retention computation
+ export const analyticsFor = (redis: Redis, db: AnalyticsDb, player: { id: string; platform: string }) =>
+ new AnalyticsClient({ redis, db, userId: player.id, platform: player.platform, version: process.env.GAME_VERSION ?? 'dev' });
+ ```
- ## Pitfalls & Anti-Patterns
+ 4. Instrument the game server. Do not await these calls:
- - **Event explosion** — don't track every mouse move or frame tick. Define a finite event catalog (see `templates/event-catalog.md`) and stick to it. If you need high-frequency data (e.g., position tracking), sample at fixed intervals and batch.
- - **PII in events** — never put emails, IP addresses, or real names in event properties. Use opaque player IDs. If you need demographics, store them in a separate PII-protected table and join at query time.
- - **Missing session boundaries** — if you only track `session_started` but forget `session_ended` (common when players crash or lose connection), your session duration data is garbage. Always implement a server-side idle timeout that closes sessions after 5 minutes of no heartbeat.
- - **Confusing retention with DAU** — "50% of our players came back yesterday" is not D1 retention. D1 retention is "of the cohort that registered on day X, what percentage played on day X+1." These are fundamentally different metrics. Use cohort analysis.
- - **No sampling strategy** — at scale (100K+ DAU), storing every event is expensive. Implement sampling: track 100% of monetization events, 100% of session events, and sample gameplay events at 10-25% with a `sampled: true` flag.
- - **Writing analytics synchronously in the game loop** — if your `track()` call awaits a database write, a DB hiccup causes frame drops or timeout errors in-game. Always buffer through Redis and flush asynchronously.
- - **Hardcoding funnel steps** — funnels change as your game evolves. Store funnel definitions as configuration (JSON or DB), not as code. Let product managers update funnels without code deploys.
+ ```typescript
+ analytics.trackSession('start'); // on connect
+ analytics.track('level_completed', { levelId: 'level_12', score: 4500, deaths: 3 });
+ analytics.track('tutorial_step_completed', { step: 3, experimentId: 'onboarding_v2', variant: 'shortened' });
+ analytics.trackSession('heartbeat'); // on a fixed interval while connected
+ analytics.trackSession('end'); // on disconnect
+ ```
- ## Designer Philosophy
+ 5. In one worker process, on a schedule: call `flush()` on one `AnalyticsClient` built for that worker (`await workerClient.flush()`; it drains until the list is empty and skips, with a log line, any buffered row that is not a valid event) and `await closeIdleSessions(db, idleMs)`. Nightly, store cohorts with `storeRetentionCohorts(db, n)` for n in 1, 7, 30, from `templates/retention-dashboard.md`.
- **Will Wright** (SimCity, The Sims): Analytics is the feedback loop that closes the gap between what you designed and what players experience. In The Sims, player behavior data revealed that people spent far more time decorating houses than managing relationships — a complete surprise that reshaped expansion pack priorities. Without telemetry, that insight would have taken years of guessing.
+ ## Retention targets
- **Raph Koster** (Ultima Online, Star Wars Galaxies): In Ultima Online, emergent player behavior — like the entire ecosystem collapse from player-killed animals — was only understood in retrospect because we lacked event-level tracking. Modern games have no excuse. Every meaningful player action should produce a queryable event, because the most important design discoveries come from patterns you weren't looking for.
+ This skill gives no D1, D7 or D30 target numbers. A benchmark only compares if its source states the same definition of "day N" as rule 6, the same platform and the same genre. Set targets from your own baseline:
- **Amy Jo Kim** (Community Design): Engagement is not about maximizing time-in-game. Healthy retention curves show players finding a sustainable rhythm. If your D1 is 40% but D30 is 2%, you have an onboarding cliff, not a content problem. Analytics should surface where meaning breaks down, not just where players leave.
+ 1. Ship with the cohort job running. Wait until at least four weekly sets of cohorts have matured past day 30.
+ 2. For each of D1, D7 and D30, take the median `retention_pct` across those mature cohorts from `analytics_retention_cohorts`. That is the baseline.
+ 3. Split the baseline by `platform` and by acquisition source before comparing; a new channel changes the mix, not the game.
+ 4. Set a target as a change over the baseline that one release is meant to cause, and judge it only on cohorts that started after the release.
+ 5. Alert when a mature cohort falls well below the baseline, not when a young cohort looks low.
- ## Sources
+ ## Pitfalls
- - [Mixpanel Engineering Blog — Event Tracking Best Practices](https://mixpanel.com/blog/)
- - [Amplitude Engineering — Behavioral Analytics at Scale](https://amplitude.com/blog/engineering)
- - [GDC Vault — Player Metrics in Game Development](https://gdcvault.com)
- - [Delta DNA — Game Analytics Patterns](https://deltadna.com)
- - [GameAnalytics Documentation](https://docs.gameanalytics.com)
- - [Drizzle ORM Documentation](https://orm.drizzle.team)
- - [Redis LPUSH/LRANGE for Buffering](https://redis.io/commands/lpush/)
+ - **Event explosion.** Do not track per-frame or per-input data. If you need positions, sample on a fixed interval and send them in one event.
+ - **PII in properties.** No emails, IPs or real names. Use the opaque player id; keep demographics in a separate protected table.
+ - **Sampling events, then counting players.** Dropping a share of events and scaling counts up breaks distinct-player counts and funnels. If volume forces sampling, sample whole players (hash the player id) and record the rate. Never sample session or purchase events.
+ - **Archiving the wrong table.** Retention reads first-seen from `analytics_sessions`. Archive old `analytics_events` rows, keep sessions, or every archived player re-enters as a new cohort.
+ - **Hard-coded funnels.** Keep step lists in configuration so designers change them without a deploy.
+ - **Independent step counts.** Counting each funnel event on its own counts players who skipped earlier steps. Use the ordered query.