Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat(telemetry): anonymous adoption telemetry, opt-out and allowlisted (#179)

anirudhkumar-nanonets65a76e5edd40
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a4178115..89062b5b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,29 @@
# Changelog
+## 0.12.0
+
+### Changed
+
+- **graft now collects anonymous usage stats, and the README no longer says it
+ doesn't.** We had no way to tell whether a repo ever got past `graft build`,
+ or whether an agent reaches for graft over grep once it has — npm downloads
+ answer neither. Six events, all buckets and fixed enums: `first_run`,
+ `init_completed`, `build_completed`, `build_failed`, `query`,
+ `session_summary`. Never your code, file paths, repo name, symbols, queries,
+ prompts, or error messages — [`TELEMETRY.md`](TELEMETRY.md) is the complete
+ contract and `src/telemetry/contract.ts` enforces it as a hard allowlist, so
+ a property that is not in the document cannot be sent even by accident.
+
+ Identity is two random UUIDs (one per machine, one per checkout), derived from
+ nothing; events are anonymous in PostHog with no person profile. Nothing is
+ sent from a command you run — events queue locally and a detached process
+ posts them at most once a day, so no query ever waits on the network.
+
+ Off if you uncheck the box in `graft init`, run `graft telemetry disable`, set
+ `DO_NOT_TRACK`, are in CI, or built from source (the key is stamped in only at
+ publish time, so forks never send). `graft telemetry debug` prints the exact
+ batch your machine would send, and sends nothing.
+
## 0.11.0
### Fixed
diff --git a/README.md b/README.md
index 9b985c5b..b326f57a 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
<a href="https://nodejs.org"><img src="https://img.shields.io/node/v/%40nanonets%2Fgraft?style=for-the-badge&logo=nodedotjs&logoColor=white" /></a>
<img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=for-the-badge&logo=typescript&logoColor=white" />
<img src="https://img.shields.io/badge/License-MIT-20C997?style=for-the-badge" />
- <img src="https://img.shields.io/badge/telemetry-none-546FFF?style=for-the-badge" />
+ <a href="TELEMETRY.md"><img src="https://img.shields.io/badge/telemetry-anonymous%2C%20opt--out-546FFF?style=for-the-badge" /></a>
<a href="https://scorecard.dev/viewer/?uri=github.com/NanoNets/Graft"><img src="https://img.shields.io/ossf-scorecard/github.com/NanoNets/Graft?style=for-the-badge&label=openssf%20scorecard" /></a>
</p>
@@ -237,7 +237,7 @@ _Summary, sources, links, and notes ship today in markdown nodes. The crux ships
- **On your machine, no key, no network:** the structural code graph. `graft build` (wiring graph + per-file cards), `graft check`, and `graft ask` are deterministic tree-sitter — they never call a model.
- **Through your provider key:** the LLM-written parts — `graft build --deep` adds the concept nodes (file summaries + node synthesis) and the per-symbol summaries and cruxes. graft is vendor-neutral: set `GRAFT_PROVIDER` (`openai` for any OpenAI-compatible endpoint, or `anthropic` for the native API), your `GRAFT_API_KEY`, `GRAFT_MODEL`, and — for the `openai` wire format — `GRAFT_BASE_URL` to point at OpenRouter, Fireworks, Groq, a LiteLLM proxy, a local server, or OpenAI itself. Or pass `--provider/--model/--api-key/--base-url` on the command line. (`OPENROUTER_API_KEY` still works as a deprecated fallback.)
-- **No telemetry** and no analytics — the only network calls are the LLM requests you configured.
+- **Anonymous usage stats** — the only network calls are the LLM requests you configured, a daily npm version check, and one batched usage ping. The ping carries buckets and fixed labels only: never your code, file paths, repo name, symbols, queries, or error messages. [`TELEMETRY.md`](TELEMETRY.md) is the complete list and `graft telemetry debug` prints exactly what your machine would send. Turn it off with `graft telemetry disable`, `DO_NOT_TRACK=1`, or by unchecking the box in `graft init`; it is off in CI and in any build from source.
See [`.env.example`](.env.example) for the full list of settings (model, base URL, graph directory).
diff --git a/TELEMETRY.md b/TELEMETRY.md
new file mode 100644
index 00000000..4ca0c8d3
--- /dev/null
+++ b/TELEMETRY.md
@@ -0,0 +1,122 @@
+# Telemetry
+
+graft collects a small set of **anonymous** usage events so we can tell whether
+the thing works: how many repos get past a build, whether an agent reaches for
+graft or falls back to grep, which commands earn their place, and what breaks in
+the wild.
+
+This document is the complete, authoritative contract: **if an event or property
+is not listed here, graft does not send it.** The implementation lives in
+[`src/telemetry/contract.ts`](src/telemetry/contract.ts) and enforces this list
+as a hard allowlist — unknown events and unknown properties are dropped before
+anything is written, let alone sent. The code and this file are kept in
+lockstep, and because the repo is open source you can verify that yourself.
+
+Nothing is ever sent from a command you run. Events are appended to a local file
+and a detached background process posts them at most once a day, so no `graft
+ask` ever waits on the network.
+
+## What is sent
+
+Every event carries only these common properties:
+
+| Property | Example | Notes |
+| --- | --- | --- |
+| `app_version` | `0.12.0` | The graft version that produced the event |
+| `os` | `darwin` / `win32` / `linux` | Platform, nothing more |
+| `arch` | `arm64` / `x64` | CPU architecture |
+| `node_major` | `20` | Major version only |
+| `ci` | `false` | Always false — CI never sends (see below) |
+| `agent_host` | `claude-code` / `cursor` / `mcp` / `cli` | Which surface graft ran under |
+| `repo_id` | a random UUID | See "How it stays anonymous" |
+
+The events:
+
+| Event | Extra properties | When |
+| --- | --- | --- |
+| `first_run` | — | Once, the first time graft runs on a machine |
+| `init_completed` | `agents` (the ids you selected, sorted), `consent` | `graft init` finishes |
+| `build_completed` | `files_bucket`, `langs`, `mode` (`fast`/`deep`), `duration_bucket`, `incremental` | A build succeeds |
+| `build_failed` | `stage`, `code` — both fixed enums | A build throws |
+| `query` | `command`, `surface` (`cli`/`mcp`/`hook`), `hit` (`ask` only) | Any query command |
+| `session_summary` | `graft_reads_bucket`, `source_reads_bucket`, `saved_tokens_bucket` | Once, after an agent session ends |
+
+Two rules govern every value above, and both are enforced in code rather than by
+review:
+
+- **Every number is a bucket.** A build reports `"200-999"` files, never `417`.
+ An exact count next to a language set starts to fingerprint a specific repo; a
+ bucket does not.
+- **Every string is a member of a fixed set.** `command` is one of eight known
+ subcommands, `code` is one of eleven known failure codes. A value outside the
+ set is dropped, not sent — which is what stops a path, a symbol name, or a
+ snippet of an error message from riding along inside a "string property".
+
+An example event, in full:
+
+```json
+{
+ "event": "build_completed",
+ "timestamp": "2026-08-21T09:14:22.417Z",
+ "properties": {
+ "app_version": "0.12.0", "os": "darwin", "arch": "arm64",
+ "node_major": "20", "ci": "false", "agent_host": "claude-code",
+ "repo_id": "6f2c1e90-...", "distinct_id": "b1f3a9c2-...",
+ "files_bucket": "200-999", "langs": "go,ts", "mode": "deep",
+ "duration_bucket": "30s-2m", "incremental": "true",
+ "$process_person_profile": false
+ }
+}
+```
+
+Run `graft telemetry debug` to print the exact batch your machine would send. It
+sends nothing.
+
+## What is never sent
+
+No source code. No file paths, repo names, organisation names, git remotes, or
+branch names. No symbol names, node summaries, or anything out of the graph. No
+query strings, prompts, or agent output. No error messages or stack traces — a
+failure contributes a code from a fixed list and nothing else. No environment
+variables, API keys, model names, hostnames, usernames, or email addresses.
+
+## How it stays anonymous
+
+- Events go to [PostHog](https://posthog.com) with
+ `$process_person_profile: false`, which makes them **anonymous events**: no
+ person profile is created and no identity is stored.
+- The only identifiers are two **random UUIDs**. `install_id` is minted on first
+ run in `~/.graft/telemetry.json`; `repo_id` is minted per checkout in
+ `graft/.cache/`. Neither is derived from your machine, your account, or your
+ git remote — they are coin flips, written down. A hash of your remote URL
+ would at least be something we could guess at and confirm; a random UUID is
+ not. Delete `~/.graft/` or `graft/` and you look like someone new.
+- IP-based geolocation is used only to derive a country for aggregate stats;
+ PostHog does not retain the IP on the event.
+
+## Opting out
+
+Any one of these fully disables telemetry:
+
+1. **Uncheck "anonymous usage stats" in the `graft init` picker.** Takes effect
+ immediately and is remembered for this machine.
+2. **`graft telemetry disable`** at any time. `graft telemetry status` shows the
+ current state, and `graft telemetry enable` turns it back on.
+3. **Set [`DO_NOT_TRACK`](https://consoledonottrack.com)** to any value other
+ than `0`. Respected unconditionally — it outranks graft's own setting.
+4. **Run in CI.** `CI`, `GITHUB_ACTIONS`, `GITLAB_CI` and friends switch it off
+ without being asked. A build server is not a user.
+5. **Build from source.** The PostHog key is stamped in only at publish time
+ (`scripts/stamp-telemetry-key.mjs`); a clone, a fork, or a local
+ `npm run build` compiles with an empty key and the telemetry module is inert.
+ Forks never send events anywhere.
+
+## Where the events go
+
+Official builds send to `https://events.nanonets.com`, Nanonets' own PostHog
+front door, so graft's numbers sit in the same project as the rest of the
+product rather than in a separate one. The client posts a single batch to
+`/batch/`.
+
+The host is a publish-time setting (`GRAFT_POSTHOG_HOST`) and PostHog itself is
+open source and self-hostable, so the endpoint can move without any code change.
diff --git a/package.json b/package.json
index 9ba56777..eddc8acf 100644
--- a/package.json
+++ b/package.json
@@ -48,7 +48,7 @@
"cli": "tsx src/cli.ts",
"test": "node scripts/run-tests.mjs",
"prepare": "npm run build",
- "prepublishOnly": "npm run build",
+ "prepublishOnly": "npm run build && node scripts/stamp-telemetry-key.mjs",
"postinstall": "node scripts/postinstall.mjs"
},
"engines": {
diff --git a/scripts/stamp-telemetry-key.mjs b/scripts/stamp-telemetry-key.mjs
new file mode 100644
index 00000000..12c80557
--- /dev/null
+++ b/scripts/stamp-telemetry-key.mjs
@@ -0,0 +1,53 @@
+/**
+ * Bakes the PostHog key into the built `dist/telemetry/key.js` at publish time.
+ *
+ * This is what makes "forks never send" true by construction rather than by
+ * policy. The key exists only in the published tarball: the repository holds an
+ * empty string, so a clone, a fork, a CI build, and a contributor's local
+ * `npm run build` all produce a graft whose telemetry module short-circuits on
+ * the very first check.
+ *
+ * Runs from `prepublishOnly`, after `npm run build`. Without GRAFT_POSTHOG_KEY
+ * in the environment it prints a warning and changes nothing — publishing a
+ * telemetry-less build is a valid thing to do, and it must never be a hard
+ * failure at the moment someone is trying to ship.
+ */
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const target = join(root, 'dist', 'telemetry', 'key.js');
+
+const key = process.env.GRAFT_POSTHOG_KEY ?? '';
+const host = process.env.GRAFT_POSTHOG_HOST ?? '';
+
+if (!key) {
+ console.warn('⚠ GRAFT_POSTHOG_KEY not set — publishing a build that sends no telemetry.');
+ process.exit(0);
+}
+if (!existsSync(target)) {
+ console.warn(`⚠ ${target} not found — did the build run? Skipping the telemetry key stamp.`);
+ process.exit(0);
+}
+// A key with a quote or a newline in it would break the generated literal (and
+// is not a PostHog key). Refuse rather than emit something that won't parse.
+if (!/^[A-Za-z0-9_-]+$/.test(key)) {
+ console.error('✗ GRAFT_POSTHOG_KEY contains characters that are not valid in a project key.');
+ process.exit(1);
+}
+if (host && !/^https:\/\/[A-Za-z0-9.-]+(:\d+)?$/.test(host)) {
+ console.error('✗ GRAFT_POSTHOG_HOST must be a plain https origin, e.g. https://eu.i.posthog.com');
+ process.exit(1);
+}
+
+const src = readFileSync(target, 'utf8');
+let out = src.replace(/const BAKED_KEY = ['"][^'"]*['"];/, `const BAKED_KEY = '${key}';`);
+if (host) out = out.replace(/const BAKED_HOST = ['"][^'"]*['"];/, `const BAKED_HOST = '${host}';`);
+
+if (out === src) {
+ console.error('✗ could not find BAKED_KEY in dist/telemetry/key.js — the stamp target moved.');
+ process.exit(1);
+}
+writeFileSync(target, out);
+console.log(`✓ telemetry key stamped into dist/telemetry/key.js${host ? ` (host ${host})` : ''}`);
diff --git a/src/claude/hooks.ts b/src/claude/hooks.ts
index 6e056b9c..00381a72 100644
--- a/src/claude/hooks.ts
+++ b/src/claude/hooks.ts
@@ -8,6 +8,7 @@ import { patchStats, readStats, acquireLock, readSession, writeSession } from '.
import { graftCliPath, claudeScriptPath } from './paths.js';
import { runUpkeep } from '../upkeep-run.js';
import { runningVersion } from '../upkeep.js';
+import { flushClosedSessions } from '../telemetry/sessions.js';
import { scopeOf, scopesOfGraph } from '../graph/scopes.js';
/** Prompts shorter than this never trigger retrieval — they are almost always
@@ -223,6 +224,9 @@ export async function main(event: string): Promise<void> {
// background:false — a hook must never touch the network; the CLI and the MCP
// server fill that cache, this only reads it.
const upkeep = runUpkeep(dir, runningVersion(), { background: false }).lines;
+ // Roll up any session that ended since we were last here. Queue-only — the
+ // hook still touches no network; the CLI or the MCP server sends it later.
+ flushClosedSessions(dir);
try {
const idx = readFileSync(join(dir, 'graft', 'INDEX.md'), 'utf8');
const banner = staleBanner(indexFreshness(dir)) ?? undefined;
diff --git a/src/claude/state.ts b/src/claude/state.ts
index dbc18c5b..ef8b8f0a 100644
--- a/src/claude/state.ts
+++ b/src/claude/state.ts
@@ -35,6 +35,11 @@ export interface SessionState {
/** Weak-match nudges spent this session, capped so the line stays signal.
* Optional for the same backwards-compatibility reason as above. */
nudges?: number;
+ /** Set once this session has been rolled up into a `session_summary`
+ * telemetry event, so a resumed or long-lived session is counted once.
+ * A flag rather than deleting the file: the file still holds `lastQuery` and
+ * `injectedPointers`, which a resumed session needs. */
+ summarized?: boolean;
}
function emptySession(): SessionState {
diff --git a/src/cli-picker.ts b/src/cli-picker.ts
index 22d4a037..40b0db4c 100644
--- a/src/cli-picker.ts
+++ b/src/cli-picker.ts
@@ -62,8 +62,27 @@ export interface PickerRow {
summary: string;
/** True when selecting this host writes outside the repo. */
hasGlobal: boolean;
+ /** Display name. Differs from the id only for setting rows, whose id is an
+ * internal marker the user should never see. */
+ label: string;
+ /** `host` rows wire an agent; `setting` rows are choices that write no files.
+ * They render below a rule, and `a` (toggle all) leaves them alone — that key
+ * means "every agent", not "flip my privacy choice too". */
+ kind: 'host' | 'setting';
}
+/**
+ * The id of the telemetry consent row.
+ *
+ * The picker is where a user is already deciding what graft may touch, which
+ * makes it the honest place to also ask whether they mind anonymous usage stats
+ * — the same move munder-difflin makes with a pre-checked box in onboarding, and
+ * the reason this is a disclosed default rather than a silent one. It is only
+ * offered when telemetry could actually run: showing it in a fork, in CI, or
+ * under DO_NOT_TRACK would be theatre.
+ */
+export const TELEMETRY_ROW_ID = '__telemetry';
+
export interface PickerState {
rows: PickerRow[];
cursor: number;
@@ -72,20 +91,39 @@ export interface PickerState {
aborted: boolean;
}
-/** Claude Code starts checked — it's the deep integration — everything else off. */
-export function initialPickerState(plan: HostPlan[], repo: string, home: string): PickerState {
- return {
- rows: plan.map((p) => ({
- id: p.id,
- detected: p.detected,
- summary: describeWrites(p.writes, repo, home),
- hasGlobal: p.writes.some((w) => w.scope === 'global'),
- })),
- cursor: 0,
- checked: new Set(plan.some((p) => p.id === 'claude') ? ['claude'] : []),
- done: false,
- aborted: false,
- };
+/**
+ * Claude Code starts checked — it's the deep integration — everything else off.
+ *
+ * `offerTelemetry` appends the consent row, checked. Default false so every
+ * existing caller (and every test) sees exactly the host rows it always did.
+ */
+export function initialPickerState(
+ plan: HostPlan[],
+ repo: string,
+ home: string,
+ opts: { offerTelemetry?: boolean } = {},
+): PickerState {
+ const rows: PickerRow[] = plan.map((p) => ({
+ id: p.id,
+ label: p.id,
+ kind: 'host' as const,
+ detected: p.detected,
+ summary: describeWrites(p.writes, repo, home),
+ hasGlobal: p.writes.some((w) => w.scope === 'global'),
+ }));
+ const checked = new Set(plan.some((p) => p.id === 'claude') ? ['claude'] : []);
+ if (opts.offerTelemetry) {
+ rows.push({
+ id: TELEMETRY_ROW_ID,
+ label: 'anonymous usage stats',
+ kind: 'setting',
+ detected: true,
+ summary: 'no code, no file paths, no queries · TELEMETRY.md',
+ hasGlobal: false,
+ });
+ checked.add(TELEMETRY_ROW_ID);
+ }
+ return { rows, cursor: 0, checked, done: false, aborted: false };
}
export type PickerKey = 'up' | 'down' | 'space' | 'all' | 'enter' | 'abort';
@@ -148,8 +186,14 @@ export function reducePicker(state: PickerState, key: PickerKey): PickerState {
return { ...state, checked: next };
}
case 'all': {
- const allOn = state.rows.every((r) => state.checked.has(r.id));
- return { ...state, checked: new Set(allOn ? [] : state.rows.map((r) => r.id)) };
+ // Hosts only. `a` means "wire everything"; a user who pressed it to select
+ // every agent has not thereby said anything about usage stats, so whatever
+ // they chose on that row survives untouched.
+ const hosts = state.rows.filter((r) => r.kind === 'host');
+ const allOn = hosts.every((r) => state.checked.has(r.id));
+ const next = new Set(state.rows.filter((r) => r.kind === 'setting' && state.checked.has(r.id)).map((r) => r.id));
+ if (!allOn) for (const r of hosts) next.add(r.id);
+ return { ...state, checked: next };
}
case 'enter':
return { ...state, done: true };
@@ -165,15 +209,22 @@ export function renderPicker(state: PickerState, tty = true): string {
// Pad on the plain label so the summary column lines up regardless of which
// rows carry the '(not detected)' tag or the cursor's colour codes.
- const label = (r: PickerRow) => `${r.id}${r.detected ? '' : ' (not detected)'}`;
+ const label = (r: PickerRow) => `${r.label}${r.detected ? '' : ' (not detected)'}`;
const width = Math.max(...state.rows.map((r) => label(r).length));
const lines = ['graft init — select what to wire into this repo:', ''];
+ let ruled = false;
for (const [i, row] of state.rows.entries()) {
+ // One rule between the agents and the settings, so the consent row reads as
+ // a separate question rather than as another thing being installed.
+ if (row.kind === 'setting' && !ruled) {
+ lines.push(dim(` ${'─'.repeat(width + 24)}`));
+ ruled = true;
+ }
const here = i === state.cursor;
const box = state.checked.has(row.id) ? '[x]' : '[ ]';
const gap = ' '.repeat(width - label(row).length);
- const name = here ? hot(row.id) : row.id;
- const tag = row.detected ? '' : dim(' (not detected)');
+ const name = here ? hot(row.label) : row.label;
+ const tag = row.detected || row.kind === 'setting' ? '' : dim(' (not detected)');
const summary = row.hasGlobal ? warn(row.summary) : dim(row.summary);
lines.push(`${here ? '›' : ' '} ${box} ${name}${tag}${gap} ${summary}`);
}
@@ -186,16 +237,37 @@ export function pickedIds(state: PickerState): string[] {
return state.rows.filter((r) => state.checked.has(r.id)).map((r) => r.id);
}
+/** Just the agents, with the setting rows filtered out — what init wires. */
+export function pickedHostIds(state: PickerState): string[] {
+ return state.rows.filter((r) => r.kind === 'host' && state.checked.has(r.id)).map((r) => r.id);
+}
+
+/** The consent answer, or undefined when the row was never offered (a fork, CI,
+ * DO_NOT_TRACK) — undefined means "don't change what's stored". */
+export function pickedTelemetry(state: PickerState): boolean | undefined {
+ if (!state.rows.some((r) => r.id === TELEMETRY_ROW_ID)) return undefined;
+ return state.checked.has(TELEMETRY_ROW_ID);
+}
+
/**
- * Drive the picker on a real terminal. Resolves the chosen ids, or null if the
- * user cancelled — in which case the caller must write nothing.
+ * Drive the picker on a real terminal. Resolves the chosen agents plus the
+ * consent answer, or null if the user cancelled — in which case the caller must
+ * write nothing, telemetry setting included.
*/
+export interface Picked {
+ /** Agent ids to wire. */
+ hosts: string[];
+ /** The consent answer, or undefined when the row was not offered. */
+ telemetry?: boolean;
+}
+
export async function runPicker(
plan: HostPlan[],
repo: string,
home: string,
-): Promise<string[] | null> {
- let state = initialPickerState(plan, repo, home);
+ opts: { offerTelemetry?: boolean } = {},
+): Promise<Picked | null> {
+ let state = initialPickerState(plan, repo, home, opts);
const out = process.stderr;
const stdin = process.stdin;
@@ -213,14 +285,14 @@ export async function runPicker(
draw();
try {
- return await new Promise<string[] | null>((resolve) => {
+ return await new Promise<Picked | null>((resolve) => {
// Both listeners come off together: a leftover 'end' would otherwise fire
// after a confirmed pick and redraw the picker over init's own output.
const finish = (onData: (b: Buffer) => void) => {
stdin.off('data', onData);
stdin.off('end', onEnd);
draw();
- resolve(state.aborted ? null : pickedIds(state));
+ resolve(state.aborted ? null : { hosts: pickedHostIds(state), telemetry: pickedTelemetry(state) });
};
const onData = (buf: Buffer) => {
const keys = keysOf(buf.toString('utf8'));
diff --git a/src/cli.ts b/src/cli.ts
index e0b2d785..880af035 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -38,10 +38,50 @@ import { homedir } from "node:os";
import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, runUpgrade } from "./cli-meta.js";
import { patchBuildConfig, type BuildConfig } from "./util/state.js";
import { formatUpdateNudge, maybeRefreshInBackground, readUpdateCache, refreshUpdateCache, writeStamp } from "./upkeep.js";
+import {
+ errorCode,
+ filesBucket,
+ durationBucket,
+ formatDebug,
+ formatStatus,
+ firstRunNotice,
+ isTrackedCommand,
+ langsValue,
+ offReason,
+ maybeFlushInBackground,
+ patchState,
+ runFlush,
+ track,
+ trackFirstRunIfNew,
+} from "./telemetry/index.js";
const program = new Command();
const currentVersion = readCurrentVersion(import.meta.url);
+/**
+ * What the `query` telemetry event will say, filled in by the command as it runs
+ * and emitted once from the `postAction` hook below.
+ *
+ * A module-level slot rather than a threaded parameter because the repo root is
+ * resolved deep inside each action (`queryRoot`) while the event is emitted
+ * centrally — and because a command that calls `process.exit` should simply
+ * report nothing, which falls out of never emitting until postAction.
+ */
+let queryNote: { repo?: string; hit?: "yes" | "no" } = {};
+
+/** Record the repo a query ran against, and pass it straight through so call
+ * sites stay one line. */
+function noteQuery(dir: string): string {
+ queryNote.repo = dir;
+ return dir;
+}
+
+/** Whether a query found anything. Only the commands that have a result count in
+ * hand call this; the property is simply absent for the others. */
+function noteHit(found: boolean): void {
+ queryNote.hit = found ? "yes" : "no";
+}
+
program
.name("graft")
.description("Build a repo's context graph as linked markdown, and keep it in sync with the code.")
@@ -145,6 +185,25 @@ program.hook("preAction", (_parent, action) => {
maybeRefreshInBackground();
const nudge = formatUpdateNudge(currentVersion, readUpdateCache()?.latest);
if (nudge) console.error(nudge);
+ // Telemetry, in the order a user should experience it: disclose first, then
+ // record, then (at most once a day, detached) send. Every step is a no-op in a
+ // fork, in CI, under DO_NOT_TRACK, or after `graft telemetry disable`.
+ const notice = firstRunNotice();
+ if (notice) console.error(notice);
+ trackFirstRunIfNew();
+ maybeFlushInBackground();
+});
+
+/**
+ * The `query` event, emitted after the command rather than before it, so it can
+ * carry what the query actually did. A command that exits early via
+ * `process.exit` never reaches here and is simply not counted — under-reporting
+ * is the right failure mode for a metric.
+ */
+program.hook("postAction", (_parent, action) => {
+ const name = action.name();
+ if (!isTrackedCommand(name)) return;
+ track("query", { command: name, surface: "cli", hit: queryNote.hit }, { repo: queryNote.repo });
});
// Hidden from --help: only ever spawned detached by maybeRefreshInBackground.
@@ -155,6 +214,43 @@ program
refreshUpdateCache();
});
+// Hidden for the same reason as _update-check: only ever spawned detached, by
+// maybeFlushInBackground. Running it by hand is harmless — it drains the queue.
+program
+ .command("_telemetry-flush", { hidden: true })
+ .description("internal: POST the queued anonymous usage events")
+ .action(async () => {
+ await runFlush();
+ });
+
+program
+ .command("telemetry")
+ .description("Show, inspect, or turn off the anonymous usage stats (see TELEMETRY.md)")
+ .argument("[action]", "status (default) | enable | disable | debug", "status")
+ .action((action: string) => {
+ switch (action) {
+ case "status":
+ console.log(formatStatus());
+ return;
+ case "enable":
+ patchState({ enabled: true });
+ console.log("telemetry: on — anonymous, aggregate-only. `graft telemetry status` for details.");
+ return;
+ case "disable":
+ // Also stamp the notice as shown: someone who has just opted out should
+ // not be told about telemetry again the next time they run a command.
+ patchState({ enabled: false, noticeShownAt: new Date().toISOString() });
+ console.log("telemetry: off. Nothing further will be recorded or sent.");
+ return;
+ case "debug":
+ console.log(formatDebug());
+ return;
+ default:
+ console.error(`✗ unknown action "${action}" — expected status, enable, disable, or debug`);
+ process.exit(1);
+ }
+ });
+
program
.command("version")
.description("Print the installed version and the latest published on npm")
@@ -214,6 +310,7 @@ program
},
command: Command,
) => {
+ const buildStartedAt = Date.now();
const concurrency = opts.concurrency ? Math.max(1, Number(opts.concurrency)) : undefined;
if (opts.concurrency && !Number.isFinite(concurrency)) {
console.error(`✗ --concurrency must be a number, got "${opts.concurrency}"`);
@@ -299,6 +396,10 @@ program
process.stderr.write(
`\r${phase === "summarize" ? "reading" : "writing"} concepts ${index + 1}/${total}: ${file.slice(0, 40).padEnd(40)}`,
),
+ }).catch((err: unknown) => {
+ // Only the stage and a code enum; the message stays on this machine.
+ track("build_failed", { stage: "summarize", code: errorCode(err) }, { repo: buildRoot });
+ throw err;
});
process.stderr.write("\n");
console.log(
@@ -319,6 +420,9 @@ program
process.stderr.write(
`\r${phase === "enrich" ? "summarizing" : "parsing"} ${index + 1}/${total}: ${file.slice(0, 50).padEnd(50)}`,
),
+ }).catch((err: unknown) => {
+ track("build_failed", { stage: "graph", code: errorCode(err) }, { repo: buildRoot });
+ throw err;
});
process.stderr.write("\n");
console.log(`✓ wiring: ${g.nodes} nodes (${fmt(g.byKind)}), ${g.edges} edges, ${g.cards} cards [${g.languages.join(", ")}]`);
@@ -330,6 +434,19 @@ program
console.log(` meaning: ${m.computed} computed, ${m.cached} cached, ${m.stale} stale, ${m.pending} pending`);
}
console.log(` → ${g.contextDir}`);
+ // The activation event. Everything here is a bucket or a fixed label: repo
+ // scale rather than a file count, a language set rather than file names.
+ track(
+ "build_completed",
+ {
+ files_bucket: filesBucket(g.files),
+ langs: langsValue(g.languages),
+ mode: deep ? "deep" : "fast",
+ duration_bucket: durationBucket(Date.now() - buildStartedAt),
+ incremental: String(g.reused > 0),
+ },
+ { repo: buildRoot },
+ );
for (const e of g.errors) console.error(`✗ ${e}`);
const rel = relative(process.cwd(), g.contextDir) || "graft";
@@ -380,7 +497,7 @@ program
.option("--no-graph-rank", "rank by lexical relevance only, without the graph-connectivity re-rank (ablation/eval)")
.option(...NO_REFRESH_FLAG)
.action(async (query: string, dirArg: string | undefined, opts: { limit: string; source?: boolean; full?: boolean; in?: string; json?: boolean; refresh?: boolean; graphRank?: boolean }) => {
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
await refreshBefore(dir, opts);
const askGlobalDir = program.opts<GlobalOpts>().dir;
if (readWorkspace(dir, askGlobalDir)) {
@@ -398,6 +515,7 @@ program
process.exit(1);
return;
}
+ noteHit(r.hits.length > 0);
if (opts.json) {
console.log(JSON.stringify(r, null, 2));
} else {
@@ -414,7 +532,7 @@ program
.option("--json", "output the result as JSON")
.option(...NO_REFRESH_FLAG)
.action(async (file: string, dirArg: string | undefined, opts: { json?: boolean; refresh?: boolean }) => {
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
await refreshBefore(dir, opts);
const { skeleton, formatSkeleton } = await import("./ask/ask.js");
const globalOpts = program.opts<{ dir?: string }>();
@@ -431,7 +549,7 @@ program
.option("--json", "output the drift as JSON")
.action(async (dirArg: string | undefined, opts: { extensions?: string[]; json?: boolean }) => {
warnUnsupportedExtensions(opts.extensions);
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
const checkGlobalDir = program.opts<GlobalOpts>().dir;
if (readWorkspace(dir, checkGlobalDir)) {
await runWorkspaceCheck(dir, checkGlobalDir);
@@ -474,7 +592,7 @@ program
.option("--export <dir>", "write one self-contained index.html instead of serving (for CI, GitHub Pages, or a build artifact)")
.option("--title <text>", "subtitle shown beside the repo name in an exported page (e.g. \"PR #151\")")
.action(async (dirArg: string | undefined, opts: { port: string; open: boolean; export?: string; title?: string }) => {
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
const { existsSync } = await import("node:fs");
const { resolve, basename } = await import("node:path");
const { spawn } = await import("node:child_process");
@@ -525,7 +643,7 @@ program
.description("Serve the graph over MCP (stdio) — exposes graft_find_code, graft_trace_calls, graft_find_all, graft_file_api, graft_repo_map and graft_check_freshness as tools")
.argument(...DIR_ARG)
.action(async (dirArg: string | undefined) => {
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
const { startMcpServer } = await import("./mcp/server.js");
const globalOpts = program.opts<{ dir?: string }>();
startMcpServer(dir, globalOpts.dir, currentVersion);
@@ -549,7 +667,7 @@ program
dirArg: string | undefined,
opts: { direction?: string; depth?: string; in?: string; json?: boolean; refresh?: boolean },
) => {
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
await refreshBefore(dir, opts);
const globalOpts = program.opts<{ dir?: string }>();
if (!opts.json && readWorkspace(dir, globalOpts.dir)) {
@@ -588,7 +706,7 @@ program
.option("--title <text>", "subtitle beside the repo name on the exported page (e.g. \"PR #171\")")
.option(...NO_REFRESH_FLAG)
.action(async (dirArg: string | undefined, opts: { base?: string; depth?: string; format?: string; name?: boolean; exportViz?: string; title?: string; refresh?: boolean }) => {
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
await refreshBefore(dir, opts);
const { runBlastCommand } = await import("./blast/blast-cli.js");
await runBlastCommand(dir, {
@@ -618,7 +736,7 @@ program
dirArg: string | undefined,
opts: { ignoreCase?: boolean; fixed?: boolean; in?: string; json?: boolean; refresh?: boolean },
) => {
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
await refreshBefore(dir, opts);
const globalOpts = program.opts<{ dir?: string }>();
if (readWorkspace(dir, globalOpts.dir)) {
@@ -648,7 +766,7 @@ program
.option("--json", "output as JSON")
.option(...NO_REFRESH_FLAG)
.action(async (dirArg: string | undefined, opts: { json?: boolean; maxDirs?: string; refresh?: boolean }) => {
- const dir = queryRoot(dirArg);
+ const dir = noteQuery(queryRoot(dirArg));
const root = resolve(dir);
const globalOpts = program.opts<{ dir?: string }>();
let maxDirsW: number | undefined;
@@ -723,22 +841,37 @@ program
const noAgents = (opts as { agents?: unknown }).agents === false;
let ids: string[];
+ // The consent answer from the picker. Undefined everywhere else — a scripted
+ // or flag-driven init never asked, so it must not silently answer.
+ let consent: boolean | undefined;
if (explicit) ids = explicit;
else if (opts.allAgents) ids = plan.map((p) => p.id);
else if (noAgents) ids = ["claude"];
else if (opts.yes || opts.dryRun) ids = detectedIds;
else if (process.stdin.isTTY && process.stderr.isTTY) {
- const picked = await runPicker(plan, repo, home);
+ // Only offer the row when telemetry could actually run. `disabled` still
+ // counts: someone who turned it off should be able to turn it back on here.
+ const reason = offReason();
+ const picked = await runPicker(plan, repo, home, {
+ offerTelemetry: reason === null || reason === "disabled",
+ });
if (picked === null) {
console.error("· cancelled — nothing written");
return;
}
- ids = picked;
+ ids = picked.hosts;
+ consent = picked.telemetry;
} else {
console.error(formatNonInteractiveHelp(detectedIds));
return;
}
+ // The picker's answer, recorded before anything is wired: a user who
+ // unchecked the row must not have this run's init_completed sent.
+ if (consent !== undefined) {
+ patchState({ enabled: consent, noticeShownAt: new Date().toISOString() });
+ }
+
// Workspace parent: every child repo gets its OWN wiring too. A session
// opens at a repo root, not at the parent, and reads `.claude/` from there —
// wiring only the parent leaves each child with no skill, hooks, or MCP.
@@ -786,6 +919,12 @@ program
edges: graphs.reduce((n, g) => n + g.meta.edgeCount, 0),
}),
);
+ // Sorted so `claude,cursor` and `cursor,claude` aggregate as one value.
+ track(
+ "init_completed",
+ { agents: [...ids].sort().join(","), consent: consent === undefined ? "unasked" : String(consent) },
+ { repo },
+ );
});
/** One repo's worth of `init` writes — the parent, then each workspace child. */
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 86bb64ba..e5072509 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -7,6 +7,22 @@ import { TOOLS, callTool } from './tools.js';
import { mcpInstructions } from './instructions.js';
import { runUpkeep } from '../upkeep-run.js';
import { runningVersion } from '../upkeep.js';
+import { maybeFlushInBackground, track } from '../telemetry/index.js';
+
+/**
+ * MCP tool name → the command enum the telemetry contract knows. A tool absent
+ * here is simply not counted: `track` would drop an unlisted command anyway, and
+ * mapping by hand keeps the wire vocabulary identical across the CLI and MCP so
+ * `ask` means the same thing in both.
+ */
+const TOOL_COMMAND: Record<string, string> = {
+ graft_find_code: 'ask',
+ graft_find_all: 'grep',
+ graft_trace_calls: 'callers',
+ graft_file_api: 'skeleton',
+ graft_repo_map: 'map',
+ graft_check_freshness: 'check',
+};
function send(msg: object): void {
process.stdout.write(`${JSON.stringify(msg)}\n`);
@@ -34,6 +50,14 @@ export function startMcpServer(root: string, dirOverride?: string, version = '0'
// put them. Never blocks: the registry fetch happens in a detached child.
const upkeep = runUpkeep(root, runningVersion()).lines;
for (const line of upkeep) console.error(line);
+ // Same deal for the telemetry queue: flushed from a detached child at boot, so
+ // a Cursor user who never touches the CLI still gets their events out.
+ //
+ // Deliberately NOT the first-run notice. This server's stderr goes to an editor
+ // log nobody reads, so printing it here would mark the disclosure as shown
+ // without anyone having seen it. It stays pending for the next CLI command,
+ // and `graft init`'s picker is the channel that reached this user already.
+ maybeFlushInBackground();
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
rl.on('line', (line) => {
@@ -78,7 +102,16 @@ export function startMcpServer(root: string, dirOverride?: string, version = '0'
// that can reject here is a bug — surface it as a JSON-RPC error rather
// than an unhandled rejection that kills the server.
callTool(root, name, args, dirOverride).then(
- (r) => reply(id, { content: [{ type: 'text', text: r.text }], isError: r.isError }),
+ (r) => {
+ // No `hit`: `isError` means the tool failed, which is not the same
+ // question as "did the graph have an answer". Absent beats wrong.
+ // hasOwn for the same reason as track()'s: a client is free to send
+ // `{"name":"constructor"}`, and a plain lookup would hand `track` a
+ // function rather than undefined.
+ const command = Object.hasOwn(TOOL_COMMAND, name) ? TOOL_COMMAND[name] : undefined;
+ track('query', { command, surface: 'mcp' }, { repo: root, host: 'mcp' });
+ reply(id, { content: [{ type: 'text', text: r.text }], isError: r.isError });
+ },
(err) => replyError(id, -32603, err instanceof Error ? err.message : String(err)),
);
return;
diff --git a/src/telemetry/contract.ts b/src/telemetry/contract.ts
new file mode 100644
index 00000000..cb380232
--- /dev/null
+++ b/src/telemetry/contract.ts
@@ -0,0 +1,200 @@
+/**
+ * The telemetry contract: the complete, machine-enforced list of what graft may
+ * send. `TELEMETRY.md` is the same list in prose, and the two are kept in
+ * lockstep — an event or property that is not in this file cannot be sent, and
+ * one that is not in `TELEMETRY.md` must not be added here.
+ *
+ * Why an allowlist rather than a review rule: every telemetry incident in the
+ * tools we studied came from a call site quietly adding a property nobody
+ * audited. `track()` (track.ts) drops unknown events and unknown keys instead of
+ * trusting its callers, so a future `track('query', { path })` sends `query`
+ * with no `path` rather than leaking one. The blast radius of a careless call
+ * site is "we lose a metric", never "we received someone's source tree".
+ *
+ * The other half of that guarantee is the value side: every number crosses as a
+ * BUCKET and every string as a member of a fixed union. A raw file count plus a
+ * language set starts to fingerprint a specific repo; `"100-500"` does not. A
+ * raw error message is a path, a symbol, and sometimes a snippet of code; an
+ * enum member is not.
+ *
+ * This module is pure — no I/O, no config, no clock. It is the file a reviewer
+ * (or a suspicious user, since the repo is public) reads to verify the claim.
+ */
+
+/* -------------------------------------------------------------------------- */
+/* the event → allowed-property-keys map */
+/* -------------------------------------------------------------------------- */
+
+/**
+ * The contract itself. Common properties (see {@link COMMON_KEYS}) are stamped
+ * centrally by `track()` and are deliberately not repeated per event.
+ */
+export const EVENTS: Record<string, ReadonlySet<string>> = {
+ /** Once per machine, when the install id is first minted. The denominator. */
+ first_run: new Set<string>(),
+ /** `graft init` completed. Tells us which agents people actually wire, and
+ * how many decline telemetry at the picker. */
+ init_completed: new Set<string>(['agents', 'consent']),
+ /** A build finished. The activation event — an install that never reaches one
+ * of these is the funnel leak we most want to see. */
+ build_completed: new Set<string>(['files_bucket', 'langs', 'mode', 'duration_bucket', 'incremental']),
+ /** A build threw. `stage`/`code` are enums; the message never travels. */
+ build_failed: new Set<string>(['stage', 'code']),
+ /** One query, from any surface. The DAU backbone and the dead-command detector. */
+ query: new Set<string>(['command', 'surface', 'hit']),
+ /** One closed agent session, summarised. `graft_reads` vs `source_reads` is
+ * the single number that says whether an agent prefers graft to grep. */
+ session_summary: new Set<string>(['graft_reads_bucket', 'source_reads_bucket', 'saved_tokens_bucket']),
+};
+
+/** Stamped on every event by `track()`; not listed per event above. */
+export const COMMON_KEYS = [
+ 'app_version',
+ 'os',
+ 'arch',
+ 'node_major',
+ 'ci',
+ 'agent_host',
+ 'repo_id',
+] as const;
+
+/* -------------------------------------------------------------------------- */
+/* the value enums */
+/* -------------------------------------------------------------------------- */
+
+/** Which surface issued a query. `hook` is Claude Code's prompt hook, which
+ * queries on the user's behalf without them typing a command. */
+export type Surface = 'cli' | 'mcp' | 'hook';
+
+/** Which editor/agent graft is running under. Derived from the surface and the
+ * wiring on disk — never from a hostname, a username, or an env var's value. */
+export type AgentHost = 'claude-code' | 'cursor' | 'mcp' | 'cli';
+
+/**
+ * The commands worth counting. A command absent here is simply not reported —
+ * `track()` drops the event rather than sending a free-form string, which is
+ * what keeps a future `graft <something-user-named>` from becoming a data leak.
+ */
+export const TRACKED_COMMANDS = [
+ 'ask', 'grep', 'callers', 'skeleton', 'map', 'check', 'blast', 'viz',
+] as const;
+export type TrackedCommand = (typeof TRACKED_COMMANDS)[number];
+
+export function isTrackedCommand(name: string): name is TrackedCommand {
+ return (TRACKED_COMMANDS as readonly string[]).includes(name);
+}
+
+/** Where a failing build died. Coarse on purpose: enough to route a bug, not
+ * enough to describe anyone's repo. */
+export const BUILD_STAGES = ['walk', 'extract', 'graph', 'summarize', 'synthesize', 'write'] as const;
+export type BuildStage = (typeof BUILD_STAGES)[number];
+
+/**
+ * The failure taxonomy. Anything unrecognised becomes `E_UNKNOWN` — the point of
+ * a closed set is that an unclassified error contributes a count and nothing
+ * else, so no message text can ride along inside a "code".
+ */
+export const ERROR_CODES = [
+ 'E_UNKNOWN', 'E_PARSE', 'E_TIMEOUT', 'E_LLM', 'E_AUTH', 'E_RATE_LIMIT',
+ 'E_NETWORK', 'E_DISK', 'E_PERMISSION', 'E_OOM', 'E_LOCK',
+] as const;
+export type ErrorCode = (typeof ERROR_CODES)[number];
+
+/**
+ * Map a thrown value to a code without letting its text through. Only fixed
+ * substrings are matched, and only a member of {@link ERROR_CODES} is returned —
+ * the error's own message is never the return value, not even in part.
+ */
+export function errorCode(err: unknown): ErrorCode {
+ const code = (err as { code?: unknown } | null)?.code;
+ if (typeof code === 'string') {
+ if (code === 'ENOSPC' || code === 'EDQUOT') return 'E_DISK';
+ if (code === 'EACCES' || code === 'EPERM') return 'E_PERMISSION';
+ if (code === 'ENOMEM') return 'E_OOM';
+ if (code === 'ETIMEDOUT' || code === 'ESOCKETTIMEDOUT') return 'E_TIMEOUT';
+ if (code === 'ENOTFOUND' || code === 'ECONNREFUSED' || code === 'ECONNRESET') return 'E_NETWORK';
+ }
+ const status = (err as { status?: unknown } | null)?.status;
+ if (typeof status === 'number') {
+ if (status === 401 || status === 403) return 'E_AUTH';
+ if (status === 429) return 'E_RATE_LIMIT';
+ if (status >= 500) return 'E_LLM';
+ }
+ const msg = err instanceof Error ? err.message.toLowerCase() : '';
+ if (msg.includes('timeout') || msg.includes('timed out')) return 'E_TIMEOUT';
+ if (msg.includes('parse') || msg.includes('syntax')) return 'E_PARSE';
+ if (msg.includes('lock')) return 'E_LOCK';
+ return 'E_UNKNOWN';
+}
+
+/* -------------------------------------------------------------------------- */
+/* buckets — every number crosses the wire as a label */
+/* -------------------------------------------------------------------------- */
+
+/** Repo scale. Exact counts fingerprint a repo; these five labels answer the
+ * only question we have ("toy, service, or monorepo?"). */
+export function filesBucket(n: number): string {
+ if (n <= 0) return '0';
+ if (n < 50) return '1-49';
+ if (n < 200) return '50-199';
+ if (n < 1000) return '200-999';
+ if (n < 5000) return '1000-4999';
+ return '5000+';
+}
+
+/** Wall-clock for a build. Coarse enough that it says "fast/slow", not "this
+ * exact machine on this exact tree". */
+export function durationBucket(ms: number): string {
+ const s = ms / 1000;
+ if (s < 1) return '<1s';
+ if (s < 5) return '1-5s';
+ if (s < 30) return '5-30s';
+ if (s < 120) return '30s-2m';
+ if (s < 600) return '2-10m';
+ return '10m+';
+}
+
+/** Generic small-count bucket, for the per-session read counters. */
+export function countBucket(n: number): string {
+ if (n <= 0) return '0';
+ if (n < 5) return '1-4';
+ if (n < 20) return '5-19';
+ if (n < 50) return '20-49';
+ if (n < 200) return '50-199';
+ return '200+';
+}
+
+/** Estimated tokens saved in one session — the README's central claim, in the
+ * only resolution we need to defend it. */
+export function savedTokensBucket(n: number): string {
+ if (n <= 0) return '0';
+ if (n < 1000) return '<1k';
+ if (n < 5000) return '1-5k';
+ if (n < 20000) return '5-20k';
+ if (n < 100000) return '20-100k';
+ return '100k+';
+}
+
+/**
+ * Languages, normalised, filtered to a safe shape, and capped.
+ *
+ * Sorted so `["go","ts"]` and `["ts","go"]` aggregate as one value, deduped, and
+ * cut to eight — a repo with a very long tail of languages is itself a
+ * distinguishing fact, and the tail answers no question we have.
+ *
+ * The character filter is the part that matters. This is the only property in
+ * the contract that is not drawn from a closed set defined in this file: the
+ * values come from the parser registry, several modules away, via
+ * `languageLabelOf() ?? container.name ?? generic.name ?? "unknown"`. That is
+ * safe today, but it means the no-free-text guarantee would rest on a promise
+ * made elsewhere — and a future generic extractor naming itself after the
+ * extension it matched would quietly turn this into a channel for file
+ * metadata. Anything outside `[a-z0-9+#._-]`, or longer than 24 characters, is
+ * therefore dropped here rather than trusted.
+ */
+export function langsValue(langs: readonly string[]): string {
+ const clean = langs
+ .map((l) => l.toLowerCase().trim())
+ .filter((l) => l.length > 0 && l.length <= 24 && /^[a-z0-9+#._-]+$/.test(l));
+ return [...new Set(clean)].sort().slice(0, 8).join(',');
+}
diff --git a/src/telemetry/flush.ts b/src/telemetry/flush.ts
new file mode 100644
index 00000000..f3d124ae
--- /dev/null
+++ b/src/telemetry/flush.ts
@@ -0,0 +1,75 @@
+/**
+ * Getting the queue off the machine without any command ever waiting for it.
+ *
+ * Deliberately the same shape as `maybeRefreshInBackground` in `upkeep.ts`,
+ * which has been doing this for the npm registry check since 0.7: check a
+ * timestamp, write the timestamp BEFORE spawning so a child that dies cannot
+ * make every subsequent command spawn another one, then `spawn` detached and
+ * `unref`. The parent returns immediately and never learns the outcome.
+ *
+ * Once a day, not once a command. Events are cheap to hold and the questions we
+ * are asking ("how many repos activated this week") do not get better answers
+ * from lower latency.
+ */
+import { spawn } from 'node:child_process';
+import { statSync } from 'node:fs';
+import { graftCliPath } from '../claude/paths.js';
+import { drain, queuePath, requeue } from './queue.js';
+import { patchState, readState } from './identity.js';
+import { sendBatch, type SendResult } from './send.js';
+import { telemetryOn } from './gate.js';
+
+/** Matches `UPDATE_TTL_MS`: a day is the natural period for both. */
+export const FLUSH_TTL_MS = 24 * 60 * 60 * 1000;
+
+function queueHasEvents(home?: string): boolean {
+ try { return statSync(queuePath(home)).size > 0; } catch { return false; }
+}
+
+export function needsFlush(flushedAt: number | undefined, now = Date.now()): boolean {
+ return typeof flushedAt !== 'number' || now - flushedAt >= FLUSH_TTL_MS;
+}
+
+/**
+ * Spawn the flush if the queue has something in it and a day has passed. Returns
+ * whether a child was started, for tests. Never waits, never throws.
+ */
+export function maybeFlushInBackground(home?: string, now = Date.now()): boolean {
+ try {
+ if (!telemetryOn(home)) return false;
+ if (!queueHasEvents(home)) return false;
+ if (!needsFlush(readState(home)?.flushedAt, now)) return false;
+ patchState({ flushedAt: now }, home); // before the spawn, so a dying child costs one attempt
+ const child = spawn(process.execPath, [graftCliPath(), '_telemetry-flush'], {
+ detached: true,
+ stdio: 'ignore',
+ });
+ child.unref();
+ return true;
+ } catch {
+ return false; // no spawn available (sandbox, ENOMEM) — try again tomorrow
+ }
+}
+
+/**
+ * Whether a failed send is worth keeping the batch for.
+ *
+ * A 5xx or a transport failure is ours to retry — a week offline should not be
+ * a week of lost events. A 4xx is not: a bad key or a malformed batch will fail
+ * identically forever, and retrying it would pin the queue at its cap until it
+ * starts dropping the events that WOULD have sent.
+ */
+export function shouldRequeue(res: SendResult): boolean {
+ if (res.ok) return false;
+ return res.status === undefined || res.status >= 500;
+}
+
+/** The `graft _telemetry-flush` body, running in the detached child. */
+export async function runFlush(home?: string): Promise<void> {
+ try {
+ if (!telemetryOn(home)) return;
+ const events = drain(home);
+ if (events.length === 0) return;
+ if (shouldRequeue(await sendBatch(events))) requeue(events, home);
+ } catch { /* a failed flush is a non-event by design */ }
+}
diff --git a/src/telemetry/gate.ts b/src/telemetry/gate.ts
new file mode 100644
index 00000000..c706313a
--- /dev/null
+++ b/src/telemetry/gate.ts
@@ -0,0 +1,67 @@
+/**
+ * The single "may we send?" predicate, checked before every append and again
+ * before every send.
+ *
+ * Four independent gates, in the order a user would expect them to win:
+ *
+ * 1. A key at all — dev builds and forks have none (see key.ts), so the whole
+ * subsystem is inert for anyone who did not install a published graft.
+ * 2. `DO_NOT_TRACK` — the cross-tool convention (consoledonottrack.com).
+ * Honoured unconditionally: it outranks our own setting, because a user who
+ * set it machine-wide has already answered the question for every tool.
+ * 3. CI — a build server is not a user. Counting it would inflate every number
+ * we care about and tell us nothing about a person.
+ * 4. The user's own choice, from the `graft init` picker or
+ * `graft telemetry disable`. Default on when never set.
+ *
+ * Re-checked at every append rather than cached at boot, so `graft telemetry
+ * disable` in one terminal takes effect in a long-lived MCP server in another
+ * without a restart.
+ */
+import { posthogKey } from './key.js';
+import { readState } from './identity.js';
+
+export type OffReason = 'no-key' | 'do-not-track' | 'ci' | 'disabled';
+
+/** The `DO_NOT_TRACK` convention: set and not `0`/empty means "off". */
+export function doNotTrack(env: NodeJS.ProcessEnv = process.env): boolean {
+ const v = env.DO_NOT_TRACK;
+ return v !== undefined && v !== '' && v !== '0';
+}
+
+/**
+ * CI detection. `CI` covers essentially every provider; the rest are the ones
+ * that historically did not set it. Deliberately generous — a false positive
+ * costs one uncounted user, a false negative pollutes the dataset.
+ */
+export function inCi(env: NodeJS.ProcessEnv = process.env): boolean {
+ if (env.CI !== undefined && env.CI !== '' && env.CI !== '0' && env.CI !== 'false') return true;
+ return Boolean(
+ env.GITHUB_ACTIONS || env.GITLAB_CI || env.BUILDKITE || env.CIRCLECI ||
+ env.TEAMCITY_VERSION || env.JENKINS_URL || env.TF_BUILD || env.BUILD_NUMBER,
+ );
+}
+
+/** Null when telemetry may run, otherwise the first gate that closed. */
+export function offReason(home?: string, env: NodeJS.ProcessEnv = process.env): OffReason | null {
+ if (!posthogKey()) return 'no-key';
+ if (doNotTrack(env)) return 'do-not-track';
+ if (inCi(env)) return 'ci';
+ if (readState(home)?.enabled === false) return 'disabled';
+ return null;
+}
+
+export function telemetryOn(home?: string, env: NodeJS.ProcessEnv = process.env): boolean {
+ return offReason(home, env) === null;
+}
+
+/** One line for `graft telemetry status`, naming the gate that is closed so a
+ * user who thinks they disabled it can see which switch actually took. */
+export function explainOff(reason: OffReason): string {
+ switch (reason) {
+ case 'no-key': return 'off — this build has no telemetry key (a fork, or a local `npm run build`); nothing can be sent';
+ case 'do-not-track': return 'off — DO_NOT_TRACK is set in this environment';
+ case 'ci': return 'off — this looks like CI';
+ case 'disabled': return 'off — you disabled it (`graft telemetry enable` to turn it back on)';
+ }
+}
diff --git a/src/telemetry/identity.ts b/src/telemetry/identity.ts
new file mode 100644
index 00000000..a77f515f
--- /dev/null
+++ b/src/telemetry/identity.ts
@@ -0,0 +1,92 @@
+/**
+ * The two identifiers, and why neither of them identifies anyone.
+ *
+ * • install id — one per machine, in `~/.graft/telemetry.json`, beside the
+ * update-check cache that already lives there. Lets us count people rather
+ * than events, so a dev running forty queries is one user and not forty.
+ * • repo id — one per checkout, in `graft/.cache/`. Activation and retention
+ * for graft are per-repo facts ("did this repo ever get past build?"), and
+ * the install id alone cannot express them.
+ *
+ * Both are `randomUUID()`. Not a machine id, not a hash of the git remote, not
+ * derived from anything real — a coin flip, written down. A hash would at least
+ * be guessable by us (we could hash a public repo URL and look for it); a random
+ * UUID cannot be reversed or confirmed even in principle. Deleting `~/.graft/`
+ * or `graft/` deletes them, and the user simply looks like someone new.
+ *
+ * Every function here is fail-soft: an unwritable home is a very common state
+ * (a locked-down CI image, a read-only container) and it must cost the caller
+ * nothing. A failed persist yields an ephemeral id for this process — still
+ * anonymous, just not stable — and never a throw.
+ */
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { cacheDir, readJson, writeJsonAtomic } from '../util/state.js';
+
+/** Machine-global telemetry state. Shares `~/.graft/` with `update-check.json`. */
+export interface TelemetryState {
+ installId: string;
+ /** The user's choice. Absent means "never chosen" → the default (on) applies. */
+ enabled?: boolean;
+ /** ISO stamp of the one-time first-run notice, so it prints exactly once. */
+ noticeShownAt?: string;
+ /** Epoch ms of the last flush ATTEMPT, mirroring `UpdateCache.checkedAt`. */
+ flushedAt?: number;
+}
+
+export function statePath(home: string = homedir()): string {
+ return join(home, '.graft', 'telemetry.json');
+}
+
+export function readState(home?: string): TelemetryState | null {
+ return readJson<TelemetryState>(statePath(home));
+}
+
+/** Read-modify-write. Not atomic across processes; a lost update costs at most a
+ * duplicated notice or an extra flush attempt, never corruption. */
+export function patchState(patch: Partial<TelemetryState>, home?: string): TelemetryState {
+ const next: TelemetryState = { ...(readState(home) ?? { installId: randomUUID() }), ...patch };
+ try { writeJsonAtomic(statePath(home), next); } catch { /* unwritable home — in-memory only */ }
+ return next;
+}
+
+export interface Install {
+ id: string;
+ /** True when this call minted the id, i.e. this is the machine's first run. */
+ firstRun: boolean;
+}
+
+/** The install id, minted on first call. */
+export function installId(home?: string): Install {
+ const existing = readState(home);
+ if (existing?.installId) return { id: existing.installId, firstRun: false };
+ const id = randomUUID();
+ try {
+ writeJsonAtomic(statePath(home), { ...(existing ?? {}), installId: id } satisfies TelemetryState);
+ return { id, firstRun: true };
+ } catch {
+ // Unwritable home: use the id for this process rather than failing closed.
+ // Reported as firstRun:false so a machine that can never persist doesn't
+ // send a first_run event on every single command.
+ return { id, firstRun: false };
+ }
+}
+
+/**
+ * The repo id, in `graft/.cache/` rather than `.graft/config.json`.
+ *
+ * `.graft/config.json` would have been the tidier home, but writing it runs
+ * `ensureBuildConfigIgnored`, which appends to the repo's `.gitignore`. Minting
+ * an id during a read-only `graft ask` must not modify a file the user has
+ * committed. `graft/.cache/` is already derived, already git-ignored, and
+ * already where every other per-repo sidecar lives.
+ */
+export function repoId(repo: string): string {
+ const path = join(cacheDir(repo), 'telemetry-repo-id.json');
+ const existing = readJson<{ repoId?: string }>(path);
+ if (existing?.repoId) return existing.repoId;
+ const id = randomUUID();
+ try { writeJsonAtomic(path, { repoId: id }); } catch { /* unwritable — ephemeral */ }
+ return id;
+}
diff --git a/src/telemetry/index.ts b/src/telemetry/index.ts
new file mode 100644
index 00000000..9d7d4e94
--- /dev/null
+++ b/src/telemetry/index.ts
@@ -0,0 +1,17 @@
+/**
+ * Anonymous adoption telemetry. `TELEMETRY.md` is the public contract;
+ * `contract.ts` is the same list enforced in code.
+ *
+ * The whole subsystem is inert unless four things are true at once: the build
+ * carries a key (published releases only), `DO_NOT_TRACK` is unset, this is not
+ * CI, and the user has not disabled it. See `gate.ts`.
+ */
+export { EVENTS, COMMON_KEYS, isTrackedCommand, errorCode, filesBucket, durationBucket, countBucket, savedTokensBucket, langsValue } from './contract.js';
+export type { AgentHost, Surface, TrackedCommand, BuildStage, ErrorCode } from './contract.js';
+export { track, trackFirstRunIfNew, detectHost } from './track.js';
+export type { QueuedEvent, TrackContext } from './track.js';
+export { telemetryOn, offReason, explainOff } from './gate.js';
+export { maybeFlushInBackground, runFlush } from './flush.js';
+export { firstRunNotice, formatStatus, formatDebug, NOTICE, TELEMETRY_DOC_URL } from './notice.js';
+export { patchState, readState } from './identity.js';
+export { flushClosedSessions } from './sessions.js';
diff --git a/src/telemetry/key.ts b/src/telemetry/key.ts
new file mode 100644
index 00000000..1e39d8a9
--- /dev/null
+++ b/src/telemetry/key.ts
@@ -0,0 +1,52 @@
+/**
+ * The PostHog project key, and the reason forks stay silent.
+ *
+ * `BAKED_KEY` is empty in the repository and is rewritten in place by
+ * `scripts/stamp-telemetry-key.mjs`, which runs from `prepublishOnly`. So the
+ * key exists only in the published tarball: a clone, a fork, and a plain
+ * `npm run build` all compile to `''`, and every send path short-circuits. A
+ * contributor cannot accidentally send us their own usage, and a fork cannot
+ * send us anything at all.
+ *
+ * `GRAFT_POSTHOG_KEY` overrides it at runtime so a maintainer can exercise the
+ * real path locally without publishing.
+ *
+ * Public project keys are write-only ingestion keys — they authorise capture and
+ * nothing else — which is why one may sit in a published artifact at all. It is
+ * still not committed here: an empty default is what makes "forks never send"
+ * true by construction rather than by policy.
+ */
+
+/** Rewritten at publish time. Do not hand-edit — see the module comment. */
+const BAKED_KEY = '';
+
+/**
+ * Nanonets' own PostHog host, not `us.i.posthog.com`.
+ *
+ * Every Nanonets product ingests through a nanonets.com proxy rather than
+ * PostHog directly, on one shared project token, so pointing graft at PostHog
+ * Cloud would put its events in a project nobody looks at.
+ *
+ * `events.` rather than `e.` because graft is server-side, and this is the host
+ * the other server-side integration already uses (the agents-platform Go
+ * backend sets `POSTHOG_HOST=https://events.nanonets.com`). The one documented
+ * objection to it — 400 `invalid_payload` — was gzip-compressed ingest from
+ * `posthog-js` in a browser, fixed there with `disable_compression: true`. We
+ * send plain uncompressed JSON from Node, so that failure mode cannot apply.
+ *
+ * Probed directly, that host answers 401 to a well-formed batch with a bad key,
+ * so it serves `/batch/` and parses the body — see the note in send.ts.
+ *
+ * The HOST is safe to commit; the KEY is not, and stays empty here. That
+ * asymmetry is the point: with no key, a fork built from this source sends
+ * nothing no matter where the host points.
+ */
+const BAKED_HOST = 'https://events.nanonets.com';
+
+export function posthogKey(): string {
+ return process.env.GRAFT_POSTHOG_KEY || BAKED_KEY;
+}
+
+export function posthogHost(): string {
+ return (process.env.GRAFT_POSTHOG_HOST || BAKED_HOST).replace(/\/+$/, '');
+}
diff --git a/src/telemetry/notice.ts b/src/telemetry/notice.ts
new file mode 100644
index 00000000..a9b01b62
--- /dev/null
+++ b/src/telemetry/notice.ts
@@ -0,0 +1,93 @@
+/**
+ * The one-time disclosure, and the `graft telemetry` command's output.
+ *
+ * The notice is the whole reason this design is defensible. Every telemetry
+ * backlash in the tools we looked at — the GitHub CLI's silent 2.91.0 rollout,
+ * Gatsby's on-by-default addition, the .NET SDK's opt-out that distributors now
+ * patch out — was about a tool that started sending without saying so. Homebrew
+ * does exactly what is done here and is uncontroversial: print once, in plain
+ * language, before anything leaves, and say how to turn it off in the same
+ * breath.
+ *
+ * Once per MACHINE, not per repo: a dev with twelve checkouts should read this
+ * one time. `graft init`'s picker is the other disclosure surface, for the users
+ * who see it — this catches everyone else.
+ */
+import { patchState, readState } from './identity.js';
+import { explainOff, offReason } from './gate.js';
+import { peek } from './queue.js';
+import { buildBatch } from './send.js';
+import { posthogHost } from './key.js';
+
+export const TELEMETRY_DOC_URL = 'https://github.com/NanoNets/context-graph-engine/blob/main/TELEMETRY.md';
+
+export const NOTICE = [
+ '· graft collects anonymous usage stats (no code, no file paths, no queries).',
+ ` What exactly: ${TELEMETRY_DOC_URL} — turn it off with \`graft telemetry disable\`.`,
+].join('\n');
+
+/**
+ * The notice text the first time it is due, then null forever after. Marks it as
+ * shown before returning, so two concurrent commands print it at most twice
+ * rather than every time.
+ */
+export function firstRunNotice(home?: string, env?: NodeJS.ProcessEnv): string | null {
+ try {
+ if (offReason(home, env) !== null) return null; // nothing to disclose if nothing can be sent
+ if (readState(home)?.noticeShownAt) return null;
+ patchState({ noticeShownAt: new Date().toISOString() }, home);
+ return NOTICE;
+ } catch {
+ return null;
+ }
+}
+
+/** `graft telemetry status`. `env` is a test seam, as elsewhere in this module —
+ * a real run must be gated on the real `DO_NOT_TRACK` and CI variables. */
+export function formatStatus(home?: string, env?: NodeJS.ProcessEnv): string {
+ const reason = offReason(home, env);
+ const pending = peek(home).length;
+ const lines = [
+ reason === null
+ ? 'telemetry: on — anonymous, aggregate-only'
+ : `telemetry: ${explainOff(reason)}`,
+ ` contract: ${TELEMETRY_DOC_URL}`,
+ ];
+ if (reason === null || reason === 'disabled') {
+ lines.push(` endpoint: ${posthogHost()}`);
+ lines.push(` queued: ${pending} event${pending === 1 ? '' : 's'} waiting for the next daily flush`);
+ }
+ lines.push(
+ reason === 'disabled'
+ ? ' enable: graft telemetry enable'
+ : ' disable: graft telemetry disable (or set DO_NOT_TRACK=1)',
+ );
+ lines.push(' inspect: graft telemetry debug (prints the exact batch, sends nothing)');
+ return lines.join('\n');
+}
+
+/**
+ * `graft telemetry debug` — Next.js's `NEXT_TELEMETRY_DEBUG` and Astro's
+ * `DEBUG=astro:telemetry` in command form. Prints the pending queue and the
+ * literal JSON body a flush would POST, and sends nothing. The point is that a
+ * user never has to take our word for the contract.
+ */
+export function formatDebug(home?: string): string {
+ const events = peek(home);
+ if (events.length === 0) {
+ return [
+ 'telemetry: nothing queued.',
+ ' Run a graft command first — events are written locally and flushed once a day.',
+ ].join('\n');
+ }
+ // A literal placeholder, never the key itself. This output is written to be
+ // pasted into an issue; the project key is not the user's to share and is not
+ // needed to audit what graft sends.
+ const body = { api_key: '<omitted — graft\'s own ingestion key>', ...buildBatch(events) };
+ return [
+ `telemetry: ${events.length} event(s) queued. This is the exact body a flush would POST`,
+ `to ${posthogHost()}/batch/ — running this command sends nothing.`,
+ '',
+ JSON.stringify(body, null, 2),
+ ].join('\n');
+}
diff --git a/src/telemetry/queue.ts b/src/telemetry/queue.ts
new file mode 100644
index 00000000..cf8019ae
--- /dev/null
+++ b/src/telemetry/queue.ts
@@ -0,0 +1,128 @@
+/**
+ * The local event queue: one NDJSON line per event in `~/.graft/`.
+ *
+ * The queue exists because graft is a CLI, not an app. Every other tool we
+ * studied sends from a process that is already running and can afford to wait;
+ * `graft ask` lives for two seconds and its whole value proposition is being
+ * faster than reading files. So nothing is ever sent inline — events are
+ * appended here, and a detached child (`graft _telemetry-flush`, once a day)
+ * does the network. A user who is offline for a week loses nothing; a user on a
+ * hostile network never notices, because no command ever waits on a socket.
+ *
+ * Concurrency: appends are a single `appendFileSync` of one short line to a file
+ * opened `O_APPEND`, which POSIX makes atomic below PIPE_BUF (4 KB — an event is
+ * ~300 bytes). Two graft processes interleaving cannot produce a torn line.
+ *
+ * Draining renames the file first and reads the renamed copy, so events appended
+ * during a flush land in a fresh queue instead of being dropped by the truncate.
+ */
+import { homedir } from 'node:os';
+import { join, dirname } from 'node:path';
+import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+
+/**
+ * The ceiling on the queue. An unflushable machine — permanently offline, or a
+ * key that never works — must not grow a file in someone's home forever.
+ *
+ * Bytes are the bound, because size is the only thing cheap enough to check on
+ * every append (one `statSync`); counting lines would mean reading the whole
+ * file each time. {@link TRIM_TO_EVENTS} is not a second ceiling — it is how
+ * FAR a trim cuts back, so a queue of unusually small events sheds a worthwhile
+ * amount rather than one line at a time. Between trims the file can hold more
+ * than that many events, and can exceed the byte bound by one append.
+ */
+export const MAX_QUEUE_BYTES = 256 * 1024;
+export const TRIM_TO_EVENTS = 500;
+
+export function queuePath(home: string = homedir()): string {
+ return join(home, '.graft', 'telemetry-queue.ndjson');
+}
+
+/**
+ * Append one event. Never throws — a full disk or a read-only home must not fail
+ * the command the user actually ran.
+ */
+export function enqueue(event: unknown, home?: string): void {
+ const path = queuePath(home);
+ try {
+ mkdirSync(dirname(path), { recursive: true });
+ appendFileSync(path, JSON.stringify(event) + '\n');
+ trim(path);
+ } catch { /* unwritable home, full disk — telemetry is never worth an error */ }
+}
+
+/**
+ * Enforce the cap by dropping the OLDEST events. Newest-wins because the recent
+ * ones describe the version the user is on now; a year-old queue from 0.9
+ * answers nothing. Only rewrites when actually over, so the common path is one
+ * `statSync`.
+ */
+function trim(path: string): void {
+ let size: number;
+ try { size = statSync(path).size; } catch { return; }
+ if (size <= MAX_QUEUE_BYTES) return;
+ try {
+ const lines = readFileSync(path, 'utf8').split('\n').filter(Boolean);
+ // Walk backwards from the newest, taking lines while both budgets hold, so
+ // the file left behind always satisfies the byte bound — a count-only trim
+ // would leave 500 large events well over it.
+ const kept: string[] = [];
+ let bytes = 0;
+ for (let i = lines.length - 1; i >= 0 && kept.length < TRIM_TO_EVENTS; i--) {
+ bytes += Buffer.byteLength(lines[i]) + 1;
+ if (bytes > MAX_QUEUE_BYTES) break;
+ kept.push(lines[i]);
+ }
+ kept.reverse();
+ writeFileSync(path, kept.length ? kept.join('\n') + '\n' : '');
+ } catch { /* leave it; the next drain clears it anyway */ }
+}
+
+/**
+ * Take everything pending, leaving an empty queue behind.
+ *
+ * The rename is what makes this safe against a concurrent append: from the
+ * instant it returns, other processes are writing to a brand-new file. Malformed
+ * lines are skipped rather than poisoning the batch — a torn write from a crash
+ * mid-append should cost one event, not the whole queue.
+ */
+export function drain(home?: string): unknown[] {
+ const path = queuePath(home);
+ const taken = `${path}.${process.pid}.sending`;
+ try { renameSync(path, taken); } catch { return []; } // nothing queued
+ let text = '';
+ try { text = readFileSync(taken, 'utf8'); } catch { /* fall through to cleanup */ }
+ try { rmSync(taken, { force: true }); } catch { /* best effort */ }
+ const out: unknown[] = [];
+ for (const line of text.split('\n')) {
+ if (!line.trim()) continue;
+ try { out.push(JSON.parse(line)); } catch { /* torn line — skip just this one */ }
+ }
+ return out;
+}
+
+/** Read without draining, for `graft telemetry debug`. */
+export function peek(home?: string): unknown[] {
+ const out: unknown[] = [];
+ let text = '';
+ try { text = readFileSync(queuePath(home), 'utf8'); } catch { return out; }
+ for (const line of text.split('\n')) {
+ if (!line.trim()) continue;
+ try { out.push(JSON.parse(line)); } catch { /* skip */ }
+ }
+ return out;
+}
+
+/** Put a failed batch back, so a flush that could not reach the network does not
+ * silently discard a week of events. Oldest-first, ahead of anything queued
+ * since the drain. */
+export function requeue(events: unknown[], home?: string): void {
+ if (events.length === 0) return;
+ const path = queuePath(home);
+ try {
+ const pending = (() => { try { return readFileSync(path, 'utf8'); } catch { return ''; } })();
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, events.map((e) => JSON.stringify(e)).join('\n') + '\n' + pending);
+ trim(path);
+ } catch { /* best effort */ }
+}
diff --git a/src/telemetry/send.ts b/src/telemetry/send.ts
new file mode 100644
index 00000000..5708ec93
--- /dev/null
+++ b/src/telemetry/send.ts
@@ -0,0 +1,91 @@
+/**
+ * The one network call in graft that is not an LLM request.
+ *
+ * A single POST of the whole queued batch to PostHog's capture endpoint, with
+ * `fetch` and no SDK. `posthog-node` would be the conventional choice, but it is
+ * a runtime dependency in a CLI whose install weight users notice, it wants to
+ * own batching and flushing (both of which the queue already does, and does
+ * differently because we are a short-lived process), and "an analytics library
+ * that can see everything" is precisely the objection this whole design exists
+ * to disarm. Twenty lines of `fetch` is auditable in a sitting.
+ *
+ * `$process_person_profile: false` on every event is what makes these ANONYMOUS
+ * events in PostHog: no person profile is created, no identity is stored, and
+ * the `distinct_id` is only ever the random install UUID.
+ */
+import { posthogKey, posthogHost } from './key.js';
+
+/** Anything longer and the detached child is just holding a socket open. */
+const SEND_TIMEOUT_MS = 8000;
+
+export interface SendResult {
+ ok: boolean;
+ status?: number;
+ /** Why it failed, for `graft telemetry debug` only — never itself reported. */
+ error?: string;
+}
+
+/**
+ * The events as PostHog wants them — everything the wire body contains EXCEPT
+ * the project key.
+ *
+ * The key is deliberately not in here. `graft telemetry debug` prints this
+ * object so a user can audit exactly what graft sends, and a command that exists
+ * to be pasted into a bug report must not also paste our ingestion key into it.
+ * `sendBatch` adds the key at the moment of the request and nowhere else, which
+ * keeps the key entirely out of every code path that can reach a terminal.
+ */
+export function buildBatch(events: unknown[]): Record<string, unknown> {
+ return {
+ batch: events.map((e) => {
+ const ev = e as { event: string; properties?: Record<string, string>; timestamp?: string; distinct_id?: string };
+ return {
+ event: ev.event,
+ timestamp: ev.timestamp,
+ properties: {
+ ...(ev.properties ?? {}),
+ distinct_id: ev.distinct_id,
+ // Anonymous event: PostHog stores it without creating a person.
+ $process_person_profile: false,
+ },
+ };
+ }),
+ };
+}
+
+/**
+ * The ingest path.
+ *
+ * `/batch/` only, with no fallback. An earlier revision also tried `/e/`,
+ * because assign's `frontend/src/lib/posthog.ts` documents `events.nanonets.com`
+ * as serving the older path and answering `400 invalid_payload` to bodies it
+ * will not take. Probed directly, that host returns **401** to a well-formed
+ * batch with a bad key — so `/batch/` is there and does parse the body, and the
+ * historical 400 was gzip from `posthog-js` in a browser, which we never send.
+ *
+ * The fallback was therefore a second request that could not fire, and a branch
+ * production never exercises is worse than no branch. If a future host needs
+ * `/e/`, point `GRAFT_POSTHOG_HOST` at it and add the path back with evidence.
+ */
+const INGEST_PATH = '/batch/';
+
+export async function sendBatch(events: unknown[]): Promise<SendResult> {
+ if (events.length === 0) return { ok: true };
+ const key = posthogKey();
+ if (!key) return { ok: false, error: 'no key' };
+ try {
+ const res = await fetch(`${posthogHost()}${INGEST_PATH}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ // The one place the key is ever attached: the request body itself.
+ body: JSON.stringify({ api_key: key, ...buildBatch(events) }),
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
+ });
+ // A 4xx is our bug (a bad key, a malformed body) and retrying it forever
+ // would pin the queue at its cap; only 5xx and transport errors go back on
+ // the queue — see shouldRequeue in flush.ts.
+ return { ok: res.ok, status: res.status };
+ } catch (e) {
+ return { ok: false, error: e instanceof Error ? e.name : 'unknown' };
+ }
+}
diff --git a/src/telemetry/sessions.ts b/src/telemetry/sessions.ts
new file mode 100644
index 00000000..12dca218
--- /dev/null
+++ b/src/telemetry/sessions.ts
@@ -0,0 +1,80 @@
+/**
+ * Rolling a finished agent session up into one `session_summary` event.
+ *
+ * This is the event that justifies the whole exercise. Everything else here
+ * counts commands; this one answers the question the product actually rests on —
+ * when an agent had both graft and grep available, which did it reach for, and
+ * how many tokens did that save? The counters already exist: the Claude Code
+ * hooks have been writing `graftReads`, `sourceReads` and `savedTokens` per
+ * session into `graft/.cache/session/` since well before telemetry did. Nothing
+ * new is measured here; a closed session is simply bucketed and queued.
+ *
+ * "Closed" is inferred from mtime rather than observed, because there is no
+ * reliable end-of-session hook — `Stop` fires per turn, and an editor that
+ * crashes fires nothing at all. A session untouched for two hours is over.
+ *
+ * Called from the session-start hook, which is the one place guaranteed to run
+ * again after a session ends. A hook must never touch the network (see the note
+ * atop upkeep.ts) and this doesn't: it only appends to the local queue.
+ */
+import { readdirSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { cacheDir } from '../util/state.js';
+import { readSession, writeSession } from '../claude/state.js';
+import { countBucket, savedTokensBucket } from './contract.js';
+import { track } from './track.js';
+import { telemetryOn } from './gate.js';
+
+/** Untouched for this long and the session is treated as over. */
+export const SESSION_IDLE_MS = 2 * 60 * 60 * 1000;
+
+/** Never roll up more than this in one hook run — a repo with a huge backlog of
+ * session files must not slow down a session start. The rest wait for the next. */
+const MAX_PER_RUN = 20;
+
+/**
+ * Queue a `session_summary` for every closed, not-yet-summarised session in this
+ * repo. Returns how many were queued (for tests). Never throws.
+ */
+export function flushClosedSessions(
+ repo: string,
+ now = Date.now(),
+ home?: string,
+ env?: NodeJS.ProcessEnv,
+): number {
+ try {
+ if (!telemetryOn(home, env)) return 0;
+ const dir = join(cacheDir(repo), 'session');
+ let files: string[];
+ try { files = readdirSync(dir).filter((f) => f.endsWith('.json')); } catch { return 0; }
+
+ let queued = 0;
+ for (const file of files.sort()) {
+ if (queued >= MAX_PER_RUN) break;
+ let mtime: number;
+ try { mtime = statSync(join(dir, file)).mtimeMs; } catch { continue; }
+ if (now - mtime < SESSION_IDLE_MS) continue;
+
+ const id = file.slice(0, -'.json'.length);
+ const s = readSession(repo, id);
+ if (s.summarized) continue;
+
+ // An empty session — opened, nothing asked — is still a fact worth having:
+ // it is the difference between "graft is installed" and "graft is used".
+ track(
+ 'session_summary',
+ {
+ graft_reads_bucket: countBucket(s.graftReads ?? 0),
+ source_reads_bucket: countBucket(s.sourceReads ?? 0),
+ saved_tokens_bucket: savedTokensBucket(s.savedTokens ?? 0),
+ },
+ { repo, host: 'claude-code', home, env },
+ );
+ writeSession(repo, id, { ...s, summarized: true });
+ queued++;
+ }
+ return queued;
+ } catch {
+ return 0; // a session start is never worth failing over a metric
+ }
+}
diff --git a/src/telemetry/track.ts b/src/telemetry/track.ts
new file mode 100644
index 00000000..f60a5a54
--- /dev/null
+++ b/src/telemetry/track.ts
@@ -0,0 +1,128 @@
+/**
+ * `track()` — the only way an event is ever created, and the place the contract
+ * is enforced.
+ *
+ * Call sites pass a name and some properties; this drops anything the contract
+ * (contract.ts) does not list, stamps the common properties, and appends to the
+ * local queue. It never sends, never blocks, and never throws — a telemetry bug
+ * must be incapable of failing a build or a query.
+ *
+ * Two rules do the actual privacy work, and both are enforced here rather than
+ * asked of callers:
+ *
+ * • unknown event → dropped whole; unknown property key → dropped, the rest of
+ * the event survives. A careless `track('query', { path })` sends `query`
+ * without a path.
+ * • non-string values → dropped. Everything that crosses the wire is a bucket
+ * label or an enum member, so a raw count or a raw message cannot get out
+ * even under a key that happens to be allowed.
+ */
+import { EVENTS } from './contract.js';
+import type { AgentHost } from './contract.js';
+import { enqueue } from './queue.js';
+import { telemetryOn } from './gate.js';
+import { installId, repoId } from './identity.js';
+import { runningVersion } from '../upkeep.js';
+
+/** One queued event, exactly as it will be sent. */
+export interface QueuedEvent {
+ event: string;
+ properties: Record<string, string>;
+ /** ISO timestamp, so a batch flushed a day late still lands on the right day. */
+ timestamp: string;
+ /** The install id, used as PostHog's `distinct_id` at send time. */
+ distinct_id: string;
+}
+
+export interface TrackContext {
+ /** Repo root, when the call site has one — supplies `repo_id`. */
+ repo?: string;
+ /** Which surface is calling. Defaults to the CLI. */
+ host?: AgentHost;
+ /** Test seam: a scratch `$HOME`. Production callers never pass this. */
+ home?: string;
+ /** Test seam: an environment to gate against. Production callers never pass
+ * this — a real run must be gated on the real `DO_NOT_TRACK` and `CI`. */
+ env?: NodeJS.ProcessEnv;
+}
+
+/**
+ * Which agent graft is running under, from the surface plus one env probe.
+ *
+ * Only the PRESENCE of `CLAUDECODE` is read, never its value — the distinction
+ * matters: a value could be anything a user's shell profile put there, presence
+ * is a boolean. Anything unrecognised is `cli`, which is the honest answer.
+ */
+export function detectHost(explicit?: AgentHost, env: NodeJS.ProcessEnv = process.env): AgentHost {
+ if (explicit) return explicit;
+ if (env.CLAUDECODE !== undefined) return 'claude-code';
+ return 'cli';
+}
+
+/** The properties every event carries. Kept in one place so no call site can
+ * disagree about them. */
+function commonProps(ctx: TrackContext): Record<string, string> {
+ const props: Record<string, string> = {
+ app_version: runningVersion(),
+ os: process.platform,
+ arch: process.arch,
+ node_major: String(process.versions.node.split('.')[0]),
+ ci: 'false', // an event only exists at all when the CI gate passed
+ agent_host: detectHost(ctx.host, ctx.env ?? process.env),
+ };
+ if (ctx.repo) {
+ try { props.repo_id = repoId(ctx.repo); } catch { /* unwritable cache — omit */ }
+ }
+ return props;
+}
+
+/**
+ * Record one event, if the contract allows it and the gates are open.
+ *
+ * Returns the event that was queued, or null — the return value exists for
+ * tests and for `graft telemetry debug`, not for control flow at call sites.
+ */
+export function track(
+ event: string,
+ props: Record<string, string | undefined> = {},
+ ctx: TrackContext = {},
+): QueuedEvent | null {
+ try {
+ if (!telemetryOn(ctx.home, ctx.env)) return null;
+ // `Object.hasOwn`, not `EVENTS[event]`: a bare object literal inherits from
+ // Object.prototype, so `EVENTS['constructor']` is truthy and would sail past
+ // a plain existence check — only failing later, on a TypeError swallowed by
+ // the catch below. The allowlist must reject by design, not by exception.
+ if (!Object.hasOwn(EVENTS, event)) return null;
+ const allowed = EVENTS[event];
+
+ const properties = commonProps(ctx);
+ for (const [k, v] of Object.entries(props)) {
+ if (allowed.has(k) && typeof v === 'string') properties[k] = v;
+ }
+
+ const queued: QueuedEvent = {
+ event,
+ properties,
+ timestamp: new Date().toISOString(),
+ distinct_id: installId(ctx.home).id,
+ };
+ enqueue(queued, ctx.home);
+ return queued;
+ } catch {
+ return null; // telemetry never surfaces as a user-visible failure
+ }
+}
+
+/**
+ * The `first_run` event, fired the once. Separate from `track` because it is the
+ * only event whose trigger is "the id did not exist a moment ago", which only
+ * `installId()` can know.
+ */
+export function trackFirstRunIfNew(ctx: TrackContext = {}): void {
+ try {
+ if (!telemetryOn(ctx.home, ctx.env)) return;
+ if (!installId(ctx.home).firstRun) return;
+ track('first_run', {}, ctx);
+ } catch { /* never */ }
+}
diff --git a/test/cli-picker.test.ts b/test/cli-picker.test.ts
index 50120ece..0de3d9d3 100644
--- a/test/cli-picker.test.ts
+++ b/test/cli-picker.test.ts
@@ -7,7 +7,8 @@ import { planInit } from '../src/hosts/plan.js';
import {
KEY_CTRL_C, KEY_DOWN, KEY_ESC, KEY_UP,
describeWrites, formatNonInteractiveHelp, formatPlan, initialPickerState,
- keyOf, keysOf, pickedIds, reducePicker, renderPicker, tilde,
+ keyOf, keysOf, pickedHostIds, pickedIds, pickedTelemetry, reducePicker, renderPicker, tilde,
+ TELEMETRY_ROW_ID,
type PickerKey,
} from '../src/cli-picker.js';
@@ -220,3 +221,68 @@ test('formatNonInteractiveHelp still helps when nothing was detected', () => {
assert.doesNotMatch(text, /^ +graft init --yes/m);
assert.match(text, /--agents claude/);
});
+
+// --- the telemetry consent row ---
+
+/** Same driver, but with the consent row offered. */
+function driveWithConsent(repo: string, home: string, keys: PickerKey[]) {
+ let state = initialPickerState(planInit(repo, { home }), repo, home, { offerTelemetry: true });
+ for (const k of keys) state = reducePicker(state, k);
+ return state;
+}
+
+test('the consent row is absent unless it is offered', () => {
+ const repo = fresh(); const home = fullHome();
+ const state = initialPickerState(planInit(repo, { home }), repo, home);
+ assert.equal(state.rows.some((r) => r.id === TELEMETRY_ROW_ID), false);
+ assert.equal(pickedTelemetry(state), undefined, 'not offered means no answer, not "no"');
+});
+
+test('when offered, the consent row is last and starts checked', () => {
+ const repo = fresh(); const home = fullHome();
+ const state = initialPickerState(planInit(repo, { home }), repo, home, { offerTelemetry: true });
+ assert.equal(state.rows.at(-1)?.id, TELEMETRY_ROW_ID);
+ assert.equal(state.rows.at(-1)?.kind, 'setting');
+ assert.equal(pickedTelemetry(state), true);
+});
+
+test('unchecking the row is how a user declines', () => {
+ const repo = fresh(); const home = fullHome();
+ // Up from the first row wraps onto the consent row, which is last.
+ const state = driveWithConsent(repo, home, ['up', 'space']);
+ assert.equal(pickedTelemetry(state), false);
+});
+
+test('the consent row is never returned as an agent to wire', () => {
+ const repo = fresh(); const home = fullHome();
+ const state = driveWithConsent(repo, home, ['all']);
+ assert.equal(pickedHostIds(state).includes(TELEMETRY_ROW_ID), false);
+ assert.equal(pickedIds(state).includes(TELEMETRY_ROW_ID), true, 'pickedIds keeps its old meaning');
+});
+
+test('a (toggle all) is about agents and leaves the consent answer alone', () => {
+ const repo = fresh(); const home = fullHome();
+ const n = planInit(repo, { home }).length;
+ // On: every agent selected, consent still the default yes.
+ const on = driveWithConsent(repo, home, ['all']);
+ assert.equal(pickedHostIds(on).length, n);
+ assert.equal(pickedTelemetry(on), true);
+ // Off: no agents, and the consent answer is STILL untouched — "wire nothing"
+ // is not the same statement as "share nothing".
+ const off = driveWithConsent(repo, home, ['all', 'all']);
+ assert.deepEqual(pickedHostIds(off), []);
+ assert.equal(pickedTelemetry(off), true);
+ // And a user who explicitly declined keeps that through a toggle-all.
+ const declined = driveWithConsent(repo, home, ['up', 'space', 'all']);
+ assert.equal(pickedTelemetry(declined), false);
+});
+
+test('the rendered row shows the label, a rule, and what is not collected', () => {
+ const repo = fresh(); const home = fullHome();
+ const out = renderPicker(initialPickerState(planInit(repo, { home }), repo, home, { offerTelemetry: true }), false);
+ assert.match(out, /\[x\] anonymous usage stats/);
+ assert.match(out, /no code, no file paths, no queries/);
+ assert.match(out, /TELEMETRY\.md/);
+ assert.equal(out.includes(TELEMETRY_ROW_ID), false, 'the internal id must never be shown');
+ assert.match(out, /─/, 'a rule separates the settings from the agents');
+});
diff --git a/test/telemetry-contract.test.ts b/test/telemetry-contract.test.ts
new file mode 100644
index 00000000..423d3c79
--- /dev/null
+++ b/test/telemetry-contract.test.ts
@@ -0,0 +1,171 @@
+/**
+ * The contract tests. These are the ones that matter: they assert that a call
+ * site cannot send something the published `TELEMETRY.md` does not list, even if
+ * it tries.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ EVENTS,
+ countBucket,
+ durationBucket,
+ errorCode,
+ filesBucket,
+ isTrackedCommand,
+ langsValue,
+ savedTokensBucket,
+} from '../src/telemetry/contract.js';
+import { track } from '../src/telemetry/track.js';
+import { peek } from '../src/telemetry/queue.js';
+import { tmpRepo } from './helpers.js';
+
+/** An env where every gate is open, so the allowlist is what's under test. */
+const OPEN: NodeJS.ProcessEnv = {};
+
+function sandbox(tag: string): string {
+ const home = tmpRepo(tag);
+ mkdirSync(join(home, '.graft'), { recursive: true });
+ process.env.GRAFT_POSTHOG_KEY = 'phc_test_key';
+ return home;
+}
+
+// --- the allowlist ---
+
+test('an event that is not in the contract is dropped whole', () => {
+ const home = sandbox('tel-unknown-event');
+ assert.equal(track('exfiltrate', { anything: 'here' }, { home, env: OPEN }), null);
+ assert.deepEqual(peek(home), []);
+});
+
+test('an unlisted property is dropped, and the rest of the event survives', () => {
+ const home = sandbox('tel-unknown-prop');
+ const ev = track(
+ 'query',
+ { command: 'ask', surface: 'cli', path: '/Users/someone/secret/repo/src/auth.ts' },
+ { home, env: OPEN },
+ );
+ assert.ok(ev);
+ assert.equal(ev.properties.command, 'ask');
+ assert.equal(ev.properties.surface, 'cli');
+ assert.equal('path' in ev.properties, false, 'a path must never survive the allowlist');
+ assert.equal(JSON.stringify(ev).includes('secret'), false);
+});
+
+test('a non-string value is dropped even under an allowed key', () => {
+ const home = sandbox('tel-nonstring');
+ // A caller passing a raw count instead of a bucket: the key is legal, the
+ // value is not, and the raw number must not reach the wire.
+ const ev = track('build_completed', { files_bucket: 4127 as unknown as string }, { home, env: OPEN });
+ assert.ok(ev);
+ assert.equal('files_bucket' in ev.properties, false);
+});
+
+test('every event carries the common properties, and no identifier beyond them', () => {
+ const home = sandbox('tel-common');
+ const ev = track('first_run', {}, { home, env: OPEN });
+ assert.ok(ev);
+ for (const k of ['app_version', 'os', 'arch', 'node_major', 'ci', 'agent_host']) {
+ assert.ok(k in ev.properties, `missing common property ${k}`);
+ }
+ // distinct_id is the random install uuid and nothing else.
+ assert.match(ev.distinct_id, /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
+});
+
+test('the contract lists exactly the six documented events', () => {
+ assert.deepEqual(Object.keys(EVENTS).sort(), [
+ 'build_completed', 'build_failed', 'first_run', 'init_completed', 'query', 'session_summary',
+ ]);
+});
+
+test('only the known commands are tracked', () => {
+ assert.equal(isTrackedCommand('ask'), true);
+ assert.equal(isTrackedCommand('init'), false, 'init has its own event, not a query');
+ assert.equal(isTrackedCommand('telemetry'), false);
+ assert.equal(isTrackedCommand('_telemetry-flush'), false);
+});
+
+// --- buckets: no raw number ever crosses ---
+
+test('filesBucket collapses a repo size to a label', () => {
+ assert.equal(filesBucket(0), '0');
+ assert.equal(filesBucket(1), '1-49');
+ assert.equal(filesBucket(49), '1-49');
+ assert.equal(filesBucket(50), '50-199');
+ assert.equal(filesBucket(999), '200-999');
+ assert.equal(filesBucket(4999), '1000-4999');
+ assert.equal(filesBucket(5000), '5000+');
+});
+
+test('durationBucket collapses wall-clock to a label', () => {
+ assert.equal(durationBucket(999), '<1s');
+ assert.equal(durationBucket(1000), '1-5s');
+ assert.equal(durationBucket(29_999), '5-30s');
+ assert.equal(durationBucket(600_000), '10m+');
+});
+
+test('countBucket and savedTokensBucket cover their boundaries', () => {
+ assert.equal(countBucket(0), '0');
+ assert.equal(countBucket(4), '1-4');
+ assert.equal(countBucket(5), '5-19');
+ assert.equal(countBucket(200), '200+');
+ assert.equal(savedTokensBucket(0), '0');
+ assert.equal(savedTokensBucket(999), '<1k');
+ assert.equal(savedTokensBucket(1000), '1-5k');
+ assert.equal(savedTokensBucket(100_000), '100k+');
+});
+
+test('langsValue sorts, dedupes and caps so it cannot fingerprint a repo', () => {
+ assert.equal(langsValue(['ts', 'go', 'TS']), 'go,ts');
+ assert.equal(langsValue([]), '');
+ assert.equal(langsValue(['a','b','c','d','e','f','g','h','i','j']).split(',').length, 8);
+});
+
+// --- error codes: a message is never a code ---
+
+test('errorCode maps to the enum and never returns the message', () => {
+ const err = new Error('cannot parse /Users/someone/private/src/secrets.ts:42');
+ assert.equal(errorCode(err), 'E_PARSE');
+ assert.equal(errorCode(Object.assign(new Error('x'), { code: 'EACCES' })), 'E_PERMISSION');
+ assert.equal(errorCode(Object.assign(new Error('x'), { status: 429 })), 'E_RATE_LIMIT');
+ assert.equal(errorCode(new Error('something nobody classified')), 'E_UNKNOWN');
+});
+
+test('a build_failed event carries a code, never the error text', () => {
+ const home = sandbox('tel-build-failed');
+ const err = new Error('ENOENT: /Users/someone/private-repo/src/index.ts');
+ const ev = track('build_failed', { stage: 'graph', code: errorCode(err) }, { home, env: OPEN });
+ assert.ok(ev);
+ assert.equal(JSON.stringify(ev).includes('private-repo'), false);
+ assert.equal(ev.properties.stage, 'graph');
+});
+
+// --- the allowlist must reject by design, not by exception ---
+
+test('a prototype key is not an event: EVENTS.constructor must not look like a hit', () => {
+ const home = sandbox('tel-proto-event');
+ for (const name of ['constructor', 'toString', '__proto__', 'hasOwnProperty', 'valueOf']) {
+ assert.equal(track(name, { command: 'ask' }, { home, env: OPEN }), null, `${name} was accepted`);
+ }
+ assert.deepEqual(peek(home), []);
+});
+
+test('a prototype key as a PROPERTY name is dropped like any other unlisted key', () => {
+ const home = sandbox('tel-proto-prop');
+ const ev = track('query', { command: 'ask', __proto__: 'x', constructor: 'y' } as never, { home, env: OPEN });
+ assert.ok(ev);
+ assert.equal(ev.properties.command, 'ask');
+ assert.equal(Object.hasOwn(ev.properties, 'constructor'), false);
+});
+
+test('langsValue drops anything that is not a plain language token', () => {
+ // The failure this guards: a value that carries file or path metadata rather
+ // than a language name.
+ assert.equal(langsValue(['ts', 'src/secret project/auth.ts']), 'ts');
+ assert.equal(langsValue(['go', 'a'.repeat(40)]), 'go');
+ assert.equal(langsValue(['ts', '../../etc/passwd']), 'ts');
+ assert.equal(langsValue(['ts', 'my repo']), 'ts', 'a space is not a language token');
+ // Real language labels survive, including the awkward ones.
+ assert.equal(langsValue(['c++', 'c#', 'objective-c', 'f#']), 'c#,c++,f#,objective-c');
+});
diff --git a/test/telemetry-gate.test.ts b/test/telemetry-gate.test.ts
new file mode 100644
index 00000000..72726ec1
--- /dev/null
+++ b/test/telemetry-gate.test.ts
@@ -0,0 +1,83 @@
+/**
+ * The four gates. Each one is tested alone, because the value of the design is
+ * that any single one of them is sufficient to stop everything.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { doNotTrack, explainOff, inCi, offReason, telemetryOn } from '../src/telemetry/gate.js';
+import { track } from '../src/telemetry/track.js';
+import { peek } from '../src/telemetry/queue.js';
+import { tmpRepo } from './helpers.js';
+
+const KEY = 'phc_test_key';
+
+function home(tag: string, state?: Record<string, unknown>): string {
+ const dir = tmpRepo(tag);
+ mkdirSync(join(dir, '.graft'), { recursive: true });
+ if (state) writeFileSync(join(dir, '.graft', 'telemetry.json'), JSON.stringify(state));
+ return dir;
+}
+
+test('no key: a fork or a local build can never send, whatever the settings say', () => {
+ const h = home('gate-nokey', { installId: 'x', enabled: true });
+ delete process.env.GRAFT_POSTHOG_KEY;
+ assert.equal(offReason(h, {}), 'no-key');
+ assert.equal(track('first_run', {}, { home: h, env: {} }), null);
+ assert.deepEqual(peek(h), []);
+});
+
+test('DO_NOT_TRACK outranks our own setting', () => {
+ process.env.GRAFT_POSTHOG_KEY = KEY;
+ const h = home('gate-dnt', { installId: 'x', enabled: true });
+ assert.equal(offReason(h, { DO_NOT_TRACK: '1' }), 'do-not-track');
+ assert.equal(track('first_run', {}, { home: h, env: { DO_NOT_TRACK: '1' } }), null);
+});
+
+test('DO_NOT_TRACK=0 and an empty value mean "not set"', () => {
+ assert.equal(doNotTrack({ DO_NOT_TRACK: '0' }), false);
+ assert.equal(doNotTrack({ DO_NOT_TRACK: '' }), false);
+ assert.equal(doNotTrack({}), false);
+ assert.equal(doNotTrack({ DO_NOT_TRACK: 'true' }), true);
+});
+
+test('CI is never counted as a user', () => {
+ process.env.GRAFT_POSTHOG_KEY = KEY;
+ const h = home('gate-ci', { installId: 'x' });
+ assert.equal(offReason(h, { CI: 'true' }), 'ci');
+ assert.equal(offReason(h, { GITHUB_ACTIONS: 'true' }), 'ci');
+ assert.equal(inCi({ CI: 'false' }), false, 'CI=false is not CI');
+ assert.equal(inCi({ CI: '0' }), false);
+});
+
+test('the user switch turns everything off', () => {
+ process.env.GRAFT_POSTHOG_KEY = KEY;
+ const h = home('gate-disabled', { installId: 'x', enabled: false });
+ assert.equal(offReason(h, {}), 'disabled');
+ assert.equal(track('query', { command: 'ask' }, { home: h, env: {} }), null);
+ assert.deepEqual(peek(h), []);
+});
+
+test('all four open: the event is recorded', () => {
+ process.env.GRAFT_POSTHOG_KEY = KEY;
+ const h = home('gate-open', { installId: 'x', enabled: true });
+ assert.equal(offReason(h, {}), null);
+ assert.equal(telemetryOn(h, {}), true);
+ assert.ok(track('query', { command: 'ask', surface: 'cli' }, { home: h, env: {} }));
+ assert.equal(peek(h).length, 1);
+});
+
+test('never chosen means on — the documented default', () => {
+ process.env.GRAFT_POSTHOG_KEY = KEY;
+ const h = home('gate-default', { installId: 'x' }); // no `enabled` field
+ assert.equal(offReason(h, {}), null);
+});
+
+test('every reason has a sentence naming the switch that is closed', () => {
+ for (const r of ['no-key', 'do-not-track', 'ci', 'disabled'] as const) {
+ assert.match(explainOff(r), /^off — \S/);
+ }
+ assert.match(explainOff('do-not-track'), /DO_NOT_TRACK/);
+ assert.match(explainOff('disabled'), /graft telemetry enable/);
+});
diff --git a/test/telemetry-identity.test.ts b/test/telemetry-identity.test.ts
new file mode 100644
index 00000000..843b6e15
--- /dev/null
+++ b/test/telemetry-identity.test.ts
@@ -0,0 +1,83 @@
+/**
+ * The identifiers. The claim being tested is narrow and important: both ids are
+ * random, both are stable, and neither is derived from anything about the user,
+ * the machine, or the repository.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { join } from 'node:path';
+import { installId, patchState, readState, repoId, statePath } from '../src/telemetry/identity.js';
+import { tmpRepo } from './helpers.js';
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
+
+test('the install id is a random uuid, minted once and then stable', () => {
+ const home = tmpRepo('id-install');
+ const first = installId(home);
+ assert.match(first.id, UUID);
+ assert.equal(first.firstRun, true);
+ const second = installId(home);
+ assert.equal(second.id, first.id);
+ assert.equal(second.firstRun, false, 'first_run fires exactly once per machine');
+});
+
+test('two machines get unrelated ids — nothing is derived from the environment', () => {
+ const a = installId(tmpRepo('id-a')).id;
+ const b = installId(tmpRepo('id-b')).id;
+ assert.notEqual(a, b);
+});
+
+test('the repo id is random, not a hash of the git remote', () => {
+ const repo = tmpRepo('id-repo');
+ execFileSync('git', ['init', '-q'], { cwd: repo });
+ execFileSync('git', ['remote', 'add', 'origin', 'https://github.com/acme/secret-repo.git'], { cwd: repo });
+ const id = repoId(repo);
+ assert.match(id, UUID);
+ assert.equal(id, repoId(repo), 'stable across calls');
+ // The whole point of random-over-hashed: we could not confirm a guess at the
+ // remote even if we tried, because the id has no relationship to it.
+ const stored = readFileSync(join(repo, 'graft', '.cache', 'telemetry-repo-id.json'), 'utf8');
+ assert.equal(stored.includes('acme'), false);
+ assert.equal(stored.includes('secret-repo'), false);
+});
+
+test('two checkouts of the same repo look like two repos', () => {
+ const a = repoId(tmpRepo('id-clone-a'));
+ const b = repoId(tmpRepo('id-clone-b'));
+ assert.notEqual(a, b);
+});
+
+test('minting the repo id does not touch .gitignore or any tracked file', () => {
+ const repo = tmpRepo('id-no-gitignore');
+ writeFileSync(join(repo, '.gitignore'), 'node_modules\n');
+ repoId(repo);
+ assert.equal(readFileSync(join(repo, '.gitignore'), 'utf8'), 'node_modules\n');
+});
+
+test('an unwritable home yields an ephemeral id rather than throwing', () => {
+ // A "home" that is actually a file: every write beneath it must fail.
+ const dir = tmpRepo('id-unwritable');
+ const blocked = join(dir, 'blocker');
+ writeFileSync(blocked, 'x');
+ const r = installId(blocked);
+ assert.match(r.id, UUID);
+ assert.equal(r.firstRun, false, 'a machine that cannot persist must not re-send first_run forever');
+});
+
+test('patchState merges rather than replacing', () => {
+ const home = tmpRepo('id-patch');
+ mkdirSync(join(home, '.graft'), { recursive: true });
+ installId(home);
+ patchState({ enabled: false }, home);
+ patchState({ noticeShownAt: '2026-01-01T00:00:00Z' }, home);
+ const st = readState(home);
+ assert.equal(st?.enabled, false);
+ assert.equal(st?.noticeShownAt, '2026-01-01T00:00:00Z');
+ assert.match(st?.installId ?? '', UUID, 'the id survives every patch');
+});
+
+test('state lives in ~/.graft, beside the update-check cache', () => {
+ assert.equal(statePath('/home/x'), join('/home/x', '.graft', 'telemetry.json'));
+});
diff --git a/test/telemetry-notice.test.ts b/test/telemetry-notice.test.ts
new file mode 100644
index 00000000..df7529e1
--- /dev/null
+++ b/test/telemetry-notice.test.ts
@@ -0,0 +1,127 @@
+/**
+ * The disclosure. Every telemetry backlash in the tools this design was drawn
+ * from was about a tool that started sending without saying so, which makes
+ * these the tests that protect the project rather than the user's data.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { firstRunNotice, formatDebug, formatStatus } from '../src/telemetry/notice.js';
+import { buildBatch } from '../src/telemetry/send.js';
+import { enqueue } from '../src/telemetry/queue.js';
+import { readState } from '../src/telemetry/identity.js';
+import { tmpRepo } from './helpers.js';
+
+/**
+ * An env with every gate open. Passed explicitly rather than mutating
+ * `process.env`: this suite runs in CI, where `GITHUB_ACTIONS` alone is enough
+ * to suppress the notice — which is the correct product behaviour, and exactly
+ * what a test of the notice must not be subject to.
+ */
+const OPEN: NodeJS.ProcessEnv = {};
+
+function home(tag: string, state?: Record<string, unknown>): string {
+ const dir = tmpRepo(tag);
+ mkdirSync(join(dir, '.graft'), { recursive: true });
+ if (state) writeFileSync(join(dir, '.graft', 'telemetry.json'), JSON.stringify(state));
+ process.env.GRAFT_POSTHOG_KEY = 'phc_test_key';
+ return dir;
+}
+
+test('the notice prints once per machine, then never again', () => {
+ const h = home('notice-once', { installId: 'x' });
+ const first = firstRunNotice(h, OPEN);
+ assert.ok(first, 'the first run must disclose');
+ assert.match(first, /anonymous/);
+ assert.match(first, /graft telemetry disable/);
+ assert.match(first, /TELEMETRY\.md/);
+ assert.equal(firstRunNotice(h, OPEN), null);
+ assert.equal(firstRunNotice(h, OPEN), null);
+ assert.ok(readState(h)?.noticeShownAt);
+});
+
+test('the notice says what is NOT collected, in the first line a user reads', () => {
+ const h = home('notice-says-what', { installId: 'x' });
+ assert.match(firstRunNotice(h, OPEN) ?? '', /no code, no file paths, no queries/);
+});
+
+test('nothing is disclosed when nothing can be sent', () => {
+ // A fork: no key, so there is no collection to announce and announcing one
+ // would be worse than saying nothing.
+ const h = home('notice-nokey', { installId: 'x' });
+ delete process.env.GRAFT_POSTHOG_KEY;
+ assert.equal(firstRunNotice(h, OPEN), null);
+ assert.equal(readState(h)?.noticeShownAt, undefined, 'and the notice stays pending');
+});
+
+test('status names the switch that is actually closed', () => {
+ const h = home('notice-status-off', { installId: 'x', enabled: false });
+ const out = formatStatus(h, OPEN);
+ assert.match(out, /telemetry: off/);
+ assert.match(out, /graft telemetry enable/);
+});
+
+test('status shows the endpoint and the pending count when it is on', () => {
+ const h = home('notice-status-on', { installId: 'x' });
+ enqueue({ event: 'query' }, h);
+ const out = formatStatus(h, OPEN);
+ assert.match(out, /telemetry: on/);
+ assert.match(out, /1 event waiting/);
+ assert.match(out, /https:\/\//);
+ assert.match(out, /graft telemetry debug/);
+});
+
+test('debug prints the exact batch and sends nothing', () => {
+ const h = home('notice-debug', { installId: 'x' });
+ enqueue({ event: 'query', properties: { command: 'ask' }, distinct_id: 'abc', timestamp: '2026-01-01T00:00:00Z' }, h);
+ const out = formatDebug(h);
+ assert.match(out, /sends nothing/);
+ const body = JSON.parse(out.slice(out.indexOf('{')));
+ assert.equal(body.batch.length, 1);
+ assert.equal(body.batch[0].event, 'query');
+ assert.equal(body.batch[0].properties.$process_person_profile, false, 'anonymous event');
+ assert.equal(body.batch[0].properties.distinct_id, 'abc');
+});
+
+test('debug never prints the project key — this output is written to be pasted into an issue', () => {
+ const h = home('notice-debug-key', { installId: 'x' });
+ process.env.GRAFT_POSTHOG_KEY = 'phc_do_not_print_me';
+ enqueue({ event: 'query', properties: { command: 'ask' }, distinct_id: 'abc' }, h);
+ const out = formatDebug(h);
+ assert.equal(out.includes('phc_do_not_print_me'), false, 'the ingestion key leaked into terminal output');
+ // The field is still shown, so the output is an honest picture of the request.
+ assert.match(out, /"api_key": "<omitted/);
+});
+
+test('buildBatch itself carries no key, so no logging path can reach one', () => {
+ process.env.GRAFT_POSTHOG_KEY = 'phc_do_not_print_me';
+ const batch = buildBatch([{ event: 'query', properties: {}, distinct_id: 'abc' }]);
+ assert.equal('api_key' in batch, false);
+ assert.equal(JSON.stringify(batch).includes('phc_do_not_print_me'), false);
+});
+
+test('status prints the endpoint but never the key', () => {
+ const h = home('notice-status-key', { installId: 'x' });
+ process.env.GRAFT_POSTHOG_KEY = 'phc_do_not_print_me';
+ assert.equal(formatStatus(h, OPEN).includes('phc_do_not_print_me'), false);
+});
+
+test('debug on an empty queue explains rather than printing an empty batch', () => {
+ assert.match(formatDebug(home('notice-debug-empty', { installId: 'x' })), /nothing queued/);
+});
+
+test('CI gets no notice — there is no one there to read a disclosure', () => {
+ const h = home('notice-ci', { installId: 'x' });
+ assert.equal(firstRunNotice(h, { GITHUB_ACTIONS: 'true' }), null);
+ assert.equal(firstRunNotice(h, { CI: 'true' }), null);
+ assert.equal(readState(h)?.noticeShownAt, undefined, 'and it stays pending for a real run');
+ // A real run on the same machine still gets it.
+ assert.ok(firstRunNotice(h, OPEN));
+});
+
+test('DO_NOT_TRACK gets no notice either', () => {
+ const h = home('notice-dnt', { installId: 'x' });
+ assert.equal(firstRunNotice(h, { DO_NOT_TRACK: '1' }), null);
+ assert.match(formatStatus(h, { DO_NOT_TRACK: '1' }), /DO_NOT_TRACK/);
+});
diff --git a/test/telemetry-queue.test.ts b/test/telemetry-queue.test.ts
new file mode 100644
index 00000000..d2773006
--- /dev/null
+++ b/test/telemetry-queue.test.ts
@@ -0,0 +1,107 @@
+/**
+ * The queue: the reason no graft command ever waits on a socket. Its contract is
+ * "append cheaply, drain exactly once, and never grow without bound".
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { MAX_QUEUE_BYTES, drain, enqueue, peek, queuePath, requeue } from '../src/telemetry/queue.js';
+import { shouldRequeue } from '../src/telemetry/flush.js';
+import { tmpRepo } from './helpers.js';
+
+function home(tag: string): string {
+ const dir = tmpRepo(tag);
+ mkdirSync(join(dir, '.graft'), { recursive: true });
+ return dir;
+}
+
+test('enqueue then drain returns the events and leaves the queue empty', () => {
+ const h = home('q-roundtrip');
+ enqueue({ event: 'a' }, h);
+ enqueue({ event: 'b' }, h);
+ assert.deepEqual(drain(h), [{ event: 'a' }, { event: 'b' }]);
+ assert.deepEqual(drain(h), [], 'a second drain finds nothing');
+});
+
+test('draining an empty or missing queue is not an error', () => {
+ assert.deepEqual(drain(home('q-empty')), []);
+});
+
+test('peek reads without draining', () => {
+ const h = home('q-peek');
+ enqueue({ event: 'a' }, h);
+ assert.equal(peek(h).length, 1);
+ assert.equal(peek(h).length, 1);
+ assert.equal(drain(h).length, 1);
+});
+
+test('a torn line costs one event, not the whole batch', () => {
+ const h = home('q-torn');
+ enqueue({ event: 'good1' }, h);
+ appendFileSync(queuePath(h), '{"event":"tor\n'); // a crash mid-append
+ enqueue({ event: 'good2' }, h);
+ assert.deepEqual(drain(h), [{ event: 'good1' }, { event: 'good2' }]);
+});
+
+test('the cap drops the OLDEST events, keeping the recent ones', () => {
+ const h = home('q-cap');
+ // Big enough payloads to blow past MAX_QUEUE_BYTES well before the count cap.
+ for (let i = 0; i < 900; i++) enqueue({ event: 'e', i, pad: 'x'.repeat(400) }, h);
+ const raw = readFileSync(queuePath(h), 'utf8');
+ const kept = drain(h) as { i: number }[];
+ // Bytes are the bound — plus at most the one append that triggered the trim.
+ // The event count is deliberately NOT asserted: trimming is size-triggered, so
+ // between trims the file legitimately holds more than TRIM_TO_EVENTS lines.
+ assert.ok(Buffer.byteLength(raw) <= MAX_QUEUE_BYTES + 1024, `queue was ${Buffer.byteLength(raw)} bytes`);
+ assert.ok(kept.length < 900, `nothing was dropped: kept ${kept.length}`);
+ assert.equal(kept.at(-1)?.i, 899, 'the newest event survives');
+ assert.ok((kept[0]?.i ?? 0) > 0, 'the oldest events were the ones dropped');
+});
+
+test('the byte bound holds even for events far larger than average', () => {
+ const h = home('q-cap-big');
+ for (let i = 0; i < 200; i++) enqueue({ event: 'e', i, pad: 'x'.repeat(8000) }, h);
+ const kept = drain(h);
+ const bytes = kept.reduce((n, e) => n + Buffer.byteLength(JSON.stringify(e)) + 1, 0);
+ assert.ok(bytes <= MAX_QUEUE_BYTES + 9000, `kept ${bytes} bytes in ${kept.length} events`);
+});
+
+test('requeue puts a failed batch back, ahead of anything queued since', () => {
+ const h = home('q-requeue');
+ const batch = drain(h);
+ assert.deepEqual(batch, []);
+ enqueue({ event: 'queued-after' }, h);
+ requeue([{ event: 'failed-send' }], h);
+ assert.deepEqual(drain(h), [{ event: 'failed-send' }, { event: 'queued-after' }]);
+});
+
+test('an unwritable home is silent, not fatal', () => {
+ // A path whose parent is a FILE: mkdir must fail, and enqueue must not throw.
+ const dir = tmpRepo('q-unwritable');
+ writeFileSync(join(dir, 'blocker'), 'x');
+ assert.doesNotThrow(() => enqueue({ event: 'a' }, join(dir, 'blocker')));
+});
+
+test('the queue file is newline-delimited JSON, one event per line', () => {
+ const h = home('q-ndjson');
+ enqueue({ event: 'a' }, h);
+ enqueue({ event: 'b' }, h);
+ const lines = readFileSync(queuePath(h), 'utf8').split('\n').filter(Boolean);
+ assert.equal(lines.length, 2);
+ for (const l of lines) assert.doesNotThrow(() => JSON.parse(l));
+});
+
+// --- what a failed flush does with the batch ---
+
+test('a transport failure or a 5xx keeps the batch; a 4xx discards it', () => {
+ // Ours to retry: the events are still good, the network or the server wasn't.
+ assert.equal(shouldRequeue({ ok: false }), true, 'transport failure');
+ assert.equal(shouldRequeue({ ok: false, status: 500 }), true);
+ assert.equal(shouldRequeue({ ok: false, status: 503 }), true);
+ // Never ours to retry: a bad key or a malformed batch fails the same way
+ // forever, and retrying would pin the queue at its cap.
+ assert.equal(shouldRequeue({ ok: false, status: 401 }), false, 'bad key');
+ assert.equal(shouldRequeue({ ok: false, status: 400 }), false, 'malformed batch');
+ assert.equal(shouldRequeue({ ok: true, status: 200 }), false);
+});
diff --git a/test/telemetry-send.test.ts b/test/telemetry-send.test.ts
new file mode 100644
index 00000000..9442855d
--- /dev/null
+++ b/test/telemetry-send.test.ts
@@ -0,0 +1,115 @@
+/**
+ * The send path, against a real local server rather than a mock.
+ *
+ * One path, `/batch/`, verified by probe against `events.nanonets.com` (401 to a
+ * well-formed batch with a bad key — the path is there and parses the body).
+ * These cover what the client does with each answer it can get back, since that
+ * is what decides whether a week of events survives or is thrown away.
+ */
+import { test, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer, type Server } from 'node:http';
+import { buildBatch, sendBatch } from '../src/telemetry/send.js';
+import { posthogHost } from '../src/telemetry/key.js';
+
+interface Hit { path: string; body: any }
+
+let server: Server;
+let port = 0;
+let hits: Hit[] = [];
+/** Paths this stub pretends not to have, so a 404 can be provoked. */
+let missing = new Set<string>();
+/** Status to answer with on a path that does exist. */
+let status = 200;
+
+before(async () => {
+ server = createServer((req, res) => {
+ let raw = '';
+ req.on('data', (c) => (raw += c));
+ req.on('end', () => {
+ if (missing.has(req.url ?? '')) { res.writeHead(404); res.end('no such path'); return; }
+ hits.push({ path: req.url ?? '', body: raw ? JSON.parse(raw) : null });
+ res.writeHead(status); res.end('{"status":1}');
+ });
+ });
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));
+ port = (server.address() as { port: number }).port;
+ process.env.GRAFT_POSTHOG_KEY = 'phc_send_test';
+ process.env.GRAFT_POSTHOG_HOST = `http://127.0.0.1:${port}`;
+});
+
+after(() => { server.close(); });
+
+function reset(): void { hits = []; missing = new Set(); status = 200; }
+
+const EVENTS = [{ event: 'query', properties: { command: 'ask' }, distinct_id: 'abc', timestamp: '2026-01-01T00:00:00Z' }];
+
+test('the batch goes to /batch/, in one request', async () => {
+ reset();
+ const res = await sendBatch(EVENTS);
+ assert.equal(res.ok, true);
+ assert.deepEqual(hits.map((h) => h.path), ['/batch/']);
+ assert.equal(hits[0].body.api_key, 'phc_send_test');
+ assert.equal(hits[0].body.batch[0].event, 'query');
+ assert.equal(hits[0].body.batch[0].properties.$process_person_profile, false);
+});
+
+test('a 404 is reported rather than retried elsewhere', async () => {
+ reset();
+ missing.add('/batch/');
+ const res = await sendBatch(EVENTS);
+ assert.equal(res.ok, false);
+ assert.equal(res.status, 404);
+ assert.deepEqual(hits, [], 'no second path is attempted');
+});
+
+test('a rejected key is reported as 401 — the state the probe produced', async () => {
+ reset();
+ status = 401;
+ const res = await sendBatch(EVENTS);
+ assert.equal(res.ok, false);
+ assert.equal(res.status, 401);
+ assert.deepEqual(hits.map((h) => h.path), ['/batch/']);
+});
+
+test('a 500 is reported so the queue keeps the batch', async () => {
+ reset();
+ status = 500;
+ const res = await sendBatch(EVENTS);
+ assert.equal(res.status, 500);
+});
+
+test('an unreachable host is a transport error, not a path problem', async () => {
+ reset();
+ const saved = process.env.GRAFT_POSTHOG_HOST;
+ process.env.GRAFT_POSTHOG_HOST = 'http://127.0.0.1:1';
+ const res = await sendBatch(EVENTS);
+ process.env.GRAFT_POSTHOG_HOST = saved;
+ assert.equal(res.ok, false);
+ assert.ok(res.error, 'a transport failure carries an error, not a status');
+ assert.equal(res.status, undefined);
+});
+
+test('an empty batch is not a request', async () => {
+ reset();
+ assert.deepEqual(await sendBatch([]), { ok: true });
+ assert.deepEqual(hits, []);
+});
+
+test('the default host is the one the other server-side integration uses', () => {
+ const saved = process.env.GRAFT_POSTHOG_HOST;
+ delete process.env.GRAFT_POSTHOG_HOST;
+ assert.equal(posthogHost(), 'https://events.nanonets.com');
+ process.env.GRAFT_POSTHOG_HOST = saved;
+});
+
+test('a trailing slash on the configured host does not produce a double slash', () => {
+ const saved = process.env.GRAFT_POSTHOG_HOST;
+ process.env.GRAFT_POSTHOG_HOST = 'https://events.nanonets.com///';
+ assert.equal(posthogHost(), 'https://events.nanonets.com');
+ process.env.GRAFT_POSTHOG_HOST = saved;
+});
+
+test('buildBatch still carries no key, whichever path is used', () => {
+ assert.equal('api_key' in buildBatch(EVENTS), false);
+});
diff --git a/test/telemetry-sessions.test.ts b/test/telemetry-sessions.test.ts
new file mode 100644
index 00000000..5cff3e3a
--- /dev/null
+++ b/test/telemetry-sessions.test.ts
@@ -0,0 +1,96 @@
+/**
+ * The session rollup — the event that answers "did the agent prefer graft to
+ * grep". Its rules: only closed sessions, only once each, and only buckets.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync, utimesSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { SESSION_IDLE_MS, flushClosedSessions } from '../src/telemetry/sessions.js';
+import { peek } from '../src/telemetry/queue.js';
+import { readSession } from '../src/claude/state.js';
+import { tmpRepo } from './helpers.js';
+
+const OPEN: NodeJS.ProcessEnv = {};
+
+function fixture(tag: string): { repo: string; home: string } {
+ const repo = tmpRepo(tag);
+ const home = tmpRepo(`${tag}-home`);
+ mkdirSync(join(home, '.graft'), { recursive: true });
+ mkdirSync(join(repo, 'graft', '.cache', 'session'), { recursive: true });
+ process.env.GRAFT_POSTHOG_KEY = 'phc_test_key';
+ return { repo, home };
+}
+
+function writeSessionFile(repo: string, id: string, body: object, ageMs: number): void {
+ const path = join(repo, 'graft', '.cache', 'session', `${id}.json`);
+ writeFileSync(path, JSON.stringify(body));
+ const when = new Date(Date.now() - ageMs);
+ utimesSync(path, when, when);
+}
+
+test('a closed session is rolled up into one bucketed event', () => {
+ const { repo, home } = fixture('sess-closed');
+ writeSessionFile(repo, 's1', { graftReads: 56, sourceReads: 12, savedTokens: 7400 }, SESSION_IDLE_MS + 1000);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 1);
+ const [ev] = peek(home) as { event: string; properties: Record<string, string> }[];
+ assert.equal(ev.event, 'session_summary');
+ assert.equal(ev.properties.graft_reads_bucket, '50-199');
+ assert.equal(ev.properties.source_reads_bucket, '5-19');
+ assert.equal(ev.properties.saved_tokens_bucket, '5-20k');
+ // The raw counters must not ride along. Checked against the property VALUES,
+ // not a substring of the serialised event: the event carries two random UUIDs,
+ // and '56' is two hex digits — a substring check here fails whenever a uuid
+ // happens to contain them, which is often.
+ const values = Object.values(ev.properties);
+ for (const raw of ['56', '12', '7400']) {
+ assert.equal(values.includes(raw), false, `the raw counter ${raw} was sent as a property value`);
+ }
+});
+
+test('a live session is left alone', () => {
+ const { repo, home } = fixture('sess-live');
+ writeSessionFile(repo, 's1', { graftReads: 3 }, 60_000);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 0);
+ assert.deepEqual(peek(home), []);
+});
+
+test('a session is counted exactly once, however often the hook runs', () => {
+ const { repo, home } = fixture('sess-once');
+ writeSessionFile(repo, 's1', { graftReads: 3 }, SESSION_IDLE_MS + 1000);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 1);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 0);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 0);
+ assert.equal(peek(home).length, 1);
+});
+
+test('the rollup marks the file instead of deleting it, so a resumed session keeps its state', () => {
+ const { repo, home } = fixture('sess-keep');
+ writeSessionFile(repo, 's1', { graftReads: 3, lastQuery: 'how does auth work', injectedPointers: ['a.ts'] }, SESSION_IDLE_MS + 1000);
+ flushClosedSessions(repo, Date.now(), home, OPEN);
+ const s = readSession(repo, 's1');
+ assert.equal(s.summarized, true);
+ assert.equal(s.lastQuery, 'how does auth work');
+ assert.deepEqual(s.injectedPointers, ['a.ts']);
+});
+
+test('the query text never reaches the event', () => {
+ const { repo, home } = fixture('sess-noquery');
+ writeSessionFile(repo, 's1', { graftReads: 1, lastQuery: 'where is the private key loaded' }, SESSION_IDLE_MS + 1000);
+ flushClosedSessions(repo, Date.now(), home, OPEN);
+ assert.equal(JSON.stringify(peek(home)).includes('private key'), false);
+});
+
+test('a repo with no sessions is a no-op', () => {
+ const repo = tmpRepo('sess-none');
+ const home = tmpRepo('sess-none-home');
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 0);
+});
+
+test('an empty session still counts — installed but unused is the signal we want', () => {
+ const { repo, home } = fixture('sess-empty');
+ writeSessionFile(repo, 's1', { graftReads: 0, sourceReads: 0, savedTokens: 0 }, SESSION_IDLE_MS + 1000);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 1);
+ const [ev] = peek(home) as { properties: Record<string, string> }[];
+ assert.equal(ev.properties.graft_reads_bucket, '0');
+});