Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

Implement anonymous usage telemetry and enhance related documentation

Lewis Carhart7ba7c64ccd91
diff --git a/.agents/skills/posthog-instrumentation/SKILL.md b/.agents/skills/posthog-instrumentation/SKILL.md
new file mode 100644
index 00000000..fcea3126
--- /dev/null
+++ b/.agents/skills/posthog-instrumentation/SKILL.md
@@ -0,0 +1,70 @@
+---
+name: posthog-instrumentation
+description: Automatically add PostHog analytics instrumentation to code. Triggers when user asks to add tracking, instrument events, add analytics, or implement feature flags in their codebase.
+---
+
+# PostHog Instrumentation Skill
+
+Help users add PostHog analytics, event tracking, and feature flags to their code.
+
+## When to Use
+
+- User asks to "add PostHog" or "add analytics"
+- User wants to track events or user actions
+- User needs to implement feature flags
+- User asks about instrumenting their code
+
+## Workflow
+
+1. Identify the framework (React, Next.js, Python, Node.js, etc.)
+2. Check for existing PostHog setup
+3. Add appropriate instrumentation
+
+## Code Patterns
+
+### JavaScript/TypeScript
+```javascript
+// Event tracking
+posthog.capture('button_clicked', { button_name: 'signup' })
+
+// Feature flags
+if (posthog.isFeatureEnabled('new-feature')) {
+ // Show new feature
+}
+
+// User identification
+posthog.identify(userId, { email: user.email })
+```
+
+### Python
+```python
+from posthog import Posthog
+posthog = Posthog(api_key='<ph_project_api_key>')
+
+# Event tracking
+posthog.capture(distinct_id='user_123', event='purchase_completed')
+
+# Feature flags
+if posthog.feature_enabled('new-feature', 'user_123'):
+ # Show new feature
+```
+
+### React
+```jsx
+import { usePostHog } from 'posthog-js/react'
+
+function MyComponent() {
+ const posthog = usePostHog()
+
+ const handleClick = () => {
+ posthog.capture('button_clicked')
+ }
+}
+```
+
+## Best Practices
+
+- Use consistent event naming (snake_case recommended)
+- Include relevant properties with events
+- Identify users early in their session
+- Use feature flags for gradual rollouts
diff --git a/.claude/skills/posthog-instrumentation b/.claude/skills/posthog-instrumentation
new file mode 120000
index 00000000..3f3fd694
--- /dev/null
+++ b/.claude/skills/posthog-instrumentation
@@ -0,0 +1 @@
+../../.agents/skills/posthog-instrumentation
\ No newline at end of file
diff --git a/.env.example b/.env.example
index c9a8a331..2b8fcda6 100644
--- a/.env.example
+++ b/.env.example
@@ -135,3 +135,29 @@ GOOGLE_CLIENT_SECRET=""
# parameters. Off by default: it buries every other line under a wall of
# SELECTs.
# PRISMA_LOG_QUERIES="true"
+
+
+# ── Anonymous usage telemetry ────────────────────────────────────────────────
+# This repo is MIT and cloned rather than installed, so there is no download
+# count and no runtime signal. Once a day the API sends one event of counts —
+# how many contacts exist in bands rather than exactly, which of the agent's
+# tools were called, how the evidence ledger behaved, which optional keys are
+# set as booleans — tied to a random UUID generated by the first migration.
+#
+# It is server-side only. There is no posthog-js anywhere, no autocapture and
+# no session replay, because autocapture on a CRM would lift contact names and
+# deal amounts out of your database. No name, address, company, subject line,
+# amount, prompt or key is ever sent, and neither is your IP: every event
+# carries $ip: null with geoip off.
+#
+# Settings → Telemetry shows your install ID and the full list either way.
+# docs/telemetry.md is the same list with every property named.
+
+# Turn it off. "1" is the whole interface, and DO_NOT_TRACK=1 does the same.
+# When either is set no client is created, so nothing can be sent later.
+#
+# There is no variable for where it goes: the project key and host are written
+# into packages/telemetry, because a write-only key is not a secret and a
+# variable would only suggest it were one. Change them there if you want the
+# numbers in your own project.
+# CRM_TELEMETRY_DISABLED="1"
diff --git a/AGENTS.md b/AGENTS.md
index 947f5532..fcac145a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,6 +13,7 @@ context until you read them, and the rules in them are not optional.
| Deal amounts, totals, charts, exchange rates | `docs/currency.md` |
| The record sheet's Agent tab | `docs/agent-panel.md` |
| Running it locally, Google Cloud, DB commands, secrets | `docs/setup.md` |
+| Anything that sends a telemetry event, or a new property on one | `docs/telemetry.md` |
Also check `.agents/skills/` for a relevant skill before starting — better-auth,
prisma, nestjs-trpc, eve, shadcn, nuqs and others have one. Tell the user which
diff --git a/README.md b/README.md
index dc28323d..4b407232 100644
--- a/README.md
+++ b/README.md
@@ -55,12 +55,6 @@ against its own work queue. It decides what to look at next, books its own follo
spends a research budget, and stops when the budget runs out. Nothing about it is
request-response: close the browser and it keeps going.
-The API deliberately has no intelligence in it at all. NestJS reports that *something
-happened* — a thread was ingested, a company was created, an attendee is unknown — by
-writing a row to a queue. The agent leases that row and decides what it means. A Nest
-service that calls an enrichment API is treated as a bug, and
-[`docs/api.md`](./docs/api.md) explains the outage that made that a rule.
-
The rule the agent itself never breaks: **nothing about a person is guessed.** No tool
accepts a confidence score, because a model asked to grade its own certainty will, and
it will be wrong in the direction that makes it look useful. Tools report what they
@@ -69,11 +63,6 @@ evidence. Strong evidence writes to the record. Weak evidence becomes a suggesti
human settles. A confidently wrong fact about a customer is worse than a blank field,
because nobody can tell it is wrong.
-It is single-tenant and internal by design. Sign-in is Google, the allow-list is one
-environment variable, and everyone who gets in can see everything. That is the whole
-authorisation model — see [SECURITY.md](./SECURITY.md) before you point it at real
-customer data.
-
## Screenshots
<table>
@@ -301,6 +290,7 @@ short version:
| `AGENT_BRIDGE_SECRET` | Lets a rep talk to the agent from a contact's **Agent** tab. |
| `REDIS_URL` | A shared cache. Without it, per-instance and in-memory. |
| `CRON_SECRET` | Guards the Gmail/Calendar sync route. Required to use it. |
+| `CRM_TELEMETRY_DISABLED` | Set to `1` and this install reports nothing. `DO_NOT_TRACK` too. |
## Tasks
diff --git a/adrs/usage.md b/adrs/usage.md
deleted file mode 100644
index 57595051..00000000
--- a/adrs/usage.md
+++ /dev/null
@@ -1,189 +0,0 @@
-# Task: anonymous usage telemetry for trycompai/crm
-
-Read `AGENTS.md` first and follow it. In particular: no code comments, one root `.env` with
-`.env.example` as its documentation, anything a self-hoster might not have is optional and its
-absence removes a capability rather than throwing, and no coauthored commits.
-
-**Before writing any implementation code, write an ADR** at `adrs/telemetry.md` following the
-format in `adrs/README.md`: what you want to change, why the current behaviour is a problem, what
-you'd do instead and what it would break. Then stop and wait for review. `CONTRIBUTING.md` is
-explicit that a paragraph someone wrote beats a PR full of generated code, and this is a change
-where the reasoning matters more than the diff.
-
-## Why
-
-This repo is MIT and cloned rather than installed, so there is no download signal and no runtime
-signal. We cannot tell which of the 20 agent tools earn their place, whether the evidence ledger
-actually holds up in the wild, or where people give up during setup. We want anonymous,
-aggregate usage data — enabled by default, trivially disabled, and auditable in one file.
-
-## Non-negotiable constraints
-
-1. **Server-side only.** `posthog-node` in `apps/api` and `apps/agent`. No `posthog-js`, no
- autocapture, no session replay, nothing in `apps/app`. Autocapture on a CRM would pull contact
- names, email addresses, company domains and deal amounts out of other people's databases. We
- do not want that data and would have to deal with it if we had it.
-
-2. **The install ID lives in Postgres, not the filesystem.** All three processes deploy to Vercel
- with an ephemeral filesystem, so the usual `~/.app/telemetry-id` pattern would mint a new ID
- on every cold start. Add a table with a single row holding a UUID, created in a migration.
- All three processes read it. Never call `identify()`, never attach an email, never attach
- `ALLOWED_SIGN_IN`.
-
-3. **Never instrument inside the sandbox.** `apps/agent/agent/sandbox` runs `deny-all` egress by
- design. A telemetry call in there will hang and then fail, and someone will spend a day
- debugging it. Emit from the agent runtime after the tool returns.
-
-4. **Never block, never throw.** Fire-and-forget with a swallowed error handler. `posthog.on('error')`
- logs at debug and nothing else. A telemetry failure must be invisible to the user and must not
- surface in a request path or an agent session.
-
-5. **Allowlist, not blocklist.** A single exported const listing every permitted property name.
- Anything not on the list is dropped before send, in code, not by convention.
-
-## Opt-out
-
-`CRM_TELEMETRY_DISABLED="1"` disables everything. Also honour `DO_NOT_TRACK=1`. Add both to
-`.env.example` with a note, and declare `CRM_TELEMETRY_DISABLED` in
-`apps/api/src/config/env.validation.ts` as optional.
-
-When disabled, call `posthog.disable()` at init so every subsequent `capture()` is a silent no-op.
-Do not scatter conditional guards through the codebase.
-
-Add a **Settings → Telemetry** page under `apps/app/app/(app)/[slug]/settings/` matching the
-existing pages there. It shows the current state, the exact JSON of the most recent payload, and
-a link to `docs/telemetry.md`. Reading it should take thirty seconds and answer every question
-someone would have.
-
-## What to send
-
-One `install_daily` rollup event per install per day, emitted from the API. Do **not** emit one
-event per tool call — the agent runs continuously and it would be noise and volume for no extra
-signal. Plus discrete events only for the setup funnel and errors, below.
-
-Derive everything from the schema in `packages/db/prisma/schema.prisma`. Counts and enum
-distributions only — never a value from a row.
-
-### Install shape
-
-- Install UUID, days since install, git commit or version
-- Deployment target: `VERCEL` set or not, Node version, Postgres major version
-- Capability booleans, mirroring `apps/agent/agent/lib/capabilities.ts` exactly: `RAPIDAPI_KEY`,
- `PERPLEXITY_API_KEY`, `CONTEXT_DEV` (the DB setting, not the key), `BLOB_READ_WRITE_TOKEN`.
- Extend with `GITHUB_TOKEN`, `REDIS_URL`, `AGENT_BRIDGE_SECRET`, `CRON_SECRET`,
- `AI_GATEWAY_API_KEY`, `IS_MARKETING`, whether Google OAuth is configured, whether an SSO
- provider row exists. Booleans only — never the values.
-- Configured agent model id from `AppSetting.agentModelId`, and its context window
-- Member count, bucketed
-
-### The agent
-
-This is the product, so it gets the most detail.
-
-- Tool invocation counts keyed by tool name, from the 20 files in `apps/agent/agent/tools/`.
- The open question is which four do 90% of the work.
-- Sessions started, sessions completed, mean tools per session
-- `AgentTask` counts by `kind` from `TASK_KINDS` (`brand`, `portrait`, `meeting-prep`, `identify`,
- `profile`, `recheck`, `company-profile`, `workspace-profile`): claimed, completed, and retired.
- A task retired by `retireExhausted()` hit `MAX_ATTEMPTS` and the session never reported back —
- that is a pure failure signal and should be its own counter per kind.
-- Mean and max `attempts` per kind
-- Budget exhaustion rate: how often a session stops because the budget ran out rather than
- because it finished
-- `schedule_recheck` calls, and the distribution of recheck intervals in day buckets
-- Whether the sandbox is enabled, and `AgentConversation` count — how many installs actually
- configure `AGENT_BRIDGE_SECRET` and talk to the agent from the Agent tab
-
-### The evidence ledger
-
-The core product claim is that nothing about a person is guessed. Telemetry can test it.
-
-- `ContactFact` counts by `status` (`APPLIED` / `PROPOSED` / `DISMISSED` / `SUPERSEDED`) and by
- `band` (`VERIFIED` / `PROBABLE` / `POSSIBLE`)
-- The dismissal rate on `PROPOSED` facts — the share a human looked at and rejected. This is the
- agent's precision as measured by users rather than by us.
-- Median time from `observedAt` to `decidedAt` — how long suggestions sit unsettled
-- Counts by `method`, and by evidence kind from the `WEIGHTS` map in
- `apps/agent/agent/lib/evidence.ts`. We assert that `crm.signature-block` and `crm.thread-reply`
- are the best evidence and that they are free. Measure whether installs with no API keys at all
- actually produce applied facts.
-- Facts superseded within N days of being applied — churn, meaning the agent changed its mind
-
-### CRM usage
-
-- `Contact`, `Company`, `Deal`, `Activity` counts, bucketed not exact
-- `Contact` and `Company` counts by `RecordSource` (`MANUAL` / `IMPORT` / `EMAIL` / `CALENDAR`).
- The README claims most contacts arrive from the mailbox sync rather than being typed. This
- measures it.
-- `Deal` counts by `DealStage`, to tell an install running a real pipeline from one only
- enriching contacts
-- `Activity` counts by `ActivityType`
-- Mailbox sync configured, last sync status from `MailboxSync`, threads and messages ingested in
- the period as counts
-- `CompanyEnrichment` counts by `EnrichmentStatus`
-- `SuppressedDomain` and `SuppressedContact` counts — people actively curating what the agent
- touches is a strong engagement signal
-- Whether `WorkspaceProfile` has been written
-
-### Setup funnel
-
-Discrete one-shot events, each fired once per install. This is the number nobody else instruments
-and probably the most valuable thing here.
-
-`migrations_applied` → `first_sign_in` → `google_oauth_configured` → `first_mailbox_sync` →
-`first_non_seed_contact` → `first_agent_task_claimed` → `first_agent_task_completed` →
-`first_fact_applied`
-
-Include a `seed_only` boolean on the daily rollup. `bun run db:seed` writes a known fixture set;
-an install whose data is only seed rows is someone who ran it once, not a user. Without this the
-numbers are meaningless.
-
-### Errors
-
-Error **class** plus the module or tool that threw. No messages, no stack traces, no payloads —
-unlike n8n, which does send error messages, our errors will contain contact fields.
-
-- Failed agent sessions by tool and error class
-- Failed Google sync by error class
-- API 5xx by route pattern and error class
-- Model or AI Gateway failures by class
-
-## What must never be sent
-
-Grounded in the actual schema. Put this list in `docs/telemetry.md` verbatim.
-
-- Any `Contact` or `User` name, email, title or photo
-- Any `Company` name, domain, industry or location
-- `ContactFact.value`, `.sourceUrl`, `.evidence`, `.field`
-- `AgentTask.reason` and `AgentTask.outcome` — both free text the agent wrote about a named person
-- `ContactBrief` content, `WorkspaceProfile.website`, `.narrative`, `.sections`
-- `EmailThread` and `EmailMessage` subjects or bodies, `CalendarEvent` titles, `CalendarAttendee` rows
-- `Deal` names and amounts. Stage distribution is fine; amounts are not.
-- `AgentEvent.data`, `AgentConversation` content, prompts, completions, reasoning traces
-- `ALLOWED_SIGN_IN`, `AppSetting.contextDevApiKey`, any key, secret, token or connection string
-- `SuppressedDomain` and `SuppressedContact` values — counts only
-- **IP address.** Set `$ip: null` and disable geoip. n8n collects IP and has to caveat their
- anonymity claim because of it. We do not need it and we would rather the claim be unqualified.
-
-## Deliverables
-
-1. `adrs/telemetry.md` — write this first, then stop for review
-2. `packages/telemetry` — one module, allowlist const, install-ID accessor, disabled-check,
- typed event builders
-3. A Prisma migration adding the install-ID table
-4. Wiring in `apps/api` (daily rollup, funnel events, API errors) and `apps/agent` (tool counters,
- session outcomes, agent errors)
-5. Settings → Telemetry page
-6. `docs/telemetry.md` — every event, every property, in plain English, plus the never-sent list
-7. `.env.example` entries and the `env.validation.ts` declaration
-8. A README line in the env table matching the style of the existing rows
-9. Tests: allowlist drops unknown properties, disabled flag produces zero network calls,
- `DO_NOT_TRACK` honoured, install ID stable across processes
-
-## Notes
-
-The PostHog project key (`phc_...`) is write-only and belongs in the committed `.env.example`
-alongside a PostHog EU host. It is public by design.
-
-Do not aggregate by querying every table on every request. The daily rollup should be one
-scheduled job doing grouped counts, reusing the pattern in `apps/api/src/dashboard` where it fits.
\ No newline at end of file
diff --git a/apps/agent/agent/agent.ts b/apps/agent/agent/agent.ts
index c6ce8583..de358c1f 100644
--- a/apps/agent/agent/agent.ts
+++ b/apps/agent/agent/agent.ts
@@ -1,12 +1,17 @@
import "@crm/env/load";
import { DEFAULT_AGENT_MODEL } from "@crm/db/settings";
+import { onTelemetryProblem, syncVersion } from "@crm/telemetry";
import { defineAgent, defineDynamic } from "eve";
import { logCapabilities } from "./lib/capabilities";
import { selectedModel } from "./lib/model";
void logCapabilities();
+onTelemetryProblem((message) => console.debug(`[telemetry] ${message}`));
+
+void syncVersion();
+
export default defineAgent({
model: defineDynamic({
fallback: DEFAULT_AGENT_MODEL.id,
diff --git a/apps/agent/agent/hooks/telemetry.ts b/apps/agent/agent/hooks/telemetry.ts
new file mode 100644
index 00000000..d203f847
--- /dev/null
+++ b/apps/agent/agent/hooks/telemetry.ts
@@ -0,0 +1,81 @@
+import { db } from "@crm/db";
+import { readAgentModel } from "@crm/db/settings";
+import { agentError, modelError } from "@crm/telemetry";
+import { defineHook } from "eve/hooks";
+
+let modelId: string | null = null;
+
+async function configuredModel(): Promise<string | null> {
+ if (modelId) return modelId;
+
+ try {
+ modelId = (await readAgentModel(db)).id;
+ } catch {
+ modelId = null;
+ }
+
+ return modelId;
+}
+
+const MODEL_CODES = [
+ "model",
+ "gateway",
+ "provider",
+ "rate_limit",
+ "context_length",
+ "overloaded",
+ "unauthorized",
+];
+
+function taskKind(
+ auth: { attributes?: Record<string, unknown> } | null,
+): string | null {
+ const kind = auth?.attributes?.taskKind;
+ return typeof kind === "string" && kind.trim() ? kind.trim() : null;
+}
+
+function looksLikeModel(code: string): boolean {
+ const lowered = code.toLowerCase();
+ return MODEL_CODES.some((marker) => lowered.includes(marker));
+}
+
+export default defineHook({
+ events: {
+ "action.result"(event, ctx) {
+ const { error, result, status } = event.data;
+ if (status === "completed") return;
+
+ agentError({
+ error: error ?? status,
+ tool: "toolName" in result ? result.toolName : null,
+ taskKind: taskKind(ctx.session.auth.current ?? null),
+ source: "tool",
+ });
+ },
+
+ "turn.failed"(event, ctx) {
+ agentError({
+ error: event.data.code,
+ taskKind: taskKind(ctx.session.auth.current ?? null),
+ source: "turn",
+ });
+ },
+
+ "session.failed"(event, ctx) {
+ agentError({
+ error: event.data.code,
+ taskKind: taskKind(ctx.session.auth.current ?? null),
+ source: "session",
+ });
+ },
+
+ async "step.failed"(event) {
+ if (!looksLikeModel(event.data.code)) return;
+
+ modelError({
+ error: event.data.code,
+ modelId: await configuredModel(),
+ });
+ },
+ },
+});
diff --git a/apps/agent/agent/lib/focus.ts b/apps/agent/agent/lib/focus.ts
index 10543ac6..0e58d33f 100644
--- a/apps/agent/agent/lib/focus.ts
+++ b/apps/agent/agent/lib/focus.ts
@@ -1,3 +1,4 @@
+import { bumpCounter, COUNTERS } from "@crm/telemetry";
import { defineState } from "eve/context";
export const focus = defineState("crm.focus", () => ({
@@ -37,6 +38,8 @@ export function spend(units = 1): { ok: true } | { ok: false; reason: string } {
const { spent, budget } = focus.get();
if (spent + units > budget) {
+ void bumpCounter(COUNTERS.budgetExhausted);
+
return {
ok: false,
reason:
diff --git a/apps/agent/agent/lib/tasks.ts b/apps/agent/agent/lib/tasks.ts
index e95ea236..a58aad9b 100644
--- a/apps/agent/agent/lib/tasks.ts
+++ b/apps/agent/agent/lib/tasks.ts
@@ -1,4 +1,5 @@
import { db, Prisma } from "@crm/db";
+import { MAX_ATTEMPTS, RETIRED_OUTCOME } from "@crm/db/agent-tasks";
export type LeasedTask = {
id: string;
@@ -21,9 +22,7 @@ export type TaskSubject = {
const LEASE_MS = 10 * 60_000;
-export const MAX_ATTEMPTS = 3;
-
-export { DIRECT_KINDS } from "@crm/db/agent-tasks";
+export { DIRECT_KINDS, MAX_ATTEMPTS } from "@crm/db/agent-tasks";
export async function claimDue(
limit: number,
@@ -70,7 +69,7 @@ export async function retireExhausted(): Promise<TaskSubject[]> {
return db.$queryRaw<TaskSubject[]>`
UPDATE "agentTask" AS t
SET "finishedAt" = ${now},
- "outcome" = ${`Gave up after ${MAX_ATTEMPTS} attempts: the session never reported back.`}
+ "outcome" = ${RETIRED_OUTCOME}
WHERE t."finishedAt" IS NULL
AND t."attempts" >= ${MAX_ATTEMPTS}
AND (t."leasedUntil" IS NULL OR t."leasedUntil" < ${now})
diff --git a/apps/agent/package.json b/apps/agent/package.json
index ab68a8a5..0c437819 100644
--- a/apps/agent/package.json
+++ b/apps/agent/package.json
@@ -12,13 +12,14 @@
"build": "eve build",
"start": "eve start",
"check-types": "tsc --noEmit",
- "test": "bun test",
+ "test": "CRM_TELEMETRY_DISABLED=1 bun test",
"lint": "biome check .",
"clean": "rm -rf .turbo .eve node_modules"
},
"dependencies": {
"@crm/db": "workspace:*",
"@crm/env": "workspace:*",
+ "@crm/telemetry": "workspace:*",
"context.dev": "^2.7.0",
"eve": "^0.29.4",
"zod": "^4.4.3"
diff --git a/apps/api/package.json b/apps/api/package.json
index 627e0b13..065a9e5c 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -16,7 +16,7 @@
"postinstall": "node scripts/chmod-trpc-binary.mjs",
"start": "bun src/main.ts",
"start:prod": "bun dist/main.js",
- "test": "bun test",
+ "test": "CRM_TELEMETRY_DISABLED=1 bun test",
"test:watch": "bun test --watch",
"trpc:generate": "nestjs-trpc generate -e src/app.module.ts -r \"**/*.router.ts\" -o src/generated",
"clean": "rm -rf .turbo dist node_modules src/generated"
@@ -25,6 +25,7 @@
"@crm/auth": "workspace:*",
"@crm/db": "workspace:*",
"@crm/env": "workspace:*",
+ "@crm/telemetry": "workspace:*",
"@keyv/redis": "^5.1.6",
"@nestjs/cache-manager": "^3.1.3",
"@nestjs/common": "^11.0.1",
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts
index 0d758d0e..4b7b31d7 100644
--- a/apps/api/src/app.module.ts
+++ b/apps/api/src/app.module.ts
@@ -22,6 +22,7 @@ import { logAuthRoute } from "./logging/request-logger.middleware";
import { SearchModule } from "./search/search.module";
import { SettingsModule } from "./settings/settings.module";
import { SsoModule } from "./sso/sso.module";
+import { TelemetryModule } from "./telemetry/telemetry.module";
import { TrpcModule } from "./trpc/trpc.module";
import { UsersModule } from "./users/users.module";
import { WorkspaceModule } from "./workspace/workspace.module";
@@ -55,6 +56,7 @@ import { WorkspaceModule } from "./workspace/workspace.module";
WorkspaceModule,
SsoModule,
BackfillModule,
+ TelemetryModule,
],
})
export class AppModule {}
diff --git a/apps/api/src/config/env.validation.ts b/apps/api/src/config/env.validation.ts
index 1ed1f3f9..55abd0a5 100644
--- a/apps/api/src/config/env.validation.ts
+++ b/apps/api/src/config/env.validation.ts
@@ -102,6 +102,10 @@ export class EnvironmentVariables {
@IsOptional()
@IsString()
AGENT_BRIDGE_SECRET?: string;
+
+ @IsOptional()
+ @IsString()
+ CRM_TELEMETRY_DISABLED?: string;
}
export function validateEnv(
diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.ts
index 69becaec..26410a91 100644
--- a/apps/api/src/generated/server.ts
+++ b/apps/api/src/generated/server.ts
@@ -35,6 +35,7 @@ import type { GoogleRouter } from "../google/google.router";
import type { SearchRouter } from "../search/search.router";
import type { SettingsRouter } from "../settings/settings.router";
import type { SsoRouter } from "../sso/sso.router";
+import type { TelemetryRouter } from "../telemetry/telemetry.router";
import type { UsersRouter } from "../users/users.router";
import type { WorkspaceRouter } from "../workspace/workspace.router";
@@ -218,6 +219,10 @@ const appRouter = t.router({
.input(deleteSsoProviderInput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SsoRouter["remove"]>>)
}),
+ telemetry: t.router({
+ status: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<TelemetryRouter["status"]>>)
+ }),
users: t.router({
me: publicProcedure
.query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<UsersRouter["me"]>>),
diff --git a/apps/api/src/google/google-sync.service.ts b/apps/api/src/google/google-sync.service.ts
index 7e284983..6b43f180 100644
--- a/apps/api/src/google/google-sync.service.ts
+++ b/apps/api/src/google/google-sync.service.ts
@@ -1,3 +1,4 @@
+import { syncError } from "@crm/telemetry";
import { Injectable, Logger } from "@nestjs/common";
import { CalendarSyncService } from "./calendar-sync.service";
import { GmailSyncService } from "./gmail-sync.service";
@@ -78,6 +79,8 @@ export class GoogleSyncService {
},
error instanceof Error ? error.stack : String(error),
);
+
+ syncError({ error, source: row.source });
}
}
diff --git a/apps/api/src/logging/all-exceptions.filter.ts b/apps/api/src/logging/all-exceptions.filter.ts
index 7e987a0a..6282a5e8 100644
--- a/apps/api/src/logging/all-exceptions.filter.ts
+++ b/apps/api/src/logging/all-exceptions.filter.ts
@@ -1,3 +1,4 @@
+import { apiError } from "@crm/telemetry";
import {
type ArgumentsHost,
Catch,
@@ -51,6 +52,8 @@ export class AllExceptionsFilter implements ExceptionFilter {
payload,
exception instanceof Error ? exception.stack : undefined,
);
+
+ apiError({ error: exception, route: routePattern(request), status });
return;
}
@@ -58,6 +61,11 @@ export class AllExceptionsFilter implements ExceptionFilter {
}
}
+function routePattern(request: Request): string | null {
+ const route = (request as { route?: { path?: unknown } }).route;
+ return typeof route?.path === "string" ? route.path : null;
+}
+
function describe(exception: unknown): string {
if (exception instanceof Error) {
return exception.message;
diff --git a/apps/api/src/telemetry/funnel.service.ts b/apps/api/src/telemetry/funnel.service.ts
new file mode 100644
index 00000000..0b6e5b46
--- /dev/null
+++ b/apps/api/src/telemetry/funnel.service.ts
@@ -0,0 +1,128 @@
+import type { Db } from "@crm/db";
+import { FactStatus } from "@crm/db";
+import {
+ MILESTONES,
+ type Milestone,
+ milestone,
+ reachedMilestones,
+ readInstall,
+} from "@crm/telemetry";
+import { Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { SEED_OWNER_PREFIX } from "./seed";
+
+@Injectable()
+export class FunnelService {
+ private readonly logger = new Logger(FunnelService.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async sweep(): Promise<Milestone[]> {
+ const reached = new Set(await reachedMilestones());
+ const outstanding = MILESTONES.filter((step) => !reached.has(step));
+ if (outstanding.length === 0) return [];
+
+ const sent: Milestone[] = [];
+
+ for (const step of outstanding) {
+ try {
+ const at = await this.when(step);
+ if (!at) continue;
+ if (await milestone(step, at)) sent.push(step);
+ } catch (error) {
+ this.logger.debug({
+ message: "Could not settle a telemetry milestone",
+ step,
+ reason: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ return sent;
+ }
+
+ private async when(step: Milestone): Promise<Date | null> {
+ switch (step) {
+ case "migrations_applied":
+ return (await readInstall())?.createdAt ?? null;
+
+ case "first_sign_in":
+ return this.earliest(
+ this.db.session.findFirst({
+ orderBy: { createdAt: "asc" },
+ select: { createdAt: true },
+ }),
+ (row) => row.createdAt,
+ );
+
+ case "google_oauth_configured":
+ return process.env.GOOGLE_CLIENT_ID?.trim() &&
+ process.env.GOOGLE_CLIENT_SECRET?.trim()
+ ? new Date()
+ : null;
+
+ case "first_mailbox_sync":
+ return this.earliest(
+ this.db.mailboxSync.findFirst({
+ where: { lastSyncedAt: { not: null } },
+ orderBy: { lastSyncedAt: "asc" },
+ select: { lastSyncedAt: true },
+ }),
+ (row) => row.lastSyncedAt,
+ );
+
+ case "first_non_seed_contact":
+ return this.earliest(
+ this.db.contact.findFirst({
+ where: {
+ OR: [
+ { ownerId: null },
+ { ownerId: { not: { startsWith: SEED_OWNER_PREFIX } } },
+ ],
+ },
+ orderBy: { createdAt: "asc" },
+ select: { createdAt: true },
+ }),
+ (row) => row.createdAt,
+ );
+
+ case "first_agent_task_claimed":
+ return this.earliest(
+ this.db.agentTask.findFirst({
+ where: { startedAt: { not: null } },
+ orderBy: { startedAt: "asc" },
+ select: { startedAt: true },
+ }),
+ (row) => row.startedAt,
+ );
+
+ case "first_agent_task_completed":
+ return this.earliest(
+ this.db.agentTask.findFirst({
+ where: { finishedAt: { not: null } },
+ orderBy: { finishedAt: "asc" },
+ select: { finishedAt: true },
+ }),
+ (row) => row.finishedAt,
+ );
+
+ case "first_fact_applied":
+ return this.earliest(
+ this.db.contactFact.findFirst({
+ where: { status: FactStatus.APPLIED },
+ orderBy: { observedAt: "asc" },
+ select: { observedAt: true, decidedAt: true },
+ }),
+ (row) => row.decidedAt ?? row.observedAt,
+ );
+ }
+ }
+
+ private async earliest<T>(
+ query: PromiseLike<T | null>,
+ pick: (row: T) => Date | null,
+ ): Promise<Date | null> {
+ const row = await query;
+ return row ? pick(row) : null;
+ }
+}
diff --git a/apps/api/src/telemetry/rollup.service.ts b/apps/api/src/telemetry/rollup.service.ts
new file mode 100644
index 00000000..68bb9913
--- /dev/null
+++ b/apps/api/src/telemetry/rollup.service.ts
@@ -0,0 +1,568 @@
+import {
+ ActivityType,
+ type Db,
+ DealStage,
+ EnrichmentStatus,
+ FactBand,
+ FactStatus,
+ RecordSource,
+} from "@crm/db";
+import { RETIRED_OUTCOME } from "@crm/db/agent-tasks";
+import { readAgentModel } from "@crm/db/settings";
+import { WORKSPACE_ID } from "@crm/db/workspace";
+import {
+ bucket,
+ dayBucket,
+ drainCounters,
+ installDaily,
+ markRollup,
+ type Properties,
+ permittedEvidenceKind,
+ permittedMethod,
+ permittedTaskKind,
+ permittedTool,
+ readInstall,
+ sameUtcDay,
+} from "@crm/telemetry";
+import { Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { FunnelService } from "./funnel.service";
+import { SEED_OWNER_PREFIX } from "./seed";
+
+const WINDOW_HOURS = 24;
+
+const HOUR_MS = 60 * 60 * 1000;
+
+const SUPERSEDE_WINDOW_DAYS = 7;
+
+const SANDBOX_TOOLS = new Set([
+ "bash",
+ "glob",
+ "grep",
+ "read_file",
+ "write_file",
+]);
+
+type Counted = { key: string; count: number };
+
+export type RollupOutcome = {
+ sent: boolean;
+ reason?: string;
+ milestones: string[];
+};
+
+@Injectable()
+export class RollupService {
+ private readonly logger = new Logger(RollupService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly funnel: FunnelService,
+ ) {}
+
+ async run(force = false): Promise<RollupOutcome> {
+ const milestones = await this.funnel.sweep();
+
+ const install = await readInstall();
+ if (!install) {
+ return { sent: false, reason: "no install row", milestones };
+ }
+
+ const now = new Date();
+ if (!force && sameUtcDay(install.lastRollupAt, now)) {
+ return { sent: false, reason: "already sent today", milestones };
+ }
+
+ const since = new Date(now.getTime() - WINDOW_HOURS * HOUR_MS);
+
+ try {
+ const properties = await this.gather(since);
+ await installDaily(properties);
+ await markRollup(now);
+
+ this.logger.log({
+ message: "Telemetry rollup sent",
+ windowHours: WINDOW_HOURS,
+ milestones: milestones.length,
+ });
+
+ return { sent: true, milestones };
+ } catch (error) {
+ this.logger.debug({
+ message: "Telemetry rollup could not be built",
+ reason: error instanceof Error ? error.message : String(error),
+ });
+
+ return { sent: false, reason: "failed", milestones };
+ }
+ }
+
+ private async gather(since: Date): Promise<Properties> {
+ const [shape, agent, ledger, crm] = await Promise.all([
+ this.shape(),
+ this.agent(since),
+ this.ledger(),
+ this.crm(since),
+ ]);
+
+ return { ...shape, ...agent, ...ledger, ...crm };
+ }
+
+ private async shape(): Promise<Properties> {
+ const [model, members, ssoProviders, postgres, contextKey] =
+ await Promise.all([
+ readAgentModel(this.db).catch(() => null),
+ this.db.member.count({ where: { organizationId: WORKSPACE_ID } }),
+ this.db.ssoProvider.count(),
+ this.postgresMajor(),
+ this.db.appSetting.findFirst({ select: { contextDevApiKey: true } }),
+ ]);
+
+ return {
+ node_version: process.versions.node.split(".")[0] ?? null,
+ postgres_version: postgres,
+ members_bucket: bucket(members),
+
+ cap_rapidapi: isSet("RAPIDAPI_KEY"),
+ cap_perplexity: isSet("PERPLEXITY_API_KEY"),
+ cap_context_dev: Boolean(contextKey?.contextDevApiKey?.trim()),
+ cap_blob: isSet("BLOB_READ_WRITE_TOKEN"),
+ cap_github: isSet("GITHUB_TOKEN"),
+ cap_redis: isSet("REDIS_URL"),
+ cap_agent_bridge: isSet("AGENT_BRIDGE_SECRET"),
+ cap_cron_secret: isSet("CRON_SECRET"),
+ cap_ai_gateway: isSet("AI_GATEWAY_API_KEY"),
+ cap_google_oauth:
+ isSet("GOOGLE_CLIENT_ID") && isSet("GOOGLE_CLIENT_SECRET"),
+ cap_sso_provider: ssoProviders > 0,
+ is_marketing: process.env.IS_MARKETING === "true",
+
+ agent_model_id: model?.id ?? null,
+ agent_model_context_window: model?.contextWindowTokens ?? null,
+ };
+ }
+
+ private async postgresMajor(): Promise<string | null> {
+ try {
+ const rows = await this.db.$queryRaw<{ version: string }[]>`
+ SELECT current_setting('server_version_num') AS version;
+ `;
+
+ const raw = Number(rows[0]?.version);
+ if (!Number.isFinite(raw)) return null;
+
+ return String(Math.floor(raw / 10_000));
+ } catch {
+ return null;
+ }
+ }
+
+ private async agent(since: Date): Promise<Properties> {
+ const [
+ tools,
+ sessions,
+ tasks,
+ attempts,
+ rechecks,
+ counters,
+ conversations,
+ ] = await Promise.all([
+ this.toolCalls(since),
+ this.sessions(since),
+ this.tasks(since),
+ this.attempts(since),
+ this.rechecks(since),
+ drainCounters(),
+ this.db.agentConversation.count(),
+ ]);
+
+ const total = Object.values(tools.calls).reduce((sum, n) => sum + n, 0);
+
+ return {
+ tool_calls: tools.calls,
+ tool_calls_total: total,
+ tool_errors: tools.errors,
+ sandbox_used: tools.sandbox,
+
+ sessions_started: sessions.started,
+ sessions_completed: sessions.completed,
+ sessions_failed: sessions.failed,
+ tools_per_session_mean: sessions.withTools
+ ? round(total / sessions.withTools)
+ : 0,
+
+ tasks_claimed: tasks.claimed,
+ tasks_completed: tasks.completed,
+ tasks_retired: tasks.retired,
+ task_attempts_mean: attempts.mean,
+ task_attempts_max: attempts.max,
+
+ budget_exhausted: counters.budget_exhausted ?? 0,
+
+ recheck_scheduled: rechecks.total,
+ recheck_interval_days: rechecks.buckets,
+
+ agent_conversations: conversations,
+ };
+ }
+
+ private async toolCalls(since: Date): Promise<{
+ calls: Record<string, number>;
+ errors: Record<string, number>;
+ sandbox: boolean;
+ }> {
+ const rows = await this.db.$queryRaw<
+ { tool: string | null; failed: boolean; count: bigint }[]
+ >`
+ SELECT
+ "data"->'result'->>'toolName' AS tool,
+ COALESCE("data"->>'status', 'completed') <> 'completed' AS failed,
+ COUNT(*) AS count
+ FROM "agentEvent"
+ WHERE "type" = 'action.result' AND "emittedAt" >= ${since}
+ GROUP BY 1, 2;
+ `;
+
+ const calls: Record<string, number> = {};
+ const errors: Record<string, number> = {};
+ let sandbox = false;
+
+ for (const row of rows) {
+ const tool = permittedTool(row.tool);
+ const count = Number(row.count);
+
+ calls[tool] = (calls[tool] ?? 0) + count;
+ if (row.failed) errors[tool] = (errors[tool] ?? 0) + count;
+ if (SANDBOX_TOOLS.has(tool)) sandbox = true;
+ }
+
+ return { calls, errors, sandbox };
+ }
+
+ private async sessions(since: Date): Promise<{
+ started: number;
+ completed: number;
+ failed: number;
+ withTools: number;
+ }> {
+ const rows = await this.db.$queryRaw<{ type: string; sessions: bigint }[]>`
+ SELECT "type", COUNT(DISTINCT "sessionId") AS sessions
+ FROM "agentEvent"
+ WHERE "emittedAt" >= ${since}
+ AND "type" IN ('session.started', 'session.waiting', 'session.failed', 'action.result')
+ GROUP BY 1;
+ `;
+
+ const of = (type: string) =>
+ Number(rows.find((row) => row.type === type)?.sessions ?? 0);
+
+ return {
+ started: of("session.started"),
+ completed: of("session.waiting"),
+ failed: of("session.failed"),
+ withTools: of("action.result"),
+ };
+ }
+
+ private async tasks(since: Date): Promise<{
+ claimed: Record<string, number>;
+ completed: Record<string, number>;
+ retired: Record<string, number>;
+ }> {
+ const [claimed, finished] = await Promise.all([
+ this.db.agentTask.groupBy({
+ by: ["kind"],
+ where: { startedAt: { gte: since } },
+ _count: { _all: true },
+ }),
+ this.db.agentTask.groupBy({
+ by: ["kind", "outcome"],
+ where: { finishedAt: { gte: since } },
+ _count: { _all: true },
+ }),
+ ]);
+
+ const completed: Record<string, number> = {};
+ const retired: Record<string, number> = {};
+
+ for (const row of finished) {
+ const kind = permittedTaskKind(row.kind);
+ const into = row.outcome === RETIRED_OUTCOME ? retired : completed;
+ into[kind] = (into[kind] ?? 0) + row._count._all;
+ }
+
+ return {
+ claimed: byKind(
+ claimed.map((row) => ({ key: row.kind, count: row._count._all })),
+ ),
+ completed,
+ retired,
+ };
+ }
+
+ private async attempts(
+ since: Date,
+ ): Promise<{ mean: Record<string, number>; max: Record<string, number> }> {
+ const rows = await this.db.agentTask.groupBy({
+ by: ["kind"],
+ where: { finishedAt: { gte: since } },
+ _avg: { attempts: true },
+ _max: { attempts: true },
+ });
+
+ const mean: Record<string, number> = {};
+ const max: Record<string, number> = {};
+
+ for (const row of rows) {
+ const kind = permittedTaskKind(row.kind);
+ mean[kind] = round(row._avg.attempts ?? 0);
+ max[kind] = row._max.attempts ?? 0;
+ }
+
+ return { mean, max };
+ }
+
+ private async rechecks(
+ since: Date,
+ ): Promise<{ total: number; buckets: Record<string, number> }> {
+ const rows = await this.db.agentTask.findMany({
+ where: { kind: "recheck", createdAt: { gte: since } },
+ select: { createdAt: true, dueAt: true },
+ });
+
+ const buckets: Record<string, number> = {};
+
+ for (const row of rows) {
+ const days = Math.max(
+ 0,
+ (row.dueAt.getTime() - row.createdAt.getTime()) / (24 * HOUR_MS),
+ );
+ const label = dayBucket(days);
+ buckets[label] = (buckets[label] ?? 0) + 1;
+ }
+
+ return { total: rows.length, buckets };
+ }
+
+ private async ledger(): Promise<Properties> {
+ const [byStatus, byBand, methods, kinds, decided, superseded] =
+ await Promise.all([
+ this.db.contactFact.groupBy({
+ by: ["status"],
+ _count: { _all: true },
+ }),
+ this.db.contactFact.groupBy({ by: ["band"], _count: { _all: true } }),
+ this.db.contactFact.groupBy({
+ by: ["method"],
+ _count: { _all: true },
+ }),
+ this.evidenceKinds(),
+ this.decisionHours(),
+ this.supersededWithin(SUPERSEDE_WINDOW_DAYS),
+ ]);
+
+ const statuses = countsOf(
+ byStatus.map((row) => ({ key: row.status, count: row._count._all })),
+ Object.values(FactStatus),
+ );
+
+ const dismissed = statuses[FactStatus.DISMISSED] ?? 0;
+ const proposed = statuses[FactStatus.PROPOSED] ?? 0;
+ const judged = dismissed + (statuses[FactStatus.APPLIED] ?? 0) + proposed;
+
+ return {
+ facts_by_status: statuses,
+ facts_by_band: countsOf(
+ byBand.map((row) => ({ key: row.band, count: row._count._all })),
+ Object.values(FactBand),
+ ),
+ facts_by_method: merge(
+ methods.map((row) => ({
+ key: permittedMethod(row.method),
+ count: row._count._all,
+ })),
+ ),
+ facts_by_evidence_kind: kinds,
+ fact_dismissal_rate: judged ? round(dismissed / judged) : 0,
+ fact_decision_median_hours: decided,
+ facts_superseded_within_7_days: superseded,
+ };
+ }
+
+ private async evidenceKinds(): Promise<Record<string, number>> {
+ const rows = await this.db.$queryRaw<{ kind: string; count: bigint }[]>`
+ SELECT item->>'kind' AS kind, COUNT(*) AS count
+ FROM "contactFact", jsonb_array_elements("evidence") AS item
+ WHERE jsonb_typeof("evidence") = 'array'
+ GROUP BY 1;
+ `;
+
+ return merge(
+ rows.map((row) => ({
+ key: permittedEvidenceKind(row.kind),
+ count: Number(row.count),
+ })),
+ );
+ }
+
+ private async decisionHours(): Promise<number | null> {
+ const rows = await this.db.$queryRaw<{ median: number | null }[]>`
+ SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (
+ ORDER BY EXTRACT(EPOCH FROM ("decidedAt" - "observedAt")) / 3600
+ ) AS median
+ FROM "contactFact"
+ WHERE "decidedAt" IS NOT NULL;
+ `;
+
+ const median = rows[0]?.median;
+ return median === null || median === undefined ? null : round(median);
+ }
+
+ private async supersededWithin(days: number): Promise<number> {
+ const rows = await this.db.$queryRaw<{ count: bigint }[]>`
+ SELECT COUNT(*) AS count
+ FROM "contactFact"
+ WHERE "supersededAt" IS NOT NULL
+ AND "supersededAt" - "observedAt" < make_interval(days => ${days});
+ `;
+
+ return Number(rows[0]?.count ?? 0);
+ }
+
+ private async crm(since: Date): Promise<Properties> {
+ const [
+ contacts,
+ companies,
+ deals,
+ activities,
+ contactSources,
+ companySources,
+ stages,
+ types,
+ syncs,
+ threads,
+ messages,
+ enrichment,
+ suppressedDomains,
+ suppressedContacts,
+ workspaceProfile,
+ nonSeedContacts,
+ ] = await Promise.all([
+ this.db.contact.count(),
+ this.db.company.count(),
+ this.db.deal.count(),
+ this.db.activity.count(),
+ this.db.contact.groupBy({ by: ["source"], _count: { _all: true } }),
+ this.db.company.groupBy({ by: ["source"], _count: { _all: true } }),
+ this.db.deal.groupBy({ by: ["stage"], _count: { _all: true } }),
+ this.db.activity.groupBy({ by: ["type"], _count: { _all: true } }),
+ this.db.mailboxSync.groupBy({ by: ["status"], _count: { _all: true } }),
+ this.db.emailThread.count({ where: { createdAt: { gte: since } } }),
+ this.db.emailMessage.count({ where: { createdAt: { gte: since } } }),
+ this.db.company.groupBy({
+ by: ["enrichmentStatus"],
+ _count: { _all: true },
+ }),
+ this.db.suppressedDomain.count(),
+ this.db.suppressedContact.count(),
+ this.db.workspaceProfile.count(),
+ this.db.contact.count({
+ where: {
+ OR: [
+ { ownerId: null },
+ { ownerId: { not: { startsWith: SEED_OWNER_PREFIX } } },
+ ],
+ },
+ }),
+ ]);
+
+ const configured = syncs.reduce((sum, row) => sum + row._count._all, 0);
+
+ return {
+ seed_only: contacts > 0 && nonSeedContacts === 0,
+
+ contacts_bucket: bucket(contacts),
+ companies_bucket: bucket(companies),
+ deals_bucket: bucket(deals),
+ activities_bucket: bucket(activities),
+
+ contacts_by_source: countsOf(
+ contactSources.map((row) => ({
+ key: row.source,
+ count: row._count._all,
+ })),
+ Object.values(RecordSource),
+ ),
+ companies_by_source: countsOf(
+ companySources.map((row) => ({
+ key: row.source,
+ count: row._count._all,
+ })),
+ Object.values(RecordSource),
+ ),
+ deals_by_stage: countsOf(
+ stages.map((row) => ({ key: row.stage, count: row._count._all })),
+ Object.values(DealStage),
+ ),
+ activities_by_type: countsOf(
+ types.map((row) => ({ key: row.type, count: row._count._all })),
+ Object.values(ActivityType),
+ ),
+
+ mailbox_sync_configured: configured > 0,
+ mailbox_sync_status: merge(
+ syncs.map((row) => ({ key: row.status, count: row._count._all })),
+ ),
+ threads_ingested: threads,
+ messages_ingested: messages,
+
+ enrichment_by_status: countsOf(
+ enrichment.map((row) => ({
+ key: row.enrichmentStatus,
+ count: row._count._all,
+ })),
+ Object.values(EnrichmentStatus),
+ ),
+
+ suppressed_domains: suppressedDomains,
+ suppressed_contacts: suppressedContacts,
+ workspace_profile_written: workspaceProfile > 0,
+ };
+ }
+}
+
+function isSet(name: string): boolean {
+ return Boolean(process.env[name]?.trim());
+}
+
+function byKind(rows: Counted[]): Record<string, number> {
+ return merge(
+ rows.map((row) => ({ ...row, key: permittedTaskKind(row.key) })),
+ );
+}
+
+function merge(rows: Counted[]): Record<string, number> {
+ const counts: Record<string, number> = {};
+
+ for (const row of rows) {
+ counts[row.key] = (counts[row.key] ?? 0) + row.count;
+ }
+
+ return counts;
+}
+
+function countsOf(
+ rows: Counted[],
+ keys: readonly string[],
+): Record<string, number> {
+ const merged = merge(rows);
+ const complete: Record<string, number> = {};
+
+ for (const key of keys) complete[key] = merged[key] ?? 0;
+
+ return complete;
+}
+
+function round(value: number): number {
+ return Math.round(value * 100) / 100;
+}
diff --git a/apps/api/src/telemetry/seed.ts b/apps/api/src/telemetry/seed.ts
new file mode 100644
index 00000000..128154ae
--- /dev/null
+++ b/apps/api/src/telemetry/seed.ts
@@ -0,0 +1,3 @@
+export const SEED_OWNER_PREFIX = "seed-";
+
+export const SEED_DEAL_PREFIX = "seed-deal-";
diff --git a/apps/api/src/telemetry/telemetry.controller.ts b/apps/api/src/telemetry/telemetry.controller.ts
new file mode 100644
index 00000000..0ccd1b85
--- /dev/null
+++ b/apps/api/src/telemetry/telemetry.controller.ts
@@ -0,0 +1,64 @@
+import {
+ Controller,
+ ForbiddenException,
+ Get,
+ Headers,
+ Logger,
+ Post,
+ ServiceUnavailableException,
+} from "@nestjs/common";
+import { ConfigService } from "@nestjs/config";
+import { AllowAnonymous } from "@thallesp/nestjs-better-auth";
+import type { EnvironmentVariables } from "../config/env.validation";
+import { RollupService } from "./rollup.service";
+
+@Controller("internal/telemetry")
+export class TelemetryController {
+ private readonly logger = new Logger(TelemetryController.name);
+ private readonly secret: string | undefined;
+
+ constructor(
+ private readonly rollup: RollupService,
+ config: ConfigService<EnvironmentVariables, true>,
+ ) {
+ this.secret = config.get("CRON_SECRET", { infer: true });
+ }
+
+ @Get("rollup")
+ @AllowAnonymous()
+ async rollupViaGet(@Headers("authorization") authorization?: string) {
+ return this.run(authorization);
+ }
+
+ @Post("rollup")
+ @AllowAnonymous()
+ async rollupViaPost(@Headers("authorization") authorization?: string) {
+ return this.run(authorization);
+ }
+
+ private async run(authorization?: string) {
+ if (!this.secret) {
+ this.logger.error({
+ message: "CRON_SECRET is not set — refusing to run the rollup route.",
+ });
+ throw new ServiceUnavailableException("Telemetry is not configured.");
+ }
+
+ if (!timingSafeEquals(authorization ?? "", `Bearer ${this.secret}`)) {
+ throw new ForbiddenException();
+ }
+
+ return this.rollup.run();
+ }
+}
+
+function timingSafeEquals(a: string, b: string): boolean {
+ if (a.length !== b.length) return false;
+
+ let mismatch = 0;
+ for (let index = 0; index < a.length; index += 1) {
+ mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index);
+ }
+
+ return mismatch === 0;
+}
diff --git a/apps/api/src/telemetry/telemetry.module.ts b/apps/api/src/telemetry/telemetry.module.ts
new file mode 100644
index 00000000..5b0e96b5
--- /dev/null
+++ b/apps/api/src/telemetry/telemetry.module.ts
@@ -0,0 +1,15 @@
+import { Module } from "@nestjs/common";
+import { TrpcModule } from "../trpc/trpc.module";
+import { FunnelService } from "./funnel.service";
+import { RollupService } from "./rollup.service";
+import { TelemetryController } from "./telemetry.controller";
+import { TelemetryRouter } from "./telemetry.router";
+import { TelemetryService } from "./telemetry.service";
+
+@Module({
+ imports: [TrpcModule],
+ controllers: [TelemetryController],
+ providers: [FunnelService, RollupService, TelemetryService, TelemetryRouter],
+ exports: [TelemetryService],
+})
+export class TelemetryModule {}
diff --git a/apps/api/src/telemetry/telemetry.router.ts b/apps/api/src/telemetry/telemetry.router.ts
new file mode 100644
index 00000000..d4c1d213
--- /dev/null
+++ b/apps/api/src/telemetry/telemetry.router.ts
@@ -0,0 +1,17 @@
+import { Inject } from "@nestjs/common";
+import { Query, Router, UseMiddlewares } from "nestjs-trpc";
+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";
+import { TelemetryService } from "./telemetry.service";
+
+@Router({ alias: "telemetry" })
+@UseMiddlewares(AuthMiddleware)
+export class TelemetryRouter {
+ constructor(
+ @Inject(TelemetryService) private readonly telemetry: TelemetryService,
+ ) {}
+
+ @Query()
+ async status() {
+ return this.telemetry.status();
+ }
+}
diff --git a/apps/api/src/telemetry/telemetry.service.ts b/apps/api/src/telemetry/telemetry.service.ts
new file mode 100644
index 00000000..8a0c530d
--- /dev/null
+++ b/apps/api/src/telemetry/telemetry.service.ts
@@ -0,0 +1,64 @@
+import {
+ crmVersion,
+ flushTelemetry,
+ onTelemetryProblem,
+ readInstall,
+ shutdownTelemetry,
+ syncVersion,
+ telemetryDisabled,
+} from "@crm/telemetry";
+import {
+ Injectable,
+ Logger,
+ type OnApplicationShutdown,
+ type OnModuleInit,
+} from "@nestjs/common";
+import { FunnelService } from "./funnel.service";
+
+@Injectable()
+export class TelemetryService implements OnModuleInit, OnApplicationShutdown {
+ private readonly logger = new Logger(TelemetryService.name);
+
+ constructor(private readonly funnel: FunnelService) {}
+
+ async onModuleInit(): Promise<void> {
+ onTelemetryProblem((message) => this.logger.debug({ message }));
+
+ if (telemetryDisabled()) {
+ this.logger.log({
+ message: "Anonymous usage telemetry is off for this install.",
+ });
+ return;
+ }
+
+ const install = await syncVersion(crmVersion() ?? undefined);
+
+ this.logger.log({
+ message: "Anonymous usage telemetry is on. See docs/telemetry.md.",
+ crmVersion: install?.version,
+ });
+
+ void this.funnel.sweep().catch(() => {});
+ }
+
+ async status(): Promise<{
+ enabled: boolean;
+ installId: string | null;
+ crmVersion: string | null;
+ lastSentAt: string | null;
+ }> {
+ const install = await readInstall();
+
+ return {
+ enabled: !telemetryDisabled(),
+ installId: install?.uuid ?? null,
+ crmVersion: install?.version ?? null,
+ lastSentAt: install?.lastRollupAt?.toISOString() ?? null,
+ };
+ }
+
+ async onApplicationShutdown(): Promise<void> {
+ await flushTelemetry();
+ await shutdownTelemetry();
+ }
+}
diff --git a/apps/api/src/trpc/trpc-error.handler.ts b/apps/api/src/trpc/trpc-error.handler.ts
index f9dddb46..4db326eb 100644
--- a/apps/api/src/trpc/trpc-error.handler.ts
+++ b/apps/api/src/trpc/trpc-error.handler.ts
@@ -1,3 +1,4 @@
+import { apiError } from "@crm/telemetry";
import { Injectable, Logger } from "@nestjs/common";
import type { OnErrorOptions, TRPCErrorHandler } from "nestjs-trpc";
@@ -14,6 +15,12 @@ export class TrpcErrorHandler implements TRPCErrorHandler {
{ message, type, path, code: error.code },
error.stack ?? String(error.cause ?? error),
);
+
+ apiError({
+ error: error.cause ?? error,
+ route: path ? `/trpc/${path}` : null,
+ status: 500,
+ });
return;
}
diff --git a/apps/api/vercel.json b/apps/api/vercel.json
index 994ee9b1..0e29716d 100644
--- a/apps/api/vercel.json
+++ b/apps/api/vercel.json
@@ -8,6 +8,10 @@
{
"path": "/internal/sync/rates",
"schedule": "0 6 * * *"
+ },
+ {
+ "path": "/internal/telemetry/rollup",
+ "schedule": "0 7 * * *"
}
]
}
diff --git a/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
index 062c2bc6..fde91357 100644
--- a/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
+++ b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
@@ -20,6 +20,7 @@ const ITEMS: SettingsNavItem[] = [
{ title: "Members", href: `${ROOT}/members` },
{ title: "SSO", href: `${ROOT}/sso` },
{ title: "Connections", href: `${ROOT}/connections` },
+ { title: "Telemetry", href: `${ROOT}/telemetry` },
];
function isActive(href: string, root: string, pathname: string): boolean {
diff --git a/apps/app/app/(app)/[slug]/settings/telemetry/page.tsx b/apps/app/app/(app)/[slug]/settings/telemetry/page.tsx
new file mode 100644
index 00000000..f3b01d8a
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/settings/telemetry/page.tsx
@@ -0,0 +1,57 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import {
+ PageShell,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellLoading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { TelemetryStatus } from "./telemetry-status";
+
+export const metadata: Metadata = {
+ title: "Telemetry",
+};
+
+export default function TelemetrySettingsPage() {
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Telemetry</PageShellTitle>
+ <PageShellDescription>
+ What this install reports about itself, and what it never will.
+ </PageShellDescription>
+ </PageShellHeading>
+ </PageShellHeader>
+
+ <PageShellContent>
+ <Suspense fallback={<PageShellLoading />}>
+ <Telemetry />
+ </Suspense>
+ </PageShellContent>
+ </PageShell>
+ );
+}
+
+async function Telemetry() {
+ await requireSession();
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+
+ await queryClient.prefetchQuery(trpc.telemetry.status.queryOptions());
+
+ return (
+ <HydrateClient>
+ <div className="flex max-w-3xl flex-col gap-6">
+ <TelemetryStatus />
+ </div>
+ </HydrateClient>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/settings/telemetry/telemetry-status.tsx b/apps/app/app/(app)/[slug]/settings/telemetry/telemetry-status.tsx
new file mode 100644
index 00000000..292907ac
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/settings/telemetry/telemetry-status.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@crm/ui/components/card";
+import { StatusIndicator } from "@crm/ui/components/status-indicator";
+import { relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useQuery } from "@tanstack/react-query";
+import { useTRPC } from "@/lib/trpc/client";
+
+const SENT = [
+ "A single daily count of what exists: how many contacts, companies, deals and activities, in bands rather than exact numbers.",
+ "Which of the agent's tools were called and how often, how many research sessions finished, and how many gave up.",
+ "How the evidence ledger behaved: how many facts were applied, proposed or dismissed, and how long suggestions waited for a decision.",
+ "Which optional keys are set — yes or no, never the values — the model you chose, your Node and Postgres versions, and this install's version.",
+ "When something failed: the error's class and the tool or route it came from.",
+];
+
+const NEVER_SENT = [
+ "Any name, email address, job title or photograph, of a contact or of you.",
+ "Any company name, domain, industry or location.",
+ "The content of a fact, a brief, a workspace profile, or anything the agent wrote about a person.",
+ "Email subjects and bodies, meeting titles, attendees, deal names and deal amounts.",
+ "Any prompt, completion, reasoning trace or agent conversation.",
+ "Any key, secret, token or connection string — and your IP address, which is discarded rather than recorded.",
+];
+
+function List({ items }: { items: readonly string[] }) {
+ return (
+ <ul className="flex list-disc flex-col gap-2 pl-4 text-muted-foreground text-sm">
+ {items.map((item) => (
+ <li key={item}>{item}</li>
+ ))}
+ </ul>
+ );
+}
+
+export function TelemetryStatus() {
+ const trpc = useTRPC();
+ const status = useQuery(trpc.telemetry.status.queryOptions());
+
+ const enabled = status.data?.enabled ?? false;
+
+ return (
+ <div className="flex flex-col gap-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>Anonymous usage telemetry</CardTitle>
+ <CardDescription>
+ This repository is cloned rather than installed, so there is no
+ other way to know which parts of it earn their place. Counts only,
+ once a day, tied to a random identifier and nothing else.
+ </CardDescription>
+
+ <CardAction>
+ <StatusIndicator
+ size="sm"
+ tone={enabled ? "success" : "neutral"}
+ label={enabled ? "On" : "Off"}
+ />
+ </CardAction>
+ </CardHeader>
+
+ <CardContent className="flex flex-col gap-4">
+ <dl className="grid gap-3 text-sm sm:grid-cols-3">
+ <div className="flex flex-col gap-1">
+ <dt className="text-muted-foreground text-xs">Install ID</dt>
+ <dd className="font-mono text-xs">
+ {status.data?.installId ?? "—"}
+ </dd>
+ </div>
+
+ <div className="flex flex-col gap-1">
+ <dt className="text-muted-foreground text-xs">Version</dt>
+ <dd className="font-mono text-xs">
+ {status.data?.crmVersion ?? "—"}
+ </dd>
+ </div>
+
+ <div className="flex flex-col gap-1">
+ <dt className="text-muted-foreground text-xs">Last sent</dt>
+ <dd className="text-xs">
+ {status.data?.lastSentAt
+ ? relativeTimeFromIso(status.data.lastSentAt)
+ : "Never"}
+ </dd>
+ </div>
+ </dl>
+
+ <p className="text-muted-foreground text-sm">
+ To turn it off, set{" "}
+ <code className="font-mono text-xs">CRM_TELEMETRY_DISABLED=1</code>{" "}
+ in the root <code className="font-mono text-xs">.env</code> file and
+ restart. <code className="font-mono text-xs">DO_NOT_TRACK=1</code>{" "}
+ does the same. Nothing is sent while either is set, and no client is
+ left running to send it later.
+ </p>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>What is sent</CardTitle>
+ <CardDescription>
+ Every property is on a list in the source, and anything not on that
+ list is dropped before the event is built.
+ </CardDescription>
+ </CardHeader>
+
+ <CardContent>
+ <List items={SENT} />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>What is never sent</CardTitle>
+ <CardDescription>
+ None of this leaves your database, whether telemetry is on or off.
+ </CardDescription>
+ </CardHeader>
+
+ <CardContent>
+ <List items={NEVER_SENT} />
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/bun.lock b/bun.lock
index 12475271..cc650a2f 100644
--- a/bun.lock
+++ b/bun.lock
@@ -16,6 +16,7 @@
"dependencies": {
"@crm/db": "workspace:*",
"@crm/env": "workspace:*",
+ "@crm/telemetry": "workspace:*",
"context.dev": "^2.7.0",
"eve": "^0.29.4",
"zod": "^4.4.3",
@@ -34,6 +35,7 @@
"@crm/auth": "workspace:*",
"@crm/db": "workspace:*",
"@crm/env": "workspace:*",
+ "@crm/telemetry": "workspace:*",
"@keyv/redis": "^5.1.6",
"@nestjs/cache-manager": "^3.1.3",
"@nestjs/common": "^11.0.1",
@@ -150,6 +152,20 @@
"typescript": "5.9.2",
},
},
+ "packages/telemetry": {
+ "name": "@crm/telemetry",
+ "version": "0.0.0",
+ "dependencies": {
+ "@crm/db": "workspace:*",
+ "@crm/env": "workspace:*",
+ "posthog-node": "^5.48.0",
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@types/node": "^24.10.1",
+ "typescript": "5.9.2",
+ },
+ },
"packages/typescript-config": {
"name": "@crm/typescript-config",
"version": "0.0.0",
@@ -347,6 +363,8 @@
"@crm/env": ["@crm/env@workspace:packages/env"],
+ "@crm/telemetry": ["@crm/telemetry@workspace:packages/telemetry"],
+
"@crm/typescript-config": ["@crm/typescript-config@workspace:packages/typescript-config"],
"@crm/ui": ["@crm/ui@workspace:packages/ui"],
@@ -511,6 +529,10 @@
"@paralleldrive/cuid2": ["@paralleldrive/[email protected]", "", { "dependencies": { "@noble/hashes": "^1.1.5" } }, "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw=="],
+ "@posthog/core": ["@posthog/[email protected]", "", { "dependencies": { "@posthog/types": "^1.401.1" } }, "sha512-WQTSwlFhsWk09xngTimHiTyhFU8QZHFZEGSm+6brY3acwYdvTLcTxpIhgl/qOCgn/XoqlCFTZqU1ldWLxNntfA=="],
+
+ "@posthog/types": ["@posthog/[email protected]", "", {}, "sha512-4PZ9wMYI8m8AqJuZ9YR1IAHGVtSnYbBVBgTevrKpzZbcSe/OUwhEV2Ks//rJh/L8eMTU8R5DrD4D/hlrOwaAiQ=="],
+
"@prisma/adapter-pg": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.9.1", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-Ho2RK1KanQxLNSC0sR5bpiiVep10sWPLXCcxK+KXfI/Q69TMRbiafSvLPv3V9snimX72rMCqGlyJ4sBO4lKTAw=="],
"@prisma/client": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/client-runtime-utils": "7.9.1" }, "peerDependencies": { "prisma": "*", "typescript": ">=5.4.0" }, "optionalPeers": ["prisma", "typescript"] }, "sha512-+xgrh2EhJVF79wC0yX5G4PI1Rdcm7Qn/nekNQ+t/O153wtNggruHal+fXHSa0QE+Tp/Cw5wvxeCEhZZ59xGm8Q=="],
@@ -1903,6 +1925,8 @@
"postgres-interval": ["[email protected]", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="],
+ "posthog-node": ["[email protected]", "", { "dependencies": { "@posthog/core": "^1.46.8" }, "peerDependencies": { "rxjs": "^7.0.0" }, "optionalPeers": ["rxjs"] }, "sha512-YIH82XV24aa1nnVph1ndiW/vBN2QDIKlrHNEJcmAYutMGeoGC4WeEefg7O5aD3dDcO5dzociy8sVwXq4tNDYsQ=="],
+
"powershell-utils": ["[email protected]", "", {}, "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A=="],
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
diff --git a/docs/environment.md b/docs/environment.md
index 1aad230a..a77b98d2 100644
--- a/docs/environment.md
+++ b/docs/environment.md
@@ -131,6 +131,24 @@ feature is only ever wrong), **no `GOOGLE_WORKSPACE_DOMAIN`** (`ALLOWED_SIGN_IN`
says who is internal — two sources is how a colleague becomes a lead), **no
`GMAIL_BACKFILL_DAYS`**, **no rate provider variable**.
+## Telemetry is on, and turning it off is one variable
+
+`CRM_TELEMETRY_DISABLED="1"` — or `DO_NOT_TRACK=1`, honoured identically — and nothing
+is sent. No client is constructed, so there is no queue waiting to flush later.
+
+- **Server side only**, `posthog-node` in the API and the agent. **There is no
+ `posthog-js` in this repo** and there must not be: autocapture on a CRM would
+ lift contact names and deal amounts out of somebody else's database.
+- **There is no variable for the destination.** The project key and host are
+ constants in `packages/telemetry/src/client.ts`. A `phc_` key is write-only —
+ it can send events and read nothing back — so making it configurable would
+ only imply it were a secret. Edit the constants to point somewhere else.
+- **The install ID is a row, not a file** — `install`, one row, UUID written by
+ the migration. Vercel's filesystem is ephemeral, so `~/.crm/telemetry-id`
+ would count containers.
+- Declared in `env.validation.ts` as optional, like everything else here. Every
+ event and the never-sent list are in **`docs/telemetry.md`**.
+
## Not env vars
- **Cache TTL** — `DEFAULT_TTL_MS` (60s) in `cache.module.ts`; `CACHE_TTL_MS` overrides.
diff --git a/docs/telemetry.md b/docs/telemetry.md
new file mode 100644
index 00000000..c3c57b06
--- /dev/null
+++ b/docs/telemetry.md
@@ -0,0 +1,192 @@
+# Telemetry
+
+What this install reports about itself, in full. The decisions behind it are in
+`adrs/telemetry.md`; this file is the list.
+
+**Turn it off** with `CRM_TELEMETRY_DISABLED="1"` or `DO_NOT_TRACK=1` in the root `.env`, then
+restart. Settings → Telemetry shows your install ID and the same lists in the app.
+
+**Where it goes** is not configurable and deliberately so: the project key and host are constants
+in `packages/telemetry/src/client.ts`. A `phc_` key is write-only — it sends events and reads
+nothing back — so a variable would only have made a public identifier look like a secret. Point
+a fork somewhere else by editing those two constants. Nothing is sent while `NODE_ENV` is
+`test`, so a test run cannot emit.
+
+## The shape of it
+
+- **Server side only.** `posthog-node` in `apps/api` and `apps/agent`. There is no `posthog-js`
+ in this repo, no autocapture, no session replay and nothing at all in `apps/app`. Autocapture
+ on a CRM would lift contact names, email addresses, company domains and deal amounts out of
+ your database; the simplest way not to hold that is not to collect it.
+- **One identifier**, a UUID generated by the migration that created your database. It is
+ attached to nothing else. `identify()` is never called, there are no person properties, and no
+ user, email or `ALLOWED_SIGN_IN` value is ever sent.
+- **One event a day**, plus eight one-shot setup events and one event per failure.
+- **No IP address.** Every event sets `$ip: null` and disables geoip, *and* the receiving project
+ has `anonymize_ips` on so the address is dropped at ingestion. Both are needed: PostHog stamps
+ `$ip` from the incoming connection whatever the SDK sends, and reads a null as "not provided"
+ rather than "do not keep". Point this at a different project and you must set it there too.
+- **Never blocks and never throws.** Every send is fire-and-forget behind a swallowed handler; a
+ telemetry failure logs at debug and is invisible everywhere else.
+- **Nothing is sent from a test run.** `NODE_ENV=test` disables it, and `apps/api` and `apps/agent`
+ additionally set `CRM_TELEMETRY_DISABLED=1` in their `test` scripts — because a spec is allowed
+ to reassign `process.env.NODE_ENV`, and one that does was enough to let a real event out.
+- **An allowlist, in code.** `ALLOWED_PROPERTIES` in `packages/telemetry/src/allowlist.ts` names
+ every property that may be sent. Anything else is dropped before the event is built — not by
+ review, not by convention.
+
+## Events
+
+### `install_daily`
+
+Once per install per day, from `POST /internal/telemetry/rollup` on the API's cron. Counts and
+distributions from grouped queries. Never a value from a row.
+
+#### The install
+
+| Property | What it is |
+| --- | --- |
+| `crm_version` | The root `package.json` version, re-read on every boot |
+| `git_commit_sha` | `VERCEL_GIT_COMMIT_SHA` when there is one; omitted otherwise |
+| `days_since_install` | Whole days since the first migration ran |
+| `is_vercel` | Whether `VERCEL` is set |
+| `node_version` | Major only, e.g. `22` |
+| `postgres_version` | Major only, e.g. `17` |
+| `members_bucket` | How many people work here, in bands |
+| `agent_model_id` | The model chosen on Settings → General, e.g. `zai/glm-5.2-fast` |
+| `agent_model_context_window` | Its context window in tokens |
+| `seed_only` | True when every contact came from `bun run db:seed` |
+
+#### Capabilities — booleans, never values
+
+`cap_rapidapi`, `cap_perplexity`, `cap_context_dev`, `cap_blob`, `cap_github`, `cap_redis`,
+`cap_agent_bridge`, `cap_cron_secret`, `cap_ai_gateway`, `cap_google_oauth`, `cap_sso_provider`,
+`is_marketing`.
+
+Each is only whether the key is set. `cap_context_dev` is whether an `AppSetting` row holds one,
+`cap_sso_provider` whether an `ssoProvider` row exists. No key, value or last-four is sent.
+
+#### The agent
+
+| Property | What it is |
+| --- | --- |
+| `tool_calls` | Calls in the last 24h, keyed by tool name |
+| `tool_calls_total` | Their sum |
+| `tool_errors` | Of those, the ones that returned an error, keyed by tool name |
+| `sandbox_used` | Whether any sandbox tool (`bash`, `grep`, `glob`, file reads and writes) ran |
+| `sessions_started` / `sessions_completed` / `sessions_failed` | Distinct sessions in the window |
+| `tools_per_session_mean` | Tool calls divided by sessions that made one |
+| `tasks_claimed` / `tasks_completed` / `tasks_retired` | `AgentTask` counts keyed by `kind` |
+| `task_attempts_mean` / `task_attempts_max` | Attempts per kind |
+| `budget_exhausted` | Sessions that stopped because the research budget ran out |
+| `recheck_scheduled` | `recheck` tasks queued in the window |
+| `recheck_interval_days` | Their intervals, in day bands |
+| `agent_conversations` | How many `AgentConversation` rows exist |
+
+Tool names are matched against the twenty tools in `apps/agent/agent/tools/` and eve's own
+builtins. Anything else is counted as `other`. Task kinds are matched against `TASK_KINDS`.
+
+Tool counts are read from the `agentEvent` rows the audit hook already writes — the event `type`
+and the tool name only. `AgentEvent.data` itself is never sent.
+
+#### The evidence ledger
+
+| Property | What it is |
+| --- | --- |
+| `facts_by_status` | `ContactFact` counts by `APPLIED` / `PROPOSED` / `DISMISSED` / `SUPERSEDED` |
+| `facts_by_band` | Counts by `VERIFIED` / `PROBABLE` / `POSSIBLE` |
+| `facts_by_method` | Counts by the `method` label a tool recorded |
+| `facts_by_evidence_kind` | Counts by evidence kind, from the `WEIGHTS` map in `lib/evidence.ts` |
+| `fact_dismissal_rate` | The share of decided facts a human rejected |
+| `fact_decision_median_hours` | Median hours from `observedAt` to `decidedAt` |
+| `facts_superseded_within_7_days` | Facts the agent changed its mind about |
+
+Evidence kinds are matched against the eleven in `lib/evidence.ts`; anything else is `other`.
+`method` is a label a tool writes, so it is sent only when it matches a strict lowercase
+dotted-slug shape under 40 characters — a name, an address or a sentence cannot pass, and is
+counted as `other` instead. The fact's `value`, `field`, `evidence` and `sourceUrl` are never
+sent.
+
+#### The CRM
+
+| Property | What it is |
+| --- | --- |
+| `contacts_bucket`, `companies_bucket`, `deals_bucket`, `activities_bucket` | Sizes, in bands |
+| `contacts_by_source`, `companies_by_source` | Counts by `MANUAL` / `IMPORT` / `EMAIL` / `CALENDAR` |
+| `deals_by_stage` | Counts by `DealStage`. Stages, never amounts |
+| `activities_by_type` | Counts by `ActivityType` |
+| `mailbox_sync_configured` | Whether any `MailboxSync` row exists |
+| `mailbox_sync_status` | Counts by `GoogleSyncStatus` |
+| `threads_ingested`, `messages_ingested` | How many arrived in the window. Counts only |
+| `enrichment_by_status` | `Company` counts by `EnrichmentStatus` |
+| `suppressed_domains`, `suppressed_contacts` | Counts. Never the domains or addresses |
+| `workspace_profile_written` | Whether a `WorkspaceProfile` row exists |
+
+### The setup funnel
+
+Eight events, each sent once per install, ever. Each carries the timestamp of the thing it
+records rather than the moment it was noticed, so the funnel reads true even though a nightly
+job is what sends it.
+
+`migrations_applied` → `first_sign_in` → `google_oauth_configured` → `first_mailbox_sync` →
+`first_non_seed_contact` → `first_agent_task_claimed` → `first_agent_task_completed` →
+`first_fact_applied`
+
+They carry no properties of their own beyond the common ones — version, days since install,
+whether this is Vercel.
+
+### Errors
+
+Error **class** and where it came from. Never a message, never a stack trace, never a payload:
+our errors would carry contact fields.
+
+| Event | Properties |
+| --- | --- |
+| `agent_error` | `error_class`, `tool`, `task_kind`, `error_source` (`tool` / `turn` / `session`) |
+| `sync_error` | `error_class`, `sync_source` (`gmail` / `calendar`) |
+| `api_error` | `error_class`, `route`, `status_code` |
+| `model_error` | `error_class`, `model_id` |
+
+`route` is the **route pattern** — `/internal/sync/google`, `/trpc/contacts.list` — never a URL
+with parameters in it. Anything that does not match a strict path shape is sent as `other`, and
+so is any error class that is not a plain identifier.
+
+## What is never sent
+
+- Any `Contact` or `User` name, email, title or photo
+- Any `Company` name, domain, industry or location
+- `ContactFact.value`, `.sourceUrl`, `.evidence`, `.field`
+- `AgentTask.reason` and `AgentTask.outcome` — both free text the agent wrote about a named person
+- `ContactBrief` content, `WorkspaceProfile.website`, `.narrative`, `.sections`
+- `EmailThread` and `EmailMessage` subjects or bodies, `CalendarEvent` titles, `CalendarAttendee` rows
+- `Deal` names and amounts. Stage distribution is fine; amounts are not.
+- `AgentEvent.data`, `AgentConversation` content, prompts, completions, reasoning traces
+- `ALLOWED_SIGN_IN`, `AppSetting.contextDevApiKey`, any key, secret, token or connection string
+- `SuppressedDomain` and `SuppressedContact` values — counts only
+- **IP address.** Set `$ip: null` and disable geoip. n8n collects IP and has to caveat their
+ anonymity claim because of it. We do not need it and we would rather the claim be unqualified.
+
+On that last line: the two properties alone do not achieve it, because PostHog fills `$ip` in from
+the connection during ingestion. `anonymize_ips` is enabled on the receiving project, which is what
+actually drops it. See `adrs/telemetry.md`.
+
+## Where it lives
+
+| | |
+| --- | --- |
+| `packages/telemetry` | The only place `posthog-node` is imported. Allowlist, install accessor, event builders |
+| `install` table | The UUID, the version, and when the last rollup went. One row, made by the migration |
+| `telemetryMilestone` table | Which funnel steps have fired |
+| `telemetryCounter` table | The two runtime numbers no other row records, drained by each rollup |
+| `apps/api/src/telemetry` | The daily rollup, the funnel sweep, the cron route |
+| `apps/agent/agent/hooks/telemetry.ts` | Tool, turn and session failures |
+
+Nothing is instrumented inside `apps/agent/agent/sandbox`, which runs `deny-all` egress by
+design. A capture in there would hang and then fail.
+
+## Adding a property
+
+1. Add its name to `ALLOWED_PROPERTIES`. Until it is there, it is dropped.
+2. Add a row to the table above.
+3. If it is an open set of keys — a tool, a method, a route — give it a `permitted*` function so
+ the keys are constrained too, not just the property name.
diff --git a/package.json b/package.json
index bb28e42b..f654946d 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "crm",
"private": true,
"license": "MIT",
- "version": "1.0.0",
+ "version": "1.0.1",
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev",
diff --git a/packages/db/prisma/migrations/20260805160000_telemetry_install/migration.sql b/packages/db/prisma/migrations/20260805160000_telemetry_install/migration.sql
new file mode 100644
index 00000000..a05a0c74
--- /dev/null
+++ b/packages/db/prisma/migrations/20260805160000_telemetry_install/migration.sql
@@ -0,0 +1,55 @@
+-- The anonymous install identity, in Postgres rather than on disk.
+--
+-- All three processes deploy to Vercel, where the filesystem is ephemeral, so
+-- the usual ~/.app/telemetry-id file would mint a new UUID on every cold start
+-- and we would be counting containers instead of installs.
+--
+-- One row, id pinned to 'install' by `@crm/telemetry`, the same singleton
+-- shape as "appSetting". The row is written here rather than on first boot so
+-- that the ID exists from the moment the schema does — "createdAt" is then a
+-- real install date, and the first funnel step is stamped by the statement
+-- that created the install rather than by whichever process happened to start.
+--
+-- "version" is upserted from the root package.json on every boot, so an
+-- upgrade is visible without redeploying telemetry code. 'unknown' only
+-- survives until the API or the agent next starts.
+CREATE TABLE "install" (
+ "id" TEXT NOT NULL,
+ "uuid" TEXT NOT NULL,
+ "version" TEXT NOT NULL,
+ "lastRollupAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "install_pkey" PRIMARY KEY ("id")
+);
+
+CREATE UNIQUE INDEX "install_uuid_key" ON "install"("uuid");
+
+INSERT INTO "install" ("id", "uuid", "version")
+VALUES ('install', gen_random_uuid()::text, 'unknown');
+
+-- The setup funnel is one-shot: each step fires once per install, ever. A
+-- boolean column read and then written races between the API and the agent;
+-- an insert that reports whether it was the one to land does not.
+CREATE TABLE "telemetryMilestone" (
+ "step" TEXT NOT NULL,
+ "reachedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "telemetryMilestone_pkey" PRIMARY KEY ("step")
+);
+
+-- Counters for the two things the daily rollup wants that leave no other row:
+-- a session that stopped because its research budget ran out, and a tool that
+-- returned an error. Everything else the rollup reports is already in the
+-- schema and is counted there.
+--
+-- Drained with UPDATE … SET count = 0 … RETURNING, so an increment landing
+-- mid-drain is counted tomorrow rather than lost.
+CREATE TABLE "telemetryCounter" (
+ "name" TEXT NOT NULL,
+ "count" INTEGER NOT NULL DEFAULT 0,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "telemetryCounter_pkey" PRIMARY KEY ("name")
+);
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index cd1bf4c8..91dc6edf 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -658,6 +658,35 @@ model AppSetting {
@@map("appSetting")
}
+model Install {
+ id String @id
+
+ uuid String @unique
+ version String
+
+ lastRollupAt DateTime?
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@map("install")
+}
+
+model TelemetryMilestone {
+ step String @id
+ reachedAt DateTime @default(now())
+
+ @@map("telemetryMilestone")
+}
+
+model TelemetryCounter {
+ name String @id
+ count Int @default(0)
+ updatedAt DateTime @updatedAt
+
+ @@map("telemetryCounter")
+}
+
model Organization {
id String @id
name String
diff --git a/packages/db/src/agent-tasks.ts b/packages/db/src/agent-tasks.ts
index 0be6d601..85c8b0de 100644
--- a/packages/db/src/agent-tasks.ts
+++ b/packages/db/src/agent-tasks.ts
@@ -19,6 +19,10 @@ export function isDirectKind(kind: string): kind is DirectKind {
return (DIRECT_KINDS as readonly string[]).includes(kind);
}
+export const MAX_ATTEMPTS = 3;
+
+export const RETIRED_OUTCOME = `Gave up after ${MAX_ATTEMPTS} attempts: the session never reported back.`;
+
export const PRIORITY = {
brand: 900,
portrait: 800,
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index 56cbbfbe..eaac876e 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -5,7 +5,7 @@ const FILES = [".env", ".env.local"] as const;
let loaded = false;
-function findWorkspaceRoot(start: string): string | null {
+export function findWorkspaceRoot(start: string): string | null {
let directory = resolve(start);
for (;;) {
diff --git a/packages/telemetry/package.json b/packages/telemetry/package.json
new file mode 100644
index 00000000..2a9718fc
--- /dev/null
+++ b/packages/telemetry/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "@crm/telemetry",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./allowlist": "./src/allowlist.ts",
+ "./install": "./src/install.ts"
+ },
+ "scripts": {
+ "check-types": "tsc --noEmit",
+ "lint": "biome check .",
+ "test": "bun test",
+ "clean": "rm -rf .turbo node_modules"
+ },
+ "dependencies": {
+ "@crm/db": "workspace:*",
+ "@crm/env": "workspace:*",
+ "posthog-node": "^5.48.0"
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@types/node": "^24.10.1",
+ "typescript": "5.9.2"
+ }
+}
diff --git a/packages/telemetry/src/allowlist.ts b/packages/telemetry/src/allowlist.ts
new file mode 100644
index 00000000..5f2e64ec
--- /dev/null
+++ b/packages/telemetry/src/allowlist.ts
@@ -0,0 +1,283 @@
+import { TASK_KINDS } from "@crm/db/agent-tasks";
+
+export const ALLOWED_PROPERTIES = [
+ "crm_version",
+ "git_commit_sha",
+ "days_since_install",
+ "is_vercel",
+ "node_version",
+ "postgres_version",
+ "seed_only",
+
+ "cap_rapidapi",
+ "cap_perplexity",
+ "cap_context_dev",
+ "cap_blob",
+ "cap_github",
+ "cap_redis",
+ "cap_agent_bridge",
+ "cap_cron_secret",
+ "cap_ai_gateway",
+ "cap_google_oauth",
+ "cap_sso_provider",
+ "is_marketing",
+ "agent_model_id",
+ "agent_model_context_window",
+ "members_bucket",
+
+ "tool_calls",
+ "tool_calls_total",
+ "tool_errors",
+ "sessions_started",
+ "sessions_completed",
+ "sessions_failed",
+ "tools_per_session_mean",
+ "tasks_claimed",
+ "tasks_completed",
+ "tasks_retired",
+ "task_attempts_mean",
+ "task_attempts_max",
+ "budget_exhausted",
+ "recheck_scheduled",
+ "recheck_interval_days",
+ "sandbox_used",
+ "agent_conversations",
+
+ "facts_by_status",
+ "facts_by_band",
+ "facts_by_method",
+ "facts_by_evidence_kind",
+ "fact_dismissal_rate",
+ "fact_decision_median_hours",
+ "facts_superseded_within_7_days",
+
+ "contacts_bucket",
+ "companies_bucket",
+ "deals_bucket",
+ "activities_bucket",
+ "contacts_by_source",
+ "companies_by_source",
+ "deals_by_stage",
+ "activities_by_type",
+ "mailbox_sync_configured",
+ "mailbox_sync_status",
+ "threads_ingested",
+ "messages_ingested",
+ "enrichment_by_status",
+ "suppressed_domains",
+ "suppressed_contacts",
+ "workspace_profile_written",
+
+ "error_class",
+ "error_source",
+ "tool",
+ "task_kind",
+ "route",
+ "status_code",
+ "sync_source",
+ "model_id",
+] as const;
+
+export type AllowedProperty = (typeof ALLOWED_PROPERTIES)[number];
+
+const ALLOWED = new Set<string>(ALLOWED_PROPERTIES);
+
+export type PropertyValue =
+ | string
+ | number
+ | boolean
+ | null
+ | Record<string, number>;
+
+export type Properties = Partial<Record<AllowedProperty, PropertyValue>>;
+
+export function permitted(
+ properties: Record<string, unknown>,
+): Record<string, PropertyValue> {
+ const kept: Record<string, PropertyValue> = {};
+
+ for (const [name, value] of Object.entries(properties)) {
+ if (!ALLOWED.has(name)) continue;
+ if (value === undefined) continue;
+ kept[name] = value as PropertyValue;
+ }
+
+ return kept;
+}
+
+export const AGENT_TOOLS = [
+ "enrich_company",
+ "fetch_contact_photo",
+ "find_contact_socials",
+ "get_contact_work_history",
+ "get_linkedin_profile",
+ "identify_contact",
+ "list_outstanding_work",
+ "read_company_history",
+ "read_crm_history",
+ "read_deal_history",
+ "record_fact",
+ "record_job_change",
+ "research_company",
+ "research_person",
+ "resolve_linkedin_profile",
+ "schedule_recheck",
+ "search_crm",
+ "set_contact_socials",
+ "write_brief",
+ "write_workspace_profile",
+] as const;
+
+export const EVE_TOOLS = [
+ "agent",
+ "ask_question",
+ "bash",
+ "connection_search",
+ "glob",
+ "grep",
+ "load_skill",
+ "read_file",
+ "todo",
+ "web_fetch",
+ "web_search",
+ "write_file",
+] as const;
+
+const TOOLS = new Set<string>([...AGENT_TOOLS, ...EVE_TOOLS]);
+
+export const OTHER = "other";
+
+export function permittedTool(name: string | null | undefined): string {
+ return name && TOOLS.has(name) ? name : OTHER;
+}
+
+export const EVIDENCE_KINDS = [
+ "profile.email-match",
+ "linkedin.employer-and-name",
+ "crm.thread-reply",
+ "crm.signature-block",
+ "github.account-identity",
+ "crm.meeting-attendance",
+ "web.cited-claim",
+ "handle.name-form",
+ "search.cites-profile",
+ "employer-only",
+ "contradiction",
+] as const;
+
+const KINDS = new Set<string>(EVIDENCE_KINDS);
+
+export function permittedEvidenceKind(kind: string | null | undefined): string {
+ return kind && KINDS.has(kind) ? kind : OTHER;
+}
+
+const METHOD_SHAPE = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;
+
+const METHOD_MAX = 40;
+
+export function permittedMethod(method: string | null | undefined): string {
+ if (!method) return OTHER;
+
+ const trimmed = method.trim();
+ if (trimmed.length > METHOD_MAX) return OTHER;
+
+ return METHOD_SHAPE.test(trimmed) ? trimmed : OTHER;
+}
+
+export const ERROR_CLASS_MAX = 64;
+
+const CLASS_SHAPE = /^[A-Za-z][A-Za-z0-9_.-]*$/;
+
+export function permittedErrorClass(value: unknown): string {
+ const name = errorName(value);
+ if (name.length > ERROR_CLASS_MAX) return OTHER;
+
+ return CLASS_SHAPE.test(name) ? name : OTHER;
+}
+
+function errorName(value: unknown): string {
+ if (value instanceof Error) return value.name || value.constructor.name;
+
+ if (typeof value === "string") return value;
+
+ if (typeof value === "object" && value !== null && "code" in value) {
+ const code = (value as { code: unknown }).code;
+ if (typeof code === "string") return code;
+ }
+
+ return OTHER;
+}
+
+const TASK_KIND_SET = new Set<string>(TASK_KINDS);
+
+export function permittedTaskKind(kind: string | null | undefined): string {
+ return kind && TASK_KIND_SET.has(kind) ? kind : OTHER;
+}
+
+export const SYNC_SOURCES = ["gmail", "calendar"] as const;
+
+const SYNC_SOURCE_SET = new Set<string>(SYNC_SOURCES);
+
+export function permittedSyncSource(source: string | null | undefined): string {
+ return source && SYNC_SOURCE_SET.has(source) ? source : OTHER;
+}
+
+const ROUTE_SHAPE = /^\/[A-Za-z0-9/_:.*-]*$/;
+
+const ROUTE_MAX = 120;
+
+export function permittedRoute(route: string | null | undefined): string {
+ if (!route) return OTHER;
+
+ const trimmed = route.trim();
+ if (trimmed.length > ROUTE_MAX) return OTHER;
+
+ return ROUTE_SHAPE.test(trimmed) ? trimmed : OTHER;
+}
+
+const MODEL_SHAPE = /^[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/i;
+
+const MODEL_MAX = 80;
+
+export function permittedModelId(model: string | null | undefined): string {
+ if (!model) return OTHER;
+
+ const trimmed = model.trim();
+ if (trimmed.length > MODEL_MAX) return OTHER;
+
+ return MODEL_SHAPE.test(trimmed) ? trimmed : OTHER;
+}
+
+const COUNT_BUCKETS = [
+ { under: 1, label: "0" },
+ { under: 10, label: "1-9" },
+ { under: 50, label: "10-49" },
+ { under: 200, label: "50-199" },
+ { under: 1_000, label: "200-999" },
+ { under: 5_000, label: "1000-4999" },
+ { under: 25_000, label: "5000-24999" },
+] as const;
+
+export function bucket(count: number): string {
+ for (const step of COUNT_BUCKETS) {
+ if (count < step.under) return step.label;
+ }
+
+ return "25000+";
+}
+
+const DAY_BUCKETS = [
+ { under: 2, label: "0-1" },
+ { under: 8, label: "2-7" },
+ { under: 31, label: "8-30" },
+ { under: 91, label: "31-90" },
+ { under: 181, label: "91-180" },
+] as const;
+
+export function dayBucket(days: number): string {
+ for (const step of DAY_BUCKETS) {
+ if (days < step.under) return step.label;
+ }
+
+ return "180+";
+}
diff --git a/packages/telemetry/src/client.ts b/packages/telemetry/src/client.ts
new file mode 100644
index 00000000..1775dc1b
--- /dev/null
+++ b/packages/telemetry/src/client.ts
@@ -0,0 +1,168 @@
+import "@crm/env/load";
+
+import { PostHog } from "posthog-node";
+import { type Properties, permitted } from "./allowlist";
+import { telemetryDisabled } from "./disabled";
+import { daysSince, readInstall } from "./install";
+import { commitSha } from "./version";
+
+export const POSTHOG_KEY = "phc_xKYTYbcX9bEB7sEaCpfZUCqV7HBxZw3QQVztuXf86Q9N";
+
+export const POSTHOG_HOST = "https://k.trycomp.ai";
+
+const FLUSH_TIMEOUT_MS = 3_000;
+
+type Debug = (message: string) => void;
+
+let debug: Debug = () => {};
+
+export function onTelemetryProblem(sink: Debug | null): void {
+ debug = sink ?? (() => {});
+}
+
+let client: PostHog | null = null;
+
+let built = false;
+
+function posthog(): PostHog | null {
+ if (built) return client;
+ built = true;
+
+ const off = telemetryDisabled();
+
+ try {
+ client = new PostHog(POSTHOG_KEY, {
+ host: POSTHOG_HOST,
+ flushAt: 1,
+ flushInterval: 0,
+ disabled: off,
+ disableGeoip: true,
+ enableExceptionAutocapture: false,
+ fetchRetryCount: 1,
+ });
+
+ if (off) {
+ void client.disable().catch(() => {});
+ debug("Telemetry is disabled — every capture is a no-op.");
+ }
+
+ client.on("error", (error: unknown) => {
+ debug(
+ `PostHog could not send: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ });
+ } catch (error) {
+ debug(
+ `PostHog could not start: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ client = null;
+ }
+
+ return client;
+}
+
+export function resetTelemetryClient(): void {
+ client = null;
+ built = false;
+}
+
+async function payload(
+ properties: Properties,
+): Promise<Record<string, unknown> | null> {
+ const install = await readInstall();
+ if (!install) return null;
+
+ const sha = commitSha();
+
+ return {
+ distinctId: install.uuid,
+ properties: {
+ ...permitted({
+ crm_version: install.version,
+ days_since_install: daysSince(install.createdAt),
+ is_vercel: Boolean(process.env.VERCEL),
+ ...(sha ? { git_commit_sha: sha } : {}),
+ ...properties,
+ }),
+ $ip: null,
+ $process_person_profile: false,
+ },
+ disableGeoip: true,
+ };
+}
+
+export function capture(event: string, properties: Properties = {}): void {
+ void send(event, properties);
+}
+
+export async function captureNow(
+ event: string,
+ properties: Properties = {},
+ at?: Date,
+): Promise<void> {
+ await send(event, properties, true, at);
+}
+
+async function send(
+ event: string,
+ properties: Properties,
+ immediate = false,
+ at?: Date,
+): Promise<void> {
+ try {
+ if (telemetryDisabled()) return;
+
+ const posted = posthog();
+ if (!posted) return;
+
+ const message = await payload(properties);
+ if (!message) return;
+
+ const full = {
+ ...message,
+ event,
+ ...(at ? { timestamp: at } : {}),
+ } as Parameters<PostHog["capture"]>[0];
+
+ if (immediate) {
+ await posted.captureImmediate(full);
+ return;
+ }
+
+ posted.capture(full);
+ } catch (error) {
+ debug(
+ `Telemetry could not capture ${event}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+}
+
+export async function flushTelemetry(): Promise<void> {
+ try {
+ await client?.flush();
+ } catch (error) {
+ debug(
+ `Telemetry could not flush: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+}
+
+export async function shutdownTelemetry(): Promise<void> {
+ try {
+ await client?._shutdown(FLUSH_TIMEOUT_MS);
+ } catch (error) {
+ debug(
+ `Telemetry could not shut down: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+}
diff --git a/packages/telemetry/src/disabled.ts b/packages/telemetry/src/disabled.ts
new file mode 100644
index 00000000..46730fe6
--- /dev/null
+++ b/packages/telemetry/src/disabled.ts
@@ -0,0 +1,15 @@
+const TRUTHY = new Set(["1", "true", "yes", "on"]);
+
+export const DISABLE_VARIABLES = ["CRM_TELEMETRY_DISABLED", "DO_NOT_TRACK"];
+
+export function telemetryDisabled(
+ env: Record<string, string | undefined> = process.env,
+): boolean {
+ if (env.NODE_ENV === "test") return true;
+
+ return DISABLE_VARIABLES.some((name) => isTruthy(env[name]));
+}
+
+function isTruthy(value: string | undefined): boolean {
+ return TRUTHY.has((value ?? "").trim().toLowerCase());
+}
diff --git a/packages/telemetry/src/events.ts b/packages/telemetry/src/events.ts
new file mode 100644
index 00000000..2fa69224
--- /dev/null
+++ b/packages/telemetry/src/events.ts
@@ -0,0 +1,79 @@
+import {
+ type Properties,
+ permittedErrorClass,
+ permittedModelId,
+ permittedRoute,
+ permittedSyncSource,
+ permittedTaskKind,
+ permittedTool,
+} from "./allowlist";
+import { capture, captureNow } from "./client";
+import { type Milestone, reachMilestone } from "./install";
+
+export const INSTALL_DAILY = "install_daily";
+
+export const AGENT_ERROR = "agent_error";
+
+export const SYNC_ERROR = "sync_error";
+
+export const API_ERROR = "api_error";
+
+export const MODEL_ERROR = "model_error";
+
+export async function installDaily(properties: Properties): Promise<void> {
+ await captureNow(INSTALL_DAILY, properties);
+}
+
+export async function milestone(step: Milestone, at?: Date): Promise<boolean> {
+ const first = await reachMilestone(step);
+ if (!first) return false;
+
+ await captureNow(step, {}, at);
+ return true;
+}
+
+export function agentError(input: {
+ error: unknown;
+ tool?: string | null;
+ taskKind?: string | null;
+ source?: "tool" | "session" | "turn";
+}): void {
+ capture(AGENT_ERROR, {
+ error_class: permittedErrorClass(input.error),
+ error_source: input.source ?? "tool",
+ tool: permittedTool(input.tool),
+ task_kind: permittedTaskKind(input.taskKind),
+ });
+}
+
+export function syncError(input: { error: unknown; source: string }): void {
+ capture(SYNC_ERROR, {
+ error_class: permittedErrorClass(input.error),
+ error_source: "google_sync",
+ sync_source: permittedSyncSource(input.source),
+ });
+}
+
+export function apiError(input: {
+ error: unknown;
+ route: string | null;
+ status: number;
+}): void {
+ capture(API_ERROR, {
+ error_class: permittedErrorClass(input.error),
+ error_source: "api",
+ route: permittedRoute(input.route),
+ status_code: input.status,
+ });
+}
+
+export function modelError(input: {
+ error: unknown;
+ modelId?: string | null;
+}): void {
+ capture(MODEL_ERROR, {
+ error_class: permittedErrorClass(input.error),
+ error_source: "model",
+ model_id: permittedModelId(input.modelId),
+ });
+}
diff --git a/packages/telemetry/src/index.ts b/packages/telemetry/src/index.ts
new file mode 100644
index 00000000..fdff4d06
--- /dev/null
+++ b/packages/telemetry/src/index.ts
@@ -0,0 +1,64 @@
+export {
+ AGENT_TOOLS,
+ ALLOWED_PROPERTIES,
+ type AllowedProperty,
+ bucket,
+ dayBucket,
+ EVE_TOOLS,
+ EVIDENCE_KINDS,
+ OTHER,
+ type Properties,
+ type PropertyValue,
+ permitted,
+ permittedErrorClass,
+ permittedEvidenceKind,
+ permittedMethod,
+ permittedModelId,
+ permittedRoute,
+ permittedSyncSource,
+ permittedTaskKind,
+ permittedTool,
+ SYNC_SOURCES,
+} from "./allowlist";
+export {
+ capture,
+ captureNow,
+ flushTelemetry,
+ onTelemetryProblem,
+ POSTHOG_HOST,
+ POSTHOG_KEY,
+ resetTelemetryClient,
+ shutdownTelemetry,
+} from "./client";
+export { DISABLE_VARIABLES, telemetryDisabled } from "./disabled";
+export {
+ AGENT_ERROR,
+ API_ERROR,
+ agentError,
+ apiError,
+ INSTALL_DAILY,
+ installDaily,
+ MODEL_ERROR,
+ milestone,
+ modelError,
+ SYNC_ERROR,
+ syncError,
+} from "./events";
+export {
+ bumpCounter,
+ COUNTERS,
+ daysSince,
+ drainCounters,
+ forgetInstall,
+ INSTALL_ID,
+ type Install,
+ MILESTONES,
+ type Milestone,
+ markRollup,
+ reachedMilestones,
+ reachMilestone,
+ readInstall,
+ sameUtcDay,
+ syncVersion,
+} from "./install";
+export { commitSha, crmVersion, UNKNOWN_VERSION } from "./version";
diff --git a/packages/telemetry/src/install.ts b/packages/telemetry/src/install.ts
new file mode 100644
index 00000000..f1bfb166
--- /dev/null
+++ b/packages/telemetry/src/install.ts
@@ -0,0 +1,163 @@
+import "@crm/env/load";
+
+import { db } from "@crm/db";
+import { crmVersion } from "./version";
+
+export const INSTALL_ID = "install";
+
+export type Install = {
+ uuid: string;
+ version: string;
+ createdAt: Date;
+ lastRollupAt: Date | null;
+};
+
+const SELECT = {
+ uuid: true,
+ version: true,
+ createdAt: true,
+ lastRollupAt: true,
+} as const;
+
+let cached: Install | null = null;
+
+export async function readInstall(): Promise<Install | null> {
+ if (cached) return cached;
+
+ try {
+ const row = await db.install.findUnique({
+ where: { id: INSTALL_ID },
+ select: SELECT,
+ });
+
+ if (row) cached = row;
+ return row;
+ } catch {
+ return null;
+ }
+}
+
+export function forgetInstall(): void {
+ cached = null;
+}
+
+export async function syncVersion(
+ version = crmVersion(),
+): Promise<Install | null> {
+ if (!version) return readInstall();
+
+ try {
+ const row = await db.install.update({
+ where: { id: INSTALL_ID },
+ data: { version },
+ select: SELECT,
+ });
+
+ cached = row;
+ return row;
+ } catch {
+ return readInstall();
+ }
+}
+
+export const MILESTONES = [
+ "migrations_applied",
+ "first_sign_in",
+ "google_oauth_configured",
+ "first_mailbox_sync",
+ "first_non_seed_contact",
+ "first_agent_task_claimed",
+ "first_agent_task_completed",
+ "first_fact_applied",
+] as const;
+
+export type Milestone = (typeof MILESTONES)[number];
+
+export async function reachMilestone(step: Milestone): Promise<boolean> {
+ try {
+ const { count } = await db.telemetryMilestone.createMany({
+ data: [{ step }],
+ skipDuplicates: true,
+ });
+
+ return count === 1;
+ } catch {
+ return false;
+ }
+}
+
+export async function reachedMilestones(): Promise<Milestone[]> {
+ try {
+ const rows = await db.telemetryMilestone.findMany({
+ select: { step: true },
+ });
+
+ const reached = new Set(rows.map((row) => row.step));
+ return MILESTONES.filter((step) => reached.has(step));
+ } catch {
+ return [];
+ }
+}
+
+export const COUNTERS = {
+ budgetExhausted: "budget_exhausted",
+} as const;
+
+export async function bumpCounter(name: string, by = 1): Promise<void> {
+ try {
+ await db.telemetryCounter.upsert({
+ where: { name },
+ create: { name, count: by },
+ update: { count: { increment: by } },
+ });
+ } catch {
+ try {
+ await db.telemetryCounter.update({
+ where: { name },
+ data: { count: { increment: by } },
+ });
+ } catch {}
+ }
+}
+
+export async function drainCounters(): Promise<Record<string, number>> {
+ try {
+ const rows = await db.$queryRaw<{ name: string; count: number }[]>`
+ DELETE FROM "telemetryCounter"
+ WHERE "count" > 0
+ RETURNING "name", "count";
+ `;
+
+ return Object.fromEntries(rows.map((row) => [row.name, row.count]));
+ } catch {
+ return {};
+ }
+}
+
+export async function markRollup(at: Date): Promise<void> {
+ try {
+ const row = await db.install.update({
+ where: { id: INSTALL_ID },
+ data: { lastRollupAt: at },
+ select: SELECT,
+ });
+
+ cached = row;
+ } catch {}
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+export function daysSince(from: Date, now = new Date()): number {
+ return Math.max(0, Math.floor((now.getTime() - from.getTime()) / DAY_MS));
+}
+
+export function sameUtcDay(a: Date | null, b: Date): boolean {
+ if (!a) return false;
+
+ return (
+ a.getUTCFullYear() === b.getUTCFullYear() &&
+ a.getUTCMonth() === b.getUTCMonth() &&
+ a.getUTCDate() === b.getUTCDate()
+ );
+}
diff --git a/packages/telemetry/src/version.ts b/packages/telemetry/src/version.ts
new file mode 100644
index 00000000..0c0269fb
--- /dev/null
+++ b/packages/telemetry/src/version.ts
@@ -0,0 +1,41 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { findWorkspaceRoot } from "@crm/env";
+
+export const UNKNOWN_VERSION = "unknown";
+
+export function crmVersion(from = process.cwd()): string | null {
+ const root = findWorkspaceRoot(from);
+ if (!root) return null;
+
+ try {
+ const parsed: unknown = JSON.parse(
+ readFileSync(join(root, "package.json"), "utf8"),
+ );
+
+ if (typeof parsed !== "object" || parsed === null) return null;
+ if (!("version" in parsed)) return null;
+
+ const version = parsed.version;
+ return typeof version === "string" && version.trim()
+ ? version.trim()
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+export function commitSha(): string | null {
+ const candidates = [
+ process.env.VERCEL_GIT_COMMIT_SHA,
+ process.env.GIT_COMMIT_SHA,
+ process.env.GITHUB_SHA,
+ ];
+
+ for (const candidate of candidates) {
+ const sha = candidate?.trim();
+ if (sha && /^[0-9a-f]{7,40}$/i.test(sha)) return sha;
+ }
+
+ return null;
+}
diff --git a/packages/telemetry/test/allowlist.spec.ts b/packages/telemetry/test/allowlist.spec.ts
new file mode 100644
index 00000000..e5494eac
--- /dev/null
+++ b/packages/telemetry/test/allowlist.spec.ts
@@ -0,0 +1,202 @@
+import { describe, expect, it } from "bun:test";
+import { readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { TASK_KINDS } from "@crm/db/agent-tasks";
+import {
+ AGENT_TOOLS,
+ ALLOWED_PROPERTIES,
+ bucket,
+ dayBucket,
+ EVIDENCE_KINDS,
+ OTHER,
+ permitted,
+ permittedErrorClass,
+ permittedEvidenceKind,
+ permittedMethod,
+ permittedModelId,
+ permittedRoute,
+ permittedTaskKind,
+ permittedTool,
+} from "../src/allowlist";
+
+const REPO = join(import.meta.dir, "..", "..", "..");
+
+describe("permitted", () => {
+ it("keeps a property on the list", () => {
+ expect(permitted({ crm_version: "1.0.0" })).toEqual({
+ crm_version: "1.0.0",
+ });
+ });
+
+ it("drops a property that is not on the list", () => {
+ expect(
+ permitted({
+ crm_version: "1.0.0",
+ contact_email: "[email protected]",
+ company_name: "Acme",
+ }),
+ ).toEqual({ crm_version: "1.0.0" });
+ });
+
+ it("drops everything when nothing is on the list", () => {
+ expect(
+ permitted({ email: "[email protected]", note: "called them" }),
+ ).toEqual({});
+ });
+
+ it("drops undefined rather than sending a null it did not mean", () => {
+ expect(permitted({ crm_version: undefined })).toEqual({});
+ });
+
+ it("keeps a deliberate null", () => {
+ expect(permitted({ postgres_version: null })).toEqual({
+ postgres_version: null,
+ });
+ });
+
+ it("names every property exactly once", () => {
+ expect(new Set(ALLOWED_PROPERTIES).size).toBe(ALLOWED_PROPERTIES.length);
+ });
+});
+
+describe("permittedTool", () => {
+ it("keeps an authored tool", () => {
+ expect(permittedTool("read_crm_history")).toBe("read_crm_history");
+ });
+
+ it("keeps an eve builtin", () => {
+ expect(permittedTool("web_search")).toBe("web_search");
+ });
+
+ it("buckets anything it does not know", () => {
+ expect(permittedTool("[email protected]")).toBe(OTHER);
+ expect(permittedTool(null)).toBe(OTHER);
+ });
+
+ it("lists every tool in apps/agent/agent/tools", () => {
+ const files = readdirSync(join(REPO, "apps", "agent", "agent", "tools"))
+ .filter((name) => name.endsWith(".ts"))
+ .map((name) => name.replace(/\.ts$/, ""));
+
+ expect([...AGENT_TOOLS].sort()).toEqual(files.sort());
+ });
+});
+
+describe("permittedEvidenceKind", () => {
+ it("keeps a kind the agent prices", () => {
+ expect(permittedEvidenceKind("crm.signature-block")).toBe(
+ "crm.signature-block",
+ );
+ });
+
+ it("buckets anything else", () => {
+ expect(permittedEvidenceKind("[email protected]")).toBe(OTHER);
+ });
+
+ it("mirrors the WEIGHTS map in lib/evidence.ts", () => {
+ const source = readFileSync(
+ join(REPO, "apps", "agent", "agent", "lib", "evidence.ts"),
+ "utf8",
+ );
+
+ const start = source.indexOf("export const WEIGHTS");
+ const block = source.slice(start, source.indexOf("\n};", start));
+
+ const kinds = [...block.matchAll(/^\t"?([a-z][a-z0-9.-]*)"?:\s*\{/gm)].map(
+ (match) => match[1] as string,
+ );
+
+ expect(kinds.length).toBeGreaterThan(0);
+ expect([...EVIDENCE_KINDS].sort()).toEqual(kinds.sort());
+ });
+});
+
+describe("permittedMethod", () => {
+ it("keeps a slug a tool wrote", () => {
+ expect(permittedMethod("linkedin.profile")).toBe("linkedin.profile");
+ expect(permittedMethod("crm.thread")).toBe("crm.thread");
+ });
+
+ it("buckets anything that could carry a person", () => {
+ expect(permittedMethod("[email protected]")).toBe(OTHER);
+ expect(permittedMethod("Ada Okafor, VP Sales at Acme")).toBe(OTHER);
+ expect(permittedMethod("https://example.test/ada")).toBe(OTHER);
+ expect(permittedMethod("a".repeat(80))).toBe(OTHER);
+ expect(permittedMethod(null)).toBe(OTHER);
+ });
+});
+
+describe("permittedTaskKind", () => {
+ it("keeps every kind the dispatcher knows", () => {
+ for (const kind of TASK_KINDS) {
+ expect(permittedTaskKind(kind)).toBe(kind);
+ }
+ });
+
+ it("buckets anything else", () => {
+ expect(permittedTaskKind("contact:[email protected]")).toBe(OTHER);
+ });
+});
+
+describe("permittedRoute", () => {
+ it("keeps a route pattern", () => {
+ expect(permittedRoute("/internal/sync/google")).toBe(
+ "/internal/sync/google",
+ );
+ expect(permittedRoute("/trpc/contacts.list")).toBe("/trpc/contacts.list");
+ expect(permittedRoute("/contacts/:id")).toBe("/contacts/:id");
+ });
+
+ it("buckets a URL with an address in the query string", () => {
+ expect(permittedRoute("/[email protected]")).toBe(OTHER);
+ expect(permittedRoute("https://crm.example.test/contacts")).toBe(OTHER);
+ expect(permittedRoute(null)).toBe(OTHER);
+ });
+});
+
+describe("permittedErrorClass", () => {
+ it("takes the class, never the message", () => {
+ expect(
+ permittedErrorClass(new TypeError("[email protected] is not a fn")),
+ ).toBe("TypeError");
+ });
+
+ it("takes an eve error code", () => {
+ expect(permittedErrorClass({ code: "model_overloaded" })).toBe(
+ "model_overloaded",
+ );
+ });
+
+ it("buckets a free-text string", () => {
+ expect(permittedErrorClass("could not reach [email protected]")).toBe(OTHER);
+ expect(permittedErrorClass({})).toBe(OTHER);
+ });
+});
+
+describe("permittedModelId", () => {
+ it("keeps a model slug", () => {
+ expect(permittedModelId("zai/glm-5.2-fast")).toBe("zai/glm-5.2-fast");
+ });
+
+ it("buckets anything else", () => {
+ expect(permittedModelId("the model said hello to ada")).toBe(OTHER);
+ });
+});
+
+describe("buckets", () => {
+ it("never reports an exact size", () => {
+ expect(bucket(0)).toBe("0");
+ expect(bucket(1)).toBe("1-9");
+ expect(bucket(9)).toBe("1-9");
+ expect(bucket(10)).toBe("10-49");
+ expect(bucket(4_999)).toBe("1000-4999");
+ expect(bucket(1_000_000)).toBe("25000+");
+ });
+
+ it("bands recheck intervals by day", () => {
+ expect(dayBucket(0)).toBe("0-1");
+ expect(dayBucket(7)).toBe("2-7");
+ expect(dayBucket(30)).toBe("8-30");
+ expect(dayBucket(365)).toBe("180+");
+ });
+});
diff --git a/packages/telemetry/test/client.integration.spec.ts b/packages/telemetry/test/client.integration.spec.ts
new file mode 100644
index 00000000..36ea7a03
--- /dev/null
+++ b/packages/telemetry/test/client.integration.spec.ts
@@ -0,0 +1,163 @@
+import { afterEach, beforeEach, describe, expect, it } from "bun:test";
+import { captureNow, POSTHOG_HOST, resetTelemetryClient } from "../src/client";
+import { forgetInstall, readInstall } from "../src/install";
+
+const real = {
+ fetch: globalThis.fetch,
+ nodeEnv: process.env.NODE_ENV,
+ disabled: process.env.CRM_TELEMETRY_DISABLED,
+ doNotTrack: process.env.DO_NOT_TRACK,
+};
+
+let calls: { url: string; body: unknown }[] = [];
+
+function stubFetch(): void {
+ calls = [];
+
+ globalThis.fetch = (async (input: unknown, init?: { body?: unknown }) => {
+ calls.push({ url: String(input), body: await decode(init?.body) });
+
+ return new Response(JSON.stringify({ status: 1 }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch;
+}
+
+async function decode(body: unknown): Promise<unknown> {
+ if (body === undefined || body === null) return null;
+ if (typeof body === "string") return JSON.parse(body);
+
+ const bytes =
+ body instanceof Blob
+ ? new Uint8Array(await body.arrayBuffer())
+ : new Uint8Array(body as ArrayBufferLike);
+
+ const text = new TextDecoder().decode(Bun.gunzipSync(bytes));
+ return JSON.parse(text);
+}
+
+beforeEach(() => {
+ stubFetch();
+ resetTelemetryClient();
+ forgetInstall();
+
+ process.env.NODE_ENV = "development";
+ delete process.env.CRM_TELEMETRY_DISABLED;
+ delete process.env.DO_NOT_TRACK;
+});
+
+afterEach(() => {
+ globalThis.fetch = real.fetch;
+ resetTelemetryClient();
+ forgetInstall();
+
+ restore("NODE_ENV", real.nodeEnv);
+ restore("CRM_TELEMETRY_DISABLED", real.disabled);
+ restore("DO_NOT_TRACK", real.doNotTrack);
+});
+
+function restore(name: string, value: string | undefined): void {
+ if (value === undefined) {
+ delete process.env[name];
+ return;
+ }
+
+ process.env[name] = value;
+}
+
+describe("capture", () => {
+ it("sends one event with the install UUID as the only identity", async () => {
+ const install = await readInstall();
+ expect(install).not.toBeNull();
+
+ await captureNow("install_daily", { crm_version: "1.0.0" });
+
+ expect(calls.length).toBe(1);
+ expect(calls[0]?.url.startsWith(POSTHOG_HOST)).toBe(true);
+
+ const event = eventOf(calls[0]?.body);
+
+ expect(event.distinct_id).toBe(install?.uuid);
+ expect(event.event).toBe("install_daily");
+ expect(JSON.stringify(event)).not.toContain("identify");
+ });
+
+ it("drops a property that is not on the allowlist", async () => {
+ await captureNow("install_daily", {
+ crm_version: "1.0.0",
+ contact_email: "[email protected]",
+ company_name: "Acme",
+ } as never);
+
+ const { properties } = eventOf(calls[0]?.body);
+
+ expect(properties.crm_version).toBe("1.0.0");
+ expect(properties).not.toHaveProperty("contact_email");
+ expect(properties).not.toHaveProperty("company_name");
+ expect(JSON.stringify(calls)).not.toContain("[email protected]");
+ });
+
+ it("sends a null IP and no geoip on every event", async () => {
+ await captureNow("install_daily", { crm_version: "1.0.0" });
+
+ const { properties } = eventOf(calls[0]?.body);
+
+ expect(properties.$ip).toBeNull();
+ expect(properties.$geoip_disable ?? true).toBeTruthy();
+ });
+
+ it("makes no network call at all when CRM_TELEMETRY_DISABLED is set", async () => {
+ process.env.CRM_TELEMETRY_DISABLED = "1";
+ resetTelemetryClient();
+
+ await captureNow("install_daily", { crm_version: "1.0.0" });
+
+ expect(calls.length).toBe(0);
+ });
+
+ it("makes no network call at all when DO_NOT_TRACK is set", async () => {
+ process.env.DO_NOT_TRACK = "1";
+ resetTelemetryClient();
+
+ await captureNow("install_daily", { crm_version: "1.0.0" });
+
+ expect(calls.length).toBe(0);
+ });
+
+ it("makes no network call at all from a test run", async () => {
+ process.env.NODE_ENV = "test";
+ resetTelemetryClient();
+
+ await captureNow("install_daily", { crm_version: "1.0.0" });
+
+ expect(calls.length).toBe(0);
+ });
+
+ it("stays silent when the host refuses the send", async () => {
+ globalThis.fetch = (async () => {
+ throw new Error("network is down");
+ }) as typeof fetch;
+
+ expect(
+ captureNow("install_daily", { crm_version: "1.0.0" }),
+ ).resolves.toBeUndefined();
+ });
+});
+
+type Captured = {
+ event: string;
+ distinct_id: string;
+ properties: Record<string, unknown>;
+};
+
+function eventOf(body: unknown): Captured {
+ const batch = (body as { batch?: Captured[] })?.batch;
+ const event = batch?.[0] ?? (body as Captured);
+
+ return {
+ event: event?.event,
+ distinct_id: event?.distinct_id,
+ properties: event?.properties ?? {},
+ };
+}
diff --git a/packages/telemetry/test/disabled.spec.ts b/packages/telemetry/test/disabled.spec.ts
new file mode 100644
index 00000000..78f682d5
--- /dev/null
+++ b/packages/telemetry/test/disabled.spec.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "bun:test";
+import { DISABLE_VARIABLES, telemetryDisabled } from "../src/disabled";
+
+describe("telemetryDisabled", () => {
+ it("is off by default", () => {
+ expect(telemetryDisabled({})).toBe(false);
+ });
+
+ it("sends nothing from a test run, whatever else is set", () => {
+ expect(telemetryDisabled({ NODE_ENV: "test" })).toBe(true);
+ });
+
+ it("honours CRM_TELEMETRY_DISABLED", () => {
+ expect(telemetryDisabled({ CRM_TELEMETRY_DISABLED: "1" })).toBe(true);
+ });
+
+ it("honours DO_NOT_TRACK", () => {
+ expect(telemetryDisabled({ DO_NOT_TRACK: "1" })).toBe(true);
+ });
+
+ it("takes any of the obvious ways to say yes", () => {
+ for (const value of ["1", "true", "TRUE", " yes ", "on"]) {
+ expect(telemetryDisabled({ DO_NOT_TRACK: value })).toBe(true);
+ }
+ });
+
+ it("does not read an empty or negative value as a yes", () => {
+ for (const value of ["", " ", "0", "false", "no"]) {
+ expect(telemetryDisabled({ CRM_TELEMETRY_DISABLED: value })).toBe(false);
+ }
+ });
+
+ it("names both variables so the docs and the code cannot drift", () => {
+ expect(DISABLE_VARIABLES).toEqual([
+ "CRM_TELEMETRY_DISABLED",
+ "DO_NOT_TRACK",
+ ]);
+ });
+});
diff --git a/packages/telemetry/test/install.integration.spec.ts b/packages/telemetry/test/install.integration.spec.ts
new file mode 100644
index 00000000..2c1bffa2
--- /dev/null
+++ b/packages/telemetry/test/install.integration.spec.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from "bun:test";
+import { join } from "node:path";
+import { db } from "@crm/db";
+import {
+ bumpCounter,
+ drainCounters,
+ INSTALL_ID,
+ reachMilestone,
+ readInstall,
+ syncVersion,
+} from "../src/install";
+
+const PACKAGE = join(import.meta.dir, "..");
+
+const PRINT_UUID = [
+ 'import { db } from "@crm/db";',
+ 'import { readInstall } from "./src/install";',
+ "const install = await readInstall();",
+ 'process.stdout.write(install?.uuid ?? "none");',
+ "await db.$disconnect();",
+ "process.exit(0);",
+].join(" ");
+
+const SPAWN_TIMEOUT_MS = 20_000;
+
+async function uuidFromNewProcess(): Promise<string> {
+ const process = Bun.spawn(["bun", "-e", PRINT_UUID], {
+ cwd: PACKAGE,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ const [output] = await Promise.all([
+ new Response(process.stdout).text(),
+ process.exited,
+ ]);
+
+ return output.trim();
+}
+
+describe("the install row", () => {
+ it("is a single row the migration already wrote", async () => {
+ const rows = await db.install.findMany({ select: { id: true } });
+
+ expect(rows).toEqual([{ id: INSTALL_ID }]);
+ });
+
+ it(
+ "hands back the same UUID to two separate processes",
+ async () => {
+ const [first, second] = await Promise.all([
+ uuidFromNewProcess(),
+ uuidFromNewProcess(),
+ ]);
+
+ expect(first).not.toBe("none");
+ expect(first).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
+ );
+ expect(second).toBe(first);
+ expect((await readInstall())?.uuid).toBe(first);
+ },
+ SPAWN_TIMEOUT_MS,
+ );
+
+ it("keeps the UUID when a boot writes a new version", async () => {
+ const before = await readInstall();
+
+ const updated = await syncVersion("9.9.9-test");
+ expect(updated?.version).toBe("9.9.9-test");
+ expect(updated?.uuid).toBe(before?.uuid as string);
+
+ await syncVersion(before?.version ?? "unknown");
+ });
+});
+
+describe("milestones", () => {
+ const step = "first_fact_applied" as const;
+
+ it("reports the first arrival and nothing after it", async () => {
+ await db.telemetryMilestone.deleteMany({ where: { step } });
+
+ expect(await reachMilestone(step)).toBe(true);
+ expect(await reachMilestone(step)).toBe(false);
+ expect(await reachMilestone(step)).toBe(false);
+
+ await db.telemetryMilestone.deleteMany({ where: { step } });
+ });
+});
+
+describe("counters", () => {
+ const name = "budget_exhausted";
+
+ it("adds up and then drains to nothing", async () => {
+ await db.telemetryCounter.deleteMany({ where: { name } });
+
+ await bumpCounter(name);
+ await bumpCounter(name);
+ await bumpCounter(name, 3);
+
+ const drained = await drainCounters();
+ expect(drained[name]).toBe(5);
+
+ expect(await drainCounters()).toEqual({});
+ });
+});
diff --git a/packages/telemetry/tsconfig.json b/packages/telemetry/tsconfig.json
new file mode 100644
index 00000000..709a6038
--- /dev/null
+++ b/packages/telemetry/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "@crm/typescript-config/internal-package.json",
+ "compilerOptions": {
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["node_modules"]
+}
diff --git a/skills-lock.json b/skills-lock.json
index b617311f..50f2fe32 100644
--- a/skills-lock.json
+++ b/skills-lock.json
@@ -37,6 +37,12 @@
"skillPath": "skills/.curated/nuqs/SKILL.md",
"computedHash": "5811f3b4c6f981aa75647ffb879d6e98429535ff830df219a04f4c9a884658a6"
},
+ "posthog-instrumentation": {
+ "source": "posthog/posthog-for-claude",
+ "sourceType": "github",
+ "skillPath": "skills/posthog-instrumentation/SKILL.md",
+ "computedHash": "a9a30a63accd756ef41009f987ac75812ab1e855b30ea5d6153e0fed16ebf22d"
+ },
"prisma-database-setup": {
"source": "prisma/skills",
"sourceType": "github",
diff --git a/turbo.json b/turbo.json
index c00c1eb9..9f3884ee 100644
--- a/turbo.json
+++ b/turbo.json
@@ -41,7 +41,11 @@
"AI_GATEWAY_API_KEY",
"VERCEL_OIDC_TOKEN",
"AGENT_URL",
- "AGENT_BRIDGE_SECRET"
+ "AGENT_BRIDGE_SECRET",
+ "CRM_TELEMETRY_DISABLED",
+ "DO_NOT_TRACK",
+ "VERCEL",
+ "VERCEL_GIT_COMMIT_SHA"
],
"tasks": {