Hamster Instrumentation Planning
Purpose
Make observability a first-class output of plan generation, not an afterthought caught in PR review.
Hamster Studio dual-writes to PostHog + Segment server-side, with Mixpanel session replay client-side. The infrastructure is already there. The failure mode this skill prevents is shipping a feature with no signal in PostHog — a feature that ships but cannot be measured, A/B tested, or debugged in production.
hamster-analytics covers how to call the tracking functions. This skill covers* what and why *to track — the decisions a plan must make before implementation begins.
When to Apply
Load this skill when any of these are true:
- Drafting an implementation plan for a brief, task, or feature
- Designing a new API endpoint, server action, BullMQ job, or page route
- Reviewing a plan that does not yet have an "Instrumentation" section
- Adding a user-facing surface (modal, flow, button, route, form)
- Scoping a "we should be able to see if this is working" intent
- Refactoring a code path that currently emits analytics
The Plan-Time Checklist
Every plan that ships behavior must answer these. If a row is "N/A," say so explicitly — do not omit.
| Question |
Answer must include |
| What outcome do we want to observe? |
One PostHog event in Title Case (e.g. 'Routine Triggered') |
| What is the failure signal? |
A separate event (e.g. 'Routine Failed') with error_code, attempt_count |
| Who is acting? |
user_id (third arg to trackServerEvent) |
| Which workspace? |
account_id in properties — drives Mixpanel/PostHog group analytics |
| Which session/trace? |
Auto-injected via RequestContext. Confirm code path runs inside a request OR pass IDs explicitly |
Any new user property (e.g. has_used_routines, routine_count)? |
Add to UserProperties, wire markFeatureAdoption and/or incrementEngagementCounter |
| Any new account property? |
Group trait via groupServerUser(userId, accountId, traits) |
| Should this be flag-gated? |
Either an apps/web/config/feature-flags.config.ts entry or a documented "ship to all" decision |
| Does it touch sensitive content? |
Apply mp-mask-pii / mp-sensitive selectors and document any *_pii properties |
| Is this in a BullMQ job or cron? |
Pass userId and account_id explicitly — request context does not propagate into workers |
| What dashboard will we look at? |
Name the funnel/metric — if no dashboard would be built, the event is probably not worth firing |
Plan Output: The "Instrumentation" Section
Every implementation plan should include a section like this. Use plan-instrumentation-template.md as a drop-in template.
## Instrumentation
### Events
- `Routine Triggered` (server, on successful job enqueue)
- Props: `routine_id`, `account_id`, `trigger_source` ('manual' | 'webhook' | 'schedule'), `user_id`
- `Routine Failed` (BullMQ failure handler — pass userId/account_id explicitly)
- Props: `routine_id`, `account_id`, `error_code`, `attempt_count`, `user_id`
- `Routine Run Page Viewed` — relies on PostHog autocapture; verify post-deploy
### User properties (set on first run)
- `has_used_routines: true` via `markFeatureAdoption(userId, 'routines')`
- `routine_count` incremented via `incrementEngagementCounter(userId, 'routine_count')`
### Feature flag
- `enableRoutines` in `apps/web/config/feature-flags.config.ts`. Default `false` in prod; flip via 1Password.
### PII / Session replay
- Routine input may contain user secrets — wrap textarea container with `className="mp-sensitive"`.
- No `*_pii` properties needed. Error messages truncated to first 200 chars.
### Success criteria (the dashboard we will build)
- DAU of `Routine Triggered` per account, sliced by `trigger_source`
- Funnel: `Routine Created` → `Routine Triggered` → `Routine Run Completed`
- p95 of `duration_ms` on `Routine Run Completed`
If the plan does not produce this section, the plan is incomplete.
Decision Tree by Surface
| Surface |
Capture in |
Critical thing to remember |
Server Action (enhanceAction) |
trackServerEvent() from @kit/analytics/server |
Runs inside RequestContext. account_id and $session_id auto-inject when context is bound. |
Next.js API route (enhanceRouteHandler) |
trackServerEvent() |
Same as above. |
NestJS controller / service (apps/ai) |
trackServerEvent() |
Verify the route is covered by RequestContextMiddleware (default for /ai/*). |
| BullMQ job consumer |
trackServerEvent() with explicit userId + account_id |
Jobs run outside RequestContext. Persist IDs in the job payload at enqueue time. |
| RSC / page |
PostHog autocaptures route navigation |
If conversion-critical, fire an explicit event from a Client Component. |
| Client form / interaction |
createAnalyticsTracker(analytics, ctx).trackXxx(props) |
Use the typed factory; never call posthog.capture directly. |
| Auth state change |
App event → analytics-provider.tsx mapping |
Add the AppEvent and let the provider call identify / group. Do not call them inline. |
| Cron / scheduled task |
Same as BullMQ — explicit IDs |
Add trigger_source: 'cron' to disambiguate. |
| Webhook receiver |
trackServerEvent() with explicit IDs |
Resolve user/account from the webhook payload before tracking. |
Critical Rules
- Never block on analytics. Every capture is fire-and-forget. Wrap in try/catch where the call site is hot, but rely on the SDK's
Promise.allSettled for normal use.
account_id is non-optional for any event tied to workspace data. Group analytics breaks without it.
- PII boundary is grep-able. Property keys without the
_pii suffix must not contain user-identifiable strings. See pii-and-replay.md.
session_id propagation. Server events must run inside RequestContext OR explicitly pass session_id from the originating request. Otherwise replay-to-event linkage breaks.
- State-sync goes on the triggering event. Use
$set / $set_once on the same event that mutates the property — do not fire a separate identify round-trip.
- Do not introduce a new flagging system. PostHog feature flags are not currently wired up. Use
apps/web/config/feature-flags.config.ts (1Password-backed). If a plan genuinely needs runtime flag flipping, call it out as a separate piece of work — see feature-flags.md.
- Typed events live in one place. Add new events to
packages/analytics/src/event-types.ts as part of the plan, not as a follow-up. Untyped trackServerEvent('My Event', ...) calls should not pass review.
- Do not call
posthog-js or posthog-node directly outside packages/analytics/. Always go through @kit/analytics.
Architecture (one-screen view)
Browser (apps/web)
├── instrumentation-client.ts → posthog.init() before hydration; Sentry trace stamping
├── analytics-provider.tsx → identify + group on auth events
├── createAnalyticsTracker(ctx) → typed client-side capture
└── fetch interceptor → injects x-session-id, x-page-trace-id on every request
Server (apps/web RSC + actions, apps/ai NestJS)
├── RequestContextMiddleware → reads x-session-id, binds userId/accountId
├── trackServerEvent() → dual-writes PostHog + Segment
│ auto-injects $session_id, $groups.account, $ai_trace_id
└── identifyServerUser / groupServerUser → user + account traits
BullMQ workers (apps/ai, apps/horde-v2)
└── trackServerEvent() with EXPLICIT userId + account_id (no request context here)
Full file map and env-var inventory: posthog-architecture.md.
References
| Reference |
When to read |
| plan-instrumentation-template.md |
Drop-in template for the "Instrumentation" plan section |
| posthog-architecture.md |
File map, env vars, init order, dual-write internals |
| event-design.md |
Naming, properties, $set / $set_once, feature-adoption pattern |
| multi-tenant-context.md |
Group analytics, RequestContext, BullMQ propagation |
| feature-flags.md |
Current flag system + when to consider PostHog flags |
| pii-and-replay.md |
Privacy boundary, *_pii suffix, replay masking selectors |
| trace-correlation.md |
session_id, $ai_trace_id, Sentry/OTel stitching |
Companion Skills
- hamster-analytics — implementation reference (function signatures, full event catalog)
- hamster-feature-flags — config-flag mechanics
- hamster-nest-api, hamster-nextjs-api — where in the request lifecycle to place capture calls
1---2name: hamster-instrumentation3description: "Plan-time observability for new features in Hamster Studio. Use PROACTIVELY during plan/brief generation, feature scoping, architectural design, or anytime a new endpoint, server action, BullMQ job, page route, or user-facing surface is being designed. Forces every plan to declare PostHog events, user/account properties, group context, feature flags, session-replay/PII posture, and trace correlation BEFORE code is written. Complements `hamster-analytics` (the implementation API) by making instrumentation a first-class output of planning."4version: "1.0.0"5metadata:6 source: https://skillmd.com/skills/gethamster/hamster-instrumentation7---89# Hamster Instrumentation Planning1011## Purpose1213Make observability a **first-class output of plan generation**, not an afterthought caught in PR review.1415Hamster Studio dual-writes to **PostHog + Segment** server-side, with **Mixpanel** session replay client-side. The infrastructure is already there. The failure mode this skill prevents is *shipping a feature with no signal in PostHog* — a feature that ships but cannot be measured, A/B tested, or debugged in production.1617`hamster-analytics` covers *how* to call the tracking functions. **This skill covers* what *and* why *to track** — the decisions a plan must make before implementation begins.1819## When to Apply2021Load this skill when any of these are true:2223- Drafting an implementation plan for a brief, task, or feature24- Designing a new API endpoint, server action, BullMQ job, or page route25- Reviewing a plan that does not yet have an "Instrumentation" section26- Adding a user-facing surface (modal, flow, button, route, form)27- Scoping a "we should be able to see if this is working" intent28- Refactoring a code path that currently emits analytics2930## The Plan-Time Checklist3132Every plan that ships behavior must answer these. If a row is "N/A," say so explicitly — do not omit.3334| Question | Answer must include |35| --- | --- |36| What outcome do we want to observe? | One PostHog event in Title Case (e.g. `'Routine Triggered'`) |37| What is the **failure** signal? | A separate event (e.g. `'Routine Failed'`) with `error_code`, `attempt_count` |38| Who is acting? | `user_id` (third arg to `trackServerEvent`) |39| Which workspace? | `account_id` in properties — drives Mixpanel/PostHog group analytics |40| Which session/trace? | Auto-injected via `RequestContext`. Confirm code path runs inside a request OR pass IDs explicitly |41| Any new **user property** (e.g. `has_used_routines`, `routine_count`)? | Add to `UserProperties`, wire `markFeatureAdoption` and/or `incrementEngagementCounter` |42| Any new **account property**? | Group trait via `groupServerUser(userId, accountId, traits)` |43| Should this be **flag-gated**? | Either an `apps/web/config/feature-flags.config.ts` entry or a documented "ship to all" decision |44| Does it touch sensitive content? | Apply `mp-mask-pii` / `mp-sensitive` selectors and document any `*_pii` properties |45| Is this in a **BullMQ job** or cron? | Pass `userId` and `account_id` **explicitly** — request context does not propagate into workers |46| What dashboard will we look at? | Name the funnel/metric — if no dashboard would be built, the event is probably not worth firing |4748## Plan Output: The "Instrumentation" Section4950Every implementation plan should include a section like this. Use [plan-instrumentation-template.md](references/plan-instrumentation-template.md) as a drop-in template.5152```markdown53## Instrumentation5455### Events56- `Routine Triggered` (server, on successful job enqueue)57 - Props: `routine_id`, `account_id`, `trigger_source` ('manual' | 'webhook' | 'schedule'), `user_id`58- `Routine Failed` (BullMQ failure handler — pass userId/account_id explicitly)59 - Props: `routine_id`, `account_id`, `error_code`, `attempt_count`, `user_id`60- `Routine Run Page Viewed` — relies on PostHog autocapture; verify post-deploy6162### User properties (set on first run)63- `has_used_routines: true` via `markFeatureAdoption(userId, 'routines')`64- `routine_count` incremented via `incrementEngagementCounter(userId, 'routine_count')`6566### Feature flag67- `enableRoutines` in `apps/web/config/feature-flags.config.ts`. Default `false` in prod; flip via 1Password.6869### PII / Session replay70- Routine input may contain user secrets — wrap textarea container with `className="mp-sensitive"`.71- No `*_pii` properties needed. Error messages truncated to first 200 chars.7273### Success criteria (the dashboard we will build)74- DAU of `Routine Triggered` per account, sliced by `trigger_source`75- Funnel: `Routine Created` → `Routine Triggered` → `Routine Run Completed`76- p95 of `duration_ms` on `Routine Run Completed`77```7879If the plan does not produce this section, the plan is incomplete.8081## Decision Tree by Surface8283| Surface | Capture in | Critical thing to remember |84| --- | --- | --- |85| Server Action (`enhanceAction`) | `trackServerEvent()` from `@kit/analytics/server` | Runs inside RequestContext. `account_id` and `$session_id` auto-inject when context is bound. |86| Next.js API route (`enhanceRouteHandler`) | `trackServerEvent()` | Same as above. |87| NestJS controller / service (`apps/ai`) | `trackServerEvent()` | Verify the route is covered by `RequestContextMiddleware` (default for `/ai/*`). |88| BullMQ job consumer | `trackServerEvent()` with **explicit** `userId` + `account_id` | Jobs run **outside** RequestContext. Persist IDs in the job payload at enqueue time. |89| RSC / page | PostHog autocaptures route navigation | If conversion-critical, fire an explicit event from a Client Component. |90| Client form / interaction | `createAnalyticsTracker(analytics, ctx).trackXxx(props)` | Use the typed factory; never call `posthog.capture` directly. |91| Auth state change | App event → `analytics-provider.tsx` mapping | Add the AppEvent and let the provider call `identify` / `group`. Do not call them inline. |92| Cron / scheduled task | Same as BullMQ — explicit IDs | Add `trigger_source: 'cron'` to disambiguate. |93| Webhook receiver | `trackServerEvent()` with explicit IDs | Resolve user/account from the webhook payload before tracking. |9495## Critical Rules96971. **Never block on analytics.** Every capture is fire-and-forget. Wrap in try/catch where the call site is hot, but rely on the SDK's `Promise.allSettled` for normal use.982. **`account_id` is non-optional** for any event tied to workspace data. Group analytics breaks without it.993. **PII boundary is grep-able.** Property keys without the `_pii` suffix must not contain user-identifiable strings. See [pii-and-replay.md](references/pii-and-replay.md).1004. **`session_id` propagation.** Server events must run inside RequestContext OR explicitly pass `session_id` from the originating request. Otherwise replay-to-event linkage breaks.1015. **State-sync goes on the triggering event.** Use `$set` / `$set_once` on the *same* event that mutates the property — do not fire a separate identify round-trip.1026. **Do not introduce a new flagging system.** PostHog feature flags are not currently wired up. Use `apps/web/config/feature-flags.config.ts` (1Password-backed). If a plan genuinely needs runtime flag flipping, call it out as a separate piece of work — see [feature-flags.md](references/feature-flags.md).1037. **Typed events live in one place.** Add new events to `packages/analytics/src/event-types.ts` *as part of the plan*, not as a follow-up. Untyped `trackServerEvent('My Event', ...)` calls should not pass review.1048. **Do not call `posthog-js` or `posthog-node` directly** outside `packages/analytics/`. Always go through `@kit/analytics`.105106## Architecture (one-screen view)107108```109Browser (apps/web)110├── instrumentation-client.ts → posthog.init() before hydration; Sentry trace stamping111├── analytics-provider.tsx → identify + group on auth events112├── createAnalyticsTracker(ctx) → typed client-side capture113└── fetch interceptor → injects x-session-id, x-page-trace-id on every request114115Server (apps/web RSC + actions, apps/ai NestJS)116├── RequestContextMiddleware → reads x-session-id, binds userId/accountId117├── trackServerEvent() → dual-writes PostHog + Segment118│ auto-injects $session_id, $groups.account, $ai_trace_id119└── identifyServerUser / groupServerUser → user + account traits120121BullMQ workers (apps/ai, apps/horde-v2)122└── trackServerEvent() with EXPLICIT userId + account_id (no request context here)123```124125Full file map and env-var inventory: [posthog-architecture.md](references/posthog-architecture.md).126127## References128129| Reference | When to read |130| --- | --- |131| [plan-instrumentation-template.md](references/plan-instrumentation-template.md) | Drop-in template for the "Instrumentation" plan section |132| [posthog-architecture.md](references/posthog-architecture.md) | File map, env vars, init order, dual-write internals |133| [event-design.md](references/event-design.md) | Naming, properties, `$set` / `$set_once`, feature-adoption pattern |134| [multi-tenant-context.md](references/multi-tenant-context.md) | Group analytics, RequestContext, BullMQ propagation |135| [feature-flags.md](references/feature-flags.md) | Current flag system + when to consider PostHog flags |136| [pii-and-replay.md](references/pii-and-replay.md) | Privacy boundary, `*_pii` suffix, replay masking selectors |137| [trace-correlation.md](references/trace-correlation.md) | session_id, `$ai_trace_id`, Sentry/OTel stitching |138139## Companion Skills140141- **hamster-analytics** — implementation reference (function signatures, full event catalog)142- **hamster-feature-flags** — config-flag mechanics143- **hamster-nest-api**, **hamster-nextjs-api** — where in the request lifecycle to place capture calls