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.

28.0 KB
Raw Blame

PostHog Development Guide

AGENTS.md is the source of truth for architecture and development rules. CLAUDE.md is a symlink to this file. Edit this file only.

Feature-level guides follow the same convention: the content lives in <dir>/AGENTS.md with a <dir>/CLAUDE.md symlink beside it. When you add a new guide, add the symlink too (ln -s AGENTS.md CLAUDE.md).

Architecture

PostHog uses a layered architecture. Business logic and UI live in shared packages/*. Each apps/* host boots those packages and binds host-specific implementations. @posthog/core and @posthog/ui must run unchanged on desktop and web.

Principle: logic is portable; hosts are thin.

Layer Responsibility
packages/core Host-agnostic business logic: orchestration, retries, dedupe, sagas, parsing, domain events, domain state. Inversify services only. No React, Node, Electron, or trpcClient.
packages/workspace-server Node-only capabilities behind tRPC: git, fs, process spawn, pty, watchers.
packages/ui React UI shell: views, components, hooks, view-state stores, route and command contributions. No business logic, Node, Electron, or trpcClient.
apps/<host> Boot, lifecycle, platform adapters, DI wiring, host transports. No business logic.

Packages

Package Owns Must not contain
@posthog/platform Host-capability interfaces and DI tokens. Host-neutral, zero runtime dependencies. Implementations, Node, DOM, tRPC, Electron
@posthog/agent-contracts Types, schemas and helpers the agent runtime shares with its hosts: task and run domain types, model catalog, Saga pattern, cloud-prompt encoding. Depends on published packages only. Internal package imports, I/O, desktop-only code
@posthog/shared Host-neutral desktop primitives and types. Re-exports @posthog/agent-contracts, so desktop code imports both through @posthog/shared. Internal package imports other than agent-contracts, I/O
@posthog/api-client PostHog/Django HTTPS client. Constructed by factory, not DI. UI, Node-only host syscalls
@posthog/workspace-client Thin tRPC client for local or sandbox workspace-server. Runs in any JS environment. Business logic, UI
@posthog/workspace-server Node backend services and colocated tRPC routers for git, fs, watchers, processes. UI, core, Electron
@posthog/core Portable Inversify services, domain schemas/types, domain stores (zustand/vanilla). Injects platform, workspace-client, api-client. React, trpcClient, Node syscalls, Electron, host-router runtime
@posthog/ui React components, hooks, contributions, view-state stores. Built on @posthog/quill. Business logic, trpcClient, Node
@posthog/host-trpc Shared initTRPC base with container-bearing context for Electron main routers. Feature logic
@posthog/host-router Electron host tRPC routers that resolve services from request context and forward calls. Exposes HostRouter type and renderer useHostTRPC. Service implementations
@posthog/di DI and boot primitives: CONTRIBUTION, boot(), ROOT_LOGGER, setRootContainer(), useService. Feature code
@posthog/electron-trpc tRPC-over-Electron-IPC transport. Feature code
@posthog/git, @posthog/enricher, @posthog/agent Reusable domain implementation packages. Host-specific code

@posthog/agent, @posthog/agent-contracts, @posthog/enricher, @posthog/git and @posthog/harness live in their own workspace at packages/agent in the repo root, because cloud sandboxes boot the agent without the desktop app. This workspace links them by path, so turbo cannot see their files: pnpm build, pnpm typecheck and pnpm test build that workspace first and write .agent-workspace-stamp, which turbo hashes. After changing that workspace, run pnpm build:agent before calling turbo directly, or turbo serves stale cached results.

Hosts:

  • apps/code: Electron desktop host.
  • apps/web: web host and portability smoke test.

Rules

  1. Business logic lives in @posthog/core services. Use @injectable() classes, constructor injection, and host-neutral dependencies.
  2. Stores hold state only. No async flows, retries, dedupe, clients, cross-store orchestration, or business decisions.
  3. Domain state lives in @posthog/core with zustand/vanilla. View state lives in @posthog/ui with zustand.
  4. Node and host syscalls live in @posthog/workspace-server or a host adapter. core reaches workspace-server through an injected workspace-client slice.
  5. Components render. Hooks wrap exactly one query, mutation, subscription, or store selector. Multi-source orchestration belongs in a service method.
  6. Cross-feature coordination uses a service or Contribution emitting typed events. Stores do not reach into other stores.
  7. Runtime boundary shapes use Zod schemas in schemas.ts. Infer TypeScript types from schemas.
  8. Host capabilities use @posthog/platform interfaces plus per-host adapters under apps/<host>.
  9. Use constructor injection only. Do not use container.get(...) or resolveService(...) inside service methods or components. resolveService is allowed only in host composition seams under apps/.
  10. Boot side effects are Contributions bound in feature modules and started by boot().
  11. tRPC routers are one-line forwards over services. No inline business logic.
  12. Use Inversify with @inversifyjs/strongly-typed. Define each token as a standalone export const TOKEN = Symbol.for("posthog.<area>.<thing>") beside its interface/service — never an object-literal token bag (TOKENS = { X: Symbol.for(...) }), because object properties are not unique symbol and cannot key a binding map. Every composition root declares a BindingMap interface (token → bound type) and constructs new TypedContainer<BindingMap>(), so a mistyped bind or a resolve of an unbound token fails at compile time. Bind in the feature module. Do not use @provide or *Port naming.
  13. Use @posthog/quill for rendering-layer primitives. Never import Radix — see UI Components. Routing is TanStack Router contributed per feature.

Hard boundary: @posthog/core and @posthog/ui never import host transports. No trpcClient, electron, or node:*.

Hard boundary: no new @radix-ui/* imports anywhere in the repo.

Import Direction

Enforced by Biome noRestrictedImports.

  • platform and agent-contracts import no internal packages. shared imports agent-contracts only.
  • agent, harness, git, and enricher import agent-contracts, never shared, so the agent runtime does not depend on desktop code.
  • api-client and workspace-client may import shared and relevant platform contracts. No UI or Node host syscalls.
  • workspace-server may import shared, platform contracts, Node modules, and workspace-server code. Never core or ui.
  • core may import shared, platform, workspace-client, api-client, and other core code. Never ui, workspace-server, electron, node:*, trpcClient, or host-router runtime.
  • ui may import core, api-client, workspace-client, platform, shared, @posthog/quill, @posthog/quill-charts, and UI feature public files. Never workspace-server, electron, node:*, or trpcClient.
  • apps/<host> may import any package and its own host adapters.

Core Eligibility

core is portable business logic. If code touches the host, it is not core yet.

Host dependency Correct home
node:fs, node:path, node:child_process, process.* workspace-server, or an injected platform/environment interface
node:crypto for ids, hashes, PKCE, random injected platform crypto/random interface
node:events emitters or async iterators shared event abstraction, or keep source in workspace-server
@posthog/enricher, git/file/AST repo scans workspace-server owns the scan; core owns result decisions
process.platform, process.arch typed host-info interface supplied by host

Split host-tangled algorithms: pure decision in core, host access in workspace-server or a platform adapter.

Placement Decision

For each new file or meaningful change:

  1. Data source:
    • Git, fs, process, pty, watchers: workspace-server procedure, consumed by a core service through workspace-client.
    • PostHog cloud API: core service/function using @posthog/api-client.
    • Client-local host capability: @posthog/platform interface plus per-host adapter.
  2. Logic:
    • Real orchestration, retries, rules, sagas, or decisions: core service.
    • Trivial passthrough or streamed value: store plus host glue.
  3. State:
    • Domain fact read by business logic: core store.
    • Pure view state: UI store.

Forbidden Patterns

  • Any new @radix-ui/* import (@radix-ui/themes, @radix-ui/react-*). Use @posthog/quill plus div + Tailwind.
  • Radix layout primitives (Box, Flex, Grid, Section, Container) in code you touch; replace them with divs.
  • Business logic in store actions.
  • Domain stores in @posthog/ui.
  • trpcClient imports in @posthog/core or @posthog/ui.
  • Service-locator calls inside services or components.
  • Hooks that orchestrate multiple queries.
  • Platform interfaces for backend data.
  • Services for trivial passthroughs.
  • Business logic in platform adapters.
  • tRPC routers with inline logic or no backing service.
  • Object-literal DI token bags (TOKENS = { X: Symbol.for(...) }); use standalone token consts so a BindingMap can key on them.
  • Untyped new Container() at a composition root; use new TypedContainer<BindingMap>().
  • Bespoke clients that wrap trpcClient.x one-to-one.
  • *Port, *_PORT, or ports.ts naming.
  • Business logic in apps/<host>.
  • New ad-hoc broad in-app announcement or promo surfaces (flag-gated promo cards, dismissible banners, one-time modals). Broad announcements are remotely controlled via the posthog-desktop-announcements flag payload — see docs/ANNOUNCEMENTS.md.

Host Boundary

apps/code contains Electron boot, lifecycle, platform adapters, and DI wiring only. scripts/check-host-boundaries.mjs checks host thinness against scripts/host-boundary-allowlist.json.

When moving logic out of apps/code, run:

node scripts/check-host-boundaries.mjs --prune

Do not use --init to baseline new violations.

Web Host

apps/web is a real host and the portability smoke test: if a @posthog/core/@posthog/ui change compiles and boots on desktop but not here, it leaked a host dependency. It is cloud-only — no local filesystem, git, pty, or worktrees — so it binds HOST_CAPABILITIES to { localWorkspaces: false } and stubs local-only host clients to reject at call time.

Building a feature for web means: the portable core/UI already runs unchanged; you only supply web adapters and bind them.

  • Composition root is apps/web/src/web-container.ts (WebBindings + TypedContainer<WebBindings>). It loads the same core/UI feature modules apps/code's renderer does, then binds web adapters (the web-*.ts files) for each platform/host capability. Unlike desktop, module-loading and adapter-binding live in this one file, not split into desktop-contributions.ts / desktop-services.ts.
  • Transport is the entire desktop↔web difference. web-trpc.ts builds HOST_TRPC_CLIENT from an in-process unstable_localLink over web-host-router.ts (a subset of HostRouter, same procedure shapes) instead of Electron's ipcLink — no HTTP hop; the backing services are host-agnostic core code resolved from the root container per call. Both hosts use the superjson transformer; keep them in sync (the host-trpc base sets transformer: superjson).
  • New host capability? Add a @posthog/platform interface (host-neutral) and a web adapter under apps/web/src, then bind it in web-container.ts. If the shared app resolves it eagerly at __root via useService, an unbound token crashes the tree — assertHostCapabilities(container, REQUIRED_HOST_CAPABILITIES) at the end of web-container.ts catches that at boot instead of on first navigation.
  • Persistence. localStorage is the web host's single persistence layer; route all access through web-local-store.ts — createRecordStore(key, entrySchema) for the per-device Record<string, Entry> registries, readValidated(key, schema, fallback) for a single persisted object, the raw readJson/writeJson/removeKey primitives for anything without a schema, and rawLocalStorage for the zustand backend. Do not call window.localStorage directly. Persisted stores are discardable per-device caches validated against a Zod schema on read (invalid data is dropped and rebuilt), so evolving a shape is a schema edit, not a hand-written migration. IndexedDB is reserved for exactly one thing — the non-extractable auth cipher key in web-auth-adapters.ts — because localStorage cannot hold a CryptoKey without exposing its raw bytes; do not add other IndexedDB usage or move that key to localStorage.
  • Boot is main.tsx: import ./web-storage first (registers the persistence backend before stores construct), then the container, setRootContainer, boot().
  • Commands. pnpm --filter @posthog/web dev (Vite dev server), build, typecheck. E2E: pnpm --filter @posthog/web test:e2e (Playwright, tests/e2e/). There is no Vitest unit suite in apps/web.

Structure

apps/code/src/
|-- main/
|   |-- index.ts                 # composition root
|   |-- bootstrap.ts             # boot sequence
|   |-- window.ts, menu.ts, deep-links.ts, preload.ts
|   |-- di/                      # container and host tokens
|   |-- services/                # host-resident services
|   `-- platform-adapters/       # Electron adapters
`-- renderer/
    |-- main.tsx                 # imports wiring, boots the app
    |-- desktop-services.ts      # renderer host adapter bindings
    |-- desktop-contributions.ts # loads core/ui modules
    |-- platform-adapters/       # renderer adapters wrapping host transport
    |-- features/                # host glue only
    `-- trpc/client.ts           # renderer trpcClient for host glue
packages/core/src/<feature>/
|-- <feature>.ts
|-- <feature>.module.ts
|-- <feature>Store.ts
|-- identifiers.ts
|-- schemas.ts
`-- <feature>.test.ts

packages/host-router/src/routers/<feature>.router.ts

packages/ui/src/features/<feature>/
|-- <Feature>View.tsx
|-- <feature>.contribution.ts
|-- <feature>.module.ts
|-- store.ts
`-- use<Feature>.ts

DI and Boot

  • Tokens are standalone export const TOKEN = Symbol.for("posthog.<area>.<thing>") consts, defined beside the interface in the owning package. Standalone consts infer unique symbol, which is what lets a BindingMap key on them; object-literal token bags do not and are forbidden.
  • Each composition root (apps/code main + renderer, apps/web, packages/workspace-server) owns a BindingMap interface mapping every token it binds to the bound type, and constructs new TypedContainer<BindingMap>() (from @inversifyjs/strongly-typed). bind/get/isBound are then checked against the map at compile time.
  • Services bind in feature .module.ts files with ContainerModule (typed via TypedContainerModule<BindingMap> where the root is typed).
  • Hosts load modules in desktop-contributions.ts or the equivalent web composition file.
  • Hosts bind platform implementations in desktop-services.ts, main/index.ts, or host equivalents.
  • Hosts call setRootContainer(container) before resolving services through React or host seams.
  • CONTRIBUTION starts subscriptions, commands, routes, menus, and feature boot.
  • React uses useService(TOKEN) at boundaries only.
setRootContainer(container);

import "./desktop-services";
import "./desktop-contributions";

await boot(container);

Commands

  • pnpm install: install dependencies.
  • pnpm bootstrap:cloud-task: link dependencies from the prebaked pnpm store without running unrelated app install hooks, then build the packages required before scoped typechecks in cloud tasks.
  • pnpm bootstrap:cloud-task:wait: in a cloud task, the backend already started bootstrap:cloud-task in the background. Run this before any other pnpm command here, so a second install does not race it. Exit code 2 means nothing was started, so run pnpm bootstrap:cloud-task yourself.
  • pnpm dev: run agent watch and desktop app.
  • pnpm build:agent: install if needed and build the agent workspace at packages/agent, then refresh the turbo stamp.
  • pnpm build: build all packages.
  • pnpm typecheck: typecheck all packages, including the agent workspace.
  • pnpm lint: run Biome lint and autofix.
  • pnpm format: run Biome format.
  • pnpm test: run unit tests.
  • pnpm test:e2e: run Playwright tests.
  • pnpm --filter <pkg> typecheck|test|build: run a scoped task.
  • pnpm --filter code package|make: package the Electron app.
  • node scripts/check-host-boundaries.mjs: verify host boundary allowlist.
  • pnpm --filter @posthog/api-client generate-client (or the @posthog/code alias): regenerate the typed PostHog API client from the local OpenAPI schema. See API client.

API client

packages/api-client/src/generated.ts is the typed PostHog API client. It is generated, formatted, and committed; never edit it by hand.

It contains only what packages/api-client/endpoint-allowlist.json names:

  • paths: the endpoints desktop code calls through the typed client (this.api.get("/api/projects/{project_id}/...")). Use the exact path template from the OpenAPI schema.
  • schemas: the component schemas desktop code imports directly as Schemas.<Name>.

Everything those reference is generated with them. The full schema documents thousands of routes, and generating all of them made every backend change churn this file; the allowlist keeps a regen to the routes the desktop uses.

The generator is packages/api-client/scripts/update-openapi-client.ts. hogli build:openapi runs it after the other OpenAPI generators, and Backend CI's "Validate OpenAPI types" job runs hogli build:openapi on backend PRs. A backend change that alters an allowlisted endpoint or schema therefore gets the regenerated generated.ts committed to its PR automatically, together with the frontend and MCP types. If the generator fails in CI (for example, an allowlisted path left the schema), the job fails. Released desktop apps still call that path, so remove it from the allowlist and its call sites in a desktop PR first, then from the backend.

To call a new endpoint or import a new schema type:

  1. Add the path template to paths, or the schema name to schemas.
  2. From the repo root, run hogli build:openapi-schema to write frontend/tmp/openapi.json from the checkout.
  3. Run pnpm --filter @posthog/api-client generate-client. It fails if an allowlisted path or schema is not in the schema, naming it, and formats the output with prettier so the diff shows only what changed.
  4. Run pnpm typecheck. A call site whose path is not allowlisted fails with not assignable to keyof GetEndpoints (or the matching method); add the path and regenerate.
  5. Commit generated.ts together with the allowlist change.

Keep desktop and backend changes in separate PRs: the desktop ships on its own auto-update schedule, so a client that calls an endpoint before it is deployed reaches users. A regen from a branch that adds a backend endpoint only carries types for it, which is safe; the call site lands after the endpoint is live. For this reason the desktop/backend coupling check ignores generated.ts, but not the allowlist or any call site.

Raw fetch calls through this.api.fetcher.fetch with a hand-built path do not need an allowlist entry, and endpoints that leave the schema surface as a generator error on the next regen: remove them from the allowlist, and typecheck shows any call site that still used them.

UI Components

Radix is banned. Do not add a @radix-ui/* import to any file, ever. That covers @radix-ui/themes and every @radix-ui/react-* package. There is no "just this once" exception for matching surrounding code: the ~500 files that still import Radix are legacy awaiting migration, not a pattern to copy. If a file you are editing already imports Radix, that is a reason to remove those imports, not to add more.

Rendering primitives come from @posthog/quill. Layout comes from plain HTML elements plus Tailwind.

Replace Radix as you go

When you touch a component that imports Radix, migrate the parts you are working in. Swap the whole file when the file is small or the change is broad; otherwise migrate at least the elements your diff touches, and leave the file no more Radix-dependent than you found it. Don't open a drive-by migration of an untouched file in an unrelated PR.

Layout primitives become divs (or the right semantic element) with Tailwind classes:

Radix Themes Replace with
<Box p="2"> <div className="p-2">
<Flex align="center" gap="2"> <div className="flex items-center gap-2">
<Flex direction="column"> <div className="flex flex-col">
<Grid columns="2" gap="3"> <div className="grid grid-cols-2 gap-3">
<Section>, <Container> <div> / <section> + Tailwind
<ScrollArea> <div className="overflow-y-auto">
<Heading> quill Heading, or <h1>–<h6> + Tailwind
<Code>, <Blockquote> <code>, <blockquote> + Tailwind
<VisuallyHidden> className="sr-only"
<Link> TanStack Router Link (in quill, render={<Link … />})

Everything else has a quill equivalent — import it from @posthog/quill:

Radix Themes quill
Text Text
Button, IconButton Button (variant/size props)
TextField, TextArea Input, Textarea, InputGroup*
Select, Checkbox, Switch, Slider, Progress same names
SegmentedControl, RadioGroup ToggleGroup + ToggleGroupItem, or Tabs
Badge, Avatar, Separator, Skeleton, Kbd, Card, Table*, Tabs* same names
Spinner Spinner or LoadingState from packages/ui/src/primitives, never quill's Spinner (see Code Style)
Tooltip, Popover, Dialog, AlertDialog, DropdownMenu, ContextMenu same names, as *Trigger / *Content compounds
Callout compose a div with Tailwind, or quill Item*

No quill equivalent and no plain-HTML answer? Build it from HTML + Tailwind in the feature, or add it to quill (see .claude/skills/quill-code/SKILL.md). Pulling in a Radix package is not the fallback.

Design tokens

  • Use the semantic design tokens from @posthog/quill-tokens by default.
  • Do not add raw color utilities such as text-(--gray-11) or bg-(--gray-2).
  • Use text-foreground for important or high-contrast text.
  • Use text-muted-foreground for less important or low-contrast text.
  • Use text-xs for body text.
  • Deviate from these design-system rules only when the task explicitly requires it.

Theme carve-out

The <Theme> root stays for now. The app-level provider (Providers.tsx), .storybook/preview.tsx, and the <Theme> wrapper in existing tests supply legacy tokens. Leave these wrappers unchanged. Do not add <Theme> to new files. New tests must not need it.

Code Style

  • Prefer local code over new dependencies for simple fixes.
  • Keep functions focused.
  • Use Biome, not ESLint or Prettier. Use 2-space indentation and double quotes.
  • No console.* in source. Inject ROOT_LOGGER as RootLogger and call .scope(name). Logger files are exempt.
  • TypeScript strict mode. Use explicit types where they clarify public contracts or nontrivial values.
  • Use path aliases and package public exports. Avoid deep relative imports.
  • No barrel files (index.ts).
  • Use Tailwind first. Keep classes sorted. Use inline style only for runtime values, library configuration, or CSS variables.
  • Empty/placeholder/loading screens (canvas and elsewhere) are a @posthog/quill <Empty> (EmptyHeader → EmptyMedia variant="icon" → EmptyTitle → EmptyDescription, then EmptyContent for CTAs). Don't hand-roll the centered Flex + dashed icon box. CTAs are quill Buttons: primary action variant="primary", secondary variant="outline", size="default". For a link CTA use render={<Link … />} (Base UI), not asChild.
  • The bar across the top of a pane, a column or a side panel is ChromeBar (packages/ui/src/primitives), never a hand-written row. It fixes the height at 40px, the border and the colour; the caller supplies the breadcrumb, title or search header inside it and the controls through actions. inset says how far from the edges the contents sit: control when the bar starts with a button, text when it starts with a label, even for a bar with the same padding both ends, title for a pane's own title bar. A title bar holds its contents on PANE_INSET, the same inset as the body under it, so the title starts on the line of the page it names; title content that starts with a size="sm" button adds LEADING_BUTTON_PULL to cancel that button's own padding. A title that pads itself instead drifts from every other pane. Fifteen copies of this row had drifted into three border colours and four paddings before it existed.
  • Loading indicators are Spinner and LoadingState from packages/ui/src/primitives. LoadingState fills a pane or section while its data loads (24px spinner, optional label). Spinner sits inline in a button, row or badge; omit size inside quill buttons and media slots so it matches the icons beside it, and pick xs/sm/md/lg elsewhere. Do not import Spinner from @posthog/quill or @radix-ui/themes, and do not spin phosphor's CircleNotch or SpinnerGap: Biome rejects those imports. Pass aria-hidden="true" when the spinner sits next to visible loading text or inside an element that already announces the loading state, so the label is not read twice. The braille DotsCircleSpinner and DotRingSpinner mark agent activity (a running tool call, a working task), not data loading.
  • Abort controllers before awaiting cleanup that depends on them.

See docs/CONVENTIONS.md.

Agent Integration

  • Use SDK types from @anthropic-ai/claude-agent-sdk and @agentclientprotocol/sdk.
  • Do not use Claude Code SDK rawInput. Use Zod-validated metadata.
  • User approvals are tool calls with permissions. Do not model approvals as custom methods plus notifications.

Key Libraries

  • React 19, Tailwind CSS, @posthog/quill (components), and @posthog/quill-tokens (design tokens). Radix is banned in new code. See UI Components. Existing Radix imports await migration.
  • TanStack Query, TanStack Router
  • Zustand, InversifyJS (with @inversifyjs/strongly-typed), Zod
  • xterm.js, CodeMirror, Tiptap

Testing

  • Unit tests: Vitest.
  • E2E tests: Playwright.
  • Test core/UI services and stores with faked injected dependencies and explicit props.
  • Prefer a parameterised test shape (it.each/test.each) when several cases exercise the same logic with different inputs and expectations. Keep separate tests when cases differ in setup, assertions, or intent.
  • Colocate tests as .test.ts or .test.tsx.
  • Put E2E tests in tests/e2e/.
  • Drive and screenshot the real running app (live data) with agent-browser over CDP :9222: run pnpm app:cdp or use the test-electron-app skill.
  • Treat virtualized-list overscan as a performance setting, not a scroll-correctness fix; preserve the visible anchor when measured row heights change.
  • After touching @posthog/platform, rebuild or typecheck its dist/.
  • After touching packages/core, run biome lint packages/core and verify zero noRestrictedImports.

See docs/TESTING.md.

Reference