Skip to content

PostHog (analytics, replay, flags, errors) ​

Status: steps 1–6 of 6 merged (PostHog stack complete). #948 merged 2026-10-15 11:39 IDT by yoni-monday (merge commit 4726df1c) — studio client and identity. Follow-up #975 (merged 2026-10-15 20:50 IDT, merge 81a79983) opens session replay to text, images and iframes. #953 merged 2026-10-15 12:45 IDT by yoni-monday (merge commit b384d838, head 4f80e927) — Sentry is gone from the codebase; errors go to PostHog. Follow-up #958 (merged 2026-10-15 13:55 IDT, merge b7b594e0) keeps token and distinct_id on $exception events so studio errors ingest again. Step 3 #959 (merged 2026-10-15 14:48 IDT by yoni-monday, merge e2107120, head 28de255f) replaces LangSmith with PostHog LLM analytics — live tracing is PostHog. Follow-up #965 (merged 2026-10-15 15:42 IDT, merge cd2f58b4) keeps error messages, scrubbed of secrets, instead of redacting them. Follow-up #970 (merged 2026-10-15 15:47 IDT, merge 88633182) adds app_id, tenant_id and user_id to every LLM trace event. Step 4 #971 (merged 2026-10-15 16:41 IDT by yoni-monday, merge cb7500e1) replaces the BI pipeline with PostHog events; the Cloudflare BI resources are destroyed on the next infra run. Step 5 #977 (merged 2026-10-15 21:25 IDT by yoni-monday, merge 13576e01) sends browser events straight to PostHog and removes POST /api/bi. Step 6 #982 (merged 2026-10-16 05:47 IDT by yoni-monday, merge 94410daa, head cfa4986b) moves feature flags from Flagship to PostHog and removes the admin Flags page — PostHog stack complete (6/6).

The decision ​

The PostHog stack (6 PRs) moves Brilliant onto PostHog in place of four tools we run today:

  • Sentry for studio and worker errors (see Control plane & studio) — step 2 (#953, merged; Sentry project teardown still pending)
  • LangSmith for LLM tracing (see Conductor) — step 3 (#959, merged; live tracing is PostHog)
  • The BI pipeline of events into R2 Iceberg (see BI events) — step 4 (#971, merged; the Cloudflare resources go on the next infra run). Step 5 (#977, merged) then took browser events off POST /api/bi and sends them straight to PostHog
  • Flagship feature flags (see Admin Feature Flags) — step 6 (#982, merged; Flagship apps still need an infra allow-deletes run to destroy — see rollout below)

At the end of the stack the admin's BI and Flags pages are removed. After #948 and #953, PostHog handles studio analytics and all studio/worker error tracking; Sentry is removed from the codebase (delete the Sentry project and SENTRY_AUTH_TOKEN once you have confirmed PostHog error tracking). After #959, PostHog LLM analytics is the live tracing tool (LangSmith is removed from the codebase); after #971, product events go to PostHog and the admin's BI, dashboards and SQL console pages are gone. After #977, browser events no longer go through /api/bi at all: the studio and the marketing site send them with posthog-js. After #982, feature flags evaluate via PostHog and the admin Flags page is gone; deploy the control plane, then run infra with allow-deletes to destroy the Flagship apps.

Step 1: studio client and identity (#948, merged) ​

Client. The studio (apps/control-plane/web) gets posthog-js, pinned to 1.438.9, in src/lib/posthog.ts. It initialises only when the build has both VITE_POSTHOG_TOKEN and VITE_POSTHOG_HOST. Otherwise the exported posthog is undefined and every call site (posthog?.…) does nothing. Every event is registered with env (local when the build sets none) and, when the build has one, release.

Identity. syncPostHogIdentity runs from routes/root.tsx once the /me session has loaded:

  • A signed-in user is identified by user.id with email, name, tenant_id and tenant_name, and joined to a tenant group (name, status).
  • If a different user signs in, the client resets first. It compares against the id PostHog persisted, so this holds across reloads.
  • During staff impersonation the user is not identified, so staff activity never lands on the customer's person. An already identified browser is reset instead.
  • The sign-out links (account menu, mobile account sheet, and the "Sign out" button on the signed-out screen) call posthog.reset().

Privacy is set in code, not in PostHog project settings, the same way the Sentry config enforces it today.

  • Session replay (current, after #975). Replay shows text, images and iframes. mask_all_text is false; blockSelector is only video, canvas (canvas still blocked because PostHog's 2026-05-30 defaults record canvas pixels, which no mask covers). Inputs stay masked while typed (maskAllInputs: true); a sent prompt is transcript text and is recorded with the replies. maskAttributeFn (maskReplayAttribute) redacts brilliant_token= values in attributes. #948 originally masked all text and blocked iframe, img, video and canvas.
  • Autocapture. mask_all_element_attributes stays on. Element text is not masked at capture time (mask_all_text: false is for replay), but before_send drops $el_text and the text="…" segments in $elements_chain, so click events stay as they were under #948.
  • Replay records no console output, request headers or bodies, and network performance capture is off, since it would put every request URL into replays.
  • URLs are cut to origin and path. A before_send hook runs scrubTelemetryUrls over event properties, $set and $set_once, so any URL under a key containing url, href or referrer loses its query and fragment. Studio URLs can carry secrets there, such as the link key in /install/<slug>#k=…. The helper lives in src/lib/telemetry-url.ts and is now shared with the Sentry config (stripTelemetryUrl moved there from observability/telemetry.ts).
  • The /start#<payload> hand-off from the marketing site is still read and stripped from the address bar by the entry module before Sentry, PostHog or BI start, so the visitor's prompt never reaches PostHog.

Projects per environment.

EnvironmentPostHog project
Staging666164
Prod664776
Side environmentsStaging's project, from the base control-plane wrangler.jsonc

The control-plane worker gets POSTHOG_TOKEN and POSTHOG_HOST (https://us.i.posthog.com) through deployedVars in scripts/env/lib/deployed-vars.ts. The studio build reads them as VITE_POSTHOG_TOKEN and VITE_POSTHOG_HOST through studioTelemetryBuildEnv in scripts/env/lib/telemetry.ts, which also blanks them when the target config has no valid value. The phc_ tokens are public project keys that ship in the browser bundle; the one in wrangler.jsonc is marked gitleaks:allow.

Replay: show text, images and iframes (#975, merged) ​

#975 (merged 2026-10-15 20:50 IDT by yoni-monday, merge 81a79983, head d08458c1, branch posthog-replay-unmask) is a follow-up to #948. Session replay in the studio now records text, images and iframes. Until this PR, mask_all_text and maskTextSelector: "*" masked all text, and blockSelector blocked iframe, img, video and canvas.

What landed (apps/control-plane/web/src/lib/posthog.ts):

  • mask_all_text: false and no maskTextSelector: text is recorded.
  • blockSelector: "video, canvas": images and iframes are recorded; video and canvas stay blocked.
  • maskAllInputs: true unchanged: the composer's typed prompt and password fields stay masked while they are being typed in. Once sent, a prompt is transcript text and is recorded with the replies — do not read the setting as "prompts are private".
  • mask_all_element_attributes: true, console and network recording stay off.

Credentials in recorded attributes. Replay records attributes as the DOM holds them, and generated images carry ?brilliant_token=<15-minute workspace token> in src. session_recording.maskAttributeFn (maskReplayAttribute) redacts that value everywhere it appears. rrweb records an iframe element without its src, so preview iframes never carried the token into the recording; a new URL parameter that carries a credential must be added to that function.

Autocapture. mask_all_text: false would make clicks carry the clicked text ($el_text, text="…" in $elements_chain). before_send drops both, so events stay as they were and the change stays limited to replay.

What replays show. Customer-visible text, generated app content, uploaded images, and the text inside same-origin iframes (a cross-origin frame's content is not recorded). This is meant as a temporary setting ("for now"); tighten mask_all_text and blockSelector together if replay privacy has to come back. Gotcha: gotchas/studio-frontend.md.

Not covered. Prod's replay sample rate and retention are PostHog project settings (tracked in #976).

Step 2: replace Sentry with PostHog error tracking (#953, merged) ​

#953 (merged 2026-10-15 12:45 IDT by yoni-monday, merge b384d838, head 4f80e927, branch posthog-2-errors) is the second PR in the PostHog stack, on top of merged #948. Sentry is removed from the codebase. Errors go to PostHog error tracking in the same projects as analytics (staging 666164, prod 664776).

Workers (control-plane, conductor, dispatch) ​

withTelemetry(service, handler) replaces withSentry. It reports what fetch / queue / scheduled throw (handled: false) and rethrows; handled errors and 5xx still go through captureWorkerException / captureWorkerResponse as before.

Events are plain fetch POSTs of $exception to /i/v0/e/, delivered via the invocation's waitUntil. There is no posthog-node. Scrubbing stays the same shape as the old worker telemetry: error messages run through scrubErrorText (since #965; before that, only fixed diagnostic messages), class-shaped error names (else Error), frame locations with credentials/query stripped, and static route labels. distinct_id is worker:<service> with $process_person_profile: false. Callers of captureWorkerException must run under withTelemetry (or pass their own waitUntil), or delivery is silently dropped.

POSTHOG_TOKEN / POSTHOG_HOST are set for dispatch as well (deployed vars and base wrangler.jsonc). SENTRY_DSN is gone from the worker configs.

Shared code: packages/capabilities/src/telemetry.ts; service wrangler.jsonc files; scripts/env/lib/deployed-vars.ts.

Studio ​

posthog-js exception autocapture covers unhandled errors and promise rejections (not console errors — capture_console_errors is off). captureStudioError, the React root handlers, and API-error reporting call posthog.captureException instead of Sentry. Custom React 19 onUncaughtError / onRecoverableError replace the defaults that call reportError, so those failures are not also picked up by window.onerror autocapture. Caught errors only go through console.error by default; turning console capture on would double-report them.

before_send scrubbing for $exception is an allowlist, not a denylist:

  • Error-specific keys kept: $exception_list, $exception_level, $exception_message, $exception_type (and the matching $issue_* / $sentry_* forms reduced to those shapes). Messages are kept but run through scrubErrorText (since #965; before it they collapsed to [Error details redacted]); $exception_steps is dropped. Stack frames stay.
  • $exception_level must be one of fatal | error | warning | log | info | debug; anything else is reset to "error". An absent level stays absent.
  • Custom context keys kept on exception events: source, recovery, status, env, release (EXCEPTION_CONTEXT). Later registered super-properties beyond env / release are silently dropped from $exception events — note this when adding props in steps 3–6.
  • Ingestion keys must never be stripped: token and distinct_id (INGESTION_PROPERTIES). PostHog requires both; if a before_send allowlist removes them, posthog-js logs that $exception lost its token and drops the event. Fixed in #958 (merged) — the #953 review allowlist had caused this regression on main. Unit fixtures for scrubbing must include both keys.
  • Frames keep only location fields and chunk_id. URL properties still go through the shared scrubTelemetryUrls from #948.
  • Non-error $-prefixed SDK keys still pass through (then URL-scrubbed); typed StudioErrorContext keeps call sites from smuggling a $foo key in.

Studio paths: apps/control-plane/web/src/lib/posthog.ts, apps/control-plane/web/src/observability/telemetry.ts. Gotcha note: gotchas/studio-frontend.md.

Keep token and distinct_id on $exception (#958, merged) ​

#958 (merged 2026-10-15 13:55 IDT by yoni-monday, merge b7b594e0, head 12424bcd, branch posthog-fix-exception-token) fixes a regression from the #953 review: the $exception allowlist deleted every non-$ property it did not list, including token and distinct_id. posthog-js then refused ingestion (Event '$exception' had its 'token' property removed…) and sent nothing — so no studio error reached PostHog. The unit fixture had neither key, so the test passed.

What landed: INGESTION_PROPERTIES (token, distinct_id) are never removed by the allowlist. The fixture and exact-keys assertion include both. Verified in Chromium against a local capture server: uncaught errors and unhandled rejections arrive as $exception with redacted message and kept stack frames after the fix.

If studio $exception events are still missing after this ship, see Troubleshooting (that symptom was this bug before #958).

Keep the message, scrub secrets (#965, merged) ​

#965 (merged 2026-10-15 15:42 IDT by yoni-monday, merge cd2f58b4, head 5abf0cbc, branch posthog-error-messages) is a follow-up to #953. With #953's rule, every studio error in PostHog showed [Error details redacted], so issues could not be debugged. That rule was carried over from the Sentry setup. Since #959 already sends prompt text in full to the same project, blanket redaction protected little and cost a lot.

What landed:

  • New packages/capabilities/src/error-text.ts (no dependencies, a new ./error-text export of the capabilities package, used by the studio and the Workers):
    • scrubErrorText keeps only scheme, host, and path for a URL of any scheme (https, wss, postgres, …), so credentials, query, and fragment go. It cuts the query and fragment off relative paths too (link keys ride in /install/<slug>#k=…). It replaces Bearer / Basic credentials, key=value or "key":"value" secrets (api_key, token, secret, password, x-api-key, and similar), emails, and token-like runs of 32+ characters. UUIDs stay readable, including prefixed ids like app_<uuid>. It then collapses whitespace and cuts to 300 characters.
    • errorTypeName keeps any class-shaped name (TypeError, AbortError, ApiError), otherwise Error.
  • The studio before_send and the Worker $exception builder both use it. On the Workers, Cloudflare platform messages that embed customer text in a prefix still map to fixed wording.
  • Frames: stripTelemetryUrl used to turn the engine's <anonymous> into /%3Canonymous%3E, so PostHog showed a frame with no source and no chunk id (the ? in the issue view). Engine-made names (<anonymous>, [native code]) now stay as they are.

Rule to keep (residual risk): scrubbing cannot tell that a message echoes customer text. Never build an error message from a prompt or an API body. The repo gotcha gotchas/studio-frontend.md says so. Example from the review commit: conductor naming (services/conductor/src/workspace/naming.ts) now logs a failed Gemini response body with console.warn (naming.gemini_error) and throws only gemini_<status>, because the body can echo the prompt.

After merge (from the PR): throw an error on the studio page on staging and check the message and frame in PostHog project 666164. A symbolicated frame still needs POSTHOG_CLI_API_KEY in the GitHub Environments (see Source maps).

See also Troubleshooting.

Source maps ​

Deploys run posthog-cli sourcemap inject then upload (release brilliant-studio@<sha>) into the environment's PostHog project; side environments upload to staging's project. Maps are deleted from dist/ in finally whether or not the upload succeeded, then wrangler deploy ships the injected JS. The SPA registers bare release: <sha>; matching relies on injected chunk_id.

The optional CI secret POSTHOG_CLI_API_KEY (a PostHog personal API key with scopes error tracking write and organization read) replaces SENTRY_AUTH_TOKEN. Without it, the deploy stays green, skips upload with a warning, and still strips .map files — so you get minified frames until the secret is set. Catalog and workflow: infra/secrets/catalog.ts, scripts/env/lib/sourcemaps.ts, .github/workflows/deploy.yml.

Pending ops (post-merge) ​

These checklist items from the PR are still open:

  1. Add POSTHOG_CLI_API_KEY to the staging and production GitHub Environments.
  2. Confirm a staging $exception in project 666164 (redacted message, no #k= in URL props, ideally a resolved frame after map upload). Unblocked by #958 — token/distinct_id stay on $exception events.
  3. Later teardown (after error tracking is confirmed): delete the Sentry project and the SENTRY_AUTH_TOKEN secret.

See also Secrets & environments and Control plane & studio.

Step 3: replace LangSmith with PostHog LLM analytics (#959, merged) ​

#959 (merged 2026-10-15 14:48 IDT by yoni-monday, merge e2107120, head 28de255f, branch posthog-3-llm-analytics) is the third PR in the PostHog stack, after merged #948 and #953 (and follow-up #958). It removes LangSmith and sends the coding agent's traces to PostHog LLM analytics in the same per-env projects (staging 666164, prod 664776). Live tracing is PostHog.

Live tracing (conductor) ​

  • host/posthog-tracer.ts replaces the LangSmith sink. pi/tracing.ts is unchanged apart from comments: the same spans, now sent as $ai_trace (a run), $ai_generation (a model response), and $ai_span (a tool call).
  • PostHog events are immutable, so each span is one event, sent when it ends. The event is timed from the span's start so a trace sorts before its children. A DO has no waitUntil: eviction mid-flight can drop a span end (same risk as with LangSmith).
  • The tracer is on when POSTHOG_TOKEN and POSTHOG_HOST are set (already from #948/#953); LANGSMITH_API_KEY no longer gates anything. Properties: workspace_id, agent_id, prompt_id, session id, plus env and release. distinct_id is workspace:<id> with no person profile. Merged follow-up #970 adds app_id, tenant_id, user_id and the tenant group.
  • Text is sent in full, capped at 16,000 characters per payload, on every environment, as with LangSmith. Explicit decision (not an oversight); the DPA question parked for prod replay applies here too.
  • The dormant keyless /langsmith/* proxy branch and its 404 pin are deleted.

ADR on main: docs/decisions/posthog-llm-tracing.md (replaces langsmith-live-tracing.md). See also Conductor.

Trace ids: app, tenant and user (#970, merged) ​

#970 (merged 2026-10-15 15:47 IDT by yoni-monday, merge 88633182, head 8fdfba3d, branch posthog-llm-metadata; opened 15:42 IDT, merged as opened in one commit) is a follow-up to #959. With #959, LLM events carried only workspace_id and agent_id, so a trace could not be tied to a customer, an app or a person.

What landed:

  • Every $ai_trace, $ai_generation and $ai_span event gets app_id and tenant_id (from the workspace's app scope) and user_id (the person whose prompt started the run). Events also join PostHog's tenant group, the same group the studio and product events use.
  • distinct_id stays workspace:<id> with no person profile; this only adds properties.
  • How the user is found. The run's identity (invocation.identity()) lives in an AsyncLocalStorage that only exists inside invocation.run(...). The Pi event stream that feeds the tracer runs outside it, so reading it there returns nothing. Instead, at run start the Pi tracer asks the runtime for the run's user (invocation.resolve(session, firstInput), a storage read), stamps it on the root span, and child spans read it from the root when they end. A tracer that rejoins a run from a snapshot after a DO eviction resolves it the same way.
  • No user_id when no person sent the prompt: an automatic launch prompt run by a service actor, or a failed lookup.

Pending check (from the PR, now merged): on staging, send a prompt and check user_id, tenant_id and app_id on the generation in LLM analytics (project 666164). Prompts the studio launches automatically (msg_launch_...) may show no user, depending on the actor; that is the thing to look at.

Cache cost and turn source on generations (#1001, merged) ​

#1001 (merged 2026-10-17 09:13 IDT by yoni-monday, merge 74ecb3d0, head 7ca1fbb7, branch cursor/ai-generation-cache-costs-035a) adds two things to $ai_generation events. Existing generation fields are unchanged, and traces and tool spans are unchanged.

Cache cost. $ai_cache_read_cost_usd and $ai_cache_write_cost_usd are priced from the model catalogue (MODEL_PRICING / ratesForPrompt in @brilliant/models), the same way a step's activity cost is split:

  • Prompt size is input plus cache-read plus cache-write tokens. A prompt over the model's long-context threshold is billed whole at the long-context rates.
  • Cost is tokens times that tier's per-million rate, divided by 1,000,000.
  • A model id the catalogue doesn't price omits both properties, so placeholder rates never look like a real price. A card priced at zero (Kimi K2.7 Code today) still sends zeros.
  • $ai_model is the catalogue id Pi stores on the assistant message (model.id from piModelFor) for every provider, for example gemini-3.8-flash, openai/gpt-6-astra, meta/muse-spark-1.3, @cf/moonshotai/kimi-k2.7-code. $ai_provider is brilliant.

Which cost is real. PostHog's $ai_total_cost_usd already includes cache reads and writes. The two cache properties are the catalogue's split of that spend, the same numbers the activity page and the ledger use, not inputs to PostHog's sum. Don't add them to $ai_total_cost_usd, that counts cache twice. When the two disagree, the catalogue is what we bill: $ai_total_cost_usd is PostHog's own price match against provider brilliant, so it's often a different price or missing. $ai_cache_reporting_exclusive stays set because Pi reports cache tokens apart from input.

Turn source. turn_source is set on $ai_generation only. It's the same value /ingest/turn sends and turn_settled stores: the run's caller source when the prompt pinned one (coding_agent and the other caller sources), otherwise the x-brilliant-source header that started the turn (mcp).

  • The tracer waits up to about a second (TURN_SOURCE_WAIT_MS) for that storage read. If it's still pending, the generation goes out without turn_source, and later generations in the run aren't held for another second. A read that finishes late still labels the next generation.
  • A failed read falls back to the header, so an MCP turn whose caller can't be loaded shows mcp. A turn with neither leaves the property off.

Catalogue cards behind the provider's list (tracked in #1002; they should change with billing, not only on this event): Kimi K2.7 Code is priced at $0 for every token class; Claude Sonnet 5 is still the retired card ($3 / $15, cache read $0.30, 5-minute write $3.75); Anthropic 1-hour cache writes are charged at the 5-minute rate because the conductor doesn't record the TTL; Muse Spark 1.3's cache write is the unpublished input rate ($1.25/M); Gemini 3.8 Flash's hourly context-cache storage fee isn't in the usage. See also Billing & credits.

The ADR docs/decisions/posthog-llm-tracing.md now has a "Which cost is real" section stating the same rules.

Evals ​

  • The runner no longer reads anything back. runner/turn-trace.ts builds the trace artifact from the turn transcript (model calls, tool calls with args, results and errors). Entries carry no per-call timing, so the trace has none.
  • Migration 0012_drop_langsmith_run_id.sql drops the column; the dashboard loses only the LangSmith link.

See Agents service & evals.

Removed ​

  • LANGSMITH_API_KEY, LANGSMITH_PROJECT, LANGSMITH_PROJECT_ID, LANGSMITH_ENDPOINT from the secrets catalog, deployed vars, side-env config, cloud-prep, wrangler and dev-vars, and the langsmith dependency.
  • The "Trace" link in app settings (it pointed at LangSmith) and its VITE_INTERNAL_TOOLS gate.
  • docs/decisions/langsmith-live-tracing.md, replaced by posthog-llm-tracing.md.

Needs no new secret. See Secrets & environments.

Pending ops ​

PR is merged; these checklist items stay open until staging confirmation:

  1. On staging: send a prompt and confirm in project 666164 (LLM analytics) one trace with a generation and tool spans, with the prompt text.
  2. Confirm an evals run produces a trace artifact.
  3. Later: delete the LangSmith projects and the LANGSMITH_API_KEY secret.

Step 4: replace the BI pipeline with PostHog events (#971, merged) ​

#971 (merged 2026-10-15 16:41 IDT by yoni-monday, merge commit cb7500e1, head 9e7a64ca; opened 15:56 IDT, branch posthog-4-bi) is the fourth PR in the PostHog stack, after #948, #953 and #959. Product events (the BI catalog, POST /api/bi, track()) now go to PostHog, and the whole BI stack is removed from the code (about 9,000 lines deleted). The live Cloudflare BI resources go away only when infra runs on each stack; see Rollout.

What stays the same. The 25-event catalog and its names, BI_EVENTS, the BiEvent row type, the browser client (batching, session id, kill switch), and POST /api/bi with its rules (visitor, browser and platform classification, batch limits, the visitor rate limit, the data size cap). Only what sits behind them changed. (Step 5, #977, merged 2026-10-15 21:25 IDT and removed POST /api/bi and this browser client, so the /api/bi, session id and signup-merge parts of this section are now history.) The repo doc is now docs/product-events.md. See BI events.

Transport ​

  • Workers. track(env, ctx, source, evt) sends the rows to PostHog's /batch/ endpoint in one request inside ctx.waitUntil, so a 50-event browser batch is one subrequest. It does nothing without POSTHOG_TOKEN / POSTHOG_HOST, and a failure or a non-2xx response only logs a warning.
  • distinct_id is the user_id, else sid:<session_id>, else tenant:<id>, app:<id>, or anonymous. The sid: prefix keeps a sender-chosen session id apart from real user ids. session_id is also sent as an event property. Rows with neither a user nor a session do not create a person. A row with a tenant joins the tenant group (the same group the studio and LLM traces use).
  • /api/bi forwards accepted rows through the same function.
  • Browser data can't set PostHog control keys or row columns. $-prefixed properties ($set, $groups, $process_person_profile, $ip), token, api_key, distinct_id and every column name (tenant_id, user_id, app_id, turn_id, session_id, placement, kind, ...) are stripped, so a visitor can't forge a tenant_id property. $current_url is the one $ key kept, cut to origin and path. Tested.
  • Impersonation. A browser batch from a staff "act as" session is accepted (202) but not forwarded. Server-side emitters (app_deployed, turn_settled, the MCP tools) still carry the customer's user_id when an action runs under an act session; those are not filtered. The studio already skips identify for staff (see Identity).
  • Signup merge. signed_up still carries the site's visitor session id and the sanitised attribution. When the login carried a sid, the control plane also sends $identify with $anon_distinct_id set to sid:<sid>, so the visitor's anonymous landing events merge into the new user. The attribution goes in $set_once, and the user joins the tenant group.

Catalog change ​

page_viewed is removed. Studio route views are posthog-js's own $pageview. The marketing site's one page view (contact) is now BI_EVENTS.pageview ($pageview, with $current_url set to origin plus path).

Removed ​

  • Pulumi: the brilliant-bi stream, data catalog, sink and pipeline; infra/bi/**; the BI pipelines binding. Pulumi no longer needs the Pipelines and Account API Token permissions, so BOOTSTRAP.md drops them. The brilliant-bi bucket is kept with retainOnDelete, because Cloudflare won't delete a bucket that still has objects. See Hosting & Pulumi.
  • Secrets: R2_SQL_TOKEN, R2_CATALOG_TOKEN, and the admin var R2_BI_BUCKET. See Secrets & environments.
  • Admin: the BI, dashboards, SQL console and dashboard-chat pages and routes; packages/dashboards; the BI e2e checks. The Flags page and Flagship were removed later by #982 (merged). See Admin client state.
  • Admin D1 database. It only held dashboards, saved queries and chats, so its Pulumi resource, the d1 ids, the migration steps in env:up, deploy and CI, and its side-env teardown are gone. Evals is now the only worker with a D1 database; the generic D1 mechanism stays for it.
  • Docs: repo docs/bi.md is replaced by docs/product-events.md.

The Iceberg history is destroyed with the resources. The PR accepts this. The admin starter dashboard's first_prompt_to_publish panel never worked anyway, because app_published has no emitter.

Rollout (from the PR review) ​

  1. Deploy the new code first. Until it is deployed, the live control plane still binds the BI stream and the live admin still binds the D1 database.
  2. Run infra on staging, then prod. The removals trip ci/removals.ts; read the preview, then re-run with allow-deletes. The stream, sink, pipeline, catalog and admin D1 are destroyed; the brilliant-bi bucket is retained.
  3. Only then trim the Pipelines and Account API Tokens permissions from the Pulumi token, and delete R2_SQL_TOKEN and R2_CATALOG_TOKEN from their stores and the GitHub Environments.
  4. Empty and delete the brilliant-bi bucket by hand, then remove its declaration from cloudflare.ts in a follow-up.

Staging checks (project 666164): prompt_submitted from a visitor and from a signed-in user, a signed_up with its $identify, and an anonymous landing event (sent before sign-up) showing up on the new user's person.

Verified per the PR: typechecks clean across the touched packages and entry scripts; tests green (control plane 2,060, capabilities 341, admin 253, site 235, among others); the infra/pulumi typecheck and tests, the full studio suite and the full conductor suite ran in CI.

Step 5: browser events go straight to PostHog (#977, merged) ​

#977 "PostHog 5: browser events go straight to PostHog, /api/bi removed" (merged 2026-10-15 21:25 IDT by yoni-monday, merge commit 13576e01, head f1612ea1; opened 18:44 IDT, branch posthog-5-browser-events) is the fifth PR in the PostHog stack, after steps 1–4 (#948, #953, #959, #971 and their follow-ups).

The change in one paragraph. Browser product events, from both the studio and the marketing site, go straight to PostHog with posthog-js. POST /api/bi is removed, together with its per-IP rate limit and the site worker's proxy for it. Events the server emits are unchanged.

Identity handoff ​

  • The site hands its PostHog id to the studio as did, in the /start#… fragment. did replaces the BI sid.
  • Every way off the site goes through /start, including the header's Log in and Sign up. The hand-off payload gained a screen field for that.
  • The studio starts from that id only while the visitor is still anonymous, never over an identified user. It accepts only a UUIDv7 (a user id is a v4), so a crafted link can't write events into a real person.
  • After sign-in, the browser calls identify(user.id), which merges the visitor's anonymous events into the user. The server-side $identify-by-sid merge from #971 is gone.
  • The site uses person_profiles: "always". With identified_only, anonymous events would never merge.
  • There is no shared site and studio cookie. The /start fragment is the only link between the two.

Marketing site scope ​

  • Events and pageviews only. No session recording, autocapture, heatmaps, surveys, exception capture or flags request.
  • Attribution keys only on the URL. $current_url keeps only utm_*, gclid, li_fat_id and c. Every other query key, the fragment, and the query on referrers are dropped.
  • The id lives in the tab's sessionStorage (persistence: "sessionStorage"). There is no cookie and no localStorage entry, the same as the old BI session id. A browser test asserts no cookie and no ph_ localStorage key.
  • Token. It reaches the site build the same way as the studio's: the base config holds staging's, and deployedVars sets it per environment. A build with no token starts nothing.

See Marketing site.

Studio ​

  • track() (@brilliant/composer/bi) calls posthog.capture with the same flattened properties as before; $-prefixed keys and reserved data keys are dropped.
  • reset() clears registered super properties, so env and release are now added in before_send. Before this, events sent after sign-out lost env.
  • tenant_id is registered as a super property after identify, so events stay queryable by tenant.
  • Staff impersonation. Capture is opted out while impersonatedBy is set. Before, /api/bi dropped those batches (see Step 4).
  • syncPostHogIdentity and adoptVisitorId carry @cc contracts.

Catalog ​

  • Without /api/bi, the split between visitor and browser no longer means anything, so BI_EVENT_POSTED_BY is browser | platform.
  • VISITOR_BI_EVENTS and the session_id column are gone.

See BI events.

Tradeoffs the PR accepts ​

  • Browser events are forgeable. The old route validated names and pinned tenant and user. The project token is public, so anyone can now send any event to the project. Do not build anything that trusts a browser event. The server's source: "brilliant-app" is forgeable too.
  • Consent. The site sets no cookie and no localStorage entry (decided with the lead), so this change needs no banner. The cost is that a new tab is a new visitor. A persistent id is the point where consent has to be decided; that is recorded in the repo's docs/plans/marketing-site.md (decision 6a).
  • Impersonation gap. The opt-out starts only once /me answers, so posthog-js's load-time $pageview or $set can go out first, under the staff member's own anonymous id (never the customer's). Documented in docs/product-events.md.
  • Off switch. localStorage["brilliant.bi.off"] is gone; PostHog's own opt-out replaces it.

Deploy and what is still unverified ​

Merge, then deploy the control plane and the site. There is no infra change: the BI_VISITOR_RATELIMIT binding is only removed from the wrangler config. See Hosting & Pulumi.

Not run before merge: a live landing-to-signup run on a side env or staging, and bun scripts/e2e-smoke.ts. The tests answer the PostHog host themselves, so they can't prove the merge on the PostHog side. Do both on a deployed env (after #975 and this PR), and check on staging (project 666164) that a visitor's landing events end up on the new user's person.

Verified per the PR: real-browser tests with a mocked PostHog host for the site (pageviews with env and only attribution keys, named events, did equal to the captured distinct_id, no-token build silent) and the studio (env survives reset(), the fragment did becomes the first distinct_id and never overrides an identified user, impersonation sends nothing); typecheck clean in every workspace; site, composer, capabilities and control plane suites green; a real site build with a test token. The design suite caught start-fragment.ts reading window.sessionStorage at import, which throws where storage is blocked; it now reads storage only when a hand-off writes.

Step 6: feature flags from PostHog (#982, merged) ​

#982 "PostHog 6/6: feature flags from PostHog, Flagship and the admin Flags page removed, MCP always on" (merged 2026-10-16 05:47 IDT by yoni-monday, merge commit 94410daa, head cfa4986b; opened 2026-10-15 22:26 IDT, branch posthog-6-feature-flags) is the last PR in the PostHog stack, after steps 1–5 (#948, #953, #959, #971, #977 and their follow-ups).

What landed. Feature flags come from PostHog. Cloudflare Flagship, the admin Flags page, and mcp_server are removed. MCP is always on (optional MCP_DISABLED=true kill switch). The PostHog stack is complete (6/6).

Evaluation ​

Lives in apps/control-plane/src/flags.ts (not packages/capabilities). The control-plane worker is the only reader. The catalog stays in packages/capabilities and must stay Effect-free; the flag service itself is Effect (Flags, flagsLayer / makeFlags, FlagsUnreadable in control-plane flags.ts).

  • Calls PostHog's public POST {POSTHOG_HOST}/flags/?v=2 with the existing POSTHOG_TOKEN (no new secret).
  • Request: distinct_id = user id, or tenant:<id> for billing and /internal/*; groups.tenant; env as a person and group property.
  • getFlag / getAllFlags: 10s in-isolate cache; /me makes one request for all flags; ~800ms timeout.
  • Every failure → catalog default (false for all flags).
  • getFlagStrict keeps the billing contract @cc keep-apps-flag-unreadable-never-unpublishes: 3s, no cache, failure → ok: false (grace end waits, does not unpublish). A flag missing from PostHog → off (notFound).

Review follow-ups (landed in the PR):

  • Strict read fails on a degraded errorsWhileComputingFlags response unless the flag itself says true, and on flags_quota_limited (a quota-limited project postpones grace ends).
  • A flag disabled in PostHog drops out of the answer and reads like deleted (see gotchas/data.md).

Remaining flags (4) ​

Already in both PostHog projects (staging 666164, prod 664776), group-aggregated on tenant, at 0%:

FlagGates
studio_header_navigationStudio header chrome
agentsAgents settings / dock / API
workflowsWorkflows settings / API / conductor builder
billing_keep_apps_publishedBilling lifecycle: keep apps published at grace end

mcp_server and studio_admin_banner_test left the catalog. To turn a flag on for a tenant: release condition on group tenant, property $group_key = tenant id, plus env (prod / staging) so staging is told apart from side envs (side envs share the staging project). See gotchas/data.md "Platform feature flags". Also Admin Feature Flags.

mcp_server always on ​

All mcp_server gates are removed (authorize page, tool-call check, studio nav/page gates, off-state tests/copy). The consent page offers every tenant the user belongs to that is not suspended; with none: "You have no active organization to connect." Optional secret MCP_DISABLED=true is the incident kill switch: refuses /oauth/authorize and every tool call. See MCP.

Admin and infra removals ​

  • Admin: Flags page, Flagship REST client, routes, changelog, tests, env vars and nav entry deleted. admin.flag.* leaves the audit allowlist in admin-audit.ts.
  • Infra: FLAGS binding, Pulumi FlagshipApp, FLAGSHIP_TOKEN in the secrets catalog/verify, admin vars CF_ACCOUNT_ID / FLAGSHIP_APP_ID, and env-renderer flagship branches removed. See Hosting and Secrets.

Rollout order (still pending ops) ​

  1. Deploy the control plane (staging, then prod).
  2. Then apply infra with allow-deletes — destroys Flagship apps in staging and prod. Not before (an old worker would still read the binding).
  3. Delete FLAGSHIP_TOKEN from each Secrets Store, and the Flagship permission from the infra token (BOOTSTRAP.md).

Not covered / open questions ​

  • Real deploy verification (control plane + infra destroy).
  • Experiments need studio posthog-js or server $feature_flag_called (decide when the first experiment is planned).
  • /me features.workflows still comes from the WORKFLOWS_STUDIO_ENABLED env var, not a flag.
  • Also fixed in this PR: docs/product-events.md said env is production, but prod events carry prod.

Stripe customers carry the PostHog distinct id (#989, merged) ​

PR #989 (merged 2026-10-17 08:27 IDT) puts metadata posthog_person_distinct_id on every new Stripe customer and every Checkout subscription. Its value is our user id, the same distinct id the studio identifies people by, so PostHog's Stripe source can tie revenue to persons once prod's live Stripe account is connected (#1009). Existing customers created before the merge don't have it.

Stripe source webhook (#1000, merged) ​

PR #1000 (merged 2026-10-17 09:28 IDT by yoni-monday) lets Pulumi create a Stripe webhook endpoint for PostHog's Stripe source, which feeds PostHog's data warehouse and revenue analytics. The endpoint exists only on stacks that set brilliant-infra:stripe.posthogWebhookUrl. At merge, staging (project 666164) set it and prod didn't; since #1009 (merged 2026-10-18) no stack sets it, and only prod will once its live Stripe account exists.

  • PostHog gets only the 36 events its revenue tables read (customers, charges, invoices, subscriptions, products, prices), never *. A table enabled in PostHog later needs its events added to POSTHOG_WEBHOOK_EVENTS in infra/pulumi/src/stripe.ts.
  • The signing secret is a stack output a person pastes into the PostHog source once (pulumi stack output posthogStripeWebhookSecret --show-secrets). Until then PostHog rejects deliveries as unsigned and no Stripe data lands. The staging paste is no longer needed after #1009.
  • Before connecting prod's source, confirm that PostHog's data-processing terms cover what these payloads carry: customer email, name and billing address, card summaries on charges, and invoice hosted-page and PDF links.

Setup and rollout: Hosting & Pulumi.

Superseded for staging: #1009 (merged) removed the staging endpoint again, so only prod's live Stripe account feeds PostHog.

Revenue analytics: prod only (#1009, merged) ​

PR #1009 (opened 2026-10-17 14:59 IDT, merged 2026-10-18 17:21 IDT by yoni-monday, branch posthog-prod-only, merge e4ac469f, head fb6180c8, 1 commit, 4 files) decides that PostHog's revenue analytics sees prod's Stripe account only. Staging's Stripe sandbox is shared by every side env, so its test purchases would only add noise.

Stripe sandbox (staging + side envs) ──✗── PostHog   (endpoint removed)
Stripe live (prod, once it exists)  ──▶── PostHog   (billing-contracts §8a step 8)
  • Pulumi.staging.yaml drops brilliant-infra:stripe.posthogWebhookUrl, so the staging apply after this merge deletes the …-stripe-posthog-webhook endpoint that #1000 created. That apply stops at the plan gate; re-dispatch infra.yml for staging with allow-deletes only after checking the plan shows just that one delete.
  • A test in infra/pulumi/test/stripe.test.ts pins the decision: staging must set no URL, and prod's URL, once set, must be one the program accepts, so a bad URL fails the PR rather than the prod apply.
  • Still to do by hand, outside the repo: delete the Stripe source in PostHog's staging project (666164) and revoke PostHog's OAuth access in the Stripe sandbox's connected apps.
  • Connecting prod (new step 8 in docs/plans/billing-contracts.md §8a, done by someone with PostHog and Stripe admin):
    1. First, whoever owns PostHog's data-processing terms confirms what these events carry (customer contact details, card summaries, invoice links).
    2. In PostHog prod (664776), add a Stripe source by OAuth against the live account, with only Customer, Charge, Invoice, Subscription, Product and Price enabled, each on Webhook sync.
    3. Put the URL from the source's Webhook tab in Pulumi.prod.yaml as brilliant-infra:stripe.posthogWebhookUrl (a reviewable PR; the prod infra run creates the endpoint).
    4. Run bun ../../scripts/pulumi.ts stack output posthogStripeWebhookSecret -s prod --show-secrets in infra/pulumi, paste it as the source's signing secret, then turn on Revenue analytics for Stripe. The posthog_person_distinct_id metadata ties revenue to the right person.
  • Nothing changed in prod with this PR; prod has no live Stripe account connected yet. PR tests: infra/pulumi 166 pass, tsc and Biome clean.

Semantic lint events (#1008, merged) ​

PR #1008 (merged 2026-10-17 14:28 IDT) adds two platform product events from the conductor: semantic_lint_run (one per lint pass) and semantic_lint_finding (one per rule answer, joined by lint_id). They go through the same track() transport as Step 4, only for tenants with the semantic_lint flag on, and carry no source or model text. This is the first product event the conductor sends from inside a coding-agent turn; productEventTracker holds the capture promise because a Durable Object's waitUntil doesn't keep the isolate alive. Properties and HogQL queries: Semantic lint, Analytics in PostHog.

Local dev ​

To turn PostHog on for a local studio build, copy apps/control-plane/web/.env.example to .env.local and fill in a token. Leave the token empty to keep PostHog off.

  • Use .env.local, not .env. Bun skips .env.local under bun test, so tests never send events. A plain .env would turn PostHog on inside tests (.env is now gitignored).
  • src/lib/posthog.ts reads import.meta.env?. with the ?., following the studio convention. The Bun.build test harnesses leave import.meta.env undefined, and without the ?. those harness tests time out.

BI events · Semantic lint · Marketing site · Admin Feature Flags · MCP · Control plane & studio · Secrets & environments · Hosting & Pulumi · Side environments