## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server sends first-party telemetry events through a collector. The collector anonymizes the events and copies them into PostHog. > - Paperclip Cloud is our own service. It needs real IDs (workspace, user, agent, task) so that a person can go from a PostHog event to the exact workspace and task. > - The collector path hashes these IDs. It also cannot link a server event to the browser session that caused it. > - This pull request adds a server-owned direct sender for Cloud only. Self-hosted installs keep the collector path with no change. > - The benefit is real IDs and session links on Cloud, and no change to self-hosted privacy. ## Linked Issues or Issue Description **Subsystem affected** Server telemetry (`packages/shared/src/telemetry`, `server/src/telemetry.ts`). **Problem or motivation** All Cloud telemetry goes through the collector. The collector hashes the install ID, agent IDs and task IDs. So, on Cloud, you cannot find the workspace, user or task of an event. Server events also cannot show in a browser session replay. **Proposed solution** On a Cloud-managed server that has `PAPERCLIP_POSTHOG_PROJECT_TOKEN`, `PAPERCLIP_CLOUD_STACK_ID` and `PAPERCLIP_POSTHOG_ENVIRONMENT`, send each telemetry batch straight to PostHog with `posthog-node`. Use the same event shape that the telemetry backend loader makes today, and add the real IDs. Keep every other install on the collector. **Alternatives considered** Send real IDs through the collector. We did not do this, because the collector exists to anonymize self-hosted data. **Roadmap alignment** This is Cloud analytics infrastructure. It does not change a core product feature. ## What Changed - Add `server/src/services/cloud-posthog-config.ts`. `resolveCloudPostHogConfig()` returns `null` unless the instance is Cloud-managed and has a token and a stack ID. `isPostHogDirectDeliveryEnabled()` also requires an environment and the kill switch on (`PAPERCLIP_POSTHOG_DIRECT` is not `0`). - Add a narrow `TelemetryTransport` seam to `TelemetryClient` in `packages/shared`. With a transport, each flushed batch goes to the transport and never to the collector. Without one, the client does what it did before. A transport can capture per-event context at track time. The context does not go into the collector envelope. - Typed helpers hash `task_id` unless the transport sets `hashesPrivateRefs: false`. Private `source_ref` values (for example a private repository name) are customer content, so they stay hashed on every path, Cloud included, with `source_ref_hashed: true`. - Add `server/src/services/posthog-direct/`: - `event-shape.ts` builds PostHog messages with the loader's event names, metadata keys and key order, the deterministic event uuid formula, and the unknown-enum fallback. It drops events that the backend quarantines (unregistered names). - `enum-fallbacks.generated.ts` holds the backend fallback rules. Enum values come from the shared generated contract. - `transport.ts` loads `posthog-node` with dynamic `import()` only on the first Cloud send. - `request-context.ts` is Cloud-only Express middleware. It reads only `X-POSTHOG-SESSION-ID` and `X-POSTHOG-WINDOW-ID`. It ignores `X-POSTHOG-DISTINCT-ID`. The acting user comes only from the authenticated request actor. Context stops when the response finishes, so later background work does not use that user. - `server/src/telemetry.ts` selects exactly one sender per process. On start, the Cloud sender sends `$groupidentify` (group `workspace`, key = stack ID) and one `cloud.workspace_started` event with `install_hash` (sha256 of the raw install ID). Both go straight to `posthog-node` and are not in `PAPERCLIP_EVENTS`. - `distinct_id` is the acting user ID, else `workspace:<stackId>`. Events without an acting user keep `$process_person_profile: false`. GeoIP stays off on all server events. - Shutdown flushes the client and then shuts down `posthog-node`. - Add `scripts/generate-posthog-direct-fixtures.mjs`. It runs the telemetry backend's own ingest and loader on one envelope and writes the golden fixture and the fallback table. The script header tells how to regenerate them. - Update `packages/shared/src/telemetry/README.md` with a "Cloud Direct Delivery" section about the privacy boundary. - Add `posthog-node@5.38.2` to `server/package.json`. This PR does not change `pnpm-lock.yaml`, because the lockfile refresh workflow owns it. Intended differences from the loader output on Cloud: `distinct_id` (user or workspace, not the HMAC install ID), raw `agent_id`, raw `task_id` (private `source_ref` stays hashed), and these added properties: `stack_id`, `company_id` and `user_id` when known, `environment`, `$groups`, `$session_id` and `$window_id`. The uuid formula is the same. The uuid is different only when the dimensions are different (raw `task_id`). ## Verification - `pnpm verify` returned exit 2 (a global CI input changed: the new script). I ran focused checks. Required CI supplies the broad coverage. - Focused tests pass: `packages/shared` `src/telemetry` (6 files, 42 tests). Server: `posthog-direct-telemetry`, `posthog-direct-event-shape`, `cloud-posthog-config`, `shared-telemetry-events`, `heartbeat-status-preserving-telemetry`, `issue-thread-interactions-telemetry`, `native-run-finalizer-telemetry`, `agent-task-run-telemetry`, `error-handler` (9 files, 115 tests), and `server-startup-feedback-export` (133 tests). - `tsc --noEmit` passes for `packages/shared`, `server` and `cli`. - New tests: - Config matrix: not Cloud, no token, no stack ID, no environment, kill switch, browser and replay flags. - Self-hosted: `posthog-node` is never loaded, the collector gets the batch, and the envelope bytes are the same as before (with `task_id` hashed). Tracing headers are ignored. - Cloud: a private `source_ref` stays hashed and the raw repository name never reaches the sender. - Cloud: one batch goes only to PostHog. Real IDs, `$groups`, `environment` on every event. `cloud.workspace_started` reaches the PostHog sender with `install_hash`. No other event has `install_hash`. - Golden: our builder output equals the backend loader output, except the intended differences above. Key order is the same. - `distinct_id`: user, agent and anonymous requests. A spoofed `X-POSTHOG-DISTINCT-ID` never changes `distinct_id` or `user_id`. A bad session header is dropped. Work after the response ends does not keep the user (red without the response-end guard, green with it). - Kill switch and a missing environment both fall back to the collector. - Local run with a real server and a local capture server (no real PostHog project): - Cloud mode (authenticated, local Postgres, `PAPERCLIP_POSTHOG_HOST` set to the capture server): the capture server got `$groupidentify`, `cloud.workspace_started`, `server.started` and `goal.created` on `/batch/`. `goal.created` from a Cloud tenant user had `distinct_id` = that user, `user_id`, `company_id`, `$session_id`, `$window_id`, `$groups` and no `$process_person_profile`. The spoofed distinct ID header was not used. Nothing went to `/ingest`. `SIGTERM` ran the `telemetry_flush` step and sent the queued events. - Self-hosted mode (same token variables but no Cloud signal): the capture server got only `/ingest` with the normal envelope. Nothing went to `/batch/`. - Runtime dependency note: `posthog-node` loads with dynamic `import()` only on Cloud with direct delivery on. The load happens after startup, outside the boot path. The unit test mocks the package to count loads. The local run used the real package. ## Risks - Medium. This is a telemetry change, so a privacy review is requested. Self-hosted output does not change. The direct path is off unless all three Cloud variables are set, so a merge does nothing until fleet config sets them. - Cloud events with an acting user create PostHog person profiles keyed by the Paperclip user ID. This is intended under the Cloud terms. - The fallback table can drift if the backend adds a new normalization rule. A test fails when a rule does not match the shared enum contract. Enum values come from the shared contract, so new enum values do not drift. - `posthog-node` keeps network failures in its own queue and drops events that PostHog rejects. The client does not resend these, so events are not sent twice. - `pnpm-lock.yaml` is not in this PR. The lockfile refresh workflow adds `posthog-node` after merge. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, local server runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
15 KiB
Telemetry Data Contract
This document explains how contributors should use Paperclip's public telemetry contract. It does not duplicate the full list of individual events or dimensions. It documents extra semantic and privacy rules where the generated shape is not sufficient.
The canonical source for first-party event names, dimensions, optionality,
allowed primitive value types, and enum descriptions is
packages/shared/src/telemetry/generated/paperclip-telemetry.ts.
Shared enum constants live in packages/shared/src/constants.ts. Use those
constants when code needs a reusable domain, but treat the generated telemetry
types as the final authority for emitted first-party telemetry shapes.
Public Sources
Use these files when reviewing or changing telemetry code:
| Contract item | Public source |
|---|---|
| First-party event names | PaperclipEventName in generated/paperclip-telemetry.ts |
| Per-event dimensions and optionality | EventDimensionsMap in generated/paperclip-telemetry.ts |
| Enum descriptions for telemetry dimensions | PAPERCLIP_ENUM_DESCRIPTIONS in generated/paperclip-telemetry.ts |
| Schema version and event envelope helpers | SCHEMA_VERSION, makeEvent(), and makeBatch() in generated/paperclip-telemetry.ts |
| Runtime-safe event names and dimensions | TelemetryEventName and TelemetryEventDimensions in types.ts |
| Allowed primitive dimension values | TelemetryDimensionValue in types.ts |
| Shared reusable enum domains | Named exports in constants.ts |
| First-party typed emit helpers | events.ts |
| Generic client behavior | client.ts |
| Retention windows and event class assignments | RETENTION_DAYS and EVENT_RETENTION_CLASS in retention.ts |
Do not copy generated event lists or dimension tables into this README. They will drift as the generated contract changes.
Emission Boundary
Paperclip telemetry uses named events with explicit dimension fields. Treat open-ended string dimensions as public contract values, not as a place for user content or private operational data. Do not send PII, secrets, credentials, private paths, prompts, model output, or other sensitive values through telemetry dimensions.
Telemetry emitters send raw dimension values. They must not pre-normalize enum-like values into a reporting form just to match today's known domain.
The receiving layer owns canonicalization. Keeping canonicalization in one place means emitters can stay simple and accurate: emit what the product observed, use the generated contract for required and optional fields, and let the receiving layer decide how legacy spellings, aliases, unknown names, and future values map to a stable reporting shape.
Do not add client-side lowercasing, alias mapping, or fallback mapping unless the generated telemetry contract specifically requires that emitted value.
If a dimension is privacy-protected before emission, emit only the protected value and its matching public marker as defined by the typed helper or generated contract. Do not emit private source material in telemetry dimensions.
Credential-bearing chat setup failures replace provider-controlled error names,
messages, and stacks with a fresh generic error before the HTTP error handler
reports the crash. The existing error.handler_crash event still uses its
generated error_code: string contract; this path emits only Error, never a
provider-supplied error name that may contain a credential. This is a privacy
boundary, not enum canonicalization. Test the value reaching the telemetry
helper as well as the separate crash-reporting and local logging sinks.
Server Startup Privacy
The startup helper emits the raw Node.js operating system family once when an enabled server telemetry client initializes. It omits OS versions, CPU architecture, hostnames, and other machine details. The usual telemetry opt-out and CI suppression apply before client initialization. If state storage fails at startup, the server disables telemetry for that process and continues to run. The warning contains no storage path or underlying error. Container and WSL servers report their runtime platform; this does not identify the underlying physical host's OS. Count distinct installation identifiers by platform to compare installations, since restart event counts also reflect restart frequency.
Contract syncs may also register existing proposals. Remove each adopted proposal marker and update its helper and transport tests in the same change. The connector helpers preserve raw enum values and send only catalog connector keys and the approved lifecycle and invocation dimensions. Connection names, credentials, tool arguments, and tool results stay out of those events.
Interaction Resolver Events
interaction.created records the interaction kind and whether the create
request used a deprecated resolver-policy alias. It does not record the prompt,
title, options, questions, target identifier, creator identifier, or resolver
identifier.
interaction.resolved records the low-cardinality interaction outcome defined
in the generated contract. Its legacy_inherited_restriction dimension is
true only when stored migration provenance preserves a legacy resolver-policy
restriction. It is false for canonical new writes. This dimension describes
policy provenance. It does not contain user content or an identifier.
Emit interaction.resolved only after the complete decision transaction commits.
Conversational answers include the card outcome, source-message reference, and
activity audit in that transaction. A rollback or matching retry must not emit
a resolution event. This changes emission timing only: message text, comment IDs,
and user IDs remain in the instance database and are not added to telemetry.
Use trackInteractionCreated() and trackInteractionResolved() from
events.ts to emit these events. The generated contract remains the authority
for their exact dimensions and optionality.
Agent Task Run Events
agent.task_run records one terminal state for one agent run: succeeded,
interrupted, failed, cancelled, or timed_out. Emit it once per run, at
the run's terminal transition. Do not emit it for a run that is still active.
The event's task_id dimension is optional and privacy-protected. Never emit
the raw task id. Pass the raw id to trackAgentTaskRun() in events.ts. The
helper calls hashPrivateRef() on client.ts, which derives the emitted
value with a salted hash of the per-installation secret.
Use trackAgentTaskRun() to emit this event. The generated contract remains
the authority for its exact dimensions and optionality.
Cloud Direct Delivery
Self-hosted installs are unchanged. They post every batch to the collector,
private references stay hashed by hashPrivateRef(), and the collector and
its loader apply their anonymization. A self-hosted server never loads
posthog-node.
A Paperclip Cloud stack can send telemetry straight to PostHog instead. The
server turns this on only when the instance is Cloud-managed and
PAPERCLIP_POSTHOG_PROJECT_TOKEN, PAPERCLIP_CLOUD_STACK_ID, and
PAPERCLIP_POSTHOG_ENVIRONMENT are set.
PAPERCLIP_POSTHOG_DIRECT=0 sends through the collector again. The server owns
this transport (server/src/services/posthog-direct/). This package only
exposes the TelemetryTransport seam on TelemetryClient:
- With a transport, each flushed batch goes to the transport and never to the collector. One batch has exactly one sender.
- A transport with
hashesPrivateRefs: falsemakes the typed helpers emit raw task ids. Private source refs (for example a private repository name) are customer content, not identifiers, so they stay hashed on every path andsource_ref_hashedstaystruefor them. - The transport can capture per-event context at track time. That context is never added to the collector envelope.
Cloud is Paperclip's own service under the Cloud terms, so its events carry real identifiers: raw agent and task ids, the stack id, and the company and acting user ids when known. Event names, dimension names, metadata keys, the deterministic event uuid, and enum fallback normalization stay the same as the collector path, so existing insights keep working. Request headers from the browser SDK only link an event to a browser session. They never set identity or grant access. Do not use this path to send fields that are not in the generated contract.
On each start, a Cloud server with direct delivery also sends one
cloud.workspace_started event and a workspace $groupidentify, straight
through the PostHog client. Neither is in the generated contract, and neither
goes through TelemetryClient or the collector. The event carries
install_hash, the sha256 of the install id, which is the same value the
collector stores as install_id. It lets an offline job join a workspace's
pre-switch history. No other event carries install_hash.
Other Data Paths
This document covers Paperclip Telemetry only. The generated Telemetry contract covers neither the Observability path nor the run-log path. Two other data paths document their own contract in their own file:
- Observability — the operator-enabled OpenTelemetry trace path and Sentry error monitoring.
- Run-Log Events — events written to the
local
heartbeat_run_eventstable.
Dimension Values
Telemetry dimension values must be primitives. Use only the value types allowed
by TelemetryDimensionValue:
stringnumberboolean
Do not emit null, undefined, arrays, or objects as dimension values. Optional
dimensions should be omitted when absent.
When a dimension is enum-like, use the shared constant from constants.ts when
one exists. If no shared constant exists, use the generated telemetry type as the
domain. In all cases, the generated telemetry type remains the source of truth
for the emitted value.
Required, Optional, And Sentinel Values
Required and optional dimensions are defined by EventDimensionsMap.
Required dimensions must be present for every event of that name. Optional dimensions should be emitted only when the value is known and useful.
Sentinel values are only for required fields that have no observed raw value at the emitting layer. Do not use a sentinel to hide a concrete value that is new, custom, or not yet represented by a shared constant. Emit the concrete raw value and let the receiving layer canonicalize it.
Adding Or Changing Telemetry
Client code is responsible for emitting approved telemetry events at the right place in the product. Stable event names, dimensions, and enum domains must come from the generated telemetry contract before normal emitters use them.
For product work that needs to propose a new first-party event before schema
registration, use the proposal marker workflow in doc/TELEMETRY_WORKFLOW.md.
Those proposed calls stay on client.track(), carry an @ts-expect-error
marker on the event-name argument, and are swallowed at runtime until the
generated schema registers the event name.
For stable event work:
- Start from
generated/paperclip-telemetry.ts. The generated types are what reviewers use to verify event names, dimensions, optionality, value types, enum descriptions, and schema version. - Choose stable event and dimension names. Do not include user content, local machine details, secrets, credentials, private paths, or values that are not part of the public event contract.
- Use only
string,number, orbooleandimension values. - Reuse a shared constant from
constants.tsfor enum-like dimensions when one exists. If the generated telemetry domain has values beyond a shared constant, keep the emitter aligned with the generated telemetry type. - Keep emitters raw. Do not normalize, alias-map, or lowercase enum-like values in the client unless the generated contract explicitly calls for that emitted value.
- Add or update a typed helper in
events.tswhen the event is first-party and should have a stable helper API. - Update tests for helper behavior, including raw pass-through for enum-like values when that is the intended boundary.
- Keep the telemetry transport contract assertions in
client.test.ts, which owns the emitted-envelope, retry, and payload-size boundaries. - Update this README only when the contributor workflow, source-of-truth pointers, or durable invariants change. Do not add an event catalog here.
Before opening a pull request, verify that the emitted code, typed helpers, and generated telemetry contract agree. If they disagree, fix the contract or code rather than documenting around the mismatch in this README.
For new first-party events that are not in the generated contract yet, follow
the public proposal and promotion workflow in
doc/TELEMETRY_WORKFLOW.md.
Retention
Retention windows are documented in retention.ts. Each event is assigned a
retention class; the class determines the window in days. This is a
housekeeping and query-cost concern managed by data-infra, not a schema
concern — updating a retention window does not require a schema version bump.
Current classes:
| Class | Window | Description |
|---|---|---|
operational_enum_count |
90 days | Enum/boolean/count/bucket events. No token material, no PII. |
When a new event carries only enums, booleans, counts, or coarse buckets and
no token material or PII, assign it to operational_enum_count in
EVENT_RETENTION_CLASS. If no existing class fits, define a new class in
RETENTION_DAYS and document it here.
GitHub-synced skills
The legacy import endpoint retains skill.imported with its existing source_type.
For source-managed GitHub skills, skill_ref is omitted, including public sources:
the saved repository may be private and its key contains user-authored names.
Source discovery, selection, and refresh add no first-party telemetry events.
Repository URLs, paths, commits, connection IDs, names, and file contents stay out
of these telemetry dimensions. Review this suppression in privacy review alongside
changes to the legacy import caller; the event schema and envelope are unchanged.